461 lines
20 KiB
JavaScript
461 lines
20 KiB
JavaScript
// server/main.mjs — entry + REST spine.
|
|
//
|
|
// Loopback, single-human, synchronous JSON. The SPA and curl are both
|
|
// just clients. Boot-rebuild: every run whose latest session was not
|
|
// housekept gets its open window back from the jsonl — the log is the
|
|
// truth, the context is a view.
|
|
//
|
|
// usage: node server/main.mjs [--mock]
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import http from 'node:http';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { makeProvider } from './provider.mjs';
|
|
import { clerkRaw, clerkRawJson, clerkJson } from './clerk.mjs';
|
|
import * as bundle from './bundle.mjs';
|
|
import * as session from './session.mjs';
|
|
import * as housekeeping from './housekeeping.mjs';
|
|
import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const MOCK = process.argv.includes('--mock');
|
|
|
|
const CONFIG_PATH = path.join(ROOT, 'server.json');
|
|
if (!fs.existsSync(CONFIG_PATH)) {
|
|
console.error('no server.json — copy server.example.json and set your key in it (or via apiKeyEnv)');
|
|
process.exit(1);
|
|
}
|
|
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
|
|
const provider = makeProvider(cfg.endpoint ?? {});
|
|
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
|
|
|
// --- boot-rebuild ------------------------------------------------------------
|
|
|
|
if (fs.existsSync(path.join(ROOT, 'runs'))) {
|
|
for (const d of fs.readdirSync(path.join(ROOT, 'runs'), { withFileTypes: true })) {
|
|
if (!d.isDirectory()) continue;
|
|
if (!fs.existsSync(path.join(ROOT, 'runs', d.name, 'run.json'))) continue;
|
|
const latest = session.latestSession(d.name);
|
|
if (latest && latest !== session.lastHousekept(d.name)) {
|
|
ctx.sessions.set(d.name, session.loadSession(d.name, latest));
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- http plumbing -----------------------------------------------------------
|
|
|
|
const send = (res, status, body) => {
|
|
const data = JSON.stringify(body);
|
|
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) });
|
|
res.end(data);
|
|
};
|
|
|
|
const readBody = (req) => new Promise((resolve, reject) => {
|
|
const chunks = [];
|
|
let size = 0;
|
|
req.on('data', (c) => {
|
|
size += c.length;
|
|
if (size > 1024 * 1024) { reject(new HttpError(413, 'body too large')); req.destroy(); return; }
|
|
chunks.push(c);
|
|
});
|
|
req.on('end', () => {
|
|
if (!chunks.length) return resolve({});
|
|
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
|
|
catch { reject(new HttpError(400, 'body is not valid JSON')); }
|
|
});
|
|
req.on('error', reject);
|
|
});
|
|
|
|
const routes = [];
|
|
const route = (method, pattern, handler) => routes.push({ method, segs: pattern.split('/').filter(Boolean), handler });
|
|
|
|
const match = (method, pathname) => {
|
|
const segs = pathname.split('/').filter(Boolean);
|
|
outer: for (const r of routes) {
|
|
if (r.method !== method || r.segs.length !== segs.length) continue;
|
|
const params = {};
|
|
for (let i = 0; i < segs.length; i++) {
|
|
if (r.segs[i].startsWith(':')) params[r.segs[i].slice(1)] = decodeURIComponent(segs[i]);
|
|
else if (r.segs[i] !== segs[i]) continue outer;
|
|
}
|
|
return { handler: r.handler, params };
|
|
}
|
|
return null;
|
|
};
|
|
|
|
// --- static: the SPA in web/ -----------------------------------------------
|
|
// The API lives under /api/*; everything else serves web/ (index.html
|
|
// at /). Traversal-guarded; the SPA is a client like curl is.
|
|
|
|
const WEB_DIR = path.join(ROOT, 'web');
|
|
const MIME = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.mjs': 'text/javascript; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.svg': 'image/svg+xml',
|
|
'.json': 'application/json',
|
|
};
|
|
|
|
function serveStatic(pathname, res) {
|
|
let rel = decodeURIComponent(pathname).replace(/^\/+/, '');
|
|
if (!rel) rel = 'index.html';
|
|
const file = path.resolve(WEB_DIR, rel);
|
|
if (!file.startsWith(WEB_DIR + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
|
// SPA fallback: client-side routes are extensionless paths —
|
|
// serve the shell; anything that looks like a file stays a 404
|
|
if (path.extname(rel)) { send(res, 404, { error: `no such file: ${rel}` }); return; }
|
|
const shell = fs.readFileSync(path.join(WEB_DIR, 'index.html'));
|
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': shell.length });
|
|
res.end(shell);
|
|
return;
|
|
}
|
|
const data = fs.readFileSync(file);
|
|
res.writeHead(200, { 'content-type': MIME[path.extname(file)] ?? 'application/octet-stream', 'content-length': data.length });
|
|
res.end(data);
|
|
}
|
|
|
|
// --- routes -------------------------------------------------------------------
|
|
|
|
route('GET', '/api', async () => ({
|
|
service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size,
|
|
// the live window inventory — debugging state divergence at a glance
|
|
windows: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
|
|
}));
|
|
|
|
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
|
|
|
|
route('GET', '/api/packages', async () => clerkRawJson('packages'));
|
|
|
|
// the repo-fed prompts, read-only: per-project opening + guards and
|
|
// substrate invariants — never copied into a run, so the editor shows
|
|
// them as context, not as something to edit
|
|
route('GET', '/api/prompts', async () => ({
|
|
system: fs.readFileSync(path.join(ROOT, 'system.md'), 'utf8').trim(),
|
|
invariants: fs.readFileSync(path.join(ROOT, 'invariants.md'), 'utf8').trim(),
|
|
}));
|
|
|
|
// the clerk's list, enriched with what the server already knows: the
|
|
// open window, the pending ask, and the housekeeping bookkeeping. A
|
|
// run with no sessions is a draft — created, never started.
|
|
route('GET', '/api/runs', async () => {
|
|
const runs = clerkRawJson('runs');
|
|
for (const r of runs) {
|
|
const s = ctx.sessions.get(r.id);
|
|
r.open = !!s;
|
|
r.window = s?.stamp ?? null;
|
|
r.fresh = s?.fresh ?? false;
|
|
r.pendingAsk = s?.pendingAsk?.question ?? null;
|
|
r.lastSession = session.latestSession(r.id);
|
|
r.lastHousekept = session.lastHousekept(r.id);
|
|
}
|
|
return runs;
|
|
});
|
|
|
|
// create: the pc's name is required (unique per package); the
|
|
// package display name defaults to the package's own. The id is
|
|
// anonymous, generated by the clerk.
|
|
route('POST', '/api/runs', async ({ body }) => {
|
|
const pkg = String(body.package ?? '').trim();
|
|
const pc = String(body.pc ?? '').trim();
|
|
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages');
|
|
if (!pc) throw new HttpError(400, 'pc is required — the main character\'s name, distinct per package');
|
|
const name = body.name === undefined ? undefined : String(body.name);
|
|
const r = clerkRaw('--json', 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
|
|
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
|
const run = JSON.parse(r.out);
|
|
return { run, dir: `runs/${run.id}` };
|
|
});
|
|
|
|
// a name to play as: rolled from the dictionary, unused by any run
|
|
route('GET', '/api/names', async () => {
|
|
const all = fs.readFileSync(path.join(ROOT, 'names-female.txt'), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean);
|
|
const used = new Set(clerkRawJson('runs').flatMap((r) => (r.pc ? [String(r.pc).toLowerCase()] : [])));
|
|
const free = all.filter((n) => !used.has(n.toLowerCase()));
|
|
const pool = free.length ? free : all; // a fully-used dictionary still suggests
|
|
return { name: pool[Math.floor(Math.random() * pool.length)] };
|
|
});
|
|
|
|
route('GET', '/api/runs/:id', async ({ params }) => {
|
|
const id = params.id;
|
|
bundle.requireRun(id);
|
|
const st = clerkJson(id, '--json', 'status');
|
|
const s = ctx.sessions.get(id);
|
|
const meta = bundle.runMeta(id);
|
|
return {
|
|
run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null },
|
|
display: bundle.runDisplay(id),
|
|
open: !!s,
|
|
draft: session.latestSession(id) === null,
|
|
lastSession: session.latestSession(id),
|
|
window: s?.stamp ?? null,
|
|
fresh: s?.fresh ?? false,
|
|
paper: st.paper,
|
|
records: st.records,
|
|
fill: st.rings,
|
|
events: st.events,
|
|
pendingAsk: s?.pendingAsk?.question ?? null,
|
|
usage: s?.usage ?? null,
|
|
context: s?.usage ? {
|
|
used: s.usage.promptTokens,
|
|
window: cfg.contextWindow ?? null,
|
|
pct: cfg.contextWindow ? Math.round((100 * s.usage.promptTokens) / cfg.contextWindow) : null,
|
|
} : null,
|
|
};
|
|
});
|
|
|
|
// --- run files: the editor's surface ------------------------------------------
|
|
//
|
|
// A fixed whitelist, not a path API: state dirs are the clerk's
|
|
// alone. Craft files are writable; housekeeper.md is substrate-
|
|
// internal (repo-fed at wrap, never copied, not exposed here) and
|
|
// gm.md lives only in the notepad endpoints (the play-view pad);
|
|
// config is read-only (vars and lineage are easy to break blind).
|
|
// JSON writes are validated before landing.
|
|
|
|
const RUN_FILES = {
|
|
'backdrop.md': 'rw',
|
|
'character.md': 'rw',
|
|
'turn-0.md': 'rw',
|
|
'seed.json': 'rw',
|
|
'handbook.md': 'rw',
|
|
'settings.json': 'ro',
|
|
'run.json': 'ro',
|
|
};
|
|
|
|
route('GET', '/api/runs/:id/files', async ({ params }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
const files = {};
|
|
for (const [f, mode] of Object.entries(RUN_FILES)) {
|
|
const p = path.join(dir, f);
|
|
files[f] = fs.existsSync(p)
|
|
? { mode, exists: true, content: fs.readFileSync(p, 'utf8') }
|
|
: { mode, exists: false };
|
|
}
|
|
return { files };
|
|
});
|
|
|
|
route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
const f = params.path;
|
|
const mode = RUN_FILES[f];
|
|
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
|
|
if (mode !== 'rw') throw new HttpError(403, `${f} is read-only`);
|
|
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
|
|
if (f.endsWith('.json')) {
|
|
try { JSON.parse(body.content); } catch { throw new HttpError(400, `${f} rejected: not valid JSON`); }
|
|
}
|
|
fs.writeFileSync(path.join(dir, f), body.content);
|
|
return { ok: true, file: f, bytes: Buffer.byteLength(body.content) };
|
|
});
|
|
|
|
// prompt vars: the inputs the prompts themselves declare ($TOKENS
|
|
// found in any prompt file). Values live in the run's settings vars.
|
|
route('POST', '/api/runs/:id/vars', async ({ params, body }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
const vars = body.vars;
|
|
if (typeof vars !== 'object' || vars === null || Array.isArray(vars)) throw new HttpError(400, 'vars (an object of token -> value) is required');
|
|
for (const [k, v] of Object.entries(vars)) {
|
|
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(k)) throw new HttpError(400, `bad var name: ${JSON.stringify(k)}`);
|
|
if (typeof v !== 'string') throw new HttpError(400, `var ${k} must be a string`);
|
|
}
|
|
const settings = bundle.readSettings(params.id);
|
|
settings.vars = { ...(settings.vars ?? {}), ...vars };
|
|
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
|
return { ok: true, vars: settings.vars };
|
|
});
|
|
|
|
// the GM's notepad: the run's gm.md — always editable in the SPA,
|
|
// never in any bundle, never sent to any model (no assembly path
|
|
// reads it). Seeded from the package at creation, the GM's to keep.
|
|
route('GET', '/api/runs/:id/notes', async ({ params }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
const file = path.join(dir, 'gm.md');
|
|
return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' };
|
|
});
|
|
|
|
route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
|
|
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
|
|
return { ok: true };
|
|
});
|
|
|
|
// delete a DRAFT: a run with no sessions holds nothing but its copy,
|
|
// so the directory is the whole run and removal is complete. A played
|
|
// run is a story — deleting one is a deliberate act that stays by
|
|
// hand (Remove-Item runs/<id>), not a button.
|
|
route('DELETE', '/api/runs/:id', async ({ params }) => {
|
|
const dir = bundle.requireRun(params.id);
|
|
if (session.latestSession(params.id) !== null) {
|
|
throw new HttpError(409, `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
|
|
}
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
return { ok: true, deleted: params.id };
|
|
});
|
|
|
|
route('POST', '/api/runs/:id/windows', async ({ params, body }) => {
|
|
const id = params.id;
|
|
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
|
|
const s = session.openWindow(id, body.override === true);
|
|
ctx.sessions.set(id, s);
|
|
return {
|
|
window: s.stamp,
|
|
fresh: s.fresh,
|
|
notes: s.lines.filter((e) => e.t === 'note').map((e) => ({ kind: e.kind, ok: e.ok, detail: e.detail })),
|
|
};
|
|
});
|
|
|
|
route('GET', '/api/runs/:id/session', async ({ params }) => {
|
|
const s = ctx.sessions.get(params.id);
|
|
if (!s) throw new HttpError(404, `no open window for '${params.id}'`);
|
|
return {
|
|
run: params.id,
|
|
window: s.stamp,
|
|
entries: s.lines,
|
|
pendingAsk: s.pendingAsk?.question ?? null,
|
|
usage: s.usage,
|
|
};
|
|
});
|
|
|
|
route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
|
|
const line = String(body.line ?? '').trim();
|
|
if (!line) throw new HttpError(400, 'line is required');
|
|
return { ok: true, ...(await gmTurn(ctx, params.id, line)) };
|
|
});
|
|
|
|
// the opening beat as its own action: sent as the first GM turn on a
|
|
// fresh window — "start" is this right after window-open
|
|
route('POST', '/api/runs/:id/turn0', async ({ params }) => ({ ok: true, ...(await turn0(ctx, params.id)) }));
|
|
|
|
route('POST', '/api/runs/:id/ask', async ({ params, body }) => {
|
|
const answer = String(body.answer ?? '').trim();
|
|
if (!answer) throw new HttpError(400, 'answer is required');
|
|
return { ok: true, ...(await answerAsk(ctx, params.id, answer)) };
|
|
});
|
|
|
|
route('GET', '/api/runs/:id/status', async ({ params }) => {
|
|
bundle.requireRun(params.id);
|
|
const s = ctx.sessions.get(params.id);
|
|
return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null };
|
|
});
|
|
|
|
// the GM's out-of-band paper override: whole-paper replace via the
|
|
// clerk (which journals the prior state). Descriptions never contain
|
|
// commas — the transport is comma-separated — so a comma inside an
|
|
// item is a 400, not a silent corruption later.
|
|
route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
|
|
const id = params.id;
|
|
bundle.requireRun(id);
|
|
const items = body.items;
|
|
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
|
|
for (const it of items) {
|
|
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
|
|
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
|
}
|
|
const paper = clerkJson(id, '--gm', 'paper-set', ...items);
|
|
return { ok: true, paper };
|
|
});
|
|
|
|
route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
|
|
// ends the window and kicks the async chain; poll GET for the outcome
|
|
const job = housekeeping.trigger(ctx, params.id);
|
|
return { state: job.state, session: job.session };
|
|
});
|
|
|
|
// dry-run the housekeeper over a session log: the same transcript
|
|
// assembly the real wrap uses, a real housekeeper call, the manifest
|
|
// saved for review — but nothing applied, no window ended, no state
|
|
// touched. The way to iterate on housekeeper.md against real data
|
|
// without playing more; works on the open window too.
|
|
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
|
|
const id = params.id;
|
|
bundle.requireRun(id);
|
|
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
|
|
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
|
|
let lines;
|
|
try {
|
|
lines = session.loadSession(id, stamp).lines;
|
|
} catch {
|
|
throw new HttpError(404, `no such session: ${stamp}`);
|
|
}
|
|
if (!lines.some((e) => e.t === 'msg')) throw new HttpError(409, 'that session has no exchange to review');
|
|
const dir = path.join(bundle.runDir(id), 'manifests');
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
const text = ctx.mock
|
|
? housekeeping.mockManifest(stamp)
|
|
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp));
|
|
let mf;
|
|
try {
|
|
mf = housekeeping.parseManifest(text);
|
|
} catch (e) {
|
|
const raw = path.join(dir, `${stamp}.replay.raw.md`);
|
|
fs.writeFileSync(raw, String(text));
|
|
return { ok: true, parsed: false, session: stamp, file: `manifests/${stamp}.replay.raw.md`, reason: e.message };
|
|
}
|
|
const file = path.join(dir, `${stamp}.replay.json`);
|
|
fs.writeFileSync(file, JSON.stringify(mf, null, 2) + '\n');
|
|
return { ok: true, parsed: true, session: stamp, file: `manifests/${stamp}.replay.json`, manifest: mf };
|
|
});
|
|
|
|
route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id));
|
|
|
|
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
|
|
|
|
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
|
|
// the recovery path: apply a (hand-edited) manifest directly — closes
|
|
// any open window, marks the latest session housekept, autorestarts
|
|
const id = params.id;
|
|
bundle.requireRun(id);
|
|
const file = String(body.file ?? '').trim();
|
|
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json');
|
|
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
|
|
if (!manifestPath.startsWith(path.join(ROOT, 'runs', id))) throw new HttpError(400, 'file must stay inside the run dir');
|
|
if (!fs.existsSync(manifestPath)) throw new HttpError(404, `no such manifest: ${file}`);
|
|
const latest = session.latestSession(id);
|
|
if (!latest) throw new HttpError(409, 'no session to mark housekept');
|
|
ctx.sessions.delete(id); // housekeeping always ends the window
|
|
try {
|
|
const next = housekeeping.applyAndRestart(ctx, id, manifestPath, latest);
|
|
return { ok: true, housekept: latest, window: next.stamp };
|
|
} catch (e) {
|
|
const job = { state: 'rejected', session: latest, reason: e.message };
|
|
ctx.jobs.set(id, job);
|
|
throw new HttpError(422, e.message);
|
|
}
|
|
});
|
|
|
|
// --- dispatch -------------------------------------------------------------------
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const started = Date.now();
|
|
try {
|
|
const url = new URL(req.url, 'http://localhost');
|
|
// the request log: one line per API call — reconstruct any session
|
|
// from the console output after the fact
|
|
res.on('finish', () => {
|
|
if (url.pathname.startsWith('/api')) {
|
|
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
|
|
}
|
|
});
|
|
if (!url.pathname.startsWith('/api')) {
|
|
if (req.method !== 'GET') throw new HttpError(405, 'static files are GET-only');
|
|
serveStatic(url.pathname, res);
|
|
return;
|
|
}
|
|
const m = match(req.method, url.pathname);
|
|
if (!m) throw new HttpError(404, `no such route: ${req.method} ${url.pathname}`);
|
|
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {};
|
|
send(res, 200, await m.handler({ params: m.params, body, req }));
|
|
} catch (e) {
|
|
const status = e.status ?? 500;
|
|
if (status >= 500) console.error(`server: ${e.stack ?? e.message}`);
|
|
send(res, status, { error: e.message, ...(e.detail ? { detail: e.detail } : {}) });
|
|
}
|
|
});
|
|
|
|
const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
|
|
server.listen(Number(port), host, () => {
|
|
console.log(`rp-test server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} window(s) rebuilt`);
|
|
});
|