• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dcdpr / jp / 25075778553

28 Apr 2026 08:23PM UTC coverage: 64.215% (+0.02%) from 64.197%
25075778553

Pull #586

github

web-flow
Merge b2748a63e into 29f81185f
Pull Request #586: refactor(config, cli): Rename `user_global_config_path` to `*_dir`

2 of 6 new or added lines in 5 files covered. (33.33%)

23436 of 36496 relevant lines covered (64.22%)

199.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

10.08
/crates/jp_cli/src/cmd/plugin/dispatch.rs
1
//! Host-side plugin message loop.
2
//!
3
//! Spawns the plugin binary, sends `init`, and relays workspace queries until
4
//! the plugin sends `exit` or the process terminates.
5

6
use std::{
7
    collections::HashSet,
8
    io::{BufRead, BufReader, Write},
9
    process::{Command, Stdio},
10
    sync::{
11
        Arc, Mutex,
12
        atomic::{AtomicBool, Ordering},
13
    },
14
    thread,
15
};
16

17
use camino::{Utf8Path, Utf8PathBuf};
18
use jp_config::{
19
    AppConfig,
20
    plugins::{
21
        PluginsConfig,
22
        command::{CommandPluginConfig, RunPolicy},
23
    },
24
};
25
use jp_inquire::{InlineOption, InlineSelect};
26
use jp_plugin::{
27
    PROTOCOL_VERSION,
28
    message::{
29
        ConfigResponse, ConversationSummary, ConversationsResponse, DescribeResponse,
30
        ErrorResponse, EventsResponse, HostToPlugin, InitMessage, LogMessage, PathsInfo,
31
        PluginToHost, WorkspaceInfo,
32
    },
33
};
34
use jp_workspace::Workspace;
35
use serde_json::Value;
36
use tracing::{debug, error, trace, warn};
37

38
use super::registry;
39
use crate::{Ctx, cmd, signals::SignalPair};
40

