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

dcdpr / jp / 28664838556

03 Jul 2026 01:50PM UTC coverage: 68.069%. First build
28664838556

Pull #837

github

web-flow
Merge ada7c85e7 into b9f599a21
Pull Request #837: feat(cli, config): Escalate Ctrl-C through a signal router

271 of 325 new or added lines in 14 files covered. (83.38%)

38545 of 56626 relevant lines covered (68.07%)

689.83 hits per line

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

9.96
/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::SignalRouter};
40

41
/// Run a plugin binary, handling the full protocol lifecycle.
42
///
43
/// `binary` is the path to the plugin executable.
44
/// `args` are the remaining CLI 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>,
×
NEW
53
    signals: &SignalRouter,
×
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(),
×
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 when
132
    // an interrupt or a graceful shutdown request arrives. If the plugin
133
    // doesn't exit within the grace period, sends SIGKILL.
134
    //
135
    // The guard drops when this function returns; the thread then sees the
136
    // notification channel close and exits.
NEW
137
    let (_interrupt_guard, mut interrupt_rx) = signals.push_handler();
×
NEW
138
    let shutdown_token = signals.shutdown_token();
×
139
    let shutdown_sent = Arc::new(AtomicBool::new(false));
×
140
    let shutdown_writer = stdin.clone();
×
141
    let shutdown_flag = shutdown_sent.clone();
×
142
    let child_id = child.id();
×
143
    let shutdown_handle = thread::spawn(move || {
×
NEW
144
        let interrupted = futures::executor::block_on(async {
×
NEW
145
            tokio::select! {
×
NEW
146
                notified = interrupt_rx.recv() => notified.is_some(),
×
NEW
147
                () = shutdown_token.cancelled() => true,
×
148
            }
NEW
149
        });
×
150

151
        // The plugin run completed and deregistered its handler.
NEW
152
        if !interrupted {
×
153
            return;
×
154
        }
×
155

156
        // Send Shutdown over the protocol.
157
        if let Ok(mut writer) = shutdown_writer.lock() {
×
158
            drop(write_message(&mut *writer, &HostToPlugin::Shutdown));
×
159
        }
×
160
        shutdown_flag.store(true, Ordering::Release);
×
161

162
        // Grace period: wait in short intervals so we don't block cleanup
163
        // if the plugin exits promptly.
164
        for _ in 0..50 {
×
165
            thread::sleep(std::time::Duration::from_millis(100));
×
166
            if !is_process_alive(child_id) {
×
167
                return;
×
168
            }
×
169
        }
170

171
        kill_child(child_id);
×
172
    });
×
173

174
    // Send init.
175
    {
176
        let mut writer = stdin.lock().expect("stdin lock poisoned");
×
177
        write_message(&mut *writer, &init)
×
178
            .map_err(|e| cmd::Error::from(format!("failed to send init: {e}")))?;
×
179
    }
180

181
    // Read messages from plugin.
182
    let reader = BufReader::new(stdout);
×
183
    let result = message_loop(reader, &stdin, workspace, &config_json, &shutdown_sent);
×
184

185
    // Always clean up, even on error.
186
    drop(child.wait());
×
187
    drop(stderr_handle.join());
×
188
    drop(shutdown_handle);
×
189

190
    result
×
191
}
×
192

