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 executable: Option<String>,
103 pub extra_env: Vec<(String, String)>,
104 pub unset_env: Vec<String>,
106 pub extra_args: Vec<String>,
107}
108
109pub 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 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 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
175pub 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 if options.stream_input {
199 return command_head;
200 }
201
202 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 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
220pub fn parse_output(output: &str) -> Vec<Value> {
230 parse_json_records(output)
231}
232
233pub 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#[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
269pub 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 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 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 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#[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
345pub 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
373pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
379 crate::usage_limit::is_recoverable_tool_error(record)
380}
381
382pub 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#[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, supports_system_prompt: false, supports_resume: true, supports_read_only: true, supports_ask: true, default_model: "nemotron-3-super-free",
449 }
450 }
451}
452
453