41
/// Run a plugin binary, handling the full protocol lifecycle.
42
///
43
/// `binary` is the path to the plugin executable. `args` are the remaining CLI
44
/// arguments to forward.
45
pub(crate) fn run_plugin(
×
46
    name: &str,
×
47
    binary: &Utf8Path,
×
48
    args: &[String],
×
49
    workspace: &Workspace,
×
50
    storage_path: Option<&Utf8Path>,
×
51
    user_storage_path: Option<&Utf8Path>,
×
52
    config: &Arc<AppConfig>,
×
53
    signals: &SignalPair,
×
54
    log_level: u8,
×
55
) -> Result<(), cmd::Error> {
×
56
    let config_json = serde_json::to_value(config.as_ref().to_partial())
×
57
        .map_err(|e| cmd::Error::from(format!("failed to serialize config: {e}")))?;
×
58

59
    let options: serde_json::Map<String, Value> = config
×
60
        .plugins
×
61
        .command
×
62
        .get(name)
×
63
        .and_then(|c| c.options.as_ref())
×
64
        .and_then(Value::as_object)
×
65
        .cloned()
×
66
        .unwrap_or_default();
×
67

68
    let storage_path = storage_path.ok_or("workspace has no storage configured")?;
×
69

70
    let home = std::env::home_dir().and_then(|p| camino::Utf8PathBuf::from_path_buf(p).ok());
×
71

72
    let init = HostToPlugin::Init(InitMessage {
×
73
        version: PROTOCOL_VERSION,
×
74
        workspace: WorkspaceInfo {
×
75
            root: workspace.root().to_owned(),
×
76
            storage: storage_path.to_owned(),
×
77
            id: workspace.id().to_string(),
×
78
        },
×
79
        paths: PathsInfo {
×
80
            user_data: jp_workspace::user_data_dir().ok(),
×
NEW
81
            user_config: jp_config::fs::user_global_config_dir(home.as_deref()),
×
82
            user_workspace: user_storage_path.map(ToOwned::to_owned),
×
83
        },
×
84
        config: config_json.clone(),
×
85
        options,
×
86
        args: args.to_vec(),
×
87
        log_level,
×
88
    });
×
89

90
    debug!(%binary, "Spawning plugin.");
×
91

92
    let mut cmd = Command::new(binary);
×
93
    cmd.stdin(Stdio::piped())
×
94
        .stdout(Stdio::piped())
×
95
        .stderr(Stdio::piped());
×
96

97
    // Prevent the child from receiving SIGINT/SIGTERM directly. The host
98
    // sends `Shutdown` over the protocol instead, giving the plugin a
99
    // chance to exit gracefully.
100
    #[cfg(unix)]
101
    {
102
        use std::os::unix::process::CommandExt as _;
103
        cmd.process_group(0);
×
104
    }
105

106
    let mut child = cmd
×
107
        .spawn()
×
108
        .map_err(|e| cmd::Error::from(format!("failed to spawn plugin: {e}")))?;
×
109

110
    let child_stdin = child.stdin.take().expect("stdin piped");
×
111
    let stdout = child.stdout.take().expect("stdout piped");
×
112
    let stderr = child.stderr.take().expect("stderr piped");
×
113

114
    // Wrap stdin so the shutdown thread can write to it too.
115
    let stdin = Arc::new(Mutex::new(child_stdin));
×
116

117
    // Forward stderr to tracing in a background thread.
118
    let stderr_handle = thread::spawn(move || {
×
119
        let reader = BufReader::new(stderr);
×
120
        for line in reader.lines() {
×
121
            match line {
×
122
                Ok(line) => trace!(target: "plugin::stderr", "{}", line),
×
123
                Err(e) => {
×
124
                    warn!("Error reading plugin stderr: {e}");
×
125
                    break;
×
126
                }
127
            }
128
        }
129
    });
×
130

131
    // Shutdown thread: sends `Shutdown` directly to the plugin's stdin
132
    // when a signal arrives. If the plugin doesn't exit within the grace
133
    // period, sends SIGKILL.
134
    let shutdown_sent = Arc::new(AtomicBool::new(false));
×
135
    let shutdown_writer = stdin.clone();
×
136
    let shutdown_flag = shutdown_sent.clone();
×
137
    let child_id = child.id();
×
138
    let mut shutdown_rx = signals.receiver.resubscribe();
×
139
    let shutdown_handle = thread::spawn(move || {
×
140
        if futures::executor::block_on(shutdown_rx.recv()).is_err() {
×
141
            return;
×
142
        }
×
143

144
        // Send Shutdown over the protocol.
145
        if let Ok(mut writer) = shutdown_writer.lock() {
×
146
            drop(write_message(&mut *writer, &HostToPlugin::Shutdown));
×
147
        }
×
148
        shutdown_flag.store(true, Ordering::Release);
×
149

150
        // Grace period: wait in short intervals so we don't block cleanup
151
        // if the plugin exits promptly.
152
        for _ in 0..50 {
×
153
            thread::sleep(std::time::Duration::from_millis(100));
×
154
            if !is_process_alive(child_id) {
×
155
                return;
×
156
            }
×
157
        }
158

159
        kill_child(child_id);
×
160
    });
×
161

162
    // Send init.
163
    {
164
        let mut writer = stdin.lock().expect("stdin lock poisoned");
×
165
        write_message(&mut *writer, &init)
×
166
            .map_err(|e| cmd::Error::from(format!("failed to send init: {e}")))?;
×
167
    }
168

169
    // Read messages from plugin.
170
    let reader = BufReader::new(stdout);
×
171
    let result = message_loop(reader, &stdin, workspace, &config_json, &shutdown_sent);
×
172

173
    // Always clean up, even on error.
174
    drop(child.wait());
×
175
    drop(stderr_handle.join());
×
176
    drop(shutdown_handle);
×
177

178
    result
×
179
}
×
180

