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