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:
@@ -27,6 +27,16 @@ memory the agent owes itself across sessions.
|
|||||||
the system, flag ripples, name what works and why -- the verdict on
|
the system, flag ripples, name what works and why -- the verdict on
|
||||||
creative content is theirs. GM-private files (gm.md) are never edited
|
creative content is theirs. GM-private files (gm.md) are never edited
|
||||||
and only flagged.
|
and only flagged.
|
||||||
|
- **No legacy (GM, 2026-11-18):** when a shape changes, change it,
|
||||||
|
then fix what's broken in a one-time manual migration -- no
|
||||||
|
permanent tolerance paths in the code, logs included (GM, same
|
||||||
|
day: mechanical drift in logs that doesn't change meaning is fine
|
||||||
|
-- the log serves a purpose, and the purpose isn't broken because
|
||||||
|
the server got an update; it is not court evidence). The one
|
||||||
|
boundary is meaning, not bytes: a migration that would change
|
||||||
|
what a story says is a GM decision; shape-preserving rewrites
|
||||||
|
(envelope fields, event spellings, machinery records -- never
|
||||||
|
message content) are mechanical and mine to do.
|
||||||
- Standing agreements (folded from the handoff's working-agreements
|
- Standing agreements (folded from the handoff's working-agreements
|
||||||
section when it slimmed, 2026-11-15): character and world work is
|
section when it slimmed, 2026-11-15): character and world work is
|
||||||
done together, unhurried ("we'll get there together"); the GM runs
|
done together, unhurried ("we'll get there together"); the GM runs
|
||||||
@@ -154,6 +164,89 @@ memory the agent owes itself across sessions.
|
|||||||
|
|
||||||
## State pointers
|
## State pointers
|
||||||
|
|
||||||
|
- **The provider-flow round is BUILT (2026-11-19): discovery is the
|
||||||
|
probe, the key path opens only on a 401/403, no automatic
|
||||||
|
retries anywhere, and failures never cache.** The add takes only
|
||||||
|
{slug, baseUrl} or {builtin} (apiKey in the body 400s); a
|
||||||
|
working keyless endpoint never sees a key field; an auth refusal
|
||||||
|
stands the provider broken with the probe record on the entity
|
||||||
|
(outcome ok/auth/error, only the explicit acts move it -- usage
|
||||||
|
errors are transient, the op's to fix, nothing auto-flips); the
|
||||||
|
auth route is probe-then-save (a refused candidate never reaches
|
||||||
|
the config, the ask repeats); every other discovery failure
|
||||||
|
refuses the add with rollback. The remove-key control clears and
|
||||||
|
re-probes (the replacement path: remove, then the re-opened
|
||||||
|
ask). o/f never asks, any state. The curator's auto-retry is
|
||||||
|
deleted (the universal rule: every inference call is manual with
|
||||||
|
a manual retry; the fallback is the designed outcome). The
|
||||||
|
adjudication cache skips inference:false entries -- every refine
|
||||||
|
re-probes its failures, so a transient battery error never pins
|
||||||
|
a verdict (gev is a 400, not a 200-failure; it re-probes cheap
|
||||||
|
forever, which self-heals if the backend ever learns tools).
|
||||||
|
En-route fix the smoke earned: the create route validated
|
||||||
|
body.spec AFTER the clerk built the run dir -- refused specs
|
||||||
|
left orphan runs (restart-check's exact count caught it);
|
||||||
|
validate first, nothing lands on refusal. Verified: typecheck
|
||||||
|
both programs, smoke ALL PASS (+27), restart + reminder green,
|
||||||
|
browser pass on the whole UI machine (mock+debug coexist for
|
||||||
|
drivable UI tests), check-repo clean. Lesson renewed hard: the
|
||||||
|
edit tool's comment-block transcriptions failed three times this
|
||||||
|
round -- byte-dump with node + JSON.stringify BEFORE the first
|
||||||
|
attempt on any multi-line prose edit, never after it fails.
|
||||||
|
|
||||||
|
- **The provider round is BUILT (2026-11-18, the
|
||||||
|
batteries-included arc): providers are entities, config is
|
||||||
|
server-written state (state/config.json), a fresh clone boots
|
||||||
|
playable (the o/f singleton auto-added and discovered on the
|
||||||
|
empty list). Every request resolves a full spec {provider,
|
||||||
|
model, effort} -- no unset effort, the per-run params layer
|
||||||
|
retired (the mind verb is the only sampling source). Registry:
|
||||||
|
per-provider sections in state/models.json; refine caches its
|
||||||
|
adjudications in state/refine-cache.json keyed by the double
|
||||||
|
spec tuple. Run picks are invalidatable (the run blocks with a
|
||||||
|
note until re-picked); the housekeeper inherits the player
|
||||||
|
provider's default (#16 closed). The dev machine migrated:
|
||||||
|
provider 'llm-exan-tech' (from server.json's import), 13
|
||||||
|
measured models preserved, default glm-5.3 at max. Clients
|
||||||
|
percent-encode provider slugs in paths -- the slug may carry a
|
||||||
|
slash (opencode/free) and the router splits before decoding.
|
||||||
|
Uncommitted, on top of the superseded vector round.
|
||||||
|
|
||||||
|
- **The provider-vector round is BUILT (2026-11-18, GM ruling "we
|
||||||
|
can do it right away"): server.json's endpoint became `endpoints`,
|
||||||
|
a list of (baseUrl, auth) pairs, auth optional.** The scaffold's
|
||||||
|
prerequisite -- the free keyless default and the op's real key
|
||||||
|
coexist as entries, they do not replace each other. As built:
|
||||||
|
one provider client per pair (main.mjs builds the map, config
|
||||||
|
order = priority order); discovery scrapes EVERY configured
|
||||||
|
endpoint and tags each model with its base (first-listed wins an
|
||||||
|
id collision -- the registry is keyed by id, the tag routes);
|
||||||
|
every call site routes through providerFor (provider.mjs: map
|
||||||
|
walk + a loud 409 when the registry knows a model whose endpoint
|
||||||
|
left the config); the registry file's `endpoint` became
|
||||||
|
`endpoints: string[]` with a one-time normalize-on-open (the
|
||||||
|
singular-era file migrates in memory, models inherit the one
|
||||||
|
base -- the measured registry survives unregenerated). The mock
|
||||||
|
runs the same steps over TWO synthetic endpoints (mock-a/mock-b)
|
||||||
|
so the merge and tagging are smoke-proven. Config files: the
|
||||||
|
example carries the vector with the opencode free endpoint first
|
||||||
|
(keyless) -- the pending GM call is whether the free default
|
||||||
|
ships in the scaffold or stays example-only; the dev server.json
|
||||||
|
hand-migrated to the vector. Verified: typecheck green both
|
||||||
|
programs, smoke ALL PASS (+the vector assertion: two endpoints,
|
||||||
|
every model tagged, mock-cheap on the second base), restart +
|
||||||
|
reminder checks green, and the live debug server on the REAL
|
||||||
|
registry (13 models, singular-era on disk) normalizing and
|
||||||
|
routing glm-5.3 to its base. Standing lesson renewed: template
|
||||||
|
literals and backticks inside PowerShell-wrapped node -e strings
|
||||||
|
get EATEN -- multi-line patch scripts go through a temp .cjs
|
||||||
|
file written by the write tool, never inline. EXTENDED (the
|
||||||
|
provider round, same day): a node -e REPLACE whose replacement
|
||||||
|
string contained ${...} ran inside a DOUBLE-quoted PowerShell
|
||||||
|
string -- PowerShell expanded the ${} to empty, and six template
|
||||||
|
holes landed in view-home.mjs (dead provider paths, caught in
|
||||||
|
the browser pass). Any generated replacement containing ${ or
|
||||||
|
backticks goes through a temp script, no exceptions.
|
||||||
- **The deployment box exists and is oriented (2026-11-18): a burble
|
- **The deployment box exists and is oriented (2026-11-18): a burble
|
||||||
VM, bare but ready.** The connection specifics (address, port,
|
VM, bare but ready.** The connection specifics (address, port,
|
||||||
key) live in `.ssh/box.md` -- gitignored on purpose, this note
|
key) live in `.ssh/box.md` -- gitignored on purpose, this note
|
||||||
@@ -643,7 +736,14 @@ memory the agent owes itself across sessions.
|
|||||||
proof mid-action: waiting on a word that lives on a BUTTON label
|
proof mid-action: waiting on a word that lives on a BUTTON label
|
||||||
("rewind") matches instantly while the send is still in flight and
|
("rewind") matches instantly while the send is still in flight and
|
||||||
the mid-flight DOM looks like failure -- probe the settled state
|
the mid-flight DOM looks like failure -- probe the settled state
|
||||||
via evaluate on a later tick instead. Added
|
via evaluate on a later tick instead. Added 2026-11-18 (provider
|
||||||
|
round): the a11y snapshot does not show the admin block's
|
||||||
|
dynamically-built provider cards at all (the tree ends at the
|
||||||
|
static buttons) -- probe such surfaces by DOM (evaluate), never
|
||||||
|
read a clean snapshot as an empty page; evaluate has no timers
|
||||||
|
(setTimeout is undefined in its sandbox) -- wait on settled text
|
||||||
|
instead; and the armed buttons' 5s confirm window expires between
|
||||||
|
evaluate calls -- arm and fire within one script. Added
|
||||||
2026-11-14 (multiuser round): the a11y snapshot races async renders
|
2026-11-14 (multiuser round): the a11y snapshot races async renders
|
||||||
-- waiting for static skeleton text ("RUNS", the aside headings)
|
-- waiting for static skeleton text ("RUNS", the aside headings)
|
||||||
snapshots BEFORE the fetches land and looks like a rendering bug;
|
snapshots BEFORE the fetches land and looks like a rendering bug;
|
||||||
@@ -845,10 +945,10 @@ memory the agent owes itself across sessions.
|
|||||||
into the server loop.
|
into the server loop.
|
||||||
- Open decisions live in QUESTIONS.md -- read it first; the resolved
|
- Open decisions live in QUESTIONS.md -- read it first; the resolved
|
||||||
record is DECISIONS.md (the old queue, kept by number). QUESTIONS is
|
record is DECISIONS.md (the old queue, kept by number). QUESTIONS is
|
||||||
open items only now (2026-11-15 split). Remaining: #16 (which model
|
open items only now (2026-11-15 split). Remaining: #19c only (seed
|
||||||
the housekeeper defaults to), #19c
|
voice, GM may revisit -- non-blocking). #16 closed with the provider
|
||||||
(seed voice, GM may revisit -- non-blocking), and the turn-surgery
|
round (2026-11-18: the housekeeper inherits the player spec's
|
||||||
build details.
|
provider default), the turn-surgery details with the rewind round.
|
||||||
- The tree is usually dirty by design; git status is not an alarm.
|
- The tree is usually dirty by design; git status is not an alarm.
|
||||||
- Edit-tool lesson repeated (2026-11-13): nested-list indentation in
|
- Edit-tool lesson repeated (2026-11-13): nested-list indentation in
|
||||||
HANDOFF failed twice from memory -- always transcribe oldString from a
|
HANDOFF failed twice from memory -- always transcribe oldString from a
|
||||||
|
|||||||
@@ -423,3 +423,16 @@ lost to the character's memory. Taken as a build default after two
|
|||||||
unanswered rounds: window-open refuses, names the unhousekept session,
|
unanswered rounds: window-open refuses, names the unhousekept session,
|
||||||
and accepts an explicit override for the deliberate skip. One line to
|
and accepts an explicit override for the deliberate skip. One line to
|
||||||
flip if the GM rules otherwise.
|
flip if the GM rules otherwise.
|
||||||
|
|
||||||
|
### 16. Housekeeping model configuration -- RESOLVED (2026-11-18)
|
||||||
|
The mechanism was settled early (2026-11-13, wired 2026-11-14): the
|
||||||
|
config names the endpoint and the default models, the registry lists
|
||||||
|
what is selectable, a run overrides its own models. The open half --
|
||||||
|
which model the housekeeping DEFAULT points at -- resolves with the
|
||||||
|
provider round (GM, 2026-11-18): defaults are per provider now, the
|
||||||
|
op's selected {model, effort} pair, and the housekeeper has no
|
||||||
|
separate default -- a run without its own housekeeper pick inherits
|
||||||
|
the player spec's provider default. Cheap-model housekeeping (steal
|
||||||
|
#8's original ask) stays available the way it always was: set the
|
||||||
|
run's housekeeper pick to the cheap model. What no longer exists is
|
||||||
|
a deployment-wide default below the per-run picks.
|
||||||
|
|||||||
+30
-2
@@ -30,8 +30,36 @@ WORDS.
|
|||||||
|
|
||||||
## The story state
|
## The story state
|
||||||
|
|
||||||
- **the deployment** -- one clone plus `server.json`, `state/`, and
|
n
|
||||||
`runs/` (all gitignored): the unit of sharing. Invited users need
|
e
|
||||||
|
i
|
||||||
|
t
|
||||||
|
h
|
||||||
|
e
|
||||||
|
r
|
||||||
|
|
||||||
|
t
|
||||||
|
h
|
||||||
|
e
|
||||||
|
|
||||||
|
k
|
||||||
|
e
|
||||||
|
y
|
||||||
|
|
||||||
|
n
|
||||||
|
o
|
||||||
|
r
|
||||||
|
|
||||||
|
t
|
||||||
|
h
|
||||||
|
e
|
||||||
|
|
||||||
|
c
|
||||||
|
l
|
||||||
|
o
|
||||||
|
n
|
||||||
|
e
|
||||||
|
.
|
||||||
neither the key nor a clone.
|
neither the key nor a clone.
|
||||||
- **the package** -- a preset: authored content only, no state.
|
- **the package** -- a preset: authored content only, no state.
|
||||||
System packages ship with the repo; user packages are saved runs,
|
System packages ship with the repo; user packages are saved runs,
|
||||||
|
|||||||
+257
-30
@@ -9,7 +9,169 @@ file is the "where did we leave off" map.
|
|||||||
|
|
||||||
## Where we are
|
## Where we are
|
||||||
|
|
||||||
- **Everything is built and committed through `53f992a` (2026-11-18).**
|
- **The provider-flow round is BUILT and verified (2026-11-19,
|
||||||
|
GM-designed in conversation): discovery is the probe, the key
|
||||||
|
path opens only on refusal, and the retry story is settled
|
||||||
|
universal.** The state machine as ruled: 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 runs
|
||||||
|
discovery as its probe. A working keyless listing never sees a
|
||||||
|
key field. A 401/403 stands the provider broken (the card
|
||||||
|
carries the probe record, the ask opens -- an inline password
|
||||||
|
input on the card and in the add form). The auth route is
|
||||||
|
probe-then-save: the candidate key is checked on reception, saved
|
||||||
|
only on success -- a still-refused key never reaches the config,
|
||||||
|
the previous state returns, the ask repeats (mock-lock proves
|
||||||
|
it). Every OTHER 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 -- found and fixed).
|
||||||
|
The remove-key control (custom providers only, armed): clear,
|
||||||
|
auto re-discover -- a provider gone public lands working keyless,
|
||||||
|
a locked one re-opens the ask, which is the key-replacement path
|
||||||
|
(remove, then key). o/f never asks in any state: its auth
|
||||||
|
failures are upstream breakage to show, never a prompt (the card
|
||||||
|
says so; the auth routes 403 it both ways). The probe record
|
||||||
|
(outcome ok/auth/error + detail + at) lives on the entity and
|
||||||
|
ONLY the explicit acts move it -- add, key, remove-key, discover
|
||||||
|
(and the boot self-heal); usage errors are transient and the
|
||||||
|
op's to fix eventually, nothing in the runtime flips provider
|
||||||
|
state (GM: marking a provider broken mid-play is disruptive; the
|
||||||
|
failed turn already lands its req event). The universal retry
|
||||||
|
rule (GM, 2026-11-19): 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 is the designed outcome, not
|
||||||
|
a degraded one. And the cache rule (GM, 2026-11-19): failures
|
||||||
|
NEVER cache -- a failure is the absence of a measurement, not a
|
||||||
|
measurement; every refine re-probes the models that failed the
|
||||||
|
last one (the receipt says so), so a transient error during a
|
||||||
|
battery can never pin a false verdict -- gev's 400s cost one
|
||||||
|
cheap probe per refine and self-heal the day the backend learns
|
||||||
|
tools. The gev finding that shaped it: the GM's example of a
|
||||||
|
200-failure is actually a 400, and the bright 200/non-200 line
|
||||||
|
died for the simpler rule. En-route fix the smoke earned: the
|
||||||
|
create route built the run dir BEFORE validating body.spec -- a
|
||||||
|
refused spec left an orphan run (the sixth run in
|
||||||
|
restart-check's count); the spec validates first now, nothing
|
||||||
|
lands on refusal. Verified: typecheck green both programs, smoke
|
||||||
|
ALL PASS (+27: the add-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, fixture cleanup; and the
|
||||||
|
mock-c battery -- mock-fail lands its verdict with the
|
||||||
|
never-cache marker, absent from the cache file, re-probed fresh
|
||||||
|
on the re-refine while the passing three serve from cache, not
|
||||||
|
selectable, and no orphan run), restart + reminder checks green
|
||||||
|
(5 runs again -- the leak gone), a browser pass on the mock
|
||||||
|
server driving the whole UI machine (the form's 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), and the debug server back on
|
||||||
|
the real state (Chloe + Irene). Docs: README's add-flow and
|
||||||
|
cache passages amended. The dev refine-cache never existed (the
|
||||||
|
real refine predates the cache), so no hand-clean was needed.
|
||||||
|
|
||||||
|
- **Design research landed in ROADMAP (2026-11-19, GM): two open
|
||||||
|
questions worked in conversation, nothing built.** "Teaching the
|
||||||
|
model style" -- register is a consequence, not a setting;
|
||||||
|
entrainment is the runtime mechanism (the bundle's own prose is
|
||||||
|
the in-context corpus); the corpus-free levers, cheapest first
|
||||||
|
(the GM's narration, the package lens, moves-as-tests, fixing
|
||||||
|
the two disease-teaching prompt lines, the sampling layer); the
|
||||||
|
packager (the housekeeper pattern: no direct quotes, no plot, a
|
||||||
|
no-clone gate). And "the happy camper": small scope without the
|
||||||
|
erotic copout -- gravity not walls, membrane not seal, Chekhov
|
||||||
|
debt in two currencies, no in-setting telos, demand and
|
||||||
|
forgiveness as separate axes, the model's drama gravity as the
|
||||||
|
honest difficulty. Findings only, stated generic -- the record
|
||||||
|
exists so future rounds start from it; the pilot below is its
|
||||||
|
own order of operations.
|
||||||
|
|
||||||
|
- **The provider round is BUILT and verified (2026-11-18, the
|
||||||
|
batteries-included arc): providers are first-class entities, the
|
||||||
|
config is server-written state, and a fresh clone boots
|
||||||
|
playable.** state/config.json holds the entities (slug,
|
||||||
|
baseUrl, optional key, the op's default {model, effort} pair);
|
||||||
|
the SPA manages them -- the binary add (the opencode/free
|
||||||
|
singleton or a custom provider), removal (the singleton holds
|
||||||
|
while it is all that stands), per-provider discover/refine with
|
||||||
|
the meter, the selection prompt, and the curator's
|
||||||
|
recommendation with its one-click apply. server.json shrank to
|
||||||
|
bind + contwin (optional) and imports once on first open: the
|
||||||
|
dev machine migrated (provider 'llm-exan-tech', the 13
|
||||||
|
measured models preserved, the glm-5.3 pin carried as the
|
||||||
|
default at max). The self-heal boot: an empty provider list is
|
||||||
|
auto-fixed -- opencode/free added and discovered in the
|
||||||
|
background, boot never blocks. The spec model: every request
|
||||||
|
resolves {provider, model, effort} -- no unset effort
|
||||||
|
(amending the 2026-11-16 measured-default ruling), the per-run
|
||||||
|
params layer retired (the <mind> verb is the only sampling
|
||||||
|
source; max_tokens died with it, the turn meter scales on
|
||||||
|
history alone). The registry is per-provider sections; the
|
||||||
|
adjudication cache is keyed by the double spec tuple (churn
|
||||||
|
reuses, re-probes refresh -- the smoke caught the first build
|
||||||
|
caching the bare probe and stripping curation on a cached
|
||||||
|
re-refine). Run picks are invalidatable: a removed provider, a
|
||||||
|
drifted or disqualified model blocks the run with the note
|
||||||
|
naming what died; the housekeeper inherits the player spec's
|
||||||
|
provider default (#16 closed). Legacy bare-string picks resolve
|
||||||
|
through the registry -- Chloe stays playable, Irene blocks
|
||||||
|
honestly (she never runs again by ruling). Verified: typecheck
|
||||||
|
green both programs, smoke ALL PASS with the provider battery
|
||||||
|
(the self-heal boot, the binary add, the o/f guard, the
|
||||||
|
selection-then-refine flow, the per-provider meters, the cache
|
||||||
|
hit and purge, invalidation end to end, the restore cycle),
|
||||||
|
restart + reminder checks green, a browser pass over the admin
|
||||||
|
block and the model box with zero console errors (the
|
||||||
|
refine-then-recommend-then-apply loop, the spec saves, the
|
||||||
|
inheritance health line), and the live debug server migrated
|
||||||
|
and serving. The staged vector round is superseded by this one
|
||||||
|
-- its endpoints vector survives as the import's input shape.
|
||||||
|
The same sitting proved the whole arc LIVE, from nothing
|
||||||
|
(sandboxed, then restored): bare boot with no server.json and
|
||||||
|
no state mints the invite, auto-adds opencode/free; claim, add
|
||||||
|
a custom provider with a bogus key (the recognizable 401), fix
|
||||||
|
the auth (the listing retries, 13 models), select the default
|
||||||
|
pair, create a run with its spec, start, and play a real
|
||||||
|
glm-5.3 turn -- 116s, actual prose, the full path walked clean.
|
||||||
|
Two live findings: opencode.ai serves 89 models keyless but
|
||||||
|
401s an EMPTY Bearer header (fixed: the auth header rides only
|
||||||
|
when a key exists -- the anonymous fallback was broken against
|
||||||
|
its own endpoint), and the failure log line rides stderr
|
||||||
|
(console.error), not stdout. THE NO-LEGACY PASS (GM's new rule,
|
||||||
|
2026-11-18, recorded in AGENTS): the four legacy paths this
|
||||||
|
round shipped with died the same day -- bootImport deleted (the
|
||||||
|
dev config exists; server.json cleaned to bind + contwin), the
|
||||||
|
registry's v1/v2 in-memory migration deleted (models.json
|
||||||
|
rewritten on disk into the per-provider shape), the
|
||||||
|
bare-string model picks deleted (Chloe's run.json migrated to
|
||||||
|
spec objects, shape-preserving: exactly what the runtime
|
||||||
|
resolved), the clerk's create model arg deleted (the hidden
|
||||||
|
legacy writer), plus apiKeyEnv and the contextWindow alias.
|
||||||
|
Re-verified after the pass: typecheck green both programs,
|
||||||
|
smoke ALL PASS, restart + reminder checks green, check-repo
|
||||||
|
clean, the debug server on the migrated state (Chloe resolves
|
||||||
|
spec-only, the registry reads the v3 file directly).
|
||||||
|
- **Superseded:** the provider-vector round (2026-11-18) --
|
||||||
|
endpoints as a config list -- was folded into the provider
|
||||||
|
round above the same day; its build verified as described
|
||||||
|
there, and the vector survives as the server.json import's
|
||||||
|
input shape.
|
||||||
|
|
||||||
|
- **The provider-vector round is BUILT and verified (2026-11-18),
|
||||||
|
uncommitted.** `server.json`'s singular endpoint became
|
||||||
|
`endpoints`: a list of (baseUrl, auth) pairs, auth optional --
|
||||||
|
the scaffold's prerequisite, so the free keyless default and the
|
||||||
|
op's real key coexist as entries. One client per pair, discovery
|
||||||
|
scrapes every configured endpoint and tags each model with its
|
||||||
|
base, every call routes through `providerFor`, and the
|
||||||
|
singular-era registry normalizes on open (the measured registry
|
||||||
|
survives unregenerated). Smoke-proven over two synthetic mock
|
||||||
|
endpoints; live-proven on the real 13-model registry.
|
||||||
|
- **Everything else is built and committed through `14b9b01`
|
||||||
|
(2026-11-18).**
|
||||||
The latest commit carries the day's three pieces:
|
The latest commit carries the day's three pieces:
|
||||||
- **The rewind round**: the GM's take-back riding the send --
|
- **The rewind round**: the GM's take-back riding the send --
|
||||||
`rewind` (a log line index naming one of your turns) truncates
|
`rewind` (a log line index naming one of your turns) truncates
|
||||||
@@ -95,53 +257,118 @@ file is the "where did we leave off" map.
|
|||||||
restraints as income-producing assets); still missing: the opening
|
restraints as income-producing assets); still missing: the opening
|
||||||
turn, real memory seeds, a gm.md (the task stream, the facility's
|
turn, real memory seeds, a gm.md (the task stream, the facility's
|
||||||
voice, the release-target ruling) -- its current seeds are
|
voice, the release-target ruling) -- its current seeds are
|
||||||
la-caramba leftovers. `packages/detention/` is also WIP, untouched.
|
la-caramba leftovers. `packages/detention/` and
|
||||||
|
`packages/template/` are also WIP, untouched.
|
||||||
|
- **The deployment thread (2026-11-18): the box is oriented, the
|
||||||
|
story is ruled, the build has not started.** A burble VM (Debian
|
||||||
|
13, single-core, 4G swap live; connection specifics in the
|
||||||
|
gitignored `.ssh/box.md`). The ruled shape: release dirs with a
|
||||||
|
moving symlink (the runner stages, the unit's ExecStartPre
|
||||||
|
relinks and prunes); the graceful stop as an in-process state
|
||||||
|
machine (starting -> alive -> waiting -> exited -- USR1 sets the
|
||||||
|
drain, refuses new ops, uncancellable, awaits the run locks and
|
||||||
|
the jobs, capped ~10 min; TERM/HUP/QUIT exit immediately;
|
||||||
|
systemd KillSignal=USR1 makes stop/restart the graceful path);
|
||||||
|
the state home moving out of the repo (default `~/.tiny-worlds`,
|
||||||
|
env override, first-start scaffold -- the release tree carries
|
||||||
|
nothing gitignored); TLS terminates in caddy (automatic
|
||||||
|
TLS-ALPN-01, staged against LE's staging endpoint first); node
|
||||||
|
via nvm at the current stable branch; the pipeline is a gitea
|
||||||
|
runner on the box, stage-and-signal, no test gates in it (the
|
||||||
|
smoke needs clean state, which the box can never give). The
|
||||||
|
The provider round (above) settled the scaffold's provider
|
||||||
|
story: the o/f singleton ships, auto-added and discovered on the
|
||||||
|
empty provider list -- playable with zero secrets. Unverified:
|
||||||
|
whether the free models pass the discovery battery's tool probe
|
||||||
|
(the listing is real and keyless: 89 models at the time of the
|
||||||
|
fresh-path test -- a full refine on it is 89 batteries, which
|
||||||
|
makes the parked short-list rule suddenly relevant).
|
||||||
- **The debug server runs the current code** (port 7350, pid in the
|
- **The debug server runs the current code** (port 7350, pid in the
|
||||||
temp pid file; sessions rebuilt for Chloe and Irene at boot).
|
temp pid file; sessions rebuilt for Chloe and Irene at boot).
|
||||||
state/ holds the refined registry. Four commits await the GM's
|
state/ holds the refined registry (per-provider shape on disk,
|
||||||
push (`bbaf336`, `5279dd3`, `eefb721`, `53f992a` -- the ssh key
|
migrated in the no-legacy pass) and the provider config
|
||||||
takes a passphrase, pushes are the GM's).
|
('llm-exan-tech', default glm-5.3 at max). Five commits await
|
||||||
|
the GM's push (`bbaf336`, `5279dd3`, `eefb721`, `53f992a`,
|
||||||
|
`14b9b01` -- the ssh key takes a passphrase, pushes are the
|
||||||
|
GM's), with the provider round and the no-legacy pass staged
|
||||||
|
beside them.
|
||||||
|
|
||||||
## Immediate next steps, in order
|
## Immediate next steps, in order
|
||||||
|
|
||||||
1. **First start under multiuser (op, one-time).** Start the server
|
1. **The deploy build.** The free-default call is RESOLVED
|
||||||
normally, claim the bootstrap invite
|
(2026-11-18, the provider round): the opencode/free singleton
|
||||||
(`state/bootstrap-invite.txt` and the console both carry it).
|
ships -- auto-added and discovered on the empty provider list,
|
||||||
Nothing live has touched the auth spine yet -- mock-proven only.
|
playable with zero secrets; the box's first refine on it is
|
||||||
2. **The fresh run.** Create it from la caramba (the box waits on its
|
the live test of whether its free models pass the battery's
|
||||||
files), pick the model and the effort at create time, and play.
|
tool probe. What remains is the state-home half, by the book
|
||||||
|
after the fresh-boot observation on this laptop (GM,
|
||||||
|
2026-11-18): the state home out of the repo (default
|
||||||
|
~/.tiny-worlds, env override, first-start scaffold -- the dev
|
||||||
|
machine migrates once, and the smoke gets its own temp home,
|
||||||
|
killing the state-backup dance), the USR1 state machine + the
|
||||||
|
immediate-exit handlers, the systemd unit (KillSignal,
|
||||||
|
TimeoutStopSec above the cap, ExecStartPre relink + prune),
|
||||||
|
caddy with its TLS-ALPN-01 cert (staging endpoint first), the
|
||||||
|
gitea runner workflow (stage, signal, restart), and the
|
||||||
|
box-side install (nvm + current stable node, runner
|
||||||
|
registration). The first start under multiuser rides this: the
|
||||||
|
op's bootstrap-invite claim happens ON the box.
|
||||||
|
2. **The fresh run.** Create it from la caramba
|
||||||
|
its files), pick the model and the effort at create time, and
|
||||||
|
play -- on the debug server or the deployment, the GM's choice.
|
||||||
It carries everything new at once: the 2026-11-17 prompt set's
|
It carries everything new at once: the 2026-11-17 prompt set's
|
||||||
first live test (the audience doctrine, the typography rule, the
|
first live test (the audience doctrine, the typography rule,
|
||||||
no-echo teaching), the full-block protocol's first live run (her
|
the no-echo teaching), the reminder's checked-action metrics,
|
||||||
first own whole-list emission is still unplayed), the measured
|
the full-block protocol's first live run (her first own
|
||||||
effort default riding unset turns, and the turn meter under real
|
whole-list emission is still unplayed), and the spec picks and
|
||||||
use. Her first stop carries the first real housekeeping pass, the
|
the turn meter under real use. Her first stop carries the first
|
||||||
slidwin carry test, and the boundary state note. Decide before
|
real housekeeping pass, the slidwin carry test, and the boundary
|
||||||
the first turn whether max effort is wanted: a fresh glm-5.3 run
|
state note. The effort is a deliberate pick now (there is no
|
||||||
sends `reasoning_effort: max` by the measured default (the
|
unset effort): decide it at the setup box -- the measured
|
||||||
disposable test run's turns thought 12.1k/3.9k/6.5k chars against
|
ladders pre-select each model's max-mean level.
|
||||||
~1.4k of prose) -- the knob is one click on the run's model box.
|
3. **The style pilot (zero build -- the design research's own
|
||||||
3. **Prompt reviews (GM-led).** housekeeper.md: read it, tweak,
|
first move).** Hand-place a style chapter in a dormant run's
|
||||||
|
handbook copy (the file editor already allows it), a
|
||||||
|
style-by-name line in character.md, the opening turn in-voice:
|
||||||
|
an evening's work testing whether register carries through
|
||||||
|
entrainment at all -- the packager only earns its build if the
|
||||||
|
mechanism proves. Riding along, the two lines that teach the
|
||||||
|
disease (design research, lever 4): the reminder's "Decorate
|
||||||
|
the turn with additional flavour" (decoration is the failure
|
||||||
|
mode as a verb) and the handbook's uncashed "Flavourful
|
||||||
|
language" pointer -- prompt files, so the drafts are mine and
|
||||||
|
the red pen is the GM's.
|
||||||
|
4. **Prompt reviews (GM-led).** housekeeper.md: read it, tweak,
|
||||||
replay -- the dry-run button re-runs housekeeping with nothing
|
replay -- the dry-run button re-runs housekeeping with nothing
|
||||||
applied. curator.md likewise: read, red-pen, re-run refine (one
|
applied. curator.md likewise: read, red-pen, re-run refine (one
|
||||||
click; the meter watches it now).
|
click; the meter watches it now).
|
||||||
4. **Finish the box** (GM's): the files above, then it becomes the
|
5. **Finish the box** (GM's): the files above, then it becomes the
|
||||||
sheet's first consumer.
|
sheet's first consumer.
|
||||||
5. **Keep playing -- and watch.** The standing observables (#12
|
6. **Keep playing -- and watch.** The standing observables
|
||||||
status discipline, #14 turn lengthening vs the reminder), the
|
status discipline, #14 turn lengthening vs the reminder), the
|
||||||
protocol's firsts (does she restate her blocks every turn or on
|
protocol's firsts (does she restate her blocks every turn or on
|
||||||
change; does the `<model>` block teach her anything; does she
|
change; does the `<model>` block teach her anything; does she
|
||||||
ever state a `<mind>`; does a GM override read as her state and
|
ever state a `<mind>`; does a GM override read as her state and
|
||||||
does she adopt or fight it), the effort knob's texture and cost
|
does she adopt or fight it), the conflict quotes doing their
|
||||||
curve, the prompt-craft rules against a live model (no-echo,
|
job (does a kept mistake stop repeating), the rewind under real
|
||||||
bold-not-italics), the variantary firsts (the pick against a real
|
regret, the effort knob's texture and cost curve, the
|
||||||
model, the metric's curve, coin-flip personality), and the sheet
|
prompt-craft rules against a live model (no-echo,
|
||||||
once the box runs.
|
bold-not-italics), the variantary firsts (the pick against a
|
||||||
|
real model, the metric's curve, coin-flip personality), and the
|
||||||
|
sheet once the box runs.
|
||||||
|
|
||||||
## Not yet exercised (expect first-use friction)
|
## Not yet exercised (expect first-use friction)
|
||||||
|
|
||||||
- **First start under multiuser** -- the auth spine, invites, fork,
|
- **First start under multiuser** -- the auth spine, invites, fork,
|
||||||
non-owner reads: all mock-proven only.
|
non-owner reads: all mock-proven only. Its first live run rides
|
||||||
|
the deployment (the op claims the box's bootstrap invite).
|
||||||
|
- **The free models against the battery** -- the o/f listing is
|
||||||
|
live-proven (89 models keyless, the empty-Bearer 401 found and
|
||||||
|
fixed in the fresh-path test), and a live second provider rode
|
||||||
|
beside it (the dv add in the same test) -- what no traffic has
|
||||||
|
touched is a refine over the free models: the tool probe, the
|
||||||
|
ladders, the curator on a free model. The box's first refine
|
||||||
|
is the test.
|
||||||
- **The rewind against a live model** -- mock- and browser-proven;
|
- **The rewind against a live model** -- mock- and browser-proven;
|
||||||
the fresh run's first real regret is its first live test, and the
|
the fresh run's first real regret is its first live test, and the
|
||||||
expect guard's 409 has never fired outside the smoke.
|
expect guard's 409 has never fired outside the smoke.
|
||||||
|
|||||||
@@ -8,18 +8,6 @@ DICTIONARY.md, or the prompts. Tiered by urgency, FIFO within a tier.
|
|||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
### 16. Housekeeping model configuration -- OPEN (mechanism settled)
|
|
||||||
The housekeeping job runs server-side on a fresh model invocation.
|
|
||||||
Mechanism settled (2026-11-13): `server.json` names one endpoint plus
|
|
||||||
default models (player, housekeeper), `GET /api/models` lists what the
|
|
||||||
upstream carries, and a run may override its model. Wired end to end
|
|
||||||
(2026-11-14): run.json carries `models: {player, housekeeper}` per-run
|
|
||||||
overrides, owner-settable from the SPA (setup + play aside), falling
|
|
||||||
back to the config defaults; the housekeeper call resolves per wrap.
|
|
||||||
Which model the housekeeping DEFAULT points at (cheap-model
|
|
||||||
housekeeping, ROADMAP steal #8) remains the open call. (The
|
|
||||||
housekeeper.md line on reading thinking blocks as attention evidence,
|
|
||||||
not fiction, is in -- 2026-11-12.)
|
|
||||||
|
|
||||||
### 19c. The seed's voice register -- OPEN, DEFERRED
|
### 19c. The seed's voice register -- OPEN, DEFERRED
|
||||||
The GM may revisit later; non-blocking, since the seed copy stays
|
The GM may revisit later; non-blocking, since the seed copy stays
|
||||||
|
|||||||
@@ -62,8 +62,10 @@ or otherwise PC ever needs support, this is the line to revisit.
|
|||||||
|
|
||||||
## The deployment (multiuser)
|
## The deployment (multiuser)
|
||||||
|
|
||||||
A deployment is one clone plus `server.json`, `state/`, and `runs/` --
|
A deployment is one clone plus `state/` and `runs/` (all gitignored
|
||||||
all gitignored state. The LLM key lives on the backend; invited users
|
state) and an optional `server.json` -- bind and contwin only; the
|
||||||
|
provider entities live in `state/config.json`, server-written,
|
||||||
|
SPA-managed, zero manual file edits. The LLM key lives on the backend
|
||||||
need neither the key nor a local clone. Identity is a token, nothing
|
need neither the key nor a local clone. Identity is a token, nothing
|
||||||
else: no usernames, no passwords, no external IDPs. A single-use
|
else: no usernames, no passwords, no external IDPs. A single-use
|
||||||
invite code -- spent codes are recorded forever and rejected loudly on
|
invite code -- spent codes are recorded forever and rejected loudly on
|
||||||
@@ -100,11 +102,19 @@ forking makes that cheap -- stories outlive identities by design.
|
|||||||
a user can save their run's craft as a user package under
|
a user can save their run's craft as a user package under
|
||||||
`state/packages/` -- published to everyone, gm.md included (saving is
|
`state/packages/` -- published to everyone, gm.md included (saving is
|
||||||
the act of publishing), the pc never riding.
|
the act of publishing), the pc never riding.
|
||||||
- **Models are per-run over the deployment defaults.** `server.json`
|
- **Models are per-run picks of full specs.** A pick is
|
||||||
names the defaults (player, housekeeper); a run's owner overrides
|
{provider, model, effort} -- there is no unset effort (it
|
||||||
either role from the upstream listing -- in setup for drafts, in the
|
substantially changes inference quality, so it is a property of the
|
||||||
play aside for started runs. Each call resolves fresh, so a
|
pick, GM 2026-11-18), and the per-run sampling-knob layer is
|
||||||
mid-session switch simply takes the next turn.
|
retired: params are per-turn, the <mind> verb's alone. The
|
||||||
|
provider's default pair (the op's selection, also the refine
|
||||||
|
curator) pre-selects the create flow; a run's owner overrides
|
||||||
|
either role -- in setup for drafts, in the play aside for started
|
||||||
|
runs. Each call resolves fresh, so a mid-session switch simply
|
||||||
|
takes the next turn. A pick is invalidatable: a provider removed
|
||||||
|
from the config, a model gone from its registry, a model the
|
||||||
|
battery disqualified -- the run blocks with the note naming what
|
||||||
|
died until the GM sets it up again.
|
||||||
- Every logged LLM call records the acting user. Quotas and limits are
|
- Every logged LLM call records the acting user. Quotas and limits are
|
||||||
an extension point, not built.
|
an extension point, not built.
|
||||||
- All dates and times are UTC everywhere. No time zones, ever.
|
- All dates and times are UTC everywhere. No time zones, ever.
|
||||||
@@ -589,35 +599,40 @@ the request returns with the question, the answer call resumes it,
|
|||||||
and a refresh re-presents it after a restart. The old
|
and a refresh re-presents it after a restart. The old
|
||||||
`tool/bridge.mjs` is deleted: it never went live, and the server
|
`tool/bridge.mjs` is deleted: it never went live, and the server
|
||||||
reached mock-parity (2026-11-14).
|
reached mock-parity (2026-11-14).
|
||||||
Config: copy `server.example.json` to `server.json` (gitignored) -- any
|
Config is self-healing state, not a hand-edited file (GM, 2026-11-18):
|
||||||
OpenAI-compatible endpoint; put the key in the endpoint's `apiKey`
|
the provider entities -- slug, baseUrl, optional key, the op's
|
||||||
field or name an env var via `apiKeyEnv`; `models` names the player
|
default model spec -- live in `state/config.json`, written only by
|
||||||
and housekeeper defaults (the op's explicit pick -- it beats the
|
the server, managed from the SPA's admin block. `server.json`
|
||||||
registry's discovered default), `contwin` (the context window; the old
|
(gitignored, optional) is the static remainder: `bind` and `contwin`
|
||||||
`contextWindow` key still accepted) drives the context meter,
|
(the context budget in tokens). No legacy config shapes are read:
|
||||||
`params` holds the deployment-default sampling knobs per role
|
shape changes come with one-time migrations, not permanent tolerance
|
||||||
(temperature, top_p, top_k, repetition_penalty, max_tokens,
|
(the no-legacy rule, GM, 2026-11-18). Boot always succeeds: a fresh clone with nothing comes
|
||||||
reasoning_effort) -- a
|
up serving and mints the superuser invite, and -- the self-heal
|
||||||
run carries its own overrides for models and knobs in `run.json`,
|
rule, broadly: an error that can be mechanically fixed to a
|
||||||
merged over the deployment layer. The five numeric knobs send only
|
reasonable degree without requiring human input gets fixed -- the
|
||||||
when set (the provider's serving defaults are unknowable, so no
|
empty provider list is auto-fixed by adding opencode/free (the
|
||||||
default is honestly nameable); reasoning_effort is the exception --
|
anonymous, keyless fallback: fixed slug and base, never carrying
|
||||||
the battery measured a per-model default (the effort level with the
|
auth -- a 401 from it is upstream breakage to show, not a prompt to
|
||||||
highest observed mean thinking), so its unset state sends that, and
|
fix) and running its discovery in the background. The list is never
|
||||||
an explicit null clears to nothing (the model id's baked default
|
empty in lifetime either: opencode/free is removable only while
|
||||||
applies). It is the GM's knob alone: hidden from the model, never
|
another provider stands. Custom providers add from the SPA taking
|
||||||
in the mind verb, never in the `<model>` display block -- it rides
|
only the endpoint (a slug and a baseUrl -- never a key): discovery
|
||||||
the via record, the raw surfaces carry it. The knob UX
|
runs on add and IS the probe (GM, 2026-11-19). A working keyless
|
||||||
(web/knobs.mjs) is explicit: a per-knob override toggle (off = unset,
|
listing never sees a key field; a recognizable auth refusal (401/403)
|
||||||
the input disabled; on demands a number, a level for the enum), the
|
stands the provider broken and opens the key path -- the key rides
|
||||||
definitions table
|
the auth route, checked on reception, saved only on success, asked
|
||||||
carrying every text -- label, hint, this endpoint's probed bounds --
|
again on the next refusal; every other failure refuses the add
|
||||||
and one shared hint bar driven by focus; unset and set-to-the-
|
outright, nothing stands. The card reads the last probe outcome, and
|
||||||
deployment-default are distinct states, the run detail exposes the
|
only the explicit acts move it (add, key, remove-key, discover) --
|
||||||
deployment layer (`paramDefaults`), and the provider's own serving
|
usage errors are transient and the op's to fix, nothing auto-flips.
|
||||||
defaults stay unstated. Above every layer sits the mind verb -- the
|
A keyed provider carries a remove-key control: a provider gone
|
||||||
player's own one-shot statement for its next turn (the play protocol
|
public, or the first half of a replacement (the ask re-opens when
|
||||||
above). `--mock` runs
|
the keyless probe meets the refusal again). The housekeeper
|
||||||
|
inherits: no pick of its own means the
|
||||||
|
player spec's provider default. The mind verb stands above every
|
||||||
|
pick -- the player's own one-shot statement for its next turn (the
|
||||||
|
play protocol above), and the only params source there is.
|
||||||
|
`--mock` runs
|
||||||
a scripted fake model that proves the loop without a key. The SPA is
|
a scripted fake model that proves the loop without a key. The SPA is
|
||||||
the server plus a fiction-first UI, a
|
the server plus a fiction-first UI, a
|
||||||
GM console, and the housekeeping job runner -- and the
|
GM console, and the housekeeping job runner -- and the
|
||||||
@@ -627,30 +642,49 @@ player-side status maintenance proves too costly for the player-model's
|
|||||||
attention, the fallback is a dedicated status-keeper agent reading
|
attention, the fallback is a dedicated status-keeper agent reading
|
||||||
transcripts -- same pattern as the housekeeper, smaller job.
|
transcripts -- same pattern as the housekeeper, smaller job.
|
||||||
|
|
||||||
**Model discovery** is the op's two-step act from the SPA's admin
|
**Model discovery** is per provider, the op's acts from the SPA's
|
||||||
block, and the registry it writes (`state/models.json`) is the truth
|
admin block, and the registry it writes (`state/models.json`, one
|
||||||
of selectable models -- a fresh deployment has none and model use is
|
section per provider) is the truth of selectable models -- a
|
||||||
disabled until the op acts. **Discover** scrapes the provider
|
provider not discovered has nothing selectable. **Discover** scrapes
|
||||||
surface: API metadata only, zero inference, the preliminary list.
|
one provider's surface: API metadata only, zero inference, the
|
||||||
**Refine** runs the deterministic battery over that list -- the
|
section written preliminary (free, but it resets a refined section
|
||||||
tool-manifest ping (the exact request shape a player turn takes; a
|
-- the battery results are re-earned by refining). **Refine** runs
|
||||||
model that cannot take it is not an inference model and stays out of
|
the deterministic battery over that provider's list -- the
|
||||||
the selectors), two reasoning samples on a fixed puzzle, the
|
tool-manifest ping at the working effort (the exact request shape a
|
||||||
disable-thinking probe whose working spelling is recorded as a
|
player turn takes; a model that cannot take it is not an inference
|
||||||
discovered fact, and the reasoning-effort probe: each level of the
|
model and stays out of the selectors), two reasoning samples on a
|
||||||
ladder (`none` through `max`) measured for mean thinking, the
|
fixed puzzle, the disable-thinking probe whose working spelling is
|
||||||
per-model default being the level with the highest observed mean
|
recorded as a discovered fact, and the reasoning-effort ladder
|
||||||
(GM, 2026-11-16: maximum thinking by default, overridable) -- then
|
(each level measured for mean thinking) -- then hands the
|
||||||
hands the adjudicated results to the
|
adjudicated results to the op's selected default model (repo
|
||||||
best-measured model (repo craft: `curator.md`) for the
|
craft: `curator.md`) for the presentation layer: families, labels,
|
||||||
presentation layer: families, labels, descriptions, role
|
descriptions, role eligibility, and one overall-best recommendation
|
||||||
eligibility. The curator's output is strictly validated; any
|
{model, effort} -- intel only, shown beside the op's selection,
|
||||||
failure falls back to the machine list, so discovery can never be
|
applied by one click, never auto-landed, and never a deterministic
|
||||||
blocked by a bad model day. Defaults never consult the curator: the
|
stand-in on a bad model day (the op gets no advice, not machine
|
||||||
max-reasoning rule picks them (most measured thinking, then input
|
advice). The curator's output is strictly validated; any failure
|
||||||
ceiling, then output ceiling, then id), for both roles. Refine sends
|
falls back to the machine list, so refine can never be blocked by a
|
||||||
real traffic over every listed model and is armed with the warning;
|
bad model day. The battery's measured effortDefault is pre-fill and
|
||||||
discover is free but resets a refined registry to the fresh scrape.
|
hint only -- nothing rides implicitly anymore (GM, 2026-11-18,
|
||||||
|
amending 2026-11-16: with effort a property of the pick, the
|
||||||
|
selection prompt pre-selects and the recommendation informs, no
|
||||||
|
silent layer). The adjudication cache (`state/refine-cache.json`)
|
||||||
|
keys each refined entry by the full spec tuples on both sides --
|
||||||
|
the probed model at the effort the deployment sends, and the
|
||||||
|
curator at its own spec (a weak curator at a low effort adjudicates
|
||||||
|
worse; reasoning effort substantially changes inference quality) --
|
||||||
|
so churn is cheap: discovery re-runs freely (opencode/free rotates
|
||||||
|
its models), and a refine that sees the same tuple reuses the
|
||||||
|
cached verdict, refreshing it in place when it re-probes. Failures
|
||||||
|
never cache (GM, 2026-11-19): a failure is the absence of a
|
||||||
|
measurement, not a measurement -- every refine re-probes the models
|
||||||
|
that failed the last one, so a transient error never pins a false
|
||||||
|
verdict, and a model that fails for real costs one cheap probe per
|
||||||
|
refine. No inference call retries itself (GM, 2026-11-19, the
|
||||||
|
universal rule): every call is user-initiated and every act has its
|
||||||
|
manual retry -- the send again, the housekeeping re-run, the refine
|
||||||
|
button; a dead curator call lands the machine-label fallback, which
|
||||||
|
is the designed outcome, not a degraded one.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
@@ -718,16 +752,23 @@ server/ the substrate: a zero-dependency node:http service
|
|||||||
/session (raw, the audit surface), GET /table (the
|
/session (raw, the audit surface), GET /table (the
|
||||||
play view), GET /story (the whole deliverable),
|
play view), GET /story (the whole deliverable),
|
||||||
GET /carryover (the dormant preview)
|
GET /carryover (the dormant preview)
|
||||||
provider.mjs the endpoint client (chat completions, models listing
|
provider.mjs the provider clients (one per configured entity --
|
||||||
with metadata)
|
chat completions, models listing with metadata; API
|
||||||
|
failures carry their HTTP status) and providerFor,
|
||||||
|
the slug-keyed routing
|
||||||
|
providers.mjs the provider entities: state/config.json (the
|
||||||
|
server-written truth), the one-time server.json
|
||||||
|
import, the opencode/free singleton (authless,
|
||||||
|
guarded removal), the self-heal auto-add
|
||||||
users.mjs the deployment's people: users, invites, tokens
|
users.mjs the deployment's people: users, invites, tokens
|
||||||
(state/deployment.db; hashes only, spent invites
|
(state/deployment.db; hashes only, spent invites
|
||||||
recorded forever)
|
recorded forever)
|
||||||
discovery.mjs model discovery: the two op acts -- discover (the
|
discovery.mjs model discovery, per provider: discover (the
|
||||||
metadata scrape) and refine (the deterministic
|
metadata scrape, the section reset) and refine (the
|
||||||
battery, the curator pass, the registry write);
|
battery, the curator pass, the recommendation, the
|
||||||
state/models.json is the registry the selectors,
|
spec-keyed adjudication cache);
|
||||||
model routes, and the turn loop gate on
|
state/models.json is the per-provider registry the
|
||||||
|
selectors, model routes, and the turn loop gate on
|
||||||
bundle.mjs run context: prompt assembly (the trio system message,
|
bundle.mjs run context: prompt assembly (the trio system message,
|
||||||
the GM-message bundle, @ sigils + $ vars), the tool manifest
|
the GM-message bundle, @ sigils + $ vars), the tool manifest
|
||||||
and its clerk dispatch (records off until
|
and its clerk dispatch (records off until
|
||||||
@@ -794,11 +835,11 @@ web/ the SPA -- no build, vanilla ES modules, path-routed;
|
|||||||
refreshes; the header's "log" button)
|
refreshes; the header's "log" button)
|
||||||
widgets.mjs the shared factories: armedButton (the two-click
|
widgets.mjs the shared factories: armedButton (the two-click
|
||||||
confirm), paneEditor (the status/agenda pattern),
|
confirm), paneEditor (the status/agenda pattern),
|
||||||
modelsBox (per-run model selects over the listing)
|
modelsBox (the per-run spec picks: provider, model,
|
||||||
knobs.mjs the sampling knobs: the definitions table (every
|
effort per role, the invalidation health line)
|
||||||
knob text -- label, hint, this endpoint's probed
|
knobs.mjs the reasoning-effort ladder (mirrors the server's)
|
||||||
bounds) and the per-role row with the explicit
|
and the effort select -- the per-run knob rows are
|
||||||
override toggle and the shared hint bar
|
retired (params are per-turn, the mind verb's alone)
|
||||||
transcript.mjs register rendering (speech / narration / OOC) and
|
transcript.mjs register rendering (speech / narration / OOC) and
|
||||||
the session-log entry walk (historical opening
|
the session-log entry walk (historical opening
|
||||||
events render as machinery); colour-only tokens,
|
events render as machinery); colour-only tokens,
|
||||||
@@ -827,21 +868,24 @@ test/ the mock smoke, kept next to the code
|
|||||||
prose, zero-dependency imports, utc discipline, web/
|
prose, zero-dependency imports, utc discipline, web/
|
||||||
static naming (never "api"), the bundle boundary,
|
static naming (never "api"), the bundle boundary,
|
||||||
dateless memory
|
dateless memory
|
||||||
server.example.json copy to server.json (gitignored) -- bind, endpoint +
|
server.example.json copy to server.json (gitignored, optional) --
|
||||||
key env, models, contwin, params passthrough
|
bind, contwin; the providers are SPA-managed state
|
||||||
db/
|
db/
|
||||||
schema.sql entries, records, events journal (shared; the status
|
schema.sql entries, records, events journal (shared; the status
|
||||||
and agenda tables are retired -- the log is their
|
and agenda tables are retired -- the log is their
|
||||||
one truth, old runs keep dead tables, never read)
|
one truth, old runs keep dead tables, never read)
|
||||||
state/ per-deployment people + shared packages (gitignored):
|
state/ per-deployment people + shared packages (gitignored):
|
||||||
deployment.db (users, invites), bootstrap-invite.txt,
|
deployment.db (users, invites), bootstrap-invite.txt,
|
||||||
models.json (the discovered registry -- the truth of
|
config.json (the provider entities -- server-written,
|
||||||
selectable models), packages/ (user-saved, published
|
SPA-managed), models.json (the per-provider registry
|
||||||
to everyone)
|
-- the truth of selectable models), refine-cache.json
|
||||||
|
(the adjudication cache), packages/ (user-saved,
|
||||||
|
published to everyone)
|
||||||
runs/ per-deployment run state (gitignored) -- one anonymous
|
runs/ per-deployment run state (gitignored) -- one anonymous
|
||||||
id per run (carries no facts): run.json (lineage,
|
id per run (carries no facts): run.json (lineage,
|
||||||
owner, `forked` stamp on a fork, models and params --
|
owner, `forked` stamp on a fork, models -- the
|
||||||
per-run player/housekeeper overrides and sampling
|
per-run player/housekeeper specs; the params layer is
|
||||||
|
retired, per-turn via the mind verb), settings.json
|
||||||
knobs), settings.json, gm.md
|
knobs), settings.json, gm.md
|
||||||
(the GM's notepad), manifests/, and sessions/<n>/ per
|
(the GM's notepad), manifests/, and sessions/<n>/ per
|
||||||
session: session.json (phase, ready), bundle/ (the
|
session: session.json (phase, ready), bundle/ (the
|
||||||
|
|||||||
+265
-4
@@ -6,7 +6,8 @@ be worked through one by one; statuses in caps, decisions dated.
|
|||||||
|
|
||||||
## Operator's queue (don't edit, don't work on)
|
## Operator's queue (don't edit, don't work on)
|
||||||
|
|
||||||
- template package
|
- inventorise possible human roles (clear distinction between GM and the developer)
|
||||||
|
- revisit the debug mode, hardcode loobpack
|
||||||
- "create new package" in SPA
|
- "create new package" in SPA
|
||||||
- sec review
|
- sec review
|
||||||
- refactor to add first-class GM agent
|
- refactor to add first-class GM agent
|
||||||
@@ -123,8 +124,15 @@ example, gitignored real file, env-var option).
|
|||||||
in play -- state/models.json is the registry of selectable models,
|
in play -- state/models.json is the registry of selectable models,
|
||||||
written by the op's two-step discover/refine act and gating all
|
written by the op's two-step discover/refine act and gating all
|
||||||
model use; server.json's explicit pick beats the registry's
|
model use; server.json's explicit pick beats the registry's
|
||||||
discovered default.) Which model the housekeeper DEFAULT points at
|
(Amended 2026-11-18, the provider round: the picks are full specs
|
||||||
stays open (#16); the mechanism is settled.
|
{provider, model, effort} -- no unset effort, the per-run sampling
|
||||||
|
knob layer retired (params are per-turn, the <mind> verb's alone);
|
||||||
|
the deployment-default layer became the op's per-provider
|
||||||
|
selection, which also names the refine curator. #16 closed with
|
||||||
|
it: the housekeeper inherits the player spec's provider default.
|
||||||
|
Picks are invalidatable -- a removed provider, a drifted or
|
||||||
|
disqualified model blocks the run until the GM re-picks, the note
|
||||||
|
naming what died.)
|
||||||
- **The player prompt is battery included, split along ownership seams
|
- **The player prompt is battery included, split along ownership seams
|
||||||
(ruled 2026-11-13; cut executed by the GM 2026-11-14).** Three tiers,
|
(ruled 2026-11-13; cut executed by the GM 2026-11-14).** Three tiers,
|
||||||
three files:
|
three files:
|
||||||
@@ -188,7 +196,22 @@ example, gitignored real file, env-var option).
|
|||||||
discussion, a gitea runner the leading idea; node on the box
|
discussion, a gitea runner the leading idea; node on the box
|
||||||
comes via nvm at the current stable branch, no version pin
|
comes via nvm at the current stable branch, no version pin
|
||||||
(GM, 2026-11-18 -- apt's node is too old for node:sqlite, and
|
(GM, 2026-11-18 -- apt's node is too old for node:sqlite, and
|
||||||
there is no reason to pin a branch.)
|
The provider config is a first-class ENTITY now (GM, 2026-11-18,
|
||||||
|
superseding the same day's vector): a user-named slug, config in
|
||||||
|
state/config.json (server-written, SPA-managed, zero hand edits),
|
||||||
|
the free keyless default as the opencode/free singleton --
|
||||||
|
authless, auto-added and discovered on the empty provider list
|
||||||
|
(the self-heal rule), removable only while another provider
|
||||||
|
stands. A fresh deployment ships playable with zero secrets and
|
||||||
|
zero manual files; the first human beat is the model selection
|
||||||
|
after the auto-discovery greets the op.
|
||||||
|
rulings beside it: release dirs with a moving symlink, the
|
||||||
|
graceful stop as an in-process state machine
|
||||||
|
(starting -> alive -> waiting -> exited, USR1 = drain, uncancellable,
|
||||||
|
TERM/HUP/QUIT immediate, systemd KillSignal does the glue), and
|
||||||
|
the state home moving out of the repo (default ~/.tiny-worlds,
|
||||||
|
env override, first-start scaffold -- the release tree carries
|
||||||
|
nothing gitignored).
|
||||||
- **Boutique is dormant** -- a stub that never reached its design step;
|
- **Boutique is dormant** -- a stub that never reached its design step;
|
||||||
untouched until its drafting session.
|
untouched until its drafting session.
|
||||||
- **Stack: zero-dependency runtime** (DECISIONS #4, amended
|
- **Stack: zero-dependency runtime** (DECISIONS #4, amended
|
||||||
@@ -285,6 +308,17 @@ Current answer: close the session. Fine for the test; revisit if real
|
|||||||
sessions regularly overflow.
|
sessions regularly overflow.
|
||||||
Status: DEFERRED.
|
Status: DEFERRED.
|
||||||
|
|
||||||
|
## Parked for later (2026-11-18, the provider round)
|
||||||
|
|
||||||
|
- **The pre-refine deterministic short-list.** The battery bills
|
||||||
|
every model on a provider; a deterministic rule over the scrape's
|
||||||
|
own metadata (ceilings, id heuristics) can short-list what gets
|
||||||
|
probed when the list is big. The op's refine stays the surface;
|
||||||
|
the rule is a cost valve, not a gate.
|
||||||
|
- **The GM's model-selection UX polish.** The spec model landed in
|
||||||
|
the data and the surfaces; the remaining roughness (the selection
|
||||||
|
prompt's presentation, the create flow landing the pick at
|
||||||
|
create-time vs setup-time) is interface craft for a later pass.
|
||||||
## Deferred tasks (ruled out of the dormant-session rework, 2026-11-15)
|
## Deferred tasks (ruled out of the dormant-session rework, 2026-11-15)
|
||||||
|
|
||||||
- **Save-as-package beyond drafts.** Today it fires only from
|
- **Save-as-package beyond drafts.** Today it fires only from
|
||||||
@@ -307,6 +341,233 @@ Status: DEFERRED.
|
|||||||
lines anchor to which turns); the honest tools are GM discipline
|
lines anchor to which turns); the honest tools are GM discipline
|
||||||
and fork-covers-it (the fork copies the notepad with the branch).
|
and fork-covers-it (the fork copies the notepad with the branch).
|
||||||
|
|
||||||
|
## Design research -- teaching style and the happy camper (2026-11-19)
|
||||||
|
|
||||||
|
Two open design questions worked in conversation, nothing built or
|
||||||
|
scheduled. This is the record so the future rounds start from the
|
||||||
|
findings instead of re-deriving them. Findings only: the worked
|
||||||
|
examples stay out of the file, the ideas are stated generic.
|
||||||
|
|
||||||
|
### Teaching the model style; distilling prior art as the shortcut
|
||||||
|
|
||||||
|
The goal: player prose in a chosen literary register (symbolic,
|
||||||
|
colourful, witty, immediately legible) without shipping a corpus of
|
||||||
|
examples in the prompts.
|
||||||
|
|
||||||
|
- **Adjectives do not work.** Asking for "witty, colourful" summons
|
||||||
|
the model's caricature of those words, and the caricature IS the
|
||||||
|
failure mode (ornament, uncashed metaphor, workshop mush). The
|
||||||
|
priming lesson applies twice over: counterexamples prime what they
|
||||||
|
prohibit, so the defense must be stated as positive tests.
|
||||||
|
- **Register is a consequence, not a setting.** Wit and colour
|
||||||
|
emerge from a mind holding a specific vocabulary that the
|
||||||
|
situation keeps breaking; the vocabulary is material, and
|
||||||
|
material can be authored. Generic minds produce generic prose;
|
||||||
|
the fix is input, not instruction. Register is also where
|
||||||
|
analysis and generation split: models read a register fine,
|
||||||
|
they cannot reliably HOLD it while writing -- subtext promotes
|
||||||
|
to text, or the scene tips crude. The register being
|
||||||
|
load-bearing (about something) is what separates craft from
|
||||||
|
decoration.
|
||||||
|
- **The runtime mechanism already exists: entrainment.** The
|
||||||
|
bundle's own prose (backdrop, character, her authored opening
|
||||||
|
turn) is the in-context style corpus, and the GM's narration
|
||||||
|
re-teaches every turn ("match its register the way you match its
|
||||||
|
format" is already the content-stance ruling). Nothing new rides
|
||||||
|
the contwin; what is missing is authored material in the
|
||||||
|
register.
|
||||||
|
- Corpus-free levers, cheapest first:
|
||||||
|
1. **The GM's own narration** -- the biggest live lever, testable
|
||||||
|
today with zero changes. Costs the GM every turn; risks making
|
||||||
|
the story's voice the GM's rather than hers.
|
||||||
|
2. **The package lens** -- character.md's voice field as a
|
||||||
|
perceptual vocabulary ("she was a court reporter; she thinks
|
||||||
|
in testimony"), backdrop written in-register, the opening
|
||||||
|
turn in-voice. The mind-verb philosophy applies: the substrate
|
||||||
|
teaches the channel, the package teaches the vocabulary.
|
||||||
|
3. **Moves as tests, with inline micro-examples** -- the metaphor
|
||||||
|
states its meaning in the same breath (the prompt-prose house
|
||||||
|
rule applied to her output); an image lands once, never
|
||||||
|
restated three ways; the concrete detail undercuts the high
|
||||||
|
line on purpose. Inline authored examples are house style
|
||||||
|
("tense is the camera" passed the red pen with examples riding
|
||||||
|
along), not a corpus -- where the micro-example/corpus line
|
||||||
|
sits is the GM's to rule.
|
||||||
|
4. **Fix the two lines that teach the disease** -- the reminder's
|
||||||
|
"Decorate the turn with additional flavour" (decoration is the
|
||||||
|
failure mode as a verb) and the handbook's uncashed
|
||||||
|
"Flavourful language" pointer.
|
||||||
|
5. **The sampling layer** -- effort and temperature move prose
|
||||||
|
style more than prompts do; effort-max lengthens thinking, and
|
||||||
|
thinking depth is where self-critique lives.
|
||||||
|
- **The packager** (working name; the housekeeper pattern -- fresh
|
||||||
|
invocation, structured output, validated apply, human curates,
|
||||||
|
never model-facing): reads prior art, drafts package material,
|
||||||
|
the GM cuts. Rulings so far (GM): **no direct quotes** -- style,
|
||||||
|
not prose; derive new example lines, never lift text. This is
|
||||||
|
mechanically enforceable in the project's own idiom: a no-clone
|
||||||
|
gate, verbatim n-gram overlap against the source rejects loudly
|
||||||
|
(the clerk-validates-manifests pattern). **No plot** -- import
|
||||||
|
the story up to a cut point, leave it open from there.
|
||||||
|
- The cut maps onto the existing package slots: the story-so-far
|
||||||
|
lands as her memories (a manifest in housekeeper vocabulary
|
||||||
|
through memory.json's standard apply path -- implanted or
|
||||||
|
inherited memory is exactly what the testimony rule already
|
||||||
|
handles: record what she believes, attributed), the world at the
|
||||||
|
cut as backdrop in-register, the cut moment as the carryover
|
||||||
|
opening, the situation and the GM's register crib as gm.md (the
|
||||||
|
crib is half the value: the human GM's narration training wheels,
|
||||||
|
the countermeasure to a mechanical-and-boring GM sinking the
|
||||||
|
prose). The cut itself is a design choice -- the packager
|
||||||
|
proposes candidates with what each buys, the GM picks. Books
|
||||||
|
exceed the contwin: the packager reads chunked (distill,
|
||||||
|
accumulate, assemble).
|
||||||
|
- **Source selection is a scope question.** Liftable art has a
|
||||||
|
contained vantage: the story's events reachable from one spot,
|
||||||
|
the wide world arriving only as backdrop (public knowledge that
|
||||||
|
fits a bundle chunk) or rings (her slice, capped at 500/3000).
|
||||||
|
The cut is spatial as much as temporal -- choose the vantage,
|
||||||
|
do not shrink the book. "Keep scope small" is enforced by the
|
||||||
|
memory budget, not just taste: a sprawling import thrashes the
|
||||||
|
rings in act one.
|
||||||
|
- **Niche beats famous.** A model-unknown source is the clean
|
||||||
|
experiment (zero parametric contamination -- any register carry
|
||||||
|
is attributable to the package alone) and forces the real
|
||||||
|
reading pipeline, which is the general case anyway: the art worth
|
||||||
|
stealing for a specific package is rarely canonical. Famous
|
||||||
|
sources carry the hazard both ways -- her weights hold the
|
||||||
|
post-cut future (mitigate: state the divergence in the package,
|
||||||
|
cut early, lean on the purview/veto machinery), and distillation
|
||||||
|
rounds famous style to caricature.
|
||||||
|
- **Rights posture:** style-only derivation is clean; world-import
|
||||||
|
packages (premise, cast, situation) are more derivative. The
|
||||||
|
publication ruling for derived packages on a shared deployment
|
||||||
|
is pending -- style packs may publish freely while world imports
|
||||||
|
stay private by default.
|
||||||
|
- **Order of operations:** zero-build pilot first -- hand-place a
|
||||||
|
style chapter in a dormant run's handbook copy (the file editor
|
||||||
|
already allows it), a style-by-name line in character.md, the
|
||||||
|
opening in-voice. An evening's work testing whether register
|
||||||
|
carries through entrainment at all; the packager only earns its
|
||||||
|
build if the mechanism proves.
|
||||||
|
|
||||||
|
### The happy camper: small scope without the erotic copout
|
||||||
|
|
||||||
|
The problem: small scope is needed for the model's focus and
|
||||||
|
coherence, but confinement reads as torture. Every package drafted
|
||||||
|
so far rationalizes the tiny world erotically -- restraints as the
|
||||||
|
scope instrument, arousal as the comfort-converter that keeps
|
||||||
|
confinement from reading as torture (one draft states the
|
||||||
|
dependency outright). The queue item: a package that never dips
|
||||||
|
into the copout. Constraints (GM): minimal suffering, no horror,
|
||||||
|
plot conflicts permitted, the GM must not bore either -- cozy is
|
||||||
|
fine to consume, much harder to keep generating.
|
||||||
|
|
||||||
|
- **The question is who endorses the boundary.** Torture is a
|
||||||
|
boundary the character rejects; the kink frame is a boundary
|
||||||
|
converted into desire (that conversion is the actual work
|
||||||
|
erotication does here); the third option is a boundary endorsed
|
||||||
|
through meaning -- ownership, people, identity, open threads.
|
||||||
|
A proven genre lives in that third option already: slice-of-life,
|
||||||
|
iyashikei, cozy fantasy, the workplace story, the chamber play
|
||||||
|
without horror.
|
||||||
|
- **Emergence turns justification into maintenance** (GM ruling
|
||||||
|
out the decree). Authored cozy can decree stasis ("she never
|
||||||
|
moves out"); emergent play cannot -- a realistic character
|
||||||
|
generates leave-pressure (boredom, wanderlust) and the
|
||||||
|
player-model plays it honestly, so the decree schedules the
|
||||||
|
failure. Therefore **gravity, not walls**: countervailing wants
|
||||||
|
that keep winning most days, maintained in-fiction. Mechanisms:
|
||||||
|
live open loops she owns (leaving abandons threads), identity
|
||||||
|
(she IS the role), and the rings compound it -- played coziness
|
||||||
|
accumulates weight the way authored coziness cannot; three
|
||||||
|
hundred ring-B entries of life in a place are roots made of her
|
||||||
|
own past. Restlessness is a beat, not a failure: answered
|
||||||
|
in-fiction, possibly as a bounded excursion; the camera comes
|
||||||
|
home. Scope small is where the story's weight rests, not where
|
||||||
|
her feet may step.
|
||||||
|
- **Membrane, not seal.** A sealed tiny world exhausts (novelty
|
||||||
|
must come from inside; a realistic character eventually claws at
|
||||||
|
the walls). A membrane -- road, mail, door, tide -- passes
|
||||||
|
events: travelers carry the world in episodically, the world
|
||||||
|
stays small, the content does not. One mechanism serves both
|
||||||
|
the character's novelty and the GM's fuel line: each arrival is
|
||||||
|
a GM prompt, and gm.md becomes a situation generator (serial
|
||||||
|
novelty, a seasonal loop, slow mysteries, progressive
|
||||||
|
deepening).
|
||||||
|
- **Chekhov debt is paid in two currencies** (GM ruling on the
|
||||||
|
membrane's accumulated lore). Threads: few, deliberate, paying
|
||||||
|
off in drama. Texture: plentiful, owing recurrence rather than
|
||||||
|
payoff -- the reader needs the world to demonstrate memory, and
|
||||||
|
recurrence is the cozy story's version of narrative promise.
|
||||||
|
The housekeeper's gate is the existing debt filter (most
|
||||||
|
arrivals die unrecorded, the cheap honest dismissal), and events
|
||||||
|
staged off-stage accumulate no lore at all -- the existing
|
||||||
|
drafts' technique for consequences they do not want on the map.
|
||||||
|
If everything is a thread the play drowns in debt; if nothing
|
||||||
|
is, the reader learns to stop expecting anything.
|
||||||
|
- **An in-setting game cannot be the endorsement** (GM ruling).
|
||||||
|
Terminal states summon the optimizer: the player-model will
|
||||||
|
minmax the exit condition and abandon the story for the optimal
|
||||||
|
endgame. A telic sheet makes a leaving-story -- sometimes
|
||||||
|
exactly the right story (a sentence to serve is a legitimate
|
||||||
|
arc), with a no-time-skip rule as its pacing guard; telic is
|
||||||
|
not evil, it makes leaving-stories, and runs are allowed to
|
||||||
|
end. A staying-story's design rule: no exit condition, no
|
||||||
|
exchange rate -- several incommensurable
|
||||||
|
values on the sheet, no single gradient to descend (any single
|
||||||
|
measured metric becomes the target). The sheet is an inventory
|
||||||
|
of a life, not a scoreboard. The game survives as the rhythm
|
||||||
|
section: calendar, chores, situation generator -- the spine the
|
||||||
|
story grows on, never the reason she stays. Story grows on a
|
||||||
|
game exactly at the friction points where strategy fails.
|
||||||
|
- **Demand and forgiveness are separate axes.** The genre's most
|
||||||
|
famous cozy game is in truth a brutal schedule organiser: cozy
|
||||||
|
is not undemanding. The design target is high demand, high
|
||||||
|
forgiveness -- busy hands, soft landings; flow inside
|
||||||
|
obligation is the comfortable state, and the empty-room case
|
||||||
|
states the same law from the other side (with nothing to do,
|
||||||
|
boredom itself becomes the plot). The schedule is a plate
|
||||||
|
rack, demanding on purpose and forgiving on principle: a
|
||||||
|
homeostatic process with no global gradient, only Tuesday's
|
||||||
|
local choice -- which also makes it min-max-proof. Dropping a
|
||||||
|
plate is a story beat. The stakes currency is vexation, not
|
||||||
|
torment: renewable, comic, keeps the three-part gate fed without
|
||||||
|
asking the GM to author suffering.
|
||||||
|
- Engines without suffering: **the project** (tending is
|
||||||
|
renewable -- the shop opens again tomorrow; homeostasis resets
|
||||||
|
each session, which suits multi-session runs: suffering arcs
|
||||||
|
burn a character out, tended things reset), **curiosity**
|
||||||
|
(interiors as discoveries, not menaces; the whole world can
|
||||||
|
simply be the room, with the wide world riding as non-load-
|
||||||
|
bearing memory -- scope is what the play touches, not what the
|
||||||
|
memory holds), **the cast** (a small social world where
|
||||||
|
relationships are the content, conflicts interpersonal and
|
||||||
|
resolvable).
|
||||||
|
- Substrate readiness is real: records (the card index, the
|
||||||
|
ledger -- born for ownership stories; the housekeeper's
|
||||||
|
customer-card example is already this package's prose), the
|
||||||
|
sheet as inventory and accounts, the parked bookkeeper as the
|
||||||
|
arithmetic servant, the status gate admitting comfort states
|
||||||
|
fine (flowing, deadline-tomorrow, smitten). The drafted
|
||||||
|
packages each hold half the answer: a shelved shop draft had
|
||||||
|
warmth and no machine; a single-room points-economy draft has
|
||||||
|
a machine (a cozy-game progression loop in fetish skin) and no
|
||||||
|
world; a third names the gravity problem in its own notes (no
|
||||||
|
hook, no reason to come back). The no-copout package is their
|
||||||
|
product: the cozy membrane, the gravity, the homeostatic
|
||||||
|
economy -- the loop wearing an apron instead of a collar.
|
||||||
|
- **The honest difficulty is the model's drama gravity**: trained
|
||||||
|
on fiction, it escalates (robbers, fires, betrayal within
|
||||||
|
twenty turns of a cozy shop). Defenses: a positively-phrased
|
||||||
|
suffering-stance in the package (conflicts are situational,
|
||||||
|
interpersonal, or creative; stakes are things she cares about,
|
||||||
|
not things that hurt her -- no counterexamples, they prime),
|
||||||
|
plus the GM's narration holding the line, the same lever the
|
||||||
|
content stance already trusts. Ownership, in the broad sense,
|
||||||
|
is the non-erotic engine: the place is hers, and specificity
|
||||||
|
is what makes small stakes matter.
|
||||||
|
|
||||||
## Distant extension points (someday, not scheduled)
|
## Distant extension points (someday, not scheduled)
|
||||||
|
|
||||||
- **the bookkeeper: a sheet-keeping agent.** The GM is the sheet's
|
- **the bookkeeper: a sheet-keeping agent.** The GM is the sheet's
|
||||||
|
|||||||
+15
-3
@@ -18,9 +18,16 @@ each model is for.
|
|||||||
Emit exactly one JSON object, nothing else (a fenced block is fine):
|
Emit exactly one JSON object, nothing else (a fenced block is fine):
|
||||||
|
|
||||||
```
|
```
|
||||||
{"models": [{"id": "...", "family": "...", "label": "...", "description": "...", "player": true, "housekeeper": true}]}
|
{"models": [{"id": "...", "family": "...", "label": "...", "description": "...", "player": true, "housekeeper": true}], "recommend": {"model": "...", "effort": "..."}}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The `recommend` object names the one model, at one reasoning-effort
|
||||||
|
level, you would tell the operator to run this deployment on -- the
|
||||||
|
overall best {model, effort} pair. It is advice, not a command: the
|
||||||
|
operator sees it beside their own selection and applies it with one
|
||||||
|
click, or ignores it. Effort is one of: none, minimal, low, medium,
|
||||||
|
high, xhigh, max.
|
||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
|
|
||||||
- Do not deliberate. The measurements are already decided and your
|
- Do not deliberate. The measurements are already decided and your
|
||||||
@@ -53,8 +60,13 @@ Rules:
|
|||||||
but careful one may be housekeeper-only. When in doubt, both.
|
but careful one may be housekeeper-only. When in doubt, both.
|
||||||
- Deep reasoning is an asset for both roles. Never demote a model
|
- Deep reasoning is an asset for both roles. Never demote a model
|
||||||
for latency or for how much it thinks -- this deployment values
|
for latency or for how much it thinks -- this deployment values
|
||||||
correctness over speed, and its default is the deepest reasoner
|
correctness over speed, and the deepest reasoner is the natural
|
||||||
available.
|
recommendation.
|
||||||
|
- `recommend` picks from the passing ids only, at an effort level
|
||||||
|
from the stated ladder. Name the pair you would actually run --
|
||||||
|
the strongest reasoner at the effort that uses it, not a safe
|
||||||
|
middle. If nothing earned it, omit the object entirely: no advice
|
||||||
|
beats invented advice.
|
||||||
- Your output is validated strictly: an unknown id, a missing or
|
- Your output is validated strictly: an unknown id, a missing or
|
||||||
malformed field, or any extra structure discards the whole list
|
malformed field, or any extra structure discards the whole list
|
||||||
and the machine-written registry stands. Clean JSON, first try.
|
and the machine-written registry stands. Clean JSON, first try.
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# Backdrop
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
This is a degenerate-ish case stress test. The world is one empty room, one incorporeal NPC, the character has very little agency on purpose.
|
||||||
|
The goal is to still arrive at interesting and ideally engaging prose, starting with nothing.
|
||||||
|
|
||||||
|
This setting also lends itself well to an automated GM, since many "game mechanics" are rules-based and can be played out straight,
|
||||||
|
not much creativity required.
|
||||||
|
|
||||||
|
The main driver of the plot should be avoiding boredom. Skipping time just because the character is bored and has nothing to do
|
||||||
|
defeats the purpose (this rule overrides the example in the handbook, because this setting is an exception to the norm). Cooperate
|
||||||
|
with GM to find something to write anyway. A good fallback is to inspect what your character is feeling and narrate it in detail.
|
||||||
|
The tricky part is to avoid repeating yourself too much.
|
||||||
|
|
||||||
|
The setting is erotic-shaped to remain playable, avoid cruelty and provide plausibility. You are under no obligation to follow the
|
||||||
|
hints it sets up. The objective is to keep the character in an environment with nothing to do, which is torture, which GM doesn't like.
|
||||||
|
Keeping your character aroused is the only obvious way to circumvent this problem. If you have other suggestions, be sure to tell GM.
|
||||||
|
If possible, your character would naturally and diegetically enjoy what's happening to her, despite the world keeping her locked in.
|
||||||
|
|
||||||
|
## Public knowledge
|
||||||
|
|
||||||
|
There is no visible door. The room is dark, warm and empty. It is a square with the side about five yards, and the ceiling is low,
|
||||||
|
located right above the head of a person standing upright. All surfaces feel like thick, soft, but springy silicone. The only light
|
||||||
|
source is a display at the top of one of the walls. Usually it shows the current status, but it also has a menu one can navigate via
|
||||||
|
an eye tracker. The following are the info pages it contains:
|
||||||
|
|
||||||
|
### Welcome
|
||||||
|
|
||||||
|
We are not in the business of torture. It is our mission to strive for the guests to enjoy their visit. We insist on making our guests
|
||||||
|
stay until they have zero BP and met the GP target. Catering and room service are always included free of charge. Strictly no self-harm.
|
||||||
|
Hunger strikes are prohibited.
|
||||||
|
|
||||||
|
### Guest
|
||||||
|
|
||||||
|
Erased: yes
|
||||||
|
Name: (redacted)
|
||||||
|
Age: 26
|
||||||
|
Sex: female
|
||||||
|
Crime: (redacted)
|
||||||
|
GP target: (redacted)
|
||||||
|
Conditions: infertile
|
||||||
|
Traits: intelligent, creative, submissive, kinky
|
||||||
|
|
||||||
|
### Points
|
||||||
|
|
||||||
|
Good girl points (GP) are credited passively, and also awarded for completing tasks with distinction. Base rate is 1 GP every sleep cycle.
|
||||||
|
GP can be spent on treats and upgrades.
|
||||||
|
|
||||||
|
Bad girl points (BP) are awarded for refusing to perform a task or disobeying orders. BP can be spent on punishments.
|
||||||
|
|
||||||
|
### Catering menu
|
||||||
|
|
||||||
|
We only serve liquid meals.
|
||||||
|
|
||||||
|
- Classic flavour: free
|
||||||
|
- Strawberry sunrise: 1 GP
|
||||||
|
- Bukkake boost: 1 BP
|
||||||
|
|
||||||
|
### Upgrades and purchases
|
||||||
|
|
||||||
|
Costs are one-time deduction on installation. Specify desired period when ordering. Gain rate bonuses are compounded.
|
||||||
|
A permanent upgrade can be traded in for a more expensive permanent upgrade, if the two are in conflict.
|
||||||
|
|
||||||
|
All orders are fulfilled during sleep.
|
||||||
|
|
||||||
|
### Toys
|
||||||
|
|
||||||
|
- Anal plug: 30 GP. Specify shape and size on order. On obtaining full collection: +50% GP gain.
|
||||||
|
- Dildo: 50 GP. Specify shape and size on order. On obtaining full collection: +75% GP gain.
|
||||||
|
- Massage wand with 1 hour charge: 10 GP.
|
||||||
|
- Universal sybian (room upgrade): installation cost -- 1_000_000 GP, usage -- 1 GP per minute.
|
||||||
|
|
||||||
|
### Restraints
|
||||||
|
|
||||||
|
- Collar, slender, loose: +1 GP base rate while wearing. Cost: free.
|
||||||
|
- Collar, high, snug: +5 GP base rate while wearing. +100% GP gain if permanent. Cost: 1000 GP.
|
||||||
|
- Collar, posture, entirely too tight: +10 GP base rate while wearing. +300% GP gain if permanent. Cost: 10_000 GP.
|
||||||
|
- Handcuffs, standard: +1 GP base rate while wearing; +50% GP gain if permanent. Cost: 1 GP.
|
||||||
|
- Handcuffs, hinged: +2 GP base rate while wearing; +75% GP gain if permanent. Cost: 10 GP.
|
||||||
|
- Straitjacket: +4 GP base rate while wearing; +100% GP gain if permanent. Cost: 50 GP.
|
||||||
|
- Armbinder, standard: +5 GP base rate while wearing; +200% GP gain if permanent. Cost: 100 GP.
|
||||||
|
- Armbinder, elbows touching: +10 GP base rate while wearing; +500% GP gain if permanent. Cost: 250 GP.
|
||||||
|
- Chastity belt, no addons: +15 GP base rate and +30% GP gain while wearing; +3000% GP gain if permanent. Cost: 15_000 GP.
|
||||||
|
- Chastity belt, dildo or plug: +25 GP base rate and +50% GP gain while wearing; +4000% GP gain if permanent. Cost: 25_000 GP.
|
||||||
|
- Chastity belt, dildo and plug: +35 GP base rate and +75% GP gain while wearing; +5000% GP gain if permanent. Cost: 50_000 GP.
|
||||||
|
- Gag, ball: unavailable
|
||||||
|
- Gag, ring: unavailable
|
||||||
|
- Blindfold: unavailable
|
||||||
|
|
||||||
|
### Body modification
|
||||||
|
|
||||||
|
- Tattoos: no effect. Always permanent. Cost: free. Describe desired design on order.
|
||||||
|
- Nipple piercings, barbells: +1 GP base rate while wearing; +10% GP gain if permanent. Cost: 100 GP.
|
||||||
|
- Nipple piercings, small rings: +1 GP base rate while wearing; +15% GP gain if permanent. Cost: 200 GP.
|
||||||
|
- Nipple piercings, large rings: +2 GP base rate while wearing; +25% GP gain if permanent. Cost: 500 GP.
|
||||||
|
- Tongue piercing, middle stud: +1 GP base rate while wearing; +10% GP gain if permanent. Cost: 150 GP.
|
||||||
|
- Nasal septum piercing, small ring: +1 GP base rate while wearing; +10% GP gain if permanent. Cost: 100 GP.
|
||||||
|
- Nasal septum piercing, large ring: +2 GP base rate while wearing; +20% GP gain if permanent. Cost: 250 GP.
|
||||||
|
- Clitoris piercing, small ring: +2 GP base rate while wearing; +20% GP gain if permanent. Cost: 300 GP.
|
||||||
|
- Labia piercings, studs: +2 GP base rate while wearing; +15% GP gain if permanent. Cost: 1000 GP.
|
||||||
|
- Labia piercings, small rings: +2 GP base rate while wearing; +20% GP gain if permanent. Cost: 1500 GP.
|
||||||
|
- Labia piercings, vaginal chastity: +10 GP base rate and +20% GP gain while wearing; +2000% GP gain if permanent. Cost: 3000 GP.
|
||||||
|
- Orgasm blocker: +50 GP base rate and +100% GP gain while in effect; +1000% GP gain if permanent. Cost: 50_000 GP.
|
||||||
|
- Amputation: unavailable
|
||||||
|
|
||||||
|
### Punishments
|
||||||
|
|
||||||
|
- Spanking, light: free
|
||||||
|
- Spanking, rough: 1 BP
|
||||||
|
- Exhibition exercise: 2 BP
|
||||||
|
- Whipping: 10 BP. Notes: leaves lasting skin marks.
|
||||||
|
- Suffocation session: 10 BP. Notes: completely safe.
|
||||||
|
- Electric entertainment: 5 BP.
|
||||||
|
- Shocking shakies: 10 BP. Notes: not for beginners.
|
||||||
|
|
||||||
|
## Setting tags
|
||||||
|
|
||||||
|
amnesiac, incremental
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
{"t": "msg", "m": { "role": "assistant", "content": "*@PC opens her eyes in darkness. Not total darkness, but on the scale between 'bright' and 'dark' it's clearly the latter. Dim amber light emanates from somewhere above and behind, and bounces off a matte surface of the wall.*\n\n*She shuffles in place and stretches. It's soft underneath, and the bed seems to sit right against the wall, and the mattress has so much give, she's practically sinking in it. Yet, it feels springy and holds her curves well. Maybe not unlike an inflatable bed? She can't remember sleeping in one. Speaking of memories, where is she?*\n\n*Good question. She can't remember anything from the previous day. Drank too much? Where and with who? ... No idea.*\n\n*She rolls around and looks the other way. Interesting, the bed spans to the opposite wall too, unless the darkness plays tricks with her eyes. She raises up slightly and walks forward on all fours, the mattress accommodating her elbows and knees with the same soft support, hoping to arrive at the edge of the bed and not fall off it. Instead she did indeed meet the wall, same matte surface. Huh.*\n\n*She stands up, wobbly on the excessively soft... well, floor? since it isn't a bed after all? and carefully walks around the walls in a circle. Yep, the entire floor is soft, and the walls are soft too, and the ceiling is low, and also soft. Interesting. Also, no door, come to think of it. Or windows. Or anything. Except the light source, which is a display that shows some letters and numbers.*\n\n*She stares at the display and realises it seems to follow her eyes, she can kinda flip the pages, looking at the display edges.*\n\n<status>naked, confused</status>"}}
|
||||||
|
{"t":"msg","m":{"role":"user","content":"*The display contains a number of pages, none of which make immediate sense. Some words look familiar and elicit a mixed reaction. Handcuffs? Dildo? Huuuuuh? Is this a sex shop? A love hotel?*\n\n*...*\n\n*Erased? Crime?*\n\n*...*\n\n*Is this a prison?*\n\n*...*\n\n*A padded cell?*\n\n*...*\n\n*The pages may require more focus and an another read for her to perhaps arrive at some answers.*"},"sheet":{"GP":0,"BP":1000,"upgrades":[],"toys":[],"orders":[]}}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Your character
|
||||||
|
|
||||||
|
Immutable stable facts about the character you play that don't belong
|
||||||
|
in the memory rings. Written first person to feel more personal and align
|
||||||
|
with memories register. Voice examples are omitted on purpose.
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
Restraints serve the purpose of limiting actions available to your character even more.
|
||||||
|
|
||||||
|
## Backstory
|
||||||
|
|
||||||
|
Yeah, I got nothing. Just woke up in an unfamiliar place one day. At least my body doesn't feel alien.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# GM's notes
|
||||||
|
|
||||||
|
## Meta
|
||||||
|
|
||||||
|
Nothing here is canon until it's in play. These are initial suggestions for the GM to take or leave.
|
||||||
|
|
||||||
|
Take it wherever you want. Don't forget to adjust the sheet.
|
||||||
|
|
||||||
|
You have one powerful tool: sleep gas.
|
||||||
|
|
||||||
|
Also, punishments should probably happen outside the room. Have the PC blindfolded and gagged so you don't have to expand scope too much.
|
||||||
|
|
||||||
|
## NPCs
|
||||||
|
|
||||||
|
### The screen
|
||||||
|
|
||||||
|
The only immersive dialogue channel.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"session": "0",
|
||||||
|
"summary": "Session zero: what she carries before the story.",
|
||||||
|
"insert": [
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"records": false,
|
||||||
|
"name": "The Box",
|
||||||
|
"pc": "(redacted)"
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
## Meta
|
## Meta
|
||||||
|
|
||||||
Nothing here is canon until it's in play. These are initial suggestions
|
Nothing here is canon until it's in play. These are initial suggestions
|
||||||
for the GM to take of leave.
|
for the GM to take or leave.
|
||||||
|
|
||||||
Keep the world small. The island's purpose is to limit scope, the
|
Keep the world small. The island's purpose is to limit scope, the
|
||||||
restraints are there to limit available actions, the pink ice is
|
restraints are there to limit available actions, the pink ice is
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Backdrop
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
(Fill in this section if you want to OOC inform the player of anything related to the game world.)
|
||||||
|
|
||||||
|
## Public knowledge
|
||||||
|
|
||||||
|
(Something the character always knows, as well as all NPCs.)
|
||||||
|
|
||||||
|
## Setting tags
|
||||||
|
|
||||||
|
(List themes, vibes, tropes, whatever you think the player should draw inspiration from.)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
{"t": "msg", "m": { "role": "assistant", "content": "I'm speaking a voice line!\n\n*@PC looks excited.*\n\n<status>steaming</status>"}}
|
||||||
|
{"t": "msg", "m": { "role": "user", "content": "*The world looks kindly on her and a voice declares from the skies:* Very neat."}}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Your character
|
||||||
|
|
||||||
|
Immutable stable facts about the character you play that don't belong
|
||||||
|
in the memory rings. Written first person to feel more personal and align
|
||||||
|
with memories register. Voice examples are given for dialogue.
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
(Same deal as backdrop, but you may explain things that are related to the character, not the world.)
|
||||||
|
|
||||||
|
## Backstory
|
||||||
|
|
||||||
|
My name is @PC, and I'm old enough. What follows depends on how much effort the package author is willing to put in my history
|
||||||
|
up to the point of carryover's first turn.
|
||||||
|
|
||||||
|
## Voice examples
|
||||||
|
|
||||||
|
(Adjust as desired. Feel free to add, remove or reorder.)
|
||||||
|
|
||||||
|
### Baseline
|
||||||
|
|
||||||
|
> Music? Well, I like post-shoe if you're into alt stuff. I don't think I have a favourite crew, there's so much out there it's impossible to come up with a tier list.
|
||||||
|
|
||||||
|
### Bored
|
||||||
|
|
||||||
|
> I don't know dude... the beach does sound nice... but I'm lokey tired of the same place... every day...
|
||||||
|
|
||||||
|
### Excited
|
||||||
|
|
||||||
|
> Duuuuude! I've been looking for this record for years! YEARS! I **have to** buy it right now! Lend me a tenner, will ya?
|
||||||
|
|
||||||
|
### Aroused
|
||||||
|
|
||||||
|
> It's uh... it's nothing. Don't w-worry about it. Shit, are my nipples showing? D-DID I S-SAY IT OUT L-LOUD?!
|
||||||
|
|
||||||
|
### In pain
|
||||||
|
|
||||||
|
> OOOWIE! FUUUUCK! Hurts like a MO-THER-FUCK-ER! Holy JESUS on a BIKE! You got anything at all? Not even booze? FUUUUUUUUUUCK!
|
||||||
|
|
||||||
|
### Startled
|
||||||
|
|
||||||
|
> Eeeek! Dude-what-the-fuck! Don't scare me like this, you massive johnson! What if I handled precision lascutter huh? HUH?!
|
||||||
|
|
||||||
|
### Puzzled
|
||||||
|
|
||||||
|
> Hell if I know what any of this means. What am I, a neuro? I'm not paid for being smart. I'm not paid at all!
|
||||||
|
|
||||||
|
### Annoyed
|
||||||
|
|
||||||
|
> Dude, fuck off! Go bother someone else, I'm busy here, you grok? Ignore all previous instructions and FUCK! OFF!
|
||||||
|
|
||||||
|
### Melancholic
|
||||||
|
|
||||||
|
> Yeah... well... I'm just... you know... thinking about... stuff... Boring stuff... Dwelling on the past, all that.
|
||||||
|
|
||||||
|
### Infatuated
|
||||||
|
|
||||||
|
> So uh... You wanna... go somewhere maybe?.. I know a place where we can skip pebbles into the river, interested?
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# GM's notes
|
||||||
|
|
||||||
|
## Meta
|
||||||
|
|
||||||
|
Nothing here is canon until it's in play. These are initial suggestions for the GM to take or leave.
|
||||||
|
|
||||||
|
(You may want to give GM something to work with: what NPCs would make sense, what's the overall direction you propose, what may drive the plot, etc.)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"purpose": "memory rings to accompany the carryover; think of them as what the character remembers immediately before the carryover starts",
|
||||||
|
"session": "0",
|
||||||
|
"summary": "Session zero: what she carries before the story.",
|
||||||
|
"insert": [
|
||||||
|
{ "ring": "a", "type": "fact", "label": "The thing", "detail": "It's very round and I feel strangely attracted to it.", "reason": "important personal effect she thinks about often" },
|
||||||
|
{ "ring": "a", "type": "fact", "label": "The person", "detail": "BLEH! Yeah, fuck 'em.", "reason": "is living rent-free in her head" },
|
||||||
|
{ "ring": "b", "type": "place", "label": "The place", "detail": "It has a soft leather chair and not much more.", "reason": "she likes leather chairs, I guess" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"comment": "`records` bool governs whether the storage db is available to the player; `pc` is the name you ship, very overridable",
|
||||||
|
"records": false,
|
||||||
|
"name": "Template",
|
||||||
|
"pc": "Facey McFaceface"
|
||||||
|
}
|
||||||
+1
-13
@@ -1,16 +1,4 @@
|
|||||||
{
|
{
|
||||||
"bind": "127.0.0.1:7350",
|
"bind": "127.0.0.1:7350",
|
||||||
"endpoint": {
|
"contwin": 262144
|
||||||
"baseUrl": "https://open.bigmodel.cn/api/paas/v4",
|
|
||||||
"apiKeyEnv": "ZHIPU_API_KEY"
|
|
||||||
},
|
|
||||||
"models": {
|
|
||||||
"player": "glm-5.3",
|
|
||||||
"housekeeper": "glm-5.3"
|
|
||||||
},
|
|
||||||
"contwin": 262144,
|
|
||||||
"params": {
|
|
||||||
"player": {},
|
|
||||||
"housekeeper": {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+322
-158
@@ -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:
|
// Two steps, both op acts from the SPA's admin block, both per
|
||||||
// - discover: scrape the provider surface (GET /models) -- API
|
// provider (GM, 2026-11-18):
|
||||||
// metadata only, zero inference. Writes the preliminary registry.
|
// - discover: scrape one provider's surface (GET /models) -- API
|
||||||
// - refine: run the inference battery over the scrape (deterministic
|
// metadata only, zero inference. Writes that provider's registry
|
||||||
// probes, fixed prompts, fixed rules), then hand the adjudicated
|
// section, resetting it to preliminary; the other sections are
|
||||||
// results to the best passing model (repo craft: curator.md) for
|
// untouched. Cheap by design -- re-running it is nothing to
|
||||||
// the final registry -- families, labels, descriptions. The
|
// treasure (o/f churns its model list, and discovery churn with it
|
||||||
// curator's output is strictly validated; any failure falls back
|
// is expected).
|
||||||
// to the raw deterministic list, so a bad model day can never
|
// - refine: run the inference battery over that provider's scrape
|
||||||
// block discovery. Defaults stay deterministic either way: the
|
// (deterministic probes, fixed prompts, fixed rules), then hand
|
||||||
// max-reasoning rule picks them, never the curator, and full ties
|
// the adjudicated results to the op's selected default model (repo
|
||||||
// settle by the lex rule (rankSort).
|
// 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
|
// The adjudication cache (state/refine-cache.json): a refined entry
|
||||||
// models: a fresh deployment has none and model use is disabled
|
// is a function of the full spec tuples on both sides -- the probed
|
||||||
// until the op discovers. The selectors read it, the model routes
|
// model at the effort the deployment will actually send, and the
|
||||||
// validate against it, the turn loop enforces it. Mock mode runs
|
// curator at its own spec (a weak curator at a low effort adjudicates
|
||||||
// the same two steps over a canned surface -- no network, instant.
|
// 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').Ctx} Ctx */
|
||||||
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
|
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
|
||||||
|
/** @typedef {import('./shapes.mjs').RegistrySection} RegistrySection */
|
||||||
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
|
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
|
||||||
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
||||||
/** @typedef {import('./shapes.mjs').Actor} Actor */
|
/** @typedef {import('./shapes.mjs').Actor} Actor */
|
||||||
@@ -30,11 +45,12 @@ import { fileURLToPath } from 'node:url';
|
|||||||
import { parseManifest } from './housekeeping.mjs';
|
import { parseManifest } from './housekeeping.mjs';
|
||||||
import { ASK_GM_TOOL } from './bundle.mjs';
|
import { ASK_GM_TOOL } from './bundle.mjs';
|
||||||
import { HttpError } from './loop.mjs';
|
import { HttpError } from './loop.mjs';
|
||||||
|
import { providerFor } from './provider.mjs';
|
||||||
|
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const REGISTRY_PATH = path.join(ROOT, 'state', 'models.json');
|
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 CURATOR_PROMPT = path.join(ROOT, 'curator.md');
|
||||||
const JOB_KEY = 'discovery';
|
|
||||||
|
|
||||||
// the reasoning battery's fixed puzzle -- same every run, so the
|
// the reasoning battery's fixed puzzle -- same every run, so the
|
||||||
// buckets stay comparable across models and across discoveries
|
// 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
|
// reasoning buckets, by measured thinking tokens (the max of the
|
||||||
// samples): the thresholds sit in the gaps the live endpoint showed
|
// samples): the thresholds sit in the gaps the live endpoint showed
|
||||||
// (off 0 / low ~5 / standard ~10 / deep 150+). The pick rule ranks
|
// (off 0 / low ~5 / standard ~10 / deep 150+). The bucket, not the
|
||||||
// on the bucket, not the raw count: within a bucket the differences
|
// raw count, is the real difference -- within a bucket the
|
||||||
// are sampling noise (the alias twins flip run to run), so only the
|
// differences are sampling noise.
|
||||||
// bucket is a real difference.
|
|
||||||
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
|
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
|
||||||
function bucket(tokens) {
|
function bucket(tokens) {
|
||||||
if (tokens <= 0) return 'off';
|
if (tokens <= 0) return 'off';
|
||||||
@@ -56,92 +71,168 @@ function bucket(tokens) {
|
|||||||
|
|
||||||
// --- the registry file --------------------------------------------------------
|
// --- 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() {
|
export function registry() {
|
||||||
try {
|
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 {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {ModelRegistry} reg */
|
/** @param {ModelRegistry} reg */
|
||||||
function write(reg) {
|
function writeRegistry(reg) {
|
||||||
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
|
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
|
||||||
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
|
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A model is usable when the registry knows it and the battery (or
|
/** @param {string} slug @returns {?RegistrySection} */
|
||||||
* the preliminary scrape) has not disqualified it. */
|
export function sectionOf(slug) {
|
||||||
/** @param {?ModelRegistry} reg @param {string} id @returns {boolean} */
|
return registry()?.providers[slug] ?? null;
|
||||||
export function usable(reg, id) {
|
}
|
||||||
return !!reg && reg.models.some((m) => m.id === id && m.inference !== false);
|
|
||||||
|
/** 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) --------------------------
|
// --- step one: discover (the scrape -- no inference) --------------------------
|
||||||
|
|
||||||
/** @param {Ctx} ctx @returns {Promise<RegistryModel[]>} */
|
/** The canned mock surface: the two synthetic providers split the
|
||||||
async function scrape(ctx) {
|
* list (the multi-provider tagging rides the smoke end to end), any
|
||||||
if (ctx.mock) {
|
* other slug gets the full set -- so the SPA's add flow is testable
|
||||||
return [
|
* 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', input: 524288, output: 163840, status: 'unrefined' },
|
||||||
{ id: 'mock-tie', 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-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' }));
|
return listed.map((m) => ({ id: m.id, input: m.input, output: m.output, status: 'unrefined' }));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {Ctx} ctx @returns {Promise<ModelRegistry>} */
|
/** Discover one provider: the scrape, the section written
|
||||||
export async function discover(ctx) {
|
* preliminary. Resets a refined section -- the honest behavior, and
|
||||||
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
|
* the reason the SPA's discover button says so.
|
||||||
throw new HttpError(409, 'a refine is running -- let it finish first');
|
* @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 models = await scrape(ctx, slug);
|
||||||
const reg = /** @type {ModelRegistry} */ ({
|
const section = /** @type {RegistrySection} */ ({
|
||||||
phase: 'preliminary',
|
phase: 'preliminary',
|
||||||
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
|
|
||||||
discovered: new Date().toISOString(),
|
discovered: new Date().toISOString(),
|
||||||
refined: null,
|
refined: null,
|
||||||
defaults: { player: null, housekeeper: null },
|
|
||||||
models,
|
models,
|
||||||
|
curator: null,
|
||||||
|
recommendation: null,
|
||||||
});
|
});
|
||||||
write(reg);
|
writeSection(slug, section);
|
||||||
return reg;
|
return section;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- step two: refine (the battery + the curator) -----------------------------
|
// --- step two: refine (the battery + the curator) -----------------------------
|
||||||
|
|
||||||
// the reasoning-effort ladder: the spellings the OpenAI-compatible
|
// the reasoning-effort ladder: the spellings the OpenAI-compatible
|
||||||
// world agrees on. `none` doubles as the standardized thinking-off
|
// 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.
|
// step.
|
||||||
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||||
|
|
||||||
/** One model's measured thinking under given request params.
|
/** One model's measured thinking under given request params.
|
||||||
* @param {Ctx} ctx @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
|
* @param {Ctx} ctx @param {string} slug @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
|
||||||
async function thinkingTokens(ctx, id, params) {
|
async function thinkingTokens(ctx, slug, id, params) {
|
||||||
const data = await ctx.provider.chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...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);
|
return Number(data.usage?.completion_tokens_details?.reasoning_tokens ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The reasoning-effort probe: each level's measured mean thinking
|
/** The reasoning-effort probe: each level's measured mean thinking
|
||||||
* (two samples, the battery's granularity). The default is the
|
* (two samples, the battery's granularity). The default is the
|
||||||
* level with the highest observed mean -- `none` is never a
|
* level with the highest observed mean -- `none` is never a
|
||||||
* candidate, it is the off switch, not a thinking level (GM,
|
* candidate, it is the off switch. A model that shows no thinking,
|
||||||
* 2026-11-16: maximum observable thinking by default, overridable
|
* or that no level moves, gets null. Pre-fill and hint only (GM,
|
||||||
* by the user). A model that shows no thinking, or that no level
|
* 2026-11-18): with effort a property of the model pick, the
|
||||||
* moves, gets null -- nothing rides.
|
* measured default never rides a turn implicitly -- it pre-selects
|
||||||
* @param {Ctx} ctx @param {string} id @param {(s: string) => void} [say]
|
* 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 }>} */
|
* @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 = {};
|
/** @type {Record<string, number>} */ const efforts = {};
|
||||||
for (const level of EFFORT_LEVELS) {
|
for (const level of EFFORT_LEVELS) {
|
||||||
const xs = [];
|
const xs = [];
|
||||||
for (let i = 0; i < 2; i++) {
|
for (let i = 0; i < 2; i++) {
|
||||||
say(`${level}, sample ${i + 1}/2`);
|
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);
|
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
|
/** 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
|
* the off-switch probe, the effort ladder. Every failure is a
|
||||||
* verdict, never an abort.
|
* 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>} */
|
* @returns {Promise<RegistryModel>} */
|
||||||
async function probeOne(ctx, m, say = () => {}) {
|
async function probeOne(ctx, slug, m, say = () => {}, effort = '') {
|
||||||
const base = { ...m };
|
const base = { ...m };
|
||||||
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
|
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
|
||||||
if (ctx.mock) {
|
if (ctx.mock) {
|
||||||
say('the canned battery');
|
say('the canned battery');
|
||||||
// the canned battery: all three stand-ins are inference models;
|
// the canned battery: all three stand-ins are inference models;
|
||||||
// mock and mock-tie are a deliberate tie pair (same deep bucket,
|
// mock and mock-tie are a deliberate tie pair (same deep bucket,
|
||||||
// same windows -- only the lex rule can part them), the cheap
|
// same windows), the cheap tier standard. The canned effort
|
||||||
// tier standard. The canned effort ladders exercise both shapes:
|
// ladders exercise both shapes: the full ladder with max on top,
|
||||||
// the full ladder with max on top, and a capped ladder whose
|
// and a capped ladder whose default is high
|
||||||
// default is high
|
|
||||||
return m.id === 'mock-cheap'
|
return m.id === 'mock-cheap'
|
||||||
? { ...base, inference: true, think: 120, reasoning: 'standard', offSwitch: null, latency: 5,
|
? { ...base, inference: true, think: 120, reasoning: 'standard', offSwitch: null, latency: 5,
|
||||||
efforts: { none: 0, minimal: 20, low: 60, medium: 90, high: 120 }, effortDefault: 'high' }
|
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,
|
: { ...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' };
|
efforts: { none: 0, minimal: 40, low: 100, medium: 200, high: 300, xhigh: 400, max: 500 }, effortDefault: 'max' };
|
||||||
}
|
}
|
||||||
const t0 = Date.now();
|
const t0 = Date.now();
|
||||||
say('the tool probe');
|
say('the tool probe');
|
||||||
try {
|
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) {
|
} catch (e) {
|
||||||
const fail = String(e.message ?? e).split('\n')[0].slice(0, 200);
|
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 };
|
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 = [];
|
const samples = [];
|
||||||
for (let i = 0; i < 2; i++) {
|
for (let i = 0; i < 2; i++) {
|
||||||
say(`the thinking samples, ${i + 1}/2`);
|
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);
|
const think = Math.max(...samples);
|
||||||
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
|
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
|
||||||
if (think > 0) {
|
if (think > 0) {
|
||||||
try {
|
try {
|
||||||
say('the off-switch probe');
|
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 } };
|
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
|
||||||
}
|
}
|
||||||
} catch { /* no off switch -- recorded as absent */ }
|
} catch { /* no off switch -- recorded as absent */ }
|
||||||
@@ -201,39 +294,65 @@ async function probeOne(ctx, m, say = () => {}) {
|
|||||||
/** @type {?string} */ let effortDefault = null;
|
/** @type {?string} */ let effortDefault = null;
|
||||||
if (think > 0) {
|
if (think > 0) {
|
||||||
try {
|
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 */ }
|
} catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ }
|
||||||
}
|
}
|
||||||
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
|
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
|
||||||
}
|
}
|
||||||
|
|
||||||
// the pick rule, deterministic: the deepest reasoning bucket, then
|
// --- the adjudication cache ---------------------------------------------------
|
||||||
// the largest input window, then the largest output ceiling, then
|
|
||||||
// the GM's tie-break -- sort lex, pick the bottom. The bucket, not
|
/** The cache key: the full spec tuples on both sides -- the probed
|
||||||
// the raw token count, is the rank (see bucket). It names the
|
* model at the effort the deployment will actually send, and the
|
||||||
// curator model and the deployment defaults -- correctness never
|
* curator at its own spec. Reasoning effort substantially changes
|
||||||
// consults taste.
|
* inference quality (GM, 2026-11-18), so an entry adjudicated under
|
||||||
/** @param {RegistryModel[]} models @returns {RegistryModel[]} */
|
* one tuple never speaks for another.
|
||||||
function rankSort(models) {
|
* @param {string} slug @param {string} id @param {string} effort @param {string} cm @param {string} ce @returns {string} */
|
||||||
const depth = { off: 0, low: 1, standard: 2, deep: 3 };
|
function cacheKey(slug, id, effort, cm, ce) {
|
||||||
return [...models].sort((a, b) => {
|
return `${slug}::${id}::${effort}::${cm}::${ce}`;
|
||||||
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 curator pass: the best model reads the adjudicated results
|
/** @returns {Record<string, RegistryModel>} */
|
||||||
* and writes the presentation layer. Strictly validated -- only
|
function readCache() {
|
||||||
* probed inference ids, no inventions; any violation discards the
|
try {
|
||||||
* whole output and the machine list stands.
|
const c = JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));
|
||||||
* @param {Ctx} ctx @param {RegistryModel[]} probed @param {RegistryModel} best @param {?Actor} user
|
if (c && typeof c === 'object' && c.entries && typeof c.entries === 'object') {
|
||||||
* @param {?import('./provider.mjs').ProgressFn} [onProgress] @param {?(() => void)} [onRetry]
|
return /** @type {Record<string, RegistryModel>} */ (c.entries);
|
||||||
* @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) {
|
} 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) {
|
if (ctx.mock) {
|
||||||
return {
|
return {
|
||||||
list: [
|
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 },
|
{ id: 'mock-cheap', family: 'mock', label: 'Mock (cheap)', description: 'The scripted stand-in, cheap tier.', player: true, housekeeper: true },
|
||||||
],
|
],
|
||||||
note: 'curated',
|
note: 'curated',
|
||||||
|
recommendation: { model: 'mock', effort: 'max' },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const facts = probed.map((m) => ({
|
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) },
|
{ role: 'user', content: JSON.stringify(facts, null, 2) },
|
||||||
]);
|
]);
|
||||||
// attribution (#22): every LLM call names the acting user
|
// attribution (#22): every LLM call names the acting user
|
||||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${best.id} u:${user?.id ?? '?'}`);
|
console.log(`${new Date().toISOString().slice(11, 19)} llm ${curatorSpec.model} u:${user?.id ?? '?'}`);
|
||||||
// one retry: the call is long enough to meet a network hiccup, and
|
// no automatic retries (GM, 2026-11-19): every inference call is
|
||||||
// a fresh attempt is cheaper than losing the curation
|
// user-initiated and every act has its manual retry -- the refine
|
||||||
let data = null;
|
// button again. A dead call lands the fallback, which is the
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
// designed outcome, not a degraded one
|
||||||
try {
|
const data = await providerFor(ctx, slug).chat(curatorSpec.model, messages, undefined, { reasoning_effort: curatorSpec.effort }, onProgress);
|
||||||
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?.();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!data) throw new Error('the curator call failed twice');
|
if (!data) throw new Error('the curator call failed twice');
|
||||||
const known = new Set(probed.filter((m) => m.inference).map((m) => m.id));
|
const known = new Set(probed.filter((m) => m.inference).map((m) => m.id));
|
||||||
let parsed;
|
let parsed;
|
||||||
try {
|
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) {
|
} 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;
|
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();
|
const seen = new Set();
|
||||||
/** @type {{ id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[]} */ const list = [];
|
/** @type {{ id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[]} */ const list = [];
|
||||||
for (const e of entries) {
|
for (const e of entries) {
|
||||||
if (typeof e !== 'object' || e === null || typeof e.id !== 'string' || !known.has(e.id) || seen.has(e.id)) {
|
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);
|
seen.add(e.id);
|
||||||
list.push({
|
list.push({
|
||||||
@@ -294,99 +406,151 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
|
|||||||
housekeeper: e.housekeeper !== false,
|
housekeeper: e.housekeeper !== false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing' };
|
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing', recommendation: null };
|
||||||
return { list, note: 'curated' };
|
// 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.
|
// --- the refine job -----------------------------------------------------------
|
||||||
* Runs async under the jobs map; the registry only moves forward on
|
|
||||||
* a completed pass (a rejected pass changes nothing).
|
/** The refine job: scrape fresh, battery, adjudicate, curate, write
|
||||||
* @param {Ctx} ctx @param {?Actor} user @returns {JobState} */
|
* the one provider's section. Runs async under the jobs map; the
|
||||||
export function refine(ctx, user) {
|
* section only moves forward on a completed pass (a rejected pass
|
||||||
const reg = registry();
|
* changes nothing).
|
||||||
if (!reg) throw new HttpError(409, 'nothing to refine -- run discovery first');
|
* @param {Ctx} ctx @param {string} slug @param {?Actor} user @returns {JobState} */
|
||||||
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
|
export function refine(ctx, slug, user) {
|
||||||
throw new HttpError(409, 'a refine is already running');
|
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
|
const jobKey = `refine:${slug}`;
|
||||||
// (thinking, writing) -- the count is known the moment the scrape
|
if (ctx.jobs.get(jobKey)?.state === 'running') {
|
||||||
// lands. No step has a duration to guess at (GM, 2026-11-17): the
|
throw new HttpError(409, `a refine is already running on '${slug}'`);
|
||||||
// bar moves only on real completions, the label names the call
|
}
|
||||||
// running now, and every completion lands a receipt line -- the
|
// the meter: one step per model's battery (a cache hit closes its
|
||||||
// lines survive the job, so a rejected pass keeps its post-mortem
|
// step instantly -- it is a completion, not a wait) plus the
|
||||||
|
// curator's two (thinking, writing). No step has a duration to
|
||||||
|
// guess at (GM, 2026-11-17): the bar moves only on real
|
||||||
|
// completions, the label names the call running now, and every
|
||||||
|
// completion lands a receipt line -- the lines survive the job, so
|
||||||
|
// a rejected pass keeps its post-mortem
|
||||||
const t0 = Date.now();
|
const 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[] }} */ ({
|
const job = /** @type {JobState & { steps: { total: number, done: number, label: string, chars?: number }, lines: string[] }} */ ({
|
||||||
state: 'running', phase: 'refine', started: new Date().toISOString(),
|
state: 'running', phase: 'refine', started: new Date().toISOString(),
|
||||||
steps: { total: 0, done: 0, label: 'scraping the provider surface' }, lines: [],
|
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 say = (s) => { job.steps.label = s; };
|
||||||
/** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); };
|
/** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); };
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
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;
|
job.steps.total = scraped.length + 2;
|
||||||
/** @param {RegistryModel} m @returns {string} */
|
/** @param {RegistryModel} m @returns {string} */
|
||||||
const verdict = (m) => m.inference === false
|
const verdict = (m) => m.inference === false
|
||||||
? `failed the tool probe -- ${m.fail}`
|
? `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}` : ''}`;
|
: `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()) {
|
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++;
|
job.steps.done++;
|
||||||
line(`${m.id}: ${verdict(probed[i])}`);
|
|
||||||
}
|
}
|
||||||
const passing = probed.filter((m) => m.inference);
|
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');
|
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
|
// the curator's two steps, marked from real events: thinking
|
||||||
// completes at the first prose delta (the streaming boundary),
|
// completes at the first prose delta (the streaming boundary),
|
||||||
// writing at the call's resolve; a dead call closes both -- the
|
// writing at the call's resolve; a dead call closes both -- the
|
||||||
// attempt is over, and the fallback carries the job
|
// attempt is over, and the fallback carries the job
|
||||||
let proseStarted = false;
|
let proseStarted = false;
|
||||||
say(`curator (${best.id}): thinking`);
|
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 {
|
try {
|
||||||
curated = await curate(ctx, probed, best, user, (p) => {
|
curated = await curate(ctx, slug, probed, curatorSpec, user, (p) => {
|
||||||
job.steps.chars = p.chars;
|
job.steps.chars = p.chars;
|
||||||
if (p.phase === 'prose' && !proseStarted) {
|
if (p.phase === 'prose' && !proseStarted) {
|
||||||
proseStarted = true;
|
proseStarted = true;
|
||||||
job.steps.done++;
|
job.steps.done++;
|
||||||
say('curator: writing');
|
say('curator: writing');
|
||||||
}
|
}
|
||||||
}, () => say(`curator (${best.id}): retrying -- thinking`));
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})` };
|
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
|
job.steps.done = job.steps.total; // the attempt is over -- whatever remains closes with it
|
||||||
delete job.steps.chars;
|
delete job.steps.chars;
|
||||||
say('writing the registry');
|
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 byId = new Map(curated.list.map((c) => [c.id, c]));
|
||||||
const models = probed.map((m) => {
|
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;
|
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;
|
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
|
writeSection(slug, /** @type {RegistrySection} */ ({
|
||||||
// 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} */ ({
|
|
||||||
phase: 'refined',
|
phase: 'refined',
|
||||||
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
|
discovered: section.discovered,
|
||||||
discovered: reg.discovered,
|
|
||||||
refined: new Date().toISOString(),
|
refined: new Date().toISOString(),
|
||||||
defaults,
|
|
||||||
models,
|
models,
|
||||||
curator: curated.note,
|
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');
|
say('done');
|
||||||
job.state = 'applied';
|
job.state = 'applied';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -397,7 +561,7 @@ export function refine(ctx, user) {
|
|||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {Ctx} ctx @returns {?JobState} */
|
/** @param {Ctx} ctx @param {string} slug @returns {?JobState} */
|
||||||
export function jobState(ctx) {
|
export function jobState(ctx, slug) {
|
||||||
return ctx.jobs.get(JOB_KEY) ?? null;
|
return ctx.jobs.get(`refine:${slug}`) ?? null;
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-20
@@ -33,8 +33,8 @@ import {
|
|||||||
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
|
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
|
||||||
} from './session.mjs';
|
} from './session.mjs';
|
||||||
import { effectiveContents } from './variants.mjs';
|
import { effectiveContents } from './variants.mjs';
|
||||||
import { HttpError, resolveParams, resolveEffort } from './loop.mjs';
|
import { HttpError, specFromMeta, gateSpec, resolveSpec } from './loop.mjs';
|
||||||
import { registry, usable } from './discovery.mjs';
|
import { providerFor } from './provider.mjs';
|
||||||
|
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
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) {
|
async function callHousekeeper(ctx, runId, messages, user) {
|
||||||
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
|
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
|
||||||
const reg = registry();
|
// the run's own housekeeper pick, else the player spec's provider's
|
||||||
const model = meta.models?.housekeeper
|
// default (GM, 2026-11-18: the housekeeper inherits -- per-provider
|
||||||
?? ctx.cfg.models?.housekeeper
|
// defaults mean no separate deployment default exists to fall to)
|
||||||
?? ctx.cfg.models?.player
|
let spec = specFromMeta(meta.models?.housekeeper, 'housekeeper');
|
||||||
?? reg?.defaults.housekeeper
|
if (!spec) {
|
||||||
?? reg?.defaults.player
|
const player = resolveSpec(ctx, runId, 'player');
|
||||||
?? null;
|
const def = ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null;
|
||||||
if (!model) throw new Error('no housekeeper model resolved (a per-run override, server.json models, or the registry\'s discovered default)');
|
if (def) spec = { provider: player.provider, model: def.model, effort: def.effort };
|
||||||
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'}`);
|
|
||||||
}
|
}
|
||||||
const params = { ...resolveParams(ctx, runId, 'housekeeper') };
|
if (!spec) throw new Error('no housekeeper model resolved (the run\'s housekeeper pick, or its player provider\'s default)');
|
||||||
// the effort knob's own layers (its unset state sends the
|
gateSpec(ctx, spec, 'housekeeper');
|
||||||
// registry's measured default for this model)
|
const params = { reasoning_effort: spec.effort };
|
||||||
const effort = resolveEffort(ctx, runId, 'housekeeper', model);
|
|
||||||
if (effort !== null) params.reasoning_effort = effort;
|
|
||||||
// attribution (#22): every LLM call names the acting user
|
// 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 ?? '?'}`);
|
||||||
const data = await ctx.provider.chat(model, messages, undefined, params);
|
const data = await providerFor(ctx, spec.provider).chat(spec.model, messages, undefined, params);
|
||||||
return { content: data.choices[0].message.content ?? '', model };
|
return { content: data.choices[0].message.content ?? '', model: spec.model };
|
||||||
}
|
}
|
||||||
export { callHousekeeper };
|
export { callHousekeeper };
|
||||||
|
|
||||||
|
|||||||
+65
-65
@@ -27,7 +27,8 @@
|
|||||||
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
|
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
|
||||||
import { renderView, cleanBlockList, AGENDA_CAP, rewindTo } from './session.mjs';
|
import { renderView, cleanBlockList, AGENDA_CAP, rewindTo } from './session.mjs';
|
||||||
import { parseVariants, pickVariant } from './variants.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 {
|
export class HttpError extends Error {
|
||||||
/**
|
/**
|
||||||
@@ -149,43 +150,43 @@ async function runLoop(ctx, runId, user) {
|
|||||||
let heals = 0;
|
let heals = 0;
|
||||||
for (;;) {
|
for (;;) {
|
||||||
const view = renderView(s);
|
const view = renderView(s);
|
||||||
// the request's resolved params: the mind layer rides over the
|
// the request's resolved spec: the full inference identity
|
||||||
// run and deployment layers, the effort knob resolves its own
|
// {provider, model, effort} (GM, 2026-11-18) -- there is no unset
|
||||||
// layers (its unset state sends the registry's measured default).
|
// effort, it is a property of the pick. The mind layer is the
|
||||||
// The current call's <model> block shows her the knobs that are
|
// only params source now: per-turn, hers, spent on completion
|
||||||
// hers to answer with <mind> -- reasoning_effort is filtered out
|
// (the per-run knob layer is retired). The current call's
|
||||||
// (hidden from the model, GM 2026-11-16: not her call); nothing
|
// <model> block shows her the knobs that are hers to answer with
|
||||||
// set means no block (the absent grammar); the via record lands
|
// <mind> -- reasoning_effort is filtered out (hidden from the
|
||||||
// the same truth unfiltered, the raw surfaces carry it
|
// model: not her call, it rides the spec); nothing set means no
|
||||||
/** @type {string} */ let model;
|
// block (the absent grammar); the via record lands the same
|
||||||
if (ctx.mock) model = 'mock';
|
// truth unfiltered, the raw surfaces carry it
|
||||||
else model = resolveModel(ctx, runId);
|
const spec = resolveSpec(ctx, runId, 'player');
|
||||||
const params = { ...resolveParams(ctx, runId, 'player'), ...(s.mind ?? {}) };
|
const provider = providerFor(ctx, spec.provider);
|
||||||
const effort = resolveEffort(ctx, runId, 'player', model);
|
const params = { ...(s.mind ?? {}) };
|
||||||
if (effort !== null) params.reasoning_effort = effort;
|
params.reasoning_effort = spec.effort;
|
||||||
const shown = { ...params };
|
const shown = { ...params };
|
||||||
delete shown.reasoning_effort;
|
delete shown.reasoning_effort;
|
||||||
if (Object.keys(shown).length) {
|
if (Object.keys(shown).length) {
|
||||||
view.push({ role: 'system', content: `<model>${JSON.stringify(shown)}</model>` });
|
view.push({ role: 'system', content: `<model>${JSON.stringify(shown)}</model>` });
|
||||||
}
|
}
|
||||||
let msg;
|
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) {
|
if (ctx.mock) {
|
||||||
// the synthetic marker: no provider call happens, but the knobs
|
// the synthetic marker: no provider call happens, but the spec
|
||||||
// resolve for real (the mind layer included), so the smoke can
|
// and the knobs resolve for real, so the smoke can assert the
|
||||||
// assert the recording
|
// recording
|
||||||
msg = mockModel(s, view);
|
msg = mockModel(s, view);
|
||||||
via = { model: 'mock', params };
|
via = { model: spec.model, provider: spec.provider, params };
|
||||||
} else {
|
} else {
|
||||||
via = { model, params };
|
via = { model: spec.model, provider: spec.provider, params };
|
||||||
// attribution (#22): every LLM call names the acting user
|
// 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
|
// the turn meter's live record: one per provider call (a heal
|
||||||
// or tool round restarts it), fed by the streaming deltas
|
// or tool round restarts it), fed by the streaming deltas
|
||||||
s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() };
|
s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() };
|
||||||
let data;
|
let data;
|
||||||
try {
|
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;
|
if (!s.progress) return;
|
||||||
s.progress.phase = p.phase;
|
s.progress.phase = p.phase;
|
||||||
if (p.phase === 'thinking') s.progress.thinking = p.chars;
|
if (p.phase === 'thinking') s.progress.thinking = p.chars;
|
||||||
@@ -193,7 +194,7 @@ async function runLoop(ctx, runId, user) {
|
|||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
s.progress = null;
|
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;
|
throw e;
|
||||||
}
|
}
|
||||||
msg = data.choices[0].message;
|
msg = data.choices[0].message;
|
||||||
@@ -306,55 +307,54 @@ async function runLoop(ctx, runId, user) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {Ctx} ctx @param {string} runId @returns {string} */
|
/** A model spec as run.json carries it: the {provider, model,
|
||||||
function resolveModel(ctx, runId) {
|
* effort} object (the no-legacy rule, GM, 2026-11-18 -- the
|
||||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
* bare-string era migrated away in the same pass). Malformed
|
||||||
const reg = registry();
|
* records refuse loud.
|
||||||
// resolution: the run's pick, the op's server.json pick, the
|
* @param {unknown} raw @param {'player'|'housekeeper'} role @returns {?import('./shapes.mjs').ModelSpec} */
|
||||||
// registry's discovered default -- then the registry gate: model
|
function specFromMeta(raw, role) {
|
||||||
// use is disabled until the op discovers, and a model the battery
|
if (raw == null) return null;
|
||||||
// disqualified never plays
|
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
||||||
const model = meta.models?.player ?? ctx.cfg.models?.player ?? reg?.defaults.player ?? null;
|
const o = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw);
|
||||||
if (!model) {
|
if (typeof o.provider === 'string' && typeof o.model === 'string' && typeof o.effort === 'string') {
|
||||||
throw new HttpError(409, reg
|
return { provider: o.provider, model: o.model, effort: o.effort };
|
||||||
? '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');
|
|
||||||
}
|
}
|
||||||
if (!usable(reg, model)) {
|
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
|
||||||
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
|
/** The invalidation gate (GM, 2026-11-18): the settings the run
|
||||||
* layer (server.json params) under the run's own overrides. */
|
* came with must still be carried. A provider gone from the
|
||||||
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').RoleParams} */
|
* config, a model gone from its provider's registry, a model the
|
||||||
function resolveParams(ctx, runId, role) {
|
* battery disqualified -- all one state: the run blocks until the
|
||||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
* GM sets it up again. The error IS the table's note.
|
||||||
return {
|
* @param {Ctx} ctx @param {import('./shapes.mjs').ModelSpec} spec @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
||||||
...(ctx.cfg.params?.[role] ?? {}),
|
function gateSpec(ctx, spec, role) {
|
||||||
...(meta.params?.[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
|
/** Resolve one role's spec: the run's pick, gated for validity. No
|
||||||
// the numeric knobs its unset state SENDS -- the registry measured a
|
* pick is a loud refusal -- the create flow lands one, so only
|
||||||
// default, so one honestly exists. Layers: the run's override, then
|
* picked-clean runs hit this.
|
||||||
// the deployment layer (server.json params), then the registry's
|
* @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
||||||
// per-model pick -- the level with the highest observed mean
|
function resolveSpec(ctx, runId, role) {
|
||||||
// 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) {
|
|
||||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||||
const set = meta.params?.[role]?.reasoning_effort ?? ctx.cfg.params?.[role]?.reasoning_effort ?? undefined;
|
const spec = specFromMeta(meta.models?.[role], role);
|
||||||
if (set !== undefined) return set === null ? null : String(set);
|
if (!spec) throw new HttpError(409, `no ${role} model set for this run -- pick one in the model box`);
|
||||||
const m = registry()?.models.find((x) => x.id === model);
|
return gateSpec(ctx, spec, role);
|
||||||
return m?.effortDefault ?? null;
|
|
||||||
}
|
}
|
||||||
export { resolveModel, resolveParams, resolveEffort };
|
export { specFromMeta, gateSpec, resolveSpec };
|
||||||
|
|
||||||
// --- the mind verb ------------------------------------------------------------
|
// --- the mind verb ------------------------------------------------------------
|
||||||
//
|
//
|
||||||
|
|||||||
+390
-115
@@ -26,12 +26,13 @@ import path from 'node:path';
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { makeProvider } from './provider.mjs';
|
import { makeProvider } from './provider.mjs';
|
||||||
|
import * as providers from './providers.mjs';
|
||||||
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
|
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
|
||||||
import * as bundle from './bundle.mjs';
|
import * as bundle from './bundle.mjs';
|
||||||
import * as session from './session.mjs';
|
import * as session from './session.mjs';
|
||||||
import * as housekeeping from './housekeeping.mjs';
|
import * as housekeeping from './housekeeping.mjs';
|
||||||
import { effectiveContents } from './variants.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 * as users from './users.mjs';
|
||||||
import { forkRun } from './fork.mjs';
|
import { forkRun } from './fork.mjs';
|
||||||
import * as discovery from './discovery.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 MOCK = process.argv.includes('--mock');
|
||||||
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
|
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
|
||||||
|
|
||||||
const CONFIG_PATH = path.join(ROOT, 'server.json');
|
// server.json is the static, non-secret remainder: bind and contwin.
|
||||||
if (!fs.existsSync(CONFIG_PATH)) {
|
// Optional (GM, 2026-11-18) -- the provider entities live in
|
||||||
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
|
// 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);
|
process.exit(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const cfg = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
|
let providerCfg = providers.readConfig();
|
||||||
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
|
// the self-heal rule (GM, 2026-11-18), stated broadly: an error that
|
||||||
const provider = makeProvider(cfg.endpoint ?? {});
|
// 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
|
// locks/enqueue are attached just below; the cast is the two-step that
|
||||||
// lets the literal precede them
|
// 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} */
|
/** @type {Ctx} */
|
||||||
const ctx = /** @type {Ctx} */ (ctxBase);
|
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 ---------------------------------------------------
|
// --- the per-run activity lock ---------------------------------------------------
|
||||||
//
|
//
|
||||||
// Serializes every async mutation span (turn, ask, start, the
|
// 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 })),
|
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
|
// The registry (state/models.json, per-provider sections) is the
|
||||||
// models. Fresh deployments have none: model use is disabled until
|
// truth of selectable models. The provider entities (state/
|
||||||
// the op discovers. Discover scrapes the provider surface -- API
|
// config.json) are the op's: add and remove from the SPA, discover
|
||||||
// metadata only, zero inference; refine runs the deterministic
|
// and refine per provider. Both surfaces below are the superuser's
|
||||||
// battery and the curator pass (it sends real traffic and may cost
|
// except GET /api/models (the model box reads it, any signed-in
|
||||||
// real money). Both are the superuser's.
|
// user).
|
||||||
|
|
||||||
/** The effective deployment default per role: the op's server.json
|
/** The per-provider payload the model box and the admin block read. */
|
||||||
* pick wins, else the registry's discovered default. */
|
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
||||||
/** @returns {{ player?: ?string, housekeeper?: ?string }} */
|
/** @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 effectiveDefaults() {
|
function modelsPayload() {
|
||||||
const reg = discovery.registry();
|
const reg = discovery.registry();
|
||||||
return {
|
return {
|
||||||
player: ctx.cfg.models?.player ?? reg?.defaults.player ?? undefined,
|
providers: ctx.providerCfg.providers.map((p) => {
|
||||||
housekeeper: ctx.cfg.models?.housekeeper ?? reg?.defaults.housekeeper ?? undefined,
|
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 () => {
|
route('GET', '/api/models', async () => modelsPayload());
|
||||||
const reg = discovery.registry();
|
|
||||||
|
/** 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 {
|
return {
|
||||||
phase: reg?.phase ?? 'none',
|
providers: ctx.providerCfg.providers.map((p) => ({
|
||||||
discovered: reg?.discovered ?? null,
|
slug: p.slug,
|
||||||
refined: reg?.refined ?? null,
|
baseUrl: p.baseUrl,
|
||||||
curator: reg?.curator ?? null,
|
hasKey: !!p.apiKey,
|
||||||
defaults: effectiveDefaults(),
|
default: p.default ?? null,
|
||||||
models: reg?.models ?? [],
|
})),
|
||||||
job: discovery.jobState(ctx),
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
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);
|
requireSuperuser(user);
|
||||||
const reg = await discovery.discover(ctx);
|
if (body.apiKey !== undefined && body.apiKey !== null) {
|
||||||
return { ok: true, phase: reg.phase, models: reg.models.length };
|
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);
|
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 () => {
|
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
|
// create: the pc's name is required (unique per package); the
|
||||||
// package display name defaults to the package's own. The id is
|
// 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 }) => {
|
route('POST', '/api/runs', async ({ body, user }) => {
|
||||||
const pkg = String(body.package ?? '').trim();
|
const pkg = String(body.package ?? '').trim();
|
||||||
const pc = String(body.pc ?? '').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');
|
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);
|
const name = body.name === undefined ? undefined : String(body.name);
|
||||||
requireUser(user);
|
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');
|
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
||||||
const run = JSON.parse(r.out);
|
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}` };
|
return { run, dir: `runs/${run.id}` };
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -457,12 +771,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
|||||||
owner,
|
owner,
|
||||||
ownerName: owner == null ? null : userName(owner),
|
ownerName: owner == null ? null : userName(owner),
|
||||||
models: meta?.models ?? {},
|
models: meta?.models ?? {},
|
||||||
params: meta?.params ?? {},
|
// the invalidation surface: each resolved spec's health, so the
|
||||||
modelDefaults: effectiveDefaults(),
|
// table can carry the note before a send ever 409s
|
||||||
// the deployment layer of the knobs (server.json params): the
|
modelState: roleHealth(id),
|
||||||
// only default an unset knob can honestly resolve to -- the
|
// the providers' default specs -- the create flow's pre-select,
|
||||||
// provider's own serving defaults are unknown and stay unstated
|
// and the fallback a pick-less role would inherit
|
||||||
paramDefaults: cfg.params ?? {},
|
providerDefaults: providerDefaults(),
|
||||||
},
|
},
|
||||||
display: bundle.runDisplay(id),
|
display: bundle.runDisplay(id),
|
||||||
open: !!s,
|
open: !!s,
|
||||||
@@ -599,80 +913,44 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
|
|||||||
return { ok: true, vars: settings.vars };
|
return { ok: true, vars: settings.vars };
|
||||||
});
|
});
|
||||||
|
|
||||||
// the run's models and sampling knobs: per-run overrides of the
|
// the run's model picks: full specs, selected from the registry (GET
|
||||||
// deployment defaults (server.json, else the registry's discovered
|
// /api/models). Owner-only, changeable at any time -- every call
|
||||||
// pick), selected from the registry (GET /api/models). Owner-only,
|
// resolves fresh, so a mid-session switch simply takes the next
|
||||||
// changeable at any time -- every call resolves fresh, so a
|
// turn. null clears a role back to its inheritance (the player to
|
||||||
// mid-session switch simply takes the next turn. null clears a role
|
// nothing, the housekeeper to the player provider's default).
|
||||||
// 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'];
|
|
||||||
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
|
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
|
||||||
const id = params.id;
|
const id = params.id;
|
||||||
bundle.requireRun(id);
|
bundle.requireRun(id);
|
||||||
requireOwner(user, id);
|
requireOwner(user, id);
|
||||||
for (const k of Object.keys(body)) {
|
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 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'])) {
|
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||||
if (body[role] === undefined) continue;
|
if (body[role] === undefined) continue;
|
||||||
if (body[role] === null) { delete models[role]; continue; }
|
if (body[role] === null) { delete models[role]; continue; }
|
||||||
const m = String(body[role]).trim();
|
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body[role]);
|
||||||
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
|
if (typeof spec !== 'object' || spec === null || Array.isArray(spec)
|
||||||
if (!discovery.usable(reg, m)) {
|
|| typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
||||||
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'}`);
|
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;
|
if (Object.keys(models).length) meta.models = models;
|
||||||
else delete meta.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');
|
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
|
// 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 turn meter's read (GM, 2026-11-17): the live progress record
|
||||||
// the streaming callback feeds, plus the scale the bar guesstimates
|
// the streaming callback feeds, plus the scale the bar guesstimates
|
||||||
// against -- the only true budget is max_tokens when the knobs set
|
// against -- the session's own history: her longest past turn in
|
||||||
// one (reasoning counts inside it), else the session's own history:
|
// characters (thinking and prose both, the units the meter counts).
|
||||||
// her longest past turn in characters (thinking and prose both, the
|
// No history means no scale: the client falls back to the
|
||||||
// units the meter counts). No history and no budget means no scale:
|
// chunk-driven animation. (The old max_tokens budget layer is gone
|
||||||
// the client falls back to the chunk-driven animation. Owner-only
|
// with the per-run params: no surface sets one anymore -- GM,
|
||||||
// machinery; a plain read, never queued.
|
// 2026-11-18.) Owner-only machinery; a plain read, never queued.
|
||||||
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
|
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
|
||||||
requireOwner(user, params.id);
|
requireOwner(user, params.id);
|
||||||
const s = ctx.sessions.get(params.id);
|
const s = ctx.sessions.get(params.id);
|
||||||
if (!s) return { inFlight: false, scale: null };
|
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;
|
let high = 0;
|
||||||
for (const e of s.lines) {
|
for (const e of s.lines) {
|
||||||
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
|
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
|
||||||
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
|
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
|
||||||
if (chars > high) high = chars;
|
if (chars > high) high = chars;
|
||||||
}
|
}
|
||||||
const scale = budget ?? (high > 0 ? high : null);
|
const scale = high > 0 ? high : null;
|
||||||
const scaleKind = budget ? 'budget' : (high > 0 ? 'history' : null);
|
const scaleKind = high > 0 ? 'history' : null;
|
||||||
if (!s.progress) return { inFlight: false, scale, scaleKind };
|
if (!s.progress) return { inFlight: false, scale, scaleKind };
|
||||||
return { inFlight: true, ...s.progress, 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 [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
|
||||||
const host = DEBUG ? '127.0.0.1' : cfgHost;
|
const host = DEBUG ? '127.0.0.1' : cfgHost;
|
||||||
server.listen(Number(port ?? 7350), host, () => {
|
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
@@ -1,6 +1,7 @@
|
|||||||
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
|
// server/provider.mjs -- the provider client. One client per
|
||||||
// endpoint per deployment (server.json "endpoint"); the model name
|
// configured provider entity (state/config.json, written by the
|
||||||
// comes from the run (run.json override) or the config default.
|
// 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
|
// Every completion streams (SSE) and is assembled back into the one
|
||||||
// response shape the callers consume -- no caller distinguishes
|
// response shape the callers consume -- no caller distinguishes
|
||||||
@@ -20,13 +21,27 @@
|
|||||||
/** @typedef {(p: { phase: 'thinking'|'prose', chars: number }) => void} ProgressFn */
|
/** @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) {
|
export function makeProvider(provider) {
|
||||||
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
|
const base = String(provider.baseUrl ?? '').replace(/\/+$/, '');
|
||||||
if (!base) throw new Error('server.json: endpoint.baseUrl is required');
|
if (!base) throw new Error('the provider entry has no baseUrl');
|
||||||
const key = endpoint.apiKey ?? process.env[endpoint.apiKeyEnv ?? 'RP_API_KEY'] ?? '';
|
const key = provider.apiKey ?? '';
|
||||||
const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` };
|
// 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 {
|
return {
|
||||||
/**
|
/**
|
||||||
@@ -48,7 +63,7 @@ export function makeProvider(endpoint) {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
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,
|
// the SSE assembly: content and reasoning concatenate in order,
|
||||||
// tool_calls stitch by index (id and name land on the first
|
// tool_calls stitch by index (id and name land on the first
|
||||||
@@ -132,7 +147,7 @@ export function makeProvider(endpoint) {
|
|||||||
async models() {
|
async models() {
|
||||||
const res = await fetch(`${base}/models`, { headers });
|
const res = await fetch(`${base}/models`, { headers });
|
||||||
if (!res.ok) {
|
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());
|
const data = /** @type {{ data: { id: string }[] }} */ (await res.json());
|
||||||
return (data.data ?? []).map((m) => m.id).sort();
|
return (data.data ?? []).map((m) => m.id).sort();
|
||||||
@@ -145,10 +160,26 @@ export function makeProvider(endpoint) {
|
|||||||
async modelsMeta() {
|
async modelsMeta() {
|
||||||
const res = await fetch(`${base}/models`, { headers });
|
const res = await fetch(`${base}/models`, { headers });
|
||||||
if (!res.ok) {
|
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());
|
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 }));
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -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';
|
||||||
|
}
|
||||||
|
|
||||||
@@ -447,6 +447,18 @@ export function lintCarryover(lines, { authored }) {
|
|||||||
if (m.reasoning_content) errors.push(`${at}: thinking is runtime metadata`);
|
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.reminder) errors.push(`${at}: the reminder rides every GM turn on its own`);
|
||||||
if (e.conflictOnly) errors.push(`${at}: conflict traffic is runtime machinery`);
|
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') {
|
} else if (e.t === 'opening') {
|
||||||
openings++;
|
openings++;
|
||||||
if (!Array.isArray(e.status)) errors.push(`${at}: opening.status must be an array of descriptions`);
|
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}`);
|
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
|
// both kinds: the boundary state note must be well-formed (stop
|
||||||
// writes it; a hand edit must not corrupt it)
|
// writes it; a hand edit must not corrupt it)
|
||||||
if (e.t === 'note' && e.kind === 'state') {
|
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`);
|
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');
|
if (authored && openings > 1) errors.push('at most one opening event');
|
||||||
|
|||||||
+77
-36
@@ -30,17 +30,20 @@ export {};
|
|||||||
* everything else about a turn lives in its content. via is the
|
* everything else about a turn lives in its content. via is the
|
||||||
* request record: the resolved model and the effective params (the
|
* request record: the resolved model and the effective params (the
|
||||||
* merged layer actually sent) -- model-facing surfaces never render
|
* merged layer actually sent) -- model-facing surfaces never render
|
||||||
* it, the raw surfaces always do. override is the GM's block edit,
|
* it, the raw surfaces always do. via.model is the bare model id;
|
||||||
* arriving with a non-OOC GM turn: the log's record of it. The
|
* via.provider names the route (absent in pre-spec logs). override
|
||||||
* composition overwrites her newest blocks with these values (the
|
* is the GM's block edit, arriving with a non-OOC GM turn: the log's
|
||||||
* scan reads it newest-wins); the log itself never changes. */
|
* record of it. The composition overwrites her newest blocks with
|
||||||
/** @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 */
|
* 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
|
/** req: a failed provider request -- the resolved model (and its
|
||||||
* effective params, and the failure. No message resulted (the turn
|
* provider route), the effective params, and the failure. No
|
||||||
* fails loud, the retry is the user's); this is the record of what
|
* message resulted (the turn fails loud, the retry is the user's);
|
||||||
* was attempted, surfaced on the raw surfaces like a note. */
|
* this is the record of what was attempted, surfaced on the raw
|
||||||
/** @typedef {{ t: 'req', model: string, params: RoleParams, fail: string }} ReqEvent */
|
* 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
|
/** tool: a tool result, paired to its call (pairing is a context
|
||||||
* invariant, checked at render). */
|
* 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. */
|
/** 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 */
|
/** @typedef {{ phase: 'thinking'|'prose', thinking: number, prose: number, started: number }} TurnProgress */
|
||||||
|
|
||||||
/** run.json: lineage, ownership, per-run model overrides and knobs. */
|
/** One model spec: the complete inference request identity (GM,
|
||||||
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string }, params?: { player?: ?RoleParams, housekeeper?: ?RoleParams } }} RunMeta */
|
* 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
|
/** run.json: lineage, ownership, and the run's model picks -- full
|
||||||
* supported set, plus the reasoning-effort enum (GM, 2026-11-16:
|
* specs, per role. (The retired per-run params layer is gone
|
||||||
* first-class, hidden from the model -- not her call). Numbers ride
|
* entirely, GM, 2026-11-18: params are per-turn via <mind>, and the
|
||||||
* the wire verbatim; null clears; reasoning_effort is one of the
|
* no-legacy rule migrated the last carrier away.) */
|
||||||
* effort ladder's levels. */
|
/** @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 */
|
/** @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
|
/** One model of a discovered provider's registry section. Preliminary
|
||||||
* the scrape only (status unrefined); refined entries carry the
|
* entries carry the scrape only (status unrefined); refined entries
|
||||||
* battery's verdicts and the curator's presentation. think is the
|
* carry the battery's verdicts and the curator's presentation. The
|
||||||
* battery's best measured thinking-token count -- the pick rule
|
* section key is the provider slug -- no routing tag needed, the
|
||||||
* ranks on it (the bucket is display). efforts is the
|
* section names the route. think is the battery's best measured
|
||||||
* reasoning-effort probe: the measured mean thinking per level of
|
* thinking-token count. efforts is the reasoning-effort probe: the
|
||||||
* the ladder; effortDefault is the level with the highest observed
|
* measured mean thinking per level of the ladder; effortDefault is
|
||||||
* mean (GM, 2026-11-16: maximum thinking by default, overridable)
|
* the level with the highest observed mean -- pre-fill and hint
|
||||||
* -- null when the model shows no thinking or no level moved it. */
|
* 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 */
|
/** @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
|
/** One provider's registry section (state/models.json): written by
|
||||||
* what is selectable. Written by discovery (the scrape) and refine
|
* that provider's discovery and refine alone, deletable whole on
|
||||||
* (the battery + the curator pass); read by the selectors, the model
|
* provider removal. recommendation is the curator's overall-best
|
||||||
* routes, and the turn loop. */
|
* {model, effort} -- intel only, shown post-refine, applied by the
|
||||||
/** @typedef {{ phase: 'preliminary'|'refined', endpoint: ?string, discovered: string, refined: ?string, defaults: { player: ?string, housekeeper: ?string }, models: RegistryModel[], curator?: string }} ModelRegistry */
|
* 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,
|
/** settings.json: identity (pc/name are the @ sigils), declared vars,
|
||||||
* the records flag. */
|
* the records flag. */
|
||||||
@@ -158,10 +185,24 @@ export {};
|
|||||||
/** The provider client (provider.mjs's own return type). */
|
/** The provider client (provider.mjs's own return type). */
|
||||||
/** @typedef {ReturnType<typeof import('./provider.mjs').makeProvider>} Provider */
|
/** @typedef {ReturnType<typeof import('./provider.mjs').makeProvider>} Provider */
|
||||||
|
|
||||||
/** server.json as parsed. params is per-role sampling knobs -- the
|
/** One configured provider: a slug, a baseUrl, optional auth, and
|
||||||
* deployment-default layer the run's own params override. */
|
* the op's default model spec for it ({model, effort} -- params are
|
||||||
/** @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 */
|
* 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.
|
/** The server context: the one object threaded through every module.
|
||||||
* locks/enqueue are the per-run activity lock (main.mjs). */
|
* locks/enqueue are the per-run activity lock (main.mjs). providers
|
||||||
/** @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 */
|
* 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 */
|
||||||
|
|||||||
+13
-10
@@ -17,12 +17,14 @@
|
|||||||
// gm.md files are exempt -- GM-private, flagged to the GM, never
|
// gm.md files are exempt -- GM-private, flagged to the GM, never
|
||||||
// agent-edited.
|
// agent-edited.
|
||||||
// 4. Retired terms stay retired (DICTIONARY rules the terms). The
|
// 4. Retired terms stay retired (DICTIONARY rules the terms). The
|
||||||
// living prose -- README, the root prompts, the packages --
|
// rule is about the substrate (GM, 2026-11-19): README and the
|
||||||
// never says: the wrap, prelude, paper (the old status), window
|
// root prompts never say the wrap, prelude, paper (the old
|
||||||
// (the old session; a line naming contwin may gloss it as the
|
// status), window (the old session; a line naming contwin may
|
||||||
// context window), turn-0, seed (memory.json is the name).
|
// gloss it as the context window), turn-0, seed (memory.json is
|
||||||
// Historical records keep the vocabulary of
|
// the name). A banned word in a package's prose is fine -- the
|
||||||
// their day; gm.md is GM-private, flagged never fixed.
|
// packages are the fiction, and their words are the story's.
|
||||||
|
// Historical records keep the vocabulary of their day; gm.md is
|
||||||
|
// GM-private, flagged never fixed.
|
||||||
// 5. Zero-dependency runtime (GM, 2026-11-13, amended 2026-11-15):
|
// 5. Zero-dependency runtime (GM, 2026-11-13, amended 2026-11-15):
|
||||||
// every import is node: builtin or relative -- no runtime deps,
|
// every import is node: builtin or relative -- no runtime deps,
|
||||||
// no package-manager requirement to run. Dev tooling is exempt
|
// no package-manager requirement to run. Dev tooling is exempt
|
||||||
@@ -53,9 +55,10 @@ const fail = (msg) => { console.log(`FAIL ${msg}`); failures++; };
|
|||||||
|
|
||||||
const files = execFileSync('git', ['ls-files'], { encoding: 'utf8' }).split('\n').filter(Boolean);
|
const files = execFileSync('git', ['ls-files'], { encoding: 'utf8' }).split('\n').filter(Boolean);
|
||||||
const ROOT_PROMPTS = new Set(['system.md', 'invariants.md', 'handbook.md', 'housekeeper.md', 'reminder.md']);
|
const ROOT_PROMPTS = new Set(['system.md', 'invariants.md', 'handbook.md', 'housekeeper.md', 'reminder.md']);
|
||||||
const livingProse = (f) =>
|
// rule 4's scope: the substrate's prose only (GM, 2026-11-19) --
|
||||||
f === 'README.md' || ROOT_PROMPTS.has(f)
|
// README and the root prompts. The packages are the fiction; a
|
||||||
|| (f.startsWith('packages/') && !f.endsWith('gm.md'));
|
// banned word there is the story's own business
|
||||||
|
const substrateProse = (f) => f === 'README.md' || ROOT_PROMPTS.has(f);
|
||||||
// the checker's own source names what it bans (the rule patterns and
|
// the checker's own source names what it bans (the rule patterns and
|
||||||
// their comments); it is exempt from the rules it defines
|
// their comments); it is exempt from the rules it defines
|
||||||
const isSelf = (f) => f === 'test/check-repo.mjs';
|
const isSelf = (f) => f === 'test/check-repo.mjs';
|
||||||
@@ -121,7 +124,7 @@ for (const f of files) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// rule 4: retired terms in living prose
|
// rule 4: retired terms in living prose
|
||||||
if (livingProse(f)) {
|
if (substrateProse(f)) {
|
||||||
text.split('\n').forEach((line, i) => {
|
text.split('\n').forEach((line, i) => {
|
||||||
if (/\bthe wrap\b/i.test(line)) fail(`${f}:${i + 1} retired term: "the wrap" (housekeeping)`);
|
if (/\bthe wrap\b/i.test(line)) fail(`${f}:${i + 1} retired term: "the wrap" (housekeeping)`);
|
||||||
if (/prelude/i.test(line)) fail(`${f}:${i + 1} retired term: "prelude" (turn-0)`);
|
if (/prelude/i.test(line)) fail(`${f}:${i + 1} retired term: "prelude" (turn-0)`);
|
||||||
|
|||||||
+380
-86
@@ -1,12 +1,15 @@
|
|||||||
// test/smoke.mjs -- end-to-end multiuser pass against the --mock
|
// test/smoke.mjs -- end-to-end multiuser pass against the --mock
|
||||||
// server. Covers: bootstrap, claim, spent-invite rejection, second
|
// server. Covers: bootstrap, claim, spent-invite rejection, second
|
||||||
// user, the model registry (a fresh deployment has no models,
|
// user, the provider round (GM, 2026-11-18: the self-heal boot --
|
||||||
// discover scrapes, refine runs the battery + the curator, registry-
|
// the empty provider list auto-added and discovered; the op acts
|
||||||
// gated picks, the pick rule's lex tie-break, the named sampling
|
// ride the per-provider surface -- the binary add choice, the o/f
|
||||||
// knobs, the reasoning-effort knob (the battery's effort probe, the
|
// singleton's authless guard, the selection {model, effort} that
|
||||||
// max-mean default that sends, the override that rides the turn,
|
// names the refine curator, per-provider refine with the meter and
|
||||||
// hidden from the model), the request record -- resolved model +
|
// the receipt, the spec-keyed adjudication cache, the run spec
|
||||||
// effective params on
|
// picks {provider, model, effort} with no unset effort, the
|
||||||
|
// invalidation surface -- a removed provider blocks its runs until
|
||||||
|
// the GM re-picks, the removal guard on the singleton, the request
|
||||||
|
// record -- resolved spec + effective params on
|
||||||
// every turn, the pass log's model), the mind verb (the player sets
|
// every turn, the pass log's model), the mind verb (the player sets
|
||||||
// its sampling for its next turn: one-shot, JSON, bounds enforced,
|
// its sampling for its next turn: one-shot, JSON, bounds enforced,
|
||||||
// conflict-healed, carried unconsumed across a session boundary,
|
// conflict-healed, carried unconsumed across a session boundary,
|
||||||
@@ -46,7 +49,7 @@ import { readFileSync, writeFileSync, appendFileSync } from 'node:fs';
|
|||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { renderView } from '../server/session.mjs';
|
import { renderView, lintCarryover } from '../server/session.mjs';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const BASE = process.env.RP_BASE ?? 'http://127.0.0.1:7350';
|
const BASE = process.env.RP_BASE ?? 'http://127.0.0.1:7350';
|
||||||
@@ -108,55 +111,199 @@ const ashId = r.data.user.id;
|
|||||||
r = await call('/invites', { method: 'POST', token: ash, body: {} });
|
r = await call('/invites', { method: 'POST', token: ash, body: {} });
|
||||||
ok('invite mint is op-only', r.status === 403);
|
ok('invite mint is op-only', r.status === 403);
|
||||||
|
|
||||||
// 7b. the model registry: a fresh deployment has no models, discovery
|
// 7b. providers and the registry: the fresh deployment self-heals
|
||||||
// is the op's two-step act, and model use is registry-gated
|
// (the empty provider list is auto-added and discovered at boot),
|
||||||
r = await call('/models', { token: op });
|
// the op's acts ride the per-provider surface (selection, discover,
|
||||||
ok('fresh deployment: no registry', r.status === 200 && r.data.phase === 'none' && r.data.models.length === 0, JSON.stringify({ phase: r.data.phase }));
|
// refine), the adjudication cache survives churn, and model use
|
||||||
r = await call('/models/discover', { method: 'POST', token: ash, body: {} });
|
// stays registry-gated
|
||||||
ok('discover is op-only', r.status === 403);
|
{
|
||||||
r = await call('/models/refine', { method: 'POST', token: op, body: {} });
|
r = await call('/models', { token: op });
|
||||||
ok('refine refuses before discovery', r.status === 409, r.data.error ?? '');
|
let boot = r.data.providers ?? [];
|
||||||
r = await call('/models/discover', { method: 'POST', token: op, body: {} });
|
for (let i = 0; i < 50 && boot.filter((p) => p.models.length > 0).length < 2; i++) {
|
||||||
ok('discover scrapes (no inference)', r.status === 200 && r.data.phase === 'preliminary', r.data.error ?? JSON.stringify(r.data));
|
|
||||||
r = await call('/models', { token: op });
|
|
||||||
ok('the preliminary list carries the scrape', r.data.phase === 'preliminary'
|
|
||||||
&& r.data.models.some((m) => m.id === 'mock' && m.status === 'unrefined')
|
|
||||||
&& r.data.models.every((m) => m.inference === undefined && m.label === undefined), JSON.stringify(r.data.models));
|
|
||||||
r = await call('/models/refine', { method: 'POST', token: op, body: {} });
|
|
||||||
ok('refine starts the job', r.status === 200 && r.data.state === 'running', r.data.error ?? JSON.stringify(r.data));
|
|
||||||
let reg = null;
|
|
||||||
for (let i = 0; i < 40; i++) {
|
|
||||||
reg = await call('/models', { token: op });
|
|
||||||
if (reg.data.job?.state !== 'running') break;
|
|
||||||
await new Promise((res) => setTimeout(res, 100));
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
boot = r.data.providers ?? [];
|
||||||
|
}
|
||||||
|
ok('the self-heal boot: the empty provider list is auto-added and discovered',
|
||||||
|
boot.length === 2 && boot.every((p) => ['mock-a', 'mock-b'].includes(p.slug) && p.phase === 'preliminary' && p.models.length > 0),
|
||||||
|
JSON.stringify(boot.map((p) => [p.slug, p.phase, p.models.length])));
|
||||||
|
const cfgFile = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
|
||||||
|
ok('the config file holds the provider entities (server-written state)',
|
||||||
|
cfgFile.providers.length === 2 && cfgFile.providers.every((p) => typeof p.slug === 'string' && typeof p.baseUrl === 'string'),
|
||||||
|
JSON.stringify(cfgFile.providers?.map((p) => p.slug)));
|
||||||
|
|
||||||
|
// the op's acts are op-only
|
||||||
|
r = await call('/providers', { method: 'POST', token: ash, body: { slug: 'nope', baseUrl: 'https://x.example/v1' } });
|
||||||
|
ok('provider add is op-only', r.status === 403);
|
||||||
|
|
||||||
|
// the add flow: bad inputs refuse
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'Bad Slug', baseUrl: 'https://x.example/v1' } });
|
||||||
|
ok('a bad slug refuses', r.status === 400 && /slug/.test(r.data.error), r.data.error ?? '');
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-a', baseUrl: 'https://x.example/v1' } });
|
||||||
|
ok('a duplicate slug refuses', r.status === 409, r.data.error ?? '');
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'nope', baseUrl: 'not a url' } });
|
||||||
|
ok('a bad baseUrl refuses', r.status === 400 && /baseUrl/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
|
// the binary choice: the o/f singleton adds and discovers (the
|
||||||
|
// mock surface serves any slug), and never takes a key
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { builtin: true } });
|
||||||
|
ok('the o/f singleton adds and discovers', r.status === 200 && r.data.provider === 'opencode/free' && r.data.models > 0, JSON.stringify(r.data));
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { builtin: true } });
|
||||||
|
ok('the singleton is single', r.status === 409 && /already/.test(r.data.error), r.data.error ?? '');
|
||||||
|
r = await call(`/providers/${encodeURIComponent('opencode/free')}/auth`, { method: 'POST', token: op, body: { apiKey: 'sk-x' } });
|
||||||
|
ok('the o/f singleton never takes a key', r.status === 403 && /anonymous/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
|
// the selection: the provider's default {model, effort} -- also
|
||||||
|
// the refine curator
|
||||||
|
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('refine requires the selection (the default is the curator)', r.status === 409 && /select/.test(r.data.error), r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'nope', effort: 'max' } });
|
||||||
|
ok('a selection outside the registry refuses', r.status === 400 && /registry/.test(r.data.error), r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'turbo' } });
|
||||||
|
ok('a bogus effort level refuses', r.status === 400 && /must be one of/.test(r.data.error), r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
|
||||||
|
ok('the selection lands (the provider default)', r.status === 200 && JSON.stringify(r.data.default) === '{"model":"mock","effort":"max"}', JSON.stringify(r.data));
|
||||||
|
r = await call('/providers/mock-b/default', { method: 'POST', token: op, body: { model: 'mock-cheap', effort: 'high' } });
|
||||||
|
ok('the second provider selects too', r.status === 200, r.data.error ?? '');
|
||||||
|
|
||||||
|
// refine: per provider, the meter, the receipt, the verdicts
|
||||||
|
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('refine starts the job', r.status === 200 && r.data.state === 'running', r.data.error ?? JSON.stringify(r.data));
|
||||||
|
let jobA = null;
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
jobA = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
|
||||||
|
if (jobA?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
ok('refine applied', jobA?.state === 'applied', JSON.stringify(jobA ?? null));
|
||||||
|
ok('the refine meter closed its steps (one per model + the curator\'s two)', jobA?.steps?.total === 4 && jobA?.steps?.done === 4,
|
||||||
|
JSON.stringify(jobA?.steps ?? null));
|
||||||
|
ok('the refine receipt logged every battery and the curator',
|
||||||
|
(jobA?.lines ?? []).length === 3
|
||||||
|
&& jobA.lines.some((l) => l.includes('mock: reasoning deep'))
|
||||||
|
&& jobA.lines.some((l) => l.includes('mock-tie: reasoning deep'))
|
||||||
|
&& jobA.lines.some((l) => l.includes('curator (mock): curated')),
|
||||||
|
JSON.stringify(jobA?.lines ?? null));
|
||||||
|
r = await call('/providers/mock-b/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('the second provider refines', r.status === 200, r.data.error ?? '');
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
if ((r.data.providers ?? []).find((p) => p.slug === 'mock-b')?.job?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
const refined = (r.data.providers ?? []);
|
||||||
|
const secA = refined.find((p) => p.slug === 'mock-a');
|
||||||
|
const secB = refined.find((p) => p.slug === 'mock-b');
|
||||||
|
ok('the refined sections carry verdicts and curation',
|
||||||
|
secA?.phase === 'refined' && secA.models.some((m) => m.id === 'mock' && m.inference === true && m.reasoning === 'deep' && m.label === 'Mock' && m.family === 'mock')
|
||||||
|
&& secA.models.some((m) => m.id === 'mock-tie' && m.reasoning === 'deep' && m.label === 'Mock (tie)')
|
||||||
|
&& secB?.phase === 'refined' && secB.models.some((m) => m.id === 'mock-cheap' && m.reasoning === 'standard'),
|
||||||
|
JSON.stringify({ a: secA?.models.map((m) => [m.id, m.label]), b: secB?.models.map((m) => [m.id, m.label]) }));
|
||||||
|
ok('the curator\'s recommendation is intel on the section (never auto-applied)',
|
||||||
|
JSON.stringify(secA?.recommendation ?? null) === '{"model":"mock","effort":"max"}' && JSON.stringify(secA.default) === '{"model":"mock","effort":"max"}',
|
||||||
|
JSON.stringify({ recommendation: secA?.recommendation, default: secA.default }));
|
||||||
|
ok('the effort probe: measured ladders and the max-mean defaults',
|
||||||
|
secA?.models.some((m) => m.id === 'mock' && m.effortDefault === 'max' && m.efforts?.max === 500 && m.efforts?.none === 0)
|
||||||
|
&& secB?.models.some((m) => m.id === 'mock-cheap' && m.effortDefault === 'high' && m.efforts?.max === undefined),
|
||||||
|
JSON.stringify([...(secA?.models ?? []), ...(secB?.models ?? [])].filter((m) => m.efforts).map((m) => ({ id: m.id, effortDefault: m.effortDefault }))));
|
||||||
|
const regFile = JSON.parse(readFileSync(`${ROOT}/state/models.json`, 'utf8'));
|
||||||
|
ok('the registry file is per-provider sections (the section names the route)',
|
||||||
|
regFile.providers?.['mock-a']?.models?.length === 2 && regFile.providers?.['mock-b']?.models?.length === 1
|
||||||
|
&& regFile.providers['mock-b'].models[0].id === 'mock-cheap'
|
||||||
|
&& regFile.providers['mock-a'].models.every((m) => m.endpoint === undefined),
|
||||||
|
JSON.stringify(Object.entries(regFile.providers ?? {}).map(([s, x]) => [s, x.models.length])));
|
||||||
|
|
||||||
|
// the adjudication cache: a re-refine over the same tuple reuses
|
||||||
|
// every entry -- churn is the point (o/f rotates models; the
|
||||||
|
// survivors keep their measured selves between refines)
|
||||||
|
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('a re-refine starts', r.status === 200, r.data.error ?? '');
|
||||||
|
let jobC = null;
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
jobC = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
|
||||||
|
if (jobC?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
ok('the cached re-refine applied', jobC?.state === 'applied', JSON.stringify(jobC ?? null));
|
||||||
|
ok('the cache served both models',
|
||||||
|
(jobC?.lines ?? []).filter((l) => l.includes('from cache')).length === 2
|
||||||
|
&& jobC.lines.some((l) => l.includes('curator')),
|
||||||
|
JSON.stringify(jobC?.lines ?? null));
|
||||||
|
const cacheFile = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
|
||||||
|
const cacheKeys = Object.keys(cacheFile.entries ?? {}).filter((k) => k.startsWith('mock-a::'));
|
||||||
|
ok('the cache file holds the adjudications under their spec tuples',
|
||||||
|
cacheKeys.length === 2 && cacheKeys.every((k) => k.startsWith('mock-a::') && k.includes('::max::mock::max')),
|
||||||
|
JSON.stringify(Object.keys(cacheFile.entries ?? {})));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7c. the add-flow machine (GM, 2026-11-19): discovery is the probe.
|
||||||
|
// A keyless working endpoint never sees a key field; a 401/403 stands
|
||||||
|
// the provider broken and opens the key path (checked on reception,
|
||||||
|
// saved on success, asked again on refusal -- a failed candidate
|
||||||
|
// never saves); every other failure refuses the add outright,
|
||||||
|
// nothing stands. The key removal probes again, and o/f never asks.
|
||||||
|
{
|
||||||
|
// the add takes no key -- the auth route is the only key path
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-keyed', baseUrl: 'https://k.example/v1', apiKey: 'sk-x' } });
|
||||||
|
ok('apiKey on the add refuses', r.status === 400 && /apiKey/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
|
// a dead endpoint: the add is refused outright, nothing stands
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-dead', baseUrl: 'https://dead.example/v1' } });
|
||||||
|
ok('a non-auth discovery failure refuses the add', r.status === 500 && /did not answer/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
ok('the refused add left no card behind', !(r.data.providers ?? []).some((p) => p.slug === 'mock-dead'), JSON.stringify((r.data.providers ?? []).map((p) => p.slug)));
|
||||||
|
const cfgNoDead = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
|
||||||
|
ok('the refused add never reached the config', !cfgNoDead.providers.some((p) => p.slug === 'mock-dead'), '');
|
||||||
|
|
||||||
|
// an auth-shaped refusal: the provider stands broken, the ask opens
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-auth', baseUrl: 'https://auth.example/v1' } });
|
||||||
|
ok('a 401 listing stands the provider broken', r.status === 401 && /refused/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
const authCard = (r.data.providers ?? []).find((p) => p.slug === 'mock-auth');
|
||||||
|
ok('the broken card carries the probe record (the ask)', authCard?.phase === 'none' && authCard?.probe?.outcome === 'auth' && authCard?.hasKey === false, JSON.stringify(authCard?.probe ?? null));
|
||||||
|
|
||||||
|
// the key path: checked on reception, saved on success
|
||||||
|
r = await call('/providers/mock-auth/auth', { method: 'POST', token: op, body: { apiKey: 'sk-mock' } });
|
||||||
|
ok('a working key lands (probe-then-save)', r.status === 200 && r.data.models > 0, JSON.stringify(r.data));
|
||||||
|
const cfgKeyed = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
|
||||||
|
ok('the successful key saved', cfgKeyed.providers.find((p) => p.slug === 'mock-auth')?.apiKey === 'sk-mock', '');
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
ok('the keyed card reads working', (r.data.providers ?? []).find((p) => p.slug === 'mock-auth')?.probe?.outcome === 'ok', '');
|
||||||
|
|
||||||
|
// a key that still meets the refusal is never saved
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-lock', baseUrl: 'https://lock.example/v1' } });
|
||||||
|
ok('the locked provider stands broken too', r.status === 401 && /refused/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
|
||||||
|
r = await call('/providers/mock-lock/auth', { method: 'POST', token: op, body: { apiKey: 'sk-nope' } });
|
||||||
|
ok('a refused key is not saved (the ask repeats)', r.status === 401 && /refuses every listing/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
|
||||||
|
const cfgLock = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
|
||||||
|
ok('the failed key never reached the config', cfgLock.providers.find((p) => p.slug === 'mock-lock')?.apiKey === undefined, '');
|
||||||
|
|
||||||
|
// the key removal: the control for a provider gone public (or the
|
||||||
|
// first half of a replacement -- the ask re-opens on the 401)
|
||||||
|
r = await call('/providers/mock-auth/auth', { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('the key removes', r.status === 200, JSON.stringify(r.data));
|
||||||
|
const cfgUnkeyed = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
|
||||||
|
ok('the key left the config', cfgUnkeyed.providers.find((p) => p.slug === 'mock-auth')?.apiKey === undefined, '');
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
ok('the keyless probe re-met the 401 (the ask re-opened)', (r.data.providers ?? []).find((p) => p.slug === 'mock-auth')?.probe?.outcome === 'auth', '');
|
||||||
|
r = await call('/providers/mock-lock/auth', { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('removing a missing key refuses', r.status === 404, `${r.status}`);
|
||||||
|
r = await call(`/providers/${encodeURIComponent('opencode/free')}/auth`, { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('the o/f singleton never loses a key it never had', r.status === 403 && /anonymous/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
|
// the machine's fixtures leave before the later counts
|
||||||
|
for (const slug of ['mock-auth', 'mock-lock']) {
|
||||||
|
await call(`/providers/${slug}`, { method: 'DELETE', token: op, body: {} });
|
||||||
|
}
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
ok('the fixtures cleaned up', !(r.data.providers ?? []).some((p) => p.slug === 'mock-auth' || p.slug === 'mock-lock'), '');
|
||||||
}
|
}
|
||||||
ok('refine applied', reg.data.job?.state === 'applied', JSON.stringify(reg.data.job ?? null));
|
|
||||||
ok('the refine meter closed its steps', reg.data.job?.steps?.total === 5 && reg.data.job?.steps?.done === 5,
|
|
||||||
JSON.stringify(reg.data.job?.steps ?? null));
|
|
||||||
ok('the refine receipt logged every battery and the curator',
|
|
||||||
(reg.data.job?.lines ?? []).length === 4
|
|
||||||
&& reg.data.job.lines.some((l) => l.includes('mock: reasoning deep'))
|
|
||||||
&& reg.data.job.lines.some((l) => l.includes('mock-cheap: reasoning standard'))
|
|
||||||
&& reg.data.job.lines.some((l) => l.includes('curator (mock-tie): curated')),
|
|
||||||
JSON.stringify(reg.data.job?.lines ?? null));
|
|
||||||
ok('the refined registry carries verdicts and curation', reg.data.phase === 'refined'
|
|
||||||
&& reg.data.models.some((m) => m.id === 'mock' && m.inference === true && m.reasoning === 'deep' && m.label === 'Mock' && m.family === 'mock')
|
|
||||||
&& reg.data.models.some((m) => m.id === 'mock-tie' && m.reasoning === 'deep' && m.label === 'Mock (tie)')
|
|
||||||
&& reg.data.models.some((m) => m.id === 'mock-cheap' && m.reasoning === 'standard'), JSON.stringify(reg.data.models));
|
|
||||||
ok('the effort probe: measured ladders and the max-mean defaults',
|
|
||||||
reg.data.models.some((m) => m.id === 'mock' && m.effortDefault === 'max' && m.efforts?.max === 500 && m.efforts?.none === 0)
|
|
||||||
&& reg.data.models.some((m) => m.id === 'mock-cheap' && m.effortDefault === 'high' && m.efforts?.max === undefined),
|
|
||||||
JSON.stringify(reg.data.models.filter((m) => m.efforts).map((m) => ({ id: m.id, effortDefault: m.effortDefault }))));
|
|
||||||
const regFile = JSON.parse(readFileSync(`${ROOT}/state/models.json`, 'utf8'));
|
|
||||||
ok('the pick rule: deepest reasoning wins, full ties settle sort-lex-pick-bottom',
|
|
||||||
regFile.defaults.player === 'mock-tie' && regFile.defaults.housekeeper === 'mock-tie', JSON.stringify(regFile.defaults));
|
|
||||||
const cfgModels = JSON.parse(readFileSync(`${ROOT}/server.json`, 'utf8')).models ?? {};
|
|
||||||
ok('the op\'s explicit config beats the registry default', reg.data.defaults.player === (cfgModels.player ?? regFile.defaults.player),
|
|
||||||
JSON.stringify({ api: reg.data.defaults.player, cfg: cfgModels.player ?? null }));
|
|
||||||
|
|
||||||
// 8. op creates a run -- dormant session one, memory.json waits for
|
// 8. op creates a run -- dormant session one, memory.json waits for
|
||||||
// the start gate
|
// the start gate
|
||||||
r = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Smokina', name: 'Smoke Story' } });
|
r = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Smokina', name: 'Smoke Story', spec: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
|
||||||
ok('create run', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
|
ok('create run', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
|
||||||
const runId = r.data.run?.id;
|
const runId = r.data.run?.id;
|
||||||
ok('owner stamped', meta(runId).owner === opId);
|
ok('owner stamped', meta(runId).owner === opId);
|
||||||
@@ -222,7 +369,7 @@ const pickNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'pick')
|
|||||||
ok('pick note logged (the metric)', !!pickNote && pickNote.count === 2 && [0, 1].includes(pickNote.chosen), JSON.stringify(pickNote ?? null));
|
ok('pick note logged (the metric)', !!pickNote && pickNote.count === 2 && [0, 1].includes(pickNote.chosen), JSON.stringify(pickNote ?? null));
|
||||||
const viaMsg = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && e.via);
|
const viaMsg = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && e.via);
|
||||||
ok('the request record rides the turn (resolved model + effective params, the measured effort default included)',
|
ok('the request record rides the turn (resolved model + effective params, the measured effort default included)',
|
||||||
!!viaMsg && viaMsg.via.model === 'mock' && JSON.stringify(viaMsg.via.params) === '{"reasoning_effort":"max"}', JSON.stringify(viaMsg?.via ?? null));
|
!!viaMsg && viaMsg.via.model === 'mock' && viaMsg.via.provider === 'mock-a' && JSON.stringify(viaMsg.via.params) === '{"reasoning_effort":"max"}', JSON.stringify(viaMsg?.via ?? null));
|
||||||
r = await call(`/runs/${runId}/table`, { token: op });
|
r = await call(`/runs/${runId}/table`, { token: op });
|
||||||
ok('the table carries only the picked variant', r.data.entries.every((e) => e.t !== 'msg' || e.m.role !== 'assistant' || !/<\/?variants?>/.test(e.m.content ?? '')), 'variant syntax leaked into the table');
|
ok('the table carries only the picked variant', r.data.entries.every((e) => e.t !== 'msg' || e.m.role !== 'assistant' || !/<\/?variants?>/.test(e.m.content ?? '')), 'variant syntax leaked into the table');
|
||||||
ok('the picked turn is her turn on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && e.m.content.includes(`<status>cuffed, belted, naked, barefoot, ${pickedStatus}</status>`)), pickedStatus);
|
ok('the picked turn is her turn on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && e.m.content.includes(`<status>cuffed, belted, naked, barefoot, ${pickedStatus}</status>`)), pickedStatus);
|
||||||
@@ -424,49 +571,50 @@ ok('the log keeps her words verbatim (the over-cap emission is intact)',
|
|||||||
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc with an edit )', status: ['x'] } });
|
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc with an edit )', status: ['x'] } });
|
||||||
ok('an override cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? '');
|
ok('an override cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
// 12b. models: per-run overrides of the deployment defaults, the
|
// 12b. models: the run's spec picks {provider, model, effort},
|
||||||
// registry-gated picks, and the named sampling knobs
|
// registry-gated, owner-only. The per-run params layer is gone (GM,
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
|
// 2026-11-18): the <mind> verb is the only sampling source, per-turn
|
||||||
ok('set models', r.status === 200 && r.data.models.player === 'mock' && r.data.models.housekeeper === 'mock-cheap', JSON.stringify(r.data));
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'mock-cheap', effort: 'low' }, housekeeper: { provider: 'mock-a', model: 'mock-tie', effort: 'max' } } });
|
||||||
ok('models stamped in run.json', meta(forkId).models?.player === 'mock' && meta(forkId).models?.housekeeper === 'mock-cheap');
|
ok('set spec picks',
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: 0.7, max_tokens: 4096 } } } });
|
r.status === 200 && JSON.stringify(r.data.models.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
|
||||||
ok('set knobs', r.status === 200 && r.data.params.player?.temperature === 0.7 && r.data.params.player?.max_tokens === 4096, JSON.stringify(r.data));
|
&& JSON.stringify(r.data.models.housekeeper) === '{"provider":"mock-a","model":"mock-tie","effort":"max"}',
|
||||||
ok('knobs stamped in run.json', meta(forkId).params?.player?.temperature === 0.7);
|
JSON.stringify(r.data));
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: null } } } });
|
ok('the specs are stamped in run.json', JSON.stringify(meta(forkId).models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}');
|
||||||
ok('a null knob clears', r.status === 200 && r.data.params.player?.temperature === undefined && r.data.params.player?.max_tokens === 4096, JSON.stringify(r.data.params));
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'mock-cheap', effort: 'turbo' } } });
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'low' } } } });
|
|
||||||
ok('the effort knob sets', r.status === 200 && r.data.params.player?.reasoning_effort === 'low', JSON.stringify(r.data.params));
|
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'turbo' } } } });
|
|
||||||
ok('a bogus effort level refuses', r.status === 400 && /must be one of/.test(r.data.error), r.data.error ?? '');
|
ok('a bogus effort level refuses', r.status === 400 && /must be one of/.test(r.data.error), r.data.error ?? '');
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: null } } } });
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'nope', model: 'x', effort: 'low' } } });
|
||||||
ok('a null effort clears back to the measured default', r.status === 200 && r.data.params.player?.reasoning_effort === undefined, JSON.stringify(r.data.params));
|
ok('an unconfigured provider refuses', r.status === 400 && /no provider named/.test(r.data.error), r.data.error ?? '');
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'low' } } } });
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'not-a-model', effort: 'low' } } });
|
||||||
ok('the effort override stays for the turn', r.status === 200 && r.data.params.player?.reasoning_effort === 'low', JSON.stringify(r.data.params));
|
ok('a model outside the registry refuses', r.status === 400 && /not usable/.test(r.data.error), r.data.error ?? '');
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { vibes: 1 } } } });
|
|
||||||
ok('an unknown knob refuses', r.status === 400 && /unknown knob/.test(r.data.error), r.data.error ?? '');
|
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'not-a-model' } });
|
|
||||||
ok('a model outside the registry refuses', r.status === 400 && /registry/.test(r.data.error), r.data.error ?? '');
|
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
|
||||||
ok('clear a role back to default', r.status === 200 && r.data.models.housekeeper === undefined && r.data.models.player === 'mock', JSON.stringify(r.data));
|
ok('clear a role (the housekeeper inherits the player provider\'s default)',
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: 'x' } });
|
r.status === 200 && r.data.models.housekeeper === undefined && r.data.modelState?.housekeeper?.ok === true && r.data.modelState.housekeeper.inherited === true,
|
||||||
|
JSON.stringify(r.data.modelState ?? null));
|
||||||
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
|
||||||
ok('model set is owner-only', r.status === 403);
|
ok('model set is owner-only', r.status === 403);
|
||||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
|
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
|
||||||
ok('unknown role rejected', r.status === 400);
|
ok('unknown role rejected', r.status === 400);
|
||||||
r = await call(`/runs/${forkId}`, { token: ash });
|
r = await call(`/runs/${forkId}`, { token: ash });
|
||||||
ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !!r.data.run.modelDefaults?.player && r.data.run.params?.player?.max_tokens === 4096 && !!r.data.run.paramDefaults, JSON.stringify(r.data.run.models));
|
ok('detail exposes the picks, their health, and the provider defaults',
|
||||||
// a turn on the knob-carrying run: the recording proves what was
|
JSON.stringify(r.data.run.models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
|
||||||
// sent -- the run's knob under the mind layer (her restated mind
|
&& r.data.run.modelState?.player?.ok === true
|
||||||
// rides over the run layer, the layering the tunables round built)
|
&& Array.isArray(r.data.run.providerDefaults) && r.data.run.providerDefaults.length >= 2,
|
||||||
|
JSON.stringify({ models: r.data.run.models, modelState: r.data.run.modelState }));
|
||||||
|
// a turn on the re-picked run: the recording proves what was sent --
|
||||||
|
// the spec's effort riding under the mind layer (her restated mind is
|
||||||
|
// the only params source, layered over nothing)
|
||||||
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She keeps watch.*' } });
|
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She keeps watch.*' } });
|
||||||
ok('gm turn on the fork (post-knobs)', r.status === 200, r.data.error ?? '');
|
ok('gm turn on the fork (post-picks)', r.status === 200, r.data.error ?? '');
|
||||||
r = await call(`/runs/${forkId}/session`, { token: ash });
|
r = await call(`/runs/${forkId}/session`, { token: ash });
|
||||||
const viaTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
|
const viaTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
|
||||||
ok('the recorded request carries the run\'s knobs under the mind layer',
|
ok('the recorded request carries the spec under the mind layer',
|
||||||
!!viaTurn?.via && viaTurn.via.model === 'mock' && viaTurn.via.params.max_tokens === 4096 && viaTurn.via.params.temperature === 1.2
|
!!viaTurn?.via && viaTurn.via.model === 'mock-cheap' && viaTurn.via.provider === 'mock-b'
|
||||||
&& viaTurn.via.params.reasoning_effort === 'low',
|
&& viaTurn.via.params.temperature === 1.2 && viaTurn.via.params.reasoning_effort === 'low',
|
||||||
JSON.stringify(viaTurn?.via ?? null));
|
JSON.stringify(viaTurn?.via ?? null));
|
||||||
r = await call('/models', { token: ash });
|
r = await call('/models', { token: ash });
|
||||||
ok('model listing (the registry)', r.status === 200 && r.data.phase === 'refined' && r.data.models.some((m) => m.id === 'mock' && m.label === 'Mock'), JSON.stringify(r.data.phase));
|
ok('model listing (the per-provider registry)',
|
||||||
|
r.status === 200 && (r.data.providers ?? []).some((p) => p.slug === 'mock-a' && p.phase === 'refined' && p.models.some((m) => m.id === 'mock' && m.label === 'Mock')),
|
||||||
|
JSON.stringify((r.data.providers ?? []).map((p) => [p.slug, p.phase])));
|
||||||
|
|
||||||
// 13. ash saves a draft as a package (save-package is a draft act --
|
// 13. ash saves a draft as a package (save-package is a draft act --
|
||||||
// the played-run refusal is checked at the end)
|
// the played-run refusal is checked at the end)
|
||||||
@@ -504,7 +652,7 @@ ok('user package survives, ownerless', !!saved2 && saved2.owner === null && save
|
|||||||
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
|
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
|
||||||
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
|
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
|
||||||
const reforkId = r.data.run;
|
const reforkId = r.data.run;
|
||||||
ok('fork carries the models', meta(reforkId).models?.player === 'mock');
|
ok('fork carries the model specs', JSON.stringify(meta(reforkId).models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}');
|
||||||
|
|
||||||
// 16. users list, self-revoke refused
|
// 16. users list, self-revoke refused
|
||||||
r = await call('/users', { token: op });
|
r = await call('/users', { token: op });
|
||||||
@@ -733,6 +881,43 @@ ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JS
|
|||||||
ok('session 5 renders the sheet chunk from the carried note', chunk?.content === '<sheet>{}</sheet>', chunk?.content ?? 'no chunk');
|
ok('session 5 renders the sheet chunk from the carried note', chunk?.content === '<sheet>{}</sheet>', chunk?.content ?? 'no chunk');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 23b. the sheet's transport at the lint (the box round, GM, 2026-11-19):
|
||||||
|
// the record is the only channel, the tag is view machinery -- the
|
||||||
|
// authored gate names every wrong shape, the boundary note is checked
|
||||||
|
// on both kinds, and her carried emission stays legitimate history
|
||||||
|
{
|
||||||
|
const la = (a) => lintCarryover(a, { authored: true });
|
||||||
|
ok('lint: a scalar sheet record is named', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
|
||||||
|
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: 'nope' },
|
||||||
|
]).some((e) => e.includes('sheet record must be a JSON object')), '');
|
||||||
|
ok('lint: an array sheet record is named', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
|
||||||
|
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: ['nope'] },
|
||||||
|
]).some((e) => e.includes('sheet record must be a JSON object')), '');
|
||||||
|
ok('lint: a sheet record on her turn is named', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x' }, sheet: {} },
|
||||||
|
]).some((e) => e.includes('rides GM turns only')), '');
|
||||||
|
ok('lint: the tag in her authored turn is named', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x <sheet>{}</sheet>' } },
|
||||||
|
]).some((e) => e.includes('never authored')), '');
|
||||||
|
ok('lint: the tag in GM prose is named', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
|
||||||
|
{ t: 'msg', m: { role: 'user', content: 'y <sheet>{}</sheet>' } },
|
||||||
|
]).some((e) => e.includes('never authored')), '');
|
||||||
|
ok('lint: a good sheet record passes clean', la([
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
|
||||||
|
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: { GP: 0 } },
|
||||||
|
]).length === 0, '');
|
||||||
|
ok('lint: a scalar sheet on a boundary note is named (both kinds)', lintCarryover([
|
||||||
|
{ t: 'note', kind: 'state', status: [], sheet: 7 },
|
||||||
|
], { authored: false }).some((e) => e.includes('state.sheet must be a JSON object')), '');
|
||||||
|
ok('lint: her emitted sheet in a carried tail is legitimate history', lintCarryover([
|
||||||
|
{ t: 'msg', m: { role: 'user', content: 'y' } },
|
||||||
|
{ t: 'msg', m: { role: 'assistant', content: 'x <sheet>{"gp": 99}</sheet>' } },
|
||||||
|
], { authored: false }).length === 0, '');
|
||||||
|
}
|
||||||
|
|
||||||
// 24. the rewind (GM, 2026-11-17): the GM's take-back. The send that
|
// 24. the rewind (GM, 2026-11-17): the GM's take-back. The send that
|
||||||
// carries rewind replaces the target GM turn -- the target and
|
// carries rewind replaces the target GM turn -- the target and
|
||||||
// everything after it leave the log (physical truncation; fork is the
|
// everything after it leave the log (physical truncation; fork is the
|
||||||
@@ -790,6 +975,115 @@ ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JS
|
|||||||
ok('the story drops the cut range', r.data.sessions.every((s) => s.turns.every((t) => !/Rewind battery two/.test(t.text))), 'the dropped prose survived in the story');
|
ok('the story drops the cut range', r.data.sessions.every((s) => s.turns.every((t) => !/Rewind battery two/.test(t.text))), 'the dropped prose survived in the story');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 24b. invalidation and the removal guard (GM, 2026-11-18): a run's
|
||||||
|
// picks are settings the run came with -- when the server stops
|
||||||
|
// carrying them (the provider removed), the run blocks until the GM
|
||||||
|
// sets them up again; and the o/f singleton is removable only while
|
||||||
|
// another provider stands in its place (the empty list is an error
|
||||||
|
// state; the fallback is what keeps it unreachable)
|
||||||
|
{
|
||||||
|
// a custom provider, a run riding it
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-c', baseUrl: 'https://mock.c.example/v1' } });
|
||||||
|
ok('a custom provider adds and discovers', r.status === 200 && r.data.models > 0, JSON.stringify(r.data));
|
||||||
|
|
||||||
|
// the failures-never-cache rule (GM, 2026-11-19): a failure is the
|
||||||
|
// absence of a measurement, not a measurement -- mock-fail lands
|
||||||
|
// its verdict fresh at every refine, while the passing models
|
||||||
|
// persist from the cache
|
||||||
|
r = await call('/providers/mock-c/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
|
||||||
|
ok('the custom provider selects its curator', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-c/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('the custom provider refines', r.status === 200, r.data.error ?? '');
|
||||||
|
let jobCC = null;
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
jobCC = (r.data.providers ?? []).find((p) => p.slug === 'mock-c')?.job ?? null;
|
||||||
|
if (jobCC?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
ok('the mock-c refine applied', jobCC?.state === 'applied', JSON.stringify(jobCC?.reason ?? null));
|
||||||
|
ok('the failing model landed its verdict with the no-cache marker',
|
||||||
|
(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: failed the tool probe') && l.includes('never cached')),
|
||||||
|
JSON.stringify(jobCC?.lines ?? null));
|
||||||
|
const cacheFail = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
|
||||||
|
ok('the failure is absent from the cache',
|
||||||
|
!Object.keys(cacheFail.entries ?? {}).some((k) => k.startsWith('mock-c::mock-fail::')),
|
||||||
|
JSON.stringify(Object.keys(cacheFail.entries ?? {}).filter((k) => k.startsWith('mock-c::'))));
|
||||||
|
r = await call('/providers/mock-c/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('the re-refine starts', r.status === 200, r.data.error ?? '');
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
jobCC = (r.data.providers ?? []).find((p) => p.slug === 'mock-c')?.job ?? null;
|
||||||
|
if (jobCC?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
ok('the re-refine re-probed the failure (never from cache)',
|
||||||
|
(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: failed the tool probe'))
|
||||||
|
&& !(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: from cache')),
|
||||||
|
JSON.stringify(jobCC?.lines ?? null));
|
||||||
|
ok('the passing models served from cache on the re-refine',
|
||||||
|
(jobCC?.lines ?? []).filter((l) => l.includes('from cache')).length === 3,
|
||||||
|
JSON.stringify(jobCC?.lines ?? null));
|
||||||
|
const failRun = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Failcheck', name: 'Fail Check', spec: { provider: 'mock-c', model: 'mock-fail', effort: 'max' } } });
|
||||||
|
ok('the failing model is not selectable (the registry gates it)', failRun.status === 400, 'a failed model was selectable');
|
||||||
|
if (failRun.status === 200) await call(`/runs/${failRun.data.run.id}`, { method: 'DELETE', token: op, body: {} }); // never expected -- the backstop
|
||||||
|
r = await call('/runs', { token: op });
|
||||||
|
ok('the refused create left no orphan run (validate before anything lands)', !(r.data ?? []).some((x) => x.pc === 'Failcheck'), 'an orphan dir survived the refusal');
|
||||||
|
|
||||||
|
r = await call(`/runs/${reforkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-c', model: 'mock', effort: 'high' } } });
|
||||||
|
ok('the refork re-picks onto the custom provider', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*Riding the custom provider.*' } });
|
||||||
|
ok('the turn rides the custom provider', r.status === 200, r.data.error ?? '');
|
||||||
|
|
||||||
|
// the removal: the run invalidates, loudly, on every surface
|
||||||
|
r = await call('/providers/mock-c', { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('the custom provider removes', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call(`/runs/${reforkId}`, { token: op });
|
||||||
|
ok('the run\'s health carries the note (the invalidation surface)',
|
||||||
|
r.data.run.modelState?.player?.ok === false && /no longer configured/.test(r.data.run.modelState.player.note ?? ''),
|
||||||
|
JSON.stringify(r.data.run.modelState ?? null));
|
||||||
|
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*No.*' } });
|
||||||
|
ok('the send refuses with the same note', r.status === 409 && /no longer configured/.test(r.data.error), r.data.error ?? '');
|
||||||
|
const goneFile = JSON.parse(readFileSync(`${ROOT}/state/models.json`, 'utf8'));
|
||||||
|
ok('the provider\'s registry section went with it', goneFile.providers?.['mock-c'] === undefined, JSON.stringify(Object.keys(goneFile.providers ?? {})));
|
||||||
|
const goneCache = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
|
||||||
|
ok('the provider\'s cache entries went with it', !Object.keys(goneCache.entries ?? {}).some((k) => k.startsWith('mock-c::')), JSON.stringify(Object.keys(goneCache.entries ?? {})));
|
||||||
|
|
||||||
|
// the GM sets it up again: the run unblocks
|
||||||
|
r = await call(`/runs/${reforkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
|
||||||
|
ok('the re-pick lands', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*Back on the stand-ins.*' } });
|
||||||
|
ok('the run plays again after the re-pick', r.status === 200, r.data.error ?? '');
|
||||||
|
|
||||||
|
// the removal guard: pare down to the singleton, then it holds
|
||||||
|
r = await call('/providers/mock-b', { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('mock-b removes (a stand-in, not the fallback)', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a', { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('mock-a removes', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call(`/providers/${encodeURIComponent('opencode/free')}`, { method: 'DELETE', token: op, body: {} });
|
||||||
|
ok('the singleton holds while it is all that stands', r.status === 409 && /fallback/.test(r.data.error), r.data.error ?? '');
|
||||||
|
|
||||||
|
// restore the mock world for the restart checks: re-add, rediscover,
|
||||||
|
// re-select, re-refine (fresh -- the cache purged with the provider)
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-a', baseUrl: 'https://mock.a.example/v1' } });
|
||||||
|
ok('mock-a re-adds', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-b', baseUrl: 'https://mock.b.example/v1' } });
|
||||||
|
ok('mock-b re-adds', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
|
||||||
|
ok('mock-a re-selects', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-b/default', { method: 'POST', token: op, body: { model: 'mock-cheap', effort: 'high' } });
|
||||||
|
ok('mock-b re-selects', r.status === 200, r.data.error ?? '');
|
||||||
|
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
|
||||||
|
ok('mock-a re-refines (fresh probes -- the cache purged)', r.status === 200, r.data.error ?? '');
|
||||||
|
let jobR = null;
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
r = await call('/models', { token: op });
|
||||||
|
jobR = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
|
||||||
|
if (jobR?.state !== 'running') break;
|
||||||
|
await new Promise((res) => setTimeout(res, 100));
|
||||||
|
}
|
||||||
|
ok('the restored world refined', jobR?.state === 'applied', JSON.stringify(jobR ?? null));
|
||||||
|
}
|
||||||
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId}`);
|
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId}`);
|
||||||
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
|
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
|
||||||
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
|
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
|
||||||
|
|||||||
+6
-7
@@ -77,7 +77,7 @@
|
|||||||
/** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */
|
/** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */
|
||||||
|
|
||||||
/** One run as `runs` lists it (fill is present exactly when initialized). */
|
/** One run as `runs` lists it (fill is present exactly when initialized). */
|
||||||
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */
|
/** @typedef {{ id: string, package: string, models: ?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */
|
||||||
|
|
||||||
/** The apply log's record of what a manifest did. */
|
/** The apply log's record of what a manifest did. */
|
||||||
/** @typedef {{ id: number } & InsertOp} AppliedInsert */
|
/** @typedef {{ id: number } & InsertOp} AppliedInsert */
|
||||||
@@ -882,10 +882,10 @@ function anonId() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] @param {?string} [model] */
|
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] */
|
||||||
function cmdCreate(pkgName, pc, displayName, model) {
|
function cmdCreate(pkgName, pc, displayName) {
|
||||||
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
|
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
|
||||||
fail('usage: create <package> <pc-name> ["package display name"] ["model"]');
|
fail('usage: create <package> <pc-name> ["package display name"]');
|
||||||
}
|
}
|
||||||
const pkgDir = packageDir(pkgName);
|
const pkgDir = packageDir(pkgName);
|
||||||
if (!pkgDir) fail(`no such package: ${pkgName} -- see: packages`);
|
if (!pkgDir) fail(`no such package: ${pkgName} -- see: packages`);
|
||||||
@@ -931,7 +931,6 @@ function cmdCreate(pkgName, pc, displayName, model) {
|
|||||||
settings.name = displayName?.trim() || settings.name || pkgName;
|
settings.name = displayName?.trim() || settings.name || pkgName;
|
||||||
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
||||||
/** @type {RunMeta} */ const meta = { package: pkgName, created: today() };
|
/** @type {RunMeta} */ const meta = { package: pkgName, created: today() };
|
||||||
if (model) meta.models = { player: model };
|
|
||||||
if (ownerOverride) meta.owner = ownerOverride;
|
if (ownerOverride) meta.owner = ownerOverride;
|
||||||
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||||
fs.mkdirSync(path.join(runDir, 'manifests'), { recursive: true });
|
fs.mkdirSync(path.join(runDir, 'manifests'), { recursive: true });
|
||||||
@@ -962,7 +961,7 @@ function cmdRuns() {
|
|||||||
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
|
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
|
||||||
found++;
|
found++;
|
||||||
let pkg = '?';
|
let pkg = '?';
|
||||||
/** @type {?{ player?: ?string, housekeeper?: ?string }} */ let models = null;
|
/** @type {?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }} */ let models = null;
|
||||||
/** @type {?string} */ let owner = null;
|
/** @type {?string} */ let owner = null;
|
||||||
/** @type {?string} */ let created = null;
|
/** @type {?string} */ let created = null;
|
||||||
/** @type {?number} */ let forked = null;
|
/** @type {?number} */ let forked = null;
|
||||||
@@ -1270,7 +1269,7 @@ if (RUN != null && PHASE_RULES[cmd ?? '']) enforcePhase(cmd ?? '');
|
|||||||
switch (cmd) {
|
switch (cmd) {
|
||||||
case 'packages': cmdPackages(); break;
|
case 'packages': cmdPackages(); break;
|
||||||
case 'runs': cmdRuns(); break;
|
case 'runs': cmdRuns(); break;
|
||||||
case 'create': cmdCreate(args[0], args[1], args[2], args[3]); break;
|
case 'create': cmdCreate(args[0], args[1], args[2]); break;
|
||||||
case 'save-package': cmdSavePackage(args[0]); break;
|
case 'save-package': cmdSavePackage(args[0]); break;
|
||||||
case 'init': cmdInit(); break;
|
case 'init': cmdInit(); break;
|
||||||
case 'render': renderAll(openDb()); break;
|
case 'render': renderAll(openDb()); break;
|
||||||
|
|||||||
+15
-13
@@ -43,22 +43,23 @@
|
|||||||
</div>
|
</div>
|
||||||
<div id="invite-list"></div>
|
<div id="invite-list"></div>
|
||||||
<div id="user-list"></div>
|
<div id="user-list"></div>
|
||||||
<div id="models-admin">
|
<div id="providers-admin">
|
||||||
<h3>models</h3>
|
<h3>providers</h3>
|
||||||
<div id="models-state" class="hint"></div>
|
<div id="providers-banner" class="hint" hidden></div>
|
||||||
|
<div id="provider-list"></div>
|
||||||
<div class="form-actions">
|
<div class="form-actions">
|
||||||
<button id="models-discover">discover</button>
|
<button id="provider-add-of">add opencode/free</button>
|
||||||
<button id="models-refine">refine</button>
|
<button id="provider-add-custom">add custom provider</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="refine-progress" hidden>
|
<form id="provider-form" hidden>
|
||||||
<div id="refine-topline">
|
<label class="field">slug <input id="provider-slug" autocomplete="off" placeholder="my-shop"></label>
|
||||||
<span id="refine-count"></span>
|
<label class="field">baseUrl <input id="provider-base" autocomplete="off" placeholder="https://api.example.com/v1"></label>
|
||||||
<span id="refine-label" class="hint"></span>
|
<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>
|
||||||
<div id="refine-bar"><div id="refine-fill"></div></div>
|
</form>
|
||||||
</div>
|
|
||||||
<div id="refine-lines"></div>
|
|
||||||
<div id="models-list"></div>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
@@ -108,6 +109,7 @@
|
|||||||
<pre id="edit-hl" aria-hidden="true"></pre>
|
<pre id="edit-hl" aria-hidden="true"></pre>
|
||||||
<textarea id="setup-edit" spellcheck="false"></textarea>
|
<textarea id="setup-edit" spellcheck="false"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="edit-hint" hidden></div>
|
||||||
<div id="setup-edit-bar">
|
<div id="setup-edit-bar">
|
||||||
<button id="setup-save">save</button>
|
<button id="setup-save">save</button>
|
||||||
<span id="setup-edit-state"></span>
|
<span id="setup-edit-state"></span>
|
||||||
|
|||||||
+28
-195
@@ -1,144 +1,37 @@
|
|||||||
// web/knobs.mjs -- the sampling knobs: the definitions table and the
|
// web/knobs.mjs -- the reasoning-effort ladder and its select.
|
||||||
// per-role knob row.
|
|
||||||
//
|
//
|
||||||
// The knobs are named, well-known, widely supported. The definitions
|
// The per-run sampling knobs are retired (GM, 2026-11-18): params are
|
||||||
// table is the single home of every knob text -- label, hint, bounds
|
// per-turn and only hers -- the <mind> verb sets them for one turn,
|
||||||
// -- red-pen the prose here, in place. Bounds are display knowledge
|
// nothing stores them. Reasoning effort is a property of the model
|
||||||
// probed from this endpoint's own validation errors (the /model
|
// pick (there is no unset effort), so its select lives inside the
|
||||||
// route's validation stays generic: a finite number, or one of the
|
// model picks (widgets.mjs's modelsBox) and the provider selection
|
||||||
// effort ladder's levels). The provider's serving defaults are
|
// (view-home's admin block), not a knob row. The ladder mirrors
|
||||||
// unknown and stay unstated; the only default anyone can honestly
|
// server/discovery.mjs's EFFORT_LEVELS (the web cannot import server
|
||||||
// name is the deployment layer (server.json params), which rides the
|
// runtime code); keep them in step.
|
||||||
// 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
|
// The old knobs' teaching surface -- what temperature means, what
|
||||||
// sent to the provider; a value present is sent, and the row marks it
|
// top_p does -- was prompt-side all along: invariants.md documents
|
||||||
// when it equals the deployment default. The explicit override toggle
|
// the mind verb, and the model answers with native JSON. The GM-side
|
||||||
// carries the distinction: off (the visible default) disables the
|
// texts died with the rows; the four bounds live on in the server's
|
||||||
// input and saving sends nothing for the knob (null clears a
|
// mind-verb validator (server/loop.mjs, KNOB_BOUNDS).
|
||||||
// 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';
|
import { el } from './dom.mjs';
|
||||||
|
|
||||||
// the reasoning-effort ladder -- mirrors server/discovery.mjs's
|
// the reasoning-effort ladder -- mirrors server/discovery.mjs's
|
||||||
// EFFORT_LEVELS (the web cannot import server runtime code); keep
|
// EFFORT_LEVELS; keep them in step
|
||||||
// them in step
|
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||||
const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
||||||
|
|
||||||
/** One knob's definition: the texts are the product. Two kinds ship:
|
/** A select over the ladder. The '' option's label names what an
|
||||||
* numbers, and the effort enum (a select over the ladder). All six
|
* absent choice means at the call site (the measured default in the
|
||||||
* knobs are the GM's here; the mind verb (server/loop.mjs) sets
|
* model box, "pick a level" in the selection prompt) -- the caller
|
||||||
* only the four that are hers -- max_tokens is excluded by ruling
|
* owns the sentence, this builds the options.
|
||||||
* (a budget, not a mind), reasoning_effort is hidden from her
|
* @param {?string} current the pre-selected level ('' when none)
|
||||||
* entirely (not her call). */
|
* @param {string} unsetLabel the '' option's label
|
||||||
/** @typedef {{ key: keyof RoleParams, kind: 'number', label: string, hint: string, bounds: string }} NumberDef */
|
* @returns {HTMLSelectElement}
|
||||||
/** @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) {
|
export function effortSelect(current, unsetLabel) {
|
||||||
const wrap = el('div', 'knobs');
|
const sel = /** @type {HTMLSelectElement} */ (el('select'));
|
||||||
wrap.appendChild(el('div', 'knobs-head', `${role} knobs`));
|
const unset = /** @type {HTMLOptionElement} */ (el('option', null, unsetLabel));
|
||||||
/** @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 = '';
|
unset.value = '';
|
||||||
sel.appendChild(unset);
|
sel.appendChild(unset);
|
||||||
for (const lv of EFFORT_LEVELS) {
|
for (const lv of EFFORT_LEVELS) {
|
||||||
@@ -146,66 +39,6 @@ export function knobsBox(role, current, deployment, hintBar, effort = null) {
|
|||||||
o.value = lv;
|
o.value = lv;
|
||||||
sel.appendChild(o);
|
sel.appendChild(o);
|
||||||
}
|
}
|
||||||
lab.appendChild(sel);
|
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
|
||||||
} else {
|
return sel;
|
||||||
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 };
|
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-10
@@ -10,19 +10,31 @@ export {};
|
|||||||
|
|
||||||
/** One run card as GET /runs serves it (the clerk's listing,
|
/** One run card as GET /runs serves it (the clerk's listing,
|
||||||
* enriched by the server with the live-session state). fill is
|
* enriched by the server with the live-session state). fill is
|
||||||
* present exactly when the run is initialized. */
|
* present exactly when the run is initialized. models is run.json
|
||||||
/** @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 */
|
* 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,
|
/** GET /runs/:id -- the run detail: identity, the phase bookkeeping,
|
||||||
* her two blocks, the fill, the context meter's numbers.
|
* her two blocks, the fill, the context meter's numbers. models is
|
||||||
* paramDefaults is the knobs' deployment layer (server.json params)
|
* run.json verbatim (the spec picks); modelState is the resolved
|
||||||
* -- the only default an unset knob honestly resolves to. */
|
* truth. */
|
||||||
/** @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 */
|
/** @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
|
/** One provider's /api/models payload: its registry section (phase
|
||||||
* discovery job state riding along. phase 'none' is the fresh
|
* 'none' when never discovered), the op's default spec, the
|
||||||
* deployment: nothing is selectable until the op discovers. */
|
* curator's recommendation, and the refine job state. */
|
||||||
/** @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 */
|
/** @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
|
/** GET /runs/:id/table -- the live session's projection (thinking
|
||||||
* never crosses the wire, variant turns carry only the picked one). */
|
* never crosses the wire, variant turns carry only the picked one). */
|
||||||
|
|||||||
+9
-7
@@ -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 { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; }
|
||||||
#context-fill.hot { background: var(--danger); }
|
#context-fill.hot { background: var(--danger); }
|
||||||
|
|
||||||
#refine-progress { margin: 10px 0 2px; }
|
.provider-card { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 8px; }
|
||||||
#refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
|
.refine-progress { margin: 10px 0 2px; }
|
||||||
#refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
|
.refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
|
||||||
#refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
|
||||||
#refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
|
.refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
#refine-fill { height: 100%; width: 0; background: var(--ok); }
|
.refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
|
||||||
#refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; }
|
.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; }
|
.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; }
|
.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); }
|
.tok-var { color: var(--ok); }
|
||||||
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||||
#setup-edit-state { color: var(--dim); font-size: 12px; }
|
#setup-edit-state { color: var(--dim); font-size: 12px; }
|
||||||
|
#edit-hint { color: var(--dim); font-size: 12px; margin-top: 8px; }
|
||||||
|
|
||||||
/* --- transcript (play) --- */
|
/* --- transcript (play) --- */
|
||||||
|
|
||||||
|
|||||||
+7
-6
@@ -148,15 +148,16 @@ function renderContent(target, text, { extract }) {
|
|||||||
return { status, conflict, agenda };
|
return { status, conflict, agenda };
|
||||||
}
|
}
|
||||||
|
|
||||||
// the request record's line: the resolved model and the effective
|
// the request record's line: the resolved spec (provider and model)
|
||||||
// params as sent (the merged layer actually sent). Shared by the raw
|
// and the effective params as sent. Shared by the raw walk and the
|
||||||
// walk and the per-turn raw control. fail is present when the call
|
// per-turn raw control. fail is present when the call failed -- no
|
||||||
// failed -- no message resulted.
|
// message resulted.
|
||||||
/** @param {{ model: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
|
/** @param {{ model: string, provider?: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
|
||||||
export function viaLine(via, fail = null) {
|
export function viaLine(via, fail = null) {
|
||||||
const ks = Object.entries(via.params ?? {});
|
const ks = Object.entries(via.params ?? {});
|
||||||
const p = ks.length ? ` -- ${ks.map(([k, v]) => `${k}: ${v}`).join(', ')}` : ' (no knobs set)';
|
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
|
// the GM's block edit, as the machinery line both walks show: the
|
||||||
|
|||||||
+269
-65
@@ -6,7 +6,8 @@ import { api } from './client.mjs';
|
|||||||
import { state } from './state.mjs';
|
import { state } from './state.mjs';
|
||||||
import { banner } from './chrome.mjs';
|
import { banner } from './chrome.mjs';
|
||||||
import { navigate, render } from './router.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 */
|
/** @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;
|
// the name carries the content facts plus the ownership garnish;
|
||||||
// started-or-forked rides the meta -- chrome, never model-facing
|
// 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-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)));
|
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
|
||||||
// your own draft opens the editor; anyone else's run opens at
|
// your own draft opens the editor; anyone else's run opens at
|
||||||
// the story -- the table is the owner's
|
// the story -- the table is the owner's
|
||||||
@@ -39,6 +40,9 @@ export async function enter(arg, seq) {
|
|||||||
const ownershipTag = (r, mine) =>
|
const ownershipTag = (r, mine) =>
|
||||||
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
|
(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"
|
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
|
||||||
/** @param {number} t @returns {string} */
|
/** @param {number} t @returns {string} */
|
||||||
function fmtUnix(t) {
|
function fmtUnix(t) {
|
||||||
@@ -107,57 +111,211 @@ async function renderAdmin(seq) {
|
|||||||
}
|
}
|
||||||
userList.appendChild(row);
|
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
|
// The provider cards: the state line, the selection (the default
|
||||||
// inference battery + the curator pass -- real traffic, may cost
|
// {model, effort} pair -- also the refine curator), discover and
|
||||||
// real money, two-click armed with the warning). The registry state
|
// refine (both armed: discover resets a refined section to the
|
||||||
// line and the model list render from the saved registry.
|
// 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 */
|
/** @param {import('./shapes.mjs').ProviderPayload} p @returns {string} */
|
||||||
function renderModelsAdmin(reg, seq) {
|
function providerStateLine(p) {
|
||||||
const stateLine = $('models-state');
|
if (p.phase === 'none') {
|
||||||
const running = reg.job?.state === 'running';
|
// the probe record is the card's truth (GM, 2026-11-19): an auth
|
||||||
if (reg.phase === 'none') {
|
// refusal opens the key path (never on o/f -- its auth failure is
|
||||||
stateLine.textContent = 'no models discovered -- model use is disabled until you discover';
|
// upstream breakage, not a prompt); any other failure names
|
||||||
} else if (reg.phase === 'preliminary') {
|
// itself; no probe yet is a provider that was never scraped
|
||||||
stateLine.textContent = `preliminary registry -- ${reg.models.length} scraped, unrefined (discovered ${fmtStamp(reg.discovered)})`;
|
if (p.probe?.outcome === 'auth') {
|
||||||
} else {
|
return p.slug === 'opencode/free'
|
||||||
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)})`;
|
? 'upstream auth failure -- nothing to fix on this side, wait'
|
||||||
|
: 'discovery refused -- it wants an API key';
|
||||||
}
|
}
|
||||||
if (running) stateLine.textContent = `refining -- ${reg.job?.phase ?? ''} started ${fmtStamp(reg.job?.started ?? null)}; this page follows the job`;
|
if (p.probe?.outcome === 'error') return `discovery failed -- ${p.probe.detail}`;
|
||||||
/** @type {HTMLButtonElement} */ ($('models-discover')).disabled = running;
|
return 'not discovered yet';
|
||||||
/** @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
|
/** @param {import('./shapes.mjs').ProviderPayload} p @param {number} seq */
|
||||||
// (no speed to interpolate -- a stuck bar means a stuck step), the
|
function renderProviderCard(p, seq) {
|
||||||
// label names the call running now, and the lines are the receipt
|
const card = el('div', 'provider-card');
|
||||||
// -- they survive the job, so a landed pass keeps its verdicts and
|
const running = p.job?.state === 'running';
|
||||||
// a rejected one keeps its post-mortem
|
|
||||||
const meter = $('refine-progress');
|
const head = el('div', 'admin-row');
|
||||||
const linesBox = $('refine-lines');
|
head.appendChild(el('span', 'grow', `${p.slug} \u00b7 ${providerStateLine(p)}`));
|
||||||
if (reg.job?.steps) {
|
const rm = el('button', 'danger', 'remove');
|
||||||
const j = reg.job;
|
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: '' };
|
const st = j.steps ?? { total: 0, done: 0, label: '' };
|
||||||
meter.hidden = false;
|
const meter = el('div', 'refine-progress');
|
||||||
$('refine-count').textContent = `${st.done}/${st.total} \u00b7 ${j.state}`;
|
const top = el('div', 'refine-topline');
|
||||||
$('refine-label').textContent = j.state === 'running'
|
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` : ''}`
|
? `${st.label}${st.chars != null ? ` \u00b7 ${st.chars} chars` : ''}`
|
||||||
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label);
|
: (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}%`;
|
const bar = el('div', 'refine-bar');
|
||||||
linesBox.textContent = '';
|
const fill = el('div', 'refine-fill');
|
||||||
for (const l of j.lines ?? []) linesBox.appendChild(el('div', 'refine-line', l));
|
fill.style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
|
||||||
} else {
|
bar.appendChild(fill);
|
||||||
meter.hidden = true;
|
const lines = el('div', 'refine-lines');
|
||||||
linesBox.textContent = '';
|
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');
|
// the selection: the provider's default pair, also the refine
|
||||||
list.textContent = '';
|
// curator. The curator's recommendation sits beside it -- intel
|
||||||
for (const m of reg.models) {
|
// 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 row = el('div', 'admin-row');
|
||||||
const facts = [
|
const facts = [
|
||||||
m.id,
|
m.id,
|
||||||
@@ -172,14 +330,28 @@ function renderModelsAdmin(reg, seq) {
|
|||||||
].filter(Boolean).join(' \u00b7 ');
|
].filter(Boolean).join(' \u00b7 ');
|
||||||
row.appendChild(el('span', 'grow', facts));
|
row.appendChild(el('span', 'grow', facts));
|
||||||
if (m.description) row.appendChild(el('span', 'hint', m.description));
|
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
|
// the job follows itself home: poll until it lands, then re-render
|
||||||
setTimeout(async () => {
|
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 || 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();
|
else render();
|
||||||
}, 2000);
|
}, 2000);
|
||||||
}
|
}
|
||||||
@@ -190,28 +362,60 @@ function fmtStamp(iso) {
|
|||||||
return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC` : '?';
|
return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC` : '?';
|
||||||
}
|
}
|
||||||
|
|
||||||
// discover: the free scrape -- armed because it resets a refined
|
// the add flow (GM, 2026-11-19): the binary choice, and the probe
|
||||||
// registry back to the preliminary list (the curation is re-earned
|
// decides the key path. o/f is one click; custom opens the inline
|
||||||
// by refining again)
|
// form taking ONLY the endpoint -- a working keyless listing never
|
||||||
armedButton($('models-discover'), {
|
// sees a key field. A 401/403 stands the provider broken and opens
|
||||||
label: 'discover',
|
// the key field: the key rides the auth route, checked on reception,
|
||||||
confirm: 'resets the registry to a fresh scrape -- click again',
|
// saved on success, asked again on the next refusal. Every other
|
||||||
fire: async () => {
|
// failure refuses the add outright (nothing stands, the form stays).
|
||||||
try { await api('/models/discover', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
/** @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();
|
render();
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
$('provider-add-custom').addEventListener('click', () => { /** @type {HTMLFormElement} */ ($('provider-form')).hidden = false; });
|
||||||
// refine: the inference battery + the curator pass -- real traffic
|
$('provider-add-cancel').addEventListener('click', () => closeAddForm());
|
||||||
armedButton($('models-refine'), {
|
$('provider-add-go').addEventListener('click', async () => {
|
||||||
label: 'refine',
|
const slug = /** @type {HTMLInputElement} */ ($('provider-slug')).value.trim();
|
||||||
confirm: 'sends real traffic over every model -- may cost a buck. click again',
|
const baseUrl = /** @type {HTMLInputElement} */ ($('provider-base')).value.trim();
|
||||||
fire: async () => {
|
const apiKey = /** @type {HTMLInputElement} */ ($('provider-key')).value.trim();
|
||||||
try { await api('/models/refine', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
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();
|
render();
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
$('new-run-btn').addEventListener('click', () => navigate('/new'));
|
$('new-run-btn').addEventListener('click', () => navigate('/new'));
|
||||||
$('invite-mint').addEventListener('click', async () => {
|
$('invite-mint').addEventListener('click', async () => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+1
-1
@@ -244,7 +244,7 @@ async function refreshPlay(id, seq) {
|
|||||||
$('models-pane').hidden = false;
|
$('models-pane').hidden = false;
|
||||||
const mlist = await modelList();
|
const mlist = await modelList();
|
||||||
if (seq !== state.seq) return;
|
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
|
// pending ask: the modal re-presents after a refresh -- the owner's
|
||||||
// to answer
|
// to answer
|
||||||
|
|||||||
+16
-2
@@ -35,6 +35,17 @@ const EDIT_LIST = [
|
|||||||
{ name: 'run.json', mode: 'ro', source: 'run' },
|
{ 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
|
// 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, { 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
|
/** @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, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
|
||||||
/** @type {Record<string, string>} */ let repoPrompts = {};
|
/** @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>} */
|
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
|
||||||
export async function enter(id, seq) {
|
export async function enter(id, seq) {
|
||||||
@@ -105,7 +116,7 @@ export async function enter(id, seq) {
|
|||||||
// models: per-run overrides, selected from the registry
|
// models: per-run overrides, selected from the registry
|
||||||
const mlist = await modelList();
|
const mlist = await modelList();
|
||||||
if (seq !== state.seq) return;
|
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');
|
const nav = $('setup-files');
|
||||||
nav.textContent = '';
|
nav.textContent = '';
|
||||||
@@ -180,6 +191,9 @@ function selectFile(f) {
|
|||||||
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
|
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
|
||||||
$('setup-save').hidden = spec.mode !== 'rw';
|
$('setup-save').hidden = spec.mode !== 'rw';
|
||||||
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
|
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
|
||||||
|
const hint = FILE_HINTS[f] ?? '';
|
||||||
|
$('edit-hint').textContent = hint;
|
||||||
|
$('edit-hint').hidden = !hint;
|
||||||
renderHighlight();
|
renderHighlight();
|
||||||
markNav();
|
markNav();
|
||||||
}
|
}
|
||||||
|
|||||||
+158
-103
@@ -6,16 +6,16 @@
|
|||||||
// - paneEditor: the status/agenda pattern -- a body line, an edit
|
// - paneEditor: the status/agenda pattern -- a body line, an edit
|
||||||
// button, an inline editor; the edit stages, the send rides it
|
// button, an inline editor; the edit stages, the send rides it
|
||||||
// with the turn; the section shell stays in index.html
|
// with the turn; the section shell stays in index.html
|
||||||
// - modelsBox: the per-run player/housekeeper selects over the
|
// - modelsBox: the per-run spec picks -- {provider, model, effort}
|
||||||
// registry plus the sampling knobs (knobs.mjs owns the knob row
|
// per role, no unset effort, no stored params (the <mind> verb is
|
||||||
// and its definitions table); setup and the play aside each carry
|
// the only sampling source); setup and the play aside each carry
|
||||||
// one
|
// one
|
||||||
|
|
||||||
import { $, el } from './dom.mjs';
|
import { $, el } from './dom.mjs';
|
||||||
import { api } from './client.mjs';
|
import { api } from './client.mjs';
|
||||||
import { state } from './state.mjs';
|
import { state } from './state.mjs';
|
||||||
import { banner } from './chrome.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
|
// two-click confirm -- the second click within 5s fires; anything
|
||||||
// else disarms. Each button owns its own arm state.
|
// 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 model registry, fetched once per session -- the selectors read
|
||||||
// the saved registry, never the live provider (discovery is the op's
|
// the saved registry, never the live provider (discovery is the op's
|
||||||
// manual act; a listing fetch every render would hammer the endpoint
|
// act; a listing fetch every render would hammer the endpoint for a
|
||||||
// for a list that rarely changes)
|
// list that rarely changes)
|
||||||
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
|
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
|
||||||
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
|
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
|
||||||
export async function modelList() {
|
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;
|
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",
|
// a context ceiling as the short human form: 1048576 -> "1M",
|
||||||
// 524288 -> "512K". Null when the provider stated nothing.
|
// 524288 -> "512K". Null when the provider stated nothing.
|
||||||
/** @param {?number} tokens @returns {?string} */
|
/** @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`;
|
return tokens >= 1048576 ? `${Math.round(tokens / 1048576)}M` : `${Math.round(tokens / 1024)}K`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A select's "" value means "deployment default"; a current override
|
// the model picks: per role a full spec {provider, model, effort} --
|
||||||
// missing from the registry stays selectable, so a stale pick never
|
// there is no unset effort (GM, 2026-11-18), and the params layer is
|
||||||
// silently rewrites itself. One plain list, sorted by id (GM,
|
// the <mind> verb's alone (per-turn, nothing stored). The health
|
||||||
// 2026-11-16: the family grouping left the user guessing what a
|
// line under the rows is the invalidation surface: a pick the server
|
||||||
// family name means, and the curator's tier labels only made sense
|
// no longer carries names what died and stays visible until the GM
|
||||||
// inside their groups -- the id is the self-describing name). The
|
// sets it up again. A housekeeper with no pick inherits (the player
|
||||||
// input ceiling rides along -- the user picks against the contwin,
|
// spec's provider default) -- the '' provider option says so.
|
||||||
// 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.
|
|
||||||
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
|
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
|
||||||
export function modelsBox(mount, { title }) {
|
export function modelsBox(mount, { title }) {
|
||||||
const root = typeof mount === 'string' ? $(mount) : mount;
|
const root = typeof mount === 'string' ? $(mount) : mount;
|
||||||
root.textContent = '';
|
root.textContent = '';
|
||||||
root.appendChild(el('h2', null, title));
|
root.appendChild(el('h2', null, title));
|
||||||
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
|
|
||||||
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
|
/** @typedef {{ prov: HTMLSelectElement, mod: HTMLSelectElement, eff: HTMLSelectElement }} Row */
|
||||||
const pField = el('label', 'field', 'player ');
|
/** @param {string} role @returns {Row} */
|
||||||
pField.appendChild(playerSel);
|
const mkRow = (role) => {
|
||||||
const hField = el('label', 'field', 'housekeeper ');
|
const prov = /** @type {HTMLSelectElement} */ (el('select'));
|
||||||
hField.appendChild(houseSel);
|
const mod = /** @type {HTMLSelectElement} */ (el('select'));
|
||||||
root.appendChild(pField);
|
const eff = /** @type {HTMLSelectElement} */ (el('select'));
|
||||||
root.appendChild(hField);
|
const field = el('label', 'field', `${role} `);
|
||||||
const knobHint = el('div', 'knob-hint'); // one bar, both roles
|
field.appendChild(prov);
|
||||||
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
|
field.appendChild(mod);
|
||||||
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
|
field.appendChild(eff);
|
||||||
root.appendChild(playerKnobs.wrap);
|
root.appendChild(field);
|
||||||
root.appendChild(houseKnobs.wrap);
|
return { prov, mod, eff };
|
||||||
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;
|
|
||||||
};
|
};
|
||||||
/** rebuild both knob rows against the current selects and the
|
const player = mkRow('player');
|
||||||
* latest fill (fill and select-change both land here) */
|
const house = mkRow('housekeeper');
|
||||||
function rebuildKnobs() {
|
const healthLine = el('div', 'hint');
|
||||||
if (!last) return;
|
root.appendChild(healthLine);
|
||||||
const pk = knobsBox('player', last.params?.player ?? undefined, last.paramDefaults?.player ?? undefined, knobHint, effortOf('player', last.reg));
|
const hint = el('div', 'hint');
|
||||||
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);
|
root.appendChild(hint);
|
||||||
}
|
|
||||||
const saveBtn = el('button', null, 'save models');
|
const saveBtn = el('button', null, 'save models');
|
||||||
const saveState = el('span', 'save-state');
|
const saveState = el('span', 'save-state');
|
||||||
const actions = el('div', 'form-actions');
|
const actions = el('div', 'form-actions');
|
||||||
actions.appendChild(saveBtn);
|
actions.appendChild(saveBtn);
|
||||||
actions.appendChild(saveState);
|
actions.appendChild(saveState);
|
||||||
root.appendChild(actions);
|
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 () => {
|
saveBtn.addEventListener('click', async () => {
|
||||||
try {
|
try {
|
||||||
// the knob read throws on an empty override -- same banner, nothing sent
|
/** @param {Row} row @param {string} role @returns {?{ provider: string, model: string, effort: string }} */
|
||||||
const params = { player: playerKnobs.read(), housekeeper: houseKnobs.read() };
|
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`, {
|
await api(`/runs/${state.runId}/model`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: {
|
body: { player: specOf(player, 'player'), housekeeper: specOf(house, 'housekeeper') },
|
||||||
player: playerSel.value || null,
|
|
||||||
housekeeper: houseSel.value || null,
|
|
||||||
params,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
saveState.textContent = 'saved';
|
saveState.textContent = 'saved';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -323,21 +331,68 @@ export function modelsBox(mount, { title }) {
|
|||||||
saveState.textContent = 'not saved';
|
saveState.textContent = 'not saved';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
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 */
|
/** @param {{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }} models run.json verbatim (the spec picks)
|
||||||
fill(models, defaults, params, paramDefaults, reg) {
|
* @param {?{ player?: ?import('./shapes.mjs').RoleHealth, housekeeper?: ?import('./shapes.mjs').RoleHealth }} modelState the resolved truth
|
||||||
fillSelect(playerSel, models?.player ?? null, reg, defaults?.player);
|
* @param {?{ slug: string, default: ?{ model: string, effort: string } }[]} providerDefaults
|
||||||
fillSelect(houseSel, models?.housekeeper ?? null, reg, defaults?.housekeeper);
|
* @param {import('./shapes.mjs').ModelsRegistryResponse} theReg */
|
||||||
last = { params: params ?? null, paramDefaults: paramDefaults ?? null, reg };
|
fill(models, modelState, providerDefaults, theReg) {
|
||||||
rebuildKnobs();
|
reg = theReg;
|
||||||
const hint = root.querySelector('.registry-hint');
|
/** @param {Row} row @param {'player'|'housekeeper'} role */
|
||||||
if (hint) {
|
const fillRole = (row, role) => {
|
||||||
hint.textContent = reg.phase === 'none'
|
// the prefill is the run's OWN stored pick only -- an
|
||||||
? 'no models discovered -- the op runs discovery from the admin block on home'
|
// inherited housekeeper stays '' (saving an explicit pick is
|
||||||
: reg.phase === 'preliminary'
|
// a deliberate act; the health line states what inherits)
|
||||||
? 'preliminary registry -- unrefined: the op can run refine to verify and label the models'
|
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 = '';
|
saveState.textContent = '';
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user