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