e60fd63d2b
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.
568 lines
28 KiB
JavaScript
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 (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 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,
|
|
* 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 {
|
|
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 (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, 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 (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}`;
|
|
}
|
|
|
|
/** @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 LLM call names the acting user
|
|
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, 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 (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 -----------------------------------------------------------
|
|
|
|
/** 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`);
|
|
}
|
|
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();
|
|
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 (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++;
|
|
}
|
|
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 (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) {
|
|
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;
|
|
}
|