@alexeiled/claude-router 1.3.0 → 1.3.2

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,14 @@
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
+ routeModel,
11
+ supportedVersion,
7
12
  TIERS,
8
13
  tuningOf,
9
14
  withClassifier,
@@ -11,23 +16,32 @@ import {
11
16
  withRoutes,
12
17
  withTuning,
13
18
  } 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';
19
+ import { changedLeaves, notSaved, restored, rewrittenConfig } from '../lib/config-file.mjs';
20
+ import {
21
+ classifierStatus,
22
+ classifierTimed,
23
+ GATEWAY_CLEANUP,
24
+ GATEWAY_SETTINGS,
25
+ missingCredentials,
26
+ } from '../lib/display.mjs';
27
+ import { clip } from '../lib/facts.mjs';
28
+ import { renderPanel, routeDraftOf, routingChanges } from '../lib/panel.mjs';
20
29
  import {
21
30
  chooseRoute,
22
31
  continueRoute,
23
32
  emptyLoop,
24
33
  isModelAllowed,
34
+ isNativeFallback,
25
35
  isSameModel,
26
36
  nativeFacts,
27
37
  observeResponse,
28
38
  prepareLoop,
29
39
  resetHistory,
30
- } from '../lib/native-router.mjs';
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,59 +49,44 @@ 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);
82
76
  }
83
77
 
84
- async function modeOf($, runtime, fallback = 'auto') {
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());
81
+ }
82
+
83
+ async function modeOf($, router, fallback = 'auto') {
85
84
  const sessionId = await $.session.id();
86
- if (runtime.modes.has(sessionId)) return runtime.modes.get(sessionId);
85
+ if (router.modes.has(sessionId)) return router.modes.get(sessionId);
87
86
  try {
88
87
  const saved = await $.store.get(`${MODE_PREFIX}${sessionId}`);
89
88
  const mode = saved === 'manual' || saved === 'auto' ? saved : fallback;
90
- runtime.modes.set(sessionId, mode);
89
+ router.modes.set(sessionId, mode);
91
90
  return mode;
92
91
  } catch {
93
92
  return 'manual';
@@ -103,25 +102,25 @@ async function rememberMode($, mode) {
103
102
  }
104
103
  }
105
104
 
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);
105
+ async function updateView($, router, patch) {
106
+ const value = router.view ?? (await readView($, router));
107
+ router.view = { ...value, ...patch };
108
+ await $.state.set(VIEW, router.view);
110
109
  }
111
110
 
112
111
  // A notice answers the last press in the pane, so the pane opens without one; the last write keeps its Undo in the
113
112
  // status bar.