181
/// The main message loop: reads plugin requests and sends responses.
182
fn message_loop(
1✔
183
    reader: BufReader<impl std::io::Read>,
1✔
184
    stdin: &Mutex<impl Write>,
1✔
185
    workspace: &Workspace,
1✔
186
    config_json: &Value,
1✔
187
    shutdown_sent: &AtomicBool,
1✔
188
) -> Result<(), cmd::Error> {
1✔
189
    for line in reader.lines() {
2✔
190
        let line =
2✔
191
            line.map_err(|e| cmd::Error::from(format!("failed to read from plugin: {e}")))?;
2✔
192

193
        if line.trim().is_empty() {
2✔
194
            continue;
×
195
        }
2✔
196

197
        let msg: PluginToHost = serde_json::from_str(&line)
2✔
198
            .map_err(|e| cmd::Error::from(format!("invalid plugin message: {e}: {line}")))?;
2✔
199

200
        trace!(?msg, "Received plugin message.");
2✔
201

202
        let mut writer = stdin.lock().expect("stdin lock poisoned");
2✔
203

204
        match msg {
2✔
205
            PluginToHost::Ready => {
206
                debug!("Plugin signaled ready.");
1✔
207
            }
208

209
            PluginToHost::ListConversations(req) => {
×
210
                let response = handle_list_conversations(workspace, req.id);
×
211
                write_message(&mut *writer, &response)?;
×
212
            }
213

214
            PluginToHost::ReadEvents(req) => {
×
215
                let response = handle_read_events(workspace, &req.conversation, req.id);
×
216
                write_message(&mut *writer, &response)?;
×
217
            }
218

219
            PluginToHost::ReadConfig(req) => {
×
220
                let response = handle_read_config(config_json, req.path, req.id);
×
221
                write_message(&mut *writer, &response)?;
×
222
            }
223

224
            PluginToHost::Print(print) => {
×
225
                // In Phase 1, write to stdout directly. Full printer
×
226
                // integration comes later when we thread through &Printer.
×
227
                let stdout = std::io::stdout();
×
228
                let mut handle = stdout.lock();
×
229
                drop(handle.write_all(print.text.as_bytes()));
×
230
                drop(handle.flush());
×
231
            }
×
232

233
            PluginToHost::Log(log) => {
×
234
                emit_log(&log);
×
235
            }
×
236

237
            PluginToHost::Describe(_) => {
238
                debug!("Ignoring describe in message loop.");
×
239
            }
240

241
            PluginToHost::Exit(exit) => {
1✔
242
                debug!(code = exit.code, "Plugin exited.");
1✔
243
                if exit.code == 0 {
1✔
244
                    return Ok(());
1✔
245
                }
×
246
                return match exit.reason {
×
247
                    Some(reason) => Err(cmd::Error::from((exit.code, reason))),
×
248
                    None => Err(cmd::Error::from(exit.code)),
×
249
                };
250
            }
251
        }
252
    }
253

254
    // Plugin's stdout closed without an `exit` message. If we sent a
255
    // shutdown, this is expected (the child exited after receiving it).
256
    if shutdown_sent.load(Ordering::Acquire) {
×
257
        debug!("Plugin exited after shutdown.");
×
258
        return Ok(());
×
259
    }
×
260

261
    error!("Plugin exited without sending exit message.");
×
262
    Err(cmd::Error::from((
×
263
        1u8,
×
264
        "plugin exited unexpectedly without sending exit message",
×
265
    )))
×
266
}
1✔
267

268
fn handle_list_conversations(workspace: &Workspace, req_id: Option<String>) -> HostToPlugin {
×
269
    let data: Vec<ConversationSummary> = workspace
×
270
        .conversations()
×
271
        .map(|(id, meta)| ConversationSummary {
×
272
            id: id.as_deciseconds().to_string(),
×
273
            title: meta.title.clone(),
×
274
            last_activated_at: meta.last_activated_at,
×
275
            events_count: meta.events_count,
×
276
        })
×
277
        .collect();
×
278

279
    HostToPlugin::Conversations(ConversationsResponse { id: req_id, data })
×
280
}
×
281

282
fn handle_read_events(
×
283
    workspace: &Workspace,
×
284
    conversation_id: &str,
×
285
    req_id: Option<String>,
×
286
) -> HostToPlugin {
×
287
    let conv_id = match jp_conversation::ConversationId::try_from_deciseconds_str(conversation_id) {
×
288
        Ok(id) => id,
×
289
        Err(e) => {
×
290
            return HostToPlugin::Error(ErrorResponse {
×
291
                id: req_id,
×
292
                request: Some("read_events".to_owned()),
×
293
                message: format!("invalid conversation ID: {e}"),
×
294
            });
×
295
        }
296
    };
297

298
    let handle = match workspace.acquire_conversation(&conv_id) {
×
299
        Ok(h) => h,
×
300
        Err(e) => {
×
301
            return HostToPlugin::Error(ErrorResponse {
×
302
                id: req_id,
×
303
                request: Some("read_events".to_owned()),
×
304
                message: format!("conversation not found: {e}"),
×
305
            });
×
306
        }
307
    };
308

309
    let events = match workspace.events(&handle) {
×
310
        Ok(stream) => stream,
×
311
        Err(e) => {
×
312
            return HostToPlugin::Error(ErrorResponse {
×
313
                id: req_id,
×
314
                request: Some("read_events".to_owned()),
×
315
                message: format!("failed to load events: {e}"),
×
316
            });
×
317
        }
318
    };
319

320
    // Serialize events to JSON values, then decode base64-encoded storage
321
    // fields so plugins receive plain text.
322
    let (_, mut event_values) = match events.to_parts() {
×
323
        Ok(parts) => parts,
×
324
        Err(e) => {
×
325
            return HostToPlugin::Error(ErrorResponse {
×
326
                id: req_id,
×
327
                request: Some("read_events".to_owned()),
×
328
                message: format!("failed to serialize events: {e}"),
×
329
            });
×
330
        }
331
    };
332

333
    for value in &mut event_values {
×
334
        jp_conversation::decode_event_value(value);
×
335
    }
×
336

337
    HostToPlugin::Events(EventsResponse {
×
338
        id: req_id,
×
339
        conversation: conversation_id.to_owned(),
×
340
        data: event_values,
×
341
    })
×
342
}
×
343

