@statelyai/agent 2.0.0-alpha.35 → 2.0.0-alpha.37

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 (130) hide show
  1. package/CHANGELOG.md +138 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-Ct_GZw_f.mjs → effects-BT_cSY0j.mjs} +1003 -109
  13. package/dist/{run-agent-s5D32w99.cjs → effects-DDseYtJk.cjs} +1037 -107
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-30mH2moE.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-DlPzBWj-.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BaNyz6Q3.d.cts} +4 -4
  46. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-C1CG_nfX.d.mts} +4 -4
  47. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +2493 -1502
  53. package/dist/testing.d.cts +360 -256
  54. package/dist/testing.d.mts +360 -256
  55. package/dist/testing.mjs +2489 -1503
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-Bm5nvpow.d.cts} +6 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-BnikdOca.d.mts} +6 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-ChyX6jq0.mjs +2306 -0
  69. package/dist/verify-CwlombbC.cjs +2359 -0
  70. package/dist/{verify-BQpE8hUz.d.cts → verify-DJHfEfm6.d.cts} +213 -14
  71. package/dist/{verify-CqeuEmIk.d.mts → verify-i9Hiwc5g.d.mts} +213 -14
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +312 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +207 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +56 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +518 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +492 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +84 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -192
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
package/dist/testing.cjs CHANGED
@@ -1,1685 +1,2671 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
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");
2
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
3
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
4
+ const require_act = require("./act-CrX0JwWY.cjs");
5
+ const require_effects = require("./effects-DDseYtJk.cjs");
6
+ const require_event_log_store = require("./event-log-store-Cl-YWDnq.cjs");
7
+ const require_verify = require("./verify-CwlombbC.cjs");
5
8
  let xstate = require("xstate");
6
- //#region src/trajectory.ts
7
- /**
8
- * Classifies one item. Event-shaped things (log entries, events) become events;
9
- * everything else is a state value. A snapshot is unwrapped to its `value`.
10
- * @internal
11
- */
12
- function normalize$1(item) {
13
- if (require_event_log.isRecord(item)) {
14
- const nested = item["event"];
15
- if (require_event_log.isRecord(nested) && typeof nested["type"] === "string") return {
16
- kind: "event",
17
- event: nested
18
- };
19
- if (typeof item["type"] === "string") return {
20
- kind: "event",
21
- event: item
22
- };
23
- if ("value" in item) return {
24
- kind: "state",
25
- value: item["value"]
26
- };
27
- }
28
- return {
29
- kind: "state",
30
- value: item
31
- };
32
- }
33
- /** Every leaf of a state value as a dot path (`{ review: 'editing' }` → `review.editing`). @internal */
34
- function statePaths$1(value) {
35
- if (typeof value === "string") return [value];
36
- if (!require_event_log.isRecord(value)) return [];
37
- return Object.entries(value).flatMap(([key, child]) => statePaths$1(child).map((path) => `${key}.${path}`));
38
- }
39
- /**
40
- * A string expectation matches a state value when it names one of its leaves or
41
- * an ancestor of one, so `'review'` matches `{ review: 'editing' }`. @internal
42
- */
43
- function stateMatchesPath(path, value) {
44
- return statePaths$1(value).some((leaf) => leaf === path || leaf.startsWith(`${path}.`));
45
- }
46
- function deepEqual(a, b) {
47
- if (Object.is(a, b)) return true;
48
- if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => deepEqual(item, b[index]));
49
- if (!require_event_log.isRecord(a) || !require_event_log.isRecord(b)) return false;
50
- const keys = Object.keys(a);
51
- return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
52
- }
53
- /**
54
- * Normalizes ONE expected item into a predicate over actual items, so the
55
- * expectation is classified once instead of once per candidate:
56
- *
57
- * - A string expectation matches an event's `type`, or a state value it names.
58
- * - An event expectation matches an event with the same `type` whose other
59
- * declared keys deep-equal, so payload details are opt-in.
60
- * - A state-value expectation matches structurally.
61
- * @internal
62
- */
63
- function matcherFor(expected) {
64
- if (typeof expected === "string") return (actual) => {
65
- const actualItem = normalize$1(actual);
66
- return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
67
- };
68
- const expectedItem = normalize$1(expected);
69
- switch (expectedItem.kind) {
70
- case "event": return (actual) => {
71
- const actualItem = normalize$1(actual);
72
- return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
73
- };
74
- case "state": return (actual) => {
75
- const actualItem = normalize$1(actual);
76
- return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
77
- };
78
- }
79
- }
9
+ //#region src/equivalence.ts
80
10
  /**
81
- * Matches a run's trajectory against an expected one.
11
+ * Verified equivalence — prove a port behaves like the code it replaces.
82
12
  *
83
- * Both trajectories may be state values or events collected from
84
- * `onTransition`;
85
- * items are compared by shape, so `['prompting', 'drafting']` scores a state
86
- * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
87
- * call.
13
+ * A port is equivalent when, given the same model answers and the same tool
14
+ * results, it produces the same OBSERVABLE EFFECTS: the same number of model
15
+ * calls, the same tool calls with the same arguments, and the same output.
16
+ * Prompts, internal steps, and states are free to differ.
88
17
  *
89
- * Semantics are an ordered subsequence: every expected item must appear in
90
- * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
91
- * equality instead.
18
+ * 1. Record the original: wrap its model (`recorder.model`, an AI SDK
19
+ * `LanguageModelV3`, or `recorder.openai`, an `openai` client) and its tools
20
+ * (`recorder.tool` / `recorder.tools`), run a scenario, call
21
+ * `recorder.output(result)`, and save `recorder.recording`.
22
+ * 2. Replay it on the port: `createRecorder({ replay: recording })` answers
23
+ * every model call and tool call from the recording, with no API key and no
24
+ * side effects, and records what the port did.
25
+ * 3. `compareRecordings(original, port)` reports the first effect that differs.
92
26
  *
93
- * @example Trajectory assertions in a test
94
- * ```ts
95
- * const statePath: unknown[] = [];
96
- * const result = await runToQuiescence(
97
- * createAgentRuntime(machine, {
98
- * executors,
99
- * onTransition: (snapshot) => statePath.push(snapshot.value),
100
- * }),
101
- * { input },
102
- * );
27
+ * A port that changes how it calls the model on purpose (a model-picked action
28
+ * that became `agent.decide`, a stream that became `doGenerate`) still replays:
29
+ * `translate` turns the recorded answer into one that fits, `fallback` answers
30
+ * the calls the original never made, and `compareRecordings(…, { kinds })`
31
+ * compares only tool calls and output.
103
32
  *
104
- * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
105
- * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
106
- * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
107
- * ```
33
+ * Any other client (`@anthropic-ai/sdk`, `@google/genai`, a framework's own
34
+ * model client) records through `recorder.client` or `recorder.fn`: each call
35
+ * is a `call` effect, answered in replay by name and order.
108
36
  *
109
- * @example Partial credit in an eval scorer
110
- * ```ts
111
- * const match = matchesTrajectory(output.statePath, expected.statePath);
112
- * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
113
- * ```
37
+ * Provider-free: every seam is wrapped structurally, so this module imports
38
+ * neither `ai` nor `openai`.
39
+ * @module
114
40
  */
115
- function matchesTrajectory(actual, expected, options = {}) {
116
- const expectedCount = expected.length;
117
- if (expectedCount === 0) throw new require_event_log.AgentError("empty-trajectory", "matchesTrajectory: expected trajectory must contain at least one item.");
118
- const exact = options.exact === true;
119
- let cursor = 0;
120
- let matchedCount = 0;
121
- let firstMiss;
122
- for (let index = 0; index < expectedCount; index++) {
123
- const want = expected[index];
124
- const matches = matcherFor(want);
125
- const searchedFrom = exact ? index : cursor;
126
- let found = -1;
127
- for (let at = searchedFrom; at < actual.length; at++) {
128
- if (matches(actual[at])) {
129
- found = at;
130
- break;
131
- }
132
- if (exact) break;
133
- }
134
- if (found === -1) {
135
- firstMiss = {
136
- index,
137
- expected: want,
138
- searchedFrom
139
- };
140
- break;
141
- }
142
- matchedCount++;
143
- cursor = found + 1;
144
- }
145
- const matched = !firstMiss && (!exact || actual.length === expectedCount);
146
- const denominator = exact ? Math.max(expectedCount, actual.length) : expectedCount;
147
- return {
148
- matched,
149
- matchedCount,
150
- expectedCount,
151
- score: matched ? 1 : denominator === 0 ? 1 : matchedCount / denominator,
152
- ...firstMiss ? { firstMiss } : {}
153
- };
154
- }
155
- //#endregion
156
- //#region src/seam.ts
157
- /** The only own keys an executor result carries. @internal */
158
- const TEXT_RESULT_KEYS = /* @__PURE__ */ new Set([
159
- "result",
160
- "messages",
161
- "usage",
162
- "raw"
163
- ]);
164
41
  /**
165
- * True when a scripted entry is the executor result rather than the output
166
- * value: it owns a `result` key and owns NOTHING outside the result's own
167
- * vocabulary. Bare `'result' in value` would swallow an output object's
168
- * siblings (`{ result: 'draft', confidence: 0.9 }` would lose `confidence`)
169
- * and would also match an inherited `result`. @internal
42
+ * Thrown in replay when the port asks for something the recording cannot
43
+ * answer: a model call past the last recorded one, or a tool call the original
44
+ * never made. The effect is still recorded, so {@link compareRecordings}
45
+ * reports it.
170
46
  */
