@alexeiled/claude-router 1.0.0 → 1.1.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.
@@ -0,0 +1,206 @@
1
+ import { TIERS } from './config.mjs';
2
+ import { CLASSIFIER, CLASSIFIER_ERRORS, GATEWAY_SETTINGS, SHORT_REASONS, usageMetrics } from './native-display.mjs';
3
+ import { modelName, TIER_COLOR } from './native-panel.mjs';
4
+
5
+ const BARS = '▂▄▆█';
6
+ const SEPARATOR = ' · ';
7
+ // Space the band keeps for the trailing Router button.
8
+ const ROUTER_BUTTON = 8;
9
+ const STRIP = 20;
10
+ // Classifier failures worth a warning; busy and cancelled are routine and pass silently.
11
+ const WARNED = new Set(['missing-key', 'paused', 'timeout', 'auth', 'http', 'unreachable', 'policy', 'malformed']);
12
+
13
+ const part = (text, style = {}) => ({ text, style });
14
+ const button = (props) => ({ button: props });
15
+ // `priority` 0 never drops; higher numbers drop first when the band is narrow.
16
+ const segment = (priority, ...parts) => ({ priority, parts: parts.flat().filter(Boolean) });
17
+ const partWidth = (p) => (p.button ? p.button.label.length + (p.button.plain ? 0 : 4) : p.text.length);
18
+ const lineWidth = (segments) =>
19
+ segments.reduce((sum, s, i) => sum + (i ? SEPARATOR.length : 0) + s.parts.reduce((n, p) => n + partWidth(p), 0), 0);
20
+
21
+ // Drops the highest-priority segments, later ones first on a tie, until the line fits `columns`. If the priority-0
22
+ // segments alone are too wide, the later ones go too, and the first is cut with an ellipsis: Ink would otherwise
23
+ // shrink every Text in the row and garble it.
24
+ export function fitSegments(segments, columns) {
25
+ const kept = [...segments];
26
+ while (lineWidth(kept) > columns && kept.length > 1) {
27
+ let drop = -1;
28
+ kept.forEach((s, i) => {
29
+ if (s.priority > 0 && (drop < 0 || s.priority >= kept[drop].priority)) drop = i;
30
+ });
31
+ kept.splice(drop < 0 ? kept.length - 1 : drop, 1);
32
+ }
33
+ const overflow = lineWidth(kept) - columns;
34
+ if (overflow > 0 && kept.length) {
35
+ const parts = [...kept[0].parts];
36
+ const last = parts.findLastIndex((p) => !p.button && p.text.length > overflow);
37
+ if (last >= 0) parts[last] = { ...parts[last], text: `${parts[last].text.slice(0, -overflow - 1)}…` };
38
+ kept[0] = { ...kept[0], parts };
39
+ }
40
+ return kept;
41
+ }
42
+
43
+ // Signal-strength bars: lit up to the tier in its color, dim above it or when `dim`.
44
+ function meter(tier, dim = false) {
45
+ const lit = dim ? -1 : TIERS.indexOf(tier);
46
+ return [...BARS].map((bar, i) => part(bar, i <= lit ? { color: TIER_COLOR[tier] } : { dimColor: true }));
47
+ }
48
+
49
+ function route(view) {
50
+ const id = view.actualModel ?? view.selectedModel ?? view.nativeModel;
51
+ const effort = view.effort === null || view.effort === undefined ? '' : ` · ${view.effort}`;
52
+ return `${modelName(id)}${effort}`;
53
+ }
54
+
55
+ function served(view) {
56
+ const { actualModel: actual, selectedModel: selected } = view;
57
+ return Boolean(actual && selected && actual !== selected && !actual.startsWith(`${selected}-`));
58
+ }
59
+
60
+ function supportText(estimate) {
61
+ if (!Number.isFinite(estimate?.threshold)) return null;
62
+ const mass = Number.isFinite(estimate.upgradeMass) ? estimate.upgradeMass : estimate.downgradeMass;
63
+ if (!Number.isFinite(mass)) return null;
64
+ const pct = (n) => `${Math.round(n * 100)}%`;
65
+ return `${CLASSIFIER} ${pct(mass)} ${mass >= estimate.threshold ? '≥' : '<'} ${pct(estimate.threshold)}`;
66
+ }
67
+
68
+ export function bandSegments(config, view, usage, actions) {
69
+ if (view.phase === 'unavailable')
70
+ return [
71
+ segment(0, part('✕ Router unavailable', { color: 'red' })),
72
+ segment(
73
+ 2,
74
+ part(view.error === GATEWAY_SETTINGS ? 'v0.8 gateway settings remain' : (view.error ?? 'unknown error'), {
75
+ color: 'red',
76
+ }),
77
+ ),
78
+ segment(1, button({ key: 'band-fix', label: 'Fix', onPress: actions.open })),
79
+ ];
80
+ if (view.mode === 'manual')
81
+ return [
82
+ segment(
83
+ 0,
84
+ part('○ ', { dimColor: true }),
85
+ part('Router '),
86
+ part('off', { color: 'yellow' }),
87
+ part(` · keeping ${modelName(view.nativeModel)}`),
88
+ view.reason === 'model selected manually' ? part(' (/model)', { dimColor: true }) : null,
89
+ ),
90
+ segment(1, button({ key: 'band-auto', label: 'Auto', onPress: () => actions.mode('auto') })),
91
+ ];
92
+ if (view.phase === 'choosing')
93
+ return [
94
+ segment(0, meter(view.tier, true), part(' choosing for this turn…', { dimColor: true })),
95
+ segment(3, part(`${CLASSIFIER} · ${config.jev.timeoutMs / 1000} s deadline`, { dimColor: true })),
96
+ ];
97
+ const pin = view.pendingPin
98
+ ? segment(
99
+ 0,
100
+ part('⏵ next turn: ', { color: 'yellow' }),
101
+ part(view.pendingPin, { bold: true, color: TIER_COLOR[view.pendingPin] }),
102
+ part(' '),
103
+ button({ key: 'band-unpin', label: '✕', plain: true, onPress: actions.unpin }),
104
+ )
105
+ : null;
106
+ if (!view.tier && view.phase === 'ready' && !view.actualModel)
107
+ return [segment(0, meter(null, true), part(' Auto · ready', { dimColor: true })), pin].filter(Boolean);
108
+ const main = segment(
109
+ 0,
110
+ view.tier
111
+ ? [...meter(view.tier), part(` ${view.tier} `, { bold: true, color: TIER_COLOR[view.tier] })]
112
+ : part('○ '),
113
+ part(route(view)),
114
+ served(view) ? part(' fallback', { color: 'yellow' }) : null,
115
+ );
116
+ if (WARNED.has(view.error))
117
+ return [
118
+ main,
119
+ pin,
120
+ segment(0, part(`⚠ ${CLASSIFIER} ${CLASSIFIER_ERRORS[view.error]}`, { color: 'yellow' })),
121
+ segment(3, part('keeping model', { color: 'yellow' })),
122
+ view.error === 'missing-key'
123
+ ? segment(1, button({ key: 'band-key', label: 'Set key', onPress: actions.key }))
124
+ : segment(2, button({ key: 'band-fix', label: 'Details', onPress: actions.open })),
125
+ ].filter(Boolean);
126
+ const metrics = usageMetrics(config, view, usage);
127
+ const percent = (bar) => part(bar.percent === null ? '?' : `${bar.percent}%`, { color: bar.color });
128
+ const support = supportText(view.estimate);
129
+ return [
130
+ main,
131
+ pin,
132
+ segment(1, part(SHORT_REASONS[view.reason] ?? view.reason ?? '', { dimColor: true })),
133
+ support ? segment(4, part(support, { dimColor: true })) : null,
134
+ metrics.contextBar.percent === null && metrics.cacheBar.percent === null
135
+ ? null
136
+ : segment(3, part('ctx '), percent(metrics.contextBar), part(' · cache '), percent(metrics.cacheBar)),
137
+ ].filter(Boolean);
138
+ }
139
+
140
+ // The second row of the detailed band: recent replies by tier and the session's switch economics.
141
+ function detailRow(config, view, usage) {
142
+ const tiers = (view.tiers ?? []).slice(-STRIP);
143
+ if (!tiers.length) return [part('no replies yet', { dimColor: true })];
144
+ const switches = tiers.slice(1).filter((tier, i) => tier && tiers[i] && tier !== tiers[i]).length;
145
+ const metrics = usageMetrics(config, view, usage);
146
+ return [
147
+ part('replies ', { dimColor: true }),
148
+ ...tiers.map((tier) => (tier ? part('█', { color: TIER_COLOR[tier] }) : part('·', { dimColor: true }))),
149
+ part(
150
+ ` ${switches} switch${switches === 1 ? '' : 'es'}` +
151
+ `${Number.isFinite(view.estimate?.taxUsd) ? ` · tax ≈ $${view.estimate.taxUsd.toFixed(2)}` : ''}` +
152
+ `${Number.isFinite(metrics.cacheBenefit) ? ` · cache saved ≈ $${metrics.cacheBenefit.toFixed(2)}` : ''}`,
153
+ { dimColor: true },
154
+ ),
155
+ ];
156
+ }
157
+
158
+ export function renderBand({ Box, Text, Button }, config, view, usage, { columns, agentId }, actions) {
159
+ const draw = (p) => (p.button ? Button(p.button) : Text({ ...p.style, children: p.text }));
160
+ const row = (parts) => Box({ children: parts.map(draw) });
161
+ if (agentId) return row([part('○ Router · subagents keep their own model', { dimColor: true })]);
162
+ const kept = fitSegments(bandSegments(config, view, usage, actions), Math.max(0, columns - ROUTER_BUTTON));
163
+ const line = kept.flatMap((s, i) => (i ? [part(SEPARATOR, { dimColor: true }), ...s.parts] : s.parts));
164
+ line.push(part(' '), button({ key: 'details', label: 'Router', plain: true, onPress: actions.open }));
165
+ const routing = view.mode === 'auto' && view.phase !== 'unavailable';
166
+ return Box({
167
+ key: 'router-band',
168
+ flexDirection: 'column',
169
+ children: [
170
+ row(line),
171
+ view.bandDetail && routing ? row(detailRow(config, view, usage)) : null,
172
+ // Revealed while the pointer is over the band; no digit hotkeys, since a bare digit in an
173
+ // empty prompt would press them.
174
+ Box({
175
+ display: 'none',
176
+ hover: { display: 'flex' },
177
+ children: [
178
+ Text({ dimColor: true, children: routing ? 'pin next turn ' : '' }),
179
+ ...(routing
180
+ ? TIERS.flatMap((tier) => [
181
+ Button({ key: `band-pin-${tier}`, label: tier, onPress: () => actions.pin(tier) }),
182
+ Text({ children: ' ' }),
183
+ ])
184
+ : []),
185
+ Text({ children: routing ? ' ' : '' }),
186
+ routing
187
+ ? Button({ key: 'band-manual', label: 'Manual', onPress: () => actions.mode('manual') })
188
+ : Button({ key: 'band-auto-row', label: 'Auto', onPress: () => actions.mode('auto') }),
189
+ Text({ children: ' ' }),
190
+ Button({
191
+ key: 'band-detail',
192
+ label: view.bandDetail ? '1 row' : '2 rows',
193
+ onPress: actions.toggleDetail,
194
+ }),
195
+ ],
196
+ }),
197
+ ],
198
+ });
199
+ }
200
+
201
+ export function switchToast(previous, next, estimate) {
202
+ const label = (decision) =>
203
+ `${modelName(decision.model)}${decision.effort === null || decision.effort === undefined ? '' : ` · ${decision.effort}`}`;
204
+ const support = supportText(estimate);
205
+ return `${label(previous)} → ${label(next)} — ${SHORT_REASONS[next.reason]?.replace(/^\W+\s*/, '') ?? next.reason}${support ? ` (${support})` : ''}`;
206
+ }
@@ -3,9 +3,9 @@ import { tierForModel } from './native-router.mjs';
3
3
  export const REASONS = {
4
4
  ready: 'ready for the next turn',
5
5
  'same-tier': 'the task fits the current tier',
6
- 'no-advice': 'keeping the current model without Jev advice',
6
+ 'no-advice': 'keeping the current model without classifier advice',
7
7
  continuation: 'continuing the previous task',
8
- uncertain: 'Jev could not justify a change',
8
+ uncertain: 'the classifier could not justify a change',
9
9
  upgrade: 'enough support for a stronger model',
10
10
  jump: 'clear need for a stronger model',
11
11
  downgrade: 'enough support for a cheaper model',
@@ -20,6 +20,50 @@ export const REASONS = {
20
20
  pinned: 'one-turn model pin',
21
21
  };
22
22
 
23
+ // The decision model behind the router. Named in the UI only where it explains a reading or a failure.
24
+ export const CLASSIFIER = 'Jev';
25
+ export const CLASSIFIER_ERRORS = {
26
+ 'missing-key': 'key not set',
27
+ paused: 'paused after failures',
28
+ timeout: 'timed out',
29
+ auth: 'rejected the key',
30
+ http: 'request failed',
31
+ unreachable: 'unreachable',
32
+ policy: 'blocked by network policy',
33
+ malformed: 'sent a bad answer',
34
+ busy: 'busy',
35
+ cancelled: 'cancelled',
36
+ };
37
+ // One or two words for the band; REASONS holds the sentence the pane shows.
38
+ export const SHORT_REASONS = {
39
+ ready: 'ready',
40
+ 'same-tier': '= fits',
41
+ 'no-advice': '= no advice',
42
+ continuation: '→ continuing',
43
+ uncertain: '= uncertain',
44
+ upgrade: '↑ upgrade',
45
+ jump: '↑ jump',
46
+ downgrade: '↓ downgrade',
47
+ 'upgrade-pending': '… waiting to go up',
48
+ 'downgrade-pending': '… waiting to go down',
49
+ hold: '= holding',
50
+ escalation: '↑ tool errors',
51
+ 'cash-gate': '= cash cap',
52
+ 'context-fit': '↑ context',
53
+ 'context-unknown': '= context unknown',
54
+ 'model-unavailable': '! model unavailable',
55
+ 'native-fallback': '! fallback',
56
+ pinned: '⏵ pinned',
57
+ interrupted: 'interrupted',
58
+ };
59
+
60
+ export const GATEWAY_SETTINGS = 'v0.8 gateway settings remain · see /router';
61
+ export const GATEWAY_CLEANUP = [
62
+ 'Remove from settings.json, then restart: model jev-router[1m], its modelPicker row,',
63
+ 'env.ANTHROPIC_BASE_URL for 127.0.0.1:43170, env.CLAUDE_CODE_GATEWAY_HINT_HEADERS,',
64
+ 'and a statusLine that runs the router scripts/statusline.mjs.',
65
+ ];
66
+
23
67
  export function formatTokens(value) {
24
68
  if (!Number.isFinite(value)) return 'unknown';
25
69
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)}M`;
@@ -67,9 +111,12 @@ export function usageMetrics(config, view, usage) {
67
111
  };
68
112
  }
69
113
 
114
+ // Scaled from the lowest to the highest reading: a long session's inputs sit close together, and a scale from zero
115
+ // draws them all as full blocks. Equal readings draw a flat middle line.
70
116
  export function sparkline(values) {
71
117
  if (!values.length || !values.every(Number.isFinite)) return 'no history yet';
72
118
  const symbols = '▁▂▃▄▅▆▇█';
73
- const maximum = Math.max(...values);
74
- return values.map((value) => symbols[maximum > 0 ? Math.round((value / maximum) * 7) : 0]).join('');
119
+ const minimum = Math.min(...values);
120
+ const span = Math.max(...values) - minimum;
121
+ return values.map((value) => symbols[span > 0 ? Math.round(((value - minimum) / span) * 7) : 3]).join('');
75
122
  }