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