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