@statelyai/agent 1.1.6 → 2.0.0-alpha.11

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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapter.cjs +15 -0
  3. package/dist/adapter.d.cts +4 -0
  4. package/dist/adapter.d.mts +4 -0
  5. package/dist/adapter.mjs +2 -0
  6. package/dist/ai-sdk.cjs +306 -0
  7. package/dist/ai-sdk.d.cts +96 -0
  8. package/dist/ai-sdk.d.mts +96 -0
  9. package/dist/ai-sdk.mjs +304 -0
  10. package/dist/decision-C3k4ve51.mjs +227 -0
  11. package/dist/decision-D8wJrM8W.cjs +286 -0
  12. package/dist/events-CRQj3VtP.cjs +1010 -0
  13. package/dist/events-JiVPYrct.mjs +759 -0
  14. package/dist/index.cjs +2528 -0
  15. package/dist/index.d.cts +1232 -0
  16. package/dist/index.d.mts +1217 -413
  17. package/dist/index.mjs +2489 -584
  18. package/dist/openai-compat.cjs +309 -0
  19. package/dist/openai-compat.d.cts +59 -0
  20. package/dist/openai-compat.d.mts +59 -0
  21. package/dist/openai-compat.mjs +308 -0
  22. package/dist/steps-BALp1eZo.d.mts +198 -0
  23. package/dist/steps-CVe54GPP.cjs +420 -0
  24. package/dist/steps-CkyyyuHd.mjs +379 -0
  25. package/dist/steps-MjnQI4aB.d.cts +198 -0
  26. package/dist/steps.cjs +12 -0
  27. package/dist/steps.d.cts +3 -0
  28. package/dist/steps.d.mts +3 -0
  29. package/dist/steps.mjs +3 -0
  30. package/dist/text-logic-CaKqgX4Y.d.mts +710 -0
  31. package/dist/text-logic-Ckhr2kKC.d.cts +710 -0
  32. package/dist/types-C9QiMjre.d.cts +219 -0
  33. package/dist/types-qm00QF91.d.mts +219 -0
  34. package/dist/utils-BYqT_Dyv.d.cts +108 -0
  35. package/dist/utils-Do5wIJrh.d.mts +108 -0
  36. package/dist/zod.cjs +31 -0
  37. package/dist/zod.d.cts +30 -0
  38. package/dist/zod.d.mts +30 -0
  39. package/dist/zod.mjs +30 -0
  40. package/package.json +132 -28
  41. package/readme.md +153 -6
  42. package/schemas/agent-workflow.json +526 -0
  43. package/.changeset/README.md +0 -8
  44. package/.changeset/config.json +0 -11
  45. package/.env.template +0 -3
  46. package/.github/actions/ci-setup/action.yml +0 -24
  47. package/.github/workflows/release.yml +0 -46
  48. package/.vscode/launch.json +0 -28
  49. package/CHANGELOG.md +0 -222
  50. package/dist/index.d.ts +0 -428
  51. package/dist/index.js +0 -621
  52. package/examples/chatbot.ts +0 -71
  53. package/examples/cot.ts +0 -89
  54. package/examples/email.ts +0 -118
  55. package/examples/example.ts +0 -81
  56. package/examples/goal.ts +0 -94
  57. package/examples/helpers/helpers.ts +0 -17
  58. package/examples/helpers/loader.ts +0 -32
  59. package/examples/helpers/runner.ts +0 -27
  60. package/examples/joke.ts +0 -225
  61. package/examples/multi.ts +0 -103
  62. package/examples/newspaper.ts +0 -324
  63. package/examples/number.ts +0 -102
  64. package/examples/raffle.ts +0 -105
  65. package/examples/sandbox.ts +0 -28
  66. package/examples/simple.ts +0 -39
  67. package/examples/support.ts +0 -147
  68. package/examples/ticTacToe.ts +0 -224
  69. package/examples/todo.ts +0 -137
  70. package/examples/tutor.ts +0 -100
  71. package/examples/verify.ts +0 -120
  72. package/examples/weather.ts +0 -178
  73. package/examples/wiki.ts +0 -30
  74. package/examples/word.ts +0 -171
  75. package/src/adapters/vercel.ts +0 -7
  76. package/src/agent-experimental.ts +0 -221
  77. package/src/agent.test.ts +0 -506
  78. package/src/agent.ts +0 -300
  79. package/src/decision.test.ts +0 -179
  80. package/src/decision.ts +0 -84
  81. package/src/index.ts +0 -4
  82. package/src/memory.ts +0 -25
  83. package/src/planners/shortestPathPlanner.ts +0 -22
  84. package/src/planners/simplePlanner.ts +0 -139
  85. package/src/schemas.ts +0 -11
  86. package/src/strategies/chain-of-note.ts +0 -155
  87. package/src/templates/defaultText.ts +0 -18
  88. package/src/text.ts +0 -241
  89. package/src/types.ts +0 -499
  90. package/src/utils.ts +0 -72
  91. package/tsconfig.json +0 -109
  92. package/vitest.config.ts +0 -9
