agent-commander 0.5.1

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Claude CLI tool configuration
//! Based on hive-mind's claude.lib.mjs implementation

use super::usage::{self, count};
use crate::streaming::parse_json_records;
use crate::tools::launch_options::{
    json_schema_arg, normalize_reasoning_effort, push_directories, LaunchOptions,
};
use crate::tools::shell::{build_command_head, escape_arg, file_content_arg, lookup_model_alias};
use serde_json::Value;
use std::collections::HashMap;

/// Get the Claude model map
pub fn get_model_map() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
    map.insert("formal-ai", "formal-ai");
    map.insert("formalai/formal-ai", "formal-ai");
    map.insert("sonnet", "claude-sonnet-5-5");
    map.insert("opus", "claude-opus-5-5");
    map.insert("haiku", "claude-haiku-5-5");
    map.insert("haiku-3-5", "claude-3-5-haiku-20241022");
    map.insert("haiku-3", "claude-3-haiku-20240307");
    map.insert("opusplan", "opusplan");
    map.insert("fable", "claude-fable-5-1");
    map.insert("fable-5-1", "claude-fable-5-1");
    map.insert("claude-fable-5-1", "claude-fable-5-1");
    map.insert("fable-5", "claude-fable-5");
    map.insert("claude-fable-5", "claude-fable-5");
    map.insert("mythos-5-1", "claude-mythos-5-1");
    map.insert("claude-mythos-5-1", "claude-mythos-5-1");
    map.insert("mythos-5", "claude-mythos-5");
    map.insert("claude-mythos-5", "claude-mythos-5");
    map.insert("sonnet-5-5", "claude-sonnet-5-5");
    map.insert("sonnet-5", "claude-sonnet-5");
    map.insert("sonnet-4-6", "claude-sonnet-4-6");
    map.insert("opus-5-5", "claude-opus-5-5");
    map.insert("opus-5", "claude-opus-5");
    map.insert("opus-4-8", "claude-opus-4-8");
    map.insert("opus-4-7", "claude-opus-4-7");
    map.insert("opus-4-6", "claude-opus-4-6");
    map.insert("opus-4-5", "claude-opus-4-5-20251101");
    map.insert("sonnet-4-5", "claude-sonnet-4-5-20250929");
    map.insert("haiku-5-5", "claude-haiku-5-5");
    map.insert("haiku-4-5", "claude-haiku-4-5-20251001");
    map.insert("claude-opus-5-5", "claude-opus-5-5");
    map.insert("claude-opus-5", "claude-opus-5");
    map.insert("claude-opus-4-8", "claude-opus-4-8");
    map.insert("claude-opus-4-7", "claude-opus-4-7");
    map.insert("claude-sonnet-5-5", "claude-sonnet-5-5");
    map.insert("claude-sonnet-5", "claude-sonnet-5");
    map.insert("claude-sonnet-4-6", "claude-sonnet-4-6");
    map.insert("claude-opus-4-6", "claude-opus-4-6");
    map.insert("claude-opus-4-5", "claude-opus-4-5-20251101");
    map.insert("claude-sonnet-4-5", "claude-sonnet-4-5-20250929");
    map.insert("claude-haiku-5-5", "claude-haiku-5-5");
    map.insert("claude-haiku-4-5", "claude-haiku-4-5-20251001");
    map.insert("best", "claude-fable-5-1");
    map.insert("sonnet-5.5", "claude-sonnet-5-5");
    map.insert("claude-sonnet-5.5", "claude-sonnet-5-5");
    map.insert("opus-5.5", "claude-opus-5-5");
    map.insert("claude-opus-5.5", "claude-opus-5-5");
    map.insert("haiku-5.5", "claude-haiku-5-5");
    map.insert("claude-haiku-5.5", "claude-haiku-5-5");
    map.insert("fable-5.1", "claude-fable-5-1");
    map.insert("claude-fable-5.1", "claude-fable-5-1");
    map.insert("mythos-5.1", "claude-mythos-5-1");
    map.insert("claude-mythos-5.1", "claude-mythos-5-1");
    map.insert("sonnet-4.6", "claude-sonnet-4-6");
    map.insert("claude-sonnet-4.6", "claude-sonnet-4-6");
    map.insert("opus-4.8", "claude-opus-4-8");
    map.insert("claude-opus-4.8", "claude-opus-4-8");
    map.insert("opus-4.7", "claude-opus-4-7");
    map.insert("claude-opus-4.7", "claude-opus-4-7");
    map.insert("opus-4.6", "claude-opus-4-6");
    map.insert("claude-opus-4.6", "claude-opus-4-6");
    map.insert("mythos", "claude-mythos-5-1");
    map.insert("haiku-3.5", "claude-3-5-haiku-20241022");
    map.insert("opus-4.5", "claude-opus-4-5-20251101");
    map.insert("sonnet-4.5", "claude-sonnet-4-5-20250929");
    map.insert("haiku-4.5", "claude-haiku-4-5-20251001");
    map.insert("claude-opus-4.5", "claude-opus-4-5-20251101");
    map.insert("claude-sonnet-4.5", "claude-sonnet-4-5-20250929");
    map.insert("claude-haiku-4.5", "claude-haiku-4-5-20251001");
    map
}

