@alexeiled/claude-router 0.8.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.claude-plugin/plugin.json +11 -7
  2. package/CHANGELOG.md +43 -0
  3. package/README.md +55 -98
  4. package/docs/architecture.md +55 -419
  5. package/docs/configuration.md +88 -182
  6. package/docs/evaluation.md +62 -81
  7. package/docs/native-router.md +80 -0
  8. package/docs/router-band.svg +119 -0
  9. package/docs/router-pane-now.svg +85 -0
  10. package/docs/router-pane-tiers.svg +62 -0
  11. package/docs/user-guide.md +127 -172
  12. package/hooks/hooks.json +1 -26
  13. package/hooks/native-router.mjs +701 -0
  14. package/lib/config.mjs +97 -63
  15. package/lib/{facts.mjs → facts-pure.mjs} +2 -23
  16. package/lib/{jev.mjs → jev-contract.mjs} +17 -38
  17. package/lib/native-band.mjs +206 -0
  18. package/lib/native-cost.mjs +88 -0
  19. package/lib/native-display.mjs +122 -0
  20. package/lib/native-jev.mjs +125 -0
  21. package/lib/native-panel.mjs +492 -0
  22. package/lib/native-router.mjs +221 -0
  23. package/lib/policy.mjs +17 -21
  24. package/package.json +10 -8
  25. package/scripts/migrate-config.mjs +57 -0
  26. package/types/index.d.ts +112 -0
  27. package/lib/cost.mjs +0 -93
  28. package/lib/gateway.mjs +0 -221
  29. package/lib/idle.mjs +0 -41
  30. package/lib/rewrite.mjs +0 -130
  31. package/lib/router.mjs +0 -276
  32. package/lib/runtime.mjs +0 -78
  33. package/lib/sse.mjs +0 -57
  34. package/lib/status.mjs +0 -152
  35. package/lib/store.mjs +0 -76
  36. package/scripts/ensure-gateway.mjs +0 -143
  37. package/scripts/gateway.mjs +0 -81
  38. package/scripts/git-hooks/pre-commit +0 -41
  39. package/scripts/git-hooks/pre-push +0 -34
  40. package/scripts/status.mjs +0 -20
  41. package/scripts/statusline.mjs +0 -45
  42. package/scripts/transcript-models.sh +0 -4
  43. package/skills/high/SKILL.md +0 -9
  44. package/skills/low/SKILL.md +0 -7
  45. package/skills/medium/SKILL.md +0 -8
  46. package/skills/micro/SKILL.md +0 -7
  47. package/skills/setup/SKILL.md +0 -31
  48. package/skills/status/SKILL.md +0 -12