344
fn handle_read_config(
3✔
345
    config_json: &Value,
3✔
346
    path: Option<String>,
3✔
347
    req_id: Option<String>,
3✔
348
) -> HostToPlugin {
3✔
349
    let data = match &path {
3✔
350
        Some(path) => {
2✔
351
            let mut current = config_json;
2✔
352
            for segment in path.split('.') {
3✔
353
                match current.get(segment) {
3✔
354
                    Some(v) => current = v,
2✔
355
                    None => {
356
                        return HostToPlugin::Error(ErrorResponse {
1✔
357
                            id: req_id,
1✔
358
                            request: Some("read_config".to_owned()),
1✔
359
                            message: format!("config path not found: {path}"),
1✔
360
                        });
1✔
361
                    }
362
                }
363
            }
364
            current.clone()
1✔
365
        }
366
        None => config_json.clone(),
1✔
367
    };
368

369
    HostToPlugin::Config(ConfigResponse {
2✔
370
        id: req_id,
2✔
371
        path,
2✔
372
        data,
2✔
373
    })
2✔
374
}
3✔
375

376
fn emit_log(log: &LogMessage) {
×
377
    match log.level.as_str() {
×
378
        "trace" => trace!(target: "plugin", message = %log.message),
×
379
        "debug" => debug!(target: "plugin", message = %log.message),
×
380
        "info" => tracing::info!(target: "plugin", message = %log.message),
×
381
        "warn" => warn!(target: "plugin", message = %log.message),
×
382
        "error" => error!(target: "plugin", message = %log.message),
×
383
        _ => {
384
            warn!(target: "plugin", level = %log.level, message = %log.message, "unknown log level");
×
385
        }
386
    }
387
}
×
388

389
fn write_message(writer: &mut impl Write, msg: &HostToPlugin) -> Result<(), cmd::Error> {
×
390
    let json = serde_json::to_string(msg)
×
391
        .map_err(|e| cmd::Error::from(format!("failed to serialize message: {e}")))?;
×
392
    writeln!(writer, "{json}")
×
393
        .map_err(|e| cmd::Error::from(format!("failed to write to plugin stdin: {e}")))?;
×
394
    writer
×
395
        .flush()
×
396
        .map_err(|e| cmd::Error::from(format!("failed to flush plugin stdin: {e}")))?;
×
397
    Ok(())
×
398
}
×
399

400
/// Check if a process is still alive by PID.
401
#[cfg(unix)]
402
fn is_process_alive(pid: u32) -> bool {
×
403
    // kill with signal 0 checks existence without sending a signal.
404
    unsafe { libc::kill(libc::pid_t::from(pid.cast_signed()), 0) == 0 }
×
405
}
×
406

407
#[cfg(windows)]
408
fn is_process_alive(pid: u32) -> bool {
409
    use windows_sys::Win32::{
410
        Foundation::{CloseHandle, STILL_ACTIVE},
411
        System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION},
412
    };
413

414
    unsafe {
415
        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
416
        if handle.is_null() {
417
            return false;
418
        }
419
        let mut exit_code: u32 = 0;
420
        let ok = GetExitCodeProcess(handle, &mut exit_code);
421
        CloseHandle(handle);
422
        ok != 0 && (exit_code as i32) == STILL_ACTIVE
423
    }
424
}
425

426
/// Send SIGKILL to a child process by PID.
427
///
428
/// Used as a last resort when the plugin doesn't exit within the grace
429
/// period after receiving `Shutdown`.
430
#[cfg(unix)]
431
fn kill_child(pid: u32) {
×
432
    // SAFETY: We're sending a signal to a process we spawned.
433
    unsafe {
×
434
        libc::kill(libc::pid_t::from(pid.cast_signed()), libc::SIGKILL);
×
435
    }
×
436
    debug!(pid, "Sent SIGKILL to plugin after grace period.");
×
437
}
×
438

439
#[cfg(windows)]
440
fn kill_child(pid: u32) {
441
    use windows_sys::Win32::{
442
        Foundation::CloseHandle,
443
        System::Threading::{OpenProcess, PROCESS_TERMINATE, TerminateProcess},
444
    };
445

446
    // SAFETY: We're terminating a process we spawned.
447
    unsafe {
448
        let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
449
        if !handle.is_null() {
450
            TerminateProcess(handle, 1);
451
            CloseHandle(handle);
452
        }
453
    }
454
    debug!(pid, "Sent TerminateProcess to plugin after grace period.");
455
}
456