/// Map model alias to full model ID
///
/// # Arguments
/// * `model` - Model alias or full ID
///
/// # Returns
/// Full model ID
pub fn map_model_to_id(model: &str) -> String {
    if let Some(base) = strip_one_million_suffix(model) {
        return format!("{}[1m]", map_base_model_to_id(base));
    }
    map_base_model_to_id(model)
}

/// Rolling Claude Code aliases. Claude Code resolves them itself, so a direct
/// run keeps them and follows the vendor's newest model (hive-mind#2290).
pub const ROLLING_CLAUDE_ALIASES: [&str; 3] = ["opus", "sonnet", "haiku"];

fn strip_one_million_suffix(model: &str) -> Option<&str> {
    let split = model.len().checked_sub(4)?;
    (model.is_char_boundary(split) && model[split..].eq_ignore_ascii_case("[1m]") && split > 0)
        .then(|| &model[..split])
}

fn map_base_model_to_id(model: &str) -> String {
    lookup_model_alias(&get_model_map(), model)
        .or_else(|| expand_claude_version_shorthand(model))
        .unwrap_or_else(|| model.to_string())
}

/// Expand a version shorthand for a known Claude family (hive-mind#2591).
///
/// `opus-6` / `opus-6.1` / `claude-opus-6.1` become `claude-opus-6` /
/// `claude-opus-6-1`, so a release newer than this build reaches Claude Code
/// under its canonical ID.
pub fn expand_claude_version_shorthand(model: &str) -> Option<String> {
    let lower = model.to_ascii_lowercase();
    let rest = lower.strip_prefix("claude-").unwrap_or(&lower);
    let (family, version) = rest.split_once('-')?;
    let (major, minor) = match version.split_once(['.', '-']) {
        Some((major, minor)) => (major, Some(minor)),
        None => (version, None),
    };
    let is_number = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
    if family.is_empty()
        || !family.bytes().all(|b| b.is_ascii_lowercase())
        || !is_number(major)
        || !minor.is_none_or(is_number)
    {
        return None;
    }
    let known_family = get_model_map().values().any(|id| {
        id.strip_prefix("claude-")
            .and_then(|id| id.strip_prefix(family))
            .and_then(|id| id.strip_prefix('-'))
            .is_some_and(|id| id.starts_with(|c: char| c.is_ascii_digit()))
    });
    known_family.then(|| match minor {
        Some(minor) => format!("claude-{family}-{major}-{minor}"),
        None => format!("claude-{family}-{major}"),
    })
}

/// Model value for `--model` / `--fallback-model`: rolling aliases stay
/// (lower-cased, `[1m]` kept), everything else maps to its full ID.
pub fn model_arg(model: &str) -> String {
    let (base, suffix) = strip_one_million_suffix(model).map_or((model, ""), |base| (base, "[1m]"));
    let lower = base.to_ascii_lowercase();
    if ROLLING_CLAUDE_ALIASES.contains(&lower.as_str()) {
        format!("{lower}{suffix}")
    } else {
        map_model_to_id(model)
    }
}

