the 2026-11-16 rounds, the whole day in one commit: model discovery (the two-step op act -- discover scrapes the provider metadata, refine runs the deterministic battery over every id and hands the adjudicated results to the best passing model for the curated registry; state/models.json is the truth of selectable models and gates all model use, a fresh deployment has none; the five named sampling knobs ride run.json params over server.json params, sent only when set; the curator call retries once on the host's network hiccups, its output strictly validated with the machine-list fallback, and the do-not-deliberate line keeps its thinking tokens down); the pick rule reworked on the GM's rulings -- the dv endpoint's 5.2/5.3-max flip was an alias (one model behind both ids), the rank keys on the reasoning bucket not the raw token count (within-bucket differences are sampling noise, the thresholds sit in the endpoint's observed gaps) and full ties settle sort-lex-pick-bottom, with the mock registry carrying a canned tie pair (mock/mock-tie) and the smoke asserting the lex-bottom pick; the play-protocol batch (OOC GM turns carry no cache blocks, memory.json is authored draft applied by the start gate's reapply over a fresh db, /story filters OOC whole, the per-turn raw control on the table); the tunables UX round (web/knobs.mjs: the definitions table with the GM's hint texts and the probed this-endpoint bounds, the per-knob explicit override toggle replacing implicit empty-means-unset diffing, the shared focus-driven hint bar; the run detail and /model responses carry paramDefaults, the deployment layer -- the only default anyone can honestly name); request recording (every provider call lands its resolved model + effective params on the msg event as via, a failed call lands a req event with the failure, both surface on the raw tab and the per-turn raw control on no model-facing surface, a req riding the slidwin tail passes the start lint as conversation machinery; the housekeeping pass log names its model via the clerk's --model flag); the mind verb (<mind> JSON in a player turn sets its sampling for its next turn -- one-shot, max_tokens excluded, a budget not a mind; bounds enforced in KNOB_BOUNDS with the range named in the conflict and the heal restatement the statement that counts; derive() makes a statement live until a player reply consumes it, honest across restarts, session boundaries and forks -- an unconsumed mind rides on); the full-block protocol (the GM rewrote system/invariants/reminder to eliminate the diff verbs: she emits whole <status>/<agenda> at her turn tail, a present block is a whole-list set, absent means unchanged never blank, over-cap agendas evict from the bottom silently -- ruled a feature, silent to her, the note shows the GM; renderView strips every copy and stamps the newest of each kind at the tail of her most recent prose turn, her own emission, so the context reads as the same sequence of events the game had; GM prose goes pure, old logs' composited rides strip, they were never GM words; <mind> is write-only, its tags strip from the view; every turn of hers carries its <model> block -- the params it rode, bare JSON from the via record, the current call included, suppressed when nothing is set, emitting one refused with a pointer at <mind>; the clerk's status-apply/agenda-apply delta verbs RETIRED with their dispatch and collectors, status-set/agenda-set are the player path now; the story strips her blocks, the table chips them; the smoke imports renderView and asserts the view policy directly -- the pattern for testing view-only policy no API exposes); and the opening event RETIRED (the start gate seeds the clerk from her last authored turn's blocks -- the GM moved la-caramba's initial status into her opening turn; old carryovers keep their events as inert history; the event's pre-existing double-landing in every started log, pre-bundle and in-carry, died with the branch); smoke ALL PASS + restart + reminder + repo checks green, browser passes over the knob UX and the new chips and notes with zero console errors, typecheck green on both programs; README and DICTIONARY carry the durable design, HANDOFF trimmed to the map

