返回 CodeWhale
runtime_options.rs
根目录 / crates / engine / src / runtime_options.rs
1 //! Startup facts passed by the canonical CLI to the Engine library.
2 //!
3 //! One Clap definition serves the CLI and the library's command decoder. Paths
4 //! remain native paths; no stringified argv round trip owns startup settings.
5
6 use anyhow::{Result, bail};
7 use clap::Args;
8 use codewhale_execpolicy::ApprovalMode;
9 use std::path::PathBuf;
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 pub enum PermissionMode {
13 Ask,
14 AcceptEdits,
15 Plan,
16 AutoReview,
17 FullAccess,
18 }
19
20 impl PermissionMode {
21 #[must_use]
22 pub fn approval_mode(self) -> Option<ApprovalMode> {
23 match self {
24 Self::Ask => Some(ApprovalMode::Suggest),
25 Self::AcceptEdits => Some(ApprovalMode::AcceptEdits),
26 Self::Plan => None,
27 Self::AutoReview => Some(ApprovalMode::Auto),
28 Self::FullAccess => Some(ApprovalMode::Bypass),
29 }
30 }
31
32 #[must_use]
33 pub fn as_str(self) -> &'static str {
34 match self {
35 Self::Ask => "ask",
36 Self::AcceptEdits => "accept-edits",
37 Self::Plan => "plan",
38 Self::AutoReview => "auto-review",
39 Self::FullAccess => "full-access",
40 }
41 }
42 }
43
44 pub fn parse_permission_mode(raw: &str) -> std::result::Result<PermissionMode, String> {
45 if raw.trim().eq_ignore_ascii_case("plan") {
46 return Ok(PermissionMode::Plan);
47 }
48 match ApprovalMode::from_config_value(raw) {
49 Some(ApprovalMode::Suggest) => Ok(PermissionMode::Ask),
50 Some(ApprovalMode::AcceptEdits) => Ok(PermissionMode::AcceptEdits),
51 Some(ApprovalMode::Auto) => Ok(PermissionMode::AutoReview),
52 Some(ApprovalMode::Bypass) => Ok(PermissionMode::FullAccess),
53 Some(ApprovalMode::Never) | None => Err(format!(
54 "invalid permission mode '{raw}'; expected ask, accept-edits, plan, auto-review, or full-access"
55 )),
56 }
57 }
58
59 #[derive(Args, Debug, Default, Clone, PartialEq, Eq)]
60 pub struct RuntimeOptions {
61 /// Path to the config file to load instead of the default.
62 #[arg(long)]
63 pub config: Option<PathBuf>,
64 /// Config profile to apply (a `[profiles.<name>]` table).
65 #[arg(long)]
66 pub profile: Option<String>,
67 /// Workspace directory for Codewhale file tools (`-w` is a legacy alias).
68 #[arg(
69 short = 'C',
70 short_alias = 'w',
71 long = "workspace",
72 alias = "cd",
73 value_name = "DIR"
74 )]
75 pub workspace: Option<PathBuf>,
76 /// Enable terminal mouse capture for scrolling and transcript selection.
77 #[arg(long = "mouse-capture", conflicts_with = "no_mouse_capture")]
78 pub mouse_capture: bool,
79 /// Disable terminal mouse capture for terminal-native text selection.
80 #[arg(long = "no-mouse-capture", conflicts_with = "mouse_capture")]
81 pub no_mouse_capture: bool,
82 /// Skip onboarding screens.
83 #[arg(long)]
84 pub skip_onboarding: bool,
85 /// Start a fresh session without automatic resume or crash recovery.
86 #[arg(long)]
87 pub fresh: bool,
88 /// Skip project config and workspace overlays for this run.
89 #[arg(long)]
90 pub no_project_config: bool,
91 /// Enable a feature for this run (repeatable).
92 #[arg(long = "enable", value_name = "FEATURE", action = clap::ArgAction::Append, global = true)]
93 pub enable: Vec<String>,
94 /// Disable a feature for this run (repeatable).
95 #[arg(long = "disable", value_name = "FEATURE", action = clap::ArgAction::Append, global = true)]
96 pub disable: Vec<String>,
97 /// Run with Full Access: no approval prompts and no Codewhale sandbox
98 /// (the same as `yolo = true`; `--yolo` is an alias).
99 #[arg(long = "full-access", alias = "yolo")]
100 pub yolo: bool,
101 #[arg(
102 long = "permission-mode",
103 value_name = "MODE",
104 value_parser = parse_permission_mode,
105 global = true,
106 help = "Start in this permission mode: ask, accept-edits, plan, auto-review, or full-access."
107 )]
108 pub permission_mode: Option<PermissionMode>,
109 /// Maximum number of concurrent sub-agents (1-128; default 64).
110 #[arg(long)]
111 pub max_subagents: Option<usize>,
112 /// Enable verbose logging.
113 #[arg(short, long)]
114 pub verbose: bool,
115 /// Start account-owned web remote control for this interactive session.
116 #[arg(long, hide = true)]
117 pub remote_control: bool,
118 #[arg(skip)]
119 pub control_frontend: Option<codewhale_runtime::runtime_control::RuntimeControlFrontend>,
120 }
121
122 impl RuntimeOptions {
123 // A `run` passthrough can still carry startup flags. Preserve the old
124 // duplicate/conflict refusal rather than silently picking an authority.
125 pub fn merge(mut self, command: Self) -> Result<Self> {
126 macro_rules! scalar {
127 ($field:ident, $flag:literal) => {
128 if self.$field.is_some() && command.$field.is_some() {
129 bail!(
130 "{} cannot be supplied both before and inside the command",
131 $flag
132 );
133 }
134 self.$field = self.$field.or(command.$field);
135 };
136 }
137 macro_rules! flag {
138 ($field:ident, $name:literal) => {
139 if self.$field && command.$field {
140 bail!(
141 "{} cannot be supplied both before and inside the command",
142 $name
143 );
144 }
145 self.$field |= command.$field;
146 };
147 }
148 scalar!(config, "--config");
149 scalar!(profile, "--profile");
150 scalar!(workspace, "--workspace");
151 scalar!(max_subagents, "--max-subagents");
152 scalar!(permission_mode, "--permission-mode");
153 scalar!(control_frontend, "selected control frontend");
154 flag!(mouse_capture, "--mouse-capture");
155 flag!(no_mouse_capture, "--no-mouse-capture");
156 flag!(skip_onboarding, "--skip-onboarding");
157 flag!(fresh, "--fresh");
158 flag!(no_project_config, "--no-project-config");
159 flag!(yolo, "--full-access");
160 flag!(verbose, "--verbose");
161 flag!(remote_control, "--remote-control");
162 if self.mouse_capture && self.no_mouse_capture {
163 bail!("--mouse-capture conflicts with --no-mouse-capture");
164 }
165 if self.permission_mode.is_some() && self.yolo {
166 bail!("--permission-mode cannot be combined with --full-access or --yolo");
167 }
168 self.enable.extend(command.enable);
169 self.disable.extend(command.disable);
170 Ok(self)
171 }
172
173 pub fn apply_features(&self, config: &mut codewhale_runtime::config::Config) -> Result<()> {
174 for feature in &self.enable {
175 config.set_feature(feature, true)?;
176 }
177 for feature in &self.disable {
178 config.set_feature(feature, false)?;
179 }
180 Ok(())
181 }
182 }
183
184 #[cfg(test)]
185 mod tests {
186 use super::*;
187
188 #[test]
189 fn typed_startup_rejects_competing_config_and_opposing_mouse_facts() {
190 let root = RuntimeOptions {
191 config: Some("root.toml".into()),
192 ..Default::default()
193 };
194 let command = RuntimeOptions {
195 config: Some("command.toml".into()),
196 ..Default::default()
197 };
198 assert!(
199 root.merge(command)
200 .unwrap_err()
201 .to_string()
202 .contains("--config")
203 );
204 let root = RuntimeOptions {
205 mouse_capture: true,
206 ..Default::default()
207 };
208 let command = RuntimeOptions {
209 no_mouse_capture: true,
210 ..Default::default()
211 };
212 assert!(
213 root.merge(command)
214 .unwrap_err()
215 .to_string()
216 .contains("conflicts")
217 );
218 }
219
220 #[test]
221 fn command_scope_facts_and_feature_disables_preserve_the_config_floor() {
222 let root = RuntimeOptions {
223 enable: vec!["web_search".into()],
224 ..Default::default()
225 };
226 let command = RuntimeOptions {
227 workspace: Some("command workspace".into()),
228 disable: vec!["web_search".into()],
229 no_project_config: true,
230 ..Default::default()
231 };
232 let merged = root.merge(command).unwrap();
233 assert_eq!(merged.workspace, Some(PathBuf::from("command workspace")));
234 assert!(merged.no_project_config);
235 let mut config = codewhale_runtime::config::Config::default();
236 merged.apply_features(&mut config).unwrap();
237 assert!(
238 !config
239 .features()
240 .enabled(codewhale_runtime::features::Feature::WebSearch)
241 );
242 }
243
244 #[test]
245 fn permission_mode_parses_all_five_modes_and_rejects_unknown_or_never() {
246 assert_eq!(parse_permission_mode("ask"), Ok(PermissionMode::Ask));
247 assert_eq!(
248 parse_permission_mode("accept-edits"),
249 Ok(PermissionMode::AcceptEdits)
250 );
251 assert_eq!(parse_permission_mode("plan"), Ok(PermissionMode::Plan));
252 assert_eq!(
253 parse_permission_mode("auto-review"),
254 Ok(PermissionMode::AutoReview)
255 );
256 assert_eq!(
257 parse_permission_mode("full-access"),
258 Ok(PermissionMode::FullAccess)
259 );
260 assert!(parse_permission_mode("never").is_err());
261 assert!(parse_permission_mode("bogus").is_err());
262 }
263 }
264
264 lines RUST