457
/// Search `$PATH` for a plugin binary matching the given subcommand segments.
458
///
459
/// For `["serve"]`, looks for `jp-serve`. For `["conversation", "export"]`,
460
/// looks for `jp-conversation-export`.
461
pub(crate) fn find_plugin_binary(segments: &[&str]) -> Option<Utf8PathBuf> {
1✔
462
    let name = format!("jp-{}", segments.join("-"));
1✔
463
    which::which(&name)
1✔
464
        .ok()
1✔
465
        .and_then(|p| Utf8PathBuf::from_path_buf(p).ok())
1✔
466
}
1✔
467

468
/// Find any existing plugin binary without downloading or prompting.
469
///
470
/// Checks the install directory first, then `$PATH`. Used for non-mutating
471
/// operations like help requests.
472
pub(crate) fn find_any_plugin_binary(name: &str) -> Option<Utf8PathBuf> {
×
473
    if let Some(path) = registry::find_installed(name) {
×
474
        return Some(path);
×
475
    }
×
476
    let segments: Vec<&str> = name.split('-').collect();
×
477
    find_plugin_binary(&segments)
×
478
}
×
479

480
/// Resolve a plugin binary through multiple sources:
481
///
482
/// 1. User-local install directory (previously installed plugins)
483
/// 2. Plugin registry (auto-install if official, prompt if third-party)
484
/// 3. `$PATH` (with approval check for unapproved plugins)
485
///
486
/// The `plugins_config` drives installation and execution policy. Per-plugin
487
/// settings override the defaults from the registry (official vs third-party).
488
pub(crate) async fn resolve_plugin_binary(
×
489
    name: &str,
×
490
    plugins_config: &PluginsConfig,
×
491
    is_tty: bool,
×
492
) -> Result<Option<Utf8PathBuf>, cmd::Error> {
×
493
    let plugin_cfg = plugins_config.command.get(name);
×
494

495
    // Explicit deny in config.
496
    if plugin_cfg.is_some_and(|c| c.run == Some(RunPolicy::Deny)) {
×
497
        return Err(cmd::Error::from(format!(
×
498
            "plugin `{name}` is denied by configuration (plugins.command.{name}.run = \"deny\")"
×
499
        )));
×
500
    }
×
501

502
    // 1. Already installed locally.
503
    if let Some(path) = registry::find_installed(name) {
×
504
        debug!(name, %path, "Found installed plugin.");
×
505
        verify_checksum(name, &path, plugin_cfg)?;
×
506
        return Ok(Some(path));
×
507
    }
×
508

509
    // 2. Check registry.
510
    if let Some(path) = try_registry_install(name, plugins_config, is_tty).await? {
×
511
        return Ok(Some(path));
×
512
    }
×
513

514
    // 3. Check $PATH with run policy.
515
    let segments: Vec<&str> = name.split('-').collect();
×
516
    if let Some(path) = find_plugin_binary(&segments) {
×
517
        check_run_policy(name, &path, plugin_cfg, is_tty)?;
×
518
        return Ok(Some(path));
×
519
    }
×
520

521
    Ok(None)
×
522
}
×
523

524
/// Verify a binary's checksum against the config-pinned value, if any.
525
fn verify_checksum(
×
526
    name: &str,
×
527
    binary_path: &Utf8Path,
×
528
    plugin_cfg: Option<&CommandPluginConfig>,
×
529
) -> Result<(), cmd::Error> {
×
530
    let Some(checksum) = plugin_cfg.and_then(|c| c.checksum.as_ref()) else {
×
531
        return Ok(());
×
532
    };
533

534
    let actual = registry::sha256_file(binary_path)?;
×
535
    if actual != checksum.value {
×
536
        return Err(cmd::Error::from(format!(
×
537
            "plugin `{name}` binary checksum mismatch.\nexpected: {}\nactual:   {actual}\nThe \
×
538
             binary at {binary_path} has changed since it was pinned. Update \
×
539
             plugins.command.{name}.checksum.value in your config to accept the new binary.",
×
540
            checksum.value,
×
541
        )));
×
542
    }
×
543

544
    Ok(())
×
545
}
×
546

