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

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 (64) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/ai-sdk.cjs +114 -63
  3. package/dist/ai-sdk.d.cts +11 -2
  4. package/dist/ai-sdk.d.mts +11 -2
  5. package/dist/ai-sdk.mjs +115 -64
  6. package/dist/{decision-BPdEaxPf.cjs → decision-BEsATcr1.cjs} +18 -2
  7. package/dist/{decision-CV7WiV5C.mjs → decision-COkJNjOW.mjs} +18 -2
  8. package/dist/{event-log-CKWeC7H-.cjs → event-log-BWSSLUff.cjs} +139 -10
  9. package/dist/{event-log-DAqsalT1.mjs → event-log-C7jeH0y8.mjs} +123 -12
  10. package/dist/{event-log-store-C2NjVlWU.d.mts → event-log-store-BzXehP7R.d.cts} +28 -3
  11. package/dist/{event-log-store-s73r1Hxf.d.cts → event-log-store-CWjN6lmM.d.mts} +28 -3
  12. package/dist/{event-log-store-DKyE7JKr.cjs → event-log-store-CleWpsp5.cjs} +1 -1
  13. package/dist/{event-log-store-BGehvVTb.mjs → event-log-store-W49TCJXi.mjs} +1 -1
  14. package/dist/index.cjs +5 -5
  15. package/dist/index.d.cts +7 -7
  16. package/dist/index.d.mts +7 -7
  17. package/dist/index.mjs +5 -5
  18. package/dist/log.cjs +2 -2
  19. package/dist/log.d.cts +1 -1
  20. package/dist/log.d.mts +1 -1
  21. package/dist/log.mjs +2 -2
  22. package/dist/machines.cjs +1 -1
  23. package/dist/machines.mjs +1 -1
  24. package/dist/{model-source-BilDEyqk.mjs → model-source-CK3F4YuU.mjs} +1 -1
  25. package/dist/{model-source-BQ97_l1-.cjs → model-source-DmhTMK39.cjs} +1 -1
  26. package/dist/openai.cjs +377 -95
  27. package/dist/openai.d.cts +55 -20
  28. package/dist/openai.d.mts +55 -20
  29. package/dist/openai.mjs +375 -96
  30. package/dist/otel.d.cts +1 -1
  31. package/dist/otel.d.mts +1 -1
  32. package/dist/{run-agent-B5QhabdY.d.cts → run-agent-B1-Eqviq.d.cts} +13 -5
  33. package/dist/{run-agent-Atu-wEk7.d.mts → run-agent-BGdx5913.d.mts} +13 -5
  34. package/dist/{run-agent-2UnSUhDb.mjs → run-agent-Ct_GZw_f.mjs} +124 -38
  35. package/dist/{run-agent-Cg0xd3K-.cjs → run-agent-s5D32w99.cjs} +123 -37
  36. package/dist/{setup-agent-CmhB-U5P.mjs → setup-agent-05uw4dPZ.mjs} +2 -2
  37. package/dist/{setup-agent-BiF1N3td.d.cts → setup-agent-BtfeFfF6.d.cts} +2 -2
  38. package/dist/{setup-agent-J9f_Wu5T.d.mts → setup-agent-C6nqzv_X.d.mts} +2 -2
  39. package/dist/{setup-agent-CwUJyqKB.cjs → setup-agent-CXEBURdo.cjs} +2 -2
  40. package/dist/tanstack-ai.cjs +91 -59
  41. package/dist/tanstack-ai.d.cts +13 -2
  42. package/dist/tanstack-ai.d.mts +13 -2
  43. package/dist/tanstack-ai.mjs +91 -59
  44. package/dist/testing.cjs +629 -13
  45. package/dist/testing.d.cts +278 -6
  46. package/dist/testing.d.mts +278 -6
  47. package/dist/testing.mjs +626 -14
  48. package/dist/{text-logic-CYP502VT.d.cts → text-logic-CV_4KGr6.d.cts} +28 -3
  49. package/dist/{text-logic-DuK9HIFM.d.mts → text-logic-Ckh-rJFV.d.mts} +28 -3
  50. package/dist/{usage-D7JKAxLc.d.mts → usage-BDiJKyv9.d.cts} +11 -1
  51. package/dist/{usage-DVw-646x.d.cts → usage-DOoVUGVq.d.mts} +11 -1
  52. package/dist/validate.cjs +3 -3
  53. package/dist/validate.d.cts +2 -2
  54. package/dist/validate.d.mts +2 -2
  55. package/dist/validate.mjs +3 -3
  56. package/dist/{verify-Dk3Vwnha.d.cts → verify-BQpE8hUz.d.cts} +1 -1
  57. package/dist/{verify-DgB8P-Wx.mjs → verify-Bpahmr34.mjs} +2 -2
  58. package/dist/{verify-BVz4cURF.d.mts → verify-CqeuEmIk.d.mts} +1 -1
  59. package/dist/{verify-CS_WLRXn.cjs → verify-DCLZa9R0.cjs} +2 -2
  60. package/dist/with-model-calls-BXYdBdcu.cjs +45 -0
  61. package/dist/with-model-calls-Bv4V4EHC.mjs +34 -0
  62. package/package.json +5 -5
  63. package/readme.md +14 -13
  64. package/skills/loop-to-machine/SKILL.md +42 -2
