Files
tiny-worlds/server/main.mjs
T
mute ba72d2ed1f substrate: server, housekeeping job, spa - the mvp complete
- prompt split, GM's cut: system.md = opening + guards (glossary, purpose, input validation; repo-fed, per-project); invariants.md = substrate (syntax markers, tools, memory, records, the paper + its three-part gate; repo-fed, travels with the code); handbook.md = craft copy (shape of play, thoughts, purview, time skips, continuity, stance, hard limits; copied per run). One system message: system -> invariants -> the run's handbook. OOC is a single open paren, closing optional, match the GM's style; a lone paren is an empty OOC line, skipped by the parser. housekeeper.md aligned: the paper holds acute states, relational shifts are recorded as the facts behind them, and dates are story dates (follow the rings' calendar, never the wall clock - the seed is 2069 now, per canon)
- server/ (phase 2, zero-dep node:http): REST spine per the sketch, per-run session machine with ask_gm pause/resume (the whole tool-call batch waits, pairing stays sound), view renderer (thinking-strip, tool-result elision with ask answers exempt, old status/conflict blocks stripped), boot-rebuild from the typed jsonl, lazy seed + turn-0 ingestion at window-open with the unhousekept refuse-and-override guard, usage tracking + context meter, tool-pairing validation, scripted mock model. The clerk gained --json (packages/runs/status); tool/bridge.mjs deleted at mock-parity per the retirement decision
- housekeeping job (phase 3, server/housekeeping.mjs): trigger ends the window and runs the chain async - transcript with labeled thinking, run-state injection (records availability; the ring views stay pure memory), housekeeper on a fresh context, manifest saved (raw output too if unparseable), clerk apply (writes the window log, snapshots dumps/<window>.sql), state.json lastHousekeptSession, autorestart. Rejection holds the restart and surfaces why; the apply endpoint is the recovery path and the manual-relay close. Live-proven twice: both manifests sound (ring-B classification, first-person voice, precise touches, story-dated)
- spa (phase 4, web/ - no build, vanilla es modules, served at /): three-register transcript per the ruled markers incl. multi-line narration blocks, bundle as a collapsed card with turn-0 as the opening GM turn, paper tags as chips, status pane with conflict surfacing, context meter hot past 85 percent, gm line input, ask modal re-presented from pendingAsk, housekeeping button with two-click arm + poll + inline log. No js alert/confirm (they block the embedded pane) - in-page banner instead. Driven end to end through the ui on a disposable live run
- seed: date fixed to the 2069 story calendar (was a real-world date; real dates never surface to the player)
- docs: README goal states the mvp is complete, layout covers server/ and web/, protocol and substrate sections rewritten for the server; ROADMAP phases 0-4 done, harness decisions current; QUESTIONS #4 #7 #10 #12 #16-mechanism #19a #20 #21 resolved; HANDOFF is the handoff map; AGENTS carries the working lessons (tokens are free, no screenshots - not multimodal, no js dialogs, external state survives rewinds)
2026-11-14 03:15:53 +00:00

258 lines
10 KiB
JavaScript

// 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.
//
// 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, 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()) {
send(res, 404, { error: `no such file: ${rel}` });
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 }));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
route('GET', '/api/packages', async () => clerkRawJson('packages'));
route('GET', '/api/runs', async () => clerkRawJson('runs'));
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)');
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 (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
return { run: bundle.runMeta(name), dir: `runs/${name}` };
});
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 },
open: !!s,
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,
};
});
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)) };
});
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 };
});
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 };
});
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) => {
try {
const url = new URL(req.url, 'http://localhost');
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`);
});