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#[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    /// A gateway reached at `base_url` as is.
58    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    /// A link-assistant/router origin; each tool appends its service path.
67    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
76/// Paths of the link-assistant/router service per tool.
77pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
78    ("claude", "/api/services/anthropic"),
79    ("codex", "/api/services/codex/v1"),
80];
81
82/// Codex provider id used for the gateway; Codex does not let `-c` redefine
83/// its built-in ids (`openai`, `ollama`, ...).
84pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
85
86/// Credentials Claude Code prefers over `apiKeyHelper` (cloud providers,
87/// `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`); removed with `env -u`.
88pub 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
96/// Validate a gateway URL: http(s), a host, and no credentials, query,
97/// fragment or whitespace, so no secret can reach the command line.
98/// Trailing slashes are removed.
99fn 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
124/// Validate a gateway and resolve its base URL for `tool`. With `router`,
125/// the base URL is `None` when the tool has no router service path.
126///
127/// # Errors
128/// Returns the message for a missing or duplicate URL, an invalid URL or an
129/// invalid `token_env`.
130pub 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
166/// Fail when the gateway token variable is missing or empty in the child
167/// environment `env` (issue #65).
168///
169/// # Errors
170/// Returns an error naming the variable.
171pub 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
190/// Resolve the gateway base URL and token variable for `tool`.
191///
192/// # Errors
193/// Returns the validation message, or names the tool when it has no router
194/// service path.
195pub 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
205/// Claude Code `--settings` value: `apiKeyHelper` prints the token from the
206/// named variable, so only the variable name is on the command line.
207pub fn claude_gateway_settings(token_env: &str) -> String {
208    serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
209}
210
211/// Codex `-c` overrides defining and selecting a custom provider whose
212/// bearer token Codex reads from `env_key`.
213pub 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        // Even a NaN constructed before launch validation must equal itself.
242        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/// What a tool natively supports among the launch options
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub struct LaunchCapabilities {
270    pub reasoning_effort: bool,
271    /// Documented effort levels; `None` when the tool or provider defines them
272    pub reasoning_efforts: Option<&'static [&'static str]>,
273    /// Whether the tool has a native per-launch output token budget.
274    pub max_output_tokens: bool,
275    /// Whether the tool has a native per-launch temperature setting.
276    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    /// Whether the tool can be routed through an API gateway (`gateway`)
283    pub gateway: bool,
284}
285
286/// Claude Code `--effort` levels
287pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
288
289/// Codex `model_reasoning_effort` levels
290pub 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    // Match JavaScript's exact integer range across the two APIs.
300    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
315/// Describe what a tool natively supports among the launch options.
316pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
317    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
318    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        // `--variant` names are defined by the model provider.
338        "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
357/// Check that every requested launch option has a native control in the tool.
358///
359/// # Errors
360/// Returns the message naming the tools that do support the option.
361pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
362    check_launch_options_against(tool, launch, &launch_capabilities(tool))
363}
364
365/// Check the requested launch options against the given capabilities, such
366/// as a `ToolOverrides::launch_capabilities` replacement.
367///
368/// # Errors
369/// Returns the message naming the tools that do support the option.
370pub 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
450/// Validate a reasoning effort / variant name.
451///
452/// # Panics
453/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
454pub 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
466/// Validate the JSON Schema the final answer must match and return it as
467/// compact JSON text.
468///
469/// # Panics
470/// Panics when the text is not JSON or not a JSON object.
471pub 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
489/// Push `flag value` for each extra directory.
490pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
491    push_paths(args, flag, directories, "additional directories");
492}
493
494/// Push `flag file` for each attachment; a repeated flag keeps variadic
495/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
496pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
497    push_paths(args, flag, attachments, "attachments");
498}
499
500/// Encode a TOML key segment (bare when possible, quoted otherwise).
501fn 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
513/// Encode a JSON value as an inline TOML value. JSON string escapes are a
514/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
515///
516/// # Errors
517/// Returns an error for `null` at the top level.
518pub 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
536/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
537/// Codex `-c mcp_servers={...}` override.
538///
539/// `headers` becomes `http_headers`
540/// and the transport `type` is dropped (Codex infers it from `command` or
541/// `url`). Codex merges the table into the servers from `config.toml`.
542///
543/// # Errors
544/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
545pub 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}