@alexeiled/claude-router 1.3.1 → 1.4.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.
@@ -1,9 +1,13 @@
1
+ import { renderBand, switchToast } from '../lib/band.mjs';
2
+ import { ClassifierClient } from '../lib/classifier-client.mjs';
3
+ import { resolveCredentials } from '../lib/classifier-contract.mjs';
1
4
  import {
2
5
  activeClassifier,
3
6
  DEFAULTS,
4
7
  effectiveRoutes,
5
8
  loadConfig,
6
9
  MIGRATION_HINT,
10
+ supportedVersion,
7
11
  TIERS,
8
12
  tuningOf,
9
13
  withClassifier,
@@ -11,23 +15,33 @@ import {
11
15
  withRoutes,
12
16
  withTuning,
13
17
  } from '../lib/config.mjs';
14
- import { clip } from '../lib/facts-pure.mjs';
15
- import { resolveCredentials } from '../lib/jev-contract.mjs';
16
- import { renderBand, switchToast } from '../lib/native-band.mjs';
17
- import { classifierStatus, GATEWAY_CLEANUP, GATEWAY_SETTINGS, missingCredentials } from '../lib/native-display.mjs';
18
- import { NativeJev } from '../lib/native-jev.mjs';
19
- import { renderPanel, routeDraftOf, routingChanges } from '../lib/native-panel.mjs';
18
+ import { changedLeaves, notSaved, restored, rewrittenConfig } from '../lib/config-file.mjs';
19
+ import {
20
+ classifierStatus,
21
+ classifierTimed,
22
+ GATEWAY_CLEANUP,
23
+ GATEWAY_SETTINGS,
24
+ missingCredentials,
25
+ } from '../lib/display.mjs';
26
+ import { clip } from '../lib/facts.mjs';
27
+ import { renderPanel, routeDraftOf, routingChanges } from '../lib/panel.mjs';
20
28
  import {
21
29
  chooseRoute,
22
30
  continueRoute,
23
31
  emptyLoop,
24
32
  isModelAllowed,
33
+ isNativeFallback,
25
34
  isSameModel,
26
35
  nativeFacts,
27
36
  observeResponse,
28
37
  prepareLoop,
29
38
  resetHistory,
30
- } from '../lib/native-router.mjs';
39
+ tierForModel,
40
+ } from '../lib/route.mjs';
41
+ import { CLEARED_READINGS, healthOf, initialView, responseMetrics } from '../lib/view.mjs';
42
+
43
+ // The engine follows $ only into functions declared in this file, never across an import: every helper that takes $
44
+ // lives here, and the pure parts live in lib/.
31
45
 
32
46
  const VIEW = { plugin: 'router', key: 'view' };
33
47
  const LOOP = { plugin: 'router', key: 'loops' };
@@ -35,65 +49,59 @@ const PANE = 'jev-router';
35
49
  const PANE_TITLE = 'Router';
36
50
  const BAND_DETAIL = 'band:detail';
37
51
  const MODE_PREFIX = 'mode:';
38
- // Replies kept for the pane's trend and tier strip.
39
- const HISTORY = 30;
40
52
 
