@bizzywork/routing 0.2.0 → 0.4.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.
@@ -7419,7 +7419,7 @@ var require_public_api = __commonJS({
7419
7419
  }
7420
7420
  return doc;
7421
7421
  }
7422
- function parse4(src, reviver, options) {
7422
+ function parse6(src, reviver, options) {
7423
7423
  let _reviver = void 0;
7424
7424
  if (typeof reviver === "function") {
7425
7425
  _reviver = reviver;
@@ -7460,7 +7460,7 @@ var require_public_api = __commonJS({
7460
7460
  return value.toString(options);
7461
7461
  return new Document.Document(value, _replacer, options).toString(options);
7462
7462
  }
7463
- exports.parse = parse4;
7463
+ exports.parse = parse6;
7464
7464
  exports.parseAllDocuments = parseAllDocuments;
7465
7465
  exports.parseDocument = parseDocument;
7466
7466
  exports.stringify = stringify;
@@ -8357,7 +8357,7 @@ var require_fast_uri = __commonJS({
8357
8357
  normalizeString(uri, options);
8358
8358
  } else if (typeof uri === "object") {
8359
8359
  uri = /** @type {T} */
8360
- parse4(serialize(uri, options), options);
8360
+ parse6(serialize(uri, options), options);
8361
8361
  }
8362
8362
  return uri;
8363
8363
  }
@@ -8400,8 +8400,8 @@ var require_fast_uri = __commonJS({
8400
8400
  function resolveComponent(base, relative, options, skipNormalization) {
8401
8401
  const target = {};
8402
8402
  if (!skipNormalization) {
8403
- base = parse4(serialize(base, options), options);
8404
- relative = parse4(serialize(relative, options), options);
8403
+ base = parse6(serialize(base, options), options);
8404
+ relative = parse6(serialize(relative, options), options);
8405
8405
  }
8406
8406
  options = options || {};
8407
8407
  if (!options.tolerant && relative.scheme) {
@@ -8719,7 +8719,7 @@ var require_fast_uri = __commonJS({
8719
8719
  }
8720
8720
  return { parsed: parsed2, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
8721
8721
  }
8722
- function parse4(uri, opts) {
8722
+ function parse6(uri, opts) {
8723
8723
  return parseWithStatus(uri, opts).parsed;
8724
8724
  }
8725
8725
  function normalizeString(uri, opts) {
@@ -8756,7 +8756,7 @@ var require_fast_uri = __commonJS({
8756
8756
  resolveComponent,
8757
8757
  equal,
8758
8758
  serialize,
8759
- parse: parse4
8759
+ parse: parse6
8760
8760
  };
8761
8761
  module.exports = fastUri;
8762
8762
  module.exports.default = fastUri;
@@ -8966,7 +8966,7 @@ var require_ms = __commonJS({
8966
8966
  options = options || {};
8967
8967
  var type = typeof val;
8968
8968
  if (type === "string" && val.length > 0) {
8969
- return parse4(val);
8969
+ return parse6(val);
8970
8970
  } else if (type === "number" && isFinite(val)) {
8971
8971
  return options.long ? fmtLong(val) : fmtShort(val);
8972
8972
  }
@@ -8974,7 +8974,7 @@ var require_ms = __commonJS({
8974
8974
  "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
8975
8975
  );
8976
8976
  };
8977
- function parse4(str) {
8977
+ function parse6(str) {
8978
8978
  str = String(str);
8979
8979
  if (str.length > 100) {
8980
8980
  return;
@@ -15057,7 +15057,7 @@ var require_dist2 = __commonJS({
15057
15057
  var HOUR = MIN * 60;
15058
15058
  var DAY = HOUR * 24;
15059
15059
  var YEAR = DAY * 365.25;
15060
- function parse4(val) {
15060
+ function parse6(val) {
15061
15061
  var num, arr = val.toLowerCase().match(RGX);
15062
15062
  if (arr != null && (num = parseFloat(arr[1]))) {
15063
15063
  if (arr[3] != null) return num * SEC;
@@ -15083,7 +15083,7 @@ var require_dist2 = __commonJS({
15083
15083
  return fmt(abs / YEAR, pfx, "year", long);
15084
15084
  }
15085
15085
  exports.format = format2;
15086
- exports.parse = parse4;
15086
+ exports.parse = parse6;
15087
15087
  }
15088
15088
  });
15089
15089
 
@@ -16546,14 +16546,14 @@ var require_accept_negotiator = __commonJS({
16546
16546
  }
16547
16547
  return false;
16548
16548
  }
16549
- parse4(header, processMatch);
16549
+ parse6(header, processMatch);
16550
16550
  return preferredEncoding;
16551
16551
  }
16552
16552
  var BEGIN = 0;
16553
16553
  var TOKEN = 1;
16554
16554
  var QUALITY = 2;
16555
16555
  var END = 3;
16556
- function parse4(header, processMatch) {
16556
+ function parse6(header, processMatch) {
16557
16557
  let str = "";
16558
16558
  let quality;
16559
16559
  let state = BEGIN;
@@ -30393,10 +30393,10 @@ var require_forwarded = __commonJS({
30393
30393
  const remote = header.trim();
30394
30394
  return remote.length ? [socketAddr, remote] : [socketAddr];
30395
30395
  } else {
30396
- return parse4(header, socketAddr);
30396
+ return parse6(header, socketAddr);
30397
30397
  }
30398
30398
  }
30399
- function parse4(header, socketAddr) {
30399
+ function parse6(header, socketAddr) {
30400
30400
  const result = [socketAddr];
30401
30401
  let end = header.length;
30402
30402
  let start = end;
@@ -31914,7 +31914,7 @@ var require_secure_json_parse = __commonJS({
31914
31914
  }
31915
31915
  return obj;
31916
31916
  }
31917
- function parse4(text, reviver, options) {
31917
+ function parse6(text, reviver, options) {
31918
31918
  const { stackTraceLimit } = Error;
31919
31919
  Error.stackTraceLimit = 0;
31920
31920
  try {
@@ -31936,9 +31936,9 @@ var require_secure_json_parse = __commonJS({
31936
31936
  }
31937
31937
  return result;
31938
31938
  }
31939
- module.exports = parse4;
31940
- module.exports.default = parse4;
31941
- module.exports.parse = parse4;
31939
+ module.exports = parse6;
31940
+ module.exports.default = parse6;
31941
+ module.exports.parse = parse6;
31942
31942
  module.exports.safeParse = safeParse3;
31943
31943
  module.exports.scan = filter;
31944
31944
  }
@@ -36133,7 +36133,7 @@ var require_fast_uri2 = __commonJS({
36133
36133
  normalizeString(uri, options);
36134
36134
  } else if (typeof uri === "object") {
36135
36135
  uri = /** @type {T} */
36136
- parse4(serialize(uri, options), options);
36136
+ parse6(serialize(uri, options), options);
36137
36137
  }
36138
36138
  return uri;
36139
36139
  }
@@ -36176,8 +36176,8 @@ var require_fast_uri2 = __commonJS({
36176
36176
  function resolveComponent(base, relative, options, skipNormalization) {
36177
36177
  const target = {};
36178
36178
  if (!skipNormalization) {
36179
- base = parse4(serialize(base, options), options);
36180
- relative = parse4(serialize(relative, options), options);
36179
+ base = parse6(serialize(base, options), options);
36180
+ relative = parse6(serialize(relative, options), options);
36181
36181
  }
36182
36182
  options = options || {};
36183
36183
  if (!options.tolerant && relative.scheme) {
@@ -36495,7 +36495,7 @@ var require_fast_uri2 = __commonJS({
36495
36495
  }
36496
36496
  return { parsed: parsed2, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
36497
36497
  }
36498
- function parse4(uri, opts) {
36498
+ function parse6(uri, opts) {
36499
36499
  return parseWithStatus(uri, opts).parsed;
36500
36500
  }
36501
36501
  function normalizeString(uri, opts) {
@@ -36532,7 +36532,7 @@ var require_fast_uri2 = __commonJS({
36532
36532
  resolveComponent,
36533
36533
  equal,
36534
36534
  serialize,
36535
- parse: parse4
36535
+ parse: parse6
36536
36536
  };
36537
36537
  module.exports = fastUri;
36538
36538
  module.exports.default = fastUri;
@@ -40507,9 +40507,9 @@ var require_parse = __commonJS({
40507
40507
  const parseFuncCode = gen.toString();
40508
40508
  sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
40509
40509
  const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
40510
- const parse4 = makeParse(this.scope.get());
40511
- this.scope.value(parseName, { ref: parse4 });
40512
- sch.parse = parse4;
40510
+ const parse6 = makeParse(this.scope.get());
40511
+ this.scope.value(parseName, { ref: parse6 });
40512
+ sch.parse = parse6;
40513
40513
  } catch (e) {
40514
40514
  if (sourceCode)
40515
40515
  this.logger.error("Error compiling parser, function code:", sourceCode);
@@ -41961,7 +41961,7 @@ var require_fast_uri3 = __commonJS({
41961
41961
  normalizeString(uri, options);
41962
41962
  } else if (typeof uri === "object") {
41963
41963
  uri = /** @type {T} */
41964
- parse4(serialize(uri, options), options);
41964
+ parse6(serialize(uri, options), options);
41965
41965
  }
41966
41966
  return uri;
41967
41967
  }
@@ -42018,8 +42018,8 @@ var require_fast_uri3 = __commonJS({
42018
42018
  function resolveComponent(base, relative, options, skipNormalization) {
42019
42019
  const target = {};
42020
42020
  if (!skipNormalization) {
42021
- base = parse4(serialize(base, options), options);
42022
- relative = parse4(serialize(relative, options), options);
42021
+ base = parse6(serialize(base, options), options);
42022
+ relative = parse6(serialize(relative, options), options);
42023
42023
  }
42024
42024
  options = options || {};
42025
42025
  if (!options.tolerant && relative.scheme) {
@@ -42358,7 +42358,7 @@ var require_fast_uri3 = __commonJS({
42358
42358
  }
42359
42359
  return { parsed: parsed2, malformedAuthorityOrPort, malformedReferenceEdge, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
42360
42360
  }
42361
- function parse4(uri, opts) {
42361
+ function parse6(uri, opts) {
42362
42362
  return parseWithStatus(uri, opts).parsed;
42363
42363
  }
42364
42364
  function normalizeString(uri, opts) {
@@ -42396,7 +42396,7 @@ var require_fast_uri3 = __commonJS({
42396
42396
  resolveComponent,
42397
42397
  equal,
42398
42398
  serialize,
42399
- parse: parse4
42399
+ parse: parse6
42400
42400
  };
42401
42401
  module.exports = fastUri;
42402
42402
  module.exports.default = fastUri;
@@ -47130,7 +47130,7 @@ var require_parse2 = __commonJS({
47130
47130
  "node_modules/semver/functions/parse.js"(exports, module) {
47131
47131
  "use strict";
47132
47132
  var SemVer = require_semver();
47133
- var parse4 = (version2, options, throwErrors = false) => {
47133
+ var parse6 = (version2, options, throwErrors = false) => {
47134
47134
  if (version2 instanceof SemVer) {
47135
47135
  return version2;
47136
47136
  }
@@ -47143,7 +47143,7 @@ var require_parse2 = __commonJS({
47143
47143
  throw er;
47144
47144
  }
47145
47145
  };
47146
- module.exports = parse4;
47146
+ module.exports = parse6;
47147
47147
  }
47148
47148
  });
47149
47149
 
@@ -47151,9 +47151,9 @@ var require_parse2 = __commonJS({
47151
47151
  var require_valid = __commonJS({
47152
47152
  "node_modules/semver/functions/valid.js"(exports, module) {
47153
47153
  "use strict";
47154
- var parse4 = require_parse2();
47154
+ var parse6 = require_parse2();
47155
47155
  var valid = (version2, options) => {
47156
- const v = parse4(version2, options);
47156
+ const v = parse6(version2, options);
47157
47157
  return v ? v.version : null;
47158
47158
  };
47159
47159
  module.exports = valid;
@@ -47164,9 +47164,9 @@ var require_valid = __commonJS({
47164
47164
  var require_clean = __commonJS({
47165
47165
  "node_modules/semver/functions/clean.js"(exports, module) {
47166
47166
  "use strict";
47167
- var parse4 = require_parse2();
47167
+ var parse6 = require_parse2();
47168
47168
  var clean = (version2, options) => {
47169
- const s = parse4(version2.trim().replace(/^[=v]+/, ""), options);
47169
+ const s = parse6(version2.trim().replace(/^[=v]+/, ""), options);
47170
47170
  return s ? s.version : null;
47171
47171
  };
47172
47172
  module.exports = clean;
@@ -47201,10 +47201,10 @@ var require_inc = __commonJS({
47201
47201
  var require_diff = __commonJS({
47202
47202
  "node_modules/semver/functions/diff.js"(exports, module) {
47203
47203
  "use strict";
47204
- var parse4 = require_parse2();
47204
+ var parse6 = require_parse2();
47205
47205
  var diff = (version1, version2) => {
47206
- const v1 = parse4(version1, null, true);
47207
- const v2 = parse4(version2, null, true);
47206
+ const v1 = parse6(version1, null, true);
47207
+ const v2 = parse6(version2, null, true);
47208
47208
  const comparison = v1.compare(v2);
47209
47209
  if (comparison === 0) {
47210
47210
  return null;
@@ -47275,9 +47275,9 @@ var require_patch = __commonJS({
47275
47275
  var require_prerelease = __commonJS({
47276
47276
  "node_modules/semver/functions/prerelease.js"(exports, module) {
47277
47277
  "use strict";
47278
- var parse4 = require_parse2();
47278
+ var parse6 = require_parse2();
47279
47279
  var prerelease = (version2, options) => {
47280
- const parsed2 = parse4(version2, options);
47280
+ const parsed2 = parse6(version2, options);
47281
47281
  return parsed2 && parsed2.prerelease.length ? parsed2.prerelease : null;
47282
47282
  };
47283
47283
  module.exports = prerelease;
@@ -47463,7 +47463,7 @@ var require_coerce = __commonJS({
47463
47463
  "node_modules/semver/functions/coerce.js"(exports, module) {
47464
47464
  "use strict";
47465
47465
  var SemVer = require_semver();
47466
- var parse4 = require_parse2();
47466
+ var parse6 = require_parse2();
47467
47467
  var { safeRe: re, t } = require_re();
47468
47468
  var coerce = (version2, options) => {
47469
47469
  if (version2 instanceof SemVer) {
@@ -47498,7 +47498,7 @@ var require_coerce = __commonJS({
47498
47498
  const patch = match[4] || "0";
47499
47499
  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
47500
47500
  const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
47501
- return parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options);
47501
+ return parse6(`${major}.${minor}.${patch}${prerelease}${build}`, options);
47502
47502
  };
47503
47503
  module.exports = coerce;
47504
47504
  }
@@ -47508,7 +47508,7 @@ var require_coerce = __commonJS({
47508
47508
  var require_truncate = __commonJS({
47509
47509
  "node_modules/semver/functions/truncate.js"(exports, module) {
47510
47510
  "use strict";
47511
- var parse4 = require_parse2();
47511
+ var parse6 = require_parse2();
47512
47512
  var constants5 = require_constants4();
47513
47513
  var SemVer = require_semver();
47514
47514
  var truncate = (version2, truncation, options) => {
@@ -47520,7 +47520,7 @@ var require_truncate = __commonJS({
47520
47520
  };
47521
47521
  var cloneInputVersion = (version2, options) => {
47522
47522
  const versionStringToParse = version2 instanceof SemVer ? version2.version : version2;
47523
- return parse4(versionStringToParse, options);
47523
+ return parse6(versionStringToParse, options);
47524
47524
  };
47525
47525
  var doTruncation = (version2, truncation) => {
47526
47526
  if (isPrerelease(truncation)) {
@@ -48564,7 +48564,7 @@ var require_semver2 = __commonJS({
48564
48564
  var constants5 = require_constants4();
48565
48565
  var SemVer = require_semver();
48566
48566
  var identifiers = require_identifiers();
48567
- var parse4 = require_parse2();
48567
+ var parse6 = require_parse2();
48568
48568
  var valid = require_valid();
48569
48569
  var clean = require_clean();
48570
48570
  var inc = require_inc();
@@ -48603,7 +48603,7 @@ var require_semver2 = __commonJS({
48603
48603
  var simplifyRange = require_simplify();
48604
48604
  var subset = require_subset();
48605
48605
  module.exports = {
48606
- parse: parse4,
48606
+ parse: parse6,
48607
48607
  valid,
48608
48608
  clean,
48609
48609
  inc,
@@ -48831,7 +48831,7 @@ var require_parse3 = __commonJS({
48831
48831
  var Empty = function() {
48832
48832
  };
48833
48833
  Empty.prototype = /* @__PURE__ */ Object.create(null);
48834
- function parse4(input2) {
48834
+ function parse6(input2) {
48835
48835
  const result = new Empty();
48836
48836
  if (typeof input2 !== "string") {
48837
48837
  return result;
@@ -48911,7 +48911,7 @@ var require_parse3 = __commonJS({
48911
48911
  }
48912
48912
  return result;
48913
48913
  }
48914
- module.exports = parse4;
48914
+ module.exports = parse6;
48915
48915
  }
48916
48916
  });
48917
48917
 
@@ -49163,15 +49163,15 @@ var require_stringify2 = __commonJS({
49163
49163
  var require_lib = __commonJS({
49164
49164
  "node_modules/fast-querystring/lib/index.js"(exports, module) {
49165
49165
  "use strict";
49166
- var parse4 = require_parse3();
49166
+ var parse6 = require_parse3();
49167
49167
  var stringify = require_stringify2();
49168
49168
  var fastQuerystring = {
49169
- parse: parse4,
49169
+ parse: parse6,
49170
49170
  stringify
49171
49171
  };
49172
49172
  module.exports = fastQuerystring;
49173
49173
  module.exports.default = fastQuerystring;
49174
- module.exports.parse = parse4;
49174
+ module.exports.parse = parse6;
49175
49175
  module.exports.stringify = stringify;
49176
49176
  }
49177
49177
  });
@@ -49971,7 +49971,7 @@ var require_dist5 = __commonJS({
49971
49971
  var require_safe_regex2 = __commonJS({
49972
49972
  "node_modules/safe-regex2/index.js"(exports, module) {
49973
49973
  "use strict";
49974
- var parse4 = require_dist5();
49974
+ var parse6 = require_dist5();
49975
49975
  var { types } = require_dist5();
49976
49976
  function walk(node2, opts, starHeight) {
49977
49977
  let i;
@@ -50006,7 +50006,7 @@ var require_safe_regex2 = __commonJS({
50006
50006
  if (isRegExp(re)) re = re.source;
50007
50007
  else if (typeof re !== "string") re = String(re);
50008
50008
  try {
50009
- return walk(parse4(re), opts, 0);
50009
+ return walk(parse6(re), opts, 0);
50010
50010
  } catch {
50011
50011
  return false;
50012
50012
  }
@@ -58570,18 +58570,18 @@ var validateAsync = async (schema, value, _ctx) => {
58570
58570
  return result.issues.length === 0;
58571
58571
  };
58572
58572
  var _encode = (_Err) => {
58573
- const parse4 = _parse(_Err);
58573
+ const parse6 = _parse(_Err);
58574
58574
  const fn = (schema, value, _ctx, _params) => {
58575
58575
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
58576
- return parse4(schema, value, ctx, finalizeParams(fn, _params));
58576
+ return parse6(schema, value, ctx, finalizeParams(fn, _params));
58577
58577
  };
58578
58578
  return fn;
58579
58579
  };
58580
58580
  var encode = /* @__PURE__ */ _encode($ZodRealError);
58581
58581
  var _decode = (_Err) => {
58582
- const parse4 = _parse(_Err);
58582
+ const parse6 = _parse(_Err);
58583
58583
  const fn = (schema, value, _ctx, _params) => {
58584
- return parse4(schema, value, _ctx, finalizeParams(fn, _params));
58584
+ return parse6(schema, value, _ctx, finalizeParams(fn, _params));
58585
58585
  };
58586
58586
  return fn;
58587
58587
  };
@@ -60076,7 +60076,7 @@ function capSize(inst, size) {
60076
60076
  if (!caps.length)
60077
60077
  return;
60078
60078
  const cap = Math.min(...caps.map((c) => c[0]));
60079
- const parse4 = inst._zod.parse;
60079
+ const parse6 = inst._zod.parse;
60080
60080
  inst._zod.parse = (payload, ctx) => {
60081
60081
  const n = size(payload.value);
60082
60082
  if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
@@ -60090,7 +60090,7 @@ function capSize(inst, size) {
60090
60090
  }
60091
60091
  }
60092
60092
  }
60093
- return parse4(payload, ctx);
60093
+ return parse6(payload, ctx);
60094
60094
  };
60095
60095
  }
60096
60096
  var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1;
@@ -76470,7 +76470,8 @@ var DecisionSourceSchema = external_exports.enum([
76470
76470
  "stage",
76471
76471
  "plan-execute",
76472
76472
  "escalation",
76473
- "judge-select"
76473
+ "judge-select",
76474
+ "judge-grade"
76474
76475
  ]);
76475
76476
  var TaskEnvelopeSchema = external_exports.object({
76476
76477
  version: external_exports.literal("2"),
@@ -76520,7 +76521,20 @@ var RunRecordSchema = external_exports.object({
76520
76521
  /** The judge's P(advantage), 0–1, when its verdict routed the run; validation calibrates the cutoff from it. */
76521
76522
  judgeAdvantage: UnitSchema.exactOptional(),
76522
76523
  /** Set when a calibration trial served the rule against the judge's verdict. */
76523
- judgeTrial: external_exports.boolean().exactOptional()
76524
+ judgeTrial: external_exports.boolean().exactOptional(),
76525
+ /** The judge's own token usage for this run's route call, regardless of which strategy asked it.
76526
+ * `costUsd` is null when no judge price was configured, not a guessed number. */
76527
+ judgeUsage: external_exports.object({
76528
+ inputTokens: CountSchema,
76529
+ outputTokens: CountSchema,
76530
+ costUsd: external_exports.number().min(0).nullable()
76531
+ }).exactOptional(),
76532
+ /** Set by the caller when a live routing-vs-control comparison chose this run's arm;
76533
+ * unset outside a comparison. The caller decides the arm itself and reports it here —
76534
+ * bizzy-v2 never sees or sets it. */
76535
+ arm: external_exports.enum(["treatment", "control"]).exactOptional(),
76536
+ /** The comparison window this run belongs to, when `arm` is set. */
76537
+ windowId: SafeIdSchema.exactOptional()
76524
76538
  }),
76525
76539
  startedAt: IsoDateSchema,
76526
76540
  settledAt: IsoDateSchema,
@@ -76583,6 +76597,7 @@ function validateRoutingState(value) {
76583
76597
  }
76584
76598
 
76585
76599
  // bizzy-routing/contracts/src/step.ts
76600
+ var gradeQuestionId = (rank) => `grade_${rank}`;
76586
76601
  function answerSchema(question) {
76587
76602
  switch (question.kind) {
76588
76603
  case "yes-no":
@@ -76609,6 +76624,7 @@ function validateTurnSignals(input2) {
76609
76624
  }
76610
76625
 
76611
76626
  // bizzy-routing/contracts/src/schemas/step.ts
76627
+ var OpenWindowSchema = external_exports.object({ id: SafeIdSchema, controlRatio: UnitSchema });
76612
76628
  var RouteDecisionSchema = external_exports.object({
76613
76629
  model: ModelCandidateSchema,
76614
76630
  mode: ModeSchema,
@@ -76637,7 +76653,9 @@ var DoneStepSchema = external_exports.object({
76637
76653
  decision: RouteDecisionSchema,
76638
76654
  state: RoutingStateSchema,
76639
76655
  /** Set by the host when a question went unanswered, so the decision is the rules' alone; for the user to see. */
76640
- notice: external_exports.string().exactOptional()
76656
+ notice: external_exports.string().exactOptional(),
76657
+ /** Set when a live routing-vs-control comparison is open; unset otherwise. */
76658
+ window: OpenWindowSchema.exactOptional()
76641
76659
  });
76642
76660
  var StepSchema = external_exports.discriminatedUnion("kind", [AskJudgeStepSchema, DoneStepSchema]);
76643
76661
 
@@ -76647,9 +76665,14 @@ var strategies = [
76647
76665
  "stage",
76648
76666
  "plan-execute",
76649
76667
  "escalate",
76650
- "judge-select"
76668
+ "judge-select",
76669
+ "judge-grade"
76670
+ ];
76671
+ var profiles = [
76672
+ "jev",
76673
+ "cascade",
76674
+ "jev-grade"
76651
76675
  ];
76652
- var profiles = ["jev", "cascade"];
76653
76676
  var maximumCandidates = 64;
76654
76677
  var maximumSummary = 8e3;
76655
76678
  var RouteBodySchema = external_exports.strictObject({
@@ -76725,7 +76748,9 @@ __export(src_exports, {
76725
76748
  getPromoted: () => getPromoted,
76726
76749
  has: () => has,
76727
76750
  isTrialDue: () => isTrialDue,
76751
+ jevGradeProfile: () => jevGradeProfile,
76728
76752
  jevProfile: () => jevProfile,
76753
+ judgeGradeStrategy: () => judgeGradeStrategy,
76729
76754
  judgeSelectConstants: () => judgeSelectConstants,
76730
76755
  judgeSelectStrategy: () => judgeSelectStrategy,
76731
76756
  list: () => list,
@@ -76776,6 +76801,7 @@ var cascadeProfile = {
76776
76801
  trigger: "new-session",
76777
76802
  context: "summary"
76778
76803
  };
76804
+ var jevGradeProfile = { name: "jev-grade" };
76779
76805
 
76780
76806
  // bizzy-routing/decision/src/registry/memory-store.ts
76781
76807
  var entryKey = (id2, taskType) => `${taskType}::${id2}`;
@@ -77132,10 +77158,13 @@ var harnessFor = (mode) => mode === "enhance" ? "robust" : "standard";
77132
77158
  function effectiveFloor(task, mode) {
77133
77159
  return mode === "enhance" ? Math.max(task.qualityFloor, task.risk === "high" ? 0.9 : 0.75) : task.qualityFloor;
77134
77160
  }
77135
- function contextFor(input2) {
77136
- const permitted = input2.candidates.filter(
77161
+ function permittedCandidates(input2) {
77162
+ return input2.candidates.filter(
77137
77163
  (candidate) => candidate.available && candidate.credentialed && (input2.accessible?.(candidate.id) ?? true) && (candidate.provider !== "openrouter" || input2.allowOpenRouter === true)
77138
77164
  );
77165
+ }
77166
+ function contextFor(input2) {
77167
+ const permitted = permittedCandidates(input2);
77139
77168
  const context = {
77140
77169
  input: input2,
77141
77170
  floor: effectiveFloor(input2.task, input2.mode),
@@ -77307,6 +77336,38 @@ function escalateStrategy(constants5 = escalationConstants) {
77307
77336
  };
77308
77337
  }
77309
77338
 
77339
+ // bizzy-routing/decision/src/strategies/judge-grade.ts
77340
+ var judgeGradeStrategy = function* (input2) {
77341
+ const state = validateRoutingState(input2.state);
77342
+ const base = cascade(input2, [pin, trial, registry2, history, coldStart]);
77343
+ if (input2.pin) return { kind: "done", decision: base, state };
77344
+ const ranked = [...permittedCandidates(input2)].sort((a, b) => a.costPer1k - b.costPer1k);
77345
+ if (!ranked.length) return { kind: "done", decision: base, state };
77346
+ const questions2 = ranked.map((_, i) => ({
77347
+ id: gradeQuestionId(i + 1),
77348
+ kind: "score",
77349
+ min: 0,
77350
+ max: 1
77351
+ }));
77352
+ const result = yield { kind: "ask-judge", questions: questions2, context: "summary" };
77353
+ if (result.kind !== "answers") return { kind: "done", decision: base, state };
77354
+ const winner = ranked.find((_, i) => {
77355
+ const answer = result.answers[gradeQuestionId(i + 1)];
77356
+ return typeof answer === "number" && answer > 0.5;
77357
+ });
77358
+ if (!winner || winner === base.model) return { kind: "done", decision: base, state };
77359
+ return {
77360
+ kind: "done",
77361
+ decision: decisionForModel(
77362
+ base,
77363
+ winner,
77364
+ "judge-grade",
77365
+ "judge-grade: cheapest candidate Jev rated capable of the task"
77366
+ ),
77367
+ state
77368
+ };
77369
+ };
77370
+
77310
77371
  // bizzy-routing/decision/src/strategies/judge-select.ts
77311
77372
  var judgeSelectConstants = { cutoff: 0.05, margin: defaultMargin };
77312
77373
  function judgeSelectStrategy(constants5 = judgeSelectConstants) {
@@ -77404,12 +77465,14 @@ var strategies2 = {
77404
77465
  stage: (tuning) => stageStrategy(tuning.stage),
77405
77466
  "plan-execute": () => planExecuteStrategy,
77406
77467
  escalate: (tuning) => escalateStrategy(tuning.escalation),
77407
- "judge-select": (tuning) => judgeSelectStrategy(tuning.judgeSelect)
77468
+ "judge-select": (tuning) => judgeSelectStrategy(tuning.judgeSelect),
77469
+ "judge-grade": () => judgeGradeStrategy
77408
77470
  };
77409
77471
  function plan(input2) {
77410
77472
  const tuning = input2.tuning ?? {};
77411
77473
  if (input2.strategy) return strategies2[input2.strategy](tuning)(input2);
77412
77474
  const profile = input2.profile ?? jevProfile;
77475
+ if (profile.name === "jev-grade") return judgeGradeStrategy(input2);
77413
77476
  const profiled = { ...input2, margin: input2.margin ?? profile.margin };
77414
77477
  if (profile.name === "cascade") return cascadeStrategy(profiled);
77415
77478
  return judgeSelectStrategy({
@@ -77464,8 +77527,8 @@ function routeFromRegistry(input2) {
77464
77527
 
77465
77528
  // bizzy-routing/decision/src/benchmarks.ts
77466
77529
  function deviation(values) {
77467
- const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
77468
- return Math.sqrt(values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length);
77530
+ const mean3 = values.reduce((sum, value) => sum + value, 0) / values.length;
77531
+ return Math.sqrt(values.reduce((sum, value) => sum + (value - mean3) ** 2, 0) / values.length);
77469
77532
  }
77470
77533
  function intelligenceScale(catalog) {
77471
77534
  const both = catalog.filter(
@@ -81308,23 +81371,36 @@ async function routeInput(envelope, options) {
81308
81371
  };
81309
81372
  }
81310
81373
  function profileFor({ envelope, material }) {
81311
- return envelope.profile === "cascade" || material.policy === "none" ? cascadeProfile : jevProfile;
81374
+ if (material.policy === "none") return cascadeProfile;
81375
+ if (envelope.profile === "cascade") return cascadeProfile;
81376
+ if (envelope.profile === "jev-grade") return jevGradeProfile;
81377
+ return jevProfile;
81312
81378
  }
81313
81379
  var routeNotices = {
81314
81380
  absent: "no OpenRouter key: routing with Bizzy's own rules",
81315
81381
  failed: "Jev did not answer: routing with Bizzy's own rules"
81316
81382
  };
81383
+ var noContextNotice = "no context set: routing with Bizzy's own rules";
81317
81384
  async function routeSteps(body, options, onStep, signal) {
81318
- return driveRoute(body, await routeInput(body.envelope, options), options, onStep, signal);
81319
- }
81320
- function driveRoute(body, input2, options, onStep = () => {
81321
- }, signal) {
81322
- const executor = options.judgeFor ? withContextPolicy(body.material.policy, options.judgeFor(body.material)) : void 0;
81385
+ const done = await driveRoute(body, await routeInput(body.envelope, options), options, {
81386
+ onStep,
81387
+ ...signal ? { signal } : {}
81388
+ });
81389
+ const implicitCascade = body.envelope.profile !== "cascade" && body.material.policy === "none";
81390
+ return implicitCascade && !done.notice ? { ...done, notice: noContextNotice } : done;
81391
+ }
81392
+ function driveRoute(body, input2, options, extra = {}) {
81393
+ const judgeUsage = extra.judgeUsage ?? { inputTokens: 0, outputTokens: 0 };
81394
+ const executor = options.judgeFor ? withContextPolicy(
81395
+ body.material.policy,
81396
+ options.judgeFor(body.material, input2.candidates.length, judgeUsage)
81397
+ ) : void 0;
81323
81398
  return drive(
81324
81399
  plan({ ...input2, profile: profileFor(body) }),
81325
81400
  executor,
81326
- signal,
81327
- onStep,
81401
+ extra.signal,
81402
+ extra.onStep ?? (() => {
81403
+ }),
81328
81404
  options.notices ?? routeNotices
81329
81405
  );
81330
81406
  }
@@ -81339,6 +81415,12 @@ async function settleBody(raw, options) {
81339
81415
  options.calibration
81340
81416
  );
81341
81417
  }
81418
+ function trialWindowOpenBody(raw) {
81419
+ const controlRatio = typeof raw === "object" && raw !== null ? raw.controlRatio : void 0;
81420
+ if (typeof controlRatio !== "number" || !(controlRatio > 0 && controlRatio < 1))
81421
+ throw new TypeError("controlRatio must be a number strictly between 0 and 1");
81422
+ return controlRatio;
81423
+ }
81342
81424
 
81343
81425
  // bizzy-routing/api/src/harness.ts
81344
81426
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
@@ -81575,6 +81657,7 @@ function harnessOutcomes(messages) {
81575
81657
  function createHarnessRouter(options, server) {
81576
81658
  const sessions = /* @__PURE__ */ new Map();
81577
81659
  const now = options.now ?? Date.now;
81660
+ const random = options.random ?? Math.random;
81578
81661
  const ttl = options.sessionTtlMs ?? 6 * 60 * 60 * 1e3;
81579
81662
  const refusalCooldown = options.refusalCooldownMs ?? 10 * 60 * 1e3;
81580
81663
  const transientCooldown = options.transientCooldownMs ?? 60 * 1e3;
@@ -81607,14 +81690,26 @@ function createHarnessRouter(options, server) {
81607
81690
  sessions.set(key, found);
81608
81691
  return found;
81609
81692
  }
81610
- async function routed(envelope, material, input2, prompt) {
81611
- if (!server.hosted) return driveRoute({ envelope, material }, input2, server);
81693
+ async function withLocalWindow(done) {
81694
+ const window2 = server.trialWindow?.load();
81695
+ return window2 ? { ...done, window: { id: window2.id, controlRatio: window2.controlRatio } } : done;
81696
+ }
81697
+ async function routed(envelope, material, input2, prompt, judgeUsage) {
81698
+ if (!server.hosted)
81699
+ return withLocalWindow(
81700
+ await driveRoute({ envelope, material }, input2, server, { judgeUsage })
81701
+ );
81612
81702
  try {
81613
81703
  return await server.hosted.route(envelope, prompt);
81614
81704
  } catch (error62) {
81615
81705
  const reason = error62 instanceof HostedError ? error62.message : "failed";
81616
- const local = await driveRoute({ envelope, material: { policy: "none" } }, input2, server);
81617
- return { ...local, notice: `hosted routing ${reason}: routing with Bizzy's own rules` };
81706
+ const local = await driveRoute({ envelope, material: { policy: "none" } }, input2, server, {
81707
+ judgeUsage
81708
+ });
81709
+ return withLocalWindow({
81710
+ ...local,
81711
+ notice: `hosted routing ${reason}: routing with Bizzy's own rules`
81712
+ });
81618
81713
  }
81619
81714
  }
81620
81715
  async function decide(current, body, models2, signals) {
@@ -81631,22 +81726,26 @@ function createHarnessRouter(options, server) {
81631
81726
  candidates: models2.pool,
81632
81727
  mode: "auto",
81633
81728
  state: current.state,
81634
- newUserTurn: true
81729
+ newUserTurn: true,
81730
+ ...options.profile ? { profile: options.profile } : {}
81635
81731
  };
81636
81732
  const material = body.prompt ? { policy: "summary", summary: body.prompt } : { policy: "none" };
81637
81733
  const input2 = await routeInput(envelope, server);
81638
- const done = await routed(envelope, material, input2, body.prompt);
81734
+ const judgeUsage = { inputTokens: 0, outputTokens: 0 };
81735
+ const done = await routed(envelope, material, input2, body.prompt, judgeUsage);
81639
81736
  const rule = done.decision.rule === "capable" ? "capable" : "efficient";
81640
81737
  current.state = { ...done.state, tier: rule, capableHold: 0 };
81641
81738
  const sent = server.hosted ? server.hosted.sharesPrompts && body.prompt : body.prompt;
81642
81739
  const notice = done.notice ?? (sent ? void 0 : noPrompt);
81643
81740
  const judged = done.decision.source === "judge-select" && !done.notice;
81741
+ const arm = done.window ? random() < done.window.controlRatio ? "control" : "treatment" : void 0;
81644
81742
  const chosen = {
81645
81743
  model: done.decision.model.id,
81646
81744
  rule,
81647
81745
  source: done.decision.source,
81648
81746
  reason: done.decision.reason,
81649
- ...notice ? { notice } : {}
81747
+ ...notice ? { notice } : {},
81748
+ ...arm ? { arm } : {}
81650
81749
  };
81651
81750
  return {
81652
81751
  chosen,
@@ -81655,6 +81754,8 @@ function createHarnessRouter(options, server) {
81655
81754
  input: input2,
81656
81755
  ...judged && typeof done.state.judgeAdvantage === "number" ? { judgeAdvantage: done.state.judgeAdvantage } : {},
81657
81756
  ...judged && done.state.judgeTrial ? { judgeTrial: true } : {},
81757
+ ...done.window ? { windowId: done.window.id } : {},
81758
+ ...judgeUsage.inputTokens || judgeUsage.outputTokens ? { judgeUsage } : {},
81658
81759
  startedAt: now(),
81659
81760
  signals
81660
81761
  };
@@ -81670,7 +81771,8 @@ function createHarnessRouter(options, server) {
81670
81771
  rule,
81671
81772
  source: "stage",
81672
81773
  reason: capable.reason ? `stage: capable; ${capable.reason}` : "stage: capable",
81673
- ...turn.chosen.notice ? { notice: turn.chosen.notice } : {}
81774
+ ...turn.chosen.notice ? { notice: turn.chosen.notice } : {},
81775
+ ...turn.chosen.arm ? { arm: turn.chosen.arm } : {}
81674
81776
  };
81675
81777
  }
81676
81778
  async function step(body, given) {
@@ -81703,7 +81805,8 @@ function createHarnessRouter(options, server) {
81703
81805
  const decision = {
81704
81806
  ...instead,
81705
81807
  source: failed.source,
81706
- reason: `fallback: ${body.model} ${body.transient ? "failed" : "refused"}`
81808
+ reason: `fallback: ${body.model} ${body.transient ? "failed" : "refused"}`,
81809
+ ...turn?.served.arm ? { arm: turn.served.arm } : {}
81707
81810
  };
81708
81811
  if (turn) turn.served = decision;
81709
81812
  if (current.last?.turnId === body.turnId) current.last = { ...current.last, decision };
@@ -81732,7 +81835,14 @@ function createHarnessRouter(options, server) {
81732
81835
  source: turn.served.source,
81733
81836
  rule: turn.served.rule,
81734
81837
  ...turn.judgeAdvantage === void 0 ? {} : { judgeAdvantage: turn.judgeAdvantage },
81735
- ...turn.judgeTrial ? { judgeTrial: true } : {}
81838
+ ...turn.judgeTrial ? { judgeTrial: true } : {},
81839
+ ...turn.judgeUsage ? {
81840
+ judgeUsage: {
81841
+ ...turn.judgeUsage,
81842
+ costUsd: server.judgePricePer1k ? turn.judgeUsage.inputTokens / 1e3 * server.judgePricePer1k.input + turn.judgeUsage.outputTokens / 1e3 * server.judgePricePer1k.output : null
81843
+ }
81844
+ } : {},
81845
+ ...turn.served.arm ? { arm: turn.served.arm, windowId: turn.windowId } : {}
81736
81846
  },
81737
81847
  startedAt: new Date(turn.startedAt).toISOString(),
81738
81848
  settledAt: new Date(settledAt).toISOString(),
@@ -82055,10 +82165,14 @@ function createCodexRelay(options, server) {
82055
82165
  const list2 = position ? await accountModels(base, forward) : null;
82056
82166
  const matched = position ? await matchedOf(list2) : void 0;
82057
82167
  let model = typeof body.model === "string" ? body.model : void 0;
82168
+ let control = false;
82058
82169
  if (position) {
82059
82170
  try {
82060
82171
  const decision = matched && await router.step({ ...position, compacted: false }, matched);
82061
- model = decision?.model;
82172
+ control = decision?.arm === "control";
82173
+ model = control ? visibleModels(list2)[0]?.slug : decision?.model;
82174
+ if (control)
82175
+ options.log?.(`codex ${position.session}: sampled into control, keeping ${model}`);
82062
82176
  if (decision?.notice && !noticed.has(position.session)) {
82063
82177
  noticed.add(position.session);
82064
82178
  options.log?.(`codex ${position.session}: ${decision.notice}`);
@@ -82100,7 +82214,7 @@ function createCodexRelay(options, server) {
82100
82214
  unreachable = error62 instanceof Error ? error62.message : String(error62);
82101
82215
  failed = { transient: true };
82102
82216
  }
82103
- const next = position && failed && model ? router.fallback(
82217
+ const next = position && failed && model && !control ? router.fallback(
82104
82218
  {
82105
82219
  session: position.session,
82106
82220
  turnId: position.turnId,
@@ -82272,6 +82386,73 @@ function openApiDocument({ auth }) {
82272
82386
  })
82273
82387
  }
82274
82388
  },
82389
+ "/v1/trial-window": {
82390
+ get: {
82391
+ summary: "Check the live routing-vs-control comparison",
82392
+ description: "A cheap, standalone check for whether a routing-vs-control comparison is open, for a caller like Kif that otherwise skips `/v1/route` entirely when sampled into control. A caller already streaming `/v1/route` sees the same thing on its `done` step and doesn't need this.",
82393
+ ...guard({
82394
+ "200": {
82395
+ description: "The open window, or `null` when none is open.",
82396
+ content: { "application/json": { schema: ref("TrialWindow") } }
82397
+ }
82398
+ })
82399
+ },
82400
+ post: {
82401
+ summary: "Open a routing-vs-control comparison",
82402
+ description: "Opens a new trial window at `controlRatio` (strictly between 0 and 1): that share of sampled sessions keep their own routing (control) instead of Bizzy's (treatment). Refused with 409 while one is already open, rather than silently replacing it and reassigning every session's arm mid-comparison; close it first.",
82403
+ requestBody: {
82404
+ required: true,
82405
+ content: {
82406
+ "application/json": {
82407
+ schema: { type: "object", properties: { controlRatio: { type: "number" } } }
82408
+ }
82409
+ }
82410
+ },
82411
+ ...guard({
82412
+ "200": {
82413
+ description: "`{ id, controlRatio, openedAt }`: the window just opened.",
82414
+ content: { "application/json": { schema: { type: "object" } } }
82415
+ },
82416
+ "400": failure2("controlRatio is missing or not strictly between 0 and 1."),
82417
+ "409": failure2("A trial window is already open; its id and controlRatio are included."),
82418
+ "501": failure2("This server has no trial window store configured.")
82419
+ })
82420
+ },
82421
+ delete: {
82422
+ summary: "Close the live routing-vs-control comparison",
82423
+ description: "Idempotent: succeeds whether or not one was open.",
82424
+ ...guard({
82425
+ "200": {
82426
+ description: "`{ closed }`: whether a window was actually open to close.",
82427
+ content: { "application/json": { schema: { type: "object" } } }
82428
+ }
82429
+ })
82430
+ }
82431
+ },
82432
+ "/v1/trial-report": {
82433
+ get: {
82434
+ summary: "Report the routing-vs-control comparison",
82435
+ description: "Per window, per arm and task kind: runs, cost per completed run (every attempt's cost over the runs that succeeded), success rate, average quality and latency. Aggregates only. Takes a key from BIZZY_API_KEYS or a read-only one from BIZZY_REPORT_KEYS.",
82436
+ ...guard({
82437
+ "200": {
82438
+ description: "`{ open, windows }`: `open` is the open window or null; `windows` has one `{ windowId, firstSettledAt, lastSettledAt, rows }` per window with sampled runs, oldest first, and `rows` holds `{ arm, taskKind, runs, costPerCompleted, successRate, avgQuality, avgLatencyMs }` (`costPerCompleted` null when nothing succeeded).",
82439
+ content: { "application/json": { schema: { type: "object" } } }
82440
+ }
82441
+ })
82442
+ }
82443
+ },
82444
+ "/v1/routing-report": {
82445
+ get: {
82446
+ summary: "Report Bizzy's own standing routing performance",
82447
+ 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.",
82448
+ ...guard({
82449
+ "200": {
82450
+ 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).",
82451
+ content: { "application/json": { schema: { type: "object" } } }
82452
+ }
82453
+ })
82454
+ }
82455
+ },
82275
82456
  "/v1/settle": {
82276
82457
  post: {
82277
82458
  summary: "Record a finished run",
@@ -82306,6 +82487,7 @@ function openApiDocument({ auth }) {
82306
82487
  Step: json2(StepSchema, "output"),
82307
82488
  ErrorLine: json2(ErrorLineSchema, "output"),
82308
82489
  RouteStreamLine: { oneOf: [ref("Step"), ref("ErrorLine")] },
82490
+ TrialWindow: json2(OpenWindowSchema.nullable(), "output"),
82309
82491
  SettleReply: json2(SettleReplySchema, "output"),
82310
82492
  ErrorBody: json2(ErrorBodySchema, "output")
82311
82493
  }
@@ -82313,11 +82495,109 @@ function openApiDocument({ auth }) {
82313
82495
  };
82314
82496
  }
82315
82497
 
82498
+ // bizzy-routing/api/src/routing-report.ts
82499
+ var mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
82500
+ function judgeCostAverage(runs) {
82501
+ const priced = runs.flatMap(
82502
+ (run3) => typeof run3.route.judgeUsage?.costUsd === "number" ? [run3.route.judgeUsage.costUsd] : []
82503
+ );
82504
+ return priced.length ? mean(priced) : null;
82505
+ }
82506
+ function summarizeRouting(records2) {
82507
+ const groups = /* @__PURE__ */ new Map();
82508
+ for (const record5 of records2) {
82509
+ if (record5.route.arm === "control") continue;
82510
+ const date5 = record5.settledAt.slice(0, 10);
82511
+ const key = `${date5}\0${record5.task.kind}`;
82512
+ const group = groups.get(key) ?? [];
82513
+ group.push(record5);
82514
+ groups.set(key, group);
82515
+ }
82516
+ return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, runs]) => {
82517
+ const [date5, taskKind] = key.split("\0");
82518
+ const completed = runs.filter((run3) => run3.taskSuccess);
82519
+ const totalCost = runs.reduce((sum, run3) => sum + run3.usage.costUsd, 0);
82520
+ return {
82521
+ date: date5,
82522
+ taskKind,
82523
+ runs: runs.length,
82524
+ costPerCompleted: completed.length ? totalCost / completed.length : null,
82525
+ successRate: completed.length / runs.length,
82526
+ avgQuality: mean(runs.map((run3) => run3.quality)),
82527
+ avgLatencyMs: mean(runs.map((run3) => run3.latencyMs)),
82528
+ avgInputTokens: mean(runs.map((run3) => run3.usage.inputTokens)),
82529
+ avgOutputTokens: mean(runs.map((run3) => run3.usage.outputTokens)),
82530
+ capableRate: runs.filter((run3) => run3.route.rule === "capable").length / runs.length,
82531
+ judgeCallRate: runs.filter((run3) => run3.route.judgeUsage).length / runs.length,
82532
+ avgJudgeCostUsd: judgeCostAverage(runs)
82533
+ };
82534
+ });
82535
+ }
82536
+
82537
+ // bizzy-routing/api/src/trial-report.ts
82538
+ var mean2 = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
82539
+ function summarizeWindow(records2) {
82540
+ const groups = /* @__PURE__ */ new Map();
82541
+ for (const record5 of records2) {
82542
+ if (!record5.route.arm) continue;
82543
+ const key = `${record5.route.arm}\0${record5.task.kind}`;
82544
+ const group = groups.get(key) ?? [];
82545
+ group.push(record5);
82546
+ groups.set(key, group);
82547
+ }
82548
+ return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, runs]) => {
82549
+ const [arm, taskKind] = key.split("\0");
82550
+ const completed = runs.filter((run3) => run3.taskSuccess);
82551
+ const totalCost = runs.reduce((sum, run3) => sum + run3.usage.costUsd, 0);
82552
+ return {
82553
+ arm,
82554
+ taskKind,
82555
+ runs: runs.length,
82556
+ costPerCompleted: completed.length ? totalCost / completed.length : null,
82557
+ successRate: completed.length / runs.length,
82558
+ avgQuality: mean2(runs.map((run3) => run3.quality)),
82559
+ avgLatencyMs: mean2(runs.map((run3) => run3.latencyMs))
82560
+ };
82561
+ });
82562
+ }
82563
+ function trialReport(records2, open3) {
82564
+ const byWindow = /* @__PURE__ */ new Map();
82565
+ for (const record5 of records2) {
82566
+ const { windowId } = record5.route;
82567
+ if (windowId) byWindow.set(windowId, [...byWindow.get(windowId) ?? [], record5]);
82568
+ }
82569
+ const windows = [...byWindow.entries()].map(([windowId, runs]) => {
82570
+ const settled = runs.map((run3) => run3.settledAt).sort();
82571
+ return {
82572
+ windowId,
82573
+ firstSettledAt: settled[0],
82574
+ lastSettledAt: settled.at(-1),
82575
+ rows: summarizeWindow(runs)
82576
+ };
82577
+ });
82578
+ return {
82579
+ open: open3,
82580
+ windows: windows.sort((a, b) => a.firstSettledAt.localeCompare(b.firstSettledAt))
82581
+ };
82582
+ }
82583
+
82316
82584
  // bizzy-routing/api/src/server.ts
82317
- var baseRoutes = ["/v1/route", "/v1/settle", "/docs", "/openapi.json"];
82585
+ var baseRoutes = [
82586
+ "/v1/route",
82587
+ "/v1/settle",
82588
+ "/v1/trial-window",
82589
+ "/v1/trial-report",
82590
+ "/v1/routing-report",
82591
+ "/docs",
82592
+ "/openapi.json"
82593
+ ];
82318
82594
  var harnessActions = ["step", "fallback", "models", "complete"];
82319
82595
  var codexBodyBytes = 64 * 1024 * 1024;
82320
82596
  var message2 = (error62) => error62 instanceof Error ? error62.message : String(error62);
82597
+ var openWindowOf = (window2) => ({
82598
+ id: window2.id,
82599
+ controlRatio: window2.controlRatio
82600
+ });
82321
82601
  function createRoutingServer(options) {
82322
82602
  useRegistryStore(options.registry);
82323
82603
  const app = (0, import_fastify.default)({ bodyLimit: options.maxBodyBytes ?? 256 * 1024 });
@@ -82361,6 +82641,38 @@ function createRoutingServer(options) {
82361
82641
  throw error62;
82362
82642
  }
82363
82643
  });
82644
+ app.get("/v1/trial-window", guarded, async () => {
82645
+ const window2 = options.trialWindow?.load();
82646
+ return window2 ? openWindowOf(window2) : null;
82647
+ });
82648
+ app.post("/v1/trial-window", guarded, async (request, reply) => {
82649
+ if (!options.trialWindow)
82650
+ return reply.code(501).send({ error: "no trial window store configured" });
82651
+ const existing = options.trialWindow.load();
82652
+ if (existing)
82653
+ return reply.code(409).send({ error: "a trial window is already open", window: openWindowOf(existing) });
82654
+ let controlRatio;
82655
+ try {
82656
+ controlRatio = trialWindowOpenBody(request.body);
82657
+ } catch (error62) {
82658
+ return reply.code(400).send({ error: message2(error62) });
82659
+ }
82660
+ return options.trialWindow.open(controlRatio);
82661
+ });
82662
+ app.delete("/v1/trial-window", guarded, async () => {
82663
+ const was = options.trialWindow?.load();
82664
+ options.trialWindow?.close();
82665
+ return { closed: Boolean(was) };
82666
+ });
82667
+ const reportKeys = [...keys, ...options.reportKeys ?? []];
82668
+ const reportGuard = reportKeys.length ? { onRequest: requireApiKey(reportKeys) } : {};
82669
+ app.get("/v1/trial-report", reportGuard, async () => {
82670
+ const window2 = options.trialWindow?.load();
82671
+ return trialReport(options.trialRuns?.() ?? [], window2 ? openWindowOf(window2) : null);
82672
+ });
82673
+ app.get("/v1/routing-report", reportGuard, async () => ({
82674
+ rows: summarizeRouting(options.allRuns?.() ?? [])
82675
+ }));
82364
82676
  app.post("/v1/route", guarded, async (request, reply) => {
82365
82677
  let parsed2;
82366
82678
  try {
@@ -82377,8 +82689,15 @@ function createRoutingServer(options) {
82377
82689
  await routeSteps(
82378
82690
  parsed2,
82379
82691
  options,
82380
- (step) => raw.write(`${JSON.stringify(step)}
82381
- `),
82692
+ // The done step picks up the open window here, at the one place that actually reaches the
82693
+ // client — routeSteps()'s own return value is never read, only what onStep writes.
82694
+ (step) => {
82695
+ const window2 = step.kind === "done" ? options.trialWindow?.load() : void 0;
82696
+ raw.write(
82697
+ `${JSON.stringify(window2 ? { ...step, window: openWindowOf(window2) } : step)}
82698
+ `
82699
+ );
82700
+ },
82382
82701
  abort.signal
82383
82702
  );
82384
82703
  } catch (error62) {
@@ -82517,7 +82836,13 @@ var SqliteRunRecordStore = class {
82517
82836
  #insert;
82518
82837
  #comparable;
82519
82838
  #observed;
82839
+ #trial;
82840
+ #all;
82520
82841
  constructor(database) {
82842
+ this.#trial = database.prepare(
82843
+ "SELECT record FROM runs WHERE json_extract(record, '$.route.arm') IS NOT NULL AND json_extract(record, '$.route.windowId') IS NOT NULL ORDER BY seq"
82844
+ );
82845
+ this.#all = database.prepare("SELECT record FROM runs ORDER BY seq");
82521
82846
  this.#insert = database.prepare(
82522
82847
  "INSERT INTO runs (kind, risk, mode, harness_id, succeeded, record) VALUES (?, ?, ?, ?, ?, ?)"
82523
82848
  );
@@ -82550,11 +82875,22 @@ var SqliteRunRecordStore = class {
82550
82875
  async loadObserved(task, mode, harnessId) {
82551
82876
  return records(this.#observed, task, mode, harnessId);
82552
82877
  }
82878
+ /** Every run sampled into a routing-vs-control window, oldest first. */
82879
+ trialRuns() {
82880
+ return parse4(this.#trial.all());
82881
+ }
82882
+ /** Every run ever settled, oldest first. */
82883
+ allRuns() {
82884
+ return parse4(this.#all.all());
82885
+ }
82553
82886
  };
82554
82887
  function records(statement, task, mode, harnessId) {
82555
82888
  const rows2 = statement.all(task.kind, task.risk, mode, harnessId);
82889
+ return parse4(rows2.reverse());
82890
+ }
82891
+ function parse4(rows2) {
82556
82892
  const parsed2 = [];
82557
- for (const { record: record5 } of rows2.reverse()) {
82893
+ for (const { record: record5 } of rows2) {
82558
82894
  try {
82559
82895
  parsed2.push(sanitizeRunRecord(JSON.parse(record5)));
82560
82896
  } catch {
@@ -82620,6 +82956,10 @@ var migrations = [
82620
82956
  CREATE TABLE calibration (
82621
82957
  slot INTEGER PRIMARY KEY CHECK (slot = 1),
82622
82958
  stored TEXT NOT NULL
82959
+ );`,
82960
+ `CREATE TABLE trial_window (
82961
+ slot INTEGER PRIMARY KEY CHECK (slot = 1),
82962
+ stored TEXT NOT NULL
82623
82963
  );`
82624
82964
  ];
82625
82965
 
@@ -82666,10 +83006,53 @@ async function openRoutingDatabase(cwd) {
82666
83006
  }
82667
83007
  }
82668
83008
 
83009
+ // bizzy-routing/api/src/sqlite/window.ts
83010
+ function parse5(stored) {
83011
+ try {
83012
+ const value = JSON.parse(stored);
83013
+ return typeof value.id === "string" && typeof value.controlRatio === "number" && typeof value.openedAt === "string" ? value : null;
83014
+ } catch {
83015
+ return null;
83016
+ }
83017
+ }
83018
+ var SqliteTrialWindowStore = class {
83019
+ #load;
83020
+ #save;
83021
+ #close;
83022
+ #now;
83023
+ constructor(database, now = () => /* @__PURE__ */ new Date()) {
83024
+ this.#load = database.prepare("SELECT stored FROM trial_window WHERE slot = 1");
83025
+ this.#save = database.prepare(
83026
+ `INSERT INTO trial_window (slot, stored) VALUES (1, ?)
83027
+ ON CONFLICT (slot) DO UPDATE SET stored = excluded.stored`
83028
+ );
83029
+ this.#close = database.prepare("DELETE FROM trial_window WHERE slot = 1");
83030
+ this.#now = now;
83031
+ }
83032
+ load() {
83033
+ const row = this.#load.get();
83034
+ return row ? parse5(row.stored) : null;
83035
+ }
83036
+ open(controlRatio) {
83037
+ if (!(controlRatio > 0 && controlRatio < 1))
83038
+ throw new RangeError("controlRatio must be between 0 and 1, exclusive");
83039
+ const window2 = {
83040
+ id: `w-${Math.floor(this.#now().getTime() / 1e3)}`,
83041
+ controlRatio,
83042
+ openedAt: this.#now().toISOString()
83043
+ };
83044
+ this.#save.run(JSON.stringify(window2));
83045
+ return window2;
83046
+ }
83047
+ close() {
83048
+ this.#close.run();
83049
+ }
83050
+ };
83051
+
82669
83052
  // bizzy-routing/api/src/setup.ts
82670
83053
  import { mkdir as mkdir2 } from "node:fs/promises";
82671
- function claudeHarness() {
82672
- return { harnessId: "claude-code", provider: "anthropic" };
83054
+ function claudeHarness(profile) {
83055
+ return { harnessId: "claude-code", provider: "anthropic", ...profile ? { profile } : {} };
82673
83056
  }
82674
83057
  function ompHarness() {
82675
83058
  return { harnessId: "omp" };
@@ -82691,13 +83074,17 @@ async function openServerState(dataDir, env, log) {
82691
83074
  log(
82692
83075
  `routing.db created; imported ${imported.runs.length} runs, ${imported.registry.length} registry entries and ${imported.calibration ? 1 : 0} calibration from the old files`
82693
83076
  );
83077
+ const evidence = new SqliteRunRecordStore(database);
82694
83078
  return {
82695
83079
  database,
82696
83080
  noKey,
82697
83081
  stores: {
82698
- evidence: new SqliteRunRecordStore(database),
83082
+ evidence,
83083
+ trialRuns: () => evidence.trialRuns(),
83084
+ allRuns: () => evidence.allRuns(),
82699
83085
  registry: new SqliteRegistryStore(database),
82700
83086
  calibration: new SqliteCalibrationStore(database),
83087
+ trialWindow: new SqliteTrialWindowStore(database),
82701
83088
  // The same key fetches the daily catalog that prices callers' candidates and scores them.
82702
83089
  catalog: bundled ? async () => bundled : () => loadCatalog({ cwd: dataDir, apiKey: env.OPENROUTER_API_KEY }),
82703
83090
  aliases: () => loadAliases(dataDir)
@@ -82728,6 +83115,9 @@ function hostedFrom(env, log) {
82728
83115
  );
82729
83116
  return createHostedRoute({ url: url2.origin, key, sharePrompts, log });
82730
83117
  }
83118
+ function claudeCodeProfileFrom(env) {
83119
+ return env.BIZZY_API_CLAUDE_CODE_PROFILE === "jev-grade" ? "jev-grade" : void 0;
83120
+ }
82731
83121
  async function startLocalServer(env, log, { docsDir } = {}) {
82732
83122
  const dataDir = env.BIZZY_API_DATA_DIR;
82733
83123
  if (!dataDir) throw new Error("BIZZY_API_DATA_DIR is required");
@@ -82736,14 +83126,16 @@ async function startLocalServer(env, log, { docsDir } = {}) {
82736
83126
  throw new Error(`invalid PORT: ${env.PORT}`);
82737
83127
  const { database, noKey, stores } = await openServerState(dataDir, env, log);
82738
83128
  const hosted = hostedFrom(env, log);
83129
+ const claudeCodeProfile = claudeCodeProfileFrom(env);
82739
83130
  const app = createRoutingServer({
82740
83131
  ...stores,
82741
83132
  ...hosted ? { hosted } : {},
82742
83133
  ...docsDir ? { docsDir } : {},
82743
83134
  notices: { ...routeNotices, absent: noKey ?? noJudge },
82744
- harnesses: { "claude-code": claudeHarness(), omp: ompHarness() },
83135
+ harnesses: { "claude-code": claudeHarness(claudeCodeProfile), omp: ompHarness() },
82745
83136
  codex: { ...codexRelay(env), log }
82746
83137
  });
83138
+ if (claudeCodeProfile) log(`claude-code: ${claudeCodeProfile}`);
82747
83139
  if (!hosted) log(noJudge);
82748
83140
  if (noKey) log(noKey);
82749
83141
  app.addHook("onClose", async () => database.close());
@@ -83008,7 +83400,10 @@ function wireClaude(target, runtime) {
83008
83400
  return {
83009
83401
  done: `Wired Claude Code: ${marketplace}`,
83010
83402
  notes: [],
83011
- next: installed ? "In a running Claude Code session: /reload-plugins" : `In Claude Code:
83403
+ ...installed && {
83404
+ run: { command: "claude /reload-plugins", title: "Start Claude Code with" }
83405
+ },
83406
+ next: installed ? "Already in a Claude Code session? Type /reload-plugins there instead." : `In Claude Code:
83012
83407
  /plugin marketplace add ${marketplace}
83013
83408
  /plugin install ${pluginId}
83014
83409
  /reload-plugins`
@@ -83377,6 +83772,7 @@ async function installFlow(harness, target, flags) {
83377
83772
  else if (io.interactive && !hasKey) ui.warn("No routing key: turns route with Bizzy's own rules");
83378
83773
  if (flags.sharePrompts === false) writeEnvValues(target.dataDir, { BIZZY_SHARE_PROMPTS: "0" });
83379
83774
  else if (flags.sharePrompts) writeEnvValues(target.dataDir, { BIZZY_SHARE_PROMPTS: void 0 });
83775
+ if (wired.run) ui.command(wired.run.command, wired.run.title);
83380
83776
  ui.note(wired.next, "Next");
83381
83777
  }
83382
83778
  function verdict(checks) {