Files
tiny-worlds/web/knobs.mjs
T
mute eebc1993dd the night rounds: the GM-input rework and the reasoning-effort knob -- the workbench renders no faces: the composer overlay and the transcript share colour-only tokens (.narration dim, .emph accent), source verbatim, asterisks tinted and kept on screen, so the input's caret can never drift (the old overlay's real bold/italic shifted advance widths -- keeping every character preserved count, not width; the scrollbar-gutter match killed the second drift source); the story view carries its OWN renderer (view-story storyBody/storySpans) -- the book keeps real bold/italic with the asterisks spent, narration italic via #story-scoped CSS, one rule for the tool and typography for the deliverable, deliberately separate; the composer is turn-shaped: rows=6 floor, field-sizing: content grows it with the turn (the thing the GM remembered Firefox doing -- it was never in use), max-height 50vh caps with internal scroll, the footer moved under the transcript's column only so the input's width is the pane's; the transcript's stick-to-bottom was DEAD CODE all along (#transcript has no height or overflow -- main is the scroller, the scrollTop assignments were no-ops in every browser): stickBottom scrolls main and re-asserts next frame (Firefox's scroll anchoring can reclaim a same-tick scroll around a content wipe), main carries overflow-anchor: none; the prose pane drops its machinery by ruling: the status/agenda chips and the retired delta tags strip (the panes carry the derived state), the reminder card never renders (it is the same every turn -- the raw tab keeps every copy), and the status/agenda note receipts (the old delta applies and the whole-list sets alike) skip the prose walk while the raw keeps them; the model dropdown collapsed to one plain list of ids sorted, ceilings riding along (the family grouping left the user guessing what a family name means, and the curator's tier labels only made sense inside their groups); and the reasoning-effort round: the battery probes the ladder (probeEfforts -- each of none/minimal/low/medium/high/xhigh/max measured for mean thinking, two samples, efforts recorded per model, effortDefault the argmax mean over minimal..max, 'none' never a candidate -- it is the off switch; null when the model shows no thinking), the knob is first-class and the GM's alone (GM, 2026-11-16: hidden from the model, not her call -- never in the mind verb, never in the <model> display block, and renderView's via-derived block filters it too, both surfaces; it rides the via record for the raw surfaces), its unset state SENDS the measured max-mean default (the one knob with an honestly nameable default -- the registry measured it; layers run override > deployment > registry per-model, explicit null clears to nothing), the first non-numeric knob (RoleParams carries the string, the /model route validates against the ladder, the knob row a select whose unset label names what rides and rebuilds on model-select change); the GLM ladder verified live by hand before the build (low suppresses to a third of baseline, max elevates about double, the whole ladder accepted on both families without 400s, and reasoning_effort 'none' doubles as a standardized thinking-off switch); the model dropdown, the composer, and the knob UX browser-proven with zero console errors (the pass caught the unreachable-helpers bug: code after a factory's return never runs, a hoisted function referencing the uninitialized const throws silently mid-fill and stale rows render); smoke ALL PASS with the effort battery (the canned mock ladders, the default riding a bare turn's via, the override riding the next turn, the bogus-level 400, the null clear, no reasoning_effort in any <model> block) + restart + reminder + repo checks green, typecheck green on both programs; ROADMAP gains the distant extension point (n-choice inference composed by a turn-editor agent) and the operator's queue moved there from QUESTIONS by the GM; HANDOFF prepared as the handoff (the typing-round bullet trimmed into the rounds list, the server line now truthful -- the debug server runs, the registry bullet carries the six-knob state and the pending-effort refine)
2026-11-16 23:52:58 +00:00

212 lines
10 KiB
JavaScript

// web/knobs.mjs -- the sampling knobs: the definitions table and the
// per-role knob row.
//
// 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.
//
// 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 */
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'];
/** 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> }}
*/
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 };
}
// 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 };
}