@alexeiled/claude-router 1.23.1 → 1.24.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/config.mjs CHANGED
@@ -21,10 +21,12 @@ const withoutShadow = (file) =>
21
21
  export const CLASSIFY = 'classify';
22
22
  // The routing mode trades cost against answer quality (lib/modes.mjs). Not the session's auto|manual mode.
23
23
  export const ROUTING_MODES = ['cost', 'balanced', 'quality'];
24
+ export const ROUTING_ENGINES = ['table', 'shadow', 'auto'];
24
25
  // The modes that patch the policy; `balanced` is the base policy itself.
25
26
  const PATCHED_MODES = ['cost', 'quality'];
26
27
  const SONNET_HIGH = { model: 'sonnet', effort: 'high' };
27
28
  export const DEFAULTS = {
29
+ routingEngine: 'table',
28
30
  baselineTier: 'low',
29
31
  // 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
30
32
  // Sonnet at medium, for a fraction of the cost per attempt (Anthropic's OSWorld 2.1 effort chart: computer use, not
@@ -82,6 +84,7 @@ export const DEFAULTS = {
82
84
  models: {
83
85
  fable: {
84
86
  id: 'claude-fable-5-2',
87
+ capability: {},
85
88
  strength: 4,
86
89
  ...listPrice('claude-fable-5-2'),
87
90
  contextWindow: 1_000_000,
@@ -90,6 +93,11 @@ export const DEFAULTS = {
90
93
  },
91
94
  opus: {
92
95
  id: 'claude-opus-5-5',
96
+ // Lead-approved user-derived policy from DEFAULTS balanced base routes and PR #79 methodology, not benchmark or quality.
97
+ capability: {
98
+ medium: 2, // built-in base route medium
99
+ xhigh: 3, // built-in base route high
100
+ },
93
101
  strength: 3,
94
102
  ...listPrice('claude-opus-5-5'),
95
103
  contextWindow: 1_000_000,
@@ -98,6 +106,7 @@ export const DEFAULTS = {
98
106
  },
99
107
  sonnet: {
100
108
  id: 'claude-sonnet-5-5',
109
+ capability: {},
101
110
  strength: 2,
102
111
  ...listPrice('claude-sonnet-5-5'),
103
112
  contextWindow: 1_000_000,
@@ -106,6 +115,11 @@ export const DEFAULTS = {
106
115
  },
107
116
  haiku: {
108
117
  id: 'claude-haiku-5-5',
118
+ // Lead-approved user-derived policy from DEFAULTS balanced base routes and PR #79 methodology, not benchmark or quality.
119
+ capability: {
120
+ medium: 0, // built-in base route micro
121
+ high: 1, // built-in base route low
122
+ },
109
123
  strength: 1,
110
124
  ...listPrice('claude-haiku-5-5'),
111
125
  contextWindow: 1_000_000,
@@ -256,6 +270,7 @@ const MODEL_KEYS = [
256
270
  'billing',
257
271
  'efforts',
258
272
  'strength',
273
+ 'capability',
259
274
  'imageInput',
260
275
  ];
261
276
  const CLASSIFIER_KEYS = ['label', 'api', 'endpoint', 'model', 'keyOption', 'timeoutMs'];
@@ -283,14 +298,20 @@ export function loadConfig({ userFile = null, provider = 'anthropic' } = {}) {
283
298
  if (userFile !== null) checkShape(userFile);
284
299
  const defaults = defaultsFor(provider);
285
300
  const merged = merge(structuredClone(defaults), withoutShadow(userFile ?? {}));
286
- // Reusing a preset alias for a different model is not a declaration of equal capability.
287
- for (const [alias, patch] of Object.entries(userFile?.models ?? {}))
288
- if (
289
- patch.id &&
290
- canonicalModel(patch.id) !== canonicalModel(defaults.models[alias]?.id) &&
291
- !Object.hasOwn(patch, 'strength')
292
- )
293
- delete merged.models[alias].strength;
301
+ // Model-specific judgments must not follow a different model under the same alias.
302
+ for (const [alias, patch] of Object.entries(userFile?.models ?? {})) {
303
+ const model = merged.models[alias];
304
+ const changed = patch.id && canonicalModel(patch.id) !== canonicalModel(defaults.models[alias]?.id);
305
+ if (changed && !Object.hasOwn(patch, 'strength')) delete model.strength;
306
+ if (Object.hasOwn(patch, 'capability')) model.capability = { ...patch.capability };
307
+ else if (changed) delete model.capability;
308
+ else if (patch.efforts && model.capability && Array.isArray(patch.efforts))
309
+ model.capability = Object.fromEntries(
310
+ Object.entries(model.capability).filter(([effort]) =>
311
+ patch.efforts.length ? patch.efforts.includes(effort) : effort === 'default',
312
+ ),
313
+ );
314
+ }
294
315
  // A user entry without `api` speaks the System One protocol that every entry spoke before 1.5.
295
316
  const config = {
296
317
  ...merged,
@@ -568,6 +589,8 @@ function checkShape(file) {
568
589
  checkObject(models, 'models');
569
590
  for (const [alias, model] of Object.entries(models)) {
570
591
  checkObject(model, `models.${alias}`, MODEL_KEYS);
592
+ if (model.capability !== undefined)
593
+ checkObject(model.capability, `models.${alias}.capability`, [...EFFORTS, 'default']);
571
594
  // null removes a built-in surcharge.
572
595
  if (model.longContext != null)
573
596
  checkObject(model.longContext, `models.${alias}.longContext`, ['above', 'multiplier']);
@@ -613,6 +636,8 @@ const isNumber = (value, min, { above = false, integer = false } = {}) =>
613
636
  Number.isFinite(value) && (above ? value > min : value >= min) && (!integer || Number.isInteger(value));
614
637
 
615
638
  function validate(config) {
639
+ if (!ROUTING_ENGINES.includes(config.routingEngine))
640
+ throw new Error(`routingEngine must be one of ${ROUTING_ENGINES.join(', ')}`);
616
641
  for (const tier of TIERS) {
617
642
  const route = config.routes[tier];
618
643
  if (!route || typeof route.model !== 'string') throw new Error(`routes.${tier}.model is required`);
@@ -740,6 +765,15 @@ function validateModel(at, model) {
740
765
  if (!['plan', 'credits'].includes(model.billing)) throw new Error(`${at}.billing must be plan or credits`);
741
766
  if (!Array.isArray(model.efforts) || model.efforts.some((e) => !EFFORTS.includes(e)))
742
767
  throw new Error(`${at}.efforts must list valid effort levels`);
768
+ if (model.capability !== undefined) {
769
+ checkObject(model.capability, `${at}.capability`, [...EFFORTS, 'default']);
770
+ for (const [effort, value] of Object.entries(model.capability)) {
771
+ if (!(model.efforts.length ? model.efforts.includes(effort) : effort === 'default'))
772
+ throw new Error(`${at}.capability.${effort} is not supported by its model`);
773
+ if (!Number.isFinite(value) || value < 0 || value > 3 || !Number.isInteger(value * 2))
774
+ throw new Error(`${at}.capability.${effort} must be a half-step from 0 to 3`);
775
+ }
776
+ }
743
777
  }
744
778
 
745
779
  function validateClassifier(at, entry) {
package/lib/decisions.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // whether its replies were priced. Counts, labels and routes only, never text. Pure: the hook collects a turn's rows and
4
4
  // writes them at turn.complete to the session's own $.store key under DECISIONS_PREFIX.
5
5
 
6
+ import { ROUTING_ENGINES } from './config.mjs';
6
7
  import { afterResetOf, isRecord } from './records.mjs';
7
8
 
8
9
  export const DECISIONS_PREFIX = 'decisions:v1:';
@@ -63,6 +64,53 @@ const round = (n, digits = 2) => (Number.isFinite(n) ? Math.round(n * 10 ** digi
63
64
  const label = (value) => (typeof value === 'string' && value.length > 0 && value.length <= 80 ? value : null);
64
65
  const count = (n) => (Number.isSafeInteger(n) && n > 0 ? n : 0);
65
66
 
67
+ // Shadow retains a narrow projection, not the engine result or any of the transcript facts.
68
+ const ALT_REASONS = [
69
+ 'classifier',
70
+ 'jump',
71
+ 'pin',
72
+ 'escalation',
73
+ 'hold',
74
+ 'no-advice',
75
+ 'uncertain',
76
+ 'same-demand',
77
+ 'upgrade',
78
+ 'upgrade-pending',
79
+ 'downgrade',
80
+ 'downgrade-pending',
81
+ 'error',
82
+ 'pinned',
83
+ ];
84
+ const ALT_OUTCOMES = ['meets-demand', 'declared-below-demand', 'unknown-only', 'no-route', 'incumbent'];
85
+ const altLevel = (n) => (Number.isFinite(n) && n >= 0 && n <= 3 && Number.isInteger(n * 2) ? n : null);
86
+ const altCost = (n) => (Number.isFinite(n) && n >= 0 ? Number(n.toFixed(6)) : null);
87
+ const ALT_ROUTE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}@(low|medium|high|xhigh|max|session)$/;
88
+ const AUTO_ROUTE = /^([^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+)@(low|medium|high|xhigh|max|session)$/u;
89
+ function validAutoRoute(value) {
90
+ if (typeof value !== 'string' || value.length > 72) return false;
91
+ const match = AUTO_ROUTE.exec(value);
92
+ return Boolean(match && match[1].length <= 64);
93
+ }
94
+ function readAlt(alt, auto = false) {
95
+ if (!isRecord(alt)) return null;
96
+ return {
97
+ demand: altLevel(alt.demand),
98
+ reason: ALT_REASONS.includes(alt.reason) ? alt.reason : null,
99
+ headroom: alt.headroom === true,
100
+ targetReason: ['escalation', 'escalation-unknown', 'escalation-exhausted'].includes(alt.targetReason)
101
+ ? alt.targetReason
102
+ : null,
103
+ requirement: altLevel(alt.requirement),
104
+ outcome: ALT_OUTCOMES.includes(alt.outcome) ? alt.outcome : null,
105
+ route: (auto ? validAutoRoute(alt.route) : typeof alt.route === 'string' && ALT_ROUTE.test(alt.route))
106
+ ? alt.route
107
+ : null,
108
+ capability: altLevel(alt.capability),
109
+ minUsd: altCost(alt.minUsd),
110
+ maxUsd: altCost(alt.maxUsd),
111
+ };
112
+ }
113
+
66
114
  // The reasons whose estimate holds a mass the policy compared with its threshold. Any other reason can carry an
67
115
  // estimate that is not its own: a context or availability override keeps the one of the decision it replaced, and a
68
116
  // jump compared its mass with jumpConfidence, not the threshold.
@@ -102,6 +150,8 @@ export function decisionRow({
102
150
  decision,
103
151
  facts = {},
104
152
  sameTask = null,
153
+ engine = null,
154
+ alt = null,
105
155
  }) {
106
156
  const activity = advice?.activity ?? null;
107
157
  const { downAllowed, contextTokens } = /** @type {{ downAllowed?: boolean, contextTokens?: number }} */ (facts);
@@ -129,6 +179,11 @@ export function decisionRow({
129
179
  down: typeof downAllowed === 'boolean' ? downAllowed : null,
130
180
  ctx: Number.isFinite(contextTokens) ? Math.round(contextTokens / 1000) : null,
131
181
  ...compared(kind, decision),
182
+ ...(ROUTING_ENGINES.includes(engine) && engine !== 'table' ? { engine } : {}),
183
+ ...(engine === 'shadow' && readAlt(alt) ? { alt: readAlt(alt) } : {}),
184
+ ...(engine === 'auto' && readAlt(decision?.auto, true)
185
+ ? { auto: { ...readAlt(decision.auto, true), move: label(decision.auto.move) } }
186
+ : {}),
132
187
  };
133
188
  }
134
189
 
@@ -201,6 +256,7 @@ const ROW_FIELDS = {
201
256
  ctx: nullable(Number.isFinite),
202
257
  mass: Number.isFinite,
203
258
  bar: Number.isFinite,
259
+ engine: (v) => ROUTING_ENGINES.includes(v),
204
260
  observed: nullable(label),
205
261
  requests: Number.isSafeInteger,
206
262
  priced: Number.isSafeInteger,
@@ -214,6 +270,9 @@ function readRow(row) {
214
270
  const out = {};
215
271
  for (const [field, check] of Object.entries(ROW_FIELDS))
216
272
  if (Object.hasOwn(row, field) && check(row[field])) out[field] = row[field];
273
+ if (out.engine === 'shadow' && readAlt(row.alt)) out.alt = readAlt(row.alt);
274
+ if (out.engine === 'auto' && readAlt(row.auto, true))
275
+ out.auto = { ...readAlt(row.auto, true), move: label(row.auto.move) };
217
276
  return out;
218
277
  }
219
278
 
@@ -259,6 +318,14 @@ const share = (p) => (Number.isFinite(p) ? ` ${Math.round(p * 100)}%` : '');
259
318
  const weighed = (row) =>
260
319
  Number.isFinite(row.mass) && Number.isFinite(row.bar) ? `${share(row.mass)} vs bar${share(row.bar)}` : '';
261
320
 
321
+ export function shadowLine(row) {
322
+ const alt = readAlt(row.alt);
323
+ if (row.engine !== 'shadow' || !alt) return null;
324
+ const cost =
325
+ alt.minUsd === null || alt.maxUsd === null ? 'unknown' : `$${alt.minUsd.toFixed(4)}–$${alt.maxUsd.toFixed(4)}`;
326
+ return `shadow demand ${alt.demand ?? '?'} (${alt.reason ?? '?'}${alt.headroom ? ', headroom' : ''}) → target ${alt.route ?? 'none'} cap ${alt.capability ?? 'unknown'}; ${alt.outcome ?? '?'}${alt.targetReason ? ` (${alt.targetReason})` : ''}; required ${alt.requirement ?? '?'}; next-turn estimate ${cost} (proposal only)`;
327
+ }
328
+
262
329
  function endLine(row) {
263
330
  const unpriced = Object.entries(row.unpriced ?? {})
264
331
  .filter(([cause]) => cause !== 'comparison')
@@ -295,6 +362,10 @@ export function decisionLines(rows, n = 20) {
295
362
  `-> ${row.tier ?? '-'}${row.activity ? ` ${row.activity}` : ''} ${row.route ?? ''}`.trimEnd(),
296
363
  `(${row.reason ?? '?'}${weighed(row)})`,
297
364
  row.pinned ? 'pinned' : null,
365
+ shadowLine(row),
366
+ row.engine === 'auto' && row.auto
367
+ ? `demand ${row.auto.demand ?? '?'} → target ${row.auto.route ?? 'none'} cap ${row.auto.capability ?? 'unknown'}; ${row.auto.outcome}; move ${row.auto.move}; next-turn estimate ${row.auto.maxUsd === null ? 'unknown' : `$${row.auto.minUsd.toFixed(4)}–$${row.auto.maxUsd.toFixed(4)}`}`
368
+ : null,
298
369
  ]
299
370
  .filter(Boolean)
300
371
  .join(' ');
package/lib/facts.mjs CHANGED
@@ -366,6 +366,33 @@ export function completedSince(messages, fromIndex, activity) {
366
366
  return false;
367
367
  }
368
368
 
369
+ // Text-free checkpoint evidence for a replay's own switch cursor, not the recorded router's dwell.
370
+ export function progressEvidence(messages) {
371
+ const calls = callsSince(messages, 0);
372
+ const last = (predicate) => calls.findLast(({ block }) => predicate(block));
373
+ const check = last((block) => block.name === 'Bash' && verifies(block.input?.command));
374
+ const edit = last((block) => FILE_EDIT_TOOLS.has(block.name));
375
+ const run = last((block) => block.name === 'Bash' && ['ops', 'shell'].includes(commandKind(block.input?.command)));
376
+ const outcome = (call) => (call ? { index: call.index, ok: succeeded(messages, call) } : null);
377
+ let result = null;
378
+ messages.forEach((message, index) => {
379
+ if (message?.role === 'user')
380
+ for (const block of blocks(message.content))
381
+ if (block.type === 'tool_result') result = { index, error: block.is_error === true };
382
+ });
383
+ return {
384
+ check: outcome(check),
385
+ lastTool: calls.at(-1)?.index ?? -1,
386
+ delegate: last((block) => DELEGATING.has(block.name))?.index ?? -1,
387
+ anyCheck: last((block) => block.name === 'Bash' && runsAnyCheck(block.input?.command))?.index ?? -1,
388
+ edit: outcome(edit),
389
+ nonDocEdit: last((block) => FILE_EDIT_TOOLS.has(block.name) && !DOC_PATH.test(editPath(block)))?.index ?? -1,
390
+ run: outcome(run),
391
+ prompt: promptIndex(messages),
392
+ result,
393
+ };
394
+ }
395
+
369
396
  function callsSince(messages, fromIndex) {
370
397
  const calls = [];
371
398
  for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
package/lib/panel.mjs CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  } from './config.mjs';
17
17
  import { effortSharesCache, routeEffort } from './cost.mjs';
18
18
  import { periodCost, resetText } from './costs.mjs';
19
+ import { decisionLines } from './decisions.mjs';
19
20
  import {
20
21
  API_ESTIMATE,
21
22
  activityReading,
@@ -297,6 +298,9 @@ function nowTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
297
298
  const cost = sessionCost(config, view, usage, now);
298
299
  return [
299
300
  ...nextLines(ui, config, view, actions, columns),
301
+ ...(view.decisionRows?.length
302
+ ? [ui.head('RECENT DECISIONS'), ...decisionLines(view.decisionRows, 5).map((line) => ui.text(line)), ui.text(' ')]
303
+ : []),
300
304
  ...planLines(ui, cost, now),
301
305
  ...sessionLines(ui, config, view, cost, actions, columns, now),
302
306
  ...contextLines(ui, config, view, usage, actions, now),
package/lib/providers.mjs CHANGED
@@ -29,6 +29,7 @@ export const PROVIDER_DEFAULTS = {
29
29
  billing: 'credits',
30
30
  // xhigh is documented but some Claude Code versions serialize it as high; use max instead.
31
31
  efforts: ['low', 'medium', 'high', 'max'],
32
+ capability: {},
32
33
  strength: 1,
33
34
  imageInput: true,
34
35
  },
@@ -54,6 +55,7 @@ export const PROVIDER_DEFAULTS = {
54
55
  billing: 'credits',
55
56
  // The Anthropic endpoint documents binary thinking, not granular effort. Keep its default thinking.
56
57
  efforts: [],
58
+ capability: {},
57
59
  strength: 1,
58
60
  imageInput: true,
59
61
  },
@@ -63,6 +65,7 @@ export const PROVIDER_DEFAULTS = {
63
65
  contextWindow: 1_000_000,
64
66
  billing: 'credits',
65
67
  efforts: [],
68
+ capability: {},
66
69
  strength: 2,
67
70
  imageInput: true,
68
71
  },
@@ -86,6 +89,7 @@ export const PROVIDER_DEFAULTS = {
86
89
  contextWindow: 1_048_576,
87
90
  billing: 'credits',
88
91
  efforts: EFFORTS,
92
+ capability: {},
89
93
  strength: 1,
90
94
  imageInput: true,
91
95
  },
@@ -108,6 +112,7 @@ export const PROVIDER_DEFAULTS = {
108
112
  contextWindow: 1_000_000,
109
113
  billing: 'credits',
110
114
  efforts: EFFORTS,
115
+ capability: {},
111
116
  strength: 1,
112
117
  imageInput: true,
113
118
  },
@@ -132,6 +137,7 @@ export const PROVIDER_DEFAULTS = {
132
137
  contextWindow: 1_000_000,
133
138
  billing: 'credits',
134
139
  efforts: EFFORTS,
140
+ capability: {},
135
141
  strength: 1,
136
142
  imageInput: true,
137
143
  },
@@ -141,6 +147,7 @@ export const PROVIDER_DEFAULTS = {
141
147
  contextWindow: 1_000_000,
142
148
  billing: 'credits',
143
149
  efforts: EFFORTS,
150
+ capability: {},
144
151
  strength: 2,
145
152
  imageInput: false,
146
153
  },