@alexeiled/claude-router 1.10.3 → 1.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "router",
3
3
  "displayName": "Router",
4
- "version": "1.10.3",
4
+ "version": "1.10.5",
5
5
  "description": "Model and effort routing for the main conversation by task difficulty and activity, advised by a prompt classifier (Jev, Clef, Clef Flash, OpenAI or local Ollama). Subagents get one model at spawn: every agent that does not pin one.",
6
6
  "author": {
7
7
  "name": "Alexei Ledenev",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.5 (2026-10-11)
4
+
5
+ The route now follows the task while it runs, for the tier and the activity, in both directions. Before, a turn was
6
+ routed once, from its prompt, and a continuation prompt could only keep the route. A team worker whose `/goal` brief
7
+ read as `ops` ran on Haiku · high and kept it for 100+ requests of coding. See
8
+ [Changes during a task](docs/user-guide.md#changes-during-a-task).
9
+
10
+ ### Added
11
+
12
+ - A turn whose own tool calls edit a code file moves at once to the tier's `code` route (`docs` for doc-only edits), shown as `↗ coding` with a toast. The tools are the evidence, so no classifier support is needed and the cache cost does not hold the move back; only the cash cap on a credits-billed model can, priced at the route the context fits. It only goes up and skips pinned turns and `activityRouting: off`.
13
+ - Classifier reviews inside a turn: every `policy.reviewEveryRequests` requests (default 4; `0` turns them off) the classifier is asked again in the background, with the turn's prompt and recent dialogue. A step never waits; the answer applies at the next step and can move the tier or the activity either way. Each review sends the classifier the same kind of text a new turn does.
14
+ - `policy.minDwellRequests` (default 8) and a checkpoint for cheaper routes on the running task: a downgrade or a cheaper activity waits for that many requests after the last model change and for the last test, build, lint or type-check command since then to pass. Until then the route stays: a tier shows `… down after a passed check` (reason `downgrade-held`), a held activity keeps the running one. A check is a test runner, type checker or linter, or a launcher running one (`npm test`, `go test`, `make lint`), alone or after `&&`; a piped check (`npm test | tail`), `;`, `|| true`, package names and paths do not count. A cheaper activity also needs `policy.downgradeMass` probability.
15
+
16
+ ### Changed
17
+
18
+ - A downgrade lands on the cheapest tier the answer supports as a whole, not only on the chosen tier. A split answer (micro 0.63, low 0.3) on `high` now moves to `low` instead of staying until `micro` alone reaches 0.9, and a cold candidate can give way to a warm tier between it and the incumbent.
19
+ - A prompt the classifier scores as a continuation of the task no longer keeps the route by itself. It is decided like a review: up on the usual votes, down past the checkpoint. The `continuation` reason is gone. `policy.continuationMass` now only decides whether a prompt counts as the running task.
20
+
21
+ ### Fixed
22
+
23
+ - Replies after an in-turn move are labelled with the activity they ran on, not the turn's first label; the classifier's answer stays as recorded for the stats.
24
+
25
+ The review interval, the dwell and the checkpoint are starting values, not tuned on data.
26
+
3
27
  ## 1.10.3 (2026-10-11)
4
28
 
5
29
  ### Fixed
package/README.md CHANGED
@@ -9,7 +9,7 @@ The Mod changes only the model and effort in Claude Code's turn hook. Claude Cod
9
9
 
10
10
  ## Supported classifiers
11
11
 
12
- The active classifier is asked once per logical turn, for the tier and for the turn's activity. Pick one on the pane's **Classifier** tab or in `router.json`; only the active one receives prompt text. With subagent routing `on` (the default), it is also asked once per routed subagent, with the task's description and prompt; set `"subagentRouting": "off"` to keep that text local.
12
+ The active classifier is asked at the start of each logical turn, for the tier and for the turn's activity, and again in the background every 4 requests while the turn runs (`policy.reviewEveryRequests`). Pick one on the pane's **Classifier** tab or in `router.json`; only the active one receives prompt text. With subagent routing `on` (the default), it is also asked once per routed subagent, with the task's description and prompt; set `"subagentRouting": "off"` to keep that text local.
13
13
 
14
14
  | Classifier | Service | Credential | Prompt text goes to | How it is asked for the activity |
15
15
  | ---------- | ------------------------------------------ | ----------------------------------- | ------------------------- | --------------------------------------------------------------------- |
@@ -54,7 +54,7 @@ sequenceDiagram
54
54
  Mod-->>Dev: Status band and router pane
55
55
  ```
56
56
 
57
- The active classifier labels a new logical turn once. Tool continuations keep that choice. A local policy applies vote, context, failure, and cache-cost rules before the Mod changes the next step. Claude Code owns request construction, model credentials, tools, streaming, and the API cost ledger.
57
+ The active classifier labels each new logical turn, and the router checks the route again while the task runs: a turn labelled `ops` that edits code moves up to the `code` route at once, and a background classifier review every 4 requests can move the tier or the activity either way. A cheaper route on the same task waits for a dwell and a passed test, build or lint run. See [Changes during a task](docs/user-guide.md#changes-during-a-task). A local policy applies vote, context, failure, and cache-cost rules before the Mod changes the next step. Claude Code owns request construction, model credentials, tools, streaming, and the API cost ledger.
58
58
 
59
59
  | Tier | Default model | Effort |
60
60
  | -------- | ------------- | -------- |
@@ -32,6 +32,13 @@ The router compares routes, not labels. If the new activity resolves to the rout
32
32
  A move to a cheaper route must pay back its cache write first. A move to a stronger route needs the classifier's
33
33
  support. The [user guide](user-guide.md#route-by-activity) has the full rules.
34
34
 
35
+ The label comes from the prompt, so it can be wrong. A prompt such as "run the worker brief" reads as `ops` and the
36
+ turn may then spend 80 requests writing code. The router therefore also watches the turn's own tool calls. Once the
37
+ turn edits a file, it moves to the `code` route of its tier (or `docs` for doc files) if that route is stronger. This
38
+ move only goes up. The cache cost does not hold it back; only the cash cap on a credits-billed model can. A later
39
+ classifier review in the same turn can move it down again, past the checks in
40
+ [Changes during a task](user-guide.md#changes-during-a-task). The next turn starts from the route the turn ended on.
41
+
35
42
  ## The default matrix
36
43
 
37
44
  A `·` cell uses the base route.
@@ -51,7 +58,7 @@ Why each row:
51
58
  scores well above Haiku on coding tests. Sonnet at `medium` does not, so it is not used.
52
59
  - **`ops` at `medium`: Haiku · high.** Command runs last many requests, so Haiku pays back its cache write. Haiku is
53
60
  weaker on multi-step tool work, so `ops` at `high` stays on Opus. Repeated tool errors move an `ops` turn to the
54
- `high` route, Opus · xhigh.
61
+ `high` route, Opus · xhigh. An `ops` turn that starts editing code moves to Opus · medium.
55
62
  - **`explore` and `docs`.** Moving them saved nothing in the replay. Haiku also scores lower on research
56
63
  benchmarks: 50.1% on Humanity's Last Exam with tools against 63.0% for Opus at `medium`. They keep the base routes.
57
64
 
@@ -163,7 +170,9 @@ model** in the pane, which writes that for you. The cell keeps that route if you
163
170
  again then:
164
171
 
165
172
  ```json
166
- { "activities": { "ops": { "medium": { "model": "opus", "effort": "medium" } } } }
173
+ {
174
+ "activities": { "ops": { "medium": { "model": "opus", "effort": "medium" } } }
175
+ }
167
176
  ```
168
177
 
169
178
  Two other directions, with what they trade:
@@ -187,8 +196,8 @@ Two other directions, with what they trade:
187
196
  ```
188
197
 
189
198
  **Activity threshold.** An activity applies only when the classifier gives it at least this probability. Below it, a
190
- new task goes back to the base route if that move passes the usual checks, and a continuation of the running task
191
- keeps its activity, or moves to the classifier's activity when that route is stronger. The default is 60% (`policy.activityMass: 0.6`). Change it on the Policy tab under **Activities**,
199
+ new task goes back to the base route if that move passes the usual checks; the running task follows
200
+ [Changes during a task](user-guide.md#changes-during-a-task). The default is 60% (`policy.activityMass: 0.6`). Change it on the Policy tab under **Activities**,
192
201
  or in `router.json`. There is no data to tune it on yet: the probe results record whether the
193
202
  label was right, not the classifier's probabilities.
194
203
 
@@ -72,11 +72,11 @@ Node.js is not part of routing. It is used for development, the optional configu
72
72
 
73
73
  ## Decision and context
74
74
 
75
- One logical turn gets one classification. Tool continuations reuse the decision and add no votes. Before each step, the controller checks whether the selected model still fits after new tool output.
75
+ A logical turn is classified at its first step, and again every `reviewEveryRequests` requests in the background (see Review inside a turn below). Other tool continuations reuse the decision and add no votes. Before each step, the controller checks whether the selected model still fits after new tool output.
76
76
 
77
77
  Repeated tool-error escalation needs matching non-empty error output and an intervening edit attempt within a 40-message lookback. A bounded fingerprint covers the full output, not only the runner header. It removes ANSI colors, normalizes line endings, and normalizes source positions in stack frames and TAP `location` fields. TAP durations and Jest `✕ ... (N ms)` timings are also normalized. Other test names, case, whitespace, and numeric error values are kept. Unrecognized runner noise remains part of the signature: changed output can miss a repeat rather than trigger a false escalation.
78
78
 
79
- An upgrade or downgrade needs a streak of supporting votes (`upgradeVotes`, `downgradeVotes`), because staying keeps a warm cache. Before the first measured reply of a history (session start, clear, rewind, committed compaction), no cache from it exists yet, so one vote is enough. The mass bars, the cash gate, escalation, holds and continuations apply as usual.
79
+ An upgrade or downgrade needs a streak of supporting votes (`upgradeVotes`, `downgradeVotes`), because staying keeps a warm cache. A downgrade lands on the cheapest tier from the choice up to just below the incumbent whose mass at or below it, with its streak, clears that tier's bar: a split answer (micro 0.63, low 0.3) on `high` moves to `low` rather than waiting for `micro` alone, and a cold candidate can give way to a warm one in between, such as the same model at a lower effort. Before the first measured reply of a history (session start, clear, rewind, committed compaction), no cache from it exists yet, so one vote is enough. The mass bars, the cash gate, escalation and holds apply as usual. On the same task (`sameTaskOf`: a review inside a turn, or a prompt with advice `continuation` at or above `continuationMass`) an upgrade proceeds as usual, but a downgrade that has its votes stays as `downgrade-held` until `facts.downAllowed`: at least `minDwellRequests` requests since the last model change (`loop.switchedAt`), and the last verification command since then (`verifiedSince`: a Bash test, build, lint or type-check run) passed.
80
80
 
81
81
  A move to a smaller context window needs a main-response measurement from the current history and Claude's local context estimate. The router uses the larger available reading and reserves 20% of the model window. If it cannot establish fit, it keeps the current model with `context-unknown`. It does not infer token count from character count.
82
82
 
@@ -84,16 +84,20 @@ An explicit context-window failure marks that model ineligible until the next hi
84
84
 
85
85
  ## Activity routing
86
86
 
87
- The router decides on a *cell*: a tier and an activity. The route is `{ ...routes[tier], ...activities[activity][tier] }`; the (model, effort) pair, not the label, is what Claude Code receives and what owns a cache. Two cells that resolve to the same route never switch.
87
+ The router decides on a _cell_: a tier and an activity. The route is `{ ...routes[tier], ...activities[activity][tier] }`; the (model, effort) pair, not the label, is what Claude Code receives and what owns a cache. Two cells that resolve to the same route never switch.
88
88
 
89
- `chooseRoute` runs one decision per logical turn:
89
+ `chooseRoute` decides at a turn's first step, and again on each review answered inside the turn:
90
90
 
91
91
  1. **Pin.** A pinned tier wins, with no activity: the pin's tier route.
92
- 2. **Activity.** Only in `on`; `off` uses none, and ignores the activity a turn in `on` ran with before the mode changed. With no advice, or advice without an activity answer, the incumbent's activity stays. On a new prompt the classifier scores as a continuation of the task (advice `continuation` at or above `continuationMass`; Ollama gives none), the advice's activity applies only if its route at the incumbent tier is stronger than the running route, so a task can move from `explore` up to `code` but a weaker label never takes over. Tool continuations inside a turn do not reclassify: they keep the turn's route and activity. Otherwise the activity with probability at least `activityMass` applies; below that, or for `uncertain`, there is none and the tier's base route is used.
92
+ 2. **Activity.** Only in `on`; `off` uses none, and ignores the activity a turn in `on` ran with before the mode changed. With no advice, or advice without an activity answer, the incumbent's activity stays. On the same task (`sameTaskOf`; Ollama gives no continuation answer, so only reviews count for it) a label whose route at the incumbent tier is stronger applies at once, and a weaker one only with at least `downgradeMass` probability once `facts.downAllowed` holds; an unclear label keeps the running activity. Otherwise the activity with probability at least `activityMass` applies; below that, or for `uncertain`, there is none and the tier's base route is used.
93
93
  3. **Tier.** The tier policy runs as before, with every candidate tier priced at its route for the activity and the incumbent at the route it runs. Repeated tool errors move to the lowest tier above whose route is stronger than the running one, or sends a request that cannot be ordered against it. With no activity that is one tier up, as in 1.5. If no tier above helps, nothing escalates and the failure signature is kept.
94
94
  4. **Lateral move.** If the tier stays and the route would change, `lateralMove` decides. Routes order by configured output price, then effort; a session effort counts as the effort Claude Code sends. Two routes that send the same request do not switch. A pair that cannot be ordered (an unpriced model, a numeric effort, two models at one price) counts as a move up, so the base route is always reachable. A stronger route needs the activity's probability to clear the upgrade bar for its switching tax (a base route with no activity counts as probability 1). A cheaper route needs its downgrade tax to be paid back within `downgradeHorizonTurns`, except before the first measured reply of a history, when there is no cache to protect. The cash gate applies to both. The result is `activity-up`, `activity-down`, `activity-pending` (stay on the running route and its activity), `cash-gate`, or `hold`. While an escalation hold lasts, only a stronger route may be taken. One vote is enough: an activity is a fact about the turn, not a noisy estimate. If the tier changes, the tier gates have already priced the new route, and no lateral rule applies.
95
95
  5. **Fit.** Context fit and model availability resolve through `route(tier, activity)`. A fallback tries the last cell, the native model's cell, then each tier with the activity. The last and the native cell count only when they carry no activity or the turn's; otherwise, or when nothing fits, the native model runs at the session effort.
96
96
 
97
+ **Observed move.** On each later step of the turn, `observedMove` reads the turn's tool calls since its prompt, or since the transcript snapshot of the last review applied inside the turn (`loop.observedFrom`), since the review already judged the earlier ones, (`observedActivity`: `code` after an edit to a non-doc file, `docs` after edits to doc files only, else `ops`, `read` or `talk`). When that activity's route at the decision's tier is stronger than the running one, the remaining steps take it, with reason `activity-up` and `lastActivity` set, so the next turn starts there. The tier is fitted to the context first, so the gates price the route that will run. It goes through `lateralMove` with probability 1: the tools are the evidence, so the switching tax never holds it back (the upgrade bar tops out near 0.9), and only the cash gate can. The turn's reply label (`turnActivities.label`) follows the move; the classifier's answer stays as recorded. It never moves down, and skips pinned turns and `off`. `canMoveUp` skips the transcript read when no activity's route at the tier is stronger, so a step on the strongest route costs nothing. A move to a smaller window waits for a measured context, as in `routeTurn`. Context fit and model availability then apply as for any continuation.
98
+
99
+ **Review inside a turn.** Every `reviewEveryRequests` requests after the last classifier answer (`loop.reviewedAt`, counted in `loop.requests`), `reviewMidTurn` reads the transcript and asks the active classifier in the background, with the turn's prompt and recent dialogue and `facts.midTurn` set. The step does not wait. The first step after the answer arrives runs `chooseRoute` on it, before the observed move, with only the advice taken from the review: the checkpoint, context and cache facts are read at that step. Tier and activity move by the same rules as a continuation prompt: up on votes, down only past `downAllowed`. A pinned turn, a failed read or ask, an answer without advice, and an answer about a replaced history (another `generation`) change nothing; turn completion and session end abort a review in flight. `observeResponse` counts each request and records the request and message count at which the served (model, effort) last changed (`switchedAt`), which the dwell and the verification window start from. A failed transcript read keeps the running route. A verification is a Bash command whose status is the check's: a checker (`pytest`, `tsc`, `eslint`, …) or a launcher whose subcommand names a check (`npm test`, `npm run lint`, `go test`, `make lint`, `uv run pytest`), alone or in an `&&` list. A pipeline, `;`, `||` or background job does not count, since its status can hide a failed check; neither do a `--version` or `--help` run, an option before the subcommand (`npm --prefix test install`), package names, paths and file names, nor a command Claude Code sent to the background, by request or after a timeout. The first response a loop serves also sets `switchedAt`, so checks from before the router chose a route do not count. When compaction or a rewind shortens the history, `prepareLoop` moves `switchedAt.messageCount` and `observedFrom` back to its end and keeps the request-based dwell.
100
+
97
101
  At session start the incumbent is the session's model. `cellForModel` looks for it in the base routes, baseline first, and only with `activityRouting: on` in the activity overrides too, so a session that starts on an override route keeps its cell until the classifier says otherwise. The start mode uses the same lookup: with `on`, a start model that only an override uses (Sonnet 5.5 on the defaults) starts with routing on.
98
102
 
99
103
  ## State and controls
@@ -70,7 +70,7 @@ The classifier also names the activity of a turn: what the turn produces. `activ
70
70
 
71
71
  A `router.json` that still sets `"shadow"`, a mode removed in 1.10.1, is read as not setting it: the default, `on`, runs, and the next save from the pane drops the value.
72
72
 
73
- The seven activities are `code`, `debug`, `explore`, `plan`, `review`, `ops`, and `docs`. The classifier may also answer `uncertain`. In `on`, an activity applies only when its probability is at least `policy.activityMass`. Below that, or on `uncertain`, a new task goes back to its base route if the move passes the cache checks; a continuation of the running task keeps its activity, or moves to the classifier's activity when that route is stronger. When the classifier gives no usable activity answer, the running activity stays and the tier answer still applies. When it gives no answer at all, the running route stays. In `off`, the base route runs.
73
+ The seven activities are `code`, `debug`, `explore`, `plan`, `review`, `ops`, and `docs`. The classifier may also answer `uncertain`. In `on`, an activity applies only when its probability is at least `policy.activityMass`. Below that, or on `uncertain`, a new task goes back to its base route if the move passes the cache checks. On the running task the activity can move either way during the turn; see [Changes during a task](user-guide.md#changes-during-a-task). When the classifier gives no usable activity answer, the running activity stays and the tier answer still applies. When it gives no answer at all, the running route stays. In `off`, the base route runs.
74
74
 
75
75
  `activities` maps an activity to a tier to a route override. An override may set `model`, `effort`, or both. A field it leaves out comes from the built-in override for that cell, or from the tier's own route, the **base route**, where there is none:
76
76
 
@@ -267,14 +267,16 @@ Policy defaults:
267
267
  | `upgradePivotUsd` | `0.5` | Cost scale used by the upgrade bar. Must be positive. |
268
268
  | `jumpConfidence` | `0.95` | Support for a two-tier jump without waiting for votes. |
269
269
  | `downgradeVotes` | `2` | Consecutive supporting votes before a downgrade; one before a history's first measured reply. |
270
- | `downgradeMass` | `0.9` | Minimum probability mass required for a downgrade. |
270
+ | `downgradeMass` | `0.9` | Minimum probability mass at or below the target tier required for a downgrade. |
271
271
  | `downgradeSlope` | `0.08` | Maximum increase to the downgrade bar from estimated switching cost. |
272
272
  | `downgradePivotUsd` | `0.5` | Cost scale used by the downgrade bar. Must be positive. |
273
273
  | `downgradeHorizonTurns` | `5` | Later turns included in a downgrade payback estimate. |
274
- | `continuationMass` | `0.7` | Advice probability that keeps the current route for a continuation. |
275
- | `escalationHoldTurns` | `2` | Turns held after a repeated tool error escalates the route. |
274
+ | `continuationMass` | `0.7` | Advice probability at which a new prompt counts as the running task, not a new one. |
275
+ | `escalationHoldTurns` | `2` | Decisions held after a repeated tool error escalates the route; each turn and in-turn review counts. |
276
276
  | `cashCapUsd` | `2` | Maximum estimated cold cache write for a `credits` model. It does not cap output or session spend. |
277
277
  | `activityMass` | `0.6` | Minimum probability for the classifier's activity to apply. Not tuned on any classifier. |
278
+ | `reviewEveryRequests` | `4` | Requests between classifier reviews inside a turn; `0` turns them off. Not tuned. |
279
+ | `minDwellRequests` | `8` | Requests after a model change before a cheaper route on the same task. Not tuned. |
278
280
 
279
281
  The pane writes a subset of these settings. The **Routes** and **Policy** tabs set `routes`, `activities`, `activityRouting`, `baselineTier`, `policy.downgradeVotes`, `policy.downgradeHorizonTurns`, `policy.cashCapUsd`, and `policy.activityMass` in one save: it writes only values that differ from the defaults and removes the rest. `/router activities <mode>` writes `activityRouting` at once, with **Undo**. The **Classifier** tab sets `classifier` and the active classifier's `timeoutMs` at once. **Undo** reverts the settings the last pane write changed. Each save validates the whole file, keeps other keys, and applies from the next turn. A failed check names the setting and leaves the file unchanged. The pane refuses to write through a symlink. Model aliases and the other settings require a direct edit.
280
282
 
@@ -4,7 +4,7 @@ This guide describes the Mod shipped in the plugin. Claude Code 2.1.289 is the m
4
4
 
5
5
  ## Turn behavior
6
6
 
7
- At the first main step of a logical turn, the Mod reads recent message text and asks the active classifier (Jev, Clef, Clef Flash, OpenAI, or Ollama) for a tier, and for the turn's activity unless `activityRouting` is `off`. It applies local policy and saves the route. Tool continuations reuse that route. Before each continuation, context fit is checked again. A large tool result can move the step to a model with a larger window.
7
+ At the first main step of a logical turn, the Mod reads recent message text and asks the active classifier (Jev, Clef, Clef Flash, OpenAI, or Ollama) for a tier, and for the turn's activity unless `activityRouting` is `off`. It applies local policy and saves the route. Tool continuations reuse that route, except that a turn whose tool calls edit code moves up to the `code` route, and every `policy.reviewEveryRequests` requests a background classifier review may move it either way ([Changes during a task](user-guide.md#changes-during-a-task)). Before each continuation, context fit is checked again. A large tool result can move the step to a model with a larger window.
8
8
 
9
9
  The classifier receives the current prompt and at most six preceding user or assistant text messages. Each item is limited to 1,200 characters. It does not receive system messages, tool inputs, or tool results. Claude Code's Anthropic credentials never enter the classifier request. Jev, Clef, Clef Flash, and OpenAI receive the text on their services; Ollama receives it on this machine. [Configuration](configuration.md#classifiers) lists each host.
10
10
 
@@ -43,35 +43,35 @@ Read the first line of the picture from left to right:
43
43
  - **Switch cost**: `switch cost ≈ $0.37`, the policy's price for the switch it weighed this turn, mostly the prompt cache the other model must write. For a move to a cheaper model it is net of what that model saves over the next turns. The higher the cost, the higher the bar a stronger model must clear.
44
44
  - **ctx** and **cache hit**: context use and the share of input read from the cache on the last reply. They turn yellow at 60% context and red at 80%.
45
45
 
46
- | Band shows | Meaning |
47
- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
48
- | `Routing on · ready` | Routing is on and ready for a new turn. |
49
- | `choosing for this turn…` | The classifier and local policy are running. The spinner says `Choosing model`. |
50
- | `⏵ next turn: high ✕` | A pin is set. **✕** cancels it. |
51
- | `⚠ Jev: no API key · keeping model` | The active classifier lacks a setting. **Set up** opens the secure plugin dialog. |
52
- | `⚠ Clef: no account ID · keeping model` | Clef has its API token but no Cloudflare account ID. **Set up** opens the dialog. |
53
- | `⚠ Jev timed out · keeping model` | The classifier failed: timed out, unreachable, rejected the key, or paused. |
54
- | `○ Routing off [ Turn on ] · every turn uses …` | Routing is off: Claude's model answers every turn. **Turn on** turns it back on. The footer also shows `routing off`. |
55
- | `✕ Routing unavailable` | Nothing routes: an old Claude Code or leftover v0.8 settings. **Fix** opens the pane. |
46
+ | Band shows | Meaning |
47
+ | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
48
+ | `Routing on · ready` | Routing is on and ready for a new turn. |
49
+ | `choosing for this turn…` | The classifier and local policy are running. The spinner says `Choosing model`. |
50
+ | `⏵ next turn: high ✕` | A pin is set. **✕** cancels it. |
51
+ | `⚠ Jev: no API key · keeping model` | The active classifier lacks a setting. **Set up** opens the secure plugin dialog. |
52
+ | `⚠ Clef: no account ID · keeping model` | Clef has its API token but no Cloudflare account ID. **Set up** opens the dialog. |
53
+ | `⚠ Jev timed out · keeping model` | The classifier failed: timed out, unreachable, rejected the key, or paused. |
54
+ | `○ Routing off [ Turn on ] · every turn uses …` | Routing is off: Claude's model answers every turn. **Turn on** turns it back on. The footer also shows `routing off`. |
55
+ | `✕ Routing unavailable` | Nothing routes: an old Claude Code or leftover v0.8 settings. **Fix** opens the pane. |
56
56
  | `○ Router · subagents keep their own model` | You are viewing a subagent's transcript. Its steps are not routed; in `on` the band reads `subagent model chosen at spawn`. |
57
57
 
58
58
  The band shows one routing control at a time. While routing is on, hover over the band for a second row: pin a tier for the next turn, **Turn off** routing, or show two rows. While routing is off, **Turn on** sits on the first line next to `Routing off` and stays at any width: a narrow band drops the explanation and the model first. On a narrow band the hover row drops `routing on`, then **2 rows**, then `pin next turn`, then the pins; it keeps **Turn off**, and **1 row** when the band shows two. The hover row needs a pointer: from the keyboard, run `/router off`, or open the pane and press `f`. The two-row band adds this session against your model, the one `/model` selects now: `session saved $1.84 (22%) vs Opus 5.5 · xhigh · 64 replies · cold-cache writes +$0.47`, or `session extra $2.48 (×5.0) vs Haiku 5.5 · high · 41 replies · stronger models +$2.31` when routing cost more. The last part names the larger of the two costs behind the result, when there is one. After a `/model` change the row shows the whole session against the new model. Before the tenth routed reply it reads `session 3 replies · too early to compare`. When the row is short, the cost part drops first, then the reply count. Router remembers that choice across sessions. When Router changes the model between turns, a toast reads `Model changed: old → new · reason`. A pin does not raise one, and neither does a change of effort alone.
59
59
 
60
60
  The band steps aside while a survey needs the space.
61
61
 
62
- Tool continuations do not trigger another classification. A subagent gets at most one model, when it starts, and keeps it for every step: Haiku for exploration, Opus for clearly hard tasks, Sonnet for the rest. An agent that pins a model in its definition keeps it, unless it sets `modelRouting: auto`. The Usage tab's **SUBAGENTS** section shows what each agent type ran on and cost. See [Subagent routing](configuration.md#subagent-routing).
62
+ Inside a turn the router checks the route again as the work changes; see [Changes during a task](#changes-during-a-task). A subagent gets at most one model, when it starts, and keeps it for every step: Haiku for exploration, Opus for clearly hard tasks, Sonnet for the rest. An agent that pins a model in its definition keeps it, unless it sets `modelRouting: auto`. The Usage tab's **SUBAGENTS** section shows what each agent type ran on and cost. See [Subagent routing](configuration.md#subagent-routing).
63
63
 
64
64
  ## Open the router pane
65
65
 
66
66
  Run `/router` or select **Router** above the prompt. Without a UI surface, as in `claude -p`, `/router` prints a short status instead. The pane has five tabs. Select a tab or press its digit while the pane has focus.
67
67
 
68
- | Tab | What it answers |
69
- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
70
- | 1 Now | What runs next turn, and why: tier, model, activity, the reason with the support it weighed; classifier support per tier with **pin**; the last 30 replies. |
71
- | 2 Routes | Which model runs: one grid of tiers by activities, the activity routing mode, and an editor for the selected cell. |
72
- | 3 Policy | How readily the router changes models: the start tier, going down, going up, the activity threshold, the credits cap; the `router.json` path. |
73
- | 4 Classifier | Which classifier to ask: one row per classifier to compare, the active one's deadline, wait, health and credentials, and the counts kept across sessions. |
74
- | 5 Usage | What routing cost: routing vs your model, plan quota, this session by activity, and Claude's readings with the estimates behind **details**. |
68
+ | Tab | What it answers |
69
+ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
70
+ | 1 Now | What runs next turn, and why: tier, model, activity, the reason with the support it weighed; classifier support per tier with **pin**; the last 30 replies. |
71
+ | 2 Routes | Which model runs: one grid of tiers by activities, the activity routing mode, and an editor for the selected cell. |
72
+ | 3 Policy | How readily the router changes models: the start tier, going down, going up, the activity threshold, the credits cap; the `router.json` path. |
73
+ | 4 Classifier | Which classifier to ask: one row per classifier to compare, the active one's deadline, wait, health and credentials, and the counts kept across sessions. |
74
+ | 5 Usage | What routing cost: routing vs your model, plan quota, this session by activity, and Claude's readings with the estimates behind **details**. |
75
75
 
76
76
  The top line of every tab, `ROUTING [ ◉ on ] [ ○ off ] Jev ready · 347 ms`, shows the routing mode, switches it, and says whether the classifier is ready. Press `o` or `f` while the pane has focus. **?** shows what the estimates leave out. When routing is unavailable, the top line reads `ROUTING unavailable Claude’s model is kept` with the reason under it, and offers no on or off: see [Troubleshooting](#troubleshooting).
77
77
 
@@ -97,7 +97,7 @@ The Usage tab opens with the answer, such as `Routing saved $1.84 (22%) this ses
97
97
  | Line | What it is |
98
98
  | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
99
99
  | Routed replies | What the routed replies cost on the models that served them. |
100
- | Same tokens on your model | What the same input and output tokens cost on your model, with one cache that never switched. |
100
+ | Same tokens on your model | What the same input and output tokens cost on your model, with one cache that never switched. |
101
101
  | Difference | Routed minus yours. Green with a percentage when routing cost less; amber with `+$` when it cost more, `×N` once it is twice yours or more. |
102
102
  | cheaper models | The part from replies on models cheaper than yours. |
103
103
  | stronger than yours | The part from replies on stronger models, with how many replies ran on them. |
@@ -141,10 +141,10 @@ A mixed turn such as "fix it and commit" takes the hardest part, here `code`. Th
141
141
 
142
142
  The mode decides what happens with the label:
143
143
 
144
- | Mode | What the router does |
145
- | -------- | ---------------------------------------------------------------------------------------------------- |
146
- | `on` | The default. Applies the activity overrides. |
147
- | `off` | Does not ask the activity: the classifier is asked for the tier only. The base routes run. |
144
+ | Mode | What the router does |
145
+ | ----- | ------------------------------------------------------------------------------------------ |
146
+ | `on` | The default. Applies the activity overrides. |
147
+ | `off` | Does not ask the activity: the classifier is asked for the tier only. The base routes run. |
148
148
 
149
149
  To turn activity routing off, run `/router activities off`, or set **Activity routing** at the top of the Routes tab and press **Save**. Routing itself stays on: only the activity overrides stop. Upgrading from 1.6, which asked the activity but ran the base routes, run `/router activities off` to keep 1.6's routes. A `router.json` that still sets `"shadow"`, for activity or subagent routing, is read as not setting it, so the default, `on`, runs.
150
150
 
@@ -154,13 +154,30 @@ How the router moves inside a tier:
154
154
 
155
155
  - It compares routes, not labels. If the new activity resolves to the route already running, nothing switches.
156
156
  - A move to a stronger route needs the classifier's support, as an upgrade between tiers does. A move to a cheaper one must pay back its cache write within the payback horizon. One vote is enough for either, because the activity is a fact about this turn.
157
- - An activity applies only when the classifier gives it at least 60% probability (`policy.activityMass`). Below that, or on `uncertain`, a new task goes back to its base route if the move passes the same checks; a continuation of the running task keeps its activity, or moves to the classifier's activity when that route is stronger. Tool continuations inside a turn keep the turn's route. When the classifier sees a new prompt as a continuation of the task, the activity may only move to a stronger route: `explore` can become `code`, but not the other way. Ollama does not answer the continuation question, so this rule does not apply to it.
157
+ - An activity applies only when the classifier gives it at least 60% probability (`policy.activityMass`). Below that, or on `uncertain`, a new task goes back to its base route if the move passes the same checks. On the running task the activity can move either way while the turn runs; see [Changes during a task](#changes-during-a-task).
158
158
  - A pinned turn uses the pin's base route and shows no activity.
159
159
  - When the classifier gives no answer at all (a timeout, a failure, a pause, or a missing key), the running route stays. When it answers the tier but gives no usable activity, only the running activity stays: the tier answer still applies, so the turn can change tier and keeps its activity there. In `off` the base route always runs.
160
160
  - A fresh session starts with routing on when the session model is a tier's route. With activity routing `on`, a model that only an activity override uses also counts: Sonnet 5.5 on the defaults. In `off` it does not.
161
161
 
162
162
  The band's activity label appears only when the activity applies, so a weak or `uncertain` answer shows none. The two-row band and the **Replies** strip show the activities of recent replies.
163
163
 
164
+ ### Changes during a task
165
+
166
+ The classifier labels a turn from its prompt, and the work can change after that: a brief that reads as `ops` may turn into an hour of coding, and a hard fix may end in routine commands. The router therefore checks the route again while a task runs, for the tier and the activity, in both directions.
167
+
168
+ - **On every later step of a turn** it reads the turn's tool calls. A turn labelled `ops` or `explore` that edits a code file moves at once to the tier's `code` route (`docs` when it edits only Markdown or `docs/` files). The tools are the evidence, so this needs no classifier support, and the cache cost does not hold it back; only the cash cap on a credits-billed model can. This move only goes up. The toast and the band show it as `↗ coding`.
169
+ - **Every 4 requests inside a turn** (`policy.reviewEveryRequests`) it asks the classifier again, in the background, with the turn's prompt and the recent dialogue. A step never waits for the answer: it applies at the first step after it arrives. Each review sends the classifier the same kind of text a new turn does. `0` turns reviews off.
170
+ - **A new prompt that continues the task**, such as a task notification, a message from another agent, or "go on", is decided the same way as a review.
171
+
172
+ On the running task:
173
+
174
+ - A stronger tier takes the usual votes: two agreeing answers, or one for a clear two-tier jump. A stronger activity takes one answer whose probability clears the cache check. Repeated tool errors still escalate at once.
175
+ - A cheaper tier or activity also waits for a checkpoint: at least 8 requests since the last model change (`policy.minDwellRequests`), and the last test, build, lint or type-check command since then passed. A check is a test runner, type checker or linter (`pytest`, `tsc`, `eslint`), or a launcher running one (`npm test`, `go test`, `make lint`), alone or after `&&`. A check piped into another command (`npm test | tail`), followed by `;` or `|| true`, or sent to the background does not count, because its exit status can hide a failure or is not known yet. While none ran, or the last one failed, the route stays: for a tier the band shows `… down after a passed check`; a held activity keeps the running one and shows `= fits`. A cheaper activity also needs 90% probability (`policy.downgradeMass`).
176
+ - A cheaper tier lands where the answer as a whole points: when the classifier says `micro` 63% and `low` 30%, the turn moves to `low`, which 93% of the answer supports, instead of staying until `micro` alone reaches 90%.
177
+ - A pinned turn does not move. A new task, a prompt the classifier does not score as a continuation, is routed as a fresh turn. Ollama does not answer the continuation question, so every prompt is a new task to it; reviews inside a turn still apply.
178
+
179
+ These thresholds are starting values. They are not tuned on data yet.
180
+
164
181
  ### Read the activity on the pane
165
182
 
166
183
  - **Now**: the **Activity** line names the classifier's choice as a verb with its share, the two next-best answers, and the threshold at which an activity applies, such as `coding 84% debugging 8% · planning 5% applies at 60%+`. An `uncertain` answer is shown dim: it applies no activity. In `on`, **Why** names the cell when the activity moved the route or the route is an override, such as `coding at low runs on Sonnet 5.5 · high`, or `low runs on its base route, Haiku 5.5 · high` for a move without an activity; a refused move, a hold, or a tier change keeps its reason. **Last replies** counts the replies per activity under the strip.
@@ -179,7 +196,7 @@ On the **Classifier** tab, **ACROSS SESSIONS · since the last reset** shows the
179
196
  | `/router auto` | Resume automatic routing. |
180
197
  | `/router off` | Turn routing off and keep Claude's selected model. |
181
198
  | `/router pin <micro\|low\|medium\|high>` | Pin the next turn and its tool continuations. Routing on must already be enabled. |
182
- | `/router activities <off\|on>` | Set the [activity routing](#route-by-activity) mode. Saved to `router.json` at once; **Undo** reverts it. |
199
+ | `/router activities <off\|on>` | Set the [activity routing](#route-by-activity) mode. Saved to `router.json` at once; **Undo** reverts it. |
183
200
  | `/model <name>` | Select a model and turn routing off. Use `/router auto` to turn it back on. |
184
201
  | **Turn on** / **Turn off** on the band | The same as `/router auto` and `/router off`. |
185
202
  | **on** / **off** on the pane (`o` / `f`) | The same as `/router auto` and `/router off`. |
@@ -217,7 +234,7 @@ The **Policy** tab writes each control inside the sentence it completes, and nam
217
234
  - **Start** at a tier: the tier a session starts from when its model is no tier's model (`baselineTier`).
218
235
  - **Going down** after 1, 2, or 3 agreeing turns in a row, and only if a cache write pays back within 1, 3, 5, or 10 later turns. A new or reset history needs one vote.
219
236
  - **Going up** needs the classifier's support at 75%, raised up to 90% as the switch costs more. Read-only here; see [Configuration](configuration.md).
220
- - **Activities** apply at 50%, 60%, 70%, or 80% certainty or more. Below it a new task runs its tier's model, and a continuation keeps its activity, or moves to a stronger route the classifier names. See [Activity routing](activity-routing.md#change-a-cell).
237
+ - **Activities** apply at 50%, 60%, 70%, or 80% certainty or more. Below it a new task runs its tier's model; the running task follows [Changes during a task](#changes-during-a-task). See [Activity routing](activity-routing.md#change-a-cell).
221
238
  - **Credits** caps one cold cache write on a `credits` model at $0.50, $1, $2, or $5. With no `credits` model in `router.json`, the tab says the cap has no effect.
222
239
 
223
240
  **Reset policy to defaults** loads the built-in values; **Save** then removes your policy overrides. The current turn keeps the settings it started with. A save preserves unrelated `router.json` keys and refuses to write through a symlink. When validation fails, the pane names the setting and leaves the file unchanged. The tab ends with the `router.json` path, a **copy** button, and the [subagent routing](configuration.md#subagent-routing) mode, which is set in `router.json`.
@@ -56,6 +56,7 @@ import {
56
56
  import { clip, observedActivity, promptIndex } from '../lib/facts.mjs';
57
57
  import { renderPanel, routeDraftOf, routingChanges } from '../lib/panel.mjs';
58
58
  import {
59
+ canMoveUp,
59
60
  cellForModel,
60
61
  chooseRoute,
61
62
  continueRoute,
@@ -64,6 +65,7 @@ import {
64
65
  isNativeFallback,
65
66
  isSameModel,
66
67
  nativeFacts,
68
+ observedMove,
67
69
  observeResponse,
68
70
  prepareLoop,
69
71
  resetHistory,
@@ -178,6 +180,8 @@ function createRouter(options) {
178
180
  // Each routed turn's activity record until turn.complete adds it to the stats, and the session's open run of
179
181
  // one activity, flushed to the store when it ends.
180
182
  turnActivities: new Map(),
183
+ // Each turn's classifier review in flight or answered (reviewMidTurn): `{ controller, generation, observedUpTo, answer }`.
184
+ reviews: new Map(),
181
185
  run: null,
182
186
  // The route a cheaper activity move went to, while the turns stay on it (advanceDown); else null.
183
187
  afterDown: null,
@@ -691,6 +695,124 @@ async function decideTurn($, router, e, signal, step) {
691
695
  }
692
696
  }
693
697
 
698
+ // Facts for a step of the running turn, read from the transcript as it is now.
699
+ function stepFacts(cfg, router, loop, e, messages, context) {
700
+ return nativeFacts(cfg, loop, {
701
+ messages,
702
+ prompt: router.prompts.get(e.turnId),
703
+ effort: e.effort,
704
+ turnId: e.turnId,
705
+ contextTokens: context.tokens,
706
+ });
707
+ }
708
+
709
+ // The transcript, or null when it cannot be read: a continuation then keeps its route.
710
+ async function transcript($) {
711
+ try {
712
+ return await $.session.messages({ as: 'api' });
713
+ } catch {
714
+ return null;
715
+ }
716
+ }
717
+
718
+ // A tool continuation whose turn shows stronger work than its route was chosen for moves up once (observedMove). Only
719
+ // tool calls after the last applied review count (`loop.observedFrom`): the review judged the ones before. The
720
+ // transcript is read only when some activity's route at this tier is stronger than the running one.
721
+ async function moveOnObserved($, router, cfg, loop, e, context) {
722
+ if (!canMoveUp(cfg, loop.decision, e.effort)) return loop;
723
+ const messages = await transcript($);
724
+ if (!messages) return loop;
725
+ const facts = stepFacts(cfg, router, loop, e, messages, context);
726
+ const observed = observedActivity(messages, Math.max(promptIndex(messages), (loop.observedFrom ?? 0) - 1));
727
+ const moved = observedMove(cfg, loop, { observed, facts, contextKnown: context.known, now: Date.now() });
728
+ if (moved === loop) return loop;
729
+ $.ui.toast(switchToast(cfg, loop.decision, moved.decision, moved.decision.estimate));
730
+ // Replies from here on are labelled with the moved activity; the classifier's answer stays as recorded.
731
+ const turn = router.turnActivities.get(e.turnId);
732
+ if (turn) router.turnActivities.set(e.turnId, { ...turn, label: moved.decision.activity });
733
+ await updateView($, router, { estimate: moved.decision.estimate ?? null, comparison: null });
734
+ return moved;
735
+ }
736
+
737
+ // Inside a turn the classifier is asked again every `policy.reviewEveryRequests` requests, in the background: a step
738
+ // never waits for it. The answer applies at the first step after it arrives, as a decision on the same task
739
+ // (sameTaskOf), so the tier and the activity can move either way: up on the usual votes, down only past the dwell and a
740
+ // passed verification. Pinned turns and a native fallback are left alone; a failed read or ask changes nothing.
741
+ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, availableModels }) {
742
+ const review = router.reviews.get(e.turnId);
743
+ if (review?.answer) {
744
+ router.reviews.delete(e.turnId);
745
+ // An answer about a history that compaction or a rewind replaced is dropped.
746
+ if (!review.answer.advice || loop.decision?.pinned || review.generation !== loop.generation) return loop;
747
+ // Only the advice is from the review; the checkpoint, context and cache facts are read now.
748
+ const messages = await transcript($);
749
+ if (!messages) return loop;
750
+ const advice = review.answer.advice;
751
+ const facts = { ...stepFacts(cfg, router, loop, e, messages, context), midTurn: true };
752
+ const selected = chooseRoute(cfg, loop, {
753
+ facts,
754
+ advice,
755
+ pin: null,
756
+ nativeModel,
757
+ contextKnown: context.known,
758
+ availableModels,
759
+ now: Date.now(),
760
+ });
761
+ const previous = loop.decision;
762
+ if (previous && (previous.model !== selected.decision.model || previous.effort !== selected.decision.effort)) {
763
+ $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
764
+ const turn = router.turnActivities.get(e.turnId);
765
+ if (turn) router.turnActivities.set(e.turnId, { ...turn, label: selected.decision.activity ?? null });
766
+ }
767
+ // The pane shows the readings behind the route; a review by a classifier the pane no longer labels keeps them off.
768
+ if (cfg.classifier === router.config.classifier)
769
+ await updateView($, router, {
770
+ comparison: selected.decision.comparison,
771
+ adviceChoice: advice.choice ?? null,
772
+ probabilities: advice.probabilities ?? null,
773
+ estimate: selected.decision.estimate ?? null,
774
+ activityChoice: advice.activity?.choice ?? null,
775
+ activityProbabilities: advice.activity?.probabilities ?? null,
776
+ });
777
+ // Tool calls up to the review's snapshot were judged by it; later ones can still move the route up.
778
+ return { ...selected, observedFrom: review.observedUpTo };
779
+ }
780
+ const every = cfg.policy.reviewEveryRequests;
781
+ if (review || every === 0 || !loop.decision?.tier || loop.decision.pinned) return loop;
782
+ if ((loop.requests ?? 0) - (loop.reviewedAt ?? 0) < every) return loop;
783
+ const job = { controller: new AbortController(), generation: loop.generation, observedUpTo: 0, answer: null };
784
+ router.reviews.set(e.turnId, job);
785
+ try {
786
+ const [credentials, messages] = await Promise.all([
787
+ resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name)),
788
+ $.session.messages({ as: 'api' }),
789
+ ]);
790
+ job.observedUpTo = messages.length;
791
+ const facts = stepFacts(cfg, router, loop, e, messages, context);
792
+ clientOf(router, cfg.classifier)
793
+ .ask({
794
+ request: (url, init) => $.http.fetch(url, init),
795
+ sleep: (ms, args) => $.clock.sleep(ms, args),
796
+ config: cfg,
797
+ apiKey: credentials.apiKey,
798
+ endpoint: credentials.endpoint,
799
+ prompt: facts.prompt,
800
+ turns: facts.turns,
801
+ signal: job.controller.signal,
802
+ })
803
+ .then((answer) => {
804
+ if (router.reviews.get(e.turnId) === job) job.answer = answer;
805
+ })
806
+ .catch(() => {
807
+ if (router.reviews.get(e.turnId) === job) router.reviews.delete(e.turnId);
808
+ });
809
+ } catch {
810
+ router.reviews.delete(e.turnId);
811
+ return loop;
812
+ }
813
+ return { ...loop, reviewedAt: loop.requests ?? 0 };
814
+ }
815
+
694
816
  // A routed reply's metrics in the view, labelled with the turn's activity when its tier served it, and added to the
695
817
  // turn's activity record with its list price (`routedUsd`, null when unpriced) and, when its tier served it, its route.
696
818
  async function publishReply($, router, turnId, response, tier, route, routedUsd) {
@@ -1274,6 +1396,8 @@ async function endSession($, router) {
1274
1396
  router.turnConfigs.clear();
1275
1397
  router.turnPins.clear();
1276
1398
  router.turnActivities.clear();
1399
+ for (const review of router.reviews.values()) review.controller.abort();
1400
+ router.reviews.clear();
1277
1401
  router.turnSavings.clear();
1278
1402
  const run = router.run;
1279
1403
  router.run = null;
@@ -1438,6 +1562,9 @@ export function register(on, options) {
1438
1562
  loop = selected.loop;
1439
1563
  loopVersion = selected.version;
1440
1564
  } else {
1565
+ // A review answer applies first, so tool calls made after its snapshot can still move the route up.
1566
+ loop = await reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, availableModels });
1567
+ loop = await moveOnObserved($, router, cfg, loop, e, context);
1441
1568
  loop = continueRoute(cfg, loop, {
1442
1569
  nativeModel,
1443
1570
  contextTokens: context.tokens,
@@ -1468,6 +1595,8 @@ export function register(on, options) {
1468
1595
  }
1469
1596
  router.turnConfigs.delete(e.turnId);
1470
1597
  router.turnPins.delete(e.turnId);
1598
+ router.reviews.get(e.turnId)?.controller.abort();
1599
+ router.reviews.delete(e.turnId);
1471
1600
  router.turnControllers.get(e.turnId)?.abort();
1472
1601
  if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
1473
1602
  router.view = { ...router.view, activeTurnId: null };
package/lib/activity.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // compare, and when a route change inside one tier is worth it. Pure.
3
3
  import { ACTIVITIES, EFFORTS, resolveRoute, routeSpec } from './config.mjs';
4
4
  import { routeEffort } from './cost.mjs';
5
- import { cashGate } from './policy.mjs';
5
+ import { cashGate, sameTaskOf } from './policy.mjs';
6
6
 
7
7
  // The classifier's activity when it names one with at least `policy.activityMass`, else null: uncertain, a weak
8
8
  // label, or no answer resolve to the tier's base route.
@@ -34,18 +34,20 @@ export const sameRequest = (config, a, b, sentEffort) =>
34
34
 
35
35
  // The activity a turn runs with, given the incumbent cell `{ tier, activity }` and its resolved `route`. Without
36
36
  // advice, or without an activity answer (a skipped, failed or malformed activity step), the incumbent's activity
37
- // stays: a flaky step must not move the route every turn. A tool continuation keeps one route per task, but may move
38
- // up (explore, then code): a weaker label never takes over mid-task.
39
- export function chooseActivity(config, advice, incumbent, sentEffort) {
37
+ // stays: a flaky step must not move the route every turn. On the same task (sameTaskOf: a review inside a turn, or a
38
+ // continuation prompt) a stronger label is taken at once (explore, then code), and a weaker one only with at least
39
+ // `downgradeMass` probability once facts.downAllowed holds: the dwell has passed and a verification passed since the
40
+ // last model change. An unclear label keeps the running activity.
41
+ export function chooseActivity(config, advice, incumbent, sentEffort, facts = {}) {
40
42
  if (!advice?.activity) return incumbent.activity;
41
- if (advice.continuation >= config.policy.continuationMass) {
42
- const label = advice.activity.choice;
43
- const stronger =
44
- ACTIVITIES.includes(label) &&
45
- compareRoutes(config, resolveRoute(config, incumbent.tier, label), incumbent.route, sentEffort) > 0;
46
- return stronger ? label : incumbent.activity;
47
- }
48
- return acceptActivity(config, advice);
43
+ if (!sameTaskOf(config, advice, facts)) return acceptActivity(config, advice);
44
+ const label = advice.activity.choice;
45
+ if (!ACTIVITIES.includes(label)) return incumbent.activity;
46
+ const order = compareRoutes(config, resolveRoute(config, incumbent.tier, label), incumbent.route, sentEffort);
47
+ if (order > 0) return label;
48
+ const mass = advice.activity.probabilities?.[label] ?? 0;
49
+ if (order < 0 && facts.downAllowed && mass >= config.policy.downgradeMass) return label;
50
+ return incumbent.activity;
49
51
  }
50
52
 
51
53
  // A route change inside the incumbent's tier, `from` → `to`. Up on evidence: `mass`, the label's probability (1 for
package/lib/config.mjs CHANGED
@@ -115,6 +115,12 @@ export const DEFAULTS = {
115
115
  downgradeHorizonTurns: 5, // turns whose output and read savings offset a downgrade's cache write
116
116
  continuationMass: 0.7,
117
117
  escalationHoldTurns: 2,
118
+ // Inside a turn the classifier is asked again every this many requests, in the background; 0 turns it off. The
119
+ // answer applies at a later step, so a step never waits for it. Not tuned yet.
120
+ reviewEveryRequests: 4,
121
+ // A move to a cheaper route on the same task waits this many requests after the last model change, and for a
122
+ // verification command (tests, build, lint) that passed since then. Not tuned yet.
123
+ minDwellRequests: 8,
118
124
  // Ceiling on a cold cache write to a `credits` model. No default model bills credits, so this is
119
125
  // inert until a user adds one in router.json; a Claude Code turn starts near 100k tokens.
120
126
  cashCapUsd: 2,
@@ -529,6 +535,9 @@ function validate(config) {
529
535
  for (const field of ['upgradeVotes', 'downgradeVotes', 'downgradeHorizonTurns', 'escalationHoldTurns']) {
530
536
  if (!isNumber(p[field], 1, { integer: true })) throw new Error(`policy.${field} must be a positive integer`);
531
537
  }
538
+ for (const field of ['reviewEveryRequests', 'minDwellRequests']) {
539
+ if (!isNumber(p[field], 0, { integer: true })) throw new Error(`policy.${field} must be a non-negative integer`);
540
+ }
532
541
  // The pivot divides: tax / (tax + pivot). Zero makes a free switch NaN and silently stops that switch.
533
542
  for (const side of ['upgrade', 'downgrade']) {
534
543
  if (!isNumber(p[`${side}Slope`], 0)) throw new Error(`policy.${side}Slope must be a non-negative number`);
package/lib/display.mjs CHANGED
@@ -59,13 +59,13 @@ export const REASONS = {
59
59
  ready: 'ready for the next turn',
60
60
  'same-tier': 'the task fits the current tier',
61
61
  'no-advice': 'keeping the current model without classifier advice',
62
- continuation: 'continuing the previous task',
63
62
  uncertain: 'the classifier could not justify a change',
64
63
  upgrade: 'enough support for a stronger model',
65
64
  jump: 'clear need for a stronger model',
66
65
  downgrade: 'enough support for a cheaper model',
67
66
  'upgrade-pending': 'waiting before upgrading',
68
67
  'downgrade-pending': 'switching is not justified yet',
68
+ 'downgrade-held': 'a cheaper model waits for a passed check on this task',
69
69
  hold: 'staying after an escalation',
70
70
  escalation: 'repeated tool failures need a stronger model',
71
71
  'cash-gate': 'estimated cold cache write exceeds the cap',
@@ -129,13 +129,13 @@ export const SHORT_REASONS = {
129
129
  ready: 'ready',
130
130
  'same-tier': '= fits',
131
131
  'no-advice': '= no advice',
132
- continuation: '→ continuing',
133
132
  uncertain: '= uncertain',
134
133
  upgrade: '↑ upgrade',
135
134
  jump: '↑ jump',
136
135
  downgrade: '↓ downgrade',
137
136
  'upgrade-pending': '… waiting to go up',
138
137
  'downgrade-pending': '… waiting to go down',
138
+ 'downgrade-held': '… down after a passed check',
139
139
  hold: '= holding',
140
140
  escalation: '↑ tool errors',
141
141
  'cash-gate': '= cash cap',
@@ -202,7 +202,7 @@ function activityRouteText(config, view) {
202
202
  }
203
203
 
204
204
  // Reasons that only say the route stayed: on an override cell they leave out why it is not the tier's base route.
205
- const STAYED = ['ready', 'same-tier', 'no-advice', 'continuation', 'uncertain'];
205
+ const STAYED = ['ready', 'same-tier', 'no-advice', 'uncertain', 'downgrade-held'];
206
206
 
207
207
  // The Now tab's Why. In `on`, an activity move, or a stay on an override cell, says the cell plainly: "coding at low
208
208
  // runs on Sonnet 5.5 · high", or for a move to no activity "low runs on its base route, Haiku 5.5 · high".
package/lib/facts.mjs CHANGED
@@ -147,3 +147,85 @@ function readsOnly(command) {
147
147
  return name === 'git' ? READ_GIT.has(sub) : READ_COMMANDS.has(name);
148
148
  });
149
149
  }
150
+
151
+ // A command whose success shows that a check passed: a checker run, or a launcher whose subcommand names a check
152
+ // (`npm test`, `npm run lint`, `go test`, `make lint`, `uv run pytest`, `python -m pytest`, `node --test`), alone or in an
153
+ // `&&` list, so the command's status is the check's. A pipeline, `;`, `||` or background job can hide a failed check,
154
+ // so none of them counts. Neither do package names, paths and file names: `npm install -D vitest`, `git diff test/x.mjs`.
155
+ const CHECKERS = new Set(['pytest', 'jest', 'vitest', 'mocha', 'tsc', 'eslint', 'biome', 'ruff', 'mypy', 'pyright']);
156
+ const LAUNCHERS = new Set([
157
+ 'npm',
158
+ 'pnpm',
159
+ 'yarn',
160
+ 'bun',
161
+ 'npx',
162
+ 'bunx',
163
+ 'uv',
164
+ 'uvx',
165
+ 'poetry',
166
+ 'cargo',
167
+ 'go',
168
+ 'make',
169
+ 'just',
170
+ 'gradle',
171
+ 'gradlew',
172
+ 'mvn',
173
+ 'dotnet',
174
+ 'swift',
175
+ 'deno',
176
+ 'node',
177
+ 'python',
178
+ 'python3',
179
+ 'tox',
180
+ ]);
181
+ const RUNS = new Set(['run', 'exec', 'x', 'dlx']);
182
+ const CHECK_WORD =
183
+ /\b(?:test|tests|pytest|jest|vitest|mocha|tsc|typecheck|lint|eslint|biome|ruff|mypy|pyright|clippy|build|check|validate)\b/;
184
+
185
+ function verifies(command) {
186
+ if (typeof command !== 'string') return false;
187
+ const bare = command.replace(/'[^']*'|"[^"]*"/g, '""').replace(/\d?>\s*&\d|\d?>\s*\/dev\/null/g, '');
188
+ const steps = bare.split('&&');
189
+ if (steps.some((step) => /\|\||[;|&\n]/.test(step))) return false;
190
+ return steps.some((step) => runsCheck(step.trim().split(/\s+/)));
191
+ }
192
+
193
+ // A version or help request runs no check.
194
+ const INFO = /^(?:--version|-V|--help|-h|help|version)$/;
195
+
196
+ // An option before the subcommand may take a value (`npm --prefix test install`), so the subcommand must come first;
197
+ // `python -m` is the one option form read. Anything else unrecognised does not count.
198
+ function runsCheck(words) {
199
+ while (words.length > 1 && /^\w+=/.test(words[0])) words.shift();
200
+ const [first, ...rest] = words;
201
+ const name = first.split('/').pop();
202
+ if (rest.some((w) => INFO.test(w))) return false;
203
+ if (CHECKERS.has(name)) return true;
204
+ if (!LAUNCHERS.has(name)) return false;
205
+ if (rest.some((w) => /^--test\b/.test(w))) return true;
206
+ let args = (name === 'python' || name === 'python3') && rest[0] === '-m' ? rest.slice(1) : rest;
207
+ if (RUNS.has(args[0])) args = args.slice(1);
208
+ const sub = args[0] ?? '';
209
+ return !sub.startsWith('-') && !sub.includes('/') && !/\.\w+$/.test(sub) && CHECK_WORD.test(sub);
210
+ }
211
+
212
+ // Whether the last verification command at or after message `fromIndex` passed: the progress checkpoint a move to a
213
+ // cheaper route on the same task waits for. False when none ran since, or the last one failed (an unresolved failure),
214
+ // or it went to the background, by request or after a timeout: its result reports the launch, not the check.
215
+ export function verifiedSince(messages, fromIndex) {
216
+ let last = null;
217
+ for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
218
+ if (messages[i]?.role === 'assistant')
219
+ for (const block of blocks(messages[i].content))
220
+ if (block.type === 'tool_use' && block.name === 'Bash' && verifies(block.input?.command))
221
+ last = { id: block.id, index: i, background: block.input?.run_in_background === true };
222
+ if (!last || last.background) return false;
223
+ for (let i = last.index + 1; i < messages.length; i += 1)
224
+ for (const block of blocks(messages[i]?.content))
225
+ if (block.type === 'tool_result' && block.tool_use_id === last.id)
226
+ return !block.is_error && !BACKGROUNDED.test(textOf(blocks(block.content)));
227
+ return false;
228
+ }
229
+
230
+ // What Claude Code's Bash tool returns for a command it moved to the background.
231
+ const BACKGROUNDED = /running in background|moved to the background/i;
package/lib/policy.mjs CHANGED
@@ -2,6 +2,13 @@
2
2
  import { rank, resolveRoute, routeSpec, TIERS } from './config.mjs';
3
3
  import * as nativeCosts from './cost.mjs';
4
4
 
5
+ // Whether an answer is about the task already running: a review inside a turn (facts.midTurn), or a new prompt the
6
+ // classifier scores as a continuation. On the same task either way is open, but a cheaper route waits for
7
+ // facts.downAllowed: the dwell since the last model change and a passed verification.
8
+ export function sameTaskOf(config, advice, facts) {
9
+ return Boolean(facts.midTurn) || (advice?.continuation ?? 0) >= config.policy.continuationMass;
10
+ }
11
+
5
12
  export function initialState() {
6
13
  return { turn: 0, votes: [], holdUntilTurn: 0, escalatedSignature: null };
7
14
  }
@@ -37,7 +44,6 @@ export function decide({
37
44
  }
38
45
  if (next.turn <= next.holdUntilTurn) return stay('hold');
39
46
  if (!advice) return stay('no-advice');
40
- if (advice.continuation >= config.policy.continuationMass) return stay('continuation');
41
47
  if (advice.choice === 'uncertain') return stay('uncertain');
42
48
 
43
49
  const choice = advice.choice;
@@ -68,19 +74,33 @@ export function decide({
68
74
  return stay('upgrade-pending', estimate);
69
75
  }
70
76
 
71
- const support = massAtOrBelow(advice.probabilities, choice);
72
- const streak = trailing(next.votes, (v) => rank(v.tier) <= rank(choice));
73
- // A downgrade is not always cheaper this turn: a cold candidate next to a warm incumbent can pay a bigger cache
74
- // write than it saves. The bar rises with that cost, net of what the next turns save, the way the upgrade bar does.
75
- const tax = costs.downgradeTaxUsd(config, routeFor(choice), current, facts, now, config.policy.downgradeHorizonTurns);
76
- const threshold =
77
- config.policy.downgradeMass + config.policy.downgradeSlope * (tax / (tax + config.policy.downgradePivotUsd));
78
- const estimate = { downgradeMass: support, streak, taxUsd: tax, threshold };
79
- if (support >= threshold && streak >= downgradeVotes) {
80
- const gated = cashGate(config, routeFor(choice), facts, now, costs, routeFor);
81
- return gated.blocked ? gatedResult(gated, incumbent, next) : result(choice, 'downgrade', next, estimate);
77
+ // The move lands on the cheapest tier the answer supports as a whole: from the choice up to just below the
78
+ // incumbent, the first tier whose mass at or below it clears its bar. A split answer (micro 0.8, low 0.16) on high
79
+ // moves to low instead of waiting for micro alone to reach the bar. A pending stay reports the choice's estimate.
80
+ let pending = null;
81
+ for (const target of TIERS.filter((t) => rank(t) >= rank(choice) && rank(t) < rank(incumbent))) {
82
+ const support = massAtOrBelow(advice.probabilities, target);
83
+ const streak = trailing(next.votes, (v) => rank(v.tier) <= rank(target));
84
+ // A downgrade is not always cheaper this turn: a cold candidate next to a warm incumbent can pay a bigger cache
85
+ // write than it saves. The bar rises with that cost, net of what the next turns save, the way the upgrade bar does.
86
+ const tax = costs.downgradeTaxUsd(
87
+ config,
88
+ routeFor(target),
89
+ current,
90
+ facts,
91
+ now,
92
+ config.policy.downgradeHorizonTurns,
93
+ );
94
+ const threshold =
95
+ config.policy.downgradeMass + config.policy.downgradeSlope * (tax / (tax + config.policy.downgradePivotUsd));
96
+ const estimate = { downgradeMass: support, streak, taxUsd: tax, threshold };
97
+ pending ??= estimate;
98
+ if (support < threshold || streak < downgradeVotes) continue;
99
+ if (sameTaskOf(config, advice, facts) && !facts.downAllowed) return stay('downgrade-held', estimate);
100
+ const gated = cashGate(config, routeFor(target), facts, now, costs, routeFor);
101
+ return gated.blocked ? gatedResult(gated, incumbent, next) : result(target, 'downgrade', next, estimate);
82
102
  }
83
- return stay('downgrade-pending', estimate);
103
+ return stay('downgrade-pending', pending);
84
104
  }
85
105
 
86
106
  // Share of a model's window the next request may fill. The estimate leaves out the new prompt and tool
@@ -110,7 +130,11 @@ export function cashGate(config, route, facts, now, costs, routeFor = (tier) =>
110
130
  const cold = costs.coldWriteUsd(config, route.model, costs.nextContextTokens(facts));
111
131
  if (cold <= config.policy.cashCapUsd) return { blocked: false };
112
132
  const fallback = [...TIERS].reverse().find((t) => routeSpec(config, routeFor(t)).billing === 'plan');
113
- const estimate = { coldUsd: cold, cap: config.policy.cashCapUsd, cache: cacheOf(config, route, facts, now, costs) };
133
+ const estimate = {
134
+ coldUsd: cold,
135
+ cap: config.policy.cashCapUsd,
136
+ cache: cacheOf(config, route, facts, now, costs),
137
+ };
114
138
  return { blocked: true, fallback, estimate };
115
139
  }
116
140
 
package/lib/route.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { chooseActivity, compareRoutes, lateralMove, sameRequest } from './activity.mjs';
2
2
  import { ACTIVITIES, rank, resolveRoute, routeSpec, TIERS } from './config.mjs';
3
3
  import * as costs from './cost.mjs';
4
- import { clip, extractFacts } from './facts.mjs';
4
+ import { clip, extractFacts, verifiedSince } from './facts.mjs';
5
5
  import { CONTEXT_FILL, decide, fitTier, initialState } from './policy.mjs';
6
6
 
7
7
  // Exact observed API snapshot, not a rule that merges different dated versions.
@@ -52,6 +52,15 @@ export function emptyLoop(config, model) {
52
52
  turnId: null,
53
53
  decision: null,
54
54
  ineligible: [],
55
+ // Routed main requests so far, the one that started on the running route (`switchedAt`: requests and message
56
+ // count then), and the request count at the last classifier answer (`reviewedAt`). Dwell and reviews count these.
57
+ requests: 0,
58
+ servedRoute: null,
59
+ switchedAt: null,
60
+ reviewedAt: 0,
61
+ // The message count at the last review applied inside a turn: tool calls before it were already judged, so only
62
+ // later ones can move the route up again (observedMove).
63
+ observedFrom: 0,
55
64
  // Each configured model's simulated cache, by models key, for the routing-vs-your-model readout (compareModels in
56
65
  // savings.mjs).
57
66
  yoursBy: {},
@@ -75,15 +84,36 @@ export function resetHistory(loop) {
75
84
  }
76
85
 
77
86
  export function prepareLoop(loop, messageCount) {
78
- const next = loop.lastMessageCount !== null && messageCount < loop.lastMessageCount ? resetHistory(loop) : loop;
79
- return { ...next, lastMessageCount: messageCount };
87
+ if (loop.lastMessageCount === null || messageCount >= loop.lastMessageCount)
88
+ return { ...loop, lastMessageCount: messageCount };
89
+ // Compaction or a rewind shortened the history: message cursors past its end move to it, so checks and edits made
90
+ // from here on count. The request-based dwell is kept.
91
+ const cursor = (count) => Math.min(count ?? 0, messageCount);
92
+ return {
93
+ ...resetHistory(loop),
94
+ lastMessageCount: messageCount,
95
+ switchedAt: loop.switchedAt && { ...loop.switchedAt, messageCount: cursor(loop.switchedAt.messageCount) },
96
+ observedFrom: cursor(loop.observedFrom),
97
+ };
80
98
  }
81
99
 
82
100
  export function nativeFacts(config, loop, { messages, prompt, effort, turnId, contextTokens }) {
83
101
  const facts = extractFacts({ messages, output_config: { effort } }, loop, config.context);
84
102
  if (typeof prompt === 'string') facts.prompt = clip(prompt, config.context.maxTextChars);
103
+ // A move down on the same task waits out the dwell and for a passed verification since the last model change.
104
+ const since = loop.switchedAt ?? { requests: 0, messageCount: 0 };
105
+ const downAllowed =
106
+ (loop.requests ?? 0) - since.requests >= config.policy.minDwellRequests &&
107
+ verifiedSince(messages, since.messageCount);
85
108
  // A loop saved without the field counts as measured, keeping the vote streak.
86
- return { ...facts, pin: null, contextTokens, turnKey: turnId, historyMeasured: loop.historyMeasured !== false };
109
+ return {
110
+ ...facts,
111
+ downAllowed,
112
+ pin: null,
113
+ contextTokens,
114
+ turnKey: turnId,
115
+ historyMeasured: loop.historyMeasured !== false,
116
+ };
87
117
  }
88
118
 
89
119
  export function isModelAllowed(id, available, nativeModel) {
@@ -119,6 +149,7 @@ export function chooseRoute(config, loop, input) {
119
149
  turnId: facts.turnKey,
120
150
  decision: applied,
121
151
  suspended: false,
152
+ reviewedAt: loop.requests ?? 0,
122
153
  };
123
154
  }
124
155
 
@@ -135,7 +166,7 @@ function routeTurn(config, loop, { facts, advice, pin, nativeModel, contextKnown
135
166
  const tier0 = TIERS.includes(facts.lastRoute) ? facts.lastRoute : config.baselineTier;
136
167
  const incumbent = { tier: tier0, activity: last.activity, route: resolveRoute(config, tier0, last.activity) };
137
168
  const activity =
138
- pin || config.activityRouting !== 'on' ? null : chooseActivity(config, advice, incumbent, facts.effort);
169
+ pin || config.activityRouting !== 'on' ? null : chooseActivity(config, advice, incumbent, facts.effort, facts);
139
170
  let result =
140
171
  pin && TIERS.includes(pin)
141
172
  ? {
@@ -246,7 +277,52 @@ function decideCell({ config, projected, facts, advice, state, now, incumbent, a
246
277
  };
247
278
  }
248
279
 
249
- // A tool continuation keeps the turn's route and activity; only the context or the model list can move it.
280
+ // Whether some activity's route at the decision's tier is stronger than the one running: only then can the turn's own
281
+ // tool calls move it (observedMove), so a step on the strongest route skips reading the transcript.
282
+ export function canMoveUp(config, decision, effort) {
283
+ if (config.activityRouting !== 'on' || !decision?.tier || decision.pinned) return false;
284
+ const from = resolveRoute(config, decision.tier, decision.activity ?? null);
285
+ return ACTIVITIES.some((a) => compareRoutes(config, resolveRoute(config, decision.tier, a), from, effort) > 0);
286
+ }
287
+
288
+ // A move up inside a turn: the classifier labels a turn from its prompt, and a prompt that reads as ops or explore can
289
+ // still end up editing code. Once the turn's tool calls show an activity (observedActivity in facts.mjs) whose route at the
290
+ // tier is stronger, the remaining steps take that route. The tools are the evidence, so the move needs no classifier
291
+ // probability. At probability 1 the switching tax never holds it back (the upgrade bar tops out near 0.9): only the
292
+ // cash gate, priced at the context-fitted route, can. Only up: a move down comes from a classifier review, past its
293
+ // checks. Returns the loop, unchanged when nothing moves.
294
+ export function observedMove(config, loop, { observed, facts, contextKnown, now }) {
295
+ const decision = loop.decision;
296
+ if (!canMoveUp(config, decision, facts.effort) || !ACTIVITIES.includes(observed)) return loop;
297
+ const from = resolveRoute(config, decision.tier, decision.activity ?? null);
298
+ // The gates price the route that will run: the one the context fits, not the tier's first choice.
299
+ const routeFor = (tier) => resolveRoute(config, tier, observed);
300
+ const tier = fitTier(config, decision.tier, costs.nextContextTokens(facts), routeFor);
301
+ const to = routeFor(tier);
302
+ if (!(compareRoutes(config, to, from, facts.effort) > 0)) return loop;
303
+ // Without a reliable reading of the context, a smaller window might overflow, as in routeTurn.
304
+ const window = (route) => routeSpec(config, route).contextWindow;
305
+ if ((!contextKnown || !loop.historyMeasured) && window(to) < window(from)) return loop;
306
+ const projected = economicConfig(config, loop);
307
+ const lateral = lateralMove({ config: projected, from, to, mass: 1, hold: false, facts, now, costs });
308
+ if (!lateral.move) return loop;
309
+ return {
310
+ ...loop,
311
+ lastActivity: observed,
312
+ decision: {
313
+ ...decision,
314
+ tier,
315
+ activity: observed,
316
+ model: routeSpec(config, to).id,
317
+ effort: costs.routeEffort(config, to, facts.effort),
318
+ reason: lateral.reason,
319
+ estimate: lateral.estimate,
320
+ },
321
+ };
322
+ }
323
+
324
+ // A tool continuation keeps the turn's route and activity; only the context, the model list, or the turn's own tool
325
+ // calls (observedMove) can move it.
250
326
  export function continueRoute(config, loop, { nativeModel, contextTokens, contextKnown, availableModels, effort }) {
251
327
  if (!loop.decision) return loop;
252
328
  let decision = loop.decision;
@@ -269,7 +345,17 @@ export function continueRoute(config, loop, { nativeModel, contextTokens, contex
269
345
  }
270
346
 
271
347
  export function observeResponse(config, loop, { usage, requestedModel, effort, stopReason, now }) {
272
- let next = loop;
348
+ // Every request counts toward dwell and reviews; a request on another (model, effort) than the last starts a dwell,
349
+ // and so does the first one this loop serves: checks from before it ran on a route the router did not choose.
350
+ const served = `${requestedModel}@${effort ?? 'session'}`;
351
+ const requests = (loop.requests ?? 0) + 1;
352
+ const switched = loop.servedRoute !== served;
353
+ let next = {
354
+ ...loop,
355
+ requests,
356
+ servedRoute: served,
357
+ switchedAt: switched ? { requests, messageCount: loop.lastMessageCount ?? 0 } : (loop.switchedAt ?? null),
358
+ };
273
359
  if (stopReason === 'model_context_window_exceeded') {
274
360
  next = { ...next, ineligible: [...new Set([...next.ineligible, requestedModel])] };
275
361
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexeiled/claude-router",
3
- "version": "1.10.3",
3
+ "version": "1.10.5",
4
4
  "description": "Native Claude Code Mod: model and effort routing for the main conversation, advised by Jev, Clef, Clef Flash, OpenAI or Ollama.",
5
5
  "license": "MIT",
6
6
  "author": "Alexei Ledenev",