Skip to main content

codex_wrapper/command/
exec.rs

1use crate::Codex;
2use crate::command::CodexCommand;
3#[cfg(feature = "json")]
4use crate::error::Error;
5use crate::error::Result;
6use crate::exec::{self, CommandOutput};
7use crate::rollout_budget::RolloutBudgetConfig;
8use crate::types::{ApprovalPolicyConfig, Color, SandboxMode, WebSearchMode};
9#[cfg(feature = "json")]
10use crate::types::{JsonLineEvent, QueryResult};
11
12/// Push the typed config-key overrides shared by the exec-family builders.
13///
14/// `codex-cli` 0.145.0 removed `--ask-for-approval` and `--search` from the
15/// exec family; both settings moved to `-c` config keys. These are pushed
16/// before any caller-supplied [`config`](ExecCommand::config) strings because
17/// `-c` is last-wins, so a raw override still beats the typed setter.
18pub(crate) fn push_typed_config(
19    args: &mut Vec<String>,
20    approval_policy: Option<ApprovalPolicyConfig>,
21    web_search: Option<WebSearchMode>,
22) {
23    if let Some(policy) = approval_policy {
24        args.push("-c".into());
25        args.push(format!("approval_policy=\"{}\"", policy.as_config_value()));
26    }
27    if let Some(mode) = web_search {
28        args.push("-c".into());
29        args.push(format!("web_search=\"{}\"", mode.as_config_value()));
30    }
31}
32
33/// Resolve the sandbox mode, folding in the deprecated `full_auto` shim.
34///
35/// `--full-auto` is hidden on the exec family (and rejected outright by `fork`
36/// and `resume`); the CLI's own advice is `--sandbox workspace-write`. An
37/// explicit `sandbox()` call is more specific and wins.
38pub(crate) fn effective_sandbox(
39    sandbox: Option<SandboxMode>,
40    full_auto: bool,
41) -> Option<SandboxMode> {
42    sandbox.or(full_auto.then_some(SandboxMode::WorkspaceWrite))
43}
44
45/// Run Codex non-interactively (`codex exec <prompt>`).
46///
47/// This is the primary command for programmatic use. It supports the full
48/// range of exec flags: model selection, sandbox policy, images, config
49/// overrides, feature flags, JSON output, and more.
50///
51/// # Example
52///
53/// ```no_run
54/// use codex_wrapper::{Codex, CodexCommand, ExecCommand, SandboxMode};
55///
56/// # async fn example() -> codex_wrapper::Result<()> {
57/// let codex = Codex::builder().build()?;
58/// let output = ExecCommand::new("fix the failing test")
59///     .model("o3")
60///     .sandbox(SandboxMode::WorkspaceWrite)
61///     .ephemeral()
62///     .execute(&codex)
63///     .await?;
64/// println!("{}", output.stdout);
65/// # Ok(())
66/// # }
67/// ```
68#[derive(Debug, Clone)]
69pub struct ExecCommand {
70    approve_for_me: bool,
71    prompt: Option<String>,
72    prompt_via_stdin: bool,
73    approval_policy: Option<ApprovalPolicyConfig>,
74    web_search: Option<WebSearchMode>,
75    config_overrides: Vec<String>,
76    enabled_features: Vec<String>,
77    disabled_features: Vec<String>,
78    rollout_budget: Option<RolloutBudgetConfig>,
79    images: Vec<String>,
80    model: Option<String>,
81    oss: bool,
82    local_provider: Option<String>,
83    sandbox: Option<SandboxMode>,
84    strict_config: bool,
85    dangerously_bypass_hook_trust: bool,
86    ignore_user_config: bool,
87    ignore_rules: bool,
88    profile: Option<String>,
89    full_auto: bool,
90    dangerously_bypass_approvals_and_sandbox: bool,
91    cd: Option<String>,
92    skip_git_repo_check: bool,
93    add_dirs: Vec<String>,
94    ephemeral: bool,
95    output_schema: Option<String>,
96    color: Option<Color>,
97    json: bool,
98    output_last_message: Option<String>,
99    extra_args: Vec<String>,
100    retry_policy: Option<crate::retry::RetryPolicy>,
101}
102
103impl ExecCommand {
104    /// Create a new exec command with the given prompt.
105    #[must_use]
106    pub fn new(prompt: impl Into<String>) -> Self {
107        Self {
108            approve_for_me: false,
109            prompt: Some(prompt.into()),
110            prompt_via_stdin: false,
111            approval_policy: None,
112            web_search: None,
113            config_overrides: Vec::new(),
114            enabled_features: Vec::new(),
115            disabled_features: Vec::new(),
116            rollout_budget: None,
117            images: Vec::new(),
118            model: None,
119            oss: false,
120            local_provider: None,
121            sandbox: None,
122            strict_config: false,
123            dangerously_bypass_hook_trust: false,
124            ignore_user_config: false,
125            ignore_rules: false,
126            profile: None,
127            full_auto: false,
128            dangerously_bypass_approvals_and_sandbox: false,
129            cd: None,
130            skip_git_repo_check: false,
131            add_dirs: Vec::new(),
132            ephemeral: false,
133            output_schema: None,
134            color: None,
135            json: false,
136            output_last_message: None,
137            extra_args: Vec::new(),
138            retry_policy: None,
139        }
140    }
141
142    /// Send the prompt on stdin instead of as an argument (`codex exec -`).
143    ///
144    /// Shorthand for [`new`](Self::new) followed by
145    /// [`prompt_via_stdin`](Self::prompt_via_stdin). Use it for prompts that
146    /// are large or awkward to pass through argv.
147    ///
148    /// ```no_run
149    /// use codex_wrapper::{Codex, CodexCommand, ExecCommand};
150    ///
151    /// # async fn example() -> codex_wrapper::Result<()> {
152    /// let codex = Codex::builder().build()?;
153    /// let diff = std::fs::read_to_string("huge.patch")?;
154    /// let output = ExecCommand::from_stdin(format!("Review this patch:\n{diff}"))
155    ///     .execute(&codex)
156    ///     .await?;
157    /// # let _ = output;
158    /// # Ok(())
159    /// # }
160    /// ```
161    ///
162    /// Before 0.3 this took no argument and set the prompt to the literal
163    /// `-`, which could not work: nothing wrote to the child's stdin, so the
164    /// CLI saw an immediate EOF and an empty prompt (#81).
165    #[must_use]
166    pub fn from_stdin(prompt: impl Into<String>) -> Self {
167        Self::new(prompt).prompt_via_stdin()
168    }
169
170    /// Deliver this command's prompt on stdin rather than in argv.
171    ///
172    /// The prompt is replaced by `-` in the argument list and written to the
173    /// child's stdin instead.
174    ///
175    /// Retry does not apply to a stdin prompt, and any policy set on the
176    /// command or the client is ignored for it. A second attempt would need to
177    /// write the prompt again, into a pipe the first attempt has already
178    /// consumed, and retrying with an empty stdin would be worse than not
179    /// retrying.
180    #[must_use]
181    pub fn prompt_via_stdin(mut self) -> Self {
182        self.prompt_via_stdin = true;
183        self
184    }
185
186    /// The prompt to write to the child's stdin, if this command sends it
187    /// there. `None` when the prompt travels in argv.
188    ///
189    /// Only the streaming path needs this, and that path is `json`-gated.
190    #[cfg(feature = "json")]
191    pub(crate) fn stdin_prompt(&self) -> Option<&str> {
192        self.prompt_via_stdin
193            .then(|| self.prompt.as_deref().unwrap_or_default())
194    }
195
196    /// Override a config key (`-c key=value`).
197    ///
198    /// May be called multiple times to set several keys. Because `-c` is
199    /// last-wins, a key set here overrides the same key set by
200    /// [`approval_policy`](Self::approval_policy) or
201    /// [`search_mode`](Self::search_mode).
202    #[must_use]
203    pub fn config(mut self, key_value: impl Into<String>) -> Self {
204        self.config_overrides.push(key_value.into());
205        self
206    }
207
208    /// Set when the model asks for approval (`-c approval_policy="<value>"`).
209    ///
210    /// `codex-cli` 0.145.0 removed `--ask-for-approval` from `codex exec`; the
211    /// config key is the supported equivalent. Accepts an
212    /// [`ApprovalPolicy`](crate::ApprovalPolicy) directly, or an
213    /// [`ApprovalPolicyConfig`] for the two values the flag never took.
214    ///
215    /// ```
216    /// use codex_wrapper::{ApprovalPolicyConfig, CodexCommand, ExecCommand};
217    ///
218    /// let args = ExecCommand::new("hi")
219    ///     .approval_policy(ApprovalPolicyConfig::Never)
220    ///     .args();
221    /// assert!(args.windows(2).any(|w| w == ["-c", "approval_policy=\"never\""]));
222    /// ```
223    #[must_use]
224    pub fn approval_policy(mut self, policy: impl Into<ApprovalPolicyConfig>) -> Self {
225        self.approval_policy = Some(policy.into());
226        self
227    }
228
229    /// Enable live web search.
230    ///
231    /// Shorthand for `search_mode(WebSearchMode::Live)`, which is what the
232    /// removed `--search` flag meant.
233    #[must_use]
234    pub fn search(self) -> Self {
235        self.search_mode(WebSearchMode::Live)
236    }
237
238    /// Set the web search mode (`-c web_search="<value>"`).
239    ///
240    /// `codex-cli` 0.145.0 removed `--search` from `codex exec`; the config
241    /// key is the supported equivalent, and it is an enum rather than the
242    /// flag's boolean.
243    #[must_use]
244    pub fn search_mode(mut self, mode: WebSearchMode) -> Self {
245        self.web_search = Some(mode);
246        self
247    }
248
249    /// Enable an optional feature flag (`--enable <feature>`).
250    ///
251    /// May be called multiple times.
252    #[must_use]
253    pub fn enable(mut self, feature: impl Into<String>) -> Self {
254        self.enabled_features.push(feature.into());
255        self
256    }
257
258    /// Disable an optional feature flag (`--disable <feature>`).
259    ///
260    /// May be called multiple times.
261    #[must_use]
262    pub fn disable(mut self, feature: impl Into<String>) -> Self {
263        self.disabled_features.push(feature.into());
264        self
265    }
266
267    /// Enforce a Codex-native rollout-unit budget for this execution.
268    ///
269    /// Codex checks the budget at response boundaries, so one response can
270    /// cross the limit before the run stops. Codex 0.145-0.146 use weighted
271    /// output and non-cached input; starting with 0.147, a provider-supplied
272    /// rollout-unit value takes precedence when available. Neither is
273    /// portable total-token usage. See [`RolloutBudgetConfig`] for the exact
274    /// versioned contract.
275    ///
276    /// This typed override is emitted after raw config, and conflicting
277    /// `rollout_budget` feature toggles from both this command and its
278    /// [`crate::Codex`] client are suppressed. Codex applies feature toggles
279    /// after every `-c` value regardless of argv order, so retaining either
280    /// toggle would otherwise disable or replace this table.
281    #[must_use]
282    pub fn rollout_budget(mut self, budget: RolloutBudgetConfig) -> Self {
283        self.rollout_budget = Some(budget);
284        self
285    }
286
287    /// Attach an image to the prompt (`--image <path>`).
288    ///
289    /// May be called multiple times to attach several images.
290    #[must_use]
291    pub fn image(mut self, path: impl Into<String>) -> Self {
292        self.images.push(path.into());
293        self
294    }
295
296    /// Set the model to use (`--model <model>`).
297    ///
298    /// Panics if `model` is an empty string.
299    #[must_use]
300    pub fn model(mut self, model: impl Into<String>) -> Self {
301        let model = model.into();
302        assert!(!model.is_empty(), "model name must not be empty");
303        self.model = Some(model);
304        self
305    }
306
307    /// Use the OSS model tier (`--oss`).
308    #[must_use]
309    pub fn oss(mut self) -> Self {
310        self.oss = true;
311        self
312    }
313
314    /// Use a local model provider (`--local-provider <provider>`).
315    #[must_use]
316    pub fn local_provider(mut self, provider: impl Into<String>) -> Self {
317        self.local_provider = Some(provider.into());
318        self
319    }
320
321    /// Set the sandbox policy (`--sandbox <mode>`).
322    #[must_use]
323    pub fn sandbox(mut self, sandbox: SandboxMode) -> Self {
324        self.sandbox = Some(sandbox);
325        self
326    }
327
328    /// Error on unrecognized config keys (`--strict-config`).
329    #[must_use]
330    pub fn strict_config(mut self) -> Self {
331        self.strict_config = true;
332        self
333    }
334
335    /// Bypass the hook trust prompt (`--dangerously-bypass-hook-trust`).
336    ///
337    /// Allows configured hooks to run without confirmation. Use with caution.
338    #[must_use]
339    pub(crate) fn set_bypass_hook_trust(mut self) -> Self {
340        self.dangerously_bypass_hook_trust = true;
341        self
342    }
343
344    /// Ignore the user-level config file (`--ignore-user-config`).
345    #[must_use]
346    pub fn ignore_user_config(mut self) -> Self {
347        self.ignore_user_config = true;
348        self
349    }
350
351    /// Ignore project rules files (`--ignore-rules`).
352    #[must_use]
353    pub fn ignore_rules(mut self) -> Self {
354        self.ignore_rules = true;
355        self
356    }
357
358    /// Select a named configuration profile (`--profile <name>`).
359    #[must_use]
360    pub fn profile(mut self, profile: impl Into<String>) -> Self {
361        self.profile = Some(profile.into());
362        self
363    }
364
365    /// Run in full-auto mode, emitted as `--sandbox workspace-write`.
366    ///
367    /// `--full-auto` is deprecated upstream. `codex-cli` 0.145.0 hides it from
368    /// `codex exec --help` and warns when it is used:
369    ///
370    /// ```text
371    /// warning: `--full-auto` is deprecated; use `--sandbox workspace-write` instead.
372    /// ```
373    ///
374    /// This method emits the replacement the CLI names. An explicit
375    /// [`sandbox`](Self::sandbox) call is more specific and wins over it.
376    #[must_use]
377    pub fn full_auto(mut self) -> Self {
378        self.full_auto = true;
379        self
380    }
381
382    /// Route approval requests through automatic review, using the
383    /// workspace-write sandbox (`--approve-for-me`).
384    ///
385    /// Added in `codex-cli` 0.147.0. Older releases reject it as an unexpected
386    /// argument, so this is the one builder method with a floor above the
387    /// wrapper's tested minimum. `codex exec review` and `codex exec resume`
388    /// do not accept it.
389    #[must_use]
390    pub fn approve_for_me(mut self) -> Self {
391        self.approve_for_me = true;
392        self
393    }
394
395    /// Bypass all approval prompts and sandbox restrictions.
396    ///
397    /// Passes `--dangerously-bypass-approvals-and-sandbox`. Use with caution.
398    #[must_use]
399    pub(crate) fn set_bypass_approvals_and_sandbox(mut self) -> Self {
400        self.dangerously_bypass_approvals_and_sandbox = true;
401        self
402    }
403
404    /// Change the working directory before running (`--cd <dir>`).
405    #[must_use]
406    pub fn cd(mut self, dir: impl Into<String>) -> Self {
407        self.cd = Some(dir.into());
408        self
409    }
410
411    /// Skip the git repository check (`--skip-git-repo-check`).
412    #[must_use]
413    pub fn skip_git_repo_check(mut self) -> Self {
414        self.skip_git_repo_check = true;
415        self
416    }
417
418    /// Add an extra directory to the context (`--add-dir <dir>`).
419    ///
420    /// May be called multiple times.
421    #[must_use]
422    pub fn add_dir(mut self, dir: impl Into<String>) -> Self {
423        self.add_dirs.push(dir.into());
424        self
425    }
426
427    /// Run in ephemeral mode — no session is persisted (`--ephemeral`).
428    #[must_use]
429    pub fn ephemeral(mut self) -> Self {
430        self.ephemeral = true;
431        self
432    }
433
434    /// Require output to conform to a JSON schema (`--output-schema <path>`).
435    #[must_use]
436    pub fn output_schema(mut self, path: impl Into<String>) -> Self {
437        self.output_schema = Some(path.into());
438        self
439    }
440
441    /// Control terminal color output (`--color <mode>`).
442    #[must_use]
443    pub fn color(mut self, color: Color) -> Self {
444        self.color = Some(color);
445        self
446    }
447
448    /// Emit JSON Lines output (`--json`).
449    ///
450    /// When set, stdout will contain one JSON object per line. Use
451    /// [`execute_json_lines`](ExecCommand::execute_json_lines) to parse the
452    /// events automatically (requires the `json` feature).
453    #[must_use]
454    pub fn json(mut self) -> Self {
455        self.json = true;
456        self
457    }
458
459    /// Write the last assistant message to a file (`--output-last-message <path>`).
460    #[must_use]
461    pub fn output_last_message(mut self, path: impl Into<String>) -> Self {
462        self.output_last_message = Some(path.into());
463        self
464    }
465
466    /// Append one native exec argument without shell parsing.
467    ///
468    /// Arguments retain call order and follow generated options, before the
469    /// prompt or stdin marker. Unlike [`crate::CodexBuilder::arg`], they are
470    /// passed after the subcommand. The caller and CLI are responsible for
471    /// validity and conflicts, including options that change output format.
472    #[must_use]
473    pub fn extra_arg(mut self, arg: impl Into<String>) -> Self {
474        self.extra_args.push(arg.into());
475        self
476    }
477
478    /// Append several native exec arguments in order.
479    ///
480    /// Each value is one argv element. See [`Self::extra_arg`] for placement
481    /// and validation semantics.
482    #[must_use]
483    pub fn extra_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
484        self.extra_args.extend(args.into_iter().map(Into::into));
485        self
486    }
487
488    /// Override the retry policy for this command.
489    ///
490    /// Takes precedence over the client-level policy set on [`Codex`].
491    #[must_use]
492    pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
493        self.retry_policy = Some(policy);
494        self
495    }
496
497    /// Stream JSONL events from the command, invoking `handler` for each
498    /// parsed [`JsonLineEvent`] as it arrives.
499    ///
500    /// Automatically enables JSON output before extra arguments. Requires the `json`
501    /// feature.
502    ///
503    /// # Example
504    ///
505    /// ```no_run
506    /// use codex_wrapper::{Codex, ExecCommand, JsonLineEvent};
507    ///
508    /// # async fn example() -> codex_wrapper::Result<()> {
509    /// let codex = Codex::builder().build()?;
510    /// ExecCommand::new("what is 2+2?")
511    ///     .ephemeral()
512    ///     .stream(&codex, |event: JsonLineEvent| {
513    ///         println!("{}: {:?}", event.event_type, event.extra);
514    ///     })
515    ///     .await?;
516    /// # Ok(())
517    /// # }
518    /// ```
519    #[cfg(feature = "json")]
520    pub async fn stream<F>(&self, codex: &Codex, handler: F) -> Result<()>
521    where
522        F: FnMut(JsonLineEvent),
523    {
524        crate::streaming::stream_exec(codex, self, handler).await
525    }
526
527    /// Stream JSONL events until completion or an explicit cancellation.
528    ///
529    /// Process-group termination and direct-child reaping complete before a
530    /// cancellation error is returned.
531    #[cfg(feature = "json")]
532    pub async fn stream_cancellable<C, F>(&self, codex: &Codex, cancel: C, handler: F) -> Result<()>
533    where
534        C: std::future::Future<Output = ()> + Send,
535        F: FnMut(JsonLineEvent),
536    {
537        crate::streaming::stream_exec_cancellable(codex, self, cancel, handler).await
538    }
539
540    /// Execute with an explicit cancellation signal.
541    ///
542    /// When `cancel` resolves, the wrapper terminates the owned process group,
543    /// awaits the direct child, and then returns [`Error::Cancelled`]. The
544    /// client timeout uses the same settled cleanup path. Retry does not
545    /// apply to cancellable execution.
546    pub async fn execute_cancellable<C>(&self, codex: &Codex, cancel: C) -> Result<CommandOutput>
547    where
548        C: std::future::Future<Output = ()> + Send,
549    {
550        if self.prompt_via_stdin {
551            let prompt = self.prompt.as_deref().unwrap_or_default();
552            return exec::run_codex_with_stdin_prompt_cancellable(
553                codex,
554                self.args(),
555                prompt,
556                cancel,
557            )
558            .await;
559        }
560        exec::run_codex_cancellable(codex, self.args(), cancel).await
561    }
562
563    /// Execute the command and parse the output as JSON Lines events.
564    ///
565    /// Automatically enables JSON output before extra arguments. Requires the `json`
566    /// feature.
567    #[cfg(feature = "json")]
568    pub async fn execute_json_lines(&self, codex: &Codex) -> Result<Vec<JsonLineEvent>> {
569        let args = self.clone().json().args();
570
571        let output = if self.prompt_via_stdin {
572            let prompt = self.prompt.as_deref().unwrap_or_default();
573            exec::run_codex_with_stdin_prompt(codex, args, prompt).await?
574        } else {
575            exec::run_codex_with_retry(codex, args, self.retry_policy.as_ref()).await?
576        };
577        parse_json_lines(&output.stdout)
578    }
579
580    /// Execute cancellably and parse the output as JSON Lines events.
581    ///
582    /// Automatically enables JSON output before extra arguments. Process cleanup is
583    /// complete before a cancellation or timeout error is returned.
584    #[cfg(feature = "json")]
585    pub async fn execute_json_lines_cancellable<C>(
586        &self,
587        codex: &Codex,
588        cancel: C,
589    ) -> Result<Vec<JsonLineEvent>>
590    where
591        C: std::future::Future<Output = ()> + Send,
592    {
593        let args = self.clone().json().args();
594
595        let output = if self.prompt_via_stdin {
596            let prompt = self.prompt.as_deref().unwrap_or_default();
597            exec::run_codex_with_stdin_prompt_cancellable(codex, args, prompt, cancel).await?
598        } else {
599            exec::run_codex_cancellable(codex, args, cancel).await?
600        };
601        parse_json_lines(&output.stdout)
602    }
603
604    /// Execute the command and return a typed [`QueryResult`].
605    ///
606    /// Assembles the final result text, ids, and token usage from the JSONL
607    /// event stream. Use [`execute_json_lines`](ExecCommand::execute_json_lines) for
608    /// the raw event stream. Requires the `json` feature.
609    #[cfg(feature = "json")]
610    pub async fn execute_json(&self, codex: &Codex) -> Result<QueryResult> {
611        let events = self.execute_json_lines(codex).await?;
612        Ok(QueryResult::from_events(events))
613    }
614
615    /// Execute cancellably and return a typed [`QueryResult`].
616    ///
617    /// The wrapper does not return a terminal cancellation or timeout result
618    /// until process cleanup has completed.
619    #[cfg(feature = "json")]
620    pub async fn execute_json_cancellable<C>(&self, codex: &Codex, cancel: C) -> Result<QueryResult>
621    where
622        C: std::future::Future<Output = ()> + Send,
623    {
624        let events = self.execute_json_lines_cancellable(codex, cancel).await?;
625        Ok(QueryResult::from_events(events))
626    }
627}
628
629impl CodexCommand for ExecCommand {
630    type Output = CommandOutput;
631
632    fn args(&self) -> Vec<String> {
633        let mut args = vec!["exec".to_string()];
634
635        push_typed_config(&mut args, self.approval_policy, self.web_search);
636        push_repeat(&mut args, "-c", &self.config_overrides);
637        push_feature_toggles(
638            &mut args,
639            &self.enabled_features,
640            &self.disabled_features,
641            self.rollout_budget.is_some(),
642        );
643        if let Some(budget) = &self.rollout_budget {
644            args.push("-c".into());
645            args.push(budget.config_override());
646        }
647        push_repeat(&mut args, "--image", &self.images);
648
649        if let Some(model) = &self.model {
650            args.push("--model".into());
651            args.push(model.clone());
652        }
653        if self.oss {
654            args.push("--oss".into());
655        }
656        if let Some(local_provider) = &self.local_provider {
657            args.push("--local-provider".into());
658            args.push(local_provider.clone());
659        }
660        if let Some(sandbox) = effective_sandbox(self.sandbox, self.full_auto) {
661            args.push("--sandbox".into());
662            args.push(sandbox.as_arg().into());
663        }
664        if self.strict_config {
665            args.push("--strict-config".into());
666        }
667        if let Some(profile) = &self.profile {
668            args.push("--profile".into());
669            args.push(profile.clone());
670        }
671        if self.approve_for_me {
672            args.push("--approve-for-me".into());
673        }
674        if self.dangerously_bypass_approvals_and_sandbox {
675            args.push("--dangerously-bypass-approvals-and-sandbox".into());
676        }
677        if self.dangerously_bypass_hook_trust {
678            args.push("--dangerously-bypass-hook-trust".into());
679        }
680        if let Some(cd) = &self.cd {
681            args.push("--cd".into());
682            args.push(cd.clone());
683        }
684        if self.skip_git_repo_check {
685            args.push("--skip-git-repo-check".into());
686        }
687        push_repeat(&mut args, "--add-dir", &self.add_dirs);
688        if self.ephemeral {
689            args.push("--ephemeral".into());
690        }
691        if self.ignore_user_config {
692            args.push("--ignore-user-config".into());
693        }
694        if self.ignore_rules {
695            args.push("--ignore-rules".into());
696        }
697        if let Some(output_schema) = &self.output_schema {
698            args.push("--output-schema".into());
699            args.push(output_schema.clone());
700        }
701        if let Some(color) = self.color {
702            args.push("--color".into());
703            args.push(color.as_arg().into());
704        }
705        if self.json {
706            args.push("--json".into());
707        }
708        if let Some(path) = &self.output_last_message {
709            args.push("--output-last-message".into());
710            args.push(path.clone());
711        }
712        args.extend(self.extra_args.iter().cloned());
713        if self.prompt_via_stdin {
714            // The prompt travels on stdin; `-` is how the CLI is told to read
715            // it from there.
716            args.push("-".into());
717        } else if let Some(prompt) = &self.prompt {
718            args.push(prompt.clone());
719        }
720
721        args
722    }
723
724    async fn execute(&self, codex: &Codex) -> Result<CommandOutput> {
725        if self.prompt_via_stdin {
726            let prompt = self.prompt.as_deref().unwrap_or_default();
727            return exec::run_codex_with_stdin_prompt(codex, self.args(), prompt).await;
728        }
729        exec::run_codex_with_retry(codex, self.args(), self.retry_policy.as_ref()).await
730    }
731}
732
733/// Resume a previous non-interactive session (`codex exec resume`).
734///
735/// Use [`session_id`](ExecResumeCommand::session_id) to target a specific
736/// session, or [`last`](ExecResumeCommand::last) to pick the most recent.
737#[derive(Debug, Clone)]
738pub struct ExecResumeCommand {
739    session_id: Option<String>,
740    prompt: Option<String>,
741    prompt_via_stdin: bool,
742    last: bool,
743    all: bool,
744    approval_policy: Option<ApprovalPolicyConfig>,
745    web_search: Option<WebSearchMode>,
746    config_overrides: Vec<String>,
747    enabled_features: Vec<String>,
748    disabled_features: Vec<String>,
749    rollout_budget: Option<RolloutBudgetConfig>,
750    images: Vec<String>,
751    model: Option<String>,
752    strict_config: bool,
753    dangerously_bypass_hook_trust: bool,
754    ignore_user_config: bool,
755    ignore_rules: bool,
756    output_schema: Option<String>,
757    full_auto: bool,
758    dangerously_bypass_approvals_and_sandbox: bool,
759    skip_git_repo_check: bool,
760    ephemeral: bool,
761    json: bool,
762    output_last_message: Option<String>,
763    extra_args: Vec<String>,
764    retry_policy: Option<crate::retry::RetryPolicy>,
765}
766
767impl ExecResumeCommand {
768    /// Create a new resume command with no options set.
769    #[must_use]
770    pub fn new() -> Self {
771        Self {
772            session_id: None,
773            prompt: None,
774            prompt_via_stdin: false,
775            last: false,
776            all: false,
777            approval_policy: None,
778            web_search: None,
779            config_overrides: Vec::new(),
780            enabled_features: Vec::new(),
781            disabled_features: Vec::new(),
782            rollout_budget: None,
783            images: Vec::new(),
784            model: None,
785            strict_config: false,
786            dangerously_bypass_hook_trust: false,
787            ignore_user_config: false,
788            ignore_rules: false,
789            output_schema: None,
790            full_auto: false,
791            dangerously_bypass_approvals_and_sandbox: false,
792            skip_git_repo_check: false,
793            ephemeral: false,
794            json: false,
795            output_last_message: None,
796            extra_args: Vec::new(),
797            retry_policy: None,
798        }
799    }
800
801    /// Resume a specific session by its ID.
802    #[must_use]
803    pub fn session_id(mut self, session_id: impl Into<String>) -> Self {
804        self.session_id = Some(session_id.into());
805        self
806    }
807
808    /// Append an additional prompt to the resumed session.
809    #[must_use]
810    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
811        self.prompt = Some(prompt.into());
812        self
813    }
814
815    /// Create a resume command whose prompt is delivered on stdin.
816    ///
817    /// The prompt is replaced by `-` in the argument list and written to the
818    /// child's stdin instead. Select the session separately with
819    /// [`session_id`](Self::session_id) or [`last`](Self::last).
820    #[must_use]
821    pub fn from_stdin(prompt: impl Into<String>) -> Self {
822        Self::new().prompt(prompt).prompt_via_stdin()
823    }
824
825    /// Deliver this command's prompt on stdin rather than in argv.
826    ///
827    /// Retry does not apply to a stdin prompt. Any policy set on the command
828    /// or client is ignored because replaying a consumed pipe would not be a
829    /// faithful retry.
830    #[must_use]
831    pub fn prompt_via_stdin(mut self) -> Self {
832        self.prompt_via_stdin = true;
833        self
834    }
835
836    /// The prompt to write to the child's stdin, if this command sends it
837    /// there. `None` when the prompt travels in argv.
838    #[cfg(feature = "json")]
839    pub(crate) fn stdin_prompt(&self) -> Option<&str> {
840        self.prompt_via_stdin
841            .then(|| self.prompt.as_deref().unwrap_or_default())
842    }
843
844    /// Resume the most recent session (`--last`).
845    #[must_use]
846    pub fn last(mut self) -> Self {
847        self.last = true;
848        self
849    }
850
851    /// Resume all sessions (`--all`).
852    #[must_use]
853    pub fn all(mut self) -> Self {
854        self.all = true;
855        self
856    }
857
858    /// Set the model to use (`--model <model>`).
859    ///
860    /// Panics if `model` is an empty string.
861    #[must_use]
862    pub fn model(mut self, model: impl Into<String>) -> Self {
863        let model = model.into();
864        assert!(!model.is_empty(), "model name must not be empty");
865        self.model = Some(model);
866        self
867    }
868
869    /// Attach an image to the prompt (`--image <path>`).
870    ///
871    /// May be called multiple times to attach several images.
872    #[must_use]
873    pub fn image(mut self, path: impl Into<String>) -> Self {
874        self.images.push(path.into());
875        self
876    }
877
878    /// Emit JSON Lines output (`--json`).
879    #[must_use]
880    pub fn json(mut self) -> Self {
881        self.json = true;
882        self
883    }
884
885    /// Write the last assistant message to a file (`--output-last-message <path>`).
886    #[must_use]
887    pub fn output_last_message(mut self, path: impl Into<String>) -> Self {
888        self.output_last_message = Some(path.into());
889        self
890    }
891
892    /// Append one native resume argument without shell parsing.
893    ///
894    /// Arguments retain call order and follow generated options, before the
895    /// session ID and prompt or stdin marker. Unlike
896    /// [`crate::CodexBuilder::arg`], they are passed after the subcommand.
897    /// The caller and CLI are responsible for validity and conflicts,
898    /// including options that change output format.
899    #[must_use]
900    pub fn extra_arg(mut self, arg: impl Into<String>) -> Self {
901        self.extra_args.push(arg.into());
902        self
903    }
904
905    /// Append several native resume arguments in order.
906    ///
907    /// Each value is one argv element. See [`Self::extra_arg`] for placement
908    /// and validation semantics.
909    #[must_use]
910    pub fn extra_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
911        self.extra_args.extend(args.into_iter().map(Into::into));
912        self
913    }
914
915    /// Override a config key (`-c key=value`).
916    ///
917    /// May be called multiple times to set several keys. Because `-c` is
918    /// last-wins, a key set here overrides the same key set by
919    /// [`approval_policy`](Self::approval_policy),
920    /// [`search_mode`](Self::search_mode), or [`full_auto`](Self::full_auto).
921    #[must_use]
922    pub fn config(mut self, key_value: impl Into<String>) -> Self {
923        self.config_overrides.push(key_value.into());
924        self
925    }
926
927    /// Set when the model asks for approval (`-c approval_policy="<value>"`).
928    ///
929    /// `codex-cli` 0.145.0 removed `--ask-for-approval` from the exec family;
930    /// the config key is the supported equivalent. Accepts an
931    /// [`ApprovalPolicy`](crate::ApprovalPolicy) directly, or an
932    /// [`ApprovalPolicyConfig`] for the two values the flag never took.
933    #[must_use]
934    pub fn approval_policy(mut self, policy: impl Into<ApprovalPolicyConfig>) -> Self {
935        self.approval_policy = Some(policy.into());
936        self
937    }
938
939    /// Enable live web search.
940    ///
941    /// Shorthand for `search_mode(WebSearchMode::Live)`, which is what the
942    /// removed `--search` flag meant.
943    #[must_use]
944    pub fn search(self) -> Self {
945        self.search_mode(WebSearchMode::Live)
946    }
947
948    /// Set the web search mode (`-c web_search="<value>"`).
949    ///
950    /// `codex-cli` 0.145.0 removed `--search` from the exec family; the config
951    /// key is the supported equivalent, and it is an enum rather than the
952    /// flag's boolean.
953    #[must_use]
954    pub fn search_mode(mut self, mode: WebSearchMode) -> Self {
955        self.web_search = Some(mode);
956        self
957    }
958
959    /// Enable an optional feature flag (`--enable <feature>`).
960    ///
961    /// May be called multiple times.
962    #[must_use]
963    pub fn enable(mut self, feature: impl Into<String>) -> Self {
964        self.enabled_features.push(feature.into());
965        self
966    }
967
968    /// Disable an optional feature flag (`--disable <feature>`).
969    ///
970    /// May be called multiple times.
971    #[must_use]
972    pub fn disable(mut self, feature: impl Into<String>) -> Self {
973        self.disabled_features.push(feature.into());
974        self
975    }
976
977    /// Enforce a Codex-native rollout-unit budget for this resumed execution.
978    ///
979    /// The meter and response-boundary overshoot are identical to
980    /// [`ExecCommand::rollout_budget`]. Emitting the same config on resume is
981    /// required: a budget applied only to the opening process does not carry
982    /// into a later `codex exec resume` process.
983    #[must_use]
984    pub fn rollout_budget(mut self, budget: RolloutBudgetConfig) -> Self {
985        self.rollout_budget = Some(budget);
986        self
987    }
988
989    /// Error on unrecognized config keys (`--strict-config`).
990    #[must_use]
991    pub fn strict_config(mut self) -> Self {
992        self.strict_config = true;
993        self
994    }
995
996    /// Bypass the hook trust prompt (`--dangerously-bypass-hook-trust`).
997    ///
998    /// Allows configured hooks to run without confirmation. Use with caution.
999    #[must_use]
1000    pub(crate) fn set_bypass_hook_trust(mut self) -> Self {
1001        self.dangerously_bypass_hook_trust = true;
1002        self
1003    }
1004
1005    /// Ignore the user-level config file (`--ignore-user-config`).
1006    #[must_use]
1007    pub fn ignore_user_config(mut self) -> Self {
1008        self.ignore_user_config = true;
1009        self
1010    }
1011
1012    /// Ignore project rules files (`--ignore-rules`).
1013    #[must_use]
1014    pub fn ignore_rules(mut self) -> Self {
1015        self.ignore_rules = true;
1016        self
1017    }
1018
1019    /// Require output to conform to a JSON schema (`--output-schema <path>`).
1020    #[must_use]
1021    pub fn output_schema(mut self, path: impl Into<String>) -> Self {
1022        self.output_schema = Some(path.into());
1023        self
1024    }
1025
1026    /// Run in full-auto mode, emitted as `-c sandbox_mode="workspace-write"`.
1027    ///
1028    /// `--full-auto` is deprecated upstream; `codex-cli` 0.145.0 hides it and
1029    /// warns to use `--sandbox workspace-write` instead. `codex exec resume`
1030    /// has no `--sandbox` flag, so this sets the equivalent config key.
1031    #[must_use]
1032    pub fn full_auto(mut self) -> Self {
1033        self.full_auto = true;
1034        self
1035    }
1036
1037    /// Bypass all approval prompts and sandbox restrictions.
1038    ///
1039    /// Passes `--dangerously-bypass-approvals-and-sandbox`. Use with caution.
1040    #[must_use]
1041    pub(crate) fn set_bypass_approvals_and_sandbox(mut self) -> Self {
1042        self.dangerously_bypass_approvals_and_sandbox = true;
1043        self
1044    }
1045
1046    /// Skip the git repository check (`--skip-git-repo-check`).
1047    #[must_use]
1048    pub fn skip_git_repo_check(mut self) -> Self {
1049        self.skip_git_repo_check = true;
1050        self
1051    }
1052
1053    /// Run in ephemeral mode — no session is persisted (`--ephemeral`).
1054    #[must_use]
1055    pub fn ephemeral(mut self) -> Self {
1056        self.ephemeral = true;
1057        self
1058    }
1059
1060    /// Override the retry policy for this command.
1061    ///
1062    /// Takes precedence over the client-level policy set on [`Codex`].
1063    #[must_use]
1064    pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
1065        self.retry_policy = Some(policy);
1066        self
1067    }
1068
1069    /// Execute this resumed turn with an explicit cancellation signal.
1070    ///
1071    /// When `cancel` resolves, the wrapper terminates the owned process group,
1072    /// awaits the direct child, and then returns [`Error::Cancelled`]. The
1073    /// client timeout uses the same settled cleanup path. Retry does not
1074    /// apply to cancellable execution.
1075    pub async fn execute_cancellable<C>(&self, codex: &Codex, cancel: C) -> Result<CommandOutput>
1076    where
1077        C: std::future::Future<Output = ()> + Send,
1078    {
1079        if self.prompt_via_stdin {
1080            let prompt = self.prompt.as_deref().unwrap_or_default();
1081            return exec::run_codex_with_stdin_prompt_cancellable(
1082                codex,
1083                self.args(),
1084                prompt,
1085                cancel,
1086            )
1087            .await;
1088        }
1089        exec::run_codex_cancellable(codex, self.args(), cancel).await
1090    }
1091
1092    /// Execute the command and parse the output as JSON Lines events.
1093    ///
1094    /// Automatically enables JSON output before extra arguments. Requires the `json`
1095    /// feature.
1096    #[cfg(feature = "json")]
1097    pub async fn execute_json_lines(&self, codex: &Codex) -> Result<Vec<JsonLineEvent>> {
1098        let args = self.clone().json().args();
1099
1100        let output = if self.prompt_via_stdin {
1101            let prompt = self.prompt.as_deref().unwrap_or_default();
1102            exec::run_codex_with_stdin_prompt(codex, args, prompt).await?
1103        } else {
1104            exec::run_codex_with_retry(codex, args, self.retry_policy.as_ref()).await?
1105        };
1106        parse_json_lines(&output.stdout)
1107    }
1108
1109    /// Execute this resumed turn cancellably and parse JSON Lines events.
1110    ///
1111    /// Automatically enables JSON output before extra arguments. Process cleanup is
1112    /// complete before a cancellation or timeout error is returned.
1113    #[cfg(feature = "json")]
1114    pub async fn execute_json_lines_cancellable<C>(
1115        &self,
1116        codex: &Codex,
1117        cancel: C,
1118    ) -> Result<Vec<JsonLineEvent>>
1119    where
1120        C: std::future::Future<Output = ()> + Send,
1121    {
1122        let args = self.clone().json().args();
1123
1124        let output = if self.prompt_via_stdin {
1125            let prompt = self.prompt.as_deref().unwrap_or_default();
1126            exec::run_codex_with_stdin_prompt_cancellable(codex, args, prompt, cancel).await?
1127        } else {
1128            exec::run_codex_cancellable(codex, args, cancel).await?
1129        };
1130        parse_json_lines(&output.stdout)
1131    }
1132
1133    /// Execute the resume command and return a typed [`QueryResult`].
1134    ///
1135    /// Assembles the final result text, ids, and token usage from the JSONL
1136    /// event stream. Requires the `json` feature.
1137    #[cfg(feature = "json")]
1138    pub async fn execute_json(&self, codex: &Codex) -> Result<QueryResult> {
1139        let events = self.execute_json_lines(codex).await?;
1140        Ok(QueryResult::from_events(events))
1141    }
1142
1143    /// Execute this resumed turn cancellably and return a typed [`QueryResult`].
1144    ///
1145    /// The wrapper does not return a terminal cancellation or timeout result
1146    /// until process cleanup has completed.
1147    #[cfg(feature = "json")]
1148    pub async fn execute_json_cancellable<C>(&self, codex: &Codex, cancel: C) -> Result<QueryResult>
1149    where
1150        C: std::future::Future<Output = ()> + Send,
1151    {
1152        let events = self.execute_json_lines_cancellable(codex, cancel).await?;
1153        Ok(QueryResult::from_events(events))
1154    }
1155
1156    /// Stream JSONL events from the resume command, invoking `handler` for
1157    /// each parsed [`JsonLineEvent`] as it arrives.
1158    ///
1159    /// Automatically enables JSON output before extra arguments. Requires the `json`
1160    /// feature.
1161    #[cfg(feature = "json")]
1162    pub async fn stream<F>(&self, codex: &Codex, handler: F) -> Result<()>
1163    where
1164        F: FnMut(JsonLineEvent),
1165    {
1166        crate::streaming::stream_exec_resume(codex, self, handler).await
1167    }
1168
1169    /// Stream resumed-turn JSONL events until completion or cancellation.
1170    ///
1171    /// Process-group termination and direct-child reaping complete before a
1172    /// cancellation error is returned.
1173    #[cfg(feature = "json")]
1174    pub async fn stream_cancellable<C, F>(&self, codex: &Codex, cancel: C, handler: F) -> Result<()>
1175    where
1176        C: std::future::Future<Output = ()> + Send,
1177        F: FnMut(JsonLineEvent),
1178    {
1179        crate::streaming::stream_exec_resume_cancellable(codex, self, cancel, handler).await
1180    }
1181}
1182
1183impl Default for ExecResumeCommand {
1184    fn default() -> Self {
1185        Self::new()
1186    }
1187}
1188
1189impl CodexCommand for ExecResumeCommand {
1190    type Output = CommandOutput;
1191
1192    fn args(&self) -> Vec<String> {
1193        let mut args = vec!["exec".into(), "resume".into()];
1194        push_typed_config(&mut args, self.approval_policy, self.web_search);
1195        // `exec resume` has no `--sandbox` flag, so the `--full-auto`
1196        // replacement has to go through the config key.
1197        if self.full_auto {
1198            args.push("-c".into());
1199            args.push(format!(
1200                "sandbox_mode=\"{}\"",
1201                SandboxMode::WorkspaceWrite.as_arg()
1202            ));
1203        }
1204        push_repeat(&mut args, "-c", &self.config_overrides);
1205        push_feature_toggles(
1206            &mut args,
1207            &self.enabled_features,
1208            &self.disabled_features,
1209            self.rollout_budget.is_some(),
1210        );
1211        if let Some(budget) = &self.rollout_budget {
1212            args.push("-c".into());
1213            args.push(budget.config_override());
1214        }
1215        if self.last {
1216            args.push("--last".into());
1217        }
1218        if self.all {
1219            args.push("--all".into());
1220        }
1221        push_repeat(&mut args, "--image", &self.images);
1222        if let Some(model) = &self.model {
1223            args.push("--model".into());
1224            args.push(model.clone());
1225        }
1226        if self.strict_config {
1227            args.push("--strict-config".into());
1228        }
1229        if self.dangerously_bypass_approvals_and_sandbox {
1230            args.push("--dangerously-bypass-approvals-and-sandbox".into());
1231        }
1232        if self.dangerously_bypass_hook_trust {
1233            args.push("--dangerously-bypass-hook-trust".into());
1234        }
1235        if self.skip_git_repo_check {
1236            args.push("--skip-git-repo-check".into());
1237        }
1238        if self.ephemeral {
1239            args.push("--ephemeral".into());
1240        }
1241        if self.ignore_user_config {
1242            args.push("--ignore-user-config".into());
1243        }
1244        if self.ignore_rules {
1245            args.push("--ignore-rules".into());
1246        }
1247        if let Some(output_schema) = &self.output_schema {
1248            args.push("--output-schema".into());
1249            args.push(output_schema.clone());
1250        }
1251        if self.json {
1252            args.push("--json".into());
1253        }
1254        if let Some(path) = &self.output_last_message {
1255            args.push("--output-last-message".into());
1256            args.push(path.clone());
1257        }
1258        args.extend(self.extra_args.iter().cloned());
1259        if let Some(session_id) = &self.session_id {
1260            args.push(session_id.clone());
1261        }
1262        if self.prompt_via_stdin {
1263            args.push("-".into());
1264        } else if let Some(prompt) = &self.prompt {
1265            args.push(prompt.clone());
1266        }
1267        args
1268    }
1269
1270    async fn execute(&self, codex: &Codex) -> Result<CommandOutput> {
1271        if self.prompt_via_stdin {
1272            let prompt = self.prompt.as_deref().unwrap_or_default();
1273            return exec::run_codex_with_stdin_prompt(codex, self.args(), prompt).await;
1274        }
1275        exec::run_codex_with_retry(codex, self.args(), self.retry_policy.as_ref()).await
1276    }
1277}
1278
1279fn push_repeat(args: &mut Vec<String>, flag: &str, values: &[String]) {
1280    for value in values {
1281        args.push(flag.into());
1282        args.push(value.clone());
1283    }
1284}
1285
1286fn push_feature_toggles(
1287    args: &mut Vec<String>,
1288    enabled: &[String],
1289    disabled: &[String],
1290    protects_rollout_budget: bool,
1291) {
1292    let keep = |feature: &&String| !protects_rollout_budget || feature.as_str() != "rollout_budget";
1293    for feature in enabled.iter().filter(keep) {
1294        args.push("--enable".into());
1295        args.push(feature.clone());
1296    }
1297    for feature in disabled.iter().filter(keep) {
1298        args.push("--disable".into());
1299        args.push(feature.clone());
1300    }
1301}
1302
1303#[cfg(feature = "json")]
1304fn parse_json_lines(stdout: &str) -> Result<Vec<JsonLineEvent>> {
1305    stdout
1306        .lines()
1307        .filter(|line| line.trim_start().starts_with('{'))
1308        .map(|line| {
1309            serde_json::from_str(line).map_err(|source| Error::Json {
1310                message: format!("failed to parse JSONL event: {line}"),
1311                source,
1312            })
1313        })
1314        .collect()
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320    use crate::types::ApprovalPolicy;
1321
1322    #[cfg(unix)]
1323    const NATIVE_ARGS: &[&str] = &["--native", "value with spaces\nand a newline", "", "--"];
1324
1325    #[cfg(unix)]
1326    struct ArgvCapture(std::path::PathBuf);
1327
1328    #[cfg(unix)]
1329    impl ArgvCapture {
1330        fn client() -> (Self, Codex) {
1331            use std::sync::atomic::{AtomicU64, Ordering};
1332            static NEXT_ID: AtomicU64 = AtomicU64::new(0);
1333            let capture = Self(std::env::temp_dir().join(format!(
1334                "codex-wrapper-{}-extra-args-{}",
1335                std::process::id(),
1336                NEXT_ID.fetch_add(1, Ordering::Relaxed)
1337            )));
1338            let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1339                .join("tests/fake-codex-capture-args.sh");
1340            let client = Codex::builder()
1341                .binary("/bin/bash")
1342                .arg(fixture.to_str().unwrap())
1343                .env("CODEX_WRAPPER_ARGS_CAPTURE", capture.0.to_str().unwrap())
1344                .timeout_secs(5)
1345                .build()
1346                .unwrap();
1347            (capture, client)
1348        }
1349
1350        fn assert_received(&self, resume: bool, stdin: bool, json: bool) {
1351            let contents = std::fs::read_to_string(&self.0).unwrap();
1352            let received: Vec<_> = contents.split_terminator('\0').collect();
1353            let mut expected = vec!["exec"];
1354            if resume {
1355                expected.push("resume");
1356            }
1357            expected.extend(["--model", "gpt-5"]);
1358            if json {
1359                expected.push("--json");
1360            }
1361            expected.extend_from_slice(NATIVE_ARGS);
1362            if resume {
1363                expected.push("thread-1");
1364            }
1365            expected.push(if stdin { "-" } else { "prompt\nsecond line" });
1366            assert_eq!(received, expected);
1367        }
1368    }
1369
1370    #[cfg(unix)]
1371    impl Drop for ArgvCapture {
1372        fn drop(&mut self) {
1373            let _ = std::fs::remove_file(&self.0);
1374        }
1375    }
1376
1377    #[cfg(unix)]
1378    fn fresh_with_extra_args(stdin: bool) -> ExecCommand {
1379        let cmd = ExecCommand::new("prompt\nsecond line")
1380            .model("gpt-5")
1381            .extra_arg(NATIVE_ARGS[0])
1382            .extra_args(NATIVE_ARGS[1..].iter().copied());
1383        if stdin { cmd.prompt_via_stdin() } else { cmd }
1384    }
1385
1386    #[cfg(unix)]
1387    fn resumed_with_extra_args(stdin: bool) -> ExecResumeCommand {
1388        let cmd = ExecResumeCommand::new()
1389            .session_id("thread-1")
1390            .prompt("prompt\nsecond line")
1391            .model("gpt-5")
1392            .extra_arg(NATIVE_ARGS[0])
1393            .extra_args(NATIVE_ARGS[1..].iter().copied());
1394        if stdin { cmd.prompt_via_stdin() } else { cmd }
1395    }
1396
1397    #[cfg(unix)]
1398    #[tokio::test]
1399    async fn extra_args_reach_buffered_fresh_and_resumed_children() {
1400        for resume in [false, true] {
1401            for stdin in [false, true] {
1402                let (capture, codex) = ArgvCapture::client();
1403                let output = if resume {
1404                    resumed_with_extra_args(stdin)
1405                        .execute_cancellable(&codex, std::future::pending())
1406                        .await
1407                } else {
1408                    fresh_with_extra_args(stdin).execute(&codex).await
1409                }
1410                .unwrap();
1411                assert!(output.success);
1412                capture.assert_received(resume, stdin, false);
1413            }
1414        }
1415    }
1416
1417    #[cfg(all(unix, feature = "json"))]
1418    #[tokio::test]
1419    async fn extra_args_preserve_json_and_streaming_prompt_transport() {
1420        for resume in [false, true] {
1421            for stdin in [false, true] {
1422                for streaming in [false, true] {
1423                    let (capture, codex) = ArgvCapture::client();
1424                    let events = if streaming {
1425                        let mut events = Vec::new();
1426                        if resume {
1427                            resumed_with_extra_args(stdin)
1428                                .stream_cancellable(&codex, std::future::pending(), |event| {
1429                                    events.push(event)
1430                                })
1431                                .await
1432                                .unwrap();
1433                        } else {
1434                            fresh_with_extra_args(stdin)
1435                                .stream(&codex, |event| events.push(event))
1436                                .await
1437                                .unwrap();
1438                        }
1439                        events
1440                    } else if resume {
1441                        resumed_with_extra_args(stdin)
1442                            .execute_json_lines_cancellable(&codex, std::future::pending())
1443                            .await
1444                            .unwrap()
1445                    } else {
1446                        fresh_with_extra_args(stdin)
1447                            .execute_json_lines(&codex)
1448                            .await
1449                            .unwrap()
1450                    };
1451                    capture.assert_received(resume, stdin, true);
1452                    let result = QueryResult::from_events(events);
1453                    assert_eq!(result.thread_id.as_deref(), Some("thread_stdin"));
1454                    assert_eq!(
1455                        result.result,
1456                        if stdin { "prompt\nsecond line" } else { "" }
1457                    );
1458                }
1459            }
1460        }
1461    }
1462
1463    #[test]
1464    fn exec_extra_args_follow_options_and_precede_the_prompt() {
1465        for stdin in [false, true] {
1466            let mut cmd = ExecCommand::new("prompt");
1467            if stdin {
1468                cmd = cmd.prompt_via_stdin();
1469            }
1470            let args = cmd
1471                .extra_arg("--native")
1472                .model("gpt-5")
1473                .extra_args(["value with spaces", "", "--json"])
1474                .extra_arg("literal $HOME; echo nope")
1475                .json()
1476                .args();
1477            assert_eq!(
1478                args,
1479                [
1480                    "exec",
1481                    "--model",
1482                    "gpt-5",
1483                    "--json",
1484                    "--native",
1485                    "value with spaces",
1486                    "",
1487                    "--json",
1488                    "literal $HOME; echo nope",
1489                    if stdin { "-" } else { "prompt" },
1490                ]
1491            );
1492        }
1493    }
1494
1495    #[test]
1496    fn resume_extra_args_precede_session_id_and_prompt() {
1497        for stdin in [false, true] {
1498            let mut cmd = ExecResumeCommand::new()
1499                .session_id("thread-1")
1500                .prompt("prompt");
1501            if stdin {
1502                cmd = cmd.prompt_via_stdin();
1503            }
1504            let args = cmd
1505                .extra_arg("--native")
1506                .model("gpt-5")
1507                .extra_args(["value with spaces", ""])
1508                .extra_arg("literal $HOME; echo nope")
1509                .json()
1510                .args();
1511            assert_eq!(
1512                args,
1513                [
1514                    "exec",
1515                    "resume",
1516                    "--model",
1517                    "gpt-5",
1518                    "--json",
1519                    "--native",
1520                    "value with spaces",
1521                    "",
1522                    "literal $HOME; echo nope",
1523                    "thread-1",
1524                    if stdin { "-" } else { "prompt" },
1525                ]
1526            );
1527        }
1528        assert_eq!(
1529            ExecResumeCommand::new()
1530                .last()
1531                .extra_args(["--native", "value"])
1532                .args(),
1533            ["exec", "resume", "--last", "--native", "value"]
1534        );
1535    }
1536
1537    #[test]
1538    fn exec_args() {
1539        let args = ExecCommand::new("fix the test")
1540            .model("gpt-5")
1541            .sandbox(SandboxMode::WorkspaceWrite)
1542            .strict_config()
1543            .skip_git_repo_check()
1544            .ephemeral()
1545            .ignore_user_config()
1546            .ignore_rules()
1547            .json()
1548            .args();
1549
1550        assert_eq!(
1551            args,
1552            vec![
1553                "exec",
1554                "--model",
1555                "gpt-5",
1556                "--sandbox",
1557                "workspace-write",
1558                "--strict-config",
1559                "--skip-git-repo-check",
1560                "--ephemeral",
1561                "--ignore-user-config",
1562                "--ignore-rules",
1563                "--json",
1564                "fix the test",
1565            ]
1566        );
1567    }
1568
1569    #[test]
1570    fn exec_args_hook_trust() {
1571        let args = ExecCommand::new("go")
1572            .set_bypass_approvals_and_sandbox()
1573            .set_bypass_hook_trust()
1574            .args();
1575
1576        assert_eq!(
1577            args,
1578            vec![
1579                "exec",
1580                "--dangerously-bypass-approvals-and-sandbox",
1581                "--dangerously-bypass-hook-trust",
1582                "go",
1583            ]
1584        );
1585    }
1586
1587    #[test]
1588    #[should_panic(expected = "model name must not be empty")]
1589    fn exec_model_empty_panics() {
1590        let _ = ExecCommand::new("prompt").model("");
1591    }
1592
1593    #[test]
1594    #[should_panic(expected = "model name must not be empty")]
1595    fn exec_resume_model_empty_panics() {
1596        let _ = ExecResumeCommand::new().model("");
1597    }
1598
1599    #[test]
1600    fn exec_resume_args() {
1601        let args = ExecResumeCommand::new()
1602            .last()
1603            .model("gpt-5")
1604            .json()
1605            .prompt("continue")
1606            .args();
1607
1608        assert_eq!(
1609            args,
1610            vec![
1611                "exec", "resume", "--last", "--model", "gpt-5", "--json", "continue",
1612            ]
1613        );
1614    }
1615
1616    #[test]
1617    fn exec_resume_new_flags() {
1618        let args = ExecResumeCommand::new()
1619            .last()
1620            .strict_config()
1621            .set_bypass_hook_trust()
1622            .args();
1623
1624        assert_eq!(
1625            args,
1626            vec![
1627                "exec",
1628                "resume",
1629                "--last",
1630                "--strict-config",
1631                "--dangerously-bypass-hook-trust",
1632            ]
1633        );
1634    }
1635
1636    /// #53: `--ask-for-approval` and `--search` were removed from `codex exec`
1637    /// in codex-cli 0.145.0; the settings live on as config keys.
1638    #[test]
1639    fn exec_approval_and_search_emit_config_keys() {
1640        let args = ExecCommand::new("hi")
1641            .approval_policy(ApprovalPolicy::Never)
1642            .search()
1643            .args();
1644        assert_eq!(
1645            args,
1646            vec![
1647                "exec",
1648                "-c",
1649                "approval_policy=\"never\"",
1650                "-c",
1651                "web_search=\"live\"",
1652                "hi"
1653            ]
1654        );
1655        assert!(
1656            !args
1657                .iter()
1658                .any(|a| a == "--ask-for-approval" || a == "--search")
1659        );
1660    }
1661
1662    /// `granular` and `on-failure` are accepted by the config key but not by
1663    /// the flag, which is why `ApprovalPolicyConfig` exists.
1664    #[test]
1665    fn exec_approval_accepts_config_only_values() {
1666        let args = ExecCommand::new("hi")
1667            .approval_policy(ApprovalPolicyConfig::Granular)
1668            .args();
1669        assert_eq!(
1670            args,
1671            vec!["exec", "-c", "approval_policy=\"granular\"", "hi"]
1672        );
1673    }
1674
1675    #[test]
1676    fn exec_search_mode_variants() {
1677        for (mode, expected) in [
1678            (WebSearchMode::Disabled, "disabled"),
1679            (WebSearchMode::Cached, "cached"),
1680            (WebSearchMode::Indexed, "indexed"),
1681            (WebSearchMode::Live, "live"),
1682        ] {
1683            let args = ExecCommand::new("hi").search_mode(mode).args();
1684            assert_eq!(args[2], format!("web_search=\"{expected}\""));
1685        }
1686    }
1687
1688    /// `-c` is last-wins, so a raw override has to be emitted after the typed
1689    /// setters for it to take effect.
1690    #[test]
1691    fn exec_raw_config_is_emitted_after_typed_config() {
1692        let args = ExecCommand::new("hi")
1693            .approval_policy(ApprovalPolicy::Never)
1694            .config("approval_policy=\"untrusted\"")
1695            .args();
1696        let typed = args
1697            .iter()
1698            .position(|a| a == "approval_policy=\"never\"")
1699            .unwrap();
1700        let raw = args
1701            .iter()
1702            .position(|a| a == "approval_policy=\"untrusted\"")
1703            .unwrap();
1704        assert!(typed < raw, "raw override must win: {args:?}");
1705    }
1706
1707    #[test]
1708    fn native_rollout_budget_is_identical_and_final_on_open_and_resume() {
1709        let budget = RolloutBudgetConfig::builder(10_000)
1710            .reminder_at_remaining_tokens([5_000, 1_000])
1711            .sampling_token_weight(1.0)
1712            .prefill_token_weight(0.25)
1713            .build()
1714            .expect("valid budget");
1715        let expected = budget.config_override();
1716        let opening = ExecCommand::new("hi")
1717            .rollout_budget(budget.clone())
1718            .config("features.rollout_budget=false")
1719            .enable("rollout_budget")
1720            .disable("rollout_budget")
1721            .enable("keep-enabled")
1722            .disable("keep-disabled")
1723            .args();
1724        let resumed = ExecResumeCommand::new()
1725            .session_id("thread")
1726            .rollout_budget(budget)
1727            .config("features.rollout_budget=false")
1728            .enable("rollout_budget")
1729            .disable("rollout_budget")
1730            .enable("keep-enabled")
1731            .disable("keep-disabled")
1732            .args();
1733
1734        for args in [opening, resumed] {
1735            let budget_at = args.iter().position(|arg| arg == &expected).unwrap();
1736            let raw_at = args
1737                .iter()
1738                .position(|arg| arg == "features.rollout_budget=false")
1739                .unwrap();
1740            assert!(
1741                raw_at < budget_at,
1742                "native budget must beat raw config: {args:?}"
1743            );
1744            assert!(
1745                !args.windows(2).any(|pair| {
1746                    matches!(pair[0].as_str(), "--enable" | "--disable")
1747                        && pair[1] == "rollout_budget"
1748                }),
1749                "native budget must suppress conflicting feature toggles: {args:?}"
1750            );
1751            assert!(
1752                args.windows(2)
1753                    .any(|pair| pair == ["--enable", "keep-enabled"])
1754            );
1755            assert!(
1756                args.windows(2)
1757                    .any(|pair| pair == ["--disable", "keep-disabled"])
1758            );
1759        }
1760    }
1761
1762    /// #55: `--full-auto` is hidden and deprecated on the exec family.
1763    #[test]
1764    fn exec_full_auto_emits_sandbox_workspace_write() {
1765        let args = ExecCommand::new("hi").full_auto().args();
1766        assert_eq!(args, vec!["exec", "--sandbox", "workspace-write", "hi"]);
1767        assert!(!args.iter().any(|a| a == "--full-auto"));
1768    }
1769
1770    #[test]
1771    fn exec_explicit_sandbox_wins_over_full_auto() {
1772        let args = ExecCommand::new("hi")
1773            .full_auto()
1774            .sandbox(SandboxMode::ReadOnly)
1775            .args();
1776        assert_eq!(args, vec!["exec", "--sandbox", "read-only", "hi"]);
1777    }
1778
1779    /// `codex exec resume` has no `--sandbox` flag, so the replacement goes
1780    /// through the config key instead.
1781    #[test]
1782    fn exec_resume_full_auto_emits_sandbox_config_key() {
1783        let args = ExecResumeCommand::new().last().full_auto().args();
1784        assert_eq!(
1785            args,
1786            vec![
1787                "exec",
1788                "resume",
1789                "-c",
1790                "sandbox_mode=\"workspace-write\"",
1791                "--last"
1792            ]
1793        );
1794        assert!(!args.iter().any(|a| a == "--full-auto"));
1795    }
1796
1797    #[test]
1798    fn exec_resume_approval_and_search_emit_config_keys() {
1799        let args = ExecResumeCommand::new()
1800            .last()
1801            .approval_policy(ApprovalPolicyConfig::OnFailure)
1802            .search_mode(WebSearchMode::Cached)
1803            .args();
1804        assert_eq!(
1805            args,
1806            vec![
1807                "exec",
1808                "resume",
1809                "-c",
1810                "approval_policy=\"on-failure\"",
1811                "-c",
1812                "web_search=\"cached\"",
1813                "--last"
1814            ]
1815        );
1816    }
1817
1818    /// #65: these three were listed in #41 P1 but never landed on
1819    /// `ExecResumeCommand`.
1820    #[test]
1821    fn exec_resume_ignore_and_output_schema_args() {
1822        let args = ExecResumeCommand::new()
1823            .last()
1824            .ignore_user_config()
1825            .ignore_rules()
1826            .output_schema("/tmp/schema.json")
1827            .args();
1828        assert_eq!(
1829            args,
1830            vec![
1831                "exec",
1832                "resume",
1833                "--last",
1834                "--ignore-user-config",
1835                "--ignore-rules",
1836                "--output-schema",
1837                "/tmp/schema.json"
1838            ]
1839        );
1840    }
1841
1842    #[cfg(all(unix, feature = "json"))]
1843    #[tokio::test]
1844    async fn fresh_json_cancellation_returns_after_reaping() {
1845        use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1846
1847        let pid_file = PidFile::new("fresh-json-cancellable");
1848        let codex = blocking_codex(&pid_file)
1849            .termination_grace(std::time::Duration::from_millis(10))
1850            .build()
1851            .expect("bash must exist");
1852
1853        let result = ExecCommand::new("probe")
1854            .execute_json_cancellable(&codex, async {
1855                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1856            })
1857            .await;
1858
1859        assert!(matches!(result, Err(Error::Cancelled { .. })));
1860        let pid = pid_file.read_pid().await;
1861        assert!(
1862            !is_running_for_test(pid),
1863            "codex ({pid}) survived cancellation"
1864        );
1865    }
1866
1867    #[cfg(all(unix, feature = "json"))]
1868    #[tokio::test]
1869    async fn resumed_stdin_json_cancellation_returns_after_reaping() {
1870        use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1871
1872        let pid_file = PidFile::new("resume-stdin-json-cancellable");
1873        let codex = blocking_codex(&pid_file)
1874            .termination_grace(std::time::Duration::from_millis(10))
1875            .build()
1876            .expect("bash must exist");
1877
1878        let result = ExecResumeCommand::from_stdin("continue")
1879            .session_id("thread-1")
1880            .execute_json_cancellable(&codex, async {
1881                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1882            })
1883            .await;
1884
1885        assert!(matches!(result, Err(Error::Cancelled { .. })));
1886        let pid = pid_file.read_pid().await;
1887        assert!(
1888            !is_running_for_test(pid),
1889            "codex ({pid}) survived cancellation"
1890        );
1891    }
1892
1893    /// #81: the builder emitted `codex exec -` while every spawn path closed
1894    /// the child's stdin, so the prompt was never delivered. This drives a
1895    /// fake codex that echoes back what it read, which is the only way to see
1896    /// the difference: the argv is identical either way.
1897    #[cfg(all(unix, feature = "json"))]
1898    #[tokio::test]
1899    async fn stdin_prompt_reaches_the_child() {
1900        let codex = echoing_stdin_codex();
1901        let prompt = "a prompt too awkward for argv\nwith a second line";
1902
1903        let result = ExecCommand::from_stdin(prompt)
1904            .execute_json(&codex)
1905            .await
1906            .unwrap();
1907
1908        assert_eq!(result.result, prompt);
1909    }
1910
1911    #[cfg(unix)]
1912    #[tokio::test]
1913    async fn resume_stdin_prompt_reaches_the_child_for_raw_execution() {
1914        let codex = echoing_stdin_codex();
1915        let prompt = "raw resumed stdin prompt";
1916
1917        let output = ExecResumeCommand::from_stdin(prompt)
1918            .session_id("thread-1")
1919            .execute(&codex)
1920            .await
1921            .unwrap();
1922
1923        assert!(output.stdout.contains(prompt));
1924    }
1925
1926    #[cfg(all(unix, feature = "json"))]
1927    #[tokio::test]
1928    async fn resume_stdin_prompt_reaches_the_child_for_json_execution() {
1929        let codex = echoing_stdin_codex();
1930        let prompt = "json resumed stdin prompt";
1931
1932        let result = ExecResumeCommand::from_stdin(prompt)
1933            .session_id("thread-1")
1934            .execute_json(&codex)
1935            .await
1936            .unwrap();
1937
1938        assert_eq!(result.result, prompt);
1939    }
1940
1941    /// The same delivery, on the streaming path, which pipes stdin separately.
1942    #[cfg(all(unix, feature = "json"))]
1943    #[tokio::test]
1944    async fn stdin_prompt_reaches_the_child_when_streaming() {
1945        let codex = echoing_stdin_codex();
1946        let prompt = "streamed stdin prompt";
1947        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1948        let sink = std::sync::Arc::clone(&seen);
1949
1950        ExecCommand::from_stdin(prompt)
1951            .stream(&codex, move |event| {
1952                if let Some(text) = event.agent_message_text() {
1953                    sink.lock().unwrap().push(text);
1954                }
1955            })
1956            .await
1957            .unwrap();
1958
1959        assert_eq!(seen.lock().unwrap().as_slice(), &[prompt.to_string()]);
1960    }
1961
1962    #[cfg(all(unix, feature = "json"))]
1963    #[tokio::test]
1964    async fn resume_stdin_prompt_reaches_the_child_when_streaming() {
1965        let codex = echoing_stdin_codex();
1966        let prompt = "streamed resumed stdin prompt";
1967        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1968        let sink = std::sync::Arc::clone(&seen);
1969
1970        ExecResumeCommand::from_stdin(prompt)
1971            .session_id("thread-1")
1972            .stream(&codex, move |event| {
1973                if let Some(text) = event.agent_message_text() {
1974                    sink.lock().unwrap().push(text);
1975                }
1976            })
1977            .await
1978            .unwrap();
1979
1980        assert_eq!(seen.lock().unwrap().as_slice(), &[prompt.to_string()]);
1981    }
1982
1983    /// A prompt larger than a pipe buffer must not deadlock: the write and the
1984    /// output drain have to run concurrently.
1985    #[cfg(all(unix, feature = "json"))]
1986    #[tokio::test]
1987    async fn a_prompt_larger_than_the_pipe_buffer_still_completes() {
1988        let codex = echoing_stdin_codex();
1989        // Well past the usual 64 KiB pipe capacity.
1990        let prompt = "x".repeat(512 * 1024);
1991
1992        let result = ExecCommand::from_stdin(&prompt)
1993            .execute_json(&codex)
1994            .await
1995            .unwrap();
1996
1997        assert_eq!(result.result.len(), prompt.len());
1998    }
1999
2000    #[cfg(unix)]
2001    fn echoing_stdin_codex() -> Codex {
2002        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2003            .join("tests")
2004            .join("fake-codex-echo-stdin.sh");
2005        Codex::builder()
2006            .binary("/bin/bash")
2007            .arg(script.to_str().unwrap())
2008            .build()
2009            .expect("bash must exist")
2010    }
2011
2012    #[test]
2013    fn from_stdin_emits_the_dash_positional_not_the_prompt() {
2014        let args = ExecCommand::from_stdin("secret prompt").ephemeral().args();
2015        assert_eq!(args, vec!["exec", "--ephemeral", "-"]);
2016        // The prompt must not leak into argv, which is the whole point of
2017        // sending it on stdin.
2018        assert!(!args.iter().any(|a| a.contains("secret")));
2019    }
2020
2021    #[test]
2022    fn prompt_via_stdin_converts_an_existing_prompt() {
2023        let args = ExecCommand::new("hello").prompt_via_stdin().args();
2024        assert_eq!(args, vec!["exec", "-"]);
2025    }
2026
2027    #[test]
2028    fn resume_from_stdin_emits_the_dash_positional_not_the_prompt() {
2029        let args = ExecResumeCommand::from_stdin("secret prompt")
2030            .session_id("thread-1")
2031            .ephemeral()
2032            .args();
2033        assert_eq!(args, vec!["exec", "resume", "--ephemeral", "thread-1", "-"]);
2034        assert!(!args.iter().any(|arg| arg.contains("secret")));
2035    }
2036
2037    #[test]
2038    fn resume_prompt_via_stdin_converts_an_existing_prompt() {
2039        let args = ExecResumeCommand::new()
2040            .session_id("thread-1")
2041            .prompt("hello")
2042            .prompt_via_stdin()
2043            .args();
2044        assert_eq!(args, vec!["exec", "resume", "thread-1", "-"]);
2045    }
2046}