agent-commander 0.4.0

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
//! Agent CLI tool configuration (@link-assistant/agent).
//!
//! Based on hive-mind's agent.lib.mjs implementation.
//! Agent is a fork of OpenCode that ships a native, enforceable permission
//! system (agent v0.24.0, PR #272) exposed through `--permission-mode`
//! (auto | plan | readonly | ask) and an OpenCode-compatible `--permission`
//! JSON policy.

use crate::error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};
use crate::streaming::parse_json_records;
use crate::tools::shell::{
    build_command_head, escape_arg, escape_single_quotes, lookup_model_alias,
};
use serde_json::Value;
use std::collections::HashMap;

/// Get the Agent model map
/// Maps aliases to full model IDs (uses OpenCode's provider/model format)
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", "formalai/formal-ai");
    map.insert("formalai/formal-ai", "formalai/formal-ai");
    map.insert("grok", "opencode/grok-code");
    map.insert("grok-code", "opencode/grok-code");
    map.insert("grok-code-fast-1", "opencode/grok-code");
    map.insert("big-pickle", "opencode/big-pickle");
    map.insert("gpt-5-nano", "opencode/gpt-5-nano");
    map.insert("minimax-m2.5-free", "opencode/minimax-m2.5-free");
    map.insert("nemotron-3-super-free", "kilo/nemotron-3-super-free");
    map.insert("nemotron-3-ultra-free", "opencode/nemotron-3-ultra-free");
    map.insert(
        "nemotron-3.5-lightning-free",
        "opencode/nemotron-3.5-lightning-free",
    );
    map.insert("ling-3.1-flash-free", "opencode/ling-3.1-flash-free");
    map.insert("mimo-v2.6-flash-free", "opencode/mimo-v2.6-flash-free");
    map.insert("step-5-preview-free", "opencode/step-5-preview-free");
    map.insert("exo-free", "opencode/exo-free");
    map.insert("glm-5-free", "kilo/glm-5-free");
    map.insert("glm-4.5-air-free", "kilo/glm-4.5-air-free");
    map.insert("deepseek-r1-free", "kilo/deepseek-r1-free");
    map.insert("giga-potato-free", "kilo/giga-potato-free");
    map.insert("trinity-large-preview", "kilo/trinity-large-preview");
    map.insert("kilo/glm-5-free", "kilo/glm-5-free");
    map.insert("kilo/glm-4.5-air-free", "kilo/glm-4.5-air-free");
    map.insert("kilo/minimax-m2.5-free", "kilo/minimax-m2.5-free");
    map.insert("kilo/deepseek-r1-free", "kilo/deepseek-r1-free");
    map.insert("kilo/giga-potato-free", "kilo/giga-potato-free");
    map.insert("kilo/trinity-large-preview", "kilo/trinity-large-preview");
    map.insert("kilo/nemotron-3-super-free", "kilo/nemotron-3-super-free");
    map.insert("qwen3.6-plus-free", "opencode/qwen3.6-plus-free");
    map.insert("kimi-k2.5-free", "opencode/kimi-k2.5-free");
    map.insert("glm-4.7-free", "opencode/glm-4.7-free");
    map.insert("minimax-m2.1-free", "opencode/minimax-m2.1-free");
    map.insert("kilo/glm-4.7-free", "kilo/glm-4.7-free");
    map.insert("kilo/kimi-k2.5-free", "kilo/kimi-k2.5-free");
    map.insert("kilo/minimax-m2.1-free", "kilo/minimax-m2.1-free");
    map.insert("opus", "anthropic/claude-opus-5-5");
    map.insert("sonnet", "anthropic/claude-sonnet-5-5");
    map.insert("haiku", "anthropic/claude-haiku-5-5");
    map.insert("fable", "anthropic/claude-fable-5-1");
    map.insert("gemini-pro", "google/gemini-3.1-pro-preview");
    map.insert("gemini-3-pro", "google/gemini-3.1-pro-preview");
    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 {
    lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
}

/// Agent command build options
#[derive(Debug, Clone, Default)]
pub struct AgentBuildOptions {
    pub prompt: Option<String>,
    pub prompt_file: Option<String>,
    pub system_prompt: Option<String>,
    pub model: Option<String>,
    pub resume: Option<String>,
    pub compact_json: bool,
    pub use_existing_claude_oauth: bool,
    /// Enforce hard read-only mode (`--permission-mode readonly`)
    pub read_only: bool,
    /// Enforce planning mode (`--permission-mode plan`)
    pub plan_only: bool,
    /// Approve each mutating command (`--permission-mode ask`)
    pub approve_each: bool,
    /// Explicit agent permission mode (auto | plan | readonly | ask)
    pub permission_mode: Option<String>,
    /// OpenCode-compatible `--permission` JSON policy
    pub permission: Option<String>,
    /// Caller owns the child's stdin and streams the prompt + permission
    /// responses as NDJSON frames, so no prompt is piped in `build_command`.
    pub stream_input: 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>,
}

