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 pub gateway: Option<GatewayOptions>,
40}
41
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct GatewayOptions {
51 pub base_url: Option<String>,
52 pub router: Option<String>,
53 pub token_env: String,
54}
55
56impl GatewayOptions {
57 pub fn with_base_url(base_url: impl Into<String>, token_env: impl Into<String>) -> Self {
59 Self {
60 base_url: Some(base_url.into()),
61 router: None,
62 token_env: token_env.into(),
63 }
64 }
65
66 pub fn with_router(router: impl Into<String>, token_env: impl Into<String>) -> Self {
68 Self {
69 base_url: None,
70 router: Some(router.into()),
71 token_env: token_env.into(),
72 }
73 }
74}
75
76pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
78 ("claude", "/api/services/anthropic"),
79 ("codex", "/api/services/codex/v1"),
80];
81
82pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
85
86pub const CLAUDE_GATEWAY_UNSET_ENV: &[&str] = &[
89 "ANTHROPIC_AUTH_TOKEN",
90 "ANTHROPIC_API_KEY",
91 "CLAUDE_CODE_USE_BEDROCK",
92 "CLAUDE_CODE_USE_VERTEX",
93 "CLAUDE_CODE_USE_FOUNDRY",
94];
95
96fn normalize_gateway_url(value: &str, name: &str) -> Result<String, String> {
100 let error = || format!("{name} must be an http(s) URL without credentials, query or fragment");
101 let lower = value.to_ascii_lowercase();
102 let rest = if lower.starts_with("https://") {
103 &value[8..]
104 } else if lower.starts_with("http://") {
105 &value[7..]
106 } else {
107 return Err(error());
108 };
109 let authority = rest.split('/').next().unwrap_or_default();
110 let host = authority
111 .rsplit_once(':')
112 .map_or(authority, |(host, _)| host);
113 if host.is_empty()
114 || authority.contains('@')
115 || value.contains('?')
116 || value.contains('#')
117 || value.chars().any(char::is_whitespace)
118 {
119 return Err(error());
120 }
121 Ok(value.trim_end_matches('/').to_string())
122}
123
124pub fn normalize_gateway(
131 gateway: &GatewayOptions,
132 tool: Option<&str>,
133) -> Result<GatewayOptions, String> {
134 if gateway.base_url.is_some() == gateway.router.is_some() {
135 return Err(
136 "gateway needs exactly one of baseUrl (--gateway-base-url) or router (--gateway-router)"
137 .to_string(),
138 );
139 }
140 if !crate::tools::shell::is_valid_env_name(&gateway.token_env) {
141 return Err("gateway.tokenEnv (--gateway-token-env) must name an environment variable ([A-Za-z_][A-Za-z0-9_]*)".to_string());
142 }
143 let router = gateway
144 .router
145 .as_deref()
146 .map(|url| normalize_gateway_url(url, "gateway.router (--gateway-router)"))
147 .transpose()?;
148 let base_url = match (&router, tool) {
149 (Some(origin), Some(tool)) => ROUTER_SERVICE_PATHS
150 .iter()
151 .find(|(name, _)| *name == tool)
152 .map(|(_, path)| format!("{origin}{path}")),
153 _ => gateway
154 .base_url
155 .as_deref()
156 .map(|url| normalize_gateway_url(url, "gateway.baseUrl (--gateway-base-url)"))
157 .transpose()?,
158 };
159 Ok(GatewayOptions {
160 base_url,
161 router,
162 token_env: gateway.token_env.clone(),
163 })
164}
165
166pub fn check_gateway_token(
172 gateway: Option<&GatewayOptions>,
173 env: &[(String, String)],
174) -> Result<(), String> {
175 match gateway {
176 Some(gateway)
177 if !env
178 .iter()
179 .any(|(key, value)| key == &gateway.token_env && !value.is_empty()) =>
180 {
181 Err(format!(
182 "gateway.tokenEnv: environment variable {} is not set or empty",
183 gateway.token_env
184 ))
185 }
186 _ => Ok(()),
187 }
188}
189
190pub fn resolve_gateway(gateway: &GatewayOptions, tool: &str) -> Result<(String, String), String> {
196 let normalized = normalize_gateway(gateway, Some(tool))?;
197 match normalized.base_url {
198 Some(base_url) => Ok((base_url, normalized.token_env)),
199 None => Err(format!(
200 "Tool \"{tool}\" has no link-assistant/router service path; pass gateway.baseUrl (--gateway-base-url) instead."
201 )),
202 }
203}
204
205pub fn claude_gateway_settings(token_env: &str) -> String {
208 serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
209}
210
211pub fn codex_gateway_overrides(base_url: &str, token_env: &str) -> Vec<String> {
214 let prefix = format!("model_providers.{CODEX_GATEWAY_PROVIDER_ID}");
215 let toml = |value: &str| Value::String(value.to_string()).to_string();
216 vec![
217 format!("model_provider={}", toml(CODEX_GATEWAY_PROVIDER_ID)),
218 format!("{prefix}.name={}", toml("agent-commander gateway")),
219 format!("{prefix}.base_url={}", toml(base_url)),
220 format!("{prefix}.env_key={}", toml(token_env)),
221 format!("{prefix}.wire_api={}", toml("responses")),
222 ]
223}
224
225impl PartialEq for LaunchOptions {
226 fn eq(&self, other: &Self) -> bool {
227 let Self {
228 reasoning_effort,
229 max_output_tokens,
230 temperature,
231 mcp_config,
232 strict_mcp_config,
233 additional_directories,
234 attachments,
235 json_schema,
236 json_schema_file,
237 system_prompt_file,
238 append_system_prompt_file,
239 gateway,
240 } = self;
241 let same_temperature = match (*temperature, other.temperature) {
243 (None, None) => true,
244 (Some(a), Some(b)) => {
245 a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
246 || (a.is_nan() && b.is_nan())
247 }
248 _ => false,
249 };
250 same_temperature
251 && reasoning_effort == &other.reasoning_effort
252 && max_output_tokens == &other.max_output_tokens
253 && mcp_config == &other.mcp_config
254 && strict_mcp_config == &other.strict_mcp_config
255 && additional_directories == &other.additional_directories
256 && attachments == &other.attachments
257 && json_schema == &other.json_schema
258 && json_schema_file == &other.json_schema_file
259 && system_prompt_file == &other.system_prompt_file
260 && append_system_prompt_file == &other.append_system_prompt_file
261 && gateway == &other.gateway
262 }
263}
264
265impl Eq for LaunchOptions {}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub struct LaunchCapabilities {
270 pub reasoning_effort: bool,
271 pub reasoning_efforts: Option<&'static [&'static str]>,
273 pub max_output_tokens: bool,
275 pub temperature: bool,
277 pub mcp_config: bool,
278 pub strict_mcp_config: bool,
279 pub additional_directories: bool,
280 pub attachments: bool,
281 pub json_schema: bool,
282 pub gateway: bool,
284}
285
286pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
288
289pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
291
292const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
293
294pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
295 "--max-output-tokens must be a positive safe integer";
296pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";
297
298pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
299 if (1..=9_007_199_254_740_991).contains(&value) {
301 Ok(())
302 } else {
303 Err(MAX_OUTPUT_TOKENS_ERROR)
304 }
305}
306
307pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
308 if value.is_finite() && value >= 0.0 {
309 Ok(())
310 } else {
311 Err(TEMPERATURE_ERROR)
312 }
313}
314
315pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
317 let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
319 "claude" => (
320 true,
321 Some(CLAUDE_REASONING_EFFORTS),
322 true,
323 true,
324 true,
325 false,
326 true,
327 ),
328 "codex" => (
329 true,
330 Some(CODEX_REASONING_EFFORTS),
331 true,
332 false,
333 true,
334 true,
335 true,
336 ),
337 "opencode" => (true, None, false, false, false, true, false),
339 "gemini" => (false, None, false, false, true, false, false),
340 "qwen" => (false, None, true, false, true, false, true),
341 _ => (false, None, false, false, false, false, false),
342 };
343 LaunchCapabilities {
344 reasoning_effort: effort,
345 reasoning_efforts: efforts,
346 max_output_tokens: matches!(tool, "claude" | "opencode"),
347 temperature: tool == "agent",
348 mcp_config: mcp,
349 strict_mcp_config: strict,
350 additional_directories: dirs,
351 attachments,
352 json_schema,
353 gateway: matches!(tool, "claude" | "codex"),
354 }
355}
356
357pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
362 check_launch_options_against(tool, launch, &launch_capabilities(tool))
363}
364
365pub fn check_launch_options_against(
371 tool: &str,
372 launch: &LaunchOptions,
373 capabilities: &LaunchCapabilities,
374) -> Result<(), String> {
375 type Pick = fn(&LaunchCapabilities) -> bool;
376 if let Some(value) = launch.max_output_tokens {
377 validate_max_output_tokens(value)?;
378 }
379 if let Some(value) = launch.temperature {
380 validate_temperature(value)?;
381 }
382 if let Some(gateway) = &launch.gateway {
383 normalize_gateway(gateway, Some(tool))?;
384 }
385 let checks: [(bool, Pick, &str); 9] = [
386 (
387 launch.max_output_tokens.is_some(),
388 |c| c.max_output_tokens,
389 "an output token budget (--max-output-tokens)",
390 ),
391 (
392 launch.temperature.is_some(),
393 |c| c.temperature,
394 "sampling temperature (--temperature)",
395 ),
396 (
397 launch.reasoning_effort.is_some(),
398 |c| c.reasoning_effort,
399 "reasoning effort (--reasoning-effort)",
400 ),
401 (
402 launch.mcp_config.is_some(),
403 |c| c.mcp_config,
404 "MCP server configuration (--mcp-config)",
405 ),
406 (
407 launch.strict_mcp_config,
408 |c| c.strict_mcp_config,
409 "strict MCP configuration (--strict-mcp-config)",
410 ),
411 (
412 !launch.additional_directories.is_empty(),
413 |c| c.additional_directories,
414 "additional directories (--add-dir)",
415 ),
416 (
417 !launch.attachments.is_empty(),
418 |c| c.attachments,
419 "file attachments (--attach)",
420 ),
421 (
422 launch.json_schema.is_some(),
423 |c| c.json_schema,
424 "structured output (--json-schema)",
425 ),
426 (
427 launch.gateway.is_some(),
428 |c| c.gateway,
429 "an API gateway (--gateway-base-url / --gateway-router)",
430 ),
431 ];
432 for (requested, pick, label) in checks {
433 if requested && !pick(capabilities) {
434 let supporting: Vec<&str> = TOOLS
435 .iter()
436 .copied()
437 .filter(|name| pick(&launch_capabilities(name)))
438 .collect();
439 return Err(format!(
440 "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
441 tool,
442 label,
443 supporting.join(", ")
444 ));
445 }
446 }
447 Ok(())
448}
449
450pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
455 assert!(
456 !reasoning_effort.is_empty()
457 && reasoning_effort
458 .chars()
459 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
460 "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
461 reasoning_effort
462 );
463 reasoning_effort.to_string()
464}
465
466pub fn json_schema_arg(json_schema: &str) -> String {
472 let schema: Value = serde_json::from_str(json_schema)
473 .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
474 assert!(
475 schema.is_object(),
476 "jsonSchema must be a JSON Schema object or its JSON text"
477 );
478 schema.to_string()
479}
480
481fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
482 for path in paths {
483 assert!(!path.is_empty(), "{name} must not be empty");
484 args.push(flag.to_string());
485 args.push(path.clone());
486 }
487}
488
489pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
491 push_paths(args, flag, directories, "additional directories");
492}
493
494pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
497 push_paths(args, flag, attachments, "attachments");
498}
499
500fn toml_key(key: &str) -> String {
502 if !key.is_empty()
503 && key
504 .chars()
505 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
506 {
507 key.to_string()
508 } else {
509 Value::String(key.to_string()).to_string()
510 }
511}
512
513pub fn to_toml_value(value: &Value) -> Result<String, String> {
519 match value {
520 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
521 Value::Array(items) => {
522 let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
523 Ok(format!("[{}]", parts?.join(", ")))
524 }
525 Value::Object(map) => {
526 let mut parts = Vec::new();
527 for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
528 parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
529 }
530 Ok(format!("{{{}}}", parts.join(", ")))
531 }
532 Value::Null => Err("Cannot encode null as a TOML value".to_string()),
533 }
534}
535
536pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
546 if !mcp_config.trim_start().starts_with('{') {
547 return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
548 }
549 let config: Value = serde_json::from_str(mcp_config)
550 .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
551 let servers = config
552 .get("mcpServers")
553 .and_then(Value::as_object)
554 .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
555 let mut table = serde_json::Map::new();
556 for (name, server) in servers {
557 let mut server = server
558 .as_object()
559 .cloned()
560 .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
561 server.remove("type");
562 if let Some(headers) = server.remove("headers") {
563 server.insert("http_headers".to_string(), headers);
564 }
565 table.insert(name.clone(), Value::Object(server));
566 }
567 Ok(format!(
568 "mcp_servers={}",
569 to_toml_value(&Value::Object(table))?
570 ))
571}