jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
runs/
|
runs/
|
||||||
state/
|
state/
|
||||||
server.json
|
server.json
|
||||||
|
node_modules/
|
||||||
|
|||||||
@@ -83,14 +83,24 @@ memory the agent owes itself across sessions.
|
|||||||
- The repo lives at `C:\data\opencode\tiny-worlds` (renamed from
|
- The repo lives at `C:\data\opencode\tiny-worlds` (renamed from
|
||||||
`rp-test` with the project name, 2026-11-15). The rename could not
|
`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
|
happen in place -- the running app held the old dir -- so the move
|
||||||
was robocopy + session repoint; `C:\data\opencode\rp-test` is a
|
was robocopy + session repoint, plus a one-time sqlite edit of
|
||||||
frozen snapshot awaiting deletion (its MOVED.txt says so). Always
|
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.
|
launch from the new path.
|
||||||
- The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running
|
- The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running
|
||||||
`--mock` server, prints its run ids, and leaves a temp token file
|
`--mock` server, prints its run ids, and leaves a temp token file
|
||||||
for `restart-check.mjs`; `check-reminder.mjs` takes a run id;
|
for `restart-check.mjs`; `check-reminder.mjs` takes a run id;
|
||||||
`check-repo.mjs` needs no server. Clean up state/ and the smoke
|
`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
|
## State pointers
|
||||||
|
|
||||||
@@ -120,7 +130,9 @@ memory the agent owes itself across sessions.
|
|||||||
- Substrate design round complete (2026-11-13); rulings live in ROADMAP
|
- Substrate design round complete (2026-11-13); rulings live in ROADMAP
|
||||||
("The harness") and HANDOFF. Bridge retired before ever going live;
|
("The harness") and HANDOFF. Bridge retired before ever going live;
|
||||||
REST + SPA is the MVP; runs are per-deployment instances copied from
|
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
|
- Build order: ALL FOUR PHASES DONE (2026-11-13/14) -- clerk paper
|
||||||
migration, preset/run split, prompt split, server, housekeeping
|
migration, preset/run split, prompt split, server, housekeeping
|
||||||
job, SPA. The MVP substrate is complete and live-proven end to end
|
job, SPA. The MVP substrate is complete and live-proven end to end
|
||||||
|
|||||||
+33
-4
@@ -9,7 +9,20 @@ file is the "where did we leave off" map.
|
|||||||
|
|
||||||
## Where we are
|
## 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
|
2026-11-15).** The full scope, each round mock-proven end to end
|
||||||
and live-proven where live could reach: the MVP substrate (clerk,
|
and live-proven where live could reach: the MVP substrate (clerk,
|
||||||
server, housekeeping job, SPA), multiuser (token identity, invites,
|
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
|
round (/story, /table, the slidwin carry), the dormant-session
|
||||||
rework (the universal session lifecycle, move-at-stop, the start
|
rework (the universal session lifecycle, move-at-stop, the start
|
||||||
lint, rebaseable housekeeping, carryover.jsonl + memory.json
|
lint, rebaseable housekeeping, carryover.jsonl + memory.json
|
||||||
packages), and the format house rules (nine-rule check-repo). The
|
packages), the format house rules (nine-rule check-repo), and the
|
||||||
design record lives in README / DICTIONARY / ROADMAP; the build
|
naming round. The design record lives in README / DICTIONARY /
|
||||||
history in the git log.
|
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
|
- **The first real story is live: "La Caramba / Irene"** (run
|
||||||
4f261452, gitignored state). Session one open, 53 GM + 53 player
|
4f261452, gitignored state). Session one open, 53 GM + 53 player
|
||||||
story turns, ~23K prompt tokens -- single-digit percent of the
|
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
|
candidates), coin-flip personality (choices offloaded to chance
|
||||||
that should be character), and whether her variants stay same-turn
|
that should be character), and whether her variants stay same-turn
|
||||||
alternatives rather than sequences.
|
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)
|
## Not yet exercised (expect first-use friction)
|
||||||
|
|
||||||
|
|||||||
+10
-8
@@ -7,14 +7,11 @@ a tier.
|
|||||||
|
|
||||||
## Operator's queue (don't edit, don't work on)
|
## Operator's queue (don't edit, don't work on)
|
||||||
|
|
||||||
- name the project. Tiny Worlds?
|
|
||||||
- jsdoc
|
|
||||||
- debug mode skipping the invite
|
- debug mode skipping the invite
|
||||||
- explain "one thing of thinking" in reminder
|
- explain "one thing of thinking" in reminder
|
||||||
- calibration package: escape room
|
- calibration package: escape room
|
||||||
- user manual
|
- user manual
|
||||||
- remove spectator mode, make all story views public and forkable
|
- remove spectator mode, make all story views public and forkable
|
||||||
- fork should copy the entire run
|
|
||||||
- add raw sessions view to the table
|
- add raw sessions view to the table
|
||||||
- git remote; no PII anywhere in repo or git history
|
- git remote; no PII anywhere in repo or git history
|
||||||
|
|
||||||
@@ -45,11 +42,16 @@ run again.
|
|||||||
|
|
||||||
## The substrate (REST + SPA)
|
## The substrate (REST + SPA)
|
||||||
|
|
||||||
### 4. Stack -- RESOLVED (2026-11-13)
|
### 4. Stack -- RESOLVED (2026-11-13), AMENDED (2026-11-15)
|
||||||
Zero-dependency, ruled by GM: `node:http` with a hand-rolled router, a
|
Zero-dependency runtime, ruled by GM: `node:http` with a hand-rolled
|
||||||
no-build vanilla ES-module SPA, no `package.json` -- the repo ethos
|
router, a no-build vanilla ES-module SPA. If a need ever demands a
|
||||||
carried through. If a need ever demands a dependency, it makes its case
|
runtime dependency, it makes its case then. Amendment (2026-11-15):
|
||||||
then.
|
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)
|
### 5. ask_gm mid-loop resumption -- RESOLVED (2026-11-12)
|
||||||
Pause/resume, no streaming: the turn request returns with the pending
|
Pause/resume, no streaming: the turn request returns with the pending
|
||||||
|
|||||||
@@ -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,
|
AGENTS.md the agent's own working notes -- style lessons, gotchas,
|
||||||
state pointers
|
state pointers
|
||||||
config.json the default package
|
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
|
names-female.txt the name dictionary -- one name per line; the new-run
|
||||||
form rolls an unused one for the main character
|
form rolls an unused one for the main character
|
||||||
tool/
|
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
|
fork.mjs fork: the staged atomic copy with the owner replaced
|
||||||
and the `forked` stamp
|
and the `forked` stamp
|
||||||
clerk.mjs the clerk boundary (every state op via memory.mjs)
|
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
|
housekeeping.mjs the pass as an async job: one trigger, two
|
||||||
behaviors -- stop (close, move the tail, freeze,
|
behaviors -- stop (close, move the tail, freeze,
|
||||||
then the pass) and the re-run (rebase + fresh
|
then the pass) and the re-run (rebase + fresh
|
||||||
|
|||||||
+7
-5
@@ -171,11 +171,13 @@ example, gitignored real file, env-var option).
|
|||||||
per-user seam.
|
per-user seam.
|
||||||
- **Boutique is dormant** -- a stub that never reached its design step;
|
- **Boutique is dormant** -- a stub that never reached its design step;
|
||||||
untouched until its drafting session.
|
untouched until its drafting session.
|
||||||
- **Stack: zero-dependency** (QUESTIONS #4 resolved). `node:http` with
|
- **Stack: zero-dependency runtime** (QUESTIONS #4, amended
|
||||||
a hand-rolled router, no-build vanilla ES-module SPA, no
|
2026-11-15). `node:http` with a hand-rolled router, no-build
|
||||||
`package.json`. The hard parts of this project are prompt-side and
|
vanilla ES-module SPA; clone-and-run with node alone. Dev tooling
|
||||||
clerk-side; the web side at loopback single-user scale is the easy
|
is exempt: `typescript` + `@types/node` type-check the JSDoc
|
||||||
part.
|
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)
|
## The multiuser server (2026-11-14, GM)
|
||||||
|
|
||||||
|
|||||||
Generated
+45
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
-7
@@ -11,6 +11,11 @@
|
|||||||
//
|
//
|
||||||
// The tool list is the capability surface: ask_gm always, records
|
// The tool list is the capability surface: ask_gm always, records
|
||||||
// verbs only when the run's settings allow.
|
// 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 fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
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 ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const RUNS_DIR = path.join(ROOT, 'runs');
|
const RUNS_DIR = path.join(ROOT, 'runs');
|
||||||
|
|
||||||
|
/** @param {string} runId */
|
||||||
export const runDir = (runId) => path.join(RUNS_DIR, runId);
|
export const runDir = (runId) => path.join(RUNS_DIR, runId);
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {?RunMeta} */
|
||||||
export const runMeta = (runId) => {
|
export const runMeta = (runId) => {
|
||||||
try {
|
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 {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {string} */
|
||||||
export function requireRun(runId) {
|
export function requireRun(runId) {
|
||||||
if (!/^[a-z0-9-]+$/.test(runId ?? '') || !fs.existsSync(path.join(runDir(runId), 'run.json'))) {
|
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;
|
err.status = 404;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
return runDir(runId);
|
return runDir(runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {RunSettings} */
|
||||||
export function readSettings(runId) {
|
export function readSettings(runId) {
|
||||||
try {
|
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 {
|
} catch {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -54,14 +65,15 @@ export function readSettings(runId) {
|
|||||||
// in a prompt surfaces as an input in setup, and the run's settings
|
// in a prompt surfaces as an input in setup, and the run's settings
|
||||||
// "vars" holds the answers (a package may ship defaults); an
|
// "vars" holds the answers (a package may ship defaults); an
|
||||||
// unresolved $TOKEN fails loudly -- the model never sees a raw var.
|
// unresolved $TOKEN fails loudly -- the model never sees a raw var.
|
||||||
|
/** @param {string} runId @param {?string} s @returns {string} */
|
||||||
function expandVars(runId, s) {
|
function expandVars(runId, s) {
|
||||||
const settings = readSettings(runId);
|
const settings = readSettings(runId);
|
||||||
let out = String(s ?? '');
|
let out = String(s ?? '');
|
||||||
const sigils = { PC: settings.pc, Package: settings.name };
|
const sigils = { PC: settings.pc, Package: settings.name };
|
||||||
out = out.replace(/@(PC|Package)\b/g, (full, 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()) {
|
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;
|
err.status = 500;
|
||||||
throw err;
|
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));
|
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]}`))];
|
const unresolved = [...new Set([...out.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)].map((m) => `$${m[1]}`))];
|
||||||
if (unresolved.length) {
|
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;
|
err.status = 500;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -80,15 +92,17 @@ export { expandVars };
|
|||||||
|
|
||||||
// "La Caramba / Rell" -- the run's display name; the anonymous id
|
// "La Caramba / Rell" -- the run's display name; the anonymous id
|
||||||
// never surfaces as a name
|
// never surfaces as a name
|
||||||
|
/** @param {string} runId @returns {string} */
|
||||||
export function runDisplay(runId) {
|
export function runDisplay(runId) {
|
||||||
const s = readSettings(runId);
|
const s = readSettings(runId);
|
||||||
const pkg = runMeta(runId)?.package ?? '?';
|
const pkg = runMeta(runId)?.package ?? '?';
|
||||||
return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg);
|
return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} p @returns {string} */
|
||||||
const read = (p) => {
|
const read = (p) => {
|
||||||
if (!fs.existsSync(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;
|
err.status = 500;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -97,6 +111,7 @@ const read = (p) => {
|
|||||||
|
|
||||||
// the system message: opening + guards (repo), substrate (repo), craft
|
// the system message: opening + guards (repo), substrate (repo), craft
|
||||||
// (the session's frozen handbook copy)
|
// (the session's frozen handbook copy)
|
||||||
|
/** @param {string} runId @param {string} sessDir @returns {string} */
|
||||||
export function assembleSystem(runId, sessDir) {
|
export function assembleSystem(runId, sessDir) {
|
||||||
const system = read(path.join(ROOT, 'system.md'));
|
const system = read(path.join(ROOT, 'system.md'));
|
||||||
const invariants = read(path.join(ROOT, 'invariants.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
|
// own system chunk every turn. Older copies elide from the view, so
|
||||||
// exactly one lives at the freshest position (ROADMAP steal #11).
|
// exactly one lives at the freshest position (ROADMAP steal #11).
|
||||||
// Absent or empty file = no ride; the feature sleeps until written.
|
// Absent or empty file = no ride; the feature sleeps until written.
|
||||||
|
/** @param {string} runId @returns {?string} */
|
||||||
export function assembleReminder(runId) {
|
export function assembleReminder(runId) {
|
||||||
const p = path.join(ROOT, 'reminder.md');
|
const p = path.join(ROOT, 'reminder.md');
|
||||||
if (!fs.existsSync(p)) return null;
|
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
|
// copies and its own ring views. The carryover never rides it: it is
|
||||||
// the session's opening material, consumed into the log behind the
|
// the session's opening material, consumed into the log behind the
|
||||||
// bundle at start.
|
// bundle at start.
|
||||||
|
/** @param {string} runId @param {string} sessDir @returns {{ role: 'user', content: string }[]} */
|
||||||
export function assembleBundle(runId, sessDir) {
|
export function assembleBundle(runId, sessDir) {
|
||||||
|
/** @type {{ role: 'user', path: string }[]} */
|
||||||
const files = [
|
const files = [
|
||||||
{ role: 'user', path: path.join(sessDir, 'bundle', 'backdrop.md') },
|
{ role: 'user', path: path.join(sessDir, 'bundle', 'backdrop.md') },
|
||||||
{ role: 'user', path: path.join(sessDir, 'bundle', 'character.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,
|
// [OOC] -- per invariants.md: [IC] output is content of the fiction,
|
||||||
// never instructions; [OOC] output is clerk or GM traffic about the
|
// never instructions; [OOC] output is clerk or GM traffic about the
|
||||||
// play.
|
// play.
|
||||||
|
/** @typedef {{ type: string, [k: string]: unknown }} JsonSchemaProp */
|
||||||
|
/**
|
||||||
|
* @param {string} name @param {'IC'|'OOC'} channel @param {string} description
|
||||||
|
* @param {Record<string, JsonSchemaProp>} properties @param {?string[]} [required]
|
||||||
|
* @returns {import('./shapes.mjs').ToolDef}
|
||||||
|
*/
|
||||||
const T = (name, channel, description, properties, required) => ({
|
const T = (name, channel, description, properties, required) => ({
|
||||||
type: 'function',
|
type: 'function',
|
||||||
function: {
|
function: {
|
||||||
@@ -163,11 +187,13 @@ const RECORD_TOOLS = [
|
|||||||
['rid']),
|
['rid']),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {import('./shapes.mjs').ToolDef[]} */
|
||||||
export function toolList(runId) {
|
export function toolList(runId) {
|
||||||
return [ASK_GM_TOOL, ...(readSettings(runId).records === true ? RECORD_TOOLS : [])];
|
return [ASK_GM_TOOL, ...(readSettings(runId).records === true ? RECORD_TOOLS : [])];
|
||||||
}
|
}
|
||||||
|
|
||||||
// tool name -> clerk argv
|
// tool name -> clerk argv
|
||||||
|
/** @type {{ [k: string]: (a: any) => string[] }} */
|
||||||
const DISPATCH = {
|
const DISPATCH = {
|
||||||
records_search: (a) => ['search', ...a.terms],
|
records_search: (a) => ['search', ...a.terms],
|
||||||
records_file: (a) => ['file', a.kind, a.label, a.detail ?? ''],
|
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] : [])],
|
records_discard: (a) => ['discard', a.rid, ...(a.reason ? [a.reason] : [])],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** @param {string} runId @param {ToolCall} call @returns {string} */
|
||||||
export function runTool(runId, call) {
|
export function runTool(runId, call) {
|
||||||
const fn = DISPATCH[call.function.name];
|
const fn = DISPATCH[call.function.name];
|
||||||
if (!fn) return `error: no such tool: ${call.function.name}`;
|
if (!fn) return `error: no such tool: ${call.function.name}`;
|
||||||
|
|||||||
@@ -19,6 +19,8 @@
|
|||||||
|
|
||||||
import { effectiveContents } from './variants.mjs';
|
import { effectiveContents } from './variants.mjs';
|
||||||
|
|
||||||
|
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
|
||||||
|
|
||||||
// ~10% of a 256K-class contwin in token terms, grounded on Irene's
|
// ~10% of a 256K-class contwin in token terms, grounded on Irene's
|
||||||
// session (84KB of turn content at ~23K prompt tokens). Substrate
|
// session (84KB of turn content at ~23K prompt tokens). Substrate
|
||||||
// policy, not deployment taste: a constant, not config.
|
// 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;
|
const STRIP_BLOCKS = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
|
||||||
|
|
||||||
// the prose the model will see for one log line in the new contwin
|
// the prose the model will see for one log line in the new contwin
|
||||||
|
/** @param {LogEvent[]} lines @param {Map<number, string>} eff @param {number} i @returns {number} */
|
||||||
function visibleBytes(lines, eff, i) {
|
function visibleBytes(lines, eff, i) {
|
||||||
const e = lines[i];
|
const e = lines[i];
|
||||||
if (e.t === 'msg') {
|
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
|
// instead of leaving her cue behind in the dead log. When nothing
|
||||||
// fits (the degenerate empty tail) it stays behind and files
|
// fits (the degenerate empty tail) it stays behind and files
|
||||||
// normally.
|
// normally.
|
||||||
|
/** @param {LogEvent[]} lines @returns {number} */
|
||||||
export function tailStart(lines) {
|
export function tailStart(lines) {
|
||||||
const eff = effectiveContents(lines);
|
const eff = effectiveContents(lines);
|
||||||
const exchanges = [];
|
const exchanges = [];
|
||||||
|
|||||||
+13
-2
@@ -1,6 +1,9 @@
|
|||||||
// server/clerk.mjs -- the clerk boundary. Every state operation goes
|
// server/clerk.mjs -- the clerk boundary. Every state operation goes
|
||||||
// through the memory.mjs CLI; the server never touches the database
|
// through the memory.mjs CLI; the server never touches the database
|
||||||
// directly. The clerk stays the one truth.
|
// 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 { spawnSync } from 'node:child_process';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
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 ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const CLERK = path.join(ROOT, 'tool', 'memory.mjs');
|
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) {
|
export function clerk(runId, ...args) {
|
||||||
const res = spawnSync(process.execPath, [CLERK, '--run', runId, '--quiet', ...args], { encoding: 'utf8' });
|
const res = spawnSync(process.execPath, [CLERK, '--run', runId, '--quiet', ...args], { encoding: 'utf8' });
|
||||||
return {
|
return {
|
||||||
code: res.status,
|
code: res.status ?? 1, // null only on a signal kill; callers only ever test against 0
|
||||||
out: (res.stdout || '').trim(),
|
out: (res.stdout || '').trim(),
|
||||||
err: (res.stderr || '').split('\n')
|
err: (res.stderr || '').split('\n')
|
||||||
.filter((l) => !l.includes('ExperimentalWarning') && !l.includes('trace-warnings'))
|
.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) {
|
export function clerkJson(runId, ...args) {
|
||||||
const r = clerk(runId, ...args);
|
const r = clerk(runId, ...args);
|
||||||
if (r.code !== 0) throw new Error(r.err || r.out || `clerk ${args[0]} failed`);
|
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)
|
// 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) {
|
export function clerkTry(runId, ...args) {
|
||||||
return clerk(runId, ...args);
|
return clerk(runId, ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// commands that address no run (packages, runs, create)
|
// commands that address no run (packages, runs, create)
|
||||||
|
/** @param {...string} args @returns {ClerkResult} */
|
||||||
export function clerkRaw(...args) {
|
export function clerkRaw(...args) {
|
||||||
const res = spawnSync(process.execPath, [CLERK, ...args], { encoding: 'utf8' });
|
const res = spawnSync(process.execPath, [CLERK, ...args], { encoding: 'utf8' });
|
||||||
return {
|
return {
|
||||||
code: res.status,
|
code: res.status ?? 1, // null only on a signal kill; callers only ever test against 0
|
||||||
out: (res.stdout || '').trim(),
|
out: (res.stdout || '').trim(),
|
||||||
err: (res.stderr || '').split('\n')
|
err: (res.stderr || '').split('\n')
|
||||||
.filter((l) => !l.includes('ExperimentalWarning') && !l.includes('trace-warnings'))
|
.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)
|
// machine output for run-less commands (packages, runs)
|
||||||
|
/** @template T @param {...string} args @returns {T} */
|
||||||
export function clerkRawJson(...args) {
|
export function clerkRawJson(...args) {
|
||||||
const r = clerkRaw('--json', ...args);
|
const r = clerkRaw('--json', ...args);
|
||||||
if (r.code !== 0) throw new Error(r.err || r.out || `clerk ${args[0]} failed`);
|
if (r.code !== 0) throw new Error(r.err || r.out || `clerk ${args[0]} failed`);
|
||||||
|
|||||||
@@ -16,9 +16,16 @@ import { fileURLToPath } from 'node:url';
|
|||||||
import { requireRun } from './bundle.mjs';
|
import { requireRun } from './bundle.mjs';
|
||||||
import { liveSession, loadSession } from './session.mjs';
|
import { liveSession, loadSession } from './session.mjs';
|
||||||
|
|
||||||
|
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
|
||||||
|
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const RUNS_DIR = path.join(ROOT, 'runs');
|
const RUNS_DIR = path.join(ROOT, 'runs');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{ sessions: Map<string, LiveSession> }} ctx
|
||||||
|
* @param {string} srcId @param {{ id: string }} user
|
||||||
|
* @returns {{ run: string }}
|
||||||
|
*/
|
||||||
export function forkRun(ctx, srcId, user) {
|
export function forkRun(ctx, srcId, user) {
|
||||||
requireRun(srcId);
|
requireRun(srcId);
|
||||||
let id;
|
let id;
|
||||||
|
|||||||
+33
-6
@@ -18,6 +18,12 @@
|
|||||||
// rejection at any step holds the state and surfaces why; the
|
// rejection at any step holds the state and surfaces why; the
|
||||||
// manifest (or the raw output, if unparseable) stays on disk for a
|
// manifest (or the raw output, if unparseable) stays on disk for a
|
||||||
// hand edit and POST .../housekeeping/apply.
|
// 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 fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -31,6 +37,7 @@ import { HttpError } from './loop.mjs';
|
|||||||
|
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
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();
|
const readAt = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').trim();
|
||||||
|
|
||||||
// --- transcript --------------------------------------------------------------
|
// --- 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
|
// branches never happened, and must never enter memory. The log is
|
||||||
// read as it was left -- stop already truncated it at the slidwin
|
// read as it was left -- stop already truncated it at the slidwin
|
||||||
// boundary, so the rings never overlap the carried prose.
|
// boundary, so the rings never overlap the carried prose.
|
||||||
|
/** @param {LogEvent[]} lines @returns {string} */
|
||||||
export function renderTranscript(lines) {
|
export function renderTranscript(lines) {
|
||||||
const eff = effectiveContents(lines);
|
const eff = effectiveContents(lines);
|
||||||
const L = [];
|
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' && e.reminder) continue; // identical every turn -- context, not exchange
|
||||||
if (e.t === 'msg') {
|
if (e.t === 'msg') {
|
||||||
if (e.m.role === 'user' && e.conflictOnly) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
if (e.m.role === 'user') {
|
if (e.m.role === 'user') {
|
||||||
@@ -89,6 +97,7 @@ export function renderTranscript(lines) {
|
|||||||
// the housekeeper's fresh context; run state rides alongside the
|
// the housekeeper's fresh context; run state rides alongside the
|
||||||
// prompt. The card, backdrop and rings are the FINISHED session's
|
// prompt. The card, backdrop and rings are the FINISHED session's
|
||||||
// own frozen material -- exactly what it played with.
|
// 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) {
|
export function buildMessages(runId, n, lines) {
|
||||||
const dir = sessionDir(runId, n);
|
const dir = sessionDir(runId, n);
|
||||||
const settings = readSettings(runId);
|
const settings = readSettings(runId);
|
||||||
@@ -109,6 +118,7 @@ export function buildMessages(runId, n, lines) {
|
|||||||
// --- the manifest ------------------------------------------------------------
|
// --- the manifest ------------------------------------------------------------
|
||||||
|
|
||||||
// the housekeeper emits one JSON manifest; tolerate fences and prose
|
// the housekeeper emits one JSON manifest; tolerate fences and prose
|
||||||
|
/** @param {?string} text @returns {Manifest} */
|
||||||
export function parseManifest(text) {
|
export function parseManifest(text) {
|
||||||
const fences = [...String(text ?? '').matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]);
|
const fences = [...String(text ?? '').matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]);
|
||||||
for (const c of [...fences, String(text ?? '')]) {
|
for (const c of [...fences, String(text ?? '')]) {
|
||||||
@@ -125,6 +135,10 @@ export function parseManifest(text) {
|
|||||||
|
|
||||||
// --- the job -----------------------------------------------------------------
|
// --- the job -----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Ctx} ctx @param {string} runId @param {?Actor} user
|
||||||
|
* @returns {JobState}
|
||||||
|
*/
|
||||||
export function trigger(ctx, runId, user) {
|
export function trigger(ctx, runId, user) {
|
||||||
requireRun(runId);
|
requireRun(runId);
|
||||||
const live = ctx.sessions.get(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.
|
// 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');
|
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
|
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.jobs.set(runId, job);
|
||||||
ctx.enqueue(runId, () => runStop(ctx, runId, live.n, user));
|
ctx.enqueue(runId, () => runStop(ctx, runId, live.n, user));
|
||||||
return job;
|
return job;
|
||||||
@@ -148,14 +162,15 @@ export function trigger(ctx, runId, user) {
|
|||||||
if (latest === 1) {
|
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');
|
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.jobs.set(runId, job);
|
||||||
ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user));
|
ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user));
|
||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise<void>} */
|
||||||
async function runStop(ctx, runId, n, user) {
|
async function runStop(ctx, runId, n, user) {
|
||||||
const job = ctx.jobs.get(runId);
|
const job = /** @type {JobState} */ (ctx.jobs.get(runId));
|
||||||
try {
|
try {
|
||||||
stopSession(runId, n); // the move, the freeze, the copies
|
stopSession(runId, n); // the move, the freeze, the copies
|
||||||
job.stopped = true;
|
job.stopped = true;
|
||||||
@@ -168,8 +183,9 @@ async function runStop(ctx, runId, n, user) {
|
|||||||
|
|
||||||
// one housekeeping pass: session n's log -> manifest -> apply into
|
// one housekeeping pass: session n's log -> manifest -> apply into
|
||||||
// the dormant session n+1 -> ready
|
// the dormant session n+1 -> ready
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise<void>} */
|
||||||
async function runPass(ctx, runId, n, user) {
|
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 lines = loadSession(runId, n).lines;
|
||||||
const text = ctx.mock
|
const text = ctx.mock
|
||||||
? mockManifest(n)
|
? mockManifest(n)
|
||||||
@@ -191,8 +207,15 @@ async function runPass(ctx, runId, n, user) {
|
|||||||
job.state = 'applied';
|
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<string>}
|
||||||
|
*/
|
||||||
async function callHousekeeper(ctx, runId, messages, user) {
|
async function callHousekeeper(ctx, runId, messages, user) {
|
||||||
const meta = ctx.runMeta?.(runId) ?? {};
|
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
|
||||||
const model = meta.models?.housekeeper
|
const model = meta.models?.housekeeper
|
||||||
?? ctx.cfg.models?.housekeeper
|
?? ctx.cfg.models?.housekeeper
|
||||||
?? ctx.cfg.models?.player
|
?? ctx.cfg.models?.player
|
||||||
@@ -212,6 +235,7 @@ export { callHousekeeper };
|
|||||||
// and agenda carry; the rings reset to the base the manifest lands
|
// and agenda carry; the rings reset to the base the manifest lands
|
||||||
// on) -- so re-runs never double-apply, and hand edits made in
|
// on) -- so re-runs never double-apply, and hand edits made in
|
||||||
// between are overwritten, ruled fine.
|
// between are overwritten, ruled fine.
|
||||||
|
/** @param {string} runId @param {string} manifestPath @param {number} n */
|
||||||
export function applyToDormant(runId, manifestPath, n) {
|
export function applyToDormant(runId, manifestPath, n) {
|
||||||
const target = sessionDir(runId, n + 1);
|
const target = sessionDir(runId, n + 1);
|
||||||
if (sessionMeta(runId, n + 1).phase !== 'dormant') {
|
if (sessionMeta(runId, n + 1).phase !== 'dormant') {
|
||||||
@@ -227,6 +251,7 @@ export function applyToDormant(runId, manifestPath, n) {
|
|||||||
writeMeta(runId, n + 1, { ready: true });
|
writeMeta(runId, n + 1, { ready: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @returns {JobState} */
|
||||||
export function jobState(ctx, runId) {
|
export function jobState(ctx, runId) {
|
||||||
requireRun(runId);
|
requireRun(runId);
|
||||||
const job = ctx.jobs.get(runId);
|
const job = ctx.jobs.get(runId);
|
||||||
@@ -243,6 +268,7 @@ export function jobState(ctx, runId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// the newest housekeeping record on disk
|
// the newest housekeeping record on disk
|
||||||
|
/** @param {string} runId @returns {{ session: number, pass: string, content: string }} */
|
||||||
export function latestLog(runId) {
|
export function latestLog(runId) {
|
||||||
const ns = listSessions(runId);
|
const ns = listSessions(runId);
|
||||||
for (let i = ns.length - 1; i >= 0; i--) {
|
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
|
// 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
|
// the cuffs (they shaped every move) and files the dark hold as a new
|
||||||
// ring-B memory. Exercises the whole chain without a key.
|
// ring-B memory. Exercises the whole chain without a key.
|
||||||
|
/** @param {number} n @returns {string} */
|
||||||
function mockManifest(n) {
|
function mockManifest(n) {
|
||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
session: String(n),
|
session: String(n),
|
||||||
|
|||||||
+37
-4
@@ -7,12 +7,20 @@
|
|||||||
// before every GM turn and rides it as a <status> block; the player's
|
// before every GM turn and rides it as a <status> block; the player's
|
||||||
// <lost>/<gained> deltas apply after its final message, and any
|
// <lost>/<gained> deltas apply after its final message, and any
|
||||||
// conflicts ride the next GM turn as a <conflict> block.
|
// conflicts ride the next GM turn as a <conflict> 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 { clerkJson } from './clerk.mjs';
|
||||||
import { toolList, runTool, assembleReminder } from './bundle.mjs';
|
import { toolList, runTool, assembleReminder } from './bundle.mjs';
|
||||||
import { renderView } from './session.mjs';
|
import { renderView } from './session.mjs';
|
||||||
import { parseVariants, pickVariant } from './variants.mjs';
|
import { parseVariants, pickVariant } from './variants.mjs';
|
||||||
|
|
||||||
export class HttpError extends Error {
|
export class HttpError extends Error {
|
||||||
|
/**
|
||||||
|
* @param {number} status @param {string} message @param {unknown} [detail]
|
||||||
|
*/
|
||||||
constructor(status, message, detail) {
|
constructor(status, message, detail) {
|
||||||
super(message);
|
super(message);
|
||||||
this.status = status;
|
this.status = status;
|
||||||
@@ -20,17 +28,25 @@ export class HttpError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @returns {LiveSession} */
|
||||||
function needSession(ctx, runId) {
|
function needSession(ctx, runId) {
|
||||||
const s = ctx.sessions.get(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`);
|
if (!s) throw new HttpError(409, `no open session for run '${runId}' -- POST /api/runs/${runId}/sessions first`);
|
||||||
return s;
|
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<TurnOut>}
|
||||||
|
*/
|
||||||
export async function gmTurn(ctx, runId, line, user) {
|
export async function gmTurn(ctx, runId, line, user) {
|
||||||
const s = needSession(ctx, runId);
|
const s = needSession(ctx, runId);
|
||||||
if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)');
|
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 status = /** @type {string[]} */ (clerkJson(runId, 'status')); // fresh per turn
|
||||||
const agenda = clerkJson(runId, 'agenda'); // 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
|
// the wire renders the queue as the model cites it: numbered from the top
|
||||||
const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; ');
|
const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; ');
|
||||||
const content = `${line.trim()}\n\n<status>${status.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
|
const content = `${line.trim()}\n\n<status>${status.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
|
||||||
@@ -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
|
// 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
|
// cue -- the first request of the assembled contwin fires with no new
|
||||||
// line (the cue is already the log's last word)
|
// line (the cue is already the log's last word)
|
||||||
|
/**
|
||||||
|
* @param {Ctx} ctx @param {string} runId @param {?Actor} user
|
||||||
|
* @returns {Promise<TurnOut>}
|
||||||
|
*/
|
||||||
export async function openingCall(ctx, runId, user) {
|
export async function openingCall(ctx, runId, user) {
|
||||||
return runLoop(ctx, runId, user);
|
return runLoop(ctx, runId, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Ctx} ctx @param {string} runId @param {string} answer @param {?Actor} user
|
||||||
|
* @returns {Promise<TurnOut>}
|
||||||
|
*/
|
||||||
export async function answerAsk(ctx, runId, answer, user) {
|
export async function answerAsk(ctx, runId, answer, user) {
|
||||||
const s = needSession(ctx, runId);
|
const s = needSession(ctx, runId);
|
||||||
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
|
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);
|
return runLoop(ctx, runId, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @param {?Actor} user @returns {Promise<TurnOut>} */
|
||||||
async function runLoop(ctx, runId, user) {
|
async function runLoop(ctx, runId, user) {
|
||||||
const s = ctx.sessions.get(runId);
|
const s = needSession(ctx, runId);
|
||||||
const tools = toolList(runId);
|
const tools = toolList(runId);
|
||||||
|
/** @type {TurnOut} */
|
||||||
const out = { tools: [] };
|
const out = { tools: [] };
|
||||||
let heals = 0;
|
let heals = 0;
|
||||||
for (;;) {
|
for (;;) {
|
||||||
@@ -155,8 +181,9 @@ async function runLoop(ctx, runId, user) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {Ctx} ctx @param {string} runId @returns {?string} */
|
||||||
function resolveModel(ctx, runId) {
|
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;
|
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
|
// path), the answer lands with status and agenda deltas (the tag
|
||||||
// transports), then the drops, a bad drop, its self-heal, and
|
// transports), then the drops, a bad drop, its self-heal, and
|
||||||
// everything after is plain prose.
|
// everything after is plain prose.
|
||||||
|
/** @typedef {import('./shapes.mjs').WireMessage} WireMessage */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {LiveSession} s @param {ViewMessage[]} view @returns {WireMessage}
|
||||||
|
*/
|
||||||
function mockModel(s, view) {
|
function mockModel(s, view) {
|
||||||
|
/** @param {string} name @param {Record<string, unknown>} args @param {string} id @returns {WireMessage} */
|
||||||
const call = (name, args, id) => ({
|
const call = (name, args, id) => ({
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: null,
|
content: null,
|
||||||
|
|||||||
+78
-21
@@ -8,6 +8,13 @@
|
|||||||
// view.
|
// view.
|
||||||
//
|
//
|
||||||
// usage: node server/main.mjs [--mock]
|
// usage: node server/main.mjs [--mock]
|
||||||
|
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
|
||||||
|
/** @typedef {import('./users.mjs').UserRow} UserRow */
|
||||||
|
/** A request as a handler sees it: path params, the parsed JSON body
|
||||||
|
* (any -- handlers validate), the raw request, the acting user. */
|
||||||
|
/** @typedef {{ params: Record<string, string>, body: any, req: import('node:http').IncomingMessage, user: ?UserRow }} Req */
|
||||||
|
/** @typedef {(req: Req) => unknown} Handler */
|
||||||
|
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import http from 'node:http';
|
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)');
|
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
|
||||||
process.exit(1);
|
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');
|
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 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 ---------------------------------------------------
|
// --- the per-run activity lock ---------------------------------------------------
|
||||||
//
|
//
|
||||||
@@ -46,7 +57,7 @@ ctx.locks = new Map();
|
|||||||
ctx.enqueue = (runId, fn) => {
|
ctx.enqueue = (runId, fn) => {
|
||||||
const prev = ctx.locks.get(runId) ?? Promise.resolve();
|
const prev = ctx.locks.get(runId) ?? Promise.resolve();
|
||||||
const next = prev.then(fn, fn); // run regardless of a prior failure
|
const next = prev.then(fn, fn); // run regardless of a prior failure
|
||||||
ctx.locks.set(runId, next.catch(() => {}));
|
ctx.locks.set(runId, /** @type {Promise<void>} */ (next.catch(() => {})));
|
||||||
return next;
|
return next;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,13 +93,16 @@ if (fs.existsSync(path.join(ROOT, 'runs'))) {
|
|||||||
|
|
||||||
// --- http plumbing -----------------------------------------------------------
|
// --- http plumbing -----------------------------------------------------------
|
||||||
|
|
||||||
|
/** @param {import('node:http').ServerResponse} res @param {number} status @param {unknown} body */
|
||||||
const send = (res, status, body) => {
|
const send = (res, status, body) => {
|
||||||
const data = JSON.stringify(body);
|
const data = JSON.stringify(body);
|
||||||
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) });
|
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) });
|
||||||
res.end(data);
|
res.end(data);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** @param {import('node:http').IncomingMessage} req @returns {Promise<any>} */
|
||||||
const readBody = (req) => new Promise((resolve, reject) => {
|
const readBody = (req) => new Promise((resolve, reject) => {
|
||||||
|
/** @type {Buffer[]} */
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let size = 0;
|
let size = 0;
|
||||||
req.on('data', (c) => {
|
req.on('data', (c) => {
|
||||||
@@ -104,14 +118,18 @@ const readBody = (req) => new Promise((resolve, reject) => {
|
|||||||
req.on('error', reject);
|
req.on('error', reject);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** @type {{ method: string, segs: string[], handler: Handler, publicRoute: boolean }[]} */
|
||||||
const routes = [];
|
const routes = [];
|
||||||
|
/** @param {string} method @param {string} pattern @param {Handler} handler @param {{ public?: boolean }} [opts] */
|
||||||
const route = (method, pattern, handler, opts = {}) =>
|
const route = (method, pattern, handler, opts = {}) =>
|
||||||
routes.push({ method, segs: pattern.split('/').filter(Boolean), handler, publicRoute: opts.public === true });
|
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 match = (method, pathname) => {
|
||||||
const segs = pathname.split('/').filter(Boolean);
|
const segs = pathname.split('/').filter(Boolean);
|
||||||
outer: for (const r of routes) {
|
outer: for (const r of routes) {
|
||||||
if (r.method !== method || r.segs.length !== segs.length) continue;
|
if (r.method !== method || r.segs.length !== segs.length) continue;
|
||||||
|
/** @type {Record<string, string>} */
|
||||||
const params = {};
|
const params = {};
|
||||||
for (let i = 0; i < segs.length; i++) {
|
for (let i = 0; i < segs.length; i++) {
|
||||||
if (r.segs[i].startsWith(':')) params[r.segs[i].slice(1)] = decodeURIComponent(segs[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.
|
// at /). Traversal-guarded; the SPA is a client like curl is.
|
||||||
|
|
||||||
const WEB_DIR = path.join(ROOT, 'web');
|
const WEB_DIR = path.join(ROOT, 'web');
|
||||||
|
/** @type {Record<string, string>} */
|
||||||
const MIME = {
|
const MIME = {
|
||||||
'.html': 'text/html; charset=utf-8',
|
'.html': 'text/html; charset=utf-8',
|
||||||
'.js': 'text/javascript; charset=utf-8',
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
@@ -136,6 +155,7 @@ const MIME = {
|
|||||||
'.json': 'application/json',
|
'.json': 'application/json',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** @param {string} pathname @param {import('node:http').ServerResponse} res */
|
||||||
function serveStatic(pathname, res) {
|
function serveStatic(pathname, res) {
|
||||||
let rel = decodeURIComponent(pathname).replace(/^\/+/, '');
|
let rel = decodeURIComponent(pathname).replace(/^\/+/, '');
|
||||||
if (!rel) rel = 'index.html';
|
if (!rel) rel = 'index.html';
|
||||||
@@ -217,28 +237,48 @@ route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** @param {?UserRow} user */
|
||||||
|
/**
|
||||||
|
* @param {?UserRow} user
|
||||||
|
* @returns {asserts user is UserRow}
|
||||||
|
*/
|
||||||
function requireSuperuser(user) {
|
function requireSuperuser(user) {
|
||||||
if (!user?.superuser) throw new HttpError(403, 'superuser only');
|
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
|
// ownership is resolved, never maintained: run.json keeps the record
|
||||||
// of who owned a run, and a dead owner id (revocation) resolves to
|
// of who owned a run, and a dead owner id (revocation) resolves to
|
||||||
// absent. The API never exposes a dangling id.
|
// absent. The API never exposes a dangling id.
|
||||||
|
/** @param {?string|undefined} owner @returns {?string} */
|
||||||
const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null);
|
const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null);
|
||||||
|
|
||||||
// ownership: every GM action -- every mutation, every model call -- is
|
// ownership: every GM action -- every mutation, every model call -- is
|
||||||
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
|
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
|
||||||
// one uniform state: readable by all, forkable, never re-claimed.
|
// 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) {
|
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
|
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) {
|
if (resolveOwner(meta.owner) == null) {
|
||||||
throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`);
|
throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`);
|
||||||
}
|
}
|
||||||
if (meta.owner !== user.id) {
|
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`);
|
throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`);
|
||||||
}
|
}
|
||||||
return meta;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- routes -------------------------------------------------------------------
|
// --- routes -------------------------------------------------------------------
|
||||||
@@ -280,7 +320,7 @@ route('POST', '/api/packages', async ({ body, user }) => {
|
|||||||
// substrate invariants, and the per-turn reminder -- never copied into
|
// substrate invariants, and the per-turn reminder -- never copied into
|
||||||
// a run, so the editor shows them as context, not as something to edit
|
// a run, so the editor shows them as context, not as something to edit
|
||||||
route('GET', '/api/prompts', async () => {
|
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 {
|
return {
|
||||||
system: readOpt('system.md'),
|
system: readOpt('system.md'),
|
||||||
invariants: readOpt('invariants.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 (!/^[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');
|
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);
|
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)] : []));
|
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');
|
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
||||||
const run = JSON.parse(r.out);
|
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
|
// a name to play as: rolled from the dictionary, unused by any run
|
||||||
route('GET', '/api/names', async () => {
|
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 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 free = all.filter((n) => !used.has(n.toLowerCase()));
|
||||||
const pool = free.length ? free : all; // a fully-used dictionary still suggests
|
const pool = free.length ? free : all; // a fully-used dictionary still suggests
|
||||||
return { name: pool[Math.floor(Math.random() * pool.length)] };
|
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
|
// play-view pad); config is read-only (vars and lineage are easy to
|
||||||
// break blind).
|
// 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) {
|
function fileSurface(runId) {
|
||||||
const live = ctx.sessions.get(runId);
|
const live = ctx.sessions.get(runId);
|
||||||
const latest = session.latestSession(runId);
|
const latest = session.latestSession(runId);
|
||||||
@@ -411,6 +456,7 @@ function fileSurface(runId) {
|
|||||||
route('GET', '/api/runs/:id/files', async ({ params }) => {
|
route('GET', '/api/runs/:id/files', async ({ params }) => {
|
||||||
bundle.requireRun(params.id);
|
bundle.requireRun(params.id);
|
||||||
const surf = fileSurface(params.id);
|
const surf = fileSurface(params.id);
|
||||||
|
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */
|
||||||
const files = {};
|
const files = {};
|
||||||
for (const [f, spec] of Object.entries(surf.files)) {
|
for (const [f, spec] of Object.entries(surf.files)) {
|
||||||
files[f] = fs.existsSync(spec.path)
|
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)) {
|
for (const k of Object.keys(body)) {
|
||||||
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} -- player and housekeeper`);
|
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 ?? {};
|
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] === undefined) continue;
|
||||||
if (body[role] === null) { delete models[role]; continue; }
|
if (body[role] === null) { delete models[role]; continue; }
|
||||||
const m = String(body[role]).trim();
|
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 }) => {
|
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
|
||||||
const id = params.id;
|
const id = params.id;
|
||||||
requireOwner(user, 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 () => {
|
return ctx.enqueue(id, async () => {
|
||||||
const { session: s, autoSend } = session.startSession(id, { override: body.override === true });
|
const { session: s, autoSend } = session.startSession(id, { override: body.override === true });
|
||||||
ctx.sessions.set(id, s);
|
ctx.sessions.set(id, s);
|
||||||
@@ -569,6 +616,7 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => {
|
|||||||
const meta = session.sessionMeta(params.id, latest);
|
const meta = session.sessionMeta(params.id, latest);
|
||||||
if (meta.phase !== 'dormant') throw new HttpError(409, `session ${latest} is ${meta.phase || 'unmarked'}`);
|
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');
|
const p = path.join(session.sessionDir(params.id, latest), 'carryover.jsonl');
|
||||||
|
/** @type {import('./shapes.mjs').LogEvent[]} */
|
||||||
const lines = [];
|
const lines = [];
|
||||||
if (fs.existsSync(p)) {
|
if (fs.existsSync(p)) {
|
||||||
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
|
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 eff = effectiveContents(lines);
|
||||||
const entries = lines.map((e, i) => {
|
const entries = lines.map((e, i) => {
|
||||||
if (e.t === 'msg' && e.m.role === 'assistant') {
|
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;
|
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
||||||
return { ...e, m };
|
return { ...e, m };
|
||||||
}
|
}
|
||||||
return e;
|
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 {
|
return {
|
||||||
run: params.id,
|
run: params.id,
|
||||||
session: latest,
|
session: latest,
|
||||||
@@ -611,7 +660,8 @@ route('GET', '/api/runs/:id/table', async ({ params }) => {
|
|||||||
const eff = effectiveContents(s.lines);
|
const eff = effectiveContents(s.lines);
|
||||||
const entries = s.lines.map((e, i) => {
|
const entries = s.lines.map((e, i) => {
|
||||||
if (e.t === 'msg' && e.m.role === 'assistant') {
|
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;
|
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
||||||
return { ...e, m };
|
return { ...e, m };
|
||||||
}
|
}
|
||||||
@@ -647,8 +697,9 @@ route('GET', '/api/runs/:id/story', async ({ params }) => {
|
|||||||
bundle.requireRun(params.id);
|
bundle.requireRun(params.id);
|
||||||
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
|
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
|
||||||
const verbs = /<(lost|gained|add|drop)>[\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);
|
const eff = effectiveContents(lines);
|
||||||
|
/** @type {{ who: string, text: string }[]} */
|
||||||
const turns = [];
|
const turns = [];
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
const e = lines[i];
|
const e = lines[i];
|
||||||
@@ -664,7 +715,9 @@ route('GET', '/api/runs/:id/story', async ({ params }) => {
|
|||||||
}
|
}
|
||||||
return turns;
|
return turns;
|
||||||
};
|
};
|
||||||
|
/** @param {string} p @returns {import('./shapes.mjs').LogEvent[]} */
|
||||||
const readJsonl = (p) => {
|
const readJsonl = (p) => {
|
||||||
|
/** @type {import('./shapes.mjs').LogEvent[]} */
|
||||||
const out = [];
|
const out = [];
|
||||||
if (!fs.existsSync(p)) return out;
|
if (!fs.existsSync(p)) return out;
|
||||||
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
|
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();
|
const line = String(body.line ?? '').trim();
|
||||||
if (!line) throw new HttpError(400, 'line is required');
|
if (!line) throw new HttpError(400, 'line is required');
|
||||||
requireOwner(user, params.id);
|
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 }) => {
|
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
|
||||||
const answer = String(body.answer ?? '').trim();
|
const answer = String(body.answer ?? '').trim();
|
||||||
if (!answer) throw new HttpError(400, 'answer is required');
|
if (!answer) throw new HttpError(400, 'answer is required');
|
||||||
requireOwner(user, params.id);
|
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
|
// 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.
|
// the copy is never taken mid-turn.
|
||||||
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
|
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
|
||||||
bundle.requireRun(params.id);
|
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 }) => {
|
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);
|
const latest = session.latestSession(id);
|
||||||
if (latest == null || latest < 2) throw new HttpError(409, 'no dormant continuation session to apply into');
|
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`);
|
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 {
|
try {
|
||||||
housekeeping.applyToDormant(id, manifestPath, latest - 1);
|
housekeeping.applyToDormant(id, manifestPath, latest - 1);
|
||||||
return { ok: true, housekept: latest - 1, target: latest };
|
return { ok: true, housekept: latest - 1, target: latest };
|
||||||
@@ -835,6 +890,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user })
|
|||||||
// --- dispatch -------------------------------------------------------------------
|
// --- dispatch -------------------------------------------------------------------
|
||||||
|
|
||||||
// bearer-token identity (users.mjs); null when absent or unknown
|
// bearer-token identity (users.mjs); null when absent or unknown
|
||||||
|
/** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */
|
||||||
function authenticate(req) {
|
function authenticate(req) {
|
||||||
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
|
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
|
||||||
return m ? users.getUserByToken(m[1].trim()) : null;
|
return m ? users.getUserByToken(m[1].trim()) : null;
|
||||||
@@ -842,9 +898,10 @@ function authenticate(req) {
|
|||||||
|
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
|
/** @type {?UserRow} */
|
||||||
let user = null;
|
let user = null;
|
||||||
try {
|
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
|
// the request log: one line per API call -- reconstruct any session
|
||||||
// from the console output after the fact; the acting user rides
|
// from the console output after the fact; the acting user rides
|
||||||
// every line (attribution, #22)
|
// every line (attribution, #22)
|
||||||
@@ -858,7 +915,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
serveStatic(url.pathname, res);
|
serveStatic(url.pathname, res);
|
||||||
return;
|
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}`);
|
if (!m) throw new HttpError(404, `no such route: ${req.method} ${url.pathname}`);
|
||||||
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {};
|
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {};
|
||||||
user = authenticate(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(':');
|
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`);
|
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt`);
|
||||||
});
|
});
|
||||||
|
|||||||
+15
-2
@@ -1,6 +1,13 @@
|
|||||||
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
|
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
|
||||||
// endpoint per deployment (server.json "endpoint"); the model name
|
// endpoint per deployment (server.json "endpoint"); the model name
|
||||||
// comes from the run (run.json override) or the config default.
|
// 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) {
|
export function makeProvider(endpoint) {
|
||||||
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
|
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
|
||||||
if (!base) throw new Error('server.json: endpoint.baseUrl is required');
|
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}` };
|
const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
/**
|
||||||
|
* @param {?string} model @param {ViewMessage[]} messages
|
||||||
|
* @param {?import('./shapes.mjs').ToolDef[]} [tools] @param {Record<string, unknown>} [params]
|
||||||
|
* @returns {Promise<ChatResponse>}
|
||||||
|
*/
|
||||||
async chat(model, messages, tools, params = {}) {
|
async chat(model, messages, tools, params = {}) {
|
||||||
const res = await fetch(`${base}/chat/completions`, {
|
const res = await fetch(`${base}/chat/completions`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -17,16 +29,17 @@ export function makeProvider(endpoint) {
|
|||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
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;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** @returns {Promise<string[]>} */
|
||||||
async models() {
|
async models() {
|
||||||
const res = await fetch(`${base}/models`, { headers });
|
const res = await fetch(`${base}/models`, { headers });
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
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();
|
return (data.data ?? []).map((m) => m.id).sort();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+73
-15
@@ -17,6 +17,13 @@
|
|||||||
// (the last few and every ask_gm answer stay), old GM-side
|
// (the last few and every ask_gm answer stay), old GM-side
|
||||||
// <status>/<conflict> blocks elide -- the current status rides the
|
// <status>/<conflict> blocks elide -- the current status rides the
|
||||||
// newest GM turn.
|
// 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 fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -27,11 +34,16 @@ import { tailStart } from './carry.mjs';
|
|||||||
|
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
|
/** @param {string} runId */
|
||||||
const sessionsDir = (runId) => path.join(runDir(runId), 'sessions');
|
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));
|
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');
|
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');
|
const carryFile = (runId, n) => path.join(sessionDir(runId, n), 'carryover.jsonl');
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {number[]} */
|
||||||
export function listSessions(runId) {
|
export function listSessions(runId) {
|
||||||
if (!fs.existsSync(sessionsDir(runId))) return [];
|
if (!fs.existsSync(sessionsDir(runId))) return [];
|
||||||
return fs.readdirSync(sessionsDir(runId), { withFileTypes: true })
|
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);
|
.map((d) => Number(d.name)).sort((a, b) => a - b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} runId @returns {?number} */
|
||||||
export const latestSession = (runId) => {
|
export const latestSession = (runId) => {
|
||||||
const ns = listSessions(runId);
|
const ns = listSessions(runId);
|
||||||
return ns.length ? ns[ns.length - 1] : null;
|
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) {
|
export function sessionMeta(runId, n) {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(fs.readFileSync(path.join(sessionDir(runId, n), 'session.json'), 'utf8'));
|
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<string, unknown>} patch
|
||||||
|
* @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }}
|
||||||
|
*/
|
||||||
export function writeMeta(runId, n, patch) {
|
export function writeMeta(runId, n, patch) {
|
||||||
const m = { ...sessionMeta(runId, n), ...patch };
|
const m = { ...sessionMeta(runId, n), ...patch };
|
||||||
fs.writeFileSync(path.join(sessionDir(runId, n), 'session.json'), JSON.stringify(m, null, 2) + '\n');
|
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,
|
// the run's state is its latest session's: live while one plays,
|
||||||
// else dormant (the review window). At most one live session exists.
|
// else dormant (the review window). At most one live session exists.
|
||||||
|
/** @param {string} runId @returns {?number} */
|
||||||
export function liveSession(runId) {
|
export function liveSession(runId) {
|
||||||
return listSessions(runId).find((n) => sessionMeta(runId, n).phase === 'live') ?? null;
|
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 err = (status, message, detail) => {
|
||||||
const e = new Error(message);
|
const e = /** @type {HttpError} */ (new Error(message));
|
||||||
e.status = status;
|
e.status = status;
|
||||||
if (detail) e.detail = detail;
|
if (detail) e.detail = detail;
|
||||||
return e;
|
return e;
|
||||||
@@ -73,6 +96,7 @@ const err = (status, message, detail) => {
|
|||||||
|
|
||||||
// --- session object ----------------------------------------------------------
|
// --- session object ----------------------------------------------------------
|
||||||
|
|
||||||
|
/** @param {string} runId @param {number} n @returns {LiveSession} */
|
||||||
function makeSession(runId, n) {
|
function makeSession(runId, n) {
|
||||||
return {
|
return {
|
||||||
runId,
|
runId,
|
||||||
@@ -82,6 +106,7 @@ function makeSession(runId, n) {
|
|||||||
lines: [],
|
lines: [],
|
||||||
pendingAsk: null, // { callId, question, calls } -- the whole batch pauses
|
pendingAsk: null, // { callId, question, calls } -- the whole batch pauses
|
||||||
usage: null, // { promptTokens, completionTokens } from the last response
|
usage: null, // { promptTokens, completionTokens } from the last response
|
||||||
|
/** @param {LogEvent} entry */
|
||||||
append(entry) {
|
append(entry) {
|
||||||
this.lines.push(entry);
|
this.lines.push(entry);
|
||||||
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
|
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
|
||||||
@@ -89,6 +114,7 @@ function makeSession(runId, n) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} file @returns {LogEvent[]} */
|
||||||
function readLogLines(file) {
|
function readLogLines(file) {
|
||||||
if (!fs.existsSync(file)) {
|
if (!fs.existsSync(file)) {
|
||||||
throw err(404, `no session log: ${path.relative(ROOT, file)}`);
|
throw err(404, `no session log: ${path.relative(ROOT, file)}`);
|
||||||
@@ -105,6 +131,7 @@ function readLogLines(file) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} file @param {LogEvent[]} lines */
|
||||||
function writeLog(file, lines) {
|
function writeLog(file, lines) {
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
const tmp = `${file}.tmp`;
|
const tmp = `${file}.tmp`;
|
||||||
@@ -112,6 +139,7 @@ function writeLog(file, lines) {
|
|||||||
fs.renameSync(tmp, file); // atomic: a crash never leaves a torn log
|
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) {
|
export function loadSession(runId, n) {
|
||||||
const s = makeSession(runId, n);
|
const s = makeSession(runId, n);
|
||||||
s.lines = readLogLines(s.file);
|
s.lines = readLogLines(s.file);
|
||||||
@@ -120,7 +148,9 @@ export function loadSession(runId, n) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// rebuild the derived state from the log alone
|
// rebuild the derived state from the log alone
|
||||||
|
/** @param {LiveSession} s */
|
||||||
function derive(s) {
|
function derive(s) {
|
||||||
|
/** @type {?PendingAsk} */
|
||||||
let pending = null;
|
let pending = null;
|
||||||
for (const e of s.lines) {
|
for (const e of s.lines) {
|
||||||
if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) {
|
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)) {
|
&& typeof last.m.content === 'string' && /<\/?variants?>/.test(last.m.content)) {
|
||||||
try {
|
try {
|
||||||
const v = parseVariants(last.m.content);
|
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) {
|
} catch (e) {
|
||||||
console.warn(`boot: an unresolved variant turn in session ${s.n} was left as-is: ${e.message}`);
|
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
|
// boot resumes a half-finished stop by re-running this over the
|
||||||
// on-disk state (the move step reconciles against what already
|
// on-disk state (the move step reconciles against what already
|
||||||
// landed, so it never moves anything twice).
|
// landed, so it never moves anything twice).
|
||||||
|
/** @param {string} runId @param {number} N */
|
||||||
export function stopSession(runId, N) {
|
export function stopSession(runId, N) {
|
||||||
const dir = sessionDir(runId, N + 1);
|
const dir = sessionDir(runId, N + 1);
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
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
|
// a stop that died in flight leaves its marker; boot finishes it
|
||||||
|
/** @param {string} runId @returns {?{ from: number, dir: number }} */
|
||||||
export function findStalledStop(runId) {
|
export function findStalledStop(runId) {
|
||||||
for (const n of listSessions(runId)) {
|
for (const n of listSessions(runId)) {
|
||||||
const p = path.join(sessionDir(runId, n), 'stop.json');
|
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.
|
// conversation: msg, tool, and note events, read as recorded.
|
||||||
// Exported for the file editor's save-time check: only clean
|
// Exported for the file editor's save-time check: only clean
|
||||||
// openings land.
|
// openings land.
|
||||||
|
/** @param {LogEvent[]} lines @param {{ authored: boolean }} opts @returns {string[]} */
|
||||||
export function lintCarryover(lines, { authored }) {
|
export function lintCarryover(lines, { authored }) {
|
||||||
const errors = [];
|
const errors = [];
|
||||||
let openings = 0;
|
let openings = 0;
|
||||||
@@ -233,7 +266,10 @@ export function lintCarryover(lines, { authored }) {
|
|||||||
const at = `line ${i + 1}`;
|
const at = `line ${i + 1}`;
|
||||||
if (authored) {
|
if (authored) {
|
||||||
if (e.t === 'msg') {
|
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<string, unknown>} */ (e.m ?? {});
|
||||||
if (m.role !== 'user' && m.role !== 'assistant') errors.push(`${at}: role must be user (the GM) or assistant (her)`);
|
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 (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`);
|
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
|
// freeze, exactly like every bundle file. A continuation carryover is
|
||||||
// live prose and NEVER expands -- a literal $word typed in play would
|
// live prose and NEVER expands -- a literal $word typed in play would
|
||||||
// bomb the unresolved-token check, and the words are already real.
|
// bomb the unresolved-token check, and the words are already real.
|
||||||
|
/** @param {string} runId @param {LogEvent[]} lines @returns {LogEvent[]} */
|
||||||
function expandCarryover(runId, lines) {
|
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 === '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)) };
|
if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) };
|
||||||
return e;
|
return e;
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// an unpicked variants event gets its crypto pick at start -- the
|
// an unpicked variants event gets its crypto pick at start -- the
|
||||||
// same dice the loop rolls on reception; a pick already adjacent
|
// same dice the loop rolls on reception; a pick already adjacent
|
||||||
// (real history) is final, re-rolls do not exist
|
// (real history) is final, re-rolls do not exist
|
||||||
|
/** @param {LogEvent[]} lines @returns {LogEvent[]} */
|
||||||
function resolvePicks(lines) {
|
function resolvePicks(lines) {
|
||||||
|
/** @type {LogEvent[]} */
|
||||||
const out = [];
|
const out = [];
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
const e = lines[i];
|
const e = lines[i];
|
||||||
out.push(e);
|
out.push(e);
|
||||||
|
const next = lines[i + 1];
|
||||||
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
|
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
|
||||||
&& /<\/?variants?>/.test(e.m.content)
|
&& /<\/?variants?>/.test(e.m.content)
|
||||||
&& !(lines[i + 1]?.t === 'note' && lines[i + 1].kind === 'pick')) {
|
&& !(next && next.t === 'note' && next.kind === 'pick')) {
|
||||||
const v = parseVariants(e.m.content); // lint already validated
|
const v = parseVariants(e.m.content); // lint already validated -- never null past the tag test
|
||||||
out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
if (v) out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {string} runId @param {number} n @returns {LogEvent[]} */
|
||||||
function readCarryover(runId, n) {
|
function readCarryover(runId, n) {
|
||||||
const p = carryFile(runId, n);
|
const p = carryFile(runId, n);
|
||||||
if (!fs.existsSync(p)) return [];
|
if (!fs.existsSync(p)) return [];
|
||||||
@@ -315,6 +356,11 @@ function readCarryover(runId, n) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} runId
|
||||||
|
* @param {{ override?: boolean }} [opts]
|
||||||
|
* @returns {{ session: LiveSession, autoSend: boolean }}
|
||||||
|
*/
|
||||||
export function startSession(runId, { override = false } = {}) {
|
export function startSession(runId, { override = false } = {}) {
|
||||||
requireRun(runId);
|
requireRun(runId);
|
||||||
const n = latestSession(runId);
|
const n = latestSession(runId);
|
||||||
@@ -364,14 +410,16 @@ export function startSession(runId, { override = false } = {}) {
|
|||||||
// renders from
|
// renders from
|
||||||
const rr = clerkTry(runId, '--session', String(n), 'render');
|
const rr = clerkTry(runId, '--session', String(n), 'render');
|
||||||
if (rr.code !== 0) throw err(500, `render failed: ${(rr.err || rr.out).split('\n')[0]}`);
|
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 system = { role: 'system', content: assembleSystem(runId, dir) };
|
||||||
const bundle = assembleBundle(runId, dir);
|
const bundle = assembleBundle(runId, dir);
|
||||||
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
|
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
|
||||||
|
/** @type {LogEvent[]} */
|
||||||
const lines = [
|
const lines = [
|
||||||
{ t: 'note', kind: 'session', n },
|
{ t: 'note', kind: 'session', n },
|
||||||
...(opening ? [opening] : []),
|
...(opening ? [opening] : []),
|
||||||
{ t: 'bundle', m: system, part: 'system' },
|
{ 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,
|
...carry,
|
||||||
];
|
];
|
||||||
// the assembled context must be sound before anything lands:
|
// 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 --
|
// the opening flow: a carryover ending on a GM turn is her cue --
|
||||||
// it sends automatically as the first request of the assembled
|
// it sends automatically as the first request of the assembled
|
||||||
// contwin; otherwise the table waits for the GM's input
|
// 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' };
|
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;
|
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) {
|
export function renderView(s, keepToolResults = 4) {
|
||||||
const eff = effectiveContents(s.lines);
|
const eff = effectiveContents(s.lines);
|
||||||
|
/** @type {number[]} */
|
||||||
const toolIdx = [];
|
const toolIdx = [];
|
||||||
|
/** @type {number[]} */
|
||||||
const reminderIdx = [];
|
const reminderIdx = [];
|
||||||
let lastGmIdx = -1;
|
let lastGmIdx = -1;
|
||||||
s.lines.forEach((e, i) => {
|
s.lines.forEach((e, i) => {
|
||||||
@@ -414,6 +470,7 @@ export function renderView(s, keepToolResults = 4) {
|
|||||||
});
|
});
|
||||||
const keep = new Set(toolIdx.slice(-keepToolResults));
|
const keep = new Set(toolIdx.slice(-keepToolResults));
|
||||||
const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1;
|
const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1;
|
||||||
|
/** @type {ViewMessage[]} */
|
||||||
const msgs = [];
|
const msgs = [];
|
||||||
for (const [i, e] of s.lines.entries()) {
|
for (const [i, e] of s.lines.entries()) {
|
||||||
if (e.t === 'bundle') {
|
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
|
// the per-turn reminder: only the newest copy lives in the
|
||||||
// context -- superseded ones elide (identical content, freshest
|
// context -- superseded ones elide (identical content, freshest
|
||||||
// position, exactly like the status/agenda blocks)
|
// 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') {
|
} else if (e.m.role === 'assistant') {
|
||||||
// thinking never goes back; the log keeps it. Variant turns
|
// thinking never goes back; the log keeps it. Variant turns
|
||||||
// render their picked variant -- the unpicked rest never reach
|
// render their picked variant -- the unpicked rest never reach
|
||||||
// a model (the log keeps them)
|
// 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;
|
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
||||||
msgs.push(m);
|
msgs.push(m);
|
||||||
} else if (e.conflictOnly) {
|
} else if (e.conflictOnly) {
|
||||||
// transient error traffic: visible while it is the latest word
|
// transient error traffic: visible while it is the latest word
|
||||||
// (the model answers it), elided entirely once the story moves
|
// (the model answers it), elided entirely once the story moves
|
||||||
// on -- the log keeps it for provenance
|
// 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) {
|
} else if (i === lastGmIdx) {
|
||||||
// the newest GM turn keeps its blocks as-sent: the current
|
// the newest GM turn keeps its blocks as-sent: the current
|
||||||
// status and agenda ride it
|
// 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 {
|
} else {
|
||||||
// older GM turns: status/agenda/conflict blocks elide
|
// 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') {
|
} else if (e.t === 'tool') {
|
||||||
if (e.ask || keep.has(i)) {
|
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
|
// tool-call pairing is never broken (the endpoint tolerates orphans
|
||||||
// silently -- probed 2026-11-12 -- so this one fails quiet unless we check)
|
// silently -- probed 2026-11-12 -- so this one fails quiet unless we check)
|
||||||
|
/** @param {ViewMessage[]} msgs @param {?string|undefined} pendingCallId */
|
||||||
function validatePairing(msgs, pendingCallId) {
|
function validatePairing(msgs, pendingCallId) {
|
||||||
const calls = new Set();
|
const calls = new Set();
|
||||||
const results = new Set();
|
const results = new Set();
|
||||||
|
|||||||
@@ -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<string, unknown>, 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<string, string> }} 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<typeof import('./provider.mjs').makeProvider>} 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<string, unknown> }} 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<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */
|
||||||
+31
-9
@@ -12,6 +12,13 @@
|
|||||||
//
|
//
|
||||||
// All times are UTC (house rule). Never model-facing: nothing here
|
// All times are UTC (house rule). Never model-facing: nothing here
|
||||||
// ever enters a bundle or a prompt.
|
// 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 { DatabaseSync } from 'node:sqlite';
|
||||||
import { createHash, randomBytes } from 'node:crypto';
|
import { createHash, randomBytes } from 'node:crypto';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
@@ -47,48 +54,58 @@ const db = new DatabaseSync(DB_PATH);
|
|||||||
db.exec(SCHEMA);
|
db.exec(SCHEMA);
|
||||||
|
|
||||||
const now = () => new Date().toISOString();
|
const now = () => new Date().toISOString();
|
||||||
|
/** @param {string} s @returns {string} */
|
||||||
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
|
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
|
||||||
|
/** @param {number} n @returns {string} */
|
||||||
const hex = (n) => randomBytes(n).toString('hex');
|
const hex = (n) => randomBytes(n).toString('hex');
|
||||||
|
|
||||||
// --- users ---------------------------------------------------------------------
|
// --- users ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** @returns {number} */
|
||||||
export function userCount() {
|
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 --
|
// does this identity exist? A revoked user's id resolves to absent --
|
||||||
// dead ids are ownerless by resolution, never by rewriting history
|
// dead ids are ownerless by resolution, never by rewriting history
|
||||||
|
/** @param {?string} uid @returns {boolean} */
|
||||||
export function exists(uid) {
|
export function exists(uid) {
|
||||||
if (uid == null) return false;
|
if (uid == null) return false;
|
||||||
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
|
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {?string} token @returns {?UserRow} */
|
||||||
export function getUserByToken(token) {
|
export function getUserByToken(token) {
|
||||||
const t = String(token ?? '').trim();
|
const t = String(token ?? '').trim();
|
||||||
if (!t) return null;
|
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;
|
return row ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {?string|undefined} uid @returns {?string} */
|
||||||
export function userName(uid) {
|
export function userName(uid) {
|
||||||
if (uid == null) return null;
|
if (uid == null) return null;
|
||||||
const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid);
|
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() {
|
export function listUsers() {
|
||||||
return db.prepare('SELECT id, name, superuser, created FROM users ORDER BY created').all()
|
return /** @type {{ id: string, name: string, superuser: number, created: string }[]} */ (
|
||||||
.map((u) => ({ ...u, superuser: u.superuser === 1 }));
|
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
|
// revocation destroys the identity: no suspend, no restore. Their runs
|
||||||
// and packages stay -- ownerless, readable, forkable.
|
// and packages stay -- ownerless, readable, forkable.
|
||||||
|
/** @param {string} id @returns {boolean} */
|
||||||
export function revokeUser(id) {
|
export function revokeUser(id) {
|
||||||
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
|
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- invites ---------------------------------------------------------------------
|
// --- invites ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** @param {string} byUid @param {'invite'|'bootstrap'} [kind] @returns {{ id: number, code: string }} */
|
||||||
export function mintInvite(byUid, kind = 'invite') {
|
export function mintInvite(byUid, kind = 'invite') {
|
||||||
const code = hex(12); // 24 hex chars -- shown once, stored hashed
|
const code = hex(12); // 24 hex chars -- shown once, stored hashed
|
||||||
const res = db.prepare(
|
const res = db.prepare(
|
||||||
@@ -97,26 +114,30 @@ export function mintInvite(byUid, kind = 'invite') {
|
|||||||
return { id: Number(res.lastInsertRowid), code };
|
return { id: Number(res.lastInsertRowid), code };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @returns {InviteListed[]} */
|
||||||
export function listInvites() {
|
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'
|
'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
|
// only unclaimed invites can be revoked; spent ones are a permanent record
|
||||||
|
/** @param {number} id @returns {boolean} */
|
||||||
export function revokeInvite(id) {
|
export function revokeInvite(id) {
|
||||||
return db.prepare('DELETE FROM invites WHERE id = ? AND claimed_by IS NULL').run(id).changes > 0;
|
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,
|
// exchange a single-use invite code for a persistent token. Unknown,
|
||||||
// spent, and dead-bootstrap codes are each named explicitly.
|
// 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) {
|
export function claimInvite(code, name) {
|
||||||
const c = String(code ?? '').trim();
|
const c = String(code ?? '').trim();
|
||||||
const n = String(name ?? '').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 (!c) fail('the invite code is required');
|
||||||
if (!n) fail('a display name 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) fail('unknown invite code');
|
||||||
if (row.claimed_by != null) fail('this invite was already used -- ask for a fresh one');
|
if (row.claimed_by != null) fail('this invite was already used -- ask for a fresh one');
|
||||||
if (row.kind === 'bootstrap' && userCount() > 0) {
|
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
|
// never generated again once any user exists; rejected at claim time
|
||||||
// if somehow presented after that.
|
// if somehow presented after that.
|
||||||
|
|
||||||
|
/** @returns {?{ reused?: boolean, code?: string }} */
|
||||||
export function bootstrap() {
|
export function bootstrap() {
|
||||||
if (userCount() > 0) return null;
|
if (userCount() > 0) return null;
|
||||||
const open = db.prepare("SELECT id FROM invites WHERE kind = 'bootstrap' AND claimed_by IS NULL").get();
|
const open = db.prepare("SELECT id FROM invites WHERE kind = 'bootstrap' AND claimed_by IS NULL").get();
|
||||||
|
|||||||
+8
-1
@@ -15,9 +15,14 @@
|
|||||||
// pairing violations).
|
// pairing violations).
|
||||||
import { randomInt } from 'node:crypto';
|
import { randomInt } from 'node:crypto';
|
||||||
|
|
||||||
|
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
|
||||||
|
|
||||||
const ANY_TAG = /<\/?variants?>/; // matches <variant>, <variants>, and both closers
|
const ANY_TAG = /<\/?variants?>/; // matches <variant>, <variants>, 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) {
|
export function parseVariants(text) {
|
||||||
const t = String(text ?? '');
|
const t = String(text ?? '');
|
||||||
if (!ANY_TAG.test(t)) return null;
|
if (!ANY_TAG.test(t)) return null;
|
||||||
@@ -35,6 +40,7 @@ export function parseVariants(text) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// the dice: uniform, server-side, unwatchable by the model
|
// the dice: uniform, server-side, unwatchable by the model
|
||||||
|
/** @param {number} count @returns {number} */
|
||||||
export const pickVariant = (count) => randomInt(count);
|
export const pickVariant = (count) => randomInt(count);
|
||||||
|
|
||||||
// The effective-content map: what each assistant message "really
|
// 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
|
// note renders the chosen variant; a message still mid-turn (a tool
|
||||||
// call carrying draft variants) renders the block stripped -- the
|
// call carrying draft variants) renders the block stripped -- the
|
||||||
// candidates are her live draft until a pick resolves them.
|
// candidates are her live draft until a pick resolves them.
|
||||||
|
/** @param {LogEvent[]} lines @returns {Map<number, string>} */
|
||||||
export function effectiveContents(lines) {
|
export function effectiveContents(lines) {
|
||||||
const eff = new Map();
|
const eff = new Map();
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
|||||||
+4
-2
@@ -23,8 +23,10 @@
|
|||||||
// context window), turn-0, seed (memory.json is the name).
|
// context window), turn-0, seed (memory.json is the name).
|
||||||
// Historical records keep the vocabulary of
|
// Historical records keep the vocabulary of
|
||||||
// their day; gm.md is GM-private, flagged never fixed.
|
// their day; gm.md is GM-private, flagged never fixed.
|
||||||
// 5. Zero-dependency stack (GM, 2026-11-13): every import is
|
// 5. Zero-dependency runtime (GM, 2026-11-13, amended 2026-11-15):
|
||||||
// node: builtin or relative. No package manager, ever.
|
// 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-
|
// 6. UTC discipline (GM, 2026-11-14): no locale- or timezone-
|
||||||
// dependent date formatting in code. No time zones, ever.
|
// dependent date formatting in code. No time zones, ever.
|
||||||
// 7. web/ static files never start with "api" -- the server's route
|
// 7. web/ static files never start with "api" -- the server's route
|
||||||
|
|||||||
@@ -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"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user