curd-editor 0.27.2

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! The assistants themselves: each one a command and the words to add to it
//! for what the panel offers, built in or read from `agents.json`.

use super::*;

/// How an assistant's command prints its answer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Format {
    /// One JSON object per line, the way `claude --output-format
    /// stream-json` does: the answer arrives in pieces, with what it did
    /// in between, and the name of the conversation.
    Claude,
    /// Plain text: whatever it prints is the answer.
    Text,
}

/// An assistant the panel can talk to: a command to run for each
/// question, and the words to add to it for what the panel offers. Words
/// are taken as they are, but for a few that stand for something:
/// `{prompt}`, `{session}`, `{model}` and `{context}`.
///
/// Claude is built in. Others are described in `agents.json` in the same
/// terms, which is all it takes to use another program.
#[derive(Clone, Debug, PartialEq)]
pub struct AgentSpec {
    /// What it is called: in the panel's title and in the list.
    pub name: String,
    /// The command and its arguments for one question.
    pub command: Vec<String>,
    /// Added to carry on the conversation called `{session}`.
    pub resume: Vec<String>,
    /// Added to carry on the last conversation, for commands that do not
    /// say what theirs is called.
    pub carry_on: Vec<String>,
    /// Added to choose the model `{model}`; and the models to offer.
    pub model: Vec<String>,
    pub models: Vec<String>,
    /// Added for each thing the assistant may do: only read; change
    /// files; change files and run commands. With all three empty the
    /// command's own settings decide, and the panel does not ask.
    pub read_only: Vec<String>,
    pub edit: Vec<String>,
    pub run: Vec<String>,
    /// Added to tell it what the editor is showing: `{context}`.
    pub context: Vec<String>,
    pub format: Format,
    /// Commands to sign in and out, and to say who is signed in. They are
    /// the program's own: the editor never sees a password or a token.
    pub login: Vec<String>,
    pub logout: Vec<String>,
    pub status: Vec<String>,
    /// How to get the program, said when it is not there.
    pub install: String,
}

pub(super) fn words(list: &[&str]) -> Vec<String> {
    list.iter().map(|word| word.to_string()).collect()
}

impl AgentSpec {
    /// Claude, through the `claude` command.
    pub fn claude() -> Self {
        Self {
            name: "Claude".into(),
            // With partial messages the answer arrives word by word.
            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(),
        }
    }

    /// Cursor, through its command-line program, which is called `agent`.
    /// It prints nearly what `claude` prints, so its answers arrive the
    /// same way.
    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(),
            // Without `--force` it changes files in the project but runs
            // only the commands its own settings allow.
            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(),
        }
    }

    /// opencode, through its `opencode run` command. What it may do is
    /// decided by its own settings.
    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(),
        }
    }

    /// True if the panel can say what this assistant may do.
    pub fn has_modes(&self) -> bool {
        !(self.read_only.is_empty() && self.edit.is_empty() && self.run.is_empty())
    }

    /// The command line to run for `request`.
    ///
    /// `setting` is the CURD_AGENT environment variable: "off" turns the
    /// panel off, and anything else is used in place of the program's
    /// name (the first word of its command).
    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(),
        };
        // Without a way to pass it apart, what the editor is showing goes
        // in front of the question.
        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 {
            // An empty name: a conversation is under way, but the command
            // never said what it is called.
            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)
    }

    /// Reads one line of what the command printed.
    pub fn parse(&self, line: &str) -> Vec<Update> {
        match self.format {
            Format::Claude => parse(line),
            Format::Text => parse_text(line),
        }
    }
}

/// The command line to ask Claude `request`: see `AgentSpec::command_line`.
#[cfg(test)]
pub fn command_line(setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
    AgentSpec::claude().command_line(setting, request)
}

/// One line printed by a command that answers in plain text. What it
/// printed as an error comes wrapped by `start`, as it does for Claude.
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)))],
    }
}

/// The assistants on offer, and which one the panel starts with: the
/// built-in ones, and those described in `text`, the contents of
/// `agents.json`:
///
/// ```json
/// {
///   "default": "cursor",
///   "agents": {
///     "cursor": {
///       "name": "Cursor",
///       "command": ["cursor-agent", "--print", "{prompt}"],
///       "resume": ["--resume", "{session}"],
///       "login": ["cursor-agent", "login"]
///     }
///   }
/// }
/// ```
///
/// One with the name of a built-in one replaces it. Returns what is
/// wrong with `text`, if something is.
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(),
        };
        // One by the key of a built-in one takes its place.
        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)
}

/// True if the program `name` can be run: it is a path to a file, or a
/// file by that name is in one of the folders of `path` (the PATH
/// variable).
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)))
}

/// `text` (the contents of agents.json, if there is such a file) with
/// `name` set as the assistant to start with, and everything else in it
/// kept. `None` if `text` is not something that can be added to.
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")
}

/// Where `agents.json` is: in `curd` under the folder for settings
/// (`config` is XDG_CONFIG_HOME, if set), or else under `.config` in
/// `home`.
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")
}