193
/// The main message loop: reads plugin requests and sends responses.
194
fn message_loop(
1✔
195
    reader: BufReader<impl std::io::Read>,
1✔
196
    stdin: &Mutex<impl Write>,
1✔
197
    workspace: &Workspace,
1✔
198
    config_json: &Value,
1✔
199
    shutdown_sent: &AtomicBool,
1✔
200
) -> Result<(), cmd::Error> {
1✔
201
    for line in reader.lines() {
2✔
202
        let line =
2✔
203
            line.map_err(|e| cmd::Error::from(format!("failed to read from plugin: {e}")))?;
2✔
204

205
        if line.trim().is_empty() {
2✔
206
            continue;
×
207
        }
2✔
208

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

212
        trace!(?msg, "Received plugin message.");
2✔
213

214
        let mut writer = stdin.lock().expect("stdin lock poisoned");
2✔
215

216
        match msg {
2✔
217
            PluginToHost::Ready => {
218
                debug!("Plugin signaled ready.");
1✔
219
            }
220

221
            PluginToHost::ListConversations(req) => {
×
222
                let response = handle_list_conversations(workspace, req.id);
×
223
                write_message(&mut *writer, &response)?;
×
224
            }
225

226
            PluginToHost::ReadEvents(req) => {
×
227
                let response = handle_read_events(workspace, &req.conversation, req.id);
×
228
                write_message(&mut *writer, &response)?;
×
229
            }
230

231
            PluginToHost::ReadConfig(req) => {
×
232
                let response = handle_read_config(config_json, req.path, req.id);
×
233
                write_message(&mut *writer, &response)?;
×
234
            }
235

236
            PluginToHost::Print(print) => {
×
237
                // In Phase 1, write to stdout directly. Full printer
×
238
                // integration comes later when we thread through &Printer.
×
239
                let stdout = std::io::stdout();
×
240
                let mut handle = stdout.lock();
×
241
                drop(handle.write_all(print.text.as_bytes()));
×
242
                drop(handle.flush());
×
243
            }
×
244

245
            PluginToHost::Log(log) => {
×
246
                emit_log(&log);
×
247
            }
×
248

249
            PluginToHost::Describe(_) => {
250
                debug!("Ignoring describe in message loop.");
×
251
            }
252

253
            PluginToHost::Exit(exit) => {
1✔
254
                debug!(code = exit.code, "Plugin exited.");
1✔
255
                if exit.code == 0 {
1✔
256
                    return Ok(());
1✔
257
                }
×
258
                return match exit.reason {
×
259
                    Some(reason) => Err(cmd::Error::from((exit.code, reason))),
×
260
                    None => Err(cmd::Error::from(exit.code)),
×
261
                };
262
            }
263
        }
264
    }
265

266
    // Plugin's stdout closed without an `exit` message. If we sent a
267
    // shutdown, this is expected (the child exited after receiving it).
268
    if shutdown_sent.load(Ordering::Acquire) {
×
269
        debug!("Plugin exited after shutdown.");
×
270
        return Ok(());
×
271
    }
×
272

273
    error!("Plugin exited without sending exit message.");
×
274
    Err(cmd::Error::from((
×
275
        1u8,
×
276
        "plugin exited unexpectedly without sending exit message",
×
277
    )))
×
278
}
1✔
279

280
fn handle_list_conversations(workspace: &Workspace, req_id: Option<String>) -> HostToPlugin {
×
281
    let data: Vec<ConversationSummary> = workspace
×
282
        .conversations()
×
283
        .map(|(id, meta)| ConversationSummary {
×
284
            id: id.as_deciseconds().to_string(),
×
285
            title: meta.title.clone(),
×
286
            last_activated_at: meta.last_activated_at,
×
287
            events_count: meta.events_count,
×
288
        })
×
289
        .collect();
×
290

291
    HostToPlugin::Conversations(ConversationsResponse { id: req_id, data })
×
292
}
×
293

