8ef96c7ac5
The mind r/w round (2026-11-20, on the box run's live evidence: her fifth turn slipped the channel, the emission came out <model>, the guard's heal doubled a story passage): the via echo renders as the per-turn <mind> block (the block on a turn shows the params its prose was inferred with -- calibration pairs exactly), the <model> guard and its mock cue are deleted, STRIP_HERS and the story verbs drop the tag, reasoning_effort stays hidden from her, and the one-shot rule stands (r/w is the tag, not persistence). The box run's log was migrated in the same stroke, no-legacy: the refused emission became the valid mind write it tried to be, the conflict and heal left, the bundle system message regenerated under the new invariants. En-route: check-reminder's logged-turns floor relaxes to >= 1. The native-markup round's first act rides adjacent (2026-11-21): the box log's markup debris cleaned and verified through the real machinery (scan, view, story projection), and the agenda grammar is BULLETS -- blockList is kind-dependent now (status keeps its wire commas, agenda splits lines only), the pane and chip parsers match, and a comma-carrying mock item proves the grammar in the smoke. The two paused guards from that round never get built -- the blocks problem dissolves downstream into real tool calls.
Then the temperature research (2026-11-22/23; TEMP-RESEARCH.md, new at root, is the full record -- scope, the reusable fork-and-edit recipe and its gotchas, the failure taxonomy, hedges, open questions). Two blind sweeps of the box run first: prose VOICE tracks temperature blind (the composed-to-impulsive gradient survives with the number hidden), prose CONTENT was demand effect (round 1's traces read the visible <mind> block and styled to it -- a stage direction, not calibration), so the live push is RETIRED: the loop never renders the current call's settings into her view again, the per-turn via echoes are the whole read side. Thinking is temperature-robust through 1.2 and dies above it in four distinct shapes (shape-mixing 422, unbounded prose soup, reasoning-channel salad, instant salad). The n=20 organic ladder (320 forks, the box run's own moment) put the cliff at 1.2 proper: of twenty turns, 8 empty-prose, 5 soups, 2 refusals -- so the clamp drops to 1.15 ("we declare 1.2 too hot to be useful", GM, 2026-11-23; KNOB_BOUNDS moved, the smoke's conflict-range text with it). Side finding at scale: the restatement attractor -- blind, 50-85% of turns re-state their own <mind>, the value pinned near her recent emissions regardless of what rode.
Round 4 (2026-11-24) audits that corpus for content and changes no code: soft inference errors are temperature-FLAT (the ~30% breakfast error is structural, every rung), CONFABULATION IS A THRESHOLD AT 1.0 (fabrication-heavy reasoning 1.4% below the line vs 26.7% at or above; attribute drift below, invented events above; 1.15 bimodal at 8/20 -- the clamp is outcome-safe, not content-safe), and every mechanical axis is flat under the band: reasoning length, prose length, wall time, register proxies. Under the threshold, temperature is a pure voice knob.
On that evidence the two-subturn turn is DESIGNED (ROADMAP, designed-not-built): (a) full view + max effort + constant mid-band temp, the recall seat; (b) draft + tool oks + low effort + variable temp, the voice seat, the draft's register as the dial's zero point; the state blocks become real tool calls, retiring the strip lists, the strict lint, the block grammar, and the prose-to-blocks seam whole. The 2026-11-28 amendments complete it: the native tool loop carries her thread content-borne across rounds (the "thinking never returns" doctrine was transport fact -- the provider drops the field; the reader-facing rule stands), a purpose param on every tool call, the append-only prefix with the reminder as the one per-call exception (four flavors: orient, continue, draft-now, and (b)'s render contract), the recall tool (player search over its whole run; read-only, therefore rewind-safe by construction -- the records tools retire and their journaled-mutator compensation debt dies unfunded), and inline [...] annotations as the author-to-machine layer, the rationale block retained as the optional whole-turn scope. Three new ROADMAP sections ride: the status scan (the wake-up questions; location, inventory, and weather channels; meters pending), the package-declared ledger (the box order tool and the boutique shop as one mechanism; the measured 45% arithmetic re-derivation tax it kills), and the scene box with its paperdoll agent (TTI register, renderer-neutral, the model never draws a pixel). The helpfulness sweep (75 turns of the run's own reasoning: 62 CLEAN, 13 TRACE, 0 AFFECTED; onset at the punishment-arc OOC turns) and the live reading failures (the legs pronoun, the gag-speech riddle, the shed mind write) are recorded as the evidence base for the reading-rules piece.
The GM's prompt-side edits ride the same commit: invariants' r/w mind section and the agenda's no-trimming/no-metaphor lines (landed against observed behavior in the box run's thinking blocks), the clamp example already reading 1.15, system.md's injection-exception rename, README's protocol passages, DICTIONARY's updates, and the box package's backdrop and carryover content pass. The calibration materials (calibration.md, packager-calibration.md -- the A/B outputs, the flake record, the wrong-woman verdict) are committed as research records at the GM's staging. detention stays untracked WIP.
Verified across the sittings: typecheck green on both programs, smoke ALL PASS (the mind-r/w battery with the mock's script renumber, the clamp's conflict-range text, the comma-carrying agenda item), restart + reminder checks green, check-repo clean, and the debug server restarted on the real state. The substrate deltas in this commit are the mind r/w, the push retirement, and the clamp; everything else is the record.
1657 lines
79 KiB
JavaScript
1657 lines
79 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): one fixed superuser ("debug") that bypasses
|
|
// the user database entirely -- no invite dance. The bearer token
|
|
// that signs it in is minted into state/debug-token.txt and printed
|
|
// at every boot. Loopback-bound by code, debug or not. 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 * as providers from './providers.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, specFromMeta, gateSpec } from './loop.mjs';
|
|
import * as users from './users.mjs';
|
|
import { forkRun } from './fork.mjs';
|
|
import * as discovery from './discovery.mjs';
|
|
import * as packager from './packager.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
|
|
|
|
// There is no server.json (developer, 2026-11-19: it held no
|
|
// meaningful configuration once the bind died) -- the bind is code
|
|
// (loopback always) and the port rides the RP_PORT env var. The
|
|
// provider entities live in state/config.json (server-written,
|
|
// SPA-managed). Nothing gates the boot: a fresh deployment with no
|
|
// config at all comes up serving, mints the superuser invite, and
|
|
// shows the global no-providers banner -- every consumer of
|
|
// providers treats "none" as a loud 409, never a crash.
|
|
let providerCfg = providers.readConfig();
|
|
// the self-heal rule (developer, 2026-11-18), stated broadly: an error that
|
|
// can be mechanically fixed to a reasonable degree without requiring
|
|
// human input gets fixed. The empty provider list is one: the
|
|
// anonymous fallback is added and discovered, as a background job --
|
|
// boot never blocks on the network, and a failure leaves the empty
|
|
// state plus the admin block's banner, whose fix path is the same
|
|
// add act. The mock world seeds its two synthetic providers instead
|
|
// (offline, the same code path).
|
|
/** @type {string[]} */
|
|
const autoAdded = [];
|
|
if (!providerCfg.providers.length) {
|
|
if (MOCK) {
|
|
providerCfg.providers.push(
|
|
{ slug: 'mock-a', baseUrl: 'mock://a', default: null },
|
|
{ slug: 'mock-b', baseUrl: 'mock://b', default: null },
|
|
);
|
|
autoAdded.push('mock-a', 'mock-b');
|
|
} else {
|
|
const p = providers.addBuiltin(providerCfg);
|
|
if (p) autoAdded.push(p.slug);
|
|
}
|
|
providers.writeConfig(providerCfg);
|
|
}
|
|
const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)]));
|
|
// locks/enqueue are attached just below; the cast is the two-step that
|
|
// lets the literal precede them
|
|
const ctxBase = { mock: MOCK, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
|
/** @type {Ctx} */
|
|
const ctx = /** @type {Ctx} */ (ctxBase);
|
|
|
|
// the auto-added providers discover in the background -- no inferencer
|
|
// calls, one GET each, zero cost; a dead network shows as the probe
|
|
// record on the card (o/f's auth failure reads as upstream breakage,
|
|
// never a prompt) plus the banner, whose fix path is the same add act
|
|
for (const slug of autoAdded) {
|
|
console.log(`fresh deployment -- auto-added '${slug}', discovering`);
|
|
void runProbe(slug)
|
|
.then((s) => console.log(`auto-discovery of '${slug}': ${s.models.length} models scraped`))
|
|
.catch((e) => console.error(`auto-discovery of '${slug}' failed: ${String(e.message ?? e).split('\n')[0]} -- the admin block's add act retries it`));
|
|
}
|
|
|
|
// --- 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 (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: one fixed superuser behind the printed token -- no invites, no users db; 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 @param {number} [limit] @returns {Promise<any>} */
|
|
const readBody = (req, limit = 1024 * 1024) => new Promise((resolve, reject) => {
|
|
/** @type {Buffer[]} */
|
|
const chunks = [];
|
|
let size = 0;
|
|
req.on('data', (c) => {
|
|
size += c.length;
|
|
if (size > limit) { 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,
|
|
debug: DEBUG, // the claim screen's hint: no invite exists here
|
|
}), { 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 })),
|
|
}));
|
|
|
|
// --- models and providers: the registry, the op's provider acts ----------------
|
|
//
|
|
// The registry (state/models.json, per-provider sections) is the
|
|
// truth of selectable models. The provider entities (state/
|
|
// config.json) are the op's: add and remove from the SPA, discover
|
|
// and refine per provider. Both surfaces below are the superuser's
|
|
// except GET /api/models (the model box reads it, any signed-in
|
|
// user).
|
|
|
|
/** The per-provider payload the model box and the admin block read. */
|
|
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
|
/** @returns {{ providers: { slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('./shapes.mjs').RegistryModel[], job: ?JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }[] }} */
|
|
function modelsPayload() {
|
|
const reg = discovery.registry();
|
|
return {
|
|
providers: ctx.providerCfg.providers.map((p) => {
|
|
const section = reg?.providers[p.slug] ?? null;
|
|
return {
|
|
slug: p.slug,
|
|
phase: section?.phase ?? 'none',
|
|
discovered: section?.discovered ?? null,
|
|
refined: section?.refined ?? null,
|
|
curator: section?.curator ?? null,
|
|
recommendation: section?.recommendation ?? null,
|
|
default: p.default ?? null,
|
|
models: section?.models ?? [],
|
|
job: discovery.jobState(ctx, p.slug),
|
|
probe: p.probe ?? null,
|
|
hasKey: !!p.apiKey,
|
|
};
|
|
}),
|
|
};
|
|
}
|
|
|
|
route('GET', '/api/models', async () => modelsPayload());
|
|
|
|
/** The providers' default specs: the create flow's pre-select, and
|
|
* what a pick-less housekeeper inherits. */
|
|
/** @returns {{ slug: string, default: ?{ model: string, effort: string } }[]} */
|
|
function providerDefaults() {
|
|
return ctx.providerCfg.providers.map((p) => ({ slug: p.slug, default: p.default ?? null }));
|
|
}
|
|
|
|
/** The run's per-role spec health, read-only: the invalidation
|
|
* surface the table renders as a note before any send refuses. An
|
|
* unset housekeeper is not an error -- it inherits the player
|
|
* spec's provider default (the same resolution the pass runs). */
|
|
/** @param {string} runId @returns {{ player: RoleHealth, housekeeper: RoleHealth }} */
|
|
function roleHealth(runId) {
|
|
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
|
|
/** @param {'player'|'housekeeper'} role @returns {RoleHealth} */
|
|
const health = (role) => {
|
|
const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
|
try {
|
|
const spec = specFromMeta(meta.models?.[role] ?? null, role);
|
|
if (spec) {
|
|
gateSpec(ctx, spec, role);
|
|
return { spec, ok: true, note: null, inherited: false };
|
|
}
|
|
if (role === 'player') {
|
|
return { spec: null, ok: false, note: 'no player model set for this run -- pick one in the model box', inherited: false };
|
|
}
|
|
// the housekeeper inherits: the player spec's provider's default
|
|
const player = specFromMeta(meta.models?.player ?? null, 'player');
|
|
const def = player ? ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null : null;
|
|
if (def) {
|
|
const inherited = { provider: /** @type {{ provider: string }} */ (player).provider, model: def.model, effort: def.effort };
|
|
gateSpec(ctx, inherited, 'housekeeper');
|
|
return { spec: inherited, ok: true, note: null, inherited: true };
|
|
}
|
|
return { spec: null, ok: false, note: 'no housekeeper pick, and no provider default to inherit', inherited: false };
|
|
} catch (e) {
|
|
return { spec: null, ok: false, note: String(/** @type {Error} */ (e).message ?? e), inherited: false };
|
|
}
|
|
};
|
|
return { player: health('player'), housekeeper: health('housekeeper') };
|
|
}
|
|
|
|
// the op's config detail: slugs, bases, key presence (the key itself
|
|
// never leaves the server), defaults -- what the admin block edits
|
|
route('GET', '/api/providers', async ({ user }) => {
|
|
requireSuperuser(user);
|
|
return {
|
|
providers: ctx.providerCfg.providers.map((p) => ({
|
|
slug: p.slug,
|
|
baseUrl: p.baseUrl,
|
|
hasKey: !!p.apiKey,
|
|
default: p.default ?? null,
|
|
})),
|
|
};
|
|
});
|
|
|
|
// the probe (developer, 2026-11-19): discovery IS the health check -- every
|
|
// path that scrapes a provider records the outcome on the entity, so
|
|
// the card reads the last probe, never a stored machine. 401/403 is
|
|
// the ask (custom providers only -- an auth failure on o/f is
|
|
// upstream breakage, shown as the error it is); everything else is
|
|
// the error named. No runtime path probes: usage errors are transient
|
|
// and the op's to fix eventually (a failed turn already landed its
|
|
// req event, and the invalidation surface only answers removal).
|
|
/** @param {string} slug @param {{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }} probe */
|
|
function setProbe(slug, probe) {
|
|
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
|
const p = cfgMut.providers.find((x) => x.slug === slug);
|
|
if (!p) return; // removed mid-probe -- the record goes with the entity
|
|
p.probe = probe;
|
|
providers.applyConfig(ctx, cfgMut);
|
|
}
|
|
/** @param {string} slug @returns {Promise<import('./discovery.mjs').RegistrySection>} */
|
|
async function runProbe(slug) {
|
|
try {
|
|
const section = await discovery.discover(ctx, slug);
|
|
setProbe(slug, { outcome: 'ok', detail: `${section.models.length} models scraped`, at: new Date().toISOString() });
|
|
return section;
|
|
} catch (e) {
|
|
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
|
setProbe(slug, {
|
|
outcome: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
|
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
|
at: new Date().toISOString(),
|
|
});
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
// add a provider (developer, 2026-11-19): {builtin: true} or {slug,
|
|
// baseUrl} -- never a key (the auth route is the only key path).
|
|
// Discovery is the probe: an auth refusal (401/403) leaves the
|
|
// provider standing broken -- the SPA asks for the key, checked on
|
|
// reception; every other failure refuses the add outright, because an
|
|
// endpoint that cannot answer is not a provider -- nothing stands.
|
|
route('POST', '/api/providers', async ({ body, user }) => {
|
|
requireSuperuser(user);
|
|
if (body.apiKey !== undefined && body.apiKey !== null) {
|
|
throw new HttpError(400, 'apiKey does not ride the add -- send the endpoint alone; a 401/403 opens the key path');
|
|
}
|
|
const cfgMut = { providers: [...ctx.providerCfg.providers] };
|
|
/** @type {import('./shapes.mjs').ProviderCfg} */ let p;
|
|
if (body.builtin === true) {
|
|
const added = providers.addBuiltin(cfgMut);
|
|
if (!added) throw new HttpError(409, 'opencode/free is already on the provider list');
|
|
p = added; // addBuiltin pushed it
|
|
} else {
|
|
const slug = String(body.slug ?? '').trim();
|
|
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '');
|
|
if (!providers.validSlug(slug)) throw new HttpError(400, 'slug must be lowercase letters, digits, dashes (one slash allowed), e.g. my-shop');
|
|
if (providers.findProvider(cfgMut, slug)) throw new HttpError(409, `a provider named '${slug}' already exists`);
|
|
if (!providers.validBaseUrl(baseUrl)) throw new HttpError(400, 'baseUrl must be a valid http(s) URL');
|
|
p = { slug, baseUrl, default: null };
|
|
cfgMut.providers.push(p);
|
|
}
|
|
providers.applyConfig(ctx, cfgMut);
|
|
let section;
|
|
try {
|
|
section = await runProbe(p.slug);
|
|
} catch (e) {
|
|
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
|
if (err.status === 401 || err.status === 403) {
|
|
// the add stands (the op keys it or removes it); the failure
|
|
// carries its status for the SPA's password branch
|
|
throw new HttpError(err.status, `provider '${p.slug}' added, but the listing was refused: ${err.message} -- send the API key`);
|
|
}
|
|
// every other failure refuses the add: roll back, nothing stands
|
|
providers.applyConfig(ctx, { providers: ctx.providerCfg.providers.filter((x) => x.slug !== p.slug) });
|
|
throw err;
|
|
}
|
|
return { ok: true, provider: p.slug, models: section.models.length };
|
|
});
|
|
|
|
// set or replace a custom provider's key (the o/f singleton never
|
|
// takes one -- its purpose is to be the anonymous fallback; a 401
|
|
// from it is upstream breakage, not a prompt). Probe-then-save (developer,
|
|
// 2026-11-19): the candidate key is checked on reception -- a key
|
|
// that still meets the refusal is never saved, the previous state
|
|
// returns, and the ask stays open for the next attempt.
|
|
route('POST', '/api/providers/:slug/auth', async ({ params, body, user }) => {
|
|
requireSuperuser(user);
|
|
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
|
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
|
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
|
if (typeof body.apiKey !== 'string' || !body.apiKey.trim()) throw new HttpError(400, 'apiKey (a non-empty string) is required');
|
|
const prev = ctx.providerCfg;
|
|
const prevEntity = /** @type {import('./shapes.mjs').ProviderCfg} */ (prev.providers.find((x) => x.slug === p.slug));
|
|
const cfgMut = { providers: prev.providers.map((x) => ({ ...x })) };
|
|
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
|
target.apiKey = body.apiKey.trim();
|
|
providers.applyConfig(ctx, cfgMut);
|
|
try {
|
|
const section = await runProbe(p.slug);
|
|
return { ok: true, provider: p.slug, models: section.models.length };
|
|
} catch (e) {
|
|
// the failed candidate never saves: the previous state returns,
|
|
// and this attempt's probe record rides back with it (the card
|
|
// shows the last attempt, whatever it was)
|
|
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
|
const candidate = ctx.providerCfg.providers.find((x) => x.slug === p.slug);
|
|
if (candidate?.probe) prevEntity.probe = candidate.probe;
|
|
providers.applyConfig(ctx, prev);
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
// remove a custom provider's key (developer, 2026-11-19): the op's control
|
|
// for a provider that went public -- or the first half of a key
|
|
// replacement, the second half being the ask, which re-opens when
|
|
// the keyless probe meets the 401 again. The removal stands whatever
|
|
// the probe says: it is the op's deliberate act, not an add; the
|
|
// probe outcome rides the response and the card.
|
|
route('DELETE', '/api/providers/:slug/auth', async ({ params, user }) => {
|
|
requireSuperuser(user);
|
|
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
|
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
|
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
|
if (!p.apiKey) throw new HttpError(404, `provider '${p.slug}' has no key to remove`);
|
|
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
|
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
|
delete target.apiKey;
|
|
providers.applyConfig(ctx, cfgMut);
|
|
try {
|
|
const section = await runProbe(p.slug);
|
|
return { ok: true, provider: p.slug, models: section.models.length };
|
|
} catch (e) {
|
|
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
|
return {
|
|
ok: true,
|
|
provider: p.slug,
|
|
probe: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
|
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
|
};
|
|
}
|
|
});
|
|
|
|
// remove a provider: the section and the adjudication cache entries
|
|
// go with it; the runs that rode it invalidate at their next send
|
|
// (the GM's table carries the note)
|
|
route('DELETE', '/api/providers/:slug', async ({ params, user }) => {
|
|
requireSuperuser(user);
|
|
const slug = params.slug;
|
|
const guard = providers.removalGuard(ctx.providerCfg, slug);
|
|
if (guard) throw new HttpError(409, guard);
|
|
const cfgMut = { providers: ctx.providerCfg.providers.filter((p) => p.slug !== slug) };
|
|
if (cfgMut.providers.length === ctx.providerCfg.providers.length) {
|
|
throw new HttpError(404, `no such provider: ${slug}`);
|
|
}
|
|
providers.applyConfig(ctx, cfgMut);
|
|
discovery.deleteSection(slug);
|
|
discovery.purgeCache(slug);
|
|
return { ok: true };
|
|
});
|
|
|
|
// re-run one provider's discovery: the scrape, the section reset to
|
|
// preliminary (a refined section loses its battery -- the button
|
|
// says so in the UI), and the probe record updated -- this manual
|
|
// act is one of the only things that moves it
|
|
route('POST', '/api/providers/:slug/discover', async ({ params, user }) => {
|
|
requireSuperuser(user);
|
|
const section = await runProbe(params.slug);
|
|
return { ok: true, provider: params.slug, phase: section.phase, models: section.models.length };
|
|
});
|
|
|
|
// the selection: the provider's default {model, effort} -- also the
|
|
// refine curator. Validated against the provider's own registry.
|
|
route('POST', '/api/providers/:slug/default', async ({ params, body, user }) => {
|
|
requireSuperuser(user);
|
|
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
|
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
|
const model = String(body.model ?? '').trim();
|
|
const effort = String(body.effort ?? '').trim();
|
|
if (!model) throw new HttpError(400, 'model (an id from this provider\'s registry) is required');
|
|
if (!discovery.EFFORT_LEVELS.includes(effort)) {
|
|
throw new HttpError(400, `effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
|
}
|
|
const m = discovery.findModel(p.slug, model);
|
|
if (!m) throw new HttpError(400, `model '${model}' is not in '${p.slug}'s registry -- run its discovery first`);
|
|
if (m.inference === false) throw new HttpError(400, `model '${model}' failed the inference battery -- it is not selectable`);
|
|
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
|
/** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug)).default = { model, effort };
|
|
providers.applyConfig(ctx, cfgMut);
|
|
return { ok: true, provider: p.slug, default: { model, effort } };
|
|
});
|
|
|
|
// refine one provider: the battery + the curator pass (the op's
|
|
// selected default is the curator). Real traffic, real cost; the job
|
|
// meters itself.
|
|
route('POST', '/api/providers/:slug/refine', async ({ params, user }) => {
|
|
requireSuperuser(user);
|
|
return discovery.refine(ctx, params.slug, user);
|
|
});
|
|
|
|
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) };
|
|
});
|
|
|
|
// fork a package: the copy-to-author act (developer, 2026-11-19).
|
|
// Any package, system or user, forkable by anyone -- the copy lands
|
|
// in state/packages owned by the forker, scaffold flag preserved.
|
|
route('POST', '/api/packages/fork', async ({ body, user }) => {
|
|
const from = String(body.from ?? '').trim();
|
|
const name = String(body.name ?? '').trim();
|
|
if (!from) throw new HttpError(400, 'from (a package name) is required');
|
|
if (!name) throw new HttpError(400, 'name (the new package\'s display name) is required');
|
|
requireUser(user);
|
|
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'fork-package', from, name);
|
|
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'fork failed');
|
|
return { package: JSON.parse(r.out) };
|
|
});
|
|
|
|
// --- the packager ----------------------------------------------------------------
|
|
//
|
|
// Literature into scaffold packages (developer, 2026-11-19). Any
|
|
// signed-in user -- packages are user-authored already; one job at a
|
|
// time (the singleton slot -- this is tens of minutes of deployment
|
|
// inference). The request carries the mode, the settings (name, pc,
|
|
// records -- user input, never a model output), the source as one
|
|
// text/plain in a JSON string field, the cut in the caller's own
|
|
// words (full mode), and an optional full spec defaulting to the
|
|
// provider default. The landing is a scaffold: review in the
|
|
// package editor, flip ready.
|
|
|
|
/** @param {unknown} raw @returns {{ slug: string, model: string, effort: string }} */
|
|
function resolvePackSpec(raw) {
|
|
if (raw === undefined || raw === null) {
|
|
const d = ctx.providerCfg.providers.find((p) => p.default);
|
|
if (!d || !d.default) throw new HttpError(409, 'no provider default is set -- the op selects one, or send a spec');
|
|
return { slug: d.slug, model: d.default.model, effort: d.default.effort };
|
|
}
|
|
if (typeof raw !== 'object' || Array.isArray(raw)) throw new HttpError(400, 'spec must be { provider, model, effort }');
|
|
const o = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw);
|
|
if (typeof o.provider !== 'string' || typeof o.model !== 'string' || typeof o.effort !== 'string') {
|
|
throw new HttpError(400, 'spec must be { provider, model, effort } -- see GET /api/models');
|
|
}
|
|
if (!discovery.EFFORT_LEVELS.includes(o.effort)) {
|
|
throw new HttpError(400, `spec.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
|
}
|
|
if (!discovery.usable(o.provider, o.model)) {
|
|
throw new HttpError(400, `spec model '${o.model}' is not usable on '${o.provider}' (not discovered, or failed the battery)`);
|
|
}
|
|
return { slug: o.provider, model: o.model, effort: o.effort };
|
|
}
|
|
|
|
route('POST', '/api/packager', async ({ body, user }) => {
|
|
requireUser(user);
|
|
const mode = body.mode;
|
|
if (mode !== 'character' && mode !== 'full') throw new HttpError(400, "mode must be 'character' or 'full'");
|
|
const name = String(body.name ?? '').trim();
|
|
const pc = String(body.pc ?? '').trim();
|
|
if (!name) throw new HttpError(400, 'name (the new package\'s display name) is required');
|
|
if (!pc) throw new HttpError(400, 'pc (her default name) is required');
|
|
// the character to lift, in the caller's own words -- required in
|
|
// character mode (no named woman, no voice to distill); optional
|
|
// in full mode, where the seat rules stand when she is unnamed
|
|
const who = String(body.who ?? '').trim();
|
|
if (mode === 'character' && !who) throw new HttpError(400, 'who (the character to lift, in your own words) is required for a character packaging');
|
|
const records = body.records === true;
|
|
if (typeof body.source !== 'string' || !body.source.trim()) throw new HttpError(400, 'source (one text/plain file) is required');
|
|
if (body.source.length > packager.SOURCE_MAX) throw new HttpError(413, `the source is too large (over ${Math.round(packager.SOURCE_MAX / 1024 / 1024)}MB)`);
|
|
const cut = String(body.cut ?? '').trim();
|
|
if (mode === 'full' && !cut) throw new HttpError(400, 'cut (where her import stops, in your own words) is required for a full packaging');
|
|
const spec = resolvePackSpec(body.spec);
|
|
return packager.start(ctx, { mode, name, pc, who, records, source: body.source, cut }, spec, user);
|
|
});
|
|
|
|
route('GET', '/api/packager', async () => packager.state());
|
|
|
|
// --- the package editor ---------------------------------------------------------
|
|
//
|
|
// The owner's authoring surface over a user package: the same fixed
|
|
// whitelist shape as the run files API, every file rw (a package is
|
|
// pre-run -- all of it is authoring material, settings included).
|
|
// System packages are repo-side and refuse; ownerless user packages
|
|
// are the departed's and refuse (the run precedent: an ownerless
|
|
// thing is readable and forkable, never editable). Save-time gates
|
|
// are the cheap cousins of the start gate's: memory.json and
|
|
// settings.json must parse as JSON objects, the carryover must pass
|
|
// the authored lint -- the deep checks still run at run creation.
|
|
|
|
/** One file of the package editor surface. */
|
|
/** @typedef {{ mode: 'rw', path: string }} PkgFileSpec */
|
|
|
|
/** @param {string} name @returns {?string} */
|
|
function packageDirOf(name) {
|
|
if (!/^[a-z0-9-]+$/.test(name)) return null;
|
|
const sys = path.join(ROOT, 'packages', name);
|
|
if (fs.existsSync(sys)) return sys;
|
|
const usr = path.join(ROOT, 'state', 'packages', name);
|
|
if (fs.existsSync(usr)) return usr;
|
|
return null;
|
|
}
|
|
|
|
/** The editor's gate: resolves the package dir for its owner, or
|
|
* refuses -- system (repo-side) and ownerless packages are not
|
|
* editable by anyone.
|
|
* @param {?UserRow} user @param {string} name @returns {string} */
|
|
function requirePackageOwner(user, name) {
|
|
const dir = packageDirOf(name);
|
|
if (!dir) throw new HttpError(404, `no such package: ${name}`);
|
|
if (!fs.existsSync(path.join(dir, 'package.json'))) {
|
|
throw new HttpError(403, 'system packages are repo-side and read-only -- fork to edit');
|
|
}
|
|
try {
|
|
const meta = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
if (meta.owner && user && meta.owner === user.id) return dir;
|
|
} catch { /* unreadable meta -- not editable */ }
|
|
throw new HttpError(403, 'this package is not yours to edit');
|
|
}
|
|
|
|
/** @param {string} dir @returns {Record<string, PkgFileSpec>} */
|
|
function packageFileSurface(dir) {
|
|
/** @type {Record<string, PkgFileSpec>} */
|
|
const spec = {};
|
|
for (const f of ['handbook.md', 'backdrop.md', 'character.md', 'memory.json', 'carryover.jsonl', 'settings.json', 'gm.md']) {
|
|
spec[f] = { mode: 'rw', path: path.join(dir, f) };
|
|
}
|
|
return spec;
|
|
}
|
|
|
|
route('GET', '/api/packages/:name/files', async ({ params, user }) => {
|
|
const dir = requirePackageOwner(user, params.name);
|
|
const spec = packageFileSurface(dir);
|
|
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */
|
|
const files = {};
|
|
for (const [f, s] of Object.entries(spec)) {
|
|
files[f] = fs.existsSync(s.path)
|
|
? { mode: s.mode, exists: true, content: fs.readFileSync(s.path, 'utf8') }
|
|
: { mode: s.mode, exists: false };
|
|
}
|
|
const settingsFile = files['settings.json'];
|
|
const settings = settingsFile?.exists ? JSON.parse(/** @type {string} */ (settingsFile.content)) : {};
|
|
return { display: settings.name ?? params.name, scaffold: settings.scaffold === true, files };
|
|
});
|
|
|
|
route('PUT', '/api/packages/:name/files/:path', async ({ params, body, user }) => {
|
|
const dir = requirePackageOwner(user, params.name);
|
|
const spec = packageFileSurface(dir)[params.path];
|
|
if (!spec) throw new HttpError(404, `no such package file in the API surface: ${params.path}`);
|
|
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
|
|
if (params.path === 'memory.json' || params.path === 'settings.json') {
|
|
// the save-time gate is syntax only: JSON objects, the same cheap
|
|
// cousin as the run surface's -- the start gate judges the rest
|
|
try {
|
|
const o = JSON.parse(body.content);
|
|
if (typeof o !== 'object' || o === null || Array.isArray(o)) throw new Error();
|
|
} catch {
|
|
throw new HttpError(400, `${params.path} must be a JSON object`);
|
|
}
|
|
}
|
|
if (params.path === 'carryover.jsonl') {
|
|
// only clean openings land: the authored lint, the run surface's
|
|
// exact save-time gate
|
|
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: true });
|
|
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: params.path, bytes: Buffer.byteLength(body.content) };
|
|
});
|
|
|
|
// 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. body.spec (the player pick, a
|
|
// full {provider, model, effort}) lands in run.json after the copy.
|
|
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);
|
|
// the spec validates before anything lands: a refused create leaves
|
|
// no orphan run dir behind (the failures-never-cache smoke found
|
|
// the old order -- create first, validate after)
|
|
if (body.spec !== undefined) {
|
|
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body.spec);
|
|
if (typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
|
throw new HttpError(400, 'spec must be { provider, model, effort } -- see GET /api/models');
|
|
}
|
|
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
|
throw new HttpError(400, `spec.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
|
}
|
|
if (!discovery.usable(spec.provider, spec.model)) {
|
|
throw new HttpError(400, `spec model '${spec.model}' is not usable on '${spec.provider}' (not discovered, or failed the battery)`);
|
|
}
|
|
}
|
|
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []));
|
|
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
|
const run = JSON.parse(r.out);
|
|
if (body.spec !== undefined) {
|
|
const spec = /** @type {{ provider: string, model: string, effort: string }} */ (body.spec);
|
|
const meta = bundle.runMeta(run.id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
|
meta.models = { ...(meta.models ?? {}), player: { provider: spec.provider, model: spec.model, effort: spec.effort } };
|
|
fs.writeFileSync(path.join(bundle.runDir(run.id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
|
}
|
|
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 state = derivedState(id); // the log's truth, not the db's
|
|
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);
|
|
const rh = roleHealth(id);
|
|
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 ?? {},
|
|
// the invalidation surface: each resolved spec's health, so the
|
|
// table can carry the note before a send ever 409s
|
|
modelState: rh,
|
|
// the providers' default specs -- the create flow's pre-select,
|
|
// and the fallback a pick-less role would inherit
|
|
providerDefaults: providerDefaults(),
|
|
},
|
|
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: state.status,
|
|
agenda: state.agenda,
|
|
sheet: state.sheet,
|
|
records: st.records,
|
|
fill: st.rings,
|
|
events: st.events,
|
|
pendingAsk: s?.pendingAsk?.question ?? null,
|
|
usage: s?.usage ?? null,
|
|
// the discovered window (developer, 2026-11-19): contwin is
|
|
// model-dependent, never deployment-declared -- the run's player
|
|
// model's input ceiling from the registry, null when the provider
|
|
// states none or no pick stands
|
|
context: (() => {
|
|
if (!s?.usage) return null;
|
|
const spec = rh.player.spec;
|
|
const win = spec ? discovery.findModel(spec.provider, spec.model)?.input ?? null : null;
|
|
return { used: s.usage.promptTokens, contwin: win, pct: win ? Math.round((100 * s.usage.promptTokens) / win) : 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 carryover
|
|
// is the review window's one editing surface (an authored opening
|
|
// and a continuation alike -- GM edits during dormancy show on the
|
|
// story's live edge, and a block edit there is a hand override);
|
|
// memory.json is the draft's starting memories -- authored
|
|
// material while the run is a draft (the start gate applies it),
|
|
// provenance after. 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: rw, path: path.join(dir, 'carryover.jsonl') }, // the review window's one editing surface (blocks included)
|
|
'memory.json': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'memory.json') }, // the draft's starting memories; the start gate applies them
|
|
'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 === 'memory.json') {
|
|
// the save-time gate is syntax only (the carryover lint's cheap
|
|
// cousin): the manifest checks run at the start gate, where a
|
|
// refusal touches nothing
|
|
try {
|
|
const mf = JSON.parse(body.content);
|
|
if (typeof mf !== 'object' || mf === null || Array.isArray(mf)) throw new Error();
|
|
} catch {
|
|
throw new HttpError(400, 'memory.json must be a JSON object');
|
|
}
|
|
}
|
|
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 model picks: full specs, selected from the registry (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 inheritance (the player to
|
|
// nothing, the housekeeper to the player provider's 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 field: ${k} -- player, 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 spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body[role]);
|
|
if (typeof spec !== 'object' || spec === null || Array.isArray(spec)
|
|
|| typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
|
throw new HttpError(400, `${role}: a full spec { provider, model, effort }, or null to clear -- see GET /api/models`);
|
|
}
|
|
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
|
|
throw new HttpError(400, `${role}: no provider named '${spec.provider}' is configured`);
|
|
}
|
|
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
|
throw new HttpError(400, `${role}.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
|
}
|
|
if (!discovery.usable(spec.provider, spec.model)) {
|
|
throw new HttpError(400, `${role}: '${spec.model}' is not usable on '${spec.provider}' (not in its registry, or failed the battery)`);
|
|
}
|
|
models[role] = { provider: spec.provider, model: spec.model, effort: spec.effort };
|
|
}
|
|
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 ?? {}, modelState: roleHealth(id) };
|
|
});
|
|
|
|
// 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|mind|status|agenda|sheet)>[\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;
|
|
// OOC is the paren channel (invariants: opens with a paren,
|
|
// closing optional) and is omitted WHOLE: turn shapes are
|
|
// turn-granular, and load-bearing prose living inside OOC only
|
|
// is a GM protocol violation the story enforces by omission
|
|
if (e.m.role === 'user' && !e.conflictOnly) {
|
|
const text = String(e.m.content ?? '').replace(rides, '').trim();
|
|
if (text && !text.startsWith('(')) 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 && !text.startsWith('(')) 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 };
|
|
});
|
|
|
|
// a block edit rides its turn (the pane editors stage their lists
|
|
// client-side and the send attaches them): only the kinds sent are
|
|
// overridden, whole-list. Descriptions never contain commas -- the
|
|
// transport is comma-separated -- so a comma inside an item is a
|
|
// 400, not a silent split in every later parse.
|
|
/** @param {Record<string, unknown>} body @returns {?{ status?: string[], agenda?: string[] }} */
|
|
function readOverride(body) {
|
|
/** @type {?{ status?: string[], agenda?: string[] }} */ let override = null;
|
|
for (const kind of ['status', 'agenda']) {
|
|
const items = body[kind];
|
|
if (items === undefined || items === null) continue;
|
|
if (!Array.isArray(items)) throw new HttpError(400, `${kind} (an array of descriptions) is required -- an empty array clears it`);
|
|
for (const it of items) {
|
|
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, `every ${kind} item must be a non-empty string`);
|
|
if (it.includes(',')) throw new HttpError(400, `${kind} items never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
|
}
|
|
const clean = items.map((it) => String(it).trim());
|
|
if (override === null) override = {};
|
|
if (kind === 'status') override.status = clean;
|
|
else override.agenda = clean;
|
|
}
|
|
return override;
|
|
}
|
|
|
|
// The sheet record (developer, 2026-11-17): the GM's ledger of arbitrated run
|
|
// state, riding the GM turn like the override. Schemaless by ruling --
|
|
// a plain JSON object, any fields, semantics living in the setting's
|
|
// prose; the route's only law is object-ness (an array or a scalar is
|
|
// a 400, nothing appended). Absent key on the turn means no edit; an
|
|
// empty object is a deliberate empty ledger.
|
|
/** @param {Record<string, unknown>} body @returns {?Record<string, unknown>} */
|
|
function readSheet(body) {
|
|
if (body.sheet === undefined || body.sheet === null) return null;
|
|
if (typeof body.sheet !== 'object' || Array.isArray(body.sheet)) {
|
|
throw new HttpError(400, 'sheet must be a JSON object -- the GM\'s ledger record');
|
|
}
|
|
return /** @type {Record<string, unknown>} */ (body.sheet);
|
|
}
|
|
|
|
// The rewind and the staleness guard (developer, 2026-11-17), both optional
|
|
// fields on the send, both native API with no UX rules riding here:
|
|
// rewind names the GM turn (a log line index) this send replaces --
|
|
// the target and everything after it leave the log; expect states the
|
|
// log line count the send was composed against, and a mismatch (a
|
|
// stale tab; the log only moves through sends) refuses before
|
|
// anything rides. The SPA always sends expect; curl may omit it.
|
|
/** @param {Record<string, unknown>} body @returns {number} */
|
|
function readRewind(body) {
|
|
if (body.rewind === undefined || body.rewind === null) return Number.NaN;
|
|
if (!Number.isInteger(body.rewind)) {
|
|
throw new HttpError(400, 'rewind must be a log line index (an integer) -- the GM turn this send replaces');
|
|
}
|
|
return Number(body.rewind);
|
|
}
|
|
/** @param {Record<string, unknown>} body @returns {?number} */
|
|
function readExpect(body) {
|
|
if (body.expect === undefined || body.expect === null) return null;
|
|
if (!Number.isInteger(body.expect)) {
|
|
throw new HttpError(400, 'expect must be the log line count this send was composed against (an integer)');
|
|
}
|
|
return Number(body.expect);
|
|
}
|
|
|
|
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');
|
|
const override = readOverride(body);
|
|
const sheet = readSheet(body);
|
|
if ((override || sheet) && line.startsWith('(')) {
|
|
throw new HttpError(400, 'a block edit cannot ride an OOC turn -- overrides arrive with a non-OOC GM turn');
|
|
}
|
|
const rewind = readRewind(body);
|
|
const expect = readExpect(body);
|
|
requireOwner(user, params.id);
|
|
const send = { rewind: Number.isNaN(rewind) ? null : rewind, expect };
|
|
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override, sheet, send))) };
|
|
});
|
|
|
|
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');
|
|
const expect = readExpect(body);
|
|
requireOwner(user, params.id);
|
|
return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user, expect))) };
|
|
});
|
|
|
|
// the turn meter's read (developer, 2026-11-17): the live progress record
|
|
// the streaming callback feeds, plus the scale the bar guesstimates
|
|
// against -- the session's own history: her longest past turn in
|
|
// characters (thinking and prose both, the units the meter counts).
|
|
// No history means no scale: the client falls back to the
|
|
// chunk-driven animation. (The old max_tokens budget layer is gone
|
|
// with the per-run params: no surface sets one anymore -- developer,
|
|
// 2026-11-18.) Owner-only machinery; a plain read, never queued.
|
|
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
|
|
requireOwner(user, params.id);
|
|
const s = ctx.sessions.get(params.id);
|
|
if (!s) return { inFlight: false, scale: null };
|
|
let high = 0;
|
|
for (const e of s.lines) {
|
|
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
|
|
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
|
|
if (chars > high) high = chars;
|
|
}
|
|
const scale = high > 0 ? high : null;
|
|
const scaleKind = high > 0 ? 'history' : null;
|
|
if (!s.progress) return { inFlight: false, scale, scaleKind };
|
|
return { inFlight: true, ...s.progress, scale, scaleKind };
|
|
});
|
|
|
|
// 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));
|
|
});
|
|
|
|
// the state read: the log is the one truth (the state scan -- the
|
|
// db holds no copy). The latest session's log is the whole story
|
|
// since its start; during dormancy the carryover is the live edge
|
|
// and rides along. A run with no sessions derives nothing.
|
|
/** @param {string} runId @returns {{ status: string[], agenda: string[], sheet: ?Record<string, unknown> }} */
|
|
function derivedState(runId) {
|
|
const live = ctx.sessions.get(runId);
|
|
const latest = session.latestSession(runId);
|
|
if (latest == null) return { status: [], agenda: [], sheet: null };
|
|
const n = live?.n ?? latest;
|
|
const dir = session.sessionDir(runId, n);
|
|
/** @type {import('./shapes.mjs').LogEvent[]} */ const lines = [];
|
|
/** @param {string} p @returns {import('./shapes.mjs').LogEvent[]} */
|
|
const readJsonl = (p) => fs.existsSync(p)
|
|
? fs.readFileSync(p, 'utf8').split('\n').filter((l) => l.trim())
|
|
.map((l) => /** @type {import('./shapes.mjs').LogEvent} */ (JSON.parse(l)))
|
|
: [];
|
|
if (live) {
|
|
lines.push(...live.lines);
|
|
} else {
|
|
lines.push(...readJsonl(path.join(dir, 'log.jsonl')));
|
|
if (session.sessionMeta(runId, n).phase === 'dormant') {
|
|
lines.push(...readJsonl(path.join(dir, 'carryover.jsonl')));
|
|
}
|
|
}
|
|
const st = session.scanState(lines);
|
|
return { status: st.status ?? [], agenda: st.agenda ?? [], sheet: st.sheet };
|
|
}
|
|
|
|
route('GET', '/api/runs/:id/status', async ({ params, user }) => {
|
|
requireOwner(user, params.id); // status and agenda are machinery
|
|
return derivedState(params.id);
|
|
});
|
|
|
|
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)).content;
|
|
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) {
|
|
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
|
|
if (DEBUG) {
|
|
// debug: the one fixed superuser, token-gated -- the token lives
|
|
// in state/debug-token.txt and is printed at every boot
|
|
return m && m[1].trim() === users.debugToken() ? DEBUG_USER : null;
|
|
}
|
|
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}`);
|
|
// the packager's body carries a whole book as one JSON string --
|
|
// every other route keeps the 1MB cap
|
|
const bodyLimit = url.pathname === '/api/packager' ? 6 * 1024 * 1024 : 1024 * 1024;
|
|
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req, bodyLimit) : {};
|
|
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 } : {}) });
|
|
}
|
|
});
|
|
|
|
// the bind is code, not config (developer, 2026-11-19): loopback
|
|
// always -- a deployment fronts the server with a proxy, and anything
|
|
// else is the op's socat. The port rides RP_PORT (the RP_BASE twin
|
|
// the test scripts use), default 7350, garbage refused loud.
|
|
const PORT = (() => {
|
|
const raw = process.env.RP_PORT;
|
|
if (raw == null || raw === '') return 7350;
|
|
const n = Number(raw);
|
|
if (!Number.isInteger(n) || n < 1 || n > 65535) {
|
|
console.error(`RP_PORT '${raw}' is not a port -- fix or unset it`);
|
|
process.exit(1);
|
|
}
|
|
return n;
|
|
})();
|
|
server.listen(PORT, '127.0.0.1', () => {
|
|
const providerCount = ctx.providerCfg.providers.length;
|
|
const discovered = Object.keys(discovery.registry()?.providers ?? {}).length;
|
|
console.log(`Tiny Worlds server: http://127.0.0.1:${PORT} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG' : ''}`);
|
|
if (DEBUG) console.log(`debug token (paste it into the sign-in box): ${users.debugToken()}`);
|
|
});
|