This commit is contained in:
2026-11-16 21:32:02 +00:00
parent 193dc336be
commit 894737fcf3
30 changed files with 2193 additions and 518 deletions
+125 -21
View File
@@ -34,6 +34,7 @@ import { effectiveContents } from './variants.mjs';
import { gmTurn, answerAsk, openingCall, HttpError } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
import * as discovery from './discovery.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock');
@@ -313,7 +314,49 @@ route('GET', '/api', async () => ({
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
}));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
// --- models: the registry, and the op's discovery acts -------------------------
//
// The registry (state/models.json) is the truth of selectable
// models. Fresh deployments have none: model use is disabled until
// the op discovers. Discover scrapes the provider surface -- API
// metadata only, zero inference; refine runs the deterministic
// battery and the curator pass (it sends real traffic and may cost
// real money). Both are the superuser's.
/** The effective deployment default per role: the op's server.json
* pick wins, else the registry's discovered default. */
/** @returns {{ player?: ?string, housekeeper?: ?string }} */
function effectiveDefaults() {
const reg = discovery.registry();
return {
player: ctx.cfg.models?.player ?? reg?.defaults.player ?? undefined,
housekeeper: ctx.cfg.models?.housekeeper ?? reg?.defaults.housekeeper ?? undefined,
};
}
route('GET', '/api/models', async () => {
const reg = discovery.registry();
return {
phase: reg?.phase ?? 'none',
discovered: reg?.discovered ?? null,
refined: reg?.refined ?? null,
curator: reg?.curator ?? null,
defaults: effectiveDefaults(),
models: reg?.models ?? [],
job: discovery.jobState(ctx),
};
});
route('POST', '/api/models/discover', async ({ user }) => {
requireSuperuser(user);
const reg = await discovery.discover(ctx);
return { ok: true, phase: reg.phase, models: reg.models.length };
});
route('POST', '/api/models/refine', async ({ user }) => {
requireSuperuser(user);
return discovery.refine(ctx, user);
});
route('GET', '/api/packages', async () => {
const pkgs = clerkRawJson('packages');
@@ -413,7 +456,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
owner,
ownerName: owner == null ? null : userName(owner),
models: meta?.models ?? {},
modelDefaults: ctx.cfg.models ?? {},
params: meta?.params ?? {},
modelDefaults: effectiveDefaults(),
// the deployment layer of the knobs (server.json params): the
// only default an unset knob can honestly resolve to -- the
// provider's own serving defaults are unknown and stay unstated
paramDefaults: cfg.params ?? {},
},
display: bundle.runDisplay(id),
open: !!s,
@@ -445,11 +493,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
// (the frozen craft) is writable only while dormant; the authored
// carryover of session one is authoring material (writable), a
// continuation carryover is conversation (read-only until the editor
// task); memory.json is inert provenance, read-only. housekeeper.md
// is substrate-internal (repo-fed at housekeeping, never copied, not
// exposed here) and gm.md lives only in the notepad endpoints (the
// play-view pad); config is read-only (vars and lineage are easy to
// break blind).
// task); memory.json is the draft's starting memories -- authored
// material while the run is a draft (the start gate applies it),
// provenance after. housekeeper.md is substrate-internal (repo-fed
// at housekeeping, never copied, not exposed here) and gm.md lives
// only in the notepad endpoints (the play-view pad); config is
// read-only (vars and lineage are easy to break blind).
/** One file of the editor surface. */
/** @typedef {{ mode: string, path: string }} FileSpec */
@@ -470,7 +519,7 @@ function fileSurface(runId) {
'backdrop.md': { mode: rw, path: path.join(dir, 'bundle', 'backdrop.md') },
'character.md': { mode: rw, path: path.join(dir, 'bundle', 'character.md') },
'carryover.jsonl': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'carryover.jsonl') },
'memory.json': { mode: 'ro', path: path.join(dir, 'memory.json') }, // session one's provenance; absent later
'memory.json': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'memory.json') }, // the draft's starting memories; the start gate applies them
'settings.json': { mode: 'ro', path: path.join(root, 'settings.json') },
'run.json': { mode: 'ro', path: path.join(root, 'run.json') },
};
@@ -499,6 +548,17 @@ route('PUT', '/api/runs/:id/files/:path', async ({ params, body, user }) => {
if (!spec) throw new HttpError(404, `no such run file in the API surface: ${f}`);
if (spec.mode !== 'rw') throw new HttpError(403, `${f} is read-only (session ${surf.n} is ${surf.phase})`);
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
if (f === 'memory.json') {
// the save-time gate is syntax only (the carryover lint's cheap
// cousin): the manifest checks run at the start gate, where a
// refusal touches nothing
try {
const mf = JSON.parse(body.content);
if (typeof mf !== 'object' || mf === null || Array.isArray(mf)) throw new Error();
} catch {
throw new HttpError(400, 'memory.json must be a JSON object');
}
}
if (f === 'carryover.jsonl') {
// the save-time lint: only clean openings land (the start lint is
// the backstop, not the first line of defense)
@@ -536,31 +596,69 @@ 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
// the run's models and sampling knobs: per-run overrides of the
// deployment defaults (server.json, else the registry's discovered
// pick), selected from the registry (GET /api/models). Owner-only,
// changeable at any time -- every call resolves fresh, so a
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default.
// back to its deployment default; a null knob clears the knob.
const KNOBS = ['temperature', 'top_p', 'top_k', 'repetition_penalty', 'max_tokens'];
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`);
if (k !== 'player' && k !== 'housekeeper' && k !== 'params') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper, params`);
}
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const reg = discovery.registry();
const models = meta.models ?? {};
for (const role of /** @type {('player'|'housekeeper')[]} */ (['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`);
if (!discovery.usable(reg, m)) {
throw new HttpError(400, `${role}: '${m}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
}
models[role] = m;
}
if (Object.keys(models).length) meta.models = models;
else delete meta.models;
if (body.params !== undefined) {
if (typeof body.params !== 'object' || body.params === null || Array.isArray(body.params)) {
throw new HttpError(400, 'params (an object of player/housekeeper knob objects) is required');
}
for (const role of Object.keys(body.params)) {
if (role !== 'player' && role !== 'housekeeper') throw new HttpError(400, `unknown params role: ${role}`);
const knobs = body.params[role];
if (typeof knobs !== 'object' || knobs === null || Array.isArray(knobs)) {
throw new HttpError(400, `params.${role} must be an object of knobs`);
}
for (const [k, v] of Object.entries(knobs)) {
if (!KNOBS.includes(k)) throw new HttpError(400, `unknown knob: ${k} -- ${KNOBS.join(', ')}`);
if (v !== null && !Number.isFinite(v)) throw new HttpError(400, `params.${role}.${k} must be a number, or null to clear`);
}
}
const rp = meta.params ?? {};
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
const knobs = body.params[role];
if (knobs === undefined) continue;
const cur = { ...(rp[role] ?? {}) };
for (const [k, v] of Object.entries(knobs)) {
if (v === null) delete cur[/** @type {'temperature'|'top_p'|'top_k'|'repetition_penalty'|'max_tokens'} */ (k)];
else cur[/** @type {'temperature'|'top_p'|'top_k'|'repetition_penalty'|'max_tokens'} */ (k)] = Number(v);
}
if (Object.keys(cur).length) rp[role] = cur;
else delete rp[role];
}
if (Object.keys(rp).length) meta.params = rp;
else delete meta.params;
}
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 ?? {} };
return { ok: true, models: meta.models ?? {}, params: meta.params ?? {}, defaults: effectiveDefaults(), paramDefaults: cfg.params ?? {} };
});
// the GM's notepad: the run's gm.md -- the owner's alone (#28's
@@ -728,7 +826,7 @@ route('GET', '/api/runs/:id/table', async ({ params, user }) => {
route('GET', '/api/runs/:id/story', async ({ params }) => {
bundle.requireRun(params.id);
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
const verbs = /<(lost|gained|add|drop)>[\s\S]*?<\/\1>/g;
const verbs = /<(lost|gained|add|drop|mind|model|status|agenda)>[\s\S]*?<\/\1>/g;
const project = (/** @type {import('./shapes.mjs').LogEvent[]} */ lines) => {
const eff = effectiveContents(lines);
/** @type {{ who: string, text: string }[]} */
@@ -736,13 +834,17 @@ route('GET', '/api/runs/:id/story', async ({ params }) => {
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
if (e.t !== 'msg' || e.reminder) continue;
// OOC is the paren channel (invariants: opens with a paren,
// closing optional) and is omitted WHOLE: turn shapes are
// turn-granular, and load-bearing prose living inside OOC only
// is a GM protocol violation the story enforces by omission
if (e.m.role === 'user' && !e.conflictOnly) {
const text = String(e.m.content ?? '').replace(rides, '').trim();
if (text) turns.push({ who: 'gm', text });
if (text && !text.startsWith('(')) turns.push({ who: 'gm', text });
} else if (e.m.role === 'assistant' && !e.m.tool_calls?.length) {
// tool prose is for the tool result turn, not the story
const text = String(eff.has(i) ? eff.get(i) : (e.m.content ?? '')).replace(verbs, '').trim();
if (text) turns.push({ who: 'player', text });
if (text && !text.startsWith('(')) turns.push({ who: 'player', text });
}
}
return turns;
@@ -842,8 +944,10 @@ route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
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 };
const r = clerkJson(id, '--gm', 'agenda-set', ...items);
// the set enforces the cap silently (ruled a feature); the evicted
// ride along for the record
return { ok: true, agenda: r.set, evicted: r.evicted };
});
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
@@ -881,7 +985,7 @@ route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }
fs.mkdirSync(dir, { recursive: true });
const text = ctx.mock
? housekeeping.mockManifest(n)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, n, lines), user);
: (await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, n, lines), user)).content;
let mf;
try {
mf = housekeeping.parseManifest(text);
@@ -977,5 +1081,5 @@ const server = http.createServer(async (req, res) => {
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
const host = DEBUG ? '127.0.0.1' : cfgHost;
server.listen(Number(port ?? 7350), host, () => {
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : (effectiveDefaults().player ?? 'no default model')} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
});