Files
tiny-worlds/server/discovery.mjs
T
mute eebc1993dd the night rounds: the GM-input rework and the reasoning-effort knob -- the workbench renders no faces: the composer overlay and the transcript share colour-only tokens (.narration dim, .emph accent), source verbatim, asterisks tinted and kept on screen, so the input's caret can never drift (the old overlay's real bold/italic shifted advance widths -- keeping every character preserved count, not width; the scrollbar-gutter match killed the second drift source); the story view carries its OWN renderer (view-story storyBody/storySpans) -- the book keeps real bold/italic with the asterisks spent, narration italic via #story-scoped CSS, one rule for the tool and typography for the deliverable, deliberately separate; the composer is turn-shaped: rows=6 floor, field-sizing: content grows it with the turn (the thing the GM remembered Firefox doing -- it was never in use), max-height 50vh caps with internal scroll, the footer moved under the transcript's column only so the input's width is the pane's; the transcript's stick-to-bottom was DEAD CODE all along (#transcript has no height or overflow -- main is the scroller, the scrollTop assignments were no-ops in every browser): stickBottom scrolls main and re-asserts next frame (Firefox's scroll anchoring can reclaim a same-tick scroll around a content wipe), main carries overflow-anchor: none; the prose pane drops its machinery by ruling: the status/agenda chips and the retired delta tags strip (the panes carry the derived state), the reminder card never renders (it is the same every turn -- the raw tab keeps every copy), and the status/agenda note receipts (the old delta applies and the whole-list sets alike) skip the prose walk while the raw keeps them; the model dropdown collapsed to one plain list of ids sorted, ceilings riding along (the family grouping left the user guessing what a family name means, and the curator's tier labels only made sense inside their groups); and the reasoning-effort round: the battery probes the ladder (probeEfforts -- each of none/minimal/low/medium/high/xhigh/max measured for mean thinking, two samples, efforts recorded per model, effortDefault the argmax mean over minimal..max, 'none' never a candidate -- it is the off switch; null when the model shows no thinking), the knob is first-class and the GM's alone (GM, 2026-11-16: hidden from the model, not her call -- never in the mind verb, never in the <model> display block, and renderView's via-derived block filters it too, both surfaces; it rides the via record for the raw surfaces), its unset state SENDS the measured max-mean default (the one knob with an honestly nameable default -- the registry measured it; layers run override > deployment > registry per-model, explicit null clears to nothing), the first non-numeric knob (RoleParams carries the string, the /model route validates against the ladder, the knob row a select whose unset label names what rides and rebuilds on model-select change); the GLM ladder verified live by hand before the build (low suppresses to a third of baseline, max elevates about double, the whole ladder accepted on both families without 400s, and reasoning_effort 'none' doubles as a standardized thinking-off switch); the model dropdown, the composer, and the knob UX browser-proven with zero console errors (the pass caught the unreachable-helpers bug: code after a factory's return never runs, a hoisted function referencing the uninitialized const throws silently mid-fill and stale rows render); smoke ALL PASS with the effort battery (the canned mock ladders, the default riding a bare turn's via, the override riding the next turn, the bogus-level 400, the null clear, no reasoning_effort in any <model> block) + restart + reminder + repo checks green, typecheck green on both programs; ROADMAP gains the distant extension point (n-choice inference composed by a turn-editor agent) and the operator's queue moved there from QUESTIONS by the GM; HANDOFF prepared as the handoff (the typing-round bullet trimmed into the rounds list, the server line now truthful -- the debug server runs, the registry bullet carries the six-knob state and the pending-effort refine)
2026-11-16 23:52:58 +00:00

354 lines
16 KiB
JavaScript

