@statelyai/agent 2.0.0-alpha.23 → 2.0.0-alpha.25

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 (53) hide show
  1. package/dist/ai-sdk.cjs +30 -34
  2. package/dist/ai-sdk.d.cts +27 -31
  3. package/dist/ai-sdk.d.mts +27 -31
  4. package/dist/ai-sdk.mjs +27 -31
  5. package/dist/decision-CM9CYZ6t.cjs +519 -0
  6. package/dist/decision-DzSv1NpD.mjs +453 -0
  7. package/dist/event-log-store-Ba2fsc4E.mjs +576 -0
  8. package/dist/event-log-store-DQmImLYk.cjs +702 -0
  9. package/dist/event-log-store-DvOcs10J.d.cts +338 -0
  10. package/dist/event-log-store-DxyVgnas.d.mts +338 -0
  11. package/dist/index.cjs +429 -4272
  12. package/dist/index.d.cts +104 -1005
  13. package/dist/index.d.mts +104 -1005
  14. package/dist/index.mjs +389 -4202
  15. package/dist/log.cjs +392 -0
  16. package/dist/log.d.cts +32 -0
  17. package/dist/log.d.mts +32 -0
  18. package/dist/log.mjs +371 -0
  19. package/dist/machines.cjs +27 -16
  20. package/dist/machines.d.cts +1 -1
  21. package/dist/machines.d.mts +1 -1
  22. package/dist/machines.mjs +27 -16
  23. package/dist/openai.cjs +16 -15
  24. package/dist/openai.d.cts +9 -9
  25. package/dist/openai.d.mts +9 -9
  26. package/dist/openai.mjs +10 -9
  27. package/dist/otel.d.cts +1 -1
  28. package/dist/otel.d.mts +1 -1
  29. package/dist/{run-agent-Ck7Sa3Tb.d.mts → run-agent-BOfoJg5B.d.cts} +86 -387
  30. package/dist/{run-agent-DWqA8KiI.d.cts → run-agent-CG343kFs.d.mts} +86 -387
  31. package/dist/run-agent-Cb1-LS5P.cjs +1783 -0
  32. package/dist/run-agent-DvDQd4If.mjs +1669 -0
  33. package/dist/{setup-agent-CeO2fARv.mjs → setup-agent-CFW-jPI8.mjs} +9 -20
  34. package/dist/{setup-agent-Dl2VELLi.cjs → setup-agent-CPf7MxnG.cjs} +20 -37
  35. package/dist/testing.cjs +1222 -0
  36. package/dist/testing.d.cts +602 -0
  37. package/dist/testing.d.mts +602 -0
  38. package/dist/testing.mjs +1212 -0
  39. package/dist/{text-logic-DJBK3LbG.d.mts → text-logic-BFEOxyxv.d.cts} +71 -147
  40. package/dist/text-logic-Bl_ZRxDi.mjs +833 -0
  41. package/dist/text-logic-C8xyr6Ag.cjs +1091 -0
  42. package/dist/{text-logic-C7bSnH_B.d.cts → text-logic-hZSiRUo1.d.mts} +71 -147
  43. package/dist/{types-CjHk5OdH.d.cts → types-B1Qs2q3q.d.cts} +2 -1
  44. package/dist/{types-DWA6X9R-.d.mts → types-tA3SdczG.d.mts} +2 -1
  45. package/dist/usage-BdEjFuIi.mjs +5 -0
  46. package/dist/usage-efOQPdf_.cjs +10 -0
  47. package/dist/utils-C1p37X_c.d.mts +209 -0
  48. package/dist/utils-RalRn9sk.d.cts +209 -0
  49. package/package.json +24 -4
  50. package/readme.md +2 -2
  51. package/skills/generate-machine/SKILL.md +4 -6
  52. package/dist/decision-BBZ2jMO1.mjs +0 -1490
  53. package/dist/decision-Cv6SfNWl.cjs +0 -1856
