diff --git a/.gitignore b/.gitignore index 1cd52d0..d69eb8f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ runs/ state/ server.json +node_modules/ diff --git a/AGENTS.md b/AGENTS.md index 10dc9bb..d943285 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,14 +83,24 @@ memory the agent owes itself across sessions. - The repo lives at `C:\data\opencode\tiny-worlds` (renamed from `rp-test` with the project name, 2026-11-15). The rename could not happen in place -- the running app held the old dir -- so the move - was robocopy + session repoint; `C:\data\opencode\rp-test` is a - frozen snapshot awaiting deletion (its MOVED.txt says so). Always + was robocopy + session repoint, plus a one-time sqlite edit of + opencode's own db (`~/.local/share/opencode/opencode.db`) to + repoint the project record and drop the stale duplicate project + the desktop UI cannot delete (anomalyco/opencode#28030). The old + dir and the db backup are gone; the rename is complete. Always launch from the new path. - The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running `--mock` server, prints its run ids, and leaves a temp token file for `restart-check.mjs`; `check-reminder.mjs` takes a run id; `check-repo.mjs` needs no server. Clean up state/ and the smoke - runs afterwards -- only the real runs stay. + runs afterwards -- only the real runs stay. The type gate: + `npm.cmd run typecheck` (plain `npx.cmd tsc -p tsconfig.json`) + runs tsc as a no-emit checker over the JSDoc annotations -- + dev-only tooling (typescript + @types/node in devDependencies, + node_modules gitignored); the runtime stays zero-dependency + (QUESTIONS #4 amended 2026-11-15). Server core is typed under + strict; the clerk (tool/memory.mjs) and web/ are phases to come -- + widen tsconfig include as they land. ## State pointers @@ -120,7 +130,9 @@ memory the agent owes itself across sessions. - Substrate design round complete (2026-11-13); rulings live in ROADMAP ("The harness") and HANDOFF. Bridge retired before ever going live; REST + SPA is the MVP; runs are per-deployment instances copied from - packages at creation; zero-dep stack. Doc set updated to match. + packages at creation; zero-dependency runtime (dev tooling exempt, + QUESTIONS #4 amended 2026-11-15: typescript rides devDependencies, + nothing imports it). Doc set updated to match. - Build order: ALL FOUR PHASES DONE (2026-11-13/14) -- clerk paper migration, preset/run split, prompt split, server, housekeeping job, SPA. The MVP substrate is complete and live-proven end to end diff --git a/HANDOFF.md b/HANDOFF.md index 57be4c1..8467bfc 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -9,7 +9,20 @@ file is the "where did we leave off" map. ## Where we are -- **Everything is built, proven, and committed (through `fa3f23b`, +- **The server core is JSDoc-typed, strict, green (2026-11-15, + evening) -- committed.** tsc runs as a + no-emit checker (`npm run typecheck`) over plain `.mjs` with JSDoc + annotations; the shared shapes live in `server/shapes.mjs` (log + events as a tagged union, wire messages, manifests, job state, + the Ctx). Dev tooling only: `typescript` + `@types/node` in + devDependencies, `node_modules/` gitignored -- the runtime stays + zero-dependency (QUESTIONS #4 amended to say so). Verified: the + full diff audited change-by-change (every non-annotation delta is + an impossible-path guard or a behavior-identical wrap), smoke + 105/105, restart-check, check-repo, all green. Phases to come are + steps 5 and 6 below. + +- **Everything is built, proven, and committed (through `d737e47`, 2026-11-15).** The full scope, each round mock-proven end to end and live-proven where live could reach: the MVP substrate (clerk, server, housekeeping job, SPA), multiuser (token identity, invites, @@ -18,9 +31,17 @@ file is the "where did we leave off" map. round (/story, /table, the slidwin carry), the dormant-session rework (the universal session lifecycle, move-at-stop, the start lint, rebaseable housekeeping, carryover.jsonl + memory.json - packages), and the format house rules (nine-rule check-repo). The - design record lives in README / DICTIONARY / ROADMAP; the build - history in the git log. + packages), the format house rules (nine-rule check-repo), and the + naming round. The design record lives in README / DICTIONARY / + ROADMAP; the build history in the git log. +- **The project is named: Tiny Worlds.** The invariant it names is + stated in README's premise -- each package is a tiny world on + purpose. The repo lives at `C:\data\opencode\tiny-worlds`; the + rename from `rp-test` is complete end to end (robocopy + session + repoint + a one-time sqlite edit of opencode's own db to repoint + the project record -- the desktop UI cannot delete or repoint + projects, anomalyco/opencode#28030). Launch sessions from the new + path. - **The first real story is live: "La Caramba / Irene"** (run 4f261452, gitignored state). Session one open, 53 GM + 53 player story turns, ~23K prompt tokens -- single-digit percent of the @@ -68,6 +89,14 @@ file is the "where did we leave off" map. candidates), coin-flip personality (choices offloaded to chance that should be character), and whether her variants stay same-turn alternatives rather than sequences. +5. **Typing phase 3: the clerk** (`tool/memory.mjs`, the big one). + The db row shapes (entries, records, status, agenda, the events + journal), the CLI dispatch, the manifest validator -- typed at the + db boundary per the same doctrine, then widen tsconfig's include + to `tool/`. +6. **Typing phase 4: web/** -- DOM types for the SPA modules + (`"lib": ["DOM"]` or a second tsconfig), the same shared shapes + imported from server/shapes.mjs where the wire surfaces appear. ## Not yet exercised (expect first-use friction) diff --git a/QUESTIONS.md b/QUESTIONS.md index c9eb4ba..ff519ae 100644 --- a/QUESTIONS.md +++ b/QUESTIONS.md @@ -7,14 +7,11 @@ a tier. ## Operator's queue (don't edit, don't work on) -- name the project. Tiny Worlds? -- jsdoc - debug mode skipping the invite - explain "one thing of thinking" in reminder - calibration package: escape room - user manual - remove spectator mode, make all story views public and forkable -- fork should copy the entire run - add raw sessions view to the table - git remote; no PII anywhere in repo or git history @@ -45,11 +42,16 @@ run again. ## The substrate (REST + SPA) -### 4. Stack -- RESOLVED (2026-11-13) -Zero-dependency, ruled by GM: `node:http` with a hand-rolled router, a -no-build vanilla ES-module SPA, no `package.json` -- the repo ethos -carried through. If a need ever demands a dependency, it makes its case -then. +### 4. Stack -- RESOLVED (2026-11-13), AMENDED (2026-11-15) +Zero-dependency runtime, ruled by GM: `node:http` with a hand-rolled +router, a no-build vanilla ES-module SPA. If a need ever demands a +runtime dependency, it makes its case then. Amendment (2026-11-15): +no *runtime* dependencies or package-manager requirements -- the +running system stays clone-and-run with node alone. Development +tooling is exempt and may use whatever is necessary; the first +dev deps are `typescript` + `@types/node` (JSDoc type checking, +`tsc` as a no-emit checker -- no transpile step, everything stays +`.mjs`). ### 5. ask_gm mid-loop resumption -- RESOLVED (2026-11-12) Pause/resume, no streaming: the turn request returns with the pending diff --git a/README.md b/README.md index 1e444a2..9e795fc 100644 --- a/README.md +++ b/README.md @@ -532,6 +532,12 @@ DICTIONARY.md the terms of art -- the ruled names, one source of AGENTS.md the agent's own working notes -- style lessons, gotchas, state pointers config.json the default package +package.json dev tooling only -- the runtime is zero-dependency; + typecheck script + pinned devDependencies (typescript, + @types/node; node_modules/ gitignored) +tsconfig.json tsc as a no-emit checker over the JSDoc annotations + (checkJs, strict); server core typed, the clerk and + web to follow names-female.txt the name dictionary -- one name per line; the new-run form rolls an unused one for the main character tool/ @@ -585,6 +591,10 @@ server/ the substrate: a zero-dependency node:http service fork.mjs fork: the staged atomic copy with the owner replaced and the `forked` stamp clerk.mjs the clerk boundary (every state op via memory.mjs) + shapes.mjs the shared type declarations -- no runtime code; the + tsc checker and the humans agree on the load-bearing + shapes (log events, wire messages, manifests, job + state) housekeeping.mjs the pass as an async job: one trigger, two behaviors -- stop (close, move the tail, freeze, then the pass) and the re-run (rebase + fresh diff --git a/ROADMAP.md b/ROADMAP.md index cf024a6..0960704 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -171,11 +171,13 @@ example, gitignored real file, env-var option). per-user seam. - **Boutique is dormant** -- a stub that never reached its design step; untouched until its drafting session. -- **Stack: zero-dependency** (QUESTIONS #4 resolved). `node:http` with - a hand-rolled router, no-build vanilla ES-module SPA, no - `package.json`. The hard parts of this project are prompt-side and - clerk-side; the web side at loopback single-user scale is the easy - part. +- **Stack: zero-dependency runtime** (QUESTIONS #4, amended + 2026-11-15). `node:http` with a hand-rolled router, no-build + vanilla ES-module SPA; clone-and-run with node alone. Dev tooling + is exempt: `typescript` + `@types/node` type-check the JSDoc + annotations (`tsc` no-emit -- everything stays `.mjs`). The hard + parts of this project are prompt-side and clerk-side; the web side + at loopback single-user scale is the easy part. ## The multiuser server (2026-11-14, GM) diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..531efda --- /dev/null +++ b/package-lock.json @@ -0,0 +1,45 @@ +{ + "name": "tiny-worlds", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tiny-worlds", + "devDependencies": { + "@types/node": "^22.10.0", + "typescript": "^5.7.0" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..70d0c28 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "tiny-worlds", + "private": true, + "description": "Long-form, freeform, text-based roleplay where the model plays one character and the human plays everything else. Runtime: plain node, zero dependencies -- this file exists for dev tooling only.", + "scripts": { + "typecheck": "tsc -p tsconfig.json" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "typescript": "^5.7.0" + } +} diff --git a/server/bundle.mjs b/server/bundle.mjs index cf0e341..b29768d 100644 --- a/server/bundle.mjs +++ b/server/bundle.mjs @@ -11,6 +11,11 @@ // // The tool list is the capability surface: ask_gm always, records // verbs only when the run's settings allow. +/** @typedef {import('./shapes.mjs').RunMeta} RunMeta */ +/** @typedef {import('./shapes.mjs').RunSettings} RunSettings */ +/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */ +/** @typedef {import('./shapes.mjs').HttpError} HttpError */ + import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -19,26 +24,32 @@ import { clerk, clerkJson } from './clerk.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const RUNS_DIR = path.join(ROOT, 'runs'); +/** @param {string} runId */ export const runDir = (runId) => path.join(RUNS_DIR, runId); + +/** @param {string} runId @returns {?RunMeta} */ export const runMeta = (runId) => { try { - return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'run.json'), 'utf8')); + return /** @type {RunMeta} */ (JSON.parse(fs.readFileSync(path.join(runDir(runId), 'run.json'), 'utf8'))); } catch { return null; } }; + +/** @param {string} runId @returns {string} */ export function requireRun(runId) { if (!/^[a-z0-9-]+$/.test(runId ?? '') || !fs.existsSync(path.join(runDir(runId), 'run.json'))) { - const err = new Error(`no such run: ${runId} -- see GET /api/runs`); + const err = /** @type {HttpError} */ (new Error(`no such run: ${runId} -- see GET /api/runs`)); err.status = 404; throw err; } return runDir(runId); } +/** @param {string} runId @returns {RunSettings} */ export function readSettings(runId) { try { - return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'settings.json'), 'utf8')); + return /** @type {RunSettings} */ (JSON.parse(fs.readFileSync(path.join(runDir(runId), 'settings.json'), 'utf8'))); } catch { return {}; } @@ -54,14 +65,15 @@ export function readSettings(runId) { // in a prompt surfaces as an input in setup, and the run's settings // "vars" holds the answers (a package may ship defaults); an // unresolved $TOKEN fails loudly -- the model never sees a raw var. +/** @param {string} runId @param {?string} s @returns {string} */ function expandVars(runId, s) { const settings = readSettings(runId); let out = String(s ?? ''); const sigils = { PC: settings.pc, Package: settings.name }; out = out.replace(/@(PC|Package)\b/g, (full, name) => { - const v = sigils[name]; + const v = sigils[/** @type {'PC'|'Package'} */ (name)]; if (v == null || !String(v).trim()) { - const err = new Error(`unresolved @${name} -- it must be set in the run's settings.json`); + const err = /** @type {HttpError} */ (new Error(`unresolved @${name} -- it must be set in the run's settings.json`)); err.status = 500; throw err; } @@ -70,7 +82,7 @@ function expandVars(runId, s) { for (const [k, v] of Object.entries(settings.vars ?? {})) out = out.replaceAll(`$${k}`, String(v)); const unresolved = [...new Set([...out.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)].map((m) => `$${m[1]}`))]; if (unresolved.length) { - const err = new Error(`unresolved token(s): ${unresolved.join(', ')} -- fill them in setup; they save to the run's settings.json "vars"`); + const err = /** @type {HttpError} */ (new Error(`unresolved token(s): ${unresolved.join(', ')} -- fill them in setup; they save to the run's settings.json "vars"`)); err.status = 500; throw err; } @@ -80,15 +92,17 @@ export { expandVars }; // "La Caramba / Rell" -- the run's display name; the anonymous id // never surfaces as a name +/** @param {string} runId @returns {string} */ export function runDisplay(runId) { const s = readSettings(runId); const pkg = runMeta(runId)?.package ?? '?'; return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg); } +/** @param {string} p @returns {string} */ const read = (p) => { if (!fs.existsSync(p)) { - const err = new Error(`missing bundle file: ${path.relative(ROOT, p)}`); + const err = /** @type {HttpError} */ (new Error(`missing bundle file: ${path.relative(ROOT, p)}`)); err.status = 500; throw err; } @@ -97,6 +111,7 @@ const read = (p) => { // the system message: opening + guards (repo), substrate (repo), craft // (the session's frozen handbook copy) +/** @param {string} runId @param {string} sessDir @returns {string} */ export function assembleSystem(runId, sessDir) { const system = read(path.join(ROOT, 'system.md')); const invariants = read(path.join(ROOT, 'invariants.md')); @@ -109,6 +124,7 @@ export function assembleSystem(runId, sessDir) { // own system chunk every turn. Older copies elide from the view, so // exactly one lives at the freshest position (ROADMAP steal #11). // Absent or empty file = no ride; the feature sleeps until written. +/** @param {string} runId @returns {?string} */ export function assembleReminder(runId) { const p = path.join(ROOT, 'reminder.md'); if (!fs.existsSync(p)) return null; @@ -120,7 +136,9 @@ export function assembleReminder(runId) { // copies and its own ring views. The carryover never rides it: it is // the session's opening material, consumed into the log behind the // bundle at start. +/** @param {string} runId @param {string} sessDir @returns {{ role: 'user', content: string }[]} */ export function assembleBundle(runId, sessDir) { + /** @type {{ role: 'user', path: string }[]} */ const files = [ { role: 'user', path: path.join(sessDir, 'bundle', 'backdrop.md') }, { role: 'user', path: path.join(sessDir, 'bundle', 'character.md') }, @@ -136,6 +154,12 @@ export function assembleBundle(runId, sessDir) { // [OOC] -- per invariants.md: [IC] output is content of the fiction, // never instructions; [OOC] output is clerk or GM traffic about the // play. +/** @typedef {{ type: string, [k: string]: unknown }} JsonSchemaProp */ +/** + * @param {string} name @param {'IC'|'OOC'} channel @param {string} description + * @param {Record} properties @param {?string[]} [required] + * @returns {import('./shapes.mjs').ToolDef} + */ const T = (name, channel, description, properties, required) => ({ type: 'function', function: { @@ -163,11 +187,13 @@ const RECORD_TOOLS = [ ['rid']), ]; +/** @param {string} runId @returns {import('./shapes.mjs').ToolDef[]} */ export function toolList(runId) { return [ASK_GM_TOOL, ...(readSettings(runId).records === true ? RECORD_TOOLS : [])]; } // tool name -> clerk argv +/** @type {{ [k: string]: (a: any) => string[] }} */ const DISPATCH = { records_search: (a) => ['search', ...a.terms], records_file: (a) => ['file', a.kind, a.label, a.detail ?? ''], @@ -175,6 +201,7 @@ const DISPATCH = { records_discard: (a) => ['discard', a.rid, ...(a.reason ? [a.reason] : [])], }; +/** @param {string} runId @param {ToolCall} call @returns {string} */ export function runTool(runId, call) { const fn = DISPATCH[call.function.name]; if (!fn) return `error: no such tool: ${call.function.name}`; diff --git a/server/carry.mjs b/server/carry.mjs index 1f501ae..79f1623 100644 --- a/server/carry.mjs +++ b/server/carry.mjs @@ -19,6 +19,8 @@ import { effectiveContents } from './variants.mjs'; +/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */ + // ~10% of a 256K-class contwin in token terms, grounded on Irene's // session (84KB of turn content at ~23K prompt tokens). Substrate // policy, not deployment taste: a constant, not config. @@ -27,6 +29,7 @@ export const CARRY_BUDGET = 96 * 1024; const STRIP_BLOCKS = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g; // the prose the model will see for one log line in the new contwin +/** @param {LogEvent[]} lines @param {Map} eff @param {number} i @returns {number} */ function visibleBytes(lines, eff, i) { const e = lines[i]; if (e.t === 'msg') { @@ -58,6 +61,7 @@ function visibleBytes(lines, eff, i) { // instead of leaving her cue behind in the dead log. When nothing // fits (the degenerate empty tail) it stays behind and files // normally. +/** @param {LogEvent[]} lines @returns {number} */ export function tailStart(lines) { const eff = effectiveContents(lines); const exchanges = []; diff --git a/server/clerk.mjs b/server/clerk.mjs index ade03d0..08ca8f8 100644 --- a/server/clerk.mjs +++ b/server/clerk.mjs @@ -1,6 +1,9 @@ // server/clerk.mjs -- the clerk boundary. Every state operation goes // through the memory.mjs CLI; the server never touches the database // directly. The clerk stays the one truth. +/** @typedef {import('./shapes.mjs').ClerkResult} ClerkResult */ +/** @typedef {import('./shapes.mjs').User} User */ + import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -8,10 +11,13 @@ import { fileURLToPath } from 'node:url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const CLERK = path.join(ROOT, 'tool', 'memory.mjs'); +// every spawn strips the sqlite experimental warning from stderr; the +// rest is the clerk's own voice +/** @param {string} runId @param {...string} args @returns {ClerkResult} */ export function clerk(runId, ...args) { const res = spawnSync(process.execPath, [CLERK, '--run', runId, '--quiet', ...args], { encoding: 'utf8' }); return { - code: res.status, + code: res.status ?? 1, // null only on a signal kill; callers only ever test against 0 out: (res.stdout || '').trim(), err: (res.stderr || '').split('\n') .filter((l) => !l.includes('ExperimentalWarning') && !l.includes('trace-warnings')) @@ -19,6 +25,8 @@ export function clerk(runId, ...args) { }; } +/** Run a clerk verb and parse its --json stdout as T. + * @template T @param {string} runId @param {...string} args @returns {T} */ export function clerkJson(runId, ...args) { const r = clerk(runId, ...args); if (r.code !== 0) throw new Error(r.err || r.out || `clerk ${args[0]} failed`); @@ -30,15 +38,17 @@ export function clerkJson(runId, ...args) { } // a clerk call that is allowed to fail (returns the result either way) +/** @param {string} runId @param {...string} args @returns {ClerkResult} */ export function clerkTry(runId, ...args) { return clerk(runId, ...args); } // commands that address no run (packages, runs, create) +/** @param {...string} args @returns {ClerkResult} */ export function clerkRaw(...args) { const res = spawnSync(process.execPath, [CLERK, ...args], { encoding: 'utf8' }); return { - code: res.status, + code: res.status ?? 1, // null only on a signal kill; callers only ever test against 0 out: (res.stdout || '').trim(), err: (res.stderr || '').split('\n') .filter((l) => !l.includes('ExperimentalWarning') && !l.includes('trace-warnings')) @@ -47,6 +57,7 @@ export function clerkRaw(...args) { } // machine output for run-less commands (packages, runs) +/** @template T @param {...string} args @returns {T} */ export function clerkRawJson(...args) { const r = clerkRaw('--json', ...args); if (r.code !== 0) throw new Error(r.err || r.out || `clerk ${args[0]} failed`); diff --git a/server/fork.mjs b/server/fork.mjs index 36c32e7..55895f6 100644 --- a/server/fork.mjs +++ b/server/fork.mjs @@ -16,9 +16,16 @@ import { fileURLToPath } from 'node:url'; import { requireRun } from './bundle.mjs'; import { liveSession, loadSession } from './session.mjs'; +/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */ + const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const RUNS_DIR = path.join(ROOT, 'runs'); +/** + * @param {{ sessions: Map }} ctx + * @param {string} srcId @param {{ id: string }} user + * @returns {{ run: string }} + */ export function forkRun(ctx, srcId, user) { requireRun(srcId); let id; diff --git a/server/housekeeping.mjs b/server/housekeeping.mjs index 2862a04..e84172f 100644 --- a/server/housekeeping.mjs +++ b/server/housekeeping.mjs @@ -18,6 +18,12 @@ // rejection at any step holds the state and surfaces why; the // manifest (or the raw output, if unparseable) stays on disk for a // hand edit and POST .../housekeeping/apply. +/** @typedef {import('./shapes.mjs').Ctx} Ctx */ +/** @typedef {import('./shapes.mjs').JobState} JobState */ +/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */ +/** @typedef {import('./shapes.mjs').Manifest} Manifest */ +/** @typedef {import('./shapes.mjs').Actor} Actor */ + import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -31,6 +37,7 @@ import { HttpError } from './loop.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +/** @param {string} dir @param {string} f @returns {string} */ const readAt = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').trim(); // --- transcript -------------------------------------------------------------- @@ -43,6 +50,7 @@ const readAt = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').trim(); // branches never happened, and must never enter memory. The log is // read as it was left -- stop already truncated it at the slidwin // boundary, so the rings never overlap the carried prose. +/** @param {LogEvent[]} lines @returns {string} */ export function renderTranscript(lines) { const eff = effectiveContents(lines); const L = []; @@ -52,7 +60,7 @@ export function renderTranscript(lines) { if (e.t === 'msg' && e.reminder) continue; // identical every turn -- context, not exchange if (e.t === 'msg') { if (e.m.role === 'user' && e.conflictOnly) { - L.push('[conflict -- answered in-band]', e.m.content.replace(/<\/?conflict>/g, '').trim(), ''); + L.push('[conflict -- answered in-band]', String(e.m.content ?? '').replace(/<\/?conflict>/g, '').trim(), ''); continue; } if (e.m.role === 'user') { @@ -89,6 +97,7 @@ export function renderTranscript(lines) { // the housekeeper's fresh context; run state rides alongside the // prompt. The card, backdrop and rings are the FINISHED session's // own frozen material -- exactly what it played with. +/** @param {string} runId @param {number} n @param {LogEvent[]} lines @returns {{ role: 'system'|'user', content: string }[]} */ export function buildMessages(runId, n, lines) { const dir = sessionDir(runId, n); const settings = readSettings(runId); @@ -109,6 +118,7 @@ export function buildMessages(runId, n, lines) { // --- the manifest ------------------------------------------------------------ // the housekeeper emits one JSON manifest; tolerate fences and prose +/** @param {?string} text @returns {Manifest} */ export function parseManifest(text) { const fences = [...String(text ?? '').matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]); for (const c of [...fences, String(text ?? '')]) { @@ -125,6 +135,10 @@ export function parseManifest(text) { // --- the job ----------------------------------------------------------------- +/** + * @param {Ctx} ctx @param {string} runId @param {?Actor} user + * @returns {JobState} + */ export function trigger(ctx, runId, user) { requireRun(runId); const live = ctx.sessions.get(runId); @@ -135,7 +149,7 @@ export function trigger(ctx, runId, user) { // the job (under the run's activity lock), then the pass runs. if (live.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it before stopping the session'); ctx.sessions.delete(runId); // the session is closed from here on - const job = { state: 'running', phase: 'stop', session: live.n, started: new Date().toISOString() }; + const job = /** @type {JobState} */ ({ state: 'running', phase: 'stop', session: live.n, started: new Date().toISOString() }); ctx.jobs.set(runId, job); ctx.enqueue(runId, () => runStop(ctx, runId, live.n, user)); return job; @@ -148,14 +162,15 @@ export function trigger(ctx, runId, user) { if (latest === 1) { throw new HttpError(409, 'session one\'s memories are its package\'s memory.json -- edit them in setup; there is no session zero to re-run'); } - const job = { state: 'running', phase: 'rerun', session: latest - 1, target: latest, started: new Date().toISOString() }; + const job = /** @type {JobState} */ ({ state: 'running', phase: 'rerun', session: latest - 1, target: latest, started: new Date().toISOString() }); ctx.jobs.set(runId, job); ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user)); return job; } +/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise} */ async function runStop(ctx, runId, n, user) { - const job = ctx.jobs.get(runId); + const job = /** @type {JobState} */ (ctx.jobs.get(runId)); try { stopSession(runId, n); // the move, the freeze, the copies job.stopped = true; @@ -168,8 +183,9 @@ async function runStop(ctx, runId, n, user) { // one housekeeping pass: session n's log -> manifest -> apply into // the dormant session n+1 -> ready +/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise} */ async function runPass(ctx, runId, n, user) { - const job = ctx.jobs.get(runId); + const job = /** @type {JobState} */ (ctx.jobs.get(runId)); const lines = loadSession(runId, n).lines; const text = ctx.mock ? mockManifest(n) @@ -191,8 +207,15 @@ async function runPass(ctx, runId, n, user) { job.state = 'applied'; } +/** @typedef {import('./shapes.mjs').RunMeta} RunMeta */ + +/** + * @param {Ctx} ctx @param {string} runId + * @param {import('./shapes.mjs').ViewMessage[]} messages @param {?Actor} user + * @returns {Promise} + */ async function callHousekeeper(ctx, runId, messages, user) { - const meta = ctx.runMeta?.(runId) ?? {}; + const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({}); const model = meta.models?.housekeeper ?? ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player @@ -212,6 +235,7 @@ export { callHousekeeper }; // and agenda carry; the rings reset to the base the manifest lands // on) -- so re-runs never double-apply, and hand edits made in // between are overwritten, ruled fine. +/** @param {string} runId @param {string} manifestPath @param {number} n */ export function applyToDormant(runId, manifestPath, n) { const target = sessionDir(runId, n + 1); if (sessionMeta(runId, n + 1).phase !== 'dormant') { @@ -227,6 +251,7 @@ export function applyToDormant(runId, manifestPath, n) { writeMeta(runId, n + 1, { ready: true }); } +/** @param {Ctx} ctx @param {string} runId @returns {JobState} */ export function jobState(ctx, runId) { requireRun(runId); const job = ctx.jobs.get(runId); @@ -243,6 +268,7 @@ export function jobState(ctx, runId) { } // the newest housekeeping record on disk +/** @param {string} runId @returns {{ session: number, pass: string, content: string }} */ export function latestLog(runId) { const ns = listSessions(runId); for (let i = ns.length - 1; i >= 0; i--) { @@ -262,6 +288,7 @@ export function latestLog(runId) { // A canned but valid manifest keyed to the mock player's script: touches // the cuffs (they shaped every move) and files the dark hold as a new // ring-B memory. Exercises the whole chain without a key. +/** @param {number} n @returns {string} */ function mockManifest(n) { return JSON.stringify({ session: String(n), diff --git a/server/loop.mjs b/server/loop.mjs index 0948431..16607cb 100644 --- a/server/loop.mjs +++ b/server/loop.mjs @@ -7,12 +7,20 @@ // before every GM turn and rides it as a block; the player's // / deltas apply after its final message, and any // conflicts ride the next GM turn as a block. +/** @typedef {import('./shapes.mjs').Ctx} Ctx */ +/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */ +/** @typedef {import('./shapes.mjs').Actor} Actor */ +/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */ + import { clerkJson } from './clerk.mjs'; import { toolList, runTool, assembleReminder } from './bundle.mjs'; import { renderView } from './session.mjs'; import { parseVariants, pickVariant } from './variants.mjs'; export class HttpError extends Error { + /** + * @param {number} status @param {string} message @param {unknown} [detail] + */ constructor(status, message, detail) { super(message); this.status = status; @@ -20,17 +28,25 @@ export class HttpError extends Error { } } +/** @param {Ctx} ctx @param {string} runId @returns {LiveSession} */ function needSession(ctx, runId) { const s = ctx.sessions.get(runId); if (!s) throw new HttpError(409, `no open session for run '${runId}' -- POST /api/runs/${runId}/sessions first`); return s; } +/** The turn request's response: what the SPA needs to render the turn. */ +/** @typedef {{ tools: string[], pendingAsk?: string, variants?: { count: number, chosen: number }, conflicts?: string[], player?: string }} TurnOut */ + +/** + * @param {Ctx} ctx @param {string} runId @param {string} line @param {?Actor} user + * @returns {Promise} + */ export async function gmTurn(ctx, runId, line, user) { const s = needSession(ctx, runId); if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)'); - const status = clerkJson(runId, 'status'); // fresh per turn - const agenda = clerkJson(runId, 'agenda'); // fresh per turn + const status = /** @type {string[]} */ (clerkJson(runId, 'status')); // fresh per turn + const agenda = /** @type {string[]} */ (clerkJson(runId, 'agenda')); // fresh per turn // the wire renders the queue as the model cites it: numbered from the top const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; '); const content = `${line.trim()}\n\n${status.join(', ')}\n${agendaWire}`; @@ -45,10 +61,18 @@ export async function gmTurn(ctx, runId, line, user) { // the opening auto-send: a carryover that ends on a GM turn is her // cue -- the first request of the assembled contwin fires with no new // line (the cue is already the log's last word) +/** + * @param {Ctx} ctx @param {string} runId @param {?Actor} user + * @returns {Promise} + */ export async function openingCall(ctx, runId, user) { return runLoop(ctx, runId, user); } +/** + * @param {Ctx} ctx @param {string} runId @param {string} answer @param {?Actor} user + * @returns {Promise} + */ export async function answerAsk(ctx, runId, answer, user) { const s = needSession(ctx, runId); if (!s.pendingAsk) throw new HttpError(409, 'no pending question'); @@ -65,9 +89,11 @@ export async function answerAsk(ctx, runId, answer, user) { return runLoop(ctx, runId, user); } +/** @param {Ctx} ctx @param {string} runId @param {?Actor} user @returns {Promise} */ async function runLoop(ctx, runId, user) { - const s = ctx.sessions.get(runId); + const s = needSession(ctx, runId); const tools = toolList(runId); + /** @type {TurnOut} */ const out = { tools: [] }; let heals = 0; for (;;) { @@ -155,8 +181,9 @@ async function runLoop(ctx, runId, user) { } } +/** @param {Ctx} ctx @param {string} runId @returns {?string} */ function resolveModel(ctx, runId) { - const meta = ctx.runMeta(runId) ?? {}; + const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({}); return meta.models?.player ?? ctx.cfg.models?.player ?? null; } @@ -173,7 +200,13 @@ function resolveModel(ctx, runId) { // path), the answer lands with status and agenda deltas (the tag // transports), then the drops, a bad drop, its self-heal, and // everything after is plain prose. +/** @typedef {import('./shapes.mjs').WireMessage} WireMessage */ + +/** + * @param {LiveSession} s @param {ViewMessage[]} view @returns {WireMessage} + */ function mockModel(s, view) { + /** @param {string} name @param {Record} args @param {string} id @returns {WireMessage} */ const call = (name, args, id) => ({ role: 'assistant', content: null, diff --git a/server/main.mjs b/server/main.mjs index 16e8c1f..93498af 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -8,6 +8,13 @@ // view. // // usage: node server/main.mjs [--mock] +/** @typedef {import('./shapes.mjs').Ctx} Ctx */ +/** @typedef {import('./users.mjs').UserRow} UserRow */ +/** A request as a handler sees it: path params, the parsed JSON body + * (any -- handlers validate), the raw request, the acting user. */ +/** @typedef {{ params: Record, body: any, req: import('node:http').IncomingMessage, user: ?UserRow }} Req */ +/** @typedef {(req: Req) => unknown} Handler */ + import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; @@ -30,10 +37,14 @@ if (!fs.existsSync(CONFIG_PATH)) { console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)'); process.exit(1); } -const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')); +const cfg = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'))); if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed'); const provider = makeProvider(cfg.endpoint ?? {}); -const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta }; +// locks/enqueue are attached just below; the cast is the two-step that +// lets the literal precede them +const ctxBase = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta }; +/** @type {Ctx} */ +const ctx = /** @type {Ctx} */ (ctxBase); // --- the per-run activity lock --------------------------------------------------- // @@ -46,7 +57,7 @@ ctx.locks = new Map(); ctx.enqueue = (runId, fn) => { const prev = ctx.locks.get(runId) ?? Promise.resolve(); const next = prev.then(fn, fn); // run regardless of a prior failure - ctx.locks.set(runId, next.catch(() => {})); + ctx.locks.set(runId, /** @type {Promise} */ (next.catch(() => {}))); return next; }; @@ -82,13 +93,16 @@ if (fs.existsSync(path.join(ROOT, 'runs'))) { // --- http plumbing ----------------------------------------------------------- +/** @param {import('node:http').ServerResponse} res @param {number} status @param {unknown} body */ const send = (res, status, body) => { const data = JSON.stringify(body); res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) }); res.end(data); }; +/** @param {import('node:http').IncomingMessage} req @returns {Promise} */ const readBody = (req) => new Promise((resolve, reject) => { + /** @type {Buffer[]} */ const chunks = []; let size = 0; req.on('data', (c) => { @@ -104,14 +118,18 @@ const readBody = (req) => new Promise((resolve, reject) => { req.on('error', reject); }); +/** @type {{ method: string, segs: string[], handler: Handler, publicRoute: boolean }[]} */ const routes = []; +/** @param {string} method @param {string} pattern @param {Handler} handler @param {{ public?: boolean }} [opts] */ const route = (method, pattern, handler, opts = {}) => routes.push({ method, segs: pattern.split('/').filter(Boolean), handler, publicRoute: opts.public === true }); +/** @param {string} method @param {string} pathname @returns {?{ handler: Handler, params: Record, 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} */ const params = {}; for (let i = 0; i < segs.length; i++) { if (r.segs[i].startsWith(':')) params[r.segs[i].slice(1)] = decodeURIComponent(segs[i]); @@ -127,6 +145,7 @@ const match = (method, pathname) => { // at /). Traversal-guarded; the SPA is a client like curl is. const WEB_DIR = path.join(ROOT, 'web'); +/** @type {Record} */ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', @@ -136,6 +155,7 @@ const MIME = { '.json': 'application/json', }; +/** @param {string} pathname @param {import('node:http').ServerResponse} res */ function serveStatic(pathname, res) { let rel = decodeURIComponent(pathname).replace(/^\/+/, ''); if (!rel) rel = 'index.html'; @@ -217,28 +237,48 @@ route('POST', '/api/users/:id/revoke', async ({ params, user }) => { return { ok: true }; }); +/** @param {?UserRow} user */ +/** + * @param {?UserRow} user + * @returns {asserts user is UserRow} + */ function requireSuperuser(user) { if (!user?.superuser) throw new HttpError(403, 'superuser only'); } +// the router already guarantees this on every protected route; the +// type system needs it said out loud +/** + * @param {?UserRow} user + * @returns {asserts user is UserRow} + */ +function requireUser(user) { + if (!user) throw new HttpError(401, 'not signed in'); +} + // ownership is resolved, never maintained: run.json keeps the record // of who owned a run, and a dead owner id (revocation) resolves to // absent. The API never exposes a dangling id. +/** @param {?string|undefined} owner @returns {?string} */ const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null); // ownership: every GM action -- every mutation, every model call -- is // the owner's alone. Ownerless runs (pre-user or revoked owner) are // one uniform state: readable by all, forkable, never re-claimed. +/** + * @param {?UserRow} user @param {string} runId + * @returns {asserts user is UserRow} + */ function requireOwner(user, runId) { + if (!user) throw new HttpError(401, 'not signed in'); // the router guarantees this on protected routes bundle.requireRun(runId); // 404 when it doesn't exist - const meta = bundle.runMeta(runId) ?? {}; + const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({}); if (resolveOwner(meta.owner) == null) { throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`); } if (meta.owner !== user.id) { throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`); } - return meta; } // --- routes ------------------------------------------------------------------- @@ -280,7 +320,7 @@ route('POST', '/api/packages', async ({ body, user }) => { // substrate invariants, and the per-turn reminder -- never copied into // a run, so the editor shows them as context, not as something to edit route('GET', '/api/prompts', async () => { - const readOpt = (f) => (fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), 'utf8').trim() : null); + const readOpt = (/** @type {string} */ f) => (fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), 'utf8').trim() : null); return { system: readOpt('system.md'), invariants: readOpt('invariants.md'), @@ -314,6 +354,7 @@ route('POST', '/api/runs', async ({ body, user }) => { if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug -- see GET /api/packages'); if (!pc) throw new HttpError(400, 'pc is required -- the main character\'s name, distinct per package'); const name = body.name === undefined ? undefined : String(body.name); + requireUser(user); const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : [])); if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed'); const run = JSON.parse(r.out); @@ -323,7 +364,7 @@ route('POST', '/api/runs', async ({ body, user }) => { // a name to play as: rolled from the dictionary, unused by any run route('GET', '/api/names', async () => { const all = fs.readFileSync(path.join(ROOT, 'names-female.txt'), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean); - const used = new Set(clerkRawJson('runs').flatMap((r) => (r.pc ? [String(r.pc).toLowerCase()] : []))); + const used = new Set(/** @type {{ pc?: string }[]} */ (clerkRawJson('runs')).flatMap((r) => (r.pc ? [String(r.pc).toLowerCase()] : []))); const free = all.filter((n) => !used.has(n.toLowerCase())); const pool = free.length ? free : all; // a fully-used dictionary still suggests return { name: pool[Math.floor(Math.random() * pool.length)] }; @@ -386,6 +427,10 @@ route('GET', '/api/runs/:id', async ({ params }) => { // play-view pad); config is read-only (vars and lineage are easy to // break blind). +/** One file of the editor surface. */ +/** @typedef {{ mode: string, path: string }} FileSpec */ + +/** @param {string} runId @returns {{ n: number, phase?: string, files: Record }} */ function fileSurface(runId) { const live = ctx.sessions.get(runId); const latest = session.latestSession(runId); @@ -411,6 +456,7 @@ function fileSurface(runId) { route('GET', '/api/runs/:id/files', async ({ params }) => { bundle.requireRun(params.id); const surf = fileSurface(params.id); + /** @type {Record} */ const files = {}; for (const [f, spec] of Object.entries(surf.files)) { files[f] = fs.existsSync(spec.path) @@ -478,9 +524,9 @@ route('POST', '/api/runs/:id/model', async ({ params, body, user }) => { for (const k of Object.keys(body)) { if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} -- player and housekeeper`); } - const meta = bundle.runMeta(id) ?? {}; + const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({}); const models = meta.models ?? {}; - for (const role of ['player', 'housekeeper']) { + for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) { if (body[role] === undefined) continue; if (body[role] === null) { delete models[role]; continue; } const m = String(body[role]).trim(); @@ -534,7 +580,8 @@ route('DELETE', '/api/runs/:id', async ({ params, user }) => { route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => { const id = params.id; requireOwner(user, id); - if (ctx.sessions.has(id)) throw new HttpError(409, `session ${ctx.sessions.get(id).n} is already live -- one active session per run`); + const cur = ctx.sessions.get(id); + if (cur) throw new HttpError(409, `session ${cur.n} is already live -- one active session per run`); return ctx.enqueue(id, async () => { const { session: s, autoSend } = session.startSession(id, { override: body.override === true }); ctx.sessions.set(id, s); @@ -569,6 +616,7 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => { const meta = session.sessionMeta(params.id, latest); if (meta.phase !== 'dormant') throw new HttpError(409, `session ${latest} is ${meta.phase || 'unmarked'}`); const p = path.join(session.sessionDir(params.id, latest), 'carryover.jsonl'); + /** @type {import('./shapes.mjs').LogEvent[]} */ const lines = []; if (fs.existsSync(p)) { for (const l of fs.readFileSync(p, 'utf8').split('\n')) { @@ -583,13 +631,14 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => { const eff = effectiveContents(lines); const entries = lines.map((e, i) => { if (e.t === 'msg' && e.m.role === 'assistant') { - const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) }; + /** @type {import('./shapes.mjs').ViewMessage} */ + const m = { role: 'assistant', content: eff.has(i) ? (eff.get(i) ?? null) : (e.m.content ?? null) }; if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls; return { ...e, m }; } return e; }); - const lastMsg = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder); + const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null); return { run: params.id, session: latest, @@ -611,7 +660,8 @@ route('GET', '/api/runs/:id/table', async ({ params }) => { const eff = effectiveContents(s.lines); const entries = s.lines.map((e, i) => { if (e.t === 'msg' && e.m.role === 'assistant') { - const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) }; + /** @type {import('./shapes.mjs').ViewMessage} */ + const m = { role: 'assistant', content: eff.has(i) ? (eff.get(i) ?? null) : (e.m.content ?? null) }; if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls; return { ...e, m }; } @@ -647,8 +697,9 @@ route('GET', '/api/runs/:id/story', async ({ params }) => { bundle.requireRun(params.id); const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g; const verbs = /<(lost|gained|add|drop)>[\s\S]*?<\/\1>/g; - const project = (lines) => { + const project = (/** @type {import('./shapes.mjs').LogEvent[]} */ lines) => { const eff = effectiveContents(lines); + /** @type {{ who: string, text: string }[]} */ const turns = []; for (let i = 0; i < lines.length; i++) { const e = lines[i]; @@ -664,7 +715,9 @@ route('GET', '/api/runs/:id/story', async ({ params }) => { } return turns; }; + /** @param {string} p @returns {import('./shapes.mjs').LogEvent[]} */ const readJsonl = (p) => { + /** @type {import('./shapes.mjs').LogEvent[]} */ const out = []; if (!fs.existsSync(p)) return out; for (const l of fs.readFileSync(p, 'utf8').split('\n')) { @@ -695,14 +748,14 @@ route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => { const line = String(body.line ?? '').trim(); if (!line) throw new HttpError(400, 'line is required'); requireOwner(user, params.id); - return { ok: true, ...(await ctx.enqueue(params.id, () => gmTurn(ctx, params.id, line, user))) }; + return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user))) }; }); route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => { const answer = String(body.answer ?? '').trim(); if (!answer) throw new HttpError(400, 'answer is required'); requireOwner(user, params.id); - return { ok: true, ...(await ctx.enqueue(params.id, () => answerAsk(ctx, params.id, answer, user))) }; + return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user))) }; }); // fork: any user, any run -- a mechanical atomic copy with the owner @@ -710,7 +763,9 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => { // the copy is never taken mid-turn. route('POST', '/api/runs/:id/fork', async ({ params, user }) => { bundle.requireRun(params.id); - return ctx.enqueue(params.id, () => forkRun(ctx, params.id, user)); + requireUser(user); // any signed-in user forks; the router guarantees this + const u = user; + return ctx.enqueue(params.id, async () => forkRun(ctx, params.id, u)); }); route('GET', '/api/runs/:id/status', async ({ params }) => { @@ -821,7 +876,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) const latest = session.latestSession(id); if (latest == null || latest < 2) throw new HttpError(409, 'no dormant continuation session to apply into'); if (session.sessionMeta(id, latest).phase !== 'dormant') throw new HttpError(409, `session ${latest} is not dormant`); - return ctx.enqueue(id, () => { + return ctx.enqueue(id, async () => { try { housekeeping.applyToDormant(id, manifestPath, latest - 1); return { ok: true, housekept: latest - 1, target: latest }; @@ -835,6 +890,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) // --- dispatch ------------------------------------------------------------------- // bearer-token identity (users.mjs); null when absent or unknown +/** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */ function authenticate(req) { const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? ''); return m ? users.getUserByToken(m[1].trim()) : null; @@ -842,9 +898,10 @@ function authenticate(req) { const server = http.createServer(async (req, res) => { const started = Date.now(); + /** @type {?UserRow} */ let user = null; try { - const url = new URL(req.url, 'http://localhost'); + const url = new URL(req.url ?? '/', 'http://localhost'); // the request log: one line per API call -- reconstruct any session // from the console output after the fact; the acting user rides // every line (attribution, #22) @@ -858,7 +915,7 @@ const server = http.createServer(async (req, res) => { serveStatic(url.pathname, res); return; } - const m = match(req.method, url.pathname); + const m = match(String(req.method), url.pathname); if (!m) throw new HttpError(404, `no such route: ${req.method} ${url.pathname}`); const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {}; user = authenticate(req); @@ -872,6 +929,6 @@ const server = http.createServer(async (req, res) => { }); const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':'); -server.listen(Number(port), host, () => { +server.listen(Number(port ?? 7350), host, () => { console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt`); }); diff --git a/server/provider.mjs b/server/provider.mjs index bef6147..a4666fe 100644 --- a/server/provider.mjs +++ b/server/provider.mjs @@ -1,6 +1,13 @@ // server/provider.mjs -- the endpoint client. One OpenAI-compatible // endpoint per deployment (server.json "endpoint"); the model name // comes from the run (run.json override) or the config default. +/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */ +/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */ +/** @typedef {import('./shapes.mjs').ChatResponse} ChatResponse */ + +/** + * @param {{ baseUrl?: string, apiKey?: string, apiKeyEnv?: string }} endpoint + */ export function makeProvider(endpoint) { const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, ''); if (!base) throw new Error('server.json: endpoint.baseUrl is required'); @@ -8,6 +15,11 @@ export function makeProvider(endpoint) { const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` }; return { + /** + * @param {?string} model @param {ViewMessage[]} messages + * @param {?import('./shapes.mjs').ToolDef[]} [tools] @param {Record} [params] + * @returns {Promise} + */ async chat(model, messages, tools, params = {}) { const res = await fetch(`${base}/chat/completions`, { method: 'POST', @@ -17,16 +29,17 @@ export function makeProvider(endpoint) { if (!res.ok) { throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`); } - const data = await res.json(); + const data = /** @type {ChatResponse} */ (await res.json()); return data; }, + /** @returns {Promise} */ async models() { const res = await fetch(`${base}/models`, { headers }); if (!res.ok) { throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`); } - const data = await res.json(); + const data = /** @type {{ data: { id: string }[] }} */ (await res.json()); return (data.data ?? []).map((m) => m.id).sort(); }, }; diff --git a/server/session.mjs b/server/session.mjs index 180eccd..7401136 100644 --- a/server/session.mjs +++ b/server/session.mjs @@ -17,6 +17,13 @@ // (the last few and every ask_gm answer stay), old GM-side // / blocks elide -- the current status rides the // newest GM turn. +/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */ +/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */ +/** @typedef {import('./shapes.mjs').PendingAsk} PendingAsk */ +/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */ +/** @typedef {import('./shapes.mjs').OpeningEvent} OpeningEvent */ +/** @typedef {import('./shapes.mjs').HttpError} HttpError */ + import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -27,11 +34,16 @@ import { tailStart } from './carry.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +/** @param {string} runId */ const sessionsDir = (runId) => path.join(runDir(runId), 'sessions'); +/** @param {string} runId @param {number} n */ export const sessionDir = (runId, n) => path.join(sessionsDir(runId), String(n)); +/** @param {string} runId @param {number} n */ const logFile = (runId, n) => path.join(sessionDir(runId, n), 'log.jsonl'); +/** @param {string} runId @param {number} n */ const carryFile = (runId, n) => path.join(sessionDir(runId, n), 'carryover.jsonl'); +/** @param {string} runId @returns {number[]} */ export function listSessions(runId) { if (!fs.existsSync(sessionsDir(runId))) return []; return fs.readdirSync(sessionsDir(runId), { withFileTypes: true }) @@ -39,11 +51,13 @@ export function listSessions(runId) { .map((d) => Number(d.name)).sort((a, b) => a - b); } +/** @param {string} runId @returns {?number} */ export const latestSession = (runId) => { const ns = listSessions(runId); return ns.length ? ns[ns.length - 1] : null; }; +/** @param {string} runId @param {number} n @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }} */ export function sessionMeta(runId, n) { try { return JSON.parse(fs.readFileSync(path.join(sessionDir(runId, n), 'session.json'), 'utf8')); @@ -52,6 +66,10 @@ export function sessionMeta(runId, n) { } } +/** + * @param {string} runId @param {number} n @param {Record} patch + * @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }} + */ export function writeMeta(runId, n, patch) { const m = { ...sessionMeta(runId, n), ...patch }; fs.writeFileSync(path.join(sessionDir(runId, n), 'session.json'), JSON.stringify(m, null, 2) + '\n'); @@ -60,12 +78,17 @@ export function writeMeta(runId, n, patch) { // the run's state is its latest session's: live while one plays, // else dormant (the review window). At most one live session exists. +/** @param {string} runId @returns {?number} */ export function liveSession(runId) { return listSessions(runId).find((n) => sessionMeta(runId, n).phase === 'live') ?? null; } +/** + * @param {number} status @param {string} message @param {unknown} [detail] + * @returns {HttpError} + */ const err = (status, message, detail) => { - const e = new Error(message); + const e = /** @type {HttpError} */ (new Error(message)); e.status = status; if (detail) e.detail = detail; return e; @@ -73,6 +96,7 @@ const err = (status, message, detail) => { // --- session object ---------------------------------------------------------- +/** @param {string} runId @param {number} n @returns {LiveSession} */ function makeSession(runId, n) { return { runId, @@ -82,6 +106,7 @@ function makeSession(runId, n) { lines: [], pendingAsk: null, // { callId, question, calls } -- the whole batch pauses usage: null, // { promptTokens, completionTokens } from the last response + /** @param {LogEvent} entry */ append(entry) { this.lines.push(entry); fs.appendFileSync(this.file, JSON.stringify(entry) + '\n'); @@ -89,6 +114,7 @@ function makeSession(runId, n) { }; } +/** @param {string} file @returns {LogEvent[]} */ function readLogLines(file) { if (!fs.existsSync(file)) { throw err(404, `no session log: ${path.relative(ROOT, file)}`); @@ -105,6 +131,7 @@ function readLogLines(file) { return out; } +/** @param {string} file @param {LogEvent[]} lines */ function writeLog(file, lines) { fs.mkdirSync(path.dirname(file), { recursive: true }); const tmp = `${file}.tmp`; @@ -112,6 +139,7 @@ function writeLog(file, lines) { fs.renameSync(tmp, file); // atomic: a crash never leaves a torn log } +/** @param {string} runId @param {number} n @returns {LiveSession} */ export function loadSession(runId, n) { const s = makeSession(runId, n); s.lines = readLogLines(s.file); @@ -120,7 +148,9 @@ export function loadSession(runId, n) { } // rebuild the derived state from the log alone +/** @param {LiveSession} s */ function derive(s) { + /** @type {?PendingAsk} */ let pending = null; for (const e of s.lines) { if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) { @@ -148,7 +178,7 @@ function derive(s) { && typeof last.m.content === 'string' && /<\/?variants?>/.test(last.m.content)) { try { const v = parseVariants(last.m.content); - s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length }); + if (v) s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length }); } catch (e) { console.warn(`boot: an unresolved variant turn in session ${s.n} was left as-is: ${e.message}`); } @@ -165,6 +195,7 @@ function derive(s) { // boot resumes a half-finished stop by re-running this over the // on-disk state (the move step reconciles against what already // landed, so it never moves anything twice). +/** @param {string} runId @param {number} N */ export function stopSession(runId, N) { const dir = sessionDir(runId, N + 1); fs.mkdirSync(dir, { recursive: true }); @@ -204,6 +235,7 @@ export function stopSession(runId, N) { } // a stop that died in flight leaves its marker; boot finishes it +/** @param {string} runId @returns {?{ from: number, dir: number }} */ export function findStalledStop(runId) { for (const n of listSessions(runId)) { const p = path.join(sessionDir(runId, n), 'stop.json'); @@ -226,6 +258,7 @@ export function findStalledStop(runId) { // conversation: msg, tool, and note events, read as recorded. // Exported for the file editor's save-time check: only clean // openings land. +/** @param {LogEvent[]} lines @param {{ authored: boolean }} opts @returns {string[]} */ export function lintCarryover(lines, { authored }) { const errors = []; let openings = 0; @@ -233,7 +266,10 @@ export function lintCarryover(lines, { authored }) { const at = `line ${i + 1}`; if (authored) { if (e.t === 'msg') { - const m = e.m ?? {}; + // authored carryovers are prompt-side: anything may be + // present that shouldn't be, so m is read permissively and + // every wrong thing is named + const m = /** @type {import('./shapes.mjs').WireMessage & Record} */ (e.m ?? {}); if (m.role !== 'user' && m.role !== 'assistant') errors.push(`${at}: role must be user (the GM) or assistant (her)`); if (typeof m.content !== 'string' || !m.content.trim()) errors.push(`${at}: content must be a non-empty string`); if (m.tool_calls?.length) errors.push(`${at}: tool calls are runtime artifacts -- the opening never calls tools`); @@ -273,32 +309,37 @@ export function lintCarryover(lines, { authored }) { // freeze, exactly like every bundle file. A continuation carryover is // live prose and NEVER expands -- a literal $word typed in play would // bomb the unresolved-token check, and the words are already real. +/** @param {string} runId @param {LogEvent[]} lines @returns {LogEvent[]} */ function expandCarryover(runId, lines) { - return lines.map((e) => { + return /** @type {LogEvent[]} */ (lines.map((e) => { if (e.t === 'msg') return { ...e, m: { ...e.m, content: expandVars(runId, e.m.content) } }; if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) }; return e; - }); + })); } // an unpicked variants event gets its crypto pick at start -- the // same dice the loop rolls on reception; a pick already adjacent // (real history) is final, re-rolls do not exist +/** @param {LogEvent[]} lines @returns {LogEvent[]} */ function resolvePicks(lines) { + /** @type {LogEvent[]} */ const out = []; for (let i = 0; i < lines.length; i++) { const e = lines[i]; out.push(e); + const next = lines[i + 1]; if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string' && /<\/?variants?>/.test(e.m.content) - && !(lines[i + 1]?.t === 'note' && lines[i + 1].kind === 'pick')) { - const v = parseVariants(e.m.content); // lint already validated - out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length }); + && !(next && next.t === 'note' && next.kind === 'pick')) { + const v = parseVariants(e.m.content); // lint already validated -- never null past the tag test + if (v) out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length }); } } return out; } +/** @param {string} runId @param {number} n @returns {LogEvent[]} */ function readCarryover(runId, n) { const p = carryFile(runId, n); if (!fs.existsSync(p)) return []; @@ -315,6 +356,11 @@ function readCarryover(runId, n) { return out; } +/** + * @param {string} runId + * @param {{ override?: boolean }} [opts] + * @returns {{ session: LiveSession, autoSend: boolean }} + */ export function startSession(runId, { override = false } = {}) { requireRun(runId); const n = latestSession(runId); @@ -364,14 +410,16 @@ export function startSession(runId, { override = false } = {}) { // renders from const rr = clerkTry(runId, '--session', String(n), 'render'); if (rr.code !== 0) throw err(500, `render failed: ${(rr.err || rr.out).split('\n')[0]}`); + /** @type {{ role: 'system', content: string }} */ const system = { role: 'system', content: assembleSystem(runId, dir) }; const bundle = assembleBundle(runId, dir); const partNames = ['backdrop', 'character', 'ring-b', 'ring-a']; + /** @type {LogEvent[]} */ const lines = [ { t: 'note', kind: 'session', n }, ...(opening ? [opening] : []), { t: 'bundle', m: system, part: 'system' }, - ...bundle.map((m, i) => ({ t: 'bundle', m, part: partNames[i] })), + ...bundle.map((m, i) => /** @type {LogEvent} */ ({ t: 'bundle', m, part: partNames[i] })), ...carry, ]; // the assembled context must be sound before anything lands: @@ -394,7 +442,7 @@ export function startSession(runId, { override = false } = {}) { // the opening flow: a carryover ending on a GM turn is her cue -- // it sends automatically as the first request of the assembled // contwin; otherwise the table waits for the GM's input - const lastMsg = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder); + const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null); return { session: s, autoSend: lastMsg?.m?.role === 'user' }; } @@ -402,9 +450,17 @@ export function startSession(runId, { override = false } = {}) { const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g; +/** The renderer reads only these two of a session -- the start path + * validates its assembled context with the same policy before going + * live. */ +/** @typedef {{ lines: LogEvent[], pendingAsk: ?PendingAsk }} SessionView */ + +/** @param {SessionView} s @param {number} [keepToolResults] @returns {ViewMessage[]} */ export function renderView(s, keepToolResults = 4) { const eff = effectiveContents(s.lines); + /** @type {number[]} */ const toolIdx = []; + /** @type {number[]} */ const reminderIdx = []; let lastGmIdx = -1; s.lines.forEach((e, i) => { @@ -414,6 +470,7 @@ export function renderView(s, keepToolResults = 4) { }); const keep = new Set(toolIdx.slice(-keepToolResults)); const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1; + /** @type {ViewMessage[]} */ const msgs = []; for (const [i, e] of s.lines.entries()) { if (e.t === 'bundle') { @@ -423,26 +480,26 @@ export function renderView(s, keepToolResults = 4) { // the per-turn reminder: only the newest copy lives in the // context -- superseded ones elide (identical content, freshest // position, exactly like the status/agenda blocks) - if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() }); + if (i === newestReminder) msgs.push({ role: 'system', content: String(e.m.content ?? '').trim() }); } else if (e.m.role === 'assistant') { // thinking never goes back; the log keeps it. Variant turns // render their picked variant -- the unpicked rest never reach // a model (the log keeps them) - const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) }; + const m = /** @type {ViewMessage} */ ({ role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) }); if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls; msgs.push(m); } else if (e.conflictOnly) { // transient error traffic: visible while it is the latest word // (the model answers it), elided entirely once the story moves // on -- the log keeps it for provenance - if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() }); + if (i === lastGmIdx) msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() }); } else if (i === lastGmIdx) { // the newest GM turn keeps its blocks as-sent: the current // status and agenda ride it - msgs.push({ role: e.m.role, content: e.m.content.trim() }); + msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() }); } else { // older GM turns: status/agenda/conflict blocks elide - msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() }); + msgs.push({ role: e.m.role, content: String(e.m.content ?? '').replace(STRIP_BLOCKS, '').trim() }); } } else if (e.t === 'tool') { if (e.ask || keep.has(i)) { @@ -458,6 +515,7 @@ export function renderView(s, keepToolResults = 4) { // tool-call pairing is never broken (the endpoint tolerates orphans // silently -- probed 2026-11-12 -- so this one fails quiet unless we check) +/** @param {ViewMessage[]} msgs @param {?string|undefined} pendingCallId */ function validatePairing(msgs, pendingCallId) { const calls = new Set(); const results = new Set(); diff --git a/server/shapes.mjs b/server/shapes.mjs new file mode 100644 index 0000000..9eef3d6 --- /dev/null +++ b/server/shapes.mjs @@ -0,0 +1,108 @@ +// server/shapes.mjs -- the shared type declarations. No runtime code: +// this module exists so the tsc checker (JSDoc mode, no emit) and the +// humans reading the code agree on the load-bearing shapes. Every +// module types against these; the smoke owns their behavioral truth. +// +// The naming follows the code's own words: a log line is an event, a +// wire message is exactly what the API carried, the view is what the +// model sees on any call. +export {}; + +/** A role on the chat wire. */ +/** @typedef {'user'|'assistant'|'system'|'tool'} Role */ + +/** One function call attached to an assistant message. */ +/** @typedef {{ id: string, type: 'function', function: { name: string, arguments: string } }} ToolCall */ + +/** A tool definition on the wire: what the API receives in `tools`. */ +/** @typedef {{ type: 'function', function: { name: string, description: string, parameters: { type: string, properties: Record, required?: string[] } } }} ToolDef */ + +/** A chat message exactly as it rides the wire (OpenAI-compatible). */ +/** @typedef {{ role: Role, content: ?string, tool_calls?: ToolCall[], reasoning_content?: string }} WireMessage */ + +/** Token usage, as the provider reports it and the log records it. */ +/** @typedef {{ prompt_tokens: number, completion_tokens: number }} Usage */ + +/** msg: one recorded turn (m is exactly what the wire carried). The + * reminder and conflictOnly flags are the only server-side marks -- + * everything else about a turn lives in its content. */ +/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage }} MsgEvent */ + +/** tool: a tool result, paired to its call (pairing is a context + * invariant, checked at render). */ +/** @typedef {{ t: 'tool', m: { role: 'tool', tool_call_id: string, content: string }, ask?: boolean }} ToolEvent */ + +/** note: the machine's own annotations -- never shown to the model, + * rendered as garnish in the SPA. Historical logs carry older kind + * names from before renames; readers must not assume this union is + * exhaustive. */ +/** @typedef {{ t: 'note', kind: 'session', n: number }} SessionNote */ +/** @typedef {{ t: 'note', kind: 'ask', question: string }} AskNote */ +/** @typedef {{ t: 'note', kind: 'pick', chosen: number, count: number }} PickNote */ +/** @typedef {{ t: 'note', kind: 'status', applied: { lost: string[], gained: string[] }, conflicts?: string[] }} StatusNote */ +/** @typedef {{ t: 'note', kind: 'agenda', applied: { added: string[], dropped: string[], evicted: string[] }, conflicts?: string[] }} AgendaNote */ +/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote} NoteEvent */ + +/** bundle: one frozen prompt part (system, backdrop, character, rings). */ +/** @typedef {{ t: 'bundle', m: { role: 'user'|'system', content: string }, part: string }} BundleEvent */ + +/** opening: her opening status -- authored carryovers only, at most one. */ +/** @typedef {{ t: 'opening', status: string[] }} OpeningEvent */ + +/** Any line of a session log or carryover, in either direction. */ +/** @typedef {MsgEvent|ToolEvent|NoteEvent|BundleEvent|OpeningEvent} LogEvent */ + +/** The pending ask, held on the session object while a turn waits. */ +/** @typedef {{ callId: string, question: string, calls: ToolCall[] }} PendingAsk */ + +/** A live session: the log in memory, its derived state, the appender. + * The log is the truth; everything on this object is rebuilt from it. */ +/** @typedef {{ runId: string, n: number, stamp: string, file: string, lines: LogEvent[], pendingAsk: ?PendingAsk, usage: ?{ promptTokens: number, completionTokens: number }, append: (entry: LogEvent) => void }} LiveSession */ + +/** run.json: lineage, ownership, per-run model overrides. */ +/** @typedef {{ package: string, created: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string } }} RunMeta */ + +/** settings.json: identity (pc/name are the @ sigils), declared vars, + * the records flag. */ +/** @typedef {{ pc?: string, name?: string, records?: boolean, vars?: Record }} RunSettings */ + +/** A housekeeping manifest -- the housekeeper's whole write surface. */ +/** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */ +/** @typedef {{ id: string, reason: string }} RefOp */ +/** @typedef {{ id: string, detail: string, reason?: string }} RewordOp */ +/** @typedef {{ type: string, label: string, detail: string }} RecordOp */ +/** @typedef {{ session: string, summary: string, insert?: InsertOp[], touch?: RefOp[], promote?: RefOp[], demote?: RefOp[], reword?: RewordOp[], delete?: RefOp[], archive?: RefOp[], record?: RecordOp[], inventions?: string[], open_questions?: string[] }} Manifest */ + +/** The housekeeping job state (GET /housekeeping). */ +/** @typedef {{ state: 'idle'|'running'|'applied'|'pending'|'rejected', phase?: 'stop'|'rerun', session?: number, target?: number, started?: string, stopped?: boolean, manifest?: string, reason?: string }} JobState */ + +/** The clerk boundary's result: exit code plus separated streams. */ +/** @typedef {{ code: number, out: string, err: string }} ClerkResult */ + +/** One message of the rendered per-call view -- what the model sees. */ +/** @typedef {{ role: Role, content: ?string, tool_calls?: ToolCall[], tool_call_id?: string }} ViewMessage */ + +/** A chat completion response (OpenAI-compatible). */ +/** @typedef {{ choices: { message: WireMessage }[], usage?: Usage }} ChatResponse */ + +/** An Error carrying an HTTP status (and optional detail payload) -- + * the server's only error shape. */ +/** @typedef {Error & { status?: number, detail?: unknown }} HttpError */ + +/** The acting user, as the auth spine resolves a bearer token. */ +/** @typedef {{ id: string, name: string, superuser: boolean }} User */ + +/** The acting user as the loops and jobs log it: attribution needs + * only the id (users.mjs's row, with its numeric superuser flag, + * flows in fine). */ +/** @typedef {{ id: string }} Actor */ + +/** The provider client (provider.mjs's own return type). */ +/** @typedef {ReturnType} Provider */ + +/** server.json as parsed. */ +/** @typedef {{ bind?: string, port?: number, endpoint?: { baseUrl?: string, apiKey?: string, apiKeyEnv?: string }, models: { player?: ?string, housekeeper?: ?string }, contwin?: number, contextWindow?: number, params?: Record }} ServerCfg */ + +/** The server context: the one object threaded through every module. + * locks/enqueue are the per-run activity lock (main.mjs). */ +/** @typedef {{ mock: boolean, cfg: ServerCfg, provider: Provider, sessions: Map, jobs: Map, runMeta: (runId: string) => ?RunMeta, locks: Map>, enqueue: (runId: string, fn: () => Promise) => Promise }} Ctx */ diff --git a/server/users.mjs b/server/users.mjs index cc9c5aa..4d4c229 100644 --- a/server/users.mjs +++ b/server/users.mjs @@ -12,6 +12,13 @@ // // All times are UTC (house rule). Never model-facing: nothing here // ever enters a bundle or a prompt. +/** @typedef {import('./shapes.mjs').User} User */ +/** A users table row (token hashes never leave this module). */ +/** @typedef {{ id: string, token_hash: string, name: string, superuser: number, created: string }} UserRow */ +/** An invites table row. */ +/** @typedef {{ id: number, code_hash: string, kind: 'invite'|'bootstrap', created_by: string, created_at: string, claimed_by: ?string, claimed_at: ?string }} InviteRow */ +/** @typedef {{ id: number, kind: 'invite'|'bootstrap', created_by: string, created_at: string, claimed_by: ?string, claimed_at: ?string }} InviteListed */ + import { DatabaseSync } from 'node:sqlite'; import { createHash, randomBytes } from 'node:crypto'; import fs from 'node:fs'; @@ -47,48 +54,58 @@ const db = new DatabaseSync(DB_PATH); db.exec(SCHEMA); const now = () => new Date().toISOString(); +/** @param {string} s @returns {string} */ const sha = (s) => createHash('sha256').update(String(s)).digest('hex'); +/** @param {number} n @returns {string} */ const hex = (n) => randomBytes(n).toString('hex'); // --- users --------------------------------------------------------------------- +/** @returns {number} */ export function userCount() { - return db.prepare('SELECT COUNT(*) AS n FROM users').get().n; + return Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0); } // does this identity exist? A revoked user's id resolves to absent -- // dead ids are ownerless by resolution, never by rewriting history +/** @param {?string} uid @returns {boolean} */ export function exists(uid) { if (uid == null) return false; return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid); } +/** @param {?string} token @returns {?UserRow} */ export function getUserByToken(token) { const t = String(token ?? '').trim(); if (!t) return null; - const row = db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t)); + const row = /** @type {?UserRow} */ (db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t))); return row ?? null; } +/** @param {?string|undefined} uid @returns {?string} */ export function userName(uid) { if (uid == null) return null; const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid); - return row ? row.name : null; + return row ? String(row.name) : null; } +/** @returns {User[]} */ export function listUsers() { - return db.prepare('SELECT id, name, superuser, created FROM users ORDER BY created').all() - .map((u) => ({ ...u, superuser: u.superuser === 1 })); + return /** @type {{ id: string, name: string, superuser: number, created: string }[]} */ ( + db.prepare('SELECT id, name, superuser, created FROM users ORDER BY created').all() + ).map((u) => ({ ...u, superuser: u.superuser === 1 })); } // revocation destroys the identity: no suspend, no restore. Their runs // and packages stay -- ownerless, readable, forkable. +/** @param {string} id @returns {boolean} */ export function revokeUser(id) { return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0; } // --- invites --------------------------------------------------------------------- +/** @param {string} byUid @param {'invite'|'bootstrap'} [kind] @returns {{ id: number, code: string }} */ export function mintInvite(byUid, kind = 'invite') { const code = hex(12); // 24 hex chars -- shown once, stored hashed const res = db.prepare( @@ -97,26 +114,30 @@ export function mintInvite(byUid, kind = 'invite') { return { id: Number(res.lastInsertRowid), code }; } +/** @returns {InviteListed[]} */ export function listInvites() { - return db.prepare( + return /** @type {InviteListed[]} */ (db.prepare( 'SELECT id, kind, created_by, created_at, claimed_by, claimed_at FROM invites ORDER BY id' - ).all(); + ).all()); } // only unclaimed invites can be revoked; spent ones are a permanent record +/** @param {number} id @returns {boolean} */ export function revokeInvite(id) { return db.prepare('DELETE FROM invites WHERE id = ? AND claimed_by IS NULL').run(id).changes > 0; } // exchange a single-use invite code for a persistent token. Unknown, // spent, and dead-bootstrap codes are each named explicitly. +/** @param {?string} code @param {?string} name @returns {{ token: string, user: User }} */ export function claimInvite(code, name) { const c = String(code ?? '').trim(); const n = String(name ?? '').trim(); - const fail = (msg) => { const e = new Error(msg); e.status = 400; throw e; }; + /** @param {string} msg @returns {never} */ + const fail = (msg) => { const e = /** @type {import('./shapes.mjs').HttpError} */ (new Error(msg)); e.status = 400; throw e; }; if (!c) fail('the invite code is required'); if (!n) fail('a display name is required'); - const row = db.prepare('SELECT * FROM invites WHERE code_hash = ?').get(sha(c)); + const row = /** @type {?InviteRow} */ (db.prepare('SELECT * FROM invites WHERE code_hash = ?').get(sha(c))); if (!row) fail('unknown invite code'); if (row.claimed_by != null) fail('this invite was already used -- ask for a fresh one'); if (row.kind === 'bootstrap' && userCount() > 0) { @@ -147,6 +168,7 @@ export function claimInvite(code, name) { // never generated again once any user exists; rejected at claim time // if somehow presented after that. +/** @returns {?{ reused?: boolean, code?: string }} */ export function bootstrap() { if (userCount() > 0) return null; const open = db.prepare("SELECT id FROM invites WHERE kind = 'bootstrap' AND claimed_by IS NULL").get(); diff --git a/server/variants.mjs b/server/variants.mjs index 882195d..95faa22 100644 --- a/server/variants.mjs +++ b/server/variants.mjs @@ -15,9 +15,14 @@ // pairing violations). import { randomInt } from 'node:crypto'; +/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */ + const ANY_TAG = /<\/?variants?>/; // matches , , and both closers -// null = no variants syntax at all (a plain turn); throws on malformed +/** The parsed candidates of one variants block. + * @typedef {{ variants: string[] }} Variants */ + +/** @param {?string} text @returns {?Variants} null = no variants syntax at all (a plain turn); throws on malformed */ export function parseVariants(text) { const t = String(text ?? ''); if (!ANY_TAG.test(t)) return null; @@ -35,6 +40,7 @@ export function parseVariants(text) { } // the dice: uniform, server-side, unwatchable by the model +/** @param {number} count @returns {number} */ export const pickVariant = (count) => randomInt(count); // The effective-content map: what each assistant message "really @@ -42,6 +48,7 @@ export const pickVariant = (count) => randomInt(count); // note renders the chosen variant; a message still mid-turn (a tool // call carrying draft variants) renders the block stripped -- the // candidates are her live draft until a pick resolves them. +/** @param {LogEvent[]} lines @returns {Map} */ export function effectiveContents(lines) { const eff = new Map(); for (let i = 0; i < lines.length; i++) { diff --git a/test/check-repo.mjs b/test/check-repo.mjs index 839e3cb..b936f4c 100644 --- a/test/check-repo.mjs +++ b/test/check-repo.mjs @@ -23,8 +23,10 @@ // context window), turn-0, seed (memory.json is the name). // Historical records keep the vocabulary of // their day; gm.md is GM-private, flagged never fixed. -// 5. Zero-dependency stack (GM, 2026-11-13): every import is -// node: builtin or relative. No package manager, ever. +// 5. Zero-dependency runtime (GM, 2026-11-13, amended 2026-11-15): +// every import is node: builtin or relative -- no runtime deps, +// no package-manager requirement to run. Dev tooling is exempt +// (typescript rides devDependencies; nothing imports it). // 6. UTC discipline (GM, 2026-11-14): no locale- or timezone- // dependent date formatting in code. No time zones, ever. // 7. web/ static files never start with "api" -- the server's route diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0012a9b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noEmit": true, + "strict": true, + "useUnknownInCatchVariables": false, + "target": "ES2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "lib": ["ES2022"], + "types": ["node"] + }, + "include": ["server/**/*.mjs"] +}