@alexeiled/claude-router 1.12.0 → 1.14.0

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.
package/lib/subagents.mjs CHANGED
@@ -6,6 +6,7 @@ import { CLASSIFY } from './config.mjs';
6
6
  import { clip } from './facts.mjs';
7
7
  import { afterResetOf, earlierSince, isRecord } from './records.mjs';
8
8
  import { modelSpec, requestUsd } from './savings.mjs';
9
+ import { DAY, dayKey, daysBefore, RETAIN_DAYS } from './usage.mjs';
9
10
 
10
11
  export const SUBAGENT_PREFIX = 'subagents:v1:';
11
12
  // The longest a spawn waits for the classifier. The wait delays the subagent's start, and the client's deadline race
@@ -17,6 +18,26 @@ export const RESPAWN_WINDOW_MS = 600_000;
17
18
  // `unlisted`: a built-in router.json does not list, or a type it lists as null. `pinned`: the agent's definition names a
18
19
  // model and does not set `modelRouting: auto`. `unknown`: its definition could not be found or read.
19
20
  export const PASS_REASONS = ['fork', 'workflow', 'explicit', 'teammate', 'unlisted', 'pinned', 'unknown'];
21
+ // Each reason as the pane and the band show it.
22
+ export const PASS_LABEL = {
23
+ fork: 'fork',
24
+ workflow: 'workflow agent',
25
+ explicit: 'explicit model',
26
+ teammate: 'teammate',
27
+ unlisted: 'type not routed',
28
+ pinned: 'pinned model',
29
+ unknown: 'no definition',
30
+ };
31
+ // Why Claude Code picked the model for each reason.
32
+ export const PASS_WHY = {
33
+ fork: 'your model',
34
+ workflow: 'the workflow sets it',
35
+ explicit: 'the Agent call sets it',
36
+ teammate: 'teammates keep theirs',
37
+ unlisted: 'not in subagents.types',
38
+ pinned: 'its agent file sets it',
39
+ unknown: 'agent file not found',
40
+ };
20
41
  // Built-ins that ignore CLAUDE_CODE_SUBAGENT_MODEL unless CLAUDE_CODE_SUBAGENT_MODEL_FORCE is set.
21
42
  const OWN_MODEL_BUILTINS = ['Explore', 'Plan'];
22
43
 