294
fn handle_read_events(
×
295
    workspace: &Workspace,
×
296
    conversation_id: &str,
×
297
    req_id: Option<String>,
×
298
) -> HostToPlugin {
×
299
    let conv_id = match jp_conversation::ConversationId::try_from_deciseconds_str(conversation_id) {
×
300
        Ok(id) => id,
×
301
        Err(e) => {
×
302
            return HostToPlugin::Error(ErrorResponse {
×
303
                id: req_id,
×
304
                request: Some("read_events".to_owned()),
×
305
                message: format!("invalid conversation ID: {e}"),
×
306
            });
×
307
        }
308
    };
309

310
    let handle = match workspace.acquire_conversation(&conv_id) {
×
311
        Ok(h) => h,
×
312
        Err(e) => {
×
313
            return HostToPlugin::Error(ErrorResponse {
×
314
                id: req_id,
×
315
                request: Some("read_events".to_owned()),
×
316
                message: format!("conversation not found: {e}"),
×
317
            });
×
318
        }
319
    };
320

321
    let events = match workspace.events(&handle) {
×
322
        Ok(stream) => stream,
×
323
        Err(e) => {
×
324
            return HostToPlugin::Error(ErrorResponse {
×
325
                id: req_id,
×
326
                request: Some("read_events".to_owned()),
×
327
                message: format!("failed to load events: {e}"),
×
328
            });
×
329
        }
330
    };
331

332
    // Serialize events to JSON values, then decode base64-encoded storage
333
    // fields so plugins receive plain text.
334
    let (_, mut event_values) = match events.to_parts() {
×
335
        Ok(parts) => parts,
×
336
        Err(e) => {
×
337
            return HostToPlugin::Error(ErrorResponse {
×
338
                id: req_id,
×
339
                request: Some("read_events".to_owned()),
×
340
                message: format!("failed to serialize events: {e}"),
×
341
            });
×
342
        }
343
    };
344

345
    for value in &mut event_values {
×
346
        jp_conversation::decode_event_value(value);
×
347
    }
×
348

349
    HostToPlugin::Events(EventsResponse {
×
350
        id: req_id,
×
351
        conversation: conversation_id.to_owned(),
×
352
        data: event_values,
×
353
    })
×
354
}
×
355

356
fn handle_read_config(
3✔
357
    config_json: &Value,
3✔
358
    path: Option<String>,
3✔
359
    req_id: Option<String>,
3✔
360
) -> HostToPlugin {
3✔
361
    let data = match &path {
3✔
362
        Some(path) => {
2✔
363
            let mut current = config_json;
2✔
364
            for segment in path.split('.') {
3✔
365
                match current.get(segment) {
3✔
366
                    Some(v) => current = v,
2✔
367
                    None => {
368
                        return HostToPlugin::Error(ErrorResponse {
1✔
369
                            id: req_id,
1✔
370
                            request: Some("read_config".to_owned()),
1✔
371
                            message: format!("config path not found: {path}"),
1✔
372
                        });
1✔
373
                    }
374
                }
375
            }
376
            current.clone()
1✔
377
        }
378
        None => config_json.clone(),
1✔
379
    };
380

381
    HostToPlugin::Config(ConfigResponse {
2✔
382
        id: req_id,
2✔
383
        path,
2✔
384
        data,
2✔
385
    })
2✔
386
}
3✔
387

388
fn emit_log(log: &LogMessage) {
×
389
    match log.level.as_str() {
×
390
        "trace" => trace!(target: "plugin", message = %log.message),
×
391
        "debug" => debug!(target: "plugin", message = %log.message),
×
392
        "info" => tracing::info!(target: "plugin", message = %log.message),
×
393
        "warn" => warn!(target: "plugin", message = %log.message),
×
394
        "error" => error!(target: "plugin", message = %log.message),
×
395
        _ => {
396
            warn!(target: "plugin", level = %log.level, message = %log.message, "unknown log level");
×
397
        }
398
    }
399
}
×
400

401
fn write_message(writer: &mut impl Write, msg: &HostToPlugin) -> Result<(), cmd::Error> {
×
402
    let json = serde_json::to_string(msg)
×
403
        .map_err(|e| cmd::Error::from(format!("failed to serialize message: {e}")))?;
×
404
    writeln!(writer, "{json}")
×
405
        .map_err(|e| cmd::Error::from(format!("failed to write to plugin stdin: {e}")))?;
×
406
    writer
×
407
        .flush()
×
408
        .map_err(|e| cmd::Error::from(format!("failed to flush plugin stdin: {e}")))?;
×
409
    Ok(())
×
410
}
×
411

412
/// Check if a process is still alive by PID.
413
#[cfg(unix)]
414
fn is_process_alive(pid: u32) -> bool {
×
415
    // kill with signal 0 checks existence without sending a signal.
416
    unsafe { libc::kill(libc::pid_t::from(pid.cast_signed()), 0) == 0 }
×
417
}
×
418

