@alexeiled/claude-router 1.24.0 → 1.25.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/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +74 -0
- package/README.md +55 -7
- package/docs/architecture.md +30 -4
- package/docs/configuration.md +23 -14
- package/docs/evaluation.md +3 -3
- package/docs/native-router.md +12 -4
- package/docs/router-band.svg +140 -142
- package/docs/router-pane-classifier.svg +48 -31
- package/docs/router-pane-now.svg +162 -120
- package/docs/router-pane-policy.svg +79 -47
- package/docs/router-pane-routes.svg +8 -8
- package/docs/router-pane-usage-whatif.svg +14 -14
- package/docs/router-pane-usage.svg +20 -20
- package/docs/routing-modes.md +10 -8
- package/docs/user-guide.md +151 -22
- package/hooks/native-router.mjs +415 -88
- package/lib/activity-stats.mjs +23 -4
- package/lib/activity.mjs +7 -5
- package/lib/auto-engine.mjs +13 -6
- package/lib/auto-route.mjs +10 -4
- package/lib/band.mjs +35 -440
- package/lib/classifier-client.mjs +12 -8
- package/lib/config-file.mjs +7 -2
- package/lib/config.mjs +24 -9
- package/lib/cost.mjs +5 -1
- package/lib/costs.mjs +4 -2
- package/lib/decisions.mjs +13 -9
- package/lib/display.mjs +71 -20
- package/lib/facts.mjs +3 -0
- package/lib/failover.mjs +55 -0
- package/lib/modes.mjs +8 -4
- package/lib/panel.mjs +75 -2167
- package/lib/policy.mjs +7 -6
- package/lib/replay-trace.mjs +5 -2
- package/lib/replay.mjs +7 -1
- package/lib/route-line.mjs +46 -0
- package/lib/route.mjs +51 -32
- package/lib/savings.mjs +14 -3
- package/lib/subagents.mjs +41 -11
- package/lib/subcommands.mjs +60 -0
- package/lib/ui/fallback.mjs +22 -0
- package/lib/ui/graphical/band.mjs +256 -0
- package/lib/ui/graphical/charts.mjs +163 -0
- package/lib/ui/graphical/classifier.mjs +153 -0
- package/lib/ui/graphical/frame.mjs +231 -0
- package/lib/ui/graphical/kit.mjs +156 -0
- package/lib/ui/graphical/meter.mjs +25 -0
- package/lib/ui/graphical/now.mjs +357 -0
- package/lib/ui/graphical/policy.mjs +56 -0
- package/lib/ui/graphical/routes.mjs +264 -0
- package/lib/ui/graphical/squares.mjs +29 -0
- package/lib/ui/graphical/usage.mjs +376 -0
- package/lib/ui/model/band.mjs +441 -0
- package/lib/ui/model/classifier.mjs +308 -0
- package/lib/ui/model/draft.mjs +62 -0
- package/lib/ui/model/format.mjs +41 -0
- package/lib/ui/model/frame.mjs +359 -0
- package/lib/ui/model/now.mjs +421 -0
- package/lib/ui/model/policy.mjs +194 -0
- package/lib/ui/model/routes.mjs +392 -0
- package/lib/ui/model/usage-agents.mjs +311 -0
- package/lib/ui/model/usage-breakdown.mjs +237 -0
- package/lib/ui/model/usage-shared.mjs +58 -0
- package/lib/ui/model/usage.mjs +330 -0
- package/lib/ui/terminal/band.mjs +253 -0
- package/lib/ui/terminal/classifier.mjs +150 -0
- package/lib/ui/terminal/frame.mjs +169 -0
- package/lib/ui/terminal/kit.mjs +162 -0
- package/lib/ui/terminal/now.mjs +293 -0
- package/lib/ui/terminal/policy.mjs +55 -0
- package/lib/ui/terminal/routes.mjs +167 -0
- package/lib/ui/terminal/usage.mjs +363 -0
- package/lib/ui/terminal/wrap.mjs +37 -0
- package/lib/ui/tokens.mjs +106 -0
- package/lib/usage.mjs +5 -5
- package/lib/view.mjs +5 -2
- package/package.json +4 -2
- package/types/index.d.ts +17 -0
package/hooks/native-router.mjs
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
} from '../lib/activity-stats.mjs';
|
|
24
24
|
import { advanceDemand, assessCandidates, initialAutoState, selectTarget } from '../lib/auto-engine.mjs';
|
|
25
25
|
import { autoRoute, observeAutoFallback } from '../lib/auto-route.mjs';
|
|
26
|
-
import { renderBand, switchToast } from '../lib/band.mjs';
|
|
26
|
+
import { renderBand, renderRouteLine, switchToast } from '../lib/band.mjs';
|
|
27
27
|
import { ClassifierClient } from '../lib/classifier-client.mjs';
|
|
28
28
|
import { resolveCredentials } from '../lib/classifier-contract.mjs';
|
|
29
29
|
import {
|
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
effectiveRoutes,
|
|
38
38
|
loadConfig,
|
|
39
39
|
MIGRATION_HINT,
|
|
40
|
+
MIN_CLAUDE_CODE,
|
|
40
41
|
ROUTING_MODES,
|
|
41
42
|
supportedVersion,
|
|
42
43
|
TIERS,
|
|
@@ -75,7 +76,10 @@ import {
|
|
|
75
76
|
GATEWAY_CLEANUP,
|
|
76
77
|
GATEWAY_SETTINGS,
|
|
77
78
|
missingCredentials,
|
|
79
|
+
modelName,
|
|
78
80
|
NOT_A_TIER_REASON,
|
|
81
|
+
pinCard,
|
|
82
|
+
pluginIdOf,
|
|
79
83
|
savingsLine,
|
|
80
84
|
storeAgreementLine,
|
|
81
85
|
unavailableReason,
|
|
@@ -92,8 +96,9 @@ import {
|
|
|
92
96
|
routingBucket,
|
|
93
97
|
stripReminders,
|
|
94
98
|
} from '../lib/facts.mjs';
|
|
99
|
+
import { activeHolds, holdModel, holdMs, holdText } from '../lib/failover.mjs';
|
|
95
100
|
import { applyMode, modeLabel, readProjectMode, resolveRoutingMode } from '../lib/modes.mjs';
|
|
96
|
-
import { renderPanel
|
|
101
|
+
import { renderPanel } from '../lib/panel.mjs';
|
|
97
102
|
import { sameTaskOf } from '../lib/policy.mjs';
|
|
98
103
|
import { providerFile, providerName } from '../lib/providers.mjs';
|
|
99
104
|
import {
|
|
@@ -132,6 +137,7 @@ import {
|
|
|
132
137
|
prepareLoop,
|
|
133
138
|
resetHistory,
|
|
134
139
|
} from '../lib/route.mjs';
|
|
140
|
+
import { LINE_MODES, lineId, lineModeOf, lineOf, routeOf, showsLine } from '../lib/route-line.mjs';
|
|
135
141
|
import {
|
|
136
142
|
afterReset,
|
|
137
143
|
compareModels,
|
|
@@ -166,6 +172,10 @@ import {
|
|
|
166
172
|
subagentsAfterReset,
|
|
167
173
|
typeRoute,
|
|
168
174
|
} from '../lib/subagents.mjs';
|
|
175
|
+
import { argumentHint, routerSuggestions } from '../lib/subcommands.mjs';
|
|
176
|
+
import { routeDraftOf, routingChanges } from '../lib/ui/model/draft.mjs';
|
|
177
|
+
import { keyHelpOf } from '../lib/ui/model/frame.mjs';
|
|
178
|
+
import { isGraphical } from '../lib/ui/tokens.mjs';
|
|
169
179
|
import {
|
|
170
180
|
emptyUsage,
|
|
171
181
|
mergeUsage,
|
|
@@ -192,10 +202,17 @@ import {
|
|
|
192
202
|
|
|
193
203
|
const VIEW = { plugin: 'router', key: 'view' };
|
|
194
204
|
const LOOP = { plugin: 'router', key: 'loops' };
|
|
205
|
+
// One record per route line placed, by its `$.ui.place` id: what its `Placed` row draws.
|
|
206
|
+
const LINES = { plugin: 'router', key: 'lines' };
|
|
195
207
|
const PANE = 'jev-router';
|
|
196
208
|
const PANE_TITLE = 'Router';
|
|
197
209
|
const BAND_DETAIL = 'band:detail';
|
|
210
|
+
// Whether and when a turn leaves a route line (lib/route-line.mjs), kept across sessions.
|
|
211
|
+
const ROUTE_LINE = 'route:line';
|
|
198
212
|
const MODE_PREFIX = 'mode:';
|
|
213
|
+
// When the toast for one reason routing cannot run last showed; the reason is appended.
|
|
214
|
+
const UNAVAILABLE_NOTICE_PREFIX = 'notice:unavailable:';
|
|
215
|
+
const UNAVAILABLE_NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
199
216
|
// The session's routing mode override (lib/modes.mjs), apart from its auto|manual MODE_PREFIX.
|
|
200
217
|
const ROUTING_MODE_PREFIX = 'routing-mode:';
|
|
201
218
|
const isSet = (value) => /^(1|true|yes|on)$/i.test(String(value ?? '').trim());
|
|
@@ -254,6 +271,20 @@ const LEDGERS = {
|
|
|
254
271
|
};
|
|
255
272
|
const LEDGER_KINDS = Object.keys(LEDGERS);
|
|
256
273
|
|
|
274
|
+
/** @typedef {ReturnType<typeof readTrace> | ReturnType<typeof newTrace>} TraceRecord */
|
|
275
|
+
/**
|
|
276
|
+
* @typedef {object} TraceHold
|
|
277
|
+
* @property {string} sessionId
|
|
278
|
+
* @property {TraceRecord | null} record
|
|
279
|
+
* @property {unknown} persisted
|
|
280
|
+
* @property {number} lostWrites
|
|
281
|
+
* @property {Set<string>} reasons
|
|
282
|
+
* @property {Map<string, any>} turns
|
|
283
|
+
* @property {number} nextTurn
|
|
284
|
+
* @property {string | null} config
|
|
285
|
+
* @property {{ events: object[], excludedEvents?: number } | null} controls
|
|
286
|
+
*/
|
|
287
|
+
|
|
257
288
|
// Everything the hooks change between events, in one object `register()` creates and passes to its helpers. Module
|
|
258
289
|
// variables, not $.state: a reload starts them over, and the view is written through to $.state as it changes.
|
|
259
290
|
function createRouter(options) {
|
|
@@ -284,16 +315,22 @@ function createRouter(options) {
|
|
|
284
315
|
// Each turn's decision rows until turn.complete writes them, with the turn's end, to the session's record, held as
|
|
285
316
|
// `{ sessionId, record }` once read (`decisionRecord`).
|
|
286
317
|
turnDecisions: new Map(),
|
|
318
|
+
// The route the last routed turn ran, to tell whether the next one moved it; null at a session's start.
|
|
319
|
+
lastRoute: null,
|
|
320
|
+
// The model of the last main request sent: the one an API error that ends the turn failed on (holdFailedModel).
|
|
321
|
+
lastRequested: /** @type {string | null} */ (null),
|
|
287
322
|
decisionRecord: null,
|
|
288
|
-
trace: null,
|
|
323
|
+
trace: /** @type {TraceHold | null} */ (null),
|
|
289
324
|
traceFreshSession: null,
|
|
290
325
|
traceClearSession: null,
|
|
291
326
|
traceStartedSession: null,
|
|
292
327
|
traceFailures: 0,
|
|
293
328
|
traceOperations: new Map(),
|
|
329
|
+
// The surfaces that showed the unavailable toast this session, so an attach never repeats it on the same one.
|
|
330
|
+
noticeSurfaces: new Set(),
|
|
294
331
|
controllers: new Set(),
|
|
295
332
|
turnControllers: new Map(),
|
|
296
|
-
view: null,
|
|
333
|
+
view: /** @type {Record<string, unknown> | null} */ (null),
|
|
297
334
|
modes: new Map(),
|
|
298
335
|
// Each session's routing mode override (null: none), as read from or written to the store.
|
|
299
336
|
routingModes: new Map(),
|
|
@@ -352,6 +389,7 @@ async function ensureTrace($, router, e, turn, loop, loaded, fresh) {
|
|
|
352
389
|
if (router.trace?.sessionId === sessionId && router.trace.record) return;
|
|
353
390
|
const previous = router.trace?.sessionId === sessionId ? router.trace : null;
|
|
354
391
|
const at = Date.now();
|
|
392
|
+
/** @type {TraceHold} */
|
|
355
393
|
const held = {
|
|
356
394
|
sessionId,
|
|
357
395
|
record: null,
|
|
@@ -534,7 +572,7 @@ async function flushTrace($, router, turnId = null, ending = false) {
|
|
|
534
572
|
try {
|
|
535
573
|
const at = Date.now();
|
|
536
574
|
const keys = await $.store.keys();
|
|
537
|
-
let entries = await Promise.all(keys.map(async (
|
|
575
|
+
let entries = await Promise.all(keys.map(async (name) => [name, await $.store.get(name)]));
|
|
538
576
|
if (entries.some(([, value]) => value === undefined)) throw new Error('store-guard');
|
|
539
577
|
if (traceBytes(Object.fromEntries(entries)) > TRACE_STORE_BYTES) throw new Error('store-guard');
|
|
540
578
|
const resetAt = entries.find(([name]) => name === SAVINGS_RESET_KEY)?.[1];
|
|
@@ -597,9 +635,8 @@ async function flushTrace($, router, turnId = null, ending = false) {
|
|
|
597
635
|
if (ending) held.controls = null;
|
|
598
636
|
} catch (error) {
|
|
599
637
|
held.lostWrites++;
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
);
|
|
638
|
+
const message = /** @type {Error} */ (error).message;
|
|
639
|
+
held.reasons.add(message === 'conflict' ? 'conflict' : message === 'store-guard' ? 'store-guard' : 'lost-write');
|
|
603
640
|
}
|
|
604
641
|
} catch {
|
|
605
642
|
traceFailed(router);
|
|
@@ -641,7 +678,7 @@ async function readView($, router) {
|
|
|
641
678
|
|
|
642
679
|
// Only a saved mode is cached: the engine can draw the band before session.start, and a cached fallback from that
|
|
643
680
|
// render would override the start rule.
|
|
644
|
-
async function modeOf($, router, fallback = 'auto') {
|
|
681
|
+
async function modeOf($, router, fallback = /** @type {string | null} */ ('auto')) {
|
|
645
682
|
const sessionId = await $.session.id();
|
|
646
683
|
if (router.modes.has(sessionId)) return router.modes.get(sessionId);
|
|
647
684
|
try {
|
|
@@ -775,15 +812,17 @@ async function readProject($, profilePath) {
|
|
|
775
812
|
}
|
|
776
813
|
|
|
777
814
|
async function updateView($, router, patch) {
|
|
778
|
-
|
|
779
|
-
|
|
815
|
+
// Read the stored view only when none is held, and merge into whatever is held once it arrives: a patch applied
|
|
816
|
+
// during that read stays.
|
|
817
|
+
const stored = router.view ? null : await readView($, router);
|
|
818
|
+
router.view = { ...(router.view ?? stored), ...patch };
|
|
780
819
|
await $.state.set(VIEW, router.view);
|
|
781
820
|
}
|
|
782
821
|
|
|
783
822
|
// This session's record of `kind`, read from the store once per session, and the last reset (ms) from any session,
|
|
784
823
|
// read each time: a Reset in another session empties a record held from before it.
|
|
785
824
|
async function ownRecord($, router, kind) {
|
|
786
|
-
const { prefix, read, afterReset } = LEDGERS[kind];
|
|
825
|
+
const { prefix, read, afterReset: resetRecord } = LEDGERS[kind];
|
|
787
826
|
const held = router.ledgers[kind];
|
|
788
827
|
const sessionId = await $.session.id();
|
|
789
828
|
const resetAt = await $.store.get(SAVINGS_RESET_KEY);
|
|
@@ -792,7 +831,7 @@ async function ownRecord($, router, kind) {
|
|
|
792
831
|
// Another call may have read it meanwhile and a turn added to it: that one stands.
|
|
793
832
|
if (held.own?.sessionId !== sessionId) held.own = { sessionId, record };
|
|
794
833
|
}
|
|
795
|
-
held.own.record =
|
|
834
|
+
held.own.record = resetRecord(held.own.record, resetAt);
|
|
796
835
|
return { own: held.own, resetAt };
|
|
797
836
|
}
|
|
798
837
|
|
|
@@ -893,7 +932,10 @@ async function storeView($, router) {
|
|
|
893
932
|
// status bar.
|
|
894
933
|
async function openPane($, router) {
|
|
895
934
|
await updateView($, router, { notice: null, confirmDelete: false, ...(await storeView($, router)) });
|
|
896
|
-
await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
|
|
935
|
+
const opened = await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
|
|
936
|
+
// The pane is open but undrawn, as where no surface places panes or the terminal is too narrow for it; saying why beats
|
|
937
|
+
// a press that shows nothing.
|
|
938
|
+
if (opened?.isPlaced === false) $.ui.toast(`The Router pane is not shown: ${opened.reason}`);
|
|
897
939
|
}
|
|
898
940
|
|
|
899
941
|
async function changeMode($, router, mode) {
|
|
@@ -951,32 +993,67 @@ async function setPin($, router, tier) {
|
|
|
951
993
|
return `${tier} pinned for the next turn and its tool continuations.`;
|
|
952
994
|
}
|
|
953
995
|
|
|
954
|
-
//
|
|
955
|
-
//
|
|
996
|
+
// What each word of the SUBCOMMANDS table does: a switch, since the engine reads `$` only where it is passed to a
|
|
997
|
+
// function it can name. A word with no case, or one that answers nothing, leaves the command to open the pane.
|
|
998
|
+
async function runSubcommand($, router, action, value) {
|
|
999
|
+
switch (action) {
|
|
1000
|
+
case 'auto':
|
|
1001
|
+
return switchRouting($, router, 'auto');
|
|
1002
|
+
case 'off':
|
|
1003
|
+
return switchRouting($, router, 'manual');
|
|
1004
|
+
case 'trace':
|
|
1005
|
+
return value === 'export' ? { text: await exportTraces($, router) } : undefined;
|
|
1006
|
+
case 'line':
|
|
1007
|
+
return {
|
|
1008
|
+
text: LINE_MODES.includes(value) ? await setRouteLine($, value) : `Choose line ${LINE_MODES.join(', ')}.`,
|
|
1009
|
+
};
|
|
1010
|
+
case 'decisions':
|
|
1011
|
+
return { text: await decisionsText($, router, value) };
|
|
1012
|
+
case 'pin':
|
|
1013
|
+
return { text: TIERS.includes(value) ? await setPin($, router, value) : `Choose ${TIERS.join(', ')}.` };
|
|
1014
|
+
case 'mode':
|
|
1015
|
+
return {
|
|
1016
|
+
text: [...ROUTING_MODES, 'default'].includes(value)
|
|
1017
|
+
? await setRoutingMode($, router, value)
|
|
1018
|
+
: `Choose mode ${[...ROUTING_MODES, 'default'].join(', ')}.`,
|
|
1019
|
+
};
|
|
1020
|
+
case 'activities':
|
|
1021
|
+
return {
|
|
1022
|
+
text: ACTIVITY_MODES.includes(value)
|
|
1023
|
+
? await setActivityRouting($, router, value)
|
|
1024
|
+
: `Choose activities ${ACTIVITY_MODES.join(', ')}.`,
|
|
1025
|
+
};
|
|
1026
|
+
default:
|
|
1027
|
+
return undefined;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// `/router line <mode>`: a preference like the band's second row, kept across sessions and never in router.json.
|
|
1032
|
+
async function setRouteLine($, mode) {
|
|
1033
|
+
const saved = await $.store.set(ROUTE_LINE, mode).then(
|
|
1034
|
+
() => true,
|
|
1035
|
+
() => false,
|
|
1036
|
+
);
|
|
1037
|
+
const says = {
|
|
1038
|
+
off: 'no route line after a turn',
|
|
1039
|
+
moves: 'a route line after a turn that ran another model or effort than the last',
|
|
1040
|
+
all: 'a route line after every turn',
|
|
1041
|
+
};
|
|
1042
|
+
return `Route line ${mode}: ${says[mode]}.${saved ? '' : ' It could not be saved for later sessions.'}`;
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
async function switchRouting($, router, mode) {
|
|
1046
|
+
const view = router.view ?? (await readView($, router));
|
|
1047
|
+
if (view.phase === 'unavailable') return { text: unavailableText(view) };
|
|
1048
|
+
await changeMode($, router, mode);
|
|
1049
|
+
return { text: mode === 'auto' ? 'Routing on.' : 'Routing off: Claude’s model is kept.' };
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// `/router [word [value]]`, the words of SUBCOMMANDS; with none, the pane, or the status text without a surface.
|
|
956
1053
|
async function routerCommand($, router, args) {
|
|
957
1054
|
const [action, value] = args.trim().split(/\s+/);
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
if (view.phase === 'unavailable') return { text: unavailableText(view) };
|
|
961
|
-
await changeMode($, router, action === 'auto' ? 'auto' : 'manual');
|
|
962
|
-
return { text: action === 'auto' ? 'Routing on.' : 'Routing off: Claude’s model is kept.' };
|
|
963
|
-
}
|
|
964
|
-
if (action === 'trace' && value === 'export') return { text: await exportTraces($, router) };
|
|
965
|
-
if (action === 'decisions') return { text: await decisionsText($, router, value) };
|
|
966
|
-
if (action === 'pin')
|
|
967
|
-
return { text: TIERS.includes(value) ? await setPin($, router, value) : `Choose ${TIERS.join(', ')}.` };
|
|
968
|
-
if (action === 'mode')
|
|
969
|
-
return {
|
|
970
|
-
text: [...ROUTING_MODES, 'default'].includes(value)
|
|
971
|
-
? await setRoutingMode($, router, value)
|
|
972
|
-
: `Choose mode ${[...ROUTING_MODES, 'default'].join(', ')}.`,
|
|
973
|
-
};
|
|
974
|
-
if (action === 'activities')
|
|
975
|
-
return {
|
|
976
|
-
text: ACTIVITY_MODES.includes(value)
|
|
977
|
-
? await setActivityRouting($, router, value)
|
|
978
|
-
: `Choose activities ${ACTIVITY_MODES.join(', ')}.`,
|
|
979
|
-
};
|
|
1055
|
+
const answer = await runSubcommand($, router, action, value);
|
|
1056
|
+
if (answer) return answer;
|
|
980
1057
|
const storedView = await readView($, router);
|
|
981
1058
|
const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
|
|
982
1059
|
if (!(await $.session.surfaces()).length)
|
|
@@ -1035,6 +1112,51 @@ async function credentialsOf($, options, config) {
|
|
|
1035
1112
|
);
|
|
1036
1113
|
}
|
|
1037
1114
|
|
|
1115
|
+
// A Set up or Edit press: in the terminal, the secure key dialog of `/plugin configure`; a graphical surface, which
|
|
1116
|
+
// has no such dialog (the command does nothing there), shows how to add the credentials from a terminal instead, in
|
|
1117
|
+
// the pane, for classifier `id`.
|
|
1118
|
+
async function keySetup($, router, press, id) {
|
|
1119
|
+
if (!isGraphical(press?.surface)) {
|
|
1120
|
+
openKeySettings($);
|
|
1121
|
+
return $.ui.close({ id: PANE });
|
|
1122
|
+
}
|
|
1123
|
+
await updateView($, router, { keyHelp: keyHelpFor(router, id ?? router.config.classifier), notice: null });
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// A graphical band or pane that throws draws the terminal tree; the error goes to the debug log, never the transcript.
|
|
1127
|
+
const logFallback = ($, what) => (error) =>
|
|
1128
|
+
$.ui.log(`graphical ${what} failed, drew the terminal one: ${error instanceof Error ? error.message : error}`, {
|
|
1129
|
+
to: 'debug',
|
|
1130
|
+
});
|
|
1131
|
+
|
|
1132
|
+
// The key help to open for classifier `id`: an Edit, when nothing is missing, stays open until Done.
|
|
1133
|
+
const keyHelpFor = (router, id) => ({
|
|
1134
|
+
id,
|
|
1135
|
+
edit: !missingCredentials(router.config, router.view ?? {}, id),
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
// The plugin's id for `claude plugin configure`: from its install path, else settings' enabledPlugins.
|
|
1139
|
+
async function pluginIdFor($) {
|
|
1140
|
+
const plugin = { name: $.plugin.name, root: $.plugin.root };
|
|
1141
|
+
const settings = await $.settings.read().catch(() => ({}));
|
|
1142
|
+
return pluginIdOf(plugin, settings?.enabledPlugins ?? null);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// The pane's credential handlers: Set up or Edit, and the key help's Copy command and Done.
|
|
1146
|
+
function keyActions($, router, view) {
|
|
1147
|
+
return {
|
|
1148
|
+
key: (press, id) => keySetup($, router, press, id),
|
|
1149
|
+
copyKeyHelp: async (press) => {
|
|
1150
|
+
const open = (router.view ?? view).keyHelp;
|
|
1151
|
+
const help = open && keyHelpOf(router.config, open.id, await pluginIdFor($), { edit: open.edit });
|
|
1152
|
+
if (!help) return;
|
|
1153
|
+
await $.ui.copy({ text: help.command, surface: press?.surface });
|
|
1154
|
+
await updateView($, router, { notice: 'Copied' });
|
|
1155
|
+
},
|
|
1156
|
+
keyHelpDone: () => updateView($, router, { keyHelp: null, notice: null }),
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1038
1160
|
// The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
|
|
1039
1161
|
function openKeySettings($) {
|
|
1040
1162
|
$.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
|
|
@@ -1649,8 +1771,7 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
|
|
|
1649
1771
|
resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name)),
|
|
1650
1772
|
$.session.messages({ as: 'api' }),
|
|
1651
1773
|
]);
|
|
1652
|
-
job
|
|
1653
|
-
job.prefix = historySignature(messages);
|
|
1774
|
+
Object.assign(job, { observedUpTo: messages.length, prefix: historySignature(messages) });
|
|
1654
1775
|
const facts = stepFacts(cfg, router, loop, e, messages, context);
|
|
1655
1776
|
clientOf(router, cfg.classifier)
|
|
1656
1777
|
.ask({
|
|
@@ -1679,7 +1800,17 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
|
|
|
1679
1800
|
}
|
|
1680
1801
|
|
|
1681
1802
|
// A routed reply's metrics in the view, with the tier that served it, and added to the turn's activity record with its list price (`routedUsd`, null when unpriced) and, when its tier served it, its route.
|
|
1682
|
-
async function publishReply(
|
|
1803
|
+
async function publishReply(
|
|
1804
|
+
$,
|
|
1805
|
+
router,
|
|
1806
|
+
turnId,
|
|
1807
|
+
request,
|
|
1808
|
+
response,
|
|
1809
|
+
tier,
|
|
1810
|
+
route,
|
|
1811
|
+
routedUsd,
|
|
1812
|
+
cause = /** @type {string | null} */ (null),
|
|
1813
|
+
) {
|
|
1683
1814
|
const turn = router.turnActivities.get(turnId);
|
|
1684
1815
|
const metrics = responseMetrics(router.view, response, tier, Date.now());
|
|
1685
1816
|
await updateView($, router, {
|
|
@@ -1936,11 +2067,13 @@ async function submitPrompt(router, e, next) {
|
|
|
1936
2067
|
router.submitting = entry;
|
|
1937
2068
|
try {
|
|
1938
2069
|
const result = await next(e);
|
|
2070
|
+
// biome-ignore lint/suspicious/noUnnecessaryConditions: turn.start sets `started` through router.submitting, an alias Biome cannot follow
|
|
1939
2071
|
if (!entry.started && typeof result?.text === 'string' && !result.drop)
|
|
1940
2072
|
router.origins = queueOrigin(router.origins, { kind: entry.kind, text: result.text, at: Date.now() });
|
|
1941
2073
|
return result;
|
|
1942
2074
|
} finally {
|
|
1943
|
-
|
|
2075
|
+
// Only the submission still current restores: a later one that started meanwhile keeps its entry.
|
|
2076
|
+
if (router.submitting === entry) router.submitting = outer;
|
|
1944
2077
|
}
|
|
1945
2078
|
}
|
|
1946
2079
|
|
|
@@ -1961,6 +2094,26 @@ function originOfTurn(router, text) {
|
|
|
1961
2094
|
return taken.kind;
|
|
1962
2095
|
}
|
|
1963
2096
|
|
|
2097
|
+
// A routed turn's route line: one record in `$.state`, one row placed at the transcript's end. Not for an interrupted
|
|
2098
|
+
// turn, a subagent's, or a turn with routing off, which has no route of its own to say. Display only, so a failure
|
|
2099
|
+
// here never breaks the turn, and a surface that cannot draw the row now is logged, not told.
|
|
2100
|
+
async function placeRouteLine($, router, e, turn) {
|
|
2101
|
+
try {
|
|
2102
|
+
const view = router.view;
|
|
2103
|
+
const route = routeOf(view);
|
|
2104
|
+
if (!turn || e.isAborted || !route || !view || view.phase === 'unavailable') return;
|
|
2105
|
+
if ((await modeOf($, router, view.mode)) === 'manual') return;
|
|
2106
|
+
const previous = router.lastRoute;
|
|
2107
|
+
router.lastRoute = route;
|
|
2108
|
+
const mode = lineModeOf(await $.store.get(ROUTE_LINE).catch(() => undefined));
|
|
2109
|
+
if (!showsLine(mode, previous, route)) return;
|
|
2110
|
+
const id = lineId(e.turnId);
|
|
2111
|
+
await $.state.set({ ...LINES, id }, lineOf(router.config, view, route));
|
|
2112
|
+
const placed = await $.ui.place({ id });
|
|
2113
|
+
if (!placed.isPlaced) $.ui.log(`router route line not drawn: ${placed.reason}`, { to: 'debug' });
|
|
2114
|
+
} catch {}
|
|
2115
|
+
}
|
|
2116
|
+
|
|
1964
2117
|
// A finished turn's decision rows and its end row, added to this session's record. Telemetry never breaks a turn: a
|
|
1965
2118
|
// failed read or write loses this turn's rows. A record from before the last reset reads as empty, and rows read
|
|
1966
2119
|
// before a Reset in this session are not written back.
|
|
@@ -1977,8 +2130,11 @@ async function flushDecisions($, router, turnId, turn) {
|
|
|
1977
2130
|
if (turn && turn.sessionId !== sessionId) return;
|
|
1978
2131
|
const key = `${DECISIONS_PREFIX}${sessionId}`;
|
|
1979
2132
|
const resetAt = await $.store.get(SAVINGS_RESET_KEY);
|
|
1980
|
-
if (router.decisionRecord?.sessionId !== sessionId)
|
|
1981
|
-
|
|
2133
|
+
if (router.decisionRecord?.sessionId !== sessionId) {
|
|
2134
|
+
const record = readDecisions(await $.store.get(key));
|
|
2135
|
+
// Another flush may have read it meanwhile and added its rows to it: that one stands.
|
|
2136
|
+
if (router.decisionRecord?.sessionId !== sessionId) router.decisionRecord = { sessionId, record };
|
|
2137
|
+
}
|
|
1982
2138
|
const held = router.decisionRecord;
|
|
1983
2139
|
const now = Date.now();
|
|
1984
2140
|
const end = turn
|
|
@@ -2065,12 +2221,12 @@ async function recordActivity($, router, turn) {
|
|
|
2065
2221
|
const start = promptIndex(messages);
|
|
2066
2222
|
if (start < 0) return;
|
|
2067
2223
|
const observed = observedActivity(messages, start);
|
|
2068
|
-
// The turn's end row reads it (flushDecisions).
|
|
2069
|
-
turn.observed = observed;
|
|
2070
2224
|
const view = router.view ?? (await readView($, router));
|
|
2071
2225
|
const manual = (await modeOf($, router)) === 'manual';
|
|
2072
2226
|
// The session may have changed during the reads; this turn is not the new session's.
|
|
2073
2227
|
if ((await $.session.id()) !== turn.sessionId) return;
|
|
2228
|
+
// The turn's end row reads it (flushDecisions).
|
|
2229
|
+
turn.observed = observed;
|
|
2074
2230
|
// Advanced before any further await, so a session change meanwhile cannot carry this run into the new session.
|
|
2075
2231
|
const { run, ended } = advanceRun(router.run, turn.answer);
|
|
2076
2232
|
router.run = run;
|
|
@@ -2212,6 +2368,17 @@ async function decideSpawn($, router, cfg, e, definition, signal) {
|
|
|
2212
2368
|
// Claude Code uses in place of the Agent call's `model` and the agent's frontmatter. Routing off or unavailable keeps
|
|
2213
2369
|
// every model Claude Code chooses, and records nothing.
|
|
2214
2370
|
async function spawnAgent($, router, e, next) {
|
|
2371
|
+
// A resumed agent keeps the model and the record of its first spawn: a hook can only refuse a resume. It runs again
|
|
2372
|
+
// from here, so the band's rows show it before its first reply.
|
|
2373
|
+
if (e.resume) {
|
|
2374
|
+
const result = await next(e);
|
|
2375
|
+
const agent = router.agents.get(e.resume.agentId);
|
|
2376
|
+
if (agent && !agent.running) {
|
|
2377
|
+
router.agents.set(e.resume.agentId, { ...agent, running: true });
|
|
2378
|
+
await showRunning($, router);
|
|
2379
|
+
}
|
|
2380
|
+
return result;
|
|
2381
|
+
}
|
|
2215
2382
|
if (!(await ensureInitialized($, router))) return next(e);
|
|
2216
2383
|
const cfg = router.config;
|
|
2217
2384
|
if (cfg.subagentRouting === 'off') return next(e);
|
|
@@ -2221,7 +2388,7 @@ async function spawnAgent($, router, e, next) {
|
|
|
2221
2388
|
const pass = passReason(cfg, e, definition);
|
|
2222
2389
|
const decision = pass ? null : await decideSpawn($, router, cfg, e, definition, next.signal).catch(() => null);
|
|
2223
2390
|
const routed = Boolean(decision?.model);
|
|
2224
|
-
const result = await next(
|
|
2391
|
+
const result = await next(decision?.model ? { ...e, model: decision.model } : e);
|
|
2225
2392
|
if (result.agentId && (pass || decision))
|
|
2226
2393
|
await noteSpawn($, router, { cfg, e, pass, decision, routed, result, definition }).catch(() => {});
|
|
2227
2394
|
return result;
|
|
@@ -2255,11 +2422,32 @@ async function noteSpawn($, router, { cfg, e, pass, decision, routed, result, de
|
|
|
2255
2422
|
await showRunning($, router);
|
|
2256
2423
|
}
|
|
2257
2424
|
|
|
2258
|
-
//
|
|
2259
|
-
// changes. An agent spawned with routing off has no record and is not
|
|
2425
|
+
// Which of the agents with a record are between their start or a step and their turn's end, and how many, in the view
|
|
2426
|
+
// when the set changes: the band draws a row for each. An agent spawned with routing off has no record and is not
|
|
2427
|
+
// listed.
|
|
2260
2428
|
async function showRunning($, router) {
|
|
2261
|
-
const
|
|
2262
|
-
if ((router.view?.
|
|
2429
|
+
const ids = [...router.agents].filter(([, agent]) => agent.running).map(([id]) => id);
|
|
2430
|
+
if ((router.view?.subagentIds ?? []).join(' ') !== ids.join(' '))
|
|
2431
|
+
await updateView($, router, { subagentsRunning: ids.length, subagentIds: ids });
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
// The band's rows: the agents with a record that Claude Code still lists as running, never a teammate, whose own
|
|
2435
|
+
// session the person opens from the tasks list. The list names the type and the task; the record the model.
|
|
2436
|
+
async function runningAgents($, router) {
|
|
2437
|
+
const listed = await $.agent.list().catch(() => []);
|
|
2438
|
+
return listed.flatMap((agent) => {
|
|
2439
|
+
const record = router.agents.get(agent.id);
|
|
2440
|
+
return record?.running && !agent.teammateId && ['running', 'waiting'].includes(agent.status)
|
|
2441
|
+
? [{ id: agent.id, type: agent.type, description: agent.description, record }]
|
|
2442
|
+
: [];
|
|
2443
|
+
});
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
// A press on an agent's row, or on Back, shows that transcript in the main view. Claude Code allows it only while the
|
|
2447
|
+
// call answers the person's own input, so a press is the one place to ask; a refusal is told.
|
|
2448
|
+
async function showView($, view) {
|
|
2449
|
+
const shown = await $.ui.view(view).catch(() => ({ deny: 'Could not switch the view.' }));
|
|
2450
|
+
if (shown.deny) $.ui.toast(shown.deny);
|
|
2263
2451
|
}
|
|
2264
2452
|
|
|
2265
2453
|
// A subagent's prompt-cache lifetime, by Claude Code's rule for requests outside the main conversation.
|
|
@@ -2326,6 +2514,14 @@ function traceConfigAdopted(router, loaded) {
|
|
|
2326
2514
|
}
|
|
2327
2515
|
}
|
|
2328
2516
|
|
|
2517
|
+
// The session row under the band, on or off. The band's button and the pane's setting share it; `view` is the view the
|
|
2518
|
+
// caller was drawn from, and `router.view` holds any press since.
|
|
2519
|
+
async function toggleBandDetail($, router, view) {
|
|
2520
|
+
const bandDetail = !(router.view ?? view).bandDetail;
|
|
2521
|
+
await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
|
|
2522
|
+
await updateView($, router, { bandDetail });
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2329
2525
|
// The pane's handlers. `view` is the view the pane was drawn from; a handler reads `router.view` first, which holds
|
|
2330
2526
|
// any press since.
|
|
2331
2527
|
function paneActions($, router, view) {
|
|
@@ -2426,14 +2622,12 @@ function paneActions($, router, view) {
|
|
|
2426
2622
|
mode: (mode) => changeMode($, router, mode),
|
|
2427
2623
|
tab: (tab) => updateView($, router, { tab, notice: null, confirmDelete: false }),
|
|
2428
2624
|
help: () => updateView($, router, { help: !(router.view ?? view).help }),
|
|
2625
|
+
toggleDetail: () => toggleBandDetail($, router, view),
|
|
2429
2626
|
pin: async (tier) => {
|
|
2430
2627
|
await updateView($, router, { notice: await setPin($, router, tier) });
|
|
2431
2628
|
},
|
|
2432
2629
|
unpin: () => updateView($, router, { pendingPin: null, notice: null }),
|
|
2433
|
-
|
|
2434
|
-
openKeySettings($);
|
|
2435
|
-
await $.ui.close({ id: PANE });
|
|
2436
|
-
},
|
|
2630
|
+
...keyActions($, router, view),
|
|
2437
2631
|
copyPath: async (press) => {
|
|
2438
2632
|
await $.ui.copy({ text: router.config.nativePath, surface: press?.surface });
|
|
2439
2633
|
await updateView($, router, { notice: 'Path copied.' });
|
|
@@ -2532,11 +2726,11 @@ function paneActions($, router, view) {
|
|
|
2532
2726
|
router.ledgers[kind] = { own: null, others: LEDGERS[kind].empty(), othersResetAt: resetAt };
|
|
2533
2727
|
return true;
|
|
2534
2728
|
};
|
|
2535
|
-
const cleared = await clearRecords().catch(() => false);
|
|
2536
2729
|
router.trace = null;
|
|
2537
2730
|
router.traceFreshSession = null;
|
|
2538
2731
|
router.traceClearSession = null;
|
|
2539
2732
|
router.traceOperations.clear();
|
|
2733
|
+
const cleared = await clearRecords().catch(() => false);
|
|
2540
2734
|
// The store kept the history: this session's records start over, and its next write replaces the stored one.
|
|
2541
2735
|
if (!cleared)
|
|
2542
2736
|
for (const kind of LEDGER_KINDS) {
|
|
@@ -2665,7 +2859,7 @@ async function imagesOf($, config, decision) {
|
|
|
2665
2859
|
}
|
|
2666
2860
|
|
|
2667
2861
|
function startError(supported, gateway) {
|
|
2668
|
-
if (!supported) return
|
|
2862
|
+
if (!supported) return `requires Claude Code ${MIN_CLAUDE_CODE} or newer`;
|
|
2669
2863
|
if (gateway) return GATEWAY_SETTINGS;
|
|
2670
2864
|
return null;
|
|
2671
2865
|
}
|
|
@@ -2689,6 +2883,8 @@ async function* sendRouted($, router, e, next, { cfg, loop, loopVersion, session
|
|
|
2689
2883
|
else request.effort = loop.decision.effort;
|
|
2690
2884
|
if (cfg.routingEngine === 'shadow' && !next.signal.aborted && (await $.session.id()) === sessionId)
|
|
2691
2885
|
traceRequest(router, e, router.turnConfigs.get(e.turnId) ?? turn, request, 'auto', loop);
|
|
2886
|
+
// biome-ignore lint/nursery/useAtomicUpdates: the request sent last names the model, whatever ran before it
|
|
2887
|
+
router.lastRequested = request.model;
|
|
2692
2888
|
const response = yield* next(request);
|
|
2693
2889
|
if (!next.signal.aborted && (await $.session.id()) === sessionId)
|
|
2694
2890
|
await observeRouted($, router, { turnId: e.turnId, cfg, loop, loopVersion, request, response, nativeModel });
|
|
@@ -2756,7 +2952,7 @@ async function traceContinuation($, router, cfg, loop, e, traceInput) {
|
|
|
2756
2952
|
if (cfg.routingEngine === 'shadow') {
|
|
2757
2953
|
// Replay's incumbent may differ from the table's: retain unconditional modality and checkpoint evidence.
|
|
2758
2954
|
// Failure stays unknown, never a false assertion that the hypothetical route can accept this history.
|
|
2759
|
-
let replayMessages
|
|
2955
|
+
let replayMessages;
|
|
2760
2956
|
let actualHasImages = null;
|
|
2761
2957
|
try {
|
|
2762
2958
|
replayMessages = await transcript($);
|
|
@@ -2771,6 +2967,10 @@ async function traceContinuation($, router, cfg, loop, e, traceInput) {
|
|
|
2771
2967
|
async function* stepMain($, router, e, next) {
|
|
2772
2968
|
if (!(await ensureInitialized($, router))) return yield* next(e);
|
|
2773
2969
|
if (e.agentId) return yield* stepAgent($, router, e, next);
|
|
2970
|
+
// A main request goes out as Claude Code built it unless sendRouted routes it, so its model is the one a failure
|
|
2971
|
+
// holds (holdFailedModel) until sendRouted names another.
|
|
2972
|
+
// biome-ignore lint/nursery/useAtomicUpdates: the request sent last names the model, whatever ran before it
|
|
2973
|
+
router.lastRequested = e.model;
|
|
2774
2974
|
const turn = router.turnConfigs.get(e.turnId) ?? (await turnConfigOf($, router));
|
|
2775
2975
|
const cfg = turn.config;
|
|
2776
2976
|
const [sessionId, nativeModel, view] = await Promise.all([$.session.id(), $.session.model(), readView($, router)]);
|
|
@@ -2847,6 +3047,7 @@ async function* stepMain($, router, e, next) {
|
|
|
2847
3047
|
contextKnown: context.known,
|
|
2848
3048
|
availableModels,
|
|
2849
3049
|
effort: e.effort,
|
|
3050
|
+
now: Date.now(),
|
|
2850
3051
|
};
|
|
2851
3052
|
loop =
|
|
2852
3053
|
cfg.routingEngine === 'auto'
|
|
@@ -2868,23 +3069,22 @@ async function initializeSession($, router) {
|
|
|
2868
3069
|
await $.command.register({
|
|
2869
3070
|
name: 'router',
|
|
2870
3071
|
description:
|
|
2871
|
-
'Open the Router pane, or switch routing: auto, off, pin <tier>, activities <mode>, mode <mode>; decisions [n] lists the last routing decisions.',
|
|
2872
|
-
argumentHint:
|
|
2873
|
-
'[auto|off|pin <tier>|activities off|on|mode cost|balanced|quality|default|decisions [n]|trace export]',
|
|
3072
|
+
'Open the Router pane, or switch routing: auto, off, pin <tier>, activities <mode>, mode <mode>, line <mode>; decisions [n] lists the last routing decisions.',
|
|
3073
|
+
argumentHint: argumentHint(),
|
|
2874
3074
|
immediate: true,
|
|
2875
3075
|
});
|
|
2876
3076
|
const model = await $.session.model();
|
|
2877
3077
|
try {
|
|
2878
|
-
|
|
3078
|
+
const config = await loadNativeConfig($);
|
|
3079
|
+
const project = await readProject($, config.nativePath);
|
|
3080
|
+
const existing = await readView($, router);
|
|
2879
3081
|
// A successful reload adopts this config even for the current turn; stale jobs must not route with the old engine.
|
|
3082
|
+
Object.assign(router, { config, project, view: existing });
|
|
2880
3083
|
for (const controller of router.controllers) controller.abort();
|
|
2881
3084
|
router.decisions.clear();
|
|
2882
3085
|
router.turnConfigs.clear();
|
|
2883
3086
|
for (const review of router.reviews.values()) review.controller.abort();
|
|
2884
3087
|
router.reviews.clear();
|
|
2885
|
-
router.project = await readProject($, router.config.nativePath);
|
|
2886
|
-
const existing = await readView($, router);
|
|
2887
|
-
router.view = existing;
|
|
2888
3088
|
const sameClassifier = existing.health?.classifier === router.config.classifier;
|
|
2889
3089
|
clientOf(router, router.config.classifier).restore(sameClassifier ? existing.health : null);
|
|
2890
3090
|
const base = await $.env.get('ANTHROPIC_BASE_URL');
|
|
@@ -2917,6 +3117,7 @@ async function initializeSession($, router) {
|
|
|
2917
3117
|
...(await storeView($, router)),
|
|
2918
3118
|
});
|
|
2919
3119
|
await pruneDecisionRecords($);
|
|
3120
|
+
// biome-ignore lint/nursery/useAtomicUpdates: ensureInitialized runs this once at a time, and the flag marks it done
|
|
2920
3121
|
router.initialized = true;
|
|
2921
3122
|
return true;
|
|
2922
3123
|
} catch (error) {
|
|
@@ -2928,6 +3129,71 @@ async function initializeSession($, router) {
|
|
|
2928
3129
|
}
|
|
2929
3130
|
}
|
|
2930
3131
|
|
|
3132
|
+
// What made routing unavailable, as the notice keys it: an old Claude Code, the v0.8 gateway settings, or a router.json
|
|
3133
|
+
// that did not load.
|
|
3134
|
+
function unavailableCause(error) {
|
|
3135
|
+
if (error?.startsWith('requires Claude Code')) return 'version';
|
|
3136
|
+
return error === GATEWAY_SETTINGS ? 'gateway' : 'config';
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
// One toast when a session starts with routing unavailable, at most once a day per cause: the band says it too, but not
|
|
3140
|
+
// once it is collapsed or scrolled away. Not for a headless run, which has no one to read it. The day is recorded before
|
|
3141
|
+
// the toast, so a toast no surface draws is not retried until tomorrow. A surface that attaches later (desktop, VS Code,
|
|
3142
|
+
// mobile) gets it too, once per surface, once this session has shown it: it was not there to see the first. The day
|
|
3143
|
+
// record still gates the session's first toast, on whichever surface asks first.
|
|
3144
|
+
async function noticeUnavailable($, router, e) {
|
|
3145
|
+
const view = router.view;
|
|
3146
|
+
if (view?.phase !== 'unavailable' || !e.isInteractive || !e.surface) return;
|
|
3147
|
+
if (router.noticeSurfaces.has(e.surface)) return;
|
|
3148
|
+
try {
|
|
3149
|
+
if (router.noticeSurfaces.size === 0) {
|
|
3150
|
+
const key = `${UNAVAILABLE_NOTICE_PREFIX}${unavailableCause(view.error)}`;
|
|
3151
|
+
const last = await $.store.get(key);
|
|
3152
|
+
const now = Date.now();
|
|
3153
|
+
if (Number.isFinite(last) && now - last >= 0 && now - last < UNAVAILABLE_NOTICE_INTERVAL_MS) return;
|
|
3154
|
+
await $.store.set(key, now);
|
|
3155
|
+
}
|
|
3156
|
+
router.noticeSurfaces.add(e.surface);
|
|
3157
|
+
$.ui.toast(`Routing off: ${unavailableReason(view)}. Claude’s model is kept.`);
|
|
3158
|
+
} catch {}
|
|
3159
|
+
}
|
|
3160
|
+
|
|
3161
|
+
const MODEL_SELECTED_MANUALLY = 'model selected manually';
|
|
3162
|
+
const MANUAL_SWITCH_SOURCES = new Set(['picker', 'sdk']);
|
|
3163
|
+
|
|
3164
|
+
// A person chose the session's model: routing turns off and keeps it.
|
|
3165
|
+
async function keepChosenModel($, router, reason) {
|
|
3166
|
+
await changeMode($, router, 'manual');
|
|
3167
|
+
await updateView($, router, { nativeModel: await $.session.model(), ...(reason ? { reason } : {}) });
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
// A main turn ended on an API error (`StopFailure`): the request is lost, and Claude Code reports neither the model nor
|
|
3171
|
+
// a retry-after. An error that is the model's holds the model the last request ran out of routing for a while
|
|
3172
|
+
// (lib/failover.mjs), so the next turn runs another; the hold lives in the loop, which the table and shadow engines
|
|
3173
|
+
// read. The `auto` engine routes without holds, so it gets none and no toast claims one.
|
|
3174
|
+
async function holdFailedModel($, router, error) {
|
|
3175
|
+
// A failed hold changes no route; the turn's result stands.
|
|
3176
|
+
try {
|
|
3177
|
+
if (holdMs(error) === null || !(await ensureInitialized($, router))) return;
|
|
3178
|
+
if (router.config.routingEngine === 'auto') return;
|
|
3179
|
+
const model = router.lastRequested ?? (await $.session.model());
|
|
3180
|
+
const ref = { ...LOOP, id: 'main' };
|
|
3181
|
+
// A write that lost to a step's own write reads the loop again.
|
|
3182
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
3183
|
+
const { value: loop, version } = await $.state.get(ref);
|
|
3184
|
+
if (!loop) return;
|
|
3185
|
+
const now = Date.now();
|
|
3186
|
+
const held = holdModel(loop.held, model, error, now);
|
|
3187
|
+
const written = await $.state.set(ref, { ...loop, held }, { ifVersion: version });
|
|
3188
|
+
if (!written.isSet) continue;
|
|
3189
|
+
const hold = activeHolds(held, now)[model];
|
|
3190
|
+
if (hold && (await modeOf($, router)) === 'auto')
|
|
3191
|
+
$.ui.toast(`${modelName(model)} held out of routing: ${holdText(hold, now)}`);
|
|
3192
|
+
return;
|
|
3193
|
+
}
|
|
3194
|
+
} catch {}
|
|
3195
|
+
}
|
|
3196
|
+
|
|
2931
3197
|
async function ensureInitialized($, router) {
|
|
2932
3198
|
if (router.initialized) return true;
|
|
2933
3199
|
router.initializing ??= initializeSession($, router).finally(() => {
|
|
@@ -2946,43 +3212,64 @@ export function register(on, options) {
|
|
|
2946
3212
|
router.traceStartedSession = sessionId;
|
|
2947
3213
|
router.trace = null;
|
|
2948
3214
|
router.traceOperations.clear();
|
|
3215
|
+
router.lastRoute = null;
|
|
3216
|
+
router.lastRequested = null;
|
|
2949
3217
|
router.initialized = false;
|
|
3218
|
+
router.noticeSurfaces.clear();
|
|
2950
3219
|
await ensureInitialized($, router);
|
|
3220
|
+
await noticeUnavailable($, router, e);
|
|
2951
3221
|
return next(e);
|
|
2952
3222
|
});
|
|
2953
3223
|
|
|
3224
|
+
// The terminal's own attachment raises nothing; a desktop, VS Code or mobile surface attaches after session.start.
|
|
3225
|
+
on('session.attach', async ($, e, next) => {
|
|
3226
|
+
const result = await next(e);
|
|
3227
|
+
await noticeUnavailable($, router, { isInteractive: true, surface: e.surface });
|
|
3228
|
+
return result;
|
|
3229
|
+
});
|
|
3230
|
+
|
|
2954
3231
|
on('command.run', { command: 'model' }, async ($, e, next) => {
|
|
2955
3232
|
const result = await next(e);
|
|
2956
|
-
if (e.origin.kind !== 'plugin')
|
|
2957
|
-
await changeMode($, router, 'manual');
|
|
2958
|
-
await updateView($, router, { nativeModel: await $.session.model(), reason: 'model selected manually' });
|
|
2959
|
-
}
|
|
3233
|
+
if (e.origin.kind !== 'plugin') await keepChosenModel($, router, MODEL_SELECTED_MANUALLY);
|
|
2960
3234
|
return result;
|
|
2961
3235
|
});
|
|
2962
3236
|
|
|
2963
3237
|
on('config.set', { key: 'model' }, async ($, e, next) => {
|
|
2964
3238
|
const result = await next(e);
|
|
2965
|
-
if (!result.deny && e.origin.kind !== 'plugin')
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
3239
|
+
if (!result.deny && e.origin.kind !== 'plugin') await keepChosenModel($, router);
|
|
3240
|
+
return result;
|
|
3241
|
+
});
|
|
3242
|
+
|
|
3243
|
+
// A switch the two hooks above never see: the model picker's shortcut, or set_model from the SDK, an IDE or Remote
|
|
3244
|
+
// Control. A 'command' switch is theirs (they know a plugin's own /model); 'auto' and 'resume' are no one's choice.
|
|
3245
|
+
on('classic.PostModelSwitch', async ($, e, next) => {
|
|
3246
|
+
const result = await next(e);
|
|
3247
|
+
if (MANUAL_SWITCH_SOURCES.has(e.source)) await keepChosenModel($, router, MODEL_SELECTED_MANUALLY);
|
|
2969
3248
|
return result;
|
|
2970
3249
|
});
|
|
2971
3250
|
|
|
2972
3251
|
on('command.run', { command: 'router' }, ($, e) => routerCommand($, router, e.args));
|
|
2973
3252
|
|
|
3253
|
+
// The words after `/router `, once one character is typed (the token is never empty). A matcher tests the token
|
|
3254
|
+
// alone, so the hook reads the text before it. Nothing is read or written but the router's own view.
|
|
3255
|
+
on('prompt.autocomplete', async (_$, e, next) => {
|
|
3256
|
+
const mine = routerSuggestions(e, {
|
|
3257
|
+
describe: (name, value) => (name === 'pin' && router.view ? pinCard(router.config, value) : undefined),
|
|
3258
|
+
});
|
|
3259
|
+
if (!mine.length) return next(e);
|
|
3260
|
+
return { suggestions: [...(await next(e)).suggestions, ...mine] };
|
|
3261
|
+
});
|
|
3262
|
+
|
|
3263
|
+
// Since 2.1.321 a subagent's loop raises turn.start too, with its agentId; the goal and prompt state is the main loop's.
|
|
2974
3264
|
on('turn.start', async ($, e, next) => {
|
|
2975
|
-
await startTurn($, router, e);
|
|
3265
|
+
if (e.agentId === undefined) await startTurn($, router, e);
|
|
2976
3266
|
return next(e);
|
|
2977
3267
|
});
|
|
2978
3268
|
|
|
2979
3269
|
on('prompt.submit', (_$, e, next) => submitPrompt(router, e, next));
|
|
2980
3270
|
|
|
2981
|
-
// A hook failure spawns the agent as Claude Code would; next(e) replays a spawn already made.
|
|
2982
|
-
|
|
2983
|
-
try {
|
|
2984
|
-
on('agent.spawn', ($, e, next) => spawnAgent($, router, e, next)).catch((_$, e, next) => next(e));
|
|
2985
|
-
} catch {}
|
|
3271
|
+
// A hook failure spawns the agent as Claude Code would; next(e) replays a spawn already made.
|
|
3272
|
+
on('agent.spawn', ($, e, next) => spawnAgent($, router, e, next)).catch((_$, e, next) => next(e));
|
|
2986
3273
|
|
|
2987
3274
|
on('turn.step', async function* ($, e, next) {
|
|
2988
3275
|
return yield* stepMain($, router, e, next);
|
|
@@ -2998,10 +3285,11 @@ export function register(on, options) {
|
|
|
2998
3285
|
router.reviews.get(e.turnId)?.controller.abort();
|
|
2999
3286
|
router.reviews.delete(e.turnId);
|
|
3000
3287
|
router.turnControllers.get(e.turnId)?.abort();
|
|
3001
|
-
|
|
3002
|
-
|
|
3288
|
+
const held = router.view;
|
|
3289
|
+
if (held !== null && held.activeTurnId === e.turnId && held.phase === 'choosing') {
|
|
3290
|
+
router.view = { ...held, activeTurnId: null };
|
|
3003
3291
|
const mode = await modeOf($, router);
|
|
3004
|
-
if (router.view
|
|
3292
|
+
if (router.view?.activeTurnId === null)
|
|
3005
3293
|
await updateView($, router, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
|
|
3006
3294
|
}
|
|
3007
3295
|
router.prompts.delete(e.turnId);
|
|
@@ -3009,6 +3297,7 @@ export function register(on, options) {
|
|
|
3009
3297
|
// `off` asks nothing, so it records nothing; it only ends the watch after a cheaper activity move.
|
|
3010
3298
|
const turn = router.turnActivities.get(e.turnId);
|
|
3011
3299
|
router.turnActivities.delete(e.turnId);
|
|
3300
|
+
await placeRouteLine($, router, e, turn);
|
|
3012
3301
|
if (turn?.mode === 'off') {
|
|
3013
3302
|
if ((await $.session.id()) === turn.sessionId) router.afterDown = advanceDown(router.afterDown, turn).after;
|
|
3014
3303
|
} else if (turn) await recordActivity($, router, turn);
|
|
@@ -3022,10 +3311,19 @@ export function register(on, options) {
|
|
|
3022
3311
|
return next(e);
|
|
3023
3312
|
});
|
|
3024
3313
|
|
|
3314
|
+
// Since 2.1.296 (present at the 2.1.321 floor): a turn that ended on an API error. A subagent's is not routed here.
|
|
3315
|
+
// A hook failure leaves the event to the hooks beneath, as without the router.
|
|
3316
|
+
on('classic.StopFailure', async ($, e, next) => {
|
|
3317
|
+
const result = await next(e);
|
|
3318
|
+
if (e.agent_id === undefined) await holdFailedModel($, router, e.error);
|
|
3319
|
+
return result;
|
|
3320
|
+
}).catch((_$, e, next) => next(e));
|
|
3321
|
+
|
|
3025
3322
|
on('session.compact', async ($, e, next) => {
|
|
3026
3323
|
const result = await next(e);
|
|
3027
3324
|
// Only the main conversation is routed, so an agent compaction changes nothing here.
|
|
3028
3325
|
if (!result.skip && e.trigger !== 'precompute' && !e.agentId) {
|
|
3326
|
+
// biome-ignore lint/suspicious/noUnnecessaryConditions: router.trace is set by helpers that take `router`, which Biome cannot follow
|
|
3029
3327
|
if (!router.trace) {
|
|
3030
3328
|
router.traceFreshSession = null;
|
|
3031
3329
|
router.traceClearSession = null;
|
|
@@ -3056,6 +3354,7 @@ export function register(on, options) {
|
|
|
3056
3354
|
if (router.trace?.turns.size) router.trace.reasons.add('aborted');
|
|
3057
3355
|
await flushTrace($, router, null, true);
|
|
3058
3356
|
}
|
|
3357
|
+
// biome-ignore lint/nursery/useAtomicUpdates: the session is over, so whatever trace the final flush held or created is dropped
|
|
3059
3358
|
router.trace = null;
|
|
3060
3359
|
router.traceOperations.clear();
|
|
3061
3360
|
router.traceFreshSession = null;
|
|
@@ -3077,6 +3376,18 @@ export function register(on, options) {
|
|
|
3077
3376
|
return label ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }) : next(e);
|
|
3078
3377
|
});
|
|
3079
3378
|
|
|
3379
|
+
// A route line: drawn from the record the turn's end kept under the row's id. Rows other plugins placed pass.
|
|
3380
|
+
on('ui.render', { component: 'Placed' }, async ($, e, next) => {
|
|
3381
|
+
if (e.props.plugin !== $.plugin.name) return next(e);
|
|
3382
|
+
const { value: line } = await $.state.get({ ...LINES, id: e.props.id });
|
|
3383
|
+
if (!line) return next(e);
|
|
3384
|
+
return renderRouteLine($.ui.resolve(e), router.config, line, {
|
|
3385
|
+
columns: e.viewport?.columns,
|
|
3386
|
+
surface: e.surface,
|
|
3387
|
+
onFallback: logFallback($, 'route line'),
|
|
3388
|
+
});
|
|
3389
|
+
});
|
|
3390
|
+
|
|
3080
3391
|
on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
|
|
3081
3392
|
if (e.component === 'Pane' && e.requestId !== PANE) return next(e);
|
|
3082
3393
|
const storedView = await readView($, router);
|
|
@@ -3097,33 +3408,49 @@ export function register(on, options) {
|
|
|
3097
3408
|
usage,
|
|
3098
3409
|
{
|
|
3099
3410
|
columns: e.props.bodyColumns,
|
|
3411
|
+
surface: e.surface,
|
|
3412
|
+
onFallback: logFallback($, 'band'),
|
|
3100
3413
|
agentId: e.props.view?.agentId,
|
|
3101
3414
|
agent: router.agents.get(e.props.view?.agentId) ?? null,
|
|
3415
|
+
agents: e.props.view?.agentId ? [] : await runningAgents($, router),
|
|
3416
|
+
back: true,
|
|
3102
3417
|
},
|
|
3103
3418
|
{
|
|
3104
3419
|
open: () => openPane($, router),
|
|
3420
|
+
viewAgent: (agentId) => showView($, { agentId }),
|
|
3421
|
+
back: () => showView($, {}),
|
|
3105
3422
|
mode: (mode) => changeMode($, router, mode),
|
|
3106
3423
|
pin: async (tier) => $.ui.toast(await setPin($, router, tier)),
|
|
3107
3424
|
unpin: () => updateView($, router, { pendingPin: null }),
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
await
|
|
3112
|
-
await updateView($, router, {
|
|
3425
|
+
// On a graphical surface the band's Set up opens the pane on how to add the credentials.
|
|
3426
|
+
key: async (press) => {
|
|
3427
|
+
if (!isGraphical(press?.surface ?? e.surface)) return openKeySettings($);
|
|
3428
|
+
await openPane($, router);
|
|
3429
|
+
await updateView($, router, { keyHelp: keyHelpFor(router, router.config.classifier) });
|
|
3113
3430
|
},
|
|
3431
|
+
toggleDetail: () => toggleBandDetail($, router, view),
|
|
3114
3432
|
},
|
|
3115
3433
|
),
|
|
3116
3434
|
],
|
|
3117
3435
|
});
|
|
3118
3436
|
}
|
|
3119
3437
|
view.decisionRows = await paneDecisionRows($, router);
|
|
3438
|
+
// A Set up's key help hides by itself once the credentials it asks for are there; an Edit's waits for Done.
|
|
3439
|
+
const open = view.keyHelp;
|
|
3440
|
+
const keyHelp =
|
|
3441
|
+
open?.id && router.config.classifiers[open.id] && (open.edit || missingCredentials(router.config, view, open.id))
|
|
3442
|
+
? open
|
|
3443
|
+
: null;
|
|
3120
3444
|
const settings = await $.settings.read().catch(() => ({}));
|
|
3121
3445
|
const modelOptions = Object.keys(router.config.models).filter((alias) =>
|
|
3122
3446
|
isModelAllowed(router.config.models[alias].id, settings.availableModels, view.nativeModel),
|
|
3123
3447
|
);
|
|
3124
|
-
return renderPanel(elements, router.config, view, usage, paneActions($, router, view), {
|
|
3448
|
+
return renderPanel(elements, router.config, { ...view, keyHelp }, usage, paneActions($, router, view), {
|
|
3125
3449
|
modelOptions,
|
|
3126
3450
|
columns: e.props.bodyColumns,
|
|
3451
|
+
surface: e.surface,
|
|
3452
|
+
onFallback: logFallback($, 'pane'),
|
|
3453
|
+
pluginId: pluginIdOf({ name: $.plugin.name, root: $.plugin.root }, settings?.enabledPlugins ?? null),
|
|
3127
3454
|
});
|
|
3128
3455
|
});
|
|
3129
3456
|
}
|