1use serde_json::Value;
4
5#[derive(Debug, Clone, Default)]
7pub struct LaunchOptions {
8 pub reasoning_effort: Option<String>,
10 pub max_output_tokens: Option<u64>,
12 pub temperature: Option<f64>,
14 pub mcp_config: Option<String>,
16 pub strict_mcp_config: bool,
18 pub additional_directories: Vec<String>,
20 pub attachments: Vec<String>,
23 pub json_schema: Option<String>,
27 pub json_schema_file: Option<String>,
32 pub system_prompt_file: Option<String>,
34 pub append_system_prompt_file: Option<String>,
37}
38
39impl PartialEq for LaunchOptions {
40 fn eq(&self, other: &Self) -> bool {
41 let Self {
42 reasoning_effort,
43 max_output_tokens,
44 temperature,
45 mcp_config,
46 strict_mcp_config,
47 additional_directories,
48 attachments,
49 json_schema,
50 json_schema_file,
51 system_prompt_file,
52 append_system_prompt_file,
53 } = self;
54 let same_temperature = match (*temperature, other.temperature) {
56 (None, None) => true,
57 (Some(a), Some(b)) => {
58 a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
59 || (a.is_nan() && b.is_nan())
60 }
61 _ => false,
62 };
63 same_temperature
64 && reasoning_effort == &other.reasoning_effort
65 && max_output_tokens == &other.max_output_tokens
66 && mcp_config == &other.mcp_config
67 && strict_mcp_config == &other.strict_mcp_config
68 && additional_directories == &other.additional_directories
69 && attachments == &other.attachments
70 && json_schema == &other.json_schema
71 && json_schema_file == &other.json_schema_file
72 && system_prompt_file == &other.system_prompt_file
73 && append_system_prompt_file == &other.append_system_prompt_file
74 }
75}
76
77impl Eq for LaunchOptions {}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct LaunchCapabilities {
82 pub reasoning_effort: bool,
83 pub reasoning_efforts: Option<&'static [&'static str]>,
85 pub max_output_tokens: bool,
87 pub temperature: bool,
89 pub mcp_config: bool,
90 pub strict_mcp_config: bool,
91 pub additional_directories: bool,
92 pub attachments: bool,
93 pub json_schema: bool,
94}
95
96pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
98
99pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
101
102const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
103
104pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
105 "--max-output-tokens must be a positive safe integer";
106pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";
107
108pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
109 if (1..=9_007_199_254_740_991).contains(&value) {
111 Ok(())
112 } else {
113 Err(MAX_OUTPUT_TOKENS_ERROR)
114 }
115}
116
117pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
118 if value.is_finite() && value >= 0.0 {
119 Ok(())
120 } else {
121 Err(TEMPERATURE_ERROR)
122 }
123}
124
125pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
127 let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
129 "claude" => (
130 true,
131 Some(CLAUDE_REASONING_EFFORTS),
132 true,
133 true,
134 true,
135 false,
136 true,
137 ),
138 "codex" => (
139 true,
140 Some(CODEX_REASONING_EFFORTS),
141 true,
142 false,
143 true,
144 true,
145 true,
146 ),
147 "opencode" => (true, None, false, false, false, true, false),
149 "gemini" => (false, None, false, false, true, false, false),
150 "qwen" => (false, None, true, false, true, false, true),
151 _ => (false, None, false, false, false, false, false),
152 };
153 LaunchCapabilities {
154 reasoning_effort: effort,
155 reasoning_efforts: efforts,
156 max_output_tokens: matches!(tool, "claude" | "opencode"),
157 temperature: tool == "agent",
158 mcp_config: mcp,
159 strict_mcp_config: strict,
160 additional_directories: dirs,
161 attachments,
162 json_schema,
163 }
164}
165
166pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
171 check_launch_options_against(tool, launch, &launch_capabilities(tool))
172}
173
174pub fn check_launch_options_against(
180 tool: &str,
181 launch: &LaunchOptions,
182 capabilities: &LaunchCapabilities,
183) -> Result<(), String> {
184 type Pick = fn(&LaunchCapabilities) -> bool;
185 if let Some(value) = launch.max_output_tokens {
186 validate_max_output_tokens(value)?;
187 }
188 if let Some(value) = launch.temperature {
189 validate_temperature(value)?;
190 }
191 let checks: [(bool, Pick, &str); 8] = [
192 (
193 launch.max_output_tokens.is_some(),
194 |c| c.max_output_tokens,
195 "an output token budget (--max-output-tokens)",
196 ),
197 (
198 launch.temperature.is_some(),
199 |c| c.temperature,
200 "sampling temperature (--temperature)",
201 ),
202 (
203 launch.reasoning_effort.is_some(),
204 |c| c.reasoning_effort,
205 "reasoning effort (--reasoning-effort)",
206 ),
207 (
208 launch.mcp_config.is_some(),
209 |c| c.mcp_config,
210 "MCP server configuration (--mcp-config)",
211 ),
212 (
213 launch.strict_mcp_config,
214 |c| c.strict_mcp_config,
215 "strict MCP configuration (--strict-mcp-config)",
216 ),
217 (
218 !launch.additional_directories.is_empty(),
219 |c| c.additional_directories,
220 "additional directories (--add-dir)",
221 ),
222 (
223 !launch.attachments.is_empty(),
224 |c| c.attachments,
225 "file attachments (--attach)",
226 ),
227 (
228 launch.json_schema.is_some(),
229 |c| c.json_schema,
230 "structured output (--json-schema)",
231 ),
232 ];
233 for (requested, pick, label) in checks {
234 if requested && !pick(capabilities) {
235 let supporting: Vec<&str> = TOOLS
236 .iter()
237 .copied()
238 .filter(|name| pick(&launch_capabilities(name)))
239 .collect();
240 return Err(format!(
241 "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
242 tool,
243 label,
244 supporting.join(", ")
245 ));
246 }
247 }
248 Ok(())
249}
250
251pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
256 assert!(
257 !reasoning_effort.is_empty()
258 && reasoning_effort
259 .chars()
260 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
261 "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
262 reasoning_effort
263 );
264 reasoning_effort.to_string()
265}
266
267pub fn json_schema_arg(json_schema: &str) -> String {
273 let schema: Value = serde_json::from_str(json_schema)
274 .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
275 assert!(
276 schema.is_object(),
277 "jsonSchema must be a JSON Schema object or its JSON text"
278 );
279 schema.to_string()
280}
281
282fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
283 for path in paths {
284 assert!(!path.is_empty(), "{name} must not be empty");
285 args.push(flag.to_string());
286 args.push(path.clone());
287 }
288}
289
290pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
292 push_paths(args, flag, directories, "additional directories");
293}
294
295pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
298 push_paths(args, flag, attachments, "attachments");
299}
300
301fn toml_key(key: &str) -> String {
303 if !key.is_empty()
304 && key
305 .chars()
306 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
307 {
308 key.to_string()
309 } else {
310 Value::String(key.to_string()).to_string()
311 }
312}
313
314pub fn to_toml_value(value: &Value) -> Result<String, String> {
320 match value {
321 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
322 Value::Array(items) => {
323 let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
324 Ok(format!("[{}]", parts?.join(", ")))
325 }
326 Value::Object(map) => {
327 let mut parts = Vec::new();
328 for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
329 parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
330 }
331 Ok(format!("{{{}}}", parts.join(", ")))
332 }
333 Value::Null => Err("Cannot encode null as a TOML value".to_string()),
334 }
335}
336
337pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
347 if !mcp_config.trim_start().starts_with('{') {
348 return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
349 }
350 let config: Value = serde_json::from_str(mcp_config)
351 .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
352 let servers = config
353 .get("mcpServers")
354 .and_then(Value::as_object)
355 .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
356 let mut table = serde_json::Map::new();
357 for (name, server) in servers {
358 let mut server = server
359 .as_object()
360 .cloned()
361 .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
362 server.remove("type");
363 if let Some(headers) = server.remove("headers") {
364 server.insert("http_headers".to_string(), headers);
365 }
366 table.insert(name.clone(), Value::Object(server));
367 }
368 Ok(format!(
369 "mcp_servers={}",
370 to_toml_value(&Value::Object(table))?
371 ))
372}