Files
tiny-worlds/server/discovery.mjs
T
mute ccdd9ea129 the roles inventory: every human and inferencer seat named, the vocabulary swept, and the duties audit
the inventory (GM-designed in conversation, 2026-11-19): six human roles -- the developer (maintains the repo, and is the system packages author by consequence: system packages ship in the repo), the deployment operator (maintains a deployment: identities, providers, the registry; filesystem access as recovery; never a reader of runs' private surfaces -- owner-gating holds even against the superuser), the deployment user (any claimed identity; the only reach is the API -- no filesystem, no keys, ever), the package author (an off-platform seat: authorship travels with the files, the machinery sees only the publisher), a run's GM (maintains a run they own -- the same person the machinery records as the run's owner, one role two names, never split; the fork creates a second GM seat over a branching canon), and the reader (defined by the act, membership-free: on-platform any signed-in user, off-platform anyone the story text reaches). The inferencer roles: the assistant, the player, the housekeeper, the curator, the clerk (code, never a model), and the bookkeeper (parked). The example that pinned the mappings: Alice the op forking Bob's Faye into her Kate (hats stack, seats don't), Charlie authoring package files Bob publishes (the author-publisher split), Dave reading the exported story with no invite at all (the reader needs nothing).

the naming convention, stated in AGENTS's header and DICTIONARY both: "GM" always means a run's GM, everywhere; ruling attributions name the developer; the assistant is the assistant; the op stays the op. The role line that is never crossed (developer, 2026-11-19): the assistant is NOT the player -- player-facing instructions are for the assistant to understand how the player would interpret them, never to follow. The root prompts and every model-facing string were already correct (GM there was always the run's GM) and are untouched; the packages' fiction is exempt from the term lint (rule 4 scopes to the substrate: README and the root prompts); the records keep their day's words -- DECISIONS gained one dated header note mapping the old usage instead of a rewrite ("GM" in a ruling attribution is the developer, "the agent" is the assistant).

the sweep: 125+ ruling attributions rewritten across living prose and code comments in every spelling the repo used (paren-wrapped, date-first, mid-sentence, line-wrapped); AGENTS.md fully re-voiced (the header rewritten, "the agent" gone, the developer-meaning prose fixed line by line); README's "invited players" became "invited users"; the gm.md carve-out made precise everywhere (the file is the run's GM's private file, the flagging target is the developer, the non-editor is the assistant).

the word retirements, both lint-banned in rule 4 exactly like "window": "agent" (the word did too many jobs at once; every seat is named; the filename AGENTS.md consumed as-is, "Windows" the OS the precedent) and "LLM" (the class word is "inferencer(s)"; "model" kept as the machinery's noun -- a registry entry, never a seat: a model is what the registry lists, an inferencer is who a seat is). The fixes the bans forced: the exposure rule's "internal agents" -> "internal inferencers", the hypothetical "status-keeper agent" -> invocation, the bookkeeper shed its "agent" tag, "player-model" fell to "the player" everywhere including housekeeper.md's one prompt hit, README's "inference key" and its Roles section re-voiced, the #22 attribution comments at the three call sites, and the runtime log markers renamed (llm -> inferencer, a meaning-preserving log rename under the no-legacy rule). DICTIONARY's renames section carries both retirement entries.

the duties audit (along the what-hats-do lines: the developer maintains the repo, the op maintains a deployment, a user's only reach is the API, a run's GM maintains their run). Found and fixed: README's Housekeeping section was pre-split era text -- "every housekeeping pass should end in a commit" and "confess in the commit message" (runs/ is gitignored; the developer's commit duty was assigned to the run flow), the dead packages/<story>/dumps and packages/<story>/db paths (the dump is per-session under runs/<id>/sessions/<n>/), "canon/ stays committed", and "single-human" (multiuser since 2026-11-14) -- rewritten to the current paths with the audit's hat named: the dump cross-check is the operator side's, a run's GM reviews a pass through the server (the housekeeping log, the rendered rings, the story). The CLI-attributed-to-the-GM lines now say what they are: deployment-side filesystem reach, --gm-authorized writes, whoever's hand runs it (the protocol passage, quickstart step 7 -- which also dropped its "commit" -- and the booting intro now names its hat switches: the author's files, the deployment-side create with its API twin named, the GM's start). "The host" -> "the op" in the pitch. One mechanical fiction PARKED on the ROADMAP deferred list instead of fixed: the memory tiers table promises records access "none -- until the GM unlocks it in the story", but no channel exists (records is a creation-time settings bool, settings.json is read-only in the file API) -- build the channel or fix the promise, later. Verified consistent by the audit: the notepad (ONE notepad -- the run's gm.md, owner-writable through its route, seeded from the package copy), the op's non-reader boundary, every provider act, the spec attributions, the reader, the prompts.

verified: typecheck green both programs, check-repo ALL CLEAN with both new bans active, the ban regexes proven by direct test (agent/agents/multi-agent and LLM/LLMs caught; AGENTS.md and the assistant pass), and final greps confirming every remaining "GM" is a protocol term and every remaining "agent"/"LLM" is a quoting entry or a record's day-words. The developer's own edits ride along: the operator queue strike (the inventory line done, the loopback typo, "external sec review"), and the handoff prepared -- the queue renumbered, the fresh-run item's garbled line repaired, the commit count brought current (seven await the push), template and box marked committed, a stray paragraph break fixed. detention stays untracked WIP, untouched.
2026-11-19 09:56:56 +00:00

568 lines
28 KiB
JavaScript

// server/discovery.mjs -- model discovery: the per-provider registry.
//
// Two steps, both op acts from the SPA's admin block, both per
// provider (developer, 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 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 */
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';
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');
// 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 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';
if (tokens <= 24) return 'low';
if (tokens <= 96) return 'standard';
return 'deep';
}
// --- the registry file --------------------------------------------------------
/** 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,
* developer, 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 {
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 writeRegistry(reg) {
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
}
/** @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) --------------------------
/** 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');
}
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' }));
}
/** 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, slug);
const section = /** @type {RegistrySection} */ ({
phase: 'preliminary',
discovered: new Date().toISOString(),
refined: null,
models,
curator: null,
recommendation: null,
});
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 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} 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. A model that shows no thinking,
* or that no level moves, gets null. Pre-fill and hint only (developer,
* 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, 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, slug, m.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 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 {string} slug @param {RegistryModel} m @param {(s: string) => void} [say] @param {string} [effort]
* @returns {Promise<RegistryModel>} */
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), 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 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 };
}
const latency = Date.now() - t0;
const samples = [];
for (let i = 0; i < 2; i++) {
say(`the thinking samples, ${i + 1}/2`);
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, slug, 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, 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 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 (developer, 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}`;
}
/** @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: [
{ 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',
recommendation: { model: 'mock', effort: 'max' },
};
}
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 inferencer call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} inferencer ${curatorSpec.model} u:${user?.id ?? '?'}`);
// no automatic retries (developer, 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, recommend?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
} catch (e) {
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', 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)})`, recommendation: null };
}
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', recommendation: null };
// the recommendation: intel only, strictly validated -- a passing
// model at a ladder level. Anything else is no advice, never
// machine advice (developer, 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 -----------------------------------------------------------
/** 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 (developer, 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`);
}
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 (developer, 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();
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(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, 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}` : ''}`;
// 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()) {
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 (developer, 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++;
}
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');
// 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 (${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 (${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;
});
writeSection(slug, /** @type {RegistrySection} */ ({
phase: 'refined',
discovered: section.discovered,
refined: new Date().toISOString(),
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 (developer,
// 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) {
job.state = 'rejected';
job.reason = String(e.message ?? e);
}
})();
return job;
}
/** @param {Ctx} ctx @param {string} slug @returns {?JobState} */
export function jobState(ctx, slug) {
return ctx.jobs.get(`refine:${slug}`) ?? null;
}