@@ -0,0 +1,1222 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_text_logic = require("./text-logic-C8xyr6Ag.cjs");
3
+ const require_decision = require("./decision-CM9CYZ6t.cjs");
4
+ const require_run_agent = require("./run-agent-Cb1-LS5P.cjs");
5
+ //#region src/verify.ts
6
+ const DECIDE_SRC = "agent.decide";
7
+ function normalizeInvokes(invoke) {
8
+ if (invoke === void 0 || invoke === null) return [];
9
+ return Array.isArray(invoke) ? invoke : [invoke];
10
+ }
11
+ function buildStateIndex(rootConfig) {
12
+ const index = /* @__PURE__ */ new Map();
13
+ const walk = (states, parentPath) => {
14
+ for (const [name, config] of Object.entries(states ?? {})) {
15
+ const path = parentPath ? `${parentPath}.${name}` : name;
16
+ const hasChildren = !!config.states && Object.keys(config.states).length > 0;
17
+ index.set(path, {
18
+ path,
19
+ config,
20
+ parentPath,
21
+ isFinal: config.type === "final",
22
+ isParallel: config.type === "parallel",
23
+ isCompound: hasChildren && config.type !== "parallel",
24
+ invokes: normalizeInvokes(config.invoke)
25
+ });
26
+ if (hasChildren) walk(config.states, path);
27
+ }
28
+ };
29
+ walk(rootConfig.states, "");
30
+ return index;
31
+ }
32
+ function ancestorChain(node, index) {
33
+ const chain = [];
34
+ let parent = node.parentPath;
35
+ while (parent) {
36
+ const parentNode = index.get(parent);
37
+ if (!parentNode) break;
38
+ chain.push(parentNode);
39
+ parent = parentNode.parentPath;
40
+ }
41
+ return chain;
42
+ }
43
+ function hasNonEmptyOn(config) {
44
+ return !!config.on && Object.keys(config.on).length > 0;
45
+ }
46
+ function isDecisionInvoke(src, actors) {
47
+ if (typeof src === "string") return src === DECIDE_SRC || require_decision.isDecisionLogic(actors[src]);
48
+ return require_decision.isDecisionLogic(src);
49
+ }
50
+ function isAgentLogicNeedingBinding(src) {
51
+ return (require_text_logic.isTextLogic(src) || require_decision.isDecisionLogic(src)) && !require_text_logic.executorBoundLogics.has(src);
52
+ }
53
+ function checkDecideWithoutEvents(ctx) {
54
+ const out = [];
55
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
56
+ if (!isDecisionInvoke(invoke.src, ctx.actors)) continue;
57
+ const selfHandles = hasNonEmptyOn(node.config);
58
+ const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
59
+ const invokeObserves = invoke.onDone !== void 0;
60
+ if (selfHandles || ancestorHandles || invokeObserves) continue;
61
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
62
+ out.push({
63
+ code: "decide-without-events",
64
+ severity: "error",
65
+ path: node.path,
66
+ message: `State '${node.path}' invokes decision source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the decision's chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
67
+ });
68
+ }
69
+ return out;
70
+ }
71
+ function checkDirectObjectSrc(ctx) {
72
+ const out = [];
73
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
74
+ const src = invoke.src;
75
+ if (typeof src === "string" || !src || typeof src !== "object") continue;
76
+ if (!isAgentLogicNeedingBinding(src)) continue;
77
+ out.push({
78
+ code: "direct-object-src",
79
+ severity: "warning",
80
+ path: node.path,
81
+ message: `State '${node.path}' invokes a direct-object agent logic. Direct-object invoke srcs cannot be rebound by runAgent, so they inherit no host executors — call '.withExecutor(...)' on the logic, or register it as a string-keyed actor source (machine.provide({ actors: { name: logic } })) and invoke it by name.`
82
+ });
83
+ }
84
+ return out;
85
+ }
86
+ function handlesActorError(config) {
87
+ if (config["onError"] !== void 0) return true;
88
+ return Object.keys(config.on ?? {}).some((type) => type === "*" || type.startsWith("xstate.error"));
89
+ }
90
+ function checkInvokeWithoutOnError(ctx) {
91
+ const out = [];
92
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
93
+ if (invoke.onError !== void 0 || handlesActorError(node.config)) continue;
94
+ if (handlesActorError(ctx.config) || ancestorChain(node, ctx.index).some((ancestor) => handlesActorError(ancestor.config))) continue;
95
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
96
+ out.push({
97
+ code: "invoke-without-on-error",
98
+ severity: "warning",
99
+ path: node.path,
100
+ message: `State '${node.path}' invokes '${srcName}' with no 'onError' transition, and no ancestor handles an actor error. A rejected request or actor puts the machine in an error state with no modeled recovery. Add 'onError' (a 'failed' final state, or a bounded retry).`
101
+ });
102
+ }
103
+ return out;
104
+ }
105
+ const LINT_CHECKS = [
106
+ checkDecideWithoutEvents,
107
+ checkDirectObjectSrc,
108
+ checkInvokeWithoutOnError
109
+ ];
110
+ /**
111
+ * Runs static structural checks over a built agent machine and returns the
112
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
113
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
114
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
115
+ * plus the schemas/actor sources the library already retains per machine.
116
+ *
117
+ * No model calls, no API keys — a coding agent that emits an agent machine can
118
+ * call this to catch agent-specific mistakes such as undeliverable decisions,
119
+ * un-rebindable request sources, and an unhandled transcript event. General
120
+ * state-machine lint belongs to XState tooling.
121
+ *
122
+ * Pass `{ throw: true }` for the one-liner form used in tests and generation
123
+ * loops: it returns silently when the machine is clean and throws
124
+ * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
125
+ * findings, or on warnings too with `{ throw: true, warnings: true }`.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
130
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
131
+ * ```
132
+ *
133
+ * @example Throwing form
134
+ * ```ts
135
+ * test('agent machine is structurally sound', () => {
136
+ * lintAgentMachine(machine, { throw: true });
137
+ * });
138
+ * ```
139
+ */
140
+ function lintAgentMachine(machine, options = {}) {
141
+ const config = machine.config ?? {};
142
+ const index = buildStateIndex(config);
143
+ const registered = require_text_logic.getRegisteredAgentExecutionOptions(machine);
144
+ const ctx = {
145
+ config,
146
+ index,
147
+ schemas: registered.schemas,
148
+ actors: registered.actors ?? machine.sources?.actors ?? {}
149
+ };
150
+ const disabled = new Set(options.disable ?? []);
151
+ const diagnostics = LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
152
+ if (options.throw) {
153
+ const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
154
+ if (failing.length > 0) throw new AgentLintError(machine.id ?? "(machine)", failing);
155
+ }
156
+ return diagnostics;
157
+ }
158
+ /**
159
+ * Thrown by `lintAgentMachine(machine, { throw: true })` (and its
160
+ * {@link assertAgentMachine} alias) when lint finds failing diagnostics.
161
+ * `diagnostics` holds the findings; the message lists them one per finding,
162
+ * so a test runner's failure output reads like the CLI's lint report.
163
+ */
164
+ var AgentLintError = class extends require_text_logic.AgentError {
165
+ diagnostics;
166
+ constructor(machineId, diagnostics) {
167
+ const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
168
+ super("lint-failed", `Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
169
+ this.name = "AgentLintError";
170
+ this.diagnostics = diagnostics;
171
+ }
172
+ };
173
+ /**
174
+ * Asserts a machine passes {@link lintAgentMachine}: returns silently when
175
+ * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
176
+ * otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
177
+ * Fails on error-severity findings; set `warnings: true` to fail on warnings
178
+ * too. The one-liner for tests and generation loops:
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * test('agent machine is structurally sound', () => {
183
+ * assertAgentMachine(machine);
184
+ * });
185
+ * ```
186
+ */
187
+ function assertAgentMachine(machine, options = {}) {
188
+ lintAgentMachine(machine, {
189
+ ...options,
190
+ throw: true
191
+ });
192
+ }
193
+ function pendingInvokes(step) {
194
+ const out = [];
195
+ for (const metadata of require_run_agent.getPendingInvokes(step.snapshot)) if (typeof metadata.src === "string") out.push({
196
+ id: metadata.id,
197
+ src: metadata.src
198
+ });
199
+ return out;
200
+ }
201
+ function takeFromQueue(channel, src) {
202
+ const queue = channel?.[src];
203
+ if (queue && queue.length > 0) return {
204
+ found: true,
205
+ value: queue.shift()
206
+ };
207
+ return { found: false };
208
+ }
209
+ /**
210
+ * Deterministically plays a machine through, resolving each request from a
211
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
212
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
213
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
214
+ * and a `trail` of every step taken.
215
+ *
216
+ * Decisions run through the live run's own validation/retry core,
217
+ * {@link resolveDecision}, with the script standing in for the model: each
218
+ * attempt consumes the next queued {@link ChosenEvent} for that src, so an
219
+ * unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
220
+ * — the next queued decision is tried, exactly as a live run re-asks the
221
+ * model. The decision logic's `maxRetries` caps attempts as it would live;
222
+ * when retries continue past the end of the queue, the last queued decision
223
+ * repeats (a scripted model that insists). The repeat applies only within one
224
+ * decision request's retries — each new decision request must have its own
225
+ * queued entry, or the dry-script error throws as usual. Exhausting all
226
+ * attempts delivers
227
+ * the resulting {@link AgentDecisionExhaustedError} to the machine as the
228
+ * decision invoke's error (so an `onError` transition observes it, as it
229
+ * would live); with no `onError` to catch it, it is thrown.
230
+ *
231
+ * Throws a descriptive error when the script runs dry mid-request, naming the
232
+ * pending request's kind, src, and id so the missing scripted response is
233
+ * obvious.
234
+ *
235
+ * @example
236
+ * ```ts
237
+ * const { status, snapshot } = simulateAgent(machine, {
238
+ * input: { topic: 'state machines' },
239
+ * script: {
240
+ * decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
241
+ * events: [{ type: 'APPROVE' }], // crosses the human gate
242
+ * },
243
+ * });
244
+ * ```
245
+ */
246
+ async function simulateAgent(machine, options) {
247
+ const maxSteps = options.maxSteps ?? 100;
248
+ const script = {
249
+ text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
250
+ decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
251
+ invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr]),
252
+ errors: mapValues(options.script.errors ?? {}, (arr) => [...arr]),
253
+ events: [...options.script.events ?? []]
254
+ };
255
+ let step = require_run_agent.initialAgentStep(machine, options.input);
256
+ const trail = [{ state: step.snapshot.value }];
257
+ for (let i = 0; i < maxSteps; i++) {
258
+ if (step.done) return {
259
+ status: "done",
260
+ snapshot: step.snapshot,
261
+ trail
262
+ };
263
+ const request = step.requests[0];
264
+ if (request) {
265
+ if (request.kind === "decision") {
266
+ const invokeMeta = findInvokeMetadata(step, request.id);
267
+ const src = invokeMeta?.src ?? request.id;
268
+ const decisionSrc = src in (script.decisions ?? {}) ? src : request.id in (script.decisions ?? {}) ? request.id : src;
269
+ const errorSrc = queueKey(script.errors, src, request.id);
270
+ const failure = takeFromQueue(script.errors, errorSrc);
271
+ if (failure.found) {
272
+ step = rejectScriptedRequest(machine, step, request.id, failure.value, {
273
+ kind: "decision",
274
+ src: errorSrc,
275
+ trail
276
+ });
277
+ continue;
278
+ }
279
+ step = await applyScriptedDecision(machine, step, request, decisionSrc, invokeMeta?.logic, script, trail);
280
+ continue;
281
+ }
282
+ const failure = takeFromQueue(script.errors, request.src);
283
+ if (failure.found) {
284
+ step = rejectScriptedRequest(machine, step, request, failure.value, {
285
+ kind: "text",
286
+ src: request.src,
287
+ trail
288
+ });
289
+ continue;
290
+ }
291
+ const taken = takeFromQueue(script.text, request.src);
292
+ if (!taken.found) throw scriptDryError("text", request.src, request.id);
293
+ step = require_run_agent.resolveAgentStep(machine, step, request, asTextResult(taken.value));
294
+ trail.push({
295
+ state: step.snapshot.value,
296
+ resolvedRequest: {
297
+ kind: "text",
298
+ src: request.src,
299
+ id: request.id,
300
+ outcome: "output"
301
+ }
302
+ });
303
+ continue;
304
+ }
305
+ const [invoke] = pendingInvokes(step);
306
+ if (invoke) {
307
+ const failure = takeFromQueue(script.errors, invoke.src);
308
+ if (failure.found) {
309
+ step = rejectScriptedRequest(machine, step, invoke.id, failure.value, {
310
+ kind: "invoke",
311
+ src: invoke.src,
312
+ trail
313
+ });
314
+ continue;
315
+ }
316
+ const taken = takeFromQueue(script.invokes, invoke.src);
317
+ if (!taken.found) throw scriptDryError("invoke", invoke.src, invoke.id);
318
+ step = require_run_agent.resolveAgentStep(machine, step, invoke.id, taken.value);
319
+ trail.push({
320
+ state: step.snapshot.value,
321
+ resolvedRequest: {
322
+ kind: "invoke",
323
+ src: invoke.src,
324
+ id: invoke.id,
325
+ outcome: "output"
326
+ }
327
+ });
328
+ continue;
329
+ }
330
+ const external = script.events;
331
+ if (external.length > 0) {
332
+ const event = external.shift();
333
+ if (!step.snapshot.can(event)) throw new Error(`simulateAgent: scripted external event '${event.type}' cannot be taken in state ${JSON.stringify(step.snapshot.value)} (no handler, or its guard rejected it). A live run's send would be silently dropped here; fix the script's \`events\` queue.`);
334
+ step = require_run_agent.transitionAgentStep(machine, step, event);
335
+ trail.push({
336
+ state: step.snapshot.value,
337
+ appliedEvent: event,
338
+ external: true
339
+ });
340
+ continue;
341
+ }
342
+ return {
343
+ status: "idle",
344
+ snapshot: step.snapshot,
345
+ trail
346
+ };
347
+ }
348
+ return {
349
+ status: "exhausted",
350
+ snapshot: step.snapshot,
351
+ trail
352
+ };
353
+ }
354
+ function queueKey(channel, src, id) {
355
+ return channel && !(src in channel) && id in channel ? id : src;
356
+ }
357
+ function rejectScriptedRequest(machine, step, request, error, entry) {
358
+ const id = typeof request === "string" ? request : request.id;
359
+ const next = require_run_agent.rejectAgentStep(machine, step, request, error);
360
+ if (next.snapshot.status === "error") throw unhandledScriptedError(error, entry.kind, entry.src, id);
361
+ entry.trail.push({
362
+ state: next.snapshot.value,
363
+ resolvedRequest: {
364
+ kind: entry.kind,
365
+ src: entry.src,
366
+ id,
367
+ outcome: "error",
368
+ error
369
+ }
370
+ });
371
+ return next;
372
+ }
373
+ function unhandledScriptedError(error, kind, src, id) {
374
+ if (error instanceof Error) return error;
375
+ return new Error(`simulateAgent: the scripted error for the ${kind} request '${src}' (id '${id}') reached no onError transition, so the machine errored. Add an onError to that invoke, or drop the errors['${src}'] entry.`, { cause: error });
376
+ }
377
+ async function applyScriptedDecision(machine, step, request, decisionSrc, invokeLogic, script, trail) {
378
+ const dequeued = [];
379
+ const decide = async () => {
380
+ const taken = takeFromQueue(script.decisions, decisionSrc);
381
+ if (taken.found) {
382
+ dequeued.push(taken.value);
383
+ return { event: taken.value };
384
+ }
385
+ if (dequeued.length === 0) throw scriptDryError("decision", decisionSrc, request.id, request);
386
+ return { event: dequeued[dequeued.length - 1] };
387
+ };
388
+ const maxRetries = (require_decision.isDecisionLogic(invokeLogic) ? invokeLogic : resolveRegisteredDecisionLogic(machine, decisionSrc))?.maxRetries;
389
+ let chosen;
390
+ try {
391
+ chosen = await require_decision.resolveDecision(request, { decide }, {
392
+ maxRetries,
393
+ canTake: (event) => step.snapshot.can(event)
394
+ });
395
+ } catch (error) {
396
+ if (!(error instanceof require_decision.AgentDecisionExhaustedError)) throw error;
397
+ const next = require_run_agent.rejectAgentStep(machine, step, request.id, error);
398
+ if (next.snapshot.status === "error") throw error;
399
+ trail.push({
400
+ state: next.snapshot.value,
401
+ rejectedEvents: dequeued
402
+ });
403
+ return next;
404
+ }
405
+ const next = require_run_agent.transitionAgentStep(machine, step, chosen);
406
+ const rejected = dequeued.slice(0, -1);
407
+ trail.push({
408
+ state: next.snapshot.value,
409
+ appliedEvent: chosen,
410
+ ...rejected.length > 0 ? { rejectedEvents: rejected } : {}
411
+ });
412
+ return next;
413
+ }
414
+ function findInvokeMetadata(step, id) {
415
+ for (const metadata of require_run_agent.getPendingInvokes(step.snapshot)) {
416
+ if (metadata.id !== id) continue;
417
+ return {
418
+ ...typeof metadata.src === "string" ? { src: metadata.src } : {},
419
+ logic: metadata.logic ?? (typeof metadata.src === "object" ? metadata.src : void 0)
420
+ };
421
+ }
422
+ }
423
+ function resolveRegisteredDecisionLogic(machine, src) {
424
+ const candidate = require_text_logic.getRegisteredAgentExecutionOptions(machine).actors?.[src] ?? machine.sources?.actors?.[src];
425
+ return require_decision.isDecisionLogic(candidate) ? candidate : void 0;
426
+ }
427
+ function asTextResult(value) {
428
+ return {
429
+ result: value,
430
+ messages: []
431
+ };
432
+ }
433
+ function mapValues(obj, fn) {
434
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
435
+ }
436
+ function scriptDryError(kind, src, id, request) {
437
+ const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
438
+ const key = kind === "text" ? `text['${src}']` : kind === "decision" ? `decisions['${src}']` : `invokes['${src}']`;
439
+ return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add an entry to the script's \`${key}\` queue.${events}`);
440
+ }
441
+ const MAX_ADVANCE_STEPS = 1e3;
442
+ function invokeFork(id, src, outputs) {
443
+ return src in outputs ? {
444
+ id,
445
+ src,
446
+ hasOutput: true,
447
+ output: outputs[src]
448
+ } : {
449
+ id,
450
+ src,
451
+ hasOutput: false
452
+ };
453
+ }
454
+ async function explore(machine, options, stopWhen) {
455
+ const maxDepth = options.maxDepth ?? 8;
456
+ const maxPaths = options.maxPaths ?? 200;
457
+ const textScript = options.text ?? {};
458
+ const invokeOutputs = { ...options.invokes };
459
+ const errorScript = options.errors ?? {};
460
+ const reachedStates = /* @__PURE__ */ new Set();
461
+ const reachedValues = [];
462
+ const terminals = [];
463
+ const unexplored = [];
464
+ let prunedByGuard = 0;
465
+ let pathsExplored = 0;
466
+ let hitPathCap = false;
467
+ let witness;
468
+ const recordState = (snapshot) => {
469
+ const key = JSON.stringify(snapshot.value);
470
+ if (!reachedStates.has(key)) {
471
+ reachedStates.add(key);
472
+ reachedValues.push(snapshot.value);
473
+ }
474
+ };
475
+ const initial = require_run_agent.initialAgentStep(machine, options.input);
476
+ recordState(initial.snapshot);
477
+ if (stopWhen?.(initial.snapshot)) witness = [];
478
+ const advance = (step) => {
479
+ let current = step;
480
+ for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
481
+ if (stopWhen?.(current.snapshot)) return {
482
+ step: current,
483
+ hit: true
484
+ };
485
+ if (current.done) return { step: current };
486
+ const request = current.requests[0];
487
+ if (request && request.kind === "text") {
488
+ if (request.src in errorScript) return {
489
+ step: current,
490
+ fork: invokeFork(request.id, request.src, textScript)
491
+ };
492
+ if (!(request.src in textScript)) return {
493
+ step: current,
494
+ blockedSrc: request.src
495
+ };
496
+ current = require_run_agent.resolveAgentStep(machine, current, request, asTextResult(textScript[request.src]));
497
+ recordState(current.snapshot);
498
+ continue;
499
+ }
500
+ if (request && request.kind === "decision") {
501
+ const src = findInvokeMetadata(current, request.id)?.src;
502
+ const errorSrc = src !== void 0 && src in errorScript ? src : request.id in errorScript ? request.id : void 0;
503
+ return errorSrc !== void 0 ? {
504
+ step: current,
505
+ fork: {
506
+ id: request.id,
507
+ src: errorSrc,
508
+ hasOutput: false,
509
+ isDecision: true
510
+ }
511
+ } : { step: current };
512
+ }
513
+ const [invoke] = pendingInvokes(current);
514
+ if (invoke) {
515
+ if (invoke.src in errorScript) return {
516
+ step: current,
517
+ fork: invokeFork(invoke.id, invoke.src, invokeOutputs)
518
+ };
519
+ if (!(invoke.src in invokeOutputs)) return {
520
+ step: current,
521
+ blockedSrc: invoke.src
522
+ };
523
+ current = require_run_agent.resolveAgentStep(machine, current, invoke.id, invokeOutputs[invoke.src]);
524
+ recordState(current.snapshot);
525
+ continue;
526
+ }
527
+ return { step: current };
528
+ }
529
+ return { step: current };
530
+ };
531
+ const visit = async (step, path, startDepth) => {
532
+ let depth = startDepth;
533
+ if (witness !== void 0) return;
534
+ if (pathsExplored >= maxPaths) {
535
+ hitPathCap = true;
536
+ return;
537
+ }
538
+ const { step: settled, blockedSrc, hit, fork } = advance(step);
539
+ if (hit) {
540
+ witness = path;
541
+ return;
542
+ }
543
+ if (fork) {
544
+ if (depth >= maxDepth) {
545
+ pathsExplored++;
546
+ terminals.push({
547
+ status: "max-depth",
548
+ path,
549
+ state: settled.snapshot.value
550
+ });
551
+ unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
552
+ return;
553
+ }
554
+ const failed = require_run_agent.rejectAgentStep(machine, settled, fork.id, errorScript[fork.src]);
555
+ recordState(failed.snapshot);
556
+ await visit(failed, [...path, { type: `xstate.error.actor.${fork.id}` }], depth + 1);
557
+ if (!fork.isDecision) {
558
+ if (fork.hasOutput) {
559
+ const resolved = require_run_agent.resolveAgentStep(machine, settled, fork.id, fork.output);
560
+ recordState(resolved.snapshot);
561
+ await visit(resolved, path, depth + 1);
562
+ }
563
+ return;
564
+ }
565
+ depth += 1;
566
+ if (witness !== void 0) return;
567
+ }
568
+ if (blockedSrc) {
569
+ pathsExplored++;
570
+ terminals.push({
571
+ status: "needs-output",
572
+ path,
573
+ state: settled.snapshot.value,
574
+ missingSrc: blockedSrc
575
+ });
576
+ unexplored.push(`needs-output: no canned output for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
577
+ return;
578
+ }
579
+ if (settled.done) {
580
+ pathsExplored++;
581
+ terminals.push({
582
+ status: "done",
583
+ path,
584
+ state: settled.snapshot.value
585
+ });
586
+ return;
587
+ }
588
+ if (settled.snapshot.status === "error") {
589
+ pathsExplored++;
590
+ terminals.push({
591
+ status: "error",
592
+ path,
593
+ state: settled.snapshot.value,
594
+ error: settled.snapshot.error
595
+ });
596
+ return;
597
+ }
598
+ const request = settled.requests[0];
599
+ const branchEvents = request?.kind === "decision" ? request.events.map((descriptor) => ({ type: descriptor.type })) : require_decision.getAcceptedEvents(settled.snapshot).map((descriptor) => ({ type: descriptor.type }));
600
+ if (branchEvents.length === 0) {
601
+ pathsExplored++;
602
+ terminals.push({
603
+ status: "idle",
604
+ path,
605
+ state: settled.snapshot.value
606
+ });
607
+ return;
608
+ }
609
+ if (depth >= maxDepth) {
610
+ pathsExplored++;
611
+ terminals.push({
612
+ status: "max-depth",
613
+ path,
614
+ state: settled.snapshot.value
615
+ });
616
+ unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
617
+ return;
618
+ }
619
+ for (const event of branchEvents) {
620
+ if (witness !== void 0 || pathsExplored >= maxPaths) {
621
+ if (pathsExplored >= maxPaths) hitPathCap = true;
622
+ return;
623
+ }
624
+ if (!settled.snapshot.can(event)) {
625
+ prunedByGuard++;
626
+ continue;
627
+ }
628
+ const next = require_run_agent.transitionAgentStep(machine, settled, event);
629
+ recordState(next.snapshot);
630
+ await visit(next, [...path, event], depth + 1);
631
+ }
632
+ };
633
+ if (witness === void 0) await visit(initial, [], 0);
634
+ return {
635
+ report: {
636
+ reachedStates: reachedValues,
637
+ terminals,
638
+ prunedByGuard,
639
+ unexplored,
640
+ pathsExplored,
641
+ hitPathCap
642
+ },
643
+ witness
644
+ };
645
+ }
646
+ /**
647
+ * Enumerates a machine's decision and external-event branches to a bounded
648
+ * depth, model-free, and reports which states are reached and how each path
649
+ * terminates. At each decision request it forks one branch per candidate event
650
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
651
+ * an idle wait it forks per externally-accepted event. Text requests resolve
652
+ * from `text`, other invokes from `invokes` — all by-src canned-output maps, and a missing src halts
653
+ * that branch with a `needs-output` terminal rather than throwing. A src in
654
+ * `errors` forks an extra branch where that invoke is rejected, so states
655
+ * behind an `onError` are explored too.
656
+ *
657
+ * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
658
+ * 200, reported via `hitPathCap`).
659
+ *
660
+ * @example
661
+ * ```ts
662
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
663
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
664
+ * ```
665
+ */
666
+ async function explorePaths(machine, options = {}) {
667
+ return (await explore(machine, options)).report;
668
+ }
669
+ /** Thrown when a string reachability target is not a state in the machine. */
670
+ var AgentUnknownStateError = class extends require_text_logic.AgentError {
671
+ target;
672
+ constructor(machineId, target) {
673
+ super("unknown-state", `canReach: machine '${machineId}' has no state matching '${target}'.`);
674
+ this.name = "AgentUnknownStateError";
675
+ this.target = target;
676
+ }
677
+ };
678
+ function resolveStateTarget(machine, target) {
679
+ const stack = [machine.root];
680
+ while (stack.length > 0) {
681
+ const node = stack.pop();
682
+ if (node.id === target.replace(/^#/, "") || node.path.join(".") === target) return node.id;
683
+ stack.push(...Object.values(node.states));
684
+ }
685
+ throw new AgentUnknownStateError(machine.id, target);
686
+ }
687
+ /**
688
+ * Answers "can the machine reach this?" by exploring its branches (a thin
689
+ * wrapper over {@link explorePaths}). The target is either a state path string
690
+ * (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
691
+ * form checks any property (a context invariant, a tag, a state+context
692
+ * combination) without reifying a sentinel state for it. Returns
693
+ * `{ reachable: true, witness }` with the event sequence that reaches it, or
694
+ * `{ reachable: false }`.
695
+ *
696
+ * @example
697
+ * ```ts
698
+ * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
699
+ * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
700
+ * ```
701
+ *
702
+ * @example Predicate target — a violation property, no sentinel state needed
703
+ * ```ts
704
+ * const violation = await canReach(
705
+ * refundMachine,
706
+ * (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
707
+ * { input: { amount: 5000 } },
708
+ * );
709
+ * // violation.reachable → false is the safety proof
710
+ * ```
711
+ */
712
+ async function canReach(machine, target, options = {}) {
713
+ const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
714
+ const { witness } = await explore(machine, options, typeof target === "function" ? target : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget));
715
+ return witness !== void 0 ? {
716
+ reachable: true,
717
+ witness,
718
+ ...resolvedTarget ? { target: resolvedTarget } : {}
719
+ } : {
720
+ reachable: false,
721
+ ...resolvedTarget ? { target: resolvedTarget } : {}
722
+ };
723
+ }
724
+ //#endregion
725
+ //#region src/trajectory.ts
726
+ /**
727
+ * Classifies one item. Event-shaped things (log entries, events) become events;
728
+ * everything else is a state value. A snapshot is unwrapped to its `value`.
729
+ * @internal
730
+ */
731
+ function normalize(item) {
732
+ if (require_decision.isRecord(item)) {
733
+ const nested = item["event"];
734
+ if (require_decision.isRecord(nested) && typeof nested["type"] === "string") return {
735
+ kind: "event",
736
+ event: nested
737
+ };
738
+ if (typeof item["type"] === "string") return {
739
+ kind: "event",
740
+ event: item
741
+ };
742
+ if ("value" in item) return {
743
+ kind: "state",
744
+ value: item["value"]
745
+ };
746
+ }
747
+ return {
748
+ kind: "state",
749
+ value: item
750
+ };
751
+ }
752
+ /** Every leaf of a state value as a dot path (`{ review: 'editing' }` → `review.editing`). @internal */
753
+ function statePaths(value) {
754
+ if (typeof value === "string") return [value];
755
+ if (!require_decision.isRecord(value)) return [];
756
+ return Object.entries(value).flatMap(([key, child]) => statePaths(child).map((path) => `${key}.${path}`));
757
+ }
758
+ /**
759
+ * A string expectation matches a state value when it names one of its leaves or
760
+ * an ancestor of one, so `'review'` matches `{ review: 'editing' }`. @internal
761
+ */
762
+ function stateMatchesPath(path, value) {
763
+ return statePaths(value).some((leaf) => leaf === path || leaf.startsWith(`${path}.`));
764
+ }
765
+ function deepEqual(a, b) {
766
+ if (Object.is(a, b)) return true;
767
+ 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]));
768
+ if (!require_decision.isRecord(a) || !require_decision.isRecord(b)) return false;
769
+ const keys = Object.keys(a);
770
+ return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
771
+ }
772
+ /**
773
+ * Normalizes ONE expected item into a predicate over actual items, so the
774
+ * expectation is classified once instead of once per candidate:
775
+ *
776
+ * - A string expectation matches an event's `type`, or a state value it names.
777
+ * - An event expectation matches an event with the same `type` whose other
778
+ * declared keys deep-equal, so payload details are opt-in.
779
+ * - A state-value expectation matches structurally.
780
+ * @internal
781
+ */
782
+ function matcherFor(expected) {
783
+ if (typeof expected === "string") return (actual) => {
784
+ const actualItem = normalize(actual);
785
+ return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
786
+ };
787
+ const expectedItem = normalize(expected);
788
+ switch (expectedItem.kind) {
789
+ case "event": return (actual) => {
790
+ const actualItem = normalize(actual);
791
+ return actualItem.kind === "event" && Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
792
+ };
793
+ case "state": return (actual) => {
794
+ const actualItem = normalize(actual);
795
+ return actualItem.kind === "state" && deepEqual(expectedItem.value, actualItem.value);
796
+ };
797
+ }
798
+ }
799
+ /**
800
+ * Matches a run's trajectory against an expected one.
801
+ *
802
+ * Both trajectories may be state values or events collected from
803
+ * `onTransition`;
804
+ * items are compared by shape, so `['prompting', 'drafting']` scores a state
805
+ * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
806
+ * call.
807
+ *
808
+ * Semantics are an ordered subsequence: every expected item must appear in
809
+ * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
810
+ * equality instead.
811
+ *
812
+ * @example Trajectory assertions in a test
813
+ * ```ts
814
+ * const statePath: unknown[] = [];
815
+ * const result = await runAgent(machine, {
816
+ * input,
817
+ * executors,
818
+ * onTransition: (snapshot) => statePath.push(snapshot.value),
819
+ * });
820
+ *
821
+ * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
822
+ * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
823
+ * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
824
+ * ```
825
+ *
826
+ * @example Partial credit in an eval scorer
827
+ * ```ts
828
+ * const match = matchesTrajectory(output.statePath, expected.statePath);
829
+ * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
830
+ * ```
831
+ */
832
+ function matchesTrajectory(actual, expected, options = {}) {
833
+ const expectedCount = expected.length;
834
+ if (expectedCount === 0) throw new require_text_logic.AgentError("empty-trajectory", "matchesTrajectory: expected trajectory must contain at least one item.");
835
+ const exact = options.exact === true;
836
+ let cursor = 0;
837
+ let matchedCount = 0;
838
+ let firstMiss;
839
+ for (let index = 0; index < expectedCount; index++) {
840
+ const want = expected[index];
841
+ const matches = matcherFor(want);
842
+ const searchedFrom = exact ? index : cursor;
843
+ let found = -1;
844
+ for (let at = searchedFrom; at < actual.length; at++) {
845
+ if (matches(actual[at])) {
846
+ found = at;
847
+ break;
848
+ }
849
+ if (exact) break;
850
+ }
851
+ if (found === -1) {
852
+ firstMiss = {
853
+ index,
854
+ expected: want,
855
+ searchedFrom
856
+ };
857
+ break;
858
+ }
859
+ matchedCount++;
860
+ cursor = found + 1;
861
+ }
862
+ const matched = !firstMiss && (!exact || actual.length === expectedCount);
863
+ const denominator = exact ? Math.max(expectedCount, actual.length) : expectedCount;
864
+ return {
865
+ matched,
866
+ matchedCount,
867
+ expectedCount,
868
+ score: matched ? 1 : denominator === 0 ? 1 : matchedCount / denominator,
869
+ ...firstMiss ? { firstMiss } : {}
870
+ };
871
+ }
872
+ //#endregion
873
+ //#region src/scripted-executors.ts
874
+ /**
875
+ * Scripted executors — a deterministic stand-in for a model host.
876
+ *
877
+ * `createScriptedExecutors` builds a full `{ generateText, streamText, decide }`
878
+ * set that plays back canned answers keyed by
879
+ * request name, so `runAgent` (or `provideExecutors`, or a bare
880
+ * `TextLogic.execute`) runs with no API key and no network.
881
+ *
882
+ * One rule: entries for a name are consumed in order, and the last entry
883
+ * repeats forever.
884
+ *
885
+ * @module
886
+ */
887
+ function toQueues(value) {
888
+ return new Map(Object.entries(value ?? {}).map(([name, entries]) => [name, {
889
+ entries: Array.isArray(entries) ? [...entries] : [entries],
890
+ index: 0
891
+ }]));
892
+ }
893
+ /**
894
+ * Takes the next entry for `name`, holding on the last entry once the list is
895
+ * spent. `undefined` means the script has no route for this name at all.
896
+ * @internal
897
+ */
898
+ function takeEntry(queues, name) {
899
+ const queue = queues.get(name) ?? queues.get("*");
900
+ if (!queue || queue.entries.length === 0) return;
901
+ const entry = queue.entries[Math.min(queue.index, queue.entries.length - 1)];
902
+ queue.index++;
903
+ return entry;
904
+ }
905
+ /** @internal */
906
+ function noAnswer(name, queues) {
907
+ const known = [...queues.keys()].join(", ") || "(none)";
908
+ return /* @__PURE__ */ new Error(`No scripted answer for request '${name}'. Known: ${known}`);
909
+ }
910
+ /** The only own keys an executor result carries. @internal */
911
+ const TEXT_RESULT_KEYS = new Set([
912
+ "result",
913
+ "messages",
914
+ "usage",
915
+ "raw"
916
+ ]);
917
+ /**
918
+ * True when a scripted entry is the executor result rather than the output
919
+ * value: it owns a `result` key and owns NOTHING outside the result's own
920
+ * vocabulary. Bare `'result' in value` would swallow an output object's
921
+ * siblings (`{ result: 'draft', confidence: 0.9 }` would lose `confidence`)
922
+ * and would also match an inherited `result`. @internal
923
+ */
924
+ function isTextResult(value) {
925
+ return Object.hasOwn(value, "result") && Object.keys(value).every((key) => TEXT_RESULT_KEYS.has(key));
926
+ }
927
+ /**
928
+ * Resolves ONE scripted text entry to an executor result: a function entry is
929
+ * called with the request, and the value is taken as the executor result only
930
+ * when it is one (see {@link isTextResult}). Shared with `runSeam`, whose routed
931
+ * queues follow the same entry conventions. @internal
932
+ */
933
+ async function resolveScriptedTextEntry(entry, request, info) {
934
+ const value = typeof entry === "function" ? await entry(request, info) : entry;
935
+ return require_decision.isRecord(value) && isTextResult(value) ? value : { result: value };
936
+ }
937
+ /**
938
+ * Names a pending text request in an error message. Shared with `runSeam`.
939
+ * @internal
940
+ */
941
+ function describeText(request) {
942
+ return request.name ? `'${request.name}' (model '${request.model}')` : `(model '${request.model}')`;
943
+ }
944
+ /**
945
+ * Stream semantics with no model: the whole text lands as one chunk. Shared
946
+ * with `runSeam`, whose scripted answers stream the same way. @internal
947
+ */
948
+ function emitScriptedChunk(result, info) {
949
+ const text = require_decision.isRecord(result) ? result["result"] : void 0;
950
+ if (typeof text === "string") info?.onChunk?.(text);
951
+ }
952
+ /**
953
+ * Executors that replay a script instead of calling a model. Every slot is
954
+ * provided, so any machine binds.
955
+ *
956
+ * Answers are keyed by the request's resolved name — its authored `name`, else
957
+ * the invoke `id` — and `"*"` serves anything unmatched.
958
+ * Entries for a name are consumed in order and the last one repeats forever, so
959
+ * a looping machine needs no extra option. A request the script has no route
960
+ * for throws an ordinary `Error` from inside the executor, which reaches the
961
+ * machine as an actor error.
962
+ *
963
+ * Queues are copied on creation, so the caller's arrays are never mutated and
964
+ * each call builds a fresh, independent playthrough. Entries may be plain
965
+ * values or functions of the request.
966
+ *
967
+ * @example
968
+ * ```ts
969
+ * const result = await runAgent(moderationMachine, {
970
+ * input: { comment: 'honestly this update is terrible', trust: 20 },
971
+ * executors: createScriptedExecutors({
972
+ * decisions: { moderate: [{ type: 'FLAG', reason: 'Borderline tone.' }] },
973
+ * }),
974
+ * });
975
+ * ```
976
+ *
977
+ * @example Dynamic entries
978
+ * ```ts
979
+ * createScriptedExecutors({
980
+ * text: { draft: (request) => `Draft about ${request.prompt}` },
981
+ * decisions: { route: (request) => ({ type: request.events[0]!.type }) },
982
+ * });
983
+ * ```
984
+ */
985
+ function createScriptedExecutors(script = {}) {
986
+ const decisions = toQueues(script.decisions);
987
+ const text = toQueues(script.text);
988
+ const calls = [];
989
+ const withDefaultUsage = (result) => result.usage || !script.usage ? result : {
990
+ ...result,
991
+ usage: script.usage
992
+ };
993
+ const nextText = async (kind, request, info) => {
994
+ const name = request.name ?? "*";
995
+ calls.push({
996
+ kind,
997
+ name,
998
+ input: request.input,
999
+ request
1000
+ });
1001
+ const entry = takeEntry(text, name);
1002
+ if (entry === void 0) throw noAnswer(name, text);
1003
+ return withDefaultUsage(await resolveScriptedTextEntry(entry, request, info));
1004
+ };
1005
+ return {
1006
+ calls,
1007
+ generateText: (request, info) => nextText("generateText", request, info),
1008
+ streamText: async (request, info) => {
1009
+ const name = request.name ?? "*";
1010
+ const streamEntry = script.stream?.[name] ?? script.stream?.["*"];
1011
+ if (streamEntry !== void 0) {
1012
+ calls.push({
1013
+ kind: "streamText",
1014
+ name,
1015
+ input: request.input,
1016
+ request
1017
+ });
1018
+ const resolved = typeof streamEntry === "function" ? await streamEntry(request, info) : streamEntry;
1019
+ const chunks = typeof resolved === "string" ? [resolved] : [...resolved];
1020
+ for (const chunk of chunks) info?.onChunk?.(chunk);
1021
+ return withDefaultUsage({ result: chunks.join("") });
1022
+ }
1023
+ const result = await nextText("streamText", request, info);
1024
+ emitScriptedChunk(result, info);
1025
+ return result;
1026
+ },
1027
+ decide: async (request) => {
1028
+ const name = request.name ?? request.id;
1029
+ calls.push({
1030
+ kind: "decide",
1031
+ name,
1032
+ input: request.input,
1033
+ request
1034
+ });
1035
+ const entry = takeEntry(decisions, name);
1036
+ if (entry === void 0) throw noAnswer(name, decisions);
1037
+ const value = typeof entry === "function" ? await entry(request) : entry;
1038
+ return withDefaultUsage(require_decision.isRecord(value) && typeof value["type"] !== "string" && "event" in value ? value : { event: value });
1039
+ }
1040
+ };
1041
+ }
1042
+ //#endregion
1043
+ //#region src/seam.ts
1044
+ /**
1045
+ * The seam's own answer, for scoring: the executor result's `result`.
1046
+ * @internal
1047
+ */
1048
+ async function seamOutputOf(result, request) {
1049
+ if (!require_decision.isRecord(result)) return;
1050
+ return await require_text_logic.normalizeGeneratorResult(result, `seam '${request.name ?? request.model}'`);
1051
+ }
1052
+ /**
1053
+ * Runs a machine end to end with one model call under test, and slices the run
1054
+ * at that call.
1055
+ *
1056
+ * The `before`/`after` slices are the point: `after.statePath` is the branch
1057
+ * the seam chose and `after.events` is the same question against the durable
1058
+ * log, both ready for `matchesTrajectory`. The state slice splits where the
1059
+ * state path stood when the seam answered; the event slice splits at the
1060
+ * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1061
+ * entry appended after the call was made).
1062
+ *
1063
+ * @example No API key: the seam is scripted too, so the whole thing runs offline.
1064
+ * ```ts
1065
+ * const run = await runSeam(emailDrafter, {
1066
+ * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
1067
+ * seam: { request: 'evaluatePrompt' },
1068
+ * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
1069
+ * });
1070
+ *
1071
+ * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
1072
+ * ```
1073
+ *
1074
+ * @example A candidate prompt at the seam, scored against the same rows.
1075
+ * ```ts
1076
+ * const { generateText } = createAiSdkExecutors({ models });
1077
+ * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
1078
+ * ```
1079
+ */
1080
+ async function runSeam(machine, options) {
1081
+ const { seam, candidate } = options;
1082
+ const queues = new Map(Object.entries(options.scripts ?? {}).map(([key, answers]) => [key, [...answers]]));
1083
+ const statePath = [];
1084
+ let calls = 0;
1085
+ let seamMatches = 0;
1086
+ let seamOutput;
1087
+ let seamUsage;
1088
+ const callLog = [];
1089
+ let seamReached = false;
1090
+ let callsBeforeSeam = -1;
1091
+ let seamStateAt = 0;
1092
+ let seamEventAt = 0;
1093
+ let liveEvents = 0;
1094
+ const queueKeyOf = (request) => request.name !== void 0 && queues.has(request.name) ? request.name : request.model;
1095
+ /**
1096
+ * Consumes this request's slot in the call plan, or resolves `undefined` when
1097
+ * its queue is dry. With `repeatLast`, the last entry is replayed instead of
1098
+ * running dry.
1099
+ */
1100
+ const takeScriptedSlot = async (request, info) => {
1101
+ const queue = queues.get(queueKeyOf(request));
1102
+ if (!queue?.length) return;
1103
+ return resolveScriptedTextEntry(options.repeatLast && queue.length === 1 ? queue[0] : queue.shift(), request, info);
1104
+ };
1105
+ const scriptedAnswer = async (request, info) => {
1106
+ const scripted = await takeScriptedSlot(request, info);
1107
+ if (!scripted) throw new require_text_logic.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.`);
1108
+ return scripted;
1109
+ };
1110
+ const route = async (request, info) => {
1111
+ const callIndex = calls++;
1112
+ const isSeam = request.name === seam.request && seamMatches++ === (seam.occurrence ?? 0);
1113
+ const ledger = (source) => {
1114
+ callLog.push({
1115
+ ...request.name !== void 0 ? { name: request.name } : {},
1116
+ model: request.model,
1117
+ key: queueKeyOf(request),
1118
+ source,
1119
+ seam: isSeam
1120
+ });
1121
+ };
1122
+ if (isSeam && candidate) {
1123
+ await takeScriptedSlot(request, info);
1124
+ seamReached = true;
1125
+ callsBeforeSeam = callIndex;
1126
+ seamStateAt = statePath.length;
1127
+ seamEventAt = liveEvents;
1128
+ const result = await candidate(request, info);
1129
+ seamOutput = await seamOutputOf(result, request);
1130
+ seamUsage = require_text_logic.getCallUsage(result);
1131
+ ledger("candidate");
1132
+ return result;
1133
+ }
1134
+ const scripted = await scriptedAnswer(request, info);
1135
+ ledger("script");
1136
+ if (!isSeam) return scripted;
1137
+ seamReached = true;
1138
+ callsBeforeSeam = callIndex;
1139
+ seamStateAt = statePath.length;
1140
+ seamEventAt = liveEvents;
1141
+ seamOutput = scripted.result;
1142
+ seamUsage = scripted.usage;
1143
+ return scripted;
1144
+ };
1145
+ const executors = {
1146
+ ...options.executors,
1147
+ generateText: route,
1148
+ streamText: async (request, info) => {
1149
+ const result = await route(request, info);
1150
+ emitScriptedChunk(result, info);
1151
+ return result;
1152
+ }
1153
+ };
1154
+ let snapshot;
1155
+ let event;
1156
+ const events = [];
1157
+ let result;
1158
+ const maxTurns = options.maxTurns ?? 12;
1159
+ for (let turn = 0; turn <= maxTurns; turn++) {
1160
+ result = await require_run_agent.runAgent(machine, {
1161
+ ...snapshot ? { snapshot } : { input: options.input },
1162
+ ...event ? { event } : {},
1163
+ ...options.actors ? { actors: options.actors } : {},
1164
+ executors,
1165
+ onTransition: (next, causedBy) => {
1166
+ if (turn > 0 && causedBy.type === "@xstate.init") return;
1167
+ events.push(causedBy);
1168
+ liveEvents = events.length;
1169
+ statePath.push(next.value);
1170
+ }
1171
+ });
1172
+ if (result.status !== "idle" || turn === maxTurns) break;
1173
+ const next = options.respond?.({
1174
+ snapshot: result.snapshot,
1175
+ state: result.snapshot.value,
1176
+ meta: require_text_logic.getStateMeta(result.snapshot),
1177
+ turn,
1178
+ result
1179
+ });
1180
+ if (!next) break;
1181
+ event = next;
1182
+ snapshot = result.persist();
1183
+ }
1184
+ let splitAt = events.length;
1185
+ if (seamReached) {
1186
+ splitAt = seamEventAt;
1187
+ for (let index = seamEventAt; index < events.length; index++) {
1188
+ const type = events[index].type;
1189
+ if (type.startsWith("xstate.done") || type.startsWith("xstate.error")) {
1190
+ splitAt = index;
1191
+ break;
1192
+ }
1193
+ }
1194
+ }
1195
+ const splitStateAt = seamReached ? seamStateAt : statePath.length;
1196
+ return {
1197
+ result,
1198
+ seamOutput,
1199
+ ...seamUsage !== void 0 ? { seamUsage } : {},
1200
+ callsBeforeSeam,
1201
+ calls: callLog,
1202
+ before: {
1203
+ statePath: statePath.slice(0, splitStateAt),
1204
+ events: events.slice(0, splitAt)
1205
+ },
1206
+ after: {
1207
+ statePath: statePath.slice(splitStateAt),
1208
+ events: events.slice(splitAt)
1209
+ }
1210
+ };
1211
+ }
1212
+ //#endregion
1213
+ exports.AgentLintError = AgentLintError;
1214
+ exports.AgentUnknownStateError = AgentUnknownStateError;
1215
+ exports.assertAgentMachine = assertAgentMachine;
1216
+ exports.canReach = canReach;
1217
+ exports.createScriptedExecutors = createScriptedExecutors;
1218
+ exports.explorePaths = explorePaths;
1219
+ exports.lintAgentMachine = lintAgentMachine;
1220
+ exports.matchesTrajectory = matchesTrajectory;
1221
+ exports.runSeam = runSeam;
1222
+ exports.simulateAgent = simulateAgent;