41
- function initialView(model) {
53
+ // Everything the hooks change between events, in one object `register()` creates and passes to its helpers. Module
54
+ // variables, not $.state: a reload starts them over, and the view is written through to $.state as it changes.
55
+ function createRouter(options) {
42
56
  return {
43
- phase: 'ready',
44
- activeTurnId: null,
45
- mode: 'auto',
46
- nativeModel: model,
47
- selectedModel: null,
48
- actualModel: null,
49
- tier: null,
50
- effort: null,
51
- reason: 'ready',
52
- error: null,
53
- pendingPin: null,
54
- credentials: null,
55
- contextTokens: null,
56
- contextKnown: false,
57
- cacheRead: null,
58
- cacheWrite: null,
59
- health: { failures: 0, pausedUntil: 0 },
60
- inputTokens: null,
61
- outputTokens: null,
62
- adviceMs: null,
63
- adviceChoice: null,
64
- estimate: null,
65
- comparison: null,
66
- probabilities: null,
67
- history: [],
68
- tiers: [],
69
- configPath: null,
70
- tuning: null,
71
- tuningBase: null,
72
- routeDraft: null,
73
- lastWrite: null,
74
- tab: 'now',
75
- help: false,
76
- notice: null,
57
+ options,
58
+ config: loadConfig(),
59
+ // Each turn's config, fixed at turn.start, so a pane save mid-turn does not change the turn.
60
+ turnConfigs: new Map(),
61
+ // One client per classifier, each with its own breaker and in-flight slot: a turn that started under one
62
+ // classifier finishes with it, and its answer, failures or pause never land on another.
63
+ clients: new Map(),
64
+ prompts: new Map(),
65
+ decisions: new Map(),
66
+ controllers: new Set(),
67
+ turnControllers: new Map(),
68
+ view: null,
69
+ modes: new Map(),
77
70
  };
78
71
  }
79
72
 
80
- async function readView($, runtime) {
81
- return (await $.state.get(VIEW)).value ?? runtime.view ?? initialView(await $.session.model());
73
+ function clientOf(router, id) {
74
+ if (!router.clients.has(id)) router.clients.set(id, new ClassifierClient());
75
+ return router.clients.get(id);
76
+ }
77
+
78
+ // `router.view` is a write-through cache of $.state, because state reads are frozen within one dispatch.
79
+ async function readView($, router) {
80
+ return (await $.state.get(VIEW)).value ?? router.view ?? initialView(await $.session.model());
82
81
  }
83
82
 
84
- async function modeOf($, runtime, fallback = 'auto') {
83
+ // Only a saved mode is cached: the engine can draw the band before session.start, and a cached fallback from that
84
+ // render would override the start rule.
85
+ async function modeOf($, router, fallback = 'auto') {
85
86
  const sessionId = await $.session.id();
86
- if (runtime.modes.has(sessionId)) return runtime.modes.get(sessionId);
87
+ if (router.modes.has(sessionId)) return router.modes.get(sessionId);
87
88
  try {
88
89
  const saved = await $.store.get(`${MODE_PREFIX}${sessionId}`);
89
- const mode = saved === 'manual' || saved === 'auto' ? saved : fallback;
90
- runtime.modes.set(sessionId, mode);
91
- return mode;
90
+ if (saved !== 'manual' && saved !== 'auto') return fallback;
91
+ router.modes.set(sessionId, saved);
92
+ return saved;
92
93
  } catch {
93
94
  return 'manual';
94
95
  }
95
96
  }
96
97
 
98
+ // A saved preference wins; a fresh session starts Auto on a model some tier routes to and Manual on any other.
99
+ async function startMode($, router, model) {
100
+ const mode = await modeOf($, router, tierForModel(router.config, model) === null ? 'manual' : 'auto');
101
+ router.modes.set(await $.session.id(), mode);
102
+ return mode;
103
+ }
104
+
97
105
  async function rememberMode($, mode) {
98
106
  try {
99
107
  await $.store.set(`${MODE_PREFIX}${await $.session.id()}`, mode);
@@ -103,25 +111,25 @@ async function rememberMode($, mode) {
103
111
  }
104
112
  }
105
113
 
106
- async function updateView($, runtime, patch) {
107
- const value = runtime.view ?? (await readView($, runtime));
108
- runtime.view = { ...value, ...patch };
109
- await $.state.set(VIEW, runtime.view);
114
+ async function updateView($, router, patch) {
115
+ const value = router.view ?? (await readView($, router));
116
+ router.view = { ...value, ...patch };
117
+ await $.state.set(VIEW, router.view);
110
118
  }
111
119
 
112
120
  // A notice answers the last press in the pane, so the pane opens without one; the last write keeps its Undo in the
113
121
  // status bar.
114
- async function openPane($, runtime) {
115
- await updateView($, runtime, { notice: null });
122
+ async function openPane($, router) {
123
+ await updateView($, router, { notice: null });
116
124
  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
117
125
  }
118
126
 
119
- async function changeMode($, runtime, mode) {
120
- const view = runtime.view ?? (await readView($, runtime));
121
- for (const controller of runtime.controllers) controller.abort();
122
- runtime.modes.set(await $.session.id(), mode);
127
+ async function changeMode($, router, mode) {
128
+ const view = router.view ?? (await readView($, router));
129
+ for (const controller of router.controllers) controller.abort();
130
+ router.modes.set(await $.session.id(), mode);
123
131
  const saved = await rememberMode($, mode);
124
- await updateView($, runtime, {
132
+ await updateView($, router, {
125
133
  mode,
126
134
  pendingPin: null,
127
135
  phase: view.phase === 'unavailable' ? 'unavailable' : mode === 'manual' ? 'manual' : 'ready',
@@ -130,12 +138,12 @@ async function changeMode($, runtime, mode) {
130
138
  });
131
139
  }
132
140
 
133
- async function setPin($, runtime, tier) {
134
- const view = runtime.view ?? (await readView($, runtime));
141
+ async function setPin($, router, tier) {
142
+ const view = router.view ?? (await readView($, router));
135
143
  if (view.phase === 'unavailable') return `Routing unavailable: ${view.error}.`;
136
- const mode = await modeOf($, runtime, view.mode);
144
+ const mode = await modeOf($, router, view.mode);
137
145
  if (mode === 'manual') return 'Routing is paused. Select Auto before pinning a turn.';
138
- await updateView($, runtime, { pendingPin: tier });
146
+ await updateView($, router, { pendingPin: tier });
139
147
  return `${tier} pinned for the next turn and its tool continuations.`;
140
148
  }
141
149
 
@@ -178,59 +186,22 @@ async function credentialsOf($, options, config) {
178
186
  );
179
187
  }
180
188
 
181
- // Failures and a pause belong to the classifier that earned them.
182
- const healthOf = (client, id) => ({ ...client.snapshot(), classifier: id });
183
- // The last classification's readings, cleared when another classifier takes over so no label claims them.
184
- const CLEARED_READINGS = { adviceMs: null, adviceChoice: null, probabilities: null, estimate: null };
185
-
186
189
  // The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
187
190
  function openKeySettings($) {
188
191
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
189
192
  }
190
193
 
191
- const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
192
-
193
- // The leaves where router.json `after` differs from `before`, each with its value in `before`, or no `value` where it
194
- // had none. An object present on one side only is walked as empty on the other, so a sibling stays out of it.
195
- function changedLeaves(before, after, path = []) {
196
- const out = [];
197
- for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
198
- const [a, b] = [before[key], after[key]];
199
- if ((isRecord(a) || a === undefined) && (isRecord(b) || b === undefined) && (isRecord(a) || isRecord(b)))
200
- out.push(...changedLeaves(a ?? {}, b ?? {}, [...path, key]));
201
- else if (JSON.stringify(a) !== JSON.stringify(b))
202
- out.push(Object.hasOwn(before, key) ? { path: [...path, key], value: a } : { path: [...path, key] });
203
- }
204
- return out;
205
- }
206
-
207
- // The router.json `file` with each leaf of one pane write put back as it was before it: a value written again
208
- // verbatim, a leaf that was absent deleted along with any object that leaves empty. Leaves the write did not touch,
209
- // such as an edit made on disk since, stay as they are.
210
- function restored(file, leaves) {
211
- const next = structuredClone(file);
212
- for (const { path, ...leaf } of leaves) {
213
- const parents = path.slice(0, -1);
214
- const key = path.at(-1);
215
- if (Object.hasOwn(leaf, 'value')) {
216
- let node = next;
217
- for (const name of parents) {
218
- if (!isRecord(node[name])) node[name] = {};
219
- node = node[name];
220
- }
221
- node[key] = leaf.value;
222
- continue;
223
- }
224
- const chain = [next];
225
- for (const name of parents) {
226
- if (!isRecord(chain.at(-1)[name])) break;
227
- chain.push(chain.at(-1)[name]);
228
- }
229
- if (chain.length !== path.length) continue;
230
- delete chain.at(-1)[key];
231
- for (let i = chain.length - 1; i > 0 && !Object.keys(chain[i]).length; i -= 1) delete chain[i - 1][path[i - 1]];
194
+ async function loadNativeConfig($) {
195
+ for (const source of ['project', 'local']) {
196
+ const settings = await $.settings.read({ source });
197
+ if (settings.env && ['HOME', 'CLAUDE_CONFIG_DIR'].some((key) => Object.hasOwn(settings.env, key)))
198
+ throw new Error('project settings cannot redirect the router profile');
232
199
  }
233
- return next;
200
+ const home = await $.env.get('HOME');
201
+ const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
202
+ const path = `${profile}/router.json`;
203
+ const userFile = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
204
+ return { ...loadConfig({ userFile }), nativePath: path };
234
205
  }
235
206
 
236
207
  // Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
@@ -239,15 +210,11 @@ async function saveConfig($, path, change) {
239
210
  try {
240
211
  if ((await $.fs.exists(path)) && (await $.fs.stat(path)).isLink)
241
212
  return { error: 'Not saved: router.json is a symlink. Edit its maintained source instead.' };
242
- const previous = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : {};
243
- const file = change(previous);
244
- const checked = loadConfig({ userFile: file });
245
- await $.fs.write(path, `${JSON.stringify(file, null, 2)}\n`);
246
- return { config: { ...checked, nativePath: path } };
213
+ const { config, text } = rewrittenConfig((await $.fs.exists(path)) ? await $.fs.read(path) : null, change);
214
+ await $.fs.write(path, text);
215
+ return { config: { ...config, nativePath: path } };
247
216
  } catch (error) {
248
- // A JSON parse message quotes the file; the loadConfig messages name the setting only.
249
- const reason = error instanceof SyntaxError ? 'router.json is not valid JSON' : error.message;
250
- return { error: `Not saved: ${reason}. router.json is unchanged.` };
217
+ return { error: notSaved(error) };
251
218
  }
252
219
  }
253
220
 
@@ -269,26 +236,6 @@ function detailText(config, view) {
269
236
  ].join('\n');
270
237
  }
271
238
 
272
- async function loadNativeConfig($) {
273
- for (const source of ['project', 'local']) {
274
- const settings = await $.settings.read({ source });
275
- if (settings.env && ['HOME', 'CLAUDE_CONFIG_DIR'].some((key) => Object.hasOwn(settings.env, key)))
276
- throw new Error('project settings cannot redirect the router profile');
277
- }
278
- const home = await $.env.get('HOME');
279
- const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
280
- const path = `${profile}/router.json`;
281
- const userFile = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
282
- return { ...loadConfig({ userFile }), nativePath: path };
283
- }
284
-
285
- function supportedVersion(version) {
286
- const parts = /^(\d+)\.(\d+)\.(\d+)(?:$|-)/.exec(version ?? '');
287
- if (!parts) return false;
288
- const [major, minor, patch] = parts.slice(1).map(Number);
289
- return major > 2 || (major === 2 && (minor > 1 || (minor === 1 && patch >= 289)));
290
- }
291
-
292
239
  async function contextOf($, loop) {
293
240
  const previous = loop.lastRequest ? loop.lastRequest.tokens + loop.lastRequest.outputTokens : null;
294
241
  try {
@@ -302,38 +249,10 @@ async function contextOf($, loop) {
302
249
  }
303
250
  }
304
251
 
305
- function responseMetrics(view, response, tier) {
306
- const usage = response.usage;
307
- const counters = usage ? [usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens] : [];
308
- const inputTokens =
309
- counters.length && counters.every(Number.isFinite) ? counters.reduce((sum, n) => sum + n, 0) : null;
310
- return {
311
- actualModel: usage?.model ?? null,
312
- cacheRead: usage?.cache_read_input_tokens ?? null,
313
- cacheWrite: usage?.cache_creation_input_tokens ?? null,
314
- inputTokens,
315
- outputTokens: usage?.output_tokens ?? null,
316
- // Appended together so the Usage trend can color each reading by its tier.
317
- ...(Number.isFinite(inputTokens)
318
- ? {
319
- history: [...(view?.history ?? []), inputTokens].slice(-HISTORY),
320
- tiers: [...(view?.tiers ?? []), tier ?? null].slice(-HISTORY),
321
- }
322
- : {}),
323
- };
324
- }
325
-
326
- // The engine may echo our own routed model on a continuation; any third model is its fallback.
327
- function isNativeFallback(loop, model) {
328
- if (loop.suspended) return true;
329
- const known = [loop.engineModel, loop.decision?.model].filter(Boolean);
330
- return known.length > 0 && !known.some((id) => isSameModel(id, model));
331
- }
332
-
333
- async function* passMain($, e, next, loop, version, nativeModel, reason, config, runtime) {
252
+ async function* passMain($, e, next, loop, version, nativeModel, reason, router) {
334
253
  const ref = { ...LOOP, id: 'main' };
335
254
  const context = await contextOf($, loop);
336
- await updateView($, runtime, {
255
+ await updateView($, router, {
337
256
  nativeModel,
338
257
  selectedModel: e.model,
339
258
  effort: e.effort ?? null,
@@ -344,7 +263,7 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
344
263
  const sessionId = await $.session.id();
345
264
  const response = yield* next(e);
346
265
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
347
- const observed = observeResponse(config, loop, {
266
+ const observed = observeResponse(loop, {
348
267
  usage: response.usage,
349
268
  requestedModel: e.model,
350
269
  effort: e.effort ?? null,
@@ -352,26 +271,271 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
352
271
  now: Date.now(),
353
272
  });
354
273
  const written = await $.state.set(ref, observed, { ifVersion: version });
355
- if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, null));
274
+ if (written.isSet) await updateView($, router, responseMetrics(router.view, response, null));
356
275
  }
357
276
  return response;
358
277
  }
359
278
 
360
- export function register(on, options) {
361
- let config = loadConfig();
362
- const turnConfigs = new Map();
363
- // One client per classifier, each with its own breaker and in-flight slot: a turn that started under one
364
- // classifier finishes with it, and its answer, failures or pause never land on another.
365
- const clients = new Map();
366
- const clientOf = (id) => {
367
- if (!clients.has(id)) clients.set(id, new NativeJev());
368
- return clients.get(id);
279
+ // One turn's classification and route, written to the loop at `loopVersion`: the loop and its new version, or null
280
+ // when the turn was aborted, left the session or Auto, or lost the write. `signal` is the step's: its abort cancels
281
+ // the classifier call. The pin is the one in `view`, the view as the step read it.
282
+ async function decideTurn($, router, e, signal, step) {
283
+ const { sessionId, view, cfg, loop, loopVersion, context, nativeModel, availableModels } = step;
284
+ const ref = { ...LOOP, id: 'main' };
285
+ const controller = new AbortController();
286
+ const cancel = () => controller.abort();
287
+ signal.addEventListener('abort', cancel, { once: true });
288
+ router.controllers.add(controller);
289
+ router.turnControllers.set(e.turnId, controller);
290
+ const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
291
+ try {
292
+ const pin = view.pendingPin;
293
+ const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name));
294
+ const messages = await $.session.messages({ as: 'api' });
295
+ if (!(await live())) return null;
296
+ const facts = nativeFacts(cfg, loop, {
297
+ messages,
298
+ prompt: router.prompts.get(e.turnId),
299
+ effort: e.effort,
300
+ turnId: e.turnId,
301
+ contextTokens: context.tokens,
302
+ });
303
+ await updateView($, router, {
304
+ phase: 'choosing',
305
+ activeTurnId: e.turnId,
306
+ nativeModel,
307
+ pendingPin: null,
308
+ credentials: { ...router.view?.credentials, [cfg.classifier]: credentials.missing },
309
+ });
310
+ const adviceStarted = Date.now();
311
+ const result = pin
312
+ ? { advice: null, error: null }
313
+ : await clientOf(router, cfg.classifier).ask({
314
+ request: (url, init) => $.http.fetch(url, init),
315
+ sleep: (ms, args) => $.clock.sleep(ms, args),
316
+ config: cfg,
317
+ apiKey: credentials.apiKey,
318
+ endpoint: credentials.endpoint,
319
+ prompt: facts.prompt,
320
+ turns: facts.turns,
321
+ signal: controller.signal,
322
+ });
323
+ if (controller.signal.aborted || (await $.session.id()) !== sessionId || (await modeOf($, router)) !== 'auto')
324
+ return null;
325
+ const previous = loop.decision;
326
+ const selected = chooseRoute(cfg, loop, {
327
+ facts,
328
+ advice: result.advice,
329
+ pin,
330
+ nativeModel,
331
+ contextKnown: context.known,
332
+ availableModels,
333
+ now: Date.now(),
334
+ });
335
+ selected.engineModel = e.model;
336
+ const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
337
+ // Manual, /clear and turn completion abort the controller; one may land during the write.
338
+ if (!written.isSet || controller.signal.aborted) return null;
339
+ if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
340
+ $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
341
+ await updateView($, router, {
342
+ phase: 'routed',
343
+ selectedModel: selected.decision.model,
344
+ actualModel: null,
345
+ tier: selected.decision.tier,
346
+ effort: selected.decision.effort,
347
+ reason: selected.decision.reason,
348
+ contextTokens: context.tokens,
349
+ contextKnown: context.known,
350
+ comparison: selected.decision.comparison,
351
+ // A turn that started before a classifier switch routes on its own classifier's answer, but the
352
+ // pane now labels the new one: its readings stay off the view.
353
+ ...(cfg.classifier === router.config.classifier
354
+ ? {
355
+ error: result.error,
356
+ health: healthOf(clientOf(router, cfg.classifier), cfg.classifier),
357
+ adviceMs: pin || !classifierTimed(result.error) ? null : Date.now() - adviceStarted,
358
+ adviceChoice: result.advice?.choice ?? null,
359
+ probabilities: result.advice?.probabilities ?? null,
360
+ estimate: selected.decision.estimate ?? null,
361
+ }
362
+ : {}),
363
+ });
364
+ return { loop: selected, version: written.version };
365
+ } finally {
366
+ signal.removeEventListener('abort', cancel);
367
+ router.controllers.delete(controller);
368
+ if (router.turnControllers.get(e.turnId) === controller) router.turnControllers.delete(e.turnId);
369
+ }
370
+ }
371
+
372
+ // The pane's handlers. `view` is the view the pane was drawn from; a handler reads `router.view` first, which holds
373
+ // any press since.
374
+ function paneActions($, router, view) {
375
+ const editRoute = (tier, change) => {
376
+ const draft = routeDraftOf(router.config, router.view ?? view);
377
+ const current = effectiveRoutes(draft, router.config).routes[tier];
378
+ return updateView($, router, {
379
+ routeDraft: { ...draft, routes: { ...draft.routes, [tier]: change(current) } },
380
+ notice: null,
381
+ });
382
+ };
383
+ // Every pane save adopts the file as written, which may name another classifier than before: a hand edit
384
+ // meanwhile, or a row press. Then the new classifier starts clean and the old one's readings leave the view;
385
+ // an unavailable reason stays.
386
+ const adopt = async (loaded) => {
387
+ const switched = loaded.classifier !== router.config.classifier;
388
+ router.config = loaded;
389
+ if (!switched) return {};
390
+ clientOf(router, router.config.classifier).restore(null);
391
+ const current = router.view ?? view;
392
+ return {
393
+ ...CLEARED_READINGS,
394
+ error: current.phase === 'unavailable' ? current.error : null,
395
+ credentials: await credentialsOf($, router.options, router.config),
396
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
397
+ };
398
+ };
399
+ // Pending drafts re-pointed at the config a write just adopted. An edit that still differs stays; everything else
400
+ // follows the file, and the file becomes what the draft compares against, so picking a value the write replaced
401
+ // counts as a change again.
402
+ const rebased = ({ routeDraft, tuning, tuningBase }) => {
403
+ const routes = routeDraft && effectiveRoutes(routeDraft, router.config);
404
+ const edited = Object.entries(tuning ?? {}).filter(([key, value]) => value !== tuningBase?.[key]);
405
+ return {
406
+ routeDraft: routes ? { ...routes, base: routeDraftOf(router.config, {}).base } : null,
407
+ tuning: edited.length ? Object.fromEntries(edited) : null,
408
+ tuningBase: edited.length ? tuningOf(router.config) : null,
409
+ };
410
+ };
411
+ const save = async (change, saved) => {
412
+ const result = await saveConfig($, router.config.nativePath, change);
413
+ if (result.error) return updateView($, router, { notice: result.error });
414
+ const drafts = router.view ?? view;
415
+ const reset = await adopt(result.config);
416
+ return updateView($, router, { ...reset, ...rebased(drafts), ...saved(router.config) });
369
417
  };
370
- const prompts = new Map();
371
- const decisions = new Map();
372
- const controllers = new Set();
373
- const turnControllers = new Map();
374
- const runtime = { view: null, controllers, modes: new Map() };
418
+ // Defaults go into the routing draft like any edit; the notice says whether Save has anything of that section left
419
+ // to write.
420
+ const loadDefaults = (patch, what) => {
421
+ const changes = routingChanges(router.config, { ...(router.view ?? view), ...patch });
422
+ const pending = what === 'route' ? changes.tiers.length + Number(changes.baseline) : changes.policy.length;
423
+ return updateView($, router, {
424
+ ...patch,
425
+ notice: pending
426
+ ? `${what === 'route' ? 'Route' : 'Policy'} defaults loaded. Save removes your ${what} overrides from router.json.`
427
+ : `${what === 'route' ? 'Routes' : 'Policy'} already at defaults.`,
428
+ });
429
+ };
430
+ // A pane write keeps the leaves it changed as router.json had them, read from the file it rewrites rather than from
431
+ // the loaded config, so Undo restores them verbatim. A later write replaces them, and Undo clears them.
432
+ const write = (label, change, patch = {}) => {
433
+ let leaves = [];
434
+ return save(
435
+ (file) => {
436
+ const written = change(file);
437
+ leaves = changedLeaves(file, written);
438
+ return written;
439
+ },
440
+ () => ({ ...patch, lastWrite: { label, leaves }, notice: `Saved: ${label}. Applies from the next turn.` }),
441
+ );
442
+ };
443
+ return {
444
+ mode: (mode) => changeMode($, router, mode),
445
+ tab: (tab) => updateView($, router, { tab, notice: null }),
446
+ help: () => updateView($, router, { help: !(router.view ?? view).help }),
447
+ pin: async (tier) => {
448
+ await updateView($, router, { notice: await setPin($, router, tier) });
449
+ },
450
+ unpin: () => updateView($, router, { pendingPin: null, notice: null }),
451
+ key: async () => {
452
+ openKeySettings($);
453
+ await $.ui.close({ id: PANE });
454
+ },
455
+ copyPath: async (press) => {
456
+ await $.ui.copy({ text: router.config.nativePath, surface: press?.surface });
457
+ await updateView($, router, { notice: 'Path copied.' });
458
+ },
459
+ close: () => $.ui.close({ id: PANE }),
460
+ routeModel: (tier, alias) =>
461
+ editRoute(tier, (route) => ({
462
+ model: alias,
463
+ effort: router.config.models[alias]?.efforts.includes(route.effort) ? route.effort : null,
464
+ })),
465
+ routeEffort: (tier, effort) => editRoute(tier, (route) => ({ model: route.model, effort })),
466
+ baseline: async (tier) => {
467
+ const draft = routeDraftOf(router.config, router.view ?? view);
468
+ await updateView($, router, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
469
+ },
470
+ saveRouting: async () => {
471
+ const current = router.view ?? view;
472
+ const routeDraft = current.routeDraft;
473
+ const saved = tuningOf(router.config);
474
+ const base = current.tuningBase ?? saved;
475
+ const edited = Object.keys(current.tuning ?? {}).filter((key) => current.tuning[key] !== base[key]);
476
+ const changes = routingChanges(router.config, current).count;
477
+ if (!changes) return updateView($, router, { notice: 'No routing changes to save.' });
478
+ const after = Object.fromEntries(edited.map((key) => [key, current.tuning[key]]));
479
+ return write(
480
+ `${changes} routing change${changes === 1 ? '' : 's'}`,
481
+ (file) => {
482
+ const routed = routeDraft ? withRoutes(file, routeDraft) : file;
483
+ return edited.length ? withTuning(routed, { ...base, ...after }, base) : routed;
484
+ },
485
+ { routeDraft: null, tuning: null, tuningBase: null },
486
+ );
487
+ },
488
+ discardRouting: () => updateView($, router, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
489
+ resetRoutes: () =>
490
+ loadDefaults(
491
+ {
492
+ routeDraft: {
493
+ ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
494
+ base: routeDraftOf(router.config, {}).base,
495
+ },
496
+ },
497
+ 'route',
498
+ ),
499
+ tune: (key, value) =>
500
+ updateView($, router, {
501
+ tuning: { ...(router.view ?? view).tuning, [key]: value },
502
+ tuningBase: (router.view ?? view).tuningBase ?? tuningOf(router.config),
503
+ notice: null,
504
+ }),
505
+ resetPolicy: () =>
506
+ loadDefaults(
507
+ // The draft is replaced whole, so it starts from the saved values, not from an older draft's base.
508
+ { tuning: tuningOf(DEFAULTS), tuningBase: tuningOf(router.config) },
509
+ 'policy',
510
+ ),
511
+ classifier: (id) => {
512
+ const { config } = router;
513
+ if (!id || id === config.classifier || !Object.hasOwn(config.classifiers, id)) return undefined;
514
+ const from = config.classifier;
515
+ return write(`classifier ${config.classifiers[from].label} → ${config.classifiers[id].label}`, (file) =>
516
+ withClassifier(file, id),
517
+ );
518
+ },
519
+ classifierTimeout: (timeoutMs) => {
520
+ const active = activeClassifier(router.config);
521
+ if (timeoutMs === active.timeoutMs) return undefined;
522
+ return write(`${active.label} deadline ${active.timeoutMs} → ${timeoutMs} ms`, (file) =>
523
+ withClassifierTimeout(file, router.config.classifier, timeoutMs),
524
+ );
525
+ },
526
+ undo: async () => {
527
+ const last = (router.view ?? view).lastWrite;
528
+ if (!last) return undefined;
529
+ return save(
530
+ (file) => restored(file, last.leaves),
531
+ () => ({ lastWrite: null, notice: `Undid: ${last.label}.` }),
532
+ );
533
+ },
534
+ };
535
+ }
536
+
537
+ export function register(on, options) {
538
+ const router = createRouter(options);
375
539
 
376
540
  on('session.start', async ($, e, next) => {
377
541
  await $.command.register({
@@ -382,28 +546,27 @@ export function register(on, options) {
382
546
  });
383
547
  const model = await $.session.model();
384
548
  try {
385
- config = await loadNativeConfig($);
386
- const existing = await readView($, runtime);
387
- runtime.view = existing;
388
- const sameClassifier = existing.health?.classifier === config.classifier;
389
- clientOf(config.classifier).restore(sameClassifier ? existing.health : null);
549
+ router.config = await loadNativeConfig($);
550
+ const existing = await readView($, router);
551
+ router.view = existing;
552
+ const sameClassifier = existing.health?.classifier === router.config.classifier;
553
+ clientOf(router, router.config.classifier).restore(sameClassifier ? existing.health : null);
390
554
  const base = await $.env.get('ANTHROPIC_BASE_URL');
391
555
  const version = await $.session.version().catch(() => null);
392
556
  const supported = supportedVersion(version?.version);
393
- const baselineModel = config.models[config.routes[config.baselineTier].model].id;
394
557
  const gateway =
395
558
  ['jev-router', 'jev-router[1m]'].includes(model) ||
396
559
  model === 'router' ||
397
560
  Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
398
- await updateView($, runtime, {
561
+ await updateView($, router, {
399
562
  nativeModel: model,
400
- mode: await modeOf($, runtime, model === baselineModel ? 'auto' : 'manual'),
563
+ mode: await startMode($, router, model),
401
564
  phase: gateway || !supported ? 'unavailable' : 'ready',
402
565
  error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
403
566
  ...(sameClassifier ? {} : CLEARED_READINGS),
404
- credentials: await credentialsOf($, options, config),
405
- health: healthOf(clientOf(config.classifier), config.classifier),
406
- configPath: config.nativePath,
567
+ credentials: await credentialsOf($, options, router.config),
568
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
569
+ configPath: router.config.nativePath,
407
570
  tuning: null,
408
571
  tuningBase: null,
409
572
  routeDraft: null,
@@ -411,7 +574,7 @@ export function register(on, options) {
411
574
  bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
412
575
  });
413
576
  } catch (error) {
414
- await updateView($, runtime, {
577
+ await updateView($, router, {
415
578
  phase: 'unavailable',
416
579
  error: error.message?.endsWith(MIGRATION_HINT)
417
580
  ? 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path'
@@ -424,8 +587,8 @@ export function register(on, options) {
424
587
  on('command.run', { command: 'model' }, async ($, e, next) => {
425
588
  const result = await next(e);
426
589
  if (e.origin.kind !== 'plugin') {
427
- await changeMode($, runtime, 'manual');
428
- await updateView($, runtime, { nativeModel: await $.session.model(), reason: 'model selected manually' });
590
+ await changeMode($, router, 'manual');
591
+ await updateView($, router, { nativeModel: await $.session.model(), reason: 'model selected manually' });
429
592
  }
430
593
  return result;
431
594
  });
@@ -433,8 +596,8 @@ export function register(on, options) {
433
596
  on('config.set', { key: 'model' }, async ($, e, next) => {
434
597
  const result = await next(e);
435
598
  if (!result.deny && e.origin.kind !== 'plugin') {
436
- await changeMode($, runtime, 'manual');
437
- await updateView($, runtime, { nativeModel: await $.session.model() });
599
+ await changeMode($, router, 'manual');
600
+ await updateView($, router, { nativeModel: await $.session.model() });
438
601
  }
439
602
  return result;
440
603
  });
@@ -442,34 +605,34 @@ export function register(on, options) {
442
605
  on('command.run', { command: 'router' }, async ($, e) => {
443
606
  const [action, tier] = e.args.trim().split(/\s+/);
444
607
  if (action === 'auto' || action === 'off') {
445
- await changeMode($, runtime, action === 'auto' ? 'auto' : 'manual');
608
+ await changeMode($, router, action === 'auto' ? 'auto' : 'manual');
446
609
  return { text: action === 'auto' ? 'Auto routing enabled.' : 'Manual mode: Claude’s model is preserved.' };
447
610
  }
448
611
  if (action === 'pin')
449
- return { text: TIERS.includes(tier) ? await setPin($, runtime, tier) : `Choose ${TIERS.join(', ')}.` };
450
- const storedView = await readView($, runtime);
451
- const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
452
- if (!(await $.session.surfaces()).length) return { text: detailText(config, view) };
453
- await openPane($, runtime);
612
+ return { text: TIERS.includes(tier) ? await setPin($, router, tier) : `Choose ${TIERS.join(', ')}.` };
613
+ const storedView = await readView($, router);
614
+ const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
615
+ if (!(await $.session.surfaces()).length) return { text: detailText(router.config, view) };
616
+ await openPane($, router);
454
617
  return {};
455
618
  });
456
619
 
457
620
  on('turn.start', (_$, e, next) => {
458
- turnConfigs.set(e.turnId, config);
459
- prompts.set(e.turnId, clip(e.text, config.context.maxTextChars));
621
+ router.turnConfigs.set(e.turnId, router.config);
622
+ router.prompts.set(e.turnId, clip(e.text, router.config.context.maxTextChars));
460
623
  return next(e);
461
624
  });
462
625
 
463
626
  on('turn.step', async function* ($, e, next) {
464
627
  if (e.agentId) return yield* next(e);
465
- const cfg = turnConfigs.get(e.turnId) ?? config;
628
+ const cfg = router.turnConfigs.get(e.turnId) ?? router.config;
466
629
  const sessionId = await $.session.id();
467
630
  const nativeModel = await $.session.model();
468
- const view = await readView($, runtime);
469
- const mode = await modeOf($, runtime, view.mode);
631
+ const view = await readView($, router);
632
+ const mode = await modeOf($, router, view.mode);
470
633
  if (e.index === 0) {
471
634
  const saved = await rememberMode($, mode);
472
- await updateView($, runtime, {
635
+ await updateView($, router, {
473
636
  mode,
474
637
  ...(!saved ? { notice: 'Resume preference could not be saved. Current mode remains active.' } : {}),
475
638
  });
@@ -479,120 +642,35 @@ export function register(on, options) {
479
642
  let loopVersion = loaded.version;
480
643
  let loop = prepareLoop(loaded.value ?? emptyLoop(cfg, e.model), e.messageCount);
481
644
  if (view.phase === 'unavailable' || mode === 'manual') {
482
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', cfg, runtime);
645
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', router);
483
646
  }
484
647
  if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
485
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', cfg, runtime);
648
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', router);
486
649
  }
487
650
  const context = await contextOf($, loop);
488
651
  const settings = await $.settings.read();
489
652
  const availableModels = settings.availableModels;
490
653
  const key = `${sessionId}:${e.turnId}:${loop.generation}`;
491
654
  if (loop.turnId !== e.turnId) {
492
- let job = decisions.get(key);
655
+ let job = router.decisions.get(key);
493
656
  if (!job) {
494
- job = (async () => {
495
- const controller = new AbortController();
496
- const cancel = () => controller.abort();
497
- next.signal.addEventListener('abort', cancel, { once: true });
498
- controllers.add(controller);
499
- turnControllers.set(e.turnId, controller);
500
- const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
501
- try {
502
- const pin = view.pendingPin;
503
- const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, options, name));
504
- const messages = await $.session.messages({ as: 'api' });
505
- if (!(await live())) return null;
506
- const facts = nativeFacts(cfg, loop, {
507
- messages,
508
- prompt: prompts.get(e.turnId),
509
- effort: e.effort,
510
- turnId: e.turnId,
511
- contextTokens: context.tokens,
512
- });
513
- await updateView($, runtime, {
514
- phase: 'choosing',
515
- activeTurnId: e.turnId,
516
- nativeModel,
517
- pendingPin: null,
518
- credentials: { ...runtime.view?.credentials, [cfg.classifier]: credentials.missing },
519
- });
520
- const adviceStarted = Date.now();
521
- const result = pin
522
- ? { advice: null, error: null }
523
- : await clientOf(cfg.classifier).ask({
524
- request: (url, init) => $.http.fetch(url, init),
525
- sleep: (ms, args) => $.clock.sleep(ms, args),
526
- config: cfg,
527
- apiKey: credentials.apiKey,
528
- endpoint: credentials.endpoint,
529
- prompt: facts.prompt,
530
- turns: facts.turns,
531
- signal: controller.signal,
532
- });
533
- if (
534
- controller.signal.aborted ||
535
- (await $.session.id()) !== sessionId ||
536
- (await modeOf($, runtime)) !== 'auto'
537
- )
538
- return null;
539
- const previous = loop.decision;
540
- const selected = chooseRoute(cfg, loop, {
541
- facts,
542
- advice: result.advice,
543
- pin,
544
- nativeModel,
545
- contextKnown: context.known,
546
- availableModels,
547
- now: Date.now(),
548
- });
549
- selected.engineModel = e.model;
550
- const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
551
- // Manual, /clear and turn completion abort the controller; one may land during the write.
552
- if (!written.isSet || controller.signal.aborted) return null;
553
- if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
554
- $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
555
- await updateView($, runtime, {
556
- phase: 'routed',
557
- selectedModel: selected.decision.model,
558
- actualModel: null,
559
- tier: selected.decision.tier,
560
- effort: selected.decision.effort,
561
- reason: selected.decision.reason,
562
- contextTokens: context.tokens,
563
- contextKnown: context.known,
564
- comparison: selected.decision.comparison,
565
- // A turn that started before a classifier switch routes on its own classifier's answer, but the
566
- // pane now labels the new one: its readings stay off the view.
567
- ...(cfg.classifier === config.classifier
568
- ? {
569
- error: result.error,
570
- health: healthOf(clientOf(cfg.classifier), cfg.classifier),
571
- adviceMs:
572
- pin || ['missing-key', 'missing-account', 'busy', 'paused'].includes(result.error)
573
- ? null
574
- : Date.now() - adviceStarted,
575
- adviceChoice: result.advice?.choice ?? null,
576
- probabilities: result.advice?.probabilities ?? null,
577
- estimate: selected.decision.estimate ?? null,
578
- }
579
- : {}),
580
- });
581
- return { loop: selected, version: written.version };
582
- } finally {
583
- next.signal.removeEventListener('abort', cancel);
584
- controllers.delete(controller);
585
- if (turnControllers.get(e.turnId) === controller) turnControllers.delete(e.turnId);
586
- }
587
- })();
588
- decisions.set(key, job);
657
+ job = decideTurn($, router, e, next.signal, {
658
+ sessionId,
659
+ view,
660
+ cfg,
661
+ loop,
662
+ loopVersion,
663
+ context,
664
+ nativeModel,
665
+ availableModels,
666
+ });
667
+ router.decisions.set(key, job);
589
668
  }
590
669
  const selected = await job;
591
670
  if (!selected) {
592
- if (!next.signal.aborted && (await $.session.id()) === sessionId && runtime.view?.activeTurnId === e.turnId) {
671
+ if (!next.signal.aborted && (await $.session.id()) === sessionId && router.view?.activeTurnId === e.turnId) {
593
672
  const reserved = await $.state.set(ref, loop, { ifVersion: loopVersion });
594
- if (reserved.isSet)
595
- return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', cfg, runtime);
673
+ if (reserved.isSet) return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', router);
596
674
  }
597
675
  return yield* next(e);
598
676
  }
@@ -606,7 +684,7 @@ export function register(on, options) {
606
684
  availableModels,
607
685
  effort: e.effort,
608
686
  });
609
- await updateView($, runtime, {
687
+ await updateView($, router, {
610
688
  selectedModel: loop.decision.model,
611
689
  effort: loop.decision.effort,
612
690
  tier: loop.decision.tier,
@@ -620,7 +698,7 @@ export function register(on, options) {
620
698
  else request.effort = loop.decision.effort;
621
699
  const response = yield* next(request);
622
700
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
623
- const observed = observeResponse(cfg, loop, {
701
+ const observed = observeResponse(loop, {
624
702
  usage: response.usage,
625
703
  requestedModel: request.model,
626
704
  effort: request.effort ?? null,
@@ -631,22 +709,22 @@ export function register(on, options) {
631
709
  const written = await $.state.set(ref, observed, { ifVersion: loopVersion });
632
710
  // A substituted reply is not the tier's: the strip and trend must not count it as one.
633
711
  const tier = isSameModel(request.model, response.usage?.model) ? loop.decision.tier : null;
634
- if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, tier));
712
+ if (written.isSet) await updateView($, router, responseMetrics(router.view, response, tier));
635
713
  }
636
714
  return response;
637
715
  });
638
716
 
639
717
  on('turn.complete', async ($, e, next) => {
640
- turnConfigs.delete(e.turnId);
641
- turnControllers.get(e.turnId)?.abort();
642
- if (runtime.view?.activeTurnId === e.turnId && runtime.view.phase === 'choosing') {
643
- runtime.view = { ...runtime.view, activeTurnId: null };
644
- const mode = await modeOf($, runtime);
645
- if (runtime.view.activeTurnId === null)
646
- await updateView($, runtime, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
718
+ router.turnConfigs.delete(e.turnId);
719
+ router.turnControllers.get(e.turnId)?.abort();
720
+ if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
721
+ router.view = { ...router.view, activeTurnId: null };
722
+ const mode = await modeOf($, router);
723
+ if (router.view.activeTurnId === null)
724
+ await updateView($, router, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
647
725
  }
648
- prompts.delete(e.turnId);
649
- for (const key of decisions.keys()) if (key.includes(`:${e.turnId}:`)) decisions.delete(key);
726
+ router.prompts.delete(e.turnId);
727
+ for (const key of router.decisions.keys()) if (key.includes(`:${e.turnId}:`)) router.decisions.delete(key);
650
728
  return next(e);
651
729
  });
652
730
 
@@ -657,24 +735,24 @@ export function register(on, options) {
657
735
  const ref = { ...LOOP, id: 'main' };
658
736
  const loop = (await $.state.get(ref)).value;
659
737
  if (loop) await $.state.set(ref, resetHistory(loop));
660
- for (const controller of controllers) controller.abort();
738
+ for (const controller of router.controllers) controller.abort();
661
739
  }
662
740
  return result;
663
741
  });
664
742
 
665
743
  on('session.end', (_$, e, next) => {
666
- for (const controller of controllers) controller.abort();
667
- decisions.clear();
668
- prompts.clear();
669
- turnConfigs.clear();
670
- runtime.view = {
671
- ...initialView(runtime.view?.nativeModel ?? ''),
744
+ for (const controller of router.controllers) controller.abort();
745
+ router.decisions.clear();
746
+ router.prompts.clear();
747
+ router.turnConfigs.clear();
748
+ router.view = {
749
+ ...initialView(router.view?.nativeModel ?? ''),
672
750
  mode: 'auto',
673
- credentials: runtime.view?.credentials ?? null,
674
- health: healthOf(clientOf(config.classifier), config.classifier),
675
- configPath: config.nativePath,
676
- phase: runtime.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
677
- error: runtime.view?.phase === 'unavailable' ? runtime.view.error : null,
751
+ credentials: router.view?.credentials ?? null,
752
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
753
+ configPath: router.config.nativePath,
754
+ phase: router.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
755
+ error: router.view?.phase === 'unavailable' ? router.view.error : null,
678
756
  };
679
757
  return next(e);
680
758
  });
@@ -682,17 +760,17 @@ export function register(on, options) {
682
760
  // While the classifier runs, the turn's spinner says so; the engine's own word returns once the route is set.
683
761
  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
684
762
  if (e.props.message !== null) return next(e);
685
- const view = await readView($, runtime);
763
+ const view = await readView($, router);
686
764
  return view.phase === 'choosing' ? next({ ...e, props: { ...e.props, message: 'Choosing model' } }) : next(e);
687
765
  });
688
766
 
689
767
  // Paused or broken routing stays visible in the prompt footer even when the band is collapsed.
690
768
  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
691
- const view = await readView($, runtime);
769
+ const view = await readView($, router);
692
770
  const label =
693
771
  view.phase === 'unavailable'
694
772
  ? 'router unavailable'
695
- : (await modeOf($, runtime, view.mode)) === 'manual'
773
+ : (await modeOf($, router, view.mode)) === 'manual'
696
774
  ? 'router off'
697
775
  : null;
698
776
  return label ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }) : next(e);
@@ -700,8 +778,8 @@ export function register(on, options) {
700
778
 
701
779
  on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
702
780
  if (e.component === 'Pane' && e.requestId !== PANE) return next(e);
703
- const storedView = await readView($, runtime);
704
- const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
781
+ const storedView = await readView($, router);
782
+ const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
705
783
  const elements = $.ui.resolve(e);
706
784
  const { Box } = elements;
707
785
  const usage = await $.session.usage().catch(() => null);
@@ -713,20 +791,20 @@ export function register(on, options) {
713
791
  await next(e),
714
792
  renderBand(
715
793
  elements,
716
- config,
794
+ router.config,
717
795
  view,
718
796
  usage,
719
797
  { columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
720
798
  {
721
- open: () => openPane($, runtime),
722
- mode: (mode) => changeMode($, runtime, mode),
723
- pin: async (tier) => $.ui.toast(await setPin($, runtime, tier)),
724
- unpin: () => updateView($, runtime, { pendingPin: null }),
799
+ open: () => openPane($, router),
800
+ mode: (mode) => changeMode($, router, mode),
801
+ pin: async (tier) => $.ui.toast(await setPin($, router, tier)),
802
+ unpin: () => updateView($, router, { pendingPin: null }),
725
803
  key: () => openKeySettings($),
726
804
  toggleDetail: async () => {
727
- const bandDetail = !view.bandDetail;
805
+ const bandDetail = !(router.view ?? view).bandDetail;
728
806
  await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
729
- await updateView($, runtime, { bandDetail });
807
+ await updateView($, router, { bandDetail });
730
808
  },
731
809
  },
732
810
  ),
@@ -734,175 +812,9 @@ export function register(on, options) {
734
812
  });
735
813
  }
736
814
  const settings = await $.settings.read().catch(() => ({}));
737
- const modelOptions = Object.keys(config.models).filter((alias) =>
738
- isModelAllowed(config.models[alias].id, settings.availableModels, view.nativeModel),
739
- );
740
- const editRoute = (tier, change) => {
741
- const draft = routeDraftOf(config, runtime.view ?? view);
742
- const current = effectiveRoutes(draft, config).routes[tier];
743
- return updateView($, runtime, {
744
- routeDraft: { ...draft, routes: { ...draft.routes, [tier]: change(current) } },
745
- notice: null,
746
- });
747
- };
748
- // Every pane save adopts the file as written, which may name another classifier than before: a hand edit
749
- // meanwhile, or a row press. Then the new classifier starts clean and the old one's readings leave the view;
750
- // an unavailable reason stays.
751
- const adopt = async (loaded) => {
752
- const switched = loaded.classifier !== config.classifier;
753
- config = loaded;
754
- if (!switched) return {};
755
- clientOf(config.classifier).restore(null);
756
- const current = runtime.view ?? view;
757
- return {
758
- ...CLEARED_READINGS,
759
- error: current.phase === 'unavailable' ? current.error : null,
760
- credentials: await credentialsOf($, options, config),
761
- health: healthOf(clientOf(config.classifier), config.classifier),
762
- };
763
- };
764
- // Pending drafts re-pointed at the config a write just adopted. An edit that still differs stays; everything else
765
- // follows the file, and the file becomes what the draft compares against, so picking a value the write replaced
766
- // counts as a change again.
767
- const rebased = ({ routeDraft, tuning, tuningBase }) => {
768
- const routes = routeDraft && effectiveRoutes(routeDraft, config);
769
- const edited = Object.entries(tuning ?? {}).filter(([key, value]) => value !== tuningBase?.[key]);
770
- return {
771
- routeDraft: routes ? { ...routes, base: routeDraftOf(config, {}).base } : null,
772
- tuning: edited.length ? Object.fromEntries(edited) : null,
773
- tuningBase: edited.length ? tuningOf(config) : null,
774
- };
775
- };
776
- const save = async (change, saved) => {
777
- const result = await saveConfig($, config.nativePath, change);
778
- if (result.error) return updateView($, runtime, { notice: result.error });
779
- const drafts = runtime.view ?? view;
780
- const reset = await adopt(result.config);
781
- return updateView($, runtime, { ...reset, ...rebased(drafts), ...saved(config) });
782
- };
783
- // Defaults go into the routing draft like any edit; the notice says whether Save has anything of that section left
784
- // to write.
785
- const loadDefaults = (patch, what) => {
786
- const changes = routingChanges(config, { ...(runtime.view ?? view), ...patch });
787
- const pending = what === 'route' ? changes.tiers.length + Number(changes.baseline) : changes.policy.length;
788
- return updateView($, runtime, {
789
- ...patch,
790
- notice: pending
791
- ? `${what === 'route' ? 'Route' : 'Policy'} defaults loaded. Save removes your ${what} overrides from router.json.`
792
- : `${what === 'route' ? 'Routes' : 'Policy'} already at defaults.`,
793
- });
794
- };
795
- // A pane write keeps the leaves it changed as router.json had them, read from the file it rewrites rather than from
796
- // the loaded config, so Undo restores them verbatim. A later write replaces them, and Undo clears them.
797
- const write = (label, change, patch = {}) => {
798
- let leaves = [];
799
- return save(
800
- (file) => {
801
- const written = change(file);
802
- leaves = changedLeaves(file, written);
803
- return written;
804
- },
805
- () => ({ ...patch, lastWrite: { label, leaves }, notice: `Saved: ${label}. Applies from the next turn.` }),
806
- );
807
- };
808
- return renderPanel(
809
- elements,
810
- config,
811
- view,
812
- usage,
813
- {
814
- mode: (mode) => changeMode($, runtime, mode),
815
- tab: (tab) => updateView($, runtime, { tab, notice: null }),
816
- help: () => updateView($, runtime, { help: !view.help }),
817
- pin: async (tier) => {
818
- await updateView($, runtime, { notice: await setPin($, runtime, tier) });
819
- },
820
- unpin: () => updateView($, runtime, { pendingPin: null, notice: null }),
821
- key: async () => {
822
- openKeySettings($);
823
- await $.ui.close({ id: PANE });
824
- },
825
- copyPath: async (press) => {
826
- await $.ui.copy({ text: config.nativePath, surface: press?.surface });
827
- await updateView($, runtime, { notice: 'Path copied.' });
828
- },
829
- close: () => $.ui.close({ id: PANE }),
830
- routeModel: (tier, alias) =>
831
- editRoute(tier, (route) => ({
832
- model: alias,
833
- effort: config.models[alias]?.efforts.includes(route.effort) ? route.effort : null,
834
- })),
835
- routeEffort: (tier, effort) => editRoute(tier, (route) => ({ model: route.model, effort })),
836
- baseline: async (tier) => {
837
- const draft = routeDraftOf(config, runtime.view ?? view);
838
- await updateView($, runtime, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
839
- },
840
- saveRouting: async () => {
841
- const current = runtime.view ?? view;
842
- const routeDraft = current.routeDraft;
843
- const saved = tuningOf(config);
844
- const base = current.tuningBase ?? saved;
845
- const edited = Object.keys(current.tuning ?? {}).filter((key) => current.tuning[key] !== base[key]);
846
- const changes = routingChanges(config, current).count;
847
- if (!changes) return updateView($, runtime, { notice: 'No routing changes to save.' });
848
- const after = Object.fromEntries(edited.map((key) => [key, current.tuning[key]]));
849
- return write(
850
- `${changes} routing change${changes === 1 ? '' : 's'}`,
851
- (file) => {
852
- const routed = routeDraft ? withRoutes(file, routeDraft) : file;
853
- return edited.length ? withTuning(routed, { ...base, ...after }, base) : routed;
854
- },
855
- { routeDraft: null, tuning: null, tuningBase: null },
856
- );
857
- },
858
- discardRouting: () =>
859
- updateView($, runtime, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
860
- resetRoutes: () =>
861
- loadDefaults(
862
- {
863
- routeDraft: {
864
- ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
865
- base: routeDraftOf(config, {}).base,
866
- },
867
- },
868
- 'route',
869
- ),
870
- tune: (key, value) =>
871
- updateView($, runtime, {
872
- tuning: { ...(runtime.view ?? view).tuning, [key]: value },
873
- tuningBase: (runtime.view ?? view).tuningBase ?? tuningOf(config),
874
- notice: null,
875
- }),
876
- resetPolicy: () =>
877
- loadDefaults(
878
- // The draft is replaced whole, so it starts from the saved values, not from an older draft's base.
879
- { tuning: tuningOf(DEFAULTS), tuningBase: tuningOf(config) },
880
- 'policy',
881
- ),
882
- classifier: (id) => {
883
- if (!id || id === config.classifier || !Object.hasOwn(config.classifiers, id)) return undefined;
884
- const from = config.classifier;
885
- return write(`classifier ${config.classifiers[from].label} → ${config.classifiers[id].label}`, (file) =>
886
- withClassifier(file, id),
887
- );
888
- },
889
- classifierTimeout: (timeoutMs) => {
890
- const active = activeClassifier(config);
891
- if (timeoutMs === active.timeoutMs) return undefined;
892
- return write(`${active.label} deadline ${active.timeoutMs} → ${timeoutMs} ms`, (file) =>
893
- withClassifierTimeout(file, config.classifier, timeoutMs),
894
- );
895
- },
896
- undo: async () => {
897
- const last = (runtime.view ?? view).lastWrite;
898
- if (!last) return undefined;
899
- return save(
900
- (file) => restored(file, last.leaves),
901
- () => ({ lastWrite: null, notice: `Undid: ${last.label}.` }),
902
- );
903
- },
904
- },
905
- { modelOptions },
815
+ const modelOptions = Object.keys(router.config.models).filter((alias) =>
816
+ isModelAllowed(router.config.models[alias].id, settings.availableModels, view.nativeModel),
906
817
  );
818
+ return renderPanel(elements, router.config, view, usage, paneActions($, router, view), { modelOptions });
907
819
  });
908
820
  }