@statelyai/agent 2.0.0-alpha.10 → 2.0.0-alpha.12

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 (62) hide show
  1. package/dist/ai-sdk.cjs +62 -99
  2. package/dist/ai-sdk.d.cts +10 -117
  3. package/dist/ai-sdk.d.mts +10 -117
  4. package/dist/ai-sdk.mjs +63 -91
  5. package/dist/{decision-CQdrKc8k.mjs → decision-BezSD_YC.mjs} +120 -32
  6. package/dist/{decision-b-lkcs4L.cjs → decision-dWGhBh0P.cjs} +141 -53
  7. package/dist/errors-BQRk9eiZ.d.cts +19 -0
  8. package/dist/errors-C9rxnWbX.d.mts +19 -0
  9. package/dist/errors-CeSXQx0v.mjs +23 -0
  10. package/dist/errors-DUBBzRLP.cjs +28 -0
  11. package/dist/event-log-store-CNT_7F0V.cjs +452 -0
  12. package/dist/event-log-store-CriMgX1D.d.mts +144 -0
  13. package/dist/event-log-store-D7pWtIhb.mjs +411 -0
  14. package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
  15. package/dist/index.cjs +2844 -30
  16. package/dist/index.d.cts +1005 -12
  17. package/dist/index.d.mts +1005 -12
  18. package/dist/index.mjs +2799 -4
  19. package/dist/machines.cjs +752 -0
  20. package/dist/machines.d.cts +372 -0
  21. package/dist/machines.d.mts +372 -0
  22. package/dist/machines.mjs +741 -0
  23. package/dist/otel.cjs +268 -0
  24. package/dist/otel.d.cts +67 -0
  25. package/dist/otel.d.mts +67 -0
  26. package/dist/otel.mjs +267 -0
  27. package/dist/run-agent-B1nBa7aV.d.mts +1111 -0
  28. package/dist/run-agent-qkg0evvW.d.cts +1111 -0
  29. package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
  30. package/dist/setup-agent-DP95MFrI.cjs +1836 -0
  31. package/dist/sqlite.cjs +135 -0
  32. package/dist/sqlite.d.cts +57 -0
  33. package/dist/sqlite.d.mts +57 -0
  34. package/dist/sqlite.mjs +133 -0
  35. package/dist/{text-logic-C7WJpCIc.d.mts → text-logic-CorGzucG.d.cts} +110 -66
  36. package/dist/{text-logic-CZjyACzQ.d.cts → text-logic-DjR5PUVz.d.mts} +110 -66
  37. package/dist/{types-C9QiMjre.d.cts → types-QbEfCVny.d.cts} +1 -1
  38. package/dist/{types-qm00QF91.d.mts → types-_FXoFBGO.d.mts} +1 -1
  39. package/package.json +55 -27
  40. package/readme.md +40 -9
  41. package/schemas/agent-workflow.json +44 -26
  42. package/skills/generate-machine/SKILL.md +267 -0
  43. package/dist/cli.cjs +0 -64
  44. package/dist/cli.d.cts +0 -1
  45. package/dist/cli.d.mts +0 -1
  46. package/dist/cli.mjs +0 -65
  47. package/dist/openai-compat.cjs +0 -319
  48. package/dist/openai-compat.d.cts +0 -98
  49. package/dist/openai-compat.d.mts +0 -98
  50. package/dist/openai-compat.mjs +0 -312
  51. package/dist/run-agent-BFMkuI1F.cjs +0 -1599
  52. package/dist/run-agent-BVMd--1l.d.cts +0 -1103
  53. package/dist/run-agent-BoAOq_0Z.mjs +0 -1540
  54. package/dist/run-agent-DzYJb3CK.d.mts +0 -1103
  55. package/dist/src-D-77Ha5p.cjs +0 -1087
  56. package/dist/src-DUeIFjv-.mjs +0 -1016
  57. package/dist/utils-Dri7aeEG.d.cts +0 -108
  58. package/dist/utils-Y6GDRGGE.d.mts +0 -108
  59. package/dist/zod.cjs +0 -31
  60. package/dist/zod.d.cts +0 -30
  61. package/dist/zod.d.mts +0 -30
  62. package/dist/zod.mjs +0 -30
