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
|
||||
creative content is theirs. GM-private files (gm.md) are never edited
|
||||
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
|
||||
section when it slimmed, 2026-11-15): character and world work is
|
||||
done together, unhurried ("we'll get there together"); the GM runs
|
||||
@@ -154,6 +164,89 @@ memory the agent owes itself across sessions.
|
||||
|
||||
## 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
|
||||
VM, bare but ready.** The connection specifics (address, port,
|
||||
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
|
||||
("rewind") matches instantly while the send is still in flight and
|
||||
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
|
||||
-- waiting for static skeleton text ("RUNS", the aside headings)
|
||||
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.
|
||||
- Open decisions live in QUESTIONS.md -- read it first; the resolved
|
||||
record is DECISIONS.md (the old queue, kept by number). QUESTIONS is
|
||||
open items only now (2026-11-15 split). Remaining: #16 (which model
|
||||
the housekeeper defaults to), #19c
|
||||
(seed voice, GM may revisit -- non-blocking), and the turn-surgery
|
||||
build details.
|
||||
open items only now (2026-11-15 split). Remaining: #19c only (seed
|
||||
voice, GM may revisit -- non-blocking). #16 closed with the provider
|
||||
round (2026-11-18: the housekeeper inherits the player spec's
|
||||
provider default), the turn-surgery details with the rewind round.
|
||||
- The tree is usually dirty by design; git status is not an alarm.
|
||||
- Edit-tool lesson repeated (2026-11-13): nested-list indentation in
|
||||
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,
|
||||
and accepts an explicit override for the deliberate skip. One line to
|
||||
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 deployment** -- one clone plus `server.json`, `state/`, and
|
||||
`runs/` (all gitignored): the unit of sharing. Invited users need
|
||||
n
|
||||
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.
|
||||
- **the package** -- a preset: authored content only, no state.
|
||||
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
|
||||
|
||||
- **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 rewind round**: the GM's take-back riding the send --
|
||||
`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
|
||||
turn, real memory seeds, a gm.md (the task stream, the facility's
|
||||
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
|
||||
temp pid file; sessions rebuilt for Chloe and Irene at boot).
|
||||
state/ holds the refined registry. Four commits await the GM's
|
||||
push (`bbaf336`, `5279dd3`, `eefb721`, `53f992a` -- the ssh key
|
||||
takes a passphrase, pushes are the GM's).
|
||||
state/ holds the refined registry (per-provider shape on disk,
|
||||
migrated in the no-legacy pass) and the provider config
|
||||
('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
|
||||
|
||||
1. **First start under multiuser (op, one-time).** Start the server
|
||||
normally, claim the bootstrap invite
|
||||
(`state/bootstrap-invite.txt` and the console both carry it).
|
||||
Nothing live has touched the auth spine yet -- mock-proven only.
|
||||
2. **The fresh run.** Create it from la caramba (the box waits on its
|
||||
files), pick the model and the effort at create time, and play.
|
||||
1. **The deploy build.** The free-default call is RESOLVED
|
||||
(2026-11-18, the provider round): the opencode/free singleton
|
||||
ships -- auto-added and discovered on the empty provider list,
|
||||
playable with zero secrets; the box's first refine on it is
|
||||
the live test of whether its free models pass the battery's
|
||||
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
|
||||
first live test (the audience doctrine, the typography rule, the
|
||||
no-echo teaching), the full-block protocol's first live run (her
|
||||
first own whole-list emission is still unplayed), the measured
|
||||
effort default riding unset turns, and the turn meter under real
|
||||
use. Her first stop carries the first real housekeeping pass, the
|
||||
slidwin carry test, and the boundary state note. Decide before
|
||||
the first turn whether max effort is wanted: a fresh glm-5.3 run
|
||||
sends `reasoning_effort: max` by the measured default (the
|
||||
disposable test run's turns thought 12.1k/3.9k/6.5k chars against
|
||||
~1.4k of prose) -- the knob is one click on the run's model box.
|
||||
3. **Prompt reviews (GM-led).** housekeeper.md: read it, tweak,
|
||||
first live test (the audience doctrine, the typography rule,
|
||||
the no-echo teaching), the reminder's checked-action metrics,
|
||||
the full-block protocol's first live run (her first own
|
||||
whole-list emission is still unplayed), and the spec picks and
|
||||
the turn meter under real use. Her first stop carries the first
|
||||
real housekeeping pass, the slidwin carry test, and the boundary
|
||||
state note. The effort is a deliberate pick now (there is no
|
||||
unset effort): decide it at the setup box -- the measured
|
||||
ladders pre-select each model's max-mean level.
|
||||
3. **The style pilot (zero build -- the design research's own
|
||||
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
|
||||
applied. curator.md likewise: read, red-pen, re-run refine (one
|
||||
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.
|
||||
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
|
||||
protocol's firsts (does she restate her blocks every turn or on
|
||||
change; does the `<model>` block teach her anything; does she
|
||||
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
|
||||
curve, the prompt-craft rules against a live model (no-echo,
|
||||
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.
|
||||
does she adopt or fight it), the conflict quotes doing their
|
||||
job (does a kept mistake stop repeating), the rewind under real
|
||||
regret, the effort knob's texture and cost curve, the
|
||||
prompt-craft rules against a live model (no-echo,
|
||||
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)
|
||||
|
||||
- **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 fresh run's first real regret is its first live test, and the
|
||||
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
|
||||
|
||||
### 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
|
||||
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)
|
||||
|
||||
A deployment is one clone plus `server.json`, `state/`, and `runs/` --
|
||||
all gitignored state. The LLM key lives on the backend; invited users
|
||||
A deployment is one clone plus `state/` and `runs/` (all gitignored
|
||||
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
|
||||
else: no usernames, no passwords, no external IDPs. A single-use
|
||||
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
|
||||
`state/packages/` -- published to everyone, gm.md included (saving is
|
||||
the act of publishing), the pc never riding.
|
||||
- **Models are per-run over the deployment defaults.** `server.json`
|
||||
names the defaults (player, housekeeper); a run's owner overrides
|
||||
either role from the upstream listing -- 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.
|
||||
- **Models are per-run picks of full specs.** A pick is
|
||||
{provider, model, effort} -- there is no unset effort (it
|
||||
substantially changes inference quality, so it is a property of the
|
||||
pick, GM 2026-11-18), and the per-run sampling-knob layer is
|
||||
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
|
||||
an extension point, not built.
|
||||
- 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
|
||||
`tool/bridge.mjs` is deleted: it never went live, and the server
|
||||
reached mock-parity (2026-11-14).
|
||||
Config: copy `server.example.json` to `server.json` (gitignored) -- any
|
||||
OpenAI-compatible endpoint; put the key in the endpoint's `apiKey`
|
||||
field or name an env var via `apiKeyEnv`; `models` names the player
|
||||
and housekeeper defaults (the op's explicit pick -- it beats the
|
||||
registry's discovered default), `contwin` (the context window; the old
|
||||
`contextWindow` key still accepted) drives the context meter,
|
||||
`params` holds the deployment-default sampling knobs per role
|
||||
(temperature, top_p, top_k, repetition_penalty, max_tokens,
|
||||
reasoning_effort) -- a
|
||||
run carries its own overrides for models and knobs in `run.json`,
|
||||
merged over the deployment layer. The five numeric knobs send only
|
||||
when set (the provider's serving defaults are unknowable, so no
|
||||
default is honestly nameable); reasoning_effort is the exception --
|
||||
the battery measured a per-model default (the effort level with the
|
||||
highest observed mean thinking), so its unset state sends that, and
|
||||
an explicit null clears to nothing (the model id's baked default
|
||||
applies). It is the GM's knob alone: hidden from the model, never
|
||||
in the mind verb, never in the `<model>` display block -- it rides
|
||||
the via record, the raw surfaces carry it. The knob UX
|
||||
(web/knobs.mjs) is explicit: a per-knob override toggle (off = unset,
|
||||
the input disabled; on demands a number, a level for the enum), the
|
||||
definitions table
|
||||
carrying every text -- label, hint, this endpoint's probed bounds --
|
||||
and one shared hint bar driven by focus; unset and set-to-the-
|
||||
deployment-default are distinct states, the run detail exposes the
|
||||
deployment layer (`paramDefaults`), and the provider's own serving
|
||||
defaults stay unstated. Above every layer sits the mind verb -- the
|
||||
player's own one-shot statement for its next turn (the play protocol
|
||||
above). `--mock` runs
|
||||
Config is self-healing state, not a hand-edited file (GM, 2026-11-18):
|
||||
the provider entities -- slug, baseUrl, optional key, the op's
|
||||
default model spec -- live in `state/config.json`, written only by
|
||||
the server, managed from the SPA's admin block. `server.json`
|
||||
(gitignored, optional) is the static remainder: `bind` and `contwin`
|
||||
(the context budget in tokens). No legacy config shapes are read:
|
||||
shape changes come with one-time migrations, not permanent tolerance
|
||||
(the no-legacy rule, GM, 2026-11-18). Boot always succeeds: a fresh clone with nothing comes
|
||||
up serving and mints the superuser invite, and -- the self-heal
|
||||
rule, broadly: an error that can be mechanically fixed to a
|
||||
reasonable degree without requiring human input gets fixed -- the
|
||||
empty provider list is auto-fixed by adding opencode/free (the
|
||||
anonymous, keyless fallback: fixed slug and base, never carrying
|
||||
auth -- a 401 from it is upstream breakage to show, not a prompt to
|
||||
fix) and running its discovery in the background. The list is never
|
||||
empty in lifetime either: opencode/free is removable only while
|
||||
another provider stands. Custom providers add from the SPA taking
|
||||
only the endpoint (a slug and a baseUrl -- never a key): discovery
|
||||
runs on add and IS the probe (GM, 2026-11-19). A working keyless
|
||||
listing never sees a key field; a recognizable auth refusal (401/403)
|
||||
stands the provider broken and opens the key path -- the key rides
|
||||
the auth route, checked on reception, saved only on success, asked
|
||||
again on the next refusal; every other failure refuses the add
|
||||
outright, nothing stands. The card reads the last probe outcome, and
|
||||
only the explicit acts move it (add, key, remove-key, discover) --
|
||||
usage errors are transient and the op's to fix, nothing auto-flips.
|
||||
A keyed provider carries a remove-key control: a provider gone
|
||||
public, or the first half of a replacement (the ask re-opens when
|
||||
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
|
||||
the server plus a fiction-first UI, a
|
||||
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
|
||||
transcripts -- same pattern as the housekeeper, smaller job.
|
||||
|
||||
**Model discovery** is the op's two-step act from the SPA's admin
|
||||
block, and the registry it writes (`state/models.json`) is the truth
|
||||
of selectable models -- a fresh deployment has none and model use is
|
||||
disabled until the op acts. **Discover** scrapes the provider
|
||||
surface: API metadata only, zero inference, the preliminary list.
|
||||
**Refine** runs the deterministic battery over that list -- the
|
||||
tool-manifest ping (the exact request shape a player turn takes; a
|
||||
model that cannot take it is not an inference model and stays out of
|
||||
the selectors), two reasoning samples on a fixed puzzle, the
|
||||
disable-thinking probe whose working spelling is recorded as a
|
||||
discovered fact, and the reasoning-effort probe: each level of the
|
||||
ladder (`none` through `max`) measured for mean thinking, the
|
||||
per-model default being the level with the highest observed mean
|
||||
(GM, 2026-11-16: maximum thinking by default, overridable) -- then
|
||||
hands the adjudicated results to the
|
||||
best-measured model (repo craft: `curator.md`) for the
|
||||
presentation layer: families, labels, descriptions, role
|
||||
eligibility. The curator's output is strictly validated; any
|
||||
failure falls back to the machine list, so discovery can never be
|
||||
blocked by a bad model day. Defaults never consult the curator: the
|
||||
max-reasoning rule picks them (most measured thinking, then input
|
||||
ceiling, then output ceiling, then id), for both roles. Refine sends
|
||||
real traffic over every listed model and is armed with the warning;
|
||||
discover is free but resets a refined registry to the fresh scrape.
|
||||
**Model discovery** is per provider, the op's acts from the SPA's
|
||||
admin block, and the registry it writes (`state/models.json`, one
|
||||
section per provider) is the truth of selectable models -- a
|
||||
provider not discovered has nothing selectable. **Discover** scrapes
|
||||
one provider's surface: API metadata only, zero inference, the
|
||||
section written preliminary (free, but it resets a refined section
|
||||
-- the battery results are re-earned by refining). **Refine** runs
|
||||
the deterministic battery over that provider's list -- the
|
||||
tool-manifest ping at the working effort (the exact request shape a
|
||||
player turn takes; a model that cannot take it is not an inference
|
||||
model and stays out of the selectors), two reasoning samples on a
|
||||
fixed puzzle, the disable-thinking probe whose working spelling is
|
||||
recorded as a discovered fact, and the reasoning-effort ladder
|
||||
(each level measured for mean thinking) -- then hands the
|
||||
adjudicated results to the op's selected default model (repo
|
||||
craft: `curator.md`) for the presentation layer: families, labels,
|
||||
descriptions, role eligibility, and one overall-best recommendation
|
||||
{model, effort} -- intel only, shown beside the op's selection,
|
||||
applied by one click, never auto-landed, and never a deterministic
|
||||
stand-in on a bad model day (the op gets no advice, not machine
|
||||
advice). The curator's output is strictly validated; any failure
|
||||
falls back to the machine list, so refine can never be blocked by a
|
||||
bad model day. The battery's measured effortDefault is pre-fill and
|
||||
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
|
||||
|
||||
@@ -718,16 +752,23 @@ server/ the substrate: a zero-dependency node:http service
|
||||
/session (raw, the audit surface), GET /table (the
|
||||
play view), GET /story (the whole deliverable),
|
||||
GET /carryover (the dormant preview)
|
||||
provider.mjs the endpoint client (chat completions, models listing
|
||||
with metadata)
|
||||
provider.mjs the provider clients (one per configured entity --
|
||||
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
|
||||
(state/deployment.db; hashes only, spent invites
|
||||
recorded forever)
|
||||
discovery.mjs model discovery: the two op acts -- discover (the
|
||||
metadata scrape) and refine (the deterministic
|
||||
battery, the curator pass, the registry write);
|
||||
state/models.json is the registry the selectors,
|
||||
model routes, and the turn loop gate on
|
||||
discovery.mjs model discovery, per provider: discover (the
|
||||
metadata scrape, the section reset) and refine (the
|
||||
battery, the curator pass, the recommendation, the
|
||||
spec-keyed adjudication cache);
|
||||
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,
|
||||
the GM-message bundle, @ sigils + $ vars), the tool manifest
|
||||
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)
|
||||
widgets.mjs the shared factories: armedButton (the two-click
|
||||
confirm), paneEditor (the status/agenda pattern),
|
||||
modelsBox (per-run model selects over the listing)
|
||||
knobs.mjs the sampling knobs: the definitions table (every
|
||||
knob text -- label, hint, this endpoint's probed
|
||||
bounds) and the per-role row with the explicit
|
||||
override toggle and the shared hint bar
|
||||
modelsBox (the per-run spec picks: provider, model,
|
||||
effort per role, the invalidation health line)
|
||||
knobs.mjs the reasoning-effort ladder (mirrors the server's)
|
||||
and the effort select -- the per-run knob rows are
|
||||
retired (params are per-turn, the mind verb's alone)
|
||||
transcript.mjs register rendering (speech / narration / OOC) and
|
||||
the session-log entry walk (historical opening
|
||||
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/
|
||||
static naming (never "api"), the bundle boundary,
|
||||
dateless memory
|
||||
server.example.json copy to server.json (gitignored) -- bind, endpoint +
|
||||
key env, models, contwin, params passthrough
|
||||
server.example.json copy to server.json (gitignored, optional) --
|
||||
bind, contwin; the providers are SPA-managed state
|
||||
db/
|
||||
schema.sql entries, records, events journal (shared; the status
|
||||
and agenda tables are retired -- the log is their
|
||||
one truth, old runs keep dead tables, never read)
|
||||
state/ per-deployment people + shared packages (gitignored):
|
||||
deployment.db (users, invites), bootstrap-invite.txt,
|
||||
models.json (the discovered registry -- the truth of
|
||||
selectable models), packages/ (user-saved, published
|
||||
to everyone)
|
||||
config.json (the provider entities -- server-written,
|
||||
SPA-managed), models.json (the per-provider registry
|
||||
-- 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
|
||||
id per run (carries no facts): run.json (lineage,
|
||||
owner, `forked` stamp on a fork, models and params --
|
||||
per-run player/housekeeper overrides and sampling
|
||||
owner, `forked` stamp on a fork, models -- the
|
||||
per-run player/housekeeper specs; the params layer is
|
||||
retired, per-turn via the mind verb), settings.json
|
||||
knobs), settings.json, gm.md
|
||||
(the GM's notepad), manifests/, and sessions/<n>/ per
|
||||
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)
|
||||
|
||||
- template package
|
||||
- inventorise possible human roles (clear distinction between GM and the developer)
|
||||
- revisit the debug mode, hardcode loobpack
|
||||
- "create new package" in SPA
|
||||
- sec review
|
||||
- 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,
|
||||
written by the op's two-step discover/refine act and gating all
|
||||
model use; server.json's explicit pick beats the registry's
|
||||
discovered default.) Which model the housekeeper DEFAULT points at
|
||||
stays open (#16); the mechanism is settled.
|
||||
(Amended 2026-11-18, the provider round: the picks are full specs
|
||||
{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
|
||||
(ruled 2026-11-13; cut executed by the GM 2026-11-14).** Three tiers,
|
||||
three files:
|
||||
@@ -188,7 +196,22 @@ example, gitignored real file, env-var option).
|
||||
discussion, a gitea runner the leading idea; node on the box
|
||||
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
|
||||
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;
|
||||
untouched until its drafting session.
|
||||
- **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.
|
||||
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)
|
||||
|
||||
- **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
|
||||
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)
|
||||
|
||||
- **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):
|
||||
|
||||
```
|
||||
{"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:
|
||||
|
||||
- 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.
|
||||
- Deep reasoning is an asset for both roles. Never demote a model
|
||||
for latency or for how much it thinks -- this deployment values
|
||||
correctness over speed, and its default is the deepest reasoner
|
||||
available.
|
||||
correctness over speed, and the deepest reasoner is the natural
|
||||
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
|
||||
malformed field, or any extra structure discards the whole list
|
||||
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
|
||||
|
||||
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
|
||||
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",
|
||||
"endpoint": {
|
||||
"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": {}
|
||||
}
|
||||
"contwin": 262144
|
||||
}
|
||||
|
||||
+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:
|
||||
// - discover: scrape the provider surface (GET /models) -- API
|
||||
// metadata only, zero inference. Writes the preliminary registry.
|
||||
// - refine: run the inference battery over the scrape (deterministic
|
||||
// probes, fixed prompts, fixed rules), then hand the adjudicated
|
||||
// results to the best passing model (repo craft: curator.md) for
|
||||
// the final registry -- families, labels, descriptions. The
|
||||
// curator's output is strictly validated; any failure falls back
|
||||
// to the raw deterministic list, so a bad model day can never
|
||||
// block discovery. Defaults stay deterministic either way: the
|
||||
// max-reasoning rule picks them, never the curator, and full ties
|
||||
// settle by the lex rule (rankSort).
|
||||
// Two steps, both op acts from the SPA's admin block, both per
|
||||
// provider (GM, 2026-11-18):
|
||||
// - discover: scrape one provider's surface (GET /models) -- API
|
||||
// metadata only, zero inference. Writes that provider's registry
|
||||
// section, resetting it to preliminary; the other sections are
|
||||
// untouched. Cheap by design -- re-running it is nothing to
|
||||
// treasure (o/f churns its model list, and discovery churn with it
|
||||
// is expected).
|
||||
// - refine: run the inference battery over that provider's scrape
|
||||
// (deterministic probes, fixed prompts, fixed rules), then hand
|
||||
// the adjudicated results to the op's selected default model (repo
|
||||
// craft: curator.md) for labels and one overall-best recommendation
|
||||
// -- intel only, applied by the op's click, never auto-landed. The
|
||||
// curator's output is strictly validated; any failure falls back to
|
||||
// the raw deterministic list and no recommendation, so a bad model
|
||||
// day can never block discovery -- the op just gets no advice.
|
||||
//
|
||||
// The registry (state/models.json) is the truth of selectable
|
||||
// models: a fresh deployment has none and model use is disabled
|
||||
// until the op discovers. The selectors read it, the model routes
|
||||
// validate against it, the turn loop enforces it. Mock mode runs
|
||||
// the same two steps over a canned surface -- no network, instant.
|
||||
// The adjudication cache (state/refine-cache.json): a refined entry
|
||||
// is a function of the full spec tuples on both sides -- the probed
|
||||
// model at the effort the deployment will actually send, and the
|
||||
// curator at its own spec (a weak curator at a low effort adjudicates
|
||||
// worse; it is an inference request like any other). Keyed by
|
||||
// {provider, model, effort, curator-model, curator-effort}; a refine
|
||||
// that sees the same tuple reuses the cached entry and refreshes it
|
||||
// in place when it re-probes. Discovery never touches the cache --
|
||||
// the scrape is cheap, the battery is what costs.
|
||||
//
|
||||
// The registry (state/models.json) is per-provider sections, the
|
||||
// truth of selectable models: the selectors read a section, the model
|
||||
// routes validate against it, the turn loop enforces it. A provider
|
||||
// not in the config has no section. Mock mode runs the same steps
|
||||
// over canned surfaces -- no network, instant.
|
||||
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
|
||||
/** @typedef {import('./shapes.mjs').RegistryModel} RegistryModel */
|
||||
/** @typedef {import('./shapes.mjs').RegistrySection} RegistrySection */
|
||||
/** @typedef {import('./shapes.mjs').ModelRegistry} ModelRegistry */
|
||||
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
||||
/** @typedef {import('./shapes.mjs').Actor} Actor */
|
||||
@@ -30,11 +45,12 @@ import { fileURLToPath } from 'node:url';
|
||||
import { parseManifest } from './housekeeping.mjs';
|
||||
import { ASK_GM_TOOL } from './bundle.mjs';
|
||||
import { HttpError } from './loop.mjs';
|
||||
import { providerFor } from './provider.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const REGISTRY_PATH = path.join(ROOT, 'state', 'models.json');
|
||||
const CACHE_PATH = path.join(ROOT, 'state', 'refine-cache.json');
|
||||
const CURATOR_PROMPT = path.join(ROOT, 'curator.md');
|
||||
const JOB_KEY = 'discovery';
|
||||
|
||||
// the reasoning battery's fixed puzzle -- same every run, so the
|
||||
// buckets stay comparable across models and across discoveries
|
||||
@@ -42,10 +58,9 @@ const PUZZLE = 'A bat and ball cost 1.10 in total. The bat costs 1.00 more than
|
||||
|
||||
// reasoning buckets, by measured thinking tokens (the max of the
|
||||
// samples): the thresholds sit in the gaps the live endpoint showed
|
||||
// (off 0 / low ~5 / standard ~10 / deep 150+). The pick rule ranks
|
||||
// on the bucket, not the raw count: within a bucket the differences
|
||||
// are sampling noise (the alias twins flip run to run), so only the
|
||||
// bucket is a real difference.
|
||||
// (off 0 / low ~5 / standard ~10 / deep 150+). The bucket, not the
|
||||
// raw count, is the real difference -- within a bucket the
|
||||
// differences are sampling noise.
|
||||
/** @param {number} tokens @returns {'off'|'low'|'standard'|'deep'} */
|
||||
function bucket(tokens) {
|
||||
if (tokens <= 0) return 'off';
|
||||
@@ -56,92 +71,168 @@ function bucket(tokens) {
|
||||
|
||||
// --- the registry file --------------------------------------------------------
|
||||
|
||||
/** @returns {?ModelRegistry} */
|
||||
/** The registry, as state/models.json holds it: one section per
|
||||
* configured provider slug. A provider absent from the config has
|
||||
* no section (removal deletes it); a provider not yet discovered
|
||||
* has none either. No legacy shapes are read (the no-legacy rule,
|
||||
* GM, 2026-11-18): shape changes come with one-time migrations of
|
||||
* the file, not permanent tolerance in the reader.
|
||||
* @returns {?ModelRegistry} */
|
||||
export function registry() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8'));
|
||||
const reg = /** @type {?ModelRegistry} */ (JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf8')));
|
||||
return reg && typeof reg === 'object' && reg.providers && typeof reg.providers === 'object' && !Array.isArray(reg.providers) ? reg : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {ModelRegistry} reg */
|
||||
function write(reg) {
|
||||
function writeRegistry(reg) {
|
||||
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
|
||||
fs.writeFileSync(REGISTRY_PATH, JSON.stringify(reg, null, 2) + '\n');
|
||||
}
|
||||
|
||||
/** A model is usable when the registry knows it and the battery (or
|
||||
* the preliminary scrape) has not disqualified it. */
|
||||
/** @param {?ModelRegistry} reg @param {string} id @returns {boolean} */
|
||||
export function usable(reg, id) {
|
||||
return !!reg && reg.models.some((m) => m.id === id && m.inference !== false);
|
||||
/** @param {string} slug @returns {?RegistrySection} */
|
||||
export function sectionOf(slug) {
|
||||
return registry()?.providers[slug] ?? null;
|
||||
}
|
||||
|
||||
/** Write one provider's section; the others are untouched.
|
||||
* @param {string} slug @param {RegistrySection} section */
|
||||
function writeSection(slug, section) {
|
||||
const reg = registry() ?? /** @type {ModelRegistry} */ ({ providers: {} });
|
||||
reg.providers[slug] = section;
|
||||
writeRegistry(reg);
|
||||
}
|
||||
|
||||
/** Remove one provider's section whole -- provider removal's other
|
||||
* half (the runs that rode it invalidate at their next send).
|
||||
* @param {string} slug */
|
||||
export function deleteSection(slug) {
|
||||
const reg = registry();
|
||||
if (!reg || !reg.providers[slug]) return;
|
||||
delete reg.providers[slug];
|
||||
writeRegistry(reg);
|
||||
}
|
||||
|
||||
/** A model is usable when its provider's section knows it and the
|
||||
* battery (or the preliminary scrape) has not disqualified it. */
|
||||
/** @param {string} slug @param {string} id @returns {boolean} */
|
||||
export function usable(slug, id) {
|
||||
const m = findModel(slug, id);
|
||||
return !!m && m.inference !== false;
|
||||
}
|
||||
|
||||
/** @param {string} slug @param {string} id @returns {?RegistryModel} */
|
||||
export function findModel(slug, id) {
|
||||
return sectionOf(slug)?.models.find((m) => m.id === id) ?? null;
|
||||
}
|
||||
|
||||
// --- step one: discover (the scrape -- no inference) --------------------------
|
||||
|
||||
/** @param {Ctx} ctx @returns {Promise<RegistryModel[]>} */
|
||||
async function scrape(ctx) {
|
||||
if (ctx.mock) {
|
||||
return [
|
||||
/** The canned mock surface: the two synthetic providers split the
|
||||
* list (the multi-provider tagging rides the smoke end to end), any
|
||||
* other slug gets the full set -- so the SPA's add flow is testable
|
||||
* offline, the o/f singleton included.
|
||||
* @param {string} slug @returns {RegistryModel[]} */
|
||||
function mockSurface(slug) {
|
||||
/** @type {RegistryModel[]} */ const all = [
|
||||
{ id: 'mock', input: 524288, output: 163840, status: 'unrefined' },
|
||||
{ id: 'mock-tie', input: 524288, output: 163840, status: 'unrefined' },
|
||||
{ id: 'mock-cheap', input: 131072, output: 32768, status: 'unrefined' },
|
||||
{ id: 'mock-fail', input: 131072, output: 32768, status: 'unrefined' },
|
||||
];
|
||||
if (slug === 'mock-a') return all.slice(0, 2);
|
||||
if (slug === 'mock-b') return [all[2]];
|
||||
if (slug === 'mock-c') return all;
|
||||
return all.slice(0, 3);
|
||||
}
|
||||
|
||||
/** The mock's probe shapes (the add-flow machine, offline): mock-auth
|
||||
* refuses the listing until a key stands on the entity, mock-lock
|
||||
* refuses whatever is sent, mock-dead never answers. The real
|
||||
* failures carry the same shapes -- 401/403 with the status on the
|
||||
* error, everything else without.
|
||||
* @param {Ctx} ctx @param {string} slug */
|
||||
function mockProbeShape(ctx, slug) {
|
||||
const p = ctx.providerCfg.providers.find((x) => x.slug === slug);
|
||||
if (slug === 'mock-auth' && !(p && p.apiKey)) {
|
||||
throw new HttpError(401, 'the mock refuses unauthenticated listings');
|
||||
}
|
||||
const listed = await ctx.provider.modelsMeta();
|
||||
if (slug === 'mock-lock') {
|
||||
throw new HttpError(401, 'the mock refuses every listing, keyed or not');
|
||||
}
|
||||
if (slug === 'mock-dead') {
|
||||
throw new Error('the mock endpoint did not answer');
|
||||
}
|
||||
}
|
||||
|
||||
/** Scrape one provider: the listing with the API metadata the
|
||||
* registry carries (token ceilings when the provider states them).
|
||||
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistryModel[]>} */
|
||||
async function scrape(ctx, slug) {
|
||||
if (ctx.mock) {
|
||||
mockProbeShape(ctx, slug);
|
||||
return mockSurface(slug).map((m) => ({ ...m }));
|
||||
}
|
||||
const listed = await providerFor(ctx, slug).modelsMeta();
|
||||
return listed.map((m) => ({ id: m.id, input: m.input, output: m.output, status: 'unrefined' }));
|
||||
}
|
||||
|
||||
/** @param {Ctx} ctx @returns {Promise<ModelRegistry>} */
|
||||
export async function discover(ctx) {
|
||||
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
|
||||
throw new HttpError(409, 'a refine is running -- let it finish first');
|
||||
/** Discover one provider: the scrape, the section written
|
||||
* preliminary. Resets a refined section -- the honest behavior, and
|
||||
* the reason the SPA's discover button says so.
|
||||
* @param {Ctx} ctx @param {string} slug @returns {Promise<RegistrySection>} */
|
||||
export async function discover(ctx, slug) {
|
||||
if (!ctx.providerCfg.providers.some((p) => p.slug === slug)) {
|
||||
throw new HttpError(404, `no such provider: ${slug}`);
|
||||
}
|
||||
const models = await scrape(ctx);
|
||||
const reg = /** @type {ModelRegistry} */ ({
|
||||
const models = await scrape(ctx, slug);
|
||||
const section = /** @type {RegistrySection} */ ({
|
||||
phase: 'preliminary',
|
||||
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
|
||||
discovered: new Date().toISOString(),
|
||||
refined: null,
|
||||
defaults: { player: null, housekeeper: null },
|
||||
models,
|
||||
curator: null,
|
||||
recommendation: null,
|
||||
});
|
||||
write(reg);
|
||||
return reg;
|
||||
writeSection(slug, section);
|
||||
return section;
|
||||
}
|
||||
|
||||
// --- step two: refine (the battery + the curator) -----------------------------
|
||||
|
||||
// the reasoning-effort ladder: the spellings the OpenAI-compatible
|
||||
// world agrees on. `none` doubles as the standardized thinking-off
|
||||
// switch. Mirrored in web/knobs.mjs for the select -- keep them in
|
||||
// switch. Mirrored in web/knobs.mjs for the selects -- keep them in
|
||||
// step.
|
||||
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||
|
||||
/** One model's measured thinking under given request params.
|
||||
* @param {Ctx} ctx @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
|
||||
async function thinkingTokens(ctx, id, params) {
|
||||
const data = await ctx.provider.chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...params });
|
||||
* @param {Ctx} ctx @param {string} slug @param {string} id @param {Record<string, unknown>} params @returns {Promise<number>} */
|
||||
async function thinkingTokens(ctx, slug, id, params) {
|
||||
const data = await providerFor(ctx, slug).chat(id, [{ role: 'user', content: PUZZLE }], undefined, { max_tokens: 600, ...params });
|
||||
return Number(data.usage?.completion_tokens_details?.reasoning_tokens ?? 0);
|
||||
}
|
||||
|
||||
/** The reasoning-effort probe: each level's measured mean thinking
|
||||
* (two samples, the battery's granularity). The default is the
|
||||
* level with the highest observed mean -- `none` is never a
|
||||
* candidate, it is the off switch, not a thinking level (GM,
|
||||
* 2026-11-16: maximum observable thinking by default, overridable
|
||||
* by the user). A model that shows no thinking, or that no level
|
||||
* moves, gets null -- nothing rides.
|
||||
* @param {Ctx} ctx @param {string} id @param {(s: string) => void} [say]
|
||||
* candidate, it is the off switch. A model that shows no thinking,
|
||||
* or that no level moves, gets null. Pre-fill and hint only (GM,
|
||||
* 2026-11-18): with effort a property of the model pick, the
|
||||
* measured default never rides a turn implicitly -- it pre-selects
|
||||
* the selection dropdown and informs the curator's recommendation.
|
||||
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say]
|
||||
* @returns {Promise<{ efforts: Record<string, number>, effortDefault: ?string }>} */
|
||||
async function probeEfforts(ctx, id, say = () => {}) {
|
||||
async function probeEfforts(ctx, slug, m, say = () => {}) {
|
||||
/** @type {Record<string, number>} */ const efforts = {};
|
||||
for (const level of EFFORT_LEVELS) {
|
||||
const xs = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
say(`${level}, sample ${i + 1}/2`);
|
||||
try { xs.push(await thinkingTokens(ctx, id, { reasoning_effort: level })); } catch { xs.push(0); }
|
||||
try { xs.push(await thinkingTokens(ctx, slug, m.id, { reasoning_effort: level })); } catch { xs.push(0); }
|
||||
}
|
||||
efforts[level] = Math.round(xs.reduce((a, b) => a + b, 0) / xs.length);
|
||||
}
|
||||
@@ -151,32 +242,34 @@ async function probeEfforts(ctx, id, say = () => {}) {
|
||||
}
|
||||
|
||||
/** The deterministic battery over one model: the tool ping (the
|
||||
* exact request shape a player turn takes), the reasoning samples,
|
||||
* exact request shape a player turn takes -- the working effort
|
||||
* rides, because every real turn sends one), the reasoning samples,
|
||||
* the off-switch probe, the effort ladder. Every failure is a
|
||||
* verdict, never an abort.
|
||||
* @param {Ctx} ctx @param {RegistryModel} m @param {(s: string) => void} [say]
|
||||
* @param {Ctx} ctx @param {string} slug @param {RegistryModel} m @param {(s: string) => void} [say] @param {string} [effort]
|
||||
* @returns {Promise<RegistryModel>} */
|
||||
async function probeOne(ctx, m, say = () => {}) {
|
||||
async function probeOne(ctx, slug, m, say = () => {}, effort = '') {
|
||||
const base = { ...m };
|
||||
delete base.status; // the scrape's mark -- a probed record is no longer unrefined
|
||||
if (ctx.mock) {
|
||||
say('the canned battery');
|
||||
// the canned battery: all three stand-ins are inference models;
|
||||
// mock and mock-tie are a deliberate tie pair (same deep bucket,
|
||||
// same windows -- only the lex rule can part them), the cheap
|
||||
// tier standard. The canned effort ladders exercise both shapes:
|
||||
// the full ladder with max on top, and a capped ladder whose
|
||||
// default is high
|
||||
// same windows), the cheap tier standard. The canned effort
|
||||
// ladders exercise both shapes: the full ladder with max on top,
|
||||
// and a capped ladder whose default is high
|
||||
return m.id === 'mock-cheap'
|
||||
? { ...base, inference: true, think: 120, reasoning: 'standard', offSwitch: null, latency: 5,
|
||||
efforts: { none: 0, minimal: 20, low: 60, medium: 90, high: 120 }, effortDefault: 'high' }
|
||||
: m.id === 'mock-fail'
|
||||
? { ...base, inference: false, fail: 'the canned failure -- a classifier that cannot tool', reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: 3 }
|
||||
: { ...base, inference: true, think: 300, reasoning: 'deep', offSwitch: null, latency: 7,
|
||||
efforts: { none: 0, minimal: 40, low: 100, medium: 200, high: 300, xhigh: 400, max: 500 }, effortDefault: 'max' };
|
||||
}
|
||||
const t0 = Date.now();
|
||||
say('the tool probe');
|
||||
try {
|
||||
await ctx.provider.chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400 });
|
||||
await providerFor(ctx, slug).chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400, ...(effort ? { reasoning_effort: effort } : {}) });
|
||||
} catch (e) {
|
||||
const fail = String(e.message ?? e).split('\n')[0].slice(0, 200);
|
||||
return { ...base, inference: false, fail, reasoning: null, offSwitch: null, efforts: null, effortDefault: null, latency: Date.now() - t0 };
|
||||
@@ -185,14 +278,14 @@ async function probeOne(ctx, m, say = () => {}) {
|
||||
const samples = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
say(`the thinking samples, ${i + 1}/2`);
|
||||
try { samples.push(await thinkingTokens(ctx, m.id, {})); } catch { samples.push(0); }
|
||||
try { samples.push(await thinkingTokens(ctx, slug, m.id, {})); } catch { samples.push(0); }
|
||||
}
|
||||
const think = Math.max(...samples);
|
||||
/** @type {Record<string, unknown>|null} */ let offSwitch = null;
|
||||
if (think > 0) {
|
||||
try {
|
||||
say('the off-switch probe');
|
||||
if (await thinkingTokens(ctx, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
|
||||
if (await thinkingTokens(ctx, slug, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) {
|
||||
offSwitch = { chat_template_kwargs: { enable_thinking: false } };
|
||||
}
|
||||
} catch { /* no off switch -- recorded as absent */ }
|
||||
@@ -201,39 +294,65 @@ async function probeOne(ctx, m, say = () => {}) {
|
||||
/** @type {?string} */ let effortDefault = null;
|
||||
if (think > 0) {
|
||||
try {
|
||||
({ efforts, effortDefault } = await probeEfforts(ctx, m.id, (s) => say(`the effort ladder: ${s}`)));
|
||||
({ efforts, effortDefault } = await probeEfforts(ctx, slug, m, (s) => say(`the effort ladder: ${s}`)));
|
||||
} catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ }
|
||||
}
|
||||
return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency };
|
||||
}
|
||||
|
||||
// the pick rule, deterministic: the deepest reasoning bucket, then
|
||||
// the largest input window, then the largest output ceiling, then
|
||||
// the GM's tie-break -- sort lex, pick the bottom. The bucket, not
|
||||
// the raw token count, is the rank (see bucket). It names the
|
||||
// curator model and the deployment defaults -- correctness never
|
||||
// consults taste.
|
||||
/** @param {RegistryModel[]} models @returns {RegistryModel[]} */
|
||||
function rankSort(models) {
|
||||
const depth = { off: 0, low: 1, standard: 2, deep: 3 };
|
||||
return [...models].sort((a, b) => {
|
||||
const db = depth[b.reasoning ?? 'off'];
|
||||
const da = depth[a.reasoning ?? 'off'];
|
||||
if (db !== da) return db - da;
|
||||
if ((b.input ?? 0) !== (a.input ?? 0)) return (b.input ?? 0) - (a.input ?? 0);
|
||||
if ((b.output ?? 0) !== (a.output ?? 0)) return (b.output ?? 0) - (a.output ?? 0);
|
||||
return a.id < b.id ? 1 : a.id > b.id ? -1 : 0; // lex bottom wins
|
||||
});
|
||||
// --- the adjudication cache ---------------------------------------------------
|
||||
|
||||
/** The cache key: the full spec tuples on both sides -- the probed
|
||||
* model at the effort the deployment will actually send, and the
|
||||
* curator at its own spec. Reasoning effort substantially changes
|
||||
* inference quality (GM, 2026-11-18), so an entry adjudicated under
|
||||
* one tuple never speaks for another.
|
||||
* @param {string} slug @param {string} id @param {string} effort @param {string} cm @param {string} ce @returns {string} */
|
||||
function cacheKey(slug, id, effort, cm, ce) {
|
||||
return `${slug}::${id}::${effort}::${cm}::${ce}`;
|
||||
}
|
||||
|
||||
/** The curator pass: the best model reads the adjudicated results
|
||||
* and writes the presentation layer. Strictly validated -- only
|
||||
* probed inference ids, no inventions; any violation discards the
|
||||
* whole output and the machine list stands.
|
||||
* @param {Ctx} ctx @param {RegistryModel[]} probed @param {RegistryModel} best @param {?Actor} user
|
||||
* @param {?import('./provider.mjs').ProgressFn} [onProgress] @param {?(() => void)} [onRetry]
|
||||
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }>} */
|
||||
async function curate(ctx, probed, best, user, onProgress = null, onRetry = null) {
|
||||
/** @returns {Record<string, RegistryModel>} */
|
||||
function readCache() {
|
||||
try {
|
||||
const c = JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));
|
||||
if (c && typeof c === 'object' && c.entries && typeof c.entries === 'object') {
|
||||
return /** @type {Record<string, RegistryModel>} */ (c.entries);
|
||||
}
|
||||
} catch { /* absent -- the cache starts empty */ }
|
||||
return {};
|
||||
}
|
||||
|
||||
/** @param {Record<string, RegistryModel>} entries */
|
||||
function writeCache(entries) {
|
||||
fs.mkdirSync(path.dirname(CACHE_PATH), { recursive: true });
|
||||
fs.writeFileSync(CACHE_PATH, JSON.stringify({ entries }, null, 2) + '\n');
|
||||
}
|
||||
|
||||
/** Provider removal purges its entries -- the models are gone with
|
||||
* the route.
|
||||
* @param {string} slug */
|
||||
export function purgeCache(slug) {
|
||||
const entries = readCache();
|
||||
const prefix = `${slug}::`;
|
||||
let dirty = false;
|
||||
for (const k of Object.keys(entries)) {
|
||||
if (k.startsWith(prefix)) { delete entries[k]; dirty = true; }
|
||||
}
|
||||
if (dirty) writeCache(entries);
|
||||
}
|
||||
|
||||
// --- the curator pass ---------------------------------------------------------
|
||||
|
||||
/** The curator pass: the op's selected default model reads the
|
||||
* adjudicated results and writes the presentation layer -- labels,
|
||||
* and one overall-best recommendation (intel only). Strictly
|
||||
* validated -- only probed inference ids, no inventions; any
|
||||
* violation discards the whole output and the machine list stands.
|
||||
* @param {Ctx} ctx @param {string} slug @param {RegistryModel[]} probed @param {{ model: string, effort: string }} curatorSpec @param {?Actor} user
|
||||
* @param {?import('./provider.mjs').ProgressFn} [onProgress]
|
||||
* @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }>} */
|
||||
async function curate(ctx, slug, probed, curatorSpec, user, onProgress = null) {
|
||||
if (ctx.mock) {
|
||||
return {
|
||||
list: [
|
||||
@@ -242,6 +361,7 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
|
||||
{ id: 'mock-cheap', family: 'mock', label: 'Mock (cheap)', description: 'The scripted stand-in, cheap tier.', player: true, housekeeper: true },
|
||||
],
|
||||
note: 'curated',
|
||||
recommendation: { model: 'mock', effort: 'max' },
|
||||
};
|
||||
}
|
||||
const facts = probed.map((m) => ({
|
||||
@@ -254,35 +374,27 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
|
||||
{ role: 'user', content: JSON.stringify(facts, null, 2) },
|
||||
]);
|
||||
// attribution (#22): every LLM call names the acting user
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${best.id} u:${user?.id ?? '?'}`);
|
||||
// one retry: the call is long enough to meet a network hiccup, and
|
||||
// a fresh attempt is cheaper than losing the curation
|
||||
let data = null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
data = await ctx.provider.chat(best.id, messages, undefined, {}, onProgress);
|
||||
break;
|
||||
} catch (e) {
|
||||
if (attempt === 1) throw e;
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} curator call failed (${String(e.message ?? e).split('\n')[0]}) -- retrying once`);
|
||||
onRetry?.();
|
||||
}
|
||||
}
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${curatorSpec.model} u:${user?.id ?? '?'}`);
|
||||
// no automatic retries (GM, 2026-11-19): every inference call is
|
||||
// user-initiated and every act has its manual retry -- the refine
|
||||
// button again. A dead call lands the fallback, which is the
|
||||
// designed outcome, not a degraded one
|
||||
const data = await providerFor(ctx, slug).chat(curatorSpec.model, messages, undefined, { reasoning_effort: curatorSpec.effort }, onProgress);
|
||||
if (!data) throw new Error('the curator call failed twice');
|
||||
const known = new Set(probed.filter((m) => m.inference).map((m) => m.id));
|
||||
let parsed;
|
||||
try {
|
||||
parsed = /** @type {{ models?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
|
||||
parsed = /** @type {{ models?: unknown, recommend?: unknown }} */ (parseManifest(data.choices[0].message.content ?? ''));
|
||||
} catch (e) {
|
||||
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})` };
|
||||
return { list: [], note: `fallback: the curator emitted no parseable JSON (${e.message})`, recommendation: null };
|
||||
}
|
||||
const entries = Array.isArray(parsed.models) ? parsed.models : null;
|
||||
if (!entries) return { list: [], note: 'fallback: the curator output has no models array' };
|
||||
if (!entries) return { list: [], note: 'fallback: the curator output has no models array', recommendation: null };
|
||||
const seen = new Set();
|
||||
/** @type {{ id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[]} */ const list = [];
|
||||
for (const e of entries) {
|
||||
if (typeof e !== 'object' || e === null || typeof e.id !== 'string' || !known.has(e.id) || seen.has(e.id)) {
|
||||
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})` };
|
||||
return { list: [], note: `fallback: the curator listed an unknown or duplicate id (${JSON.stringify(e?.id ?? e)})`, recommendation: null };
|
||||
}
|
||||
seen.add(e.id);
|
||||
list.push({
|
||||
@@ -294,99 +406,151 @@ async function curate(ctx, probed, best, user, onProgress = null, onRetry = null
|
||||
housekeeper: e.housekeeper !== false,
|
||||
});
|
||||
}
|
||||
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing' };
|
||||
return { list, note: 'curated' };
|
||||
if (!list.length) return { list: [], note: 'fallback: the curator listed nothing', recommendation: null };
|
||||
// the recommendation: intel only, strictly validated -- a passing
|
||||
// model at a ladder level. Anything else is no advice, never
|
||||
// machine advice (GM, 2026-11-18: on a bad model day the op gets
|
||||
// no recommendation, not a deterministic stand-in)
|
||||
let recommendation = null;
|
||||
const r = /** @type {{ model?: unknown, effort?: unknown }|null|undefined} */ (parsed.recommend);
|
||||
if (r && typeof r === 'object' && typeof r.model === 'string' && known.has(r.model)
|
||||
&& typeof r.effort === 'string' && EFFORT_LEVELS.includes(r.effort)) {
|
||||
recommendation = { model: r.model, effort: r.effort };
|
||||
}
|
||||
return { list, note: 'curated', recommendation };
|
||||
}
|
||||
|
||||
/** The refine job: scrape fresh, battery, adjudicate, curate, write.
|
||||
* Runs async under the jobs map; the registry only moves forward on
|
||||
* a completed pass (a rejected pass changes nothing).
|
||||
* @param {Ctx} ctx @param {?Actor} user @returns {JobState} */
|
||||
export function refine(ctx, user) {
|
||||
const reg = registry();
|
||||
if (!reg) throw new HttpError(409, 'nothing to refine -- run discovery first');
|
||||
if (ctx.jobs.get(JOB_KEY)?.state === 'running') {
|
||||
throw new HttpError(409, 'a refine is already running');
|
||||
// --- the refine job -----------------------------------------------------------
|
||||
|
||||
/** The refine job: scrape fresh, battery, adjudicate, curate, write
|
||||
* the one provider's section. Runs async under the jobs map; the
|
||||
* section only moves forward on a completed pass (a rejected pass
|
||||
* changes nothing).
|
||||
* @param {Ctx} ctx @param {string} slug @param {?Actor} user @returns {JobState} */
|
||||
export function refine(ctx, slug, user) {
|
||||
const provider = ctx.providerCfg.providers.find((p) => p.slug === slug);
|
||||
if (!provider) throw new HttpError(404, `no such provider: ${slug}`);
|
||||
const section = sectionOf(slug);
|
||||
if (!section) throw new HttpError(409, `nothing to refine on '${slug}' -- run its discovery first`);
|
||||
// the curator IS the selected default (GM, 2026-11-18) -- refine
|
||||
// requires the selection
|
||||
const curatorSpec = provider.default;
|
||||
if (!curatorSpec) {
|
||||
throw new HttpError(409, `select '${slug}'s default model first -- the default is also the refine curator`);
|
||||
}
|
||||
// the meter: one step per model's battery plus the curator's two
|
||||
// (thinking, writing) -- the count is known the moment the scrape
|
||||
// lands. No step has a duration to guess at (GM, 2026-11-17): the
|
||||
// bar moves only on real completions, the label names the call
|
||||
// running now, and every completion lands a receipt line -- the
|
||||
// lines survive the job, so a rejected pass keeps its post-mortem
|
||||
const jobKey = `refine:${slug}`;
|
||||
if (ctx.jobs.get(jobKey)?.state === 'running') {
|
||||
throw new HttpError(409, `a refine is already running on '${slug}'`);
|
||||
}
|
||||
// the meter: one step per model's battery (a cache hit closes its
|
||||
// step instantly -- it is a completion, not a wait) plus the
|
||||
// curator's two (thinking, writing). No step has a duration to
|
||||
// guess at (GM, 2026-11-17): the bar moves only on real
|
||||
// completions, the label names the call running now, and every
|
||||
// completion lands a receipt line -- the lines survive the job, so
|
||||
// a rejected pass keeps its post-mortem
|
||||
const t0 = Date.now();
|
||||
// the local view narrows steps/lines to present -- the job is born
|
||||
// with them, and the reporter writes through this reference
|
||||
const job = /** @type {JobState & { steps: { total: number, done: number, label: string, chars?: number }, lines: string[] }} */ ({
|
||||
state: 'running', phase: 'refine', started: new Date().toISOString(),
|
||||
steps: { total: 0, done: 0, label: 'scraping the provider surface' }, lines: [],
|
||||
});
|
||||
ctx.jobs.set(JOB_KEY, job);
|
||||
ctx.jobs.set(jobKey, job);
|
||||
/** @param {string} s */ const say = (s) => { job.steps.label = s; };
|
||||
/** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); };
|
||||
void (async () => {
|
||||
try {
|
||||
const scraped = await scrape(ctx); // fresh metadata -- ids can drift between discoveries
|
||||
const scraped = await scrape(ctx, slug); // fresh metadata -- ids can drift between discoveries
|
||||
if (!scraped.some((m) => m.id === curatorSpec.model)) {
|
||||
throw new Error(`the selected default '${curatorSpec.model}' is not in '${slug}'s current registry -- re-discover and re-select`);
|
||||
}
|
||||
job.steps.total = scraped.length + 2;
|
||||
/** @param {RegistryModel} m @returns {string} */
|
||||
const verdict = (m) => m.inference === false
|
||||
? `failed the tool probe -- ${m.fail}`
|
||||
: `reasoning ${m.reasoning} \u00b7 ${m.think} think tokens \u00b7 ${m.offSwitch ? 'off switch' : 'no off switch'} \u00b7 ${m.latency}ms${m.effortDefault ? ` \u00b7 effort default ${m.effortDefault}` : ''}`;
|
||||
const probed = [];
|
||||
// the adjudication cache: same tuple, same verdict -- churn is
|
||||
// the point (o/f rotates models; the survivors keep their
|
||||
// measured selves between refines)
|
||||
const cache = readCache();
|
||||
/** @type {RegistryModel[]} */ const probed = [];
|
||||
/** @type {RegistryModel[]} */ const fresh = [];
|
||||
for (const [i, m] of scraped.entries()) {
|
||||
probed.push(await probeOne(ctx, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`)));
|
||||
const key = cacheKey(slug, m.id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort);
|
||||
const hit = cache[key];
|
||||
if (hit) {
|
||||
say(`battery ${i + 1}/${scraped.length}: ${m.id} -- cached`);
|
||||
probed.push(hit);
|
||||
line(`${m.id}: from cache`);
|
||||
} else {
|
||||
probed.push(await probeOne(ctx, slug, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`), curatorSpec.effort));
|
||||
fresh.push(probed[probed.length - 1]);
|
||||
// failures never cache (GM, 2026-11-19): a failure is the
|
||||
// absence of a measurement, not a measurement -- the next
|
||||
// refine always re-probes it, so the receipt says so
|
||||
line(`${m.id}: ${verdict(probed[probed.length - 1])}${probed[probed.length - 1].inference === false ? ' -- never cached, retried at every refine' : ''}`);
|
||||
}
|
||||
job.steps.done++;
|
||||
line(`${m.id}: ${verdict(probed[i])}`);
|
||||
}
|
||||
const passing = probed.filter((m) => m.inference);
|
||||
if (!passing.length) throw new Error('no model passed the inference battery -- the provider surface has nothing playable');
|
||||
const best = rankSort(passing)[0];
|
||||
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }} */
|
||||
let curated = { list: [], note: 'fallback: not attempted' };
|
||||
// the curator's two steps, marked from real events: thinking
|
||||
// completes at the first prose delta (the streaming boundary),
|
||||
// writing at the call's resolve; a dead call closes both -- the
|
||||
// attempt is over, and the fallback carries the job
|
||||
let proseStarted = false;
|
||||
say(`curator (${best.id}): thinking`);
|
||||
say(`curator (${curatorSpec.model}): thinking`);
|
||||
/** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string, recommendation: ?{ model: string, effort: string } }} */
|
||||
let curated = { list: [], note: 'fallback: not attempted', recommendation: null };
|
||||
const curatorModel = probed.find((m) => m.id === curatorSpec.model);
|
||||
if (curatorModel?.inference === false) {
|
||||
curated = { list: [], note: 'fallback: the curator model failed the battery -- re-select the default', recommendation: null };
|
||||
line(`curator: ${curated.note}`);
|
||||
} else {
|
||||
try {
|
||||
curated = await curate(ctx, probed, best, user, (p) => {
|
||||
curated = await curate(ctx, slug, probed, curatorSpec, user, (p) => {
|
||||
job.steps.chars = p.chars;
|
||||
if (p.phase === 'prose' && !proseStarted) {
|
||||
proseStarted = true;
|
||||
job.steps.done++;
|
||||
say('curator: writing');
|
||||
}
|
||||
}, () => say(`curator (${best.id}): retrying -- thinking`));
|
||||
});
|
||||
} 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
|
||||
delete job.steps.chars;
|
||||
say('writing the registry');
|
||||
line(curated.note === 'curated' ? `curator (${best.id}): curated \u00b7 ${curated.list.length} labeled` : `curator: ${curated.note}`);
|
||||
line(curated.note === 'curated' ? `curator (${curatorSpec.model}): curated \u00b7 ${curated.list.length} labeled${curated.recommendation ? ` \u00b7 recommends ${curated.recommendation.model} at ${curated.recommendation.effort}` : ''}` : `curator: ${curated.note}`);
|
||||
// labels apply to the freshly probed models only -- a cache hit
|
||||
// keeps the entry it was adjudicated with (the same curator
|
||||
// tuple, the cached verdict IS the verdict)
|
||||
const byId = new Map(curated.list.map((c) => [c.id, c]));
|
||||
const models = probed.map((m) => {
|
||||
if (!fresh.includes(m)) return m; // a cache hit -- kept whole
|
||||
const c = m.inference ? byId.get(m.id) : undefined;
|
||||
return c ? { ...m, family: c.family, label: c.label, description: c.description, roles: { player: c.player, housekeeper: c.housekeeper } } : m;
|
||||
});
|
||||
// the defaults never consult the curator: the max-reasoning
|
||||
// rule over the models eligible for the role
|
||||
/** @param {(m: RegistryModel) => boolean} ok @returns {?string} */
|
||||
const pick = (ok) => {
|
||||
const eligible = models.filter((m) => m.inference && (m.roles?.player ?? true) && ok(m));
|
||||
return eligible.length ? rankSort(eligible)[0].id : null;
|
||||
};
|
||||
const defaults = { player: pick(() => true), housekeeper: pick((m) => m.roles?.housekeeper ?? true) };
|
||||
write(/** @type {ModelRegistry} */ ({
|
||||
writeSection(slug, /** @type {RegistrySection} */ ({
|
||||
phase: 'refined',
|
||||
endpoint: ctx.cfg.endpoint?.baseUrl ?? null,
|
||||
discovered: reg.discovered,
|
||||
discovered: section.discovered,
|
||||
refined: new Date().toISOString(),
|
||||
defaults,
|
||||
models,
|
||||
curator: curated.note,
|
||||
recommendation: curated.recommendation,
|
||||
}));
|
||||
// the cache write-back: every final PASSING entry lands under
|
||||
// its key -- the labeled result, not the bare probe (the cached
|
||||
// entry IS the verdict, curation included), a re-probe refreshes
|
||||
// in place, the survivors persist. Failures never cache (GM,
|
||||
// 2026-11-19): only a measurement is worth keeping -- a failure
|
||||
// is retried at every refine until it stops being one
|
||||
for (const [i, m] of models.entries()) {
|
||||
if (m.inference === false) continue;
|
||||
cache[cacheKey(slug, scraped[i].id, curatorSpec.effort, curatorSpec.model, curatorSpec.effort)] = m;
|
||||
}
|
||||
writeCache(cache);
|
||||
say('done');
|
||||
job.state = 'applied';
|
||||
} catch (e) {
|
||||
@@ -397,7 +561,7 @@ export function refine(ctx, user) {
|
||||
return job;
|
||||
}
|
||||
|
||||
/** @param {Ctx} ctx @returns {?JobState} */
|
||||
export function jobState(ctx) {
|
||||
return ctx.jobs.get(JOB_KEY) ?? null;
|
||||
/** @param {Ctx} ctx @param {string} slug @returns {?JobState} */
|
||||
export function jobState(ctx, slug) {
|
||||
return ctx.jobs.get(`refine:${slug}`) ?? null;
|
||||
}
|
||||
|
||||
+16
-20
@@ -33,8 +33,8 @@ import {
|
||||
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
|
||||
} from './session.mjs';
|
||||
import { effectiveContents } from './variants.mjs';
|
||||
import { HttpError, resolveParams, resolveEffort } from './loop.mjs';
|
||||
import { registry, usable } from './discovery.mjs';
|
||||
import { HttpError, specFromMeta, gateSpec, resolveSpec } from './loop.mjs';
|
||||
import { providerFor } from './provider.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
@@ -232,26 +232,22 @@ async function runPass(ctx, runId, n, user) {
|
||||
*/
|
||||
async function callHousekeeper(ctx, runId, messages, user) {
|
||||
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
|
||||
const reg = registry();
|
||||
const model = meta.models?.housekeeper
|
||||
?? ctx.cfg.models?.housekeeper
|
||||
?? ctx.cfg.models?.player
|
||||
?? reg?.defaults.housekeeper
|
||||
?? reg?.defaults.player
|
||||
?? null;
|
||||
if (!model) throw new Error('no housekeeper model resolved (a per-run override, server.json models, or the registry\'s discovered default)');
|
||||
if (!usable(reg, model)) {
|
||||
throw new Error(`model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
|
||||
// the run's own housekeeper pick, else the player spec's provider's
|
||||
// default (GM, 2026-11-18: the housekeeper inherits -- per-provider
|
||||
// defaults mean no separate deployment default exists to fall to)
|
||||
let spec = specFromMeta(meta.models?.housekeeper, 'housekeeper');
|
||||
if (!spec) {
|
||||
const player = resolveSpec(ctx, runId, 'player');
|
||||
const def = ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null;
|
||||
if (def) spec = { provider: player.provider, model: def.model, effort: def.effort };
|
||||
}
|
||||
const params = { ...resolveParams(ctx, runId, 'housekeeper') };
|
||||
// the effort knob's own layers (its unset state sends the
|
||||
// registry's measured default for this model)
|
||||
const effort = resolveEffort(ctx, runId, 'housekeeper', model);
|
||||
if (effort !== null) params.reasoning_effort = effort;
|
||||
if (!spec) throw new Error('no housekeeper model resolved (the run\'s housekeeper pick, or its player provider\'s default)');
|
||||
gateSpec(ctx, spec, 'housekeeper');
|
||||
const params = { reasoning_effort: spec.effort };
|
||||
// attribution (#22): every LLM call names the acting user
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
|
||||
const data = await ctx.provider.chat(model, messages, undefined, params);
|
||||
return { content: data.choices[0].message.content ?? '', model };
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${spec.model} u:${user?.id ?? '?'}`);
|
||||
const data = await providerFor(ctx, spec.provider).chat(spec.model, messages, undefined, params);
|
||||
return { content: data.choices[0].message.content ?? '', model: spec.model };
|
||||
}
|
||||
export { callHousekeeper };
|
||||
|
||||
|
||||
+65
-65
@@ -27,7 +27,8 @@
|
||||
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
|
||||
import { renderView, cleanBlockList, AGENDA_CAP, rewindTo } from './session.mjs';
|
||||
import { parseVariants, pickVariant } from './variants.mjs';
|
||||
import { registry, usable } from './discovery.mjs';
|
||||
import { providerFor } from './provider.mjs';
|
||||
import { findModel } from './discovery.mjs';
|
||||
|
||||
export class HttpError extends Error {
|
||||
/**
|
||||
@@ -149,43 +150,43 @@ async function runLoop(ctx, runId, user) {
|
||||
let heals = 0;
|
||||
for (;;) {
|
||||
const view = renderView(s);
|
||||
// the request's resolved params: the mind layer rides over the
|
||||
// run and deployment layers, the effort knob resolves its own
|
||||
// layers (its unset state sends the registry's measured default).
|
||||
// The current call's <model> block shows her the knobs that are
|
||||
// hers to answer with <mind> -- reasoning_effort is filtered out
|
||||
// (hidden from the model, GM 2026-11-16: not her call); nothing
|
||||
// set means no block (the absent grammar); the via record lands
|
||||
// the same truth unfiltered, the raw surfaces carry it
|
||||
/** @type {string} */ let model;
|
||||
if (ctx.mock) model = 'mock';
|
||||
else model = resolveModel(ctx, runId);
|
||||
const params = { ...resolveParams(ctx, runId, 'player'), ...(s.mind ?? {}) };
|
||||
const effort = resolveEffort(ctx, runId, 'player', model);
|
||||
if (effort !== null) params.reasoning_effort = effort;
|
||||
// the request's resolved spec: the full inference identity
|
||||
// {provider, model, effort} (GM, 2026-11-18) -- there is no unset
|
||||
// effort, it is a property of the pick. The mind layer is the
|
||||
// only params source now: per-turn, hers, spent on completion
|
||||
// (the per-run knob layer is retired). The current call's
|
||||
// <model> block shows her the knobs that are hers to answer with
|
||||
// <mind> -- reasoning_effort is filtered out (hidden from the
|
||||
// model: not her call, it rides the spec); nothing set means no
|
||||
// block (the absent grammar); the via record lands the same
|
||||
// truth unfiltered, the raw surfaces carry it
|
||||
const spec = resolveSpec(ctx, runId, 'player');
|
||||
const provider = providerFor(ctx, spec.provider);
|
||||
const params = { ...(s.mind ?? {}) };
|
||||
params.reasoning_effort = spec.effort;
|
||||
const shown = { ...params };
|
||||
delete shown.reasoning_effort;
|
||||
if (Object.keys(shown).length) {
|
||||
view.push({ role: 'system', content: `<model>${JSON.stringify(shown)}</model>` });
|
||||
}
|
||||
let msg;
|
||||
/** @type {{ model: string, params: import('./shapes.mjs').RoleParams }} */ let via;
|
||||
/** @type {{ model: string, provider?: string, params: import('./shapes.mjs').RoleParams }} */ let via;
|
||||
if (ctx.mock) {
|
||||
// the synthetic marker: no provider call happens, but the knobs
|
||||
// resolve for real (the mind layer included), so the smoke can
|
||||
// assert the recording
|
||||
// the synthetic marker: no provider call happens, but the spec
|
||||
// and the knobs resolve for real, so the smoke can assert the
|
||||
// recording
|
||||
msg = mockModel(s, view);
|
||||
via = { model: 'mock', params };
|
||||
via = { model: spec.model, provider: spec.provider, params };
|
||||
} else {
|
||||
via = { model, params };
|
||||
via = { model: spec.model, provider: spec.provider, params };
|
||||
// attribution (#22): every LLM call names the acting user
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
|
||||
console.log(`${new Date().toISOString().slice(11, 19)} llm ${spec.model} u:${user?.id ?? '?'}`);
|
||||
// the turn meter's live record: one per provider call (a heal
|
||||
// or tool round restarts it), fed by the streaming deltas
|
||||
s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() };
|
||||
let data;
|
||||
try {
|
||||
data = await ctx.provider.chat(model, view, tools, params, (p) => {
|
||||
data = await provider.chat(spec.model, view, tools, params, (p) => {
|
||||
if (!s.progress) return;
|
||||
s.progress.phase = p.phase;
|
||||
if (p.phase === 'thinking') s.progress.thinking = p.chars;
|
||||
@@ -193,7 +194,7 @@ async function runLoop(ctx, runId, user) {
|
||||
});
|
||||
} catch (e) {
|
||||
s.progress = null;
|
||||
s.append({ t: 'req', model, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
|
||||
s.append({ t: 'req', model: spec.model, provider: spec.provider, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
|
||||
throw e;
|
||||
}
|
||||
msg = data.choices[0].message;
|
||||
@@ -306,55 +307,54 @@ async function runLoop(ctx, runId, user) {
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Ctx} ctx @param {string} runId @returns {string} */
|
||||
function resolveModel(ctx, runId) {
|
||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
const reg = registry();
|
||||
// resolution: the run's pick, the op's server.json pick, the
|
||||
// registry's discovered default -- then the registry gate: model
|
||||
// use is disabled until the op discovers, and a model the battery
|
||||
// disqualified never plays
|
||||
const model = meta.models?.player ?? ctx.cfg.models?.player ?? reg?.defaults.player ?? null;
|
||||
if (!model) {
|
||||
throw new HttpError(409, reg
|
||||
? 'no player model resolved -- set one for this run (POST /model), or a deployment default (server.json, or the registry\'s discovered pick)'
|
||||
: 'no models discovered yet -- the op runs discovery from the admin block first');
|
||||
/** A model spec as run.json carries it: the {provider, model,
|
||||
* effort} object (the no-legacy rule, GM, 2026-11-18 -- the
|
||||
* bare-string era migrated away in the same pass). Malformed
|
||||
* records refuse loud.
|
||||
* @param {unknown} raw @param {'player'|'housekeeper'} role @returns {?import('./shapes.mjs').ModelSpec} */
|
||||
function specFromMeta(raw, role) {
|
||||
if (raw == null) return null;
|
||||
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
const o = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw);
|
||||
if (typeof o.provider === 'string' && typeof o.model === 'string' && typeof o.effort === 'string') {
|
||||
return { provider: o.provider, model: o.model, effort: o.effort };
|
||||
}
|
||||
if (!usable(reg, model)) {
|
||||
throw new HttpError(409, `model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ''} -- pick a discovered model`);
|
||||
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
|
||||
}
|
||||
return model;
|
||||
throw new HttpError(409, `the run's ${role} model record is malformed -- set it again in the model box`);
|
||||
}
|
||||
|
||||
/** The effective sampling knobs for a role: the deployment default
|
||||
* layer (server.json params) under the run's own overrides. */
|
||||
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').RoleParams} */
|
||||
function resolveParams(ctx, runId, role) {
|
||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
return {
|
||||
...(ctx.cfg.params?.[role] ?? {}),
|
||||
...(meta.params?.[role] ?? {}),
|
||||
};
|
||||
/** The invalidation gate (GM, 2026-11-18): the settings the run
|
||||
* came with must still be carried. A provider gone from the
|
||||
* config, a model gone from its provider's registry, a model the
|
||||
* battery disqualified -- all one state: the run blocks until the
|
||||
* GM sets it up again. The error IS the table's note.
|
||||
* @param {Ctx} ctx @param {import('./shapes.mjs').ModelSpec} spec @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
||||
function gateSpec(ctx, spec, role) {
|
||||
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
|
||||
throw new HttpError(409, `the run's ${role} model rides provider '${spec.provider}', which is no longer configured -- set it up again in the model box`);
|
||||
}
|
||||
const m = findModel(spec.provider, spec.model);
|
||||
if (!m) {
|
||||
throw new HttpError(409, `the run's ${role} model '${spec.model}' is not in provider '${spec.provider}'s registry (the discovered ids drifted) -- set it up again in the model box`);
|
||||
}
|
||||
if (m.inference === false) {
|
||||
throw new HttpError(409, `the run's ${role} model '${spec.model}' failed the inference battery -- set it up again in the model box`);
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
|
||||
// The reasoning-effort knob's own resolution (GM, 2026-11-16): unlike
|
||||
// the numeric knobs its unset state SENDS -- the registry measured a
|
||||
// default, so one honestly exists. Layers: the run's override, then
|
||||
// the deployment layer (server.json params), then the registry's
|
||||
// per-model pick -- the level with the highest observed mean
|
||||
// thinking. An explicit null clears the layers: nothing rides, the
|
||||
// model id's baked default applies. Hidden from the model entirely:
|
||||
// never in the mind verb, never in the <model> display block -- it
|
||||
// rides the via record, the raw surfaces carry it.
|
||||
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @param {string} model @returns {?string} */
|
||||
function resolveEffort(ctx, runId, role, model) {
|
||||
/** Resolve one role's spec: the run's pick, gated for validity. No
|
||||
* pick is a loud refusal -- the create flow lands one, so only
|
||||
* picked-clean runs hit this.
|
||||
* @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {import('./shapes.mjs').ModelSpec} */
|
||||
function resolveSpec(ctx, runId, role) {
|
||||
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
const set = meta.params?.[role]?.reasoning_effort ?? ctx.cfg.params?.[role]?.reasoning_effort ?? undefined;
|
||||
if (set !== undefined) return set === null ? null : String(set);
|
||||
const m = registry()?.models.find((x) => x.id === model);
|
||||
return m?.effortDefault ?? null;
|
||||
const spec = specFromMeta(meta.models?.[role], role);
|
||||
if (!spec) throw new HttpError(409, `no ${role} model set for this run -- pick one in the model box`);
|
||||
return gateSpec(ctx, spec, role);
|
||||
}
|
||||
export { resolveModel, resolveParams, resolveEffort };
|
||||
export { specFromMeta, gateSpec, resolveSpec };
|
||||
|
||||
// --- the mind verb ------------------------------------------------------------
|
||||
//
|
||||
|
||||
+390
-115
@@ -26,12 +26,13 @@ import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { makeProvider } from './provider.mjs';
|
||||
import * as providers from './providers.mjs';
|
||||
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
|
||||
import * as bundle from './bundle.mjs';
|
||||
import * as session from './session.mjs';
|
||||
import * as housekeeping from './housekeeping.mjs';
|
||||
import { effectiveContents } from './variants.mjs';
|
||||
import { gmTurn, answerAsk, openingCall, HttpError, resolveParams } from './loop.mjs';
|
||||
import { gmTurn, answerAsk, openingCall, HttpError, specFromMeta, gateSpec } from './loop.mjs';
|
||||
import * as users from './users.mjs';
|
||||
import { forkRun } from './fork.mjs';
|
||||
import * as discovery from './discovery.mjs';
|
||||
@@ -40,20 +41,66 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const MOCK = process.argv.includes('--mock');
|
||||
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
|
||||
|
||||
const CONFIG_PATH = path.join(ROOT, 'server.json');
|
||||
if (!fs.existsSync(CONFIG_PATH)) {
|
||||
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
|
||||
// server.json is the static, non-secret remainder: bind and contwin.
|
||||
// Optional (GM, 2026-11-18) -- the provider entities live in
|
||||
// state/config.json (server-written, SPA-managed). Nothing here gates
|
||||
// the boot: a fresh deployment with no config at all comes up
|
||||
// serving, mints the superuser invite, and shows the global
|
||||
// no-providers banner -- every consumer of providers treats "none"
|
||||
// as a loud 409, never a crash.
|
||||
/** @type {import('./shapes.mjs').ServerCfg} */
|
||||
let cfg = {};
|
||||
const SERVER_JSON = path.join(ROOT, 'server.json');
|
||||
if (fs.existsSync(SERVER_JSON)) {
|
||||
try {
|
||||
cfg = JSON.parse(fs.readFileSync(SERVER_JSON, 'utf8'));
|
||||
} catch {
|
||||
console.error('server.json does not parse -- fix it or remove it (the provider entities live in state/config.json)');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
const cfg = /** @type {import('./shapes.mjs').ServerCfg} */ (JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
|
||||
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
|
||||
const provider = makeProvider(cfg.endpoint ?? {});
|
||||
let providerCfg = providers.readConfig();
|
||||
// the self-heal rule (GM, 2026-11-18), stated broadly: an error that
|
||||
// can be mechanically fixed to a reasonable degree without requiring
|
||||
// human input gets fixed. The empty provider list is one: the
|
||||
// anonymous fallback is added and discovered, as a background job --
|
||||
// boot never blocks on the network, and a failure leaves the empty
|
||||
// state plus the admin block's banner, whose fix path is the same
|
||||
// add act. The mock world seeds its two synthetic providers instead
|
||||
// (offline, the same code path).
|
||||
/** @type {string[]} */
|
||||
const autoAdded = [];
|
||||
if (!providerCfg.providers.length) {
|
||||
if (MOCK) {
|
||||
providerCfg.providers.push(
|
||||
{ slug: 'mock-a', baseUrl: 'mock://a', default: null },
|
||||
{ slug: 'mock-b', baseUrl: 'mock://b', default: null },
|
||||
);
|
||||
autoAdded.push('mock-a', 'mock-b');
|
||||
} else {
|
||||
const p = providers.addBuiltin(providerCfg);
|
||||
if (p) autoAdded.push(p.slug);
|
||||
}
|
||||
providers.writeConfig(providerCfg);
|
||||
}
|
||||
const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)]));
|
||||
// locks/enqueue are attached just below; the cast is the two-step that
|
||||
// lets the literal precede them
|
||||
const ctxBase = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
||||
const ctxBase = { mock: MOCK, cfg, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
|
||||
/** @type {Ctx} */
|
||||
const ctx = /** @type {Ctx} */ (ctxBase);
|
||||
|
||||
// the auto-added providers discover in the background -- no LLM
|
||||
// calls, one GET each, zero cost; a dead network shows as the probe
|
||||
// record on the card (o/f's auth failure reads as upstream breakage,
|
||||
// never a prompt) plus the banner, whose fix path is the same add act
|
||||
for (const slug of autoAdded) {
|
||||
console.log(`fresh deployment -- auto-added '${slug}', discovering`);
|
||||
void runProbe(slug)
|
||||
.then((s) => console.log(`auto-discovery of '${slug}': ${s.models.length} models scraped`))
|
||||
.catch((e) => console.error(`auto-discovery of '${slug}' failed: ${String(e.message ?? e).split('\n')[0]} -- the admin block's add act retries it`));
|
||||
}
|
||||
|
||||
// --- the per-run activity lock ---------------------------------------------------
|
||||
//
|
||||
// Serializes every async mutation span (turn, ask, start, the
|
||||
@@ -314,48 +361,293 @@ route('GET', '/api', async () => ({
|
||||
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
|
||||
}));
|
||||
|
||||
// --- models: the registry, and the op's discovery acts -------------------------
|
||||
// --- models and providers: the registry, the op's provider acts ----------------
|
||||
//
|
||||
// The registry (state/models.json) is the truth of selectable
|
||||
// models. Fresh deployments have none: model use is disabled until
|
||||
// the op discovers. Discover scrapes the provider surface -- API
|
||||
// metadata only, zero inference; refine runs the deterministic
|
||||
// battery and the curator pass (it sends real traffic and may cost
|
||||
// real money). Both are the superuser's.
|
||||
// The registry (state/models.json, per-provider sections) is the
|
||||
// truth of selectable models. The provider entities (state/
|
||||
// config.json) are the op's: add and remove from the SPA, discover
|
||||
// and refine per provider. Both surfaces below are the superuser's
|
||||
// except GET /api/models (the model box reads it, any signed-in
|
||||
// user).
|
||||
|
||||
/** The effective deployment default per role: the op's server.json
|
||||
* pick wins, else the registry's discovered default. */
|
||||
/** @returns {{ player?: ?string, housekeeper?: ?string }} */
|
||||
function effectiveDefaults() {
|
||||
/** The per-provider payload the model box and the admin block read. */
|
||||
/** @typedef {import('./shapes.mjs').JobState} JobState */
|
||||
/** @returns {{ providers: { slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('./shapes.mjs').RegistryModel[], job: ?JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }[] }} */
|
||||
function modelsPayload() {
|
||||
const reg = discovery.registry();
|
||||
return {
|
||||
player: ctx.cfg.models?.player ?? reg?.defaults.player ?? undefined,
|
||||
housekeeper: ctx.cfg.models?.housekeeper ?? reg?.defaults.housekeeper ?? undefined,
|
||||
providers: ctx.providerCfg.providers.map((p) => {
|
||||
const section = reg?.providers[p.slug] ?? null;
|
||||
return {
|
||||
slug: p.slug,
|
||||
phase: section?.phase ?? 'none',
|
||||
discovered: section?.discovered ?? null,
|
||||
refined: section?.refined ?? null,
|
||||
curator: section?.curator ?? null,
|
||||
recommendation: section?.recommendation ?? null,
|
||||
default: p.default ?? null,
|
||||
models: section?.models ?? [],
|
||||
job: discovery.jobState(ctx, p.slug),
|
||||
probe: p.probe ?? null,
|
||||
hasKey: !!p.apiKey,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
route('GET', '/api/models', async () => {
|
||||
const reg = discovery.registry();
|
||||
route('GET', '/api/models', async () => modelsPayload());
|
||||
|
||||
/** The providers' default specs: the create flow's pre-select, and
|
||||
* what a pick-less housekeeper inherits. */
|
||||
/** @returns {{ slug: string, default: ?{ model: string, effort: string } }[]} */
|
||||
function providerDefaults() {
|
||||
return ctx.providerCfg.providers.map((p) => ({ slug: p.slug, default: p.default ?? null }));
|
||||
}
|
||||
|
||||
/** The run's per-role spec health, read-only: the invalidation
|
||||
* surface the table renders as a note before any send refuses. An
|
||||
* unset housekeeper is not an error -- it inherits the player
|
||||
* spec's provider default (the same resolution the pass runs). */
|
||||
/** @param {string} runId @returns {{ player: RoleHealth, housekeeper: RoleHealth }} */
|
||||
function roleHealth(runId) {
|
||||
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
|
||||
/** @param {'player'|'housekeeper'} role @returns {RoleHealth} */
|
||||
const health = (role) => {
|
||||
const meta = bundle.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
try {
|
||||
const spec = specFromMeta(meta.models?.[role] ?? null, role);
|
||||
if (spec) {
|
||||
gateSpec(ctx, spec, role);
|
||||
return { spec, ok: true, note: null, inherited: false };
|
||||
}
|
||||
if (role === 'player') {
|
||||
return { spec: null, ok: false, note: 'no player model set for this run -- pick one in the model box', inherited: false };
|
||||
}
|
||||
// the housekeeper inherits: the player spec's provider's default
|
||||
const player = specFromMeta(meta.models?.player ?? null, 'player');
|
||||
const def = player ? ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null : null;
|
||||
if (def) {
|
||||
const inherited = { provider: /** @type {{ provider: string }} */ (player).provider, model: def.model, effort: def.effort };
|
||||
gateSpec(ctx, inherited, 'housekeeper');
|
||||
return { spec: inherited, ok: true, note: null, inherited: true };
|
||||
}
|
||||
return { spec: null, ok: false, note: 'no housekeeper pick, and no provider default to inherit', inherited: false };
|
||||
} catch (e) {
|
||||
return { spec: null, ok: false, note: String(/** @type {Error} */ (e).message ?? e), inherited: false };
|
||||
}
|
||||
};
|
||||
return { player: health('player'), housekeeper: health('housekeeper') };
|
||||
}
|
||||
|
||||
// the op's config detail: slugs, bases, key presence (the key itself
|
||||
// never leaves the server), defaults -- what the admin block edits
|
||||
route('GET', '/api/providers', async ({ user }) => {
|
||||
requireSuperuser(user);
|
||||
return {
|
||||
phase: reg?.phase ?? 'none',
|
||||
discovered: reg?.discovered ?? null,
|
||||
refined: reg?.refined ?? null,
|
||||
curator: reg?.curator ?? null,
|
||||
defaults: effectiveDefaults(),
|
||||
models: reg?.models ?? [],
|
||||
job: discovery.jobState(ctx),
|
||||
providers: ctx.providerCfg.providers.map((p) => ({
|
||||
slug: p.slug,
|
||||
baseUrl: p.baseUrl,
|
||||
hasKey: !!p.apiKey,
|
||||
default: p.default ?? null,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
route('POST', '/api/models/discover', async ({ user }) => {
|
||||
// the probe (GM, 2026-11-19): discovery IS the health check -- every
|
||||
// path that scrapes a provider records the outcome on the entity, so
|
||||
// the card reads the last probe, never a stored machine. 401/403 is
|
||||
// the ask (custom providers only -- an auth failure on o/f is
|
||||
// upstream breakage, shown as the error it is); everything else is
|
||||
// the error named. No runtime path probes: usage errors are transient
|
||||
// and the op's to fix eventually (a failed turn already landed its
|
||||
// req event, and the invalidation surface only answers removal).
|
||||
/** @param {string} slug @param {{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }} probe */
|
||||
function setProbe(slug, probe) {
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
const p = cfgMut.providers.find((x) => x.slug === slug);
|
||||
if (!p) return; // removed mid-probe -- the record goes with the entity
|
||||
p.probe = probe;
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
}
|
||||
/** @param {string} slug @returns {Promise<import('./discovery.mjs').RegistrySection>} */
|
||||
async function runProbe(slug) {
|
||||
try {
|
||||
const section = await discovery.discover(ctx, slug);
|
||||
setProbe(slug, { outcome: 'ok', detail: `${section.models.length} models scraped`, at: new Date().toISOString() });
|
||||
return section;
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
setProbe(slug, {
|
||||
outcome: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
||||
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
||||
at: new Date().toISOString(),
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// add a provider (GM, 2026-11-19): {builtin: true} or {slug,
|
||||
// baseUrl} -- never a key (the auth route is the only key path).
|
||||
// Discovery is the probe: an auth refusal (401/403) leaves the
|
||||
// provider standing broken -- the SPA asks for the key, checked on
|
||||
// reception; every other failure refuses the add outright, because an
|
||||
// endpoint that cannot answer is not a provider -- nothing stands.
|
||||
route('POST', '/api/providers', async ({ body, user }) => {
|
||||
requireSuperuser(user);
|
||||
const reg = await discovery.discover(ctx);
|
||||
return { ok: true, phase: reg.phase, models: reg.models.length };
|
||||
if (body.apiKey !== undefined && body.apiKey !== null) {
|
||||
throw new HttpError(400, 'apiKey does not ride the add -- send the endpoint alone; a 401/403 opens the key path');
|
||||
}
|
||||
const cfgMut = { providers: [...ctx.providerCfg.providers] };
|
||||
/** @type {import('./shapes.mjs').ProviderCfg} */ let p;
|
||||
if (body.builtin === true) {
|
||||
const added = providers.addBuiltin(cfgMut);
|
||||
if (!added) throw new HttpError(409, 'opencode/free is already on the provider list');
|
||||
p = added; // addBuiltin pushed it
|
||||
} else {
|
||||
const slug = String(body.slug ?? '').trim();
|
||||
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||
if (!providers.validSlug(slug)) throw new HttpError(400, 'slug must be lowercase letters, digits, dashes (one slash allowed), e.g. my-shop');
|
||||
if (providers.findProvider(cfgMut, slug)) throw new HttpError(409, `a provider named '${slug}' already exists`);
|
||||
if (!providers.validBaseUrl(baseUrl)) throw new HttpError(400, 'baseUrl must be a valid http(s) URL');
|
||||
p = { slug, baseUrl, default: null };
|
||||
cfgMut.providers.push(p);
|
||||
}
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
let section;
|
||||
try {
|
||||
section = await runProbe(p.slug);
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
// the add stands (the op keys it or removes it); the failure
|
||||
// carries its status for the SPA's password branch
|
||||
throw new HttpError(err.status, `provider '${p.slug}' added, but the listing was refused: ${err.message} -- send the API key`);
|
||||
}
|
||||
// every other failure refuses the add: roll back, nothing stands
|
||||
providers.applyConfig(ctx, { providers: ctx.providerCfg.providers.filter((x) => x.slug !== p.slug) });
|
||||
throw err;
|
||||
}
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
});
|
||||
|
||||
route('POST', '/api/models/refine', async ({ user }) => {
|
||||
// set or replace a custom provider's key (the o/f singleton never
|
||||
// takes one -- its purpose is to be the anonymous fallback; a 401
|
||||
// from it is upstream breakage, not a prompt). Probe-then-save (GM,
|
||||
// 2026-11-19): the candidate key is checked on reception -- a key
|
||||
// that still meets the refusal is never saved, the previous state
|
||||
// returns, and the ask stays open for the next attempt.
|
||||
route('POST', '/api/providers/:slug/auth', async ({ params, body, user }) => {
|
||||
requireSuperuser(user);
|
||||
return discovery.refine(ctx, user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
||||
if (typeof body.apiKey !== 'string' || !body.apiKey.trim()) throw new HttpError(400, 'apiKey (a non-empty string) is required');
|
||||
const prev = ctx.providerCfg;
|
||||
const prevEntity = /** @type {import('./shapes.mjs').ProviderCfg} */ (prev.providers.find((x) => x.slug === p.slug));
|
||||
const cfgMut = { providers: prev.providers.map((x) => ({ ...x })) };
|
||||
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
||||
target.apiKey = body.apiKey.trim();
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
try {
|
||||
const section = await runProbe(p.slug);
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
} catch (e) {
|
||||
// the failed candidate never saves: the previous state returns,
|
||||
// and this attempt's probe record rides back with it (the card
|
||||
// shows the last attempt, whatever it was)
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
const candidate = ctx.providerCfg.providers.find((x) => x.slug === p.slug);
|
||||
if (candidate?.probe) prevEntity.probe = candidate.probe;
|
||||
providers.applyConfig(ctx, prev);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// remove a custom provider's key (GM, 2026-11-19): the op's control
|
||||
// for a provider that went public -- or the first half of a key
|
||||
// replacement, the second half being the ask, which re-opens when
|
||||
// the keyless probe meets the 401 again. The removal stands whatever
|
||||
// the probe says: it is the op's deliberate act, not an add; the
|
||||
// probe outcome rides the response and the card.
|
||||
route('DELETE', '/api/providers/:slug/auth', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
if (p.slug === providers.OF_SLUG) throw new HttpError(403, 'opencode/free never takes an API key -- it is the anonymous fallback');
|
||||
if (!p.apiKey) throw new HttpError(404, `provider '${p.slug}' has no key to remove`);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
const target = /** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug));
|
||||
delete target.apiKey;
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
try {
|
||||
const section = await runProbe(p.slug);
|
||||
return { ok: true, provider: p.slug, models: section.models.length };
|
||||
} catch (e) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (e);
|
||||
return {
|
||||
ok: true,
|
||||
provider: p.slug,
|
||||
probe: err.status === 401 || err.status === 403 ? 'auth' : 'error',
|
||||
detail: String(err.message ?? e).split('\n')[0].slice(0, 200),
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// remove a provider: the section and the adjudication cache entries
|
||||
// go with it; the runs that rode it invalidate at their next send
|
||||
// (the GM's table carries the note)
|
||||
route('DELETE', '/api/providers/:slug', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const slug = params.slug;
|
||||
const guard = providers.removalGuard(ctx.providerCfg, slug);
|
||||
if (guard) throw new HttpError(409, guard);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.filter((p) => p.slug !== slug) };
|
||||
if (cfgMut.providers.length === ctx.providerCfg.providers.length) {
|
||||
throw new HttpError(404, `no such provider: ${slug}`);
|
||||
}
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
discovery.deleteSection(slug);
|
||||
discovery.purgeCache(slug);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// re-run one provider's discovery: the scrape, the section reset to
|
||||
// preliminary (a refined section loses its battery -- the button
|
||||
// says so in the UI), and the probe record updated -- this manual
|
||||
// act is one of the only things that moves it
|
||||
route('POST', '/api/providers/:slug/discover', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
const section = await runProbe(params.slug);
|
||||
return { ok: true, provider: params.slug, phase: section.phase, models: section.models.length };
|
||||
});
|
||||
|
||||
// the selection: the provider's default {model, effort} -- also the
|
||||
// refine curator. Validated against the provider's own registry.
|
||||
route('POST', '/api/providers/:slug/default', async ({ params, body, user }) => {
|
||||
requireSuperuser(user);
|
||||
const p = providers.findProvider(ctx.providerCfg, params.slug);
|
||||
if (!p) throw new HttpError(404, `no such provider: ${params.slug}`);
|
||||
const model = String(body.model ?? '').trim();
|
||||
const effort = String(body.effort ?? '').trim();
|
||||
if (!model) throw new HttpError(400, 'model (an id from this provider\'s registry) is required');
|
||||
if (!discovery.EFFORT_LEVELS.includes(effort)) {
|
||||
throw new HttpError(400, `effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
const m = discovery.findModel(p.slug, model);
|
||||
if (!m) throw new HttpError(400, `model '${model}' is not in '${p.slug}'s registry -- run its discovery first`);
|
||||
if (m.inference === false) throw new HttpError(400, `model '${model}' failed the inference battery -- it is not selectable`);
|
||||
const cfgMut = { providers: ctx.providerCfg.providers.map((x) => ({ ...x })) };
|
||||
/** @type {import('./shapes.mjs').ProviderCfg} */ (cfgMut.providers.find((x) => x.slug === p.slug)).default = { model, effort };
|
||||
providers.applyConfig(ctx, cfgMut);
|
||||
return { ok: true, provider: p.slug, default: { model, effort } };
|
||||
});
|
||||
|
||||
// refine one provider: the battery + the curator pass (the op's
|
||||
// selected default is the curator). Real traffic, real cost; the job
|
||||
// meters itself.
|
||||
route('POST', '/api/providers/:slug/refine', async ({ params, user }) => {
|
||||
requireSuperuser(user);
|
||||
return discovery.refine(ctx, params.slug, user);
|
||||
});
|
||||
|
||||
route('GET', '/api/packages', async () => {
|
||||
@@ -414,7 +706,8 @@ route('GET', '/api/runs', async () => {
|
||||
|
||||
// create: the pc's name is required (unique per package); the
|
||||
// package display name defaults to the package's own. The id is
|
||||
// anonymous, generated by the clerk.
|
||||
// anonymous, generated by the clerk. body.spec (the player pick, a
|
||||
// full {provider, model, effort}) lands in run.json after the copy.
|
||||
route('POST', '/api/runs', async ({ body, user }) => {
|
||||
const pkg = String(body.package ?? '').trim();
|
||||
const pc = String(body.pc ?? '').trim();
|
||||
@@ -422,9 +715,30 @@ route('POST', '/api/runs', async ({ body, user }) => {
|
||||
if (!pc) throw new HttpError(400, 'pc is required -- the main character\'s name, distinct per package');
|
||||
const name = body.name === undefined ? undefined : String(body.name);
|
||||
requireUser(user);
|
||||
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
|
||||
// the spec validates before anything lands: a refused create leaves
|
||||
// no orphan run dir behind (the failures-never-cache smoke found
|
||||
// the old order -- create first, validate after)
|
||||
if (body.spec !== undefined) {
|
||||
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body.spec);
|
||||
if (typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
||||
throw new HttpError(400, 'spec must be { provider, model, effort } -- see GET /api/models');
|
||||
}
|
||||
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
||||
throw new HttpError(400, `spec.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
if (!discovery.usable(spec.provider, spec.model)) {
|
||||
throw new HttpError(400, `spec model '${spec.model}' is not usable on '${spec.provider}' (not discovered, or failed the battery)`);
|
||||
}
|
||||
}
|
||||
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []));
|
||||
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
|
||||
const run = JSON.parse(r.out);
|
||||
if (body.spec !== undefined) {
|
||||
const spec = /** @type {{ provider: string, model: string, effort: string }} */ (body.spec);
|
||||
const meta = bundle.runMeta(run.id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
meta.models = { ...(meta.models ?? {}), player: { provider: spec.provider, model: spec.model, effort: spec.effort } };
|
||||
fs.writeFileSync(path.join(bundle.runDir(run.id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
}
|
||||
return { run, dir: `runs/${run.id}` };
|
||||
});
|
||||
|
||||
@@ -457,12 +771,12 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
||||
owner,
|
||||
ownerName: owner == null ? null : userName(owner),
|
||||
models: meta?.models ?? {},
|
||||
params: meta?.params ?? {},
|
||||
modelDefaults: effectiveDefaults(),
|
||||
// the deployment layer of the knobs (server.json params): the
|
||||
// only default an unset knob can honestly resolve to -- the
|
||||
// provider's own serving defaults are unknown and stay unstated
|
||||
paramDefaults: cfg.params ?? {},
|
||||
// the invalidation surface: each resolved spec's health, so the
|
||||
// table can carry the note before a send ever 409s
|
||||
modelState: roleHealth(id),
|
||||
// the providers' default specs -- the create flow's pre-select,
|
||||
// and the fallback a pick-less role would inherit
|
||||
providerDefaults: providerDefaults(),
|
||||
},
|
||||
display: bundle.runDisplay(id),
|
||||
open: !!s,
|
||||
@@ -599,80 +913,44 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
|
||||
return { ok: true, vars: settings.vars };
|
||||
});
|
||||
|
||||
// the run's models and sampling knobs: per-run overrides of the
|
||||
// deployment defaults (server.json, else the registry's discovered
|
||||
// pick), selected from the registry (GET /api/models). Owner-only,
|
||||
// changeable at any time -- every call resolves fresh, so a
|
||||
// mid-session switch simply takes the next turn. null clears a role
|
||||
// back to its deployment default; a null knob clears the knob (for
|
||||
// reasoning_effort, clearing means the registry's measured default
|
||||
// rides again).
|
||||
const KNOBS = ['temperature', 'top_p', 'top_k', 'repetition_penalty', 'max_tokens', 'reasoning_effort'];
|
||||
// the run's model picks: full specs, selected from the registry (GET
|
||||
// /api/models). Owner-only, changeable at any time -- every call
|
||||
// resolves fresh, so a mid-session switch simply takes the next
|
||||
// turn. null clears a role back to its inheritance (the player to
|
||||
// nothing, the housekeeper to the player provider's default).
|
||||
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, id);
|
||||
for (const k of Object.keys(body)) {
|
||||
if (k !== 'player' && k !== 'housekeeper' && k !== 'params') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper, params`);
|
||||
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown field: ${k} -- player, housekeeper`);
|
||||
}
|
||||
const meta = bundle.runMeta(id) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
|
||||
const reg = discovery.registry();
|
||||
const models = meta.models ?? {};
|
||||
const models = { ...(meta.models ?? {}) };
|
||||
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||
if (body[role] === undefined) continue;
|
||||
if (body[role] === null) { delete models[role]; continue; }
|
||||
const m = String(body[role]).trim();
|
||||
if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`);
|
||||
if (!discovery.usable(reg, m)) {
|
||||
throw new HttpError(400, `${role}: '${m}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
|
||||
const spec = /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (body[role]);
|
||||
if (typeof spec !== 'object' || spec === null || Array.isArray(spec)
|
||||
|| typeof spec.provider !== 'string' || typeof spec.model !== 'string' || typeof spec.effort !== 'string') {
|
||||
throw new HttpError(400, `${role}: a full spec { provider, model, effort }, or null to clear -- see GET /api/models`);
|
||||
}
|
||||
models[role] = m;
|
||||
if (!ctx.providerCfg.providers.some((p) => p.slug === spec.provider)) {
|
||||
throw new HttpError(400, `${role}: no provider named '${spec.provider}' is configured`);
|
||||
}
|
||||
if (!discovery.EFFORT_LEVELS.includes(spec.effort)) {
|
||||
throw new HttpError(400, `${role}.effort must be one of ${discovery.EFFORT_LEVELS.join(', ')}`);
|
||||
}
|
||||
if (!discovery.usable(spec.provider, spec.model)) {
|
||||
throw new HttpError(400, `${role}: '${spec.model}' is not usable on '${spec.provider}' (not in its registry, or failed the battery)`);
|
||||
}
|
||||
models[role] = { provider: spec.provider, model: spec.model, effort: spec.effort };
|
||||
}
|
||||
if (Object.keys(models).length) meta.models = models;
|
||||
else delete meta.models;
|
||||
|
||||
if (body.params !== undefined) {
|
||||
if (typeof body.params !== 'object' || body.params === null || Array.isArray(body.params)) {
|
||||
throw new HttpError(400, 'params (an object of player/housekeeper knob objects) is required');
|
||||
}
|
||||
for (const role of Object.keys(body.params)) {
|
||||
if (role !== 'player' && role !== 'housekeeper') throw new HttpError(400, `unknown params role: ${role}`);
|
||||
const knobs = body.params[role];
|
||||
if (typeof knobs !== 'object' || knobs === null || Array.isArray(knobs)) {
|
||||
throw new HttpError(400, `params.${role} must be an object of knobs`);
|
||||
}
|
||||
for (const [k, v] of Object.entries(knobs)) {
|
||||
if (!KNOBS.includes(k)) throw new HttpError(400, `unknown knob: ${k} -- ${KNOBS.join(', ')}`);
|
||||
if (k === 'reasoning_effort') {
|
||||
// the enum knob: one of the ladder's levels, or null to
|
||||
// clear back to the measured default
|
||||
if (v !== null && !discovery.EFFORT_LEVELS.includes(String(v))) {
|
||||
throw new HttpError(400, `params.${role}.reasoning_effort must be one of ${discovery.EFFORT_LEVELS.join(', ')} -- or null to ride the model's measured default`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (v !== null && !Number.isFinite(v)) throw new HttpError(400, `params.${role}.${k} must be a number, or null to clear`);
|
||||
}
|
||||
}
|
||||
const rp = meta.params ?? {};
|
||||
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||
const knobs = body.params[role];
|
||||
if (knobs === undefined) continue;
|
||||
const cur = { ...(rp[role] ?? {}) };
|
||||
for (const [k, v] of Object.entries(knobs)) {
|
||||
if (v === null) delete cur[/** @type {keyof import('./shapes.mjs').RoleParams} */ (k)];
|
||||
else if (k === 'reasoning_effort') cur[/** @type {'reasoning_effort'} */ (k)] = String(v);
|
||||
else cur[/** @type {'temperature'|'top_p'|'top_k'|'repetition_penalty'|'max_tokens'} */ (k)] = Number(v);
|
||||
}
|
||||
if (Object.keys(cur).length) rp[role] = cur;
|
||||
else delete rp[role];
|
||||
}
|
||||
if (Object.keys(rp).length) meta.params = rp;
|
||||
else delete meta.params;
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
return { ok: true, models: meta.models ?? {}, params: meta.params ?? {}, defaults: effectiveDefaults(), paramDefaults: cfg.params ?? {} };
|
||||
return { ok: true, models: meta.models ?? {}, modelState: roleHealth(id) };
|
||||
});
|
||||
|
||||
// the GM's notepad: the run's gm.md -- the owner's alone (#28's
|
||||
@@ -985,29 +1263,24 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
|
||||
|
||||
// the turn meter's read (GM, 2026-11-17): the live progress record
|
||||
// the streaming callback feeds, plus the scale the bar guesstimates
|
||||
// against -- the only true budget is max_tokens when the knobs set
|
||||
// one (reasoning counts inside it), else the session's own history:
|
||||
// her longest past turn in characters (thinking and prose both, the
|
||||
// units the meter counts). No history and no budget means no scale:
|
||||
// the client falls back to the chunk-driven animation. Owner-only
|
||||
// machinery; a plain read, never queued.
|
||||
// against -- the session's own history: her longest past turn in
|
||||
// characters (thinking and prose both, the units the meter counts).
|
||||
// No history means no scale: the client falls back to the
|
||||
// chunk-driven animation. (The old max_tokens budget layer is gone
|
||||
// with the per-run params: no surface sets one anymore -- GM,
|
||||
// 2026-11-18.) Owner-only machinery; a plain read, never queued.
|
||||
route('GET', '/api/runs/:id/progress', async ({ params, user }) => {
|
||||
requireOwner(user, params.id);
|
||||
const s = ctx.sessions.get(params.id);
|
||||
if (!s) return { inFlight: false, scale: null };
|
||||
// the max_tokens layer mirrors the loop's own resolution (the mind
|
||||
// rides over the run and deployment params); ~4 chars a token is
|
||||
// the meter's rough exchange rate -- a meter, not a ledger
|
||||
const eff = { ...resolveParams(ctx, params.id, 'player'), ...(s.mind ?? {}) };
|
||||
const budget = typeof eff.max_tokens === 'number' ? eff.max_tokens * 4 : null;
|
||||
let high = 0;
|
||||
for (const e of s.lines) {
|
||||
if (e.t !== 'msg' || e.m.role !== 'assistant') continue;
|
||||
const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length;
|
||||
if (chars > high) high = chars;
|
||||
}
|
||||
const scale = budget ?? (high > 0 ? high : null);
|
||||
const scaleKind = budget ? 'budget' : (high > 0 ? 'history' : null);
|
||||
const scale = high > 0 ? high : null;
|
||||
const scaleKind = high > 0 ? 'history' : null;
|
||||
if (!s.progress) return { inFlight: false, scale, scaleKind };
|
||||
return { inFlight: true, ...s.progress, scale, scaleKind };
|
||||
});
|
||||
@@ -1187,5 +1460,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
|
||||
const host = DEBUG ? '127.0.0.1' : cfgHost;
|
||||
server.listen(Number(port ?? 7350), host, () => {
|
||||
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : (effectiveDefaults().player ?? 'no default model')} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
|
||||
const providerCount = ctx.providerCfg.providers.length;
|
||||
const discovered = Object.keys(discovery.registry()?.providers ?? {}).length;
|
||||
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`);
|
||||
});
|
||||
|
||||
+43
-12
@@ -1,6 +1,7 @@
|
||||
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
|
||||
// endpoint per deployment (server.json "endpoint"); the model name
|
||||
// comes from the run (run.json override) or the config default.
|
||||
// server/provider.mjs -- the provider client. One client per
|
||||
// configured provider entity (state/config.json, written by the
|
||||
// server from the SPA); model specs name the provider slug, and
|
||||
// providerFor walks the map to the client that owns it.
|
||||
//
|
||||
// Every completion streams (SSE) and is assembled back into the one
|
||||
// response shape the callers consume -- no caller distinguishes
|
||||
@@ -20,13 +21,27 @@
|
||||
/** @typedef {(p: { phase: 'thinking'|'prose', chars: number }) => void} ProgressFn */
|
||||
|
||||
/**
|
||||
* @param {{ baseUrl?: string, apiKey?: string, apiKeyEnv?: string }} endpoint
|
||||
* @param {{ baseUrl?: string, apiKey?: string }} provider
|
||||
*/
|
||||
export function makeProvider(endpoint) {
|
||||
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
|
||||
if (!base) throw new Error('server.json: endpoint.baseUrl is required');
|
||||
const key = endpoint.apiKey ?? process.env[endpoint.apiKeyEnv ?? 'RP_API_KEY'] ?? '';
|
||||
const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` };
|
||||
export function makeProvider(provider) {
|
||||
const base = String(provider.baseUrl ?? '').replace(/\/+$/, '');
|
||||
if (!base) throw new Error('the provider entry has no baseUrl');
|
||||
const key = provider.apiKey ?? '';
|
||||
// the auth header rides only when a key exists: an EMPTY Bearer is
|
||||
// not the same as no auth (opencode.ai 401s the empty spelling and
|
||||
// serves the anonymous listing to the headerless request -- found
|
||||
// live in the fresh-path test, 2026-11-18)
|
||||
const headers = { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) };
|
||||
|
||||
/** An API failure carries its HTTP status on the error object --
|
||||
* the SPA branches on it (a 401/403 asks for the key), never on
|
||||
* message parsing.
|
||||
* @param {Response} res @returns {Promise<Error>} */
|
||||
const apiError = async (res) => {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`));
|
||||
err.status = res.status;
|
||||
return err;
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
@@ -48,7 +63,7 @@ export function makeProvider(endpoint) {
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
||||
throw await apiError(res);
|
||||
}
|
||||
// the SSE assembly: content and reasoning concatenate in order,
|
||||
// tool_calls stitch by index (id and name land on the first
|
||||
@@ -132,7 +147,7 @@ export function makeProvider(endpoint) {
|
||||
async models() {
|
||||
const res = await fetch(`${base}/models`, { headers });
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
||||
throw await apiError(res);
|
||||
}
|
||||
const data = /** @type {{ data: { id: string }[] }} */ (await res.json());
|
||||
return (data.data ?? []).map((m) => m.id).sort();
|
||||
@@ -145,10 +160,26 @@ export function makeProvider(endpoint) {
|
||||
async modelsMeta() {
|
||||
const res = await fetch(`${base}/models`, { headers });
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
||||
throw await apiError(res);
|
||||
}
|
||||
const data = /** @type {{ data: { id: string, max_input_tokens?: ?number, max_output_tokens?: ?number }[] }} */ (await res.json());
|
||||
return (data.data ?? []).map((m) => ({ id: m.id, input: m.max_input_tokens ?? null, output: m.max_output_tokens ?? null }));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// The routing: the client that owns a provider slug. Model specs
|
||||
// name the provider; the config holds the entity. A missing entry
|
||||
// means the config dropped a provider the run still rides -- loud,
|
||||
// never a silent fallback to some other provider (the model may not
|
||||
// exist there, and the auth certainly differs).
|
||||
/** @param {import('./shapes.mjs').Ctx} ctx @param {?string} slug @returns {ReturnType<typeof makeProvider>} */
|
||||
export function providerFor(ctx, slug) {
|
||||
const p = ctx.providers.get(String(slug ?? ''));
|
||||
if (!p) {
|
||||
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`the provider '${slug}' is not configured -- the run rides a route that is gone (re-add the provider, or re-pick the run's model)`));
|
||||
err.status = 409;
|
||||
throw err;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -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 (e.reminder) errors.push(`${at}: the reminder rides every GM turn on its own`);
|
||||
if (e.conflictOnly) errors.push(`${at}: conflict traffic is runtime machinery`);
|
||||
// the sheet's transport (GM, 2026-11-19, the box round): the
|
||||
// record is the only channel -- the tag is view machinery,
|
||||
// composed by renderView, never authored by anyone. Hers would
|
||||
// never apply (the scan holds the GM's record) and primes the
|
||||
// guarded emission; GM prose rides the view and story raw (the
|
||||
// GM-side strips do not know the tag)
|
||||
if (m.role === 'assistant' && e.sheet !== undefined) {
|
||||
errors.push(`${at}: the sheet is the GM's record -- it rides GM turns only`);
|
||||
}
|
||||
if (typeof m.content === 'string' && /<\/?sheet>/.test(m.content)) {
|
||||
errors.push(`${at}: the sheet tag is composed by the view, never authored -- the JSON rides the GM turn as its "sheet" record`);
|
||||
}
|
||||
} else if (e.t === 'opening') {
|
||||
openings++;
|
||||
if (!Array.isArray(e.status)) errors.push(`${at}: opening.status must be an array of descriptions`);
|
||||
@@ -470,6 +482,13 @@ export function lintCarryover(lines, { authored }) {
|
||||
errors.push(`${at}: malformed variants block -- ${e2.message}`);
|
||||
}
|
||||
}
|
||||
// both kinds: a GM turn's sheet record is the scan's source -- the
|
||||
// route checks object-ness live, the lint covers every hand path
|
||||
// (authored carryovers and dormancy edits both pass through here)
|
||||
if (e.t === 'msg' && e.m?.role === 'user' && e.sheet !== undefined
|
||||
&& (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
|
||||
errors.push(`${at}: the sheet record must be a JSON object`);
|
||||
}
|
||||
// both kinds: the boundary state note must be well-formed (stop
|
||||
// writes it; a hand edit must not corrupt it)
|
||||
if (e.t === 'note' && e.kind === 'state') {
|
||||
@@ -481,6 +500,9 @@ export function lintCarryover(lines, { authored }) {
|
||||
errors.push(`${at}: state.${k} must be an array of non-empty strings`);
|
||||
}
|
||||
}
|
||||
if (e.sheet !== undefined && (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
|
||||
errors.push(`${at}: state.sheet must be a JSON object`);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (authored && openings > 1) errors.push('at most one opening event');
|
||||
|
||||
+77
-36
@@ -30,17 +30,20 @@ export {};
|
||||
* everything else about a turn lives in its content. via is the
|
||||
* request record: the resolved model and the effective params (the
|
||||
* merged layer actually sent) -- model-facing surfaces never render
|
||||
* it, the raw surfaces always do. override is the GM's block edit,
|
||||
* arriving with a non-OOC GM turn: the log's record of it. The
|
||||
* composition overwrites her newest blocks with these values (the
|
||||
* scan reads it newest-wins); the log itself never changes. */
|
||||
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record<string, unknown> }} MsgEvent */
|
||||
* it, the raw surfaces always do. via.model is the bare model id;
|
||||
* via.provider names the route (absent in pre-spec logs). override
|
||||
* is the GM's block edit, arriving with a non-OOC GM turn: the log's
|
||||
* record of it. The composition overwrites her newest blocks with
|
||||
* these values (the scan reads it newest-wins); the log itself never
|
||||
* changes. */
|
||||
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, provider?: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record<string, unknown> }} MsgEvent */
|
||||
|
||||
/** req: a failed provider request -- the resolved model, the
|
||||
* effective params, and the failure. No message resulted (the turn
|
||||
* fails loud, the retry is the user's); this is the record of what
|
||||
* was attempted, surfaced on the raw surfaces like a note. */
|
||||
/** @typedef {{ t: 'req', model: string, params: RoleParams, fail: string }} ReqEvent */
|
||||
/** req: a failed provider request -- the resolved model (and its
|
||||
* provider route), the effective params, and the failure. No
|
||||
* message resulted (the turn fails loud, the retry is the user's);
|
||||
* this is the record of what was attempted, surfaced on the raw
|
||||
* surfaces like a note. */
|
||||
/** @typedef {{ t: 'req', model: string, provider?: string, params: RoleParams, fail: string }} ReqEvent */
|
||||
|
||||
/** tool: a tool result, paired to its call (pairing is a context
|
||||
* invariant, checked at render). */
|
||||
@@ -92,32 +95,56 @@ export {};
|
||||
/** The turn meter's live record: what the streaming callback knows. `phase` is what is arriving now; `started` is the provider call's epoch ms. */
|
||||
/** @typedef {{ phase: 'thinking'|'prose', thinking: number, prose: number, started: number }} TurnProgress */
|
||||
|
||||
/** run.json: lineage, ownership, per-run model overrides and knobs. */
|
||||
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string }, params?: { player?: ?RoleParams, housekeeper?: ?RoleParams } }} RunMeta */
|
||||
/** One model spec: the complete inference request identity (GM,
|
||||
* 2026-11-18) -- which provider routes it, the model id, and the
|
||||
* reasoning effort, all three required (there is no unset effort:
|
||||
* it substantially changes inference quality, so it is a property
|
||||
* of the model pick, never a free-floating knob). The fourth spec
|
||||
* member, sampling params, is optional and never stored: the <mind>
|
||||
* verb sets it for one specific turn. */
|
||||
/** @typedef {{ provider: string, model: string, effort: string }} ModelSpec */
|
||||
|
||||
/** The named sampling knobs, per role -- the well-known, widely
|
||||
* supported set, plus the reasoning-effort enum (GM, 2026-11-16:
|
||||
* first-class, hidden from the model -- not her call). Numbers ride
|
||||
* the wire verbatim; null clears; reasoning_effort is one of the
|
||||
* effort ladder's levels. */
|
||||
/** run.json: lineage, ownership, and the run's model picks -- full
|
||||
* specs, per role. (The retired per-run params layer is gone
|
||||
* entirely, GM, 2026-11-18: params are per-turn via <mind>, and the
|
||||
* no-legacy rule migrated the last carrier away.) */
|
||||
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?ModelSpec, housekeeper?: ?ModelSpec } }} RunMeta */
|
||||
|
||||
/** The named sampling knobs -- the <mind> verb's four (hers to set
|
||||
* for one turn), plus the wire-side extras the substrate itself
|
||||
* rides: reasoning_effort always comes from the model spec, never
|
||||
* the mind layer (hidden from the model, not her call). Numbers
|
||||
* ride the wire verbatim. */
|
||||
/** @typedef {{ temperature?: number, top_p?: number, top_k?: number, repetition_penalty?: number, max_tokens?: number, reasoning_effort?: string }} RoleParams */
|
||||
|
||||
/** One model of the discovered registry. Preliminary entries carry
|
||||
* the scrape only (status unrefined); refined entries carry the
|
||||
* battery's verdicts and the curator's presentation. think is the
|
||||
* battery's best measured thinking-token count -- the pick rule
|
||||
* ranks on it (the bucket is display). efforts is the
|
||||
* reasoning-effort probe: the measured mean thinking per level of
|
||||
* the ladder; effortDefault is the level with the highest observed
|
||||
* mean (GM, 2026-11-16: maximum thinking by default, overridable)
|
||||
* -- null when the model shows no thinking or no level moved it. */
|
||||
/** One model of a discovered provider's registry section. Preliminary
|
||||
* entries carry the scrape only (status unrefined); refined entries
|
||||
* carry the battery's verdicts and the curator's presentation. The
|
||||
* section key is the provider slug -- no routing tag needed, the
|
||||
* section names the route. think is the battery's best measured
|
||||
* thinking-token count. efforts is the reasoning-effort probe: the
|
||||
* measured mean thinking per level of the ladder; effortDefault is
|
||||
* the level with the highest observed mean -- pre-fill and hint
|
||||
* only (GM, 2026-11-18: with effort a property of the pick, nothing
|
||||
* rides implicitly anymore; it pre-selects the selection prompt's
|
||||
* dropdown and informs the curator's recommendation, no more). */
|
||||
/** @typedef {{ id: string, input: ?number, output: ?number, status?: 'unrefined', inference?: boolean, fail?: string, think?: ?number, reasoning?: 'off'|'low'|'standard'|'deep'|null, offSwitch?: Record<string, unknown>|null, efforts?: ?Record<string, number>, effortDefault?: ?string, latency?: ?number, family?: ?string, label?: ?string, description?: ?string, roles?: { player: boolean, housekeeper: boolean } }} RegistryModel */
|
||||
|
||||
/** state/models.json: the deployment's model registry -- the truth of
|
||||
* what is selectable. Written by discovery (the scrape) and refine
|
||||
* (the battery + the curator pass); read by the selectors, the model
|
||||
* routes, and the turn loop. */
|
||||
/** @typedef {{ phase: 'preliminary'|'refined', endpoint: ?string, discovered: string, refined: ?string, defaults: { player: ?string, housekeeper: ?string }, models: RegistryModel[], curator?: string }} ModelRegistry */
|
||||
/** One provider's registry section (state/models.json): written by
|
||||
* that provider's discovery and refine alone, deletable whole on
|
||||
* provider removal. recommendation is the curator's overall-best
|
||||
* {model, effort} -- intel only, shown post-refine, applied by the
|
||||
* op's click, never auto-landed and never deterministic on a bad
|
||||
* model day (GM, 2026-11-18: on a bad day the op gets no advice,
|
||||
* not machine advice). */
|
||||
/** @typedef {{ phase: 'preliminary'|'refined', discovered: string, refined: ?string, models: RegistryModel[], curator?: ?string, recommendation?: ?{ model: string, effort: string } }} RegistrySection */
|
||||
|
||||
/** state/models.json: the per-provider registry -- the truth of what
|
||||
* is selectable, one section per configured provider slug. A
|
||||
* provider absent from the config has no section (removal deletes
|
||||
* it); a provider not yet discovered has none either. The singular
|
||||
* and flat-vector era shapes migrate in memory on open. */
|
||||
/** @typedef {{ providers: Record<string, RegistrySection> }} ModelRegistry
|
||||
|
||||
/** settings.json: identity (pc/name are the @ sigils), declared vars,
|
||||
* the records flag. */
|
||||
@@ -158,10 +185,24 @@ export {};
|
||||
/** The provider client (provider.mjs's own return type). */
|
||||
/** @typedef {ReturnType<typeof import('./provider.mjs').makeProvider>} Provider */
|
||||
|
||||
/** server.json as parsed. params is per-role sampling knobs -- the
|
||||
* deployment-default layer the run's own params override. */
|
||||
/** @typedef {{ bind?: string, port?: number, endpoint?: { baseUrl?: string, apiKey?: string, apiKeyEnv?: string }, models: { player?: ?string, housekeeper?: ?string }, contwin?: number, contextWindow?: number, params?: { player?: RoleParams, housekeeper?: RoleParams } }} ServerCfg */
|
||||
/** One configured provider: a slug, a baseUrl, optional auth, and
|
||||
* the op's default model spec for it ({model, effort} -- params are
|
||||
* per-turn via <mind>, never in the provider default). The
|
||||
* opencode/free singleton is this shape with the slug and baseUrl
|
||||
* fixed and auth structurally absent. */
|
||||
/** @typedef {{ slug: string, baseUrl: string, apiKey?: string, default?: ?{ model: string, effort: string }, probe?: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string } }} ProviderCfg */
|
||||
|
||||
/** state/config.json: the deployment's provider entities -- server
|
||||
* written only (the SPA is the surface, zero hand edits). */
|
||||
/** @typedef {{ providers: ProviderCfg[] }} DeployCfg */
|
||||
|
||||
/** server.json as parsed -- the static, non-secret remainder of the
|
||||
* old config: bind and contwin. */
|
||||
/** @typedef {{ bind?: string, port?: number, contwin?: number }} ServerCfg */
|
||||
|
||||
/** The server context: the one object threaded through every module.
|
||||
* locks/enqueue are the per-run activity lock (main.mjs). */
|
||||
/** @typedef {{ mock: boolean, cfg: ServerCfg, provider: Provider, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */
|
||||
* locks/enqueue are the per-run activity lock (main.mjs). providers
|
||||
* is the provider clients keyed by slug (the config's truth,
|
||||
* rebuilt on every config mutation); providerCfg is the config
|
||||
* itself. */
|
||||
/** @typedef {{ mock: boolean, cfg: ServerCfg, providerCfg: DeployCfg, providers: Map<string, Provider>, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */
|
||||
|
||||
+13
-10
@@ -17,12 +17,14 @@
|
||||
// gm.md files are exempt -- GM-private, flagged to the GM, never
|
||||
// agent-edited.
|
||||
// 4. Retired terms stay retired (DICTIONARY rules the terms). The
|
||||
// living prose -- README, the root prompts, the packages --
|
||||
// never says: the wrap, prelude, paper (the old status), window
|
||||
// (the old session; a line naming contwin may gloss it as the
|
||||
// context window), turn-0, seed (memory.json is the name).
|
||||
// Historical records keep the vocabulary of
|
||||
// their day; gm.md is GM-private, flagged never fixed.
|
||||
// rule is about the substrate (GM, 2026-11-19): README and the
|
||||
// root prompts never say the wrap, prelude, paper (the old
|
||||
// status), window (the old session; a line naming contwin may
|
||||
// gloss it as the context window), turn-0, seed (memory.json is
|
||||
// the name). A banned word in a package's prose is fine -- the
|
||||
// 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):
|
||||
// every import is node: builtin or relative -- no runtime deps,
|
||||
// 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 ROOT_PROMPTS = new Set(['system.md', 'invariants.md', 'handbook.md', 'housekeeper.md', 'reminder.md']);
|
||||
const livingProse = (f) =>
|
||||
f === 'README.md' || ROOT_PROMPTS.has(f)
|
||||
|| (f.startsWith('packages/') && !f.endsWith('gm.md'));
|
||||
// rule 4's scope: the substrate's prose only (GM, 2026-11-19) --
|
||||
// README and the root prompts. The packages are the fiction; a
|
||||
// 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
|
||||
// their comments); it is exempt from the rules it defines
|
||||
const isSelf = (f) => f === 'test/check-repo.mjs';
|
||||
@@ -121,7 +124,7 @@ for (const f of files) {
|
||||
}
|
||||
|
||||
// rule 4: retired terms in living prose
|
||||
if (livingProse(f)) {
|
||||
if (substrateProse(f)) {
|
||||
text.split('\n').forEach((line, i) => {
|
||||
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)`);
|
||||
|
||||
+380
-86
@@ -1,12 +1,15 @@
|
||||
// test/smoke.mjs -- end-to-end multiuser pass against the --mock
|
||||
// server. Covers: bootstrap, claim, spent-invite rejection, second
|
||||
// user, the model registry (a fresh deployment has no models,
|
||||
// discover scrapes, refine runs the battery + the curator, registry-
|
||||
// gated picks, the pick rule's lex tie-break, the named sampling
|
||||
// knobs, the reasoning-effort knob (the battery's effort probe, the
|
||||
// max-mean default that sends, the override that rides the turn,
|
||||
// hidden from the model), the request record -- resolved model +
|
||||
// effective params on
|
||||
// user, the provider round (GM, 2026-11-18: the self-heal boot --
|
||||
// the empty provider list auto-added and discovered; the op acts
|
||||
// ride the per-provider surface -- the binary add choice, the o/f
|
||||
// singleton's authless guard, the selection {model, effort} that
|
||||
// names the refine curator, per-provider refine with the meter and
|
||||
// the receipt, the spec-keyed adjudication cache, the run spec
|
||||
// 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
|
||||
// its sampling for its next turn: one-shot, JSON, bounds enforced,
|
||||
// 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 { join, dirname } from 'node:path';
|
||||
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 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: {} });
|
||||
ok('invite mint is op-only', r.status === 403);
|
||||
|
||||
// 7b. the model registry: a fresh deployment has no models, discovery
|
||||
// is the op's two-step act, and model use is registry-gated
|
||||
r = await call('/models', { token: op });
|
||||
ok('fresh deployment: no registry', r.status === 200 && r.data.phase === 'none' && r.data.models.length === 0, JSON.stringify({ phase: r.data.phase }));
|
||||
r = await call('/models/discover', { method: 'POST', token: ash, body: {} });
|
||||
ok('discover is op-only', r.status === 403);
|
||||
r = await call('/models/refine', { method: 'POST', token: op, body: {} });
|
||||
ok('refine refuses before discovery', r.status === 409, r.data.error ?? '');
|
||||
r = await call('/models/discover', { method: 'POST', token: op, body: {} });
|
||||
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;
|
||||
// 7b. providers and the registry: the fresh deployment self-heals
|
||||
// (the empty provider list is auto-added and discovered at boot),
|
||||
// the op's acts ride the per-provider surface (selection, discover,
|
||||
// refine), the adjudication cache survives churn, and model use
|
||||
// stays registry-gated
|
||||
{
|
||||
r = await call('/models', { token: op });
|
||||
let boot = r.data.providers ?? [];
|
||||
for (let i = 0; i < 50 && boot.filter((p) => p.models.length > 0).length < 2; i++) {
|
||||
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
|
||||
// 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);
|
||||
const runId = r.data.run?.id;
|
||||
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));
|
||||
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)',
|
||||
!!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 });
|
||||
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);
|
||||
@@ -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'] } });
|
||||
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
|
||||
// registry-gated picks, and the named sampling knobs
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
|
||||
ok('set models', r.status === 200 && r.data.models.player === 'mock' && r.data.models.housekeeper === 'mock-cheap', JSON.stringify(r.data));
|
||||
ok('models stamped in run.json', meta(forkId).models?.player === 'mock' && meta(forkId).models?.housekeeper === 'mock-cheap');
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: 0.7, max_tokens: 4096 } } } });
|
||||
ok('set knobs', r.status === 200 && r.data.params.player?.temperature === 0.7 && r.data.params.player?.max_tokens === 4096, JSON.stringify(r.data));
|
||||
ok('knobs stamped in run.json', meta(forkId).params?.player?.temperature === 0.7);
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: null } } } });
|
||||
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: { 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' } } } });
|
||||
// 12b. models: the run's spec picks {provider, model, effort},
|
||||
// registry-gated, owner-only. The per-run params layer is gone (GM,
|
||||
// 2026-11-18): the <mind> verb is the only sampling source, per-turn
|
||||
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('set spec picks',
|
||||
r.status === 200 && JSON.stringify(r.data.models.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
|
||||
&& JSON.stringify(r.data.models.housekeeper) === '{"provider":"mock-a","model":"mock-tie","effort":"max"}',
|
||||
JSON.stringify(r.data));
|
||||
ok('the specs are stamped in run.json', JSON.stringify(meta(forkId).models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}');
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'mock-cheap', 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(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: null } } } });
|
||||
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));
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_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));
|
||||
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: { player: { provider: 'nope', model: 'x', effort: 'low' } } });
|
||||
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: { player: { provider: 'mock-b', model: 'not-a-model', effort: 'low' } } });
|
||||
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: { 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));
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: 'x' } });
|
||||
ok('clear a role (the housekeeper inherits the player provider\'s default)',
|
||||
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);
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
|
||||
ok('unknown role rejected', r.status === 400);
|
||||
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));
|
||||
// a turn on the knob-carrying run: the recording proves what was
|
||||
// sent -- the run's knob under the mind layer (her restated mind
|
||||
// rides over the run layer, the layering the tunables round built)
|
||||
ok('detail exposes the picks, their health, and the provider defaults',
|
||||
JSON.stringify(r.data.run.models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
|
||||
&& r.data.run.modelState?.player?.ok === true
|
||||
&& 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.*' } });
|
||||
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 });
|
||||
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',
|
||||
!!viaTurn?.via && viaTurn.via.model === 'mock' && viaTurn.via.params.max_tokens === 4096 && viaTurn.via.params.temperature === 1.2
|
||||
&& viaTurn.via.params.reasoning_effort === 'low',
|
||||
ok('the recorded request carries the spec under the mind layer',
|
||||
!!viaTurn?.via && viaTurn.via.model === 'mock-cheap' && viaTurn.via.provider === 'mock-b'
|
||||
&& viaTurn.via.params.temperature === 1.2 && viaTurn.via.params.reasoning_effort === 'low',
|
||||
JSON.stringify(viaTurn?.via ?? null));
|
||||
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 --
|
||||
// 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: {} });
|
||||
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? 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
|
||||
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');
|
||||
}
|
||||
|
||||
// 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
|
||||
// carries rewind replaces the target GM turn -- the target and
|
||||
// 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');
|
||||
}
|
||||
|
||||
// 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}`);
|
||||
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
|
||||
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 */
|
||||
|
||||
/** 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. */
|
||||
/** @typedef {{ id: number } & InsertOp} AppliedInsert */
|
||||
@@ -882,10 +882,10 @@ function anonId() {
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] @param {?string} [model] */
|
||||
function cmdCreate(pkgName, pc, displayName, model) {
|
||||
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] */
|
||||
function cmdCreate(pkgName, pc, displayName) {
|
||||
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);
|
||||
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;
|
||||
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
||||
/** @type {RunMeta} */ const meta = { package: pkgName, created: today() };
|
||||
if (model) meta.models = { player: model };
|
||||
if (ownerOverride) meta.owner = ownerOverride;
|
||||
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
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
|
||||
found++;
|
||||
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 created = null;
|
||||
/** @type {?number} */ let forked = null;
|
||||
@@ -1270,7 +1269,7 @@ if (RUN != null && PHASE_RULES[cmd ?? '']) enforcePhase(cmd ?? '');
|
||||
switch (cmd) {
|
||||
case 'packages': cmdPackages(); 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 'init': cmdInit(); break;
|
||||
case 'render': renderAll(openDb()); break;
|
||||
|
||||
+15
-13
@@ -43,22 +43,23 @@
|
||||
</div>
|
||||
<div id="invite-list"></div>
|
||||
<div id="user-list"></div>
|
||||
<div id="models-admin">
|
||||
<h3>models</h3>
|
||||
<div id="models-state" class="hint"></div>
|
||||
<div id="providers-admin">
|
||||
<h3>providers</h3>
|
||||
<div id="providers-banner" class="hint" hidden></div>
|
||||
<div id="provider-list"></div>
|
||||
<div class="form-actions">
|
||||
<button id="models-discover">discover</button>
|
||||
<button id="models-refine">refine</button>
|
||||
<button id="provider-add-of">add opencode/free</button>
|
||||
<button id="provider-add-custom">add custom provider</button>
|
||||
</div>
|
||||
<div id="refine-progress" hidden>
|
||||
<div id="refine-topline">
|
||||
<span id="refine-count"></span>
|
||||
<span id="refine-label" class="hint"></span>
|
||||
<form id="provider-form" hidden>
|
||||
<label class="field">slug <input id="provider-slug" autocomplete="off" placeholder="my-shop"></label>
|
||||
<label class="field">baseUrl <input id="provider-base" autocomplete="off" placeholder="https://api.example.com/v1"></label>
|
||||
<label class="field" id="provider-key-field" hidden>API key <input id="provider-key" type="password" autocomplete="off"></label>
|
||||
<div class="form-actions">
|
||||
<button type="button" id="provider-add-go">add and discover</button>
|
||||
<button type="button" id="provider-add-cancel">cancel</button>
|
||||
</div>
|
||||
<div id="refine-bar"><div id="refine-fill"></div></div>
|
||||
</div>
|
||||
<div id="refine-lines"></div>
|
||||
<div id="models-list"></div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
@@ -108,6 +109,7 @@
|
||||
<pre id="edit-hl" aria-hidden="true"></pre>
|
||||
<textarea id="setup-edit" spellcheck="false"></textarea>
|
||||
</div>
|
||||
<div id="edit-hint" hidden></div>
|
||||
<div id="setup-edit-bar">
|
||||
<button id="setup-save">save</button>
|
||||
<span id="setup-edit-state"></span>
|
||||
|
||||
+28
-195
@@ -1,144 +1,37 @@
|
||||
// web/knobs.mjs -- the sampling knobs: the definitions table and the
|
||||
// per-role knob row.
|
||||
// web/knobs.mjs -- the reasoning-effort ladder and its select.
|
||||
//
|
||||
// The knobs are named, well-known, widely supported. The definitions
|
||||
// table is the single home of every knob text -- label, hint, bounds
|
||||
// -- red-pen the prose here, in place. Bounds are display knowledge
|
||||
// probed from this endpoint's own validation errors (the /model
|
||||
// route's validation stays generic: a finite number, or one of the
|
||||
// effort ladder's levels). The provider's serving defaults are
|
||||
// unknown and stay unstated; the only default anyone can honestly
|
||||
// name is the deployment layer (server.json params), which rides the
|
||||
// run detail as paramDefaults -- reasoning_effort is the one
|
||||
// exception: the registry measured a per-model default (the maximum
|
||||
// observed mean thinking), so its unset state honestly sends.
|
||||
// The per-run sampling knobs are retired (GM, 2026-11-18): params are
|
||||
// per-turn and only hers -- the <mind> verb sets them for one turn,
|
||||
// nothing stores them. Reasoning effort is a property of the model
|
||||
// pick (there is no unset effort), so its select lives inside the
|
||||
// model picks (widgets.mjs's modelsBox) and the provider selection
|
||||
// (view-home's admin block), not a knob row. The ladder mirrors
|
||||
// server/discovery.mjs's EFFORT_LEVELS (the web cannot import server
|
||||
// runtime code); keep them in step.
|
||||
//
|
||||
// Two defaults, never conflated: a knob unset means its value is NOT
|
||||
// sent to the provider; a value present is sent, and the row marks it
|
||||
// when it equals the deployment default. The explicit override toggle
|
||||
// carries the distinction: off (the visible default) disables the
|
||||
// input and saving sends nothing for the knob (null clears a
|
||||
// previously-set value); on demands a number (a level, for the enum).
|
||||
//
|
||||
// The hint bar is shared by both roles -- one explanation at a time,
|
||||
// driven by focus (a tap focuses), cleared when focus leaves the
|
||||
// knobs entirely.
|
||||
|
||||
/** @typedef {import('../server/shapes.mjs').RoleParams} RoleParams */
|
||||
// The old knobs' teaching surface -- what temperature means, what
|
||||
// top_p does -- was prompt-side all along: invariants.md documents
|
||||
// the mind verb, and the model answers with native JSON. The GM-side
|
||||
// texts died with the rows; the four bounds live on in the server's
|
||||
// mind-verb validator (server/loop.mjs, KNOB_BOUNDS).
|
||||
|
||||
import { el } from './dom.mjs';
|
||||
|
||||
// the reasoning-effort ladder -- mirrors server/discovery.mjs's
|
||||
// EFFORT_LEVELS (the web cannot import server runtime code); keep
|
||||
// them in step
|
||||
const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||
// EFFORT_LEVELS; keep them in step
|
||||
export const EFFORT_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||
|
||||
/** One knob's definition: the texts are the product. Two kinds ship:
|
||||
* numbers, and the effort enum (a select over the ladder). All six
|
||||
* knobs are the GM's here; the mind verb (server/loop.mjs) sets
|
||||
* only the four that are hers -- max_tokens is excluded by ruling
|
||||
* (a budget, not a mind), reasoning_effort is hidden from her
|
||||
* entirely (not her call). */
|
||||
/** @typedef {{ key: keyof RoleParams, kind: 'number', label: string, hint: string, bounds: string }} NumberDef */
|
||||
/** @typedef {{ key: keyof RoleParams, kind: 'enum', label: string, hint: string }} EnumDef */
|
||||
/** @typedef {NumberDef|EnumDef} KnobDef */
|
||||
|
||||
/** @type {KnobDef[]} */
|
||||
const DEFS = [
|
||||
{
|
||||
key: 'temperature',
|
||||
kind: 'number',
|
||||
label: 'temperature',
|
||||
hint: 'How adventurous the word choice is. Higher: more varied and surprising, occasionally unhinged. Lower: more predictable and conservative; at 0 the same prompt tends to get the same words.',
|
||||
bounds: 'This endpoint: 0 to 2.',
|
||||
},
|
||||
{
|
||||
key: 'top_p',
|
||||
kind: 'number',
|
||||
label: 'top_p',
|
||||
hint: 'Narrows the field to the most likely words that together cover this much probability. Higher: more words in play, more variety. Lower: fewer, safer choices; very low makes her repeat herself.',
|
||||
bounds: 'This endpoint: above 0 (0 is refused), up to 1.',
|
||||
},
|
||||
{
|
||||
key: 'top_k',
|
||||
kind: 'number',
|
||||
label: 'top_k',
|
||||
hint: 'Like top_p but by count -- only the k most likely words are considered each step. Higher: more variety. Lower: more locked-in; at 1 she picks the single most likely word every time. -1 and 0 turn the filter off.',
|
||||
bounds: 'No known bounds on this endpoint; -1 and 0 both mean the filter is off.',
|
||||
},
|
||||
{
|
||||
key: 'repetition_penalty',
|
||||
kind: 'number',
|
||||
label: 'repetition_penalty',
|
||||
hint: 'A direct nudge against repeating recent words and phrasings. 1 is no effect; raise it to make her evade repetition. Too high and she substitutes odd words to escape.',
|
||||
bounds: 'Must be above 0 on this endpoint, no known max.',
|
||||
},
|
||||
{
|
||||
key: 'max_tokens',
|
||||
kind: 'number',
|
||||
label: 'max_tokens',
|
||||
hint: 'The response\'s hard length budget. Higher: room for long turns. Lower: cheaper and shorter, but the turn can cut off mid-sentence -- and on reasoning models thinking counts against this budget first, so a low cap can be eaten entirely before she writes a word.',
|
||||
bounds: '1 or more on this endpoint; no enforced max (values above the model\'s output ceiling are accepted).',
|
||||
},
|
||||
{
|
||||
key: 'reasoning_effort',
|
||||
kind: 'enum',
|
||||
label: 'reasoning effort',
|
||||
hint: 'How hard the model thinks before answering. Higher levels reason more thoroughly and cost more (thinking bills as output tokens); lower levels answer faster. The level is a request, not a guarantee -- the model adapts to the task. Not hers to set: the mind verb never carries it.',
|
||||
},
|
||||
];
|
||||
|
||||
/** The hint bar's text for one knob: label, the explanation, the
|
||||
* bounds, and the honest default statement for this role's
|
||||
* deployment layer. Never invents an unknown value. The enum knob
|
||||
* states its own honest default: the measured pick. */
|
||||
/** @param {KnobDef} def @param {number|string|undefined|null} dep @param {?{ measured: Record<string, number>, fallback: ?string }} [effort] @returns {string} */
|
||||
function hintText(def, dep, effort) {
|
||||
if (def.kind === 'enum') {
|
||||
const table = effort
|
||||
? `Measured mean thinking for this model: ${Object.entries(effort.measured).map(([k, v]) => `${k} ${v}`).join(', ')}.`
|
||||
: 'No effort measurements for this model (an unrefined registry, or the model shows no thinking).';
|
||||
const rides = (dep !== undefined && dep !== null ? String(dep) : null) ?? effort?.fallback ?? null;
|
||||
const defLine = rides
|
||||
? `Unset = ${rides} rides (the measured default: the level with the highest observed thinking).`
|
||||
: 'Unset = not sent; the model id\'s own baked default applies.';
|
||||
return `${def.label} -- ${def.hint} ${table} ${defLine}`;
|
||||
}
|
||||
const d = /** @type {NumberDef} */ (def);
|
||||
const defLine = dep !== undefined && dep !== null
|
||||
? `Unset = the deployment default (${dep}).`
|
||||
: 'Unset = not sent; the provider\'s own default applies (unknown).';
|
||||
return `${d.label.replace(/_/g, ' ')} -- ${d.hint} ${d.bounds} ${defLine}`;
|
||||
}
|
||||
|
||||
/** One role's knob row.
|
||||
* @param {string} role
|
||||
* @param {RoleParams|undefined} current the run's own knobs
|
||||
* @param {RoleParams|undefined|null} deployment the deployment layer (server.json params)
|
||||
* @param {HTMLElement} hintBar the shared hint bar
|
||||
* @param {?{ measured: Record<string, number>, fallback: ?string }} [effort] the current model's measured effort ladder (null: none)
|
||||
* @returns {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }}
|
||||
/** A select over the ladder. The '' option's label names what an
|
||||
* absent choice means at the call site (the measured default in the
|
||||
* model box, "pick a level" in the selection prompt) -- the caller
|
||||
* owns the sentence, this builds the options.
|
||||
* @param {?string} current the pre-selected level ('' when none)
|
||||
* @param {string} unsetLabel the '' option's label
|
||||
* @returns {HTMLSelectElement}
|
||||
*/
|
||||
export function knobsBox(role, current, deployment, hintBar, effort = null) {
|
||||
const wrap = el('div', 'knobs');
|
||||
wrap.appendChild(el('div', 'knobs-head', `${role} knobs`));
|
||||
/** @type {Record<string, { tog: HTMLInputElement, inp: HTMLInputElement, sel: ?HTMLSelectElement }>} */
|
||||
const rows = {};
|
||||
for (const def of DEFS) {
|
||||
const row = el('div', 'knob');
|
||||
const tog = /** @type {HTMLInputElement} */ (el('input'));
|
||||
tog.type = 'checkbox';
|
||||
tog.title = 'override';
|
||||
const lab = el('label', null, `${def.label.replace(/_/g, ' ')} `);
|
||||
const mark = el('span', 'knob-default', ' \u00b7 deployment default');
|
||||
/** @type {?HTMLSelectElement} */ let sel = null;
|
||||
const inp = /** @type {HTMLInputElement} */ (el('input'));
|
||||
if (def.kind === 'enum') {
|
||||
// the effort row: a select over the ladder; unset sends the
|
||||
// measured default (the registry's pick for the current model)
|
||||
sel = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const rides = deployment?.[def.key] ?? effort?.fallback ?? null;
|
||||
const unset = /** @type {HTMLOptionElement} */ (el('option', null, rides ? `(default: ${rides})` : '(not sent)'));
|
||||
export function effortSelect(current, unsetLabel) {
|
||||
const sel = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const unset = /** @type {HTMLOptionElement} */ (el('option', null, unsetLabel));
|
||||
unset.value = '';
|
||||
sel.appendChild(unset);
|
||||
for (const lv of EFFORT_LEVELS) {
|
||||
@@ -146,66 +39,6 @@ export function knobsBox(role, current, deployment, hintBar, effort = null) {
|
||||
o.value = lv;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
lab.appendChild(sel);
|
||||
} else {
|
||||
inp.type = 'number';
|
||||
inp.step = 'any';
|
||||
lab.appendChild(inp);
|
||||
}
|
||||
lab.appendChild(mark);
|
||||
row.appendChild(tog);
|
||||
row.appendChild(lab);
|
||||
wrap.appendChild(row);
|
||||
|
||||
const set = current?.[def.key];
|
||||
tog.checked = set !== undefined;
|
||||
const dep = deployment?.[def.key];
|
||||
// the toggle owns the state: off disables the input (the value
|
||||
// stays for a change of mind), on demands a number (a level);
|
||||
// a value equal to the deployment default is still sent, and
|
||||
// the row marks it
|
||||
const sync = () => {
|
||||
const field = /** @type {HTMLInputElement|HTMLSelectElement} */ (sel ?? inp);
|
||||
field.disabled = !tog.checked;
|
||||
const v = sel ? sel.value : inp.value.trim();
|
||||
mark.hidden = !(tog.checked && v !== '' && v === String(dep ?? '\u0000'));
|
||||
};
|
||||
tog.addEventListener('change', sync);
|
||||
if (sel) sel.addEventListener('change', sync);
|
||||
else inp.addEventListener('input', sync);
|
||||
sync();
|
||||
const focusEl = /** @type {HTMLElement} */ (sel ?? inp);
|
||||
focusEl.addEventListener('focus', () => { hintBar.textContent = hintText(def, dep, effort); });
|
||||
if (sel && set !== undefined) sel.value = String(set);
|
||||
else if (!sel && set !== undefined) inp.value = String(set);
|
||||
rows[def.key] = { tog, inp, sel };
|
||||
}
|
||||
// the bar keeps its text while focus moves inside the row, clears
|
||||
// when it leaves the knobs entirely
|
||||
wrap.addEventListener('focusout', (e) => {
|
||||
if (!wrap.contains(/** @type {?Node} */ (e.relatedTarget))) hintBar.textContent = '';
|
||||
});
|
||||
const read = () => {
|
||||
/** @type {Record<string, number|string|null>} */ const out = {};
|
||||
for (const def of DEFS) {
|
||||
const { tog, inp, sel } = rows[def.key];
|
||||
if (tog.checked) {
|
||||
if (sel) {
|
||||
const v = sel.value;
|
||||
if (!v) throw new Error(`${def.label}: a level is required -- or switch the override off`);
|
||||
out[def.key] = v;
|
||||
} else {
|
||||
const v = inp.value.trim();
|
||||
if (v === '' || !Number.isFinite(Number(v))) {
|
||||
throw new Error(`${def.label}: a number is required -- or switch the override off`);
|
||||
}
|
||||
out[def.key] = Number(v);
|
||||
}
|
||||
} else if (current?.[def.key] !== undefined) {
|
||||
out[def.key] = null; // clearing a previously-set knob
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
return { wrap, read };
|
||||
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
|
||||
return sel;
|
||||
}
|
||||
|
||||
+22
-10
@@ -10,19 +10,31 @@ export {};
|
||||
|
||||
/** One run card as GET /runs serves it (the clerk's listing,
|
||||
* enriched by the server with the live-session state). fill is
|
||||
* present exactly when the run is initialized. */
|
||||
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
|
||||
* present exactly when the run is initialized. models is run.json
|
||||
* verbatim: the spec picks. */
|
||||
/** @typedef {{ id: string, package: string, models: ?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
|
||||
|
||||
/** One role's spec health: the resolved spec (null when unset or
|
||||
* unresolvable), whether it is playable, and the note when it is
|
||||
* not -- the invalidation surface the table and the model box
|
||||
* render. An unset housekeeper that inherits is ok with
|
||||
* inherited: true. */
|
||||
/** @typedef {{ spec: ?{ provider: string, model: string, effort: string }, ok: boolean, note: ?string, inherited: boolean }} RoleHealth */
|
||||
|
||||
/** GET /runs/:id -- the run detail: identity, the phase bookkeeping,
|
||||
* her two blocks, the fill, the context meter's numbers.
|
||||
* paramDefaults is the knobs' deployment layer (server.json params)
|
||||
* -- the only default an unset knob honestly resolves to. */
|
||||
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, params: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, modelDefaults: { player?: ?string, housekeeper?: ?string }, paramDefaults: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
|
||||
* her two blocks, the fill, the context meter's numbers. models is
|
||||
* run.json verbatim (the spec picks); modelState is the resolved
|
||||
* truth. */
|
||||
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, modelState: { player: RoleHealth, housekeeper: RoleHealth }, providerDefaults: { slug: string, default: ?{ model: string, effort: string } }[] }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
|
||||
|
||||
/** GET /api/models -- the deployment's model registry and the
|
||||
* discovery job state riding along. phase 'none' is the fresh
|
||||
* deployment: nothing is selectable until the op discovers. */
|
||||
/** @typedef {{ phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, defaults: { player?: ?string, housekeeper?: ?string }, models: import('../server/shapes.mjs').RegistryModel[], job: ?import('../server/shapes.mjs').JobState }} ModelsRegistryResponse */
|
||||
/** One provider's /api/models payload: its registry section (phase
|
||||
* 'none' when never discovered), the op's default spec, the
|
||||
* curator's recommendation, and the refine job state. */
|
||||
/** @typedef {{ slug: string, phase: 'none'|'preliminary'|'refined', discovered: ?string, refined: ?string, curator: ?string, recommendation: ?{ model: string, effort: string }, default: ?{ model: string, effort: string }, models: import('../server/shapes.mjs').RegistryModel[], job: ?import('../server/shapes.mjs').JobState, probe: ?{ outcome: 'ok' | 'auth' | 'error', detail: string, at: string }, hasKey: boolean }} ProviderPayload */
|
||||
|
||||
/** GET /api/models -- the per-provider registry: one payload per
|
||||
* configured provider, the truth of what is selectable. */
|
||||
/** @typedef {{ providers: ProviderPayload[] }} ModelsRegistryResponse */
|
||||
|
||||
/** GET /runs/:id/table -- the live session's projection (thinking
|
||||
* never crosses the wire, variant turns carry only the picked one). */
|
||||
|
||||
+9
-7
@@ -66,13 +66,14 @@ body.play #context-meter { visibility: visible; }
|
||||
#context-fill { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; }
|
||||
#context-fill.hot { background: var(--danger); }
|
||||
|
||||
#refine-progress { margin: 10px 0 2px; }
|
||||
#refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
|
||||
#refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
|
||||
#refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
|
||||
#refine-fill { height: 100%; width: 0; background: var(--ok); }
|
||||
#refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; }
|
||||
.provider-card { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 8px; }
|
||||
.refine-progress { margin: 10px 0 2px; }
|
||||
.refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; }
|
||||
.refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; }
|
||||
.refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
|
||||
.refine-fill { height: 100%; width: 0; background: var(--ok); }
|
||||
.refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; }
|
||||
.refine-line { font-family: monospace; white-space: pre-wrap; }
|
||||
|
||||
.turn-live { margin: 10px 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; }
|
||||
@@ -272,6 +273,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
|
||||
.tok-var { color: var(--ok); }
|
||||
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
#setup-edit-state { color: var(--dim); font-size: 12px; }
|
||||
#edit-hint { color: var(--dim); font-size: 12px; margin-top: 8px; }
|
||||
|
||||
/* --- transcript (play) --- */
|
||||
|
||||
|
||||
+7
-6
@@ -148,15 +148,16 @@ function renderContent(target, text, { extract }) {
|
||||
return { status, conflict, agenda };
|
||||
}
|
||||
|
||||
// the request record's line: the resolved model and the effective
|
||||
// params as sent (the merged layer actually sent). Shared by the raw
|
||||
// walk and the per-turn raw control. fail is present when the call
|
||||
// failed -- no message resulted.
|
||||
/** @param {{ model: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
|
||||
// the request record's line: the resolved spec (provider and model)
|
||||
// and the effective params as sent. Shared by the raw walk and the
|
||||
// per-turn raw control. fail is present when the call failed -- no
|
||||
// message resulted.
|
||||
/** @param {{ model: string, provider?: string, params?: Record<string, number|string> }} via @param {?string} [fail] @returns {string} */
|
||||
export function viaLine(via, fail = null) {
|
||||
const ks = Object.entries(via.params ?? {});
|
||||
const p = ks.length ? ` -- ${ks.map(([k, v]) => `${k}: ${v}`).join(', ')}` : ' (no knobs set)';
|
||||
return fail ? `[request failed] ${via.model}${p} -- ${fail}` : `[request] ${via.model}${p}`;
|
||||
const who = via.provider ? `${via.provider}/${via.model}` : via.model;
|
||||
return fail ? `[request failed] ${who}${p} -- ${fail}` : `[request] ${who}${p}`;
|
||||
}
|
||||
|
||||
// the GM's block edit, as the machinery line both walks show: the
|
||||
|
||||
+269
-65
@@ -6,7 +6,8 @@ import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { navigate, render } from './router.mjs';
|
||||
import { armedButton, fmtCeiling } from './widgets.mjs';
|
||||
import { armedButton, fmtCeiling, dropModelCache } from './widgets.mjs';
|
||||
import { EFFORT_LEVELS } from './knobs.mjs';
|
||||
|
||||
/** @typedef {import('./shapes.mjs').RunCard} RunCard */
|
||||
|
||||
@@ -25,7 +26,7 @@ export async function enter(arg, seq) {
|
||||
// the name carries the content facts plus the ownership garnish;
|
||||
// started-or-forked rides the meta -- chrome, never model-facing
|
||||
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
|
||||
card.appendChild(el('span', 'card-meta', `${r.package} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${r.models?.player ? ` \u00b7 ${r.models.player}` : ''}`));
|
||||
card.appendChild(el('span', 'card-meta', `${r.package} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${specTag(r.models?.player)}`));
|
||||
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
|
||||
// your own draft opens the editor; anyone else's run opens at
|
||||
// the story -- the table is the owner's
|
||||
@@ -39,6 +40,9 @@ export async function enter(arg, seq) {
|
||||
const ownershipTag = (r, mine) =>
|
||||
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
|
||||
|
||||
// the card's model garnish: a spec renders as provider/model
|
||||
/** @param {{ provider?: string, model?: string }|null|undefined} pick @returns {string} */
|
||||
const specTag = (pick) => (pick && pick.provider ? ` \u00b7 ${pick.provider}/${pick.model ?? '?'}` : '');
|
||||
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
|
||||
/** @param {number} t @returns {string} */
|
||||
function fmtUnix(t) {
|
||||
@@ -107,57 +111,211 @@ async function renderAdmin(seq) {
|
||||
}
|
||||
userList.appendChild(row);
|
||||
}
|
||||
renderModelsAdmin(reg, seq);
|
||||
renderProvidersAdmin(reg, seq);
|
||||
}
|
||||
|
||||
// --- models: the discovery surface --------------------------------------------
|
||||
// --- providers: the op's surface ---------------------------------------------
|
||||
//
|
||||
// Two op acts: discover (the metadata scrape, free) and refine (the
|
||||
// inference battery + the curator pass -- real traffic, may cost
|
||||
// real money, two-click armed with the warning). The registry state
|
||||
// line and the model list render from the saved registry.
|
||||
// The provider cards: the state line, the selection (the default
|
||||
// {model, effort} pair -- also the refine curator), discover and
|
||||
// refine (both armed: discover resets a refined section to the
|
||||
// scrape, refine sends real traffic over every model on the
|
||||
// provider), remove (the o/f singleton holds while it is all that
|
||||
// stands), the refine meter with its surviving receipt, the model
|
||||
// list, and the curator's recommendation beside the selection --
|
||||
// intel, one click to apply. The add flow is the binary choice:
|
||||
// opencode/free (disabled when present) or a custom provider.
|
||||
|
||||
/** @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {number} seq */
|
||||
function renderModelsAdmin(reg, seq) {
|
||||
const stateLine = $('models-state');
|
||||
const running = reg.job?.state === 'running';
|
||||
if (reg.phase === 'none') {
|
||||
stateLine.textContent = 'no models discovered -- model use is disabled until you discover';
|
||||
} else if (reg.phase === 'preliminary') {
|
||||
stateLine.textContent = `preliminary registry -- ${reg.models.length} scraped, unrefined (discovered ${fmtStamp(reg.discovered)})`;
|
||||
} else {
|
||||
stateLine.textContent = `refined registry -- ${reg.models.filter((m) => m.inference !== false).length}/${reg.models.length} usable \u00b7 defaults ${reg.defaults.player ?? 'none'} / ${reg.defaults.housekeeper ?? 'none'}${reg.curator && reg.curator !== 'curated' ? ` \u00b7 ${reg.curator}` : ''} (refined ${fmtStamp(reg.refined)})`;
|
||||
/** @param {import('./shapes.mjs').ProviderPayload} p @returns {string} */
|
||||
function providerStateLine(p) {
|
||||
if (p.phase === 'none') {
|
||||
// the probe record is the card's truth (GM, 2026-11-19): an auth
|
||||
// refusal opens the key path (never on o/f -- its auth failure is
|
||||
// upstream breakage, not a prompt); any other failure names
|
||||
// itself; no probe yet is a provider that was never scraped
|
||||
if (p.probe?.outcome === 'auth') {
|
||||
return p.slug === 'opencode/free'
|
||||
? 'upstream auth failure -- nothing to fix on this side, wait'
|
||||
: 'discovery refused -- it wants an API key';
|
||||
}
|
||||
if (running) stateLine.textContent = `refining -- ${reg.job?.phase ?? ''} started ${fmtStamp(reg.job?.started ?? null)}; this page follows the job`;
|
||||
/** @type {HTMLButtonElement} */ ($('models-discover')).disabled = running;
|
||||
/** @type {HTMLButtonElement} */ ($('models-refine')).disabled = running || reg.phase === 'none';
|
||||
if (p.probe?.outcome === 'error') return `discovery failed -- ${p.probe.detail}`;
|
||||
return 'not discovered yet';
|
||||
}
|
||||
if (p.phase === 'preliminary') return `${p.models.length} scraped, unrefined (discovered ${fmtStamp(p.discovered)})`;
|
||||
const usable = p.models.filter((m) => m.inference !== false).length;
|
||||
const def = p.default ? ` \u00b7 default ${p.default.model} at ${p.default.effort}` : ' \u00b7 no default selected';
|
||||
return `refined -- ${usable}/${p.models.length} usable${def}${p.curator && p.curator !== 'curated' ? ` \u00b7 ${p.curator}` : ''} (refined ${fmtStamp(p.refined)})`;
|
||||
}
|
||||
|
||||
// the refine meter: the bar moves only on real step completions
|
||||
// (no speed to interpolate -- a stuck bar means a stuck step), the
|
||||
// label names the call running now, and the lines are the receipt
|
||||
// -- they survive the job, so a landed pass keeps its verdicts and
|
||||
// a rejected one keeps its post-mortem
|
||||
const meter = $('refine-progress');
|
||||
const linesBox = $('refine-lines');
|
||||
if (reg.job?.steps) {
|
||||
const j = reg.job;
|
||||
/** @param {import('./shapes.mjs').ProviderPayload} p @param {number} seq */
|
||||
function renderProviderCard(p, seq) {
|
||||
const card = el('div', 'provider-card');
|
||||
const running = p.job?.state === 'running';
|
||||
|
||||
const head = el('div', 'admin-row');
|
||||
head.appendChild(el('span', 'grow', `${p.slug} \u00b7 ${providerStateLine(p)}`));
|
||||
const rm = el('button', 'danger', 'remove');
|
||||
armedButton(rm, {
|
||||
label: 'remove',
|
||||
confirm: 'the runs riding it block until re-picked -- click again',
|
||||
fire: async () => {
|
||||
try { await api(`/providers/${encodeURIComponent(p.slug)}`, { method: 'DELETE', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
head.appendChild(rm);
|
||||
card.appendChild(head);
|
||||
|
||||
// the acts
|
||||
const acts = el('div', 'form-actions');
|
||||
const disc = /** @type {HTMLButtonElement} */ (el('button', null, 'discover'));
|
||||
const refi = /** @type {HTMLButtonElement} */ (el('button', null, 'refine'));
|
||||
disc.disabled = running;
|
||||
refi.disabled = running || p.phase === 'none';
|
||||
armedButton(disc, {
|
||||
label: 'discover',
|
||||
confirm: 'resets this provider\'s section to a fresh scrape -- the battery results are re-earned by refining. click again',
|
||||
fire: async () => {
|
||||
try { await api(`/providers/${encodeURIComponent(p.slug)}/discover`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
armedButton(refi, {
|
||||
label: 'refine',
|
||||
confirm: 'sends real traffic over every model on this provider -- may cost a buck. click again',
|
||||
fire: async () => {
|
||||
try { await api(`/providers/${encodeURIComponent(p.slug)}/refine`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
acts.appendChild(disc);
|
||||
acts.appendChild(refi);
|
||||
// the key control (GM, 2026-11-19): remove re-probes the keyless
|
||||
// endpoint -- a provider gone public lands working, a locked one
|
||||
// re-opens the ask (that is the key-replacement path). o/f never
|
||||
// carries a key, so the control never shows on it.
|
||||
if (p.hasKey) {
|
||||
const rmk = /** @type {HTMLButtonElement} */ (el('button', null, 'remove key'));
|
||||
armedButton(rmk, {
|
||||
label: 'remove key',
|
||||
confirm: 'the key leaves the config and the endpoint is probed again -- click again',
|
||||
fire: async () => {
|
||||
try {
|
||||
const res = await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'DELETE', body: {} });
|
||||
if (res.probe && res.probe !== 'ok') banner(res.detail ?? 'the endpoint failed the keyless probe');
|
||||
} catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
acts.appendChild(rmk);
|
||||
}
|
||||
card.appendChild(acts);
|
||||
|
||||
// the ask (GM, 2026-11-19): a provider whose last probe met an auth
|
||||
// refusal opens the key path -- the token is checked on reception,
|
||||
// saved on success, asked again on the next refusal
|
||||
if (p.probe?.outcome === 'auth' && p.slug !== 'opencode/free') {
|
||||
const ask = el('div', 'admin-row');
|
||||
const lab = el('label', 'field', 'API key ');
|
||||
const key = /** @type {HTMLInputElement} */ (el('input'));
|
||||
key.type = 'password';
|
||||
key.autocomplete = 'off';
|
||||
lab.appendChild(key);
|
||||
const send = el('button', null, 'send key');
|
||||
send.addEventListener('click', async () => {
|
||||
if (!key.value.trim()) { banner('enter the key first'); return; }
|
||||
try {
|
||||
await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'POST', body: { apiKey: key.value.trim() } });
|
||||
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
|
||||
dropModelCache();
|
||||
render();
|
||||
});
|
||||
ask.appendChild(lab);
|
||||
ask.appendChild(send);
|
||||
card.appendChild(ask);
|
||||
}
|
||||
|
||||
// the refine meter: the bar moves only on real step completions,
|
||||
// the label names the call running now, and the lines are the
|
||||
// receipt -- they survive the job, so a landed pass keeps its
|
||||
// verdicts and a rejected one keeps its post-mortem
|
||||
if (p.job?.steps) {
|
||||
const j = p.job;
|
||||
const st = j.steps ?? { total: 0, done: 0, label: '' };
|
||||
meter.hidden = false;
|
||||
$('refine-count').textContent = `${st.done}/${st.total} \u00b7 ${j.state}`;
|
||||
$('refine-label').textContent = j.state === 'running'
|
||||
const meter = el('div', 'refine-progress');
|
||||
const top = el('div', 'refine-topline');
|
||||
top.appendChild(el('span', 'refine-count', `${st.done}/${st.total} \u00b7 ${j.state}`));
|
||||
top.appendChild(el('span', 'refine-label hint', j.state === 'running'
|
||||
? `${st.label}${st.chars != null ? ` \u00b7 ${st.chars} chars` : ''}`
|
||||
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label);
|
||||
/** @type {HTMLDivElement} */ ($('refine-fill')).style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
|
||||
linesBox.textContent = '';
|
||||
for (const l of j.lines ?? []) linesBox.appendChild(el('div', 'refine-line', l));
|
||||
} else {
|
||||
meter.hidden = true;
|
||||
linesBox.textContent = '';
|
||||
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label)));
|
||||
const bar = el('div', 'refine-bar');
|
||||
const fill = el('div', 'refine-fill');
|
||||
fill.style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
|
||||
bar.appendChild(fill);
|
||||
const lines = el('div', 'refine-lines');
|
||||
for (const l of j.lines ?? []) lines.appendChild(el('div', 'refine-line', l));
|
||||
meter.appendChild(top);
|
||||
meter.appendChild(bar);
|
||||
card.appendChild(meter);
|
||||
card.appendChild(lines);
|
||||
}
|
||||
|
||||
const list = $('models-list');
|
||||
list.textContent = '';
|
||||
for (const m of reg.models) {
|
||||
// the selection: the provider's default pair, also the refine
|
||||
// curator. The curator's recommendation sits beside it -- intel
|
||||
// only, applied by the op's click (never auto-landed)
|
||||
if (p.models.length) {
|
||||
const sel = el('div', 'admin-row');
|
||||
const selLab = el('label', 'field', 'default ');
|
||||
const mod = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const eff = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
/** @param {HTMLSelectElement} s @param {string} v @param {string} label */
|
||||
const mk = (s, v, label) => {
|
||||
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
|
||||
o.value = v;
|
||||
s.appendChild(o);
|
||||
};
|
||||
mk(mod, '', '(none)');
|
||||
for (const m of [...p.models].filter((x) => x.inference !== false).sort((a, b) => (a.id < b.id ? -1 : 1))) mk(mod, m.id, m.id);
|
||||
mod.value = p.default?.model ?? '';
|
||||
mk(eff, '', '(level)');
|
||||
for (const lv of EFFORT_LEVELS) mk(eff, lv, lv);
|
||||
eff.value = p.default?.effort ?? '';
|
||||
const save = el('button', null, 'set default');
|
||||
save.addEventListener('click', async () => {
|
||||
if (!mod.value || !eff.value) { banner('the default is a pair -- pick a model and an effort level'); return; }
|
||||
try {
|
||||
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: mod.value, effort: eff.value } });
|
||||
} catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
});
|
||||
selLab.appendChild(mod);
|
||||
selLab.appendChild(eff);
|
||||
sel.appendChild(selLab);
|
||||
sel.appendChild(save);
|
||||
card.appendChild(sel);
|
||||
if (p.recommendation && (p.recommendation.model !== p.default?.model || p.recommendation.effort !== p.default?.effort)) {
|
||||
const rec = el('div', 'admin-row');
|
||||
rec.appendChild(el('span', 'grow', `the curator recommends ${p.recommendation.model} at ${p.recommendation.effort}`));
|
||||
const apply = el('button', null, 'apply');
|
||||
apply.addEventListener('click', async () => {
|
||||
try {
|
||||
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: p.recommendation?.model, effort: p.recommendation?.effort } });
|
||||
} catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
});
|
||||
rec.appendChild(apply);
|
||||
card.appendChild(rec);
|
||||
}
|
||||
}
|
||||
|
||||
// the model list
|
||||
for (const m of p.models) {
|
||||
const row = el('div', 'admin-row');
|
||||
const facts = [
|
||||
m.id,
|
||||
@@ -172,14 +330,28 @@ function renderModelsAdmin(reg, seq) {
|
||||
].filter(Boolean).join(' \u00b7 ');
|
||||
row.appendChild(el('span', 'grow', facts));
|
||||
if (m.description) row.appendChild(el('span', 'hint', m.description));
|
||||
list.appendChild(row);
|
||||
card.appendChild(row);
|
||||
}
|
||||
if (running && seq === state.seq) {
|
||||
return card;
|
||||
}
|
||||
|
||||
/** @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {number} seq */
|
||||
function renderProvidersAdmin(reg, seq) {
|
||||
const list = $('provider-list');
|
||||
list.textContent = '';
|
||||
const none = !reg.providers.length;
|
||||
/** @type {HTMLDivElement} */ ($('providers-banner')).hidden = !none;
|
||||
if (none) {
|
||||
$('providers-banner').textContent = 'no providers configured -- add opencode/free (the anonymous fallback) or a custom provider; the server also self-heals this on restart';
|
||||
}
|
||||
/** @type {HTMLButtonElement} */ ($('provider-add-of')).disabled = reg.providers.some((p) => p.slug === 'opencode/free');
|
||||
for (const p of reg.providers) list.appendChild(renderProviderCard(p, seq));
|
||||
if (reg.providers.some((p) => p.job?.state === 'running') && seq === state.seq) {
|
||||
// the job follows itself home: poll until it lands, then re-render
|
||||
setTimeout(async () => {
|
||||
const r = await api('/models').catch(() => null);
|
||||
const r = /** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => null));
|
||||
if (!r || seq !== state.seq || state.view !== 'home') return;
|
||||
if (r.job?.state === 'running') renderModelsAdmin(r, seq);
|
||||
if (r.providers.some((p) => p.job?.state === 'running')) renderProvidersAdmin(r, seq);
|
||||
else render();
|
||||
}, 2000);
|
||||
}
|
||||
@@ -190,28 +362,60 @@ function fmtStamp(iso) {
|
||||
return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC` : '?';
|
||||
}
|
||||
|
||||
// discover: the free scrape -- armed because it resets a refined
|
||||
// registry back to the preliminary list (the curation is re-earned
|
||||
// by refining again)
|
||||
armedButton($('models-discover'), {
|
||||
label: 'discover',
|
||||
confirm: 'resets the registry to a fresh scrape -- click again',
|
||||
fire: async () => {
|
||||
try { await api('/models/discover', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
// the add flow (GM, 2026-11-19): the binary choice, and the probe
|
||||
// decides the key path. o/f is one click; custom opens the inline
|
||||
// form taking ONLY the endpoint -- a working keyless listing never
|
||||
// sees a key field. A 401/403 stands the provider broken and opens
|
||||
// the key field: the key rides the auth route, checked on reception,
|
||||
// saved on success, asked again on the next refusal. Every other
|
||||
// failure refuses the add outright (nothing stands, the form stays).
|
||||
/** @type {?string} */ let authTarget = null; // set when an add landed broken on auth -- the form's next go keys it
|
||||
function closeAddForm() {
|
||||
authTarget = null;
|
||||
/** @type {HTMLFormElement} */ ($('provider-form')).hidden = true;
|
||||
/** @type {HTMLInputElement} */ ($('provider-slug')).value = '';
|
||||
/** @type {HTMLInputElement} */ ($('provider-base')).value = '';
|
||||
/** @type {HTMLInputElement} */ ($('provider-key')).value = '';
|
||||
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = true;
|
||||
}
|
||||
$('provider-add-of').addEventListener('click', async () => {
|
||||
try { await api('/providers', { method: 'POST', body: { builtin: true } }); } catch (e) { banner(e.message); return; }
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
|
||||
// refine: the inference battery + the curator pass -- real traffic
|
||||
armedButton($('models-refine'), {
|
||||
label: 'refine',
|
||||
confirm: 'sends real traffic over every model -- may cost a buck. click again',
|
||||
fire: async () => {
|
||||
try { await api('/models/refine', { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
$('provider-add-custom').addEventListener('click', () => { /** @type {HTMLFormElement} */ ($('provider-form')).hidden = false; });
|
||||
$('provider-add-cancel').addEventListener('click', () => closeAddForm());
|
||||
$('provider-add-go').addEventListener('click', async () => {
|
||||
const slug = /** @type {HTMLInputElement} */ ($('provider-slug')).value.trim();
|
||||
const baseUrl = /** @type {HTMLInputElement} */ ($('provider-base')).value.trim();
|
||||
const apiKey = /** @type {HTMLInputElement} */ ($('provider-key')).value.trim();
|
||||
if (authTarget) {
|
||||
// the provider stands broken -- this go sends the key, not another add
|
||||
if (!apiKey) { banner('the endpoint wants a key -- enter one or cancel'); return; }
|
||||
try {
|
||||
await api(`/providers/${encodeURIComponent(authTarget)}/auth`, { method: 'POST', body: { apiKey } });
|
||||
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
|
||||
closeAddForm();
|
||||
dropModelCache();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (!slug || !baseUrl) { banner('slug and baseUrl are both required'); return; }
|
||||
try {
|
||||
await api('/providers', { method: 'POST', body: { slug, baseUrl } });
|
||||
} catch (e) {
|
||||
if (e.status === 401 || e.status === 403) {
|
||||
authTarget = slug;
|
||||
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = false;
|
||||
banner(e.message);
|
||||
return;
|
||||
}
|
||||
banner(e.message); return; // refused outright (or bad input) -- nothing stands
|
||||
}
|
||||
closeAddForm();
|
||||
dropModelCache();
|
||||
render();
|
||||
},
|
||||
});
|
||||
|
||||
$('new-run-btn').addEventListener('click', () => navigate('/new'));
|
||||
$('invite-mint').addEventListener('click', async () => {
|
||||
try {
|
||||
|
||||
+1
-1
@@ -244,7 +244,7 @@ async function refreshPlay(id, seq) {
|
||||
$('models-pane').hidden = false;
|
||||
const mlist = await modelList();
|
||||
if (seq !== state.seq) return;
|
||||
models.fill(detail.run.models, detail.run.modelDefaults, detail.run.params, detail.run.paramDefaults, mlist);
|
||||
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
|
||||
|
||||
// pending ask: the modal re-presents after a refresh -- the owner's
|
||||
// to answer
|
||||
|
||||
+16
-2
@@ -35,6 +35,17 @@ const EDIT_LIST = [
|
||||
{ name: 'run.json', mode: 'ro', source: 'run' },
|
||||
];
|
||||
|
||||
// per-file authoring hints: the formats the raw editor would otherwise
|
||||
// ask the author to know by heart -- the save lint names violations,
|
||||
// the hint teaches the shape up front
|
||||
/** @type {Record<string, string>} */
|
||||
const FILE_HINTS = {
|
||||
'carryover.jsonl':
|
||||
'one JSON object per line. A turn is {"t": "msg", "m": {"role": "assistant" or "user", "content": "..."}}. '
|
||||
+ 'Her turn carries the <status> and <agenda> blocks; the sheet rides a GM turn as its "sheet" field, never as a tag. '
|
||||
+ '@PC, @Package and $VARS expand at start (the authored opening only).',
|
||||
};
|
||||
|
||||
// the editor's working set -- module-local, reset on every enter
|
||||
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
|
||||
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
|
||||
@@ -42,7 +53,7 @@ const EDIT_LIST = [
|
||||
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
|
||||
/** @type {Record<string, string>} */ let repoPrompts = {};
|
||||
|
||||
const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' });
|
||||
const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' });
|
||||
|
||||
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
|
||||
export async function enter(id, seq) {
|
||||
@@ -105,7 +116,7 @@ export async function enter(id, seq) {
|
||||
// models: per-run overrides, selected from the registry
|
||||
const mlist = await modelList();
|
||||
if (seq !== state.seq) return;
|
||||
models.fill(detail.run.models, detail.run.modelDefaults, detail.run.params, detail.run.paramDefaults, mlist);
|
||||
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
|
||||
|
||||
const nav = $('setup-files');
|
||||
nav.textContent = '';
|
||||
@@ -180,6 +191,9 @@ function selectFile(f) {
|
||||
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
|
||||
$('setup-save').hidden = spec.mode !== 'rw';
|
||||
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
|
||||
const hint = FILE_HINTS[f] ?? '';
|
||||
$('edit-hint').textContent = hint;
|
||||
$('edit-hint').hidden = !hint;
|
||||
renderHighlight();
|
||||
markNav();
|
||||
}
|
||||
|
||||
+158
-103
@@ -6,16 +6,16 @@
|
||||
// - paneEditor: the status/agenda pattern -- a body line, an edit
|
||||
// button, an inline editor; the edit stages, the send rides it
|
||||
// with the turn; the section shell stays in index.html
|
||||
// - modelsBox: the per-run player/housekeeper selects over the
|
||||
// registry plus the sampling knobs (knobs.mjs owns the knob row
|
||||
// and its definitions table); setup and the play aside each carry
|
||||
// - modelsBox: the per-run spec picks -- {provider, model, effort}
|
||||
// per role, no unset effort, no stored params (the <mind> verb is
|
||||
// the only sampling source); setup and the play aside each carry
|
||||
// one
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { knobsBox } from './knobs.mjs';
|
||||
import { EFFORT_LEVELS } from './knobs.mjs';
|
||||
|
||||
// two-click confirm -- the second click within 5s fires; anything
|
||||
// else disarms. Each button owns its own arm state.
|
||||
@@ -199,15 +199,22 @@ export function sheetEditor(section, body) {
|
||||
|
||||
// the model registry, fetched once per session -- the selectors read
|
||||
// the saved registry, never the live provider (discovery is the op's
|
||||
// manual act; a listing fetch every render would hammer the endpoint
|
||||
// for a list that rarely changes)
|
||||
// act; a listing fetch every render would hammer the endpoint for a
|
||||
// list that rarely changes)
|
||||
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
|
||||
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
|
||||
export async function modelList() {
|
||||
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ phase: 'none', discovered: null, refined: null, curator: null, defaults: {}, models: [], job: null })));
|
||||
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ providers: [] })));
|
||||
return cachedRegistry;
|
||||
}
|
||||
|
||||
/** Invalidate the cached registry -- provider state changed (the op
|
||||
* added, removed, discovered, or refined), the next modelList
|
||||
* refetches. */
|
||||
export function dropModelCache() {
|
||||
cachedRegistry = null;
|
||||
}
|
||||
|
||||
// a context ceiling as the short human form: 1048576 -> "1M",
|
||||
// 524288 -> "512K". Null when the provider stated nothing.
|
||||
/** @param {?number} tokens @returns {?string} */
|
||||
@@ -216,106 +223,107 @@ export function fmtCeiling(tokens) {
|
||||
return tokens >= 1048576 ? `${Math.round(tokens / 1048576)}M` : `${Math.round(tokens / 1024)}K`;
|
||||
}
|
||||
|
||||
// A select's "" value means "deployment default"; a current override
|
||||
// missing from the registry stays selectable, so a stale pick never
|
||||
// silently rewrites itself. One plain list, sorted by id (GM,
|
||||
// 2026-11-16: the family grouping left the user guessing what a
|
||||
// family name means, and the curator's tier labels only made sense
|
||||
// inside their groups -- the id is the self-describing name). The
|
||||
// input ceiling rides along -- the user picks against the contwin,
|
||||
// so the context limit belongs in the open.
|
||||
/** @param {HTMLSelectElement} sel @param {?string} current @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {?string} [def] */
|
||||
function fillSelect(sel, current, reg, def) {
|
||||
sel.textContent = '';
|
||||
/** @param {string} v @param {string} label */
|
||||
const mk = (v, label) => {
|
||||
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
|
||||
o.value = v;
|
||||
sel.appendChild(o);
|
||||
};
|
||||
mk('', `deployment default${def ? ` -- ${def}` : ' (unset)'}`);
|
||||
const usableModels = reg.models.filter((m) => m.inference !== false && (m.roles?.player ?? true));
|
||||
const extras = current && !usableModels.some((m) => m.id === current) ? [current] : [];
|
||||
for (const m of [...usableModels].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
|
||||
const ceil = fmtCeiling(m.input);
|
||||
mk(m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
|
||||
}
|
||||
for (const x of extras) mk(x, `${x} (not in the registry)`);
|
||||
sel.value = current ?? '';
|
||||
}
|
||||
|
||||
// the models box: player/housekeeper selects over the registry, the
|
||||
// sampling knobs per role (one shared hint bar under both rows), and
|
||||
// one save. The mount keeps its id -- the CSS panels it. The knob
|
||||
// rows rebuild when the model select changes: the effort knob's
|
||||
// default is measured per model, so switching the model switches the
|
||||
// honest default.
|
||||
// the model picks: per role a full spec {provider, model, effort} --
|
||||
// there is no unset effort (GM, 2026-11-18), and the params layer is
|
||||
// the <mind> verb's alone (per-turn, nothing stored). The health
|
||||
// line under the rows is the invalidation surface: a pick the server
|
||||
// no longer carries names what died and stays visible until the GM
|
||||
// sets it up again. A housekeeper with no pick inherits (the player
|
||||
// spec's provider default) -- the '' provider option says so.
|
||||
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
|
||||
export function modelsBox(mount, { title }) {
|
||||
const root = typeof mount === 'string' ? $(mount) : mount;
|
||||
root.textContent = '';
|
||||
root.appendChild(el('h2', null, title));
|
||||
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const pField = el('label', 'field', 'player ');
|
||||
pField.appendChild(playerSel);
|
||||
const hField = el('label', 'field', 'housekeeper ');
|
||||
hField.appendChild(houseSel);
|
||||
root.appendChild(pField);
|
||||
root.appendChild(hField);
|
||||
const knobHint = el('div', 'knob-hint'); // one bar, both roles
|
||||
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
|
||||
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
|
||||
root.appendChild(playerKnobs.wrap);
|
||||
root.appendChild(houseKnobs.wrap);
|
||||
root.appendChild(knobHint);
|
||||
// the latest fill's inputs -- the select-change refresh rebuilds
|
||||
// the knob rows against them (the effort context follows the
|
||||
// newly-picked model)
|
||||
/** @type {?{ params: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, paramDefaults: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, reg: import('./shapes.mjs').ModelsRegistryResponse }} */ let last = null;
|
||||
// the effort knob's context: the currently-selected model's
|
||||
// measured ladder (null when the registry has none for it)
|
||||
/** @param {'player'|'housekeeper'} role @param {import('./shapes.mjs').ModelsRegistryResponse} reg @returns {?{ measured: Record<string, number>, fallback: ?string }} */
|
||||
const effortOf = (role, reg) => {
|
||||
const id = (role === 'player' ? playerSel.value : houseSel.value)
|
||||
|| reg.defaults?.[role] || null;
|
||||
const m = id ? reg.models.find((x) => x.id === id) : null;
|
||||
return m?.efforts ? { measured: m.efforts, fallback: m.effortDefault ?? null } : null;
|
||||
|
||||
/** @typedef {{ prov: HTMLSelectElement, mod: HTMLSelectElement, eff: HTMLSelectElement }} Row */
|
||||
/** @param {string} role @returns {Row} */
|
||||
const mkRow = (role) => {
|
||||
const prov = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const mod = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const eff = /** @type {HTMLSelectElement} */ (el('select'));
|
||||
const field = el('label', 'field', `${role} `);
|
||||
field.appendChild(prov);
|
||||
field.appendChild(mod);
|
||||
field.appendChild(eff);
|
||||
root.appendChild(field);
|
||||
return { prov, mod, eff };
|
||||
};
|
||||
/** rebuild both knob rows against the current selects and the
|
||||
* latest fill (fill and select-change both land here) */
|
||||
function rebuildKnobs() {
|
||||
if (!last) return;
|
||||
const pk = knobsBox('player', last.params?.player ?? undefined, last.paramDefaults?.player ?? undefined, knobHint, effortOf('player', last.reg));
|
||||
const hk = knobsBox('housekeeper', last.params?.housekeeper ?? undefined, last.paramDefaults?.housekeeper ?? undefined, knobHint, effortOf('housekeeper', last.reg));
|
||||
playerKnobs.wrap.replaceWith(pk.wrap);
|
||||
houseKnobs.wrap.replaceWith(hk.wrap);
|
||||
playerKnobs = pk;
|
||||
houseKnobs = hk;
|
||||
}
|
||||
playerSel.addEventListener('change', rebuildKnobs);
|
||||
houseSel.addEventListener('change', rebuildKnobs);
|
||||
if (!root.querySelector('.registry-hint')) {
|
||||
const hint = el('div', 'hint registry-hint', '');
|
||||
const player = mkRow('player');
|
||||
const house = mkRow('housekeeper');
|
||||
const healthLine = el('div', 'hint');
|
||||
root.appendChild(healthLine);
|
||||
const hint = el('div', 'hint');
|
||||
root.appendChild(hint);
|
||||
}
|
||||
const saveBtn = el('button', null, 'save models');
|
||||
const saveState = el('span', 'save-state');
|
||||
const actions = el('div', 'form-actions');
|
||||
actions.appendChild(saveBtn);
|
||||
actions.appendChild(saveState);
|
||||
root.appendChild(actions);
|
||||
|
||||
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let reg = null;
|
||||
|
||||
/** @param {HTMLSelectElement} sel @param {string} v @param {string} label */
|
||||
const opt = (sel, v, label) => {
|
||||
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
|
||||
o.value = v;
|
||||
sel.appendChild(o);
|
||||
};
|
||||
|
||||
// one provider's usable player models; a stale pick stays selectable
|
||||
// (a stale pick never silently rewrites itself)
|
||||
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} current */
|
||||
const fillModels = (sel, slug, current) => {
|
||||
const section = reg?.providers.find((p) => p.slug === slug) ?? null;
|
||||
sel.textContent = '';
|
||||
opt(sel, '', '(no model picked)');
|
||||
const usable = (section?.models ?? []).filter((m) => m.inference !== false && (m.roles?.player ?? true));
|
||||
const sorted = [...usable].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||
for (const m of sorted) {
|
||||
const ceil = fmtCeiling(m.input);
|
||||
opt(sel, m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
|
||||
}
|
||||
if (current && !sorted.some((m) => m.id === current)) opt(sel, current, `${current} (not in this provider's registry)`);
|
||||
sel.value = current ?? '';
|
||||
};
|
||||
|
||||
// the effort select: the ladder, the '' option naming the measured
|
||||
// default when the registry carries one
|
||||
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} modelId @param {?string} current */
|
||||
const fillEffort = (sel, slug, modelId, current) => {
|
||||
const m = reg?.providers.find((p) => p.slug === slug)?.models.find((x) => x.id === modelId) ?? null;
|
||||
sel.textContent = '';
|
||||
opt(sel, '', m?.effortDefault ? `(measured default: ${m.effortDefault})` : '(pick a level)');
|
||||
for (const lv of EFFORT_LEVELS) opt(sel, lv, lv);
|
||||
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
|
||||
};
|
||||
|
||||
// a provider or model change re-derives the dependent options (the
|
||||
// effort choice survives a model switch -- it is the pick's, not
|
||||
// the model's)
|
||||
for (const row of [player, house]) {
|
||||
row.prov.addEventListener('change', () => {
|
||||
fillModels(row.mod, row.prov.value, null);
|
||||
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
|
||||
});
|
||||
row.mod.addEventListener('change', () => {
|
||||
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
|
||||
});
|
||||
}
|
||||
|
||||
saveBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
// the knob read throws on an empty override -- same banner, nothing sent
|
||||
const params = { player: playerKnobs.read(), housekeeper: houseKnobs.read() };
|
||||
/** @param {Row} row @param {string} role @returns {?{ provider: string, model: string, effort: string }} */
|
||||
const specOf = (row, role) => {
|
||||
if (!row.prov.value) return null;
|
||||
if (!row.mod.value) throw new Error(`${role}: pick a model (or clear the provider)`);
|
||||
if (!row.eff.value) throw new Error(`${role}: pick an effort level -- there is no unset effort`);
|
||||
return { provider: row.prov.value, model: row.mod.value, effort: row.eff.value };
|
||||
};
|
||||
await api(`/runs/${state.runId}/model`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
player: playerSel.value || null,
|
||||
housekeeper: houseSel.value || null,
|
||||
params,
|
||||
},
|
||||
body: { player: specOf(player, 'player'), housekeeper: specOf(house, 'housekeeper') },
|
||||
});
|
||||
saveState.textContent = 'saved';
|
||||
} catch (e) {
|
||||
@@ -323,21 +331,68 @@ export function modelsBox(mount, { title }) {
|
||||
saveState.textContent = 'not saved';
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} params @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} paramDefaults @param {import('./shapes.mjs').ModelsRegistryResponse} reg */
|
||||
fill(models, defaults, params, paramDefaults, reg) {
|
||||
fillSelect(playerSel, models?.player ?? null, reg, defaults?.player);
|
||||
fillSelect(houseSel, models?.housekeeper ?? null, reg, defaults?.housekeeper);
|
||||
last = { params: params ?? null, paramDefaults: paramDefaults ?? null, reg };
|
||||
rebuildKnobs();
|
||||
const hint = root.querySelector('.registry-hint');
|
||||
if (hint) {
|
||||
hint.textContent = reg.phase === 'none'
|
||||
? 'no models discovered -- the op runs discovery from the admin block on home'
|
||||
: reg.phase === 'preliminary'
|
||||
? 'preliminary registry -- unrefined: the op can run refine to verify and label the models'
|
||||
: '';
|
||||
/** @param {{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }} models run.json verbatim (the spec picks)
|
||||
* @param {?{ player?: ?import('./shapes.mjs').RoleHealth, housekeeper?: ?import('./shapes.mjs').RoleHealth }} modelState the resolved truth
|
||||
* @param {?{ slug: string, default: ?{ model: string, effort: string } }[]} providerDefaults
|
||||
* @param {import('./shapes.mjs').ModelsRegistryResponse} theReg */
|
||||
fill(models, modelState, providerDefaults, theReg) {
|
||||
reg = theReg;
|
||||
/** @param {Row} row @param {'player'|'housekeeper'} role */
|
||||
const fillRole = (row, role) => {
|
||||
// the prefill is the run's OWN stored pick only -- an
|
||||
// inherited housekeeper stays '' (saving an explicit pick is
|
||||
// a deliberate act; the health line states what inherits)
|
||||
const raw = models?.[role];
|
||||
const spec = raw && typeof raw === 'object' && !Array.isArray(raw)
|
||||
? /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw) : null;
|
||||
const pick = spec && typeof spec.provider === 'string' && typeof spec.model === 'string' && typeof spec.effort === 'string'
|
||||
? { provider: spec.provider, model: spec.model, effort: spec.effort } : null;
|
||||
row.prov.textContent = '';
|
||||
opt(row.prov, '', role === 'housekeeper' ? '(inherit -- the player provider\'s default)' : '(no provider picked)');
|
||||
const slugs = (reg?.providers ?? []).map((p) => p.slug);
|
||||
if (pick && !slugs.includes(pick.provider)) opt(row.prov, pick.provider, `${pick.provider} (no longer configured)`);
|
||||
for (const s of slugs) opt(row.prov, s, s);
|
||||
row.prov.value = pick?.provider ?? '';
|
||||
if (pick) {
|
||||
fillModels(row.mod, pick.provider, pick.model);
|
||||
fillEffort(row.eff, pick.provider, pick.model, pick.effort);
|
||||
return;
|
||||
}
|
||||
// no stored pick: the player pre-selects the first provider's
|
||||
// default (the create flow lands an explicit pick); the
|
||||
// housekeeper inherits, so it stays ''
|
||||
if (role === 'player' && slugs.length) {
|
||||
const withDef = providerDefaults?.find((x) => x.default && slugs.includes(x.slug)) ?? null;
|
||||
const slug = withDef?.slug ?? slugs[0];
|
||||
row.prov.value = slug;
|
||||
fillModels(row.mod, slug, withDef?.default?.model ?? null);
|
||||
fillEffort(row.eff, slug, withDef?.default?.model ?? null, withDef?.default?.effort ?? null);
|
||||
} else {
|
||||
fillModels(row.mod, row.prov.value, null);
|
||||
fillEffort(row.eff, row.prov.value, null, null);
|
||||
}
|
||||
};
|
||||
fillRole(player, 'player');
|
||||
fillRole(house, 'housekeeper');
|
||||
// the health line: the invalidation notes and the inheritance
|
||||
const notes = [];
|
||||
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
|
||||
const st = modelState?.[role];
|
||||
if (!st) continue;
|
||||
if (st.ok && st.inherited && st.spec) notes.push(`${role}: inherits ${st.spec.provider}'s default (${st.spec.model} at ${st.spec.effort})`);
|
||||
if (!st.ok && st.note) notes.push(`${role}: ${st.note}`);
|
||||
}
|
||||
healthLine.textContent = notes.join(' \u00b7 ');
|
||||
const providers = reg?.providers ?? [];
|
||||
hint.textContent = !providers.length
|
||||
? 'no providers configured -- the op fixes this from the admin block on home'
|
||||
: providers.every((p) => p.phase === 'none')
|
||||
? 'providers configured but nothing discovered -- the op discovers from the admin block on home'
|
||||
: providers.some((p) => p.phase === 'preliminary')
|
||||
? 'a preliminary registry is unrefined: the op can run refine to verify and label its models'
|
||||
: '';
|
||||
saveState.textContent = '';
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user