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}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct LaunchCapabilities {
32 pub reasoning_effort: bool,
33 pub reasoning_efforts: Option<&'static [&'static str]>,
35 pub mcp_config: bool,
36 pub strict_mcp_config: bool,
37 pub additional_directories: bool,
38 pub attachments: bool,
39 pub json_schema: bool,
40}
41
42pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
44
45pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
47
48const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
49
50pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
52 let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
54 "claude" => (
55 true,
56 Some(CLAUDE_REASONING_EFFORTS),
57 true,
58 true,
59 true,
60 false,
61 true,
62 ),
63 "codex" => (
64 true,
65 Some(CODEX_REASONING_EFFORTS),
66 true,
67 false,
68 true,
69 true,
70 true,
71 ),
72 "opencode" => (true, None, false, false, false, true, false),
74 "gemini" => (false, None, false, false, true, false, false),
75 "qwen" => (false, None, true, false, true, false, true),
76 _ => (false, None, false, false, false, false, false),
77 };
78 LaunchCapabilities {
79 reasoning_effort: effort,
80 reasoning_efforts: efforts,
81 mcp_config: mcp,
82 strict_mcp_config: strict,
83 additional_directories: dirs,
84 attachments,
85 json_schema,
86 }
87}
88
89pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
94 check_launch_options_against(tool, launch, &launch_capabilities(tool))
95}
96
97pub fn check_launch_options_against(
103 tool: &str,
104 launch: &LaunchOptions,
105 capabilities: &LaunchCapabilities,
106) -> Result<(), String> {
107 type Pick = fn(&LaunchCapabilities) -> bool;
108 let checks: [(bool, Pick, &str); 6] = [
109 (
110 launch.reasoning_effort.is_some(),
111 |c| c.reasoning_effort,
112 "reasoning effort (--reasoning-effort)",
113 ),
114 (
115 launch.mcp_config.is_some(),
116 |c| c.mcp_config,
117 "MCP server configuration (--mcp-config)",
118 ),
119 (
120 launch.strict_mcp_config,
121 |c| c.strict_mcp_config,
122 "strict MCP configuration (--strict-mcp-config)",
123 ),
124 (
125 !launch.additional_directories.is_empty(),
126 |c| c.additional_directories,
127 "additional directories (--add-dir)",
128 ),
129 (
130 !launch.attachments.is_empty(),
131 |c| c.attachments,
132 "file attachments (--attach)",
133 ),
134 (
135 launch.json_schema.is_some(),
136 |c| c.json_schema,
137 "structured output (--json-schema)",
138 ),
139 ];
140 for (requested, pick, label) in checks {
141 if requested && !pick(capabilities) {
142 let supporting: Vec<&str> = TOOLS
143 .iter()
144 .copied()
145 .filter(|name| pick(&launch_capabilities(name)))
146 .collect();
147 return Err(format!(
148 "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
149 tool,
150 label,
151 supporting.join(", ")
152 ));
153 }
154 }
155 Ok(())
156}
157
158pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
163 assert!(
164 !reasoning_effort.is_empty()
165 && reasoning_effort
166 .chars()
167 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
168 "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
169 reasoning_effort
170 );
171 reasoning_effort.to_string()
172}
173
174pub fn json_schema_arg(json_schema: &str) -> String {
180 let schema: Value = serde_json::from_str(json_schema)
181 .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
182 assert!(
183 schema.is_object(),
184 "jsonSchema must be a JSON Schema object or its JSON text"
185 );
186 schema.to_string()
187}
188
189fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
190 for path in paths {
191 assert!(!path.is_empty(), "{name} must not be empty");
192 args.push(flag.to_string());
193 args.push(path.clone());
194 }
195}
196
197pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
199 push_paths(args, flag, directories, "additional directories");
200}
201
202pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
205 push_paths(args, flag, attachments, "attachments");
206}
207
208fn toml_key(key: &str) -> String {
210 if !key.is_empty()
211 && key
212 .chars()
213 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
214 {
215 key.to_string()
216 } else {
217 Value::String(key.to_string()).to_string()
218 }
219}
220
221pub fn to_toml_value(value: &Value) -> Result<String, String> {
227 match value {
228 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
229 Value::Array(items) => {
230 let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
231 Ok(format!("[{}]", parts?.join(", ")))
232 }
233 Value::Object(map) => {
234 let mut parts = Vec::new();
235 for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
236 parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
237 }
238 Ok(format!("{{{}}}", parts.join(", ")))
239 }
240 Value::Null => Err("Cannot encode null as a TOML value".to_string()),
241 }
242}
243
244pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
254 if !mcp_config.trim_start().starts_with('{') {
255 return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
256 }
257 let config: Value = serde_json::from_str(mcp_config)
258 .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
259 let servers = config
260 .get("mcpServers")
261 .and_then(Value::as_object)
262 .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
263 let mut table = serde_json::Map::new();
264 for (name, server) in servers {
265 let mut server = server
266 .as_object()
267 .cloned()
268 .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
269 server.remove("type");
270 if let Some(headers) = server.remove("headers") {
271 server.insert("http_headers".to_string(), headers);
272 }
273 table.insert(name.clone(), Value::Object(server));
274 }
275 Ok(format!(
276 "mcp_servers={}",
277 to_toml_value(&Value::Object(table))?
278 ))
279}