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_ndjson;
6use crate::tools::shell::{build_command_head, escape_arg};
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");
17    map.insert("opus", "claude-opus-5");
18    map.insert("haiku", "claude-haiku-4-5-20251001");
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", "claude-sonnet-5");
32    map.insert("sonnet-4-6", "claude-sonnet-4-6");
33    map.insert("opus-5-5", "claude-opus-5-5");
34    map.insert("opus-5", "claude-opus-5");
35    map.insert("opus-4-8", "claude-opus-4-8");
36    map.insert("opus-4-7", "claude-opus-4-7");
37    map.insert("opus-4-6", "claude-opus-4-6");
38    map.insert("opus-4-5", "claude-opus-4-5-20251101");
39    map.insert("sonnet-4-5", "claude-sonnet-4-5-20250929");
40    map.insert("haiku-4-5", "claude-haiku-4-5-20251001");
41    map.insert("claude-opus-5-5", "claude-opus-5-5");
42    map.insert("claude-opus-5", "claude-opus-5");
43    map.insert("claude-opus-4-8", "claude-opus-4-8");
44    map.insert("claude-opus-4-7", "claude-opus-4-7");
45    map.insert("claude-sonnet-5", "claude-sonnet-5");
46    map.insert("claude-sonnet-4-6", "claude-sonnet-4-6");
47    map.insert("claude-opus-4-6", "claude-opus-4-6");
48    map.insert("claude-opus-4-5", "claude-opus-4-5-20251101");
49    map.insert("claude-sonnet-4-5", "claude-sonnet-4-5-20250929");
50    map.insert("claude-haiku-4-5", "claude-haiku-4-5-20251001");
51    map
52}
53
54/// Map model alias to full model ID
55///
56/// # Arguments
57/// * `model` - Model alias or full ID
58///
59/// # Returns
60/// Full model ID
61pub fn map_model_to_id(model: &str) -> String {
62    let model_map = get_model_map();
63    model_map
64        .get(model)
65        .map(|s| s.to_string())
66        .unwrap_or_else(|| model.to_string())
67}
68
69/// Claude command build options
70#[derive(Debug, Clone, Default)]
71pub struct ClaudeBuildOptions {
72    pub prompt: Option<String>,
73    pub prompt_file: Option<String>,
74    pub system_prompt: Option<String>,
75    pub append_system_prompt: Option<String>,
76    pub model: Option<String>,
77    pub fallback_model: Option<String>,
78    pub print: bool,
79    pub verbose: bool,
80    pub json: bool,
81    pub json_input: bool,
82    pub replay_user_messages: bool,
83    pub resume: Option<String>,
84    pub session_id: Option<String>,
85    pub fork_session: bool,
86    pub read_only: bool,
87    /// Approve each command (`--permission-mode default` + stream-json relay)
88    pub approve_each: bool,
89    pub executable: Option<String>,
90    pub extra_env: Vec<(String, String)>,
91    pub extra_args: Vec<String>,
92    pub skip_default_safety_flags: bool,
93    pub permission_mode: Option<String>,
94    /// Caller owns the child's stdin and streams the prompt + permission
95    /// responses as NDJSON frames, so no `--prompt` arg is passed.
96    pub stream_input: bool,
97}
98
99impl ClaudeBuildOptions {
100    /// Create new options
101    pub fn new() -> Self {
102        Self::default()
103    }
104}
105
106/// Build command line arguments for Claude
107///
108/// # Arguments
109/// * `options` - Build options
110///
111/// # Returns
112/// Vector of CLI arguments
113pub fn build_args(options: &ClaudeBuildOptions) -> Vec<String> {
114    let mut args = Vec::new();
115
116    if options.approve_each {
117        // Per-command approval: ask before each tool use via the stream-json
118        // can_use_tool control protocol. `default` keeps Claude's own prompting
119        // active instead of bypassing it; the relay answers each request.
120        args.push("--permission-mode".to_string());
121        args.push("default".to_string());
122    } else if options.read_only {
123        args.push("--permission-mode".to_string());
124        args.push("plan".to_string());
125    } else if let Some(ref permission_mode) = options.permission_mode {
126        args.push("--permission-mode".to_string());
127        args.push(permission_mode.clone());
128    } else if !options.skip_default_safety_flags {
129        // Permission bypass is enabled by default for autonomous execution.
130        args.push("--dangerously-skip-permissions".to_string());
131    }
132
133    if let Some(ref model) = options.model {
134        let mapped_model = if model == "opus" {
135            model.clone()
136        } else {
137            map_model_to_id(model)
138        };
139        args.push("--model".to_string());
140        args.push(mapped_model);
141    }
142
143    if let Some(ref fallback_model) = options.fallback_model {
144        let mapped_fallback = map_model_to_id(fallback_model);
145        args.push("--fallback-model".to_string());
146        args.push(mapped_fallback);
147    }
148
149    // In stream-input mode the prompt is written to stdin as NDJSON frames by
150    // the per-command approval relay, so it is not passed as a --prompt arg.
151    if options.prompt_file.is_none() && !options.stream_input {
152        if let Some(ref prompt) = options.prompt {
153            args.push("-p".to_string());
154            args.push(prompt.clone());
155        }
156    }
157
158    if let Some(ref system_prompt) = options.system_prompt {
159        args.push("--system-prompt".to_string());
160        args.push(system_prompt.clone());
161    }
162
163    if let Some(ref append_system_prompt) = options.append_system_prompt {
164        args.push("--append-system-prompt".to_string());
165        args.push(append_system_prompt.clone());
166    }
167
168    if options.verbose || options.json {
169        args.push("--verbose".to_string());
170    }
171
172    if options.prompt.is_none()
173        && (options.print || options.json || options.json_input || options.prompt_file.is_some())
174    {
175        args.push("-p".to_string()); // Print mode
176    }
177
178    // JSON output mode - use stream-json format per issue #3
179    if options.json {
180        args.push("--output-format".to_string());
181        args.push("stream-json".to_string());
182    }
183
184    // JSON input mode - use stream-json format per issue #3
185    if options.json_input {
186        args.push("--input-format".to_string());
187        args.push("stream-json".to_string());
188    }
189
190    // Replay user messages (only with stream-json input/output)
191    if options.replay_user_messages {
192        args.push("--replay-user-messages".to_string());
193    }
194
195    // Session management
196    if let Some(ref session_id) = options.session_id {
197        args.push("--session-id".to_string());
198        args.push(session_id.clone());
199    }
200
201    if let Some(ref resume) = options.resume {
202        args.push("--resume".to_string());
203        args.push(resume.clone());
204    }
205
206    if options.fork_session {
207        args.push("--fork-session".to_string());
208    }
209
210    args.extend(options.extra_args.clone());
211
212    args
213}
214
215/// Build complete command string for Claude
216///
217/// # Arguments
218/// * `options` - Build options
219///
220/// # Returns
221/// Complete command string
222pub fn build_command(options: &ClaudeBuildOptions) -> String {
223    let args = build_args(options);
224    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
225    let executable = options.executable.as_deref().unwrap_or("claude");
226    let command = format!(
227        "{} {}",
228        build_command_head(executable, &options.extra_env, &[]),
229        args_str.join(" ")
230    )
231    .trim()
232    .to_string();
233
234    // In stream-input mode the caller owns the child's stdin and writes the
235    // prompt and permission responses as NDJSON frames (per-command approval
236    // relay), so no prompt is piped here.
237    if options.stream_input {
238        command
239    } else if let Some(prompt_file) = &options.prompt_file {
240        format!("cat {} | {}", escape_arg(prompt_file), command)
241    } else {
242        command
243    }
244}
245
246/// Parse JSON messages from Claude output
247/// Claude outputs NDJSON (newline-delimited JSON) in JSON mode
248///
249/// # Arguments
250/// * `output` - Raw output string
251///
252/// # Returns
253/// Vector of parsed JSON messages
254pub fn parse_output(output: &str) -> Vec<Value> {
255    parse_ndjson(output)
256}
257
258/// Extract session ID from Claude output
259///
260/// # Arguments
261/// * `output` - Raw output string
262///
263/// # Returns
264/// Session ID or None
265pub fn extract_session_id(output: &str) -> Option<String> {
266    let messages = parse_output(output);
267
268    for msg in messages {
269        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
270            return Some(session_id.to_string());
271        }
272    }
273
274    None
275}
276
277/// Usage statistics
278#[derive(Debug, Clone, Default, serde::Serialize)]
279#[serde(rename_all = "camelCase")]
280pub struct ClaudeUsage {
281    pub input_tokens: u64,
282    pub output_tokens: u64,
283    pub cache_creation_tokens: u64,
284    pub cache_read_tokens: u64,
285}
286
287/// Extract usage statistics from Claude output
288///
289/// # Arguments
290/// * `output` - Raw output string
291///
292/// # Returns
293/// Usage statistics
294pub fn extract_usage(output: &str) -> ClaudeUsage {
295    let messages = parse_output(output);
296    let mut result = ClaudeUsage::default();
297    for record in usage::records("claude", &messages) {
298        result.input_tokens += count(record, usage::INPUT);
299        result.output_tokens += count(record, usage::OUTPUT);
300        result.cache_read_tokens += count(record, usage::CACHE_READ);
301        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
302    }
303    result
304}
305
306/// Claude tool configuration
307#[derive(Debug, Clone)]
308pub struct ClaudeTool {
309    pub name: &'static str,
310    pub display_name: &'static str,
311    pub executable: &'static str,
312    pub supports_json_output: bool,
313    pub supports_json_input: bool,
314    pub supports_system_prompt: bool,
315    pub supports_append_system_prompt: bool,
316    pub supports_resume: bool,
317    pub supports_fork_session: bool,
318    pub supports_session_id: bool,
319    pub supports_fallback_model: bool,
320    pub supports_verbose: bool,
321    pub supports_replay_user_messages: bool,
322    pub supports_read_only: bool,
323    pub supports_ask: bool,
324    pub default_model: &'static str,
325}
326
327impl Default for ClaudeTool {
328    fn default() -> Self {
329        Self {
330            name: "claude",
331            display_name: "Claude Code CLI",
332            executable: "claude",
333            supports_json_output: true,
334            supports_json_input: true, // Claude supports stream-json input format
335            supports_system_prompt: true,
336            supports_append_system_prompt: true, // Supports --append-system-prompt
337            supports_resume: true,
338            supports_fork_session: true,   // Supports --fork-session
339            supports_session_id: true,     // Supports --session-id
340            supports_fallback_model: true, // Supports --fallback-model
341            supports_verbose: true,        // Supports --verbose
342            supports_replay_user_messages: true, // Supports --replay-user-messages
343            supports_read_only: true,      // Supports --permission-mode plan
344            supports_ask: true, // Supports --permission-mode default with stream-json relay
345            default_model: "opus",
346        }
347    }
348}
349
350// Tests are in rust/tests/claude_tests.rs