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