/// Build command line arguments for Agent
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Vector of CLI arguments
pub fn build_args(options: &AgentBuildOptions) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone(), "--no-fork".into()]);
    }

    // Native, enforceable permission system (agent v0.24.0, PR #272).
    // --plan-only maps to `plan`, --read-only maps to the harder `readonly`,
    // --approve-each maps to `ask` (per-command approval relayed over JSON),
    // matching agent's own distinction between the modes. An explicit
    // permission_mode always wins.
    let resolved_permission_mode = options.permission_mode.clone().or_else(|| {
        if options.approve_each {
            Some("ask".to_string())
        } else if options.plan_only {
            Some("plan".to_string())
        } else if options.read_only {
            Some("readonly".to_string())
        } else {
            None
        }
    });
    let is_ask = resolved_permission_mode.as_deref() == Some("ask");
    if let Some(mode) = resolved_permission_mode {
        args.push("--permission-mode".to_string());
        args.push(mode);
    }

    // Ask mode emits requests mid-turn and blocks until answered, so it requires
    // a streaming input mode (single-shot prompt over stdin would deadlock).
    if is_ask {
        args.push("--input-format".to_string());
        args.push("stream-json".to_string());
    }

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

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

    if options.compact_json {
        args.push("--compact-json".to_string());
    }

    if options.use_existing_claude_oauth {
        args.push("--use-existing-claude-oauth".to_string());
    }

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

    args
}

/// Build complete command string for Agent
/// Agent uses stdin for prompt input (NDJSON streaming supported)
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Complete command string
pub fn build_command(options: &AgentBuildOptions) -> String {
    let args = build_args(options);
    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
    let executable = options.executable.as_deref().unwrap_or("agent");
    let command_head = format!(
        "{} {}",
        build_command_head(executable, &options.unset_env, &options.extra_env, &[]),
        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 {
        return command_head;
    }

    // Agent expects prompt via stdin, combine system and user prompts
    let combined_prompt = match (&options.system_prompt, &options.prompt) {
        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
        (Some(sys), None) => sys.clone(),
        (None, Some(prompt)) => prompt.clone(),
        (None, None) => String::new(),
    };

    // Build command with stdin piping
    let input_command = options.prompt_file.as_ref().map_or_else(
        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
    );
    format!("{} | {}", input_command, command_head)
        .trim()
        .to_string()
}

/// Parse JSON messages from Agent output
/// Agent pretty-prints JSON events by default and emits NDJSON with
/// `--compact-json`; both shapes are parsed by the record scanner.
///
/// # 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 Agent 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")
            .or_else(|| msg.get("sessionID"))
            .and_then(|v| v.as_str())
        {
            return Some(session_id.to_string());
        }
    }

    None
}

/// Usage statistics for Agent
#[derive(Debug, Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub reasoning_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub total_cost: f64,
    pub step_count: u64,
}

/// Parse token usage from Agent output
/// Agent outputs step_finish events with token data
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Token usage statistics
pub fn extract_usage(output: &str) -> AgentUsage {
    let messages = parse_output(output);
    let mut usage = AgentUsage::default();

    for msg in messages {
        // Look for step_finish events which contain token usage
        if msg.get("type").and_then(|t| t.as_str()) == Some("step_finish") {
            if let Some(part) = msg.get("part") {
                usage.step_count += 1;

                if let Some(tokens) = part.get("tokens") {
                    if let Some(input) = tokens.get("input").and_then(|v| v.as_u64()) {
                        usage.input_tokens += input;
                    }
                    if let Some(output) = tokens.get("output").and_then(|v| v.as_u64()) {
                        usage.output_tokens += output;
                    }
                    if let Some(reasoning) = tokens.get("reasoning").and_then(|v| v.as_u64()) {
                        usage.reasoning_tokens += reasoning;
                    }

                    // Handle cache tokens
                    if let Some(cache) = tokens.get("cache") {
                        if let Some(read) = cache.get("read").and_then(|v| v.as_u64()) {
                            usage.cache_read_tokens += read;
                        }
                        if let Some(write) = cache.get("write").and_then(|v| v.as_u64()) {
                            usage.cache_write_tokens += write;
                        }
                    }
                }

                // Add cost from step_finish
                if let Some(cost) = part.get("cost").and_then(|v| v.as_f64()) {
                    usage.total_cost += cost;
                }
            }
        }
    }

    usage
}

