@alexeiled/claude-router 1.5.1 → 1.6.1

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/config.mjs CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  export const TIERS = ['micro', 'low', 'medium', 'high'];
4
4
  export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
5
+ // What kind of work a turn does, named by what it produces. Closed: the classifier question is built for this set.
6
+ export const ACTIVITIES = ['code', 'debug', 'explore', 'plan', 'review', 'ops', 'docs'];
7
+ export const ACTIVITY_VALUES = [...ACTIVITIES, 'uncertain'];
8
+ // `off` asks nothing new and routes as 1.5; `shadow` asks and records but keeps the 1.5 route; `on` applies overrides.
9
+ export const ACTIVITY_MODES = ['off', 'shadow', 'on'];
10
+ const SONNET_MEDIUM = { model: 'sonnet', effort: 'medium' };
5
11
  export const DEFAULTS = {
6
12
  baselineTier: 'low',
7
13
  // Haiku 5.5 is the worker at `low` and `micro`: at high effort it scored above Sonnet 5.5 at low, and at xhigh near
@@ -15,6 +21,21 @@ export const DEFAULTS = {
15
21
  low: { model: 'haiku', effort: 'high' },
16
22
  micro: { model: 'haiku', effort: 'medium' },
17
23
  },
24
+ // Sparse per-field overrides of `routes` by activity; a missing activity, tier or field inherits the tier's route.
25
+ // Coding is where Haiku is weakest (Terminal-Bench 4.0: Haiku 5.5 39.2%, Sonnet 5.5 70.6%), so `low` work that
26
+ // edits, debugs, plans or reviews runs on Sonnet. On knowledge and terminal work Sonnet 5.5 matches Opus 5.5
27
+ // (GDPval-AA 1844 vs 1846; Terminal-Bench 70.6% vs 66.4%), so docs, ops and explore at `medium` run on Sonnet.
28
+ // Every cell reuses Sonnet at medium: one more cache than the base routes, not one per cell.
29
+ activityRouting: 'shadow',
30
+ activities: {
31
+ code: { low: SONNET_MEDIUM },
32
+ debug: { low: SONNET_MEDIUM },
33
+ explore: { medium: SONNET_MEDIUM },
34
+ plan: { low: SONNET_MEDIUM },
35
+ review: { low: SONNET_MEDIUM },
36
+ ops: { medium: SONNET_MEDIUM },
37
+ docs: { low: SONNET_MEDIUM, medium: SONNET_MEDIUM },
38
+ },
18
39
  // `id` selects the native model. List prices in USD per million tokens; `cacheRead` is absolute,
19
40
  // not a multiplier (Opus 5.5 reads at 0.05x input, the rest at the standard 0.1x). Haiku 5.5 lists the rates for
20
41
  // prompts up to 100k tokens; above that Anthropic charges 5x on input, output and cache read, so estimates run low there. A price change must also change
@@ -71,6 +92,9 @@ export const DEFAULTS = {
71
92
  // Ceiling on a cold cache write to a `credits` model. No default model bills credits, so this is
72
93
  // inert until a user adds one in router.json; a Claude Code turn starts near 100k tokens.
73
94
  cashCapUsd: 2,
95
+ // An activity applies only above this probability; below it the tier's base route runs. Not tuned on any
96
+ // classifier yet: calibrate from the probe set and shadow stats.
97
+ activityMass: 0.6,
74
98
  },
75
99
  // The active entry of `classifiers`. `api` names the wire protocol (CLASSIFIER_APIS); a user entry without one speaks
76
100
  // `system-one`. `keyOption` names the plugin option that holds the bearer key, or null for no key (a local server);
@@ -224,6 +248,90 @@ export function withRoutes(file, draft) {
224
248
  };
225
249
  }
226
250
 
