Skip to main content

agent_abstraction/
agent.rs

1//! The three agents, what each can do, and how a request becomes an argv.
2//!
3//! Everything here is pure: [`Agent::argv`] builds a command line from a
4//! [`Plan`] without touching the filesystem, the clock, or a process, so every
5//! flag mapping is covered by an ordinary unit test. Spawning lives in
6//! [`crate::run`].
7
8use std::fmt;
9
10use serde::{Deserialize, Serialize};
11
12use crate::error::{Error, Result};
13
14/// A coding agent this crate can drive headlessly.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "kebab-case")]
17pub enum Agent {
18    /// Anthropic's Claude Code (`claude`).
19    Claude,
20    /// The `OpenAI` Codex CLI (`codex`).
21    Codex,
22    /// GitHub Copilot CLI (`copilot`).
23    Copilot,
24}
25
26/// How an agent's native session id is obtained. This is the axis deciding whether
27/// a caller-owned session name can be bound to it at all.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum SessionSupport {
30    /// The caller assigns the id up front (`claude --session-id <uuid>`), so the
31    /// binding is known before the process starts and survives a crashed run.
32    Minted,
33    /// The agent prints an id we read back out of its output (Codex's
34    /// `thread_id`). The binding only exists once the run produced output.
35    Printed,
36    /// No id is exposed headlessly. Named sessions are refused for this agent.
37    None,
38}
39
40/// What an agent supports. Used to reject an impossible request before spawning
41/// rather than silently doing something weaker than asked.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[non_exhaustive]
44#[expect(
45    clippy::struct_excessive_bools,
46    reason = "one flag per capability; a bitfield would read worse at every call site"
47)]
48pub struct Caps {
49    /// How a native session id is obtained, if at all.
50    pub session: SessionSupport,
51    /// Whether resuming can branch a new session instead of appending in place.
52    pub fork: bool,
53    /// Whether the agent emits a structured event stream this crate normalizes.
54    pub events: bool,
55    /// Whether the agent takes a real system-prompt flag. When false the system
56    /// text is prepended to the prompt so it still reaches the model.
57    pub native_system: bool,
58    /// How the agent accepts a JSON Schema for its answer, if at all.
59    pub schema: SchemaSupport,
60    /// Whether the agent answers slash commands such as `/compact`.
61    ///
62    /// Claude publishes a catalogue and acts on them; the others read the same
63    /// text as prose and would discuss the command rather than run it, which is
64    /// worse than refusing.
65    pub commands: bool,
66    /// Whether another user message can be delivered while a turn is running.
67    pub live_follow_up: bool,
68    /// Whether gated tool calls can be routed to the caller for a decision.
69    pub approvals: bool,
70}
71
72/// How an agent accepts a JSON Schema constraining its answer.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum SchemaSupport {
75    /// The schema rides the command line (`claude --json-schema <schema>`).
76    Inline,
77    /// The schema must be a file the agent reads
78    /// (`codex exec --output-schema <FILE>`), so the runner writes one.
79    File,
80    /// No structured-output support. Asking is an error rather than a prose
81    /// answer dressed up as data.
82    None,
83}
84
85/// Permission posture for a run, mapped onto each agent's own vocabulary.
86///
87/// # What these do and do not guarantee
88///
89/// These postures constrain each CLI's **built-in** tools: its shell, its file
90/// writes, its sandbox. They do **not** constrain MCP servers, plugins or custom
91/// tools the agent is configured with. An MCP tool that files an issue, writes
92/// to a database or calls a deployment API is a separate tool category in all
93/// three CLIs and can still act during a nominally restricted run.
94///
95/// If a run must not cause remote side effects, the containment has to come from
96/// the agent's own configuration (which MCP servers are enabled at all), not
97/// from this enum. What is selected here is enforced by the CLI, and what the
98/// CLI does not model cannot be enforced from out here.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
100#[serde(rename_all = "kebab-case")]
101pub enum Permission {
102    /// No writes to the local filesystem, and no shell where the CLI can gate
103    /// one.
104    ///
105    /// The strongest posture this crate can express, and still not a guarantee
106    /// of "no side effects": see the type-level note about MCP tools. Codex
107    /// enforces it with a read-only sandbox, which blocks writes but still
108    /// permits command execution.
109    #[default]
110    ReadOnly,
111    /// Ask the agent to plan rather than act.
112    ///
113    /// Claude and Copilot have a real plan mode. **Codex has none**, so this
114    /// maps to its read-only sandbox: writes are blocked, but the model is not
115    /// instructed to withhold execution the way a true plan mode would.
116    Plan,
117    /// Allow file edits, while still gating shell commands where the CLI can.
118    Edit,
119    /// Allow the agent's own default automation.
120    Auto,
121    /// Skip every permission check. For sandboxes.
122    Bypass,
123}
124
125/// Environment variables that route an agent's traffic through a corporate
126/// proxy or a custom certificate authority.
127///
128/// None of the three vendors documents proxy support, and none exposes a proxy
129/// flag, so this is a convenience list of names a host may want to forward, not
130/// a claim that forwarding them works. (The names do appear in all three
131/// shipped binaries, but that shows they are referenced, not that provider
132/// traffic honours them.) Verify against your own proxy before relying on it.
133///
134/// Not included in [`EnvPolicy::Minimal`]: they are situational, and the proxy
135/// URLs frequently carry credentials. Offered here so a host can present them
136/// as an explicit setting and forward the ones it wants with
137/// [`crate::Request::env`], rather than every caller rediscovering the names.
138///
139/// Excluding them from `Minimal` does not block them. Under the default
140/// [`EnvPolicy::Inherit`] they flow exactly as they would for the CLI run from a
141/// shell; the only thing `Minimal` changes is that forwarding becomes a
142/// decision rather than an accident.
143///
144/// ```no_run
145/// # use agent_abstraction::{Agent, EnvPolicy, NETWORK_ENV, Request};
146/// let mut request = Request::new(Agent::Claude, "hi").env_policy(EnvPolicy::Minimal);
147/// // Forward only the proxy settings this host actually has.
148/// for name in NETWORK_ENV {
149///     if let Ok(value) = std::env::var(name) {
150///         request = request.env(*name, value);
151///     }
152/// }
153/// ```
154pub const NETWORK_ENV: &[&str] = &[
155    "HTTP_PROXY",
156    "HTTPS_PROXY",
157    "ALL_PROXY",
158    "NO_PROXY",
159    "http_proxy",
160    "https_proxy",
161    "all_proxy",
162    "no_proxy",
163    "SSL_CERT_FILE",
164    "SSL_CERT_DIR",
165    "NODE_EXTRA_CA_CERTS",
166];
167
168/// Which of the host's environment variables reach the agent.
169///
170/// **The default is [`EnvPolicy::Minimal`].** Inheriting the whole environment
171/// is what a CLI gets from a shell, but this crate is embedded in processes that
172/// hold unrelated secrets, and full inheritance hands every one of them to the
173/// agent and to every command the agent runs. That is a decision worth making
174/// deliberately, so it is the opt-in rather than the default.
175#[derive(Debug, Clone, PartialEq, Eq, Default)]
176#[non_exhaustive]
177pub enum EnvPolicy {
178    /// Pass through only what the selected agent needs, per
179    /// [`Agent::essential_env`], plus anything set with [`crate::Request::env`].
180    ///
181    /// The crate owns this list rather than the caller, because "what does this
182    /// CLI need to work" is knowledge about the agent, and an incomplete
183    /// hand-written list produces a run that fails in a way that looks like an
184    /// auth problem. Every agent is verified to authenticate under it by the
185    /// live test suite.
186    #[default]
187    Minimal,
188    /// Pass the whole parent environment through, as a shell would.
189    ///
190    /// Correct when the host process holds nothing the agent should not see, or
191    /// when something environment-specific (a proxy, a custom CA, a vendor
192    /// variable this crate does not know about) has to reach the CLI and
193    /// enumerating it is impractical.
194    Inherit,
195    /// Pass through only these names, plus anything set with
196    /// [`crate::Request::env`]. Names unset in the parent are skipped.
197    Only(Vec<String>),
198}
199
200/// Output shape requested from the agent.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
202#[serde(rename_all = "kebab-case")]
203pub enum Format {
204    /// Plain prose on stdout. Carries no session id and no events.
205    Text,
206    /// One JSON result document, delivered when the turn ends.
207    ///
208    /// Nothing is observable until then, so a caller watching a run sees
209    /// nothing for its whole duration. Cheaper to parse, and fine when only the
210    /// answer matters.
211    Json,
212    /// A JSONL event stream, normalized into [`crate::Event`]s.
213    ///
214    /// The default, because the alternative is silence: under `Json` a run that
215    /// takes twenty minutes reports nothing for twenty minutes. This carries
216    /// everything `Json` does, the session id and any schema-conforming value
217    /// included, so defaulting to it costs only parsing.
218    #[default]
219    Stream,
220}
221
222/// How a run continues an earlier conversation.
223#[derive(Debug, Clone, PartialEq, Eq, Default)]
224pub enum Continue {
225    /// Start a fresh conversation.
226    #[default]
227    New,
228    /// Start a fresh conversation under an id the caller chose. Only valid for
229    /// [`SessionSupport::Minted`] agents.
230    NewWith(String),
231    /// Append to an existing conversation in place.
232    Resume(String),
233    /// Branch a new conversation off an existing one, leaving it untouched.
234    Fork(String),
235}
236
237/// A fully resolved run request, ready to become an argv. Built by
238/// [`crate::Request::plan`]; consumed by [`Agent::argv`].
239#[derive(Debug, Clone)]
240#[expect(
241    clippy::struct_excessive_bools,
242    reason = "each names a distinct thing the argv builder branches on"
243)]
244pub struct Plan {
245    /// The binary to invoke.
246    pub bin: String,
247    /// The user prompt.
248    pub prompt: String,
249    /// System prompt, if any.
250    pub system: Option<String>,
251    /// Model id or alias, if pinned.
252    pub model: Option<String>,
253    /// Reasoning effort level, if set. Passed through verbatim, for the same
254    /// reason [`Plan::model`] is: the accepted set is the provider's to define
255    /// and it has already grown once.
256    pub effort: Option<String>,
257    /// Permission posture.
258    pub permission: Permission,
259    /// Requested output shape.
260    pub format: Format,
261    /// How this run continues an earlier one.
262    pub cont: Continue,
263    /// True when the prompt is piped on stdin instead of riding the argv.
264    pub stdin_prompt: bool,
265    /// True when stdin stays open for the turn so the caller can send more.
266    ///
267    /// Implied by [`Plan::approvals`], which needs the same open channel.
268    pub duplex: bool,
269    /// True when gated tool calls are routed to the caller for a decision
270    /// rather than resolved by the posture.
271    pub approvals: bool,
272    /// A JSON Schema the answer must conform to, as text.
273    ///
274    /// Delivered differently per agent: Claude takes it inline, Codex takes a
275    /// path, so this is the source and `schema_file` is where the runner put it
276    /// when a file was needed.
277    pub schema: Option<String>,
278    /// Path to the schema on disk, materialized by the runner for agents that
279    /// take a file rather than an inline value.
280    pub schema_file: Option<String>,
281    /// True when the prompt is a slash command rather than something to answer.
282    ///
283    /// Changes nothing about the argv — a command travels as the prompt — and
284    /// exists so [`Agent::check`] can refuse an agent that would read it as
285    /// prose.
286    pub is_command: bool,
287}
288
289/// Prompts at or above this many bytes are piped on stdin rather than placed on
290/// the argv. Well under the ~1 MiB `ARG_MAX` floor on macOS, with room for the
291/// rest of the command line and the inherited environment.
292pub(crate) const STDIN_THRESHOLD: usize = 128 * 1024;
293
294/// The budget for everything on one command line.
295///
296/// `ARG_MAX` is about 1 MiB on macOS and covers the environment as well as the
297/// arguments, so half of it leaves room for a large inherited environment. Over
298/// this the spawn fails with a bare `E2BIG` that names nothing; the crate checks
299/// first so the error can say which input was too big.
300pub(crate) const MAX_COMMAND_LINE: usize = 512 * 1024;
301
302impl Agent {
303    /// Every agent, in a stable order.
304    pub const ALL: [Agent; 3] = [Agent::Claude, Agent::Codex, Agent::Copilot];
305
306    /// The stable identifier used in session records and logs.
307    #[must_use]
308    pub fn id(self) -> &'static str {
309        match self {
310            Agent::Claude => "claude-code",
311            Agent::Codex => "codex",
312            Agent::Copilot => "copilot",
313        }
314    }
315
316    /// The default binary name looked up on `PATH`.
317    #[must_use]
318    pub fn bin(self) -> &'static str {
319        match self {
320            Agent::Claude => "claude",
321            Agent::Codex => "codex",
322            Agent::Copilot => "copilot",
323        }
324    }
325
326    /// The command that asks this agent whether it is logged in, or `None`
327    /// when it offers no way to ask.
328    ///
329    /// Verified against each CLI: Claude has `auth status`, which answers JSON
330    /// by default, and Codex has `login status`, which answers prose. Copilot
331    /// has neither, so its credentials cannot be confirmed without spending a
332    /// request.
333    #[must_use]
334    pub fn auth_status_argv(self) -> Option<&'static [&'static str]> {
335        match self {
336            Agent::Claude => Some(&["auth", "status", "--json"]),
337            Agent::Codex => Some(&["login", "status"]),
338            Agent::Copilot => None,
339        }
340    }
341
342    /// The environment variables this agent accepts a credential in, most
343    /// preferred first.
344    ///
345    /// Copilot documents its precedence explicitly: `COPILOT_GITHUB_TOKEN`,
346    /// then `GH_TOKEN`, then `GITHUB_TOKEN`.
347    #[must_use]
348    pub fn auth_env_vars(self) -> &'static [&'static str] {
349        match self {
350            Agent::Claude => &["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"],
351            Agent::Codex => &["CODEX_API_KEY", "OPENAI_API_KEY"],
352            Agent::Copilot => &["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"],
353        }
354    }
355
356    /// The command that resolves a missing login for this agent.
357    ///
358    /// Verified against each CLI's own help: Codex and Copilot expose a `login`
359    /// subcommand, while Claude authenticates interactively or through a
360    /// long-lived token.
361    #[must_use]
362    pub fn login_hint(self) -> &'static str {
363        match self {
364            Agent::Claude => {
365                "run `claude` and use /login, or `claude setup-token` for a \
366                              long-lived token"
367            }
368            Agent::Codex => "run `codex login`",
369            Agent::Copilot => "run `copilot login`",
370        }
371    }
372
373    /// The release this crate's flag mappings were verified against.
374    ///
375    /// Every mapping in this module was checked by running these exact
376    /// versions, not by reading their documentation. [`crate::Probe`] compares
377    /// an installed CLI against this so drift is a question a host can ask up
378    /// front rather than something a failing run reveals.
379    #[must_use]
380    pub fn verified_version(self) -> crate::Version {
381        let (major, minor, patch) = match self {
382            // `claude --version` -> "2.1.212 (Claude Code)"
383            Agent::Claude => (2, 1, 212),
384            // `codex --version` -> "codex-cli 0.145.0"
385            Agent::Codex => (0, 145, 0),
386            // `copilot --version` -> "GitHub Copilot CLI 1.0.75."
387            Agent::Copilot => (1, 0, 75),
388        };
389        crate::Version {
390            major,
391            minor,
392            patch,
393        }
394    }
395
396    /// The documented install command, surfaced by [`Error::NotInstalled`].
397    #[must_use]
398    pub fn install_hint(self) -> &'static str {
399        match self {
400            Agent::Claude => "npm install -g @anthropic-ai/claude-code",
401            Agent::Codex => "npm install -g @openai/codex",
402            Agent::Copilot => "npm install -g @github/copilot",
403        }
404    }
405
406    /// The environment variables this agent needs to function, used by
407    /// [`EnvPolicy::Minimal`].
408    ///
409    /// Two groups: what any process needs to start, and this agent's own
410    /// credential and config variables. Permission-controlling variables are
411    /// excluded on principle: `COPILOT_ALLOW_ALL` is Copilot's env equivalent
412    /// of `--allow-all-tools`, so inheriting it would let the host's ambient
413    /// environment widen a run's permissions behind [`Permission`]'s back. A name absent from the parent
414    /// environment is skipped, so nothing here is fabricated.
415    ///
416    /// Proxy and custom-CA variables are deliberately **not** here. They are
417    /// environment-specific rather than required, and `HTTP_PROXY` /
418    /// `HTTPS_PROXY` routinely embed credentials (`http://user:pass@proxy`), so
419    /// passing them automatically would leak one through the very policy meant
420    /// to withhold secrets. A host that needs them should offer them as a
421    /// setting and pass them with [`crate::Request::env`]; [`NETWORK_ENV`] names
422    /// them so a settings screen does not have to hardcode the list.
423    ///
424    /// `PATH`, `HOME` and `USER` are the verified floor on macOS: all three CLIs
425    /// answer correctly with exactly those set, and Claude reports "Not logged
426    /// in" without `USER`, since its keychain lookup is keyed on it. The Windows
427    /// names are included on the same reasoning but are **not** verified, as
428    /// this crate has not been run there.
429    #[must_use]
430    pub fn essential_env(self) -> Vec<&'static str> {
431        // Needed by any child process, plus the locale and temp dir the CLIs
432        // use for scratch files.
433        const BASE: &[&str] = &[
434            "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "LANG", "LC_ALL",
435        ];
436        // Unverified: this crate has not been exercised on Windows.
437        const WINDOWS: &[&str] = &[
438            "USERPROFILE",
439            "APPDATA",
440            "LOCALAPPDATA",
441            "SystemRoot",
442            "SystemDrive",
443            "TEMP",
444            "TMP",
445            "PATHEXT",
446            "ComSpec",
447        ];
448        let agent: &[&str] = match self {
449            Agent::Claude => &[
450                "ANTHROPIC_API_KEY",
451                "ANTHROPIC_AUTH_TOKEN",
452                "ANTHROPIC_BASE_URL",
453                "CLAUDE_CONFIG_DIR",
454            ],
455            Agent::Codex => &[
456                "CODEX_HOME",
457                "CODEX_API_KEY",
458                "OPENAI_API_KEY",
459                "OPENAI_BASE_URL",
460            ],
461            // `COPILOT_GITHUB_TOKEN` takes precedence over the others per
462            // Copilot's own docs, and was missing here: a host using it would
463            // have failed to authenticate under EnvPolicy::Minimal.
464            Agent::Copilot => &[
465                "COPILOT_GITHUB_TOKEN",
466                "GH_TOKEN",
467                "GITHUB_TOKEN",
468                "XDG_CONFIG_HOME",
469            ],
470        };
471        BASE.iter().chain(WINDOWS).chain(agent).copied().collect()
472    }
473
474    /// What this agent supports.
475    #[must_use]
476    pub fn caps(self) -> Caps {
477        match self {
478            // Verified against claude 2.1.212: `--session-id <uuid>` assigns the
479            // id, `--fork-session` branches, `--output-format stream-json`
480            // streams (and demands `--verbose`), `--append-system-prompt` is a
481            // real flag.
482            Agent::Claude => Caps {
483                session: SessionSupport::Minted,
484                fork: true,
485                events: true,
486                native_system: true,
487                // Verified: `--json-schema <inline>` puts the conforming value
488                // in the result document's `structured_output`.
489                schema: SchemaSupport::Inline,
490                // Verified: `/compact` reports `compact_result` and the init
491                // record lists the whole catalogue.
492                commands: true,
493                live_follow_up: true,
494                approvals: true,
495            },
496            // `codex exec --json` emits `thread_id`; continuation is the
497            // `resume` subcommand and is linear (`codex fork` is TUI-only).
498            Agent::Codex => Caps {
499                session: SessionSupport::Printed,
500                fork: false,
501                events: true,
502                native_system: false,
503                // Verified: `--output-schema <FILE>` makes the final
504                // `agent_message` the conforming JSON, with no separate field.
505                schema: SchemaSupport::File,
506                commands: false,
507                live_follow_up: false,
508                approvals: false,
509            },
510            // Verified against Copilot CLI 1.0.75: `--session-id <uuid>` both
511            // mints a new session and resumes an existing one (one flag, both
512            // directions), and `--output-format json` is a JSONL event stream.
513            // There is no headless fork.
514            Agent::Copilot => Caps {
515                session: SessionSupport::Minted,
516                fork: false,
517                events: true,
518                native_system: false,
519                // Copilot 1.0.75 exposes no schema flag at all.
520                schema: SchemaSupport::None,
521                commands: false,
522                live_follow_up: false,
523                approvals: false,
524            },
525        }
526    }
527
528    /// The format that can carry this agent's session id, if any. A named
529    /// session upgrades to this when the caller did not pin a format.
530    #[must_use]
531    pub fn session_format(self) -> Option<Format> {
532        match self.caps().session {
533            // Claude reports the id in both structured formats; `Json` is the
534            // cheaper default when the caller did not ask to stream.
535            SessionSupport::Minted | SessionSupport::Printed => Some(match self {
536                Agent::Claude => Format::Json,
537                // `--json` IS Codex's stream and Copilot's `json` is JSONL;
538                // neither has a single-document form.
539                Agent::Codex | Agent::Copilot => Format::Stream,
540            }),
541            SessionSupport::None => None,
542        }
543    }
544
545    /// Whether `format` can carry this agent's session id.
546    ///
547    /// Distinct from [`Agent::session_format`], which names the *preferred* one:
548    /// Claude reports its id under both `Json` and `Stream`, and only plain text
549    /// loses it. A named session needs this, not equality with the preferred
550    /// format, or streaming a named Claude session would be refused for no
551    /// reason.
552    #[must_use]
553    pub fn format_carries_session(self, format: Format) -> bool {
554        self.session_format().is_some() && format != Format::Text
555    }
556
557    /// Reject a plan this agent cannot honour, before anything is spawned.
558    fn check(self, plan: &Plan) -> Result<()> {
559        let caps = self.caps();
560        if matches!(plan.cont, Continue::Fork(_)) && !caps.fork {
561            return Err(Error::Unsupported {
562                agent: self,
563                what: "forking a session headlessly",
564            });
565        }
566        if matches!(plan.cont, Continue::NewWith(_)) && caps.session != SessionSupport::Minted {
567            return Err(Error::Unsupported {
568                agent: self,
569                what: "assigning a session id up front",
570            });
571        }
572        if plan.schema.is_some() && caps.schema == SchemaSupport::None {
573            return Err(Error::Unsupported {
574                agent: self,
575                what: "constraining its answer to a JSON schema",
576            });
577        }
578        if plan.format == Format::Stream && !caps.events {
579            return Err(Error::Unsupported {
580                agent: self,
581                what: "a structured event stream",
582            });
583        }
584        // Refused rather than passed through: an agent with no command
585        // vocabulary reads `/compact` as prose and answers a question about
586        // it, which looks like the command running and silently is not.
587        if plan.is_command && !caps.commands {
588            return Err(Error::Unsupported {
589                agent: self,
590                what: "slash commands such as /compact",
591            });
592        }
593        Ok(())
594    }
595
596    /// Build the command line for `plan`.
597    ///
598    /// The first element is the binary; the rest are its arguments. Returns
599    /// [`Error::Unsupported`] when the plan asks for a capability this agent
600    /// lacks, never a quiet downgrade.
601    ///
602    /// # Errors
603    /// [`Error::Unsupported`] if the plan needs a capability this agent lacks.
604    pub fn argv(self, plan: &Plan) -> Result<Vec<String>> {
605        Ok(self
606            .typed_argv(plan)?
607            .into_iter()
608            .map(|arg| arg.value)
609            .collect())
610    }
611
612    /// The command line with each argument's sensitivity attached.
613    ///
614    /// # Errors
615    /// [`Error::Unsupported`] if the plan needs a capability this agent lacks.
616    pub(crate) fn typed_argv(self, plan: &Plan) -> Result<Vec<Arg>> {
617        // Verified against codex-cli 0.145.0 and Copilot CLI 1.0.75: `codex
618        // exec` has no approval callback, its sandbox mode being the answer
619        // decided before the run starts, and Copilot needs `--allow-all-tools`
620        // to run headlessly at all and gates only through `--deny-tool`. A run
621        // that quietly never asked would be the worst outcome here, since a
622        // caller would read silence as "nothing needed approval".
623        let caps = self.caps();
624        if plan.approvals && !caps.approvals {
625            return Err(Error::Unsupported {
626                agent: self,
627                what: "routing tool approvals to the caller",
628            });
629        }
630        // Verified against codex-cli 0.145.0 and Copilot CLI 1.0.75: neither
631        // takes a structured message stream on stdin, so neither can be sent a
632        // second message once a turn is under way.
633        if plan.duplex && !caps.live_follow_up {
634            return Err(Error::Unsupported {
635                agent: self,
636                what: "sending a follow-up message while a turn is running",
637            });
638        }
639        // `ReadOnly` keeps its guarantee by removing the mutating tools
640        // outright, so under it there is nothing left to be asked about: a
641        // caller would opt into approvals and then never be asked, and read the
642        // silence as "the agent wanted nothing". Refused rather than quietly
643        // dropping either half, since dropping the tool removal would weaken a
644        // posture the caller asked for by name.
645        if plan.approvals && plan.permission == Permission::ReadOnly {
646            return Err(Error::Unsupported {
647                agent: self,
648                what: "approvals under a read-only posture, which removes the \
649                       tools that would be asked about; use `Permission::Edit` \
650                       and decide per call",
651            });
652        }
653        self.check(plan)?;
654        Ok(match self {
655            Agent::Claude => argv_claude(plan),
656            Agent::Codex => argv_codex(plan),
657            Agent::Copilot => argv_copilot(plan),
658        })
659    }
660
661    /// The prompt text actually delivered, with the system prompt folded in for
662    /// agents that have no flag for it. Never dropped silently.
663    #[must_use]
664    pub fn effective_prompt(self, plan: &Plan) -> String {
665        match (&plan.system, self.caps().native_system) {
666            (Some(system), false) => format!("{system}\n\n{}", plan.prompt),
667            _ => plan.prompt.clone(),
668        }
669    }
670}
671
672impl fmt::Display for Agent {
673    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674        f.write_str(self.id())
675    }
676}
677
678/// How sensitive one argument's value is, decided where the argument is built
679/// rather than guessed back afterwards.
680///
681/// Reconstructing this from a finished command line means pattern-matching flag
682/// names and positions, which misses exactly the cases that matter: Codex's
683/// prompt is a bare trailing positional, and anything from `unchecked_args` has
684/// no recognizable shape at all. Recording it at construction cannot miss.
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
686pub(crate) enum Sensitivity {
687    /// A flag name or fixed token. Safe to show.
688    Public,
689    /// User or caller content: prompts and system prompts.
690    Prompt,
691    /// A session handle, which resumes a conversation.
692    SessionId,
693    /// Caller-supplied raw arguments. Unknowable, so assumed sensitive.
694    Unchecked,
695}
696
697/// One argument and how sensitive it is.
698#[derive(Debug, Clone)]
699pub(crate) struct Arg {
700    pub(crate) value: String,
701    pub(crate) sensitivity: Sensitivity,
702}
703
704/// Builds an argv, keeping every flag name literal at its call site so the flag
705/// list for an agent stays greppable and auditable against `--help`, and
706/// recording per-argument sensitivity so the executable and redacted forms come
707/// from one source.
708pub(crate) struct Argv(Vec<Arg>);
709
710impl Argv {
711    /// Start with the binary.
712    fn new(bin: &str) -> Self {
713        Self(vec![Arg {
714            value: bin.to_string(),
715            sensitivity: Sensitivity::Public,
716        }])
717    }
718
719    fn push(&mut self, value: impl Into<String>, sensitivity: Sensitivity) -> &mut Self {
720        self.0.push(Arg {
721            value: value.into(),
722            sensitivity,
723        });
724        self
725    }
726
727    /// A bare flag with no value.
728    fn bare(&mut self, flag: &str) -> &mut Self {
729        self.push(flag, Sensitivity::Public)
730    }
731
732    /// A flag and a value that is safe to show.
733    fn pair(&mut self, flag: &str, value: impl AsRef<str>) -> &mut Self {
734        self.bare(flag).push(value.as_ref(), Sensitivity::Public)
735    }
736
737    /// A flag and a value that must not be logged.
738    fn secret(&mut self, flag: &str, value: impl AsRef<str>, kind: Sensitivity) -> &mut Self {
739        self.bare(flag).push(value.as_ref(), kind)
740    }
741
742    /// A flag and its value, only when the value is present.
743    fn opt(&mut self, flag: &str, value: Option<&String>) -> &mut Self {
744        if let Some(value) = value {
745            self.pair(flag, value);
746        }
747        self
748    }
749
750    /// A positional argument that is safe to show.
751    fn arg(&mut self, value: impl Into<String>) -> &mut Self {
752        self.push(value, Sensitivity::Public)
753    }
754
755    /// A positional argument carrying caller content.
756    fn arg_sensitive(&mut self, value: impl Into<String>, kind: Sensitivity) -> &mut Self {
757        self.push(value, kind)
758    }
759
760    fn done(&mut self) -> Vec<Arg> {
761        std::mem::take(&mut self.0)
762    }
763}
764
765/// Claude Code's permission-mode token for each posture. Choices verified from
766/// `claude --help` (2.1.212): acceptEdits, auto, bypassPermissions, manual,
767/// dontAsk, plan.
768fn claude_mode(p: Permission) -> &'static str {
769    match p {
770        // `dontAsk` auto-denies gated tools and keeps going rather than
771        // blocking on a prompt no one can answer headlessly. The read-only
772        // guarantee comes from `--disallowedTools`, below.
773        Permission::ReadOnly => "dontAsk",
774        Permission::Plan => "plan",
775        Permission::Edit => "acceptEdits",
776        Permission::Auto => "auto",
777        Permission::Bypass => "bypassPermissions",
778    }
779}
780
781/// `claude -p <prompt> --permission-mode M --output-format F [...]`
782fn argv_claude(plan: &Plan) -> Vec<Arg> {
783    let mut a = Argv::new(&plan.bin);
784    a.bare("-p");
785    if plan.duplex || plan.approvals {
786        // Under `--input-format stream-json` the prompt is a JSON message on
787        // stdin, so it must not also ride the argv.
788    } else if plan.stdin_prompt {
789        // With `--input-format text` claude reads the prompt from stdin, so a
790        // large prompt never has to fit on the argv.
791        a.pair("--input-format", "text");
792    } else {
793        a.arg_sensitive(Agent::Claude.effective_prompt(plan), Sensitivity::Prompt);
794    }
795
796    // Approvals ride the same open channel, so they imply it.
797    if plan.duplex || plan.approvals {
798        // Messages travel as JSON on stdin, which is what lets a caller send
799        // another one mid-turn. Verified against claude 2.1.212: a message
800        // written while a turn is running is taken up at the next step
801        // boundary, so a three-command task interrupted after the first runs
802        // only that one.
803        a.pair("--input-format", "stream-json");
804    }
805    if plan.approvals {
806        // The control channel that carries a `can_use_tool` question out and a
807        // decision back. Verified against claude 2.1.212: `manual` is the mode
808        // that asks, `stdio` names this process as the answerer, and the
809        // handshake in `crate::approval` is what actually switches the requests
810        // on.
811        //
812        // Deliberately *not* `--setting-sources ""`. It would suppress the
813        // user's own settings, including their CLAUDE.md, and it is not needed:
814        // verified that a mutating command still asks with their settings
815        // loaded. Read-only commands are allowed without asking either way,
816        // which is Claude's decision to make and not this crate's to override.
817        a.pair("--permission-mode", "manual");
818        a.pair("--permission-prompt-tool", "stdio");
819    } else {
820        a.pair("--permission-mode", claude_mode(plan.permission));
821    }
822    if plan.permission == Permission::ReadOnly {
823        // Remove the mutating built-ins outright. Reads still run via
824        // Read/Grep/Glob. `mcp__*` covers every MCP tool: denying only the
825        // built-in writers would leave an MCP server free to mutate remote
826        // state during a run the caller asked to be read-only.
827        a.bare("--disallowedTools");
828        for tool in ["Bash", "Edit", "Write", "NotebookEdit", "mcp__*"] {
829            a.arg(tool);
830        }
831    }
832
833    a.opt("--model", plan.model.as_ref());
834    // Verified against claude 2.1.212: `--effort <level>` (low, medium, high,
835    // xhigh, max), a session-level flag rather than a per-model one.
836    a.opt("--effort", plan.effort.as_ref());
837    if let Some(system) = &plan.system {
838        a.secret("--append-system-prompt", system, Sensitivity::Prompt);
839    }
840
841    match &plan.cont {
842        Continue::New => {}
843        Continue::NewWith(id) => {
844            a.secret("--session-id", id, Sensitivity::SessionId);
845        }
846        Continue::Resume(id) => {
847            a.secret("--resume", id, Sensitivity::SessionId);
848        }
849        Continue::Fork(id) => {
850            // Mints a new id off `id`, leaving the original and its cached
851            // prefix untouched. The new id comes back in the output.
852            a.secret("--resume", id, Sensitivity::SessionId)
853                .bare("--fork-session");
854        }
855    }
856
857    a.pair(
858        "--output-format",
859        match plan.format {
860            Format::Text => "text",
861            Format::Json => "json",
862            Format::Stream => "stream-json",
863        },
864    );
865    if let Some(schema) = &plan.schema {
866        // Inline, and the conforming value comes back in `structured_output`.
867        a.secret("--json-schema", schema, Sensitivity::Prompt);
868    }
869    if plan.format == Format::Stream {
870        // Claude refuses `-p --output-format stream-json` without it:
871        // "--print with --output-format=stream-json requires --verbose".
872        a.bare("--verbose");
873        // Without this Claude emits only *completed* messages, so text arrives
874        // a paragraph at a time. With it, `stream_event` records carry the
875        // token-level deltas, which is what makes a transcript type rather than
876        // appear. Copilot streams deltas natively, so this is what puts the two
877        // on equal footing.
878        a.bare("--include-partial-messages");
879    }
880    a.done()
881}
882
883/// `codex exec [resume <id>] --skip-git-repo-check [sandbox flags] [--model M]
884/// [--json] <prompt>`
885fn argv_codex(plan: &Plan) -> Vec<Arg> {
886    let mut a = Argv::new(&plan.bin);
887    a.bare("exec");
888    if let Continue::Resume(id) = &plan.cont {
889        // Continuation is a subcommand, not a flag.
890        a.bare("resume")
891            .arg_sensitive(id.clone(), Sensitivity::SessionId);
892    }
893
894    // `codex exec` aborts outside a git repository unless told not to. That
895    // check guards against an agent editing files with no way to undo them, but
896    // this crate is embedded in hosts that legitimately run against scratch
897    // directories, worktrees and review checkouts, and a hard abort there is
898    // useless to them. The real containment is the sandbox below, which is
899    // `read-only` by default, so nothing is unrecoverable regardless.
900    a.bare("--skip-git-repo-check");
901
902    // `codex exec` takes `--sandbox`, but `codex exec resume` does **not**: it
903    // rejects the flag outright and takes the same setting as a `-c` config
904    // override instead. Verified against codex-cli 0.145.0, where passing
905    // `--sandbox` to a resume fails with "unexpected argument '--sandbox'".
906    // Dropping the sandbox on resume would silently run a continued turn under a
907    // different posture than the caller asked for.
908    let resuming = matches!(plan.cont, Continue::Resume(_));
909    let sandbox = match plan.permission {
910        Permission::Bypass => None,
911        Permission::ReadOnly | Permission::Plan => Some("read-only"),
912        Permission::Edit | Permission::Auto => Some("workspace-write"),
913    };
914    match (sandbox, resuming) {
915        (None, _) => a.bare("--dangerously-bypass-approvals-and-sandbox"),
916        (Some(mode), false) => a.pair("--sandbox", mode),
917        // The value is TOML-parsed, falling back to a raw string, so the bare
918        // token is read as the mode name.
919        (Some(mode), true) => a.pair("-c", format!("sandbox_mode={mode}")),
920    };
921
922    a.opt("--model", plan.model.as_ref());
923    // Verified against codex-cli 0.145.0: `codex exec` has no effort flag, it
924    // is a config override, and `--strict-config` accepts this key. A bad value
925    // is refused by the provider with its own enum rather than by the CLI.
926    if let Some(effort) = plan.effort.as_ref() {
927        a.pair("-c", format!("model_reasoning_effort={effort}"));
928    }
929    // Codex reads the schema from a file, which the runner writes before the
930    // spawn. `Request::argv` has no file to name, so it shows a placeholder:
931    // the preview is for display, and the real path exists only at spawn time.
932    if plan.schema.is_some() {
933        a.pair(
934            "--output-schema",
935            plan.schema_file.as_deref().unwrap_or("<schema-file>"),
936        );
937    }
938    // `--json` is Codex's event stream and the only place `thread_id` appears.
939    if plan.format != Format::Text {
940        a.bare("--json");
941    }
942    // Codex has no system flag, so the system text rides the prompt. A literal
943    // `-` makes it read the prompt from stdin instead, keeping a large one off
944    // the argv.
945    // Codex takes the prompt as a bare trailing positional, which is exactly
946    // the shape positional redaction guesswork gets wrong.
947    if plan.stdin_prompt {
948        a.arg("-");
949    } else {
950        a.arg_sensitive(Agent::Codex.effective_prompt(plan), Sensitivity::Prompt);
951    }
952    a.done()
953}
954
955/// `copilot -p <prompt> --allow-all-tools [...] [--session-id <uuid>]`
956///
957/// Flags verified against Copilot CLI 1.0.75. Two of its conventions matter:
958/// `--allow-all-tools` is *required* for non-interactive mode, and the
959/// repeatable tool filters are declared `--allow-tool[=tools...]`, an optional
960/// value, which only binds with `=`, never across a space.
961fn argv_copilot(plan: &Plan) -> Vec<Arg> {
962    // Copilot reads stdin as the prompt only when `-p` is absent: a `-p` value
963    // makes the pipe be ignored. So a piped prompt drops the flag entirely.
964    let mut a = Argv::new(&plan.bin);
965    if !plan.stdin_prompt {
966        a.secret(
967            "-p",
968            Agent::Copilot.effective_prompt(plan),
969            Sensitivity::Prompt,
970        );
971    }
972
973    // Without this, a headless run stops at the first tool confirmation.
974    a.bare("--allow-all-tools").bare("--no-ask-user");
975    match plan.permission {
976        Permission::Bypass | Permission::Auto => a.bare("--allow-all-paths"),
977        // Deny beats allow, so this is allow-all minus the mutating tools.
978        // `--allow-all-paths` is deliberately NOT set: it disables path
979        // verification entirely, which would widen filesystem reach in the one
980        // posture that exists to narrow it.
981        Permission::ReadOnly => a.bare("--deny-tool=shell").bare("--deny-tool=write"),
982        // Edits run; shell stays denied so commands cannot.
983        Permission::Edit => a.bare("--deny-tool=shell"),
984        Permission::Plan => a.pair("--mode", "plan"),
985    };
986
987    a.opt("--model", plan.model.as_ref());
988    // Verified against Copilot CLI 1.0.75: `--effort` is the documented spelling
989    // and `--reasoning-effort` its alias (none, minimal, low, medium, high,
990    // xhigh, max). A wider set than Claude's, which is why the level is passed
991    // through rather than mapped to a shared enum.
992    a.opt("--effort", plan.effort.as_ref());
993    // One flag serves both directions: it sets the UUID for a new session and
994    // resumes an existing one by id.
995    match &plan.cont {
996        Continue::NewWith(id) | Continue::Resume(id) => {
997            a.secret("--session-id", id, Sensitivity::SessionId);
998        }
999        // `Fork` is rejected by `Agent::check` before reaching here.
1000        Continue::New | Continue::Fork(_) => {}
1001    }
1002
1003    a.pair(
1004        "--output-format",
1005        if plan.format == Format::Text {
1006            "text"
1007        } else {
1008            // Copilot's `json` is JSONL, so it serves both structured formats.
1009            "json"
1010        },
1011    );
1012    a.done()
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018
1019    fn plan(bin: &str) -> Plan {
1020        Plan {
1021            bin: bin.into(),
1022            prompt: "hi".into(),
1023            system: None,
1024            model: None,
1025            effort: None,
1026            permission: Permission::ReadOnly,
1027            format: Format::Json,
1028            cont: Continue::New,
1029            stdin_prompt: false,
1030            duplex: false,
1031            approvals: false,
1032            schema: None,
1033            schema_file: None,
1034            is_command: false,
1035        }
1036    }
1037
1038    fn argv(agent: Agent, plan: &Plan) -> Vec<String> {
1039        agent.argv(plan).expect("plan is supported")
1040    }
1041
1042    #[test]
1043    fn interactive_capabilities_match_the_supported_request_paths() {
1044        let claude = Agent::Claude.caps();
1045        assert!(claude.live_follow_up);
1046        assert!(claude.approvals);
1047
1048        for agent in [Agent::Codex, Agent::Copilot] {
1049            let caps = agent.caps();
1050            assert!(!caps.live_follow_up, "{agent} cannot take live follow-ups");
1051            assert!(!caps.approvals, "{agent} has no headless approval channel");
1052        }
1053    }
1054
1055    fn pos(a: &[String], needle: &str) -> Option<usize> {
1056        a.iter().position(|s| s == needle)
1057    }
1058
1059    #[test]
1060    fn claude_builds_print_mode_with_format_and_permission() {
1061        let a = argv(Agent::Claude, &plan("claude"));
1062        assert_eq!(a[0..3], ["claude", "-p", "hi"]);
1063        assert!(pos(&a, "--permission-mode").is_some());
1064        assert!(a.contains(&"dontAsk".to_string()));
1065        assert_eq!(a[pos(&a, "--output-format").unwrap() + 1], "json");
1066    }
1067
1068    #[test]
1069    fn claude_read_only_removes_the_mutating_tools() {
1070        let a = argv(Agent::Claude, &plan("claude"));
1071        let at = pos(&a, "--disallowedTools").expect("read-only denies tools");
1072        assert_eq!(
1073            &a[at + 1..at + 5],
1074            ["Bash", "Edit", "Write", "NotebookEdit"]
1075        );
1076    }
1077
1078    /// Each agent takes the level a different way, and Codex takes it as a
1079    /// config override because it has no flag for it at all.
1080    /// The approvals posture rewires how Claude is invoked: the control channel
1081    /// replaces the posture flag, and the prompt leaves the argv because it
1082    /// travels as a JSON message on stdin instead.
1083    #[test]
1084    fn approvals_switch_claude_to_the_control_channel() {
1085        let mut p = plan("claude");
1086        p.approvals = true;
1087        p.permission = Permission::Edit;
1088        let a = argv(Agent::Claude, &p);
1089
1090        assert_eq!(a[pos(&a, "--permission-mode").unwrap() + 1], "manual");
1091        assert_eq!(a[pos(&a, "--permission-prompt-tool").unwrap() + 1], "stdio");
1092        assert_eq!(a[pos(&a, "--input-format").unwrap() + 1], "stream-json");
1093        assert!(
1094            !a.iter().any(|arg| arg == "hi"),
1095            "the prompt must not ride the argv as well: {a:?}"
1096        );
1097        // Suppressing the user's own settings is not part of this: it would
1098        // discard their CLAUDE.md, and a mutating command asks without it.
1099        assert!(
1100            pos(&a, "--setting-sources").is_none(),
1101            "the user's settings stay loaded: {a:?}"
1102        );
1103    }
1104
1105    /// Neither other agent has a headless approval channel, so asking must fail
1106    /// loudly. A run that quietly never asked is the dangerous outcome: silence
1107    /// would read as "nothing needed approval".
1108    #[test]
1109    fn agents_without_an_approval_channel_refuse_before_spawning() {
1110        let mut p = plan("x");
1111        p.approvals = true;
1112        p.permission = Permission::Edit;
1113        for agent in [Agent::Codex, Agent::Copilot] {
1114            assert!(
1115                matches!(agent.typed_argv(&p), Err(Error::Unsupported { .. })),
1116                "{agent} should refuse to pretend it can ask"
1117            );
1118        }
1119        assert!(Agent::Claude.typed_argv(&p).is_ok());
1120    }
1121
1122    /// Read-only removes the mutating tools outright, so there is nothing left
1123    /// to ask about. Opting into approvals there would mean never being asked,
1124    /// which reads as "the agent wanted nothing".
1125    #[test]
1126    fn approvals_under_read_only_are_refused_rather_than_silent() {
1127        let mut p = plan("claude");
1128        p.approvals = true;
1129        p.permission = Permission::ReadOnly;
1130        assert!(matches!(
1131            Agent::Claude.typed_argv(&p),
1132            Err(Error::Unsupported { .. })
1133        ));
1134
1135        // Every posture that leaves the tools in place is fine.
1136        for permission in [Permission::Edit, Permission::Auto, Permission::Bypass] {
1137            p.permission = permission;
1138            assert!(
1139                Agent::Claude.typed_argv(&p).is_ok(),
1140                "{permission:?} should allow approvals"
1141            );
1142        }
1143    }
1144
1145    /// Interactive alone opens the message channel without switching the
1146    /// permission posture: a caller who wants to send follow-ups is not
1147    /// thereby asking to be prompted about every tool.
1148    #[test]
1149    fn interactive_opens_the_channel_without_changing_the_posture() {
1150        let mut p = plan("claude");
1151        p.duplex = true;
1152        p.permission = Permission::Edit;
1153        let a = argv(Agent::Claude, &p);
1154
1155        assert_eq!(a[pos(&a, "--input-format").unwrap() + 1], "stream-json");
1156        assert_eq!(a[pos(&a, "--permission-mode").unwrap() + 1], "acceptEdits");
1157        assert!(
1158            pos(&a, "--permission-prompt-tool").is_none(),
1159            "no approval channel was asked for: {a:?}"
1160        );
1161        assert!(
1162            !a.iter().any(|arg| arg == "hi"),
1163            "the prompt travels as a stdin message: {a:?}"
1164        );
1165    }
1166
1167    /// Approvals need the same open channel, so they imply it. Checked on a
1168    /// hand-built `Plan` because the builder is not the only way to make one.
1169    #[test]
1170    fn approvals_imply_the_open_channel_even_without_the_builder() {
1171        let mut p = plan("claude");
1172        p.approvals = true;
1173        p.duplex = false;
1174        p.permission = Permission::Edit;
1175        let a = argv(Agent::Claude, &p);
1176        assert_eq!(a[pos(&a, "--input-format").unwrap() + 1], "stream-json");
1177    }
1178
1179    /// Neither other agent reads a structured message stream on stdin.
1180    #[test]
1181    fn agents_that_cannot_take_a_follow_up_refuse_before_spawning() {
1182        let mut p = plan("x");
1183        p.duplex = true;
1184        for agent in [Agent::Codex, Agent::Copilot] {
1185            assert!(
1186                matches!(agent.typed_argv(&p), Err(Error::Unsupported { .. })),
1187                "{agent} cannot be sent a second message mid-turn"
1188            );
1189        }
1190    }
1191
1192    /// An ordinary run is untouched, so nothing about the default path changes.
1193    #[test]
1194    fn without_approvals_claude_keeps_its_posture_flag() {
1195        let mut p = plan("claude");
1196        p.permission = Permission::ReadOnly;
1197        let a = argv(Agent::Claude, &p);
1198        assert_eq!(a[pos(&a, "--permission-mode").unwrap() + 1], "dontAsk");
1199        assert!(pos(&a, "--permission-prompt-tool").is_none());
1200    }
1201
1202    #[test]
1203    fn effort_reaches_each_cli_the_way_that_cli_takes_it() {
1204        let mut p = plan("x");
1205        p.effort = Some("xhigh".into());
1206
1207        let claude = argv(Agent::Claude, &p);
1208        assert_eq!(claude[pos(&claude, "--effort").unwrap() + 1], "xhigh");
1209
1210        let copilot = argv(Agent::Copilot, &p);
1211        assert_eq!(copilot[pos(&copilot, "--effort").unwrap() + 1], "xhigh");
1212
1213        let codex = argv(Agent::Codex, &p);
1214        assert!(
1215            pos(&codex, "--effort").is_none(),
1216            "codex has no effort flag: {codex:?}"
1217        );
1218        assert!(
1219            codex
1220                .windows(2)
1221                .any(|w| w[0] == "-c" && w[1] == "model_reasoning_effort=xhigh"),
1222            "codex takes it as a config override: {codex:?}"
1223        );
1224    }
1225
1226    /// An unset effort must add nothing, so the agent keeps its own default.
1227    #[test]
1228    fn no_effort_means_no_flag() {
1229        let p = plan("x");
1230        for agent in [Agent::Claude, Agent::Codex, Agent::Copilot] {
1231            let a = argv(agent, &p);
1232            assert!(pos(&a, "--effort").is_none(), "{agent}: {a:?}");
1233            assert!(
1234                !a.iter()
1235                    .any(|arg| arg.starts_with("model_reasoning_effort")),
1236                "{agent}: {a:?}"
1237            );
1238        }
1239    }
1240
1241    #[test]
1242    fn claude_bypass_does_not_deny_tools() {
1243        let mut p = plan("claude");
1244        p.permission = Permission::Bypass;
1245        let a = argv(Agent::Claude, &p);
1246        assert!(a.contains(&"bypassPermissions".to_string()));
1247        assert!(pos(&a, "--disallowedTools").is_none());
1248    }
1249
1250    #[test]
1251    fn claude_stream_format_adds_verbose_but_json_does_not() {
1252        let mut p = plan("claude");
1253        p.format = Format::Stream;
1254        assert!(argv(Agent::Claude, &p).contains(&"--verbose".to_string()));
1255        p.format = Format::Json;
1256        assert!(!argv(Agent::Claude, &p).contains(&"--verbose".to_string()));
1257    }
1258
1259    #[test]
1260    fn claude_mints_an_id_for_a_new_session_and_resumes_an_old_one() {
1261        let mut p = plan("claude");
1262        p.cont = Continue::NewWith("11111111-2222-3333-4444-555555555555".into());
1263        let a = argv(Agent::Claude, &p);
1264        assert_eq!(
1265            a[pos(&a, "--session-id").unwrap() + 1],
1266            "11111111-2222-3333-4444-555555555555"
1267        );
1268        assert!(pos(&a, "--resume").is_none());
1269
1270        p.cont = Continue::Resume("sess-1".into());
1271        let a = argv(Agent::Claude, &p);
1272        assert_eq!(a[pos(&a, "--resume").unwrap() + 1], "sess-1");
1273        assert!(!a.contains(&"--fork-session".to_string()));
1274    }
1275
1276    #[test]
1277    fn claude_fork_resumes_and_branches() {
1278        let mut p = plan("claude");
1279        p.cont = Continue::Fork("sess-1".into());
1280        let a = argv(Agent::Claude, &p);
1281        assert_eq!(a[pos(&a, "--resume").unwrap() + 1], "sess-1");
1282        assert!(a.contains(&"--fork-session".to_string()));
1283    }
1284
1285    #[test]
1286    fn claude_keeps_the_system_prompt_on_its_own_flag() {
1287        let mut p = plan("claude");
1288        p.system = Some("be terse".into());
1289        let a = argv(Agent::Claude, &p);
1290        assert_eq!(
1291            a[pos(&a, "--append-system-prompt").unwrap() + 1],
1292            "be terse"
1293        );
1294        // The prompt itself stays clean.
1295        assert!(a.contains(&"hi".to_string()));
1296    }
1297
1298    #[test]
1299    fn claude_stdin_prompt_leaves_the_argv() {
1300        let mut p = plan("claude");
1301        p.stdin_prompt = true;
1302        let a = argv(Agent::Claude, &p);
1303        assert_eq!(a[pos(&a, "--input-format").unwrap() + 1], "text");
1304        assert!(!a.contains(&"hi".to_string()), "prompt must not ride argv");
1305    }
1306
1307    #[test]
1308    fn codex_resume_is_a_subcommand_and_prompt_is_last() {
1309        let mut p = plan("codex");
1310        p.cont = Continue::Resume("thread-9".into());
1311        let a = argv(Agent::Codex, &p);
1312        assert_eq!(a[0..4], ["codex", "exec", "resume", "thread-9"]);
1313        assert_eq!(a.last().unwrap(), "hi");
1314    }
1315
1316    /// `Minimal` exists to withhold secrets, so nothing it passes through may
1317    /// be a credential carrier. Proxy URLs in particular routinely embed
1318    /// `user:pass`, which is why they are offered separately instead.
1319    #[test]
1320    fn the_minimal_environment_carries_no_proxy_variables() {
1321        for agent in Agent::ALL {
1322            let essential = agent.essential_env();
1323            for name in NETWORK_ENV {
1324                assert!(
1325                    !essential.contains(name),
1326                    "{agent} would pass {name} through EnvPolicy::Minimal"
1327                );
1328            }
1329        }
1330    }
1331
1332    /// The floor verified live on macOS: with exactly these set, all three CLIs
1333    /// authenticate and answer. Claude reports "Not logged in" without `USER`.
1334    #[test]
1335    fn every_agent_asks_for_the_verified_floor() {
1336        for agent in Agent::ALL {
1337            let essential = agent.essential_env();
1338            for name in ["PATH", "HOME", "USER"] {
1339                assert!(essential.contains(&name), "{agent} omits {name}");
1340            }
1341        }
1342    }
1343
1344    /// Each agent's own credentials, and nobody else's.
1345    #[test]
1346    fn agents_do_not_request_each_others_credentials() {
1347        let claude = Agent::Claude.essential_env();
1348        assert!(claude.contains(&"ANTHROPIC_API_KEY"));
1349        assert!(!claude.contains(&"OPENAI_API_KEY"));
1350        assert!(!claude.contains(&"GH_TOKEN"));
1351
1352        let codex = Agent::Codex.essential_env();
1353        assert!(codex.contains(&"OPENAI_API_KEY"));
1354        assert!(!codex.contains(&"ANTHROPIC_API_KEY"));
1355    }
1356
1357    /// The model is the caller's choice on every agent. It is forwarded
1358    /// verbatim and never defaulted, normalized, or validated here: a host with
1359    /// a model picker owns that list, and an unknown name must surface as the
1360    /// agent's own error rather than something this crate guessed at.
1361    #[test]
1362    fn every_agent_forwards_the_callers_model_verbatim() {
1363        for agent in Agent::ALL {
1364            let mut p = plan(agent.bin());
1365            // Deliberately not a real model id: nothing here may interpret it.
1366            p.model = Some("some-model-9".into());
1367            let a = argv(agent, &p);
1368            let at = pos(&a, "--model").unwrap_or_else(|| panic!("{agent} dropped --model: {a:?}"));
1369            assert_eq!(a[at + 1], "some-model-9", "{agent} rewrote the model");
1370        }
1371    }
1372
1373    /// No model means the agent picks its own, so a host can offer a "default"
1374    /// entry without this crate inventing one.
1375    #[test]
1376    fn no_model_means_no_model_flag() {
1377        for agent in Agent::ALL {
1378            let p = plan(agent.bin());
1379            assert!(p.model.is_none());
1380            let a = argv(agent, &p);
1381            assert!(
1382                pos(&a, "--model").is_none(),
1383                "{agent} invented a model: {a:?}"
1384            );
1385        }
1386    }
1387
1388    /// `codex exec` aborts outside a git repository. A host embedding this
1389    /// crate runs against scratch dirs and review checkouts, so the check is
1390    /// waived on every invocation; the sandbox is what actually contains a run.
1391    #[test]
1392    fn codex_always_waives_the_git_repo_check() {
1393        for cont in [Continue::New, Continue::Resume("t-1".into())] {
1394            let mut p = plan("codex");
1395            p.cont = cont.clone();
1396            assert!(
1397                argv(Agent::Codex, &p).contains(&"--skip-git-repo-check".to_string()),
1398                "{cont:?} must still run outside a repo"
1399            );
1400        }
1401    }
1402
1403    /// `codex exec resume` rejects `--sandbox` and takes `-c sandbox_mode=`
1404    /// instead. Getting this wrong makes every second turn fail with an
1405    /// "unexpected argument" error, which only a multi-turn run reveals.
1406    /// The two CLIs take a schema differently, and the difference is the
1407    /// whole reason this needs handling rather than one shared flag.
1408    #[test]
1409    fn each_agent_takes_a_schema_in_its_own_shape() {
1410        let schema = r#"{"type":"object"}"#;
1411
1412        let mut claude = plan("claude");
1413        claude.schema = Some(schema.into());
1414        let a = argv(Agent::Claude, &claude);
1415        assert_eq!(
1416            a[pos(&a, "--json-schema").unwrap() + 1],
1417            schema,
1418            "claude takes it inline"
1419        );
1420
1421        let mut codex = plan("codex");
1422        codex.schema = Some(schema.into());
1423        codex.schema_file = Some("/tmp/s.json".into());
1424        let a = argv(Agent::Codex, &codex);
1425        assert_eq!(
1426            a[pos(&a, "--output-schema").unwrap() + 1],
1427            "/tmp/s.json",
1428            "codex takes a path, never the schema itself"
1429        );
1430        assert!(!a.iter().any(|arg| arg.contains("\"type\"")));
1431    }
1432
1433    /// Copilot 1.0.75 has no schema flag, and a prose answer presented as data
1434    /// is exactly the silent downgrade this crate refuses elsewhere.
1435    #[test]
1436    fn copilot_refuses_a_schema_rather_than_answering_in_prose() {
1437        let mut p = plan("copilot");
1438        p.schema = Some(r#"{"type":"object"}"#.into());
1439        assert!(matches!(
1440            Agent::Copilot.argv(&p),
1441            Err(Error::Unsupported { .. })
1442        ));
1443    }
1444
1445    /// A caller inspecting the command before running it has no file yet, since
1446    /// it is written at spawn time.
1447    #[test]
1448    fn a_codex_schema_preview_shows_a_placeholder_path() {
1449        let mut p = plan("codex");
1450        p.schema = Some(r#"{"type":"object"}"#.into());
1451        let a = argv(Agent::Codex, &p);
1452        assert_eq!(a[pos(&a, "--output-schema").unwrap() + 1], "<schema-file>");
1453    }
1454
1455    #[test]
1456    fn codex_sets_the_sandbox_by_flag_when_fresh_and_by_config_when_resuming() {
1457        let mut fresh = plan("codex");
1458        fresh.permission = Permission::ReadOnly;
1459        let a = argv(Agent::Codex, &fresh);
1460        assert_eq!(a[pos(&a, "--sandbox").unwrap() + 1], "read-only");
1461        assert!(pos(&a, "-c").is_none());
1462
1463        let mut resumed = fresh.clone();
1464        resumed.cont = Continue::Resume("thread-9".into());
1465        let a = argv(Agent::Codex, &resumed);
1466        assert!(
1467            pos(&a, "--sandbox").is_none(),
1468            "resume rejects --sandbox: {a:?}"
1469        );
1470        assert_eq!(a[pos(&a, "-c").unwrap() + 1], "sandbox_mode=read-only");
1471    }
1472
1473    #[test]
1474    fn codex_bypass_uses_the_same_flag_on_both_paths() {
1475        for cont in [Continue::New, Continue::Resume("t".into())] {
1476            let mut p = plan("codex");
1477            p.permission = Permission::Bypass;
1478            p.cont = cont.clone();
1479            let a = argv(Agent::Codex, &p);
1480            assert!(a.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
1481            assert!(pos(&a, "--sandbox").is_none(), "{cont:?}: {a:?}");
1482        }
1483    }
1484
1485    #[test]
1486    fn codex_without_a_system_flag_prepends_it_to_the_prompt() {
1487        let mut p = plan("codex");
1488        p.system = Some("be terse".into());
1489        let a = argv(Agent::Codex, &p);
1490        assert_eq!(a.last().unwrap(), "be terse\n\nhi");
1491    }
1492
1493    #[test]
1494    fn codex_maps_each_posture_to_a_sandbox() {
1495        for (perm, expect) in [
1496            (Permission::ReadOnly, "read-only"),
1497            (Permission::Plan, "read-only"),
1498            (Permission::Edit, "workspace-write"),
1499            (Permission::Auto, "workspace-write"),
1500        ] {
1501            let mut p = plan("codex");
1502            p.permission = perm;
1503            let a = argv(Agent::Codex, &p);
1504            assert_eq!(a[pos(&a, "--sandbox").unwrap() + 1], expect, "{perm:?}");
1505        }
1506        let mut p = plan("codex");
1507        p.permission = Permission::Bypass;
1508        let a = argv(Agent::Codex, &p);
1509        assert!(a.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
1510        assert!(pos(&a, "--sandbox").is_none());
1511    }
1512
1513    #[test]
1514    fn copilot_drops_dash_p_when_the_prompt_is_piped() {
1515        let mut p = plan("copilot");
1516        p.stdin_prompt = true;
1517        let a = argv(Agent::Copilot, &p);
1518        assert!(
1519            !a.contains(&"-p".to_string()),
1520            "a -p value shadows the pipe"
1521        );
1522        assert!(!a.contains(&"hi".to_string()));
1523    }
1524
1525    /// Copilot declares its tool filters as `--deny-tool[=tools...]`, an
1526    /// optional value, which binds only with `=`. Passed across a space the
1527    /// value is silently read as a positional instead, so the deny is lost.
1528    #[test]
1529    fn copilot_read_only_denies_shell_and_write_with_the_combined_form() {
1530        let a = argv(Agent::Copilot, &plan("copilot"));
1531        assert!(a.contains(&"--deny-tool=shell".to_string()));
1532        assert!(a.contains(&"--deny-tool=write".to_string()));
1533        assert!(
1534            !a.iter().any(|s| s == "--deny-tool"),
1535            "a bare --deny-tool would drop its value: {a:?}"
1536        );
1537    }
1538
1539    /// A headless Copilot run stalls at the first tool confirmation without it.
1540    #[test]
1541    fn copilot_always_allows_tools_and_silences_the_ask_tool() {
1542        for permission in [Permission::ReadOnly, Permission::Plan, Permission::Bypass] {
1543            let mut p = plan("copilot");
1544            p.permission = permission;
1545            let a = argv(Agent::Copilot, &p);
1546            assert!(
1547                a.contains(&"--allow-all-tools".to_string()),
1548                "{permission:?}"
1549            );
1550            assert!(a.contains(&"--no-ask-user".to_string()), "{permission:?}");
1551        }
1552    }
1553
1554    /// Copilot uses one flag in both directions: it sets the id for a new
1555    /// session and resumes an existing one.
1556    #[test]
1557    fn copilot_uses_session_id_for_both_new_and_resumed_sessions() {
1558        for cont in [
1559            Continue::NewWith("11111111-2222-3333-4444-555555555555".into()),
1560            Continue::Resume("11111111-2222-3333-4444-555555555555".into()),
1561        ] {
1562            let mut p = plan("copilot");
1563            p.cont = cont.clone();
1564            let a = argv(Agent::Copilot, &p);
1565            assert_eq!(
1566                a[pos(&a, "--session-id").unwrap() + 1],
1567                "11111111-2222-3333-4444-555555555555",
1568                "{cont:?}"
1569            );
1570        }
1571    }
1572
1573    #[test]
1574    fn unsupported_capabilities_are_refused_not_downgraded() {
1575        // Forking headlessly is Claude-only.
1576        for agent in [Agent::Codex, Agent::Copilot] {
1577            let mut p = plan(agent.bin());
1578            p.cont = Continue::Fork("s".into());
1579            assert!(
1580                matches!(agent.argv(&p), Err(Error::Unsupported { .. })),
1581                "{agent} must refuse a fork rather than resume linearly"
1582            );
1583        }
1584        // Codex's id is printed, not assigned, so it cannot be chosen up front.
1585        let mut p = plan("codex");
1586        p.cont = Continue::NewWith("id".into());
1587        assert!(matches!(
1588            Agent::Codex.argv(&p),
1589            Err(Error::Unsupported { .. })
1590        ));
1591    }
1592
1593    /// The failure mode this refusal exists to prevent is a silent one: an
1594    /// agent with no command vocabulary reads `/compact` as prose and answers a
1595    /// question *about* compaction, which looks from the outside exactly like
1596    /// the command having run.
1597    #[test]
1598    fn a_slash_command_is_refused_by_agents_that_only_read_prose() {
1599        for agent in [Agent::Codex, Agent::Copilot] {
1600            let mut p = plan(agent.bin());
1601            p.is_command = true;
1602            assert!(
1603                matches!(agent.argv(&p), Err(Error::Unsupported { .. })),
1604                "{agent} must refuse a slash command rather than send it as text"
1605            );
1606        }
1607        let mut p = plan("claude");
1608        p.is_command = true;
1609        assert!(
1610            Agent::Claude.argv(&p).is_ok(),
1611            "Claude publishes a catalogue and acts on them"
1612        );
1613    }
1614
1615    /// All three expose an id, so all three can back a named session, but only
1616    /// through a format that actually carries one.
1617    #[test]
1618    fn every_agent_has_a_format_that_carries_its_session_id() {
1619        assert_eq!(Agent::Claude.session_format(), Some(Format::Json));
1620        assert_eq!(Agent::Codex.session_format(), Some(Format::Stream));
1621        assert_eq!(Agent::Copilot.session_format(), Some(Format::Stream));
1622    }
1623
1624    /// Claude and Copilot let the caller assign the id, so a run that dies
1625    /// mid-turn still leaves a resumable session.
1626    #[test]
1627    fn the_minting_agents_are_claude_and_copilot() {
1628        let minting: Vec<_> = Agent::ALL
1629            .into_iter()
1630            .filter(|a| a.caps().session == SessionSupport::Minted)
1631            .collect();
1632        assert_eq!(minting, [Agent::Claude, Agent::Copilot]);
1633    }
1634}