547
/// Try to install a plugin from the cached registry.
548
async fn try_registry_install(
×
549
    name: &str,
×
550
    plugins_config: &PluginsConfig,
×
551
    is_tty: bool,
×
552
) -> Result<Option<Utf8PathBuf>, cmd::Error> {
×
553
    let Some(reg) = registry::load_cached() else {
×
554
        return Ok(None);
×
555
    };
556

557
    // Find the registry entry whose `id` matches the requested name.
558
    // In Phase 5, this will use the command path (registry key) for
559
    // multi-segment routing. For now, we match on `id`.
560
    let Some(plugin) = reg.plugins.values().find(|p| p.id == name) else {
×
561
        return Ok(None);
×
562
    };
563

564
    // Only handle command plugins.
565
    let jp_plugin::registry::PluginKind::Command { ref binaries, .. } = plugin.kind else {
×
566
        return Ok(None);
×
567
    };
568

569
    let target = registry::current_target();
×
570
    let Some(binary_info) = binaries.get(&target) else {
×
571
        return Ok(None);
×
572
    };
573

574
    let id = &plugin.id;
×
575
    let plugin_cfg = plugins_config.command.get(id);
×
576

577
    // Check if auto-install is allowed.
578
    let auto_install = plugin_cfg
×
579
        .and_then(|c| c.install)
×
580
        .unwrap_or(plugins_config.auto_install);
×
581

582
    if !auto_install && !plugin.official {
×
583
        return Ok(None);
×
584
    }
×
585

586
    // Determine run policy: config > registry default.
587
    let run_policy = plugin_cfg
×
588
        .and_then(|c| c.run)
×
589
        .unwrap_or(if plugin.official {
×
590
            RunPolicy::Unattended
×
591
        } else {
592
            RunPolicy::Ask
×
593
        });
594

595
    match run_policy {
×
596
        RunPolicy::Deny => {
597
            return Err(cmd::Error::from(format!(
×
598
                "plugin `{id}` is denied by configuration"
×
599
            )));
×
600
        }
601
        RunPolicy::Ask => {
602
            if !is_tty {
×
603
                return Err(cmd::Error::from(format!(
×
604
                    "plugin `{id}` requires approval. Run `jp plugin install {id}` first, or set \
×
605
                     plugins.command.{id}.run = \"unattended\" in config."
×
606
                )));
×
607
            }
×
608

609
            let mut writer = std::io::stderr();
×
610
            drop(writeln!(
×
611
                writer,
×
612
                "  \u{2192} Plugin `{id}` found in registry."
613
            ));
614
            let options = vec![
×
615
                InlineOption::new('y', "install and run"),
×
616
                InlineOption::new('n', "cancel"),
×
617
            ];
618
            let answer = InlineSelect::new("Install and run it?", options)
×
619
                .prompt(&mut writer)
×
620
                .map_err(|e| cmd::Error::from(format!("prompt failed: {e}")))?;
×
621

622
            if answer != 'y' {
×
623
                return Err(cmd::Error::from("plugin execution cancelled"));
×
624
            }
×
625
        }
626
        RunPolicy::Unattended => {}
×
627
    }
628

629
    drop(writeln!(
×
630
        std::io::stderr(),
×
631
        "  \u{2192} Installing jp-{id} for {target}..."
632
    ));
633
    let client = reqwest::Client::new();
×
634
    let data = registry::download_and_verify(&client, binary_info).await?;
×
635

636
    let path = registry::install_binary(id, &data)?;
×
637
    drop(writeln!(
×
638
        std::io::stderr(),
×
639
        "  \u{2192} Installed to {path}",
640
    ));
641

642
    // Verify against pinned checksum if configured.
643
    verify_checksum(id, &path, plugin_cfg)?;
×
644

645
    Ok(Some(path))
×
646
}
×
647

