Add the agent-less setup page, a shared agent list and the split Agents & models tab

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-03 04:08:27 -08:00
1 parent c122332657
commit 33f1783979
55 files changed
+5453 -1345

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
// Plan2Code - the one agent list (agents.json) and the one rule for where an
// agent's command is found: the shipped list the launcher, the console and
// (mirrored in Rust) the desktop app read; defines only.
//
// install.js copies this file to ~/.plan2code/bin/ beside plan2code.js and
// agents.json, so `loadAgentList()` reads its sibling by default. The shared
// cases in scripts/fixtures/agent-lookup-cases.json pin the Node and Rust
// lookups to the same answers.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const AGENT_LIST_SCHEMA = 1;
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
const isFile = (file) => {
try {
return fs.statSync(file).isFile();
} catch {
return false;
}
};
/**
* The shipped agent list: `agents.json` in `dir` (default: the folder holding
* this module, so the installed copy in ~/.plan2code/bin/ reads its sibling).
* Returns `{ builtins, templates, warnings }`; a missing or bad file means
* empty lists and one warning, never a throw, so callers fall back. With
* `optional` an absent file warns nothing: the shipped list simply is not
* there, while a malformed one is still named.
*/
export function loadAgentList({ dir = MODULE_DIR, optional = false } = {}) {
const warnings = [];
let file;
try {
file = JSON.parse(fs.readFileSync(path.join(dir, "agents.json"), "utf8"));
} catch (error) {
if (optional && error && error.code === "ENOENT") return { builtins: [], templates: [], warnings };
const why = error && error.code === "ENOENT" ? "is missing" : "is not valid JSON";
return { builtins: [], templates: [], warnings: [`agents.json ${why}`] };
}
if (!file || typeof file !== "object" || Array.isArray(file)) {
return { builtins: [], templates: [], warnings: ["agents.json is not an object"] };
}
if (file.schema !== AGENT_LIST_SCHEMA) {
return { builtins: [], templates: [], warnings: [`agents.json has schema ${JSON.stringify(file.schema)}, not ${AGENT_LIST_SCHEMA}`] };
}
const list = Array.isArray(file.agents) ? file.agents : [];
const builtins = [];
const templates = [];
list.forEach((entry, index) => {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
warnings.push(`agents[${index}] skipped: not an object`);
return;
}
if (entry.kind === "builtin") builtins.push(entry);
else if (entry.kind === "template") templates.push(entry);
else warnings.push(`agents[${index}] skipped: unknown kind ${JSON.stringify(entry.kind)}`);
});
return { builtins, templates, warnings };
}
/** `%NAME%` replaced from `env` (case-insensitive, as Windows reads it); an unknown name stays as written. */
function expandPercentVars(text, env) {
const lookup = (name) => {
const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
return key === undefined ? undefined : env[key];
};
return text.replace(/%([^%]+)%/g, (whole, name) => lookup(name) ?? whole);
}
/** `~` at the start (alone or before a separator) replaced with `home`. */
function expandHome(text, home) {
return text.replace(/^~(?=$|[\\/])/, home);
}
/** The folders a PATH-like string names, quotes stripped. */
function pathDirs(pathValue) {
return String(pathValue || "")
.split(path.delimiter)
.filter(Boolean)
.map((dir) => dir.replace(/^"|"$/g, ""));
}
/** `command` in `dirs`, each extension tried on Windows. The first file hit, or null. */
function findInDirs(command, dirs, extensions) {
for (const dir of dirs) {
const hit = findInDir(command, dir, extensions);
if (hit) return hit;
}
return null;
}
/**
* `command` (a bare name) in `dir`, PATHEXT tried on Windows. Extensions come
* in uppercase there while files are usually lowercase: both cases are tried
* so the path returned names the file as written. The first hit, or null.
*/
function findInDir(command, dir, extensions) {
// A name that already carries an extension (goose.cmd) is tried as written first.
const exts = path.extname(command) ? ["", ...extensions] : extensions;
for (const ext of exts) {
for (const name of new Set([command + ext.toLowerCase(), command + ext])) {
const candidate = path.join(dir, name);
if (isFile(candidate)) return candidate;
}
}
return null;
}
/**
* The saved user and system PATH from the Windows registry (what a newly
* opened terminal gets), as one PATH string, or "" elsewhere / on failure.
* PLAN2CODE_NO_SAVED_PATH keeps it out of test runs, as the launcher's
* addSavedWindowsPath() honors it.
*/
function savedWindowsPath(windows) {
if (!windows || process.env.PLAN2CODE_NO_SAVED_PATH) return "";
const reg = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
const parts = [];
for (const key of ["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "HKCU\\Environment"]) {
let out;
try {
out = spawnSync(reg, ["query", key, "/v", "Path"], { encoding: "utf8", windowsHide: true, timeout: 5000 });
} catch {
continue;
}
const value = parseRegQueryValue(out && out.stdout);
if (value) parts.push(expandPercentVars(value, process.env));
}
return parts.join(path.delimiter);
}
/** The value after the REG_SZ / REG_EXPAND_SZ column in `reg query` output, or null. */
function parseRegQueryValue(output) {
for (const line of String(output || "").split(/\r?\n/)) {
const match = /\sREG_(?:EXPAND_)?SZ\s+(.*)$/.exec(line);
if (match && match[1].trim()) return match[1].trim();
}
return null;
}
let cachedNpmBin; // undefined: not worked out yet; null: no npm folder found.
/**
* npm's global bin folder, worked out once per process: derived without
* spawning where possible (npm_config_prefix, %APPDATA%\npm on Windows),
* `npm config get prefix` with a short timeout only as the fallback, and a
* failure means "no npm folder", never an error.
*/
function npmGlobalBin(windows, env) {
if (cachedNpmBin !== undefined) return cachedNpmBin;
cachedNpmBin = null;
const prefix = env.npm_config_prefix;
if (prefix) {
cachedNpmBin = windows ? prefix : path.join(prefix, "bin");
} else if (windows && env.APPDATA) {
cachedNpmBin = path.join(env.APPDATA, "npm");
} else {
try {
const out = spawnSync("npm", ["config", "get", "prefix"], {
encoding: "utf8",
windowsHide: true,
timeout: 3000,
});
const got = (out && out.stdout ? out.stdout.trim() : "") || "";
if (got) cachedNpmBin = windows ? got : path.join(got, "bin");
} catch {}
}
return cachedNpmBin;
}
/** Tests only: drop the cached npm folder so a later findAgent() derives it again. */
export function resetNpmBinCache() {
cachedNpmBin = undefined;
}
/**
* Where `entry.command` can run from: `{ state, path, where, folder }` with
* `state` "found" (on the process PATH), "outside" (on the saved Windows PATH,
* in npm's global folder or in one of the entry's installDirs) or "missing".
* `where` is "path" | "saved-path" | "npm" | "install-dir" | null and `folder`
* the directory it was found in. A command with a path separator is checked
* as a file, PATHEXT tried on Windows when it has none.
*
* `env` overrides `path`, `pathext`, `savedPath`, `npmBin`, `platform` and
* `home` for tests: pass strings ("" for none); `platform` is "win" | "mac" |
* "linux" (default: this OS).
*/
export function findAgent(entry, env = {}) {
const command = String(entry && entry.command ? entry.command : "").trim().replace(/^"(.*)"$/, "$1");
if (!command) return { state: "missing", path: null, where: null, folder: null };
const platform = env.platform || (process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux");
const windows = platform === "win";
const pathext = env.pathext !== undefined ? env.pathext : process.env.PATHEXT;
const extensions = windows ? String(pathext || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
// A command written as a path is checked as a file, never looked up.
if (command.includes("/") || (windows && command.includes("\\"))) {
const full = path.resolve(command);
const tries = windows && !path.extname(full) ? extensions.map((ext) => full + ext) : [full];
const hit = tries.find(isFile);
return hit
? { state: "found", path: hit, where: "path", folder: path.dirname(hit) }
: { state: "missing", path: null, where: null, folder: null };
}
const searchPath = env.path !== undefined ? env.path : process.env.PATH;
const onPath = findInDirs(command, pathDirs(searchPath), extensions);
if (onPath) return { state: "found", path: onPath, where: "path", folder: path.dirname(onPath) };
const saved = env.savedPath !== undefined ? env.savedPath : savedWindowsPath(windows);
const onSaved = findInDirs(command, pathDirs(saved), extensions);
if (onSaved) return { state: "outside", path: onSaved, where: "saved-path", folder: path.dirname(onSaved) };
const npmBin = env.npmBin !== undefined ? env.npmBin : npmGlobalBin(windows, process.env);
const onNpm = npmBin ? findInDir(command, npmBin, extensions) : null;
if (onNpm) return { state: "outside", path: onNpm, where: "npm", folder: path.dirname(onNpm) };
const home = env.home !== undefined ? env.home : os.homedir();
const dirs = (entry.installDirs && entry.installDirs[platform]) || [];
for (const dir of dirs) {
const expanded = expandPercentVars(expandHome(String(dir), home), env.vars || process.env);
const hit = findInDir(command, expanded, extensions);
if (hit) return { state: "outside", path: hit, where: "install-dir", folder: path.dirname(hit) };
}
return { state: "missing", path: null, where: null, folder: null };
}
+53 -11
View File
@@ -10,7 +10,23 @@
import fs from "node:fs";
import path from "node:path";
export const BUILTIN_AGENT_IDS = ["claude", "devin", "codex"];
import { loadAgentList } from "./agent-lookup.mjs";
import { SHIPPED_AGENTS_FILE } from "./files.mjs";
// The built-in ids come from the shipped list (bin/agents.json), so adding a
// built-in agent needs no code change here. The hard-coded trio is only the
// fallback for a missing or unreadable file. Worked out once at load, never
// throws: a broken shipped file must not take the whole module down.
function shippedBuiltinIds() {
try {
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const ids = builtins.map((a) => a && a.id).filter((id) => typeof id === "string" && id);
if (ids.length) return ids;
} catch {}
return ["claude", "devin", "codex"];
}
export const BUILTIN_AGENT_IDS = shippedBuiltinIds();
export const AGENTS_SCHEMA = 1;
export const MAX_AGENTS = 50;
@@ -169,29 +185,55 @@ function trimDashes(text) {
/**
* 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.
* model is chosen, then `bypassArgs` when checks are off. An argument that is
* exactly `{bypass}` or `{model}` expands to the entry's `bypassArgs` /
* `modelArgs` in place (nothing when off / unset) and that flag is no longer
* appended at the end. `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 modelArgs = entry.modelArgs || DEFAULT_MODEL_ARGS;
const out = [];
let placed = false;
let hasBypass = false;
let hasModel = false;
for (const arg of entry.args || []) {
if (!arg.includes("{prompt}")) {
if (arg === "{bypass}") {
hasBypass = true;
if (bypass) out.push(...(entry.bypassArgs || []));
continue;
}
if (arg === "{model}") {
hasModel = true;
if (model) for (const m of modelArgs) out.push(m.split("{model}").join(model));
continue;
}
if (arg.includes("{bypass}")) hasBypass = true;
if (arg.includes("{model}")) hasModel = true;
if (!arg.includes("{prompt}") && !arg.includes("{model}")) {
out.push(arg);
continue;
}
placed = true;
if (arg === "{prompt}" && blank) continue;
out.push(arg.split("{prompt}").join(text));
if (arg === "{prompt}" && blank) {
placed = true;
continue;
}
let next = arg;
if (next.includes("{prompt}")) {
placed = true;
next = next.split("{prompt}").join(text);
}
if (next.includes("{model}")) next = next.split("{model}").join(model || "");
out.push(next);
}
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 (model && !hasModel) {
for (const arg of modelArgs) out.push(arg.split("{model}").join(model));
}
if (bypass) out.push(...(entry.bypassArgs || []));
if (bypass && !hasBypass) out.push(...(entry.bypassArgs || []));
return out;
}
+6 -3
View File
@@ -4,7 +4,7 @@ import fs from "node:fs";
import path from "node:path";
import { HERE } from "./files.mjs";
import { WORKFLOWS, isBuild } from "./public/skills.js";
import { WORKFLOWS, isBuild, isAgentless } from "./public/skills.js";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
@@ -22,8 +22,11 @@ function workflowLines(width = 78) {
const pad = " ".repeat(lead.length);
const lines = [];
let line = "";
WORKFLOWS.forEach((w, i) => {
const piece = i < WORKFLOWS.length - 1 ? `${w} ·` : w;
// Agent-less modes are opened by the launcher or the app, never by an agent
// typing --workflow, so they stay off the usage list (spec phase-2 note).
const listed = WORKFLOWS.filter((w) => !isAgentless(w));
listed.forEach((w, i) => {
const piece = i < listed.length - 1 ? `${w} ·` : w;
const start = lines.length ? pad : lead;
if (line && (start + line + " " + piece).length > width) {
lines.push(start + line);
+111 -21
View File
@@ -1,6 +1,7 @@
// Plan2Code Web Console - the `open` command: start or resume a session, its server and the browser.
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { spawn } from "node:child_process";
@@ -53,6 +54,7 @@ import { WORKFLOWS, isWorkflow } from "./public/skills.js";
import { startsClean } from "./public/hops.js";
import { snapshot } from "./git-repo.mjs";
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
import { findAgent } from "./agent-lookup.mjs";
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
import {
readPatch,
@@ -139,6 +141,14 @@ export async function cmdOpen() {
if (sid && fs.existsSync(sessionDir(sid))) args.resume = sid;
}
}
// The launcher's setup flow hands this open's page back to the console that
// asked for it: instead of a browser, the session's link is POSTed to that
// console's /handover, which moves the launcher's own tab here. Fresh opens
// outside the app only; a resume or an in-app session keeps its own flow.
const setupAnnounce =
!inApp && !args.resume && !args.session && process.env.PLAN2CODE_SETUP_ANNOUNCE && process.env.PLAN2CODE_SETUP_TOKEN
? { announce: process.env.PLAN2CODE_SETUP_ANNOUNCE, token: process.env.PLAN2CODE_SETUP_TOKEN }
: null;
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -235,12 +245,21 @@ export async function cmdOpen() {
}
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// A setup session carries the hand-over data the launcher needs: which
// CLI it is setting up and the per-session token /handover checks. On
// resume it is rewritten only when --for-cli is passed or the session
// has none yet; a plain resume keeps the existing token valid.
if (args.workflow === "setup" && (args["for-cli"] !== undefined || !s.setup)) {
s.setup = { forCli: args["for-cli"] || null, token: newToken(), created: nowIso() };
}
// The loop lock follows the flag: --loop locks the page, and a resume
// without it (Fix it by hand, from a stop screen) is an ordinary,
// unlocked session.
// unlocked session. `loopExpect` goes with the lock: the app restamps it
// on its next look, so a stale setup never judges a new run.
if (loopMode) s.loop = { driving: true };
else {
delete s.loop;
delete s.loopExpect;
// The loop's cards mean nothing without it, and validate() refuses
// handledBy outside a loop session, which would wedge every post.
s.items = (s.items || []).map(({ handledBy, ...item }) => item);
@@ -270,6 +289,11 @@ export async function cmdOpen() {
if (args.workflow === "dashboard") state.wake = true;
// Locked from the first frame, before the state is first written.
if (loopMode) state.loop = { driving: true };
// The setup session's hand-over data (forCli + the token /handover
// checks), created with the state so the first write already has it.
if (args.workflow === "setup") {
state.setup = { forCli: args["for-cli"] || null, token: newToken(), created: nowIso() };
}
}
// A first payload's meter and folder reports, as `post` takes them: checked
@@ -336,7 +360,7 @@ export async function cmdOpen() {
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -437,6 +461,11 @@ export async function cmdOpen() {
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
const remote = remoteWarning();
const reuseNotes = [];
if (remote.note) reuseNotes.push(remote.note);
// Reuse only happens under --resume/--session, where a setup hand-over is
// never armed, so this path just reopens the page.
if (!args["no-open"]) openBrowser(existing.url);
const inAppReport = await tellApp(inApp, { url: existing.url, sid, workflow: state.workflow });
const [owed, subCursor] = subagentsOwed();
@@ -446,12 +475,14 @@ export async function cmdOpen() {
session: dir,
url: existing.url,
embed: EMBED_API,
...(state.setup && state.setup.token ? { setup: { url: existing.url, token: state.setup.token } } : {}),
...inAppReport,
...(carried ? { pendingResult: true } : {}),
terminalLine: terminalLine(existing.url),
...folders,
...owed,
...remoteWarning(),
...(remote.remote ? { remote: remote.remote } : {}),
...(reuseNotes.length ? { note: reuseNotes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
sweep();
@@ -467,7 +498,7 @@ export async function cmdOpen() {
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -481,9 +512,24 @@ export async function cmdOpen() {
// The early tab went to the port `open` bound. If the server ended up
// anywhere else, that tab is a dead end, so send the browser to the real one.
if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url);
const remote = remoteWarning();
// With a setup hand-over the early tab was never sent at all: only the
// FINAL url is POSTed to the launcher console's /handover, which moves its
// own tab here. A failed hand-over falls back to the browser and a note.
let handoverDone = false;
const notes = [];
if (!args["no-open"]) {
if (setupAnnounce) {
const moved = await postHandover(setupAnnounce, handle.url);
handoverDone = moved === "ok";
// "moved" or "gone" means the first open already spent the hand-over, so
// the browser fallback is quiet; anything else earns the note.
if (moved !== "ok") openBrowser(handle.url);
if (moved === false) notes.push("Could not move the setup tab; opened a new browser tab.");
} else if (handle.url !== started.opened) {
openBrowser(handle.url);
}
}
const remote = remoteWarning();
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const inAppReport = await tellApp(inApp, { url: handle.url, sid, workflow: state.workflow });
@@ -497,7 +543,9 @@ export async function cmdOpen() {
session: dir,
url: handle.url,
embed: EMBED_API,
...(state.setup && state.setup.token ? { setup: { url: handle.url, token: state.setup.token } } : {}),
...inAppReport,
...(handoverDone ? { handover: true } : {}),
port: handle.port,
pid: handle.pid,
...(carried ? { pendingResult: true } : {}),
@@ -522,6 +570,58 @@ async function tellApp(signal, page) {
return { inApp: true, announced };
}
/**
* POST this session's sign-in link to the setup console that asked for it
* (PLAN2CODE_SETUP_ANNOUNCE / _TOKEN): its /handover then moves the
* launcher's own tab here instead of a second browser opening. Loopback http
* only, like in-app.mjs's request(): a foreign or https target is no
* hand-over at all. Resolves "ok" on a 2xx, "moved" on the route's already-
* moved 409, "gone" when nothing answers (the setup console already went
* away, so the fallback is a quiet browser open) and false on any other
* answer, which earns the caller's fallback note. Never throws.
*/
function postHandover(setup, url) {
return new Promise((resolve) => {
let target;
try {
target = new URL("/handover", setup.announce);
} catch {
return resolve(false);
}
if (target.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(target.hostname)) {
return resolve(false);
}
const body = JSON.stringify({ url });
const req = http.request(
target,
{
method: "POST",
timeout: 1500,
headers: {
"x-plan2code-token": setup.token,
"content-type": "application/json",
"content-length": Buffer.byteLength(body),
},
},
(res) => {
res.resume();
res.on("end", () =>
resolve(
res.statusCode === 409
? "moved"
: res.statusCode && res.statusCode >= 200 && res.statusCode < 300
? "ok"
: false
)
);
}
);
req.on("timeout", () => req.destroy());
req.on("error", () => resolve("gone"));
req.end(body);
});
}
/**
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
@@ -563,7 +663,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -616,7 +716,9 @@ async function startServer(project, worktree, sid, dir, { handoff = true } = {})
// No socket to give (the bind failed): the server binds its own, and the
// channel is let go once it has.
released = handOff(child, pre);
if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
// noBrowser: a setup hand-over replaces the early tab; the caller POSTs
// only the final url to the launcher console's /handover instead.
if (pre && !args["no-open"] && !noBrowser) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
} else child.unref();
// Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so
// the browser's comes after the server's: the server's boot is what the
@@ -701,7 +803,7 @@ function openBrowser(url) {
// Linux and friends. WSL first: xdg-open there either is absent or opens a
// Linux browser that cannot reach the Windows host.
if (isWsl()) {
const exe = which("wslview") ? "wslview" : "powershell.exe";
const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
return;
@@ -721,15 +823,3 @@ function isWsl() {
return false;
}
}
function which(bin) {
const dirs = (process.env.PATH || "").split(path.delimiter);
return dirs.some((d) => {
try {
fs.accessSync(path.join(d, bin), fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}
+1 -1
View File
@@ -115,7 +115,7 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms"];
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
+3
View File
@@ -39,6 +39,9 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
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");
// The shipped agent list (builtins + starter templates), same override
// mechanism: install.js drops it in bin/ beside models.json.
export const SHIPPED_AGENTS_FILE = path.join(PLAN2CODE_DIR, "bin", "agents.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.
+5 -18
View File
@@ -12,10 +12,11 @@
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { findAgent } from "./agent-lookup.mjs";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
@@ -154,21 +155,6 @@ public static class Plan2CodeFolderPicker {
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
@@ -233,13 +219,14 @@ export function pickerCommand(start, prompt) {
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
// findAgent is the shared "is this command on PATH" check (agent-lookup.mjs).
if (findAgent({ command: "zenity" }).state === "found") {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
if (findAgent({ command: "kdialog" }).state === "found") {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
+8 -4
View File
@@ -267,7 +267,7 @@ export function workflowLabel(workflow) {
// skill as `additionalReferences`). Any other next step has no browser page
// to open, and asking for one would send the next session looking for
// something that is not there. Derived from skills.js: every entry is one.
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command);
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command).filter(Boolean);
// Rides on the end of the command as part of the skill's argument. Every
// console skill takes it as the answer to "web console or terminal?" instead
@@ -420,8 +420,10 @@ export function resumeCommand({ workflow, specDir } = {}) {
// someone with no way to tell it was wrong.
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
// What follows the command is the entry's `resume` (skills.js). A workflow
// the console does not know (an old session's) resumes as Pathfinder.
const entry = skillFor(workflow) || skillFor("pathfinder");
// the console does not know (an old session's, or an agent-less one like
// setup, which has no command) resumes as Pathfinder.
let entry = skillFor(workflow);
if (!entry || !entry.command) entry = skillFor("pathfinder");
if (dir && entry.resume === "overview") return `${entry.command} ${dir}/overview.md`;
if (dir && entry.resume === "folder") return `${entry.command} ${dir}/pathfinder`;
return entry.command;
@@ -1036,7 +1038,9 @@ export function noteReplyLines(title, text, attachments) {
* below the page's own threshold, and capped at an hour so a typo cannot hide
* a dead session.
*/
export function quietLimitMs(agent, baseMs) {
export function quietLimitMs(agent, baseMs, agentless = false) {
// An agent-less session has nobody to go quiet: the limit is infinite.
if (agentless) return Number.POSITIVE_INFINITY;
if (!agent || agent.status !== "working") return baseMs;
const m = Number(agent.quietMinutes);
if (!Number.isFinite(m) || m <= 0) return baseMs;
+8
View File
@@ -87,6 +87,14 @@ export async function startNewSession(command = "") {
tellApp("new-session");
}
/**
* Tell the app an agent was just found on the setup page: it returns to the
* screen it came from, rechecks, and picks that agent on the launch card.
*/
export function agentFound(id) {
tellApp("agent-found", { id });
}
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
export function tellApp(kind, extra = {}) {
if (!framed()) return;
+4 -2
View File
@@ -237,8 +237,10 @@ export function chatAnswering(frameChat) {
* adrift (anything else), which is also the only signal left once the server
* is gone. An Ask message in hand (`answering`) stretches either to ASK_BUSY_MS.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false }) {
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false, agentless = false }) {
// An agent-less session never goes "offline": there is nobody to hear silence.
if (agentless) return false;
const silent = now - agentLastSeenMs;
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS);
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS, agentless);
return silent > (answering ? Math.max(limit, ASK_BUSY_MS) : limit);
}
+2
View File
@@ -29,6 +29,7 @@ export const HELP_TABS = Object.freeze([
tab("activities", "Activities", false),
tab("finishing", "Stopping and finishing", false),
tab("prefs", "Keyboard and preferences", false),
tab("setup", "Setting up an agent", false),
tab("privacy", "Privacy and where things are saved", false),
]);
@@ -46,6 +47,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (workflow === "setup") return "setup";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v === "map" || v === "draft" || v.startsWith("doc:")) return "docs";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,110 @@
// Plan2Code Web Console - the agents view's pure data helpers.
//
// Everything the agents view computes without touching the page: draft keys,
// saved lookups, dirty checks, summary rows, an agent's shape on the way in
// or out. No DOM access and no imports at module scope, so the page and
// `node --test` both import this file.
// The CLIs the launcher reads a model list for, in table order (the shipped bin/agents.json list).
export const MODEL_CLIS = ["claude", "devin", "codex"];
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
export const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
export function emptyLists() {
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
}
export function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
export function normalizeAgent(agent) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
return agent;
}
// A form's draft key: "cli:<cli>" for a built-in's own models, "agent:<id>"
// for an added agent, "agent:new" for one being added.
export const cliOf = (key) => key.slice("cli:".length);
export const agentId = (key) => key.slice("agent:".length);
// What a draft is checked against in `saved`: a built-in's own models for a
// cli key, a fresh newAgent for "agent:new", the added agent for "agent:<id>".
export function savedEntry(saved, key) {
if (key.startsWith("cli:")) return saved.user[cliOf(key)] || [];
if (key === "agent:new") return newAgent();
return saved.agents.find((a) => a.id === agentId(key));
}
// JSON with object keys sorted, so a label removed and typed back counts as unchanged.
export function canonical(value) {
return JSON.stringify(value, (_, v) =>
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
);
}
export function isDirty(saved, drafts, key) {
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(saved, key));
}
export function nameOf(saved, drafts, key) {
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
const draft = drafts.get(key);
return String((draft && draft.name) || "").trim() || savedEntry(saved, key)?.name || "a new agent";
}
export function modelNames(list) {
return list.map((m) => m.label || m.id);
}
// One row per agent, in order: the built-ins, then the added agents (the
// view appends the v3 orchestrator row itself).
export function summaryRows(saved) {
return [
...MODEL_CLIS.map((cli) => ({
key: "cli:" + cli,
name: BUILT_IN[cli],
command: cli,
models: [...saved.shipped[cli], ...saved.user[cli]],
noneShip: saved.shipped[cli].length === 0,
})),
...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })),
];
}
// The state GET /agents already worked out for a summary row's entry:
// "ok" or "missing" as drawBadge understands them, or null when the entry
// carries no state (an older server), which falls back to a live check.
export function serverStateFor(saved, row) {
const entry = row.key.startsWith("cli:")
? saved.builtins.find((b) => b.id === cliOf(row.key))
: saved.agents.find((a) => a.id === agentId(row.key));
if (!entry || !entry.state) return null;
return entry.state === "found" ? "ok" : "missing";
}
// The list as the server wants it: blank rows and models without an id dropped.
export function cleanAgent(a) {
return {
...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),
};
}
// A template's shape as a new-agent draft, so its Use opens the same form
// a hand-typed agent gets, prefilled rather than saved behind the back.
export function templateDraft(t) {
return {
name: t.name,
command: t.command,
prompt: t.prompt || "/plan2code",
args: t.args || [],
bypassArgs: t.bypassArgs || [],
modelArgs: t.modelArgs && t.modelArgs.length ? t.modelArgs : ["--model", "{model}"],
models: [],
};
}
@@ -0,0 +1,224 @@
// Plan2Code Web Console - the agents view's per-agent form, the detail pane.
//
// What the right pane draws while a draft is being edited: the built-in's
// models fold or an added agent's fields (identity inline, Models and
// Command-line arguments folded), the foot (Save, Discard, the Unsaved
// badge, Save anyway after a 409, Delete with its inline confirm), error
// marking, and the focus save/restore that keeps a redraw from stealing
// where the person was. It only draws and listens: state and fetches live
// in the mount, reached through `ctx`.
import { el } from "../../render.js";
import { listEditor } from "./agents-list-editor.js";
import { BUILT_IN, cliOf, savedEntry, isDirty } from "./agents-data.js";
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(ctx, 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("input", () => {
agent[key] = trim ? input.value.trim() : input.value;
ctx.edited();
});
return input;
}
// The command's Test: where it would run from. Never saves.
function agentTest(ctx, agent) {
const wrap = el("div", "prefs-agents-test");
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...";
result.textContent = await ctx.testCommand(command);
});
wrap.append(test, result);
return wrap;
}
// A folded section: `<details>` whose open state lives on the mount (`which`
// is "modelsOpen" or "argsOpen") so a redraw keeps it where the person left it.
function fold(ctx, which, title, cls, kids) {
const d = el("details", cls);
d.open = ctx[which];
d.addEventListener("toggle", () => (ctx[which] = d.open));
d.append(el("summary", null, title), ...kids);
return d;
}
// A built-in's whole form is its models, so the one fold holds the note, the
// locked shipped list and the editor for the person's own additions.
function builtInFields(ctx, cli, draft) {
const shipped = el("div", "models-list prefs-agents-shipped");
shipped.setAttribute("aria-label", "Comes with Plan2Code");
for (const m of ctx.saved.shipped[cli]) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const note = el("div", "models-note");
note.innerHTML =
"<ul>" +
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
"<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>" +
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
"</ul>";
const comes = el("div", "agent-field");
comes.append(el("span", null, "Comes with Plan2Code"));
if (ctx.saved.shipped[cli].length) comes.append(shipped);
else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
const yours = agentField(
"Models you added",
"models",
listEditor({ list: draft, kind: "models", field: "models", optionalName: false, addLabel: "Add a model", onChange: ctx.edited })
);
return [fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours])];
}
function addedFields(ctx, draft) {
const command = agentField("Command", "command", agentInput(ctx, draft, "command", "Command", "Program to run, such as myagent", true));
command.append(agentTest(ctx, draft));
const models = fold(ctx, "modelsOpen", "Models", "agent-fold", [
agentField(
"Models",
"models",
listEditor({ list: draft.models, kind: "models", field: "models", addLabel: "Add a model", onChange: ctx.edited })
),
]);
const args = fold(ctx, "argsOpen", "Command-line arguments", "agent-fold prefs-agents-args", [
agentField("Arguments", "args", listEditor({ list: draft.args, field: "args", placeholder: "--message={prompt}", addLabel: "Add an argument", aria: "Arguments", onChange: ctx.edited })),
agentField("Bypass arguments", "bypassArgs", listEditor({ list: draft.bypassArgs, field: "bypassArgs", placeholder: "--yes-always", addLabel: "Add an argument", aria: "Bypass arguments", onChange: ctx.edited })),
agentField("Model arguments", "modelArgs", listEditor({ list: draft.modelArgs, field: "modelArgs", placeholder: "--model={model}", addLabel: "Add an argument", aria: "Model arguments", onChange: ctx.edited })),
]);
return [
agentField("Name", "name", agentInput(ctx, draft, "name", "Name", "Name shown in the menu", true)),
command,
agentField("Start prompt", "prompt", agentInput(ctx, draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
models,
args,
];
}
// Save, Discard and the Unsaved badge (shown only while the draft differs),
// the Saved mark's spot, Save anyway after a 409, and Delete agent with its
// confirm on the form itself (never the browser's confirm()).
function formFoot(ctx, key) {
const foot = el("div", "agent-foot prefs-agents-foot");
const save = el("button", "btn small primary prefs-agents-save", "Save");
save.type = "button";
save.addEventListener("click", () => ctx.save(key));
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
discard.type = "button";
discard.addEventListener("click", () => ctx.discard());
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
foot.append(save, discard, badge);
if (ctx.formReplace) {
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
anyway.type = "button";
anyway.addEventListener("click", () => ctx.save(key, { replace: true }));
foot.append(anyway);
}
if (key.startsWith("agent:") && key !== "agent:new") {
if (ctx.confirming) {
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
yes.addEventListener("click", () => ctx.deleteAgent(key));
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
keep.addEventListener("click", () => {
ctx.confirming = false;
ctx.drawForm();
});
foot.append(el("span", "help", "Delete this agent?"), yes, keep);
} else {
const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent");
del.type = "button";
del.addEventListener("click", () => {
ctx.confirming = true;
ctx.drawForm();
});
foot.append(del);
}
}
return foot;
}
// The Unsaved badge and the Save/Discard buttons appear only while the open
// draft differs from what is saved.
export function renderDirty(ctx, key) {
const foot = ctx.$("form").querySelector(".prefs-agents-foot");
if (!foot || key !== ctx.openKey) return;
const dirty = isDirty(ctx.saved, ctx.drafts, key);
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
}
// Which field or button has focus, so a redraw (an id assigned, an error
// marked) puts the person back where they were: { nth, start, end }. What
// they typed is already in the draft the redraw reads.
const FORM_FOCUSABLE = "input, button, summary";
function formFocus(form) {
const active = document.activeElement;
if (!active || !form.contains(active)) return null;
const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreFormFocus(form, at) {
if (!at) return;
const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth];
// A button the redraw hid (Save, once saved) hands focus to the heading.
if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus();
target.focus();
if (target instanceof HTMLInputElement && at.start !== undefined) {
try {
target.setSelectionRange(at.start, at.end);
} catch {}
}
}
export function drawForm(ctx) {
const pane = ctx.$("form");
const key = ctx.openKey;
const draft = ctx.drafts.get(key);
const focus = formFocus(pane);
pane.replaceChildren();
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.tabIndex = -1;
if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(ctx.saved, key).name));
head.appendChild(title);
pane.appendChild(head);
const fields = el("div", "prefs-agents-fields");
fields.append(...(key.startsWith("cli:") ? builtInFields(ctx, cliOf(key), draft) : addedFields(ctx, draft)));
pane.appendChild(fields);
if (ctx.formError) {
for (const input of pane.querySelectorAll("input")) {
if (input.dataset.field === ctx.formError.field) input.classList.add("invalid");
}
pane.appendChild(el("p", "agent-error", ctx.formError.error));
}
if (ctx.formReplace && ctx.formReplace.length) pane.appendChild(el("p", "agent-error", ctx.formReplace.join(" ")));
pane.appendChild(formFoot(ctx, key));
renderDirty(ctx, key);
restoreFormFocus(pane, focus);
}
@@ -0,0 +1,74 @@
// Plan2Code Web Console - the agents form's row-list editor (arguments and models).
//
// The shared editor behind the three argument lists (args, bypassArgs,
// modelArgs) and the models list. Text rows hold one input; model rows hold an
// id and a name for the menu. Which list it edits and how its rows look come
// from the options, so each field configures its own copy.
import { el } from "../../render.js";
// `list` is the live array being edited (strings, or {id, label?} models).
// `kind` "text" | "models". `onChange` runs after every edit, add or remove.
export function listEditor({ list, kind = "text", field = kind === "models" ? "models" : "", placeholder = "", addLabel = "Add", optionalName = true, aria = "", onChange = () => {} }) {
const box = el("div", "agent-rows");
box.dataset.field = field;
const draw = () => {
box.replaceChildren();
list.forEach((item, i) => {
const row = el("div", kind === "models" ? "agent-row model" : "agent-row");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
list.splice(i, 1);
draw();
onChange();
});
if (kind === "models") {
const id = el("input");
id.value = item.id || "";
id.placeholder = optionalName ? "Model id, for {model}" : "Model id";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = item.label || "";
label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
id.addEventListener("input", () => {
item.id = id.value.trim();
onChange();
});
label.addEventListener("input", () => {
const text = label.value.trim();
if (text || !optionalName) item.label = text;
else delete item.label;
onChange();
});
row.append(id, label, remove);
} else {
const input = el("input");
input.value = item;
input.placeholder = placeholder;
input.setAttribute("aria-label", aria);
input.dataset.field = field;
input.addEventListener("input", () => {
list[i] = input.value.trim();
onChange();
});
row.append(input, remove);
}
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
list.push(kind === "models" ? (optionalName ? { id: "" } : { id: "", label: "" }) : "");
draw();
onChange();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return box;
}
@@ -0,0 +1,256 @@
// Plan2Code Web Console - the agents view's collection side.
//
// The master-detail's left column for both mounts: Preferences draws one
// pickable row per agent (name, command, found badge, its models) plus the
// v3 orchestrator placeholder; the setup page draws the same rows with their
// found/outside/missing badges and the starter templates. While no form is
// open the right pane is this module's too: the empty text, or the picked
// entry's state and way forward (Start, Use it from here, the install lines).
// It only draws and listens: every fetch and every piece of state lives in
// the mount, reached through `ctx`.
import { el, copyButton } from "../../render.js";
import { summaryRows, serverStateFor, modelNames, agentId, templateDraft } from "./agents-data.js";
/* ------------------------------------------------------------- badges */
export const BADGES = {
ok: "Found",
missing: "Not found on PATH",
unknown: "Not checked",
};
export function drawBadge(badge, state) {
badge.textContent = BADGES[state];
badge.classList.remove("ok", "missing");
if (state !== "unknown") badge.classList.add(state);
}
/* --------------------------------------------------------- the prefs rows */
// One pickable row: the whole row is the Edit button, so it carries the
// data-key and the "Edit <name>" aria-label the flows rely on.
function prefsRow(ctx, row, check) {
const r = el("button", "split-row");
r.type = "button";
r.dataset.key = row.key;
r.setAttribute("aria-label", "Edit " + row.name);
r.setAttribute("aria-current", ctx.openKey === row.key ? "true" : "false");
r.addEventListener("click", () => ctx.pick(row.key));
r.appendChild(el("span", "row-name", row.name));
const sub = el("span", "row-sub");
sub.id = "row-sub-" + row.key;
r.setAttribute("aria-describedby", sub.id);
sub.appendChild(el("code", null, row.command));
const badge = el("span", "prefs-badge");
const known = serverStateFor(ctx.saved, row);
if (known) {
ctx.found.set(row.key, { command: row.command, state: known });
drawBadge(badge, known);
} else {
const last = ctx.found.get(row.key);
if (last && last.command === row.command) drawBadge(badge, last.state);
else {
badge.textContent = "Checking...";
check.push(row);
}
}
sub.appendChild(badge);
const names = modelNames(row.models);
sub.appendChild(el("span", "row-models", names.length ? `${names.length}: ${names.join(", ")}` : "None"));
r.appendChild(sub);
if (row.noneShip) r.appendChild(el("span", "help row-note", `No models ship for ${row.name} yet; open this row to add your own.`));
return r;
}
/* --------------------------------------------------------- the setup rows */
// The badge a setup row's state gets: the glanceable half, with the pane
// beside it saying what the state means and what can be done about it.
function setupStateBadge(entry) {
const badge = el("span", "prefs-badge");
if (entry.state === "found") {
badge.textContent = "Found";
badge.classList.add("ok");
} else if (entry.state === "outside") {
badge.textContent = "Found outside PATH";
badge.classList.add("missing");
} else if (entry.state === "missing") {
badge.textContent = "Not found";
badge.classList.add("missing");
} else {
badge.textContent = "Not checked";
}
return badge;
}
// A pickable setup row: selecting it fills the pane with the entry's state,
// not a form (custom agents get an Edit in that pane).
function setupRow(ctx, entry, key, badgeFor) {
const r = el("button", "split-row");
r.type = "button";
r.dataset.key = key;
r.setAttribute("aria-current", ctx.setupSel === key ? "true" : "false");
r.addEventListener("click", () => ctx.pickSetup(key));
r.appendChild(el("span", "row-name", entry.name || entry.id));
const sub = el("span", "row-sub");
sub.appendChild(el("code", null, entry.command));
if (badgeFor) sub.appendChild(badgeFor(entry));
r.appendChild(sub);
return r;
}
/* ---------------------------------------------------------- the list itself */
// The left column, whichever the mode: rows, the placeholder or templates,
// then the scaffold's Add agent button pinned last (grabbed before the list
// is cleared: a live query for it after replaceChildren finds nothing).
export function renderSummary(ctx) {
const list = ctx.$("table");
const add = ctx.$("add");
list.replaceChildren();
if (ctx.mode === "setup") {
const cli = ctx.forCli();
const builtins = [...ctx.saved.builtins].sort((a, b) => (a.id === cli ? -1 : b.id === cli ? 1 : 0));
for (const b of builtins) list.appendChild(setupRow(ctx, b, "setup:" + b.id, setupStateBadge));
for (const a of ctx.saved.agents) list.appendChild(setupRow(ctx, a, "setup:" + a.id, setupStateBadge));
if (ctx.saved.templates.length) {
list.appendChild(el("div", "split-list-head", "Or start from a template"));
for (const t of ctx.saved.templates) list.appendChild(setupRow(ctx, t, "setup:" + t.name));
}
} else {
const check = [];
for (const row of summaryRows(ctx.saved)) list.appendChild(prefsRow(ctx, row, check));
if (ctx.saved.templates.length) {
list.appendChild(el("div", "split-list-head", "Or start from a template"));
for (const t of ctx.saved.templates) list.appendChild(setupRow(ctx, t, "setup:" + t.name));
}
const soon = el("div", "split-row soon");
soon.append(el("span", "row-name", "v3 orchestrator"), el("span", "row-sub", "Nothing to set yet."));
list.appendChild(soon);
if (check.length) ctx.checkFound(check);
}
if (add) list.appendChild(add);
}
/* ------------------------------------------------ the pane while nothing is open */
// How the person puts the found folder on PATH themselves, for the OS their
// browser reports. The server already knows where the agent is; this is the
// alternative to letting Plan2Code save that location for it.
function pathNote(folder) {
const os = navigator.platform || navigator.userAgent || "";
if (/win/i.test(os)) {
return "Or add its folder to your PATH: Settings > System > About > Advanced system settings > Environment Variables.";
}
if (/mac/i.test(os)) return `Or add its folder to PATH in ~/.zshrc: export PATH="${folder}:$PATH"`;
return `Or add its folder to PATH in ~/.bashrc: export PATH="${folder}:$PATH"`;
}
// The state area of a picked setup entry: the badge, what the state means,
// and the one thing to do about it (Start, Use it from here, the install lines).
function setupStateArea(ctx, entry) {
const area = el("div", "setup-agent-state");
const badge = setupStateBadge(entry);
if (entry.state === "found") {
const line = el("p", "setup-agent-line");
line.appendChild(badge);
if (entry.path) line.append(" ", el("span", "help", entry.path));
area.appendChild(line);
// A session opened for one CLI only offers that one's Start.
if (ctx.onStart && (!ctx.forCli() || entry.id === ctx.forCli())) {
const start = el("button", "btn small primary", "Start with this agent");
start.type = "button";
start.addEventListener("click", () => ctx.onStart(entry));
area.appendChild(start);
}
} else if (entry.state === "outside") {
const line = el("p", "setup-agent-line");
line.append(badge, ` Found at ${entry.path || ""}, but not on PATH`);
area.appendChild(line);
const use = el("button", "btn small", "Use it from here");
use.type = "button";
use.addEventListener("click", () => ctx.useFromHere(entry));
area.appendChild(use);
area.appendChild(el("p", "help", entry.folder ? pathNote(entry.folder) : "Or add its folder to your PATH yourself."));
} else {
area.appendChild(badge);
if (entry.state === "missing") {
for (const inst of Array.isArray(entry.install) ? entry.install : []) {
const d = el("div", "setup-install");
d.append(el("span", null, inst.label), el("code", null, inst.run));
if (inst.note) d.appendChild(el("span", "help", inst.note));
d.appendChild(copyButton(inst.run));
area.appendChild(d);
}
if (entry.installUrl) {
const a = el("a", null, "Install page");
a.href = entry.installUrl;
a.target = "_blank";
a.rel = "noopener";
area.appendChild(a);
}
}
}
return area;
}
// A template's pane half: its name, command and note with a Use that opens
// the new-agent form prefilled, shared by both mounts.
function templatePane(ctx, template) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, template.name), el("code", null, template.command));
head.appendChild(title);
box.appendChild(head);
if (template.note) box.appendChild(el("p", "help", template.note));
const use = el("button", "btn small", "Use this template");
use.type = "button";
use.addEventListener("click", () => {
// Cloned: the form edits the draft in place, and saved.templates is
// the server's copy the next load draws from.
ctx.drafts.set("agent:new", structuredClone(templateDraft(template)));
ctx.pick("agent:new");
});
box.appendChild(use);
return box;
}
// The detail pane with no form open: the picked entry's state and way
// forward, a template's note and Use, or the empty text. In Preferences a
// template row drives the same pane; every other row opens a form.
export function drawSummaryPane(ctx) {
const pane = ctx.$("form");
pane.replaceChildren();
const sel = ctx.setupSel;
const all = [...ctx.saved.builtins, ...ctx.saved.agents];
const entry = sel && all.find((e) => "setup:" + e.id === sel);
const template = sel && !entry && ctx.saved.templates.find((t) => "setup:" + t.name === sel);
if (ctx.mode !== "setup") {
pane.appendChild(template ? templatePane(ctx, template) : el("div", "split-empty", "Pick an agent on the left to edit it here."));
return;
}
if (entry) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, entry.name || entry.id), el("code", null, entry.command));
head.appendChild(title);
box.append(head, setupStateArea(ctx, entry));
if (ctx.saved.agents.includes(entry)) {
const edit = el("button", "btn small", "Edit");
edit.type = "button";
edit.setAttribute("aria-label", "Edit " + (entry.name || entry.id));
edit.addEventListener("click", () => ctx.pick("agent:" + entry.id));
box.appendChild(edit);
}
pane.appendChild(box);
return;
}
if (template) {
pane.appendChild(templatePane(ctx, template));
return;
}
pane.appendChild(el("div", "split-empty", "Pick an agent on the left to see its state and the way forward."));
}
@@ -66,7 +66,7 @@ export function openPrefs(tab) {
}
// The unsaved prompt on screen: { resolve, promise, from }, or null. `from`
// is what had focus when it asked (the tab, Close, Back to summary, a field).
// is what had focus when it asked (the tab, Close, another agent's row, a field).
let asking = null;
// Everything in the dialog but the prompt, kept out of reach while it asks.
@@ -85,7 +85,7 @@ function endAsking(go) {
}
// Before anything leaves an agent form with an unsaved edit (Close, Esc, a
// backdrop click, another tab, Back to summary): Save, Discard or Keep
// backdrop click, another tab, another agent's row): Save, Discard or Keep
// editing, asked inside the dialog. Resolves true when it may go on.
export function confirmUnsaved() {
if (!hooks.hasUnsaved()) return Promise.resolve(true);
+182
View File
@@ -0,0 +1,182 @@
// Plan2Code Web Console - the agent-less setup screen: pick or install an
// agent, then hand the session to it. Only defines.
//
// `plan2code` opens this page when no agent can run. The list it draws is the
// same agents view User Preferences drives (mountAgentsView, handed in by
// core.js because a screen never imports a screen), in its "setup" mode: a
// row per agent with its found state and the one thing to do about it.
// Start posts the pick as a session action the waiting launcher collects;
// the new agent's console then calls /handover, which sends this page the
// `move` event that carries it across. The grace line only shows if that
// move never comes.
import { agentFound, framed } from "../app-bridge.js";
import { el } from "../render.js";
import { hooks, page, redraw, saveNow } from "../state.js";
const $ = (id) => document.getElementById(id);
// The screen, its mounted agents view, and the start it is waiting on. All
// module-level because renderMain clears the column every pass: re-attaching
// the SAME root keeps the DOM, the open form and every typed character.
let root = null;
let view = null;
let moved = false;
let graceTimer = null;
// Once the grace wait has ended the line stays drawn: a redraw rebuilds the
// pane from this flag rather than the element.
let graceShown = false;
// How long the starting pane waits for the `move` event before it points at
// the terminal. Overridable in tests through window.__P2C_SETUP_GRACE_MS.
const GRACE_MS = () => Number(window.__P2C_SETUP_GRACE_MS) || 120000;
// The skill's own Planny acting out "setup", cloned from the template in
// index.html so the drawing stays markup; the dock's Planny is the fallback.
function setupStage() {
const stage = el("div", "setup-stage");
const art = $("start-poses")?.content.querySelector('[data-pose="setup"]');
if (art) stage.appendChild(art.cloneNode(true));
else {
const bot = $("planny")?.cloneNode(true);
if (bot) {
bot.removeAttribute("id");
stage.appendChild(bot);
}
}
return stage;
}
// The pick is sent: the launcher turns it into a session that hands this
// tab over. `entry` is the agent row's object ({ id, name, ... }).
async function onStart(entry) {
const label = entry.name || entry.id;
page.local.setupStart = { id: entry.id, label, at: Date.now() };
saveNow();
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }),
});
if (!res.ok) throw new Error("refused");
} catch {
// The send never landed, so the wait never starts: put the list back.
delete page.local.setupStart;
saveNow();
hooks.banner("That did not go through, but the console is still up. Nothing was lost, try again.", "warn");
redraw();
return;
}
redraw();
armGrace();
}
// The grace wait for the `move` event: the new session should take this tab
// over itself, and only a wait that ends unmoved earns the terminal hint.
function armGrace() {
clearTimeout(graceTimer);
graceTimer = setTimeout(() => {
graceTimer = null;
if (moved || !page.local.setupStart) return;
graceShown = true;
for (const note of document.querySelectorAll(".setup-no-page, .setup-back")) note.hidden = false;
}, GRACE_MS());
}
// The `move` event reached the page (core.js follows the url itself); this
// only stands the grace wait down so the hint can never appear mid-handover.
export function setupMoved(url) {
moved = true;
clearTimeout(graceTimer);
graceTimer = null;
}
// The pick-list pane, built once and re-attached every render. mountAgents
// is core.js's copy of mountAgentsView (a screen never imports a screen), so
// a bare import under a test simply leaves the list unmounted.
function buildRoot(mountAgents) {
const box = el("div", "setup-screen");
box.appendChild(setupStage());
box.appendChild(el("p", "card-kicker", "Agent setup"));
box.appendChild(el("h2", null, "No agent yet"));
box.appendChild(
el(
"p",
"help",
"Plan2Code runs your AI agent for you, but it could not find one on this computer. Pick one below, or install one and press Check again."
)
);
const agents = el("div", "setup-agents");
box.appendChild(agents);
const actions = el("div", "setup-actions");
const again = el("button", "btn small", "Check again");
again.type = "button";
again.addEventListener("click", () => view?.load());
actions.appendChild(again);
box.appendChild(actions);
if (mountAgents) {
// The setup page has no unsaved prompt of its own: picking a row is
// always free. The pick itself, not the dialog, is what can be lost.
view = mountAgents(agents, {
mode: "setup",
// A getter, not a snapshot: use-path on the asked-for built-in rewrites
// state.setup.forCli to the saved id, and the Start gate must see it.
forCli: () => (page.S && page.S.setup && page.S.setup.forCli) || null,
// In the app's window there is no waiting launcher to Start for: the
// app picks the found agent on its own launch card instead, and hears
// of it through agent-found.
onStart: framed() ? null : onStart,
onFound: framed() ? (entry) => agentFound(entry.id) : null,
confirmUnsaved: () => Promise.resolve(true),
});
view.wire();
view.load();
}
return box;
}
// The waiting pane: same bones as the starting screens, plus the hint the
// grace timer reveals if the new session never calls back.
function startingPane(started) {
const pane = el("div", "launching setup-starting");
pane.appendChild(setupStage());
pane.appendChild(el("p", "card-kicker", "On it"));
pane.appendChild(el("h2", "launch-title", `Starting ${started.label}…`));
pane.appendChild(el("p", "launch-hint", "This page moves to your session the moment it opens. No need to touch anything."));
const noPage = el("p", "help setup-no-page", `${started.label} did not open a page. Look at the terminal where you ran plan2code.`);
noPage.hidden = !graceShown;
pane.appendChild(noPage);
// A wait that died unmoved should not park the page on "Starting" forever:
// once the grace hint is up, the way back to the pick list shows beside it.
const back = el("button", "btn small setup-back", "Show the agent list again");
back.type = "button";
back.hidden = !graceShown;
back.addEventListener("click", () => {
delete page.local.setupStart;
graceShown = false;
saveNow();
redraw();
});
pane.appendChild(back);
return pane;
}
// The agent-less session's whole main column. The root is persistent rather
// than drawn each pass, so an in-progress form survives every re-render.
export function renderSetup(main, mountAgents) {
const started = page.local.setupStart;
if (started) {
// A reload mid-wait starts the wait over: the move may have gone unheard
// while the page was down, and the hint is its fallback.
if (!graceTimer && !moved && !graceShown) armGrace();
main.appendChild(startingPane(started));
return;
}
if (graceTimer) {
clearTimeout(graceTimer);
graceTimer = null;
}
if (!root) root = buildRoot(mountAgents);
main.appendChild(root);
}
+5 -1
View File
@@ -6,6 +6,7 @@
import { page, redraw } from "./state.js";
import { boardAwaiting } from "./git-board.js";
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
import { isAgentless } from "./skills.js";
import { activityLabel, workingLine } from "./labels.js";
import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
@@ -203,7 +204,7 @@ export function workingMs() {
// The three silence thresholds below, stretched while the agent has said a
// long quiet stretch is normal (a build task). See quietLimitMs.
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs);
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs, isAgentless(page.S && page.S.workflow));
// What the agent says it is doing right now, when it has said: "Task 3 of 9:
// the user service". Only meaningful while it is working. A build's line is
@@ -232,6 +233,8 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
// An agent answering an Ask message is out of `wait` too, and busy rather than
// gone, so it gets ASK_BUSY_MS before anything calls it adrift.
export function agentAdrift() {
// An agent-less session has nobody to be adrift: silence means nothing there.
if (isAgentless(page.S && page.S.workflow)) return false;
if (!page.agentLastSeen || page.gone || finish()) return false;
const silent = Date.now() - Date.parse(page.agentLastSeen);
const limit = page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS);
@@ -266,6 +269,7 @@ export const stranded = () => page.pendingResult && agentAdrift();
// turn ended while the person was away) and the press sits saved until it
// is woken.
export function pressStranded() {
if (isAgentless(page.S && page.S.workflow)) return false;
if (!finish() || page.gone || !page.pendingResult || !page.agentLastSeen) return false;
if (!page.local.afterBuild || page.local.afterBuild === "done") return false;
return Date.now() - Date.parse(page.agentLastSeen) > UNCOLLECTED_MS;
+25 -2
View File
@@ -64,7 +64,7 @@ function skill(entry) {
const card = entry.card ? Object.freeze({ ...entry.card }) : null;
const states = Array.isArray(entry.states) ? Object.freeze([...entry.states]) : entry.states;
const greyed = entry.greyed ? Object.freeze({ ...entry.greyed }) : null;
return Object.freeze({ marksNext: false, ...entry, command: "/" + entry.skill, states, greyed, card });
return Object.freeze({ marksNext: false, ...entry, command: entry.skill ? "/" + entry.skill : null, states, greyed, card });
}
export const SKILLS = Object.freeze([
@@ -446,6 +446,26 @@ export const SKILLS = Object.freeze([
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
}),
// The agent-less setup page: opened by the `plan2code` command (or the app)
// when no agent can run. It is a workflow, not a skill: no command, no card,
// and every list derived from FLOW_SKILLS leaves it out (no card, no command,
// no resume, metered false). `agentless` switches off the agent-silence
// states, the Ask and Subagents tabs, the Notebook send and most of the top
// bar, all checked through isAgentless().
skill({
skill: null,
workflow: "setup",
agentless: true,
label: "Agent setup",
name: "Setup",
pose: "setup",
builds: false, phased: false, metered: false, templates: false,
weight: null, started: null, ran: null, resume: null,
subagents: null,
states: null,
greyed: null,
card: null,
}),
skill({
skill: "plan2code",
workflow: "dashboard",
@@ -466,7 +486,8 @@ export const SKILLS = Object.freeze([
export const FLOW_SKILLS = Object.freeze(SKILLS.filter((s) => !s.appOnly));
const BY_WORKFLOW = new Map(FLOW_SKILLS.map((s) => [s.workflow, s]));
const BY_SKILL = new Map(FLOW_SKILLS.map((s) => [s.skill, s]));
// Entries with no skill (the agent-less setup page) are not looked up by one.
const BY_SKILL = new Map(FLOW_SKILLS.filter((s) => s.skill).map((s) => [s.skill, s]));
// Every workflow name the console knows, in SKILLS order.
export const WORKFLOWS = Object.freeze(FLOW_SKILLS.map((s) => s.workflow));
@@ -490,6 +511,8 @@ export const isBuild = (workflow) => Boolean(skillFor(workflow)?.builds);
export const isPhased = (workflow) => Boolean(skillFor(workflow)?.phased);
export const isMetered = (workflow) => Boolean(skillFor(workflow)?.metered);
export const takesTemplates = (workflow) => Boolean(skillFor(workflow)?.templates);
/** A session with no agent behind it: silence states, Ask and helpers stay off. */
export const isAgentless = (workflow) => Boolean(skillFor(workflow)?.agentless);
/** The Subagents switch's instruction for a workflow, or null when it is not offered. */
export function subagentsFor(workflow) {
+157
View File
@@ -0,0 +1,157 @@
/* agents.css: the Agents & models view - a master-detail split shared by User
Preferences' tab and the agent-less setup page. The list is pinned left;
the right pane holds the picked agent's form (prefs), the picked entry's
state and way forward (setup), or the empty text. Every rule that used to
be spread over prefs.css and responsive.css lives here. */
/* ------------------------------------------------------------- the mount */
.prefs-agents { display: grid; gap: 10px; }
.prefs-agents > .help { margin: 0; }
.prefs-agents [hidden], .setup-agents [hidden] { display: none; }
[data-av="status"]:empty { display: none; }
[data-av="status"].error { color: var(--danger, #d64545); }
/* ----------------------------------------------------------- the split */
.split {
display: grid;
grid-template-columns: 250px minmax(0, 1fr);
border: 1px solid var(--rule-2);
border-radius: var(--radius);
overflow: hidden;
background: var(--panel);
}
.split-list {
border-right: 1px solid var(--rule);
display: flex;
flex-direction: column;
min-width: 0;
background: var(--panel-2);
}
.split-list-head { padding: 8px 12px 2px; color: var(--ink-3); font-size: 13px; }
.split-row {
appearance: none;
font: inherit;
text-align: left;
border: 0;
border-bottom: 1px solid var(--rule);
background: transparent;
color: var(--ink);
padding: 10px 12px;
cursor: pointer;
display: grid;
gap: 2px;
}
.split-row:hover { background: var(--accent-soft); }
.split-row[aria-current="true"] { background: var(--accent-soft); box-shadow: inset 3px 0 0 var(--accent); }
.split-row .row-name { font-weight: 600; font-size: 13.5px; }
.split-row .row-sub { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-3); flex-wrap: wrap; }
.split-row .row-sub code { color: var(--ink-3); }
.split-row .row-models { color: var(--ink-2); overflow-wrap: anywhere; }
.split-row .row-note { display: block; margin-top: 2px; font-size: 12px; }
.split-row.soon { color: var(--ink-3); font-style: italic; cursor: default; }
.split-add { margin: 8px; align-self: flex-start; }
.split-pane {
padding: 16px 18px 30px;
display: grid;
gap: 12px;
align-content: start;
min-width: 0;
}
.split-empty { color: var(--ink-3); display: grid; place-items: center; min-height: 240px; text-align: center; }
/* ------------------------------------------------------------- badges */
.prefs-badge, .prefs-unsaved-badge {
display: inline-block;
font-size: 11.5px;
line-height: 1.5;
padding: 0 7px;
border-radius: 10px;
background: var(--panel-2);
color: var(--ink-3);
white-space: nowrap;
}
.split-row .prefs-badge { background: var(--panel); }
.prefs-badge.ok { color: var(--ok); }
.prefs-badge.missing { color: var(--warn); }
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
/* -------------------------------------------------------------- the form */
.form-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-title:focus { outline: none; }
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; }
.prefs-agents-fields input { min-width: 0; }
.prefs-agents-fields input.invalid, .split-pane input.invalid { border-color: var(--danger, #d64545); }
.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; }
.prefs-agents-test .agent-test-result { flex: 1 1 auto; }
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.prefs-agents-test .help { margin: 0; }
.prefs-agents-none { margin: 0; }
/* A folded section (Models, Command-line arguments): the picked design keeps
both behind a summary line until opened. */
.agent-fold { display: grid; gap: 8px; }
.agent-fold > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
.agent-fold[open] > summary { margin-bottom: 4px; }
.agent-fold > .agent-field + .agent-field, .agent-fold > .models-note + .agent-field { margin-top: 8px; }
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
/* ------------------------------------------------------------- models lists */
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
/* --------------------------------------------------------- the setup pane */
.setup-detail { display: grid; gap: 12px; align-content: start; }
.setup-agent-state { display: grid; gap: 6px; }
.setup-agent-line {
margin: 0;
color: var(--ink-2);
font-size: 13px;
}
.setup-install {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0 0;
flex-wrap: wrap;
}
.setup-install code {
background: var(--panel-2);
border-radius: 6px;
padding: 2px 7px;
font-size: 12px;
}
/* --------------------------------------------------------- narrow screens */
@media (max-width: 720px) {
.split { grid-template-columns: 1fr; }
.split-list { border-right: 0; border-bottom: 1px solid var(--rule); max-height: 260px; overflow: auto; }
}
+8 -2
View File
@@ -126,11 +126,12 @@
they carry view-box origins rather than their own boxes. */
.planny .arms { display: none; }
.planny .a-rest { display: inline; }
.planny:is(.is-point, .is-work, .is-done, .is-gone, .is-adrift) .a-rest { display: none; }
.planny:is(.is-point, .is-work, .is-done, .is-gone, .is-adrift, .is-setup) .a-rest { display: none; }
.planny.is-point .a-point,
.planny.is-work .a-work,
.planny.is-done .a-done,
.planny.is-gone .a-gone { display: inline; }
.planny.is-gone .a-gone,
.planny.is-setup .a-setup { display: inline; }
.planny .arm.wave,
.planny .arm.pump-l,
.planny .arm.pump-r { transform-box: view-box; }
@@ -182,6 +183,11 @@
.planny.is-gone { opacity: 0.5; }
.planny.is-gone .eye { fill: var(--warn); animation: none; transform: scaleY(0.12); }
/* The setup page, waiting on a pick: the point look without the work
spinner -- a friendly lean and wave, star lit, while nothing runs yet. */
.planny.is-setup { animation: planny-lean 2.6s ease-in-out infinite; }
.planny.is-setup .eye { fill: var(--accent); }
/* ------------------------------------------------------ mood variants
Each mood above is a family, not a single drawing: app.js rolls a v0/v1/v2
+26 -66
View File
@@ -1,5 +1,6 @@
/* prefs.css: User Preferences' tabs (the side list, the narrow strip), the Saved
mark, the Agents & models table and form, and the unsaved prompt. */
mark, and the unsaved prompt. The Agents & models view's rules moved to
agents.css when it became a master-detail split. */
/* --------------------------------------------------------- tabs and panels */
@@ -73,69 +74,6 @@
.prefs-saved.is-saved { opacity: 1; }
}
/* --------------------------------------------------------- Agents & models */
.prefs-agents { display: grid; gap: 10px; }
.prefs-agents > .help { margin: 0; }
.prefs-agents [hidden] { display: none; }
#agents-status:empty { display: none; }
#agents-status.error { color: var(--danger, #d64545); }
#agents-add { justify-self: start; }
.prefs-agents-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.prefs-agents-table th {
text-align: left;
font-weight: 600;
font-size: 12px;
color: var(--ink-3);
padding: 4px 8px;
border-bottom: 1px solid var(--rule-2);
}
.prefs-agents-table td { padding: 8px; border-bottom: 1px solid var(--rule-2); vertical-align: top; }
.prefs-agents-name span, .prefs-agents-name code { display: block; }
.prefs-agents-name code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-name .help { margin-top: 2px; font-size: 12px; }
.prefs-agents-models { color: var(--ink-2); overflow-wrap: anywhere; }
.prefs-agents-edit { text-align: right; }
.prefs-agents-soon td { color: var(--ink-3); font-style: italic; }
.prefs-badge, .prefs-unsaved-badge {
display: inline-block;
font-size: 11.5px;
line-height: 1.5;
padding: 0 7px;
border-radius: 10px;
background: var(--panel-2);
color: var(--ink-3);
white-space: nowrap;
}
.prefs-badge.ok { color: var(--ok); }
.prefs-badge.missing { color: var(--warn); }
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
.prefs-agents-form { display: grid; gap: 10px; }
.prefs-agents-back { justify-self: start; }
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-title:focus { outline: none; }
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px 14px; }
.prefs-agents-fields > .models-note,
.prefs-agents-fields > [data-field="models"],
.prefs-agents-fields > .prefs-agents-args,
.prefs-agents-fields > .agent-field:has(> .models-list),
.prefs-agents-fields > .agent-field:has(> .prefs-agents-none) { grid-column: 1 / -1; }
.prefs-agents-form input { min-width: 0; }
.prefs-agents-form input.invalid { border-color: var(--danger, #d64545); }
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.prefs-agents-test .help { margin: 0; }
.prefs-agents-none { margin: 0; }
.prefs-agents-args { display: grid; gap: 8px; }
.prefs-agents-args > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
.prefs-agents-args[open] > summary { margin-bottom: 4px; }
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
/* --------------------------------------------------------- unsaved prompt */
/* Over the dialog, inside it: never the browser's confirm(). */
@@ -183,6 +121,28 @@
}
.prefs-tab[aria-selected="true"] { border-bottom-color: var(--accent); }
.prefs-tab-hint { display: none; }
.prefs-agents-models { display: none; }
.prefs-agents-fields { grid-template-columns: 1fr; }
}
/* ------------------------------------------------------- the setup page
The agent-less setup screen (workflow "setup"): Planny's pose over the
agents view, which now draws its own split inside .setup-agents. */
.setup-screen {
max-width: 640px;
margin: 0 auto;
padding: 24px 16px 40px;
display: flex;
flex-direction: column;
gap: 8px;
}
.setup-stage { display: flex; justify-content: center; }
.setup-stage .pose { width: 150px; height: auto; }
.setup-screen h2 { margin: 0; }
.setup-actions {
display: flex;
align-items: center;
gap: 10px;
margin: 14px 0 0;
}
.setup-no-page { margin: 10px 0 0; }
.setup-no-page[hidden] { display: none; }
+169 -10
View File
@@ -14,6 +14,7 @@ import crypto from "node:crypto";
import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_AGENTS_FILE,
SHIPPED_MODELS_FILE,
USER_AGENTS_FILE,
USER_MODELS_FILE,
@@ -23,10 +24,12 @@ import {
nowIso,
readJson,
readText,
updateState,
withStateLock,
writeJsonAtomic,
} from "./files.mjs";
import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { AGENTS_SCHEMA, makeId, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { findAgent, loadAgentList } from "./agent-lookup.mjs";
import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs";
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
@@ -75,6 +78,9 @@ const WORKSPACE_EDITS = { "/workspace/add": "addFolder", "/workspace/edit": "edi
const ROUTES = [
{ path: "/health", open: true, run: health },
{ match: (p) => p.startsWith("/s/"), open: true, run: signIn },
// Open on purpose: the caller is another Plan2Code process handing the
// setup tab over, not a cookied browser. It has its own token (state.setup).
{ path: "/handover", method: "POST", open: true, run: handover },
{ path: "/", method: "GET", run: page },
{ match: (p, req) => req.method === "GET" && SERVABLE.has(p.slice(1)), run: publicFile },
{ path: "/overview", method: "GET", run: overview },
@@ -92,6 +98,7 @@ const ROUTES = [
{ path: "/agents", method: "GET", run: agentsGet },
{ path: "/agents", method: "POST", origin: true, run: agentsPost },
{ path: "/agents/test", method: "POST", origin: true, run: agentsTest },
{ path: "/agents/use-path", method: "POST", origin: true, run: agentsUsePath },
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
{ path: "/upload", method: "POST", origin: true, run: upload },
{ path: "/notepad", method: "GET", run: notepadGet },
@@ -178,6 +185,45 @@ function signIn(req, res, ctx, url) {
return res.end();
}
// The setup session's hand-over: a launcher process opened this session's
// /s/ link in its own web view, then POSTs here so the launcher's setup page
// (the caller's own console) can move that tab to the new session. Only a
// setup session answers, and only for the per-session setup token that
// `open` printed for the launcher, never the browser cookie. On success the
// page gets a `move` SSE event carrying the url to hand itself to.
function handover(req, res, ctx) {
const state = ctx.readState();
if (!state || state.workflow !== "setup" || !state.setup || !state.setup.token) {
return json(res, 404, { error: "not-found" });
}
if (!timingSafeEq(req.headers["x-plan2code-token"] || "", state.setup.token)) {
return json(res, 403, { error: "forbidden" });
}
ctx.touch();
// The tab moved once; a second open in the same conversation is not a
// hand-over, so the caller can open a browser without a failure note.
if (state.setup.moved) return json(res, 409, { error: "moved" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "bad-url" });
const target = typeof body?.url === "string" ? body.url : "";
// Only another console's sign-in link is a legal destination.
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+\/s\/[A-Za-z0-9_-]+\/?$/.test(target)) {
return json(res, 400, { error: "bad-url" });
}
try {
updateState(ctx.dir, (fresh) => {
if (!fresh) return null;
fresh.setup = { ...(fresh.setup || {}), moved: { url: target, at: nowIso() } };
return fresh;
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
ctx.broadcast("move", { url: target });
return send(res, 204, "");
});
}
/* -------------------------------------------------------- the page itself */
// PLAN2CODE_EMBED_ORIGIN is an opt-in widening of frame-ancestors for a shell
@@ -525,8 +571,16 @@ function prHost(req, res, ctx) {
});
}
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js listModels).
const MODEL_CLIS = ["claude", "devin", "codex"];
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js
// listModels): the shipped agent list's built-ins. Worked out per call so a
// bin/agents.json written after server boot is picked up; the hard-coded
// trio is only the fallback for a missing or bad file.
const MODEL_CLI_FALLBACK = ["claude", "devin", "codex"];
function modelClis() {
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const ids = builtins.map((a) => a && a.id).filter((id) => typeof id === "string" && id);
return ids.length ? ids : MODEL_CLI_FALLBACK;
}
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
@@ -539,7 +593,7 @@ const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
for (const cli of modelClis()) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
@@ -561,7 +615,7 @@ function cleanModels(input) {
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
for (const cli of modelClis()) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
@@ -571,7 +625,7 @@ function shippedModels() {
function modelsGet(req, res) {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])) });
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])) });
}
function modelsPost(req, res) {
@@ -589,12 +643,41 @@ 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.
// This OS's key in the shipped install instructions / installDirs.
const OS_KEY = process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux";
// The person's custom agents (agents.mjs has the rules) plus the shipped
// list: built-ins with only this OS's install lines and their found state,
// and the starter templates as-is. The custom file is 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. Each
// entry's {state,path,where,folder} is the "found badge" data, from
// findAgent (a bare name searches PATH + saved PATH + npm + installDirs; a
// path is a file check).
function agentsGet(req, res) {
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
return json(res, 200, normalizeAgents(raw));
const { agents, warnings } = normalizeAgents(raw);
const agentsWithState = agents.map((a) => ({ ...a, ...findAgent({ command: a.command }) }));
const { builtins, templates, warnings: shippedWarnings } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE), optional: true });
warnings.push(...shippedWarnings);
const builtinsForOs = builtins.map((entry) => ({
id: entry.id,
name: entry.name,
command: entry.command,
prompt: entry.prompt,
args: entry.args,
bypassArgs: entry.bypassArgs,
modelArgs: entry.modelArgs,
installUrl: entry.installUrl,
install: (entry.install && entry.install[OS_KEY]) || [],
...findAgent(entry),
}));
const TEMPLATE_FIELDS = ["id", "name", "command", "prompt", "args", "bypassArgs", "modelArgs", "note"];
const templatesAsIs = templates.map((entry) =>
Object.fromEntries(TEMPLATE_FIELDS.filter((f) => entry[f] !== undefined).map((f) => [f, entry[f]]))
);
return json(res, 200, { agents: agentsWithState, warnings, builtins: builtinsForOs, templates: templatesAsIs });
}
// The whole list from User Preferences, checked, then written atomically. The
@@ -638,6 +721,82 @@ function agentsTest(req, res) {
});
}
// "Use this path instead": findAgent found the command off this process's
// PATH (saved Windows PATH, npm's global folder, an install dir), so the
// found location becomes the agent's command. Only findAgent's result is
// ever saved, never a path the request carried. A built-in is materialized
// as a new custom entry; a custom agent gets its command rewritten.
function agentsUsePath(req, res, ctx) {
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const id = typeof body?.id === "string" ? body.id.trim() : "";
if (!id) return json(res, 400, { error: "id is required" });
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const builtin = builtins.find((a) => a && a.id === id);
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
const { agents: customAgents, warnings } = normalizeAgents(raw);
// Same guard as agentsPost: a rewrite would drop the entries it skipped.
if (warnings.length) {
return json(res, 409, { error: "agents.json holds entries this page could not read. Saving replaces them.", warnings });
}
const custom = builtin ? null : customAgents.find((a) => a.id === id);
const entry = builtin || custom;
if (!entry) return json(res, 404, { error: "not-found" });
const found = findAgent(entry);
if (found.state === "missing") return json(res, 409, { error: "not-found" });
// Already on PATH: nothing to write, the badge can just say so.
if (found.state === "found") return json(res, 200, { ok: true, id, command: found.path || entry.command });
const list = customAgents.map((a) => ({ ...a }));
let savedId;
if (builtin) {
savedId = makeId(entry.name || id, list.map((a) => a.id));
list.push({
id: savedId,
name: entry.name,
command: found.path,
prompt: entry.prompt,
args: entry.args,
bypassArgs: entry.bypassArgs,
modelArgs: entry.modelArgs,
models: [],
});
} else {
savedId = id;
list.find((a) => a.id === id).command = found.path;
}
const { agents, error, index, field } = validateForSave(list);
if (error) return json(res, 400, { error, index, field });
// Same write as agentsPost: top-level keys the file already had are kept.
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) });
}
// A --for-cli setup asked for this built-in: the materialized entry carries
// its id over, or the page's Start gate would never match it again. Done
// after the write so a failed save never leaves a dangling forCli.
const setup = ctx && ctx.readState && ctx.readState()?.setup;
if (builtin && setup && setup.forCli === id) {
try {
updateState(ctx.dir, (fresh) => {
if (!fresh) return null;
fresh.setup = { ...(fresh.setup || {}), forCli: savedId };
return fresh;
});
} catch {
return json(res, 500, { error: "could not update the session" });
}
}
return json(res, 200, { ok: true, id: savedId, command: found.path });
});
}
// User Preferences -> System -> 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,
+5 -1
View File
@@ -47,6 +47,7 @@ import { serverWorkspace } from "./workspace.mjs";
import { serverSubagents } from "./settings.mjs";
import { inAppSignal } from "./in-app.mjs";
import { chatAnswering, chatOffline } from "./public/chat.js";
import { isAgentless } from "./public/skills.js";
import { meterView } from "./public/meter.js";
import { SERVABLE, asset } from "./static.mjs";
import { handle } from "./routes.mjs";
@@ -185,6 +186,7 @@ function chatOfflineNow(state, chat = chatNow(state)) {
agentLastSeenMs: agentSeenAt,
now: Date.now(),
answering: chatAnswering(chat),
agentless: isAgentless(state && state.workflow),
});
}
@@ -250,7 +252,9 @@ function stateFrame(state) {
const chat = chatNow(state);
return {
rev,
state,
// The setup hand-over token is for the launcher only: the page gets
// forCli, which is all the setup screen reads.
state: state.setup ? { ...state, setup: { forCli: state.setup.forCli || null } } : state,
agentLastSeen: agentLastSeen(),
pendingResult: pending,
pendingStop: stop,