114
- async function openPane($, runtime) {
115
- await updateView($, runtime, { notice: null });
113
+ async function openPane($, router) {
114
+ await updateView($, router, { notice: null });
116
115
  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
117
116
  }
118
117
 
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);
118
+ async function changeMode($, router, mode) {
119
+ const view = router.view ?? (await readView($, router));
120
+ for (const controller of router.controllers) controller.abort();
121
+ router.modes.set(await $.session.id(), mode);
123
122
  const saved = await rememberMode($, mode);
124
- await updateView($, runtime, {
123
+ await updateView($, router, {
125
124
  mode,
126
125
  pendingPin: null,
127
126
  phase: view.phase === 'unavailable' ? 'unavailable' : mode === 'manual' ? 'manual' : 'ready',
@@ -130,12 +129,12 @@ async function changeMode($, runtime, mode) {
130
129
  });
131
130
  }
132
131
 
133
- async function setPin($, runtime, tier) {
134
- const view = runtime.view ?? (await readView($, runtime));
132
+ async function setPin($, router, tier) {
133
+ const view = router.view ?? (await readView($, router));
135
134
  if (view.phase === 'unavailable') return `Routing unavailable: ${view.error}.`;
136
- const mode = await modeOf($, runtime, view.mode);
135
+ const mode = await modeOf($, router, view.mode);
137
136
  if (mode === 'manual') return 'Routing is paused. Select Auto before pinning a turn.';
138
- await updateView($, runtime, { pendingPin: tier });
137
+ await updateView($, router, { pendingPin: tier });
139
138
  return `${tier} pinned for the next turn and its tool continuations.`;
140
139
  }
141
140
 
@@ -178,59 +177,22 @@ async function credentialsOf($, options, config) {
178
177
  );
179
178
  }
180
179
 
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
180
  // The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
187
181
  function openKeySettings($) {
188
182
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
189
183
  }
190
184
 
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]];
185
+ async function loadNativeConfig($) {
186
+ for (const source of ['project', 'local']) {
187
+ const settings = await $.settings.read({ source });
188
+ if (settings.env && ['HOME', 'CLAUDE_CONFIG_DIR'].some((key) => Object.hasOwn(settings.env, key)))
189
+ throw new Error('project settings cannot redirect the router profile');
232
190
  }
233
- return next;
191
+ const home = await $.env.get('HOME');
192
+ const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
193
+ const path = `${profile}/router.json`;
194
+ const userFile = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
195
+ return { ...loadConfig({ userFile }), nativePath: path };
234
196
  }
235
197
 
236
198
  // Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
@@ -239,15 +201,11 @@ async function saveConfig($, path, change) {
239
201
  try {
240
202
  if ((await $.fs.exists(path)) && (await $.fs.stat(path)).isLink)
241
203
  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 } };
204
+ const { config, text } = rewrittenConfig((await $.fs.exists(path)) ? await $.fs.read(path) : null, change);
205
+ await $.fs.write(path, text);
206
+ return { config: { ...config, nativePath: path } };
247
207
  } 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.` };
208
+ return { error: notSaved(error) };
251
209
  }
252
210
  }
253
211
 
@@ -269,26 +227,6 @@ function detailText(config, view) {
269
227
  ].join('\n');
270
228
  }
271
229
 
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
230
  async function contextOf($, loop) {
293
231
  const previous = loop.lastRequest ? loop.lastRequest.tokens + loop.lastRequest.outputTokens : null;
294
232
  try {
@@ -302,38 +240,10 @@ async function contextOf($, loop) {
302
240
  }
303
241
  }
304
242
 
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) {
243
+ async function* passMain($, e, next, loop, version, nativeModel, reason, router) {
334
244
  const ref = { ...LOOP, id: 'main' };
335
245
  const context = await contextOf($, loop);
336
- await updateView($, runtime, {
246
+ await updateView($, router, {
337
247
  nativeModel,
338
248
  selectedModel: e.model,
339
249
  effort: e.effort ?? null,
@@ -344,7 +254,7 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
344
254
  const sessionId = await $.session.id();
345
255
  const response = yield* next(e);
346
256
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
347
- const observed = observeResponse(config, loop, {
257
+ const observed = observeResponse(loop, {
348
258
  usage: response.usage,
349
259
  requestedModel: e.model,
350
260
  effort: e.effort ?? null,
@@ -352,26 +262,271 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
352
262
  now: Date.now(),
353
263
  });
354
264
  const written = await $.state.set(ref, observed, { ifVersion: version });
355
- if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, null));
265
+ if (written.isSet) await updateView($, router, responseMetrics(router.view, response, null));
356
266
  }
357
267
  return response;
358
268
  }
359
269
 
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);
270
+ // One turn's classification and route, written to the loop at `loopVersion`: the loop and its new version, or null
271
+ // when the turn was aborted, left the session or Auto, or lost the write. `signal` is the step's: its abort cancels
272
+ // the classifier call. The pin is the one in `view`, the view as the step read it.
273
+ async function decideTurn($, router, e, signal, step) {
274
+ const { sessionId, view, cfg, loop, loopVersion, context, nativeModel, availableModels } = step;
275
+ const ref = { ...LOOP, id: 'main' };
276
+ const controller = new AbortController();
277
+ const cancel = () => controller.abort();
278
+ signal.addEventListener('abort', cancel, { once: true });
279
+ router.controllers.add(controller);
280
+ router.turnControllers.set(e.turnId, controller);
281
+ const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
282
+ try {
283
+ const pin = view.pendingPin;
284
+ const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, router.options, name));
285
+ const messages = await $.session.messages({ as: 'api' });
286
+ if (!(await live())) return null;
287
+ const facts = nativeFacts(cfg, loop, {
288
+ messages,
289
+ prompt: router.prompts.get(e.turnId),
290
+ effort: e.effort,
291
+ turnId: e.turnId,
292
+ contextTokens: context.tokens,
293
+ });
294
+ await updateView($, router, {
295
+ phase: 'choosing',
296
+ activeTurnId: e.turnId,
297
+ nativeModel,
298
+ pendingPin: null,
299
+ credentials: { ...router.view?.credentials, [cfg.classifier]: credentials.missing },
300
+ });
301
+ const adviceStarted = Date.now();
302
+ const result = pin
303
+ ? { advice: null, error: null }
304
+ : await clientOf(router, cfg.classifier).ask({
305
+ request: (url, init) => $.http.fetch(url, init),
306
+ sleep: (ms, args) => $.clock.sleep(ms, args),
307
+ config: cfg,
308
+ apiKey: credentials.apiKey,
309
+ endpoint: credentials.endpoint,
310
+ prompt: facts.prompt,
311
+ turns: facts.turns,
312
+ signal: controller.signal,
313
+ });
314
+ if (controller.signal.aborted || (await $.session.id()) !== sessionId || (await modeOf($, router)) !== 'auto')
315
+ return null;
316
+ const previous = loop.decision;
317
+ const selected = chooseRoute(cfg, loop, {
318
+ facts,
319
+ advice: result.advice,
320
+ pin,
321
+ nativeModel,
322
+ contextKnown: context.known,
323
+ availableModels,
324
+ now: Date.now(),
325
+ });
326
+ selected.engineModel = e.model;
327
+ const written = await $.state.set(ref, selected, { ifVersion: loopVersion });
328
+ // Manual, /clear and turn completion abort the controller; one may land during the write.
329
+ if (!written.isSet || controller.signal.aborted) return null;
330
+ if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
331
+ $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
332
+ await updateView($, router, {
333
+ phase: 'routed',
334
+ selectedModel: selected.decision.model,
335
+ actualModel: null,
336
+ tier: selected.decision.tier,
337
+ effort: selected.decision.effort,
338
+ reason: selected.decision.reason,
339
+ contextTokens: context.tokens,
340
+ contextKnown: context.known,
341
+ comparison: selected.decision.comparison,
342
+ // A turn that started before a classifier switch routes on its own classifier's answer, but the
343
+ // pane now labels the new one: its readings stay off the view.
344
+ ...(cfg.classifier === router.config.classifier
345
+ ? {
346
+ error: result.error,
347
+ health: healthOf(clientOf(router, cfg.classifier), cfg.classifier),
348
+ adviceMs: pin || !classifierTimed(result.error) ? null : Date.now() - adviceStarted,
349
+ adviceChoice: result.advice?.choice ?? null,
350
+ probabilities: result.advice?.probabilities ?? null,
351
+ estimate: selected.decision.estimate ?? null,
352
+ }
353
+ : {}),
354
+ });
355
+ return { loop: selected, version: written.version };
356
+ } finally {
357
+ signal.removeEventListener('abort', cancel);
358
+ router.controllers.delete(controller);
359
+ if (router.turnControllers.get(e.turnId) === controller) router.turnControllers.delete(e.turnId);
360
+ }
361
+ }
362
+
363
+ // The pane's handlers. `view` is the view the pane was drawn from; a handler reads `router.view` first, which holds
364
+ // any press since.
365
+ function paneActions($, router, view) {
366
+ const editRoute = (tier, change) => {
367
+ const draft = routeDraftOf(router.config, router.view ?? view);
368
+ const current = effectiveRoutes(draft, router.config).routes[tier];
369
+ return updateView($, router, {
370
+ routeDraft: { ...draft, routes: { ...draft.routes, [tier]: change(current) } },
371
+ notice: null,
372
+ });
373
+ };
374
+ // Every pane save adopts the file as written, which may name another classifier than before: a hand edit
375
+ // meanwhile, or a row press. Then the new classifier starts clean and the old one's readings leave the view;
376
+ // an unavailable reason stays.
377
+ const adopt = async (loaded) => {
378
+ const switched = loaded.classifier !== router.config.classifier;
379
+ router.config = loaded;
380
+ if (!switched) return {};
381
+ clientOf(router, router.config.classifier).restore(null);
382
+ const current = router.view ?? view;
383
+ return {
384
+ ...CLEARED_READINGS,
385
+ error: current.phase === 'unavailable' ? current.error : null,
386
+ credentials: await credentialsOf($, router.options, router.config),
387
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
388
+ };
389
+ };
390
+ // Pending drafts re-pointed at the config a write just adopted. An edit that still differs stays; everything else
391
+ // follows the file, and the file becomes what the draft compares against, so picking a value the write replaced
392
+ // counts as a change again.
393
+ const rebased = ({ routeDraft, tuning, tuningBase }) => {
394
+ const routes = routeDraft && effectiveRoutes(routeDraft, router.config);
395
+ const edited = Object.entries(tuning ?? {}).filter(([key, value]) => value !== tuningBase?.[key]);
396
+ return {
397
+ routeDraft: routes ? { ...routes, base: routeDraftOf(router.config, {}).base } : null,
398
+ tuning: edited.length ? Object.fromEntries(edited) : null,
399
+ tuningBase: edited.length ? tuningOf(router.config) : null,
400
+ };
401
+ };
402
+ const save = async (change, saved) => {
403
+ const result = await saveConfig($, router.config.nativePath, change);
404
+ if (result.error) return updateView($, router, { notice: result.error });
405
+ const drafts = router.view ?? view;
406
+ const reset = await adopt(result.config);
407
+ return updateView($, router, { ...reset, ...rebased(drafts), ...saved(router.config) });
408
+ };
409
+ // Defaults go into the routing draft like any edit; the notice says whether Save has anything of that section left
410
+ // to write.
411
+ const loadDefaults = (patch, what) => {
412
+ const changes = routingChanges(router.config, { ...(router.view ?? view), ...patch });
413
+ const pending = what === 'route' ? changes.tiers.length + Number(changes.baseline) : changes.policy.length;
414
+ return updateView($, router, {
415
+ ...patch,
416
+ notice: pending
417
+ ? `${what === 'route' ? 'Route' : 'Policy'} defaults loaded. Save removes your ${what} overrides from router.json.`
418
+ : `${what === 'route' ? 'Routes' : 'Policy'} already at defaults.`,
419
+ });
420
+ };
421
+ // A pane write keeps the leaves it changed as router.json had them, read from the file it rewrites rather than from
422
+ // the loaded config, so Undo restores them verbatim. A later write replaces them, and Undo clears them.
423
+ const write = (label, change, patch = {}) => {
424
+ let leaves = [];
425
+ return save(
426
+ (file) => {
427
+ const written = change(file);
428
+ leaves = changedLeaves(file, written);
429
+ return written;
430
+ },
431
+ () => ({ ...patch, lastWrite: { label, leaves }, notice: `Saved: ${label}. Applies from the next turn.` }),
432
+ );
433
+ };
434
+ return {
435
+ mode: (mode) => changeMode($, router, mode),
436
+ tab: (tab) => updateView($, router, { tab, notice: null }),
437
+ help: () => updateView($, router, { help: !(router.view ?? view).help }),
438
+ pin: async (tier) => {
439
+ await updateView($, router, { notice: await setPin($, router, tier) });
440
+ },
441
+ unpin: () => updateView($, router, { pendingPin: null, notice: null }),
442
+ key: async () => {
443
+ openKeySettings($);
444
+ await $.ui.close({ id: PANE });
445
+ },
446
+ copyPath: async (press) => {
447
+ await $.ui.copy({ text: router.config.nativePath, surface: press?.surface });
448
+ await updateView($, router, { notice: 'Path copied.' });
449
+ },
450
+ close: () => $.ui.close({ id: PANE }),
451
+ routeModel: (tier, alias) =>
452
+ editRoute(tier, (route) => ({
453
+ model: alias,
454
+ effort: router.config.models[alias]?.efforts.includes(route.effort) ? route.effort : null,
455
+ })),
456
+ routeEffort: (tier, effort) => editRoute(tier, (route) => ({ model: route.model, effort })),
457
+ baseline: async (tier) => {
458
+ const draft = routeDraftOf(router.config, router.view ?? view);
459
+ await updateView($, router, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
460
+ },
461
+ saveRouting: async () => {
462
+ const current = router.view ?? view;
463
+ const routeDraft = current.routeDraft;
464
+ const saved = tuningOf(router.config);
465
+ const base = current.tuningBase ?? saved;
466
+ const edited = Object.keys(current.tuning ?? {}).filter((key) => current.tuning[key] !== base[key]);
467
+ const changes = routingChanges(router.config, current).count;
468
+ if (!changes) return updateView($, router, { notice: 'No routing changes to save.' });
469
+ const after = Object.fromEntries(edited.map((key) => [key, current.tuning[key]]));
470
+ return write(
471
+ `${changes} routing change${changes === 1 ? '' : 's'}`,
472
+ (file) => {
473
+ const routed = routeDraft ? withRoutes(file, routeDraft) : file;
474
+ return edited.length ? withTuning(routed, { ...base, ...after }, base) : routed;
475
+ },
476
+ { routeDraft: null, tuning: null, tuningBase: null },
477
+ );
478
+ },
479
+ discardRouting: () => updateView($, router, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
480
+ resetRoutes: () =>
481
+ loadDefaults(
482
+ {
483
+ routeDraft: {
484
+ ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
485
+ base: routeDraftOf(router.config, {}).base,
486
+ },
487
+ },
488
+ 'route',
489
+ ),
490
+ tune: (key, value) =>
491
+ updateView($, router, {
492
+ tuning: { ...(router.view ?? view).tuning, [key]: value },
493
+ tuningBase: (router.view ?? view).tuningBase ?? tuningOf(router.config),
494
+ notice: null,
495
+ }),
496
+ resetPolicy: () =>
497
+ loadDefaults(
498
+ // The draft is replaced whole, so it starts from the saved values, not from an older draft's base.
499
+ { tuning: tuningOf(DEFAULTS), tuningBase: tuningOf(router.config) },
500
+ 'policy',
501
+ ),
502
+ classifier: (id) => {
503
+ const { config } = router;
504
+ if (!id || id === config.classifier || !Object.hasOwn(config.classifiers, id)) return undefined;
505
+ const from = config.classifier;
506
+ return write(`classifier ${config.classifiers[from].label} → ${config.classifiers[id].label}`, (file) =>
507
+ withClassifier(file, id),
508
+ );
509
+ },
510
+ classifierTimeout: (timeoutMs) => {
511
+ const active = activeClassifier(router.config);
512
+ if (timeoutMs === active.timeoutMs) return undefined;
513
+ return write(`${active.label} deadline ${active.timeoutMs} → ${timeoutMs} ms`, (file) =>
514
+ withClassifierTimeout(file, router.config.classifier, timeoutMs),
515
+ );
516
+ },
517
+ undo: async () => {
518
+ const last = (router.view ?? view).lastWrite;
519
+ if (!last) return undefined;
520
+ return save(
521
+ (file) => restored(file, last.leaves),
522
+ () => ({ lastWrite: null, notice: `Undid: ${last.label}.` }),
523
+ );
524
+ },
369
525
  };
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() };
526
+ }
527
+
528
+ export function register(on, options) {
529
+ const router = createRouter(options);
375
530
 
376
531
  on('session.start', async ($, e, next) => {
377
532
  await $.command.register({
@@ -382,28 +537,28 @@ export function register(on, options) {
382
537
  });
383
538
  const model = await $.session.model();
384
539
  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);
540
+ router.config = await loadNativeConfig($);
541
+ const existing = await readView($, router);
542
+ router.view = existing;
543
+ const sameClassifier = existing.health?.classifier === router.config.classifier;
544
+ clientOf(router, router.config.classifier).restore(sameClassifier ? existing.health : null);
390
545
  const base = await $.env.get('ANTHROPIC_BASE_URL');
391
546
  const version = await $.session.version().catch(() => null);
392
547
  const supported = supportedVersion(version?.version);
393
- const baselineModel = config.models[config.routes[config.baselineTier].model].id;
548
+ const baselineModel = routeModel(router.config, router.config.baselineTier).id;
394
549
  const gateway =
395
550
  ['jev-router', 'jev-router[1m]'].includes(model) ||
396
551
  model === 'router' ||
397
552
  Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
398
- await updateView($, runtime, {
553
+ await updateView($, router, {
399
554
  nativeModel: model,
400
- mode: await modeOf($, runtime, model === baselineModel ? 'auto' : 'manual'),
555
+ mode: await modeOf($, router, model === baselineModel ? 'auto' : 'manual'),
401
556
  phase: gateway || !supported ? 'unavailable' : 'ready',
402
557
  error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
403
558
  ...(sameClassifier ? {} : CLEARED_READINGS),
404
- credentials: await credentialsOf($, options, config),
405
- health: healthOf(clientOf(config.classifier), config.classifier),
406
- configPath: config.nativePath,
559
+ credentials: await credentialsOf($, options, router.config),
560
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
561
+ configPath: router.config.nativePath,
407
562
  tuning: null,
408
563
  tuningBase: null,
409
564
  routeDraft: null,
@@ -411,7 +566,7 @@ export function register(on, options) {
411
566
  bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
412
567
  });
413
568
  } catch (error) {
414
- await updateView($, runtime, {
569
+ await updateView($, router, {
415
570
  phase: 'unavailable',
416
571
  error: error.message?.endsWith(MIGRATION_HINT)
417
572
  ? 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path'
@@ -424,8 +579,8 @@ export function register(on, options) {
424
579
  on('command.run', { command: 'model' }, async ($, e, next) => {
425
580
  const result = await next(e);
426
581
  if (e.origin.kind !== 'plugin') {
427
- await changeMode($, runtime, 'manual');
428
- await updateView($, runtime, { nativeModel: await $.session.model(), reason: 'model selected manually' });
582
+ await changeMode($, router, 'manual');
583
+ await updateView($, router, { nativeModel: await $.session.model(), reason: 'model selected manually' });
429
584
  }
430
585
  return result;
431
586
  });
@@ -433,8 +588,8 @@ export function register(on, options) {
433
588
  on('config.set', { key: 'model' }, async ($, e, next) => {
434
589
  const result = await next(e);
435
590
  if (!result.deny && e.origin.kind !== 'plugin') {
436
- await changeMode($, runtime, 'manual');
437
- await updateView($, runtime, { nativeModel: await $.session.model() });
591
+ await changeMode($, router, 'manual');
592
+ await updateView($, router, { nativeModel: await $.session.model() });
438
593
  }
439
594
  return result;
440
595
  });
@@ -442,34 +597,34 @@ export function register(on, options) {
442
597
  on('command.run', { command: 'router' }, async ($, e) => {
443
598
  const [action, tier] = e.args.trim().split(/\s+/);
444
599
  if (action === 'auto' || action === 'off') {
445
- await changeMode($, runtime, action === 'auto' ? 'auto' : 'manual');
600
+ await changeMode($, router, action === 'auto' ? 'auto' : 'manual');
446
601
  return { text: action === 'auto' ? 'Auto routing enabled.' : 'Manual mode: Claude’s model is preserved.' };
447
602
  }
448
603
  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);
604
+ return { text: TIERS.includes(tier) ? await setPin($, router, tier) : `Choose ${TIERS.join(', ')}.` };
605
+ const storedView = await readView($, router);
606
+ const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
607
+ if (!(await $.session.surfaces()).length) return { text: detailText(router.config, view) };
608
+ await openPane($, router);
454
609
  return {};
455
610
  });
456
611
 
457
612
  on('turn.start', (_$, e, next) => {
458
- turnConfigs.set(e.turnId, config);
459
- prompts.set(e.turnId, clip(e.text, config.context.maxTextChars));
613
+ router.turnConfigs.set(e.turnId, router.config);
614
+ router.prompts.set(e.turnId, clip(e.text, router.config.context.maxTextChars));
460
615
  return next(e);
461
616
  });
462
617
 
463
618
  on('turn.step', async function* ($, e, next) {
464
619
  if (e.agentId) return yield* next(e);
465
- const cfg = turnConfigs.get(e.turnId) ?? config;
620
+ const cfg = router.turnConfigs.get(e.turnId) ?? router.config;
466
621
  const sessionId = await $.session.id();
467
622
  const nativeModel = await $.session.model();
468
- const view = await readView($, runtime);
469
- const mode = await modeOf($, runtime, view.mode);
623
+ const view = await readView($, router);
624
+ const mode = await modeOf($, router, view.mode);
470
625
  if (e.index === 0) {
471
626
  const saved = await rememberMode($, mode);
472
- await updateView($, runtime, {
627
+ await updateView($, router, {
473
628
  mode,
474
629
  ...(!saved ? { notice: 'Resume preference could not be saved. Current mode remains active.' } : {}),
475
630
  });
@@ -479,120 +634,35 @@ export function register(on, options) {
479
634
  let loopVersion = loaded.version;
480
635
  let loop = prepareLoop(loaded.value ?? emptyLoop(cfg, e.model), e.messageCount);
481
636
  if (view.phase === 'unavailable' || mode === 'manual') {
482
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', cfg, runtime);
637
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', router);
483
638
  }
484
639
  if (loop.turnId === e.turnId && isNativeFallback(loop, e.model)) {
485
- return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', cfg, runtime);
640
+ return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'native-fallback', router);
486
641
  }
487
642
  const context = await contextOf($, loop);
488
643
  const settings = await $.settings.read();
489
644
  const availableModels = settings.availableModels;
490
645
  const key = `${sessionId}:${e.turnId}:${loop.generation}`;
491
646
  if (loop.turnId !== e.turnId) {
492
- let job = decisions.get(key);
647
+ let job = router.decisions.get(key);
493
648
  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);
649
+ job = decideTurn($, router, e, next.signal, {
650
+ sessionId,
651
+ view,
652
+ cfg,
653
+ loop,
654
+ loopVersion,
655
+ context,
656
+ nativeModel,
657
+ availableModels,
658
+ });
659
+ router.decisions.set(key, job);
589
660
  }
590
661
  const selected = await job;
591
662
  if (!selected) {
592
- if (!next.signal.aborted && (await $.session.id()) === sessionId && runtime.view?.activeTurnId === e.turnId) {
663
+ if (!next.signal.aborted && (await $.session.id()) === sessionId && router.view?.activeTurnId === e.turnId) {
593
664
  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);
665
+ if (reserved.isSet) return yield* passMain($, e, next, loop, reserved.version, nativeModel, 'manual', router);
596
666
  }
597
667
  return yield* next(e);
598
668
  }
@@ -606,7 +676,7 @@ export function register(on, options) {
606
676
  availableModels,
607
677
  effort: e.effort,
608
678
  });
609
- await updateView($, runtime, {
679
+ await updateView($, router, {
610
680
  selectedModel: loop.decision.model,
611
681
  effort: loop.decision.effort,
612
682
  tier: loop.decision.tier,
@@ -620,7 +690,7 @@ export function register(on, options) {
620
690
  else request.effort = loop.decision.effort;
621
691
  const response = yield* next(request);
622
692
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
623
- const observed = observeResponse(cfg, loop, {
693
+ const observed = observeResponse(loop, {
624
694
  usage: response.usage,
625
695
  requestedModel: request.model,
626
696
  effort: request.effort ?? null,
@@ -631,22 +701,22 @@ export function register(on, options) {
631
701
  const written = await $.state.set(ref, observed, { ifVersion: loopVersion });
632
702
  // A substituted reply is not the tier's: the strip and trend must not count it as one.
633
703
  const tier = isSameModel(request.model, response.usage?.model) ? loop.decision.tier : null;
634
- if (written.isSet) await updateView($, runtime, responseMetrics(runtime.view, response, tier));
704
+ if (written.isSet) await updateView($, router, responseMetrics(router.view, response, tier));
635
705
  }
636
706
  return response;
637
707
  });
638
708
 
639
709
  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' });
710
+ router.turnConfigs.delete(e.turnId);
711
+ router.turnControllers.get(e.turnId)?.abort();
712
+ if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
713
+ router.view = { ...router.view, activeTurnId: null };
714
+ const mode = await modeOf($, router);
715
+ if (router.view.activeTurnId === null)
716
+ await updateView($, router, { phase: mode === 'manual' ? 'manual' : 'ready', reason: 'interrupted' });
647
717
  }
648
- prompts.delete(e.turnId);
649
- for (const key of decisions.keys()) if (key.includes(`:${e.turnId}:`)) decisions.delete(key);
718
+ router.prompts.delete(e.turnId);
719
+ for (const key of router.decisions.keys()) if (key.includes(`:${e.turnId}:`)) router.decisions.delete(key);
650
720
  return next(e);
651
721
  });
652
722
 
@@ -657,24 +727,24 @@ export function register(on, options) {
657
727
  const ref = { ...LOOP, id: 'main' };
658
728
  const loop = (await $.state.get(ref)).value;
659
729
  if (loop) await $.state.set(ref, resetHistory(loop));
660
- for (const controller of controllers) controller.abort();
730
+ for (const controller of router.controllers) controller.abort();
661
731
  }
662
732
  return result;
663
733
  });
664
734
 
665
735
  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 ?? ''),
736
+ for (const controller of router.controllers) controller.abort();
737
+ router.decisions.clear();
738
+ router.prompts.clear();
739
+ router.turnConfigs.clear();
740
+ router.view = {
741
+ ...initialView(router.view?.nativeModel ?? ''),
672
742
  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,
743
+ credentials: router.view?.credentials ?? null,
744
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
745
+ configPath: router.config.nativePath,
746
+ phase: router.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
747
+ error: router.view?.phase === 'unavailable' ? router.view.error : null,
678
748
  };
679
749
  return next(e);
680
750
  });
@@ -682,17 +752,17 @@ export function register(on, options) {
682
752
  // While the classifier runs, the turn's spinner says so; the engine's own word returns once the route is set.
683
753
  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
684
754
  if (e.props.message !== null) return next(e);
685
- const view = await readView($, runtime);
755
+ const view = await readView($, router);
686
756
  return view.phase === 'choosing' ? next({ ...e, props: { ...e.props, message: 'Choosing model' } }) : next(e);
687
757
  });
688
758
 
689
759
  // Paused or broken routing stays visible in the prompt footer even when the band is collapsed.
690
760
  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
691
- const view = await readView($, runtime);
761
+ const view = await readView($, router);
692
762
  const label =
693
763
  view.phase === 'unavailable'
694
764
  ? 'router unavailable'
695
- : (await modeOf($, runtime, view.mode)) === 'manual'
765
+ : (await modeOf($, router, view.mode)) === 'manual'
696
766
  ? 'router off'
697
767
  : null;
698
768
  return label ? next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }) : next(e);
@@ -700,8 +770,8 @@ export function register(on, options) {
700
770
 
701
771
  on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
702
772
  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) };
773
+ const storedView = await readView($, router);
774
+ const view = { ...storedView, mode: await modeOf($, router, storedView.mode) };
705
775
  const elements = $.ui.resolve(e);
706
776
  const { Box } = elements;
707
777
  const usage = await $.session.usage().catch(() => null);
@@ -713,20 +783,20 @@ export function register(on, options) {
713
783
  await next(e),
714
784
  renderBand(
715
785
  elements,
716
- config,
786
+ router.config,
717
787
  view,
718
788
  usage,
719
789
  { columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
720
790
  {
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 }),
791
+ open: () => openPane($, router),
792
+ mode: (mode) => changeMode($, router, mode),
793
+ pin: async (tier) => $.ui.toast(await setPin($, router, tier)),
794
+ unpin: () => updateView($, router, { pendingPin: null }),
725
795
  key: () => openKeySettings($),
726
796
  toggleDetail: async () => {
727
- const bandDetail = !view.bandDetail;
797
+ const bandDetail = !(router.view ?? view).bandDetail;
728
798
  await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
729
- await updateView($, runtime, { bandDetail });
799
+ await updateView($, router, { bandDetail });
730
800
  },
731
801
  },
732
802
  ),
@@ -734,175 +804,9 @@ export function register(on, options) {
734
804
  });
735
805
  }
736
806
  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 },
807
+ const modelOptions = Object.keys(router.config.models).filter((alias) =>
808
+ isModelAllowed(router.config.models[alias].id, settings.availableModels, view.nativeModel),
906
809
  );
810
+ return renderPanel(elements, router.config, view, usage, paneActions($, router, view), { modelOptions });
907
811
  });
908
812
  }