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

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

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

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

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

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

verified: typecheck green both programs; smoke ALL PASS (+27 the provider-flow battery: apiKey-on-add 400, the dead-endpoint refusal with config rollback, the auth-standing card with its probe record, probe-then-save both ways, the remove-key round trip, the o/f guards, the failures-never-cache proof over mock-fail -- verdict with the marker, absent from the cache file, re-probed fresh while the passing three serve from cache, not selectable, no orphan run; +8 the sheet-transport lint battery); restart + reminder checks green; a browser pass driving the whole add-flow machine on a mock+debug server (the hidden key field opening on the 401, the key landing through the auth route, the remove-key round trip re-opening the ask, the dead add refusing with the banner and no card, zero console errors beyond the expected 401/500 resource lines); check-repo clean with the box's windows. detention stays untracked WIP, untouched.
This commit is contained in:
2026-11-19 08:35:23 +00:00
parent 14b9b01d86
commit e60fd63d2b
42 changed files with 3071 additions and 1086 deletions
+334 -170
View File
@@ -1,25 +1,40 @@
// server/discovery.mjs -- model discovery: the registry.
// server/discovery.mjs -- model discovery: the per-provider registry.
//
// Two steps, both op acts from the SPA's admin block:
// - discover: scrape the provider surface (GET /models) -- API
// metadata only, zero inference. Writes the preliminary registry.
// - refine: run the inference battery over the scrape (deterministic
// probes, fixed prompts, fixed rules), then hand the adjudicated
// results to the best passing model (repo craft: curator.md) for
// the final registry -- families, labels, descriptions. The
// curator's output is strictly validated; any failure falls back
// to the raw deterministic list, so a bad model day can never
// block discovery. Defaults stay deterministic either way: the
// max-reasoning rule picks them, never the curator, and full ties
// settle by the lex rule (rankSort).
// Two steps, both op acts from the SPA's admin block, both per
// provider (GM, 2026-11-18):
// - discover: scrape one provider's surface (GET /models) -- API
// metadata only, zero inference. Writes that provider's registry
// section, resetting it to preliminary; the other sections are
// untouched. Cheap by design -- re-running it is nothing to
// treasure (o/f churns its model list, and discovery churn with it
// is expected).
// - refine: run the inference battery over that provider's scrape
// (deterministic probes, fixed prompts, fixed rules), then hand
// the adjudicated results to the op's selected default model (repo
// craft: curator.md) for labels and one overall-best recommendation
// -- intel only, applied by the op's click, never auto-landed. The
// curator's output is strictly validated; any failure falls back to
// the raw deterministic list and no recommendation, so a bad model
// day can never block discovery -- the op just gets no advice.
//
// The registry (state/models.json) is the truth of selectable
// models: a fresh deployment has none and model use is disabled
// until the op discovers. The selectors read it, the model routes
// validate against it, the turn loop enforces it. Mock mode runs
// the same two steps over a canned surface -- no network, instant.
// The adjudication cache (state/refine-cache.json): a refined entry
// is a function of the full spec tuples on both sides -- the probed
// model at the effort the deployment will actually send, and the
// curator at its own spec (a weak curator at a low effort adjudicates
// worse; it is an inference request like any other). Keyed by
// {provider, model, effort, curator-model, curator-effort}; a refine
// that sees the same tuple reuses the cached entry and refreshes it
// in place when it re-probes. Discovery never touches the cache --
// the scrape is cheap, the battery is what costs.
//
// The registry (state/models.json) is per-provider sections, the
// truth of selectable models: the selectors read a section, the model
// routes validate against it, the turn loop enforces it. A provider
// not in the config has no section. Mock mode runs the same steps
// over canned surfaces -- no network, instant.
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
/** @typedef {import('./shapes.mjs').RegistrySection} RegistrySection */
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
/** @typedef {import('./shapes.mjs').JobState} JobState */
/** @typedef {import('./shapes.mjs').Actor} Actor */
@@ -30,11 +45,12 @@ import { fileURLToPath } from 'node:url';
import { parseManifest } from './housekeeping.mjs';
import { ASK_GM_TOOL } from './bundle.mjs';
import { HttpError } from './loop.mjs';
import { providerFor } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const REGISTRY_PATH = path.join(ROOT, 'state', 'models.json');
const CACHE_PATH = path.join(ROOT, 'state', 'refine-cache.json');
const CURATOR_PROMPT = path.join(ROOT, 'curator.md');
const JOB_KEY = 'discovery';
// the reasoning battery's fixed puzzle -- same every run, so the
// buckets stay comparable across models and across discoveries
@@ -42,10 +58,9 @@ const PUZZLE = 'A bat and ball cost 1.10 in total. The bat costs 1.00 more than
// reasoning buckets, by measured thinking tokens (the max of the
// samples): the thresholds sit in the gaps the live endpoint showed
// (off 0 / low ~5 / standard ~10 / deep 150+). The pick rule ranks
// on the bucket, not the raw count: within a bucket the differences
// are sampling noise (the alias twins flip run to run), so only the
// bucket is a real difference.
// (off 0 / low ~5 / standard ~10 / deep 150+). The bucket, not the
// raw count, is the real difference -- within a bucket the
// differences are sampling noise.
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
function bucket(tokens) {
if (tokens <= 0) return 'off';
@@ -56,92 +71,168 @@ function bucket(tokens) {
// --- the registry file --------------------------------------------------------
/** @returns {?ModelRegistry} */
/** The registry, as state/models.json holds it: one section per
* configured provider slug. A provider absent from the config has
* no section (removal deletes it); a provider not yet discovered
* has none either. No legacy shapes are read (the no-legacy rule,
* GM, 2026-11-18): shape changes come with one-time migrations of
* the file, not permanent tolerance in the reader.
* @returns {?ModelRegistry} */
export function registry() {
try {
return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8'));
const reg = /** @type {?ModelRegistry} */ (JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8')));
return reg && typeof reg === 'object' && reg.providers && typeof reg.providers === 'object' && !Array.isArray(reg.providers) ? reg : null;
} catch {
return null;
}
}
/** @param {ModelRegistry} reg */
function write(reg) {
function writeRegistry(reg) {
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
}
/** A model is usable when the registry knows it and the battery (or
* the preliminary scrape) has not disqualified it. */
/** @param {?ModelRegistry} reg @param {string} id @returns {boolean} */
export function usable(reg, id) {
return !!reg && reg.models.some((m) => m.id === id && m.inference !== false);
/** @param {string} slug @returns {?RegistrySection} */
export function sectionOf(slug) {
return registry()?.providers[slug] ?? null;
}
/** Write one provider's section; the others are untouched.
* @param {string} slug @param {RegistrySection} section */
function writeSection(slug, section) {
const reg = registry() ?? /** @type {ModelRegistry} */ ({ providers: {} });
reg.providers[slug] = section;
writeRegistry(reg);
}
/** Remove one provider's section whole -- provider removal's other
* half (the runs that rode it invalidate at their next send).
* @param {string} slug */
export function deleteSection(slug) {
const reg = registry();
if (!reg || !reg.providers[slug]) return;
delete reg.providers[slug];
writeRegistry(reg);
}
/** A model is usable when its provider's section knows it and the
* battery (or the preliminary scrape) has not disqualified it. */
/** @param {string} slug @param {string} id @returns {boolean} */
export function usable(slug, id) {
const m = findModel(slug, id);
return !!m && m.inference !== false;
}
/** @param {string} slug @param {string} id @returns {?RegistryModel} */
export function findModel(slug, id) {
return sectionOf(slug)?.models.find((m) => m.id === id) ?? null;
}
// --- step one: discover (the scrape -- no inference) --------------------------
/** @param {Ctx} ctx @returns {Promise<RegistryModel[]>} */
async function scrape(ctx) {
if (ctx.mock) {
return [
{ id: 'mock', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-tie', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-cheap', input: 131072, output: 32768, status: 'unrefined' },
];
/** The canned mock surface: the two synthetic providers split the
* list (the multi-provider tagging rides the smoke end to end), any
* other slug gets the full set -- so the SPA's add flow is testable
* offline, the o/f singleton included.
* @param {string} slug @returns {RegistryModel[]} */
function mockSurface(slug) {
/** @type {RegistryModel[]} */ const all = [
{ id: 'mock', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-tie', input: 524288, output: 163840, status: 'unrefined' },
{ id: 'mock-cheap', input: 131072, output: 32768, status: 'unrefined' },
{ id: 'mock-fail', input: 131072, output: 32768, status: 'unrefined' },
];
if (slug === 'mock-a') return all.slice(0, 2);
if (slug === 'mock-b') return [all[2]];
if (slug === 'mock-c') return all;
return all.slice(0, 3);
}
/** The mock's probe shapes (the add-flow machine, offline): mock-auth
* refuses the listing until a key stands on the entity, mock-lock
* refuses whatever is sent, mock-dead never answers. The real
* failures carry the same shapes -- 401/403 with the status on the
* error, everything else without.
* @param {Ctx} ctx @param {string} slug */
function mockProbeShape(ctx, slug) {
const p = ctx.providerCfg.providers.find((x) => x.slug === slug);
if (slug === 'mock-auth' && !(p && p.apiKey)) {
throw new HttpError(401, 'the mock refuses unauthenticated listings');
}
const listed = await ctx.provider.modelsMeta();
if (slug === 'mock-lock') {
throw new HttpError(401, 'the mock refuses every listing, keyed or not');
}
if (slug === 'mock-dead') {
throw new Error('the mock endpoint did not answer');
}
}
/** Scrape one provider: the listing with the API metadata the
* registry carries (token ceilings when the provider states them).
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistryModel[]>} */
async function scrape(ctx, slug) {
if (ctx.mock) {
mockProbeShape(ctx, slug);
return mockSurface(slug).map((m) => ({ ...m }));
}
const listed = await providerFor(ctx, slug).modelsMeta();
return listed.map((m) => ({ id: m.id, input: m.input, output: m.output, status: 'unrefined' }));
}
/** @param {Ctx} ctx @returns {Promise<ModelRegistry>} */
export async function discover(ctx) {
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
throw new HttpError(409, 'a refine is running -- let it finish first');
/** Discover one provider: the scrape, the section written
* preliminary. Resets a refined section -- the honest behavior, and
* the reason the SPA's discover button says so.
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistrySection>} */
export async function discover(ctx, slug) {
if (!ctx.providerCfg.providers.some((p) => p.slug === slug)) {
throw new HttpError(404, `no such provider: ${slug}`);
}
const models = await scrape(ctx);
const reg = /** @type {ModelRegistry} */ ({
const models = await scrape(ctx, slug);
const section = /** @type {RegistrySection} */ ({
phase: 'preliminary',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: new Date().toISOString(),
refined: null,
defaults: { player: null, housekeeper: null },
models,
curator: null,
recommendation: null,
});
write(reg);
return reg;
writeSection(slug, section);
return section;
}
// --- step two: refine (the battery + the curator) -----------------------------
// the reasoning-effort ladder: the spellings the OpenAI-compatible
// world agrees on. `none` doubles as the standardized thinking-off
// switch. Mirrored in web/knobs.mjs for the select -- keep them in
// switch. Mirrored in web/knobs.mjs for the selects -- keep them in
// step.
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
/** One model's measured thinking under given request params.
* @param {Ctx} ctx @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
async function thinkingTokens(ctx, id, params) {
const data = await ctx.provider.chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...params });
* @param {Ctx} ctx @param {string} slug @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
async function thinkingTokens(ctx, slug, id, params) {
const data = await providerFor(ctx, slug).chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...params });
return Number(data.usage?.completion_tokens_details?.reasoning_tokens ?? 0);
}
/** The reasoning-effort probe: each level's measured mean thinking
* (two samples, the battery's granularity). The default is the
* level with the highest observed mean -- `none` is never a
* candidate, it is the off switch, not a thinking level (GM,
* 2026-11-16: maximum observable thinking by default, overridable
* by the user). A model that shows no thinking, or that no level
* moves, gets null -- nothing rides.
* @param {Ctx} ctx @param {string} id @param {(s: string) => void} [say]
* candidate, it is the off switch. A model that shows no thinking,
* or that no level moves, gets null. Pre-fill and hint only (GM,
* 2026-11-18): with effort a property of the model pick, the
* measured default never rides a turn implicitly -- it pre-selects
* the selection dropdown and informs the curator's recommendation.
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say]
* @returns {Promise<{ efforts: Record<string, number>, effortDefault: ?string }>} */
async function probeEfforts(ctx, id, say = () => {}) {
async function probeEfforts(ctx, slug, m, say = () => {}) {
/** @type {Record<string, number>} */ const efforts = {};
for (const level of EFFORT_LEVELS) {
const xs = [];
for (let i = 0; i < 2; i++) {
say(`${level}, sample ${i + 1}/2`);
try { xs.push(await thinkingTokens(ctx, id, { reasoning_effort: level })); } catch { xs.push(0); }
try { xs.push(await thinkingTokens(ctx, slug, m.id, { reasoning_effort: level })); } catch { xs.push(0); }
}
efforts[level] = Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
}
@@ -151,32 +242,34 @@ async function probeEfforts(ctx, id, say = () => {}) {
}
/** The deterministic battery over one model: the tool ping (the
* exact request shape a player turn takes), the reasoning samples,
* exact request shape a player turn takes -- the working effort
* rides, because every real turn sends one), the reasoning samples,
* the off-switch probe, the effort ladder. Every failure is a
* verdict, never an abort.
* @param {Ctx} ctx @param {RegistryModel} m @param {(s: string) => void} [say]
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say] @param {string} [effort]
* @returns {Promise<RegistryModel>} */
async function probeOne(ctx, m, say = () => {}) {
async function probeOne(ctx, slug, m, say = () => {}, effort = '') {
const base = { ...m };
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
if (ctx.mock) {
say('the canned battery');
// the canned battery: all three stand-ins are inference models;
// mock and mock-tie are a deliberate tie pair (same deep bucket,
// same windows -- only the lex rule can part them), the cheap
// tier standard. The canned effort ladders exercise both shapes:
// the full ladder with max on top, and a capped ladder whose
// default is high
// same windows), the cheap tier standard. The canned effort
// ladders exercise both shapes: the full ladder with max on top,
// and a capped ladder whose default is high
return m.id === 'mock-cheap'
? { ...base, inference: true, think: 120, reasoning: 'standard', offSwitch: null, latency: 5,
efforts: { none: 0, minimal: 20, low: 60, medium: 90, high: 120 }, effortDefault: 'high' }
: m.id === 'mock-fail'
? { ...base, inference: false, fail: 'the canned failure -- a classifier that cannot tool', reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: 3 }
: { ...base, inference: true, think: 300, reasoning: 'deep', offSwitch: null, latency: 7,
efforts: { none: 0, minimal: 40, low: 100, medium: 200, high: 300, xhigh: 400, max: 500 }, effortDefault: 'max' };
}
const t0 = Date.now();
say('the tool probe');
try {
await ctx.provider.chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400 });
await providerFor(ctx, slug).chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400, ...(effort ? { reasoning_effort: effort } : {}) });
} catch (e) {
const fail = String(e.message ?? e).split('\n')[0].slice(0, 200);
return { ...base, inference: false, fail, reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: Date.now() - t0 };
@@ -185,14 +278,14 @@ async function probeOne(ctx, m, say = () => {}) {
const samples = [];
for (let i = 0; i < 2; i++) {
say(`the thinking samples, ${i + 1}/2`);
try { samples.push(await thinkingTokens(ctx, m.id, {})); } catch { samples.push(0); }
try { samples.push(await thinkingTokens(ctx, slug, m.id, {})); } catch { samples.push(0); }
}
const think = Math.max(...samples);
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
if (think > 0) {
try {
say('the off-switch probe');
if (await thinkingTokens(ctx, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
if (await thinkingTokens(ctx, slug, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
}
} catch { /* no off switch -- recorded as absent */ }
@@ -201,39 +294,65 @@ async function probeOne(ctx, m, say = () => {}) {
/** @type {?string} */ let effortDefault = null;
if (think > 0) {
try {
({ efforts, effortDefault } = await probeEfforts(ctx, m.id, (s) => say(`the effort ladder: ${s}`)));
({ efforts, effortDefault } = await probeEfforts(ctx, slug, m, (s) => say(`the effort ladder: ${s}`)));
} catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ }
}
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
}
// the pick rule, deterministic: the deepest reasoning bucket, then
// the largest input window, then the largest output ceiling, then
// the GM's tie-break -- sort lex, pick the bottom. The bucket, not
// the raw token count, is the rank (see bucket). It names the
// curator model and the deployment defaults -- correctness never
// consults taste.
/** @param {RegistryModel[]} models @returns {RegistryModel[]} */
function rankSort(models) {
const depth = { off: 0, low: 1, standard: 2, deep: 3 };
return [...models].sort((a, b) => {
const db = depth[b.reasoning ?? 'off'];
const da = depth[a.reasoning ?? 'off'];
if (db !== da) return db - da;
if ((b.input ?? 0) !== (a.input ?? 0)) return (b.input ?? 0) - (a.input ?? 0);
if ((b.output ?? 0) !== (a.output ?? 0)) return (b.output ?? 0) - (a.output ?? 0);
return a.id < b.id ? 1 : a.id > b.id ? -1 : 0; // lex bottom wins
});
// --- the adjudication cache ---------------------------------------------------
/** The cache key: the full spec tuples on both sides -- the probed
* model at the effort the deployment will actually send, and the
* curator at its own spec. Reasoning effort substantially changes
* inference quality (GM, 2026-11-18), so an entry adjudicated under
* one tuple never speaks for another.
* @param {string} slug @param {string} id @param {string} effort @param {string} cm @param {string} ce @returns {string} */
function cacheKey(slug, id, effort, cm, ce) {
return `${slug}::${id}::${effort}::${cm}::${ce}`;
}
/** The curator pass: the best model reads the adjudicated results
* and writes the presentation layer. Strictly validated -- only
* probed inference ids, no inventions; any violation discards the
* whole output and the machine list stands.
* @param {Ctx} ctx @param {RegistryModel[]} probed @param {RegistryModel} best @param {?Actor} user
* @param {?import('./provider.mjs').ProgressFn} [onProgress] @param {?(() => void)} [onRetry]
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }>} */
async function curate(ctx, probed, best, user, onProgress = null, onRetry = null) {
/** @returns {Record<string, RegistryModel>} */
function readCache() {
try {
const c = JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));
if (c && typeof c === 'object' && c.entries && typeof c.entries === 'object') {
return /** @type {Record<string, RegistryModel>} */ (c.entries);
}
} catch { /* absent -- the cache starts empty */ }
return {};
}
/** @param {Record<string, RegistryModel>} entries */
function writeCache(entries) {
fs.mkdirSync(path.dirname(CACHE_PATH), { recursive: true });
fs.writeFileSync(CACHE_PATH, JSON.stringify({ entries }, null, 2) + '\n');
}
/** Provider removal purges its entries -- the models are gone with
* the route.
* @param {string} slug */
export function purgeCache(slug) {
const entries = readCache();
const prefix = `${slug}::`;
let dirty = false;
for (const k of Object.keys(entries)) {
if (k.startsWith(prefix)) { delete entries[k]; dirty = true; }
}
if (dirty) writeCache(entries);
}
// --- the curator pass ---------------------------------------------------------
/** The curator pass: the op's selected default model reads the
* adjudicated results and writes the presentation layer -- labels,
* and one overall-best recommendation (intel only). Strictly
* validated -- only probed inference ids, no inventions; any
* violation discards the whole output and the machine list stands.
* @param {Ctx} ctx @param {string} slug @param {RegistryModel[]} probed @param {{ model: string, effort: string }} curatorSpec @param {?Actor} user
* @param {?import('./provider.mjs').ProgressFn} [onProgress]
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }>} */
async function curate(ctx, slug, probed, curatorSpec, user, onProgress = null) {
if (ctx.mock) {
return {
list: [
@@ -242,6 +361,7 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
{ id: 'mock-cheap', family: 'mock', label: 'Mock (cheap)', description: 'The scripted stand-in, cheap tier.', player: true, housekeeper: true },
],
note: 'curated',
recommendation: { model: 'mock', effort: 'max' },
};
}
const facts = probed.map((m) => ({
@@ -254,35 +374,27 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
{ role: 'user', content: JSON.stringify(facts, null, 2) },
]);
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${best.id} u:${user?.id ?? '?'}`);
// one retry: the call is long enough to meet a network hiccup, and
// a fresh attempt is cheaper than losing the curation
let data = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
data = await ctx.provider.chat(best.id, messages, undefined, {}, onProgress);
break;
} catch (e) {
if (attempt === 1) throw e;
console.log(`${new Date().toISOString().slice(11, 19)} curator call failed (${String(e.message ?? e).split('\n')[0]}) -- retrying once`);
onRetry?.();
}
}
console.log(`${new Date().toISOString().slice(11, 19)} llm ${curatorSpec.model} u:${user?.id ?? '?'}`);
// no automatic retries (GM, 2026-11-19): every inference call is
// user-initiated and every act has its manual retry -- the refine
// button again. A dead call lands the fallback, which is the
// designed outcome, not a degraded one
const data = await providerFor(ctx, slug).chat(curatorSpec.model, messages, undefined, { reasoning_effort: curatorSpec.effort }, onProgress);
if (!data) throw new Error('the curator call failed twice');
const known = new Set(probed.filter((m) => m.inference).map((m) => m.id));
let parsed;
try {
parsed = /** @type {{ models?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
parsed = /** @type {{ models?: unknown, recommend?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
} catch (e) {
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})` };
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})`, recommendation: null };
}
const entries = Array.isArray(parsed.models) ? parsed.models : null;
if (!entries) return { list: [], note: 'fallback: the curator output has no models array' };
if (!entries) return { list: [], note: 'fallback: the curator output has no models array', recommendation: null };
const seen = new Set();
/** @type {{ id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[]} */ const list = [];
for (const e of entries) {
if (typeof e !== 'object' || e === null || typeof e.id !== 'string' || !known.has(e.id) || seen.has(e.id)) {
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})` };
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})`, recommendation: null };
}
seen.add(e.id);
list.push({
@@ -294,99 +406,151 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
housekeeper: e.housekeeper !== false,
});
}
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing' };
return { list, note: 'curated' };
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing', recommendation: null };
// the recommendation: intel only, strictly validated -- a passing
// model at a ladder level. Anything else is no advice, never
// machine advice (GM, 2026-11-18: on a bad model day the op gets
// no recommendation, not a deterministic stand-in)
let recommendation = null;
const r = /** @type {{ model?: unknown, effort?: unknown }|null|undefined} */ (parsed.recommend);
if (r && typeof r === 'object' && typeof r.model === 'string' && known.has(r.model)
&& typeof r.effort === 'string' && EFFORT_LEVELS.includes(r.effort)) {
recommendation = { model: r.model, effort: r.effort };
}
return { list, note: 'curated', recommendation };
}
/** The refine job: scrape fresh, battery, adjudicate, curate, write.
* Runs async under the jobs map; the registry only moves forward on
* a completed pass (a rejected pass changes nothing).
* @param {Ctx} ctx @param {?Actor} user @returns {JobState} */
export function refine(ctx, user) {
const reg = registry();
if (!reg) throw new HttpError(409, 'nothing to refine -- run discovery first');
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
throw new HttpError(409, 'a refine is already running');
// --- the refine job -----------------------------------------------------------
/** The refine job: scrape fresh, battery, adjudicate, curate, write
* the one provider's section. Runs async under the jobs map; the
* section only moves forward on a completed pass (a rejected pass
* changes nothing).
* @param {Ctx} ctx @param {string} slug @param {?Actor} user @returns {JobState} */
export function refine(ctx, slug, user) {
const provider = ctx.providerCfg.providers.find((p) => p.slug === slug);
if (!provider) throw new HttpError(404, `no such provider: ${slug}`);
const section = sectionOf(slug);
if (!section) throw new HttpError(409, `nothing to refine on '${slug}' -- run its discovery first`);
// the curator IS the selected default (GM, 2026-11-18) -- refine
// requires the selection
const curatorSpec = provider.default;
if (!curatorSpec) {
throw new HttpError(409, `select '${slug}'s default model first -- the default is also the refine curator`);
}
// the meter: one step per model's battery plus the curator's two
// (thinking, writing) -- the count is known the moment the scrape
// lands. No step has a duration to guess at (GM, 2026-11-17): the
// bar moves only on real completions, the label names the call
// running now, and every completion lands a receipt line -- the
// lines survive the job, so a rejected pass keeps its post-mortem
const jobKey = `refine:${slug}`;
if (ctx.jobs.get(jobKey)?.state === 'running') {
throw new HttpError(409, `a refine is already running on '${slug}'`);
}
// the meter: one step per model's battery (a cache hit closes its
// step instantly -- it is a completion, not a wait) plus the
// curator's two (thinking, writing). No step has a duration to
// guess at (GM, 2026-11-17): the bar moves only on real
// completions, the label names the call running now, and every
// completion lands a receipt line -- the lines survive the job, so
// a rejected pass keeps its post-mortem
const t0 = Date.now();
// the local view narrows steps/lines to present -- the job is born
// with them, and the reporter writes through this reference
const job = /** @type {JobState & { steps: { total: number, done: number, label: string, chars?: number }, lines: string[] }} */ ({
state: 'running', phase: 'refine', started: new Date().toISOString(),
steps: { total: 0, done: 0, label: 'scraping the provider surface' }, lines: [],
});
ctx.jobs.set(JOB_KEY, job);
ctx.jobs.set(jobKey, job);
/** @param {string} s */ const say = (s) => { job.steps.label = s; };
/** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); };
void (async () => {
try {
const scraped = await scrape(ctx); // fresh metadata -- ids can drift between discoveries
const scraped = await scrape(ctx, slug); // fresh metadata -- ids can drift between discoveries
if (!scraped.some((m) => m.id === curatorSpec.model)) {
throw new Error(`the selected default '${curatorSpec.model}' is not in '${slug}'s current registry -- re-discover and re-select`);
}
job.steps.total = scraped.length + 2;
/** @param {RegistryModel} m @returns {string} */
const verdict = (m) => m.inference === false
? `failed the tool probe -- ${m.fail}`
: `reasoning ${m.reasoning} \u00b7 ${m.think} think tokens \u00b7 ${m.offSwitch ? 'off switch' : 'no off switch'} \u00b7 ${m.latency}ms${m.effortDefault ? ` \u00b7 effort default ${m.effortDefault}` : ''}`;
const probed = [];
// the adjudication cache: same tuple, same verdict -- churn is
// the point (o/f rotates models; the survivors keep their
// measured selves between refines)
const cache = readCache();
/** @type {RegistryModel[]} */ const probed = [];
/** @type {RegistryModel[]} */ const fresh = [];
for (const [i, m] of scraped.entries()) {
probed.push(await probeOne(ctx, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`)));
const key = cacheKey(slug, m.id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort);
const hit = cache[key];
if (hit) {
say(`battery ${i + 1}/${scraped.length}: ${m.id} -- cached`);
probed.push(hit);
line(`${m.id}: from cache`);
} else {
probed.push(await probeOne(ctx, slug, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`), curatorSpec.effort));
fresh.push(probed[probed.length - 1]);
// failures never cache (GM, 2026-11-19): a failure is the
// absence of a measurement, not a measurement -- the next
// refine always re-probes it, so the receipt says so
line(`${m.id}: ${verdict(probed[probed.length - 1])}${probed[probed.length - 1].inference === false ? ' -- never cached, retried at every refine' : ''}`);
}
job.steps.done++;
line(`${m.id}: ${verdict(probed[i])}`);
}
const passing = probed.filter((m) => m.inference);
if (!passing.length) throw new Error('no model passed the inference battery -- the provider surface has nothing playable');
const best = rankSort(passing)[0];
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }} */
let curated = { list: [], note: 'fallback: not attempted' };
// the curator's two steps, marked from real events: thinking
// completes at the first prose delta (the streaming boundary),
// writing at the call's resolve; a dead call closes both -- the
// attempt is over, and the fallback carries the job
let proseStarted = false;
say(`curator (${best.id}): thinking`);
try {
curated = await curate(ctx, probed, best, user, (p) => {
job.steps.chars = p.chars;
if (p.phase === 'prose' && !proseStarted) {
proseStarted = true;
job.steps.done++;
say('curator: writing');
}
}, () => say(`curator (${best.id}): retrying -- thinking`));
} catch (e) {
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})` };
say(`curator (${curatorSpec.model}): thinking`);
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }} */
let curated = { list: [], note: 'fallback: not attempted', recommendation: null };
const curatorModel = probed.find((m) => m.id === curatorSpec.model);
if (curatorModel?.inference === false) {
curated = { list: [], note: 'fallback: the curator model failed the battery -- re-select the default', recommendation: null };
line(`curator: ${curated.note}`);
} else {
try {
curated = await curate(ctx, slug, probed, curatorSpec, user, (p) => {
job.steps.chars = p.chars;
if (p.phase === 'prose' && !proseStarted) {
proseStarted = true;
job.steps.done++;
say('curator: writing');
}
});
} catch (e) {
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})`, recommendation: null };
}
}
job.steps.done = job.steps.total; // the attempt is over -- whatever remains closes with it
delete job.steps.chars;
say('writing the registry');
line(curated.note === 'curated' ? `curator (${best.id}): curated \u00b7 ${curated.list.length} labeled` : `curator: ${curated.note}`);
line(curated.note === 'curated' ? `curator (${curatorSpec.model}): curated \u00b7 ${curated.list.length} labeled${curated.recommendation ? ` \u00b7 recommends ${curated.recommendation.model} at ${curated.recommendation.effort}` : ''}` : `curator: ${curated.note}`);
// labels apply to the freshly probed models only -- a cache hit
// keeps the entry it was adjudicated with (the same curator
// tuple, the cached verdict IS the verdict)
const byId = new Map(curated.list.map((c) => [c.id, c]));
const models = probed.map((m) => {
if (!fresh.includes(m)) return m; // a cache hit -- kept whole
const c = m.inference ? byId.get(m.id) : undefined;
return c ? { ...m, family: c.family, label: c.label, description: c.description, roles: { player: c.player, housekeeper: c.housekeeper } } : m;
});
// the defaults never consult the curator: the max-reasoning
// rule over the models eligible for the role
/** @param {(m: RegistryModel) => boolean} ok @returns {?string} */
const pick = (ok) => {
const eligible = models.filter((m) => m.inference && (m.roles?.player ?? true) && ok(m));
return eligible.length ? rankSort(eligible)[0].id : null;
};
const defaults = { player: pick(() => true), housekeeper: pick((m) => m.roles?.housekeeper ?? true) };
write(/** @type {ModelRegistry} */ ({
writeSection(slug, /** @type {RegistrySection} */ ({
phase: 'refined',
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
discovered: reg.discovered,
discovered: section.discovered,
refined: new Date().toISOString(),
defaults,
models,
curator: curated.note,
recommendation: curated.recommendation,
}));
// the cache write-back: every final PASSING entry lands under
// its key -- the labeled result, not the bare probe (the cached
// entry IS the verdict, curation included), a re-probe refreshes
// in place, the survivors persist. Failures never cache (GM,
// 2026-11-19): only a measurement is worth keeping -- a failure
// is retried at every refine until it stops being one
for (const [i, m] of models.entries()) {
if (m.inference === false) continue;
cache[cacheKey(slug, scraped[i].id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort)] = m;
}
writeCache(cache);
say('done');
job.state = 'applied';
} catch (e) {
@@ -397,7 +561,7 @@ export function refine(ctx, user) {
return job;
}
/** @param {Ctx} ctx @returns {?JobState} */
export function jobState(ctx) {
return ctx.jobs.get(JOB_KEY) ?? null;
/** @param {Ctx} ctx @param {string} slug @returns {?JobState} */
export function jobState(ctx, slug) {
return ctx.jobs.get(`refine:${slug}`) ?? null;
}
+16 -20
View File
@@ -33,8 +33,8 @@ import {
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
} from './session.mjs';
import { effectiveContents } from './variants.mjs';
import { HttpError, resolveParams, resolveEffort } from './loop.mjs';
import { registry, usable } from './discovery.mjs';
import { HttpError, specFromMeta, gateSpec, resolveSpec } from './loop.mjs';
import { providerFor } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -232,26 +232,22 @@ async function runPass(ctx, runId, n, user) {
*/
async function callHousekeeper(ctx, runId, messages, user) {
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
const reg = registry();
const model = meta.models?.housekeeper
?? ctx.cfg.models?.housekeeper
?? ctx.cfg.models?.player
?? reg?.defaults.housekeeper
?? reg?.defaults.player
?? null;
if (!model) throw new Error('no housekeeper model resolved (a per-run override, server.json models, or the registry\'s discovered default)');
if (!usable(reg, model)) {
throw new Error(`model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
// the run's own housekeeper pick, else the player spec's provider's
// default (GM, 2026-11-18: the housekeeper inherits -- per-provider
// defaults mean no separate deployment default exists to fall to)
let spec = specFromMeta(meta.models?.housekeeper, 'housekeeper');
if (!spec) {
const player = resolveSpec(ctx, runId, 'player');
const def = ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null;
if (def) spec = { provider: player.provider, model: def.model, effort: def.effort };
}
const params = { ...resolveParams(ctx, runId, 'housekeeper') };
// the effort knob's own layers (its unset state sends the
// registry's measured default for this model)
const effort = resolveEffort(ctx, runId, 'housekeeper', model);
if (effort !== null) params.reasoning_effort = effort;
if (!spec) throw new Error('no housekeeper model resolved (the run\'s housekeeper pick, or its player provider\'s default)');
gateSpec(ctx, spec, 'housekeeper');
const params = { reasoning_effort: spec.effort };
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, messages, undefined, params);
return { content: data.choices[0].message.content ?? '', model };
console.log(`${new Date().toISOString().slice(11, 19)} llm ${spec.model} u:${user?.id ?? '?'}`);
const data = await providerFor(ctx, spec.provider).chat(spec.model, messages, undefined, params);
return { content: data.choices[0].message.content ?? '', model: spec.model };
}
export { callHousekeeper };
+66 -66
View File
@@ -27,7 +27,8 @@
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
import { renderView, cleanBlockList, AGENDA_CAP, rewindTo } from './session.mjs';
import { parseVariants, pickVariant } from './variants.mjs';
import { registry, usable } from './discovery.mjs';
import { providerFor } from './provider.mjs';
import { findModel } from './discovery.mjs';
export class HttpError extends Error {
/**
@@ -149,43 +150,43 @@ async function runLoop(ctx, runId, user) {
let heals = 0;
for (;;) {
const view = renderView(s);
// the request's resolved params: the mind layer rides over the
// run and deployment layers, the effort knob resolves its own
// layers (its unset state sends the registry's measured default).
// The current call's <model> block shows her the knobs that are
// hers to answer with <mind> -- reasoning_effort is filtered out
// (hidden from the model, GM 2026-11-16: not her call); nothing
// set means no block (the absent grammar); the via record lands
// the same truth unfiltered, the raw surfaces carry it
/** @type {string} */ let model;
if (ctx.mock) model = 'mock';
else model = resolveModel(ctx, runId);
const params = { ...resolveParams(ctx, runId, 'player'), ...(s.mind ?? {}) };
const effort = resolveEffort(ctx, runId, 'player', model);
if (effort !== null) params.reasoning_effort = effort;
// the request's resolved spec: the full inference identity
// {provider, model, effort} (GM, 2026-11-18) -- there is no unset
// effort, it is a property of the pick. The mind layer is the
// only params source now: per-turn, hers, spent on completion
// (the per-run knob layer is retired). The current call's
// <model> block shows her the knobs that are hers to answer with
// <mind> -- reasoning_effort is filtered out (hidden from the
// model: not her call, it rides the spec); nothing set means no
// block (the absent grammar); the via record lands the same
// truth unfiltered, the raw surfaces carry it
const spec = resolveSpec(ctx, runId, 'player');
const provider = providerFor(ctx, spec.provider);
const params = { ...(s.mind ?? {}) };
params.reasoning_effort = spec.effort;
const shown = { ...params };
delete shown.reasoning_effort;
if (Object.keys(shown).length) {
view.push({ role: 'system', content: `<model>${JSON.stringify(shown)}</model>` });
}
let msg;
/** @type {{ model: string, params: import('./shapes.mjs').RoleParams }} */ let via;
/** @type {{ model: string, provider?: string, params: import('./shapes.mjs').RoleParams }} */ let via;
if (ctx.mock) {
// the synthetic marker: no provider call happens, but the knobs
// resolve for real (the mind layer included), so the smoke can
// assert the recording
// the synthetic marker: no provider call happens, but the spec
// and the knobs resolve for real, so the smoke can assert the
// recording
msg = mockModel(s, view);
via = { model: 'mock', params };
via = { model: spec.model, provider: spec.provider, params };
} else {
via = { model, params };
via = { model: spec.model, provider: spec.provider, params };
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
console.log(`${new Date().toISOString().slice(11, 19)} llm ${spec.model} u:${user?.id ?? '?'}`);
// the turn meter's live record: one per provider call (a heal
// or tool round restarts it), fed by the streaming deltas
s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() };
let data;
try {
data = await ctx.provider.chat(model, view, tools, params, (p) => {
data = await provider.chat(spec.model, view, tools, params, (p) => {
if (!s.progress) return;
s.progress.phase = p.phase;
if (p.phase === 'thinking') s.progress.thinking = p.chars;
@@ -193,7 +194,7 @@ async function runLoop(ctx, runId, user) {
});
} catch (e) {
s.progress = null;
s.append({ t: 'req', model, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
s.append({ t: 'req', model: spec.model, provider: spec.provider, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
throw e;
}
msg = data.choices[0].message;
@@ -306,55 +307,54 @@ async function runLoop(ctx, runId, user) {
}
}
/** @param {Ctx} ctx @param {string} runId @returns {string} */
function resolveModel(ctx, runId) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const reg = registry();
// resolution: the run's pick, the op's server.json pick, the
// registry's discovered default -- then the registry gate: model
// use is disabled until the op discovers, and a model the battery
// disqualified never plays
const model = meta.models?.player ?? ctx.cfg.models?.player ?? reg?.defaults.player ?? null;
if (!model) {
throw new HttpError(409, reg
? 'no player model resolved -- set one for this run (POST /model), or a deployment default (server.json, or the registry\'s discovered pick)'
: 'no models discovered yet -- the op runs discovery from the admin block first');
/** A model spec as run.json carries it: the {provider, model,
* effort} object (the no-legacy rule, GM, 2026-11-18 -- the
* bare-string era migrated away in the same pass). Malformed
* records refuse loud.
* @param {unknown} raw @param {'player'|'housekeeper'} role @returns {?import('./shapes.mjs').ModelSpec} */
function specFromMeta(raw, role) {
if (raw == null) return null;
if (typeof raw === 'object' && !Array.isArray(raw)) {
const o = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw);
if (typeof o.provider === 'string' && typeof o.model === 'string' && typeof o.effort === 'string') {
return { provider: o.provider, model: o.model, effort: o.effort };
}
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
}
if (!usable(reg, model)) {
throw new HttpError(409, `model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ''} -- pick a discovered model`);
}
return model;
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
}
/** The effective sampling knobs for a role: the deployment default
* layer (server.json params) under the run's own overrides. */
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').RoleParams} */
function resolveParams(ctx, runId, role) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
return {
...(ctx.cfg.params?.[role] ?? {}),
...(meta.params?.[role] ?? {}),
};
/** The invalidation gate (GM, 2026-11-18): the settings the run
* came with must still be carried. A provider gone from the
* config, a model gone from its provider's registry, a model the
* battery disqualified -- all one state: the run blocks until the
* GM sets it up again. The error IS the table's note.
* @param {Ctx} ctx @param {import('./shapes.mjs').ModelSpec} spec @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
function gateSpec(ctx, spec, role) {
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
throw new HttpError(409, `the run's ${role} model rides provider '${spec.provider}', which is no longer configured -- set it up again in the model box`);
}
const m = findModel(spec.provider, spec.model);
if (!m) {
throw new HttpError(409, `the run's ${role} model '${spec.model}' is not in provider '${spec.provider}'s registry (the discovered ids drifted) -- set it up again in the model box`);
}
if (m.inference === false) {
throw new HttpError(409, `the run's ${role} model '${spec.model}' failed the inference battery -- set it up again in the model box`);
}
return spec;
}
// The reasoning-effort knob's own resolution (GM, 2026-11-16): unlike
// the numeric knobs its unset state SENDS -- the registry measured a
// default, so one honestly exists. Layers: the run's override, then
// the deployment layer (server.json params), then the registry's
// per-model pick -- the level with the highest observed mean
// thinking. An explicit null clears the layers: nothing rides, the
// model id's baked default applies. Hidden from the model entirely:
// never in the mind verb, never in the <model> display block -- it
// rides the via record, the raw surfaces carry it.
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @param {string} model @returns {?string} */
function resolveEffort(ctx, runId, role, model) {
/** Resolve one role's spec: the run's pick, gated for validity. No
* pick is a loud refusal -- the create flow lands one, so only
* picked-clean runs hit this.
* @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
function resolveSpec(ctx, runId, role) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const set = meta.params?.[role]?.reasoning_effort ?? ctx.cfg.params?.[role]?.reasoning_effort ?? undefined;
if (set !== undefined) return set === null ? null : String(set);
const m = registry()?.models.find((x) => x.id === model);
return m?.effortDefault ?? null;
const spec = specFromMeta(meta.models?.[role], role);
if (!spec) throw new HttpError(409, `no ${role} model set for this run -- pick one in the model box`);
return gateSpec(ctx, spec, role);
}
export { resolveModel, resolveParams, resolveEffort };
export { specFromMeta, gateSpec, resolveSpec };
// --- the mind verb ------------------------------------------------------------
//
+391 -116
View File
@@ -26,12 +26,13 @@ import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { makeProvider } from './provider.mjs';
import * as providers from './providers.mjs';
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
import * as bundle from './bundle.mjs';
import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs';
import { effectiveContents } from './variants.mjs';
import { gmTurn, answerAsk, openingCall, HttpError, resolveParams } from './loop.mjs';
import { gmTurn, answerAsk, openingCall, HttpError, specFromMeta, gateSpec } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
import * as discovery from './discovery.mjs';
@@ -40,20 +41,66 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock');
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
const CONFIG_PATH = path.join(ROOT, 'server.json');
if (!fs.existsSync(CONFIG_PATH)) {
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
process.exit(1);
// server.json is the static, non-secret remainder: bind and contwin.
// Optional (GM, 2026-11-18) -- the provider entities live in
// state/config.json (server-written, SPA-managed). Nothing here gates
// the boot: a fresh deployment with no config at all comes up
// serving, mints the superuser invite, and shows the global
// no-providers banner -- every consumer of providers treats "none"
// as a loud 409, never a crash.
/** @type {import('./shapes.mjs').ServerCfg} */
let cfg = {};
const SERVER_JSON = path.join(ROOT, 'server.json');
if (fs.existsSync(SERVER_JSON)) {
try {
cfg = JSON.parse(fs.readFileSync(SERVER_JSON, 'utf8'));
} catch {
console.error('server.json does not parse -- fix it or remove it (the provider entities live in state/config.json)');
process.exit(1);
}
}
const cfg = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
const provider = makeProvider(cfg.endpoint ?? {});
let providerCfg = providers.readConfig();
// the self-heal rule (GM, 2026-11-18), stated broadly: an error that
// can be mechanically fixed to a reasonable degree without requiring
// human input gets fixed. The empty provider list is one: the
// anonymous fallback is added and discovered, as a background job --
// boot never blocks on the network, and a failure leaves the empty
// state plus the admin block's banner, whose fix path is the same
// add act. The mock world seeds its two synthetic providers instead
// (offline, the same code path).
/** @type {string[]} */
const autoAdded = [];
if (!providerCfg.providers.length) {
if (MOCK) {
providerCfg.providers.push(
{ slug: 'mock-a', baseUrl: 'mock://a', default: null },
{ slug: 'mock-b', baseUrl: 'mock://b', default: null },
);
autoAdded.push('mock-a', 'mock-b');
} else {
const p = providers.addBuiltin(providerCfg);
if (p) autoAdded.push(p.slug);
}
providers.writeConfig(providerCfg);
}
const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)]));
// locks/enqueue are attached just below; the cast is the two-step that
// lets the literal precede them
const ctxBase = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
const ctxBase = { mock: MOCK, cfg, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
/** @type {Ctx} */
const ctx = /** @type {Ctx} */ (ctxBase);
// the auto-added providers discover in the background -- no LLM
// calls, one GET each, zero cost; a dead network shows as the probe
// record on the card (o/f's auth failure reads as upstream breakage,
// never a prompt) plus the banner, whose fix path is the same add act
for (const slug of autoAdded) {
console.log(`fresh deployment -- auto-added '${slug}', discovering`);
void runProbe(slug)
.then((s) => console.log(`auto-discovery of '${slug}': ${s.models.length} models scraped`))
.catch((e) => console.error(`auto-discovery of '${slug}' failed: ${String(e.message ?? e).split('\n')[0]} -- the admin block's add act retries it`));
}
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, start, the
@@ -314,48 +361,293 @@ route('GET', '/api', async () => ({
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
}));
// --- models: the registry, and the op's discovery acts -------------------------
// --- models and providers: the registry, the op's provider acts ----------------
//
// The registry (state/models.json) is the truth of selectable
// models. Fresh deployments have none: model use is disabled until
// the op discovers. Discover scrapes the provider surface -- API
// metadata only, zero inference; refine runs the deterministic
// battery and the curator pass (it sends real traffic and may cost
// real money). Both are the superuser's.
// The registry (state/models.json, per-provider sections) is the
// truth of selectable models. The provider entities (state/
// config.json) are the op's: add and remove from the SPA, discover
// and refine per provider. Both surfaces below are the superuser's
// except GET /api/models (the model box reads it, any signed-in
// user).
/** The effective deployment default per role: the op's server.json
* pick wins, else the registry's discovered default. */
/** @returns {{ player?: ?string, housekeeper?: ?string }} */
function effectiveDefaults() {
/** The per-provider payload the model box and the admin block read. */
/** @typedef {import('./shapes.mjs').JobState} JobState */
/** @returns {{ providers: { slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('./shapes.mjs').RegistryModel[], job: ?JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }[] }} */
function modelsPayload() {
const reg = discovery.registry();
return {
player: ctx.cfg.models?.player ?? reg?.defaults.player ?? undefined,
housekeeper: ctx.cfg.models?.housekeeper ?? reg?.defaults.housekeeper ?? undefined,
providers: ctx.providerCfg.providers.map((p) => {
const section = reg?.providers[p.slug] ?? null;
return {
slug: p.slug,
phase: section?.phase ?? 'none',
discovered: section?.discovered ?? null,
refined: section?.refined ?? null,
curator: section?.curator ?? null,
recommendation: section?.recommendation ?? null,
default: p.default ?? null,
models: section?.models ?? [],
job: discovery.jobState(ctx, p.slug),
probe: p.probe ?? null,
hasKey: !!p.apiKey,
};
}),
};
}
route('GET', '/api/models', async () => {
const reg = discovery.registry();
route('GET', '/api/models', async () => modelsPayload());
/** The providers' default specs: the create flow's pre-select, and
* what a pick-less housekeeper inherits. */
/** @returns {{ slug: string, default: ?{ model: string, effort: string } }[]} */
function providerDefaults() {
return ctx.providerCfg.providers.map((p) => ({ slug: p.slug, default: p.default ?? null }));
}
/** The run's per-role spec health, read-only: the invalidation
* surface the table renders as a note before any send refuses. An
* unset housekeeper is not an error -- it inherits the player
* spec's provider default (the same resolution the pass runs). */
/** @param {string} runId @returns {{ player: RoleHealth, housekeeper: RoleHealth }} */
function roleHealth(runId) {
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
/** @param {'player'|'housekeeper'} role @returns {RoleHealth} */
const health = (role) => {
const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
try {
const spec = specFromMeta(meta.models?.[role] ?? null, role);
if (spec) {
gateSpec(ctx, spec, role);
return { spec, ok: true, note: null, inherited: false };
}
if (role === 'player') {
return { spec: null, ok: false, note: 'no player model set for this run -- pick one in the model box', inherited: false };
}
// the housekeeper inherits: the player spec's provider's default
const player = specFromMeta(meta.models?.player ?? null, 'player');
const def = player ? ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null : null;
if (def) {
const inherited = { provider: /** @type {{ provider: string }} */ (player).provider, model: def.model, effort: def.effort };
gateSpec(ctx, inherited, 'housekeeper');
return { spec: inherited, ok: true, note: null, inherited: true };
}
return { spec: null, ok: false, note: 'no housekeeper pick, and no provider default to inherit', inherited: false };
} catch (e) {
return { spec: null, ok: false, note: String(/** @type {Error} */ (e).message ?? e), inherited: false };
}
};
return { player: health('player'), housekeeper: health('housekeeper') };
}
// the op's config detail: slugs, bases, key presence (the key itself
// never leaves the server), defaults -- what the admin block edits
route('GET', '/api/providers', async ({ user }) => {
requireSuperuser(user);
return {
phase: reg?.phase ?? 'none',
discovered: reg?.discovered ?? null,
refined: reg?.refined ?? null,
curator: reg?.curator ?? null,
defaults: effectiveDefaults(),
models: reg?.models ?? [],
job: discovery.jobState(ctx),
providers: ctx.providerCfg.providers.map((p) => ({
slug: p.slug,
baseUrl: p.baseUrl,
hasKey: !!p.apiKey,
default: p.default ?? null,
})),
};
});
route('POST', '/api/models/discover', async ({ user }) => {
// the probe (GM, 2026-11-19): discovery IS the health check -- every
// path that scrapes a provider records the outcome on the entity, so
// the card reads the last probe, never a stored machine. 401/403 is
// the ask (custom providers only -- an auth failure on o/f is
// upstream breakage, shown as the error it is); everything else is
// the error named. No runtime path probes: usage errors are transient
// and the op's to fix eventually (a failed turn already landed its
// req event, and the invalidation surface only answers removal).
/** @param {string} slug @param {{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }} probe */
function setProbe(slug, probe) {
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
const p = cfgMut.providers.find((x) => x.slug === slug);
if (!p) return; // removed mid-probe -- the record goes with the entity
p.probe = probe;
providers.applyConfig(ctx, cfgMut);
}
/** @param {string} slug @returns {Promise<import('./discovery.mjs').RegistrySection>} */
async function runProbe(slug) {
try {
const section = await discovery.discover(ctx, slug);
setProbe(slug, { outcome: 'ok', detail: `${section.models.length} models scraped`, at: new Date().toISOString() });
return section;
} catch (e) {
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
setProbe(slug, {
outcome: err.status === 401 || err.status === 403 ? 'auth' : 'error',
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
at: new Date().toISOString(),
});
throw e;
}
}
// add a provider (GM, 2026-11-19): {builtin: true} or {slug,
// baseUrl} -- never a key (the auth route is the only key path).
// Discovery is the probe: an auth refusal (401/403) leaves the
// provider standing broken -- the SPA asks for the key, checked on
// reception; every other failure refuses the add outright, because an
// endpoint that cannot answer is not a provider -- nothing stands.
route('POST', '/api/providers', async ({ body, user }) => {
requireSuperuser(user);
const reg = await discovery.discover(ctx);
return { ok: true, phase: reg.phase, models: reg.models.length };
if (body.apiKey !== undefined && body.apiKey !== null) {
throw new HttpError(400, 'apiKey does not ride the add -- send the endpoint alone; a 401/403 opens the key path');
}
const cfgMut = { providers: [...ctx.providerCfg.providers] };
/** @type {import('./shapes.mjs').ProviderCfg} */ let p;
if (body.builtin === true) {
const added = providers.addBuiltin(cfgMut);
if (!added) throw new HttpError(409, 'opencode/free is already on the provider list');
p = added; // addBuiltin pushed it
} else {
const slug = String(body.slug ?? '').trim();
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '');
if (!providers.validSlug(slug)) throw new HttpError(400, 'slug must be lowercase letters, digits, dashes (one slash allowed), e.g. my-shop');
if (providers.findProvider(cfgMut, slug)) throw new HttpError(409, `a provider named '${slug}' already exists`);
if (!providers.validBaseUrl(baseUrl)) throw new HttpError(400, 'baseUrl must be a valid http(s) URL');
p = { slug, baseUrl, default: null };
cfgMut.providers.push(p);
}
providers.applyConfig(ctx, cfgMut);
let section;
try {
section = await runProbe(p.slug);
} catch (e) {
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
if (err.status === 401 || err.status === 403) {
// the add stands (the op keys it or removes it); the failure
// carries its status for the SPA's password branch
throw new HttpError(err.status, `provider '${p.slug}' added, but the listing was refused: ${err.message} -- send the API key`);
}
// every other failure refuses the add: roll back, nothing stands
providers.applyConfig(ctx, { providers: ctx.providerCfg.providers.filter((x) => x.slug !== p.slug) });
throw err;
}
return { ok: true, provider: p.slug, models: section.models.length };
});
route('POST', '/api/models/refine', async ({ user }) => {
// set or replace a custom provider's key (the o/f singleton never
// takes one -- its purpose is to be the anonymous fallback; a 401
// from it is upstream breakage, not a prompt). Probe-then-save (GM,
// 2026-11-19): the candidate key is checked on reception -- a key
// that still meets the refusal is never saved, the previous state
// returns, and the ask stays open for the next attempt.
route('POST', '/api/providers/:slug/auth', async ({ params, body, user }) => {
requireSuperuser(user);
return discovery.refine(ctx, user);
const p = providers.findProvider(ctx.providerCfg, params.slug);
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
if (typeof body.apiKey !== 'string' || !body.apiKey.trim()) throw new HttpError(400, 'apiKey (a non-empty string) is required');
const prev = ctx.providerCfg;
const prevEntity = /** @type {import('./shapes.mjs').ProviderCfg} */ (prev.providers.find((x) => x.slug === p.slug));
const cfgMut = { providers: prev.providers.map((x) => ({ ...x })) };
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
target.apiKey = body.apiKey.trim();
providers.applyConfig(ctx, cfgMut);
try {
const section = await runProbe(p.slug);
return { ok: true, provider: p.slug, models: section.models.length };
} catch (e) {
// the failed candidate never saves: the previous state returns,
// and this attempt's probe record rides back with it (the card
// shows the last attempt, whatever it was)
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
const candidate = ctx.providerCfg.providers.find((x) => x.slug === p.slug);
if (candidate?.probe) prevEntity.probe = candidate.probe;
providers.applyConfig(ctx, prev);
throw err;
}
});
// remove a custom provider's key (GM, 2026-11-19): the op's control
// for a provider that went public -- or the first half of a key
// replacement, the second half being the ask, which re-opens when
// the keyless probe meets the 401 again. The removal stands whatever
// the probe says: it is the op's deliberate act, not an add; the
// probe outcome rides the response and the card.
route('DELETE', '/api/providers/:slug/auth', async ({ params, user }) => {
requireSuperuser(user);
const p = providers.findProvider(ctx.providerCfg, params.slug);
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
if (!p.apiKey) throw new HttpError(404, `provider '${p.slug}' has no key to remove`);
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
delete target.apiKey;
providers.applyConfig(ctx, cfgMut);
try {
const section = await runProbe(p.slug);
return { ok: true, provider: p.slug, models: section.models.length };
} catch (e) {
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
return {
ok: true,
provider: p.slug,
probe: err.status === 401 || err.status === 403 ? 'auth' : 'error',
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
};
}
});
// remove a provider: the section and the adjudication cache entries
// go with it; the runs that rode it invalidate at their next send
// (the GM's table carries the note)
route('DELETE', '/api/providers/:slug', async ({ params, user }) => {
requireSuperuser(user);
const slug = params.slug;
const guard = providers.removalGuard(ctx.providerCfg, slug);
if (guard) throw new HttpError(409, guard);
const cfgMut = { providers: ctx.providerCfg.providers.filter((p) => p.slug !== slug) };
if (cfgMut.providers.length === ctx.providerCfg.providers.length) {
throw new HttpError(404, `no such provider: ${slug}`);
}
providers.applyConfig(ctx, cfgMut);
discovery.deleteSection(slug);
discovery.purgeCache(slug);
return { ok: true };
});
// re-run one provider's discovery: the scrape, the section reset to
// preliminary (a refined section loses its battery -- the button
// says so in the UI), and the probe record updated -- this manual
// act is one of the only things that moves it
route('POST', '/api/providers/:slug/discover', async ({ params, user }) => {
requireSuperuser(user);
const section = await runProbe(params.slug);
return { ok: true, provider: params.slug, phase: section.phase, models: section.models.length };
});
// the selection: the provider's default {model, effort} -- also the
// refine curator. Validated against the provider's own registry.
route('POST', '/api/providers/:slug/default', async ({ params, body, user }) => {
requireSuperuser(user);
const p = providers.findProvider(ctx.providerCfg, params.slug);
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
const model = String(body.model ?? '').trim();
const effort = String(body.effort ?? '').trim();
if (!model) throw new HttpError(400, 'model (an id from this provider\'s registry) is required');
if (!discovery.EFFORT_LEVELS.includes(effort)) {
throw new HttpError(400, `effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
}
const m = discovery.findModel(p.slug, model);
if (!m) throw new HttpError(400, `model '${model}' is not in '${p.slug}'s registry -- run its discovery first`);
if (m.inference === false) throw new HttpError(400, `model '${model}' failed the inference battery -- it is not selectable`);
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
/** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug)).default = { model, effort };
providers.applyConfig(ctx, cfgMut);
return { ok: true, provider: p.slug, default: { model, effort } };
});
// refine one provider: the battery + the curator pass (the op's
// selected default is the curator). Real traffic, real cost; the job
// meters itself.
route('POST', '/api/providers/:slug/refine', async ({ params, user }) => {
requireSuperuser(user);
return discovery.refine(ctx, params.slug, user);
});
route('GET', '/api/packages', async () => {
@@ -414,7 +706,8 @@ route('GET', '/api/runs', async () => {
// create: the pc's name is required (unique per package); the
// package display name defaults to the package's own. The id is
// anonymous, generated by the clerk.
// anonymous, generated by the clerk. body.spec (the player pick, a
// full {provider, model, effort}) lands in run.json after the copy.
route('POST', '/api/runs', async ({ body, user }) => {
const pkg = String(body.package ?? '').trim();
const pc = String(body.pc ?? '').trim();
@@ -422,9 +715,30 @@ route('POST', '/api/runs', async ({ body, user }) => {
if (!pc) throw new HttpError(400, 'pc is required -- the main character\'s name, distinct per package');
const name = body.name === undefined ? undefined : String(body.name);
requireUser(user);
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
// the spec validates before anything lands: a refused create leaves
// no orphan run dir behind (the failures-never-cache smoke found
// the old order -- create first, validate after)
if (body.spec !== undefined) {
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body.spec);
if (typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
throw new HttpError(400, 'spec must be { provider, model, effort } -- see GET /api/models');
}
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
throw new HttpError(400, `spec.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
}
if (!discovery.usable(spec.provider, spec.model)) {
throw new HttpError(400, `spec model '${spec.model}' is not usable on '${spec.provider}' (not discovered, or failed the battery)`);
}
}
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []));
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
const run = JSON.parse(r.out);
if (body.spec !== undefined) {
const spec = /** @type {{ provider: string, model: string, effort: string }} */ (body.spec);
const meta = bundle.runMeta(run.id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
meta.models = { ...(meta.models ?? {}), player: { provider: spec.provider, model: spec.model, effort: spec.effort } };
fs.writeFileSync(path.join(bundle.runDir(run.id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
}
return { run, dir: `runs/${run.id}` };
});
@@ -457,12 +771,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
owner,
ownerName: owner == null ? null : userName(owner),
models: meta?.models ?? {},
params: meta?.params ?? {},
modelDefaults: effectiveDefaults(),
// the deployment layer of the knobs (server.json params): the
// only default an unset knob can honestly resolve to -- the
// provider's own serving defaults are unknown and stay unstated
paramDefaults: cfg.params ?? {},
// the invalidation surface: each resolved spec's health, so the
// table can carry the note before a send ever 409s
modelState: roleHealth(id),
// the providers' default specs -- the create flow's pre-select,
// and the fallback a pick-less role would inherit
providerDefaults: providerDefaults(),
},
display: bundle.runDisplay(id),
open: !!s,
@@ -599,80 +913,44 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
return { ok: true, vars: settings.vars };
});
// the run's models and sampling knobs: per-run overrides of the
// deployment defaults (server.json, else the registry's discovered
// pick), selected from the registry (GET /api/models). Owner-only,
// changeable at any time -- every call resolves fresh, so a
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default; a null knob clears the knob (for
// reasoning_effort, clearing means the registry's measured default
// rides again).
const KNOBS = ['temperature', 'top_p', 'top_k', 'repetition_penalty', 'max_tokens', 'reasoning_effort'];
// the run's model picks: full specs, selected from the registry (GET
// /api/models). Owner-only, changeable at any time -- every call
// resolves fresh, so a mid-session switch simply takes the next
// turn. null clears a role back to its inheritance (the player to
// nothing, the housekeeper to the player provider's default).
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
for (const k of Object.keys(body)) {
if (k !== 'player' && k !== 'housekeeper' && k !== 'params') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper, params`);
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper`);
}
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
const reg = discovery.registry();
const models = meta.models ?? {};
const models = { ...(meta.models ?? {}) };
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
if (body[role] === undefined) continue;
if (body[role] === null) { delete models[role]; continue; }
const m = String(body[role]).trim();
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
if (!discovery.usable(reg, m)) {
throw new HttpError(400, `${role}: '${m}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body[role]);
if (typeof spec !== 'object' || spec === null || Array.isArray(spec)
|| typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
throw new HttpError(400, `${role}: a full spec { provider, model, effort }, or null to clear -- see GET /api/models`);
}
models[role] = m;
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
throw new HttpError(400, `${role}: no provider named '${spec.provider}' is configured`);
}
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
throw new HttpError(400, `${role}.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
}
if (!discovery.usable(spec.provider, spec.model)) {
throw new HttpError(400, `${role}: '${spec.model}' is not usable on '${spec.provider}' (not in its registry, or failed the battery)`);
}
models[role] = { provider: spec.provider, model: spec.model, effort: spec.effort };
}
if (Object.keys(models).length) meta.models = models;
else delete meta.models;
if (body.params !== undefined) {
if (typeof body.params !== 'object' || body.params === null || Array.isArray(body.params)) {
throw new HttpError(400, 'params (an object of player/housekeeper knob objects) is required');
}
for (const role of Object.keys(body.params)) {
if (role !== 'player' && role !== 'housekeeper') throw new HttpError(400, `unknown params role: ${role}`);
const knobs = body.params[role];
if (typeof knobs !== 'object' || knobs === null || Array.isArray(knobs)) {
throw new HttpError(400, `params.${role} must be an object of knobs`);
}
for (const [k, v] of Object.entries(knobs)) {
if (!KNOBS.includes(k)) throw new HttpError(400, `unknown knob: ${k} -- ${KNOBS.join(', ')}`);
if (k === 'reasoning_effort') {
// the enum knob: one of the ladder's levels, or null to
// clear back to the measured default
if (v !== null && !discovery.EFFORT_LEVELS.includes(String(v))) {
throw new HttpError(400, `params.${role}.reasoning_effort must be one of ${discovery.EFFORT_LEVELS.join(', ')} -- or null to ride the model's measured default`);
}
continue;
}
if (v !== null && !Number.isFinite(v)) throw new HttpError(400, `params.${role}.${k} must be a number, or null to clear`);
}
}
const rp = meta.params ?? {};
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
const knobs = body.params[role];
if (knobs === undefined) continue;
const cur = { ...(rp[role] ?? {}) };
for (const [k, v] of Object.entries(knobs)) {
if (v === null) delete cur[/** @type {keyof import('./shapes.mjs').RoleParams} */ (k)];
else if (k === 'reasoning_effort') cur[/** @type {'reasoning_effort'} */ (k)] = String(v);
else cur[/** @type {'temperature'|'top_p'|'top_k'|'repetition_penalty'|'max_tokens'} */ (k)] = Number(v);
}
if (Object.keys(cur).length) rp[role] = cur;
else delete rp[role];
}
if (Object.keys(rp).length) meta.params = rp;
else delete meta.params;
}
fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
return { ok: true, models: meta.models ?? {}, params: meta.params ?? {}, defaults: effectiveDefaults(), paramDefaults: cfg.params ?? {} };
return { ok: true, models: meta.models ?? {}, modelState: roleHealth(id) };
});
// the GM's notepad: the run's gm.md -- the owner's alone (#28's
@@ -985,29 +1263,24 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
// the turn meter's read (GM, 2026-11-17): the live progress record
// the streaming callback feeds, plus the scale the bar guesstimates
// against -- the only true budget is max_tokens when the knobs set
// one (reasoning counts inside it), else the session's own history:
// her longest past turn in characters (thinking and prose both, the
// units the meter counts). No history and no budget means no scale:
// the client falls back to the chunk-driven animation. Owner-only
// machinery; a plain read, never queued.
// against -- the session's own history: her longest past turn in
// characters (thinking and prose both, the units the meter counts).
// No history means no scale: the client falls back to the
// chunk-driven animation. (The old max_tokens budget layer is gone
// with the per-run params: no surface sets one anymore -- GM,
// 2026-11-18.) Owner-only machinery; a plain read, never queued.
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
requireOwner(user, params.id);
const s = ctx.sessions.get(params.id);
if (!s) return { inFlight: false, scale: null };
// the max_tokens layer mirrors the loop's own resolution (the mind
// rides over the run and deployment params); ~4 chars a token is
// the meter's rough exchange rate -- a meter, not a ledger
const eff = { ...resolveParams(ctx, params.id, 'player'), ...(s.mind ?? {}) };
const budget = typeof eff.max_tokens === 'number' ? eff.max_tokens * 4 : null;
let high = 0;
for (const e of s.lines) {
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
if (chars > high) high = chars;
}
const scale = budget ?? (high > 0 ? high : null);
const scaleKind = budget ? 'budget' : (high > 0 ? 'history' : null);
const scale = high > 0 ? high : null;
const scaleKind = high > 0 ? 'history' : null;
if (!s.progress) return { inFlight: false, scale, scaleKind };
return { inFlight: true, ...s.progress, scale, scaleKind };
});
@@ -1187,5 +1460,7 @@ const server = http.createServer(async (req, res) => {
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
const host = DEBUG ? '127.0.0.1' : cfgHost;
server.listen(Number(port ?? 7350), host, () => {
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : (effectiveDefaults().player ?? 'no default model')} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
const providerCount = ctx.providerCfg.providers.length;
const discovered = Object.keys(discovery.registry()?.providers ?? {}).length;
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
});
+43 -12
View File
@@ -1,6 +1,7 @@
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
// endpoint per deployment (server.json "endpoint"); the model name
// comes from the run (run.json override) or the config default.
// server/provider.mjs -- the provider client. One client per
// configured provider entity (state/config.json, written by the
// server from the SPA); model specs name the provider slug, and
// providerFor walks the map to the client that owns it.
//
// Every completion streams (SSE) and is assembled back into the one
// response shape the callers consume -- no caller distinguishes
@@ -20,13 +21,27 @@
/** @typedef {(p: { phase: 'thinking'|'prose', chars: number }) => void} ProgressFn */
/**
* @param {{ baseUrl?: string, apiKey?: string, apiKeyEnv?: string }} endpoint
* @param {{ baseUrl?: string, apiKey?: string }} provider
*/
export function makeProvider(endpoint) {
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
if (!base) throw new Error('server.json: endpoint.baseUrl is required');
const key = endpoint.apiKey ?? process.env[endpoint.apiKeyEnv ?? 'RP_API_KEY'] ?? '';
const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` };
export function makeProvider(provider) {
const base = String(provider.baseUrl ?? '').replace(/\/+$/, '');
if (!base) throw new Error('the provider entry has no baseUrl');
const key = provider.apiKey ?? '';
// the auth header rides only when a key exists: an EMPTY Bearer is
// not the same as no auth (opencode.ai 401s the empty spelling and
// serves the anonymous listing to the headerless request -- found
// live in the fresh-path test, 2026-11-18)
const headers = { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) };
/** An API failure carries its HTTP status on the error object --
* the SPA branches on it (a 401/403 asks for the key), never on
* message parsing.
* @param {Response} res @returns {Promise<Error>} */
const apiError = async (res) => {
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`));
err.status = res.status;
return err;
};
return {
/**
@@ -48,7 +63,7 @@ export function makeProvider(endpoint) {
}),
});
if (!res.ok) {
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
throw await apiError(res);
}
// the SSE assembly: content and reasoning concatenate in order,
// tool_calls stitch by index (id and name land on the first
@@ -132,7 +147,7 @@ export function makeProvider(endpoint) {
async models() {
const res = await fetch(`${base}/models`, { headers });
if (!res.ok) {
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
throw await apiError(res);
}
const data = /** @type {{ data: { id: string }[] }} */ (await res.json());
return (data.data ?? []).map((m) => m.id).sort();
@@ -145,10 +160,26 @@ export function makeProvider(endpoint) {
async modelsMeta() {
const res = await fetch(`${base}/models`, { headers });
if (!res.ok) {
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
throw await apiError(res);
}
const data = /** @type {{ data: { id: string, max_input_tokens?: ?number, max_output_tokens?: ?number }[] }} */ (await res.json());
return (data.data ?? []).map((m) => ({ id: m.id, input: m.max_input_tokens ?? null, output: m.max_output_tokens ?? null }));
},
};
}
// The routing: the client that owns a provider slug. Model specs
// name the provider; the config holds the entity. A missing entry
// means the config dropped a provider the run still rides -- loud,
// never a silent fallback to some other provider (the model may not
// exist there, and the auth certainly differs).
/** @param {import('./shapes.mjs').Ctx} ctx @param {?string} slug @returns {ReturnType<typeof makeProvider>} */
export function providerFor(ctx, slug) {
const p = ctx.providers.get(String(slug ?? ''));
if (!p) {
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`the provider '${slug}' is not configured -- the run rides a route that is gone (re-add the provider, or re-pick the run's model)`));
err.status = 409;
throw err;
}
return p;
}
+118
View File
@@ -0,0 +1,118 @@
// server/providers.mjs -- the provider entities.
//
// A provider is a first-class thing (GM, 2026-11-18): a user-named
// slug, a baseUrl, optional auth, and the op's default model spec for
// it -- {model, effort}, never params (those are per-turn, the <mind>
// verb's alone). state/config.json is the truth, written only by the
// server; the SPA is the surface, zero hand edits. No legacy shapes
// are read: the config is born in this shape, and shape changes come
// with one-time migrations, not permanent tolerance (the no-legacy
// rule, GM, 2026-11-18).
//
// The built-in singleton: opencode/free -- the anonymous, keyless
// fallback, the harness thesis in one entry (playable with zero
// secrets). It never carries auth: if it starts answering 401, that
// is upstream breakage to show as an error, never a prompt to fix.
// It is always available: removable only while another provider
// exists, auto-added (with its discovery) whenever the provider list
// is empty -- the self-heal rule, broadly: an error that can be
// mechanically fixed to a reasonable degree without requiring human
// input gets fixed.
/** @typedef {import('./shapes.mjs').ProviderCfg} ProviderCfg */
/** @typedef {import('./shapes.mjs').DeployCfg} DeployCfg */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { makeProvider } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CONFIG_PATH = path.join(ROOT, 'state', 'config.json');
/** The singleton: fixed slug, fixed base, structurally authless. */
export const OF_SLUG = 'opencode/free';
export const OF_BASE = 'https://opencode.ai/inference/openai/v1';
/** A slug: lowercase letters, digits, dashes; at most one slash
* (the singleton's own two-segment shape is the precedent). */
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*(?:\/[a-z0-9][a-z0-9-]*)?$/;
/** @param {string} slug @returns {boolean} */
export function validSlug(slug) {
return SLUG_RE.test(slug) && slug.length <= 64;
}
/** @param {string} baseUrl @returns {boolean} */
export function validBaseUrl(baseUrl) {
try {
const u = new URL(baseUrl);
return u.protocol === 'https:' || u.protocol === 'http:';
} catch {
return false;
}
}
// --- the config file --------------------------------------------------------
/** @returns {DeployCfg} */
export function readConfig() {
try {
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
if (cfg && Array.isArray(cfg.providers)) return cfg;
} catch { /* absent or unreadable -- the empty state is legal */ }
return { providers: [] };
}
/** @param {DeployCfg} cfg */
export function writeConfig(cfg) {
fs.mkdirSync(path.dirname(CONFIG_PATH), { recursive: true });
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n');
}
/** @param {DeployCfg} cfg @param {string} slug @returns {?ProviderCfg} */
export function findProvider(cfg, slug) {
return cfg.providers.find((p) => p.slug === slug) ?? null;
}
/** The base-to-slug map -- what the routing errors and any
* base-keyed lookup read. */
/** @param {DeployCfg} cfg @returns {Map<string, string>} */
export function slugMap(cfg) {
return new Map(cfg.providers.map((p) => [p.baseUrl.replace(/\/+$/, ''), p.slug]));
}
/** Apply a mutated config: persist it and rebuild the context's
* clients. Every mutation goes through here -- the file and the map
* can never disagree.
* @param {import('./shapes.mjs').Ctx} ctx @param {DeployCfg} cfg @returns {DeployCfg} */
export function applyConfig(ctx, cfg) {
writeConfig(cfg);
ctx.providerCfg = cfg;
ctx.providers = new Map(cfg.providers.map((p) => [p.slug, makeProvider(p)]));
return cfg;
}
// --- the singleton ----------------------------------------------------------
/** Add the opencode/free singleton. Idempotent: returns null when it
* is already present (the add modal disables the choice, this is
* the backstop).
* @param {DeployCfg} cfg @returns {?ProviderCfg} */
export function addBuiltin(cfg) {
if (findProvider(cfg, OF_SLUG)) return null;
/** @type {ProviderCfg} */
const p = { slug: OF_SLUG, baseUrl: OF_BASE, default: null };
cfg.providers.push(p);
return p;
}
/** The removal guard (GM, 2026-11-18): the singleton goes only when
* a custom provider stands in its place -- the empty list is an
* error state, and the fallback is what keeps it unreachable.
* @param {DeployCfg} cfg @param {string} slug @returns {string} an error message, or '' when removable */
export function removalGuard(cfg, slug) {
if (slug !== OF_SLUG) return '';
if (cfg.providers.length > 1) return '';
return 'opencode/free is the anonymous fallback -- it is removable only while another provider is configured';
}
+22
View File
@@ -447,6 +447,18 @@ export function lintCarryover(lines, { authored }) {
if (m.reasoning_content) errors.push(`${at}: thinking is runtime metadata`);
if (e.reminder) errors.push(`${at}: the reminder rides every GM turn on its own`);
if (e.conflictOnly) errors.push(`${at}: conflict traffic is runtime machinery`);
// the sheet's transport (GM, 2026-11-19, the box round): the
// record is the only channel -- the tag is view machinery,
// composed by renderView, never authored by anyone. Hers would
// never apply (the scan holds the GM's record) and primes the
// guarded emission; GM prose rides the view and story raw (the
// GM-side strips do not know the tag)
if (m.role === 'assistant' && e.sheet !== undefined) {
errors.push(`${at}: the sheet is the GM's record -- it rides GM turns only`);
}
if (typeof m.content === 'string' && /<\/?sheet>/.test(m.content)) {
errors.push(`${at}: the sheet tag is composed by the view, never authored -- the JSON rides the GM turn as its "sheet" record`);
}
} else if (e.t === 'opening') {
openings++;
if (!Array.isArray(e.status)) errors.push(`${at}: opening.status must be an array of descriptions`);
@@ -470,6 +482,13 @@ export function lintCarryover(lines, { authored }) {
errors.push(`${at}: malformed variants block -- ${e2.message}`);
}
}
// both kinds: a GM turn's sheet record is the scan's source -- the
// route checks object-ness live, the lint covers every hand path
// (authored carryovers and dormancy edits both pass through here)
if (e.t === 'msg' && e.m?.role === 'user' && e.sheet !== undefined
&& (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
errors.push(`${at}: the sheet record must be a JSON object`);
}
// both kinds: the boundary state note must be well-formed (stop
// writes it; a hand edit must not corrupt it)
if (e.t === 'note' && e.kind === 'state') {
@@ -481,6 +500,9 @@ export function lintCarryover(lines, { authored }) {
errors.push(`${at}: state.${k} must be an array of non-empty strings`);
}
}
if (e.sheet !== undefined && (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
errors.push(`${at}: state.sheet must be a JSON object`);
}
}
});
if (authored && openings > 1) errors.push('at most one opening event');
+77 -36
View File
@@ -30,17 +30,20 @@ export {};
* everything else about a turn lives in its content. via is the
* request record: the resolved model and the effective params (the
* merged layer actually sent) -- model-facing surfaces never render
* it, the raw surfaces always do. override is the GM's block edit,
* arriving with a non-OOC GM turn: the log's record of it. The
* composition overwrites her newest blocks with these values (the
* scan reads it newest-wins); the log itself never changes. */
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record<string, unknown> }} MsgEvent */
* it, the raw surfaces always do. via.model is the bare model id;
* via.provider names the route (absent in pre-spec logs). override
* is the GM's block edit, arriving with a non-OOC GM turn: the log's
* record of it. The composition overwrites her newest blocks with
* these values (the scan reads it newest-wins); the log itself never
* changes. */
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, provider?: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record<string, unknown> }} MsgEvent */
/** req: a failed provider request -- the resolved model, the
* effective params, and the failure. No message resulted (the turn
* fails loud, the retry is the user's); this is the record of what
* was attempted, surfaced on the raw surfaces like a note. */
/** @typedef {{ t: 'req', model: string, params: RoleParams, fail: string }} ReqEvent */
/** req: a failed provider request -- the resolved model (and its
* provider route), the effective params, and the failure. No
* message resulted (the turn fails loud, the retry is the user's);
* this is the record of what was attempted, surfaced on the raw
* surfaces like a note. */
/** @typedef {{ t: 'req', model: string, provider?: string, params: RoleParams, fail: string }} ReqEvent */
/** tool: a tool result, paired to its call (pairing is a context
* invariant, checked at render). */
@@ -92,32 +95,56 @@ export {};
/** The turn meter's live record: what the streaming callback knows. `phase` is what is arriving now; `started` is the provider call's epoch ms. */
/** @typedef {{ phase: 'thinking'|'prose', thinking: number, prose: number, started: number }} TurnProgress */
/** run.json: lineage, ownership, per-run model overrides and knobs. */
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string }, params?: { player?: ?RoleParams, housekeeper?: ?RoleParams } }} RunMeta */
/** One model spec: the complete inference request identity (GM,
* 2026-11-18) -- which provider routes it, the model id, and the
* reasoning effort, all three required (there is no unset effort:
* it substantially changes inference quality, so it is a property
* of the model pick, never a free-floating knob). The fourth spec
* member, sampling params, is optional and never stored: the <mind>
* verb sets it for one specific turn. */
/** @typedef {{ provider: string, model: string, effort: string }} ModelSpec */
/** The named sampling knobs, per role -- the well-known, widely
* supported set, plus the reasoning-effort enum (GM, 2026-11-16:
* first-class, hidden from the model -- not her call). Numbers ride
* the wire verbatim; null clears; reasoning_effort is one of the
* effort ladder's levels. */
/** run.json: lineage, ownership, and the run's model picks -- full
* specs, per role. (The retired per-run params layer is gone
* entirely, GM, 2026-11-18: params are per-turn via <mind>, and the
* no-legacy rule migrated the last carrier away.) */
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?ModelSpec, housekeeper?: ?ModelSpec } }} RunMeta */
/** The named sampling knobs -- the <mind> verb's four (hers to set
* for one turn), plus the wire-side extras the substrate itself
* rides: reasoning_effort always comes from the model spec, never
* the mind layer (hidden from the model, not her call). Numbers
* ride the wire verbatim. */
/** @typedef {{ temperature?: number, top_p?: number, top_k?: number, repetition_penalty?: number, max_tokens?: number, reasoning_effort?: string }} RoleParams */
/** One model of the discovered registry. Preliminary entries carry
* the scrape only (status unrefined); refined entries carry the
* battery's verdicts and the curator's presentation. think is the
* battery's best measured thinking-token count -- the pick rule
* ranks on it (the bucket is display). efforts is the
* reasoning-effort probe: the measured mean thinking per level of
* the ladder; effortDefault is the level with the highest observed
* mean (GM, 2026-11-16: maximum thinking by default, overridable)
* -- null when the model shows no thinking or no level moved it. */
/** One model of a discovered provider's registry section. Preliminary
* entries carry the scrape only (status unrefined); refined entries
* carry the battery's verdicts and the curator's presentation. The
* section key is the provider slug -- no routing tag needed, the
* section names the route. think is the battery's best measured
* thinking-token count. efforts is the reasoning-effort probe: the
* measured mean thinking per level of the ladder; effortDefault is
* the level with the highest observed mean -- pre-fill and hint
* only (GM, 2026-11-18: with effort a property of the pick, nothing
* rides implicitly anymore; it pre-selects the selection prompt's
* dropdown and informs the curator's recommendation, no more). */
/** @typedef {{ id: string, input: ?number, output: ?number, status?: 'unrefined', inference?: boolean, fail?: string, think?: ?number, reasoning?: 'off'|'low'|'standard'|'deep'|null, offSwitch?: Record<string, unknown>|null, efforts?: ?Record<string, number>, effortDefault?: ?string, latency?: ?number, family?: ?string, label?: ?string, description?: ?string, roles?: { player: boolean, housekeeper: boolean } }} RegistryModel */
/** state/models.json: the deployment's model registry -- the truth of
* what is selectable. Written by discovery (the scrape) and refine
* (the battery + the curator pass); read by the selectors, the model
* routes, and the turn loop. */
/** @typedef {{ phase: 'preliminary'|'refined', endpoint: ?string, discovered: string, refined: ?string, defaults: { player: ?string, housekeeper: ?string }, models: RegistryModel[], curator?: string }} ModelRegistry */
/** One provider's registry section (state/models.json): written by
* that provider's discovery and refine alone, deletable whole on
* provider removal. recommendation is the curator's overall-best
* {model, effort} -- intel only, shown post-refine, applied by the
* op's click, never auto-landed and never deterministic on a bad
* model day (GM, 2026-11-18: on a bad day the op gets no advice,
* not machine advice). */
/** @typedef {{ phase: 'preliminary'|'refined', discovered: string, refined: ?string, models: RegistryModel[], curator?: ?string, recommendation?: ?{ model: string, effort: string } }} RegistrySection */
/** state/models.json: the per-provider registry -- the truth of what
* is selectable, 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. The singular
* and flat-vector era shapes migrate in memory on open. */
/** @typedef {{ providers: Record<string, RegistrySection> }} ModelRegistry
/** settings.json: identity (pc/name are the @ sigils), declared vars,
* the records flag. */
@@ -158,10 +185,24 @@ export {};
/** The provider client (provider.mjs's own return type). */
/** @typedef {ReturnType<typeof import('./provider.mjs').makeProvider>} Provider */
/** server.json as parsed. params is per-role sampling knobs -- the
* deployment-default layer the run's own params override. */
/** @typedef {{ bind?: string, port?: number, endpoint?: { baseUrl?: string, apiKey?: string, apiKeyEnv?: string }, models: { player?: ?string, housekeeper?: ?string }, contwin?: number, contextWindow?: number, params?: { player?: RoleParams, housekeeper?: RoleParams } }} ServerCfg */
/** One configured provider: a slug, a baseUrl, optional auth, and
* the op's default model spec for it ({model, effort} -- params are
* per-turn via <mind>, never in the provider default). The
* opencode/free singleton is this shape with the slug and baseUrl
* fixed and auth structurally absent. */
/** @typedef {{ slug: string, baseUrl: string, apiKey?: string, default?: ?{ model: string, effort: string }, probe?: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string } }} ProviderCfg */
/** state/config.json: the deployment's provider entities -- server
* written only (the SPA is the surface, zero hand edits). */
/** @typedef {{ providers: ProviderCfg[] }} DeployCfg */
/** server.json as parsed -- the static, non-secret remainder of the
* old config: bind and contwin. */
/** @typedef {{ bind?: string, port?: number, contwin?: number }} ServerCfg */
/** The server context: the one object threaded through every module.
* locks/enqueue are the per-run activity lock (main.mjs). */
/** @typedef {{ mock: boolean, cfg: ServerCfg, provider: Provider, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */
* locks/enqueue are the per-run activity lock (main.mjs). providers
* is the provider clients keyed by slug (the config's truth,
* rebuilt on every config mutation); providerCfg is the config
* itself. */
/** @typedef {{ mock: boolean, cfg: ServerCfg, providerCfg: DeployCfg, providers: Map<string, Provider>, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */