Skip to main content

agent_commander/tools/
claude.rs

1//! Claude CLI tool configuration
2//! Based on hive-mind's claude.lib.mjs implementation
3
4use super::usage::{self, count};
5use crate::streaming::parse_json_records;
6use crate::tools::launch_options::{
7    json_schema_arg, normalize_reasoning_effort, push_directories, validate_max_output_tokens,
8    LaunchOptions,
9};
10use crate::tools::shell::{build_command_head, escape_arg, file_content_arg, lookup_model_alias};
11use serde_json::Value;
12use std::collections::HashMap;
13
14/// Get the Claude model map
15pub fn get_model_map() -> HashMap<&'static str, &'static str> {
16    let mut map = HashMap::new();
17    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
18    map.insert("formal-ai", "formal-ai");
19    map.insert("formalai/formal-ai", "formal-ai");
20    map.insert("sonnet", "claude-sonnet-5-5");
21    map.insert("opus", "claude-opus-5-5");
22    map.insert("haiku", "claude-haiku-5-5");
23    map.insert("haiku-3-5", "claude-3-5-haiku-20241022");
24    map.insert("haiku-3", "claude-3-haiku-20240307");
25    map.insert("opusplan", "opusplan");
26    map.insert("fable", "claude-fable-5-1");
27    map.insert("fable-5-1", "claude-fable-5-1");
28    map.insert("claude-fable-5-1", "claude-fable-5-1");
29    map.insert("fable-5", "claude-fable-5");
30    map.insert("claude-fable-5", "claude-fable-5");
31    map.insert("mythos-5-1", "claude-mythos-5-1");
32    map.insert("claude-mythos-5-1", "claude-mythos-5-1");
33    map.insert("mythos-5", "claude-mythos-5");
34    map.insert("claude-mythos-5", "claude-mythos-5");
35    map.insert("sonnet-5-5", "claude-sonnet-5-5");
36    map.insert("sonnet-5", "claude-sonnet-5");
37    map.insert("sonnet-4-6", "claude-sonnet-4-6");
38    map.insert("opus-5-5", "claude-opus-5-5");
39    map.insert("opus-5", "claude-opus-5");
40    map.insert("opus-4-8", "claude-opus-4-8");
41    map.insert("opus-4-7", "claude-opus-4-7");
42    map.insert("opus-4-6", "claude-opus-4-6");
43    map.insert("opus-4-5", "claude-opus-4-5-20251101");
44    map.insert("sonnet-4-5", "claude-sonnet-4-5-20250929");
45    map.insert("haiku-5-5", "claude-haiku-5-5");
46    map.insert("haiku-4-5", "claude-haiku-4-5-20251001");
47    map.insert("claude-opus-5-5", "claude-opus-5-5");
48    map.insert("claude-opus-5", "claude-opus-5");
49    map.insert("claude-opus-4-8", "claude-opus-4-8");
50    map.insert("claude-opus-4-7", "claude-opus-4-7");
51    map.insert("claude-sonnet-5-5", "claude-sonnet-5-5");
52    map.insert("claude-sonnet-5", "claude-sonnet-5");
53    map.insert("claude-sonnet-4-6", "claude-sonnet-4-6");
54    map.insert("claude-opus-4-6", "claude-opus-4-6");
55    map.insert("claude-opus-4-5", "claude-opus-4-5-20251101");
56    map.insert("claude-sonnet-4-5", "claude-sonnet-4-5-20250929");
57    map.insert("claude-haiku-5-5", "claude-haiku-5-5");
58    map.insert("claude-haiku-4-5", "claude-haiku-4-5-20251001");
59    map.insert("best", "claude-fable-5-1");
60    map.insert("sonnet-5.5", "claude-sonnet-5-5");
61    map.insert("claude-sonnet-5.5", "claude-sonnet-5-5");
62    map.insert("opus-5.5", "claude-opus-5-5");
63    map.insert("claude-opus-5.5", "claude-opus-5-5");
64    map.insert("haiku-5.5", "claude-haiku-5-5");
65    map.insert("claude-haiku-5.5", "claude-haiku-5-5");
66    map.insert("fable-5.1", "claude-fable-5-1");
67    map.insert("claude-fable-5.1", "claude-fable-5-1");
68    map.insert("mythos-5.1", "claude-mythos-5-1");
69    map.insert("claude-mythos-5.1", "claude-mythos-5-1");
70    map.insert("sonnet-4.6", "claude-sonnet-4-6");
71    map.insert("claude-sonnet-4.6", "claude-sonnet-4-6");
72    map.insert("opus-4.8", "claude-opus-4-8");
73    map.insert("claude-opus-4.8", "claude-opus-4-8");
74    map.insert("opus-4.7", "claude-opus-4-7");
75    map.insert("claude-opus-4.7", "claude-opus-4-7");
76    map.insert("opus-4.6", "claude-opus-4-6");
77    map.insert("claude-opus-4.6", "claude-opus-4-6");
78    map.insert("mythos", "claude-mythos-5-1");
79    map.insert("haiku-3.5", "claude-3-5-haiku-20241022");
80    map.insert("opus-4.5", "claude-opus-4-5-20251101");
81    map.insert("sonnet-4.5", "claude-sonnet-4-5-20250929");
82    map.insert("haiku-4.5", "claude-haiku-4-5-20251001");
83    map.insert("claude-opus-4.5", "claude-opus-4-5-20251101");
84    map.insert("claude-sonnet-4.5", "claude-sonnet-4-5-20250929");
85    map.insert("claude-haiku-4.5", "claude-haiku-4-5-20251001");
86    map
87}
88
89/// Map model alias to full model ID
90///
91/// # Arguments
92/// * `model` - Model alias or full ID
93///
94/// # Returns
95/// Full model ID
96pub fn map_model_to_id(model: &str) -> String {
97    if let Some(base) = strip_one_million_suffix(model) {
98        return format!("{}[1m]", map_base_model_to_id(base));
99    }
100    map_base_model_to_id(model)
101}
102
103/// Rolling Claude Code aliases. Claude Code resolves them itself, so a direct
104/// run keeps them and follows the vendor's newest model (hive-mind#2290).
105pub const ROLLING_CLAUDE_ALIASES: [&str; 3] = ["opus", "sonnet", "haiku"];
106
107fn strip_one_million_suffix(model: &str) -> Option<&str> {
108    let split = model.len().checked_sub(4)?;
109    (model.is_char_boundary(split) && model[split..].eq_ignore_ascii_case("[1m]") && split > 0)
110        .then(|| &model[..split])
111}
112
113fn map_base_model_to_id(model: &str) -> String {
114    lookup_model_alias(&get_model_map(), model)
115        .or_else(|| expand_claude_version_shorthand(model))
116        .unwrap_or_else(|| model.to_string())
117}
118
119/// Expand a version shorthand for a known Claude family (hive-mind#2591).
120///
121/// `opus-6` / `opus-6.1` / `claude-opus-6.1` become `claude-opus-6` /
122/// `claude-opus-6-1`, so a release newer than this build reaches Claude Code
123/// under its canonical ID.
124pub fn expand_claude_version_shorthand(model: &str) -> Option<String> {
125    let lower = model.to_ascii_lowercase();
126    let rest = lower.strip_prefix("claude-").unwrap_or(&lower);
127    let (family, version) = rest.split_once('-')?;
128    let (major, minor) = match version.split_once(['.', '-']) {
129        Some((major, minor)) => (major, Some(minor)),
130        None => (version, None),
131    };
132    let is_number = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
133    if family.is_empty()
134        || !family.bytes().all(|b| b.is_ascii_lowercase())
135        || !is_number(major)
136        || !minor.is_none_or(is_number)
137    {
138        return None;
139    }
140    let known_family = get_model_map().values().any(|id| {
141        id.strip_prefix("claude-")
142            .and_then(|id| id.strip_prefix(family))
143            .and_then(|id| id.strip_prefix('-'))
144            .is_some_and(|id| id.starts_with(|c: char| c.is_ascii_digit()))
145    });
146    known_family.then(|| match minor {
147        Some(minor) => format!("claude-{family}-{major}-{minor}"),
148        None => format!("claude-{family}-{major}"),
149    })
150}
151
152/// Model value for `--model` / `--fallback-model`: rolling aliases stay
153/// (lower-cased, `[1m]` kept), everything else maps to its full ID.
154pub fn model_arg(model: &str) -> String {
155    let (base, suffix) = strip_one_million_suffix(model).map_or((model, ""), |base| (base, "[1m]"));
156    let lower = base.to_ascii_lowercase();
157    if ROLLING_CLAUDE_ALIASES.contains(&lower.as_str()) {
158        format!("{lower}{suffix}")
159    } else {
160        map_model_to_id(model)
161    }
162}
163
164/// Claude command build options
165#[derive(Debug, Clone, Default)]
166pub struct ClaudeBuildOptions {
167    pub prompt: Option<String>,
168    pub prompt_file: Option<String>,
169    pub system_prompt: Option<String>,
170    pub append_system_prompt: Option<String>,
171    pub model: Option<String>,
172    pub fallback_model: Option<String>,
173    pub print: bool,
174    pub verbose: bool,
175    pub json: bool,
176    pub json_input: bool,
177    pub replay_user_messages: bool,
178    pub resume: Option<String>,
179    pub session_id: Option<String>,
180    pub fork_session: bool,
181    pub read_only: bool,
182    /// Approve each command (`--permission-mode default` + stream-json relay)
183    pub approve_each: bool,
184    pub executable: Option<String>,
185    pub extra_env: Vec<(String, String)>,
186    /// Variables removed from the inherited environment (`env -u`)
187    pub unset_env: Vec<String>,
188    pub extra_args: Vec<String>,
189    pub skip_default_safety_flags: bool,
190    pub permission_mode: Option<String>,
191    /// Caller owns the child's stdin and streams the prompt + permission
192    /// responses as NDJSON frames, so no `--prompt` arg is passed.
193    pub stream_input: bool,
194    /// Shared launch options (reasoning effort, MCP servers, extra directories)
195    pub launch: LaunchOptions,
196}
197
198impl ClaudeBuildOptions {
199    /// Create new options
200    pub fn new() -> Self {
201        Self::default()
202    }
203}
204
205/// Build command line arguments for Claude
206///
207/// # Arguments
208/// * `options` - Build options
209///
210/// # Returns
211/// Vector of CLI arguments
212pub fn build_args(options: &ClaudeBuildOptions) -> Vec<String> {
213    let mut args = Vec::new();
214
215    if options.approve_each {
216        // Per-command approval: ask before each tool use via the stream-json
217        // can_use_tool control protocol. `default` keeps Claude's own prompting
218        // active instead of bypassing it; the relay answers each request.
219        args.push("--permission-mode".to_string());
220        args.push("default".to_string());
221    } else if options.read_only {
222        args.push("--permission-mode".to_string());
223        args.push("plan".to_string());
224    } else if let Some(ref permission_mode) = options.permission_mode {
225        args.push("--permission-mode".to_string());
226        args.push(permission_mode.clone());
227    } else if !options.skip_default_safety_flags {
228        // Permission bypass is enabled by default for autonomous execution.
229        args.push("--dangerously-skip-permissions".to_string());
230    }
231
232    // Variadic flags (`--add-dir`, `--mcp-config`) stay before `--model` so the
233    // next option terminates them.
234    let launch = &options.launch;
235    push_directories(&mut args, "--add-dir", &launch.additional_directories);
236    if let Some(ref mcp_config) = launch.mcp_config {
237        args.push("--mcp-config".to_string());
238        args.push(mcp_config.clone());
239    }
240    if launch.strict_mcp_config {
241        args.push("--strict-mcp-config".to_string());
242    }
243    if let Some(ref effort) = launch.reasoning_effort {
244        args.push("--effort".to_string());
245        args.push(normalize_reasoning_effort(effort));
246    }
247    // The answer is reported as `structured_output` on the result message.
248    if launch.json_schema_file.is_some() {
249        // Appended by `build_command` as `"$(cat <file>)"`.
250    } else if let Some(ref json_schema) = launch.json_schema {
251        args.push("--json-schema".to_string());
252        args.push(json_schema_arg(json_schema));
253    }
254
255    if let Some(ref model) = options.model {
256        args.push("--model".to_string());
257        args.push(model_arg(model));
258    }
259
260    if let Some(ref fallback_model) = options.fallback_model {
261        let mapped_fallback = model_arg(fallback_model);
262        args.push("--fallback-model".to_string());
263        args.push(mapped_fallback);
264    }
265
266    // In stream-input mode the prompt is written to stdin as NDJSON frames by
267    // the per-command approval relay, so it is not passed as a --prompt arg.
268    if options.prompt_file.is_none() && !options.stream_input {
269        if let Some(ref prompt) = options.prompt {
270            args.push("-p".to_string());
271            args.push(prompt.clone());
272        }
273    }
274
275    if let Some(ref file) = options.launch.system_prompt_file {
276        args.push("--system-prompt-file".to_string());
277        args.push(file.clone());
278    } else if let Some(ref system_prompt) = options.system_prompt {
279        args.push("--system-prompt".to_string());
280        args.push(system_prompt.clone());
281    }
282
283    if let Some(ref file) = options.launch.append_system_prompt_file {
284        args.push("--append-system-prompt-file".to_string());
285        args.push(file.clone());
286    } else if let Some(ref append_system_prompt) = options.append_system_prompt {
287        args.push("--append-system-prompt".to_string());
288        args.push(append_system_prompt.clone());
289    }
290
291    if options.verbose || options.json {
292        args.push("--verbose".to_string());
293    }
294
295    // Without a prompt argument (stream input frames, prompt file) print mode
296    // still needs `-p`.
297    if (options.prompt.is_none() || options.stream_input)
298        && (options.print || options.json || options.json_input || options.prompt_file.is_some())
299    {
300        args.push("-p".to_string()); // Print mode
301    }
302
303    // JSON output mode - use stream-json format per issue #3
304    if options.json {
305        args.push("--output-format".to_string());
306        args.push("stream-json".to_string());
307    }
308
309    // JSON input mode - use stream-json format per issue #3
310    if options.json_input {
311        args.push("--input-format".to_string());
312        args.push("stream-json".to_string());
313    }
314
315    // Replay user messages (only with stream-json input/output)
316    if options.replay_user_messages {
317        args.push("--replay-user-messages".to_string());
318    }
319
320    // Session management
321    if let Some(ref session_id) = options.session_id {
322        args.push("--session-id".to_string());
323        args.push(session_id.clone());
324    }
325
326    if let Some(ref resume) = options.resume {
327        args.push("--resume".to_string());
328        args.push(resume.clone());
329    }
330
331    if options.fork_session {
332        args.push("--fork-session".to_string());
333    }
334
335    args.extend(options.extra_args.clone());
336
337    args
338}
339
340/// Build complete command string for Claude
341///
342/// # Arguments
343/// * `options` - Build options
344///
345/// # Returns
346/// Complete command string
347pub fn build_command(options: &ClaudeBuildOptions) -> String {
348    let args = build_args(options);
349    let mut args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
350    if let Some(ref file) = options.launch.json_schema_file {
351        args_str.push(file_content_arg("--json-schema", file));
352    }
353    let executable = options.executable.as_deref().unwrap_or("claude");
354    let fixed_env: Vec<_> = options
355        .launch
356        .max_output_tokens
357        .map(|limit| {
358            validate_max_output_tokens(limit).unwrap_or_else(|error| panic!("{error}"));
359            (
360                "CLAUDE_CODE_MAX_OUTPUT_TOKENS".to_string(),
361                limit.to_string(),
362            )
363        })
364        .into_iter()
365        .collect();
366    let command = format!(
367        "{} {}",
368        build_command_head(executable, &[], &fixed_env, &[]),
369        args_str.join(" ")
370    )
371    .trim()
372    .to_string();
373
374    // In stream-input mode the caller owns the child's stdin and writes the
375    // prompt and permission responses as NDJSON frames (per-command approval
376    // relay), so no prompt is piped here.
377    if options.stream_input {
378        command
379    } else if let Some(prompt_file) = &options.prompt_file {
380        format!("cat {} | {}", escape_arg(prompt_file), command)
381    } else {
382        command
383    }
384}
385
386/// Parse JSON messages from Claude output
387/// Claude outputs NDJSON (newline-delimited JSON) in JSON mode
388///
389/// # Arguments
390/// * `output` - Raw output string
391///
392/// # Returns
393/// Vector of parsed JSON messages
394pub fn parse_output(output: &str) -> Vec<Value> {
395    parse_json_records(output)
396}
397
398/// Extract session ID from Claude output
399///
400/// # Arguments
401/// * `output` - Raw output string
402///
403/// # Returns
404/// Session ID or None
405pub fn extract_session_id(output: &str) -> Option<String> {
406    let messages = parse_output(output);
407
408    for msg in messages {
409        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
410            return Some(session_id.to_string());
411        }
412    }
413
414    None
415}
416
417/// Usage statistics
418#[derive(Debug, Clone, Default, serde::Serialize)]
419#[serde(rename_all = "camelCase")]
420pub struct ClaudeUsage {
421    pub input_tokens: u64,
422    pub output_tokens: u64,
423    pub cache_creation_tokens: u64,
424    pub cache_read_tokens: u64,
425}
426
427/// Extract usage statistics from Claude output
428///
429/// # Arguments
430/// * `output` - Raw output string
431///
432/// # Returns
433/// Usage statistics
434pub fn extract_usage(output: &str) -> ClaudeUsage {
435    let messages = parse_output(output);
436    let mut result = ClaudeUsage::default();
437    for record in usage::records("claude", &messages) {
438        result.input_tokens += count(record, usage::INPUT);
439        result.output_tokens += count(record, usage::OUTPUT);
440        result.cache_read_tokens += count(record, usage::CACHE_READ);
441        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
442    }
443    result
444}
445
446/// Claude tool configuration
447#[derive(Debug, Clone)]
448pub struct ClaudeTool {
449    pub name: &'static str,
450    pub display_name: &'static str,
451    pub executable: &'static str,
452    pub supports_json_output: bool,
453    pub supports_json_input: bool,
454    pub supports_system_prompt: bool,
455    pub supports_append_system_prompt: bool,
456    pub supports_resume: bool,
457    pub supports_fork_session: bool,
458    pub supports_session_id: bool,
459    pub supports_fallback_model: bool,
460    pub supports_verbose: bool,
461    pub supports_replay_user_messages: bool,
462    pub supports_read_only: bool,
463    pub supports_ask: bool,
464    pub default_model: &'static str,
465}
466
467impl Default for ClaudeTool {
468    fn default() -> Self {
469        Self {
470            name: "claude",
471            display_name: "Claude Code CLI",
472            executable: "claude",
473            supports_json_output: true,
474            supports_json_input: true, // Claude supports stream-json input format
475            supports_system_prompt: true,
476            supports_append_system_prompt: true, // Supports --append-system-prompt
477            supports_resume: true,
478            supports_fork_session: true,   // Supports --fork-session
479            supports_session_id: true,     // Supports --session-id
480            supports_fallback_model: true, // Supports --fallback-model
481            supports_verbose: true,        // Supports --verbose
482            supports_replay_user_messages: true, // Supports --replay-user-messages
483            supports_read_only: true,      // Supports --permission-mode plan
484            supports_ask: true, // Supports --permission-mode default with stream-json relay
485            default_model: "opus",
486        }
487    }
488}
489
490// Tests are in rust/tests/claude_tests.rs