419
#[cfg(windows)]
420
fn is_process_alive(pid: u32) -> bool {
421
    use windows_sys::Win32::{
422
        Foundation::{CloseHandle, STILL_ACTIVE},
423
        System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION},
424
    };
425

426
    unsafe {
427
        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
428
        if handle.is_null() {
429
            return false;
430
        }
431
        let mut exit_code: u32 = 0;
432
        let ok = GetExitCodeProcess(handle, &mut exit_code);
433
        CloseHandle(handle);
434
        ok != 0 && (exit_code as i32) == STILL_ACTIVE
435
    }
436
}
437

438
/// Send SIGKILL to a child process by PID.
439
///
440
/// Used as a last resort when the plugin doesn't exit within the grace period
441
/// after receiving `Shutdown`.
442
#[cfg(unix)]
443
fn kill_child(pid: u32) {
×
444
    // SAFETY: We're sending a signal to a process we spawned.
445
    unsafe {
×
446
        libc::kill(libc::pid_t::from(pid.cast_signed()), libc::SIGKILL);
×
447
    }
×
448
    debug!(pid, "Sent SIGKILL to plugin after grace period.");
×
449
}
×
450

451
#[cfg(windows)]
452
fn kill_child(pid: u32) {
453
    use windows_sys::Win32::{
454
        Foundation::CloseHandle,
455
        System::Threading::{OpenProcess, PROCESS_TERMINATE, TerminateProcess},
456
    };
457

458
    // SAFETY: We're terminating a process we spawned.
459
    unsafe {
460
        let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
461
        if !handle.is_null() {
462
            TerminateProcess(handle, 1);
463
            CloseHandle(handle);
464
        }
465
    }
466
    debug!(pid, "Sent TerminateProcess to plugin after grace period.");
467
}
468

469
/// Search `$PATH` for a plugin binary matching the given subcommand segments.
470
///
471
/// For `["serve"]`, looks for `jp-serve`.
472
/// For `["conversation", "export"]`, looks for `jp-conversation-export`.
473
pub(crate) fn find_plugin_binary(segments: &[&str]) -> Option<Utf8PathBuf> {
1✔
474
    let name = format!("jp-{}", segments.join("-"));
1✔
475
    which::which(&name)
1✔
476
        .ok()
1✔
477
        .and_then(|p| Utf8PathBuf::from_path_buf(p).ok())
1✔
478
}
1✔
479

480
/// Find any existing plugin binary without downloading or prompting.
481
///
482
/// Checks the install directory first, then `$PATH`.
483
/// Used for non-mutating operations like help requests.
484
pub(crate) fn find_any_plugin_binary(name: &str) -> Option<Utf8PathBuf> {
×
485
    if let Some(path) = registry::find_installed(name) {
×
486
        return Some(path);
×
487
    }
×
488
    let segments: Vec<&str> = name.split('-').collect();
×
489
    find_plugin_binary(&segments)
×
490
}
×
491

