196 lines
9.3 KiB
JavaScript
196 lines
9.3 KiB
JavaScript
// server/loop.mjs — the turn loop.
|
|
//
|
|
// Synchronous REST: a POST runs the tool loop and returns. ask_gm
|
|
// pauses mid-turn — the whole tool-call batch waits (pairing stays
|
|
// sound), the request returns with the pending question, and the
|
|
// answer call resumes the loop. The paper is re-read from the clerk
|
|
// 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, runDir, expandVars, assembleReminder } from './bundle.mjs';
|
|
import { renderView } from './session.mjs';
|
|
|
|
export class HttpError extends Error {
|
|
constructor(status, message, detail) {
|
|
super(message);
|
|
this.status = status;
|
|
this.detail = detail;
|
|
}
|
|
}
|
|
|
|
function needSession(ctx, runId) {
|
|
const s = ctx.sessions.get(runId);
|
|
if (!s) throw new HttpError(409, `no open window for run '${runId}' — POST /api/runs/${runId}/windows first`);
|
|
return s;
|
|
}
|
|
|
|
export async function gmTurn(ctx, runId, line, user) {
|
|
const s = needSession(ctx, runId);
|
|
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
|
|
const paper = clerkJson(runId, 'paper'); // fresh per turn
|
|
const agenda = clerkJson(runId, 'agenda'); // fresh per turn
|
|
// the wire renders the queue as the model cites it: numbered from the top
|
|
const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; ');
|
|
const content = `${line.trim()}\n\n<status>${paper.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
|
|
s.append({ t: 'msg', m: { role: 'user', content } });
|
|
// the reminder follows the GM's prose as its own system chunk —
|
|
// every turn, one live copy (older ones elide in the view)
|
|
const reminder = assembleReminder(runId);
|
|
if (reminder) s.append({ t: 'msg', m: { role: 'system', content: reminder }, reminder: true });
|
|
return runLoop(ctx, runId, user);
|
|
}
|
|
|
|
// 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, user) {
|
|
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(), user);
|
|
}
|
|
|
|
export async function answerAsk(ctx, runId, answer, user) {
|
|
const s = needSession(ctx, runId);
|
|
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
|
|
// execute the paused batch: the ask gets the answer, its siblings
|
|
// (if any) get dispatched now — pairing stays whole
|
|
for (const call of s.pendingAsk.calls) {
|
|
if (call.id === s.pendingAsk.callId) {
|
|
s.append({ t: 'tool', ask: true, m: { role: 'tool', tool_call_id: call.id, content: answer } });
|
|
} else {
|
|
s.append({ t: 'tool', m: { role: 'tool', tool_call_id: call.id, content: runTool(runId, call) } });
|
|
}
|
|
}
|
|
s.pendingAsk = null;
|
|
return runLoop(ctx, runId, user);
|
|
}
|
|
|
|
async function runLoop(ctx, runId, user) {
|
|
const s = ctx.sessions.get(runId);
|
|
const tools = toolList(runId);
|
|
const out = { tools: [] };
|
|
let heals = 0;
|
|
for (;;) {
|
|
const view = renderView(s);
|
|
let msg;
|
|
if (ctx.mock) {
|
|
msg = mockModel(s, view);
|
|
} else {
|
|
const model = resolveModel(ctx, runId);
|
|
// attribution (#22): every LLM call names the acting user
|
|
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
|
|
const data = await ctx.provider.chat(model, view, tools, ctx.cfg.params ?? {});
|
|
msg = data.choices[0].message;
|
|
s.usage = data.usage
|
|
? { promptTokens: data.usage.prompt_tokens, completionTokens: data.usage.completion_tokens }
|
|
: null;
|
|
}
|
|
s.append({ t: 'msg', m: msg, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
|
|
|
|
if (msg.tool_calls?.length) {
|
|
const ask = msg.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 {}
|
|
s.pendingAsk = { callId: ask.id, question: q, calls: msg.tool_calls };
|
|
s.append({ t: 'note', kind: 'ask', question: q });
|
|
out.pendingAsk = q;
|
|
return out; // the turn request returns with the question
|
|
}
|
|
for (const call of msg.tool_calls) {
|
|
out.tools.push(call.function.name);
|
|
s.append({ t: 'tool', m: { role: 'tool', tool_call_id: call.id, content: runTool(runId, call) } });
|
|
}
|
|
continue; // let the model see the results before ending its turn
|
|
}
|
|
|
|
// final player message — the paper and agenda deltas ride the turn
|
|
// text. Same-verb blocks combine into one apply (the clerk's
|
|
// collectors gather every block before executing anything), never a
|
|
// sequence of applies.
|
|
const text = msg.content ?? '';
|
|
const carry = [];
|
|
if (/<(lost|gained)>/.test(text)) {
|
|
const r = clerkJson(runId, 'paper-apply', text);
|
|
s.append({ t: 'note', kind: 'paper', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
|
|
carry.push(...(r.conflicts ?? []));
|
|
}
|
|
if (/<(add|drop)>/.test(text)) {
|
|
const r = clerkJson(runId, 'agenda-apply', text);
|
|
s.append({ t: 'note', kind: 'agenda', applied: { added: r.added, dropped: r.dropped, evicted: r.evicted }, conflicts: r.conflicts });
|
|
carry.push(...(r.conflicts ?? []));
|
|
}
|
|
if (carry.length && heals < 3) {
|
|
// a conflict answers for itself: it goes back as its own message,
|
|
// not attached to a GM turn — clean of prose, easy to read, easy
|
|
// to heal. Capped so a confused model cannot ping-pong forever.
|
|
heals++;
|
|
s.append({ t: 'msg', m: { role: 'user', content: `<conflict>${carry.join('; ')}</conflict>` }, conflictOnly: true });
|
|
continue;
|
|
}
|
|
if (carry.length) out.conflicts = carry; // healing gave up — the transcript shows it
|
|
out.player = text;
|
|
return out;
|
|
}
|
|
}
|
|
|
|
function resolveModel(ctx, runId) {
|
|
const meta = ctx.runMeta(runId) ?? {};
|
|
return meta.models?.player ?? ctx.cfg.models?.player ?? null;
|
|
}
|
|
|
|
// --- the mock model ----------------------------------------------------------
|
|
//
|
|
// A scripted stand-in that exercises the loop without a key: turn one
|
|
// rolls, turn two asks (the pause/resume path), the answer lands with
|
|
// paper deltas (the tag transport), everything after is plain prose.
|
|
function mockModel(s, view) {
|
|
const call = (name, args, id) => ({
|
|
role: 'assistant',
|
|
content: null,
|
|
tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
|
|
});
|
|
const assistantCount = s.lines.filter((e) => e.t === 'msg' && e.m.role === 'assistant').length;
|
|
const toolResults = view.filter((m) => m.role === 'tool').length;
|
|
if (assistantCount === 0 && toolResults === 0) {
|
|
return call('roll', { options: ['press on along the hull', 'double back to the container'] }, `mock-roll-${s.lines.length}`);
|
|
}
|
|
if (assistantCount === 1 && toolResults >= 1) {
|
|
return { role: 'assistant', content: 'Mock: the coin says press on. *She presses on, palms flat against the warm metal.*' };
|
|
}
|
|
if (assistantCount === 2) {
|
|
return call('ask_gm', { question: 'From where she stands, does the deck look clear toward the bow?' }, `mock-ask-${s.lines.length}`);
|
|
}
|
|
if (assistantCount === 3) {
|
|
// two <gained> and two <add> blocks on one turn: same-verb blocks
|
|
// combine into one apply, never a sequence — the smoke asserts the
|
|
// merged, order-preserving result
|
|
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<lost>worried</lost>\n<gained>settled</gained>\n<gained>curious about the clicking</gained>\n<add>find fresh water</add>\n<add>signal any passing ship, build a shelter</add>' };
|
|
}
|
|
if (assistantCount === 4) {
|
|
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<drop>0</drop>' };
|
|
}
|
|
if (assistantCount === 5) {
|
|
return { role: 'assistant', content: 'Mock: *She squints at the horizon.*\n<drop>9</drop>' };
|
|
}
|
|
if (assistantCount === 6) {
|
|
// the self-heal: this fires in answer to the conflict-only message
|
|
return { role: 'assistant', content: 'Mock: *She shakes her head — no such thing on the list.*\n<drop>0, 1</drop>' };
|
|
}
|
|
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
|
|
}
|