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 temperature: Option<f64>,
88 pub resume: Option<String>,
89 pub compact_json: bool,
90 pub use_existing_claude_oauth: bool,
91 pub read_only: bool,
93 pub plan_only: bool,
95 pub approve_each: bool,
97 pub permission_mode: Option<String>,
99 pub permission: Option<String>,
101 pub stream_input: bool,
104 pub json_input: bool,
106 pub executable: Option<String>,
107 pub extra_env: Vec<(String, String)>,
108 pub unset_env: Vec<String>,
110 pub extra_args: Vec<String>,
111}
112
113pub 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 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 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
187pub 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 if options.stream_input {
211 return command_head;
212 }
213
214 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 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
232pub fn parse_output(output: &str) -> Vec<Value> {
242 parse_json_records(output)
243}
244
245pub 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#[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
281pub 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 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 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 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#[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
357pub 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
385pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
391 crate::usage_limit::is_recoverable_tool_error(record)
392}
393
394pub 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#[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, supports_system_prompt: false, supports_resume: true, supports_read_only: true, supports_ask: true, default_model: "nemotron-3-super-free",
461 }
462 }
463}
464
465