@bizzywork/routing 0.0.0-stage → 0.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.
- package/LICENSE +26 -0
- package/README.md +34 -2
- package/dist/bundle/THIRD-PARTY-NOTICES.txt +1960 -0
- package/dist/bundle/bizzy-routing.js +60 -0
- package/dist/bundle/chunk-RYVRLJBJ.js +62 -0
- package/dist/bundle/clack-ui-KUXMJI7C.js +1405 -0
- package/dist/bundle/harnesses/claude-code/.claude-plugin/plugin.json +6 -0
- package/dist/bundle/harnesses/claude-code/hooks/hooks.json +1 -0
- package/dist/bundle/harnesses/claude-code/hooks/register.ts +391 -0
- package/dist/bundle/harnesses/omp/index.ts +433 -0
- package/dist/bundle/harnesses/omp/routing.ts +164 -0
- package/dist/bundle/main-7NNVOX2S.js +83583 -0
- package/dist/bundle/static/csp.json +1 -0
- package/dist/bundle/static/favicon-16x16.png +0 -0
- package/dist/bundle/static/favicon-32x32.png +0 -0
- package/dist/bundle/static/index.css +16 -0
- package/dist/bundle/static/index.html +19 -0
- package/dist/bundle/static/logo.svg +43 -0
- package/dist/bundle/static/oauth2-redirect.html +6 -0
- package/dist/bundle/static/oauth2-redirect.js +1 -0
- package/dist/bundle/static/swagger-ui-bundle.js +2 -0
- package/dist/bundle/static/swagger-ui-standalone-preset.js +2 -0
- package/dist/bundle/static/swagger-ui.css +2 -0
- package/dist/bundle/static/swagger-ui.js +1 -0
- package/dist/bundle/ui-4PTMUQQ4.js +40 -0
- package/package.json +27 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.ts"] }
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import type { EngineInterface, Register } from "claude-code";
|
|
2
|
+
|
|
3
|
+
// Written by the packager: where the routing API listens and, optionally, how to start it.
|
|
4
|
+
interface Config {
|
|
5
|
+
url: string;
|
|
6
|
+
server?: { argv: string[]; cwd: string; env: Record<string, string> };
|
|
7
|
+
}
|
|
8
|
+
interface ModelList {
|
|
9
|
+
fetchedAt: number;
|
|
10
|
+
available: string[];
|
|
11
|
+
}
|
|
12
|
+
// The fields read from Claude Code's model cache; every one may be missing.
|
|
13
|
+
interface CatalogFile {
|
|
14
|
+
version?: unknown;
|
|
15
|
+
fetchedAt?: unknown;
|
|
16
|
+
catalog?: {
|
|
17
|
+
config?: {
|
|
18
|
+
models?: { id?: unknown; section?: unknown }[];
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
interface Decision {
|
|
23
|
+
model: string;
|
|
24
|
+
rule: string;
|
|
25
|
+
reason: string;
|
|
26
|
+
notice?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const WINDOW = 24;
|
|
30
|
+
const MAX_RESULT = 4000;
|
|
31
|
+
const STEP_MS = 2000;
|
|
32
|
+
// A turn's first step waits for Jev: its 10 s timeout plus the routing API's own time.
|
|
33
|
+
const FIRST_STEP_MS = 12000;
|
|
34
|
+
const MAX_PROMPT = 8000;
|
|
35
|
+
const POLL_MS = 30000;
|
|
36
|
+
const WAITING = "Bizzy Auto · waiting for a request";
|
|
37
|
+
const DISCLOSURE =
|
|
38
|
+
"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.";
|
|
39
|
+
// Claude Code refetches its model list about hourly; one older than this is a cache it no longer writes.
|
|
40
|
+
const LIST_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
41
|
+
|
|
42
|
+
let config: Config | undefined;
|
|
43
|
+
let enabled = true;
|
|
44
|
+
let status = WAITING;
|
|
45
|
+
let sessionId: string | undefined;
|
|
46
|
+
// The model Claude Code itself resolves; a change means the person picked one with /model.
|
|
47
|
+
let nativeModel: string | undefined;
|
|
48
|
+
let serving = false;
|
|
49
|
+
let listing = false;
|
|
50
|
+
// The last prompt typed, which the next turn's first step sends for Jev and uses up.
|
|
51
|
+
let prompt: string | undefined;
|
|
52
|
+
// Why the last turn routed without Jev, shown once per session and in /bizzy status.
|
|
53
|
+
let notice: string | undefined;
|
|
54
|
+
let noticed = false;
|
|
55
|
+
|
|
56
|
+
const claudeModel = /^claude-[\w.-]+$/;
|
|
57
|
+
|
|
58
|
+
const safeId = (value: string) =>
|
|
59
|
+
value
|
|
60
|
+
.replace(/[^A-Za-z0-9._:/-]/g, "-")
|
|
61
|
+
.replace(/^[^A-Za-z0-9]+/, "")
|
|
62
|
+
.slice(0, 128) || "none";
|
|
63
|
+
|
|
64
|
+
function show($: EngineInterface, text: string) {
|
|
65
|
+
status = text;
|
|
66
|
+
$.ui.status(text);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function loadConfig($: EngineInterface): Promise<Config> {
|
|
70
|
+
if (config) return config;
|
|
71
|
+
const fromEnv = await $.env.get("BIZZY_ROUTING_URL");
|
|
72
|
+
let file: Partial<Config> = {};
|
|
73
|
+
try {
|
|
74
|
+
file = JSON.parse(await $.fs.read(`${$.plugin.root}/bizzy.json`)) as Partial<Config>;
|
|
75
|
+
} catch {}
|
|
76
|
+
config = {
|
|
77
|
+
url: fromEnv ?? file.url ?? "http://127.0.0.1:4100",
|
|
78
|
+
...(file.server ? { server: file.server } : {}),
|
|
79
|
+
};
|
|
80
|
+
return config;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function within<T>($: EngineInterface, ms: number, promise: Promise<T>): Promise<T> {
|
|
84
|
+
return Promise.race([
|
|
85
|
+
promise,
|
|
86
|
+
$.clock.sleep(ms).then(() => {
|
|
87
|
+
throw new Error("routing API timed out");
|
|
88
|
+
}),
|
|
89
|
+
]);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function post<T>($: EngineInterface, path: string, body: unknown, ms = STEP_MS): Promise<T> {
|
|
93
|
+
const { url } = await loadConfig($);
|
|
94
|
+
const response = await within(
|
|
95
|
+
$,
|
|
96
|
+
ms,
|
|
97
|
+
$.http.fetch(`${url}${path}`, {
|
|
98
|
+
method: "POST",
|
|
99
|
+
headers: { "content-type": "application/json" },
|
|
100
|
+
body: JSON.stringify(body),
|
|
101
|
+
}),
|
|
102
|
+
);
|
|
103
|
+
if (!response.ok) throw new Error(`routing API ${response.status}`);
|
|
104
|
+
return JSON.parse(response.text) as T;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The harness routes answer 405 to a GET, which says the API is up with them on.
|
|
108
|
+
async function isUp($: EngineInterface): Promise<boolean> {
|
|
109
|
+
const { url } = await loadConfig($);
|
|
110
|
+
try {
|
|
111
|
+
return (await within($, STEP_MS, $.http.fetch(`${url}/v1/harness/step`))).status === 405;
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Claude kills a child when the dispatch that spawned it ends, so the server is kept from session.start's own loop.
|
|
118
|
+
async function keepServer($: EngineInterface) {
|
|
119
|
+
if (serving) return;
|
|
120
|
+
serving = true;
|
|
121
|
+
for (;;) {
|
|
122
|
+
const { server } = await loadConfig($);
|
|
123
|
+
if (server && !(await isUp($))) {
|
|
124
|
+
const child = $.process.spawn({ argv: server.argv, cwd: server.cwd, env: server.env });
|
|
125
|
+
try {
|
|
126
|
+
for await (const _ of child) {
|
|
127
|
+
/* drain so the child is never blocked on a full pipe */
|
|
128
|
+
}
|
|
129
|
+
} catch {}
|
|
130
|
+
}
|
|
131
|
+
await $.clock.sleep(POLL_MS);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Claude Code's cache of the /model picker's list. Undocumented, so anything unexpected reads as no list.
|
|
136
|
+
async function accountModels($: EngineInterface) {
|
|
137
|
+
const root = (await $.env.get("CLAUDE_CONFIG_DIR")) ?? `${await $.env.get("HOME")}/.claude`;
|
|
138
|
+
const directory = `${root}/cache/model-catalog`;
|
|
139
|
+
let newest: ModelList | undefined;
|
|
140
|
+
for (const entry of await $.fs.list(directory).catch(() => [])) {
|
|
141
|
+
if (entry.kind !== "file" || !entry.name.endsWith("-cc.json")) continue;
|
|
142
|
+
const file = await $.fs
|
|
143
|
+
.read(`${directory}/${entry.name}`)
|
|
144
|
+
.then((text) => JSON.parse(text) as CatalogFile)
|
|
145
|
+
.catch(() => undefined);
|
|
146
|
+
if (file?.version !== 2 || typeof file.fetchedAt !== "number") continue;
|
|
147
|
+
if (newest && newest.fetchedAt >= file.fetchedAt) continue;
|
|
148
|
+
const listedModels = file.catalog?.config?.models;
|
|
149
|
+
const available = (Array.isArray(listedModels) ? listedModels : []).flatMap((model) =>
|
|
150
|
+
model?.section === "main" && typeof model.id === "string" && claudeModel.test(model.id)
|
|
151
|
+
? [model.id]
|
|
152
|
+
: [],
|
|
153
|
+
);
|
|
154
|
+
if (available.length) newest = { fetchedAt: file.fetchedAt, available };
|
|
155
|
+
}
|
|
156
|
+
return newest && (await $.clock.now()) - newest.fetchedAt < LIST_MAX_AGE_MS ? newest : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// The server keeps the list in memory, so it is sent on every poll: a restarted server has it again within one.
|
|
160
|
+
// With no fresh list nothing is sent, and the server answers each step 409, so Claude Code keeps its own model.
|
|
161
|
+
async function keepModels($: EngineInterface) {
|
|
162
|
+
if (listing) return;
|
|
163
|
+
listing = true;
|
|
164
|
+
for (;;) {
|
|
165
|
+
const models = await accountModels($);
|
|
166
|
+
if (models) await post($, "/v1/harness/models", models).catch(() => {});
|
|
167
|
+
await $.clock.sleep(POLL_MS);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Besides the prompt sent for Jev, only tool activity leaves Claude Code: tool names, shell commands and capped results.
|
|
172
|
+
function routingWindow(messages: readonly { role: string; content: readonly unknown[] }[]) {
|
|
173
|
+
return messages.slice(-WINDOW).flatMap((message) => {
|
|
174
|
+
const content = message.content.flatMap((raw): Record<string, unknown>[] => {
|
|
175
|
+
const block = raw as Record<string, any>;
|
|
176
|
+
if (block.type === "tool_use") {
|
|
177
|
+
const command = typeof block.input?.command === "string" ? block.input.command : undefined;
|
|
178
|
+
return [
|
|
179
|
+
{
|
|
180
|
+
type: "tool_use",
|
|
181
|
+
id: block.id,
|
|
182
|
+
name: block.name,
|
|
183
|
+
input: command === undefined ? {} : { command },
|
|
184
|
+
},
|
|
185
|
+
];
|
|
186
|
+
}
|
|
187
|
+
if (block.type === "tool_result") {
|
|
188
|
+
const text =
|
|
189
|
+
typeof block.content === "string"
|
|
190
|
+
? block.content
|
|
191
|
+
: Array.isArray(block.content)
|
|
192
|
+
? block.content
|
|
193
|
+
.map((part: any) => (part?.type === "text" ? part.text : ""))
|
|
194
|
+
.join("\n")
|
|
195
|
+
: "";
|
|
196
|
+
return [
|
|
197
|
+
{
|
|
198
|
+
type: "tool_result",
|
|
199
|
+
tool_use_id: block.tool_use_id,
|
|
200
|
+
content: text.slice(0, MAX_RESULT),
|
|
201
|
+
is_error: block.is_error === true,
|
|
202
|
+
},
|
|
203
|
+
];
|
|
204
|
+
}
|
|
205
|
+
return [];
|
|
206
|
+
});
|
|
207
|
+
return content.length ? [{ role: message.role, content }] : [];
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// A new session id (/clear, /resume) starts its own routing; Claude does not always fire session.start for it.
|
|
212
|
+
async function sync($: EngineInterface) {
|
|
213
|
+
const id = await $.session.id();
|
|
214
|
+
if (id === sessionId) return;
|
|
215
|
+
sessionId = id;
|
|
216
|
+
enabled = true;
|
|
217
|
+
notice = undefined;
|
|
218
|
+
noticed = false;
|
|
219
|
+
nativeModel = await $.session.model();
|
|
220
|
+
show($, WAITING);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function pause($: EngineInterface, model?: string) {
|
|
224
|
+
enabled = false;
|
|
225
|
+
show($, model ? `Bizzy Auto off · you picked ${model}; /bizzy on to resume` : "Bizzy Auto off");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// The routing API names the other pick and skips the failed model for a while; without it, Claude Code's own model.
|
|
229
|
+
async function fallback<E extends { model: string; turnId: string }>(
|
|
230
|
+
$: EngineInterface,
|
|
231
|
+
e: E,
|
|
232
|
+
failed: string,
|
|
233
|
+
error: unknown,
|
|
234
|
+
): Promise<E | undefined> {
|
|
235
|
+
const text = error instanceof Error ? error.message : String(error ?? "");
|
|
236
|
+
const transient = !/model|not.?found|404|permission|403/i.test(text);
|
|
237
|
+
let model = e.model;
|
|
238
|
+
try {
|
|
239
|
+
const decision = await post<{ model: string | null }>($, "/v1/harness/fallback", {
|
|
240
|
+
session: safeId(sessionId!),
|
|
241
|
+
turnId: safeId(e.turnId),
|
|
242
|
+
model: failed,
|
|
243
|
+
transient,
|
|
244
|
+
});
|
|
245
|
+
if (decision.model && claudeModel.test(decision.model)) model = decision.model;
|
|
246
|
+
} catch (fallbackError) {
|
|
247
|
+
// The routing server itself is unreachable, not just the failed model: fall back to Claude
|
|
248
|
+
// Code's own choice rather than leaving the turn stuck re-trying the model that just failed.
|
|
249
|
+
if (nativeModel !== undefined && nativeModel !== failed) {
|
|
250
|
+
show(
|
|
251
|
+
$,
|
|
252
|
+
`Bizzy Auto unavailable · keeping ${nativeModel}: ${fallbackError instanceof Error ? fallbackError.message : String(fallbackError)}`,
|
|
253
|
+
);
|
|
254
|
+
return { ...e, model: nativeModel };
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (model === failed) return undefined;
|
|
258
|
+
show($, `Bizzy Auto · ${model} · ${failed} ${transient ? "failed" : "unavailable"}`);
|
|
259
|
+
return { ...e, model };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export const register: Register = (on) => {
|
|
263
|
+
on("session.start", async ($, e, next) => {
|
|
264
|
+
void keepServer($);
|
|
265
|
+
void keepModels($);
|
|
266
|
+
await $.command.register({
|
|
267
|
+
name: "bizzy",
|
|
268
|
+
description: "Bizzy Auto routing: on, off, or status",
|
|
269
|
+
});
|
|
270
|
+
await sync($);
|
|
271
|
+
if (!(await $.store.get("disclosed"))) {
|
|
272
|
+
$.ui.toast(DISCLOSURE, { timeoutMs: 15000 });
|
|
273
|
+
await $.store.set("disclosed", true);
|
|
274
|
+
}
|
|
275
|
+
return next(e);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
// The prompt as typed, without the reminders and context the engine adds beside it.
|
|
279
|
+
on("prompt.submit", async ($, e, next) => {
|
|
280
|
+
if (!e.isMeta) prompt = e.text.slice(0, MAX_PROMPT);
|
|
281
|
+
return next(e);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
on("command.run", { command: "bizzy" }, async ($, e) => {
|
|
285
|
+
await sync($);
|
|
286
|
+
const action = e.args.trim() || "status";
|
|
287
|
+
if (action === "off") pause($);
|
|
288
|
+
else if (action === "on") {
|
|
289
|
+
enabled = true;
|
|
290
|
+
nativeModel = await $.session.model();
|
|
291
|
+
show($, WAITING);
|
|
292
|
+
} else if (action !== "status") return { text: "Usage: /bizzy [on|off|status]" };
|
|
293
|
+
return { text: [status, notice, DISCLOSURE].filter(Boolean).join("\n") };
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
on("command.run", { command: "model" }, async ($, e, next) => {
|
|
297
|
+
const result = await next(e);
|
|
298
|
+
await sync($);
|
|
299
|
+
if (enabled && e.args.trim()) pause($, await $.session.model());
|
|
300
|
+
return result;
|
|
301
|
+
}).catch(($, e, next) => (next.called ? {} : next(e)));
|
|
302
|
+
|
|
303
|
+
on("turn.step", async function* ($, e, next) {
|
|
304
|
+
if (e.agentId !== undefined || !enabled) return yield* next(e);
|
|
305
|
+
let routed = e;
|
|
306
|
+
try {
|
|
307
|
+
await sync($);
|
|
308
|
+
const current = await $.session.model();
|
|
309
|
+
if (nativeModel !== undefined && current !== nativeModel) pause($, current);
|
|
310
|
+
else {
|
|
311
|
+
nativeModel = current;
|
|
312
|
+
const messages = await $.session.messages({ as: "api" });
|
|
313
|
+
const first = e.index === 0;
|
|
314
|
+
const sent = first ? prompt : undefined;
|
|
315
|
+
if (first) prompt = undefined;
|
|
316
|
+
const decision = await post<Decision>(
|
|
317
|
+
$,
|
|
318
|
+
"/v1/harness/step",
|
|
319
|
+
{
|
|
320
|
+
session: safeId(sessionId!),
|
|
321
|
+
turnId: safeId(e.turnId),
|
|
322
|
+
index: e.index,
|
|
323
|
+
depth: messages.filter((message) => message.role === "assistant").length,
|
|
324
|
+
compacted: false,
|
|
325
|
+
messages: routingWindow(messages),
|
|
326
|
+
...(sent ? { prompt: sent } : {}),
|
|
327
|
+
},
|
|
328
|
+
first ? FIRST_STEP_MS : STEP_MS,
|
|
329
|
+
);
|
|
330
|
+
if (!claudeModel.test(decision.model)) throw new Error("not a Claude model id");
|
|
331
|
+
if (first) notice = decision.notice;
|
|
332
|
+
show($, `Bizzy Auto · ${decision.model} · ${notice ? "own rules" : decision.rule}`);
|
|
333
|
+
if (notice && !noticed) {
|
|
334
|
+
noticed = true;
|
|
335
|
+
$.ui.toast(`Bizzy Auto: ${notice}`);
|
|
336
|
+
}
|
|
337
|
+
routed = { ...e, model: decision.model };
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
show(
|
|
341
|
+
$,
|
|
342
|
+
`Bizzy Auto unavailable · keeping ${e.model}: ${error instanceof Error ? error.message : String(error)}`,
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
if (routed.model === e.model) return yield* next(routed);
|
|
346
|
+
// Nothing has reached the person before the first chunk, so a request that fails on the routed model is sent
|
|
347
|
+
// again on another; once a chunk has streamed, errors propagate as they are and the stream is never replayed.
|
|
348
|
+
const stream = next(routed);
|
|
349
|
+
let first;
|
|
350
|
+
try {
|
|
351
|
+
first = await stream.next();
|
|
352
|
+
} catch (error) {
|
|
353
|
+
const again = await fallback($, e, routed.model, error);
|
|
354
|
+
if (!again) throw error;
|
|
355
|
+
return yield* next(again);
|
|
356
|
+
}
|
|
357
|
+
if (first.done) {
|
|
358
|
+
if (first.value.stopReason !== null || next.signal.aborted) return first.value;
|
|
359
|
+
const again = await fallback($, e, routed.model, undefined);
|
|
360
|
+
return again ? yield* next(again) : first.value;
|
|
361
|
+
}
|
|
362
|
+
yield first.value;
|
|
363
|
+
return yield* stream;
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
on("turn.complete", async ($, e, next) => {
|
|
367
|
+
const result = await next(e);
|
|
368
|
+
if (e.agentId === undefined && enabled && sessionId) {
|
|
369
|
+
const usage = result.usage ?? e.usage;
|
|
370
|
+
void post($, "/v1/harness/complete", {
|
|
371
|
+
session: safeId(sessionId),
|
|
372
|
+
turnId: safeId(e.turnId),
|
|
373
|
+
reason: e.reason,
|
|
374
|
+
// The id that served the turn, which an alias tier doesn't name.
|
|
375
|
+
...(usage?.model ? { model: usage.model } : {}),
|
|
376
|
+
...(usage
|
|
377
|
+
? {
|
|
378
|
+
usage: {
|
|
379
|
+
inputTokens:
|
|
380
|
+
usage.input_tokens +
|
|
381
|
+
usage.cache_read_input_tokens +
|
|
382
|
+
usage.cache_creation_input_tokens,
|
|
383
|
+
outputTokens: usage.output_tokens,
|
|
384
|
+
},
|
|
385
|
+
}
|
|
386
|
+
: {}),
|
|
387
|
+
}).catch(() => {});
|
|
388
|
+
}
|
|
389
|
+
return result;
|
|
390
|
+
});
|
|
391
|
+
};
|