1use 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
17pub fn get_model_map() -> HashMap<&'static str, &'static str> {
20 let mut map = HashMap::new();
21 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
68pub 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#[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 pub read_only: bool,
91 pub plan_only: bool,
93 pub approve_each: bool,
95 pub permission_mode: Option<String>,
97 pub permission: Option<String>,
99 pub stream_input: bool,
102 pub json_input: bool,
104 pub executable: Option<String>,
105 pub extra_env: Vec<(String, String)>,
106 pub unset_env: Vec<String>,
108 pub extra_args: Vec<String>,
109}
110
111pub 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 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 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
178pub 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, &options.unset_env, &options.extra_env, &[]),
193 args_str.join(" ")
194 )
195 .trim()
196 .to_string();
197
198 if options.stream_input {
202 return command_head;
203 }
204
205 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 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
223pub fn parse_output(output: &str) -> Vec<Value> {
233 parse_json_records(output)
234}
235
236pub 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#[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
272pub 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 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 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 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#[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
348pub 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
376pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
382 crate::usage_limit::is_recoverable_tool_error(record)
383}
384
385pub 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#[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, supports_system_prompt: false, supports_resume: true, supports_read_only: true, supports_ask: true, default_model: "nemotron-3-super-free",
452 }
453 }
454}
455
456