1use 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
14pub fn get_model_map() -> HashMap<&'static str, &'static str> {
17 let mut map = HashMap::new();
18 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
53pub 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#[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 pub read_only: bool,
80 pub plan_only: bool,
82 pub approve_each: bool,
84 pub permission_mode: Option<String>,
86 pub permission: Option<String>,
88 pub stream_input: bool,
91 pub executable: Option<String>,
92 pub extra_env: Vec<(String, String)>,
93 pub extra_args: Vec<String>,
94}
95
96pub 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 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 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
162pub 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 if options.stream_input {
186 return command_head;
187 }
188
189 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 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
207pub fn parse_output(output: &str) -> Vec<Value> {
216 parse_ndjson(output)
217}
218
219pub 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#[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
255pub 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 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 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 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#[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
314pub fn detect_errors(output: &str) -> ErrorResult {
322 let messages = parse_output(output);
323
324 for msg in messages {
325 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#[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, supports_system_prompt: false, supports_resume: true, supports_read_only: true, supports_ask: true, default_model: "nemotron-3-super-free",
371 }
372 }
373}
374
375