@@ -116,11 +137,20 @@ export function coreModelOf(config, spawn, { envModel = null, force = false, def
116
137
  return usesEnv ? idOf(envModel) : spawn.parentModel;
117
138
  }
118
139
 
140
+ // How the router's model compares with core's: null when they are the same, `up` or `down` by output price, `moved`
141
+ // when either has no price.
142
+ export function moveOf(config, routedModel, coreModel) {
143
+ if (!routedModel || !coreModel || routedModel === coreModel) return null;
144
+ const [routed, core] = [routedModel, coreModel].map((id) => modelSpec(config, id)?.output);
145
+ if (!Number.isFinite(routed) || !Number.isFinite(core) || routed === core) return 'moved';
146
+ return routed > core ? 'up' : 'down';
147
+ }
148
+
119
149
  // One spawn's record while its agent runs: what was decided and the priced replies since the last flush. `pass` is a
120
150
  // PASS_REASONS entry or null. `choice` is the models key decided, or 'core' when the decision kept core's model.
121
- // `actualUsd` prices each reply on the model it ran on; `otherUsd` the same tokens on core's estimated model. Null for
122
- // a pass-through.
123
- export function spawnRecord({ sessionId, spawn, pass, choice, routedModel, coreModel, failed, respawn }) {
151
+ // `move` is moveOf the routed model against core's. `actualUsd` prices each reply on the model it ran on; `otherUsd`
152
+ // the same tokens on core's estimated model, none for a pass-through.
153
+ export function spawnRecord({ sessionId, spawn, pass, choice, routedModel, coreModel, move = null, failed, respawn }) {
124
154
  return {
125
155
  sessionId,
126
156
  type: spawn.subagentType,
@@ -128,6 +158,7 @@ export function spawnRecord({ sessionId, spawn, pass, choice, routedModel, coreM
128
158
  choice,
129
159
  routedModel,
130
160
  coreModel,
161
+ move,
131
162
  failed: Boolean(failed),
132
163
  respawn: Boolean(respawn),
133
164
  counted: false,
@@ -161,48 +192,70 @@ export function addAgentReply(config, agent, usage, ttl) {
161
192
  return next;
162
193
  }
163
194
 
164
- // A record kept across sessions, one session's or their sum, since `since` (ms), the first agent after a reset.
165
- // `routed.on[type]` counts the routed types; `passed[reason]` the pass-throughs, priced on the model they ran on. Records
166
- // saved before 1.10.1 may also hold `routed.shadow`, which reads as dropped.
195
+ // A record kept across sessions, one session's or their sum, since `since` (ms), the first agent after a reset, by
196
+ // local calendar day like the usage records, so the Usage tab's period applies. A day holds `routed[type]` and
197
+ // `passed[reason]`: agents, requests and the retry proxies of the type, and per model id the agents ran on, its agents
198
+ // and their cost (`models`); a routed model also counts the agents the router moved onto it, `up` or `down` from
199
+ // core's, and core's estimated cost of the same tokens. A version 1 record, from before 1.14.0, has neither days nor
200
+ // models: it reads as `undated` totals, which only the periods without a range (session and all) count.
167
201
  export function emptySubagentStore() {
168
- return { version: 1, since: null, routed: { on: {} }, passed: {} };
202
+ return { version: 2, since: null, days: {} };
169
203
  }
170
204
 
171
- const ROUTED_SUMS = ['agents', 'differs', 'requests', 'pricedRequests', 'coreUsd', 'routedUsd', 'respawns', 'failures'];
172
- const PASSED_SUMS = ['agents', 'requests', 'pricedRequests', 'usd'];
205
+ const ROUTED_SUMS = ['agents', 'requests', 'pricedRequests', 'respawns', 'failures'];
206
+ const PASSED_SUMS = ['agents', 'requests', 'pricedRequests'];
207
+ const ROUTED_MODEL_SUMS = ['agents', 'moved', 'up', 'down', 'usd', 'coreUsd'];
208
+ const PASSED_MODEL_SUMS = ['agents', 'usd'];
209
+ const UNDATED_SUMS = ['agents', 'usd'];
210
+ const SUMS = {
211
+ routed: [ROUTED_SUMS, ROUTED_MODEL_SUMS],
212
+ passed: [PASSED_SUMS, PASSED_MODEL_SUMS],
213
+ };
214
+ // A model id the record never got.
215
+ const UNKNOWN_MODEL = 'unknown';
216
+
217
+ const zeros = (sums) => Object.fromEntries(sums.map((sum) => [sum, 0]));
218
+ const emptyCounts = (sums) => ({ ...zeros(sums), models: {} });
219
+ const emptySubagentDay = () => ({ routed: {}, passed: {} });
173
220
 
174
- const emptyRouted = () => ({ ...Object.fromEntries(ROUTED_SUMS.map((sum) => [sum, 0])), choices: {} });
175
- const emptyPassed = () => Object.fromEntries(PASSED_SUMS.map((sum) => [sum, 0]));
221
+ // A key read from the store, such as a model id `__proto__`, must neither answer from the prototype nor set it.
222
+ const own = (object, key) => (Object.hasOwn(object, key) ? object[key] : undefined);
223
+ const put = (object, key, value) =>
224
+ Object.defineProperty(object, key, { value, enumerable: true, writable: true, configurable: true });
176
225
 
177
- // The finished turn's counts of one agent added to a store at `now`: the agent once, on its first flush, then its
178
- // requests and prices since the last flush.
226
+ // The finished turn's counts of one agent added to a store at `now`, on that day: the agent once, on its first flush,
227
+ // with the model it ran on and the router's move, then its requests and prices since the last flush. Days past
228
+ // RETAIN_DAYS leave the record.
179
229
  export function recordAgent(store, agent, now) {
180
230
  if (!agent.requests && agent.counted) return store;
181
231
  const first = agent.counted ? 0 : 1;
182
- const next = { ...store, since: store.since ?? now, routed: { ...store.routed }, passed: { ...store.passed } };
183
- if (agent.pass) {
184
- const counts = { ...(next.passed[agent.pass] ?? emptyPassed()) };
185
- counts.agents += first;
186
- counts.requests += agent.requests;
187
- counts.pricedRequests += agent.pricedRequests;
188
- counts.usd += agent.actualUsd;
189
- next.passed[agent.pass] = counts;
190
- return next;
191
- }
192
- const byType = { ...next.routed.on };
193
- const counts = { ...(byType[agent.type] ?? emptyRouted()), choices: { ...byType[agent.type]?.choices } };
232
+ const days = structuredClone(store.days);
233
+ const day = days[dayKey(now)] ?? emptySubagentDay();
234
+ const kind = agent.pass ? 'passed' : 'routed';
235
+ const key = agent.pass ?? agent.type;
236
+ const [sums, modelSums] = SUMS[kind];
237
+ const counts = own(day[kind], key) ?? emptyCounts(sums);
194
238
  counts.agents += first;
195
- counts.differs += first && agent.routedModel !== agent.coreModel ? 1 : 0;
196
- counts.respawns += first && agent.respawn ? 1 : 0;
197
- counts.failures += first && agent.failed ? 1 : 0;
198
- if (first) counts.choices[agent.choice] = (counts.choices[agent.choice] ?? 0) + 1;
199
239
  counts.requests += agent.requests;
200
240
  counts.pricedRequests += agent.pricedRequests;
201
- counts.coreUsd += agent.otherUsd;
202
- counts.routedUsd += agent.actualUsd;
203
- byType[agent.type] = counts;
204
- next.routed = { on: byType };
205
- return next;
241
+ const modelId = agent.routedModel || UNKNOWN_MODEL;
242
+ const model = own(counts.models, modelId) ?? zeros(modelSums);
243
+ model.agents += first;
244
+ model.usd += agent.actualUsd;
245
+ if (!agent.pass) {
246
+ counts.respawns += first && agent.respawn ? 1 : 0;
247
+ counts.failures += first && agent.failed ? 1 : 0;
248
+ model.moved += first && agent.move ? 1 : 0;
249
+ model.up += first && agent.move === 'up' ? 1 : 0;
250
+ model.down += first && agent.move === 'down' ? 1 : 0;
251
+ model.coreUsd += agent.otherUsd;
252
+ }
253
+ put(counts.models, modelId, model);
254
+ put(day[kind], key, counts);
255
+ days[dayKey(now)] = day;
256
+ const cutoff = daysBefore(now, RETAIN_DAYS);
257
+ for (const old of Object.keys(days)) if (old < cutoff) delete days[old];
258
+ return { version: 2, since: store.since ?? now, days, ...(store.undated ? { undated: store.undated } : {}) };
206
259
  }
207
260
 
208
261
  // The record after a flush: counted once, nothing pending.
@@ -215,58 +268,123 @@ export const flushedAgent = (agent) => ({
215
268
  otherUsd: 0,
216
269
  });
217
270
 
218
- function readCounts(value, sums, withChoices) {
219
- if (!isRecord(value) || !sums.every((sum) => isCount(value[sum]))) return null;
220
- const out = Object.fromEntries(sums.map((sum) => [sum, value[sum]]));
221
- if (!withChoices) return out;
222
- const choices = isRecord(value.choices) ? value.choices : {};
223
- out.choices = Object.fromEntries(Object.entries(choices).filter(([, n]) => Number.isSafeInteger(n) && n >= 0));
224
- return out;
271
+ const readSums = (value, sums) =>
272
+ isRecord(value) && sums.every((sum) => isCount(value[sum]))
273
+ ? Object.fromEntries(sums.map((sum) => [sum, value[sum]]))
274
+ : null;
275
+
276
+ function readCounts(value, [sums, modelSums]) {
277
+ const counts = readSums(value, sums);
278
+ if (!counts || !isRecord(value.models)) return null;
279
+ counts.models = {};
280
+ for (const [id, model] of Object.entries(value.models)) {
281
+ const read = readSums(model, modelSums);
282
+ if (!read) return null;
283
+ put(counts.models, id, read);
284
+ }
285
+ return counts;
225
286
  }
226
287
 
227
- function readMap(value, sums, withChoices) {
288
+ function readKind(value, kind) {
228
289
  const out = {};
229
290
  if (!isRecord(value)) return out;
230
291
  for (const [key, counts] of Object.entries(value)) {
231
- const read = readCounts(counts, sums, withChoices);
232
- if (read) out[key] = read;
292
+ const read = readCounts(counts, SUMS[kind]);
293
+ if (read) put(out, key, read);
233
294
  }
234
295
  return out;
235
296
  }
236
297
 
237
- // The stored value with its well-formed entries, else an empty store: a missing, hand-edited or unknown value must not
238
- // break a turn or the pane.
239
- export function readSubagentStore(value) {
240
- if (!isRecord(value) || value.version !== 1 || !(value.since === null || Number.isFinite(value.since)))
241
- return emptySubagentStore();
242
- return {
243
- version: 1,
244
- since: value.since,
245
- routed: { on: readMap(value.routed?.on, ROUTED_SUMS, true) },
246
- passed: readMap(value.passed, PASSED_SUMS, false),
298
+ const readDay = (day) => ({ routed: readKind(day.routed, 'routed'), passed: readKind(day.passed, 'passed') });
299
+
300
+ // A version 1 record's agents and their cost on the models they ran on: what is left of it without days or models.
301
+ function undatedOf(value) {
302
+ const out = zeros(UNDATED_SUMS);
303
+ const add = (counts, usd) => {
304
+ if (!isRecord(counts) || !isCount(counts.agents) || !isCount(counts[usd])) return;
305
+ out.agents += counts.agents;
306
+ out.usd += counts[usd];
247
307
  };
308
+ for (const counts of Object.values(isRecord(value.routed?.on) ? value.routed.on : {})) add(counts, 'routedUsd');
309
+ for (const counts of Object.values(isRecord(value.passed) ? value.passed : {})) add(counts, 'usd');
310
+ return out;
311
+ }
312
+
313
+ // The stored value with its well-formed days and entries, else an empty store: a missing, hand-edited or unknown value
314
+ // must not break a turn or the pane.
315
+ export function readSubagentStore(value) {
316
+ if (!isRecord(value) || !(value.since === null || Number.isFinite(value.since))) return emptySubagentStore();
317
+ if (value.version === 1) {
318
+ const undated = undatedOf(value);
319
+ return { version: 2, since: value.since, days: {}, ...(undated.agents ? { undated } : {}) };
320
+ }
321
+ if (value.version !== 2 || !isRecord(value.days)) return emptySubagentStore();
322
+ const days = {};
323
+ for (const [key, day] of Object.entries(value.days)) if (DAY.test(key) && isRecord(day)) days[key] = readDay(day);
324
+ const undated = readSums(value.undated, UNDATED_SUMS);
325
+ return { version: 2, since: value.since, days, ...(undated ? { undated } : {}) };
248
326
  }
249
327
 
250
328
  // A record whose first agent came before the last reset at `resetAt` (ms) reads as empty.
251
329
  export const subagentsAfterReset = (record, resetAt) => afterResetOf(record, resetAt, emptySubagentStore);
252
330
 
253
- function addInto(target, source, sums, withChoices) {
254
- for (const [key, counts] of Object.entries(source)) {
255
- const into = target[key] ?? (withChoices ? emptyRouted() : emptyPassed());
256
- for (const sum of sums) into[sum] += counts[sum];
257
- if (withChoices)
258
- for (const [choice, n] of Object.entries(counts.choices)) into.choices[choice] = (into.choices[choice] ?? 0) + n;
259
- target[key] = into;
331
+ const addSums = (into, from, sums) => {
332
+ for (const sum of sums) into[sum] += from[sum];
333
+ };
334
+
335
+ function addDay(into, day) {
336
+ for (const kind of ['routed', 'passed']) {
337
+ const [sums, modelSums] = SUMS[kind];
338
+ for (const [key, counts] of Object.entries(day[kind])) {
339
+ const total = own(into[kind], key) ?? emptyCounts(sums);
340
+ addSums(total, counts, sums);
341
+ for (const [id, model] of Object.entries(counts.models)) {
342
+ const sum = own(total.models, id) ?? zeros(modelSums);
343
+ addSums(sum, model, modelSums);
344
+ put(total.models, id, sum);
345
+ }
346
+ put(into[kind], key, total);
347
+ }
260
348
  }
261
349
  }
262
350
 
263
- // Every session's record since the last reset added up, since the earliest.
351
+ // Every session's record since the last reset added up day by day, since the earliest.
264
352
  export function mergeSubagentStores(values, resetAt = null) {
265
353
  const merged = emptySubagentStore();
266
354
  for (const one of values.map((value) => subagentsAfterReset(readSubagentStore(value), resetAt))) {
267
355
  merged.since = earlierSince(merged.since, one.since);
268
- addInto(merged.routed.on, one.routed.on, ROUTED_SUMS, true);
269
- addInto(merged.passed, one.passed, PASSED_SUMS, false);
356
+ for (const [key, day] of Object.entries(one.days)) {
357
+ merged.days[key] ??= emptySubagentDay();
358
+ addDay(merged.days[key], day);
359
+ }
360
+ if (one.undated) {
361
+ merged.undated ??= zeros(UNDATED_SUMS);
362
+ addSums(merged.undated, one.undated, UNDATED_SUMS);
363
+ }
270
364
  }
271
365
  return merged;
272
366
  }
367
+
368
+ // A record's days inside `range` (periodRange in lib/usage.mjs) added up, with the agents per day, oldest first; null
369
+ // ends take the whole record and its undated totals.
370
+ export function summarizeSubagents(record, { from, to }) {
371
+ const total = emptySubagentDay();
372
+ const perDay = [];
373
+ for (const key of Object.keys(record.days).sort()) {
374
+ if ((from !== null && key < from) || (to !== null && key > to)) continue;
375
+ const day = record.days[key];
376
+ addDay(total, day);
377
+ const agents = [...Object.values(day.routed), ...Object.values(day.passed)].reduce((n, c) => n + c.agents, 0);
378
+ perDay.push([key, agents]);
379
+ }
380
+ const whole = from === null && to === null;
381
+ return { ...total, perDay, undated: whole && record.undated ? record.undated : null };
382
+ }
383
+
384
+ // A routed type's or a pass-through's totals over its models: agents moved and their direction, routed cost and
385
+ // core's estimate (zero for a pass-through).
386
+ export function modelTotals(counts) {
387
+ const out = zeros(ROUTED_MODEL_SUMS);
388
+ for (const model of Object.values(counts.models)) for (const sum of ROUTED_MODEL_SUMS) out[sum] += model[sum] ?? 0;
389
+ return out;
390
+ }
package/lib/usage.mjs CHANGED
@@ -33,7 +33,7 @@ export const CELL_SUMS = [
33
33
  ];
34
34
  const USD = new Set(['routedUsd', 'yoursUsd', 'cheaperUsd', 'strongerUsd', 'switchUsd']);
35
35
  const IS_USD = CELL_SUMS.map((sum) => USD.has(sum));
36
- const DAY = /^\d{4}-\d{2}-\d{2}$/;
36
+ export const DAY = /^\d{4}-\d{2}-\d{2}$/;
37
37
  // `activity|tier|id@effort`: activity and tier never hold a `|`, and an effort never an `@`, so a model id may hold
38
38
  // either.
39
39
  const CELL_KEY = /^[^|]+\|[^|]+\|.+@[^@]+$/;
package/lib/view.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  // The view the band and pane draw from: its initial shape and the patches built from pure inputs. Pure: the hook
2
2
  // writes the view to $.state.
3
3
 
4
- // Replies kept for the pane's trend and tier strip.
5
- const HISTORY = 30;
4
+ // Replies kept for the input trend behind the Now tab's details.
5
+ export const HISTORY = 30;
6
+ // The session strip's most cells. Once it is full, neighbouring cells merge, so each covers twice the replies and the
7
+ // strip always spans the whole session in a bounded view.
8
+ export const STRIP_CELLS = 48;
6
9
 
7
10
  export function initialView(model) {
8
11
  return {
@@ -37,8 +40,10 @@ export function initialView(model) {
37
40
  activityProbabilities: null,
38
41
  history: [],
39
42
  tiers: [],
40
- activities: [],
41
- routes: [],
43
+ // The session's replies by tier (addToStrip), and the last route switch: when, the tiers and routes it moved
44
+ // between, and the turn's activity.
45
+ strip: null,
46
+ lastSwitch: null,
42
47
  activityStats: null,
43
48
  activityStore: null,
44
49
  activityMetrics: null,
@@ -51,6 +56,9 @@ export function initialView(model) {
51
56
  // Routed usage by day: every session's records as last read or written, and this session's own.
52
57
  usageStore: null,
53
58
  usageSession: null,
59
+ // Subagents by day: every session's records as last read or written, and this session's own.
60
+ subagentStore: null,
61
+ subagentSession: null,
54
62
  // The Usage tab's controls: the period (kept across sessions), the breakdown, the what-if view, the open row
55
63
  // (`<group>:<name>`), and whether Delete history waits for its confirmation.
56
64
  usagePeriod: 'session',
@@ -97,10 +105,45 @@ export function continuationView(config, decision, context) {
97
105
  };
98
106
  }
99
107
 
100
- // The view patch for a main reply's usage. `tier` is the routed tier that served it, else null; `activity` the
101
- // turn's activity as the view labels it, else null.
102
- // `route` is the (model, effort) the request went out with, so the switch count reads what served each reply.
103
- export function responseMetrics(view, response, tier, activity = null, route = null) {
108
+ // The view patch for a route switch at `at`: the routes it moved between with their tiers, and the activity the new
109
+ // route runs for (null outside activity routing `on`).
110
+ export const switchView = (from, to, activity, at) => ({
111
+ lastSwitch: { at, from: routeOf(from), to: routeOf(to), activity: activity ?? null },
112
+ });
113
+ const routeOf = (decision) => ({ tier: decision.tier ?? null, model: decision.model, effort: decision.effort ?? null });
114
+
115
+ // A reply that arrived `at` (ms) added to the session strip, `{ per, cells, from }`: each cell counts up to `per`
116
+ // replies by tier, `none` for one routing did not serve, and `from` is when the first reply arrived. A full strip
117
+ // merges each pair of cells first. The view lives as long as the Claude Code process, so after a restart the strip
118
+ // starts again while the session's usage record goes on: `from` tells the two apart.
119
+ export function addToStrip(strip, tier, at = null) {
120
+ const key = tier ?? 'none';
121
+ const from = strip?.from ?? at;
122
+ let per = strip?.per ?? 1;
123
+ let cells = strip?.cells ?? [];
124
+ const last = cells.at(-1);
125
+ if (last && Object.values(last).reduce((sum, n) => sum + n, 0) < per)
126
+ return { per, cells: [...cells.slice(0, -1), { ...last, [key]: (last[key] ?? 0) + 1 }], from };
127
+ if (cells.length >= STRIP_CELLS) {
128
+ cells = mergePairs(cells);
129
+ per *= 2;
130
+ }
131
+ return { per, cells: [...cells, { [key]: 1 }], from };
132
+ }
133
+
134
+ // Each pair of cells as one, its counts added; an odd last cell stays as it is.
135
+ export function mergePairs(cells) {
136
+ const merged = [];
137
+ for (let i = 0; i < cells.length; i += 2) {
138
+ const cell = { ...cells[i] };
139
+ for (const [key, n] of Object.entries(cells[i + 1] ?? {})) cell[key] = (cell[key] ?? 0) + n;
140
+ merged.push(cell);
141
+ }
142
+ return merged;
143
+ }
144
+
145
+ // The view patch for a main reply's usage that arrived `at` (ms). `tier` is the routed tier that served it, else null.
146
+ export function responseMetrics(view, response, tier, at = null) {
104
147
  const usage = response.usage;
105
148
  const counters = usage ? [usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens] : [];
106
149
  const inputTokens =
@@ -111,13 +154,12 @@ export function responseMetrics(view, response, tier, activity = null, route = n
111
154
  cacheWrite: usage?.cache_creation_input_tokens ?? null,
112
155
  inputTokens,
113
156
  outputTokens: usage?.output_tokens ?? null,
114
- // Appended together so the Usage trend can color each reading by its tier, and REPLIES letter it by activity.
157
+ // Appended together so the input trend can color each reading by its tier.
115
158
  ...(Number.isFinite(inputTokens)
116
159
  ? {
117
160
  history: [...(view?.history ?? []), inputTokens].slice(-HISTORY),
118
161
  tiers: [...(view?.tiers ?? []), tier ?? null].slice(-HISTORY),
119
- activities: [...(view?.activities ?? []), activity ?? null].slice(-HISTORY),
120
- routes: [...(view?.routes ?? []), route ?? null].slice(-HISTORY),
162
+ strip: addToStrip(view?.strip, tier, at),
121
163
  }
122
164
  : {}),
123
165
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexeiled/claude-router",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "Native Claude Code Mod: model and effort routing for the main conversation, advised by Jev, Clef, Clef Flash, Clef Omni, OpenAI or Ollama.",
5
5
  "license": "MIT",
6
6
  "author": "Alexei Ledenev",
package/types/index.d.ts CHANGED
@@ -114,8 +114,8 @@ declare module 'claude-code' {
114
114
  version: 1;
115
115
  since: number | null;
116
116
  }
117
- // Subagent routing counts for one agent type in one mode (lib/subagents.mjs). `differs`: agents the decision moved off
118
- // core's model; `choices`: agents by models key decided, or 'core'. USD over the priced requests.
117
+ // Subagent routing counts for one agent type (lib/subagents.mjs). `differs`: agents the decision moved off core's
118
+ // model. USD over the priced requests.
119
119
  interface RouterSubagentCounts {
120
120
  agents: number;
121
121
  differs: number;
@@ -125,7 +125,8 @@ declare module 'claude-code' {
125
125
  routedUsd: number;
126
126
  respawns: number;
127
127
  failures: number;
128
- choices: Record<string, number>;
128
+ // Agents by the model id they ran on; in `undated`, by the models key decided ('core': Claude Code's model).
129
+ models: Record<string, number>;
129
130
  }
130
131
  // Spawns that passed through for one reason, priced on the model they ran on.
131
132
  interface RouterSubagentPassed {
@@ -133,14 +134,22 @@ declare module 'claude-code' {
133
134
  requests: number;
134
135
  pricedRequests: number;
135
136
  usd: number;
137
+ models: Record<string, number>;
136
138
  }
137
- // Kept across sessions, one per session under store key 'subagents:v1:<session id>' or their sum in the view, since
138
- // the first agent after the last reset (ms).
139
+ // One local calendar day of subagents: routed types and pass-throughs by reason.
140
+ interface RouterSubagentDay {
141
+ routed: Record<string, RouterSubagentCounts>;
142
+ passed: Partial<
143
+ Record<'fork' | 'workflow' | 'explicit' | 'teammate' | 'unlisted' | 'pinned' | 'unknown', RouterSubagentPassed>
144
+ >;
145
+ }
146
+ // Kept across sessions, one per session under store key 'subagents:v1:<session id>' or their sum in the view, by day
147
+ // ('2026-10-13'), since the first agent after the last reset (ms). `undated` holds a record from before 1.14.0.
139
148
  interface RouterSubagentStore {
140
- version: 1;
149
+ version: 2;
141
150
  since: number | null;
142
- routed: { on: Record<string, RouterSubagentCounts> };
143
- passed: Partial<Record<'fork' | 'explicit' | 'teammate' | 'workflow' | 'unlisted', RouterSubagentPassed>>;
151
+ days: Record<string, RouterSubagentDay>;
152
+ undated?: RouterSubagentDay;
144
153
  }
145
154
  // One local calendar day of routed replies (lib/usage.mjs). `cells` by 'activity|tier|modelId@effort' hold, in order,
146
155
  // replies, routedUsd, yoursUsd, cheaperUsd, strongerUsd, switchUsd, inputTokens, cacheReadTokens, outputTokens.
@@ -196,17 +205,26 @@ declare module 'claude-code' {
196
205
  activityProbabilities?: Partial<Record<RouterActivityAnswer, number>> | null;
197
206
  history?: number[];
198
207
  tiers?: (RouterTier | null)[];
199
- // Aligned with `history` and `tiers`.
200
- activities?: (RouterActivity | null)[];
201
- // The (model, effort) each reply's request went out with, aligned with tiers; null where routing did not choose.
202
- routes?: (string | null)[];
208
+ // Every reply since Claude Code started the session by tier: each cell counts up to `per` replies, `none` for one
209
+ // routing did not serve; `from` is when the first one arrived (ms).
210
+ strip?: { per: number; cells: Partial<Record<RouterTier | 'none', number>>[]; from?: number | null } | null;
211
+ // The last route switch, at turn start or inside a turn: when, the routes it moved between with their tiers, and
212
+ // the activity the new route runs for.
213
+ lastSwitch?: {
214
+ at: number;
215
+ from: { tier: RouterTier | null; model: string; effort: string | null };
216
+ to: { tier: RouterTier | null; model: string; effort: string | null };
217
+ activity: RouterActivity | null;
218
+ } | null;
203
219
  activityStats?: RouterActivitySession | null;
204
220
  // The counts kept across sessions as last read or written.
205
221
  activityStore?: RouterActivityStore | null;
206
222
  activityMetrics?: RouterActivityMetrics | null;
207
223
  savings?: RouterSavingsSession | null;
208
224
  savingsStore?: RouterSavingsStore | null;
225
+ // Every session's subagent records as last read or written, and this session's own.
209
226
  subagentStore?: RouterSubagentStore | null;
227
+ subagentSession?: RouterSubagentStore | null;
210
228
  // Every session's usage records as last read or written, and this session's own.
211
229
  usageStore?: RouterUsageStore | null;
212
230
  usageSession?: RouterUsageStore | null;