171
- function isTextResult(value) {
172
- return Object.hasOwn(value, "result") && Object.keys(value).every((key) => TEXT_RESULT_KEYS.has(key));
47
+ var RecordingDivergenceError = class extends Error {
48
+ name = "RecordingDivergenceError";
49
+ };
50
+ function toRecordedError(error) {
51
+ if (!(error instanceof Error)) return {
52
+ name: "Error",
53
+ message: String(error)
54
+ };
55
+ const recorded = {
56
+ name: error.name,
57
+ message: error.message
58
+ };
59
+ if (Object.prototype.propertyIsEnumerable.call(error, "name")) recorded.ownName = true;
60
+ const code = error.code;
61
+ if (code !== void 0) recorded.code = toJson(code);
62
+ const data = Object.fromEntries(Object.entries(error).filter(([key, value]) => key !== "code" && (typeof value === "number" || typeof value === "boolean")));
63
+ if (Object.keys(data).length) recorded.data = data;
64
+ const markers = /* @__PURE__ */ new Set();
65
+ for (let holder = error; holder; holder = Object.getPrototypeOf(holder)) for (const symbol of Object.getOwnPropertySymbols(holder)) {
66
+ const key = Symbol.keyFor(symbol);
67
+ if (key !== void 0 && error[symbol] === true) markers.add(key);
68
+ }
69
+ if (markers.size) recorded.markers = [...markers];
70
+ return recorded;
173
71
  }
174
- /**
175
- * Resolves ONE scripted entry to an executor result: a function entry is
176
- * called with the request, and the value is taken as the executor result only
177
- * when it is one (see {@link isTextResult}). @internal
178
- */
179
- async function resolveSeamScriptEntry(entry, request, info) {
180
- const value = typeof entry === "function" ? await entry(request, info) : entry;
181
- return require_event_log.isRecord(value) && isTextResult(value) ? value : { result: value };
72
+ function fromRecordedError({ data, markers, name, ownName, ...fields }) {
73
+ const error = Object.assign(new Error(fields.message), fields, data);
74
+ if (ownName || name !== "Error") Object.defineProperty(error, "name", {
75
+ value: name,
76
+ writable: true,
77
+ configurable: true,
78
+ enumerable: ownName ?? false
79
+ });
80
+ for (const marker of markers ?? []) error[Symbol.for(marker)] = true;
81
+ return error;
182
82
  }
183
- /** Names a pending text request in an error message. @internal */
184
- function describeText(request) {
185
- return request.name ? `'${request.name}' (model '${request.model}')` : `(model '${request.model}')`;
83
+ /** What two runs compare of an error: its data and markers may differ. */
84
+ function errorIdentity$1(error) {
85
+ return error && {
86
+ name: error.name,
87
+ message: error.message,
88
+ code: error.code
89
+ };
186
90
  }
187
- /**
188
- * Stream semantics with no model: the whole text lands as one chunk. @internal
189
- */
190
- function emitScriptedChunk(result, info) {
191
- const text = require_event_log.isRecord(result) ? result["result"] : void 0;
192
- if (typeof text === "string") info?.onChunk?.(text);
91
+ /** A JSON-safe copy: Dates become ISO strings, Errors become {@link RecordedError}. */
92
+ function toJson(value) {
93
+ if (value === void 0) return void 0;
94
+ return JSON.parse(JSON.stringify(value, function(key, item) {
95
+ const raw = this[key];
96
+ if (raw instanceof Date) return raw.toISOString();
97
+ if (item instanceof Error) return toRecordedError(item);
98
+ if (typeof item === "bigint") return item.toString();
99
+ if (item instanceof Uint8Array) return Array.from(item);
100
+ return item;
101
+ }));
102
+ }
103
+ /** Restores the `Date` timestamps the AI SDK puts on responses. */
104
+ function reviveTimestamps(value) {
105
+ if (value && typeof value === "object") {
106
+ for (const holder of [value, value.response]) if (holder && typeof holder["timestamp"] === "string") holder["timestamp"] = new Date(holder["timestamp"]);
107
+ }
108
+ return value;
109
+ }
110
+ function omit(value, keys) {
111
+ if (!value || typeof value !== "object") return value;
112
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
193
113
  }
194
114
  /**
195
- * The seam's own answer, for scoring: the executor result's `result`.
115
+ * Key-order-independent JSON, for equality.
196
116
  * @internal
197
117
  */
198
- async function seamOutputOf(result, request) {
199
- if (!require_event_log.isRecord(result)) return;
200
- return await require_event_log.normalizeGeneratorResult(result, `seam '${request.name ?? request.model}'`);
118
+ function stableStringify(value) {
119
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
120
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
121
+ return JSON.stringify(value) ?? "undefined";
122
+ }
123
+ function jsonEqual(a, b) {
124
+ return stableStringify(toJson(a)) === stableStringify(toJson(b));
125
+ }
126
+ function streamFrom(parts) {
127
+ return new ReadableStream({ start(controller) {
128
+ for (const part of parts) controller.enqueue(reviveTimestamps(structuredClone(part)));
129
+ controller.close();
130
+ } });
131
+ }
132
+ async function* iterate(chunks) {
133
+ for (const chunk of chunks) yield structuredClone(chunk);
201
134
  }
202
135
  /**
203
- * Runs a machine end to end with one model call under test, and slices the run
204
- * at that call.
205
- *
206
- * The `before`/`after` slices are the point: `after.statePath` is the branch
207
- * the seam chose and `after.events` is the same question against the durable
208
- * log, both ready for `matchesTrajectory`. The state slice splits where the
209
- * state path stood when the seam answered; the event slice splits at the
210
- * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
211
- * entry appended after the call was made).
212
- *
213
- * @example No API key: the seam is scripted too, so the whole thing runs offline.
214
- * ```ts
215
- * const run = await runSeam(emailDrafter, {
216
- * scripts: { writeFollowUps: [followUps], emailDrafter: [draft] },
217
- * seam: { request: 'writeFollowUps' },
218
- * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
219
- * });
136
+ * Creates a {@link Recorder}. With no options it records: every wrapped call
137
+ * runs for real. With `replay` it answers from a recording instead.
138
+ */
139
+ function createRecorder(options = {}) {
140
+ const effects = [];
141
+ const replay = options.replay?.effects;
142
+ const replayedModels = replay?.filter((effect) => effect.kind === "model");
143
+ const usedModels = /* @__PURE__ */ new Set();
144
+ const usedTools = /* @__PURE__ */ new Set();
145
+ const usedCalls = /* @__PURE__ */ new Set();
146
+ const callCounts = /* @__PURE__ */ new Map();
147
+ const normalizeEffect = (effect, list) => options.normalize?.(effect, list.indexOf(effect), list) ?? effect;
148
+ let modelCalls = 0;
149
+ let toolsInFlight = 0;
150
+ /**
151
+ * The earliest unused recorded call that fits this one: one `translate`
152
+ * adapts, or one with the same method and shape. Not by position, so a call
153
+ * the port added or dropped does not shift every answer after it.
154
+ */
155
+ function nextReplayedModel(effect) {
156
+ for (const recorded of replayedModels) {
157
+ if (usedModels.has(recorded)) continue;
158
+ const translated = options.translate?.(structuredClone(recorded), effect);
159
+ if (translated) {
160
+ effect.translated = true;
161
+ return {
162
+ recorded,
163
+ answer: translated
164
+ };
165
+ }
166
+ if (recorded.method === effect.method && modelCallsMatch(options.modelCalls, recorded, effect)) return {
167
+ recorded,
168
+ answer: recorded
169
+ };
170
+ }
171
+ }
172
+ function noAnswerMessage(effect) {
173
+ const unused = replayedModels.filter((recorded) => !usedModels.has(recorded));
174
+ return unused.length ? `Model call #${effect.call} (${effect.method}, ${JSON.stringify(modelCallShape(effect))}) fits no unused recorded call: ${unused.map((recorded) => `#${recorded.call} (${recorded.method}, ${JSON.stringify(modelCallShape(recorded))})`).join(", ")}. A recorded answer only fits a call of the same method and shape; pass \`translate\` to adapt one.` : `Model call #${effect.call} was never made by the recorded run (it made ${replayedModels.length}).`;
175
+ }
176
+ /**
177
+ * Records a model call around `run`, or answers it from the recording.
178
+ * `fallback` runs it on the stand-in when the recording has no answer.
179
+ */
180
+ async function modelCall(seam, method, request, streamed, run, fallback) {
181
+ const effect = {
182
+ kind: "model",
183
+ seam,
184
+ method,
185
+ call: modelCalls++,
186
+ request: toJson(omit(request, [
187
+ "abortSignal",
188
+ "headers",
189
+ "signal"
190
+ ]))
191
+ };
192
+ effects.push(effect);
193
+ if (replay) {
194
+ const replayed = nextReplayedModel(effect);
195
+ if (replayed) {
196
+ const { recorded, answer } = replayed;
197
+ usedModels.add(recorded);
198
+ effect.replayed = recorded.call;
199
+ if (answer.error) {
200
+ effect.error = answer.error;
201
+ throw fromRecordedError(answer.error);
202
+ }
203
+ effect.response = answer.response;
204
+ effect.stream = answer.stream;
205
+ if (seam === "openai") return streamed ? iterate(answer.stream ?? []) : structuredClone(answer.response);
206
+ return streamed ? {
207
+ ...reviveTimestamps(structuredClone(answer.response) ?? {}),
208
+ stream: streamFrom(answer.stream ?? [])
209
+ } : reviveTimestamps(structuredClone(answer.response));
210
+ }
211
+ if (!fallback) {
212
+ const error = new RecordingDivergenceError(noAnswerMessage(effect));
213
+ effect.error = toRecordedError(error);
214
+ throw error;
215
+ }
216
+ effect.unrecorded = true;
217
+ run = fallback;
218
+ }
219
+ let result;
220
+ try {
221
+ result = await run();
222
+ } catch (error) {
223
+ effect.error = toRecordedError(error);
224
+ throw error;
225
+ }
226
+ if (!streamed) {
227
+ effect.response = toJson(result);
228
+ return result;
229
+ }
230
+ const parts = [];
231
+ effect.stream = parts;
232
+ if (seam === "openai") {
233
+ const source = result;
234
+ return (async function* () {
235
+ for await (const chunk of source) {
236
+ parts.push(toJson(chunk));
237
+ yield chunk;
238
+ }
239
+ })();
240
+ }
241
+ const { stream, ...rest } = result;
242
+ effect.response = toJson(rest);
243
+ return {
244
+ ...rest,
245
+ stream: stream.pipeThrough(new TransformStream({ transform(part, controller) {
246
+ parts.push(toJson(part));
247
+ controller.enqueue(part);
248
+ } }))
249
+ };
250
+ }
251
+ /** `inputOf` picks the recorded input from the call's arguments. */
252
+ function tool(name, fn, inputOf = (args) => args.length === 1 ? args[0] : args) {
253
+ return ((...args) => {
254
+ const input = toJson(inputOf(args));
255
+ const effect = {
256
+ kind: "tool",
257
+ name,
258
+ step: modelCalls,
259
+ input,
260
+ ...toolsInFlight > 0 ? { concurrent: true } : {}
261
+ };
262
+ effects.push(effect);
263
+ return track(call(effect, args));
264
+ });
265
+ function call(effect, args) {
266
+ const { input } = effect;
267
+ if (replay && options.tools !== "live") {
268
+ const wanted = normalizeEffect(effect, effects).input;
269
+ const matches = (candidate) => candidate.kind === "tool" && !usedTools.has(candidate) && candidate.name === name && jsonEqual(normalizeEffect(candidate, replay).input, wanted);
270
+ const recorded = replay.find(matches);
271
+ if (!recorded && options.fallback?.tools) {
272
+ effect.unrecorded = true;
273
+ return runLive(effect, args);
274
+ }
275
+ const settle = (value) => {
276
+ if (recorded?.sync) return value();
277
+ try {
278
+ return Promise.resolve(value());
279
+ } catch (error) {
280
+ return Promise.reject(error);
281
+ }
282
+ };
283
+ return settle(() => {
284
+ if (!recorded) {
285
+ const error = new RecordingDivergenceError(`Tool '${name}' was called with ${JSON.stringify(input)}; the recorded run made no such call.`);
286
+ effect.error = toRecordedError(error);
287
+ throw error;
288
+ }
289
+ usedTools.add(recorded);
290
+ if (recorded.sync) effect.sync = true;
291
+ if (recorded.error) {
292
+ effect.error = recorded.error;
293
+ throw fromRecordedError(recorded.error);
294
+ }
295
+ effect.output = recorded.output;
296
+ return structuredClone(recorded.output);
297
+ });
298
+ }
299
+ return runLive(effect, args);
300
+ }
301
+ function runLive(effect, args) {
302
+ let output;
303
+ try {
304
+ output = fn(...args);
305
+ } catch (error) {
306
+ effect.sync = true;
307
+ effect.error = toRecordedError(error);
308
+ throw error;
309
+ }
310
+ if (!(output instanceof Promise)) {
311
+ effect.sync = true;
312
+ effect.output = toJson(output);
313
+ return output;
314
+ }
315
+ return output.then((value) => {
316
+ effect.output = toJson(value);
317
+ return value;
318
+ }, (error) => {
319
+ effect.error = toRecordedError(error);
320
+ throw error;
321
+ });
322
+ }
323
+ }
324
+ function fn(name, run, callOptions = {}) {
325
+ const { redact, serialize = toJson, revive } = callOptions;
326
+ return (async (...args) => {
327
+ const passed = [...args];
328
+ while (passed.length && passed.at(-1) === void 0) passed.pop();
329
+ const call = callCounts.get(name) ?? 0;
330
+ callCounts.set(name, call + 1);
331
+ const effect = {
332
+ kind: "call",
333
+ name,
334
+ call,
335
+ args: toJson(redact ? redact(passed) : passed)
336
+ };
337
+ effects.push(effect);
338
+ if (replay) {
339
+ const recorded = replay.find((candidate) => candidate.kind === "call" && candidate.name === name && !usedCalls.has(candidate));
340
+ if (!recorded) {
341
+ const error = new RecordingDivergenceError(`Call #${call} to '${name}' was never made by the recorded run.`);
342
+ effect.error = toRecordedError(error);
343
+ throw error;
344
+ }
345
+ usedCalls.add(recorded);
346
+ if (recorded.error) {
347
+ effect.error = recorded.error;
348
+ throw fromRecordedError(recorded.error);
349
+ }
350
+ if (recorded.stream) {
351
+ effect.stream = recorded.stream;
352
+ const chunks = structuredClone(recorded.stream);
353
+ return revive ? revive(chunks) : iterate(chunks);
354
+ }
355
+ effect.result = recorded.result;
356
+ const result = structuredClone(recorded.result);
357
+ return revive ? revive(result) : result;
358
+ }
359
+ let result;
360
+ try {
361
+ result = await run(...args);
362
+ } catch (error) {
363
+ effect.error = toRecordedError(error);
364
+ throw error;
365
+ }
366
+ if (!require_effects.isAsyncIterable(result)) {
367
+ effect.result = toJson(serialize(result));
368
+ return result;
369
+ }
370
+ const chunks = [];
371
+ effect.stream = chunks;
372
+ const source = result;
373
+ return (async function* () {
374
+ try {
375
+ for await (const chunk of source) {
376
+ chunks.push(toJson(serialize(chunk)));
377
+ yield chunk;
378
+ }
379
+ } catch (error) {
380
+ effect.error = toRecordedError(error);
381
+ throw error;
382
+ }
383
+ })();
384
+ });
385
+ }
386
+ /** Counts an async tool call as running until it settles. */
387
+ function track(result) {
388
+ if (result instanceof Promise) {
389
+ toolsInFlight++;
390
+ const settled = () => {
391
+ toolsInFlight--;
392
+ };
393
+ result.then(settled, settled);
394
+ }
395
+ return result;
396
+ }
397
+ return {
398
+ model(model) {
399
+ const base = model;
400
+ const stand = options.fallback?.model;
401
+ const wrapped = Object.create(base);
402
+ for (const method of [
403
+ "doGenerate",
404
+ "doStream",
405
+ "doDecide",
406
+ "doEvaluate"
407
+ ]) {
408
+ if (typeof base[method] !== "function") continue;
409
+ const invoke = (target, callOptions) => target[method].call(target, callOptions);
410
+ wrapped[method] = (callOptions) => modelCall("ai-sdk", method, callOptions, method === "doStream", () => invoke(base, callOptions), stand && typeof stand[method] === "function" ? () => invoke(stand, callOptions) : void 0);
411
+ }
412
+ return wrapped;
413
+ },
414
+ openai(client) {
415
+ const wrapCreate = (resource, method) => new Proxy(resource, { get(target, key, receiver) {
416
+ if (key !== "create") return Reflect.get(target, key, receiver);
417
+ return (params, requestOptions) => {
418
+ let api;
419
+ const create = (resource) => () => {
420
+ api = Reflect.get(resource, "create").call(resource, params, requestOptions);
421
+ return Promise.resolve(api);
422
+ };
423
+ const stand = fallbackResource(method);
424
+ const promise = modelCall("openai", method, params, params?.stream === true, create(target), stand && create(stand));
425
+ return Object.assign(promise, { withResponse: async () => {
426
+ const data = await promise;
427
+ const meta = await api?.withResponse?.();
428
+ return {
429
+ data,
430
+ response: meta?.response ?? new Response(null),
431
+ request_id: meta?.request_id ?? null
432
+ };
433
+ } });
434
+ };
435
+ } });
436
+ const fallbackResource = (method) => {
437
+ let value = options.fallback?.openai;
438
+ for (const key of method.split(".").slice(0, -1)) value = value?.[key];
439
+ return value && typeof value === "object" ? value : void 0;
440
+ };
441
+ const wrapped = /* @__PURE__ */ new Map();
442
+ const wrap = (key, make) => {
443
+ if (!wrapped.has(key)) wrapped.set(key, make());
444
+ return wrapped.get(key);
445
+ };
446
+ return new Proxy(client, { get(target, key, receiver) {
447
+ const value = Reflect.get(target, key, receiver);
448
+ if (key === "responses" && value) return wrap(key, () => wrapCreate(value, "responses.create"));
449
+ if (key === "chat" && value) return wrap(key, () => new Proxy(value, { get(chat, chatKey, chatReceiver) {
450
+ const inner = Reflect.get(chat, chatKey, chatReceiver);
451
+ return chatKey === "completions" && inner ? wrap("chat.completions", () => wrapCreate(inner, "chat.completions.create")) : inner;
452
+ } }));
453
+ return value;
454
+ } });
455
+ },
456
+ tool: (name, fn) => tool(name, fn),
457
+ fn,
458
+ client(name, client, { methods, ...callOptions }) {
459
+ const paths = methods.map((method) => method.split("."));
460
+ const startsWith = (path, prefix) => prefix.every((key, index) => path[index] === key);
461
+ const wrapAt = (target, prefix) => {
462
+ const wrapped = /* @__PURE__ */ new Map();
463
+ return new Proxy(target, { get(object, key, receiver) {
464
+ if (typeof key !== "string") return Reflect.get(object, key, receiver);
465
+ const path = [...prefix, key];
466
+ const method = paths.some((p) => p.length === path.length && startsWith(p, path));
467
+ if (!method && !paths.some((p) => startsWith(p, path))) return Reflect.get(object, key, receiver);
468
+ if (!wrapped.has(key)) {
469
+ const value = Reflect.get(object, key, receiver);
470
+ wrapped.set(key, method ? fn(`${name}.${path.join(".")}`, (...args) => value.apply(object, args), callOptions) : wrapAt(value && typeof value === "object" ? value : {}, path));
471
+ }
472
+ return wrapped.get(key);
473
+ } });
474
+ };
475
+ return wrapAt(client, []);
476
+ },
477
+ tools(tools) {
478
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => [name, definition.execute ? {
479
+ ...definition,
480
+ execute: tool(name, definition.execute, (args) => args[0])
481
+ } : definition]));
482
+ },
483
+ output(value) {
484
+ effects.push({
485
+ kind: "output",
486
+ value: toJson(value)
487
+ });
488
+ },
489
+ get recording() {
490
+ return {
491
+ version: 1,
492
+ effects: toJson(effects)
493
+ };
494
+ }
495
+ };
496
+ }
497
+ /** True when two model calls offer the same tool names and response format. */
498
+ function sameModelCallShape(expected, actual) {
499
+ return jsonEqual(modelCallShape(expected), modelCallShape(actual));
500
+ }
501
+ function modelCallsMatch(match, expected, actual) {
502
+ if (match === "none") return true;
503
+ if (typeof match === "function") return match(expected, actual);
504
+ return sameModelCallShape(expected, actual);
505
+ }
506
+ function shapeMessage(expected, actual) {
507
+ 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.`;
508
+ }
509
+ /**
510
+ * Offered tool names and the response format, or a decision's questions and
511
+ * their options: what a recorded answer depends on.
512
+ */
513
+ function modelCallShape(effect) {
514
+ const request = effect.request ?? {};
515
+ const questions = request["questions"];
516
+ if (questions && typeof questions === "object") return { questions: Object.entries(questions).map(([name, question]) => {
517
+ const criteria = question["criteria"];
518
+ if (question["type"] === "choice" && criteria && typeof criteria === "object") return [
519
+ name,
520
+ question["type"],
521
+ Object.keys(criteria).sort()
522
+ ];
523
+ if (question["type"] === "score" && Array.isArray(criteria)) return [
524
+ name,
525
+ question["type"],
526
+ criteria.length
527
+ ];
528
+ return [name, question["type"]];
529
+ }).sort((x, y) => String(x[0]).localeCompare(String(y[0]))) };
530
+ return {
531
+ tools: (Array.isArray(request["tools"]) ? request["tools"] : []).map((tool) => tool["name"] ?? tool["function"]?.["name"]).sort(),
532
+ format: request["responseFormat"]?.["type"] ?? request["response_format"]?.["type"] ?? (request["text"]?.["format"])?.["type"] ?? "text"
533
+ };
534
+ }
535
+ /**
536
+ * Puts each group of concurrent tool calls in a stable order, so parallel tool
537
+ * calls that finished in a different order still compare equal. A tool call
538
+ * that started after the previous one settled begins a new group, so
539
+ * sequential calls keep their order.
540
+ */
541
+ function normalize$1(effects) {
542
+ const result = [];
543
+ let batch = [];
544
+ const flush = () => {
545
+ result.push(...batch.sort((a, b) => stableStringify([a.name, a.input]).localeCompare(stableStringify([b.name, b.input]))));
546
+ batch = [];
547
+ };
548
+ for (const effect of effects) {
549
+ if (effect.kind !== "tool" || !effect.concurrent) flush();
550
+ if (effect.kind === "tool") batch.push(effect);
551
+ else result.push(effect);
552
+ }
553
+ flush();
554
+ return result;
555
+ }
556
+ function describe(effect) {
557
+ switch (effect.kind) {
558
+ case "model": return `model call #${effect.call} (${effect.method})`;
559
+ case "tool": return `tool '${effect.name}' with ${JSON.stringify(effect.input)}`;
560
+ case "call": return `call #${effect.call} to '${effect.name}' with ${JSON.stringify(effect.args)}`;
561
+ case "output": return `output ${JSON.stringify(effect.value)}`;
562
+ }
563
+ }
564
+ /** Why two effects differ, or `undefined` when they are the same. */
565
+ function differ(left, right, options) {
566
+ if (left.kind !== right.kind) return {
567
+ reason: "kind",
568
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
569
+ };
570
+ if (left.kind === "model" && right.kind === "model") {
571
+ if (right.translated && right.replayed === left.call) return void 0;
572
+ if (left.method !== right.method) return {
573
+ reason: "model-method",
574
+ message: `Model call #${left.call} used ${left.method}; the port used ${right.method}.`
575
+ };
576
+ if (!modelCallsMatch(options.modelCalls, left, right)) return {
577
+ reason: "model-call-shape",
578
+ message: shapeMessage(left, right)
579
+ };
580
+ if (!jsonEqual(errorIdentity$1(left.error), errorIdentity$1(right.error))) {
581
+ const outcome = (error) => error ? `failed with ${error.name}: ${error.message}` : "succeeded";
582
+ return {
583
+ reason: "model-error",
584
+ message: `Model call #${left.call} ${outcome(left.error)}; in the port it ${outcome(right.error)}.`
585
+ };
586
+ }
587
+ return;
588
+ }
589
+ if (left.kind === "tool" && right.kind === "tool") {
590
+ if (left.name !== right.name) return {
591
+ reason: "tool-name",
592
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
593
+ };
594
+ if (!jsonEqual(left.input, right.input)) return {
595
+ reason: "tool-input",
596
+ message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.input)}.`
597
+ };
598
+ if (!jsonEqual(left.output, right.output) || !jsonEqual(errorIdentity$1(left.error), errorIdentity$1(right.error))) return {
599
+ reason: "tool-result",
600
+ message: `Tool '${left.name}' returned a different result.`
601
+ };
602
+ return;
603
+ }
604
+ if (left.kind === "call" && right.kind === "call") {
605
+ if (left.name !== right.name) return {
606
+ reason: "call-name",
607
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
608
+ };
609
+ if (!jsonEqual(left.args, right.args)) return {
610
+ reason: "call-args",
611
+ message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.args)}.`
612
+ };
613
+ if (!jsonEqual(left.result, right.result) || !jsonEqual(left.stream, right.stream) || !jsonEqual(errorIdentity$1(left.error), errorIdentity$1(right.error))) return {
614
+ reason: "call-result",
615
+ message: `Call #${left.call} to '${left.name}' returned a different result.`
616
+ };
617
+ return;
618
+ }
619
+ if (left.kind === "output" && right.kind === "output" && !jsonEqual(left.value, right.value)) return {
620
+ reason: "output",
621
+ message: `Expected ${describe(left)}; the port returned ${JSON.stringify(right.value)}.`
622
+ };
623
+ }
624
+ /**
625
+ * Compares two recordings and reports every effect that differs. `expected`
626
+ * is the original's recording, `actual` the port's. Effects that are the same
627
+ * on both sides are lined up first (longest common subsequence), so one extra
628
+ * call does not shift every effect after it; between them, effects of the same
629
+ * kind pair up and report what changed, and the rest are missing or extra.
630
+ */
631
+ function compareRecordings(expected, actual, options = {}) {
632
+ const select = (effects) => normalize$1(effects.flatMap((effect, index) => {
633
+ if (options.kinds && !options.kinds.includes(effect.kind)) return [];
634
+ const mapped = options.normalize ? options.normalize(effect, index, effects) : effect;
635
+ return mapped ? [mapped] : [];
636
+ }));
637
+ const a = select(expected.effects);
638
+ const b = select(actual.effects);
639
+ const same = a.map((left) => b.map((right) => !differ(left, right, options)));
640
+ const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }, () => 0));
641
+ 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]);
642
+ const divergences = [];
643
+ let lefts = [];
644
+ let rights = [];
645
+ const flushGap = (at) => {
646
+ const unpairedRights = [...rights];
647
+ const changed = [];
648
+ for (const index of lefts) {
649
+ const left = a[index];
650
+ const k = unpairedRights.findIndex((j) => b[j].kind === left.kind);
651
+ if (k === -1) {
652
+ changed.push({
653
+ index,
654
+ reason: left.kind === "output" ? "output" : "missing-effect",
655
+ expected: left,
656
+ message: left.kind === "output" ? `The port never returned; the original returned ${JSON.stringify(left.value)}.` : `The port never made ${describe(left)}.`
657
+ });
658
+ continue;
659
+ }
660
+ const right = b[unpairedRights.splice(k, 1)[0]];
661
+ const difference = differ(left, right, options);
662
+ if (difference) changed.push({
663
+ index,
664
+ expected: left,
665
+ actual: right,
666
+ ...difference
667
+ });
668
+ }
669
+ for (const j of unpairedRights) {
670
+ const extra = b[j];
671
+ divergences.push({
672
+ index: lefts[0] ?? at,
673
+ reason: extra.kind === "output" ? "output" : "extra-effect",
674
+ actual: extra,
675
+ message: extra.kind === "output" ? `The original never returned; the port returned ${JSON.stringify(extra.value)}.` : `The port made ${describe(extra)}, which the original never made.`
676
+ });
677
+ }
678
+ divergences.push(...changed);
679
+ lefts = [];
680
+ rights = [];
681
+ };
682
+ let i = 0;
683
+ let j = 0;
684
+ while (i < a.length || j < b.length) if (i < a.length && j < b.length && same[i][j]) {
685
+ flushGap(i);
686
+ i++;
687
+ j++;
688
+ } else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) rights.push(j++);
689
+ else lefts.push(i++);
690
+ flushGap(i);
691
+ divergences.sort((x, y) => x.index - y.index);
692
+ return divergences.length ? {
693
+ equivalent: false,
694
+ divergence: divergences[0],
695
+ divergences
696
+ } : {
697
+ equivalent: true,
698
+ divergences
699
+ };
700
+ }
701
+ //#endregion
702
+ //#region src/crash-recovery.ts
703
+ var CrashError = class extends Error {
704
+ constructor() {
705
+ super("checkCrashRecovery: simulated crash");
706
+ this.name = "CrashError";
707
+ }
708
+ };
709
+ const DONE_ACTOR = "xstate.done.actor";
710
+ const ERROR_ACTOR = "xstate.error.actor";
711
+ /**
712
+ * Runs `machine` once uninterrupted, then once per crash point: killed after
713
+ * each log append and while each effect is in flight, then resumed from the
714
+ * store's log by a fresh runtime. Each resumed run is checked against the
715
+ * uninterrupted one:
220
716
  *
221
- * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
222
- * ```
717
+ * - An effect whose completion was durable before the crash never runs again.
718
+ * Only an effect in flight at the crash may (execution is at-least-once).
719
+ * - Every effect of the uninterrupted run runs, and no other: a re-executed
720
+ * model call keeps its `callKey` and its request.
721
+ * - The run ends with the same status, output, state value, and context.
722
+ * - The resumed log replays to that state.
223
723
  *
224
- * @example A candidate prompt at the seam, scored against the same rows.
225
- * ```ts
226
- * const { generateText } = createAiSdkExecutors({ models });
227
- * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
228
- * ```
724
+ * Model calls the uninterrupted run made are answered from its recording.
725
+ * Plain actors run live, so they must give the same result however many times
726
+ * they run (pass `reset` for fakes that keep state).
229
727
  */
