Files
tiny-worlds/server/main.mjs
T
mute e763d6c146 the access round: spectator mode removed and reads made story-only -- the table, raw session, carryover, files, status, and the notepad are owner-only; the story is the one public read (any signed-in user, fork button on it that copies the run that made the story, never the view); #28's human-side open read overturned with the ruling, gm.md stays never model-facing; non-owners land in the story view (play/setup redirect on the 403, home cards link there directly), the story view names its owner and stands alone on the story response, which now carries display/owner/ownerName; the table gains a raw tab -- the whole log as it rode the wire (thinking, every variant block, every reminder copy, full tool results, rides inline) next to the curated projection, live sessions only, sticky across turn re-renders; --debug mode for easy testing: every request is a fixed superuser that bypasses the users db entirely, no invite dance, loopback-bound regardless of config (found live: the SPA boot only asked the server who it was when a token existed, so tokenless browsers never learned they were the debug user -- boot now always asks); lint rule 10: no laptop-visible facts anywhere and all commits always from Mute -- the username and home paths are derived at runtime so the checker never contains them, scanned over the tracked tree, every historical blob, and commit messages, identity enforced on author and committer on every ref plus git config; the queue split: resolved questions relocated to DECISIONS.md verbatim by number (day's words kept, reversals annotate never rewrite, the agenda/reminder trio gets its own section), QUESTIONS is open items only (stale OPENs resolved on the way: #10 by the 2026-11-13 pairing default, #11 by the raw tab); smoke reworked to the story-only battery -- ash 403s on every run surface, 200 on the story alone, the ownerless-run check rides the runs list; all twelve QUESTIONS-number citations re-pointed at DECISIONS; smoke ALL PASS in a worktree (111 checks), two-user browser pass (the non-owner's whole run surface is a 403 detail and a 200 story, back-to-table hidden, owner views intact), raw-tab browser pass (curated table leak-free, raw shows the whole variants block, tabs vanish on dormancy), typecheck green on both programs, check-repo clean
2026-11-15 22:37:06 +00:00

982 lines
44 KiB
JavaScript