648
/// Check run policy for a `$PATH`-discovered plugin.
649
fn check_run_policy(
×
650
    name: &str,
×
651
    binary_path: &Utf8Path,
×
652
    plugin_cfg: Option<&CommandPluginConfig>,
×
653
    is_tty: bool,
×
654
) -> Result<(), cmd::Error> {
×
655
    // Verify pinned checksum first.
656
    verify_checksum(name, binary_path, plugin_cfg)?;
×
657

658
    let run_policy = plugin_cfg.and_then(|c| c.run).unwrap_or(RunPolicy::Ask);
×
659

660
    match run_policy {
×
661
        RunPolicy::Unattended => Ok(()),
×
662
        RunPolicy::Deny => Err(cmd::Error::from(format!(
×
663
            "plugin `{name}` is denied by configuration"
×
664
        ))),
×
665
        RunPolicy::Ask => {
666
            if !is_tty {
×
667
                return Err(cmd::Error::from(format!(
×
668
                    "plugin `jp-{name}` found on $PATH but requires approval. Set \
×
669
                     plugins.command.{name}.run = \"unattended\" in config, or run `jp {name}` in \
×
670
                     a terminal."
×
671
                )));
×
672
            }
×
673

674
            // Check existing permanent approvals.
675
            if let Some(approvals) = registry::load_approvals()
×
676
                && let Some(approved) = approvals.approved.get(name)
×
677
                && approved.path == binary_path
×
678
                && registry::sha256_file(binary_path).is_ok_and(|sha| sha == approved.sha256)
×
679
            {
680
                debug!(name, %binary_path, "Plugin previously approved.");
×
681
                return Ok(());
×
682
            }
×
683

684
            let mut writer = std::io::stderr();
×
685
            drop(writeln!(
×
686
                writer,
×
687
                "  \u{2192} Found jp-{name} on $PATH ({binary_path})",
688
            ));
689
            let options = vec![
×
690
                InlineOption::new('y', "run this time"),
×
691
                InlineOption::new('Y', "run and remember permanently"),
×
692
                InlineOption::new('n', "deny"),
×
693
            ];
694
            let answer = InlineSelect::new("Run it?", options)
×
695
                .prompt(&mut writer)
×
696
                .map_err(|e| cmd::Error::from(format!("prompt failed: {e}")))?;
×
697

698
            match answer {
×
699
                'y' => Ok(()),
×
700
                'Y' => {
701
                    registry::save_approval(name, binary_path)?;
×
702
                    Ok(())
×
703
                }
704
                _ => Err(cmd::Error::from("plugin execution denied")),
×
705
            }
706
        }
707
    }
708
}
×
709

710
/// Send a `Describe` request to a plugin and return its metadata.
711
///
712
/// Spawns the binary, sends `{"type":"describe"}`, reads one response line,
713
/// and returns the parsed [`DescribeResponse`]. Returns `None` if the plugin
714
/// doesn't support describe or fails to respond.
715
pub(crate) fn describe_plugin(binary: &Utf8Path) -> Option<DescribeResponse> {
×
716
    let mut child = Command::new(binary)
×
717
        .stdin(Stdio::piped())
×
718
        .stdout(Stdio::piped())
×
719
        .stderr(Stdio::null())
×
720
        .spawn()
×
721
        .ok()?;
×
722

723
    let mut child_stdin = child.stdin.take()?;
×
724
    let child_stdout = child.stdout.take()?;
×
725

726
    // Send describe request.
727
    let json = serde_json::to_string(&HostToPlugin::Describe).ok()?;
×
728
    writeln!(child_stdin, "{json}").ok()?;
×
729
    child_stdin.flush().ok()?;
×
730
    drop(child_stdin); // Signal no more messages.
×
731

732
    // Read one line response.
733
    let mut reader = BufReader::new(child_stdout);
×
734
    let mut line = String::new();
×
735
    reader.read_line(&mut line).ok()?;
×
736

737
    drop(child.wait());
×
738

739
    if line.trim().is_empty() {
×
740
        return None;
×
741
    }
×
742

743
    let msg: PluginToHost = serde_json::from_str(line.trim()).ok()?;
×
744
    match msg {
×
745
        PluginToHost::Describe(resp) => Some(resp),
×
746
        _ => None,
×
747
    }
748
}
×
749

750
/// Discover plugin binaries on `$PATH` and in the user-local install directory.
751
///
752
/// Returns `(subcommand_name, binary_path)` pairs, sorted by name.
753
/// For a binary named `jp-serve`, the subcommand name is `serve`.
754
/// Installed plugins take priority over `$PATH` duplicates.
755
pub(crate) fn discover_plugins() -> Vec<(String, Utf8PathBuf)> {
×
756
    let path_var = std::env::var_os("PATH").unwrap_or_default();
×
757
    let mut seen = HashSet::new();
×
758
    let mut plugins = Vec::new();
×
759

760
    // Scan install directory first so installed plugins take priority.
761
    if let Some(bin_dir) = registry::bin_dir() {
×
762
        scan_dir_for_plugins(&bin_dir, &mut seen, &mut plugins);
×
763
    }
×
764

765
    for dir in std::env::split_paths(&path_var) {
×
766
        let Some(dir) = Utf8Path::from_path(&dir) else {
×
767
            continue;
×
768
        };
769

770
        scan_dir_for_plugins(dir, &mut seen, &mut plugins);
×
771
    }
772

773
    plugins.sort_by(|a, b| a.0.cmp(&b.0));
×
774
    plugins
×
775
}
×
776

