@alexeiled/claude-router 1.20.0 → 1.21.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/display.mjs CHANGED
@@ -3,7 +3,6 @@ import { readMetrics, readStore, storeSummary, UNPRICED_CAUSES } from './activit
3
3
  import {
4
4
  activeClassifier,
5
5
  CLASSIFIER_OPTIONS,
6
- DEFAULTS,
7
6
  endpointSettings,
8
7
  resolveRoute,
9
8
  routeSpec,
@@ -11,12 +10,13 @@ import {
11
10
  TIERS,
12
11
  } from './config.mjs';
13
12
  import { ratesAt } from './cost.mjs';
13
+ import { periodCost } from './costs.mjs';
14
14
  import { applyMode, modeLabel, modeRoute } from './modes.mjs';
15
15
  import { PROBE_RESULTS } from './probe-results.mjs';
16
- import { PROVIDER_DEFAULTS } from './providers.mjs';
17
16
  import { cellForModel } from './route.mjs';
18
- import { modelSpec, readout } from './savings.mjs';
19
- import { allTime, breakdown, periodRange, readUsage, summarize, withReplies } from './usage.mjs';
17
+ import { modelSpec } from './savings.mjs';
18
+ import { readSubagentStore, summarizeSubagents } from './subagents.mjs';
19
+ import { periodRange, readUsage, summarize, withReplies } from './usage.mjs';
20
20
 
21
21
  // Cost order, cheapest first, so the colors read as a scale. Hex values: every surface draws them.
22
22
  export const TIER_COLOR = { micro: '#5fd7af', low: '#5f9fe0', medium: '#d7af5f', high: '#e0708a' };
@@ -72,11 +72,20 @@ export const NOT_A_TIER_REASON = 'not a routing tier';
72
72
 
73
73
  export function modelName(id) {
74
74
  if (!id) return 'no response yet';
75
+ if (id.startsWith('claude-'))
76
+ return id
77
+ .replace(/^claude-/, '')
78
+ .replace(/-([0-9])-([0-9])(-\d{8})?$/, ' $1.$2')
79
+ .replace(/^./, (c) => c.toUpperCase());
80
+ // A provider id, `deepseek-flash[1m]` → "DeepSeek Flash": the `[1m]` context suffix is client metadata, not a name.
75
81
  return id
76
- .replace(/^claude-/, '')
77
- .replace(/-([0-9])-([0-9])(-\d{8})?$/, ' $1.$2')
78
- .replace(/^./, (c) => c.toUpperCase());
82
+ .replace(/\[[^\]]*\]$/, '')
83
+ .split('-')
84
+ .map((word) => BRANDS[word.toLowerCase()] ?? word.replace(/^./, (c) => c.toUpperCase()))
85
+ .join(' ');
79
86
  }
87
+ // Provider names whose casing a capital first letter gets wrong.
88
+ const BRANDS = { deepseek: 'DeepSeek', glm: 'GLM', minimax: 'MiniMax', mimo: 'MiMo' };
80
89
 
81
90
  // "Opus 5.5 · high"; a model with no effort reading shows its name alone.
82
91
  export const routeLabel = (model, effort) =>