230
- async function runSeam(machine, options) {
231
- const { seam, candidate } = options;
232
- const queues = new Map(Object.entries(options.scripts ?? {}).map(([key, answers]) => [key, [...answers]]));
233
- const statePath = [];
234
- let calls = 0;
235
- let seamMatches = 0;
236
- let seamOutput;
237
- let seamUsage;
238
- const callLog = [];
239
- let seamReached = false;
240
- let callsBeforeSeam = -1;
241
- let seamStateAt = 0;
242
- let seamEventAt = 0;
243
- let liveEvents = 0;
244
- const queueKeyOf = (request) => request.name !== void 0 && queues.has(request.name) ? request.name : request.model;
245
- /**
246
- * Consumes this request's slot in the call plan, or resolves `undefined` when
247
- * its queue is dry. With `repeatLast`, the last entry is replayed instead of
248
- * running dry.
249
- */
250
- const takeScriptedSlot = async (request, info) => {
251
- const queue = queues.get(queueKeyOf(request));
252
- if (!queue?.length) return;
253
- return resolveSeamScriptEntry(options.repeatLast && queue.length === 1 ? queue[0] : queue.shift(), request, info);
728
+ async function checkCrashRecovery(machine, options = {}) {
729
+ const timeout = options.timeout ?? 5e3;
730
+ options.reset?.();
731
+ const baselineWorld = newWorld(() => false);
732
+ const baselineStore = observedStore((options.store ?? require_event_log_store.createInMemoryEventLogStore)(), baselineWorld, () => false);
733
+ const baseline = await withTimeout(runTurns(machine, options, baselineWorld, baselineStore.store), timeout);
734
+ if (baseline === TIMED_OUT) throw new Error(`checkCrashRecovery: the uninterrupted run did not settle within ${timeout}ms`);
735
+ if (baselineWorld.unsent.length > 0) {
736
+ const keys = baselineWorld.unsent.map((index) => {
737
+ const { during, occurrence = 0 } = options.sendDuring[index];
738
+ return occurrence === 0 ? `'${during}'` : `'${during}' (start ${occurrence})`;
739
+ });
740
+ throw new Error(`checkCrashRecovery: sendDuring names effects the uninterrupted run never started: ${keys.join(", ")}`);
741
+ }
742
+ if (baselineWorld.undelivered > 0) throw new Error(`checkCrashRecovery: the uninterrupted run settled '${baseline.status}' with ${baselineWorld.undelivered} of \`events\` undelivered`);
743
+ const baselineEntries = await baselineStore.store.read(THREAD);
744
+ const baselineCounts = countBy(baselineWorld.effects);
745
+ const expected = outcomeOf(baseline);
746
+ const points = [];
747
+ for (const entries of /* @__PURE__ */ new Set([0, ...baselineStore.appends])) points.push({
748
+ kind: "log",
749
+ entries
750
+ });
751
+ const seen = /* @__PURE__ */ new Map();
752
+ baselineWorld.effects.forEach((effect, index) => {
753
+ const occurrence = seen.get(effect.key) ?? 0;
754
+ seen.set(effect.key, occurrence + 1);
755
+ points.push({
756
+ kind: "effect",
757
+ effect: {
758
+ kind: effect.kind,
759
+ key: effect.key
760
+ },
761
+ index,
762
+ occurrence
763
+ });
764
+ });
765
+ const failures = [];
766
+ const unreached = [];
767
+ const ctx = {
768
+ machine,
769
+ options,
770
+ timeout,
771
+ baselineCounts,
772
+ recorded: baselineWorld.answers,
773
+ expected,
774
+ sentAt: new Map([...baselineWorld.sentEntries].map(([index, entry]) => [index, entry.index]))
254
775
  };
255
- const scriptedAnswer = async (request, info) => {
256
- const scripted = await takeScriptedSlot(request, info);
257
- if (!scripted) throw new require_event_log.AgentError("seam-script-exhausted", `runSeam: no scripted answer left for request ${describeText(request)}. Add an entry to \`scripts.${queueKeyOf(request)}\`, or pass \`repeatLast: true\` to replay its last entry down a longer branch.`);
258
- return scripted;
776
+ for (const point of points) {
777
+ let found = await crashAt(point, ctx);
778
+ for (let retry = 1; !Array.isArray(found) && retry < UNREACHED_RETRIES; retry++) found = await crashAt(point, ctx);
779
+ if (Array.isArray(found)) failures.push(...found);
780
+ else unreached.push({
781
+ point,
782
+ reason: found.unreached
783
+ });
784
+ }
785
+ return {
786
+ ok: failures.length === 0 && unreached.length === 0,
787
+ baseline: {
788
+ status: baseline.status,
789
+ ...baseline.status === "done" ? { output: baseline.output } : {},
790
+ entries: baselineEntries.length,
791
+ effects: baselineWorld.effects.map(({ kind, key }) => ({
792
+ kind,
793
+ key
794
+ }))
795
+ },
796
+ points,
797
+ unreached,
798
+ failures
259
799
  };
260
- const route = async (request, info) => {
261
- const callIndex = calls++;
262
- const isSeam = request.name === seam.request && seamMatches++ === (seam.occurrence ?? 0);
263
- const ledger = (source) => {
264
- callLog.push({
265
- ...request.name !== void 0 ? { name: request.name } : {},
266
- model: request.model,
267
- key: queueKeyOf(request),
268
- source,
269
- seam: isSeam
270
- });
271
- };
272
- if (isSeam && candidate) {
273
- await takeScriptedSlot(request, info);
274
- seamReached = true;
275
- callsBeforeSeam = callIndex;
276
- seamStateAt = statePath.length;
277
- seamEventAt = liveEvents;
278
- const result = await candidate(request, info);
279
- seamOutput = await seamOutputOf(result, request);
280
- seamUsage = require_event_log.getCallUsage(result);
281
- ledger("candidate");
282
- return result;
283
- }
284
- const scripted = await scriptedAnswer(request, info);
285
- ledger("script");
286
- if (!isSeam) return scripted;
287
- seamReached = true;
288
- callsBeforeSeam = callIndex;
289
- seamStateAt = statePath.length;
290
- seamEventAt = liveEvents;
291
- seamOutput = scripted.result;
292
- seamUsage = scripted.usage;
293
- return scripted;
800
+ }
801
+ const THREAD = "crash-recovery";
802
+ const UNREACHED_RETRIES = 3;
803
+ const SKIPPED_TURN = "(no timer pending)";
804
+ const TIMED_OUT = Symbol("timed out");
805
+ async function crashAt(point, ctx) {
806
+ const { machine, options, timeout } = ctx;
807
+ const fail = (problem, message, key) => ({
808
+ point,
809
+ problem,
810
+ message,
811
+ ...key !== void 0 ? { key } : {}
812
+ });
813
+ options.reset?.();
814
+ let backing;
815
+ try {
816
+ backing = (options.store ?? require_event_log_store.createInMemoryEventLogStore)();
817
+ } catch (error) {
818
+ return [fail("threw", `the store factory threw: ${String(error)}`)];
819
+ }
820
+ const controller = new AbortController();
821
+ let runs = 0;
822
+ const crashed = newWorld((effect) => point.kind === "effect" && effect.key === point.effect.key && runs++ === point.occurrence, ctx.recorded);
823
+ const crash = () => {
824
+ if (crashed.crashed) return;
825
+ crashed.crashed = true;
826
+ controller.abort(new CrashError());
294
827
  };
295
- const executors = {
296
- ...options.executors,
297
- generateText: route,
298
- streamText: async (request, info) => {
299
- const result = await route(request, info);
300
- emitScriptedChunk(result, info);
301
- return result;
828
+ let missed = point.kind === "log" && point.entries === 0 ? void 0 : point.kind === "log" ? "the log never reached that length" : "the run never started that effect";
829
+ const onEffect = crashed.onEffect;
830
+ crashed.onEffect = (effect) => {
831
+ const dies = onEffect(effect);
832
+ if (dies) {
833
+ missed = void 0;
834
+ queueMicrotask(crash);
302
835
  }
836
+ return dies;
303
837
  };
304
- let snapshot;
305
- let event;
306
- const events = [];
838
+ const dying = observedStore(backing, crashed, (accepted) => {
839
+ if (point.kind !== "log" || accepted < point.entries) return false;
840
+ missed = accepted === point.entries ? void 0 : `one write took the log to ${accepted} entries`;
841
+ crash();
842
+ return true;
843
+ });
844
+ if (point.kind === "log" && point.entries === 0) dying.freeze();
845
+ let died;
846
+ try {
847
+ died = await withTimeout(runTurns(machine, options, crashed, dying.store, void 0, controller.signal), timeout);
848
+ } catch (error) {
849
+ if (!(error instanceof CrashError)) {
850
+ crash();
851
+ return [fail("threw", `the crashed run threw: ${String(error)}`)];
852
+ }
853
+ }
854
+ crash();
855
+ if (died === TIMED_OUT) return [fail("stuck", `the run did not stop within ${timeout}ms after the crash`)];
856
+ if (missed !== void 0) return { unreached: missed };
857
+ const resumed = newWorld(() => false, ctx.recorded);
858
+ const resumeController = new AbortController();
307
859
  let result;
308
- const maxTurns = options.maxTurns ?? 12;
309
- for (let turn = 0; turn <= maxTurns; turn++) {
310
- result = await require_run_agent.runToQuiescence(require_run_agent.createAgentRuntime(machine, {
311
- ...options.actors ? { actors: options.actors } : {},
312
- executors,
313
- onTransition: (next, causedBy) => {
314
- if (turn > 0 && causedBy.type === "@xstate.init") return;
315
- events.push(causedBy);
316
- liveEvents = events.length;
317
- statePath.push(next.value);
860
+ try {
861
+ result = await withTimeout(runTurns(machine, options, resumed, backing, {
862
+ crashed,
863
+ sentAt: ctx.sentAt
864
+ }, resumeController.signal), timeout);
865
+ } catch (error) {
866
+ resumed.crashed = true;
867
+ resumeController.abort(new CrashError());
868
+ return [fail("threw", `the resume threw: ${String(error)}`)];
869
+ }
870
+ if (result === TIMED_OUT) {
871
+ resumed.crashed = true;
872
+ resumeController.abort(new CrashError());
873
+ return [fail("stuck", `the resume did not settle within ${timeout}ms`)];
874
+ }
875
+ const failures = [];
876
+ for (const index of resumed.unsentAfterCrash) {
877
+ const { during, occurrence = 0 } = options.sendDuring[index];
878
+ failures.push(fail("undelivered", `the sendDuring event for '${during}' (start ${occurrence}) was lost in the crash and never sent again`));
879
+ }
880
+ const total = countBy([...crashed.effects, ...resumed.effects]);
881
+ const inFlight = countBy(crashed.effects.filter((effect) => !effect.completed));
882
+ for (const [key, count] of total) {
883
+ const expected = ctx.baselineCounts.get(key) ?? 0;
884
+ const allowed = expected + (inFlight.get(key) ?? 0);
885
+ if (expected === 0) failures.push(fail("unexpected", `'${key}' ran ${count}x; the uninterrupted run never made it`, key));
886
+ else if (count > allowed) failures.push(fail("reran", `'${key}' ran ${count}x, at most ${allowed} expected: its completion was durable before the crash`, key));
887
+ }
888
+ for (const [key, expected] of ctx.baselineCounts) {
889
+ const count = total.get(key) ?? 0;
890
+ if (count < expected) failures.push(fail("skipped", `'${key}' ran ${count}x, ${expected} expected`, key));
891
+ }
892
+ const crashedRequests = new Map(crashed.effects.filter((effect) => effect.kind === "model").map((effect) => [effect.key, effect.request]));
893
+ for (const effect of resumed.effects) {
894
+ if (effect.kind !== "model" || !crashedRequests.has(effect.key)) continue;
895
+ const before = crashedRequests.get(effect.key);
896
+ if (before === void 0 || effect.request === void 0) continue;
897
+ if (before !== effect.request) failures.push(fail("request-changed", `'${effect.key}' re-executed with a different request`, effect.key));
898
+ }
899
+ const actual = outcomeOf(result);
900
+ if (actual !== ctx.expected) failures.push(fail("outcome", `resumed run ended ${actual}, expected ${ctx.expected}`));
901
+ const log = await backing.read(THREAD);
902
+ try {
903
+ const replayed = require_event_log.replay(options.actors !== void 0 ? machine.provide({ actors: options.actors }) : machine, log);
904
+ const fromLog = stableStringify(require_effects.toJsonValue({
905
+ value: replayed.snapshot.value,
906
+ context: replayed.snapshot.context
907
+ }));
908
+ const live = stableStringify(require_effects.toJsonValue({
909
+ value: result.snapshot.value,
910
+ context: result.snapshot.context
911
+ }));
912
+ if (fromLog !== live) failures.push(fail("replay", `the log replays to ${fromLog}, the resumed run ended at ${live}`));
913
+ } catch (error) {
914
+ failures.push(fail("replay", `the log does not replay: ${String(error)}`));
915
+ }
916
+ return failures;
917
+ }
918
+ /**
919
+ * Runs the turns: start from `input`, then one host event per idle settle,
920
+ * with `sendDuring` events sent as their effects start and host timers fired
921
+ * when the run is idle. Resuming, what the crashed run's log holds is skipped.
922
+ */
923
+ async function runTurns(machine, options, world, store, resuming, signal) {
924
+ const tracked = trackActors(machine, world);
925
+ const executors = trackExecutors(options.executors ?? {}, world);
926
+ const actors = options.actors !== void 0 ? Object.fromEntries(Object.entries(options.actors).map(([key, logic]) => [key, require_effects.isStateMachineLogic(logic) ? trackActors(logic, world) : trackLogic(logic, world)])) : void 0;
927
+ const before = resuming?.crashed;
928
+ const log = before !== void 0 ? await store.read(THREAD) : [];
929
+ const durable = new Set(log.map((entry) => entry.id));
930
+ const events = options.events ?? [];
931
+ let next = 0;
932
+ if (before !== void 0) while (next < before.hostEntries.length && (before.hostEntries[next] === SKIPPED_TURN || durable.has(before.hostEntries[next]))) next++;
933
+ const sends = options.sendDuring ?? [];
934
+ const unsent = /* @__PURE__ */ new Set();
935
+ const redeliver = [];
936
+ const sendAt = /* @__PURE__ */ new Map();
937
+ const waitsFor = /* @__PURE__ */ new Map();
938
+ sends.forEach(({ during, occurrence = 0 }, index) => {
939
+ if (resuming === void 0) {
940
+ waitsFor.set(index, occurrence);
941
+ unsent.add(index);
942
+ return;
943
+ }
944
+ const entry = before.sentEntries.get(index);
945
+ if (entry !== void 0 && durable.has(entry.id)) return;
946
+ const starts = before.effects.filter((effect) => effect.key === during);
947
+ if (starts[occurrence]?.completed !== true) {
948
+ waitsFor.set(index, occurrence - starts.filter((effect) => effect.completed).length);
949
+ unsent.add(index);
950
+ return;
951
+ }
952
+ const at = resuming.sentAt.get(index);
953
+ if (at === void 0) return;
954
+ if (at <= log.length) redeliver.push(index);
955
+ else sendAt.set(index, at);
956
+ });
957
+ const awaitingSends = [];
958
+ let live;
959
+ const send = (index) => {
960
+ const { event } = sends[index];
961
+ awaitingSends.push({
962
+ index,
963
+ json: require_event_log.canonicalEventJson(event)
964
+ });
965
+ live?.send(event);
966
+ };
967
+ const startsSeen = /* @__PURE__ */ new Map();
968
+ const onEffect = world.onEffect;
969
+ world.onEffect = (effect) => {
970
+ const nth = startsSeen.get(effect.key) ?? 0;
971
+ startsSeen.set(effect.key, nth + 1);
972
+ for (const index of unsent) {
973
+ if (sends[index].during !== effect.key || waitsFor.get(index) !== nth) continue;
974
+ unsent.delete(index);
975
+ send(index);
976
+ }
977
+ return onEffect(effect);
978
+ };
979
+ const pendingTimers = /* @__PURE__ */ new Map();
980
+ world.clock = {
981
+ now: before?.clock.now ?? 0,
982
+ due: pendingTimers
983
+ };
984
+ const dueBefore = new Map(before?.clock.due ?? []);
985
+ const timers = options.timers === "host" ? {
986
+ schedule: ({ id, delay }) => {
987
+ if (!pendingTimers.has(id)) {
988
+ const restored = dueBefore.get(id);
989
+ dueBefore.delete(id);
990
+ pendingTimers.set(id, restored ?? world.clock.now + delay);
318
991
  }
319
- }), {
320
- ...snapshot ? { snapshot } : { input: options.input },
321
- ...event ? { event } : {}
992
+ },
993
+ cancel: (id) => {
994
+ pendingTimers.delete(id);
995
+ }
996
+ } : void 0;
997
+ /** `track`: the turn delivers one of `events` (a host event, or a timer's turn), whose entry is recorded. */
998
+ const turn = (event, track) => {
999
+ let awaiting = event !== void 0 && track === "host" ? require_event_log.canonicalEventJson(event) : void 0;
1000
+ let awaitingTimer = track === "timer";
1001
+ live = require_effects.createAgentRuntime(tracked, {
1002
+ ...options.runtime,
1003
+ onEvent: (entry) => {
1004
+ options.runtime?.onEvent?.(entry);
1005
+ for (const [index, at] of sendAt) {
1006
+ if (entry.index + 1 < at) continue;
1007
+ sendAt.delete(index);
1008
+ send(index);
1009
+ }
1010
+ if (entry.actorPath !== void 0) return;
1011
+ const json = require_event_log.canonicalEventJson(entry.event);
1012
+ if (awaiting !== void 0 && json === awaiting) {
1013
+ world.hostEntries.push(entry.id);
1014
+ awaiting = void 0;
1015
+ return;
1016
+ }
1017
+ if (awaitingTimer && entry.event.type === "xstate.timer") {
1018
+ world.hostEntries.push(entry.id);
1019
+ awaitingTimer = false;
1020
+ return;
1021
+ }
1022
+ const sent = awaitingSends.findIndex((item) => item.json === json);
1023
+ if (sent !== -1) {
1024
+ world.sentEntries.set(awaitingSends[sent].index, {
1025
+ id: entry.id,
1026
+ index: entry.index
1027
+ });
1028
+ awaitingSends.splice(sent, 1);
1029
+ }
1030
+ },
1031
+ executors,
1032
+ ...actors !== void 0 ? { actors } : {},
1033
+ store,
1034
+ threadId: THREAD,
1035
+ ...timers !== void 0 ? { timers } : {},
1036
+ ...signal !== void 0 ? { signal } : {}
322
1037
  });
323
- if (result.status !== "idle" || turn === maxTurns) break;
324
- const next = await options.respond?.({
325
- snapshot: result.snapshot,
326
- state: result.snapshot.value,
327
- meta: require_event_log.getStateMeta(result.snapshot),
328
- turn,
329
- result
1038
+ for (const index of redeliver.splice(0)) send(index);
1039
+ return require_effects.runToQuiescence(live, {
1040
+ ...options.input !== void 0 ? { input: options.input } : {},
1041
+ ...event !== void 0 ? { event } : {}
330
1042
  });
331
- if (!next) break;
332
- event = next;
333
- snapshot = result.persist();
334
- }
335
- let splitAt = events.length;
336
- if (seamReached) {
337
- splitAt = seamEventAt;
338
- for (let index = seamEventAt; index < events.length; index++) {
339
- const type = events[index].type;
340
- if (type.startsWith("xstate.done") || type.startsWith("xstate.error")) {
341
- splitAt = index;
342
- break;
1043
+ };
1044
+ const soonestTimer = () => {
1045
+ let soonest;
1046
+ for (const timer of pendingTimers) if (soonest === void 0 || timer[1] < soonest[1]) soonest = timer;
1047
+ if (soonest === void 0) return void 0;
1048
+ pendingTimers.delete(soonest[0]);
1049
+ world.clock.now = soonest[1];
1050
+ return {
1051
+ type: "xstate.timer",
1052
+ id: soonest[0]
1053
+ };
1054
+ };
1055
+ let result = await turn();
1056
+ while (result.status === "idle" && !world.crashed) {
1057
+ let event;
1058
+ let host = true;
1059
+ let marked = false;
1060
+ if (next < events.length) {
1061
+ event = events[next++];
1062
+ if (event.type === "xstate.timer" && !("id" in event)) {
1063
+ event = soonestTimer();
1064
+ host = false;
1065
+ marked = true;
1066
+ if (event === void 0) {
1067
+ world.hostEntries.push(SKIPPED_TURN);
1068
+ continue;
1069
+ }
343
1070
  }
1071
+ } else {
1072
+ event = soonestTimer();
1073
+ host = false;
344
1074
  }
1075
+ if (event === void 0) break;
1076
+ result = await turn(event, host ? "host" : marked ? "timer" : void 0);
1077
+ await result.drain?.();
345
1078
  }
346
- const splitStateAt = seamReached ? seamStateAt : statePath.length;
1079
+ await result.drain?.();
1080
+ world.unsent = [...unsent];
1081
+ world.unsentAfterCrash = resuming !== void 0 ? [...unsent, ...sendAt.keys()] : [];
1082
+ world.undelivered = events.length - next;
1083
+ return result;
1084
+ }
1085
+ function newWorld(crashesAt, recorded) {
347
1086
  return {
348
- result,
349
- seamOutput,
350
- ...seamUsage !== void 0 ? { seamUsage } : {},
351
- callsBeforeSeam,
352
- calls: callLog,
353
- before: {
354
- statePath: statePath.slice(0, splitStateAt),
355
- events: events.slice(0, splitAt)
1087
+ effects: [],
1088
+ hostEntries: [],
1089
+ sentEntries: /* @__PURE__ */ new Map(),
1090
+ unsent: [],
1091
+ unsentAfterCrash: [],
1092
+ undelivered: 0,
1093
+ clock: {
1094
+ now: 0,
1095
+ due: /* @__PURE__ */ new Map()
356
1096
  },
357
- after: {
358
- statePath: statePath.slice(splitStateAt),
359
- events: events.slice(splitAt)
360
- }
1097
+ answers: /* @__PURE__ */ new Map(),
1098
+ ...recorded !== void 0 ? { recorded } : {},
1099
+ crashed: false,
1100
+ onEffect: (effect) => crashesAt(effect)
361
1101
  };
362
1102
  }
363
- //#endregion
364
- //#region src/internal/trace-states.ts
365
- /** The `value` of a trace event's `from` or `snapshot`. @internal */
366
- function valueOf(holder) {
367
- return require_event_log.isRecord(holder) ? holder.value : void 0;
368
- }
369
- /** A decision request on its first attempt (no failed attempts yet). @internal */
370
- function isFirstDecision(request) {
371
- return require_event_log.isRecord(request) && request.kind === "decision" && (!Array.isArray(request.attempts) || request.attempts.length === 0);
372
- }
373
1103
  /**
374
- * Every active leaf of a state value as a dot path:
375
- * `'a'` → `['a']`; `{ a: 'b' }` → `['a.b']`; `{ p: { x: 'one', y: {} } }` → `['p.x.one', 'p.y']`.
376
- * @internal
1104
+ * `store`, recording each append's resulting length and marking the effects
1105
+ * whose completion an accepted entry carries. `afterAppend` returns true to
1106
+ * freeze it: every later append rejects, as if the process died.
377
1107
  */
378
- function statePaths(value, prefix = "") {
379
- if (typeof value === "string") return [prefix + value];
380
- if (!require_event_log.isRecord(value)) return [];
381
- const entries = Object.entries(value);
382
- if (entries.length === 0) return prefix ? [prefix.slice(0, -1)] : [];
383
- return entries.flatMap(([key, child]) => statePaths(child, `${prefix}${key}.`));
1108
+ function observedStore(store, world, afterAppend) {
1109
+ const appends = [];
1110
+ let frozen = false;
1111
+ return {
1112
+ store: {
1113
+ ...store,
1114
+ read: (threadId, options) => store.read(threadId, options),
1115
+ length: (threadId) => store.length(threadId),
1116
+ fork: (input) => store.fork(input),
1117
+ async append(input) {
1118
+ if (frozen || world.crashed) throw new CrashError();
1119
+ await store.append(input);
1120
+ for (const entry of input.entries) markCompleted(entry, world.effects);
1121
+ const accepted = input.expectedIndex + input.entries.length;
1122
+ appends.push(accepted);
1123
+ if (afterAppend(accepted)) frozen = true;
1124
+ }
1125
+ },
1126
+ appends,
1127
+ freeze: () => {
1128
+ frozen = true;
1129
+ }
1130
+ };
384
1131
  }
385
1132
  /**
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
1133
+ * Marks the call an accepted entry completes: a decision's chosen event names
1134
+ * its call (`site#n`); a completion completes the oldest open effect at its
1135
+ * invoke site, with the other attempts of the same model call.
390
1136
  */
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;
1137
+ function markCompleted(entry, effects) {
1138
+ if (entry.decidedBy !== void 0) {
1139
+ const call = entry.decidedBy;
1140
+ for (const effect of effects) if (effect.key === call || effect.key.startsWith(`${call}.`)) effect.completed = true;
1141
+ return;
1142
+ }
1143
+ if (entry.event.type !== DONE_ACTOR && entry.event.type !== ERROR_ACTOR) return;
1144
+ const actorId = entry.event.actorId;
1145
+ if (typeof actorId !== "string") return;
1146
+ const site = require_event_log.agentCallSite(entry.actorPath ?? [], actorId);
1147
+ const oldest = effects.find((effect) => effect.site === site && !effect.completed);
1148
+ if (oldest === void 0) return;
1149
+ const call = oldest.kind === "model" ? callOfModelKey(oldest.key) : void 0;
1150
+ for (const effect of effects) if (effect === oldest || call !== void 0 && effect.site === site && callOfModelKey(effect.key) === call) effect.completed = true;
1151
+ }
1152
+ function countBy(effects) {
1153
+ const counts = /* @__PURE__ */ new Map();
1154
+ for (const { key } of effects) counts.set(key, (counts.get(key) ?? 0) + 1);
1155
+ return counts;
1156
+ }
1157
+ function outcomeOf(result) {
1158
+ const snapshot = result.snapshot;
1159
+ return stableStringify(require_effects.toJsonValue({
1160
+ status: result.status,
1161
+ ...result.status === "done" ? { output: result.output } : {},
1162
+ ...result.status === "error" ? { cause: result.cause } : {},
1163
+ value: snapshot.value,
1164
+ context: snapshot.context
1165
+ }));
1166
+ }
1167
+ async function withTimeout(promise, ms) {
1168
+ let timer;
1169
+ try {
1170
+ return await Promise.race([promise, new Promise((resolve) => {
1171
+ timer = setTimeout(() => resolve(TIMED_OUT), ms);
1172
+ })]);
1173
+ } finally {
1174
+ clearTimeout(timer);
1175
+ }
1176
+ }
1177
+ /** `callKey` without its execution id: the same call has the same key in every run. */
1178
+ function modelKey(callKey) {
1179
+ return callKey.slice(callKey.indexOf(":") + 1);
1180
+ }
1181
+ function siteOfModelKey(key) {
1182
+ const hash = key.lastIndexOf("#");
1183
+ return hash === -1 ? key : key.slice(0, hash);
1184
+ }
1185
+ /** `site#n` of a model key: the call, without its attempt or strategy suffix. */
1186
+ function callOfModelKey(key) {
1187
+ const hash = key.lastIndexOf("#");
1188
+ if (hash === -1) return key;
1189
+ const dot = key.indexOf(".", hash);
1190
+ return dot === -1 ? key : key.slice(0, dot);
1191
+ }
1192
+ function trackExecutors(executors, world) {
1193
+ const tracked = {};
1194
+ for (const [slot, executor] of Object.entries(executors)) {
1195
+ if (typeof executor !== "function") continue;
1196
+ tracked[slot] = async (request, info) => {
1197
+ if (world.crashed) return never(info?.signal);
1198
+ const key = info?.callKey !== void 0 ? modelKey(info.callKey) : `${slot}:?`;
1199
+ const effect = {
1200
+ kind: "model",
1201
+ key,
1202
+ site: siteOfModelKey(key),
1203
+ completed: false,
1204
+ request: requestFingerprint(request)
1205
+ };
1206
+ world.effects.push(effect);
1207
+ const dies = world.onEffect(effect);
1208
+ const recorded = world.recorded?.get(key);
1209
+ let result;
1210
+ if (recorded !== void 0) {
1211
+ await new Promise((resolve) => setTimeout(resolve, recorded.ms));
1212
+ result = recorded.result;
1213
+ } else {
1214
+ const started = Date.now();
1215
+ result = await executor(request, info);
1216
+ if (info?.callKey !== void 0) world.answers.set(key, {
1217
+ result,
1218
+ ms: Date.now() - started
1219
+ });
1220
+ }
1221
+ if (dies || world.crashed) return never(info?.signal);
1222
+ return result;
1223
+ };
1224
+ }
1225
+ return tracked;
1226
+ }
1227
+ const VOLATILE_REQUEST_KEYS = /* @__PURE__ */ new Set(["runId"]);
1228
+ function requestFingerprint(request) {
1229
+ try {
1230
+ const json = require_effects.toJsonValue(request);
1231
+ if (json && typeof json === "object" && !Array.isArray(json)) for (const key of VOLATILE_REQUEST_KEYS) delete json[key];
1232
+ return stableStringify(json);
1233
+ } catch {
1234
+ return;
1235
+ }
1236
+ }
1237
+ function never(signal) {
1238
+ return new Promise((_, reject) => {
1239
+ if (signal?.aborted) reject(signal.reason);
1240
+ signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
1241
+ });
1242
+ }
1243
+ /** `machine` with every plain actor source, at any depth, tracked. */
1244
+ function trackActors(machine, world, ancestors = /* @__PURE__ */ new Set()) {
1245
+ if (ancestors.has(machine)) return machine;
1246
+ const visited = /* @__PURE__ */ new Set([...ancestors, machine]);
1247
+ const sources = machine.sources?.actors ?? {};
1248
+ const wrapped = {};
1249
+ for (const [key, logic] of Object.entries(sources)) {
1250
+ if (require_event_log.isTextLogic(logic) || require_decision.isDecisionLogic(logic) || require_act.isActLogic(logic)) continue;
1251
+ if (require_effects.isStateMachineLogic(logic)) {
1252
+ const inner = trackActors(logic, world, visited);
1253
+ if (inner !== logic) wrapped[key] = inner;
398
1254
  continue;
399
1255
  }
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;
1256
+ if (typeof logic?.transition === "function") wrapped[key] = trackLogic(logic, world);
416
1257
  }
417
- return steps;
1258
+ return Object.keys(wrapped).length > 0 ? machine.provide({ actors: wrapped }) : machine;
1259
+ }
1260
+ /** The invoke site of an actor: its path's last id, under its parents' path. */
1261
+ function actorSite(self) {
1262
+ const path = [];
1263
+ for (let at = self; at?._parent !== void 0; at = at._parent) path.unshift(String(at.id));
1264
+ return require_event_log.agentCallSite(path.slice(0, -1), path.at(-1) ?? "");
418
1265
  }
419
- //#endregion
420
- //#region src/fold-traces.ts
421
1266
  /**
422
- * Folds many runs' traces into per-state stats: how many runs visited each
423
- * state, how many of those failed, how many options the guards withheld
424
- * at decisions made there, how many events it ignored, and how many failures
425
- * `blame` traced back to it. Pure; reads only:
426
- *
427
- * - `machine.transition`: the run visited `from.value` and `snapshot.value`;
428
- * with `ignored`, each of those states ignored one event.
429
- * - `request.start` of a decision, first attempt only: its `request.withheld`
430
- * counts toward the state the run was in, the `from.value` of the
431
- * transition its choice causes.
432
- *
433
- * A trace is one run's events, live (`AgentTraceEvent`) or serialized
434
- * (`serializeTraceEvent`). A host-driven `decideNext` traces nothing; push
435
- * `{ type: 'request.start', request: result.request }` onto the trace before
436
- * sending its event. Parallel states count once per active leaf.
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
- *
442
- * @example
443
- * ```ts no-check
444
- * const stats = foldTraces(traces, {
445
- * failed: (trace) => trace.at(-1)?.type === 'run.end' && trace.at(-1).status === 'error',
446
- * });
447
- * ```
1267
+ * `logic`, recording each effect it starts (`@xstate.effect`: an async
1268
+ * actor's run, a callback's body). After the crash, effects do not start.
448
1269
  */
449
- function foldTraces(traces, options) {
450
- const stats = /* @__PURE__ */ new Map();
451
- const statsFor = (state) => {
452
- let entry = stats.get(state);
453
- if (!entry) {
454
- entry = {
455
- state,
456
- visits: 0,
457
- failures: 0,
458
- withheld: 0,
459
- ignored: 0,
460
- blamed: 0
1270
+ function trackLogic(logic, world) {
1271
+ if (require_event_log.isTextLogic(logic) || require_decision.isDecisionLogic(logic) || require_act.isActLogic(logic)) return logic;
1272
+ const track = (result, self) => {
1273
+ const [snapshot, effects] = result;
1274
+ if (!Array.isArray(effects) || !effects.some((e) => e?.type === "@xstate.effect")) return result;
1275
+ return [snapshot, effects.map((effect) => {
1276
+ if (effect?.type !== "@xstate.effect") return effect;
1277
+ const exec = effect.exec;
1278
+ const tracked = (...args) => {
1279
+ if (world.crashed) return;
1280
+ const site = actorSite(self);
1281
+ const started = {
1282
+ kind: "actor",
1283
+ key: `actor:${site}`,
1284
+ site,
1285
+ completed: false
1286
+ };
1287
+ world.effects.push(started);
1288
+ world.onEffect(started);
1289
+ return exec(...args);
461
1290
  };
462
- stats.set(state, entry);
463
- }
464
- return entry;
1291
+ return {
1292
+ ...effect,
1293
+ exec: tracked,
1294
+ action: tracked
1295
+ };
1296
+ })];
465
1297
  };
466
- for (const trace of traces) {
467
- const visited = /* @__PURE__ */ new Set();
468
- let current = [];
469
- const visit = (state) => {
470
- statsFor(state);
471
- visited.add(state);
1298
+ const overrides = { transition: { value: (...args) => track(logic.transition(...args), args[2].self) } };
1299
+ if (typeof logic.initialTransition === "function") overrides["initialTransition"] = { value: (...args) => track(logic.initialTransition(...args), args[1].self) };
1300
+ if (typeof logic.start === "function") overrides["start"] = { value: (snapshot, scope, startOptions) => logic.start(snapshot, new Proxy(scope, { get(target, property) {
1301
+ if (property === "actionExecutor") return (effect) => {
1302
+ const [, [tracked]] = track([void 0, [effect]], target.self);
1303
+ target.actionExecutor(tracked);
472
1304
  };
473
- for (const event of trace) if (event.type === "machine.transition") {
474
- for (const state of statePaths(valueOf(event.from))) visit(state);
475
- current = statePaths(valueOf(event.snapshot));
476
- for (const state of current) visit(state);
477
- if (event.ignored === true) for (const state of current) statsFor(state).ignored++;
478
- } else if (event.type === "request.start" && isFirstDecision(event.request)) {
479
- const withheld = event.request.withheld;
480
- if (!Array.isArray(withheld)) continue;
481
- for (const state of current) statsFor(state).withheld += withheld.length;
482
- }
483
- const failed = options.failed(trace);
484
- for (const state of visited) {
485
- const entry = statsFor(state);
486
- entry.visits++;
487
- if (failed) entry.failures++;
488
- }
489
- const blamed = failed ? options.blame?.(trace) : void 0;
490
- if (blamed !== void 0) statsFor(blamed).blamed++;
491
- }
492
- return [...stats.values()];
1305
+ return Reflect.get(target, property, target);
1306
+ } }), startOptions) };
1307
+ return Object.create(logic, overrides);
493
1308
  }
494
1309
  //#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;
1310
+ //#region src/trajectory.ts
1311
+ /**
1312
+ * Classifies one item. Event-shaped things (log entries, events) become events;
1313
+ * everything else is a state value. A snapshot is unwrapped to its `value`.
1314
+ * @internal
1315
+ */
1316
+ function normalize(item) {
1317
+ if (require_event_log.isRecord(item)) {
1318
+ const nested = item["event"];
1319
+ if (require_event_log.isRecord(nested) && typeof nested["type"] === "string") return {
1320
+ kind: "event",
1321
+ event: nested
1322
+ };
1323
+ if (typeof item["type"] === "string") return {
1324
+ kind: "event",
1325
+ event: item
1326
+ };
1327
+ if ("value" in item) return {
1328
+ kind: "state",
1329
+ value: item["value"]
1330
+ };
505
1331
  }
506
- return true;
1332
+ return {
1333
+ kind: "state",
1334
+ value: item
1335
+ };
507
1336
  }
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));
1337
+ /** Every leaf of a state value as a dot path (`{ review: 'editing' }` → `review.editing`). @internal */
1338
+ function statePaths$1(value) {
1339
+ if (typeof value === "string") return [value];
1340
+ if (!require_event_log.isRecord(value)) return [];
1341
+ return Object.entries(value).flatMap(([key, child]) => statePaths$1(child).map((path) => `${key}.${path}`));
513
1342
  }
514
1343
  /**
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).
1344
+ * A string expectation matches a state value when it names one of its leaves or
1345
+ * an ancestor of one, so `'review'` matches `{ review: 'editing' }`. @internal
518
1346
  */
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)));
1347
+ function stateMatchesPath(path, value) {
1348
+ return statePaths$1(value).some((leaf) => leaf === path || leaf.startsWith(`${path}.`));
1349
+ }
1350
+ function deepEqual(a, b) {
1351
+ if (Object.is(a, b)) return true;
1352
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => deepEqual(item, b[index]));
1353
+ if (!require_event_log.isRecord(a) || !require_event_log.isRecord(b)) return false;
1354
+ const keys = Object.keys(a);
1355
+ return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
523
1356
  }
524
- const pathOf = (node) => node.path.join(".");
525
- const sameLeaves = (a, b) => statePaths(a).sort().join("|") === statePaths(b).sort().join("|");
526
1357
  /**
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.
1358
+ * Normalizes ONE expected item into a predicate over actual items, so the
1359
+ * expectation is classified once instead of once per candidate:
1360
+ *
1361
+ * - A string expectation matches an event's `type`, or a state value it names.
1362
+ * - An event expectation matches an event with the same `type` whose other
1363
+ * declared keys deep-equal, so payload details are opt-in.
1364
+ * - A state-value expectation matches structurally.
1365
+ * @internal
535
1366
  */
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;
1367
+ function matcherFor(expected) {
1368
+ if (typeof expected === "string") return (actual) => {
1369
+ const actualItem = normalize(actual);
1370
+ return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
1371
+ };
1372
+ const expectedItem = normalize(expected);
1373
+ switch (expectedItem.kind) {
1374
+ case "event": return (actual) => {
1375
+ const actualItem = normalize(actual);
1376
+ return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
1377
+ };
1378
+ case "state": return (actual) => {
1379
+ const actualItem = normalize(actual);
1380
+ return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
1381
+ };
553
1382
  }
554
- return leaves;
555
1383
  }
556
- const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
557
1384
  /**
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`).
1385
+ * Matches a run's trajectory against an expected one.
564
1386
  *
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.
1387
+ * Both trajectories may be state values or events collected from
1388
+ * `onTransition`;
1389
+ * items are compared by shape, so `['prompting', 'drafting']` scores a state
1390
+ * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
1391
+ * call.
575
1392
  *
576
- * @example
577
- * ```ts no-check
578
- * const report = traceCoverage(machine, traces, { reachable: await explorePaths(machine) });
579
- * expect(report.unvisitedHandlers).toEqual([]);
1393
+ * Semantics are an ordered subsequence: every expected item must appear in
1394
+ * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
1395
+ * equality instead.
1396
+ *
1397
+ * @example Trajectory assertions in a test
1398
+ * ```ts
1399
+ * const statePath: unknown[] = [];
1400
+ * const result = await runToQuiescence(
1401
+ * createAgentRuntime(machine, {
1402
+ * executors,
1403
+ * onTransition: (snapshot) => statePath.push(snapshot.value),
1404
+ * }),
1405
+ * { input },
1406
+ * );
1407
+ *
1408
+ * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
1409
+ * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
1410
+ * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1411
+ * ```
1412
+ *
1413
+ * @example Partial credit in an eval scorer
1414
+ * ```ts
1415
+ * const match = matchesTrajectory(output.statePath, expected.statePath);
1416
+ * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
580
1417
  * ```
581
1418
  */
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));
1419
+ function matchesTrajectory(actual, expected, options = {}) {
1420
+ const expectedCount = expected.length;
1421
+ if (expectedCount === 0) throw new require_event_log.AgentError("empty-trajectory", "matchesTrajectory: expected trajectory must contain at least one item.");
1422
+ const exact = options.exact === true;
1423
+ let cursor = 0;
1424
+ let matchedCount = 0;
1425
+ let firstMiss;
1426
+ for (let index = 0; index < expectedCount; index++) {
1427
+ const want = expected[index];
1428
+ const matches = matcherFor(want);
1429
+ const searchedFrom = exact ? index : cursor;
1430
+ let found = -1;
1431
+ for (let at = searchedFrom; at < actual.length; at++) {
1432
+ if (matches(actual[at])) {
1433
+ found = at;
641
1434
  break;
642
1435
  }
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
- }
1436
+ if (exact) break;
649
1437
  }
650
- for (const state of visited) {
651
- const row = stateRuns.get(state);
652
- if (row) row.runs++;
1438
+ if (found === -1) {
1439
+ firstMiss = {
1440
+ index,
1441
+ expected: want,
1442
+ searchedFrom
1443
+ };
1444
+ break;
653
1445
  }
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);
1446
+ matchedCount++;
1447
+ cursor = found + 1;
668
1448
  }
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
- }));
1449
+ const matched = !firstMiss && (!exact || actual.length === expectedCount);
1450
+ const denominator = exact ? Math.max(expectedCount, actual.length) : expectedCount;
675
1451
  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
- }
1452
+ matched,
1453
+ matchedCount,
1454
+ expectedCount,
1455
+ score: matched ? 1 : denominator === 0 ? 1 : matchedCount / denominator,
1456
+ ...firstMiss ? { firstMiss } : {}
687
1457
  };
688
1458
  }
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"));
1459
+ //#endregion
1460
+ //#region src/seam.ts
1461
+ /** The only own keys an executor result carries. @internal */
1462
+ const TEXT_RESULT_KEYS = /* @__PURE__ */ new Set([
1463
+ "result",
1464
+ "messages",
1465
+ "usage",
1466
+ "raw"
1467
+ ]);
1468
+ /**
1469
+ * True when a scripted entry is the executor result rather than the output
1470
+ * value: it owns a `result` key and owns NOTHING outside the result's own
1471
+ * vocabulary. Bare `'result' in value` would swallow an output object's
1472
+ * siblings (`{ result: 'draft', confidence: 0.9 }` would lose `confidence`)
1473
+ * and would also match an inherited `result`. @internal
1474
+ */
1475
+ function isTextResult(value) {
1476
+ return Object.hasOwn(value, "result") && Object.keys(value).every((key) => TEXT_RESULT_KEYS.has(key));
1477
+ }
1478
+ /**
1479
+ * Resolves ONE scripted entry to an executor result: a function entry is
1480
+ * called with the request, and the value is taken as the executor result only
1481
+ * when it is one (see {@link isTextResult}). @internal
1482
+ */
1483
+ async function resolveSeamScriptEntry(entry, request, info) {
1484
+ const value = typeof entry === "function" ? await entry(request, info) : entry;
1485
+ return require_event_log.isRecord(value) && isTextResult(value) ? value : { result: value };
1486
+ }
1487
+ /** Names a pending text request in an error message. @internal */
1488
+ function describeText(request) {
1489
+ return request.name ? `'${request.name}' (model '${request.model}')` : `(model '${request.model}')`;
1490
+ }
722
1491
  /**
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.
1492
+ * Stream semantics with no model: the whole text lands as one chunk. @internal
1493
+ */
1494
+ function emitScriptedChunk(result, info) {
1495
+ const text = require_event_log.isRecord(result) ? result["result"] : void 0;
1496
+ if (typeof text === "string") info?.onChunk?.(text);
1497
+ }
1498
+ /**
1499
+ * The seam's own answer, for scoring: the executor result's `result`.
1500
+ * @internal
1501
+ */
1502
+ async function seamOutputOf(result, request) {
1503
+ if (!require_event_log.isRecord(result)) return;
1504
+ return await require_event_log.normalizeGeneratorResult(result, `seam '${request.name ?? request.model}'`);
1505
+ }
1506
+ /**
1507
+ * Runs a machine end to end with one model call under test, and slices the run
1508
+ * at that call.
735
1509
  *
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.
1510
+ * The `before`/`after` slices are the point: `after.statePath` is the branch
1511
+ * the seam chose and `after.events` is the same question against the durable
1512
+ * log, both ready for `matchesTrajectory`. The state slice splits where the
1513
+ * state path stood when the seam answered; the event slice splits at the
1514
+ * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1515
+ * entry appended after the call was made).
740
1516
  *
741
- * @example
742
- * ```ts no-check
743
- * const stats = foldTraces(traces, {
744
- * failed,
745
- * blame: (trace) => firstDivergence(trace, passingRunFor(trace))?.state,
1517
+ * @example No API key: the seam is scripted too, so the whole thing runs offline.
1518
+ * ```ts
1519
+ * const run = await runSeam(emailDrafter, {
1520
+ * scripts: { writeFollowUps: [followUps], emailDrafter: [draft] },
1521
+ * seam: { request: 'writeFollowUps' },
1522
+ * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
746
1523
  * });
1524
+ *
1525
+ * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
1526
+ * ```
1527
+ *
1528
+ * @example A candidate prompt at the seam, scored against the same rows.
1529
+ * ```ts
1530
+ * const { generateText } = createAiSdkExecutors({ models });
1531
+ * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
747
1532
  * ```
748
1533
  */
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 }
1534
+ async function runSeam(machine, options) {
1535
+ const { seam, candidate } = options;
1536
+ const queues = new Map(Object.entries(options.scripts ?? {}).map(([key, answers]) => [key, [...answers]]));
1537
+ const statePath = [];
1538
+ let calls = 0;
1539
+ let seamMatches = 0;
1540
+ let seamOutput;
1541
+ let seamUsage;
1542
+ const callLog = [];
1543
+ let seamReached = false;
1544
+ let callsBeforeSeam = -1;
1545
+ let seamStateAt = 0;
1546
+ let seamEventAt = 0;
1547
+ let liveEvents = 0;
1548
+ const queueKeyOf = (request) => request.name !== void 0 && queues.has(request.name) ? request.name : request.model;
1549
+ /**
1550
+ * Consumes this request's slot in the call plan, or resolves `undefined` when
1551
+ * its queue is dry. With `repeatLast`, the last entry is replayed instead of
1552
+ * running dry.
1553
+ */
1554
+ const takeScriptedSlot = async (request, info) => {
1555
+ const queue = queues.get(queueKeyOf(request));
1556
+ if (!queue?.length) return;
1557
+ return resolveSeamScriptEntry(options.repeatLast && queue.length === 1 ? queue[0] : queue.shift(), request, info);
761
1558
  };
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);
1559
+ const scriptedAnswer = async (request, info) => {
1560
+ const scripted = await takeScriptedSlot(request, info);
1561
+ if (!scripted) throw new require_event_log.AgentError("seam-script-exhausted", `runSeam: no scripted answer left for request ${describeText(request)}. Add an entry to \`scripts.${queueKeyOf(request)}\`, or pass \`repeatLast: true\` to replay its last entry down a longer branch.`);
1562
+ return scripted;
1563
+ };
1564
+ const route = async (request, info) => {
1565
+ const callIndex = calls++;
1566
+ const isSeam = request.name === seam.request && seamMatches++ === (seam.occurrence ?? 0);
1567
+ const ledger = (source) => {
1568
+ callLog.push({
1569
+ ...request.name !== void 0 ? { name: request.name } : {},
1570
+ model: request.model,
1571
+ key: queueKeyOf(request),
1572
+ source,
1573
+ seam: isSeam
1574
+ });
1575
+ };
1576
+ if (isSeam && candidate) {
1577
+ await takeScriptedSlot(request, info);
1578
+ seamReached = true;
1579
+ callsBeforeSeam = callIndex;
1580
+ seamStateAt = statePath.length;
1581
+ seamEventAt = liveEvents;
1582
+ const result = await candidate(request, info);
1583
+ seamOutput = await seamOutputOf(result, request);
1584
+ seamUsage = require_event_log.getCallUsage(result);
1585
+ ledger("candidate");
1586
+ return result;
1587
+ }
1588
+ const scripted = await scriptedAnswer(request, info);
1589
+ ledger("script");
1590
+ if (!isSeam) return scripted;
1591
+ seamReached = true;
1592
+ callsBeforeSeam = callIndex;
1593
+ seamStateAt = statePath.length;
1594
+ seamEventAt = liveEvents;
1595
+ seamOutput = scripted.result;
1596
+ seamUsage = scripted.usage;
1597
+ return scripted;
1598
+ };
1599
+ const executors = {
1600
+ ...options.executors,
1601
+ generateText: route,
1602
+ streamText: async (request, info) => {
1603
+ const result = await route(request, info);
1604
+ emitScriptedChunk(result, info);
1605
+ return result;
1606
+ }
1607
+ };
1608
+ let snapshot;
1609
+ let event;
1610
+ const events = [];
1611
+ let result;
1612
+ const maxTurns = options.maxTurns ?? 12;
1613
+ for (let turn = 0; turn <= maxTurns; turn++) {
1614
+ result = await require_effects.runToQuiescence(require_effects.createAgentRuntime(machine, {
1615
+ ...options.actors ? { actors: options.actors } : {},
1616
+ executors,
1617
+ onTransition: (next, causedBy) => {
1618
+ if (turn > 0 && causedBy.type === "@xstate.init") return;
1619
+ events.push(causedBy);
1620
+ liveEvents = events.length;
1621
+ statePath.push(next.value);
1622
+ }
1623
+ }), {
1624
+ ...snapshot ? { snapshot } : { input: options.input },
1625
+ ...event ? { event } : {}
1626
+ });
1627
+ if (result.status !== "idle" || turn === maxTurns) break;
1628
+ const next = await options.respond?.({
1629
+ snapshot: result.snapshot,
1630
+ state: result.snapshot.value,
1631
+ meta: require_event_log.getStateMeta(result.snapshot),
1632
+ turn,
1633
+ result
1634
+ });
1635
+ if (!next) break;
1636
+ event = next;
1637
+ snapshot = result.persist();
770
1638
  }
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);
1639
+ let splitAt = events.length;
1640
+ if (seamReached) {
1641
+ splitAt = seamEventAt;
1642
+ for (let index = seamEventAt; index < events.length; index++) {
1643
+ const type = events[index].type;
1644
+ if (type.startsWith("xstate.done") || type.startsWith("xstate.error")) {
1645
+ splitAt = index;
1646
+ break;
1647
+ }
1648
+ }
1649
+ }
1650
+ const splitStateAt = seamReached ? seamStateAt : statePath.length;
1651
+ return {
1652
+ result,
1653
+ seamOutput,
1654
+ ...seamUsage !== void 0 ? { seamUsage } : {},
1655
+ callsBeforeSeam,
1656
+ calls: callLog,
1657
+ before: {
1658
+ statePath: statePath.slice(0, splitStateAt),
1659
+ events: events.slice(0, splitAt)
1660
+ },
1661
+ after: {
1662
+ statePath: statePath.slice(splitStateAt),
1663
+ events: events.slice(splitAt)
782
1664
  }
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;
1665
+ };
792
1666
  }
793
1667
  //#endregion
794
- //#region src/decision-requests.ts
1668
+ //#region src/internal/trace-states.ts
1669
+ /** The `value` of a trace event's `from` or `snapshot`. @internal */
1670
+ function valueOf(holder) {
1671
+ return require_event_log.isRecord(holder) ? holder.value : void 0;
1672
+ }
1673
+ /** A decision request on its first attempt (no failed attempts yet). @internal */
1674
+ function isFirstDecision(request) {
1675
+ return require_event_log.isRecord(request) && request.kind === "decision" && (!Array.isArray(request.attempts) || request.attempts.length === 0);
1676
+ }
795
1677
  /**
796
- * The decisions a run asked for, read from its trace: each decision's first
797
- * `request.start`, with the states the run was in. A trace is one run's events,
798
- * live or serialized with `serializeTraceEvent`. Retries of the same decision
799
- * are left out, so each decision appears once.
800
- *
801
- * Use the requests as eval rows (run a decider on each and compare its event
802
- * with a label) or as probe inputs for a policy. A serialized request keeps its
803
- * `options`, `metadata`, `system`, and `prompt`; event schemas do not survive
804
- * serialization, so replay closed choices (`options`) rather than open ones.
805
- *
806
- * @example
807
- * ```ts no-check
808
- * const rows = traces.flatMap((trace) => getDecisionRequests(trace, { name: "chooseResolution" }));
809
- * for (const { request } of rows) console.log((await decide(request)).event);
810
- * ```
1678
+ * Every active leaf of a state value as a dot path:
1679
+ * `'a'` → `['a']`; `{ a: 'b' }` → `['a.b']`; `{ p: { x: 'one', y: {} } }` → `['p.x.one', 'p.y']`.
1680
+ * @internal
811
1681
  */
812
- function getDecisionRequests(trace, options = {}) {
813
- const requests = [];
814
- let current = [];
815
- for (const event of trace) if (event.type === "machine.transition") current = statePaths(valueOf(event.snapshot));
816
- else if (event.type === "request.start" && isFirstDecision(event.request)) {
817
- if (options.name !== void 0 && event.request.name !== options.name) continue;
818
- requests.push({
819
- states: [...current],
820
- request: event.request
1682
+ function statePaths(value, prefix = "") {
1683
+ if (typeof value === "string") return [prefix + value];
1684
+ if (!require_event_log.isRecord(value)) return [];
1685
+ const entries = Object.entries(value);
1686
+ if (entries.length === 0) return prefix ? [prefix.slice(0, -1)] : [];
1687
+ return entries.flatMap(([key, child]) => statePaths(child, `${prefix}${key}.`));
1688
+ }
1689
+ /**
1690
+ * A trace's `machine.transition` events as steps, skipping `@xstate.init`.
1691
+ * A first-attempt decision's `request.start` names the decision on the step
1692
+ * that follows it, skipping `@agent.usage` steps. Reads live and serialized traces alike.
1693
+ * @internal
1694
+ */
1695
+ function traceSteps(trace) {
1696
+ const steps = [];
1697
+ let decision;
1698
+ for (const event of trace) {
1699
+ if (event.type === "request.start" && isFirstDecision(event.request)) {
1700
+ const name = event.request.name;
1701
+ decision = typeof name === "string" ? name : void 0;
1702
+ continue;
1703
+ }
1704
+ if (event.type !== "machine.transition") continue;
1705
+ const type = require_event_log.isRecord(event.event) ? event.event.type : void 0;
1706
+ if (type === "@xstate.init") continue;
1707
+ const fromValue = valueOf(event.from);
1708
+ const toValue = valueOf(event.snapshot);
1709
+ steps.push({
1710
+ from: statePaths(fromValue),
1711
+ fromValue,
1712
+ event: typeof type === "string" ? type : "",
1713
+ payload: event.event,
1714
+ to: statePaths(toValue),
1715
+ toValue,
1716
+ ignored: event.ignored === true,
1717
+ ...decision === void 0 || type === "@agent.usage" ? {} : { decision }
821
1718
  });
1719
+ if (type !== "@agent.usage") decision = void 0;
822
1720
  }
823
- return requests;
1721
+ return steps;
824
1722
  }
825
1723
  //#endregion
826
- //#region src/repeat-runs.ts
1724
+ //#region src/fold-traces.ts
827
1725
  /**
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.
1726
+ * Folds many runs' traces into per-state stats: how many runs visited each
1727
+ * state, how many of those failed, how many options the guards withheld
1728
+ * at decisions made there, how many events it ignored, and how many failures
1729
+ * `blame` traced back to it. Pure; reads only:
833
1730
  *
834
- * A scenario that passes 3 of 5 runs and `divergedAt: 'deciding'` points at one
835
- * decision, not at a flaky agent.
1731
+ * - `machine.transition`: the run visited `from.value` and `snapshot.value`;
1732
+ * with `ignored`, each of those states ignored one event.
1733
+ * - `request.start` of a decision, first attempt only: its `request.withheld`
1734
+ * counts toward the state the run was in, the `from.value` of the
1735
+ * transition its choice causes.
836
1736
  *
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.
1737
+ * A trace is one run's events, live (`AgentTraceEvent`) or serialized
1738
+ * (`serializeTraceEvent`). A host-driven `decideNext` traces nothing; push
1739
+ * `{ type: 'request.start', request: result.request }` onto the trace before
1740
+ * sending its event. Parallel states count once per active leaf.
862
1741
  *
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.
1742
+ * `failures` counts a failed run against every state it visited, so states
1743
+ * after a bad decision rank as high as the decision. Sort by `blamed` to see
1744
+ * where failures start.
865
1745
  *
866
1746
  * @example
867
1747
  * ```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,
1748
+ * const stats = foldTraces(traces, {
1749
+ * failed: (trace) => trace.at(-1)?.type === 'run.end' && trace.at(-1).status === 'error',
880
1750
  * });
881
- * report.passHat(5);
882
1751
  * ```
883
1752
  */
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
- });
1753
+ function foldTraces(traces, options) {
1754
+ const stats = /* @__PURE__ */ new Map();
1755
+ const statsFor = (state) => {
1756
+ let entry = stats.get(state);
1757
+ if (!entry) {
1758
+ entry = {
1759
+ state,
1760
+ visits: 0,
1761
+ failures: 0,
1762
+ withheld: 0,
1763
+ ignored: 0,
1764
+ blamed: 0
1765
+ };
1766
+ stats.set(state, entry);
901
1767
  }
902
- groups.push({
903
- id: scenario.id,
904
- scenario,
905
- runs
906
- });
1768
+ return entry;
1769
+ };
1770
+ for (const trace of traces) {
1771
+ const visited = /* @__PURE__ */ new Set();
1772
+ let current = [];
1773
+ const visit = (state) => {
1774
+ statsFor(state);
1775
+ visited.add(state);
1776
+ };
1777
+ for (const event of trace) if (event.type === "machine.transition") {
1778
+ for (const state of statePaths(valueOf(event.from))) visit(state);
1779
+ current = statePaths(valueOf(event.snapshot));
1780
+ for (const state of current) visit(state);
1781
+ if (event.ignored === true) for (const state of current) statsFor(state).ignored++;
1782
+ } else if (event.type === "request.start" && isFirstDecision(event.request)) {
1783
+ const withheld = event.request.withheld;
1784
+ if (!Array.isArray(withheld)) continue;
1785
+ for (const state of current) statsFor(state).withheld += withheld.length;
1786
+ }
1787
+ const failed = options.failed(trace);
1788
+ for (const state of visited) {
1789
+ const entry = statsFor(state);
1790
+ entry.visits++;
1791
+ if (failed) entry.failures++;
1792
+ }
1793
+ const blamed = failed ? options.blame?.(trace) : void 0;
1794
+ if (blamed !== void 0) statsFor(blamed).blamed++;
907
1795
  }
908
- return summarizeRepeats(groups);
1796
+ return [...stats.values()];
909
1797
  }
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;
1798
+ //#endregion
1799
+ //#region src/trace-coverage.ts
1800
+ /** Mirrors xstate@6.0.0-alpha.69 `matchesEventDescriptor` (src/utils.ts), which the package does not export. */
1801
+ function matchesDescriptor(eventType, descriptor) {
1802
+ if (descriptor === eventType || descriptor === "*") return true;
1803
+ if (!descriptor.endsWith(".*")) return false;
1804
+ const tokens = descriptor.split(".");
1805
+ const eventTokens = eventType.split(".");
1806
+ for (let index = 0; index < tokens.length; index++) {
1807
+ if (tokens[index] === "*") return index === tokens.length - 1;
1808
+ if (tokens[index] !== eventTokens[index]) return false;
920
1809
  }
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
- };
1810
+ return true;
1811
+ }
1812
+ /** Whether a definition's `matches` pattern (e.g. an invoke's `actorId`) accepts the traced event. */
1813
+ function matchesPattern(definition, event) {
1814
+ const pattern = definition.matches;
1815
+ if (!require_event_log.isRecord(pattern) || !require_event_log.isRecord(event)) return true;
1816
+ return Object.entries(pattern).every(([key, value]) => Object.is(event[key], value));
1817
+ }
1818
+ /**
1819
+ * The descriptor XState would try first at `node` for `event`, guards aside:
1820
+ * the exact key, then partial and wildcard keys longest first, as in
1821
+ * xstate@6.0.0-alpha.69 `getCandidates` (src/stateUtils.ts).
1822
+ */
1823
+ function candidateAt(node, type, event) {
1824
+ const keys = [...node.transitions.keys()].filter((key) => key !== type && matchesDescriptor(type, key)).sort((a, b) => b.length - a.length);
1825
+ if (node.transitions.has(type)) keys.unshift(type);
1826
+ return keys.find((key) => node.transitions.get(key).some((d) => matchesPattern(d, event)));
929
1827
  }
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;
1828
+ const pathOf = (node) => node.path.join(".");
1829
+ const sameLeaves = (a, b) => statePaths(a).sort().join("|") === statePaths(b).sort().join("|");
1830
+ /**
1831
+ * The leaves a trace passed through inside its macrosteps: states an `always`
1832
+ * transition left before the step ended, which no traced snapshot holds.
1833
+ * Re-derived with XState's pure `getMicrosteps` from the snapshot before each
1834
+ * step (the previous step's, or the fresh start's microsteps from its input).
1835
+ * A step that cannot be recomputed, or whose recomputation ends elsewhere
1836
+ * than the traced snapshot, adds none. Only `value` and `context` are rebuilt,
1837
+ * so a guard that reads live children can take another route to the same
1838
+ * leaves, and that route is credited.
1839
+ */
1840
+ function passedThrough(machine, trace) {
1841
+ const leaves = /* @__PURE__ */ new Set();
1842
+ let resumed = false;
1843
+ let previous;
1844
+ for (const event of trace) {
1845
+ if (event.type === "run.start") resumed = event.snapshot !== void 0;
1846
+ if (event.type !== "machine.transition" || !require_event_log.isRecord(event.event)) continue;
1847
+ const snapshot = require_event_log.isRecord(event.snapshot) ? event.snapshot : void 0;
1848
+ try {
1849
+ 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({
1850
+ value: previous.value,
1851
+ context: previous.context
1852
+ }), event.event) : [];
1853
+ const last = microsteps.at(-1)?.[0];
1854
+ if (last && snapshot && sameLeaves(last.value, snapshot.value)) for (const [step] of microsteps) for (const leaf of statePaths(step.value)) leaves.add(leaf);
1855
+ } catch {}
1856
+ previous = snapshot;
1857
+ }
1858
+ return leaves;
935
1859
  }
936
- //#endregion
937
- //#region src/judge-agreement.ts
1860
+ const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
938
1861
  /**
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.
1862
+ * Measures how much of a machine a set of runs exercised: which atomic and
1863
+ * final states they visited, and which handlers they took. A handler is a
1864
+ * `(declaring state, event descriptor)` pair from `on`, invoke
1865
+ * `onDone`/`onError`, and `after`, with the targets it declares and the
1866
+ * leaves the runs landed in after it. Pure; reads only `machine.transition`
1867
+ * events, live (`AgentTraceEvent`) or serialized (`serializeTraceEvent`).
949
1868
  *
950
- * Throws `AgentError` with code `'empty-agreement-rows'` when `rows` is empty.
1869
+ * A step credits one handler per active leaf: the nearest node, from the leaf
1870
+ * up, whose exact, partial (`a.*`), or wildcard (`*`) descriptor matches the
1871
+ * event, preferred in XState's order. Guards are not replayed, so a step
1872
+ * whose nearest handler was rejected and fell through to an ancestor is
1873
+ * credited to the nearest one. XState keys invoke and `after` handlers by
1874
+ * bare type (`xstate.done.actor`), one per state however many invokes; a
1875
+ * definition's `matches` (an invoke's `actorId`) must accept the traced event
1876
+ * for its state to be credited. Ignored steps credit no handler. `always`
1877
+ * handlers are listed as `unobservable`, never as unvisited; a state one
1878
+ * passes through is visited, re-derived from each step's microsteps.
951
1879
  *
952
1880
  * @example
953
1881
  * ```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
1882
+ * const report = traceCoverage(machine, traces, { reachable: await explorePaths(machine) });
1883
+ * expect(report.unvisitedHandlers).toEqual([]);
960
1884
  * ```
961
1885
  */
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]);
1886
+ function traceCoverage(machine, traces, options = {}) {
1887
+ const nodes = /* @__PURE__ */ new Map();
1888
+ const states = [];
1889
+ const handlers = [];
1890
+ const handlerAt = /* @__PURE__ */ new Map();
1891
+ const unobservable = [];
1892
+ const walk = (node) => {
1893
+ const state = pathOf(node);
1894
+ nodes.set(state, node);
1895
+ if (node.type === "atomic" || node.type === "final") states.push({
1896
+ state,
1897
+ runs: 0
1898
+ });
1899
+ const byEvent = /* @__PURE__ */ new Map();
1900
+ for (const [event, definitions] of node.transitions) {
1901
+ const dynamic = definitions.some((d) => typeof d.to === "function");
1902
+ const declared = [...new Set(definitions.flatMap((d) => (d.target ?? []).map(pathOf)))];
1903
+ const handler = {
1904
+ state,
1905
+ event,
1906
+ runs: 0,
1907
+ targets: {
1908
+ declared: dynamic ? "dynamic" : declared,
1909
+ seen: [],
1910
+ unreached: []
1911
+ }
1912
+ };
1913
+ handlers.push(handler);
1914
+ byEvent.set(event, handler);
974
1915
  }
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
1916
+ handlerAt.set(node, byEvent);
1917
+ if (node.always?.length) unobservable.push({
1918
+ state,
1919
+ event: "always"
1001
1920
  });
1921
+ for (const child of Object.values(node.states)) walk(child);
1922
+ };
1923
+ walk(machine.root);
1924
+ const stateRuns = new Map(states.map((row) => [row.state, row]));
1925
+ const seen = /* @__PURE__ */ new Map();
1926
+ for (const trace of traces) {
1927
+ const steps = traceSteps(trace);
1928
+ const visited = new Set(steps[0]?.from);
1929
+ for (const event of trace) {
1930
+ if (event.type !== "machine.transition" || !require_event_log.isRecord(event.event)) continue;
1931
+ if (event.event.type !== "@xstate.init" || !require_event_log.isRecord(event.snapshot)) continue;
1932
+ for (const leaf of statePaths(event.snapshot.value)) visited.add(leaf);
1933
+ }
1934
+ if (unobservable.length > 0) for (const leaf of passedThrough(machine, trace)) visited.add(leaf);
1935
+ const credited = /* @__PURE__ */ new Set();
1936
+ for (const step of steps) {
1937
+ for (const leaf of step.to) visited.add(leaf);
1938
+ if (step.ignored) continue;
1939
+ const hits = /* @__PURE__ */ new Set();
1940
+ for (const leaf of step.from) for (let node = nodes.get(leaf); node; node = node.parent) {
1941
+ if (node.type === "final") continue;
1942
+ const event = candidateAt(node, step.event, step.payload);
1943
+ if (event === void 0) continue;
1944
+ hits.add(handlerAt.get(node).get(event));
1945
+ break;
1946
+ }
1947
+ for (const handler of hits) {
1948
+ credited.add(handler);
1949
+ let leaves = seen.get(handler);
1950
+ if (!leaves) seen.set(handler, leaves = /* @__PURE__ */ new Set());
1951
+ for (const leaf of step.to) leaves.add(leaf);
1952
+ }
1953
+ }
1954
+ for (const state of visited) {
1955
+ const row = stateRuns.get(state);
1956
+ if (row) row.runs++;
1957
+ }
1958
+ for (const handler of credited) handler.runs++;
1002
1959
  }
1003
- const summary = {
1004
- total: rows.length,
1005
- accuracy: agreed / rows.length,
1006
- perLabel,
1007
- confusion,
1008
- disagreements
1960
+ for (const handler of handlers) {
1961
+ const leaves = [...seen.get(handler) ?? []];
1962
+ handler.targets.seen = leaves;
1963
+ const { declared } = handler.targets;
1964
+ if (declared === "dynamic") continue;
1965
+ handler.targets.unreached = declared.filter((target) => !leaves.some((leaf) => leaf === target || leaf.startsWith(`${target}.`)));
1966
+ }
1967
+ const reachableComplete = options.reachable ? require_verify.isExplorationComplete(options.reachable) : void 0;
1968
+ let unreachable;
1969
+ if (options.reachable && reachableComplete) {
1970
+ const reached = new Set(options.reachable.reachedStates.flatMap((value) => statePaths(value)));
1971
+ unreachable = states.filter((row) => !reached.has(row.state) && row.runs === 0).map((row) => row.state);
1972
+ }
1973
+ const counted = unreachable ? states.filter((row) => !unreachable.includes(row.state)) : states;
1974
+ const unvisitedStates = counted.filter((row) => row.runs === 0).map((row) => row.state);
1975
+ const unvisitedHandlers = handlers.filter((handler) => handler.runs === 0).map(({ state, event }) => ({
1976
+ state,
1977
+ event
1978
+ }));
1979
+ return {
1980
+ states,
1981
+ handlers,
1982
+ unvisitedStates,
1983
+ unvisitedHandlers,
1984
+ unobservable,
1985
+ ...unreachable ? { unreachable } : {},
1986
+ ...reachableComplete === void 0 ? {} : { reachableComplete },
1987
+ ratio: {
1988
+ states: ratioOf(counted.length - unvisitedStates.length, counted.length),
1989
+ handlers: ratioOf(handlers.length - unvisitedHandlers.length, handlers.length)
1990
+ }
1009
1991
  };
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++;
1992
+ }
1993
+ //#endregion
1994
+ //#region src/first-divergence.ts
1995
+ const defaultKey = (step) => `${step.from.join(",")}|${step.event}|${step.to.join(",")}`;
1996
+ const isErrorLike = (value) => require_event_log.isError(value) || require_event_log.isRecord(value) && typeof value.name === "string" && typeof value.message === "string";
1997
+ const normalizeErrors = (value, seen = /* @__PURE__ */ new WeakSet()) => {
1998
+ if (value === null || typeof value !== "object") return value;
1999
+ if (seen.has(value)) return "[circular]";
2000
+ seen.add(value);
2001
+ try {
2002
+ if (isErrorLike(value) && (require_event_log.isError(value) || "stack" in value || "code" in value)) {
2003
+ const { name, message, code, cause } = value;
2004
+ return {
2005
+ name,
2006
+ message,
2007
+ ...typeof code === "string" ? { code } : {},
2008
+ ...cause !== void 0 ? { cause: normalizeErrors(cause, seen) } : {}
2009
+ };
2010
+ }
2011
+ if (Array.isArray(value)) return value.map((item) => normalizeErrors(item, seen));
2012
+ if (!require_event_log.isPlainObject(value)) return value;
2013
+ const copy = Object.create(null);
2014
+ for (const key of Object.keys(value)) copy[key] = normalizeErrors(value[key], seen);
2015
+ return copy;
2016
+ } finally {
2017
+ seen.delete(value);
1021
2018
  }
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
1032
- //#region src/compare-runs.ts
2019
+ };
2020
+ const payloadKey = (step) => {
2021
+ if (!require_event_log.isRecord(step.payload)) return `${defaultKey(step)}|${require_event_log.canonicalEventJson(step.payload)}`;
2022
+ const { sessionId: _sessionId, ...payload } = step.payload;
2023
+ return `${defaultKey(step)}|${require_event_log.canonicalEventJson(normalizeErrors(payload))}`;
2024
+ };
2025
+ 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"));
1033
2026
  /**
1034
- * Runs every scenario through a baseline and a candidate implementation and
1035
- * labels each difference, so a port can show where it behaves like the code it
1036
- * replaces and where it differs on purpose.
2027
+ * Finds the first step where a run departs from a reference, so a failure is
2028
+ * blamed on the state it started in rather than on every state the run went
2029
+ * through afterwards.
1037
2030
  *
1038
- * Parity is outcome-level: the terminal outcome and the effects in the world,
1039
- * not the sequence of tool calls, since a machine usually reorders steps. A
1040
- * candidate that broke no rule where the baseline broke one is intended, even
1041
- * when the outcome matches. A difference also counts as intended when only the
1042
- * candidate reached the scenario's `expected` outcome. Every other difference,
1043
- * and every candidate rule break, is a regression for a person to review.
2031
+ * - Against a reference **trace**, such as a passing run of the same
2032
+ * scenario, steps are compared in order by `key`. The first step that
2033
+ * differs, or the point where either trace ends early, is the divergence.
2034
+ * - Against an expected **trajectory** (`TrajectoryItem[]`, as for
2035
+ * {@link matchesTrajectory}), the run is laid out as its initial state, then
2036
+ * each step's event and new state. The first expected item it never reaches
2037
+ * is the divergence, blamed on the step after the last item it did reach. A
2038
+ * run that goes on past the trajectory has not diverged.
1044
2039
  *
1045
- * Runs are sequential, baseline first. A run that throws is recorded with
1046
- * outcome `'threw'` and the error message as its `detail`. Parity holds for
1047
- * these scenarios and these runs only; with a live model, run it more than once.
2040
+ * An empty reference is a trace with no steps, so any step diverges from it.
2041
+ * A trace is one run's events, live or serialized. Steps the machine ignored
2042
+ * changed nothing and are left out on both sides. Returns `undefined` when the
2043
+ * run does not diverge.
1048
2044
  *
1049
2045
  * @example
1050
2046
  * ```ts no-check
1051
- * const report = await compareRuns({
1052
- * scenarios,
1053
- * baseline: async (s) => toParityRun(await runRawLoop(s)),
1054
- * candidate: async (s) => toParityRun(await runDesk(s)),
2047
+ * const stats = foldTraces(traces, {
2048
+ * failed,
2049
+ * blame: (trace) => firstDivergence(trace, passingRunFor(trace))?.state,
1055
2050
  * });
1056
- * expect(report.ok).toBe(true);
1057
2051
  * ```
1058
2052
  */
1059
- async function compareRuns(options) {
1060
- const scenarios = [];
1061
- const counts = {
1062
- same: 0,
1063
- intended: 0,
1064
- regression: 0
1065
- };
1066
- for (const scenario of options.scenarios) {
1067
- const baseline = await settle(() => options.baseline(scenario));
1068
- const candidate = await settle(() => options.candidate(scenario));
1069
- const { label, reason } = labelRun(scenario.expected, baseline, candidate);
1070
- counts[label]++;
1071
- scenarios.push({
1072
- id: scenario.id,
1073
- scenario,
1074
- label,
1075
- reason,
1076
- baseline,
1077
- candidate
1078
- });
1079
- }
1080
- return {
1081
- scenarios,
1082
- counts,
1083
- ok: counts.regression === 0
1084
- };
1085
- }
1086
- async function settle(run) {
1087
- try {
1088
- return await run();
1089
- } catch (error) {
1090
- return {
1091
- outcome: "threw",
1092
- detail: error instanceof Error ? error.message : String(error)
1093
- };
1094
- }
2053
+ function firstDivergence(actual, reference, options = {}) {
2054
+ const steps = traceSteps(actual).filter((step) => !step.ignored);
2055
+ return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key === "payload" ? payloadKey : options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
1095
2056
  }
1096
- function labelRun(expected, baseline, candidate) {
1097
- if (candidate.violations?.length) return {
1098
- label: "regression",
1099
- reason: `candidate broke a rule: ${list(candidate.violations)}`
1100
- };
1101
- if (candidate.outcome === "threw") return {
1102
- label: "regression",
1103
- reason: `candidate threw: ${String(candidate.detail)}`
1104
- };
1105
- if (baseline.violations?.length) return {
1106
- label: "intended",
1107
- reason: `baseline broke a rule: ${list(baseline.violations)}`
1108
- };
1109
- const sameOutcome = baseline.outcome === candidate.outcome;
1110
- if (sameOutcome && structurallyEqual(baseline.effects, candidate.effects)) return {
1111
- label: "same",
1112
- reason: ""
1113
- };
1114
- if (expected !== void 0 && candidate.outcome === expected && baseline.outcome !== expected) return {
1115
- label: "intended",
1116
- reason: `only the candidate reached the expected '${expected}'`
1117
- };
2057
+ function diverged(steps, index, expected, initial = steps[0]?.fromValue) {
2058
+ const step = steps[index];
1118
2059
  return {
1119
- label: "regression",
1120
- reason: sameOutcome ? "effects differ" : `outcome differs: ${baseline.outcome} → ${candidate.outcome}`
1121
- };
1122
- }
1123
- function list(items) {
1124
- return items.map((item) => typeof item === "string" ? item : JSON.stringify(item)).join(", ");
1125
- }
1126
- function structurallyEqual(a, b) {
1127
- if (Object.is(a, b)) return true;
1128
- if (a instanceof Date || b instanceof Date) return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
1129
- if (a instanceof Map || b instanceof Map) return a instanceof Map && b instanceof Map && structurallyEqual([...a], [...b]);
1130
- if (a instanceof Set || b instanceof Set) return a instanceof Set && b instanceof Set && structurallyEqual([...a], [...b]);
1131
- if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => structurallyEqual(item, b[index]));
1132
- if (!require_event_log.isRecord(a) || !require_event_log.isRecord(b)) return false;
1133
- const keys = Object.keys(a);
1134
- return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && structurallyEqual(a[key], b[key]));
1135
- }
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)) return {
1149
- name: "Error",
1150
- message: String(error)
1151
- };
1152
- const recorded = {
1153
- name: error.name,
1154
- message: error.message
1155
- };
1156
- const code = error.code;
1157
- if (code !== void 0) recorded.code = toJson(code);
1158
- const data = Object.fromEntries(Object.entries(error).filter(([key, value]) => key !== "code" && (typeof value === "number" || typeof value === "boolean")));
1159
- if (Object.keys(data).length) recorded.data = data;
1160
- const markers = /* @__PURE__ */ new Set();
1161
- for (let holder = error; holder; holder = Object.getPrototypeOf(holder)) for (const symbol of Object.getOwnPropertySymbols(holder)) {
1162
- const key = Symbol.keyFor(symbol);
1163
- if (key !== void 0 && error[symbol] === true) markers.add(key);
1164
- }
1165
- if (markers.size) recorded.markers = [...markers];
1166
- return recorded;
1167
- }
1168
- function fromRecordedError({ data, markers, ...fields }) {
1169
- const error = Object.assign(new Error(fields.message), fields, data);
1170
- for (const marker of markers ?? []) error[Symbol.for(marker)] = true;
1171
- return error;
1172
- }
1173
- /** What two runs compare of an error: its data and markers may differ. */
1174
- function errorIdentity(error) {
1175
- return error && {
1176
- name: error.name,
1177
- message: error.message,
1178
- code: error.code
2060
+ index,
2061
+ state: (step ? step.from[0] : steps.at(-1)?.to[0] ?? statePaths(initial)[0]) ?? "",
2062
+ ...step?.decision === void 0 ? {} : { decision: step.decision },
2063
+ ...step ? { actual: step } : {},
2064
+ ...expected === void 0 ? {} : { expected }
1179
2065
  };
1180
2066
  }
