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::streaming::parse_ndjson;
10use crate::tools::shell::{build_command_head, escape_arg, escape_single_quotes};
11use serde_json::Value;
12use std::collections::HashMap;
13
14/// Get the Agent model map
15/// Maps aliases to full model IDs (uses OpenCode's provider/model format)
16pub fn get_model_map() -> HashMap<&'static str, &'static str> {
17    let mut map = HashMap::new();
18    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
19    map.insert("formal-ai", "formalai/formal-ai");
20    map.insert("formalai/formal-ai", "formalai/formal-ai");
21    map.insert("grok", "opencode/grok-code");
22    map.insert("grok-code", "opencode/grok-code");
23    map.insert("grok-code-fast-1", "opencode/grok-code");
24    map.insert("big-pickle", "opencode/big-pickle");
25    map.insert("gpt-5-nano", "opencode/gpt-5-nano");
26    map.insert("minimax-m2.5-free", "opencode/minimax-m2.5-free");
27    map.insert("nemotron-3-super-free", "opencode/nemotron-3-super-free");
28    map.insert("glm-5-free", "kilo/glm-5-free");
29    map.insert("glm-4.5-air-free", "kilo/glm-4.5-air-free");
30    map.insert("deepseek-r1-free", "kilo/deepseek-r1-free");
31    map.insert("giga-potato-free", "kilo/giga-potato-free");
32    map.insert("trinity-large-preview", "kilo/trinity-large-preview");
33    map.insert("kilo/glm-5-free", "kilo/glm-5-free");
34    map.insert("kilo/glm-4.5-air-free", "kilo/glm-4.5-air-free");
35    map.insert("kilo/minimax-m2.5-free", "kilo/minimax-m2.5-free");
36    map.insert("kilo/deepseek-r1-free", "kilo/deepseek-r1-free");
37    map.insert("kilo/giga-potato-free", "kilo/giga-potato-free");
38    map.insert("kilo/trinity-large-preview", "kilo/trinity-large-preview");
39    map.insert("qwen3.6-plus-free", "opencode/qwen3.6-plus-free");
40    map.insert("kimi-k2.5-free", "opencode/kimi-k2.5-free");
41    map.insert("glm-4.7-free", "opencode/glm-4.7-free");
42    map.insert("minimax-m2.1-free", "opencode/minimax-m2.1-free");
43    map.insert("kilo/glm-4.7-free", "kilo/glm-4.7-free");
44    map.insert("kilo/kimi-k2.5-free", "kilo/kimi-k2.5-free");
45    map.insert("kilo/minimax-m2.1-free", "kilo/minimax-m2.1-free");
46    map.insert("sonnet", "anthropic/claude-3-5-sonnet");
47    map.insert("haiku", "anthropic/claude-3-5-haiku");
48    map.insert("opus", "anthropic/claude-3-opus");
49    map.insert("gemini-3-pro", "google/gemini-3-pro");
50    map
51}
52
53/// Map model alias to full model ID
54///
55/// # Arguments
56/// * `model` - Model alias or full ID
57///
58/// # Returns
59/// Full model ID
60pub fn map_model_to_id(model: &str) -> String {
61    let model_map = get_model_map();
62    model_map
63        .get(model)
64        .map(|s| s.to_string())
65        .unwrap_or_else(|| model.to_string())
66}
67
68/// Agent command build options
69#[derive(Debug, Clone, Default)]
70pub struct AgentBuildOptions {
71    pub prompt: Option<String>,
72    pub prompt_file: Option<String>,
73    pub system_prompt: Option<String>,
74    pub model: Option<String>,
75    pub resume: Option<String>,
76    pub compact_json: bool,
77    pub use_existing_claude_oauth: bool,
78    /// Enforce hard read-only mode (`--permission-mode readonly`)
79    pub read_only: bool,
80    /// Enforce planning mode (`--permission-mode plan`)
81    pub plan_only: bool,
82    /// Approve each mutating command (`--permission-mode ask`)
83    pub approve_each: bool,
84    /// Explicit agent permission mode (auto | plan | readonly | ask)
85    pub permission_mode: Option<String>,
86    /// OpenCode-compatible `--permission` JSON policy
87    pub permission: Option<String>,
88    /// Caller owns the child's stdin and streams the prompt + permission
89    /// responses as NDJSON frames, so no prompt is piped in `build_command`.
90    pub stream_input: bool,
91    pub executable: Option<String>,
92    pub extra_env: Vec<(String, String)>,
93    pub extra_args: Vec<String>,
94}
95
96/// Build command line arguments for Agent
97///
98/// # Arguments
99/// * `options` - Build options
100///
101/// # Returns
102/// Vector of CLI arguments
103pub fn build_args(options: &AgentBuildOptions) -> Vec<String> {
104    let mut args = Vec::new();
105    if let Some(resume) = &options.resume {
106        args.extend(["--resume".into(), resume.clone(), "--no-fork".into()]);
107    }
108
109    // Native, enforceable permission system (agent v0.24.0, PR #272).
110    // --plan-only maps to `plan`, --read-only maps to the harder `readonly`,
111    // --approve-each maps to `ask` (per-command approval relayed over JSON),
112    // matching agent's own distinction between the modes. An explicit
113    // permission_mode always wins.
114    let resolved_permission_mode = options.permission_mode.clone().or_else(|| {
115        if options.approve_each {
116            Some("ask".to_string())
117        } else if options.plan_only {
118            Some("plan".to_string())
119        } else if options.read_only {
120            Some("readonly".to_string())
121        } else {
122            None
123        }
124    });
125    let is_ask = resolved_permission_mode.as_deref() == Some("ask");
126    if let Some(mode) = resolved_permission_mode {
127        args.push("--permission-mode".to_string());
128        args.push(mode);
129    }
130
131    // Ask mode emits requests mid-turn and blocks until answered, so it requires
132    // a streaming input mode (single-shot prompt over stdin would deadlock).
133    if is_ask {
134        args.push("--input-format".to_string());
135        args.push("stream-json".to_string());
136    }
137
138    if let Some(ref permission) = options.permission {
139        args.push("--permission".to_string());
140        args.push(permission.clone());
141    }
142
143    if let Some(ref model) = options.model {
144        let mapped_model = map_model_to_id(model);
145        args.push("--model".to_string());
146        args.push(mapped_model);
147    }
148
149    if options.compact_json {
150        args.push("--compact-json".to_string());
151    }
152
153    if options.use_existing_claude_oauth {
154        args.push("--use-existing-claude-oauth".to_string());
155    }
156
157    args.extend(options.extra_args.clone());
158
159    args
160}
161
162/// Build complete command string for Agent
163/// Agent uses stdin for prompt input (NDJSON streaming supported)
164///
165/// # Arguments
166/// * `options` - Build options
167///
168/// # Returns
169/// Complete command string
170pub fn build_command(options: &AgentBuildOptions) -> String {
171    let args = build_args(options);
172    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
173    let executable = options.executable.as_deref().unwrap_or("agent");
174    let command_head = format!(
175        "{} {}",
176        build_command_head(executable, &options.extra_env, &[]),
177        args_str.join(" ")
178    )
179    .trim()
180    .to_string();
181
182    // In stream-input mode the caller owns the child's stdin and writes the
183    // prompt and permission responses as NDJSON frames (per-command approval
184    // relay), so no prompt is piped here.
185    if options.stream_input {
186        return command_head;
187    }
188
189    // Agent expects prompt via stdin, combine system and user prompts
190    let combined_prompt = match (&options.system_prompt, &options.prompt) {
191        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
192        (Some(sys), None) => sys.clone(),
193        (None, Some(prompt)) => prompt.clone(),
194        (None, None) => String::new(),
195    };
196
197    // Build command with stdin piping
198    let input_command = options.prompt_file.as_ref().map_or_else(
199        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
200        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
201    );
202    format!("{} | {}", input_command, command_head)
203        .trim()
204        .to_string()
205}
206
207/// Parse JSON messages from Agent output
208/// Agent outputs NDJSON format with specific event types
209///
210/// # Arguments
211/// * `output` - Raw output string
212///
213/// # Returns
214/// Vector of parsed JSON messages
215pub fn parse_output(output: &str) -> Vec<Value> {
216    parse_ndjson(output)
217}
218
219/// Extract session ID from Agent output
220///
221/// # Arguments
222/// * `output` - Raw output string
223///
224/// # Returns
225/// Session ID or None
226pub fn extract_session_id(output: &str) -> Option<String> {
227    let messages = parse_output(output);
228
229    for msg in messages {
230        if let Some(session_id) = msg
231            .get("session_id")
232            .or_else(|| msg.get("sessionID"))
233            .and_then(|v| v.as_str())
234        {
235            return Some(session_id.to_string());
236        }
237    }
238
239    None
240}
241
242/// Usage statistics for Agent
243#[derive(Debug, Clone, Default, serde::Serialize)]
244#[serde(rename_all = "camelCase")]
245pub struct AgentUsage {
246    pub input_tokens: u64,
247    pub output_tokens: u64,
248    pub reasoning_tokens: u64,
249    pub cache_read_tokens: u64,
250    pub cache_write_tokens: u64,
251    pub total_cost: f64,
252    pub step_count: u64,
253}
254
255/// Parse token usage from Agent output
256/// Agent outputs step_finish events with token data
257///
258/// # Arguments
259/// * `output` - Raw output string
260///
261/// # Returns
262/// Token usage statistics
263pub fn extract_usage(output: &str) -> AgentUsage {
264    let messages = parse_output(output);
265    let mut usage = AgentUsage::default();
266
267    for msg in messages {
268        // Look for step_finish events which contain token usage
269        if msg.get("type").and_then(|t| t.as_str()) == Some("step_finish") {
270            if let Some(part) = msg.get("part") {
271                usage.step_count += 1;
272
273                if let Some(tokens) = part.get("tokens") {
274                    if let Some(input) = tokens.get("input").and_then(|v| v.as_u64()) {
275                        usage.input_tokens += input;
276                    }
277                    if let Some(output) = tokens.get("output").and_then(|v| v.as_u64()) {
278                        usage.output_tokens += output;
279                    }
280                    if let Some(reasoning) = tokens.get("reasoning").and_then(|v| v.as_u64()) {
281                        usage.reasoning_tokens += reasoning;
282                    }
283
284                    // Handle cache tokens
285                    if let Some(cache) = tokens.get("cache") {
286                        if let Some(read) = cache.get("read").and_then(|v| v.as_u64()) {
287                            usage.cache_read_tokens += read;
288                        }
289                        if let Some(write) = cache.get("write").and_then(|v| v.as_u64()) {
290                            usage.cache_write_tokens += write;
291                        }
292                    }
293                }
294
295                // Add cost from step_finish
296                if let Some(cost) = part.get("cost").and_then(|v| v.as_f64()) {
297                    usage.total_cost += cost;
298                }
299            }
300        }
301    }
302
303    usage
304}
305
306/// Error detection result
307#[derive(Debug, Clone, Default)]
308pub struct ErrorResult {
309    pub has_error: bool,
310    pub error_type: Option<String>,
311    pub message: Option<String>,
312}
313
314/// Detect errors in Agent output
315///
316/// # Arguments
317/// * `output` - Raw output string
318///
319/// # Returns
320/// Error detection result
321pub fn detect_errors(output: &str) -> ErrorResult {
322    let messages = parse_output(output);
323
324    for msg in messages {
325        // Check for explicit error message types from agent
326        let msg_type = msg.get("type").and_then(|t| t.as_str());
327        if msg_type == Some("error") || msg_type == Some("step_error") {
328            return ErrorResult {
329                has_error: true,
330                error_type: msg_type.map(|s| s.to_string()),
331                message: msg
332                    .get("message")
333                    .and_then(|m| m.as_str())
334                    .map(|s| s.to_string())
335                    .or_else(|| Some("Unknown error".to_string())),
336            };
337        }
338    }
339
340    ErrorResult::default()
341}
342
343/// Agent tool configuration
344#[derive(Debug, Clone)]
345pub struct AgentTool {
346    pub name: &'static str,
347    pub display_name: &'static str,
348    pub executable: &'static str,
349    pub supports_json_output: bool,
350    pub supports_json_input: bool,
351    pub supports_system_prompt: bool,
352    pub supports_resume: bool,
353    pub supports_read_only: bool,
354    pub supports_ask: bool,
355    pub default_model: &'static str,
356}
357
358impl Default for AgentTool {
359    fn default() -> Self {
360        Self {
361            name: "agent",
362            display_name: "@link-assistant/agent",
363            executable: "agent",
364            supports_json_output: true,
365            supports_json_input: true, // Agent supports full JSON streaming input
366            supports_system_prompt: false, // System prompt is combined with user prompt
367            supports_resume: true,     // --resume SESSION --no-fork
368            supports_read_only: true, // Native --permission-mode readonly/plan (agent v0.24.0, PR #272)
369            supports_ask: true,       // Native --permission-mode ask with JSON permission relay
370            default_model: "nemotron-3-super-free",
371        }
372    }
373}
374
375// Tests are in rust/tests/agent_tests.rs