mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Let people define custom agent CLIs and start them from the app and the launcher
AI Assisted
This commit is contained in:
1 parent
3e22d53bf5
commit
94063fc0a9
27 files changed
+4025
-95
No files matched your search
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the rules of ~/.plan2code/agents.json, the person's custom agent CLIs: reading the file, checking a save, naming an entry, building its command line and finding its command; defines only.
|
||||
//
|
||||
// The console is the file's only writer (routes.mjs, from User Preferences);
|
||||
// the launcher and the desktop app read it with their own copies of these
|
||||
// rules. scripts/fixtures/agents-cases.json pins all three to the same cases,
|
||||
// so change a rule there first.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export const BUILTIN_AGENT_IDS = ["claude", "devin", "codex"];
|
||||
export const AGENTS_SCHEMA = 1;
|
||||
export const MAX_AGENTS = 50;
|
||||
|
||||
const AGENT_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
||||
const MAX_NAME = 60;
|
||||
const DEFAULT_PROMPT = "/plan2code";
|
||||
const DEFAULT_MODEL_ARGS = ["--model", "{model}"];
|
||||
const LIST_FIELDS = ["args", "bypassArgs", "modelArgs"];
|
||||
|
||||
/**
|
||||
* The file as the launcher and the app will use it: `raw` is its text (or the
|
||||
* parsed value; undefined or null when there is no file). Bad entries are
|
||||
* skipped and named in `warnings`, and a bad file means no agents. Never throws.
|
||||
*/
|
||||
export function normalizeAgents(raw) {
|
||||
const warnings = [];
|
||||
if (raw === undefined || raw === null) return { agents: [], warnings };
|
||||
let file = raw;
|
||||
if (typeof raw === "string") {
|
||||
try {
|
||||
file = JSON.parse(raw);
|
||||
} catch {
|
||||
return { agents: [], warnings: ["agents.json is not valid JSON, so no custom agents are used"] };
|
||||
}
|
||||
}
|
||||
if (!file || typeof file !== "object" || Array.isArray(file)) {
|
||||
return { agents: [], warnings: ["agents.json is not an object, so no custom agents are used"] };
|
||||
}
|
||||
if (file.schema !== AGENTS_SCHEMA) {
|
||||
return { agents: [], warnings: [`agents.json has schema ${JSON.stringify(file.schema)}, not ${AGENTS_SCHEMA}, so no custom agents are used`] };
|
||||
}
|
||||
if (file.agents === undefined || file.agents === null) return { agents: [], warnings };
|
||||
if (!Array.isArray(file.agents)) return { agents: [], warnings: ["agents.json: agents is not a list, so no custom agents are used"] };
|
||||
|
||||
let list = file.agents;
|
||||
if (list.length > MAX_AGENTS) {
|
||||
warnings.push(`agents.json lists ${list.length} agents; only the first ${MAX_AGENTS} are used`);
|
||||
list = list.slice(0, MAX_AGENTS);
|
||||
}
|
||||
const agents = [];
|
||||
const ids = new Set();
|
||||
const names = new Set();
|
||||
list.forEach((entry, index) => {
|
||||
const out = checkEntry(entry, ids, names);
|
||||
if (out.error) return warnings.push(`agents[${index}] skipped: ${out.error}`);
|
||||
ids.add(out.agent.id);
|
||||
names.add(out.agent.name.toLowerCase());
|
||||
agents.push(out.agent);
|
||||
});
|
||||
return { agents, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the form sends, checked before it is written: the same rules as
|
||||
* normalizeAgents, but the first failure comes back as { error, index, field }
|
||||
* instead of being skipped. An entry with no id gets one from its name.
|
||||
* Returns { agents } with every default filled.
|
||||
*/
|
||||
export function validateForSave(list) {
|
||||
if (!Array.isArray(list)) return { error: "agents must be a list", field: "agents" };
|
||||
if (list.length > MAX_AGENTS) return { error: `at most ${MAX_AGENTS} agents`, field: "agents" };
|
||||
// Ids the form already carries are fixed, so a new entry's id steers around them.
|
||||
const taken = list.map((entry) => (entry && typeof entry === "object" && typeof entry.id === "string" ? entry.id : "")).filter(Boolean);
|
||||
const agents = [];
|
||||
const ids = new Set();
|
||||
const names = new Set();
|
||||
for (let index = 0; index < list.length; index++) {
|
||||
let entry = list[index];
|
||||
if (entry && typeof entry === "object" && !Array.isArray(entry) && (entry.id === undefined || entry.id === null || entry.id === "")) {
|
||||
const id = makeId(typeof entry.name === "string" ? entry.name : "", taken);
|
||||
taken.push(id);
|
||||
entry = { ...entry, id };
|
||||
}
|
||||
const out = checkEntry(entry, ids, names);
|
||||
if (out.error) return { error: out.error, index, field: out.field };
|
||||
ids.add(out.agent.id);
|
||||
names.add(out.agent.name.toLowerCase());
|
||||
agents.push(out.agent);
|
||||
}
|
||||
return { agents };
|
||||
}
|
||||
|
||||
// One entry against the rules: { agent } with the defaults filled and any
|
||||
// unknown keys kept, or { error, field } naming the first thing wrong.
|
||||
function checkEntry(entry, ids, names) {
|
||||
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { error: "not an object", field: "" };
|
||||
const { id } = entry;
|
||||
if (typeof id !== "string" || !id) return { error: "id is missing", field: "id" };
|
||||
if (BUILTIN_AGENT_IDS.includes(id)) return { error: `id "${id}" belongs to a built-in agent`, field: "id" };
|
||||
if (!AGENT_ID.test(id)) return { error: `id "${id}" must be 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit`, field: "id" };
|
||||
if (ids.has(id)) return { error: `id "${id}" is already used`, field: "id" };
|
||||
|
||||
const name = typeof entry.name === "string" ? entry.name.trim() : "";
|
||||
if (!name) return { error: "name is missing", field: "name" };
|
||||
if (name.length > MAX_NAME) return { error: `name is longer than ${MAX_NAME} characters`, field: "name" };
|
||||
if (names.has(name.toLowerCase())) return { error: `name "${name}" is already used`, field: "name" };
|
||||
|
||||
const command = typeof entry.command === "string" ? entry.command.trim() : "";
|
||||
if (!command) return { error: "command is missing", field: "command" };
|
||||
|
||||
const agent = { ...entry, id, name, command };
|
||||
for (const field of LIST_FIELDS) {
|
||||
const value = entry[field];
|
||||
if (value === undefined || value === null) {
|
||||
agent[field] = field === "modelArgs" ? [...DEFAULT_MODEL_ARGS] : [];
|
||||
} else if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
|
||||
return { error: `${field} must be a list of text`, field };
|
||||
} else agent[field] = [...value];
|
||||
}
|
||||
|
||||
if (entry.prompt === undefined || entry.prompt === null) agent.prompt = DEFAULT_PROMPT;
|
||||
else if (typeof entry.prompt !== "string") return { error: "prompt must be text", field: "prompt" };
|
||||
|
||||
if (entry.models === undefined || entry.models === null) agent.models = [];
|
||||
else if (!Array.isArray(entry.models)) return { error: "models must be a list", field: "models" };
|
||||
else {
|
||||
agent.models = [];
|
||||
const seen = new Set();
|
||||
for (const model of entry.models) {
|
||||
if (!model || typeof model !== "object" || typeof model.id !== "string") return { error: "every model in models needs an id", field: "models" };
|
||||
const modelId = model.id.trim();
|
||||
if (!modelId || seen.has(modelId)) continue;
|
||||
seen.add(modelId);
|
||||
const label = typeof model.label === "string" ? model.label.trim() : "";
|
||||
agent.models.push(label ? { id: modelId, label } : { id: modelId });
|
||||
}
|
||||
}
|
||||
return { agent };
|
||||
}
|
||||
|
||||
/**
|
||||
* An id for a new entry: its name in kebab case ("agent" when nothing is
|
||||
* left), at most 32 characters, with -2, -3 ... on a clash with `taken` or a
|
||||
* built-in id.
|
||||
*/
|
||||
export function makeId(name, taken = []) {
|
||||
const used = new Set([...BUILTIN_AGENT_IDS, ...taken]);
|
||||
const base = trimDashes(
|
||||
String(name ?? "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.slice(0, 32)
|
||||
) || "agent";
|
||||
if (!used.has(base)) return base;
|
||||
for (let n = 2; ; n++) {
|
||||
const suffix = `-${n}`;
|
||||
const id = trimDashes(base.slice(0, 32 - suffix.length)) + suffix;
|
||||
if (!used.has(id)) return id;
|
||||
}
|
||||
}
|
||||
|
||||
function trimDashes(text) {
|
||||
return text.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The arguments that start an entry, in order: `args` with {prompt} filled
|
||||
* (the prompt appended when no argument holds it), then `modelArgs` when a
|
||||
* model is chosen, then `bypassArgs` when checks are off. `prompt` defaults
|
||||
* to the entry's own; a blank one drops an argument that is exactly
|
||||
* {prompt}. Plain text in, plain text out: no quoting for any shell.
|
||||
*/
|
||||
export function buildArgs(entry, { prompt, model, bypass } = {}) {
|
||||
const text = prompt === undefined ? (typeof entry.prompt === "string" ? entry.prompt : DEFAULT_PROMPT) : String(prompt ?? "");
|
||||
const blank = !text.trim();
|
||||
const out = [];
|
||||
let placed = false;
|
||||
for (const arg of entry.args || []) {
|
||||
if (!arg.includes("{prompt}")) {
|
||||
out.push(arg);
|
||||
continue;
|
||||
}
|
||||
placed = true;
|
||||
if (arg === "{prompt}" && blank) continue;
|
||||
out.push(arg.split("{prompt}").join(text));
|
||||
}
|
||||
if (!placed && !blank) out.push(text);
|
||||
if (model) {
|
||||
for (const arg of entry.modelArgs || DEFAULT_MODEL_ARGS) out.push(arg.split("{model}").join(model));
|
||||
}
|
||||
if (bypass) out.push(...(entry.bypassArgs || []));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where `command` runs from, or null. A command with a path separator is
|
||||
* checked as a file; a bare name is looked for on PATH. On Windows each
|
||||
* PATHEXT extension is tried when the command has none, as the launcher's
|
||||
* findOnPath() does. Never runs anything.
|
||||
*/
|
||||
export function resolveCommand(command, { path: searchPath = process.env.PATH, pathext = process.env.PATHEXT } = {}) {
|
||||
const name = String(command ?? "").trim().replace(/^"(.*)"$/, "$1");
|
||||
if (!name) return null;
|
||||
const windows = process.platform === "win32";
|
||||
const extensions = windows ? (pathext || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [];
|
||||
const tries = (file) => (windows && !path.extname(file) ? extensions.map((ext) => file + ext) : [file]);
|
||||
const isFile = (file) => {
|
||||
try {
|
||||
return fs.statSync(file).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (name.includes("/") || (windows && name.includes("\\"))) {
|
||||
return tries(path.resolve(name)).find(isFile) || null;
|
||||
}
|
||||
for (const dir of String(searchPath || "").split(path.delimiter).filter(Boolean)) {
|
||||
const found = tries(path.join(dir.replace(/^"|"$/g, ""), name)).find(isFile);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -40,6 +40,9 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
|
||||
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
|
||||
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
|
||||
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
// The person's custom agent CLIs (agents.mjs has the rules). The console is its only
|
||||
// writer, from User Preferences; the launcher and the desktop app read it.
|
||||
export const USER_AGENTS_FILE = path.join(PLAN2CODE_DIR, "agents.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
|
||||
@@ -2648,6 +2648,22 @@
|
||||
<span class="help" id="models-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models looks-agents">
|
||||
<legend>Agents</legend>
|
||||
<div class="models-note">
|
||||
<p>Agent CLIs Plan2Code did not find on its own. The <code>plan2code</code> command and the desktop app list the ones that are installed.</p>
|
||||
<ul>
|
||||
<li><code>/plan2code</code> works only in agents that load the installed Plan2Code skills. A blank start prompt starts the agent with nothing typed.</li>
|
||||
<li>The list is saved as plain text in <code>~/.plan2code/agents.json</code>.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="agents-list" id="agents-list" aria-label="Agents you added"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="agents-add">Add agent</button>
|
||||
<button type="button" class="btn small danger" id="agents-replace" hidden>Save anyway</button>
|
||||
<span class="help" id="agents-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
|
||||
|
||||
@@ -90,6 +90,354 @@ async function loadModelsData() {
|
||||
renderModels();
|
||||
}
|
||||
|
||||
// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json.
|
||||
// Each card edits its entry in place (unknown keys ride along untouched); every change
|
||||
// saves the whole list. A new card is not sent until it has a name and a command.
|
||||
let agentsData = [];
|
||||
|
||||
// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData).
|
||||
let agentsError = null;
|
||||
|
||||
// The entry whose Delete is waiting for a second click.
|
||||
let agentsConfirming = null;
|
||||
|
||||
// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn.
|
||||
let agentsSaveSeq = 0;
|
||||
|
||||
// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new
|
||||
// card still held back) sends nothing.
|
||||
let agentsLastSent = null;
|
||||
|
||||
function setAgentsStatus(text, isError) {
|
||||
const status = $("agents-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function newAgent() {
|
||||
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
|
||||
}
|
||||
|
||||
function agentField(label, field, child) {
|
||||
const wrap = el("div", "agent-field");
|
||||
wrap.dataset.field = field;
|
||||
wrap.append(el("span", null, label), child);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function agentInput(agent, key, label, placeholder, trim) {
|
||||
const input = el("input");
|
||||
input.value = agent[key] || "";
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("change", () => {
|
||||
agent[key] = trim ? input.value.trim() : input.value;
|
||||
saveAgents();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
// A list of text rows (arguments), with Remove on each and an Add under them.
|
||||
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = key;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent[key].forEach((value, i) => {
|
||||
const row = el("div", "agent-row");
|
||||
const input = el("input");
|
||||
input.value = value;
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); });
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
agent[key].splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(input, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", addLabel);
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent[key].push("");
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(label, key, box);
|
||||
}
|
||||
|
||||
// The models list: an id and an optional name for the menu on each row.
|
||||
function agentModelsEditor(agent) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = "models";
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent.models.forEach((m, i) => {
|
||||
const row = el("div", "agent-row model");
|
||||
const id = el("input");
|
||||
id.value = m.id || "";
|
||||
id.placeholder = "Model id, for {model}";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
id.dataset.field = "models";
|
||||
const label = el("input");
|
||||
label.value = m.label || "";
|
||||
label.placeholder = "Name shown in the menu (optional)";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
label.dataset.field = "models";
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); });
|
||||
label.addEventListener("change", () => {
|
||||
const text = label.value.trim();
|
||||
if (text) m.label = text;
|
||||
else delete m.label;
|
||||
saveAgents();
|
||||
});
|
||||
remove.addEventListener("click", () => {
|
||||
agent.models.splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", "Add a model");
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent.models.push({ id: "" });
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField("Models", "models", box);
|
||||
}
|
||||
|
||||
// Test, and Delete with its confirm step on the card itself (never the browser's confirm()).
|
||||
function agentFoot(agent) {
|
||||
const foot = el("div", "agent-foot");
|
||||
const test = el("button", "btn small", "Test");
|
||||
test.type = "button";
|
||||
const result = el("span", "help agent-test-result");
|
||||
result.setAttribute("role", "status");
|
||||
test.addEventListener("click", async () => {
|
||||
const command = String(agent.command || "").trim();
|
||||
if (!command) {
|
||||
result.textContent = "Type a command first.";
|
||||
return;
|
||||
}
|
||||
result.textContent = "Looking...";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) result.textContent = body.error || "Could not test.";
|
||||
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
|
||||
} catch {
|
||||
result.textContent = "Could not test.";
|
||||
}
|
||||
});
|
||||
foot.append(test);
|
||||
if (agentsConfirming === agent) {
|
||||
const ask = el("span", "help", "Delete this agent?");
|
||||
const yes = el("button", "btn small danger", "Yes, delete");
|
||||
yes.type = "button";
|
||||
const keep = el("button", "btn small ghost", "Keep");
|
||||
keep.type = "button";
|
||||
yes.addEventListener("click", async () => {
|
||||
agentsConfirming = null;
|
||||
agentsData.splice(agentsData.indexOf(agent), 1);
|
||||
agentsError = null;
|
||||
renderAgents();
|
||||
await saveAgents();
|
||||
});
|
||||
keep.addEventListener("click", () => {
|
||||
agentsConfirming = null;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(ask, yes, keep);
|
||||
} else {
|
||||
const del = el("button", "btn small ghost danger", "Delete");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => {
|
||||
agentsConfirming = agent;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(del);
|
||||
}
|
||||
foot.append(result);
|
||||
return foot;
|
||||
}
|
||||
|
||||
// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the
|
||||
// person back where they were, with what they had typed: { card, nth, value, start, end }.
|
||||
const AGENT_FOCUSABLE = "input, button";
|
||||
|
||||
function agentsFocus(list) {
|
||||
const active = document.activeElement;
|
||||
const card = active && list.contains(active) ? active.closest(".agent-card") : null;
|
||||
if (!card) return null;
|
||||
const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) };
|
||||
if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd });
|
||||
return at;
|
||||
}
|
||||
|
||||
function restoreAgentsFocus(list, at) {
|
||||
const card = at && list.children[at.card];
|
||||
const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth];
|
||||
if (!target) return;
|
||||
if (!(target instanceof HTMLInputElement) || at.value === undefined) {
|
||||
target.focus();
|
||||
return;
|
||||
}
|
||||
const drawn = target.value;
|
||||
target.value = at.value;
|
||||
target.focus();
|
||||
try {
|
||||
target.setSelectionRange(at.start, at.end);
|
||||
} catch {}
|
||||
// Text typed before the redraw is not in agentsData yet, and the browser fires no change
|
||||
// for a value set from script, so leaving the field sends it on.
|
||||
if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true });
|
||||
}
|
||||
|
||||
function renderAgents() {
|
||||
const list = $("agents-list");
|
||||
const focus = agentsFocus(list);
|
||||
list.replaceChildren();
|
||||
agentsData.forEach((agent, i) => {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) {
|
||||
if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
const card = el("div", "agent-card");
|
||||
const top = el("div", "agent-top");
|
||||
top.append(
|
||||
agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)),
|
||||
agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)),
|
||||
);
|
||||
card.append(
|
||||
top,
|
||||
agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"),
|
||||
agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
|
||||
agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
|
||||
agentModelsEditor(agent),
|
||||
);
|
||||
if (agentsError && agentsError.index === i) {
|
||||
card.classList.add("invalid");
|
||||
for (const input of card.querySelectorAll("input")) {
|
||||
if (input.dataset.field === agentsError.field) input.classList.add("invalid");
|
||||
}
|
||||
card.appendChild(el("p", "agent-error", agentsError.error));
|
||||
}
|
||||
card.appendChild(agentFoot(agent));
|
||||
list.appendChild(card);
|
||||
});
|
||||
restoreAgentsFocus(list, focus);
|
||||
}
|
||||
|
||||
// The list as the server wants it: blank rows dropped, and a new card without both a name and
|
||||
// a command (one still being typed) left out, so its first field is not refused as half an
|
||||
// agent. `kept` maps each sent entry back to its place.
|
||||
function agentsPayload() {
|
||||
const kept = [];
|
||||
const agents = [];
|
||||
agentsData.forEach((a, i) => {
|
||||
if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return;
|
||||
kept.push(i);
|
||||
agents.push({
|
||||
...a,
|
||||
args: a.args.filter((v) => v !== ""),
|
||||
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
|
||||
modelArgs: a.modelArgs.filter((v) => v !== ""),
|
||||
models: a.models.filter((m) => m.id),
|
||||
});
|
||||
});
|
||||
return { kept, agents };
|
||||
}
|
||||
|
||||
// `replace` is the person's Save anyway, over a file holding entries this page could not read.
|
||||
async function saveAgents({ replace = false } = {}) {
|
||||
const { kept, agents } = agentsPayload();
|
||||
const sent = JSON.stringify(agents);
|
||||
if (!replace && agentsError === null && sent === agentsLastSent) return;
|
||||
const seq = ++agentsSaveSeq;
|
||||
try {
|
||||
const res = await fetch("/agents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(replace ? { agents, replace: true } : { agents }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (seq !== agentsSaveSeq) return;
|
||||
if (res.status === 409) {
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true);
|
||||
$("agents-replace").hidden = false;
|
||||
return;
|
||||
}
|
||||
$("agents-replace").hidden = true;
|
||||
if (!res.ok) {
|
||||
const at = Number.isInteger(body.index) ? kept[body.index] : undefined;
|
||||
agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." };
|
||||
setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true);
|
||||
renderAgents();
|
||||
return;
|
||||
}
|
||||
// Ids are assigned on the first save: take the server's entries, and redraw only then
|
||||
// (or to clear a mark), so typing in another card is not interrupted.
|
||||
const fresh = agents.some((a) => !a.id) || agentsError !== null;
|
||||
agentsError = null;
|
||||
agentsLastSent = sent;
|
||||
setAgentsStatus("Saved.", false);
|
||||
if (fresh) {
|
||||
kept.forEach((at, n) => { agentsData[at] = body.agents[n]; });
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
renderAgents();
|
||||
}
|
||||
} catch {
|
||||
if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAgents() {
|
||||
agentsError = null;
|
||||
agentsConfirming = null;
|
||||
agentsLastSent = null;
|
||||
$("agents-replace").hidden = true;
|
||||
try {
|
||||
const res = await fetch("/agents");
|
||||
if (res.ok) {
|
||||
const body = await res.json();
|
||||
agentsData = Array.isArray(body.agents) ? body.agents : [];
|
||||
for (const agent of agentsData) {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus(warnings.join(" "), warnings.length > 0);
|
||||
} else {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
} catch {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
renderAgents();
|
||||
}
|
||||
|
||||
// Following the system, the saved looks painted before anything is drawn, and
|
||||
// the sound cues let go on the next touch. `boot` is the page's boot data.
|
||||
export function startLooks(boot) {
|
||||
@@ -119,6 +467,7 @@ export function wireLooks() {
|
||||
renderSwatches();
|
||||
setModelsStatus("", false);
|
||||
loadModelsData();
|
||||
loadAgents();
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
@@ -188,6 +537,15 @@ export function wireLooks() {
|
||||
renderModels();
|
||||
$("models-user").querySelector(".models-row:last-child input")?.focus();
|
||||
});
|
||||
$("agents-add").addEventListener("click", () => {
|
||||
agentsData.push(newAgent());
|
||||
renderAgents();
|
||||
$("agents-list").querySelector(".agent-card:last-child input")?.focus();
|
||||
});
|
||||
$("agents-replace").addEventListener("click", () => {
|
||||
$("agents-replace").hidden = true;
|
||||
saveAgents({ replace: true });
|
||||
});
|
||||
$("models-reset").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
|
||||
@@ -108,6 +108,23 @@
|
||||
.models-row input { min-width: 0; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
.agents-list { display: grid; gap: 10px; }
|
||||
.agents-list:empty { display: none; }
|
||||
.agent-card { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--rule-2); border-radius: 8px; }
|
||||
.agent-card.invalid { border-color: var(--danger, #d64545); }
|
||||
.agent-card input { min-width: 0; }
|
||||
.agent-card input.invalid { border-color: var(--danger, #d64545); }
|
||||
.agent-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
|
||||
.agent-field { display: grid; gap: 4px; min-width: 0; }
|
||||
.agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; }
|
||||
.agent-rows { display: grid; gap: 4px; }
|
||||
.agent-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px; align-items: center; }
|
||||
.agent-row.model { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; }
|
||||
.agent-foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.agent-foot .help { margin: 0; }
|
||||
.agent-foot .agent-test-result { flex: 1 1 auto; }
|
||||
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
|
||||
#agents-replace[hidden] { display: none; }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
|
||||
@@ -15,15 +15,18 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
USER_AGENTS_FILE,
|
||||
USER_MODELS_FILE,
|
||||
appendEvent,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
nowIso,
|
||||
readJson,
|
||||
readText,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
} from "./files.mjs";
|
||||
import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
|
||||
import { checkDocument, cleanupFindings, readOverview, removeCleanup } from "./sessions.mjs";
|
||||
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
|
||||
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
|
||||
@@ -83,6 +86,9 @@ const ROUTES = [
|
||||
{ path: "/pr-host", method: "POST", origin: true, run: prHost },
|
||||
{ path: "/models", method: "GET", run: modelsGet },
|
||||
{ path: "/models", method: "POST", origin: true, run: modelsPost },
|
||||
{ path: "/agents", method: "GET", run: agentsGet },
|
||||
{ path: "/agents", method: "POST", origin: true, run: agentsPost },
|
||||
{ path: "/agents/test", method: "POST", origin: true, run: agentsTest },
|
||||
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
|
||||
{ path: "/upload", method: "POST", origin: true, run: upload },
|
||||
{ path: "/notepad", method: "GET", run: notepadGet },
|
||||
@@ -568,6 +574,55 @@ function modelsPost(req, res) {
|
||||
});
|
||||
}
|
||||
|
||||
// The person's custom agents (agents.mjs has the rules). Read as text, not
|
||||
// with readJson: a half-written or broken file has to come back as a warning,
|
||||
// which readJson would turn into the same nothing as a missing file.
|
||||
function agentsGet(req, res) {
|
||||
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
|
||||
return json(res, 200, normalizeAgents(raw));
|
||||
}
|
||||
|
||||
// The whole list from User Preferences, checked, then written atomically. The
|
||||
// first failure names the entry and field so the page can mark them, and
|
||||
// nothing is written. Top-level keys the file already had are kept. A file
|
||||
// holding anything GET /agents could not read (another schema, a skipped
|
||||
// entry) is refused with 409 unless the page says `replace: true`, so a save
|
||||
// never silently drops what the person wrote there by hand.
|
||||
function agentsPost(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { agents, error, index, field } = validateForSave(body && body.agents);
|
||||
if (error) return json(res, 400, { error, index, field });
|
||||
if (body.replace !== true && fs.existsSync(USER_AGENTS_FILE)) {
|
||||
const { warnings } = normalizeAgents(readText(USER_AGENTS_FILE));
|
||||
if (warnings.length) {
|
||||
return json(res, 409, { error: "agents.json holds entries this page could not read. Saving replaces them.", warnings });
|
||||
}
|
||||
}
|
||||
const saved = readJson(USER_AGENTS_FILE, null);
|
||||
const kept = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
try {
|
||||
ensureDir(path.dirname(USER_AGENTS_FILE));
|
||||
writeJsonAtomic(USER_AGENTS_FILE, { ...kept, schema: AGENTS_SCHEMA, agents });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
return json(res, 200, { ok: true, agents });
|
||||
});
|
||||
}
|
||||
|
||||
// Where a command would run from, for the form's Test button. Only looks: it
|
||||
// never runs the command.
|
||||
function agentsTest(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const command = typeof body?.command === "string" ? body.command.trim() : "";
|
||||
if (!command || command.length > 1024) return json(res, 400, { error: "command must be 1 to 1024 characters" });
|
||||
const found = resolveCommand(command);
|
||||
return json(res, 200, found ? { found: true, path: found } : { found: false });
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
|
||||
// removes those of the ids a fresh scan still finds. Never this session,
|
||||
|
||||
@@ -345,9 +345,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// `plan2code update` reads (install.json), the models the person added and
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs) and
|
||||
// the notepads, removed only one at a time through Cleanup (notepads.mjs), and
|
||||
// the desktop app (app/, which install.js fills, and app.json, its settings).
|
||||
// the desktop app (app/, which install.js fills, and app.json, its settings)
|
||||
// and the custom agents the person added (agents.json).
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json", "agents.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
|
||||
Reference in new issue
Block a user