492
/// Resolve a plugin binary through multiple sources:
493
///
494
/// 1. User-local install directory (previously installed plugins)
495
/// 2. Plugin registry (auto-install if official, prompt if third-party)
496
/// 3. `$PATH` (with approval check for unapproved plugins)
497
///
498
/// The `plugins_config` drives installation and execution policy.
499
/// Per-plugin settings override the defaults from the registry (official vs
500
/// third-party).
501
pub(crate) async fn resolve_plugin_binary(
×
502
    name: &str,
×
503
    plugins_config: &PluginsConfig,
×
504
    is_tty: bool,
×
505
) -> Result<Option<Utf8PathBuf>, cmd::Error> {
×
506
    let plugin_cfg = plugins_config.command.get(name);
×
507

508
    // Explicit deny in config.
509
    if plugin_cfg.is_some_and(|c| c.run == Some(RunPolicy::Deny)) {
×
510
        return Err(cmd::Error::from(format!(
×
511
            "plugin `{name}` is denied by configuration (plugins.command.{name}.run = \"deny\")"
×
512
        )));
×
513
    }
×
514

515
    // 1. Already installed locally.
516
    if let Some(path) = registry::find_installed(name) {
×
517
        debug!(name, %path, "Found installed plugin.");
×
518
        verify_checksum(name, &path, plugin_cfg)?;
×
519
        return Ok(Some(path));
×
520
    }
×
521

522
    // 2. Check registry.
523
    if let Some(path) = try_registry_install(name, plugins_config, is_tty).await? {
×
524
        return Ok(Some(path));
×
525
    }
×
526

527
    // 3. Check $PATH with run policy.
528
    let segments: Vec<&str> = name.split('-').collect();
×
529
    if let Some(path) = find_plugin_binary(&segments) {
×
530
        check_run_policy(name, &path, plugin_cfg, is_tty)?;
×
531
        return Ok(Some(path));
×
532
    }
×
533

534
    Ok(None)
×
535
}
×
536

537
/// Verify a binary's checksum against the config-pinned value, if any.
538
fn verify_checksum(
×
539
    name: &str,
×
540
    binary_path: &Utf8Path,
×
541
    plugin_cfg: Option<&CommandPluginConfig>,
×
542
) -> Result<(), cmd::Error> {
×
543
    let Some(checksum) = plugin_cfg.and_then(|c| c.checksum.as_ref()) else {
×
544
        return Ok(());
×
545
    };
546

547
    let actual = registry::sha256_file(binary_path)?;
×
548
    if actual != checksum.value {
×
549
        return Err(cmd::Error::from(format!(
×
550
            "plugin `{name}` binary checksum mismatch.\nexpected: {}\nactual:   {actual}\nThe \
×
551
             binary at {binary_path} has changed since it was pinned. Update \
×
552
             plugins.command.{name}.checksum.value in your config to accept the new binary.",
×
553
            checksum.value,
×
554
        )));
×
555
    }
×
556

557
    Ok(())
×
558
}
×
559

560
/// Try to install a plugin from the cached registry.
561
async fn try_registry_install(
×
562
    name: &str,
×
563
    plugins_config: &PluginsConfig,
×
564
    is_tty: bool,
×
565
) -> Result<Option<Utf8PathBuf>, cmd::Error> {
×
566
    let Some(reg) = registry::load_cached() else {
×
567
        return Ok(None);
×
568
    };
569

570
    // Find the registry entry whose `id` matches the requested name.
571
    // In Phase 5, this will use the command path (registry key) for
572
    // multi-segment routing. For now, we match on `id`.
573
    let Some(plugin) = reg.plugins.values().find(|p| p.id == name) else {
×
574
        return Ok(None);
×
575
    };
576

577
    // Only handle command plugins.
578
    let jp_plugin::registry::PluginKind::Command { ref binaries, .. } = plugin.kind else {
×
579
        return Ok(None);
×
580
    };
581

582
    let target = registry::current_target();
×
583
    let Some(binary_info) = binaries.get(&target) else {
×
584
        return Ok(None);
×
585
    };
586

587
    let id = &plugin.id;
×
588
    let plugin_cfg = plugins_config.command.get(id);
×
589

590
    // Check if auto-install is allowed.
591
    let auto_install = plugin_cfg
×
592
        .and_then(|c| c.install)
×
593
        .unwrap_or(plugins_config.auto_install);
×
594

595
    if !auto_install && !plugin.official {
×
596
        return Ok(None);
×
597
    }
×
598

599
    // Determine run policy: config > registry default.
600
    let run_policy = plugin_cfg
×
601
        .and_then(|c| c.run)
×
602
        .unwrap_or(if plugin.official {
×
603
            RunPolicy::Unattended
×
604
        } else {
605
            RunPolicy::Ask
×
606
        });
607

608
    match run_policy {
×
609
        RunPolicy::Deny => {
610
            return Err(cmd::Error::from(format!(
×
611
                "plugin `{id}` is denied by configuration"
×
612
            )));
×
613
        }
614
        RunPolicy::Ask => {
615
            if !is_tty {
×
616
                return Err(cmd::Error::from(format!(
×
617
                    "plugin `{id}` requires approval. Run `jp plugin install {id}` first, or set \
×
618
                     plugins.command.{id}.run = \"unattended\" in config."
×
619
                )));
×
620
            }
×
621

622
            let mut writer = std::io::stderr();
×
623
            drop(writeln!(
×
624
                writer,
×
625
                "  \u{2192} Plugin `{id}` found in registry."
626
            ));
627
            let options = vec![
×
628
                InlineOption::new('y', "install and run"),
×
629
                InlineOption::new('n', "cancel"),
×
630
            ];
631
            let answer = InlineSelect::new("Install and run it?", options)
×
632
                .prompt(&mut writer)
×
633
                .map_err(|e| cmd::Error::from(format!("prompt failed: {e}")))?;
×
634

635
            if answer != 'y' {
×
636
                return Err(cmd::Error::from("plugin execution cancelled"));
×
637
            }
×
638
        }
639
        RunPolicy::Unattended => {}
×
640
    }
641

642
    drop(writeln!(
×
643
        std::io::stderr(),
×
644
        "  \u{2192} Installing jp-{id} for {target}..."
645
    ));
646
    let client = reqwest::Client::new();
×
647
    let data = registry::download_and_verify(&client, binary_info).await?;
×
648

649
    let path = registry::install_binary(id, &data)?;
×
650
    drop(writeln!(
×
651
        std::io::stderr(),
×
652
        "  \u{2192} Installed to {path}",
653
    ));
654

655
    // Verify against pinned checksum if configured.
656
    verify_checksum(id, &path, plugin_cfg)?;
×
657

658
    Ok(Some(path))
×
659
}
×
660

