jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases

This commit is contained in:
2026-11-15 15:28:56 +00:00
parent d737e47f82
commit f81b188ce1
22 changed files with 594 additions and 90 deletions
+78 -21
View File
@@ -8,6 +8,13 @@
// view.
//
// usage: node server/main.mjs [--mock]
/** @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';
@@ -30,10 +37,14 @@ 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 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 ?? {});
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
// 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 ---------------------------------------------------
//
@@ -46,7 +57,7 @@ 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, next.catch(() => {}));
ctx.locks.set(runId, /** @type {Promise<void>} */ (next.catch(() => {})));
return next;
};
@@ -82,13 +93,16 @@ if (fs.existsSync(path.join(ROOT, 'runs'))) {
// --- 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) => {
@@ -104,14 +118,18 @@ const readBody = (req) => new Promise((resolve, reject) => {
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]);
@@ -127,6 +145,7 @@ const match = (method, pathname) => {
// 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',
@@ -136,6 +155,7 @@ const MIME = {
'.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';
@@ -217,28 +237,48 @@ route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
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 && users.exists(owner) ? owner : null);
// ownership: every GM action -- every mutation, every model call -- is
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
// one uniform state: readable by all, 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) ?? {};
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 ${users.userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`);
}
return meta;
}
// --- routes -------------------------------------------------------------------
@@ -280,7 +320,7 @@ route('POST', '/api/packages', async ({ body, user }) => {
// 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 = (f) => (fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), 'utf8').trim() : null);
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'),
@@ -314,6 +354,7 @@ route('POST', '/api/runs', async ({ body, user }) => {
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);
@@ -323,7 +364,7 @@ route('POST', '/api/runs', async ({ body, user }) => {
// 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 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)] };
@@ -386,6 +427,10 @@ route('GET', '/api/runs/:id', async ({ params }) => {
// 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);
@@ -411,6 +456,7 @@ function fileSurface(runId) {
route('GET', '/api/runs/:id/files', async ({ params }) => {
bundle.requireRun(params.id);
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)
@@ -478,9 +524,9 @@ route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
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) ?? {};
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const models = meta.models ?? {};
for (const role of ['player', 'housekeeper']) {
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();
@@ -534,7 +580,8 @@ route('DELETE', '/api/runs/:id', async ({ params, user }) => {
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `session ${ctx.sessions.get(id).n} is already live -- one active session per run`);
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);
@@ -569,6 +616,7 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => {
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')) {
@@ -583,13 +631,14 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => {
const eff = effectiveContents(lines);
const entries = lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) };
/** @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 = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder);
const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null);
return {
run: params.id,
session: latest,
@@ -611,7 +660,8 @@ route('GET', '/api/runs/:id/table', async ({ params }) => {
const eff = effectiveContents(s.lines);
const entries = s.lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) };
/** @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 };
}
@@ -647,8 +697,9 @@ 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 = (lines) => {
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];
@@ -664,7 +715,9 @@ route('GET', '/api/runs/:id/story', async ({ params }) => {
}
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')) {
@@ -695,14 +748,14 @@ 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, () => gmTurn(ctx, params.id, line, user))) };
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, () => answerAsk(ctx, params.id, answer, user))) };
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
@@ -710,7 +763,9 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
// the copy is never taken mid-turn.
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
bundle.requireRun(params.id);
return ctx.enqueue(params.id, () => forkRun(ctx, params.id, user));
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 }) => {
@@ -821,7 +876,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user })
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, () => {
return ctx.enqueue(id, async () => {
try {
housekeeping.applyToDormant(id, manifestPath, latest - 1);
return { ok: true, housekept: latest - 1, target: latest };
@@ -835,6 +890,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user })
// --- dispatch -------------------------------------------------------------------
// bearer-token identity (users.mjs); null when absent or unknown
/** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */
function authenticate(req) {
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
return m ? users.getUserByToken(m[1].trim()) : null;
@@ -842,9 +898,10 @@ function authenticate(req) {
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');
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)
@@ -858,7 +915,7 @@ const server = http.createServer(async (req, res) => {
serveStatic(url.pathname, res);
return;
}
const m = match(req.method, url.pathname);
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);
@@ -872,6 +929,6 @@ const server = http.createServer(async (req, res) => {
});
const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
server.listen(Number(port), host, () => {
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`);
});