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