@alexeiled/claude-router 1.2.0 → 1.3.1

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.
@@ -16,7 +16,7 @@ import { resolveCredentials } from '../lib/jev-contract.mjs';
16
16
  import { renderBand, switchToast } from '../lib/native-band.mjs';
17
17
  import { classifierStatus, GATEWAY_CLEANUP, GATEWAY_SETTINGS, missingCredentials } from '../lib/native-display.mjs';
18
18
  import { NativeJev } from '../lib/native-jev.mjs';
19
- import { renderPanel, routeDraftOf } from '../lib/native-panel.mjs';
19
+ import { renderPanel, routeDraftOf, routingChanges } from '../lib/native-panel.mjs';
20
20
  import {
21
21
  chooseRoute,
22
22
  continueRoute,
@@ -70,7 +70,7 @@ function initialView(model) {
70
70
  tuning: null,
71
71
  tuningBase: null,
72
72
  routeDraft: null,
73
- classifierUndo: null,
73
+ lastWrite: null,
74
74
  tab: 'now',
75
75
  help: false,
76
76
  notice: null,
@@ -109,6 +109,13 @@ async function updateView($, runtime, patch) {
109
109
  await $.state.set(VIEW, runtime.view);
110
110
  }
111
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
+
112
119
  async function changeMode($, runtime, mode) {
113
120
  const view = runtime.view ?? (await readView($, runtime));
114
121
  for (const controller of runtime.controllers) controller.abort();
@@ -181,6 +188,51 @@ function openKeySettings($) {
181
188
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
182
189
  }
183
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
+
184
236
  // Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
185
237
  // line for the pane; a failure leaves the file untouched.
186
238
  async function saveConfig($, path, change) {
@@ -354,6 +406,8 @@ export function register(on, options) {
354
406
  configPath: config.nativePath,
355
407
  tuning: null,
356
408
  tuningBase: null,
409
+ routeDraft: null,
410
+ lastWrite: null,
357
411
  bandDetail: (await $.store.get(BAND_DETAIL).catch(() => false)) === true,
358
412
  });
359
413
  } catch (error) {
@@ -396,7 +450,7 @@ export function register(on, options) {
396
450
  const storedView = await readView($, runtime);
397
451
  const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
398
452
  if (!(await $.session.surfaces()).length) return { text: detailText(config, view) };
399
- await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
453
+ await openPane($, runtime);
400
454
  return {};
401
455
  });
402
456
 
@@ -651,7 +705,6 @@ export function register(on, options) {
651
705
  const elements = $.ui.resolve(e);
652
706
  const { Box } = elements;
653
707
  const usage = await $.session.usage().catch(() => null);
654
- const openPane = () => $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true });
655
708
  if (e.component === 'AbovePrompt') {
656
709
  if (e.props.hasSurvey) return next(e);
657
710
  return Box({
@@ -665,7 +718,7 @@ export function register(on, options) {
665
718
  usage,
666
719
  { columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
667
720
  {
668
- open: openPane,
721
+ open: () => openPane($, runtime),
669
722
  mode: (mode) => changeMode($, runtime, mode),
670
723
  pin: async (tier) => $.ui.toast(await setPin($, runtime, tier)),
671
724
  unpin: () => updateView($, runtime, { pendingPin: null }),
@@ -708,20 +761,50 @@ export function register(on, options) {
708
761
  health: healthOf(clientOf(config.classifier), config.classifier),
709
762
  };
710
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
+ };
711
776
  const save = async (change, saved) => {
712
777
  const result = await saveConfig($, config.nativePath, change);
713
778
  if (result.error) return updateView($, runtime, { notice: result.error });
779
+ const drafts = runtime.view ?? view;
714
780
  const reset = await adopt(result.config);
715
- return updateView($, runtime, { ...reset, ...saved(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
+ );
716
807
  };
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
- );
725
808
  return renderPanel(
726
809
  elements,
727
810
  config,
@@ -729,7 +812,7 @@ export function register(on, options) {
729
812
  usage,
730
813
  {
731
814
  mode: (mode) => changeMode($, runtime, mode),
732
- tab: (tab) => updateView($, runtime, { tab, notice: null, classifierUndo: null }),
815
+ tab: (tab) => updateView($, runtime, { tab, notice: null }),
733
816
  help: () => updateView($, runtime, { help: !view.help }),
734
817
  pin: async (tier) => {
735
818
  await updateView($, runtime, { notice: await setPin($, runtime, tier) });
@@ -754,50 +837,70 @@ export function register(on, options) {
754
837
  const draft = routeDraftOf(config, runtime.view ?? view);
755
838
  await updateView($, runtime, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
756
839
  },
757
- saveRoutes: async () => {
758
- const draft = (runtime.view ?? view).routeDraft;
759
- if (!draft) return updateView($, runtime, { notice: 'No route changes to save.' });
760
- return save(
761
- (file) => withRoutes(file, draft),
762
- () => ({ routeDraft: null, notice: 'Saved routes. They apply from the next turn.' }),
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 },
763
856
  );
764
857
  },
765
- discardRoutes: () => updateView($, runtime, { routeDraft: null, notice: null }),
858
+ discardRouting: () =>
859
+ updateView($, runtime, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
766
860
  resetRoutes: () =>
767
- updateView($, runtime, {
768
- routeDraft: {
769
- ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
770
- base: routeDraftOf(config, {}).base,
861
+ loadDefaults(
862
+ {
863
+ routeDraft: {
864
+ ...structuredClone({ routes: DEFAULTS.routes, baselineTier: DEFAULTS.baselineTier }),
865
+ base: routeDraftOf(config, {}).base,
866
+ },
771
867
  },
772
- notice: 'Defaults loaded. Save routes to remove your overrides from router.json.',
773
- }),
868
+ 'route',
869
+ ),
774
870
  tune: (key, value) =>
775
871
  updateView($, runtime, {
776
872
  tuning: { ...(runtime.view ?? view).tuning, [key]: value },
777
873
  tuningBase: (runtime.view ?? view).tuningBase ?? tuningOf(config),
778
874
  notice: null,
779
875
  }),
780
- saveTuning: async () => {
781
- const current = runtime.view ?? view;
782
- const base = current.tuningBase ?? tuningOf(config);
783
- const draft = { ...base, ...current.tuning };
784
- if (Object.keys(base).every((key) => draft[key] === base[key]))
785
- return updateView($, runtime, { notice: 'No tuning changes to save.' });
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;
786
899
  return save(
787
- (file) => withTuning(file, draft, base),
788
- () => ({ tuning: null, tuningBase: null, notice: 'Saved. New tuning applies to future turns.' }),
900
+ (file) => restored(file, last.leaves),
901
+ () => ({ lastWrite: null, notice: `Undid: ${last.label}.` }),
789
902
  );
790
903
  },
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
- ),
801
904
  },
802
905
  { modelOptions },
803
906
  );
package/lib/config.mjs CHANGED
@@ -6,15 +6,17 @@ export const DEFAULTS = {
6
6
  baselineTier: 'low',
7
7
  // Sonnet 5.5 is the worker at `low`, at the effort the user picked. `medium` is Opus 5.5 at medium effort, a balance
8
8
  // of speed and cost per task; `high` is Opus 5.5 at xhigh, the strongest setting this router asks for.
9
+ // `micro` is Haiku 5.5 at low effort: Claude Code owns the thinking field, so low effort is the least thinking the router can ask for.
9
10
  // These are routing defaults, not a claim of equal model quality.
10
11
  routes: {
11
12
  high: { model: 'opus', effort: 'xhigh' },
12
13
  medium: { model: 'opus', effort: 'medium' },
13
14
  low: { model: 'sonnet' },
14
- micro: { model: 'haiku' },
15
+ micro: { model: 'haiku', effort: 'low' },
15
16
  },
16
17
  // `id` selects the native model. List prices in USD per million tokens; `cacheRead` is absolute,
17
- // not a multiplier (Opus 5.5 reads at 0.05x input, the rest at the standard 0.1x). A price change must also change
18
+ // not a multiplier (Opus 5.5 reads at 0.05x input, the rest at the standard 0.1x). Haiku 5.5 lists the rates for
19
+ // prompts up to 100k tokens; above that Anthropic charges 5x on input, output and cache read, so estimates run low there. A price change must also change
18
20
  // test/fixtures/list-prices.json, with its source and date. `output` feeds the shadow estimate and the downgrade tax.
19
21
  // `efforts` lists what the model accepts; an empty list means no effort field and no adaptive thinking. A change
20
22
  // must also change test/fixtures/effort-support.json, from a new probe against the real API.
@@ -38,13 +40,13 @@ export const DEFAULTS = {
38
40
  efforts: EFFORTS,
39
41
  },
40
42
  haiku: {
41
- id: 'claude-haiku-4-5',
42
- input: 1,
43
- output: 5,
44
- cacheRead: 0.1,
45
- contextWindow: 200_000,
43
+ id: 'claude-haiku-5-5',
44
+ input: 0.1,
45
+ output: 0.5,
46
+ cacheRead: 0.01,
47
+ contextWindow: 1_000_000,
46
48
  billing: 'plan',
47
- efforts: [],
49
+ efforts: EFFORTS,
48
50
  },
49
51
  },
50
52
  cache: {
@@ -202,11 +204,17 @@ export function tuningOf(config) {
202
204
  );
203
205
  }
204
206
 
205
- // The router.json `file` with only the tuning values the person changed in `draft` against `saved`.
207
+ // The router.json `file` with only the tuning values the person changed in `draft` against `saved`. A value equal to
208
+ // the default is written as no key, and a section left empty is dropped, as for routes and deadlines.
206
209
  export function withTuning(file, draft, saved) {
207
210
  let next = file;
208
- for (const [key, [section, field]] of Object.entries(TUNING_FIELDS))
209
- if (draft[key] !== saved[key]) next = { ...next, [section]: { ...next[section], [field]: draft[key] } };
211
+ for (const [key, [section, field]] of Object.entries(TUNING_FIELDS)) {
212
+ if (draft[key] === saved[key]) continue;
213
+ const { [field]: _, ...kept } = next[section] ?? {};
214
+ const entry = draft[key] === DEFAULTS[section][field] ? kept : { ...kept, [field]: draft[key] };
215
+ const { [section]: __, ...rest } = next;
216
+ next = Object.keys(entry).length ? { ...rest, [section]: entry } : rest;
217
+ }
210
218
  return next;
211
219
  }
212
220