Files

568 lines
28 KiB
JavaScript
Raw Permalink Normal View History

// server/discovery.mjs -- model discovery: the per-provider registry.
2026-11-16 21:32:02 +00:00
//
// 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.
2026-11-16 21:32:02 +00:00
//
// 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.
2026-11-16 21:32:02 +00:00
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
/** @typedef {import('./shapes.mjs').RegistrySection} RegistrySection */
2026-11-16 21:32:02 +00:00
/** @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';
2026-11-16 21:32:02 +00:00
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');
2026-11-16 21:32:02 +00:00
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.
2026-11-16 21:32:02 +00:00
/** @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} */
2026-11-16 21:32:02 +00:00
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;
2026-11-16 21:32:02 +00:00
} catch {
return null;
}
}
/** @param {ModelRegistry} reg */
function writeRegistry(reg) {
2026-11-16 21:32:02 +00:00
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;
2026-11-16 21:32:02 +00:00
}
// --- 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) {
2026-11-16 21:32:02 +00:00
if (ctx.mock) {
mockProbeShape(ctx, slug);
return mockSurface(slug).map((m) => ({ ...m }));
2026-11-16 21:32:02 +00:00
}
const listed = await providerFor(ctx, slug).modelsMeta();
2026-11-16 21:32:02 +00:00
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}`);
2026-11-16 21:32:02 +00:00
}
const models = await scrape(ctx, slug);
const section = /** @type {RegistrySection} */ ({
2026-11-16 21:32:02 +00:00
phase: 'preliminary',
discovered: new Date().toISOString(),
refined: null,
models,
curator: null,
recommendation: null,
2026-11-16 21:32:02 +00:00
});
writeSection(slug, section);
return section;
2026-11-16 21:32:02 +00:00
}
// --- step two: refine (the battery + the curator) -----------------------------
2026-11-16 23:52:58 +00:00
// 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
2026-11-16 23:52:58 +00:00
// step.
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
2026-11-16 21:32:02 +00:00
/** 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 });
2026-11-16 21:32:02 +00:00
return Number(data.usage?.completion_tokens_details?.reasoning_tokens ?? 0);
}
2026-11-16 23:52:58 +00:00
/** 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]
2026-11-17 02:21:38 +00:00
* @returns {Promise<{ efforts: Record<string, number>, effortDefault: ?string }>} */
async function probeEfforts(ctx, slug, m, say = () => {}) {
2026-11-16 23:52:58 +00:00
/** @type {Record<string, number>} */ const efforts = {};
for (const level of EFFORT_LEVELS) {
const xs = [];
for (let i = 0; i < 2; i++) {
2026-11-17 02:21:38 +00:00
say(`${level}, sample ${i + 1}/2`);
try { xs.push(await thinkingTokens(ctx, slug, m.id, { reasoning_effort: level })); } catch { xs.push(0); }
2026-11-16 23:52:58 +00:00
}
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 };
}
2026-11-16 21:32:02 +00:00
/** 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,
2026-11-16 23:52:58 +00:00
* 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]
2026-11-17 02:21:38 +00:00
* @returns {Promise<RegistryModel>} */
async function probeOne(ctx, slug, m, say = () => {}, effort = '') {
2026-11-16 21:32:02 +00:00
const base = { ...m };
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
if (ctx.mock) {
2026-11-17 02:21:38 +00:00
say('the canned battery');
2026-11-16 21:32:02 +00:00
// 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
2026-11-16 21:32:02 +00:00
return m.id === 'mock-cheap'
2026-11-16 23:52:58 +00:00
? { ...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 }
2026-11-16 23:52:58 +00:00
: { ...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' };
2026-11-16 21:32:02 +00:00
}
const t0 = Date.now();
2026-11-17 02:21:38 +00:00
say('the tool probe');
2026-11-16 21:32:02 +00:00
try {
await providerFor(ctx, slug).chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400, ...(effort ? { reasoning_effort: effort } : {}) });
2026-11-16 21:32:02 +00:00
} catch (e) {
const fail = String(e.message ?? e).split('\n')[0].slice(0, 200);
2026-11-16 23:52:58 +00:00
return { ...base, inference: false, fail, reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: Date.now() - t0 };
2026-11-16 21:32:02 +00:00
}
const latency = Date.now() - t0;
const samples = [];
for (let i = 0; i < 2; i++) {
2026-11-17 02:21:38 +00:00
say(`the thinking samples, ${i + 1}/2`);
try { samples.push(await thinkingTokens(ctx, slug, m.id, {})); } catch { samples.push(0); }
2026-11-16 21:32:02 +00:00
}
const think = Math.max(...samples);
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
if (think > 0) {
try {
2026-11-17 02:21:38 +00:00
say('the off-switch probe');
if (await thinkingTokens(ctx, slug, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
2026-11-16 21:32:02 +00:00
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
}
} catch { /* no off switch -- recorded as absent */ }
}
2026-11-16 23:52:58 +00:00
/** @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}`)));
2026-11-16 23:52:58 +00:00
} catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ }
}
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
2026-11-16 21:32:02 +00:00
}
// --- 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}`;
2026-11-16 21:32:02 +00:00
}
/** @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) {
2026-11-16 21:32:02 +00:00
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' },
2026-11-16 21:32:02 +00:00
};
}
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,
2026-11-16 23:52:58 +00:00
effortDefault: m.effortDefault ?? null,
2026-11-16 21:32:02 +00:00
}));
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);
2026-11-16 21:32:02 +00:00
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 ?? ''));
2026-11-16 21:32:02 +00:00
} catch (e) {
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})`, recommendation: null };
2026-11-16 21:32:02 +00:00
}
const entries = Array.isArray(parsed.models) ? parsed.models : null;
if (!entries) return { list: [], note: 'fallback: the curator output has no models array', recommendation: null };
2026-11-16 21:32:02 +00:00
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 };
2026-11-16 21:32:02 +00:00
}
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 };
2026-11-16 21:32:02 +00:00
}
// --- 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}'`);
2026-11-16 21:32:02 +00:00
}
// 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
2026-11-17 02:21:38 +00:00
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);
2026-11-17 02:21:38 +00:00
/** @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}`); };
2026-11-16 21:32:02 +00:00
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`);
}
2026-11-17 02:21:38 +00:00
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 = [];
2026-11-17 02:21:38 +00:00
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' : ''}`);
}
2026-11-17 02:21:38 +00:00
job.steps.done++;
}
2026-11-16 21:32:02 +00:00
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');
2026-11-17 02:21:38 +00:00
// 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 };
}
2026-11-16 21:32:02 +00:00
}
2026-11-17 02:21:38 +00:00
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)
2026-11-16 21:32:02 +00:00
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
2026-11-16 21:32:02 +00:00
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} */ ({
2026-11-16 21:32:02 +00:00
phase: 'refined',
discovered: section.discovered,
2026-11-16 21:32:02 +00:00
refined: new Date().toISOString(),
models,
curator: curated.note,
recommendation: curated.recommendation,
2026-11-16 21:32:02 +00:00
}));
// 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);
2026-11-17 02:21:38 +00:00
say('done');
2026-11-16 21:32:02 +00:00
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;
2026-11-16 21:32:02 +00:00
}