@bizzywork/routing 0.4.5 → 0.5.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/README.md CHANGED
@@ -20,7 +20,13 @@ npx @bizzywork/routing help # every command and option
20
20
 
21
21
  The Claude Code plugin and the omp extension start the server themselves; when one already runs, the Codex service leaves it.
22
22
 
23
- On a terminal, `install` asks once for your Bizzy routing key and saves it to `~/.bizzy/routing/.env` (mode 0600, never printed). With it, each turn's model is picked by Bizzy's hosted API, whose judge Jev reads the prompt you typed; tool output, the conversation and your harness logins stay on your machine. Without a key, or when the hosted API doesn't answer, Bizzy's own rules pick on your machine. `--no-share-prompts` keeps prompts local too, and the hosted API then routes on its rules.
23
+ On a terminal, `install` asks once for your Bizzy routing key and saves it to `~/.bizzy/routing/.env` (mode 0600, never printed). With it, each turn's model is picked by Bizzy's hosted API, whose judge Jev reads the prompt you typed and grades the models you can use against it, cheapest first; the first one it rates able to do the task serves. Tool output, the conversation and your harness logins stay on your machine. Without a key, or when the hosted API doesn't answer, Bizzy's own rules pick on your machine. `--no-share-prompts` keeps prompts local too, and the hosted API then routes on its rules.
24
+
25
+ - **Only approved models are routed:** a named set of Claude, GPT and OpenRouter models. Any other model your harness offers is left out.
26
+ - **A model you reach both ways is offered once, on your subscription login,** so it isn't billed per token. In omp, Jev grades subscription-login models before per-token ones.
27
+ - **Each turn's record holds numbers only:** the model, token counts (cache reads and writes apart), the model you would have used without routing, and the task type Jev named. Bizzy's reports use them to estimate savings and completion rate. No prompt or tool output is stored.
28
+ - **In omp, `/model bizzy/auto` replaces your `@default`,** so the extension remembers the last real one and uses it when routing is off.
29
+ - **`install claude-code --jev-grade`** asks for per-model grading by name. The hosted API already grades by default, so it changes nothing there.
24
30
 
25
31
  Other commands:
26
32
 
@@ -24,7 +24,7 @@ async function readStdin() {
24
24
  for await (const chunk of process.stdin) text += String(chunk);
25
25
  return text;
26
26
  }
27
- var { run } = await import("./main-HTRHF32Q.js");
27
+ var { run } = await import("./main-5GEO2B7F.js");
28
28
  var { plainUi } = await import("./ui-PEKFVWX7.js");
29
29
  var { clackUi, showError } = await import("./clack-ui-KG2I32T5.js");
30
30
  var interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
