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)]
55pub struct GatewayOptions {
56 pub base_url: Option<String>,
57 pub router: Option<String>,
58 pub token_env: String,
59 pub standalone_web_search: Option<bool>,
60}
61
62impl GatewayOptions {
63 pub fn with_base_url(base_url: impl Into<String>, token_env: impl Into<String>) -> Self {
65 Self {
66 base_url: Some(base_url.into()),
67 router: None,
68 token_env: token_env.into(),
69 standalone_web_search: None,
70 }
71 }
72
73 pub fn with_router(router: impl Into<String>, token_env: impl Into<String>) -> Self {
75 Self {
76 base_url: None,
77 router: Some(router.into()),
78 token_env: token_env.into(),
79 standalone_web_search: None,
80 }
81 }
82
83 #[must_use]
85 pub fn with_standalone_web_search(mut self, enabled: bool) -> Self {
86 self.standalone_web_search = Some(enabled);
87 self
88 }
89
90 pub fn serves_standalone_web_search(&self) -> bool {
93 self.standalone_web_search
94 .unwrap_or_else(|| self.router.is_some())
95 }
96}
97
98pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
100 ("claude", "/api/services/anthropic"),
101 ("codex", "/api/services/codex/v1"),
102 ("agent", "/api/services/openai/v1"),
103 ("opencode", "/api/services/openai/v1"),
104];
105
106pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
109
110pub const CLAUDE_GATEWAY_UNSET_ENV: &[&str] = &[
113 "ANTHROPIC_AUTH_TOKEN",
114 "ANTHROPIC_API_KEY",
115 "CLAUDE_CODE_USE_BEDROCK",
116 "CLAUDE_CODE_USE_VERTEX",
117 "CLAUDE_CODE_USE_FOUNDRY",
118];
119
120fn normalize_gateway_url(value: &str, name: &str) -> Result<String, String> {
124 let error = || format!("{name} must be an http(s) URL without credentials, query or fragment");
125 let lower = value.to_ascii_lowercase();
126 let rest = if lower.starts_with("https://") {
127 &value[8..]
128 } else if lower.starts_with("http://") {
129 &value[7..]
130 } else {
131 return Err(error());
132 };
133 let authority = rest.split('/').next().unwrap_or_default();
134 let host = authority
135 .rsplit_once(':')
136 .map_or(authority, |(host, _)| host);
137 if host.is_empty()
138 || authority.contains('@')
139 || value.contains('?')
140 || value.contains('#')
141 || value.chars().any(char::is_whitespace)
142 {
143 return Err(error());
144 }
145 Ok(value.trim_end_matches('/').to_string())
146}
147
148pub fn normalize_gateway(
155 gateway: &GatewayOptions,
156 tool: Option<&str>,
157) -> Result<GatewayOptions, String> {
158 if gateway.base_url.is_some() == gateway.router.is_some() {
159 return Err(
160 "gateway needs exactly one of baseUrl (--gateway-base-url) or router (--gateway-router)"
161 .to_string(),
162 );
163 }
164 if !crate::tools::shell::is_valid_env_name(&gateway.token_env) {
165 return Err("gateway.tokenEnv (--gateway-token-env) must name an environment variable ([A-Za-z_][A-Za-z0-9_]*)".to_string());
166 }
167 let router = gateway
168 .router
169 .as_deref()
170 .map(|url| normalize_gateway_url(url, "gateway.router (--gateway-router)"))
171 .transpose()?;
172 let base_url = match (&router, tool) {
173 (Some(origin), Some(tool)) => ROUTER_SERVICE_PATHS
174 .iter()
175 .find(|(name, _)| *name == tool)
176 .map(|(_, path)| format!("{origin}{path}")),
177 _ => gateway
178 .base_url
179 .as_deref()
180 .map(|url| normalize_gateway_url(url, "gateway.baseUrl (--gateway-base-url)"))
181 .transpose()?,
182 };
183 Ok(GatewayOptions {
184 base_url,
185 router,
186 token_env: gateway.token_env.clone(),
187 standalone_web_search: Some(gateway.serves_standalone_web_search()),
188 })
189}
190
191pub fn check_gateway_token(
197 gateway: Option<&GatewayOptions>,
198 env: &[(String, String)],
199) -> Result<(), String> {
200 match gateway {
201 Some(gateway)
202 if !env
203 .iter()
204 .any(|(key, value)| key == &gateway.token_env && !value.is_empty()) =>
205 {
206 Err(format!(
207 "gateway.tokenEnv: environment variable {} is not set or empty",
208 gateway.token_env
209 ))
210 }
211 _ => Ok(()),
212 }
213}
214
215pub fn resolve_gateway(gateway: &GatewayOptions, tool: &str) -> Result<(String, String), String> {
221 let normalized = normalize_gateway(gateway, Some(tool))?;
222 match normalized.base_url {
223 Some(base_url) => Ok((base_url, normalized.token_env)),
224 None => Err(format!(
225 "Tool \"{tool}\" has no link-assistant/router service path; pass gateway.baseUrl (--gateway-base-url) instead."
226 )),
227 }
228}
229
230pub fn claude_gateway_settings(token_env: &str) -> String {
233 serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
234}
235
236pub fn codex_gateway_overrides(
246 base_url: &str,
247 token_env: &str,
248 standalone_web_search: bool,
249) -> Vec<String> {
250 let prefix = format!("model_providers.{CODEX_GATEWAY_PROVIDER_ID}");
251 let toml = |value: &str| Value::String(value.to_string()).to_string();
252 let mut overrides = vec![
253 format!("model_provider={}", toml(CODEX_GATEWAY_PROVIDER_ID)),
254 format!("{prefix}.name={}", toml("agent-commander gateway")),
255 format!("{prefix}.base_url={}", toml(base_url)),
256 format!("{prefix}.env_key={}", toml(token_env)),
257 format!("{prefix}.wire_api={}", toml("responses")),
258 ];
259 if standalone_web_search {
260 overrides.push(format!("{prefix}.supports_standalone_web_search=true"));
261 }
262 overrides
263}
264
265impl PartialEq for LaunchOptions {
266 fn eq(&self, other: &Self) -> bool {
267 let Self {
268 reasoning_effort,
269 max_output_tokens,
270 temperature,
271 mcp_config,
272 strict_mcp_config,
273 additional_directories,
274 attachments,
275 json_schema,
276 json_schema_file,
277 system_prompt_file,
278 append_system_prompt_file,
279 gateway,
280 } = self;
281 let same_temperature = match (*temperature, other.temperature) {
283 (None, None) => true,
284 (Some(a), Some(b)) => {
285 a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
286 || (a.is_nan() && b.is_nan())
287 }
288 _ => false,
289 };
290 same_temperature
291 && reasoning_effort == &other.reasoning_effort
292 && max_output_tokens == &other.max_output_tokens
293 && mcp_config == &other.mcp_config
294 && strict_mcp_config == &other.strict_mcp_config
295 && additional_directories == &other.additional_directories
296 && attachments == &other.attachments
297 && json_schema == &other.json_schema
298 && json_schema_file == &other.json_schema_file
299 && system_prompt_file == &other.system_prompt_file
300 && append_system_prompt_file == &other.append_system_prompt_file
301 && gateway == &other.gateway
302 }
303}
304
305impl Eq for LaunchOptions {}
306
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct LaunchCapabilities {
310 pub reasoning_effort: bool,
311 pub reasoning_efforts: Option<&'static [&'static str]>,
313 pub max_output_tokens: bool,
315 pub temperature: bool,
317 pub mcp_config: bool,
318 pub strict_mcp_config: bool,
319 pub additional_directories: bool,
320 pub attachments: bool,
321 pub json_schema: bool,
322 pub gateway: bool,
324 pub timeout: bool,
326}
327
328pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
330
331pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
333
334const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
335
336pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
337 "--max-output-tokens must be a positive safe integer";
338pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";
339
340pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
341 if (1..=9_007_199_254_740_991).contains(&value) {
343 Ok(())
344 } else {
345 Err(MAX_OUTPUT_TOKENS_ERROR)
346 }
347}
348
349pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
350 if value.is_finite() && value >= 0.0 {
351 Ok(())
352 } else {
353 Err(TEMPERATURE_ERROR)
354 }
355}
356
357pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
359 let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
361 "claude" => (
362 true,
363 Some(CLAUDE_REASONING_EFFORTS),
364 true,
365 true,
366 true,
367 false,
368 true,
369 ),
370 "codex" => (
371 true,
372 Some(CODEX_REASONING_EFFORTS),
373 true,
374 false,
375 true,
376 true,
377 true,
378 ),
379 "opencode" => (true, None, false, false, false, true, false),
381 "gemini" => (false, None, false, false, true, false, false),
382 "qwen" => (false, None, true, false, true, false, true),
383 _ => (false, None, false, false, false, false, false),
384 };
385 LaunchCapabilities {
386 reasoning_effort: effort,
387 reasoning_efforts: efforts,
388 max_output_tokens: matches!(tool, "claude" | "opencode"),
389 temperature: tool == "agent",
390 mcp_config: mcp,
391 strict_mcp_config: strict,
392 additional_directories: dirs,
393 attachments,
394 json_schema,
395 gateway: matches!(tool, "claude" | "codex" | "agent" | "opencode"),
396 timeout: true,
397 }
398}
399
400pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
405 check_launch_options_against(tool, launch, &launch_capabilities(tool))
406}
407
408pub fn check_launch_options_against(
414 tool: &str,
415 launch: &LaunchOptions,
416 capabilities: &LaunchCapabilities,
417) -> Result<(), String> {
418 type Pick = fn(&LaunchCapabilities) -> bool;
419 if let Some(value) = launch.max_output_tokens {
420 validate_max_output_tokens(value)?;
421 }
422 if let Some(value) = launch.temperature {
423 validate_temperature(value)?;
424 }
425 if let Some(gateway) = &launch.gateway {
426 normalize_gateway(gateway, Some(tool))?;
427 }
428 let checks: [(bool, Pick, &str); 9] = [
429 (
430 launch.max_output_tokens.is_some(),
431 |c| c.max_output_tokens,
432 "an output token budget (--max-output-tokens)",
433 ),
434 (
435 launch.temperature.is_some(),
436 |c| c.temperature,
437 "sampling temperature (--temperature)",
438 ),
439 (
440 launch.reasoning_effort.is_some(),
441 |c| c.reasoning_effort,
442 "reasoning effort (--reasoning-effort)",
443 ),
444 (
445 launch.mcp_config.is_some(),
446 |c| c.mcp_config,
447 "MCP server configuration (--mcp-config)",
448 ),
449 (
450 launch.strict_mcp_config,
451 |c| c.strict_mcp_config,
452 "strict MCP configuration (--strict-mcp-config)",
453 ),
454 (
455 !launch.additional_directories.is_empty(),
456 |c| c.additional_directories,
457 "additional directories (--add-dir)",
458 ),
459 (
460 !launch.attachments.is_empty(),
461 |c| c.attachments,
462 "file attachments (--attach)",
463 ),
464 (
465 launch.json_schema.is_some(),
466 |c| c.json_schema,
467 "structured output (--json-schema)",
468 ),
469 (
470 launch.gateway.is_some(),
471 |c| c.gateway,
472 "an API gateway (--gateway-base-url / --gateway-router)",
473 ),
474 ];
475 for (requested, pick, label) in checks {
476 if requested && !pick(capabilities) {
477 let supporting: Vec<&str> = TOOLS
478 .iter()
479 .copied()
480 .filter(|name| pick(&launch_capabilities(name)))
481 .collect();
482 return Err(format!(
483 "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
484 tool,
485 label,
486 supporting.join(", ")
487 ));
488 }
489 }
490 Ok(())
491}
492
493pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
498 assert!(
499 !reasoning_effort.is_empty()
500 && reasoning_effort
501 .chars()
502 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
503 "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
504 reasoning_effort
505 );
506 reasoning_effort.to_string()
507}
508
509pub fn json_schema_arg(json_schema: &str) -> String {
521 let mut schema: Value = serde_json::from_str(json_schema)
522 .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
523 let Some(object) = schema.as_object_mut() else {
524 panic!("jsonSchema must be a JSON Schema object or its JSON text");
525 };
526 object.remove("$schema");
527 schema.to_string()
528}
529
530fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
531 for path in paths {
532 assert!(!path.is_empty(), "{name} must not be empty");
533 args.push(flag.to_string());
534 args.push(path.clone());
535 }
536}
537
538pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
540 push_paths(args, flag, directories, "additional directories");
541}
542
543pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
546 push_paths(args, flag, attachments, "attachments");
547}
548
549fn toml_key(key: &str) -> String {
551 if !key.is_empty()
552 && key
553 .chars()
554 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
555 {
556 key.to_string()
557 } else {
558 Value::String(key.to_string()).to_string()
559 }
560}
561
562pub fn to_toml_value(value: &Value) -> Result<String, String> {
568 match value {
569 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
570 Value::Array(items) => {
571 let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
572 Ok(format!("[{}]", parts?.join(", ")))
573 }
574 Value::Object(map) => {
575 let mut parts = Vec::new();
576 for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
577 parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
578 }
579 Ok(format!("{{{}}}", parts.join(", ")))
580 }
581 Value::Null => Err("Cannot encode null as a TOML value".to_string()),
582 }
583}
584
585pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
595 if !mcp_config.trim_start().starts_with('{') {
596 return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
597 }
598 let config: Value = serde_json::from_str(mcp_config)
599 .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
600 let servers = config
601 .get("mcpServers")
602 .and_then(Value::as_object)
603 .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
604 let mut table = serde_json::Map::new();
605 for (name, server) in servers {
606 let mut server = server
607 .as_object()
608 .cloned()
609 .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
610 server.remove("type");
611 if let Some(headers) = server.remove("headers") {
612 server.insert("http_headers".to_string(), headers);
613 }
614 table.insert(name.clone(), Value::Object(server));
615 }
616 Ok(format!(
617 "mcp_servers={}",
618 to_toml_value(&Value::Object(table))?
619 ))
620}