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
12pub(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
33pub(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#[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 #[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 #[must_use]
164 pub fn from_stdin(prompt: impl Into<String>) -> Self {
165 Self::new(prompt).prompt_via_stdin()
166 }
167
168 #[must_use]
179 pub fn prompt_via_stdin(mut self) -> Self {
180 self.prompt_via_stdin = true;
181 self
182 }
183
184 #[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 #[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 #[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 #[must_use]
232 pub fn search(self) -> Self {
233 self.search_mode(WebSearchMode::Live)
234 }
235
236 #[must_use]
242 pub fn search_mode(mut self, mode: WebSearchMode) -> Self {
243 self.web_search = Some(mode);
244 self
245 }
246
247 #[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 #[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 #[must_use]
280 pub fn rollout_budget(mut self, budget: RolloutBudgetConfig) -> Self {
281 self.rollout_budget = Some(budget);
282 self
283 }
284
285 #[must_use]
289 pub fn image(mut self, path: impl Into<String>) -> Self {
290 self.images.push(path.into());
291 self
292 }
293
294 #[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 #[must_use]
307 pub fn oss(mut self) -> Self {
308 self.oss = true;
309 self
310 }
311
312 #[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 #[must_use]
321 pub fn sandbox(mut self, sandbox: SandboxMode) -> Self {
322 self.sandbox = Some(sandbox);
323 self
324 }
325
326 #[must_use]
328 pub fn strict_config(mut self) -> Self {
329 self.strict_config = true;
330 self
331 }
332
333 #[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 #[must_use]
344 pub fn ignore_user_config(mut self) -> Self {
345 self.ignore_user_config = true;
346 self
347 }
348
349 #[must_use]
351 pub fn ignore_rules(mut self) -> Self {
352 self.ignore_rules = true;
353 self
354 }
355
356 #[must_use]
358 pub fn profile(mut self, profile: impl Into<String>) -> Self {
359 self.profile = Some(profile.into());
360 self
361 }
362
363 #[must_use]
375 pub fn full_auto(mut self) -> Self {
376 self.full_auto = true;
377 self
378 }
379
380 #[must_use]
388 pub fn approve_for_me(mut self) -> Self {
389 self.approve_for_me = true;
390 self
391 }
392
393 #[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 #[must_use]
404 pub fn cd(mut self, dir: impl Into<String>) -> Self {
405 self.cd = Some(dir.into());
406 self
407 }
408
409 #[must_use]
411 pub fn skip_git_repo_check(mut self) -> Self {
412 self.skip_git_repo_check = true;
413 self
414 }
415
416 #[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 #[must_use]
427 pub fn ephemeral(mut self) -> Self {
428 self.ephemeral = true;
429 self
430 }
431
432 #[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 #[must_use]
441 pub fn color(mut self, color: Color) -> Self {
442 self.color = Some(color);
443 self
444 }
445
446 #[must_use]
452 pub fn json(mut self) -> Self {
453 self.json = true;
454 self
455 }
456
457 #[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 #[must_use]
468 pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
469 self.retry_policy = Some(policy);
470 self
471 }
472
473 #[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 #[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 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 #[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 #[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 #[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 #[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 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#[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 #[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 #[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 #[must_use]
789 pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
790 self.prompt = Some(prompt.into());
791 self
792 }
793
794 #[must_use]
800 pub fn from_stdin(prompt: impl Into<String>) -> Self {
801 Self::new().prompt(prompt).prompt_via_stdin()
802 }
803
804 #[must_use]
810 pub fn prompt_via_stdin(mut self) -> Self {
811 self.prompt_via_stdin = true;
812 self
813 }
814
815 #[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 #[must_use]
825 pub fn last(mut self) -> Self {
826 self.last = true;
827 self
828 }
829
830 #[must_use]
832 pub fn all(mut self) -> Self {
833 self.all = true;
834 self
835 }
836
837 #[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 #[must_use]
852 pub fn image(mut self, path: impl Into<String>) -> Self {
853 self.images.push(path.into());
854 self
855 }
856
857 #[must_use]
859 pub fn json(mut self) -> Self {
860 self.json = true;
861 self
862 }
863
864 #[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 #[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 #[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 #[must_use]
900 pub fn search(self) -> Self {
901 self.search_mode(WebSearchMode::Live)
902 }
903
904 #[must_use]
910 pub fn search_mode(mut self, mode: WebSearchMode) -> Self {
911 self.web_search = Some(mode);
912 self
913 }
914
915 #[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 #[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 #[must_use]
940 pub fn rollout_budget(mut self, budget: RolloutBudgetConfig) -> Self {
941 self.rollout_budget = Some(budget);
942 self
943 }
944
945 #[must_use]
947 pub fn strict_config(mut self) -> Self {
948 self.strict_config = true;
949 self
950 }
951
952 #[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 #[must_use]
963 pub fn ignore_user_config(mut self) -> Self {
964 self.ignore_user_config = true;
965 self
966 }
967
968 #[must_use]
970 pub fn ignore_rules(mut self) -> Self {
971 self.ignore_rules = true;
972 self
973 }
974
975 #[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 #[must_use]
988 pub fn full_auto(mut self) -> Self {
989 self.full_auto = true;
990 self
991 }
992
993 #[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 #[must_use]
1004 pub fn skip_git_repo_check(mut self) -> Self {
1005 self.skip_git_repo_check = true;
1006 self
1007 }
1008
1009 #[must_use]
1011 pub fn ephemeral(mut self) -> Self {
1012 self.ephemeral = true;
1013 self
1014 }
1015
1016 #[must_use]
1020 pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
1021 self.retry_policy = Some(policy);
1022 self
1023 }
1024
1025 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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}