@statelyai/agent 2.0.0-alpha.32 → 2.0.0-alpha.34

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/ai-sdk.cjs +114 -63
  3. package/dist/ai-sdk.d.cts +11 -2
  4. package/dist/ai-sdk.d.mts +11 -2
  5. package/dist/ai-sdk.mjs +115 -64
  6. package/dist/{decision-BPdEaxPf.cjs → decision-BEsATcr1.cjs} +18 -2
  7. package/dist/{decision-CV7WiV5C.mjs → decision-COkJNjOW.mjs} +18 -2
  8. package/dist/{event-log-CKWeC7H-.cjs → event-log-BWSSLUff.cjs} +139 -10
  9. package/dist/{event-log-DAqsalT1.mjs → event-log-C7jeH0y8.mjs} +123 -12
  10. package/dist/{event-log-store-C2NjVlWU.d.mts → event-log-store-BzXehP7R.d.cts} +28 -3
  11. package/dist/{event-log-store-s73r1Hxf.d.cts → event-log-store-CWjN6lmM.d.mts} +28 -3
  12. package/dist/{event-log-store-DKyE7JKr.cjs → event-log-store-CleWpsp5.cjs} +1 -1
  13. package/dist/{event-log-store-BGehvVTb.mjs → event-log-store-W49TCJXi.mjs} +1 -1
  14. package/dist/index.cjs +5 -5
  15. package/dist/index.d.cts +7 -7
  16. package/dist/index.d.mts +7 -7
  17. package/dist/index.mjs +5 -5
  18. package/dist/log.cjs +2 -2
  19. package/dist/log.d.cts +1 -1
  20. package/dist/log.d.mts +1 -1
  21. package/dist/log.mjs +2 -2
  22. package/dist/machines.cjs +1 -1
  23. package/dist/machines.mjs +1 -1
  24. package/dist/{model-source-BilDEyqk.mjs → model-source-CK3F4YuU.mjs} +1 -1
  25. package/dist/{model-source-BQ97_l1-.cjs → model-source-DmhTMK39.cjs} +1 -1
  26. package/dist/openai.cjs +377 -95
  27. package/dist/openai.d.cts +55 -20
  28. package/dist/openai.d.mts +55 -20
  29. package/dist/openai.mjs +375 -96
  30. package/dist/otel.d.cts +1 -1
  31. package/dist/otel.d.mts +1 -1
  32. package/dist/{run-agent-B5QhabdY.d.cts → run-agent-B1-Eqviq.d.cts} +13 -5
  33. package/dist/{run-agent-Atu-wEk7.d.mts → run-agent-BGdx5913.d.mts} +13 -5
  34. package/dist/{run-agent-2UnSUhDb.mjs → run-agent-Ct_GZw_f.mjs} +124 -38
  35. package/dist/{run-agent-Cg0xd3K-.cjs → run-agent-s5D32w99.cjs} +123 -37
  36. package/dist/{setup-agent-CmhB-U5P.mjs → setup-agent-05uw4dPZ.mjs} +2 -2
  37. package/dist/{setup-agent-BiF1N3td.d.cts → setup-agent-BtfeFfF6.d.cts} +2 -2
  38. package/dist/{setup-agent-J9f_Wu5T.d.mts → setup-agent-C6nqzv_X.d.mts} +2 -2
  39. package/dist/{setup-agent-CwUJyqKB.cjs → setup-agent-CXEBURdo.cjs} +2 -2
  40. package/dist/tanstack-ai.cjs +91 -59
  41. package/dist/tanstack-ai.d.cts +13 -2
  42. package/dist/tanstack-ai.d.mts +13 -2
  43. package/dist/tanstack-ai.mjs +91 -59
  44. package/dist/testing.cjs +1026 -10
  45. package/dist/testing.d.cts +585 -5
  46. package/dist/testing.d.mts +585 -5
  47. package/dist/testing.mjs +1018 -11
  48. package/dist/{text-logic-CYP502VT.d.cts → text-logic-CV_4KGr6.d.cts} +28 -3
  49. package/dist/{text-logic-DuK9HIFM.d.mts → text-logic-Ckh-rJFV.d.mts} +28 -3
  50. package/dist/{usage-D7JKAxLc.d.mts → usage-BDiJKyv9.d.cts} +11 -1
  51. package/dist/{usage-DVw-646x.d.cts → usage-DOoVUGVq.d.mts} +11 -1
  52. package/dist/validate.cjs +3 -3
  53. package/dist/validate.d.cts +2 -2
  54. package/dist/validate.d.mts +2 -2
  55. package/dist/validate.mjs +3 -3
  56. package/dist/{verify-Dk3Vwnha.d.cts → verify-BQpE8hUz.d.cts} +1 -1
  57. package/dist/{verify-CoCvR1eM.mjs → verify-Bpahmr34.mjs} +14 -4
  58. package/dist/{verify-BVz4cURF.d.mts → verify-CqeuEmIk.d.mts} +1 -1
  59. package/dist/{verify-D_llRCTr.cjs → verify-DCLZa9R0.cjs} +19 -3
  60. package/dist/with-model-calls-BXYdBdcu.cjs +45 -0
  61. package/dist/with-model-calls-Bv4V4EHC.mjs +34 -0
  62. package/package.json +5 -5
  63. package/readme.md +14 -13
  64. package/skills/add-evals/SKILL.md +8 -2
  65. package/skills/improve-machine/SKILL.md +1 -1
  66. package/skills/loop-to-machine/SKILL.md +40 -2
package/dist/testing.cjs CHANGED
@@ -1,14 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_log = require("./event-log-CKWeC7H-.cjs");
3
- const require_run_agent = require("./run-agent-Cg0xd3K-.cjs");
4
- const require_verify = require("./verify-D_llRCTr.cjs");
2
+ const require_event_log = require("./event-log-BWSSLUff.cjs");
3
+ const require_run_agent = require("./run-agent-s5D32w99.cjs");
4
+ const require_verify = require("./verify-DCLZa9R0.cjs");
5
+ let xstate = require("xstate");
5
6
  //#region src/trajectory.ts
6
7
  /**
7
8
  * Classifies one item. Event-shaped things (log entries, events) become events;
8
9
  * everything else is a state value. A snapshot is unwrapped to its `value`.
9
10
  * @internal
10
11
  */
