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}
38
39impl PartialEq for LaunchOptions {
40    fn eq(&self, other: &Self) -> bool {
41        let Self {
42            reasoning_effort,
43            max_output_tokens,
44            temperature,
45            mcp_config,
46            strict_mcp_config,
47            additional_directories,
48            attachments,
49            json_schema,
50            json_schema_file,
51            system_prompt_file,
52            append_system_prompt_file,
53        } = self;
54        // Even a NaN constructed before launch validation must equal itself.
55        let same_temperature = match (*temperature, other.temperature) {
56            (None, None) => true,
57            (Some(a), Some(b)) => {
58                a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
59                    || (a.is_nan() && b.is_nan())
60            }
61            _ => false,
62        };
63        same_temperature
64            && reasoning_effort == &other.reasoning_effort
65            && max_output_tokens == &other.max_output_tokens
66            && mcp_config == &other.mcp_config
67            && strict_mcp_config == &other.strict_mcp_config
68            && additional_directories == &other.additional_directories
69            && attachments == &other.attachments
70            && json_schema == &other.json_schema
71            && json_schema_file == &other.json_schema_file
72            && system_prompt_file == &other.system_prompt_file
73            && append_system_prompt_file == &other.append_system_prompt_file
74    }
75}
76
77impl Eq for LaunchOptions {}
78
79/// What a tool natively supports among the launch options
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct LaunchCapabilities {
82    pub reasoning_effort: bool,
83    /// Documented effort levels; `None` when the tool or provider defines them
84    pub reasoning_efforts: Option<&'static [&'static str]>,
85    /// Whether the tool has a native per-launch output token budget.
86    pub max_output_tokens: bool,
87    /// Whether the tool has a native per-launch temperature setting.
88    pub temperature: bool,
89    pub mcp_config: bool,
90    pub strict_mcp_config: bool,
91    pub additional_directories: bool,
92    pub attachments: bool,
93    pub json_schema: bool,
94}
95
96/// Claude Code `--effort` levels
97pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
98
99/// Codex `model_reasoning_effort` levels
100pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
101
102const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
103
104pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
105    "--max-output-tokens must be a positive safe integer";
106pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";
107
108pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
109    // Match JavaScript's exact integer range across the two APIs.
110    if (1..=9_007_199_254_740_991).contains(&value) {
111        Ok(())
112    } else {
113        Err(MAX_OUTPUT_TOKENS_ERROR)
114    }
115}
116
117pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
118    if value.is_finite() && value >= 0.0 {
119        Ok(())
120    } else {
121        Err(TEMPERATURE_ERROR)
122    }
123}
124
125/// Describe what a tool natively supports among the launch options.
126pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
127    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
128    let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
129        "claude" => (
130            true,
131            Some(CLAUDE_REASONING_EFFORTS),
132            true,
133            true,
134            true,
135            false,
136            true,
137        ),
138        "codex" => (
139            true,
140            Some(CODEX_REASONING_EFFORTS),
141            true,
142            false,
143            true,
144            true,
145            true,
146        ),
147        // `--variant` names are defined by the model provider.
148        "opencode" => (true, None, false, false, false, true, false),
149        "gemini" => (false, None, false, false, true, false, false),
150        "qwen" => (false, None, true, false, true, false, true),
151        _ => (false, None, false, false, false, false, false),
152    };
153    LaunchCapabilities {
154        reasoning_effort: effort,
155        reasoning_efforts: efforts,
156        max_output_tokens: matches!(tool, "claude" | "opencode"),
157        temperature: tool == "agent",
158        mcp_config: mcp,
159        strict_mcp_config: strict,
160        additional_directories: dirs,
161        attachments,
162        json_schema,
163    }
164}
165
166/// Check that every requested launch option has a native control in the tool.
167///
168/// # Errors
169/// Returns the message naming the tools that do support the option.
170pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
171    check_launch_options_against(tool, launch, &launch_capabilities(tool))
172}
173
174/// Check the requested launch options against the given capabilities, such
175/// as a `ToolOverrides::launch_capabilities` replacement.
176///
177/// # Errors
178/// Returns the message naming the tools that do support the option.
179pub fn check_launch_options_against(
180    tool: &str,
181    launch: &LaunchOptions,
182    capabilities: &LaunchCapabilities,
183) -> Result<(), String> {
184    type Pick = fn(&LaunchCapabilities) -> bool;
185    if let Some(value) = launch.max_output_tokens {
186        validate_max_output_tokens(value)?;
187    }
188    if let Some(value) = launch.temperature {
189        validate_temperature(value)?;
190    }
191    let checks: [(bool, Pick, &str); 8] = [
192        (
193            launch.max_output_tokens.is_some(),
194            |c| c.max_output_tokens,
195            "an output token budget (--max-output-tokens)",
196        ),
197        (
198            launch.temperature.is_some(),
199            |c| c.temperature,
200            "sampling temperature (--temperature)",
201        ),
202        (
203            launch.reasoning_effort.is_some(),
204            |c| c.reasoning_effort,
205            "reasoning effort (--reasoning-effort)",
206        ),
207        (
208            launch.mcp_config.is_some(),
209            |c| c.mcp_config,
210            "MCP server configuration (--mcp-config)",
211        ),
212        (
213            launch.strict_mcp_config,
214            |c| c.strict_mcp_config,
215            "strict MCP configuration (--strict-mcp-config)",
216        ),
217        (
218            !launch.additional_directories.is_empty(),
219            |c| c.additional_directories,
220            "additional directories (--add-dir)",
221        ),
222        (
223            !launch.attachments.is_empty(),
224            |c| c.attachments,
225            "file attachments (--attach)",
226        ),
227        (
228            launch.json_schema.is_some(),
229            |c| c.json_schema,
230            "structured output (--json-schema)",
231        ),
232    ];
233    for (requested, pick, label) in checks {
234        if requested && !pick(capabilities) {
235            let supporting: Vec<&str> = TOOLS
236                .iter()
237                .copied()
238                .filter(|name| pick(&launch_capabilities(name)))
239                .collect();
240            return Err(format!(
241                "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
242                tool,
243                label,
244                supporting.join(", ")
245            ));
246        }
247    }
248    Ok(())
249}
250
251/// Validate a reasoning effort / variant name.
252///
253/// # Panics
254/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
255pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
256    assert!(
257        !reasoning_effort.is_empty()
258            && reasoning_effort
259                .chars()
260                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
261        "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
262        reasoning_effort
263    );
264    reasoning_effort.to_string()
265}
266
267/// Validate the JSON Schema the final answer must match and return it as
268/// compact JSON text.
269///
270/// # Panics
271/// Panics when the text is not JSON or not a JSON object.
272pub fn json_schema_arg(json_schema: &str) -> String {
273    let schema: Value = serde_json::from_str(json_schema)
274        .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
275    assert!(
276        schema.is_object(),
277        "jsonSchema must be a JSON Schema object or its JSON text"
278    );
279    schema.to_string()
280}
281
282fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
283    for path in paths {
284        assert!(!path.is_empty(), "{name} must not be empty");
285        args.push(flag.to_string());
286        args.push(path.clone());
287    }
288}
289
290/// Push `flag value` for each extra directory.
291pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
292    push_paths(args, flag, directories, "additional directories");
293}
294
295/// Push `flag file` for each attachment; a repeated flag keeps variadic
296/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
297pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
298    push_paths(args, flag, attachments, "attachments");
299}
300
301/// Encode a TOML key segment (bare when possible, quoted otherwise).
302fn toml_key(key: &str) -> String {
303    if !key.is_empty()
304        && key
305            .chars()
306            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
307    {
308        key.to_string()
309    } else {
310        Value::String(key.to_string()).to_string()
311    }
312}
313
314/// Encode a JSON value as an inline TOML value. JSON string escapes are a
315/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
316///
317/// # Errors
318/// Returns an error for `null` at the top level.
319pub fn to_toml_value(value: &Value) -> Result<String, String> {
320    match value {
321        Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
322        Value::Array(items) => {
323            let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
324            Ok(format!("[{}]", parts?.join(", ")))
325        }
326        Value::Object(map) => {
327            let mut parts = Vec::new();
328            for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
329                parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
330            }
331            Ok(format!("{{{}}}", parts.join(", ")))
332        }
333        Value::Null => Err("Cannot encode null as a TOML value".to_string()),
334    }
335}
336
337/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
338/// Codex `-c mcp_servers={...}` override.
339///
340/// `headers` becomes `http_headers`
341/// and the transport `type` is dropped (Codex infers it from `command` or
342/// `url`). Codex merges the table into the servers from `config.toml`.
343///
344/// # Errors
345/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
346pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
347    if !mcp_config.trim_start().starts_with('{') {
348        return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
349    }
350    let config: Value = serde_json::from_str(mcp_config)
351        .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
352    let servers = config
353        .get("mcpServers")
354        .and_then(Value::as_object)
355        .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
356    let mut table = serde_json::Map::new();
357    for (name, server) in servers {
358        let mut server = server
359            .as_object()
360            .cloned()
361            .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
362        server.remove("type");
363        if let Some(headers) = server.remove("headers") {
364            server.insert("http_headers".to_string(), headers);
365        }
366        table.insert(name.clone(), Value::Object(server));
367    }
368    Ok(format!(
369        "mcp_servers={}",
370        to_toml_value(&Value::Object(table))?
371    ))
372}