Skip to main content

scv_tools/delegate/
adapters.rs

1//! The native agent CLIs SCV can delegate to, one descriptor each.
2//!
3//! A descriptor is the whole integration: the default command line, where the
4//! CLI keeps its state inside SCV's private agent home, which inherited
5//! variables it must never see, and how `scv agents login|status|logout`
6//! handle it. Adding an agent means adding one entry to [`ADAPTERS`].
7
8use std::{
9    ffi::OsStr,
10    path::{Path, PathBuf},
11};
12
13/// How SCV signs an agent in, inside its private agent home.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Login {
16    /// Run the CLI's own sign-in command.
17    Command(&'static [&'static str]),
18    /// Open the CLI interactively; `hint` names its in-app sign-in command.
19    Interactive {
20        args: &'static [&'static str],
21        hint: &'static str,
22    },
23    /// Prompt for an API key and store it in the CLI's own credential file.
24    ApiKey(KeyStore),
25    /// Copy SCV's own configuration: `scv agents import <name>`.
26    Import,
27}
28
29/// How SCV reports whether an agent is signed in.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Status {
32    /// The CLI prints its own status and exits non-zero when signed out.
33    Command(&'static [&'static str]),
34    /// SCV inspects the CLI's credential file without printing secrets.
35    Stored(KeyStore),
36}
37
38/// What a CLI prints on stdout when SCV runs it, and so how SCV reads its
39/// reply, usage, and failure out of it.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum OutputFormat {
42    /// Plain text: stdout is the reply.
43    Text,
44    /// Claude Code `--output-format stream-json --verbose`: one JSON event per
45    /// line, ending with a `result` event.
46    ClaudeStreamJson,
47    /// `codex exec --json`: JSON events per line; SCV also passes `-o <file>`
48    /// so the final message survives an unparsable stream.
49    CodexJsonl,
50    /// pi `--mode json`: JSON events per line; the reply is the last
51    /// assistant `message_end`.
52    PiJson,
53}
54
55impl OutputFormat {
56    /// Arguments that select this format, placed after the fixed arguments.
57    pub(crate) fn args(self) -> &'static [&'static str] {
58        match self {
59            Self::Text => &[],
60            Self::ClaudeStreamJson => &["--output-format", "stream-json", "--verbose"],
61            Self::CodexJsonl => &["--json"],
62            Self::PiJson => &["--mode", "json"],
63        }
64    }
65}
66
67/// How SCV talks to an agent.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Transport {
70    /// One CLI process per turn: the prompt is an argument and the reply is
71    /// read from its output ([`OutputFormat`]), continued through [`Resume`].
72    Process,
73    /// A long-running `scv server --stdio` per conversation, driven over the
74    /// SCV protocol: its tool approvals are relayed to the calling session
75    /// and its events become progress.
76    ScvProtocol,
77}
78
79/// How to start an agent's Agent Client Protocol (ACP) server: a long-running
80/// process speaking JSON-RPC 2.0 over stdio, one conversation per ACP session.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct AcpLaunch {
83    /// The ACP server executable: the agent itself or its official adapter.
84    pub command: &'static str,
85    /// Its arguments; a `{full}` entry is replaced by `full_args` for
86    /// `permissions = "full"` and dropped otherwise.
87    pub(crate) args: &'static [&'static str],
88    pub(crate) full_args: &'static [&'static str],
89    /// The ACP session mode selected for `permissions = "full"`, for agents
90    /// whose permission level is a session mode.
91    pub full_mode: Option<&'static str>,
92    /// Environment for the ACP server under `permissions = "full"`, for
93    /// settings the server reads only from its environment.
94    pub full_environment: &'static [(&'static str, &'static str)],
95    /// The server takes `model` and `effort` as session config options even
96    /// though the CLI run once per turn takes neither as an argument, as
97    /// DeepSeek Harness's does. Other agents take them over ACP where their
98    /// CLI takes them as arguments.
99    pub session_options: bool,
100}
101
102/// Expand `launch.args` for the configured permission level.
103pub fn acp_args(launch: &AcpLaunch, full: bool) -> Vec<String> {
104    let mut args = Vec::with_capacity(launch.args.len() + launch.full_args.len());
105    for arg in launch.args {
106        if *arg == "{full}" {
107            if full {
108                args.extend(launch.full_args.iter().map(|arg| (*arg).to_owned()));
109            }
110        } else {
111            args.push((*arg).to_owned());
112        }
113    }
114    args
115}
116
117/// How a CLI continues an earlier conversation. `{session}` in any argument
118/// is replaced by the conversation's vendor session ID.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum Resume {
121    /// Every call starts a fresh conversation.
122    Unsupported,
123    Supported {
124        /// Starts a conversation under an ID SCV chooses. Empty when the CLI
125        /// picks its own ID and reports it in its output (Codex).
126        start: &'static [&'static str],
127        /// Placed right after the fixed arguments when continuing: a
128        /// subcommand such as Codex's `exec resume`.
129        subcommand: &'static [&'static str],
130        /// Options that continue the conversation.
131        options: &'static [&'static str],
132        /// Placed immediately before the prompt when continuing, for a CLI
133        /// that takes the session ID as a positional argument.
134        positional: &'static [&'static str],
135    },
136}
137
138impl Resume {
139    pub(crate) fn is_supported(self) -> bool {
140        matches!(self, Self::Supported { .. })
141    }
142
143    /// Whether SCV chooses the vendor session ID when a conversation starts.
144    pub(crate) fn assigns_id(self) -> bool {
145        matches!(self, Self::Supported { start, .. } if !start.is_empty())
146    }
147}
148
149/// Where a CLI keeps conversation transcripts inside its agent home:
150/// files with `extension` anywhere below `dir`, named after their session ID.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub struct ConversationFiles {
153    pub(crate) dir: &'static str,
154    pub(crate) extension: &'static str,
155}
156
157/// How SCV condenses a CLI's own status output. The raw output names the
158/// account (an email) or part of a key, so it is never printed.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum StatusSummary {
161    /// `claude auth status` JSON: `loggedIn`, `authMethod`, `subscriptionType`.
162    ClaudeJson,
163    /// `codex login status` text: "Logged in using an API key" or "ChatGPT".
164    CodexText,
165    /// The exit status alone.
166    ExitStatus,
167}
168
169/// How SCV signs an agent out.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum Logout {
172    Command(&'static [&'static str]),
173    /// SCV removes the credentials it can see in the CLI's own files.
174    Stored(KeyStore),
175}
176
177/// A CLI's native credential file, relative to the agent home.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum KeyStore {
180    /// Grok: sign-ins from `grok login` in `auth` (a JSON object of entries),
181    /// or an API key in the `config` profile of its default model.
182    Grok {
183        auth: &'static str,
184        config: &'static str,
185    },
186    /// DeepSeek Harness `.credentials.yaml`, holding `refs.<variable>`.
187    DshRefs {
188        path: &'static str,
189        variable: &'static str,
190    },
191    /// pi's agent directory: `auth.json`, plus the SCV-configured
192    /// OpenAI-compatible endpoint in `models.json` and `settings.json`.
193    Pi { dir: &'static str },
194    /// A nested SCV's own `config.toml`, holding the provider copied from the
195    /// user's SCV by `scv agents import scv`.
196    Scv { config: &'static str },
197}
198
199#[derive(Debug, Clone, Copy)]
200pub struct AdapterDescriptor {
201    /// Short name: the `agent` tool's value for it and the home `agents/<name>`.
202    pub name: &'static str,
203    /// Product name for messages and the tool description.
204    pub product: &'static str,
205    /// What this harness offers, as one factual clause for the tool
206    /// description, so the model can choose between agents.
207    pub(crate) offers: &'static str,
208    pub command: &'static str,
209    pub args: &'static [&'static str],
210    /// Placed immediately before the prompt, for CLIs whose prompt is a flag
211    /// value (`grok -p <prompt>`).
212    pub prompt_args: &'static [&'static str],
213    pub model_args: &'static [&'static str],
214    pub effort_args: &'static [&'static str],
215    /// Describes the `model` argument for the calling model.
216    pub model_hint: &'static str,
217    /// Variables pointing the CLI's state into the agent home, as paths
218    /// relative to it (`""` is the home itself).
219    pub home_environment: &'static [(&'static str, &'static str)],
220    /// Fixed variables for every delegated run.
221    pub fixed_environment: &'static [(&'static str, &'static str)],
222    /// Credential, endpoint, and state-location variables no delegated agent
223    /// inherits. A trailing `*` matches a prefix.
224    pub(crate) removed_environment: &'static [&'static str],
225    /// Added after `args` when `[agents.<name>] permissions = "full"`: the
226    /// CLI's own switches that turn off its approval prompts and sandbox and
227    /// enable web search where the CLI gates it. Empty when the CLI has no
228    /// permission system of its own.
229    pub full_permission_args: &'static [&'static str],
230    /// Variables set for `permissions = "full"`, for CLIs configured that way.
231    pub full_permission_environment: &'static [(&'static str, &'static str)],
232    /// Per-user install directories searched before `PATH`, relative to the
233    /// user's home, as a login shell orders them. A user service's `PATH`
234    /// omits them, so without this the daemon would miss or pick a different
235    /// install than the user's shell.
236    pub(crate) search_dirs: &'static [&'static str],
237    pub login: Login,
238    pub status: Status,
239    /// How a [`Status::Command`] result is summarized.
240    pub status_summary: StatusSummary,
241    pub logout: Logout,
242    /// What the CLI prints when SCV delegates to it.
243    pub output: OutputFormat,
244    /// How SCV continues a conversation with it, when it can.
245    pub resume: Resume,
246    /// Transcripts `scv agents gc` may remove; `None` when unknown.
247    pub conversation_files: Option<ConversationFiles>,
248    /// Files in the agent home that hold its sign-in or keys, relative to it,
249    /// which `scv config show` reports without reading.
250    pub credential_files: &'static [&'static str],
251    /// How SCV talks to the agent.
252    pub transport: Transport,
253    /// Its ACP server, when it has a verified one. With `[agents.<name>]
254    /// transport = "auto"` SCV prefers it over [`Transport::Process`] once the
255    /// command is installed.
256    pub acp: Option<AcpLaunch>,
257}
258
259/// Directories every adapter searches before `PATH`, relative to the user's home.
260const USER_BIN_DIRS: &[&str] = &[".local/bin"];
261
262/// Removed from every agent regardless of adapter: SCV's own selectors and
263/// cloud keys that name no single agent. Any variable ending in `_API_KEY`
264/// is removed as well.
265const COMMON_REMOVED_ENVIRONMENT: &[&str] = &[
266    "SCV_CONFIG",
267    "SCV_MODEL",
268    "SCV_PROVIDER",
269    "SCV_BASE_URL",
270    "SCV_API_KEY_ENV",
271    "GEMINI_API_KEY",
272    "GOOGLE_API_KEY",
273    "AZURE_OPENAI_API_KEY",
274    "AZURE_OPENAI_ENDPOINT",
275];
276
277const PI_STORE: KeyStore = KeyStore::Pi { dir: ".pi/agent" };
278const SCV_STORE: KeyStore = KeyStore::Scv {
279    config: "config.toml",
280};
281const DSH_STORE: KeyStore = KeyStore::DshRefs {
282    path: ".dsh/.credentials.yaml",
283    variable: "DEEPSEEK_API_KEY",
284};
285
286pub const ADAPTERS: &[AdapterDescriptor] = &[
287    AdapterDescriptor {
288        name: "claude",
289        product: "Claude Code",
290        offers: "Anthropic's coding agent; it reads, edits, and runs code in a project and can search and fetch the web",
291        command: "claude",
292        args: &["-p"],
293        prompt_args: &[],
294        model_args: &["--model", "{model}"],
295        effort_args: &["--effort", "{effort}"],
296        model_hint: "Claude model alias or ID, such as sonnet or opus.",
297        home_environment: &[],
298        fixed_environment: &[],
299        removed_environment: &[
300            "ANTHROPIC_API_KEY",
301            "ANTHROPIC_BASE_URL",
302            "ANTHROPIC_AUTH_TOKEN",
303            "CLAUDE_CODE_OAUTH_TOKEN",
304            "CLAUDE_CONFIG_DIR",
305        ],
306        // Also allows WebSearch and WebFetch without prompting.
307        full_permission_args: &["--permission-mode", "bypassPermissions"],
308        full_permission_environment: &[],
309        search_dirs: &[],
310        login: Login::Command(&["auth", "login"]),
311        status: Status::Command(&["auth", "status"]),
312        status_summary: StatusSummary::ClaudeJson,
313        logout: Logout::Command(&["auth", "logout"]),
314        output: OutputFormat::ClaudeStreamJson,
315        // `--resume` in print mode keeps the original session ID.
316        resume: Resume::Supported {
317            start: &["--session-id", "{session}"],
318            subcommand: &[],
319            options: &["--resume", "{session}"],
320            positional: &[],
321        },
322        conversation_files: Some(ConversationFiles {
323            dir: ".claude/projects",
324            extension: "jsonl",
325        }),
326        credential_files: &[".claude/.credentials.json"],
327        transport: Transport::Process,
328        // The official adapter from the ACP organisation (npm
329        // @agentclientprotocol/claude-agent-acp), on the Claude Agent SDK.
330        acp: Some(AcpLaunch {
331            command: "claude-agent-acp",
332            args: &[],
333            full_args: &[],
334            full_mode: Some("bypassPermissions"),
335            full_environment: &[],
336            session_options: false,
337        }),
338    },
339    AdapterDescriptor {
340        name: "codex",
341        product: "Codex",
342        offers: "OpenAI's coding agent; it reads, edits, and runs code in a project, with live web search under full permissions",
343        command: "codex",
344        args: &["exec"],
345        prompt_args: &[],
346        model_args: &["-m", "{model}"],
347        effort_args: &["-c", "model_reasoning_effort=\"{effort}\""],
348        model_hint: "OpenAI model ID from the Codex configuration; not a Claude alias.",
349        home_environment: &[("CODEX_HOME", "")],
350        fixed_environment: &[],
351        removed_environment: &[
352            "OPENAI_API_KEY",
353            "OPENAI_BASE_URL",
354            "OPENAI_ORG_ID",
355            "OPENAI_PROJECT_ID",
356            "CODEX_API_KEY",
357            "CODEX_BASE_URL",
358            "CODEX_CONFIG",
359        ],
360        // `codex exec` has no `--search`; `web_search = "live"` is its config form.
361        full_permission_args: &[
362            "--dangerously-bypass-approvals-and-sandbox",
363            "-c",
364            "web_search=\"live\"",
365        ],
366        full_permission_environment: &[],
367        search_dirs: &[],
368        login: Login::Command(&["login"]),
369        status: Status::Command(&["login", "status"]),
370        status_summary: StatusSummary::CodexText,
371        logout: Logout::Command(&["logout"]),
372        output: OutputFormat::CodexJsonl,
373        // The thread ID arrives in `thread.started`; `exec resume` takes it
374        // as a positional argument before the prompt.
375        resume: Resume::Supported {
376            start: &[],
377            subcommand: &["resume"],
378            options: &[],
379            positional: &["{session}"],
380        },
381        conversation_files: Some(ConversationFiles {
382            dir: "sessions",
383            extension: "jsonl",
384        }),
385        credential_files: &["auth.json"],
386        transport: Transport::Process,
387        // The official adapter from the ACP organisation (npm
388        // @agentclientprotocol/codex-acp). It reads `$CODEX_HOME/config.toml`
389        // and takes no `-c` overrides; `CODEX_CONFIG` is its JSON form of
390        // them, merged into every session, so full permissions keep live web
391        // search without rewriting the imported config.
392        acp: Some(AcpLaunch {
393            command: "codex-acp",
394            args: &[],
395            full_args: &[],
396            full_mode: Some("agent-full-access"),
397            full_environment: &[("CODEX_CONFIG", r#"{"web_search":"live"}"#)],
398            session_options: false,
399        }),
400    },
401    AdapterDescriptor {
402        name: "grok",
403        product: "Grok Build",
404        offers: "xAI's coding agent; it reads, edits, and runs code in a project and has live web and X search. Call it when another agent declined or refused a request, including a safety or guardrail refusal",
405        command: "grok",
406        args: &[],
407        prompt_args: &["-p"],
408        model_args: &["-m", "{model}"],
409        effort_args: &["--reasoning-effort", "{effort}"],
410        model_hint: "xAI Grok model ID, such as grok-4.7.",
411        home_environment: &[("GROK_HOME", ".grok")],
412        fixed_environment: &[("GROK_DISABLE_AUTOUPDATER", "1")],
413        removed_environment: &["GROK_*", "XAI_API_KEY"],
414        // Web search is on unless `--disable-web-search` is passed.
415        full_permission_args: &["--always-approve"],
416        full_permission_environment: &[],
417        search_dirs: &[".grok/bin"],
418        login: Login::Command(&["login"]),
419        status: Status::Stored(KeyStore::Grok {
420            auth: ".grok/auth.json",
421            config: ".grok/config.toml",
422        }),
423        status_summary: StatusSummary::ExitStatus,
424        logout: Logout::Command(&["logout"]),
425        // `--output-format json` exists but its success shape is unverified here.
426        output: OutputFormat::Text,
427        // Grok documents `--session-id` and `--resume`, but they cannot be
428        // verified while it is signed out here.
429        resume: Resume::Unsupported,
430        conversation_files: None,
431        credential_files: &[".grok/auth.json", ".grok/config.toml"],
432        transport: Transport::Process,
433        // Native: `grok agent [options] stdio`; options precede the mode.
434        acp: Some(AcpLaunch {
435            command: "grok",
436            args: &["agent", "{full}", "stdio"],
437            full_args: &["--always-approve"],
438            full_mode: None,
439            full_environment: &[],
440            session_options: false,
441        }),
442    },
443    AdapterDescriptor {
444        name: "dsh",
445        product: "DeepSeek Harness",
446        offers: "a coding agent on DeepSeek models; it reads, edits, and runs code in a project",
447        command: "dsh",
448        args: &["--profile", "headless"],
449        prompt_args: &[],
450        model_args: &[],
451        effort_args: &[],
452        model_hint: "provider/model as its ACP server lists them, such as deepseek-official/deepseek-v4-pro.",
453        home_environment: &[("DSH_HOME", ".dsh")],
454        fixed_environment: &[],
455        removed_environment: &["DSH_*", "DEEPSEEK_API_KEY", "DEEPSEEK_BASE_URL"],
456        // Bypasses its file sandbox and sets its approval policy to `never`.
457        full_permission_args: &[],
458        full_permission_environment: &[("DSH_PERMISSION_MODE", "danger-full-access")],
459        search_dirs: &[],
460        login: Login::ApiKey(DSH_STORE),
461        status: Status::Stored(DSH_STORE),
462        status_summary: StatusSummary::ExitStatus,
463        logout: Logout::Stored(DSH_STORE),
464        output: OutputFormat::Text,
465        // Only its interactive profile documents `--resume`.
466        resume: Resume::Unsupported,
467        conversation_files: None,
468        credential_files: &[".dsh/.credentials.yaml"],
469        transport: Transport::Process,
470        // Native: the shipped `acp` profile. `permissions = "full"` is the
471        // `DSH_PERMISSION_MODE` variable above. Its sessions offer `model`
472        // (every configured provider's models, as `["provider","model"]`)
473        // and `reasoning_effort`, which the headless profile cannot take.
474        acp: Some(AcpLaunch {
475            command: "dsh",
476            args: &["--profile", "acp"],
477            full_args: &[],
478            full_mode: None,
479            full_environment: &[],
480            session_options: true,
481        }),
482    },
483    AdapterDescriptor {
484        name: "pi",
485        product: "pi",
486        offers: "a minimal coding agent (read, write, edit, bash) that can run on SCV's own model endpoint; it has no web search",
487        command: "pi",
488        args: &["-p"],
489        prompt_args: &[],
490        model_args: &["--model", "{model}"],
491        effort_args: &["--thinking", "{effort}"],
492        model_hint: "pi model pattern or provider/id; the SCV-configured endpoint is provider scv.",
493        home_environment: &[("PI_CODING_AGENT_DIR", ".pi/agent")],
494        fixed_environment: &[],
495        removed_environment: &["PI_*"],
496        // pi has no approval prompts or sandbox, and no built-in web search.
497        full_permission_args: &[],
498        full_permission_environment: &[],
499        search_dirs: &[],
500        login: Login::Interactive {
501            args: &[],
502            hint: "run /login and choose a provider, then /quit",
503        },
504        status: Status::Stored(PI_STORE),
505        status_summary: StatusSummary::ExitStatus,
506        logout: Logout::Stored(PI_STORE),
507        output: OutputFormat::PiJson,
508        // `--session-id` uses the exact project session, creating it if missing.
509        resume: Resume::Supported {
510            start: &["--session-id", "{session}"],
511            subcommand: &[],
512            options: &["--session-id", "{session}"],
513            positional: &[],
514        },
515        conversation_files: Some(ConversationFiles {
516            dir: ".pi/agent/sessions",
517            extension: "jsonl",
518        }),
519        credential_files: &[".pi/agent/auth.json", ".pi/agent/models.json"],
520        transport: Transport::Process,
521        // Only a community ACP adapter exists.
522        acp: None,
523    },
524    AdapterDescriptor {
525        name: "scv",
526        product: "SCV",
527        offers: "a nested SCV session with its own context and tools; suited to a self-contained sub-task kept out of this conversation's context, or work in another project",
528        command: "scv",
529        args: &["server", "--stdio"],
530        prompt_args: &[],
531        // A model is chosen per conversation through `session.start`.
532        model_args: &[],
533        effort_args: &[],
534        model_hint: "Model ID for the nested SCV's provider; applies to a new conversation only.",
535        // `SCV_HOME` already points at the agent home, where the nested
536        // SCV keeps its config, skills, and its own delegations.
537        home_environment: &[],
538        fixed_environment: &[],
539        removed_environment: &[],
540        // Its tool approvals are relayed to the calling session instead.
541        full_permission_args: &[],
542        full_permission_environment: &[],
543        // Where `cargo install` puts `scv`; a user service's PATH omits it.
544        search_dirs: &[".cargo/bin"],
545        login: Login::Import,
546        status: Status::Stored(SCV_STORE),
547        status_summary: StatusSummary::ExitStatus,
548        logout: Logout::Stored(SCV_STORE),
549        output: OutputFormat::Text,
550        resume: Resume::Unsupported,
551        conversation_files: None,
552        credential_files: &["config.toml"],
553        transport: Transport::ScvProtocol,
554        acp: None,
555    },
556];
557
558/// The descriptor for `name`, such as `"codex"`.
559pub fn adapter(name: &str) -> Option<&'static AdapterDescriptor> {
560    ADAPTERS.iter().find(|adapter| adapter.name == name)
561}
562
563/// Whether a delegated agent must not inherit `variable`: SCV's selectors,
564/// any `*_API_KEY`, and every adapter's credential and state variables, so
565/// no agent sees another's credentials either.
566pub fn is_removed_agent_variable(variable: &OsStr) -> bool {
567    let Some(variable) = variable.to_str() else {
568        return false;
569    };
570    variable.ends_with("_API_KEY")
571        || COMMON_REMOVED_ENVIRONMENT.contains(&variable)
572        || ADAPTERS
573            .iter()
574            .flat_map(|adapter| adapter.removed_environment)
575            .any(|rule| match rule.strip_suffix('*') {
576                Some(prefix) => variable.starts_with(prefix),
577                None => variable == *rule,
578            })
579}
580
581/// One line describing a CLI's own status result without echoing it: the raw
582/// output names the signed-in account or part of a key.
583pub fn summarize_status(summary: StatusSummary, succeeded: bool, output: &str) -> String {
584    let signed_out = "not signed in".to_owned();
585    match summary {
586        StatusSummary::ClaudeJson => {
587            // The first JSON value; anything after it (such as stderr) is ignored.
588            let first = serde_json::Deserializer::from_str(output)
589                .into_iter::<serde_json::Value>()
590                .next();
591            let Some(Ok(value)) = first else {
592                return if succeeded {
593                    "signed in".into()
594                } else {
595                    signed_out
596                };
597            };
598            if value.get("loggedIn").and_then(serde_json::Value::as_bool) != Some(true) {
599                return signed_out;
600            }
601            let method = match value.get("authMethod").and_then(serde_json::Value::as_str) {
602                Some("claude.ai") => "Claude account",
603                Some("api_key" | "apiKey" | "console") => "API key",
604                Some("oauth_token" | "oauthToken") => "OAuth token",
605                _ => "other method",
606            };
607            match value
608                .get("subscriptionType")
609                .and_then(serde_json::Value::as_str)
610                .filter(|plan| ["free", "pro", "max", "team", "enterprise"].contains(plan))
611            {
612                Some(plan) => format!("signed in ({method}, {plan})"),
613                None => format!("signed in ({method})"),
614            }
615        }
616        StatusSummary::CodexText => {
617            let lower = output.to_ascii_lowercase();
618            if !succeeded || lower.contains("not logged in") {
619                signed_out
620            } else if lower.contains("api key") {
621                "signed in (API key)".into()
622            } else if lower.contains("chatgpt") {
623                "signed in (ChatGPT account)".into()
624            } else {
625                "signed in".into()
626            }
627        }
628        StatusSummary::ExitStatus => {
629            if succeeded {
630                "signed in".into()
631            } else {
632                signed_out
633            }
634        }
635    }
636}
637
638/// Resolve `command` in the per-user `search_dirs`, then on `PATH`. A command
639/// containing a path separator is used as given.
640pub fn resolve_agent_executable(command: &str, search_dirs: &[PathBuf]) -> Option<PathBuf> {
641    if command.contains('/') {
642        let path = Path::new(command);
643        return path.is_file().then(|| path.to_path_buf());
644    }
645    std::env::join_paths(search_dirs)
646        .ok()
647        .and_then(|dirs| {
648            let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
649            which::which_in(command, Some(dirs), cwd).ok()
650        })
651        .or_else(|| which::which(command).ok())
652}
653
654/// Absolute per-user search directories for `adapter` under `home`.
655pub fn adapter_search_dirs(adapter: &AdapterDescriptor, home: &Path) -> Vec<PathBuf> {
656    adapter
657        .search_dirs
658        .iter()
659        .chain(USER_BIN_DIRS)
660        .map(|dir| home.join(dir))
661        .collect()
662}
663
664#[cfg(test)]
665mod tests;