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

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 (130) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
  13. package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
  46. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  47. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +399 -20
  53. package/dist/testing.d.cts +196 -255
  54. package/dist/testing.d.mts +196 -255
  55. package/dist/testing.mjs +395 -20
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-Bink-Drw.cjs +2304 -0
  69. package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
  70. package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
  71. package/dist/verify-Dpz1u5Pe.mjs +2251 -0
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +311 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +136 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +54 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +516 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +487 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +81 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -192
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
@@ -0,0 +1,2304 @@
1
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
3
+ let xstate = require("xstate");
4
+ //#region src/steps.ts
5
+ /**
6
+ * Internal: the pure `(state, event) => (nextState, requests)` view of an
7
+ * agent machine, used by model-free simulation (`simulateAgent`) and tests.
8
+ * An {@link AgentStep} is a snapshot plus the model requests the machine is
9
+ * now waiting on; nothing here executes anything. Hosts use
10
+ * `createAgentRuntime`.
11
+ * @module
12
+ */
13
+ /** @internal Normalizes current and legacy XState invoke effect shapes. */
14
+ function getInvokeEffectMetadata(action) {
15
+ if (action.type === "@xstate.spawn") return action;
16
+ if (action.type === "xstate.spawnChild") {
17
+ const params = action.params;
18
+ return params ? {
19
+ ...params,
20
+ logic: action.logic
21
+ } : void 0;
22
+ }
23
+ if (action.type === "@xstate.start" && typeof action.src === "string") return action;
24
+ }
25
+ /**
26
+ * The invokes a snapshot is still waiting on, lowered to the same spawn-effect
27
+ * shape {@link getAgentRequests} reads. Derived from the snapshot's live
28
+ * children rather than the last transition's actions, so a state that invokes
29
+ * several actors at once (an `invoke: [...]` array, or parallel regions each
30
+ * invoking) keeps reporting the siblings after the first one settles —
31
+ * including when the settled invoke's `onDone` is targetless and starts
32
+ * nothing new.
33
+ *
34
+ * Entries are ordered by invoke id, so a walker that resolves one invoke per
35
+ * step is deterministic.
36
+ *
37
+ * @internal
38
+ */
39
+ function getPendingInvokes(snapshot) {
40
+ const children = snapshot.children ?? {};
41
+ return Object.keys(children).sort().flatMap((id) => {
42
+ const child = children[id];
43
+ const childSnapshot = child?.getSnapshot?.();
44
+ if (!child || childSnapshot?.status !== "active") return [];
45
+ return [{
46
+ type: "@xstate.spawn",
47
+ id,
48
+ src: child.src,
49
+ input: childSnapshot.input,
50
+ logic: child.logic
51
+ }];
52
+ });
53
+ }
54
+ /**
55
+ * Scans a set of executable actions (as returned by xstate's `transition`/
56
+ * `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
57
+ * lowers each into an {@link AgentStepRequest}. Pass `options.machine` to
58
+ * pre-fill `schemas`/`actors` from the machine's registered `setupAgent`
59
+ * options instead of passing them by hand.
60
+ * `options.snapshot` is required to resolve a decision's candidate events
61
+ * (intersecting declared `allowedEvents` with what's currently legal) — omit
62
+ * it and decision requests report an empty `events` list.
63
+ *
64
+ * @internal
65
+ */
66
+ function getAgentRequests(actions, { machine, ...options } = {}) {
67
+ if (machine) options = {
68
+ ...require_event_log.getRegisteredAgentExecutionOptions(machine),
69
+ ...options
70
+ };
71
+ return actions.flatMap((action) => {
72
+ const metadata = getInvokeEffectMetadata(action);
73
+ const params = metadata && typeof metadata.src !== "string" && typeof metadata.id === "string" && (require_event_log.isTextLogic(metadata.logic) || require_decision.isDecisionLogic(metadata.logic)) ? {
74
+ ...metadata,
75
+ src: metadata.id
76
+ } : metadata;
77
+ if (!params || typeof params.src !== "string") return [];
78
+ if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
79
+ const registeredLogic = require_event_log.isTextLogic(params.logic) || require_decision.isDecisionLogic(params.logic) ? params.logic : options.actors?.[params.src];
80
+ if (require_decision.isDecisionLogic(registeredLogic)) {
81
+ const decisionRequest = registeredLogic.request(params.input);
82
+ const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
83
+ const events = options.snapshot ? require_decision.getAcceptedEvents(options.snapshot, {
84
+ events: options.events,
85
+ schemas: options.schemas,
86
+ eventTypes: allowedEventTypes,
87
+ actor: "agent"
88
+ }) : [];
89
+ const humanEventTypes = options.snapshot ? require_decision.getHumanEventTypes(options.snapshot) : /* @__PURE__ */ new Set();
90
+ return [{
91
+ ...decisionRequest,
92
+ id: params.id,
93
+ events,
94
+ ...decisionRequest.options ? { options: decisionRequest.options.filter((option) => !humanEventTypes.has(option.event.type)) } : {}
95
+ }];
96
+ }
97
+ const textLogic = require_event_log.isTextLogic(registeredLogic) ? registeredLogic : void 0;
98
+ const input = textLogic ? textLogic.request(params.input) : void 0;
99
+ if (!input) return [];
100
+ return [{
101
+ kind: "text",
102
+ id: params.id,
103
+ src: params.src,
104
+ ...textLogic ? { mode: textLogic.mode } : {},
105
+ input,
106
+ tools: input.tools ?? {},
107
+ events: []
108
+ }];
109
+ });
110
+ }
111
+ /**
112
+ * Builds the canonical `xstate.done.actor` event xstate's `transition()`
113
+ * expects to resolve a spawned invoke — including the child session identity
114
+ * that rejects a stale completion from an earlier incarnation.
115
+ *
116
+ * @internal
117
+ */
118
+ function doneEvent(snapshot, request, output) {
119
+ const id = typeof request === "string" ? request : request.id;
120
+ const child = snapshot.children[id];
121
+ return {
122
+ type: "xstate.done.actor",
123
+ actorId: id,
124
+ ...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
125
+ output
126
+ };
127
+ }
128
+ /**
129
+ * The `xstate.error.actor` counterpart of {@link doneEvent} — the event a
130
+ * failed invoke delivers, which `onError` transitions observe. Carries the
131
+ * same child session identity, so xstate does not discard it as stale.
132
+ *
133
+ * @internal
134
+ */
135
+ function errorEvent(snapshot, request, error) {
136
+ const id = typeof request === "string" ? request : request.id;
137
+ const child = snapshot.children[id];
138
+ return {
139
+ type: "xstate.error.actor",
140
+ actorId: id,
141
+ ...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
142
+ error
143
+ };
144
+ }
145
+ /**
146
+ * Applies a request's `output` as a done event (or, with `outcome: 'error'`,
147
+ * its `output` as the invoke's error) via `transition(...)`, returning the raw
148
+ * `[snapshot, actions]` tuple. Lower-level than {@link resolveAgentStep} /
149
+ * {@link rejectAgentStep} — those helpers wrap this and also run
150
+ * {@link getAgentRequests} to produce the next {@link AgentStep}.
151
+ *
152
+ * @internal
153
+ */
154
+ function transitionResult(logic, snapshot, request, output, outcome = "output") {
155
+ const event = outcome === "error" ? errorEvent(snapshot, request, output) : doneEvent(snapshot, request, output);
156
+ const result = (0, xstate.transition)(logic, snapshot, event);
157
+ applyFinalStateOutput(logic, result[0], event);
158
+ return result;
159
+ }
160
+ /**
161
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
162
+ * equivalent of `initialTransition` plus request discovery. Begins the
163
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
164
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
165
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
166
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
167
+ */
168
+ function initialAgentStep(machine, input, options) {
169
+ const [snapshot, actions] = (0, xstate.initialTransition)(machine, input);
170
+ return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
171
+ }
172
+ /**
173
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
174
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
175
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
176
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
177
+ * step object through without manually plucking the snapshot out.
178
+ */
179
+ function transitionAgentStep(machine, snapshotOrStep, event, options) {
180
+ const snapshot = isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep;
181
+ const [nextSnapshot, actions] = (0, xstate.transition)(machine, snapshot, event);
182
+ return createAgentStep(machine, nextSnapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
183
+ }
184
+ /**
185
+ * Applies a resolved text request's output (a `kind: 'text'`
186
+ * {@link AgentRequest} — not a decision) as a done event and returns the
187
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
188
+ * (which returns a {@link ChosenEvent}) and apply it with
189
+ * {@link transitionAgentStep} instead — a decision has no output value of
190
+ * its own to feed here.
191
+ */
192
+ function resolveAgentStep(machine, step, request, output, options) {
193
+ const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
194
+ return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
195
+ }
196
+ /**
197
+ * Rejects a pending invoke — the failure counterpart of
198
+ * {@link resolveAgentStep}. Delivers `error` as the invoke's
199
+ * `xstate.error.actor` event, so the machine takes that invoke's `onError`
200
+ * transition and returns the next {@link AgentStep}. With no `onError` in
201
+ * scope the returned step's snapshot has `status: 'error'`, exactly as a live
202
+ * run's failed invoke does.
203
+ *
204
+ * A durable host replays a failed call with this: the log says the call
205
+ * failed, so the replay rejects the invoke instead of resolving it. Scripted
206
+ * playthroughs use it too — see `simulateAgent`'s `script.errors`.
207
+ *
208
+ * `error` can be any value. An `Error` instance is the usual one, but a plain
209
+ * object (`{ code: 'truncated' }`) reaches the `onError` transition as
210
+ * `event.error` untouched, so a machine that branches on a failure code is
211
+ * testable without constructing a provider's error class.
212
+ */
213
+ function rejectAgentStep(machine, step, request, error, options) {
214
+ const [snapshot, actions] = transitionResult(machine, step.snapshot, request, error, "error");
215
+ return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
216
+ }
217
+ function createAgentStep(machine, snapshot, actions, options) {
218
+ applyFinalStateOutput(machine, snapshot);
219
+ return {
220
+ snapshot,
221
+ actions,
222
+ requests: getAgentRequests(getPendingInvokes(snapshot), {
223
+ ...options,
224
+ snapshot
225
+ }),
226
+ done: snapshot.status === "done"
227
+ };
228
+ }
229
+ function resolveStateValueConfig(config, value) {
230
+ if (typeof value === "string") return config.states?.[value];
231
+ if (!value || typeof value !== "object") return;
232
+ for (const [key, childValue] of Object.entries(value)) {
233
+ const childConfig = config.states?.[key];
234
+ if (!childConfig) continue;
235
+ if (childConfig.type === "final") return childConfig;
236
+ const nested = resolveStateValueConfig(childConfig, childValue);
237
+ if (nested) return nested;
238
+ }
239
+ }
240
+ function applyFinalStateOutput(logic, snapshot, event) {
241
+ const machineSnapshot = snapshot;
242
+ if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
243
+ const config = logic.config;
244
+ if (!config) return;
245
+ const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
246
+ if (output === void 0) return;
247
+ machineSnapshot.output = typeof output === "function" ? output({
248
+ context: machineSnapshot.context,
249
+ event
250
+ }) : output;
251
+ }
252
+ function isAgentStep(value) {
253
+ return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
254
+ }
255
+ //#endregion
256
+ //#region src/verify.ts
257
+ /**
258
+ * Provider-free verification for agent machines — static lint checks plus
259
+ * model-free simulation over the pure step path. Coding agents generate these
260
+ * machines; this module lets them close the loop and self-verify WITHOUT any
261
+ * API keys or model calls.
262
+ *
263
+ * - {@link lintAgentMachine} — static structural checks over a built machine
264
+ * (works for TS-authored and `setupAgent.fromConfig`-compiled machines).
265
+ * - {@link simulateAgent} — a deterministic, scripted playthrough.
266
+ * - {@link explorePaths} — enumerates decision/external branches to a bounded
267
+ * depth and reports reached states and terminal outcomes.
268
+ * - {@link canReach} — a thin wrapper over {@link explorePaths} answering
269
+ * "can this state (or snapshot predicate) be reached?" with a witness path.
270
+ *
271
+ * @module
272
+ */
273
+ const DECIDE_SRC = "agent.decide";
274
+ const ACT_SRC = "agent.act";
275
+ function normalizeInvokes(invoke) {
276
+ if (invoke === void 0 || invoke === null) return [];
277
+ return Array.isArray(invoke) ? invoke : [invoke];
278
+ }
279
+ function buildStateIndex(rootConfig) {
280
+ const index = /* @__PURE__ */ new Map();
281
+ const walk = (states, parentPath) => {
282
+ for (const [name, config] of Object.entries(states ?? {})) {
283
+ const path = parentPath ? `${parentPath}.${name}` : name;
284
+ const hasChildren = !!config.states && Object.keys(config.states).length > 0;
285
+ index.set(path, {
286
+ path,
287
+ config,
288
+ parentPath,
289
+ isFinal: config.type === "final",
290
+ isParallel: config.type === "parallel",
291
+ isCompound: hasChildren && config.type !== "parallel",
292
+ invokes: normalizeInvokes(config.invoke)
293
+ });
294
+ if (hasChildren) walk(config.states, path);
295
+ }
296
+ };
297
+ walk(rootConfig.states, "");
298
+ return index;
299
+ }
300
+ function ancestorChain(node, index) {
301
+ const chain = [];
302
+ let parent = node.parentPath;
303
+ while (parent) {
304
+ const parentNode = index.get(parent);
305
+ if (!parentNode) break;
306
+ chain.push(parentNode);
307
+ parent = parentNode.parentPath;
308
+ }
309
+ return chain;
310
+ }
311
+ function hasNonEmptyOn(config) {
312
+ return !!config.on && Object.keys(config.on).length > 0;
313
+ }
314
+ function isDecisionInvoke(src, actors) {
315
+ if (typeof src === "string") return src === DECIDE_SRC || require_decision.isDecisionLogic(actors[src]);
316
+ return require_decision.isDecisionLogic(src);
317
+ }
318
+ function isAgentLogicNeedingBinding(src) {
319
+ return (require_event_log.isTextLogic(src) || require_decision.isDecisionLogic(src)) && !require_event_log.executorBoundLogics.has(src);
320
+ }
321
+ function safeJsonSchema(schema) {
322
+ try {
323
+ return require_event_log.getJsonSchemaSync(schema);
324
+ } catch {
325
+ return;
326
+ }
327
+ }
328
+ function checkDecideWithoutEvents(ctx) {
329
+ const out = [];
330
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
331
+ if (!isDecisionInvoke(invoke.src, ctx.actors)) continue;
332
+ const selfHandles = hasNonEmptyOn(node.config);
333
+ const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
334
+ const invokeObserves = invoke.onDone !== void 0;
335
+ if (selfHandles || ancestorHandles || invokeObserves) continue;
336
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
337
+ out.push({
338
+ code: "decide-without-events",
339
+ severity: "error",
340
+ path: node.path,
341
+ message: `State '${node.path}' invokes decision source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the decision's chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
342
+ });
343
+ }
344
+ return out;
345
+ }
346
+ function literalAllowedEvents(json, path, index) {
347
+ let node = json;
348
+ for (const key of path.split(".")) node = node?.states?.[key];
349
+ let input = normalizeInvokes(node?.invoke)[index]?.input;
350
+ if (require_event_log.isRecord(input) && typeof input["@expr"] === "string") try {
351
+ input = JSON.parse(input["@expr"]);
352
+ } catch {
353
+ return;
354
+ }
355
+ const allowedEvents = require_event_log.isRecord(input) ? input.allowedEvents : void 0;
356
+ return typeof allowedEvents === "string" ? [allowedEvents] : Array.isArray(allowedEvents) ? allowedEvents : void 0;
357
+ }
358
+ function handlesAsHuman(config, eventType) {
359
+ const transitions = config.on?.[eventType];
360
+ return (Array.isArray(transitions) ? transitions : [transitions]).some((transition) => !!transition && typeof transition === "object" && transition.meta?.actor === "human");
361
+ }
362
+ function checkDecideAllowsHumanEvent(ctx) {
363
+ const out = [];
364
+ for (const node of ctx.index.values()) for (const [index, invoke] of node.invokes.entries()) {
365
+ const isAct = invoke.src === ACT_SRC;
366
+ if (!isAct && !isDecisionInvoke(invoke.src, ctx.actors)) continue;
367
+ const allowedEvents = literalAllowedEvents(ctx.json, node.path, index);
368
+ if (!allowedEvents) continue;
369
+ const configs = [
370
+ node.config,
371
+ ...ancestorChain(node, ctx.index).map((ancestor) => ancestor.config),
372
+ ctx.config
373
+ ];
374
+ for (const type of allowedEvents) {
375
+ if (typeof type !== "string" || require_decision.isEventPattern(type) || !configs.some((config) => handlesAsHuman(config, type))) continue;
376
+ out.push({
377
+ code: "decide-allows-human-event",
378
+ severity: "error",
379
+ path: node.path,
380
+ message: `State '${node.path}' lets ${isAct ? "'agent.act'" : "a decision"} choose '${type}', but a transition tagged 'meta: { actor: "human" }' handles it, so the model is never offered it. Remove '${type}' from 'allowedEvents', or drop the tag if a model may send it.`
381
+ });
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+ function checkDirectObjectSrc(ctx) {
387
+ const out = [];
388
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
389
+ const src = invoke.src;
390
+ if (typeof src === "string" || !src || typeof src !== "object") continue;
391
+ if (!isAgentLogicNeedingBinding(src)) continue;
392
+ out.push({
393
+ code: "direct-object-src",
394
+ severity: "warning",
395
+ path: node.path,
396
+ message: `State '${node.path}' invokes a direct-object agent logic. Direct-object invoke srcs cannot be rebound by the agent runtime, so they inherit no host executors — call '.withExecutor(...)' on the logic, or register it as a string-keyed actor source (machine.provide({ actors: { name: logic } })) and invoke it by name.`
397
+ });
398
+ }
399
+ return out;
400
+ }
401
+ function handlesActorError(config) {
402
+ if (config["onError"] !== void 0) return true;
403
+ return Object.keys(config.on ?? {}).some((type) => type === "*" || type.startsWith("xstate.error"));
404
+ }
405
+ function checkInvokeWithoutOnError(ctx) {
406
+ const out = [];
407
+ for (const node of ctx.index.values()) for (const invoke of node.invokes) {
408
+ if (invoke.onError !== void 0 || handlesActorError(node.config)) continue;
409
+ if (handlesActorError(ctx.config) || ancestorChain(node, ctx.index).some((ancestor) => handlesActorError(ancestor.config))) continue;
410
+ const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
411
+ out.push({
412
+ code: "invoke-without-on-error",
413
+ severity: "warning",
414
+ path: node.path,
415
+ message: `State '${node.path}' invokes '${srcName}' with no 'onError' transition, and no ancestor handles an actor error. A rejected request or actor puts the machine in an error state with no modeled recovery. Add 'onError' (a 'failed' final state, or a bounded retry).`
416
+ });
417
+ }
418
+ return out;
419
+ }
420
+ const LINT_CHECKS = [
421
+ checkDecideWithoutEvents,
422
+ checkDecideAllowsHumanEvent,
423
+ checkDirectObjectSrc,
424
+ checkInvokeWithoutOnError
425
+ ];
426
+ /**
427
+ * Runs static structural checks over a built agent machine and returns the
428
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
429
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
430
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
431
+ * plus the schemas/actor sources the library already retains per machine.
432
+ *
433
+ * No model calls, no API keys — a coding agent that emits an agent machine can
434
+ * call this to catch agent-specific mistakes such as undeliverable decisions,
435
+ * un-rebindable request sources, and an unhandled transcript event. General
436
+ * state-machine lint belongs to XState tooling.
437
+ *
438
+ * Pass `{ throw: true }` for the one-liner form used in tests and generation
439
+ * loops: it returns silently when the machine is clean and throws
440
+ * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
441
+ * findings, or on warnings too with `{ throw: true, warnings: true }`.
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
446
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
447
+ * ```
448
+ *
449
+ * @example Throwing form
450
+ * ```ts
451
+ * test('agent machine is structurally sound', () => {
452
+ * lintAgentMachine(machine, { throw: true });
453
+ * });
454
+ * ```
455
+ */
456
+ function lintAgentMachine(machine, options = {}) {
457
+ const config = machine.config ?? {};
458
+ const index = buildStateIndex(config);
459
+ const registered = require_event_log.getRegisteredAgentExecutionOptions(machine);
460
+ let json;
461
+ try {
462
+ json = (0, xstate.machineToJSON)(machine);
463
+ } catch {
464
+ json = void 0;
465
+ }
466
+ const ctx = {
467
+ config,
468
+ json,
469
+ index,
470
+ schemas: registered.schemas,
471
+ actors: registered.actors ?? machine.sources?.actors ?? {}
472
+ };
473
+ const disabled = new Set(options.disable ?? []);
474
+ const ignored = options.ignore ?? [];
475
+ const diagnostics = LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code) && !ignored.some((entry) => entry.code === d.code && entry.path === d.path));
476
+ if (options.throw) {
477
+ const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
478
+ if (failing.length > 0) throw new AgentLintError(machine.id, failing);
479
+ }
480
+ return diagnostics;
481
+ }
482
+ /**
483
+ * Thrown by `lintAgentMachine(machine, { throw: true })` (and its
484
+ * {@link assertAgentMachine} alias) when lint finds failing diagnostics.
485
+ * `diagnostics` holds the findings; the message lists them one per finding,
486
+ * so a test runner's failure output reads like the CLI's lint report.
487
+ */
488
+ var AgentLintError = class extends require_event_log.AgentError {
489
+ diagnostics;
490
+ constructor(machineId, diagnostics) {
491
+ const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
492
+ super("lint-failed", `Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
493
+ this.name = "AgentLintError";
494
+ this.diagnostics = diagnostics;
495
+ }
496
+ };
497
+ /**
498
+ * Asserts a machine passes {@link lintAgentMachine}: returns silently when
499
+ * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
500
+ * otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
501
+ * Fails on error-severity findings; set `warnings: true` to fail on warnings
502
+ * too. The one-liner for tests and generation loops:
503
+ *
504
+ * @example
505
+ * ```ts
506
+ * test('agent machine is structurally sound', () => {
507
+ * assertAgentMachine(machine);
508
+ * });
509
+ * ```
510
+ */
511
+ function assertAgentMachine(machine, options = {}) {
512
+ lintAgentMachine(machine, {
513
+ ...options,
514
+ throw: true
515
+ });
516
+ }
517
+ function pendingInvokes(step) {
518
+ const out = [];
519
+ const children = step.snapshot.children ?? {};
520
+ for (const metadata of getPendingInvokes(step.snapshot)) {
521
+ const src = typeof metadata.src === "string" ? metadata.src : metadata.id;
522
+ if (typeof src === "string") {
523
+ const ref = children[metadata.id];
524
+ out.push({
525
+ id: metadata.id,
526
+ src,
527
+ input: metadata.input ?? ref?.options?.input,
528
+ logic: metadata.logic,
529
+ ref
530
+ });
531
+ }
532
+ }
533
+ return out;
534
+ }
535
+ function takeFromQueue(channel, src) {
536
+ const queue = channel?.[src];
537
+ if (queue && queue.length > 0) return {
538
+ found: true,
539
+ value: queue.shift()
540
+ };
541
+ return { found: false };
542
+ }
543
+ /**
544
+ * Deterministically plays a machine through, resolving each request from a
545
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
546
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
547
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
548
+ * and a `trail` of every step taken.
549
+ *
550
+ * Decisions run through the live run's own validation/retry core,
551
+ * {@link resolveDecision}, with the script standing in for the model: each
552
+ * attempt consumes the next queued {@link ChosenEvent} for that src, so an
553
+ * unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
554
+ * — the next queued decision is tried, exactly as a live run re-asks the
555
+ * model. The decision logic's `maxRetries` caps attempts as it would live;
556
+ * when retries continue past the end of the queue, the last queued decision
557
+ * repeats (a scripted model that insists). The repeat applies only within one
558
+ * decision request's retries — each new decision request must have its own
559
+ * queued entry, or the dry-script error throws as usual. Exhausting all
560
+ * attempts delivers
561
+ * the resulting {@link AgentDecisionExhaustedError} to the machine as the
562
+ * decision invoke's error (so an `onError` transition observes it, as it
563
+ * would live); with no `onError` to catch it, it is thrown.
564
+ *
565
+ * Throws a descriptive error when the script runs dry mid-request, naming the
566
+ * pending request's kind, src, and id so the missing scripted response is
567
+ * obvious.
568
+ *
569
+ * @example
570
+ * ```ts
571
+ * const { status, snapshot } = simulateAgent(machine, {
572
+ * input: { topic: 'state machines' },
573
+ * script: {
574
+ * decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
575
+ * events: [{ type: 'APPROVE' }], // crosses the human gate
576
+ * },
577
+ * });
578
+ * ```
579
+ */
580
+ async function simulateAgent(machine, options) {
581
+ const maxSteps = options.maxSteps ?? 100;
582
+ const script = {
583
+ text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
584
+ decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
585
+ invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr]),
586
+ errors: mapValues(options.script.errors ?? {}, (arr) => [...arr]),
587
+ events: [...options.script.events ?? []]
588
+ };
589
+ let step = initialAgentStep(machine, options.input);
590
+ const trail = [{ state: step.snapshot.value }];
591
+ for (let i = 0; i < maxSteps; i++) {
592
+ if (step.done) return {
593
+ status: "done",
594
+ snapshot: step.snapshot,
595
+ trail
596
+ };
597
+ const request = step.requests[0];
598
+ if (request) {
599
+ if (request.kind === "decision") {
600
+ const invokeMeta = findInvokeMetadata(step, request.id);
601
+ const src = invokeMeta?.src ?? request.id;
602
+ const decisionSrc = src in (script.decisions ?? {}) ? src : request.id in (script.decisions ?? {}) ? request.id : src;
603
+ const errorSrc = queueKey(script.errors, src, request.id);
604
+ const failure = takeFromQueue(script.errors, errorSrc);
605
+ if (failure.found) {
606
+ step = rejectScriptedRequest(machine, step, request.id, failure.value, {
607
+ kind: "decision",
608
+ src: errorSrc,
609
+ trail
610
+ });
611
+ continue;
612
+ }
613
+ step = await applyScriptedDecision(machine, step, request, decisionSrc, invokeMeta?.logic, script, trail);
614
+ continue;
615
+ }
616
+ const failure = takeFromQueue(script.errors, request.src);
617
+ if (failure.found) {
618
+ step = rejectScriptedRequest(machine, step, request, failure.value, {
619
+ kind: "text",
620
+ src: request.src,
621
+ trail
622
+ });
623
+ continue;
624
+ }
625
+ const taken = takeFromQueue(script.text, request.src);
626
+ if (!taken.found) throw scriptDryError("text", request.src, request.id);
627
+ step = resolveAgentStep(machine, step, request, asTextResult(taken.value));
628
+ trail.push({
629
+ state: step.snapshot.value,
630
+ resolvedRequest: {
631
+ kind: "text",
632
+ src: request.src,
633
+ id: request.id,
634
+ outcome: "output"
635
+ }
636
+ });
637
+ continue;
638
+ }
639
+ const [invoke] = pendingInvokes(step);
640
+ if (invoke) {
641
+ const failure = takeFromQueue(script.errors, invoke.src);
642
+ if (failure.found) {
643
+ step = rejectScriptedRequest(machine, step, invoke.id, failure.value, {
644
+ kind: "invoke",
645
+ src: invoke.src,
646
+ trail
647
+ });
648
+ continue;
649
+ }
650
+ const taken = takeFromQueue(script.invokes, invoke.src);
651
+ if (!taken.found) throw scriptDryError("invoke", invoke.src, invoke.id);
652
+ step = resolveAgentStep(machine, step, invoke.id, taken.value);
653
+ trail.push({
654
+ state: step.snapshot.value,
655
+ resolvedRequest: {
656
+ kind: "invoke",
657
+ src: invoke.src,
658
+ id: invoke.id,
659
+ outcome: "output"
660
+ }
661
+ });
662
+ continue;
663
+ }
664
+ const external = script.events;
665
+ if (external.length > 0) {
666
+ const event = external.shift();
667
+ if (!step.snapshot.can(event)) throw new Error(`simulateAgent: scripted external event '${event.type}' cannot be taken in state ${JSON.stringify(step.snapshot.value)} (no handler, or its guard rejected it). A live run's send would be silently dropped here; fix the script's \`events\` queue.`);
668
+ step = transitionAgentStep(machine, step, event);
669
+ trail.push({
670
+ state: step.snapshot.value,
671
+ appliedEvent: event,
672
+ external: true
673
+ });
674
+ continue;
675
+ }
676
+ return {
677
+ status: "idle",
678
+ snapshot: step.snapshot,
679
+ trail
680
+ };
681
+ }
682
+ return {
683
+ status: "exhausted",
684
+ snapshot: step.snapshot,
685
+ trail
686
+ };
687
+ }
688
+ function queueKey(channel, src, id) {
689
+ return channel && !(src in channel) && id in channel ? id : src;
690
+ }
691
+ function rejectScriptedRequest(machine, step, request, error, entry) {
692
+ const id = typeof request === "string" ? request : request.id;
693
+ const next = rejectAgentStep(machine, step, request, error);
694
+ if (next.snapshot.status === "error") throw unhandledScriptedError(error, entry.kind, entry.src, id);
695
+ entry.trail.push({
696
+ state: next.snapshot.value,
697
+ resolvedRequest: {
698
+ kind: entry.kind,
699
+ src: entry.src,
700
+ id,
701
+ outcome: "error",
702
+ error
703
+ }
704
+ });
705
+ return next;
706
+ }
707
+ function unhandledScriptedError(error, kind, src, id) {
708
+ if (error instanceof Error) return error;
709
+ return new Error(`simulateAgent: the scripted error for the ${kind} request '${src}' (id '${id}') reached no onError transition, so the machine errored. Add an onError to that invoke, or drop the errors['${src}'] entry.`, { cause: error });
710
+ }
711
+ async function applyScriptedDecision(machine, step, request, decisionSrc, invokeLogic, script, trail) {
712
+ const dequeued = [];
713
+ const decide = async () => {
714
+ const taken = takeFromQueue(script.decisions, decisionSrc);
715
+ if (taken.found) {
716
+ dequeued.push(taken.value);
717
+ return { event: taken.value };
718
+ }
719
+ if (dequeued.length === 0) throw scriptDryError("decision", decisionSrc, request.id, request);
720
+ return { event: dequeued[dequeued.length - 1] };
721
+ };
722
+ const logic = require_decision.isDecisionLogic(invokeLogic) ? invokeLogic : resolveRegisteredDecisionLogic(machine, decisionSrc);
723
+ const maxRetries = request.maxRetries ?? logic?.maxRetries;
724
+ const can = (event) => step.snapshot.can(event);
725
+ const options = require_decision.acceptedDecisionOptions(request, can);
726
+ const offered = options ? {
727
+ ...request,
728
+ options
729
+ } : request;
730
+ let chosen;
731
+ try {
732
+ chosen = await require_decision.resolveDecision(offered, { decide }, {
733
+ maxRetries,
734
+ canTake: can
735
+ });
736
+ } catch (error) {
737
+ if (!(error instanceof require_decision.AgentDecisionExhaustedError)) throw error;
738
+ const next = rejectAgentStep(machine, step, request.id, error);
739
+ if (next.snapshot.status === "error") throw error;
740
+ trail.push({
741
+ state: next.snapshot.value,
742
+ rejectedEvents: dequeued
743
+ });
744
+ return next;
745
+ }
746
+ const next = transitionAgentStep(machine, step, chosen);
747
+ const rejected = dequeued.slice(0, -1);
748
+ trail.push({
749
+ state: next.snapshot.value,
750
+ appliedEvent: chosen,
751
+ ...rejected.length > 0 ? { rejectedEvents: rejected } : {}
752
+ });
753
+ return next;
754
+ }
755
+ function findInvokeMetadata(step, id) {
756
+ for (const metadata of getPendingInvokes(step.snapshot)) {
757
+ if (metadata.id !== id) continue;
758
+ return {
759
+ ...typeof metadata.src === "string" ? { src: metadata.src } : {},
760
+ logic: metadata.logic ?? (typeof metadata.src === "object" ? metadata.src : void 0)
761
+ };
762
+ }
763
+ }
764
+ function resolveRegisteredDecisionLogic(machine, src) {
765
+ const candidate = require_event_log.getRegisteredAgentExecutionOptions(machine).actors?.[src] ?? machine.sources?.actors?.[src];
766
+ return require_decision.isDecisionLogic(candidate) ? candidate : void 0;
767
+ }
768
+ const textOutputs = /* @__PURE__ */ new WeakSet();
769
+ /**
770
+ * Marks a canned text-request output for {@link explorePaths},
771
+ * {@link canReach}, or {@link simulateAgent} as the whole
772
+ * `{ result, messages }` envelope the invoke resolves with, so a machine that
773
+ * reads `output.messages` sees them. A plain canned value is the `result`,
774
+ * with `messages: []`.
775
+ *
776
+ * @example
777
+ * ```ts
778
+ * await explorePaths(machine, {
779
+ * outputs: { reply: [textOutput('hi', { messages: [{ role: 'assistant', content: 'hi' }] })] },
780
+ * });
781
+ * ```
782
+ */
783
+ function textOutput(result, options = {}) {
784
+ const envelope = {
785
+ result,
786
+ messages: options.messages ?? []
787
+ };
788
+ textOutputs.add(envelope);
789
+ return envelope;
790
+ }
791
+ function asTextResult(value) {
792
+ return require_event_log.isRecord(value) && textOutputs.has(value) ? value : {
793
+ result: value,
794
+ messages: []
795
+ };
796
+ }
797
+ function mapValues(obj, fn) {
798
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
799
+ }
800
+ function scriptDryError(kind, src, id, request) {
801
+ const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
802
+ const key = kind === "text" ? `text['${src}']` : kind === "decision" ? `decisions['${src}']` : `invokes['${src}']`;
803
+ return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add an entry to the script's \`${key}\` queue.${events}`);
804
+ }
805
+ const MAX_ADVANCE_STEPS = 1e3;
806
+ const FINITE_PAYLOAD_CAP = 64;
807
+ const DEFAULT_MAX_NODES = 1e5;
808
+ const MAX_CHILD_NESTING = 4;
809
+ const DEFAULT_BUDGET_NODES = 25e4;
810
+ const DEFAULT_CHILD_CACHE = 64;
811
+ function startBudget(budget) {
812
+ const started = Date.now();
813
+ return {
814
+ nodes: 0,
815
+ maxNodes: budget?.nodes ?? DEFAULT_BUDGET_NODES,
816
+ started,
817
+ deadline: budget?.ms === void 0 ? void 0 : started + budget.ms
818
+ };
819
+ }
820
+ const logicIds = /* @__PURE__ */ new WeakMap();
821
+ let nextLogicId = 0;
822
+ function logicId(logic) {
823
+ let id = logicIds.get(logic);
824
+ if (id === void 0) {
825
+ id = nextLogicId++;
826
+ logicIds.set(logic, id);
827
+ }
828
+ return id;
829
+ }
830
+ function isMachineLogic(logic) {
831
+ return require_event_log.isRecord(logic) && "root" in logic && "config" in logic && typeof logic["transition"] === "function";
832
+ }
833
+ function pushDistinct(values, seen, value) {
834
+ let key;
835
+ try {
836
+ key = value instanceof Error ? `Error:${value.name}:${value.message}` : JSON.stringify(value) ?? String(value);
837
+ } catch {
838
+ values.push(value);
839
+ return;
840
+ }
841
+ if (!seen.has(key)) {
842
+ seen.add(key);
843
+ values.push(value);
844
+ }
845
+ }
846
+ function eventsToParent(effects, parent) {
847
+ if (parent === void 0 || !Array.isArray(effects)) return [];
848
+ return effects.flatMap((effect) => require_event_log.isRecord(effect) && effect["type"] === "@xstate.sendTo" && effect["target"] === parent && require_event_log.isRecord(effect["event"]) && typeof effect["event"]["type"] === "string" ? [effect["event"]] : []);
849
+ }
850
+ function outboundOf(effects, parent, own) {
851
+ if (parent === void 0 || !Array.isArray(effects)) return [];
852
+ const children = Object.entries(require_event_log.isRecord(own) ? own : {});
853
+ const out = [];
854
+ for (const effect of effects) {
855
+ if (!require_event_log.isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !require_event_log.isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
856
+ const target = effect["target"];
857
+ const event = effect["event"];
858
+ if (target === parent) out.push({ event });
859
+ else if (!children.some(([id, ref]) => ref === target || id === target)) out.push({ route: {
860
+ target,
861
+ event
862
+ } });
863
+ }
864
+ return out;
865
+ }
866
+ function finiteDomain(schema) {
867
+ if (!require_event_log.isRecord(schema)) return;
868
+ if ("const" in schema) return [schema["const"]];
869
+ if (Array.isArray(schema["enum"])) return schema["enum"];
870
+ const union = schema["anyOf"] ?? schema["oneOf"];
871
+ if (Array.isArray(union)) {
872
+ const parts = union.map(finiteDomain);
873
+ return parts.every((part) => part !== void 0) ? [...new Set(parts.flat())] : void 0;
874
+ }
875
+ const types = Array.isArray(schema["type"]) ? schema["type"] : [schema["type"]];
876
+ if (types.every((type) => type === "boolean" || type === "null")) return types.flatMap((type) => type === "boolean" ? [true, false] : [null]);
877
+ }
878
+ const OMITTED = Symbol("omitted");
879
+ function finitePayloads(jsonSchema) {
880
+ const bare = {
881
+ payloads: [{}],
882
+ complete: false
883
+ };
884
+ if (!require_event_log.isRecord(jsonSchema) || jsonSchema["type"] !== "object" && !require_event_log.isRecord(jsonSchema["properties"])) return bare;
885
+ const properties = require_event_log.isRecord(jsonSchema["properties"]) ? jsonSchema["properties"] : {};
886
+ const required = new Set(Array.isArray(jsonSchema["required"]) ? jsonSchema["required"] : []);
887
+ if ([...required].some((key) => key !== "type" && !(key in properties))) return bare;
888
+ let product = [{}];
889
+ let complete = true;
890
+ for (const [key, schema] of Object.entries(properties)) {
891
+ if (key === "type") continue;
892
+ const domain = finiteDomain(schema);
893
+ if (!domain || domain.length === 0) {
894
+ if (required.has(key)) return bare;
895
+ complete = false;
896
+ continue;
897
+ }
898
+ const choices = required.has(key) ? domain : [OMITTED, ...domain];
899
+ if (product.length * choices.length > FINITE_PAYLOAD_CAP) return bare;
900
+ product = product.flatMap((payload) => choices.map((value) => value === OMITTED ? payload : {
901
+ ...payload,
902
+ [key]: value
903
+ }));
904
+ }
905
+ return {
906
+ payloads: product,
907
+ complete
908
+ };
909
+ }
910
+ function mayReadPayload(snapshot, type) {
911
+ return (0, xstate.getNextTransitions)(snapshot).some((transition) => transition.eventType === type && (transition.to !== void 0 || transition.guard !== void 0 || transition.matches !== void 0 || typeof transition.context === "function"));
912
+ }
913
+ function extend(prev, event) {
914
+ return {
915
+ event,
916
+ prev,
917
+ length: (prev?.length ?? 0) + 1
918
+ };
919
+ }
920
+ function pathOf(link) {
921
+ const path = Array.from({ length: link?.length ?? 0 });
922
+ for (let at = link; at; at = at.prev) path[at.length - 1] = at.event;
923
+ return path;
924
+ }
925
+ function pathTypes(link) {
926
+ return pathOf(link).map((event) => typeof event.actorId === "string" ? `${event.type}(${event.actorId})` : event.type).join(", ");
927
+ }
928
+ const MAX_PUMP = 1e3;
929
+ function childStartStep(machine, input, ref) {
930
+ const fresh = initialAgentStep(machine, input);
931
+ const snapshot = ref?.getSnapshot?.();
932
+ return withLiveRequests(require_event_log.isRecord(snapshot) && snapshot["status"] === "active" ? {
933
+ ...fresh,
934
+ snapshot
935
+ } : fresh);
936
+ }
937
+ function withLiveRequests(step) {
938
+ if (step.requests.length === 0) return step;
939
+ const children = step.snapshot.children ?? {};
940
+ const requests = step.requests.filter((request) => {
941
+ const logic = children[request.id]?.logic;
942
+ return logic === void 0 || require_event_log.isTextLogic(logic) || require_decision.isDecisionLogic(logic);
943
+ });
944
+ return requests.length === step.requests.length ? step : {
945
+ ...step,
946
+ requests
947
+ };
948
+ }
949
+ function declaresUsageTransition(snapshot) {
950
+ return (0, xstate.getNextTransitions)(snapshot).some((transition) => transition.eventType === "@agent.usage" || transition.eventType === "*");
951
+ }
952
+ function childSession(id, ref) {
953
+ return typeof ref?.sessionId === "string" ? ref.sessionId : id;
954
+ }
955
+ function pruneDelivered(delivered, step) {
956
+ if (delivered === void 0 || delivered.size === 0) return delivered;
957
+ const children = step.snapshot.children ?? {};
958
+ const running = new Set(Object.entries(children).map(([id, ref]) => childSession(id, ref)));
959
+ const kept = [...delivered].filter((key) => running.has(key.slice(0, key.indexOf("\0"))));
960
+ return kept.length === delivered.size ? delivered : new Set(kept);
961
+ }
962
+ function hasTransientStates(node) {
963
+ const visit = (node) => {
964
+ if (!require_event_log.isRecord(node)) return false;
965
+ if (node["type"] === "choice" || Array.isArray(node["always"]) && node["always"].length > 0) return true;
966
+ return Object.values(require_event_log.isRecord(node["states"]) ? node["states"] : {}).some(visit);
967
+ };
968
+ return visit(node);
969
+ }
970
+ function transientStateIds(node, ids = []) {
971
+ if (!require_event_log.isRecord(node)) return ids;
972
+ if (node["type"] === "choice" || Array.isArray(node["always"]) && node["always"].length > 0) ids.push(String(node["id"]));
973
+ for (const child of Object.values(require_event_log.isRecord(node["states"]) ? node["states"] : {})) transientStateIds(child, ids);
974
+ return ids;
975
+ }
976
+ function hasParallelStates(node) {
977
+ return require_event_log.isRecord(node) && (node["type"] === "parallel" || Object.values(require_event_log.isRecord(node["states"]) ? node["states"] : {}).some(hasParallelStates));
978
+ }
979
+ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false) {
980
+ const maxDepth = options.maxDepth ?? 8;
981
+ const maxPaths = options.maxPaths ?? 200;
982
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
983
+ const errorScript = options.errors ?? {};
984
+ const outputScript = options.outputs ?? {};
985
+ const coupled = options.children === "coupled";
986
+ const timerMode = options.timers ?? "fire";
987
+ const usageScript = nesting === 0 && !stepping ? options.usage ?? {} : void 0;
988
+ const interleaving = options.interleave === "pending" || stepping;
989
+ const errorsFor = (key) => {
990
+ if (!(key in errorScript)) return;
991
+ const entry = errorScript[key];
992
+ if (Array.isArray(entry)) return entry.length > 0 ? {
993
+ values: entry,
994
+ record: true
995
+ } : void 0;
996
+ return {
997
+ values: [entry],
998
+ record: false
999
+ };
1000
+ };
1001
+ const eventSchemas = require_event_log.getRegisteredAgentExecutionOptions(machine).schemas?.events ?? machine.schemas?.events ?? {};
1002
+ const unseenTransient = new Set(trackTransits ? transientStateIds(machine.root) : []);
1003
+ const keepTracking = trackTransits && hasParallelStates(machine.root);
1004
+ const transits = /* @__PURE__ */ new WeakMap();
1005
+ const withTransits = (next, microsteps) => {
1006
+ next = withLiveRequests(next);
1007
+ if (unseenTransient.size > 0 || keepTracking) {
1008
+ const passed = microsteps().slice(0, -1).map(([snapshot]) => snapshot);
1009
+ for (const snapshot of passed) for (const node of snapshot.nodes) unseenTransient.delete(node.id);
1010
+ transits.set(next, passed);
1011
+ }
1012
+ return next;
1013
+ };
1014
+ const resolveStep = (prev, id, output) => withTransits(resolveAgentStep(machine, prev, id, output), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, doneEvent(prev.snapshot, id, output)));
1015
+ const rejectStep = (prev, id, error) => withTransits(rejectAgentStep(machine, prev, id, error), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, errorEvent(prev.snapshot, id, error)));
1016
+ const transitionStep = (prev, event) => withTransits(transitionAgentStep(machine, prev, event), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event));
1017
+ const settleStep = (prev, id, output, usage) => {
1018
+ if (!usage) return {
1019
+ step: resolveStep(prev, id, output),
1020
+ completed: true
1021
+ };
1022
+ const charged = transitionStep(prev, usage);
1023
+ if (!pendingInvokes(charged).some((invoke) => invoke.id === id)) return {
1024
+ step: charged,
1025
+ completed: false
1026
+ };
1027
+ const resolved = resolveStep(charged, id, output);
1028
+ transits.set(resolved, [
1029
+ ...transits.get(charged) ?? [],
1030
+ charged.snapshot,
1031
+ ...transits.get(resolved) ?? []
1032
+ ]);
1033
+ return {
1034
+ step: resolved,
1035
+ completed: true
1036
+ };
1037
+ };
1038
+ const usageFor = (step, request) => {
1039
+ if (!usageScript || request.kind !== "text" || !declaresUsageTransition(step.snapshot)) return;
1040
+ const values = usageScript[request.src];
1041
+ if (!values?.length) {
1042
+ vacuous.add(require_event_log.AGENT_USAGE_EVENT_TYPE);
1043
+ return;
1044
+ }
1045
+ return values.map((usage) => ({
1046
+ type: require_event_log.AGENT_USAGE_EVENT_TYPE,
1047
+ kind: "text",
1048
+ id: request.id,
1049
+ src: request.src,
1050
+ model: request.input.model,
1051
+ ...request.input.name !== void 0 ? { name: request.input.name } : {},
1052
+ usage
1053
+ }));
1054
+ };
1055
+ const stops = (step) => stopWhen !== void 0 && (stopWhen(step.snapshot) || (transits.get(step)?.some((snapshot) => stopWhen(snapshot)) ?? false));
1056
+ const finiteCache = /* @__PURE__ */ new Map();
1057
+ const schemaPayloads = (type, snapshot) => {
1058
+ const schema = eventSchemas[type];
1059
+ let fill = finiteCache.get(type);
1060
+ if (schema && !fill) {
1061
+ fill = finitePayloads(safeJsonSchema(schema));
1062
+ finiteCache.set(type, fill);
1063
+ }
1064
+ fill ??= {
1065
+ payloads: [{}],
1066
+ complete: !mayReadPayload(snapshot, type)
1067
+ };
1068
+ if (!fill.complete && fill.payloads.length === 1 && Object.keys(fill.payloads[0]).length === 0 && mayReadPayload(snapshot, type)) vacuous.add(type);
1069
+ if (!fill.complete && !unexpanded.has(type)) {
1070
+ unexpanded.add(type);
1071
+ note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
1072
+ }
1073
+ return fill.payloads;
1074
+ };
1075
+ const variantsOf = (type, snapshot, table, requestOptions) => {
1076
+ const listed = table[type];
1077
+ if (listed) return listed.map((payload) => ({
1078
+ ...payload,
1079
+ type
1080
+ }));
1081
+ if (requestOptions) return requestOptions.filter((option) => option.event.type === type).map((option) => option.event);
1082
+ return schemaPayloads(type, snapshot).map((payload) => ({
1083
+ ...payload,
1084
+ type
1085
+ }));
1086
+ };
1087
+ const childCache = /* @__PURE__ */ new Map();
1088
+ const childCacheSize = options.budget?.childCache ?? DEFAULT_CHILD_CACHE;
1089
+ const exploreChild = (src, logic, input, ref) => {
1090
+ if (nesting >= MAX_CHILD_NESTING) {
1091
+ note(() => `child: src '${src}' is nested deeper than ${MAX_CHILD_NESTING} machines; not explored`);
1092
+ return {
1093
+ outputs: [],
1094
+ errors: [],
1095
+ events: [],
1096
+ stalls: false,
1097
+ complete: false
1098
+ };
1099
+ }
1100
+ let key;
1101
+ try {
1102
+ key = `${logicId(logic)}\u0000${src}\u0000${JSON.stringify(input) ?? "undefined"}`;
1103
+ } catch {
1104
+ key = void 0;
1105
+ }
1106
+ const cached = key === void 0 ? void 0 : childCache.get(key);
1107
+ if (cached) {
1108
+ childCache.delete(key);
1109
+ childCache.set(key, cached);
1110
+ return cached;
1111
+ }
1112
+ const child = explore(logic, {
1113
+ ...options,
1114
+ input
1115
+ }, void 0, nesting + 1, new Set(options.childEvents?.[src] ?? []), ref, false, budget);
1116
+ if (child.undeliverable.length > 0) note(() => `child: src '${src}' waits for ${child.undeliverable.join(", ")}, which childEvents does not list as reaching it; list each event the parent forwards`);
1117
+ for (const type of child.report.unexpandedEvents) unexpanded.add(type);
1118
+ for (const type of child.report.vacuous) vacuous.add(type);
1119
+ const outcome = {
1120
+ outputs: child.doneOutputs,
1121
+ errors: child.failures,
1122
+ events: child.parentEvents,
1123
+ stalls: child.stalls,
1124
+ complete: !child.unfinished && isExplorationComplete(child.report) && child.undeliverable.length === 0
1125
+ };
1126
+ if (!outcome.complete) note(() => `child: exploring src '${src}' was incomplete, so its outputs may be partial; add an outputs entry for it`);
1127
+ if (key !== void 0 && childCacheSize > 0) {
1128
+ childCache.set(key, outcome);
1129
+ if (childCache.size > childCacheSize) childCache.delete(childCache.keys().next().value);
1130
+ }
1131
+ return outcome;
1132
+ };
1133
+ const neverSettles = (src) => outputScript[src]?.length === 0 && !errorsFor(src);
1134
+ const settleFor = (id, src, isText, invoke, usage) => {
1135
+ const failures = errorsFor(src);
1136
+ if (neverSettles(src)) return { never: true };
1137
+ if (options.children === "explore" && !(src in outputScript) && !failures && isMachineLogic(invoke?.logic)) {
1138
+ const child = exploreChild(src, invoke.logic, invoke.input, invoke.ref);
1139
+ if (child.outputs.length === 1 && child.errors.length === 0 && child.events.length === 0 && !child.stalls && child.complete) return { output: child.outputs[0] };
1140
+ if (child.outputs.length === 0 && child.errors.length === 0 && child.events.length === 0 && !child.stalls) return { blocked: true };
1141
+ return { fork: {
1142
+ id,
1143
+ errors: child.errors,
1144
+ recordError: true,
1145
+ outputs: child.outputs,
1146
+ events: child.events,
1147
+ session: childSession(id, invoke.ref),
1148
+ stalls: child.stalls,
1149
+ ...child.complete ? {} : { incompleteSrc: src }
1150
+ } };
1151
+ }
1152
+ const outputs = outputScript[src] ?? [];
1153
+ if (failures || outputs.length > 1 || outputs.length === 1 && (usage?.length ?? 0) > 1) return { fork: {
1154
+ id,
1155
+ errors: failures?.values ?? [],
1156
+ recordError: failures?.record ?? false,
1157
+ outputs,
1158
+ isText,
1159
+ ...usage ? { usage } : {}
1160
+ } };
1161
+ return outputs.length === 1 ? { output: outputs[0] } : { blocked: true };
1162
+ };
1163
+ const isExploredChild = (invoke) => (options.children === "explore" || coupled) && !(invoke.src in outputScript) && !errorsFor(invoke.src) && isMachineLogic(invoke.logic);
1164
+ const concurrentForks = (step) => {
1165
+ if (options.children !== "explore" && !coupled) return;
1166
+ const invokes = pendingInvokes(step);
1167
+ if (!invokes.some(isExploredChild)) return;
1168
+ const kids = coupled ? invokes.filter(isExploredChild) : [];
1169
+ const blocked = [];
1170
+ const asFork = (settle, id, src, isText, usage) => {
1171
+ if ("fork" in settle) return [settle.fork];
1172
+ if ("blocked" in settle) {
1173
+ blocked.push(src);
1174
+ return [];
1175
+ }
1176
+ if ("never" in settle) return [];
1177
+ return [{
1178
+ id,
1179
+ errors: [],
1180
+ outputs: [settle.output],
1181
+ isText,
1182
+ ...usage ? { usage } : {}
1183
+ }];
1184
+ };
1185
+ const texts = step.requests.filter((request) => request.kind === "text");
1186
+ const requestIds = new Set(step.requests.map((request) => request.id));
1187
+ const forks = [...texts.flatMap((request) => {
1188
+ const usage = usageFor(step, request);
1189
+ return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
1190
+ }), ...invokes.filter((invoke) => !requestIds.has(invoke.id) && !kids.includes(invoke)).flatMap((invoke) => asFork(settleFor(invoke.id, invoke.src, false, invoke), invoke.id, invoke.src, false))];
1191
+ const decisions = step.requests.filter((request) => request.kind === "decision");
1192
+ for (const decision of decisions) {
1193
+ const src = findInvokeMetadata(step, decision.id)?.src;
1194
+ const failed = (src !== void 0 ? errorsFor(src) : void 0) ?? errorsFor(decision.id);
1195
+ if (failed) forks.push({
1196
+ id: decision.id,
1197
+ errors: failed.values,
1198
+ recordError: failed.record,
1199
+ outputs: []
1200
+ });
1201
+ }
1202
+ if (coupled) return {
1203
+ forks,
1204
+ blocked,
1205
+ decisions,
1206
+ kids
1207
+ };
1208
+ return forks.length > 0 && forks.length + blocked.length + decisions.length > 1 ? {
1209
+ forks,
1210
+ blocked,
1211
+ decisions
1212
+ } : void 0;
1213
+ };
1214
+ const reachedStates = /* @__PURE__ */ new Set();
1215
+ const reachedValues = [];
1216
+ const terminals = [];
1217
+ const unexplored = [];
1218
+ const unexpanded = /* @__PURE__ */ new Set();
1219
+ const vacuous = /* @__PURE__ */ new Set();
1220
+ const doneOutputs = [];
1221
+ const failures = [];
1222
+ const seenOutputs = /* @__PURE__ */ new Set();
1223
+ const seenFailures = /* @__PURE__ */ new Set();
1224
+ const seenParentEvents = /* @__PURE__ */ new Set();
1225
+ let stalls = false;
1226
+ let unfinished = false;
1227
+ const note = (text) => {
1228
+ if (nesting === 0) unexplored.push(text());
1229
+ };
1230
+ let captured;
1231
+ const endPath = (path, terminal) => {
1232
+ if (captured) {
1233
+ captured.push({
1234
+ status: terminal.status,
1235
+ ...terminal.missingSrc === void 0 ? {} : { missingSrc: terminal.missingSrc }
1236
+ });
1237
+ return;
1238
+ }
1239
+ pathsExplored++;
1240
+ if (terminal.status === "idle") stalls = true;
1241
+ else if (terminal.status !== "done" && terminal.status !== "error") unfinished = true;
1242
+ if (nesting === 0) terminals.push({
1243
+ ...terminal,
1244
+ path: pathOf(path)
1245
+ });
1246
+ };
1247
+ let prunedByGuard = 0;
1248
+ let pathsExplored = 0;
1249
+ let nodesExpanded = 0;
1250
+ let hitPathCap = false;
1251
+ const capped = () => {
1252
+ if (!stepping && (pathsExplored >= maxPaths || nodesExpanded >= maxNodes)) hitPathCap = true;
1253
+ if (budget.exhausted === void 0) {
1254
+ if (budget.nodes >= budget.maxNodes) budget.exhausted = "nodes";
1255
+ else if (budget.deadline !== void 0 && Date.now() >= budget.deadline) budget.exhausted = "ms";
1256
+ }
1257
+ return hitPathCap || budget.exhausted !== void 0;
1258
+ };
1259
+ let witness;
1260
+ const visited = /* @__PURE__ */ new Map();
1261
+ const parentEvents = [];
1262
+ const parent = childRef?._parent;
1263
+ const recordState = (step, effects = step.actions) => {
1264
+ const key = JSON.stringify(step.snapshot.value);
1265
+ if (!reachedStates.has(key)) {
1266
+ reachedStates.add(key);
1267
+ reachedValues.push(step.snapshot.value);
1268
+ }
1269
+ for (const event of eventsToParent(effects, parent)) pushDistinct(parentEvents, seenParentEvents, event);
1270
+ for (const snapshot of transits.get(step) ?? []) {
1271
+ const transitKey = JSON.stringify(snapshot.value);
1272
+ if (!reachedStates.has(transitKey)) {
1273
+ reachedStates.add(transitKey);
1274
+ reachedValues.push(snapshot.value);
1275
+ }
1276
+ }
1277
+ };
1278
+ const initial = stepping ? void 0 : withTransits(childStartStep(machine, options.input, childRef), () => (0, xstate.getInitialMicrosteps)(machine, options.input));
1279
+ if (initial) {
1280
+ recordState(initial, childRef?._initialEffects ?? initial.actions);
1281
+ if (stops(initial)) witness = [];
1282
+ }
1283
+ const undeliverable = /* @__PURE__ */ new Set();
1284
+ const external = deliverable ?? (options.hostEvents === void 0 ? void 0 : new Set(options.hostEvents));
1285
+ const arriving = (snapshot) => require_decision.getAcceptedEvents(snapshot).filter((descriptor) => {
1286
+ if (external === void 0 || external.has(descriptor.type)) return true;
1287
+ if (deliverable !== void 0) undeliverable.add(descriptor.type);
1288
+ return false;
1289
+ });
1290
+ const races = (step) => stepping || interleaving && (arriving(step.snapshot).length > 0 || timerMode === "fire" && armedTimers(step.snapshot).length > 0);
1291
+ const advance = (step, recordEvent) => {
1292
+ let current = step;
1293
+ for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
1294
+ if (stops(current)) return {
1295
+ step: current,
1296
+ hit: true
1297
+ };
1298
+ if (current.done) return { step: current };
1299
+ const request = current.requests.find((pending) => pending.kind !== "text" || !neverSettles(pending.src));
1300
+ const concurrent = concurrentForks(current);
1301
+ if (concurrent) return {
1302
+ step: current,
1303
+ fork: concurrent.forks[0],
1304
+ siblings: concurrent.forks.slice(1),
1305
+ blockedSiblings: concurrent.blocked,
1306
+ decisions: concurrent.decisions,
1307
+ ...concurrent.kids?.length ? { kids: concurrent.kids } : {}
1308
+ };
1309
+ if (request && request.kind === "text") {
1310
+ const usage = usageFor(current, request);
1311
+ const settle = settleFor(request.id, request.src, true, void 0, usage);
1312
+ if ("fork" in settle) return {
1313
+ step: current,
1314
+ fork: settle.fork
1315
+ };
1316
+ if ("blocked" in settle) return {
1317
+ step: current,
1318
+ blockedSrc: request.src
1319
+ };
1320
+ if ("never" in settle) return { step: current };
1321
+ if (races(current)) return {
1322
+ step: current,
1323
+ pending: {
1324
+ id: request.id,
1325
+ output: asTextResult(settle.output),
1326
+ ...usage ? { usage: usage[0] } : {}
1327
+ }
1328
+ };
1329
+ if (usage) recordEvent(usage[0]);
1330
+ current = settleStep(current, request.id, asTextResult(settle.output), usage?.[0]).step;
1331
+ recordState(current);
1332
+ continue;
1333
+ }
1334
+ if (request && request.kind === "decision") {
1335
+ const src = findInvokeMetadata(current, request.id)?.src;
1336
+ const failed = (src !== void 0 ? errorsFor(src) : void 0) ?? errorsFor(request.id);
1337
+ return failed ? {
1338
+ step: current,
1339
+ fork: {
1340
+ id: request.id,
1341
+ errors: failed.values,
1342
+ recordError: failed.record,
1343
+ outputs: [],
1344
+ isDecision: true
1345
+ }
1346
+ } : { step: current };
1347
+ }
1348
+ const [invoke] = pendingInvokes(current).filter((pending) => !neverSettles(pending.src));
1349
+ if (invoke) {
1350
+ const settle = settleFor(invoke.id, invoke.src, false, invoke);
1351
+ if ("fork" in settle) return {
1352
+ step: current,
1353
+ fork: settle.fork
1354
+ };
1355
+ if ("blocked" in settle) return {
1356
+ step: current,
1357
+ blockedSrc: invoke.src
1358
+ };
1359
+ if ("never" in settle) return { step: current };
1360
+ if (races(current)) return {
1361
+ step: current,
1362
+ pending: {
1363
+ id: invoke.id,
1364
+ output: settle.output
1365
+ }
1366
+ };
1367
+ current = resolveStep(current, invoke.id, settle.output);
1368
+ recordState(current);
1369
+ continue;
1370
+ }
1371
+ return { step: current };
1372
+ }
1373
+ return { step: current };
1374
+ };
1375
+ const acceptedVariants = (snapshot, path, table, except) => [...arriving(snapshot).flatMap((descriptor) => {
1376
+ if (except?.has(descriptor.type)) return [];
1377
+ if (table[descriptor.type]?.length === 0) {
1378
+ unexpanded.add(descriptor.type);
1379
+ note(() => `skipped: payloads lists no ${descriptor.type} at path [${pathTypes(path)}], so its branches were not explored`);
1380
+ }
1381
+ return variantsOf(descriptor.type, snapshot, table);
1382
+ }), ...timerEvents(snapshot, path)];
1383
+ const timerFires = /* @__PURE__ */ new WeakMap();
1384
+ const applied = (event) => timerFires.get(event) ?? event;
1385
+ const ignoredTimers = /* @__PURE__ */ new Set();
1386
+ function armedTimers(snapshot) {
1387
+ const timers = snapshot.timers;
1388
+ if (!Array.isArray(timers) || timers.length === 0) return [];
1389
+ return timers.flatMap((timer) => {
1390
+ if (!require_event_log.isRecord(timer) || timer["target"] !== "self" || !require_event_log.isRecord(timer["event"]) || typeof timer["event"]["type"] !== "string") return [];
1391
+ const event = timer["event"];
1392
+ if (!snapshot.can(event)) return [];
1393
+ return [{
1394
+ event,
1395
+ key: typeof timer["id"] === "string" ? { id: timer["id"] } : typeof timer["seq"] === "number" ? { seq: timer["seq"] } : { event }
1396
+ }];
1397
+ });
1398
+ }
1399
+ const timerEvents = (snapshot, path) => {
1400
+ const armed = armedTimers(snapshot);
1401
+ if (timerMode === "ignore") {
1402
+ for (const { event } of armed) {
1403
+ unexpanded.add(event.type);
1404
+ const key = JSON.stringify(event);
1405
+ if (!ignoredTimers.has(key)) {
1406
+ ignoredTimers.add(key);
1407
+ note(() => `timers: ${key} is armed at path [${pathTypes(path)}], and timers: "ignore" never fires it`);
1408
+ }
1409
+ }
1410
+ return [];
1411
+ }
1412
+ return armed.map(({ event, key }) => {
1413
+ const entry = { ...event };
1414
+ timerFires.set(entry, {
1415
+ type: "xstate.timer",
1416
+ ...key
1417
+ });
1418
+ return entry;
1419
+ });
1420
+ };
1421
+ function* raceBranches(settled, path, depth, except) {
1422
+ const snapshot = settled.snapshot;
1423
+ const table = options.payloads?.(snapshot) ?? {};
1424
+ for (const event of acceptedVariants(snapshot, path, table, except)) {
1425
+ if (witness !== void 0 || capped()) return;
1426
+ if (!snapshot.can(event)) {
1427
+ prunedByGuard++;
1428
+ continue;
1429
+ }
1430
+ const next = transitionStep(settled, applied(event));
1431
+ recordState(next);
1432
+ yield {
1433
+ step: next,
1434
+ path: extend(path, event),
1435
+ depth: depth + 1
1436
+ };
1437
+ }
1438
+ }
1439
+ const failBranch = (settled, path, depth, fork, error) => {
1440
+ const failed = rejectStep(settled, fork.id, error);
1441
+ recordState(failed);
1442
+ return {
1443
+ step: failed,
1444
+ path: extend(path, {
1445
+ type: "xstate.error.actor",
1446
+ actorId: fork.id,
1447
+ ...fork.recordError ? { error } : {}
1448
+ }),
1449
+ depth: depth + 1
1450
+ };
1451
+ };
1452
+ function* doneBranches(settled, path, depth, fork, output) {
1453
+ const value = fork.isText ? asTextResult(output) : output;
1454
+ const recorded = fork.isText ? value.result : output;
1455
+ const usages = fork.usage?.length ? fork.usage : [void 0];
1456
+ for (const [i, usage] of usages.entries()) {
1457
+ if (i > 0 && (witness !== void 0 || capped())) return;
1458
+ const { step, completed } = settleStep(settled, fork.id, value, usage);
1459
+ recordState(step);
1460
+ const charged = usage ? extend(path, usage) : path;
1461
+ yield {
1462
+ step,
1463
+ path: completed ? extend(charged, {
1464
+ type: "xstate.done.actor",
1465
+ actorId: fork.id,
1466
+ output: recorded
1467
+ }) : charged,
1468
+ depth: depth + 1
1469
+ };
1470
+ }
1471
+ }
1472
+ const maxDepthTerminal = (settled, path) => {
1473
+ endPath(path, {
1474
+ status: "max-depth",
1475
+ state: settled.snapshot.value
1476
+ });
1477
+ note(() => `max-depth: stopped at path [${pathTypes(path)}]`);
1478
+ };
1479
+ const steppers = /* @__PURE__ */ new Map();
1480
+ const stepperFor = (src, logic) => {
1481
+ if (nesting >= MAX_CHILD_NESTING) {
1482
+ note(() => `child: src '${src}' is nested deeper than ${MAX_CHILD_NESTING} machines; not explored`);
1483
+ return;
1484
+ }
1485
+ const key = `${logicId(logic)}\u0000${src}`;
1486
+ let stepper = steppers.get(key);
1487
+ if (!stepper) {
1488
+ stepper = explore(logic, {
1489
+ ...options,
1490
+ input: void 0,
1491
+ dedupeBy: void 0
1492
+ }, void 0, nesting + 1, new Set(options.childEvents?.[src] ?? []), void 0, false, budget, true).stepper;
1493
+ steppers.set(key, stepper);
1494
+ }
1495
+ return stepper;
1496
+ };
1497
+ const pumped = /* @__PURE__ */ new WeakSet();
1498
+ let outParent;
1499
+ const register = (step, kids, queue) => {
1500
+ const live = pendingInvokes(step).filter(isExploredChild);
1501
+ const sessions = new Set(live.map((invoke) => childSession(invoke.id, invoke.ref)));
1502
+ for (const session of kids.keys()) if (!sessions.has(session)) kids.delete(session);
1503
+ for (const invoke of live) {
1504
+ const session = childSession(invoke.id, invoke.ref);
1505
+ if (kids.has(session)) continue;
1506
+ const logic = invoke.logic;
1507
+ const engine = stepperFor(invoke.src, logic);
1508
+ if (!engine) continue;
1509
+ const fresh = childStartStep(logic, invoke.input, invoke.ref);
1510
+ const start = invoke.ref?._initialEffects === void 0 ? fresh : {
1511
+ ...fresh,
1512
+ actions: invoke.ref._initialEffects
1513
+ };
1514
+ const parentRef = invoke.ref?._parent;
1515
+ const kid = {
1516
+ id: invoke.id,
1517
+ src: invoke.src,
1518
+ engine,
1519
+ step: start,
1520
+ parent: parentRef,
1521
+ kids: void 0
1522
+ };
1523
+ const primed = engine.prime(kid);
1524
+ if (primed.overflow) return false;
1525
+ kids.set(session, {
1526
+ ...kid,
1527
+ step: primed.step,
1528
+ kids: primed.kids
1529
+ });
1530
+ queue.push(...outboundOf(start.actions, parentRef, start.snapshot.children), ...primed.outbound);
1531
+ if (primed.step.snapshot.status !== "active") queue.push({ settle: session });
1532
+ }
1533
+ return true;
1534
+ };
1535
+ const kidSessionFor = (step, target, kids) => {
1536
+ const children = step.snapshot.children ?? {};
1537
+ for (const [id, ref] of Object.entries(children)) if (ref === target || id === target) {
1538
+ const session = childSession(id, ref);
1539
+ return kids.has(session) ? session : void 0;
1540
+ }
1541
+ };
1542
+ const pump = (start, link, kids, queue) => {
1543
+ let step = start;
1544
+ let overflow = false;
1545
+ const outbound = [];
1546
+ const deliverTo = (at, target, event) => {
1547
+ const session = kidSessionFor(at, target, kids);
1548
+ const kid = session === void 0 ? void 0 : kids.get(session);
1549
+ if (!kid) return false;
1550
+ if (kid.step.snapshot.status !== "active") return true;
1551
+ const delivered = kid.engine.deliver(kid, event);
1552
+ if (delivered.overflow) {
1553
+ overflow = true;
1554
+ endPath(link, {
1555
+ status: "max-depth",
1556
+ state: at.snapshot.value
1557
+ });
1558
+ return true;
1559
+ }
1560
+ kids.set(session, {
1561
+ ...kid,
1562
+ step: delivered.step,
1563
+ kids: delivered.kids
1564
+ });
1565
+ queue.push(...delivered.outbound);
1566
+ if (delivered.step.snapshot.status !== "active") queue.push({ settle: session });
1567
+ return true;
1568
+ };
1569
+ const unrouted = (route) => {
1570
+ if (stepping) {
1571
+ outbound.push({ route });
1572
+ return;
1573
+ }
1574
+ unexpanded.add(route.event.type);
1575
+ note(() => `coupled: a child sent '${route.event.type}' to an actor the search does not model, at path [${pathTypes(link)}]`);
1576
+ };
1577
+ const flush = (at) => {
1578
+ if (pumped.has(at)) return;
1579
+ pumped.add(at);
1580
+ if (!register(at, kids, queue)) {
1581
+ overflow = true;
1582
+ endPath(link, {
1583
+ status: "max-depth",
1584
+ state: at.snapshot.value
1585
+ });
1586
+ return;
1587
+ }
1588
+ for (const effect of Array.isArray(at.actions) ? at.actions : []) {
1589
+ if (!require_event_log.isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !require_event_log.isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
1590
+ deliverTo(at, effect["target"], effect["event"]);
1591
+ if (overflow) return;
1592
+ }
1593
+ };
1594
+ flush(step);
1595
+ for (let i = 0; queue.length > 0 && !overflow; i++) {
1596
+ if (step.done || step.snapshot.status !== "active" || witness !== void 0) break;
1597
+ if (i >= MAX_PUMP) {
1598
+ endPath(link, {
1599
+ status: "max-depth",
1600
+ state: step.snapshot.value
1601
+ });
1602
+ note(() => `coupled: more than ${MAX_PUMP} deliveries at path [${pathTypes(link)}]`);
1603
+ overflow = true;
1604
+ break;
1605
+ }
1606
+ const item = queue.shift();
1607
+ if ("route" in item) {
1608
+ if (!deliverTo(step, item.route.target, item.route.event)) unrouted(item.route);
1609
+ continue;
1610
+ }
1611
+ if ("event" in item) {
1612
+ const accepted = step.snapshot.can(item.event);
1613
+ step = transitionStep(step, item.event);
1614
+ if (accepted) link = extend(link, item.event);
1615
+ } else {
1616
+ const kid = kids.get(item.settle);
1617
+ if (!kid) continue;
1618
+ kids.delete(item.settle);
1619
+ const settledKid = kid.step.snapshot;
1620
+ if (settledKid.status === "done") {
1621
+ step = resolveStep(step, kid.id, settledKid.output);
1622
+ link = extend(link, {
1623
+ type: "xstate.done.actor",
1624
+ actorId: kid.id,
1625
+ output: settledKid.output
1626
+ });
1627
+ } else {
1628
+ step = rejectStep(step, kid.id, settledKid.error);
1629
+ link = extend(link, {
1630
+ type: "xstate.error.actor",
1631
+ actorId: kid.id,
1632
+ error: settledKid.error
1633
+ });
1634
+ }
1635
+ }
1636
+ recordState(step);
1637
+ outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
1638
+ if (stops(step)) {
1639
+ witness = pathOf(link);
1640
+ break;
1641
+ }
1642
+ flush(step);
1643
+ }
1644
+ return {
1645
+ step,
1646
+ link,
1647
+ kids,
1648
+ outbound,
1649
+ overflow
1650
+ };
1651
+ };
1652
+ let unkeyable = 0;
1653
+ const kidsKey = (kids) => {
1654
+ if (!kids || kids.size === 0) return "";
1655
+ return `\u0003${[...kids.values()].map((kid) => `${kid.id}\u0000${kid.src}\u0000${kid.engine.stateKey(kid)}`).sort().join("")}`;
1656
+ };
1657
+ const stateKey = (kid) => {
1658
+ const snapshot = kid.step.snapshot;
1659
+ try {
1660
+ return JSON.stringify([
1661
+ snapshot.value,
1662
+ snapshot.context,
1663
+ snapshot.status,
1664
+ snapshot.historyValue ?? null,
1665
+ kid.step.requests.map((request) => request.id),
1666
+ Object.keys(snapshot.children ?? {}),
1667
+ pumped.has(kid.step)
1668
+ ]) + kidsKey(kid.kids);
1669
+ } catch {
1670
+ return `\u0002${unkeyable++}`;
1671
+ }
1672
+ };
1673
+ function* expand({ step, path, depth, delivered, kids: nodeKids }) {
1674
+ if (witness !== void 0 || capped()) return;
1675
+ nodesExpanded++;
1676
+ budget.nodes++;
1677
+ const { step: settled, blockedSrc, hit, fork, siblings, blockedSiblings, decisions, pending, kids: pendingKids } = advance(step, (event) => {
1678
+ path = extend(path, event);
1679
+ });
1680
+ if (hit) {
1681
+ witness = pathOf(path);
1682
+ return;
1683
+ }
1684
+ if (pendingKids) {
1685
+ const kids = new Map(nodeKids ?? []);
1686
+ const sizeBefore = kids.size;
1687
+ const synced = pump(settled, path, kids, []);
1688
+ if (synced.overflow) return;
1689
+ if (witness !== void 0 || synced.step !== settled || synced.kids.size !== sizeBefore || [...synced.kids].some(([session, kid]) => nodeKids?.get(session) !== kid)) {
1690
+ if (witness === void 0) yield {
1691
+ step: synced.step,
1692
+ path: synced.link,
1693
+ depth,
1694
+ kids: synced.kids,
1695
+ outbound: synced.outbound
1696
+ };
1697
+ return;
1698
+ }
1699
+ }
1700
+ if (options.dedupeBy) {
1701
+ const key = options.dedupeBy(settled.snapshot) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1702
+ const seenAt = visited.get(key);
1703
+ if (seenAt !== void 0 && seenAt <= depth) return;
1704
+ visited.set(key, depth);
1705
+ }
1706
+ if (pending) {
1707
+ if (depth >= maxDepth) {
1708
+ maxDepthTerminal(settled, path);
1709
+ return;
1710
+ }
1711
+ const resolved = settleStep(settled, pending.id, pending.output, pending.usage).step;
1712
+ recordState(resolved);
1713
+ const charged = pending.usage ? extend(path, pending.usage) : path;
1714
+ yield {
1715
+ step: resolved,
1716
+ path: stepping ? extend(charged, {
1717
+ type: "xstate.done.actor",
1718
+ actorId: pending.id,
1719
+ output: pending.output
1720
+ }) : charged,
1721
+ depth
1722
+ };
1723
+ yield* raceBranches(settled, path, depth);
1724
+ return;
1725
+ }
1726
+ if (pendingKids) {
1727
+ if (depth >= maxDepth) {
1728
+ maxDepthTerminal(settled, path);
1729
+ return;
1730
+ }
1731
+ let moved = false;
1732
+ let quiet = true;
1733
+ for (const [session, kid] of nodeKids ?? []) {
1734
+ const { moves, blocked, idle } = kid.engine.moves(kid, depth);
1735
+ if (!idle && moves.length > 0) quiet = false;
1736
+ for (const type of kid.engine.unexpanded) unexpanded.add(type);
1737
+ for (const type of kid.engine.vacuous) vacuous.add(type);
1738
+ for (const terminal of blocked) {
1739
+ if (witness !== void 0 || capped()) return;
1740
+ if (terminal.status === "idle" || terminal.status === "done" || terminal.status === "error") continue;
1741
+ endPath(path, {
1742
+ status: terminal.status,
1743
+ state: settled.snapshot.value,
1744
+ ...terminal.status === "needs-output" ? { missingSrc: terminal.missingSrc ?? kid.src } : {}
1745
+ });
1746
+ note(() => `child: src '${kid.src}' (actor '${kid.id}') stopped ${terminal.status} at path [${pathTypes(path)}]`);
1747
+ }
1748
+ for (const move of moves) {
1749
+ if (witness !== void 0 || capped()) return;
1750
+ moved = true;
1751
+ const kids = new Map(nodeKids);
1752
+ kids.set(session, {
1753
+ ...kid,
1754
+ step: move.step,
1755
+ kids: move.kids
1756
+ });
1757
+ const queue = [...move.outbound];
1758
+ if (move.step.snapshot.status !== "active") queue.push({ settle: session });
1759
+ let link = path;
1760
+ for (const event of move.path) {
1761
+ const actor = typeof event["actor"] === "string" ? `${kid.id}.${event["actor"]}` : kid.id;
1762
+ link = extend(link, {
1763
+ ...event,
1764
+ actor
1765
+ });
1766
+ }
1767
+ let next = {
1768
+ step: settled,
1769
+ link,
1770
+ kids,
1771
+ outbound: []
1772
+ };
1773
+ for (const item of queue) {
1774
+ const after = pump(next.step, next.link, next.kids, [item]);
1775
+ next = {
1776
+ ...after,
1777
+ outbound: [...next.outbound, ...after.outbound]
1778
+ };
1779
+ if (after.overflow || witness !== void 0 || after.step.snapshot.status !== "active") break;
1780
+ }
1781
+ if (witness !== void 0) return;
1782
+ if (next.overflow) continue;
1783
+ yield {
1784
+ step: next.step,
1785
+ path: next.link,
1786
+ depth: move.depth,
1787
+ kids: next.kids,
1788
+ outbound: next.outbound
1789
+ };
1790
+ }
1791
+ }
1792
+ const registered = new Set([...(nodeKids ?? /* @__PURE__ */ new Map()).values()].map((kid) => kid.id));
1793
+ for (const kid of pendingKids.filter((invoke) => !registered.has(invoke.id))) {
1794
+ if (witness !== void 0 || capped()) return;
1795
+ endPath(path, {
1796
+ status: "needs-output",
1797
+ state: settled.snapshot.value,
1798
+ missingSrc: kid.src
1799
+ });
1800
+ }
1801
+ const others = [...fork ? [fork] : [], ...siblings ?? []];
1802
+ for (const other of others) {
1803
+ for (const error of other.errors) {
1804
+ if (witness !== void 0 || capped()) return;
1805
+ yield failBranch(settled, path, depth, other, error);
1806
+ }
1807
+ for (const output of other.outputs) {
1808
+ if (witness !== void 0 || capped()) return;
1809
+ yield* doneBranches(settled, path, depth, other, output);
1810
+ }
1811
+ }
1812
+ for (const src of blockedSiblings ?? []) {
1813
+ if (witness !== void 0 || capped()) return;
1814
+ endPath(path, {
1815
+ status: "needs-output",
1816
+ state: settled.snapshot.value,
1817
+ missingSrc: src
1818
+ });
1819
+ note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
1820
+ }
1821
+ if (!decisions?.length && (moved || others.length > 0 || (blockedSiblings ?? []).length > 0)) {
1822
+ if (interleaving || quiet && others.length === 0 && !blockedSiblings?.length) yield* raceBranches(settled, path, depth);
1823
+ return;
1824
+ }
1825
+ if (witness !== void 0) return;
1826
+ }
1827
+ if (fork && !pendingKids) {
1828
+ if (depth >= maxDepth) {
1829
+ maxDepthTerminal(settled, path);
1830
+ return;
1831
+ }
1832
+ for (const error of fork.errors) {
1833
+ if (witness !== void 0 || capped()) return;
1834
+ yield failBranch(settled, path, depth, fork, error);
1835
+ }
1836
+ if (!fork.isDecision) {
1837
+ for (const output of fork.outputs) {
1838
+ if (witness !== void 0 || capped()) return;
1839
+ yield* doneBranches(settled, path, depth, fork, output);
1840
+ }
1841
+ for (const other of siblings ?? []) {
1842
+ for (const error of other.errors) {
1843
+ if (witness !== void 0 || capped()) return;
1844
+ yield failBranch(settled, path, depth, other, error);
1845
+ }
1846
+ for (const output of other.outputs) {
1847
+ if (witness !== void 0 || capped()) return;
1848
+ yield* doneBranches(settled, path, depth, other, output);
1849
+ }
1850
+ }
1851
+ for (const child of [fork, ...siblings ?? []]) for (const event of child.events ?? []) {
1852
+ if (witness !== void 0 || capped()) return;
1853
+ const key = `${child.session ?? child.id}\u0000${JSON.stringify(event)}`;
1854
+ if (delivered?.has(key) || !settled.snapshot.can(event)) continue;
1855
+ const next = transitionStep(settled, event);
1856
+ recordState(next);
1857
+ yield {
1858
+ step: next,
1859
+ path: extend(path, event),
1860
+ depth: depth + 1,
1861
+ delivered: /* @__PURE__ */ new Set([...delivered ?? [], key])
1862
+ };
1863
+ }
1864
+ if (fork.stalls && witness === void 0 && !capped()) endPath(path, {
1865
+ status: "idle",
1866
+ state: settled.snapshot.value
1867
+ });
1868
+ for (const src of blockedSiblings ?? []) note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
1869
+ for (const incompleteSrc of [...[fork, ...siblings ?? []].flatMap((child) => child.incompleteSrc === void 0 ? [] : [child.incompleteSrc]), ...blockedSiblings ?? []]) {
1870
+ if (witness !== void 0 || capped()) break;
1871
+ endPath(path, {
1872
+ status: "needs-output",
1873
+ state: settled.snapshot.value,
1874
+ missingSrc: incompleteSrc
1875
+ });
1876
+ }
1877
+ if (!decisions?.length) {
1878
+ if (interleaving) yield* raceBranches(settled, path, depth);
1879
+ return;
1880
+ }
1881
+ }
1882
+ if (witness !== void 0) return;
1883
+ }
1884
+ if (blockedSrc) {
1885
+ endPath(path, {
1886
+ status: "needs-output",
1887
+ state: settled.snapshot.value,
1888
+ missingSrc: blockedSrc
1889
+ });
1890
+ note(() => `needs-output: no \`outputs\` entry for src '${blockedSrc}' at path [${pathTypes(path)}]`);
1891
+ if (interleaving && depth < maxDepth) yield* raceBranches(settled, path, depth);
1892
+ return;
1893
+ }
1894
+ if (settled.done) {
1895
+ const output = settled.snapshot.output;
1896
+ endPath(path, {
1897
+ status: "done",
1898
+ state: settled.snapshot.value,
1899
+ ...output === void 0 ? {} : { output }
1900
+ });
1901
+ pushDistinct(doneOutputs, seenOutputs, output);
1902
+ return;
1903
+ }
1904
+ if (settled.snapshot.status === "error") {
1905
+ const error = settled.snapshot.error;
1906
+ endPath(path, {
1907
+ status: "error",
1908
+ state: settled.snapshot.value,
1909
+ error
1910
+ });
1911
+ pushDistinct(failures, seenFailures, error);
1912
+ return;
1913
+ }
1914
+ const snapshot = settled.snapshot;
1915
+ const table = options.payloads?.(snapshot) ?? {};
1916
+ const branchRequests = decisions?.length ? decisions : [settled.requests.find((request) => request.kind !== "text" || !neverSettles(request.src))];
1917
+ for (const request of branchRequests) {
1918
+ const requestOptions = request?.kind === "decision" ? require_decision.acceptedDecisionOptions(request, () => true) : void 0;
1919
+ const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : acceptedVariants(snapshot, path, table);
1920
+ if (branchEvents.length === 0 && request?.kind !== "decision") {
1921
+ endPath(path, {
1922
+ status: "idle",
1923
+ state: settled.snapshot.value
1924
+ });
1925
+ return;
1926
+ }
1927
+ if (depth >= maxDepth) {
1928
+ endPath(path, {
1929
+ status: "max-depth",
1930
+ state: settled.snapshot.value
1931
+ });
1932
+ note(() => `max-depth: stopped at path [${pathTypes(path)}]`);
1933
+ return;
1934
+ }
1935
+ let taken = 0;
1936
+ for (const event of branchEvents) {
1937
+ if (witness !== void 0 || capped()) return;
1938
+ if (!snapshot.can(event)) {
1939
+ prunedByGuard++;
1940
+ continue;
1941
+ }
1942
+ taken++;
1943
+ const next = transitionStep(settled, applied(event));
1944
+ recordState(next);
1945
+ yield {
1946
+ step: next,
1947
+ path: extend(path, event),
1948
+ depth: depth + 1
1949
+ };
1950
+ }
1951
+ if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
1952
+ endPath(path, {
1953
+ status: "idle",
1954
+ state: settled.snapshot.value
1955
+ });
1956
+ const refused = [...new Set(branchEvents.map((event) => event.type))];
1957
+ for (const type of refused) unexpanded.add(type);
1958
+ note(() => `stuck: every offered ${refused.join(", ")} event at path [${pathTypes(path)}] was refused by the machine's guards; add a payloads entry it accepts`);
1959
+ return;
1960
+ }
1961
+ if (request?.kind === "decision" && taken === 0) {
1962
+ if (witness !== void 0 || capped()) return;
1963
+ const exhausted = new require_decision.AgentDecisionExhaustedError([]);
1964
+ exhausted.message = `Decision '${request.name ?? request.id}' has no candidate the current snapshot accepts (explored, no model call).`;
1965
+ const failed = rejectStep(settled, request.id, exhausted);
1966
+ recordState(failed);
1967
+ yield {
1968
+ step: failed,
1969
+ path: extend(path, {
1970
+ type: "xstate.error.actor",
1971
+ actorId: request.id
1972
+ }),
1973
+ depth: depth + 1
1974
+ };
1975
+ }
1976
+ }
1977
+ const offered = branchRequests.filter((request) => request?.kind === "decision");
1978
+ if (interleaving && offered.length > 0) yield* raceBranches(settled, path, depth, new Set(offered.flatMap((request) => request.events.map((descriptor) => descriptor.type))));
1979
+ }
1980
+ if (stepping) {
1981
+ const stepper = {
1982
+ moves(kid, depth) {
1983
+ const outer = {
1984
+ captured,
1985
+ outParent
1986
+ };
1987
+ captured = [];
1988
+ outParent = kid.parent;
1989
+ try {
1990
+ const idle = stepper.quiet(kid);
1991
+ const moves = [];
1992
+ for (const node of expand({
1993
+ step: kid.step,
1994
+ path: void 0,
1995
+ depth,
1996
+ kids: kid.kids
1997
+ })) {
1998
+ const settledMove = pump(node.step, node.path, new Map(node.kids ?? kid.kids ?? []), []);
1999
+ if (settledMove.overflow) continue;
2000
+ moves.push({
2001
+ step: settledMove.step,
2002
+ path: pathOf(settledMove.link),
2003
+ depth: node.depth,
2004
+ kids: settledMove.kids,
2005
+ outbound: [...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children), ...settledMove.outbound]
2006
+ });
2007
+ }
2008
+ return {
2009
+ moves,
2010
+ blocked: captured,
2011
+ idle
2012
+ };
2013
+ } finally {
2014
+ captured = outer.captured;
2015
+ outParent = outer.outParent;
2016
+ }
2017
+ },
2018
+ deliver(kid, event) {
2019
+ const outer = outParent;
2020
+ outParent = kid.parent;
2021
+ try {
2022
+ const primed = pump(kid.step, void 0, new Map(kid.kids ?? []), []);
2023
+ if (primed.overflow) return {
2024
+ ...primed,
2025
+ overflow: true
2026
+ };
2027
+ const next = transitionStep(primed.step, event);
2028
+ recordState(next);
2029
+ const pumpedKids = pump(next, void 0, primed.kids, []);
2030
+ return {
2031
+ step: pumpedKids.step,
2032
+ kids: pumpedKids.kids,
2033
+ outbound: [
2034
+ ...primed.outbound,
2035
+ ...outboundOf(next.actions, kid.parent, next.snapshot.children),
2036
+ ...pumpedKids.outbound
2037
+ ],
2038
+ ...pumpedKids.overflow ? { overflow: true } : {}
2039
+ };
2040
+ } finally {
2041
+ outParent = outer;
2042
+ }
2043
+ },
2044
+ prime(kid) {
2045
+ const outer = outParent;
2046
+ outParent = kid.parent;
2047
+ try {
2048
+ return pump(kid.step, void 0, new Map(kid.kids ?? []), []);
2049
+ } finally {
2050
+ outParent = outer;
2051
+ }
2052
+ },
2053
+ quiet(kid) {
2054
+ if (kid.step.requests.length > 0) return false;
2055
+ const held = [...(kid.kids ?? /* @__PURE__ */ new Map()).values()];
2056
+ return pendingInvokes(kid.step).every((invoke) => {
2057
+ const child = held.find((candidate) => candidate.id === invoke.id);
2058
+ return child !== void 0 && child.engine.quiet(child);
2059
+ });
2060
+ },
2061
+ stateKey,
2062
+ unexpanded,
2063
+ vacuous
2064
+ };
2065
+ return {
2066
+ report: void 0,
2067
+ doneOutputs,
2068
+ failures,
2069
+ undeliverable: [],
2070
+ parentEvents,
2071
+ stalls,
2072
+ unfinished,
2073
+ stepper
2074
+ };
2075
+ }
2076
+ const root = {
2077
+ step: initial,
2078
+ path: void 0,
2079
+ depth: 0
2080
+ };
2081
+ if (witness === void 0 && stopWhen) {
2082
+ const levels = [[root]];
2083
+ search: for (let length = 0; length < levels.length; length++) {
2084
+ const level = levels[length] ?? [];
2085
+ for (let i = 0; i < level.length; i++) {
2086
+ const node = level[i];
2087
+ level[i] = void 0;
2088
+ for (const child of expand(node)) {
2089
+ child.delivered = pruneDelivered(child.delivered ?? node.delivered, child.step);
2090
+ child.kids ??= node.kids;
2091
+ (levels[child.path?.length ?? 0] ??= []).push(child);
2092
+ }
2093
+ if (witness !== void 0 || hitPathCap || budget.exhausted !== void 0) break search;
2094
+ }
2095
+ levels[length] = [];
2096
+ }
2097
+ } else if (witness === void 0) {
2098
+ const visit = (node) => {
2099
+ for (const child of expand(node)) {
2100
+ child.delivered = pruneDelivered(child.delivered ?? node.delivered, child.step);
2101
+ child.kids ??= node.kids;
2102
+ visit(child);
2103
+ }
2104
+ };
2105
+ visit(root);
2106
+ }
2107
+ if (nesting === 0 && budget.exhausted !== void 0) unexplored.push(`budget-exhausted: ${budget.exhausted} (${budget.nodes} nodes expanded in ${Date.now() - budget.started} ms, child searches included)`);
2108
+ const partial = hitPathCap || budget.exhausted !== void 0;
2109
+ const report = {
2110
+ reachedStates: reachedValues,
2111
+ terminals,
2112
+ prunedByGuard,
2113
+ unexplored,
2114
+ pathsExplored,
2115
+ hitPathCap,
2116
+ partial,
2117
+ complete: false,
2118
+ unexpandedEvents: [...unexpanded],
2119
+ vacuous: [...vacuous]
2120
+ };
2121
+ report.complete = isExplorationComplete(report);
2122
+ return {
2123
+ report,
2124
+ witness,
2125
+ doneOutputs,
2126
+ failures,
2127
+ undeliverable: [...undeliverable],
2128
+ parentEvents,
2129
+ stalls,
2130
+ unfinished
2131
+ };
2132
+ }
2133
+ /**
2134
+ * Enumerates a machine's decision and external-event branches to a bounded
2135
+ * depth, model-free, and reports which states are reached and how each path
2136
+ * terminates. At each decision request it forks one branch per candidate event
2137
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); a
2138
+ * decision with no takeable candidate exhausts as it does live, taking its
2139
+ * `onError` (an `error` terminal without one). At an idle wait it forks per
2140
+ * externally-accepted event. Text requests and other
2141
+ * invokes resolve from `outputs`, a by-src map of outputs to try (a
2142
+ * one-element list is a canned output; several fork one branch each), and a
2143
+ * missing src halts that branch with a `needs-output` terminal rather than
2144
+ * throwing. A src in
2145
+ * `errors` forks an extra branch where that invoke is rejected, so states
2146
+ * behind an `onError` are explored too.
2147
+ *
2148
+ * Events are applied as `{ type }` unless a payload is known: `payloads`
2149
+ * forks a type once per listed payload, a decide input's own `payloads`
2150
+ * become the branch set, and an event schema whose fields are finite (enums,
2151
+ * booleans, consts) expands to their product, each optional field also
2152
+ * omitted. A type that could not be fully expanded is listed in
2153
+ * `unexpandedEvents`, as is a type with no schema whose transition could read
2154
+ * the payload (a function transition, guard, `matches`, or context mapper).
2155
+ * `dedupeBy` explores each projected snapshot once, which keeps a large
2156
+ * payload table tractable.
2157
+ *
2158
+ * Combinatorics are bounded by `maxDepth` (default 8), `maxPaths` (default
2159
+ * 200), and `maxNodes` (default 100,000) per search, the last two reported
2160
+ * via `hitPathCap`, and by `budget` across the whole call, child searches
2161
+ * included. A cut-short report is `partial` and not `complete`.
2162
+ *
2163
+ * @example
2164
+ * ```ts
2165
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
2166
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
2167
+ * ```
2168
+ */
2169
+ async function explorePaths(machine, options = {}) {
2170
+ return explore(machine, options).report;
2171
+ }
2172
+ /** Thrown when a string reachability target is not a state in the machine. */
2173
+ var AgentUnknownStateError = class extends require_event_log.AgentError {
2174
+ target;
2175
+ constructor(machineId, target) {
2176
+ super("unknown-state", `canReach: machine '${machineId}' has no state matching '${target}'.`);
2177
+ this.name = "AgentUnknownStateError";
2178
+ this.target = target;
2179
+ }
2180
+ };
2181
+ function resolveStateTarget(machine, target) {
2182
+ const stack = [machine.root];
2183
+ while (stack.length > 0) {
2184
+ const node = stack.pop();
2185
+ if (node.id === target.replace(/^#/, "") || node.path.join(".") === target) return node.id;
2186
+ stack.push(...Object.values(node.states));
2187
+ }
2188
+ throw new AgentUnknownStateError(machine.id, target);
2189
+ }
2190
+ /**
2191
+ * Answers "can the machine reach this?" by exploring its branches (a thin
2192
+ * wrapper over {@link explorePaths}). The target is either a state path string
2193
+ * (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
2194
+ * form checks any property (a context invariant, a tag, a state+context
2195
+ * combination) without reifying a sentinel state for it. Returns
2196
+ * `{ reachable: true, witness }` with the event sequence that reaches it, or
2197
+ * `{ reachable: false }`. Check `complete` before treating `reachable: false`
2198
+ * as a proof: it is false when a cap or `maxDepth` cut exploration short, a
2199
+ * branch needed an `outputs` entry it did not have, or an event's payloads were
2200
+ * not all tried.
2201
+ *
2202
+ * @example
2203
+ * ```ts
2204
+ * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
2205
+ * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
2206
+ * ```
2207
+ *
2208
+ * @example Predicate target — a violation property, no sentinel state needed
2209
+ * ```ts
2210
+ * const violation = await canReach(
2211
+ * refundMachine,
2212
+ * (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
2213
+ * { input: { amount: 5000 } },
2214
+ * );
2215
+ * // violation.reachable → false is the safety proof
2216
+ * ```
2217
+ */
2218
+ async function canReach(machine, target, options = {}) {
2219
+ const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
2220
+ const { witness, report } = explore(machine, options, typeof target === "function" ? target : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget), 0, void 0, void 0, resolvedTarget !== void 0 && hasTransientStates(machine.getStateNodeById(resolvedTarget)));
2221
+ if (witness !== void 0) return {
2222
+ reachable: true,
2223
+ witness,
2224
+ complete: true,
2225
+ ...resolvedTarget ? { target: resolvedTarget } : {}
2226
+ };
2227
+ const complete = isExplorationComplete(report);
2228
+ return {
2229
+ reachable: false,
2230
+ complete,
2231
+ ...resolvedTarget ? { target: resolvedTarget } : {},
2232
+ ...complete ? {} : { unexplored: [
2233
+ ...report.unexplored,
2234
+ ...report.hitPathCap ? [`path-cap: maxPaths or maxNodes cut the search short after ${report.pathsExplored} paths`] : [],
2235
+ ...report.unexpandedEvents.length ? [`unexpanded-events: not every payload variant was explored for ${report.unexpandedEvents.join(", ")}`] : [],
2236
+ ...report.terminals.some((terminal) => terminal.status === "max-depth") ? ["max-depth: a path reached maxDepth before settling"] : []
2237
+ ] }
2238
+ };
2239
+ }
2240
+ /**
2241
+ * Whether an `explorePaths` report covers every path: no cap cut it short,
2242
+ * every payload was expanded, and every branch ended on its own. `done`,
2243
+ * `idle`, and `error` end a branch the machine itself ended; any other
2244
+ * terminal stopped a branch the search did not explore.
2245
+ * @internal
2246
+ */
2247
+ function isExplorationComplete(report) {
2248
+ return !report.hitPathCap && !report.partial && report.unexpandedEvents.length === 0 && report.terminals.every((terminal) => terminal.status === "done" || terminal.status === "idle" || terminal.status === "error");
2249
+ }
2250
+ //#endregion
2251
+ Object.defineProperty(exports, "AgentLintError", {
2252
+ enumerable: true,
2253
+ get: function() {
2254
+ return AgentLintError;
2255
+ }
2256
+ });
2257
+ Object.defineProperty(exports, "AgentUnknownStateError", {
2258
+ enumerable: true,
2259
+ get: function() {
2260
+ return AgentUnknownStateError;
2261
+ }
2262
+ });
2263
+ Object.defineProperty(exports, "assertAgentMachine", {
2264
+ enumerable: true,
2265
+ get: function() {
2266
+ return assertAgentMachine;
2267
+ }
2268
+ });
2269
+ Object.defineProperty(exports, "canReach", {
2270
+ enumerable: true,
2271
+ get: function() {
2272
+ return canReach;
2273
+ }
2274
+ });
2275
+ Object.defineProperty(exports, "explorePaths", {
2276
+ enumerable: true,
2277
+ get: function() {
2278
+ return explorePaths;
2279
+ }
2280
+ });
2281
+ Object.defineProperty(exports, "isExplorationComplete", {
2282
+ enumerable: true,
2283
+ get: function() {
2284
+ return isExplorationComplete;
2285
+ }
2286
+ });
2287
+ Object.defineProperty(exports, "lintAgentMachine", {
2288
+ enumerable: true,
2289
+ get: function() {
2290
+ return lintAgentMachine;
2291
+ }
2292
+ });
2293
+ Object.defineProperty(exports, "simulateAgent", {
2294
+ enumerable: true,
2295
+ get: function() {
2296
+ return simulateAgent;
2297
+ }
2298
+ });
2299
+ Object.defineProperty(exports, "textOutput", {
2300
+ enumerable: true,
2301
+ get: function() {
2302
+ return textOutput;
2303
+ }
2304
+ });