251
+ // Activity cells are sparse: a missing field inherits the tier's route, so `effort: undefined` and `effort: null`
252
+ // differ. A null or missing cell is no override.
253
+ export const sameCell = (a, b) => (a && b ? a.model === b.model && a.effort === b.effort : !a === !b);
254
+ const cellOf = (activities, activity, tier) => activities?.[activity]?.[tier];
255
+
256
+ // The activity side of a route draft, with the effectiveRoutes rule: a cell or the mode counts as edited when it
257
+ // differs from the draft's `base`; everything else follows `current`. A draft built without `activities` or
258
+ // `activityRouting` edits none. A null cell is a removed override.
259
+ export function effectiveActivities(draft, current) {
260
+ const { base } = draft;
261
+ const activityRouting =
262
+ draft.activityRouting === undefined || draft.activityRouting === base.activityRouting
263
+ ? current.activityRouting
264
+ : draft.activityRouting;
265
+ if (!draft.activities) return { activities: current.activities, activityRouting };
266
+ const activities = {};
267
+ for (const activity of ACTIVITIES) {
268
+ for (const tier of TIERS) {
269
+ const edited = cellOf(draft.activities, activity, tier);
270
+ const cell = sameCell(edited, cellOf(base.activities, activity, tier))
271
+ ? cellOf(current.activities, activity, tier)
272
+ : edited;
273
+ if (cell) activities[activity] = { ...activities[activity], [tier]: cell };
274
+ }
275
+ }
276
+ return { activities, activityRouting };
277
+ }
278
+
279
+ // The route draft after a pane edit of cell (activity, tier): `kind` is 'model' (value: alias), 'effort' (value:
280
+ // effort or null), 'add' or 'remove'. A model change keeps the effort when the new model accepts it, as for routes.
281
+ // An added cell starts from the built-in override, so re-adding a removed default restores it, else from the base
282
+ // route, which the pane flags as having no effect until edited. An edit that lands on the route the saved cell
283
+ // already resolves to is the saved cell, so a partial cell is not rewritten with the fields it inherits.
284
+ export function editActivity(draft, current, activity, tier, kind, value = null) {
285
+ const config = { ...current, ...effectiveRoutes(draft, current), ...effectiveActivities(draft, current) };
286
+ const route = resolveRoute(config, tier, activity);
287
+ let cell = {
288
+ model: () => ({ model: value, effort: config.models[value]?.efforts.includes(route.effort) ? route.effort : null }),
289
+ effort: () => ({ model: route.model, effort: value }),
290
+ add: () => ({ ...(cellOf(DEFAULTS.activities, activity, tier) ?? resolveRoute(config, tier)) }),
291
+ remove: () => null,
292
+ }[kind]();
293
+ const saved = cellOf(draft.base.activities, activity, tier);
294
+ const at = (c) => resolveRoute({ ...config, activities: { [activity]: { [tier]: c } } }, tier, activity);
295
+ if (cell && saved && sameRoute(at(cell), at(saved))) cell = { ...saved };
296
+ const activities = draft.activities ?? draft.base.activities;
297
+ return { ...draft, activities: { ...activities, [activity]: { ...activities[activity], [tier]: cell } } };
298
+ }
299
+
300
+ // The router.json `file` with the activity cells and mode the person edited in `draft`; untouched cells stay as the
301
+ // file has them. Only differences from DEFAULTS are written. A removed built-in override is written as the tier's
302
+ // route in `file` (the merge would bring the built-in back otherwise), so call this after withRoutes.
303
+ export function withActivities(file, draft) {
304
+ const { base } = draft;
305
+ const { activities: kept = {}, activityRouting: keptMode, ...rest } = file;
306
+ const activities = {};
307
+ for (const activity of ACTIVITIES) {
308
+ for (const tier of TIERS) {
309
+ const cell = cellOf(draft.activities, activity, tier);
310
+ const preset = cellOf(DEFAULTS.activities, activity, tier);
311
+ let written;
312
+ if (!draft.activities || sameCell(cell, cellOf(base.activities, activity, tier)))
313
+ written = cellOf(kept, activity, tier);
314
+ else if (cell) written = sameCell(cell, preset) ? undefined : cell;
315
+ else if (preset) {
316
+ const route = { ...DEFAULTS.routes[tier], ...file.routes?.[tier] };
317
+ written = { model: route.model, effort: route.effort ?? null };
318
+ }
319
+ if (written) activities[activity] = { ...activities[activity], [tier]: written };
320
+ }
321
+ }
322
+ const mode =
323
+ draft.activityRouting === undefined || draft.activityRouting === base.activityRouting
324
+ ? keptMode
325
+ : draft.activityRouting === DEFAULTS.activityRouting
326
+ ? undefined
327
+ : draft.activityRouting;
328
+ return {
329
+ ...rest,
330
+ ...(Object.keys(activities).length ? { activities } : {}),
331
+ ...(mode === undefined ? {} : { activityRouting: mode }),
332
+ };
333
+ }
334
+
227
335
  // The pane's policy controls and the router.json fields they stand for. The classifier deadline saves on its own.
