#!/usr/bin/env node
// Plan2Code Web Console - the HTTP server.
//
// Spawned DETACHED by console.mjs, never as a harness-managed background task:
// those get killed on compaction, on a new prompt, and at assorted timeouts,
// which would take the human's half-finished answers with them.
//
// It owns no durable state of its own. Everything lives in the session
// directory, which is what makes the console survivable: the human can finish
// the form even if the agent session died, and a fresh agent picks the result up.
//
// Node built-ins only.
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import {
CHAT_CURSOR_FILE,
CHAT_FILE,
LEDGER_FILE,
HERE,
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
readChat,
readCursor,
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
SHOTS_DIR_NAME,
SHOT_NAME,
shotType,
saveSubagentStoreEntry,
PR_HOST_KINDS,
savePrHost,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
// Canonicalise before anything derives a path from it: a session dir reached
// through a junction or a subst'd drive is watched under the wrong spelling,
// which is the libuv assert described below. The native realpath resolves
// those AND expands 8.3 short names, which lets the watcher run in a TEMP
// spelled C:\Users\JUSTIN~1.PAR; the JS one is the fallback, and the watcher
// still checks what it was given.
const DIR = (() => {
for (const real of [fs.realpathSync.native, fs.realpathSync]) {
try {
return real(args.session);
} catch {}
}
return args.session;
})();
if (!DIR) {
process.stderr.write("server: --session
is required\n");
process.exit(2);
}
const SID = path.basename(DIR);
// No token, no server: authed() waves everything through on an empty one. A
// bare `--token` (or one whose value parseArgs took for a flag) arrives as
// `true`, so anything but a non-empty string is refused here, at boot.
if (typeof args.token !== "string" || !args.token) {
process.stderr.write("server: --token= is required (a non-empty string)\n");
process.exit(2);
}
const TOKEN = args.token;
const PROJECT = args.project || process.cwd();
// The checkout this session runs in, from `open`. PROJECT is the folder that
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
// folder to seed the workspace with or resolve a typed path against. A fresh
// `open` starts this server before it writes the state, so until the state is
// there this is the only place the worktree can come from.
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
const STATE_FILE = path.join(DIR, "state.json");
const DRAFT_FILE = path.join(DIR, "draft.json");
const RESULT_FILE = path.join(DIR, "result.json");
const CHAT_PATH = path.join(DIR, CHAT_FILE);
const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE);
// Images and documents attached to notes and quick questions. Only ever named
// by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only
// ever resolved inside this directory: the client's file name is a label.
// Images are served back as JPEG. A document is served under a fixed type
// (PDF, or text/plain for everything else, sandboxed and never sniffed), so
// the page can link it without ever letting a browser run it.
const UPLOADS_DIR = path.join(DIR, "uploads");
const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)];
const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
// Screenshots the agent saved for a doc's image block (Show me it working),
// only ever directly inside /shots/ under SHOT_NAME's plain shape.
const SHOTS_DIR = path.join(DIR, SHOTS_DIR_NAME);
const SHOT_TYPES = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" };
function shotPath(name) {
if (!SHOT_NAME.test(name)) return null;
const file = path.resolve(SHOTS_DIR, name);
if (!file.startsWith(path.resolve(SHOTS_DIR) + path.sep)) return null;
try {
const real = fs.realpathSync.native(file);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
if (fold(path.dirname(real)) !== fold(fs.realpathSync.native(SHOTS_DIR))) return null;
return fs.statSync(real).isFile() ? real : null;
} catch {
return null;
}
}
// A kept attachment's name, as attachmentName() in lib.mjs writes it:
// -..
const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`);
function keptPath(name) {
const state = readState() || {};
if (typeof state.specDir !== "string" || !state.specDir.trim()) return null;
const root = path.resolve(state.worktree || process.cwd());
const dir = path.resolve(root, state.specDir, "attachments");
const file = path.join(dir, name);
try {
const real = fs.realpathSync.native(file);
const realDir = fs.realpathSync.native(dir);
const realRoot = fs.realpathSync.native(root);
const inside = (p, base) => {
const rel = path.relative(base.toLowerCase(), p.toLowerCase());
return rel && !rel.startsWith("..") && !path.isAbsolute(rel);
};
if (path.dirname(real).toLowerCase() !== realDir.toLowerCase() || !inside(real, realRoot)) return null;
return fs.statSync(real).isFile() ? real : null;
} catch {
return null;
}
}
function uploadPath(id, ext = "jpg") {
if (!UPLOAD_EXTS.includes(ext)) return null;
const result = path.join(UPLOADS_DIR, id + "." + ext);
return path.resolve(result).startsWith(path.resolve(UPLOADS_DIR) + path.sep) ? result : null;
}
// "image" for one of this session's JPEGs, "file" for one of its documents,
// false for anything else.
function isOwnUpload(p) {
if (typeof p !== "string") return false;
const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
const abs = path.resolve(p);
const base = fold(path.basename(abs));
if (fold(path.dirname(abs)) !== fold(path.resolve(UPLOADS_DIR)) || !UPLOAD_NAME.test(base)) return false;
return base.endsWith(".jpg") ? "image" : "file";
}
// A client-supplied label, safe to put on a reply line: control characters
// become spaces, since a newline in a file name would split the line in two.
function cleanLabel(name, fallback) {
return (
(typeof name === "string" ? name : "")
.replace(/[\u0000-\u001f\u007f]/g, " ")
.trim()
.slice(0, 200) || fallback
);
}
// The file name the page sent, decoded but not yet cleaned or cut short.
function rawUploadName(req) {
try {
return decodeURIComponent(req.headers["x-p2c-name"] || "");
} catch {
return "";
}
}
function uploadLabel(req, fallback) {
return cleanLabel(rawUploadName(req), fallback);
}
// Whether a send's `images` and `files` are this session's uploads of the
// right kind, within the combined cap. Absent lists are fine.
function attachmentsOk(images, files) {
const listOk = (list, kind) =>
list === undefined ||
(Array.isArray(list) &&
list.every(
(a) =>
a &&
typeof a === "object" &&
isOwnUpload(a.path) === kind &&
fs.existsSync(a.path) &&
(a.name === undefined || typeof a.name === "string")
));
const count = (Array.isArray(images) ? images.length : 0) + (Array.isArray(files) ? files.length : 0);
return { images: listOk(images, "image"), files: listOk(files, "file"), count: count <= MAX_ATTACHMENTS };
}
const STARTED = Date.now();
let lastContact = Date.now();
let browsers = 0;
let rev = 0;
let seq = 0;
/* ------------------------------------------------------------ mime types */
const TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".mp3": "audio/mpeg",
".png": "image/png",
};
// A hardcoded allow-list, not a filesystem lookup. Nothing to traverse.
const SERVABLE = new Set([
"app.js",
"answers.js",
"app.css",
"render.js",
"palette.js",
"labels.js",
"boot.js",
"chat.js",
"help.js",
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"git-board.js",
"git-board-view.js",
"pr-url.js",
"start-stop.mp3",
"next.mp3",
"insert.mp3",
"sleeping.mp3",
"bootup.mp3",
"start-skill.mp3",
"favicon.svg",
"favicon.png",
"vendor/marked.esm.js",
]);
/* -------------------------------------------------------------- helpers */
// The state as last read, re-read only when its file has changed. Every
// request, every SSE frame and the one-second poll used to read and parse
// state.json afresh, and the state grows with the session (whole documents
// live in it). A stat says whether anything moved; refreshing through
// checkState also means a request that sees a new state first still counts
// it as a new revision and tells every other tab. Callers must not mutate
// what this returns -- /submit edits a fresh read of its own, under the lock.
function readState() {
checkState();
return stateNow;
}
// Both facts about result.json from one read, cached the same way. The page's
// heartbeat, every state frame and /submit's guard each asked for them, and
// each used to read and parse the file twice.
//
// An answered-but-not-yet-collected result: while one exists the session is
// mid-handoff, and the page must not send again and must say why.
// A stop the person asked for that nothing has collected yet. Reported from
// here rather than remembered by the page, because the page's memory is per
// origin and a resumed session comes back on a new port: the one place that
// still knows a stop is on its way is the result sitting on this disk.
let resultSeen = { stamp: null, pending: false, stop: false };
function resultFlags() {
const stamp = fileStamp(RESULT_FILE);
if (stamp !== resultSeen.stamp) {
let text = null;
try {
text = stamp ? fs.readFileSync(RESULT_FILE, "utf8") : null;
} catch (err) {
// There but unreadable for now (an antivirus lock, say). Never cached,
// so the next call reads it again, and meanwhile it counts as pending:
// a result nobody could read is exactly the one /submit must not
// overwrite.
if (err.code !== "ENOENT") return { ...resultSeen, pending: true };
}
let r = null;
try {
r = text ? JSON.parse(text) : null;
} catch {}
const pending = Boolean(r && !r.consumedAt);
resultSeen = {
stamp,
pending,
stop: pending && Array.isArray(r.actions) && r.actions.some((a) => a && a.type === "stop"),
};
}
return resultSeen;
}
const pendingResult = () => resultFlags().pending;
const pendingStop = () => resultFlags().stop;
// The chat inbox as last parsed, re-read only when the file has moved: every
// frame carries the conversation, and frames go out on every change.
let chatSeen = { stamp: null, entries: [] };
function chatEntries() {
const stamp = fileStamp(CHAT_PATH);
if (stamp !== chatSeen.stamp) chatSeen = { stamp, entries: readChat(DIR) };
return chatSeen.entries;
}
// How far the agent has collected the inbox. console.mjs writes the cursor
// when it hands entries over, so this is the "picked up, answering" signal the
// Ask pane shows a spinner for.
let cursorSeen = { stamp: null, seq: 0 };
function chatPickedUp() {
const stamp = fileStamp(CURSOR_PATH);
if (stamp !== cursorSeen.stamp) cursorSeen = { stamp, seq: readCursor(DIR) };
return cursorSeen.seq;
}
function chatOfflineNow(state) {
return chatOffline({
finish: state && state.finish,
agent: state && state.agent,
agentLastSeenMs: agentSeenAt,
now: Date.now(),
});
}
/* ------------------------------------------------------------ workspace */
// workspace.json has one writer, this server; ledger.ndjson has one,
// console.mjs. Both are re-read only when their file has moved.
const WORKSPACE_PATH = path.join(DIR, WORKSPACE_FILE);
const LEDGER_PATH = path.join(DIR, LEDGER_FILE);
const FOLD_CASE = process.platform === "win32" || process.platform === "darwin";
const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = () => stateNow?.worktree || WORKTREE || null;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
if (stamp && stamp === workspaceSeen.stamp) return workspaceSeen.ws;
const ws = (stamp && readWorkspace(DIR)) || null;
if (ws) {
workspaceSeen = { stamp, ws };
return ws;
}
const root = sessionWorktree();
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: PROJECT is only a guess
// (the main checkout, for a linked worktree), and the file, once written,
// is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
return fresh;
}
function saveWorkspace(ws) {
writeWorkspace(DIR, ws);
workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws };
}
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
// A folder deleted on disk is marked missing, and unmarked when it comes back.
function checkFolders(ws) {
ws.missing = ws.missing || [];
for (const f of ws.folders) {
const there = isFolder(f.path);
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
let ledgerSeen = { stamp: null, entries: [], launches: 0 };
function ledgerEntries() {
const stamp = fileStamp(LEDGER_PATH);
if (stamp !== ledgerSeen.stamp) {
const entries = readLedger(DIR);
ledgerSeen = { stamp, entries, launches: entries.filter((e) => e.kind === "launch").length };
}
return ledgerSeen.entries;
}
// What the agent reported it could not read during the current skill run:
// folder-issue entries after the last launch, the latest per folder name.
function folderIssues(entries) {
let from = 0;
entries.forEach((e, i) => e.kind === "launch" && (from = i + 1));
const latest = new Map();
for (const e of entries.slice(from)) {
if (e.kind !== "folder-issue") continue;
latest.set(e.name, { name: e.name, reason: e.reason, ...(e.hint ? { hint: e.hint } : {}) });
}
return [...latest.values()];
}
function workspaceView() {
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
function within(parent, child) {
const rel = path.relative(foldPath(parent), foldPath(child));
return rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel);
}
const cleanDescription = (d) => (typeof d === "string" ? d.trim().slice(0, 200) : "");
function nextFolderId(ws) {
const ns = ws.folders.map((f) => Number.parseInt(String(f.id).slice(1), 10)).filter(Number.isInteger);
return "f" + (Math.max(-1, ...ns) + 1);
}
// Each route below answers with [status, body]; validation always comes
// before any change, so a refusal leaves the file as it was.
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(sessionWorktree() || PROJECT, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
const nested = ws.folders.some((f) => within(f.path, resolved));
const name = typeof body.name === "string" && body.name ? body.name : defaultName(resolved);
if (nameProblem(name)) return [400, { reason: "bad-name" }];
const taken = new Set(ws.folders.map((f) => f.name));
if (taken.has(name)) return [400, { reason: "name-taken", suggest: freeName(name, taken) }];
const entry = { id: nextFolderId(ws), path: resolved, name, description: cleanDescription(body.description), nested };
ws.folders = [...ws.folders, entry];
bumpWorkspace(ws, { kind: "added", name, path: resolved, description: entry.description });
return [200, entry];
}
function editFolder(ws, body) {
const entry = ws.folders.find((f) => f.id === body.id);
if (!entry) return [404, { reason: "unknown" }];
const rename = typeof body.name === "string" && body.name !== entry.name;
if (rename) {
if (nameProblem(body.name)) return [400, { reason: "bad-name" }];
const taken = new Set(ws.folders.filter((f) => f !== entry).map((f) => f.name));
if (taken.has(body.name)) return [400, { reason: "name-taken", suggest: freeName(body.name, taken) }];
}
const description = typeof body.description === "string" ? cleanDescription(body.description) : entry.description;
if (rename) {
const from = entry.name;
entry.name = body.name;
bumpWorkspace(ws, { kind: "renamed", from, name: entry.name, path: entry.path });
}
if (description !== entry.description) {
entry.description = description;
bumpWorkspace(ws, { kind: "described", name: entry.name, path: entry.path, description });
}
return [200, entry];
}
function removeFolder(ws, body) {
const entry = ws.folders.find((f) => f.id === body.id);
if (entry && entry.original) return [400, { reason: "original" }];
if (!entry) return [404, { reason: "unknown" }];
ws.folders = ws.folders.filter((f) => f !== entry);
ws.missing = (ws.missing || []).filter((id) => id !== entry.id);
bumpWorkspace(ws, { kind: "removed", name: entry.name, path: entry.path });
return [200, { ok: true }];
}
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || PROJECT;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
// minutes, and every poll, chat message and `wait` health check has to keep
// being answered meanwhile.
let pickerBusy = false;
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
ws.remote = remote;
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
* Open a conversation when there is none, and a new one whenever the page
* passes through the dashboard. The reset line carries the workflow it was
* opened under, so a server that restarts across a hop still sees the switch.
* A resume that keeps its workflow keeps its conversation.
*/
function ensureConversation(state) {
if (!state) return;
const last = currentConversation(readChat(DIR));
let entry = null;
if (!last.conversation) {
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
} else if (
last.workflow !== state.workflow &&
// The same switches `open --resume` treats as a hop (a blank page, the
// agent's replies included): through the dashboard, or into git from
// anywhere (Commit it now, Changelog's "Commit this now?"). Without a new
// conversation, the old questions would show as unanswered again.
(last.workflow === "dashboard" || state.workflow === "dashboard" || state.workflow === "git")
) {
entry = appendChat(DIR, {
kind: "reset",
conversation: last.conversation + 1,
workflow: state.workflow,
reason: "switch",
});
}
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
}
/* ------------------------------------------------------------ subagents */
// subagents-setting.json has one writer, this server, and the agent hears of
// it only through what console.mjs reads there; events.ndjson's latest `open`
// says whether the agent's console copy can carry it. Both re-read only when
// their file has moved.
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
const EVENTS_PATH = path.join(DIR, "events.ndjson");
let subagentSettingSeen = { stamp: null, setting: null };
function subagentSettingNow() {
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
return subagentSettingSeen.setting;
}
let capsSeen = { stamp: null, caps: [] };
function openCapsNow() {
const stamp = fileStamp(EVENTS_PATH);
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
return capsSeen.caps;
}
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
/**
* Turn the per-project store into this session's setting, for the workflow
* the session is in now. The only place that happens (FR-7): a session an
* older server ran has no setting file, so nothing is ever injected into it.
* A record that already matches is left alone, revision and all, so a
* restart alone never re-tells the agent anything.
*/
function syncSubagentSetting(state) {
if (!state || typeof state.workflow !== "string") return;
const { workflow } = state;
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
const target = { workflow, on, instruction, max };
const current = readSubagentSetting(DIR);
if (current && sameSetting(current, target)) return;
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
}
// What the page needs to draw itself, in the shape of the SSE state frame.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
function stateFrame(state) {
const { pending, stop } = resultFlags();
return {
rev,
state,
agentLastSeen: agentLastSeen(),
pendingResult: pending,
pendingStop: stop,
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
// The page shows the switch only when `offered && supported` (FR-3); the
// frame says both and leaves combining them to the page. `instruction: null`
// is the shipped default, which the page reads from subagents.js itself.
function subagentsView(state) {
const workflow = state && state.workflow;
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
}
function haveKey() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
);
}
/**
* Write what the person sent onto the item itself.
*
* The page shows a settled question's answer back to them, and the agent is
* supposed to record one when it settles the question. This is the belt to that
* braces: a model that forgets the `answer` field leaves someone staring at a
* card marked "Settled" with nothing in it, and they cannot tell what they said.
*
* It never touches `status`. Only the agent decides when a question is settled,
* and this must not look like an answer the agent has read.
*/
function recordSubmitted(state, actions) {
if (!Array.isArray(state.items)) return;
const at = nowIso();
for (const action of actions) {
if (!action || typeof action !== "object") continue;
const item = state.items.find((i) => i && i.id === action.i);
if (!item) continue;
if (action.type === "comment") {
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
// JSON.parse makes "__proto__" an own property, and it would then be
// written back into state.json and re-read forever.
if (Object.prototype.hasOwnProperty.call(rest, "__proto__")) delete rest["__proto__"];
// A skip says so on the record, so settling it can record a skip.
item.submitted = { at, ...rest, ...(type === "skip" ? { skipped: true } : {}) };
}
}
function baseHeaders(extra = {}) {
return {
"cache-control": "no-store",
"x-content-type-options": "nosniff",
"referrer-policy": "no-referrer",
...extra,
};
}
function send(res, code, body, type = "application/json", extra = {}) {
res.writeHead(code, baseHeaders({ "content-type": type, ...extra }));
res.end(body);
}
function json(res, code, obj, extra = {}) {
send(res, code, JSON.stringify(obj), "application/json", extra);
}
function timingSafeEq(a, b) {
const ab = Buffer.from(String(a));
const bb = Buffer.from(String(b));
if (ab.length !== bb.length) return false;
return crypto.timingSafeEqual(ab, bb);
}
// One cookie per port. Browsers scope cookies by host and ignore the port, so
// with one shared name every session on 127.0.0.1 wrote over the one before
// it, and the first session's tab went on sending the second one's token and
// got nothing but 403s. The port is what makes a session's origin its own, and
// a resumed server on a new port is reached again only through its /s/ link,
// which sets the cookie under the new name.
const cookieName = () => `p2c_console_${PORT}`;
function cookieToken(req) {
const raw = req.headers.cookie || "";
const name = cookieName();
for (const part of raw.split(";")) {
const [k, ...v] = part.trim().split("=");
if (k === name) return v.join("=");
}
return null;
}
function authed(req) {
if (!TOKEN) return true;
const c = cookieToken(req);
return c ? timingSafeEq(c, TOKEN) : false;
}
/**
* The DNS-rebinding defence, and the highest-value check in this file.
*
* Without it, any page the user visits can resolve its own hostname to
* 127.0.0.1 and then talk to this server as same-origin. That is not
* theoretical: it is the exact shape of Vite's GHSA-vg6x-rcgg-rjx6.
*/
function hostOk(req, port) {
const host = req.headers.host;
if (!host) return false;
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
}
function originOk(req, port) {
const origin = req.headers.origin;
if (!origin) return true; // same-origin fetches and plain navigations send none
return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
}
function touch() {
lastContact = Date.now();
}
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js listModels).
const MODEL_CLIS = ["claude", "devin", "codex"];
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;
/**
* The user's added models: { claude: [{id,label}], devin: [...], codex: [...] }. Returns { models } or
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
* defaults to the id. Nothing else in the body survives.
*/
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) {
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();
models[cli] = [];
for (const row of list) {
const id = String((row && row.id) ?? "").trim();
if (!id) continue;
if (!MODEL_ID.test(id)) return { error: `"${id}" is not a valid model id` };
if (MODEL_EFFORT_BLOCKED.test(id)) return { error: `"${id}": only Low, Medium and High efforts are allowed` };
if (seen.has(id)) continue;
seen.add(id);
const label = String((row && row.label) ?? "").trim().slice(0, 80) || id;
models[cli].push({ id, label });
}
}
return { models };
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
}
/**
* Whittle a POSTed settings object down to what a settings file may hold.
* The page only sends { theme, accent } today, but the file is shared and
* forward-compatible: any flat string/number/boolean may live in it. Nested
* objects, arrays and a hundred-key dump may not — this is a preference file,
* not free storage, and it is read back into the page unfiltered.
*/
function cleanLooks(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return null;
const out = {};
for (const [k, v] of Object.entries(input)) {
if (k === "__proto__" || k.length > 64) continue;
const t = typeof v;
if (t === "number" || t === "boolean" || (t === "string" && v.length <= 256)) out[k] = v;
if (Object.keys(out).length > 40) return null;
}
return Object.keys(out).length ? out : null;
}
/* ---------------------------------------------------------------- assets */
// Read once per server, from memory after that. Held for the server's whole
// life on purpose: a skill reinstalled under a running session must not hand
// one page a new app.js beside the old answers.js it imports.
//
// Revalidated rather than stored: `no-cache` plus an ETag makes a reload a
// round of 304s instead of 400KB again. Every session is a new port, and so a
// new origin with a cold cache, which is why the first load is made cheap by
// other means (preload hints, the inline boot state) rather than by caching.
const assets = new Map();
function asset(rel) {
let a = assets.get(rel);
if (!a) {
let body = fs.readFileSync(path.join(PUBLIC_DIR, rel));
if (rel === "app.css") body = Buffer.concat([body, Buffer.from(accentCss())]);
const etag = `"${crypto.createHash("sha1").update(body).digest("base64url").slice(0, 20)}"`;
a = { body, etag, type: TYPES[path.extname(rel)] || "application/octet-stream" };
assets.set(rel, a);
}
return a;
}
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
const vars = (shades) =>
["--accent", "--accent-soft", "--accent-ink", "--accent-line"].map((n, i) => `${n}:${shades[i]}`).join(";");
let css = "\n/* Generated by server.mjs from palette.js: the saved accent before app.js runs. */\n";
for (const [id, a] of Object.entries(ACCENTS)) {
if (id === DEFAULT_ACCENT) continue;
const sel = `:root[data-looks-accent="${id}"]`;
css += `${sel}{${vars(a.light)}}\n`;
css += `@media (prefers-color-scheme: dark){${sel}:not([data-theme="light"]){${vars(a.dark)}}}\n`;
css += `${sel}[data-theme="dark"]{${vars(a.dark)}}\n`;
}
return css;
}
// looks.json, re-read only when it changes: it is read into every page load.
let looksSeen = { stamp: null, looks: null };
function savedLooks() {
const stamp = fileStamp(LOOKS_FILE);
if (stamp !== looksSeen.stamp) {
const saved = stamp ? readJson(LOOKS_FILE, null) : null;
looksSeen = { stamp, looks: saved && saved.looks && typeof saved.looks === "object" ? saved.looks : null };
}
return looksSeen.looks;
}
const escHtml = (s) =>
String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
let indexTemplate = null;
/**
* The page, with everything the first paint needs already in it.
*
* The page used to arrive as a blank template that said "Pathfinder" and
* "Connecting…" whatever the session was, then fetch /state, then /looks, and
* only then draw anything real. Now the server writes the session's name,
* badge and theme into the markup and the whole first state into an inline
* JSON block, so the script draws the real screen the moment it runs, with no
* round trip in between. The block is data, not script: `application/json`
* is never executed, so the CSP's ban on inline script stands untouched.
* Every `<` in it is escaped, which is what keeps a `` inside some
* agent-written text from closing the block early.
*/
function renderIndex() {
if (indexTemplate === null) indexTemplate = fs.readFileSync(path.join(PUBLIC_DIR, "index.html"), "utf8");
const state = readState();
const looks = savedLooks();
const boot = {
...stateFrame(state),
draft: readJson(DRAFT_FILE, {}),
looks,
};
let htmlAttrs = "";
if (looks && (looks.theme === "light" || looks.theme === "dark")) htmlAttrs += ` data-theme="${looks.theme}"`;
if (looks && looks.accent !== DEFAULT_ACCENT && Object.hasOwn(ACCENTS, String(looks.accent))) {
htmlAttrs += ` data-looks-accent="${looks.accent}"`;
}
// The same first-paint reasoning as the accent: a Wide user never sees the
// column jump from the default width. The value is one of the fixed preset
// keys, so there is nothing to escape.
if (looks && cardWidth(looks.width) !== DEFAULT_CARD_WIDTH) {
htmlAttrs += ` data-width="${cardWidth(looks.width)}"`;
}
const title = (state && state.title) || "Session";
const workflow = state && state.workflow;
const json = JSON.stringify(boot).replace(/', () => ``)
.replace(
"Plan2Code Console",
() => `${escHtml(title)} · #${escHtml(String(SID).slice(-6))} · Plan2Code`
)
.replace('Plan2Code Console
', () => `${escHtml(title)}
`)
.replace(
'Pathfinder',
() => `${escHtml(workflowLabel(workflow))}`
)
.replace(
'Opening the console
',
() =>
`${escHtml(
workflow === "dashboard" ? "Opening the dashboard" : `Starting ${workflowTitle(workflow)}`
)}
`
)
.replace("", () => ``);
}
/* ------------------------------------------------------------------ SSE */
// Exactly one stream per page. Browsers cap HTTP/1.1 at ~6 connections per
// origin, and an open stream holds one permanently; a second stream per tab
// across three tabs wedges the origin with no error and no timeout. Everything
// is multiplexed through this one channel with a `type` field.
const clients = new Set();
function broadcast(type, data) {
seq++;
const payload = `id: ${seq}\nevent: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of clients) {
try {
res.write(payload);
} catch {
clients.delete(res);
}
}
}
function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const version = readJson(file, {}).version;
if (typeof version === "string" && version) return version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
}
/* --------------------------------------------------------------- routes */
// The port this server answers on. Known before the server is: a handed-over
// socket was bound by console.mjs, so `server.address()` has nothing to say.
let PORT = 0;
const server = http.createServer((req, res) => {
const port = PORT;
const url = new URL(req.url, `http://127.0.0.1:${port}`);
const pathname = url.pathname;
if (!hostOk(req, port)) return send(res, 403, "", "text/plain");
// /health is the liveness probe the CLI uses to distinguish "our server"
// from a process that merely inherited the PID. Deliberately unauthenticated
// and deliberately tells you nothing but the session id.
if (pathname === "/health") {
touch();
agentSeenAt = Date.now();
return json(res, 200, { ok: true, sid: SID, browsers, rev, phase: readState()?.phase || "unknown" });
}
// Token in the PATH, not the query string. Two reasons: a query string would
// put an `&` in the URL, and `cmd /c start ` on Windows parses `&` as a
// command separator; and the 302 below gets the secret out of the address bar,
// out of history, and out of any screenshot the user pastes into a ticket.
if (pathname.startsWith("/s/")) {
const given = pathname.slice(3).replace(/\/$/, "");
if (!TOKEN || !timingSafeEq(given, TOKEN)) return send(res, 403, "Not found", "text/plain");
touch();
res.writeHead(
302,
baseHeaders({
location: "/",
"set-cookie": `${cookieName()}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
})
);
return res.end();
}
if (!authed(req)) return send(res, 403, "Open the link the terminal printed.", "text/plain");
touch();
if (pathname === "/" && req.method === "GET") {
let html;
try {
html = renderIndex();
} catch {
return send(res, 500, "index.html missing", "text/plain");
}
// No 'unsafe-inline'. That is why the client is separate .js/.css files
// rather than one inlined page: it makes an injected inline