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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +32 -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 +539 -13
  45. package/dist/testing.d.cts +202 -6
  46. package/dist/testing.d.mts +202 -6
  47. package/dist/testing.mjs +536 -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 +40 -2
package/dist/testing.cjs CHANGED
@@ -1,14 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_log = require("./event-log-CKWeC7H-.cjs");
3
- const require_run_agent = require("./run-agent-Cg0xd3K-.cjs");
4
- const require_verify = require("./verify-CS_WLRXn.cjs");
2
+ const require_event_log = require("./event-log-BWSSLUff.cjs");
3
+ const require_run_agent = require("./run-agent-s5D32w99.cjs");
4
+ const require_verify = require("./verify-DCLZa9R0.cjs");
5
+ let xstate = require("xstate");
5
6
  //#region src/trajectory.ts
6
7
  /**
7
8
  * Classifies one item. Event-shaped things (log entries, events) become events;
8
9
  * everything else is a state value. A snapshot is unwrapped to its `value`.
9
10
  * @internal
10
11
  */
11
- function normalize(item) {
12
+ function normalize$1(item) {
12
13
  if (require_event_log.isRecord(item)) {
13
14
  const nested = item["event"];
14
15
  if (require_event_log.isRecord(nested) && typeof nested["type"] === "string") return {
@@ -61,17 +62,17 @@ function deepEqual(a, b) {
61
62
  */
62
63
  function matcherFor(expected) {
63
64
  if (typeof expected === "string") return (actual) => {
64
- const actualItem = normalize(actual);
65
+ const actualItem = normalize$1(actual);
65
66
  return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
66
67
  };
67
- const expectedItem = normalize(expected);
68
+ const expectedItem = normalize$1(expected);
68
69
  switch (expectedItem.kind) {
69
70
  case "event": return (actual) => {
70
- const actualItem = normalize(actual);
71
+ const actualItem = normalize$1(actual);
71
72
  return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
72
73
  };
73
74
  case "state": return (actual) => {
74
- const actualItem = normalize(actual);
75
+ const actualItem = normalize$1(actual);
75
76
  return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
76
77
  };
77
78
  }
@@ -384,7 +385,7 @@ function statePaths(value, prefix = "") {
384
385
  /**
385
386
  * A trace's `machine.transition` events as steps, skipping `@xstate.init`.
386
387
  * A first-attempt decision's `request.start` names the decision on the step
387
- * that follows it. Reads live and serialized traces alike.
388
+ * that follows it, skipping `@agent.usage` steps. Reads live and serialized traces alike.
388
389
  * @internal
389
390
  */
390
391
  function traceSteps(trace) {
@@ -409,9 +410,9 @@ function traceSteps(trace) {
409
410
  to: statePaths(toValue),
410
411
  toValue,
411
412
  ignored: event.ignored === true,
412
- ...decision === void 0 ? {} : { decision }
413
+ ...decision === void 0 || type === "@agent.usage" ? {} : { decision }
413
414
  });
414
- decision = void 0;
415
+ if (type !== "@agent.usage") decision = void 0;
415
416
  }
416
417
  return steps;
417
418
  }
@@ -521,6 +522,37 @@ function candidateAt(node, type, event) {
521
522
  return keys.find((key) => node.transitions.get(key).some((d) => matchesPattern(d, event)));
522
523
  }
523
524
  const pathOf = (node) => node.path.join(".");
525
+ const sameLeaves = (a, b) => statePaths(a).sort().join("|") === statePaths(b).sort().join("|");
526
+ /**
527
+ * The leaves a trace passed through inside its macrosteps: states an `always`
528
+ * transition left before the step ended, which no traced snapshot holds.
529
+ * Re-derived with XState's pure `getMicrosteps` from the snapshot before each
530
+ * step (the previous step's, or the fresh start's microsteps from its input).
531
+ * A step that cannot be recomputed, or whose recomputation ends elsewhere
532
+ * than the traced snapshot, adds none. Only `value` and `context` are rebuilt,
533
+ * so a guard that reads live children can take another route to the same
534
+ * leaves, and that route is credited.
535
+ */
536
+ function passedThrough(machine, trace) {
537
+ const leaves = /* @__PURE__ */ new Set();
538
+ let resumed = false;
539
+ let previous;
540
+ for (const event of trace) {
541
+ if (event.type === "run.start") resumed = event.snapshot !== void 0;
542
+ if (event.type !== "machine.transition" || !require_event_log.isRecord(event.event)) continue;
543
+ const snapshot = require_event_log.isRecord(event.snapshot) ? event.snapshot : void 0;
544
+ try {
545
+ const microsteps = event.event.type === "@xstate.init" ? resumed ? [] : (0, xstate.getInitialMicrosteps)(machine, event.event.input) : previous && sameLeaves(previous.value, valueOf(event.from)) ? (0, xstate.getMicrosteps)(machine, machine.resolveState({
546
+ value: previous.value,
547
+ context: previous.context
548
+ }), event.event) : [];
549
+ const last = microsteps.at(-1)?.[0];
550
+ if (last && snapshot && sameLeaves(last.value, snapshot.value)) for (const [step] of microsteps) for (const leaf of statePaths(step.value)) leaves.add(leaf);
551
+ } catch {}
552
+ previous = snapshot;
553
+ }
554
+ return leaves;
555
+ }
524
556
  const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
525
557
  /**
526
558
  * Measures how much of a machine a set of runs exercised: which atomic and
@@ -538,7 +570,8 @@ const ratioOf = (visited, total) => total === 0 ? 1 : visited / total;
538
570
  * bare type (`xstate.done.actor`), one per state however many invokes; a
539
571
  * definition's `matches` (an invoke's `actorId`) must accept the traced event
540
572
  * for its state to be credited. Ignored steps credit no handler. `always`
541
- * handlers are listed as `unobservable`, never as unvisited.
573
+ * handlers are listed as `unobservable`, never as unvisited; a state one
574
+ * passes through is visited, re-derived from each step's microsteps.
542
575
  *
543
576
  * @example
544
577
  * ```ts no-check
@@ -594,6 +627,7 @@ function traceCoverage(machine, traces, options = {}) {
594
627
  if (event.event.type !== "@xstate.init" || !require_event_log.isRecord(event.snapshot)) continue;
595
628
  for (const leaf of statePaths(event.snapshot.value)) visited.add(leaf);
596
629
  }
630
+ if (unobservable.length > 0) for (const leaf of passedThrough(machine, trace)) visited.add(leaf);
597
631
  const credited = /* @__PURE__ */ new Set();
598
632
  for (const step of steps) {
599
633
  for (const leaf of step.to) visited.add(leaf);
@@ -655,6 +689,35 @@ function traceCoverage(machine, traces, options = {}) {
655
689
  //#endregion
656
690
  //#region src/first-divergence.ts
657
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
+ };
658
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"));
659
722
  /**
660
723
  * Finds the first step where a run departs from a reference, so a failure is
@@ -685,7 +748,7 @@ const isTrace = (items) => items.length === 0 || items.some((item) => require_ev
685
748
  */
686
749
  function firstDivergence(actual, reference, options = {}) {
687
750
  const steps = traceSteps(actual).filter((step) => !step.ignored);
688
- return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
751
+ return isTrace(reference) ? againstTrace(steps, traceSteps(reference).filter((step) => !step.ignored), options.key === "payload" ? payloadKey : options.key ?? defaultKey) : againstTrajectory(actual, steps, reference);
689
752
  }
690
753
  function diverged(steps, index, expected, initial = steps[0]?.fromValue) {
691
754
  const step = steps[index];
@@ -1071,11 +1134,473 @@ function structurallyEqual(a, b) {
1071
1134
  return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && structurallyEqual(a[key], b[key]));
1072
1135
  }
1073
1136
  //#endregion
1137
+ //#region src/equivalence.ts
1138
+ /**
1139
+ * Thrown in replay when the port asks for something the recording cannot
1140
+ * answer: a model call past the last recorded one, or a tool call the original
1141
+ * never made. The effect is still recorded, so {@link compareRecordings}
1142
+ * reports it.
1143
+ */
1144
+ var RecordingDivergenceError = class extends Error {
1145
+ name = "RecordingDivergenceError";
1146
+ };
1147
+ function toRecordedError(error) {
1148
+ if (error instanceof Error) {
1149
+ const code = error.code;
1150
+ return code === void 0 ? {
1151
+ name: error.name,
1152
+ message: error.message
1153
+ } : {
1154
+ name: error.name,
1155
+ message: error.message,
1156
+ code: toJson(code)
1157
+ };
1158
+ }
1159
+ return {
1160
+ name: "Error",
1161
+ message: String(error)
1162
+ };
1163
+ }
1164
+ function fromRecordedError(error) {
1165
+ return Object.assign(new Error(error.message), error);
1166
+ }
1167
+ /** A JSON-safe copy: Dates become ISO strings, Errors become {@link RecordedError}. */
1168
+ function toJson(value) {
1169
+ if (value === void 0) return void 0;
1170
+ return JSON.parse(JSON.stringify(value, function(key, item) {
1171
+ const raw = this[key];
1172
+ if (raw instanceof Date) return raw.toISOString();
1173
+ if (item instanceof Error) return toRecordedError(item);
1174
+ if (typeof item === "bigint") return item.toString();
1175
+ if (item instanceof Uint8Array) return Array.from(item);
1176
+ return item;
1177
+ }));
1178
+ }
1179
+ /** Restores the `Date` timestamps the AI SDK puts on responses. */
1180
+ function reviveTimestamps(value) {
1181
+ if (value && typeof value === "object") {
1182
+ for (const holder of [value, value.response]) if (holder && typeof holder["timestamp"] === "string") holder["timestamp"] = new Date(holder["timestamp"]);
1183
+ }
1184
+ return value;
1185
+ }
1186
+ function omit(value, keys) {
1187
+ if (!value || typeof value !== "object") return value;
1188
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
1189
+ }
1190
+ /** Key-order-independent JSON, for equality. */
1191
+ function stableStringify(value) {
1192
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1193
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
1194
+ return JSON.stringify(value) ?? "undefined";
1195
+ }
1196
+ function jsonEqual(a, b) {
1197
+ return stableStringify(toJson(a)) === stableStringify(toJson(b));
1198
+ }
1199
+ function streamFrom(parts) {
1200
+ return new ReadableStream({ start(controller) {
1201
+ for (const part of parts) controller.enqueue(reviveTimestamps(structuredClone(part)));
1202
+ controller.close();
1203
+ } });
1204
+ }
1205
+ async function* iterate(chunks) {
1206
+ for (const chunk of chunks) yield structuredClone(chunk);
1207
+ }
1208
+ /**
1209
+ * Creates a {@link Recorder}. With no options it records: every wrapped call
1210
+ * runs for real. With `replay` it answers from a recording instead.
1211
+ */
1212
+ function createRecorder(options = {}) {
1213
+ const effects = [];
1214
+ const replay = options.replay?.effects;
1215
+ const replayedModels = replay?.filter((effect) => effect.kind === "model");
1216
+ const usedTools = /* @__PURE__ */ new Set();
1217
+ const normalizeEffect = options.normalize ?? ((effect) => effect);
1218
+ let modelCalls = 0;
1219
+ let toolsInFlight = 0;
1220
+ function nextReplayedModel(effect) {
1221
+ const recorded = replayedModels[effect.call];
1222
+ if (!recorded) throw new RecordingDivergenceError(`Model call #${effect.call} was never made by the recorded run (it made ${replayedModels.length}).`);
1223
+ if (recorded.method !== effect.method) throw new RecordingDivergenceError(`Model call #${effect.call} uses ${effect.method}; the recorded run used ${recorded.method}.`);
1224
+ if (!modelCallsMatch(options.modelCalls, recorded, effect)) throw new RecordingDivergenceError(shapeMessage(recorded, effect));
1225
+ return recorded;
1226
+ }
1227
+ /** Records a model call around `run`, or answers it from the recording. */
1228
+ async function modelCall(seam, method, request, streamed, run) {
1229
+ const effect = {
1230
+ kind: "model",
1231
+ seam,
1232
+ method,
1233
+ call: modelCalls++,
1234
+ request: toJson(omit(request, [
1235
+ "abortSignal",
1236
+ "headers",
1237
+ "signal"
1238
+ ]))
1239
+ };
1240
+ effects.push(effect);
1241
+ if (replay) {
1242
+ let recorded;
1243
+ try {
1244
+ recorded = nextReplayedModel(effect);
1245
+ } catch (error) {
1246
+ effect.error = toRecordedError(error);
1247
+ throw error;
1248
+ }
1249
+ if (recorded.error) {
1250
+ effect.error = recorded.error;
1251
+ throw fromRecordedError(recorded.error);
1252
+ }
1253
+ effect.response = recorded.response;
1254
+ effect.stream = recorded.stream;
1255
+ if (seam === "openai") return streamed ? iterate(recorded.stream ?? []) : structuredClone(recorded.response);
1256
+ return streamed ? {
1257
+ ...reviveTimestamps(structuredClone(recorded.response) ?? {}),
1258
+ stream: streamFrom(recorded.stream ?? [])
1259
+ } : reviveTimestamps(structuredClone(recorded.response));
1260
+ }
1261
+ let result;
1262
+ try {
1263
+ result = await run();
1264
+ } catch (error) {
1265
+ effect.error = toRecordedError(error);
1266
+ throw error;
1267
+ }
1268
+ if (!streamed) {
1269
+ effect.response = toJson(result);
1270
+ return result;
1271
+ }
1272
+ const parts = [];
1273
+ effect.stream = parts;
1274
+ if (seam === "openai") {
1275
+ const source = result;
1276
+ return (async function* () {
1277
+ for await (const chunk of source) {
1278
+ parts.push(toJson(chunk));
1279
+ yield chunk;
1280
+ }
1281
+ })();
1282
+ }
1283
+ const { stream, ...rest } = result;
1284
+ effect.response = toJson(rest);
1285
+ return {
1286
+ ...rest,
1287
+ stream: stream.pipeThrough(new TransformStream({ transform(part, controller) {
1288
+ parts.push(toJson(part));
1289
+ controller.enqueue(part);
1290
+ } }))
1291
+ };
1292
+ }
1293
+ /** `inputOf` picks the recorded input from the call's arguments. */
1294
+ function tool(name, fn, inputOf = (args) => args.length === 1 ? args[0] : args) {
1295
+ return ((...args) => {
1296
+ const input = toJson(inputOf(args));
1297
+ const effect = {
1298
+ kind: "tool",
1299
+ name,
1300
+ step: modelCalls,
1301
+ input,
1302
+ ...toolsInFlight > 0 ? { concurrent: true } : {}
1303
+ };
1304
+ effects.push(effect);
1305
+ return track(call(effect, args));
1306
+ });
1307
+ function call(effect, args) {
1308
+ const { input } = effect;
1309
+ if (replay && options.tools !== "live") {
1310
+ const wanted = normalizeEffect(effect).input;
1311
+ const recorded = replay.find((candidate) => candidate.kind === "tool" && !usedTools.has(candidate) && candidate.step === effect.step && candidate.name === name && jsonEqual(normalizeEffect(candidate).input, wanted));
1312
+ const settle = (value) => {
1313
+ if (recorded?.sync) return value();
1314
+ try {
1315
+ return Promise.resolve(value());
1316
+ } catch (error) {
1317
+ return Promise.reject(error);
1318
+ }
1319
+ };
1320
+ return settle(() => {
1321
+ if (!recorded) {
1322
+ const error = new RecordingDivergenceError(`Tool '${name}' was called with ${JSON.stringify(input)} ${effect.step === 0 ? "before any model call" : `after model call #${effect.step - 1}`}; the recorded run made no such call.`);
1323
+ effect.error = toRecordedError(error);
1324
+ throw error;
1325
+ }
1326
+ usedTools.add(recorded);
1327
+ if (recorded.sync) effect.sync = true;
1328
+ if (recorded.error) {
1329
+ effect.error = recorded.error;
1330
+ throw fromRecordedError(recorded.error);
1331
+ }
1332
+ effect.output = recorded.output;
1333
+ return structuredClone(recorded.output);
1334
+ });
1335
+ }
1336
+ let output;
1337
+ try {
1338
+ output = fn(...args);
1339
+ } catch (error) {
1340
+ effect.sync = true;
1341
+ effect.error = toRecordedError(error);
1342
+ throw error;
1343
+ }
1344
+ if (!(output instanceof Promise)) {
1345
+ effect.sync = true;
1346
+ effect.output = toJson(output);
1347
+ return output;
1348
+ }
1349
+ return output.then((value) => {
1350
+ effect.output = toJson(value);
1351
+ return value;
1352
+ }, (error) => {
1353
+ effect.error = toRecordedError(error);
1354
+ throw error;
1355
+ });
1356
+ }
1357
+ }
1358
+ /** Counts an async tool call as running until it settles. */
1359
+ function track(result) {
1360
+ if (result instanceof Promise) {
1361
+ toolsInFlight++;
1362
+ const settled = () => {
1363
+ toolsInFlight--;
1364
+ };
1365
+ result.then(settled, settled);
1366
+ }
1367
+ return result;
1368
+ }
1369
+ return {
1370
+ model(model) {
1371
+ const base = model;
1372
+ const wrapped = Object.create(base);
1373
+ wrapped["doGenerate"] = (callOptions) => modelCall("ai-sdk", "doGenerate", callOptions, false, () => base["doGenerate"].call(base, callOptions));
1374
+ wrapped["doStream"] = (callOptions) => modelCall("ai-sdk", "doStream", callOptions, true, () => base["doStream"].call(base, callOptions));
1375
+ return wrapped;
1376
+ },
1377
+ openai(client) {
1378
+ const wrapCreate = (resource, method) => new Proxy(resource, { get(target, key, receiver) {
1379
+ if (key !== "create") return Reflect.get(target, key, receiver);
1380
+ return (params, requestOptions) => {
1381
+ let api;
1382
+ const promise = modelCall("openai", method, params, params?.stream === true, () => {
1383
+ api = Reflect.get(target, "create").call(target, params, requestOptions);
1384
+ return Promise.resolve(api);
1385
+ });
1386
+ return Object.assign(promise, { withResponse: async () => {
1387
+ const data = await promise;
1388
+ const meta = await api?.withResponse?.();
1389
+ return {
1390
+ data,
1391
+ response: meta?.response ?? new Response(null),
1392
+ request_id: meta?.request_id ?? null
1393
+ };
1394
+ } });
1395
+ };
1396
+ } });
1397
+ const wrapped = /* @__PURE__ */ new Map();
1398
+ const wrap = (key, make) => {
1399
+ if (!wrapped.has(key)) wrapped.set(key, make());
1400
+ return wrapped.get(key);
1401
+ };
1402
+ return new Proxy(client, { get(target, key, receiver) {
1403
+ const value = Reflect.get(target, key, receiver);
1404
+ if (key === "responses" && value) return wrap(key, () => wrapCreate(value, "responses.create"));
1405
+ if (key === "chat" && value) return wrap(key, () => new Proxy(value, { get(chat, chatKey, chatReceiver) {
1406
+ const inner = Reflect.get(chat, chatKey, chatReceiver);
1407
+ return chatKey === "completions" && inner ? wrap("chat.completions", () => wrapCreate(inner, "chat.completions.create")) : inner;
1408
+ } }));
1409
+ return value;
1410
+ } });
1411
+ },
1412
+ tool: (name, fn) => tool(name, fn),
1413
+ tools(tools) {
1414
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => [name, definition.execute ? {
1415
+ ...definition,
1416
+ execute: tool(name, definition.execute, (args) => args[0])
1417
+ } : definition]));
1418
+ },
1419
+ output(value) {
1420
+ effects.push({
1421
+ kind: "output",
1422
+ value: toJson(value)
1423
+ });
1424
+ },
1425
+ get recording() {
1426
+ return {
1427
+ version: 1,
1428
+ effects: toJson(effects)
1429
+ };
1430
+ }
1431
+ };
1432
+ }
1433
+ /** True when two model calls offer the same tool names and response format. */
1434
+ function sameModelCallShape(expected, actual) {
1435
+ return jsonEqual(modelCallShape(expected), modelCallShape(actual));
1436
+ }
1437
+ function modelCallsMatch(match, expected, actual) {
1438
+ if (match === "none") return true;
1439
+ if (typeof match === "function") return match(expected, actual);
1440
+ return sameModelCallShape(expected, actual);
1441
+ }
1442
+ function shapeMessage(expected, actual) {
1443
+ return `Model call #${expected.call} changed shape: ${JSON.stringify(modelCallShape(expected))} → ${JSON.stringify(modelCallShape(actual))}. A recorded answer only fits a call of the same shape.`;
1444
+ }
1445
+ /** Offered tool names and the response format: what a recorded answer depends on. */
1446
+ function modelCallShape(effect) {
1447
+ const request = effect.request ?? {};
1448
+ return {
1449
+ tools: (Array.isArray(request["tools"]) ? request["tools"] : []).map((tool) => tool["name"] ?? tool["function"]?.["name"]).sort(),
1450
+ format: request["responseFormat"]?.["type"] ?? request["response_format"]?.["type"] ?? (request["text"]?.["format"])?.["type"] ?? "text"
1451
+ };
1452
+ }
1453
+ /**
1454
+ * Puts each group of concurrent tool calls in a stable order, so parallel tool
1455
+ * calls that finished in a different order still compare equal. A tool call
1456
+ * that started after the previous one settled begins a new group, so
1457
+ * sequential calls keep their order.
1458
+ */
1459
+ function normalize(effects) {
1460
+ const result = [];
1461
+ let batch = [];
1462
+ const flush = () => {
1463
+ result.push(...batch.sort((a, b) => stableStringify([a.name, a.input]).localeCompare(stableStringify([b.name, b.input]))));
1464
+ batch = [];
1465
+ };
1466
+ for (const effect of effects) {
1467
+ if (effect.kind !== "tool" || !effect.concurrent) flush();
1468
+ if (effect.kind === "tool") batch.push(effect);
1469
+ else result.push(effect);
1470
+ }
1471
+ flush();
1472
+ return result;
1473
+ }
1474
+ function describe(effect) {
1475
+ switch (effect.kind) {
1476
+ case "model": return `model call #${effect.call} (${effect.method})`;
1477
+ case "tool": return `tool '${effect.name}' with ${JSON.stringify(effect.input)}`;
1478
+ case "output": return `output ${JSON.stringify(effect.value)}`;
1479
+ }
1480
+ }
1481
+ /** Why two effects differ, or `undefined` when they are the same. */
1482
+ function differ(left, right, options) {
1483
+ if (left.kind !== right.kind) return {
1484
+ reason: "kind",
1485
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1486
+ };
1487
+ if (left.kind === "model" && right.kind === "model") {
1488
+ if (left.method !== right.method) return {
1489
+ reason: "model-method",
1490
+ message: `Model call #${left.call} used ${left.method}; the port used ${right.method}.`
1491
+ };
1492
+ if (!modelCallsMatch(options.modelCalls, left, right)) return {
1493
+ reason: "model-call-shape",
1494
+ message: shapeMessage(left, right)
1495
+ };
1496
+ if (!jsonEqual(left.error, right.error)) {
1497
+ const outcome = (error) => error ? `failed with ${error.name}: ${error.message}` : "succeeded";
1498
+ return {
1499
+ reason: "model-error",
1500
+ message: `Model call #${left.call} ${outcome(left.error)}; in the port it ${outcome(right.error)}.`
1501
+ };
1502
+ }
1503
+ return;
1504
+ }
1505
+ if (left.kind === "tool" && right.kind === "tool") {
1506
+ if (left.name !== right.name) return {
1507
+ reason: "tool-name",
1508
+ message: `Expected ${describe(left)}; the port made ${describe(right)}.`
1509
+ };
1510
+ if (!jsonEqual(left.input, right.input)) return {
1511
+ reason: "tool-input",
1512
+ message: `Expected ${describe(left)}; the port passed ${JSON.stringify(right.input)}.`
1513
+ };
1514
+ if (!jsonEqual(left.output, right.output) || !jsonEqual(left.error, right.error)) return {
1515
+ reason: "tool-result",
1516
+ message: `Tool '${left.name}' returned a different result.`
1517
+ };
1518
+ return;
1519
+ }
1520
+ if (left.kind === "output" && right.kind === "output" && !jsonEqual(left.value, right.value)) return {
1521
+ reason: "output",
1522
+ message: `Expected ${describe(left)}; the port returned ${JSON.stringify(right.value)}.`
1523
+ };
1524
+ }
1525
+ /**
1526
+ * Compares two recordings and reports every effect that differs. `expected`
1527
+ * is the original's recording, `actual` the port's. Effects that are the same
1528
+ * on both sides are lined up first (longest common subsequence), so one extra
1529
+ * call does not shift every effect after it; between them, effects of the same
1530
+ * kind pair up and report what changed, and the rest are missing or extra.
1531
+ */
1532
+ function compareRecordings(expected, actual, options = {}) {
1533
+ const map = options.normalize ?? ((effect) => effect);
1534
+ const a = normalize(expected.effects.map(map));
1535
+ const b = normalize(actual.effects.map(map));
1536
+ const same = a.map((left) => b.map((right) => !differ(left, right, options)));
1537
+ const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }, () => 0));
1538
+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = same[i][j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
1539
+ const divergences = [];
1540
+ let lefts = [];
1541
+ let rights = [];
1542
+ const flushGap = (at) => {
1543
+ const unpairedRights = [...rights];
1544
+ const changed = [];
1545
+ for (const index of lefts) {
1546
+ const left = a[index];
1547
+ const k = unpairedRights.findIndex((j) => b[j].kind === left.kind);
1548
+ if (k === -1) {
1549
+ changed.push({
1550
+ index,
1551
+ reason: "missing-effect",
1552
+ expected: left,
1553
+ message: `The port never made ${describe(left)}.`
1554
+ });
1555
+ continue;
1556
+ }
1557
+ const right = b[unpairedRights.splice(k, 1)[0]];
1558
+ const difference = differ(left, right, options);
1559
+ if (difference) changed.push({
1560
+ index,
1561
+ expected: left,
1562
+ actual: right,
1563
+ ...difference
1564
+ });
1565
+ }
1566
+ for (const j of unpairedRights) divergences.push({
1567
+ index: lefts[0] ?? at,
1568
+ reason: "extra-effect",
1569
+ actual: b[j],
1570
+ message: `The port made ${describe(b[j])}, which the original never made.`
1571
+ });
1572
+ divergences.push(...changed);
1573
+ lefts = [];
1574
+ rights = [];
1575
+ };
1576
+ let i = 0;
1577
+ let j = 0;
1578
+ while (i < a.length || j < b.length) if (i < a.length && j < b.length && same[i][j]) {
1579
+ flushGap(i);
1580
+ i++;
1581
+ j++;
1582
+ } else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) rights.push(j++);
1583
+ else lefts.push(i++);
1584
+ flushGap(i);
1585
+ divergences.sort((x, y) => x.index - y.index);
1586
+ return divergences.length ? {
1587
+ equivalent: false,
1588
+ divergence: divergences[0],
1589
+ divergences
1590
+ } : {
1591
+ equivalent: true,
1592
+ divergences
1593
+ };
1594
+ }
1595
+ //#endregion
1074
1596
  exports.AgentLintError = require_verify.AgentLintError;
1075
1597
  exports.AgentUnknownStateError = require_verify.AgentUnknownStateError;
1598
+ exports.RecordingDivergenceError = RecordingDivergenceError;
1076
1599
  exports.assertAgentMachine = require_verify.assertAgentMachine;
1077
1600
  exports.canReach = require_verify.canReach;
1601
+ exports.compareRecordings = compareRecordings;
1078
1602
  exports.compareRuns = compareRuns;
1603
+ exports.createRecorder = createRecorder;
1079
1604
  exports.explorePaths = require_verify.explorePaths;
1080
1605
  exports.firstDivergence = firstDivergence;
1081
1606
  exports.foldTraces = foldTraces;
@@ -1085,6 +1610,7 @@ exports.lintAgentMachine = require_verify.lintAgentMachine;
1085
1610
  exports.matchesTrajectory = matchesTrajectory;
1086
1611
  exports.repeatRuns = repeatRuns;
1087
1612
  exports.runSeam = runSeam;
1613
+ exports.sameModelCallShape = sameModelCallShape;
1088
1614
  exports.simulateAgent = require_verify.simulateAgent;
1089
1615
  exports.summarizeRepeats = summarizeRepeats;
1090
1616
  exports.traceCoverage = traceCoverage;