@alexeiled/claude-router 1.1.1 → 1.2.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.
@@ -18,14 +18,17 @@ claude --model claude-sonnet-5-5
18
18
  In Claude Code:
19
19
 
20
20
  1. Run `/plugin configure router`.
21
- 2. Select the Jev API key option, enter the key, and save it.
22
- 3. Check the band above the prompt: `▂▄▆█ Auto · ready`. On another model the session starts in Manual; run `/router auto` to route.
21
+ 2. Enter the credentials of the classifier you use, and save them:
22
+ - **Jev** (the default): the Jev API key from typesafe.ai.
23
+ - **Clef** or **Clef Flash** on Cloudflare Workers AI: the Cloudflare API token and the Cloudflare account ID. One token covers both models.
24
+ 3. To use Clef or Clef Flash, open the pane's **Tuning** tab and select its row under **Classifier**. See [Choose the classifier](#choose-the-classifier).
25
+ 4. Check the band above the prompt: `▂▄▆█ Auto · ready`. On another model the session starts in Manual; run `/router auto` to route.
23
26
 
24
- The key is stored as a sensitive plugin option. Do not paste it into a model conversation. The [configuration guide](configuration.md) covers optional settings and the old v0.8 migration.
27
+ Keys are stored as sensitive plugin options. Do not paste them into a model conversation. The [configuration guide](configuration.md) covers optional settings and migrations.
25
28
 
26
29
  ## Read the status band
27
30
 
28
- Router draws one line above the prompt. The line ends with a **Router** button that opens the pane. When the band is narrow, the less important parts drop first: classifier figures, then context and cache, then the reason. The tier and model always stay.
31
+ Router draws one line above the prompt. The line ends with a **Router** button that opens the pane. When the band is narrow, the less important parts drop first: classifier figures, then context and cache, then the reason. The tier and model always stay, except behind a classifier warning: the warning and its **Set up** button come first, and the route gives way to them.
29
32
 
30
33
  ![Five band states: routed to high, two rows with the hover row, a pending pin, a missing classifier key, and Manual mode](router-band.svg)
31
34
 
@@ -34,7 +37,7 @@ Read the first line of the picture from left to right:
34
37
  - **Tier meter** `▂▄▆█`: one bar per tier, lit up to the current tier in its color, like signal strength.
35
38
  - **Tier and model**: the route for this turn. **fallback** means Claude Code answered with another model.
36
39
  - **Reason**: one or two words with a direction, such as `↑ jump`, `↓ downgrade`, `= fits`, or `… waiting to go down`.
37
- - **Classifier support**: what Jev gave the switch against the bar the policy required.
40
+ - **Classifier support**: what the active classifier, such as Jev or Clef Flash, gave the switch against the bar the policy required.
38
41
  - **ctx** and **cache**: context use and cache reuse on the last reply. They turn yellow at 60% context and red at 80%.
39
42
 
40
43
  | Band shows | Meaning |
@@ -42,7 +45,8 @@ Read the first line of the picture from left to right:
42
45
  | `Auto · ready` | Auto mode is ready for a new turn. |
43
46
  | `choosing for this turn…` | The classifier and local policy are running. The spinner says `Choosing model`. |
44
47
  | `⏵ next turn: high ✕` | A pin is set. **✕** cancels it. |
45
- | `⚠ Jev key not set · keeping model` | No key is available. **Set key** opens the secure plugin dialog. |
48
+ | `⚠ Jev: no API key · keeping model` | The active classifier lacks a setting. **Set up** opens the secure plugin dialog. |
49
+ | `⚠ Clef: no account ID · keeping model` | Clef has its API token but no Cloudflare account ID. **Set up** opens the dialog. |
46
50
  | `⚠ Jev timed out · keeping model` | The classifier failed: timed out, unreachable, rejected the key, or paused. |
47
51
  | `○ Router off · keeping …` | Manual mode. **Auto** resumes routing. The footer also shows `router off`. |
48
52
  | `✕ Router unavailable` | Nothing routes: an old Claude Code or leftover v0.8 settings. **Fix** opens the pane. |
@@ -66,12 +70,12 @@ The **Now** tab answers "what runs next turn, and why". The ladder lists the tie
66
70
 
