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

+6 -1
View File
@@ -97,6 +97,10 @@ plan2code/
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
### Agents file
`~/.plan2code/agents.json` holds the person's custom agent CLIs (`{ "schema": 1, "agents": [...] }`). The web console is its only writer (User Preferences → Agents, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. A bad file or entry is skipped with a warning, never a crash. Until the feature is finalized, the rules are written out in `specs/agent-setup-and-taskbar-attention/PLAN-DRAFT-20261025.md` section 4.4.
## Workflow Prompts (in `src/`)
| File | Step | Purpose |
@@ -197,6 +201,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see Agents file above), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
@@ -291,7 +296,7 @@ Key design points:
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
+1 -1
View File
@@ -8,7 +8,7 @@
"scripts": {
"prepare": "husky",
"build:skills": "node install.js --build-skills",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test --test-concurrency=8 scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test --test-concurrency=8 scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
},
"devDependencies": {
"husky": "^9.0.0",
+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());
}
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, Once};
use std::time::{Duration, Instant};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
use plan2code_app_lib::agents::{AgentKind, PermissionMode, AGENT_BIN_ENV};
use plan2code_app_lib::agents::{Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
mod common;
use common::process_alive;
@@ -99,7 +99,7 @@ impl Harness {
}
fn start_and_wait_ready(&mut self) {
self.manager.start(AgentKind::Claude, None, None, PermissionMode::Bypass, None).expect("start the fake agent");
self.manager.start(Agent::Builtin(AgentKind::Claude), None, None, PermissionMode::Bypass, None).expect("start the fake agent");
self.wait_for_output(READY, 1);
}
@@ -118,7 +118,7 @@ fn a_second_start_while_running_is_refused() {
h.start_and_wait_ready();
let generation = h.manager.snapshot().generation;
let refused = h.manager.start(AgentKind::Devin, None, None, PermissionMode::Bypass, None);
let refused = h.manager.start(Agent::Builtin(AgentKind::Devin), None, None, PermissionMode::Bypass, None);
assert!(refused.is_err(), "a second start must be refused");
let after = h.manager.snapshot();
assert_eq!(after.state, AgentState::Running);
@@ -130,18 +130,18 @@ fn a_second_start_while_running_is_refused() {
fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
let mut h = Harness::new();
h.manager
.start(AgentKind::Codex, Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None)
.start(Agent::Builtin(AgentKind::Codex), Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None)
.expect("start the fake agent");
h.wait_for_output(READY, 1);
let before = h.manager.snapshot();
assert_eq!(before.kind, Some(AgentKind::Codex));
assert_eq!(before.kind, Some("codex".to_string()));
assert_eq!(before.mode, Some(PermissionMode::Checked));
assert_eq!(h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string())));
h.manager.restart().unwrap();
h.wait_for_output(READY, 2);
let after = h.manager.snapshot();
assert_eq!(after.kind, Some(AgentKind::Codex), "restart must keep the same agent");
assert_eq!(after.kind, Some("codex".to_string()), "restart must keep the same agent");
assert_eq!(after.mode, Some(PermissionMode::Checked), "restart must keep the same permission mode");
assert_eq!(
h.manager.model_and_effort(),
+112 -16
View File
@@ -2,7 +2,7 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor } from './meter.js';
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
@@ -27,6 +27,7 @@ const launchCard = document.getElementById('launch-card');
const launchAgentEl = document.getElementById('launch-agent');
const launchMissingEl = document.getElementById('launch-missing');
const launchModelEl = document.getElementById('launch-model');
const launchModelListEl = document.getElementById('launch-model-list');
const launchEffortRow = document.getElementById('launch-effort-row');
const launchEffortEl = document.getElementById('launch-effort');
const launchBypassEl = document.getElementById('launch-bypass');
@@ -63,7 +64,10 @@ const MAXIMIZED_PANE = 0.80;
const SMALL_PANE = 0.15;
const QUIET_BADGE_MS = 10000;
const AGENT_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' };
// Only the bar's fallback, before (or without) agent_availability: the launch
// card and the bar otherwise read each agent's label from that list.
const FALLBACK_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' };
const agentLabel = (id) => (agentAvailability[id] && agentAvailability[id].label) || FALLBACK_LABELS[id] || id || '';
// Devin's model ids already carry their effort (`swe-2-high`); only these two
// take a separate effort, at the levels their own CLI documents.
const EFFORT_OPTIONS = {
@@ -109,7 +113,7 @@ function applyAgentState(next, { skipReset } = {}) {
lastOutputAt = Date.now();
}
agent = next;
const label = AGENT_LABELS[agent.kind] || '';
const label = agentLabel(agent.kind);
const active = agentActive();
const ended = agent.state === 'ended';
@@ -259,19 +263,94 @@ function confirmRestart(onYes) {
}
// What the launch card offers for each agent: whether its CLI was found on
// PATH (else how to install it) and whether it takes its own effort.
// PATH (else how to install it) and whether it takes its own effort. The list
// keeps the order Rust sent (built-ins, then custom agents); the map is by id.
let agentList = [];
let agentAvailability = {};
async function loadAgentAvailability() {
try {
const list = await invoke('agent_availability');
agentAvailability = Object.fromEntries(list.map((entry) => [entry.id, entry]));
agentList = await invoke('agent_availability');
agentAvailability = Object.fromEntries(agentList.map((entry) => [entry.id, entry]));
} catch {
// Nothing to show is not a reason to block the card: Start just tries it.
agentList = [];
agentAvailability = {};
}
}
// The launch card's agent choices, from the availability list. With nothing
// to list (the check failed) the fixed options in index.html stay as they are.
function populateAgentSelect(selected) {
if (agentList.length === 0) return;
launchAgentEl.replaceChildren(
...agentList.map((entry) => {
const option = document.createElement('option');
option.value = entry.id;
option.textContent = entry.label || entry.id;
return option;
})
);
if (selected) launchAgentEl.value = selected;
}
// Pick the agent to start on and show the card's state for it.
function applyDefaultAgent(remembered) {
populateAgentSelect(pickDefaultAgent(agentList, remembered));
refreshLaunchCard();
}
// A button that opens a built-in agent's install page in the browser.
function installPageButton(id) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'agent-link';
button.textContent = 'Install page';
button.onclick = () => {
invoke('open_install_page', { id }).catch((error) => {
setAgentStatus(`Could not open the install page: ${error}`, { error: true });
});
};
return button;
}
// Shown when no agent CLI is installed, in the first-run checklist and on the
// launch card: what an agent CLI is, each built-in's install command and page,
// and a way to look again once one is installed.
function noAgentExplainer() {
const box = document.createElement('div');
box.className = 'agent-explainer';
const intro = document.createElement('p');
intro.className = 'agent-explainer';
intro.textContent = 'An agent CLI is the AI coding assistant Plan2Code runs for you in its terminal. None was found on PATH. Install one of these:';
const list = document.createElement('ul');
for (const entry of agentList.filter((a) => !a.custom)) {
const item = document.createElement('li');
item.append(`${entry.label}: `);
const code = document.createElement('code');
code.textContent = entry.installHint || '';
item.append(code, installPageButton(entry.id));
list.append(item);
}
const other = document.createElement('p');
other.className = 'agent-explainer';
other.textContent = 'Already use another agent CLI? Add it in User Preferences under Agents.';
const check = document.createElement('button');
check.type = 'button';
check.textContent = 'Check again';
check.onclick = checkAgentsAgain;
box.append(intro, list, other, check);
return box;
}
// Re-read the agents from disk (a CLI installed or a custom agent added since),
// then redraw whatever shows them and pick the default again.
async function checkAgentsAgain() {
await loadAgentAvailability();
applyDefaultAgent((appState && appState.lastAgent) || launchAgentEl.value);
if (!firstRunEl.hidden && appState) renderFirstRun(appState);
}
function refreshLaunchCard() {
const kind = launchAgentEl.value;
const info = agentAvailability[kind];
@@ -280,13 +359,28 @@ function refreshLaunchCard() {
launchMissingEl.hidden = installed;
launchMissingEl.replaceChildren();
if (!installed) {
const label = (info && info.label) || AGENT_LABELS[kind] || kind;
launchMissingEl.append(`${label} was not found on PATH. Install it: `);
const code = document.createElement('code');
code.textContent = (info && info.installHint) || '';
launchMissingEl.append(code);
if (!agentList.some((a) => a.installed)) {
launchMissingEl.append(noAgentExplainer());
} else {
launchMissingEl.append(`${agentLabel(kind)} was not found on PATH.`);
if (info && !info.custom) {
launchMissingEl.append(' Install it: ');
const code = document.createElement('code');
code.textContent = info.installHint || '';
launchMissingEl.append(code, installPageButton(kind));
}
}
}
const levels = EFFORT_OPTIONS[kind] || [];
// A custom agent has no separate effort, and offers its models as
// suggestions in the (still free-text) model field.
launchModelListEl.replaceChildren();
for (const model of (info && info.custom && info.models) || []) {
const option = document.createElement('option');
option.value = model.id;
if (model.label) option.label = model.label;
launchModelListEl.append(option);
}
const levels = info && info.custom ? [] : EFFORT_OPTIONS[kind] || [];
launchEffortRow.hidden = levels.length === 0;
launchEffortEl.replaceChildren();
const def = document.createElement('option');
@@ -350,11 +444,13 @@ function renderFirstRun(state) {
const nodeDetail = `${state.nodeVersion || 'found'} (18 or newer)${state.nodeBinary ? ` — ${state.nodeBinary}` : ''}`;
firstRunListEl.append(firstRunRow(true, 'Node.js', nodeDetail));
const agentsKnown = Object.values(agentAvailability);
const agentsKnown = agentList;
const anyAgentInstalled = agentsKnown.length === 0 || agentsKnown.some((a) => a.installed);
const agentsDetail = document.createElement('span');
if (agentsKnown.length === 0) {
agentsDetail.textContent = 'Could not check.';
} else if (!anyAgentInstalled) {
agentsDetail.append(noAgentExplainer());
} else {
agentsKnown.forEach((a, i) => {
if (i > 0) agentsDetail.append(', ');
@@ -397,7 +493,8 @@ async function startAgent(event) {
if (event) event.preventDefault();
const kind = launchAgentEl.value;
const model = launchModelEl.value.trim() || null;
const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
const info = agentAvailability[kind];
const effort = !(info && info.custom) && (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
setAgentStatus('');
showState('Waiting for the agent to open the dashboard');
@@ -929,7 +1026,6 @@ async function main() {
return;
}
appState = state;
if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent;
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
if (state.termPanel) {
paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom';
@@ -945,7 +1041,7 @@ async function main() {
}
applyPaneLayout();
await loadAgentAvailability();
refreshLaunchCard();
applyDefaultAgent(state.lastAgent);
setInterval(updateBadge, BADGE_POLL_MS);
checkVersions();
+7 -1
View File
@@ -146,6 +146,11 @@
}
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-missing code { color: #ddd; }
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
.agent-explainer code { color: #ddd; }
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
#launch-effort-row[hidden] { display: none; }
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
#launch-bypass-row input { margin: 0; }
@@ -292,7 +297,8 @@
</select>
<p id="launch-missing" hidden></p>
<label for="launch-model">Model</label>
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off">
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off" list="launch-model-list">
<datalist id="launch-model-list"></datalist>
<div id="launch-effort-row">
<label for="launch-effort">Effort</label>
<select id="launch-effort"></select>
+21 -1
View File
@@ -17,7 +17,8 @@ export const NEXT_STEP_LABELS = {
* text as a queued message while its turn is busy, and the button only shows
* once the agent stopped checking in with the console, so by then the turn is
* stuck and the queued word would never send by itself: for it, the send-now
* chord (ctrl+x ctrl+s) follows.
* chord (ctrl+x ctrl+s) follows. Any id it does not know (a custom agent)
* gets the plain word and Enter.
*/
export function continueKeys(kind) {
const keys = ['continue', '\r'];
@@ -25,6 +26,25 @@ export function continueKeys(kind) {
return keys;
}
/**
* Which agent the launch card starts on, from `agent_availability`'s list
* (built-ins first, then custom agents): the remembered id when it is
* installed, else the first installed built-in, else the first installed
* custom agent, else the remembered id or the first entry, so the card's
* missing-agent line explains what is wrong instead of picking silently.
*/
export function pickDefaultAgent(availability, remembered) {
const list = Array.isArray(availability) ? availability : [];
const rememberedEntry = list.find((a) => a.id === remembered);
if (rememberedEntry && rememberedEntry.installed) return remembered;
const builtIn = list.find((a) => a.installed && !a.custom);
if (builtIn) return builtIn.id;
const custom = list.find((a) => a.installed && a.custom);
if (custom) return custom.id;
if (remembered) return remembered;
return list.length > 0 ? list[0].id : null;
}
/**
* What the right end of the bar offers, most pressing first: the bar shows
* the first step (short text plus its one button) and counts the rest as
File diff suppressed because it is too large. Load diff
+132
View File
@@ -0,0 +1,132 @@
// The rules of ~/.plan2code/agents.json, console side (src/web-console/agents.mjs),
// against the shared cases every reader's tests load (scripts/fixtures/agents-cases.json),
// plus what only the console does: finding a command and checking a save.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { MAX_AGENTS, buildArgs, makeId, normalizeAgents, resolveCommand, validateForSave } from "../src/web-console/agents.mjs";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agents-cases.json"), "utf8"));
const WINDOWS = process.platform === "win32";
for (const c of CASES.files) {
test(`agents file: ${c.name}`, () => {
const { agents, warnings } = normalizeAgents(c.raw);
assert.deepEqual(agents, c.agents);
if (!c.warnings.length) assert.deepEqual(warnings, []);
for (const part of c.warnings) {
assert.ok(warnings.some((w) => w.includes(part)), `a warning names "${part}": ${JSON.stringify(warnings)}`);
}
});
}
for (const c of CASES.buildArgs) {
test(`buildArgs: ${c.name}`, () => {
assert.deepEqual(buildArgs(c.entry, c.options), c.args);
});
}
for (const c of CASES.ids) {
test(`makeId: ${c.name}`, () => {
assert.equal(makeId(c.input, c.taken), c.id);
});
}
test("normalizeAgents takes the parsed file too, and never throws on odd input", () => {
assert.deepEqual(normalizeAgents({ schema: 1, agents: [{ id: "goose", name: "Goose", command: "goose" }] }).agents.map((a) => a.id), ["goose"]);
for (const odd of [0, true, "null", "42", "\"text\"", [], () => {}]) {
assert.deepEqual(normalizeAgents(odd).agents, [], String(odd));
}
});
test("the fixture covers every rule it promises", () => {
assert.ok(CASES.files.length >= 20 && CASES.buildArgs.length >= 10 && CASES.ids.length >= 8);
const many = CASES.files.find((c) => c.name.startsWith("51 entries"));
assert.equal(many.agents.length, MAX_AGENTS);
});
/* ------------------------------------------------------- resolveCommand */
function fakePath(t) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const bin = path.join(base, "bin");
const spaced = path.join(base, "with space");
fs.mkdirSync(bin);
fs.mkdirSync(spaced);
return { base, bin, spaced };
}
test("resolveCommand finds a bare name on PATH, a full path, and misses what is not there", (t) => {
const { bin, spaced } = fakePath(t);
const name = WINDOWS ? "goose.exe" : "goose";
fs.writeFileSync(path.join(bin, name), "");
const opts = { path: [spaced, `"${bin}"`].join(path.delimiter), pathext: ".EXE;.CMD" };
assert.equal(resolveCommand("goose", opts)?.toLowerCase(), path.join(bin, name).toLowerCase(), "a bare name, PATH entry quoted");
assert.equal(resolveCommand(path.join(bin, name), opts), path.join(bin, name), "a full path");
assert.equal(resolveCommand(` "${path.join(bin, name)}" `, opts), path.join(bin, name), "a quoted, padded full path");
assert.equal(resolveCommand("nowhere", opts), null);
assert.equal(resolveCommand(path.join(bin, "nowhere"), opts), null);
assert.equal(resolveCommand(bin, opts), null, "a folder is not a command");
assert.equal(resolveCommand("", opts), null);
assert.equal(resolveCommand("goose", { path: "", pathext: ".EXE" }), null, "an empty PATH finds nothing");
});
test("resolveCommand on Windows tries PATHEXT, also in a folder with a space and for a full path", { skip: !WINDOWS && "Windows only" }, (t) => {
const { spaced } = fakePath(t);
const cmd = path.join(spaced, "aider.cmd");
fs.writeFileSync(cmd, "@echo off");
const opts = { path: spaced, pathext: ".EXE;.CMD;.BAT" };
assert.equal(resolveCommand("aider", opts)?.toLowerCase(), cmd.toLowerCase(), "found through PATHEXT");
assert.equal(resolveCommand("aider.cmd", opts), cmd, "a name that already has its extension");
assert.equal(resolveCommand(path.join(spaced, "aider"), opts)?.toLowerCase(), cmd.toLowerCase(), "a full path without its extension");
assert.equal(resolveCommand("aider", { path: spaced, pathext: ".EXE" }), null, "only the listed extensions");
});
/* ------------------------------------------------------- validateForSave */
test("validateForSave fills ids from names and every default", () => {
const { agents, error } = validateForSave([
{ id: "goose", name: "Goose", command: "goose" },
{ name: "My Agent", command: " my-agent " },
{ name: "goose!", command: "goose2" },
]);
assert.equal(error, undefined);
assert.deepEqual(agents.map((a) => a.id), ["goose", "my-agent", "goose-2"]);
assert.equal(agents[1].command, "my-agent");
assert.deepEqual(agents[1].modelArgs, ["--model", "{model}"]);
assert.equal(agents[1].prompt, "/plan2code");
});
test("validateForSave names the entry and field of the first failure", () => {
const cases = [
[[{ name: "Goose", command: "goose" }, { name: "GOOSE", command: "x" }], 1, "name"],
[[{ name: "Goose", command: " " }], 0, "command"],
[[{ name: "", command: "x" }], 0, "name"],
[[{ id: "claude", name: "Mine", command: "claude" }], 0, "id"],
[[{ id: "Bad Id", name: "Mine", command: "x" }], 0, "id"],
[[{ id: "a", name: "A", command: "a" }, { id: "a", name: "B", command: "b" }], 1, "id"],
[[{ name: "A", command: "a", args: ["--x", 1] }], 0, "args"],
[[{ name: "A", command: "a", models: [{ label: "no id" }] }], 0, "models"],
[[{ name: "A", command: "a" }, "text"], 1, ""],
];
for (const [list, index, field] of cases) {
const out = validateForSave(list);
assert.ok(out.error, JSON.stringify(list));
assert.equal(out.index, index, JSON.stringify(list));
assert.equal(out.field, field, JSON.stringify(list));
}
assert.equal(validateForSave({}).field, "agents");
assert.equal(validateForSave(Array.from({ length: MAX_AGENTS + 1 }, (_, i) => ({ name: `A${i}`, command: "a" }))).field, "agents");
});
test("an id the form already carries is never handed to a new entry", () => {
const { agents } = validateForSave([{ name: "Goose", command: "a" }, { id: "goose", name: "Other", command: "b" }]);
assert.deepEqual(agents.map((a) => a.id), ["goose-2", "goose"]);
});
+27 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -232,3 +232,29 @@ test("toggling the tired Planny <svg>'s hidden attribute the way app.js does act
await browser.close();
}
});
test("continueKeys gives a custom agent id the plain word and Enter", () => {
assert.deepEqual(continueKeys("my-aider"), ["continue", "\r"]);
});
const AVAIL = (spec) =>
spec.map(([id, installed, custom = false]) => ({ id, label: id, installed, custom }));
test("pickDefaultAgent keeps the remembered agent when it is installed, custom ones included", () => {
const list = AVAIL([["claude", true], ["devin", true], ["codex", true], ["mine", true, true]]);
assert.equal(pickDefaultAgent(list, "codex"), "codex");
assert.equal(pickDefaultAgent(list, "mine"), "mine");
});
test("pickDefaultAgent falls back to the first installed built-in, then the first installed custom agent", () => {
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", true]]), null), "codex");
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", true], ["codex", true]]), "claude"), "devin");
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", false], ["mine", true, true]]), "claude"), "mine");
});
test("pickDefaultAgent with nothing installed returns the remembered id, else the first entry, else null", () => {
const none = AVAIL([["claude", false], ["devin", false], ["codex", false]]);
assert.equal(pickDefaultAgent(none, "devin"), "devin");
assert.equal(pickDefaultAgent(none, null), "claude");
assert.equal(pickDefaultAgent([], null), null);
});
+176 -4
View File
@@ -307,14 +307,25 @@ test("launcher: the shipped models.json is curated Devin at low/medium/high only
}
});
test("launcher: with no CLI installed it exits 127 and says how to run the skill from an agent", (t) => {
test("launcher: with no CLI installed it exits 127 and explains how to get one and how to run the skill from an agent", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 127);
assert.match(result.stderr, /none of `claude`, `devin` or `codex` was found/);
assert.ok(result.stderr.includes("type /plan2code"));
assert.ok(result.stderr.includes("$plan2code (Codex)"));
assert.match(result.stderr, /Plan2Code runs inside an AI coding agent CLI, and none was found/);
// Every built-in's label, install command and official page.
for (const part of [
"Claude Code: npm i -g @anthropic-ai/claude-code",
"https://code.claude.com/docs/en/setup",
"Codex: npm i -g @openai/codex",
"https://github.com/openai/codex",
"Devin: https://devin.ai",
"https://docs.devin.ai/work-with-devin/devin-cli",
]) {
assert.ok(result.stderr.includes(part), part);
}
assert.ok(result.stderr.includes("Add it in User Preferences (web console) under Agents, then run `plan2code` again."));
assert.ok(result.stderr.includes("type /plan2code ($plan2code in Codex)"));
assert.match(result.stderr, /cd into the project/);
});
@@ -607,3 +618,164 @@ test("launcher app: an AGENTS.md marks the folder as a project, so the agent sta
assert.doesNotMatch(result.stderr, /doesn't look like a project/);
assert.notEqual(box.argsOf("claude"), null);
});
// Custom agents (~/.plan2code/agents.json). The shared fixture is the contract the console and
// the desktop app read too; the rest starts real stand-ins from a temp home.
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agents-cases.json"), "utf8"));
const GOOSE = {
id: "goose",
name: "Goose",
command: "goose",
args: ["--yes", "{prompt}"],
bypassArgs: ["--bypass"],
models: [{ id: "m1", label: "Model one" }, { id: "m2" }],
};
/** Write ~/.plan2code/agents.json (an object is stringified; a string goes in as it is). */
function writeAgents(box, file) {
const target = path.join(box.home, ".plan2code", "agents.json");
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, typeof file === "string" ? file : JSON.stringify(file));
return target;
}
const goose = (extra = {}) => ({ schema: 1, agents: [{ ...GOOSE, ...extra }] });
for (const c of CASES.files) {
test(`launcher agents file: ${c.name}`, () => {
const { normalizeAgents } = require(LAUNCHER);
const { agents, warnings } = normalizeAgents(c.raw);
assert.deepEqual(agents, c.agents);
if (!c.warnings.length) assert.deepEqual(warnings, []);
for (const part of c.warnings) {
assert.ok(warnings.some((w) => w.includes(part)), `a warning names "${part}": ${JSON.stringify(warnings)}`);
}
});
}
for (const c of CASES.buildArgs) {
test(`launcher buildArgs: ${c.name}`, () => {
const { buildArgs } = require(LAUNCHER);
assert.deepEqual(buildArgs(c.entry, c.options), c.args);
});
}
test("launcher agents: --cli <custom id> starts it with args, the model through modelArgs, then bypassArgs and the forwarded args", (t) => {
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const result = box.run(["--cli", "goose", "--model", "m1", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--model", "m1", "--bypass", "--verbose"]);
assert.equal(box.argsOf("claude"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
// No model chosen and no models flag: the model arguments are left out.
assert.equal(box.run(["--cli=goose"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--bypass"]);
});
test("launcher agents: the last pick can be a custom id, and the --cli error names custom ids", (t) => {
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
fs.writeFileSync(box.stateFile, JSON.stringify({ lastCli: "goose" }));
assert.equal(box.run([]).status, 0);
assert.notEqual(box.argsOf("goose"), null);
assert.equal(box.argsOf("claude"), null);
const bad = box.run(["--cli", "bogus"]);
assert.equal(bad.status, 2);
assert.match(bad.stderr, /--cli takes claude, devin, codex or goose, not "bogus"/);
});
test("launcher agents: the model menu is the agent's own models, with no shipped list or user models.json", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
fs.mkdirSync(path.join(box.home, ".plan2code"), { recursive: true });
const file = writeAgents(box, goose());
const { customClis, listModels, hasModelFlag } = require(LAUNCHER);
const [cli] = customClis(file, false);
assert.deepEqual(listModels(cli), [{ id: "m1", label: "Model one" }, { id: "m2", label: "" }]);
assert.deepEqual(listModels(customClis(writeAgents(box, goose({ models: [] })), false)[0]), []);
// Only --model counts for a custom agent: Codex's -m does not.
assert.equal(hasModelFlag(["--model", "x"], "goose"), true);
assert.equal(hasModelFlag(["-m", "x"], "goose"), false);
// A model given on the command line goes through modelArgs, once.
assert.deepEqual(cli.args(["--model=m2", "-x"]), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
});
test("launcher agents: a custom agent whose command is not found is left out and named when nothing can run", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
writeAgents(box, { schema: 1, agents: [{ id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
// Left out of the way: claude still starts.
assert.equal(box.run([]).status, 0);
assert.notEqual(box.argsOf("claude"), null);
const asked = box.run(["--cli", "ghost"]);
assert.equal(asked.status, 127);
assert.match(asked.stderr, /Custom agent Ghost: ghost-cmd not found/);
const none = sandbox([]);
t.after(none.cleanup);
writeAgents(none, { schema: 1, agents: [{ id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
const result = none.run([]);
assert.equal(result.status, 127);
assert.match(result.stderr, /Custom agent Ghost: ghost-cmd not found/);
assert.ok(result.stderr.includes("User Preferences"));
});
test("launcher agents: a malformed agents.json warns on a terminal, never crashes, and gives no agents", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const file = writeAgents(box, "{ not json");
const { customClis } = require(LAUNCHER);
const lines = [];
const realError = console.error;
console.error = (line) => lines.push(String(line));
try {
assert.deepEqual(customClis(file, true), []);
assert.deepEqual(customClis(path.join(box.home, "missing.json"), true), []);
} finally {
console.error = realError;
}
assert.equal(lines.length, 1);
assert.match(lines[0], /plan2code: agents\.json: agents\.json is not valid JSON/);
// A piped run prints no warning, and the built-ins carry on.
const result = box.run([]);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, "");
assert.notEqual(box.argsOf("claude"), null);
});
test("launcher agents: the app hand-over passes a custom id and its model unchanged", (t) => {
const box = sandbox(["goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
const result = box.run(["--cli", "goose", "--model", "m2"], { PLAN2CODE_APP: box.appFile, ...display });
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.appArgs().slice(2), ["--agent", "goose", "--model", "m2"]);
assert.equal(box.argsOf("goose"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
});
test("launcher agents: a full-path command starts, and on Windows a .cmd in a folder with a space too", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const spaced = path.join(box.dir, "with space");
fs.mkdirSync(spaced);
const recorder = path.join(box.dir, "bin", "record.js");
let file;
if (IS_WINDOWS) {
file = path.join(spaced, "spaced.cmd");
fs.writeFileSync(file, `@"${process.execPath}" "${recorder}" spaced %*\r\n`);
} else {
file = path.join(spaced, "spaced");
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${recorder}" spaced "$@"\n`);
fs.chmodSync(file, 0o755);
}
writeAgents(box, { schema: 1, agents: [{ id: "spaced", name: "Spaced", command: file, args: ["{prompt}"] }] });
const result = box.run(["--cli", "spaced", "--note", "a b"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("spaced"), ["/plan2code", "--note", "a b"]);
});
+2
View File
@@ -392,6 +392,8 @@ test("every state-changing route refuses a foreign Origin, and nothing changes",
["POST", "/draft", { staged: { q1: { k: "B" } } }],
["POST", "/looks", { looks: { theme: "light" } }],
["POST", "/models", { models: { devin: [{ id: "x" }] } }],
["POST", "/agents", { agents: [{ name: "X", command: "x" }] }],
["POST", "/agents/test", { command: "node" }],
["POST", "/workspace/add", { path: picked }],
["POST", "/workspace/edit", { id: "f0", name: "renamed" }],
["POST", "/workspace/remove", { id: "f0" }],
+77
View File
@@ -484,6 +484,83 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [] });
});
test("agents: no file is an empty list, a save is written whole and keeps unknown keys, and a bad save names its entry and field", async (t) => {
const file = path.join(MODELS_DIR, "agents.json");
t.after(() => fs.rmSync(file, { force: true }));
fs.rmSync(file, { force: true });
const get = async () => (await fetch(baseUrl + "/agents", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
assert.deepEqual(await get(), { agents: [], warnings: [] }, "no file");
fs.mkdirSync(MODELS_DIR, { recursive: true });
fs.writeFileSync(file, "{ \"schema\": 1, \"agents\": [");
const broken = await get();
assert.deepEqual(broken.agents, [], "a half-written file is no agents");
assert.match(broken.warnings.join(" "), /not valid JSON/, "and says why");
fs.writeFileSync(file, JSON.stringify({ schema: 1, theme: "kept", agents: [] }));
const saved = await post("/agents", { agents: [{ name: "My Agent", command: " my-agent ", note: "mine" }] });
assert.equal(saved.status, 200);
const body = await saved.json();
assert.equal(body.ok, true);
assert.equal(body.agents[0].id, "my-agent", "an id is made from the name");
const written = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(written.schema, 1);
assert.equal(written.theme, "kept", "a top-level key the file had survives the rewrite");
assert.deepEqual(written.agents, [
{ name: "My Agent", command: "my-agent", note: "mine", id: "my-agent", args: [], bypassArgs: [], modelArgs: ["--model", "{model}"], prompt: "/plan2code", models: [] },
]);
assert.deepEqual(fs.readdirSync(MODELS_DIR).filter((n) => n.startsWith("agents.json.")), [], "no temp file left behind");
assert.deepEqual((await get()).agents.map((a) => a.id), ["my-agent"]);
const before = fs.readFileSync(file, "utf8");
const dup = await post("/agents", { agents: [{ id: "my-agent", name: "My Agent", command: "my-agent" }, { name: "MY AGENT", command: "x" }] });
assert.equal(dup.status, 400);
assert.deepEqual(await dup.json(), { error: 'name "MY AGENT" is already used', index: 1, field: "name" });
for (const agents of [[{ name: "A", command: " " }], [{ id: "codex", name: "A", command: "a" }], "nope"]) {
assert.equal((await post("/agents", { agents })).status, 400, JSON.stringify(agents));
}
assert.equal((await raw("POST", "/agents", "not json")).status, 400);
assert.equal(fs.readFileSync(file, "utf8"), before, "a refused save writes nothing");
});
test("agents: a file with entries the page could not read is not overwritten unless the save says replace", async (t) => {
const file = path.join(MODELS_DIR, "agents.json");
t.after(() => fs.rmSync(file, { force: true }));
fs.mkdirSync(MODELS_DIR, { recursive: true });
const mine = { agents: [{ name: "Mine", command: "mine" }] };
for (const text of [
JSON.stringify({ schema: 2, agents: [{ id: "future", name: "Future", command: "future" }] }),
JSON.stringify({ schema: 1, agents: [{ id: "Hand", name: "Hand", command: "hand" }] }),
"{ \"schema\": 1, \"agents\": [",
]) {
fs.writeFileSync(file, text);
const refused = await post("/agents", mine);
assert.equal(refused.status, 409, text);
const body = await refused.json();
assert.match(body.error, /could not read/);
assert.ok(body.warnings.length > 0, "the warnings come back with it");
assert.equal(fs.readFileSync(file, "utf8"), text, "nothing is written");
}
const replaced = await post("/agents", { ...mine, replace: true });
assert.equal(replaced.status, 200, "replace: true writes anyway");
const written = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(written.schema, 1);
assert.deepEqual(written.agents.map((a) => a.id), ["mine"]);
assert.equal((await post("/agents", mine)).status, 200, "a file the page reads whole saves as usual");
});
test("agents/test: finds a command on PATH or says it is not there, and never runs it", async () => {
const found = await (await post("/agents/test", { command: "node" })).json();
assert.equal(found.found, true);
assert.ok(fs.statSync(found.path).isFile(), found.path);
assert.deepEqual(await (await post("/agents/test", { command: "p2c-no-such-agent-cli" })).json(), { found: false });
for (const command of ["", " ", 7, "x".repeat(1025)]) {
assert.equal((await post("/agents/test", { command })).status, 400, String(command).slice(0, 20));
}
});
test("cleanup over HTTP: a scan lists strays in the console home, and a delete removes only what the scan found", async () => {
const stray = path.join(HOME, "stray-cleanup.json");
fs.writeFileSync(stray, "{}");
+111
View File
@@ -117,6 +117,117 @@ test("the launcher's model menus have Claude, Devin and Codex tabs, and a model
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
});
test("Agents: a person adds an agent, tests its command, sees it saved after a reload, and deletes it", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.rmSync(file, { force: true });
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
const list = s.page.locator("#agents-list");
assert.equal(await list.locator(".agent-card").count(), 0, "no agents before one is added");
await s.page.click("#agents-add");
const card = list.locator(".agent-card").last();
await card.getByRole("textbox", { name: "Name", exact: true }).fill("Test Agent");
await card.getByRole("textbox", { name: "Command", exact: true }).fill("node");
await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
await card.getByRole("button", { name: "Test", exact: true }).click();
await card.locator(".agent-test-result").filter({ hasText: /^Found at / }).waitFor();
const saved = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(saved.schema, 1);
assert.deepEqual(saved.agents.map((a) => [a.id, a.name, a.command, a.prompt]), [["test-agent", "Test Agent", "node", "/plan2code"]]);
// A second agent with the same name is refused on its own card and field.
await s.page.click("#agents-add");
const second = list.locator(".agent-card").nth(1);
await second.getByRole("textbox", { name: "Command", exact: true }).fill("x");
await second.getByRole("textbox", { name: "Name", exact: true }).fill("TEST AGENT");
await second.getByRole("textbox", { name: "Name", exact: true }).press("Tab");
await list.locator(".agent-card").nth(1).locator(".agent-error").filter({ hasText: /already used/ }).waitFor();
assert.equal(await list.locator(".agent-card").nth(1).locator('input.invalid[data-field="name"]').count(), 1, "the name field is marked");
assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents.length, 1, "a refused save writes nothing");
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await s.page.click("#btn-looks");
await list.locator(".agent-card").first().waitFor();
assert.equal(await list.locator(".agent-card").count(), 1);
assert.equal(await list.locator(".agent-card").first().getByRole("textbox", { name: "Name", exact: true }).inputValue(), "Test Agent");
await list.locator(".agent-card").first().getByRole("button", { name: "Delete", exact: true }).click();
await list.locator(".agent-card").first().getByRole("button", { name: "Yes, delete" }).click();
await s.page.waitForFunction(() => document.querySelectorAll("#agents-list .agent-card").length === 0);
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents, []);
});
test("Agents: a new card's first field is not saved alone, and a redraw keeps focus and what was typed", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.rmSync(file, { force: true });
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
const list = s.page.locator("#agents-list");
await s.page.click("#agents-add");
const card = list.locator(".agent-card").last();
const name = card.getByRole("textbox", { name: "Name", exact: true });
const command = card.getByRole("textbox", { name: "Command", exact: true });
await name.fill("Focus Agent");
await name.press("Tab");
await s.page.waitForTimeout(300);
assert.equal(await list.locator(".agent-error").count(), 0, "a name alone is not sent, so nothing is refused");
assert.equal(fs.existsSync(file), false, "and nothing is written");
assert.equal(await command.evaluate((el) => el === document.activeElement), true, "Tab lands on Command");
// The first good save assigns an id and redraws every card: focus stays where Tab put it.
await command.fill("node");
await command.press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents[0].id, "focus-agent");
assert.equal(await s.page.evaluate(() => document.activeElement?.textContent), "Add an argument", "focus survives the redraw");
// A refused save redraws too: the field being typed in keeps its text, and leaving it saves it.
const prompt = list.locator(".agent-card").last().getByRole("textbox", { name: "Start prompt", exact: true });
await name.fill("");
await prompt.click();
await prompt.fill("/plan2code hi");
await list.locator(".agent-error").filter({ hasText: /name is missing/ }).waitFor();
assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Start prompt");
assert.equal(await s.page.evaluate(() => document.activeElement?.value), "/plan2code hi");
});
test("Agents: a file holding entries the page could not read is only replaced after Save anyway", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.mkdirSync(MODELS_DIR, { recursive: true });
const text = JSON.stringify({ schema: 2, agents: [{ id: "future", name: "Future", command: "future" }] });
fs.writeFileSync(file, text);
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
await s.page.locator("#agents-status").filter({ hasText: /schema 2/ }).waitFor();
assert.equal(await s.page.locator("#agents-replace").isVisible(), false, "no Save anyway before a save is tried");
await s.page.click("#agents-add");
const card = s.page.locator("#agents-list .agent-card").last();
await card.getByRole("textbox", { name: "Name", exact: true }).fill("Mine");
await card.getByRole("textbox", { name: "Command", exact: true }).fill("node");
await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /could not read/ }).waitFor();
assert.equal(fs.readFileSync(file, "utf8"), text, "the refused save writes nothing");
await s.page.locator("#agents-replace").click();
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.equal(await s.page.locator("#agents-replace").isVisible(), false);
assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents.map((a) => a.id), ["mine"]);
});
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
+2 -1
View File
@@ -447,6 +447,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
backdate(put(path.join(plan2code, "app", "plan2code-app"), "x"));
backdate(path.join(plan2code, "app"));
backdate(put(path.join(plan2code, "app.json")));
backdate(put(path.join(plan2code, "agents.json")));
// In use right now: a held lock and a temp between its write and rename.
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
kept.push(...live);
@@ -462,7 +463,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
"session:20250801-101010-aaaaaa",
]);
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
for (const id of ["root:app", "root:app.json"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`);
for (const id of ["root:app", "root:app.json", "root:agents.json"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`);
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
+1 -1
View File
@@ -185,7 +185,7 @@ test("shape: no page module sets a style attribute from script", () => {
// no routes of its own: its buttons are sends (`__git`), through /submit.
const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace",
+278 -30
View File
@@ -19,6 +19,10 @@
* Self-contained, Node built-ins only: install.js copies this file to ~/.plan2code/bin/ and
* points the global shims at it.
*
* Custom agents: the person's own agent CLIs in ~/.plan2code/agents.json (written by User
* Preferences in the web console) are listed after the built-ins and started the same way, with
* `--cli <id>` or from the menu. Their rules are copied from src/web-console/agents.mjs below.
*
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
* project folder with a native folder picker first, starting on the folder picked last time.
*
@@ -54,6 +58,7 @@ const APP_FILE = IS_WINDOWS ? 'plan2code-app.exe' : 'plan2code-app';
// How long a freshly started app may take to fall over before the launcher calls it started.
const APP_START_GRACE_MS = 1200;
const STATE_FILE = path.join(os.homedir(), '.plan2code', 'launcher.json');
const USER_AGENTS_FILE = path.join(os.homedir(), '.plan2code', 'agents.json');
// Menus longer than this print compactly (id-only, two columns).
const MODELS_MENU_COMPACT_AT = 30;
const PICKER_PROMPT = 'Choose the project folder to open Plan2Code in';
@@ -128,6 +133,7 @@ const CLIS = [
id: 'claude',
label: 'Claude Code',
install: 'npm i -g @anthropic-ai/claude-code',
installUrl: 'https://code.claude.com/docs/en/setup',
prompt: '/plan2code',
args: (extra) => ['/plan2code', '--permission-mode', 'bypassPermissions', ...extra],
},
@@ -135,6 +141,7 @@ const CLIS = [
id: 'devin',
label: 'Devin',
install: 'https://devin.ai',
installUrl: 'https://docs.devin.ai/work-with-devin/devin-cli',
prompt: '/plan2code',
args: (extra) => ['--permission-mode', 'bypass', ...extra, '--', '/plan2code'],
},
@@ -142,26 +149,243 @@ const CLIS = [
id: 'codex',
label: 'Codex',
install: 'npm i -g @openai/codex',
installUrl: 'https://github.com/openai/codex',
prompt: '$plan2code',
// Codex mentions a skill with `$name`; the prompt is its one positional argument.
args: (extra) => ['--dangerously-bypass-approvals-and-sandbox', ...extra, '$plan2code'],
},
];
/** What to do when no agent is installed: how to get one and how to run the skill from it. */
const SKILL_STEPS = [
'Plan2Code runs inside an AI coding agent. To use it:',
' 1. Install one: Claude Code (npm i -g @anthropic-ai/claude-code), Codex (npm i -g @openai/codex) or Devin (https://devin.ai).',
' 2. Open a new terminal and cd into the project you want to work on.',
' 3. Start your agent there, then type /plan2code (Claude Code, Devin) or $plan2code (Codex).',
];
/** The CLI ids as prose: "`claude`, `devin` or `codex`", or without the backticks for `quote` ''. */
function cliIdList(quote = '`') {
const ids = CLIS.map((cli) => quote + cli.id + quote);
function cliIdList(quote = '`', clis = CLIS) {
const ids = clis.map((cli) => quote + cli.id + quote);
return `${ids.slice(0, -1).join(', ')} or ${ids[ids.length - 1]}`;
}
/** An install command with its official page after it, unless the command is the page. */
function installLine(cli) {
return cli.installUrl && cli.installUrl !== cli.install ? `${cli.install} (${cli.installUrl})` : cli.install;
}
/**
* What to do when no agent can run: what an agent CLI is, how to get each built-in, where to add
* another, and how to run the skill from an agent. `missing` names custom agents whose command
* was not found. Printed to stderr; the caller exits 127.
*/
function printNoAgentGuidance(missing = []) {
console.error(`${ce.red('plan2code:')} Plan2Code runs inside an AI coding agent CLI, and none was found on your PATH.`);
console.error('');
console.error(ce.bright('Install one:'));
for (const cli of CLIS) console.error(` ${ce.cyan(cli.label)}: ${installLine(cli)}`);
console.error('');
console.error('Already use another agent CLI? Add it in User Preferences (web console) under Agents, then run `plan2code` again.');
for (const cli of missing) console.error(ce.yellow(`Custom agent ${cli.label}: ${cli.entry.command} not found`));
console.error('');
console.error('After installing, open a new terminal, cd into the project you want to work on and run `plan2code`.');
console.error('Or open your agent in your project and type /plan2code ($plan2code in Codex).');
}
// ---------------------------------------------------------------------------------------------
// Custom agents. normalizeAgents and buildArgs are copies of the rules in
// src/web-console/agents.mjs (this file is installed alone and cannot import it). The shared
// cases in scripts/fixtures/agents-cases.json are the contract: change a rule there first.
const AGENTS_SCHEMA = 1;
const MAX_AGENTS = 50;
const BUILTIN_AGENT_IDS = ['claude', 'devin', 'codex'];
const AGENT_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
const MAX_NAME = 60;
const DEFAULT_PROMPT = '/plan2code';
const DEFAULT_MODEL_ARGS = ['--model', '{model}'];
const LIST_FIELDS = ['args', 'bypassArgs', 'modelArgs'];
/**
* The file as the launcher uses it: `raw` is its text (or the parsed value; undefined or null
* when there is no file). Bad entries are skipped and named in `warnings`, and a bad file means
* no agents. Never throws.
*/
function normalizeAgents(raw) {
const warnings = [];
if (raw === undefined || raw === null) return { agents: [], warnings };
let file = raw;
if (typeof raw === 'string') {
try {
file = JSON.parse(raw);
} catch {
return { agents: [], warnings: ['agents.json is not valid JSON, so no custom agents are used'] };
}
}
if (!file || typeof file !== 'object' || Array.isArray(file)) {
return { agents: [], warnings: ['agents.json is not an object, so no custom agents are used'] };
}
if (file.schema !== AGENTS_SCHEMA) {
return { agents: [], warnings: [`agents.json has schema ${JSON.stringify(file.schema)}, not ${AGENTS_SCHEMA}, so no custom agents are used`] };
}
if (file.agents === undefined || file.agents === null) return { agents: [], warnings };
if (!Array.isArray(file.agents)) return { agents: [], warnings: ['agents.json: agents is not a list, so no custom agents are used'] };
let list = file.agents;
if (list.length > MAX_AGENTS) {
warnings.push(`agents.json lists ${list.length} agents; only the first ${MAX_AGENTS} are used`);
list = list.slice(0, MAX_AGENTS);
}
const agents = [];
const ids = new Set();
const names = new Set();
list.forEach((entry, index) => {
const out = checkAgentEntry(entry, ids, names);
if (out.error) return warnings.push(`agents[${index}] skipped: ${out.error}`);
ids.add(out.agent.id);
names.add(out.agent.name.toLowerCase());
agents.push(out.agent);
});
return { agents, warnings };
}
// One entry against the rules: { agent } with the defaults filled and any unknown keys kept,
// or { error } naming the first thing wrong.
function checkAgentEntry(entry, ids, names) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return { error: 'not an object' };
const { id } = entry;
if (typeof id !== 'string' || !id) return { error: 'id is missing' };
if (BUILTIN_AGENT_IDS.includes(id)) return { error: `id "${id}" belongs to a built-in agent` };
if (!AGENT_ID.test(id)) return { error: `id "${id}" must be 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit` };
if (ids.has(id)) return { error: `id "${id}" is already used` };
const name = typeof entry.name === 'string' ? entry.name.trim() : '';
if (!name) return { error: 'name is missing' };
if (name.length > MAX_NAME) return { error: `name is longer than ${MAX_NAME} characters` };
if (names.has(name.toLowerCase())) return { error: `name "${name}" is already used` };
const command = typeof entry.command === 'string' ? entry.command.trim() : '';
if (!command) return { error: 'command is missing' };
const agent = { ...entry, id, name, command };
for (const field of LIST_FIELDS) {
const value = entry[field];
if (value === undefined || value === null) {
agent[field] = field === 'modelArgs' ? [...DEFAULT_MODEL_ARGS] : [];
} else if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
return { error: `${field} must be a list of text` };
} else agent[field] = [...value];
}
if (entry.prompt === undefined || entry.prompt === null) agent.prompt = DEFAULT_PROMPT;
else if (typeof entry.prompt !== 'string') return { error: 'prompt must be text' };
if (entry.models === undefined || entry.models === null) agent.models = [];
else if (!Array.isArray(entry.models)) return { error: 'models must be a list' };
else {
agent.models = [];
const seen = new Set();
for (const model of entry.models) {
if (!model || typeof model !== 'object' || typeof model.id !== 'string') return { error: 'every model in models needs an id' };
const modelId = model.id.trim();
if (!modelId || seen.has(modelId)) continue;
seen.add(modelId);
const label = typeof model.label === 'string' ? model.label.trim() : '';
agent.models.push(label ? { id: modelId, label } : { id: modelId });
}
}
return { agent };
}
/**
* The arguments that start an entry, in order: `args` with {prompt} filled (the prompt appended
* when no argument holds it), then `modelArgs` when a model is chosen, then `bypassArgs` when
* checks are off. `prompt` defaults to the entry's own; a blank one drops an argument that is
* exactly {prompt}. Plain text in, plain text out: no quoting for any shell.
*/
function buildArgs(entry, { prompt, model, bypass } = {}) {
const text = prompt === undefined ? (typeof entry.prompt === 'string' ? entry.prompt : DEFAULT_PROMPT) : String(prompt ?? '');
const blank = !text.trim();
const out = [];
let placed = false;
for (const arg of entry.args || []) {
if (!arg.includes('{prompt}')) {
out.push(arg);
continue;
}
placed = true;
if (arg === '{prompt}' && blank) continue;
out.push(arg.split('{prompt}').join(text));
}
if (!placed && !blank) out.push(text);
if (model) {
for (const arg of entry.modelArgs || DEFAULT_MODEL_ARGS) out.push(arg.split('{model}').join(model));
}
if (bypass) out.push(...(entry.bypassArgs || []));
return out;
}
/** `args` without `--model <x>` / `--model=<x>`: a custom agent gets its model through modelArgs. */
function withoutModelFlag(args) {
const out = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === '--model') i++;
else if (!args[i].startsWith('--model=')) out.push(args[i]);
}
return out;
}
/**
* The custom agents in agents.json as CLIS-shaped entries, none resolved yet. A missing or
* malformed file gives an empty list (and, with `print` on, which is a terminal only, one stderr
* line per warning), never an error. chooseCli() asks once, so each warning shows once per run.
*/
function customClis(file = USER_AGENTS_FILE, print = Boolean(process.stderr.isTTY)) {
let raw = null;
try {
raw = fs.readFileSync(file, 'utf8');
} catch {}
const { agents, warnings } = normalizeAgents(raw);
if (print) for (const warning of warnings) console.error(`${ce.yellow('plan2code:')} agents.json: ${warning}`);
return agents.map((entry) => ({
id: entry.id,
label: entry.name,
install: null,
prompt: entry.prompt,
custom: true,
entry,
args: (extra) => [...buildArgs(entry, { bypass: true, model: modelFrom(extra, entry.id) }), ...withoutModelFlag(extra)],
}));
}
/**
* Where a custom agent's command runs from, as { path, fullPath }, or null. A command with a
* path separator is checked as a file (PATHEXT tried on Windows when it has no extension); a
* bare name is looked for on PATH. Never runs anything.
*/
function resolveCustomCommand(command) {
const name = String(command ?? '').trim().replace(/^"(.*)"$/, '$1');
if (!name) return null;
const isFile = (file) => {
try {
return fs.statSync(file).isFile();
} catch {
return false;
}
};
const extensions = IS_WINDOWS ? (process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean) : [];
if (name.includes('/') || (IS_WINDOWS && name.includes('\\'))) {
const full = path.resolve(name);
const found = (IS_WINDOWS && !path.extname(full) ? extensions.map((ext) => full + ext) : [full]).find(isFile);
return found ? { path: found, fullPath: true } : null;
}
let found = findOnPath(name);
// A bare name that already has an extension (goose.cmd) is not found by findOnPath, which adds one.
if (!found && IS_WINDOWS && path.extname(name)) {
for (const dir of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
const candidate = path.join(dir.replace(/^"|"$/g, ''), name);
if (isFile(candidate)) {
found = candidate;
break;
}
}
}
return found ? { path: found, fullPath: false } : null;
}
// The curated menu ships beside this file (models.json, overwritten by every install); models
// the user adds in User Preferences live in ~/.plan2code/models.json and are merged in.
const SHIPPED_MODELS_FILE = path.join(__dirname, 'models.json');
@@ -413,20 +637,31 @@ function announceCli(cli) {
* exit code) after printing why none can be used.
*/
async function chooseCli(requested) {
const customs = customClis();
const all = [...CLIS, ...customs];
const installed = CLIS.map((cli) => ({ ...cli, path: findOnPath(cli.id) })).filter((cli) => cli.path);
// A custom agent whose command does not resolve is left out of the menu and named when nothing can run.
const missing = [];
for (const cli of customs) {
const found = resolveCustomCommand(cli.entry.command);
if (found) installed.push({ ...cli, ...found });
else missing.push(cli);
}
if (requested !== undefined) {
const known = CLIS.find((cli) => cli.id === requested);
const known = all.find((cli) => cli.id === requested);
if (!known) {
console.error(`${ce.red('plan2code:')} --cli takes ${cliIdList('')}${requested ? `, not "${requested}"` : ''}.`);
console.error(`${ce.red('plan2code:')} --cli takes ${cliIdList('', all)}${requested ? `, not "${requested}"` : ''}.`);
return { code: 2 };
}
const found = installed.find((cli) => cli.id === requested);
if (!found) {
if (!found && known.custom) {
console.error(`${ce.red('plan2code:')} Custom agent ${known.label}: ${known.entry.command} not found`);
} else if (!found) {
console.error(`${ce.red('plan2code:')} the \`${known.id}\` CLI was not found on your PATH.`);
console.error('');
console.error(`To use ${known.label}:`);
console.error(` 1. Install it: ${known.install}`);
console.error(` 1. Install it: ${installLine(known)}`);
console.error(' 2. Open a new terminal and cd into the project you want to work on.');
console.error(` 3. Run \`plan2code --cli ${known.id}\` there, or start ${known.label} and type ${known.prompt}.`);
}
@@ -435,11 +670,7 @@ async function chooseCli(requested) {
}
if (installed.length === 0) {
console.error(`${ce.red('plan2code:')} none of ${cliIdList()} was found on your PATH.`);
console.error('');
for (const step of SKILL_STEPS) console.error(step);
console.error('');
console.error('Already have an agent? Open it in your project and type /plan2code ($plan2code in Codex), or install it and run `plan2code` again.');
printNoAgentGuidance(missing);
return { code: 127 };
}
if (installed.length === 1 || !process.stdin.isTTY) {
@@ -503,6 +734,8 @@ function readJsonFile(file) {
/** The model menu for one CLI: the curated list plus the user's additions from User Preferences. */
function listModels(cli) {
// A custom agent's menu is its own models: no shipped list and no User Preferences additions.
if (cli.custom) return cli.entry.models.map((m) => ({ id: m.id, label: m.label || '' }));
return mergeModels(
modelEntries(readJsonFile(SHIPPED_MODELS_FILE), cli.id),
modelEntries(readJsonFile(USER_MODELS_FILE), cli.id)
@@ -515,6 +748,7 @@ function listModels(cli) {
* nobody to ask, so it just says which model will be used, as it always has.
*/
async function chooseModel(cli, extraArgs) {
if (cli.custom && !listModels(cli).length) return;
if (!process.stdin.isTTY) {
console.log(`${cli.label} will use the model you last used in it. To use a different model, open`);
console.log(`\`${cli.id}\` on its own and switch model there, or run \`plan2code --model <name>\`.`);
@@ -536,7 +770,7 @@ async function chooseModel(cli, extraArgs) {
console.log(left.replace(`${i + 1})`, c.cyan(`${i + 1})`)) + right);
}
} else {
models.forEach((model, i) => console.log(` ${c.cyan(`${i + 1})`)} ${model.id} — ${model.label}`));
models.forEach((model, i) => console.log(!model.label ? ` ${c.cyan(`${i + 1})`)} ${model.id}` : ` ${c.cyan(`${i + 1})`)} ${model.id} — ${model.label}`));
}
for (;;) {
const answer = (await ask(`Choice ${c.green('[keep last used]')}: `)).trim().toLowerCase();
@@ -760,16 +994,30 @@ async function exitWith(code, fromShortcut) {
/**
* Spawn a resolved command with `args`. A .cmd/.bat wrapper on Windows goes through cmd.exe,
* since Node refuses to spawn one without a shell.
* since Node refuses to spawn one without a shell. `options.fromFullPath` (never passed on to
* spawn) marks a custom agent whose command was given as a full path: that wrapper runs as
* `cmd /c <file name> ...args` with its folder first on the child's PATH, so a space in the
* folder is never in the cmd line itself.
*/
function spawnCommand(file, args, options) {
return IS_WINDOWS && /\.(cmd|bat)$/i.test(file)
? spawn(
process.env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `"${[file, ...args].map(quoteForCmd).join(' ')}"`],
{ ...options, windowsVerbatimArguments: true }
)
: spawn(file, args, options);
const { fromFullPath, ...spawnOptions } = options || {};
if (!(IS_WINDOWS && /\.(cmd|bat)$/i.test(file))) return spawn(file, args, spawnOptions);
const shell = process.env.ComSpec || 'cmd.exe';
if (!fromFullPath) {
return spawn(shell, ['/d', '/s', '/c', `"${[file, ...args].map(quoteForCmd).join(' ')}"`], {
...spawnOptions,
windowsVerbatimArguments: true,
});
}
const env = { ...(spawnOptions.env || process.env) };
// Windows env names are case-insensitive and the copy keeps the original spelling (Path).
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
env[pathKey] = path.dirname(file) + path.delimiter + (env[pathKey] || '');
return spawn(shell, ['/d', '/s', '/c', `"${[path.basename(file), ...args].map(quoteForCmd).join(' ')}"`], {
...spawnOptions,
env,
windowsVerbatimArguments: true,
});
}
/**
@@ -885,7 +1133,7 @@ async function launch() {
}
const args = cli.args(extraArgs);
const options = { cwd, stdio: 'inherit' };
const options = { cwd, stdio: 'inherit', ...(cli.fullPath ? { fromFullPath: true } : {}) };
const child = spawnCommand(cli.path, args, options);
@@ -913,4 +1161,4 @@ async function launch() {
// Run only when invoked directly; requiring the file (the tests do) is load-only.
if (require.main === module) launch();
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
+226
View File
@@ -0,0 +1,226 @@
// Plan2Code Web Console - the rules of ~/.plan2code/agents.json, the person's custom agent CLIs: reading the file, checking a save, naming an entry, building its command line and finding its command; defines only.
//
// The console is the file's only writer (routes.mjs, from User Preferences);
// the launcher and the desktop app read it with their own copies of these
// rules. scripts/fixtures/agents-cases.json pins all three to the same cases,
// so change a rule there first.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import path from "node:path";
export const BUILTIN_AGENT_IDS = ["claude", "devin", "codex"];
export const AGENTS_SCHEMA = 1;
export const MAX_AGENTS = 50;
const AGENT_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
const MAX_NAME = 60;
const DEFAULT_PROMPT = "/plan2code";
const DEFAULT_MODEL_ARGS = ["--model", "{model}"];
const LIST_FIELDS = ["args", "bypassArgs", "modelArgs"];
/**
* The file as the launcher and the app will use it: `raw` is its text (or the
* parsed value; undefined or null when there is no file). Bad entries are
* skipped and named in `warnings`, and a bad file means no agents. Never throws.
*/
export function normalizeAgents(raw) {
const warnings = [];
if (raw === undefined || raw === null) return { agents: [], warnings };
let file = raw;
if (typeof raw === "string") {
try {
file = JSON.parse(raw);
} catch {
return { agents: [], warnings: ["agents.json is not valid JSON, so no custom agents are used"] };
}
}
if (!file || typeof file !== "object" || Array.isArray(file)) {
return { agents: [], warnings: ["agents.json is not an object, so no custom agents are used"] };
}
if (file.schema !== AGENTS_SCHEMA) {
return { agents: [], warnings: [`agents.json has schema ${JSON.stringify(file.schema)}, not ${AGENTS_SCHEMA}, so no custom agents are used`] };
}
if (file.agents === undefined || file.agents === null) return { agents: [], warnings };
if (!Array.isArray(file.agents)) return { agents: [], warnings: ["agents.json: agents is not a list, so no custom agents are used"] };
let list = file.agents;
if (list.length > MAX_AGENTS) {
warnings.push(`agents.json lists ${list.length} agents; only the first ${MAX_AGENTS} are used`);
list = list.slice(0, MAX_AGENTS);
}
const agents = [];
const ids = new Set();
const names = new Set();
list.forEach((entry, index) => {
const out = checkEntry(entry, ids, names);
if (out.error) return warnings.push(`agents[${index}] skipped: ${out.error}`);
ids.add(out.agent.id);
names.add(out.agent.name.toLowerCase());
agents.push(out.agent);
});
return { agents, warnings };
}
/**
* What the form sends, checked before it is written: the same rules as
* normalizeAgents, but the first failure comes back as { error, index, field }
* instead of being skipped. An entry with no id gets one from its name.
* Returns { agents } with every default filled.
*/
export function validateForSave(list) {
if (!Array.isArray(list)) return { error: "agents must be a list", field: "agents" };
if (list.length > MAX_AGENTS) return { error: `at most ${MAX_AGENTS} agents`, field: "agents" };
// Ids the form already carries are fixed, so a new entry's id steers around them.
const taken = list.map((entry) => (entry && typeof entry === "object" && typeof entry.id === "string" ? entry.id : "")).filter(Boolean);
const agents = [];
const ids = new Set();
const names = new Set();
for (let index = 0; index < list.length; index++) {
let entry = list[index];
if (entry && typeof entry === "object" && !Array.isArray(entry) && (entry.id === undefined || entry.id === null || entry.id === "")) {
const id = makeId(typeof entry.name === "string" ? entry.name : "", taken);
taken.push(id);
entry = { ...entry, id };
}
const out = checkEntry(entry, ids, names);
if (out.error) return { error: out.error, index, field: out.field };
ids.add(out.agent.id);
names.add(out.agent.name.toLowerCase());
agents.push(out.agent);
}
return { agents };
}
// One entry against the rules: { agent } with the defaults filled and any
// unknown keys kept, or { error, field } naming the first thing wrong.
function checkEntry(entry, ids, names) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { error: "not an object", field: "" };
const { id } = entry;
if (typeof id !== "string" || !id) return { error: "id is missing", field: "id" };
if (BUILTIN_AGENT_IDS.includes(id)) return { error: `id "${id}" belongs to a built-in agent`, field: "id" };
if (!AGENT_ID.test(id)) return { error: `id "${id}" must be 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit`, field: "id" };
if (ids.has(id)) return { error: `id "${id}" is already used`, field: "id" };
const name = typeof entry.name === "string" ? entry.name.trim() : "";
if (!name) return { error: "name is missing", field: "name" };
if (name.length > MAX_NAME) return { error: `name is longer than ${MAX_NAME} characters`, field: "name" };
if (names.has(name.toLowerCase())) return { error: `name "${name}" is already used`, field: "name" };
const command = typeof entry.command === "string" ? entry.command.trim() : "";
if (!command) return { error: "command is missing", field: "command" };
const agent = { ...entry, id, name, command };
for (const field of LIST_FIELDS) {
const value = entry[field];
if (value === undefined || value === null) {
agent[field] = field === "modelArgs" ? [...DEFAULT_MODEL_ARGS] : [];
} else if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
return { error: `${field} must be a list of text`, field };
} else agent[field] = [...value];
}
if (entry.prompt === undefined || entry.prompt === null) agent.prompt = DEFAULT_PROMPT;
else if (typeof entry.prompt !== "string") return { error: "prompt must be text", field: "prompt" };
if (entry.models === undefined || entry.models === null) agent.models = [];
else if (!Array.isArray(entry.models)) return { error: "models must be a list", field: "models" };
else {
agent.models = [];
const seen = new Set();
for (const model of entry.models) {
if (!model || typeof model !== "object" || typeof model.id !== "string") return { error: "every model in models needs an id", field: "models" };
const modelId = model.id.trim();
if (!modelId || seen.has(modelId)) continue;
seen.add(modelId);
const label = typeof model.label === "string" ? model.label.trim() : "";
agent.models.push(label ? { id: modelId, label } : { id: modelId });
}
}
return { agent };
}
/**
* An id for a new entry: its name in kebab case ("agent" when nothing is
* left), at most 32 characters, with -2, -3 ... on a clash with `taken` or a
* built-in id.
*/
export function makeId(name, taken = []) {
const used = new Set([...BUILTIN_AGENT_IDS, ...taken]);
const base = trimDashes(
String(name ?? "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.slice(0, 32)
) || "agent";
if (!used.has(base)) return base;
for (let n = 2; ; n++) {
const suffix = `-${n}`;
const id = trimDashes(base.slice(0, 32 - suffix.length)) + suffix;
if (!used.has(id)) return id;
}
}
function trimDashes(text) {
return text.replace(/^-+|-+$/g, "");
}
/**
* The arguments that start an entry, in order: `args` with {prompt} filled
* (the prompt appended when no argument holds it), then `modelArgs` when a
* model is chosen, then `bypassArgs` when checks are off. `prompt` defaults
* to the entry's own; a blank one drops an argument that is exactly
* {prompt}. Plain text in, plain text out: no quoting for any shell.
*/
export function buildArgs(entry, { prompt, model, bypass } = {}) {
const text = prompt === undefined ? (typeof entry.prompt === "string" ? entry.prompt : DEFAULT_PROMPT) : String(prompt ?? "");
const blank = !text.trim();
const out = [];
let placed = false;
for (const arg of entry.args || []) {
if (!arg.includes("{prompt}")) {
out.push(arg);
continue;
}
placed = true;
if (arg === "{prompt}" && blank) continue;
out.push(arg.split("{prompt}").join(text));
}
if (!placed && !blank) out.push(text);
if (model) {
for (const arg of entry.modelArgs || DEFAULT_MODEL_ARGS) out.push(arg.split("{model}").join(model));
}
if (bypass) out.push(...(entry.bypassArgs || []));
return out;
}
/**
* Where `command` runs from, or null. A command with a path separator is
* checked as a file; a bare name is looked for on PATH. On Windows each
* PATHEXT extension is tried when the command has none, as the launcher's
* findOnPath() does. Never runs anything.
*/
export function resolveCommand(command, { path: searchPath = process.env.PATH, pathext = process.env.PATHEXT } = {}) {
const name = String(command ?? "").trim().replace(/^"(.*)"$/, "$1");
if (!name) return null;
const windows = process.platform === "win32";
const extensions = windows ? (pathext || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [];
const tries = (file) => (windows && !path.extname(file) ? extensions.map((ext) => file + ext) : [file]);
const isFile = (file) => {
try {
return fs.statSync(file).isFile();
} catch {
return false;
}
};
if (name.includes("/") || (windows && name.includes("\\"))) {
return tries(path.resolve(name)).find(isFile) || null;
}
for (const dir of String(searchPath || "").split(path.delimiter).filter(Boolean)) {
const found = tries(path.join(dir.replace(/^"|"$/g, ""), name)).find(isFile);
if (found) return found;
}
return null;
}
+3
View File
@@ -40,6 +40,9 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
// The person's custom agent CLIs (agents.mjs has the rules). The console is its only
// writer, from User Preferences; the launcher and the desktop app read it.
export const USER_AGENTS_FILE = path.join(PLAN2CODE_DIR, "agents.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
+16
View File
@@ -2648,6 +2648,22 @@
<span class="help" id="models-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models looks-agents">
<legend>Agents</legend>
<div class="models-note">
<p>Agent CLIs Plan2Code did not find on its own. The <code>plan2code</code> command and the desktop app list the ones that are installed.</p>
<ul>
<li><code>/plan2code</code> works only in agents that load the installed Plan2Code skills. A blank start prompt starts the agent with nothing typed.</li>
<li>The list is saved as plain text in <code>~/.plan2code/agents.json</code>.</li>
</ul>
</div>
<div class="agents-list" id="agents-list" aria-label="Agents you added"></div>
<div class="models-actions">
<button type="button" class="btn small" id="agents-add">Add agent</button>
<button type="button" class="btn small danger" id="agents-replace" hidden>Save anyway</button>
<span class="help" id="agents-status" role="status"></span>
</div>
</fieldset>
</div>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
+358
View File
@@ -90,6 +90,354 @@ async function loadModelsData() {
renderModels();
}
// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json.
// Each card edits its entry in place (unknown keys ride along untouched); every change
// saves the whole list. A new card is not sent until it has a name and a command.
let agentsData = [];
// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData).
let agentsError = null;
// The entry whose Delete is waiting for a second click.
let agentsConfirming = null;
// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn.
let agentsSaveSeq = 0;
// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new
// card still held back) sends nothing.
let agentsLastSent = null;
function setAgentsStatus(text, isError) {
const status = $("agents-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
wrap.dataset.field = field;
wrap.append(el("span", null, label), child);
return wrap;
}
function agentInput(agent, key, label, placeholder, trim) {
const input = el("input");
input.value = agent[key] || "";
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("change", () => {
agent[key] = trim ? input.value.trim() : input.value;
saveAgents();
});
return input;
}
// A list of text rows (arguments), with Remove on each and an Add under them.
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
const box = el("div", "agent-rows");
box.dataset.field = key;
const draw = () => {
box.replaceChildren();
agent[key].forEach((value, i) => {
const row = el("div", "agent-row");
const input = el("input");
input.value = value;
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); });
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
agent[key].splice(i, 1);
draw();
saveAgents();
});
row.append(input, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
agent[key].push("");
draw();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField(label, key, box);
}
// The models list: an id and an optional name for the menu on each row.
function agentModelsEditor(agent) {
const box = el("div", "agent-rows");
box.dataset.field = "models";
const draw = () => {
box.replaceChildren();
agent.models.forEach((m, i) => {
const row = el("div", "agent-row model");
const id = el("input");
id.value = m.id || "";
id.placeholder = "Model id, for {model}";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = m.label || "";
label.placeholder = "Name shown in the menu (optional)";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); });
label.addEventListener("change", () => {
const text = label.value.trim();
if (text) m.label = text;
else delete m.label;
saveAgents();
});
remove.addEventListener("click", () => {
agent.models.splice(i, 1);
draw();
saveAgents();
});
row.append(id, label, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", "Add a model");
add.type = "button";
add.addEventListener("click", () => {
agent.models.push({ id: "" });
draw();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField("Models", "models", box);
}
// Test, and Delete with its confirm step on the card itself (never the browser's confirm()).
function agentFoot(agent) {
const foot = el("div", "agent-foot");
const test = el("button", "btn small", "Test");
test.type = "button";
const result = el("span", "help agent-test-result");
result.setAttribute("role", "status");
test.addEventListener("click", async () => {
const command = String(agent.command || "").trim();
if (!command) {
result.textContent = "Type a command first.";
return;
}
result.textContent = "Looking...";
try {
const res = await fetch("/agents/test", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ command }),
});
const body = await res.json();
if (!res.ok) result.textContent = body.error || "Could not test.";
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
} catch {
result.textContent = "Could not test.";
}
});
foot.append(test);
if (agentsConfirming === agent) {
const ask = el("span", "help", "Delete this agent?");
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
yes.addEventListener("click", async () => {
agentsConfirming = null;
agentsData.splice(agentsData.indexOf(agent), 1);
agentsError = null;
renderAgents();
await saveAgents();
});
keep.addEventListener("click", () => {
agentsConfirming = null;
renderAgents();
});
foot.append(ask, yes, keep);
} else {
const del = el("button", "btn small ghost danger", "Delete");
del.type = "button";
del.addEventListener("click", () => {
agentsConfirming = agent;
renderAgents();
});
foot.append(del);
}
foot.append(result);
return foot;
}
// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the
// person back where they were, with what they had typed: { card, nth, value, start, end }.
const AGENT_FOCUSABLE = "input, button";
function agentsFocus(list) {
const active = document.activeElement;
const card = active && list.contains(active) ? active.closest(".agent-card") : null;
if (!card) return null;
const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreAgentsFocus(list, at) {
const card = at && list.children[at.card];
const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth];
if (!target) return;
if (!(target instanceof HTMLInputElement) || at.value === undefined) {
target.focus();
return;
}
const drawn = target.value;
target.value = at.value;
target.focus();
try {
target.setSelectionRange(at.start, at.end);
} catch {}
// Text typed before the redraw is not in agentsData yet, and the browser fires no change
// for a value set from script, so leaving the field sends it on.
if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true });
}
function renderAgents() {
const list = $("agents-list");
const focus = agentsFocus(list);
list.replaceChildren();
agentsData.forEach((agent, i) => {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) {
if (!Array.isArray(agent[key])) agent[key] = [];
}
const card = el("div", "agent-card");
const top = el("div", "agent-top");
top.append(
agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)),
agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)),
);
card.append(
top,
agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"),
agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
agentModelsEditor(agent),
);
if (agentsError && agentsError.index === i) {
card.classList.add("invalid");
for (const input of card.querySelectorAll("input")) {
if (input.dataset.field === agentsError.field) input.classList.add("invalid");
}
card.appendChild(el("p", "agent-error", agentsError.error));
}
card.appendChild(agentFoot(agent));
list.appendChild(card);
});
restoreAgentsFocus(list, focus);
}
// The list as the server wants it: blank rows dropped, and a new card without both a name and
// a command (one still being typed) left out, so its first field is not refused as half an
// agent. `kept` maps each sent entry back to its place.
function agentsPayload() {
const kept = [];
const agents = [];
agentsData.forEach((a, i) => {
if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return;
kept.push(i);
agents.push({
...a,
args: a.args.filter((v) => v !== ""),
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
modelArgs: a.modelArgs.filter((v) => v !== ""),
models: a.models.filter((m) => m.id),
});
});
return { kept, agents };
}
// `replace` is the person's Save anyway, over a file holding entries this page could not read.
async function saveAgents({ replace = false } = {}) {
const { kept, agents } = agentsPayload();
const sent = JSON.stringify(agents);
if (!replace && agentsError === null && sent === agentsLastSent) return;
const seq = ++agentsSaveSeq;
try {
const res = await fetch("/agents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(replace ? { agents, replace: true } : { agents }),
});
const body = await res.json();
if (seq !== agentsSaveSeq) return;
if (res.status === 409) {
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true);
$("agents-replace").hidden = false;
return;
}
$("agents-replace").hidden = true;
if (!res.ok) {
const at = Number.isInteger(body.index) ? kept[body.index] : undefined;
agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." };
setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true);
renderAgents();
return;
}
// Ids are assigned on the first save: take the server's entries, and redraw only then
// (or to clear a mark), so typing in another card is not interrupted.
const fresh = agents.some((a) => !a.id) || agentsError !== null;
agentsError = null;
agentsLastSent = sent;
setAgentsStatus("Saved.", false);
if (fresh) {
kept.forEach((at, n) => { agentsData[at] = body.agents[n]; });
agentsLastSent = JSON.stringify(agentsPayload().agents);
renderAgents();
}
} catch {
if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true);
}
}
async function loadAgents() {
agentsError = null;
agentsConfirming = null;
agentsLastSent = null;
$("agents-replace").hidden = true;
try {
const res = await fetch("/agents");
if (res.ok) {
const body = await res.json();
agentsData = Array.isArray(body.agents) ? body.agents : [];
for (const agent of agentsData) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
}
agentsLastSent = JSON.stringify(agentsPayload().agents);
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
setAgentsStatus(warnings.join(" "), warnings.length > 0);
} else {
setAgentsStatus("Agents could not be loaded.", true);
}
} catch {
setAgentsStatus("Agents could not be loaded.", true);
}
renderAgents();
}
// Following the system, the saved looks painted before anything is drawn, and
// the sound cues let go on the next touch. `boot` is the page's boot data.
export function startLooks(boot) {
@@ -119,6 +467,7 @@ export function wireLooks() {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
loadAgents();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
@@ -188,6 +537,15 @@ export function wireLooks() {
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("agents-add").addEventListener("click", () => {
agentsData.push(newAgent());
renderAgents();
$("agents-list").querySelector(".agent-card:last-child input")?.focus();
});
$("agents-replace").addEventListener("click", () => {
$("agents-replace").hidden = true;
saveAgents({ replace: true });
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
@@ -108,6 +108,23 @@
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
.agents-list { display: grid; gap: 10px; }
.agents-list:empty { display: none; }
.agent-card { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--rule-2); border-radius: 8px; }
.agent-card.invalid { border-color: var(--danger, #d64545); }
.agent-card input { min-width: 0; }
.agent-card input.invalid { border-color: var(--danger, #d64545); }
.agent-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
.agent-field { display: grid; gap: 4px; min-width: 0; }
.agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; }
.agent-rows { display: grid; gap: 4px; }
.agent-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.agent-row.model { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; }
.agent-foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.agent-foot .help { margin: 0; }
.agent-foot .agent-test-result { flex: 1 1 auto; }
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
#agents-replace[hidden] { display: none; }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
+55
View File
@@ -15,15 +15,18 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
USER_AGENTS_FILE,
USER_MODELS_FILE,
appendEvent,
ensureDir,
fileStamp,
nowIso,
readJson,
readText,
withStateLock,
writeJsonAtomic,
} from "./files.mjs";
import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { checkDocument, cleanupFindings, readOverview, removeCleanup } from "./sessions.mjs";
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
@@ -83,6 +86,9 @@ const ROUTES = [
{ path: "/pr-host", method: "POST", origin: true, run: prHost },
{ path: "/models", method: "GET", run: modelsGet },
{ path: "/models", method: "POST", origin: true, run: modelsPost },
{ path: "/agents", method: "GET", run: agentsGet },
{ path: "/agents", method: "POST", origin: true, run: agentsPost },
{ path: "/agents/test", method: "POST", origin: true, run: agentsTest },
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
{ path: "/upload", method: "POST", origin: true, run: upload },
{ path: "/notepad", method: "GET", run: notepadGet },
@@ -568,6 +574,55 @@ function modelsPost(req, res) {
});
}
// The person's custom agents (agents.mjs has the rules). Read as text, not
// with readJson: a half-written or broken file has to come back as a warning,
// which readJson would turn into the same nothing as a missing file.
function agentsGet(req, res) {
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
return json(res, 200, normalizeAgents(raw));
}
// The whole list from User Preferences, checked, then written atomically. The
// first failure names the entry and field so the page can mark them, and
// nothing is written. Top-level keys the file already had are kept. A file
// holding anything GET /agents could not read (another schema, a skipped
// entry) is refused with 409 unless the page says `replace: true`, so a save
// never silently drops what the person wrote there by hand.
function agentsPost(req, res) {
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { agents, error, index, field } = validateForSave(body && body.agents);
if (error) return json(res, 400, { error, index, field });
if (body.replace !== true && fs.existsSync(USER_AGENTS_FILE)) {
const { warnings } = normalizeAgents(readText(USER_AGENTS_FILE));
if (warnings.length) {
return json(res, 409, { error: "agents.json holds entries this page could not read. Saving replaces them.", warnings });
}
}
const saved = readJson(USER_AGENTS_FILE, null);
const kept = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
try {
ensureDir(path.dirname(USER_AGENTS_FILE));
writeJsonAtomic(USER_AGENTS_FILE, { ...kept, schema: AGENTS_SCHEMA, agents });
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, agents });
});
}
// Where a command would run from, for the form's Test button. Only looks: it
// never runs the command.
function agentsTest(req, res) {
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const command = typeof body?.command === "string" ? body.command.trim() : "";
if (!command || command.length > 1024) return json(res, 400, { error: "command must be 1 to 1024 characters" });
const found = resolveCommand(command);
return json(res, 200, found ? { found: true, path: found } : { found: false });
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
// removes those of the ids a fresh scan still finds. Never this session,
+3 -2
View File
@@ -345,9 +345,10 @@ export async function removeScratch(consoleDir, names) {
// `plan2code update` reads (install.json), the models the person added and
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs) and
// the notepads, removed only one at a time through Cleanup (notepads.mjs), and
// the desktop app (app/, which install.js fills, and app.json, its settings).
// the desktop app (app/, which install.js fills, and app.json, its settings)
// and the custom agents the person added (agents.json).
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json", "agents.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its