777
fn scan_dir_for_plugins(
×
778
    dir: &Utf8Path,
×
779
    seen: &mut HashSet<String>,
×
780
    plugins: &mut Vec<(String, Utf8PathBuf)>,
×
781
) {
×
782
    let Ok(entries) = dir.read_dir_utf8() else {
×
783
        return;
×
784
    };
785
    for entry in entries.flatten() {
×
786
        let name = entry.file_name();
×
787
        let Some(subcommand) = name.strip_prefix("jp-") else {
×
788
            continue;
×
789
        };
790

791
        // On Windows, strip the .exe extension.
792
        #[cfg(windows)]
793
        let subcommand = subcommand.strip_suffix(".exe").unwrap_or(subcommand);
794

795
        // On Unix, skip non-executable files.
796
        #[cfg(unix)]
797
        {
798
            use std::os::unix::fs::PermissionsExt as _;
799
            let Ok(meta) = entry.metadata() else {
×
800
                continue;
×
801
            };
802
            if meta.permissions().mode() & 0o111 == 0 {
×
803
                continue;
×
804
            }
×
805
        }
806

807
        if seen.insert(subcommand.to_owned()) {
×
808
            plugins.push((subcommand.to_owned(), entry.into_path()));
×
809
        }
×
810
    }
811
}
×
812

813
/// Show a plugin's help text via the `Describe` protocol.
814
pub(crate) fn show_plugin_help(binary: &Utf8Path) -> cmd::Output {
×
815
    match describe_plugin(binary) {
×
816
        Some(desc) => {
×
817
            let mut out = std::io::stdout().lock();
×
818
            if let Some(help) = &desc.help {
×
819
                drop(writeln!(out, "{help}"));
×
820
            } else {
×
821
                drop(writeln!(out, "{}: {}", desc.name, desc.description));
×
822
            }
×
823
            Ok(())
×
824
        }
825
        None => Err(cmd::Error::from("plugin does not support describe")),
×
826
    }
827
}
×
828

829
/// Produce a clap-formatted error for an unknown subcommand.
830
///
831
/// Uses `Command::error()` to get clap's standard error chrome (colored
832
/// `error:` prefix, usage line, help hint). The message includes our
833
/// plugin-specific context. Returns exit code 2 (clap's convention for usage
834
/// errors) with no message, since the output was already written.
835
fn unknown_subcommand_error(name: &str) -> cmd::Error {
×
836
    use clap::CommandFactory as _;
837

838
    let mut cmd = crate::Cli::command();
×
839
    let err = cmd.error(
×
840
        clap::error::ErrorKind::InvalidSubcommand,
×
841
        format!(
×
842
            "unrecognized subcommand '{name}'\n\n  No built-in command, registry plugin, or \
843
             `jp-{name}` binary found on $PATH."
844
        ),
845
    );
846
    drop(err.print());
×
847
    cmd::Error::from(2u8)
×
848
}
×
849

850
/// Dispatch an external plugin subcommand.
851
///
852
/// Resolves the plugin binary, then runs the protocol loop. Called from
853
/// `Commands::run()` after the normal startup flow.
854
pub(crate) async fn run_external(args: &[String], ctx: &Ctx) -> cmd::Output {
×
855
    let (subcommand, plugin_args) = args
×
856
        .split_first()
×
857
        .ok_or("no subcommand provided for plugin dispatch")?;
×
858

859
    // Handle help without downloading or approval.
860
    if plugin_args.iter().any(|a| a == "-h" || a == "--help") {
×
861
        let binary = find_any_plugin_binary(subcommand).ok_or_else(|| {
×
862
            cmd::Error::from(format!(
×
863
                "plugin `{subcommand}` not found. No installed plugin or `jp-{subcommand}` binary \
864
                 found on $PATH.",
865
            ))
866
        })?;
×
867
        return show_plugin_help(&binary);
×
868
    }
×
869

870
    let config = ctx.config();
×
871
    let Some(binary) = resolve_plugin_binary(subcommand, &config.plugins, ctx.term.is_tty).await?
×
872
    else {
873
        return Err(unknown_subcommand_error(subcommand));
×
874
    };
875

876
    debug!(%binary, subcommand, "Dispatching to plugin.");
×
877

878
    run_plugin(
×
879
        subcommand,
×
880
        &binary,
×
881
        plugin_args,
×
882
        &ctx.workspace,
×
883
        ctx.storage_path(),
×
884
        ctx.user_storage_path(),
×
885
        &config,
×
886
        &ctx.signals,
×
887
        ctx.term.args.verbose,
×
888
    )?;
×
889
    Ok(())
×
890
}
×
891

892
#[cfg(test)]
893
#[path = "dispatch_tests.rs"]
894
mod tests;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc