@alexeiled/claude-router 1.23.1 → 1.25.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.
Files changed (81) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +62 -1
  3. package/README.md +39 -7
  4. package/docs/architecture.md +27 -4
  5. package/docs/auto-engine.md +152 -0
  6. package/docs/configuration.md +47 -3
  7. package/docs/evaluation.md +222 -3
  8. package/docs/native-router.md +11 -3
  9. package/docs/providers.md +28 -0
  10. package/docs/router-band.svg +124 -133
  11. package/docs/router-pane-classifier.svg +24 -23
  12. package/docs/router-pane-now.svg +9 -7
  13. package/docs/router-pane-policy.svg +4 -4
  14. package/docs/router-pane-routes.svg +8 -8
  15. package/docs/router-pane-usage-whatif.svg +14 -14
  16. package/docs/router-pane-usage.svg +20 -20
  17. package/docs/routing-modes.md +13 -4
  18. package/docs/user-guide.md +79 -19
  19. package/hooks/native-router.mjs +1194 -215
  20. package/lib/activity-stats.mjs +23 -4
  21. package/lib/activity.mjs +7 -5
  22. package/lib/auto-engine.mjs +414 -0
  23. package/lib/auto-route.mjs +253 -0
  24. package/lib/band.mjs +35 -440
  25. package/lib/classifier-client.mjs +12 -8
  26. package/lib/config-file.mjs +7 -2
  27. package/lib/config.mjs +64 -15
  28. package/lib/cost.mjs +5 -1
  29. package/lib/costs.mjs +4 -2
  30. package/lib/decisions.mjs +80 -5
  31. package/lib/display.mjs +69 -20
  32. package/lib/facts.mjs +30 -0
  33. package/lib/modes.mjs +8 -4
  34. package/lib/panel.mjs +75 -2163
  35. package/lib/policy.mjs +7 -6
  36. package/lib/providers.mjs +7 -0
  37. package/lib/replay-trace.mjs +550 -0
  38. package/lib/replay.mjs +718 -0
  39. package/lib/route-line.mjs +46 -0
  40. package/lib/route.mjs +35 -21
  41. package/lib/savings.mjs +14 -3
  42. package/lib/subagents.mjs +41 -11
  43. package/lib/subcommands.mjs +60 -0
  44. package/lib/ui/fallback.mjs +22 -0
  45. package/lib/ui/graphical/band.mjs +256 -0
  46. package/lib/ui/graphical/charts.mjs +163 -0
  47. package/lib/ui/graphical/classifier.mjs +153 -0
  48. package/lib/ui/graphical/frame.mjs +227 -0
  49. package/lib/ui/graphical/kit.mjs +156 -0
  50. package/lib/ui/graphical/meter.mjs +25 -0
  51. package/lib/ui/graphical/now.mjs +353 -0
  52. package/lib/ui/graphical/policy.mjs +56 -0
  53. package/lib/ui/graphical/routes.mjs +264 -0
  54. package/lib/ui/graphical/squares.mjs +29 -0
  55. package/lib/ui/graphical/usage.mjs +376 -0
  56. package/lib/ui/model/band.mjs +439 -0
  57. package/lib/ui/model/classifier.mjs +308 -0
  58. package/lib/ui/model/draft.mjs +62 -0
  59. package/lib/ui/model/format.mjs +41 -0
  60. package/lib/ui/model/frame.mjs +359 -0
  61. package/lib/ui/model/now.mjs +390 -0
  62. package/lib/ui/model/policy.mjs +194 -0
  63. package/lib/ui/model/routes.mjs +392 -0
  64. package/lib/ui/model/usage-agents.mjs +311 -0
  65. package/lib/ui/model/usage-breakdown.mjs +237 -0
  66. package/lib/ui/model/usage-shared.mjs +58 -0
  67. package/lib/ui/model/usage.mjs +330 -0
  68. package/lib/ui/terminal/band.mjs +220 -0
  69. package/lib/ui/terminal/classifier.mjs +142 -0
  70. package/lib/ui/terminal/frame.mjs +169 -0
  71. package/lib/ui/terminal/kit.mjs +133 -0
  72. package/lib/ui/terminal/now.mjs +300 -0
  73. package/lib/ui/terminal/policy.mjs +52 -0
  74. package/lib/ui/terminal/routes.mjs +167 -0
  75. package/lib/ui/terminal/usage.mjs +363 -0
  76. package/lib/ui/terminal/wrap.mjs +37 -0
  77. package/lib/ui/tokens.mjs +106 -0
  78. package/lib/usage.mjs +5 -5
  79. package/lib/view.mjs +5 -2
  80. package/package.json +3 -2
  81. package/types/index.d.ts +15 -0
@@ -1,3 +1,4 @@
1
+ import { acceptActivity, acceptPhase } from '../lib/activity.mjs';
1
2
  import {
2
3
  ACTIVITY_CONTRACT,
3
4
  advanceDown,
@@ -20,7 +21,9 @@ import {
20
21
  storeAfterReset,
21
22
  turnActivity,
22
23
  } from '../lib/activity-stats.mjs';
23
- import { renderBand, switchToast } from '../lib/band.mjs';
24
+ import { advanceDemand, assessCandidates, initialAutoState, selectTarget } from '../lib/auto-engine.mjs';
25
+ import { autoRoute, observeAutoFallback } from '../lib/auto-route.mjs';
26
+ import { renderBand, renderRouteLine, switchToast } from '../lib/band.mjs';
24
27
  import { ClassifierClient } from '../lib/classifier-client.mjs';
25
28
  import { resolveCredentials } from '../lib/classifier-contract.mjs';
26
29
  import {
@@ -34,6 +37,7 @@ import {
34
37
  effectiveRoutes,
35
38
  loadConfig,
36
39
  MIGRATION_HINT,
40
+ MIN_CLAUDE_CODE,
37
41
  ROUTING_MODES,
38
42
  supportedVersion,
39
43
  TIERS,
@@ -73,6 +77,8 @@ import {
73
77
  GATEWAY_SETTINGS,
74
78
  missingCredentials,
75
79
  NOT_A_TIER_REASON,
80
+ pinCard,
81
+ pluginIdOf,
76
82
  savingsLine,
77
83
  storeAgreementLine,
78
84
  unavailableReason,
@@ -84,20 +90,41 @@ import {
84
90
  hasImages,
85
91
  historySignature,
86
92
  observedActivity,
93
+ progressEvidence,
87
94
  promptIndex,
88
95
  routingBucket,
89
96
  stripReminders,
90
97
  } from '../lib/facts.mjs';
91
98
  import { applyMode, modeLabel, readProjectMode, resolveRoutingMode } from '../lib/modes.mjs';
92
- import { renderPanel, routeDraftOf, routingChanges } from '../lib/panel.mjs';
99
+ import { renderPanel } from '../lib/panel.mjs';
93
100
  import { sameTaskOf } from '../lib/policy.mjs';
94
101
  import { providerFile, providerName } from '../lib/providers.mjs';
102
+ import {
103
+ appendTrace,
104
+ bufferTrace,
105
+ mergeTraceExport,
106
+ newTrace,
107
+ readTrace,
108
+ TRACE_ACTIVE_MS,
109
+ TRACE_EXPORT_BYTES,
110
+ TRACE_PREFIX,
111
+ TRACE_SESSION_BYTES,
112
+ TRACE_STORE_BYTES,
113
+ traceAdmission,
114
+ traceBytes,
115
+ traceConfig,
116
+ traceOperation,
117
+ traceResponse,
118
+ traceVictims,
119
+ } from '../lib/replay-trace.mjs';
95
120
  import {
96
121
  canMoveUp,
97
122
  cellForModel,
98
123
  chooseRoute,
99
124
  continueRoute,
125
+ economicConfig,
100
126
  emptyLoop,
127
+ hasRoutedDecision,
101
128
  isModelAllowed,
102
129
  isNativeFallback,
103
130
  isSameModel,
@@ -108,6 +135,7 @@ import {
108
135
  prepareLoop,
109
136
  resetHistory,
110
137
  } from '../lib/route.mjs';
138
+ import { LINE_MODES, lineId, lineModeOf, lineOf, routeOf, showsLine } from '../lib/route-line.mjs';
111
139
  import {
112
140
  afterReset,
113
141
  compareModels,
@@ -142,6 +170,10 @@ import {
142
170
  subagentsAfterReset,
143
171
  typeRoute,
144
172
  } from '../lib/subagents.mjs';
173
+ import { argumentHint, routerSuggestions } from '../lib/subcommands.mjs';
174
+ import { routeDraftOf, routingChanges } from '../lib/ui/model/draft.mjs';
175
+ import { keyHelpOf } from '../lib/ui/model/frame.mjs';
176
+ import { isGraphical } from '../lib/ui/tokens.mjs';
145
177
  import {
146
178
  emptyUsage,
147
179
  mergeUsage,
@@ -168,10 +200,17 @@ import {
168
200
 
169
201
  const VIEW = { plugin: 'router', key: 'view' };
170
202
  const LOOP = { plugin: 'router', key: 'loops' };
203
+ // One record per route line placed, by its `$.ui.place` id: what its `Placed` row draws.
204
+ const LINES = { plugin: 'router', key: 'lines' };
171
205
  const PANE = 'jev-router';
172
206
  const PANE_TITLE = 'Router';
173
207
  const BAND_DETAIL = 'band:detail';
208
+ // Whether and when a turn leaves a route line (lib/route-line.mjs), kept across sessions.
209
+ const ROUTE_LINE = 'route:line';
174
210
  const MODE_PREFIX = 'mode:';
211
+ // When the toast for one reason routing cannot run last showed; the reason is appended.
212
+ const UNAVAILABLE_NOTICE_PREFIX = 'notice:unavailable:';
213
+ const UNAVAILABLE_NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000;
175
214
  // The session's routing mode override (lib/modes.mjs), apart from its auto|manual MODE_PREFIX.
176
215
  const ROUTING_MODE_PREFIX = 'routing-mode:';
177
216
  const isSet = (value) => /^(1|true|yes|on)$/i.test(String(value ?? '').trim());
@@ -230,11 +269,27 @@ const LEDGERS = {
230
269
  };
231
270
  const LEDGER_KINDS = Object.keys(LEDGERS);
232
271
 
272
+ /** @typedef {ReturnType<typeof readTrace> | ReturnType<typeof newTrace>} TraceRecord */
273
+ /**
274
+ * @typedef {object} TraceHold
275
+ * @property {string} sessionId
276
+ * @property {TraceRecord | null} record
277
+ * @property {unknown} persisted
278
+ * @property {number} lostWrites
279
+ * @property {Set<string>} reasons
280
+ * @property {Map<string, any>} turns
281
+ * @property {number} nextTurn
282
+ * @property {string | null} config
283
+ * @property {{ events: object[], excludedEvents?: number } | null} controls
284
+ */
285
+
233
286
  // Everything the hooks change between events, in one object `register()` creates and passes to its helpers. Module
234
287
  // variables, not $.state: a reload starts them over, and the view is written through to $.state as it changes.
235
288
  function createRouter(options) {
236
289
  return {
237
290
  options,
291
+ initialized: false,
292
+ initializing: null,
238
293
  config: loadConfig(),
239
294
  // Each turn's config, fixed at turn.start, so a pane save mid-turn does not change the turn.
240
295
  turnConfigs: new Map(),
@@ -258,10 +313,18 @@ function createRouter(options) {
258
313
  // Each turn's decision rows until turn.complete writes them, with the turn's end, to the session's record, held as
259
314
  // `{ sessionId, record }` once read (`decisionRecord`).
260
315
  turnDecisions: new Map(),
316
+ // The route the last routed turn ran, to tell whether the next one moved it; null at a session's start.
317
+ lastRoute: null,
261
318
  decisionRecord: null,
319
+ trace: /** @type {TraceHold | null} */ (null),
320
+ traceFreshSession: null,
321
+ traceClearSession: null,
322
+ traceStartedSession: null,
323
+ traceFailures: 0,
324
+ traceOperations: new Map(),
262
325
  controllers: new Set(),
263
326
  turnControllers: new Map(),
264
- view: null,
327
+ view: /** @type {Record<string, unknown> | null} */ (null),
265
328
  modes: new Map(),
266
329
  // Each session's routing mode override (null: none), as read from or written to the store.
267
330
  routingModes: new Map(),
@@ -301,6 +364,302 @@ function createRouter(options) {
301
364
  };
302
365
  }
303
366
 
367
+ // These writes share the main-turn lifecycle with decision rows. There is no background writer.
368
+ // Quota scans fail closed; the host has no transaction spanning scans, deletes and a set.
369
+ function traceFailed(router) {
370
+ if (router.trace) {
371
+ router.trace.lostWrites++;
372
+ router.trace.reasons.add('recorder-error');
373
+ } else router.traceFailures++;
374
+ }
375
+
376
+ async function ensureTrace($, router, e, turn, loop, loaded, fresh) {
377
+ try {
378
+ if (turn.config.routingEngine !== 'shadow' || router.config.routingEngine !== 'shadow') {
379
+ if (router.trace) router.trace.reasons.add('mode-gap');
380
+ return;
381
+ }
382
+ const sessionId = await $.session.id();
383
+ if (router.trace?.sessionId === sessionId && router.trace.record) return;
384
+ const previous = router.trace?.sessionId === sessionId ? router.trace : null;
385
+ const at = Date.now();
386
+ /** @type {TraceHold} */
387
+ const held = {
388
+ sessionId,
389
+ record: null,
390
+ persisted: null,
391
+ lostWrites: (previous?.lostWrites ?? 0) + router.traceFailures,
392
+ reasons: new Set(previous?.reasons ?? []),
393
+ turns: new Map(),
394
+ nextTurn: 1,
395
+ config: null,
396
+ controls: null,
397
+ };
398
+ router.trace = held;
399
+ router.traceFailures = 0;
400
+ try {
401
+ const raw = await $.store.get(`${TRACE_PREFIX}${sessionId}`);
402
+ held.record = readTrace(raw);
403
+ held.persisted = raw;
404
+ if (raw !== undefined) held.reasons.add(loaded ? 'reload' : 'resume');
405
+ } catch {
406
+ held.lostWrites++;
407
+ held.reasons.add('lost-write');
408
+ }
409
+ let freshHistory = false;
410
+ if (fresh && e.index === 0 && !loaded && held.persisted === undefined) {
411
+ // API history is normalized for this request; startup reminders are user rows, not prior assistant work.
412
+ const messages = await transcript($);
413
+ freshHistory =
414
+ Array.isArray(messages) &&
415
+ messages.length > 0 &&
416
+ messages.every(
417
+ (message) =>
418
+ message?.role === 'user' &&
419
+ Array.isArray(message.content) &&
420
+ message.content.length > 0 &&
421
+ message.content.every((block) => block && typeof block.type === 'string' && block.type.length > 0),
422
+ );
423
+ }
424
+ if (!freshHistory) held.reasons.add('mid-session');
425
+ held.record ??= newTrace(at, { configured: turn.configured, config: turn.config, loop }, [...held.reasons]);
426
+ if (traceBytes(held.record) > TRACE_SESSION_BYTES - 1024) {
427
+ held.record = {
428
+ version: 1,
429
+ startedAt: at,
430
+ updatedAt: at,
431
+ active: true,
432
+ incomplete: ['mid-session', 'store-guard'],
433
+ lostWrites: 0,
434
+ capped: { at, turns: 0, events: 0 },
435
+ events: [],
436
+ };
437
+ held.reasons.add('store-guard');
438
+ }
439
+ held.config = JSON.stringify({ configured: traceConfig(turn.configured), config: traceConfig(turn.config) });
440
+ } catch {
441
+ traceFailed(router);
442
+ }
443
+ }
444
+
445
+ function traceTurn(router, e) {
446
+ const held = router.trace;
447
+ if (!held) return null;
448
+ if (!held.turns.has(e.turnId)) held.turns.set(e.turnId, { number: held.nextTurn++, buffer: null });
449
+ return held.turns.get(e.turnId);
450
+ }
451
+
452
+ function addTrace(router, e, event) {
453
+ try {
454
+ const held = router.trace;
455
+ if (!held || router.config.routingEngine !== 'shadow') return;
456
+ const turn = traceTurn(router, e);
457
+ if (held.record.capped || turn.buffer?.excludedEvents) {
458
+ turn.buffer = { events: [], bytes: 2, excludedEvents: (turn.buffer?.excludedEvents ?? 0) + 1 };
459
+ return;
460
+ }
461
+ const remaining = Math.max(0, TRACE_SESSION_BYTES - traceBytes(held.record) - 1024);
462
+ turn.buffer = bufferTrace(turn.buffer, { ...event, turn: turn.number, index: e.index }, remaining);
463
+ } catch {
464
+ traceFailed(router);
465
+ }
466
+ }
467
+
468
+ function traceOp(router, e, cfg, kind, input, selected, messages = null) {
469
+ try {
470
+ if (cfg.routingEngine !== 'shadow' || !router.trace || router.config.routingEngine !== 'shadow') return;
471
+ if (router.trace.record.capped || traceTurn(router, e).buffer?.excludedEvents) return;
472
+ const operations = router.traceOperations.get(e.turnId) ?? [];
473
+ operations.push(
474
+ traceOperation(
475
+ kind,
476
+ input.now ?? Date.now(),
477
+ { ...input, taskProgress: messages ? progressEvidence(messages) : null },
478
+ selected,
479
+ ),
480
+ );
481
+ router.traceOperations.set(e.turnId, operations);
482
+ } catch {
483
+ traceFailed(router);
484
+ }
485
+ }
486
+
487
+ function traceRequest(router, e, turn, request, mode, loop) {
488
+ try {
489
+ if (turn.config.routingEngine !== 'shadow' || router.config.routingEngine !== 'shadow' || !router.trace) return;
490
+ const cfg = { configured: traceConfig(turn.configured), config: traceConfig(turn.config) };
491
+ const fingerprint = JSON.stringify(cfg);
492
+ if (router.trace.config !== fingerprint) {
493
+ addTrace(router, e, { type: 'config', at: Date.now(), ...cfg });
494
+ router.trace.config = fingerprint;
495
+ }
496
+ if (router.trace.controls) {
497
+ const controls = router.trace.controls;
498
+ router.trace.controls = null;
499
+ if (controls.excludedEvents) {
500
+ const active = traceTurn(router, e);
501
+ active.buffer = {
502
+ events: [],
503
+ bytes: 2,
504
+ excludedEvents: controls.excludedEvents + (active.buffer?.events.length ?? 0),
505
+ };
506
+ } else for (const event of controls.events) addTrace(router, e, event);
507
+ }
508
+ addTrace(router, e, {
509
+ type: 'request',
510
+ at: Date.now(),
511
+ model: request.model,
512
+ effort: request.effort,
513
+ engineModel: e.model,
514
+ engineEffort: e.effort,
515
+ mode,
516
+ messageCount: e.messageCount,
517
+ reviewedAt: loop.reviewedAt,
518
+ observedFrom: loop.observedFrom,
519
+ operations: router.traceOperations.get(e.turnId) ?? [],
520
+ });
521
+ router.traceOperations.delete(e.turnId);
522
+ } catch {
523
+ traceFailed(router);
524
+ }
525
+ }
526
+
527
+ function recordTraceResponse(router, e, request, response, ttl, at) {
528
+ try {
529
+ addTrace(router, e, traceResponse(at, request, response, ttl));
530
+ } catch {
531
+ traceFailed(router);
532
+ }
533
+ }
534
+
535
+ function traceReset(router, event) {
536
+ try {
537
+ router.trace.controls = bufferTrace(router.trace.controls, event, 4096);
538
+ } catch {
539
+ traceFailed(router);
540
+ }
541
+ }
542
+
543
+ function traceControl(router) {
544
+ try {
545
+ if (router.config.routingEngine !== 'shadow' || !router.trace) return;
546
+ const view = router.view;
547
+ const event = {
548
+ type: 'control',
549
+ at: Date.now(),
550
+ mode: view?.routingMode,
551
+ pin: view?.pendingPin,
552
+ enabled: view?.mode !== 'manual',
553
+ };
554
+ router.trace.controls = bufferTrace(router.trace.controls, event, 4096);
555
+ } catch {
556
+ traceFailed(router);
557
+ }
558
+ }
559
+
560
+ async function flushTrace($, router, turnId = null, ending = false) {
561
+ try {
562
+ const held = router.trace;
563
+ if (!held || router.config.routingEngine !== 'shadow') return;
564
+ const turn = held.turns.get(turnId);
565
+ held.turns.delete(turnId);
566
+ try {
567
+ const at = Date.now();
568
+ const keys = await $.store.keys();
569
+ let entries = await Promise.all(keys.map(async (name) => [name, await $.store.get(name)]));
570
+ if (entries.some(([, value]) => value === undefined)) throw new Error('store-guard');
571
+ if (traceBytes(Object.fromEntries(entries)) > TRACE_STORE_BYTES) throw new Error('store-guard');
572
+ const resetAt = entries.find(([name]) => name === SAVINGS_RESET_KEY)?.[1];
573
+ if (Number.isFinite(resetAt) && held.record.startedAt < resetAt) {
574
+ held.record = {
575
+ version: 1,
576
+ startedAt: at,
577
+ updatedAt: at,
578
+ active: true,
579
+ incomplete: ['reset', 'mid-session'],
580
+ lostWrites: 0,
581
+ capped: null,
582
+ events: [],
583
+ };
584
+ held.persisted = undefined;
585
+ held.reasons.add('reset');
586
+ }
587
+ const key = `${TRACE_PREFIX}${held.sessionId}`;
588
+ const raw = entries.find(([name]) => name === key)?.[1];
589
+ if (raw !== undefined && !readTrace(raw)) throw new Error('conflict');
590
+ if (JSON.stringify(raw) !== JSON.stringify(held.persisted)) {
591
+ held.reasons.add('conflict');
592
+ if (raw)
593
+ held.record = mergeTraceExport(null, [
594
+ [key, held.record],
595
+ [key, raw],
596
+ ]).sessions[key];
597
+ }
598
+ if (held.record.events.length === 1 && traceBytes(held.record) > TRACE_SESSION_BYTES - 1024)
599
+ throw new Error('store-guard');
600
+ const events = turn?.buffer?.events ?? [];
601
+ if (ending && held.controls && !held.controls.excludedEvents) events.push(...held.controls.events);
602
+ const candidate = appendTrace(held.record, events, at, {
603
+ lostWrites: held.lostWrites,
604
+ reasons: [...held.reasons],
605
+ excludedEvents: turn?.buffer?.excludedEvents ?? held.controls?.excludedEvents ?? 0,
606
+ });
607
+ candidate.active = !ending;
608
+ const traces = entries.filter(([name]) => name.startsWith(TRACE_PREFIX));
609
+ for (const victim of traceVictims(traces, at, key, candidate)) {
610
+ const previous = entries.find(([name]) => name === victim)?.[1];
611
+ const current = await $.store.get(victim);
612
+ if (
613
+ readTrace(current) &&
614
+ JSON.stringify(current) === JSON.stringify(previous) &&
615
+ !(current.active && at - current.updatedAt <= TRACE_ACTIVE_MS)
616
+ )
617
+ await $.store.delete(victim);
618
+ }
619
+ // Scan again after eviction: missing/unreadable values never become a quota undercount.
620
+ const after = await $.store.keys();
621
+ entries = await Promise.all(after.map(async (name) => [name, await $.store.get(name)]));
622
+ if (entries.some(([, value]) => value === undefined) || !traceAdmission(entries, key, candidate))
623
+ throw new Error('store-guard');
624
+ await $.store.set(key, candidate);
625
+ held.record = candidate;
626
+ held.persisted = candidate;
627
+ held.lostWrites = 0;
628
+ held.reasons.clear();
629
+ if (ending) held.controls = null;
630
+ } catch (error) {
631
+ held.lostWrites++;
632
+ const message = /** @type {Error} */ (error).message;
633
+ held.reasons.add(message === 'conflict' ? 'conflict' : message === 'store-guard' ? 'store-guard' : 'lost-write');
634
+ }
635
+ } catch {
636
+ traceFailed(router);
637
+ }
638
+ }
639
+
640
+ async function exportTraces($, router) {
641
+ try {
642
+ const keys = (await $.store.keys()).filter((key) => key.startsWith(TRACE_PREFIX));
643
+ const entries = await Promise.all(keys.map(async (key) => [key, await $.store.get(key)]));
644
+ const root = router.config.nativePath.slice(0, router.config.nativePath.lastIndexOf('/'));
645
+ let path = `${root}/router-traces.json`;
646
+ if ((await $.fs.exists(path)) && (await $.fs.stat(path)).isLink) throw new Error('linked export');
647
+ const previous = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
648
+ let merged = mergeTraceExport(previous, entries);
649
+ if (traceBytes(merged) > TRACE_EXPORT_BYTES) {
650
+ path = `${root}/router-traces-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
651
+ if ((await $.fs.exists(path)) && (await $.fs.stat(path)).isLink) throw new Error('linked export');
652
+ const prior = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
653
+ merged = mergeTraceExport(prior, entries);
654
+ }
655
+ if (traceBytes(merged) > TRACE_EXPORT_BYTES) return 'Trace export exceeds the file budget; no file changed.';
656
+ await $.fs.write(path, JSON.stringify(merged));
657
+ return `Exported ${Object.keys(merged.sessions).length} retained trace sessions to ${path}.`;
658
+ } catch {
659
+ return 'Trace export failed; retained traces and existing exports were not intentionally removed.';
660
+ }
661
+ }
662
+
304
663
  function clientOf(router, id) {
305
664
  if (!router.clients.has(id)) router.clients.set(id, new ClassifierClient());
306
665
  return router.clients.get(id);
@@ -313,7 +672,7 @@ async function readView($, router) {
313
672
 
314
673
  // Only a saved mode is cached: the engine can draw the band before session.start, and a cached fallback from that
315
674
  // render would override the start rule.
316
- async function modeOf($, router, fallback = 'auto') {
675
+ async function modeOf($, router, fallback = /** @type {string | null} */ ('auto')) {
317
676
  const sessionId = await $.session.id();
318
677
  if (router.modes.has(sessionId)) return router.modes.get(sessionId);
319
678
  try {
@@ -326,10 +685,14 @@ async function modeOf($, router, fallback = 'auto') {
326
685
  }
327
686
  }
328
687
 
329
- // A saved preference wins; a fresh session starts with routing on for a model some route runs (a tier's, or in `on` an
330
- // activity override's), and off for any other.
688
+ // A saved preference wins. A fresh auto-engine session starts on for any catalog model; table/shadow require a tier
689
+ // route or, with activity routing on, an activity override. Other models start with routing off.
331
690
  async function startMode($, router, model) {
332
- const mode = await modeOf($, router, cellForModel(router.config, model) === null ? 'manual' : 'auto');
691
+ const listed =
692
+ router.config.routingEngine === 'auto'
693
+ ? Object.values(router.config.models).some((spec) => isSameModel(spec.id, model))
694
+ : cellForModel(router.config, model) !== null;
695
+ const mode = await modeOf($, router, listed ? 'auto' : 'manual');
333
696
  router.modes.set(await $.session.id(), mode);
334
697
  return mode;
335
698
  }
@@ -383,7 +746,14 @@ const sameMode = (a, b) => a?.mode === b?.mode && a?.source === b?.source;
383
746
 
384
747
  // A turn's configs when turn.start did not record them, as after a reload of the Mod mid-turn.
385
748
  async function turnConfigOf($, router) {
386
- return { config: applyMode(router.config, await routingModeOf($, router)), configured: router.config };
749
+ const routingMode = await routingModeOf($, router);
750
+ return {
751
+ config:
752
+ router.config.routingEngine === 'auto'
753
+ ? { ...router.config, routingMode }
754
+ : applyMode(router.config, routingMode),
755
+ configured: router.config,
756
+ };
387
757
  }
388
758
 
389
759
  // The turn routes on the configured routes as its routing mode moves them, fixed now so a change mid-turn waits for
@@ -410,6 +780,7 @@ async function setRoutingMode($, router, value) {
410
780
  router.routingModes.set(sessionId, value === 'default' ? null : value);
411
781
  const routingMode = await routingModeOf($, router);
412
782
  await updateView($, router, { routingMode });
783
+ if (router.config.routingEngine === 'shadow') traceControl(router);
413
784
  const unsaved =
414
785
  value === 'default'
415
786
  ? 'A resume of this session may bring the cleared mode back: the store could not be written.'
@@ -435,15 +806,17 @@ async function readProject($, profilePath) {
435
806
  }
436
807
 
437
808
  async function updateView($, router, patch) {
438
- const value = router.view ?? (await readView($, router));
439
- router.view = { ...value, ...patch };
809
+ // Read the stored view only when none is held, and merge into whatever is held once it arrives: a patch applied
810
+ // during that read stays.
811
+ const stored = router.view ? null : await readView($, router);
812
+ router.view = { ...(router.view ?? stored), ...patch };
440
813
  await $.state.set(VIEW, router.view);
441
814
  }
442
815
 
443
816
  // This session's record of `kind`, read from the store once per session, and the last reset (ms) from any session,
444
817
  // read each time: a Reset in another session empties a record held from before it.
445
818
  async function ownRecord($, router, kind) {
446
- const { prefix, read, afterReset } = LEDGERS[kind];
819
+ const { prefix, read, afterReset: resetRecord } = LEDGERS[kind];
447
820
  const held = router.ledgers[kind];
448
821
  const sessionId = await $.session.id();
449
822
  const resetAt = await $.store.get(SAVINGS_RESET_KEY);
@@ -452,7 +825,7 @@ async function ownRecord($, router, kind) {
452
825
  // Another call may have read it meanwhile and a turn added to it: that one stands.
453
826
  if (held.own?.sessionId !== sessionId) held.own = { sessionId, record };
454
827
  }
455
- held.own.record = afterReset(held.own.record, resetAt);
828
+ held.own.record = resetRecord(held.own.record, resetAt);
456
829
  return { own: held.own, resetAt };
457
830
  }
458
831
 
@@ -553,7 +926,10 @@ async function storeView($, router) {
553
926
  // status bar.
554
927
  async function openPane($, router) {
555
928
  await updateView($, router, { notice: null, confirmDelete: false, ...(await storeView($, router)) });
556
- await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
929
+ const opened = await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
930
+ // The pane is open but undrawn, as where no surface places panes or the terminal is too narrow for it; saying why beats
931
+ // a press that shows nothing.
932
+ if (opened?.isPlaced === false) $.ui.toast(`The Router pane is not shown: ${opened.reason}`);
557
933
  }
558
934
 
559
935
  async function changeMode($, router, mode) {
@@ -563,6 +939,30 @@ async function changeMode($, router, mode) {
563
939
  if (mode === 'manual') {
564
940
  router.afterDown = null;
565
941
  router.offSwitches += 1;
942
+ if (
943
+ router.config.routingEngine === 'auto' ||
944
+ [...router.turnConfigs.values()].some((turn) => turn.config.routingEngine === 'auto')
945
+ ) {
946
+ for (const review of router.reviews.values()) review.controller.abort();
947
+ router.reviews.clear();
948
+ router.decisions.clear();
949
+ const ref = { ...LOOP, id: 'main' };
950
+ const loaded = await $.state.get(ref);
951
+ if (loaded.value)
952
+ await $.state.set(
953
+ ref,
954
+ {
955
+ ...loaded.value,
956
+ hasRoutedDecision: hasRoutedDecision(loaded.value),
957
+ auto: null,
958
+ turnId: null,
959
+ decision: null,
960
+ route: null,
961
+ generation: loaded.value.generation + 1,
962
+ },
963
+ { ifVersion: loaded.version },
964
+ );
965
+ }
566
966
  }
567
967
  router.modes.set(await $.session.id(), mode);
568
968
  const saved = await rememberMode($, mode);
@@ -573,6 +973,7 @@ async function changeMode($, router, mode) {
573
973
  reason: mode === 'manual' ? 'routing off' : 'ready',
574
974
  ...(!saved ? { notice: 'Mode changed for this session. Resume preference could not be saved.' } : {}),
575
975
  });
976
+ if (router.config.routingEngine === 'shadow') traceControl(router);
576
977
  }
577
978
 
578
979
  async function setPin($, router, tier) {
@@ -582,34 +983,71 @@ async function setPin($, router, tier) {
582
983
  if (mode === 'manual') return 'Routing is off. Turn routing on before pinning a turn.';
583
984
  router.pinPresses += 1;
584
985
  await updateView($, router, { pendingPin: tier });
986
+ if (router.config.routingEngine === 'shadow') traceControl(router);
585
987
  return `${tier} pinned for the next turn and its tool continuations.`;
586
988
  }
587
989
 
588
- // `/router [auto|off|pin <tier>|activities <mode>|mode <mode>]`; with no action, the pane, or the status text without
589
- // a surface.
990
+ // What each word of the SUBCOMMANDS table does: a switch, since the engine reads `$` only where it is passed to a
991
+ // function it can name. A word with no case, or one that answers nothing, leaves the command to open the pane.
992
+ async function runSubcommand($, router, action, value) {
993
+ switch (action) {
994
+ case 'auto':
995
+ return switchRouting($, router, 'auto');
996
+ case 'off':
997
+ return switchRouting($, router, 'manual');
998
+ case 'trace':
999
+ return value === 'export' ? { text: await exportTraces($, router) } : undefined;
1000
+ case 'line':
1001
+ return {
1002
+ text: LINE_MODES.includes(value) ? await setRouteLine($, value) : `Choose line ${LINE_MODES.join(', ')}.`,
1003
+ };
1004
+ case 'decisions':
1005
+ return { text: await decisionsText($, router, value) };
1006
+ case 'pin':
1007
+ return { text: TIERS.includes(value) ? await setPin($, router, value) : `Choose ${TIERS.join(', ')}.` };
1008
+ case 'mode':
1009
+ return {
1010
+ text: [...ROUTING_MODES, 'default'].includes(value)
1011
+ ? await setRoutingMode($, router, value)
1012
+ : `Choose mode ${[...ROUTING_MODES, 'default'].join(', ')}.`,
1013
+ };
1014
+ case 'activities':
1015
+ return {
1016
+ text: ACTIVITY_MODES.includes(value)
1017
+ ? await setActivityRouting($, router, value)
1018
+ : `Choose activities ${ACTIVITY_MODES.join(', ')}.`,
1019
+ };
1020
+ default:
1021
+ return undefined;
1022
+ }
1023
+ }
1024
+
1025
+ // `/router line <mode>`: a preference like the band's second row, kept across sessions and never in router.json.
1026
+ async function setRouteLine($, mode) {
1027
+ const saved = await $.store.set(ROUTE_LINE, mode).then(
1028
+ () => true,
1029
+ () => false,
1030
+ );
1031
+ const says = {
1032
+ off: 'no route line after a turn',
1033
+ moves: 'a route line after a turn that ran another model or effort than the last',
1034
+ all: 'a route line after every turn',
1035
+ };
1036
+ return `Route line ${mode}: ${says[mode]}.${saved ? '' : ' It could not be saved for later sessions.'}`;
1037
+ }
1038
+
1039
+ async function switchRouting($, router, mode) {
1040
+ const view = router.view ?? (await readView($, router));
1041
+ if (view.phase === 'unavailable') return { text: unavailableText(view) };
1042
+ await changeMode($, router, mode);
1043
+ return { text: mode === 'auto' ? 'Routing on.' : 'Routing off: Claude’s model is kept.' };
1044
+ }
1045
+
1046
+ // `/router [word [value]]`, the words of SUBCOMMANDS; with none, the pane, or the status text without a surface.
590
1047
  async function routerCommand($, router, args) {
591
1048
  const [action, value] = args.trim().split(/\s+/);
592
- if (action === 'auto' || action === 'off') {
593
- const view = router.view ?? (await readView($, router));
594
- if (view.phase === 'unavailable') return { text: unavailableText(view) };
595
- await changeMode($, router, action === 'auto' ? 'auto' : 'manual');
596
- return { text: action === 'auto' ? 'Routing on.' : 'Routing off: Claude’s model is kept.' };
597
- }
598
- if (action === 'decisions') return { text: await decisionsText($, router, value) };
599
- if (action === 'pin')
600
- return { text: TIERS.includes(value) ? await setPin($, router, value) : `Choose ${TIERS.join(', ')}.` };
601
- if (action === 'mode')
602
- return {
603
- text: [...ROUTING_MODES, 'default'].includes(value)
604
- ? await setRoutingMode($, router, value)
605
- : `Choose mode ${[...ROUTING_MODES, 'default'].join(', ')}.`,
606
- };
607
- if (action === 'activities')
608
- return {
609
- text: ACTIVITY_MODES.includes(value)
610
- ? await setActivityRouting($, router, value)
611
- : `Choose activities ${ACTIVITY_MODES.join(', ')}.`,
612
- };
1049
+ const answer = await runSubcommand($, router, action, value);
1050
+ if (answer) return answer;
613
1051
  const storedView = await readView($, router);
614
1052
  const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
615
1053
  if (!(await $.session.surfaces()).length)
@@ -668,6 +1106,51 @@ async function credentialsOf($, options, config) {
668
1106
  );
669
1107
  }
670
1108
 
1109
+ // A Set up or Edit press: in the terminal, the secure key dialog of `/plugin configure`; a graphical surface, which
1110
+ // has no such dialog (the command does nothing there), shows how to add the credentials from a terminal instead, in
1111
+ // the pane, for classifier `id`.
1112
+ async function keySetup($, router, press, id) {
1113
+ if (!isGraphical(press?.surface)) {
1114
+ openKeySettings($);
1115
+ return $.ui.close({ id: PANE });
1116
+ }
1117
+ await updateView($, router, { keyHelp: keyHelpFor(router, id ?? router.config.classifier), notice: null });
1118
+ }
1119
+
1120
+ // A graphical band or pane that throws draws the terminal tree; the error goes to the debug log, never the transcript.
1121
+ const logFallback = ($, what) => (error) =>
1122
+ $.ui.log(`graphical ${what} failed, drew the terminal one: ${error instanceof Error ? error.message : error}`, {
1123
+ to: 'debug',
1124
+ });
1125
+
1126
+ // The key help to open for classifier `id`: an Edit, when nothing is missing, stays open until Done.
1127
+ const keyHelpFor = (router, id) => ({
1128
+ id,
1129
+ edit: !missingCredentials(router.config, router.view ?? {}, id),
1130
+ });
1131
+
1132
+ // The plugin's id for `claude plugin configure`: from its install path, else settings' enabledPlugins.
1133
+ async function pluginIdFor($) {
1134
+ const plugin = { name: $.plugin.name, root: $.plugin.root };
1135
+ const settings = await $.settings.read().catch(() => ({}));
1136
+ return pluginIdOf(plugin, settings?.enabledPlugins ?? null);
1137
+ }
1138
+
1139
+ // The pane's credential handlers: Set up or Edit, and the key help's Copy command and Done.
1140
+ function keyActions($, router, view) {
1141
+ return {
1142
+ key: (press, id) => keySetup($, router, press, id),
1143
+ copyKeyHelp: async (press) => {
1144
+ const open = (router.view ?? view).keyHelp;
1145
+ const help = open && keyHelpOf(router.config, open.id, await pluginIdFor($), { edit: open.edit });
1146
+ if (!help) return;
1147
+ await $.ui.copy({ text: help.command, surface: press?.surface });
1148
+ await updateView($, router, { notice: 'Copied' });
1149
+ },
1150
+ keyHelpDone: () => updateView($, router, { keyHelp: null, notice: null }),
1151
+ };
1152
+ }
1153
+
671
1154
  // The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
672
1155
  function openKeySettings($) {
673
1156
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
@@ -775,11 +1258,15 @@ async function contextOf($, loop) {
775
1258
  }
776
1259
  }
777
1260
 
778
- async function* passMain($, e, next, loop, version, nativeModel, reason, router) {
1261
+ async function* passMain($, e, next, previous, version, nativeModel, reason, router) {
779
1262
  // A turn routing did not choose is a turn on another route: it ends the watch for escalations after a cheaper
780
1263
  // activity move, including one a turn started before routing was turned off mid-turn.
781
1264
  if (reason === 'manual') router.afterDown = null;
782
1265
  const ref = { ...LOOP, id: 'main' };
1266
+ const turn = router.turnConfigs.get(e.turnId) ?? { config: router.config, configured: router.config };
1267
+ const auto = turn.config.routingEngine === 'auto';
1268
+ const loop =
1269
+ reason === 'manual' && auto ? { ...previous, auto: null, route: null, decision: null, turnId: null } : previous;
783
1270
  const context = await contextOf($, loop);
784
1271
  await updateView($, router, {
785
1272
  nativeModel,
@@ -790,32 +1277,130 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, router)
790
1277
  contextKnown: context.known,
791
1278
  });
792
1279
  const sessionId = await $.session.id();
1280
+ if (turn.config.routingEngine === 'shadow')
1281
+ traceRequest(router, e, turn, e, reason === 'manual' ? 'manual' : 'auto', loop);
793
1282
  const response = yield* next(e);
794
1283
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
795
- const observed = observeResponse(router.config, loop, {
1284
+ const at = Date.now();
1285
+ const cfg = auto ? turn.config : router.config;
1286
+ let observed = observeResponse(cfg, loop, {
796
1287
  usage: response.usage,
797
1288
  requestedModel: e.model,
798
1289
  effort: e.effort ?? null,
799
1290
  stopReason: response.stopReason,
800
- now: Date.now(),
1291
+ now: at,
801
1292
  });
1293
+ if (auto && ['no-route-native', 'native-fallback'].includes(reason))
1294
+ observed = {
1295
+ ...observeAutoFallback(cfg, observed, {
1296
+ requestedModel: e.model,
1297
+ effort: e.effort,
1298
+ usage: response.usage,
1299
+ }),
1300
+ suspended: true,
1301
+ };
1302
+ if (reason === 'no-route-native' && loop.auto?.savedPin) {
1303
+ observed.switchedAt = loop.auto.savedPin.switchedAt;
1304
+ observed.servedRoute = loop.auto.savedPin.servedRoute;
1305
+ }
802
1306
  // Before routing has chosen a route, the one in use is the model serving now: /model can change it with routing
803
1307
  // off. Once a decision exists, the last routed route is kept, as for every model.
804
- if (reason === 'manual' && !loop.decision) observed.route = ownRoute(router.config, e.model);
1308
+ if (reason === 'manual' && !loop.decision && !auto) observed.route = ownRoute(router.config, e.model);
805
1309
  // Routing chose nothing here, so the reply is not counted; your model's cache still follows it.
806
- const compared = await compareYours($, router, loop, response, e.effort ?? null, nativeModel);
1310
+ const compared = await compareYours($, router, loop, response, e.effort ?? null, nativeModel, cfg);
807
1311
  if (compared) observed.yoursBy = compared.states;
808
1312
  const written = await $.state.set(ref, observed, { ifVersion: version });
1313
+ if (turn.config.routingEngine === 'shadow') {
1314
+ if (written.isSet) recordTraceResponse(router, e, e, response, compared?.ttl, at);
1315
+ else router.trace?.reasons.add('gap');
1316
+ }
809
1317
  if (written.isSet)
810
1318
  await updateView($, router, {
811
1319
  ...responseMetrics(router.view, response, null, Date.now()),
812
1320
  delegatedModel: e.model,
813
1321
  delegatedEffort: e.effort ?? null,
814
1322
  });
815
- }
1323
+ } else if (turn.config.routingEngine === 'shadow') router.trace?.reasons.add('aborted');
816
1324
  return response;
817
1325
  }
818
1326
 
1327
+ // Shadow retains demand evidence only; target selection sees the actual incumbent and cache.
1328
+ function shadowProposal(
1329
+ config,
1330
+ loop,
1331
+ selected,
1332
+ { facts, advice, pin, nativeModel, contextKnown, availableModels, now, mode, offSwitches },
1333
+ ) {
1334
+ if (config.routingEngine !== 'shadow') {
1335
+ delete selected.shadow;
1336
+ return null;
1337
+ }
1338
+ try {
1339
+ const projected = economicConfig(config, loop);
1340
+ const beforePin = loop.decision?.pinned ? loop.route : null;
1341
+ const model = loop.decision?.pinned && !beforePin ? nativeModel : (loop.decision?.model ?? nativeModel);
1342
+ const alias = Object.keys(config.models).find(
1343
+ (key) => isSameModel(config.models[key].id, model) || isSameModel(projected.models[key].id, model),
1344
+ );
1345
+ const incumbent = beforePin ?? {
1346
+ model: alias ?? model,
1347
+ effort: loop.decision?.pinned ? (facts.effort ?? null) : (loop.decision?.effort ?? facts.effort ?? null),
1348
+ };
1349
+ const initial = TIERS.indexOf(config.baselineTier);
1350
+ const state =
1351
+ loop.shadow?.generation === loop.generation && loop.shadow.offSwitches === offSwitches
1352
+ ? loop.shadow.state
1353
+ : initialAutoState({ demand: initial });
1354
+ const demand = advanceDemand({
1355
+ config,
1356
+ state,
1357
+ advice,
1358
+ facts,
1359
+ pin,
1360
+ boundedExecute:
1361
+ config.activityRouting === 'on' &&
1362
+ acceptActivity(config, advice) !== null &&
1363
+ acceptPhase(config, advice) === 'execute',
1364
+ });
1365
+ const candidates = assessCandidates({
1366
+ config: projected,
1367
+ facts: { ...facts, ineligible: loop.ineligible.map((id) => loop.resolutions[id] ?? id) },
1368
+ now,
1369
+ incumbent,
1370
+ contextKnown,
1371
+ availableModels,
1372
+ nativeModel,
1373
+ });
1374
+ const target = selectTarget({
1375
+ candidates,
1376
+ demand: demand.level,
1377
+ mode: pin ? 'balanced' : mode,
1378
+ headroom: demand.headroom,
1379
+ escalation: demand.escalated,
1380
+ });
1381
+ if (demand.escalated || demand.headroom) demand.state = { ...demand.state, headroom: target.headroom };
1382
+ const { routedDemand: _routed, routeCause: _cause, ...demandState } = pin ? state : demand.state;
1383
+ selected.shadow = { generation: loop.generation, offSwitches, state: demandState };
1384
+ return {
1385
+ demand: demand.level,
1386
+ reason: demand.reason,
1387
+ headroom: target.headroom,
1388
+ targetReason: target.reason,
1389
+ requirement: target.requirement,
1390
+ outcome: target.outcome,
1391
+ route: target.route
1392
+ ? `${target.route.model}@${typeof target.route.effort === 'string' ? target.route.effort : 'session'}`
1393
+ : null,
1394
+ capability: target.capability,
1395
+ minUsd: target.estimate?.minUsd,
1396
+ maxUsd: target.estimate?.maxUsd,
1397
+ };
1398
+ } catch {
1399
+ delete selected.shadow;
1400
+ return { reason: 'error' };
1401
+ }
1402
+ }
1403
+
819
1404
  // One turn's classification and route, written to the loop at `loopVersion`: the loop and its new version, or null
820
1405
  // when the turn was aborted, left the session or Auto, or lost the write. `signal` is the step's: its abort cancels
821
1406
  // the classifier call. The pin is the one in `view`, the view as the step read it; it is used up only once the route
@@ -823,7 +1408,7 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, router)
823
1408
  async function decideTurn($, router, e, signal, step) {
824
1409
  const { sessionId, view, loop, loopVersion, context, nativeModel, availableModels } = step;
825
1410
  // A pin runs its tier's configured route: the routing mode moves only routes the router chooses.
826
- const cfg = view.pendingPin ? step.configured : step.cfg;
1411
+ const cfg = view.pendingPin && step.cfg.routingEngine !== 'auto' ? step.configured : step.cfg;
827
1412
  const ref = { ...LOOP, id: 'main' };
828
1413
  const controller = new AbortController();
829
1414
  const cancel = () => controller.abort();
@@ -886,7 +1471,7 @@ async function decideTurn($, router, e, signal, step) {
886
1471
  const previous = loop.decision;
887
1472
  if (pin)
888
1473
  router.turnConfigs.set(e.turnId, { config: { ...cfg, routingMode: step.cfg.routingMode }, configured: cfg });
889
- const selected = chooseRoute(cfg, loop, {
1474
+ const traceInput = {
890
1475
  facts,
891
1476
  advice: result.advice,
892
1477
  pin,
@@ -894,6 +1479,21 @@ async function decideTurn($, router, e, signal, step) {
894
1479
  contextKnown: context.known,
895
1480
  availableModels,
896
1481
  now: Date.now(),
1482
+ };
1483
+ const selected =
1484
+ cfg.routingEngine === 'auto'
1485
+ ? autoRoute(cfg, loop, { ...traceInput, engineModel: e.model })
1486
+ : chooseRoute(cfg, loop, traceInput);
1487
+ const alt = shadowProposal(step.configured, loop, selected, {
1488
+ facts,
1489
+ advice: result.advice,
1490
+ pin,
1491
+ nativeModel,
1492
+ contextKnown: context.known,
1493
+ availableModels,
1494
+ now: Date.now(),
1495
+ mode: step.cfg.routingMode.mode,
1496
+ offSwitches: router.offSwitches,
897
1497
  });
898
1498
  selected.engineModel = e.model;
899
1499
  const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
@@ -901,6 +1501,7 @@ async function decideTurn($, router, e, signal, step) {
901
1501
  if (written.isSet && pin) router.turnPins.set(e.turnId, pinPresses);
902
1502
  // Manual, /clear and turn completion abort the controller; one may land during the write.
903
1503
  if (!written.isSet || controller.signal.aborted) return null;
1504
+ if (cfg.routingEngine === 'shadow') traceOp(router, e, cfg, 'choose', traceInput, selected, messages);
904
1505
  rememberGoal(router, e.turnId, result.advice, cfg.policy.continuationMass, messages);
905
1506
  if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
906
1507
  $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
@@ -919,6 +1520,8 @@ async function decideTurn($, router, e, signal, step) {
919
1520
  decision: selected.decision,
920
1521
  facts,
921
1522
  sameTask: sameTaskOf(cfg, result.advice, facts),
1523
+ engine: cfg.routingEngine,
1524
+ alt,
922
1525
  }),
923
1526
  );
924
1527
  // One line per decision in Claude Code's debug log, so a later replay can compare modes. No prompt text.
@@ -1025,14 +1628,16 @@ const activityLabel = (cfg, decision) => (cfg.activityRouting === 'on' ? (decisi
1025
1628
  // tool calls after the last applied review count (`loop.observedFrom`): the review judged the ones before. The
1026
1629
  // transcript is read only when some activity's route at this tier is stronger than the running one.
1027
1630
  async function moveOnObserved($, router, cfg, loop, e, context) {
1028
- if (!canMoveUp(cfg, loop.decision, e.effort)) return loop;
1631
+ if (cfg.routingEngine === 'auto' || !canMoveUp(cfg, loop.decision, e.effort)) return loop;
1029
1632
  const messages = await transcript($);
1030
1633
  if (!messages) return loop;
1031
1634
  const facts = stepFacts(cfg, router, loop, e, messages, context);
1032
1635
  const observed = routingBucket(
1033
1636
  observedActivity(messages, Math.max(promptIndex(messages), (loop.observedFrom ?? 0) - 1)),
1034
1637
  );
1035
- const moved = observedMove(cfg, loop, { observed, facts, contextKnown: context.known, now: Date.now() });
1638
+ const traceInput = { observed, facts, contextKnown: context.known, now: Date.now() };
1639
+ const moved = observedMove(cfg, loop, traceInput);
1640
+ if (cfg.routingEngine === 'shadow') traceOp(router, e, cfg, 'observed', traceInput, moved, messages);
1036
1641
  if (moved === loop) return loop;
1037
1642
  addDecision(
1038
1643
  router,
@@ -1040,6 +1645,7 @@ async function moveOnObserved($, router, cfg, loop, e, context) {
1040
1645
  decisionRow({
1041
1646
  at: Date.now(),
1042
1647
  kind: 'observed',
1648
+ engine: cfg.routingEngine,
1043
1649
  origin: router.turnOrigins.get(e.turnId) ?? 'unknown',
1044
1650
  mode: cfg.routingMode?.mode ?? null,
1045
1651
  decision: moved.decision,
@@ -1075,7 +1681,7 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1075
1681
  const advice =
1076
1682
  messages.length === review.observedUpTo ? review.answer.advice : { ...review.answer.advice, phase: null };
1077
1683
  const facts = { ...stepFacts(cfg, router, loop, e, messages, context), midTurn: true };
1078
- const selected = chooseRoute(cfg, loop, {
1684
+ const traceInput = {
1079
1685
  facts,
1080
1686
  advice,
1081
1687
  pin: null,
@@ -1083,8 +1689,23 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1083
1689
  contextKnown: context.known,
1084
1690
  availableModels,
1085
1691
  now: Date.now(),
1086
- });
1692
+ };
1693
+ const selected =
1694
+ cfg.routingEngine === 'auto' ? autoRoute(cfg, loop, traceInput) : chooseRoute(cfg, loop, traceInput);
1695
+ if (cfg.routingEngine === 'shadow') traceOp(router, e, cfg, 'choose', traceInput, selected, messages);
1087
1696
  const previous = loop.decision;
1697
+ const configured = router.turnConfigs.get(e.turnId)?.configured ?? router.config;
1698
+ const alt = shadowProposal(configured, loop, selected, {
1699
+ facts,
1700
+ advice,
1701
+ pin: null,
1702
+ nativeModel,
1703
+ contextKnown: context.known,
1704
+ availableModels,
1705
+ now: Date.now(),
1706
+ mode: cfg.routingMode?.mode ?? DEFAULTS.mode,
1707
+ offSwitches: router.offSwitches,
1708
+ });
1088
1709
  addDecision(
1089
1710
  router,
1090
1711
  e.turnId,
@@ -1097,6 +1718,8 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1097
1718
  decision: selected.decision,
1098
1719
  facts,
1099
1720
  sameTask: sameTaskOf(cfg, advice, facts),
1721
+ engine: configured.routingEngine,
1722
+ alt,
1100
1723
  }),
1101
1724
  );
1102
1725
  if (previous && (previous.model !== selected.decision.model || previous.effort !== selected.decision.effort)) {
@@ -1142,8 +1765,7 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1142
1765
  resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name)),
1143
1766
  $.session.messages({ as: 'api' }),
1144
1767
  ]);
1145
- job.observedUpTo = messages.length;
1146
- job.prefix = historySignature(messages);
1768
+ Object.assign(job, { observedUpTo: messages.length, prefix: historySignature(messages) });
1147
1769
  const facts = stepFacts(cfg, router, loop, e, messages, context);
1148
1770
  clientOf(router, cfg.classifier)
1149
1771
  .ask({
@@ -1172,7 +1794,17 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1172
1794
  }
1173
1795
 
1174
1796
  // 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.
1175
- async function publishReply($, router, turnId, request, response, tier, route, routedUsd, cause = null) {
1797
+ async function publishReply(
1798
+ $,
1799
+ router,
1800
+ turnId,
1801
+ request,
1802
+ response,
1803
+ tier,
1804
+ route,
1805
+ routedUsd,
1806
+ cause = /** @type {string | null} */ (null),
1807
+ ) {
1176
1808
  const turn = router.turnActivities.get(turnId);
1177
1809
  const metrics = responseMetrics(router.view, response, tier, Date.now());
1178
1810
  await updateView($, router, {
@@ -1198,7 +1830,7 @@ async function publishReply($, router, turnId, request, response, tier, route, r
1198
1830
  async function observeRouted($, router, { turnId, cfg, loop, loopVersion, request, response, nativeModel }) {
1199
1831
  // When the reply arrived: the awaits below can cross midnight or the hour it is kept under.
1200
1832
  const at = Date.now();
1201
- const observed = observeResponse(cfg, loop, {
1833
+ let observed = observeResponse(cfg, loop, {
1202
1834
  usage: response.usage,
1203
1835
  requestedModel: request.model,
1204
1836
  effort: request.effort ?? null,
@@ -1206,10 +1838,24 @@ async function observeRouted($, router, { turnId, cfg, loop, loopVersion, reques
1206
1838
  now: at,
1207
1839
  });
1208
1840
  if (response.stopReason === null) observed.suspended = true;
1841
+ if (cfg.routingEngine === 'auto' && response.usage?.model && !isSameModel(request.model, response.usage.model))
1842
+ observed = observeAutoFallback(cfg, observed, {
1843
+ requestedModel: request.model,
1844
+ effort: request.effort,
1845
+ usage: response.usage,
1846
+ });
1847
+ if (cfg.routingEngine === 'auto' && loop.auto?.savedPin) {
1848
+ observed.switchedAt = loop.auto.savedPin.switchedAt;
1849
+ observed.servedRoute = loop.auto.savedPin.servedRoute;
1850
+ }
1209
1851
  const compared = await compareYours($, router, loop, response, request.effort ?? null, nativeModel, cfg);
1210
1852
  if (compared) observed.yoursBy = compared.states;
1211
1853
  const written = await $.state.set({ ...LOOP, id: 'main' }, observed, { ifVersion: loopVersion });
1212
- if (!written.isSet) return;
1854
+ if (!written.isSet) {
1855
+ if (cfg.routingEngine === 'shadow') router.trace?.reasons.add('gap');
1856
+ return;
1857
+ }
1858
+ if (cfg.routingEngine === 'shadow') recordTraceResponse(router, request, request, response, compared?.ttl, at);
1213
1859
  // A substituted reply is not the tier's: the strip and trend must not count it as one.
1214
1860
  const tier = isSameModel(request.model, response.usage?.model) ? loop.decision.tier : null;
1215
1861
  const route = `${request.model}@${request.effort ?? 'session'}`;
@@ -1338,6 +1984,7 @@ async function flushUsage($, router, turnId, switched) {
1338
1984
  // its report as dialogue (progressInput); without a goal from this session it reads as before. A goal origin's prompt
1339
1985
  // becomes the goal.
1340
1986
  async function startTurn($, router, e) {
1987
+ if (!(await ensureInitialized($, router))) return;
1341
1988
  const epoch = ++router.goalEpoch;
1342
1989
  router.goalTurnId = e.turnId;
1343
1990
  await fixTurnConfig($, router, e.turnId);
@@ -1414,11 +2061,13 @@ async function submitPrompt(router, e, next) {
1414
2061
  router.submitting = entry;
1415
2062
  try {
1416
2063
  const result = await next(e);
2064
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: turn.start sets `started` through router.submitting, an alias Biome cannot follow
1417
2065
  if (!entry.started && typeof result?.text === 'string' && !result.drop)
1418
2066
  router.origins = queueOrigin(router.origins, { kind: entry.kind, text: result.text, at: Date.now() });
1419
2067
  return result;
1420
2068
  } finally {
1421
- router.submitting = outer;
2069
+ // Only the submission still current restores: a later one that started meanwhile keeps its entry.
2070
+ if (router.submitting === entry) router.submitting = outer;
1422
2071
  }
1423
2072
  }
1424
2073
 
@@ -1439,6 +2088,26 @@ function originOfTurn(router, text) {
1439
2088
  return taken.kind;
1440
2089
  }
1441
2090
 
2091
+ // A routed turn's route line: one record in `$.state`, one row placed at the transcript's end. Not for an interrupted
2092
+ // turn, a subagent's, or a turn with routing off, which has no route of its own to say. Display only, so a failure
2093
+ // here never breaks the turn, and a surface that cannot draw the row now is logged, not told.
2094
+ async function placeRouteLine($, router, e, turn) {
2095
+ try {
2096
+ const view = router.view;
2097
+ const route = routeOf(view);
2098
+ if (!turn || e.isAborted || !route || !view || view.phase === 'unavailable') return;
2099
+ if ((await modeOf($, router, view.mode)) === 'manual') return;
2100
+ const previous = router.lastRoute;
2101
+ router.lastRoute = route;
2102
+ const mode = lineModeOf(await $.store.get(ROUTE_LINE).catch(() => undefined));
2103
+ if (!showsLine(mode, previous, route)) return;
2104
+ const id = lineId(e.turnId);
2105
+ await $.state.set({ ...LINES, id }, lineOf(router.config, view, route));
2106
+ const placed = await $.ui.place({ id });
2107
+ if (!placed.isPlaced) $.ui.log(`router route line not drawn: ${placed.reason}`, { to: 'debug' });
2108
+ } catch {}
2109
+ }
2110
+
1442
2111
  // A finished turn's decision rows and its end row, added to this session's record. Telemetry never breaks a turn: a
1443
2112
  // failed read or write loses this turn's rows. A record from before the last reset reads as empty, and rows read
1444
2113
  // before a Reset in this session are not written back.
@@ -1455,8 +2124,11 @@ async function flushDecisions($, router, turnId, turn) {
1455
2124
  if (turn && turn.sessionId !== sessionId) return;
1456
2125
  const key = `${DECISIONS_PREFIX}${sessionId}`;
1457
2126
  const resetAt = await $.store.get(SAVINGS_RESET_KEY);
1458
- if (router.decisionRecord?.sessionId !== sessionId)
1459
- router.decisionRecord = { sessionId, record: readDecisions(await $.store.get(key)) };
2127
+ if (router.decisionRecord?.sessionId !== sessionId) {
2128
+ const record = readDecisions(await $.store.get(key));
2129
+ // Another flush may have read it meanwhile and added its rows to it: that one stands.
2130
+ if (router.decisionRecord?.sessionId !== sessionId) router.decisionRecord = { sessionId, record };
2131
+ }
1460
2132
  const held = router.decisionRecord;
1461
2133
  const now = Date.now();
1462
2134
  const end = turn
@@ -1506,6 +2178,17 @@ async function pruneDecisionRecords($) {
1506
2178
  }
1507
2179
 
1508
2180
  // `/router decisions [n]`: this session's newest routing decisions, the running turn's included.
2181
+ async function paneDecisionRows($, router) {
2182
+ if (!['shadow', 'auto'].includes(router.config.routingEngine)) return [];
2183
+ const sessionId = await $.session.id();
2184
+ const record =
2185
+ router.decisionRecord?.sessionId === sessionId
2186
+ ? router.decisionRecord.record
2187
+ : readDecisions(await $.store.get(`${DECISIONS_PREFIX}${sessionId}`).catch(() => null));
2188
+ const resetAt = await $.store.get(SAVINGS_RESET_KEY).catch(() => null);
2189
+ return [...decisionsAfterReset(record, resetAt).rows, ...[...router.turnDecisions.values()].flat()];
2190
+ }
2191
+
1509
2192
  async function decisionsText($, router, value) {
1510
2193
  const n = Math.min(MAX_ROWS, Math.max(1, Number.parseInt(value, 10) || 20));
1511
2194
  try {
@@ -1532,12 +2215,12 @@ async function recordActivity($, router, turn) {
1532
2215
  const start = promptIndex(messages);
1533
2216
  if (start < 0) return;
1534
2217
  const observed = observedActivity(messages, start);
1535
- // The turn's end row reads it (flushDecisions).
1536
- turn.observed = observed;
1537
2218
  const view = router.view ?? (await readView($, router));
1538
2219
  const manual = (await modeOf($, router)) === 'manual';
1539
2220
  // The session may have changed during the reads; this turn is not the new session's.
1540
2221
  if ((await $.session.id()) !== turn.sessionId) return;
2222
+ // The turn's end row reads it (flushDecisions).
2223
+ turn.observed = observed;
1541
2224
  // Advanced before any further await, so a session change meanwhile cannot carry this run into the new session.
1542
2225
  const { run, ended } = advanceRun(router.run, turn.answer);
1543
2226
  router.run = run;
@@ -1679,6 +2362,18 @@ async function decideSpawn($, router, cfg, e, definition, signal) {
1679
2362
  // Claude Code uses in place of the Agent call's `model` and the agent's frontmatter. Routing off or unavailable keeps
1680
2363
  // every model Claude Code chooses, and records nothing.
1681
2364
  async function spawnAgent($, router, e, next) {
2365
+ // A resumed agent keeps the model and the record of its first spawn: a hook can only refuse a resume. It runs again
2366
+ // from here, so the band's rows show it before its first reply.
2367
+ if (e.resume) {
2368
+ const result = await next(e);
2369
+ const agent = router.agents.get(e.resume.agentId);
2370
+ if (agent && !agent.running) {
2371
+ router.agents.set(e.resume.agentId, { ...agent, running: true });
2372
+ await showRunning($, router);
2373
+ }
2374
+ return result;
2375
+ }
2376
+ if (!(await ensureInitialized($, router))) return next(e);
1682
2377
  const cfg = router.config;
1683
2378
  if (cfg.subagentRouting === 'off') return next(e);
1684
2379
  const view = router.view ?? (await readView($, router));
@@ -1687,7 +2382,7 @@ async function spawnAgent($, router, e, next) {
1687
2382
  const pass = passReason(cfg, e, definition);
1688
2383
  const decision = pass ? null : await decideSpawn($, router, cfg, e, definition, next.signal).catch(() => null);
1689
2384
  const routed = Boolean(decision?.model);
1690
- const result = await next(routed ? { ...e, model: decision.model } : e);
2385
+ const result = await next(decision?.model ? { ...e, model: decision.model } : e);
1691
2386
  if (result.agentId && (pass || decision))
1692
2387
  await noteSpawn($, router, { cfg, e, pass, decision, routed, result, definition }).catch(() => {});
1693
2388
  return result;
@@ -1721,11 +2416,32 @@ async function noteSpawn($, router, { cfg, e, pass, decision, routed, result, de
1721
2416
  await showRunning($, router);
1722
2417
  }
1723
2418
 
1724
- // How many of the agents with a record are between their start or a step and their turn's end, in the view when it
1725
- // changes. An agent spawned with routing off has no record and is not counted.
2419
+ // 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
2420
+ // when the set changes: the band draws a row for each. An agent spawned with routing off has no record and is not
2421
+ // listed.
1726
2422
  async function showRunning($, router) {
1727
- const running = [...router.agents.values()].filter((agent) => agent.running).length;
1728
- if ((router.view?.subagentsRunning ?? 0) !== running) await updateView($, router, { subagentsRunning: running });
2423
+ const ids = [...router.agents].filter(([, agent]) => agent.running).map(([id]) => id);
2424
+ if ((router.view?.subagentIds ?? []).join(' ') !== ids.join(' '))
2425
+ await updateView($, router, { subagentsRunning: ids.length, subagentIds: ids });
2426
+ }
2427
+
2428
+ // The band's rows: the agents with a record that Claude Code still lists as running, never a teammate, whose own
2429
+ // session the person opens from the tasks list. The list names the type and the task; the record the model.
2430
+ async function runningAgents($, router) {
2431
+ const listed = await $.agent.list().catch(() => []);
2432
+ return listed.flatMap((agent) => {
2433
+ const record = router.agents.get(agent.id);
2434
+ return record?.running && !agent.teammateId && ['running', 'waiting'].includes(agent.status)
2435
+ ? [{ id: agent.id, type: agent.type, description: agent.description, record }]
2436
+ : [];
2437
+ });
2438
+ }
2439
+
2440
+ // A press on an agent's row, or on Back, shows that transcript in the main view. Claude Code allows it only while the
2441
+ // call answers the person's own input, so a press is the one place to ask; a refusal is told.
2442
+ async function showView($, view) {
2443
+ const shown = await $.ui.view(view).catch(() => ({ deny: 'Could not switch the view.' }));
2444
+ if (shown.deny) $.ui.toast(shown.deny);
1729
2445
  }
1730
2446
 
1731
2447
  // A subagent's prompt-cache lifetime, by Claude Code's rule for requests outside the main conversation.
@@ -1780,6 +2496,26 @@ async function flushSubagents($, router, agents) {
1780
2496
  } catch {}
1781
2497
  }
1782
2498
 
2499
+ function traceConfigAdopted(router, loaded) {
2500
+ try {
2501
+ if (router.config.routingEngine !== 'shadow' || loaded.routingEngine === 'shadow' || !router.trace) return;
2502
+ router.trace.reasons.add('mode-gap');
2503
+ router.trace.turns.clear();
2504
+ router.traceOperations.clear();
2505
+ router.trace.controls = null;
2506
+ } catch {
2507
+ traceFailed(router);
2508
+ }
2509
+ }
2510
+
2511
+ // 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
2512
+ // caller was drawn from, and `router.view` holds any press since.
2513
+ async function toggleBandDetail($, router, view) {
2514
+ const bandDetail = !(router.view ?? view).bandDetail;
2515
+ await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
2516
+ await updateView($, router, { bandDetail });
2517
+ }
2518
+
1783
2519
  // The pane's handlers. `view` is the view the pane was drawn from; a handler reads `router.view` first, which holds
1784
2520
  // any press since.
1785
2521
  function paneActions($, router, view) {
@@ -1808,7 +2544,9 @@ function paneActions($, router, view) {
1808
2544
  // an unavailable reason stays.
1809
2545
  const adopt = async (loaded) => {
1810
2546
  const switched = loaded.classifier !== router.config.classifier;
2547
+ traceConfigAdopted(router, loaded);
1811
2548
  router.config = loaded;
2549
+
1812
2550
  if (!switched) return {};
1813
2551
  clientOf(router, router.config.classifier).restore(null);
1814
2552
  const current = router.view ?? view;
@@ -1878,14 +2616,12 @@ function paneActions($, router, view) {
1878
2616
  mode: (mode) => changeMode($, router, mode),
1879
2617
  tab: (tab) => updateView($, router, { tab, notice: null, confirmDelete: false }),
1880
2618
  help: () => updateView($, router, { help: !(router.view ?? view).help }),
2619
+ toggleDetail: () => toggleBandDetail($, router, view),
1881
2620
  pin: async (tier) => {
1882
2621
  await updateView($, router, { notice: await setPin($, router, tier) });
1883
2622
  },
1884
2623
  unpin: () => updateView($, router, { pendingPin: null, notice: null }),
1885
- key: async () => {
1886
- openKeySettings($);
1887
- await $.ui.close({ id: PANE });
1888
- },
2624
+ ...keyActions($, router, view),
1889
2625
  copyPath: async (press) => {
1890
2626
  await $.ui.copy({ text: router.config.nativePath, surface: press?.surface });
1891
2627
  await updateView($, router, { notice: 'Path copied.' });
@@ -1974,6 +2710,7 @@ function paneActions($, router, view) {
1974
2710
  const keys = (await $.store.keys()).filter(
1975
2711
  (key) =>
1976
2712
  key.startsWith(DECISIONS_PREFIX) ||
2713
+ key.startsWith(TRACE_PREFIX) ||
1977
2714
  key === LEGACY_STORE_PREFIX ||
1978
2715
  key.startsWith(`${LEGACY_STORE_PREFIX}:`) ||
1979
2716
  Object.values(LEDGERS).some(({ prefix, legacy }) => key.startsWith(prefix) || key === legacy),
@@ -1983,6 +2720,10 @@ function paneActions($, router, view) {
1983
2720
  router.ledgers[kind] = { own: null, others: LEDGERS[kind].empty(), othersResetAt: resetAt };
1984
2721
  return true;
1985
2722
  };
2723
+ router.trace = null;
2724
+ router.traceFreshSession = null;
2725
+ router.traceClearSession = null;
2726
+ router.traceOperations.clear();
1986
2727
  const cleared = await clearRecords().catch(() => false);
1987
2728
  // The store kept the history: this session's records start over, and its next write replaces the stored one.
1988
2729
  if (!cleared)
@@ -2111,68 +2852,315 @@ async function imagesOf($, config, decision) {
2111
2852
  return messages === null || hasImages(messages);
2112
2853
  }
2113
2854
 
2855
+ function startError(supported, gateway) {
2856
+ if (!supported) return `requires Claude Code ${MIN_CLAUDE_CODE} or newer`;
2857
+ if (gateway) return GATEWAY_SETTINGS;
2858
+ return null;
2859
+ }
2860
+
2114
2861
  function configurationError(error) {
2115
2862
  if (error.message?.endsWith(MIGRATION_HINT))
2116
2863
  return 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path';
2117
2864
  return error.message === 'selected provider router file is missing' ? error.message : 'invalid router configuration';
2118
2865
  }
2119
2866
 
2120
- export function register(on, options) {
2121
- const router = createRouter(options);
2867
+ async function* sendRouted($, router, e, next, { cfg, loop, loopVersion, sessionId, nativeModel, turn }) {
2868
+ const pinPresses = router.turnPins.get(e.turnId);
2869
+ if (pinPresses !== undefined) {
2870
+ router.turnPins.delete(e.turnId);
2871
+ if (pinPresses === router.pinPresses) await updateView($, router, { pendingPin: null });
2872
+ }
2873
+ if (cfg.routingEngine === 'auto' && !loop.decision.route)
2874
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'no-route-native', router);
2875
+ const request = { ...e, model: loop.decision.model };
2876
+ if (loop.decision.effort === null) delete request.effort;
2877
+ else request.effort = loop.decision.effort;
2878
+ if (cfg.routingEngine === 'shadow' && !next.signal.aborted && (await $.session.id()) === sessionId)
2879
+ traceRequest(router, e, router.turnConfigs.get(e.turnId) ?? turn, request, 'auto', loop);
2880
+ const response = yield* next(request);
2881
+ if (!next.signal.aborted && (await $.session.id()) === sessionId)
2882
+ await observeRouted($, router, { turnId: e.turnId, cfg, loop, loopVersion, request, response, nativeModel });
2883
+ else if (cfg.routingEngine === 'shadow') router.trace?.reasons.add('aborted');
2884
+ return response;
2885
+ }
2122
2886
 
2123
- on('session.start', async ($, e, next) => {
2124
- router.definitions.clear();
2125
- await $.command.register({
2126
- name: 'router',
2127
- description:
2128
- 'Open the Router pane, or switch routing: auto, off, pin <tier>, activities <mode>, mode <mode>; decisions [n] lists the last routing decisions.',
2129
- argumentHint: '[auto|off|pin <tier>|activities off|on|mode cost|balanced|quality|default|decisions [n]]',
2130
- immediate: true,
2131
- });
2132
- const model = await $.session.model();
2887
+ function resetEngine(router, cfg, configured, model, messageCount, previous) {
2888
+ let loop = previous;
2889
+ // Engine state is incompatible, but physical cache/usage observations remain valid across engine changes.
2890
+ if ((cfg.routingEngine === 'auto' || loop.activeEngine === 'auto') && loop.activeEngine !== cfg.routingEngine) {
2891
+ const fresh = emptyLoop(configured, model);
2892
+ loop = {
2893
+ ...loop,
2894
+ lastRoute: fresh.lastRoute,
2895
+ lastActivity: fresh.lastActivity,
2896
+ route: fresh.route,
2897
+ state: fresh.state,
2898
+ turnId: null,
2899
+ decision: null,
2900
+ suspended: false,
2901
+ reviewedAt: loop.requests,
2902
+ observedFrom: messageCount,
2903
+ auto: null,
2904
+ shadow: undefined,
2905
+ generation: loop.generation + 1,
2906
+ activeEngine: cfg.routingEngine,
2907
+ };
2908
+ for (const review of router.reviews.values()) review.controller.abort();
2909
+ router.reviews.clear();
2910
+ router.decisions.clear();
2911
+ }
2912
+ return loop;
2913
+ }
2914
+
2915
+ async function continueAuto($, router, cfg, prior, e, context, traceInput) {
2916
+ let loop = prior;
2917
+ const messages = await transcript($);
2918
+ const facts = { ...stepFacts(cfg, router, loop, e, messages ?? [], context), midTurn: true };
2919
+ // An unreadable transcript cannot establish that an image-ineligible request is safe.
2920
+ facts.hasImages = messages ? hasImages(messages) : true;
2921
+ const observed = messages
2922
+ ? routingBucket(observedActivity(messages, Math.max(promptIndex(messages), (loop.observedFrom ?? 0) - 1)))
2923
+ : null;
2924
+ const previous = loop.decision;
2925
+ loop = autoRoute(cfg, loop, { ...traceInput, facts, now: Date.now() }, { continuation: true, observed });
2926
+ if (JSON.stringify(previous.auto) !== JSON.stringify(loop.decision.auto))
2927
+ addDecision(
2928
+ router,
2929
+ e.turnId,
2930
+ decisionRow({
2931
+ at: Date.now(),
2932
+ kind: 'observed',
2933
+ engine: 'auto',
2934
+ mode: cfg.routingMode.mode,
2935
+ decision: loop.decision,
2936
+ facts,
2937
+ }),
2938
+ );
2939
+
2940
+ return loop;
2941
+ }
2942
+
2943
+ async function traceContinuation($, router, cfg, loop, e, traceInput) {
2944
+ if (cfg.routingEngine === 'shadow') {
2945
+ // Replay's incumbent may differ from the table's: retain unconditional modality and checkpoint evidence.
2946
+ // Failure stays unknown, never a false assertion that the hypothetical route can accept this history.
2947
+ let replayMessages;
2948
+ let actualHasImages = null;
2133
2949
  try {
2134
- router.config = await loadNativeConfig($);
2135
- router.project = await readProject($, router.config.nativePath);
2136
- const existing = await readView($, router);
2137
- router.view = existing;
2138
- const sameClassifier = existing.health?.classifier === router.config.classifier;
2139
- clientOf(router, router.config.classifier).restore(sameClassifier ? existing.health : null);
2140
- const base = await $.env.get('ANTHROPIC_BASE_URL');
2141
- const version = await $.session.version().catch(() => null);
2142
- const supported = supportedVersion(version?.version);
2143
- const gateway =
2144
- ['jev-router', 'jev-router[1m]'].includes(model) ||
2145
- model === 'router' ||
2146
- Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
2147
- await updateView($, router, {
2148
- nativeModel: model,
2149
- ...(existing.activityContract !== ACTIVITY_CONTRACT
2150
- ? { activityContract: ACTIVITY_CONTRACT, activityStats: null }
2151
- : {}),
2152
- ...(await startView($, router, model)),
2153
- phase: gateway || !supported ? 'unavailable' : 'ready',
2154
- error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
2155
- ...(sameClassifier ? {} : CLEARED_READINGS),
2156
- credentials: await credentialsOf($, options, router.config),
2157
- health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
2158
- configPath: router.config.nativePath,
2159
- routingMode: await routingModeOf($, router),
2160
- projectError: router.project.error,
2161
- tuning: null,
2162
- tuningBase: null,
2163
- routeDraft: null,
2164
- lastWrite: null,
2165
- bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
2166
- usagePeriod: await periodOf($),
2167
- ...(await storeView($, router)),
2168
- });
2169
- await pruneDecisionRecords($);
2170
- } catch (error) {
2171
- await updateView($, router, {
2172
- phase: 'unavailable',
2173
- error: configurationError(error),
2950
+ replayMessages = await transcript($);
2951
+ if (replayMessages) actualHasImages = hasImages(replayMessages);
2952
+ } catch {
2953
+ replayMessages = null;
2954
+ }
2955
+ traceOp(router, e, cfg, 'continue', { ...traceInput, actualHasImages }, loop, replayMessages);
2956
+ }
2957
+ }
2958
+
2959
+ async function* stepMain($, router, e, next) {
2960
+ if (!(await ensureInitialized($, router))) return yield* next(e);
2961
+ if (e.agentId) return yield* stepAgent($, router, e, next);
2962
+ const turn = router.turnConfigs.get(e.turnId) ?? (await turnConfigOf($, router));
2963
+ const cfg = turn.config;
2964
+ const [sessionId, nativeModel, view] = await Promise.all([$.session.id(), $.session.model(), readView($, router)]);
2965
+ const mode = await modeOf($, router, view.mode);
2966
+ const freshTrace =
2967
+ router.traceFreshSession === sessionId ||
2968
+ (router.traceClearSession !== null && router.traceClearSession !== sessionId);
2969
+ router.traceFreshSession = null;
2970
+ router.traceClearSession = null;
2971
+ if (e.index === 0) {
2972
+ const saved = await rememberMode($, mode);
2973
+ await updateView($, router, {
2974
+ mode,
2975
+ nativeEffort: e.effort ?? null,
2976
+ ...(!saved ? { notice: 'Resume preference could not be saved. Current mode remains active.' } : {}),
2977
+ });
2978
+ }
2979
+ const ref = { ...LOOP, id: 'main' };
2980
+ const loaded = await $.state.get(ref);
2981
+ let loopVersion = loaded.version;
2982
+ // The session's model names its tier in the configured routes: a mode's table can run it at another tier.
2983
+ let loop = prepareLoop(loaded.value ?? emptyLoop(turn.configured, e.model), e.messageCount);
2984
+ loop = resetEngine(router, cfg, turn.configured, e.model, e.messageCount, loop);
2985
+ if (loaded.value && loop.generation !== loaded.value.generation) clearGoal(router);
2986
+ if (cfg.routingEngine === 'shadow' && router.config.routingEngine === 'shadow') {
2987
+ await ensureTrace($, router, e, turn, loop, Boolean(loaded.value), freshTrace);
2988
+ router.traceOperations.delete(e.turnId);
2989
+ if (loaded.value && loop.generation !== loaded.value.generation)
2990
+ addTrace(router, e, { type: 'reset', at: Date.now(), cause: 'history', loop, generation: loop.generation });
2991
+ } else if (router.trace) router.trace.reasons.add('mode-gap');
2992
+ if (view.phase === 'unavailable' || mode === 'manual') {
2993
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', router);
2994
+ }
2995
+ if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
2996
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', router);
2997
+ }
2998
+ const [context, settings] = await Promise.all([contextOf($, loop), $.settings.read()]);
2999
+ const availableModels = settings.availableModels;
3000
+ const key = `${sessionId}:${e.turnId}:${loop.generation}`;
3001
+ if (loop.turnId !== e.turnId) {
3002
+ let job = router.decisions.get(key);
3003
+ if (!job) {
3004
+ job = decideTurn($, router, e, next.signal, {
3005
+ sessionId,
3006
+ view,
3007
+ cfg,
3008
+ configured: turn.configured,
3009
+ loop,
3010
+ loopVersion,
3011
+ context,
3012
+ nativeModel,
3013
+ availableModels,
2174
3014
  });
3015
+ router.decisions.set(key, job);
3016
+ }
3017
+ const selected = await job;
3018
+ if (!selected) {
3019
+ if (!next.signal.aborted && (await $.session.id()) === sessionId && router.view?.activeTurnId === e.turnId) {
3020
+ const reserved = await $.state.set(ref, loop, { ifVersion: loopVersion });
3021
+ if (reserved.isSet) return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', router);
3022
+ }
3023
+ return yield* next(e);
2175
3024
  }
3025
+ loop = selected.loop;
3026
+ loopVersion = selected.version;
3027
+ } else {
3028
+ // A review answer applies first, so tool calls made after its snapshot can still move the route up.
3029
+ loop = await reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, availableModels });
3030
+ loop = await moveOnObserved($, router, cfg, loop, e, context);
3031
+ const traceInput = {
3032
+ hasImages: cfg.routingEngine === 'auto' ? false : await imagesOf($, cfg, loop.decision),
3033
+ nativeModel,
3034
+ contextTokens: context.tokens,
3035
+ contextKnown: context.known,
3036
+ availableModels,
3037
+ effort: e.effort,
3038
+ };
3039
+ loop =
3040
+ cfg.routingEngine === 'auto'
3041
+ ? await continueAuto($, router, cfg, loop, e, context, traceInput)
3042
+ : continueRoute(cfg, loop, traceInput);
3043
+ await traceContinuation($, router, cfg, loop, e, traceInput);
3044
+ await updateView($, router, continuationView(cfg, loop.decision, context));
3045
+ }
3046
+ if (
3047
+ cfg.routingEngine === 'auto' &&
3048
+ (next.signal.aborted || (await $.session.id()) !== sessionId || (await modeOf($, router)) !== 'auto')
3049
+ )
3050
+ return yield* next(e);
3051
+ return yield* sendRouted($, router, e, next, { cfg, loop, loopVersion, sessionId, nativeModel, turn });
3052
+ }
3053
+
3054
+ async function initializeSession($, router) {
3055
+ router.definitions.clear();
3056
+ await $.command.register({
3057
+ name: 'router',
3058
+ description:
3059
+ 'Open the Router pane, or switch routing: auto, off, pin <tier>, activities <mode>, mode <mode>, line <mode>; decisions [n] lists the last routing decisions.',
3060
+ argumentHint: argumentHint(),
3061
+ immediate: true,
3062
+ });
3063
+ const model = await $.session.model();
3064
+ try {
3065
+ const config = await loadNativeConfig($);
3066
+ const project = await readProject($, config.nativePath);
3067
+ const existing = await readView($, router);
3068
+ // A successful reload adopts this config even for the current turn; stale jobs must not route with the old engine.
3069
+ Object.assign(router, { config, project, view: existing });
3070
+ for (const controller of router.controllers) controller.abort();
3071
+ router.decisions.clear();
3072
+ router.turnConfigs.clear();
3073
+ for (const review of router.reviews.values()) review.controller.abort();
3074
+ router.reviews.clear();
3075
+ const sameClassifier = existing.health?.classifier === router.config.classifier;
3076
+ clientOf(router, router.config.classifier).restore(sameClassifier ? existing.health : null);
3077
+ const base = await $.env.get('ANTHROPIC_BASE_URL');
3078
+ const version = await $.session.version().catch(() => null);
3079
+ const supported = supportedVersion(version?.version);
3080
+ const gateway =
3081
+ ['jev-router', 'jev-router[1m]'].includes(model) ||
3082
+ model === 'router' ||
3083
+ Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
3084
+ await updateView($, router, {
3085
+ nativeModel: model,
3086
+ ...(existing.activityContract !== ACTIVITY_CONTRACT
3087
+ ? { activityContract: ACTIVITY_CONTRACT, activityStats: null }
3088
+ : {}),
3089
+ ...(await startView($, router, model)),
3090
+ phase: gateway || !supported ? 'unavailable' : 'ready',
3091
+ error: startError(supported, gateway),
3092
+ ...(sameClassifier ? {} : CLEARED_READINGS),
3093
+ credentials: await credentialsOf($, router.options, router.config),
3094
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
3095
+ configPath: router.config.nativePath,
3096
+ routingMode: await routingModeOf($, router),
3097
+ projectError: router.project.error,
3098
+ tuning: null,
3099
+ tuningBase: null,
3100
+ routeDraft: null,
3101
+ lastWrite: null,
3102
+ bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
3103
+ usagePeriod: await periodOf($),
3104
+ ...(await storeView($, router)),
3105
+ });
3106
+ await pruneDecisionRecords($);
3107
+ // biome-ignore lint/nursery/useAtomicUpdates: ensureInitialized runs this once at a time, and the flag marks it done
3108
+ router.initialized = true;
3109
+ return true;
3110
+ } catch (error) {
3111
+ await updateView($, router, {
3112
+ phase: 'unavailable',
3113
+ error: configurationError(error),
3114
+ });
3115
+ return false;
3116
+ }
3117
+ }
3118
+
3119
+ // What made routing unavailable, as the notice keys it: an old Claude Code, the v0.8 gateway settings, or a router.json
3120
+ // that did not load.
3121
+ function unavailableCause(error) {
3122
+ if (error?.startsWith('requires Claude Code')) return 'version';
3123
+ return error === GATEWAY_SETTINGS ? 'gateway' : 'config';
3124
+ }
3125
+
3126
+ // One toast when a session starts with routing unavailable, at most once a day per cause: the band says it too, but not
3127
+ // once it is collapsed or scrolled away. Not for a headless run, which has no one to read it. The day is recorded before
3128
+ // the toast, so a toast no surface draws is not retried until tomorrow.
3129
+ async function noticeUnavailable($, router, e) {
3130
+ const view = router.view;
3131
+ if (view?.phase !== 'unavailable' || !e.isInteractive || !e.surface) return;
3132
+ try {
3133
+ const key = `${UNAVAILABLE_NOTICE_PREFIX}${unavailableCause(view.error)}`;
3134
+ const last = await $.store.get(key);
3135
+ const now = Date.now();
3136
+ if (Number.isFinite(last) && now - last >= 0 && now - last < UNAVAILABLE_NOTICE_INTERVAL_MS) return;
3137
+ await $.store.set(key, now);
3138
+ $.ui.toast(`Routing off: ${unavailableReason(view)}. Claude’s model is kept.`);
3139
+ } catch {}
3140
+ }
3141
+
3142
+ async function ensureInitialized($, router) {
3143
+ if (router.initialized) return true;
3144
+ router.initializing ??= initializeSession($, router).finally(() => {
3145
+ router.initializing = null;
3146
+ });
3147
+ return router.initializing;
3148
+ }
3149
+
3150
+ export function register(on, options) {
3151
+ const router = createRouter(options);
3152
+
3153
+ on('session.start', async ($, e, next) => {
3154
+ const sessionId = await $.session.id();
3155
+ // Lazy profile loading is not a lifecycle signal; only a real Mod start can establish freshness.
3156
+ router.traceFreshSession = router.traceStartedSession !== sessionId ? sessionId : null;
3157
+ router.traceStartedSession = sessionId;
3158
+ router.trace = null;
3159
+ router.traceOperations.clear();
3160
+ router.lastRoute = null;
3161
+ router.initialized = false;
3162
+ await ensureInitialized($, router);
3163
+ await noticeUnavailable($, router, e);
2176
3164
  return next(e);
2177
3165
  });
2178
3166
 
@@ -2196,100 +3184,29 @@ export function register(on, options) {
2196
3184
 
2197
3185
  on('command.run', { command: 'router' }, ($, e) => routerCommand($, router, e.args));
2198
3186
 
3187
+ // The words after `/router `, once one character is typed (the token is never empty). A matcher tests the token
3188
+ // alone, so the hook reads the text before it. Nothing is read or written but the router's own view.
3189
+ on('prompt.autocomplete', async (_$, e, next) => {
3190
+ const mine = routerSuggestions(e, {
3191
+ describe: (name, value) => (name === 'pin' && router.view ? pinCard(router.config, value) : undefined),
3192
+ });
3193
+ if (!mine.length) return next(e);
3194
+ return { suggestions: [...(await next(e)).suggestions, ...mine] };
3195
+ });
3196
+
3197
+ // 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.
2199
3198
  on('turn.start', async ($, e, next) => {
2200
- await startTurn($, router, e);
3199
+ if (e.agentId === undefined) await startTurn($, router, e);
2201
3200
  return next(e);
2202
3201
  });
2203
3202
 
2204
3203
  on('prompt.submit', (_$, e, next) => submitPrompt(router, e, next));
2205
3204
 
2206
- // A hook failure spawns the agent as Claude Code would; next(e) replays a spawn already made. agent.spawn and a
2207
- // catchable on() are in the 2.1.293 build types, not checked on 2.1.289: an engine without them still loads routing.
2208
- try {
2209
- on('agent.spawn', ($, e, next) => spawnAgent($, router, e, next)).catch((_$, e, next) => next(e));
2210
- } catch {}
3205
+ // A hook failure spawns the agent as Claude Code would; next(e) replays a spawn already made.
3206
+ on('agent.spawn', ($, e, next) => spawnAgent($, router, e, next)).catch((_$, e, next) => next(e));
2211
3207
 
2212
3208
  on('turn.step', async function* ($, e, next) {
2213
- if (e.agentId) return yield* stepAgent($, router, e, next);
2214
- const turn = router.turnConfigs.get(e.turnId) ?? (await turnConfigOf($, router));
2215
- const cfg = turn.config;
2216
- const [sessionId, nativeModel, view] = await Promise.all([$.session.id(), $.session.model(), readView($, router)]);
2217
- const mode = await modeOf($, router, view.mode);
2218
- if (e.index === 0) {
2219
- const saved = await rememberMode($, mode);
2220
- await updateView($, router, {
2221
- mode,
2222
- nativeEffort: e.effort ?? null,
2223
- ...(!saved ? { notice: 'Resume preference could not be saved. Current mode remains active.' } : {}),
2224
- });
2225
- }
2226
- const ref = { ...LOOP, id: 'main' };
2227
- const loaded = await $.state.get(ref);
2228
- let loopVersion = loaded.version;
2229
- // The session's model names its tier in the configured routes: a mode's table can run it at another tier.
2230
- let loop = prepareLoop(loaded.value ?? emptyLoop(turn.configured, e.model), e.messageCount);
2231
- if (loaded.value && loop.generation !== loaded.value.generation) clearGoal(router);
2232
- if (view.phase === 'unavailable' || mode === 'manual') {
2233
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', router);
2234
- }
2235
- if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
2236
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', router);
2237
- }
2238
- const [context, settings] = await Promise.all([contextOf($, loop), $.settings.read()]);
2239
- const availableModels = settings.availableModels;
2240
- const key = `${sessionId}:${e.turnId}:${loop.generation}`;
2241
- if (loop.turnId !== e.turnId) {
2242
- let job = router.decisions.get(key);
2243
- if (!job) {
2244
- job = decideTurn($, router, e, next.signal, {
2245
- sessionId,
2246
- view,
2247
- cfg,
2248
- configured: turn.configured,
2249
- loop,
2250
- loopVersion,
2251
- context,
2252
- nativeModel,
2253
- availableModels,
2254
- });
2255
- router.decisions.set(key, job);
2256
- }
2257
- const selected = await job;
2258
- if (!selected) {
2259
- if (!next.signal.aborted && (await $.session.id()) === sessionId && router.view?.activeTurnId === e.turnId) {
2260
- const reserved = await $.state.set(ref, loop, { ifVersion: loopVersion });
2261
- if (reserved.isSet) return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', router);
2262
- }
2263
- return yield* next(e);
2264
- }
2265
- loop = selected.loop;
2266
- loopVersion = selected.version;
2267
- } else {
2268
- // A review answer applies first, so tool calls made after its snapshot can still move the route up.
2269
- loop = await reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, availableModels });
2270
- loop = await moveOnObserved($, router, cfg, loop, e, context);
2271
- loop = continueRoute(cfg, loop, {
2272
- hasImages: await imagesOf($, cfg, loop.decision),
2273
- nativeModel,
2274
- contextTokens: context.tokens,
2275
- contextKnown: context.known,
2276
- availableModels,
2277
- effort: e.effort,
2278
- });
2279
- await updateView($, router, continuationView(cfg, loop.decision, context));
2280
- }
2281
- const pinPresses = router.turnPins.get(e.turnId);
2282
- if (pinPresses !== undefined) {
2283
- router.turnPins.delete(e.turnId);
2284
- if (pinPresses === router.pinPresses) await updateView($, router, { pendingPin: null });
2285
- }
2286
- const request = { ...e, model: loop.decision.model };
2287
- if (loop.decision.effort === null) delete request.effort;
2288
- else request.effort = loop.decision.effort;
2289
- const response = yield* next(request);
2290
- if (!next.signal.aborted && (await $.session.id()) === sessionId)
2291
- await observeRouted($, router, { turnId: e.turnId, cfg, loop, loopVersion, request, response, nativeModel });
2292
- return response;
3209
+ return yield* stepMain($, router, e, next);
2293
3210
  });
2294
3211
 
2295
3212
  on('turn.complete', async ($, e, next) => {
@@ -2302,10 +3219,11 @@ export function register(on, options) {
2302
3219
  router.reviews.get(e.turnId)?.controller.abort();
2303
3220
  router.reviews.delete(e.turnId);
2304
3221
  router.turnControllers.get(e.turnId)?.abort();
2305
- if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
2306
- router.view = { ...router.view, activeTurnId: null };
3222
+ const held = router.view;
3223
+ if (held !== null && held.activeTurnId === e.turnId && held.phase === 'choosing') {
3224
+ router.view = { ...held, activeTurnId: null };
2307
3225
  const mode = await modeOf($, router);
2308
- if (router.view.activeTurnId === null)
3226
+ if (router.view?.activeTurnId === null)
2309
3227
  await updateView($, router, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
2310
3228
  }
2311
3229
  router.prompts.delete(e.turnId);
@@ -2313,11 +3231,17 @@ export function register(on, options) {
2313
3231
  // `off` asks nothing, so it records nothing; it only ends the watch after a cheaper activity move.
2314
3232
  const turn = router.turnActivities.get(e.turnId);
2315
3233
  router.turnActivities.delete(e.turnId);
3234
+ await placeRouteLine($, router, e, turn);
2316
3235
  if (turn?.mode === 'off') {
2317
3236
  if ((await $.session.id()) === turn.sessionId) router.afterDown = advanceDown(router.afterDown, turn).after;
2318
3237
  } else if (turn) await recordActivity($, router, turn);
2319
3238
  if (router.turnUsage.has(e.turnId)) await flushUsage($, router, e.turnId, turn?.switched ?? null);
2320
3239
  await flushDecisions($, router, e.turnId, turn);
3240
+ if (router.config.routingEngine === 'shadow' && router.trace?.turns.has(e.turnId)) {
3241
+ addTrace(router, e, { type: 'end', at: Date.now() });
3242
+ await flushTrace($, router, e.turnId);
3243
+ }
3244
+ router.traceOperations.delete(e.turnId);
2321
3245
  return next(e);
2322
3246
  });
2323
3247
 
@@ -2325,16 +3249,42 @@ export function register(on, options) {
2325
3249
  const result = await next(e);
2326
3250
  // Only the main conversation is routed, so an agent compaction changes nothing here.
2327
3251
  if (!result.skip && e.trigger !== 'precompute' && !e.agentId) {
3252
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: router.trace is set by helpers that take `router`, which Biome cannot follow
3253
+ if (!router.trace) {
3254
+ router.traceFreshSession = null;
3255
+ router.traceClearSession = null;
3256
+ }
2328
3257
  const ref = { ...LOOP, id: 'main' };
2329
3258
  const loop = (await $.state.get(ref)).value;
2330
- if (loop) await $.state.set(ref, resetHistory(loop));
3259
+ if (loop) {
3260
+ const reset = resetHistory(loop);
3261
+ await $.state.set(ref, reset);
3262
+ if (router.config.routingEngine === 'shadow' && router.trace) {
3263
+ const event = { type: 'reset', at: Date.now(), cause: 'compact', loop: reset, generation: reset.generation };
3264
+ traceReset(router, event);
3265
+ }
3266
+ }
2331
3267
  clearGoal(router);
2332
3268
  for (const controller of router.controllers) controller.abort();
3269
+ if (router.config.routingEngine === 'auto') {
3270
+ for (const review of router.reviews.values()) review.controller.abort();
3271
+ router.reviews.clear();
3272
+ router.decisions.clear();
3273
+ }
2333
3274
  }
2334
3275
  return result;
2335
3276
  });
2336
3277
 
2337
3278
  on('session.end', async ($, e, next) => {
3279
+ if (router.config.routingEngine === 'shadow') {
3280
+ if (router.trace?.turns.size) router.trace.reasons.add('aborted');
3281
+ await flushTrace($, router, null, true);
3282
+ }
3283
+ // biome-ignore lint/nursery/useAtomicUpdates: the session is over, so whatever trace the final flush held or created is dropped
3284
+ router.trace = null;
3285
+ router.traceOperations.clear();
3286
+ router.traceFreshSession = null;
3287
+ router.traceClearSession = e.reason === 'clear' && typeof e.sessionId === 'string' ? e.sessionId : null;
2338
3288
  await endSession($, router);
2339
3289
  return next(e);
2340
3290
  });
@@ -2352,6 +3302,18 @@ export function register(on, options) {
2352
3302
  return label ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }) : next(e);
2353
3303
  });
2354
3304
 
3305
+ // A route line: drawn from the record the turn's end kept under the row's id. Rows other plugins placed pass.
3306
+ on('ui.render', { component: 'Placed' }, async ($, e, next) => {
3307
+ if (e.props.plugin !== $.plugin.name) return next(e);
3308
+ const { value: line } = await $.state.get({ ...LINES, id: e.props.id });
3309
+ if (!line) return next(e);
3310
+ return renderRouteLine($.ui.resolve(e), router.config, line, {
3311
+ columns: e.viewport?.columns,
3312
+ surface: e.surface,
3313
+ onFallback: logFallback($, 'route line'),
3314
+ });
3315
+ });
3316
+
2355
3317
  on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
2356
3318
  if (e.component === 'Pane' && e.requestId !== PANE) return next(e);
2357
3319
  const storedView = await readView($, router);
@@ -2372,32 +3334,49 @@ export function register(on, options) {
2372
3334
  usage,
2373
3335
  {
2374
3336
  columns: e.props.bodyColumns,
3337
+ surface: e.surface,
3338
+ onFallback: logFallback($, 'band'),
2375
3339
  agentId: e.props.view?.agentId,
2376
3340
  agent: router.agents.get(e.props.view?.agentId) ?? null,
3341
+ agents: e.props.view?.agentId ? [] : await runningAgents($, router),
3342
+ back: true,
2377
3343
  },
2378
3344
  {
2379
3345
  open: () => openPane($, router),
3346
+ viewAgent: (agentId) => showView($, { agentId }),
3347
+ back: () => showView($, {}),
2380
3348
  mode: (mode) => changeMode($, router, mode),
2381
3349
  pin: async (tier) => $.ui.toast(await setPin($, router, tier)),
2382
3350
  unpin: () => updateView($, router, { pendingPin: null }),
2383
- key: () => openKeySettings($),
2384
- toggleDetail: async () => {
2385
- const bandDetail = !(router.view ?? view).bandDetail;
2386
- await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
2387
- await updateView($, router, { bandDetail });
3351
+ // On a graphical surface the band's Set up opens the pane on how to add the credentials.
3352
+ key: async (press) => {
3353
+ if (!isGraphical(press?.surface ?? e.surface)) return openKeySettings($);
3354
+ await openPane($, router);
3355
+ await updateView($, router, { keyHelp: keyHelpFor(router, router.config.classifier) });
2388
3356
  },
3357
+ toggleDetail: () => toggleBandDetail($, router, view),
2389
3358
  },
2390
3359
  ),
2391
3360
  ],
2392
3361
  });
2393
3362
  }
3363
+ view.decisionRows = await paneDecisionRows($, router);
3364
+ // A Set up's key help hides by itself once the credentials it asks for are there; an Edit's waits for Done.
3365
+ const open = view.keyHelp;
3366
+ const keyHelp =
3367
+ open?.id && router.config.classifiers[open.id] && (open.edit || missingCredentials(router.config, view, open.id))
3368
+ ? open
3369
+ : null;
2394
3370
  const settings = await $.settings.read().catch(() => ({}));
2395
3371
  const modelOptions = Object.keys(router.config.models).filter((alias) =>
2396
3372
  isModelAllowed(router.config.models[alias].id, settings.availableModels, view.nativeModel),
2397
3373
  );
2398
- return renderPanel(elements, router.config, view, usage, paneActions($, router, view), {
3374
+ return renderPanel(elements, router.config, { ...view, keyHelp }, usage, paneActions($, router, view), {
2399
3375
  modelOptions,
2400
3376
  columns: e.props.bodyColumns,
3377
+ surface: e.surface,
3378
+ onFallback: logFallback($, 'pane'),
3379
+ pluginId: pluginIdOf({ name: $.plugin.name, root: $.plugin.root }, settings?.enabledPlugins ?? null),
2401
3380
  });
2402
3381
  });
2403
3382
  }