package/dist/index.mjs CHANGED
@@ -1,4 +1,2799 @@
1
- import { a as runAgent, c as setupAgent, i as inspectTransitions, l as appendMessages, n as IllegalResumeEventError, o as runAgentToCompletion, r as SnapshotVersionMismatchError, s as createAgentSchemas, t as AgentIdleError, u as messagesSchema } from "./run-agent-BoAOq_0Z.mjs";
2
- import { $ as validateSchemaSync, A as parseOutput, C as createTextLogic, E as isStructuredOutputSchema, G as getJsonSchemaSync, J as isStandardSchema, K as getMachineStructuralHash, Q as userMessage, T as getAgentOutputMode, U as getAgentMessages, V as assistantMessage, W as getJsonSchema, X as systemMessage, Y as persistSnapshot, Z as toolMessage, b as bindRequestExecutor, d as EVENT_TOOL_PREFIX, f as getAcceptedEvents, j as parseStructuredEnvelope, k as parseModelRef, l as renderDecisionAttempts, m as parseAgentEvent, n as PLAN_DONE_EVENT_TYPE, p as matchesEventPattern, q as getStateMeta, t as DecisionExhaustedError, u as resolveDecision, x as buildEnvelopeSchema } from "./decision-CQdrKc8k.mjs";
3
- import { a as lintAgentMachine, c as getAgentRequests, d as resolveAgentStep, f as transitionAgentStep, i as explorePaths, l as initialAgentStep, n as assertAgentMachine, o as simulateAgent, r as canReach, s as executeAgentRequest, t as AgentLintError, u as resolveAgentRequests } from "./src-DUeIFjv-.mjs";
4
- export { AgentIdleError, AgentLintError, DecisionExhaustedError, EVENT_TOOL_PREFIX, IllegalResumeEventError, PLAN_DONE_EVENT_TYPE, SnapshotVersionMismatchError, appendMessages, assertAgentMachine, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
1
+ import { t as AgentError } from "./errors-CeSXQx0v.mjs";
2
+ import { _ as resolveAgentRequests, a as AgentReplayDivergenceError, b as appendMessages, c as diffEventLogs, d as initEntry, f as replay, g as initialAgentStep, h as getInvokeEffectMetadata, i as AGENT_USAGE_EVENT_TYPE, l as getAgentEffects, m as executeAgentRequest, n as setupAgent, o as AgentReplayMachineMismatchError, p as verifyReplay, r as AGENT_INIT_EVENT_TYPE, s as createReplayEntry, t as createAgentSchemas, u as getCallUsage, v as resolveAgentStep, x as messagesSchema, y as transitionAgentStep } from "./setup-agent-DAZZSjDS.mjs";
3
+ import { A as parseStructuredEnvelope, D as normalizeGeneratorResult, E as isTextLogic, F as getMachineSuspensionPredicate, G as getJsonSchemaSync, H as findNonSerializableContextPaths, I as getRegisteredAgentExecutionOptions, J as isStandardSchema, K as getMachineStructuralHash, L as isUnboundPlaceholder, N as executorBoundLogics, O as parseModelRef, P as getMachineStaticTransitionTargets, Q as userMessage, S as createTextLogic, T as getAgentOutputMode, U as getAgentMessages, V as assistantMessage, W as getJsonSchema, X as systemMessage, Y as persistSnapshot, Z as toolMessage, b as buildEnvelopeSchema, c as isPlanLogic, d as getAcceptedEvents, f as parseAgentEvent, g as INTERPRET_SOURCE, k as parseOutput, l as renderDecisionAttempts, m as AGENT_USAGE_TOKEN_FIELDS, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, p as sanitizeEventToolName, q as getStateMeta, r as advancePlanLedger, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision, w as extractCallUsage, y as bindRequestExecutor } from "./decision-BezSD_YC.mjs";
4
+ import { a as assertEventLogStoreConformance, i as assertAgentLogEntry, n as AgentEventLogConflictError, o as assertJsonSerializable, r as NonSerializableAgentEventError, s as createInMemoryEventLogStore, t as AGENT_EVENT_SCHEMA_VERSION } from "./event-log-store-D7pWtIhb.mjs";
5
+ import { createActor, createAsyncLogic, getNextTransitions } from "xstate";
6
+ //#region src/internal/state-request-pass.ts
7
+ async function runTextPhase(stateRequest, baseMessages, deps) {
8
+ const { model, system } = stateRequest;
9
+ const id = stateRequest.id ?? deps.nextRequestId();
10
+ const promptMessage = userMessage(stateRequest.prompt);
11
+ if (stateRequest.kind === "decision") return {
12
+ stateRequest,
13
+ id,
14
+ output: void 0,
15
+ appended: [promptMessage]
16
+ };
17
+ if (!deps.generateText) throw new Error("runAgent: a getRequests request needs a 'generateText' executor (or use kind: 'decision').");
18
+ const request = {
19
+ model,
20
+ ...system !== void 0 ? { system } : {},
21
+ messages: [...baseMessages, promptMessage],
22
+ tools: {}
23
+ };
24
+ const agentRequest = {
25
+ kind: "text",
26
+ id,
27
+ src: INTERPRET_SOURCE,
28
+ mode: "generate",
29
+ input: request,
30
+ tools: {},
31
+ events: []
32
+ };
33
+ deps.consumeModelCall();
34
+ deps.onTrace?.({
35
+ type: "request.start",
36
+ request: agentRequest
37
+ });
38
+ let output;
39
+ try {
40
+ const raw = await deps.generateText(request, { signal: deps.signal });
41
+ output = await normalizeGeneratorResult(raw, id, { request });
42
+ const rawReasoning = raw?.reasoning;
43
+ const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
44
+ const usage = extractCallUsage(raw);
45
+ if (usage) deps.recordUsage?.(usage);
46
+ deps.onResult?.(agentRequest, {
47
+ output,
48
+ raw
49
+ });
50
+ deps.onTrace?.({
51
+ type: "request.end",
52
+ request: agentRequest,
53
+ output,
54
+ raw,
55
+ ...reasoning !== void 0 ? { reasoning } : {},
56
+ ...usage !== void 0 ? { usage } : {}
57
+ });
58
+ } catch (error) {
59
+ deps.onTrace?.({
60
+ type: "request.error",
61
+ request: agentRequest,
62
+ error
63
+ });
64
+ throw error;
65
+ }
66
+ return {
67
+ stateRequest,
68
+ id,
69
+ output,
70
+ appended: [promptMessage, assistantMessage(typeof output === "string" ? output : JSON.stringify(output))]
71
+ };
72
+ }
73
+ async function runAdvancePhase(plan, deps) {
74
+ const { stateRequest, id, output } = plan;
75
+ const { model, system } = stateRequest;
76
+ deps.appendToLog(...plan.appended);
77
+ if (stateRequest.kind !== "decision" && stateRequest.onDone !== void 0) {
78
+ const snapshot = deps.getSnapshot();
79
+ const resolved = typeof stateRequest.onDone === "function" ? stateRequest.onDone({
80
+ output,
81
+ snapshot,
82
+ messages: deps.messages
83
+ }) : stateRequest.onDone;
84
+ if (!resolved) return false;
85
+ const acceptedTypes = getAcceptedEvents(snapshot, { schemas: deps.schemas }).map((descriptor) => descriptor.type);
86
+ if (!acceptedTypes.includes(resolved.type)) throw new Error(`runAgent: getRequests request '${id}' resolved onDone to event '${resolved.type}', which the current state does not accept. Accepted: ${acceptedTypes.join(", ") || "(none)"}.`);
87
+ if (!snapshot.can(resolved)) return false;
88
+ deps.send(resolved);
89
+ return true;
90
+ }
91
+ const events = getAcceptedEvents(deps.getSnapshot(), {
92
+ schemas: deps.schemas,
93
+ ...stateRequest.allowedEvents ? { eventTypes: stateRequest.allowedEvents } : {}
94
+ });
95
+ if (events.length === 0) return false;
96
+ if (!deps.decide) throw new Error(`runAgent: a getRequests request without 'onDone' needs a 'decide' executor to choose between events ${events.map((descriptor) => `'${descriptor.type}'`).join(", ")}. Provide request.onDone for deterministic advancement, or a 'decide' executor.`);
97
+ const chosen = await resolveDecision({
98
+ kind: "decision",
99
+ id,
100
+ model,
101
+ ...system !== void 0 ? { system } : {},
102
+ messages: [...deps.messages],
103
+ events,
104
+ attempts: []
105
+ }, deps.decide, {
106
+ signal: deps.signal,
107
+ canTake: (event) => deps.getSnapshot().can(event)
108
+ });
109
+ if (deps.isSettled()) return false;
110
+ deps.appendToLog(assistantMessage(`[chose: ${chosen.type}]`));
111
+ deps.send(chosen);
112
+ return true;
113
+ }
114
+ /**
115
+ * Executes one getRequests pass: all text calls concurrently against the
116
+ * pass-start log, then per-request advancement sequentially in request
117
+ * order. Returns whether ANY request sent an event — the host settles idle
118
+ * when none did (otherwise an unchanged snapshot would re-produce the same
119
+ * pass forever). Stops early (skipping remaining appends/sends) once
120
+ * {@link StateRequestPassDeps.isSettled} reports the run is over. Throws on
121
+ * executor/`onDone` errors — the host maps them to its error settle.
122
+ */
123
+ async function runStateRequestPass(requests, deps) {
124
+ const baseMessages = [...deps.messages];
125
+ const plans = await Promise.all(requests.map((stateRequest) => runTextPhase(stateRequest, baseMessages, deps)));
126
+ let sentAny = false;
127
+ for (const plan of plans) {
128
+ if (deps.isSettled()) break;
129
+ sentAny = await runAdvancePhase(plan, deps) || sentAny;
130
+ }
131
+ return { sentAny };
132
+ }
133
+ //#endregion
134
+ //#region src/run-agent.ts
135
+ /**
136
+ * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
137
+ * `type` the restored state cannot accept (a type-level check via
138
+ * {@link getAcceptedEvents}). A programmer/integration error, in the same
139
+ * class as runAgent's bind-time throws — it throws rather than settling an
140
+ * `error` result. A type-legal event a guard rejects is NOT this error (the
141
+ * machine simply takes no transition). Opt out with
142
+ * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
143
+ */
144
+ var AgentIllegalResumeEventError = class extends AgentError {
145
+ eventType;
146
+ acceptedTypes;
147
+ constructor(eventType, acceptedTypes) {
148
+ super("illegal-resume-event", `runAgent: cannot resume with event '${eventType}' — the restored state does not accept it. Accepted event types: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
149
+ this.name = "AgentIllegalResumeEventError";
150
+ this.eventType = eventType;
151
+ this.acceptedTypes = acceptedTypes;
152
+ }
153
+ };
154
+ /**
155
+ * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
156
+ * `agentMeta.version` differs from the current machine's version, under the
157
+ * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
158
+ * structural fingerprint of the machine changed since the snapshot was
159
+ * persisted (a state/transition/invoke was added, removed, or retargeted), so
160
+ * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
161
+ * `to` the current machine's.
162
+ */
163
+ var AgentSnapshotVersionMismatchError = class extends AgentError {
164
+ from;
165
+ to;
166
+ machineId;
167
+ constructor(from, to, machineId) {
168
+ super("snapshot-version-mismatch", `runAgent: cannot resume snapshot stamped with machine version '${from}' against machine '${machineId}' at version '${to}' — the machine's structure changed since the snapshot was persisted. Provide options.migrateSnapshot to adapt it, or set options.onVersionMismatch to 'warn'/'ignore' to proceed anyway.`);
169
+ this.name = "AgentSnapshotVersionMismatchError";
170
+ this.from = from;
171
+ this.to = to;
172
+ this.machineId = machineId;
173
+ }
174
+ };
175
+ /**
176
+ * Thrown by {@link generateResult} when the run settles `idle` instead of
177
+ * `done`: the machine paused for external input. Carries the idle `snapshot`
178
+ * and `acceptedTypes` (the event types that could resume it, via
179
+ * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
180
+ * expected outcome you handle.
181
+ */
182
+ var AgentIdleError = class extends AgentError {
183
+ snapshot;
184
+ acceptedTypes;
185
+ constructor(snapshot, acceptedTypes) {
186
+ super("agent-idle", `generateResult: the machine paused (idle) instead of completing. Resume it by calling runAgent with one of these events: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
187
+ this.name = "AgentIdleError";
188
+ this.snapshot = snapshot;
189
+ this.acceptedTypes = acceptedTypes;
190
+ }
191
+ };
192
+ /**
193
+ * The version of the {@link AgentTraceEvent} envelope every trace event carries
194
+ * as `schemaVersion`. Bumped only on a breaking change to the envelope or any
195
+ * payload shape, so a consumer can gate on it. Emitted identically by
196
+ * {@link runAgent}, {@link provideExecutors}' `onTrace`, and
197
+ * {@link traceTransitions}.
198
+ */
199
+ const AGENT_TRACE_SCHEMA_VERSION = 1;
200
+ const TRACE_ENVELOPE_KEYS = [
201
+ "schemaVersion",
202
+ "runId",
203
+ "seq",
204
+ "timestamp",
205
+ "machineId",
206
+ "machineVersion",
207
+ "type",
208
+ "status",
209
+ "cause",
210
+ "eventId",
211
+ "reasoning",
212
+ "chunk"
213
+ ];
214
+ /**
215
+ * Best-effort JSON projection of an arbitrary value. Never throws: functions,
216
+ * symbols, `undefined`, and cyclic back-references are DROPPED (array holes
217
+ * become `null`), non-finite numbers become `null`, `bigint`s become strings,
218
+ * `Error`s become `{ name, message, stack?, code? }`, and anything with a
219
+ * `toJSON()` (e.g. `Date`) is projected through it — the same losses a
220
+ * `JSON.parse(JSON.stringify(...))` round-trip incurs, minus the throws.
221
+ */
222
+ function toJsonValue(value, ancestors) {
223
+ if (value === null) return null;
224
+ const type = typeof value;
225
+ if (type === "string" || type === "boolean") return value;
226
+ if (type === "number") return Number.isFinite(value) ? value : null;
227
+ if (type === "bigint") return value.toString();
228
+ if (type !== "object") return;
229
+ const object = value;
230
+ if (ancestors.includes(object)) return;
231
+ const nextAncestors = [...ancestors, object];
232
+ if (object instanceof Error) {
233
+ const serialized = {
234
+ name: object.name,
235
+ message: object.message
236
+ };
237
+ if (typeof object.stack === "string") serialized.stack = object.stack;
238
+ const code = object.code;
239
+ if (typeof code === "string") serialized.code = code;
240
+ const cause = toJsonValue(object.cause, nextAncestors);
241
+ if (cause !== void 0) serialized.cause = cause;
242
+ return serialized;
243
+ }
244
+ const toJSON = object.toJSON;
245
+ if (typeof toJSON === "function") return toJsonValue(toJSON.call(object), nextAncestors);
246
+ if (Array.isArray(object)) return object.map((item) => toJsonValue(item, nextAncestors) ?? null);
247
+ const out = {};
248
+ for (const [key, item] of Object.entries(object)) {
249
+ const serializedItem = toJsonValue(item, nextAncestors);
250
+ if (serializedItem !== void 0) out[key] = serializedItem;
251
+ }
252
+ return out;
253
+ }
254
+ /**
255
+ * Projects an {@link AgentTraceEvent} into a guaranteed JSON-safe envelope —
256
+ * the form the trace stream is actually sold for (one `JSON.stringify` per line
257
+ * in a JSONL file). Live values are sanitized rather than trusted:
258
+ *
259
+ * - Snapshots (`run.start`, `machine.transition`, `run.end`) go through the
260
+ * same JSON round-trip as {@link persistSnapshot}, so what lands on disk is
261
+ * what a resume would see.
262
+ * - `request.end`'s `raw` (a provider SDK object, frequently cyclic) is DROPPED
263
+ * unless `includeRaw` is set, in which case it is sanitized like everything
264
+ * else.
265
+ * - Non-serializable values anywhere (functions, symbols, `undefined`, cyclic
266
+ * back-references) are dropped; `Error`s become `{ name, message, stack?,
267
+ * code? }` instead of `{}`. Nothing throws.
268
+ *
269
+ * @example
270
+ * ```ts
271
+ * await appendFile('trace.jsonl', JSON.stringify(serializeTraceEvent(event)) + '\n');
272
+ * ```
273
+ */
274
+ function serializeTraceEvent(event, options = {}) {
275
+ const out = {};
276
+ for (const [key, value] of Object.entries(event)) {
277
+ if (key === "raw" && !options.includeRaw) continue;
278
+ if (TRACE_ENVELOPE_KEYS.includes(key)) {
279
+ if (value !== void 0) out[key] = value;
280
+ continue;
281
+ }
282
+ const serialized = toJsonValue(value, []);
283
+ if (serialized !== void 0) out[key] = serialized;
284
+ }
285
+ return out;
286
+ }
287
+ let nextRunAgentTraceId = 1;
288
+ var AgentMaxModelCallsExceededError = class extends AgentError {
289
+ constructor() {
290
+ super("max-model-calls-exceeded", "runAgent exceeded maxModelCalls.");
291
+ this.name = "AgentMaxModelCallsExceededError";
292
+ }
293
+ };
294
+ function wrapsDecisionExhausted(error) {
295
+ let current = error;
296
+ for (let depth = 0; depth < 10 && current != null; depth++) {
297
+ if (current instanceof AgentDecisionExhaustedError) return true;
298
+ current = current.cause;
299
+ }
300
+ return false;
301
+ }
302
+ /**
303
+ * Recursively collects every invoke's `src` from raw machine config (spike
304
+ * S6: `machine.config` preserves authored srcs; the built `machine.root`
305
+ * normalizes object srcs to synthetic string ids and loses the distinction
306
+ * this walk needs). Function-valued `src` resolvers are dynamic and are not
307
+ * statically analyzable, so they are skipped (pass-through, like any other
308
+ * non-agent actor).
309
+ */
310
+ function collectConfiguredInvokeSrcs(stateConfig, stateName, out) {
311
+ if (!stateConfig) return;
312
+ const invokes = stateConfig.invoke === void 0 ? [] : Array.isArray(stateConfig.invoke) ? stateConfig.invoke : [stateConfig.invoke];
313
+ for (const invokeConfig of invokes) {
314
+ const src = invokeConfig?.src;
315
+ if (typeof src === "string" || src && typeof src === "object") out.push({
316
+ stateName,
317
+ src
318
+ });
319
+ }
320
+ for (const [childName, childConfig] of Object.entries(stateConfig.states ?? {})) collectConfiguredInvokeSrcs(childConfig, `${stateName}.${childName}`, out);
321
+ }
322
+ /**
323
+ * Duck-types a state machine actor logic (an invoked child machine) vs. any
324
+ * other actor logic. xstate's `StateMachine` carries `.config`, `.root`, and
325
+ * a `.provide(...)` method plus a `sources.actors` map — this
326
+ * combination is unique to machines and survives the dual-package/version
327
+ * boundary an `instanceof` check would not. Used to descend the bind-time
328
+ * walk into invoked child machines (their internal agent requests are opaque
329
+ * to the parent-level source walk otherwise).
330
+ */
331
+ function isStateMachine(logic) {
332
+ return !!logic && typeof logic === "object" && "config" in logic && "root" in logic && typeof logic.provide === "function" && typeof logic.sources === "object" && !!logic.sources?.actors;
333
+ }
334
+ /**
335
+ * Fails fast (throws) at bind time — before any actor runs — when the
336
+ * machine invokes an agent actor `runAgent` cannot execute. See §3.2 point 2.
337
+ *
338
+ * Recurses into invoked child state machines (arbitrarily deep). A child
339
+ * machine's agent requests reached through string-keyed invoke srcs DO inherit
340
+ * the parent runAgent's `generateText`/`streamText`/`decide` executors —
341
+ * runAgent rebinds them with the same host-backed wrappers (see
342
+ * {@link rebindChildMachine}) — so the only remaining bind-time errors are: a
343
+ * required executor kind missing entirely (naming the invoke chain and src),
344
+ * and an unbound request reached through a direct-object invoke src that can't
345
+ * be rebound ({@link unrebindableChildRequestError}). A request that carries
346
+ * its own executor (`.withExecutor(...)`, tracked in `executorBoundLogics`)
347
+ * always runs itself; explicit binding shadows inheritance.
348
+ */
349
+ function assertBindable(machine, effectiveSources, options) {
350
+ assertMachineBindable(machine, effectiveSources, options, {
351
+ isChild: false,
352
+ childPath: "",
353
+ rebindable: true,
354
+ visited: new Set([machine])
355
+ });
356
+ }
357
+ function assertMachineBindable(machine, effectiveSources, options, ctx) {
358
+ const invokes = [];
359
+ collectConfiguredInvokeSrcs(machine.config, machine.config.id ?? "(root)", invokes);
360
+ const where = ctx.isChild ? `child machine '${ctx.childPath}' state` : "state";
361
+ for (const { stateName, src } of invokes) {
362
+ if (typeof src !== "string") {
363
+ if (isStateMachine(src)) {
364
+ assertChildMachineBindable(src, src, stateName, options, ctx);
365
+ continue;
366
+ }
367
+ if ((isTextLogic(src) || isDecisionLogic(src) || isPlanLogic(src)) && !executorBoundLogics.has(src)) throw new Error(`runAgent: ${where} '${stateName}' invokes a direct-object actor logic (kind: '${src.kind}'). Direct-object invoke srcs cannot be rebound by runAgent — either call '.withExecutor(...)' on the logic before invoking it, or register it as a string-keyed actor source instead (machine.provide({ actors: { name: logic } })) and invoke it by name.`);
368
+ continue;
369
+ }
370
+ const logic = effectiveSources[src];
371
+ if (logic === void 0) throw new Error(`runAgent: ${where} '${stateName}' invokes unregistered actor source '${src}'. Provide it via machine.provide({ actors: { '${src}': ... } }) or runAgent(machine, { actors: { '${src}': ... } }).`);
372
+ if (isStateMachine(logic)) {
373
+ assertChildMachineBindable(logic, src, stateName, options, ctx);
374
+ continue;
375
+ }
376
+ if (src === "agent.userInput") continue;
377
+ if (isDecisionLogic(logic)) {
378
+ if (executorBoundLogics.has(logic)) continue;
379
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "decision");
380
+ if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes decision source '${src}' but no 'decide' executor was provided to runAgent(...).`);
381
+ continue;
382
+ }
383
+ if (isPlanLogic(logic)) {
384
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "plan");
385
+ if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes plan source '${src}' but no 'decide' executor was provided to runAgent(...).`);
386
+ continue;
387
+ }
388
+ if (isTextLogic(logic)) {
389
+ if (executorBoundLogics.has(logic)) continue;
390
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, logic.mode === "stream" ? "streaming text" : "text");
391
+ if (logic.mode === "stream" && !options.hasStreamText) throw new Error(`runAgent: ${where} '${stateName}' invokes streaming text source '${src}' but no 'streamText' executor was provided to runAgent(...).`);
392
+ if (logic.mode !== "stream" && !options.hasGenerateText) throw new Error(`runAgent: ${where} '${stateName}' invokes text source '${src}' but no 'generateText' executor was provided to runAgent(...).`);
393
+ continue;
394
+ }
395
+ if (isUnboundPlaceholder(logic)) throw new Error(`runAgent: ${where} '${stateName}' invokes actor source '${src}', which has no host execution. Provide it via machine.provide({ actors: { '${src}': ... } }) or runAgent(machine, { actors: { '${src}': ... } }).`);
396
+ }
397
+ }
398
+ /** Descends the bind-time walk into an invoked child state machine, guarding
399
+ * against a machine that (transitively) invokes itself. */
400
+ function assertChildMachineBindable(childMachine, childSrc, stateName, options, ctx) {
401
+ if (ctx.visited.has(childMachine)) return;
402
+ const childName = typeof childSrc === "string" ? childSrc : childMachine.config.id ?? "(child machine)";
403
+ const childPath = ctx.childPath ? `${ctx.childPath} > ${childName}` : childName;
404
+ const childSources = childMachine.sources.actors;
405
+ assertMachineBindable(childMachine, childSources, options, {
406
+ isChild: true,
407
+ childPath,
408
+ rebindable: ctx.rebindable && typeof childSrc === "string",
409
+ visited: new Set([...ctx.visited, childMachine])
410
+ });
411
+ }
412
+ /** The loud bind-time error for an unbound agent request reached under a
413
+ * direct-object invoke src, which runAgent cannot rebind (only string-keyed
414
+ * sources can be swapped via `.provide`). Names the invoke chain AND the
415
+ * request src, and spells out the `.withExecutor`/string-keyed remedy. Note:
416
+ * requests reachable through string-keyed srcs at any depth DO inherit
417
+ * runAgent's executors — this error is only for the unrebindable direct-object
418
+ * case. */
419
+ function unrebindableChildRequestError(childPath, stateName, requestSrc, kind) {
420
+ return /* @__PURE__ */ new Error(`runAgent: child machine '${childPath}' (state '${stateName}') invokes ${kind} source '${requestSrc}', which has no host execution and is reached through a direct-object invoke src that runAgent cannot rebind. Requests reached through string-keyed actor sources inherit runAgent's generateText/streamText/decide executors automatically; a direct-object child machine does not. Either bind the request with its own executor (requestLogic.withExecutor(...)), or register the child as a string-keyed actor source (machine.provide({ actors: { <child>: childMachine } })) and invoke it by name.`);
421
+ }
422
+ /**
423
+ * True when the snapshot's active states declare a transition for the reserved
424
+ * `'@agent.usage'` type EXPLICITLY. A catch-all `on: { '*': … }` deliberately
425
+ * does not count: a wildcard is a machine's own event vocabulary, not an
426
+ * opt-in to a library-reserved event, and `snapshot.can(event)` alone cannot
427
+ * tell the two apart (it answers "would this event be taken?", which a
428
+ * wildcard makes true for everything). Gating delivery on the explicit
429
+ * declaration is what keeps `@agent.usage` opt-in by construction — and keeps
430
+ * a wildcard machine's context and event log byte-identical to a run without
431
+ * the feature. @internal
432
+ */
433
+ function declaresUsageTransition(snapshot) {
434
+ return getNextTransitions(snapshot).some((transition) => transition.eventType === AGENT_USAGE_EVENT_TYPE);
435
+ }
436
+ /** Reads the durable invoke id/src off the async actor's own ref (`self`). */
437
+ function selfIdAndSrc(self) {
438
+ const ref = self;
439
+ return {
440
+ id: typeof ref?.id === "string" ? ref.id : "",
441
+ src: typeof ref?.src === "string" ? ref.src : ""
442
+ };
443
+ }
444
+ /**
445
+ * The machine actor that INVOKED a decision/plan request — the actor whose
446
+ * live snapshot supplies the candidate events and drives `canTake`/`send`.
447
+ * For a top-level request this is the root actor (identity-equal to
448
+ * `runCtx.actorHolder.actorRef`); for a request inside an invoked child
449
+ * machine it is that child's actor, so a child decision/plan reads and drives
450
+ * the CHILD's snapshot — not the root's. Read off `self._parent`, with the
451
+ * root actor as a fallback.
452
+ */
453
+ function invokingActorOf(self, runCtx) {
454
+ return self?._parent ?? runCtx.actorHolder.actorRef;
455
+ }
456
+ /**
457
+ * The shared text/stream emission helper: binds a {@link TextLogic} to
458
+ * `runCtx`'s executor and constructs the `request.start` / `stream.chunk` /
459
+ * `request.end` (incl. the lifted `reasoning`) / `request.error` trace payloads.
460
+ * Used by both `runAgent` and `provideExecutors` so the two paths produce
461
+ * identical event shapes by construction. @internal
462
+ */
463
+ function wrapTextLogicForRunAgent(logic, runCtx) {
464
+ return logic.withExecutor(async ({ request, self, signal }) => {
465
+ const { id, src } = selfIdAndSrc(self);
466
+ const executor = logic.mode === "stream" ? runCtx.streamText : runCtx.generateText;
467
+ if (!executor) throw new Error(`runAgent: no '${logic.mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
468
+ const requestWithTools = {
469
+ ...request,
470
+ tools: request.tools ?? {}
471
+ };
472
+ const agentRequest = {
473
+ kind: "text",
474
+ id,
475
+ src,
476
+ mode: logic.mode,
477
+ input: request,
478
+ tools: requestWithTools.tools,
479
+ events: []
480
+ };
481
+ runCtx.consumeModelCall();
482
+ runCtx.onTrace?.({
483
+ type: "request.start",
484
+ request: agentRequest
485
+ }, self);
486
+ try {
487
+ const raw = await executor(requestWithTools, {
488
+ onChunk: (chunk) => {
489
+ runCtx.onTrace?.({
490
+ type: "stream.chunk",
491
+ request: agentRequest,
492
+ chunk
493
+ }, self);
494
+ runCtx.onChunk?.(chunk, { request: agentRequest });
495
+ },
496
+ signal,
497
+ ...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
498
+ ...id !== "" ? { requestId: id } : {}
499
+ });
500
+ const output = await normalizeGeneratorResult(raw, id, {
501
+ request,
502
+ onChunk: (chunk) => {
503
+ runCtx.onTrace?.({
504
+ type: "stream.chunk",
505
+ request: agentRequest,
506
+ chunk
507
+ }, self);
508
+ runCtx.onChunk?.(chunk, { request: agentRequest });
509
+ }
510
+ });
511
+ const rawReasoning = raw?.reasoning;
512
+ const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
513
+ const usage = extractCallUsage(raw);
514
+ if (usage) runCtx.recordUsage?.(usage, {
515
+ kind: "text",
516
+ ...id !== "" ? { id } : {},
517
+ ...src !== "" ? { src } : {},
518
+ model: request.model,
519
+ ...request.name !== void 0 ? { name: request.name } : {}
520
+ }, self);
521
+ runCtx.onResult?.(agentRequest, {
522
+ output,
523
+ raw
524
+ });
525
+ runCtx.onTrace?.({
526
+ type: "request.end",
527
+ request: agentRequest,
528
+ output,
529
+ raw,
530
+ ...reasoning !== void 0 ? { reasoning } : {},
531
+ ...usage !== void 0 ? { usage } : {}
532
+ }, self);
533
+ return { output };
534
+ } catch (error) {
535
+ runCtx.onTrace?.({
536
+ type: "request.error",
537
+ request: agentRequest,
538
+ error
539
+ }, self);
540
+ throw error;
541
+ }
542
+ });
543
+ }
544
+ function createCountingDecide(runCtx, self, kind = "decision") {
545
+ return async (attemptRequest) => {
546
+ runCtx.consumeModelCall();
547
+ runCtx.onTrace?.({
548
+ type: "request.start",
549
+ request: attemptRequest
550
+ }, self);
551
+ try {
552
+ const result = await runCtx.decide(runCtx.runId !== void 0 ? {
553
+ ...attemptRequest,
554
+ runId: runCtx.runId
555
+ } : attemptRequest);
556
+ const usage = extractCallUsage(result);
557
+ if (usage) {
558
+ const { src } = selfIdAndSrc(self);
559
+ runCtx.recordUsage?.(usage, {
560
+ kind,
561
+ ...attemptRequest.id ? { id: attemptRequest.id } : {},
562
+ ...src !== "" ? { src } : {},
563
+ model: attemptRequest.model
564
+ }, self);
565
+ }
566
+ runCtx.onResult?.(attemptRequest, {
567
+ output: result.event,
568
+ raw: result
569
+ });
570
+ runCtx.onTrace?.({
571
+ type: "request.end",
572
+ request: attemptRequest,
573
+ output: result.event,
574
+ raw: result,
575
+ ...usage !== void 0 ? { usage } : {}
576
+ }, self);
577
+ return result;
578
+ } catch (error) {
579
+ runCtx.onTrace?.({
580
+ type: "request.error",
581
+ request: attemptRequest,
582
+ error
583
+ }, self);
584
+ throw error;
585
+ }
586
+ };
587
+ }
588
+ /**
589
+ * Builds the decision actor logic runAgent installs in place of a
590
+ * `DecisionLogic`/`agent.decide` source. `DecisionLogic.withExecutor(...)`
591
+ * can only swap the innermost per-attempt executor — the `resolveDecision(...)`
592
+ * call (and its `canTake`) is hardwired inside the original logic's `run`.
593
+ * To supply `canTake` (mode-3, §2.6), runAgent instead builds a fresh async
594
+ * logic here that calls `resolveDecision` itself, reusing `logic.request(...)`
595
+ * to build the request the same way the original logic would have.
596
+ *
597
+ * On success it SENDS the chosen event to the invoking actor (auto-delivery,
598
+ * mirroring {@link createRunAgentPlanLogic}) and then completes with that event
599
+ * as its output — so callers never wire an `onDone` to deliver it. See the
600
+ * send-then-complete note inside `run` for how exit-cancels-invoke interacts
601
+ * with `onDone`.
602
+ */
603
+ function createRunAgentDecisionLogic(logic, runCtx) {
604
+ const decisionLogic = createAsyncLogic({ run: async ({ input, signal, self }) => {
605
+ if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
606
+ const { id } = selfIdAndSrc(self);
607
+ const declaredEventTypes = logic.allowedEventTypes?.(input);
608
+ await Promise.resolve();
609
+ const actorRef = invokingActorOf(self, runCtx);
610
+ const events = actorRef ? getAcceptedEvents(actorRef.getSnapshot(), {
611
+ schemas: runCtx.schemas,
612
+ eventTypes: declaredEventTypes
613
+ }) : [];
614
+ const chosen = await resolveDecision({
615
+ ...logic.request(input),
616
+ id,
617
+ events
618
+ }, createCountingDecide(runCtx, self), {
619
+ maxRetries: logic.maxRetries,
620
+ signal,
621
+ canTake: (event) => actorRef ? actorRef.getSnapshot().can(event) : true
622
+ });
623
+ actorRef?.send(chosen);
624
+ await Promise.resolve();
625
+ return chosen;
626
+ } });
627
+ return Object.assign(decisionLogic, {
628
+ kind: "statelyai.decisionLogic",
629
+ maxRetries: logic.maxRetries,
630
+ request: logic.request,
631
+ withExecutor: (nextExecute) => createRunAgentDecisionLogic(logic.withExecutor(nextExecute), runCtx)
632
+ });
633
+ }
634
+ /**
635
+ * Builds the plan actor logic runAgent installs in place of the `agent.plan`
636
+ * builtin: iterated {@link resolveDecision}. Each step re-reads the live
637
+ * snapshot (so the candidate set reflects everything applied so far), asks
638
+ * the `decide` executor for one legal event with the same validation/retry
639
+ * loop a decision gets, and sends it to the machine. The loop ends on a
640
+ * `stopOn` event, at `maxSteps`, when no legal candidate remains, or when an
641
+ * applied event exits the invoking state (xstate cancels this invoke — the
642
+ * machine simply moves on and the pending output is discarded).
643
+ *
644
+ * The invoke's `input` is resolved once, so the prompt cannot re-render
645
+ * context between steps; instead the applied trail is appended to the prompt
646
+ * each step so the model can see plan progress.
647
+ */
648
+ function createRunAgentPlanLogic(logic, runCtx) {
649
+ const planLogic = createAsyncLogic({ run: async ({ input, signal, self }) => {
650
+ if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
651
+ const { id } = selfIdAndSrc(self);
652
+ const stopOn = new Set(input.stopOn ?? []);
653
+ const countingDecide = createCountingDecide(runCtx, self, "plan");
654
+ const base = logic.request(input);
655
+ let ledger = initialPlanLedger(logic, input);
656
+ const end = (stopped) => {
657
+ ledger = advancePlanLedger(logic, ledger, {
658
+ type: "plan.ended",
659
+ stopped
660
+ });
661
+ return ledger.output;
662
+ };
663
+ await Promise.resolve();
664
+ const invokingActor = invokingActorOf(self, runCtx);
665
+ while (ledger.context.stepsRemaining > 0) {
666
+ const actorRef = invokingActor;
667
+ if (!actorRef || signal.aborted) break;
668
+ const machineEvents = getAcceptedEvents(actorRef.getSnapshot(), {
669
+ schemas: runCtx.schemas,
670
+ eventTypes: logic.allowedEventTypes(input)
671
+ });
672
+ if (machineEvents.length === 0) return end("no-legal-events");
673
+ const doneDescriptor = {
674
+ type: PLAN_DONE_EVENT_TYPE,
675
+ toolName: sanitizeEventToolName(PLAN_DONE_EVENT_TYPE)
676
+ };
677
+ const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, doneDescriptor];
678
+ const applied = ledger.context.applied;
679
+ const trail = applied.length === 0 ? "" : `\n\nEvents already applied in this plan, in order:\n${applied.map((step) => JSON.stringify(step)).join("\n")}\nContinue from here; do not repeat applied events.`;
680
+ const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${PLAN_DONE_EVENT_TYPE}'.`;
681
+ const chosen = await resolveDecision({
682
+ ...base,
683
+ id: `${id}[${applied.length}]`,
684
+ events,
685
+ prompt: `${base.prompt ?? ""}${trail}${doneHint}`,
686
+ attempts: []
687
+ }, countingDecide, {
688
+ maxRetries: input.maxRetries ?? logic.maxRetries,
689
+ signal,
690
+ canTake: (event) => {
691
+ if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
692
+ return invokingActor ? invokingActor.getSnapshot().can(event) : true;
693
+ }
694
+ });
695
+ if (chosen.type === "agent.plan.done") return end("done");
696
+ actorRef.send(chosen);
697
+ ledger = advancePlanLedger(logic, ledger, {
698
+ type: "plan.applied",
699
+ event: chosen
700
+ });
701
+ await Promise.resolve();
702
+ if (stopOn.has(chosen.type)) return end("stop-event");
703
+ }
704
+ return end("max-steps");
705
+ } });
706
+ return Object.assign(planLogic, {
707
+ kind: "statelyai.planLogic",
708
+ maxRetries: logic.maxRetries,
709
+ request: logic.request,
710
+ allowedEventTypes: logic.allowedEventTypes
711
+ });
712
+ }
713
+ /**
714
+ * The set of string-keyed actor `src`s the machine's own config invokes
715
+ * (top-level, recursing into child STATES but not into invoked child
716
+ * machines). {@link provideExecutors} uses it to require an executor only for a
717
+ * source the machine actually invokes — the always-registered `agent.*`
718
+ * builtins that go unused must not force their executors to be supplied.
719
+ * @internal
720
+ */
721
+ function getConfiguredInvokeSrcs(machine) {
722
+ const invokes = [];
723
+ collectConfiguredInvokeSrcs(machine.config, machine.config.id ?? "(root)", invokes);
724
+ const srcs = /* @__PURE__ */ new Set();
725
+ for (const { src } of invokes) if (typeof src === "string") srcs.add(src);
726
+ return srcs;
727
+ }
728
+ const rootTraceRegistry = /* @__PURE__ */ new WeakMap();
729
+ let nextProvideRunId = 1;
730
+ /** Walks `self._parent` from an invoked async leaf actor up to its root actor. */
731
+ function rootActorOf(self) {
732
+ let ref = self;
733
+ if (!ref) return;
734
+ while (ref._parent) ref = ref._parent;
735
+ return ref;
736
+ }
737
+ /** The per-root envelope state, minted on first use (runId `run_<n>`, matching runAgent). */
738
+ function rootTraceState(root) {
739
+ let state = rootTraceRegistry.get(root);
740
+ if (!state) {
741
+ const logic = root.logic;
742
+ const machineId = (logic?.config)?.id ?? logic?.id ?? "(machine)";
743
+ const machineVersion = logic ? getMachineStructuralHash(logic) : "";
744
+ state = {
745
+ runId: `run_${nextProvideRunId++}`,
746
+ seq: 0,
747
+ machineId,
748
+ machineVersion
749
+ };
750
+ rootTraceRegistry.set(root, state);
751
+ }
752
+ return state;
753
+ }
754
+ /** Stamps a per-root-actor envelope onto a bare trace payload. */
755
+ function stampRootTrace(root, payload) {
756
+ const state = rootTraceState(root);
757
+ return {
758
+ schemaVersion: 1,
759
+ runId: state.runId,
760
+ seq: ++state.seq,
761
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
762
+ machineId: state.machineId,
763
+ machineVersion: state.machineVersion,
764
+ ...payload
765
+ };
766
+ }
767
+ /** Adapts a public `onTrace` into the payload-level {@link RunAgentBindContext.onTrace} sink used by the shared emission helpers. */
768
+ function provideTraceSink(onTrace) {
769
+ if (!onTrace) return;
770
+ return (payload, self) => {
771
+ const root = rootActorOf(self);
772
+ if (root) onTrace(stampRootTrace(root, payload));
773
+ };
774
+ }
775
+ /**
776
+ * A minimal {@link RunAgentBindContext} for `provideExecutors` (uncontrolled
777
+ * `createActor`): the same wrappers runAgent installs, MINUS the run-scoped
778
+ * model-call counter. `consumeModelCall` is a no-op (no budget), and
779
+ * `actorHolder.actorRef` is left undefined — the wrappers read the invoking
780
+ * actor off `self._parent`, always present under a live `createActor` tree.
781
+ * `onTrace` (when given) mints a per-root-actor envelope. `schemas` come from
782
+ * the machine's registered `setupAgent` execution options.
783
+ *
784
+ * `recordUsage` has no run-level aggregate to fold into here (there is no
785
+ * run), so it does one thing: deliver the reserved `@agent.usage` event, gated
786
+ * exactly like runAgent's — see {@link deliverUsageToInvokingActor}.
787
+ */
788
+ function provideBindContext(machine, executors, options) {
789
+ return {
790
+ generateText: executors.generateText,
791
+ streamText: executors.streamText,
792
+ decide: executors.decide,
793
+ onChunk: options.onChunk ? (chunk) => options.onChunk(chunk) : void 0,
794
+ onTrace: provideTraceSink(options.onTrace),
795
+ consumeModelCall: () => {},
796
+ recordUsage: (usage, source, self) => {
797
+ deliverUsageToInvokingActor(usage, source ?? {}, self);
798
+ },
799
+ actorHolder: { actorRef: void 0 },
800
+ schemas: getRegisteredAgentExecutionOptions(machine).schemas
801
+ };
802
+ }
803
+ /**
804
+ * `provideExecutors`' counterpart to runAgent's `deliverUsageEvent`: after a
805
+ * bound call settles with reported usage, send the reserved
806
+ * `@agent.usage` event to the machine actor that INVOKED the request — read
807
+ * off the settling request actor's `self._parent`, which under a live
808
+ * `createActor` tree is always the invoking machine (there is no run-scoped
809
+ * root actor on this path).
810
+ *
811
+ * Gated identically to runAgent: the invoking snapshot must be active, must
812
+ * declare an `'@agent.usage'` transition EXPLICITLY (see
813
+ * {@link declaresUsageTransition} — a catch-all `on: { '*' }` is not an opt-in),
814
+ * and must be able to take the event. There is no cycle to settle in
815
+ * uncontrolled mode, so there are no dropped stragglers.
816
+ *
817
+ * Delivery follows `provideExecutors`' binding boundary: only sources IT bound
818
+ * report here, so an invoked child machine that was not itself passed through
819
+ * `provideExecutors` reports nothing. @internal
820
+ */
821
+ function deliverUsageToInvokingActor(usage, source, self) {
822
+ const actorRef = self?._parent;
823
+ if (!actorRef) return;
824
+ const snapshot = actorRef.getSnapshot();
825
+ if (snapshot?.status !== "active" || !declaresUsageTransition(snapshot)) return;
826
+ const event = {
827
+ type: AGENT_USAGE_EVENT_TYPE,
828
+ ...source,
829
+ usage
830
+ };
831
+ if (!snapshot.can(event)) return;
832
+ actorRef.send(event);
833
+ }
834
+ /**
835
+ * Host-binds one text/stream source for {@link provideExecutors} using the SAME
836
+ * emission helper as `runAgent` ({@link wrapTextLogicForRunAgent}), so a bound
837
+ * text request emits request.start/stream.chunk/request.end/request.error with
838
+ * identical shapes. @internal
839
+ */
840
+ function bindTextForProvide(machine, logic, executors, options) {
841
+ return wrapTextLogicForRunAgent(logic, provideBindContext(machine, executors, options));
842
+ }
843
+ /**
844
+ * Host-binds one `DecisionLogic`/`agent.decide` source for
845
+ * {@link provideExecutors}: runAgent's decision wrapper (snapshot-driven
846
+ * candidate events, `canTake`, auto-delivery of the chosen event) with the same
847
+ * request-level tracing runAgent emits, minus run-scoped counting. @internal
848
+ */
849
+ function bindDecisionForProvide(machine, logic, executors, options) {
850
+ return createRunAgentDecisionLogic(logic, provideBindContext(machine, executors, options));
851
+ }
852
+ /**
853
+ * Host-binds one `agent.plan` source for {@link provideExecutors}: runAgent's
854
+ * plan wrapper (iterated snapshot-driven decisions, auto-delivery) with the same
855
+ * request-level tracing runAgent emits, minus run-scoped counting. @internal
856
+ */
857
+ function bindPlanForProvide(machine, logic, executors, options) {
858
+ return createRunAgentPlanLogic(logic, provideBindContext(machine, executors, options));
859
+ }
860
+ /**
861
+ * Recursively rebinds an invoked child machine's own agent sources with the
862
+ * SAME host-backed wrappers runAgent applies to the top-level machine, so a
863
+ * child's text/stream/decision/plan requests inherit runAgent's executors and
864
+ * participate in maxModelCalls counting, onTrace/onChunk/onResult exactly like
865
+ * parent requests. Returns the child machine to invoke: a `.provide`-rebound
866
+ * copy when any inner source needed wrapping, else the original untouched.
867
+ *
868
+ * Only string-keyed sources are visited — a direct-object invoke src cannot be
869
+ * swapped via `.provide` (assertBindable already rejected an unbound request
870
+ * under one). A source that already carries its own executor
871
+ * (`executorBoundLogics`) is left as-is: explicit binding shadows inheritance.
872
+ * Cycle-safe via `visited` (a machine that invokes itself is returned as-is).
873
+ */
874
+ function rebindChildMachine(childMachine, runCtx, visited) {
875
+ if (visited.has(childMachine)) return childMachine;
876
+ const childVisited = new Set([...visited, childMachine]);
877
+ const sources = childMachine.sources.actors;
878
+ const wrapped = {};
879
+ for (const [key, logic] of Object.entries(sources)) {
880
+ if (isDecisionLogic(logic)) {
881
+ if (!executorBoundLogics.has(logic)) wrapped[key] = createRunAgentDecisionLogic(logic, runCtx);
882
+ continue;
883
+ }
884
+ if (isPlanLogic(logic)) {
885
+ wrapped[key] = createRunAgentPlanLogic(logic, runCtx);
886
+ continue;
887
+ }
888
+ if (isTextLogic(logic)) {
889
+ if (!executorBoundLogics.has(logic)) wrapped[key] = wrapTextLogicForRunAgent(logic, runCtx);
890
+ continue;
891
+ }
892
+ if (isStateMachine(logic)) {
893
+ const rebound = rebindChildMachine(logic, runCtx, childVisited);
894
+ if (rebound !== logic) wrapped[key] = rebound;
895
+ continue;
896
+ }
897
+ }
898
+ return Object.keys(wrapped).length > 0 ? childMachine.provide({ actors: wrapped }) : childMachine;
899
+ }
900
+ /**
901
+ * Runs an agent machine to completion or idle: a `createActor` host that
902
+ * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
903
+ * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
904
+ * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
905
+ * the step helpers ({@link initialAgentStep} etc — a pure
906
+ * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
907
+ * internally; there is no continuation callback, so **idle always settles**
908
+ * and the caller resumes explicitly by passing the settled `{ snapshot,
909
+ * event }` back in. The actor is stopped on every settle path (`done`,
910
+ * `idle`, and `error` alike) — resume is always by snapshot, never by
911
+ * holding a reference to a live actor.
912
+ *
913
+ * Binding happens **before** the actor starts: every invoke the machine
914
+ * could reach is walked and checked against the effective actor sources
915
+ * (`options.actors` merged onto the machine), so a missing
916
+ * `streamText`/`decide` executor or any other unbound actor source throws
917
+ * immediately — a bind-time error, not a mid-run failure. The one exception
918
+ * is `agent.userInput`: unhandled, it binds as a pending placeholder that
919
+ * settles the run idle (with `pendingUserInputs`) instead of erroring.
920
+ *
921
+ * @example
922
+ * ```ts
923
+ * const executors = createAiSdkExecutors({ models });
924
+ * let r = await runAgent(machine, { input, executors });
925
+ * while (r.status === 'idle') {
926
+ * const event = await promptUser(getAcceptedEvents(r.snapshot));
927
+ * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
928
+ * }
929
+ * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
930
+ * console.log(r.output);
931
+ * ```
932
+ *
933
+ * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
934
+ * functions directly (`executors: { generateText, streamText }` with them
935
+ * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
936
+ * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
937
+ * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
938
+ */
939
+ async function runAgent(machine, options) {
940
+ return createAgentSession(machine, options, { oneShot: true }).settled();
941
+ }
942
+ /**
943
+ * Session mode: {@link runAgent}'s engine with a long-lived actor. Use it when
944
+ * the agent is a *session* fed by external events (chat turns, device or
945
+ * timer events, a socket) rather than a one-shot job — you keep the log,
946
+ * budget, traces, and idle semantics that bare `provideExecutors` +
947
+ * `createActor` would forfeit.
948
+ *
949
+ * ```ts
950
+ * const session = createAgentActor(machine, { input, executors });
951
+ * let result = await session.settled(); // first quiescence
952
+ * while (result.status === "idle") {
953
+ * session.actor.send(await nextUserEvent(result.snapshot));
954
+ * result = await session.settled(); // next quiescence, same log
955
+ * }
956
+ * session.stop();
957
+ * ```
958
+ *
959
+ * Accepts the same options as {@link runAgent} (including `snapshot`/`events`
960
+ * resume). Not yet supported in session mode: `getRequests` re-interpretation
961
+ * across cycles behaves per-cycle exactly as in `runAgent`.
962
+ */
963
+ function createAgentActor(machine, options) {
964
+ return createAgentSession(machine, options, { oneShot: false });
965
+ }
966
+ function createAgentSession(machine, options, lifecycle) {
967
+ const maxModelCalls = options.maxModelCalls ?? 100;
968
+ let modelCallCount = 0;
969
+ let budgetExceeded = false;
970
+ let warnedNonSerializable = false;
971
+ let warnedHeuristicIdle = false;
972
+ const runId = `run_${nextRunAgentTraceId++}`;
973
+ let traceSeq = 0;
974
+ const machineId = machine.config.id ?? machine.id ?? "(machine)";
975
+ const machineVersion = options.machineVersion ?? machine.version ?? getMachineStructuralHash(machine);
976
+ const agentMeta = {
977
+ machineId,
978
+ version: machineVersion
979
+ };
980
+ const stampAgentMeta = (snapshot) => {
981
+ if (snapshot && typeof snapshot === "object") snapshot.agentMeta = agentMeta;
982
+ };
983
+ const onTrace = (event) => {
984
+ options.onTrace?.({
985
+ schemaVersion: 1,
986
+ runId,
987
+ seq: ++traceSeq,
988
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
989
+ machineId,
990
+ machineVersion,
991
+ ...event
992
+ });
993
+ };
994
+ const consumeModelCall = () => {
995
+ if (budgetExceeded) throw new AgentMaxModelCallsExceededError();
996
+ if (modelCallCount + 1 > maxModelCalls) {
997
+ budgetExceeded = true;
998
+ throw new AgentMaxModelCallsExceededError();
999
+ }
1000
+ modelCallCount += 1;
1001
+ };
1002
+ const tokenTotals = {};
1003
+ const cycleGate = { isResolved: () => false };
1004
+ const deliverUsageEvent = (usage, source) => {
1005
+ const actorRef = actorHolder.actorRef;
1006
+ if (!actorRef) return;
1007
+ const event = {
1008
+ type: AGENT_USAGE_EVENT_TYPE,
1009
+ ...source,
1010
+ usage
1011
+ };
1012
+ const snapshot = actorRef.getSnapshot();
1013
+ if (snapshot?.status !== "active" || !declaresUsageTransition(snapshot)) return;
1014
+ if (cycleGate.isResolved()) {
1015
+ onTrace({
1016
+ type: "usage.dropped",
1017
+ event,
1018
+ reason: "settled"
1019
+ });
1020
+ return;
1021
+ }
1022
+ if (!snapshot.can(event)) return;
1023
+ actorRef.send(event);
1024
+ };
1025
+ const recordUsage = (usage, source = {}) => {
1026
+ for (const field of AGENT_USAGE_TOKEN_FIELDS) {
1027
+ const value = usage[field];
1028
+ if (typeof value === "number" && Number.isFinite(value)) tokenTotals[field] = (tokenTotals[field] ?? 0) + value;
1029
+ }
1030
+ deliverUsageEvent(usage, source);
1031
+ };
1032
+ const runUsage = () => ({
1033
+ ...tokenTotals,
1034
+ modelCalls: modelCallCount
1035
+ });
1036
+ const warnNonSerializableContext = (snapshot) => {
1037
+ if (warnedNonSerializable || process.env.NODE_ENV === "production") return;
1038
+ let offending = [];
1039
+ try {
1040
+ offending = findNonSerializableContextPaths(snapshot.context);
1041
+ } catch {
1042
+ return;
1043
+ }
1044
+ if (offending.length === 0) return;
1045
+ warnedNonSerializable = true;
1046
+ console.warn(`runAgent: context holds value(s) that will not survive snapshot persist/resume (JSON round-trip): ${offending.join(", ")}. Persist only JSON-serializable context, or convert these before the run settles.`);
1047
+ };
1048
+ const provided = machine.provide({ actors: options.actors });
1049
+ const effectiveSources = provided.sources.actors;
1050
+ assertBindable(provided, effectiveSources, {
1051
+ hasGenerateText: !!options.executors?.generateText,
1052
+ hasDecide: !!options.executors?.decide,
1053
+ hasStreamText: !!options.executors?.streamText
1054
+ });
1055
+ if (options.getRequests && !options.executors?.generateText && !options.executors?.decide) throw new Error("runAgent: 'getRequests' requires a 'generateText' and/or 'decide' executor — the returned requests run through them.");
1056
+ const actorHolder = { actorRef: void 0 };
1057
+ const runCtx = {
1058
+ generateText: options.executors?.generateText,
1059
+ streamText: options.executors?.streamText,
1060
+ decide: options.executors?.decide,
1061
+ onChunk: options.onChunk,
1062
+ onResult: options.onResult,
1063
+ onTrace,
1064
+ consumeModelCall,
1065
+ recordUsage,
1066
+ actorHolder,
1067
+ runId,
1068
+ schemas: getRegisteredAgentExecutionOptions(machine).schemas
1069
+ };
1070
+ let userInputIsPlaceholder = false;
1071
+ const wrappedSources = {};
1072
+ for (const [key, logic] of Object.entries(effectiveSources)) {
1073
+ if (key === "agent.userInput") {
1074
+ if (options.userInput) {
1075
+ const userInput = options.userInput;
1076
+ wrappedSources[key] = createAsyncLogic({ run: async ({ input }) => await userInput(input) });
1077
+ } else if (isUnboundPlaceholder(logic)) {
1078
+ userInputIsPlaceholder = true;
1079
+ wrappedSources[key] = createAsyncLogic({ run: () => new Promise(() => {}) });
1080
+ }
1081
+ continue;
1082
+ }
1083
+ if (isDecisionLogic(logic)) {
1084
+ wrappedSources[key] = createRunAgentDecisionLogic(logic, runCtx);
1085
+ continue;
1086
+ }
1087
+ if (isPlanLogic(logic)) {
1088
+ wrappedSources[key] = createRunAgentPlanLogic(logic, runCtx);
1089
+ continue;
1090
+ }
1091
+ if (isTextLogic(logic)) {
1092
+ if (!executorBoundLogics.has(logic)) wrappedSources[key] = wrapTextLogicForRunAgent(logic, runCtx);
1093
+ continue;
1094
+ }
1095
+ if (isStateMachine(logic)) {
1096
+ const rebound = rebindChildMachine(logic, runCtx, new Set([machine]));
1097
+ if (rebound !== logic) wrappedSources[key] = rebound;
1098
+ continue;
1099
+ }
1100
+ }
1101
+ const boundMachine = provided.provide({ actors: wrappedSources });
1102
+ const declaredSuspensionPredicate = options.isSuspended ?? getMachineSuspensionPredicate(machine);
1103
+ const isSuspended = declaredSuspensionPredicate ?? (() => false);
1104
+ let effectiveSnapshot = options.snapshot;
1105
+ if (effectiveSnapshot !== void 0) {
1106
+ const from = effectiveSnapshot.agentMeta?.version ?? effectiveSnapshot.version;
1107
+ if (from !== void 0 && from !== machineVersion) {
1108
+ const info = {
1109
+ from,
1110
+ to: machineVersion
1111
+ };
1112
+ if (options.migrateSnapshot) effectiveSnapshot = options.migrateSnapshot(effectiveSnapshot, info);
1113
+ else {
1114
+ const mode = options.onVersionMismatch ?? "throw";
1115
+ if (mode === "throw") throw new AgentSnapshotVersionMismatchError(from, machineVersion, machineId);
1116
+ if (mode === "warn") console.warn(`runAgent: resuming a snapshot stamped with machine version '${from}' against machine '${machineId}' at version '${machineVersion}'. Structural changes may not resume cleanly.`);
1117
+ }
1118
+ }
1119
+ }
1120
+ const resumeEvents = options.events;
1121
+ if (effectiveSnapshot === void 0 && options.events !== void 0 && options.events[0]?.event.type === "@agent.init") {
1122
+ const { snapshot: replayedSnapshot } = replay(machine, resumeEvents, { machineVersion });
1123
+ effectiveSnapshot = machine.getPersistedSnapshot(replayedSnapshot);
1124
+ }
1125
+ const machineOwnVersion = machine.version;
1126
+ if (effectiveSnapshot !== void 0 && effectiveSnapshot.version !== machineOwnVersion) {
1127
+ const aligned = Object.assign(Object.create(Object.getPrototypeOf(effectiveSnapshot)), effectiveSnapshot);
1128
+ if (machineOwnVersion === void 0) delete aligned.version;
1129
+ else aligned.version = machineOwnVersion;
1130
+ effectiveSnapshot = aligned;
1131
+ }
1132
+ const priorMessages = getAgentMessages(effectiveSnapshot);
1133
+ const messages = typeof options.messages === "function" ? [...options.messages([...priorMessages])] : [...priorMessages, ...options.messages ?? []];
1134
+ const stampMessages = (snapshot) => {
1135
+ if (!options.getRequests && !options.messages && messages.length === 0) return;
1136
+ if (snapshot && typeof snapshot === "object") snapshot.messages = [...messages];
1137
+ };
1138
+ if (effectiveSnapshot !== void 0 && options.event !== void 0 && (options.onIllegalResumeEvent ?? "throw") === "throw") {
1139
+ const acceptedTypes = getAcceptedEvents(createActor(boundMachine, { snapshot: effectiveSnapshot }).getSnapshot(), { schemas: runCtx.schemas }).map((descriptor) => descriptor.type);
1140
+ const eventType = options.event.type;
1141
+ if (!acceptedTypes.includes(eventType)) throw new AgentIllegalResumeEventError(eventType, acceptedTypes);
1142
+ }
1143
+ const replayEvents = [...resumeEvents ?? []];
1144
+ const replayEventIds = /* @__PURE__ */ new Set();
1145
+ for (let index = 0; index < replayEvents.length; index++) {
1146
+ const entry = replayEvents[index];
1147
+ assertAgentLogEntry(entry);
1148
+ if (entry.index !== index) throw new Error(`runAgent events must be contiguous from index 0; found entry.index ${entry.index} at position ${index}.`);
1149
+ if (entry.machineId !== machineId || entry.machineVersion !== machineVersion) throw new AgentReplayMachineMismatchError(entry.id, entry.index, {
1150
+ machineId,
1151
+ machineVersion
1152
+ }, {
1153
+ machineId: entry.machineId,
1154
+ machineVersion: entry.machineVersion
1155
+ });
1156
+ if (replayEventIds.has(entry.id)) throw new Error(`runAgent events contain duplicate event id '${entry.id}'.`);
1157
+ replayEventIds.add(entry.id);
1158
+ }
1159
+ const hasCompleteReplayHistory = replayEvents[0]?.event.type === "@agent.init" || effectiveSnapshot === void 0 && replayEvents.length === 0;
1160
+ const appendReplayEvent = (event) => {
1161
+ const entry = createReplayEntry(machine, replayEvents, event, {
1162
+ machineVersion,
1163
+ verification: hasCompleteReplayHistory
1164
+ });
1165
+ if (replayEventIds.has(entry.id)) throw new Error(`runAgent generated duplicate event id '${entry.id}'.`);
1166
+ replayEventIds.add(entry.id);
1167
+ replayEvents.push(entry);
1168
+ options.onEvent?.(entry);
1169
+ return entry;
1170
+ };
1171
+ if (replayEvents.length === 0 && effectiveSnapshot === void 0) {
1172
+ const entry = initEntry(machine, options.input, { machineVersion });
1173
+ replayEventIds.add(entry.id);
1174
+ replayEvents.push(entry);
1175
+ options.onEvent?.(entry);
1176
+ }
1177
+ return (() => {
1178
+ let settled = false;
1179
+ let finalized = false;
1180
+ cycleGate.isResolved = () => settled;
1181
+ let lastResult;
1182
+ const waiters = [];
1183
+ let idleTimer;
1184
+ let actor;
1185
+ let deliveringResumeEvent = options.event !== void 0;
1186
+ const settle = (outcome) => {
1187
+ if (settled) return;
1188
+ settled = true;
1189
+ const result = {
1190
+ ...outcome,
1191
+ events: [...replayEvents],
1192
+ usage: runUsage()
1193
+ };
1194
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
1195
+ stampAgentMeta(result.snapshot);
1196
+ stampMessages(result.snapshot);
1197
+ if ("persistedSnapshot" in result) {
1198
+ stampAgentMeta(result.persistedSnapshot);
1199
+ stampMessages(result.persistedSnapshot);
1200
+ }
1201
+ onTrace({
1202
+ type: "run.end",
1203
+ ...outcome
1204
+ });
1205
+ if (lifecycle.oneShot || result.status !== "idle") {
1206
+ finalized = true;
1207
+ if (options.signal) options.signal.removeEventListener("abort", onAbort);
1208
+ actor.stop();
1209
+ }
1210
+ lastResult = result;
1211
+ for (const resolve of waiters.splice(0)) resolve(result);
1212
+ };
1213
+ const onAbort = () => {
1214
+ settle({
1215
+ status: "error",
1216
+ cause: "aborted",
1217
+ error: options.signal?.reason ?? /* @__PURE__ */ new Error("Aborted"),
1218
+ snapshot: actor.getSnapshot()
1219
+ });
1220
+ };
1221
+ const settleIdle = (current) => {
1222
+ warnNonSerializableContext(current);
1223
+ const pendingUserInputs = userInputIsPlaceholder ? collectPendingUserInputs(current) : [];
1224
+ settle({
1225
+ status: "idle",
1226
+ snapshot: current,
1227
+ ...pendingUserInputs.length > 0 ? {
1228
+ pendingUserInputs,
1229
+ persistedSnapshot: actor.getPersistedSnapshot()
1230
+ } : {}
1231
+ });
1232
+ };
1233
+ let interpreting = false;
1234
+ let interpretSeq = 0;
1235
+ const appendToLog = (...items) => {
1236
+ messages.push(...items);
1237
+ if (options.onMessage) {
1238
+ const info = {
1239
+ runId,
1240
+ machineId,
1241
+ machineVersion
1242
+ };
1243
+ for (const item of items) options.onMessage(item, info);
1244
+ }
1245
+ };
1246
+ const runErrorCause = (error) => budgetExceeded ? "max-model-calls" : wrapsDecisionExhausted(error) ? "decision-exhausted" : "machine";
1247
+ const settleInterpretError = (error) => {
1248
+ settle({
1249
+ status: "error",
1250
+ cause: runErrorCause(error),
1251
+ error,
1252
+ snapshot: actor.getSnapshot()
1253
+ });
1254
+ };
1255
+ const passDeps = {
1256
+ getSnapshot: () => actor.getSnapshot(),
1257
+ send: (event) => actor.send(event),
1258
+ isSettled: () => settled,
1259
+ messages,
1260
+ appendToLog,
1261
+ generateText: runCtx.generateText,
1262
+ decide: runCtx.decide ? createCountingDecide(runCtx, void 0) : void 0,
1263
+ consumeModelCall,
1264
+ recordUsage,
1265
+ nextRequestId: () => `interpret_${++interpretSeq}`,
1266
+ onTrace,
1267
+ onResult: runCtx.onResult,
1268
+ schemas: runCtx.schemas,
1269
+ signal: options.signal
1270
+ };
1271
+ const maybeInterpret = (snapshot) => {
1272
+ if (!options.getRequests || settled) return false;
1273
+ if (interpreting) return true;
1274
+ let requested;
1275
+ try {
1276
+ requested = options.getRequests(snapshot, { messages });
1277
+ } catch (error) {
1278
+ settleInterpretError(error);
1279
+ return true;
1280
+ }
1281
+ const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter((stateRequest) => Boolean(stateRequest));
1282
+ if (requests.length === 0) return false;
1283
+ interpreting = true;
1284
+ runStateRequestPass(requests, passDeps).then(({ sentAny }) => {
1285
+ if (settled || sentAny) return;
1286
+ const current = actor.getSnapshot();
1287
+ if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) settleIdle(current);
1288
+ }).catch((error) => settleInterpretError(error)).finally(() => {
1289
+ interpreting = false;
1290
+ if (!settled) scheduleIdleCheck();
1291
+ });
1292
+ return true;
1293
+ };
1294
+ const scheduleIdleCheck = () => {
1295
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
1296
+ idleTimer = setTimeout(() => {
1297
+ idleTimer = void 0;
1298
+ if (settled) return;
1299
+ const current = actor.getSnapshot();
1300
+ if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) {
1301
+ if (!maybeInterpret(current)) {
1302
+ if (!declaredSuspensionPredicate && current.status === "active" && !warnedHeuristicIdle && process.env.NODE_ENV !== "production") {
1303
+ warnedHeuristicIdle = true;
1304
+ console.warn("[@statelyai/agent] runAgent settled idle via the timing heuristic (no suspension predicate declared). This is best-effort; for deterministic idle detection, declare setupAgent({ isSuspended }) or pass runAgent(machine, { isSuspended }), e.g. (s) => s.hasTag('waiting').");
1305
+ }
1306
+ settleIdle(current);
1307
+ }
1308
+ }
1309
+ }, 0);
1310
+ };
1311
+ actor = createActor(boundMachine, {
1312
+ input: options.input,
1313
+ snapshot: effectiveSnapshot,
1314
+ inspect: (event) => {
1315
+ if (typeof options.inspect === "function") options.inspect(event);
1316
+ else options.inspect?.next?.(event);
1317
+ if (event.type !== "@xstate.transition" || event.actorRef !== actor.ref) return;
1318
+ if (settled) {
1319
+ if (finalized) return;
1320
+ settled = false;
1321
+ lastResult = void 0;
1322
+ }
1323
+ const snapshot = event.snapshot;
1324
+ let eventId;
1325
+ if (event.event.type !== "@xstate.init" && (event.sourceRef !== event.actorRef || event.event.type === "xstate.timer")) eventId = appendReplayEvent(event.event).id;
1326
+ else if (event.event.type === "@xstate.init") eventId = replayEvents[0]?.event.type === "@agent.init" ? replayEvents[0].id : void 0;
1327
+ onTrace({
1328
+ type: "machine.transition",
1329
+ snapshot,
1330
+ event: event.event,
1331
+ ...eventId !== void 0 ? { eventId } : {}
1332
+ });
1333
+ options.onTransition?.(snapshot, event.event);
1334
+ if (snapshot.status === "done") {
1335
+ settle({
1336
+ status: "done",
1337
+ output: snapshot.output,
1338
+ snapshot
1339
+ });
1340
+ return;
1341
+ }
1342
+ if (snapshot.status === "error") {
1343
+ settle({
1344
+ status: "error",
1345
+ cause: runErrorCause(snapshot.error),
1346
+ error: snapshot.error,
1347
+ snapshot
1348
+ });
1349
+ return;
1350
+ }
1351
+ if (snapshot.status === "stopped") {
1352
+ settle({
1353
+ status: "error",
1354
+ cause: "stopped",
1355
+ error: /* @__PURE__ */ new Error("Actor stopped externally."),
1356
+ snapshot
1357
+ });
1358
+ return;
1359
+ }
1360
+ if (!deliveringResumeEvent && isSuspended(snapshot) && isIdleSnapshot(snapshot, { ignoreUserInputChildren: userInputIsPlaceholder })) {
1361
+ if (!maybeInterpret(snapshot)) settleIdle(snapshot);
1362
+ return;
1363
+ }
1364
+ scheduleIdleCheck();
1365
+ }
1366
+ });
1367
+ actorHolder.actorRef = actor;
1368
+ actor.subscribe({ error: () => {} });
1369
+ actor.on("*", (event) => {
1370
+ onTrace({
1371
+ type: "emit",
1372
+ event
1373
+ });
1374
+ });
1375
+ for (const [type, handler] of Object.entries(options.on ?? {})) if (typeof handler === "function") actor.on(type, handler);
1376
+ const sessionApi = {
1377
+ actor,
1378
+ get events() {
1379
+ return replayEvents;
1380
+ },
1381
+ usage: runUsage,
1382
+ settled: () => settled && lastResult !== void 0 ? Promise.resolve(lastResult) : new Promise((resolve) => {
1383
+ waiters.push(resolve);
1384
+ }),
1385
+ stop: () => {
1386
+ actor.stop();
1387
+ }
1388
+ };
1389
+ if (options.signal) {
1390
+ if (options.signal.aborted) {
1391
+ settle({
1392
+ status: "error",
1393
+ cause: "aborted",
1394
+ error: options.signal.reason ?? /* @__PURE__ */ new Error("Aborted"),
1395
+ snapshot: actor.getSnapshot()
1396
+ });
1397
+ return sessionApi;
1398
+ }
1399
+ options.signal.addEventListener("abort", onAbort);
1400
+ }
1401
+ onTrace({
1402
+ type: "run.start",
1403
+ ...options.input !== void 0 ? { input: options.input } : {},
1404
+ ...effectiveSnapshot !== void 0 ? { snapshot: effectiveSnapshot } : {},
1405
+ ...options.event !== void 0 ? { event: options.event } : {}
1406
+ });
1407
+ actor.start();
1408
+ if (options.event) {
1409
+ deliveringResumeEvent = false;
1410
+ actor.send(options.event);
1411
+ }
1412
+ return sessionApi;
1413
+ })();
1414
+ }
1415
+ /**
1416
+ * Runs an agent machine to a **final state**, for run-to-done flows where an
1417
+ * idle pause is unexpected. Wraps {@link runAgent}:
1418
+ *
1419
+ * - `done` → resolves with the done result: `result.output` (the machine's
1420
+ * `OutputFrom`) plus metadata — `result.snapshot`, the replayable
1421
+ * `result.events`, and the aggregated `result.usage` — the same shape
1422
+ * `generateText` users expect (`text` + call metadata).
1423
+ * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1424
+ * event types that could resume it.
1425
+ * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1426
+ * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1427
+ * `.error` is the raw thrown value.
1428
+ *
1429
+ * Use {@link runAgent} directly when idle is an expected outcome you handle
1430
+ * (human-in-the-loop, resumable flows); use `generateResult` when the
1431
+ * machine is meant to run straight through to a final state.
1432
+ */
1433
+ async function generateResult(machine, options) {
1434
+ const result = await runAgent(machine, options);
1435
+ if (result.status === "done") return result;
1436
+ if (result.status === "idle") {
1437
+ const acceptedTypes = getAcceptedEvents(result.snapshot, { schemas: getRegisteredAgentExecutionOptions(machine).schemas }).map((descriptor) => descriptor.type);
1438
+ throw new AgentIdleError(result.snapshot, acceptedTypes);
1439
+ }
1440
+ if (result.error instanceof Error) throw result.error;
1441
+ const wrapped = /* @__PURE__ */ new Error(`generateResult: run failed with cause '${result.cause}'.`);
1442
+ wrapped.cause = result.cause;
1443
+ wrapped.error = result.error;
1444
+ throw wrapped;
1445
+ }
1446
+ /**
1447
+ * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1448
+ * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1449
+ * `@xstate.transition` events and hands the handler the typed
1450
+ * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1451
+ * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1452
+ * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1453
+ * actorRef casts.
1454
+ */
1455
+ function inspectTransitions(handler) {
1456
+ return (inspectionEvent) => {
1457
+ if (inspectionEvent.type !== "@xstate.transition") return;
1458
+ handler(inspectionEvent.snapshot, inspectionEvent.actorRef);
1459
+ };
1460
+ }
1461
+ /**
1462
+ * An xstate `inspect` handler that emits `machine.transition` trace events onto
1463
+ * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
1464
+ * registry as {@link provideExecutors}' `onTrace`. Pair the two on one actor to
1465
+ * get a single ordered trace stream (request + transition events) for the
1466
+ * uncontrolled path:
1467
+ *
1468
+ * ```ts
1469
+ * const bound = provideExecutors(machine, executors, { onTrace });
1470
+ * const actor = createActor(bound, { inspect: traceTransitions(onTrace) });
1471
+ * ```
1472
+ *
1473
+ * Only ROOT-actor transitions are traced (matching `runAgent`'s
1474
+ * `machine.transition`); child-actor transitions are ignored. Attribute the
1475
+ * event via its envelope `runId`.
1476
+ *
1477
+ * By design this path has NO `run.start`/`run.end` events: `createActor` has no
1478
+ * run boundary the way `runAgent` does, so the stream starts at the actor's
1479
+ * first transition. It also does NOT emit `emit` trace events: in this xstate
1480
+ * build emitted events are delivered through `actor.on(...)`, not the inspection
1481
+ * protocol, so they are not observable from an `inspect` handler — subscribe
1482
+ * with `actor.on('*', ...)` if you need them.
1483
+ */
1484
+ function traceTransitions(onTrace) {
1485
+ return (inspectionEvent) => {
1486
+ if (inspectionEvent.type !== "@xstate.transition") return;
1487
+ const actorRef = inspectionEvent.actorRef;
1488
+ if (actorRef?._parent) return;
1489
+ onTrace(stampRootTrace(actorRef, {
1490
+ type: "machine.transition",
1491
+ snapshot: inspectionEvent.snapshot,
1492
+ event: inspectionEvent.event
1493
+ }));
1494
+ };
1495
+ }
1496
+ function isIdleSnapshot(snapshot, { ignoreUserInputChildren }) {
1497
+ if (snapshot.status !== "active") return false;
1498
+ if (Object.values(snapshot.children ?? {}).some((child) => {
1499
+ const ref = child;
1500
+ if (ignoreUserInputChildren && ref?.src === "agent.userInput") return false;
1501
+ return ref?.getSnapshot?.()?.status === "active";
1502
+ })) return false;
1503
+ return !getNextTransitions(snapshot).some((transitionDef) => transitionDef.eventType === "" || transitionDef.eventType.startsWith("xstate.after"));
1504
+ }
1505
+ function collectPendingUserInputs(snapshot) {
1506
+ const pending = [];
1507
+ for (const [id, child] of Object.entries(snapshot.children ?? {})) {
1508
+ const ref = child;
1509
+ if (ref?.src !== "agent.userInput") continue;
1510
+ const childSnapshot = ref.getSnapshot?.();
1511
+ if (childSnapshot?.status !== "active") continue;
1512
+ pending.push({
1513
+ id,
1514
+ input: childSnapshot.input
1515
+ });
1516
+ }
1517
+ return pending;
1518
+ }
1519
+ //#endregion
1520
+ //#region src/agent-run.ts
1521
+ /**
1522
+ * Wraps {@link runAgent} in a canonical run-stream handle: the run's trace
1523
+ * events as a pull-based {@link AgentRun.events} async iterator, alongside the
1524
+ * unchanged {@link AgentRun.result} promise.
1525
+ *
1526
+ * Semantics:
1527
+ *
1528
+ * 1. **Starts immediately.** The underlying `runAgent` is invoked on this call,
1529
+ * not on the first `events` iteration — work is already in flight when
1530
+ * `createAgentRun` returns.
1531
+ * 2. **Buffer, don't stall.** Events are queued in an unbounded in-memory
1532
+ * buffer as the run emits them; a slow or absent consumer never applies
1533
+ * backpressure to the run. Once `run.end` is delivered, the iterator
1534
+ * completes.
1535
+ * 3. **Composes `onTrace`.** If `options.onTrace` is passed, it still fires for
1536
+ * every event — the wrapper adds queue delivery, it does not replace the
1537
+ * caller's sink.
1538
+ * 4. **`result` mirrors `runAgent`.** Same resolution and rejection behavior
1539
+ * (see {@link AgentRun.result}). A no-op rejection handler is attached
1540
+ * internally so a caller who reads only `events` never trips an unhandled
1541
+ * rejection on a bind-time throw; the returned promise still rejects for a
1542
+ * caller who awaits it.
1543
+ * 5. **Resume is identical.** Options pass straight through, so starting from a
1544
+ * persisted `snapshot` (+ resume `event`) streams that run's events from its
1545
+ * own `run.start`, exactly as `runAgent` would run it.
1546
+ * 6. **Early termination does not cancel the run.** Breaking out of a
1547
+ * `for await` (or calling `events.return()`) stops delivery, but the run
1548
+ * keeps going and `result` still settles. Cancelling the run itself is
1549
+ * future work — pass `options.signal` to abort it.
1550
+ * 7. **`events` is single-consumer.** See {@link AgentRun.events}.
1551
+ */
1552
+ function createAgentRun(machine, options) {
1553
+ const buffer = [];
1554
+ const resolvers = [];
1555
+ let closed = false;
1556
+ let stopped = false;
1557
+ const push = (event) => {
1558
+ if (closed || stopped) return;
1559
+ const resolve = resolvers.shift();
1560
+ if (resolve) resolve({
1561
+ value: event,
1562
+ done: false
1563
+ });
1564
+ else buffer.push(event);
1565
+ };
1566
+ const close = () => {
1567
+ if (closed) return;
1568
+ closed = true;
1569
+ while (resolvers.length > 0) resolvers.shift()({
1570
+ value: void 0,
1571
+ done: true
1572
+ });
1573
+ };
1574
+ const userOnTrace = options.onTrace;
1575
+ const result = runAgent(machine, {
1576
+ ...options,
1577
+ onTrace: (event) => {
1578
+ push(event);
1579
+ userOnTrace?.(event);
1580
+ if (event.type === "run.end") close();
1581
+ }
1582
+ });
1583
+ result.then(close, close);
1584
+ return {
1585
+ events: {
1586
+ next() {
1587
+ if (buffer.length > 0) return Promise.resolve({
1588
+ value: buffer.shift(),
1589
+ done: false
1590
+ });
1591
+ if (closed || stopped) return Promise.resolve({
1592
+ value: void 0,
1593
+ done: true
1594
+ });
1595
+ return new Promise((resolve) => {
1596
+ resolvers.push(resolve);
1597
+ });
1598
+ },
1599
+ return() {
1600
+ stopped = true;
1601
+ buffer.length = 0;
1602
+ while (resolvers.length > 0) resolvers.shift()({
1603
+ value: void 0,
1604
+ done: true
1605
+ });
1606
+ return Promise.resolve({
1607
+ value: void 0,
1608
+ done: true
1609
+ });
1610
+ },
1611
+ [Symbol.asyncIterator]() {
1612
+ return this;
1613
+ }
1614
+ },
1615
+ result
1616
+ };
1617
+ }
1618
+ //#endregion
1619
+ //#region src/provide-executors.ts
1620
+ /**
1621
+ * Binds a machine's agent actor sources to a set of host `executors` in one
1622
+ * call, returning a `machine.provide(...)`-ed copy ready for a plain
1623
+ * `createActor(...)` — the uncontrolled-mode counterpart to {@link runAgent}.
1624
+ * No run loop, no idle settling: the returned machine drives itself, so
1625
+ *
1626
+ * ```ts
1627
+ * const actor = createActor(provideExecutors(machine, { generateText, decide }), { input });
1628
+ * actor.start();
1629
+ * ```
1630
+ *
1631
+ * behaves like a normal XState actor whose agent invokes now reach real models.
1632
+ *
1633
+ * Binding pass over `machine.sources.actors` (after merging
1634
+ * `options.actors`):
1635
+ * - `mode: 'generate'` text source → `executors.generateText`
1636
+ * - `mode: 'stream'` text source → `executors.streamText`
1637
+ * - decision / `agent.decide` source → `executors.decide` (snapshot-driven
1638
+ * candidate events, guard `canTake`, and auto-delivery of the chosen event,
1639
+ * mirroring `runAgent` but without its model-call counting)
1640
+ * - `agent.plan` source → `executors.decide` (iterated, same semantics)
1641
+ *
1642
+ * Pass `options.onTrace` to observe request-level trace events (identical in
1643
+ * shape to `runAgent`'s); pair it with {@link traceTransitions} on the actor's
1644
+ * `inspect` to also capture `machine.transition` events in the same stream.
1645
+ *
1646
+ * A source that already carries its own executor (`.withExecutor(...)`) is left
1647
+ * as-is. `agent.userInput` is left UNBOUND — an uncontrolled host handles idle
1648
+ * itself, so supply a handler via `options.actors` if the machine uses it.
1649
+ * Non-agent actors are untouched.
1650
+ *
1651
+ * Throws at bind time if a source needs an executor kind that `executors` does
1652
+ * not provide.
1653
+ *
1654
+ * v1 does NOT descend into invoked child state machines: a string-keyed child
1655
+ * machine source is left untouched, so a child with its own agent invokes needs
1656
+ * its own `provideExecutors(...)` (or `runAgent`, which does rebind children).
1657
+ */
1658
+ function provideExecutors(machine, executors, options = {}) {
1659
+ const bindOptions = {
1660
+ onChunk: options.onChunk,
1661
+ onTrace: options.onTrace
1662
+ };
1663
+ const provided = options.actors ? machine.provide({ actors: options.actors }) : machine;
1664
+ const effectiveSources = provided.sources.actors;
1665
+ const wrappedSources = {};
1666
+ const invokedSrcs = getConfiguredInvokeSrcs(provided);
1667
+ for (const [key, logic] of Object.entries(effectiveSources)) {
1668
+ if (key === "agent.userInput") continue;
1669
+ if (isDecisionLogic(logic)) {
1670
+ if (executorBoundLogics.has(logic)) continue;
1671
+ if (!executors.decide) {
1672
+ if (invokedSrcs.has(key)) throw missingExecutorError(key, "decision", "decide");
1673
+ continue;
1674
+ }
1675
+ wrappedSources[key] = bindDecisionForProvide(provided, logic, executors, bindOptions);
1676
+ continue;
1677
+ }
1678
+ if (isPlanLogic(logic)) {
1679
+ if (!executors.decide) {
1680
+ if (invokedSrcs.has(key)) throw missingExecutorError(key, "plan", "decide");
1681
+ continue;
1682
+ }
1683
+ wrappedSources[key] = bindPlanForProvide(provided, logic, executors, bindOptions);
1684
+ continue;
1685
+ }
1686
+ if (isTextLogic(logic)) {
1687
+ if (executorBoundLogics.has(logic)) continue;
1688
+ if (!(logic.mode === "stream" ? executors.streamText : executors.generateText)) {
1689
+ if (invokedSrcs.has(key)) throw logic.mode === "stream" ? missingExecutorError(key, "streaming text", "streamText") : missingExecutorError(key, "text", "generateText");
1690
+ continue;
1691
+ }
1692
+ wrappedSources[key] = bindTextForProvide(provided, logic, executors, bindOptions);
1693
+ continue;
1694
+ }
1695
+ }
1696
+ return provided.provide({ actors: wrappedSources });
1697
+ }
1698
+ function missingExecutorError(src, kind, executor) {
1699
+ return /* @__PURE__ */ new Error(`provideExecutors: actor source '${src}' is a ${kind} source but no '${executor}' executor was provided. Add it to the executors object, or bind the source with its own executor (logic.withExecutor(...)) before calling provideExecutors.`);
1700
+ }
1701
+ //#endregion
1702
+ //#region src/verify.ts
1703
+ const DECIDE_SRC = "agent.decide";
1704
+ const PLAN_SRC = "agent.plan";
1705
+ function normalizeInvokes(invoke) {
1706
+ if (invoke === void 0 || invoke === null) return [];
1707
+ return Array.isArray(invoke) ? invoke : [invoke];
1708
+ }
1709
+ function buildStateIndex(rootConfig) {
1710
+ const index = /* @__PURE__ */ new Map();
1711
+ const walk = (states, parentPath) => {
1712
+ for (const [name, config] of Object.entries(states ?? {})) {
1713
+ const path = parentPath ? `${parentPath}.${name}` : name;
1714
+ const hasChildren = !!config.states && Object.keys(config.states).length > 0;
1715
+ index.set(path, {
1716
+ path,
1717
+ name,
1718
+ config,
1719
+ parentPath,
1720
+ type: config.type,
1721
+ isFinal: config.type === "final",
1722
+ isParallel: config.type === "parallel",
1723
+ isCompound: hasChildren && config.type !== "parallel",
1724
+ invokes: normalizeInvokes(config.invoke)
1725
+ });
1726
+ if (hasChildren) walk(config.states, path);
1727
+ }
1728
+ };
1729
+ walk(rootConfig.states, "");
1730
+ return index;
1731
+ }
1732
+ function childrenOf(index, parentPath) {
1733
+ const out = [];
1734
+ for (const node of index.values()) if (node.parentPath === parentPath) out.push(node);
1735
+ return out;
1736
+ }
1737
+ function collectTransitionTargets(value, fromNode, index, out) {
1738
+ if (value === void 0 || value === null) return;
1739
+ if (Array.isArray(value)) {
1740
+ for (const item of value) collectTransitionTargets(item, fromNode, index, out);
1741
+ return;
1742
+ }
1743
+ if (typeof value === "function") {
1744
+ out.opaque = true;
1745
+ return;
1746
+ }
1747
+ if (typeof value === "string") {
1748
+ resolveTargetString(value, fromNode, index, out);
1749
+ return;
1750
+ }
1751
+ if (typeof value === "object") {
1752
+ const { target, to } = value;
1753
+ if (target !== void 0) {
1754
+ collectTransitionTargets(target, fromNode, index, out);
1755
+ return;
1756
+ }
1757
+ if (to !== void 0) {
1758
+ collectTransitionTargets(to, fromNode, index, out);
1759
+ return;
1760
+ }
1761
+ }
1762
+ }
1763
+ function resolveTargetString(target, fromNode, index, out) {
1764
+ if (target.startsWith("#")) {
1765
+ out.opaque = true;
1766
+ return;
1767
+ }
1768
+ const resolved = target.startsWith(".") ? `${fromNode.path}.${target.slice(1)}` : fromNode.parentPath ? `${fromNode.parentPath}.${target}` : target;
1769
+ if (index.has(resolved)) out.targets.push(resolved);
1770
+ else out.opaque = true;
1771
+ }
1772
+ function outgoingTargets(node, index, staticTargets) {
1773
+ const out = {
1774
+ targets: [],
1775
+ opaque: false
1776
+ };
1777
+ const { config } = node;
1778
+ if (staticTargets) {
1779
+ for (const target of staticTargets[node.path] ?? []) resolveTargetString(target, node, index, out);
1780
+ return out;
1781
+ }
1782
+ for (const value of Object.values(config.on ?? {})) collectTransitionTargets(value, node, index, out);
1783
+ collectTransitionTargets(config.always, node, index, out);
1784
+ collectTransitionTargets(config.choice, node, index, out);
1785
+ for (const value of Object.values(config.after ?? {})) collectTransitionTargets(value, node, index, out);
1786
+ collectTransitionTargets(config.onDone, node, index, out);
1787
+ for (const invoke of node.invokes) {
1788
+ collectTransitionTargets(invoke.onDone, node, index, out);
1789
+ collectTransitionTargets(invoke.onError, node, index, out);
1790
+ }
1791
+ return out;
1792
+ }
1793
+ function computeReachable(rootConfig, index, staticTargets) {
1794
+ const reachable = /* @__PURE__ */ new Set();
1795
+ const queue = [];
1796
+ const markAncestors = (path) => {
1797
+ let parent = index.get(path)?.parentPath ?? "";
1798
+ while (parent) {
1799
+ reachable.add(parent);
1800
+ parent = index.get(parent)?.parentPath ?? "";
1801
+ }
1802
+ };
1803
+ const enter = (path) => {
1804
+ if (reachable.has(path)) return;
1805
+ const node = index.get(path);
1806
+ if (!node) return;
1807
+ reachable.add(path);
1808
+ queue.push(path);
1809
+ markAncestors(path);
1810
+ if (node.isParallel) for (const child of childrenOf(index, path)) enter(child.path);
1811
+ else if (node.isCompound && node.config.initial) enter(`${path}.${node.config.initial}`);
1812
+ };
1813
+ if (rootConfig.type === "parallel") for (const child of childrenOf(index, "")) enter(child.path);
1814
+ else if (rootConfig.initial) enter(rootConfig.initial);
1815
+ while (queue.length > 0) {
1816
+ const node = index.get(queue.shift());
1817
+ if (!node) continue;
1818
+ const { targets, opaque } = outgoingTargets(node, index, staticTargets);
1819
+ for (const target of targets) enter(target);
1820
+ if (opaque) for (const sibling of childrenOf(index, node.parentPath)) enter(sibling.path);
1821
+ }
1822
+ return reachable;
1823
+ }
1824
+ function ancestorChain(node, index) {
1825
+ const chain = [];
1826
+ let parent = node.parentPath;
1827
+ while (parent) {
1828
+ const parentNode = index.get(parent);
1829
+ if (!parentNode) break;
1830
+ chain.push(parentNode);
1831
+ parent = parentNode.parentPath;
1832
+ }
1833
+ return chain;
1834
+ }
1835
+ function hasNonEmptyOn(config) {
1836
+ return !!config.on && Object.keys(config.on).length > 0;
1837
+ }
1838
+ function decisionKindOf(src, actors) {
1839
+ if (typeof src === "string") {
1840
+ if (src === DECIDE_SRC) return "decision";
1841
+ if (src === PLAN_SRC) return "plan";
1842
+ const logic = actors[src];
1843
+ if (isDecisionLogic(logic)) return "decision";
1844
+ if (isPlanLogic(logic)) return "plan";
1845
+ return;
1846
+ }
1847
+ if (isDecisionLogic(src)) return "decision";
1848
+ if (isPlanLogic(src)) return "plan";
1849
+ }
1850
+ function isAgentLogicNeedingBinding(src) {
1851
+ return (isTextLogic(src) || isDecisionLogic(src) || isPlanLogic(src)) && !executorBoundLogics.has(src);
1852
+ }
1853
+ function schemaExposesJson(schema) {
1854
+ if (!schema) return false;
1855
+ try {
1856
+ return getJsonSchemaSync(schema) !== void 0;
1857
+ } catch {
1858
+ return false;
1859
+ }
1860
+ }
1861
+ function isDeclaredOutputSchema(schema) {
1862
+ if (!schema) return false;
1863
+ let json;
1864
+ try {
1865
+ json = getJsonSchemaSync(schema);
1866
+ } catch {
1867
+ return false;
1868
+ }
1869
+ if (!json) return false;
1870
+ const properties = json.properties;
1871
+ const required = json.required;
1872
+ return json.type === "object" && !!properties && Object.keys(properties).length > 0 || Array.isArray(required) && required.length > 0;
1873
+ }
1874
+ function checkUnreachableStates(ctx) {
1875
+ const out = [];
1876
+ for (const node of ctx.index.values()) if (!ctx.reachable.has(node.path)) out.push({
1877
+ code: "unreachable-state",
1878
+ severity: "error",
1879
+ path: node.path,
1880
+ message: `State '${node.path}' is unreachable: no transition, always, onDone, or onError target (from any reachable state) leads to it. Remove it or add a transition.`
1881
+ });
1882
+ return out;
1883
+ }
1884
+ function checkDecideWithoutEvents(ctx) {
1885
+ const out = [];
1886
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
1887
+ const kind = decisionKindOf(invoke.src, ctx.actors);
1888
+ if (!kind) continue;
1889
+ const selfHandles = hasNonEmptyOn(node.config);
1890
+ const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
1891
+ const invokeObserves = invoke.onDone !== void 0;
1892
+ if (selfHandles || ancestorHandles || invokeObserves) continue;
1893
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
1894
+ out.push({
1895
+ code: "decide-without-events",
1896
+ severity: "error",
1897
+ path: node.path,
1898
+ message: `State '${node.path}' invokes ${kind} source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the ${kind}'s chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
1899
+ });
1900
+ }
1901
+ return out;
1902
+ }
1903
+ function checkUnserializableContext(ctx) {
1904
+ const contextSchema = ctx.schemas?.context;
1905
+ if (!contextSchema) return [];
1906
+ if (schemaExposesJson(contextSchema)) return [];
1907
+ return [{
1908
+ code: "unserializable-context",
1909
+ severity: "warning",
1910
+ path: "context",
1911
+ message: "The context schema does not expose a JSON schema (e.g. a `z.custom` without a `jsonSchema` extension, such as a messages array), so its fields cannot be statically checked for JSON persist/resume round-tripping. This is expected for message transcripts; verify any other custom-typed context is JSON-serializable."
1912
+ }];
1913
+ }
1914
+ function checkDirectObjectSrc(ctx) {
1915
+ const out = [];
1916
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
1917
+ const src = invoke.src;
1918
+ if (typeof src === "string" || !src || typeof src !== "object") continue;
1919
+ if (!isAgentLogicNeedingBinding(src)) continue;
1920
+ out.push({
1921
+ code: "direct-object-src",
1922
+ severity: "warning",
1923
+ path: node.path,
1924
+ 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.`
1925
+ });
1926
+ }
1927
+ return out;
1928
+ }
1929
+ function checkFinalWithoutOutput(ctx) {
1930
+ if (!isDeclaredOutputSchema(ctx.schemas?.output)) return [];
1931
+ if (ctx.config.output !== void 0) return [];
1932
+ const out = [];
1933
+ for (const node of ctx.index.values()) {
1934
+ if (node.parentPath !== "" || !node.isFinal) continue;
1935
+ if (node.config.output === void 0) out.push({
1936
+ code: "final-without-output",
1937
+ severity: "error",
1938
+ path: node.path,
1939
+ message: `The machine declares an output schema, but top-level final state '${node.path}' has no 'output'. Its snapshot output will be undefined and fail the schema. Add an 'output' to this final state (or a root 'output').`
1940
+ });
1941
+ }
1942
+ return out;
1943
+ }
1944
+ function outputFnReadsEvent(fn) {
1945
+ return /\bevent\s*(?:\.|\?\.|\[)/.test(fn.toString());
1946
+ }
1947
+ function checkFinalOutputReadsEvent(ctx) {
1948
+ const out = [];
1949
+ for (const node of ctx.index.values()) {
1950
+ if (node.parentPath !== "" || !node.isFinal) continue;
1951
+ const output = node.config.output;
1952
+ if (typeof output !== "function") continue;
1953
+ if (!outputFnReadsEvent(output)) continue;
1954
+ out.push({
1955
+ code: "final-output-reads-event",
1956
+ severity: "warning",
1957
+ path: node.path,
1958
+ message: `Final state '${node.path}' has an 'output' function that reads 'event'. Final-state 'output' functions are evaluated more than once with different events (the entering event, then the machine-done computation) under current xstate behavior, so 'event' is unreliable here. Read 'context' only; capture what you need from the entering event into context in the transition that targets this state. (This guard can relax if xstate guarantees a stable entering event across evaluations.)`
1959
+ });
1960
+ }
1961
+ return out;
1962
+ }
1963
+ function isBuiltinOrWildcardEvent(eventType) {
1964
+ return eventType === "*" || eventType.includes("*") || eventType.startsWith("xstate.") || eventType.startsWith("done.") || eventType.startsWith("error.");
1965
+ }
1966
+ function checkUndeclaredEvents(ctx) {
1967
+ const declared = ctx.schemas?.events;
1968
+ const declaredTypes = new Set(Object.keys(declared ?? {}));
1969
+ if ([...declaredTypes].every((type) => type.startsWith("@agent."))) return [];
1970
+ const out = [];
1971
+ for (const node of ctx.index.values()) for (const eventType of Object.keys(node.config.on ?? {})) {
1972
+ if (declaredTypes.has(eventType) || isBuiltinOrWildcardEvent(eventType)) continue;
1973
+ out.push({
1974
+ code: "undeclared-event",
1975
+ severity: "warning",
1976
+ path: node.path,
1977
+ message: `State '${node.path}' handles event '${eventType}' in 'on:', but it is not declared in schemas.events and is not a builtin/wildcard pattern. If intentional its payload stays unvalidated; otherwise this is likely a typo.`
1978
+ });
1979
+ }
1980
+ return out;
1981
+ }
1982
+ function checkMissingFinal(ctx) {
1983
+ for (const node of ctx.index.values()) if (node.isFinal && ctx.reachable.has(node.path)) return [];
1984
+ return [{
1985
+ code: "missing-final",
1986
+ severity: "warning",
1987
+ path: "(root)",
1988
+ message: "The machine has no reachable final state, so a run can never settle 'done' (only idle/looping). This is legal for agents that only idle, but verify it is intended."
1989
+ }];
1990
+ }
1991
+ const LINT_CHECKS = [
1992
+ checkUnreachableStates,
1993
+ checkDecideWithoutEvents,
1994
+ checkUnserializableContext,
1995
+ checkDirectObjectSrc,
1996
+ checkFinalWithoutOutput,
1997
+ checkFinalOutputReadsEvent,
1998
+ checkUndeclaredEvents,
1999
+ checkMissingFinal
2000
+ ];
2001
+ /**
2002
+ * Runs static structural checks over a built agent machine and returns the
2003
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
2004
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
2005
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
2006
+ * plus the schemas/actor sources the library already retains per machine.
2007
+ *
2008
+ * No model calls, no API keys — a coding agent that emits an agent machine can
2009
+ * call this to catch dead states, undeliverable decisions, un-rebindable
2010
+ * invoke srcs, and output-contract gaps before ever running it.
2011
+ *
2012
+ * @example
2013
+ * ```ts
2014
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
2015
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
2016
+ * ```
2017
+ */
2018
+ function lintAgentMachine(machine, options = {}) {
2019
+ const config = machine.config ?? {};
2020
+ const index = buildStateIndex(config);
2021
+ const reachable = computeReachable(config, index, getMachineStaticTransitionTargets(machine));
2022
+ const registered = getRegisteredAgentExecutionOptions(machine);
2023
+ const ctx = {
2024
+ machine,
2025
+ config,
2026
+ index,
2027
+ reachable,
2028
+ schemas: registered.schemas,
2029
+ actors: registered.actors ?? machine.sources?.actors ?? {}
2030
+ };
2031
+ const disabled = new Set(options.disable ?? []);
2032
+ return LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
2033
+ }
2034
+ /**
2035
+ * Thrown by {@link assertAgentMachine} when lint finds failing diagnostics.
2036
+ * `diagnostics` holds the findings; the message lists them one per finding,
2037
+ * so a test runner's failure output reads like the CLI's lint report.
2038
+ */
2039
+ var AgentLintError = class extends AgentError {
2040
+ diagnostics;
2041
+ constructor(machineId, diagnostics) {
2042
+ const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
2043
+ super("lint-failed", `Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
2044
+ this.name = "AgentLintError";
2045
+ this.diagnostics = diagnostics;
2046
+ }
2047
+ };
2048
+ /**
2049
+ * Asserts a machine passes {@link lintAgentMachine}: returns silently when
2050
+ * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
2051
+ * otherwise. Fails on error-severity findings; set `warnings: true` to fail on
2052
+ * warnings too. The one-liner for tests and generation loops:
2053
+ *
2054
+ * @example
2055
+ * ```ts
2056
+ * test('agent machine is structurally sound', () => {
2057
+ * assertAgentMachine(machine);
2058
+ * });
2059
+ * ```
2060
+ */
2061
+ function assertAgentMachine(machine, options = {}) {
2062
+ const diagnostics = lintAgentMachine(machine, options);
2063
+ const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
2064
+ if (failing.length > 0) throw new AgentLintError(machine.id ?? "(machine)", failing);
2065
+ }
2066
+ function pendingInvokes(step) {
2067
+ const out = [];
2068
+ for (const action of step.actions) {
2069
+ const metadata = getInvokeEffectMetadata(action);
2070
+ if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
2071
+ id: metadata.id,
2072
+ src: metadata.src
2073
+ });
2074
+ }
2075
+ return out;
2076
+ }
2077
+ function takeFromQueue(channel, src) {
2078
+ const queue = channel?.[src];
2079
+ if (queue && queue.length > 0) return {
2080
+ found: true,
2081
+ value: queue.shift()
2082
+ };
2083
+ return { found: false };
2084
+ }
2085
+ /**
2086
+ * Deterministically plays a machine through, resolving each request from a
2087
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
2088
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
2089
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
2090
+ * and a `trail` of every step taken.
2091
+ *
2092
+ * Throws a descriptive error when the script runs dry mid-request, naming the
2093
+ * pending request's kind, src, and id so the missing scripted response is
2094
+ * obvious.
2095
+ *
2096
+ * @example
2097
+ * ```ts
2098
+ * const { status, snapshot } = simulateAgent(machine, {
2099
+ * input: { topic: 'state machines' },
2100
+ * script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
2101
+ * });
2102
+ * ```
2103
+ */
2104
+ async function simulateAgent(machine, options) {
2105
+ const maxSteps = options.maxSteps ?? 100;
2106
+ const script = {
2107
+ text: { ...options.script.text },
2108
+ decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
2109
+ invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr])
2110
+ };
2111
+ let step = initialAgentStep(machine, options.input);
2112
+ const trail = [];
2113
+ for (let i = 0; i < maxSteps; i++) {
2114
+ if (step.done) return {
2115
+ status: "done",
2116
+ snapshot: step.snapshot,
2117
+ trail
2118
+ };
2119
+ const request = step.requests[0];
2120
+ if (request) {
2121
+ if (request.kind === "decision") {
2122
+ const decisionSrc = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src])).get(request.id) ?? request.id;
2123
+ const taken = takeFromQueue(script.decisions, decisionSrc);
2124
+ if (!taken.found) throw scriptDryError("decision", decisionSrc, request.id, request);
2125
+ step = transitionAgentStep(machine, step, taken.value);
2126
+ trail.push({
2127
+ state: step.snapshot.value,
2128
+ appliedEvent: taken.value
2129
+ });
2130
+ continue;
2131
+ }
2132
+ if (request.kind === "plan") {
2133
+ const taken = takeFromQueue(script.decisions, request.src);
2134
+ if (!taken.found) throw scriptDryError("decision", request.src, request.id, request);
2135
+ const event = taken.value;
2136
+ step = await resolveAgentRequests(machine, step, { decide: async () => ({ event }) });
2137
+ trail.push({
2138
+ state: step.snapshot.value,
2139
+ appliedEvent: taken.value
2140
+ });
2141
+ continue;
2142
+ }
2143
+ const taken = takeFromQueue(script.text, request.src);
2144
+ if (!taken.found) throw scriptDryError("text", request.src, request.id);
2145
+ step = resolveAgentStep(machine, step, request, taken.value);
2146
+ trail.push({
2147
+ state: step.snapshot.value,
2148
+ resolvedRequest: {
2149
+ kind: "text",
2150
+ src: request.src,
2151
+ id: request.id
2152
+ }
2153
+ });
2154
+ continue;
2155
+ }
2156
+ const [invoke] = pendingInvokes(step);
2157
+ if (invoke) {
2158
+ const taken = takeFromQueue(script.invokes, invoke.src);
2159
+ if (!taken.found) throw scriptDryError("userInput", invoke.src, invoke.id);
2160
+ step = resolveAgentStep(machine, step, invoke.id, taken.value);
2161
+ trail.push({
2162
+ state: step.snapshot.value,
2163
+ resolvedRequest: {
2164
+ kind: "userInput",
2165
+ src: invoke.src,
2166
+ id: invoke.id
2167
+ }
2168
+ });
2169
+ continue;
2170
+ }
2171
+ return {
2172
+ status: "idle",
2173
+ snapshot: step.snapshot,
2174
+ trail
2175
+ };
2176
+ }
2177
+ return {
2178
+ status: "exhausted",
2179
+ snapshot: step.snapshot,
2180
+ trail
2181
+ };
2182
+ }
2183
+ function mapValues(obj, fn) {
2184
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
2185
+ }
2186
+ function scriptDryError(kind, src, id, request) {
2187
+ const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
2188
+ return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add a '${kind}' entry for '${src}' to the script.${events}`);
2189
+ }
2190
+ async function explore(machine, options, stopWhen) {
2191
+ const maxDepth = options.maxDepth ?? 8;
2192
+ const maxPaths = options.maxPaths ?? 200;
2193
+ const textOutputs = options.textOutputs ?? {};
2194
+ const reachedStates = /* @__PURE__ */ new Set();
2195
+ const reachedValues = [];
2196
+ const terminals = [];
2197
+ const unexplored = [];
2198
+ let prunedByGuard = 0;
2199
+ let pathsExplored = 0;
2200
+ let hitPathCap = false;
2201
+ let witness;
2202
+ const recordState = (snapshot) => {
2203
+ const key = JSON.stringify(snapshot.value);
2204
+ if (!reachedStates.has(key)) {
2205
+ reachedStates.add(key);
2206
+ reachedValues.push(snapshot.value);
2207
+ }
2208
+ };
2209
+ const initial = initialAgentStep(machine, options.input);
2210
+ recordState(initial.snapshot);
2211
+ if (stopWhen?.(initial.snapshot)) witness = [];
2212
+ const advance = (step) => {
2213
+ let current = step;
2214
+ for (let i = 0; i < 1e3; i++) {
2215
+ if (current.done) return { step: current };
2216
+ const request = current.requests[0];
2217
+ if (request && request.kind === "text") {
2218
+ if (!(request.src in textOutputs)) return {
2219
+ step: current,
2220
+ blockedSrc: request.src
2221
+ };
2222
+ current = resolveAgentStep(machine, current, request, textOutputs[request.src]);
2223
+ recordState(current.snapshot);
2224
+ continue;
2225
+ }
2226
+ if (request && (request.kind === "decision" || request.kind === "plan")) return { step: current };
2227
+ const [invoke] = pendingInvokes(current);
2228
+ if (invoke) {
2229
+ if (!(invoke.src in textOutputs)) return {
2230
+ step: current,
2231
+ blockedSrc: invoke.src
2232
+ };
2233
+ current = resolveAgentStep(machine, current, invoke.id, textOutputs[invoke.src]);
2234
+ recordState(current.snapshot);
2235
+ continue;
2236
+ }
2237
+ return { step: current };
2238
+ }
2239
+ return { step: current };
2240
+ };
2241
+ const visit = async (step, path, depth) => {
2242
+ if (witness !== void 0) return;
2243
+ if (pathsExplored >= maxPaths) {
2244
+ hitPathCap = true;
2245
+ return;
2246
+ }
2247
+ const { step: settled, blockedSrc } = advance(step);
2248
+ if (stopWhen?.(settled.snapshot)) {
2249
+ witness = path;
2250
+ return;
2251
+ }
2252
+ if (blockedSrc) {
2253
+ pathsExplored++;
2254
+ terminals.push({
2255
+ status: "needs-output",
2256
+ path,
2257
+ state: settled.snapshot.value,
2258
+ missingSrc: blockedSrc
2259
+ });
2260
+ unexplored.push(`needs-output: no canned output for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
2261
+ return;
2262
+ }
2263
+ if (settled.done) {
2264
+ pathsExplored++;
2265
+ terminals.push({
2266
+ status: "done",
2267
+ path,
2268
+ state: settled.snapshot.value
2269
+ });
2270
+ return;
2271
+ }
2272
+ const request = settled.requests[0];
2273
+ const isPlan = request?.kind === "plan";
2274
+ const branchEvents = request?.kind === "decision" || request?.kind === "plan" ? request.events.map((descriptor) => ({ type: descriptor.type })) : getAcceptedEvents(settled.snapshot).map((descriptor) => ({ type: descriptor.type }));
2275
+ if (branchEvents.length === 0) {
2276
+ pathsExplored++;
2277
+ terminals.push({
2278
+ status: "idle",
2279
+ path,
2280
+ state: settled.snapshot.value
2281
+ });
2282
+ return;
2283
+ }
2284
+ if (depth >= maxDepth) {
2285
+ pathsExplored++;
2286
+ terminals.push({
2287
+ status: "max-depth",
2288
+ path,
2289
+ state: settled.snapshot.value
2290
+ });
2291
+ unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
2292
+ return;
2293
+ }
2294
+ for (const event of branchEvents) {
2295
+ if (witness !== void 0 || pathsExplored >= maxPaths) {
2296
+ if (pathsExplored >= maxPaths) hitPathCap = true;
2297
+ return;
2298
+ }
2299
+ if (!(isPlan && event.type === "agent.plan.done") && !settled.snapshot.can(event)) {
2300
+ prunedByGuard++;
2301
+ continue;
2302
+ }
2303
+ const next = isPlan ? await resolveAgentRequests(machine, settled, { decide: async () => ({ event }) }) : transitionAgentStep(machine, settled, event);
2304
+ recordState(next.snapshot);
2305
+ await visit(next, [...path, event], depth + 1);
2306
+ }
2307
+ };
2308
+ if (witness === void 0) await visit(initial, [], 0);
2309
+ return {
2310
+ report: {
2311
+ reachedStates: reachedValues,
2312
+ terminals,
2313
+ prunedByGuard,
2314
+ unexplored,
2315
+ pathsExplored,
2316
+ hitPathCap
2317
+ },
2318
+ witness
2319
+ };
2320
+ }
2321
+ /**
2322
+ * Enumerates a machine's decision and external-event branches to a bounded
2323
+ * depth, model-free, and reports which states are reached and how each path
2324
+ * terminates. At each decision request it forks one branch per candidate event
2325
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
2326
+ * an idle wait it forks per externally-accepted event. A `agent.plan` request
2327
+ * forks the same way — one branch per candidate, including the reserved
2328
+ * `agent.plan.done` move — advancing each branch through the real plan protocol
2329
+ * (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
2330
+ * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
2331
+ * halts that branch with a `needs-output` terminal rather than throwing.
2332
+ *
2333
+ * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
2334
+ * 200, reported via `hitPathCap`).
2335
+ *
2336
+ * @example
2337
+ * ```ts
2338
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
2339
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
2340
+ * ```
2341
+ */
2342
+ async function explorePaths(machine, options = {}) {
2343
+ return (await explore(machine, options)).report;
2344
+ }
2345
+ /**
2346
+ * Answers "can the machine reach `statePath`?" by exploring its branches (a
2347
+ * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
2348
+ * with the event sequence that reaches it, or `{ canReach: false }`.
2349
+ *
2350
+ * @example
2351
+ * ```ts
2352
+ * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
2353
+ * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
2354
+ * ```
2355
+ */
2356
+ async function canReach(machine, statePath, options = {}) {
2357
+ const { witness } = await explore(machine, options, (snapshot) => {
2358
+ try {
2359
+ return snapshot.matches(statePath);
2360
+ } catch {
2361
+ return false;
2362
+ }
2363
+ });
2364
+ return witness !== void 0 ? {
2365
+ canReach: true,
2366
+ witness
2367
+ } : { canReach: false };
2368
+ }
2369
+ //#endregion
2370
+ //#region src/trajectory.ts
2371
+ function isRecord$2(value) {
2372
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2373
+ }
2374
+ /**
2375
+ * Classifies one item. Event-shaped things (log entries, events) become events;
2376
+ * everything else is a state value. A snapshot is unwrapped to its `value`.
2377
+ * @internal
2378
+ */
2379
+ function normalize(item) {
2380
+ if (isRecord$2(item)) {
2381
+ const nested = item["event"];
2382
+ if (isRecord$2(nested) && typeof nested["type"] === "string") return {
2383
+ kind: "event",
2384
+ event: nested
2385
+ };
2386
+ if (typeof item["type"] === "string") return {
2387
+ kind: "event",
2388
+ event: item
2389
+ };
2390
+ if ("value" in item && "status" in item) return {
2391
+ kind: "state",
2392
+ value: item["value"]
2393
+ };
2394
+ }
2395
+ return {
2396
+ kind: "state",
2397
+ value: item
2398
+ };
2399
+ }
2400
+ /** Every leaf of a state value as a dot path (`{ review: 'editing' }` → `review.editing`). @internal */
2401
+ function statePaths(value) {
2402
+ if (typeof value === "string") return [value];
2403
+ if (!isRecord$2(value)) return [];
2404
+ return Object.entries(value).flatMap(([key, child]) => statePaths(child).map((path) => `${key}.${path}`));
2405
+ }
2406
+ /**
2407
+ * A string expectation matches a state value when it names one of its leaves or
2408
+ * an ancestor of one, so `'review'` matches `{ review: 'editing' }`. @internal
2409
+ */
2410
+ function stateMatchesPath(path, value) {
2411
+ return statePaths(value).some((leaf) => leaf === path || leaf.startsWith(`${path}.`));
2412
+ }
2413
+ function deepEqual(a, b) {
2414
+ if (Object.is(a, b)) return true;
2415
+ 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]));
2416
+ if (!isRecord$2(a) || !isRecord$2(b)) return false;
2417
+ const keys = Object.keys(a);
2418
+ return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
2419
+ }
2420
+ /**
2421
+ * Does one actual item satisfy one expected item?
2422
+ *
2423
+ * - A string expectation matches an event's `type`, or a state value it names.
2424
+ * - An event expectation matches an event with the same `type` whose other
2425
+ * declared keys deep-equal, so payload details are opt-in.
2426
+ * - A state-value expectation matches structurally.
2427
+ * @internal
2428
+ */
2429
+ function matchesItem(expected, actual) {
2430
+ const actualItem = normalize(actual);
2431
+ if (typeof expected === "string") return actualItem.kind === "event" ? actualItem.event.type === expected : stateMatchesPath(expected, actualItem.value);
2432
+ const expectedItem = normalize(expected);
2433
+ if (expectedItem.kind !== actualItem.kind) return false;
2434
+ if (expectedItem.kind === "event" && actualItem.kind === "event") return Object.keys(expectedItem.event).every((key) => deepEqual(expectedItem.event[key], actualItem.event[key]));
2435
+ return deepEqual(expectedItem.value, actualItem.value);
2436
+ }
2437
+ /**
2438
+ * Matches a run's trajectory against an expected one.
2439
+ *
2440
+ * Both trajectories may be state values (collected from `onTransition`) or
2441
+ * events (`result.events`, whose {@link AgentLogEntry} envelopes are unwrapped);
2442
+ * items are compared by shape, so `['prompting', 'drafting']` scores a state
2443
+ * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
2444
+ * call.
2445
+ *
2446
+ * Semantics are an ordered subsequence: every expected item must appear in
2447
+ * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
2448
+ * equality instead.
2449
+ *
2450
+ * @example Trajectory assertions in a test
2451
+ * ```ts
2452
+ * const statePath: unknown[] = [];
2453
+ * const result = await runAgent(machine, {
2454
+ * input,
2455
+ * executors,
2456
+ * onTransition: (snapshot) => statePath.push(snapshot.value),
2457
+ * });
2458
+ *
2459
+ * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
2460
+ * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
2461
+ * expect(matchesTrajectory(result.events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
2462
+ * ```
2463
+ *
2464
+ * @example Partial credit in an eval scorer
2465
+ * ```ts
2466
+ * const match = matchesTrajectory(output.statePath, expected.statePath);
2467
+ * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
2468
+ * ```
2469
+ */
2470
+ function matchesTrajectory(actual, expected, options = {}) {
2471
+ const expectedCount = expected.length;
2472
+ if (options.exact) {
2473
+ let matchedCount = 0;
2474
+ let firstMiss;
2475
+ for (let index = 0; index < expectedCount; index++) {
2476
+ if (index < actual.length && matchesItem(expected[index], actual[index])) {
2477
+ matchedCount++;
2478
+ continue;
2479
+ }
2480
+ firstMiss = {
2481
+ index,
2482
+ expected: expected[index],
2483
+ searchedFrom: index
2484
+ };
2485
+ break;
2486
+ }
2487
+ const matched = !firstMiss && actual.length === expectedCount;
2488
+ const denominator = Math.max(expectedCount, actual.length);
2489
+ return {
2490
+ matched,
2491
+ matchedCount,
2492
+ expectedCount,
2493
+ score: matched ? 1 : denominator === 0 ? 1 : matchedCount / denominator,
2494
+ ...firstMiss ? { firstMiss } : {}
2495
+ };
2496
+ }
2497
+ let cursor = 0;
2498
+ let matchedCount = 0;
2499
+ for (let index = 0; index < expectedCount; index++) {
2500
+ const want = expected[index];
2501
+ let found = -1;
2502
+ for (let at = cursor; at < actual.length; at++) if (matchesItem(want, actual[at])) {
2503
+ found = at;
2504
+ break;
2505
+ }
2506
+ if (found === -1) return {
2507
+ matched: false,
2508
+ matchedCount,
2509
+ expectedCount,
2510
+ score: matchedCount / expectedCount,
2511
+ firstMiss: {
2512
+ index,
2513
+ expected: want,
2514
+ searchedFrom: cursor
2515
+ }
2516
+ };
2517
+ matchedCount++;
2518
+ cursor = found + 1;
2519
+ }
2520
+ return {
2521
+ matched: true,
2522
+ matchedCount,
2523
+ expectedCount,
2524
+ score: 1
2525
+ };
2526
+ }
2527
+ //#endregion
2528
+ //#region src/scripted-executors.ts
2529
+ /**
2530
+ * Scripted executors — a keyless, deterministic stand-in for a model host.
2531
+ *
2532
+ * `createScriptedExecutors` builds a full `{ generateText, streamText, decide }`
2533
+ * set that plays back canned answers from FIFO queues, so `runAgent` (or
2534
+ * `provideExecutors`, or a bare `TextLogic.execute`) runs with no API key and no
2535
+ * network. It is the fastest way to see a machine run, and the least ceremonial
2536
+ * way to test one: same machine, same executor contract, scripted answers.
2537
+ */
2538
+ /** Thrown when a scripted queue runs dry on a pending request. */
2539
+ var ScriptedExecutorsError = class extends AgentError {
2540
+ constructor(message) {
2541
+ super("scripted-executors-exhausted", message);
2542
+ this.name = "ScriptedExecutorsError";
2543
+ }
2544
+ };
2545
+ function isRecord$1(value) {
2546
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2547
+ }
2548
+ /** The only own keys an executor-result envelope carries. @internal */
2549
+ const TEXT_ENVELOPE_KEYS = new Set([
2550
+ "output",
2551
+ "usage",
2552
+ "raw"
2553
+ ]);
2554
+ /**
2555
+ * True when a scripted entry is the executor envelope rather than the output
2556
+ * value: it owns an `output` key and owns NOTHING outside the envelope's own
2557
+ * vocabulary. Bare `'output' in value` would swallow an output object's
2558
+ * siblings (`{ output: 'draft', confidence: 0.9 }` would lose `confidence`)
2559
+ * and would also match an inherited `output`. @internal
2560
+ */
2561
+ function isTextEnvelope(value) {
2562
+ return Object.hasOwn(value, "output") && Object.keys(value).every((key) => TEXT_ENVELOPE_KEYS.has(key));
2563
+ }
2564
+ /**
2565
+ * Resolves ONE scripted text entry to an executor result: a function entry is
2566
+ * called with the request, and the value is taken as the raw envelope only when
2567
+ * it is one (see {@link isTextEnvelope}). Shared with `runSeam`, whose routed
2568
+ * queues follow the same entry conventions. @internal
2569
+ */
2570
+ async function resolveScriptedTextEntry(entry, request, info) {
2571
+ const value = typeof entry === "function" ? await entry(request, info) : entry;
2572
+ return isRecord$1(value) && isTextEnvelope(value) ? value : { output: value };
2573
+ }
2574
+ /**
2575
+ * Keyless executors that replay a script instead of calling a model. Every
2576
+ * slot is provided, so any machine binds; a request with no entry left throws a
2577
+ * descriptive error naming what was pending.
2578
+ *
2579
+ * Queues are consumed FIFO and are copied on creation, so the caller's arrays
2580
+ * are never mutated and each call builds a fresh, independent playthrough.
2581
+ * Entries may be plain values or functions of the request, which is how one
2582
+ * script serves a machine that loops or branches: route on `request.name` (the
2583
+ * `setupAgent({ requests })` key) or on the decision's candidate `events`.
2584
+ *
2585
+ * @example
2586
+ * ```ts
2587
+ * const result = await runAgent(moderationMachine, {
2588
+ * input: { comment: 'honestly this update is terrible', trust: 20 },
2589
+ * executors: createScriptedExecutors({
2590
+ * decisions: [{ type: 'FLAG', reason: 'Borderline tone.' }],
2591
+ * }),
2592
+ * });
2593
+ * ```
2594
+ *
2595
+ * @example Dynamic entries
2596
+ * ```ts
2597
+ * createScriptedExecutors({
2598
+ * text: [(request) => `Draft about ${request.prompt}`],
2599
+ * decisions: [(request) => ({ type: request.events[0]!.type })],
2600
+ * });
2601
+ * ```
2602
+ */
2603
+ function createScriptedExecutors(script = {}) {
2604
+ const decisions = [...script.decisions ?? []];
2605
+ const text = [...script.text ?? []];
2606
+ const nextText = async (request, info) => {
2607
+ if (text.length === 0) throw new ScriptedExecutorsError(`createScriptedExecutors: script ran dry on a pending text request ${describeText(request)}. Add another entry to the script's \`text\` queue.`);
2608
+ return resolveScriptedTextEntry(text.shift(), request, info);
2609
+ };
2610
+ return {
2611
+ generateText: nextText,
2612
+ streamText: async (request, info) => {
2613
+ const result = await nextText(request, info);
2614
+ if (typeof result.output === "string") info?.onChunk?.(result.output);
2615
+ return result;
2616
+ },
2617
+ decide: async (request) => {
2618
+ if (decisions.length === 0) throw new ScriptedExecutorsError(`createScriptedExecutors: script ran dry on a pending decision request (id '${request.id}'). Add another entry to the script's \`decisions\` queue. Candidate events: ${request.events.map((event) => event.type).join(", ") || "(none)"}.`);
2619
+ const entry = decisions.shift();
2620
+ const value = typeof entry === "function" ? await entry(request) : entry;
2621
+ return typeof value.type === "string" ? { event: value } : value;
2622
+ }
2623
+ };
2624
+ }
2625
+ function describeText(request) {
2626
+ return request.name ? `'${request.name}'` : `(model '${request.model}')`;
2627
+ }
2628
+ //#endregion
2629
+ //#region src/seam.ts
2630
+ /** Thrown when the call plan runs dry on a request that is not the live seam. */
2631
+ var SeamScriptError = class extends AgentError {
2632
+ constructor(message) {
2633
+ super("seam-script-exhausted", message);
2634
+ this.name = "SeamScriptError";
2635
+ }
2636
+ };
2637
+ function seamKeyOf(seam) {
2638
+ return seam.request ?? seam.model;
2639
+ }
2640
+ function describeRequest(request) {
2641
+ return request.name ? `'${request.name}' (model '${request.model}')` : `(model '${request.model}')`;
2642
+ }
2643
+ function isRecord(value) {
2644
+ return typeof value === "object" && value !== null;
2645
+ }
2646
+ /**
2647
+ * The seam's own answer, for scoring. Our `{ output }` envelope is read
2648
+ * directly; a raw AI SDK `generateText` result contributes its `text`. A raw
2649
+ * STREAM result is left alone — the machine consumes that stream, and reading
2650
+ * it here would steal the chunks — so `seamOutput` is `undefined` for a
2651
+ * streaming candidate that returns one. Score its trajectory instead.
2652
+ * @internal
2653
+ */
2654
+ async function seamOutputOf(result, request) {
2655
+ if (!isRecord(result)) return;
2656
+ if ("output" in result) return await result["output"];
2657
+ if ("textStream" in result) return;
2658
+ return await normalizeGeneratorResult(result, `seam '${request.name ?? request.model}'`, { request });
2659
+ }
2660
+ /**
2661
+ * Runs a machine end to end with one model call under test, and slices the run
2662
+ * at that call.
2663
+ *
2664
+ * The `before`/`after` slices are the point: `after.statePath` is the branch
2665
+ * the seam chose and `after.events` is the same question against the durable
2666
+ * log, both ready for `matchesTrajectory`. The state slice splits where the
2667
+ * state path stood when the seam answered; the event slice splits at the
2668
+ * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
2669
+ * entry appended after the call was made).
2670
+ *
2671
+ * @example Keyless: the seam is scripted too, so the whole thing runs offline.
2672
+ * ```ts
2673
+ * const run = await runSeam(emailDrafter, {
2674
+ * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
2675
+ * seam: { request: 'evaluatePrompt' },
2676
+ * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
2677
+ * });
2678
+ *
2679
+ * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
2680
+ * ```
2681
+ *
2682
+ * @example A candidate prompt at the seam, scored against the same rows.
2683
+ * ```ts
2684
+ * const { generateText } = createAiSdkExecutors({ models });
2685
+ * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
2686
+ * ```
2687
+ */
2688
+ async function runSeam(machine, options) {
2689
+ const { seam, candidate } = options;
2690
+ const queues = new Map(Object.entries(options.scripts ?? {}).map(([key, answers]) => [key, [...answers]]));
2691
+ const statePath = [];
2692
+ let calls = 0;
2693
+ let seamMatches = 0;
2694
+ let seamOutput;
2695
+ let seamReached = false;
2696
+ let callsBeforeSeam = -1;
2697
+ let seamStateAt = 0;
2698
+ let seamEventAt = 0;
2699
+ let liveEvents = 0;
2700
+ const scriptedAnswer = async (request, info, optional) => {
2701
+ const key = request.name !== void 0 && queues.has(request.name) ? request.name : request.model;
2702
+ const queue = queues.get(key);
2703
+ if (!queue?.length) {
2704
+ if (optional) return;
2705
+ throw new SeamScriptError(`runSeam: no scripted answer left for request ${describeRequest(request)}. Add an entry to \`scripts.${key}\` — its last entry repeats, so one extra answer covers a longer branch.`);
2706
+ }
2707
+ return resolveScriptedTextEntry(queue.length === 1 ? queue[0] : queue.shift(), request, info);
2708
+ };
2709
+ const route = async (request, info) => {
2710
+ const callIndex = calls++;
2711
+ const isSeam = (seam.request !== void 0 ? request.name === seam.request : request.model === seam.model) && seamMatches++ === (seam.occurrence ?? 0);
2712
+ const scripted = await scriptedAnswer(request, info, isSeam && candidate !== void 0);
2713
+ if (!isSeam) return scripted;
2714
+ seamReached = true;
2715
+ callsBeforeSeam = callIndex;
2716
+ seamStateAt = statePath.length;
2717
+ seamEventAt = liveEvents;
2718
+ if (!candidate) {
2719
+ if (!scripted) throw new SeamScriptError(`runSeam: the seam '${seamKeyOf(seam)}' has no candidate and no scripted answer. Pass \`candidate\`, or script the seam's key.`);
2720
+ seamOutput = scripted.output;
2721
+ return scripted;
2722
+ }
2723
+ const result = await candidate(request, info);
2724
+ seamOutput = await seamOutputOf(result, request);
2725
+ return result;
2726
+ };
2727
+ const executors = {
2728
+ ...options.executors,
2729
+ generateText: route,
2730
+ streamText: async (request, info) => {
2731
+ const result = await route(request, info);
2732
+ const output = isRecord(result) ? result["output"] : void 0;
2733
+ if (typeof output === "string") info?.onChunk?.(output);
2734
+ return result;
2735
+ }
2736
+ };
2737
+ let snapshot;
2738
+ let event;
2739
+ let events = [];
2740
+ let result;
2741
+ const maxTurns = options.maxTurns ?? 12;
2742
+ for (let turn = 0; turn <= maxTurns; turn++) {
2743
+ result = await runAgent(machine, {
2744
+ ...snapshot ? { snapshot } : { input: options.input },
2745
+ ...event ? { event } : {},
2746
+ ...options.isSuspended ? { isSuspended: options.isSuspended } : {},
2747
+ ...options.actors ? { actors: options.actors } : {},
2748
+ events,
2749
+ executors,
2750
+ onEvent: () => {
2751
+ liveEvents++;
2752
+ },
2753
+ onTransition: (next, causedBy) => {
2754
+ if (turn > 0 && causedBy.type === "@xstate.init") return;
2755
+ statePath.push(next.value);
2756
+ }
2757
+ });
2758
+ events = result.events;
2759
+ liveEvents = events.length;
2760
+ if (result.status !== "idle" || turn === maxTurns) break;
2761
+ const next = options.respond?.({
2762
+ snapshot: result.snapshot,
2763
+ state: result.snapshot.value,
2764
+ meta: getStateMeta(result.snapshot),
2765
+ turn,
2766
+ result
2767
+ });
2768
+ if (!next) break;
2769
+ event = next;
2770
+ snapshot = result.snapshot;
2771
+ }
2772
+ let splitAt = events.length;
2773
+ if (seamReached) {
2774
+ splitAt = seamEventAt;
2775
+ for (let index = seamEventAt; index < events.length; index++) {
2776
+ const type = events[index].event.type;
2777
+ if (type.startsWith("xstate.done") || type.startsWith("xstate.error")) {
2778
+ splitAt = index;
2779
+ break;
2780
+ }
2781
+ }
2782
+ }
2783
+ const splitStateAt = seamReached ? seamStateAt : statePath.length;
2784
+ return {
2785
+ result,
2786
+ seamOutput,
2787
+ callsBeforeSeam,
2788
+ before: {
2789
+ statePath: statePath.slice(0, splitStateAt),
2790
+ events: events.slice(0, splitAt)
2791
+ },
2792
+ after: {
2793
+ statePath: statePath.slice(splitStateAt),
2794
+ events: events.slice(splitAt)
2795
+ }
2796
+ };
2797
+ }
2798
+ //#endregion
2799
+ export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentIdleError, AgentIllegalResumeEventError, AgentLintError, AgentReplayDivergenceError, AgentReplayMachineMismatchError, AgentSnapshotVersionMismatchError, NonSerializableAgentEventError, PLAN_DONE_EVENT_TYPE, appendMessages, assertAgentLogEntry, assertAgentMachine, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage, verifyReplay };