8ef96c7ac5
The mind r/w round (2026-11-20, on the box run's live evidence: her fifth turn slipped the channel, the emission came out <model>, the guard's heal doubled a story passage): the via echo renders as the per-turn <mind> block (the block on a turn shows the params its prose was inferred with -- calibration pairs exactly), the <model> guard and its mock cue are deleted, STRIP_HERS and the story verbs drop the tag, reasoning_effort stays hidden from her, and the one-shot rule stands (r/w is the tag, not persistence). The box run's log was migrated in the same stroke, no-legacy: the refused emission became the valid mind write it tried to be, the conflict and heal left, the bundle system message regenerated under the new invariants. En-route: check-reminder's logged-turns floor relaxes to >= 1. The native-markup round's first act rides adjacent (2026-11-21): the box log's markup debris cleaned and verified through the real machinery (scan, view, story projection), and the agenda grammar is BULLETS -- blockList is kind-dependent now (status keeps its wire commas, agenda splits lines only), the pane and chip parsers match, and a comma-carrying mock item proves the grammar in the smoke. The two paused guards from that round never get built -- the blocks problem dissolves downstream into real tool calls.
Then the temperature research (2026-11-22/23; TEMP-RESEARCH.md, new at root, is the full record -- scope, the reusable fork-and-edit recipe and its gotchas, the failure taxonomy, hedges, open questions). Two blind sweeps of the box run first: prose VOICE tracks temperature blind (the composed-to-impulsive gradient survives with the number hidden), prose CONTENT was demand effect (round 1's traces read the visible <mind> block and styled to it -- a stage direction, not calibration), so the live push is RETIRED: the loop never renders the current call's settings into her view again, the per-turn via echoes are the whole read side. Thinking is temperature-robust through 1.2 and dies above it in four distinct shapes (shape-mixing 422, unbounded prose soup, reasoning-channel salad, instant salad). The n=20 organic ladder (320 forks, the box run's own moment) put the cliff at 1.2 proper: of twenty turns, 8 empty-prose, 5 soups, 2 refusals -- so the clamp drops to 1.15 ("we declare 1.2 too hot to be useful", GM, 2026-11-23; KNOB_BOUNDS moved, the smoke's conflict-range text with it). Side finding at scale: the restatement attractor -- blind, 50-85% of turns re-state their own <mind>, the value pinned near her recent emissions regardless of what rode.
Round 4 (2026-11-24) audits that corpus for content and changes no code: soft inference errors are temperature-FLAT (the ~30% breakfast error is structural, every rung), CONFABULATION IS A THRESHOLD AT 1.0 (fabrication-heavy reasoning 1.4% below the line vs 26.7% at or above; attribute drift below, invented events above; 1.15 bimodal at 8/20 -- the clamp is outcome-safe, not content-safe), and every mechanical axis is flat under the band: reasoning length, prose length, wall time, register proxies. Under the threshold, temperature is a pure voice knob.
On that evidence the two-subturn turn is DESIGNED (ROADMAP, designed-not-built): (a) full view + max effort + constant mid-band temp, the recall seat; (b) draft + tool oks + low effort + variable temp, the voice seat, the draft's register as the dial's zero point; the state blocks become real tool calls, retiring the strip lists, the strict lint, the block grammar, and the prose-to-blocks seam whole. The 2026-11-28 amendments complete it: the native tool loop carries her thread content-borne across rounds (the "thinking never returns" doctrine was transport fact -- the provider drops the field; the reader-facing rule stands), a purpose param on every tool call, the append-only prefix with the reminder as the one per-call exception (four flavors: orient, continue, draft-now, and (b)'s render contract), the recall tool (player search over its whole run; read-only, therefore rewind-safe by construction -- the records tools retire and their journaled-mutator compensation debt dies unfunded), and inline [...] annotations as the author-to-machine layer, the rationale block retained as the optional whole-turn scope. Three new ROADMAP sections ride: the status scan (the wake-up questions; location, inventory, and weather channels; meters pending), the package-declared ledger (the box order tool and the boutique shop as one mechanism; the measured 45% arithmetic re-derivation tax it kills), and the scene box with its paperdoll agent (TTI register, renderer-neutral, the model never draws a pixel). The helpfulness sweep (75 turns of the run's own reasoning: 62 CLEAN, 13 TRACE, 0 AFFECTED; onset at the punishment-arc OOC turns) and the live reading failures (the legs pronoun, the gag-speech riddle, the shed mind write) are recorded as the evidence base for the reading-rules piece.
The GM's prompt-side edits ride the same commit: invariants' r/w mind section and the agenda's no-trimming/no-metaphor lines (landed against observed behavior in the box run's thinking blocks), the clamp example already reading 1.15, system.md's injection-exception rename, README's protocol passages, DICTIONARY's updates, and the box package's backdrop and carryover content pass. The calibration materials (calibration.md, packager-calibration.md -- the A/B outputs, the flake record, the wrong-woman verdict) are committed as research records at the GM's staging. detention stays untracked WIP.
Verified across the sittings: typecheck green on both programs, smoke ALL PASS (the mind-r/w battery with the mock's script renumber, the clamp's conflict-range text, the comma-carrying agenda item), restart + reminder checks green, check-repo clean, and the debug server restarted on the real state. The substrate deltas in this commit are the mind r/w, the push retirement, and the clamp; everything else is the record.
565 lines
29 KiB
JavaScript
565 lines
29 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, developer 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>) 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, rewindTo } from './session.mjs';
|
|
import { parseVariants, pickVariant } from './variants.mjs';
|
|
import { providerFor } from './provider.mjs';
|
|
import { findModel } 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]
|
|
* @param {?{ rewind?: ?number, expect?: ?number }} [send]
|
|
* @returns {Promise<TurnOut>}
|
|
*/
|
|
export async function gmTurn(ctx, runId, line, user, override = null, sheet = null, send = null) {
|
|
const s = needSession(ctx, runId);
|
|
if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)');
|
|
// the staleness guard (developer, 2026-11-17): the client states the log it
|
|
// composed against. The log only moves through sends, so a mismatch
|
|
// means a stale tab -- refuse before anything rides, rewind or not
|
|
if (send?.expect != null && send.expect !== s.lines.length) {
|
|
throw new HttpError(409, `the session moved on -- this send was composed against a stale view (${send.expect} lines then, ${s.lines.length} now); refresh and re-send`);
|
|
}
|
|
// 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}`);
|
|
}
|
|
// the rewind (developer, 2026-11-17): the target GM turn and everything
|
|
// after it leave the log, and this send takes its place. The commit
|
|
// happens here -- after the line expanded cleanly, so a refusal
|
|
// truncates nothing -- and as one landing with the turn: the log is
|
|
// never left rewound-and-waiting
|
|
if (send?.rewind != null) rewindTo(s, send.rewind);
|
|
// 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
|
|
* @param {?number} [expect]
|
|
* @returns {Promise<TurnOut>}
|
|
*/
|
|
export async function answerAsk(ctx, runId, answer, user, expect = null) {
|
|
const s = needSession(ctx, runId);
|
|
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
|
|
// the same staleness guard as the turn send: the answer appends too
|
|
if (expect != null && expect !== s.lines.length) {
|
|
throw new HttpError(409, `the session moved on -- this answer was composed against a stale view (${expect} lines then, ${s.lines.length} now); refresh and re-answer`);
|
|
}
|
|
// 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 spec: the full inference identity
|
|
// {provider, model, effort} (developer, 2026-11-18) -- there is no unset
|
|
// effort, it is a property of the pick. The mind layer is the
|
|
// only params source now: per-turn, hers, spent on completion
|
|
// (the per-run knob layer is retired). The live push is retired
|
|
// (developer, 2026-11-22, on the temperature-test round's
|
|
// demand-effect evidence: a current-call <mind> block showed her
|
|
// the settings mid-composition and she styled to the number -- a
|
|
// stage direction, not calibration). The read side is the
|
|
// per-turn via echoes only: past turns carry what rode them, the
|
|
// stash riding THIS call is invisible to her until the next
|
|
// echo. reasoning_effort never renders to her either way (not
|
|
// her call, it rides the spec); the via record lands the same
|
|
// truth unfiltered, the raw surfaces carry it
|
|
const spec = resolveSpec(ctx, runId, 'player');
|
|
const provider = providerFor(ctx, spec.provider);
|
|
const params = { ...(s.mind ?? {}) };
|
|
params.reasoning_effort = spec.effort;
|
|
let msg;
|
|
/** @type {{ model: string, provider?: string, params: import('./shapes.mjs').RoleParams }} */ let via;
|
|
if (ctx.mock) {
|
|
// the synthetic marker: no provider call happens, but the spec
|
|
// and the knobs resolve for real, so the smoke can assert the
|
|
// recording. Usage rides too (developer round, 2026-11-19): a
|
|
// rough chars-over-4 token count of the assembled view, so the
|
|
// detail's usage and the context gauge exercise against the
|
|
// mock exactly as they do against a real endpoint
|
|
msg = mockModel(s, view);
|
|
via = { model: spec.model, provider: spec.provider, params };
|
|
const chars = view.reduce((a, m) => a + String(m.content ?? '').length, 0);
|
|
s.usage = { promptTokens: Math.round(chars / 4), completionTokens: Math.round(String(msg.content ?? '').length / 4) };
|
|
} else {
|
|
via = { model: spec.model, provider: spec.provider, params };
|
|
// attribution (#22): every inferencer call names the acting user
|
|
console.log(`${new Date().toISOString().slice(11, 19)} inferencer ${spec.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 provider.chat(spec.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: spec.model, provider: spec.provider, 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 (developer,
|
|
// 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 <sheet> block is display-only (developer, 2026-11-17) --
|
|
// the GM's ledger, changes propose in prose. The guard quotes
|
|
// the offending emission: a conflict must be self-contained
|
|
// (developer, 2026-11-18) -- it stays in the contwin, and
|
|
// the block it answers strips from the view, so the quote is the
|
|
// only visible trace of what went wrong. (The <mind> block needs
|
|
// no guard since 2026-11-20: it is r/w, emitting it IS the write.)
|
|
if (/<sheet>/.test(text)) {
|
|
const emitted = quote(String(text.match(/<sheet>([\s\S]*?)<\/sheet>/)?.[1] ?? ''));
|
|
carry.push(`the <sheet> block is the GM's ledger -- propose changes in prose (yours said: ${emitted})`);
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
|
|
/** A model spec as run.json carries it: the {provider, model,
|
|
* effort} object (the no-legacy rule, developer, 2026-11-18 -- the
|
|
* bare-string era migrated away in the same pass). Malformed
|
|
* records refuse loud.
|
|
* @param {unknown} raw @param {'player'|'housekeeper'} role @returns {?import('./shapes.mjs').ModelSpec} */
|
|
function specFromMeta(raw, role) {
|
|
if (raw == null) return null;
|
|
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
|
const o = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw);
|
|
if (typeof o.provider === 'string' && typeof o.model === 'string' && typeof o.effort === 'string') {
|
|
return { provider: o.provider, model: o.model, effort: o.effort };
|
|
}
|
|
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
|
|
}
|
|
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
|
|
}
|
|
|
|
/** The invalidation gate (developer, 2026-11-18): the settings the run
|
|
* came with must still be carried. A provider gone from the
|
|
* config, a model gone from its provider's registry, a model the
|
|
* battery disqualified -- all one state: the run blocks until the
|
|
* GM sets it up again. The error IS the table's note.
|
|
* @param {Ctx} ctx @param {import('./shapes.mjs').ModelSpec} spec @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
|
function gateSpec(ctx, spec, role) {
|
|
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
|
|
throw new HttpError(409, `the run's ${role} model rides provider '${spec.provider}', which is no longer configured -- set it up again in the model box`);
|
|
}
|
|
const m = findModel(spec.provider, spec.model);
|
|
if (!m) {
|
|
throw new HttpError(409, `the run's ${role} model '${spec.model}' is not in provider '${spec.provider}'s registry (the discovered ids drifted) -- set it up again in the model box`);
|
|
}
|
|
if (m.inference === false) {
|
|
throw new HttpError(409, `the run's ${role} model '${spec.model}' failed the inference battery -- set it up again in the model box`);
|
|
}
|
|
return spec;
|
|
}
|
|
|
|
/** Resolve one role's spec: the run's pick, gated for validity. No
|
|
* pick is a loud refusal -- the create flow lands one, so only
|
|
* picked-clean runs hit this.
|
|
* @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
|
function resolveSpec(ctx, runId, role) {
|
|
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
|
const spec = specFromMeta(meta.models?.[role], role);
|
|
if (!spec) throw new HttpError(409, `no ${role} model set for this run -- pick one in the model box`);
|
|
return gateSpec(ctx, spec, role);
|
|
}
|
|
export { specFromMeta, gateSpec, resolveSpec };
|
|
|
|
// --- 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 (developer,
|
|
// 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 (developer, 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 = {
|
|
// the temperature ceiling is the test round's measured edge
|
|
// (developer, 2026-11-22): 1.2 was the last clean rung in both
|
|
// sweeps -- above it the output degrades before it disintegrates
|
|
// (1.3: prose outside a <variants> block, the shape-mixing 422;
|
|
// 1.4: unbounded prose soup; 1.5/2.0: reasoning-channel salad).
|
|
// Amended (developer, 2026-11-23, on the n=20 organic sweep's
|
|
// evidence): 1.2 fails or degenerates in ~75% of twenty samples
|
|
// (empty-prose completions, refused turns, prose soups), while
|
|
// 1.15 holds 19/20 clean -- 1.2 is declared too hot to be useful
|
|
// and the ceiling drops to 1.15.
|
|
temperature: { min: 0, max: 1.15 },
|
|
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)`;
|
|
}
|
|
|
|
// a conflict quotes the offending emission (self-contained, GM,
|
|
// 2026-11-18): the conflict stays in the contwin, the block it
|
|
// answers strips from the view, so the quote is the only visible
|
|
// trace of what went wrong. Trim, collapse whitespace, cap the
|
|
// length -- enough to identify the mistake, never a wall
|
|
/** @param {string} s @returns {string} */
|
|
function quote(s) {
|
|
const flat = s.trim().replace(/\s+/g, ' ');
|
|
return flat.length > 160 ? `${flat.slice(0, 160)}...` : flat;
|
|
}
|
|
|
|
/** 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. The errors carry what she wrote: a
|
|
* conflict must describe its problem in full (developer, 2026-11-18), even
|
|
* when the problem originates in the turn it immediately follows --
|
|
* the block itself strips from the view, the conflict is what
|
|
* remains.
|
|
* @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 -- yours: ${quote(block)} (${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 -- yours: ${quote(block)}`);
|
|
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 (you set: max_tokens ${JSON.stringify(v)})`);
|
|
continue;
|
|
}
|
|
const range = KNOB_BOUNDS[key];
|
|
if (!range) {
|
|
errors.push(`the <mind> block names an unknown knob: ${key} (you set: ${JSON.stringify(v)}) -- ${Object.keys(KNOB_BOUNDS).join(', ')}`);
|
|
continue;
|
|
}
|
|
if (typeof v !== 'number' || !Number.isFinite(v)) {
|
|
errors.push(`the <mind> block wants a number for ${key} (you set: ${JSON.stringify(v)})`);
|
|
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, 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);
|
|
// the comma inside the item is prose -- the agenda grammar is
|
|
// bullets, not the status wire commas (developer, 2026-11-21)
|
|
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<agenda>\n- signal any passing ship, or swim for it\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.15}</mind>' };
|
|
}
|
|
if (count === 6) {
|
|
// 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 === 7) {
|
|
// the heal's restatement -- the statement that counts
|
|
return { role: 'assistant', content: 'Mock: *She breathes until the numbers behave.*\n<mind>{"temperature": 1.15}</mind>' };
|
|
}
|
|
if (count === 8) {
|
|
// 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.15}</mind>' };
|
|
}
|
|
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
|
|
}
|