agenda: the player's second paper (add/drop deltas, cap-5 recency queue); conflicts self-heal as their own turn; same-verb blocks combine; per-run model selection; substrate-tag syntax rule
This commit is contained in:
+12
-2
@@ -32,6 +32,10 @@ export function renderTranscript(lines) {
|
||||
for (const e of lines) {
|
||||
if (e.t === 'bundle') continue; // context, not exchange — provided as separate inputs
|
||||
if (e.t === 'msg') {
|
||||
if (e.m.role === 'user' && e.conflictOnly) {
|
||||
L.push('[conflict — answered in-band]', e.m.content.replace(/<\/?conflict>/g, '').trim(), '');
|
||||
continue;
|
||||
}
|
||||
if (e.m.role === 'user') {
|
||||
L.push('[GM]', e.m.content, '');
|
||||
} else if (e.m.role === 'assistant') {
|
||||
@@ -48,6 +52,8 @@ export function renderTranscript(lines) {
|
||||
if (e.t === 'note') {
|
||||
if (e.kind === 'paper') {
|
||||
L.push(`[paper] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
|
||||
} else if (e.kind === 'agenda') {
|
||||
L.push(`[agenda] added: ${JSON.stringify(e.applied?.added ?? [])}, dropped: ${JSON.stringify(e.applied?.dropped ?? [])}, evicted: ${JSON.stringify(e.applied?.evicted ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
|
||||
} else if (e.kind === 'ask') {
|
||||
L.push(`[ask_gm pending] ${e.question}`, '');
|
||||
} else if (e.kind === 'window') {
|
||||
@@ -139,8 +145,12 @@ async function runJob(ctx, runId, stamp, lines, user) {
|
||||
}
|
||||
|
||||
async function callHousekeeper(ctx, runId, messages, user) {
|
||||
const model = ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player ?? null;
|
||||
if (!model) throw new Error('no housekeeper model configured (server.json models.housekeeper)');
|
||||
const meta = ctx.runMeta?.(runId) ?? {};
|
||||
const model = meta.models?.housekeeper
|
||||
?? ctx.cfg.models?.housekeeper
|
||||
?? ctx.cfg.models?.player
|
||||
?? null;
|
||||
if (!model) throw new Error('no housekeeper model resolved (server.json models.housekeeper, or a per-run override)');
|
||||
// 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, messages, undefined, ctx.cfg.params ?? {});
|
||||
|
||||
+40
-9
@@ -31,11 +31,10 @@ 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
|
||||
let content = `${line.trim()}\n\n<status>${paper.join(', ')}</status>`;
|
||||
if (s.conflict) {
|
||||
content += `\n<conflict>${s.conflict}</conflict>`;
|
||||
s.conflict = null;
|
||||
}
|
||||
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 } });
|
||||
return runLoop(ctx, runId, user);
|
||||
}
|
||||
@@ -80,6 +79,7 @@ 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;
|
||||
@@ -114,13 +114,31 @@ async function runLoop(ctx, runId, user) {
|
||||
continue; // let the model see the results before ending its turn
|
||||
}
|
||||
|
||||
// final player message — paper deltas ride the turn text itself
|
||||
// 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 });
|
||||
if (r.conflicts?.length) s.conflict = r.conflicts.join('; ');
|
||||
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;
|
||||
}
|
||||
@@ -128,7 +146,7 @@ async function runLoop(ctx, runId, user) {
|
||||
|
||||
function resolveModel(ctx, runId) {
|
||||
const meta = ctx.runMeta(runId) ?? {};
|
||||
return meta.model ?? ctx.cfg.models?.player ?? null;
|
||||
return meta.models?.player ?? ctx.cfg.models?.player ?? null;
|
||||
}
|
||||
|
||||
// --- the mock model ----------------------------------------------------------
|
||||
@@ -154,7 +172,20 @@ function mockModel(s, view) {
|
||||
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) {
|
||||
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<lost>worried</lost>\n<gained>settled</gained>' };
|
||||
// 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.*' };
|
||||
}
|
||||
|
||||
+51
-4
@@ -154,7 +154,8 @@ function serveStatic(pathname, res) {
|
||||
// among invitees, not with the world.
|
||||
|
||||
route('GET', '/api/session', async ({ user }) => ({
|
||||
user, // null when signed out or the token is stale
|
||||
// the public shape only — the stored row (token hash) never leaves
|
||||
user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null,
|
||||
fresh: users.userCount() === 0,
|
||||
}), { public: true });
|
||||
|
||||
@@ -332,7 +333,8 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
forked: meta?.forked ?? null,
|
||||
owner,
|
||||
ownerName: owner == null ? null : users.userName(owner),
|
||||
model: meta?.model ?? null,
|
||||
models: meta?.models ?? {},
|
||||
modelDefaults: ctx.cfg.models ?? {},
|
||||
},
|
||||
display: bundle.runDisplay(id),
|
||||
open: !!s,
|
||||
@@ -341,6 +343,7 @@ route('GET', '/api/runs/:id', async ({ params }) => {
|
||||
window: s?.stamp ?? null,
|
||||
fresh: s?.fresh ?? false,
|
||||
paper: st.paper,
|
||||
agenda: st.agenda,
|
||||
records: st.records,
|
||||
fill: st.rings,
|
||||
events: st.events,
|
||||
@@ -417,6 +420,33 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
|
||||
return { ok: true, vars: settings.vars };
|
||||
});
|
||||
|
||||
// the run's models: per-run overrides of the deployment defaults
|
||||
// (server.json), selected from the upstream listing (GET /api/models).
|
||||
// Owner-only, changeable at any time — every call resolves fresh, so a
|
||||
// mid-window switch simply takes the next turn. null clears a role
|
||||
// back to its deployment default.
|
||||
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, id);
|
||||
for (const k of Object.keys(body)) {
|
||||
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} — player and housekeeper`);
|
||||
}
|
||||
const meta = bundle.runMeta(id) ?? {};
|
||||
const models = meta.models ?? {};
|
||||
for (const role of ['player', 'housekeeper']) {
|
||||
if (body[role] === undefined) continue;
|
||||
if (body[role] === null) { delete models[role]; continue; }
|
||||
const m = String(body[role]).trim();
|
||||
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
|
||||
models[role] = m;
|
||||
}
|
||||
if (Object.keys(models).length) meta.models = models;
|
||||
else delete meta.models;
|
||||
fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
return { ok: true, models: meta.models ?? {}, defaults: ctx.cfg.models ?? {} };
|
||||
});
|
||||
|
||||
// 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.
|
||||
@@ -504,8 +534,7 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
|
||||
|
||||
route('GET', '/api/runs/:id/status', async ({ params }) => {
|
||||
bundle.requireRun(params.id);
|
||||
const s = ctx.sessions.get(params.id);
|
||||
return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null };
|
||||
return { paper: clerkJson(params.id, 'paper'), agenda: clerkJson(params.id, 'agenda') };
|
||||
});
|
||||
|
||||
// the GM's out-of-band paper override: whole-paper replace via the
|
||||
@@ -526,6 +555,24 @@ route('POST', '/api/runs/:id/paper', async ({ params, body, user }) => {
|
||||
return { ok: true, paper };
|
||||
});
|
||||
|
||||
// the GM's out-of-band agenda override: whole-queue replace via the
|
||||
// clerk (journaled). Items land in written order, first = top; an
|
||||
// empty array clears it. Commas are the add transport's separator —
|
||||
// an item containing one is a 400, not a silent split later.
|
||||
route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, 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 agenda');
|
||||
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, `items never contain commas (the add transport is comma-separated): ${JSON.stringify(it)}`);
|
||||
}
|
||||
const agenda = clerkJson(id, '--gm', 'agenda-set', ...items);
|
||||
return { ok: true, agenda };
|
||||
});
|
||||
|
||||
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
|
||||
// ends the window and kicks the async chain; poll GET for the outcome
|
||||
requireOwner(user, params.id);
|
||||
|
||||
+8
-9
@@ -53,7 +53,6 @@ function makeSession(runId, st) {
|
||||
file: sessionFile(runId, st),
|
||||
lines: [],
|
||||
pendingAsk: null, // { callId, question, calls } — the whole batch pauses
|
||||
conflict: null, // carried to the next GM turn as a <conflict> block
|
||||
usage: null, // { promptTokens, completionTokens } from the last response
|
||||
fresh: false,
|
||||
append(entry) {
|
||||
@@ -153,10 +152,6 @@ function derive(s) {
|
||||
}
|
||||
} else if (e.t === 'tool' && pending && e.m.tool_call_id === pending.callId) {
|
||||
pending = null;
|
||||
} else if (e.t === 'note' && e.kind === 'paper') {
|
||||
s.conflict = e.conflicts?.length ? e.conflicts.join('; ') : null;
|
||||
} else if (e.t === 'msg' && e.m.role === 'user') {
|
||||
s.conflict = null; // it rode this GM turn
|
||||
} else if (e.t === 'msg' && e.usage) {
|
||||
s.usage = { promptTokens: e.usage.prompt_tokens, completionTokens: e.usage.completion_tokens };
|
||||
}
|
||||
@@ -166,7 +161,7 @@ function derive(s) {
|
||||
|
||||
// --- the view renderer: log + policy -> per-call context ---------------------
|
||||
|
||||
const STRIP_BLOCKS = /\n?<(status|conflict)>[\s\S]*?<\/\1>\n?/g;
|
||||
const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g;
|
||||
|
||||
export function renderView(s, keepToolResults = 4) {
|
||||
const toolIdx = [];
|
||||
@@ -186,13 +181,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 (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 rides it, and a pending conflict rides it — the
|
||||
// model must see both
|
||||
// paper and agenda ride it
|
||||
msgs.push({ role: e.m.role, content: e.m.content.trim() });
|
||||
} else {
|
||||
// older GM turns: status/conflict blocks elide
|
||||
// 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') {
|
||||
|
||||
Reference in New Issue
Block a user