/// Claude command build options
#[derive(Debug, Clone, Default)]
pub struct ClaudeBuildOptions {
    pub prompt: Option<String>,
    pub prompt_file: Option<String>,
    pub system_prompt: Option<String>,
    pub append_system_prompt: Option<String>,
    pub model: Option<String>,
    pub fallback_model: Option<String>,
    pub print: bool,
    pub verbose: bool,
    pub json: bool,
    pub json_input: bool,
    pub replay_user_messages: bool,
    pub resume: Option<String>,
    pub session_id: Option<String>,
    pub fork_session: bool,
    pub read_only: bool,
    /// Approve each command (`--permission-mode default` + stream-json relay)
    pub approve_each: bool,
    pub executable: Option<String>,
    pub extra_env: Vec<(String, String)>,
    /// Variables removed from the inherited environment (`env -u`)
    pub unset_env: Vec<String>,
    pub extra_args: Vec<String>,
    pub skip_default_safety_flags: bool,
    pub permission_mode: Option<String>,
    /// Caller owns the child's stdin and streams the prompt + permission
    /// responses as NDJSON frames, so no `--prompt` arg is passed.
    pub stream_input: bool,
    /// Shared launch options (reasoning effort, MCP servers, extra directories)
    pub launch: LaunchOptions,
}

impl ClaudeBuildOptions {
    /// Create new options
    pub fn new() -> Self {
        Self::default()
    }
}

/// Build command line arguments for Claude
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Vector of CLI arguments
pub fn build_args(options: &ClaudeBuildOptions) -> Vec<String> {
    let mut args = Vec::new();

    if options.approve_each {
        // Per-command approval: ask before each tool use via the stream-json
        // can_use_tool control protocol. `default` keeps Claude's own prompting
        // active instead of bypassing it; the relay answers each request.
        args.push("--permission-mode".to_string());
        args.push("default".to_string());
    } else if options.read_only {
        args.push("--permission-mode".to_string());
        args.push("plan".to_string());
    } else if let Some(ref permission_mode) = options.permission_mode {
        args.push("--permission-mode".to_string());
        args.push(permission_mode.clone());
    } else if !options.skip_default_safety_flags {
        // Permission bypass is enabled by default for autonomous execution.
        args.push("--dangerously-skip-permissions".to_string());
    }

    // Variadic flags (`--add-dir`, `--mcp-config`) stay before `--model` so the
    // next option terminates them.
    let launch = &options.launch;
    push_directories(&mut args, "--add-dir", &launch.additional_directories);
    if let Some(ref mcp_config) = launch.mcp_config {
        args.push("--mcp-config".to_string());
        args.push(mcp_config.clone());
    }
    if launch.strict_mcp_config {
        args.push("--strict-mcp-config".to_string());
    }
    if let Some(ref effort) = launch.reasoning_effort {
        args.push("--effort".to_string());
        args.push(normalize_reasoning_effort(effort));
    }
    // The answer is reported as `structured_output` on the result message.
    if launch.json_schema_file.is_some() {
        // Appended by `build_command` as `"$(cat <file>)"`.
    } else if let Some(ref json_schema) = launch.json_schema {
        args.push("--json-schema".to_string());
        args.push(json_schema_arg(json_schema));
    }

    if let Some(ref model) = options.model {
        args.push("--model".to_string());
        args.push(model_arg(model));
    }

    if let Some(ref fallback_model) = options.fallback_model {
        let mapped_fallback = model_arg(fallback_model);
        args.push("--fallback-model".to_string());
        args.push(mapped_fallback);
    }

    // In stream-input mode the prompt is written to stdin as NDJSON frames by
    // the per-command approval relay, so it is not passed as a --prompt arg.
    if options.prompt_file.is_none() && !options.stream_input {
        if let Some(ref prompt) = options.prompt {
            args.push("-p".to_string());
            args.push(prompt.clone());
        }
    }

    if let Some(ref file) = options.launch.system_prompt_file {
        args.push("--system-prompt-file".to_string());
        args.push(file.clone());
    } else if let Some(ref system_prompt) = options.system_prompt {
        args.push("--system-prompt".to_string());
        args.push(system_prompt.clone());
    }

    if let Some(ref file) = options.launch.append_system_prompt_file {
        args.push("--append-system-prompt-file".to_string());
        args.push(file.clone());
    } else if let Some(ref append_system_prompt) = options.append_system_prompt {
        args.push("--append-system-prompt".to_string());
        args.push(append_system_prompt.clone());
    }

    if options.verbose || options.json {
        args.push("--verbose".to_string());
    }

    // Without a prompt argument (stream input frames, prompt file) print mode
    // still needs `-p`.
    if (options.prompt.is_none() || options.stream_input)
        && (options.print || options.json || options.json_input || options.prompt_file.is_some())
    {
        args.push("-p".to_string()); // Print mode
    }

    // JSON output mode - use stream-json format per issue #3
    if options.json {
        args.push("--output-format".to_string());
        args.push("stream-json".to_string());
    }

    // JSON input mode - use stream-json format per issue #3
    if options.json_input {
        args.push("--input-format".to_string());
        args.push("stream-json".to_string());
    }

    // Replay user messages (only with stream-json input/output)
    if options.replay_user_messages {
        args.push("--replay-user-messages".to_string());
    }

    // Session management
    if let Some(ref session_id) = options.session_id {
        args.push("--session-id".to_string());
        args.push(session_id.clone());
    }

    if let Some(ref resume) = options.resume {
        args.push("--resume".to_string());
        args.push(resume.clone());
    }

    if options.fork_session {
        args.push("--fork-session".to_string());
    }

    args.extend(options.extra_args.clone());

    args
}

