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
+15 -13
View File
@@ -43,22 +43,23 @@
</div>
<div id="invite-list"></div>
<div id="user-list"></div>
<div id="models-admin">
<h3>models</h3>
<div id="models-state" class="hint"></div>
<div id="providers-admin">
<h3>providers</h3>
<div id="providers-banner" class="hint" hidden></div>
<div id="provider-list"></div>
<div class="form-actions">
<button id="models-discover">discover</button>
<button id="models-refine">refine</button>
<button id="provider-add-of">add opencode/free</button>
<button id="provider-add-custom">add custom provider</button>
</div>
<div id="refine-progress" hidden>
<div id="refine-topline">
<span id="refine-count"></span>
<span id="refine-label" class="hint"></span>
<form id="provider-form" hidden>
<label class="field">slug <input id="provider-slug" autocomplete="off" placeholder="my-shop"></label>
<label class="field">baseUrl <input id="provider-base" autocomplete="off" placeholder="https://api.example.com/v1"></label>
<label class="field" id="provider-key-field" hidden>API key <input id="provider-key" type="password" autocomplete="off"></label>
<div class="form-actions">
<button type="button" id="provider-add-go">add and discover</button>
<button type="button" id="provider-add-cancel">cancel</button>
</div>
<div id="refine-bar"><div id="refine-fill"></div></div>
</div>
<div id="refine-lines"></div>
<div id="models-list"></div>
</form>
</div>
</section>
</section>
@@ -108,6 +109,7 @@
<pre id="edit-hl" aria-hidden="true"></pre>
<textarea id="setup-edit" spellcheck="false"></textarea>
</div>
<div id="edit-hint" hidden></div>
<div id="setup-edit-bar">
<button id="setup-save">save</button>
<span id="setup-edit-state"></span>
+34 -201
View File
@@ -1,211 +1,44 @@
// web/knobs.mjs -- the sampling knobs: the definitions table and the
// per-role knob row.
// web/knobs.mjs -- the reasoning-effort ladder and its select.
//
// The knobs are named, well-known, widely supported. The definitions
// table is the single home of every knob text -- label, hint, bounds
// -- red-pen the prose here, in place. Bounds are display knowledge
// probed from this endpoint's own validation errors (the /model
// route's validation stays generic: a finite number, or one of the
// effort ladder's levels). The provider's serving defaults are
// unknown and stay unstated; the only default anyone can honestly
// name is the deployment layer (server.json params), which rides the
// run detail as paramDefaults -- reasoning_effort is the one
// exception: the registry measured a per-model default (the maximum
// observed mean thinking), so its unset state honestly sends.
// The per-run sampling knobs are retired (GM, 2026-11-18): params are
// per-turn and only hers -- the <mind> verb sets them for one turn,
// nothing stores them. Reasoning effort is a property of the model
// pick (there is no unset effort), so its select lives inside the
// model picks (widgets.mjs's modelsBox) and the provider selection
// (view-home's admin block), not a knob row. The ladder mirrors
// server/discovery.mjs's EFFORT_LEVELS (the web cannot import server
// runtime code); keep them in step.
//
// Two defaults, never conflated: a knob unset means its value is NOT
// sent to the provider; a value present is sent, and the row marks it
// when it equals the deployment default. The explicit override toggle
// carries the distinction: off (the visible default) disables the
// input and saving sends nothing for the knob (null clears a
// previously-set value); on demands a number (a level, for the enum).
//
// The hint bar is shared by both roles -- one explanation at a time,
// driven by focus (a tap focuses), cleared when focus leaves the
// knobs entirely.
/** @typedef {import('../server/shapes.mjs').RoleParams} RoleParams */
// The old knobs' teaching surface -- what temperature means, what
// top_p does -- was prompt-side all along: invariants.md documents
// the mind verb, and the model answers with native JSON. The GM-side
// texts died with the rows; the four bounds live on in the server's
// mind-verb validator (server/loop.mjs, KNOB_BOUNDS).
import { el } from './dom.mjs';
// the reasoning-effort ladder -- mirrors server/discovery.mjs's
// EFFORT_LEVELS (the web cannot import server runtime code); keep
// them in step
const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
// EFFORT_LEVELS; keep them in step
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
/** One knob's definition: the texts are the product. Two kinds ship:
* numbers, and the effort enum (a select over the ladder). All six
* knobs are the GM's here; the mind verb (server/loop.mjs) sets
* only the four that are hers -- max_tokens is excluded by ruling
* (a budget, not a mind), reasoning_effort is hidden from her
* entirely (not her call). */
/** @typedef {{ key: keyof RoleParams, kind: 'number', label: string, hint: string, bounds: string }} NumberDef */
/** @typedef {{ key: keyof RoleParams, kind: 'enum', label: string, hint: string }} EnumDef */
/** @typedef {NumberDef|EnumDef} KnobDef */
/** @type {KnobDef[]} */
const DEFS = [
{
key: 'temperature',
kind: 'number',
label: 'temperature',
hint: 'How adventurous the word choice is. Higher: more varied and surprising, occasionally unhinged. Lower: more predictable and conservative; at 0 the same prompt tends to get the same words.',
bounds: 'This endpoint: 0 to 2.',
},
{
key: 'top_p',
kind: 'number',
label: 'top_p',
hint: 'Narrows the field to the most likely words that together cover this much probability. Higher: more words in play, more variety. Lower: fewer, safer choices; very low makes her repeat herself.',
bounds: 'This endpoint: above 0 (0 is refused), up to 1.',
},
{
key: 'top_k',
kind: 'number',
label: 'top_k',
hint: 'Like top_p but by count -- only the k most likely words are considered each step. Higher: more variety. Lower: more locked-in; at 1 she picks the single most likely word every time. -1 and 0 turn the filter off.',
bounds: 'No known bounds on this endpoint; -1 and 0 both mean the filter is off.',
},
{
key: 'repetition_penalty',
kind: 'number',
label: 'repetition_penalty',
hint: 'A direct nudge against repeating recent words and phrasings. 1 is no effect; raise it to make her evade repetition. Too high and she substitutes odd words to escape.',
bounds: 'Must be above 0 on this endpoint, no known max.',
},
{
key: 'max_tokens',
kind: 'number',
label: 'max_tokens',
hint: 'The response\'s hard length budget. Higher: room for long turns. Lower: cheaper and shorter, but the turn can cut off mid-sentence -- and on reasoning models thinking counts against this budget first, so a low cap can be eaten entirely before she writes a word.',
bounds: '1 or more on this endpoint; no enforced max (values above the model\'s output ceiling are accepted).',
},
{
key: 'reasoning_effort',
kind: 'enum',
label: 'reasoning effort',
hint: 'How hard the model thinks before answering. Higher levels reason more thoroughly and cost more (thinking bills as output tokens); lower levels answer faster. The level is a request, not a guarantee -- the model adapts to the task. Not hers to set: the mind verb never carries it.',
},
];
/** The hint bar's text for one knob: label, the explanation, the
* bounds, and the honest default statement for this role's
* deployment layer. Never invents an unknown value. The enum knob
* states its own honest default: the measured pick. */
/** @param {KnobDef} def @param {number|string|undefined|null} dep @param {?{ measured: Record<string, number>, fallback: ?string }} [effort] @returns {string} */
function hintText(def, dep, effort) {
if (def.kind === 'enum') {
const table = effort
? `Measured mean thinking for this model: ${Object.entries(effort.measured).map(([k, v]) => `${k} ${v}`).join(', ')}.`
: 'No effort measurements for this model (an unrefined registry, or the model shows no thinking).';
const rides = (dep !== undefined && dep !== null ? String(dep) : null) ?? effort?.fallback ?? null;
const defLine = rides
? `Unset = ${rides} rides (the measured default: the level with the highest observed thinking).`
: 'Unset = not sent; the model id\'s own baked default applies.';
return `${def.label} -- ${def.hint} ${table} ${defLine}`;
}
const d = /** @type {NumberDef} */ (def);
const defLine = dep !== undefined && dep !== null
? `Unset = the deployment default (${dep}).`
: 'Unset = not sent; the provider\'s own default applies (unknown).';
return `${d.label.replace(/_/g, ' ')} -- ${d.hint} ${d.bounds} ${defLine}`;
}
/** One role's knob row.
* @param {string} role
* @param {RoleParams|undefined} current the run's own knobs
* @param {RoleParams|undefined|null} deployment the deployment layer (server.json params)
* @param {HTMLElement} hintBar the shared hint bar
* @param {?{ measured: Record<string, number>, fallback: ?string }} [effort] the current model's measured effort ladder (null: none)
* @returns {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }}
/** A select over the ladder. The '' option's label names what an
* absent choice means at the call site (the measured default in the
* model box, "pick a level" in the selection prompt) -- the caller
* owns the sentence, this builds the options.
* @param {?string} current the pre-selected level ('' when none)
* @param {string} unsetLabel the '' option's label
* @returns {HTMLSelectElement}
*/
export function knobsBox(role, current, deployment, hintBar, effort = null) {
const wrap = el('div', 'knobs');
wrap.appendChild(el('div', 'knobs-head', `${role} knobs`));
/** @type {Record<string, { tog: HTMLInputElement, inp: HTMLInputElement, sel: ?HTMLSelectElement }>} */
const rows = {};
for (const def of DEFS) {
const row = el('div', 'knob');
const tog = /** @type {HTMLInputElement} */ (el('input'));
tog.type = 'checkbox';
tog.title = 'override';
const lab = el('label', null, `${def.label.replace(/_/g, ' ')} `);
const mark = el('span', 'knob-default', ' \u00b7 deployment default');
/** @type {?HTMLSelectElement} */ let sel = null;
const inp = /** @type {HTMLInputElement} */ (el('input'));
if (def.kind === 'enum') {
// the effort row: a select over the ladder; unset sends the
// measured default (the registry's pick for the current model)
sel = /** @type {HTMLSelectElement} */ (el('select'));
const rides = deployment?.[def.key] ?? effort?.fallback ?? null;
const unset = /** @type {HTMLOptionElement} */ (el('option', null, rides ? `(default: ${rides})` : '(not sent)'));
unset.value = '';
sel.appendChild(unset);
for (const lv of EFFORT_LEVELS) {
const o = /** @type {HTMLOptionElement} */ (el('option', null, lv));
o.value = lv;
sel.appendChild(o);
}
lab.appendChild(sel);
} else {
inp.type = 'number';
inp.step = 'any';
lab.appendChild(inp);
}
lab.appendChild(mark);
row.appendChild(tog);
row.appendChild(lab);
wrap.appendChild(row);
const set = current?.[def.key];
tog.checked = set !== undefined;
const dep = deployment?.[def.key];
// the toggle owns the state: off disables the input (the value
// stays for a change of mind), on demands a number (a level);
// a value equal to the deployment default is still sent, and
// the row marks it
const sync = () => {
const field = /** @type {HTMLInputElement|HTMLSelectElement} */ (sel ?? inp);
field.disabled = !tog.checked;
const v = sel ? sel.value : inp.value.trim();
mark.hidden = !(tog.checked && v !== '' && v === String(dep ?? '\u0000'));
};
tog.addEventListener('change', sync);
if (sel) sel.addEventListener('change', sync);
else inp.addEventListener('input', sync);
sync();
const focusEl = /** @type {HTMLElement} */ (sel ?? inp);
focusEl.addEventListener('focus', () => { hintBar.textContent = hintText(def, dep, effort); });
if (sel && set !== undefined) sel.value = String(set);
else if (!sel && set !== undefined) inp.value = String(set);
rows[def.key] = { tog, inp, sel };
export function effortSelect(current, unsetLabel) {
const sel = /** @type {HTMLSelectElement} */ (el('select'));
const unset = /** @type {HTMLOptionElement} */ (el('option', null, unsetLabel));
unset.value = '';
sel.appendChild(unset);
for (const lv of EFFORT_LEVELS) {
const o = /** @type {HTMLOptionElement} */ (el('option', null, lv));
o.value = lv;
sel.appendChild(o);
}
// the bar keeps its text while focus moves inside the row, clears
// when it leaves the knobs entirely
wrap.addEventListener('focusout', (e) => {
if (!wrap.contains(/** @type {?Node} */ (e.relatedTarget))) hintBar.textContent = '';
});
const read = () => {
/** @type {Record<string, number|string|null>} */ const out = {};
for (const def of DEFS) {
const { tog, inp, sel } = rows[def.key];
if (tog.checked) {
if (sel) {
const v = sel.value;
if (!v) throw new Error(`${def.label}: a level is required -- or switch the override off`);
out[def.key] = v;
} else {
const v = inp.value.trim();
if (v === '' || !Number.isFinite(Number(v))) {
throw new Error(`${def.label}: a number is required -- or switch the override off`);
}
out[def.key] = Number(v);
}
} else if (current?.[def.key] !== undefined) {
out[def.key] = null; // clearing a previously-set knob
}
}
return out;
};
return { wrap, read };
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
return sel;
}
+22 -10
View File
@@ -10,19 +10,31 @@ export {};
/** One run card as GET /runs serves it (the clerk's listing,
* enriched by the server with the live-session state). fill is
* present exactly when the run is initialized. */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
* present exactly when the run is initialized. models is run.json
* verbatim: the spec picks. */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
/** One role's spec health: the resolved spec (null when unset or
* unresolvable), whether it is playable, and the note when it is
* not -- the invalidation surface the table and the model box
* render. An unset housekeeper that inherits is ok with
* inherited: true. */
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
/** GET /runs/:id -- the run detail: identity, the phase bookkeeping,
* her two blocks, the fill, the context meter's numbers.
* paramDefaults is the knobs' deployment layer (server.json params)
* -- the only default an unset knob honestly resolves to. */
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, params: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, modelDefaults: { player?: ?string, housekeeper?: ?string }, paramDefaults: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
* her two blocks, the fill, the context meter's numbers. models is
* run.json verbatim (the spec picks); modelState is the resolved
* truth. */
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, modelState: { player: RoleHealth, housekeeper: RoleHealth }, providerDefaults: { slug: string, default: ?{ model: string, effort: string } }[] }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
/** GET /api/models -- the deployment's model registry and the
* discovery job state riding along. phase 'none' is the fresh
* deployment: nothing is selectable until the op discovers. */
/** @typedef {{ phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, defaults: { player?: ?string, housekeeper?: ?string }, models: import('../server/shapes.mjs').RegistryModel[], job: ?import('../server/shapes.mjs').JobState }} ModelsRegistryResponse */
/** One provider's /api/models payload: its registry section (phase
* 'none' when never discovered), the op's default spec, the
* curator's recommendation, and the refine job state. */
/** @typedef {{ slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('../server/shapes.mjs').RegistryModel[], job: ?import('../server/shapes.mjs').JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }} ProviderPayload */
/** GET /api/models -- the per-provider registry: one payload per
* configured provider, the truth of what is selectable. */
/** @typedef {{ providers: ProviderPayload[] }} ModelsRegistryResponse */
/** GET /runs/:id/table -- the live session's projection (thinking
* never crosses the wire, variant turns carry only the picked one). */
+9 -7
View File
@@ -66,13 +66,14 @@ body.play #context-meter { visibility: visible; }
#context-fill { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; }
#context-fill.hot { background: var(--danger); }
#refine-progress { margin: 10px 0 2px; }
#refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
#refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
#refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
#refine-fill { height: 100%; width: 0; background: var(--ok); }
#refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; }
.provider-card { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 8px; }
.refine-progress { margin: 10px 0 2px; }
.refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
.refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
.refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
.refine-fill { height: 100%; width: 0; background: var(--ok); }
.refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; }
.refine-line { font-family: monospace; white-space: pre-wrap; }
.turn-live { margin: 10px 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; }
@@ -272,6 +273,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
.tok-var { color: var(--ok); }
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
#setup-edit-state { color: var(--dim); font-size: 12px; }
#edit-hint { color: var(--dim); font-size: 12px; margin-top: 8px; }
/* --- transcript (play) --- */
+7 -6
View File
@@ -148,15 +148,16 @@ function renderContent(target, text, { extract }) {
return { status, conflict, agenda };
}
// the request record's line: the resolved model and the effective
// params as sent (the merged layer actually sent). Shared by the raw
// walk and the per-turn raw control. fail is present when the call
// failed -- no message resulted.
/** @param {{ model: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
// the request record's line: the resolved spec (provider and model)
// and the effective params as sent. Shared by the raw walk and the
// per-turn raw control. fail is present when the call failed -- no
// message resulted.
/** @param {{ model: string, provider?: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
export function viaLine(via, fail = null) {
const ks = Object.entries(via.params ?? {});
const p = ks.length ? ` -- ${ks.map(([k, v]) => `${k}: ${v}`).join(', ')}` : ' (no knobs set)';
return fail ? `[request failed] ${via.model}${p} -- ${fail}` : `[request] ${via.model}${p}`;
const who = via.provider ? `${via.provider}/${via.model}` : via.model;
return fail ? `[request failed] ${who}${p} -- ${fail}` : `[request] ${who}${p}`;
}
// the GM's block edit, as the machinery line both walks show: the
+270 -66
View File
@@ -6,7 +6,8 @@ import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, render } from './router.mjs';
import { armedButton, fmtCeiling } from './widgets.mjs';
import { armedButton, fmtCeiling, dropModelCache } from './widgets.mjs';
import { EFFORT_LEVELS } from './knobs.mjs';
/** @typedef {import('./shapes.mjs').RunCard} RunCard */
@@ -25,7 +26,7 @@ export async function enter(arg, seq) {
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta -- chrome, never model-facing
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${r.models?.player ? ` \u00b7 ${r.models.player}` : ''}`));
card.appendChild(el('span', 'card-meta', `${r.package} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${specTag(r.models?.player)}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
// your own draft opens the editor; anyone else's run opens at
// the story -- the table is the owner's
@@ -39,6 +40,9 @@ export async function enter(arg, seq) {
const ownershipTag = (r, mine) =>
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
// the card's model garnish: a spec renders as provider/model
/** @param {{ provider?: string, model?: string }|null|undefined} pick @returns {string} */
const specTag = (pick) => (pick && pick.provider ? ` \u00b7 ${pick.provider}/${pick.model ?? '?'}` : '');
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
/** @param {number} t @returns {string} */
function fmtUnix(t) {
@@ -107,57 +111,211 @@ async function renderAdmin(seq) {
}
userList.appendChild(row);
}
renderModelsAdmin(reg, seq);
renderProvidersAdmin(reg, seq);
}
// --- models: the discovery surface --------------------------------------------
// --- providers: the op's surface ---------------------------------------------
//
// Two op acts: discover (the metadata scrape, free) and refine (the
// inference battery + the curator pass -- real traffic, may cost
// real money, two-click armed with the warning). The registry state
// line and the model list render from the saved registry.
// The provider cards: the state line, the selection (the default
// {model, effort} pair -- also the refine curator), discover and
// refine (both armed: discover resets a refined section to the
// scrape, refine sends real traffic over every model on the
// provider), remove (the o/f singleton holds while it is all that
// stands), the refine meter with its surviving receipt, the model
// list, and the curator's recommendation beside the selection --
// intel, one click to apply. The add flow is the binary choice:
// opencode/free (disabled when present) or a custom provider.
/** @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {number} seq */
function renderModelsAdmin(reg, seq) {
const stateLine = $('models-state');
const running = reg.job?.state === 'running';
if (reg.phase === 'none') {
stateLine.textContent = 'no models discovered -- model use is disabled until you discover';
} else if (reg.phase === 'preliminary') {
stateLine.textContent = `preliminary registry -- ${reg.models.length} scraped, unrefined (discovered ${fmtStamp(reg.discovered)})`;
} else {
stateLine.textContent = `refined registry -- ${reg.models.filter((m) => m.inference !== false).length}/${reg.models.length} usable \u00b7 defaults ${reg.defaults.player ?? 'none'} / ${reg.defaults.housekeeper ?? 'none'}${reg.curator && reg.curator !== 'curated' ? ` \u00b7 ${reg.curator}` : ''} (refined ${fmtStamp(reg.refined)})`;
/** @param {import('./shapes.mjs').ProviderPayload} p @returns {string} */
function providerStateLine(p) {
if (p.phase === 'none') {
// the probe record is the card's truth (GM, 2026-11-19): an auth
// refusal opens the key path (never on o/f -- its auth failure is
// upstream breakage, not a prompt); any other failure names
// itself; no probe yet is a provider that was never scraped
if (p.probe?.outcome === 'auth') {
return p.slug === 'opencode/free'
? 'upstream auth failure -- nothing to fix on this side, wait'
: 'discovery refused -- it wants an API key';
}
if (p.probe?.outcome === 'error') return `discovery failed -- ${p.probe.detail}`;
return 'not discovered yet';
}
if (running) stateLine.textContent = `refining -- ${reg.job?.phase ?? ''} started ${fmtStamp(reg.job?.started ?? null)}; this page follows the job`;
/** @type {HTMLButtonElement} */ ($('models-discover')).disabled = running;
/** @type {HTMLButtonElement} */ ($('models-refine')).disabled = running || reg.phase === 'none';
if (p.phase === 'preliminary') return `${p.models.length} scraped, unrefined (discovered ${fmtStamp(p.discovered)})`;
const usable = p.models.filter((m) => m.inference !== false).length;
const def = p.default ? ` \u00b7 default ${p.default.model} at ${p.default.effort}` : ' \u00b7 no default selected';
return `refined -- ${usable}/${p.models.length} usable${def}${p.curator && p.curator !== 'curated' ? ` \u00b7 ${p.curator}` : ''} (refined ${fmtStamp(p.refined)})`;
}
// the refine meter: the bar moves only on real step completions
// (no speed to interpolate -- a stuck bar means a stuck step), the
// label names the call running now, and the lines are the receipt
// -- they survive the job, so a landed pass keeps its verdicts and
// a rejected one keeps its post-mortem
const meter = $('refine-progress');
const linesBox = $('refine-lines');
if (reg.job?.steps) {
const j = reg.job;
/** @param {import('./shapes.mjs').ProviderPayload} p @param {number} seq */
function renderProviderCard(p, seq) {
const card = el('div', 'provider-card');
const running = p.job?.state === 'running';
const head = el('div', 'admin-row');
head.appendChild(el('span', 'grow', `${p.slug} \u00b7 ${providerStateLine(p)}`));
const rm = el('button', 'danger', 'remove');
armedButton(rm, {
label: 'remove',
confirm: 'the runs riding it block until re-picked -- click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}`, { method: 'DELETE', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
head.appendChild(rm);
card.appendChild(head);
// the acts
const acts = el('div', 'form-actions');
const disc = /** @type {HTMLButtonElement} */ (el('button', null, 'discover'));
const refi = /** @type {HTMLButtonElement} */ (el('button', null, 'refine'));
disc.disabled = running;
refi.disabled = running || p.phase === 'none';
armedButton(disc, {
label: 'discover',
confirm: 'resets this provider\'s section to a fresh scrape -- the battery results are re-earned by refining. click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}/discover`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
armedButton(refi, {
label: 'refine',
confirm: 'sends real traffic over every model on this provider -- may cost a buck. click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}/refine`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
acts.appendChild(disc);
acts.appendChild(refi);
// the key control (GM, 2026-11-19): remove re-probes the keyless
// endpoint -- a provider gone public lands working, a locked one
// re-opens the ask (that is the key-replacement path). o/f never
// carries a key, so the control never shows on it.
if (p.hasKey) {
const rmk = /** @type {HTMLButtonElement} */ (el('button', null, 'remove key'));
armedButton(rmk, {
label: 'remove key',
confirm: 'the key leaves the config and the endpoint is probed again -- click again',
fire: async () => {
try {
const res = await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'DELETE', body: {} });
if (res.probe && res.probe !== 'ok') banner(res.detail ?? 'the endpoint failed the keyless probe');
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
acts.appendChild(rmk);
}
card.appendChild(acts);
// the ask (GM, 2026-11-19): a provider whose last probe met an auth
// refusal opens the key path -- the token is checked on reception,
// saved on success, asked again on the next refusal
if (p.probe?.outcome === 'auth' && p.slug !== 'opencode/free') {
const ask = el('div', 'admin-row');
const lab = el('label', 'field', 'API key ');
const key = /** @type {HTMLInputElement} */ (el('input'));
key.type = 'password';
key.autocomplete = 'off';
lab.appendChild(key);
const send = el('button', null, 'send key');
send.addEventListener('click', async () => {
if (!key.value.trim()) { banner('enter the key first'); return; }
try {
await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'POST', body: { apiKey: key.value.trim() } });
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
dropModelCache();
render();
});
ask.appendChild(lab);
ask.appendChild(send);
card.appendChild(ask);
}
// the refine meter: the bar moves only on real step completions,
// the label names the call running now, and the lines are the
// receipt -- they survive the job, so a landed pass keeps its
// verdicts and a rejected one keeps its post-mortem
if (p.job?.steps) {
const j = p.job;
const st = j.steps ?? { total: 0, done: 0, label: '' };
meter.hidden = false;
$('refine-count').textContent = `${st.done}/${st.total} \u00b7 ${j.state}`;
$('refine-label').textContent = j.state === 'running'
const meter = el('div', 'refine-progress');
const top = el('div', 'refine-topline');
top.appendChild(el('span', 'refine-count', `${st.done}/${st.total} \u00b7 ${j.state}`));
top.appendChild(el('span', 'refine-label hint', j.state === 'running'
? `${st.label}${st.chars != null ? ` \u00b7 ${st.chars} chars` : ''}`
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label);
/** @type {HTMLDivElement} */ ($('refine-fill')).style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
linesBox.textContent = '';
for (const l of j.lines ?? []) linesBox.appendChild(el('div', 'refine-line', l));
} else {
meter.hidden = true;
linesBox.textContent = '';
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label)));
const bar = el('div', 'refine-bar');
const fill = el('div', 'refine-fill');
fill.style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
bar.appendChild(fill);
const lines = el('div', 'refine-lines');
for (const l of j.lines ?? []) lines.appendChild(el('div', 'refine-line', l));
meter.appendChild(top);
meter.appendChild(bar);
card.appendChild(meter);
card.appendChild(lines);
}
const list = $('models-list');
list.textContent = '';
for (const m of reg.models) {
// the selection: the provider's default pair, also the refine
// curator. The curator's recommendation sits beside it -- intel
// only, applied by the op's click (never auto-landed)
if (p.models.length) {
const sel = el('div', 'admin-row');
const selLab = el('label', 'field', 'default ');
const mod = /** @type {HTMLSelectElement} */ (el('select'));
const eff = /** @type {HTMLSelectElement} */ (el('select'));
/** @param {HTMLSelectElement} s @param {string} v @param {string} label */
const mk = (s, v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
s.appendChild(o);
};
mk(mod, '', '(none)');
for (const m of [...p.models].filter((x) => x.inference !== false).sort((a, b) => (a.id < b.id ? -1 : 1))) mk(mod, m.id, m.id);
mod.value = p.default?.model ?? '';
mk(eff, '', '(level)');
for (const lv of EFFORT_LEVELS) mk(eff, lv, lv);
eff.value = p.default?.effort ?? '';
const save = el('button', null, 'set default');
save.addEventListener('click', async () => {
if (!mod.value || !eff.value) { banner('the default is a pair -- pick a model and an effort level'); return; }
try {
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: mod.value, effort: eff.value } });
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
selLab.appendChild(mod);
selLab.appendChild(eff);
sel.appendChild(selLab);
sel.appendChild(save);
card.appendChild(sel);
if (p.recommendation && (p.recommendation.model !== p.default?.model || p.recommendation.effort !== p.default?.effort)) {
const rec = el('div', 'admin-row');
rec.appendChild(el('span', 'grow', `the curator recommends ${p.recommendation.model} at ${p.recommendation.effort}`));
const apply = el('button', null, 'apply');
apply.addEventListener('click', async () => {
try {
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: p.recommendation?.model, effort: p.recommendation?.effort } });
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
rec.appendChild(apply);
card.appendChild(rec);
}
}
// the model list
for (const m of p.models) {
const row = el('div', 'admin-row');
const facts = [
m.id,
@@ -172,14 +330,28 @@ function renderModelsAdmin(reg, seq) {
].filter(Boolean).join(' \u00b7 ');
row.appendChild(el('span', 'grow', facts));
if (m.description) row.appendChild(el('span', 'hint', m.description));
list.appendChild(row);
card.appendChild(row);
}
if (running && seq === state.seq) {
return card;
}
/** @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {number} seq */
function renderProvidersAdmin(reg, seq) {
const list = $('provider-list');
list.textContent = '';
const none = !reg.providers.length;
/** @type {HTMLDivElement} */ ($('providers-banner')).hidden = !none;
if (none) {
$('providers-banner').textContent = 'no providers configured -- add opencode/free (the anonymous fallback) or a custom provider; the server also self-heals this on restart';
}
/** @type {HTMLButtonElement} */ ($('provider-add-of')).disabled = reg.providers.some((p) => p.slug === 'opencode/free');
for (const p of reg.providers) list.appendChild(renderProviderCard(p, seq));
if (reg.providers.some((p) => p.job?.state === 'running') && seq === state.seq) {
// the job follows itself home: poll until it lands, then re-render
setTimeout(async () => {
const r = await api('/models').catch(() => null);
const r = /** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => null));
if (!r || seq !== state.seq || state.view !== 'home') return;
if (r.job?.state === 'running') renderModelsAdmin(r, seq);
if (r.providers.some((p) => p.job?.state === 'running')) renderProvidersAdmin(r, seq);
else render();
}, 2000);
}
@@ -190,28 +362,60 @@ function fmtStamp(iso) {
return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC` : '?';
}
// discover: the free scrape -- armed because it resets a refined
// registry back to the preliminary list (the curation is re-earned
// by refining again)
armedButton($('models-discover'), {
label: 'discover',
confirm: 'resets the registry to a fresh scrape -- click again',
fire: async () => {
try { await api('/models/discover', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
render();
},
// the add flow (GM, 2026-11-19): the binary choice, and the probe
// decides the key path. o/f is one click; custom opens the inline
// form taking ONLY the endpoint -- a working keyless listing never
// sees a key field. A 401/403 stands the provider broken and opens
// the key field: the key rides the auth route, checked on reception,
// saved on success, asked again on the next refusal. Every other
// failure refuses the add outright (nothing stands, the form stays).
/** @type {?string} */ let authTarget = null; // set when an add landed broken on auth -- the form's next go keys it
function closeAddForm() {
authTarget = null;
/** @type {HTMLFormElement} */ ($('provider-form')).hidden = true;
/** @type {HTMLInputElement} */ ($('provider-slug')).value = '';
/** @type {HTMLInputElement} */ ($('provider-base')).value = '';
/** @type {HTMLInputElement} */ ($('provider-key')).value = '';
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = true;
}
$('provider-add-of').addEventListener('click', async () => {
try { await api('/providers', { method: 'POST', body: { builtin: true } }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
// refine: the inference battery + the curator pass -- real traffic
armedButton($('models-refine'), {
label: 'refine',
confirm: 'sends real traffic over every model -- may cost a buck. click again',
fire: async () => {
try { await api('/models/refine', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
$('provider-add-custom').addEventListener('click', () => { /** @type {HTMLFormElement} */ ($('provider-form')).hidden = false; });
$('provider-add-cancel').addEventListener('click', () => closeAddForm());
$('provider-add-go').addEventListener('click', async () => {
const slug = /** @type {HTMLInputElement} */ ($('provider-slug')).value.trim();
const baseUrl = /** @type {HTMLInputElement} */ ($('provider-base')).value.trim();
const apiKey = /** @type {HTMLInputElement} */ ($('provider-key')).value.trim();
if (authTarget) {
// the provider stands broken -- this go sends the key, not another add
if (!apiKey) { banner('the endpoint wants a key -- enter one or cancel'); return; }
try {
await api(`/providers/${encodeURIComponent(authTarget)}/auth`, { method: 'POST', body: { apiKey } });
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
closeAddForm();
dropModelCache();
render();
},
return;
}
if (!slug || !baseUrl) { banner('slug and baseUrl are both required'); return; }
try {
await api('/providers', { method: 'POST', body: { slug, baseUrl } });
} catch (e) {
if (e.status === 401 || e.status === 403) {
authTarget = slug;
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = false;
banner(e.message);
return;
}
banner(e.message); return; // refused outright (or bad input) -- nothing stands
}
closeAddForm();
dropModelCache();
render();
});
$('new-run-btn').addEventListener('click', () => navigate('/new'));
$('invite-mint').addEventListener('click', async () => {
try {
+1 -1
View File
@@ -244,7 +244,7 @@ async function refreshPlay(id, seq) {
$('models-pane').hidden = false;
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelDefaults, detail.run.params, detail.run.paramDefaults, mlist);
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
// pending ask: the modal re-presents after a refresh -- the owner's
// to answer
+16 -2
View File
@@ -35,6 +35,17 @@ const EDIT_LIST = [
{ name: 'run.json', mode: 'ro', source: 'run' },
];
// per-file authoring hints: the formats the raw editor would otherwise
// ask the author to know by heart -- the save lint names violations,
// the hint teaches the shape up front
/** @type {Record<string, string>} */
const FILE_HINTS = {
'carryover.jsonl':
'one JSON object per line. A turn is {"t": "msg", "m": {"role": "assistant" or "user", "content": "..."}}. '
+ 'Her turn carries the <status> and <agenda> blocks; the sheet rides a GM turn as its "sheet" field, never as a tag. '
+ '@PC, @Package and $VARS expand at start (the authored opening only).',
};
// the editor's working set -- module-local, reset on every enter
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
@@ -42,7 +53,7 @@ const EDIT_LIST = [
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
/** @type {Record<string, string>} */ let repoPrompts = {};
const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' });
const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' });
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
@@ -105,7 +116,7 @@ export async function enter(id, seq) {
// models: per-run overrides, selected from the registry
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelDefaults, detail.run.params, detail.run.paramDefaults, mlist);
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
const nav = $('setup-files');
nav.textContent = '';
@@ -180,6 +191,9 @@ function selectFile(f) {
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
const hint = FILE_HINTS[f] ?? '';
$('edit-hint').textContent = hint;
$('edit-hint').hidden = !hint;
renderHighlight();
markNav();
}
+159 -104
View File
@@ -6,16 +6,16 @@
// - paneEditor: the status/agenda pattern -- a body line, an edit
// button, an inline editor; the edit stages, the send rides it
// with the turn; the section shell stays in index.html
// - modelsBox: the per-run player/housekeeper selects over the
// registry plus the sampling knobs (knobs.mjs owns the knob row
// and its definitions table); setup and the play aside each carry
// - modelsBox: the per-run spec picks -- {provider, model, effort}
// per role, no unset effort, no stored params (the <mind> verb is
// the only sampling source); setup and the play aside each carry
// one
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { knobsBox } from './knobs.mjs';
import { EFFORT_LEVELS } from './knobs.mjs';
// two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
@@ -199,15 +199,22 @@ export function sheetEditor(section, body) {
// the model registry, fetched once per session -- the selectors read
// the saved registry, never the live provider (discovery is the op's
// manual act; a listing fetch every render would hammer the endpoint
// for a list that rarely changes)
// act; a listing fetch every render would hammer the endpoint for a
// list that rarely changes)
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
export async function modelList() {
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ phase: 'none', discovered: null, refined: null, curator: null, defaults: {}, models: [], job: null })));
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ providers: [] })));
return cachedRegistry;
}
/** Invalidate the cached registry -- provider state changed (the op
* added, removed, discovered, or refined), the next modelList
* refetches. */
export function dropModelCache() {
cachedRegistry = null;
}
// a context ceiling as the short human form: 1048576 -> "1M",
// 524288 -> "512K". Null when the provider stated nothing.
/** @param {?number} tokens @returns {?string} */
@@ -216,106 +223,107 @@ export function fmtCeiling(tokens) {
return tokens >= 1048576 ? `${Math.round(tokens / 1048576)}M` : `${Math.round(tokens / 1024)}K`;
}
// A select's "" value means "deployment default"; a current override
// missing from the registry stays selectable, so a stale pick never
// silently rewrites itself. One plain list, sorted by id (GM,
// 2026-11-16: the family grouping left the user guessing what a
// family name means, and the curator's tier labels only made sense
// inside their groups -- the id is the self-describing name). The
// input ceiling rides along -- the user picks against the contwin,
// so the context limit belongs in the open.
/** @param {HTMLSelectElement} sel @param {?string} current @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {?string} [def] */
function fillSelect(sel, current, reg, def) {
sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` -- ${def}` : ' (unset)'}`);
const usableModels = reg.models.filter((m) => m.inference !== false && (m.roles?.player ?? true));
const extras = current && !usableModels.some((m) => m.id === current) ? [current] : [];
for (const m of [...usableModels].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
const ceil = fmtCeiling(m.input);
mk(m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
}
for (const x of extras) mk(x, `${x} (not in the registry)`);
sel.value = current ?? '';
}
// the models box: player/housekeeper selects over the registry, the
// sampling knobs per role (one shared hint bar under both rows), and
// one save. The mount keeps its id -- the CSS panels it. The knob
// rows rebuild when the model select changes: the effort knob's
// default is measured per model, so switching the model switches the
// honest default.
// the model picks: per role a full spec {provider, model, effort} --
// there is no unset effort (GM, 2026-11-18), and the params layer is
// the <mind> verb's alone (per-turn, nothing stored). The health
// line under the rows is the invalidation surface: a pick the server
// no longer carries names what died and stays visible until the GM
// sets it up again. A housekeeper with no pick inherits (the player
// spec's provider default) -- the '' provider option says so.
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
hField.appendChild(houseSel);
root.appendChild(pField);
root.appendChild(hField);
const knobHint = el('div', 'knob-hint'); // one bar, both roles
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
root.appendChild(playerKnobs.wrap);
root.appendChild(houseKnobs.wrap);
root.appendChild(knobHint);
// the latest fill's inputs -- the select-change refresh rebuilds
// the knob rows against them (the effort context follows the
// newly-picked model)
/** @type {?{ params: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, paramDefaults: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, reg: import('./shapes.mjs').ModelsRegistryResponse }} */ let last = null;
// the effort knob's context: the currently-selected model's
// measured ladder (null when the registry has none for it)
/** @param {'player'|'housekeeper'} role @param {import('./shapes.mjs').ModelsRegistryResponse} reg @returns {?{ measured: Record<string, number>, fallback: ?string }} */
const effortOf = (role, reg) => {
const id = (role === 'player' ? playerSel.value : houseSel.value)
|| reg.defaults?.[role] || null;
const m = id ? reg.models.find((x) => x.id === id) : null;
return m?.efforts ? { measured: m.efforts, fallback: m.effortDefault ?? null } : null;
/** @typedef {{ prov: HTMLSelectElement, mod: HTMLSelectElement, eff: HTMLSelectElement }} Row */
/** @param {string} role @returns {Row} */
const mkRow = (role) => {
const prov = /** @type {HTMLSelectElement} */ (el('select'));
const mod = /** @type {HTMLSelectElement} */ (el('select'));
const eff = /** @type {HTMLSelectElement} */ (el('select'));
const field = el('label', 'field', `${role} `);
field.appendChild(prov);
field.appendChild(mod);
field.appendChild(eff);
root.appendChild(field);
return { prov, mod, eff };
};
/** rebuild both knob rows against the current selects and the
* latest fill (fill and select-change both land here) */
function rebuildKnobs() {
if (!last) return;
const pk = knobsBox('player', last.params?.player ?? undefined, last.paramDefaults?.player ?? undefined, knobHint, effortOf('player', last.reg));
const hk = knobsBox('housekeeper', last.params?.housekeeper ?? undefined, last.paramDefaults?.housekeeper ?? undefined, knobHint, effortOf('housekeeper', last.reg));
playerKnobs.wrap.replaceWith(pk.wrap);
houseKnobs.wrap.replaceWith(hk.wrap);
playerKnobs = pk;
houseKnobs = hk;
}
playerSel.addEventListener('change', rebuildKnobs);
houseSel.addEventListener('change', rebuildKnobs);
if (!root.querySelector('.registry-hint')) {
const hint = el('div', 'hint registry-hint', '');
root.appendChild(hint);
}
const player = mkRow('player');
const house = mkRow('housekeeper');
const healthLine = el('div', 'hint');
root.appendChild(healthLine);
const hint = el('div', 'hint');
root.appendChild(hint);
const saveBtn = el('button', null, 'save models');
const saveState = el('span', 'save-state');
const actions = el('div', 'form-actions');
actions.appendChild(saveBtn);
actions.appendChild(saveState);
root.appendChild(actions);
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let reg = null;
/** @param {HTMLSelectElement} sel @param {string} v @param {string} label */
const opt = (sel, v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
// one provider's usable player models; a stale pick stays selectable
// (a stale pick never silently rewrites itself)
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} current */
const fillModels = (sel, slug, current) => {
const section = reg?.providers.find((p) => p.slug === slug) ?? null;
sel.textContent = '';
opt(sel, '', '(no model picked)');
const usable = (section?.models ?? []).filter((m) => m.inference !== false && (m.roles?.player ?? true));
const sorted = [...usable].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (const m of sorted) {
const ceil = fmtCeiling(m.input);
opt(sel, m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
}
if (current && !sorted.some((m) => m.id === current)) opt(sel, current, `${current} (not in this provider's registry)`);
sel.value = current ?? '';
};
// the effort select: the ladder, the '' option naming the measured
// default when the registry carries one
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} modelId @param {?string} current */
const fillEffort = (sel, slug, modelId, current) => {
const m = reg?.providers.find((p) => p.slug === slug)?.models.find((x) => x.id === modelId) ?? null;
sel.textContent = '';
opt(sel, '', m?.effortDefault ? `(measured default: ${m.effortDefault})` : '(pick a level)');
for (const lv of EFFORT_LEVELS) opt(sel, lv, lv);
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
};
// a provider or model change re-derives the dependent options (the
// effort choice survives a model switch -- it is the pick's, not
// the model's)
for (const row of [player, house]) {
row.prov.addEventListener('change', () => {
fillModels(row.mod, row.prov.value, null);
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
});
row.mod.addEventListener('change', () => {
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
});
}
saveBtn.addEventListener('click', async () => {
try {
// the knob read throws on an empty override -- same banner, nothing sent
const params = { player: playerKnobs.read(), housekeeper: houseKnobs.read() };
/** @param {Row} row @param {string} role @returns {?{ provider: string, model: string, effort: string }} */
const specOf = (row, role) => {
if (!row.prov.value) return null;
if (!row.mod.value) throw new Error(`${role}: pick a model (or clear the provider)`);
if (!row.eff.value) throw new Error(`${role}: pick an effort level -- there is no unset effort`);
return { provider: row.prov.value, model: row.mod.value, effort: row.eff.value };
};
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: {
player: playerSel.value || null,
housekeeper: houseSel.value || null,
params,
},
body: { player: specOf(player, 'player'), housekeeper: specOf(house, 'housekeeper') },
});
saveState.textContent = 'saved';
} catch (e) {
@@ -323,21 +331,68 @@ export function modelsBox(mount, { title }) {
saveState.textContent = 'not saved';
}
});
return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} params @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} paramDefaults @param {import('./shapes.mjs').ModelsRegistryResponse} reg */
fill(models, defaults, params, paramDefaults, reg) {
fillSelect(playerSel, models?.player ?? null, reg, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, reg, defaults?.housekeeper);
last = { params: params ?? null, paramDefaults: paramDefaults ?? null, reg };
rebuildKnobs();
const hint = root.querySelector('.registry-hint');
if (hint) {
hint.textContent = reg.phase === 'none'
? 'no models discovered -- the op runs discovery from the admin block on home'
: reg.phase === 'preliminary'
? 'preliminary registry -- unrefined: the op can run refine to verify and label the models'
: '';
/** @param {{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }} models run.json verbatim (the spec picks)
* @param {?{ player?: ?import('./shapes.mjs').RoleHealth, housekeeper?: ?import('./shapes.mjs').RoleHealth }} modelState the resolved truth
* @param {?{ slug: string, default: ?{ model: string, effort: string } }[]} providerDefaults
* @param {import('./shapes.mjs').ModelsRegistryResponse} theReg */
fill(models, modelState, providerDefaults, theReg) {
reg = theReg;
/** @param {Row} row @param {'player'|'housekeeper'} role */
const fillRole = (row, role) => {
// the prefill is the run's OWN stored pick only -- an
// inherited housekeeper stays '' (saving an explicit pick is
// a deliberate act; the health line states what inherits)
const raw = models?.[role];
const spec = raw && typeof raw === 'object' && !Array.isArray(raw)
? /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw) : null;
const pick = spec && typeof spec.provider === 'string' && typeof spec.model === 'string' && typeof spec.effort === 'string'
? { provider: spec.provider, model: spec.model, effort: spec.effort } : null;
row.prov.textContent = '';
opt(row.prov, '', role === 'housekeeper' ? '(inherit -- the player provider\'s default)' : '(no provider picked)');
const slugs = (reg?.providers ?? []).map((p) => p.slug);
if (pick && !slugs.includes(pick.provider)) opt(row.prov, pick.provider, `${pick.provider} (no longer configured)`);
for (const s of slugs) opt(row.prov, s, s);
row.prov.value = pick?.provider ?? '';
if (pick) {
fillModels(row.mod, pick.provider, pick.model);
fillEffort(row.eff, pick.provider, pick.model, pick.effort);
return;
}
// no stored pick: the player pre-selects the first provider's
// default (the create flow lands an explicit pick); the
// housekeeper inherits, so it stays ''
if (role === 'player' && slugs.length) {
const withDef = providerDefaults?.find((x) => x.default && slugs.includes(x.slug)) ?? null;
const slug = withDef?.slug ?? slugs[0];
row.prov.value = slug;
fillModels(row.mod, slug, withDef?.default?.model ?? null);
fillEffort(row.eff, slug, withDef?.default?.model ?? null, withDef?.default?.effort ?? null);
} else {
fillModels(row.mod, row.prov.value, null);
fillEffort(row.eff, row.prov.value, null, null);
}
};
fillRole(player, 'player');
fillRole(house, 'housekeeper');
// the health line: the invalidation notes and the inheritance
const notes = [];
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
const st = modelState?.[role];
if (!st) continue;
if (st.ok && st.inherited && st.spec) notes.push(`${role}: inherits ${st.spec.provider}'s default (${st.spec.model} at ${st.spec.effort})`);
if (!st.ok && st.note) notes.push(`${role}: ${st.note}`);
}
healthLine.textContent = notes.join(' \u00b7 ');
const providers = reg?.providers ?? [];
hint.textContent = !providers.length
? 'no providers configured -- the op fixes this from the admin block on home'
: providers.every((p) => p.phase === 'none')
? 'providers configured but nothing discovered -- the op discovers from the admin block on home'
: providers.some((p) => p.phase === 'preliminary')
? 'a preliminary registry is unrefined: the op can run refine to verify and label its models'
: '';
saveState.textContent = '';
},
};