67
71
  The **Tiers** tab edits the routes. In the picture, `medium` was changed to Sonnet 5.5 at `xhigh`: the tier shows **●**, the switch-cost lines now price `medium → high` as a model change, and the diff lists the one `router.json` line that **Save routes** will write. [Edit tiers](#edit-tiers) explains the controls.
68
72
 
69
- | Tab | What it shows |
70
- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------- |
71
- | 1 Now | The current tier, model, and reason; Jev's support for each tier with a **pin** button; the last 30 replies by tier; context and cache. |
72
- | 2 Tiers | The model and effort for each tier, the baseline tier, the cache cost of each step up, and the `router.json` change to save. |
73
- | 3 Tuning | Jev deadline, downgrade votes, payback horizon, credits cap, the Jev key, and the `router.json` path. |
74
- | 4 Usage | Claude-reported cost, context and cache detail, input per reply, quota, and configured-price estimates. |
73
+ | Tab | What it shows |
74
+ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | 1 Now | The current tier, model, and reason; the classifier's support for each tier with a **pin** button; the last 30 replies by tier; context and cache. |
76
+ | 2 Tiers | The model and effort for each tier, the baseline tier, the cache cost of each step up, and the `router.json` change to save. |
77
+ | 3 Tuning | The classifier with its deadline, health, and keys; downgrade votes, payback horizon, and credits cap; the `router.json` path. |
78
+ | 4 Usage | Claude-reported cost, context and cache detail, input per reply, quota, and configured-price estimates. |
75
79
 
76
80
  **Auto** and **Manual: keep /model** stay at the top of every tab. **?** shows what the estimates leave out.
77
81
 
@@ -80,14 +84,14 @@ The **Tiers** tab edits the routes. In the picture, `medium` was changed to Sonn
80
84
  - **Cost** comes from Claude Code's native usage API. If the account is on a plan, a configured list-price estimate is not the subscription cash charge.
81
85
  - **Context** compares the larger available context reading with the routed model's configured window. The router reserves 20% of that window. Values can be unknown when Claude does not provide the needed estimate.
82
86
  - **Cache** reuse is cache-read tokens divided by the last response's input counters.
83
- - **Jev support** is the probability Jev gave each tier on the last classified turn. The line under it compares the support for a switch with the bar the policy required, and shows the estimated switch tax.
87
+ - **Classifier support**, such as **Jev support**, is the probability the classifier gave each tier on the last classified turn. The line under it compares the support for a switch with the bar the policy required, and shows the estimated switch tax.
84
88
  - **Replies** colors each of the last 30 main-conversation replies by the tier that served it. A dot marks a reply the router did not choose, such as one in Manual mode.
85
89
  - **Input per reply** scales the last 30 input sizes from the lowest to the highest reading. It is a scale comparison, not a forecast.
86
90
  - **Cache read benefit** is a configured-price estimate for cached reads before write costs. It is not a measured saving.
87
91
  - **Next-turn difference** compares the candidate with the current model under five-minute and one-hour cache-write scenarios. A negative number means the candidate is estimated to cost less for that request.
88
92
  - **Payback** estimates later turns to recover an initial difference under assumed future cache reads and the last observed output size. It does not guarantee savings.
89
93
 
90
- There is no router-side spend or savings ledger. The pane does not include Jev charges. Claude's native `/cost` is the source for its reported API cost.
94
+ There is no router-side spend or savings ledger. The pane does not include classifier charges. Claude's native `/cost` is the source for its reported API cost.
91
95
 
92
96
  ## Change routing
93
97
 
@@ -115,14 +119,37 @@ A new model ID needs an entry in `router.json` `models` with its price, context
115
119
 
116
120
  ## Tune future decisions
117
121
 
118
- On the **Tuning** tab, pick the values, then select **Save tuning**:
122
+ On the **Tuning** tab, under **Policy**, pick the values, then select **Save tuning**:
119
123
 
120
- - **Jev deadline:** 500, 1,000, 1,500, or 3,000 ms for the total advice attempt, including any retry.
121
124
  - **Votes to go down:** 1, 2, or 3 consecutive votes before a cheaper tier.
122
125
  - **Payback horizon:** 1, 3, 5, or 10 later turns used by the downgrade estimate.
123
126
  - **Credits cap:** $0.50, $1, $2, or $5 for an estimated cold cache write on a `credits` model.
124
127
 
125
- The current turn keeps the settings it started with. A save preserves unrelated `router.json` keys and refuses to write through a symlink. When validation fails, the pane names the setting and leaves the file unchanged. **Set Jev key** or **Edit key** opens Claude Code's secure plugin configuration.
128
+ The current turn keeps the settings it started with. A save preserves unrelated `router.json` keys and refuses to write through a symlink. When validation fails, the pane names the setting and leaves the file unchanged.
129
+
130
+ ## Choose the classifier
131
+
132
+ Router asks one classifier per turn. Three are built in:
133
+
134
+ | Classifier | Service | Credentials | Deadline |
135
+ | ---------- | -------------------------- | ---------------------------------------------- | -------: |
136
+ | Jev | typesafe.ai | Jev API key | 1,500 ms |
137
+ | Clef | Cloudflare Workers AI, 27B | Cloudflare API token and Cloudflare account ID | 3,000 ms |
138
+ | Clef Flash | Cloudflare Workers AI, 9B | Cloudflare API token and Cloudflare account ID | 3,000 ms |
139
+
140
+ ![The Tuning tab: classifier rows with the active one marked, a missing Jev API key with Set up, Undo after a switch, the deadline, health, the receiving host, the credentials each classifier needs, and the policy controls](router-pane-tuning.svg)
141
+
142
+ You can save credentials for all of them; only the active one is asked. The **Classifier** section at the top of the **Tuning** tab has one row per classifier: `◉` marks the active one, followed by its service and whether its credentials are complete. A row that lacks one names it, such as `○ no API token`, and has its own **Set up** button.
143
+
144
+ Select a row to switch. The choice is written to `router.json` at once and applies from the next turn. A line under the rows names the previous classifier with an **Undo** button; it goes when you leave the tab. A turn that is already being classified finishes with the classifier it started with. The new classifier starts with a clean failure count.
145
+
146
+ - **Deadline:** 500, 1,000, 1,500, or 3,000 ms for the active classifier's total advice attempt, including any retry. Each classifier keeps its own deadline, saved at once.
147
+ - **Health** shows recent failures or a pause. **Sends** names the service that receives prompt text.
148
+ - **Credentials** lists what each classifier needs, such as `Jev: API key · Clef, Clef Flash: API token, account ID`. **Edit** opens Claude Code's secure plugin configuration, where you enter them.
149
+
150
+ **Sends** names the service that receives the prompt and recent dialogue. With Clef or Clef Flash that is Cloudflare, not typesafe.ai. Give the Cloudflare token Workers AI permissions only.
151
+
152
+ The routing policy thresholds were tuned against Jev's probabilities. Clef's probabilities have not been compared with Jev's, so the same prompt can switch tiers at a different point. Watch **Classifier support** for a few sessions before you rely on a new classifier.
126
153
 
127
154
  ## Move from v0.8 gateway setup
128
155
 
@@ -143,15 +170,16 @@ To stop routing for a session, run `/router off`. To stop loading the Mod, run `
143
170
 
144
171
  ## Troubleshooting
145
172
 
146
- | Symptom | Cause | Fix |
147
- | ----------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
148
- | Status says the Jev key is missing | The plugin option is unset or unavailable to this process. | Select **Set Jev key** in the pane, or run `/plugin configure router`. Save the option and start a new turn. |
149
- | Route stays on the current model | Jev timed out, failed, is paused, or network policy refused the request. | Read the status band and the pane header. Network policy refusal is not bypassed. |
150
- | `/model` changed but routing stopped | Choosing a model enters Manual mode. | Run `/router auto` to resume automatic routing. |
151
- | Router reports invalid configuration | `router.json` is invalid, or project/local settings redirect the router profile. | Inspect `router.json`, remove project/local `HOME` or `CLAUDE_CONFIG_DIR` overrides, or run the [migration command](configuration.md#convert-a-v08-configuration). |
152
- | Router says old settings need migration | `router.json` still contains v0.8 gateway keys. | Run the [migration command](configuration.md#convert-a-v08-configuration). |
153
- | Band reads `v0.8 gateway settings remain` | The `jev-router[1m]` model or the `127.0.0.1:43170` base URL is still set. | Run `/router`: it lists the keys. Remove them as in the [migration checklist](configuration.md#convert-a-v08-configuration) and restart. |
154
- | Router controls are unavailable | Claude Code is older than 2.1.289. | Update Claude Code. |
155
- | Context reads as unknown | The router lacks a reliable local estimate or current-history measurement. | Keep using the current model, or start a new history with a supported context estimate. |
173
+ | Symptom | Cause | Fix |
174
+ | ------------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
175
+ | Status says `no API key` or `no API token` | The active classifier's plugin option is unset or unavailable to this process. | Select **Set up** in the pane, or run `/plugin configure router`. Save the option and start a new turn. |
176
+ | Status says `no account ID` | Clef or Clef Flash is active without the Cloudflare account ID. | Run `/plugin configure router` and save the Cloudflare account ID. |
177
+ | Route stays on the current model | The classifier timed out, failed, is paused, or network policy refused it. | Read the status band and the pane header. Network policy refusal is not bypassed. |
178
+ | `/model` changed but routing stopped | Choosing a model enters Manual mode. | Run `/router auto` to resume automatic routing. |
179
+ | Router reports invalid configuration | `router.json` is invalid, or project/local settings redirect the router profile. | Inspect `router.json`, remove project/local `HOME` or `CLAUDE_CONFIG_DIR` overrides, or run the [migration command](configuration.md#convert-an-older-routerjson). |
180
+ | Router says old settings need migration | `router.json` still contains v0.8 gateway keys or the 1.1 `jev` section. | Run the [migration command](configuration.md#convert-an-older-routerjson). |
181
+ | Band reads `v0.8 gateway settings remain` | The `jev-router[1m]` model or the `127.0.0.1:43170` base URL is still set. | Run `/router`: it lists the keys. Remove them as in the [migration checklist](configuration.md#convert-a-v08-configuration) and restart. |
182
+ | Router controls are unavailable | Claude Code is older than 2.1.289. | Update Claude Code. |
183
+ | Context reads as unknown | The router lacks a reliable local estimate or current-history measurement. | Keep using the current model, or start a new history with a supported context estimate. |
156
184
 
157
185
  For the internal event flow and network deadline behavior, see [Architecture](architecture.md). For what the test traces do and do not show, see [Evaluation](evaluation.md).
@@ -1,7 +1,20 @@
1
- import { DEFAULTS, effectiveRoutes, loadConfig, TIERS, tuningOf, withRoutes, withTuning } from '../lib/config.mjs';
1
+ import {
2
+ activeClassifier,
3
+ DEFAULTS,
4
+ effectiveRoutes,
5
+ loadConfig,
6
+ MIGRATION_HINT,
7
+ TIERS,
8
+ tuningOf,
9
+ withClassifier,
10
+ withClassifierTimeout,
11
+ withRoutes,
12
+ withTuning,
13
+ } from '../lib/config.mjs';
2
14
  import { clip } from '../lib/facts-pure.mjs';
15
+ import { resolveCredentials } from '../lib/jev-contract.mjs';
3
16
  import { renderBand, switchToast } from '../lib/native-band.mjs';
4
- import { GATEWAY_CLEANUP, GATEWAY_SETTINGS } from '../lib/native-display.mjs';
17
+ import { classifierStatus, GATEWAY_CLEANUP, GATEWAY_SETTINGS, missingCredentials } from '../lib/native-display.mjs';
5
18
  import { NativeJev } from '../lib/native-jev.mjs';
6
19
  import { renderPanel, routeDraftOf } from '../lib/native-panel.mjs';
7
20
  import {
@@ -38,7 +51,7 @@ function initialView(model) {
38
51
  reason: 'ready',
39
52
  error: null,
40
53
  pendingPin: null,
41
- keySet: false,
54
+ credentials: null,
42
55
  contextTokens: null,
43
56
  contextKnown: false,
44
57
  cacheRead: null,
@@ -57,6 +70,7 @@ function initialView(model) {
57
70
  tuning: null,
58
71
  tuningBase: null,
59
72
  routeDraft: null,
73
+ classifierUndo: null,
60
74
  tab: 'now',
61
75
  help: false,
62
76
  notice: null,
@@ -118,12 +132,50 @@ async function setPin($, runtime, tier) {
118
132
  return `${tier} pinned for the next turn and its tool continuations.`;
119
133
  }
120
134
 
121
- async function apiKeyOf($, options) {
122
- return typeof options.typesafe_api_key === 'string' && options.typesafe_api_key.trim()
123
- ? options.typesafe_api_key.trim()
124
- : (await $.env.get('TYPESAFE_API_KEY')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_TYPESAFE_API_KEY'));
135
+ // The environment variables that stand in for a classifier option: its upper-case name, then the one Claude Code
136
+ // exports for a plugin option. Spelled out because $.env.get takes literal names only. Cases: CLASSIFIER_OPTIONS.
137
+ async function envSettingOf($, name) {
138
+ switch (name) {
139
+ case 'typesafe_api_key':
140
+ return (await $.env.get('TYPESAFE_API_KEY')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_TYPESAFE_API_KEY'));
141
+ case 'cloudflare_api_token':
142
+ return (
143
+ (await $.env.get('CLOUDFLARE_API_TOKEN')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_CLOUDFLARE_API_TOKEN'))
144
+ );
145
+ case 'cloudflare_account_id':
146
+ return (
147
+ (await $.env.get('CLOUDFLARE_ACCOUNT_ID')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_CLOUDFLARE_ACCOUNT_ID'))
148
+ );
149
+ default:
150
+ return null;
151
+ }
152
+ }
153
+
154
+ // A plugin option, else its environment variables.
155
+ async function settingOf($, options, name) {
156
+ const value = options[name];
157
+ if (typeof value === 'string' && value.trim()) return value.trim();
158
+ return ((await envSettingOf($, name)) ?? '').trim() || null;
159
+ }
160
+
161
+ // The credentials error, or null, of every configured classifier: the pane lists them all.
162
+ async function credentialsOf($, options, config) {
163
+ const lookup = (name) => settingOf($, options, name);
164
+ return Object.fromEntries(
165
+ await Promise.all(
166
+ Object.entries(config.classifiers).map(async ([id, entry]) => [
167
+ id,
168
+ (await resolveCredentials(entry, lookup)).missing,
169
+ ]),
170
+ ),
171
+ );
125
172
  }
126
173
 
174
+ // Failures and a pause belong to the classifier that earned them.
175
+ const healthOf = (client, id) => ({ ...client.snapshot(), classifier: id });
176
+ // The last classification's readings, cleared when another classifier takes over so no label claims them.
177
+ const CLEARED_READINGS = { adviceMs: null, adviceChoice: null, probabilities: null, estimate: null };
178
+
127
179
  // The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
128
180
  function openKeySettings($) {
129
181
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
@@ -147,14 +199,15 @@ async function saveConfig($, path, change) {
147
199
  }
148
200
  }
149
201
 
150
- function detailText(view) {
202
+ function detailText(config, view) {
203
+ const missing = missingCredentials(view, config.classifier);
151
204
  return [
152
205
  `Router — ${view.mode === 'auto' ? 'Auto' : 'Manual'}`,
153
206
  `Native model: ${view.nativeModel}`,
154
207
  `Selected: ${view.selectedModel ?? 'not selected'}`,
155
208
  `Observed: ${view.actualModel ?? 'no response yet'}`,
156
209
  `Reason: ${view.reason}`,
157
- `Jev: ${view.error ?? (view.keySet ? 'ready' : 'key not set')}`,
210
+ view.error || missing ? classifierStatus(config, view.error ?? missing) : `${activeClassifier(config).label} ready`,
158
211
  `Context: ${view.contextKnown ? `${view.contextTokens} tokens (estimate)` : 'unknown'}`,
159
212
  `Observed cache: ${view.cacheRead ?? 'unknown'} read, ${view.cacheWrite ?? 'unknown'} written tokens`,
160
213
  view.pendingPin ? `Next turn pin: ${view.pendingPin}` : 'No next-turn pin.',
@@ -255,7 +308,13 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
255
308
  export function register(on, options) {
256
309
  let config = loadConfig();
257
310
  const turnConfigs = new Map();
258
- const classifier = new NativeJev();
311
+ // One client per classifier, each with its own breaker and in-flight slot: a turn that started under one
312
+ // classifier finishes with it, and its answer, failures or pause never land on another.
313
+ const clients = new Map();
314
+ const clientOf = (id) => {
315
+ if (!clients.has(id)) clients.set(id, new NativeJev());
316
+ return clients.get(id);
317
+ };
259
318
  const prompts = new Map();
260
319
  const decisions = new Map();
261
320
  const controllers = new Set();
@@ -274,7 +333,8 @@ export function register(on, options) {
274
333
  config = await loadNativeConfig($);
275
334
  const existing = await readView($, runtime);
276
335
  runtime.view = existing;
277
- classifier.restore(existing.health);
336
+ const sameClassifier = existing.health?.classifier === config.classifier;
337
+ clientOf(config.classifier).restore(sameClassifier ? existing.health : null);
278
338
  const base = await $.env.get('ANTHROPIC_BASE_URL');
279
339
  const version = await $.session.version().catch(() => null);
280
340
  const supported = supportedVersion(version?.version);
@@ -288,7 +348,9 @@ export function register(on, options) {
288
348
  mode: await modeOf($, runtime, model === baselineModel ? 'auto' : 'manual'),
289
349
  phase: gateway || !supported ? 'unavailable' : 'ready',
290
350
  error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
291
- keySet: Boolean(await apiKeyOf($, options)),
351
+ ...(sameClassifier ? {} : CLEARED_READINGS),
352
+ credentials: await credentialsOf($, options, config),
353
+ health: healthOf(clientOf(config.classifier), config.classifier),
292
354
  configPath: config.nativePath,
293
355
  tuning: null,
294
356
  tuningBase: null,
@@ -297,7 +359,7 @@ export function register(on, options) {
297
359
  } catch (error) {
298
360
  await updateView($, runtime, {
299
361
  phase: 'unavailable',
300
- error: error.message?.startsWith('router.json uses gateway settings;')
362
+ error: error.message?.endsWith(MIGRATION_HINT)
301
363
  ? 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path'
302
364
  : 'invalid router configuration',
303
365
  });
@@ -333,7 +395,7 @@ export function register(on, options) {
333
395
  return { text: TIERS.includes(tier) ? await setPin($, runtime, tier) : `Choose ${TIERS.join(', ')}.` };
334
396
  const storedView = await readView($, runtime);
335
397
  const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
336
- if (!(await $.session.surfaces()).length) return { text: detailText(view) };
398
+ if (!(await $.session.surfaces()).length) return { text: detailText(config, view) };
337
399
  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
338
400
  return {};
339
401
  });
@@ -384,7 +446,7 @@ export function register(on, options) {
384
446
  const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
385
447
  try {
386
448
  const pin = view.pendingPin;
387
- const apiKey = await apiKeyOf($, options);
449
+ const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, options, name));
388
450
  const messages = await $.session.messages({ as: 'api' });
389
451
  if (!(await live())) return null;
390
452
  const facts = nativeFacts(cfg, loop, {
@@ -399,16 +461,17 @@ export function register(on, options) {
399
461
  activeTurnId: e.turnId,
400
462
  nativeModel,
401
463
  pendingPin: null,
402
- keySet: Boolean(apiKey),
464
+ credentials: { ...runtime.view?.credentials, [cfg.classifier]: credentials.missing },
403
465
  });
404
466
  const adviceStarted = Date.now();
405
467
  const result = pin
406
468
  ? { advice: null, error: null }
407
- : await classifier.ask({
469
+ : await clientOf(cfg.classifier).ask({
408
470
  request: (url, init) => $.http.fetch(url, init),
409
471
  sleep: (ms, args) => $.clock.sleep(ms, args),
410
472
  config: cfg,
411
- apiKey,
473
+ apiKey: credentials.apiKey,
474
+ endpoint: credentials.endpoint,
412
475
  prompt: facts.prompt,
413
476
  turns: facts.turns,
414
477
  signal: controller.signal,
@@ -434,7 +497,7 @@ export function register(on, options) {
434
497
  // Manual, /clear and turn completion abort the controller; one may land during the write.
435
498
  if (!written.isSet || controller.signal.aborted) return null;
436
499
  if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
437
- $.ui.toast(switchToast(previous, selected.decision, selected.decision.estimate));
500
+ $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
438
501
  await updateView($, runtime, {
439
502
  phase: 'routed',
440
503
  selectedModel: selected.decision.model,
@@ -442,16 +505,24 @@ export function register(on, options) {
442
505
  tier: selected.decision.tier,
443
506
  effort: selected.decision.effort,
444
507
  reason: selected.decision.reason,
445
- error: result.error,
446
- health: classifier.snapshot(),
447
508
  contextTokens: context.tokens,
448
509
  contextKnown: context.known,
449
- adviceMs:
450
- pin || ['missing-key', 'busy', 'paused'].includes(result.error) ? null : Date.now() - adviceStarted,
451
- adviceChoice: result.advice?.choice ?? null,
452
- probabilities: result.advice?.probabilities ?? null,
453
- estimate: selected.decision.estimate ?? null,
454
510
  comparison: selected.decision.comparison,
511
+ // A turn that started before a classifier switch routes on its own classifier's answer, but the
512
+ // pane now labels the new one: its readings stay off the view.
513
+ ...(cfg.classifier === config.classifier
514
+ ? {
515
+ error: result.error,
516
+ health: healthOf(clientOf(cfg.classifier), cfg.classifier),
517
+ adviceMs:
518
+ pin || ['missing-key', 'missing-account', 'busy', 'paused'].includes(result.error)
519
+ ? null
520
+ : Date.now() - adviceStarted,
521
+ adviceChoice: result.advice?.choice ?? null,
522
+ probabilities: result.advice?.probabilities ?? null,
523
+ estimate: selected.decision.estimate ?? null,
524
+ }
525
+ : {}),
455
526
  });
456
527
  return { loop: selected, version: written.version };
457
528
  } finally {
@@ -545,8 +616,8 @@ export function register(on, options) {
545
616
  runtime.view = {
546
617
  ...initialView(runtime.view?.nativeModel ?? ''),
547
618
  mode: 'auto',
548
- keySet: runtime.view?.keySet ?? false,
549
- health: classifier.snapshot(),
619
+ credentials: runtime.view?.credentials ?? null,
620
+ health: healthOf(clientOf(config.classifier), config.classifier),
550
621
  configPath: config.nativePath,
551
622
  phase: runtime.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
552
623
  error: runtime.view?.phase === 'unavailable' ? runtime.view.error : null,
@@ -621,12 +692,36 @@ export function register(on, options) {
621
692
  notice: null,
622
693
  });
623
694
  };
695
+ // Every pane save adopts the file as written, which may name another classifier than before: a hand edit
696
+ // meanwhile, or a row press. Then the new classifier starts clean and the old one's readings leave the view;
697
+ // an unavailable reason stays.
698
+ const adopt = async (loaded) => {
699
+ const switched = loaded.classifier !== config.classifier;
700
+ config = loaded;
701
+ if (!switched) return {};
702
+ clientOf(config.classifier).restore(null);
703
+ const current = runtime.view ?? view;
704
+ return {
705
+ ...CLEARED_READINGS,
706
+ error: current.phase === 'unavailable' ? current.error : null,
707
+ credentials: await credentialsOf($, options, config),
708
+ health: healthOf(clientOf(config.classifier), config.classifier),
709
+ };
710
+ };
624
711
  const save = async (change, saved) => {
625
712
  const result = await saveConfig($, config.nativePath, change);
626
713
  if (result.error) return updateView($, runtime, { notice: result.error });
627
- config = result.config;
628
- return updateView($, runtime, saved(config));
714
+ const reset = await adopt(result.config);
715
+ return updateView($, runtime, { ...reset, ...saved(config) });
629
716
  };
717
+ // A classifier choice applies at once; `undo` is the one Undo returns to, null after an Undo.
718
+ const activateClassifier = (id, undo) =>
719
+ !id || id === config.classifier || !Object.hasOwn(config.classifiers, id)
720
+ ? undefined
721
+ : save(
722
+ (file) => withClassifier(file, id),
723
+ () => ({ classifierUndo: undo, notice: null }),
724
+ );
630
725
  return renderPanel(
631
726
  elements,
632
727
  config,
@@ -634,7 +729,7 @@ export function register(on, options) {
634
729
  usage,
635
730
  {
636
731
  mode: (mode) => changeMode($, runtime, mode),
637
- tab: (tab) => updateView($, runtime, { tab, notice: null }),
732
+ tab: (tab) => updateView($, runtime, { tab, notice: null, classifierUndo: null }),
638
733
  help: () => updateView($, runtime, { help: !view.help }),
639
734
  pin: async (tier) => {
640
735
  await updateView($, runtime, { notice: await setPin($, runtime, tier) });
@@ -694,6 +789,15 @@ export function register(on, options) {
694
789
  );
695
790
  },
696
791
  resetTuning: () => updateView($, runtime, { tuning: null, tuningBase: null, notice: null }),
792
+ classifier: (id) => activateClassifier(id, config.classifier),
793
+ undoClassifier: () => activateClassifier((runtime.view ?? view).classifierUndo, null),
794
+ classifierTimeout: (timeoutMs) =>
795
+ save(
796
+ (file) => withClassifierTimeout(file, config.classifier, timeoutMs),
797
+ (saved) => ({
798
+ notice: `Saved. ${activeClassifier(saved).label} waits ${timeoutMs} ms from the next turn.`,
799
+ }),
800
+ ),
697
801
  },
698
802
  { modelOptions },
699
803
  );