// server/discovery.mjs -- model discovery: the registry.
//
// Two steps, both op acts from the SPA's admin block:
// - discover: scrape the provider surface (GET /models) -- API
// metadata only, zero inference. Writes the preliminary registry.
// - refine: run the inference battery over the scrape (deterministic
// probes, fixed prompts, fixed rules), then hand the adjudicated
// results to the best passing model (repo craft: curator.md) for
// the final registry -- families, labels, descriptions. The
// curator's output is strictly validated; any failure falls back
// to the raw deterministic list, so a bad model day can never
// block discovery. Defaults stay deterministic either way: the
// max-reasoning rule picks them, never the curator, and full ties
// settle by the lex rule (rankSort).
//
// The registry (state/models.json) is the truth of selectable
// models: a fresh deployment has none and model use is disabled
// until the op discovers. The selectors read it, the model routes
// validate against it, the turn loop enforces it. Mock mode runs
// the same two steps over a canned surface -- no network, instant.
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
/** @typedef {import('./shapes.mjs').JobState} JobState */
/** @typedef {import('./shapes.mjs').Actor} Actor */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseManifest } from './housekeeping.mjs';
import { ASK_GM_TOOL } from './bundle.mjs';
import { HttpError } from './loop.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const REGISTRY_PATH = path.join(ROOT, 'state', 'models.json');
const CURATOR_PROMPT = path.join(ROOT, 'curator.md');
const JOB_KEY = 'discovery';
// the reasoning battery's fixed puzzle -- same every run, so the
// buckets stay comparable across models and across discoveries
const PUZZLE = 'A bat and ball cost 1.10 in total. The bat costs 1.00 more than the ball. How much is the ball?';
// reasoning buckets, by measured thinking tokens (the max of the
// samples): the thresholds sit in the gaps the live endpoint showed
// (off 0 / low ~5 / standard ~10 / deep 150+). The pick rule ranks
// on the bucket, not the raw count: within a bucket the differences
// are sampling noise (the alias twins flip run to run), so only the
// bucket is a real difference.
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
function bucket(tokens) {
if (tokens <= 0) return 'off';
if (tokens <= 24) return 'low';
if (tokens <= 96) return 'standard';
return 'deep';
}
// --- the registry file --------------------------------------------------------
/** @returns {?ModelRegistry} */
export function registry() {
try {
return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8'));
} catch {
return null;
}
}
/** @param {ModelRegistry} reg */
function write(reg) {
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
}
/** A model is usable when the registry knows it and the battery (or
* the preliminary scrape) has not disqualified it. */
/** @param {?ModelRegistry} reg @param {string} id @returns {boolean} */
export function usable(reg, id) {
return !!reg && reg.models.some((m) => m.id === id && m.inference !== false);
}
// --- step one: discover (the scrape -- no inference) --------------------------
/** @param {Ctx} ctx @returns {Promise<RegistryModel[]>} */
async function scrape(ctx) {
if (ctx.mock) {
return [
{ id: 'mock', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-tie', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-cheap', input: 131072, output: 32768, status: 'unrefined' },
];
}
const listed = await ctx.provider.modelsMeta();
return listed.map((m) => ({ id: m.id, input: m.input, output: m.output, status: 'unrefined' }));
}
/** @param {Ctx} ctx @returns {Promise<ModelRegistry>} */
export async function discover(ctx) {
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
throw new HttpError(409, 'a refine is running -- let it finish first');
}
const models = await scrape(ctx);
const reg = /** @type {ModelRegistry} */ ({
phase: 'preliminary',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: new Date().toISOString(),
refined: null,
defaults: { player: null, housekeeper: null },
models,
});
write(reg);
return reg;
}
// --- step two: refine (the battery + the curator) -----------------------------
// the reasoning-effort ladder: the spellings the OpenAI-compatible
// world agrees on. `none` doubles as the standardized thinking-off
// switch. Mirrored in web/knobs.mjs for the select -- keep them in
// step.
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
/** One model's measured thinking under given request params.
* @param {Ctx} ctx @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
async function thinkingTokens(ctx, id, params) {
const data = await ctx.provider.chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...params });
return Number(data.usage?.completion_tokens_details?.reasoning_tokens ?? 0);
}
/** The reasoning-effort probe: each level's measured mean thinking
* (two samples, the battery's granularity). The default is the
* level with the highest observed mean -- `none` is never a
* candidate, it is the off switch, not a thinking level (GM,
* 2026-11-16: maximum observable thinking by default, overridable
* by the user). A model that shows no thinking, or that no level
* moves, gets null -- nothing rides.
* @param {Ctx} ctx @param {string} id @returns {Promise<{ efforts: Record<string, number>, effortDefault: ?string }>} */
async function probeEfforts(ctx, id) {
/** @type {Record<string, number>} */ const efforts = {};
for (const level of EFFORT_LEVELS) {
const xs = [];
for (let i = 0; i < 2; i++) {
try { xs.push(await thinkingTokens(ctx, id, { reasoning_effort: level })); } catch { xs.push(0); }
}
efforts[level] = Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
}
const candidates = EFFORT_LEVELS.filter((l) => l !== 'none');
const best = candidates.reduce((acc, l) => (efforts[l] > efforts[acc] ? l : acc), candidates[0]);
return { efforts, effortDefault: efforts[best] > 0 ? best : null };
}
/** The deterministic battery over one model: the tool ping (the
* exact request shape a player turn takes), the reasoning samples,
* the off-switch probe, the effort ladder. Every failure is a
* verdict, never an abort.
* @param {Ctx} ctx @param {RegistryModel} m @returns {Promise<RegistryModel>} */
async function probeOne(ctx, m) {
const base = { ...m };
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
if (ctx.mock) {
// the canned battery: all three stand-ins are inference models;
// mock and mock-tie are a deliberate tie pair (same deep bucket,
// same windows -- only the lex rule can part them), the cheap
// tier standard. The canned effort ladders exercise both shapes:
// the full ladder with max on top, and a capped ladder whose
// default is high
return m.id === 'mock-cheap'
? { ...base, inference: true, think: 120, reasoning: 'standard', offSwitch: null, latency: 5,
efforts: { none: 0, minimal: 20, low: 60, medium: 90, high: 120 }, effortDefault: 'high' }
: { ...base, inference: true, think: 300, reasoning: 'deep', offSwitch: null, latency: 7,
efforts: { none: 0, minimal: 40, low: 100, medium: 200, high: 300, xhigh: 400, max: 500 }, effortDefault: 'max' };
}
const t0 = Date.now();
try {
await ctx.provider.chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400 });
} catch (e) {
const fail = String(e.message ?? e).split('\n')[0].slice(0, 200);
return { ...base, inference: false, fail, reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: Date.now() - t0 };
}
const latency = Date.now() - t0;
const samples = [];
for (let i = 0; i < 2; i++) {
try { samples.push(await thinkingTokens(ctx, m.id, {})); } catch { samples.push(0); }
}
const think = Math.max(...samples);
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
if (think > 0) {
try {
if (await thinkingTokens(ctx, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
}
} catch { /* no off switch -- recorded as absent */ }
}
/** @type {Record<string, number>|null} */ let efforts = null;
/** @type {?string} */ let effortDefault = null;
if (think > 0) {
try {
({ efforts, effortDefault } = await probeEfforts(ctx, m.id));
} catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ }
}
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
}
// the pick rule, deterministic: the deepest reasoning bucket, then
// the largest input window, then the largest output ceiling, then
// the GM's tie-break -- sort lex, pick the bottom. The bucket, not
// the raw token count, is the rank (see bucket). It names the
// curator model and the deployment defaults -- correctness never
// consults taste.
/** @param {RegistryModel[]} models @returns {RegistryModel[]} */
function rankSort(models) {
const depth = { off: 0, low: 1, standard: 2, deep: 3 };
return [...models].sort((a, b) => {
const db = depth[b.reasoning ?? 'off'];
const da = depth[a.reasoning ?? 'off'];
if (db !== da) return db - da;
if ((b.input ?? 0) !== (a.input ?? 0)) return (b.input ?? 0) - (a.input ?? 0);
if ((b.output ?? 0) !== (a.output ?? 0)) return (b.output ?? 0) - (a.output ?? 0);
return a.id < b.id ? 1 : a.id > b.id ? -1 : 0; // lex bottom wins
});
}
/** The curator pass: the best model reads the adjudicated results
* and writes the presentation layer. Strictly validated -- only
* probed inference ids, no inventions; any violation discards the
* whole output and the machine list stands.
* @param {Ctx} ctx @param {RegistryModel[]} probed @param {RegistryModel} best @param {?Actor} user
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }>} */
async function curate(ctx, probed, best, user) {
if (ctx.mock) {
return {
list: [
{ id: 'mock', family: 'mock', label: 'Mock', description: 'The scripted stand-in.', player: true, housekeeper: true },
{ id: 'mock-tie', family: 'mock', label: 'Mock (tie)', description: 'The scripted stand-in, tie tier.', player: true, housekeeper: true },
{ id: 'mock-cheap', family: 'mock', label: 'Mock (cheap)', description: 'The scripted stand-in, cheap tier.', player: true, housekeeper: true },
],
note: 'curated',
};
}
const facts = probed.map((m) => ({
id: m.id, input: m.input, output: m.output, inference: m.inference ?? false,
fail: m.fail ?? null, reasoning: m.reasoning ?? null, hasOffSwitch: !!m.offSwitch, latencyMs: m.latency ?? null,
effortDefault: m.effortDefault ?? null,
}));
const messages = /** @type {import('./shapes.mjs').ViewMessage[]} */ ([
{ role: 'system', content: fs.readFileSync(CURATOR_PROMPT, 'utf8').trim() },
{ role: 'user', content: JSON.stringify(facts, null, 2) },
]);
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${best.id} u:${user?.id ?? '?'}`);
// one retry: the call is long enough to meet a network hiccup, and
// a fresh attempt is cheaper than losing the curation
let data = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
data = await ctx.provider.chat(best.id, messages, undefined, {});
break;
} catch (e) {
if (attempt === 1) throw e;
console.log(`${new Date().toISOString().slice(11, 19)} curator call failed (${String(e.message ?? e).split('\n')[0]}) -- retrying once`);
}
}
if (!data) throw new Error('the curator call failed twice');
const known = new Set(probed.filter((m) => m.inference).map((m) => m.id));
let parsed;
try {
parsed = /** @type {{ models?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
} catch (e) {
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})` };
}
const entries = Array.isArray(parsed.models) ? parsed.models : null;
if (!entries) return { list: [], note: 'fallback: the curator output has no models array' };
const seen = new Set();
/** @type {{ id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[]} */ const list = [];
for (const e of entries) {
if (typeof e !== 'object' || e === null || typeof e.id !== 'string' || !known.has(e.id) || seen.has(e.id)) {
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})` };
}
seen.add(e.id);
list.push({
id: e.id,
family: typeof e.family === 'string' && e.family.trim() ? e.family.trim() : null,
label: typeof e.label === 'string' && e.label.trim() ? e.label.trim() : null,
description: typeof e.description === 'string' && e.description.trim() ? e.description.trim() : null,
player: e.player !== false,
housekeeper: e.housekeeper !== false,
});
}
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing' };
return { list, note: 'curated' };
}
/** The refine job: scrape fresh, battery, adjudicate, curate, write.
* Runs async under the jobs map; the registry only moves forward on
* a completed pass (a rejected pass changes nothing).
* @param {Ctx} ctx @param {?Actor} user @returns {JobState} */
export function refine(ctx, user) {
const reg = registry();
if (!reg) throw new HttpError(409, 'nothing to refine -- run discovery first');
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
throw new HttpError(409, 'a refine is already running');
}
const job = /** @type {JobState} */ ({ state: 'running', phase: 'refine', started: new Date().toISOString() });
ctx.jobs.set(JOB_KEY, job);
void (async () => {
try {
const scraped = await scrape(ctx); // fresh metadata -- ids can drift between discoveries
const probed = [];
for (const m of scraped) probed.push(await probeOne(ctx, m));
const passing = probed.filter((m) => m.inference);
if (!passing.length) throw new Error('no model passed the inference battery -- the provider surface has nothing playable');
const best = rankSort(passing)[0];
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }} */
let curated = { list: [], note: 'fallback: not attempted' };
try {
curated = await curate(ctx, probed, best, user);
} catch (e) {
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})` };
}
const byId = new Map(curated.list.map((c) => [c.id, c]));
const models = probed.map((m) => {
const c = m.inference ? byId.get(m.id) : undefined;
return c ? { ...m, family: c.family, label: c.label, description: c.description, roles: { player: c.player, housekeeper: c.housekeeper } } : m;
});
// the defaults never consult the curator: the max-reasoning
// rule over the models eligible for the role
/** @param {(m: RegistryModel) => boolean} ok @returns {?string} */
const pick = (ok) => {
const eligible = models.filter((m) => m.inference && (m.roles?.player ?? true) && ok(m));
return eligible.length ? rankSort(eligible)[0].id : null;
};
const defaults = { player: pick(() => true), housekeeper: pick((m) => m.roles?.housekeeper ?? true) };
write(/** @type {ModelRegistry} */ ({
phase: 'refined',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: reg.discovered,
refined: new Date().toISOString(),
defaults,
models,
curator: curated.note,
}));
job.state = 'applied';
} catch (e) {
job.state = 'rejected';
job.reason = String(e.message ?? e);
}
})();
return job;
}
/** @param {Ctx} ctx @returns {?JobState} */
export function jobState(ctx) {
return ctx.jobs.get(JOB_KEY) ?? null;
}