11
- function normalize(item) {
12
+ function normalize$1(item) {
12
13
  if (require_event_log.isRecord(item)) {
13
14
  const nested = item["event"];
14
15
  if (require_event_log.isRecord(nested) && typeof nested["type"] === "string") return {
@@ -61,17 +62,17 @@ function deepEqual(a, b) {
61
62
  */
62
63
  function matcherFor(expected) {
63
64
  if (typeof expected === "string") return (actual) => {
64
- const actualItem = normalize(actual);
65
+ const actualItem = normalize$1(actual);
65
66
  return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
66
67
  };
67
- const expectedItem = normalize(expected);
68
+ const expectedItem = normalize$1(expected);
68
69
  switch (expectedItem.kind) {
69
70
  case "event": return (actual) => {
70
- const actualItem = normalize(actual);
71
+ const actualItem = normalize$1(actual);
71
72
  return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
72
73
  };
73
74
  case "state": return (actual) => {
74
- const actualItem = normalize(actual);
75
+ const actualItem = normalize$1(actual);
75
76
  return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
76
77
  };
77
78
  }
@@ -381,12 +382,47 @@ function statePaths(value, prefix = "") {
381
382
  if (entries.length === 0) return prefix ? [prefix.slice(0, -1)] : [];
382
383
  return entries.flatMap(([key, child]) => statePaths(child, `${prefix}${key}.`));
383
384
  }
385
+ /**
386
+ * A trace's `machine.transition` events as steps, skipping `@xstate.init`.
387
+ * A first-attempt decision's `request.start` names the decision on the step
388
+ * that follows it, skipping `@agent.usage` steps. Reads live and serialized traces alike.
389
+ * @internal
390
+ */
391
+ function traceSteps(trace) {
392
+ const steps = [];
393
+ let decision;
394
+ for (const event of trace) {
395
+ if (event.type === "request.start" && isFirstDecision(event.request)) {
396
+ const name = event.request.name;
397
+ decision = typeof name === "string" ? name : void 0;
398
+ continue;
399
+ }
400
+ if (event.type !== "machine.transition") continue;
401
+ const type = require_event_log.isRecord(event.event) ? event.event.type : void 0;
402
+ if (type === "@xstate.init") continue;
403
+ const fromValue = valueOf(event.from);
404
+ const toValue = valueOf(event.snapshot);
405
+ steps.push({
406
+ from: statePaths(fromValue),
407
+ fromValue,
408
+ event: typeof type === "string" ? type : "",
409
+ payload: event.event,
410
+ to: statePaths(toValue),
411
+ toValue,
412
+ ignored: event.ignored === true,
413
+ ...decision === void 0 || type === "@agent.usage" ? {} : { decision }
414
+ });
415
+ if (type !== "@agent.usage") decision = void 0;
416
+ }
417
+ return steps;
418
+ }
384
419
  //#endregion
385
420
  //#region src/fold-traces.ts
386
421
  /**
387
422
  * Folds many runs' traces into per-state stats: how many runs visited each
388
423
  * state, how many of those failed, how many options the guards withheld
389
- * at decisions made there, and how many events it ignored. Pure; reads only:
424
+ * at decisions made there, how many events it ignored, and how many failures
425
+ * `blame` traced back to it. Pure; reads only:
390
426
  *
391
427
  * - `machine.transition`: the run visited `from.value` and `snapshot.value`;
392
428
  * with `ignored`, each of those states ignored one event.
@@ -399,6 +435,10 @@ function statePaths(value, prefix = "") {
399
435
  * `{ type: 'request.start', request: result.request }` onto the trace before
400
436
  * sending its event. Parallel states count once per active leaf.
401
437
  *
438
+ * `failures` counts a failed run against every state it visited, so states
439
+ * after a bad decision rank as high as the decision. Sort by `blamed` to see
440
+ * where failures start.
441
+ *
402
442
  * @example
403
443
  * ```ts no-check
404
444
  * const stats = foldTraces(traces, {
@@ -416,7 +456,8 @@ function foldTraces(traces, options) {
416
456
  visits: 0,
417
457
  failures: 0,
418
458
  withheld: 0,
419
- ignored: 0
459
+ ignored: 0,
460
+ blamed: 0
420
461
  };
421
462
  stats.set(state, entry);
422
463
  }
@@ -445,10 +486,311 @@ function foldTraces(traces, options) {
445
486
  entry.visits++;
446
487
  if (failed) entry.failures++;
447
488
  }
489
+ const blamed = failed ? options.blame?.(trace) : void 0;
490
+ if (blamed !== void 0) statsFor(blamed).blamed++;
448
491
  }
449
492
  return [...stats.values()];
450
493
  }
451
494
  //#endregion
495
+ //#region src/trace-coverage.ts
496
+ /** Mirrors xstate@6.0.0-alpha.69 `matchesEventDescriptor` (src/utils.ts), which the package does not export. */
497
+ function matchesDescriptor(eventType, descriptor) {
498
+ if (descriptor === eventType || descriptor === "*") return true;
499
+ if (!descriptor.endsWith(".*")) return false;
500
+ const tokens = descriptor.split(".");
501
+ const eventTokens = eventType.split(".");
502
+ for (let index = 0; index < tokens.length; index++) {
503
+ if (tokens[index] === "*") return index === tokens.length - 1;
504
+ if (tokens[index] !== eventTokens[index]) return false;
505
+ }
506
+ return true;
507
+ }
508
+ /** Whether a definition's `matches` pattern (e.g. an invoke's `actorId`) accepts the traced event. */
509
+ function matchesPattern(definition, event) {
510
+ const pattern = definition.matches;
511
+ if (!require_event_log.isRecord(pattern) || !require_event_log.isRecord(event)) return true;
512
+ return Object.entries(pattern).every(([key, value]) => Object.is(event[key], value));
513
+ }
514
+ /**
515
+ * The descriptor XState would try first at `node` for `event`, guards aside:
516
+ * the exact key, then partial and wildcard keys longest first, as in
517
+ * xstate@6.0.0-alpha.69 `getCandidates` (src/stateUtils.ts).
518
+ */
519
+ function candidateAt(node, type, event) {
520
+ const keys = [...node.transitions.keys()].filter((key) => key !== type && matchesDescriptor(type, key)).sort((a, b) => b.length - a.length);
521
+ if (node.transitions.has(type)) keys.unshift(type);
522
+ return keys.find((key) => node.transitions.get(key).some((d) => matchesPattern(d, event)));
523
+ }
524
+ const pathOf = (node) => node.path.join(".");
525
+ const sameLeaves = (a, b) => statePaths(a).sort().join("|") === statePaths(b).sort().join("|");
526
+ /**
527
+ * The leaves a trace passed through inside its macrosteps: states an `always`
528
+ * transition left before the step ended, which no traced snapshot holds.
529
+ * Re-derived with XState's pure `getMicrosteps` from the snapshot before each
530
+ * step (the previous step's, or the fresh start's microsteps from its input).
531
+ * A step that cannot be recomputed, or whose recomputation ends elsewhere
532
+ * than the traced snapshot, adds none. Only `value` and `context` are rebuilt,
533
+ * so a guard that reads live children can take another route to the same
534
+ * leaves, and that route is credited.
535
+ */
536
+ function passedThrough(machine, trace) {
537
+ const leaves = /* @__PURE__ */ new Set();
538
+ let resumed = false;
539
+ let previous;
540
+ for (const event of trace) {
541
+ if (event.type === "run.start") resumed = event.snapshot !== void 0;
542
+ if (event.type !== "machine.transition" || !require_event_log.isRecord(event.event)) continue;
543
+ const snapshot = require_event_log.isRecord(event.snapshot) ? event.snapshot : void 0;
544
+ try {
545
+ const microsteps = event.event.type === "@xstate.init" ? resumed ? [] : (0, xstate.getInitialMicrosteps)(machine, event.event.input) : previous && sameLeaves(previous.value, valueOf(event.from)) ? (0, xstate.getMicrosteps)(machine, machine.resolveState({
546
+ value: previous.value,
547
+ context: previous.context
548
+ }), event.event) : [];
549
+ const last = microsteps.at(-1)?.[0];
550
+ if (last && snapshot && sameLeaves(last.value, snapshot.value)) for (const [step] of microsteps) for (const leaf of statePaths(step.value)) leaves.add(leaf);
551
+ } catch {}
552
+ previous = snapshot;
553
+ }
554
+ return leaves;
555
+ }
556
+ const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
557
+ /**
558
+ * Measures how much of a machine a set of runs exercised: which atomic and
559
+ * final states they visited, and which handlers they took. A handler is a
560
+ * `(declaring state, event descriptor)` pair from `on`, invoke
561
+ * `onDone`/`onError`, and `after`, with the targets it declares and the
562
+ * leaves the runs landed in after it. Pure; reads only `machine.transition`
563
+ * events, live (`AgentTraceEvent`) or serialized (`serializeTraceEvent`).
564
+ *
565
+ * A step credits one handler per active leaf: the nearest node, from the leaf
566
+ * up, whose exact, partial (`a.*`), or wildcard (`*`) descriptor matches the
567
+ * event, preferred in XState's order. Guards are not replayed, so a step
568
+ * whose nearest handler was rejected and fell through to an ancestor is
569
+ * credited to the nearest one. XState keys invoke and `after` handlers by
570
+ * bare type (`xstate.done.actor`), one per state however many invokes; a
571
+ * definition's `matches` (an invoke's `actorId`) must accept the traced event
572
+ * for its state to be credited. Ignored steps credit no handler. `always`
573
+ * handlers are listed as `unobservable`, never as unvisited; a state one
574
+ * passes through is visited, re-derived from each step's microsteps.
575
+ *
576
+ * @example
577
+ * ```ts no-check
578
+ * const report = traceCoverage(machine, traces, { reachable: await explorePaths(machine) });
579
+ * expect(report.unvisitedHandlers).toEqual([]);
580
+ * ```
581
+ */
582
+ function traceCoverage(machine, traces, options = {}) {
583
+ const nodes = /* @__PURE__ */ new Map();
584
+ const states = [];
585
+ const handlers = [];
586
+ const handlerAt = /* @__PURE__ */ new Map();
587
+ const unobservable = [];
588
+ const walk = (node) => {
589
+ const state = pathOf(node);
590
+ nodes.set(state, node);
591
+ if (node.type === "atomic" || node.type === "final") states.push({
592
+ state,
593
+ runs: 0
594
+ });
595
+ const byEvent = /* @__PURE__ */ new Map();
596
+ for (const [event, definitions] of node.transitions) {
597
+ const dynamic = definitions.some((d) => typeof d.to === "function");
598
+ const declared = [...new Set(definitions.flatMap((d) => (d.target ?? []).map(pathOf)))];
599
+ const handler = {
600
+ state,
601
+ event,
602
+ runs: 0,
603
+ targets: {
604
+ declared: dynamic ? "dynamic" : declared,
605
+ seen: [],
606
+ unreached: []
607
+ }
608
+ };
609
+ handlers.push(handler);
610
+ byEvent.set(event, handler);
611
+ }
612
+ handlerAt.set(node, byEvent);
613
+ if (node.always?.length) unobservable.push({
614
+ state,
615
+ event: "always"
616
+ });
617
+ for (const child of Object.values(node.states)) walk(child);
618
+ };
619
+ walk(machine.root);
620
+ const stateRuns = new Map(states.map((row) => [row.state, row]));
621
+ const seen = /* @__PURE__ */ new Map();
622
+ for (const trace of traces) {
623
+ const steps = traceSteps(trace);
624
+ const visited = new Set(steps[0]?.from);
625
+ for (const event of trace) {
626
+ if (event.type !== "machine.transition" || !require_event_log.isRecord(event.event)) continue;
627
+ if (event.event.type !== "@xstate.init" || !require_event_log.isRecord(event.snapshot)) continue;
628
+ for (const leaf of statePaths(event.snapshot.value)) visited.add(leaf);
629
+ }
630
+ if (unobservable.length > 0) for (const leaf of passedThrough(machine, trace)) visited.add(leaf);
631
+ const credited = /* @__PURE__ */ new Set();
632
+ for (const step of steps) {
633
+ for (const leaf of step.to) visited.add(leaf);
634
+ if (step.ignored) continue;
635
+ const hits = /* @__PURE__ */ new Set();
636
+ for (const leaf of step.from) for (let node = nodes.get(leaf); node; node = node.parent) {
637
+ if (node.type === "final") continue;
638
+ const event = candidateAt(node, step.event, step.payload);
639
+ if (event === void 0) continue;
640
+ hits.add(handlerAt.get(node).get(event));
641
+ break;
642
+ }
643
+ for (const handler of hits) {
644
+ credited.add(handler);
645
+ let leaves = seen.get(handler);
646
+ if (!leaves) seen.set(handler, leaves = /* @__PURE__ */ new Set());
647
+ for (const leaf of step.to) leaves.add(leaf);
648
+ }
649
+ }
650
+ for (const state of visited) {
651
+ const row = stateRuns.get(state);
652
+ if (row) row.runs++;
653
+ }
654
+ for (const handler of credited) handler.runs++;
655
+ }
656
+ for (const handler of handlers) {
657
+ const leaves = [...seen.get(handler) ?? []];
658
+ handler.targets.seen = leaves;
659
+ const { declared } = handler.targets;
660
+ if (declared === "dynamic") continue;
661
+ handler.targets.unreached = declared.filter((target) => !leaves.some((leaf) => leaf === target || leaf.startsWith(`${target}.`)));
662
+ }
663
+ const reachableComplete = options.reachable ? require_verify.isExplorationComplete(options.reachable) : void 0;
664
+ let unreachable;
665
+ if (options.reachable && reachableComplete) {
666
+ const reached = new Set(options.reachable.reachedStates.flatMap((value) => statePaths(value)));
667
+ unreachable = states.filter((row) => !reached.has(row.state) && row.runs === 0).map((row) => row.state);
668
+ }
669
+ const counted = unreachable ? states.filter((row) => !unreachable.includes(row.state)) : states;
670
+ const unvisitedStates = counted.filter((row) => row.runs === 0).map((row) => row.state);
671
+ const unvisitedHandlers = handlers.filter((handler) => handler.runs === 0).map(({ state, event }) => ({
672
+ state,
673
+ event
674
+ }));
675
+ return {
676
+ states,
677
+ handlers,
678
+ unvisitedStates,
679
+ unvisitedHandlers,
680
+ unobservable,
681
+ ...unreachable ? { unreachable } : {},
682
+ ...reachableComplete === void 0 ? {} : { reachableComplete },
683
+ ratio: {
684
+ states: ratioOf(counted.length - unvisitedStates.length, counted.length),
685
+ handlers: ratioOf(handlers.length - unvisitedHandlers.length, handlers.length)
686
+ }
687
+ };
688
+ }
689
+ //#endregion
690
+ //#region src/first-divergence.ts
691
+ const defaultKey = (step) => `${step.from.join(",")}|${step.event}|${step.to.join(",")}`;
692
+ const isErrorLike = (value) => require_event_log.isError(value) || require_event_log.isRecord(value) && typeof value.name === "string" && typeof value.message === "string";
693
+ const normalizeErrors = (value, seen = /* @__PURE__ */ new WeakSet()) => {
694
+ if (value === null || typeof value !== "object") return value;
695
+ if (seen.has(value)) return "[circular]";
696
+ seen.add(value);
697
+ try {
698
+ if (isErrorLike(value) && (require_event_log.isError(value) || "stack" in value || "code" in value)) {
699
+ const { name, message, code, cause } = value;
700
+ return {
701
+ name,
702
+ message,
703
+ ...typeof code === "string" ? { code } : {},
704
+ ...cause !== void 0 ? { cause: normalizeErrors(cause, seen) } : {}
705
+ };
706
+ }
707
+ if (Array.isArray(value)) return value.map((item) => normalizeErrors(item, seen));
708
+ if (!require_event_log.isPlainObject(value)) return value;
709
+ const copy = Object.create(null);
710
+ for (const key of Object.keys(value)) copy[key] = normalizeErrors(value[key], seen);
711
+ return copy;
712
+ } finally {
713
+ seen.delete(value);
714
+ }
715
+ };
716
+ const payloadKey = (step) => {
717
+ if (!require_event_log.isRecord(step.payload)) return `${defaultKey(step)}|${require_event_log.canonicalEventJson(step.payload)}`;
718
+ const { sessionId: _sessionId, ...payload } = step.payload;
719
+ return `${defaultKey(step)}|${require_event_log.canonicalEventJson(normalizeErrors(payload))}`;
720
+ };
721
+ const isTrace = (items) => items.length === 0 || items.some((item) => require_event_log.isRecord(item) && (item.type === "machine.transition" || item.type === "run.start" || item.type === "run.end"));
722
+ /**
723
+ * Finds the first step where a run departs from a reference, so a failure is
724
+ * blamed on the state it started in rather than on every state the run went
725
+ * through afterwards.
726
+ *
727
+ * - Against a reference **trace**, such as a passing run of the same
728
+ * scenario, steps are compared in order by `key`. The first step that
729
+ * differs, or the point where either trace ends early, is the divergence.
730
+ * - Against an expected **trajectory** (`TrajectoryItem[]`, as for
731
+ * {@link matchesTrajectory}), the run is laid out as its initial state, then
732
+ * each step's event and new state. The first expected item it never reaches
733
+ * is the divergence, blamed on the step after the last item it did reach. A
734
+ * run that goes on past the trajectory has not diverged.
735
+ *
736
+ * An empty reference is a trace with no steps, so any step diverges from it.
737
+ * A trace is one run's events, live or serialized. Steps the machine ignored
738
+ * changed nothing and are left out on both sides. Returns `undefined` when the
739
+ * run does not diverge.
740
+ *
741
+ * @example
742
+ * ```ts no-check
743
+ * const stats = foldTraces(traces, {
744
+ * failed,
745
+ * blame: (trace) => firstDivergence(trace, passingRunFor(trace))?.state,
746
+ * });
747
+ * ```
748
+ */
749
+ function firstDivergence(actual, reference, options = {}) {
750
+ const steps = traceSteps(actual).filter((step) => !step.ignored);
751
+ return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key === "payload" ? payloadKey : options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
752
+ }
753
+ function diverged(steps, index, expected, initial = steps[0]?.fromValue) {
754
+ const step = steps[index];
755
+ return {
756
+ index,
757
+ state: (step ? step.from[0] : steps.at(-1)?.to[0] ?? statePaths(initial)[0]) ?? "",
758
+ ...step?.decision === void 0 ? {} : { decision: step.decision },
759
+ ...step ? { actual: step } : {},
760
+ ...expected === void 0 ? {} : { expected }
761
+ };
762
+ }
763
+ function againstTrace(steps, reference, key) {
764
+ const length = Math.max(steps.length, reference.length);
765
+ for (let index = 0; index < length; index++) {
766
+ const step = steps[index];
767
+ const want = reference[index];
768
+ if (step && want && key(step) === key(want)) continue;
769
+ return diverged(steps, index, want, steps[0]?.fromValue ?? reference[0]?.fromValue);
770
+ }
771
+ }
772
+ function againstTrajectory(trace, steps, expected) {
773
+ const initial = initialValue(trace, steps);
774
+ const timeline = initial === void 0 ? [] : [{ value: initial }];
775
+ const stepAt = initial === void 0 ? [] : [0];
776
+ steps.forEach((step, index) => {
777
+ timeline.push(step.payload);
778
+ stepAt.push(index);
779
+ if (JSON.stringify(step.toValue) !== JSON.stringify(step.fromValue)) {
780
+ timeline.push({ value: step.toValue });
781
+ stepAt.push(index);
782
+ }
783
+ });
784
+ const match = matchesTrajectory(timeline, expected);
785
+ if (!match.firstMiss) return void 0;
786
+ const at = match.firstMiss.searchedFrom;
787
+ return diverged(steps, at < timeline.length ? stepAt[at] ?? steps.length : steps.length, match.firstMiss.expected, initial);
788
+ }
789
+ function initialValue(trace, steps) {
790
+ for (const event of trace) if (event.type === "machine.transition" && require_event_log.isRecord(event.snapshot)) return event.snapshot.value;
791
+ return steps[0]?.fromValue;
792
+ }
793
+ //#endregion
452
794
  //#region src/decision-requests.ts
453
795
  /**
454
796
  * The decisions a run asked for, read from its trace: each decision's first
@@ -481,6 +823,212 @@ function getDecisionRequests(trace, options = {}) {
481
823
  return requests;
482
824
  }
483
825
  //#endregion
826
+ //#region src/repeat-runs.ts
827
+ /**
828
+ * Summarizes repeated runs of each scenario: how often each passed, whether
829
+ * all its runs passed (pass^k), how many distinct state paths they took, and
830
+ * where they first went different ways. Pure. Use it for runs collected
831
+ * elsewhere, such as CI shards or replays; {@link repeatRuns} collects them and
832
+ * calls it.
833
+ *
834
+ * A scenario that passes 3 of 5 runs and `divergedAt: 'deciding'` points at one
835
+ * decision, not at a flaky agent.
836
+ *
837
+ * @example
838
+ * ```ts no-check
839
+ * const report = summarizeRepeats(shards.map((s) => ({ id: s.id, scenario: s, runs: s.runs })));
840
+ * report.passHat(3); // the chance 3 runs of a scenario all pass
841
+ * ```
842
+ */
843
+ function summarizeRepeats(groups) {
844
+ const scenarios = groups.map((group) => summarize$1(group));
845
+ const traces = groups.flatMap((group) => group.runs.flatMap((run) => run.trace ? [run.trace] : []));
846
+ const most = Math.max(0, ...groups.map((group) => group.runs.length));
847
+ const passHat = (j) => {
848
+ if (!Number.isInteger(j) || j < 1 || j > most) throw new require_event_log.AgentError("pass-hat-out-of-range", `passHat: j must be a whole number from 1 to ${most}, got ${j}.`);
849
+ const eligible = scenarios.filter((scenario) => scenario.runs.length >= j);
850
+ return eligible.reduce((total, scenario) => total + allPass(scenario.passes, scenario.runs.length, j), 0) / eligible.length;
851
+ };
852
+ return {
853
+ scenarios,
854
+ passHat,
855
+ traces
856
+ };
857
+ }
858
+ /**
859
+ * Runs every scenario `k` times and summarizes the runs with
860
+ * {@link summarizeRepeats}. Runs are sequential, scenario by scenario. A run
861
+ * that throws fails, with its message as `error` and no trace.
862
+ *
863
+ * With a live model, one run per scenario says little: τ-bench found pass^k
864
+ * falls well below the single-run rate. Report pass^k next to it.
865
+ *
866
+ * @example
867
+ * ```ts no-check
868
+ * const report = await repeatRuns({
869
+ * scenarios,
870
+ * k: 5,
871
+ * run: async (scenario) => {
872
+ * const trace: AgentTraceEvent[] = [];
873
+ * const result = await runToQuiescence(
874
+ * createAgentRuntime(machine, { executors, onTrace: (event) => trace.push(event) }),
875
+ * { input: scenario.input },
876
+ * );
877
+ * return { trace, outcome: String(result.snapshot.value) };
878
+ * },
879
+ * passed: (scenario, { outcome }) => outcome === scenario.expected,
880
+ * });
881
+ * report.passHat(5);
882
+ * ```
883
+ */
884
+ async function repeatRuns(options) {
885
+ if (!Number.isInteger(options.k) || options.k < 1) throw new require_event_log.AgentError("invalid-repeat-count", `repeatRuns: k must be a whole number of 1 or more, got ${options.k}.`);
886
+ const groups = [];
887
+ for (const scenario of options.scenarios) {
888
+ const runs = [];
889
+ for (let attempt = 0; attempt < options.k; attempt++) try {
890
+ const result = await options.run(scenario, attempt);
891
+ runs.push({
892
+ passed: options.passed(scenario, result),
893
+ trace: result.trace,
894
+ ...result.outcome === void 0 ? {} : { outcome: result.outcome }
895
+ });
896
+ } catch (error) {
897
+ runs.push({
898
+ passed: false,
899
+ error: error instanceof Error ? error.message : String(error)
900
+ });
901
+ }
902
+ groups.push({
903
+ id: scenario.id,
904
+ scenario,
905
+ runs
906
+ });
907
+ }
908
+ return summarizeRepeats(groups);
909
+ }
910
+ function summarize$1(group) {
911
+ const passes = group.runs.filter((run) => run.passed).length;
912
+ const traces = group.runs.flatMap((run) => run.trace ? [run.trace] : []);
913
+ const paths = new Set(traces.map((trace) => traceSteps(trace).filter((step) => !step.ignored).map((step) => `${step.from.join(",")}|${step.event}|${step.to.join(",")}`).join(" ")));
914
+ const reference = traces.find((trace) => trace.some((event) => event.type === "machine.transition"));
915
+ let earliest;
916
+ for (const trace of reference ? traces : []) {
917
+ if (trace === reference) continue;
918
+ const divergence = firstDivergence(trace, reference);
919
+ if (divergence && (!earliest || divergence.index < earliest.index)) earliest = divergence;
920
+ }
921
+ return {
922
+ ...group,
923
+ passes,
924
+ passAny: passes > 0,
925
+ passAll: group.runs.length > 0 && passes === group.runs.length,
926
+ distinctPaths: paths.size,
927
+ ...earliest ? { divergedAt: earliest.state } : {}
928
+ };
929
+ }
930
+ /** C(passes, j) / C(runs, j), as a product so large counts don't overflow. */
931
+ function allPass(passes, runs, j) {
932
+ let chance = 1;
933
+ for (let i = 0; i < j; i++) chance *= Math.max(0, passes - i) / (runs - i);
934
+ return chance;
935
+ }
936
+ //#endregion
937
+ //#region src/judge-agreement.ts
938
+ /**
939
+ * Measures how well a judge agrees with people on the same cases: accuracy,
940
+ * per-label recall, the confusion matrix, and the rows that disagree. With
941
+ * `positive`, also the TPR and TNR, the recommended view for binary judges
942
+ * (Husain/Shankar), and a correction for the judge's bias on unlabeled rows.
943
+ * Pure.
944
+ *
945
+ * Build rows from confirmed labels only; draft labels gate nothing. Group by
946
+ * decision state or request name so each narrow judge is aligned on its own.
947
+ * A row with no group key counts in the totals and in no group. Run it on a
948
+ * dev split and report the held-out split separately.
949
+ *
950
+ * Throws `AgentError` with code `'empty-agreement-rows'` when `rows` is empty.
951
+ *
952
+ * @example
953
+ * ```ts no-check
954
+ * const report = judgeAgreement(
955
+ * labeled.map((s) => ({ id: s.id, human: s.label, judge: verdicts[s.id], group: s.request })),
956
+ * { positive: 'fail' },
957
+ * );
958
+ * report.binary; // { tpr: 0.9, tnr: 0.8 }
959
+ * report.correct?.(0.3); // estimated true failure rate in production
960
+ * ```
961
+ */
962
+ function judgeAgreement(rows, options = {}) {
963
+ if (rows.length === 0) throw new require_event_log.AgentError("empty-agreement-rows", "judgeAgreement: rows must contain at least one row.");
964
+ const report = summarize(rows, options.positive);
965
+ const groupOf = options.groupBy ?? ((row) => row.group);
966
+ if (options.groupBy || rows.some((row) => row.group !== void 0)) {
967
+ const grouped = /* @__PURE__ */ new Map();
968
+ for (const row of rows) {
969
+ const key = groupOf(row);
970
+ if (key === void 0) continue;
971
+ const members = grouped.get(key);
972
+ if (members) members.push(row);
973
+ else grouped.set(key, [row]);
974
+ }
975
+ const groups = Object.create(null);
976
+ for (const [key, members] of grouped) groups[key] = summarize(members, options.positive);
977
+ report.groups = groups;
978
+ }
979
+ return report;
980
+ }
981
+ function summarize(rows, positive) {
982
+ const perLabel = Object.create(null);
983
+ const confusion = Object.create(null);
984
+ const disagreements = [];
985
+ let agreed = 0;
986
+ for (const { id, human, judge } of rows) {
987
+ const label = perLabel[human] ??= {
988
+ human: 0,
989
+ agreed: 0
990
+ };
991
+ const row = confusion[human] ??= Object.create(null);
992
+ label.human++;
993
+ row[judge] = (row[judge] ?? 0) + 1;
994
+ if (human === judge) {
995
+ label.agreed++;
996
+ agreed++;
997
+ } else disagreements.push({
998
+ id,
999
+ human,
1000
+ judge
1001
+ });
1002
+ }
1003
+ const summary = {
1004
+ total: rows.length,
1005
+ accuracy: agreed / rows.length,
1006
+ perLabel,
1007
+ confusion,
1008
+ disagreements
1009
+ };
1010
+ if (positive === void 0) return summary;
1011
+ let positives = 0;
1012
+ let truePositives = 0;
1013
+ let negatives = 0;
1014
+ let trueNegatives = 0;
1015
+ for (const { human, judge } of rows) if (human === positive) {
1016
+ positives++;
1017
+ if (judge === positive) truePositives++;
1018
+ } else {
1019
+ negatives++;
1020
+ if (judge !== positive) trueNegatives++;
1021
+ }
1022
+ const tpr = positives === 0 ? void 0 : truePositives / positives;
1023
+ const tnr = negatives === 0 ? void 0 : trueNegatives / negatives;
1024
+ summary.binary = {
1025
+ tpr,
1026
+ tnr
1027
+ };
1028
+ if (tpr !== void 0 && tnr !== void 0 && tpr + tnr > 1) summary.correct = (p) => Math.min(1, Math.max(0, (p + tnr - 1) / (tpr + tnr - 1)));
1029
+ return summary;
1030
+ }
1031
+ //#endregion
484
1032
  //#region src/compare-runs.ts
485
1033
  /**
486
1034
  * Runs every scenario through a baseline and a candidate implementation and
@@ -586,15 +1134,483 @@ function structurallyEqual(a, b) {
586
1134
  return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && structurallyEqual(a[key], b[key]));
587
1135
  }
588
1136
  //#endregion
1137
+ //#region src/equivalence.ts
1138
+ /**
1139
+ * Thrown in replay when the port asks for something the recording cannot
1140
+ * answer: a model call past the last recorded one, or a tool call the original
1141
+ * never made. The effect is still recorded, so {@link compareRecordings}
1142
+ * reports it.
1143
+ */
1144
+ var RecordingDivergenceError = class extends Error {
1145
+ name = "RecordingDivergenceError";
1146
+ };
1147
+ function toRecordedError(error) {
1148
+ if (error instanceof Error) {
1149
+ const code = error.code;
1150
+ return code === void 0 ? {
1151
+ name: error.name,
1152
+ message: error.message
1153
+ } : {
1154
+ name: error.name,
1155
+ message: error.message,
1156
+ code: toJson(code)
1157
+ };
1158
+ }
1159
+ return {
1160
+ name: "Error",
1161
+ message: String(error)
1162
+ };
1163
+ }
1164
+ function fromRecordedError(error) {
1165
+ return Object.assign(new Error(error.message), error);
1166
+ }
1167
+ /** A JSON-safe copy: Dates become ISO strings, Errors become {@link RecordedError}. */
1168
+ function toJson(value) {
1169
+ if (value === void 0) return void 0;
1170
+ return JSON.parse(JSON.stringify(value, function(key, item) {
1171
+ const raw = this[key];
1172
+ if (raw instanceof Date) return raw.toISOString();
1173
+ if (item instanceof Error) return toRecordedError(item);
1174
+ if (typeof item === "bigint") return item.toString();
1175
+ if (item instanceof Uint8Array) return Array.from(item);
1176
+ return item;
1177
+ }));
1178
+ }
1179
+ /** Restores the `Date` timestamps the AI SDK puts on responses. */
1180
+ function reviveTimestamps(value) {
1181
+ if (value && typeof value === "object") {
1182
+ for (const holder of [value, value.response]) if (holder && typeof holder["timestamp"] === "string") holder["timestamp"] = new Date(holder["timestamp"]);
1183
+ }
1184
+ return value;
1185
+ }
1186
+ function omit(value, keys) {
1187
+ if (!value || typeof value !== "object") return value;
1188
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
1189
+ }
1190
+ /** Key-order-independent JSON, for equality. */
1191
+ function stableStringify(value) {
1192
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1193
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
1194
+ return JSON.stringify(value) ?? "undefined";
1195
+ }
1196
+ function jsonEqual(a, b) {
1197
+ return stableStringify(toJson(a)) === stableStringify(toJson(b));
1198
+ }
1199
+ function streamFrom(parts) {
1200
+ return new ReadableStream({ start(controller) {
1201
+ for (const part of parts) controller.enqueue(reviveTimestamps(structuredClone(part)));
1202
+ controller.close();
1203
+ } });
1204
+ }
1205
+ async function* iterate(chunks) {
1206
+ for (const chunk of chunks) yield structuredClone(chunk);
1207
+ }
1208
+ /**
1209
+ * Creates a {@link Recorder}. With no options it records: every wrapped call
1210
+ * runs for real. With `replay` it answers from a recording instead.
1211
+ */
1212
+ function createRecorder(options = {}) {
1213
+ const effects = [];
1214
+ const replay = options.replay?.effects;
1215
+ const replayedModels = replay?.filter((effect) => effect.kind === "model");
1216
+ const usedTools = /* @__PURE__ */ new Set();
1217
+ const normalizeEffect = options.normalize ?? ((effect) => effect);
1218
+ let modelCalls = 0;
1219
+ let toolsInFlight = 0;
1220
+ function nextReplayedModel(effect) {
1221
+ const recorded = replayedModels[effect.call];
1222
+ if (!recorded) throw new RecordingDivergenceError(`Model call #${effect.call} was never made by the recorded run (it made ${replayedModels.length}).`);
1223
+ if (recorded.method !== effect.method) throw new RecordingDivergenceError(`Model call #${effect.call} uses ${effect.method}; the recorded run used ${recorded.method}.`);
1224
+ if (!modelCallsMatch(options.modelCalls, recorded, effect)) throw new RecordingDivergenceError(shapeMessage(recorded, effect));
1225
+ return recorded;
1226
+ }
1227
+ /** Records a model call around `run`, or answers it from the recording. */
1228
+ async function modelCall(seam, method, request, streamed, run) {
1229
+ const effect = {
1230
+ kind: "model",
1231
+ seam,
1232
+ method,
1233
+ call: modelCalls++,
1234
+ request: toJson(omit(request, [
1235
+ "abortSignal",
1236
+ "headers",
1237
+ "signal"
1238
+ ]))
1239
+ };
1240
+ effects.push(effect);
1241
+ if (replay) {
1242
+ let recorded;
1243
+ try {
1244
+ recorded = nextReplayedModel(effect);
1245
+ } catch (error) {
1246
+ effect.error = toRecordedError(error);
1247
+ throw error;
1248
+ }
1249
+ if (recorded.error) {
1250
+ effect.error = recorded.error;
1251
+ throw fromRecordedError(recorded.error);
1252
+ }
1253
+ effect.response = recorded.response;
1254
+ effect.stream = recorded.stream;
1255
+ if (seam === "openai") return streamed ? iterate(recorded.stream ?? []) : structuredClone(recorded.response);
1256
+ return streamed ? {
1257
+ ...reviveTimestamps(structuredClone(recorded.response) ?? {}),
1258
+ stream: streamFrom(recorded.stream ?? [])
1259
+ } : reviveTimestamps(structuredClone(recorded.response));
1260
+ }
1261
+ let result;
1262
+ try {
1263
+ result = await run();
1264
+ } catch (error) {
1265
+ effect.error = toRecordedError(error);
1266
+ throw error;
1267
+ }
1268
+ if (!streamed) {
1269
+ effect.response = toJson(result);
1270
+ return result;
1271
+ }
1272
+ const parts = [];
1273
+ effect.stream = parts;
1274
+ if (seam === "openai") {
1275
+ const source = result;
1276
+ return (async function* () {
1277
+ for await (const chunk of source) {
1278
+ parts.push(toJson(chunk));
1279
+ yield chunk;
1280
+ }
1281
+ })();
1282
+ }
1283
+ const { stream, ...rest } = result;
1284
+ effect.response = toJson(rest);
1285
+ return {
1286
+ ...rest,
1287
+ stream: stream.pipeThrough(new TransformStream({ transform(part, controller) {
1288
+ parts.push(toJson(part));
1289
+ controller.enqueue(part);
1290
+ } }))
1291
+ };
1292
+ }
1293
+ /** `inputOf` picks the recorded input from the call's arguments. */
1294
+ function tool(name, fn, inputOf = (args) => args.length === 1 ? args[0] : args) {
1295
+ return ((...args) => {
1296
+ const input = toJson(inputOf(args));
1297
+ const effect = {
1298
+ kind: "tool",
1299
+ name,
1300
+ step: modelCalls,
1301
+ input,
1302
+ ...toolsInFlight > 0 ? { concurrent: true } : {}
1303
+ };
1304
+ effects.push(effect);
1305
+ return track(call(effect, args));
1306
+ });
1307
+ function call(effect, args) {
1308
+ const { input } = effect;
1309
+ if (replay && options.tools !== "live") {
1310
+ const wanted = normalizeEffect(effect).input;
1311
+ const recorded = replay.find((candidate) => candidate.kind === "tool" && !usedTools.has(candidate) && candidate.step === effect.step && candidate.name === name && jsonEqual(normalizeEffect(candidate).input, wanted));
1312
+ const settle = (value) => {
1313
+ if (recorded?.sync) return value();
1314
+ try {
1315
+ return Promise.resolve(value());
1316
+ } catch (error) {
1317
+ return Promise.reject(error);
1318
+ }
1319
+ };
1320
+ return settle(() => {
1321
+ if (!recorded) {
1322
+ const error = new RecordingDivergenceError(`Tool '${name}' was called with ${JSON.stringify(input)} ${effect.step === 0 ? "before any model call" : `after model call #${effect.step - 1}`}; the recorded run made no such call.`);
1323
+ effect.error = toRecordedError(error);
1324
+ throw error;
1325
+ }
1326
+ usedTools.add(recorded);
1327
+ if (recorded.sync) effect.sync = true;
1328
+ if (recorded.error) {
1329
+ effect.error = recorded.error;
1330
+ throw fromRecordedError(recorded.error);
1331
+ }
1332
+ effect.output = recorded.output;
1333
+ return structuredClone(recorded.output);
1334
+ });
1335
+ }
1336
+ let output;
1337
+ try {
1338
+ output = fn(...args);
1339
+ } catch (error) {
1340
+ effect.sync = true;
1341
+ effect.error = toRecordedError(error);
1342
+ throw error;
1343
+ }
1344
+ if (!(output instanceof Promise)) {
1345
+ effect.sync = true;
1346
+ effect.output = toJson(output);
1347
+ return output;
1348
+ }
1349
+ return output.then((value) => {
1350
+ effect.output = toJson(value);
1351
+ return value;
1352
+ }, (error) => {
1353
+ effect.error = toRecordedError(error);
1354
+ throw error;
1355
+ });
1356
+ }
1357
+ }
1358
+ /** Counts an async tool call as running until it settles. */
1359
+ function track(result) {
1360
+ if (result instanceof Promise) {
1361
+ toolsInFlight++;
1362
+ const settled = () => {
1363
+ toolsInFlight--;
1364
+ };
1365
+ result.then(settled, settled);
1366
+ }
1367
+ return result;
1368
+ }
1369
+ return {
1370
+ model(model) {
1371
+ const base = model;
1372
+ const wrapped = Object.create(base);
1373
+ wrapped["doGenerate"] = (callOptions) => modelCall("ai-sdk", "doGenerate", callOptions, false, () => base["doGenerate"].call(base, callOptions));
1374
+ wrapped["doStream"] = (callOptions) => modelCall("ai-sdk", "doStream", callOptions, true, () => base["doStream"].call(base, callOptions));
1375
+ return wrapped;
1376
+ },
1377
+ openai(client) {
1378
+ const wrapCreate = (resource, method) => new Proxy(resource, { get(target, key, receiver) {
1379
+ if (key !== "create") return Reflect.get(target, key, receiver);
1380
+ return (params, requestOptions) => {
1381
+ let api;
1382
+ const promise = modelCall("openai", method, params, params?.stream === true, () => {
1383
+ api = Reflect.get(target, "create").call(target, params, requestOptions);
1384
+ return Promise.resolve(api);
1385
+ });
1386
+ return Object.assign(promise, { withResponse: async () => {
1387
+ const data = await promise;
1388
+ const meta = await api?.withResponse?.();
1389
+ return {
1390
+ data,
1391
+ response: meta?.response ?? new Response(null),
1392
+ request_id: meta?.request_id ?? null
1393
+ };
1394
+ } });
1395
+ };
1396
+ } });
1397
+ const wrapped = /* @__PURE__ */ new Map();
1398
+ const wrap = (key, make) => {
1399
+ if (!wrapped.has(key)) wrapped.set(key, make());
1400
+ return wrapped.get(key);
1401
+ };
1402
+ return new Proxy(client, { get(target, key, receiver) {
1403
+ const value = Reflect.get(target, key, receiver);
1404
+ if (key === "responses" && value) return wrap(key, () => wrapCreate(value, "responses.create"));
1405
+ if (key === "chat" && value) return wrap(key, () => new Proxy(value, { get(chat, chatKey, chatReceiver) {
1406
+ const inner = Reflect.get(chat, chatKey, chatReceiver);
1407
+ return chatKey === "completions" && inner ? wrap("chat.completions", () => wrapCreate(inner, "chat.completions.create")) : inner;
1408
+ } }));
1409
+ return value;
1410
+ } });
1411
+ },
1412
+ tool: (name, fn) => tool(name, fn),
1413
+ tools(tools) {
1414
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => [name, definition.execute ? {
1415
+ ...definition,
1416
+ execute: tool(name, definition.execute, (args) => args[0])
1417
+ } : definition]));
1418
+ },
1419
+ output(value) {
1420
+ effects.push({
1421
+ kind: "output",
1422
+ value: toJson(value)
1423
+ });
1424
+ },
1425
+ get recording() {
1426
+ return {
1427
+ version: 1,
1428
+ effects: toJson(effects)
1429
+ };
1430
+ }
1431
+ };
1432
+ }
1433
+ /** True when two model calls offer the same tool names and response format. */
1434
+ function sameModelCallShape(expected, actual) {
1435
+ return jsonEqual(modelCallShape(expected), modelCallShape(actual));
1436
+ }
1437
+ function modelCallsMatch(match, expected, actual) {
1438
+ if (match === "none") return true;
1439
+ if (typeof match === "function") return match(expected, actual);
1440
+ return sameModelCallShape(expected, actual);
1441
+ }
1442
+ function shapeMessage(expected, actual) {
1443
+ return `Model call #${expected.call} changed shape: ${JSON.stringify(modelCallShape(expected))} → ${JSON.stringify(modelCallShape(actual))}. A recorded answer only fits a call of the same shape.`;
1444
+ }
1445
+ /** Offered tool names and the response format: what a recorded answer depends on. */
1446
+ function modelCallShape(effect) {
1447
+ const request = effect.request ?? {};
1448
+ return {
1449
+ tools: (Array.isArray(request["tools"]) ? request["tools"] : []).map((tool) => tool["name"] ?? tool["function"]?.["name"]).sort(),
1450
+ format: request["responseFormat"]?.["type"] ?? request["response_format"]?.["type"] ?? (request["text"]?.["format"])?.["type"] ?? "text"
1451
+ };
1452
+ }
1453
+ /**
1454
+ * Puts each group of concurrent tool calls in a stable order, so parallel tool
1455
+ * calls that finished in a different order still compare equal. A tool call
1456
+ * that started after the previous one settled begins a new group, so
1457
+ * sequential calls keep their order.
1458
+ */
1459
+ function normalize(effects) {
1460
+ const result = [];
1461
+ let batch = [];
1462
+ const flush = () => {
1463
+ result.push(...batch.sort((a, b) => stableStringify([a.name, a.input]).localeCompare(stableStringify([b.name, b.input]))));
1464
+ batch = [];
1465
+ };
1466
+ for (const effect of effects) {
1467
+ if (effect.kind !== "tool" || !effect.concurrent) flush();
1468
+ if (effect.kind === "tool") batch.push(effect);
1469
+ else result.push(effect);
1470
+ }
1471
+ flush();
1472
+ return result;
1473
+ }
1474
+ function describe(effect) {
1475
+ switch (effect.kind) {
1476
+ case "model": return `model call #${effect.call} (${effect.method})`;
1477
+ case "tool": return `tool '${effect.name}' with ${JSON.stringify(effect.input)}`;
1478
+ case "output": return `output ${JSON.stringify(effect.value)}`;
1479
+ }
1480
+ }
1481
+ /** Why two effects differ, or `undefined` when they are the same. */
1482
+ function differ(left, right, options) {
1483
+ if (left.kind !== right.kind) return {
1484
+ reason: "kind",
1485
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1486
+ };
1487
+ if (left.kind === "model" && right.kind === "model") {
1488
+ if (left.method !== right.method) return {
1489
+ reason: "model-method",
1490
+ message: `Model call #${left.call} used ${left.method}; the port used ${right.method}.`
1491
+ };
1492
+ if (!modelCallsMatch(options.modelCalls, left, right)) return {
1493
+ reason: "model-call-shape",
1494
+ message: shapeMessage(left, right)
1495
+ };
1496
+ if (!jsonEqual(left.error, right.error)) {
1497
+ const outcome = (error) => error ? `failed with ${error.name}: ${error.message}` : "succeeded";
1498
+ return {
1499
+ reason: "model-error",
1500
+ message: `Model call #${left.call} ${outcome(left.error)}; in the port it ${outcome(right.error)}.`
1501
+ };
1502
+ }
1503
+ return;
1504
+ }
1505
+ if (left.kind === "tool" && right.kind === "tool") {
1506
+ if (left.name !== right.name) return {
1507
+ reason: "tool-name",
1508
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1509
+ };
1510
+ if (!jsonEqual(left.input, right.input)) return {
1511
+ reason: "tool-input",
1512
+ message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.input)}.`
1513
+ };
1514
+ if (!jsonEqual(left.output, right.output) || !jsonEqual(left.error, right.error)) return {
1515
+ reason: "tool-result",
1516
+ message: `Tool '${left.name}' returned a different result.`
1517
+ };
1518
+ return;
1519
+ }
1520
+ if (left.kind === "output" && right.kind === "output" && !jsonEqual(left.value, right.value)) return {
1521
+ reason: "output",
1522
+ message: `Expected ${describe(left)}; the port returned ${JSON.stringify(right.value)}.`
1523
+ };
1524
+ }
1525
+ /**
1526
+ * Compares two recordings and reports every effect that differs. `expected`
1527
+ * is the original's recording, `actual` the port's. Effects that are the same
1528
+ * on both sides are lined up first (longest common subsequence), so one extra
1529
+ * call does not shift every effect after it; between them, effects of the same
1530
+ * kind pair up and report what changed, and the rest are missing or extra.
1531
+ */
1532
+ function compareRecordings(expected, actual, options = {}) {
1533
+ const map = options.normalize ?? ((effect) => effect);
1534
+ const a = normalize(expected.effects.map(map));
1535
+ const b = normalize(actual.effects.map(map));
1536
+ const same = a.map((left) => b.map((right) => !differ(left, right, options)));
1537
+ const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }, () => 0));
1538
+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = same[i][j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
1539
+ const divergences = [];
1540
+ let lefts = [];
1541
+ let rights = [];
1542
+ const flushGap = (at) => {
1543
+ const unpairedRights = [...rights];
1544
+ const changed = [];
1545
+ for (const index of lefts) {
1546
+ const left = a[index];
1547
+ const k = unpairedRights.findIndex((j) => b[j].kind === left.kind);
1548
+ if (k === -1) {
1549
+ changed.push({
1550
+ index,
1551
+ reason: "missing-effect",
1552
+ expected: left,
1553
+ message: `The port never made ${describe(left)}.`
1554
+ });
1555
+ continue;
1556
+ }
1557
+ const right = b[unpairedRights.splice(k, 1)[0]];
1558
+ const difference = differ(left, right, options);
1559
+ if (difference) changed.push({
1560
+ index,
1561
+ expected: left,
1562
+ actual: right,
1563
+ ...difference
1564
+ });
1565
+ }
1566
+ for (const j of unpairedRights) divergences.push({
1567
+ index: lefts[0] ?? at,
1568
+ reason: "extra-effect",
1569
+ actual: b[j],
1570
+ message: `The port made ${describe(b[j])}, which the original never made.`
1571
+ });
1572
+ divergences.push(...changed);
1573
+ lefts = [];
1574
+ rights = [];
1575
+ };
1576
+ let i = 0;
1577
+ let j = 0;
1578
+ while (i < a.length || j < b.length) if (i < a.length && j < b.length && same[i][j]) {
1579
+ flushGap(i);
1580
+ i++;
1581
+ j++;
1582
+ } else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) rights.push(j++);
1583
+ else lefts.push(i++);
1584
+ flushGap(i);
1585
+ divergences.sort((x, y) => x.index - y.index);
1586
+ return divergences.length ? {
1587
+ equivalent: false,
1588
+ divergence: divergences[0],
1589
+ divergences
1590
+ } : {
1591
+ equivalent: true,
1592
+ divergences
1593
+ };
1594
+ }
1595
+ //#endregion
589
1596
  exports.AgentLintError = require_verify.AgentLintError;
590
1597
  exports.AgentUnknownStateError = require_verify.AgentUnknownStateError;
1598
+ exports.RecordingDivergenceError = RecordingDivergenceError;
591
1599
  exports.assertAgentMachine = require_verify.assertAgentMachine;
592
1600
  exports.canReach = require_verify.canReach;
1601
+ exports.compareRecordings = compareRecordings;
593
1602
  exports.compareRuns = compareRuns;
1603
+ exports.createRecorder = createRecorder;
594
1604
  exports.explorePaths = require_verify.explorePaths;
1605
+ exports.firstDivergence = firstDivergence;
595
1606
  exports.foldTraces = foldTraces;
596
1607
  exports.getDecisionRequests = getDecisionRequests;
1608
+ exports.judgeAgreement = judgeAgreement;
597
1609
  exports.lintAgentMachine = require_verify.lintAgentMachine;
598
1610
  exports.matchesTrajectory = matchesTrajectory;
1611
+ exports.repeatRuns = repeatRuns;
599
1612
  exports.runSeam = runSeam;
1613
+ exports.sameModelCallShape = sameModelCallShape;
600
1614
  exports.simulateAgent = require_verify.simulateAgent;
1615
+ exports.summarizeRepeats = summarizeRepeats;
1616
+ exports.traceCoverage = traceCoverage;