use super::*;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Format {
Claude,
Text,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AgentSpec {
pub name: String,
pub command: Vec<String>,
pub resume: Vec<String>,
pub carry_on: Vec<String>,
pub model: Vec<String>,
pub models: Vec<String>,
pub read_only: Vec<String>,
pub edit: Vec<String>,
pub run: Vec<String>,
pub context: Vec<String>,
pub format: Format,
pub login: Vec<String>,
pub logout: Vec<String>,
pub status: Vec<String>,
pub install: String,
}
pub(super) fn words(list: &[&str]) -> Vec<String> {
list.iter().map(|word| word.to_string()).collect()
}
impl AgentSpec {
pub fn claude() -> Self {
Self {
name: "Claude".into(),
command: words(&[
"claude", "--print", "{prompt}", "--output-format", "stream-json", "--verbose",
"--include-partial-messages",
]),
resume: words(&["--resume", "{session}"]),
carry_on: Vec::new(),
model: words(&["--model", "{model}"]),
models: words(&["opus", "sonnet", "haiku"]),
read_only: words(&["--disallowedTools", WRITING_TOOLS]),
edit: words(&["--permission-mode", "acceptEdits"]),
run: words(&["--permission-mode", "acceptEdits", "--allowedTools", "Bash"]),
context: words(&["--append-system-prompt", "{context}"]),
format: Format::Claude,
login: words(&["claude", "auth", "login"]),
logout: words(&["claude", "auth", "logout"]),
status: words(&["claude", "auth", "status"]),
install: "see https://code.claude.com/docs".into(),
}
}
pub fn cursor() -> Self {
Self {
name: "Cursor".into(),
command: words(&["agent", "--print", "{prompt}", "--output-format", "stream-json"]),
resume: words(&["--resume", "{session}"]),
carry_on: Vec::new(),
model: words(&["--model", "{model}"]),
models: Vec::new(),
read_only: words(&["--mode", "ask"]),
edit: Vec::new(),
run: words(&["--force"]),
context: Vec::new(),
format: Format::Claude,
login: words(&["agent", "login"]),
logout: words(&["agent", "logout"]),
status: words(&["agent", "status"]),
install: "curl https://cursor.com/install -fsS | bash".into(),
}
}
pub fn opencode() -> Self {
Self {
name: "opencode".into(),
command: words(&["opencode", "run", "{prompt}"]),
resume: words(&["--session", "{session}"]),
carry_on: words(&["--continue"]),
model: words(&["--model", "{model}"]),
models: Vec::new(),
read_only: Vec::new(),
edit: Vec::new(),
run: Vec::new(),
context: Vec::new(),
format: Format::Text,
login: words(&["opencode", "auth", "login"]),
logout: words(&["opencode", "auth", "logout"]),
status: words(&["opencode", "auth", "list"]),
install: "see https://opencode.ai".into(),
}
}
pub fn has_modes(&self) -> bool {
!(self.read_only.is_empty() && self.edit.is_empty() && self.run.is_empty())
}
pub fn command_line(&self, setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
let program: Vec<String> = match setting.map(str::trim) {
Some("off") => return None,
Some(custom) if !custom.is_empty() => custom.split_whitespace().map(String::from).collect(),
_ => self.command.iter().take(1).cloned().collect(),
};
let prompt = match (self.context.is_empty(), request.context.is_empty()) {
(true, false) => format!("({})\n\n{}", request.context, request.prompt),
_ => request.prompt.to_string(),
};
let fill = |word: &String| {
word.replace("{prompt}", &prompt)
.replace("{session}", request.session.unwrap_or_default())
.replace("{model}", request.model.unwrap_or_default())
.replace("{context}", request.context)
};
let mut line = program;
line.extend(self.command.iter().skip(1).map(fill));
match request.session {
Some("") => line.extend(self.carry_on.iter().map(fill)),
Some(_) => line.extend(self.resume.iter().map(fill)),
None => {}
}
if request.model.is_some() {
line.extend(self.model.iter().map(fill));
}
let mode = match (request.can_edit, request.can_run) {
(false, _) => &self.read_only,
(true, false) => &self.edit,
(true, true) => &self.run,
};
line.extend(mode.iter().map(fill));
if !request.context.is_empty() {
line.extend(self.context.iter().map(fill));
}
Some(line)
}
pub fn parse(&self, line: &str) -> Vec<Update> {
match self.format {
Format::Claude => parse(line),
Format::Text => parse_text(line),
}
}
}
#[cfg(test)]
pub fn command_line(setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
AgentSpec::claude().command_line(setting, request)
}
pub(super) fn parse_text(line: &str) -> Vec<Update> {
match serde_json::from_str::<Value>(line) {
Ok(message) if message["type"].as_str() == Some("stderr") => {
let text = crate::runner::clean(message["text"].as_str().unwrap_or_default());
if text.trim().is_empty() { Vec::new() } else { vec![Update::Problem(text)] }
}
_ => vec![Update::Partial(format!("{}\n", crate::runner::clean(line)))],
}
}
pub fn load_specs(text: Option<&str>) -> (Vec<AgentSpec>, usize, Option<String>) {
let mut specs = vec![AgentSpec::claude(), AgentSpec::cursor(), AgentSpec::opencode()];
let Some(text) = text else {
return (specs, 0, None);
};
let config: Value = match serde_json::from_str(text) {
Ok(config) => config,
Err(error) => return (specs, 0, Some(format!("agents.json: {error}"))),
};
let mut problem = None;
let list = |value: &Value| -> Vec<String> {
let items = value.as_array().into_iter().flatten();
items.filter_map(|item| item.as_str().map(String::from)).collect()
};
for (key, agent) in config["agents"].as_object().into_iter().flatten() {
let command = list(&agent["command"]);
if command.is_empty() {
problem = Some(format!("agents.json: {key} has no command"));
continue;
}
let spec = AgentSpec {
name: agent["name"].as_str().unwrap_or(key).to_string(),
command,
resume: list(&agent["resume"]),
carry_on: list(&agent["continue"]),
model: list(&agent["model"]),
models: list(&agent["models"]),
read_only: list(&agent["read_only"]),
edit: list(&agent["edit"]),
run: list(&agent["run"]),
context: list(&agent["context"]),
format: match agent["format"].as_str() {
Some("claude") => Format::Claude,
_ => Format::Text,
},
login: list(&agent["login"]),
logout: list(&agent["logout"]),
status: list(&agent["status"]),
install: agent["install"].as_str().unwrap_or("see its own documentation").to_string(),
};
let same = |known: &AgentSpec| known.name.eq_ignore_ascii_case(key);
match specs.iter().position(same) {
Some(index) => specs[index] = spec,
None => specs.push(spec),
}
}
let first = config["default"].as_str().and_then(|wanted| {
specs.iter().position(|spec| spec.name.eq_ignore_ascii_case(wanted))
});
(specs, first.unwrap_or(0), problem)
}
pub fn is_installed(name: &str, path: &str) -> bool {
let exists = |file: PathBuf| file.is_file() || file.with_extension("exe").is_file();
if name.contains(['/', '\\']) {
return exists(PathBuf::from(name));
}
std::env::split_paths(path).any(|folder| exists(folder.join(name)))
}
pub fn with_default(text: Option<&str>, name: &str) -> Option<String> {
let mut config: Value = match text.map(str::trim).filter(|text| !text.is_empty()) {
Some(text) => serde_json::from_str(text).ok()?,
None => json!({}),
};
config.as_object_mut()?.insert("default".into(), json!(name));
serde_json::to_string_pretty(&config).ok().map(|text| text + "\n")
}
pub fn config_path(config: Option<&str>, home: &Path) -> PathBuf {
let base = match config {
Some(config) if !config.is_empty() => PathBuf::from(config),
_ => home.join(".config"),
};
base.join("curd").join("agents.json")
}