gm surface: home flow, run identity, full-assembly editor, notepad, wrap replay; sigils and dateless rings
This commit is contained in:
+36
-8
@@ -5,8 +5,8 @@
|
||||
// The bundle rides as GM messages (user role), one per file: backdrop,
|
||||
// character, ring-b, ring-a — identity first, then memory, ring A in
|
||||
// the recency slot; turn-0 opens a fresh run before the GM's first
|
||||
// line. $NAME tokens resolve from the run's settings.json "vars" and
|
||||
// fail loudly when unresolved — the model never sees a raw $NAME.
|
||||
// line. Substitution resolves before sending — the model never sees a
|
||||
// raw sigil.
|
||||
//
|
||||
// The tool list is the capability surface: roll and ask_gm always,
|
||||
// records verbs only when the run's settings allow.
|
||||
@@ -43,13 +43,33 @@ export function readSettings(runId) {
|
||||
}
|
||||
}
|
||||
|
||||
// Substitution has two classes. @ sigils are identity — @PC (the
|
||||
// character's name, settings "pc") and @Package (the display name,
|
||||
// settings "name") — first-class, never user-fillable; these two are
|
||||
// ours, and an unresolved one fails loudly. Any other @-word is the
|
||||
// author's own text — @ syntax is not owned here, users may find
|
||||
// other uses for it — and passes through untouched. $TOKENS are
|
||||
// template vars, declared by the prompts themselves: any $TOKEN found
|
||||
// in a prompt surfaces as an input in setup, and the run's settings
|
||||
// "vars" holds the answers (a package may ship defaults); an
|
||||
// unresolved $TOKEN fails loudly — the model never sees a raw var.
|
||||
function expandVars(runId, s) {
|
||||
const vars = readSettings(runId).vars ?? {};
|
||||
const settings = readSettings(runId);
|
||||
let out = String(s ?? '');
|
||||
for (const [k, v] of Object.entries(vars)) out = out.replaceAll(`$${k}`, String(v));
|
||||
const sigils = { PC: settings.pc, Package: settings.name };
|
||||
out = out.replace(/@(PC|Package)\b/g, (full, name) => {
|
||||
const v = sigils[name];
|
||||
if (v == null || !String(v).trim()) {
|
||||
const err = new Error(`unresolved @${name} — it must be set in the run's settings.json`);
|
||||
err.status = 500;
|
||||
throw err;
|
||||
}
|
||||
return 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]}`))];
|
||||
if (unresolved.length) {
|
||||
const err = new Error(`unresolved token(s): ${unresolved.join(', ')} — declare them in the run's settings.json "vars"`);
|
||||
const err = new Error(`unresolved token(s): ${unresolved.join(', ')} — fill them in setup; they save to the run's settings.json "vars"`);
|
||||
err.status = 500;
|
||||
throw err;
|
||||
}
|
||||
@@ -57,6 +77,14 @@ function expandVars(runId, s) {
|
||||
}
|
||||
export { expandVars };
|
||||
|
||||
// "La Caramba / Rell" — the run's display name; the anonymous id
|
||||
// never surfaces as a name
|
||||
export function runDisplay(runId) {
|
||||
const s = readSettings(runId);
|
||||
const pkg = runMeta(runId)?.package ?? '?';
|
||||
return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg);
|
||||
}
|
||||
|
||||
const read = (p) => {
|
||||
if (!fs.existsSync(p)) {
|
||||
const err = new Error(`missing bundle file: ${path.relative(ROOT, p)}`);
|
||||
@@ -74,8 +102,9 @@ export function assembleSystem(runId) {
|
||||
return expandVars(runId, [system, invariants, handbook].join('\n\n'));
|
||||
}
|
||||
|
||||
// the bundle: GM messages, one per file. turn-0 only on a fresh run.
|
||||
export function assembleBundle(runId, fresh) {
|
||||
// the bundle: GM messages, one per file. turn-0 never rides it — the
|
||||
// opening beat is a GM turn (sent on start), not context.
|
||||
export function assembleBundle(runId) {
|
||||
const d = runDir(runId);
|
||||
const files = [
|
||||
{ role: 'user', path: path.join(d, 'backdrop.md') },
|
||||
@@ -83,7 +112,6 @@ export function assembleBundle(runId, fresh) {
|
||||
{ role: 'user', path: path.join(d, 'canon', 'ring-b.md') },
|
||||
{ role: 'user', path: path.join(d, 'canon', 'ring-a.md') },
|
||||
];
|
||||
if (fresh) files.push({ role: 'user', path: path.join(d, 'turn-0.md') });
|
||||
return files.map((f) => ({ role: f.role, content: expandVars(runId, read(f.path)) }));
|
||||
}
|
||||
|
||||
|
||||
@@ -30,10 +30,7 @@ const readRun = (runId, f) => fs.readFileSync(path.join(runDir(runId), f), 'utf8
|
||||
export function renderTranscript(lines) {
|
||||
const L = [];
|
||||
for (const e of lines) {
|
||||
if (e.t === 'bundle') {
|
||||
if (e.part === 'turn-0') L.push('[GM: opening beat]', e.m.content, '');
|
||||
continue;
|
||||
}
|
||||
if (e.t === 'bundle') continue; // context, not exchange — provided as separate inputs
|
||||
if (e.t === 'msg') {
|
||||
if (e.m.role === 'user') {
|
||||
L.push('[GM]', e.m.content, '');
|
||||
@@ -70,7 +67,7 @@ export function buildMessages(runId, lines, stamp) {
|
||||
? 'available — this character keeps files; the archive op is valid'
|
||||
: 'none — this character keeps no files; the archive op is invalid'}. The ended session is ${stamp}.`;
|
||||
return [
|
||||
{ role: 'system', content: expandVars(runId, readRun(runId, 'housekeeper.md')) },
|
||||
{ role: 'system', content: expandVars(runId, fs.readFileSync(path.join(ROOT, 'housekeeper.md'), 'utf8').trim()) }, // substrate-internal, repo-fed
|
||||
{ role: 'user', content: runState },
|
||||
{ role: 'user', content: expandVars(runId, readRun(runId, 'character.md')) },
|
||||
{ role: 'user', content: expandVars(runId, readRun(runId, 'backdrop.md')) },
|
||||
@@ -145,6 +142,7 @@ async function callHousekeeper(ctx, runId, messages) {
|
||||
const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {});
|
||||
return data.choices[0].message.content ?? '';
|
||||
}
|
||||
export { callHousekeeper };
|
||||
|
||||
// apply -> mark housekept -> autorestart. Shared by the chain and the
|
||||
// manual apply endpoint (hand-edited manifests).
|
||||
@@ -186,7 +184,6 @@ export function latestLog(runId) {
|
||||
function mockManifest(stamp) {
|
||||
return JSON.stringify({
|
||||
window: stamp.toLowerCase(),
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.',
|
||||
touch: [{ id: 'e1', reason: 'the cuffs shaped every move she made' }],
|
||||
insert: [{
|
||||
@@ -196,3 +193,4 @@ function mockManifest(stamp) {
|
||||
}],
|
||||
});
|
||||
}
|
||||
export { mockManifest };
|
||||
|
||||
+23
-1
@@ -7,8 +7,10 @@
|
||||
// before every GM turn and rides it as a <status> block; the player's
|
||||
// <lost>/<gained> deltas apply after its final message, and any
|
||||
// conflicts ride the next GM turn as a <conflict> block.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { clerkJson } from './clerk.mjs';
|
||||
import { toolList, runTool, readSettings } from './bundle.mjs';
|
||||
import { toolList, runTool, readSettings, runDir, expandVars } from './bundle.mjs';
|
||||
import { renderView } from './session.mjs';
|
||||
|
||||
export class HttpError extends Error {
|
||||
@@ -38,6 +40,26 @@ export async function gmTurn(ctx, runId, line) {
|
||||
return runLoop(ctx, runId);
|
||||
}
|
||||
|
||||
// the opening beat: turn-0 sent as the first GM turn, separate from
|
||||
// the bundle (start = open window, then this). Its trailing <status>
|
||||
// block was ingested as her opening paper at window-open — stripped
|
||||
// here, since the normal ride carries the current paper on every GM
|
||||
// turn, the beat included.
|
||||
export async function turn0(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.fresh) throw new HttpError(409, 'turn-0 opens a fresh run only');
|
||||
if (s.lines.some((e) => e.t === 'msg' && e.m.role === 'user')) {
|
||||
throw new HttpError(409, 'a GM line already exists — the opening beat was sent, or the GM spoke first');
|
||||
}
|
||||
const file = path.join(runDir(runId), 'turn-0.md');
|
||||
if (!fs.existsSync(file)) throw new HttpError(404, 'this run has no turn-0.md — narrate the opening yourself (POST /turn)');
|
||||
let text = expandVars(runId, fs.readFileSync(file, 'utf8')); // $NAME tokens resolve like every bundle file
|
||||
const sm = text.match(/<status>[\s\S]*?<\/status>/);
|
||||
if (sm) text = text.replace(sm[0], '');
|
||||
return gmTurn(ctx, runId, text.trim());
|
||||
}
|
||||
|
||||
export async function answerAsk(ctx, runId, answer) {
|
||||
const s = needSession(ctx, runId);
|
||||
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
|
||||
|
||||
+216
-13
@@ -1,10 +1,9 @@
|
||||
// server/main.mjs — entry + REST spine.
|
||||
//
|
||||
// Loopback, single-human, synchronous JSON. The SPA (later) and curl
|
||||
// are both just clients. Boot-rebuild: every run whose latest session
|
||||
// was not housekept gets its open window back from the jsonl — the log
|
||||
// is the truth, the context is a view. Housekeeping endpoints answer
|
||||
// 501 until phase 3 lands the job.
|
||||
// Loopback, single-human, synchronous JSON. The SPA and curl are both
|
||||
// just clients. Boot-rebuild: every run whose latest session was not
|
||||
// housekept gets its open window back from the jsonl — the log is the
|
||||
// truth, the context is a view.
|
||||
//
|
||||
// usage: node server/main.mjs [--mock]
|
||||
import fs from 'node:fs';
|
||||
@@ -16,7 +15,7 @@ import { clerkRaw, clerkRawJson, clerkJson } from './clerk.mjs';
|
||||
import * as bundle from './bundle.mjs';
|
||||
import * as session from './session.mjs';
|
||||
import * as housekeeping from './housekeeping.mjs';
|
||||
import { gmTurn, answerAsk, HttpError } from './loop.mjs';
|
||||
import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const MOCK = process.argv.includes('--mock');
|
||||
@@ -103,7 +102,12 @@ function serveStatic(pathname, res) {
|
||||
if (!rel) rel = 'index.html';
|
||||
const file = path.resolve(WEB_DIR, rel);
|
||||
if (!file.startsWith(WEB_DIR + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
||||
send(res, 404, { error: `no such file: ${rel}` });
|
||||
// SPA fallback: client-side routes are extensionless paths —
|
||||
// serve the shell; anything that looks like a file stays a 404
|
||||
if (path.extname(rel)) { send(res, 404, { error: `no such file: ${rel}` }); return; }
|
||||
const shell = fs.readFileSync(path.join(WEB_DIR, 'index.html'));
|
||||
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': shell.length });
|
||||
res.end(shell);
|
||||
return;
|
||||
}
|
||||
const data = fs.readFileSync(file);
|
||||
@@ -113,21 +117,63 @@ function serveStatic(pathname, res) {
|
||||
|
||||
// --- routes -------------------------------------------------------------------
|
||||
|
||||
route('GET', '/api', async () => ({ service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size }));
|
||||
route('GET', '/api', async () => ({
|
||||
service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size,
|
||||
// the live window inventory — debugging state divergence at a glance
|
||||
windows: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
|
||||
}));
|
||||
|
||||
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
|
||||
|
||||
route('GET', '/api/packages', async () => clerkRawJson('packages'));
|
||||
route('GET', '/api/runs', async () => clerkRawJson('runs'));
|
||||
|
||||
// the repo-fed prompts, read-only: per-project opening + guards and
|
||||
// substrate invariants — never copied into a run, so the editor shows
|
||||
// them as context, not as something to edit
|
||||
route('GET', '/api/prompts', async () => ({
|
||||
system: fs.readFileSync(path.join(ROOT, 'system.md'), 'utf8').trim(),
|
||||
invariants: fs.readFileSync(path.join(ROOT, 'invariants.md'), 'utf8').trim(),
|
||||
}));
|
||||
|
||||
// the clerk's list, enriched with what the server already knows: the
|
||||
// open window, the pending ask, and the housekeeping bookkeeping. A
|
||||
// run with no sessions is a draft — created, never started.
|
||||
route('GET', '/api/runs', async () => {
|
||||
const runs = clerkRawJson('runs');
|
||||
for (const r of runs) {
|
||||
const s = ctx.sessions.get(r.id);
|
||||
r.open = !!s;
|
||||
r.window = s?.stamp ?? null;
|
||||
r.fresh = s?.fresh ?? false;
|
||||
r.pendingAsk = s?.pendingAsk?.question ?? null;
|
||||
r.lastSession = session.latestSession(r.id);
|
||||
r.lastHousekept = session.lastHousekept(r.id);
|
||||
}
|
||||
return runs;
|
||||
});
|
||||
|
||||
// create: the pc's name is required (unique per package); the
|
||||
// package display name defaults to the package's own. The id is
|
||||
// anonymous, generated by the clerk.
|
||||
route('POST', '/api/runs', async ({ body }) => {
|
||||
const name = String(body.name ?? '').trim();
|
||||
const pkg = String(body.package ?? '').trim();
|
||||
if (!/^[a-z0-9-]+$/.test(name)) throw new HttpError(400, 'name must be a slug (lowercase letters, digits, dashes)');
|
||||
const pc = String(body.pc ?? '').trim();
|
||||
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages');
|
||||
const r = clerkRaw('create', pkg, name, ...(body.model ? [String(body.model)] : []));
|
||||
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 r = clerkRaw('--json', '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');
|
||||
return { run: bundle.runMeta(name), dir: `runs/${name}` };
|
||||
const run = JSON.parse(r.out);
|
||||
return { run, dir: `runs/${run.id}` };
|
||||
});
|
||||
|
||||
// a name to play as: rolled from the dictionary, unused by any run
|
||||
route('GET', '/api/names', async () => {
|
||||
const all = fs.readFileSync(path.join(ROOT, 'names-female.txt'), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean);
|
||||
const used = new Set(clerkRawJson('runs').flatMap((r) => (r.pc ? [String(r.pc).toLowerCase()] : [])));
|
||||
const free = all.filter((n) => !used.has(n.toLowerCase()));
|
||||
const pool = free.length ? free : all; // a fully-used dictionary still suggests
|
||||
return { name: pool[Math.floor(Math.random() * pool.length)] };
|
||||
});
|
||||
|
||||
route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
@@ -138,7 +184,10 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
const meta = bundle.runMeta(id);
|
||||
return {
|
||||
run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null },
|
||||
display: bundle.runDisplay(id),
|
||||
open: !!s,
|
||||
draft: session.latestSession(id) === null,
|
||||
lastSession: session.latestSession(id),
|
||||
window: s?.stamp ?? null,
|
||||
fresh: s?.fresh ?? false,
|
||||
paper: st.paper,
|
||||
@@ -155,6 +204,96 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
};
|
||||
});
|
||||
|
||||
// --- run files: the editor's surface ------------------------------------------
|
||||
//
|
||||
// A fixed whitelist, not a path API: state dirs are the clerk's
|
||||
// alone. Craft files are writable; housekeeper.md is substrate-
|
||||
// internal (repo-fed at wrap, never copied, not exposed here) and
|
||||
// gm.md lives only in the notepad endpoints (the play-view pad);
|
||||
// config is read-only (vars and lineage are easy to break blind).
|
||||
// JSON writes are validated before landing.
|
||||
|
||||
const RUN_FILES = {
|
||||
'backdrop.md': 'rw',
|
||||
'character.md': 'rw',
|
||||
'turn-0.md': 'rw',
|
||||
'seed.json': 'rw',
|
||||
'handbook.md': 'rw',
|
||||
'settings.json': 'ro',
|
||||
'run.json': 'ro',
|
||||
};
|
||||
|
||||
route('GET', '/api/runs/:id/files', async ({ params }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
const files = {};
|
||||
for (const [f, mode] of Object.entries(RUN_FILES)) {
|
||||
const p = path.join(dir, f);
|
||||
files[f] = fs.existsSync(p)
|
||||
? { mode, exists: true, content: fs.readFileSync(p, 'utf8') }
|
||||
: { mode, exists: false };
|
||||
}
|
||||
return { files };
|
||||
});
|
||||
|
||||
route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
const f = params.path;
|
||||
const mode = RUN_FILES[f];
|
||||
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
|
||||
if (mode !== 'rw') throw new HttpError(403, `${f} is read-only`);
|
||||
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
|
||||
if (f.endsWith('.json')) {
|
||||
try { JSON.parse(body.content); } catch { throw new HttpError(400, `${f} rejected: not valid JSON`); }
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, f), body.content);
|
||||
return { ok: true, file: f, bytes: Buffer.byteLength(body.content) };
|
||||
});
|
||||
|
||||
// prompt vars: the inputs the prompts themselves declare ($TOKENS
|
||||
// found in any prompt file). Values live in the run's settings vars.
|
||||
route('POST', '/api/runs/:id/vars', async ({ params, body }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
const vars = body.vars;
|
||||
if (typeof vars !== 'object' || vars === null || Array.isArray(vars)) throw new HttpError(400, 'vars (an object of token -> value) is required');
|
||||
for (const [k, v] of Object.entries(vars)) {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(k)) throw new HttpError(400, `bad var name: ${JSON.stringify(k)}`);
|
||||
if (typeof v !== 'string') throw new HttpError(400, `var ${k} must be a string`);
|
||||
}
|
||||
const settings = bundle.readSettings(params.id);
|
||||
settings.vars = { ...(settings.vars ?? {}), ...vars };
|
||||
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
||||
return { ok: true, vars: settings.vars };
|
||||
});
|
||||
|
||||
// the GM's notepad: the run's gm.md — always editable in the SPA,
|
||||
// never in any bundle, never sent to any model (no assembly path
|
||||
// reads it). Seeded from the package at creation, the GM's to keep.
|
||||
route('GET', '/api/runs/:id/notes', async ({ params }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
const file = path.join(dir, 'gm.md');
|
||||
return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' };
|
||||
});
|
||||
|
||||
route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
|
||||
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// delete a DRAFT: a run with no sessions holds nothing but its copy,
|
||||
// so the directory is the whole run and removal is complete. A played
|
||||
// run is a story — deleting one is a deliberate act that stays by
|
||||
// hand (Remove-Item runs/<id>), not a button.
|
||||
route('DELETE', '/api/runs/:id', async ({ params }) => {
|
||||
const dir = bundle.requireRun(params.id);
|
||||
if (session.latestSession(params.id) !== null) {
|
||||
throw new HttpError(409, `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
return { ok: true, deleted: params.id };
|
||||
});
|
||||
|
||||
route('POST', '/api/runs/:id/windows', async ({ params, body }) => {
|
||||
const id = params.id;
|
||||
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
|
||||
@@ -185,6 +324,10 @@ route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
|
||||
return { ok: true, ...(await gmTurn(ctx, params.id, line)) };
|
||||
});
|
||||
|
||||
// the opening beat as its own action: sent as the first GM turn on a
|
||||
// fresh window — "start" is this right after window-open
|
||||
route('POST', '/api/runs/:id/turn0', async ({ params }) => ({ ok: true, ...(await turn0(ctx, params.id)) }));
|
||||
|
||||
route('POST', '/api/runs/:id/ask', async ({ params, body }) => {
|
||||
const answer = String(body.answer ?? '').trim();
|
||||
if (!answer) throw new HttpError(400, 'answer is required');
|
||||
@@ -197,12 +340,64 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
|
||||
return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null };
|
||||
});
|
||||
|
||||
// the GM's out-of-band paper override: whole-paper replace via the
|
||||
// clerk (which journals the prior state). Descriptions never contain
|
||||
// commas — the transport is comma-separated — so a comma inside an
|
||||
// item is a 400, not a silent corruption later.
|
||||
route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
const items = body.items;
|
||||
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
|
||||
for (const it of items) {
|
||||
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
|
||||
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
||||
}
|
||||
const paper = clerkJson(id, '--gm', 'paper-set', ...items);
|
||||
return { ok: true, paper };
|
||||
});
|
||||
|
||||
route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
|
||||
// ends the window and kicks the async chain; poll GET for the outcome
|
||||
const job = housekeeping.trigger(ctx, params.id);
|
||||
return { state: job.state, session: job.session };
|
||||
});
|
||||
|
||||
// dry-run the housekeeper over a session log: the same transcript
|
||||
// assembly the real wrap uses, a real housekeeper call, the manifest
|
||||
// saved for review — but nothing applied, no window ended, no state
|
||||
// touched. The way to iterate on housekeeper.md against real data
|
||||
// without playing more; works on the open window too.
|
||||
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
|
||||
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
|
||||
let lines;
|
||||
try {
|
||||
lines = session.loadSession(id, stamp).lines;
|
||||
} catch {
|
||||
throw new HttpError(404, `no such session: ${stamp}`);
|
||||
}
|
||||
if (!lines.some((e) => e.t === 'msg')) throw new HttpError(409, 'that session has no exchange to review');
|
||||
const dir = path.join(bundle.runDir(id), 'manifests');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const text = ctx.mock
|
||||
? housekeeping.mockManifest(stamp)
|
||||
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp));
|
||||
let mf;
|
||||
try {
|
||||
mf = housekeeping.parseManifest(text);
|
||||
} catch (e) {
|
||||
const raw = path.join(dir, `${stamp}.replay.raw.md`);
|
||||
fs.writeFileSync(raw, String(text));
|
||||
return { ok: true, parsed: false, session: stamp, file: `manifests/${stamp}.replay.raw.md`, reason: e.message };
|
||||
}
|
||||
const file = path.join(dir, `${stamp}.replay.json`);
|
||||
fs.writeFileSync(file, JSON.stringify(mf, null, 2) + '\n');
|
||||
return { ok: true, parsed: true, session: stamp, file: `manifests/${stamp}.replay.json`, manifest: mf };
|
||||
});
|
||||
|
||||
route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id));
|
||||
|
||||
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
|
||||
@@ -233,8 +428,16 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
|
||||
// --- dispatch -------------------------------------------------------------------
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
// the request log: one line per API call — reconstruct any session
|
||||
// from the console output after the fact
|
||||
res.on('finish', () => {
|
||||
if (url.pathname.startsWith('/api')) {
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
|
||||
}
|
||||
});
|
||||
if (!url.pathname.startsWith('/api')) {
|
||||
if (req.method !== 'GET') throw new HttpError(405, 'static files are GET-only');
|
||||
serveStatic(url.pathname, res);
|
||||
|
||||
+21
-7
@@ -101,8 +101,10 @@ export function openWindow(runId, override = false) {
|
||||
}
|
||||
|
||||
const system = { role: 'system', content: assembleSystem(runId) };
|
||||
const bundle = assembleBundle(runId, fresh);
|
||||
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a', ...(fresh ? ['turn-0'] : [])];
|
||||
const bundle = assembleBundle(runId);
|
||||
// turn-0 is not a bundle part: the opening beat is sent as the
|
||||
// first GM turn (POST /api/runs/<id>/turn0) when play starts
|
||||
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
|
||||
const s = makeSession(runId, stamp());
|
||||
s.fresh = fresh;
|
||||
fs.mkdirSync(sessionsDir(runId), { recursive: true });
|
||||
@@ -131,6 +133,10 @@ export function loadSession(runId, st) {
|
||||
}
|
||||
}
|
||||
derive(s);
|
||||
// fresh survives a restart: this window is the run's first iff no
|
||||
// earlier session log exists (derive() can't know — it sees one log)
|
||||
const files = fs.readdirSync(sessionsDir(runId)).filter((f) => f.endsWith('.jsonl')).sort();
|
||||
s.fresh = files.length === 1 && files[0] === `${st}.jsonl`;
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -164,10 +170,14 @@ const STRIP_BLOCKS = /\n?<(status|conflict)>[\s\S]*?<\/\1>\n?/g;
|
||||
|
||||
export function renderView(s, keepToolResults = 4) {
|
||||
const toolIdx = [];
|
||||
s.lines.forEach((e, i) => { if (e.t === 'tool') toolIdx.push(i); });
|
||||
let lastGmIdx = -1;
|
||||
s.lines.forEach((e, i) => {
|
||||
if (e.t === 'tool') toolIdx.push(i);
|
||||
if (e.t === 'msg' && e.m.role === 'user') lastGmIdx = i;
|
||||
});
|
||||
const keep = new Set(toolIdx.slice(-keepToolResults));
|
||||
const msgs = [];
|
||||
for (const e of s.lines) {
|
||||
for (const [i, e] of s.lines.entries()) {
|
||||
if (e.t === 'bundle') {
|
||||
msgs.push({ role: e.m.role, content: e.m.content });
|
||||
} else if (e.t === 'msg') {
|
||||
@@ -176,13 +186,17 @@ export function renderView(s, keepToolResults = 4) {
|
||||
const m = { role: 'assistant', content: e.m.content ?? null };
|
||||
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
||||
msgs.push(m);
|
||||
} else if (i === lastGmIdx) {
|
||||
// the newest GM turn keeps its blocks as-sent: the current
|
||||
// paper rides it, and a pending conflict rides it — the
|
||||
// model must see both
|
||||
msgs.push({ role: e.m.role, content: e.m.content.trim() });
|
||||
} else {
|
||||
// GM-side: old status/conflict blocks elide — the current
|
||||
// paper rides the newest GM turn
|
||||
// older GM turns: status/conflict blocks elide
|
||||
msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() });
|
||||
}
|
||||
} else if (e.t === 'tool') {
|
||||
if (e.ask || keep.has(s.lines.indexOf(e))) {
|
||||
if (e.ask || keep.has(i)) {
|
||||
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: e.m.content });
|
||||
} else {
|
||||
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: '[elided: earlier tool result]' });
|
||||
|
||||
Reference in New Issue
Block a user