diff --git a/.claude/tasks/contracts/2026-10-25-picker-scope-1952.md b/.claude/tasks/contracts/2026-10-25-picker-scope-1952.md new file mode 100644 index 0000000..0cb34c4 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-25-picker-scope-1952.md @@ -0,0 +1,54 @@ +# CONTRACT — picker-scope +- date: 2026-10-25 | flow: feat | branch: feature/model-scope-dialog (in place) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +"oui commence par la feat sélecteur. j'ai pris un nouveau dossier j'ai mis haiku, et j'ai mis un autre dossier encore et c'etait haiku de base alors que ca devrait etre opus par defaut si on a pas de pin par projet on pin opus. Et dans tout les cas, on utilise les dernieres verison de chaque model. bref corrige tout cela" ++ earlier: "je voulais effectivement qu'on puisse dnas le selecteur, dire le model qu'on veut, puis que cela propose si on le veut project scope ou user scope" ++ "Donc la, si je fais /model sur un projet, ce dit projet pin le model choisi, et il peut etre different pour chaque projet / conversation et a par defaut opus. On est ok la dessu ? fait le /feat si tu veux" + +## CLARIFICATIONS +- [gated 2026-10-25] Picker answers = This project / This conversation / Everywhere (same as `/model `, BDR-126). +- [gated 2026-10-25] Project pin = full id (`claude-fable-5-1`, `[1m]` kept); "latest version" = the router table carries the latest ids (2c39524). +- [gated 2026-10-25] A model chosen by hand through the dialog (picker or `/model `, scopes This project / This conversation) ALWAYS switches: it bypasses `mainUpgrade` / `mainModelSwitch` and the cold-read caps; the breaker (model down) and the context window (`fits`) stay in force. +- [gated 2026-10-25] Picker "Default" (requested_model null) → native, no question. +- Default with no project pin = opus: user settings.json is written only by Everywhere (native). Restored to opus 2026-10-25 after the picker leaks (BLK-036). +- [after the challenge 2026-10-25] Plan r2: hand pick = own early branch in decideMain (breaker on the TARGET checked every turn); slot held → deny + toast (no native leak); a native user switch drops a hand pick; stale-conversation guard. Plan r3 (confirmation FATAL(1) folded inline): unusable hand pick falls through to the existing chain; Everywhere thunk returns {}; clock fixtures named; conv read before the slot check; hand-pick drop skipped while a picker dialog is open; hand pick clears its target's mark; effort-shift l.70 amended. Residuals: `/config` Model row still native (source `command`), hand pick dropped at `/clear`, no timeout on a never-settling dialog. +- SPIKE PROVEN 2026-10-25 (dev mod picker-spike, user-run in a live session): `on('classic.PreModelSwitch')` fires for `source: 'picker'` with `requested_model`; `$.ui.ask` awaited INSIDE the hook never renders (UI frozen on "Running PreModelSwitch hooks…"); returning `{ permissionDecision: 'deny', permissionDecisionReason }` at once blocks the switch and the user settings.json write; a continuation launched before return and run after it (`await $.clock.sleep(300)` then `$.ui.ask`) renders; `$.command.run({ command: 'model', args })` from that continuation runs the native switch + user settings write. + +## ACCEPTANCE CRITERIA +1. A `classic.PreModelSwitch` hook: `source: 'picker'`, router on, `requested_model` a string the table knows (`knownModel`), a surface present, no dialog in flight → returns `{ permissionDecision: 'deny', permissionDecisionReason }` WITHOUT awaiting any dialog, and holds the single-dialog slot (`st.asking`) from before the return until the deferred dialog ends. +2. Passthrough (`next(e)`, no dialog, no deny) for: `source` `command` or `sdk` (a first-line source filter, ahead of `ensureConfig`); `requested_model` null or unknown to the table; router off; no surface. `ensureConfig` runs before those gates. `st.asking` already held → deny + toast `answer the open dialog first`, never native. The hook's `.catch` passes through with its own warnOnce key. +3. The deferred dialog (after a short sleep) asks the same question and options as `/model ` (This project / This conversation / Everywhere, header `model-router`, pin note when the project already pins a model) for the picked model's full id. +4. Picker → This project: same effects as `/model ` → This project (project settings.local.json written with the full id under the same refusal rules, sticky model route, run slot dropped, sticky effort kept); the outcome text reaches the transcript (`$.ui.log`); user settings.json never written (native never runs). +5. Picker → This conversation: sticky route only, nothing written, native never runs; outcome logged. +6. Picker → Everywhere: prior sticky model/tier dropped, then `$.command.run({ command: 'model', args: })` (native switch + user settings write); its PreModelSwitch (`source: 'command'`) and its `command.run` (origin plugin) both pass through, no second dialog. +7. Picker dialog dismissed or free text → nothing written, nothing routed, native never runs, the NO_SCOPE text logged. A throw inside the deferred dialog (before or after the answer) is logged under the picker's own warn key and always releases `st.asking`. If the conversation changed (`$.session.id()`) between the deny and the answer, nothing is applied and that is logged. +8. Hand choice always switches: with a sticky model route set by a dialog answer (picker or `/model `, This project / This conversation), every main step, in later turns too, moves to that model even when the cold read exceeds `upgradeMaxTokens` / `downgradeMaxTokens`, `mainUpgrade` / `mainModelSwitch` is off, the current model is down or the session model is outside the table. When the hand-picked model is marked down or does not fit its known window, the hand pick waits (one log) and the EXISTING automatic chain decides as if no model were wanted (a down current model, even when it IS the hand pick, falls back to the next available model; windowReturn still applies), on every turn until the hand-picked model is usable again. A hand pick clears its target's breaker mark at the time of the pick, like a native user switch. A sticky route set by a typed `/route model=` keeps today's caps. A native user switch (PostModelSwitch source command/picker/sdk) drops a hand pick. +9. Tests in register.test.ts cover criteria 1-8 as listed in the plan r2 §Tests (deny without awaiting, each passthrough, slot-held deny, the three answers, dismiss, sleep throw, post-answer throw, stale conversation, hand pick down ACROSS a turn boundary, cur down, unranked session, cap bypass up and down, `/route model=` still capped, native switch drops the hand pick). +10. lib/effort-shift.md documents the picker (deny then scope question; Everywhere = native write) and the hand-choice cap bypass; lines ≤ 80 cols. + CHECK: a=$(grep -c 'picker' lib/effort-shift.md); b=$(awk 'length($0)>80' lib/effort-shift.md | wc -l); echo "doc=$([ "$a" -ge 1 ] && echo ok)/$b" + EXPECT: doc=ok/0 + EVIDENCE: MET exit=0 marker-found :: doc=ok/0 +11. Mod suite green. + CHECK: make test suite=lib/tests/mods.test.sh 2>&1 | tail -1 + EXPECT: all suites green + EVIDENCE: MET exit=0 marker-found :: all suites green +12. Full suite green. + CHECK: make test 2>&1 | tail -1 + EXPECT: all suites green + EVIDENCE: MET exit=0 marker-found :: all suites green +13. Diff since 48778af touches only the FILE SCOPE. + CHECK: git diff --name-only 48778af -- . ':!.claude' | grep -vcE '^(mods/model-router/hooks/register.ts|mods/model-router/hooks/register.test.ts|lib/effort-shift.md)$' | sed 's/^/n=/' + EXPECT: n=0 + EVIDENCE: MET exit=0 marker-found :: n=0 +14. No new lint or test suppression. + CHECK: git diff -U0 48778af -- . ':!.claude' | grep -E '^\+' | grep -cE 'eslint-disable|@ts-ignore|@ts-expect-error|shellcheck disable' | sed 's/^/n=/' + EXPECT: n=0 + EVIDENCE: MET exit=0 marker-found :: n=0 + +## FILE SCOPE +- mods/model-router/hooks/register.ts +- mods/model-router/hooks/register.test.ts +- lib/effort-shift.md +(README.md, USAGE.md, CHANGELOG.md: doc-sync step, not the executor) diff --git a/.claude/tasks/plans/2026-10-25-picker-scope-1952.md b/.claude/tasks/plans/2026-10-25-picker-scope-1952.md new file mode 100644 index 0000000..6f48d0f --- /dev/null +++ b/.claude/tasks/plans/2026-10-25-picker-scope-1952.md @@ -0,0 +1,78 @@ +# PLAN r2 — picker-scope (feat) +Contract: `.claude/tasks/contracts/2026-10-25-picker-scope-1952.md` +Scope rule 7: register.ts + register.test.ts + lib/effort-shift.md (docs README/USAGE/CHANGELOG via doc-sync). +r1 → r2 after 3 lenses: correctness FATAL(5), robustness FATAL(2), simplicity SOLID(3 MINOR). Change named at the finding it closes (C = correctness, R = robustness, S = simplicity). + +## Files +- `mods/model-router/hooks/register.ts` + - `Routed` type (beside `explicitEffort?`, l.~52): `explicitModel?: boolean // the model was chosen by hand in the scope dialog`. + - `stickyModel` (l.~2095) sets `explicitModel: true`. `dropStickyModel` (l.~2109) builds its effort-only slot WITHOUT `explicitModel` (it is the one writer that copies fields, S2). No other writer changes. + - HAND PICK BRANCH (closes C1/R1 BLOCKER, C2/R2, C3, R8). New helpers near `decideMain` (l.~1386): + - `handPicked(st, wanted): boolean` = `st.userMain?.explicitModel === true && wanted !== undefined && wanted === ` (the check names the TARGET, not only the slot, R8). + - `handCall(st, cur, wanted, read): Call`: (a) same alias as `canonical(cur)` → `keep(cur)`; (b) `st.down.has(canonical(st.cfg, wanted))` → `keep(cur, 'hand pick down', is held down; staying on until it is back>)`; (c) `!fits(st, wanted, read.tokens)` → `keep(cur, 'no fit', noFit(wanted))`; (d) else `moveTo(cur, wanted, 'hand pick', st.sessionModel)`. + - `decideMain`: right after `if (st.off) return keep(cur)`, insert `if (handPicked(st, wanted)) return handCall(st, cur, wanted, read)`. It runs BEFORE `unknownCall` (an unranked session model no longer traps a hand pick, C3), before `windowReturn`, before the `cur` down branch (a down current model moves to the hand pick when that one is up, C2/R2). `upgradeCall`, `downgradeCall`, `leaveDown` stay UNCHANGED (r1's bypass inside them is dropped). + - verbose transition cause word `hand pick` where the existing `why` words are mapped (follow the `upgrade`/`downgrade` mapping). + - `scopeDialog` (S1): replace `answerScope` with `async function scopeDialog($, st, token, everywhere: () => Promise, warnKey: string): Promise`: `scopeQuestion($, fullId(st.cfg, token))` → `askOr($, question, MODEL_SCOPES)` → not in MODEL_SCOPES → `{ text: NO_SCOPE }`; Everywhere → `dropStickyModel(st); return await everywhere()`; else `applyLocalScope(...)` → `{ text }`; the post-answer try/catch keeps its text and uses `warnOnce(st, $, warnKey, …)` (C8/R6). `handleModelCommand` keeps its gates and slot, then `return await scopeDialog($, st, token, () => next(e), 'command.run model')`. + - PICKER (new, in the `/model ` section after `handleModelCommand`): + - `const PICKER_DELAY_MS = 300 // the engine draws nothing while a PreModelSwitch hook runs` + - `const PICKER_DENY = 'model-router asks where this switch applies'` + - `const PICKER_BUSY = 'answer the open dialog first'` (reuse the existing string constant if one exists at l.~3137) + - `async function handlePicker($, st, e, next)`: the source filter is a matcher-like first line (`e.source !== 'picker'` → `return next(e)`; C6: the contract wording is amended to say so); then `await ensureConfig($, st)`; gates → `return next(e)`: `st.off`; `typeof e.requested_model !== 'string'` (Default); `!knownModel(st.cfg, asked)`; `(await $.session.surfaces()).length === 0`. Then `st.asking !== null` → `$.ui.toast(PICKER_BUSY)` and return the deny (R3: never native while a dialog is open, the BLK-036 leak). Then, synchronously: `st.asking = \`picker:${asked}\``; `const conv = await` is NOT allowed after this point, so read `$.session.id()` BEFORE the slot is set and pass it in; `void pickerDialog($, st, asked, conv)`; `return { permissionDecision: 'deny', permissionDecisionReason: PICKER_DENY }`. + - `async function pickerDialog($, st, asked, conv): Promise`: `try { await $.clock.sleep(PICKER_DELAY_MS); const out = await scopeDialog($, st, asked, () => $.command.run({ command: 'model', args: asked }), 'PreModelSwitch picker', conv-check); … } catch (err) { warnOnce(st, $, 'PreModelSwitch picker', errWord(err)) } finally { st.asking = null }`. + - stale conversation (C10): `scopeDialog` gets an optional `stillHere: () => Promise`; the picker passes `async () => (await $.session.id()) === conv`, checked right after the answer and before any effect; false → `{ text: 'model: the conversation changed, nothing applied' }`. + - logging (C7): log `out.text` with the safe-log helper (`tryLog`, l.~353) only when the answer was not Everywhere (`$.command.run` already prints the native lines); NO_SCOPE and the stale text are logged. + - registration (S3): in `registerCommandHook` (l.~4002), next to `command.run model`: `on('classic.PreModelSwitch', ($, e, next) => handlePicker($, st, e, next)).catch(($, e, next) => { warnOnce(st, $, 'PreModelSwitch', next.error.kind); return next(e) })`. + - A native user switch drops a hand pick (C4): in `onModelSwitch` (l.~3930), for `USER_SWITCH.has(e.source)` and main (`e.agent_id === undefined`): `if (st.userMain?.explicitModel) dropStickyModel(st)`. So picker Default / unknown name / `/config` row / Everywhere all leave the native model in charge. Our denied switches raise no PostModelSwitch; `/model ` → This project/Conversation never runs native. + - section comment of the `/model ` block: one line on the picker (deny now, ask after) and the hand-pick rule. +- `mods/model-router/hooks/register.test.ts` + - boot: bottom `on('classic.PreModelSwitch', () => ({}))` beside `classic.PostModelSwitch` (l.~278). + - helper `picker($, requested, source = 'picker')` firing `$.classic.PreModelSwitch({...})` with every required field (mirror the PostModelSwitch helper at l.~727). + - World flag `sleepFails` (C5/R6): boot swaps the mock clock's `clock.sleep` for one that rejects (same replacement pattern as `failingClock`, LRN-229; it keeps `clock.now`), so pickerDialog's own catch is reached. + - native witness: the existing `model` command recorder. +- `lib/effort-shift.md`: rewrite the `/model` paragraph (C9: l.~52 "no args … native, no question" is false now): `/model ` or a pick in the `/model` picker asks the scope (the picker's switch is held first: the engine prints that a hook blocked it, then the question comes); Esc = nothing; Everywhere = the native write to user settings.json; picker Default, an unknown name, a headless run = native, and a native switch drops a hand pick. Hand pick rule: a model chosen in that dialog always switches (no cold-read cap, no switch flag); a model held down keeps main where it is; the window guard needs a `windows` entry (none shipped, R4). Residuals: `/clear` drops a hand pick until relaunch (R7); the `/config` Model row still writes user settings.json (R5). ≤ 80 cols. + +## Approach +1. Deny now, ask in a continuation after the hook returned (spike-proven). +2. One dialog function (`scopeDialog`) for both entries, an `everywhere` thunk and a warn key per entry. +3. A hand pick is decided by its own branch in `decideMain`, ahead of every automatic rule; the automatic cap functions stay as they are. +4. The native path stays the only writer of user settings.json (BDR-116). + +## Edge cases +- `[1m]` picks: `knownModel` accepts, the pin keeps `[1m]`, the route uses the bare token (BDR-126). +- picker while a dialog is open → deny + toast, no native (R3). +- `$.command.run` rejects on Everywhere → scopeDialog's catch text → logged under `PreModelSwitch picker`. +- `/clear` while the picker dialog is open → stale check → nothing applied (C10). +- hand-picked model marked down → stays on cur with one log; back up → moves (C1/R1). +- `[deferred 2026-10-25]` R3 timeout: a `$.ui.ask` that never settles keeps the slot (no timeout, same as the first-use dialog); picker picks are then denied with the toast (no leak). R7: hand pick lost at `/clear` (BDR-126 residual). R5: `/config` Model row writes user settings (source `command`, indistinguishable from Everywhere's native run). + +## Tests (register.test.ts, "picker" + "hand pick" blocks) +- picker known model → hook result is the deny AND `w.asked` is empty at that moment; after `clock.advance(300)` + flush: the three-scope question. +- passthrough, no deny, no question: source `command`, `sdk`; requested null; `opusplan`; `claude-opus-5-6`; router off; surfaces `[]`. +- slot held (a `/model` dialog gated open) → deny + `answer the open dialog first` toast, no question, native empty. +- picker → This project / This conversation / Everywhere (native recorder once with `model `, `w.asked` length 1, prior hand pick dropped); dismissed → NO_SCOPE logged, slot freed (a second picker asks again). +- `sleepFails` → warn logged under `PreModelSwitch picker`, slot freed, nothing applied. +- post-answer throw on the picker path → `model failed (` logged, native empty, slot freed. +- stale conversation: `session.id` changes between deny and answer → `conversation changed` logged, nothing written, no route. +- hand pick across turns (C1/R1): hand-pick fable, mark fable down, END THE TURN, next turn's first step on the session model → stays on the session model + one log; hold expires → next turn on fable. +- hand pick cur down (C2/R2): session opus marked down, hand-pick fable with usage over `upgradeMaxTokens` and `mainUpgrade` off → fable. +- hand pick bypass: usage over `upgradeMaxTokens` → fable; usage over `downgradeMaxTokens` + `switch off` → sonnet; `/route model=fable` same usage → held (unchanged). +- unranked session model (C3): session on an id outside the table, hand pick opus → main on opus. +- native user switch drops a hand pick (C4): hand pick fable, then `PostModelSwitch` source `picker` to sonnet → next step on sonnet. +- existing `/model ` tests green with `scopeDialog`. + +## Disposition (STEP 0.6) +- extends BDR-126; amends its held-route residual (hand pick always switches, user pick); keeps its writer rules and full-id pin. +- honors BDR-116: Everywhere = native command; the mod never writes user settings.json. +- honors LRN-203 (`fullId`), LRN-228 (via `applyLocalScope`), LRN-229 (`sleepFails` follows its clock-swap pattern), LRN-230 (no new per-model fact; the window guard caveat is documented). +- accepts LRN-204's cost (one cold re-read per hand switch), user pick. +- BLK-036: picker leak closed; `/config` Model row named as residual (R5), not claimed closed. + +## r3 — confirmation pass folded inline (FATAL(1) + 6 MINOR; re-challenge budget spent) +These OVERRIDE the r2 text where they conflict. +- K1 BLOCKER (hand pick unusable must not pin a down model): `handCall` returns `Call | undefined`. Order: (1) `usable = !st.down.has(canonical(st.cfg, wanted)) && fits(st, wanted, read.tokens)`; (2) not usable → return `undefined`; (3) same alias as `canonical(cur)` → `keep(cur)`; (4) else `moveTo(cur, wanted, 'hand pick', st.sessionModel)`. In `decideMain`: `if (handPicked(st, wanted)) { const hand = handCall(...); if (hand !== undefined) return hand; held = true; wanted = undefined }` then the EXISTING chain runs unchanged with no wanted model (unknownCall / windowReturn / cur down → leaveDown → nextAvailable / keep). When `held`, the returned call carries a `once` log `model-router: is held down or does not fit; hand pick waits` (merge into the call's `once` only when it has none). Tests add: hand pick == current model (opus pinned, session opus), opus marked down → next step in the SAME turn and on the NEXT turn goes to the next available model (sonnet), never opus; hand pick fable mid-turn after the router moved there, fable fails (StopFailure) → next step leaves fable; hand pick outgrowing a known `windows` override → windowReturn still applies. +- K2: the picker's Everywhere thunk is `() => $.command.run({ command: 'model', args: asked }).then(() => ({}))`; pickerDialog logs `out.text` whenever it is defined (so the catch text of a failed Everywhere is logged, the native lines are not printed twice). +- K3 fixtures: `failingClock` (LRN-229 rig) ALSO answers `clock.sleep` at once (so `clockFailsAfterAsk` reaches the dialog); `sleepFails` = a separate whole-clock replacement answering `clock.now` and REJECTING `clock.sleep`. Post-answer-throw picker test uses `clockFailsAfterAsk`; the sleep-throw test uses `sleepFails`. +- K4 order in handlePicker: all awaited gates AND `const conv = await $.session.id()` first; then `st.asking !== null` → deny + toast; then synchronously `st.asking = …`, `void pickerDialog(...)`, return deny. No await between the asking check and the set. +- K5: `onModelSwitch` drop of a hand pick is skipped while `st.asking?.startsWith('picker:')` (a PostModelSwitch emitted for a switch the picker denied must not drop the earlier hand pick). Live check item: does the engine emit PostModelSwitch for a denied picker switch. +- K6: a hand pick clears its target's breaker mark like a native user switch: `applyLocalScope` (both local scopes) calls `clearBreaker(st, canonical(st.cfg, fullId-bare))` before `stickyModel`. +- K7: lib/effort-shift.md l.~70-71 ("Fable on main comes only from a skill row, the `route` tool or a typed `/route`") gains "or a hand pick (`/model`, picker)" in the same edit. diff --git a/lib/effort-shift.md b/lib/effort-shift.md index 0764b32..2761927 100644 --- a/lib/effort-shift.md +++ b/lib/effort-shift.md @@ -42,15 +42,25 @@ relaunch: `ultrathink` in the prompt (turn floor) or `/route effort=max` (sticky, `/route clear` after). Builtin `/effort` is NOT a lever inside a run: rows and routes outrank it. -`/model ` typed with a name the router knows asks the scope (Esc -changes nothing). This project writes the full id as `model` into +`/model ` typed, or a pick in the `/model` picker, with a name the +router knows asks the scope (Esc changes nothing). The picker's switch is +held first: the engine prints that a hook blocked it, then the question +comes. This project writes the full id as `model` into `.claude/settings.local.json` (created if absent: keep it gitignored) and sets a sticky model route. This conversation sets the sticky route only, nothing written. Everywhere is the native command: user `settings.json`, every project. The two non-native answers drop the run slot like a native switch and keep a sticky effort; Everywhere drops an earlier sticky model. -No args, an unknown name or a run with no surface (`-p`) go native, no -question. The file is the session root's: in a worktree, that worktree's. +Picker Default, no args, an unknown name or a run with no surface (`-p`) +go native, no question. A native switch (`/config` Model row included) +drops a hand pick. The file is the session root's: in a worktree, that +worktree's. + +A model chosen in that dialog (a hand pick) always switches: no cold-read +cap, no `mainUpgrade` or `mainModelSwitch` flag, an unranked session model +included. A pick held down keeps main where it is (one log) until it is +back; the window guard needs a `windows` entry (none shipped). A typed +`/route model=` keeps the caps. `/clear` drops a hand pick until relaunch. ## Limits @@ -68,7 +78,8 @@ question. The file is the session root's: in a worktree, that worktree's. `why|review|audit…`), `ultrathink` and a background agent dispatch (derived `orchestrate`) set the turn's effort only, never a model above the session model: Fable on main comes only from a - skill row, the `route` tool or a typed `/route`. + skill row, the `route` tool, a typed `/route` or a hand pick (`/model`, + picker). - Mod off: typed agents fall back to their `model:`/`effort:` frontmatter. - First use of a row asks once, with context (Later, Keep or Change: model, then effort, then Everywhere or this project only); the answer is kept in diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index d992681..7c56f0d 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -40,6 +40,8 @@ type World = { writeGate: Promise | undefined // holds an fs.write open failWrite: boolean // fs.write rejects clockFailsAfterAsk: boolean // clock.now rejects once a dialog opened + sleepFails: boolean // clock.sleep rejects (the picker's delay) + sessionId: string // what session.id answers onAsk: (() => void) | undefined // called when a dialog opens onWrite: (() => void) | undefined // called when an fs.write starts repo: { root: string; remote: string | null } | null | 'fail' @@ -67,6 +69,7 @@ type Fixture = { noHome?: boolean // HOME unset: env.get answers undefined surfaces?: readonly string[] // default ['terminal'] clockFailsAfterAsk?: boolean // see World; the rig gets no MockClock + sleepFails?: boolean // see World; the rig gets no MockClock } /** @@ -129,6 +132,8 @@ function newWorld(fx: Fixture = {}): World { writeGate: undefined, failWrite: false, clockFailsAfterAsk: fx.clockFailsAfterAsk ?? false, + sleepFails: fx.sleepFails ?? false, + sessionId: 's1', onAsk: undefined, onWrite: undefined, repo: fx.repo === undefined ? { root: ROOT, remote: REMOTE } : fx.repo, @@ -253,9 +258,25 @@ function failingClock(on: On, w: World): MockClock { if (w.asked.length > 0) throw new Error('boom') return { value: 0 } }) + on('clock.sleep', () => ({ value: undefined })) return undefined as unknown as MockClock } +/** A clock whose sleep rejects (LRN-229: a whole-clock replacement). */ +function sleepFailsClock(on: On): MockClock { + on('clock.now', () => ({ value: 0 })) + on('clock.sleep', () => { + throw new Error('boom') + }) + return undefined as unknown as MockClock +} + +/** The clock the world asks for: a mock one unless a fixture breaks it. */ +function clockOf(on: On, w: World): MockClock { + if (w.clockFailsAfterAsk) return failingClock(on, w) + return w.sleepFails ? sleepFailsClock(on) : mock.clock(on) +} + /** * Fires session.start so the mod loads its config and registers /route. * The bottom hooks the router reads are in place before the first `$` call: @@ -270,12 +291,12 @@ async function boot( tokens: number | null = 1000, world: World = newWorld(), ): Promise { - const clock = world.clockFailsAfterAsk - ? failingClock(on, world) - : mock.clock(on) + const clock = clockOf(on, world) on('session.model', () => ({ value: model })) on('classic.StopFailure', () => ({})) on('classic.PostModelSwitch', () => ({})) + on('classic.PreModelSwitch', () => ({})) + on('session.id', () => ({ value: world.sessionId })) on('skill.prompt', ($, e) => ({ text: e.text })) on('agent.offer', () => ({ isOffered: true })) // the probe of the model main runs on: every model answers unless a test says not @@ -721,7 +742,7 @@ const switchTo = ( $: Engine, from: string, to: string, - source: 'command' | 'auto', + source: 'command' | 'auto' | 'picker', cache_ttl: '5m' | '1h' = '5m', agent_id?: string, ) => $.classic.PostModelSwitch({ @@ -6328,3 +6349,374 @@ test('writes: kit: only the project settings.local.json is carved out', { } expect(worldServes(m.w, LOCAL_FILE)).toBe(true) }) + +// ---- /model picker: deny now, ask after ---------------------------------- + +const BUSY = 'answer the open dialog first' +const DENY = 'model-router asks where this switch applies' + +type SwitchSource = 'picker' | 'command' | 'sdk' + +/** The PreModelSwitch input of a switch to `requested` from `source`. */ +const preSwitch = (requested: string | null, source: SwitchSource) => ({ + from_model: OPUS, + to_model: requested ?? OPUS, + requested_model: requested, + source, + context_tokens: 0, + prompt_cache_warm: false, + cache_ttl: '5m' as const, + estimated_cache_write_usd: 0, + pricing: 'catalog' as const, +}) + +const pick = ( + $: Engine, + requested: string | null, + source: SwitchSource = 'picker', +) => $.classic.PreModelSwitch(preSwitch(requested, source)) + +/** Lets the timers and the hooks of the deferred dialog run. */ +async function settle(done: () => boolean = () => false): Promise { + for (let i = 0; i < 100 && !done(); i++) { + await new Promise(r => setTimeout(r, 0)) + } + for (let i = 0; i < 5; i++) await new Promise(r => setTimeout(r, 0)) +} + +type PickerRig = ModelRig & { logs: string[] } + +async function bootPicker( + $: Engine, + on: On, + answers: string[], + fx: Fixture = {}, +): Promise { + const logs = recordLogs(on) + const m = await bootModel($, on, answers, OPUS, fx) + return { ...m, logs } +} + +/** The picker's switch, then the deferred question answered. */ +async function pickAndAnswer( + $: Engine, + p: PickerRig, + requested: string, +): Promise { + const out = await pick($, requested) + await p.rig.clock.advance(300) + await settle(() => p.w.asked.length > 0 && p.logs.length > 0) + return out +} + +test('picker: a known model is denied at once, the question comes after', async ( + $, on) => { + const p = await bootPicker($, on, ['This conversation']) + const held = deferred() + p.w.gate = held.gate + const out = await pick($, 'fable') + expect(JSON.stringify(out)).toContain(DENY) + expect(JSON.stringify(out)).toContain('deny') + expect(p.w.asked).toEqual([]) + await p.rig.clock.advance(300) + await settle(() => p.w.asked.length > 0) + const [q] = p.w.asked as [Asked] + expect(q.options).toEqual(SCOPES) + expect(q.header).toBe('model-router') + expect(q.text.endsWith(`Switch main to ${FABLE} where?`)).toBe(true) + held.release() + await settle() + expect(p.ran).toEqual([]) +}) + +const PASSTHROUGH: [string, string | null, SwitchSource][] = [ + ['source command', 'fable', 'command'], + ['source sdk', 'fable', 'sdk'], + ['Default (null)', null, 'picker'], + ['opusplan', 'opusplan', 'picker'], + ['an unknown id', 'claude-opus-5-6', 'picker'], +] + +for (const [name, requested, source] of PASSTHROUGH) { + test(`picker: ${name} passes through, no question`, async ($, on) => { + const p = await bootPicker($, on, ['This project']) + const out = await pick($, requested, source) + await p.rig.clock.advance(300) + await settle() + expect(JSON.stringify(out)).not.toContain('deny') + expect(p.w.asked).toEqual([]) + expect(p.toasts).toEqual([]) + }) +} + +test('picker: router off passes through', async ($, on) => { + const p = await bootPicker($, on, []) + await route($, 'off') + expect(JSON.stringify(await pick($, 'fable'))).not.toContain('deny') + await settle() + expect(p.w.asked).toEqual([]) +}) + +test('picker: no surface passes through', async ($, on) => { + const p = await bootPicker($, on, [], { surfaces: [] }) + expect(JSON.stringify(await pick($, 'fable'))).not.toContain('deny') + await settle() + expect(p.w.asked).toEqual([]) +}) + +test('picker: an open dialog denies with a toast, never native', async ( + $, on) => { + const p = await bootPicker($, on, ['This conversation']) + const held = deferred() + const open = deferred() + p.w.gate = held.gate + p.w.onAsk = open.release + const first = modelCmd($, 'fable') + await open.gate + const out = await pick($, 'sonnet') + expect(JSON.stringify(out)).toContain('deny') + expect(p.toasts).toEqual([BUSY]) + held.release() + await first + expect(p.w.asked).toHaveLength(1) + expect(p.ran).toEqual([]) +}) + +test('picker: This project writes the full id, native never runs', async ( + $, on) => { + const p = await bootPicker($, on, ['This project']) + await pickAndAnswer($, p, 'fable') + expect(localOf(p.w)).toEqual({ model: FABLE }) + expect(p.logs.join('\n')).toContain(`${FABLE} written to`) + expect(p.ran).toEqual([]) + expect((await stepOn($, p.rig, OPUS)).model).toBe(FABLE) +}) + +test('picker: This conversation routes only, writes nothing', async ( + $, on) => { + const p = await bootPicker($, on, ['This conversation']) + await pickAndAnswer($, p, 'fable') + expect(p.w.written).toEqual([]) + expect(p.logs.join('\n')).toContain('for this conversation') + expect(p.ran).toEqual([]) + expect((await stepOn($, p.rig, OPUS)).model).toBe(FABLE) +}) + +test('picker: Everywhere drops a hand pick, runs native once', async ( + $, on) => { + const p = await bootPicker($, on, ['This conversation', 'Everywhere']) + await modelCmd($, 'fable') + await pickAndAnswer($, p, 'sonnet') + expect(p.ran).toEqual(['sonnet']) + expect(p.w.asked).toHaveLength(2) + expect(p.w.written).toEqual([]) + expect(mainLine(await route($, 'show'))).toContain('session defaults') + expect(p.logs.filter(l => l.includes('native'))).toEqual([]) +}) + +test('picker: dismissed logs the no-scope text and frees the slot', async ( + $, on) => { + const p = await bootPicker($, on, []) + await pickAndAnswer($, p, 'fable') + expect(p.logs).toContain(NO_SCOPE) + expect(p.ran).toEqual([]) + expect(p.w.written).toEqual([]) + await pickAndAnswer($, p, 'fable') + expect(p.w.asked).toHaveLength(2) +}) + +test('picker: a throwing sleep is logged under its key, slot freed', async ( + $, on) => { + const logs = recordLogs(on) + const m = await bootModel($, on, ['This project'], OPUS, + { sleepFails: true }) + expect(JSON.stringify(await pick($, 'fable'))).toContain('deny') + await settle(() => logs.some(l => l.includes('PreModelSwitch picker'))) + expect(logs.join('\n')).toContain('PreModelSwitch picker failed') + expect(m.w.asked).toEqual([]) + expect(m.w.written).toEqual([]) + const again = await pick($, 'fable') + expect(JSON.stringify(again)).toContain('deny') + expect(m.toasts).toEqual([]) +}) + +test('picker: a throw after the answer is logged, native never runs', async ( + $, on) => { + const logs = recordLogs(on) + const m = await bootModel($, on, ['This conversation'], OPUS, + { clockFailsAfterAsk: true }) + await pick($, 'fable') + await settle(() => logs.some(l => l.includes('model failed ('))) + expect(logs.join('\n')).toContain('model failed (') + expect(m.ran).toEqual([]) + await pick($, 'fable') + await settle() + expect(m.w.asked).toHaveLength(2) +}) + +test('picker: a changed conversation applies nothing', async ($, on) => { + const p = await bootPicker($, on, ['This project']) + const held = deferred() + const open = deferred() + p.w.gate = held.gate + p.w.onAsk = open.release + await pick($, 'fable') + await p.rig.clock.advance(300) + await open.gate + p.w.sessionId = 's2' + held.release() + await settle(() => p.logs.length > 0) + expect(p.logs.join('\n')).toContain('conversation changed') + expect(p.w.written).toEqual([]) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('picker: a native switch passes without a second dialog', async ( + $, on) => { + const p = await bootPicker($, on, ['Everywhere']) + await pickAndAnswer($, p, 'opus') + expect(JSON.stringify(await pick($, 'opus', 'command'))).not.toContain('deny') + expect(p.w.asked).toHaveLength(1) +}) + +test('picker: a pick clears the mark of its target', async ($, on) => { + const p = await bootPicker($, on, ['This conversation']) + await route($, 'model=fable') + await stepOn($, p.rig, FABLE) + await failWith($, 'overloaded') + expect(await route($, 'show')).toContain('claude-fable-5-1 for') + await pickAndAnswer($, p, 'fable') + expect(await route($, 'show')).toContain('down: none') +}) + +test('picker: a PostModelSwitch of a denied pick keeps the hand pick', async ( + $, on) => { + const p = await bootPicker($, on, ['This conversation', 'This conversation']) + await modelCmd($, 'fable') + const held = deferred() + p.w.gate = held.gate + await pick($, 'sonnet') + await switchTo($, OPUS, SONNET, 'picker') + held.release() + await settle() + expect(mainLine(await route($, 'show'))).toContain('user custom') +}) + +// ---- hand pick: a model chosen by hand always switches -------------------- + +type HandRig = { + w: World + rig: Rig + usage: { set: (n: number) => void } + logs: string[] +} + +async function bootHand( + $: Engine, + on: On, + answers: string[], + session: string = OPUS, + tokens = 1000, + fx: Fixture = {}, +): Promise { + on('command.run', { command: 'model' }, () => ({ text: 'native' })) + const logs = recordLogs(on) + const w = newWorld({ answers, ...fx }) + const { rig, usage } = await bootRigVar($, on, session, tokens, w) + return { w, rig, usage, logs } +} + +test('hand pick: a held-down target waits across the turn boundary', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation']) + await modelCmd($, 'fable') + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) + await failWith($, 'overloaded') + await endTurn($) + expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS) + await stepOn($, h.rig, OPUS) + expect(h.logs.filter(l => l.includes('hand pick waits'))).toHaveLength(1) + await endTurn($) + await h.rig.clock.advance(15 * 60000) + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) +}) + +test('hand pick: the current model down leaves it for the hand pick', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation'], OPUS, 300000, + { home: { mainUpgrade: false } }) + await stepOn($, h.rig, OPUS) + await failWith($, 'overloaded') + await endTurn($) + await modelCmd($, 'fable') + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) +}) + +test('hand pick: an unranked session model does not trap it', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation'], 'claude-zz-9') + await modelCmd($, 'opus') + expect((await stepOn($, h.rig, 'claude-zz-9')).model).toBe(OPUS) +}) + +test('hand pick: over the upgrade cap and with the switch off still moves', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation'], OPUS, 300000, + { home: { mainUpgrade: false } }) + await modelCmd($, 'fable') + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) + await endTurn($) + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) +}) + +test('hand pick: over the downgrade cap with switch off still moves', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation'], FABLE, 300000) + await route($, 'switch off') + await modelCmd($, 'sonnet') + expect((await stepOn($, h.rig, FABLE)).model).toBe(SONNET) +}) + +test('hand pick: a typed /route model= keeps the caps', async ($, on) => { + const h = await bootHand($, on, [], OPUS, 300000) + await route($, 'model=fable') + expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS) +}) + +test('hand pick: the current model pinned and down falls to the next', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation']) + await modelCmd($, 'opus') + expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS) + await failWith($, 'overloaded') + const same = (await stepOn($, h.rig, OPUS)).model + expect(same).not.toBe(OPUS) + await endTurn($) + expect((await stepOn($, h.rig, OPUS)).model).toBe(same) +}) + +test('hand pick: a target that fails mid-turn is left', async ($, on) => { + const h = await bootHand($, on, ['This conversation']) + await modelCmd($, 'fable') + expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE) + await failWith($, 'overloaded') + expect((await stepOn($, h.rig, OPUS)).model).not.toBe(FABLE) +}) + +test('hand pick: outgrowing a known window still returns home', async ( + $, on) => { + const h = await bootHand($, on, ['This conversation'], FABLE, 1000, + { home: { windows: { [HAIKU]: 200000 } } }) + await modelCmd($, 'haiku') + expect((await stepOn($, h.rig, FABLE)).model).toBe(HAIKU) + h.usage.set(250000) + expect((await stepOn($, h.rig, FABLE)).model).toBe(FABLE) +}) + +test('hand pick: a native user switch drops it', async ($, on) => { + const h = await bootHand($, on, ['This conversation']) + await modelCmd($, 'fable') + await switchTo($, OPUS, SONNET, 'picker') + expect((await stepOn($, h.rig, SONNET)).model).toBe(SONNET) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index c28c283..efa102d 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -50,6 +50,7 @@ type Routed = { source: Source label?: string // the skill a skill route came from, for the logs explicitEffort?: boolean // the effort was asked for, not the phase's own + explicitModel?: boolean // the model was chosen by hand in the scope dialog } type Served = { at: number; tokens: number } // ms, context tokens type Hold = { until: number; reason: string } // until: ms, Infinity = reload @@ -1377,13 +1378,12 @@ function windowReturn( } /** - * The one decision of the main loop's model, in this order: router off, a - * model the table does not rank (never touched), a model whose window the - * context outgrew (back to the session model), `cur` down (leave it, - * always), no or same wanted model, a better one (upgrade), a cheaper one - * (downgrade). Used by the step AND by every text, so they agree. + * The automatic chain, in this order: router off, a model the table does + * not rank (never touched), a model whose window the context outgrew (back + * to the session model), `cur` down (leave it, always), no or same wanted + * model, a better one (upgrade), a cheaper one (downgrade). */ -function decideMain( +function automaticCall( st: State, cur: string, wanted: string | undefined, @@ -1402,6 +1402,57 @@ function decideMain( : downgradeCall(st, cur, wanted, read) } +/** The sticky model slot holds a model chosen by hand, and it is `wanted`. */ +function handPicked( + st: State, + wanted: string | undefined, +): wanted is string { + return wanted !== undefined && st.userMain?.explicitModel === true && + mainModelSlot(st) === st.userMain +} + +/** + * A hand pick (the scope dialog) always switches: no switch flag, no cold + * read cap, ahead of every automatic rule. Undefined when it cannot run + * (held down, or the context outgrew its known window): then it waits. + */ +function handCall( + st: State, + cur: string, + wanted: string, + read: Reading, +): Call | undefined { + const usable = !st.down.has(canonical(st.cfg, wanted)) && + fits(st, wanted, read.tokens) + if (!usable) return undefined + if (aliasOf(st.cfg, wanted) === aliasOf(st.cfg, canonical(st.cfg, cur))) { + return keep(cur) + } + return moveTo(cur, wanted, 'hand pick', st.sessionModel) +} + +/** + * The one decision of the main loop's model: a hand pick when one can run, + * else the automatic chain. Used by the step AND by every text, so they + * agree. + */ +function decideMain( + st: State, + cur: string, + wanted: string | undefined, + read: Reading, +): Call { + if (st.off || !handPicked(st, wanted)) { + return automaticCall(st, cur, wanted, read) + } + const hand = handCall(st, cur, wanted, read) + if (hand !== undefined) return hand + const call = automaticCall(st, cur, undefined, read) + const once = `model-router: ${canonical(st.cfg, wanted)} is held down or ` + + 'does not fit; hand pick waits' + return { ...call, once: call.once ?? once } +} + /** * The slot that names main's model: sticky, turn route, then run slot. A * floor names no model (prompt rules set the effort only). @@ -2073,6 +2124,8 @@ async function handleCommand($: Api, st: State, args: string): Promise { // settings.local.json. Fail-open to native only before an answer. type ModelNext = Next<'command.run'> +type PreSwitchNext = Next<'classic.PreModelSwitch'> +type PreSwitchIn = Parameters[0] type Local = { data: Rec; created: boolean } type Unreadable = { cause: string } @@ -2099,6 +2152,7 @@ function stickyModel($: Api, st: State, bare: string): void { phase: 'custom', route: { model: bare, ...(effort === undefined ? {} : { effort }) }, source: 'user', + explicitModel: true, ...(prev?.explicitEffort ? { explicitEffort: true } : {}), } st.runMain = null @@ -2108,10 +2162,11 @@ function stickyModel($: Api, st: State, bare: string): void { /** Everywhere: a sticky model or tier would route main back after native. */ function dropStickyModel(st: State): void { if (st.userMain === null) return - const effort = st.userMain.route.effort + const { explicitModel: _hand, ...rest } = st.userMain + const effort = rest.route.effort st.userMain = effort === undefined ? null - : { ...st.userMain, phase: 'custom', route: { effort } } + : { ...rest, phase: 'custom', route: { effort } } } async function localPath($: Api): Promise { @@ -2238,6 +2293,7 @@ async function applyLocalScope( const id = fullId(st.cfg, token) const wrote = toFile ? await writeLocalModel($, id) : undefined const bare = token.replace(ONE_M, '') + clearBreaker(st, canonical(st.cfg, bare)) // a hand pick, like a native one stickyModel($, st, bare) if (wrote !== undefined && wrote !== 'written' && wrote !== 'created') { $.ui.toast(`settings.local.json not written: ${wrote}`) @@ -2250,24 +2306,39 @@ async function applyLocalScope( return `${head}${note}\n${await show($, st)}` } -/** After an answer native never runs on a failure: a text says what to do. */ -async function answerScope( +/** How a dialog entry reaches native, names its failures, checks it. */ +type ScopeVia = { + everywhere: () => Promise // the native switch + warnKey: string // the fail-open log key of this entry + stillHere?: () => Promise // false: the dialog's moment is gone +} + +/** + * The scope question and its answer, for both entries. Before an answer a + * failure fails open (the caller's `.catch`); after one native never runs + * on a failure: a text says what to do. + */ +async function scopeDialog( $: Api, st: State, - e: CommandRunInput, - next: ModelNext, - answer: string, + token: string, + via: ScopeVia, ): Promise { + const question = await scopeQuestion($, fullId(st.cfg, token)) + const answer = await askOr($, question, MODEL_SCOPES) + if (!MODEL_SCOPES.includes(answer)) return { text: NO_SCOPE } try { + if (via.stillHere !== undefined && !(await via.stillHere())) { + return { text: 'model: the conversation changed, nothing applied' } + } if (answer === EVERYWHERE) { dropStickyModel(st) - return await next(e) + return await via.everywhere() } - const text = await applyLocalScope( - $, st, e.args.trim(), answer === PROJECT_SCOPE) - return { text } + return { text: await applyLocalScope( + $, st, token, answer === PROJECT_SCOPE) } } catch (err) { - warnOnce(st, $, 'command.run model', errWord(err)) + warnOnce(st, $, via.warnKey, errWord(err)) return { text: `model failed (${errWord(err)}); the file write or the ` + `sticky route may have landed: check /route show and ${LOCAL_SETTINGS}` } } @@ -2289,15 +2360,73 @@ async function handleModelCommand( } st.asking = `model:${token}` try { - const question = await scopeQuestion($, fullId(st.cfg, token)) - const answer = await askOr($, question, MODEL_SCOPES) - if (!MODEL_SCOPES.includes(answer)) return { text: NO_SCOPE } - return await answerScope($, st, e, next, answer) + return await scopeDialog($, st, token, + { everywhere: () => next(e), warnKey: 'command.run model' }) } finally { st.asking = null } } +// The /model picker: the engine draws nothing while a PreModelSwitch hook +// runs, so the switch is denied at once and the question comes after the +// hook returned. Everywhere then runs the native command (its own hooks +// pass through); the two local scopes never reach native. + +const PICKER_DELAY_MS = 300 +const PICKER_DENY = 'model-router asks where this switch applies' +const PICKER_BUSY = 'answer the open dialog first' + +const pickerDeny = { + permissionDecision: 'deny' as const, + permissionDecisionReason: PICKER_DENY, +} + +/** The question after the deny; always frees the slot, never throws. */ +async function pickerDialog( + $: Api, + st: State, + asked: string, + conv: string, +): Promise { + try { + await $.clock.sleep(PICKER_DELAY_MS) + const out = await scopeDialog($, st, asked, { + everywhere: () => $.command.run({ command: 'model', args: asked }) + .then(() => ({})), + warnKey: 'PreModelSwitch picker', + stillHere: async () => (await $.session.id()) === conv, + }) + if (out.text !== undefined) tryLog($, out.text) + } catch (err) { + warnOnce(st, $, 'PreModelSwitch picker', errWord(err)) + } finally { + st.asking = null + } +} + +async function handlePicker( + $: Api, + st: State, + e: PreSwitchIn, + next: PreSwitchNext, +) { + if (e.source !== 'picker') return next(e) + await ensureConfig($, st) + const asked = e.requested_model + if (st.off || typeof asked !== 'string' || !knownModel(st.cfg, asked) || + (await $.session.surfaces()).length === 0) { + return next(e) + } + const conv = await $.session.id() + if (st.asking !== null) { + $.ui.toast(PICKER_BUSY) + return pickerDeny + } + st.asking = `picker:${asked}` + void pickerDialog($, st, asked, conv) + return pickerDeny +} + // ---- first use: one dialog per row, the answer kept in routing.json ----- // The first time a row routes (a typed skill, an agent spawn, a phase // declared through the route tool) the user confirms it once, for every @@ -3608,6 +3737,7 @@ function modelCause(st: State, why: Why): string | undefined { if (call.why === 'upgrade') return 'upgrade' if (call.why === 'downgrade') return 'switch' if (call.why === 'window') return 'window' + if (call.why === 'hand pick') return 'hand pick' return `fallback: ${nameOf(st.cfg, cur)} down` } @@ -3923,6 +4053,12 @@ async function onAutoSwitch($: Api, st: State, e: SwitchIn): Promise { markDown($, st, target, 'engine fallback', await $.clock.now()) } +/** A native user switch on main ends a hand pick, the picker's own aside. */ +const handPickEnds = (st: State, e: SwitchIn): boolean => + USER_SWITCH.has(e.source) && e.agent_id === undefined && + st.userMain?.explicitModel === true && + st.asking?.startsWith('picker:') !== true + /** * Any model change: keeps `sessionModel` and the cache TTL (main's own * switches only); a user choice clears its mark. @@ -3933,6 +4069,7 @@ async function onModelSwitch($: Api, st: State, e: SwitchIn): Promise { st.cacheTtlMs = ttlOf(e.cache_ttl) ?? st.cacheTtlMs } if (USER_SWITCH.has(e.source)) st.runMain = null + if (handPickEnds(st, e)) dropStickyModel(st) if (st.off || e.source === 'resume') return if (e.source === 'auto') await onAutoSwitch($, st, e) else clearBreaker(st, canonical(st.cfg, e.to_model)) @@ -4006,6 +4143,12 @@ function registerCommandHook(on: On, st: State): void { warnOnce(st, $, 'command.run model', next.error.kind) return next(e) }) + on('classic.PreModelSwitch', async ($, e, next) => + handlePicker($, st, e, next) + ).catch(($, e, next) => { + warnOnce(st, $, 'PreModelSwitch', next.error.kind) + return next(e) + }) on('command.run', { command: 'route' }, async ($, e) => { if (e.origin.kind !== 'composer') { return { text: 'route: user-only command' }