Skip to main content

agent_commander/tools/
launch_options.rs

1//! Shared launch options and their native tool capabilities.
2
3use serde_json::Value;
4
5/// Launch options shared by every tool
6#[derive(Debug, Clone, Default)]
7pub struct LaunchOptions {
8    /// Native reasoning effort / variant level (`--reasoning-effort`)
9    pub reasoning_effort: Option<String>,
10    /// Native output token budget (`--max-output-tokens`)
11    pub max_output_tokens: Option<u64>,
12    /// Native sampling temperature (`--temperature`)
13    pub temperature: Option<f64>,
14    /// MCP servers: config file path or inline `{"mcpServers": {...}}` JSON
15    pub mcp_config: Option<String>,
16    /// Use only the servers from `mcp_config`
17    pub strict_mcp_config: bool,
18    /// Extra directories the agent may access (`--add-dir`)
19    pub additional_directories: Vec<String>,
20    /// Files attached to the prompt (`--attach`): Codex `--image`, OpenCode
21    /// `--file`. Relative paths resolve against the working directory.
22    pub attachments: Vec<String>,
23    /// JSON Schema text the final answer must match (`--json-schema`):
24    /// Claude and Qwen `--json-schema`, Codex `--output-schema`. The result
25    /// is reported as `metadata.structured_output`.
26    pub json_schema: Option<String>,
27    /// File holding `json_schema` (written by [`crate::Agent::start`] so the
28    /// schema does not appear on the command line; issue #60). Codex reads it
29    /// with `--output-schema <file>`, Qwen with `--json-schema @<file>` and
30    /// Claude through `--json-schema "$(cat <file>)"`.
31    pub json_schema_file: Option<String>,
32    /// Claude `--system-prompt-file` (replaces the inline `--system-prompt`)
33    pub system_prompt_file: Option<String>,
34    /// Claude `--append-system-prompt-file` (replaces the inline
35    /// `--append-system-prompt`)
36    pub append_system_prompt_file: Option<String>,
37    /// Route the tool through an API gateway (`--gateway-base-url` /
38    /// `--gateway-router` with `--gateway-token-env`; claude, codex)
39    pub gateway: Option<GatewayOptions>,
40}
41
42/// An API gateway for one run (issue #65).
43///
44/// Exactly one of `base_url` (used as is) or `router` (a link-assistant/router
45/// origin; the tool's service path is appended), plus `token_env`, the
46/// variable holding the token. Only the
47/// variable name reaches the command line; the tool reads the value from its
48/// environment, which always inherits `token_env`.
49///
50/// `standalone_web_search` says the gateway serves Codex's standalone search
51/// route (`POST <base_url>/alpha/search`, issue #74); `None` means `true`
52/// with `router` (link-assistant/router serves it) and `false` with
53/// `base_url`.
54#[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    /// A gateway reached at `base_url` as is.
64    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    /// A link-assistant/router origin; each tool appends its service path.
74    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    /// Declare whether the gateway serves Codex's standalone search route.
84    #[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    /// Whether the gateway serves Codex's standalone search route: the
91    /// explicit setting, else `true` for a router origin.
92    pub fn serves_standalone_web_search(&self) -> bool {
93        self.standalone_web_search
94            .unwrap_or_else(|| self.router.is_some())
95    }
96}
97
98/// Paths of the link-assistant/router service per tool.
99pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
100    ("claude", "/api/services/anthropic"),
101    ("codex", "/api/services/codex/v1"),
102];
103
104/// Codex provider id used for the gateway; Codex does not let `-c` redefine
105/// its built-in ids (`openai`, `ollama`, ...).
106pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
107
108/// Credentials Claude Code prefers over `apiKeyHelper` (cloud providers,
109/// `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`); removed with `env -u`.
110pub 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
118/// Validate a gateway URL: http(s), a host, and no credentials, query,
119/// fragment or whitespace, so no secret can reach the command line.
120/// Trailing slashes are removed.
121fn 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
146/// Validate a gateway and resolve its base URL for `tool`. With `router`,
147/// the base URL is `None` when the tool has no router service path.
148///
149/// # Errors
150/// Returns the message for a missing or duplicate URL, an invalid URL or an
151/// invalid `token_env`.
152pub 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
189/// Fail when the gateway token variable is missing or empty in the child
190/// environment `env` (issue #65).
191///
192/// # Errors
193/// Returns an error naming the variable.
194pub 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
213/// Resolve the gateway base URL and token variable for `tool`.
214///
215/// # Errors
216/// Returns the validation message, or names the tool when it has no router
217/// service path.
218pub 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
228/// Claude Code `--settings` value: `apiKeyHelper` prints the token from the
229/// named variable, so only the variable name is on the command line.
230pub fn claude_gateway_settings(token_env: &str) -> String {
231    serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
232}
233
234/// Codex `-c` overrides defining and selecting a custom provider whose
235/// bearer token Codex reads from `env_key`.
236///
237/// With `standalone_web_search`, the provider also declares
238/// `supports_standalone_web_search = true` (issue #74). Codex sends no hosted
239/// `web_search` tool to a Responses Lite model; it installs the standalone
240/// `web.run` tool (`POST <base_url>/alpha/search`) only for the built-in
241/// OpenAI provider or a provider with that flag (openai/codex rust-v0.172.0
242/// `core/src/tools/spec_plan.rs`, `ext/web-search/src/extension.rs`).
243pub 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        // Even a NaN constructed before launch validation must equal itself.
280        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/// What a tool natively supports among the launch options
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
307pub struct LaunchCapabilities {
308    pub reasoning_effort: bool,
309    /// Documented effort levels; `None` when the tool or provider defines them
310    pub reasoning_efforts: Option<&'static [&'static str]>,
311    /// Whether the tool has a native per-launch output token budget.
312    pub max_output_tokens: bool,
313    /// Whether the tool has a native per-launch temperature setting.
314    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    /// Whether the tool can be routed through an API gateway (`gateway`)
321    pub gateway: bool,
322}
323
324/// Claude Code `--effort` levels
325pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
326
327/// Codex `model_reasoning_effort` levels
328pub 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    // Match JavaScript's exact integer range across the two APIs.
338    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
353/// Describe what a tool natively supports among the launch options.
354pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
355    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
356    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        // `--variant` names are defined by the model provider.
376        "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
395/// Check that every requested launch option has a native control in the tool.
396///
397/// # Errors
398/// Returns the message naming the tools that do support the option.
399pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
400    check_launch_options_against(tool, launch, &launch_capabilities(tool))
401}
402
403/// Check the requested launch options against the given capabilities, such
404/// as a `ToolOverrides::launch_capabilities` replacement.
405///
406/// # Errors
407/// Returns the message naming the tools that do support the option.
408pub 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
488/// Validate a reasoning effort / variant name.
489///
490/// # Panics
491/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
492pub 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
504/// Validate the JSON Schema the final answer must match and return it as
505/// compact JSON text.
506///
507/// A top-level `$schema` dialect declaration is dropped (issue #68): Claude
508/// Code validates the schema with Ajv's default draft-07 instance, which
509/// rejects the draft 2020-12 meta-schema URI that zod 4 emits ("no schema
510/// with key or ref"). The dialect declaration carries no constraint, so every
511/// tool receives the schema without it; nested `$schema` keys are kept.
512///
513/// # Panics
514/// Panics when the text is not JSON or not a JSON object.
515pub 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
533/// Push `flag value` for each extra directory.
534pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
535    push_paths(args, flag, directories, "additional directories");
536}
537
538/// Push `flag file` for each attachment; a repeated flag keeps variadic
539/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
540pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
541    push_paths(args, flag, attachments, "attachments");
542}
543
544/// Encode a TOML key segment (bare when possible, quoted otherwise).
545fn 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
557/// Encode a JSON value as an inline TOML value. JSON string escapes are a
558/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
559///
560/// # Errors
561/// Returns an error for `null` at the top level.
562pub 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
580/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
581/// Codex `-c mcp_servers={...}` override.
582///
583/// `headers` becomes `http_headers`
584/// and the transport `type` is dropped (Codex infers it from `command` or
585/// `url`). Codex merges the table into the servers from `config.toml`.
586///
587/// # Errors
588/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
589pub 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}