@@ -0,0 +1,701 @@
1
+ import { DEFAULTS, effectiveRoutes, loadConfig, TIERS, tuningOf, withRoutes, withTuning } from '../lib/config.mjs';
2
+ import { clip } from '../lib/facts-pure.mjs';
3
+ import { renderBand, switchToast } from '../lib/native-band.mjs';
4
+ import { GATEWAY_CLEANUP, GATEWAY_SETTINGS } from '../lib/native-display.mjs';
5
+ import { NativeJev } from '../lib/native-jev.mjs';
6
+ import { renderPanel, routeDraftOf } from '../lib/native-panel.mjs';
7
+ import {
8
+ chooseRoute,
9
+ continueRoute,
10
+ emptyLoop,
11
+ isModelAllowed,
12
+ isSameModel,
13
+ nativeFacts,
14
+ observeResponse,
15
+ prepareLoop,
16
+ resetHistory,
17
+ } from '../lib/native-router.mjs';
18
+
19
+ const VIEW = { plugin: 'router', key: 'view' };
20
+ const LOOP = { plugin: 'router', key: 'loops' };
21
+ const PANE = 'jev-router';
22
+ const PANE_TITLE = 'Router';
23
+ const BAND_DETAIL = 'band:detail';
24
+ const MODE_PREFIX = 'mode:';
25
+ // Replies kept for the pane's trend and tier strip.
26
+ const HISTORY = 30;
27
+
28
+ function initialView(model) {
29
+ return {
30
+ phase: 'ready',
31
+ activeTurnId: null,
32
+ mode: 'auto',
33
+ nativeModel: model,
34
+ selectedModel: null,
35
+ actualModel: null,
36
+ tier: null,
37
+ effort: null,
38
+ reason: 'ready',
39
+ error: null,
40
+ pendingPin: null,
41
+ keySet: false,
42
+ contextTokens: null,
43
+ contextKnown: false,
44
+ cacheRead: null,
45
+ cacheWrite: null,
46
+ health: { failures: 0, pausedUntil: 0 },
47
+ inputTokens: null,
48
+ outputTokens: null,
49
+ adviceMs: null,
50
+ adviceChoice: null,
51
+ estimate: null,
52
+ comparison: null,
53
+ probabilities: null,
54
+ history: [],
55
+ tiers: [],
56
+ configPath: null,
57
+ tuning: null,
58
+ tuningBase: null,
59
+ routeDraft: null,
60
+ tab: 'now',
61
+ help: false,
62
+ notice: null,
63
+ };
64
+ }
65
+
66
+ async function readView($, runtime) {
67
+ return (await $.state.get(VIEW)).value ?? runtime.view ?? initialView(await $.session.model());
68
+ }
69
+
70
+ async function modeOf($, runtime, fallback = 'auto') {
71
+ const sessionId = await $.session.id();
72
+ if (runtime.modes.has(sessionId)) return runtime.modes.get(sessionId);
73
+ try {
74
+ const saved = await $.store.get(`${MODE_PREFIX}${sessionId}`);
75
+ const mode = saved === 'manual' || saved === 'auto' ? saved : fallback;
76
+ runtime.modes.set(sessionId, mode);
77
+ return mode;
78
+ } catch {
79
+ return 'manual';
80
+ }
81
+ }
82
+
83
+ async function rememberMode($, mode) {
84
+ try {
85
+ await $.store.set(`${MODE_PREFIX}${await $.session.id()}`, mode);
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ async function updateView($, runtime, patch) {
93
+ const value = runtime.view ?? (await readView($, runtime));
94
+ runtime.view = { ...value, ...patch };
95
+ await $.state.set(VIEW, runtime.view);
96
+ }
97
+
98
+ async function changeMode($, runtime, mode) {
99
+ const view = runtime.view ?? (await readView($, runtime));
100
+ for (const controller of runtime.controllers) controller.abort();
101
+ runtime.modes.set(await $.session.id(), mode);
102
+ const saved = await rememberMode($, mode);
103
+ await updateView($, runtime, {
104
+ mode,
105
+ pendingPin: null,
106
+ phase: view.phase === 'unavailable' ? 'unavailable' : mode === 'manual' ? 'manual' : 'ready',
107
+ reason: mode === 'manual' ? 'routing paused' : 'ready',
108
+ ...(!saved ? { notice: 'Mode changed for this session. Resume preference could not be saved.' } : {}),
109
+ });
110
+ }
111
+
112
+ async function setPin($, runtime, tier) {
113
+ const view = runtime.view ?? (await readView($, runtime));
114
+ if (view.phase === 'unavailable') return `Routing unavailable: ${view.error}.`;
115
+ const mode = await modeOf($, runtime, view.mode);
116
+ if (mode === 'manual') return 'Routing is paused. Select Auto before pinning a turn.';
117
+ await updateView($, runtime, { pendingPin: tier });
118
+ return `${tier} pinned for the next turn and its tool continuations.`;
119
+ }
120
+
121
+ async function apiKeyOf($, options) {
122
+ return typeof options.typesafe_api_key === 'string' && options.typesafe_api_key.trim()
123
+ ? options.typesafe_api_key.trim()
124
+ : (await $.env.get('TYPESAFE_API_KEY')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_TYPESAFE_API_KEY'));
125
+ }
126
+
127
+ // The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
128
+ function openKeySettings($) {
129
+ $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
130
+ }
131
+
132
+ // Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
133
+ // line for the pane; a failure leaves the file untouched.
134
+ async function saveConfig($, path, change) {
135
+ try {
136
+ if ((await $.fs.exists(path)) && (await $.fs.stat(path)).isLink)
137
+ return { error: 'Not saved: router.json is a symlink. Edit its maintained source instead.' };
138
+ const previous = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : {};
139
+ const file = change(previous);
140
+ const checked = loadConfig({ userFile: file });
141
+ await $.fs.write(path, `${JSON.stringify(file, null, 2)}\n`);
142
+ return { config: { ...checked, nativePath: path } };
143
+ } catch (error) {
144
+ // A JSON parse message quotes the file; the loadConfig messages name the setting only.
145
+ const reason = error instanceof SyntaxError ? 'router.json is not valid JSON' : error.message;
146
+ return { error: `Not saved: ${reason}. router.json is unchanged.` };
147
+ }
148
+ }
149
+
150
+ function detailText(view) {
151
+ return [
152
+ `Router — ${view.mode === 'auto' ? 'Auto' : 'Manual'}`,
153
+ `Native model: ${view.nativeModel}`,
154
+ `Selected: ${view.selectedModel ?? 'not selected'}`,
155
+ `Observed: ${view.actualModel ?? 'no response yet'}`,
156
+ `Reason: ${view.reason}`,
157
+ `Jev: ${view.error ?? (view.keySet ? 'ready' : 'key not set')}`,
158
+ `Context: ${view.contextKnown ? `${view.contextTokens} tokens (estimate)` : 'unknown'}`,
159
+ `Observed cache: ${view.cacheRead ?? 'unknown'} read, ${view.cacheWrite ?? 'unknown'} written tokens`,
160
+ view.pendingPin ? `Next turn pin: ${view.pendingPin}` : 'No next-turn pin.',
161
+ 'Auto enables routing. Manual preserves Claude’s model. Pins serve one turn only.',
162
+ 'Cache lifetime is an estimate. Claude’s cost ledger owns session totals.',
163
+ ...(view.error === GATEWAY_SETTINGS ? GATEWAY_CLEANUP : []),
164
+ ].join('\n');
165
+ }
166
+
167
+ async function loadNativeConfig($) {
168
+ for (const source of ['project', 'local']) {
169
+ const settings = await $.settings.read({ source });
170
+ if (settings.env && ['HOME', 'CLAUDE_CONFIG_DIR'].some((key) => Object.hasOwn(settings.env, key)))
171
+ throw new Error('project settings cannot redirect the router profile');
172
+ }
173
+ const home = await $.env.get('HOME');
174
+ const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
175
+ const path = `${profile}/router.json`;
176
+ const userFile = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
177
+ return { ...loadConfig({ userFile }), nativePath: path };
178
+ }
179
+
180
+ function supportedVersion(version) {
181
+ const parts = /^(\d+)\.(\d+)\.(\d+)(?:$|-)/.exec(version ?? '');
182
+ if (!parts) return false;
183
+ const [major, minor, patch] = parts.slice(1).map(Number);
184
+ return major > 2 || (major === 2 && (minor > 1 || (minor === 1 && patch >= 289)));
185
+ }
186
+
187
+ async function contextOf($, loop) {
188
+ const previous = loop.lastRequest ? loop.lastRequest.tokens + loop.lastRequest.outputTokens : null;
189
+ try {
190
+ const usage = await $.session.usage({ breakdown: 'summary' });
191
+ const estimate = usage.context.breakdown?.totalTokens;
192
+ const observed = usage.context.tokens;
193
+ const values = [previous, estimate, observed].filter((n) => Number.isFinite(n) && n >= 0);
194
+ return { tokens: values.length ? Math.max(...values) : null, known: Number.isFinite(estimate) };
195
+ } catch {
196
+ return { tokens: previous, known: false };
197
+ }
198
+ }
199
+
200
+ function responseMetrics(view, response, tier) {
201
+ const usage = response.usage;
202
+ const counters = usage ? [usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens] : [];
203
+ const inputTokens =
204
+ counters.length && counters.every(Number.isFinite) ? counters.reduce((sum, n) => sum + n, 0) : null;
205
+ return {
206
+ actualModel: usage?.model ?? null,
207
+ cacheRead: usage?.cache_read_input_tokens ?? null,
208
+ cacheWrite: usage?.cache_creation_input_tokens ?? null,
209
+ inputTokens,
210
+ outputTokens: usage?.output_tokens ?? null,
211
+ // Appended together so the Usage trend can color each reading by its tier.
212
+ ...(Number.isFinite(inputTokens)
213
+ ? {
214
+ history: [...(view?.history ?? []), inputTokens].slice(-HISTORY),
215
+ tiers: [...(view?.tiers ?? []), tier ?? null].slice(-HISTORY),
216
+ }
217
+ : {}),
218
+ };
219
+ }
220
+
221
+ // The engine may echo our own routed model on a continuation; any third model is its fallback.
222
+ function isNativeFallback(loop, model) {
223
+ if (loop.suspended) return true;
224
+ const known = [loop.engineModel, loop.decision?.model].filter(Boolean);
225
+ return known.length > 0 && !known.some((id) => isSameModel(id, model));
226
+ }
227
+
228
+ async function* passMain($, e, next, loop, version, nativeModel, reason, config, runtime) {
229
+ const ref = { ...LOOP, id: 'main' };
230
+ const context = await contextOf($, loop);
231
+ await updateView($, runtime, {
232
+ nativeModel,
233
+ selectedModel: e.model,
234
+ effort: e.effort ?? null,
235
+ reason,
236
+ contextTokens: context.tokens,
237
+ contextKnown: context.known,
238
+ });
239
+ const sessionId = await $.session.id();
240
+ const response = yield* next(e);
241
+ if (!next.signal.aborted && (await $.session.id()) === sessionId) {
242
+ const observed = observeResponse(config, loop, {
243
+ usage: response.usage,
244
+ requestedModel: e.model,
245
+ effort: e.effort ?? null,
246
+ stopReason: response.stopReason,
247
+ now: Date.now(),
248
+ });
249
+ const written = await $.state.set(ref, observed, { ifVersion: version });
250
+ if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, null));
251
+ }
252
+ return response;
253
+ }
254
+
255
+ export function register(on, options) {
256
+ let config = loadConfig();
257
+ const turnConfigs = new Map();
258
+ const classifier = new NativeJev();
259
+ const prompts = new Map();
260
+ const decisions = new Map();
261
+ const controllers = new Set();
262
+ const turnControllers = new Map();
263
+ const runtime = { view: null, controllers, modes: new Map() };
264
+
265
+ on('session.start', async ($, e, next) => {
266
+ await $.command.register({
267
+ name: 'router',
268
+ description: 'Open the Router pane, or switch routing: auto, off, pin <tier>.',
269
+ argumentHint: '[auto|off|pin <tier>]',
270
+ immediate: true,
271
+ });
272
+ const model = await $.session.model();
273
+ try {
274
+ config = await loadNativeConfig($);
275
+ const existing = await readView($, runtime);
276
+ runtime.view = existing;
277
+ classifier.restore(existing.health);
278
+ const base = await $.env.get('ANTHROPIC_BASE_URL');
279
+ const version = await $.session.version().catch(() => null);
280
+ const supported = supportedVersion(version?.version);
281
+ const baselineModel = config.models[config.routes[config.baselineTier].model].id;
282
+ const gateway =
283
+ ['jev-router', 'jev-router[1m]'].includes(model) ||
284
+ model === 'router' ||
285
+ Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
286
+ await updateView($, runtime, {
287
+ nativeModel: model,
288
+ mode: await modeOf($, runtime, model === baselineModel ? 'auto' : 'manual'),
289
+ phase: gateway || !supported ? 'unavailable' : 'ready',
290
+ error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
291
+ keySet: Boolean(await apiKeyOf($, options)),
292
+ configPath: config.nativePath,
293
+ tuning: null,
294
+ tuningBase: null,
295
+ bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
296
+ });
297
+ } catch (error) {
298
+ await updateView($, runtime, {
299
+ phase: 'unavailable',
300
+ error: error.message?.startsWith('router.json uses gateway settings;')
301
+ ? 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path'
302
+ : 'invalid router configuration',
303
+ });
304
+ }
305
+ return next(e);
306
+ });
307
+
308
+ on('command.run', { command: 'model' }, async ($, e, next) => {
309
+ const result = await next(e);
310
+ if (e.origin.kind !== 'plugin') {
311
+ await changeMode($, runtime, 'manual');
312
+ await updateView($, runtime, { nativeModel: await $.session.model(), reason: 'model selected manually' });
313
+ }
314
+ return result;
315
+ });
316
+
317
+ on('config.set', { key: 'model' }, async ($, e, next) => {
318
+ const result = await next(e);
319
+ if (!result.deny && e.origin.kind !== 'plugin') {
320
+ await changeMode($, runtime, 'manual');
321
+ await updateView($, runtime, { nativeModel: await $.session.model() });
322
+ }
323
+ return result;
324
+ });
325
+
326
+ on('command.run', { command: 'router' }, async ($, e) => {
327
+ const [action, tier] = e.args.trim().split(/\s+/);
328
+ if (action === 'auto' || action === 'off') {
329
+ await changeMode($, runtime, action === 'auto' ? 'auto' : 'manual');
330
+ return { text: action === 'auto' ? 'Auto routing enabled.' : 'Manual mode: Claude’s model is preserved.' };
331
+ }
332
+ if (action === 'pin')
333
+ return { text: TIERS.includes(tier) ? await setPin($, runtime, tier) : `Choose ${TIERS.join(', ')}.` };
334
+ const storedView = await readView($, runtime);
335
+ const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
336
+ if (!(await $.session.surfaces()).length) return { text: detailText(view) };
337
+ await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
338
+ return {};
339
+ });
340
+
341
+ on('turn.start', (_$, e, next) => {
342
+ turnConfigs.set(e.turnId, config);
343
+ prompts.set(e.turnId, clip(e.text, config.context.maxTextChars));
344
+ return next(e);
345
+ });
346
+
347
+ on('turn.step', async function* ($, e, next) {
348
+ if (e.agentId) return yield* next(e);
349
+ const cfg = turnConfigs.get(e.turnId) ?? config;
350
+ const sessionId = await $.session.id();
351
+ const nativeModel = await $.session.model();
352
+ const view = await readView($, runtime);
353
+ const mode = await modeOf($, runtime, view.mode);
354
+ if (e.index === 0) {
355
+ const saved = await rememberMode($, mode);
356
+ await updateView($, runtime, {
357
+ mode,
358
+ ...(!saved ? { notice: 'Resume preference could not be saved. Current mode remains active.' } : {}),
359
+ });
360
+ }
361
+ const ref = { ...LOOP, id: 'main' };
362
+ const loaded = await $.state.get(ref);
363
+ let loopVersion = loaded.version;
364
+ let loop = prepareLoop(loaded.value ?? emptyLoop(cfg, e.model), e.messageCount);
365
+ if (view.phase === 'unavailable' || mode === 'manual') {
366
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', cfg, runtime);
367
+ }
368
+ if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
369
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', cfg, runtime);
370
+ }
371
+ const context = await contextOf($, loop);
372
+ const settings = await $.settings.read();
373
+ const availableModels = settings.availableModels;
374
+ const key = `${sessionId}:${e.turnId}:${loop.generation}`;
375
+ if (loop.turnId !== e.turnId) {
376
+ let job = decisions.get(key);
377
+ if (!job) {
378
+ job = (async () => {
379
+ const controller = new AbortController();
380
+ const cancel = () => controller.abort();
381
+ next.signal.addEventListener('abort', cancel, { once: true });
382
+ controllers.add(controller);
383
+ turnControllers.set(e.turnId, controller);
384
+ const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
385
+ try {
386
+ const pin = view.pendingPin;
387
+ const apiKey = await apiKeyOf($, options);
388
+ const messages = await $.session.messages({ as: 'api' });
389
+ if (!(await live())) return null;
390
+ const facts = nativeFacts(cfg, loop, {
391
+ messages,
392
+ prompt: prompts.get(e.turnId),
393
+ effort: e.effort,
394
+ turnId: e.turnId,
395
+ contextTokens: context.tokens,
396
+ });
397
+ await updateView($, runtime, {
398
+ phase: 'choosing',
399
+ activeTurnId: e.turnId,
400
+ nativeModel,
401
+ pendingPin: null,
402
+ keySet: Boolean(apiKey),
403
+ });
404
+ const adviceStarted = Date.now();
405
+ const result = pin
406
+ ? { advice: null, error: null }
407
+ : await classifier.ask({
408
+ request: (url, init) => $.http.fetch(url, init),
409
+ sleep: (ms, args) => $.clock.sleep(ms, args),
410
+ config: cfg,
411
+ apiKey,
412
+ prompt: facts.prompt,
413
+ turns: facts.turns,
414
+ signal: controller.signal,
415
+ });
416
+ if (
417
+ controller.signal.aborted ||
418
+ (await $.session.id()) !== sessionId ||
419
+ (await modeOf($, runtime)) !== 'auto'
420
+ )
421
+ return null;
422
+ const previous = loop.decision;
423
+ const selected = chooseRoute(cfg, loop, {
424
+ facts,
425
+ advice: result.advice,
426
+ pin,
427
+ nativeModel,
428
+ contextKnown: context.known,
429
+ availableModels,
430
+ now: Date.now(),
431
+ });
432
+ selected.engineModel = e.model;
433
+ const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
434
+ // Manual, /clear and turn completion abort the controller; one may land during the write.
435
+ if (!written.isSet || controller.signal.aborted) return null;
436
+ if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
437
+ $.ui.toast(switchToast(previous, selected.decision, selected.decision.estimate));
438
+ await updateView($, runtime, {
439
+ phase: 'routed',
440
+ selectedModel: selected.decision.model,
441
+ actualModel: null,
442
+ tier: selected.decision.tier,
443
+ effort: selected.decision.effort,
444
+ reason: selected.decision.reason,
445
+ error: result.error,
446
+ health: classifier.snapshot(),
447
+ contextTokens: context.tokens,
448
+ contextKnown: context.known,
449
+ adviceMs:
450
+ pin || ['missing-key', 'busy', 'paused'].includes(result.error) ? null : Date.now() - adviceStarted,
451
+ adviceChoice: result.advice?.choice ?? null,
452
+ probabilities: result.advice?.probabilities ?? null,
453
+ estimate: selected.decision.estimate ?? null,
454
+ comparison: selected.decision.comparison,
455
+ });
456
+ return { loop: selected, version: written.version };
457
+ } finally {
458
+ next.signal.removeEventListener('abort', cancel);
459
+ controllers.delete(controller);
460
+ if (turnControllers.get(e.turnId) === controller) turnControllers.delete(e.turnId);
461
+ }
462
+ })();
463
+ decisions.set(key, job);
464
+ }
465
+ const selected = await job;
466
+ if (!selected) {
467
+ if (!next.signal.aborted && (await $.session.id()) === sessionId && runtime.view?.activeTurnId === e.turnId) {
468
+ const reserved = await $.state.set(ref, loop, { ifVersion: loopVersion });
469
+ if (reserved.isSet)
470
+ return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', cfg, runtime);
471
+ }
472
+ return yield* next(e);
473
+ }
474
+ loop = selected.loop;
475
+ loopVersion = selected.version;
476
+ } else {
477
+ loop = continueRoute(cfg, loop, {
478
+ nativeModel,
479
+ contextTokens: context.tokens,
480
+ contextKnown: context.known,
481
+ availableModels,
482
+ effort: e.effort,
483
+ });
484
+ await updateView($, runtime, {
485
+ selectedModel: loop.decision.model,
486
+ effort: loop.decision.effort,
487
+ tier: loop.decision.tier,
488
+ reason: loop.decision.reason,
489
+ contextTokens: context.tokens,
490
+ contextKnown: context.known,
491
+ });
492
+ }
493
+ const request = { ...e, model: loop.decision.model };
494
+ if (loop.decision.effort === null) delete request.effort;
495
+ else request.effort = loop.decision.effort;
496
+ const response = yield* next(request);
497
+ if (!next.signal.aborted && (await $.session.id()) === sessionId) {
498
+ const observed = observeResponse(cfg, loop, {
499
+ usage: response.usage,
500
+ requestedModel: request.model,
501
+ effort: request.effort ?? null,
502
+ stopReason: response.stopReason,
503
+ now: Date.now(),
504
+ });
505
+ if (response.stopReason === null) observed.suspended = true;
506
+ const written = await $.state.set(ref, observed, { ifVersion: loopVersion });
507
+ // A substituted reply is not the tier's: the strip and trend must not count it as one.
508
+ const tier = isSameModel(request.model, response.usage?.model) ? loop.decision.tier : null;
509
+ if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, tier));
510
+ }
511
+ return response;
512
+ });
513
+
514
+ on('turn.complete', async ($, e, next) => {
515
+ turnConfigs.delete(e.turnId);
516
+ turnControllers.get(e.turnId)?.abort();
517
+ if (runtime.view?.activeTurnId === e.turnId && runtime.view.phase === 'choosing') {
518
+ runtime.view = { ...runtime.view, activeTurnId: null };
519
+ const mode = await modeOf($, runtime);
520
+ if (runtime.view.activeTurnId === null)
521
+ await updateView($, runtime, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
522
+ }
523
+ prompts.delete(e.turnId);
524
+ for (const key of decisions.keys()) if (key.includes(`:${e.turnId}:`)) decisions.delete(key);
525
+ return next(e);
526
+ });
527
+
528
+ on('session.compact', async ($, e, next) => {
529
+ const result = await next(e);
530
+ // Only the main conversation is routed, so an agent compaction changes nothing here.
531
+ if (!result.skip && e.trigger !== 'precompute' && !e.agentId) {
532
+ const ref = { ...LOOP, id: 'main' };
533
+ const loop = (await $.state.get(ref)).value;
534
+ if (loop) await $.state.set(ref, resetHistory(loop));
535
+ for (const controller of controllers) controller.abort();
536
+ }
537
+ return result;
538
+ });
539
+
540
+ on('session.end', (_$, e, next) => {
541
+ for (const controller of controllers) controller.abort();
542
+ decisions.clear();
543
+ prompts.clear();
544
+ turnConfigs.clear();
545
+ runtime.view = {
546
+ ...initialView(runtime.view?.nativeModel ?? ''),
547
+ mode: 'auto',
548
+ keySet: runtime.view?.keySet ?? false,
549
+ health: classifier.snapshot(),
550
+ configPath: config.nativePath,
551
+ phase: runtime.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
552
+ error: runtime.view?.phase === 'unavailable' ? runtime.view.error : null,
553
+ };
554
+ return next(e);
555
+ });
556
+
557
+ // While the classifier runs, the turn's spinner says so; the engine's own word returns once the route is set.
558
+ on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
559
+ if (e.props.message !== null) return next(e);
560
+ const view = await readView($, runtime);
561
+ return view.phase === 'choosing' ? next({ ...e, props: { ...e.props, message: 'Choosing model' } }) : next(e);
562
+ });
563
+
564
+ // Paused or broken routing stays visible in the prompt footer even when the band is collapsed.
565
+ on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
566
+ const view = await readView($, runtime);
567
+ const label =
568
+ view.phase === 'unavailable'
569
+ ? 'router unavailable'
570
+ : (await modeOf($, runtime, view.mode)) === 'manual'
571
+ ? 'router off'
572
+ : null;
573
+ return label ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }) : next(e);
574
+ });
575
+
576
+ on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
577
+ if (e.component === 'Pane' && e.requestId !== PANE) return next(e);
578
+ const storedView = await readView($, runtime);
579
+ const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
580
+ const elements = $.ui.resolve(e);
581
+ const { Box } = elements;
582
+ const usage = await $.session.usage().catch(() => null);
583
+ const openPane = () => $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
584
+ if (e.component === 'AbovePrompt') {
585
+ if (e.props.hasSurvey) return next(e);
586
+ return Box({
587
+ flexDirection: 'column',
588
+ children: [
589
+ await next(e),
590
+ renderBand(
591
+ elements,
592
+ config,
593
+ view,
594
+ usage,
595
+ { columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
596
+ {
597
+ open: openPane,
598
+ mode: (mode) => changeMode($, runtime, mode),
599
+ pin: async (tier) => $.ui.toast(await setPin($, runtime, tier)),
600
+ unpin: () => updateView($, runtime, { pendingPin: null }),
601
+ key: () => openKeySettings($),
602
+ toggleDetail: async () => {
603
+ const bandDetail = !view.bandDetail;
604
+ await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
605
+ await updateView($, runtime, { bandDetail });
606
+ },
607
+ },
608
+ ),
609
+ ],
610
+ });
611
+ }
612
+ const settings = await $.settings.read().catch(() => ({}));
613
+ const modelOptions = Object.keys(config.models).filter((alias) =>
614
+ isModelAllowed(config.models[alias].id, settings.availableModels, view.nativeModel),
615
+ );
616
+ const editRoute = (tier, change) => {
617
+ const draft = routeDraftOf(config, runtime.view ?? view);
618
+ const current = effectiveRoutes(draft, config).routes[tier];
619
+ return updateView($, runtime, {
620
+ routeDraft: { ...draft, routes: { ...draft.routes, [tier]: change(current) } },
621
+ notice: null,
622
+ });
623
+ };
624
+ const save = async (change, saved) => {
625
+ const result = await saveConfig($, config.nativePath, change);
626
+ if (result.error) return updateView($, runtime, { notice: result.error });
627
+ config = result.config;
628
+ return updateView($, runtime, saved(config));
629
+ };
630
+ return renderPanel(
631
+ elements,
632
+ config,
633
+ view,
634
+ usage,
635
+ {
636
+ mode: (mode) => changeMode($, runtime, mode),
637
+ tab: (tab) => updateView($, runtime, { tab, notice: null }),
638
+ help: () => updateView($, runtime, { help: !view.help }),
639
+ pin: async (tier) => {
640
+ await updateView($, runtime, { notice: await setPin($, runtime, tier) });
641
+ },
642
+ unpin: () => updateView($, runtime, { pendingPin: null, notice: null }),
643
+ key: async () => {
644
+ openKeySettings($);
645
+ await $.ui.close({ id: PANE });
646
+ },
647
+ copyPath: async (press) => {
648
+ await $.ui.copy({ text: config.nativePath, surface: press?.surface });
649
+ await updateView($, runtime, { notice: 'Path copied.' });
650
+ },
651
+ close: () => $.ui.close({ id: PANE }),
652
+ routeModel: (tier, alias) =>
653
+ editRoute(tier, (route) => ({
654
+ model: alias,
655
+ effort: config.models[alias]?.efforts.includes(route.effort) ? route.effort : null,
656
+ })),
657
+ routeEffort: (tier, effort) => editRoute(tier, (route) => ({ model: route.model, effort })),
658
+ baseline: async (tier) => {
659
+ const draft = routeDraftOf(config, runtime.view ?? view);
660
+ await updateView($, runtime, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
661
+ },
662
+ saveRoutes: async () => {
663
+ const draft = (runtime.view ?? view).routeDraft;
664
+ if (!draft) return updateView($, runtime, { notice: 'No route changes to save.' });
665
+ return save(
666
+ (file) => withRoutes(file, draft),
667
+ () => ({ routeDraft: null, notice: 'Saved routes. They apply from the next turn.' }),
668
+ );
669
+ },
670
+ discardRoutes: () => updateView($, runtime, { routeDraft: null, notice: null }),
671
+ resetRoutes: () =>
672
+ updateView($, runtime, {
673
+ routeDraft: {
674
+ ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
675
+ base: routeDraftOf(config, {}).base,
676
+ },
677
+ notice: 'Defaults loaded. Save routes to remove your overrides from router.json.',
678
+ }),
679
+ tune: (key, value) =>
680
+ updateView($, runtime, {
681
+ tuning: { ...(runtime.view ?? view).tuning, [key]: value },
682
+ tuningBase: (runtime.view ?? view).tuningBase ?? tuningOf(config),
683
+ notice: null,
684
+ }),
685
+ saveTuning: async () => {
686
+ const current = runtime.view ?? view;
687
+ const base = current.tuningBase ?? tuningOf(config);
688
+ const draft = { ...base, ...current.tuning };
689
+ if (Object.keys(base).every((key) => draft[key] === base[key]))
690
+ return updateView($, runtime, { notice: 'No tuning changes to save.' });
691
+ return save(
692
+ (file) => withTuning(file, draft, base),
693
+ () => ({ tuning: null, tuningBase: null, notice: 'Saved. New tuning applies to future turns.' }),
694
+ );
695
+ },
696
+ resetTuning: () => updateView($, runtime, { tuning: null, tuningBase: null, notice: null }),
697
+ },
698
+ { modelOptions },
699
+ );
700
+ });
701
+ }