/// Build complete command string for Claude
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Complete command string
pub fn build_command(options: &ClaudeBuildOptions) -> String {
    let args = build_args(options);
    let mut args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
    if let Some(ref file) = options.launch.json_schema_file {
        args_str.push(file_content_arg("--json-schema", file));
    }
    let executable = options.executable.as_deref().unwrap_or("claude");
    let command = format!(
        "{} {}",
        build_command_head(executable, &[], &[], &[]),
        args_str.join(" ")
    )
    .trim()
    .to_string();

    // In stream-input mode the caller owns the child's stdin and writes the
    // prompt and permission responses as NDJSON frames (per-command approval
    // relay), so no prompt is piped here.
    if options.stream_input {
        command
    } else if let Some(prompt_file) = &options.prompt_file {
        format!("cat {} | {}", escape_arg(prompt_file), command)
    } else {
        command
    }
}

/// Parse JSON messages from Claude output
/// Claude outputs NDJSON (newline-delimited JSON) in JSON mode
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Vector of parsed JSON messages
pub fn parse_output(output: &str) -> Vec<Value> {
    parse_json_records(output)
}

/// Extract session ID from Claude output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Session ID or None
pub fn extract_session_id(output: &str) -> Option<String> {
    let messages = parse_output(output);

    for msg in messages {
        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
            return Some(session_id.to_string());
        }
    }

    None
}

/// Usage statistics
#[derive(Debug, Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClaudeUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_creation_tokens: u64,
    pub cache_read_tokens: u64,
}

/// Extract usage statistics from Claude output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Usage statistics
pub fn extract_usage(output: &str) -> ClaudeUsage {
    let messages = parse_output(output);
    let mut result = ClaudeUsage::default();
    for record in usage::records("claude", &messages) {
        result.input_tokens += count(record, usage::INPUT);
        result.output_tokens += count(record, usage::OUTPUT);
        result.cache_read_tokens += count(record, usage::CACHE_READ);
        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
    }
    result
}

/// Claude tool configuration
#[derive(Debug, Clone)]
pub struct ClaudeTool {
    pub name: &'static str,
    pub display_name: &'static str,
    pub executable: &'static str,
    pub supports_json_output: bool,
    pub supports_json_input: bool,
    pub supports_system_prompt: bool,
    pub supports_append_system_prompt: bool,
    pub supports_resume: bool,
    pub supports_fork_session: bool,
    pub supports_session_id: bool,
    pub supports_fallback_model: bool,
    pub supports_verbose: bool,
    pub supports_replay_user_messages: bool,
    pub supports_read_only: bool,
    pub supports_ask: bool,
    pub default_model: &'static str,
}

impl Default for ClaudeTool {
    fn default() -> Self {
        Self {
            name: "claude",
            display_name: "Claude Code CLI",
            executable: "claude",
            supports_json_output: true,
            supports_json_input: true, // Claude supports stream-json input format
            supports_system_prompt: true,
            supports_append_system_prompt: true, // Supports --append-system-prompt
            supports_resume: true,
            supports_fork_session: true,   // Supports --fork-session
            supports_session_id: true,     // Supports --session-id
            supports_fallback_model: true, // Supports --fallback-model
            supports_verbose: true,        // Supports --verbose
            supports_replay_user_messages: true, // Supports --replay-user-messages
            supports_read_only: true,      // Supports --permission-mode plan
            supports_ask: true, // Supports --permission-mode default with stream-json relay
            default_model: "opus",
        }
    }
}

// Tests are in rust/tests/claude_tests.rs