Files
tiny-worlds/server/session.mjs
T

237 lines
9.5 KiB
JavaScript

// server/session.mjs — a window's live state.
//
// The append-only jsonl is the truth; the in-memory context is a view
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
// note) so later features (turn surgery) can append their own kinds
// without a format migration. The view renderer is pure policy over
// the log: thinking never goes back, old tool results elide to stubs
// (the last few and every ask_gm answer stay), old GM-side
// <status>/<conflict> blocks elide — the current paper rides the
// newest GM turn.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { clerk, clerkTry, clerkJson } from './clerk.mjs';
import { runDir, requireRun, assembleSystem, assembleBundle } from './bundle.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const sessionsDir = (runId) => path.join(runDir(runId), 'sessions');
const sessionFile = (runId, s) => path.join(sessionsDir(runId), `${s}.jsonl`);
export function latestSession(runId) {
const dir = sessionsDir(runId);
if (!fs.existsSync(dir)) return null;
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')).sort();
return files.length ? files[files.length - 1].replace(/\.jsonl$/, '') : null;
}
function readState(runId) {
try {
return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'state.json'), 'utf8'));
} catch {
return {};
}
}
export const lastHousekept = (runId) => readState(runId).lastHousekeptSession ?? null;
export function markHousekept(runId, stamp) {
const state = readState(runId);
state.lastHousekeptSession = stamp;
fs.writeFileSync(path.join(runDir(runId), 'state.json'), JSON.stringify(state, null, 2) + '\n');
}
// --- session object ----------------------------------------------------------
function makeSession(runId, st) {
return {
runId,
stamp: st,
file: sessionFile(runId, st),
lines: [],
pendingAsk: null, // { callId, question, calls } — the whole batch pauses
usage: null, // { promptTokens, completionTokens } from the last response
fresh: false,
append(entry) {
this.lines.push(entry);
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
},
};
}
// --- open a window -----------------------------------------------------------
// The #21 guard: opening over an unhousekept session means that
// transcript never reaches the rings — refuse and name it, unless the
// caller explicitly overrides (the deliberate skip).
export function openWindow(runId, override = false) {
requireRun(runId);
const latest = latestSession(runId);
if (latest && latest !== (readState(runId).lastHousekeptSession ?? null) && !override) {
const err = new Error(`the previous window (${latest}) was never housekept — its transcript would never reach the rings`);
err.status = 409;
err.detail = { session: latest, hint: 'housekeep it first, or POST with {"override": true} to deliberately skip it' };
throw err;
}
const notes = [];
const fresh = latest === null;
if (fresh) {
// lazy seed: applies at the first window-open, before render and
// assembly, so the bundle sees populated rings. The clerk refuses
// on history (a hand-prepped run), which is the opt-out.
if (fs.existsSync(path.join(runDir(runId), 'seed.json'))) {
const r = clerkTry(runId, 'seed');
notes.push({ kind: 'seed', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
if (fs.existsSync(path.join(runDir(runId), 'turn-0.md'))) {
const r = clerkTry(runId, 'paper-ingest', path.join(runDir(runId), 'turn-0.md'));
notes.push({ kind: 'ingest', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
}
const r = clerkTry(runId, 'render');
if (r.code !== 0) {
const err = new Error(r.err || 'render failed');
err.status = 500;
throw err;
}
const system = { role: 'system', content: assembleSystem(runId) };
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 });
s.append({ t: 'note', kind: 'window', at: s.stamp, fresh });
for (const n of notes) s.append({ t: 'note', kind: n.kind, ok: n.ok, detail: n.detail });
s.append({ t: 'bundle', m: system, part: 'system' });
for (let i = 0; i < bundle.length; i++) s.append({ t: 'bundle', m: bundle[i], part: partNames[i] });
return s;
}
// --- boot-rebuild ------------------------------------------------------------
export function loadSession(runId, st) {
const s = makeSession(runId, st);
if (!fs.existsSync(s.file)) {
const err = new Error(`no session log: ${path.relative(ROOT, s.file)}`);
err.status = 404;
throw err;
}
for (const line of fs.readFileSync(s.file, 'utf8').split('\n')) {
if (!line.trim()) continue;
try {
s.lines.push(JSON.parse(line));
} catch {
// a torn tail line (crash mid-append) is skipped, not fatal
}
}
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;
}
// rebuild the derived state from the log alone
function derive(s) {
let pending = null;
for (const e of s.lines) {
if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) {
const ask = e.m.tool_calls.find((c) => c.function.name === 'ask_gm');
if (ask) {
let q = '(no question)';
try { q = JSON.parse(ask.function.arguments || '{}').question ?? q; } catch {}
pending = { callId: ask.id, question: q, calls: e.m.tool_calls };
}
} else if (e.t === 'tool' && pending && e.m.tool_call_id === pending.callId) {
pending = null;
} else if (e.t === 'msg' && e.usage) {
s.usage = { promptTokens: e.usage.prompt_tokens, completionTokens: e.usage.completion_tokens };
}
}
s.pendingAsk = pending;
}
// --- the view renderer: log + policy -> per-call context ---------------------
const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g;
export function renderView(s, keepToolResults = 4) {
const toolIdx = [];
const reminderIdx = [];
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;
if (e.t === 'msg' && e.reminder) reminderIdx.push(i);
});
const keep = new Set(toolIdx.slice(-keepToolResults));
const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1;
const msgs = [];
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') {
if (e.reminder) {
// the per-turn reminder: only the newest copy lives in the
// context — superseded ones elide (identical content, freshest
// position, exactly like the papers)
if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() });
} else if (e.m.role === 'assistant') {
// thinking never goes back; the log keeps it
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 (e.conflictOnly) {
// transient error traffic: visible while it is the latest word
// (the model answers it), elided entirely once the story moves
// on — the log keeps it for provenance
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else if (i === lastGmIdx) {
// the newest GM turn keeps its blocks as-sent: the current
// paper and agenda ride it
msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else {
// older GM turns: status/agenda/conflict blocks elide
msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() });
}
} else if (e.t === 'tool') {
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]' });
}
}
}
validatePairing(msgs, s.pendingAsk?.callId);
return msgs;
}
// tool-call pairing is never broken (the endpoint tolerates orphans
// silently — probed 2026-11-12 — so this one fails quiet unless we check)
function validatePairing(msgs, pendingCallId) {
const calls = new Set();
const results = new Set();
for (const m of msgs) {
if (m.role === 'assistant' && m.tool_calls) for (const c of m.tool_calls) calls.add(c.id);
if (m.role === 'tool') results.add(m.tool_call_id);
}
for (const id of results) {
if (!calls.has(id)) throw new Error(`context invariant violated: orphaned tool result ${id}`);
}
for (const id of calls) {
if (!results.has(id) && id !== pendingCallId) {
throw new Error(`context invariant violated: tool call ${id} has no result`);
}
}
}
export { clerkJson };