661
/// Check run policy for a `$PATH`-discovered plugin.
662
fn check_run_policy(
×
663
    name: &str,
×
664
    binary_path: &Utf8Path,
×
665
    plugin_cfg: Option<&CommandPluginConfig>,
×
666
    is_tty: bool,
×
667
) -> Result<(), cmd::Error> {
×
668
    // Verify pinned checksum first.
669
    verify_checksum(name, binary_path, plugin_cfg)?;
×
670

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

673
    match run_policy {
×
674
        RunPolicy::Unattended => Ok(()),
×
675
        RunPolicy::Deny => Err(cmd::Error::from(format!(
×
676
            "plugin `{name}` is denied by configuration"
×
677
        ))),
×
678
        RunPolicy::Ask => {
679
            if !is_tty {
×
680
                return Err(cmd::Error::from(format!(
×
681
                    "plugin `jp-{name}` found on $PATH but requires approval. Set \
×
682
                     plugins.command.{name}.run = \"unattended\" in config, or run `jp {name}` in \
×
683
                     a terminal."
×
684
                )));
×
685
            }
×
686

687
            // Check existing permanent approvals.
688
            if let Some(approvals) = registry::load_approvals()
×
689
                && let Some(approved) = approvals.approved.get(name)
×
690
                && approved.path == binary_path
×
691
                && registry::sha256_file(binary_path).is_ok_and(|sha| sha == approved.sha256)
×
692
            {
693
                debug!(name, %binary_path, "Plugin previously approved.");
×
694
                return Ok(());
×
695
            }
×
696

697
            let mut writer = std::io::stderr();
×
698
            drop(writeln!(
×
699
                writer,
×
700
                "  \u{2192} Found jp-{name} on $PATH ({binary_path})",
701
            ));
702
            let options = vec![
×
703
                InlineOption::new('y', "run this time"),
×
704
                InlineOption::new('Y', "run and remember permanently"),
×
705
                InlineOption::new('n', "deny"),
×
706
            ];
707
            let answer = InlineSelect::new("Run it?", options)
×
708
                .prompt(&mut writer)
×
709
                .map_err(|e| cmd::Error::from(format!("prompt failed: {e}")))?;
×
710

711
            match answer {
×
712
                'y' => Ok(()),
×
713
                'Y' => {
714
                    registry::save_approval(name, binary_path)?;
×
715
                    Ok(())
×
716
                }
717
                _ => Err(cmd::Error::from("plugin execution denied")),
×
718
            }
719
        }
720
    }
721
}
×
722

