1use serde_json::Value;
8
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct LaunchOptions {
12 pub reasoning_effort: Option<String>,
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
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct LaunchCapabilities {
42 pub reasoning_effort: bool,
43 pub reasoning_efforts: Option<&'static [&'static str]>,
45 pub mcp_config: bool,
46 pub strict_mcp_config: bool,
47 pub additional_directories: bool,
48 pub attachments: bool,
49 pub json_schema: bool,
50}
51
52pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
54
55pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
57
58const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
59
60pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
62 let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
64 "claude" => (
65 true,
66 Some(CLAUDE_REASONING_EFFORTS),
67 true,
68 true,
69 true,
70 false,
71 true,
72 ),
73 "codex" => (
74 true,
75 Some(CODEX_REASONING_EFFORTS),
76 true,
77 false,
78 true,
79 true,
80 true,
81 ),
82 "opencode" => (true, None, false, false, false, true, false),
84 "gemini" => (false, None, false, false, true, false, false),
85 "qwen" => (false, None, true, false, true, false, true),
86 _ => (false, None, false, false, false, false, false),
87 };
88 LaunchCapabilities {
89 reasoning_effort: effort,
90 reasoning_efforts: efforts,
91 mcp_config: mcp,
92 strict_mcp_config: strict,
93 additional_directories: dirs,
94 attachments,
95 json_schema,
96 }
97}
98
99pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
104 check_launch_options_against(tool, launch, &launch_capabilities(tool))
105}
106
107pub fn check_launch_options_against(
113 tool: &str,
114 launch: &LaunchOptions,
115 capabilities: &LaunchCapabilities,
116) -> Result<(), String> {
117 type Pick = fn(&LaunchCapabilities) -> bool;
118 let checks: [(bool, Pick, &str); 6] = [
119 (
120 launch.reasoning_effort.is_some(),
121 |c| c.reasoning_effort,
122 "reasoning effort (--reasoning-effort)",
123 ),
124 (
125 launch.mcp_config.is_some(),
126 |c| c.mcp_config,
127 "MCP server configuration (--mcp-config)",
128 ),
129 (
130 launch.strict_mcp_config,
131 |c| c.strict_mcp_config,
132 "strict MCP configuration (--strict-mcp-config)",
133 ),
134 (
135 !launch.additional_directories.is_empty(),
136 |c| c.additional_directories,
137 "additional directories (--add-dir)",
138 ),
139 (
140 !launch.attachments.is_empty(),
141 |c| c.attachments,
142 "file attachments (--attach)",
143 ),
144 (
145 launch.json_schema.is_some(),
146 |c| c.json_schema,
147 "structured output (--json-schema)",
148 ),
149 ];
150 for (requested, pick, label) in checks {
151 if requested && !pick(capabilities) {
152 let supporting: Vec<&str> = TOOLS
153 .iter()
154 .copied()
155 .filter(|name| pick(&launch_capabilities(name)))
156 .collect();
157 return Err(format!(
158 "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
159 tool,
160 label,
161 supporting.join(", ")
162 ));
163 }
164 }
165 Ok(())
166}
167
168pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
173 assert!(
174 !reasoning_effort.is_empty()
175 && reasoning_effort
176 .chars()
177 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
178 "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
179 reasoning_effort
180 );
181 reasoning_effort.to_string()
182}
183
184pub fn json_schema_arg(json_schema: &str) -> String {
190 let schema: Value = serde_json::from_str(json_schema)
191 .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
192 assert!(
193 schema.is_object(),
194 "jsonSchema must be a JSON Schema object or its JSON text"
195 );
196 schema.to_string()
197}
198
199fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
200 for path in paths {
201 assert!(!path.is_empty(), "{name} must not be empty");
202 args.push(flag.to_string());
203 args.push(path.clone());
204 }
205}
206
207pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
209 push_paths(args, flag, directories, "additional directories");
210}
211
212pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
215 push_paths(args, flag, attachments, "attachments");
216}
217
218fn toml_key(key: &str) -> String {
220 if !key.is_empty()
221 && key
222 .chars()
223 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
224 {
225 key.to_string()
226 } else {
227 Value::String(key.to_string()).to_string()
228 }
229}
230
231pub fn to_toml_value(value: &Value) -> Result<String, String> {
237 match value {
238 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
239 Value::Array(items) => {
240 let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
241 Ok(format!("[{}]", parts?.join(", ")))
242 }
243 Value::Object(map) => {
244 let mut parts = Vec::new();
245 for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
246 parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
247 }
248 Ok(format!("{{{}}}", parts.join(", ")))
249 }
250 Value::Null => Err("Cannot encode null as a TOML value".to_string()),
251 }
252}
253
254pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
264 if !mcp_config.trim_start().starts_with('{') {
265 return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
266 }
267 let config: Value = serde_json::from_str(mcp_config)
268 .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
269 let servers = config
270 .get("mcpServers")
271 .and_then(Value::as_object)
272 .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
273 let mut table = serde_json::Map::new();
274 for (name, server) in servers {
275 let mut server = server
276 .as_object()
277 .cloned()
278 .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
279 server.remove("type");
280 if let Some(headers) = server.remove("headers") {
281 server.insert("http_headers".to_string(), headers);
282 }
283 table.insert(name.clone(), Value::Object(server));
284 }
285 Ok(format!(
286 "mcp_servers={}",
287 to_toml_value(&Value::Object(table))?
288 ))
289}