use crate::error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};
use crate::streaming::parse_json_records;
use crate::tools::shell::{
build_command_head, escape_arg, escape_single_quotes, lookup_model_alias,
};
use serde_json::Value;
use std::collections::HashMap;
pub fn get_model_map() -> HashMap<&'static str, &'static str> {
let mut map = HashMap::new();
map.insert("formal-ai", "formalai/formal-ai");
map.insert("formalai/formal-ai", "formalai/formal-ai");
map.insert("grok", "opencode/grok-code");
map.insert("grok-code", "opencode/grok-code");
map.insert("grok-code-fast-1", "opencode/grok-code");
map.insert("big-pickle", "opencode/big-pickle");
map.insert("gpt-5-nano", "opencode/gpt-5-nano");
map.insert("minimax-m2.5-free", "opencode/minimax-m2.5-free");
map.insert("nemotron-3-super-free", "kilo/nemotron-3-super-free");
map.insert("nemotron-3-ultra-free", "opencode/nemotron-3-ultra-free");
map.insert(
"nemotron-3.5-lightning-free",
"opencode/nemotron-3.5-lightning-free",
);
map.insert("ling-3.1-flash-free", "opencode/ling-3.1-flash-free");
map.insert("mimo-v2.6-flash-free", "opencode/mimo-v2.6-flash-free");
map.insert("step-5-preview-free", "opencode/step-5-preview-free");
map.insert("exo-free", "opencode/exo-free");
map.insert("glm-5-free", "kilo/glm-5-free");
map.insert("glm-4.5-air-free", "kilo/glm-4.5-air-free");
map.insert("deepseek-r1-free", "kilo/deepseek-r1-free");
map.insert("giga-potato-free", "kilo/giga-potato-free");
map.insert("trinity-large-preview", "kilo/trinity-large-preview");
map.insert("kilo/glm-5-free", "kilo/glm-5-free");
map.insert("kilo/glm-4.5-air-free", "kilo/glm-4.5-air-free");
map.insert("kilo/minimax-m2.5-free", "kilo/minimax-m2.5-free");
map.insert("kilo/deepseek-r1-free", "kilo/deepseek-r1-free");
map.insert("kilo/giga-potato-free", "kilo/giga-potato-free");
map.insert("kilo/trinity-large-preview", "kilo/trinity-large-preview");
map.insert("kilo/nemotron-3-super-free", "kilo/nemotron-3-super-free");
map.insert("qwen3.6-plus-free", "opencode/qwen3.6-plus-free");
map.insert("kimi-k2.5-free", "opencode/kimi-k2.5-free");
map.insert("glm-4.7-free", "opencode/glm-4.7-free");
map.insert("minimax-m2.1-free", "opencode/minimax-m2.1-free");
map.insert("kilo/glm-4.7-free", "kilo/glm-4.7-free");
map.insert("kilo/kimi-k2.5-free", "kilo/kimi-k2.5-free");
map.insert("kilo/minimax-m2.1-free", "kilo/minimax-m2.1-free");
map.insert("opus", "anthropic/claude-opus-5-5");
map.insert("sonnet", "anthropic/claude-sonnet-5-5");
map.insert("haiku", "anthropic/claude-haiku-5-5");
map.insert("fable", "anthropic/claude-fable-5-1");
map.insert("gemini-pro", "google/gemini-3.1-pro-preview");
map.insert("gemini-3-pro", "google/gemini-3.1-pro-preview");
map
}
pub fn map_model_to_id(model: &str) -> String {
lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
}
#[derive(Debug, Clone, Default)]
pub struct AgentBuildOptions {
pub prompt: Option<String>,
pub prompt_file: Option<String>,
pub system_prompt: Option<String>,
pub model: Option<String>,
pub temperature: Option<f64>,
pub resume: Option<String>,
pub compact_json: bool,
pub use_existing_claude_oauth: bool,
pub read_only: bool,
pub plan_only: bool,
pub approve_each: bool,
pub permission_mode: Option<String>,
pub permission: Option<String>,
pub stream_input: bool,
pub json_input: bool,
pub executable: Option<String>,
pub extra_env: Vec<(String, String)>,
pub unset_env: Vec<String>,
pub extra_args: Vec<String>,
}
pub fn build_args(options: &AgentBuildOptions) -> Vec<String> {
let mut args = Vec::new();
if let Some(resume) = &options.resume {
args.extend(["--resume".into(), resume.clone(), "--no-fork".into()]);
}
let resolved_permission_mode = options.permission_mode.clone().or_else(|| {
if options.approve_each {
Some("ask".to_string())
} else if options.plan_only {
Some("plan".to_string())
} else if options.read_only {
Some("readonly".to_string())
} else {
None
}
});
let is_ask = resolved_permission_mode.as_deref() == Some("ask");
if let Some(mode) = resolved_permission_mode {
args.push("--permission-mode".to_string());
args.push(mode);
}
if is_ask || options.json_input {
args.push("--input-format".to_string());
args.push("stream-json".to_string());
}
if let Some(ref permission) = options.permission {
args.push("--permission".to_string());
args.push(permission.clone());
}
if let Some(ref model) = options.model {
let mapped_model = map_model_to_id(model);
args.push("--model".to_string());
args.push(mapped_model);
}
if let Some(temperature) = options.temperature {
super::launch_options::validate_temperature(temperature)
.unwrap_or_else(|error| panic!("{error}"));
args.push("--temperature".to_string());
args.push(temperature.to_string());
}
if options.compact_json {
args.push("--compact-json".to_string());
}
if options.use_existing_claude_oauth {
args.push("--use-existing-claude-oauth".to_string());
}
args.extend(options.extra_args.clone());
args
}
pub fn build_command(options: &AgentBuildOptions) -> String {
let args = build_args(options);
let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
let executable = options.executable.as_deref().unwrap_or("agent");
let command_head = format!(
"{} {}",
build_command_head(executable, &[], &[], &[]),
args_str.join(" ")
)
.trim()
.to_string();
if options.stream_input {
return command_head;
}
let combined_prompt = match (&options.system_prompt, &options.prompt) {
(Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
(Some(sys), None) => sys.clone(),
(None, Some(prompt)) => prompt.clone(),
(None, None) => String::new(),
};
let input_command = options.prompt_file.as_ref().map_or_else(
|| format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
|prompt_file| format!("cat {}", escape_arg(prompt_file)),
);
format!("{} | {}", input_command, command_head)
.trim()
.to_string()
}
pub fn parse_output(output: &str) -> Vec<Value> {
parse_json_records(output)
}
pub fn extract_session_id(output: &str) -> Option<String> {
let messages = parse_output(output);
for msg in messages {
if let Some(session_id) = msg
.get("session_id")
.or_else(|| msg.get("sessionID"))
.and_then(|v| v.as_str())
{
return Some(session_id.to_string());
}
}
None
}
#[derive(Debug, Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentUsage {
pub input_tokens: u64,
pub output_tokens: u64,
pub reasoning_tokens: u64,
pub cache_read_tokens: u64,
pub cache_write_tokens: u64,
pub total_cost: f64,
pub step_count: u64,
}
pub fn extract_usage(output: &str) -> AgentUsage {
let messages = parse_output(output);
let mut usage = AgentUsage::default();
for msg in messages {
if msg.get("type").and_then(|t| t.as_str()) == Some("step_finish") {
if let Some(part) = msg.get("part") {
usage.step_count += 1;
if let Some(tokens) = part.get("tokens") {
if let Some(input) = tokens.get("input").and_then(|v| v.as_u64()) {
usage.input_tokens += input;
}
if let Some(output) = tokens.get("output").and_then(|v| v.as_u64()) {
usage.output_tokens += output;
}
if let Some(reasoning) = tokens.get("reasoning").and_then(|v| v.as_u64()) {
usage.reasoning_tokens += reasoning;
}
if let Some(cache) = tokens.get("cache") {
if let Some(read) = cache.get("read").and_then(|v| v.as_u64()) {
usage.cache_read_tokens += read;
}
if let Some(write) = cache.get("write").and_then(|v| v.as_u64()) {
usage.cache_write_tokens += write;
}
}
}
if let Some(cost) = part.get("cost").and_then(|v| v.as_f64()) {
usage.total_cost += cost;
}
}
}
}
usage
}
#[derive(Debug, Clone, Default)]
pub struct ErrorResult {
pub has_error: bool,
pub error_type: Option<String>,
pub message: Option<String>,
}
const FATAL_AGENT_LOG_PATTERNS: [&str; 4] = [
"providermodelnotfounderror",
"provideriniterror",
"nosuchmodelerror",
"modelnotfounderror",
];
fn is_fatal_log_text(text: &str) -> bool {
let lower = text.to_lowercase();
FATAL_AGENT_LOG_PATTERNS
.iter()
.any(|pattern| lower.contains(pattern))
|| lower
.find("failed to initialize ")
.is_some_and(|index| lower[index..].contains("model"))
}
pub fn detect_fatal_agent_log_record(record: &Value) -> Option<String> {
if record["type"] != "log" || record["level"] != "error" {
return None;
}
let error = stringify_error_value(&record["error"], MAX_ERROR_TEXT_LENGTH, "");
let message = stringify_error_value(&record["message"], MAX_ERROR_TEXT_LENGTH, "");
if !is_fatal_log_text(&format!("{error} {message}")) {
return None;
}
let hint = stringify_error_value(&record["hint"], MAX_ERROR_TEXT_LENGTH, "");
let hint = if hint.is_empty() {
hint
} else {
format!("hint: {hint}")
};
Some(
[error, message, hint]
.into_iter()
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" — "),
)
}
pub fn is_recoverable_agent_tool_error(record: &Value) -> bool {
crate::usage_limit::is_recoverable_tool_error(record)
}
pub fn detect_errors(output: &str) -> ErrorResult {
let mut detection = ErrorResult::default();
for msg in parse_output(output) {
if let Some(fatal_log) = detect_fatal_agent_log_record(&msg) {
let error_type =
stringify_error_value(&msg["error"], MAX_ERROR_TEXT_LENGTH, "fatal_log");
detection = ErrorResult {
has_error: true,
error_type: Some(error_type),
message: Some(fatal_log),
};
} else if matches!(msg["type"].as_str(), Some("error" | "step_error"))
&& !is_recoverable_agent_tool_error(&msg)
{
let error_type = msg
.pointer("/error/name")
.and_then(Value::as_str)
.filter(|name| !name.is_empty())
.or_else(|| msg["type"].as_str())
.map(ToString::to_string);
detection = ErrorResult {
has_error: true,
error_type,
message: Some(first_error_text(
&[&msg["message"], &msg["error"], &msg["data"]],
"Agent emitted an error event without any details",
)),
};
}
}
detection
}
#[derive(Debug, Clone)]
pub struct AgentTool {
pub name: &'static str,
pub display_name: &'static str,
pub executable: &'static str,
pub supports_json_output: bool,
pub supports_json_input: bool,
pub supports_system_prompt: bool,
pub supports_resume: bool,
pub supports_read_only: bool,
pub supports_ask: bool,
pub default_model: &'static str,
}
impl Default for AgentTool {
fn default() -> Self {
Self {
name: "agent",
display_name: "@link-assistant/agent",
executable: "agent",
supports_json_output: true,
supports_json_input: true, supports_system_prompt: false, supports_resume: true, supports_read_only: true, supports_ask: true, default_model: "nemotron-3-super-free",
}
}
}