// server/main.mjs -- entry + REST spine.
//
// Synchronous JSON over HTTP; the SPA and curl are both just clients.
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation, model call, and run read (the story is the one
// public surface), fork for everyone. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// session back from the jsonl -- the log is the truth, the context is a
// view.
//
// Debug mode (--debug): every request is one fixed superuser that
// bypasses the user database entirely -- no invite dance, no tokens.
// Loopback-bound whatever the config says. Testing only, never a real
// deployment.
//
// usage: node server/main.mjs [--mock] [--debug]
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./users.mjs').UserRow} UserRow */
/** A request as a handler sees it: path params, the parsed JSON body
* (any -- handlers validate), the raw request, the acting user. */
/** @typedef {{ params: Record<string, string>, body: any, req: import('node:http').IncomingMessage, user: ?UserRow }} Req */
/** @typedef {(req: Req) => unknown} Handler */
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, clerk } from './clerk.mjs';
import * as bundle from './bundle.mjs';
import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs';
import { effectiveContents } from './variants.mjs';
import { gmTurn, answerAsk, openingCall, HttpError } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock');
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
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 = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
const provider = makeProvider(cfg.endpoint ?? {});
// locks/enqueue are attached just below; the cast is the two-step that
// lets the literal precede them
const ctxBase = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
/** @type {Ctx} */
const ctx = /** @type {Ctx} */ (ctxBase);
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, start, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (status-set, file writes) need no lock: they
// block the event loop and are atomic by construction.
ctx.locks = new Map();
ctx.enqueue = (runId, fn) => {
const prev = ctx.locks.get(runId) ?? Promise.resolve();
const next = prev.then(fn, fn); // run regardless of a prior failure
ctx.locks.set(runId, /** @type {Promise<void>} */ (next.catch(() => {})));
return next;
};
// --- bootstrap: the fresh-deployment superuser invite ---------------------------
if (DEBUG) {
console.warn('debug mode: every request is the superuser -- no invites, no tokens; testing only, never a real deployment');
}
const boot = DEBUG ? null : users.bootstrap(); // debug skips the invite dance entirely
if (boot?.code) {
console.log(`fresh deployment -- the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`);
console.log(` ${boot.code}`);
} else if (boot?.reused) {
console.log(`fresh deployment -- the superuser invite waits at ${path.relative(ROOT, users.bootstrapFile)}`);
}
// --- boot --------------------------------------------------------------------
//
// The log is the truth, the context is a view. A stop that died in
// flight resumes first (every step idempotent); then every live
// session reopens from its jsonl.
if (fs.existsSync(path.join(ROOT, 'runs'))) {
for (const d of fs.readdirSync(path.join(ROOT, 'runs'), { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
if (!fs.existsSync(path.join(ROOT, 'runs', d.name, 'run.json'))) continue;
const stalled = session.findStalledStop(d.name);
if (stalled) {
session.stopSession(d.name, stalled.from);
console.log(`boot: resumed the interrupted stop of session ${stalled.from} in '${d.name}' -- housekeeping is pending, re-run it`);
}
const live = session.liveSession(d.name);
if (live != null) ctx.sessions.set(d.name, session.loadSession(d.name, live));
}
}
// --- http plumbing -----------------------------------------------------------
/** @param {import('node:http').ServerResponse} res @param {number} status @param {unknown} body */
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);
};
/** @param {import('node:http').IncomingMessage} req @returns {Promise<any>} */
const readBody = (req) => new Promise((resolve, reject) => {
/** @type {Buffer[]} */
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);
});
/** @type {{ method: string, segs: string[], handler: Handler, publicRoute: boolean }[]} */
const routes = [];
/** @param {string} method @param {string} pattern @param {Handler} handler @param {{ public?: boolean }} [opts] */
const route = (method, pattern, handler, opts = {}) =>
routes.push({ method, segs: pattern.split('/').filter(Boolean), handler, publicRoute: opts.public === true });
/** @param {string} method @param {string} pathname @returns {?{ handler: Handler, params: Record<string, string>, publicRoute: boolean }} */
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;
/** @type {Record<string, string>} */
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, publicRoute: r.publicRoute };
}
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');
/** @type {Record<string, string>} */
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',
};
/** @param {string} pathname @param {import('node:http').ServerResponse} res */
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);
}
// --- identity: session, claim, invites, users ---------------------------------
//
// Identity is a bearer token (server/users.mjs). Two routes are
// public: reading your own session (null when signed out) and
// claiming an invite. Everything else -- reads included -- requires a
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
// debug mode: the fixed identity. authenticate() returns it for every
// request -- no token, no lookup; users.mjs is bypassed entirely, and
// these wrappers make the id resolve as an owner through the same
// ownership code (a user the db never heard of).
const DEBUG_ID = 'debug';
/** @type {UserRow} */
const DEBUG_USER = { id: DEBUG_ID, token_hash: '', name: 'Debug', superuser: 1, created: '' };
/** @param {?string|undefined} uid @returns {boolean} */
const userExists = (uid) => (DEBUG && uid === DEBUG_ID) || users.exists(uid ?? null);
/** @param {?string|undefined} uid @returns {?string} */
const userName = (uid) => (DEBUG && uid === DEBUG_ID ? 'Debug' : users.userName(uid ?? null));
route('GET', '/api/session', async ({ user }) => ({
// the public shape only -- the stored row (token hash) never leaves
user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null,
fresh: users.userCount() === 0,
}), { public: true });
route('POST', '/api/claim', async ({ body }) => {
const r = users.claimInvite(body.code, body.name);
return { token: r.token, user: r.user };
}, { public: true });
// superuser: mint an invite -- the code is returned once, never stored
route('POST', '/api/invites', async ({ user }) => {
requireSuperuser(user);
return users.mintInvite(user.id);
});
// superuser: the invite ledger, hashes only -- codes are never listed
route('GET', '/api/invites', async ({ user }) => {
requireSuperuser(user);
const list = users.listInvites().map((i) => ({
id: i.id,
kind: i.kind,
created_at: i.created_at,
state: i.claimed_by == null ? 'unclaimed' : `claimed by ${userName(i.claimed_by) ?? i.claimed_by}`,
}));
return { invites: list };
});
// superuser: revoke an unclaimed invite (handed to the wrong chat)
route('DELETE', '/api/invites/:id', async ({ params, user }) => {
requireSuperuser(user);
if (!users.revokeInvite(Number(params.id))) throw new HttpError(409, 'no such unclaimed invite');
return { ok: true };
});
route('GET', '/api/users', async ({ user }) => {
requireSuperuser(user);
return { users: users.listUsers() };
});
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched -- the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open sessions close.
route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
requireSuperuser(user);
if (params.id === user.id) throw new HttpError(409, 'revoking yourself would lock the deployment out of its superuser');
if (!users.revokeUser(params.id)) throw new HttpError(404, `no such user: ${params.id}`);
for (const id of [...ctx.sessions.keys()]) {
if (bundle.runMeta(id)?.owner === params.id) ctx.sessions.delete(id);
}
return { ok: true };
});
/** @param {?UserRow} user */
/**
* @param {?UserRow} user
* @returns {asserts user is UserRow}
*/
function requireSuperuser(user) {
if (!user?.superuser) throw new HttpError(403, 'superuser only');
}
// the router already guarantees this on every protected route; the
// type system needs it said out loud
/**
* @param {?UserRow} user
* @returns {asserts user is UserRow}
*/
function requireUser(user) {
if (!user) throw new HttpError(401, 'not signed in');
}
// ownership is resolved, never maintained: run.json keeps the record
// of who owned a run, and a dead owner id (revocation) resolves to
// absent. The API never exposes a dangling id.
/** @param {?string|undefined} owner @returns {?string} */
const resolveOwner = (owner) => (owner != null && userExists(owner) ? owner : null);
// ownership: every GM action -- every mutation, every model call --
// and the whole working surface (table, raw session, carryover,
// files, status, notepad) is the owner's alone; the story is the one
// public read. Ownerless runs (pre-user or revoked owner) are one
// uniform state: story-readable, forkable, never re-claimed.
/**
* @param {?UserRow} user @param {string} runId
* @returns {asserts user is UserRow}
*/
function requireOwner(user, runId) {
if (!user) throw new HttpError(401, 'not signed in'); // the router guarantees this on protected routes
bundle.requireRun(runId); // 404 when it doesn't exist
const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
if (resolveOwner(meta.owner) == null) {
throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`);
}
if (meta.owner !== user.id) {
throw new HttpError(403, `run '${runId}' is ${userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`);
}
}
// --- routes -------------------------------------------------------------------
route('GET', '/api', async () => ({
service: 'tiny-worlds', mock: MOCK, openSessions: ctx.sessions.size,
// the live session inventory -- debugging state divergence at a glance
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
}));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
route('GET', '/api/packages', async () => {
const pkgs = clerkRawJson('packages');
for (const p of pkgs) {
if (p.origin === 'user') {
p.owner = resolveOwner(p.owner);
p.ownerName = p.owner == null ? null : userName(p.owner);
}
}
return pkgs;
});
// save a run's craft as a new user package, published to every user
// (gm.md included -- saving is the act of publishing). The pc never
// rides: the next create asks for one.
route('POST', '/api/packages', async ({ body, user }) => {
const from = String(body.from ?? '').trim();
const name = String(body.name ?? '').trim();
if (!from) throw new HttpError(400, 'from (a run id) is required');
if (!name) throw new HttpError(400, 'name (the new package\'s display name) is required');
requireOwner(user, from);
const r = clerk(from, '--json', '--owner', user.id, 'save-package', name);
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'save-package failed');
return { package: JSON.parse(r.out) };
});
// the repo-fed prompts, read-only: per-project opening + guards,
// substrate invariants, and the per-turn reminder -- never copied into
// a run, so the editor shows them as context, not as something to edit
route('GET', '/api/prompts', async () => {
const readOpt = (/** @type {string} */ f) => (fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), 'utf8').trim() : null);
return {
system: readOpt('system.md'),
invariants: readOpt('invariants.md'),
reminder: readOpt('reminder.md'),
};
});
// the clerk's list, enriched with what the server already knows: the
// live session, the pending ask, and the phase bookkeeping. A run's
// state is its latest session's -- live while one plays, else dormant
// (the review window); a draft is a dormant session one.
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.session = s?.n ?? null;
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.owner = resolveOwner(r.owner);
r.ownerName = r.owner == null ? null : userName(r.owner);
}
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, user }) => {
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);
requireUser(user);
const r = clerkRaw('--quiet', '--json', '--owner', user.id, '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(/** @type {{ pc?: string }[]} */ (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, user }) => {
const id = params.id;
requireOwner(user, id); // the table's face: panes, meter, phase -- the owner's
const st = clerkJson(id, '--json', 'report');
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
const latest = session.latestSession(id);
const sm = latest == null ? {} : session.sessionMeta(id, latest);
const phase = s ? 'live' : (sm.phase ?? null);
return {
run: {
id,
package: meta?.package ?? null,
created: meta?.created ?? null,
forked: meta?.forked ?? null,
owner,
ownerName: owner == null ? null : userName(owner),
models: meta?.models ?? {},
modelDefaults: ctx.cfg.models ?? {},
},
display: bundle.runDisplay(id),
open: !!s,
phase,
session: s?.n ?? null,
sessions: latest ?? 0,
draft: phase === 'dormant' && latest === 1, // a never-started run
ready: sm.ready ?? null,
status: st.status,
agenda: st.agenda,
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,
contwin: cfg.contwin ?? null,
pct: cfg.contwin ? Math.round((100 * s.usage.promptTokens) / cfg.contwin) : null,
} : null,
};
});
// --- run files: the editor's surface ------------------------------------------
//
// A fixed whitelist, not a path API: state dirs are the clerk's
// alone. The ADDRESSED session is the live one while one plays, else
// the latest (the dormant one during the review window). Its bundle
// (the frozen craft) is writable only while dormant; the authored
// carryover of session one is authoring material (writable), a
// continuation carryover is conversation (read-only until the editor
// task); memory.json is inert provenance, read-only. housekeeper.md
// is substrate-internal (repo-fed at housekeeping, 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).
/** One file of the editor surface. */
/** @typedef {{ mode: string, path: string }} FileSpec */
/** @param {string} runId @returns {{ n: number, phase?: string, files: Record<string, FileSpec> }} */
function fileSurface(runId) {
const live = ctx.sessions.get(runId);
const latest = session.latestSession(runId);
if (latest == null) throw new HttpError(409, 'this run has no sessions');
const n = live?.n ?? latest;
const dir = session.sessionDir(runId, n);
const phase = live ? 'live' : session.sessionMeta(runId, n).phase;
const dormant = phase === 'dormant';
const rw = dormant ? 'rw' : 'ro';
const root = bundle.runDir(runId);
const spec = {
'handbook.md': { mode: rw, path: path.join(dir, 'bundle', 'handbook.md') },
'backdrop.md': { mode: rw, path: path.join(dir, 'bundle', 'backdrop.md') },
'character.md': { mode: rw, path: path.join(dir, 'bundle', 'character.md') },
'carryover.jsonl': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'carryover.jsonl') },
'memory.json': { mode: 'ro', path: path.join(dir, 'memory.json') }, // session one's provenance; absent later
'settings.json': { mode: 'ro', path: path.join(root, 'settings.json') },
'run.json': { mode: 'ro', path: path.join(root, 'run.json') },
};
return { n, phase, files: spec };
}
route('GET', '/api/runs/:id/files', async ({ params, user }) => {
requireOwner(user, params.id); // the craft is working material
const surf = fileSurface(params.id);
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */
const files = {};
for (const [f, spec] of Object.entries(surf.files)) {
files[f] = fs.existsSync(spec.path)
? { mode: spec.mode, exists: true, content: fs.readFileSync(spec.path, 'utf8') }
: { mode: spec.mode, exists: false };
}
return { session: surf.n, phase: surf.phase, files };
});
route('PUT', '/api/runs/:id/files/:path', async ({ params, body, user }) => {
bundle.requireRun(params.id);
requireOwner(user, params.id);
const surf = fileSurface(params.id);
const f = params.path;
const spec = surf.files[f];
if (!spec) throw new HttpError(404, `no such run file in the API surface: ${f}`);
if (spec.mode !== 'rw') throw new HttpError(403, `${f} is read-only (session ${surf.n} is ${surf.phase})`);
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
if (f === 'carryover.jsonl') {
// the save-time lint: only clean openings land (the start lint is
// the backstop, not the first line of defense)
const lines = [];
const raw = body.content.split('\n');
for (let i = 0; i < raw.length; i++) {
if (!raw[i].trim()) continue;
try {
lines.push(JSON.parse(raw[i]));
} catch {
throw new HttpError(400, `not valid JSONL: line ${i + 1} does not parse`);
}
}
const errors = session.lintCarryover(lines, { authored: surf.n === 1 });
if (errors.length) throw new HttpError(400, `the carryover did not pass the lint: ${errors.join('; ')}`);
}
fs.writeFileSync(spec.path, 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, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, 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 run's models: per-run overrides of the deployment defaults
// (server.json), selected from the upstream listing (GET /api/models).
// Owner-only, changeable at any time -- every call resolves fresh, so a
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default.
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
for (const k of Object.keys(body)) {
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} -- player and housekeeper`);
}
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const models = meta.models ?? {};
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
if (body[role] === undefined) continue;
if (body[role] === null) { delete models[role]; continue; }
const m = String(body[role]).trim();
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
models[role] = m;
}
if (Object.keys(models).length) meta.models = models;
else delete meta.models;
fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
return { ok: true, models: meta.models ?? {}, defaults: ctx.cfg.models ?? {} };
});
// the GM's notepad: the run's gm.md -- the owner's alone (#28's
// human-side open read overturned 2026-11-15), never in any bundle,
// never sent to any model (no assembly path reads it -- the model
// boundary stands). Seeded from the package at creation, the GM's to
// keep.
route('GET', '/api/runs/:id/notes', async ({ params, user }) => {
requireOwner(user, params.id);
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, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id); // the pad is owner-only in both directions
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 whose sessions were never started 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, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
const played = session.listSessions(params.id).some((n) => fs.existsSync(path.join(session.sessionDir(params.id, n), 'log.jsonl')));
if (played) {
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 };
});
// start: the dormant session goes live -- lint the carryover, freeze
// the bundle, consume the carryover into the log. If the carryover
// ends on a GM turn, that turn is her cue: the first request of the
// assembled contwin fires automatically. Everything rides the run's
// activity lock (serialized with turns and the housekeeping job).
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
const cur = ctx.sessions.get(id);
if (cur) throw new HttpError(409, `session ${cur.n} is already live -- one active session per run`);
return ctx.enqueue(id, async () => {
const { session: s, autoSend } = session.startSession(id, { override: body.override === true });
ctx.sessions.set(id, s);
const out = { ok: true, session: s.n, autoSend };
if (autoSend) return { ...out, ...(await openingCall(ctx, id, user)) };
return out;
});
});
route('GET', '/api/runs/:id/session', async ({ params, user }) => {
requireOwner(user, params.id); // the raw audit surface
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no live session for '${params.id}'`);
return {
run: params.id,
session: s.n,
entries: s.lines,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
};
});
// the carryover: the dormant session's opening material, raw and
// read-only -- the review window's preview of the next contwin. Same
// projection as the table (the picked variant only, thinking stays in
// the raw log), plus the ending that decides the opening flow.
route('GET', '/api/runs/:id/carryover', async ({ params, user }) => {
requireOwner(user, params.id); // the table's dormant stand-in
const live = ctx.sessions.get(params.id);
if (live) throw new HttpError(409, `session ${live.n} is live -- the table is the surface`);
const latest = session.latestSession(params.id);
if (latest == null) throw new HttpError(404, 'no sessions');
const meta = session.sessionMeta(params.id, latest);
if (meta.phase !== 'dormant') throw new HttpError(409, `session ${latest} is ${meta.phase || 'unmarked'}`);
const p = path.join(session.sessionDir(params.id, latest), 'carryover.jsonl');
/** @type {import('./shapes.mjs').LogEvent[]} */
const lines = [];
if (fs.existsSync(p)) {
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
if (!l.trim()) continue;
try {
lines.push(JSON.parse(l));
} catch {
throw new HttpError(422, 'the carryover is not valid JSONL -- fix it before start');
}
}
}
const eff = effectiveContents(lines);
const entries = lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
/** @type {import('./shapes.mjs').ViewMessage} */
const m = { role: 'assistant', content: eff.has(i) ? (eff.get(i) ?? null) : (e.m.content ?? null) };
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
return { ...e, m };
}
return e;
});
const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null);
return {
run: params.id,
session: latest,
ready: meta.ready === true,
entries,
ends: lastMsg == null ? null : (lastMsg.m.role === 'user' ? 'gm' : 'player'),
};
});
// the table: the play surface's projection of the live session --
// what the GM needs at the table. Same envelope as /session,
// different policy over the same log: thinking never crosses the
// wire, variant turns carry only the picked variant. The raw
// /session stays whole as the audit surface (the table's raw tab
// in the SPA); during dormancy the
// /carryover endpoint is the table's stand-in.
route('GET', '/api/runs/:id/table', async ({ params, user }) => {
requireOwner(user, params.id); // the table is the owner's working surface
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no live session for '${params.id}'`);
const eff = effectiveContents(s.lines);
const entries = s.lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
/** @type {import('./shapes.mjs').ViewMessage} */
const m = { role: 'assistant', content: eff.has(i) ? (eff.get(i) ?? null) : (e.m.content ?? null) };
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
return { ...e, m };
}
return e;
});
// the variantary metric: how variant she tends to be, straight off
// the pick notes (counted, never content)
const picks = s.lines.filter((e) => e.t === 'note' && e.kind === 'pick');
return {
run: params.id,
session: s.n,
entries,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
variance: {
picks: picks.length,
offered: picks.reduce((a, p) => a + (p.count ?? 0), 0),
maxVariants: picks.reduce((a, p) => Math.max(a, p.count ?? 0), 0),
},
};
});
// the story: the whole deliverable, read-only -- every non-dropped
// literature turn from the opening to the last recorded, across all
// sessions in order. OOC, tool calls, substrate verbs, thinking,
// rings, machinery: all out; load-bearing prose living inside OOC
// only is a GM protocol violation, and the story enforces that by
// omission. A dormant session's carryover is the story's live edge:
// its raw lines project like any log's, at the chronological end --
// GM edits during dormancy show, because the carryover is the current
// truth of where the story stands. The public reading surface: any
// signed-in user; the table and everything else in the run is the
// owner's.
route('GET', '/api/runs/:id/story', async ({ params }) => {
bundle.requireRun(params.id);
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
const verbs = /<(lost|gained|add|drop)>[\s\S]*?<\/\1>/g;
const project = (/** @type {import('./shapes.mjs').LogEvent[]} */ lines) => {
const eff = effectiveContents(lines);
/** @type {{ who: string, text: string }[]} */
const turns = [];
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
if (e.t !== 'msg' || e.reminder) continue;
if (e.m.role === 'user' && !e.conflictOnly) {
const text = String(e.m.content ?? '').replace(rides, '').trim();
if (text) turns.push({ who: 'gm', text });
} else if (e.m.role === 'assistant' && !e.m.tool_calls?.length) {
// tool prose is for the tool result turn, not the story
const text = String(eff.has(i) ? eff.get(i) : (e.m.content ?? '')).replace(verbs, '').trim();
if (text) turns.push({ who: 'player', text });
}
}
return turns;
};
/** @param {string} p @returns {import('./shapes.mjs').LogEvent[]} */
const readJsonl = (p) => {
/** @type {import('./shapes.mjs').LogEvent[]} */
const out = [];
if (!fs.existsSync(p)) return out;
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
if (!l.trim()) continue;
try {
out.push(JSON.parse(l));
} catch {
// a malformed line fails loud at start; the story skips it
}
}
return out;
};
const sessions = [];
for (const n of session.listSessions(params.id)) {
const dir = session.sessionDir(params.id, n);
const meta = session.sessionMeta(params.id, n);
const lines = readJsonl(path.join(dir, 'log.jsonl'));
const turns = project(lines);
if (meta.phase === 'dormant') {
turns.push(...project(readJsonl(path.join(dir, 'carryover.jsonl'))));
}
if (turns.length) sessions.push({ session: n, turns });
}
// the public face rides along: what the run is called and whose it
// is -- the story view stands alone (the detail it used to lean on
// is owner-only now)
const meta = bundle.runMeta(params.id);
const owner = resolveOwner(meta?.owner);
return { run: params.id, display: bundle.runDisplay(params.id), owner, ownerName: owner == null ? null : userName(owner), sessions };
});
route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
const line = String(body.line ?? '').trim();
if (!line) throw new HttpError(400, 'line is required');
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user))) };
});
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required');
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user))) };
});
// fork: any user, any run -- a mechanical atomic copy with the owner
// replaced (server/fork.mjs). The source's activity lock is held, so
// the copy is never taken mid-turn.
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
bundle.requireRun(params.id);
requireUser(user); // any signed-in user forks; the router guarantees this
const u = user;
return ctx.enqueue(params.id, async () => forkRun(ctx, params.id, u));
});
route('GET', '/api/runs/:id/status', async ({ params, user }) => {
requireOwner(user, params.id); // status and agenda are machinery
return { status: clerkJson(params.id, 'status'), agenda: clerkJson(params.id, 'agenda') };
});
// the GM's out-of-band status override: whole-status 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/status', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, 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 status');
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 status = clerkJson(id, '--gm', 'status-set', ...items);
return { ok: true, status };
});
// the GM's out-of-band agenda override: whole-queue replace via the
// clerk (journaled). Items land in written order, first = top; an
// empty array clears it. Commas are the add transport's separator --
// an item containing one is a 400, not a silent split later.
route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, 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 agenda');
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, `items never contain commas (the add transport is comma-separated): ${JSON.stringify(it)}`);
}
const agenda = clerkJson(id, '--gm', 'agenda-set', ...items);
return { ok: true, agenda };
});
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// with a live session this is STOP (close, move the tail, freeze,
// then the pass); with a dormant latest it is the RE-RUN. Poll GET
// for the outcome.
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
return { state: job.state, phase: job.phase, session: job.session, target: job.target ?? null };
});
// dry-run the housekeeper over a session log: the same transcript
// assembly the real housekeeping uses, a real housekeeper call, the manifest
// saved for review -- but nothing applied, no state touched. The way
// to iterate on housekeeper.md against real data without playing
// more; works on the live session and on finished ones alike.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id); // a replay spends a model call on the shared key
const latest = session.latestSession(id);
if (latest == null) throw new HttpError(409, 'no session to replay -- this run has none');
// default: the newest session that has a log -- the live one, else
// the finished predecessor of a dormant latest
const n = body?.session != null ? Number(body.session) : (ctx.sessions.get(id)?.n ?? latest - 1);
if (!Number.isInteger(n) || n < 1) throw new HttpError(409, 'no session log to replay yet');
let lines;
try {
lines = session.loadSession(id, n).lines;
} catch {
throw new HttpError(404, `no such session log: ${n}`);
}
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(n)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, n, lines), user);
let mf;
try {
mf = housekeeping.parseManifest(text);
} catch (e) {
const raw = path.join(dir, `${n}.replay.raw.md`);
fs.writeFileSync(raw, String(text));
return { ok: true, parsed: false, session: n, file: `manifests/${n}.replay.raw.md`, reason: e.message };
}
const file = path.join(dir, `${n}.replay.json`);
fs.writeFileSync(file, JSON.stringify(mf, null, 2) + '\n');
return { ok: true, parsed: true, session: n, file: `manifests/${n}.replay.json`, manifest: mf };
});
route('GET', '/api/runs/:id/housekeeping', async ({ params, user }) => {
requireOwner(user, params.id); // the job state is machinery
return housekeeping.jobState(ctx, params.id);
});
route('GET', '/api/runs/:id/housekeeping/log', async ({ params, user }) => {
requireOwner(user, params.id); // the apply log is machinery
return housekeeping.latestLog(params.id);
});
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly -- the
// rebase + apply + ready, into the dormant continuation session
const id = params.id;
bundle.requireRun(id);
requireOwner(user, 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/<session>.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 == null || latest < 2) throw new HttpError(409, 'no dormant continuation session to apply into');
if (session.sessionMeta(id, latest).phase !== 'dormant') throw new HttpError(409, `session ${latest} is not dormant`);
return ctx.enqueue(id, async () => {
try {
housekeeping.applyToDormant(id, manifestPath, latest - 1);
return { ok: true, housekept: latest - 1, target: latest };
} catch (e) {
ctx.jobs.set(id, { state: 'rejected', session: latest - 1, reason: e.message });
throw new HttpError(422, e.message);
}
});
});
// --- dispatch -------------------------------------------------------------------
// bearer-token identity (users.mjs); null when absent or unknown
/** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */
function authenticate(req) {
if (DEBUG) return DEBUG_USER; // debug: everyone is the superuser
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
return m ? users.getUserByToken(m[1].trim()) : null;
}
const server = http.createServer(async (req, res) => {
const started = Date.now();
/** @type {?UserRow} */
let user = null;
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; the acting user rides
// every line (attribution, #22)
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${user ? ` u:${user.id}` : ''}`);
}
});
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(String(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) : {};
user = authenticate(req);
if (!m.publicRoute && !user) throw new HttpError(401, 'not signed in -- claim an invite first (POST /api/claim)');
send(res, 200, await m.handler({ params: m.params, body, req, user }));
} 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 } : {}) });
}
});
// debug never leaves this machine: whatever the config binds, the
// debug host is loopback (the port stays configurable)
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
const host = DEBUG ? '127.0.0.1' : cfgHost;
server.listen(Number(port ?? 7350), host, () => {
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
});