gm surface: home flow, run identity, full-assembly editor, notepad, wrap replay; sigils and dateless rings
This commit is contained in:
+216
-13
@@ -1,10 +1,9 @@
|
||||
// server/main.mjs — entry + REST spine.
|
||||
//
|
||||
// Loopback, single-human, synchronous JSON. The SPA (later) 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. Housekeeping endpoints answer
|
||||
// 501 until phase 3 lands the job.
|
||||
// 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';
|
||||
@@ -16,7 +15,7 @@ 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, HttpError } from './loop.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');
|
||||
@@ -103,7 +102,12 @@ function serveStatic(pathname, res) {
|
||||
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()) {
|
||||
send(res, 404, { error: `no such file: ${rel}` });
|
||||
// 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);
|
||||
@@ -113,21 +117,63 @@ function serveStatic(pathname, res) {
|
||||
|
||||
// --- routes -------------------------------------------------------------------
|
||||
|
||||
route('GET', '/api', async () => ({ service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size }));
|
||||
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'));
|
||||
route('GET', '/api/runs', async () => clerkRawJson('runs'));
|
||||
|
||||
// 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 name = String(body.name ?? '').trim();
|
||||
const pkg = String(body.package ?? '').trim();
|
||||
if (!/^[a-z0-9-]+$/.test(name)) throw new HttpError(400, 'name must be a slug (lowercase letters, digits, dashes)');
|
||||
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');
|
||||
const r = clerkRaw('create', pkg, name, ...(body.model ? [String(body.model)] : []));
|
||||
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');
|
||||
return { run: bundle.runMeta(name), dir: `runs/${name}` };
|
||||
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 }) => {
|
||||
@@ -138,7 +184,10 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
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,
|
||||
@@ -155,6 +204,96 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
};
|
||||
});
|
||||
|
||||
// --- 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`);
|
||||
@@ -185,6 +324,10 @@ route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
|
||||
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');
|
||||
@@ -197,12 +340,64 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
|
||||
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));
|
||||
@@ -233,8 +428,16 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
|
||||
// --- 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);
|
||||
|
||||
Reference in New Issue
Block a user