Let people define custom agent CLIs and start them from the app and the launcher

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 21:26:08 -07:00
1 parent 3e22d53bf5
commit 94063fc0a9
27 files changed
+4025 -95

No files matched your search

+7 -7
View File
@@ -10,7 +10,7 @@ use std::thread;
use serde::Serialize;
use crate::agents::{launch_spec, AgentKind, PermissionMode};
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
use crate::pty_host::{PtyHost, StartOptions};
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -33,7 +33,7 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
pub struct AgentSnapshot {
#[serde(flatten)]
pub state: AgentState,
pub kind: Option<AgentKind>,
pub kind: Option<String>,
pub generation: u64,
/// The running (or last started) agent's permission mode, so the bar's
/// note can name it instead of assuming bypass.
@@ -61,7 +61,7 @@ struct Running {
/// whole, unchanged choice (Task 9.6).
#[derive(Clone)]
struct StartChoice {
kind: AgentKind,
kind: Agent,
model: Option<String>,
effort: Option<String>,
mode: PermissionMode,
@@ -156,13 +156,13 @@ impl AgentManager {
}
}
/// Start `kind` on `model`, `effort` and `mode`, with `brief` (`None` is
/// Start `kind` (built-in or custom) on `model`, `effort` and `mode`, with `brief` (`None` is
/// the placeholder brief: the plain `/plan2code` prompt, which opens the
/// dashboard). A second start while an agent runs is refused. Restart
/// reuses this exact choice, so a later call replaces it for good.
pub fn start(
&self,
kind: AgentKind,
kind: Agent,
model: Option<String>,
effort: Option<String>,
mode: PermissionMode,
@@ -271,7 +271,7 @@ impl Shared {
fn snapshot(&self, inner: &Inner) -> AgentSnapshot {
AgentSnapshot {
state: inner.state.clone(),
kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind),
kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind.id().to_string()),
mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode),
generation: self.generation.load(Ordering::SeqCst),
brief_note: inner.brief_note.clone(),
@@ -287,7 +287,7 @@ impl Shared {
let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?;
let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string());
let mut spec =
launch_spec(choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt);
agent_launch_spec(&choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt);
if let Ok(extra) = self.extra_env.lock() {
spec.env.extend(extra.iter().cloned());
}
+574 -1
View File
@@ -4,7 +4,10 @@
use std::path::{Path, PathBuf};
use serde::Serialize;
use std::collections::HashSet;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// Tests only: run this program instead of the real agent, for any `AgentKind`,
/// so the fake agent stands in for Claude, Devin and Codex.
@@ -76,6 +79,16 @@ impl AgentKind {
AgentKind::Codex => "npm i -g @openai/codex",
}
}
/// The official page to install this agent from. The same links as the
/// launcher's `CLIS` and the overview's Quick Reference: change all together.
pub fn install_url(self) -> &'static str {
match self {
AgentKind::Claude => "https://code.claude.com/docs/en/setup",
AgentKind::Devin => "https://docs.devin.ai/work-with-devin/devin-cli",
AgentKind::Codex => "https://github.com/openai/codex",
}
}
}
/// Whether permission checks run while the agent works. Bypass is always an
@@ -260,6 +273,427 @@ pub fn windows_command(program: &str, args: Vec<String>, path_var: &str) -> (Str
(program.to_string(), args)
}
/* ------------------------------------------------------------ custom agents */
pub const MAX_CUSTOM_AGENTS: usize = 50;
const BUILTIN_IDS: [&str; 3] = ["claude", "devin", "codex"];
const MAX_NAME: usize = 60;
const DEFAULT_CUSTOM_PROMPT: &str = "/plan2code";
/// One model a custom agent offers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomModel {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
/// One entry of `~/.plan2code/agents.json`, with every default filled. The
/// rules live in `src/web-console/agents.mjs`; `scripts/fixtures/agents-cases.json`
/// pins this reader to them. Unknown keys are not kept here (the console is the
/// file's only writer).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomAgent {
pub id: String,
pub name: String,
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default = "default_custom_prompt")]
pub prompt: String,
#[serde(default)]
pub bypass_args: Vec<String>,
#[serde(default = "default_model_args")]
pub model_args: Vec<String>,
#[serde(default)]
pub models: Vec<CustomModel>,
}
fn default_custom_prompt() -> String {
DEFAULT_CUSTOM_PROMPT.to_string()
}
fn default_model_args() -> Vec<String> {
vec!["--model".to_string(), "{model}".to_string()]
}
/// `~/.plan2code/agents.json`.
pub fn agents_file() -> Option<PathBuf> {
Some(std::env::home_dir()?.join(".plan2code").join("agents.json"))
}
/// The custom agents in `file` and the warnings about what was skipped. A
/// missing file is no agents and no warnings; a bad file is no agents and a
/// warning. Never panics.
pub fn load_custom_agents(file: &Path) -> (Vec<CustomAgent>, Vec<String>) {
match std::fs::read_to_string(file) {
Ok(text) => parse_agents_file(&text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Vec::new(), Vec::new()),
Err(e) => (Vec::new(), vec![format!("agents.json could not be read ({e}), so no custom agents are used")]),
}
}
/// `normalizeAgents` for the file's text.
pub fn parse_agents_file(text: &str) -> (Vec<CustomAgent>, Vec<String>) {
let none = |warning: String| (Vec::new(), vec![warning]);
let Ok(file) = serde_json::from_str::<Value>(text) else {
return none("agents.json is not valid JSON, so no custom agents are used".to_string());
};
let Some(file) = file.as_object() else {
return none("agents.json is not an object, so no custom agents are used".to_string());
};
if file.get("schema").and_then(Value::as_f64) != Some(1.0) {
let shown = file.get("schema").map_or("undefined".to_string(), |v| v.to_string());
return none(format!("agents.json has schema {shown}, not 1, so no custom agents are used"));
}
let list = match file.get("agents") {
None | Some(Value::Null) => return (Vec::new(), Vec::new()),
Some(Value::Array(list)) => list,
Some(_) => return none("agents.json: agents is not a list, so no custom agents are used".to_string()),
};
let mut warnings = Vec::new();
let mut list: &[Value] = list;
if list.len() > MAX_CUSTOM_AGENTS {
warnings.push(format!("agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used", list.len()));
list = &list[..MAX_CUSTOM_AGENTS];
}
let mut agents: Vec<CustomAgent> = Vec::new();
let mut ids = HashSet::new();
let mut names = HashSet::new();
for (index, entry) in list.iter().enumerate() {
match check_entry(entry, &ids, &names) {
Ok(agent) => {
ids.insert(agent.id.clone());
names.insert(agent.name.to_lowercase());
agents.push(agent);
}
Err(error) => warnings.push(format!("agents[{index}] skipped: {error}")),
}
}
(agents, warnings)
}
fn valid_agent_id(id: &str) -> bool {
let mut chars = id.chars();
let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
first_ok && id.len() <= 32 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
fn text_list(entry: &Value, field: &str, default: Vec<String>) -> Result<Vec<String>, String> {
match entry.get(field) {
None | Some(Value::Null) => Ok(default),
Some(Value::Array(items)) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| format!("{field} must be a list of text")),
Some(_) => Err(format!("{field} must be a list of text")),
}
}
// One entry against the rules, in the same order as `checkEntry` in agents.mjs.
fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) -> Result<CustomAgent, String> {
let Some(object) = entry.as_object() else { return Err("not an object".to_string()) };
let id = match object.get("id").and_then(Value::as_str) {
Some(id) if !id.is_empty() => id,
_ => return Err("id is missing".to_string()),
};
if BUILTIN_IDS.contains(&id) {
return Err(format!("id \"{id}\" belongs to a built-in agent"));
}
if !valid_agent_id(id) {
return Err(format!(
"id \"{id}\" must be 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit"
));
}
if ids.contains(id) {
return Err(format!("id \"{id}\" is already used"));
}
let name = object.get("name").and_then(Value::as_str).map_or("", str::trim);
if name.is_empty() {
return Err("name is missing".to_string());
}
if name.encode_utf16().count() > MAX_NAME {
return Err(format!("name is longer than {MAX_NAME} characters"));
}
if names.contains(&name.to_lowercase()) {
return Err(format!("name \"{name}\" is already used"));
}
let command = object.get("command").and_then(Value::as_str).map_or("", str::trim);
if command.is_empty() {
return Err("command is missing".to_string());
}
let args = text_list(entry, "args", Vec::new())?;
let bypass_args = text_list(entry, "bypassArgs", Vec::new())?;
let model_args = text_list(entry, "modelArgs", default_model_args())?;
let prompt = match object.get("prompt") {
None | Some(Value::Null) => default_custom_prompt(),
Some(Value::String(text)) => text.clone(),
Some(_) => return Err("prompt must be text".to_string()),
};
let mut models: Vec<CustomModel> = Vec::new();
match object.get("models") {
None | Some(Value::Null) => {}
Some(Value::Array(items)) => {
let mut seen = HashSet::new();
for item in items {
let Some(model_id) = item.get("id").and_then(Value::as_str) else {
return Err("every model in models needs an id".to_string());
};
let model_id = model_id.trim();
if model_id.is_empty() || !seen.insert(model_id.to_string()) {
continue;
}
let label = item.get("label").and_then(Value::as_str).map(str::trim).filter(|l| !l.is_empty());
models.push(CustomModel { id: model_id.to_string(), label: label.map(str::to_string) });
}
}
Some(_) => return Err("models must be a list".to_string()),
}
Ok(CustomAgent {
id: id.to_string(),
name: name.to_string(),
command: command.to_string(),
args,
prompt,
bypass_args,
model_args,
models,
})
}
/// The arguments that start a custom agent, in order (`buildArgs` in
/// agents.mjs): `args` with `{prompt}` filled (the prompt appended when no
/// argument holds it), then `model_args` when a model is chosen, then
/// `bypass_args` when checks are off. `prompt` defaults to the entry's own; a
/// blank one drops an argument that is exactly `{prompt}`. Plain text only.
pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Option<&str>, bypass: bool) -> Vec<String> {
let text = prompt.unwrap_or(&agent.prompt);
let blank = text.trim().is_empty();
let mut out = Vec::new();
let mut placed = false;
for arg in &agent.args {
if !arg.contains("{prompt}") {
out.push(arg.clone());
continue;
}
placed = true;
if arg == "{prompt}" && blank {
continue;
}
out.push(arg.replace("{prompt}", text));
}
if !placed && !blank {
out.push(text.to_string());
}
if let Some(model) = model.filter(|m| !m.is_empty()) {
out.extend(agent.model_args.iter().map(|arg| arg.replace("{model}", model)));
}
if bypass {
out.extend(agent.bypass_args.iter().cloned());
}
out
}
/// An agent the app can run: one of the three built-ins or a custom entry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Agent {
Builtin(AgentKind),
Custom(CustomAgent),
}
impl Agent {
pub fn id(&self) -> &str {
match self {
Agent::Builtin(kind) => kind.id(),
Agent::Custom(agent) => &agent.id,
}
}
pub fn label(&self) -> &str {
match self {
Agent::Builtin(kind) => kind.label(),
Agent::Custom(agent) => &agent.name,
}
}
/// What a first start types.
pub fn default_prompt(&self) -> &str {
match self {
Agent::Builtin(kind) => kind.default_prompt(),
Agent::Custom(agent) => &agent.prompt,
}
}
/// A custom agent has no effort of its own.
pub fn has_effort(&self) -> bool {
matches!(self, Agent::Builtin(kind) if kind.has_effort())
}
/// Where this agent's program runs from, or `None` when it cannot be run.
/// `PLAN2CODE_APP_AGENT_BIN` still overrides the program (tests only).
pub fn installed_at(&self) -> Option<PathBuf> {
match self {
Agent::Builtin(kind) => installed_at(*kind),
Agent::Custom(agent) => {
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
let command = bin.as_deref().unwrap_or(&agent.command);
resolve_command(command, crate::node_check::resolved_path())
}
}
}
}
/// The agent named `id`: a built-in first, else an entry of `agents.json`.
pub fn find_agent(id: &str) -> Option<Agent> {
find_agent_in(id, agents_file().as_deref())
}
/// `find_agent` against a given agents file (`None`: built-ins only).
pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
if let Some(kind) = AgentKind::from_id(id) {
return Some(Agent::Builtin(kind));
}
let (agents, _) = load_custom_agents(file?);
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
}
/// Every custom agent in `~/.plan2code/agents.json`, read afresh.
pub fn custom_agents() -> Vec<CustomAgent> {
agents_file().map(|file| load_custom_agents(&file).0).unwrap_or_default()
}
fn clean_command(command: &str) -> &str {
let command = command.trim();
command.strip_prefix('"').and_then(|c| c.strip_suffix('"')).unwrap_or(command)
}
fn has_separator(command: &str, windows: bool) -> bool {
command.contains('/') || (windows && command.contains('\\'))
}
// A file as written, or on Windows with an extension a program can have.
fn file_with_extensions(base: PathBuf) -> Option<PathBuf> {
if base.is_file() {
return Some(base);
}
if cfg!(windows) && base.extension().is_none() {
for ext in ["exe", "cmd", "bat"] {
let mut candidate = base.clone().into_os_string();
candidate.push(format!(".{ext}"));
let candidate = PathBuf::from(candidate);
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
/// Where `command` runs from: a full path is checked as a file, a bare name is
/// looked for on `path_var`. Never runs anything.
fn resolve_command(command: &str, path_var: &str) -> Option<PathBuf> {
let command = clean_command(command);
if command.is_empty() {
return None;
}
if has_separator(command, cfg!(windows)) {
return file_with_extensions(PathBuf::from(command));
}
if let Some(found) = find_on_path(command, path_var) {
return Some(found);
}
// A name that already carries its extension (`tool.cmd`).
path_var
.split(if cfg!(windows) { ';' } else { ':' })
.filter(|dir| !dir.is_empty())
.map(|dir| Path::new(dir.trim_matches('"')).join(command))
.find(|candidate| candidate.is_file())
}
/// How to start `agent` in `folder`: a built-in exactly as `launch_spec`, a
/// custom agent from its resolved command and `build_custom_args` (bypass when
/// `mode` is `Bypass`; effort does not apply).
pub fn agent_launch_spec(
agent: &Agent,
folder: &Path,
model: Option<&str>,
effort: Option<&str>,
mode: PermissionMode,
prompt: &str,
) -> LaunchSpec {
match agent {
Agent::Builtin(kind) => launch_spec(*kind, folder, model, effort, mode, prompt),
Agent::Custom(custom) => {
if let Some(bin) = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()) {
return LaunchSpec { program: bin, args: vec![], env: vec![], cwd: folder.to_path_buf() };
}
let resolved = agent.installed_at();
custom_launch_spec(
custom,
resolved.as_deref(),
folder,
model,
mode,
prompt,
crate::node_check::resolved_path(),
cfg!(windows),
)
}
}
}
// `agent_launch_spec` for a custom agent, with the lookup result and the
// platform passed in so the Windows rules can be tested anywhere.
#[allow(clippy::too_many_arguments)]
fn custom_launch_spec(
custom: &CustomAgent,
resolved: Option<&Path>,
folder: &Path,
model: Option<&str>,
mode: PermissionMode,
prompt: &str,
base_path: &str,
windows: bool,
) -> LaunchSpec {
let mut args = build_custom_args(custom, Some(prompt), model, mode == PermissionMode::Bypass);
let mut path = base_path.to_string();
let mut program =
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
if windows {
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
let file_name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// A full path may have a space in its folder, and `cmd /c` mangles a
// command line that starts with a quote: run the bare file name with
// its folder at the front of the child's PATH instead.
if has_separator(clean_command(&custom.command), true) {
if let Some(dir) = file.parent() {
path = format!("{};{}", dir.to_string_lossy(), base_path);
}
}
let mut wrapped = vec!["/c".to_string(), file_name];
wrapped.append(&mut args);
args = wrapped;
program = "cmd".to_string();
}
}
LaunchSpec { program, args, env: vec![("PATH".to_string(), path)], cwd: folder.to_path_buf() }
}
/// The page a built-in agent installs from; any other id is an error.
pub fn install_page_url(id: &str) -> Result<&'static str, String> {
AgentKind::from_id(id).map(AgentKind::install_url).ok_or_else(|| format!("no install page for agent: {id}"))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -470,4 +904,143 @@ mod tests {
}
assert_eq!(AgentKind::from_id("nope"), None);
}
/* ------------------------------------------------------ custom agents */
const CASES: &str = include_str!("../../../scripts/fixtures/agents-cases.json");
fn cases() -> Value {
serde_json::from_str(CASES).unwrap()
}
#[test]
fn the_fixture_files_cases_read_the_same() {
let cases = cases();
let files = cases["files"].as_array().unwrap();
assert!(files.len() >= 20);
for case in files {
let name = case["name"].as_str().unwrap();
let (agents, warnings) = match case["raw"].as_str() {
Some(raw) => parse_agents_file(raw),
None => (Vec::new(), Vec::new()),
};
let want: Vec<CustomAgent> = serde_json::from_value(case["agents"].clone()).unwrap();
assert_eq!(agents, want, "{name}");
let parts = case["warnings"].as_array().unwrap();
if parts.is_empty() {
assert!(warnings.is_empty(), "{name}: {warnings:?}");
}
for part in parts {
let part = part.as_str().unwrap();
assert!(warnings.iter().any(|w| w.contains(part)), "{name}: no warning names {part}: {warnings:?}");
}
}
}
#[test]
fn the_fixture_build_args_cases_build_the_same() {
let cases = cases();
let list = cases["buildArgs"].as_array().unwrap();
assert!(list.len() >= 10);
for case in list {
let name = case["name"].as_str().unwrap();
let entry: CustomAgent = serde_json::from_value(case["entry"].clone()).unwrap();
let options = &case["options"];
let got = build_custom_args(
&entry,
options["prompt"].as_str(),
options["model"].as_str(),
options["bypass"].as_bool().unwrap_or(false),
);
let want: Vec<String> = serde_json::from_value(case["args"].clone()).unwrap();
assert_eq!(got, want, "{name}");
}
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
const GOOSE: &str = r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose","args":["{prompt}"],"bypassArgs":["--yes"]}]}"#;
#[test]
fn a_missing_file_is_empty_and_a_bad_one_warns() {
let dir = temp_dir("load");
assert_eq!(load_custom_agents(&dir.join("agents.json")), (Vec::new(), Vec::new()));
std::fs::write(dir.join("agents.json"), "{ nope").unwrap();
let (agents, warnings) = load_custom_agents(&dir.join("agents.json"));
assert!(agents.is_empty() && warnings.len() == 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn find_agent_prefers_built_ins_then_the_file() {
let dir = temp_dir("find");
let file = dir.join("agents.json");
std::fs::write(&file, GOOSE).unwrap();
assert_eq!(find_agent_in("claude", Some(&file)), Some(Agent::Builtin(AgentKind::Claude)));
let goose = find_agent_in("goose", Some(&file)).unwrap();
assert_eq!((goose.id(), goose.label(), goose.has_effort(), goose.default_prompt()), ("goose", "Goose", false, "/plan2code"));
assert_eq!(find_agent_in("goose", None), None);
assert_eq!(find_agent_in("nope", Some(&file)), None);
let _ = std::fs::remove_dir_all(&dir);
}
fn goose() -> CustomAgent {
parse_agents_file(GOOSE).0.remove(0)
}
#[test]
fn a_custom_launch_spec_has_its_program_and_arguments() {
let bin = Path::new("tools").join("goose");
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), None, PermissionMode::Checked, "/plan2code", "P", false);
assert_eq!(spec.program, bin.to_string_lossy());
assert_eq!(spec.args, ["/plan2code"]);
assert_eq!(spec.env, [("PATH".to_string(), "P".to_string())]);
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), Some("m"), PermissionMode::Bypass, "/plan2code", "P", false);
assert_eq!(spec.args, ["/plan2code", "--model", "m", "--yes"]);
let spec = custom_launch_spec(&goose(), None, &folder(), None, PermissionMode::Checked, "", "P", false);
assert_eq!((spec.program.as_str(), spec.args.len()), ("goose", 0));
}
#[test]
fn a_windows_cmd_runs_through_cmd_with_its_folder_on_path_for_a_full_path() {
let mut full = goose();
full.command = "C:\\with space\\goose.cmd".to_string();
let found = Path::new("C:\\with space").join("goose.cmd");
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!(spec.program, "cmd");
assert_eq!(spec.args, ["/c", "goose.cmd", "/p"]);
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
// A bare name keeps the plain PATH.
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
}
#[cfg(windows)]
#[test]
fn a_full_path_cmd_in_a_spaced_folder_resolves_and_wraps() {
let dir = temp_dir("spaced").join("with space");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("goose.cmd"), "@echo off").unwrap();
let mut agent = goose();
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((spec.program.as_str(), spec.args[1].as_str()), ("cmd", "goose.cmd"));
assert!(spec.env[0].1.starts_with(&dir.to_string_lossy().to_string()));
let _ = std::fs::remove_dir_all(dir.parent().unwrap());
}
#[test]
fn install_pages_are_for_built_ins_only() {
assert_eq!(install_page_url("codex").unwrap(), "https://github.com/openai/codex");
assert!(install_page_url("goose").is_err());
for kind in AgentKind::ALL {
assert!(kind.install_url().starts_with("https://"));
}
}
}
+38 -11
View File
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::agents::AgentKind;
use crate::agents;
/// Where the project folder came from, in the order it is tried.
#[derive(Clone, Copy, Serialize)]
@@ -45,10 +45,11 @@ fn remembered_folder() -> Option<PathBuf> {
dir.is_dir().then_some(dir)
}
/// The agent the launcher last ran. The bar's picker starts on it until the
/// app has a choice of its own (`settings.rs`).
pub fn remembered_agent() -> Option<AgentKind> {
AgentKind::from_id(read_launcher().get("lastCli")?.as_str()?)
/// The id of the agent the launcher last ran (it may be a custom one). The
/// bar's picker starts on it until the app has a choice of its own
/// (`settings.rs`); a caller ignores an id that no longer resolves.
pub fn remembered_agent() -> Option<String> {
Some(read_launcher().get("lastCli")?.as_str()?.to_string()).filter(|id| !id.is_empty())
}
/// `--project <dir>`, `--project=<dir>` or the first bare argument: the folder
@@ -85,7 +86,8 @@ fn argument_folder(args: &[String]) -> Option<PathBuf> {
/// an agent, since a model name belongs to one agent.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LaunchChoice {
pub agent: Option<AgentKind>,
/// An agent id, built-in or custom; resolved at use through `agents::find_agent`.
pub agent: Option<String>,
pub model: Option<String>,
}
@@ -106,8 +108,15 @@ fn flag_value(args: &[String], flag: &str) -> Option<String> {
}
pub fn launch_choice(args: &[String]) -> LaunchChoice {
let agent = flag_value(args, "--agent").and_then(|id| AgentKind::from_id(&id.to_lowercase()));
let model = agent.and_then(|_| flag_value(args, "--model"));
launch_choice_in(args, agents::agents_file().as_deref())
}
/// `launch_choice` with the custom agents read from `agents_file` (`None`: built-ins only).
pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchChoice {
let agent = flag_value(args, "--agent")
.map(|id| id.to_lowercase())
.filter(|id| agents::find_agent_in(id, agents_file).is_some());
let model = agent.as_ref().and_then(|_| flag_value(args, "--model"));
LaunchChoice { agent, model }
}
@@ -140,6 +149,11 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
#[cfg(test)]
mod tests {
use super::*;
use crate::agents::AgentKind;
fn launch_choice(args: &[String]) -> LaunchChoice {
launch_choice_in(args, None)
}
fn args(list: &[&str]) -> Vec<String> {
std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect()
@@ -147,7 +161,7 @@ mod tests {
#[test]
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
let want = LaunchChoice { agent: Some(AgentKind::Codex), model: Some("gpt-5".into()) };
let want = LaunchChoice { agent: Some(AgentKind::Codex.id().to_string()), model: Some("gpt-5".into()) };
assert_eq!(launch_choice(&args(&["--project", ".", "--agent", "codex", "--model", "gpt-5"])), want);
assert_eq!(launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), want);
assert_eq!(launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), want);
@@ -157,7 +171,7 @@ mod tests {
fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() {
assert_eq!(
launch_choice(&args(&["--agent", "claude"])),
LaunchChoice { agent: Some(AgentKind::Claude), model: None }
LaunchChoice { agent: Some(AgentKind::Claude.id().to_string()), model: None }
);
assert_eq!(launch_choice(&args(&["--model", "opus"])), LaunchChoice::default());
}
@@ -171,10 +185,23 @@ mod tests {
assert_eq!(launch_choice(&args(&[])), LaunchChoice::default());
assert_eq!(
launch_choice(&args(&["--agent", "devin", "--model"])),
LaunchChoice { agent: Some(AgentKind::Devin), model: None }
LaunchChoice { agent: Some(AgentKind::Devin.id().to_string()), model: None }
);
}
#[test]
fn a_custom_agent_id_is_accepted_when_the_file_names_it() {
let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("agents.json");
std::fs::write(&file, r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#).unwrap();
let want = LaunchChoice { agent: Some("goose".into()), model: Some("m1".into()) };
assert_eq!(launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)), want);
assert_eq!(launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)), LaunchChoice::default());
assert_eq!(launch_choice_in(&args(&["--agent", "goose"]), None), LaunchChoice::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_agent_and_model_values_are_never_taken_for_a_folder() {
// A folder named like the agent exists right here, so a bare-argument reading would pick it.
+13 -11
View File
@@ -4,8 +4,6 @@
use std::path::{Path, PathBuf};
use crate::agents::AgentKind;
const LAST_AGENT_KEY: &str = "lastAgent";
const TERM_DOCK_KEY: &str = "termDock";
const TERM_FRACTION_KEY: &str = "termFraction";
@@ -38,15 +36,16 @@ fn read(file: &Path) -> serde_json::Map<String, serde_json::Value> {
.unwrap_or_default()
}
/// The agent saved in `file`, when it still names one the app can run.
pub fn load_last_agent(file: &Path) -> Option<AgentKind> {
AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?)
/// The agent id saved in `file` (built-in or custom). Whether it still
/// resolves is the caller's check (`agents::find_agent`).
pub fn load_last_agent(file: &Path) -> Option<String> {
Some(read(file).get(LAST_AGENT_KEY)?.as_str()?.to_string()).filter(|id| !id.is_empty())
}
/// Save the pick, keeping any other key the file holds.
pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> {
pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> {
let mut settings = read(file);
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(kind.id().to_string()));
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(id.to_string()));
write(file, settings)
}
@@ -129,18 +128,21 @@ mod tests {
let file = temp_file("round-trip");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
save_last_agent(&file, AgentKind::Devin).unwrap();
assert_eq!(load_last_agent(&file), Some(AgentKind::Devin));
save_last_agent(&file, "devin").unwrap();
assert_eq!(load_last_agent(&file), Some("devin".to_string()));
save_last_agent(&file, "goose").unwrap();
assert_eq!(load_last_agent(&file), Some("goose".to_string()), "a custom id round-trips");
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn an_unknown_agent_is_ignored() {
fn an_id_is_returned_as_stored_and_the_caller_checks_it() {
let file = temp_file("unknown");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"lastAgent": "nope"}"#).unwrap();
assert_eq!(load_last_agent(&file), None);
assert_eq!(load_last_agent(&file), Some("nope".to_string()));
assert!(crate::agents::find_agent_in("nope", None).is_none());
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}