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    pub executable: Option<String>,
103    pub extra_env: Vec<(String, String)>,
104    /// Variables removed from the inherited environment (`env -u`)
105    pub unset_env: Vec<String>,
106    pub extra_args: Vec<String>,
107}
108
109/// Build command line arguments for Agent
110///
111/// # Arguments
112/// * `options` - Build options
113///
114/// # Returns
115/// Vector of CLI arguments
116pub fn build_args(options: &AgentBuildOptions) -> Vec<String> {
117    let mut args = Vec::new();
118    if let Some(resume) = &options.resume {
119        args.extend(["--resume".into(), resume.clone(), "--no-fork".into()]);
120    }
121
122    // Native, enforceable permission system (agent v0.24.0, PR #272).
123    // --plan-only maps to `plan`, --read-only maps to the harder `readonly`,
124    // --approve-each maps to `ask` (per-command approval relayed over JSON),
125    // matching agent's own distinction between the modes. An explicit
126    // permission_mode always wins.
127    let resolved_permission_mode = options.permission_mode.clone().or_else(|| {
128        if options.approve_each {
129            Some("ask".to_string())
130        } else if options.plan_only {
131            Some("plan".to_string())
132        } else if options.read_only {
133            Some("readonly".to_string())
134        } else {
135            None
136        }
137    });
138    let is_ask = resolved_permission_mode.as_deref() == Some("ask");
139    if let Some(mode) = resolved_permission_mode {
140        args.push("--permission-mode".to_string());
141        args.push(mode);
142    }
143
144    // Ask mode emits requests mid-turn and blocks until answered, so it requires
145    // a streaming input mode (single-shot prompt over stdin would deadlock).
146    if is_ask {
147        args.push("--input-format".to_string());
148        args.push("stream-json".to_string());
149    }
150
151    if let Some(ref permission) = options.permission {
152        args.push("--permission".to_string());
153        args.push(permission.clone());
154    }
155
156    if let Some(ref model) = options.model {
157        let mapped_model = map_model_to_id(model);
158        args.push("--model".to_string());
159        args.push(mapped_model);
160    }
161
162    if options.compact_json {
163        args.push("--compact-json".to_string());
164    }
165
166    if options.use_existing_claude_oauth {
167        args.push("--use-existing-claude-oauth".to_string());
168    }
169
170    args.extend(options.extra_args.clone());
171
172    args
173}
174
175/// Build complete command string for Agent
176/// Agent uses stdin for prompt input (NDJSON streaming supported)
177///
178/// # Arguments
179/// * `options` - Build options
180///
181/// # Returns
182/// Complete command string
183pub fn build_command(options: &AgentBuildOptions) -> String {
184    let args = build_args(options);
185    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
186    let executable = options.executable.as_deref().unwrap_or("agent");
187    let command_head = format!(
188        "{} {}",
189        build_command_head(executable, &options.unset_env, &options.extra_env, &[]),
190        args_str.join(" ")
191    )
192    .trim()
193    .to_string();
194
195    // In stream-input mode the caller owns the child's stdin and writes the
196    // prompt and permission responses as NDJSON frames (per-command approval
197    // relay), so no prompt is piped here.
198    if options.stream_input {
199        return command_head;
200    }
201
202    // Agent expects prompt via stdin, combine system and user prompts
203    let combined_prompt = match (&options.system_prompt, &options.prompt) {
204        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
205        (Some(sys), None) => sys.clone(),
206        (None, Some(prompt)) => prompt.clone(),
207        (None, None) => String::new(),
208    };
209
210    // Build command with stdin piping
211    let input_command = options.prompt_file.as_ref().map_or_else(
212        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
213        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
214    );
215    format!("{} | {}", input_command, command_head)
216        .trim()
217        .to_string()
218}
219
220/// Parse JSON messages from Agent output
221/// Agent pretty-prints JSON events by default and emits NDJSON with
222/// `--compact-json`; both shapes are parsed by the record scanner.
223///
224/// # Arguments
225/// * `output` - Raw output string
226///
227/// # Returns
228/// Vector of parsed JSON messages
229pub fn parse_output(output: &str) -> Vec<Value> {
230    parse_json_records(output)
231}
232
233/// Extract session ID from Agent output
234///
235/// # Arguments
236/// * `output` - Raw output string
237///
238/// # Returns
239/// Session ID or None
240pub fn extract_session_id(output: &str) -> Option<String> {
241    let messages = parse_output(output);
242
243    for msg in messages {
244        if let Some(session_id) = msg
245            .get("session_id")
246            .or_else(|| msg.get("sessionID"))
247            .and_then(|v| v.as_str())
248        {
249            return Some(session_id.to_string());
250        }
251    }
252
253    None
254}
255
256/// Usage statistics for Agent
257#[derive(Debug, Clone, Default, serde::Serialize)]
258#[serde(rename_all = "camelCase")]
259pub struct AgentUsage {
260    pub input_tokens: u64,
261    pub output_tokens: u64,
262    pub reasoning_tokens: u64,
263    pub cache_read_tokens: u64,
264    pub cache_write_tokens: u64,
265    pub total_cost: f64,
266    pub step_count: u64,
267}
268
269/// Parse token usage from Agent output
270/// Agent outputs step_finish events with token data
271///
272/// # Arguments
273/// * `output` - Raw output string
274///
275/// # Returns
276/// Token usage statistics
277pub fn extract_usage(output: &str) -> AgentUsage {
278    let messages = parse_output(output);
279    let mut usage = AgentUsage::default();
280
281    for msg in messages {
282        // Look for step_finish events which contain token usage
283        if msg.get("type").and_then(|t| t.as_str()) == Some("step_finish") {
284            if let Some(part) = msg.get("part") {
285                usage.step_count += 1;
286
287                if let Some(tokens) = part.get("tokens") {
288                    if let Some(input) = tokens.get("input").and_then(|v| v.as_u64()) {
289                        usage.input_tokens += input;
290                    }
291                    if let Some(output) = tokens.get("output").and_then(|v| v.as_u64()) {
292                        usage.output_tokens += output;
293                    }
294                    if let Some(reasoning) = tokens.get("reasoning").and_then(|v| v.as_u64()) {
295                        usage.reasoning_tokens += reasoning;
296                    }
297
298                    // Handle cache tokens
299                    if let Some(cache) = tokens.get("cache") {
300                        if let Some(read) = cache.get("read").and_then(|v| v.as_u64()) {
301                            usage.cache_read_tokens += read;
302                        }
303                        if let Some(write) = cache.get("write").and_then(|v| v.as_u64()) {
304                            usage.cache_write_tokens += write;
305                        }
306                    }
307                }
308
309                // Add cost from step_finish
310                if let Some(cost) = part.get("cost").and_then(|v| v.as_f64()) {
311                    usage.total_cost += cost;
312                }
313            }
314        }
315    }
316
317    usage
318}
319
320/// Error detection result
321#[derive(Debug, Clone, Default)]
322pub struct ErrorResult {
323    pub has_error: bool,
324    pub error_type: Option<String>,
325    pub message: Option<String>,
326}
327
328const FATAL_AGENT_LOG_PATTERNS: [&str; 4] = [
329    "providermodelnotfounderror",
330    "provideriniterror",
331    "nosuchmodelerror",
332    "modelnotfounderror",
333];
334
335fn is_fatal_log_text(text: &str) -> bool {
336    let lower = text.to_lowercase();
337    FATAL_AGENT_LOG_PATTERNS
338        .iter()
339        .any(|pattern| lower.contains(pattern))
340        || lower
341            .find("failed to initialize ")
342            .is_some_and(|index| lower[index..].contains("model"))
343}
344
345/// Detect a `log` record reporting a fatal startup failure
346///
347/// Agent prints it, then `session.idle`, and exits 0 without an `error`
348/// record (hive-mind#2141). Returns the readable failure text.
349pub fn detect_fatal_agent_log_record(record: &Value) -> Option<String> {
350    if record["type"] != "log" || record["level"] != "error" {
351        return None;
352    }
353    let error = stringify_error_value(&record["error"], MAX_ERROR_TEXT_LENGTH, "");
354    let message = stringify_error_value(&record["message"], MAX_ERROR_TEXT_LENGTH, "");
355    if !is_fatal_log_text(&format!("{error} {message}")) {
356        return None;
357    }
358    let hint = stringify_error_value(&record["hint"], MAX_ERROR_TEXT_LENGTH, "");
359    let hint = if hint.is_empty() {
360        hint
361    } else {
362        format!("hint: {hint}")
363    };
364    Some(
365        [error, message, hint]
366            .into_iter()
367            .filter(|part| !part.is_empty())
368            .collect::<Vec<_>>()
369            .join(" — "),
370    )
371}
372
373/// Whether an error record is a failed tool call the model recovers from
374///
375/// A failed tool call is returned to the model as the tool result; agent
376/// 0.26.13 and earlier also repeated it as a top-level error record (agent#332,
377/// hive-mind#3213). Only the session's own errors decide the run.
378pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
379    crate::usage_limit::is_recoverable_tool_error(record)
380}
381
382/// Detect errors in Agent output
383///
384/// The last fatal error record is the one the session ended on; failed tool
385/// calls are skipped.
386pub fn detect_errors(output: &str) -> ErrorResult {
387    let mut detection = ErrorResult::default();
388
389    for msg in parse_output(output) {
390        if let Some(fatal_log) = detect_fatal_agent_log_record(&msg) {
391            let error_type =
392                stringify_error_value(&msg["error"], MAX_ERROR_TEXT_LENGTH, "fatal_log");
393            detection = ErrorResult {
394                has_error: true,
395                error_type: Some(error_type),
396                message: Some(fatal_log),
397            };
398        } else if matches!(msg["type"].as_str(), Some("error" | "step_error"))
399            && !is_recoverable_agent_tool_error(&msg)
400        {
401            let error_type = msg
402                .pointer("/error/name")
403                .and_then(Value::as_str)
404                .filter(|name| !name.is_empty())
405                .or_else(|| msg["type"].as_str())
406                .map(ToString::to_string);
407            detection = ErrorResult {
408                has_error: true,
409                error_type,
410                message: Some(first_error_text(
411                    &[&msg["message"], &msg["error"], &msg["data"]],
412                    "Agent emitted an error event without any details",
413                )),
414            };
415        }
416    }
417
418    detection
419}
420
421/// Agent tool configuration
422#[derive(Debug, Clone)]
423pub struct AgentTool {
424    pub name: &'static str,
425    pub display_name: &'static str,
426    pub executable: &'static str,
427    pub supports_json_output: bool,
428    pub supports_json_input: bool,
429    pub supports_system_prompt: bool,
430    pub supports_resume: bool,
431    pub supports_read_only: bool,
432    pub supports_ask: bool,
433    pub default_model: &'static str,
434}
435
436impl Default for AgentTool {
437    fn default() -> Self {
438        Self {
439            name: "agent",
440            display_name: "@link-assistant/agent",
441            executable: "agent",
442            supports_json_output: true,
443            supports_json_input: true, // Agent supports full JSON streaming input
444            supports_system_prompt: false, // System prompt is combined with user prompt
445            supports_resume: true,     // --resume SESSION --no-fork
446            supports_read_only: true, // Native --permission-mode readonly/plan (agent v0.24.0, PR #272)
447            supports_ask: true,       // Native --permission-mode ask with JSON permission relay
448            default_model: "nemotron-3-super-free",
449        }
450    }
451}
452
453// Tests are in rust/tests/agent_tests.rs