228
336
  const TUNING_FIELDS = {
229
337
  downgradeVotes: ['policy', 'downgradeVotes'],
@@ -267,8 +375,15 @@ export function rank(tier) {
267
375
  return TIERS.indexOf(tier);
268
376
  }
269
377
 
270
- // The model entry a tier routes to.
271
- export const routeModel = (config, tier) => config.models[config.routes[tier].model];
378
+ // The (model, effort) a tier runs on for an activity: the tier's route with that activity's sparse override on top.
379
+ // A null activity (off, uncertain, failed) resolves to the tier's route.
380
+ export function resolveRoute(config, tier, activity = null) {
381
+ const route = { ...config.routes[tier], ...config.activities?.[activity]?.[tier] };
382
+ return { model: route.model, effort: route.effort ?? null };
383
+ }
384
+
385
+ // The model entry a route runs on.
386
+ export const routeSpec = (config, route) => config.models[route.model];
272
387
 
273
388
  // Whether a Claude Code version, such as 2.1.289 or a 2.1.290-beta build, runs the router: 2.1.289 or newer.
274
389
  export function supportedVersion(version) {
@@ -306,11 +421,19 @@ function checkShape(file) {
306
421
  if (file && typeof file === 'object' && Object.hasOwn(file, 'jev'))
307
422
  throw new Error(`router.json uses the 1.1 jev section; ${MIGRATION_HINT}`);
308
423
  checkObject(file, 'router.json', Object.keys(DEFAULTS));
309
- const { routes, models, cache, policy, classifiers, context } = file;
424
+ const { routes, activities, models, cache, policy, classifiers, context } = file;
310
425
  if (routes !== undefined) {
311
426
  checkObject(routes, 'routes', TIERS);
312
427
  for (const [tier, route] of Object.entries(routes)) checkObject(route, `routes.${tier}`, ROUTE_KEYS);
313
428
  }
429
+ if (activities !== undefined) {
430
+ checkObject(activities, 'activities', ACTIVITIES);
431
+ for (const [activity, tiers] of Object.entries(activities)) {
432
+ checkObject(tiers, `activities.${activity}`, TIERS);
433
+ for (const [tier, route] of Object.entries(tiers))
434
+ checkObject(route, `activities.${activity}.${tier}`, ROUTE_KEYS);
435
+ }
436
+ }
314
437
  if (models !== undefined) {
315
438
  checkObject(models, 'models');
316
439
  for (const [alias, model] of Object.entries(models)) checkObject(model, `models.${alias}`, MODEL_KEYS);
@@ -350,6 +473,17 @@ function validate(config) {
350
473
  if (route.effort != null && !EFFORTS.includes(route.effort))
351
474
  throw new Error(`routes.${tier}.effort must be one of ${EFFORTS.join(', ')} or null`);
352
475
  }
476
+ if (!ACTIVITY_MODES.includes(config.activityRouting))
477
+ throw new Error(`activityRouting must be one of ${ACTIVITY_MODES.join(', ')}`);
478
+ for (const [activity, tiers] of Object.entries(config.activities)) {
479
+ for (const [tier, { model, effort }] of Object.entries(tiers)) {
480
+ const at = `activities.${activity}.${tier}`;
481
+ if (model !== undefined && !(typeof model === 'string' && Object.hasOwn(config.models, model)))
482
+ throw new Error(`${at}.model is not in models`);
483
+ if (effort != null && !EFFORTS.includes(effort))
484
+ throw new Error(`${at}.effort must be one of ${EFFORTS.join(', ')} or null`);
485
+ }
486
+ }
353
487
  for (const [alias, model] of Object.entries(config.models)) {
354
488
  for (const field of ['input', 'cacheRead', 'contextWindow']) {
355
489
  if (!Number.isFinite(model[field]) || model[field] < 0)
@@ -365,7 +499,7 @@ function validate(config) {
365
499
  }
366
500
  if (!TIERS.includes(config.baselineTier)) throw new Error(`baselineTier must be one of ${TIERS.join(', ')}`);
367
501
  const p = config.policy;
368
- for (const field of ['upgradeBase', 'jumpConfidence', 'downgradeMass', 'continuationMass']) {
502
+ for (const field of ['upgradeBase', 'jumpConfidence', 'downgradeMass', 'continuationMass', 'activityMass']) {
369
503
  if (!(isNumber(p[field], 0) && p[field] <= 1)) throw new Error(`policy.${field} must be between 0 and 1`);
370
504
  }
371
505
  for (const field of ['upgradeVotes', 'downgradeVotes', 'downgradeHorizonTurns', 'escalationHoldTurns']) {
package/lib/cost.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { EFFORTS, routeModel } from './config.mjs';
1
+ import { EFFORTS, routeSpec } from './config.mjs';
2
2
 
3
3
  export function cacheKey(modelId, effort) {
4
4
  return effort ? `${modelId}@${effort}` : modelId;
@@ -16,17 +16,17 @@ export function nextContextTokens(facts) {
16
16
  return Math.max(previous, Number.isFinite(facts.contextTokens) ? facts.contextTokens : 0);
17
17
  }
18
18
 
19
- export function routeEffort(config, tier, sentEffort) {
20
- const route = config.routes[tier];
21
- const model = routeModel(config, tier);
19
+ // Functions below take a route { model, effort }, not a tier: one tier can run on different routes.
20
+ export function routeEffort(config, route, sentEffort) {
21
+ const model = routeSpec(config, route);
22
22
  if (model.efforts.length === 0) return null;
23
23
  if (route.effort) return clampEffort(route.effort, model.efforts);
24
24
  if (typeof sentEffort === 'number' && Number.isFinite(sentEffort)) return sentEffort;
25
25
  return clampEffort(sentEffort, model.efforts);
26
26
  }
27
27
 
28
- export function routeCacheKey(config, tier, sentEffort) {
29
- return cacheKey(routeModel(config, tier).id, routeEffort(config, tier, sentEffort));
28
+ export function routeCacheKey(config, route, sentEffort) {
29
+ return cacheKey(routeSpec(config, route).id, routeEffort(config, route, sentEffort));
30
30
  }
31
31
 
32
32
  export function isWarm(state, now, cache) {
@@ -40,9 +40,9 @@ export function cacheState(state, now, cache) {
40
40
  }
41
41
 
42
42
  // Bounds are scenarios, never an independent ledger. Unknown incumbent cache can still be served.
43
- export function inputBounds(config, tier, tokens, facts, now) {
44
- const model = routeModel(config, tier);
45
- const state = facts.models[routeCacheKey(config, tier, facts.effort)];
43
+ export function inputBounds(config, route, tokens, facts, now) {
44
+ const model = routeSpec(config, route);
45
+ const state = facts.models[routeCacheKey(config, route, facts.effort)];
46
46
  const prefix = Math.min(state?.prefixTokens ?? tokens, tokens);
47
47
  const fresh = isWarm(state, now, config.cache);
48
48
  const maximumWrite = model.input * Math.max(...Object.values(config.cache.writeMultiplier));
@@ -63,9 +63,21 @@ export function switchingTaxUsd(config, candidate, incumbent, facts, now) {
63
63
  );
64
64
  }
65
65
 
66
+ // The next request on `candidate` against `incumbent` as a range: the input bounds crossed, plus the output difference
67
+ // at the last reply's length when both routes have an output price, as shadowEconomics compares.
68
+ export function nextTurnRange(config, candidate, incumbent, facts, now) {
69
+ const tokens = nextContextTokens(facts);
70
+ const proposed = inputBounds(config, candidate, tokens, facts, now);
71
+ const current = inputBounds(config, incumbent, tokens, facts, now);
72
+ const [to, from] = [routeSpec(config, candidate), routeSpec(config, incumbent)];
73
+ const outputTokens = facts.lastRequest?.outputTokens ?? 0;
74
+ const output = to.output > 0 && from.output > 0 ? ((to.output - from.output) * outputTokens) / 1e6 : 0;
75
+ return { minUsd: proposed.min - current.max + output, maxUsd: proposed.max - current.min + output };
76
+ }
77
+
66
78
  export function shadowEconomics(config, candidate, incumbent, facts, now) {
67
- const proposed = routeModel(config, candidate);
68
- const current = routeModel(config, incumbent);
79
+ const proposed = routeSpec(config, candidate);
80
+ const current = routeSpec(config, incumbent);
69
81
  if (!(proposed.output > 0) || !(current.output > 0)) return null;
70
82
  const tokens = nextContextTokens(facts);
71
83
  const outputTokens = facts.lastRequest?.outputTokens ?? 0;
package/lib/display.mjs CHANGED
@@ -1,5 +1,14 @@
1
- import { activeClassifier, CLASSIFIER_OPTIONS, endpointSettings, routeModel } from './config.mjs';
2
- import { tierForModel } from './route.mjs';
1
+ import { acceptActivity } from './activity.mjs';
2
+ import { readStore, storeSummary } from './activity-stats.mjs';
3
+ import {
4
+ activeClassifier,
5
+ CLASSIFIER_OPTIONS,
6
+ endpointSettings,
7
+ resolveRoute,
8
+ routeSpec,
9
+ sameRoute,
10
+ } from './config.mjs';
11
+ import { cellForModel, isSameModel } from './route.mjs';
3
12
 
4
13
  // Cost order, cheapest first, so the colors read as a scale. Hex values: every surface draws them.
5
14
  export const TIER_COLOR = { micro: '#5fd7af', low: '#5f9fe0', medium: '#d7af5f', high: '#e0708a' };
@@ -19,6 +28,15 @@ export function modelName(id) {
19
28
  export const routeLabel = (model, effort) =>
20
29
  `${modelName(model)}${effort === null || effort === undefined ? '' : ` · ${effort}`}`;
21
30
 
31
+ // A configured route by its model's name; a null effort is the session's, and a model without efforts shows none.
32
+ export function routeName(config, route) {
33
+ const model = config.models[route.model];
34
+ return `${modelName(model.id)}${model.efforts.length ? ` · ${route.effort ?? 'session'}` : ''}`;
35
+ }
36
+
37
+ // One letter per activity for the REPLIES strip: `docs` is `w` (writing), since `debug` has `d`.
38
+ export const ACTIVITY_LETTER = { code: 'c', debug: 'd', explore: 'e', plan: 'p', review: 'r', ops: 'o', docs: 'w' };
39
+
22
40
  // Changes of tier between consecutive replies; a reply routing did not choose breaks no run.
23
41
  export const switchCount = (tiers) => tiers.slice(1).filter((tier, i) => tier && tiers[i] && tier !== tiers[i]).length;
24
42
 
@@ -42,6 +60,9 @@ export const REASONS = {
42
60
  'context-unknown': 'context is not measured reliably',
43
61
  'model-unavailable': 'the requested model is not available',
44
62
  pinned: 'one-turn model pin',
63
+ 'activity-up': 'the activity needs a stronger route',
64
+ 'activity-down': 'a cheaper route fits the activity and pays back its cache',
65
+ 'activity-pending': 'a route for the activity does not pay back yet',
45
66
  };
46
67
 
47
68
  // The active decision model behind the router. Named in the UI only where it explains a reading or a failure.
@@ -125,8 +146,83 @@ export const SHORT_REASONS = {
125
146
  'native-fallback': '! fallback',
126
147
  pinned: '⏵ pinned',
127
148
  interrupted: 'interrupted',
149
+ 'activity-up': '↗ {activity}',
150
+ 'activity-down': '↘ {activity}',
151
+ 'activity-pending': '… {activity}: not worth a switch',
128
152
  };
129
153
 
154
+ // The band's words for `reason`; an activity move names the activity it is about, `base` for the tier's own route.
155
+ export const shortReason = (reason, activity) =>
156
+ (SHORT_REASONS[reason] ?? reason ?? '').replace('{activity}', activity ?? 'base');
157
+
158
+ // The activity a reason is about: the applied one for a move, and for a refused move the classifier's activity when
159
+ // it carries enough mass to apply, else null (the tier's base route).
160
+ export function reasonActivity(config, view) {
161
+ if (view.reason !== 'activity-pending') return view.activity ?? null;
162
+ return acceptActivity(config, {
163
+ activity: { choice: view.activityChoice, probabilities: view.activityProbabilities },
164
+ });
165
+ }
166
+
167
+ // The classifier's activity answer: its choice with the share it got and the two runners-up, or null when there is
168
+ // none.
169
+ export function activityReading(view) {
170
+ const choice = view.activityChoice ?? view.activity ?? null;
171
+ if (!choice) return null;
172
+ const probabilities = Object.entries(view.activityProbabilities ?? {}).filter(([, p]) => Number.isFinite(p));
173
+ const share = probabilities.find(([name]) => name === choice)?.[1];
174
+ const others = probabilities
175
+ .filter(([name, p]) => name !== choice && p > 0)
176
+ .sort((a, b) => b[1] - a[1])
177
+ .slice(0, 2)
178
+ .map(([name, p]) => `${name} ${percent(p)}`);
179
+ return { choice, share: Number.isFinite(share) ? percent(share) : null, others };
180
+ }
181
+
182
+ // The route the turn's cell resolves to, against the tier's base route: `on` names the override, `shadow` what `on`
183
+ // would run beside the route in use. Null in `off`, or before a turn has a tier.
184
+ export function activityRouteText(config, view) {
185
+ const mode = config.activityRouting;
186
+ if (mode === 'shadow') {
187
+ const would = view.wouldRoute;
188
+ if (!would?.tier) return null;
189
+ const current = view.selectedModel ?? view.nativeModel;
190
+ const same = isSameModel(would.model, current) && (would.effort ?? null) === (view.effort ?? null);
191
+ return (
192
+ `${would.tier}${would.activity ? ` + ${would.activity}` : ''} would use ${routeLabel(would.model, would.effort)}` +
193
+ ` (shadow; ${same ? 'same route' : `using ${routeLabel(current, view.effort)}`})`
194
+ );
195
+ }
196
+ if (mode !== 'on' || !view.tier) return null;
197
+ const cell = `${view.tier}${view.activity ? ` + ${view.activity}` : ''}`;
198
+ const route = resolveRoute(config, view.tier, view.activity ?? null);
199
+ const base = resolveRoute(config, view.tier);
200
+ return sameRoute(route, base)
201
+ ? `${cell} → ${routeName(config, route)} (base)`
202
+ : `${cell} → ${routeName(config, route)} (override) base: ${routeName(config, base)}`;
203
+ }
204
+
205
+ // The activity lines of /router without a UI surface: "Activity: ops (81%)" and the resolved route. None in `off`.
206
+ export function activityDetailLines(config, view) {
207
+ if (config.activityRouting === 'off') return [];
208
+ const reading = activityReading(view);
209
+ const route = activityRouteText(config, view);
210
+ return [
211
+ `Activity: ${reading ? `${reading.choice}${reading.share ? ` (${reading.share})` : ''}` : 'none yet'}`,
212
+ ...(route ? [`Route: ${route}`] : []),
213
+ ];
214
+ }
215
+
216
+ // The tool agreement kept across sessions, for `/router` without a surface. The view holds the store as last read.
217
+ export function storeAgreementLine(view) {
218
+ const { agreement, focus } = storeSummary(readStore(view.activityStore));
219
+ const share = ({ matched, total }) => `${matched} of ${total}`;
220
+ if (!agreement.total) return 'Agreement across sessions: no labelled turns yet';
221
+ const all = `${share(agreement)} turns (${percent(agreement.matched / agreement.total)})`;
222
+ const code = focus.total ? ` · code/ops/explore ${share(focus)} (${percent(focus.matched / focus.total)})` : '';
223
+ return `Agreement across sessions: ${all}${code}`;
224
+ }
225
+
130
226
  export const GATEWAY_SETTINGS = 'v0.8 gateway settings remain · see /router';
131
227
  export const GATEWAY_CLEANUP = [
132
228
  'Remove from settings.json, then restart: model jev-router[1m], its modelPicker row,',
@@ -154,8 +250,8 @@ export function bar(value, maximum, width = 16) {
154
250
 
155
251
  export function usageMetrics(config, view, usage) {
156
252
  const model = view.actualModel ?? view.selectedModel ?? view.nativeModel;
157
- const tier = tierForModel(config, model);
158
- const spec = tier ? routeModel(config, tier) : null;
253
+ const cell = cellForModel(config, model);
254
+ const spec = cell ? routeSpec(config, resolveRoute(config, cell.tier, cell.activity)) : null;
159
255
  const window = spec?.contextWindow ?? null;
160
256
  const observed = Number.isFinite(usage?.context?.tokens) ? usage.context.tokens : null;
161
257
  const candidates = [view.contextTokens, observed === null ? null : observed + (view.outputTokens ?? 0)].filter(
package/lib/facts.mjs CHANGED
@@ -81,3 +81,51 @@ function textOf(content) {
81
81
  .join('\n')
82
82
  .trim();
83
83
  }
84
+
85
+ const FILE_EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
86
+ const DOC_PATH = /\.(?:md|mdx|rst|txt)$|(?:^|[\\/])docs[\\/]/i;
87
+ const READ_COMMANDS = new Set(['cat', 'ls', 'grep', 'rg', 'find', 'head', 'tail', 'cd']);
88
+ const READ_GIT = new Set(['status', 'log', 'diff', 'show']);
89
+ const SEPARATORS = /&&|\|\||[;|&\n]/;
90
+ // find can run or delete what it finds.
91
+ const WRITING_FIND = /\s-(?:exec|execdir|ok|okdir|delete)\b/;
92
+
93
+ // The index of the last user prompt, a user message that is not a tool result: where the latest turn starts. -1 when
94
+ // there is none.
95
+ export function promptIndex(messages) {
96
+ return messages.findLastIndex(
97
+ (m) => m?.role === 'user' && !blocks(m.content).some((block) => block?.type === 'tool_result'),
98
+ );
99
+ }
100
+
101
+ // The bucket of a finished turn, from the tool calls the assistant made after the user message at `fromIndex`:
102
+ // code, docs, ops, read or talk. First match wins; only names and paths are read, no text is kept.
103
+ export function observedActivity(messages, fromIndex) {
104
+ const calls = [];
105
+ for (let i = fromIndex + 1; i < messages.length; i += 1)
106
+ if (messages[i]?.role === 'assistant')
107
+ for (const block of blocks(messages[i].content)) if (block.type === 'tool_use') calls.push(block);
108
+ const edited = calls.filter((c) => FILE_EDIT_TOOLS.has(c.name));
109
+ if (edited.length > 0) return edited.every((c) => DOC_PATH.test(editPath(c))) ? 'docs' : 'code';
110
+ if (calls.some((c) => c.name === 'Bash' && !readsOnly(c.input?.command))) return 'ops';
111
+ return calls.length > 0 ? 'read' : 'talk';
112
+ }
113
+
114
+ function editPath(call) {
115
+ const path = call.input?.file_path ?? call.input?.notebook_path;
116
+ return typeof path === 'string' ? path : '';
117
+ }
118
+
119
+ // Every command of a pipeline or list only reads. Command substitution runs inside double quotes, so it is looked for
120
+ // in the whole command; a literal one in single quotes counts too. Quoted text is then blanked, so a `;` or `>` inside
121
+ // a pattern is not taken for shell syntax. Anything unrecognised counts as running something.
122
+ function readsOnly(command) {
123
+ if (typeof command !== 'string' || /`|\$\(/.test(command)) return false;
124
+ const bare = command.replace(/'[^']*'|"[^"]*"/g, '""').replace(/\d?>\s*&\d|\d?>\s*\/dev\/null/g, '');
125
+ if (/[<>]/.test(bare) || WRITING_FIND.test(bare)) return false;
126
+ return bare.split(SEPARATORS).every((part) => {
127
+ if (!part.trim()) return true;
128
+ const [name, sub] = part.trim().split(/\s+/);
129
+ return name === 'git' ? READ_GIT.has(sub) : READ_COMMANDS.has(name);
130
+ });
131
+ }