723
/// Send a `Describe` request to a plugin and return its metadata.
724
///
725
/// Spawns the binary, sends `{"type":"describe"}`, reads one response line, and
726
/// returns the parsed [`DescribeResponse`].
727
/// Returns `None` if the plugin doesn't support describe or fails to respond.
728
pub(crate) fn describe_plugin(binary: &Utf8Path) -> Option<DescribeResponse> {
×
729
    let mut child = Command::new(binary)
×
730
        .stdin(Stdio::piped())
×
731
        .stdout(Stdio::piped())
×
732
        .stderr(Stdio::null())
×
733
        .spawn()
×
734
        .ok()?;
×
735

736
    let mut child_stdin = child.stdin.take()?;
×
737
    let child_stdout = child.stdout.take()?;
×
738

739
    // Send describe request.
740
    let json = serde_json::to_string(&HostToPlugin::Describe).ok()?;
×
741
    writeln!(child_stdin, "{json}").ok()?;
×
742
    child_stdin.flush().ok()?;
×
743
    drop(child_stdin); // Signal no more messages.
×
744

745
    // Read one line response.
746
    let mut reader = BufReader::new(child_stdout);
×
747
    let mut line = String::new();
×
748
    reader.read_line(&mut line).ok()?;
×
749

750
    drop(child.wait());
×
751

752
    if line.trim().is_empty() {
×
753
        return None;
×
754
    }
×
755

756
    let msg: PluginToHost = serde_json::from_str(line.trim()).ok()?;
×
757
    match msg {
×
758
        PluginToHost::Describe(resp) => Some(resp),
×
759
        _ => None,
×
760
    }
761
}
×
762

763
/// Discover plugin binaries on `$PATH` and in the user-local install directory.
764
///
765
/// Returns `(subcommand_name, binary_path)` pairs, sorted by name.
766
/// For a binary named `jp-serve`, the subcommand name is `serve`.
767
/// Installed plugins take priority over `$PATH` duplicates.
768
pub(crate) fn discover_plugins() -> Vec<(String, Utf8PathBuf)> {
×
769
    let path_var = std::env::var_os("PATH").unwrap_or_default();
×
770
    let mut seen = HashSet::new();
×
771
    let mut plugins = Vec::new();
×
772

773
    // Scan install directory first so installed plugins take priority.
774
    if let Some(bin_dir) = registry::bin_dir() {
×
775
        scan_dir_for_plugins(&bin_dir, &mut seen, &mut plugins);
×
776
    }
×
777

778
    for dir in std::env::split_paths(&path_var) {
×
779
        let Some(dir) = Utf8Path::from_path(&dir) else {
×
780
            continue;
×
781
        };
782

783
        scan_dir_for_plugins(dir, &mut seen, &mut plugins);
×
784
    }
785

786
    plugins.sort_by(|a, b| a.0.cmp(&b.0));
×
787
    plugins
×
788
}
×
789

790
fn scan_dir_for_plugins(
×
791
    dir: &Utf8Path,
×
792
    seen: &mut HashSet<String>,
×
793
    plugins: &mut Vec<(String, Utf8PathBuf)>,
×
794
) {
×
795
    let Ok(entries) = dir.read_dir_utf8() else {
×
796
        return;
×
797
    };
798
    for entry in entries.flatten() {
×
799
        let name = entry.file_name();
×
800
        let Some(subcommand) = name.strip_prefix("jp-") else {
×
801
            continue;
×
802
        };
803

804
        // On Windows, strip the .exe extension.
805
        #[cfg(windows)]
806
        let subcommand = subcommand.strip_suffix(".exe").unwrap_or(subcommand);
807

808
        // On Unix, skip non-executable files.
809
        #[cfg(unix)]
810
        {
811
            use std::os::unix::fs::PermissionsExt as _;
812
            let Ok(meta) = entry.metadata() else {
×
813
                continue;
×
814
            };
815
            if meta.permissions().mode() & 0o111 == 0 {
×
816
                continue;
×
817
            }
×
818
        }
819

820
        if seen.insert(subcommand.to_owned()) {
×
821
            plugins.push((subcommand.to_owned(), entry.into_path()));
×
822
        }
×
823
    }
824
}
×
825