1181
- /** A JSON-safe copy: Dates become ISO strings, Errors become {@link RecordedError}. */
1182
- function toJson(value) {
1183
- if (value === void 0) return void 0;
1184
- return JSON.parse(JSON.stringify(value, function(key, item) {
1185
- const raw = this[key];
1186
- if (raw instanceof Date) return raw.toISOString();
1187
- if (item instanceof Error) return toRecordedError(item);
1188
- if (typeof item === "bigint") return item.toString();
1189
- if (item instanceof Uint8Array) return Array.from(item);
1190
- return item;
1191
- }));
1192
- }
1193
- /** Restores the `Date` timestamps the AI SDK puts on responses. */
1194
- function reviveTimestamps(value) {
1195
- if (value && typeof value === "object") {
1196
- for (const holder of [value, value.response]) if (holder && typeof holder["timestamp"] === "string") holder["timestamp"] = new Date(holder["timestamp"]);
2067
+ function againstTrace(steps, reference, key) {
2068
+ const length = Math.max(steps.length, reference.length);
2069
+ for (let index = 0; index < length; index++) {
2070
+ const step = steps[index];
2071
+ const want = reference[index];
2072
+ if (step && want && key(step) === key(want)) continue;
2073
+ return diverged(steps, index, want, steps[0]?.fromValue ?? reference[0]?.fromValue);
1197
2074
  }
1198
- return value;
1199
- }
1200
- function omit(value, keys) {
1201
- if (!value || typeof value !== "object") return value;
1202
- return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
1203
- }
1204
- /** Key-order-independent JSON, for equality. */
1205
- function stableStringify(value) {
1206
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1207
- if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
1208
- return JSON.stringify(value) ?? "undefined";
1209
- }
1210
- function jsonEqual(a, b) {
1211
- return stableStringify(toJson(a)) === stableStringify(toJson(b));
1212
2075
  }
1213
- function streamFrom(parts) {
1214
- return new ReadableStream({ start(controller) {
1215
- for (const part of parts) controller.enqueue(reviveTimestamps(structuredClone(part)));
1216
- controller.close();
1217
- } });
2076
+ function againstTrajectory(trace, steps, expected) {
2077
+ const initial = initialValue(trace, steps);
2078
+ const timeline = initial === void 0 ? [] : [{ value: initial }];
2079
+ const stepAt = initial === void 0 ? [] : [0];
2080
+ steps.forEach((step, index) => {
2081
+ timeline.push(step.payload);
2082
+ stepAt.push(index);
2083
+ if (JSON.stringify(step.toValue) !== JSON.stringify(step.fromValue)) {
2084
+ timeline.push({ value: step.toValue });
2085
+ stepAt.push(index);
2086
+ }
2087
+ });
2088
+ const match = matchesTrajectory(timeline, expected);
2089
+ if (!match.firstMiss) return void 0;
2090
+ const at = match.firstMiss.searchedFrom;
2091
+ return diverged(steps, at < timeline.length ? stepAt[at] ?? steps.length : steps.length, match.firstMiss.expected, initial);
1218
2092
  }
1219
- async function* iterate(chunks) {
1220
- for (const chunk of chunks) yield structuredClone(chunk);
2093
+ function initialValue(trace, steps) {
2094
+ for (const event of trace) if (event.type === "machine.transition" && require_event_log.isRecord(event.snapshot)) return event.snapshot.value;
2095
+ return steps[0]?.fromValue;
1221
2096
  }
2097
+ //#endregion
2098
+ //#region src/propose-from-traces.ts
1222
2099
  /**
1223
- * Creates a {@link Recorder}. With no options it records: every wrapped call
1224
- * runs for real. With `replay` it answers from a recording instead.
2100
+ * Groups the approval verdicts in many runs' traces by `key` and proposes an
2101
+ * `allow` or `deny` rule for each. Pure and deterministic; a proposal is for
2102
+ * a person to review, and nothing here changes a machine.
2103
+ *
2104
+ * Reads `machine.transition` events: a verdict is a transition, not ignored,
2105
+ * out of `approvalState` on an approve or reject event. Rows come in the
2106
+ * order keys were first seen.
2107
+ *
2108
+ * @example
2109
+ * ```ts no-check
2110
+ * const rows = proposeApprovalRules(traces, {
2111
+ * approvalState: "awaitingApproval",
2112
+ * approveEvents: ["APPROVE"],
2113
+ * rejectEvents: ["REJECT"],
2114
+ * key: ({ snapshot }) => `${snapshot.context.pending.tool}:${snapshot.context.pending.path}`,
2115
+ * });
2116
+ * ```
1225
2117
  */
1226
- function createRecorder(options = {}) {
1227
- const effects = [];
1228
- const replay = options.replay?.effects;
1229
- const replayedModels = replay?.filter((effect) => effect.kind === "model");
1230
- const usedModels = /* @__PURE__ */ new Set();
1231
- const usedTools = /* @__PURE__ */ new Set();
1232
- const normalizeEffect = (effect, list) => options.normalize?.(effect, list.indexOf(effect), list) ?? effect;
1233
- let modelCalls = 0;
1234
- let toolsInFlight = 0;
1235
- /**
1236
- * The earliest unused recorded call that fits this one: one `translate`
1237
- * adapts, or one with the same method and shape. Not by position, so a call
1238
- * the port added or dropped does not shift every answer after it.
1239
- */
1240
- function nextReplayedModel(effect) {
1241
- for (const recorded of replayedModels) {
1242
- if (usedModels.has(recorded)) continue;
1243
- const translated = options.translate?.(structuredClone(recorded), effect);
1244
- if (translated) {
1245
- effect.translated = true;
1246
- return {
1247
- recorded,
1248
- answer: translated
1249
- };
1250
- }
1251
- if (recorded.method === effect.method && modelCallsMatch(options.modelCalls, recorded, effect)) return {
1252
- recorded,
1253
- answer: recorded
2118
+ function proposeApprovalRules(traces, options) {
2119
+ const rows = /* @__PURE__ */ new Map();
2120
+ const rowFor = (key) => {
2121
+ let row = rows.get(key);
2122
+ if (!row) {
2123
+ row = {
2124
+ key,
2125
+ approved: 0,
2126
+ rejected: 0,
2127
+ violations: 0,
2128
+ runs: [],
2129
+ proposal: null,
2130
+ support: 0
1254
2131
  };
2132
+ rows.set(key, row);
1255
2133
  }
1256
- }
1257
- function noAnswerMessage(effect) {
1258
- const unused = replayedModels.filter((recorded) => !usedModels.has(recorded));
1259
- return unused.length ? `Model call #${effect.call} (${effect.method}, ${JSON.stringify(modelCallShape(effect))}) fits no unused recorded call: ${unused.map((recorded) => `#${recorded.call} (${recorded.method}, ${JSON.stringify(modelCallShape(recorded))})`).join(", ")}. A recorded answer only fits a call of the same method and shape; pass \`translate\` to adapt one.` : `Model call #${effect.call} was never made by the recorded run (it made ${replayedModels.length}).`;
1260
- }
1261
- /**
1262
- * Records a model call around `run`, or answers it from the recording.
1263
- * `fallback` runs it on the stand-in when the recording has no answer.
1264
- */
1265
- async function modelCall(seam, method, request, streamed, run, fallback) {
1266
- const effect = {
1267
- kind: "model",
1268
- seam,
1269
- method,
1270
- call: modelCalls++,
1271
- request: toJson(omit(request, [
1272
- "abortSignal",
1273
- "headers",
1274
- "signal"
1275
- ]))
1276
- };
1277
- effects.push(effect);
1278
- if (replay) {
1279
- const replayed = nextReplayedModel(effect);
1280
- if (replayed) {
1281
- const { recorded, answer } = replayed;
1282
- usedModels.add(recorded);
1283
- effect.replayed = recorded.call;
1284
- if (answer.error) {
1285
- effect.error = answer.error;
1286
- throw fromRecordedError(answer.error);
1287
- }
1288
- effect.response = answer.response;
1289
- effect.stream = answer.stream;
1290
- if (seam === "openai") return streamed ? iterate(answer.stream ?? []) : structuredClone(answer.response);
1291
- return streamed ? {
1292
- ...reviveTimestamps(structuredClone(answer.response) ?? {}),
1293
- stream: streamFrom(answer.stream ?? [])
1294
- } : reviveTimestamps(structuredClone(answer.response));
1295
- }
1296
- if (!fallback) {
1297
- const error = new RecordingDivergenceError(noAnswerMessage(effect));
1298
- effect.error = toRecordedError(error);
1299
- throw error;
2134
+ return row;
2135
+ };
2136
+ const inState = (value) => statePaths(value).some((path) => path === options.approvalState || path.startsWith(`${options.approvalState}.`));
2137
+ let index = 0;
2138
+ for (const trace of traces) {
2139
+ const run = index++;
2140
+ const seen = /* @__PURE__ */ new Set();
2141
+ let snapshot;
2142
+ for (const event of trace) {
2143
+ if (event.type !== "machine.transition") continue;
2144
+ const before = snapshot;
2145
+ snapshot = event.snapshot;
2146
+ const type = require_event_log.isRecord(event.event) ? event.event.type : void 0;
2147
+ if (event.ignored === true || typeof type !== "string" || !inState(valueOf(event.from))) continue;
2148
+ const approve = options.approveEvents.includes(type);
2149
+ if (!approve && !options.rejectEvents.includes(type)) continue;
2150
+ const key = options.key({
2151
+ event: event.event,
2152
+ snapshot: before,
2153
+ trace
2154
+ });
2155
+ if (key === void 0) continue;
2156
+ const row = rowFor(key);
2157
+ if (approve) row.approved++;
2158
+ else row.rejected++;
2159
+ if (!seen.has(key)) {
2160
+ seen.add(key);
2161
+ row.runs.push(run);
1300
2162
  }
1301
- effect.unrecorded = true;
1302
- run = fallback;
1303
2163
  }
1304
- let result;
1305
- try {
1306
- result = await run();
1307
- } catch (error) {
1308
- effect.error = toRecordedError(error);
1309
- throw error;
1310
- }
1311
- if (!streamed) {
1312
- effect.response = toJson(result);
1313
- return result;
2164
+ for (const key of options.violations?.(trace) ?? []) {
2165
+ const row = rows.get(key);
2166
+ if (row) row.violations++;
1314
2167
  }
1315
- const parts = [];
1316
- effect.stream = parts;
1317
- if (seam === "openai") {
1318
- const source = result;
1319
- return (async function* () {
1320
- for await (const chunk of source) {
1321
- parts.push(toJson(chunk));
1322
- yield chunk;
1323
- }
1324
- })();
2168
+ }
2169
+ for (const row of rows.values()) {
2170
+ row.support = row.runs.length;
2171
+ row.proposal = row.approved > 0 && row.rejected === 0 && row.violations === 0 ? "allow" : row.rejected > 0 && row.approved === 0 ? "deny" : null;
2172
+ }
2173
+ return [...rows.values()];
2174
+ }
2175
+ /**
2176
+ * Proposes a value for each cap (retry count, steps, batch size) from many
2177
+ * runs' traces: the 95th percentile of what passing runs used, plus one, and
2178
+ * never below the current cap while runs still hit it. Pure and
2179
+ * deterministic; a proposal is for a person to review, and nothing here
2180
+ * changes a machine.
2181
+ *
2182
+ * @example
2183
+ * ```ts no-check
2184
+ * const [retries] = proposeCaps(traces, {
2185
+ * caps: [{ name: "retries", current: 3, failureState: "gaveUp", valueFromRun: countRetries }],
2186
+ * });
2187
+ * ```
2188
+ */
2189
+ function proposeCaps(traces, options) {
2190
+ const runs = [...traces];
2191
+ return options.caps.map((cap) => {
2192
+ let hits = 0;
2193
+ let max = null;
2194
+ const passing = [];
2195
+ for (const trace of runs) {
2196
+ const hit = hitCap(trace, cap);
2197
+ if (hit) hits++;
2198
+ const value = cap.valueFromRun(trace);
2199
+ if (value === void 0) continue;
2200
+ max = max === null ? value : Math.max(max, value);
2201
+ if (!hit) passing.push(value);
1325
2202
  }
1326
- const { stream, ...rest } = result;
1327
- effect.response = toJson(rest);
2203
+ passing.sort((a, b) => a - b);
2204
+ const p95 = passing.length ? passing[Math.ceil(.95 * passing.length) - 1] : null;
2205
+ const proposal = p95 === null ? null : hits > 0 && cap.current !== void 0 ? Math.max(p95 + 1, cap.current) : p95 + 1;
1328
2206
  return {
1329
- ...rest,
1330
- stream: stream.pipeThrough(new TransformStream({ transform(part, controller) {
1331
- parts.push(toJson(part));
1332
- controller.enqueue(part);
1333
- } }))
2207
+ name: cap.name,
2208
+ hits,
2209
+ passing: passing.length,
2210
+ max,
2211
+ p95,
2212
+ proposal
1334
2213
  };
2214
+ });
2215
+ }
2216
+ function hitCap(trace, cap) {
2217
+ for (const event of trace) {
2218
+ if (cap.failureState !== void 0 && event.type === "machine.transition" && statePaths(valueOf(event.snapshot)).some((path) => path === cap.failureState || path.startsWith(`${cap.failureState}.`))) return true;
2219
+ if (cap.failureOutput && event.type === "run.end" && event.status === "done") {
2220
+ if (cap.failureOutput(event.output)) return true;
2221
+ }
1335
2222
  }
1336
- /** `inputOf` picks the recorded input from the call's arguments. */
1337
- function tool(name, fn, inputOf = (args) => args.length === 1 ? args[0] : args) {
1338
- return ((...args) => {
1339
- const input = toJson(inputOf(args));
1340
- const effect = {
1341
- kind: "tool",
1342
- name,
1343
- step: modelCalls,
1344
- input,
1345
- ...toolsInFlight > 0 ? { concurrent: true } : {}
1346
- };
1347
- effects.push(effect);
1348
- return track(call(effect, args));
2223
+ return false;
2224
+ }
2225
+ //#endregion
2226
+ //#region src/decision-requests.ts
2227
+ /**
2228
+ * The decisions a run asked for, read from its trace: each decision's first
2229
+ * `request.start`, with the states the run was in. A trace is one run's events,
2230
+ * live or serialized with `serializeTraceEvent`. Retries of the same decision
2231
+ * are left out, so each decision appears once.
2232
+ *
2233
+ * Use the requests as eval rows (run a decider on each and compare its event
2234
+ * with a label) or as probe inputs for a policy. A serialized request keeps its
2235
+ * `options`, `metadata`, `system`, and `prompt`; event schemas do not survive
2236
+ * serialization, so replay closed choices (`options`) rather than open ones.
2237
+ *
2238
+ * @example
2239
+ * ```ts no-check
2240
+ * const rows = traces.flatMap((trace) => getDecisionRequests(trace, { name: "chooseResolution" }));
2241
+ * for (const { request } of rows) console.log((await decide(request)).event);
2242
+ * ```
2243
+ */
2244
+ function getDecisionRequests(trace, options = {}) {
2245
+ const requests = [];
2246
+ let current = [];
2247
+ for (const event of trace) if (event.type === "machine.transition") current = statePaths(valueOf(event.snapshot));
2248
+ else if (event.type === "request.start" && isFirstDecision(event.request)) {
2249
+ if (options.name !== void 0 && event.request.name !== options.name) continue;
2250
+ requests.push({
2251
+ states: [...current],
2252
+ request: event.request
1349
2253
  });
1350
- function call(effect, args) {
1351
- const { input } = effect;
1352
- if (replay && options.tools !== "live") {
1353
- const wanted = normalizeEffect(effect, effects).input;
1354
- const matches = (candidate) => candidate.kind === "tool" && !usedTools.has(candidate) && candidate.name === name && jsonEqual(normalizeEffect(candidate, replay).input, wanted);
1355
- const recorded = replay.find(matches);
1356
- if (!recorded && options.fallback?.tools) {
1357
- effect.unrecorded = true;
1358
- return runLive(effect, args);
1359
- }
1360
- const settle = (value) => {
1361
- if (recorded?.sync) return value();
1362
- try {
1363
- return Promise.resolve(value());
1364
- } catch (error) {
1365
- return Promise.reject(error);
1366
- }
1367
- };
1368
- return settle(() => {
1369
- if (!recorded) {
1370
- const error = new RecordingDivergenceError(`Tool '${name}' was called with ${JSON.stringify(input)}; the recorded run made no such call.`);
1371
- effect.error = toRecordedError(error);
1372
- throw error;
1373
- }
1374
- usedTools.add(recorded);
1375
- if (recorded.sync) effect.sync = true;
1376
- if (recorded.error) {
1377
- effect.error = recorded.error;
1378
- throw fromRecordedError(recorded.error);
1379
- }
1380
- effect.output = recorded.output;
1381
- return structuredClone(recorded.output);
1382
- });
1383
- }
1384
- return runLive(effect, args);
1385
- }
1386
- function runLive(effect, args) {
1387
- let output;
1388
- try {
1389
- output = fn(...args);
1390
- } catch (error) {
1391
- effect.sync = true;
1392
- effect.error = toRecordedError(error);
1393
- throw error;
1394
- }
1395
- if (!(output instanceof Promise)) {
1396
- effect.sync = true;
1397
- effect.output = toJson(output);
1398
- return output;
1399
- }
1400
- return output.then((value) => {
1401
- effect.output = toJson(value);
1402
- return value;
1403
- }, (error) => {
1404
- effect.error = toRecordedError(error);
1405
- throw error;
2254
+ }
2255
+ return requests;
2256
+ }
2257
+ //#endregion
2258
+ //#region src/repeat-runs.ts
2259
+ /**
2260
+ * Summarizes repeated runs of each scenario: how often each passed, whether
2261
+ * all its runs passed (pass^k), how many distinct state paths they took, and
2262
+ * where they first went different ways. Pure. Use it for runs collected
2263
+ * elsewhere, such as CI shards or replays; {@link repeatRuns} collects them and
2264
+ * calls it.
2265
+ *
2266
+ * A scenario that passes 3 of 5 runs and `divergedAt: 'deciding'` points at one
2267
+ * decision, not at a flaky agent.
2268
+ *
2269
+ * @example
2270
+ * ```ts no-check
2271
+ * const report = summarizeRepeats(shards.map((s) => ({ id: s.id, scenario: s, runs: s.runs })));
2272
+ * report.passHat(3); // the chance 3 runs of a scenario all pass
2273
+ * ```
2274
+ */
2275
+ function summarizeRepeats(groups) {
2276
+ const scenarios = groups.map((group) => summarize$1(group));
2277
+ const traces = groups.flatMap((group) => group.runs.flatMap((run) => run.trace ? [run.trace] : []));
2278
+ const most = Math.max(0, ...groups.map((group) => group.runs.length));
2279
+ const passHat = (j) => {
2280
+ 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}.`);
2281
+ const eligible = scenarios.filter((scenario) => scenario.runs.length >= j);
2282
+ return eligible.reduce((total, scenario) => total + allPass(scenario.passes, scenario.runs.length, j), 0) / eligible.length;
2283
+ };
2284
+ return {
2285
+ scenarios,
2286
+ passHat,
2287
+ traces
2288
+ };
2289
+ }
2290
+ /**
2291
+ * Runs every scenario `k` times and summarizes the runs with
2292
+ * {@link summarizeRepeats}. Runs are sequential, scenario by scenario. A run
2293
+ * that throws fails, with its message as `error` and no trace.
2294
+ *
2295
+ * With a live model, one run per scenario says little: τ-bench found pass^k
2296
+ * falls well below the single-run rate. Report pass^k next to it.
2297
+ *
2298
+ * @example
2299
+ * ```ts no-check
2300
+ * const report = await repeatRuns({
2301
+ * scenarios,
2302
+ * k: 5,
2303
+ * run: async (scenario) => {
2304
+ * const trace: AgentTraceEvent[] = [];
2305
+ * const result = await runToQuiescence(
2306
+ * createAgentRuntime(machine, { executors, onTrace: (event) => trace.push(event) }),
2307
+ * { input: scenario.input },
2308
+ * );
2309
+ * return { trace, outcome: String(result.snapshot.value) };
2310
+ * },
2311
+ * passed: (scenario, { outcome }) => outcome === scenario.expected,
2312
+ * });
2313
+ * report.passHat(5);
2314
+ * ```
2315
+ */
2316
+ async function repeatRuns(options) {
2317
+ 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}.`);
2318
+ const groups = [];
2319
+ for (const scenario of options.scenarios) {
2320
+ const runs = [];
2321
+ for (let attempt = 0; attempt < options.k; attempt++) try {
2322
+ const result = await options.run(scenario, attempt);
2323
+ runs.push({
2324
+ passed: options.passed(scenario, result),
2325
+ trace: result.trace,
2326
+ ...result.outcome === void 0 ? {} : { outcome: result.outcome }
2327
+ });
2328
+ } catch (error) {
2329
+ runs.push({
2330
+ passed: false,
2331
+ error: error instanceof Error ? error.message : String(error)
1406
2332
  });
1407
2333
  }
2334
+ groups.push({
2335
+ id: scenario.id,
2336
+ scenario,
2337
+ runs
2338
+ });
1408
2339
  }
1409
- /** Counts an async tool call as running until it settles. */
1410
- function track(result) {
1411
- if (result instanceof Promise) {
1412
- toolsInFlight++;
1413
- const settled = () => {
1414
- toolsInFlight--;
1415
- };
1416
- result.then(settled, settled);
1417
- }
1418
- return result;
2340
+ return summarizeRepeats(groups);
2341
+ }
2342
+ function summarize$1(group) {
2343
+ const passes = group.runs.filter((run) => run.passed).length;
2344
+ const traces = group.runs.flatMap((run) => run.trace ? [run.trace] : []);
2345
+ const paths = new Set(traces.map((trace) => traceSteps(trace).filter((step) => !step.ignored).map((step) => `${step.from.join(",")}|${step.event}|${step.to.join(",")}`).join(" ")));
2346
+ const reference = traces.find((trace) => trace.some((event) => event.type === "machine.transition"));
2347
+ let earliest;
2348
+ for (const trace of reference ? traces : []) {
2349
+ if (trace === reference) continue;
2350
+ const divergence = firstDivergence(trace, reference);
2351
+ if (divergence && (!earliest || divergence.index < earliest.index)) earliest = divergence;
1419
2352
  }
1420
2353
  return {
1421
- model(model) {
1422
- const base = model;
1423
- const stand = options.fallback?.model;
1424
- const wrapped = Object.create(base);
1425
- for (const method of [
1426
- "doGenerate",
1427
- "doStream",
1428
- "doDecide",
1429
- "doEvaluate"
1430
- ]) {
1431
- if (typeof base[method] !== "function") continue;
1432
- const invoke = (target, callOptions) => target[method].call(target, callOptions);
1433
- wrapped[method] = (callOptions) => modelCall("ai-sdk", method, callOptions, method === "doStream", () => invoke(base, callOptions), stand && typeof stand[method] === "function" ? () => invoke(stand, callOptions) : void 0);
1434
- }
1435
- return wrapped;
1436
- },
1437
- openai(client) {
1438
- const wrapCreate = (resource, method) => new Proxy(resource, { get(target, key, receiver) {
1439
- if (key !== "create") return Reflect.get(target, key, receiver);
1440
- return (params, requestOptions) => {
1441
- let api;
1442
- const create = (resource) => () => {
1443
- api = Reflect.get(resource, "create").call(resource, params, requestOptions);
1444
- return Promise.resolve(api);
1445
- };
1446
- const stand = fallbackResource(method);
1447
- const promise = modelCall("openai", method, params, params?.stream === true, create(target), stand && create(stand));
1448
- return Object.assign(promise, { withResponse: async () => {
1449
- const data = await promise;
1450
- const meta = await api?.withResponse?.();
1451
- return {
1452
- data,
1453
- response: meta?.response ?? new Response(null),
1454
- request_id: meta?.request_id ?? null
1455
- };
1456
- } });
1457
- };
1458
- } });
1459
- const fallbackResource = (method) => {
1460
- let value = options.fallback?.openai;
1461
- for (const key of method.split(".").slice(0, -1)) value = value?.[key];
1462
- return value && typeof value === "object" ? value : void 0;
1463
- };
1464
- const wrapped = /* @__PURE__ */ new Map();
1465
- const wrap = (key, make) => {
1466
- if (!wrapped.has(key)) wrapped.set(key, make());
1467
- return wrapped.get(key);
1468
- };
1469
- return new Proxy(client, { get(target, key, receiver) {
1470
- const value = Reflect.get(target, key, receiver);
1471
- if (key === "responses" && value) return wrap(key, () => wrapCreate(value, "responses.create"));
1472
- if (key === "chat" && value) return wrap(key, () => new Proxy(value, { get(chat, chatKey, chatReceiver) {
1473
- const inner = Reflect.get(chat, chatKey, chatReceiver);
1474
- return chatKey === "completions" && inner ? wrap("chat.completions", () => wrapCreate(inner, "chat.completions.create")) : inner;
1475
- } }));
1476
- return value;
1477
- } });
1478
- },
1479
- tool: (name, fn) => tool(name, fn),
1480
- tools(tools) {
1481
- return Object.fromEntries(Object.entries(tools).map(([name, definition]) => [name, definition.execute ? {
1482
- ...definition,
1483
- execute: tool(name, definition.execute, (args) => args[0])
1484
- } : definition]));
1485
- },
1486
- output(value) {
1487
- effects.push({
1488
- kind: "output",
1489
- value: toJson(value)
1490
- });
1491
- },
1492
- get recording() {
1493
- return {
1494
- version: 1,
1495
- effects: toJson(effects)
1496
- };
1497
- }
2354
+ ...group,
2355
+ passes,
2356
+ passAny: passes > 0,
2357
+ passAll: group.runs.length > 0 && passes === group.runs.length,
2358
+ distinctPaths: paths.size,
2359
+ ...earliest ? { divergedAt: earliest.state } : {}
1498
2360
  };
1499
2361
  }
1500
- /** True when two model calls offer the same tool names and response format. */
1501
- function sameModelCallShape(expected, actual) {
1502
- return jsonEqual(modelCallShape(expected), modelCallShape(actual));
1503
- }
1504
- function modelCallsMatch(match, expected, actual) {
1505
- if (match === "none") return true;
1506
- if (typeof match === "function") return match(expected, actual);
1507
- return sameModelCallShape(expected, actual);
1508
- }
1509
- function shapeMessage(expected, actual) {
1510
- 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.`;
2362
+ /** C(passes, j) / C(runs, j), as a product so large counts don't overflow. */
2363
+ function allPass(passes, runs, j) {
2364
+ let chance = 1;
2365
+ for (let i = 0; i < j; i++) chance *= Math.max(0, passes - i) / (runs - i);
2366
+ return chance;
1511
2367
  }
2368
+ //#endregion
2369
+ //#region src/judge-agreement.ts
1512
2370
  /**
1513
- * Offered tool names and the response format, or a decision's questions and
1514
- * their options: what a recorded answer depends on.
2371
+ * Measures how well a judge agrees with people on the same cases: accuracy,
2372
+ * per-label recall, the confusion matrix, and the rows that disagree. With
2373
+ * `positive`, also the TPR and TNR, the recommended view for binary judges
2374
+ * (Husain/Shankar), and a correction for the judge's bias on unlabeled rows.
2375
+ * Pure.
2376
+ *
2377
+ * Build rows from confirmed labels only; draft labels gate nothing. Group by
2378
+ * decision state or request name so each narrow judge is aligned on its own.
2379
+ * A row with no group key counts in the totals and in no group. Run it on a
2380
+ * dev split and report the held-out split separately.
2381
+ *
2382
+ * Throws `AgentError` with code `'empty-agreement-rows'` when `rows` is empty.
2383
+ *
2384
+ * @example
2385
+ * ```ts no-check
2386
+ * const report = judgeAgreement(
2387
+ * labeled.map((s) => ({ id: s.id, human: s.label, judge: verdicts[s.id], group: s.request })),
2388
+ * { positive: 'fail' },
2389
+ * );
2390
+ * report.binary; // { tpr: 0.9, tnr: 0.8 }
2391
+ * report.correct?.(0.3); // estimated true failure rate in production
2392
+ * ```
1515
2393
  */
1516
- function modelCallShape(effect) {
1517
- const request = effect.request ?? {};
1518
- const questions = request["questions"];
1519
- if (questions && typeof questions === "object") return { questions: Object.entries(questions).map(([name, question]) => {
1520
- const criteria = question["criteria"];
1521
- if (question["type"] === "choice" && criteria && typeof criteria === "object") return [
1522
- name,
1523
- question["type"],
1524
- Object.keys(criteria).sort()
1525
- ];
1526
- if (question["type"] === "score" && Array.isArray(criteria)) return [
1527
- name,
1528
- question["type"],
1529
- criteria.length
1530
- ];
1531
- return [name, question["type"]];
1532
- }).sort((x, y) => String(x[0]).localeCompare(String(y[0]))) };
1533
- return {
1534
- tools: (Array.isArray(request["tools"]) ? request["tools"] : []).map((tool) => tool["name"] ?? tool["function"]?.["name"]).sort(),
1535
- format: request["responseFormat"]?.["type"] ?? request["response_format"]?.["type"] ?? (request["text"]?.["format"])?.["type"] ?? "text"
2394
+ function judgeAgreement(rows, options = {}) {
2395
+ if (rows.length === 0) throw new require_event_log.AgentError("empty-agreement-rows", "judgeAgreement: rows must contain at least one row.");
2396
+ const report = summarize(rows, options.positive);
2397
+ const groupOf = options.groupBy ?? ((row) => row.group);
2398
+ if (options.groupBy || rows.some((row) => row.group !== void 0)) {
2399
+ const grouped = /* @__PURE__ */ new Map();
2400
+ for (const row of rows) {
2401
+ const key = groupOf(row);
2402
+ if (key === void 0) continue;
2403
+ const members = grouped.get(key);
2404
+ if (members) members.push(row);
2405
+ else grouped.set(key, [row]);
2406
+ }
2407
+ const groups = Object.create(null);
2408
+ for (const [key, members] of grouped) groups[key] = summarize(members, options.positive);
2409
+ report.groups = groups;
2410
+ }
2411
+ return report;
2412
+ }
2413
+ function summarize(rows, positive) {
2414
+ const perLabel = Object.create(null);
2415
+ const confusion = Object.create(null);
2416
+ const disagreements = [];
2417
+ let agreed = 0;
2418
+ for (const { id, human, judge } of rows) {
2419
+ const label = perLabel[human] ??= {
2420
+ human: 0,
2421
+ agreed: 0
2422
+ };
2423
+ const row = confusion[human] ??= Object.create(null);
2424
+ label.human++;
2425
+ row[judge] = (row[judge] ?? 0) + 1;
2426
+ if (human === judge) {
2427
+ label.agreed++;
2428
+ agreed++;
2429
+ } else disagreements.push({
2430
+ id,
2431
+ human,
2432
+ judge
2433
+ });
2434
+ }
2435
+ const summary = {
2436
+ total: rows.length,
2437
+ accuracy: agreed / rows.length,
2438
+ perLabel,
2439
+ confusion,
2440
+ disagreements
2441
+ };
2442
+ if (positive === void 0) return summary;
2443
+ let positives = 0;
2444
+ let truePositives = 0;
2445
+ let negatives = 0;
2446
+ let trueNegatives = 0;
2447
+ for (const { human, judge } of rows) if (human === positive) {
2448
+ positives++;
2449
+ if (judge === positive) truePositives++;
2450
+ } else {
2451
+ negatives++;
2452
+ if (judge !== positive) trueNegatives++;
2453
+ }
2454
+ const tpr = positives === 0 ? void 0 : truePositives / positives;
2455
+ const tnr = negatives === 0 ? void 0 : trueNegatives / negatives;
2456
+ summary.binary = {
2457
+ tpr,
2458
+ tnr
1536
2459
  };
2460
+ 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)));
2461
+ return summary;
1537
2462
  }
2463
+ //#endregion
2464
+ //#region src/compare-runs.ts
1538
2465
  /**
1539
- * Puts each group of concurrent tool calls in a stable order, so parallel tool
1540
- * calls that finished in a different order still compare equal. A tool call
1541
- * that started after the previous one settled begins a new group, so
1542
- * sequential calls keep their order.
2466
+ * Runs every scenario through a baseline and a candidate implementation and
2467
+ * labels each difference, so a port can show where it behaves like the code it
2468
+ * replaces and where it differs on purpose.
2469
+ *
2470
+ * Parity is outcome-level: the terminal outcome and the effects in the world,
2471
+ * not the sequence of tool calls, since a machine usually reorders steps. A
2472
+ * candidate that broke no rule where the baseline broke one is intended, even
2473
+ * when the outcome matches. A difference also counts as intended when only the
2474
+ * candidate reached the scenario's `expected` outcome. Every other difference,
2475
+ * and every candidate rule break, is a regression for a person to review.
2476
+ *
2477
+ * Runs are sequential, baseline first. A run that throws is recorded with
2478
+ * outcome `'threw'` and the error message as its `detail`. Parity holds for
2479
+ * these scenarios and these runs only; with a live model, run it more than once.
2480
+ *
2481
+ * @example
2482
+ * ```ts no-check
2483
+ * const report = await compareRuns({
2484
+ * scenarios,
2485
+ * baseline: async (s) => toParityRun(await runRawLoop(s)),
2486
+ * candidate: async (s) => toParityRun(await runDesk(s)),
2487
+ * });
2488
+ * expect(report.ok).toBe(true);
2489
+ * ```
1543
2490
  */
1544
- function normalize(effects) {
1545
- const result = [];
1546
- let batch = [];
1547
- const flush = () => {
1548
- result.push(...batch.sort((a, b) => stableStringify([a.name, a.input]).localeCompare(stableStringify([b.name, b.input]))));
1549
- batch = [];
2491
+ async function compareRuns(options) {
2492
+ const scenarios = [];
2493
+ const counts = {
2494
+ same: 0,
2495
+ intended: 0,
2496
+ regression: 0
1550
2497
  };
1551
- for (const effect of effects) {
1552
- if (effect.kind !== "tool" || !effect.concurrent) flush();
1553
- if (effect.kind === "tool") batch.push(effect);
1554
- else result.push(effect);
2498
+ for (const scenario of options.scenarios) {
2499
+ const baseline = await settle$1(() => options.baseline(scenario));
2500
+ const candidate = await settle$1(() => options.candidate(scenario));
2501
+ const { label, reason } = labelRun(scenario.expected, baseline, candidate);
2502
+ counts[label]++;
2503
+ scenarios.push({
2504
+ id: scenario.id,
2505
+ scenario,
2506
+ label,
2507
+ reason,
2508
+ baseline,
2509
+ candidate
2510
+ });
1555
2511
  }
1556
- flush();
1557
- return result;
2512
+ return {
2513
+ scenarios,
2514
+ counts,
2515
+ ok: counts.regression === 0
2516
+ };
1558
2517
  }
1559
- function describe(effect) {
1560
- switch (effect.kind) {
1561
- case "model": return `model call #${effect.call} (${effect.method})`;
1562
- case "tool": return `tool '${effect.name}' with ${JSON.stringify(effect.input)}`;
1563
- case "output": return `output ${JSON.stringify(effect.value)}`;
2518
+ async function settle$1(run) {
2519
+ try {
2520
+ return await run();
2521
+ } catch (error) {
2522
+ return {
2523
+ outcome: "threw",
2524
+ detail: error instanceof Error ? error.message : String(error)
2525
+ };
1564
2526
  }
1565
2527
  }
1566
- /** Why two effects differ, or `undefined` when they are the same. */
1567
- function differ(left, right, options) {
1568
- if (left.kind !== right.kind) return {
1569
- reason: "kind",
1570
- message: `Expected ${describe(left)}; the port made ${describe(right)}.`
2528
+ function labelRun(expected, baseline, candidate) {
2529
+ if (candidate.violations?.length) return {
2530
+ label: "regression",
2531
+ reason: `candidate broke a rule: ${list(candidate.violations)}`
1571
2532
  };
1572
- if (left.kind === "model" && right.kind === "model") {
1573
- if (right.translated && right.replayed === left.call) return void 0;
1574
- if (left.method !== right.method) return {
1575
- reason: "model-method",
1576
- message: `Model call #${left.call} used ${left.method}; the port used ${right.method}.`
1577
- };
1578
- if (!modelCallsMatch(options.modelCalls, left, right)) return {
1579
- reason: "model-call-shape",
1580
- message: shapeMessage(left, right)
1581
- };
1582
- if (!jsonEqual(errorIdentity(left.error), errorIdentity(right.error))) {
1583
- const outcome = (error) => error ? `failed with ${error.name}: ${error.message}` : "succeeded";
1584
- return {
1585
- reason: "model-error",
1586
- message: `Model call #${left.call} ${outcome(left.error)}; in the port it ${outcome(right.error)}.`
1587
- };
1588
- }
1589
- return;
2533
+ if (candidate.outcome === "threw") return {
2534
+ label: "regression",
2535
+ reason: `candidate threw: ${String(candidate.detail)}`
2536
+ };
2537
+ if (baseline.violations?.length) return {
2538
+ label: "intended",
2539
+ reason: `baseline broke a rule: ${list(baseline.violations)}`
2540
+ };
2541
+ const sameOutcome = baseline.outcome === candidate.outcome;
2542
+ if (sameOutcome && structurallyEqual(baseline.effects, candidate.effects)) return {
2543
+ label: "same",
2544
+ reason: ""
2545
+ };
2546
+ if (expected !== void 0 && candidate.outcome === expected && baseline.outcome !== expected) return {
2547
+ label: "intended",
2548
+ reason: `only the candidate reached the expected '${expected}'`
2549
+ };
2550
+ return {
2551
+ label: "regression",
2552
+ reason: sameOutcome ? "effects differ" : `outcome differs: ${baseline.outcome} → ${candidate.outcome}`
2553
+ };
2554
+ }
2555
+ function list(items) {
2556
+ return items.map((item) => typeof item === "string" ? item : JSON.stringify(item)).join(", ");
2557
+ }
2558
+ function structurallyEqual(a, b) {
2559
+ if (Object.is(a, b)) return true;
2560
+ if (a instanceof Date || b instanceof Date) return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
2561
+ if (a instanceof Map || b instanceof Map) return a instanceof Map && b instanceof Map && structurallyEqual([...a], [...b]);
2562
+ if (a instanceof Set || b instanceof Set) return a instanceof Set && b instanceof Set && structurallyEqual([...a], [...b]);
2563
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => structurallyEqual(item, b[index]));
2564
+ if (!require_event_log.isRecord(a) || !require_event_log.isRecord(b)) return false;
2565
+ const keys = Object.keys(a);
2566
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && structurallyEqual(a[key], b[key]));
2567
+ }
2568
+ //#endregion
2569
+ //#region src/check-parity.ts
2570
+ /**
2571
+ * `checkParity` — one call that records a workflow, replays its port, and
2572
+ * compares their effects, per scenario.
2573
+ * @module
2574
+ */
2575
+ /** Each function effect wrapped with `recorder.fn`, by its key. */
2576
+ function recordEffects(recorder, effects) {
2577
+ return require_effects.mapEffects(effects, (name, effect) => recorder.fn(name, effect));
2578
+ }
2579
+ async function settle(run, recorder, normalize) {
2580
+ try {
2581
+ const output = await run();
2582
+ recorder.output(normalize(output));
2583
+ return { output };
2584
+ } catch (error) {
2585
+ return { error };
1590
2586
  }
1591
- if (left.kind === "tool" && right.kind === "tool") {
1592
- if (left.name !== right.name) return {
1593
- reason: "tool-name",
1594
- message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1595
- };
1596
- if (!jsonEqual(left.input, right.input)) return {
1597
- reason: "tool-input",
1598
- message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.input)}.`
1599
- };
1600
- if (!jsonEqual(left.output, right.output) || !jsonEqual(errorIdentity(left.error), errorIdentity(right.error))) return {
1601
- reason: "tool-result",
1602
- message: `Tool '${left.name}' returned a different result.`
1603
- };
1604
- return;
2587
+ }
2588
+ function errorIdentity(outcome, normalize) {
2589
+ if (!("error" in outcome)) return void 0;
2590
+ const error = normalize ? normalize(outcome.error) : outcome.error;
2591
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
2592
+ if (!normalize) return String(error);
2593
+ try {
2594
+ return stableStringify(require_effects.toJsonValue(error) ?? null);
2595
+ } catch {
2596
+ return String(error);
1605
2597
  }
1606
- if (left.kind === "output" && right.kind === "output" && !jsonEqual(left.value, right.value)) return {
1607
- reason: "output",
1608
- message: `Expected ${describe(left)}; the port returned ${JSON.stringify(right.value)}.`
1609
- };
1610
2598
  }
1611
2599
  /**
1612
- * Compares two recordings and reports every effect that differs. `expected`
1613
- * is the original's recording, `actual` the port's. Effects that are the same
1614
- * on both sides are lined up first (longest common subsequence), so one extra
1615
- * call does not shift every effect after it; between them, effects of the same
1616
- * kind pair up and report what changed, and the rest are missing or extra.
2600
+ * Checks a port against the workflow it replaces, scenario by scenario: runs
2601
+ * `before` on fresh `effects` under `createRecorder`, replays `after` against
2602
+ * that recording (no effect really runs), and compares the two with
2603
+ * `compareRecordings`. Effects are compared by name, call order, arguments
2604
+ * and results; the output by value.
2605
+ *
2606
+ * Never throws for a port that misbehaves: an `after` that throws (a
2607
+ * `RecordingDivergenceError` for a call the original never made, or its own
2608
+ * error) is a row with `after: { error }`. When both sides throw, they match
2609
+ * on the error's name and message, after `normalizeError` when given.
2610
+ *
2611
+ * @example
2612
+ * ```ts
2613
+ * const report = await checkParity({
2614
+ * scenarios: [{ id: "refund", input: ticket }],
2615
+ * effects: () => createFakeEffects(),
2616
+ * before: (input, effects) => legacyRunTicket(input, effects),
2617
+ * after: (input, effects) => step1.run(input, { effects }),
2618
+ * });
2619
+ * expect(report.equivalent).toBe(true);
2620
+ * ```
1617
2621
  */
1618
- function compareRecordings(expected, actual, options = {}) {
1619
- const select = (effects) => normalize(effects.flatMap((effect, index) => {
1620
- if (options.kinds && !options.kinds.includes(effect.kind)) return [];
1621
- const mapped = options.normalize ? options.normalize(effect, index, effects) : effect;
1622
- return mapped ? [mapped] : [];
1623
- }));
1624
- const a = select(expected.effects);
1625
- const b = select(actual.effects);
1626
- const same = a.map((left) => b.map((right) => !differ(left, right, options)));
1627
- const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }, () => 0));
1628
- 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]);
1629
- const divergences = [];
1630
- let lefts = [];
1631
- let rights = [];
1632
- const flushGap = (at) => {
1633
- const unpairedRights = [...rights];
1634
- const changed = [];
1635
- for (const index of lefts) {
1636
- const left = a[index];
1637
- const k = unpairedRights.findIndex((j) => b[j].kind === left.kind);
1638
- if (k === -1) {
1639
- changed.push({
1640
- index,
1641
- reason: "missing-effect",
1642
- expected: left,
1643
- message: `The port never made ${describe(left)}.`
1644
- });
1645
- continue;
1646
- }
1647
- const right = b[unpairedRights.splice(k, 1)[0]];
1648
- const difference = differ(left, right, options);
1649
- if (difference) changed.push({
1650
- index,
1651
- expected: left,
1652
- actual: right,
1653
- ...difference
2622
+ async function checkParity(options) {
2623
+ const rows = [];
2624
+ for (const scenario of options.scenarios) {
2625
+ const recorder = createRecorder();
2626
+ const effects = recordEffects(recorder, options.effects(scenario));
2627
+ const normalize = (output) => options.normalizeOutput ? options.normalizeOutput(output, scenario) : output;
2628
+ const before = await settle(() => options.before(scenario.input, effects), recorder, normalize);
2629
+ const recording = recorder.recording;
2630
+ const replayer = createRecorder({ replay: recording });
2631
+ const stand = recordEffects(replayer, options.effects(scenario));
2632
+ const after = await settle(() => options.after(scenario.input, stand), replayer, normalize);
2633
+ const replay = replayer.recording;
2634
+ const { divergences } = compareRecordings(recording, replay, options.compare);
2635
+ const normalizeError = options.normalizeError && ((error) => options.normalizeError(error, scenario));
2636
+ const thrownBefore = errorIdentity(before, normalizeError);
2637
+ const thrownAfter = errorIdentity(after, normalizeError);
2638
+ if (thrownBefore !== void 0 && thrownAfter !== void 0 && thrownBefore !== thrownAfter) divergences.push({
2639
+ index: recording.effects.length,
2640
+ reason: "output",
2641
+ message: `The original threw ${thrownBefore}; the port threw ${thrownAfter}.`
2642
+ });
2643
+ else if (thrownBefore === void 0 !== (thrownAfter === void 0)) {
2644
+ const returned = (thrownBefore === void 0 ? recording : replay).effects.filter((effect) => effect.kind === "output").at(-1);
2645
+ const value = JSON.stringify(returned?.kind === "output" ? returned.value : void 0);
2646
+ const message = thrownAfter !== void 0 ? `The original returned ${value}; the port threw ${thrownAfter}.` : `The original threw ${thrownBefore}; the port returned ${value}.`;
2647
+ const existing = divergences.find((d) => d.reason === "output" && d.expected?.kind === "output" !== (d.actual?.kind === "output"));
2648
+ if (existing) existing.message = message;
2649
+ else divergences.push({
2650
+ index: recording.effects.length,
2651
+ reason: "output",
2652
+ message
1654
2653
  });
1655
2654
  }
1656
- for (const j of unpairedRights) divergences.push({
1657
- index: lefts[0] ?? at,
1658
- reason: "extra-effect",
1659
- actual: b[j],
1660
- message: `The port made ${describe(b[j])}, which the original never made.`
2655
+ rows.push({
2656
+ id: scenario.id,
2657
+ scenario,
2658
+ equivalent: divergences.length === 0,
2659
+ divergences,
2660
+ before,
2661
+ after,
2662
+ recording,
2663
+ replay
1661
2664
  });
1662
- divergences.push(...changed);
1663
- lefts = [];
1664
- rights = [];
1665
- };
1666
- let i = 0;
1667
- let j = 0;
1668
- while (i < a.length || j < b.length) if (i < a.length && j < b.length && same[i][j]) {
1669
- flushGap(i);
1670
- i++;
1671
- j++;
1672
- } else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) rights.push(j++);
1673
- else lefts.push(i++);
1674
- flushGap(i);
1675
- divergences.sort((x, y) => x.index - y.index);
1676
- return divergences.length ? {
1677
- equivalent: false,
1678
- divergence: divergences[0],
1679
- divergences
1680
- } : {
1681
- equivalent: true,
1682
- divergences
2665
+ }
2666
+ return {
2667
+ equivalent: rows.every((row) => row.equivalent),
2668
+ scenarios: rows
1683
2669
  };
1684
2670
  }
1685
2671
  //#endregion
@@ -1688,6 +2674,8 @@ exports.AgentUnknownStateError = require_verify.AgentUnknownStateError;
1688
2674
  exports.RecordingDivergenceError = RecordingDivergenceError;
1689
2675
  exports.assertAgentMachine = require_verify.assertAgentMachine;
1690
2676
  exports.canReach = require_verify.canReach;
2677
+ exports.checkCrashRecovery = checkCrashRecovery;
2678
+ exports.checkParity = checkParity;
1691
2679
  exports.compareRecordings = compareRecordings;
1692
2680
  exports.compareRuns = compareRuns;
1693
2681
  exports.createRecorder = createRecorder;
@@ -1698,9 +2686,12 @@ exports.getDecisionRequests = getDecisionRequests;
1698
2686
  exports.judgeAgreement = judgeAgreement;
1699
2687
  exports.lintAgentMachine = require_verify.lintAgentMachine;
1700
2688
  exports.matchesTrajectory = matchesTrajectory;
2689
+ exports.proposeApprovalRules = proposeApprovalRules;
2690
+ exports.proposeCaps = proposeCaps;
1701
2691
  exports.repeatRuns = repeatRuns;
1702
2692
  exports.runSeam = runSeam;
1703
2693
  exports.sameModelCallShape = sameModelCallShape;
1704
2694
  exports.simulateAgent = require_verify.simulateAgent;
1705
2695
  exports.summarizeRepeats = summarizeRepeats;
2696
+ exports.textOutput = require_verify.textOutput;
1706
2697
  exports.traceCoverage = traceCoverage;