package/dist/testing.mjs CHANGED
@@ -1,13 +1,14 @@
1
- import { $ as getStateMeta, F as normalizeGeneratorResult, N as getCallUsage, lt as isRecord, ut as AgentError } from "./event-log-DAqsalT1.mjs";
2
- import { p as runToQuiescence, s as createAgentRuntime } from "./run-agent-2UnSUhDb.mjs";
3
- import { a as explorePaths, c as simulateAgent, i as canReach, n as AgentUnknownStateError, o as isExplorationComplete, r as assertAgentMachine, s as lintAgentMachine, t as AgentLintError } from "./verify-DgB8P-Wx.mjs";
1
+ import { F as getCallUsage, L as normalizeGeneratorResult, d as canonicalEventJson, dt as isPlainObject, ft as isRecord, pt as AgentError, tt as getStateMeta, ut as isError } from "./event-log-C7jeH0y8.mjs";
2
+ import { p as runToQuiescence, s as createAgentRuntime } from "./run-agent-Ct_GZw_f.mjs";
3
+ import { a as explorePaths, c as simulateAgent, i as canReach, n as AgentUnknownStateError, o as isExplorationComplete, r as assertAgentMachine, s as lintAgentMachine, t as AgentLintError } from "./verify-Bpahmr34.mjs";
4
+ import { getInitialMicrosteps, getMicrosteps } from "xstate";
4
5
  //#region src/trajectory.ts
5
6
  /**
6
7
  * Classifies one item. Event-shaped things (log entries, events) become events;
7
8
  * everything else is a state value. A snapshot is unwrapped to its `value`.
8
9
  * @internal
9
10
  */