@@ -171,48 +180,42 @@ const CLASSIFIER_ERRORS = {
171
180
  export const classifierWarns = (error) => CLASSIFIER_ERRORS[error]?.warn === true;
172
181
  // No error, or one outside the table, times the wait.
173
182
  export const classifierTimed = (error) => CLASSIFIER_ERRORS[error]?.timed !== false;
174
- // One or two words for the band; REASONS holds the sentence the pane shows.
183
+ // A glyph and at most three words for every reason: the band, the pane's Why, the switch toast and the subagent row
184
+ // say the same. The glyph is the direction: ↑ stronger, ↓ cheaper, = stays, … waits, ! fault, ⏵ pin. REASONS holds the
185
+ // sentence /router prints.
175
186
  export const SHORT_REASONS = {
176
187
  ready: 'ready',
177
188
  'same-tier': '= fits',
178
189
  'no-advice': '= no advice',
179
- uncertain: '= uncertain',
180
- upgrade: '↑ upgrade',
181
- jump: '↑ jump',
182
- downgrade: '↓ downgrade',
183
- 'upgrade-pending': '… waiting to go up',
184
- 'downgrade-pending': '… waiting to go down',
185
- 'downgrade-held': '… down after a checkpoint',
186
- hold: '= holding',
190
+ uncertain: '= unsure',
191
+ upgrade: '↑ needs stronger',
192
+ jump: '↑ clearly stronger',
193
+ downgrade: '↓ cheaper fits',
194
+ 'upgrade-pending': '… stronger, waiting',
195
+ 'downgrade-pending': '… cheaper, waiting',
196
+ 'downgrade-held': '… cheaper after a check',
197
+ hold: '= holding after ↑',
187
198
  escalation: '↑ tool errors',
188
- 'cash-gate': '= cash cap',
189
- 'context-fit': '↑ context',
199
+ 'cash-gate': '= cache cap',
200
+ 'context-fit': '↑ needs context',
190
201
  'context-unknown': '= context unknown',
191
202
  'context-full': '! context full',
192
203
  'model-unavailable': '! model unavailable',
193
204
  'native-fallback': '! fallback',
194
205
  pinned: '⏵ pinned',
195
- interrupted: 'interrupted',
196
- 'activity-up': '↗ {activity}',
197
- 'activity-down': '↘ {activity}',
198
- 'activity-pending': '… {activity}: not worth a switch',
206
+ manual: '= routing skipped',
207
+ 'routing off': 'routing off',
208
+ interrupted: '! interrupted',
209
+ 'activity-up': '↑ {activity}',
210
+ 'activity-down': '↓ {activity}',
211
+ 'activity-pending': '… {activity}, not worth a switch',
199
212
  };
200
213
 
201
- // What the band calls each activity: the verb for the work, as Claude Code names a turn's action.
202
- const ACTIVITY_VERB = {
203
- code: 'coding',
204
- debug: 'debugging',
205
- explore: 'exploring',
206
- plan: 'planning',
207
- review: 'reviewing',
208
- ops: 'running',
209
- docs: 'documenting',
210
- };
211
- export const activityVerb = (activity) => ACTIVITY_VERB[activity] ?? activity;
212
-
214
+ // Whether the band's words for `reason` already name the activity, so the activity is not said twice.
215
+ export const reasonNamesActivity = (reason) => SHORT_REASONS[reason]?.includes('{activity}') ?? false;
213
216
  // The band's words for `reason`; an activity move names the activity it is about, `base` for the tier's own route.
214
217
  export const shortReason = (reason, activity) =>
215
- (SHORT_REASONS[reason] ?? reason ?? '').replace('{activity}', activity ? activityVerb(activity) : 'base');
218
+ (SHORT_REASONS[reason] ?? reason ?? '').replace('{activity}', activity ?? 'base');
216
219
 
217
220
  // The activity a reason is about: the applied one for a move, and for a refused move the classifier's activity when
218
221
  // it carries enough mass to apply, else null (the tier's base route).
@@ -270,7 +273,7 @@ export function whyText(configured, view) {
270
273
  routeSpec(config, route).id === view.selectedModel && (route.effort === null || route.effort === view.effort);
271
274
  if (!moved && view.selectedModel && !runs) return reason;
272
275
  return activity
273
- ? `${activityVerb(activity)} at ${view.tier} runs on ${routeName(config, route)}`
276
+ ? `${activity} at ${view.tier} runs on ${routeName(config, route)}`
274
277
  : `${view.tier} runs on its base route, ${routeName(config, route)}`;
275
278
  }
276
279
 
@@ -314,7 +317,7 @@ export function probeText(config, id) {
314
317
  return `activity probe ${probe.correct}/${probe.probes} · p95 ${probe.p95Ms} ms · ${day}`;
315
318
  }
316
319
 
317
- // Routing vs your model: less is green, more is amber, not red: a stronger model is a purchase, not a fault.
320
+ // Routing vs no routing: less is green, more is amber, not red: a stronger model is a purchase, not a fault.
318
321
  export const SAVINGS_COLOR = { less: '#6fcf97', more: '#f0b429' };
319
322
 
320
323
  // "$6.40"; signed for a difference or a part: "−$1.84", "+$0.47", "$0.00".
@@ -322,23 +325,7 @@ export const usd = (value) => `$${Math.abs(value).toFixed(2)}`;
322
325
  export const signedUsd = (value) => (value === 0 ? '$0.00' : `${value < 0 ? '−' : '+'}${usd(value)}`);
323
326
  export const savingsColor = (value) => (value < 0 ? SAVINGS_COLOR.less : value > 0 ? SAVINGS_COLOR.more : undefined);
324
327
 
325
- // The difference against your model: "−22%", "+15%", or "×5.0" once routing cost twice your model or more. Null when
326
- // it rounds to nothing or there is nothing to compare.
327
- export function differenceShare(r) {
328
- if (r.differenceUsd === 0 || r.share === null) return null;
329
- if (r.ratio >= 2) return `×${r.ratio.toFixed(1)}`;
330
- const share = Math.round(r.share * 100);
331
- return share === 0 ? null : `${share < 0 ? '−' : '+'}${Math.abs(share)}%`;
332
- }
333
-
334
- // "−$1.84 (−22%)".
335
- export const savingsAmount = (r) => {
336
- const share = differenceShare(r);
337
- return `${signedUsd(r.differenceUsd)}${share ? ` (${share})` : ''}`;
338
- };
339
-
340
328
  export const yourModel = (view) => routeLabel(view.nativeModel, view.nativeEffort);
341
- export const sinceDate = (ms) => new Date(ms).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
342
329
  const replyCount = (n, what = 'replies') => `${n} ${n === 1 ? what.replace(/ies$/, 'y') : what}`;
343
330
 
344
331
  // A usage record with the running turns' replies (view.usageLive) added, which every readout counts: the band, the
@@ -347,88 +334,6 @@ export const liveUsage = (view, record) => withReplies(readUsage(record), view.u
347
334
  // This session's routed replies, the running turns' included.
348
335
  export const sessionUsage = (view, now) => summarize(liveUsage(view, view.usageSession), periodRange('session', now));
349
336
 
350
- // Observed spend is valid even when a counterfactual cache history cannot be priced. With a billing split, each
351
- // billing's spend: plan and credits are not added.
352
- export const observedUsageText = (observed, split = null) =>
353
- `observed ${split ? billingCosts(split, 'observedUsd') : usd(observed.routedUsd)} · ${observed.replies} repl${observed.replies === 1 ? 'y' : 'ies'} · comparison unavailable`;
354
-
355
- // Plan and credits are different money: on a Claude plan the list-price dollars stand for quota, credits are paid.
356
- export const BILLINGS = ['credits', 'plan'];
357
- // The billing of the model an API id runs on: the selected profile's entry, else a built-in profile's, so a period
358
- // that holds another profile's sessions still reads. Null for a model no profile prices.
359
- const BUILT_IN_PROFILES = [DEFAULTS, ...Object.values(PROVIDER_DEFAULTS)];
360
- export function billingOf(config, id) {
361
- for (const profile of [config, ...BUILT_IN_PROFILES]) {
362
- const spec = modelSpec(profile, id);
363
- if (spec) return spec.billing;
364
- }
365
- return null;
366
- }
367
- const wholeCents = (value) => Math.round(value * 100) / 100;
368
-
369
- // A summary told per billing when its replies ran on, or are compared with, both plan and credits models: one sum
370
- // would add quota to cash. `yours` is your model's billing; per billing, in whole cents: `observedUsd` what every
371
- // reply cost, `routedUsd` what the compared replies cost, and `yoursUsd` your model's cost for them, all of it in your
372
- // model's billing. `yours` and `yoursUsd` are null when your models themselves span both billings: a record keeps
373
- // which model was yours, not each reply's cost on it. Null when one billing covers every model, or some model has no
374
- // known billing: the one-sum readout stands then.
375
- export function billingSplit(config, summary) {
376
- const seen = new Set();
377
- const costs = (cells) => {
378
- const out = { credits: 0, plan: 0 };
379
- for (const { name, sums } of breakdown(cells, 'model')) {
380
- const billing = billingOf(config, name);
381
- if (!billing) return null;
382
- seen.add(billing);
383
- out[billing] += sums[1];
384
- }
385
- return out;
386
- };
387
- const observed = costs(summary.observed.cells);
388
- const routed = costs(summary.cells);
389
- const yours = new Set(Object.keys(summary.yours).map((id) => billingOf(config, id)));
390
- if (!observed || !routed || yours.has(null)) return null;
391
- for (const billing of yours) seen.add(billing);
392
- if (seen.size < 2) return null;
393
- const mine = yours.size === 1 ? [...yours][0] : null;
394
- const side = (billing) => ({
395
- observedUsd: wholeCents(observed[billing]),
396
- routedUsd: wholeCents(routed[billing]),
397
- yoursUsd: mine === null ? null : billing === mine ? wholeCents(summary.yoursUsd) : 0,
398
- });
399
- return { yours: mine, credits: side('credits'), plan: side('plan') };
400
- }
401
- // The split of every reply kept across sessions (allTime). Limit: the undated totals from before the usage records
402
- // name no models, so while they hold replies the one sum stands.
403
- export const keptSplit = (config, kept) => (kept.legacy.replies ? null : billingSplit(config, kept.summary));
404
-
405
- // "credits $4.10 · plan $20.00": each billing's `key` sum.
406
- const billingCosts = (split, key) => BILLINGS.map((billing) => `${billing} ${usd(split[billing][key])}`).join(' · ');
407
- // Routing against your model in one billing, in whole cents: minus is less than your model.
408
- export const billingDifference = (side) => wholeCents(side.routedUsd - side.yoursUsd);
409
- // Every compared reply of the split is priced against models of one billing.
410
- export const splitCompared = (split) => split.yours !== null;
411
-
412
- // The answer as text parts, each with the signed amount that colors it (null: plain): one sum, "routing −$1.84
413
- // (−22%)"; per billing, "routing credits +$4.10 · plan −$61.20"; or, when your models span both billings, what each
414
- // billing cost, "observed credits $4.10 · plan $20.00 · your models mix plan and credits".
415
- export function answerSegments(r, split) {
416
- if (!split) return [{ text: routingAnswer(r), value: r.differenceUsd }];
417
- if (!splitCompared(split))
418
- return [{ text: `observed ${billingCosts(split, 'routedUsd')} · your models mix plan and credits`, value: null }];
419
- return [
420
- { text: 'routing ', value: null },
421
- ...BILLINGS.flatMap((billing, i) => {
422
- const value = billingDifference(split[billing]);
423
- return [...(i ? [{ text: ' · ', value: null }] : []), { text: `${billing} ${signedUsd(value)}`, value }];
424
- }),
425
- ];
426
- }
427
- export const answerText = (r, split) =>
428
- answerSegments(r, split)
429
- .map((segment) => segment.text)
430
- .join('');
431
-
432
337
  // The models a session's replies were priced against, when they are not the one `/model` selects now: after a
433
338
  // `/model` change the record keeps each reply against the model selected when it ran. Null when they are.
434
339
  export function recordedModels(config, view, summary) {
@@ -440,48 +345,34 @@ export function recordedModels(config, view, summary) {
440
345
  // record kept them against.
441
346
  export const comparedModel = (config, view, summary) => recordedModels(config, view, summary) ?? yourModel(view);
442
347
 
443
- // The words every readout uses. Routing against your model: "routing −$1.84 (−22%)", minus less than your model, plus
444
- // more; then the parts that add up to it.
445
- export const routingAnswer = (r) => `routing ${savingsAmount(r)}`;
446
- export const COST_PART = { cheaper: 'cheaper models', stronger: 'stronger models', switches: 'cache rebuilds' };
447
- // The parts of a readout that are not zero, as [signed amount, words]: "−$2.31", "cheaper models".
448
- export function costParts(r) {
449
- return [
450
- [r.cheaperUsd, COST_PART.cheaper],
451
- [r.strongerUsd, COST_PART.stronger],
452
- [r.switchUsd, COST_PART.switches],
453
- ]
454
- .filter(([value]) => value !== 0)
455
- .map(([value, words]) => [signedUsd(value), words, value]);
456
- }
457
348
  // Cache rebuilds cost more than the cheaper models saved: the switches lost money.
458
349
  export const switchesLost = (r) => r.switchUsd > 0 && r.switchUsd > -r.cheaperUsd;
459
350
 
460
- // The `/router` line without a surface: this session's readout, or why there is none yet, with the saved totals
461
- // when this session has no routed reply.
462
- export function savingsLine(config, view, now) {
463
- const summary = sessionUsage(view, now);
464
- const session = readout(summary);
465
- const split = billingSplit(config, summary);
466
- if (summary.observed.uncomparedReplies)
467
- return `Session: ${observedUsageText(summary.observed, split)}${session.replies ? `; ${replyCount(session.replies)} comparable only: ${answerText(session, split)}` : ''}, est. at list prices`;
468
- const label = `vs ${comparedModel(config, view, summary)}`;
469
- if (!session.replies) {
470
- const kept = allTime(view.usageStore, view.savingsStore);
471
- const across = readout(kept.totals);
472
- const keptBy = keptSplit(config, kept);
473
- if (kept.observed.uncomparedReplies)
474
- return `Session ${label}: no routed replies yet; across sessions ${observedUsageText(kept.observed, keptBy)}, est. at list prices`;
475
- const saved = across.early
476
- ? ''
477
- : `; ${answerText(across, keptBy)} since ${sinceDate(kept.since)}, each session against its own model`;
478
- return `Session ${label}: no routed replies yet${saved}`;
479
- }
480
- // Per billing the parts would subtract quota from cash, so a split says its two differences alone.
481
- const answer = split && !splitCompared(split) ? answerText(session, split) : `${answerText(session, split)} ${label}`;
482
- if (session.early) return `Session: ${answer}, ${replyCount(session.replies)}, early sample, est. at list prices`;
483
- const parts = split ? [] : costParts(session).map(([amount, words]) => `${amount} ${words}`);
484
- return `Session: ${answer}${parts.length ? ` = ${parts.join(' ')}` : ''}, ${replyCount(session.replies)}, est. at list prices`;
351
+ // The `/router` lines without a surface, in the band's and pane's words and numbers: the plan windows, then this
352
+ // session's cost with its subagents against no routing.
353
+ // "3 of 20 replies have no comparison", or "no reply has a comparison" when none has.
354
+ export const uncomparedText = (cost) =>
355
+ cost.uncomparedReplies === cost.replies
356
+ ? 'no reply has a comparison'
357
+ : `${cost.uncomparedReplies} of ${cost.replies} replies have no comparison`;
358
+
359
+ export function savingsLine(config, view, usage, now) {
360
+ const cost = sessionCost(config, view, usage, now);
361
+ const plan = cost.limits.map((l) => `${l.label} ${l.percent}%`).join(' · ');
362
+ const lines = plan ? [`Plan: ${plan}`] : [];
363
+ if (!cost.replies && !cost.agents) return [...lines, 'Session: no routed replies yet'].join('\n');
364
+ const split = cost.agents ? ` (main ${usd(cost.mainUsd)} + agents ${usd(cost.agentUsd)})` : '';
365
+ const credits = cost.creditsUsd ? ` · billed ${usd(cost.creditsUsd)}` : '';
366
+ const versus =
367
+ cost.diffUsd !== null
368
+ ? ` · ${diffText(cost.diffUsd, cost.baseUsd)} vs no routing${cost.early ? ', early sample' : ''}`
369
+ : cost.effortOnly
370
+ ? ` · effort ${cost.effortMix.map(([effort, n]) => `${effort} ${n}`).join(' · ')}`
371
+ : ` · ${uncomparedText(cost)}`;
372
+ lines.push(
373
+ `Session: ${costText(cost.totalUsd, cost.billing)} ${BILLING_WORDS[cost.billing]}${split}${credits}${versus} · ${replyCount(cost.replies)}`,
374
+ );
375
+ return lines.join('\n');
485
376
  }
486
377
 
487
378
  export const GATEWAY_SETTINGS = 'v0.8 gateway settings remain · see /router';
@@ -523,7 +414,6 @@ export function usageMetrics(config, view, usage) {
523
414
  );
524
415
  const nextContext = candidates.length ? Math.max(...candidates) : null;
525
416
  const reuse = view.inputTokens > 0 && Number.isFinite(view.cacheRead) ? view.cacheRead / view.inputTokens : null;
526
- const cost = Number.isFinite(usage?.cost?.usd) ? usage.cost.usd : null;
527
417
  const rates = spec && ratesAt(spec, view.inputTokens ?? 0);
528
418
  const cacheBenefit =
529
419
  rates && Number.isFinite(view.cacheRead) ? ((rates.input - rates.cacheRead) * view.cacheRead) / 1e6 : null;
@@ -532,7 +422,6 @@ export function usageMetrics(config, view, usage) {
532
422
  observed,
533
423
  nextContext,
534
424
  reuse,
535
- cost,
536
425
  cacheBenefit,
537
426
  contextBar: bar(nextContext, window),
538
427
  cacheBar: {
@@ -551,3 +440,52 @@ export function sparkline(values) {
551
440
  const span = Math.max(...values) - minimum;
552
441
  return values.map((value) => symbols[span > 0 ? Math.round(((value - minimum) / span) * 7) : 3]).join('');
553
442
  }
443
+
444
+ // "Haiku" for Haiku 5.5, "GLM Flash" for GLM 5.3 Flash, "Kimi Pro" for Kimi K3.1 Pro: a model's name without its
445
+ // version, for the pins and the Routes grid, where the tier's place already tells models apart.
446
+ export const shortModelName = (id) =>
447
+ modelName(id)
448
+ .split(' ')
449
+ .filter((word) => !/^[A-Za-z]?\d+(\.\d+)*$/.test(word))
450
+ .join(' ');
451
+ // A route as a pin labels it, "Haiku·high"; a model without efforts shows its name alone.
452
+ export function shortRoute(config, route) {
453
+ const model = config.models[route.model];
454
+ if (!model) return route.model;
455
+ const effort = model.efforts.length ? (route.effort ?? 'session') : null;
456
+ return `${shortModelName(model.id)}${effort ? `·${effort}` : ''}`;
457
+ }
458
+
459
+ // A tier as signal-strength bars, "▂▄▆" for medium: the band and pane draw the tier this way, never as a word, so the
460
+ // only "low" or "high" beside a model is its effort.
461
+ const METER = '▂▄▆█';
462
+ export const tierBars = (tier) => METER.slice(0, TIERS.indexOf(tier) + 1);
463
+
464
+ // Money by how it is paid: "≈$7.60" on a plan (quota, valued at API prices), "$3.76" when billed.
465
+ export const costText = (value, billing) => `${billing === 'billed' ? '' : '≈'}${usd(value)}`;
466
+ export const BILLING_WORDS = { plan: 'API value', mixed: 'API value', billed: 'billed' };
467
+ // "−$1.76 (−19%)", or "+$2.48 (×5.0)" past double; one format for every difference against no routing.
468
+ export function diffText(diff, base) {
469
+ const share = base > 0 ? Math.round((diff / base) * 100) : 0;
470
+ if (share > 100) return `${signedUsd(diff)} (×${((base + diff) / base).toFixed(1)})`;
471
+ return `${signedUsd(diff)}${share ? ` (${share < 0 ? '−' : '+'}${Math.abs(share)}%)` : ''}`;
472
+ }
473
+
474
+ // A gauge of `cells` cells for a fraction 0–1: [filled, empty].
475
+ export function gaugeCells(fraction, cells) {
476
+ // Anything above zero lights one cell, so a small reading never reads as empty.
477
+ const lit = Number.isFinite(fraction) && fraction > 0 ? Math.max(1, Math.round(fraction * cells)) : 0;
478
+ const filled = Math.min(cells, lit);
479
+ return ['▰'.repeat(filled), '▱'.repeat(cells - filled)];
480
+ }
481
+ // A plan window's colour by how much is used: green, then the warning colour past 75%, red past 90%.
482
+ export const limitColor = (percent) => (percent >= 90 ? 'red' : percent >= 75 ? SAVINGS_COLOR.more : 'green');
483
+
484
+ // This session's cost with its subagents and plan windows (costs.mjs periodCost).
485
+ export function sessionCost(config, view, usage, now) {
486
+ return periodCost(config, {
487
+ summary: sessionUsage(view, now),
488
+ agents: summarizeSubagents(readSubagentStore(view.subagentSession), { from: null, to: null }),
489
+ usage,
490
+ });
491
+ }