@alexeiled/claude-router 1.10.2 → 1.10.3

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.2",
4
+ "version": "1.10.3",
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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.3 (2026-10-11)
4
+
5
+ ### Fixed
6
+
7
+ - Activity stats kept across sessions (classifier vs tools, runs, activity moves) no longer lose counts when two sessions finish turns at the same moment, and a session that read them before **Reset stats** can no longer write them back. Each session now keeps its own `activity:stats:v1:<session id>` record, summed on read like the other counts. The single key earlier versions shared still counts until the next **Reset stats** deletes it. After running this version, 1.10.2 or earlier shows only the counts in that shared key.
8
+ - A one-turn pin is no longer lost when the turn is interrupted before its route is set, and a pin pressed again while a pinned turn chooses its model now serves the next turn.
9
+ - A subagent spawn keeps core's model when the router cannot read the settings, since they may limit the models through `availableModels`.
10
+ - An agent definition file that could not be read is read again at the next spawn of its type, instead of passing that type through for the rest of the session.
11
+ - The Now tab's **Why** line gives a sentence, not a raw key, for a turn routing did not choose, routing off, a model fallback by Claude Code, and an interrupted turn.
12
+ - The Classifier tab names the host a request actually reaches: user info before `@` in an endpoint is not shown as the host, and an endpoint on `[::1]` shows as this machine.
13
+ - `scripts/migrate-config.mjs` refuses to write through a symlink, writes the converted file beside `router.json` and renames it into place, and removes its backup after a failed write, so the next run starts clean.
14
+
3
15
  ## 1.10.2 (2026-10-11)
4
16
 
5
17
  ### Fixed
@@ -109,7 +109,7 @@ When a turn completes, the Mod labels it from the tool calls the assistant made
109
109
  Two stores hold counts:
110
110
 
111
111
  - **Session**: `activityStats` in the view, reset when the session ends. It has turns, requests, tokens, the list price of priced replies with their count, and routed replies by `model@effort` per activity, switches by tier and by activity, lateral moves taken and refused, and tool agreement. The label counted per activity is the applied activity in `on`. Tool agreement compares the answer that cleared `activityMass`, so it measures the classifier in both modes. The view also keeps an `activities` array aligned with the last 30 replies.