826
/// Show a plugin's help text via the `Describe` protocol.
827
pub(crate) fn show_plugin_help(binary: &Utf8Path) -> cmd::Output {
×
828
    match describe_plugin(binary) {
×
829
        Some(desc) => {
×
830
            let mut out = std::io::stdout().lock();
×
831
            if let Some(help) = &desc.help {
×
832
                drop(writeln!(out, "{help}"));
×
833
            } else {
×
834
                drop(writeln!(out, "{}: {}", desc.name, desc.description));
×
835
            }
×
836
            Ok(())
×
837
        }
838
        None => Err(cmd::Error::from("plugin does not support describe")),
×
839
    }
840
}
×
841

842
/// Produce a clap-formatted error for an unknown subcommand.
843
///
844
/// Uses `Command::error()` to get clap's standard error chrome (colored
845
/// `error:` prefix, usage line, help hint).
846
/// The message includes our plugin-specific context.
847
/// Returns exit code 2 (clap's convention for usage errors) with no message,
848
/// since the output was already written.
849
fn unknown_subcommand_error(name: &str) -> cmd::Error {
×
850
    use clap::CommandFactory as _;
851

852
    let mut cmd = crate::Cli::command();
×
853
    let err = cmd.error(
×
854
        clap::error::ErrorKind::InvalidSubcommand,
×
855
        format!(
×
856
            "unrecognized subcommand '{name}'\n\n  No built-in command, registry plugin, or \
857
             `jp-{name}` binary found on $PATH."
858
        ),
859
    );
860
    drop(err.print());
×
861
    cmd::Error::from(2u8)
×
862
}
×
863

864
/// Dispatch an external plugin subcommand.
865
///
866
/// Resolves the plugin binary, then runs the protocol loop.
867
/// Called from `Commands::run()` after the normal startup flow.
868
pub(crate) async fn run_external(args: &[String], ctx: &Ctx) -> cmd::Output {
×
869
    let (subcommand, plugin_args) = args
×
870
        .split_first()
×
871
        .ok_or("no subcommand provided for plugin dispatch")?;
×
872

873
    // Handle help without downloading or approval.
874
    if plugin_args.iter().any(|a| a == "-h" || a == "--help") {
×
875
        let binary = find_any_plugin_binary(subcommand).ok_or_else(|| {
×
876
            cmd::Error::from(format!(
×
877
                "plugin `{subcommand}` not found. No installed plugin or `jp-{subcommand}` binary \
878
                 found on $PATH.",
879
            ))
880
        })?;
×
881
        return show_plugin_help(&binary);
×
882
    }
×
883

884
    let config = ctx.config();
×
885
    let Some(binary) = resolve_plugin_binary(subcommand, &config.plugins, ctx.term.is_tty).await?
×
886
    else {
887
        return Err(unknown_subcommand_error(subcommand));
×
888
    };
889

890
    debug!(%binary, subcommand, "Dispatching to plugin.");
×
891

892
    run_plugin(
×
893
        subcommand,
×
894
        &binary,
×
895
        plugin_args,
×
896
        &ctx.workspace,
×
897
        ctx.storage_path(),
×
898
        ctx.user_storage_path(),
×
899
        &config,
×
900
        &ctx.signals,
×
901
        ctx.term.args.verbose,
×
902
    )?;
×
903
    Ok(())
×
904
}
×
905

906
#[cfg(test)]
907
#[path = "dispatch_tests.rs"]
908
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