Skip to main content

agent_commander/tools/
launch_options.rs

1//! Launch options shared by every tool (issue #57).
2//!
3//! Reasoning effort, MCP servers, extra workspace directories, file
4//! attachments and a JSON Schema for structured output. Each tool maps them onto its own native flag; a tool without a native flag rejects the option instead of
5//! silently dropping it.
6
7use serde_json::Value;
8
9/// Launch options shared by every tool
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct LaunchOptions {
12    /// Native reasoning effort / variant level (`--reasoning-effort`)
13    pub reasoning_effort: Option<String>,
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}
28
29/// What a tool natively supports among the launch options
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct LaunchCapabilities {
32    pub reasoning_effort: bool,
33    /// Documented effort levels; `None` when the tool or provider defines them
34    pub reasoning_efforts: Option<&'static [&'static str]>,
35    pub mcp_config: bool,
36    pub strict_mcp_config: bool,
37    pub additional_directories: bool,
38    pub attachments: bool,
39    pub json_schema: bool,
40}
41
42/// Claude Code `--effort` levels
43pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
44
45/// Codex `model_reasoning_effort` levels
46pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
47
48const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
49
50/// Describe what a tool natively supports among the launch options.
51pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
52    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
53    let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
54        "claude" => (
55            true,
56            Some(CLAUDE_REASONING_EFFORTS),
57            true,
58            true,
59            true,
60            false,
61            true,
62        ),
63        "codex" => (
64            true,
65            Some(CODEX_REASONING_EFFORTS),
66            true,
67            false,
68            true,
69            true,
70            true,
71        ),
72        // `--variant` names are defined by the model provider.
73        "opencode" => (true, None, false, false, false, true, false),
74        "gemini" => (false, None, false, false, true, false, false),
75        "qwen" => (false, None, true, false, true, false, true),
76        _ => (false, None, false, false, false, false, false),
77    };
78    LaunchCapabilities {
79        reasoning_effort: effort,
80        reasoning_efforts: efforts,
81        mcp_config: mcp,
82        strict_mcp_config: strict,
83        additional_directories: dirs,
84        attachments,
85        json_schema,
86    }
87}
88
89/// Check that every requested launch option has a native flag in the tool.
90///
91/// # Errors
92/// Returns the message naming the tools that do support the option.
93pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
94    check_launch_options_against(tool, launch, &launch_capabilities(tool))
95}
96
97/// Check the requested launch options against the given capabilities, such
98/// as a `ToolOverrides::launch_capabilities` replacement.
99///
100/// # Errors
101/// Returns the message naming the tools that do support the option.
102pub fn check_launch_options_against(
103    tool: &str,
104    launch: &LaunchOptions,
105    capabilities: &LaunchCapabilities,
106) -> Result<(), String> {
107    type Pick = fn(&LaunchCapabilities) -> bool;
108    let checks: [(bool, Pick, &str); 6] = [
109        (
110            launch.reasoning_effort.is_some(),
111            |c| c.reasoning_effort,
112            "reasoning effort (--reasoning-effort)",
113        ),
114        (
115            launch.mcp_config.is_some(),
116            |c| c.mcp_config,
117            "MCP server configuration (--mcp-config)",
118        ),
119        (
120            launch.strict_mcp_config,
121            |c| c.strict_mcp_config,
122            "strict MCP configuration (--strict-mcp-config)",
123        ),
124        (
125            !launch.additional_directories.is_empty(),
126            |c| c.additional_directories,
127            "additional directories (--add-dir)",
128        ),
129        (
130            !launch.attachments.is_empty(),
131            |c| c.attachments,
132            "file attachments (--attach)",
133        ),
134        (
135            launch.json_schema.is_some(),
136            |c| c.json_schema,
137            "structured output (--json-schema)",
138        ),
139    ];
140    for (requested, pick, label) in checks {
141        if requested && !pick(capabilities) {
142            let supporting: Vec<&str> = TOOLS
143                .iter()
144                .copied()
145                .filter(|name| pick(&launch_capabilities(name)))
146                .collect();
147            return Err(format!(
148                "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
149                tool,
150                label,
151                supporting.join(", ")
152            ));
153        }
154    }
155    Ok(())
156}
157
158/// Validate a reasoning effort / variant name.
159///
160/// # Panics
161/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
162pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
163    assert!(
164        !reasoning_effort.is_empty()
165            && reasoning_effort
166                .chars()
167                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
168        "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
169        reasoning_effort
170    );
171    reasoning_effort.to_string()
172}
173
174/// Validate the JSON Schema the final answer must match and return it as
175/// compact JSON text.
176///
177/// # Panics
178/// Panics when the text is not JSON or not a JSON object.
179pub fn json_schema_arg(json_schema: &str) -> String {
180    let schema: Value = serde_json::from_str(json_schema)
181        .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
182    assert!(
183        schema.is_object(),
184        "jsonSchema must be a JSON Schema object or its JSON text"
185    );
186    schema.to_string()
187}
188
189fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
190    for path in paths {
191        assert!(!path.is_empty(), "{name} must not be empty");
192        args.push(flag.to_string());
193        args.push(path.clone());
194    }
195}
196
197/// Push `flag value` for each extra directory.
198pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
199    push_paths(args, flag, directories, "additional directories");
200}
201
202/// Push `flag file` for each attachment; a repeated flag keeps variadic
203/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
204pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
205    push_paths(args, flag, attachments, "attachments");
206}
207
208/// Encode a TOML key segment (bare when possible, quoted otherwise).
209fn toml_key(key: &str) -> String {
210    if !key.is_empty()
211        && key
212            .chars()
213            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
214    {
215        key.to_string()
216    } else {
217        Value::String(key.to_string()).to_string()
218    }
219}
220
221/// Encode a JSON value as an inline TOML value. JSON string escapes are a
222/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
223///
224/// # Errors
225/// Returns an error for `null` at the top level.
226pub fn to_toml_value(value: &Value) -> Result<String, String> {
227    match value {
228        Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
229        Value::Array(items) => {
230            let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
231            Ok(format!("[{}]", parts?.join(", ")))
232        }
233        Value::Object(map) => {
234            let mut parts = Vec::new();
235            for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
236                parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
237            }
238            Ok(format!("{{{}}}", parts.join(", ")))
239        }
240        Value::Null => Err("Cannot encode null as a TOML value".to_string()),
241    }
242}
243
244/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
245/// Codex `-c mcp_servers={...}` override.
246///
247/// `headers` becomes `http_headers`
248/// and the transport `type` is dropped (Codex infers it from `command` or
249/// `url`). Codex merges the table into the servers from `config.toml`.
250///
251/// # Errors
252/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
253pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
254    if !mcp_config.trim_start().starts_with('{') {
255        return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
256    }
257    let config: Value = serde_json::from_str(mcp_config)
258        .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
259    let servers = config
260        .get("mcpServers")
261        .and_then(Value::as_object)
262        .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
263    let mut table = serde_json::Map::new();
264    for (name, server) in servers {
265        let mut server = server
266            .as_object()
267            .cloned()
268            .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
269        server.remove("type");
270        if let Some(headers) = server.remove("headers") {
271            server.insert("http_headers".to_string(), headers);
272        }
273        table.insert(name.clone(), Value::Object(server));
274    }
275    Ok(format!(
276        "mcp_servers={}",
277        to_toml_value(&Value::Object(table))?
278    ))
279}