112
- - **Across sessions**: one `$.store` key and one record per session. `activity:stats:v1` holds a confusion matrix of the classifier's raw answer (including `uncertain` and `none`) against the observed bucket, run lengths per activity in five buckets, and lateral switches taken and refused (from the decision's `lateral` field, so a hold or the cash gate counts). A value with an unknown key or shape reads as empty; the `shadow` key that versions before 1.10.1 wrote is dropped on read and the rest is kept. 1.10.0 and earlier need that key, so they reset the store. Each session's `activity:metrics:v1:<session id>` holds a classifier latency histogram per classifier id (22 buckets, at most 8 ids), the cheaper activity moves taken in `on` with the escalations that followed one, and `since`, its first reading; each part reads as empty on its own when its shape is wrong, as after a change of buckets. Keeping them apart from the stats key lets 1.7.0, which never reads them, keep the counts across a downgrade. The metrics follow the savings records below: one writer per key, so sessions that finish turns at the same moment do not overwrite each other; this session's record held in memory and written after each turn that adds a reading; the readout the sum of all records, latency kept to the first 8 classifier ids; and the same reset marker. The stats key has a fixed key set; each metrics record is bounded, and the records grow by one per session that recorded a reading until **Reset stats**, as the savings records do. The view keeps the last values read or written as `activityStore` and `activityMetrics` (the sum): read at session start and when the pane opens, replaced after each turn's write and after a reset. The open run is written when the session ends. **Reset stats** clears the session counts, the stats key and every metrics record, and the routing-vs-your-model totals below.
112
+ - **Across sessions**: two `$.store` records per session. Each session's `activity:stats:v1:<session id>` holds a confusion matrix of the classifier's raw answer (including `uncertain` and `none`) against the observed bucket, run lengths per activity in five buckets, lateral switches taken and refused (from the decision's `lateral` field, so a hold or the cash gate counts), and `since`, its first count. A value with an unknown key or shape reads as empty; the `shadow` key that versions before 1.10.1 wrote is dropped on read and the rest is kept. Before 1.10.3 every session shared one `activity:stats:v1` key, read-modified-written each turn, so two sessions finishing turns together could lose a count and a stale write could undo a reset; that key now counts as one more record in the sum until **Reset stats** deletes it, and 1.10.2 and earlier read only it. Each session's `activity:metrics:v1:<session id>` holds a classifier latency histogram per classifier id (22 buckets, at most 8 ids), the cheaper activity moves taken in `on` with the escalations that followed one, and `since`, its first reading; each part reads as empty on its own when its shape is wrong, as after a change of buckets. Both follow the savings records below: one writer per key, so sessions that finish turns at the same moment do not overwrite each other; this session's record held in memory and written after each turn that adds a count; the readout the sum of all records, latency kept to the first 8 classifier ids; and the same reset marker. Each record is bounded, and the records grow by one per session that recorded a count until **Reset stats**, as the savings records do. The view keeps the last sums read or written as `activityStore` and `activityMetrics`: read at session start and when the pane opens, replaced after each turn's write and after a reset. The open run is written when the session ends. **Reset stats** clears the session counts, every stats and metrics record, and the routing-vs-your-model totals below.
113
113
 
114
114
  Nothing is recorded with `activityRouting: off`. Stats run inside a guard: a failed transcript read or store access loses that turn's counts and never fails the turn. Readings already in the session's metrics record stay in memory after a failed write and go out with the next turn that adds a reading. A turn from a session that has since changed is dropped.
115
115
 
@@ -125,7 +125,7 @@ A subagent's model is chosen once, in the `agent.spawn` hook, before its cache e
125
125
  - Workflow `agent()` calls raise `agent.spawn` with `e.workflow`, but a model rewrite there is ignored.
126
126
  - The hook has 10 seconds of its own time. `$` calls do not count against it, but a `$.clock.sleep` does.
127
127
 
128
- `spawnAgent` in `hooks/native-router.mjs` passes the spawn through unchanged for a fork, a workflow agent (before the explicit check, since a workflow `agent({ model })` has `e.model` set), an explicit `e.model`, or a teammate (`passReason` in `lib/subagents.mjs`). Then `typeRoute` decides. A `subagents.types` entry wins; a key without a colon matches only the engine's built-in of that name. An unlisted built-in passes (`unlisted`), since its definition is not on disk. Any other agent is routed by its definition. `agentDefinition` finds the file once per provider and type in a session. A plugin agent's `provider.plugin` is `plugin@marketplace`, the key of `<profile>/plugins/installed_plugins.json`, whose `installPath` entries hold `agents/*.md`. Other agents are looked up under the session's `.claude/agents`, then `<profile>/agents`. `agentFrontmatter` reads `name`, `model` and `modelRouting` from YAML or a one-line JSON object. No model, `inherit`, or `modelRouting: auto` is routed; any other model passes (`pinned`); a file not found, unreadable, or matches that disagree pass (`unknown`). A routed agent's type uses its models key, or for `classify` the active classifier is asked with the description and prompt alone, clipped to `context.maxTextChars`, with no history and no tool results. The answer maps to `subagents.heavy` when `P(high) ≥ heavyMass`, to `light` for an `explore` activity above `activityMass` or tier `micro`, else to `standard`. The spawn path has its own classifier client per classifier: its own failure count and pause, and no in-flight slot, so parallel spawns each get an answer and spawn failures never pause main-turn routing. Its deadline is the classifier's, capped at 3 seconds. That bounds how long a subagent waits to start. No advice, a missing key, or a model `availableModels` blocks keeps core's model. The router sends the configured full id, never an alias, because a family alias resolves to the parent's exact model when the families match. A `.catch` runs `next(e)`, so a failing hook spawns the agent as Claude Code would. Routing off (`/router off`, `/model`) or unavailable passes every spawn through and records nothing.
128
+ `spawnAgent` in `hooks/native-router.mjs` passes the spawn through unchanged for a fork, a workflow agent (before the explicit check, since a workflow `agent({ model })` has `e.model` set), an explicit `e.model`, or a teammate (`passReason` in `lib/subagents.mjs`). Then `typeRoute` decides. A `subagents.types` entry wins; a key without a colon matches only the engine's built-in of that name. An unlisted built-in passes (`unlisted`), since its definition is not on disk. Any other agent is routed by its definition. `agentDefinition` finds the file once per provider and type in a session; a read that fails is tried again at the next spawn of the type. A plugin agent's `provider.plugin` is `plugin@marketplace`, the key of `<profile>/plugins/installed_plugins.json`, whose `installPath` entries hold `agents/*.md`. Other agents are looked up under the session's `.claude/agents`, then `<profile>/agents`. `agentFrontmatter` reads `name`, `model` and `modelRouting` from YAML or a one-line JSON object. No model, `inherit`, or `modelRouting: auto` is routed; any other model passes (`pinned`); a file not found, unreadable, or matches that disagree pass (`unknown`). A routed agent's type uses its models key, or for `classify` the active classifier is asked with the description and prompt alone, clipped to `context.maxTextChars`, with no history and no tool results. The answer maps to `subagents.heavy` when `P(high) ≥ heavyMass`, to `light` for an `explore` activity above `activityMass` or tier `micro`, else to `standard`. The spawn path has its own classifier client per classifier: its own failure count and pause, and no in-flight slot, so parallel spawns each get an answer and spawn failures never pause main-turn routing. Its deadline is the classifier's, capped at 3 seconds. That bounds how long a subagent waits to start. No advice, a missing key, a model `availableModels` blocks, or settings that cannot be read keep core's model. The router sends the configured full id, never an alias, because a family alias resolves to the parent's exact model when the families match. A `.catch` runs `next(e)`, so a failing hook spawns the agent as Claude Code would. Routing off (`/router off`, `/model`) or unavailable passes every spawn through and records nothing.
129
129
 
130
130
  Every spawn in `on` gets a record keyed by `agentId`, from `next(e)`'s answer. Its replies are priced in `turn.step` (`addAgentReply`), on the model they ran on and on core's model as `coreModelOf` estimates it (the definition's own model, else `CLAUDE_CODE_SUBAGENT_MODEL` except for Explore and Plan without `CLAUDE_CODE_SUBAGENT_MODEL_FORCE`, else `parentModel`). Cache writes are priced at the subagent lifetime (`subagentCacheTtl`). The record's counts go to this session's `$.store` key `subagents:v1:<session id>` at each of the agent's `turn.complete`s, and at session end for agents still running. They are counted per type and per pass-through reason, with respawns: a spawn of the type its parent loop finished one of in the last 10 minutes. The records follow the savings records: one writer per key, the readout `subagentStore` in the view is the sum, and the same reset marker applies. **Reset stats** clears them too.
131
131
 
@@ -170,7 +170,7 @@ To check a classifier outside Claude Code, run `node scripts/probe-classifier.mj
170
170
 
171
171
  ### Ollama
172
172
 
173
- `ollama` needs no key and keeps the text on this machine. Run `ollama serve`, pull the model named in `model`, and select the classifier. `model` is any tag you have pulled, such as `qwen3.5:9b`; change it under `classifiers.ollama.model`. The endpoint must stay on `localhost`, `127.0.0.1`, or `[::1]`, so a server on another machine on your network is not reachable through this entry. Each request turns thinking off. The activity is a second request, sent after the route answer parses and only when at least 300 ms of the deadline remain; if it fails, the turn keeps the running activity and the classifier is not counted as failed. If Ollama rejects that setting for a model, the request fails and the router keeps the baseline. Ollama unloads an idle model after its keep-alive period, and the first request after that can exceed `timeoutMs` while the model loads; the router then keeps the baseline for that turn.
173
+ `ollama` needs no key and keeps the text on this machine. Run `ollama serve`, pull the model named in `model`, and select the classifier. `model` is any tag you have pulled, such as `qwen3.5:9b`; change it under `classifiers.ollama.model`. Plain `http` works only on `localhost`, `127.0.0.1`, or `[::1]`, so a server on another machine needs an `https` endpoint, and the prompt text then leaves this machine. Each request turns thinking off. The activity is a second request, sent after the route answer parses and only when at least 300 ms of the deadline remain; if it fails, the turn keeps the running activity and the classifier is not counted as failed. If Ollama rejects that setting for a model, the request fails and the router keeps the baseline. Ollama unloads an idle model after its keep-alive period, and the first request after that can exceed `timeoutMs` while the model loads; the router then keeps the baseline for that turn.
174
174
 
175
175
  ## Subagent routing
176
176
 
@@ -224,7 +224,7 @@ The values above are the defaults.
224
224
 
225
225
  - `types` overrides the rule for an agent type: a models key, `classify`, or `null` to never route it. A user file adds to the defaults. A key without a colon matches only Claude Code's built-in of that name, such as `Explore`; a project agent named `Explore` replaces the built-in and follows its own definition. A `plugin:name` key matches only that plugin's agent. A listed type is routed even if its definition pins a model.
226
226
  - `classify` asks the active classifier, once, with the task's description and prompt. It sends no history and no tool results. The task runs on `heavy` when the classifier gives `high` at least `heavyMass`. It runs on `light` for exploration (the `explore` activity above `policy.activityMass`) or the `micro` tier. Everything else runs on `standard`. Every routed agent not listed in `types` is classified. In `on` the spawn waits up to the classifier's `timeoutMs`, at most 3 seconds.
227
- - A classifier failure or a missing key keeps the model Claude Code gives the agent, and so does a model that `availableModels` blocks. So does routing off: `/router off`, or a `/model` choice.
227
+ - A classifier failure or a missing key keeps the model Claude Code gives the agent, and so does a model that `availableModels` blocks, or settings the router cannot read. So does routing off: `/router off`, or a `/model` choice.
228
228
  - A spawn sets a model, not an effort. An agent's `effort` frontmatter still applies.
229
229
 
230
230
  The Usage tab's **SUBAGENTS** section shows, per agent type, what routing cost against the model Claude Code would have used, and which agents passed through and why. [Evaluation](evaluation.md#subagent-routing) says what to look for. To stop it, set `"off"`. Router 1.8 rejects both keys as unknown, so remove `subagentRouting` and `subagents` before you downgrade. Subagent routing needs the `agent.spawn` hook: it is checked on Claude Code 2.1.293 and 2.1.296, and unverified on older builds.
@@ -306,7 +306,7 @@ node ~/.claude/plugins/cache/alexei-led-claude-router/router/1.2.0/scripts/migra
306
306
 
307
307
  Use the installed version in the path. From a checkout, run `node scripts/migrate-config.mjs ~/.claude/router.json`.
308
308
 
309
- Pass the file under your active profile instead when `CLAUDE_CONFIG_DIR` points elsewhere. The command validates the converted configuration before writing it and creates an exact-byte `router.json.v0.8.backup` for a v0.8 file, or `router.json.v1.1.backup` for a 1.1 file. It refuses to overwrite an existing backup. Route, model-price, cache, and policy overrides remain in the converted file.
309
+ Pass the file under your active profile instead when `CLAUDE_CONFIG_DIR` points elsewhere. The command validates the converted configuration before writing it and creates an exact-byte `router.json.v0.8.backup` for a v0.8 file, or `router.json.v1.1.backup` for a 1.1 file. It refuses to overwrite an existing backup and to write through a symlink; it writes the converted file beside the original and renames it into place. Route, model-price, cache, and policy overrides remain in the converted file.
310
310
 
311
311
  The converter removes old gateway and logging settings, request-feature fields, and model output caps. It moves `gateway.baselineTier` to top-level `baselineTier` and the `jev` section to `classifiers.jev`. It stops without writing when it finds an unsupported old field or invalid setting.
312
312
 
@@ -56,7 +56,7 @@ The script writes aggregate counts, reason histograms, route transitions, and sh
56
56
 
57
57
  Activity routing has no measured result. The replay above predates it and covers tiers only. It is `on` by default since 1.7, with defaults chosen from Anthropic's published benchmarks and a list-price replay of one developer's sessions; [Activity routing](activity-routing.md#what-the-estimates-mean) gives that replay and its limits. The pane counts turns, requests, switches, and the turns `on` would route differently, with a configured list-price estimate of those turns' next requests, not a measured saving. Two checks look at the classifier's activity label.
58
58
 
59
- The figures plan §11 tracks (tool agreement of at least 80% on `code` against `ops` and `explore`, Jev p95 latency of at most 450 ms, at most 1 tool-error escalation in 10 cheaper activity moves, the number of activity switches) are read from the Usage tab's **ACROSS SESSIONS** block, which shows the counts kept since the last reset: **Code/ops/explore** for the tool agreement on turns the classifier answered `code`, `ops` or `explore`, **Agreement** and **Mismatch** for all of them, **Activity moves** for moves inside a tier taken and refused (a refusal by a hold or the credits cap included), **Escalations** for the tool-error escalations that followed a cheaper activity move in `on` while the turns stayed on its route in `on` (turning routing off, a turn with routing off, or a turn in `off` ends the watch, a pin in between does not, and an escalation the credits cap held counts), **Latency** for the active classifier's p95 wait. Latency is kept in fixed buckets, so the p95 reads as a bound (`≤ 350 ms`); it is the wait for the classifier's answer, transient retries included, without the routing after it, so it compares with the probe's p95 below, and is not recorded with activity routing `off`. `/router` without a UI surface prints both agreements. The underlying counts are the `activity:stats:v1` store and the per-session `activity:metrics:v1:<session id>` records described in [Architecture](architecture.md).
59
+ The figures plan §11 tracks (tool agreement of at least 80% on `code` against `ops` and `explore`, Jev p95 latency of at most 450 ms, at most 1 tool-error escalation in 10 cheaper activity moves, the number of activity switches) are read from the Usage tab's **ACROSS SESSIONS** block, which shows the counts kept since the last reset: **Code/ops/explore** for the tool agreement on turns the classifier answered `code`, `ops` or `explore`, **Agreement** and **Mismatch** for all of them, **Activity moves** for moves inside a tier taken and refused (a refusal by a hold or the credits cap included), **Escalations** for the tool-error escalations that followed a cheaper activity move in `on` while the turns stayed on its route in `on` (turning routing off, a turn with routing off, or a turn in `off` ends the watch, a pin in between does not, and an escalation the credits cap held counts), **Latency** for the active classifier's p95 wait. Latency is kept in fixed buckets, so the p95 reads as a bound (`≤ 350 ms`); it is the wait for the classifier's answer, transient retries included, without the routing after it, so it compares with the probe's p95 below, and is not recorded with activity routing `off`. `/router` without a UI surface prints both agreements. The underlying counts are the per-session `activity:stats:v1:<session id>` and `activity:metrics:v1:<session id>` records described in [Architecture](architecture.md).
60
60
 
61
61
  ### Tool agreement
62
62
 
@@ -6,6 +6,7 @@ import {
6
6
  emptyStore,
7
7
  METRICS_PREFIX,
8
8
  mergeMetrics,
9
+ mergeStores,
9
10
  metricsAfterReset,
10
11
  readMetrics,
11
12
  readStore,
@@ -13,6 +14,8 @@ import {
13
14
  recordStore,
14
15
  recordTurn,
15
16
  STORE_KEY,
17
+ STORE_PREFIX,
18
+ storeAfterReset,
16
19
  turnActivity,
17
20
  } from '../lib/activity-stats.mjs';
18
21
  import { renderBand, switchToast } from '../lib/band.mjs';
@@ -114,6 +117,47 @@ const BAND_DETAIL = 'band:detail';
114
117
  const MODE_PREFIX = 'mode:';
115
118
  const isSet = (value) => /^(1|true|yes|on)$/i.test(String(value ?? '').trim());
116
119
 
120
+ // The counts kept across sessions: each session writes only its own record of a kind, `prefix` and its session id,
121
+ // because $.store has no atomic update; the view's `field` shows every session's record since the last reset added
122
+ // up. One marker, SAVINGS_RESET_KEY, resets them all. `legacy` is the key all sessions shared before 1.10.3: it counts
123
+ // as another session's record until a reset deletes it.
124
+ const LEDGERS = {
125
+ savings: {
126
+ prefix: SAVINGS_PREFIX,
127
+ field: 'savingsStore',
128
+ read: readSavingsStore,
129
+ afterReset,
130
+ merge: mergeSavingsStores,
131
+ empty: emptySavingsStore,
132
+ },
133
+ metrics: {
134
+ prefix: METRICS_PREFIX,
135
+ field: 'activityMetrics',
136
+ read: readMetrics,
137
+ afterReset: metricsAfterReset,
138
+ merge: mergeMetrics,
139
+ empty: emptyMetrics,
140
+ },
141
+ subagents: {
142
+ prefix: SUBAGENT_PREFIX,
143
+ field: 'subagentStore',
144
+ read: readSubagentStore,
145
+ afterReset: subagentsAfterReset,
146
+ merge: mergeSubagentStores,
147
+ empty: emptySubagentStore,
148
+ },
149
+ activity: {
150
+ prefix: STORE_PREFIX,
151
+ legacy: STORE_KEY,
152
+ field: 'activityStore',
153
+ read: readStore,
154
+ afterReset: storeAfterReset,
155
+ merge: mergeStores,
156
+ empty: emptyStore,
157
+ },
158
+ };
159
+ const LEDGER_KINDS = Object.keys(LEDGERS);
160
+
117
161
  // Everything the hooks change between events, in one object `register()` creates and passes to its helpers. Module
118
162
  // variables, not $.state: a reload starts them over, and the view is written through to $.state as it changes.
119
163
  function createRouter(options) {
@@ -141,24 +185,25 @@ function createRouter(options) {
141
185
  offSwitches: 0,
142
186
  // Each turn's routing-vs-your-model totals until turn.complete adds them to the store.
143
187
  turnSavings: new Map(),
144
- // The totals kept across sessions: this session's record (`{ sessionId, record }`), held here so a refresh never
145
- // reads it back from the store while a write of it is pending, and the sum of every other session's, read on
146
- // refresh. The view shows their sum.
147
- savingsOwn: null,
148
- savingsOthers: null,
149
- // The activity metrics kept across sessions, held the same way: this session's record and the others' sum.
150
- metricsOwn: null,
151
- metricsOthers: null,
188
+ // The counts kept across sessions, by LEDGERS kind: this session's record (`own`, `{ sessionId, record }`), held
189
+ // here so a refresh never reads it back from the store while a write of it is pending, and the sum of every other
190
+ // session's (`others`), read on refresh. The view shows their sum.
191
+ // `othersResetAt` is the reset marker the others were read under: a newer one means they are read again.
192
+ ledgers: Object.fromEntries(
193
+ Object.keys(LEDGERS).map((kind) => [kind, { own: null, others: null, othersResetAt: null }]),
194
+ ),
152
195
  // Bumped by Reset activity stats, so a store write that read the counts before the reset skips.
153
196
  statsResets: 0,
197
+ // Bumped by each pin press, and each pinned turn's count when its route was written: the pin is used up when the
198
+ // first request goes out on that route, unless it was pressed again meanwhile.
199
+ pinPresses: 0,
200
+ turnPins: new Map(),
154
201
  // Each spawned agent's record by agentId (spawnRecord), and when each parent loop last finished an agent of a type,
155
- // for respawns. The subagent totals kept across sessions, held as the savings records are.
202
+ // for respawns.
156
203
  agents: new Map(),
157
204
  finished: new Map(),
158
205
  // Each agent type's definition frontmatter by provider and type, read once per session (agentDefinition).
159
206
  definitions: new Map(),
160
- subagentsOwn: null,
161
- subagentsOthers: null,
162
207
  };
163
208
  }
164
209
 
@@ -221,107 +266,85 @@ async function updateView($, router, patch) {
221
266
  await $.state.set(VIEW, router.view);
222
267
  }
223
268
 
224
- // This session's record kept across sessions, read from the store once per session, and the last reset (ms) from
225
- // any session, read each time: a Reset in another session empties a record held from before it.
226
- async function ownSavings($, router) {
269
+ // This session's record of `kind`, read from the store once per session, and the last reset (ms) from any session,
270
+ // read each time: a Reset in another session empties a record held from before it.
271
+ async function ownRecord($, router, kind) {
272
+ const { prefix, read, afterReset } = LEDGERS[kind];
273
+ const held = router.ledgers[kind];
227
274
  const sessionId = await $.session.id();
228
275
  const resetAt = await $.store.get(SAVINGS_RESET_KEY);
229
- if (router.savingsOwn?.sessionId !== sessionId) {
230
- const record = readSavingsStore(await $.store.get(`${SAVINGS_PREFIX}${sessionId}`));
276
+ if (held.own?.sessionId !== sessionId) {
277
+ const record = read(await $.store.get(`${prefix}${sessionId}`));
231
278
  // Another call may have read it meanwhile and a turn added to it: that one stands.
232
- if (router.savingsOwn?.sessionId !== sessionId) router.savingsOwn = { sessionId, record };
279
+ if (held.own?.sessionId !== sessionId) held.own = { sessionId, record };
233
280
  }
234
- router.savingsOwn.record = afterReset(router.savingsOwn.record, resetAt);
235
- return { own: router.savingsOwn, resetAt };
281
+ held.own.record = afterReset(held.own.record, resetAt);
282
+ return { own: held.own, resetAt };
236
283
  }
237
284
 
238
- // Every other session's record since the last reset, added up.
239
- async function otherSavings($, sessionId, resetAt) {
240
- const own = `${SAVINGS_PREFIX}${sessionId}`;
241
- const keys = (await $.store.keys()).filter((key) => key.startsWith(SAVINGS_PREFIX) && key !== own);
242
- return mergeSavingsStores(await Promise.all(keys.map((key) => $.store.get(key))), resetAt);
285
+ // Every other session's record of `kind` since the last reset, added up and held. `keys` is one $.store.keys() listing.
286
+ async function readOthers($, router, kind, { sessionId, resetAt, keys }) {
287
+ const { prefix, legacy, merge } = LEDGERS[kind];
288
+ const own = `${prefix}${sessionId}`;
289
+ const names = keys.filter((key) => (key.startsWith(prefix) && key !== own) || key === legacy);
290
+ const others = merge(await Promise.all(names.map((key) => $.store.get(key))), resetAt);
291
+ router.ledgers[kind] = { ...router.ledgers[kind], others, othersResetAt: resetAt ?? null };
243
292
  }
244
293
 
245
- // This session's metrics record and the last reset, as ownSavings: Reset stats clears both with one marker.
246
- async function ownMetrics($, router) {
247
- const sessionId = await $.session.id();
248
- const resetAt = await $.store.get(SAVINGS_RESET_KEY);
249
- if (router.metricsOwn?.sessionId !== sessionId) {
250
- const record = readMetrics(await $.store.get(`${METRICS_PREFIX}${sessionId}`));
251
- if (router.metricsOwn?.sessionId !== sessionId) router.metricsOwn = { sessionId, record };
294
+ // The view's sums of `kinds`, this session's record and the others', from what the router holds; a kind whose others
295
+ // were never read gives nothing.
296
+ function ledgerView(router, kinds = LEDGER_KINDS) {
297
+ const patch = {};
298
+ for (const kind of kinds) {
299
+ const { others, own } = router.ledgers[kind];
300
+ if (others) patch[LEDGERS[kind].field] = LEDGERS[kind].merge([others, own?.record]);
252
301
  }
253
- router.metricsOwn.record = metricsAfterReset(router.metricsOwn.record, resetAt);
254
- return { own: router.metricsOwn, resetAt };
255
- }
256
-
257
- // Every other session's metrics since the last reset, added up.
258
- async function otherMetrics($, sessionId, resetAt) {
259
- const own = `${METRICS_PREFIX}${sessionId}`;
260
- const keys = (await $.store.keys()).filter((key) => key.startsWith(METRICS_PREFIX) && key !== own);
261
- return mergeMetrics(await Promise.all(keys.map((key) => $.store.get(key))), resetAt);
302
+ return patch;
262
303
  }
263
304
 
264
- // This session's subagent record and the last reset, as ownSavings: Reset stats clears it with the same marker.
265
- async function ownSubagents($, router) {
266
- const sessionId = await $.session.id();
267
- const resetAt = await $.store.get(SAVINGS_RESET_KEY);
268
- if (router.subagentsOwn?.sessionId !== sessionId) {
269
- const record = readSubagentStore(await $.store.get(`${SUBAGENT_PREFIX}${sessionId}`));
270
- if (router.subagentsOwn?.sessionId !== sessionId) router.subagentsOwn = { sessionId, record };
305
+ // Adds to this session's record of `kind` (`add(record, now)` returns the record itself when it adds nothing) and
306
+ // writes it. A record read before a Reset is never written back: the reset counter is compared after the reads. The
307
+ // record is added to in memory before the write, so a refresh during the write counts it once. True when the view
308
+ // may show the new sums: no reset ran meanwhile.
309
+ async function addToLedger($, router, kind, add) {
310
+ const resets = router.statsResets;
311
+ const { own, resetAt } = await ownRecord($, router, kind);
312
+ const held = router.ledgers[kind];
313
+ // The others held from before a reset in another session are read again: a record from before 1.10.3 has no
314
+ // `since` to tell.
315
+ if (!held.others || held.othersResetAt !== (resetAt ?? null))
316
+ await readOthers($, router, kind, { sessionId: own.sessionId, resetAt, keys: await $.store.keys() });
317
+ if (router.statsResets !== resets) return false;
318
+ const record = add(own.record, Date.now());
319
+ if (record !== own.record) {
320
+ own.record = record;
321
+ await $.store.set(`${LEDGERS[kind].prefix}${own.sessionId}`, record);
271
322
  }
272
- router.subagentsOwn.record = subagentsAfterReset(router.subagentsOwn.record, resetAt);
273
- return { own: router.subagentsOwn, resetAt };
274
- }
275
-
276
- // Every other session's subagent record since the last reset, added up.
277
- async function otherSubagents($, sessionId, resetAt) {
278
- const own = `${SUBAGENT_PREFIX}${sessionId}`;
279
- const keys = (await $.store.keys()).filter((key) => key.startsWith(SUBAGENT_PREFIX) && key !== own);
280
- return mergeSubagentStores(await Promise.all(keys.map((key) => $.store.get(key))), resetAt);
323
+ return router.statsResets === resets;
281
324
  }
282
325
 
283
- // The view's subagent totals, this session's and the others', from what the router holds; nothing until a read
284
- // succeeded.
285
- const subagentView = (router) =>
286
- router.subagentsOthers
287
- ? { subagentStore: mergeSubagentStores([router.subagentsOthers, router.subagentsOwn?.record]) }
288
- : {};
289
-
290
- const metricsView = (router) => mergeMetrics([router.metricsOthers, router.metricsOwn?.record]);
291
-
292
- // The view's totals kept across sessions, from what the router holds; nothing until a read succeeded.
293
- const savedView = (router) =>
294
- router.savingsOthers ? { savingsStore: mergeSavingsStores([router.savingsOthers, router.savingsOwn?.record]) } : {};
295
-
296
326
  // The counts kept across sessions for the view, read when the session starts and the pane opens: another session
297
- // may have added to them. A failed read keeps what the view has; it never breaks a turn or a render. The saved
298
- // totals are taken from the router after the reads, so a turn that finished meanwhile counts once.
327
+ // may have added to them. A failed read keeps what the view has; it never breaks a turn or a render. The sums are
328
+ // taken from the router after the reads, so a turn that finished meanwhile counts once; a Reset meanwhile gives
329
+ // nothing, as the reset view stands.
299
330
  async function storeView($, router) {
300
- const out = {};
301
- try {
302
- out.activityStore = readStore(await $.store.get(STORE_KEY));
303
- } catch {}
331
+ const resets = router.statsResets;
304
332
  try {
305
- const { own, resetAt } = await ownMetrics($, router);
306
- router.metricsOthers = await otherMetrics($, own.sessionId, resetAt);
307
- out.activityMetrics = metricsView(router);
308
- } catch {}
309
- try {
310
- const { own, resetAt } = await ownSavings($, router);
311
- router.savingsOthers = await otherSavings($, own.sessionId, resetAt);
312
- } catch {}
313
- try {
314
- const { own, resetAt } = await ownSubagents($, router);
315
- router.subagentsOthers = await otherSubagents($, own.sessionId, resetAt);
316
- Object.assign(out, subagentView(router));
333
+ const keys = await $.store.keys();
334
+ for (const kind of LEDGER_KINDS) {
335
+ try {
336
+ const { own, resetAt } = await ownRecord($, router, kind);
337
+ await readOthers($, router, kind, { sessionId: own.sessionId, resetAt, keys });
338
+ } catch {}
339
+ }
317
340
  } catch {}
318
- return out;
341
+ return router.statsResets === resets ? ledgerView(router) : {};
319
342
  }
320
343
 
321
344
  // A notice answers the last press in the pane, so the pane opens without one; the last write keeps its Undo in the
322
345
  // status bar.
323
346
  async function openPane($, router) {
324
- await updateView($, router, { notice: null, ...(await storeView($, router)), ...savedView(router) });
347
+ await updateView($, router, { notice: null, ...(await storeView($, router)) });
325
348
  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
326
349
  }
327
350
 
@@ -349,6 +372,7 @@ async function setPin($, router, tier) {
349
372
  if (view.phase === 'unavailable') return unavailableText(view);
350
373
  const mode = await modeOf($, router, view.mode);
351
374
  if (mode === 'manual') return 'Routing is off. Turn routing on before pinning a turn.';
375
+ router.pinPresses += 1;
352
376
  await updateView($, router, { pendingPin: tier });
353
377
  return `${tier} pinned for the next turn and its tool continuations.`;
354
378
  }
@@ -548,7 +572,8 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, router)
548
572
 
549
573
  // One turn's classification and route, written to the loop at `loopVersion`: the loop and its new version, or null
550
574
  // when the turn was aborted, left the session or Auto, or lost the write. `signal` is the step's: its abort cancels
551
- // the classifier call. The pin is the one in `view`, the view as the step read it.
575
+ // the classifier call. The pin is the one in `view`, the view as the step read it; it is used up only once the route
576
+ // is written, so a turn interrupted before then leaves it for the next.
552
577
  async function decideTurn($, router, e, signal, step) {
553
578
  const { sessionId, view, cfg, loop, loopVersion, context, nativeModel, availableModels } = step;
554
579
  const ref = { ...LOOP, id: 'main' };
@@ -560,8 +585,11 @@ async function decideTurn($, router, e, signal, step) {
560
585
  const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
561
586
  try {
562
587
  const pin = view.pendingPin;
563
- const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name));
564
- const messages = await $.session.messages({ as: 'api' });
588
+ const pinPresses = router.pinPresses;
589
+ const [credentials, messages] = await Promise.all([
590
+ resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name)),
591
+ $.session.messages({ as: 'api' }),
592
+ ]);
565
593
  if (!(await live())) return null;
566
594
  const facts = nativeFacts(cfg, loop, {
567
595
  messages,
@@ -574,7 +602,6 @@ async function decideTurn($, router, e, signal, step) {
574
602
  phase: 'choosing',
575
603
  activeTurnId: e.turnId,
576
604
  nativeModel,
577
- pendingPin: null,
578
605
  credentials: { ...router.view?.credentials, [cfg.classifier]: credentials.missing },
579
606
  });
580
607
  const adviceStarted = Date.now();
@@ -606,6 +633,8 @@ async function decideTurn($, router, e, signal, step) {
606
633
  });
607
634
  selected.engineModel = e.model;
608
635
  const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
636
+ // The written route serves the turn's next steps, even if an abort lands now.
637
+ if (written.isSet && pin) router.turnPins.set(e.turnId, pinPresses);
609
638
  // Manual, /clear and turn completion abort the controller; one may land during the write.
610
639
  if (!written.isSet || controller.signal.aborted) return null;
611
640
  if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
@@ -759,20 +788,11 @@ async function addSavings($, router, turnId, compared, tier) {
759
788
  } catch {}
760
789
  }
761
790
 
762
- // A finished turn's totals added to this session's record kept across sessions, with the guard recordActivity uses:
763
- // totals read before a reset are not written back. The record is added to in memory before the write, so a refresh
764
- // during the write counts the turn once.
791
+ // A finished turn's totals added to this session's record kept across sessions.
765
792
  async function flushSavings($, router, totals) {
766
793
  try {
767
- const resets = router.statsResets;
768
- const { own, resetAt } = await ownSavings($, router);
769
- // The others held from before a reset in another session are read again.
770
- if (!router.savingsOthers || afterReset(router.savingsOthers, resetAt) !== router.savingsOthers)
771
- router.savingsOthers = await otherSavings($, own.sessionId, resetAt);
772
- if (router.statsResets !== resets) return;
773
- own.record = recordSavingsStore(own.record, totals, Date.now());
774
- await $.store.set(`${SAVINGS_PREFIX}${own.sessionId}`, own.record);
775
- if (router.statsResets === resets) await updateView($, router, savedView(router));
794
+ if (await addToLedger($, router, 'savings', (record, now) => recordSavingsStore(record, totals, now)))
795
+ await updateView($, router, ledgerView(router, ['savings']));
776
796
  } catch {}
777
797
  }
778
798
 
@@ -814,90 +834,72 @@ async function recordActivity($, router, turn) {
814
834
  lateral: turn.lateral,
815
835
  }),
816
836
  });
817
- const resets = router.statsResets;
818
- const store = readStore(await $.store.get(STORE_KEY));
819
- const { own, resetAt } = await ownMetrics($, router);
820
- // The others held from before a reset in another session are read again.
821
- if (!router.metricsOthers || metricsAfterReset(router.metricsOthers, resetAt) !== router.metricsOthers)
822
- router.metricsOthers = await otherMetrics($, own.sessionId, resetAt);
823
- // Writing counts read before a reset would bring them back; this turn's are lost instead.
824
- if (router.statsResets !== resets) return;
825
- const written = recordStore(store, {
826
- predicted: turn.predicted,
827
- observed,
828
- runEnded: ended,
829
- lateral: turn.lateral,
830
- });
831
- const measured = recordMetrics(own.record, {
832
- classifier: turn.classifier,
833
- adviceMs: turn.adviceMs,
834
- downMove: down.event,
835
- now: Date.now(),
836
- });
837
- // Added to in memory before the write, so a refresh during the write counts the turn once.
838
- const changed = measured !== own.record;
839
- own.record = measured;
840
- // Both writes start before any reset can run between them.
841
- await Promise.all([
842
- $.store.set(STORE_KEY, written),
843
- changed ? $.store.set(`${METRICS_PREFIX}${own.sessionId}`, measured) : null,
837
+ // Writing counts read before a reset would bring them back; this turn's are lost instead. A reset during a write
838
+ // empties the view; these counts are older than it. Each record is written on its own: a failed write of one
839
+ // keeps the other.
840
+ const stats = { predicted: turn.predicted, observed, runEnded: ended, lateral: turn.lateral };
841
+ const metrics = { classifier: turn.classifier, adviceMs: turn.adviceMs, downMove: down.event };
842
+ const shown = await Promise.all([
843
+ addToLedger($, router, 'activity', (record, now) => recordStore(record, stats, now)).catch(() => false),
844
+ addToLedger($, router, 'metrics', (record, now) => recordMetrics(record, { ...metrics, now })).catch(() => false),
844
845
  ]);
845
- // A reset during the write emptied the view; these counts are older than it.
846
- if (router.statsResets === resets)
847
- await updateView($, router, { activityStore: written, activityMetrics: metricsView(router) });
846
+ const kinds = ['activity', 'metrics'].filter((_, i) => shown[i]);
847
+ if (kinds.length) await updateView($, router, ledgerView(router, kinds));
848
848
  } catch {}
849
849
  }
850
850
 
851
851
  // The session's open run ends with it; without this flush it is never counted.
852
- async function flushRun($, run) {
852
+ async function flushRun($, router, run) {
853
853
  try {
854
- const store = readStore(await $.store.get(STORE_KEY));
855
854
  const ended = { predicted: null, observed: null, runEnded: run, lateral: null };
856
- await $.store.set(STORE_KEY, recordStore(store, ended));
855
+ await addToLedger($, router, 'activity', (record, now) => recordStore(record, ended, now));
857
856
  } catch {}
858
857
  }
859
858
 
860
859
  // The frontmatter of the agent file a spawn starts (agentFrontmatter), or null when it cannot be found or read. Read
861
- // once per provider and type in a session, and never for a built-in, whose definition is not on disk.
860
+ // once per provider and type in a session, and never for a built-in, whose definition is not on disk. A read that
861
+ // failed is not kept: the next spawn of the type reads again.
862
862
  async function agentDefinition($, router, e) {
863
863
  const plugin = e.provider?.plugin;
864
864
  if (typeof plugin !== 'string' || plugin === 'engine' || typeof e.subagentType !== 'string') return null;
865
865
  const key = `${plugin} ${e.subagentType}`;
866
- if (!router.definitions.has(key)) router.definitions.set(key, await findDefinition($, plugin, e.subagentType));
866
+ if (!router.definitions.has(key)) {
867
+ try {
868
+ router.definitions.set(key, await findDefinition($, plugin, e.subagentType));
869
+ } catch {
870
+ return null;
871
+ }
872
+ }
867
873
  return router.definitions.get(key);
868
874
  }
869
875
 
870
876
  // A plugin agent (provider `plugin@marketplace`) is looked up under each install path installed_plugins.json gives
871
877
  // that plugin, the files Claude Code itself loads; any other agent under the session's .claude/agents, then the
872
878
  // profile's agents. Every match must agree on the model, or the definition is unknown. Limit: a plugin that keeps its
873
- // agents outside `agents/` reads as unknown, so its agents pass through.
879
+ // agents outside `agents/` reads as unknown, so its agents pass through. Throws when a file cannot be read.
874
880
  async function findDefinition($, plugin, type) {
875
- try {
876
- const home = await $.env.get('HOME');
877
- const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
878
- const name = type.slice(type.indexOf(':') + 1);
879
- const fromPlugin = plugin.includes('@');
880
- const dirs = fromPlugin
881
- ? (JSON.parse(await $.fs.read(`${profile}/plugins/installed_plugins.json`)).plugins?.[plugin] ?? []).map(
882
- (entry) => `${entry.installPath}/agents`,
883
- )
884
- : [`${await $.session.cwd()}/.claude/agents`, `${profile}/agents`];
885
- const found = [];
886
- for (const dir of dirs) {
887
- if (!(await $.fs.exists(dir))) continue;
888
- for (const entry of await $.fs.list(dir)) {
889
- if (entry.kind === 'dir' || !entry.name.endsWith('.md')) continue;
890
- const definition = agentFrontmatter(await $.fs.read(`${dir}/${entry.name}`));
891
- if (definition && (definition.name ?? entry.name.slice(0, -3)) === name) found.push(definition);
892
- }
893
- // A project agent replaces a user agent of the same name.
894
- if (found.length && !fromPlugin) break;
881
+ const home = await $.env.get('HOME');
882
+ const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
883
+ const name = type.slice(type.indexOf(':') + 1);
884
+ const fromPlugin = plugin.includes('@');
885
+ const dirs = fromPlugin
886
+ ? (JSON.parse(await $.fs.read(`${profile}/plugins/installed_plugins.json`)).plugins?.[plugin] ?? []).map(
887
+ (entry) => `${entry.installPath}/agents`,
888
+ )
889
+ : [`${await $.session.cwd()}/.claude/agents`, `${profile}/agents`];
890
+ const found = [];
891
+ for (const dir of dirs) {
892
+ if (!(await $.fs.exists(dir))) continue;
893
+ for (const entry of await $.fs.list(dir)) {
894
+ if (entry.kind === 'dir' || !entry.name.endsWith('.md')) continue;
895
+ const definition = agentFrontmatter(await $.fs.read(`${dir}/${entry.name}`));
896
+ if (definition && (definition.name ?? entry.name.slice(0, -3)) === name) found.push(definition);
895
897
  }
896
- const agree = found.every((d) => d.model === found[0].model && d.modelRouting === found[0].modelRouting);
897
- return found.length && agree ? found[0] : null;
898
- } catch {
899
- return null;
898
+ // A project agent replaces a user agent of the same name.
899
+ if (found.length && !fromPlugin) break;
900
900
  }
901
+ const agree = found.every((d) => d.model === found[0].model && d.modelRouting === found[0].modelRouting);
902
+ return found.length && agree ? found[0] : null;
901
903
  }
902
904
 
903
905
  // The spawn path's classifier client: a breaker of its own, so spawn failures never pause main-turn routing, and no
@@ -933,8 +935,9 @@ async function decideSpawn($, router, cfg, e, definition, signal) {
933
935
  }
934
936
  // The full id, not an alias: a family alias would resolve to the parent's exact model when the families match.
935
937
  const model = alias ? cfg.models[alias].id : null;
936
- const settings = await $.settings.read().catch(() => ({}));
937
- if (!model || !isModelAllowed(model, settings.availableModels, e.parentModel))
938
+ // Settings that cannot be read may hold an availableModels list, so the model is not sent.
939
+ const settings = await $.settings.read().catch(() => null);
940
+ if (!model || !settings || !isModelAllowed(model, settings.availableModels, e.parentModel))
938
941
  return { choice: 'core', model: null, failed };
939
942
  return { choice: alias, model, failed };
940
943
  }
@@ -1016,21 +1019,15 @@ async function finishAgent($, router, agentId) {
1016
1019
  await flushSubagents($, router, [agent]);
1017
1020
  }
1018
1021
 
1019
- // Agents' counts added to this session's record, with the guard flushSavings uses: counts read before a reset are not
1020
- // written back. Stats never break a turn: a failed read or write loses these counts.
1022
+ // This session's agents' counts added to its record kept across sessions. Stats never break a turn: a failed read or
1023
+ // write loses these counts.
1021
1024
  async function flushSubagents($, router, agents) {
1022
1025
  try {
1023
- const resets = router.statsResets;
1024
- const { own, resetAt } = await ownSubagents($, router);
1025
- const mine = agents.filter((agent) => agent.sessionId === own.sessionId);
1026
+ const sessionId = await $.session.id();
1027
+ const mine = agents.filter((agent) => agent.sessionId === sessionId);
1026
1028
  if (!mine.length) return;
1027
- if (!router.subagentsOthers || subagentsAfterReset(router.subagentsOthers, resetAt) !== router.subagentsOthers)
1028
- router.subagentsOthers = await otherSubagents($, own.sessionId, resetAt);
1029
- if (router.statsResets !== resets) return;
1030
- const now = Date.now();
1031
- own.record = mine.reduce((record, agent) => recordAgent(record, agent, now), own.record);
1032
- await $.store.set(`${SUBAGENT_PREFIX}${own.sessionId}`, own.record);
1033
- if (router.statsResets === resets) await updateView($, router, subagentView(router));
1029
+ const add = (record, now) => mine.reduce((sum, agent) => recordAgent(sum, agent, now), record);
1030
+ if (await addToLedger($, router, 'subagents', add)) await updateView($, router, ledgerView(router, ['subagents']));
1034
1031
  } catch {}
1035
1032
  }
1036
1033
 
@@ -1193,40 +1190,28 @@ function paneActions($, router, view) {
1193
1190
  router.afterDown = null;
1194
1191
  router.turnSavings.clear();
1195
1192
  for (const [id, agent] of router.agents) router.agents.set(id, flushedAgent(agent));
1196
- const clear = (key, value) =>
1197
- $.store
1198
- .set(key, value)
1199
- .then(() => true)
1200
- .catch(() => false);
1201
- // The per-session records: savings and activity metrics.
1193
+ // Every session's records. The marker is written first, so a session still holding its record from before the
1194
+ // reset drops it, unless that record's first count has the reset's millisecond or the clock moved back across
1195
+ // the reset.
1202
1196
  const clearRecords = async () => {
1203
- // Written first, so a session still holding its record from before the reset drops it, unless that record's
1204
- // first reading has the reset's millisecond or the clock moved back across the reset.
1205
- await $.store.set(SAVINGS_RESET_KEY, Date.now());
1197
+ const resetAt = Date.now();
1198
+ await $.store.set(SAVINGS_RESET_KEY, resetAt);
1206
1199
  const keys = (await $.store.keys()).filter((key) =>
1207
- [SAVINGS_PREFIX, METRICS_PREFIX, SUBAGENT_PREFIX].some((prefix) => key.startsWith(prefix)),
1200
+ Object.values(LEDGERS).some(({ prefix, legacy }) => key.startsWith(prefix) || key === legacy),
1208
1201
  );
1209
1202
  await Promise.all(keys.map((key) => $.store.delete(key)));
1210
- router.savingsOwn = null;
1211
- router.savingsOthers = emptySavingsStore();
1212
- router.metricsOwn = null;
1213
- router.metricsOthers = emptyMetrics();
1214
- router.subagentsOwn = null;
1215
- router.subagentsOthers = emptySubagentStore();
1203
+ for (const kind of LEDGER_KINDS)
1204
+ router.ledgers[kind] = { own: null, others: LEDGERS[kind].empty(), othersResetAt: resetAt };
1216
1205
  return true;
1217
1206
  };
1218
- const [stats, records] = await Promise.all([clear(STORE_KEY, emptyStore()), clearRecords().catch(() => false)]);
1207
+ const cleared = await clearRecords().catch(() => false);
1219
1208
  await updateView($, router, {
1220
1209
  activityStats: null,
1221
1210
  savingsBy: {},
1222
- ...(stats ? { activityStore: emptyStore() } : {}),
1223
- ...(records
1224
- ? { activityMetrics: emptyMetrics(), savingsStore: emptySavingsStore(), subagentStore: emptySubagentStore() }
1225
- : {}),
1226
- notice:
1227
- stats && records
1228
- ? 'Stats reset: activity and routing vs your model, this session and saved.'
1229
- : 'This session’s stats reset. Saved stats could not be cleared.',
1211
+ ...(cleared ? ledgerView(router) : {}),
1212
+ notice: cleared
1213
+ ? 'Stats reset: activity and routing vs your model, this session and saved.'
1214
+ : 'This session’s stats reset. Saved stats could not be cleared.',
1230
1215
  });
1231
1216
  },
1232
1217
  discardRouting: () => updateView($, router, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
@@ -1287,12 +1272,13 @@ async function endSession($, router) {
1287
1272
  router.decisions.clear();
1288
1273
  router.prompts.clear();
1289
1274
  router.turnConfigs.clear();
1275
+ router.turnPins.clear();
1290
1276
  router.turnActivities.clear();
1291
1277
  router.turnSavings.clear();
1292
1278
  const run = router.run;
1293
1279
  router.run = null;
1294
1280
  router.afterDown = null;
1295
- if (run) await flushRun($, run);
1281
+ if (run) await flushRun($, router, run);
1296
1282
  // Agents still running when the session ends: what they did so far is counted.
1297
1283
  const agents = [...router.agents.values()];
1298
1284
  router.agents.clear();
@@ -1356,7 +1342,6 @@ export function register(on, options) {
1356
1342
  lastWrite: null,
1357
1343
  bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
1358
1344
  ...(await storeView($, router)),
1359
- ...savedView(router),
1360
1345
  });
1361
1346
  } catch (error) {
1362
1347
  await updateView($, router, {
@@ -1404,9 +1389,7 @@ export function register(on, options) {
1404
1389
  on('turn.step', async function* ($, e, next) {
1405
1390
  if (e.agentId) return yield* stepAgent($, router, e, next);
1406
1391
  const cfg = router.turnConfigs.get(e.turnId) ?? router.config;
1407
- const sessionId = await $.session.id();
1408
- const nativeModel = await $.session.model();
1409
- const view = await readView($, router);
1392
+ const [sessionId, nativeModel, view] = await Promise.all([$.session.id(), $.session.model(), readView($, router)]);
1410
1393
  const mode = await modeOf($, router, view.mode);
1411
1394
  if (e.index === 0) {
1412
1395
  const saved = await rememberMode($, mode);
@@ -1426,8 +1409,7 @@ export function register(on, options) {
1426
1409
  if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
1427
1410
  return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', router);
1428
1411
  }
1429
- const context = await contextOf($, loop);
1430
- const settings = await $.settings.read();
1412
+ const [context, settings] = await Promise.all([contextOf($, loop), $.settings.read()]);
1431
1413
  const availableModels = settings.availableModels;
1432
1414
  const key = `${sessionId}:${e.turnId}:${loop.generation}`;
1433
1415
  if (loop.turnId !== e.turnId) {
@@ -1465,6 +1447,11 @@ export function register(on, options) {
1465
1447
  });
1466
1448
  await updateView($, router, continuationView(cfg, loop.decision, context));
1467
1449
  }
1450
+ const pinPresses = router.turnPins.get(e.turnId);
1451
+ if (pinPresses !== undefined) {
1452
+ router.turnPins.delete(e.turnId);
1453
+ if (pinPresses === router.pinPresses) await updateView($, router, { pendingPin: null });
1454
+ }
1468
1455
  const request = { ...e, model: loop.decision.model };
1469
1456
  if (loop.decision.effort === null) delete request.effort;
1470
1457
  else request.effort = loop.decision.effort;
@@ -1480,6 +1467,7 @@ export function register(on, options) {
1480
1467
  return next(e);
1481
1468
  }
1482
1469
  router.turnConfigs.delete(e.turnId);
1470
+ router.turnPins.delete(e.turnId);
1483
1471
  router.turnControllers.get(e.turnId)?.abort();
1484
1472
  if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
1485
1473
  router.view = { ...router.view, activeTurnId: null };
@@ -1,12 +1,16 @@
1
1
  // Activity statistics: counts only, never text. The session reducer feeds the Usage tab; the store reducers feed the
2
- // counts kept across sessions under `activity:stats:v1` and, per session, under METRICS_PREFIX. Pure: state and a turn
3
- // in, new state out.
2
+ // counts kept across sessions, per session under STORE_PREFIX and METRICS_PREFIX. Pure: state and a turn in, new state
3
+ // out.
4
4
 
5
5
  import { acceptActivity } from './activity.mjs';
6
6
  import { ACTIVITIES, ACTIVITY_VALUES } from './config.mjs';
7
+ import { afterResetOf, earlierSince, isRecord } from './records.mjs';
7
8
 
8
9
  export const OBSERVED = ['code', 'docs', 'ops', 'read', 'talk'];
10
+ // The one stats key every session shared before 1.10.3: it reads as another session's record until a reset deletes it.
9
11
  export const STORE_KEY = 'activity:stats:v1';
12
+ // Each session keeps its own stats under this prefix and its session id, as the metrics do.
13
+ export const STORE_PREFIX = 'activity:stats:v1:';
10
14
  // Each session keeps its own metrics under this prefix and its session id, as savings does (SAVINGS_PREFIX): sessions
11
15
  // finishing turns at the same moment do not overwrite each other. The readout is their sum (mergeMetrics).
12
16
  export const METRICS_PREFIX = 'activity:metrics:v1:';
@@ -117,8 +121,9 @@ export const LATENCY_BOUNDS = [
117
121
  const LATENCY_BUCKETS = LATENCY_BOUNDS.length + 1;
118
122
  const LATENCY_CLASSIFIERS = 8;
119
123
 
124
+ // `since` (ms) is the first count after a reset; null in a record from before 1.10.3.
120
125
  export function emptyStore() {
121
- return { version: 1, confusion: {}, runs: {}, lateral: { taken: 0, refused: 0 } };
126
+ return { version: 1, since: null, confusion: {}, runs: {}, lateral: { taken: 0, refused: 0 } };
122
127
  }
123
128
 
124
129
  // The p95 of a latency histogram: the upper bound of its bucket in ms, `over` when it lies above the last bound, and
@@ -137,19 +142,19 @@ export function latencyP95(buckets) {
137
142
  }
138
143
 
139
144
  const isCount = (n) => Number.isSafeInteger(n) && n >= 0;
140
- const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
141
145
  const onlyKeys = (v, keys) => isRecord(v) && Object.keys(v).every((k) => keys.includes(k));
142
146
  const countsOf = (v, keys) => onlyKeys(v, keys) && Object.values(v).every(isCount);
143
147
  const exactCountsOf = (v, keys) =>
144
148
  isRecord(v) && Object.keys(v).length === keys.length && keys.every((k) => isCount(v[k]));
145
149
 
146
150
  // The stored value if it has a known shape, else an empty store: a hand-edited or unknown file must not break stats.
147
- // Any other key is rejected: a new count goes under its own key, such as METRICS_KEY. A store saved before 1.10.1 also
148
- // holds the shadow readout, which reads as dropped; a release before 1.10.1 resets a store saved without it.
151
+ // Any other key is rejected: a new count goes under its own key, such as METRICS_PREFIX. A store saved before 1.10.1
152
+ // also holds the shadow readout, which reads as dropped; a release before 1.10.1 resets a store saved without it.
149
153
  export function readStore(value) {
150
154
  const ok =
151
- onlyKeys(value, ['version', 'confusion', 'runs', 'lateral', 'shadow']) &&
155
+ onlyKeys(value, ['version', 'since', 'confusion', 'runs', 'lateral', 'shadow']) &&
152
156
  value.version === 1 &&
157
+ (value.since === undefined || value.since === null || Number.isFinite(value.since)) &&
153
158
  onlyKeys(value.confusion, CONFUSION_ROWS) &&
154
159
  Object.values(value.confusion).every((row) => countsOf(row, OBSERVED)) &&
155
160
  onlyKeys(value.runs, ACTIVITIES) &&
@@ -159,28 +164,60 @@ export function readStore(value) {
159
164
  exactCountsOf(value.lateral, ['taken', 'refused']);
160
165
  if (!ok) return emptyStore();
161
166
  const { shadow: _retired, ...store } = value;
162
- return store;
167
+ return { ...store, since: store.since ?? null };
163
168
  }
164
169
 
165
- // One finished turn. `predicted` is the classifier's answer (null: none), `runEnded` a run that closed this turn and
166
- // `lateral` the outcome of a lateral switch decision. Unknown labels are dropped, so the store keeps a fixed set of keys.
167
- export function recordStore(store, { predicted, observed, runEnded, lateral }) {
170
+ // One finished turn at `now`. `predicted` is the classifier's answer (null: none), `runEnded` a run that closed this
171
+ // turn and `lateral` the outcome of a lateral switch decision. Unknown labels are dropped, so the store keeps a fixed
172
+ // set of keys. A turn that adds nothing returns `store` itself.
173
+ export function recordStore(store, { predicted, observed, runEnded, lateral }, now = null) {
168
174
  const row = predicted ?? 'none';
169
175
  const next = {
170
176
  version: 1,
177
+ since: store.since ?? now,
171
178
  confusion: { ...store.confusion },
172
179
  runs: { ...store.runs },
173
180
  lateral: { ...store.lateral },
174
181
  };
175
- if (CONFUSION_ROWS.includes(row) && OBSERVED.includes(observed))
182
+ let counted = false;
183
+ if (CONFUSION_ROWS.includes(row) && OBSERVED.includes(observed)) {
176
184
  next.confusion[row] = { ...next.confusion[row], [observed]: (next.confusion[row]?.[observed] ?? 0) + 1 };
185
+ counted = true;
186
+ }
177
187
  if (runEnded && ACTIVITIES.includes(runEnded.activity) && runEnded.length >= 1) {
178
188
  const lengths = [...(next.runs[runEnded.activity] ?? Array(RUN_BUCKETS).fill(0))];
179
189
  lengths[Math.min(Math.floor(runEnded.length), RUN_BUCKETS) - 1] += 1;
180
190
  next.runs[runEnded.activity] = lengths;
191
+ counted = true;
181
192
  }
182
- if (lateral === 'taken' || lateral === 'refused') next.lateral[lateral] += 1;
183
- return next;
193
+ if (lateral === 'taken' || lateral === 'refused') {
194
+ next.lateral[lateral] += 1;
195
+ counted = true;
196
+ }
197
+ return counted ? next : store;
198
+ }
199
+
200
+ // A record whose first count came before the last reset at `resetAt` (ms) reads as empty.
201
+ export const storeAfterReset = (record, resetAt) => afterResetOf(record, resetAt, emptyStore);
202
+
203
+ // The stats kept across sessions: every session's record since the last reset added up, since the earliest.
204
+ export function mergeStores(values, resetAt = null) {
205
+ const merged = emptyStore();
206
+ for (const one of values.map((value) => storeAfterReset(readStore(value), resetAt))) {
207
+ merged.since = earlierSince(merged.since, one.since);
208
+ for (const [row, counts] of Object.entries(one.confusion)) {
209
+ const into = { ...merged.confusion[row] };
210
+ for (const [observed, n] of Object.entries(counts)) into[observed] = (into[observed] ?? 0) + n;
211
+ merged.confusion[row] = into;
212
+ }
213
+ for (const [activity, lengths] of Object.entries(one.runs))
214
+ merged.runs[activity] = lengths.map((n, i) => n + (merged.runs[activity]?.[i] ?? 0));
215
+ merged.lateral = {
216
+ taken: merged.lateral.taken + one.lateral.taken,
217
+ refused: merged.lateral.refused + one.lateral.refused,
218
+ };
219
+ }
220
+ return merged;
184
221
  }
185
222
 
186
223
  // The readings kept across sessions beside the stats store, one session's or their sum: the classifier wait per
@@ -237,18 +274,15 @@ export function recordMetrics(metrics, { classifier = null, adviceMs = null, dow
237
274
  return next;
238
275
  }
239
276
 
240
- // A record whose first reading came before the last reset at `resetAt` (ms) reads as empty, as savings' afterReset.
241
- export function metricsAfterReset(record, resetAt) {
242
- return Number.isFinite(resetAt) && record.since !== null && record.since < resetAt ? emptyMetrics() : record;
243
- }
277
+ // A record whose first reading came before the last reset at `resetAt` (ms) reads as empty.
278
+ export const metricsAfterReset = (record, resetAt) => afterResetOf(record, resetAt, emptyMetrics);
244
279
 
245
280
  // The metrics kept across sessions: every session's record since the last reset added up, since the earliest. Latency
246
281
  // keeps the first LATENCY_CLASSIFIERS classifier ids in the order given, so the sum still reads back (readMetrics).
247
282
  export function mergeMetrics(values, resetAt = null) {
248
283
  const merged = emptyMetrics();
249
284
  for (const one of values.map((value) => metricsAfterReset(readMetrics(value), resetAt))) {
250
- const since = [merged.since, one.since].filter(Number.isFinite);
251
- merged.since = since.length ? Math.min(...since) : null;
285
+ merged.since = earlierSince(merged.since, one.since);
252
286
  for (const [id, buckets] of Object.entries(one.latency)) {
253
287
  // Own keys only: a classifier id such as `toString` must not read Object.prototype.
254
288
  const known = Object.hasOwn(merged.latency, id) ? merged.latency[id] : null;
package/lib/display.mjs CHANGED
@@ -73,6 +73,10 @@ export const REASONS = {
73
73
  'context-unknown': 'context is not measured reliably',
74
74
  'model-unavailable': 'the requested model is not available',
75
75
  pinned: 'one-turn model pin',
76
+ manual: 'routing did not choose this turn, so Claude’s model is kept',
77
+ 'routing off': 'routing is off, so Claude’s model is kept',
78
+ 'native-fallback': 'Claude Code switched to another model, so the router kept it',
79
+ interrupted: 'the turn ended before a model was chosen',
76
80
  'activity-up': 'the activity needs a stronger route',
77
81
  'activity-down': 'a cheaper route fits the activity and is estimated to pay back its cache write',
78
82
  'activity-pending': 'a route for the activity does not pay back yet',
package/lib/panel.mjs CHANGED
@@ -108,8 +108,18 @@ export function routeDraftOf(config, view) {
108
108
 
109
109
  const dollars = (value) => (Number.isFinite(value) ? `$${value.toFixed(3)}` : 'not reported');
110
110
  const difference = (value) => `${value < 0 ? '−' : '+'}$${Math.abs(value).toFixed(3)}`;
111
- const hostOf = (endpoint) => endpoint.replace(/^https?:\/\//, '').split('/')[0];
112
- const isLocal = (endpoint) => /^(127\.0\.0\.1|localhost)(:|$)/.test(hostOf(endpoint));
111
+ // The host and port as the request sees them: user info before an `@` is not the host. An endpoint that does not
112
+ // parse, such as one with a placeholder in its host, shows as written up to its path, and is not this machine.
113
+ function urlOf(endpoint) {
114
+ try {
115
+ return new URL(endpoint);
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+ const hostOf = (endpoint) => urlOf(endpoint)?.host ?? endpoint.replace(/^https?:\/\//, '').split('/')[0];
121
+ const LOCAL_HOSTS = ['127.0.0.1', 'localhost', '[::1]'];
122
+ const isLocal = (endpoint) => LOCAL_HOSTS.includes(urlOf(endpoint)?.hostname);
113
123
  const windowSize = (tokens) => (tokens >= 1e6 ? `${tokens / 1e6}M` : `${Math.round(tokens / 1e3)}K`);
114
124
  const share = (value) => (value === null ? '—' : `${value}%`);
115
125
  const plural = (n, word, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;
@@ -0,0 +1,14 @@
1
+ // What the records kept across sessions share: savings, activity stats and metrics, and subagents. Each session keeps
2
+ // its own record of a kind, with `since` (ms), its first count after a reset; the readout sums them.
3
+
4
+ export const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
5
+
6
+ // A record whose first count came before the last reset at `resetAt` (ms) reads as `empty()`.
7
+ export const afterResetOf = (record, resetAt, empty) =>
8
+ Number.isFinite(resetAt) && record.since !== null && record.since < resetAt ? empty() : record;
9
+
10
+ // The earlier of two `since` values, or null when neither is set.
11
+ export function earlierSince(a, b) {
12
+ const since = [a, b].filter(Number.isFinite);
13
+ return since.length ? Math.min(...since) : null;
14
+ }
package/lib/savings.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // the hook feeds each reply and keeps the totals in the view and, per session, in $.store under SAVINGS_PREFIX.
4
4
 
5
5
  import { effortSharesCache, ratesAt } from './cost.mjs';
6
+ import { afterResetOf, earlierSince, isRecord } from './records.mjs';
6
7
  import { HISTORY_SHRINK, isSameModel } from './route.mjs';
7
8
 
8
9
  // Each session keeps its own record under this prefix and its session id: $.store has no atomic update, and Claude
@@ -213,9 +214,7 @@ const STORE_KEYS = Object.keys(emptySavingsStore());
213
214
  // break a turn or the pane.
214
215
  export function readSavingsStore(value) {
215
216
  const ok =
216
- value !== null &&
217
- typeof value === 'object' &&
218
- !Array.isArray(value) &&
217
+ isRecord(value) &&
219
218
  Object.keys(value).length === STORE_KEYS.length &&
220
219
  STORE_KEYS.every((key) => Object.hasOwn(value, key)) &&
221
220
  value.version === 1 &&
@@ -227,16 +226,13 @@ export function readSavingsStore(value) {
227
226
  }
228
227
 
229
228
  // A record whose first reply came before the last reset at `resetAt` (ms) reads as empty.
230
- export function afterReset(record, resetAt) {
231
- return Number.isFinite(resetAt) && record.since !== null && record.since < resetAt ? emptySavingsStore() : record;
232
- }
229
+ export const afterReset = (record, resetAt) => afterResetOf(record, resetAt, emptySavingsStore);
233
230
 
234
231
  // The totals kept across sessions: every session's record since the last reset added up, since the earliest.
235
232
  export function mergeSavingsStores(values, resetAt = null) {
236
233
  const merged = emptySavingsStore();
237
234
  for (const one of values.map((value) => afterReset(readSavingsStore(value), resetAt))) {
238
- const since = [merged.since, one.since].filter(Number.isFinite);
239
- merged.since = since.length ? Math.min(...since) : null;
235
+ merged.since = earlierSince(merged.since, one.since);
240
236
  merged.replies += one.replies;
241
237
  for (const sum of SUMS) merged[sum] += one[sum];
242
238
  }
package/lib/subagents.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { CLASSIFY } from './config.mjs';
6
6
  import { clip } from './facts.mjs';
7
+ import { afterResetOf, earlierSince, isRecord } from './records.mjs';
7
8
  import { modelSpec, requestUsd } from './savings.mjs';
8
9
 
9
10
  export const SUBAGENT_PREFIX = 'subagents:v1:';
@@ -169,7 +170,6 @@ export function emptySubagentStore() {
169
170
 
170
171
  const ROUTED_SUMS = ['agents', 'differs', 'requests', 'pricedRequests', 'coreUsd', 'routedUsd', 'respawns', 'failures'];
171
172
  const PASSED_SUMS = ['agents', 'requests', 'pricedRequests', 'usd'];
172
- const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
173
173
 
174
174
  const emptyRouted = () => ({ ...Object.fromEntries(ROUTED_SUMS.map((sum) => [sum, 0])), choices: {} });
175
175
  const emptyPassed = () => Object.fromEntries(PASSED_SUMS.map((sum) => [sum, 0]));
@@ -248,9 +248,7 @@ export function readSubagentStore(value) {
248
248
  }
249
249
 
250
250
  // A record whose first agent came before the last reset at `resetAt` (ms) reads as empty.
251
- export function subagentsAfterReset(record, resetAt) {
252
- return Number.isFinite(resetAt) && record.since !== null && record.since < resetAt ? emptySubagentStore() : record;
253
- }
251
+ export const subagentsAfterReset = (record, resetAt) => afterResetOf(record, resetAt, emptySubagentStore);
254
252
 
255
253
  function addInto(target, source, sums, withChoices) {
256
254
  for (const [key, counts] of Object.entries(source)) {
@@ -266,8 +264,7 @@ function addInto(target, source, sums, withChoices) {
266
264
  export function mergeSubagentStores(values, resetAt = null) {
267
265
  const merged = emptySubagentStore();
268
266
  for (const one of values.map((value) => subagentsAfterReset(readSubagentStore(value), resetAt))) {
269
- const since = [merged.since, one.since].filter(Number.isFinite);
270
- merged.since = since.length ? Math.min(...since) : null;
267
+ merged.since = earlierSince(merged.since, one.since);
271
268
  addInto(merged.routed.on, one.routed.on, ROUTED_SUMS, true);
272
269
  addInto(merged.passed, one.passed, PASSED_SUMS, false);
273
270
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexeiled/claude-router",
3
- "version": "1.10.2",
3
+ "version": "1.10.3",
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",
@@ -1,4 +1,4 @@
1
- import { readFile, writeFile } from 'node:fs/promises';
1
+ import { chmod, lstat, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { isGatewayLayout, loadConfig } from '../lib/config.mjs';
@@ -48,10 +48,30 @@ export async function migrateFile(path) {
48
48
  const file = JSON.parse(original);
49
49
  const next = migrateConfig(file);
50
50
  if (JSON.stringify(file) === JSON.stringify(next)) return null;
51
+ // Renaming over a symlink would replace the link, not the file a dotfile manager keeps: as the pane, refuse it.
52
+ const info = await lstat(path);
53
+ if (info.isSymbolicLink()) throw new Error(`${path} is a symlink: migrate the file it points to`);
51
54
  // Named for the layout it keeps, so a 1.1 migration never collides with a 0.8 backup already on disk.
52
55
  const backup = `${path}.${isGatewayLayout(file) ? 'v0.8' : 'v1.1'}.backup`;
53
- await writeFile(backup, original, { flag: 'wx', mode: 0o600 });
54
- await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
56
+ try {
57
+ await writeFile(backup, original, { flag: 'wx', mode: 0o600 });
58
+ } catch (error) {
59
+ if (error.code === 'EEXIST') error.message = `${backup} already exists: move it away, then run again`;
60
+ throw error;
61
+ }
62
+ // Written beside it and renamed over it, so a crash mid-write leaves router.json whole. A failure removes this
63
+ // run's backup and its temporary file, never one it did not create, so the next run starts clean.
64
+ const temp = `${path}.${process.pid}.tmp`;
65
+ let created = false;
66
+ try {
67
+ await writeFile(temp, `${JSON.stringify(next, null, 2)}\n`, { flag: 'wx' });
68
+ created = true;
69
+ await chmod(temp, info.mode & 0o777);
70
+ await rename(temp, path);
71
+ } catch (error) {
72
+ await Promise.all([created ? rm(temp, { force: true }) : null, rm(backup, { force: true })]);
73
+ throw error;
74
+ }
55
75
  return backup;
56
76
  }
57
77
 
package/types/index.d.ts CHANGED
@@ -39,9 +39,12 @@ declare module 'claude-code' {
39
39
  lateral?: { taken: number; refused: number };
40
40
  agreement: { matched: number; total: number };
41
41
  }
42
- // Cross-session counts under store key 'activity:stats:v1'. `runs` buckets run lengths 1, 2, 3, 4, 5+.
42
+ // Cross-session counts, one record per session under store key 'activity:stats:v1:<session id>', and their sum.
43
+ // `since` is the first count after a reset (null in the key all sessions shared before 1.10.3). `runs` buckets run
44
+ // lengths 1, 2, 3, 4, 5+.
43
45
  interface RouterActivityStore {
44
46
  version: 1;
47
+ since: number | null;
45
48
  confusion: Partial<Record<RouterActivityAnswer | 'none', Partial<Record<RouterObserved, number>>>>;
46
49
  runs: Partial<Record<RouterActivity, [number, number, number, number, number]>>;
47
50
  lateral: { taken: number; refused: number };