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, agent, opencode)
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    ("agent", "/api/services/openai/v1"),
103    ("opencode", "/api/services/openai/v1"),
104];
105
106/// Codex provider id used for the gateway; Codex does not let `-c` redefine
107/// its built-in ids (`openai`, `ollama`, ...).
108pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
109
110/// Credentials Claude Code prefers over `apiKeyHelper` (cloud providers,
111/// `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`); removed with `env -u`.
112pub 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
120/// Validate a gateway URL: http(s), a host, and no credentials, query,
121/// fragment or whitespace, so no secret can reach the command line.
122/// Trailing slashes are removed.
123fn 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
148/// Validate a gateway and resolve its base URL for `tool`. With `router`,
149/// the base URL is `None` when the tool has no router service path.
150///
151/// # Errors
152/// Returns the message for a missing or duplicate URL, an invalid URL or an
153/// invalid `token_env`.
154pub 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
191/// Fail when the gateway token variable is missing or empty in the child
192/// environment `env` (issue #65).
193///
194/// # Errors
195/// Returns an error naming the variable.
196pub 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
215/// Resolve the gateway base URL and token variable for `tool`.
216///
217/// # Errors
218/// Returns the validation message, or names the tool when it has no router
219/// service path.
220pub 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
230/// Claude Code `--settings` value: `apiKeyHelper` prints the token from the
231/// named variable, so only the variable name is on the command line.
232pub fn claude_gateway_settings(token_env: &str) -> String {
233    serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
234}
235
236/// Codex `-c` overrides defining and selecting a custom provider whose
237/// bearer token Codex reads from `env_key`.
238///
239/// With `standalone_web_search`, the provider also declares
240/// `supports_standalone_web_search = true` (issue #74). Codex sends no hosted
241/// `web_search` tool to a Responses Lite model; it installs the standalone
242/// `web.run` tool (`POST <base_url>/alpha/search`) only for the built-in
243/// OpenAI provider or a provider with that flag (openai/codex rust-v0.172.0
244/// `core/src/tools/spec_plan.rs`, `ext/web-search/src/extension.rs`).
245pub 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        // Even a NaN constructed before launch validation must equal itself.
282        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/// What a tool natively supports among the launch options
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct LaunchCapabilities {
310    pub reasoning_effort: bool,
311    /// Documented effort levels; `None` when the tool or provider defines them
312    pub reasoning_efforts: Option<&'static [&'static str]>,
313    /// Whether the tool has a native per-launch output token budget.
314    pub max_output_tokens: bool,
315    /// Whether the tool has a native per-launch temperature setting.
316    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    /// Whether the tool can be routed through an API gateway (`gateway`)
323    pub gateway: bool,
324    /// Whether the controller can enforce an attached run deadline.
325    pub timeout: bool,
326}
327
328/// Claude Code `--effort` levels
329pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
330
331/// Codex `model_reasoning_effort` levels
332pub 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    // Match JavaScript's exact integer range across the two APIs.
342    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
357/// Describe what a tool natively supports among the launch options.
358pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
359    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
360    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        // `--variant` names are defined by the model provider.
380        "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
400/// Check that every requested launch option has a native control in the tool.
401///
402/// # Errors
403/// Returns the message naming the tools that do support the option.
404pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
405    check_launch_options_against(tool, launch, &launch_capabilities(tool))
406}
407
408/// Check the requested launch options against the given capabilities, such
409/// as a `ToolOverrides::launch_capabilities` replacement.
410///
411/// # Errors
412/// Returns the message naming the tools that do support the option.
413pub 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
493/// Validate a reasoning effort / variant name.
494///
495/// # Panics
496/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
497pub 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
509/// Validate the JSON Schema the final answer must match and return it as
510/// compact JSON text.
511///
512/// A top-level `$schema` dialect declaration is dropped (issue #68): Claude
513/// Code validates the schema with Ajv's default draft-07 instance, which
514/// rejects the draft 2020-12 meta-schema URI that zod 4 emits ("no schema
515/// with key or ref"). The dialect declaration carries no constraint, so every
516/// tool receives the schema without it; nested `$schema` keys are kept.
517///
518/// # Panics
519/// Panics when the text is not JSON or not a JSON object.
520pub 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
538/// Push `flag value` for each extra directory.
539pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
540    push_paths(args, flag, directories, "additional directories");
541}
542
543/// Push `flag file` for each attachment; a repeated flag keeps variadic
544/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
545pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
546    push_paths(args, flag, attachments, "attachments");
547}
548
549/// Encode a TOML key segment (bare when possible, quoted otherwise).
550fn 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
562/// Encode a JSON value as an inline TOML value. JSON string escapes are a
563/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
564///
565/// # Errors
566/// Returns an error for `null` at the top level.
567pub 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
585/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
586/// Codex `-c mcp_servers={...}` override.
587///
588/// `headers` becomes `http_headers`
589/// and the transport `type` is dropped (Codex infers it from `command` or
590/// `url`). Codex merges the table into the servers from `config.toml`.
591///
592/// # Errors
593/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
594pub 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}