/// Error detection result
#[derive(Debug, Clone, Default)]
pub struct ErrorResult {
    pub has_error: bool,
    pub error_type: Option<String>,
    pub message: Option<String>,
}

const FATAL_AGENT_LOG_PATTERNS: [&str; 4] = [
    "providermodelnotfounderror",
    "provideriniterror",
    "nosuchmodelerror",
    "modelnotfounderror",
];

fn is_fatal_log_text(text: &str) -> bool {
    let lower = text.to_lowercase();
    FATAL_AGENT_LOG_PATTERNS
        .iter()
        .any(|pattern| lower.contains(pattern))
        || lower
            .find("failed to initialize ")
            .is_some_and(|index| lower[index..].contains("model"))
}

/// Detect a `log` record reporting a fatal startup failure
///
/// Agent prints it, then `session.idle`, and exits 0 without an `error`
/// record (hive-mind#2141). Returns the readable failure text.
pub fn detect_fatal_agent_log_record(record: &Value) -> Option<String> {
    if record["type"] != "log" || record["level"] != "error" {
        return None;
    }
    let error = stringify_error_value(&record["error"], MAX_ERROR_TEXT_LENGTH, "");
    let message = stringify_error_value(&record["message"], MAX_ERROR_TEXT_LENGTH, "");
    if !is_fatal_log_text(&format!("{error} {message}")) {
        return None;
    }
    let hint = stringify_error_value(&record["hint"], MAX_ERROR_TEXT_LENGTH, "");
    let hint = if hint.is_empty() {
        hint
    } else {
        format!("hint: {hint}")
    };
    Some(
        [error, message, hint]
            .into_iter()
            .filter(|part| !part.is_empty())
            .collect::<Vec<_>>()
            .join(" — "),
    )
}

/// Whether an error record is a failed tool call the model recovers from
///
/// A failed tool call is returned to the model as the tool result; agent
/// 0.26.13 and earlier also repeated it as a top-level error record (agent#332,
/// hive-mind#3213). Only the session's own errors decide the run.
pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
    crate::usage_limit::is_recoverable_tool_error(record)
}

/// Detect errors in Agent output
///
/// The last fatal error record is the one the session ended on; failed tool
/// calls are skipped.
pub fn detect_errors(output: &str) -> ErrorResult {
    let mut detection = ErrorResult::default();

    for msg in parse_output(output) {
        if let Some(fatal_log) = detect_fatal_agent_log_record(&msg) {
            let error_type =
                stringify_error_value(&msg["error"], MAX_ERROR_TEXT_LENGTH, "fatal_log");
            detection = ErrorResult {
                has_error: true,
                error_type: Some(error_type),
                message: Some(fatal_log),
            };
        } else if matches!(msg["type"].as_str(), Some("error" | "step_error"))
            && !is_recoverable_agent_tool_error(&msg)
        {
            let error_type = msg
                .pointer("/error/name")
                .and_then(Value::as_str)
                .filter(|name| !name.is_empty())
                .or_else(|| msg["type"].as_str())
                .map(ToString::to_string);
            detection = ErrorResult {
                has_error: true,
                error_type,
                message: Some(first_error_text(
                    &[&msg["message"], &msg["error"], &msg["data"]],
                    "Agent emitted an error event without any details",
                )),
            };
        }
    }

    detection
}

/// Agent tool configuration
#[derive(Debug, Clone)]
pub struct AgentTool {
    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_resume: bool,
    pub supports_read_only: bool,
    pub supports_ask: bool,
    pub default_model: &'static str,
}

impl Default for AgentTool {
    fn default() -> Self {
        Self {
            name: "agent",
            display_name: "@link-assistant/agent",
            executable: "agent",
            supports_json_output: true,
            supports_json_input: true, // Agent supports full JSON streaming input
            supports_system_prompt: false, // System prompt is combined with user prompt
            supports_resume: true,     // --resume SESSION --no-fork
            supports_read_only: true, // Native --permission-mode readonly/plan (agent v0.24.0, PR #272)
            supports_ask: true,       // Native --permission-mode ask with JSON permission relay
            default_model: "nemotron-3-super-free",
        }
    }
}

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