Files
tiny-worlds/server/main.mjs
T

258 lines
10 KiB
JavaScript
Raw Normal View History

// 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`);
});