Skip to main content

agentmux_srv/server/
cli_handlers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(windows)]
5use agentmux_common::win32::NoWindow;
6use std::sync::Arc;
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    ToolchainEnvReq, ToolchainEnvResult, ToolchainVersionsReq,
11    ToolchainPruneItem, ToolchainPruneReq, ToolchainPruneResult, ToolchainPruneSkip,
12    WidgetApiResult, WidgetHealthResult,
13    CheckCliAuthResult, CommandCheckCliAuthData, CommandResolveCliData, CommandRunCliLoginData,
14    EnsureProviderAuthDirReq, EnsureProviderAuthDirResult, ResolveCliResult, RunCliLoginResult,
15    COMMAND_CHECK_CLI_AUTH, COMMAND_ENSURE_PROVIDER_AUTH_DIR, COMMAND_RESOLVE_CLI,
16};
17
18use super::AppState;
19
20/// Register CLI-related RPC handlers (resolvecli, checkcliauth, runclilogin).
21pub fn register_cli_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
22    // resolvecli → detect or install a CLI tool for an agent provider.
23    // Installs are shared across AgentMux versions, keyed by the provider's
24    // pinned CLI version: `<shared_dir>/cli/<provider>/<pinned_version>/`,
25    // with the legacy `<home>/instances/v<AGENTMUX_VERSION>/cli/<provider>/`
26    // as a read-only fallback. One definition for every resolver
27    // (`install.start` / `install.check`, `agent.open`, the picker's
28    // read-only lookup): `backend::cli_install`.
29    // Never falls back to system PATH for npm-backed providers.
30    let broker_resolve = state.broker.clone();
31    let filestore_resolve = state.filestore.clone();
32    let mstore_resolve = state.mstore.clone();
33    engine.register_typed(
34        COMMAND_RESOLVE_CLI,
35        move |cmd: CommandResolveCliData, _ctx| {
36            let notices = CliNotices {
37                broker: broker_resolve.clone(),
38                filestore: filestore_resolve.clone(),
39                mstore: mstore_resolve.clone(),
40                block_id: notice_block_id(&cmd),
41                agent_id: cmd.agent_id.clone().filter(|a| !a.trim().is_empty()),
42                provider: cmd.provider_id.clone(),
43            };
44            resolve_cli(cmd, broker_resolve.clone(), notices)
45        },
46    );
47
48    // checkcliauth → check if a CLI tool is authenticated
49    // For Claude: reads ~/.claude/.credentials.json directly (instant, no subprocess).
50    // For other providers: falls back to running the CLI auth check command.
51    engine.register_typed(COMMAND_CHECK_CLI_AUTH, |cmd: CommandCheckCliAuthData, _ctx| check_cli_auth(cmd));
52
53    // provider.ensureauthdir → create the provider's default (shared) auth dir
54    // and apply its isolation guarantees, exactly as agent open does; returns
55    // the path for the launch env (e.g. CLAUDE_CONFIG_DIR). Replaces the CEF
56    // host's `ensure_auth_dir`, which only created the dir.
57    engine.register_typed(COMMAND_ENSURE_PROVIDER_AUTH_DIR, |req: EnsureProviderAuthDirReq, _ctx| {
58        ensure_provider_auth_dir(req)
59    });
60
61    // runclilogin → spawn CLI login flow, extract OAuth URL from output, return immediately
62    engine.register_typed("runclilogin", |cmd: CommandRunCliLoginData, _ctx| run_cli_login(cmd));
63
64    // toolchain.env — report the environment the srv resolves tools in: the
65    // effective PATH, how it was derived (set by the host/srv PATH enricher,
66    // see SPEC_TOOLCHAIN_MANAGER §3), and OS/arch. Powers the Toolchain
67    // modal's Environment section so PATH problems are diagnosable.
68    //
69    // `Option<_>` -- see `ToolchainEnvReq`: it is what makes both encodings
70    // of "no argument" deserialize.
71    engine.register_typed("toolchain.env", |_req: Option<ToolchainEnvReq>, _ctx| toolchain_env());
72
73    // toolchain.prune — find (dry run, the default) or remove (an explicit
74    // `dry_run: false`, from a user action) provider CLI installs that nothing
75    // has used for 30 days and nothing is running. Never runs on its own.
76    // SPEC_RUNTIME_MENU_REMAINING_GAPS_2026_10_01.md §5.
77    let mstore_prune = state.mstore.clone();
78    engine.register_typed("toolchain.prune", move |req: Option<ToolchainPruneReq>, _ctx| {
79        toolchain_prune(req, mstore_prune.clone())
80    });
81
82    // widget.health — HTTP liveness probe for an external widget server running
83    // on localhost. The frontend passes { port, health_check_path,
84    // health_check_body_contains? } and gets back { healthy, status_code }.
85    // Connection-refused or timeout → { healthy: false } (not an RPC error).
86    // health_check_body_contains lets callers distinguish services that share
87    // a default port (e.g. Flowise and Grafana both default to 3000).
88    // Registered with `serde_json::Value` as the REQUEST type rather than a
89    // struct. `Value` deserializes from anything, so this is exactly as
90    // tolerant as the untyped handler it replaces -- and the handler needs that
91    // tolerance: a bad port or path is answered with `healthy: false`, not an
92    // RPC error, which a typed request would turn into a deserialize failure.
93    //
94    // What it buys over `register_handler` is the RESPONSE type, which is the
95    // half that was actually drifting.
96    engine.register_typed("widget.health", |data: serde_json::Value, _ctx| widget_health(data));
97
98    // widget.api — HTTP proxy to a widget's local server. Bypasses browser CORS
99    // restrictions: the frontend sends { port, path, method?, headers?, body? }
100    // and gets back { ok, status_code, body, error? }. Agents use this to call
101    // ComfyUI /prompt, Grafana /api/query, etc. without needing a CORS header.
102    // 30-second timeout accommodates generative tasks (image synthesis, etc.).
103    // `Value` request for the same reason as `widget.health` above: an invalid
104    // port or path is a `ok: false` ANSWER, not a rejected request.
105    engine.register_typed("widget.api", |data: serde_json::Value, _ctx| widget_api(data));
106
107    // toolchain.versions — fetch the latest published version for a list of npm
108    // packages from the npm registry. Input: { packages: [{id, package}] }.
109    // Output: { id: "x.y.z" | null, ... }. Each lookup is independent — a
110    // network error for one package yields null for that entry, not a failure.
111    // 5-second per-request timeout; all lookups run concurrently.
112    engine.register_typed("toolchain.versions", |req: ToolchainVersionsReq, _ctx| toolchain_versions(req));
113}
114
115/// `resolvecli`: find the CLI, else say how to install it, else install it.
116async fn resolve_cli(
117    cmd: CommandResolveCliData,
118    broker: Arc<crate::backend::mps::Broker>,
119    notices: CliNotices,
120) -> Result<ResolveCliResult, String> {
121    const AGENTMUX_VERSION: &str = env!("CARGO_PKG_VERSION");
122
123    tracing::info!(
124        provider = %cmd.provider_id,
125        cli = %cmd.cli_command,
126        block_id = %cmd.block_id,
127        agentmux_version = AGENTMUX_VERSION,
128        "ResolveCli"
129    );
130
131    // Only AgentMux's own registry names a package to install: an id
132    // outside it that sends one is refused before anything is looked up.
133    if !cmd.npm_package.is_empty() && crate::backend::providers::get_provider(&cmd.provider_id).is_none() {
134        return Err(format!("resolvecli: {:?} is not a known agent CLI", cmd.provider_id));
135    }
136
137    // Install location: shared across AgentMux versions, keyed
138    // by the provider's pinned CLI version, with the legacy
139    // per-version dir as a read-only fallback — see
140    // `backend::cli_install` (SPEC_AGENT_OPEN_LATENCY_2026_09_27.md
141    // F1). The backend registry's pin wins over the caller's.
142    let paths = agentmux_common::DataPaths::from_env()
143        .ok_or_else(|| "DataPaths::from_env() failed".to_string())?;
144    let pinned_version = crate::backend::providers::get_provider(&cmd.provider_id)
145        .map(|p| p.pinned_version.to_string())
146        .unwrap_or_else(|| cmd.pinned_version.clone());
147    let install_dir = crate::backend::cli_install::install_dir(&paths, &cmd.provider_id, &pinned_version);
148    let provider_dir = install_dir.to_string_lossy().to_string();
149    // npm binary path — the only valid location for installed CLIs.
150    let npm_bin = crate::backend::cli_install::npm_bin(&install_dir, &cmd.cli_command)
151        .to_string_lossy()
152        .to_string();
153
154    let registered = crate::backend::providers::get_provider(&cmd.provider_id);
155    if let Some(found) = locate_for_resolve(&cmd, &paths, &pinned_version).await {
156        let version = get_cli_version(&found.path).await;
157        tracing::info!(path = %found.path, version = %version, source = found.source.as_str(), "CLI found");
158        notices.observe_version(&version);
159        return Ok(ResolveCliResult {
160            cli_path: found.path,
161            version,
162            source: found.source.as_str().to_string(),
163        });
164    }
165    if let Some(refusal) = not_installed_refusal(&cmd, registered) {
166        return Err(refusal);
167    }
168
169    // What gets installed is the registry's package for this id,
170    // whatever the request names; an id outside the registry is not
171    // installed.
172    let provider = crate::server::install_handlers::installable_provider(&cmd.provider_id)
173        .map_err(|e| format!("resolvecli: {e}"))?;
174    if crate::backend::cli_download::is_managed_install(provider.id) {
175        return resolve_by_download(&notices, &broker, &paths, &cmd, provider.id, &pinned_version).await;
176    }
177    tracing::info!(
178        provider = %provider.id,
179        npm_package = %provider.npm_package,
180        pinned_version = %pinned_version,
181        target_dir = %provider_dir,
182        "CLI not found locally, installing via npm"
183    );
184    install_via_npm(&cmd, &broker, &notices, &paths, provider, &pinned_version, &npm_bin).await
185}
186
187/// Steps 1 and 2 of `resolvecli`: already there? A provider in the registry goes
188/// through the one lookup (`locate_provider_cli`): AgentMux's
189/// install, else the user's own copy only when the registry says
190/// AgentMux doesn't install it. A core tool (git, node, …) isn't
191/// in the registry: its install dir, else PATH when the caller
192/// sent no package.
193async fn locate_for_resolve(
194    cmd: &CommandResolveCliData,
195    paths: &agentmux_common::DataPaths,
196    pinned_version: &str,
197) -> Option<LocatedCli> {
198    if crate::backend::providers::get_provider(&cmd.provider_id).is_some() {
199        return locate_provider_cli(&cmd.provider_id).await;
200    }
201    match crate::backend::cli_install::find_installed(paths, &cmd.provider_id, pinned_version, &cmd.cli_command) {
202        Some(found) => Some(LocatedCli {
203            path: found.to_string_lossy().into_owned(),
204            source: CliSource::LocalInstall,
205        }),
206        None if cmd.npm_package.is_empty() => {
207            resolve_provider_cli_on_path(&cmd.provider_id, &cmd.cli_command)
208                .await
209                .map(|path| LocatedCli { path, source: CliSource::SystemPath })
210        }
211        None => None,
212    }
213}
214
215/// A CLI that was not found and that `resolvecli` must not install: AgentMux doesn't
216/// install it (say how to), or the caller sent no package (a look, not an install request).
217fn not_installed_refusal(
218    cmd: &CommandResolveCliData,
219    registered: Option<&'static crate::backend::providers::ProviderConfig>,
220) -> Option<String> {
221    let path_only = registered
222        .map(|p| p.npm_package.is_empty() && !crate::backend::cli_download::is_managed_install(p.id))
223        .unwrap_or_else(|| cmd.npm_package.is_empty());
224    if path_only {
225        // This branch fires for PATH-only providers
226        // (`npm_package` empty) whose CLI isn't on the
227        // system PATH. AgentMux can't auto-install these
228        // — emit AMX-CLI-004 with a manual install hint
229        // instead of AMX-CLI-001 ("Click Install now"),
230        // which would point the user at an install
231        // affordance that doesn't apply.
232        let install_hint = if cfg!(target_os = "windows") {
233            cmd.windows_install_command.clone()
234        } else {
235            cmd.unix_install_command.clone()
236        };
237        return Some(
238            agentmux_common::AgentMuxError::CliMissingOnPath {
239                provider: cmd.provider_id.clone(),
240                cli: cmd.cli_command.clone(),
241                install_hint,
242            }
243            .to_wire()
244            .to_string(),
245        );
246    }
247    // An npm-managed provider that isn't installed, asked about
248    // without its package: a look, not an install request.
249    if cmd.npm_package.is_empty() {
250        return Some(
251            agentmux_common::AgentMuxError::CliNotInstalled {
252                provider: cmd.provider_id.clone(),
253                cli: cmd.cli_command.clone(),
254            }
255            .to_wire()
256            .to_string(),
257        );
258    }
259    None
260}
261
262/// Whether `npm` can be found: `where` on Windows, `which` elsewhere.
263async fn npm_is_available() -> bool {
264    if cfg!(windows) {
265        // CREATE_NO_WINDOW (0x08000000) suppresses cmd flash —
266        // see broader fix in this file's other spawns.
267        let mut probe = tokio::process::Command::new("where");
268        probe.arg("npm");
269        #[cfg(windows)]
270        {
271            probe.no_window();
272        }
273        probe.output().await.map(|o| o.status.success()).unwrap_or(false)
274    } else {
275        tokio::process::Command::new("which").arg("npm").output().await
276            .map(|o| o.status.success()).unwrap_or(false)
277    }
278}
279
280/// Install the provider's pinned package with npm and report the result.
281async fn install_via_npm(
282    cmd: &CommandResolveCliData,
283    broker: &Arc<crate::backend::mps::Broker>,
284    notices: &CliNotices,
285    paths: &agentmux_common::DataPaths,
286    provider: &'static crate::backend::providers::ProviderConfig,
287    pinned_version: &str,
288    npm_bin: &str,
289) -> Result<ResolveCliResult, String> {
290    // Verify npm is available before attempting install.
291    if !npm_is_available().await {
292        return Err(format!(
293            "{} requires Node.js/npm to install. \
294            Install Node.js from https://nodejs.org then restart AgentMux.",
295            cmd.cli_command
296        ));
297    }
298
299    let outcome = run_npm_install(cmd, broker, notices, paths, provider, pinned_version).await?;
300
301    use crate::backend::cli_install::{InstallError, InstallOutcome};
302    let (bin, source) = match outcome {
303        Ok(InstallOutcome::Installed(bin)) => (bin, "installed"),
304        Ok(InstallOutcome::AlreadyInstalled(bin)) => (bin, "local_install"),
305        Err(InstallError::NpmFailed { code }) => {
306            return Err(agentmux_common::AgentMuxError::NpmInstallFailed {
307                package: format!("{}@{}", provider.npm_package, pinned_version),
308                message: format!(
309                    "exit {}; check the output above",
310                    code.unwrap_or(-1)
311                ),
312            }
313            .to_wire()
314            .to_string());
315        }
316        Err(InstallError::ShimMissing { .. }) => {
317            return Err(agentmux_common::AgentMuxError::CliShimMissing {
318                provider: cmd.provider_id.clone(),
319                expected_path: npm_bin.to_string(),
320            }
321            .to_wire()
322            .to_string());
323        }
324        Err(e) => return Err(e.to_string()),
325    };
326    let bin = bin.to_string_lossy().to_string();
327    let version = get_cli_version(&bin).await;
328    tracing::info!(path = %bin, version = %version, source, "CLI installed (npm)");
329    notices.observe_version(&version);
330    Ok(ResolveCliResult {
331        cli_path: bin,
332        version,
333        source: source.to_string(),
334    })
335}
336
337/// One install routine for this and the startup warm-up
338/// (`cli_install::install_pinned_cli`): cross-instance lock
339/// held for npm's whole lifetime — inside the blocking task,
340/// so a timed-out RPC can't release it early — reuse of an
341/// install another instance finished while we waited, and
342/// the completion marker only after the shim is verified.
343/// The pane says it's installing, then how it went: a pane
344/// restored at startup otherwise just starts slower.
345async fn run_npm_install(
346    cmd: &CommandResolveCliData,
347    broker: &Arc<crate::backend::mps::Broker>,
348    notices: &CliNotices,
349    paths: &agentmux_common::DataPaths,
350    provider: &'static crate::backend::providers::ProviderConfig,
351    pinned_version: &str,
352) -> Result<
353    Result<crate::backend::cli_install::InstallOutcome, crate::backend::cli_install::InstallError>,
354    String,
355> {
356    let req = crate::backend::cli_install::NpmInstallRequest {
357        provider_id: provider.id.to_string(),
358        npm_package: provider.npm_package.to_string(),
359        pinned_version: pinned_version.to_string(),
360        cli_command: provider.cli_command.to_string(),
361        background: false,
362    };
363    let install_paths = paths.clone();
364    let block_id_install = cmd.block_id.clone();
365    let install_id = format!("{}-{}-{}", cmd.provider_id, pinned_version, agentmux_common::time::now_ms());
366    let install_started = std::time::Instant::now();
367    notices.install(&install_id, pinned_version, crate::backend::cli_notice::InstallState::Installing, None, None);
368    let broker_npm = broker.clone();
369    let outcome = tokio::task::spawn_blocking(move || {
370        let on_line = |stream: &'static str, line: &str| {
371            tracing::info!(stream, line = %line, "npm output");
372            if !block_id_install.is_empty() {
373                crate::backend::mps::publish_install_progress(
374                    &broker_npm,
375                    &block_id_install,
376                    line,
377                );
378            }
379        };
380        crate::backend::cli_install::install_pinned_cli(
381            &install_paths,
382            &req,
383            &on_line,
384        )
385    })
386    .await
387    .map_err(|e| format!("npm install task panicked: {e}"))?;
388    match &outcome {
389        Ok(_) => notices.install(
390            &install_id,
391            pinned_version,
392            crate::backend::cli_notice::InstallState::Installed,
393            Some(install_started.elapsed().as_secs_f64()),
394            None,
395        ),
396        Err(e) => notices.install(
397            &install_id,
398            pinned_version,
399            crate::backend::cli_notice::InstallState::Failed,
400            None,
401            Some(&e.to_string()),
402        ),
403    }
404    Ok(outcome)
405}
406
407/// `checkcliauth`.
408///
409/// Two-phase auth check for Claude; single-phase for other providers.
410///
411/// Phase 1 (fast, <1 ms): read the credentials file to determine whether
412/// tokens exist at all. If no file / no tokens → return unauthenticated
413/// immediately without spawning the CLI. This avoids a 10+ second cold-start
414/// stall when the user is definitely not logged in.
415///
416/// Phase 2 (CLI, 10 s timeout): only when tokens ARE present, run
417/// `claude auth status --json` to validate them and obtain the real email.
418/// This catches expired/revoked tokens — the false-positive that the old
419/// file-only fast path missed.
420///
421/// Other providers skip Phase 1 and go straight to the CLI (they don't have
422/// a predictable credentials file layout).
423///
424/// See SPEC_AUTH_CHECK_FALSE_POSITIVE_2026_04_15.md.
425async fn check_cli_auth(cmd: CommandCheckCliAuthData) -> Result<CheckCliAuthResult, String> {
426    tracing::info!(cli = %cmd.cli_path, "CheckCliAuth");
427
428    if cmd.cli_path.to_lowercase().contains("claude") {
429        if let Some(signed_out) = claude_credentials_gate(&cmd).await {
430            return Ok(signed_out);
431        }
432    }
433
434    let (authenticated, email, auth_method, raw_output) =
435        run_auth_check(&cmd.cli_path, &cmd.auth_check_args, &cmd.auth_env).await?;
436
437    // REMOVED 2026-08-31 (Codex P1 on PR #2878) — the "self-heal a
438    // stale isolated Claude credential" step. When validation
439    // failed, it copied the user's personal
440    // `~/.claude/.credentials.json` into the isolated dir (via
441    // `refresh_claude_dir_from_global_if_stale`) whenever the global
442    // access token differed, then re-validated ONCE so the agent
443    // "recovered" — meaning a channel silently acquired a credential
444    // authenticated OUTSIDE it and could then report authenticated
445    // with no channel-local login at all.
446    //
447    // Same source and same end state as the first-run bootstrap
448    // removed above, just a different trigger, so removing only that
449    // one would have left this per-channel-isolation bypass wide
450    // open. See
451    // `docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md`
452    // (#5).
453    //
454    // The real failure it was papering over (a global re-login
455    // rotating the token and killing the isolated refresh token —
456    // the "Pozl 401") is now surfaced honestly: validation fails, the
457    // auth card appears, and the user logs in FOR THIS CHANNEL.
458
459    Ok(CheckCliAuthResult {
460        authenticated,
461        email,
462        auth_method,
463        raw_output,
464        store_problem: None,
465    })
466}
467
468/// Phase 1 of the Claude auth check: `Some(result)` answers "signed out" without
469/// running the CLI; `None` means go on and ask the CLI.
470async fn claude_credentials_gate(cmd: &CommandCheckCliAuthData) -> Option<CheckCliAuthResult> {
471    let home = std::env::var("HOME")
472        .or_else(|_| std::env::var("USERPROFILE"))
473        .unwrap_or_default();
474
475    // REMOVED 2026-08-31 — the first-run bootstrap that copied
476    // the user's global `~/.claude/.credentials.json` into the
477    // isolated CLAUDE_CONFIG_DIR (gated on a
478    // `.agentmux-cred-seeded` sentinel).
479    //
480    // It ran during a routine AUTH CHECK — no login, no user
481    // action, no bound account — so an agent in a fresh
482    // channel silently acquired the operator's personal
483    // credential. That is the most direct of the four
484    // per-channel-isolation bypasses catalogued in
485    // `docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md`
486    // (#4), and the most likely answer to the reported "agents
487    // operate with no account" (it also explains why the
488    // symptom varied by machine — it depended on whether
489    // `~/.claude` happened to hold a valid credential).
490    //
491    // Its original justification
492    // (`docs/retro/retro-provider-auth-isolation-regression-2026-06-05.md`)
493    // predates the "agents never use ~/.claude" requirement
494    // (`SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md`)
495    // and was never revisited against it.
496    //
497    // An unauthenticated isolated dir must now simply report
498    // `authenticated: false` and let the user log in FOR THIS
499    // CHANNEL. Do not reintroduce an import here: a check must
500    // report state, never mint credentials as a side effect.
501
502    // §4 INVARIANT (provider-auth-isolation.md): validate the SAME dir
503    // the agent runs in — the isolated CLAUDE_CONFIG_DIR if set, else
504    // global ~/.claude. NEVER "isolated OR global": that "check global /
505    // run isolated" split is the validate-spin regression's root cause
506    // (phase 2 below runs `claude auth status --json` against this exact
507    // dir, so phase 1 must check the same one).
508    let creds_path = cmd
509        .auth_env
510        .get("CLAUDE_CONFIG_DIR")
511        .map(|d| format!("{}/.credentials.json", d))
512        .unwrap_or_else(|| format!("{}/.claude/.credentials.json", home));
513
514    let tokens_exist = claude_tokens_exist(&creds_path);
515
516    // Login/logout robustness diagnostic: snapshot the SAME dir
517    // we validate (token fingerprint is redacted — see
518    // identity::auth_diag). Across login/logout rounds this
519    // surfaces the classic bugs — a check reading a different
520    // dir than login wrote, a token that didn't change after a
521    // re-login, or a credential that outlived a logout. The CLI
522    // verdict is logged separately below; compare the two.
523    // Cover BOTH the isolated dir (CLAUDE_CONFIG_DIR) and the
524    // global-fallback dir (~/.claude) — creds_path/tokens_exist
525    // above use exactly this resolution, so the snapshot always
526    // reflects the dir actually validated (not only the isolated
527    // case). "auth.credstate:" is `muxlog auth` vocabulary.
528    let checked_dir = cmd
529        .auth_env
530        .get("CLAUDE_CONFIG_DIR")
531        .cloned()
532        .unwrap_or_else(|| format!("{home}/.claude"));
533    tracing::info!(
534        "auth.credstate: check {}",
535        crate::identity::auth_diag::snapshot(&checked_dir)
536    );
537
538    if !tokens_exist {
539        // On macOS the Claude CLI stores credentials in the
540        // Keychain ("Claude Safe Storage"), NOT in
541        // .credentials.json — so a missing file does NOT mean
542        // logged out. Fall through to `claude auth status`, which
543        // reads the Keychain (and does so without a prompt — the
544        // CLI owns that Keychain item). On Windows/Linux the file
545        // IS the credential store, so the fast "definitely not
546        // authenticated" short-circuit stays correct there.
547        #[cfg(not(target_os = "macos"))]
548        {
549            tracing::info!("claude auth check: no credentials in provider dir, skipping CLI");
550            return Some(CheckCliAuthResult::signed_out("no credentials found"));
551        }
552        #[cfg(target_os = "macos")]
553        {
554            // No login keychain: say so instead of asking the CLI, whose read of it
555            // makes macOS open its "Keychain Not Found" dialog on every poll.
556            if let Some(result) = super::keychain_probe::no_keychain_result().await {
557                return Some(result);
558            }
559            tracing::info!("claude auth check: no credentials file — checking Keychain via CLI (macOS)");
560        }
561    } else {
562        // Tokens exist in the provider dir — validate with the CLI (10 s timeout).
563        tracing::info!("claude auth check: credentials found, validating via CLI");
564    }
565    None
566}
567
568/// Whether the Claude credentials file holds an access or a refresh token.
569fn claude_tokens_exist(creds_path: &str) -> bool {
570    match std::fs::read_to_string(creds_path) {
571        Ok(content) => serde_json::from_str::<serde_json::Value>(&content)
572            .ok()
573            .map(|json| {
574                let oauth = json.get("claudeAiOauth");
575                let has_token = oauth
576                    .and_then(|o| o.get("accessToken"))
577                    .and_then(|v| v.as_str())
578                    .map(|s| !s.is_empty())
579                    .unwrap_or(false);
580                let has_refresh = oauth
581                    .and_then(|o| o.get("refreshToken"))
582                    .and_then(|v| v.as_str())
583                    .map(|s| !s.is_empty())
584                    .unwrap_or(false);
585                has_token || has_refresh
586            })
587            .unwrap_or(false),
588        Err(_) => false,
589    }
590}
591
592async fn ensure_provider_auth_dir(req: EnsureProviderAuthDirReq) -> Result<EnsureProviderAuthDirResult, String> {
593    let provider = crate::backend::providers::get_provider(&req.provider_id)
594        .ok_or_else(|| format!("provider.ensureauthdir: unknown provider {:?}", req.provider_id))?;
595    let path = crate::backend::providers::default_auth_dir(provider)?;
596    crate::backend::providers::prepare_provider_auth_dir(provider, &path)
597        .map_err(|e| format!("provider.ensureauthdir: failed to prepare {path}: {e}"))?;
598    Ok(EnsureProviderAuthDirResult { path })
599}
600
601async fn run_cli_login(cmd: CommandRunCliLoginData) -> Result<RunCliLoginResult, String> {
602    tracing::info!(cli = %cmd.cli_path, args = ?cmd.login_args, "RunCliLogin");
603
604    // Dead path: the active login flow is the CEF host IPC
605    // `run_cli_login`, which owns the child's lifecycle (supersede-kill
606    // + timeout reaper). This srv-side variant previously spawned a
607    // DETACHED, unkillable `auth login` child here — a process leak if
608    // ever invoked. It has no live caller; do NOT spawn.
609    Ok(RunCliLoginResult { auth_url: None, raw_output: String::new() })
610}
611
612async fn toolchain_env() -> Result<ToolchainEnvResult, String> {
613    Ok(ToolchainEnvResult {
614        path: std::env::var("PATH").unwrap_or_default(),
615        path_source: std::env::var("AGENTMUX_PATH_SOURCE")
616            .unwrap_or_else(|_| "inherited".to_string()),
617        os: std::env::consts::OS.to_string(),
618        arch: std::env::consts::ARCH.to_string(),
619    })
620}
621
622async fn toolchain_prune(
623    req: Option<ToolchainPruneReq>,
624    mstore: Arc<crate::backend::storage::store::Store>,
625) -> Result<ToolchainPruneResult, String> {
626    let dry_run = req.as_ref().and_then(|r| r.dry_run).unwrap_or(true);
627    let only = req.and_then(|r| r.only);
628    let paths = agentmux_common::DataPaths::from_env()
629        .ok_or_else(|| "DataPaths::from_env() failed".to_string())?;
630    let live = super::uninstall_handlers::live_block_commands(&mstore).map_err(|e| format!("toolchain.prune: {e}"))?;
631    let max_idle = crate::backend::cli_prune::DEFAULT_MAX_IDLE;
632    let now = std::time::SystemTime::now();
633    let run = tokio::task::spawn_blocking(move || {
634        crate::backend::cli_prune::run(&paths, &live, dry_run, only.as_deref(), max_idle, now)
635    })
636    .await
637    .map_err(|e| format!("toolchain.prune: {e}"))?;
638    Ok(prune_result(run, dry_run, max_idle))
639}
640
641async fn widget_health(data: serde_json::Value) -> Result<WidgetHealthResult, String> {
642    let port_raw = data.get("port").and_then(|v| v.as_u64()).unwrap_or(0);
643    if port_raw == 0 || port_raw > 65535 {
644        return Ok(WidgetHealthResult { healthy: false, status_code: None });
645    }
646    let port = port_raw as u16;
647    let path = data
648        .get("health_check_path")
649        .and_then(|v| v.as_str())
650        .unwrap_or("/")
651        .to_string();
652    let body_contains = data
653        .get("health_check_body_contains")
654        .and_then(|v| v.as_str())
655        .map(|s| s.to_string());
656    let url = format!("http://127.0.0.1:{}{}", port, path);
657    let client = crate::http_client::builder()
658        .timeout(std::time::Duration::from_secs(3))
659        .build()
660        .map_err(|e| e.to_string())?;
661    match client.get(&url).send().await {
662        Ok(resp) => {
663            let status = resp.status().as_u16();
664            let ok_status = resp.status().is_success();
665            if !ok_status {
666                return Ok(WidgetHealthResult {
667                    healthy: false,
668                    status_code: Some(status),
669                });
670            }
671            // Optionally verify response body for service identity.
672            let healthy = if let Some(needle) = body_contains {
673                let body = resp.text().await.unwrap_or_default();
674                body.contains(&needle)
675            } else {
676                true
677            };
678            Ok(WidgetHealthResult { healthy, status_code: Some(status) })
679        }
680        Err(_) => Ok(WidgetHealthResult { healthy: false, status_code: None }),
681    }
682}
683
684fn widget_api_rejection(why: &str) -> WidgetApiResult {
685    WidgetApiResult {
686        ok: false,
687        status_code: None,
688        body: None,
689        error: Some(why.to_string()),
690    }
691}
692
693async fn widget_api(data: serde_json::Value) -> Result<WidgetApiResult, String> {
694    let reject = widget_api_rejection;
695    let port_raw = data.get("port").and_then(|v| v.as_u64()).unwrap_or(0);
696    if port_raw == 0 || port_raw > 65535 {
697        return Ok(reject("invalid port"));
698    }
699    let port = port_raw as u16;
700    let path = data.get("path").and_then(|v| v.as_str()).unwrap_or("/").to_string();
701    // Reject paths that could escape localhost: must start with '/',
702    // no '@' (user-info injection: 127.0.0.1@evil.com), no backslash,
703    // no protocol-relative '//' prefix.
704    if !path.starts_with('/') || path.contains('@') || path.contains('\\') || path.starts_with("//") {
705        return Ok(reject("invalid path"));
706    }
707    let method = data
708        .get("method")
709        .and_then(|v| v.as_str())
710        .unwrap_or("GET")
711        .to_uppercase();
712    let body_str = data.get("body").and_then(|v| v.as_str()).map(|s| s.to_string());
713    let headers_obj = data.get("headers").and_then(|v| v.as_object()).cloned();
714
715    let url = format!("http://127.0.0.1:{}{}", port, path);
716    let client = crate::http_client::builder()
717        .timeout(std::time::Duration::from_secs(30))
718        .redirect(reqwest::redirect::Policy::none())
719        .build()
720        .map_err(|e| e.to_string())?;
721
722    let mut req = match method.as_str() {
723        "POST" => client.post(&url),
724        "PUT" => client.put(&url),
725        "DELETE" => client.delete(&url),
726        "PATCH" => client.patch(&url),
727        _ => client.get(&url),
728    };
729
730    if let Some(headers) = headers_obj {
731        for (k, v) in &headers {
732            if let Some(vs) = v.as_str() {
733                if let (Ok(hn), Ok(hv)) = (
734                    reqwest::header::HeaderName::from_bytes(k.as_bytes()),
735                    reqwest::header::HeaderValue::from_str(vs),
736                ) {
737                    req = req.header(hn, hv);
738                }
739            }
740        }
741    }
742
743    if let Some(body) = body_str {
744        req = req
745            .header(reqwest::header::CONTENT_TYPE, "application/json")
746            .body(body);
747    }
748
749    match req.send().await {
750        Ok(resp) => {
751            let status = resp.status().as_u16();
752            let body = resp.text().await.unwrap_or_default();
753            Ok(WidgetApiResult {
754                ok: true,
755                status_code: Some(status),
756                body: Some(body),
757                error: None,
758            })
759        }
760        Err(e) => Ok(reject(&e.to_string())),
761    }
762}
763
764async fn toolchain_versions(
765    req: ToolchainVersionsReq,
766) -> Result<std::collections::HashMap<String, Option<String>>, String> {
767    let packages = req.packages;
768
769    let client = crate::http_client::builder()
770        .timeout(std::time::Duration::from_secs(5))
771        .user_agent("agentmux/toolchain-versions")
772        .build()
773        .map_err(|e| e.to_string())?;
774
775    let futs: Vec<_> = packages.into_iter().map(|pkg| {
776        let c = client.clone();
777        async move {
778            let url = format!("https://registry.npmjs.org/{}/latest", pkg.package);
779            let version = match c.get(&url).send().await {
780                Ok(resp) if resp.status().is_success() => {
781                    resp.json::<serde_json::Value>().await.ok()
782                        .and_then(|v| v.get("version").and_then(|s| s.as_str()).map(|s| s.to_string()))
783                }
784                _ => None,
785            };
786            (pkg.id, version)
787        }
788    }).collect();
789
790    let results = futures_util::future::join_all(futs).await;
791    // A map keyed by the caller's own `id`s, so the response type
792    // is the map itself rather than a named struct -- there is no
793    // fixed set of fields to name.
794    let mut out = std::collections::HashMap::new();
795    for (id, version) in results {
796        out.insert(id, version);
797    }
798    Ok(out)
799}
800
801pub(crate) use crate::backend::pane_env::make_cli_cmd;
802
803/// `pi --list-models` exits 0 either way; it is signed in when it lists
804/// models rather than "No models available".
805fn pi_lists_models(success: bool, stdout: &str, stderr: &str) -> bool {
806    success && !stdout.contains("No models available") && !stderr.contains("No models available")
807}
808
809/// Run the provider auth-check CLI against `auth_env` and parse the verdict.
810/// Returns `(authenticated, email, auth_method, raw_output)`. Extracted so the
811/// stale-credential self-heal can re-run the exact same check after refreshing.
812async fn run_auth_check(
813    cli_path: &str,
814    auth_check_args: &[String],
815    auth_env: &std::collections::HashMap<String, String>,
816) -> Result<(bool, Option<String>, Option<String>, String), String> {
817    // No check command must never read as signed in: a bare CLI with null
818    // stdin often just exits 0 (pi-acp does).
819    if auth_check_args.is_empty() {
820        // A CLI with no status command (Grok Build, Muse Code) is asked through its login file.
821        return match crate::identity::resolver::cli_file_signed_in(cli_path, auth_env) {
822            Some(signed_in) => Ok((signed_in, None, Some("credential file".to_string()), String::new())),
823            None => Err("this CLI has no sign-in check".to_string()),
824        };
825    }
826    // pi-acp has no status command of its own; the pi beside it does:
827    // `pi --list-models` prints "No models available" until a provider is
828    // set up (SPEC_PI_HARNESS_VIA_PI_ACP_2026_10_06.md).
829    let pi = crate::backend::providers::pi_beside_pi_acp(cli_path);
830    // pi-acp itself exits 0 on any flag, so without its pi there is nothing
831    // that can answer.
832    if pi.is_none() && crate::backend::providers::is_pi_acp(cli_path) {
833        return Err("pi is not installed beside pi-acp".to_string());
834    }
835    let program = pi.as_deref().unwrap_or(cli_path);
836    let output = tokio::time::timeout(std::time::Duration::from_secs(10), {
837        let mut check_cmd = make_cli_cmd(program);
838        // An auth check is the provider CLI acting as a plain third-party
839        // binary, not as one of our agents — no endpoint, no credential.
840        // (ReAgent P0, round 5, on #3326.)
841        crate::backend::pane_env::sanitize_external_command(&mut check_cmd);
842        check_cmd.args(auth_check_args);
843        for (k, v) in auth_env {
844            check_cmd.env(k, v);
845        }
846        // Null stdin: prevents the CLI from blocking on interactive first-run
847        // prompts (onboarding, theme selection) that only appear on a TTY.
848        check_cmd.stdin(std::process::Stdio::null());
849        check_cmd.output()
850    })
851    .await
852    .map_err(|_| "auth check timed out (10s)".to_string())?
853    .map_err(|e| format!("failed to run auth check: {e}"))?;
854
855    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
856    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
857
858    let mut email = None;
859    let mut auth_method = None;
860    let authenticated = if let Ok(json) = serde_json::from_str::<serde_json::Value>(&stdout) {
861        // Claude outputs `emailAddress`; other CLIs use `email`. Check both.
862        email = json
863            .get("emailAddress")
864            .or_else(|| json.get("email"))
865            .and_then(|v| v.as_str())
866            .map(|s| s.to_string());
867        auth_method = json
868            .get("authMethod")
869            .and_then(|v| v.as_str())
870            .map(|s| s.to_string());
871        json.get("loggedIn").and_then(|v| v.as_bool()).unwrap_or(false)
872    } else if pi.is_some() {
873        pi_lists_models(output.status.success(), &stdout, &stderr)
874    } else {
875        output.status.success()
876    };
877    let raw_output = if !stdout.is_empty() { stdout } else { stderr };
878    Ok((authenticated, email, auth_method, raw_output))
879}
880
881// REMOVED 2026-08-31 (Codex P1 on PR #2878): `claude_access_token`,
882// `refresh_claude_dir_from_global_if_stale`, and `refresh_dir_from_global` —
883// the machinery behind the auth check's "self-heal from the user's global
884// ~/.claude" step, together with its `selfheal_tests` module.
885//
886// Deleted rather than left unused on purpose: a helper whose entire job is
887// copying the operator's personal credential into an isolated dir is exactly
888// the thing that gets quietly rewired back in later. There is now nothing to
889// call. See `docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md`
890// (#5) for the full reasoning.
891//
892// The real condition it recovered from (the "Pozl 401" — a global re-login
893// rotating the access token and invalidating the isolated copy's refresh
894// token) now surfaces honestly as a failed validation plus an actionable auth
895// card, and is fixed by logging in for THIS channel.
896
897/// Where a CLI found by [`locate_provider_cli`] came from.
898#[derive(Debug, Clone, Copy, PartialEq, Eq)]
899pub(crate) enum CliSource {
900    /// AgentMux's own install, under its shared or legacy CLI dir.
901    LocalInstall,
902    /// The user's own install: on PATH or in its installer's folder.
903    SystemPath,
904}
905
906impl CliSource {
907    /// The wire value, as `resolvecli` and `install.check` report it.
908    pub(crate) fn as_str(self) -> &'static str {
909        match self {
910            CliSource::LocalInstall => "local_install",
911            CliSource::SystemPath => "system_path",
912        }
913    }
914}
915
916/// A provider CLI that [`locate_provider_cli`] found.
917#[derive(Debug, Clone, PartialEq, Eq)]
918pub(crate) struct LocatedCli {
919    pub path: String,
920    pub source: CliSource,
921}
922
923/// `resolvecli` for a provider that is a release download (Grok, Muse), not an npm
924/// package: the pinned file, its hash checked, unpacked under the install lock
925/// and marked complete (`backend::cli_download`).
926async fn resolve_by_download(
927    notices: &CliNotices,
928    broker: &Arc<crate::backend::mps::Broker>,
929    paths: &agentmux_common::DataPaths,
930    cmd: &CommandResolveCliData,
931    provider_id: &str,
932    pinned_version: &str,
933) -> Result<ResolveCliResult, String> {
934    use crate::backend::cli_install::InstallOutcome;
935    use crate::backend::cli_notice::InstallState;
936    let install_id = format!("{provider_id}-{pinned_version}-{}", agentmux_common::time::now_ms());
937    let started = std::time::Instant::now();
938    notices.install(&install_id, pinned_version, InstallState::Installing, None, None);
939    let (block_id, broker) = (cmd.block_id.clone(), broker.clone());
940    let on_line = move |_: &'static str, line: &str| {
941        tracing::info!(line = %line, "download output");
942        if !block_id.is_empty() {
943            crate::backend::mps::publish_install_progress(&broker, &block_id, line);
944        }
945    };
946    let stop = std::sync::atomic::AtomicBool::new(false);
947    let outcome = crate::backend::cli_download::install_managed_cli(paths, provider_id, &on_line, &stop).await;
948    match &outcome {
949        Ok(_) => notices.install(&install_id, pinned_version, InstallState::Installed, Some(started.elapsed().as_secs_f64()), None),
950        Err(e) => notices.install(&install_id, pinned_version, InstallState::Failed, None, Some(&e.to_string())),
951    }
952    let (bin, source) = match outcome.map_err(|e| e.to_string())? {
953        InstallOutcome::Installed(bin) => (bin, "installed"),
954        InstallOutcome::AlreadyInstalled(bin) => (bin, "local_install"),
955    };
956    let bin = bin.to_string_lossy().to_string();
957    let version = get_cli_version(&bin).await;
958    tracing::info!(path = %bin, version = %version, source, "CLI installed (download)");
959    notices.observe_version(&version);
960    Ok(ResolveCliResult { cli_path: bin, version, source: source.to_string() })
961}
962
963/// The CLI a launch of `provider_id` would run, without installing anything:
964/// AgentMux's own install, for every provider. The person's own copy on PATH
965/// or in its installer's folder only when they listed the provider in
966/// `cli:usepath` ("Use the CLI on my PATH"), and then it comes first. Never
967/// otherwise, so a copy on PATH can't make a missing install read as "found".
968/// The one lookup behind `install.check`, `resolvecli`, the launch
969/// (`agent.open`) and the ambient calls, so the agent picker and the Toolchain
970/// pane can't disagree (SPEC_AGENT_PICKER_INLINE_CREATE_2026_10_18.md §1).
971/// `None` for an unknown provider.
972pub(crate) async fn locate_provider_cli(provider_id: &str) -> Option<LocatedCli> {
973    locate_provider_cli_with(provider_id, crate::backend::providers::uses_path_cli(provider_id)).await
974}
975
976/// [`locate_provider_cli`]'s path, for the ambient calls: registered once at startup (`ambient::cli_locator`).
977pub(crate) fn locate_for_ambient(provider_id: &str) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<String>> + Send + '_>> {
978    Box::pin(async move { locate_provider_cli(provider_id).await.map(|l| l.path) })
979}
980
981async fn locate_provider_cli_with(provider_id: &str, use_path: bool) -> Option<LocatedCli> {
982    let provider = crate::backend::providers::get_provider(provider_id)?;
983    // A custom harness the person installed themselves is registered under the absolute path its command has on PATH
984    // (`providers_custom::launch_command`); AgentMux installs nothing for it, so that file is the CLI.
985    if provider.tier == crate::backend::providers::Tier::Custom
986        && std::path::Path::new(provider.cli_command).is_absolute()
987        && std::path::Path::new(provider.cli_command).is_file()
988    {
989        return Some(LocatedCli { path: provider.cli_command.to_string(), source: CliSource::SystemPath });
990    }
991    if use_path {
992        if let Some(path) = resolve_provider_cli_on_path(provider.id, provider.cli_command).await {
993            return Some(LocatedCli { path, source: CliSource::SystemPath });
994        }
995    }
996    let paths = agentmux_common::DataPaths::from_env()?;
997    crate::backend::cli_install::find_installed_for_provider(&paths, provider.id)
998        .map(|bin| LocatedCli { path: bin.to_string_lossy().into_owned(), source: CliSource::LocalInstall })
999}
1000
1001/// The person's own copy of a CLI: on PATH, else in the folder its own installer
1002/// uses ([`crate::backend::providers::known_install_paths`]), which may not
1003/// be on this process's PATH until AgentMux restarts.
1004///
1005/// A provider that takes its prompt on the command line
1006/// (`ProviderConfig::prompt_arg_flag`) must run as the real executable: a
1007/// `.cmd`/`.bat` wrapper is re-parsed by `cmd.exe`, where `&`, `|` or `%` in
1008/// a prompt could turn into a command. For those the installer's own
1009/// executable comes first, and a script wrapper on PATH is never used.
1010pub(crate) async fn resolve_provider_cli_on_path(provider_id: &str, cli_command: &str) -> Option<String> {
1011    let known = || {
1012        crate::backend::providers::known_install_paths(provider_id)
1013            .into_iter()
1014            .find(|p| p.is_file())
1015            .map(|p| p.to_string_lossy().into_owned())
1016    };
1017    // A prompt-in-argv CLI, a terminal-tier one (it runs as the pane's own
1018    // process) and Muse's MSP host (its launcher updates itself and wraps the
1019    // stdio) can't be a `.cmd` wrapper that isn't an npm shim.
1020    let provider = crate::backend::providers::get_provider(provider_id);
1021    let prompt_in_argv = provider.and_then(|p| p.prompt_arg_flag()).is_some();
1022    let terminal = provider.is_some_and(|p| {
1023        matches!(p.controller_type, crate::backend::providers::ControllerType::Terminal | crate::backend::providers::ControllerType::Msp)
1024    });
1025    if prompt_in_argv || terminal {
1026        if let Some(path) = known() {
1027            return Some(path);
1028        }
1029        // Every match, not just the first: a `.cmd` shim ahead of the real
1030        // executable on PATH must not hide it.
1031        return resolve_cli_candidates_on_path(cli_command)
1032            .await
1033            .into_iter()
1034            .find(|path| !is_script_wrapper(path));
1035    }
1036    if let Some(path) = resolve_cli_on_path(cli_command).await {
1037        return Some(path);
1038    }
1039    known()
1040}
1041
1042/// Whether `path` is a Windows batch script (`.cmd`/`.bat`), which runs
1043/// through `cmd.exe` and re-parses its arguments.
1044fn is_script_wrapper(path: &str) -> bool {
1045    let lower = path.to_ascii_lowercase();
1046    lower.ends_with(".cmd") || lower.ends_with(".bat")
1047}
1048
1049/// Resolve a CLI command on the system PATH.
1050///
1051/// Uses `where` on Windows and `which` on Unix. Returns the absolute path
1052/// if the command is found and exists, otherwise `None`.
1053///
1054/// On Windows we pass the bare command name (no `.cmd` suffix) so that
1055/// `where` resolves the correct extension via PATHEXT. This correctly finds
1056/// `docker.exe`, `git.exe`, `node.exe` AND `npm.cmd` — previously the
1057/// hard-coded `.cmd` suffix caused all `.exe`-based tools (docker, git,
1058/// node) to report as not installed even when present on PATH.
1059///
1060/// `where` can return multiple lines (e.g. Node.js ships both an extensionless
1061/// `npm` Unix shell script and `npm.cmd` on Windows). We filter to the first
1062/// line whose extension `make_cli_cmd` can actually spawn (.exe / .cmd / .bat).
1063/// Taking the raw first line would yield the extensionless entry, which
1064/// `Command::new` cannot run on Windows without a shell.
1065async fn resolve_cli_on_path(cli_command: &str) -> Option<String> {
1066    resolve_cli_candidates_on_path(cli_command).await.into_iter().next()
1067}
1068
1069/// Every spawnable match for `cli_command` on PATH that exists, in PATH order.
1070async fn resolve_cli_candidates_on_path(cli_command: &str) -> Vec<String> {
1071    let which_result = if cfg!(windows) {
1072        let mut probe = tokio::process::Command::new("where");
1073        probe.arg(cli_command);
1074        #[cfg(windows)]
1075        {
1076            probe.no_window();
1077        }
1078        probe.output().await
1079    } else {
1080        tokio::process::Command::new("which").arg(cli_command).output().await
1081    };
1082    match which_result {
1083        Ok(out) if out.status.success() => spawnable_candidates(&String::from_utf8_lossy(&out.stdout), cfg!(windows))
1084            .into_iter()
1085            .filter(|p| std::path::Path::new(p).exists())
1086            .collect(),
1087        _ => Vec::new(),
1088    }
1089}
1090
1091/// The lines of `where`/`which` output a spawn can use. On Windows that is
1092/// the ones `make_cli_cmd` can run (.exe / .cmd / .bat), skipping e.g. the
1093/// extensionless `npm` shell script; elsewhere `which` prints one path.
1094fn spawnable_candidates(stdout: &str, windows: bool) -> Vec<String> {
1095    let lines = stdout.lines().map(str::trim).filter(|l| !l.is_empty());
1096    if windows {
1097        lines
1098            .filter(|l| {
1099                let lo = l.to_lowercase();
1100                lo.ends_with(".exe") || lo.ends_with(".cmd") || lo.ends_with(".bat")
1101            })
1102            .map(str::to_string)
1103            .collect()
1104    } else {
1105        lines.take(1).map(str::to_string).collect()
1106    }
1107}
1108
1109/// The CLI notices one `ResolveCli` call can put in its pane
1110/// (`backend::cli_notice`, SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md
1111/// §6.3). A probe with no `block_id` (the picker, the Toolchain pane) puts
1112/// nothing anywhere.
1113struct CliNotices {
1114    broker: std::sync::Arc<crate::backend::mps::Broker>,
1115    filestore: std::sync::Arc<crate::backend::storage::filestore::FileStore>,
1116    mstore: std::sync::Arc<crate::backend::storage::store::Store>,
1117    /// The pane being launched (`notice_block_id`, else `block_id`).
1118    block_id: String,
1119    /// The agent being launched, when the caller says; else the pane's
1120    /// `agentId` meta.
1121    agent_id: Option<String>,
1122    provider: String,
1123}
1124
1125/// The pane a resolve's notices go to: the launch target when the caller
1126/// names one (a quick fork resolves from its source pane), else `block_id`.
1127fn notice_block_id(cmd: &CommandResolveCliData) -> String {
1128    cmd.notice_block_id
1129        .as_deref()
1130        .map(str::trim)
1131        .filter(|b| !b.is_empty())
1132        .unwrap_or(&cmd.block_id)
1133        .to_string()
1134}
1135
1136impl CliNotices {
1137    fn install(
1138        &self,
1139        install_id: &str,
1140        version: &str,
1141        state: crate::backend::cli_notice::InstallState,
1142        seconds: Option<f64>,
1143        error: Option<&str>,
1144    ) {
1145        if self.block_id.is_empty() {
1146            return;
1147        }
1148        let frame = crate::backend::cli_notice::install_frame(install_id, &self.provider, version, state, seconds, error);
1149        crate::backend::cli_notice::append_to_pane(&self.broker, &self.filestore, &self.mstore, &self.block_id, &frame);
1150    }
1151
1152    /// Record the version this pane's agent is about to run. Claude reports
1153    /// the version it actually runs in its own `system/init` frame, which
1154    /// covers every spawn path (`persistent/stdout_reader.rs`), so it is observed
1155    /// there and not here.
1156    fn observe_version(&self, raw_version: &str) {
1157        if self.block_id.is_empty() || self.provider == "claude" {
1158            return;
1159        }
1160        let Some(version) = crate::backend::cli_notice::version_token(raw_version) else { return };
1161        let (broker, filestore, mstore) = (self.broker.clone(), self.filestore.clone(), self.mstore.clone());
1162        let (block_id, provider, agent_id) = (self.block_id.clone(), self.provider.clone(), self.agent_id.clone());
1163        tokio::task::spawn_blocking(move || {
1164            crate::backend::cli_notice::observe_and_notify(
1165                &broker,
1166                &filestore,
1167                &mstore,
1168                &block_id,
1169                agent_id.as_deref(),
1170                &provider,
1171                &version,
1172            );
1173        });
1174    }
1175}
1176
1177/// The version `cli_path` reports, asked of the CLI once per file (`cli_version.rs`): it runs on
1178/// every agent open, and each probe is a node process.
1179pub(crate) async fn get_cli_version(cli_path: &str) -> String {
1180    super::cli_version::cached_version(cli_path, || probe_cli_version(cli_path)).await
1181}
1182
1183/// Run `<cli> --version`; `None` if it timed out or failed.
1184async fn probe_cli_version(cli_path: &str) -> Option<String> {
1185    let result = tokio::time::timeout(
1186        std::time::Duration::from_secs(5),
1187        {
1188            let mut c = make_cli_cmd(cli_path);
1189            // Version probe — same reasoning as the auth check above.
1190            crate::backend::pane_env::sanitize_external_command(&mut c);
1191            c.arg("--version").stdin(std::process::Stdio::null());
1192            c.output()
1193        },
1194    ).await;
1195    match result {
1196        Ok(Ok(output)) if output.status.success() => {
1197            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
1198        }
1199        Ok(_) => None,
1200        Err(_) => {
1201            tracing::warn!(cli_path = %cli_path, "get_cli_version timed out after 5s");
1202            None
1203        }
1204    }
1205}
1206
1207/// The wire form of a prune [`crate::backend::cli_prune::Run`].
1208fn prune_result(
1209    run: crate::backend::cli_prune::Run,
1210    dry_run: bool,
1211    max_idle: std::time::Duration,
1212) -> ToolchainPruneResult {
1213    use crate::backend::cli_prune::Candidate;
1214    let item = |c: &Candidate| ToolchainPruneItem {
1215        dir: c.dir.to_string_lossy().into_owned(),
1216        provider: c.provider.clone(),
1217        version: c.version.clone(),
1218        legacy: c.legacy,
1219        bytes: c.bytes,
1220        idle_days: c.idle.as_secs() / 86_400,
1221    };
1222    let removed_dirs: std::collections::HashSet<&std::path::PathBuf> = run
1223        .report
1224        .iter()
1225        .flat_map(|r| r.removed.iter().map(|(d, _)| d))
1226        .collect();
1227    ToolchainPruneResult {
1228        dry_run,
1229        scan_ok: run.scan_ok,
1230        candidates: run.plan.prunable.iter().map(item).collect(),
1231        reclaimable_bytes: run.plan.reclaimable_bytes(),
1232        removed: run
1233            .plan
1234            .prunable
1235            .iter()
1236            .filter(|c| removed_dirs.contains(&c.dir))
1237            .map(item)
1238            .collect(),
1239        skipped: run
1240            .report
1241            .iter()
1242            .flat_map(|r| r.skipped.iter())
1243            .map(|(d, why)| ToolchainPruneSkip { dir: d.to_string_lossy().into_owned(), reason: why.clone() })
1244            .collect(),
1245        kept: run.plan.kept.len() as u32,
1246        max_idle_days: (max_idle.as_secs() / 86_400) as u32,
1247    }
1248}
1249
1250#[cfg(test)]
1251mod tests;