the provider round and the provider-flow round, plus the template and box packages

the provider round (2026-11-18, batteries-included): providers are first-class entities, the config is server-written state (state/config.json), and a fresh clone boots playable -- the opencode/free singleton auto-added and discovered on the empty list, playable with zero secrets. Every request resolves a full spec {provider, model, effort}: no unset effort, the per-run params layer retired, the mind verb the only sampling source. The registry is per-provider sections (state/models.json), refine caches adjudications under the double spec tuple (state/refine-cache.json), run picks are invalidatable (a removed provider or drifted model blocks the run with the note naming what died), and the housekeeper inherits the player spec's provider default (#16 closed). The no-legacy pass died the same day it shipped: bootImport deleted (server.json is bind + contwin), the registry's v1/v2 in-memory migrations deleted (models.json rewritten on disk into the per-provider shape), bare-string model picks deleted (Chloe's run.json migrated to spec objects, shape-preserving), the clerk's create model arg deleted, apiKeyEnv and the contextWindow alias gone. The live arc proven from a bare boot: invite minted, o/f auto-added, a custom provider with a bogus key (the recognizable 401), the auth fixed (13 models), the default pair selected, and a real glm-5.3 turn through the full path. Two live findings: opencode.ai serves 89 models keyless but 401s an empty Bearer header (the auth header rides only when a key exists), and the failure log line rides stderr.

the provider-flow round (2026-11-19, GM-designed): discovery IS the probe. The add takes only the endpoint -- {slug, baseUrl} or {builtin: true}, an apiKey in the body 400s (the auth route is the only key path) -- and a working keyless listing never sees a key field. A 401/403 stands the provider broken: the entity carries a probe record (outcome ok/auth/error, detail, at), the card opens the ask, and only the explicit acts move the record -- add, key, remove-key, discover; usage errors are transient and the op's to fix, nothing in the runtime flips provider state. The auth route is probe-then-save: the candidate key checks on reception, saves only on success -- a still-refused key never reaches the config, the previous state returns, the ask repeats. Every other discovery failure refuses the add outright with rollback: an endpoint that cannot answer is not a provider, nothing stands (the old code let it stand on any failure). The remove-key control (custom providers, armed) clears and re-probes: a provider gone public lands working keyless, a locked one re-opens the ask -- which is the key-replacement path. o/f never asks in any state: its auth failures are upstream breakage to show, not a prompt. The universal retry rule: NO automatic retries anywhere -- every inference call is user-initiated (the send, the housekeeping run, the refine) and every act has its manual retry; the curator's one auto-retry (the 2026-11-17 hiccup lesson) is deleted, the machine-label fallback the designed outcome. And failures never cache (GM: a failure is the absence of a measurement, not a measurement) -- the adjudication cache skips inference:false entries, the receipt line says "never cached, retried at every refine", and a transient battery error can never pin a false verdict; gev's 400s cost one cheap probe per refine and self-heal the day the backend learns tools. En-route fix the smoke earned: the create route validated body.spec AFTER the clerk built the run dir -- a refused spec left an orphan run (restart-check's exact count caught the sixth run); the spec validates first now, nothing lands on refusal.

the sheet's transport at the lint: the record is the only channel, the tag is view machinery composed by renderView, never authored by anyone -- the authored gate names the tag in any content (hers would never apply and primes the guarded emission; GM prose rides the view and story raw, the GM-side strips do not know it), names a sheet record on her turn, and checks object-ness on GM-turn records and boundary state notes both kinds; her emitted sheet in a carried tail stays legitimate history (the log keeps guard-conflicted emissions verbatim, and a stop can move one into the slidwin). The carryover editor teaches its own format now: a per-file hint between the editor and the save bar (one JSON object per line; status and agenda ride her turns; the sheet rides yours as the "sheet" field, never as a tag; the sigils and $VARS expand at start on the authored opening only).

