@bizzywork/routing 0.4.4 → 0.4.6

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.
@@ -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-TRXFLPTZ.js");
27
+ var { run } = await import("./main-IY47BGRH.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.4" : "dev",
38
+ version: true ? "0.4.6" : "dev",
39
39
  platform: process.platform,
40
40
  uid: process.getuid?.(),
41
41
  interactive,
@@ -392,6 +392,8 @@ export const register: Register = (on) => {
392
392
  reason: e.reason,
393
393
  // The id that served the turn, which an alias tier doesn't name.
394
394
  ...(usage?.model ? { model: usage.model } : {}),
395
+ // The session's own model: what this turn would have used without routing.
396
+ ...(nativeModel ? { baseline: safeId(nativeModel) } : {}),
395
397
  ...(usage
396
398
  ? {
397
399
  usage: {
@@ -400,6 +402,8 @@ export const register: Register = (on) => {
400
402
  usage.cache_read_input_tokens +
401
403
  usage.cache_creation_input_tokens,
402
404
  outputTokens: usage.output_tokens,
405
+ cacheReadTokens: usage.cache_read_input_tokens,
406
+ cacheWriteTokens: usage.cache_creation_input_tokens,
403
407
  },
404
408
  }
405
409
  : {}),
@@ -419,9 +419,12 @@ export default function (pi: ExtensionAPI) {
419
419
  ? "aborted"
420
420
  : "error",
421
421
  model: safeId(modelId(real)),
422
+ baseline: safeId(modelId(fallbackModel)),
422
423
  usage: {
423
424
  inputTokens: message.usage.input + message.usage.cacheRead + message.usage.cacheWrite,
424
425
  outputTokens: message.usage.output,
426
+ cacheReadTokens: message.usage.cacheRead,
427
+ cacheWriteTokens: message.usage.cacheWrite,
425
428
  },
426
429
  }).catch(() => {});
427
430
  }
@@ -1173,7 +1173,7 @@ var require_foldFlowLines = __commonJS({
1173
1173
  else
1174
1174
  end = lineWidth - indentAtStart;
1175
1175
  }
1176
- let split = void 0;
1176
+ let split2 = void 0;
1177
1177
  let prev = void 0;
1178
1178
  let overflow = false;
1179
1179
  let i = -1;
@@ -1206,18 +1206,18 @@ var require_foldFlowLines = __commonJS({
1206
1206
  if (mode === FOLD_BLOCK)
1207
1207
  i = consumeMoreIndentedLines(text, i, indent.length);
1208
1208
  end = i + indent.length + endStep;
1209
- split = void 0;
1209
+ split2 = void 0;
1210
1210
  } else {
1211
1211
  if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") {
1212
1212
  const next = text[i + 1];
1213
1213
  if (next && next !== " " && next !== "\n" && next !== " ")
1214
- split = i;
1214
+ split2 = i;
1215
1215
  }
1216
1216
  if (i >= end) {
1217
- if (split) {
1218
- folds.push(split);
1219
- end = split + endStep;
1220
- split = void 0;
1217
+ if (split2) {
1218
+ folds.push(split2);
1219
+ end = split2 + endStep;
1220
+ split2 = void 0;
1221
1221
  } else if (mode === FOLD_QUOTED) {
1222
1222
  while (prev === " " || prev === " ") {
1223
1223
  prev = ch;
@@ -1230,7 +1230,7 @@ var require_foldFlowLines = __commonJS({
1230
1230
  folds.push(j);
1231
1231
  escapedFolds[j] = true;
1232
1232
  end = j + endStep;
1233
- split = void 0;
1233
+ split2 = void 0;
1234
1234
  } else {
1235
1235
  overflow = true;
1236
1236
  }
@@ -4764,13 +4764,13 @@ var require_resolve_block_scalar = __commonJS({
4764
4764
  return { mode, indent, chomp, comment, length };
4765
4765
  }
4766
4766
  function splitLines(source) {
4767
- const split = source.split(/\n( *)/);
4768
- const first = split[0];
4767
+ const split2 = source.split(/\n( *)/);
4768
+ const first = split2[0];
4769
4769
  const m = first.match(/^( *)/);
4770
4770
  const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
4771
4771
  const lines2 = [line0];
4772
- for (let i = 1; i < split.length; i += 2)
4773
- lines2.push([split[i], split[i + 1]]);
4772
+ for (let i = 1; i < split2.length; i += 2)
4773
+ lines2.push([split2[i], split2[i + 1]]);
4774
4774
  return lines2;
4775
4775
  }
4776
4776
  exports.resolveBlockScalar = resolveBlockScalar;
@@ -9172,8 +9172,8 @@ var require_common = __commonJS({
9172
9172
  createDebug.namespaces = namespaces;
9173
9173
  createDebug.names = [];
9174
9174
  createDebug.skips = [];
9175
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
9176
- for (const ns of split) {
9175
+ const split2 = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
9176
+ for (const ns of split2) {
9177
9177
  if (ns[0] === "-") {
9178
9178
  createDebug.skips.push(ns.slice(1));
9179
9179
  } else {
@@ -19041,11 +19041,11 @@ var require_plugin = __commonJS({
19041
19041
  this.server = server;
19042
19042
  const func = this.func;
19043
19043
  const name = this.name;
19044
- let completed = false;
19044
+ let completed2 = false;
19045
19045
  this.options = typeof this.options === "function" ? this.options(this.server) : this.options;
19046
19046
  let timer = null;
19047
19047
  const done = (execErr) => {
19048
- if (completed) {
19048
+ if (completed2) {
19049
19049
  debug("loading complete", name);
19050
19050
  return;
19051
19051
  }
@@ -19055,7 +19055,7 @@ var require_plugin = __commonJS({
19055
19055
  } else {
19056
19056
  debug("exec completed", name);
19057
19057
  }
19058
- completed = true;
19058
+ completed2 = true;
19059
19059
  if (timer) {
19060
19060
  clearTimeout(timer);
19061
19061
  }
@@ -19631,12 +19631,12 @@ var require_avvio = __commonJS({
19631
19631
  executeWithThenable(func, [err], cb);
19632
19632
  } else {
19633
19633
  if (this._opts.timeout === 0) {
19634
- let completed = false;
19634
+ let completed2 = false;
19635
19635
  const wrapCb = (err2) => {
19636
- if (completed) {
19636
+ if (completed2) {
19637
19637
  return;
19638
19638
  }
19639
- completed = true;
19639
+ completed2 = true;
19640
19640
  this._error = err2;
19641
19641
  process.nextTick(cb, this._error);
19642
19642
  };
@@ -54052,16 +54052,16 @@ var require_set_cookie = __commonJS({
54052
54052
  input2 = sch;
54053
54053
  }
54054
54054
  }
54055
- var split = options.split;
54055
+ var split2 = options.split;
54056
54056
  var isArray = Array.isArray(input2);
54057
- if (split === "auto") {
54058
- split = !isArray;
54057
+ if (split2 === "auto") {
54058
+ split2 = !isArray;
54059
54059
  }
54060
54060
  if (!isArray) {
54061
54061
  input2 = [input2];
54062
54062
  }
54063
54063
  input2 = input2.filter(isNonEmptyString);
54064
- if (split) {
54064
+ if (split2) {
54065
54065
  input2 = input2.map(splitCookiesString).flat();
54066
54066
  }
54067
54067
  if (!options.map) {
@@ -76498,18 +76498,56 @@ var ModelCandidateSchema = external_exports.object({
76498
76498
  taskType: SafeIdSchema.exactOptional()
76499
76499
  });
76500
76500
 
76501
+ // bizzy-routing/contracts/src/schemas/signals.ts
76502
+ var maximumLength = 64;
76503
+ var CountSchema = external_exports.number().int().min(0);
76504
+ var TurnSignalsSchema = external_exports.object({
76505
+ /** Worst severity in the recent window: 0 clean, 0.3 soft, 0.7 hard, 1 critical. */
76506
+ maxSeverity: UnitSchema,
76507
+ /** The same hard or explicit failure appeared twice in the recent window. */
76508
+ repeatedFailure: external_exports.boolean(),
76509
+ /** Read, edit, write and planning calls in the recent window. */
76510
+ reads: CountSchema,
76511
+ edits: CountSchema,
76512
+ writes: CountSchema,
76513
+ plans: CountSchema,
76514
+ /** Turns into the mission. */
76515
+ depth: CountSchema,
76516
+ /** Clean tool results back from the most recent. */
76517
+ cleanStreak: CountSchema,
76518
+ /** A test pass after the latest failure in the recent window. */
76519
+ testsPassed: external_exports.boolean(),
76520
+ compacted: external_exports.boolean()
76521
+ });
76522
+ var RoutingStateSchema = external_exports.record(
76523
+ external_exports.string().max(maximumLength),
76524
+ external_exports.union([external_exports.string().max(maximumLength), external_exports.number(), external_exports.boolean()])
76525
+ );
76526
+
76501
76527
  // bizzy-routing/contracts/src/schemas/run-record.ts
76502
76528
  var IsoDateSchema = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T/).refine((value) => Number.isFinite(Date.parse(value)));
76503
- var CountSchema = external_exports.number().int().min(0);
76529
+ var CountSchema2 = external_exports.number().int().min(0);
76504
76530
  var UsageSchema = external_exports.object({
76505
- inputTokens: CountSchema,
76506
- outputTokens: CountSchema,
76507
- costUsd: external_exports.number().min(0)
76531
+ /** All input tokens, cached ones included: the total the provider bills against. */
76532
+ inputTokens: CountSchema2,
76533
+ outputTokens: CountSchema2,
76534
+ costUsd: external_exports.number().min(0),
76535
+ /** The part of `inputTokens` served from the provider's prompt cache, and the part written to it. Unset on
76536
+ * runs recorded before they were split out, which price as fresh input. */
76537
+ cacheReadTokens: CountSchema2.exactOptional(),
76538
+ cacheWriteTokens: CountSchema2.exactOptional()
76508
76539
  });
76509
76540
  var RunRecordSchema = external_exports.object({
76510
76541
  version: external_exports.literal("2"),
76511
76542
  runId: SafeIdSchema,
76512
- task: external_exports.object({ kind: SafeIdSchema, risk: RiskSchema, inputRef: HashRefSchema }),
76543
+ task: external_exports.object({
76544
+ kind: SafeIdSchema,
76545
+ risk: RiskSchema,
76546
+ inputRef: HashRefSchema,
76547
+ /** What the judge called the task (`coding`, `legal`, ...), for reports. `kind` stays the routing scope that
76548
+ * history and earned scores are kept under. */
76549
+ type: SafeIdSchema.exactOptional()
76550
+ }),
76513
76551
  route: external_exports.object({
76514
76552
  modelId: SafeIdSchema,
76515
76553
  provider: SafeIdSchema,
@@ -76525,8 +76563,8 @@ var RunRecordSchema = external_exports.object({
76525
76563
  /** The judge's own token usage for this run's route call, regardless of which strategy asked it.
76526
76564
  * `costUsd` is null when no judge price was configured, not a guessed number. */
76527
76565
  judgeUsage: external_exports.object({
76528
- inputTokens: CountSchema,
76529
- outputTokens: CountSchema,
76566
+ inputTokens: CountSchema2,
76567
+ outputTokens: CountSchema2,
76530
76568
  costUsd: external_exports.number().min(0).nullable()
76531
76569
  }).exactOptional(),
76532
76570
  /** Set by the caller when a live routing-vs-control comparison chose this run's arm;
@@ -76534,12 +76572,17 @@ var RunRecordSchema = external_exports.object({
76534
76572
  * bizzy-v2 never sees or sets it. */
76535
76573
  arm: external_exports.enum(["treatment", "control"]).exactOptional(),
76536
76574
  /** The comparison window this run belongs to, when `arm` is set. */
76537
- windowId: SafeIdSchema.exactOptional()
76575
+ windowId: SafeIdSchema.exactOptional(),
76576
+ /** The model this person's own harness would have used without routing (their default). Unset from a client that
76577
+ * doesn't send it; a report then prices the run against a standard baseline. */
76578
+ baselineModelId: SafeIdSchema.exactOptional()
76538
76579
  }),
76539
76580
  startedAt: IsoDateSchema,
76540
76581
  settledAt: IsoDateSchema,
76541
76582
  latencyMs: external_exports.number().min(0),
76542
76583
  usage: UsageSchema,
76584
+ /** The turn's tool activity when it ended, as numbers and flags: the proxy for whether it went well. */
76585
+ signals: TurnSignalsSchema.exactOptional(),
76543
76586
  quality: UnitSchema,
76544
76587
  taskSuccess: external_exports.boolean(),
76545
76588
  processSuccess: external_exports.boolean(),
@@ -76561,32 +76604,6 @@ function sanitizeRunRecord(input2) {
76561
76604
  return parseOrThrow(RunRecordSchema, input2, (issue2) => issueField("RunRecord", issue2));
76562
76605
  }
76563
76606
 
76564
- // bizzy-routing/contracts/src/schemas/signals.ts
76565
- var maximumLength = 64;
76566
- var CountSchema2 = external_exports.number().int().min(0);
76567
- var TurnSignalsSchema = external_exports.object({
76568
- /** Worst severity in the recent window: 0 clean, 0.3 soft, 0.7 hard, 1 critical. */
76569
- maxSeverity: UnitSchema,
76570
- /** The same hard or explicit failure appeared twice in the recent window. */
76571
- repeatedFailure: external_exports.boolean(),
76572
- /** Read, edit, write and planning calls in the recent window. */
76573
- reads: CountSchema2,
76574
- edits: CountSchema2,
76575
- writes: CountSchema2,
76576
- plans: CountSchema2,
76577
- /** Turns into the mission. */
76578
- depth: CountSchema2,
76579
- /** Clean tool results back from the most recent. */
76580
- cleanStreak: CountSchema2,
76581
- /** A test pass after the latest failure in the recent window. */
76582
- testsPassed: external_exports.boolean(),
76583
- compacted: external_exports.boolean()
76584
- });
76585
- var RoutingStateSchema = external_exports.record(
76586
- external_exports.string().max(maximumLength),
76587
- external_exports.union([external_exports.string().max(maximumLength), external_exports.number(), external_exports.boolean()])
76588
- );
76589
-
76590
76607
  // bizzy-routing/contracts/src/state.ts
76591
76608
  function validateRoutingState(value) {
76592
76609
  return parseOrThrow(
@@ -76655,7 +76672,9 @@ var DoneStepSchema = external_exports.object({
76655
76672
  /** Set by the host when a question went unanswered, so the decision is the rules' alone; for the user to see. */
76656
76673
  notice: external_exports.string().exactOptional(),
76657
76674
  /** Set when a live routing-vs-control comparison is open; unset otherwise. */
76658
- window: OpenWindowSchema.exactOptional()
76675
+ window: OpenWindowSchema.exactOptional(),
76676
+ /** What the judge called the task, when it was asked; unset when no judge answered. */
76677
+ taskType: SafeIdSchema.exactOptional()
76659
76678
  });
76660
76679
  var StepSchema = external_exports.discriminatedUnion("kind", [AskJudgeStepSchema, DoneStepSchema]);
76661
76680
 
@@ -76683,6 +76702,7 @@ var RouteBodySchema = external_exports.strictObject({
76683
76702
  mode: ModeSchema,
76684
76703
  pin: SafeIdSchema.exactOptional(),
76685
76704
  allowOpenRouter: external_exports.boolean().exactOptional(),
76705
+ subscriptionFirst: external_exports.boolean().exactOptional(),
76686
76706
  strategy: external_exports.enum(strategies).exactOptional(),
76687
76707
  profile: external_exports.enum(profiles).exactOptional(),
76688
76708
  newUserTurn: external_exports.boolean().exactOptional(),
@@ -76782,6 +76802,7 @@ __export(src_exports, {
76782
76802
  stageConstants: () => stageConstants,
76783
76803
  stageStrategy: () => stageStrategy,
76784
76804
  summarize: () => summarize,
76805
+ taskTypes: () => taskTypes,
76785
76806
  updateRuleScore: () => updateRuleScore,
76786
76807
  updateScore: () => updateScore,
76787
76808
  useRegistryStore: () => useRegistryStore,
@@ -76822,6 +76843,18 @@ var approved = /* @__PURE__ */ new Set([...anthropicModels, ...openAiModels, ...
76822
76843
  var isSubscription = (provider) => subscriptionProviders.has(provider);
76823
76844
  var isApproved = (catalogId) => catalogId !== null && approved.has(catalogId);
76824
76845
 
76846
+ // bizzy-routing/decision/src/task-types.ts
76847
+ var taskTypes = [
76848
+ "engineering",
76849
+ "finance",
76850
+ "legal",
76851
+ "healthcare",
76852
+ "strategy",
76853
+ "cyber",
76854
+ "multilingual",
76855
+ "general"
76856
+ ];
76857
+
76825
76858
  // bizzy-routing/decision/src/profiles.ts
76826
76859
  var jevProfile = {
76827
76860
  name: "jev",
@@ -77378,23 +77411,31 @@ var judgeGradeStrategy = function* (input2) {
77378
77411
  const base = cascade(input2, [pin, trial, registry2, history, coldStart]);
77379
77412
  if (input2.pin) return { kind: "done", decision: base, state };
77380
77413
  const priors = input2.priors ?? {};
77414
+ const subscriptionRank = (provider) => input2.subscriptionFirst ? Number(!isSubscription(provider)) : 0;
77381
77415
  const ranked = [...permittedCandidates(input2)].sort(
77382
- (a, b) => Number(!(a.id in priors)) - Number(!(b.id in priors)) || a.costPer1k - b.costPer1k
77416
+ (a, b) => subscriptionRank(a.provider) - subscriptionRank(b.provider) || Number(!(a.id in priors)) - Number(!(b.id in priors)) || a.costPer1k - b.costPer1k
77383
77417
  );
77384
77418
  if (!ranked.length) return { kind: "done", decision: base, state };
77385
- const questions2 = ranked.map((_, i) => ({
77386
- id: gradeQuestionId(i + 1),
77387
- kind: "score",
77388
- min: 0,
77389
- max: 1
77390
- }));
77419
+ const questions2 = [
77420
+ ...ranked.map((_, i) => ({
77421
+ id: gradeQuestionId(i + 1),
77422
+ kind: "score",
77423
+ min: 0,
77424
+ max: 1
77425
+ })),
77426
+ // The same call names the task's type, for reports; it doesn't change the pick.
77427
+ { id: "taskType", kind: "choice", options: taskTypes }
77428
+ ];
77391
77429
  const result = yield { kind: "ask-judge", questions: questions2, context: "summary" };
77392
77430
  if (result.kind !== "answers") return { kind: "done", decision: base, state };
77431
+ const taskType = result.answers.taskType;
77432
+ const typed2 = typeof taskType === "string" ? { taskType } : {};
77393
77433
  const winner = ranked.find((_, i) => {
77394
77434
  const answer = result.answers[gradeQuestionId(i + 1)];
77395
77435
  return typeof answer === "number" && answer > 0.5;
77396
77436
  });
77397
- if (!winner || winner === base.model) return { kind: "done", decision: base, state };
77437
+ if (!winner || winner === base.model)
77438
+ return { kind: "done", decision: base, state, ...typed2 };
77398
77439
  return {
77399
77440
  kind: "done",
77400
77441
  decision: decisionForModel(
@@ -77403,7 +77444,8 @@ var judgeGradeStrategy = function* (input2) {
77403
77444
  "judge-grade",
77404
77445
  "judge-grade: cheapest candidate Jev rated capable of the task"
77405
77446
  ),
77406
- state
77447
+ state,
77448
+ ...typed2
77407
77449
  };
77408
77450
  };
77409
77451
 
@@ -80967,11 +81009,15 @@ function parseModels(body) {
80967
81009
  const input2 = Number(pricing?.prompt) * 1e3, output2 = Number(pricing?.completion) * 1e3;
80968
81010
  if (!(input2 >= 0 && output2 >= 0)) continue;
80969
81011
  const parameters = Array.isArray(row.supported_parameters) ? row.supported_parameters : [];
81012
+ const cache = pricing;
81013
+ const cacheRead = Number(cache?.input_cache_read) * 1e3, cacheWrite = Number(cache?.input_cache_write) * 1e3;
80970
81014
  models.push({
80971
81015
  id: id2,
80972
81016
  contextLength: score(row.context_length) ?? 0,
80973
81017
  inputPer1k: input2,
80974
81018
  outputPer1k: output2,
81019
+ ...cacheRead >= 0 ? { cacheReadPer1k: cacheRead } : {},
81020
+ ...cacheWrite >= 0 ? { cacheWritePer1k: cacheWrite } : {},
80975
81021
  toolUse: parameters.includes("tools"),
80976
81022
  codingIndex: null,
80977
81023
  agenticIndex: null,
@@ -81467,6 +81513,15 @@ function trialWindowOpenBody(raw) {
81467
81513
  // bizzy-routing/api/src/harness.ts
81468
81514
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
81469
81515
 
81516
+ // bizzy-routing/api/src/catalog-match.ts
81517
+ var vendor = (value) => value.replace(/^openai-codex(?=\/|$)/, "openai");
81518
+ function harnessCatalogId(model, catalog, { provider, aliases }) {
81519
+ return catalogIdOf(vendor(model), catalog, {
81520
+ ...provider ? { provider: vendor(provider) } : {},
81521
+ ...aliases ? { aliases } : {}
81522
+ });
81523
+ }
81524
+
81470
81525
  // bizzy-routing/api/src/hosted.ts
81471
81526
  var HostedError = class extends Error {
81472
81527
  };
@@ -81506,6 +81561,7 @@ function createHostedRoute(options) {
81506
81561
  ...envelope.profile ? { profile: envelope.profile } : {},
81507
81562
  ...envelope.newUserTurn ? { newUserTurn: true } : {},
81508
81563
  ...envelope.allowOpenRouter ? { allowOpenRouter: true } : {},
81564
+ ...envelope.subscriptionFirst ? { subscriptionFirst: true } : {},
81509
81565
  ...shared ? { context: "summary", summary: shared } : {}
81510
81566
  };
81511
81567
  const text = await post(
@@ -81617,10 +81673,7 @@ async function matchModels(available, server, provider) {
81617
81673
  (a, b) => Number(!isSubscription(providerOf(a, provider))) - Number(!isSubscription(providerOf(b, provider)))
81618
81674
  );
81619
81675
  for (const model of byPreference) {
81620
- const catalogId = catalog ? catalogIdOf(model.replace(/^openai-codex\//, "openai/"), catalog, {
81621
- ...provider ? { provider } : {},
81622
- aliases
81623
- }) : null;
81676
+ const catalogId = catalog ? harnessCatalogId(model, catalog, { ...provider ? { provider } : {}, aliases }) : null;
81624
81677
  if (server.approved && !server.approved(catalogId)) continue;
81625
81678
  const row = catalogId ? rows2.get(catalogId) : void 0;
81626
81679
  if (!row?.toolUse) {
@@ -81667,10 +81720,13 @@ function parseHarnessComplete(raw) {
81667
81720
  turnId: id(body.turnId, "turnId"),
81668
81721
  reason: body.reason,
81669
81722
  ...body.model === void 0 ? {} : { model: id(body.model, "model") },
81723
+ ...body.baseline === void 0 ? {} : { baseline: id(body.baseline, "baseline") },
81670
81724
  ...usage ? {
81671
81725
  usage: {
81672
81726
  inputTokens: count(usage.inputTokens, "usage.inputTokens"),
81673
- outputTokens: count(usage.outputTokens, "usage.outputTokens")
81727
+ outputTokens: count(usage.outputTokens, "usage.outputTokens"),
81728
+ ...usage.cacheReadTokens === void 0 ? {} : { cacheReadTokens: count(usage.cacheReadTokens, "usage.cacheReadTokens") },
81729
+ ...usage.cacheWriteTokens === void 0 ? {} : { cacheWriteTokens: count(usage.cacheWriteTokens, "usage.cacheWriteTokens") }
81674
81730
  }
81675
81731
  } : {}
81676
81732
  };
@@ -81785,6 +81841,7 @@ function createHarnessRouter(options, server) {
81785
81841
  newUserTurn: true,
81786
81842
  // The harness's OpenRouter models are ones its user signed in to; the approved list has already narrowed them.
81787
81843
  allowOpenRouter: true,
81844
+ ...options.subscriptionFirst ? { subscriptionFirst: true } : {},
81788
81845
  ...options.profile ? { profile: options.profile } : {}
81789
81846
  };
81790
81847
  const material = body.prompt ? { policy: "summary", summary: body.prompt } : { policy: "none" };
@@ -81813,6 +81870,7 @@ function createHarnessRouter(options, server) {
81813
81870
  ...judged && typeof done.state.judgeAdvantage === "number" ? { judgeAdvantage: done.state.judgeAdvantage } : {},
81814
81871
  ...judged && done.state.judgeTrial ? { judgeTrial: true } : {},
81815
81872
  ...done.window ? { windowId: done.window.id } : {},
81873
+ ...done.taskType ? { taskType: done.taskType } : {},
81816
81874
  ...judgeUsage.inputTokens || judgeUsage.outputTokens ? { judgeUsage } : {},
81817
81875
  startedAt: now(),
81818
81876
  signals
@@ -81884,7 +81942,12 @@ function createHarnessRouter(options, server) {
81884
81942
  const run3 = {
81885
81943
  version: "2",
81886
81944
  runId: randomUUID2(),
81887
- task: { kind: "code", risk: "low", inputRef: hashRef(`${body.session}:${body.turnId}`) },
81945
+ task: {
81946
+ kind: "code",
81947
+ risk: "low",
81948
+ inputRef: hashRef(`${body.session}:${body.turnId}`),
81949
+ ...turn.taskType ? { type: turn.taskType } : {}
81950
+ },
81888
81951
  route: {
81889
81952
  modelId: served,
81890
81953
  provider: providerOf(served, options.provider),
@@ -81900,7 +81963,8 @@ function createHarnessRouter(options, server) {
81900
81963
  costUsd: server.judgePricePer1k ? turn.judgeUsage.inputTokens / 1e3 * server.judgePricePer1k.input + turn.judgeUsage.outputTokens / 1e3 * server.judgePricePer1k.output : null
81901
81964
  }
81902
81965
  } : {},
81903
- ...turn.served.arm ? { arm: turn.served.arm, windowId: turn.windowId } : {}
81966
+ ...turn.served.arm ? { arm: turn.served.arm, windowId: turn.windowId } : {},
81967
+ ...body.baseline === void 0 ? {} : { baselineModelId: body.baseline }
81904
81968
  },
81905
81969
  startedAt: new Date(turn.startedAt).toISOString(),
81906
81970
  settledAt: new Date(settledAt).toISOString(),
@@ -81909,8 +81973,11 @@ function createHarnessRouter(options, server) {
81909
81973
  usage: {
81910
81974
  inputTokens: body.usage?.inputTokens ?? 0,
81911
81975
  outputTokens: body.usage?.outputTokens ?? 0,
81912
- costUsd: 0
81976
+ costUsd: 0,
81977
+ ...body.usage?.cacheReadTokens === void 0 ? {} : { cacheReadTokens: body.usage.cacheReadTokens },
81978
+ ...body.usage?.cacheWriteTokens === void 0 ? {} : { cacheWriteTokens: body.usage.cacheWriteTokens }
81913
81979
  },
81980
+ signals: turn.signals,
81914
81981
  quality: 0,
81915
81982
  taskSuccess: false,
81916
81983
  processSuccess: body.reason === "answer",
@@ -82150,7 +82217,12 @@ function terminalWatcher(onEnd) {
82150
82217
  const askedForTools = output2.some((item) => /call$/.test(String(record4(item)?.type)));
82151
82218
  onEnd(
82152
82219
  event.type === "response.completed" ? "answer" : "error",
82153
- usage && typeof usage.input_tokens === "number" && typeof usage.output_tokens === "number" ? { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } : void 0,
82220
+ usage && typeof usage.input_tokens === "number" && typeof usage.output_tokens === "number" ? {
82221
+ inputTokens: usage.input_tokens,
82222
+ outputTokens: usage.output_tokens,
82223
+ // OpenAI bills cached input at a discount and charges nothing extra to write it.
82224
+ ...typeof record4(usage.input_tokens_details)?.cached_tokens === "number" ? { cacheReadTokens: record4(usage.input_tokens_details).cached_tokens } : {}
82225
+ } : void 0,
82154
82226
  askedForTools
82155
82227
  );
82156
82228
  }
@@ -82304,11 +82376,20 @@ function createCodexRelay(options, server) {
82304
82376
  if (usage) {
82305
82377
  sum.inputTokens += usage.inputTokens;
82306
82378
  sum.outputTokens += usage.outputTokens;
82379
+ if (usage.cacheReadTokens !== void 0)
82380
+ sum.cacheReadTokens = (sum.cacheReadTokens ?? 0) + usage.cacheReadTokens;
82307
82381
  }
82308
82382
  turns.set(key, sum);
82309
82383
  if (askedForTools && reason === "answer") return;
82310
82384
  turns.delete(key);
82311
- settling = router.complete({ session: position.session, turnId: position.turnId, reason, usage: sum }).catch(() => {
82385
+ settling = router.complete({
82386
+ session: position.session,
82387
+ turnId: position.turnId,
82388
+ reason,
82389
+ usage: sum,
82390
+ // Codex's own first model: what this account would have used without the relay.
82391
+ ...visibleModels(list2)[0] ? { baseline: visibleModels(list2)[0].slug } : {}
82392
+ }).catch(() => {
82312
82393
  });
82313
82394
  }) : void 0;
82314
82395
  const decoder = new TextDecoder();
@@ -82502,10 +82583,10 @@ function openApiDocument({ auth }) {
82502
82583
  "/v1/routing-report": {
82503
82584
  get: {
82504
82585
  summary: "Report Bizzy's own standing routing performance",
82505
- description: "Per day and task kind, over every run Bizzy actually routed (a trial's control arm is excluded; it isn't Bizzy's routing): runs, cost per completed run, success rate, average quality, latency and token usage, how often routing escalated to the capable model, and Jev's own call rate and cost. Aggregates only. Independent of any trial window. Takes a key from BIZZY_API_KEYS or a read-only one from BIZZY_REPORT_KEYS.",
82586
+ description: "Per day and task kind, over every run Bizzy actually routed (a trial's control arm is excluded; it isn't Bizzy's routing): runs, cost per completed run, success rate, completion rate (finished, with no hard tool failure), estimated savings at catalog list prices against each person's default model (subscription turns included; not cash), average quality, latency and token usage, how often routing escalated to the capable model, and Jev's own call rate and cost. Aggregates only. Independent of any trial window. Takes a key from BIZZY_API_KEYS or a read-only one from BIZZY_REPORT_KEYS.",
82506
82587
  ...guard({
82507
82588
  "200": {
82508
- description: "`{ rows }`: one `{ date, taskKind, runs, costPerCompleted, successRate, avgQuality, avgLatencyMs, avgInputTokens, avgOutputTokens, capableRate, judgeCallRate, avgJudgeCostUsd }` per day and task kind, oldest first (`costPerCompleted` and `avgJudgeCostUsd` null when nothing succeeded, or nothing priced the judge).",
82589
+ description: "`{ rows, models }`: `models` has one `{ date, taskKind, modelId, provider, billing, runs, completedRuns, inputTokens, outputTokens, listPriceCostUsd }` per day, task kind and served model, for a table of which models were selected. `rows` is one `{ date, taskKind, runs, costPerCompleted, successRate, completionRate, listPriceCostUsd, baselineListPriceCostUsd, listPriceSavingsUsd, pricedRuns, missingBaselineRuns, avgQuality, avgLatencyMs, avgInputTokens, avgOutputTokens, capableRate, judgeCallRate, avgJudgeCostUsd }` per day and task kind, oldest first (`costPerCompleted` and `avgJudgeCostUsd` null when nothing succeeded, or nothing priced the judge; the list-price fields null when the catalog priced no run).",
82509
82590
  content: { "application/json": { schema: { type: "object" } } }
82510
82591
  }
82511
82592
  })
@@ -82554,6 +82635,22 @@ function openApiDocument({ auth }) {
82554
82635
  }
82555
82636
 
82556
82637
  // bizzy-routing/api/src/routing-report.ts
82638
+ var standardBaseline = "anthropic/claude-sonnet-5.5";
82639
+ function catalogPrice(catalog, aliases = {}) {
82640
+ const rows2 = new Map(catalog.models.map((model) => [model.id, model]));
82641
+ return (modelId, provider) => {
82642
+ const id2 = harnessCatalogId(modelId, catalog, { provider, aliases });
82643
+ return id2 ? rows2.get(id2) : void 0;
82644
+ };
82645
+ }
82646
+ var completed = (run3) => run3.processSuccess && (run3.signals === void 0 || run3.signals.maxSeverity < 0.7 && !run3.signals.repeatedFailure);
82647
+ var split = (run3) => run3.usage.cacheReadTokens !== void 0 || run3.usage.cacheWriteTokens !== void 0;
82648
+ var tokensCost = (run3, price) => {
82649
+ const read = run3.usage.cacheReadTokens ?? 0;
82650
+ const write = run3.usage.cacheWriteTokens ?? 0;
82651
+ const fresh = Math.max(0, run3.usage.inputTokens - read - write);
82652
+ return fresh / 1e3 * price.inputPer1k + read / 1e3 * (price.cacheReadPer1k ?? price.inputPer1k) + write / 1e3 * (price.cacheWritePer1k ?? price.inputPer1k) + run3.usage.outputTokens / 1e3 * price.outputPer1k;
82653
+ };
82557
82654
  var mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
82558
82655
  function judgeCostAverage(runs) {
82559
82656
  const priced = runs.flatMap(
@@ -82561,26 +82658,39 @@ function judgeCostAverage(runs) {
82561
82658
  );
82562
82659
  return priced.length ? mean(priced) : null;
82563
82660
  }
82564
- function summarizeRouting(records2) {
82661
+ function summarizeRouting(records2, price) {
82565
82662
  const groups = /* @__PURE__ */ new Map();
82566
82663
  for (const record5 of records2) {
82567
82664
  if (record5.route.arm === "control") continue;
82568
82665
  const date5 = record5.settledAt.slice(0, 10);
82569
- const key = `${date5}\0${record5.task.kind}`;
82666
+ const key = `${date5}\0${record5.task.type ?? record5.task.kind}`;
82570
82667
  const group = groups.get(key) ?? [];
82571
82668
  group.push(record5);
82572
82669
  groups.set(key, group);
82573
82670
  }
82574
82671
  return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, runs]) => {
82575
82672
  const [date5, taskKind] = key.split("\0");
82576
- const completed = runs.filter((run3) => run3.taskSuccess);
82577
- const totalCost = runs.reduce((sum, run3) => sum + run3.usage.costUsd, 0);
82673
+ const succeeded = runs.filter((run3) => run3.taskSuccess);
82674
+ const priced = price ? runs.filter(split).flatMap((run3) => {
82675
+ const served = price(run3.route.modelId, run3.route.provider);
82676
+ const baseline = run3.route.baselineModelId && price(run3.route.baselineModelId, run3.route.provider) || price(standardBaseline, run3.route.provider);
82677
+ return served && baseline ? [{ served: tokensCost(run3, served), baseline: tokensCost(run3, baseline) }] : [];
82678
+ }) : [];
82679
+ const sum = (values) => values.reduce((total, value) => total + value, 0);
82680
+ const totalCost = runs.reduce((total, run3) => total + run3.usage.costUsd, 0);
82578
82681
  return {
82579
82682
  date: date5,
82580
82683
  taskKind,
82581
82684
  runs: runs.length,
82582
- costPerCompleted: completed.length ? totalCost / completed.length : null,
82583
- successRate: completed.length / runs.length,
82685
+ costPerCompleted: succeeded.length ? totalCost / succeeded.length : null,
82686
+ successRate: succeeded.length / runs.length,
82687
+ completionRate: runs.filter(completed).length / runs.length,
82688
+ listPriceCostUsd: priced.length ? sum(priced.map((run3) => run3.served)) : null,
82689
+ baselineListPriceCostUsd: priced.length ? sum(priced.map((run3) => run3.baseline)) : null,
82690
+ listPriceSavingsUsd: priced.length ? sum(priced.map((run3) => run3.baseline - run3.served)) : null,
82691
+ pricedRuns: priced.length,
82692
+ missingBaselineRuns: runs.filter((run3) => run3.route.baselineModelId === void 0).length,
82693
+ unsplitRuns: runs.filter((run3) => !split(run3)).length,
82584
82694
  avgQuality: mean(runs.map((run3) => run3.quality)),
82585
82695
  avgLatencyMs: mean(runs.map((run3) => run3.latencyMs)),
82586
82696
  avgInputTokens: mean(runs.map((run3) => run3.usage.inputTokens)),
@@ -82591,6 +82701,37 @@ function summarizeRouting(records2) {
82591
82701
  };
82592
82702
  });
82593
82703
  }
82704
+ function summarizeModels(records2, price) {
82705
+ const groups = /* @__PURE__ */ new Map();
82706
+ for (const record5 of records2) {
82707
+ if (record5.route.arm === "control") continue;
82708
+ const kind = record5.task.type ?? record5.task.kind;
82709
+ const key = [
82710
+ record5.settledAt.slice(0, 10),
82711
+ kind,
82712
+ record5.route.modelId,
82713
+ record5.route.provider
82714
+ ].join("\0");
82715
+ groups.set(key, [...groups.get(key) ?? [], record5]);
82716
+ }
82717
+ const sum = (values) => values.reduce((total, value) => total + value, 0);
82718
+ return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, runs]) => {
82719
+ const [date5, taskKind, modelId, provider] = key.split("\0");
82720
+ const rate = price?.(modelId, provider);
82721
+ return {
82722
+ date: date5,
82723
+ taskKind,
82724
+ modelId,
82725
+ provider,
82726
+ billing: isSubscription(provider) ? "subscription" : "per-token",
82727
+ runs: runs.length,
82728
+ completedRuns: runs.filter(completed).length,
82729
+ inputTokens: sum(runs.map((run3) => run3.usage.inputTokens)),
82730
+ outputTokens: sum(runs.map((run3) => run3.usage.outputTokens)),
82731
+ listPriceCostUsd: rate && runs.some(split) ? sum(runs.filter(split).map((run3) => tokensCost(run3, rate))) : null
82732
+ };
82733
+ });
82734
+ }
82594
82735
 
82595
82736
  // bizzy-routing/api/src/trial-report.ts
82596
82737
  var mean2 = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
@@ -82598,21 +82739,21 @@ function summarizeWindow(records2) {
82598
82739
  const groups = /* @__PURE__ */ new Map();
82599
82740
  for (const record5 of records2) {
82600
82741
  if (!record5.route.arm) continue;
82601
- const key = `${record5.route.arm}\0${record5.task.kind}`;
82742
+ const key = `${record5.route.arm}\0${record5.task.type ?? record5.task.kind}`;
82602
82743
  const group = groups.get(key) ?? [];
82603
82744
  group.push(record5);
82604
82745
  groups.set(key, group);
82605
82746
  }
82606
82747
  return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, runs]) => {
82607
82748
  const [arm, taskKind] = key.split("\0");
82608
- const completed = runs.filter((run3) => run3.taskSuccess);
82749
+ const completed2 = runs.filter((run3) => run3.taskSuccess);
82609
82750
  const totalCost = runs.reduce((sum, run3) => sum + run3.usage.costUsd, 0);
82610
82751
  return {
82611
82752
  arm,
82612
82753
  taskKind,
82613
82754
  runs: runs.length,
82614
- costPerCompleted: completed.length ? totalCost / completed.length : null,
82615
- successRate: completed.length / runs.length,
82755
+ costPerCompleted: completed2.length ? totalCost / completed2.length : null,
82756
+ successRate: completed2.length / runs.length,
82616
82757
  avgQuality: mean2(runs.map((run3) => run3.quality)),
82617
82758
  avgLatencyMs: mean2(runs.map((run3) => run3.latencyMs))
82618
82759
  };
@@ -82728,9 +82869,13 @@ function createRoutingServer(options) {
82728
82869
  const window2 = options.trialWindow?.load();
82729
82870
  return trialReport(options.trialRuns?.() ?? [], window2 ? openWindowOf(window2) : null);
82730
82871
  });
82731
- app.get("/v1/routing-report", reportGuard, async () => ({
82732
- rows: summarizeRouting(options.allRuns?.() ?? [])
82733
- }));
82872
+ app.get("/v1/routing-report", reportGuard, async () => {
82873
+ const catalog = await options.catalog?.().catch(() => null);
82874
+ const aliases = await options.aliases?.().catch(() => void 0) ?? {};
82875
+ const runs = options.allRuns?.() ?? [];
82876
+ const price = catalog ? catalogPrice(catalog, aliases) : void 0;
82877
+ return { rows: summarizeRouting(runs, price), models: summarizeModels(runs, price) };
82878
+ });
82734
82879
  app.post("/v1/route", guarded, async (request, reply) => {
82735
82880
  let parsed2;
82736
82881
  try {
@@ -83113,7 +83258,7 @@ function claudeHarness(profile) {
83113
83258
  return { harnessId: "claude-code", provider: "anthropic", ...profile ? { profile } : {} };
83114
83259
  }
83115
83260
  function ompHarness() {
83116
- return { harnessId: "omp" };
83261
+ return { harnessId: "omp", subscriptionFirst: true };
83117
83262
  }
83118
83263
  function codexRelay(env) {
83119
83264
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bizzywork/routing",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "type": "module",
5
5
  "description": "Bizzy Auto routing for Claude Code, oh-my-pi and Codex: npx @bizzywork/routing install <harness>.",
6
6
  "license": "SEE LICENSE IN LICENSE",