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