10
- function normalize(item) {
11
+ function normalize$1(item) {
11
12
  if (isRecord(item)) {
12
13
  const nested = item["event"];
13
14
  if (isRecord(nested) && typeof nested["type"] === "string") return {
@@ -60,17 +61,17 @@ function deepEqual(a, b) {
60
61
  */
61
62
  function matcherFor(expected) {
62
63
  if (typeof expected === "string") return (actual) => {
63
- const actualItem = normalize(actual);
64
+ const actualItem = normalize$1(actual);
64
65
  return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
65
66
  };
66
- const expectedItem = normalize(expected);
67
+ const expectedItem = normalize$1(expected);
67
68
  switch (expectedItem.kind) {
68
69
  case "event": return (actual) => {
69
- const actualItem = normalize(actual);
70
+ const actualItem = normalize$1(actual);
70
71
  return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
71
72
  };
72
73
  case "state": return (actual) => {
73
- const actualItem = normalize(actual);
74
+ const actualItem = normalize$1(actual);
74
75
  return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
75
76
  };
76
77
  }
@@ -383,7 +384,7 @@ function statePaths(value, prefix = "") {
383
384
  /**
384
385
  * A trace's `machine.transition` events as steps, skipping `@xstate.init`.
385
386
  * A first-attempt decision's `request.start` names the decision on the step
386
- * that follows it. Reads live and serialized traces alike.
387
+ * that follows it, skipping `@agent.usage` steps. Reads live and serialized traces alike.
387
388
  * @internal
388
389
  */
389
390
  function traceSteps(trace) {
@@ -408,9 +409,9 @@ function traceSteps(trace) {
408
409
  to: statePaths(toValue),
409
410
  toValue,
410
411
  ignored: event.ignored === true,
411
- ...decision === void 0 ? {} : { decision }
412
+ ...decision === void 0 || type === "@agent.usage" ? {} : { decision }
412
413
  });
413
- decision = void 0;
414
+ if (type !== "@agent.usage") decision = void 0;
414
415
  }
415
416
  return steps;
416
417
  }
@@ -520,6 +521,37 @@ function candidateAt(node, type, event) {
520
521
  return keys.find((key) => node.transitions.get(key).some((d) => matchesPattern(d, event)));
521
522
  }
522
523
  const pathOf = (node) => node.path.join(".");
524
+ const sameLeaves = (a, b) => statePaths(a).sort().join("|") === statePaths(b).sort().join("|");
525
+ /**
526
+ * The leaves a trace passed through inside its macrosteps: states an `always`
527
+ * transition left before the step ended, which no traced snapshot holds.
528
+ * Re-derived with XState's pure `getMicrosteps` from the snapshot before each
529
+ * step (the previous step's, or the fresh start's microsteps from its input).
530
+ * A step that cannot be recomputed, or whose recomputation ends elsewhere
531
+ * than the traced snapshot, adds none. Only `value` and `context` are rebuilt,
532
+ * so a guard that reads live children can take another route to the same
533
+ * leaves, and that route is credited.
534
+ */
535
+ function passedThrough(machine, trace) {
536
+ const leaves = /* @__PURE__ */ new Set();
537
+ let resumed = false;
538
+ let previous;
539
+ for (const event of trace) {
540
+ if (event.type === "run.start") resumed = event.snapshot !== void 0;
541
+ if (event.type !== "machine.transition" || !isRecord(event.event)) continue;
542
+ const snapshot = isRecord(event.snapshot) ? event.snapshot : void 0;
543
+ try {
544
+ const microsteps = event.event.type === "@xstate.init" ? resumed ? [] : getInitialMicrosteps(machine, event.event.input) : previous && sameLeaves(previous.value, valueOf(event.from)) ? getMicrosteps(machine, machine.resolveState({
545
+ value: previous.value,
546
+ context: previous.context
547
+ }), event.event) : [];
548
+ const last = microsteps.at(-1)?.[0];
549
+ if (last && snapshot && sameLeaves(last.value, snapshot.value)) for (const [step] of microsteps) for (const leaf of statePaths(step.value)) leaves.add(leaf);
550
+ } catch {}
551
+ previous = snapshot;
552
+ }
553
+ return leaves;
554
+ }
523
555
  const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
524
556
  /**
525
557
  * Measures how much of a machine a set of runs exercised: which atomic and
@@ -537,7 +569,8 @@ const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
537
569
  * bare type (`xstate.done.actor`), one per state however many invokes; a
538
570
  * definition's `matches` (an invoke's `actorId`) must accept the traced event
539
571
  * for its state to be credited. Ignored steps credit no handler. `always`
540
- * handlers are listed as `unobservable`, never as unvisited.
572
+ * handlers are listed as `unobservable`, never as unvisited; a state one
573
+ * passes through is visited, re-derived from each step's microsteps.
541
574
  *
542
575
  * @example
543
576
  * ```ts no-check
@@ -593,6 +626,7 @@ function traceCoverage(machine, traces, options = {}) {
593
626
  if (event.event.type !== "@xstate.init" || !isRecord(event.snapshot)) continue;
594
627
  for (const leaf of statePaths(event.snapshot.value)) visited.add(leaf);
595
628
  }
629
+ if (unobservable.length > 0) for (const leaf of passedThrough(machine, trace)) visited.add(leaf);
596
630
  const credited = /* @__PURE__ */ new Set();
597
631
  for (const step of steps) {
598
632
  for (const leaf of step.to) visited.add(leaf);
@@ -654,6 +688,35 @@ function traceCoverage(machine, traces, options = {}) {
654
688
  //#endregion
655
689
  //#region src/first-divergence.ts
656
690
  const defaultKey = (step) => `${step.from.join(",")}|${step.event}|${step.to.join(",")}`;
691
+ const isErrorLike = (value) => isError(value) || isRecord(value) && typeof value.name === "string" && typeof value.message === "string";
692
+ const normalizeErrors = (value, seen = /* @__PURE__ */ new WeakSet()) => {
693
+ if (value === null || typeof value !== "object") return value;
694
+ if (seen.has(value)) return "[circular]";
695
+ seen.add(value);
696
+ try {
697
+ if (isErrorLike(value) && (isError(value) || "stack" in value || "code" in value)) {
698
+ const { name, message, code, cause } = value;
699
+ return {
700
+ name,
701
+ message,
702
+ ...typeof code === "string" ? { code } : {},
703
+ ...cause !== void 0 ? { cause: normalizeErrors(cause, seen) } : {}
704
+ };
705
+ }
706
+ if (Array.isArray(value)) return value.map((item) => normalizeErrors(item, seen));
707
+ if (!isPlainObject(value)) return value;
708
+ const copy = Object.create(null);
709
+ for (const key of Object.keys(value)) copy[key] = normalizeErrors(value[key], seen);
710
+ return copy;
711
+ } finally {
712
+ seen.delete(value);
713
+ }
714
+ };
715
+ const payloadKey = (step) => {
716
+ if (!isRecord(step.payload)) return `${defaultKey(step)}|${canonicalEventJson(step.payload)}`;
717
+ const { sessionId: _sessionId, ...payload } = step.payload;
718
+ return `${defaultKey(step)}|${canonicalEventJson(normalizeErrors(payload))}`;
719
+ };
657
720
  const isTrace = (items) => items.length === 0 || items.some((item) => isRecord(item) && (item.type === "machine.transition" || item.type === "run.start" || item.type === "run.end"));
658
721
  /**
659
722
  * Finds the first step where a run departs from a reference, so a failure is
@@ -684,7 +747,7 @@ const isTrace = (items) => items.length === 0 || items.some((item) => isRecord(i
684
747
  */
685
748
  function firstDivergence(actual, reference, options = {}) {
686
749
  const steps = traceSteps(actual).filter((step) => !step.ignored);
687
- return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
750
+ return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key === "payload" ? payloadKey : options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
688
751
  }
689
752
  function diverged(steps, index, expected, initial = steps[0]?.fromValue) {
690
753
  const step = steps[index];
@@ -1070,4 +1133,553 @@ function structurallyEqual(a, b) {
1070
1133
  return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && structurallyEqual(a[key], b[key]));
1071
1134
  }
1072
1135
  //#endregion
1073
- export { AgentLintError, AgentUnknownStateError, assertAgentMachine, canReach, compareRuns, explorePaths, firstDivergence, foldTraces, getDecisionRequests, judgeAgreement, lintAgentMachine, matchesTrajectory, repeatRuns, runSeam, simulateAgent, summarizeRepeats, traceCoverage };
1136
+ //#region src/equivalence.ts
1137
+ /**
1138
+ * Thrown in replay when the port asks for something the recording cannot
1139
+ * answer: a model call past the last recorded one, or a tool call the original
1140
+ * never made. The effect is still recorded, so {@link compareRecordings}
1141
+ * reports it.
1142
+ */
1143
+ var RecordingDivergenceError = class extends Error {
1144
+ name = "RecordingDivergenceError";
1145
+ };
1146
+ function toRecordedError(error) {
1147
+ if (!(error instanceof Error)) return {
1148
+ name: "Error",
1149
+ message: String(error)
1150
+ };
1151
+ const recorded = {
1152
+ name: error.name,
1153
+ message: error.message
1154
+ };
1155
+ const code = error.code;
1156
+ if (code !== void 0) recorded.code = toJson(code);
1157
+ const data = Object.fromEntries(Object.entries(error).filter(([key, value]) => key !== "code" && (typeof value === "number" || typeof value === "boolean")));
1158
+ if (Object.keys(data).length) recorded.data = data;
1159
+ const markers = /* @__PURE__ */ new Set();
1160
+ for (let holder = error; holder; holder = Object.getPrototypeOf(holder)) for (const symbol of Object.getOwnPropertySymbols(holder)) {
1161
+ const key = Symbol.keyFor(symbol);
1162
+ if (key !== void 0 && error[symbol] === true) markers.add(key);
1163
+ }
1164
+ if (markers.size) recorded.markers = [...markers];
1165
+ return recorded;
1166
+ }
1167
+ function fromRecordedError({ data, markers, ...fields }) {
1168
+ const error = Object.assign(new Error(fields.message), fields, data);
1169
+ for (const marker of markers ?? []) error[Symbol.for(marker)] = true;
1170
+ return error;
1171
+ }
1172
+ /** What two runs compare of an error: its data and markers may differ. */
1173
+ function errorIdentity(error) {
1174
+ return error && {
1175
+ name: error.name,
1176
+ message: error.message,
1177
+ code: error.code
1178
+ };
1179
+ }
1180
+ /** A JSON-safe copy: Dates become ISO strings, Errors become {@link RecordedError}. */
1181
+ function toJson(value) {
1182
+ if (value === void 0) return void 0;
1183
+ return JSON.parse(JSON.stringify(value, function(key, item) {
1184
+ const raw = this[key];
1185
+ if (raw instanceof Date) return raw.toISOString();
1186
+ if (item instanceof Error) return toRecordedError(item);
1187
+ if (typeof item === "bigint") return item.toString();
1188
+ if (item instanceof Uint8Array) return Array.from(item);
1189
+ return item;
1190
+ }));
1191
+ }
1192
+ /** Restores the `Date` timestamps the AI SDK puts on responses. */
1193
+ function reviveTimestamps(value) {
1194
+ if (value && typeof value === "object") {
1195
+ for (const holder of [value, value.response]) if (holder && typeof holder["timestamp"] === "string") holder["timestamp"] = new Date(holder["timestamp"]);
1196
+ }
1197
+ return value;
1198
+ }
1199
+ function omit(value, keys) {
1200
+ if (!value || typeof value !== "object") return value;
1201
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
1202
+ }
1203
+ /** Key-order-independent JSON, for equality. */
1204
+ function stableStringify(value) {
1205
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1206
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
1207
+ return JSON.stringify(value) ?? "undefined";
1208
+ }
1209
+ function jsonEqual(a, b) {
1210
+ return stableStringify(toJson(a)) === stableStringify(toJson(b));
1211
+ }
1212
+ function streamFrom(parts) {
1213
+ return new ReadableStream({ start(controller) {
1214
+ for (const part of parts) controller.enqueue(reviveTimestamps(structuredClone(part)));
1215
+ controller.close();
1216
+ } });
1217
+ }
1218
+ async function* iterate(chunks) {
1219
+ for (const chunk of chunks) yield structuredClone(chunk);
1220
+ }
1221
+ /**
1222
+ * Creates a {@link Recorder}. With no options it records: every wrapped call
1223
+ * runs for real. With `replay` it answers from a recording instead.
1224
+ */
1225
+ function createRecorder(options = {}) {
1226
+ const effects = [];
1227
+ const replay = options.replay?.effects;
1228
+ const replayedModels = replay?.filter((effect) => effect.kind === "model");
1229
+ const usedModels = /* @__PURE__ */ new Set();
1230
+ const usedTools = /* @__PURE__ */ new Set();
1231
+ const normalizeEffect = (effect, list) => options.normalize?.(effect, list.indexOf(effect), list) ?? effect;
1232
+ let modelCalls = 0;
1233
+ let toolsInFlight = 0;
1234
+ /**
1235
+ * The earliest unused recorded call that fits this one: one `translate`
1236
+ * adapts, or one with the same method and shape. Not by position, so a call
1237
+ * the port added or dropped does not shift every answer after it.
1238
+ */
1239
+ function nextReplayedModel(effect) {
1240
+ for (const recorded of replayedModels) {
1241
+ if (usedModels.has(recorded)) continue;
1242
+ const translated = options.translate?.(structuredClone(recorded), effect);
1243
+ if (translated) {
1244
+ effect.translated = true;
1245
+ return {
1246
+ recorded,
1247
+ answer: translated
1248
+ };
1249
+ }
1250
+ if (recorded.method === effect.method && modelCallsMatch(options.modelCalls, recorded, effect)) return {
1251
+ recorded,
1252
+ answer: recorded
1253
+ };
1254
+ }
1255
+ }
1256
+ function noAnswerMessage(effect) {
1257
+ const unused = replayedModels.filter((recorded) => !usedModels.has(recorded));
1258
+ 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}).`;
1259
+ }
1260
+ /**
1261
+ * Records a model call around `run`, or answers it from the recording.
1262
+ * `fallback` runs it on the stand-in when the recording has no answer.
1263
+ */
1264
+ async function modelCall(seam, method, request, streamed, run, fallback) {
1265
+ const effect = {
1266
+ kind: "model",
1267
+ seam,
1268
+ method,
1269
+ call: modelCalls++,
1270
+ request: toJson(omit(request, [
1271
+ "abortSignal",
1272
+ "headers",
1273
+ "signal"
1274
+ ]))
1275
+ };
1276
+ effects.push(effect);
1277
+ if (replay) {
1278
+ const replayed = nextReplayedModel(effect);
1279
+ if (replayed) {
1280
+ const { recorded, answer } = replayed;
1281
+ usedModels.add(recorded);
1282
+ effect.replayed = recorded.call;
1283
+ if (answer.error) {
1284
+ effect.error = answer.error;
1285
+ throw fromRecordedError(answer.error);
1286
+ }
1287
+ effect.response = answer.response;
1288
+ effect.stream = answer.stream;
1289
+ if (seam === "openai") return streamed ? iterate(answer.stream ?? []) : structuredClone(answer.response);
1290
+ return streamed ? {
1291
+ ...reviveTimestamps(structuredClone(answer.response) ?? {}),
1292
+ stream: streamFrom(answer.stream ?? [])
1293
+ } : reviveTimestamps(structuredClone(answer.response));
1294
+ }
1295
+ if (!fallback) {
1296
+ const error = new RecordingDivergenceError(noAnswerMessage(effect));
1297
+ effect.error = toRecordedError(error);
1298
+ throw error;
1299
+ }
1300
+ effect.unrecorded = true;
1301
+ run = fallback;
1302
+ }
1303
+ let result;
1304
+ try {
1305
+ result = await run();
1306
+ } catch (error) {
1307
+ effect.error = toRecordedError(error);
1308
+ throw error;
1309
+ }
1310
+ if (!streamed) {
1311
+ effect.response = toJson(result);
1312
+ return result;
1313
+ }
1314
+ const parts = [];
1315
+ effect.stream = parts;
1316
+ if (seam === "openai") {
1317
+ const source = result;
1318
+ return (async function* () {
1319
+ for await (const chunk of source) {
1320
+ parts.push(toJson(chunk));
1321
+ yield chunk;
1322
+ }
1323
+ })();
1324
+ }
1325
+ const { stream, ...rest } = result;
1326
+ effect.response = toJson(rest);
1327
+ return {
1328
+ ...rest,
1329
+ stream: stream.pipeThrough(new TransformStream({ transform(part, controller) {
1330
+ parts.push(toJson(part));
1331
+ controller.enqueue(part);
1332
+ } }))
1333
+ };
1334
+ }
1335
+ /** `inputOf` picks the recorded input from the call's arguments. */
1336
+ function tool(name, fn, inputOf = (args) => args.length === 1 ? args[0] : args) {
1337
+ return ((...args) => {
1338
+ const input = toJson(inputOf(args));
1339
+ const effect = {
1340
+ kind: "tool",
1341
+ name,
1342
+ step: modelCalls,
1343
+ input,
1344
+ ...toolsInFlight > 0 ? { concurrent: true } : {}
1345
+ };
1346
+ effects.push(effect);
1347
+ return track(call(effect, args));
1348
+ });
1349
+ function call(effect, args) {
1350
+ const { input } = effect;
1351
+ if (replay && options.tools !== "live") {
1352
+ const wanted = normalizeEffect(effect, effects).input;
1353
+ const matches = (candidate) => candidate.kind === "tool" && !usedTools.has(candidate) && candidate.name === name && jsonEqual(normalizeEffect(candidate, replay).input, wanted);
1354
+ const recorded = replay.find(matches);
1355
+ if (!recorded && options.fallback?.tools) {
1356
+ effect.unrecorded = true;
1357
+ return runLive(effect, args);
1358
+ }
1359
+ const settle = (value) => {
1360
+ if (recorded?.sync) return value();
1361
+ try {
1362
+ return Promise.resolve(value());
1363
+ } catch (error) {
1364
+ return Promise.reject(error);
1365
+ }
1366
+ };
1367
+ return settle(() => {
1368
+ if (!recorded) {
1369
+ const error = new RecordingDivergenceError(`Tool '${name}' was called with ${JSON.stringify(input)}; the recorded run made no such call.`);
1370
+ effect.error = toRecordedError(error);
1371
+ throw error;
1372
+ }
1373
+ usedTools.add(recorded);
1374
+ if (recorded.sync) effect.sync = true;
1375
+ if (recorded.error) {
1376
+ effect.error = recorded.error;
1377
+ throw fromRecordedError(recorded.error);
1378
+ }
1379
+ effect.output = recorded.output;
1380
+ return structuredClone(recorded.output);
1381
+ });
1382
+ }
1383
+ return runLive(effect, args);
1384
+ }
1385
+ function runLive(effect, args) {
1386
+ let output;
1387
+ try {
1388
+ output = fn(...args);
1389
+ } catch (error) {
1390
+ effect.sync = true;
1391
+ effect.error = toRecordedError(error);
1392
+ throw error;
1393
+ }
1394
+ if (!(output instanceof Promise)) {
1395
+ effect.sync = true;
1396
+ effect.output = toJson(output);
1397
+ return output;
1398
+ }
1399
+ return output.then((value) => {
1400
+ effect.output = toJson(value);
1401
+ return value;
1402
+ }, (error) => {
1403
+ effect.error = toRecordedError(error);
1404
+ throw error;
1405
+ });
1406
+ }
1407
+ }
1408
+ /** Counts an async tool call as running until it settles. */
1409
+ function track(result) {
1410
+ if (result instanceof Promise) {
1411
+ toolsInFlight++;
1412
+ const settled = () => {
1413
+ toolsInFlight--;
1414
+ };
1415
+ result.then(settled, settled);
1416
+ }
1417
+ return result;
1418
+ }
1419
+ return {
1420
+ model(model) {
1421
+ const base = model;
1422
+ const stand = options.fallback?.model;
1423
+ const wrapped = Object.create(base);
1424
+ for (const method of [
1425
+ "doGenerate",
1426
+ "doStream",
1427
+ "doDecide",
1428
+ "doEvaluate"
1429
+ ]) {
1430
+ if (typeof base[method] !== "function") continue;
1431
+ const invoke = (target, callOptions) => target[method].call(target, callOptions);
1432
+ wrapped[method] = (callOptions) => modelCall("ai-sdk", method, callOptions, method === "doStream", () => invoke(base, callOptions), stand && typeof stand[method] === "function" ? () => invoke(stand, callOptions) : void 0);
1433
+ }
1434
+ return wrapped;
1435
+ },
1436
+ openai(client) {
1437
+ const wrapCreate = (resource, method) => new Proxy(resource, { get(target, key, receiver) {
1438
+ if (key !== "create") return Reflect.get(target, key, receiver);
1439
+ return (params, requestOptions) => {
1440
+ let api;
1441
+ const create = (resource) => () => {
1442
+ api = Reflect.get(resource, "create").call(resource, params, requestOptions);
1443
+ return Promise.resolve(api);
1444
+ };
1445
+ const stand = fallbackResource(method);
1446
+ const promise = modelCall("openai", method, params, params?.stream === true, create(target), stand && create(stand));
1447
+ return Object.assign(promise, { withResponse: async () => {
1448
+ const data = await promise;
1449
+ const meta = await api?.withResponse?.();
1450
+ return {
1451
+ data,
1452
+ response: meta?.response ?? new Response(null),
1453
+ request_id: meta?.request_id ?? null
1454
+ };
1455
+ } });
1456
+ };
1457
+ } });
1458
+ const fallbackResource = (method) => {
1459
+ let value = options.fallback?.openai;
1460
+ for (const key of method.split(".").slice(0, -1)) value = value?.[key];
1461
+ return value && typeof value === "object" ? value : void 0;
1462
+ };
1463
+ const wrapped = /* @__PURE__ */ new Map();
1464
+ const wrap = (key, make) => {
1465
+ if (!wrapped.has(key)) wrapped.set(key, make());
1466
+ return wrapped.get(key);
1467
+ };
1468
+ return new Proxy(client, { get(target, key, receiver) {
1469
+ const value = Reflect.get(target, key, receiver);
1470
+ if (key === "responses" && value) return wrap(key, () => wrapCreate(value, "responses.create"));
1471
+ if (key === "chat" && value) return wrap(key, () => new Proxy(value, { get(chat, chatKey, chatReceiver) {
1472
+ const inner = Reflect.get(chat, chatKey, chatReceiver);
1473
+ return chatKey === "completions" && inner ? wrap("chat.completions", () => wrapCreate(inner, "chat.completions.create")) : inner;
1474
+ } }));
1475
+ return value;
1476
+ } });
1477
+ },
1478
+ tool: (name, fn) => tool(name, fn),
1479
+ tools(tools) {
1480
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => [name, definition.execute ? {
1481
+ ...definition,
1482
+ execute: tool(name, definition.execute, (args) => args[0])
1483
+ } : definition]));
1484
+ },
1485
+ output(value) {
1486
+ effects.push({
1487
+ kind: "output",
1488
+ value: toJson(value)
1489
+ });
1490
+ },
1491
+ get recording() {
1492
+ return {
1493
+ version: 1,
1494
+ effects: toJson(effects)
1495
+ };
1496
+ }
1497
+ };
1498
+ }
1499
+ /** True when two model calls offer the same tool names and response format. */
1500
+ function sameModelCallShape(expected, actual) {
1501
+ return jsonEqual(modelCallShape(expected), modelCallShape(actual));
1502
+ }
1503
+ function modelCallsMatch(match, expected, actual) {
1504
+ if (match === "none") return true;
1505
+ if (typeof match === "function") return match(expected, actual);
1506
+ return sameModelCallShape(expected, actual);
1507
+ }
1508
+ function shapeMessage(expected, actual) {
1509
+ 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.`;
1510
+ }
1511
+ /**
1512
+ * Offered tool names and the response format, or a decision's questions and
1513
+ * their options: what a recorded answer depends on.
1514
+ */
1515
+ function modelCallShape(effect) {
1516
+ const request = effect.request ?? {};
1517
+ const questions = request["questions"];
1518
+ if (questions && typeof questions === "object") return { questions: Object.entries(questions).map(([name, question]) => {
1519
+ const criteria = question["criteria"];
1520
+ if (question["type"] === "choice" && criteria && typeof criteria === "object") return [
1521
+ name,
1522
+ question["type"],
1523
+ Object.keys(criteria).sort()
1524
+ ];
1525
+ if (question["type"] === "score" && Array.isArray(criteria)) return [
1526
+ name,
1527
+ question["type"],
1528
+ criteria.length
1529
+ ];
1530
+ return [name, question["type"]];
1531
+ }).sort((x, y) => String(x[0]).localeCompare(String(y[0]))) };
1532
+ return {
1533
+ tools: (Array.isArray(request["tools"]) ? request["tools"] : []).map((tool) => tool["name"] ?? tool["function"]?.["name"]).sort(),
1534
+ format: request["responseFormat"]?.["type"] ?? request["response_format"]?.["type"] ?? (request["text"]?.["format"])?.["type"] ?? "text"
1535
+ };
1536
+ }
1537
+ /**
1538
+ * Puts each group of concurrent tool calls in a stable order, so parallel tool
1539
+ * calls that finished in a different order still compare equal. A tool call
1540
+ * that started after the previous one settled begins a new group, so
1541
+ * sequential calls keep their order.
1542
+ */
1543
+ function normalize(effects) {
1544
+ const result = [];
1545
+ let batch = [];
1546
+ const flush = () => {
1547
+ result.push(...batch.sort((a, b) => stableStringify([a.name, a.input]).localeCompare(stableStringify([b.name, b.input]))));
1548
+ batch = [];
1549
+ };
1550
+ for (const effect of effects) {
1551
+ if (effect.kind !== "tool" || !effect.concurrent) flush();
1552
+ if (effect.kind === "tool") batch.push(effect);
1553
+ else result.push(effect);
1554
+ }
1555
+ flush();
1556
+ return result;
1557
+ }
1558
+ function describe(effect) {
1559
+ switch (effect.kind) {
1560
+ case "model": return `model call #${effect.call} (${effect.method})`;
1561
+ case "tool": return `tool '${effect.name}' with ${JSON.stringify(effect.input)}`;
1562
+ case "output": return `output ${JSON.stringify(effect.value)}`;
1563
+ }
1564
+ }
1565
+ /** Why two effects differ, or `undefined` when they are the same. */
1566
+ function differ(left, right, options) {
1567
+ if (left.kind !== right.kind) return {
1568
+ reason: "kind",
1569
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1570
+ };
1571
+ if (left.kind === "model" && right.kind === "model") {
1572
+ if (right.translated && right.replayed === left.call) return void 0;
1573
+ if (left.method !== right.method) return {
1574
+ reason: "model-method",
1575
+ message: `Model call #${left.call} used ${left.method}; the port used ${right.method}.`
1576
+ };
1577
+ if (!modelCallsMatch(options.modelCalls, left, right)) return {
1578
+ reason: "model-call-shape",
1579
+ message: shapeMessage(left, right)
1580
+ };
1581
+ if (!jsonEqual(errorIdentity(left.error), errorIdentity(right.error))) {
1582
+ const outcome = (error) => error ? `failed with ${error.name}: ${error.message}` : "succeeded";
1583
+ return {
1584
+ reason: "model-error",
1585
+ message: `Model call #${left.call} ${outcome(left.error)}; in the port it ${outcome(right.error)}.`
1586
+ };
1587
+ }
1588
+ return;
1589
+ }
1590
+ if (left.kind === "tool" && right.kind === "tool") {
1591
+ if (left.name !== right.name) return {
1592
+ reason: "tool-name",
1593
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1594
+ };
1595
+ if (!jsonEqual(left.input, right.input)) return {
1596
+ reason: "tool-input",
1597
+ message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.input)}.`
1598
+ };
1599
+ if (!jsonEqual(left.output, right.output) || !jsonEqual(errorIdentity(left.error), errorIdentity(right.error))) return {
1600
+ reason: "tool-result",
1601
+ message: `Tool '${left.name}' returned a different result.`
1602
+ };
1603
+ return;
1604
+ }
1605
+ if (left.kind === "output" && right.kind === "output" && !jsonEqual(left.value, right.value)) return {
1606
+ reason: "output",
1607
+ message: `Expected ${describe(left)}; the port returned ${JSON.stringify(right.value)}.`
1608
+ };
1609
+ }
1610
+ /**
1611
+ * Compares two recordings and reports every effect that differs. `expected`
1612
+ * is the original's recording, `actual` the port's. Effects that are the same
1613
+ * on both sides are lined up first (longest common subsequence), so one extra
1614
+ * call does not shift every effect after it; between them, effects of the same
1615
+ * kind pair up and report what changed, and the rest are missing or extra.
1616
+ */
1617
+ function compareRecordings(expected, actual, options = {}) {
1618
+ const select = (effects) => normalize(effects.flatMap((effect, index) => {
1619
+ if (options.kinds && !options.kinds.includes(effect.kind)) return [];
1620
+ const mapped = options.normalize ? options.normalize(effect, index, effects) : effect;
1621
+ return mapped ? [mapped] : [];
1622
+ }));
1623
+ const a = select(expected.effects);
1624
+ const b = select(actual.effects);
1625
+ const same = a.map((left) => b.map((right) => !differ(left, right, options)));
1626
+ const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }, () => 0));
1627
+ 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]);
1628
+ const divergences = [];
1629
+ let lefts = [];
1630
+ let rights = [];
1631
+ const flushGap = (at) => {
1632
+ const unpairedRights = [...rights];
1633
+ const changed = [];
1634
+ for (const index of lefts) {
1635
+ const left = a[index];
1636
+ const k = unpairedRights.findIndex((j) => b[j].kind === left.kind);
1637
+ if (k === -1) {
1638
+ changed.push({
1639
+ index,
1640
+ reason: "missing-effect",
1641
+ expected: left,
1642
+ message: `The port never made ${describe(left)}.`
1643
+ });
1644
+ continue;
1645
+ }
1646
+ const right = b[unpairedRights.splice(k, 1)[0]];
1647
+ const difference = differ(left, right, options);
1648
+ if (difference) changed.push({
1649
+ index,
1650
+ expected: left,
1651
+ actual: right,
1652
+ ...difference
1653
+ });
1654
+ }
1655
+ for (const j of unpairedRights) divergences.push({
1656
+ index: lefts[0] ?? at,
1657
+ reason: "extra-effect",
1658
+ actual: b[j],
1659
+ message: `The port made ${describe(b[j])}, which the original never made.`
1660
+ });
1661
+ divergences.push(...changed);
1662
+ lefts = [];
1663
+ rights = [];
1664
+ };
1665
+ let i = 0;
1666
+ let j = 0;
1667
+ while (i < a.length || j < b.length) if (i < a.length && j < b.length && same[i][j]) {
1668
+ flushGap(i);
1669
+ i++;
1670
+ j++;
1671
+ } else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) rights.push(j++);
1672
+ else lefts.push(i++);
1673
+ flushGap(i);
1674
+ divergences.sort((x, y) => x.index - y.index);
1675
+ return divergences.length ? {
1676
+ equivalent: false,
1677
+ divergence: divergences[0],
1678
+ divergences
1679
+ } : {
1680
+ equivalent: true,
1681
+ divergences
1682
+ };
1683
+ }
1684
+ //#endregion
1685
+ export { AgentLintError, AgentUnknownStateError, RecordingDivergenceError, assertAgentMachine, canReach, compareRecordings, compareRuns, createRecorder, explorePaths, firstDivergence, foldTraces, getDecisionRequests, judgeAgreement, lintAgentMachine, matchesTrajectory, repeatRuns, runSeam, sameModelCallShape, simulateAgent, summarizeRepeats, traceCoverage };