Files
tiny-worlds/server/loop.mjs
T
mute eefb721675 the sheet round: the GM's ledger of arbitrated run state -- the second state channel, split from status and agenda by truth model (GM, 2026-11-17). The rulings first: status and agenda are narrative self-report (their truth is "she said so", the scan caches her latest words); the sheet is actual run state (its truth is "the GM set so", the record IS the truth event -- nothing cached from anyone's words). The override channel promoted to a standing section, and that precedent decided the presentation: the sheet renders as its OWN authoritative system chunk at the freshest end, never a canon-point stamp, which would read as her words -- the same reason the override composes as hers and the sheet never does. Schemaless JSON in the tag (the mind-verb philosophy: the substrate teaches the channel, the package teaches the vocabulary -- the invariants rule the GM wrote is one universal paragraph with deliberately non-box examples, clothes and grades, and the propose-additions line as her schema-evolution channel); details learnt in-place; NO package gating -- the channel is universal and "optional, if given" makes the invariant forward-compatible in every bundle that never sets one. The build: a sheet record rides the GM turn like the override (readSheet: object-ness is the route's only law, 400 loud on arrays and scalars, nothing appended; OOC turns refuse it exactly like block edits); scanState derives newest-wins whole-set -- an absent key drops, never keeps, and {} is a live empty ledger (a truthy check, never falsy); the boundary state note carries it across stops and the dormant read path serves it; renderView appends the chunk once per assembly so one live copy holds by construction; the guard is the <model> sibling (an emitted <sheet> conflicts with "the GM's ledger -- propose changes in prose", healed in-turn, cap 3, and her emission never applies -- the scan holds the GM's record); every strip surface learned the tag (the view's STRIP_HERS, the story's verbs, the table's chip regex -- the standing grep-every-strip-list lesson, applied); and the web gains sheetEditor, the paneEditor's JSON sibling in widgets.mjs (same stage/pending/discard pattern, bad JSON refuses at the stage), the third pane in the aside, the send attaching body.sheet, and [sheet] machinery lines on both table and raw walks. The mock's sheet-guard branch is CUE-KEYED, not position-keyed: the carried tail shifts the script's counts (session 4's log starts the script over -- the battery's first attempt landed on the ask position and crashed renderView on the unpaired call; the battery now answers the script ask and moves on), while a marked GM turn is immune to every shift -- mockModel reads the view, the marked turn earns the emission, the conflict it earns earns the plain-prose heal. check-reminder is sheet-aware (the chunk is a legitimate third system surface; the count and freshest-end assertions tolerate exactly one, and the freshest-end check now allows her latest reply and/or the chunk to follow the reminder). Verified: smoke ALL PASS with +15 sheet assertions (newest-wins, whole-set semantics, the chunk one-live-copy -- ANCHORED with startsWith because the invariants bundle itself mentions the tag and a bare regex matches it twice, an honest test bug caught by an honest test), the guard's conflict and heal with her emission kept verbatim in the raw log and never applied, the view and story strips, the empty ledger rendering its chunk, the boundary note carrying the sheet, the dormant read deriving it, and session 5 deriving it from the carried note end to end), restart + reminder checks green, typecheck green on both programs, check-repo clean (it caught the round's own prose twice: "window" is a retired term in README, the contwin vocabulary wins), and a browser pass over the pane end to end with zero console errors -- staging, the pending marker, the ride, the scan re-render, and both machinery lines on the table. Docs: README's protocol passage carries the sheet with the numbers-live-on-the-sheet line (prose numbers die with the contwin; sheet numbers ride the scan forever) -- NOT in the memory tiers table, where the first draft wrongly put it (the GM's ruling: the sheet belongs in neither memories nor records); the identity tier lost its loose "character sheet" name now that the term is technical; DICTIONARY gains the sheet entry with the history line (dice retired into variant literature, sheets arrived as the state machinery -- the tabletop metaphor completing while its realism stays advisory, players hold their own pencils in the real thing and we don't, for drift); ROADMAP parks the bookkeeper extension (the housekeeper's arithmetic sibling: reads the setting's rules prose and the latest turns, computes the ledger delta from a purchase in her prose, lands it as a STAGED edit -- applied on the GM's next turn or discarded; sheet-only authority, curator fallback, per-package opt-in because an agent cannot bookkeep what is not arithmetic). The GM's prompt-side edits ride the same commit: invariants' "Character's sheet" section (the universal rule, the trailing-clause flag taken in review), the reminder's inventory line gaining "the sheet (optional)", and la caramba's gm.md lore updates. The box package (the first consumer) and detention stay untracked WIP, untouched. The 2026-11-17 roadmap audit rides the same commit (GM: "done items can retire"): retired outright -- the SPA-vs-bridge and voice-examples decisions (long resolved) and steal items #1, #3, #4, #8, #11 (done, or in #8's case never work -- the housekeeper model is per-run selection, built); retired with tombstones -- the multiuser section (built 2026-11-14, the rulings live in DECISIONS #22-31 and README, the lifecycle tail kept visible) and the SPA v1 section (all four phases done, the API sketch superseded by README's living API docs, the substrate doctrine in README), with the one unbuilt design it held -- the turn-surgery saga rule -- surviving as its own bullet cross-referenced at steal #2; amended in place, dated -- seed.json (dead, successors named: the authored carryover and memory.json), turn-0.md (dead: her authored opening turn), the upstream model listing (never queried in play since discovery), the delta-tag transport (the full-block protocol, the sheet named), the service step (multiuser built, hosting remains), the carryover editor (the raw file-editor surface exists, the purpose-built UI stays deferred); kept -- the operator's queue, the landscape and receipts, the live constraints, the open steals with numbering preserved so cross-references resolve, the deferred tasks, the distant points, the rejections, the notes. 582 lines to 338; the first deletion pass duplicated the steal-list header and the verification re-read caught it
2026-11-17 22:50:59 +00:00

525 lines
26 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. GM prose goes pure (the full-block
// protocol, GM 2026-11-16): no cache blocks ride any turn -- her
// <status>/<agenda>/<mind> blocks ride at her own tail, the view
// stamps the scan's newest values at her most recent turn, and the
// log is the one truth (the state scan -- the db holds no copy). A
// GM block edit rides its GM turn as the override record; the
// composition overwrites her newest blocks with it, the log keeps
// her words verbatim. The player's present blocks are whole-list
// SETs (absent means unchanged, never blank); conflicts (a refused
// <mind>, an emitted <model>) ride the self-heal channel. GM input
// expands at ingestion (strict, DECISIONS #9): @PC/@Package and
// $vars resolve before the line is logged; an expansion error
// refuses the turn and the line is handed back for editing. Every
// provider request records its resolved model and effective params
// on the resulting msg event (via); a failed call lands a req event
// with the failure -- the turn still fails loud.
/** @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 { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
import { renderView, cleanBlockList, AGENDA_CAP } from './session.mjs';
import { parseVariants, pickVariant } from './variants.mjs';
import { registry, usable } from './discovery.mjs';
export class HttpError extends Error {
/**
* @param {number} status @param {string} message @param {unknown} [detail]
*/
constructor(status, message, detail) {
super(message);
this.status = status;
this.detail = detail;
}
}
/** @param {Ctx} ctx @param {string} runId @returns {LiveSession} */
function needSession(ctx, runId) {
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open session for run '${runId}' -- POST /api/runs/${runId}/sessions first`);
return s;
}
/** The turn request's response: what the SPA needs to render the turn. */
/** @typedef {{ tools: string[], pendingAsk?: string, variants?: { count: number, chosen: number }, conflicts?: string[], player?: string }} TurnOut */
/**
* @param {Ctx} ctx @param {string} runId @param {string} line @param {?Actor} user
* @param {?{ status?: string[], agenda?: string[] }} [override]
* @param {?Record<string, unknown>} [sheet]
* @returns {Promise<TurnOut>}
*/
export async function gmTurn(ctx, runId, line, user, override = null, sheet = null) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)');
// GM-input expansion (strict, DECISIONS #9): the line resolves at
// ingestion -- the log records the expanded words, which is what
// keeps continuation carryovers expansion-free forever. A refused
// turn appends nothing: the client hands the line back for editing.
let prose;
try {
prose = expandVars(runId, line.trim());
} catch (e) {
throw new HttpError(400, `the line was not sent -- ${e.message}`);
}
// GM prose goes pure: no cache blocks ride any turn. A block edit,
// when given, rides this turn as the override record -- the
// composition overwrites her newest blocks with it (the scan reads
// it newest-wins), the log keeps her words verbatim. The sheet
// record rides the same way: the GM's ledger, a whole set, the scan
// reads it newest-wins, the log never mutates
s.append({ t: 'msg', m: { role: 'user', content: prose }, ...(override ? { override } : {}), ...(sheet ? { sheet } : {}) });
// 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 auto-send: a carryover that ends on a GM turn is her
// cue -- the first request of the assembled contwin fires with no new
// line (the cue is already the log's last word)
/**
* @param {Ctx} ctx @param {string} runId @param {?Actor} user
* @returns {Promise<TurnOut>}
*/
export async function openingCall(ctx, runId, user) {
return runLoop(ctx, runId, user);
}
/**
* @param {Ctx} ctx @param {string} runId @param {string} answer @param {?Actor} user
* @returns {Promise<TurnOut>}
*/
export async function answerAsk(ctx, runId, answer, user) {
const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
// the answer is GM input: same strict expansion, same hand-back --
// a refusal leaves the pending question untouched
let resolved;
try {
resolved = expandVars(runId, answer.trim());
} catch (e) {
throw new HttpError(400, `the answer was not sent -- ${e.message}`);
}
// 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: resolved } });
} 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);
}
/** @param {Ctx} ctx @param {string} runId @param {?Actor} user @returns {Promise<TurnOut>} */
async function runLoop(ctx, runId, user) {
const s = needSession(ctx, runId);
const tools = toolList(runId);
/** @type {TurnOut} */
const out = { tools: [] };
let heals = 0;
for (;;) {
const view = renderView(s);
// the request's resolved params: the mind layer rides over the
// run and deployment layers, the effort knob resolves its own
// layers (its unset state sends the registry's measured default).
// The current call's <model> block shows her the knobs that are
// hers to answer with <mind> -- reasoning_effort is filtered out
// (hidden from the model, GM 2026-11-16: not her call); nothing
// set means no block (the absent grammar); the via record lands
// the same truth unfiltered, the raw surfaces carry it
/** @type {string} */ let model;
if (ctx.mock) model = 'mock';
else model = resolveModel(ctx, runId);
const params = { ...resolveParams(ctx, runId, 'player'), ...(s.mind ?? {}) };
const effort = resolveEffort(ctx, runId, 'player', model);
if (effort !== null) params.reasoning_effort = effort;
const shown = { ...params };
delete shown.reasoning_effort;
if (Object.keys(shown).length) {
view.push({ role: 'system', content: `<model>${JSON.stringify(shown)}</model>` });
}
let msg;
/** @type {{ model: string, params: import('./shapes.mjs').RoleParams }} */ let via;
if (ctx.mock) {
// the synthetic marker: no provider call happens, but the knobs
// resolve for real (the mind layer included), so the smoke can
// assert the recording
msg = mockModel(s, view);
via = { model: 'mock', params };
} else {
via = { model, params };
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
// the turn meter's live record: one per provider call (a heal
// or tool round restarts it), fed by the streaming deltas
s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() };
let data;
try {
data = await ctx.provider.chat(model, view, tools, params, (p) => {
if (!s.progress) return;
s.progress.phase = p.phase;
if (p.phase === 'thinking') s.progress.thinking = p.chars;
else s.progress.prose = p.chars;
});
} catch (e) {
s.progress = null;
s.append({ t: 'req', model, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
throw e;
}
msg = data.choices[0].message;
s.usage = data.usage
? { promptTokens: data.usage.prompt_tokens, completionTokens: data.usage.completion_tokens }
: null;
}
if (msg.tool_calls?.length) {
const ask = msg.tool_calls.find((c) => c.function.name === 'ask_gm');
s.append({ t: 'msg', m: msg, via, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
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;
s.progress = null;
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
}
// the final message. Variant literature resolves on reception:
// validated strictly BEFORE anything is appended (a malformed
// block refuses loud, nothing applies), then one variant is
// picked at random and only that turn goes forward -- the pick
// note rides the log as the variantary metric, the unpicked rest
// never render on any model-facing surface
let vv = null;
try {
vv = parseVariants(msg.content);
} catch (e) {
s.progress = null;
throw new HttpError(422, `the player emitted a malformed variants block -- nothing applied; the turn is lost, retry: ${e.message}`);
}
s.append({ t: 'msg', m: msg, via, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
let text;
if (vv) {
const chosen = pickVariant(vv.variants.length);
s.append({ t: 'note', kind: 'pick', chosen, count: vv.variants.length });
out.variants = { count: vv.variants.length, chosen };
text = vv.variants[chosen];
} else {
text = msg.content ?? '';
}
// the status and agenda ride the turn text (the picked variant's,
// for variant literature). The full-block protocol (GM,
// 2026-11-16): a present block is a whole-list SET -- absent
// means unchanged, never blank; a present-but-empty block is a
// deliberate clear. Same-verb blocks combine into one set. No
// apply happens -- the log is the truth; the notes are the GM's
// receipt and the housekeeper's reading, the derivation is the
// scan's (its clean, its cap)
const carry = [];
if (/<status>/.test(text)) {
s.append({ t: 'note', kind: 'status', set: cleanBlockList(text, 'status') });
}
if (/<agenda>/.test(text)) {
const items = cleanBlockList(text, 'agenda');
// the cap is a derivation rule: the log keeps all her items,
// every derived surface shows the top five. The eviction is
// silent to her, visible to the GM (the note)
s.append({ t: 'note', kind: 'agenda', set: items.slice(0, AGENDA_CAP), evicted: items.slice(AGENDA_CAP) });
}
// the mind verb: parse now so a refused statement heals in-turn
// like any conflict; the stash itself lands only at the completing
// return (a healed restatement is the statement that counts)
/** @type {Record<string, number>} */ let mindNext = {};
if (/<mind>/.test(text)) {
const mind = parseMind(text);
carry.push(...mind.errors);
mindNext = mind.params;
}
// the <model> block is display-only: the read side of the mind
// verb, never hers to emit
if (/<model>/.test(text)) {
carry.push('the <model> block is a read-only display of your active parameters -- state them in a <mind> block');
}
// the <sheet> block is display-only the same way: the GM's ledger,
// read-only for her (GM, 2026-11-17) -- changes propose in prose
if (/<sheet>/.test(text)) {
carry.push('the <sheet> block is the GM\'s ledger -- propose changes in prose');
}
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
// the mind verb is one-shot: this completing turn consumed the
// mind it rode with; a fresh statement restates it for the next
s.mind = Object.keys(mindNext).length ? mindNext : null;
if (Object.keys(mindNext).length) s.append({ t: 'note', kind: 'mind', params: mindNext });
out.player = text;
s.progress = null;
return out;
}
}
/** @param {Ctx} ctx @param {string} runId @returns {string} */
function resolveModel(ctx, runId) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const reg = registry();
// resolution: the run's pick, the op's server.json pick, the
// registry's discovered default -- then the registry gate: model
// use is disabled until the op discovers, and a model the battery
// disqualified never plays
const model = meta.models?.player ?? ctx.cfg.models?.player ?? reg?.defaults.player ?? null;
if (!model) {
throw new HttpError(409, reg
? 'no player model resolved -- set one for this run (POST /model), or a deployment default (server.json, or the registry\'s discovered pick)'
: 'no models discovered yet -- the op runs discovery from the admin block first');
}
if (!usable(reg, model)) {
throw new HttpError(409, `model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ''} -- pick a discovered model`);
}
return model;
}
/** The effective sampling knobs for a role: the deployment default
* layer (server.json params) under the run's own overrides. */
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').RoleParams} */
function resolveParams(ctx, runId, role) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
return {
...(ctx.cfg.params?.[role] ?? {}),
...(meta.params?.[role] ?? {}),
};
}
// The reasoning-effort knob's own resolution (GM, 2026-11-16): unlike
// the numeric knobs its unset state SENDS -- the registry measured a
// default, so one honestly exists. Layers: the run's override, then
// the deployment layer (server.json params), then the registry's
// per-model pick -- the level with the highest observed mean
// thinking. An explicit null clears the layers: nothing rides, the
// model id's baked default applies. Hidden from the model entirely:
// never in the mind verb, never in the <model> display block -- it
// rides the via record, the raw surfaces carry it.
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @param {string} model @returns {?string} */
function resolveEffort(ctx, runId, role, model) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const set = meta.params?.[role]?.reasoning_effort ?? ctx.cfg.params?.[role]?.reasoning_effort ?? undefined;
if (set !== undefined) return set === null ? null : String(set);
const m = registry()?.models.find((x) => x.id === model);
return m?.effortDefault ?? null;
}
export { resolveModel, resolveParams, resolveEffort };
// --- the mind verb ------------------------------------------------------------
//
// <mind>{"temperature": 1.4}</mind> -- the player sets its own sampling
// knobs for its NEXT turn, to reflect the character's mind (GM,
// 2026-11-16: tag form, one-shot, no GM lock; the block carries a
// JSON object -- models emit JSON natively; the parameters need no
// model-facing explanation, they live native in base training).
// max_tokens is excluded by ruling (GM, 2026-11-16) -- it is a
// budget, not a mind. A substrate verb like the deltas: parsed from
// the picked variant's text after the final message, merged over the
// run and deployment layers for every call of the next turn, then
// spent. The bounds are the probed this-endpoint knowledge --
// enforced here, strictly, with the range named in the conflict so
// she can heal. The web's definitions table (web/knobs.mjs) carries
// the bounds as display prose for all five knobs; this table is the
// mind verb's validator, the four that are hers to set.
/** One knob's validated range. An absent bound is unknown (no limit
* stated); minExclusive excludes the min itself (top_p refuses 0,
* repetition_penalty refuses 0). */
/** @typedef {{ min?: number, max?: number, minExclusive?: boolean }} KnobRange */
/** @type {Record<string, KnobRange>} */
const KNOB_BOUNDS = {
temperature: { min: 0, max: 2 },
top_p: { min: 0, max: 1, minExclusive: true },
top_k: {}, // unbounded -- -1 and 0 both mean the filter is off
repetition_penalty: { min: 0, minExclusive: true },
};
/** @param {string} key @param {KnobRange} r @returns {string} */
function rangeText(key, r) {
if (r.min !== undefined && r.max !== undefined) {
return `${key} must be ${r.minExclusive ? 'above' : 'at least'} ${r.min} and up to ${r.max}`;
}
if (r.min !== undefined) return `${key} must be ${r.minExclusive ? 'above' : `${r.min} or more`}`;
if (r.max !== undefined) return `${key} must be at most ${r.max}`;
return `${key} accepts any number (-1 and 0 turn the filter off)`;
}
/** Parse one turn's <mind> blocks: a JSON object of knobs per block,
* all blocks combined (last wins per key, the same-verb rule). Every
* wrong thing is named -- the caller rides the conflict path, and
* she heals by restating.
* @param {string} text @returns {{ params: Record<string, number>, errors: string[] }}
*/
function parseMind(text) {
/** @type {Record<string, number>} */ const params = {};
/** @type {string[]} */ const errors = [];
const blocks = [...text.matchAll(/<mind>([\s\S]*?)<\/mind>/g)].map((m) => m[1]);
for (const block of blocks) {
let obj;
try {
obj = JSON.parse(block);
} catch (e) {
errors.push(`the <mind> block wants a JSON object (${String(e.message ?? e).split('\n')[0].slice(0, 120)})`);
continue;
}
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
errors.push('the <mind> block wants a JSON object of knobs');
continue;
}
for (const [key, v] of Object.entries(obj)) {
if (key === 'max_tokens') {
errors.push('max_tokens is not hers to set -- the mind verb sets temperature, top_p, top_k, repetition_penalty');
continue;
}
const range = KNOB_BOUNDS[key];
if (!range) {
errors.push(`the <mind> block names an unknown knob: ${key} -- ${Object.keys(KNOB_BOUNDS).join(', ')}`);
continue;
}
if (typeof v !== 'number' || !Number.isFinite(v)) {
errors.push(`the <mind> block wants a number for ${key}`);
continue;
}
if ((range.min !== undefined && (range.minExclusive ? v <= range.min : v < range.min))
|| (range.max !== undefined && v > range.max)) {
errors.push(`the <mind> block was refused on this endpoint's bounds: ${rangeText(key, range)} (got ${v})`);
continue;
}
params[key] = v;
}
}
if (blocks.length && !Object.keys(params).length && !errors.length) {
errors.push('the <mind> block is empty -- it wants a JSON object of knobs');
}
return { params, errors };
}
export { parseMind };
// --- the mock model ----------------------------------------------------------
//
// A scripted stand-in that exercises the loop without a key. The
// script advances one step per assistant reply, counted across the
// whole log (the conflict heal is a reply like any other). A
// session's head -- carryover turns before the first exchange --
// never counts; a continuation carryover's exchanges DO, so a
// carried history shifts the first turn's script position, and the
// smoke knows exactly where that is. Turn one offers variant
// literature (the random pick, each variant with its own status
// block), turn two asks (the pause/resume path), the answer lands
// whole-list status and agenda sets, then a restated agenda, an
// over-cap agenda with a valid mind, the <model> guard and its
// plain-prose heal, an out-of-bounds mind and its restating heal,
// the GM-override turn's reply (no blocks, the mind restated), and
// everything after is plain prose.
/** @typedef {import('./shapes.mjs').WireMessage} WireMessage */
/**
* @param {LiveSession} s @param {ViewMessage[]} view @returns {WireMessage}
*/
function mockModel(s, view) {
/** @param {string} name @param {Record<string, unknown>} args @param {string} id @returns {WireMessage} */
const call = (name, args, id) => ({
role: 'assistant',
content: null,
tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
});
// the sheet guard's cue (position-independent -- the carried tail
// shifts counts, a cue does not shift): the marked GM turn gets the
// emission, the conflict it earns gets the plain-prose heal. The
// view carries the conflict as its raw text (the log field does not
// ride), so the check reads the tags
const lastMsg = view[view.length - 1];
const lastGm = [...view].reverse().find((m) => m.role === 'user' && !/^<conflict>/.test(String(m.content ?? '')));
if (lastGm && /the floating numbers/.test(String(lastGm.content ?? ''))) {
if (lastMsg && /^<conflict>/.test(String(lastMsg.content ?? ''))) {
// the heal: plain prose, no blocks -- she proposes in prose
return { role: 'assistant', content: 'Mock: *She shakes the numbers out of her head and asks for the change out loud instead.*' };
}
return { role: 'assistant', content: 'Mock: *She squints at the ledger floating in her mind.*\n<sheet>{"gp": 99}</sheet>' };
}
let inExchange = false;
let count = 0;
for (const e of s.lines) {
if (e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly) {
inExchange = true;
} else if (inExchange && e.t === 'msg' && e.m.role === 'assistant') {
count++;
}
}
const toolResults = view.filter((m) => m.role === 'tool').length;
if (count === 0) {
// variant literature: two complete candidate turns, each with its
// own status block -- only the picked one's ever applies
return { role: 'assistant', content: '<variants>\n<variant>\n*She presses on along the hull, palms flat against the warm metal.*\n<status>cuffed, belted, naked, barefoot, determined</status>\n</variant>\n<variant>\n*She doubles back to the container and crouches in its shadow.*\n<status>cuffed, belted, naked, barefoot, cautious</status>\n</variant>\n</variants>' };
}
if (count === 1 && toolResults === 0) {
return call('ask_gm', { question: 'From where she stands, does the deck look clear toward the bow?' }, `mock-ask-${s.lines.length}`);
}
if (count === 2 && toolResults >= 1) {
// the full-block protocol: whole-list sets
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<status>cuffed, belted, naked, barefoot, settled, curious about the clicking</status>\n<agenda>\n- find fresh water\n- signal any passing ship\n- build a shelter\n</agenda>' };
}
if (count === 3) {
// a restated agenda replaces the list (the first item is done)
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<agenda>\n- signal any passing ship\n- build a shelter\n</agenda>' };
}
if (count === 4) {
// an over-cap agenda evicts from the bottom, silently; a valid
// mind rides the same turn
return { role: 'assistant', content: 'Mock: *Her thoughts race ahead of her feet.*\n<agenda>\n- item one\n- item two\n- item three\n- item four\n- item five\n- item six\n- item seven\n</agenda>\n<mind>{"temperature": 1.2}</mind>' };
}
if (count === 5) {
// the <model> block is display-only: the guard conflicts
return { role: 'assistant', content: 'Mock: *She squints at the horizon.*\n<model>{"temperature": 0.1}</model>' };
}
if (count === 6) {
// the guard's heal: plain prose, no blocks -- omitted means unchanged
return { role: 'assistant', content: 'Mock: *She shakes her head and gets back to watching the water.*' };
}
if (count === 7) {
// an out-of-bounds mind: the conflict names the range
return { role: 'assistant', content: 'Mock: *Her thoughts scatter.*\n<mind>{"temperature": 7}</mind>' };
}
if (count === 8) {
// the heal's restatement -- the statement that counts (and the
// last word of the session, so it rides the boundary unconsumed)
return { role: 'assistant', content: 'Mock: *She breathes until the numbers behave.*\n<mind>{"temperature": 1.2}</mind>' };
}
if (count === 9) {
// the GM-override turn's reply: no blocks (the override stands as
// the newest word), the mind restated so it rides the boundary
// unconsumed
return { role: 'assistant', content: 'Mock: *She nods to herself and settles in.*\n<mind>{"temperature": 1.2}</mind>' };
}
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
}