@@ -35,7 +35,7 @@ try {
35
35
  home: homedir(),
36
36
  execPath: process.execPath,
37
37
  bundleDir: dirname(fileURLToPath(import.meta.url)),
38
- version: true ? "0.4.5" : "dev",
38
+ version: true ? "0.5.0" : "dev",
39
39
  platform: process.platform,
40
40
  uid: process.getuid?.(),
41
41
  interactive,
@@ -3,6 +3,8 @@ import type { EngineInterface, Register } from "claude-code";
3
3
  // Written by the packager: where the routing API listens and, optionally, how to start it.
4
4
  interface Config {
5
5
  url: string;
6
+ /** The @bizzywork/routing version that installed this mod. */
7
+ version?: string;
6
8
  server?: { argv: string[]; cwd: string; env: Record<string, string> };
7
9
  }
8
10
  interface ModelList {
@@ -23,6 +25,12 @@ interface Decision {
23
25
  model: string;
24
26
  rule: string;
25
27
  reason: string;
28
+ /** "stage" once tool signals moved the turn up from its first pick. */
29
+ source?: string;
30
+ /** The serving model's strength among the turn's models, 1 to 5; unset with no benchmark data. */
31
+ level?: number;
32
+ /** The serving model's list price among the turn's models, 1 to 3; unset with no price or no spread. */
33
+ price?: number;
26
34
  notice?: string;
27
35
  /** Set when a live routing-vs-control comparison sampled this turn. "control" keeps the native model. */
28
36
  arm?: "treatment" | "control";
@@ -40,10 +48,16 @@ const DISCLOSURE =
40
48
  "Bizzy Auto sends each prompt you type to Bizzy's routing API, where Jev picks the capable or efficient model (BIZZY_SHARE_PROMPTS=0 in ~/.bizzy/routing/.env keeps prompts here). /bizzy off stops routing.";
41
49
  // Claude Code refetches its model list about hourly; one older than this is a cache it no longer writes.
42
50
  const LIST_MAX_AGE_MS = 24 * 60 * 60 * 1000;
51
+ const DAY_MS = 24 * 60 * 60 * 1000;
52
+ const REGISTRY = "https://registry.npmjs.org/@bizzywork%2Frouting/latest";
53
+ const MANUAL_UPDATE = "npx @bizzywork/routing@latest install claude-code";
43
54
 
44
55
  let config: Config | undefined;
45
56
  let enabled = true;
46
57
  let status = WAITING;
58
+ // The status line without the update notice, and the newest published version when it is ahead of this install.
59
+ let base = WAITING;
60
+ let update: string | undefined;
47
61
  let sessionId: string | undefined;
48
62
  // The model Claude Code itself resolves; a change means the person picked one with /model.
49
63
  let nativeModel: string | undefined;
@@ -54,6 +68,14 @@ let prompt: string | undefined;
54
68
  // Why the last turn routed without Jev, shown once per session and in /bizzy status.
55
69
  let notice: string | undefined;
56
70
  let noticed = false;
71
+ // Why the last request got its model, for /bizzy status.
72
+ let reason: string | undefined;
73
+
74
+ // The level as a five-cell bar, or the rule's name when the model has no benchmark data; then the price as one to three `$`.
75
+ const meter = (decision: Decision) =>
76
+ (decision.level ? "●".repeat(decision.level) + "○".repeat(5 - decision.level) : decision.rule) +
77
+ (decision.price ? ` · ${"$".repeat(decision.price)}` : "") +
78
+ (decision.source === "stage" ? " · escalated" : "");
57
79
 
58
80
  const claudeModel = /^claude-[\w.-]+$/;
59
81
 
@@ -63,9 +85,14 @@ const safeId = (value: string) =>
63
85
  .replace(/^[^A-Za-z0-9]+/, "")
64
86
  .slice(0, 128) || "none";
65
87
 
88
+ function render($: EngineInterface) {
89
+ status = update ? `${base} · update ${update} available: /bizzy update` : base;
90
+ $.ui.status(status);
91
+ }
92
+
66
93
  function show($: EngineInterface, text: string) {
67
- status = text;
68
- $.ui.status(text);
94
+ base = text;
95
+ render($);
69
96
  }
70
97
 
71
98
  async function loadConfig($: EngineInterface): Promise<Config> {
@@ -77,6 +104,7 @@ async function loadConfig($: EngineInterface): Promise<Config> {
77
104
  } catch {}
78
105
  config = {
79
106
  url: fromEnv ?? file.url ?? "http://127.0.0.1:4100",
107
+ ...(file.version ? { version: file.version } : {}),
80
108
  ...(file.server ? { server: file.server } : {}),
81
109
  };
82
110
  return config;
@@ -267,13 +295,69 @@ async function fallback<E extends { model: string; turnId: string }>(
267
295
  return { ...e, model };
268
296
  }
269
297
 
298
+ const newer = (latest: string, current: string) => {
299
+ const [a, b] = [latest, current].map((version) => version.split(".").map(Number));
300
+ const at = a!.findIndex((part, i) => part !== (b![i] ?? 0));
301
+ return at !== -1 && a![at]! > (b![at] ?? 0);
302
+ };
303
+
304
+ async function latestVersion($: EngineInterface): Promise<string | undefined> {
305
+ try {
306
+ const reply = await within($, 5000, $.http.fetch(REGISTRY));
307
+ const { version } = JSON.parse(reply.text) as { version?: unknown };
308
+ return reply.ok && typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
309
+ ? version
310
+ : undefined;
311
+ } catch {
312
+ return undefined;
313
+ }
314
+ }
315
+
316
+ // Asks the npm registry at most once a day, silently: offline or BIZZY_NO_UPDATE_CHECK set leaves the status as it was.
317
+ async function checkUpdate($: EngineInterface) {
318
+ const { version } = await loadConfig($);
319
+ if (!version || (await $.env.get("BIZZY_NO_UPDATE_CHECK"))) return;
320
+ const now = await $.clock.now();
321
+ let latest = (await $.store.get("latestVersion")) as string | undefined;
322
+ if (now - Number((await $.store.get("checkedAt")) ?? 0) > DAY_MS) {
323
+ latest = (await latestVersion($)) ?? latest;
324
+ await $.store.set("checkedAt", now);
325
+ if (latest) await $.store.set("latestVersion", latest);
326
+ }
327
+ update = latest && newer(latest, version) ? latest : undefined;
328
+ render($);
329
+ }
330
+
331
+ // Reinstalls from the newest package, keeping the key and settings; the running mod keeps the old code until /reload-plugins.
332
+ async function runUpdate($: EngineInterface): Promise<string> {
333
+ const { url, version } = await loadConfig($);
334
+ const latest = await latestVersion($);
335
+ if (latest && version && !newer(latest, version)) return `Bizzy is up to date (${version}).`;
336
+ const port = /:(\d+)\/?$/.exec(url)?.[1] ?? "4100";
337
+ try {
338
+ const { exitCode, stdout, stderr } = await $.process.run(
339
+ ["npx", "--yes", "@bizzywork/routing@latest", "install", "claude-code", "--port", port],
340
+ { timeoutMs: 180_000 },
341
+ );
342
+ if (exitCode === 0) {
343
+ update = undefined;
344
+ render($);
345
+ return `Updated${latest ? ` to ${latest}` : ""}. Type /reload-plugins to load it.`;
346
+ }
347
+ return `The update failed (exit ${exitCode}):\n${(stderr || stdout).trim().slice(-400)}\nRun it in a terminal: ${MANUAL_UPDATE}`;
348
+ } catch (error) {
349
+ return `Couldn't run the update here (${error instanceof Error ? error.message : error}). Run it in a terminal: ${MANUAL_UPDATE}`;
350
+ }
351
+ }
352
+
270
353
  export const register: Register = (on) => {
271
354
  on("session.start", async ($, e, next) => {
272
355
  void keepServer($);
273
356
  void keepModels($);
357
+ void checkUpdate($);
274
358
  await $.command.register({
275
359
  name: "bizzy",
276
- description: "Bizzy Auto routing: on, off, or status",
360
+ description: "Bizzy Auto routing: on, off, status, or update",
277
361
  });
278
362
  await sync($);
279
363
  if (!(await $.store.get("disclosed"))) {
@@ -297,8 +381,13 @@ export const register: Register = (on) => {
297
381
  enabled = true;
298
382
  nativeModel = await $.session.model();
299
383
  show($, WAITING);
300
- } else if (action !== "status") return { text: "Usage: /bizzy [on|off|status]" };
301
- return { text: [status, notice, DISCLOSURE].filter(Boolean).join("\n") };
384
+ } else if (action === "update") {
385
+ $.ui.toast("Updating Bizzy…");
386
+ return { text: await runUpdate($) };
387
+ } else if (action !== "status") return { text: "Usage: /bizzy [on|off|status|update]" };
388
+ return {
389
+ text: [status, reason && `Why: ${reason}`, notice, DISCLOSURE].filter(Boolean).join("\n"),
390
+ };
302
391
  });
303
392
 
304
393
  on("command.run", { command: "model" }, async ($, e, next) => {
@@ -343,11 +432,12 @@ export const register: Register = (on) => {
343
432
  // Control keeps the request on Claude Code's own model: the comparison needs a sample of
344
433
  // turns Bizzy never touched, not just an opinion it kept to itself.
345
434
  const control = decision.arm === "control";
435
+ reason = control ? undefined : decision.reason;
346
436
  show(
347
437
  $,
348
438
  control
349
439
  ? `Bizzy Auto · control · keeping ${current}`
350
- : `Bizzy Auto · ${decision.model} · ${notice ? "own rules" : decision.rule}${decision.arm ? " · treatment" : ""}`,
440
+ : `Bizzy Auto · ${decision.model} · ${meter(decision)}${notice ? " · own rules" : ""}${decision.arm ? " · treatment" : ""}`,
351
441
  );
352
442
  if (notice && !noticed) {
353
443
  noticed = true;
@@ -402,6 +492,8 @@ export const register: Register = (on) => {
402
492
  usage.cache_read_input_tokens +
403
493
  usage.cache_creation_input_tokens,
404
494
  outputTokens: usage.output_tokens,
495
+ cacheReadTokens: usage.cache_read_input_tokens,
496
+ cacheWriteTokens: usage.cache_creation_input_tokens,
405
497
  },
406
498
  }
407
499
  : {}),
@@ -1,7 +1,8 @@
1
- import { spawn } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
5
6
  // The package index re-exports the stream class as a type only; omp's own code imports it from here.
6
7
  import { AssistantMessageEventStream } from "@oh-my-pi/pi-ai/utils/event-stream";
7
8
  import {
@@ -19,6 +20,8 @@ import {
19
20
  isTransient,
20
21
  modelId,
21
22
  fallbackFrom,
23
+ meter,
24
+ newer,
22
25
  realModel,
23
26
  routingWindow,
24
27
  turnOf,
@@ -27,12 +30,20 @@ import {
27
30
  // Written by the installer: where the routing API listens and, optionally, how to start it.
28
31
  interface Config {
29
32
  url: string;
33
+ /** The @bizzywork/routing version that installed this extension. */
34
+ version?: string;
30
35
  server?: { argv: string[]; cwd: string; env: Record<string, string> };
31
36
  }
32
37
  interface Decision {
33
38
  model: string;
34
39
  rule: string;
35
40
  reason: string;
41
+ /** "stage" once tool signals moved the turn up from its first pick. */
42
+ source?: string;
43
+ /** The serving model's strength among the turn's models, 1 to 5; unset with no benchmark data. */
44
+ level?: number;
45
+ /** The serving model's list price among the turn's models, 1 to 3; unset with no price or no spread. */
46
+ price?: number;
36
47
  notice?: string;
37
48
  /** Set when a live routing-vs-control comparison sampled this turn. "control" keeps the native model. */
38
49
  arm?: "treatment" | "control";
@@ -69,6 +80,7 @@ function loadConfig(): Config {
69
80
  }
70
81
  return {
71
82
  url: process.env.BIZZY_ROUTING_URL ?? file.url ?? "http://127.0.0.1:4100",
83
+ ...(file.version ? { version: file.version } : {}),
72
84
  ...(file.server ? { server: file.server } : {}),
73
85
  };
74
86
  }
@@ -92,19 +104,88 @@ const shared: {
92
104
  enabled: boolean;
93
105
  compacted: boolean;
94
106
  status: string;
107
+ // The status line without the update notice, and the newest published version when it is ahead of this install.
108
+ base: string;
109
+ update?: string | undefined;
95
110
  sent?: string;
96
111
  // Why the last turn routed without Jev, shown once per session and in /bizzy status.
97
112
  notice?: string | undefined;
98
113
  noticed?: boolean;
114
+ // Why the last request got its model, for /bizzy status.
115
+ reason?: string | undefined;
99
116
  // Conservative until the server first names its picks.
100
117
  meta: Meta;
101
118
  } = {
102
119
  enabled: true,
103
120
  compacted: false,
104
121
  status: WAITING,
122
+ base: WAITING,
105
123
  meta: { contextWindow: 128_000, maxTokens: 16_000, input: ["text"], reasoning: false },
106
124
  };
107
125
 
126
+ const DAY_MS = 24 * 60 * 60 * 1000;
127
+ const REGISTRY = "https://registry.npmjs.org/@bizzywork%2Frouting/latest";
128
+ const MANUAL_UPDATE = "npx @bizzywork/routing@latest install omp";
129
+ const CHECKED = join(
130
+ config.server?.cwd ?? dirname(fileURLToPath(import.meta.url)),
131
+ "update-check.json",
132
+ );
133
+ const run = promisify(execFile);
134
+
135
+ async function latestVersion(): Promise<string | undefined> {
136
+ try {
137
+ const reply = await fetch(REGISTRY, { signal: AbortSignal.timeout(5000) });
138
+ const { version } = (await reply.json()) as { version?: unknown };
139
+ return reply.ok && typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
140
+ ? version
141
+ : undefined;
142
+ } catch {
143
+ return undefined;
144
+ }
145
+ }
146
+
147
+ // Asks the npm registry at most once a day, silently: offline or BIZZY_NO_UPDATE_CHECK set leaves the status as it was.
148
+ async function checkUpdate() {
149
+ if (!config.version || process.env.BIZZY_NO_UPDATE_CHECK) return;
150
+ let saved: { checkedAt?: number; latest?: string } = {};
151
+ try {
152
+ saved = JSON.parse(readFileSync(CHECKED, "utf8")) as typeof saved;
153
+ } catch {
154
+ // Never checked, or unreadable: check now.
155
+ }
156
+ let latest = saved.latest;
157
+ if (Date.now() - (saved.checkedAt ?? 0) > DAY_MS) {
158
+ latest = (await latestVersion()) ?? latest;
159
+ try {
160
+ writeFileSync(
161
+ CHECKED,
162
+ JSON.stringify({ checkedAt: Date.now(), ...(latest ? { latest } : {}) }),
163
+ );
164
+ } catch {
165
+ // A read-only install asks again next session.
166
+ }
167
+ }
168
+ shared.update = latest && newer(latest, config.version) ? latest : undefined;
169
+ }
170
+
171
+ // Reinstalls from the newest package, keeping the key and settings; omp keeps the old code until it restarts.
172
+ async function runUpdate(): Promise<string> {
173
+ const latest = await latestVersion();
174
+ if (latest && config.version && !newer(latest, config.version))
175
+ return `Bizzy is up to date (${config.version}).`;
176
+ const port = /:(\d+)\/?$/.exec(config.url)?.[1] ?? "4100";
177
+ try {
178
+ await run("npx", ["--yes", "@bizzywork/routing@latest", "install", "omp", "--port", port], {
179
+ timeout: 180_000,
180
+ });
181
+ shared.update = undefined;
182
+ return `Updated${latest ? ` to ${latest}` : ""}. Restart omp to load it.`;
183
+ } catch (error) {
184
+ const failed = error as { stderr?: string; stdout?: string; message: string };
185
+ return `The update failed:\n${(failed.stderr || failed.stdout || failed.message).trim().slice(-400)}\nRun it in a terminal: ${MANUAL_UPDATE}`;
186
+ }
187
+ }
188
+
108
189
  class ApiError extends Error {
109
190
  constructor(readonly status: number) {
110
191
  super(`routing API ${status}`);
@@ -177,8 +258,11 @@ function failure(model: Model, text: string): AssistantMessage {
177
258
 
178
259
  export default function (pi: ExtensionAPI) {
179
260
  const show = (text: string) => {
180
- shared.status = text;
181
- shared.ctx?.ui.setStatus("bizzy", text);
261
+ shared.base = text;
262
+ shared.status = shared.update
263
+ ? `${text} · update ${shared.update} available: /bizzy update`
264
+ : text;
265
+ shared.ctx?.ui.setStatus("bizzy", shared.status);
182
266
  };
183
267
 
184
268
  const register = (meta: Meta = shared.meta) => {
@@ -305,10 +389,11 @@ export default function (pi: ExtensionAPI) {
305
389
  control = decision.arm === "control";
306
390
  target = control ? fallbackModel : (pick(c, decision.model) ?? fallbackModel);
307
391
  if (turn.index === 0) shared.notice = decision.notice;
392
+ shared.reason = control ? undefined : decision.reason;
308
393
  show(
309
394
  control
310
395
  ? `Bizzy Auto · control · keeping ${modelId(target)}`
311
- : `Bizzy Auto · ${modelId(target)} · ${shared.notice ? "own rules" : decision.rule}${decision.arm ? " · treatment" : ""}`,
396
+ : `Bizzy Auto · ${modelId(target)} · ${meter(decision)}${shared.notice ? " · own rules" : ""}${decision.arm ? " · treatment" : ""}`,
312
397
  );
313
398
  if (shared.notice && !shared.noticed) {
314
399
  shared.noticed = true;
@@ -423,6 +508,8 @@ export default function (pi: ExtensionAPI) {
423
508
  usage: {
424
509
  inputTokens: message.usage.input + message.usage.cacheRead + message.usage.cacheWrite,
425
510
  outputTokens: message.usage.output,
511
+ cacheReadTokens: message.usage.cacheRead,
512
+ cacheWriteTokens: message.usage.cacheWrite,
426
513
  },
427
514
  }).catch(() => {});
428
515
  }
@@ -445,6 +532,7 @@ export default function (pi: ExtensionAPI) {
445
532
  }
446
533
  }
447
534
  keepServer(c);
535
+ void checkUpdate().then(() => show(shared.base));
448
536
  await refresh(c);
449
537
  c.setInterval(() => void refresh(c), POLL_MS);
450
538
  });
@@ -460,14 +548,26 @@ export default function (pi: ExtensionAPI) {
460
548
  });
461
549
 
462
550
  pi.registerCommand("bizzy", {
463
- description: "Bizzy Auto routing: on, off, or status",
551
+ description: "Bizzy Auto routing: on, off, status, or update",
464
552
  handler: async (args, c) => {
465
553
  const action = args.trim() || "status";
554
+ if (action === "update") {
555
+ c.ui.notify("Updating Bizzy…", "info");
556
+ const text = await runUpdate();
557
+ show(shared.base);
558
+ return c.ui.notify(text, "info");
559
+ }
466
560
  if (action === "off") shared.enabled = false;
467
561
  else if (action === "on") shared.enabled = true;
468
- else if (action !== "status") return c.ui.notify("Usage: /bizzy [on|off|status]", "warning");
562
+ else if (action !== "status")
563
+ return c.ui.notify("Usage: /bizzy [on|off|status|update]", "warning");
469
564
  if (action !== "status") show(shared.enabled ? WAITING : "Bizzy Auto off");
470
- c.ui.notify([shared.status, shared.notice, DISCLOSURE].filter(Boolean).join("\n"), "info");
565
+ c.ui.notify(
566
+ [shared.status, shared.reason && `Why: ${shared.reason}`, shared.notice, DISCLOSURE]
567
+ .filter(Boolean)
568
+ .join("\n"),
569
+ "info",
570
+ );
471
571
  },
472
572
  });
473
573
  }
@@ -56,6 +56,25 @@ const textOf = (content: unknown) =>
56
56
 
57
57
  export const modelId = (model: { provider: string; id: string }) => `${model.provider}/${model.id}`;
58
58
 
59
+ /** A decision's level as a five-cell bar, or its rule's name when the model has no benchmark data; then its price as
60
+ * one to three `$`, and "escalated" once tool signals moved the turn up. */
61
+ export const meter = (decision: {
62
+ level?: number;
63
+ price?: number;
64
+ rule: string;
65
+ source?: string;
66
+ }) =>
67
+ (decision.level ? "●".repeat(decision.level) + "○".repeat(5 - decision.level) : decision.rule) +
68
+ (decision.price ? ` · ${"$".repeat(decision.price)}` : "") +
69
+ (decision.source === "stage" ? " · escalated" : "");
70
+
71
+ /** Whether `latest` is a later x.y.z than `current`. */
72
+ export function newer(latest: string, current: string): boolean {
73
+ const [a, b] = [latest, current].map((version) => version.split(".").map(Number));
74
+ const at = a!.findIndex((part, i) => part !== (b![i] ?? 0));
75
+ return at !== -1 && a![at]! > (b![at] ?? 0);
76
+ }
77
+
59
78
  /** Besides the prompt `turnOf` reads for Jev, only tool activity leaves omp: tool names, shell commands and capped results. */
60
79
  export function routingWindow(messages: readonly OmpMessage[]): ApiMessage[] {
61
80
  return messages.slice(-WINDOW).flatMap((message): ApiMessage[] => {