use crate::streaming::parse_ndjson;
use crate::tools::shell::{build_command_head, escape_arg, escape_single_quotes};
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", "opencode/nemotron-3-super-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("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("sonnet", "anthropic/claude-3-5-sonnet");
map.insert("haiku", "anthropic/claude-3-5-haiku");
map.insert("opus", "anthropic/claude-3-opus");
map.insert("gemini-3-pro", "google/gemini-3-pro");
map
}
pub fn map_model_to_id(model: &str) -> String {
let model_map = get_model_map();
model_map
.get(model)
.map(|s| s.to_string())
.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 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 executable: Option<String>,
pub extra_env: Vec<(String, 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 {
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 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, &options.extra_env, &[]),
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_ndjson(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>,
}
pub fn detect_errors(output: &str) -> ErrorResult {
let messages = parse_output(output);
for msg in messages {
let msg_type = msg.get("type").and_then(|t| t.as_str());
if msg_type == Some("error") || msg_type == Some("step_error") {
return ErrorResult {
has_error: true,
error_type: msg_type.map(|s| s.to_string()),
message: msg
.get("message")
.and_then(|m| m.as_str())
.map(|s| s.to_string())
.or_else(|| Some("Unknown error".to_string())),
};
}
}
ErrorResult::default()
}
#[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",
}
}
}