Skip to main content

agent_commander/tools/
agent.rs

1//! Agent CLI tool configuration (@link-assistant/agent).
2//!
3//! Based on hive-mind's agent.lib.mjs implementation.
4//! Agent is a fork of OpenCode that ships a native, enforceable permission
5//! system (agent v0.24.0, PR #272) exposed through `--permission-mode`
6//! (auto | plan | readonly | ask) and an OpenCode-compatible `--permission`
7//! JSON policy.
8
9use crate::error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};
10use crate::streaming::parse_json_records;
11use crate::tools::shell::{
12    build_command_head, escape_arg, escape_single_quotes, lookup_model_alias,
13};
14use serde_json::Value;
15use std::collections::HashMap;
16
17/// Get the Agent model map
18/// Maps aliases to full model IDs (uses OpenCode's provider/model format)
19pub fn get_model_map() -> HashMap<&'static str, &'static str> {
20    let mut map = HashMap::new();
21    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
22    map.insert("formal-ai", "formalai/formal-ai");
23    map.insert("formalai/formal-ai", "formalai/formal-ai");
24    map.insert("grok", "opencode/grok-code");
25    map.insert("grok-code", "opencode/grok-code");
26    map.insert("grok-code-fast-1", "opencode/grok-code");
27    map.insert("big-pickle", "opencode/big-pickle");
28    map.insert("gpt-5-nano", "opencode/gpt-5-nano");
29    map.insert("minimax-m2.5-free", "opencode/minimax-m2.5-free");
30    map.insert("nemotron-3-super-free", "kilo/nemotron-3-super-free");
31    map.insert("nemotron-3-ultra-free", "opencode/nemotron-3-ultra-free");
32    map.insert(
33        "nemotron-3.5-lightning-free",
34        "opencode/nemotron-3.5-lightning-free",
35    );
36    map.insert("ling-3.1-flash-free", "opencode/ling-3.1-flash-free");
37    map.insert("mimo-v2.6-flash-free", "opencode/mimo-v2.6-flash-free");
38    map.insert("step-5-preview-free", "opencode/step-5-preview-free");
39    map.insert("exo-free", "opencode/exo-free");
40    map.insert("glm-5-free", "kilo/glm-5-free");
41    map.insert("glm-4.5-air-free", "kilo/glm-4.5-air-free");
42    map.insert("deepseek-r1-free", "kilo/deepseek-r1-free");
43    map.insert("giga-potato-free", "kilo/giga-potato-free");
44    map.insert("trinity-large-preview", "kilo/trinity-large-preview");
45    map.insert("kilo/glm-5-free", "kilo/glm-5-free");
46    map.insert("kilo/glm-4.5-air-free", "kilo/glm-4.5-air-free");
47    map.insert("kilo/minimax-m2.5-free", "kilo/minimax-m2.5-free");
48    map.insert("kilo/deepseek-r1-free", "kilo/deepseek-r1-free");
49    map.insert("kilo/giga-potato-free", "kilo/giga-potato-free");
50    map.insert("kilo/trinity-large-preview", "kilo/trinity-large-preview");
51    map.insert("kilo/nemotron-3-super-free", "kilo/nemotron-3-super-free");
52    map.insert("qwen3.6-plus-free", "opencode/qwen3.6-plus-free");
53    map.insert("kimi-k2.5-free", "opencode/kimi-k2.5-free");
54    map.insert("glm-4.7-free", "opencode/glm-4.7-free");
55    map.insert("minimax-m2.1-free", "opencode/minimax-m2.1-free");
56    map.insert("kilo/glm-4.7-free", "kilo/glm-4.7-free");
57    map.insert("kilo/kimi-k2.5-free", "kilo/kimi-k2.5-free");
58    map.insert("kilo/minimax-m2.1-free", "kilo/minimax-m2.1-free");
59    map.insert("opus", "anthropic/claude-opus-5-5");
60    map.insert("sonnet", "anthropic/claude-sonnet-5-5");
61    map.insert("haiku", "anthropic/claude-haiku-5-5");
62    map.insert("fable", "anthropic/claude-fable-5-1");
63    map.insert("gemini-pro", "google/gemini-3.1-pro-preview");
64    map.insert("gemini-3-pro", "google/gemini-3.1-pro-preview");
65    map
66}
67
68/// Map model alias to full model ID
69///
70/// # Arguments
71/// * `model` - Model alias or full ID
72///
73/// # Returns
74/// Full model ID
75pub fn map_model_to_id(model: &str) -> String {
76    lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
77}
78
79/// Agent command build options
80#[derive(Debug, Clone, Default)]
81pub struct AgentBuildOptions {
82    pub prompt: Option<String>,
83    pub prompt_file: Option<String>,
84    pub system_prompt: Option<String>,
85    pub model: Option<String>,
86    pub resume: Option<String>,
87    pub compact_json: bool,
88    pub use_existing_claude_oauth: bool,
89    /// Enforce hard read-only mode (`--permission-mode readonly`)
90    pub read_only: bool,
91    /// Enforce planning mode (`--permission-mode plan`)
92    pub plan_only: bool,
93    /// Approve each mutating command (`--permission-mode ask`)
94    pub approve_each: bool,
95    /// Explicit agent permission mode (auto | plan | readonly | ask)
96    pub permission_mode: Option<String>,
97    /// OpenCode-compatible `--permission` JSON policy
98    pub permission: Option<String>,
99    /// Caller owns the child's stdin and streams the prompt + permission
100    /// responses as NDJSON frames, so no prompt is piped in `build_command`.
101    pub stream_input: bool,
102    /// Read stream-json user frames from stdin (live input)
103    pub json_input: bool,
104    pub executable: Option<String>,
105    pub extra_env: Vec<(String, String)>,
106    /// Variables removed from the inherited environment (`env -u`)
107    pub unset_env: Vec<String>,
108    pub extra_args: Vec<String>,
109}
110
111/// Build command line arguments for Agent
112///
113/// # Arguments
114/// * `options` - Build options
115///
116/// # Returns
117/// Vector of CLI arguments
118pub fn build_args(options: &AgentBuildOptions) -> Vec<String> {
119    let mut args = Vec::new();
120    if let Some(resume) = &options.resume {
121        args.extend(["--resume".into(), resume.clone(), "--no-fork".into()]);
122    }
123
124    // Native, enforceable permission system (agent v0.24.0, PR #272).
125    // --plan-only maps to `plan`, --read-only maps to the harder `readonly`,
126    // --approve-each maps to `ask` (per-command approval relayed over JSON),
127    // matching agent's own distinction between the modes. An explicit
128    // permission_mode always wins.
129    let resolved_permission_mode = options.permission_mode.clone().or_else(|| {
130        if options.approve_each {
131            Some("ask".to_string())
132        } else if options.plan_only {
133            Some("plan".to_string())
134        } else if options.read_only {
135            Some("readonly".to_string())
136        } else {
137            None
138        }
139    });
140    let is_ask = resolved_permission_mode.as_deref() == Some("ask");
141    if let Some(mode) = resolved_permission_mode {
142        args.push("--permission-mode".to_string());
143        args.push(mode);
144    }
145
146    // Ask mode emits requests mid-turn and blocks until answered, so it requires
147    // a streaming input mode (single-shot prompt over stdin would deadlock).
148    // Live input reads follow-up user frames on the same channel.
149    if is_ask || options.json_input {
150        args.push("--input-format".to_string());
151        args.push("stream-json".to_string());
152    }
153
154    if let Some(ref permission) = options.permission {
155        args.push("--permission".to_string());
156        args.push(permission.clone());
157    }
158
159    if let Some(ref model) = options.model {
160        let mapped_model = map_model_to_id(model);
161        args.push("--model".to_string());
162        args.push(mapped_model);
163    }
164
165    if options.compact_json {
166        args.push("--compact-json".to_string());
167    }
168
169    if options.use_existing_claude_oauth {
170        args.push("--use-existing-claude-oauth".to_string());
171    }
172
173    args.extend(options.extra_args.clone());
174
175    args
176}
177
178/// Build complete command string for Agent
179/// Agent uses stdin for prompt input (NDJSON streaming supported)
180///
181/// # Arguments
182/// * `options` - Build options
183///
184/// # Returns
185/// Complete command string
186pub fn build_command(options: &AgentBuildOptions) -> String {
187    let args = build_args(options);
188    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
189    let executable = options.executable.as_deref().unwrap_or("agent");
190    let command_head = format!(
191        "{} {}",
192        build_command_head(executable, &[], &[], &[]),
193        args_str.join(" ")
194    )
195    .trim()
196    .to_string();
197
198    // In stream-input mode the caller owns the child's stdin and writes the
199    // prompt and permission responses as NDJSON frames (per-command approval
200    // relay), so no prompt is piped here.
201    if options.stream_input {
202        return command_head;
203    }
204
205    // Agent expects prompt via stdin, combine system and user prompts
206    let combined_prompt = match (&options.system_prompt, &options.prompt) {
207        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
208        (Some(sys), None) => sys.clone(),
209        (None, Some(prompt)) => prompt.clone(),
210        (None, None) => String::new(),
211    };
212
213    // Build command with stdin piping
214    let input_command = options.prompt_file.as_ref().map_or_else(
215        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
216        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
217    );
218    format!("{} | {}", input_command, command_head)
219        .trim()
220        .to_string()
221}
222
223/// Parse JSON messages from Agent output
224/// Agent pretty-prints JSON events by default and emits NDJSON with
225/// `--compact-json`; both shapes are parsed by the record scanner.
226///
227/// # Arguments
228/// * `output` - Raw output string
229///
230/// # Returns
231/// Vector of parsed JSON messages
232pub fn parse_output(output: &str) -> Vec<Value> {
233    parse_json_records(output)
234}
235
236/// Extract session ID from Agent output
237///
238/// # Arguments
239/// * `output` - Raw output string
240///
241/// # Returns
242/// Session ID or None
243pub fn extract_session_id(output: &str) -> Option<String> {
244    let messages = parse_output(output);
245
246    for msg in messages {
247        if let Some(session_id) = msg
248            .get("session_id")
249            .or_else(|| msg.get("sessionID"))
250            .and_then(|v| v.as_str())
251        {
252            return Some(session_id.to_string());
253        }
254    }
255
256    None
257}
258
259/// Usage statistics for Agent
260#[derive(Debug, Clone, Default, serde::Serialize)]
261#[serde(rename_all = "camelCase")]
262pub struct AgentUsage {
263    pub input_tokens: u64,
264    pub output_tokens: u64,
265    pub reasoning_tokens: u64,
266    pub cache_read_tokens: u64,
267    pub cache_write_tokens: u64,
268    pub total_cost: f64,
269    pub step_count: u64,
270}
271
272/// Parse token usage from Agent output
273/// Agent outputs step_finish events with token data
274///
275/// # Arguments
276/// * `output` - Raw output string
277///
278/// # Returns
279/// Token usage statistics
280pub fn extract_usage(output: &str) -> AgentUsage {
281    let messages = parse_output(output);
282    let mut usage = AgentUsage::default();
283
284    for msg in messages {
285        // Look for step_finish events which contain token usage
286        if msg.get("type").and_then(|t| t.as_str()) == Some("step_finish") {
287            if let Some(part) = msg.get("part") {
288                usage.step_count += 1;
289
290                if let Some(tokens) = part.get("tokens") {
291                    if let Some(input) = tokens.get("input").and_then(|v| v.as_u64()) {
292                        usage.input_tokens += input;
293                    }
294                    if let Some(output) = tokens.get("output").and_then(|v| v.as_u64()) {
295                        usage.output_tokens += output;
296                    }
297                    if let Some(reasoning) = tokens.get("reasoning").and_then(|v| v.as_u64()) {
298                        usage.reasoning_tokens += reasoning;
299                    }
300
301                    // Handle cache tokens
302                    if let Some(cache) = tokens.get("cache") {
303                        if let Some(read) = cache.get("read").and_then(|v| v.as_u64()) {
304                            usage.cache_read_tokens += read;
305                        }
306                        if let Some(write) = cache.get("write").and_then(|v| v.as_u64()) {
307                            usage.cache_write_tokens += write;
308                        }
309                    }
310                }
311
312                // Add cost from step_finish
313                if let Some(cost) = part.get("cost").and_then(|v| v.as_f64()) {
314                    usage.total_cost += cost;
315                }
316            }
317        }
318    }
319
320    usage
321}
322
323/// Error detection result
324#[derive(Debug, Clone, Default)]
325pub struct ErrorResult {
326    pub has_error: bool,
327    pub error_type: Option<String>,
328    pub message: Option<String>,
329}
330
331const FATAL_AGENT_LOG_PATTERNS: [&str; 4] = [
332    "providermodelnotfounderror",
333    "provideriniterror",
334    "nosuchmodelerror",
335    "modelnotfounderror",
336];
337
338fn is_fatal_log_text(text: &str) -> bool {
339    let lower = text.to_lowercase();
340    FATAL_AGENT_LOG_PATTERNS
341        .iter()
342        .any(|pattern| lower.contains(pattern))
343        || lower
344            .find("failed to initialize ")
345            .is_some_and(|index| lower[index..].contains("model"))
346}
347
348/// Detect a `log` record reporting a fatal startup failure
349///
350/// Agent prints it, then `session.idle`, and exits 0 without an `error`
351/// record (hive-mind#2141). Returns the readable failure text.
352pub fn detect_fatal_agent_log_record(record: &Value) -> Option<String> {
353    if record["type"] != "log" || record["level"] != "error" {
354        return None;
355    }
356    let error = stringify_error_value(&record["error"], MAX_ERROR_TEXT_LENGTH, "");
357    let message = stringify_error_value(&record["message"], MAX_ERROR_TEXT_LENGTH, "");
358    if !is_fatal_log_text(&format!("{error} {message}")) {
359        return None;
360    }
361    let hint = stringify_error_value(&record["hint"], MAX_ERROR_TEXT_LENGTH, "");
362    let hint = if hint.is_empty() {
363        hint
364    } else {
365        format!("hint: {hint}")
366    };
367    Some(
368        [error, message, hint]
369            .into_iter()
370            .filter(|part| !part.is_empty())
371            .collect::<Vec<_>>()
372            .join(" — "),
373    )
374}
375
376/// Whether an error record is a failed tool call the model recovers from
377///
378/// A failed tool call is returned to the model as the tool result; agent
379/// 0.26.13 and earlier also repeated it as a top-level error record (agent#332,
380/// hive-mind#3213). Only the session's own errors decide the run.
381pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
382    crate::usage_limit::is_recoverable_tool_error(record)
383}
384
385/// Detect errors in Agent output
386///
387/// The last fatal error record is the one the session ended on; failed tool
388/// calls are skipped.
389pub fn detect_errors(output: &str) -> ErrorResult {
390    let mut detection = ErrorResult::default();
391
392    for msg in parse_output(output) {
393        if let Some(fatal_log) = detect_fatal_agent_log_record(&msg) {
394            let error_type =
395                stringify_error_value(&msg["error"], MAX_ERROR_TEXT_LENGTH, "fatal_log");
396            detection = ErrorResult {
397                has_error: true,
398                error_type: Some(error_type),
399                message: Some(fatal_log),
400            };
401        } else if matches!(msg["type"].as_str(), Some("error" | "step_error"))
402            && !is_recoverable_agent_tool_error(&msg)
403        {
404            let error_type = msg
405                .pointer("/error/name")
406                .and_then(Value::as_str)
407                .filter(|name| !name.is_empty())
408                .or_else(|| msg["type"].as_str())
409                .map(ToString::to_string);
410            detection = ErrorResult {
411                has_error: true,
412                error_type,
413                message: Some(first_error_text(
414                    &[&msg["message"], &msg["error"], &msg["data"]],
415                    "Agent emitted an error event without any details",
416                )),
417            };
418        }
419    }
420
421    detection
422}
423
424/// Agent tool configuration
425#[derive(Debug, Clone)]
426pub struct AgentTool {
427    pub name: &'static str,
428    pub display_name: &'static str,
429    pub executable: &'static str,
430    pub supports_json_output: bool,
431    pub supports_json_input: bool,
432    pub supports_system_prompt: bool,
433    pub supports_resume: bool,
434    pub supports_read_only: bool,
435    pub supports_ask: bool,
436    pub default_model: &'static str,
437}
438
439impl Default for AgentTool {
440    fn default() -> Self {
441        Self {
442            name: "agent",
443            display_name: "@link-assistant/agent",
444            executable: "agent",
445            supports_json_output: true,
446            supports_json_input: true, // Agent supports full JSON streaming input
447            supports_system_prompt: false, // System prompt is combined with user prompt
448            supports_resume: true,     // --resume SESSION --no-fork
449            supports_read_only: true, // Native --permission-mode readonly/plan (agent v0.24.0, PR #272)
450            supports_ask: true,       // Native --permission-mode ask with JSON permission relay
451            default_model: "nemotron-3-super-free",
452        }
453    }
454}
455
456// Tests are in rust/tests/agent_tests.rs