package/dist/index.cjs ADDED
@@ -0,0 +1,2528 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_events = require("./events-CRQj3VtP.cjs");
3
+ const require_decision = require("./decision-D8wJrM8W.cjs");
4
+ const require_steps = require("./steps-CVe54GPP.cjs");
5
+ let xstate = require("xstate");
6
+ //#region src/messages.ts
7
+ function addMessages(resolve) {
8
+ return (args) => {
9
+ const resolved = typeof resolve === "function" ? resolve(args) : resolve;
10
+ return [...args.context.messages, ...Array.isArray(resolved) ? resolved : [resolved]];
11
+ };
12
+ }
13
+ /**
14
+ * Builds a transition-function result that appends one or more
15
+ * {@link AgentMessage}s to a context's `messages` array. `resolve` is either
16
+ * a message (or array of messages) or a function of `{ context, event }`
17
+ * returning them; the returned function is meant to be used directly as (or
18
+ * composed into) a transition's result, e.g. `on: { USER_REPLIED:
19
+ * agent.appendMessages(({ event }) => userMessage(event.text)) }`. Requires
20
+ * `messages: AgentMessage[]` on context — see {@link messagesSchema} for a
21
+ * ready-made schema for that field.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * on: {
26
+ * USER_REPLIED: appendMessages(({ event }) => userMessage(event.text)),
27
+ * }
28
+ * ```
29
+ */
30
+ function appendMessages(resolve) {
31
+ return (args) => ({ context: { messages: addMessages(resolve)(args) } });
32
+ }
33
+ const KNOWN_PART_TYPES = new Set([
34
+ "text",
35
+ "image",
36
+ "file",
37
+ "tool-call",
38
+ "tool-result"
39
+ ]);
40
+ function isKnownPart(part) {
41
+ return !!part && typeof part === "object" && KNOWN_PART_TYPES.has(part.type);
42
+ }
43
+ function validatePartsArray(content) {
44
+ if (!Array.isArray(content)) return "Expected content to be a string or an array of parts";
45
+ for (const part of content) if (!isKnownPart(part)) {
46
+ const type = part && typeof part === "object" ? part.type : void 0;
47
+ return `Unknown message part type: ${JSON.stringify(type)}`;
48
+ }
49
+ }
50
+ /**
51
+ * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
52
+ * checks that every message has a known `role` (`system`/`user`/`assistant`/
53
+ * `tool`) and that `content` is either a string (where the role allows it) or
54
+ * an array of parts with a known `type`. Use it directly as a context
55
+ * schema's `messages` field when authoring with `createAgentSchemas`.
56
+ */
57
+ const messagesSchema = { "~standard": {
58
+ version: 1,
59
+ vendor: "statelyai-agent",
60
+ validate(value) {
61
+ if (!Array.isArray(value)) return { issues: [{ message: "Expected an array of agent messages" }] };
62
+ for (const message of value) {
63
+ if (!message || typeof message !== "object") return { issues: [{ message: "Expected an array of agent messages" }] };
64
+ const role = message.role;
65
+ const content = message.content;
66
+ if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") return { issues: [{ message: `Unknown message role: ${JSON.stringify(role)}` }] };
67
+ if (role === "system") {
68
+ if (typeof content !== "string") return { issues: [{ message: "system message content must be a string" }] };
69
+ continue;
70
+ }
71
+ if (role === "tool") {
72
+ const error = validatePartsArray(content) ?? (content.some((part) => part.type !== "tool-result") ? "tool message content must contain only tool-result parts" : void 0);
73
+ if (error) return { issues: [{ message: error }] };
74
+ continue;
75
+ }
76
+ if (typeof content === "string") continue;
77
+ const error = validatePartsArray(content);
78
+ if (error) return { issues: [{ message: error }] };
79
+ }
80
+ return { value };
81
+ }
82
+ } };
83
+ //#endregion
84
+ //#region src/workflow-config.ts
85
+ const DECIDE_SRC$1 = "agent.decide";
86
+ const workflowConfigWholeExpressionPattern = /^\{\{\s*([\s\S]*?)\s*\}\}$/;
87
+ const workflowConfigTemplateExpressionPattern = /\{\{\s*([\s\S]*?)\s*\}\}/g;
88
+ function evaluateWorkflowConfigPath(expression, scope) {
89
+ const parts = expression.trim().split(".").filter(Boolean);
90
+ let current = scope;
91
+ for (const part of parts) {
92
+ if (!current || typeof current !== "object") return;
93
+ current = current[part];
94
+ }
95
+ return current;
96
+ }
97
+ function evaluateWorkflowConfigValue(value, scope) {
98
+ if (typeof value === "string") {
99
+ const wholeMatch = value.match(workflowConfigWholeExpressionPattern);
100
+ if (wholeMatch?.[1]) return evaluateWorkflowConfigPath(wholeMatch[1], scope);
101
+ return value.replace(workflowConfigTemplateExpressionPattern, (_match, expression) => {
102
+ const resolved = evaluateWorkflowConfigPath(expression, scope);
103
+ return resolved === void 0 || resolved === null ? "" : String(resolved);
104
+ });
105
+ }
106
+ if (Array.isArray(value)) return value.map((item) => evaluateWorkflowConfigValue(item, scope));
107
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, evaluateWorkflowConfigValue(item, scope)]));
108
+ return value;
109
+ }
110
+ function createSchemasFromWorkflowConfig(config, compileSchema) {
111
+ return createAgentSchemas({
112
+ context: compileSchema(config.schemas?.context ?? { type: "object" }, "context"),
113
+ events: Object.fromEntries(Object.entries(config.schemas?.events ?? {}).map(([key, schema]) => [key, compileSchema(schema, `event.${key}`)])),
114
+ emitted: Object.fromEntries(Object.entries(config.schemas?.emitted ?? {}).map(([key, schema]) => [key, compileSchema(schema, `emitted.${key}`)])),
115
+ input: compileSchema(config.schemas?.input ?? {}, "input"),
116
+ output: compileSchema(config.schemas?.output ?? {}, "output"),
117
+ meta: compileSchema(config.schemas?.meta ?? {}, "meta")
118
+ });
119
+ }
120
+ function createRequestsFromWorkflowConfig(config, compileSchema) {
121
+ return Object.fromEntries(Object.entries(config.requests ?? {}).map(([key, request]) => [key, {
122
+ mode: request.mode,
123
+ description: request.description,
124
+ schemas: {
125
+ input: compileSchema(request.input, `${key}.input`),
126
+ output: compileSchema(request.output, `${key}.output`)
127
+ },
128
+ model: ({ input }) => String(evaluateWorkflowConfigValue(request.model, { input }) ?? ""),
129
+ system: request.system === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.system, { input }),
130
+ prompt: request.prompt === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.prompt, { input }),
131
+ messages: request.messages === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.messages, { input }),
132
+ tools: request.tools,
133
+ toolChoice: request.toolChoice,
134
+ reasoning: request.reasoning,
135
+ temperature: request.temperature === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.temperature, { input }),
136
+ maxOutputTokens: request.maxOutputTokens === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.maxOutputTokens, { input }),
137
+ topP: request.topP === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.topP, { input }),
138
+ topK: request.topK === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.topK, { input }),
139
+ seed: request.seed === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.seed, { input }),
140
+ stopSequences: request.stopSequences === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.stopSequences, { input }),
141
+ metadata: request.metadata === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.metadata, { input })
142
+ }]));
143
+ }
144
+ function createActorPlaceholdersFromWorkflowConfig(config) {
145
+ return Object.fromEntries(Object.keys(config.actors ?? {}).map((key) => [key, require_events.missingActor(key)]));
146
+ }
147
+ function createAssignAction(assignConfig) {
148
+ return ({ context, event }) => ({ context: Object.fromEntries(Object.entries(assignConfig).map(([key, value]) => [key, evaluateWorkflowConfigValue(value, {
149
+ context,
150
+ event
151
+ })])) });
152
+ }
153
+ function lowerWorkflowActions(actionConfig) {
154
+ if (!actionConfig) return;
155
+ const lowered = (Array.isArray(actionConfig) ? actionConfig : [actionConfig]).map((action) => {
156
+ if (action.assign !== void 0) return createAssignAction(action.assign);
157
+ if (action.emit !== void 0) return ({ context, event }, enq) => {
158
+ enq.emit(evaluateWorkflowConfigValue(action.emit, {
159
+ context,
160
+ event
161
+ }));
162
+ };
163
+ if (!action.type) throw new Error("setupAgent.fromConfig: action must declare 'type', 'assign', or 'emit'.");
164
+ return {
165
+ type: action.type,
166
+ params: ({ context, event }) => evaluateWorkflowConfigValue(action.params, {
167
+ context,
168
+ event
169
+ })
170
+ };
171
+ });
172
+ return Array.isArray(actionConfig) ? lowered : lowered[0];
173
+ }
174
+ function workflowTransitionMatches(transitionConfig, scope) {
175
+ if (transitionConfig.guard === void 0) return true;
176
+ if (typeof transitionConfig.guard === "string") return Boolean(evaluateWorkflowConfigValue(transitionConfig.guard, scope));
177
+ return typeof transitionConfig.guard === "function" ? transitionConfig.guard(scope) : false;
178
+ }
179
+ function applyWorkflowTransitionActions(actionConfig, scope, enq) {
180
+ if (!actionConfig) return;
181
+ const actions = Array.isArray(actionConfig) ? actionConfig : [actionConfig];
182
+ let assigned;
183
+ for (const action of actions) if (action.assign !== void 0) assigned = {
184
+ ...assigned ?? {},
185
+ ...Object.fromEntries(Object.entries(action.assign).map(([key, value]) => [key, evaluateWorkflowConfigValue(value, scope)]))
186
+ };
187
+ else if (action.emit !== void 0) enq.emit(evaluateWorkflowConfigValue(action.emit, scope));
188
+ else if (action.type) throw new Error(`setupAgent.fromConfig: named action type '${action.type}' is not supported in a transition 'actions' entry (config lowering wires no action implementations). Use 'emit' or 'assign', or move it to a state 'entry'/'exit'.`);
189
+ else throw new Error("setupAgent.fromConfig: a transition action must declare 'emit', 'assign', or 'type'.");
190
+ return assigned;
191
+ }
192
+ function lowerWorkflowTransitionResult(transitionConfig, scope, enq) {
193
+ const actionAssign = applyWorkflowTransitionActions(transitionConfig.actions, scope, enq);
194
+ const configAssign = transitionConfig.assign ? Object.fromEntries(Object.entries(transitionConfig.assign).map(([key, value]) => [key, evaluateWorkflowConfigValue(value, scope)])) : void 0;
195
+ const context = configAssign || actionAssign ? {
196
+ ...configAssign ?? {},
197
+ ...actionAssign ?? {}
198
+ } : void 0;
199
+ return {
200
+ ...transitionConfig.target !== void 0 ? { target: transitionConfig.target } : {},
201
+ ...context ? { context } : {},
202
+ ...transitionConfig.description !== void 0 ? { description: transitionConfig.description } : {},
203
+ ...transitionConfig.reenter !== void 0 ? { reenter: transitionConfig.reenter } : {},
204
+ ...transitionConfig.meta !== void 0 ? { meta: transitionConfig.meta } : {}
205
+ };
206
+ }
207
+ function lowerWorkflowTransition(transitionConfig) {
208
+ return ({ context, event }, enq) => {
209
+ const scope = {
210
+ context,
211
+ event
212
+ };
213
+ if (!workflowTransitionMatches(transitionConfig, scope)) return;
214
+ return lowerWorkflowTransitionResult(transitionConfig, scope, enq);
215
+ };
216
+ }
217
+ function lowerWorkflowTransitionOrArray(transitionConfig) {
218
+ if (!transitionConfig) return;
219
+ return Array.isArray(transitionConfig) ? ({ context, event }, enq) => {
220
+ const scope = {
221
+ context,
222
+ event
223
+ };
224
+ const transition = transitionConfig.find((candidate) => workflowTransitionMatches(candidate, scope));
225
+ if (!transition) return;
226
+ return lowerWorkflowTransitionResult(transition, scope, enq);
227
+ } : lowerWorkflowTransition(transitionConfig);
228
+ }
229
+ function lowerWorkflowInvoke(invokeConfig, stateKey) {
230
+ if (invokeConfig.src === DECIDE_SRC$1 && invokeConfig.onDone !== void 0) throw new Error(`setupAgent.fromConfig: state '${stateKey}' declares an 'onDone' on its 'agent.decide' invoke, which is always a config error. A decision has no output of its own — the chosen event is delivered automatically and handled by the state's 'on' transitions. Remove the 'onDone' (use 'on' for the chosen event; 'onError' still handles retries exhausted).`);
231
+ return {
232
+ ...invokeConfig.id !== void 0 ? { id: invokeConfig.id } : {},
233
+ src: invokeConfig.src,
234
+ ...invokeConfig.input !== void 0 ? { input: ({ context, event }) => evaluateWorkflowConfigValue(invokeConfig.input, {
235
+ context,
236
+ event
237
+ }) } : {},
238
+ ...invokeConfig.onDone !== void 0 ? { onDone: lowerWorkflowTransitionOrArray(invokeConfig.onDone) } : {},
239
+ ...invokeConfig.onError !== void 0 ? { onError: lowerWorkflowTransitionOrArray(invokeConfig.onError) } : {},
240
+ ...invokeConfig.meta !== void 0 ? { meta: invokeConfig.meta } : {}
241
+ };
242
+ }
243
+ function assertValidTransitionTargets(stateKey, location, transitionConfig, siblingKeys) {
244
+ if (!transitionConfig) return;
245
+ const transitions = Array.isArray(transitionConfig) ? transitionConfig : [transitionConfig];
246
+ for (const transition of transitions) {
247
+ const targets = transition.target === void 0 ? [] : Array.isArray(transition.target) ? transition.target : [transition.target];
248
+ for (const target of targets) {
249
+ if (typeof target !== "string" || target.startsWith("#") || target.startsWith(".")) continue;
250
+ const head = target.split(".")[0];
251
+ if (!siblingKeys.has(head)) throw new Error(`setupAgent.fromConfig: state '${stateKey}' has a ${location} transition targeting '${target}', which is not a state at that level. Valid targets: ${[...siblingKeys].join(", ") || "(none)"}.`);
252
+ }
253
+ }
254
+ }
255
+ function assertStateTransitionTargets(stateKey, stateConfig, siblingKeys) {
256
+ for (const [eventType, transition] of Object.entries(stateConfig.on ?? {})) assertValidTransitionTargets(stateKey, `'on.${eventType}'`, transition, siblingKeys);
257
+ for (const [delay, transition] of Object.entries(stateConfig.after ?? {})) assertValidTransitionTargets(stateKey, `'after.${delay}'`, transition, siblingKeys);
258
+ assertValidTransitionTargets(stateKey, "'always'", stateConfig.always, siblingKeys);
259
+ assertValidTransitionTargets(stateKey, "'onDone'", stateConfig.onDone, siblingKeys);
260
+ assertValidTransitionTargets(stateKey, "'choice'", stateConfig.choice, siblingKeys);
261
+ const invokes = stateConfig.invoke ? Array.isArray(stateConfig.invoke) ? stateConfig.invoke : [stateConfig.invoke] : [];
262
+ for (const invoke of invokes) {
263
+ assertValidTransitionTargets(stateKey, "invoke 'onDone'", invoke.onDone, siblingKeys);
264
+ assertValidTransitionTargets(stateKey, "invoke 'onError'", invoke.onError, siblingKeys);
265
+ }
266
+ }
267
+ function lowerWorkflowState(stateKey, stateConfig, siblingKeys) {
268
+ assertStateTransitionTargets(stateKey, stateConfig, siblingKeys);
269
+ const childKeys = new Set(Object.keys(stateConfig.states ?? {}));
270
+ return {
271
+ ...stateConfig.description !== void 0 ? { description: stateConfig.description } : {},
272
+ ...stateConfig.type !== void 0 ? { type: stateConfig.type } : {},
273
+ ...stateConfig.initial !== void 0 ? { initial: stateConfig.initial } : {},
274
+ ...stateConfig.states !== void 0 ? { states: Object.fromEntries(Object.entries(stateConfig.states).map(([key, child]) => [key, lowerWorkflowState(key, child, childKeys)])) } : {},
275
+ ...stateConfig.choice !== void 0 ? { choice: lowerWorkflowTransitionOrArray(stateConfig.choice) } : {},
276
+ ...stateConfig.invoke !== void 0 ? { invoke: Array.isArray(stateConfig.invoke) ? stateConfig.invoke.map((invoke) => lowerWorkflowInvoke(invoke, stateKey)) : lowerWorkflowInvoke(stateConfig.invoke, stateKey) } : {},
277
+ ...stateConfig.on !== void 0 ? { on: Object.fromEntries(Object.entries(stateConfig.on).map(([eventType, transitionConfig]) => [eventType, lowerWorkflowTransitionOrArray(transitionConfig)])) } : {},
278
+ ...stateConfig.always !== void 0 ? { always: lowerWorkflowTransitionOrArray(stateConfig.always) } : {},
279
+ ...stateConfig.onDone !== void 0 ? { onDone: lowerWorkflowTransitionOrArray(stateConfig.onDone) } : {},
280
+ ...stateConfig.after !== void 0 ? { after: Object.fromEntries(Object.entries(stateConfig.after).map(([delay, transitionConfig]) => [delay, lowerWorkflowTransitionOrArray(transitionConfig)])) } : {},
281
+ ...stateConfig.entry !== void 0 ? { entry: lowerWorkflowActions(stateConfig.entry) } : {},
282
+ ...stateConfig.exit !== void 0 ? { exit: lowerWorkflowActions(stateConfig.exit) } : {},
283
+ ...stateConfig.tags !== void 0 ? { tags: stateConfig.tags } : {},
284
+ ...stateConfig.output !== void 0 ? { output: ({ context, event }) => evaluateWorkflowConfigValue(stateConfig.output, {
285
+ context,
286
+ event
287
+ }) } : {},
288
+ ...stateConfig.meta !== void 0 ? { meta: stateConfig.meta } : {}
289
+ };
290
+ }
291
+ function setupAgentFromConfig(config, options) {
292
+ if (!options || typeof options.compileSchema !== "function") throw new Error("setupAgent.fromConfig(...) requires a 'compileSchema' option: { compileSchema: (jsonSchema, name) => StandardSchemaV1 }. Bring your own JSON Schema engine (Ajv, @cfworker/json-schema, a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no JSON Schema engine.");
293
+ const { compileSchema } = options;
294
+ const schemas = createSchemasFromWorkflowConfig(config, compileSchema);
295
+ const requestActors = createRequestActors(createRequestsFromWorkflowConfig(config, compileSchema));
296
+ return setupAgent({
297
+ schemas,
298
+ actorSources: {
299
+ ...createActorPlaceholdersFromWorkflowConfig(config),
300
+ ...requestActors
301
+ }
302
+ }).createMachine({
303
+ ...config.id !== void 0 ? { id: config.id } : {},
304
+ ...config.description !== void 0 ? { description: config.description } : {},
305
+ ...config.context !== void 0 ? { context: ({ input }) => require_events.validateSchemaSync(schemas.context, evaluateWorkflowConfigValue(config.context, { input })) } : {},
306
+ initial: config.initial,
307
+ states: (() => {
308
+ const rootKeys = new Set(Object.keys(config.states));
309
+ return Object.fromEntries(Object.entries(config.states).map(([key, state]) => [key, lowerWorkflowState(key, state, rootKeys)]));
310
+ })(),
311
+ ...config.meta !== void 0 ? { meta: config.meta } : {}
312
+ });
313
+ }
314
+ //#endregion
315
+ //#region src/setup-agent.ts
316
+ const emptyEventSchema = { "~standard": {
317
+ version: 1,
318
+ vendor: "statelyai-agent",
319
+ validate(value) {
320
+ return value !== null && typeof value === "object" && Object.keys(value).length === 0 ? { value: {} } : { issues: [{ message: "Expected an empty event payload" }] };
321
+ }
322
+ } };
323
+ function normalizeEventSchemas(events) {
324
+ return Object.fromEntries(Object.entries(events).map(([type, schema]) => [type, schema && typeof schema === "object" && "~standard" in schema ? schema : emptyEventSchema]));
325
+ }
326
+ /**
327
+ * Builds a machine's {@link AgentSchemaPack} from a partial schema
328
+ * declaration — only `context` is required; `events`/`input`/`output`/`meta`
329
+ * default to empty/unknown schemas when omitted. Pass the result as
330
+ * `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
331
+ * directly into `setupAgent({ context, events, ... })` — both forms are
332
+ * accepted).
333
+ */
334
+ function createAgentSchemas(schemas) {
335
+ return {
336
+ context: schemas.context,
337
+ events: normalizeEventSchemas(schemas.events ?? {}),
338
+ input: schemas.input,
339
+ output: schemas.output,
340
+ meta: schemas.meta,
341
+ emitted: schemas.emitted
342
+ };
343
+ }
344
+ function mergeContextSchema(base, fields) {
345
+ return { "~standard": {
346
+ version: 1,
347
+ vendor: "statelyai-agent",
348
+ validate(value) {
349
+ const baseResult = base["~standard"].validate(value);
350
+ if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
351
+ if (baseResult.issues) return baseResult;
352
+ const merged = { ...baseResult.value };
353
+ const issues = [];
354
+ for (const [key, fieldSchema] of Object.entries(fields)) {
355
+ const fieldResult = fieldSchema["~standard"].validate(value[key]);
356
+ if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
357
+ if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
358
+ ...issue,
359
+ path: [key, ...issue.path ?? []]
360
+ })));
361
+ else merged[key] = fieldResult.value;
362
+ }
363
+ return issues.length > 0 ? { issues } : { value: merged };
364
+ }
365
+ } };
366
+ }
367
+ function resolveAgentStateSchemas(contextSchema, states) {
368
+ return Object.fromEntries(Object.entries(states).map(([key, state]) => {
369
+ if (!state || typeof state !== "object") return [key, state];
370
+ const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
371
+ if ("context" in state && state.context) return [key, {
372
+ schemas: { context: mergeContextSchema(contextSchema, state.context) },
373
+ ...children ? { states: children } : {}
374
+ }];
375
+ return [key, children ? {
376
+ ...state,
377
+ states: children
378
+ } : state];
379
+ }));
380
+ }
381
+ /**
382
+ * Schema-first `setup(...)` for agent machines — the standard entry point
383
+ * for authoring a machine (the blueprint) that this library then runs (via
384
+ * {@link runAgent} or the step helpers) against host-supplied model/decision
385
+ * executors. Context, events, machine input, machine output, and
386
+ * state/transition meta are all standard schemas — no `{} as Type` casts —
387
+ * and are retained on `result.schemas` for runtime validation. Also
388
+ * registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
389
+ * `agent.decide`/`agent.plan` builtin actors and lowers `requests`/`actorSources` into the
390
+ * machine's actor sources. The result is the xstate `setup(...)` object with
391
+ * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
392
+ * `requests`/`appendMessages` attached. Also has a
393
+ * `setupAgent.fromConfig(...)` namespace member for building a machine from
394
+ * a serializable {@link AgentWorkflowConfig} instead of this TS API.
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * const schemas = createAgentSchemas({
399
+ * context: z.object({ topic: z.string(), joke: z.string().nullable() }),
400
+ * input: z.object({ topic: z.string() }),
401
+ * output: z.object({ joke: z.string() }),
402
+ * });
403
+ *
404
+ * const agent = setupAgent({
405
+ * schemas,
406
+ * actorSources: { tellJoke },
407
+ * });
408
+ *
409
+ * const jokeMachine = agent.createMachine({
410
+ * context: ({ input }) => ({ topic: input.topic, joke: null }),
411
+ * initial: 'telling',
412
+ * states: {
413
+ * telling: {
414
+ * invoke: {
415
+ * id: 'joke',
416
+ * src: 'tellJoke',
417
+ * input: ({ context }) => ({ topic: context.topic }),
418
+ * onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
419
+ * },
420
+ * },
421
+ * done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
422
+ * },
423
+ * });
424
+ * ```
425
+ */
426
+ function setupAgent(config) {
427
+ return createSetupAgent(config);
428
+ }
429
+ function collectFinalStateOutputs(states, outputs = []) {
430
+ for (const state of Object.values(states ?? {})) {
431
+ if (state?.type === "final" && state.output !== void 0) outputs.push(state.output);
432
+ collectFinalStateOutputs(state?.states, outputs);
433
+ }
434
+ return outputs;
435
+ }
436
+ function withRootOutputFromSingleFinal(config) {
437
+ if (!config || typeof config !== "object" || "output" in config || !("states" in config)) return config;
438
+ const outputs = collectFinalStateOutputs(config.states);
439
+ return outputs.length === 1 ? {
440
+ ...config,
441
+ output: outputs[0]
442
+ } : config;
443
+ }
444
+ (function(_setupAgent) {
445
+ function fromConfig(config, options) {
446
+ return setupAgentFromConfig(config, options);
447
+ }
448
+ _setupAgent.fromConfig = fromConfig;
449
+ })(setupAgent || (setupAgent = {}));
450
+ /** Builds one TextLogic actor per `setupAgent({ requests })` entry. @internal */
451
+ function createRequestActors(requests) {
452
+ return Object.fromEntries(Object.entries(requests).map(([key, request]) => {
453
+ return [key, require_events.createTextLogic({
454
+ ...request,
455
+ name: key,
456
+ mode: request.mode ?? "generate"
457
+ })];
458
+ }));
459
+ }
460
+ function normalizeAgentSchemas(config) {
461
+ if ("schemas" in config && config.schemas) return config.schemas;
462
+ const loose = config;
463
+ return createAgentSchemas({
464
+ ...loose,
465
+ context: loose.context
466
+ });
467
+ }
468
+ function normalizeAgentRequestInput(requests) {
469
+ return requests ?? {};
470
+ }
471
+ /**
472
+ * Runtime guard: a key appearing in both `actorSources`/`requests` is almost
473
+ * certainly a mistake (whichever spread applies last would silently win) —
474
+ * fail fast with a clear message rather than let one implementation shadow
475
+ * another.
476
+ */
477
+ function assertNoActorKeyCollisions(actorSources, requests) {
478
+ const seenIn = /* @__PURE__ */ new Map();
479
+ const groups = [["actorSources", actorSources], ["requests", requests]];
480
+ for (const [groupName, group] of groups) for (const key of Object.keys(group ?? {})) {
481
+ const existingGroup = seenIn.get(key);
482
+ if (existingGroup) throw new Error(`setupAgent: key '${key}' is defined in both '${existingGroup}' and '${groupName}'. Each actor source key must be unique across 'actorSources' and 'requests'.`);
483
+ seenIn.set(key, groupName);
484
+ }
485
+ }
486
+ const RESERVED_AGENT_ACTOR_KEYS = [
487
+ ...Object.keys(require_events.builtinTextActors),
488
+ require_events.USER_INPUT_ACTOR,
489
+ require_events.DECIDE_ACTOR,
490
+ require_events.PLAN_ACTOR
491
+ ];
492
+ /**
493
+ * Rejects a user-supplied `actorSources`/`requests` key in the reserved
494
+ * `agent.*` builtin namespace. Without this, the builtins-first spread in
495
+ * {@link createAgentActorSources} lets such a key overwrite the builtin
496
+ * (`agent.decide`, `agent.plan`, …) silently. Deliberate override of a builtin
497
+ * is still possible after the machine is created, via
498
+ * `machine.provide({ actorSources: { 'agent.decide': ... } })`.
499
+ */
500
+ function assertNoReservedAgentKeys(actorSources, requests) {
501
+ const groups = [["actorSources", actorSources], ["requests", requests]];
502
+ for (const [groupName, group] of groups) for (const key of Object.keys(group ?? {})) if (RESERVED_AGENT_ACTOR_KEYS.includes(key)) throw new Error(`setupAgent: '${groupName}' key '${key}' is a reserved builtin agent actor and cannot be redefined here (it would silently clobber the builtin). Reserved keys: ${RESERVED_AGENT_ACTOR_KEYS.join(", ")}. To deliberately override a builtin, do it on the created machine instead: machine.provide({ actorSources: { '${key}': ... } }).`);
503
+ }
504
+ function createAgentActorSources(actorSources, requestActors) {
505
+ assertNoActorKeyCollisions(actorSources, requestActors);
506
+ assertNoReservedAgentKeys(actorSources, requestActors);
507
+ return {
508
+ ...require_events.builtinTextActors,
509
+ [require_events.USER_INPUT_ACTOR]: require_events.userInputActor,
510
+ [require_events.DECIDE_ACTOR]: require_decision.createDecideActor(),
511
+ [require_events.PLAN_ACTOR]: require_decision.createPlanActor(),
512
+ ...actorSources,
513
+ ...requestActors
514
+ };
515
+ }
516
+ function createAgentSetupConfig(schemas, actorSources, config) {
517
+ return {
518
+ schemas: {
519
+ context: schemas.context,
520
+ events: schemas.events,
521
+ input: schemas.input,
522
+ output: schemas.output,
523
+ meta: schemas.meta,
524
+ ...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
525
+ },
526
+ ...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
527
+ actorSources,
528
+ actions: config.actions,
529
+ guards: config.guards,
530
+ delays: config.delays
531
+ };
532
+ }
533
+ function createSetupAgent(config) {
534
+ const schemas = normalizeAgentSchemas(config);
535
+ const requestActors = createRequestActors(normalizeAgentRequestInput(config.requests));
536
+ const actorSources = createAgentActorSources(config.actorSources, requestActors);
537
+ const base = (0, xstate.setup)(createAgentSetupConfig(schemas, actorSources, config));
538
+ const createBaseMachine = base.createMachine.bind(base);
539
+ const models = config.models ?? {};
540
+ const machineOptions = {
541
+ schemas,
542
+ actorSources,
543
+ models
544
+ };
545
+ return Object.assign(base, {
546
+ createMachine(machineConfig) {
547
+ const machine = createBaseMachine(withRootOutputFromSingleFinal(machineConfig));
548
+ require_events.agentExecutionOptions.set(machine, machineOptions);
549
+ if (config.isSuspended) {
550
+ const rootConfig = machine.config;
551
+ if (rootConfig) require_events.machineSuspensionPredicates.set(rootConfig, config.isSuspended);
552
+ }
553
+ return machine;
554
+ },
555
+ schemas,
556
+ models,
557
+ requests: requestActors,
558
+ appendMessages(resolve) {
559
+ return appendMessages(resolve);
560
+ }
561
+ });
562
+ }
563
+ //#endregion
564
+ //#region src/internal/state-request-pass.ts
565
+ async function runTextPhase(stateRequest, baseMessages, deps) {
566
+ const { model, system } = stateRequest;
567
+ const id = stateRequest.id ?? deps.nextRequestId();
568
+ const promptMessage = require_events.userMessage(stateRequest.prompt);
569
+ if (stateRequest.kind === "decision") return {
570
+ stateRequest,
571
+ id,
572
+ output: void 0,
573
+ appended: [promptMessage]
574
+ };
575
+ if (!deps.generateText) throw new Error("runAgent: a getRequests request needs a 'generateText' executor (or use kind: 'decision').");
576
+ const request = {
577
+ model,
578
+ ...system !== void 0 ? { system } : {},
579
+ messages: [...baseMessages, promptMessage],
580
+ tools: {}
581
+ };
582
+ const agentRequest = {
583
+ kind: "text",
584
+ id,
585
+ src: require_events.INTERPRET_SOURCE,
586
+ mode: "generate",
587
+ input: request,
588
+ tools: {},
589
+ events: []
590
+ };
591
+ deps.consumeModelCall();
592
+ deps.onTrace?.({
593
+ type: "request.start",
594
+ request: agentRequest
595
+ });
596
+ let output;
597
+ try {
598
+ const raw = await deps.generateText(request, { signal: deps.signal });
599
+ output = await require_events.normalizeGeneratorResult(raw, id, { request });
600
+ const rawReasoning = raw?.reasoning;
601
+ const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
602
+ deps.onResult?.(agentRequest, {
603
+ output,
604
+ raw
605
+ });
606
+ deps.onTrace?.({
607
+ type: "request.end",
608
+ request: agentRequest,
609
+ output,
610
+ raw,
611
+ ...reasoning !== void 0 ? { reasoning } : {}
612
+ });
613
+ } catch (error) {
614
+ deps.onTrace?.({
615
+ type: "request.error",
616
+ request: agentRequest,
617
+ error
618
+ });
619
+ throw error;
620
+ }
621
+ return {
622
+ stateRequest,
623
+ id,
624
+ output,
625
+ appended: [promptMessage, require_events.assistantMessage(typeof output === "string" ? output : JSON.stringify(output))]
626
+ };
627
+ }
628
+ async function runAdvancePhase(plan, deps) {
629
+ const { stateRequest, id, output } = plan;
630
+ const { model, system } = stateRequest;
631
+ deps.appendToLog(...plan.appended);
632
+ if (stateRequest.kind !== "decision" && stateRequest.onDone !== void 0) {
633
+ const snapshot = deps.getSnapshot();
634
+ const resolved = typeof stateRequest.onDone === "function" ? stateRequest.onDone({
635
+ output,
636
+ snapshot,
637
+ messages: deps.messages
638
+ }) : stateRequest.onDone;
639
+ if (!resolved) return false;
640
+ const acceptedTypes = require_events.getAcceptedEvents(snapshot, { schemas: deps.schemas }).map((descriptor) => descriptor.type);
641
+ 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)"}.`);
642
+ if (!snapshot.can(resolved)) return false;
643
+ deps.send(resolved);
644
+ return true;
645
+ }
646
+ const events = require_events.getAcceptedEvents(deps.getSnapshot(), {
647
+ schemas: deps.schemas,
648
+ ...stateRequest.allowedEvents ? { eventTypes: stateRequest.allowedEvents } : {}
649
+ });
650
+ if (events.length === 0) return false;
651
+ 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.`);
652
+ const chosen = await require_decision.resolveDecision({
653
+ kind: "decision",
654
+ id,
655
+ model,
656
+ ...system !== void 0 ? { system } : {},
657
+ messages: [...deps.messages],
658
+ events,
659
+ attempts: []
660
+ }, deps.decide, {
661
+ signal: deps.signal,
662
+ canTake: (event) => deps.getSnapshot().can(event)
663
+ });
664
+ if (deps.isSettled()) return false;
665
+ deps.appendToLog(require_events.assistantMessage(`[chose: ${chosen.type}]`));
666
+ deps.send(chosen);
667
+ return true;
668
+ }
669
+ /**
670
+ * Executes one getRequests pass: all text calls concurrently against the
671
+ * pass-start log, then per-request advancement sequentially in request
672
+ * order. Returns whether ANY request sent an event — the host settles idle
673
+ * when none did (otherwise an unchanged snapshot would re-produce the same
674
+ * pass forever). Stops early (skipping remaining appends/sends) once
675
+ * {@link StateRequestPassDeps.isSettled} reports the run is over. Throws on
676
+ * executor/`onDone` errors — the host maps them to its error settle.
677
+ */
678
+ async function runStateRequestPass(requests, deps) {
679
+ const baseMessages = [...deps.messages];
680
+ const plans = await Promise.all(requests.map((stateRequest) => runTextPhase(stateRequest, baseMessages, deps)));
681
+ let sentAny = false;
682
+ for (const plan of plans) {
683
+ if (deps.isSettled()) break;
684
+ sentAny = await runAdvancePhase(plan, deps) || sentAny;
685
+ }
686
+ return { sentAny };
687
+ }
688
+ //#endregion
689
+ //#region src/run-agent.ts
690
+ /**
691
+ * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
692
+ * `type` the restored state cannot accept (a type-level check via
693
+ * {@link getAcceptedEvents}). A programmer/integration error, in the same
694
+ * class as runAgent's bind-time throws — it throws rather than settling an
695
+ * `error` result. A type-legal event a guard rejects is NOT this error (the
696
+ * machine simply takes no transition). Opt out with
697
+ * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
698
+ */
699
+ var IllegalResumeEventError = class extends Error {
700
+ eventType;
701
+ acceptedTypes;
702
+ constructor(eventType, acceptedTypes) {
703
+ super(`runAgent: cannot resume with event '${eventType}' — the restored state does not accept it. Accepted event types: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
704
+ this.name = "IllegalResumeEventError";
705
+ this.eventType = eventType;
706
+ this.acceptedTypes = acceptedTypes;
707
+ }
708
+ };
709
+ /**
710
+ * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
711
+ * `agentMeta.version` differs from the current machine's version, under the
712
+ * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
713
+ * structural fingerprint of the machine changed since the snapshot was
714
+ * persisted (a state/transition/invoke was added, removed, or retargeted), so
715
+ * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
716
+ * `to` the current machine's.
717
+ */
718
+ var SnapshotVersionMismatchError = class extends Error {
719
+ from;
720
+ to;
721
+ machineId;
722
+ constructor(from, to, machineId) {
723
+ super(`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.`);
724
+ this.name = "SnapshotVersionMismatchError";
725
+ this.from = from;
726
+ this.to = to;
727
+ this.machineId = machineId;
728
+ }
729
+ };
730
+ /**
731
+ * Thrown by {@link runAgentToCompletion} when the run settles `idle` instead of
732
+ * `done`: the machine paused for external input. Carries the idle `snapshot`
733
+ * and `acceptedTypes` (the event types that could resume it, via
734
+ * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
735
+ * expected outcome you handle.
736
+ */
737
+ var AgentIdleError = class extends Error {
738
+ snapshot;
739
+ acceptedTypes;
740
+ constructor(snapshot, acceptedTypes) {
741
+ super(`runAgentToCompletion: the machine paused (idle) instead of completing. Resume it by calling runAgent with one of these events: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
742
+ this.name = "AgentIdleError";
743
+ this.snapshot = snapshot;
744
+ this.acceptedTypes = acceptedTypes;
745
+ }
746
+ };
747
+ /**
748
+ * The version of the {@link AgentTraceEvent} envelope every trace event carries
749
+ * as `schemaVersion`. Bumped only on a breaking change to the envelope or any
750
+ * payload shape, so a consumer can gate on it. Emitted identically by
751
+ * {@link runAgent}, {@link provideExecutors}' `onTrace`, and
752
+ * {@link traceTransitions}.
753
+ */
754
+ const AGENT_TRACE_SCHEMA_VERSION = 1;
755
+ let nextRunAgentTraceId = 1;
756
+ var MaxModelCallsExceededError = class extends Error {
757
+ constructor() {
758
+ super("runAgent exceeded maxModelCalls.");
759
+ this.name = "MaxModelCallsExceededError";
760
+ }
761
+ };
762
+ function wrapsDecisionExhausted(error) {
763
+ let current = error;
764
+ for (let depth = 0; depth < 10 && current != null; depth++) {
765
+ if (current instanceof require_decision.DecisionExhaustedError) return true;
766
+ current = current.cause;
767
+ }
768
+ return false;
769
+ }
770
+ /**
771
+ * Recursively collects every invoke's `src` from raw machine config (spike
772
+ * S6: `machine.config` preserves authored srcs; the built `machine.root`
773
+ * normalizes object srcs to synthetic string ids and loses the distinction
774
+ * this walk needs). Function-valued `src` resolvers are dynamic and are not
775
+ * statically analyzable, so they are skipped (pass-through, like any other
776
+ * non-agent actor).
777
+ */
778
+ function collectConfiguredInvokeSrcs(stateConfig, stateName, out) {
779
+ if (!stateConfig) return;
780
+ const invokes = stateConfig.invoke === void 0 ? [] : Array.isArray(stateConfig.invoke) ? stateConfig.invoke : [stateConfig.invoke];
781
+ for (const invokeConfig of invokes) {
782
+ const src = invokeConfig?.src;
783
+ if (typeof src === "string" || src && typeof src === "object") out.push({
784
+ stateName,
785
+ src
786
+ });
787
+ }
788
+ for (const [childName, childConfig] of Object.entries(stateConfig.states ?? {})) collectConfiguredInvokeSrcs(childConfig, `${stateName}.${childName}`, out);
789
+ }
790
+ /**
791
+ * Duck-types a state machine actor logic (an invoked child machine) vs. any
792
+ * other actor logic. xstate's `StateMachine` carries `.config`, `.root`, and
793
+ * a `.provide(...)` method plus an `implementations.actorSources` map — this
794
+ * combination is unique to machines and survives the dual-package/version
795
+ * boundary an `instanceof` check would not. Used to descend the bind-time
796
+ * walk into invoked child machines (their internal agent requests are opaque
797
+ * to the parent-level source walk otherwise).
798
+ */
799
+ function isStateMachine(logic) {
800
+ return !!logic && typeof logic === "object" && "config" in logic && "root" in logic && typeof logic.provide === "function" && typeof logic.implementations === "object" && !!logic.implementations?.actorSources;
801
+ }
802
+ /**
803
+ * Fails fast (throws) at bind time — before any actor runs — when the
804
+ * machine invokes an agent actor `runAgent` cannot execute. See §3.2 point 2.
805
+ *
806
+ * Recurses into invoked child state machines (arbitrarily deep). A child
807
+ * machine's agent requests reached through string-keyed invoke srcs DO inherit
808
+ * the parent runAgent's `generateText`/`streamText`/`decide` executors —
809
+ * runAgent rebinds them with the same host-backed wrappers (see
810
+ * {@link rebindChildMachine}) — so the only remaining bind-time errors are: a
811
+ * required executor kind missing entirely (naming the invoke chain and src),
812
+ * and an unbound request reached through a direct-object invoke src that can't
813
+ * be rebound ({@link unrebindableChildRequestError}). A request that carries
814
+ * its own executor (`.withExecutor(...)`, tracked in `executorBoundLogics`)
815
+ * always runs itself; explicit binding shadows inheritance.
816
+ */
817
+ function assertBindable(machine, effectiveSources, options) {
818
+ assertMachineBindable(machine, effectiveSources, options, {
819
+ isChild: false,
820
+ childPath: "",
821
+ rebindable: true,
822
+ visited: new Set([machine])
823
+ });
824
+ }
825
+ function assertMachineBindable(machine, effectiveSources, options, ctx) {
826
+ const invokes = [];
827
+ collectConfiguredInvokeSrcs(machine.config, machine.config.id ?? "(root)", invokes);
828
+ const where = ctx.isChild ? `child machine '${ctx.childPath}' state` : "state";
829
+ for (const { stateName, src } of invokes) {
830
+ if (typeof src !== "string") {
831
+ if (isStateMachine(src)) {
832
+ assertChildMachineBindable(src, src, stateName, options, ctx);
833
+ continue;
834
+ }
835
+ if ((require_events.isTextLogic(src) || require_decision.isDecisionLogic(src) || require_decision.isPlanLogic(src)) && !require_events.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({ actorSources: { name: logic } })) and invoke it by name.`);
836
+ continue;
837
+ }
838
+ const logic = effectiveSources[src];
839
+ if (logic === void 0) throw new Error(`runAgent: ${where} '${stateName}' invokes unregistered actor source '${src}'. Provide it via machine.provide({ actorSources: { '${src}': ... } }) or runAgent(machine, { actorSources: { '${src}': ... } }).`);
840
+ if (isStateMachine(logic)) {
841
+ assertChildMachineBindable(logic, src, stateName, options, ctx);
842
+ continue;
843
+ }
844
+ if (src === "agent.userInput") continue;
845
+ if (require_decision.isDecisionLogic(logic)) {
846
+ if (require_events.executorBoundLogics.has(logic)) continue;
847
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "decision");
848
+ if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes decision source '${src}' but no 'decide' executor was provided to runAgent(...).`);
849
+ continue;
850
+ }
851
+ if (require_decision.isPlanLogic(logic)) {
852
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "plan");
853
+ if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes plan source '${src}' but no 'decide' executor was provided to runAgent(...).`);
854
+ continue;
855
+ }
856
+ if (require_events.isTextLogic(logic)) {
857
+ if (require_events.executorBoundLogics.has(logic)) continue;
858
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, logic.mode === "stream" ? "streaming text" : "text");
859
+ 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(...).`);
860
+ if (logic.mode !== "stream" && !options.hasGenerateText) throw new Error(`runAgent: ${where} '${stateName}' invokes text source '${src}' but no 'generateText' executor was provided to runAgent(...).`);
861
+ continue;
862
+ }
863
+ if (require_events.isUnboundPlaceholder(logic)) throw new Error(`runAgent: ${where} '${stateName}' invokes actor source '${src}', which has no host execution. Provide it via machine.provide({ actorSources: { '${src}': ... } }) or runAgent(machine, { actorSources: { '${src}': ... } }).`);
864
+ }
865
+ }
866
+ /** Descends the bind-time walk into an invoked child state machine, guarding
867
+ * against a machine that (transitively) invokes itself. */
868
+ function assertChildMachineBindable(childMachine, childSrc, stateName, options, ctx) {
869
+ if (ctx.visited.has(childMachine)) return;
870
+ const childName = typeof childSrc === "string" ? childSrc : childMachine.config.id ?? "(child machine)";
871
+ const childPath = ctx.childPath ? `${ctx.childPath} > ${childName}` : childName;
872
+ const childSources = childMachine.implementations.actorSources;
873
+ assertMachineBindable(childMachine, childSources, options, {
874
+ isChild: true,
875
+ childPath,
876
+ rebindable: ctx.rebindable && typeof childSrc === "string",
877
+ visited: new Set([...ctx.visited, childMachine])
878
+ });
879
+ }
880
+ /** The loud bind-time error for an unbound agent request reached under a
881
+ * direct-object invoke src, which runAgent cannot rebind (only string-keyed
882
+ * sources can be swapped via `.provide`). Names the invoke chain AND the
883
+ * request src, and spells out the `.withExecutor`/string-keyed remedy. Note:
884
+ * requests reachable through string-keyed srcs at any depth DO inherit
885
+ * runAgent's executors — this error is only for the unrebindable direct-object
886
+ * case. */
887
+ function unrebindableChildRequestError(childPath, stateName, requestSrc, kind) {
888
+ 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({ actorSources: { <child>: childMachine } })) and invoke it by name.`);
889
+ }
890
+ /** Reads the durable invoke id/src off the async actor's own ref (`self`). */
891
+ function selfIdAndSrc(self) {
892
+ const ref = self;
893
+ return {
894
+ id: typeof ref?.id === "string" ? ref.id : "",
895
+ src: typeof ref?.src === "string" ? ref.src : ""
896
+ };
897
+ }
898
+ /**
899
+ * The machine actor that INVOKED a decision/plan request — the actor whose
900
+ * live snapshot supplies the candidate events and drives `canTake`/`send`.
901
+ * For a top-level request this is the root actor (identity-equal to
902
+ * `runCtx.actorHolder.actorRef`); for a request inside an invoked child
903
+ * machine it is that child's actor, so a child decision/plan reads and drives
904
+ * the CHILD's snapshot — not the root's. Read off `self._parent`, with the
905
+ * root actor as a fallback.
906
+ */
907
+ function invokingActorOf(self, runCtx) {
908
+ return self?._parent ?? runCtx.actorHolder.actorRef;
909
+ }
910
+ /**
911
+ * The shared text/stream emission helper: binds a {@link TextLogic} to
912
+ * `runCtx`'s executor and constructs the `request.start` / `stream.chunk` /
913
+ * `request.end` (incl. the lifted `reasoning`) / `request.error` trace payloads.
914
+ * Used by both `runAgent` and `provideExecutors` so the two paths produce
915
+ * identical event shapes by construction. @internal
916
+ */
917
+ function wrapTextLogicForRunAgent(logic, runCtx) {
918
+ return logic.withExecutor(async ({ request, self, signal }) => {
919
+ const { id, src } = selfIdAndSrc(self);
920
+ const executor = logic.mode === "stream" ? runCtx.streamText : runCtx.generateText;
921
+ if (!executor) throw new Error(`runAgent: no '${logic.mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
922
+ const requestWithTools = {
923
+ ...request,
924
+ tools: request.tools ?? {}
925
+ };
926
+ const agentRequest = {
927
+ kind: "text",
928
+ id,
929
+ src,
930
+ mode: logic.mode,
931
+ input: request,
932
+ tools: requestWithTools.tools,
933
+ events: []
934
+ };
935
+ runCtx.consumeModelCall();
936
+ runCtx.onTrace?.({
937
+ type: "request.start",
938
+ request: agentRequest
939
+ }, self);
940
+ try {
941
+ const raw = await executor(requestWithTools, {
942
+ onChunk: (chunk) => {
943
+ runCtx.onTrace?.({
944
+ type: "stream.chunk",
945
+ request: agentRequest,
946
+ chunk
947
+ }, self);
948
+ runCtx.onChunk?.(chunk, { request: agentRequest });
949
+ },
950
+ signal
951
+ });
952
+ const output = await require_events.normalizeGeneratorResult(raw, id, {
953
+ request,
954
+ onChunk: (chunk) => {
955
+ runCtx.onTrace?.({
956
+ type: "stream.chunk",
957
+ request: agentRequest,
958
+ chunk
959
+ }, self);
960
+ runCtx.onChunk?.(chunk, { request: agentRequest });
961
+ }
962
+ });
963
+ const rawReasoning = raw?.reasoning;
964
+ const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
965
+ runCtx.onResult?.(agentRequest, {
966
+ output,
967
+ raw
968
+ });
969
+ runCtx.onTrace?.({
970
+ type: "request.end",
971
+ request: agentRequest,
972
+ output,
973
+ raw,
974
+ ...reasoning !== void 0 ? { reasoning } : {}
975
+ }, self);
976
+ return { output };
977
+ } catch (error) {
978
+ runCtx.onTrace?.({
979
+ type: "request.error",
980
+ request: agentRequest,
981
+ error
982
+ }, self);
983
+ throw error;
984
+ }
985
+ });
986
+ }
987
+ function createCountingDecide(runCtx, self) {
988
+ return async (attemptRequest) => {
989
+ runCtx.consumeModelCall();
990
+ runCtx.onTrace?.({
991
+ type: "request.start",
992
+ request: attemptRequest
993
+ }, self);
994
+ try {
995
+ const result = await runCtx.decide(attemptRequest);
996
+ runCtx.onResult?.(attemptRequest, {
997
+ output: result.event,
998
+ raw: result
999
+ });
1000
+ runCtx.onTrace?.({
1001
+ type: "request.end",
1002
+ request: attemptRequest,
1003
+ output: result.event,
1004
+ raw: result
1005
+ }, self);
1006
+ return result;
1007
+ } catch (error) {
1008
+ runCtx.onTrace?.({
1009
+ type: "request.error",
1010
+ request: attemptRequest,
1011
+ error
1012
+ }, self);
1013
+ throw error;
1014
+ }
1015
+ };
1016
+ }
1017
+ /**
1018
+ * Builds the decision actor logic runAgent installs in place of a
1019
+ * `DecisionLogic`/`agent.decide` source. `DecisionLogic.withExecutor(...)`
1020
+ * can only swap the innermost per-attempt executor — the `resolveDecision(...)`
1021
+ * call (and its `canTake`) is hardwired inside the original logic's `run`.
1022
+ * To supply `canTake` (mode-3, §2.6), runAgent instead builds a fresh async
1023
+ * logic here that calls `resolveDecision` itself, reusing `logic.request(...)`
1024
+ * to build the request the same way the original logic would have.
1025
+ *
1026
+ * On success it SENDS the chosen event to the invoking actor (auto-delivery,
1027
+ * mirroring {@link createRunAgentPlanLogic}) and then completes with that event
1028
+ * as its output — so callers never wire an `onDone` to deliver it. See the
1029
+ * send-then-complete note inside `run` for how exit-cancels-invoke interacts
1030
+ * with `onDone`.
1031
+ */
1032
+ function createRunAgentDecisionLogic(logic, runCtx) {
1033
+ const decisionLogic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal, self }) => {
1034
+ if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
1035
+ const { id } = selfIdAndSrc(self);
1036
+ const declaredEventTypes = logic.allowedEventTypes?.(input);
1037
+ await Promise.resolve();
1038
+ const actorRef = invokingActorOf(self, runCtx);
1039
+ const events = actorRef ? require_events.getAcceptedEvents(actorRef.getSnapshot(), {
1040
+ schemas: runCtx.schemas,
1041
+ eventTypes: declaredEventTypes
1042
+ }) : [];
1043
+ const chosen = await require_decision.resolveDecision({
1044
+ ...logic.request(input),
1045
+ id,
1046
+ events
1047
+ }, createCountingDecide(runCtx, self), {
1048
+ maxRetries: logic.maxRetries,
1049
+ signal,
1050
+ canTake: (event) => actorRef ? actorRef.getSnapshot().can(event) : true
1051
+ });
1052
+ actorRef?.send(chosen);
1053
+ await Promise.resolve();
1054
+ return chosen;
1055
+ } });
1056
+ return Object.assign(decisionLogic, {
1057
+ kind: "statelyai.decisionLogic",
1058
+ maxRetries: logic.maxRetries,
1059
+ request: logic.request,
1060
+ withExecutor: (nextExecute) => createRunAgentDecisionLogic(logic.withExecutor(nextExecute), runCtx)
1061
+ });
1062
+ }
1063
+ /**
1064
+ * Builds the plan actor logic runAgent installs in place of the `agent.plan`
1065
+ * builtin: iterated {@link resolveDecision}. Each step re-reads the live
1066
+ * snapshot (so the candidate set reflects everything applied so far), asks
1067
+ * the `decide` executor for one legal event with the same validation/retry
1068
+ * loop a decision gets, and sends it to the machine. The loop ends on a
1069
+ * `stopOn` event, at `maxSteps`, when no legal candidate remains, or when an
1070
+ * applied event exits the invoking state (xstate cancels this invoke — the
1071
+ * machine simply moves on and the pending output is discarded).
1072
+ *
1073
+ * The invoke's `input` is resolved once, so the prompt cannot re-render
1074
+ * context between steps; instead the applied trail is appended to the prompt
1075
+ * each step so the model can see plan progress.
1076
+ */
1077
+ function createRunAgentPlanLogic(logic, runCtx) {
1078
+ const planLogic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal, self }) => {
1079
+ if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
1080
+ const { id } = selfIdAndSrc(self);
1081
+ const stopOn = new Set(input.stopOn ?? []);
1082
+ const countingDecide = createCountingDecide(runCtx, self);
1083
+ const base = logic.request(input);
1084
+ let ledger = require_decision.initialPlanLedger(logic, input);
1085
+ const end = (stopped) => {
1086
+ ledger = require_decision.advancePlanLedger(logic, ledger, {
1087
+ type: "plan.ended",
1088
+ stopped
1089
+ });
1090
+ return ledger.output;
1091
+ };
1092
+ await Promise.resolve();
1093
+ const invokingActor = invokingActorOf(self, runCtx);
1094
+ while (ledger.context.stepsRemaining > 0) {
1095
+ const actorRef = invokingActor;
1096
+ if (!actorRef || signal.aborted) break;
1097
+ const machineEvents = require_events.getAcceptedEvents(actorRef.getSnapshot(), {
1098
+ schemas: runCtx.schemas,
1099
+ eventTypes: logic.allowedEventTypes(input)
1100
+ });
1101
+ if (machineEvents.length === 0) return end("no-legal-events");
1102
+ const doneDescriptor = {
1103
+ type: require_decision.PLAN_DONE_EVENT_TYPE,
1104
+ toolName: require_events.sanitizeEventToolName(require_decision.PLAN_DONE_EVENT_TYPE)
1105
+ };
1106
+ const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, doneDescriptor];
1107
+ const applied = ledger.context.applied;
1108
+ 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.`;
1109
+ const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${require_decision.PLAN_DONE_EVENT_TYPE}'.`;
1110
+ const chosen = await require_decision.resolveDecision({
1111
+ ...base,
1112
+ id: `${id}[${applied.length}]`,
1113
+ events,
1114
+ prompt: `${base.prompt ?? ""}${trail}${doneHint}`,
1115
+ attempts: []
1116
+ }, countingDecide, {
1117
+ maxRetries: input.maxRetries ?? logic.maxRetries,
1118
+ signal,
1119
+ canTake: (event) => {
1120
+ if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
1121
+ return invokingActor ? invokingActor.getSnapshot().can(event) : true;
1122
+ }
1123
+ });
1124
+ if (chosen.type === "agent.plan.done") return end("done");
1125
+ actorRef.send(chosen);
1126
+ ledger = require_decision.advancePlanLedger(logic, ledger, {
1127
+ type: "plan.applied",
1128
+ event: chosen
1129
+ });
1130
+ await Promise.resolve();
1131
+ if (stopOn.has(chosen.type)) return end("stop-event");
1132
+ }
1133
+ return end("max-steps");
1134
+ } });
1135
+ return Object.assign(planLogic, {
1136
+ kind: "statelyai.planLogic",
1137
+ maxRetries: logic.maxRetries,
1138
+ request: logic.request,
1139
+ allowedEventTypes: logic.allowedEventTypes
1140
+ });
1141
+ }
1142
+ /**
1143
+ * The set of string-keyed actor `src`s the machine's own config invokes
1144
+ * (top-level, recursing into child STATES but not into invoked child
1145
+ * machines). {@link provideExecutors} uses it to require an executor only for a
1146
+ * source the machine actually invokes — the always-registered `agent.*`
1147
+ * builtins that go unused must not force their executors to be supplied.
1148
+ * @internal
1149
+ */
1150
+ function getConfiguredInvokeSrcs(machine) {
1151
+ const invokes = [];
1152
+ collectConfiguredInvokeSrcs(machine.config, machine.config.id ?? "(root)", invokes);
1153
+ const srcs = /* @__PURE__ */ new Set();
1154
+ for (const { src } of invokes) if (typeof src === "string") srcs.add(src);
1155
+ return srcs;
1156
+ }
1157
+ const rootTraceRegistry = /* @__PURE__ */ new WeakMap();
1158
+ let nextProvideRunId = 1;
1159
+ /** Walks `self._parent` from an invoked async leaf actor up to its root actor. */
1160
+ function rootActorOf(self) {
1161
+ let ref = self;
1162
+ if (!ref) return;
1163
+ while (ref._parent) ref = ref._parent;
1164
+ return ref;
1165
+ }
1166
+ /** The per-root envelope state, minted on first use (runId `run_<n>`, matching runAgent). */
1167
+ function rootTraceState(root) {
1168
+ let state = rootTraceRegistry.get(root);
1169
+ if (!state) {
1170
+ const logic = root.logic;
1171
+ const machineId = (logic?.config)?.id ?? logic?.id ?? "(machine)";
1172
+ const machineVersion = logic ? require_events.getMachineStructuralHash(logic) : "";
1173
+ state = {
1174
+ runId: `run_${nextProvideRunId++}`,
1175
+ seq: 0,
1176
+ machineId,
1177
+ machineVersion
1178
+ };
1179
+ rootTraceRegistry.set(root, state);
1180
+ }
1181
+ return state;
1182
+ }
1183
+ /** Stamps a per-root-actor envelope onto a bare trace payload. */
1184
+ function stampRootTrace(root, payload) {
1185
+ const state = rootTraceState(root);
1186
+ return {
1187
+ schemaVersion: 1,
1188
+ runId: state.runId,
1189
+ seq: ++state.seq,
1190
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1191
+ machineId: state.machineId,
1192
+ machineVersion: state.machineVersion,
1193
+ ...payload
1194
+ };
1195
+ }
1196
+ /** Adapts a public `onTrace` into the payload-level {@link RunAgentBindContext.onTrace} sink used by the shared emission helpers. */
1197
+ function provideTraceSink(onTrace) {
1198
+ if (!onTrace) return;
1199
+ return (payload, self) => {
1200
+ const root = rootActorOf(self);
1201
+ if (root) onTrace(stampRootTrace(root, payload));
1202
+ };
1203
+ }
1204
+ /**
1205
+ * A minimal {@link RunAgentBindContext} for `provideExecutors` (uncontrolled
1206
+ * `createActor`): the same wrappers runAgent installs, MINUS the run-scoped
1207
+ * model-call counter. `consumeModelCall` is a no-op (no budget), and
1208
+ * `actorHolder.actorRef` is left undefined — the wrappers read the invoking
1209
+ * actor off `self._parent`, always present under a live `createActor` tree.
1210
+ * `onTrace` (when given) mints a per-root-actor envelope. `schemas` come from
1211
+ * the machine's registered `setupAgent` execution options.
1212
+ */
1213
+ function provideBindContext(machine, executors, options) {
1214
+ return {
1215
+ generateText: executors.generateText,
1216
+ streamText: executors.streamText,
1217
+ decide: executors.decide,
1218
+ onChunk: options.onChunk ? (chunk) => options.onChunk(chunk) : void 0,
1219
+ onTrace: provideTraceSink(options.onTrace),
1220
+ consumeModelCall: () => {},
1221
+ actorHolder: { actorRef: void 0 },
1222
+ schemas: require_events.getRegisteredAgentExecutionOptions(machine).schemas
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Host-binds one text/stream source for {@link provideExecutors} using the SAME
1227
+ * emission helper as `runAgent` ({@link wrapTextLogicForRunAgent}), so a bound
1228
+ * text request emits request.start/stream.chunk/request.end/request.error with
1229
+ * identical shapes. @internal
1230
+ */
1231
+ function bindTextForProvide(machine, logic, executors, options) {
1232
+ return wrapTextLogicForRunAgent(logic, provideBindContext(machine, executors, options));
1233
+ }
1234
+ /**
1235
+ * Host-binds one `DecisionLogic`/`agent.decide` source for
1236
+ * {@link provideExecutors}: runAgent's decision wrapper (snapshot-driven
1237
+ * candidate events, `canTake`, auto-delivery of the chosen event) with the same
1238
+ * request-level tracing runAgent emits, minus run-scoped counting. @internal
1239
+ */
1240
+ function bindDecisionForProvide(machine, logic, executors, options) {
1241
+ return createRunAgentDecisionLogic(logic, provideBindContext(machine, executors, options));
1242
+ }
1243
+ /**
1244
+ * Host-binds one `agent.plan` source for {@link provideExecutors}: runAgent's
1245
+ * plan wrapper (iterated snapshot-driven decisions, auto-delivery) with the same
1246
+ * request-level tracing runAgent emits, minus run-scoped counting. @internal
1247
+ */
1248
+ function bindPlanForProvide(machine, logic, executors, options) {
1249
+ return createRunAgentPlanLogic(logic, provideBindContext(machine, executors, options));
1250
+ }
1251
+ /**
1252
+ * Recursively rebinds an invoked child machine's own agent sources with the
1253
+ * SAME host-backed wrappers runAgent applies to the top-level machine, so a
1254
+ * child's text/stream/decision/plan requests inherit runAgent's executors and
1255
+ * participate in maxModelCalls counting, onTrace/onChunk/onResult exactly like
1256
+ * parent requests. Returns the child machine to invoke: a `.provide`-rebound
1257
+ * copy when any inner source needed wrapping, else the original untouched.
1258
+ *
1259
+ * Only string-keyed sources are visited — a direct-object invoke src cannot be
1260
+ * swapped via `.provide` (assertBindable already rejected an unbound request
1261
+ * under one). A source that already carries its own executor
1262
+ * (`executorBoundLogics`) is left as-is: explicit binding shadows inheritance.
1263
+ * Cycle-safe via `visited` (a machine that invokes itself is returned as-is).
1264
+ */
1265
+ function rebindChildMachine(childMachine, runCtx, visited) {
1266
+ if (visited.has(childMachine)) return childMachine;
1267
+ const childVisited = new Set([...visited, childMachine]);
1268
+ const sources = childMachine.implementations.actorSources;
1269
+ const wrapped = {};
1270
+ for (const [key, logic] of Object.entries(sources)) {
1271
+ if (require_decision.isDecisionLogic(logic)) {
1272
+ if (!require_events.executorBoundLogics.has(logic)) wrapped[key] = createRunAgentDecisionLogic(logic, runCtx);
1273
+ continue;
1274
+ }
1275
+ if (require_decision.isPlanLogic(logic)) {
1276
+ wrapped[key] = createRunAgentPlanLogic(logic, runCtx);
1277
+ continue;
1278
+ }
1279
+ if (require_events.isTextLogic(logic)) {
1280
+ if (!require_events.executorBoundLogics.has(logic)) wrapped[key] = wrapTextLogicForRunAgent(logic, runCtx);
1281
+ continue;
1282
+ }
1283
+ if (isStateMachine(logic)) {
1284
+ const rebound = rebindChildMachine(logic, runCtx, childVisited);
1285
+ if (rebound !== logic) wrapped[key] = rebound;
1286
+ continue;
1287
+ }
1288
+ }
1289
+ return Object.keys(wrapped).length > 0 ? childMachine.provide({ actorSources: wrapped }) : childMachine;
1290
+ }
1291
+ /**
1292
+ * Runs an agent machine to completion or idle: a `createActor` host that
1293
+ * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
1294
+ * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
1295
+ * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
1296
+ * the step helpers ({@link initialAgentStep} etc — a pure
1297
+ * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
1298
+ * internally; there is no continuation callback, so **idle always settles**
1299
+ * and the caller resumes explicitly by passing the settled `{ snapshot,
1300
+ * event }` back in. The actor is stopped on every settle path (`done`,
1301
+ * `idle`, and `error` alike) — resume is always by snapshot, never by
1302
+ * holding a reference to a live actor.
1303
+ *
1304
+ * Binding happens **before** the actor starts: every invoke the machine
1305
+ * could reach is walked and checked against the effective actor sources
1306
+ * (`options.actorSources` merged onto the machine), so a missing
1307
+ * `streamText`/`decide` executor or any other unbound actor source throws
1308
+ * immediately — a bind-time error, not a mid-run failure. The one exception
1309
+ * is `agent.userInput`: unhandled, it binds as a pending placeholder that
1310
+ * settles the run idle (with `pendingUserInputs`) instead of erroring.
1311
+ *
1312
+ * @example
1313
+ * ```ts
1314
+ * const executors = createAiSdkExecutors({ models });
1315
+ * let r = await runAgent(machine, { input, executors });
1316
+ * while (r.status === 'idle') {
1317
+ * const event = await promptUser(getAcceptedEvents(r.snapshot));
1318
+ * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
1319
+ * }
1320
+ * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
1321
+ * console.log(r.output);
1322
+ * ```
1323
+ *
1324
+ * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
1325
+ * functions directly (`executors: { generateText, streamText }` with them
1326
+ * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
1327
+ * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
1328
+ * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
1329
+ */
1330
+ async function runAgent(machine, options) {
1331
+ const maxModelCalls = options.maxModelCalls ?? 100;
1332
+ let modelCallCount = 0;
1333
+ let budgetExceeded = false;
1334
+ let warnedNonSerializable = false;
1335
+ const runId = `run_${nextRunAgentTraceId++}`;
1336
+ let traceSeq = 0;
1337
+ const machineId = machine.config.id ?? machine.id ?? "(machine)";
1338
+ const machineVersion = options.machineVersion ?? require_events.getMachineStructuralHash(machine);
1339
+ const agentMeta = {
1340
+ machineId,
1341
+ version: machineVersion
1342
+ };
1343
+ const stampAgentMeta = (snapshot) => {
1344
+ if (snapshot && typeof snapshot === "object") snapshot.agentMeta = agentMeta;
1345
+ };
1346
+ const onTrace = (event) => {
1347
+ options.onTrace?.({
1348
+ schemaVersion: 1,
1349
+ runId,
1350
+ seq: ++traceSeq,
1351
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1352
+ machineId,
1353
+ machineVersion,
1354
+ ...event
1355
+ });
1356
+ };
1357
+ const consumeModelCall = () => {
1358
+ if (budgetExceeded) throw new MaxModelCallsExceededError();
1359
+ modelCallCount += 1;
1360
+ if (modelCallCount > maxModelCalls) {
1361
+ budgetExceeded = true;
1362
+ throw new MaxModelCallsExceededError();
1363
+ }
1364
+ };
1365
+ const warnNonSerializableContext = (snapshot) => {
1366
+ if (warnedNonSerializable || process.env.NODE_ENV === "production") return;
1367
+ let offending = [];
1368
+ try {
1369
+ offending = require_events.findNonSerializableContextPaths(snapshot.context);
1370
+ } catch {
1371
+ return;
1372
+ }
1373
+ if (offending.length === 0) return;
1374
+ warnedNonSerializable = true;
1375
+ 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.`);
1376
+ };
1377
+ const provided = machine.provide({ actorSources: options.actorSources });
1378
+ const effectiveSources = provided.implementations.actorSources;
1379
+ assertBindable(provided, effectiveSources, {
1380
+ hasGenerateText: !!options.executors?.generateText,
1381
+ hasDecide: !!options.executors?.decide,
1382
+ hasStreamText: !!options.executors?.streamText
1383
+ });
1384
+ 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.");
1385
+ const actorHolder = { actorRef: void 0 };
1386
+ const runCtx = {
1387
+ generateText: options.executors?.generateText,
1388
+ streamText: options.executors?.streamText,
1389
+ decide: options.executors?.decide,
1390
+ onChunk: options.onChunk,
1391
+ onResult: options.onResult,
1392
+ onTrace,
1393
+ consumeModelCall,
1394
+ actorHolder,
1395
+ schemas: require_events.getRegisteredAgentExecutionOptions(machine).schemas
1396
+ };
1397
+ let userInputIsPlaceholder = false;
1398
+ const wrappedSources = {};
1399
+ for (const [key, logic] of Object.entries(effectiveSources)) {
1400
+ if (key === "agent.userInput") {
1401
+ if (options.userInput) {
1402
+ const userInput = options.userInput;
1403
+ wrappedSources[key] = (0, xstate.createAsyncLogic)({ run: async ({ input }) => await userInput(input) });
1404
+ } else if (require_events.isUnboundPlaceholder(logic)) {
1405
+ userInputIsPlaceholder = true;
1406
+ wrappedSources[key] = (0, xstate.createAsyncLogic)({ run: () => new Promise(() => {}) });
1407
+ }
1408
+ continue;
1409
+ }
1410
+ if (require_decision.isDecisionLogic(logic)) {
1411
+ wrappedSources[key] = createRunAgentDecisionLogic(logic, runCtx);
1412
+ continue;
1413
+ }
1414
+ if (require_decision.isPlanLogic(logic)) {
1415
+ wrappedSources[key] = createRunAgentPlanLogic(logic, runCtx);
1416
+ continue;
1417
+ }
1418
+ if (require_events.isTextLogic(logic)) {
1419
+ if (!require_events.executorBoundLogics.has(logic)) wrappedSources[key] = wrapTextLogicForRunAgent(logic, runCtx);
1420
+ continue;
1421
+ }
1422
+ if (isStateMachine(logic)) {
1423
+ const rebound = rebindChildMachine(logic, runCtx, new Set([machine]));
1424
+ if (rebound !== logic) wrappedSources[key] = rebound;
1425
+ continue;
1426
+ }
1427
+ }
1428
+ const boundMachine = provided.provide({ actorSources: wrappedSources });
1429
+ const isSuspended = options.isSuspended ?? require_events.getMachineSuspensionPredicate(machine) ?? (() => false);
1430
+ let effectiveSnapshot = options.snapshot;
1431
+ if (effectiveSnapshot !== void 0) {
1432
+ const from = effectiveSnapshot.agentMeta?.version;
1433
+ if (from !== void 0 && from !== machineVersion) {
1434
+ const info = {
1435
+ from,
1436
+ to: machineVersion
1437
+ };
1438
+ if (options.migrateSnapshot) effectiveSnapshot = options.migrateSnapshot(effectiveSnapshot, info);
1439
+ else {
1440
+ const mode = options.onVersionMismatch ?? "throw";
1441
+ if (mode === "throw") throw new SnapshotVersionMismatchError(from, machineVersion, machineId);
1442
+ 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.`);
1443
+ }
1444
+ }
1445
+ }
1446
+ const priorMessages = require_events.getAgentMessages(effectiveSnapshot);
1447
+ const messages = typeof options.messages === "function" ? [...options.messages([...priorMessages])] : [...priorMessages, ...options.messages ?? []];
1448
+ const stampMessages = (snapshot) => {
1449
+ if (!options.getRequests && !options.messages && messages.length === 0) return;
1450
+ if (snapshot && typeof snapshot === "object") snapshot.messages = [...messages];
1451
+ };
1452
+ if (effectiveSnapshot !== void 0 && options.event !== void 0 && (options.onIllegalResumeEvent ?? "throw") === "throw") {
1453
+ const acceptedTypes = require_events.getAcceptedEvents((0, xstate.createActor)(boundMachine, { snapshot: effectiveSnapshot }).getSnapshot(), { schemas: runCtx.schemas }).map((descriptor) => descriptor.type);
1454
+ const eventType = options.event.type;
1455
+ if (!acceptedTypes.includes(eventType)) throw new IllegalResumeEventError(eventType, acceptedTypes);
1456
+ }
1457
+ return new Promise((resolvePromise) => {
1458
+ let settled = false;
1459
+ let idleTimer;
1460
+ let actor;
1461
+ let deliveringResumeEvent = options.event !== void 0;
1462
+ const settle = (result) => {
1463
+ if (settled) return;
1464
+ settled = true;
1465
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
1466
+ if (options.signal) options.signal.removeEventListener("abort", onAbort);
1467
+ stampAgentMeta(result.snapshot);
1468
+ stampMessages(result.snapshot);
1469
+ if ("persistedSnapshot" in result) {
1470
+ stampAgentMeta(result.persistedSnapshot);
1471
+ stampMessages(result.persistedSnapshot);
1472
+ }
1473
+ onTrace({
1474
+ type: "run.end",
1475
+ ...result
1476
+ });
1477
+ actor.stop();
1478
+ resolvePromise(result);
1479
+ };
1480
+ const onAbort = () => {
1481
+ settle({
1482
+ status: "error",
1483
+ cause: "aborted",
1484
+ error: options.signal?.reason ?? /* @__PURE__ */ new Error("Aborted"),
1485
+ snapshot: actor.getSnapshot()
1486
+ });
1487
+ };
1488
+ const settleIdle = (current) => {
1489
+ warnNonSerializableContext(current);
1490
+ const pendingUserInputs = userInputIsPlaceholder ? collectPendingUserInputs(current) : [];
1491
+ settle({
1492
+ status: "idle",
1493
+ snapshot: current,
1494
+ ...pendingUserInputs.length > 0 ? {
1495
+ pendingUserInputs,
1496
+ persistedSnapshot: actor.getPersistedSnapshot()
1497
+ } : {}
1498
+ });
1499
+ };
1500
+ let interpreting = false;
1501
+ let interpretSeq = 0;
1502
+ const appendToLog = (...items) => {
1503
+ messages.push(...items);
1504
+ if (options.onMessage) {
1505
+ const info = {
1506
+ runId,
1507
+ machineId,
1508
+ machineVersion
1509
+ };
1510
+ for (const item of items) options.onMessage(item, info);
1511
+ }
1512
+ };
1513
+ const runErrorCause = (error) => budgetExceeded ? "max-model-calls" : wrapsDecisionExhausted(error) ? "decision-exhausted" : "machine";
1514
+ const settleInterpretError = (error) => {
1515
+ settle({
1516
+ status: "error",
1517
+ cause: runErrorCause(error),
1518
+ error,
1519
+ snapshot: actor.getSnapshot()
1520
+ });
1521
+ };
1522
+ const passDeps = {
1523
+ getSnapshot: () => actor.getSnapshot(),
1524
+ send: (event) => actor.send(event),
1525
+ isSettled: () => settled,
1526
+ messages,
1527
+ appendToLog,
1528
+ generateText: runCtx.generateText,
1529
+ decide: runCtx.decide ? createCountingDecide(runCtx, void 0) : void 0,
1530
+ consumeModelCall,
1531
+ nextRequestId: () => `interpret_${++interpretSeq}`,
1532
+ onTrace,
1533
+ onResult: runCtx.onResult,
1534
+ schemas: runCtx.schemas,
1535
+ signal: options.signal
1536
+ };
1537
+ const maybeInterpret = (snapshot) => {
1538
+ if (!options.getRequests || settled) return false;
1539
+ if (interpreting) return true;
1540
+ let requested;
1541
+ try {
1542
+ requested = options.getRequests(snapshot, { messages });
1543
+ } catch (error) {
1544
+ settleInterpretError(error);
1545
+ return true;
1546
+ }
1547
+ const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter((stateRequest) => Boolean(stateRequest));
1548
+ if (requests.length === 0) return false;
1549
+ interpreting = true;
1550
+ runStateRequestPass(requests, passDeps).then(({ sentAny }) => {
1551
+ if (settled || sentAny) return;
1552
+ const current = actor.getSnapshot();
1553
+ if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) settleIdle(current);
1554
+ }).catch((error) => settleInterpretError(error)).finally(() => {
1555
+ interpreting = false;
1556
+ if (!settled) scheduleIdleCheck();
1557
+ });
1558
+ return true;
1559
+ };
1560
+ const scheduleIdleCheck = () => {
1561
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
1562
+ idleTimer = setTimeout(() => {
1563
+ idleTimer = void 0;
1564
+ if (settled) return;
1565
+ const current = actor.getSnapshot();
1566
+ if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) {
1567
+ if (!maybeInterpret(current)) settleIdle(current);
1568
+ }
1569
+ }, 0);
1570
+ };
1571
+ actor = (0, xstate.createActor)(boundMachine, {
1572
+ input: options.input,
1573
+ snapshot: effectiveSnapshot,
1574
+ inspect: (event) => {
1575
+ if (typeof options.inspect === "function") options.inspect(event);
1576
+ else options.inspect?.next?.(event);
1577
+ if (settled || event.type !== "@xstate.transition" || event.actorRef !== actor.ref) return;
1578
+ const snapshot = event.snapshot;
1579
+ onTrace({
1580
+ type: "machine.transition",
1581
+ snapshot,
1582
+ event: event.event
1583
+ });
1584
+ options.onTransition?.(snapshot, event.event);
1585
+ if (snapshot.status === "done") {
1586
+ settle({
1587
+ status: "done",
1588
+ output: snapshot.output,
1589
+ snapshot
1590
+ });
1591
+ return;
1592
+ }
1593
+ if (snapshot.status === "error") {
1594
+ settle({
1595
+ status: "error",
1596
+ cause: runErrorCause(snapshot.error),
1597
+ error: snapshot.error,
1598
+ snapshot
1599
+ });
1600
+ return;
1601
+ }
1602
+ if (snapshot.status === "stopped") {
1603
+ settle({
1604
+ status: "error",
1605
+ cause: "stopped",
1606
+ error: /* @__PURE__ */ new Error("Actor stopped externally."),
1607
+ snapshot
1608
+ });
1609
+ return;
1610
+ }
1611
+ if (!deliveringResumeEvent && isSuspended(snapshot) && isIdleSnapshot(snapshot, { ignoreUserInputChildren: userInputIsPlaceholder })) {
1612
+ if (!maybeInterpret(snapshot)) settleIdle(snapshot);
1613
+ return;
1614
+ }
1615
+ scheduleIdleCheck();
1616
+ }
1617
+ });
1618
+ actorHolder.actorRef = actor;
1619
+ actor.subscribe({ error: () => {} });
1620
+ actor.on("*", (event) => {
1621
+ onTrace({
1622
+ type: "emit",
1623
+ event
1624
+ });
1625
+ });
1626
+ for (const [type, handler] of Object.entries(options.on ?? {})) if (typeof handler === "function") actor.on(type, handler);
1627
+ if (options.signal) {
1628
+ if (options.signal.aborted) {
1629
+ settle({
1630
+ status: "error",
1631
+ cause: "aborted",
1632
+ error: options.signal.reason ?? /* @__PURE__ */ new Error("Aborted"),
1633
+ snapshot: actor.getSnapshot()
1634
+ });
1635
+ return;
1636
+ }
1637
+ options.signal.addEventListener("abort", onAbort);
1638
+ }
1639
+ onTrace({
1640
+ type: "run.start",
1641
+ ...options.input !== void 0 ? { input: options.input } : {},
1642
+ ...effectiveSnapshot !== void 0 ? { snapshot: effectiveSnapshot } : {},
1643
+ ...options.event !== void 0 ? { event: options.event } : {}
1644
+ });
1645
+ actor.start();
1646
+ if (options.event) {
1647
+ deliveringResumeEvent = false;
1648
+ actor.send(options.event);
1649
+ }
1650
+ });
1651
+ }
1652
+ /**
1653
+ * Runs an agent machine to a **final state** and returns its output, for
1654
+ * run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
1655
+ *
1656
+ * - `done` → resolves with `result.output` (the machine's `OutputFrom`).
1657
+ * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1658
+ * event types that could resume it.
1659
+ * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1660
+ * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1661
+ * `.error` is the raw thrown value.
1662
+ *
1663
+ * Use {@link runAgent} directly when idle is an expected outcome you handle
1664
+ * (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
1665
+ * machine is meant to run straight through to a final state.
1666
+ */
1667
+ async function runAgentToCompletion(machine, options) {
1668
+ const result = await runAgent(machine, options);
1669
+ if (result.status === "done") return result.output;
1670
+ if (result.status === "idle") {
1671
+ const acceptedTypes = require_events.getAcceptedEvents(result.snapshot, { schemas: require_events.getRegisteredAgentExecutionOptions(machine).schemas }).map((descriptor) => descriptor.type);
1672
+ throw new AgentIdleError(result.snapshot, acceptedTypes);
1673
+ }
1674
+ if (result.error instanceof Error) throw result.error;
1675
+ const wrapped = /* @__PURE__ */ new Error(`runAgentToCompletion: run failed with cause '${result.cause}'.`);
1676
+ wrapped.cause = result.cause;
1677
+ wrapped.error = result.error;
1678
+ throw wrapped;
1679
+ }
1680
+ /**
1681
+ * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1682
+ * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1683
+ * `@xstate.transition` events and hands the handler the typed
1684
+ * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1685
+ * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1686
+ * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1687
+ * actorRef casts.
1688
+ */
1689
+ function inspectTransitions(handler) {
1690
+ return (inspectionEvent) => {
1691
+ if (inspectionEvent.type !== "@xstate.transition") return;
1692
+ handler(inspectionEvent.snapshot, inspectionEvent.actorRef);
1693
+ };
1694
+ }
1695
+ /**
1696
+ * An xstate `inspect` handler that emits `machine.transition` trace events onto
1697
+ * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
1698
+ * registry as {@link provideExecutors}' `onTrace`. Pair the two on one actor to
1699
+ * get a single ordered trace stream (request + transition events) for the
1700
+ * uncontrolled path:
1701
+ *
1702
+ * ```ts
1703
+ * const bound = provideExecutors(machine, executors, { onTrace });
1704
+ * const actor = createActor(bound, { inspect: traceTransitions(onTrace) });
1705
+ * ```
1706
+ *
1707
+ * Only ROOT-actor transitions are traced (matching `runAgent`'s
1708
+ * `machine.transition`); child-actor transitions are ignored. Attribute the
1709
+ * event via its envelope `runId`.
1710
+ *
1711
+ * By design this path has NO `run.start`/`run.end` events: `createActor` has no
1712
+ * run boundary the way `runAgent` does, so the stream starts at the actor's
1713
+ * first transition. It also does NOT emit `emit` trace events: in this xstate
1714
+ * build emitted events are delivered through `actor.on(...)`, not the inspection
1715
+ * protocol, so they are not observable from an `inspect` handler — subscribe
1716
+ * with `actor.on('*', ...)` if you need them.
1717
+ */
1718
+ function traceTransitions(onTrace) {
1719
+ return (inspectionEvent) => {
1720
+ if (inspectionEvent.type !== "@xstate.transition") return;
1721
+ const actorRef = inspectionEvent.actorRef;
1722
+ if (actorRef?._parent) return;
1723
+ onTrace(stampRootTrace(actorRef, {
1724
+ type: "machine.transition",
1725
+ snapshot: inspectionEvent.snapshot,
1726
+ event: inspectionEvent.event
1727
+ }));
1728
+ };
1729
+ }
1730
+ function isIdleSnapshot(snapshot, { ignoreUserInputChildren }) {
1731
+ if (snapshot.status !== "active") return false;
1732
+ if (Object.values(snapshot.children ?? {}).some((child) => {
1733
+ const ref = child;
1734
+ if (ignoreUserInputChildren && ref?.src === "agent.userInput") return false;
1735
+ return ref?.getSnapshot?.()?.status === "active";
1736
+ })) return false;
1737
+ return !(0, xstate.getNextTransitions)(snapshot).some((transitionDef) => transitionDef.eventType === "" || transitionDef.eventType.startsWith("xstate.after"));
1738
+ }
1739
+ function collectPendingUserInputs(snapshot) {
1740
+ const pending = [];
1741
+ for (const [id, child] of Object.entries(snapshot.children ?? {})) {
1742
+ const ref = child;
1743
+ if (ref?.src !== "agent.userInput") continue;
1744
+ const childSnapshot = ref.getSnapshot?.();
1745
+ if (childSnapshot?.status !== "active") continue;
1746
+ pending.push({
1747
+ id,
1748
+ input: childSnapshot.input
1749
+ });
1750
+ }
1751
+ return pending;
1752
+ }
1753
+ //#endregion
1754
+ //#region src/provide-executors.ts
1755
+ /**
1756
+ * Binds a machine's agent actor sources to a set of host `executors` in one
1757
+ * call, returning a `machine.provide(...)`-ed copy ready for a plain
1758
+ * `createActor(...)` — the uncontrolled-mode counterpart to {@link runAgent}.
1759
+ * No run loop, no idle settling: the returned machine drives itself, so
1760
+ *
1761
+ * ```ts
1762
+ * const actor = createActor(provideExecutors(machine, { generateText, decide }), { input });
1763
+ * actor.start();
1764
+ * ```
1765
+ *
1766
+ * behaves like a normal XState actor whose agent invokes now reach real models.
1767
+ *
1768
+ * Binding pass over `machine.implementations.actorSources` (after merging
1769
+ * `options.actorSources`):
1770
+ * - `mode: 'generate'` text source → `executors.generateText`
1771
+ * - `mode: 'stream'` text source → `executors.streamText`
1772
+ * - decision / `agent.decide` source → `executors.decide` (snapshot-driven
1773
+ * candidate events, guard `canTake`, and auto-delivery of the chosen event,
1774
+ * mirroring `runAgent` but without its model-call counting)
1775
+ * - `agent.plan` source → `executors.decide` (iterated, same semantics)
1776
+ *
1777
+ * Pass `options.onTrace` to observe request-level trace events (identical in
1778
+ * shape to `runAgent`'s); pair it with {@link traceTransitions} on the actor's
1779
+ * `inspect` to also capture `machine.transition` events in the same stream.
1780
+ *
1781
+ * A source that already carries its own executor (`.withExecutor(...)`) is left
1782
+ * as-is. `agent.userInput` is left UNBOUND — an uncontrolled host handles idle
1783
+ * itself, so supply a handler via `options.actorSources` if the machine uses it.
1784
+ * Non-agent actors are untouched.
1785
+ *
1786
+ * Throws at bind time if a source needs an executor kind that `executors` does
1787
+ * not provide.
1788
+ *
1789
+ * v1 does NOT descend into invoked child state machines: a string-keyed child
1790
+ * machine source is left untouched, so a child with its own agent invokes needs
1791
+ * its own `provideExecutors(...)` (or `runAgent`, which does rebind children).
1792
+ */
1793
+ function provideExecutors(machine, executors, options = {}) {
1794
+ const bindOptions = {
1795
+ onChunk: options.onChunk,
1796
+ onTrace: options.onTrace
1797
+ };
1798
+ const provided = options.actorSources ? machine.provide({ actorSources: options.actorSources }) : machine;
1799
+ const effectiveSources = provided.implementations.actorSources;
1800
+ const wrappedSources = {};
1801
+ const invokedSrcs = getConfiguredInvokeSrcs(provided);
1802
+ for (const [key, logic] of Object.entries(effectiveSources)) {
1803
+ if (key === "agent.userInput") continue;
1804
+ if (require_decision.isDecisionLogic(logic)) {
1805
+ if (require_events.executorBoundLogics.has(logic)) continue;
1806
+ if (!executors.decide) {
1807
+ if (invokedSrcs.has(key)) throw missingExecutorError(key, "decision", "decide");
1808
+ continue;
1809
+ }
1810
+ wrappedSources[key] = bindDecisionForProvide(provided, logic, executors, bindOptions);
1811
+ continue;
1812
+ }
1813
+ if (require_decision.isPlanLogic(logic)) {
1814
+ if (!executors.decide) {
1815
+ if (invokedSrcs.has(key)) throw missingExecutorError(key, "plan", "decide");
1816
+ continue;
1817
+ }
1818
+ wrappedSources[key] = bindPlanForProvide(provided, logic, executors, bindOptions);
1819
+ continue;
1820
+ }
1821
+ if (require_events.isTextLogic(logic)) {
1822
+ if (require_events.executorBoundLogics.has(logic)) continue;
1823
+ if (!(logic.mode === "stream" ? executors.streamText : executors.generateText)) {
1824
+ if (invokedSrcs.has(key)) throw logic.mode === "stream" ? missingExecutorError(key, "streaming text", "streamText") : missingExecutorError(key, "text", "generateText");
1825
+ continue;
1826
+ }
1827
+ wrappedSources[key] = bindTextForProvide(provided, logic, executors, bindOptions);
1828
+ continue;
1829
+ }
1830
+ }
1831
+ return provided.provide({ actorSources: wrappedSources });
1832
+ }
1833
+ function missingExecutorError(src, kind, executor) {
1834
+ 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.`);
1835
+ }
1836
+ //#endregion
1837
+ //#region src/verify.ts
1838
+ const DECIDE_SRC = "agent.decide";
1839
+ const PLAN_SRC = "agent.plan";
1840
+ function normalizeInvokes(invoke) {
1841
+ if (invoke === void 0 || invoke === null) return [];
1842
+ return Array.isArray(invoke) ? invoke : [invoke];
1843
+ }
1844
+ function buildStateIndex(rootConfig) {
1845
+ const index = /* @__PURE__ */ new Map();
1846
+ const walk = (states, parentPath) => {
1847
+ for (const [name, config] of Object.entries(states ?? {})) {
1848
+ const path = parentPath ? `${parentPath}.${name}` : name;
1849
+ const hasChildren = !!config.states && Object.keys(config.states).length > 0;
1850
+ index.set(path, {
1851
+ path,
1852
+ name,
1853
+ config,
1854
+ parentPath,
1855
+ type: config.type,
1856
+ isFinal: config.type === "final",
1857
+ isParallel: config.type === "parallel",
1858
+ isCompound: hasChildren && config.type !== "parallel",
1859
+ invokes: normalizeInvokes(config.invoke)
1860
+ });
1861
+ if (hasChildren) walk(config.states, path);
1862
+ }
1863
+ };
1864
+ walk(rootConfig.states, "");
1865
+ return index;
1866
+ }
1867
+ function childrenOf(index, parentPath) {
1868
+ const out = [];
1869
+ for (const node of index.values()) if (node.parentPath === parentPath) out.push(node);
1870
+ return out;
1871
+ }
1872
+ function collectTransitionTargets(value, fromNode, index, out) {
1873
+ if (value === void 0 || value === null) return;
1874
+ if (Array.isArray(value)) {
1875
+ for (const item of value) collectTransitionTargets(item, fromNode, index, out);
1876
+ return;
1877
+ }
1878
+ if (typeof value === "function") {
1879
+ out.opaque = true;
1880
+ return;
1881
+ }
1882
+ if (typeof value === "string") {
1883
+ resolveTargetString(value, fromNode, index, out);
1884
+ return;
1885
+ }
1886
+ if (typeof value === "object") {
1887
+ const target = value.target;
1888
+ if (target !== void 0) collectTransitionTargets(target, fromNode, index, out);
1889
+ }
1890
+ }
1891
+ function resolveTargetString(target, fromNode, index, out) {
1892
+ if (target.startsWith("#")) {
1893
+ out.opaque = true;
1894
+ return;
1895
+ }
1896
+ const resolved = target.startsWith(".") ? `${fromNode.path}.${target.slice(1)}` : fromNode.parentPath ? `${fromNode.parentPath}.${target}` : target;
1897
+ if (index.has(resolved)) out.targets.push(resolved);
1898
+ else out.opaque = true;
1899
+ }
1900
+ function outgoingTargets(node, index) {
1901
+ const out = {
1902
+ targets: [],
1903
+ opaque: false
1904
+ };
1905
+ const { config } = node;
1906
+ for (const value of Object.values(config.on ?? {})) collectTransitionTargets(value, node, index, out);
1907
+ collectTransitionTargets(config.always, node, index, out);
1908
+ collectTransitionTargets(config.choice, node, index, out);
1909
+ for (const value of Object.values(config.after ?? {})) collectTransitionTargets(value, node, index, out);
1910
+ collectTransitionTargets(config.onDone, node, index, out);
1911
+ for (const invoke of node.invokes) {
1912
+ collectTransitionTargets(invoke.onDone, node, index, out);
1913
+ collectTransitionTargets(invoke.onError, node, index, out);
1914
+ }
1915
+ return out;
1916
+ }
1917
+ function computeReachable(rootConfig, index) {
1918
+ const reachable = /* @__PURE__ */ new Set();
1919
+ const queue = [];
1920
+ const markAncestors = (path) => {
1921
+ let parent = index.get(path)?.parentPath ?? "";
1922
+ while (parent) {
1923
+ reachable.add(parent);
1924
+ parent = index.get(parent)?.parentPath ?? "";
1925
+ }
1926
+ };
1927
+ const enter = (path) => {
1928
+ if (reachable.has(path)) return;
1929
+ const node = index.get(path);
1930
+ if (!node) return;
1931
+ reachable.add(path);
1932
+ queue.push(path);
1933
+ markAncestors(path);
1934
+ if (node.isParallel) for (const child of childrenOf(index, path)) enter(child.path);
1935
+ else if (node.isCompound && node.config.initial) enter(`${path}.${node.config.initial}`);
1936
+ };
1937
+ if (rootConfig.type === "parallel") for (const child of childrenOf(index, "")) enter(child.path);
1938
+ else if (rootConfig.initial) enter(rootConfig.initial);
1939
+ while (queue.length > 0) {
1940
+ const node = index.get(queue.shift());
1941
+ if (!node) continue;
1942
+ const { targets, opaque } = outgoingTargets(node, index);
1943
+ for (const target of targets) enter(target);
1944
+ if (opaque) for (const sibling of childrenOf(index, node.parentPath)) enter(sibling.path);
1945
+ }
1946
+ return reachable;
1947
+ }
1948
+ function ancestorChain(node, index) {
1949
+ const chain = [];
1950
+ let parent = node.parentPath;
1951
+ while (parent) {
1952
+ const parentNode = index.get(parent);
1953
+ if (!parentNode) break;
1954
+ chain.push(parentNode);
1955
+ parent = parentNode.parentPath;
1956
+ }
1957
+ return chain;
1958
+ }
1959
+ function hasNonEmptyOn(config) {
1960
+ return !!config.on && Object.keys(config.on).length > 0;
1961
+ }
1962
+ function decisionKindOf(src, actorSources) {
1963
+ if (typeof src === "string") {
1964
+ if (src === DECIDE_SRC) return "decision";
1965
+ if (src === PLAN_SRC) return "plan";
1966
+ const logic = actorSources[src];
1967
+ if (require_decision.isDecisionLogic(logic)) return "decision";
1968
+ if (require_decision.isPlanLogic(logic)) return "plan";
1969
+ return;
1970
+ }
1971
+ if (require_decision.isDecisionLogic(src)) return "decision";
1972
+ if (require_decision.isPlanLogic(src)) return "plan";
1973
+ }
1974
+ function isAgentLogicNeedingBinding(src) {
1975
+ return (require_events.isTextLogic(src) || require_decision.isDecisionLogic(src) || require_decision.isPlanLogic(src)) && !require_events.executorBoundLogics.has(src);
1976
+ }
1977
+ function schemaExposesJson(schema) {
1978
+ if (!schema) return false;
1979
+ try {
1980
+ return require_events.getJsonSchemaSync(schema) !== void 0;
1981
+ } catch {
1982
+ return false;
1983
+ }
1984
+ }
1985
+ function isDeclaredOutputSchema(schema) {
1986
+ if (!schema) return false;
1987
+ let json;
1988
+ try {
1989
+ json = require_events.getJsonSchemaSync(schema);
1990
+ } catch {
1991
+ return false;
1992
+ }
1993
+ if (!json) return false;
1994
+ const properties = json.properties;
1995
+ const required = json.required;
1996
+ return json.type === "object" && !!properties && Object.keys(properties).length > 0 || Array.isArray(required) && required.length > 0;
1997
+ }
1998
+ function checkUnreachableStates(ctx) {
1999
+ const out = [];
2000
+ for (const node of ctx.index.values()) if (!ctx.reachable.has(node.path)) out.push({
2001
+ code: "unreachable-state",
2002
+ severity: "error",
2003
+ path: node.path,
2004
+ 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.`
2005
+ });
2006
+ return out;
2007
+ }
2008
+ function checkDecideWithoutEvents(ctx) {
2009
+ const out = [];
2010
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
2011
+ const kind = decisionKindOf(invoke.src, ctx.actorSources);
2012
+ if (!kind) continue;
2013
+ const selfHandles = hasNonEmptyOn(node.config);
2014
+ const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
2015
+ const invokeObserves = invoke.onDone !== void 0;
2016
+ if (selfHandles || ancestorHandles || invokeObserves) continue;
2017
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
2018
+ out.push({
2019
+ code: "decide-without-events",
2020
+ severity: "error",
2021
+ path: node.path,
2022
+ 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.`
2023
+ });
2024
+ }
2025
+ return out;
2026
+ }
2027
+ function checkUnserializableContext(ctx) {
2028
+ const contextSchema = ctx.schemas?.context;
2029
+ if (!contextSchema) return [];
2030
+ if (schemaExposesJson(contextSchema)) return [];
2031
+ return [{
2032
+ code: "unserializable-context",
2033
+ severity: "warning",
2034
+ path: "context",
2035
+ 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."
2036
+ }];
2037
+ }
2038
+ function checkDirectObjectSrc(ctx) {
2039
+ const out = [];
2040
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
2041
+ const src = invoke.src;
2042
+ if (typeof src === "string" || !src || typeof src !== "object") continue;
2043
+ if (!isAgentLogicNeedingBinding(src)) continue;
2044
+ out.push({
2045
+ code: "direct-object-src",
2046
+ severity: "warning",
2047
+ path: node.path,
2048
+ 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({ actorSources: { name: logic } })) and invoke it by name.`
2049
+ });
2050
+ }
2051
+ return out;
2052
+ }
2053
+ function checkFinalWithoutOutput(ctx) {
2054
+ if (!isDeclaredOutputSchema(ctx.schemas?.output)) return [];
2055
+ if (ctx.config.output !== void 0) return [];
2056
+ const out = [];
2057
+ for (const node of ctx.index.values()) {
2058
+ if (node.parentPath !== "" || !node.isFinal) continue;
2059
+ if (node.config.output === void 0) out.push({
2060
+ code: "final-without-output",
2061
+ severity: "error",
2062
+ path: node.path,
2063
+ 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').`
2064
+ });
2065
+ }
2066
+ return out;
2067
+ }
2068
+ function outputFnReadsEvent(fn) {
2069
+ return /\bevent\s*(?:\.|\?\.|\[)/.test(fn.toString());
2070
+ }
2071
+ function checkFinalOutputReadsEvent(ctx) {
2072
+ const out = [];
2073
+ for (const node of ctx.index.values()) {
2074
+ if (node.parentPath !== "" || !node.isFinal) continue;
2075
+ const output = node.config.output;
2076
+ if (typeof output !== "function") continue;
2077
+ if (!outputFnReadsEvent(output)) continue;
2078
+ out.push({
2079
+ code: "final-output-reads-event",
2080
+ severity: "warning",
2081
+ path: node.path,
2082
+ 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.)`
2083
+ });
2084
+ }
2085
+ return out;
2086
+ }
2087
+ function isBuiltinOrWildcardEvent(eventType) {
2088
+ return eventType === "*" || eventType.includes("*") || eventType.startsWith("xstate.") || eventType.startsWith("done.") || eventType.startsWith("error.");
2089
+ }
2090
+ function checkUndeclaredEvents(ctx) {
2091
+ const declared = ctx.schemas?.events;
2092
+ if (!declared || Object.keys(declared).length === 0) return [];
2093
+ const declaredTypes = new Set(Object.keys(declared));
2094
+ const out = [];
2095
+ for (const node of ctx.index.values()) for (const eventType of Object.keys(node.config.on ?? {})) {
2096
+ if (declaredTypes.has(eventType) || isBuiltinOrWildcardEvent(eventType)) continue;
2097
+ out.push({
2098
+ code: "undeclared-event",
2099
+ severity: "warning",
2100
+ path: node.path,
2101
+ 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.`
2102
+ });
2103
+ }
2104
+ return out;
2105
+ }
2106
+ function checkMissingFinal(ctx) {
2107
+ for (const node of ctx.index.values()) if (node.isFinal && ctx.reachable.has(node.path)) return [];
2108
+ return [{
2109
+ code: "missing-final",
2110
+ severity: "warning",
2111
+ path: "(root)",
2112
+ 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."
2113
+ }];
2114
+ }
2115
+ const LINT_CHECKS = [
2116
+ checkUnreachableStates,
2117
+ checkDecideWithoutEvents,
2118
+ checkUnserializableContext,
2119
+ checkDirectObjectSrc,
2120
+ checkFinalWithoutOutput,
2121
+ checkFinalOutputReadsEvent,
2122
+ checkUndeclaredEvents,
2123
+ checkMissingFinal
2124
+ ];
2125
+ /**
2126
+ * Runs static structural checks over a built agent machine and returns the
2127
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
2128
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
2129
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
2130
+ * plus the schemas/actor sources the library already retains per machine.
2131
+ *
2132
+ * No model calls, no API keys — a coding agent that emits an agent machine can
2133
+ * call this to catch dead states, undeliverable decisions, un-rebindable
2134
+ * invoke srcs, and output-contract gaps before ever running it.
2135
+ *
2136
+ * @example
2137
+ * ```ts
2138
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
2139
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
2140
+ * ```
2141
+ */
2142
+ function lintAgentMachine(machine, options = {}) {
2143
+ const config = machine.config ?? {};
2144
+ const index = buildStateIndex(config);
2145
+ const reachable = computeReachable(config, index);
2146
+ const registered = require_events.getRegisteredAgentExecutionOptions(machine);
2147
+ const ctx = {
2148
+ machine,
2149
+ config,
2150
+ index,
2151
+ reachable,
2152
+ schemas: registered.schemas,
2153
+ actorSources: registered.actorSources ?? machine.implementations?.actorSources ?? {}
2154
+ };
2155
+ const disabled = new Set(options.disable ?? []);
2156
+ return LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
2157
+ }
2158
+ /**
2159
+ * Thrown by {@link assertAgentMachine} when lint finds failing diagnostics.
2160
+ * `diagnostics` holds the findings; the message lists them one per finding,
2161
+ * so a test runner's failure output reads like the CLI's lint report.
2162
+ */
2163
+ var AgentLintError = class extends Error {
2164
+ diagnostics;
2165
+ constructor(machineId, diagnostics) {
2166
+ const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
2167
+ super(`Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
2168
+ this.name = "AgentLintError";
2169
+ this.diagnostics = diagnostics;
2170
+ }
2171
+ };
2172
+ /**
2173
+ * Asserts a machine passes {@link lintAgentMachine}: returns silently when
2174
+ * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
2175
+ * otherwise. Fails on error-severity findings; set `warnings: true` to fail on
2176
+ * warnings too. The one-liner for tests and generation loops:
2177
+ *
2178
+ * @example
2179
+ * ```ts
2180
+ * test('agent machine is structurally sound', () => {
2181
+ * assertAgentMachine(machine);
2182
+ * });
2183
+ * ```
2184
+ */
2185
+ function assertAgentMachine(machine, options = {}) {
2186
+ const diagnostics = lintAgentMachine(machine, options);
2187
+ const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
2188
+ if (failing.length > 0) throw new AgentLintError(machine.id ?? "(machine)", failing);
2189
+ }
2190
+ function pendingInvokes(step) {
2191
+ const out = [];
2192
+ for (const action of step.actions) {
2193
+ const metadata = require_steps.getInvokeEffectMetadata(action);
2194
+ if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
2195
+ id: metadata.id,
2196
+ src: metadata.src
2197
+ });
2198
+ }
2199
+ return out;
2200
+ }
2201
+ function takeFromQueue(channel, src) {
2202
+ const queue = channel?.[src];
2203
+ if (queue && queue.length > 0) return {
2204
+ found: true,
2205
+ value: queue.shift()
2206
+ };
2207
+ return { found: false };
2208
+ }
2209
+ /**
2210
+ * Deterministically plays a machine through, resolving each request from a
2211
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
2212
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
2213
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
2214
+ * and a `trail` of every step taken.
2215
+ *
2216
+ * Throws a descriptive error when the script runs dry mid-request, naming the
2217
+ * pending request's kind, src, and id so the missing scripted response is
2218
+ * obvious.
2219
+ *
2220
+ * @example
2221
+ * ```ts
2222
+ * const { status, snapshot } = simulateAgent(machine, {
2223
+ * input: { topic: 'state machines' },
2224
+ * script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
2225
+ * });
2226
+ * ```
2227
+ */
2228
+ async function simulateAgent(machine, options) {
2229
+ const maxSteps = options.maxSteps ?? 100;
2230
+ const script = {
2231
+ text: { ...options.script.text },
2232
+ decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
2233
+ invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr])
2234
+ };
2235
+ let step = require_steps.initialAgentStep(machine, options.input);
2236
+ const trail = [];
2237
+ for (let i = 0; i < maxSteps; i++) {
2238
+ if (step.done) return {
2239
+ status: "done",
2240
+ snapshot: step.snapshot,
2241
+ trail
2242
+ };
2243
+ const request = step.requests[0];
2244
+ if (request) {
2245
+ if (request.kind === "decision") {
2246
+ const decisionSrc = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src])).get(request.id) ?? request.id;
2247
+ const taken = takeFromQueue(script.decisions, decisionSrc);
2248
+ if (!taken.found) throw scriptDryError("decision", decisionSrc, request.id, request);
2249
+ step = require_steps.transitionAgentStep(machine, step, taken.value);
2250
+ trail.push({
2251
+ state: step.snapshot.value,
2252
+ appliedEvent: taken.value
2253
+ });
2254
+ continue;
2255
+ }
2256
+ if (request.kind === "plan") {
2257
+ const taken = takeFromQueue(script.decisions, request.src);
2258
+ if (!taken.found) throw scriptDryError("decision", request.src, request.id, request);
2259
+ const event = taken.value;
2260
+ step = await require_steps.resolveAgentRequests(machine, step, { decide: async () => ({ event }) });
2261
+ trail.push({
2262
+ state: step.snapshot.value,
2263
+ appliedEvent: taken.value
2264
+ });
2265
+ continue;
2266
+ }
2267
+ const taken = takeFromQueue(script.text, request.src);
2268
+ if (!taken.found) throw scriptDryError("text", request.src, request.id);
2269
+ step = require_steps.resolveAgentStep(machine, step, request, taken.value);
2270
+ trail.push({
2271
+ state: step.snapshot.value,
2272
+ resolvedRequest: {
2273
+ kind: "text",
2274
+ src: request.src,
2275
+ id: request.id
2276
+ }
2277
+ });
2278
+ continue;
2279
+ }
2280
+ const [invoke] = pendingInvokes(step);
2281
+ if (invoke) {
2282
+ const taken = takeFromQueue(script.invokes, invoke.src);
2283
+ if (!taken.found) throw scriptDryError("userInput", invoke.src, invoke.id);
2284
+ step = require_steps.resolveAgentStep(machine, step, invoke.id, taken.value);
2285
+ trail.push({
2286
+ state: step.snapshot.value,
2287
+ resolvedRequest: {
2288
+ kind: "userInput",
2289
+ src: invoke.src,
2290
+ id: invoke.id
2291
+ }
2292
+ });
2293
+ continue;
2294
+ }
2295
+ return {
2296
+ status: "idle",
2297
+ snapshot: step.snapshot,
2298
+ trail
2299
+ };
2300
+ }
2301
+ return {
2302
+ status: "exhausted",
2303
+ snapshot: step.snapshot,
2304
+ trail
2305
+ };
2306
+ }
2307
+ function mapValues(obj, fn) {
2308
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
2309
+ }
2310
+ function scriptDryError(kind, src, id, request) {
2311
+ const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
2312
+ 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}`);
2313
+ }
2314
+ async function explore(machine, options, stopWhen) {
2315
+ const maxDepth = options.maxDepth ?? 8;
2316
+ const maxPaths = options.maxPaths ?? 200;
2317
+ const textOutputs = options.textOutputs ?? {};
2318
+ const reachedStates = /* @__PURE__ */ new Set();
2319
+ const reachedValues = [];
2320
+ const terminals = [];
2321
+ const unexplored = [];
2322
+ let prunedByGuard = 0;
2323
+ let pathsExplored = 0;
2324
+ let hitPathCap = false;
2325
+ let witness;
2326
+ const recordState = (snapshot) => {
2327
+ const key = JSON.stringify(snapshot.value);
2328
+ if (!reachedStates.has(key)) {
2329
+ reachedStates.add(key);
2330
+ reachedValues.push(snapshot.value);
2331
+ }
2332
+ };
2333
+ const initial = require_steps.initialAgentStep(machine, options.input);
2334
+ recordState(initial.snapshot);
2335
+ if (stopWhen?.(initial.snapshot)) witness = [];
2336
+ const advance = (step) => {
2337
+ let current = step;
2338
+ for (let i = 0; i < 1e3; i++) {
2339
+ if (current.done) return { step: current };
2340
+ const request = current.requests[0];
2341
+ if (request && request.kind === "text") {
2342
+ if (!(request.src in textOutputs)) return {
2343
+ step: current,
2344
+ blockedSrc: request.src
2345
+ };
2346
+ current = require_steps.resolveAgentStep(machine, current, request, textOutputs[request.src]);
2347
+ recordState(current.snapshot);
2348
+ continue;
2349
+ }
2350
+ if (request && (request.kind === "decision" || request.kind === "plan")) return { step: current };
2351
+ const [invoke] = pendingInvokes(current);
2352
+ if (invoke) {
2353
+ if (!(invoke.src in textOutputs)) return {
2354
+ step: current,
2355
+ blockedSrc: invoke.src
2356
+ };
2357
+ current = require_steps.resolveAgentStep(machine, current, invoke.id, textOutputs[invoke.src]);
2358
+ recordState(current.snapshot);
2359
+ continue;
2360
+ }
2361
+ return { step: current };
2362
+ }
2363
+ return { step: current };
2364
+ };
2365
+ const visit = async (step, path, depth) => {
2366
+ if (witness !== void 0) return;
2367
+ if (pathsExplored >= maxPaths) {
2368
+ hitPathCap = true;
2369
+ return;
2370
+ }
2371
+ const { step: settled, blockedSrc } = advance(step);
2372
+ if (stopWhen?.(settled.snapshot)) {
2373
+ witness = path;
2374
+ return;
2375
+ }
2376
+ if (blockedSrc) {
2377
+ pathsExplored++;
2378
+ terminals.push({
2379
+ status: "needs-output",
2380
+ path,
2381
+ state: settled.snapshot.value,
2382
+ missingSrc: blockedSrc
2383
+ });
2384
+ unexplored.push(`needs-output: no canned output for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
2385
+ return;
2386
+ }
2387
+ if (settled.done) {
2388
+ pathsExplored++;
2389
+ terminals.push({
2390
+ status: "done",
2391
+ path,
2392
+ state: settled.snapshot.value
2393
+ });
2394
+ return;
2395
+ }
2396
+ const request = settled.requests[0];
2397
+ const isPlan = request?.kind === "plan";
2398
+ const branchEvents = request?.kind === "decision" || request?.kind === "plan" ? request.events.map((descriptor) => ({ type: descriptor.type })) : require_events.getAcceptedEvents(settled.snapshot).map((descriptor) => ({ type: descriptor.type }));
2399
+ if (branchEvents.length === 0) {
2400
+ pathsExplored++;
2401
+ terminals.push({
2402
+ status: "idle",
2403
+ path,
2404
+ state: settled.snapshot.value
2405
+ });
2406
+ return;
2407
+ }
2408
+ if (depth >= maxDepth) {
2409
+ pathsExplored++;
2410
+ terminals.push({
2411
+ status: "max-depth",
2412
+ path,
2413
+ state: settled.snapshot.value
2414
+ });
2415
+ unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
2416
+ return;
2417
+ }
2418
+ for (const event of branchEvents) {
2419
+ if (witness !== void 0 || pathsExplored >= maxPaths) {
2420
+ if (pathsExplored >= maxPaths) hitPathCap = true;
2421
+ return;
2422
+ }
2423
+ if (!(isPlan && event.type === "agent.plan.done") && !settled.snapshot.can(event)) {
2424
+ prunedByGuard++;
2425
+ continue;
2426
+ }
2427
+ const next = isPlan ? await require_steps.resolveAgentRequests(machine, settled, { decide: async () => ({ event }) }) : require_steps.transitionAgentStep(machine, settled, event);
2428
+ recordState(next.snapshot);
2429
+ await visit(next, [...path, event], depth + 1);
2430
+ }
2431
+ };
2432
+ if (witness === void 0) await visit(initial, [], 0);
2433
+ return {
2434
+ report: {
2435
+ reachedStates: reachedValues,
2436
+ terminals,
2437
+ prunedByGuard,
2438
+ unexplored,
2439
+ pathsExplored,
2440
+ hitPathCap
2441
+ },
2442
+ witness
2443
+ };
2444
+ }
2445
+ /**
2446
+ * Enumerates a machine's decision and external-event branches to a bounded
2447
+ * depth, model-free, and reports which states are reached and how each path
2448
+ * terminates. At each decision request it forks one branch per candidate event
2449
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
2450
+ * an idle wait it forks per externally-accepted event. A `agent.plan` request
2451
+ * forks the same way — one branch per candidate, including the reserved
2452
+ * `agent.plan.done` move — advancing each branch through the real plan protocol
2453
+ * (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
2454
+ * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
2455
+ * halts that branch with a `needs-output` terminal rather than throwing.
2456
+ *
2457
+ * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
2458
+ * 200, reported via `hitPathCap`).
2459
+ *
2460
+ * @example
2461
+ * ```ts
2462
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
2463
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
2464
+ * ```
2465
+ */
2466
+ async function explorePaths(machine, options = {}) {
2467
+ return (await explore(machine, options)).report;
2468
+ }
2469
+ /**
2470
+ * Answers "can the machine reach `statePath`?" by exploring its branches (a
2471
+ * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
2472
+ * with the event sequence that reaches it, or `{ canReach: false }`.
2473
+ *
2474
+ * @example
2475
+ * ```ts
2476
+ * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
2477
+ * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
2478
+ * ```
2479
+ */
2480
+ async function canReach(machine, statePath, options = {}) {
2481
+ const { witness } = await explore(machine, options, (snapshot) => {
2482
+ try {
2483
+ return snapshot.matches(statePath);
2484
+ } catch {
2485
+ return false;
2486
+ }
2487
+ });
2488
+ return witness !== void 0 ? {
2489
+ canReach: true,
2490
+ witness
2491
+ } : { canReach: false };
2492
+ }
2493
+ //#endregion
2494
+ exports.AGENT_TRACE_SCHEMA_VERSION = AGENT_TRACE_SCHEMA_VERSION;
2495
+ exports.AgentIdleError = AgentIdleError;
2496
+ exports.AgentLintError = AgentLintError;
2497
+ exports.DecisionExhaustedError = require_decision.DecisionExhaustedError;
2498
+ exports.IllegalResumeEventError = IllegalResumeEventError;
2499
+ exports.SnapshotVersionMismatchError = SnapshotVersionMismatchError;
2500
+ exports.appendMessages = appendMessages;
2501
+ exports.assertAgentMachine = assertAgentMachine;
2502
+ exports.assistantMessage = require_events.assistantMessage;
2503
+ exports.canReach = canReach;
2504
+ exports.createAgentSchemas = createAgentSchemas;
2505
+ exports.createTextLogic = require_events.createTextLogic;
2506
+ exports.explorePaths = explorePaths;
2507
+ exports.getAcceptedEvents = require_events.getAcceptedEvents;
2508
+ exports.getAgentMessages = require_events.getAgentMessages;
2509
+ exports.getStateMeta = require_events.getStateMeta;
2510
+ exports.inspectTransitions = inspectTransitions;
2511
+ exports.lintAgentMachine = lintAgentMachine;
2512
+ exports.messagesSchema = messagesSchema;
2513
+ exports.parseAgentEvent = require_events.parseAgentEvent;
2514
+ exports.persistSnapshot = require_events.persistSnapshot;
2515
+ exports.provideExecutors = provideExecutors;
2516
+ exports.runAgent = runAgent;
2517
+ exports.runAgentToCompletion = runAgentToCompletion;
2518
+ Object.defineProperty(exports, "setupAgent", {
2519
+ enumerable: true,
2520
+ get: function() {
2521
+ return setupAgent;
2522
+ }
2523
+ });
2524
+ exports.simulateAgent = simulateAgent;
2525
+ exports.systemMessage = require_events.systemMessage;
2526
+ exports.toolMessage = require_events.toolMessage;
2527
+ exports.traceTransitions = traceTransitions;
2528
+ exports.userMessage = require_events.userMessage;