the packages: template (the base for new packages -- the mood-indexed voice examples, the settings comment convention, non-playable as-is) and box (the sheet's first consumer: an incremental-game economy as ERP, GP and BP as two currencies with the room pushing her to fund her own punishments; the opening turn third-person per the typography ruling, ending on the display that needs a second read; the amnesiac rings empty by design; the erased name reading "(redacted)" after sigil expansion). The review found and fixed: both carryovers were pretty-printed JSON with duplicate keys -- unstartable under every per-line reader, flattened to true JSONL; the box's opening sheet rode her authored prose -- dead on every surface (the scan reads GM-turn records only, the strips eat it) and priming the exact emission the guard conflicts -- moved to the GM turn's sheet record, the override's shape; the gm.md "take of leave" typo fixed in all three packages.

the lint's rule 4 scoped to the substrate (GM, 2026-11-19): a banned word in a package's prose is fine -- the packages are the fiction and their words are the story's; README and the root prompts stay patrolled, and the box's "Or windows" is an architectural plural in a padded cell.

verified: typecheck green both programs; smoke ALL PASS (+27 the provider-flow battery: apiKey-on-add 400, the dead-endpoint refusal with config rollback, the auth-standing card with its probe record, probe-then-save both ways, the remove-key round trip, the o/f guards, the failures-never-cache proof over mock-fail -- verdict with the marker, absent from the cache file, re-probed fresh while the passing three serve from cache, not selectable, no orphan run; +8 the sheet-transport lint battery); restart + reminder checks green; a browser pass driving the whole add-flow machine on a mock+debug server (the hidden key field opening on the 401, the key landing through the auth route, the remove-key round trip re-opening the ask, the dead add refusing with the banner and no card, zero console errors beyond the expected 401/500 resource lines); check-repo clean with the box's windows. detention stays untracked WIP, untouched.
This commit is contained in:
2026-11-19 08:35:23 +00:00
parent 14b9b01d86
commit e60fd63d2b
42 changed files with 3071 additions and 1086 deletions
+334 -170
View File
@@ -1,25 +1,40 @@
// server/discovery.mjs -- model discovery: the registry.
// server/discovery.mjs -- model discovery: the per-provider 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).
// Two steps, both op acts from the SPA's admin block, both per
// provider (GM, 2026-11-18):
// - discover: scrape one provider's surface (GET /models) -- API
// metadata only, zero inference. Writes that provider's registry
// section, resetting it to preliminary; the other sections are
// untouched. Cheap by design -- re-running it is nothing to
// treasure (o/f churns its model list, and discovery churn with it
// is expected).
// - refine: run the inference battery over that provider's scrape
// (deterministic probes, fixed prompts, fixed rules), then hand
// the adjudicated results to the op's selected default model (repo
// craft: curator.md) for labels and one overall-best recommendation
// -- intel only, applied by the op's click, never auto-landed. The
// curator's output is strictly validated; any failure falls back to
// the raw deterministic list and no recommendation, so a bad model
// day can never block discovery -- the op just gets no advice.
//
// 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.
// The adjudication cache (state/refine-cache.json): a refined entry
// is a function of the full spec tuples on both sides -- the probed
// model at the effort the deployment will actually send, and the
// curator at its own spec (a weak curator at a low effort adjudicates
// worse; it is an inference request like any other). Keyed by
// {provider, model, effort, curator-model, curator-effort}; a refine
// that sees the same tuple reuses the cached entry and refreshes it
// in place when it re-probes. Discovery never touches the cache --
// the scrape is cheap, the battery is what costs.
//
// The registry (state/models.json) is per-provider sections, the
// truth of selectable models: the selectors read a section, the model
// routes validate against it, the turn loop enforces it. A provider
// not in the config has no section. Mock mode runs the same steps
// over canned surfaces -- no network, instant.
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
/** @typedef {import('./shapes.mjs').RegistrySection} RegistrySection */
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
/** @typedef {import('./shapes.mjs').JobState} JobState */
/** @typedef {import('./shapes.mjs').Actor} Actor */
@@ -30,11 +45,12 @@ import { fileURLToPath } from 'node:url';
import { parseManifest } from './housekeeping.mjs';
import { ASK_GM_TOOL } from './bundle.mjs';
import { HttpError } from './loop.mjs';
import { providerFor } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const REGISTRY_PATH = path.join(ROOT, 'state', 'models.json');
const CACHE_PATH = path.join(ROOT, 'state', 'refine-cache.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
@@ -42,10 +58,9 @@ const PUZZLE = 'A bat and ball cost 1.10 in total. The bat costs 1.00 more than
// 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.
// (off 0 / low ~5 / standard ~10 / deep 150+). The bucket, not the
// raw count, is the real difference -- within a bucket the
// differences are sampling noise.
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
function bucket(tokens) {
if (tokens <= 0) return 'off';
@@ -56,92 +71,168 @@ function bucket(tokens) {
// --- the registry file --------------------------------------------------------
/** @returns {?ModelRegistry} */
/** The registry, as state/models.json holds it: one section per
* configured provider slug. A provider absent from the config has
* no section (removal deletes it); a provider not yet discovered
* has none either. No legacy shapes are read (the no-legacy rule,
* GM, 2026-11-18): shape changes come with one-time migrations of
* the file, not permanent tolerance in the reader.
* @returns {?ModelRegistry} */
export function registry() {
try {
return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8'));
const reg = /** @type {?ModelRegistry} */ (JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8')));
return reg && typeof reg === 'object' && reg.providers && typeof reg.providers === 'object' && !Array.isArray(reg.providers) ? reg : null;
} catch {
return null;
}
}
/** @param {ModelRegistry} reg */
function write(reg) {
function writeRegistry(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);
/** @param {string} slug @returns {?RegistrySection} */
export function sectionOf(slug) {
return registry()?.providers[slug] ?? null;
}
/** Write one provider's section; the others are untouched.
* @param {string} slug @param {RegistrySection} section */
function writeSection(slug, section) {
const reg = registry() ?? /** @type {ModelRegistry} */ ({ providers: {} });
reg.providers[slug] = section;
writeRegistry(reg);
}
/** Remove one provider's section whole -- provider removal's other
* half (the runs that rode it invalidate at their next send).
* @param {string} slug */
export function deleteSection(slug) {
const reg = registry();
if (!reg || !reg.providers[slug]) return;
delete reg.providers[slug];
writeRegistry(reg);
}
/** A model is usable when its provider's section knows it and the
* battery (or the preliminary scrape) has not disqualified it. */
/** @param {string} slug @param {string} id @returns {boolean} */
export function usable(slug, id) {
const m = findModel(slug, id);
return !!m && m.inference !== false;
}
/** @param {string} slug @param {string} id @returns {?RegistryModel} */
export function findModel(slug, id) {
return sectionOf(slug)?.models.find((m) => m.id === id) ?? null;
}
// --- 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' },
];
/** The canned mock surface: the two synthetic providers split the
* list (the multi-provider tagging rides the smoke end to end), any
* other slug gets the full set -- so the SPA's add flow is testable
* offline, the o/f singleton included.
* @param {string} slug @returns {RegistryModel[]} */
function mockSurface(slug) {
/** @type {RegistryModel[]} */ const all = [
{ 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' },
{ id: 'mock-fail', input: 131072, output: 32768, status: 'unrefined' },
];
if (slug === 'mock-a') return all.slice(0, 2);
if (slug === 'mock-b') return [all[2]];
if (slug === 'mock-c') return all;
return all.slice(0, 3);
}
/** The mock's probe shapes (the add-flow machine, offline): mock-auth
* refuses the listing until a key stands on the entity, mock-lock
* refuses whatever is sent, mock-dead never answers. The real
* failures carry the same shapes -- 401/403 with the status on the
* error, everything else without.
* @param {Ctx} ctx @param {string} slug */
function mockProbeShape(ctx, slug) {
const p = ctx.providerCfg.providers.find((x) => x.slug === slug);
if (slug === 'mock-auth' && !(p && p.apiKey)) {
throw new HttpError(401, 'the mock refuses unauthenticated listings');
}
const listed = await ctx.provider.modelsMeta();
if (slug === 'mock-lock') {
throw new HttpError(401, 'the mock refuses every listing, keyed or not');
}
if (slug === 'mock-dead') {
throw new Error('the mock endpoint did not answer');
}
}
/** Scrape one provider: the listing with the API metadata the
* registry carries (token ceilings when the provider states them).
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistryModel[]>} */
async function scrape(ctx, slug) {
if (ctx.mock) {
mockProbeShape(ctx, slug);
return mockSurface(slug).map((m) => ({ ...m }));
}
const listed = await providerFor(ctx, slug).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');
/** Discover one provider: the scrape, the section written
* preliminary. Resets a refined section -- the honest behavior, and
* the reason the SPA's discover button says so.
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistrySection>} */
export async function discover(ctx, slug) {
if (!ctx.providerCfg.providers.some((p) => p.slug === slug)) {
throw new HttpError(404, `no such provider: ${slug}`);
}
const models = await scrape(ctx);
const reg = /** @type {ModelRegistry} */ ({
const models = await scrape(ctx, slug);
const section = /** @type {RegistrySection} */ ({
phase: 'preliminary',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: new Date().toISOString(),
refined: null,
defaults: { player: null, housekeeper: null },
models,
curator: null,
recommendation: null,
});
write(reg);
return reg;
writeSection(slug, section);
return section;
}
// --- 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
// switch. Mirrored in web/knobs.mjs for the selects -- 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 });
* @param {Ctx} ctx @param {string} slug @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
async function thinkingTokens(ctx, slug, id, params) {
const data = await providerFor(ctx, slug).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 @param {(s: string) => void} [say]
* candidate, it is the off switch. A model that shows no thinking,
* or that no level moves, gets null. Pre-fill and hint only (GM,
* 2026-11-18): with effort a property of the model pick, the
* measured default never rides a turn implicitly -- it pre-selects
* the selection dropdown and informs the curator's recommendation.
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say]
* @returns {Promise<{ efforts: Record<string, number>, effortDefault: ?string }>} */
async function probeEfforts(ctx, id, say = () => {}) {
async function probeEfforts(ctx, slug, m, say = () => {}) {
/** @type {Record<string, number>} */ const efforts = {};
for (const level of EFFORT_LEVELS) {
const xs = [];
for (let i = 0; i < 2; i++) {
say(`${level}, sample ${i + 1}/2`);
try { xs.push(await thinkingTokens(ctx, id, { reasoning_effort: level })); } catch { xs.push(0); }
try { xs.push(await thinkingTokens(ctx, slug, m.id, { reasoning_effort: level })); } catch { xs.push(0); }
}
efforts[level] = Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
}
@@ -151,32 +242,34 @@ async function probeEfforts(ctx, id, say = () => {}) {
}
/** The deterministic battery over one model: the tool ping (the
* exact request shape a player turn takes), the reasoning samples,
* exact request shape a player turn takes -- the working effort
* rides, because every real turn sends one), the reasoning samples,
* the off-switch probe, the effort ladder. Every failure is a
* verdict, never an abort.
* @param {Ctx} ctx @param {RegistryModel} m @param {(s: string) => void} [say]
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say] @param {string} [effort]
* @returns {Promise<RegistryModel>} */
async function probeOne(ctx, m, say = () => {}) {
async function probeOne(ctx, slug, m, say = () => {}, effort = '') {
const base = { ...m };
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
if (ctx.mock) {
say('the canned battery');
// 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
// same windows), 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' }
: m.id === 'mock-fail'
? { ...base, inference: false, fail: 'the canned failure -- a classifier that cannot tool', reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: 3 }
: { ...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();
say('the tool probe');
try {
await ctx.provider.chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400 });
await providerFor(ctx, slug).chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400, ...(effort ? { reasoning_effort: effort } : {}) });
} 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 };
@@ -185,14 +278,14 @@ async function probeOne(ctx, m, say = () => {}) {
const samples = [];
for (let i = 0; i < 2; i++) {
say(`the thinking samples, ${i + 1}/2`);
try { samples.push(await thinkingTokens(ctx, m.id, {})); } catch { samples.push(0); }
try { samples.push(await thinkingTokens(ctx, slug, m.id, {})); } catch { samples.push(0); }
}
const think = Math.max(...samples);
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
if (think > 0) {
try {
say('the off-switch probe');
if (await thinkingTokens(ctx, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
if (await thinkingTokens(ctx, slug, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
}
} catch { /* no off switch -- recorded as absent */ }
@@ -201,39 +294,65 @@ async function probeOne(ctx, m, say = () => {}) {
/** @type {?string} */ let effortDefault = null;
if (think > 0) {
try {
({ efforts, effortDefault } = await probeEfforts(ctx, m.id, (s) => say(`the effort ladder: ${s}`)));
({ efforts, effortDefault } = await probeEfforts(ctx, slug, m, (s) => say(`the effort ladder: ${s}`)));
} 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 adjudication cache ---------------------------------------------------
/** The cache key: the full spec tuples on both sides -- the probed
* model at the effort the deployment will actually send, and the
* curator at its own spec. Reasoning effort substantially changes
* inference quality (GM, 2026-11-18), so an entry adjudicated under
* one tuple never speaks for another.
* @param {string} slug @param {string} id @param {string} effort @param {string} cm @param {string} ce @returns {string} */
function cacheKey(slug, id, effort, cm, ce) {
return `${slug}::${id}::${effort}::${cm}::${ce}`;
}
/** 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
* @param {?import('./provider.mjs').ProgressFn} [onProgress] @param {?(() => void)} [onRetry]
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }>} */
async function curate(ctx, probed, best, user, onProgress = null, onRetry = null) {
/** @returns {Record<string, RegistryModel>} */
function readCache() {
try {
const c = JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));
if (c && typeof c === 'object' && c.entries && typeof c.entries === 'object') {
return /** @type {Record<string, RegistryModel>} */ (c.entries);
}
} catch { /* absent -- the cache starts empty */ }
return {};
}
/** @param {Record<string, RegistryModel>} entries */
function writeCache(entries) {
fs.mkdirSync(path.dirname(CACHE_PATH), { recursive: true });
fs.writeFileSync(CACHE_PATH, JSON.stringify({ entries }, null, 2) + '\n');
}
/** Provider removal purges its entries -- the models are gone with
* the route.
* @param {string} slug */
export function purgeCache(slug) {
const entries = readCache();
const prefix = `${slug}::`;
let dirty = false;
for (const k of Object.keys(entries)) {
if (k.startsWith(prefix)) { delete entries[k]; dirty = true; }
}
if (dirty) writeCache(entries);
}
// --- the curator pass ---------------------------------------------------------
/** The curator pass: the op's selected default model reads the
* adjudicated results and writes the presentation layer -- labels,
* and one overall-best recommendation (intel only). Strictly
* validated -- only probed inference ids, no inventions; any
* violation discards the whole output and the machine list stands.
* @param {Ctx} ctx @param {string} slug @param {RegistryModel[]} probed @param {{ model: string, effort: string }} curatorSpec @param {?Actor} user
* @param {?import('./provider.mjs').ProgressFn} [onProgress]
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }>} */
async function curate(ctx, slug, probed, curatorSpec, user, onProgress = null) {
if (ctx.mock) {
return {
list: [
@@ -242,6 +361,7 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
{ id: 'mock-cheap', family: 'mock', label: 'Mock (cheap)', description: 'The scripted stand-in, cheap tier.', player: true, housekeeper: true },
],
note: 'curated',
recommendation: { model: 'mock', effort: 'max' },
};
}
const facts = probed.map((m) => ({
@@ -254,35 +374,27 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
{ 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, {}, onProgress);
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`);
onRetry?.();
}
}
console.log(`${new Date().toISOString().slice(11, 19)} llm ${curatorSpec.model} u:${user?.id ?? '?'}`);
// no automatic retries (GM, 2026-11-19): every inference call is
// user-initiated and every act has its manual retry -- the refine
// button again. A dead call lands the fallback, which is the
// designed outcome, not a degraded one
const data = await providerFor(ctx, slug).chat(curatorSpec.model, messages, undefined, { reasoning_effort: curatorSpec.effort }, onProgress);
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 ?? ''));
parsed = /** @type {{ models?: unknown, recommend?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
} catch (e) {
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})` };
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})`, recommendation: null };
}
const entries = Array.isArray(parsed.models) ? parsed.models : null;
if (!entries) return { list: [], note: 'fallback: the curator output has no models array' };
if (!entries) return { list: [], note: 'fallback: the curator output has no models array', recommendation: null };
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)})` };
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})`, recommendation: null };
}
seen.add(e.id);
list.push({
@@ -294,99 +406,151 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
housekeeper: e.housekeeper !== false,
});
}
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing' };
return { list, note: 'curated' };
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing', recommendation: null };
// the recommendation: intel only, strictly validated -- a passing
// model at a ladder level. Anything else is no advice, never
// machine advice (GM, 2026-11-18: on a bad model day the op gets
// no recommendation, not a deterministic stand-in)
let recommendation = null;
const r = /** @type {{ model?: unknown, effort?: unknown }|null|undefined} */ (parsed.recommend);
if (r && typeof r === 'object' && typeof r.model === 'string' && known.has(r.model)
&& typeof r.effort === 'string' && EFFORT_LEVELS.includes(r.effort)) {
recommendation = { model: r.model, effort: r.effort };
}
return { list, note: 'curated', recommendation };
}
/** 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');
// --- the refine job -----------------------------------------------------------
/** The refine job: scrape fresh, battery, adjudicate, curate, write
* the one provider's section. Runs async under the jobs map; the
* section only moves forward on a completed pass (a rejected pass
* changes nothing).
* @param {Ctx} ctx @param {string} slug @param {?Actor} user @returns {JobState} */
export function refine(ctx, slug, user) {
const provider = ctx.providerCfg.providers.find((p) => p.slug === slug);
if (!provider) throw new HttpError(404, `no such provider: ${slug}`);
const section = sectionOf(slug);
if (!section) throw new HttpError(409, `nothing to refine on '${slug}' -- run its discovery first`);
// the curator IS the selected default (GM, 2026-11-18) -- refine
// requires the selection
const curatorSpec = provider.default;
if (!curatorSpec) {
throw new HttpError(409, `select '${slug}'s default model first -- the default is also the refine curator`);
}
// the meter: one step per model's battery plus the curator's two
// (thinking, writing) -- the count is known the moment the scrape
// lands. No step has a duration to guess at (GM, 2026-11-17): the
// bar moves only on real completions, the label names the call
// running now, and every completion lands a receipt line -- the
// lines survive the job, so a rejected pass keeps its post-mortem
const jobKey = `refine:${slug}`;
if (ctx.jobs.get(jobKey)?.state === 'running') {
throw new HttpError(409, `a refine is already running on '${slug}'`);
}
// the meter: one step per model's battery (a cache hit closes its
// step instantly -- it is a completion, not a wait) plus the
// curator's two (thinking, writing). No step has a duration to
// guess at (GM, 2026-11-17): the bar moves only on real
// completions, the label names the call running now, and every
// completion lands a receipt line -- the lines survive the job, so
// a rejected pass keeps its post-mortem
const t0 = Date.now();
// the local view narrows steps/lines to present -- the job is born
// with them, and the reporter writes through this reference
const job = /** @type {JobState & { steps: { total: number, done: number, label: string, chars?: number }, lines: string[] }} */ ({
state: 'running', phase: 'refine', started: new Date().toISOString(),
steps: { total: 0, done: 0, label: 'scraping the provider surface' }, lines: [],
});
ctx.jobs.set(JOB_KEY, job);
ctx.jobs.set(jobKey, job);
/** @param {string} s */ const say = (s) => { job.steps.label = s; };
/** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); };
void (async () => {
try {
const scraped = await scrape(ctx); // fresh metadata -- ids can drift between discoveries
const scraped = await scrape(ctx, slug); // fresh metadata -- ids can drift between discoveries
if (!scraped.some((m) => m.id === curatorSpec.model)) {
throw new Error(`the selected default '${curatorSpec.model}' is not in '${slug}'s current registry -- re-discover and re-select`);
}
job.steps.total = scraped.length + 2;
/** @param {RegistryModel} m @returns {string} */
const verdict = (m) => m.inference === false
? `failed the tool probe -- ${m.fail}`
: `reasoning ${m.reasoning} \u00b7 ${m.think} think tokens \u00b7 ${m.offSwitch ? 'off switch' : 'no off switch'} \u00b7 ${m.latency}ms${m.effortDefault ? ` \u00b7 effort default ${m.effortDefault}` : ''}`;
const probed = [];
// the adjudication cache: same tuple, same verdict -- churn is
// the point (o/f rotates models; the survivors keep their
// measured selves between refines)
const cache = readCache();
/** @type {RegistryModel[]} */ const probed = [];
/** @type {RegistryModel[]} */ const fresh = [];
for (const [i, m] of scraped.entries()) {
probed.push(await probeOne(ctx, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`)));
const key = cacheKey(slug, m.id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort);
const hit = cache[key];
if (hit) {
say(`battery ${i + 1}/${scraped.length}: ${m.id} -- cached`);
probed.push(hit);
line(`${m.id}: from cache`);
} else {
probed.push(await probeOne(ctx, slug, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`), curatorSpec.effort));
fresh.push(probed[probed.length - 1]);
// failures never cache (GM, 2026-11-19): a failure is the
// absence of a measurement, not a measurement -- the next
// refine always re-probes it, so the receipt says so
line(`${m.id}: ${verdict(probed[probed.length - 1])}${probed[probed.length - 1].inference === false ? ' -- never cached, retried at every refine' : ''}`);
}
job.steps.done++;
line(`${m.id}: ${verdict(probed[i])}`);
}
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' };
// the curator's two steps, marked from real events: thinking
// completes at the first prose delta (the streaming boundary),
// writing at the call's resolve; a dead call closes both -- the
// attempt is over, and the fallback carries the job
let proseStarted = false;
say(`curator (${best.id}): thinking`);
try {
curated = await curate(ctx, probed, best, user, (p) => {
job.steps.chars = p.chars;
if (p.phase === 'prose' && !proseStarted) {
proseStarted = true;
job.steps.done++;
say('curator: writing');
}
}, () => say(`curator (${best.id}): retrying -- thinking`));
} catch (e) {
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})` };
say(`curator (${curatorSpec.model}): thinking`);
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }} */
let curated = { list: [], note: 'fallback: not attempted', recommendation: null };
const curatorModel = probed.find((m) => m.id === curatorSpec.model);
if (curatorModel?.inference === false) {
curated = { list: [], note: 'fallback: the curator model failed the battery -- re-select the default', recommendation: null };
line(`curator: ${curated.note}`);
} else {
try {
curated = await curate(ctx, slug, probed, curatorSpec, user, (p) => {
job.steps.chars = p.chars;
if (p.phase === 'prose' && !proseStarted) {
proseStarted = true;
job.steps.done++;
say('curator: writing');
}
});
} catch (e) {
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})`, recommendation: null };
}
}
job.steps.done = job.steps.total; // the attempt is over -- whatever remains closes with it
delete job.steps.chars;
say('writing the registry');
line(curated.note === 'curated' ? `curator (${best.id}): curated \u00b7 ${curated.list.length} labeled` : `curator: ${curated.note}`);
line(curated.note === 'curated' ? `curator (${curatorSpec.model}): curated \u00b7 ${curated.list.length} labeled${curated.recommendation ? ` \u00b7 recommends ${curated.recommendation.model} at ${curated.recommendation.effort}` : ''}` : `curator: ${curated.note}`);
// labels apply to the freshly probed models only -- a cache hit
// keeps the entry it was adjudicated with (the same curator
// tuple, the cached verdict IS the verdict)
const byId = new Map(curated.list.map((c) => [c.id, c]));
const models = probed.map((m) => {
if (!fresh.includes(m)) return m; // a cache hit -- kept whole
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} */ ({
writeSection(slug, /** @type {RegistrySection} */ ({
phase: 'refined',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: reg.discovered,
discovered: section.discovered,
refined: new Date().toISOString(),
defaults,
models,
curator: curated.note,
recommendation: curated.recommendation,
}));
// the cache write-back: every final PASSING entry lands under
// its key -- the labeled result, not the bare probe (the cached
// entry IS the verdict, curation included), a re-probe refreshes
// in place, the survivors persist. Failures never cache (GM,
// 2026-11-19): only a measurement is worth keeping -- a failure
// is retried at every refine until it stops being one
for (const [i, m] of models.entries()) {
if (m.inference === false) continue;
cache[cacheKey(slug, scraped[i].id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort)] = m;
}
writeCache(cache);
say('done');
job.state = 'applied';
} catch (e) {
@@ -397,7 +561,7 @@ export function refine(ctx, user) {
return job;
}
/** @param {Ctx} ctx @returns {?JobState} */
export function jobState(ctx) {
return ctx.jobs.get(JOB_KEY) ?? null;
/** @param {Ctx} ctx @param {string} slug @returns {?JobState} */
export function jobState(ctx, slug) {
return ctx.jobs.get(`refine:${slug}`) ?? null;
}