@alexeiled/claude-router 1.1.1 → 1.3.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.
- package/.claude-plugin/plugin.json +15 -4
- package/CHANGELOG.md +33 -0
- package/README.md +9 -9
- package/docs/architecture.md +25 -23
- package/docs/configuration.md +76 -22
- package/docs/native-router.md +22 -17
- package/docs/router-band.svg +14 -14
- package/docs/router-pane-classifier.svg +45 -0
- package/docs/router-pane-now.svg +6 -5
- package/docs/router-pane-routing.svg +81 -0
- package/docs/user-guide.md +72 -35
- package/hooks/native-router.mjs +263 -56
- package/lib/config.mjs +116 -30
- package/lib/jev-contract.mjs +25 -6
- package/lib/native-band.mjs +31 -14
- package/lib/native-display.mjs +34 -3
- package/lib/native-jev.mjs +7 -5
- package/lib/native-panel.mjs +202 -134
- package/package.json +2 -2
- package/scripts/migrate-config.mjs +14 -3
- package/types/index.d.ts +6 -4
- package/docs/router-pane-tiers.svg +0 -62
package/hooks/native-router.mjs
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
|
-
import {
|
|
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
|
-
import { renderPanel, routeDraftOf } from '../lib/native-panel.mjs';
|
|
19
|
+
import { renderPanel, routeDraftOf, routingChanges } from '../lib/native-panel.mjs';
|
|
7
20
|
import {
|
|
8
21
|
chooseRoute,
|
|
9
22
|
continueRoute,
|
|
@@ -38,7 +51,7 @@ function initialView(model) {
|
|
|
38
51
|
reason: 'ready',
|
|
39
52
|
error: null,
|
|
40
53
|
pendingPin: null,
|
|
41
|
-
|
|
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
|
+
lastWrite: null,
|
|
60
74
|
tab: 'now',
|
|
61
75
|
help: false,
|
|
62
76
|
notice: null,
|
|
@@ -95,6 +109,13 @@ async function updateView($, runtime, patch) {
|
|
|
95
109
|
await $.state.set(VIEW, runtime.view);
|
|
96
110
|
}
|
|
97
111
|
|
|
112
|
+
// A notice answers the last press in the pane, so the pane opens without one; the last write keeps its Undo in the
|
|
113
|
+
// status bar.
|
|
114
|
+
async function openPane($, runtime) {
|
|
115
|
+
await updateView($, runtime, { notice: null });
|
|
116
|
+
await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
|
|
117
|
+
}
|
|
118
|
+
|
|
98
119
|
async function changeMode($, runtime, mode) {
|
|
99
120
|
const view = runtime.view ?? (await readView($, runtime));
|
|
100
121
|
for (const controller of runtime.controllers) controller.abort();
|
|
@@ -118,17 +139,100 @@ async function setPin($, runtime, tier) {
|
|
|
118
139
|
return `${tier} pinned for the next turn and its tool continuations.`;
|
|
119
140
|
}
|
|
120
141
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
142
|
+
// The environment variables that stand in for a classifier option: its upper-case name, then the one Claude Code
|
|
143
|
+
// exports for a plugin option. Spelled out because $.env.get takes literal names only. Cases: CLASSIFIER_OPTIONS.
|
|
144
|
+
async function envSettingOf($, name) {
|
|
145
|
+
switch (name) {
|
|
146
|
+
case 'typesafe_api_key':
|
|
147
|
+
return (await $.env.get('TYPESAFE_API_KEY')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_TYPESAFE_API_KEY'));
|
|
148
|
+
case 'cloudflare_api_token':
|
|
149
|
+
return (
|
|
150
|
+
(await $.env.get('CLOUDFLARE_API_TOKEN')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_CLOUDFLARE_API_TOKEN'))
|
|
151
|
+
);
|
|
152
|
+
case 'cloudflare_account_id':
|
|
153
|
+
return (
|
|
154
|
+
(await $.env.get('CLOUDFLARE_ACCOUNT_ID')) || (await $.env.get('CLAUDE_PLUGIN_OPTION_CLOUDFLARE_ACCOUNT_ID'))
|
|
155
|
+
);
|
|
156
|
+
default:
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// A plugin option, else its environment variables.
|
|
162
|
+
async function settingOf($, options, name) {
|
|
163
|
+
const value = options[name];
|
|
164
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
165
|
+
return ((await envSettingOf($, name)) ?? '').trim() || null;
|
|
125
166
|
}
|
|
126
167
|
|
|
168
|
+
// The credentials error, or null, of every configured classifier: the pane lists them all.
|
|
169
|
+
async function credentialsOf($, options, config) {
|
|
170
|
+
const lookup = (name) => settingOf($, options, name);
|
|
171
|
+
return Object.fromEntries(
|
|
172
|
+
await Promise.all(
|
|
173
|
+
Object.entries(config.classifiers).map(async ([id, entry]) => [
|
|
174
|
+
id,
|
|
175
|
+
(await resolveCredentials(entry, lookup)).missing,
|
|
176
|
+
]),
|
|
177
|
+
),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
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
|
+
|
|
127
186
|
// The host refuses $.command.run from a hook the turn is holding, so the secure key dialog opens from a timer.
|
|
128
187
|
function openKeySettings($) {
|
|
129
188
|
$.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
|
|
130
189
|
}
|
|
131
190
|
|
|
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]];
|
|
232
|
+
}
|
|
233
|
+
return next;
|
|
234
|
+
}
|
|
235
|
+
|
|
132
236
|
// Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
|
|
133
237
|
// line for the pane; a failure leaves the file untouched.
|
|
134
238
|
async function saveConfig($, path, change) {
|
|
@@ -147,14 +251,15 @@ async function saveConfig($, path, change) {
|
|
|
147
251
|
}
|
|
148
252
|
}
|
|
149
253
|
|
|
150
|
-
function detailText(view) {
|
|
254
|
+
function detailText(config, view) {
|
|
255
|
+
const missing = missingCredentials(view, config.classifier);
|
|
151
256
|
return [
|
|
152
257
|
`Router — ${view.mode === 'auto' ? 'Auto' : 'Manual'}`,
|
|
153
258
|
`Native model: ${view.nativeModel}`,
|
|
154
259
|
`Selected: ${view.selectedModel ?? 'not selected'}`,
|
|
155
260
|
`Observed: ${view.actualModel ?? 'no response yet'}`,
|
|
156
261
|
`Reason: ${view.reason}`,
|
|
157
|
-
|
|
262
|
+
view.error || missing ? classifierStatus(config, view.error ?? missing) : `${activeClassifier(config).label} ready`,
|
|
158
263
|
`Context: ${view.contextKnown ? `${view.contextTokens} tokens (estimate)` : 'unknown'}`,
|
|
159
264
|
`Observed cache: ${view.cacheRead ?? 'unknown'} read, ${view.cacheWrite ?? 'unknown'} written tokens`,
|
|
160
265
|
view.pendingPin ? `Next turn pin: ${view.pendingPin}` : 'No next-turn pin.',
|
|
@@ -255,7 +360,13 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, config,
|
|
|
255
360
|
export function register(on, options) {
|
|
256
361
|
let config = loadConfig();
|
|
257
362
|
const turnConfigs = new Map();
|
|
258
|
-
|
|
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);
|
|
369
|
+
};
|
|
259
370
|
const prompts = new Map();
|
|
260
371
|
const decisions = new Map();
|
|
261
372
|
const controllers = new Set();
|
|
@@ -274,7 +385,8 @@ export function register(on, options) {
|
|
|
274
385
|
config = await loadNativeConfig($);
|
|
275
386
|
const existing = await readView($, runtime);
|
|
276
387
|
runtime.view = existing;
|
|
277
|
-
|
|
388
|
+
const sameClassifier = existing.health?.classifier === config.classifier;
|
|
389
|
+
clientOf(config.classifier).restore(sameClassifier ? existing.health : null);
|
|
278
390
|
const base = await $.env.get('ANTHROPIC_BASE_URL');
|
|
279
391
|
const version = await $.session.version().catch(() => null);
|
|
280
392
|
const supported = supportedVersion(version?.version);
|
|
@@ -288,16 +400,20 @@ export function register(on, options) {
|
|
|
288
400
|
mode: await modeOf($, runtime, model === baselineModel ? 'auto' : 'manual'),
|
|
289
401
|
phase: gateway || !supported ? 'unavailable' : 'ready',
|
|
290
402
|
error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
|
|
291
|
-
|
|
403
|
+
...(sameClassifier ? {} : CLEARED_READINGS),
|
|
404
|
+
credentials: await credentialsOf($, options, config),
|
|
405
|
+
health: healthOf(clientOf(config.classifier), config.classifier),
|
|
292
406
|
configPath: config.nativePath,
|
|
293
407
|
tuning: null,
|
|
294
408
|
tuningBase: null,
|
|
409
|
+
routeDraft: null,
|
|
410
|
+
lastWrite: null,
|
|
295
411
|
bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
|
|
296
412
|
});
|
|
297
413
|
} catch (error) {
|
|
298
414
|
await updateView($, runtime, {
|
|
299
415
|
phase: 'unavailable',
|
|
300
|
-
error: error.message?.
|
|
416
|
+
error: error.message?.endsWith(MIGRATION_HINT)
|
|
301
417
|
? 'router.json needs migration; run the plugin scripts/migrate-config.mjs with your router.json path'
|
|
302
418
|
: 'invalid router configuration',
|
|
303
419
|
});
|
|
@@ -333,8 +449,8 @@ export function register(on, options) {
|
|
|
333
449
|
return { text: TIERS.includes(tier) ? await setPin($, runtime, tier) : `Choose ${TIERS.join(', ')}.` };
|
|
334
450
|
const storedView = await readView($, runtime);
|
|
335
451
|
const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
|
|
336
|
-
if (!(await $.session.surfaces()).length) return { text: detailText(view) };
|
|
337
|
-
await
|
|
452
|
+
if (!(await $.session.surfaces()).length) return { text: detailText(config, view) };
|
|
453
|
+
await openPane($, runtime);
|
|
338
454
|
return {};
|
|
339
455
|
});
|
|
340
456
|
|
|
@@ -384,7 +500,7 @@ export function register(on, options) {
|
|
|
384
500
|
const live = async () => !controller.signal.aborted && (await $.session.id()) === sessionId;
|
|
385
501
|
try {
|
|
386
502
|
const pin = view.pendingPin;
|
|
387
|
-
const
|
|
503
|
+
const credentials = await resolveCredentials(activeClassifier(cfg), (name) => settingOf($, options, name));
|
|
388
504
|
const messages = await $.session.messages({ as: 'api' });
|
|
389
505
|
if (!(await live())) return null;
|
|
390
506
|
const facts = nativeFacts(cfg, loop, {
|
|
@@ -399,16 +515,17 @@ export function register(on, options) {
|
|
|
399
515
|
activeTurnId: e.turnId,
|
|
400
516
|
nativeModel,
|
|
401
517
|
pendingPin: null,
|
|
402
|
-
|
|
518
|
+
credentials: { ...runtime.view?.credentials, [cfg.classifier]: credentials.missing },
|
|
403
519
|
});
|
|
404
520
|
const adviceStarted = Date.now();
|
|
405
521
|
const result = pin
|
|
406
522
|
? { advice: null, error: null }
|
|
407
|
-
: await classifier.ask({
|
|
523
|
+
: await clientOf(cfg.classifier).ask({
|
|
408
524
|
request: (url, init) => $.http.fetch(url, init),
|
|
409
525
|
sleep: (ms, args) => $.clock.sleep(ms, args),
|
|
410
526
|
config: cfg,
|
|
411
|
-
apiKey,
|
|
527
|
+
apiKey: credentials.apiKey,
|
|
528
|
+
endpoint: credentials.endpoint,
|
|
412
529
|
prompt: facts.prompt,
|
|
413
530
|
turns: facts.turns,
|
|
414
531
|
signal: controller.signal,
|
|
@@ -434,7 +551,7 @@ export function register(on, options) {
|
|
|
434
551
|
// Manual, /clear and turn completion abort the controller; one may land during the write.
|
|
435
552
|
if (!written.isSet || controller.signal.aborted) return null;
|
|
436
553
|
if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
|
|
437
|
-
$.ui.toast(switchToast(previous, selected.decision, selected.decision.estimate));
|
|
554
|
+
$.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
|
|
438
555
|
await updateView($, runtime, {
|
|
439
556
|
phase: 'routed',
|
|
440
557
|
selectedModel: selected.decision.model,
|
|
@@ -442,16 +559,24 @@ export function register(on, options) {
|
|
|
442
559
|
tier: selected.decision.tier,
|
|
443
560
|
effort: selected.decision.effort,
|
|
444
561
|
reason: selected.decision.reason,
|
|
445
|
-
error: result.error,
|
|
446
|
-
health: classifier.snapshot(),
|
|
447
562
|
contextTokens: context.tokens,
|
|
448
563
|
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
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
|
+
: {}),
|
|
455
580
|
});
|
|
456
581
|
return { loop: selected, version: written.version };
|
|
457
582
|
} finally {
|
|
@@ -545,8 +670,8 @@ export function register(on, options) {
|
|
|
545
670
|
runtime.view = {
|
|
546
671
|
...initialView(runtime.view?.nativeModel ?? ''),
|
|
547
672
|
mode: 'auto',
|
|
548
|
-
|
|
549
|
-
health: classifier.
|
|
673
|
+
credentials: runtime.view?.credentials ?? null,
|
|
674
|
+
health: healthOf(clientOf(config.classifier), config.classifier),
|
|
550
675
|
configPath: config.nativePath,
|
|
551
676
|
phase: runtime.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
|
|
552
677
|
error: runtime.view?.phase === 'unavailable' ? runtime.view.error : null,
|
|
@@ -580,7 +705,6 @@ export function register(on, options) {
|
|
|
580
705
|
const elements = $.ui.resolve(e);
|
|
581
706
|
const { Box } = elements;
|
|
582
707
|
const usage = await $.session.usage().catch(() => null);
|
|
583
|
-
const openPane = () => $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
|
|
584
708
|
if (e.component === 'AbovePrompt') {
|
|
585
709
|
if (e.props.hasSurvey) return next(e);
|
|
586
710
|
return Box({
|
|
@@ -594,7 +718,7 @@ export function register(on, options) {
|
|
|
594
718
|
usage,
|
|
595
719
|
{ columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
|
|
596
720
|
{
|
|
597
|
-
open: openPane,
|
|
721
|
+
open: () => openPane($, runtime),
|
|
598
722
|
mode: (mode) => changeMode($, runtime, mode),
|
|
599
723
|
pin: async (tier) => $.ui.toast(await setPin($, runtime, tier)),
|
|
600
724
|
unpin: () => updateView($, runtime, { pendingPin: null }),
|
|
@@ -621,11 +745,65 @@ export function register(on, options) {
|
|
|
621
745
|
notice: null,
|
|
622
746
|
});
|
|
623
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
|
+
};
|
|
624
776
|
const save = async (change, saved) => {
|
|
625
777
|
const result = await saveConfig($, config.nativePath, change);
|
|
626
778
|
if (result.error) return updateView($, runtime, { notice: result.error });
|
|
627
|
-
|
|
628
|
-
|
|
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
|
+
);
|
|
629
807
|
};
|
|
630
808
|
return renderPanel(
|
|
631
809
|
elements,
|
|
@@ -659,41 +837,70 @@ export function register(on, options) {
|
|
|
659
837
|
const draft = routeDraftOf(config, runtime.view ?? view);
|
|
660
838
|
await updateView($, runtime, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
|
|
661
839
|
},
|
|
662
|
-
|
|
663
|
-
const
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
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 },
|
|
668
856
|
);
|
|
669
857
|
},
|
|
670
|
-
|
|
858
|
+
discardRouting: () =>
|
|
859
|
+
updateView($, runtime, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
|
|
671
860
|
resetRoutes: () =>
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
861
|
+
loadDefaults(
|
|
862
|
+
{
|
|
863
|
+
routeDraft: {
|
|
864
|
+
...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
|
|
865
|
+
base: routeDraftOf(config, {}).base,
|
|
866
|
+
},
|
|
676
867
|
},
|
|
677
|
-
|
|
678
|
-
|
|
868
|
+
'route',
|
|
869
|
+
),
|
|
679
870
|
tune: (key, value) =>
|
|
680
871
|
updateView($, runtime, {
|
|
681
872
|
tuning: { ...(runtime.view ?? view).tuning, [key]: value },
|
|
682
873
|
tuningBase: (runtime.view ?? view).tuningBase ?? tuningOf(config),
|
|
683
874
|
notice: null,
|
|
684
875
|
}),
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
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;
|
|
691
899
|
return save(
|
|
692
|
-
(file) =>
|
|
693
|
-
() => ({
|
|
900
|
+
(file) => restored(file, last.leaves),
|
|
901
|
+
() => ({ lastWrite: null, notice: `Undid: ${last.label}.` }),
|
|
694
902
|
);
|
|
695
903
|
},
|
|
696
|
-
resetTuning: () => updateView($, runtime, { tuning: null, tuningBase: null, notice: null }),
|
|
697
904
|
},
|
|
698
905
|
{ modelOptions },
|
|
699
906
|
);
|