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

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 +138 -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-Ct_GZw_f.mjs → effects-BT_cSY0j.mjs} +1003 -109
  13. package/dist/{run-agent-s5D32w99.cjs → effects-DDseYtJk.cjs} +1037 -107
  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-30mH2moE.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-DlPzBWj-.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-BaNyz6Q3.d.cts} +4 -4
  46. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-C1CG_nfX.d.mts} +4 -4
  47. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  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 +2493 -1502
  53. package/dist/testing.d.cts +360 -256
  54. package/dist/testing.d.mts +360 -256
  55. package/dist/testing.mjs +2489 -1503
  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-Bm5nvpow.d.cts} +6 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-BnikdOca.d.mts} +6 -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-ChyX6jq0.mjs +2306 -0
  69. package/dist/verify-CwlombbC.cjs +2359 -0
  70. package/dist/{verify-BQpE8hUz.d.cts → verify-DJHfEfm6.d.cts} +213 -14
  71. package/dist/{verify-CqeuEmIk.d.mts → verify-i9Hiwc5g.d.mts} +213 -14
  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 +312 -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 +207 -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 +56 -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 +518 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +492 -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 +84 -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
@@ -1,1288 +0,0 @@
1
- const require_event_log = require("./event-log-BWSSLUff.cjs");
2
- const require_decision = require("./decision-BEsATcr1.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 params = getInvokeEffectMetadata(action);
73
- if (!params || typeof params.src !== "string") return [];
74
- if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
75
- const registeredLogic = require_event_log.isTextLogic(params.logic) || require_decision.isDecisionLogic(params.logic) ? params.logic : options.actors?.[params.src];
76
- if (require_decision.isDecisionLogic(registeredLogic)) {
77
- const decisionRequest = registeredLogic.request(params.input);
78
- const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
79
- const events = options.snapshot ? require_decision.getAcceptedEvents(options.snapshot, {
80
- events: options.events,
81
- schemas: options.schemas,
82
- eventTypes: allowedEventTypes,
83
- actor: "agent"
84
- }) : [];
85
- const humanEventTypes = options.snapshot ? require_decision.getHumanEventTypes(options.snapshot) : /* @__PURE__ */ new Set();
86
- return [{
87
- ...decisionRequest,
88
- id: params.id,
89
- events,
90
- ...decisionRequest.options ? { options: decisionRequest.options.filter((option) => !humanEventTypes.has(option.event.type)) } : {}
91
- }];
92
- }
93
- const textLogic = require_event_log.isTextLogic(registeredLogic) ? registeredLogic : void 0;
94
- const input = textLogic ? textLogic.request(params.input) : void 0;
95
- if (!input) return [];
96
- return [{
97
- kind: "text",
98
- id: params.id,
99
- src: params.src,
100
- ...textLogic ? { mode: textLogic.mode } : {},
101
- input,
102
- tools: input.tools ?? {},
103
- events: []
104
- }];
105
- });
106
- }
107
- /**
108
- * Builds the canonical `xstate.done.actor` event xstate's `transition()`
109
- * expects to resolve a spawned invoke — including the child session identity
110
- * that rejects a stale completion from an earlier incarnation.
111
- *
112
- * @internal
113
- */
114
- function doneEvent(snapshot, request, output) {
115
- const id = typeof request === "string" ? request : request.id;
116
- const child = snapshot.children[id];
117
- return {
118
- type: "xstate.done.actor",
119
- actorId: id,
120
- ...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
121
- output
122
- };
123
- }
124
- /**
125
- * The `xstate.error.actor` counterpart of {@link doneEvent} — the event a
126
- * failed invoke delivers, which `onError` transitions observe. Carries the
127
- * same child session identity, so xstate does not discard it as stale.
128
- *
129
- * @internal
130
- */
131
- function errorEvent(snapshot, request, error) {
132
- const id = typeof request === "string" ? request : request.id;
133
- const child = snapshot.children[id];
134
- return {
135
- type: "xstate.error.actor",
136
- actorId: id,
137
- ...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
138
- error
139
- };
140
- }
141
- /**
142
- * Applies a request's `output` as a done event (or, with `outcome: 'error'`,
143
- * its `output` as the invoke's error) via `transition(...)`, returning the raw
144
- * `[snapshot, actions]` tuple. Lower-level than {@link resolveAgentStep} /
145
- * {@link rejectAgentStep} — those helpers wrap this and also run
146
- * {@link getAgentRequests} to produce the next {@link AgentStep}.
147
- *
148
- * @internal
149
- */
150
- function transitionResult(logic, snapshot, request, output, outcome = "output") {
151
- const event = outcome === "error" ? errorEvent(snapshot, request, output) : doneEvent(snapshot, request, output);
152
- const result = (0, xstate.transition)(logic, snapshot, event);
153
- applyFinalStateOutput(logic, result[0], event);
154
- return result;
155
- }
156
- /**
157
- * Starts a machine and returns its first {@link AgentStep} — the step-path
158
- * equivalent of `initialTransition` plus request discovery. Begins the
159
- * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
160
- * (via {@link executeAgentRequest} for `kind: 'text'`, or
161
- * {@link resolveDecision} for `kind: 'decision'`), then advance with
162
- * {@link resolveAgentStep} or {@link transitionAgentStep}.
163
- */
164
- function initialAgentStep(machine, input, options) {
165
- const [snapshot, actions] = (0, xstate.initialTransition)(machine, input);
166
- return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
167
- }
168
- /**
169
- * Applies an externally-sent event (e.g. a decision's chosen event, or a
170
- * human's reply) and returns the next {@link AgentStep}. Accepts **either**
171
- * a raw snapshot **or** a prior `AgentStep` as the second argument —
172
- * `.snapshot` is unwrapped automatically, so callers can thread the whole
173
- * step object through without manually plucking the snapshot out.
174
- */
175
- function transitionAgentStep(machine, snapshotOrStep, event, options) {
176
- const snapshot = isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep;
177
- const [nextSnapshot, actions] = (0, xstate.transition)(machine, snapshot, event);
178
- return createAgentStep(machine, nextSnapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
179
- }
180
- /**
181
- * Applies a resolved text request's output (a `kind: 'text'`
182
- * {@link AgentRequest} — not a decision) as a done event and returns the
183
- * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
184
- * (which returns a {@link ChosenEvent}) and apply it with
185
- * {@link transitionAgentStep} instead — a decision has no output value of
186
- * its own to feed here.
187
- */
188
- function resolveAgentStep(machine, step, request, output, options) {
189
- const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
190
- return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
191
- }
192
- /**
193
- * Rejects a pending invoke — the failure counterpart of
194
- * {@link resolveAgentStep}. Delivers `error` as the invoke's
195
- * `xstate.error.actor` event, so the machine takes that invoke's `onError`
196
- * transition and returns the next {@link AgentStep}. With no `onError` in
197
- * scope the returned step's snapshot has `status: 'error'`, exactly as a live
198
- * run's failed invoke does.
199
- *
200
- * A durable host replays a failed call with this: the log says the call
201
- * failed, so the replay rejects the invoke instead of resolving it. Scripted
202
- * playthroughs use it too — see `simulateAgent`'s `script.errors`.
203
- *
204
- * `error` can be any value. An `Error` instance is the usual one, but a plain
205
- * object (`{ code: 'truncated' }`) reaches the `onError` transition as
206
- * `event.error` untouched, so a machine that branches on a failure code is
207
- * testable without constructing a provider's error class.
208
- */
209
- function rejectAgentStep(machine, step, request, error, options) {
210
- const [snapshot, actions] = transitionResult(machine, step.snapshot, request, error, "error");
211
- return createAgentStep(machine, snapshot, actions, require_event_log.getRegisteredAgentExecutionOptions(machine, options));
212
- }
213
- function createAgentStep(machine, snapshot, actions, options) {
214
- applyFinalStateOutput(machine, snapshot);
215
- return {
216
- snapshot,
217
- actions,
218
- requests: getAgentRequests(getPendingInvokes(snapshot), {
219
- ...options,
220
- snapshot
221
- }),
222
- done: snapshot.status === "done"
223
- };
224
- }
225
- function resolveStateValueConfig(config, value) {
226
- if (typeof value === "string") return config.states?.[value];
227
- if (!value || typeof value !== "object") return;
228
- for (const [key, childValue] of Object.entries(value)) {
229
- const childConfig = config.states?.[key];
230
- if (!childConfig) continue;
231
- if (childConfig.type === "final") return childConfig;
232
- const nested = resolveStateValueConfig(childConfig, childValue);
233
- if (nested) return nested;
234
- }
235
- }
236
- function applyFinalStateOutput(logic, snapshot, event) {
237
- const machineSnapshot = snapshot;
238
- if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
239
- const config = logic.config;
240
- if (!config) return;
241
- const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
242
- if (output === void 0) return;
243
- machineSnapshot.output = typeof output === "function" ? output({
244
- context: machineSnapshot.context,
245
- event
246
- }) : output;
247
- }
248
- function isAgentStep(value) {
249
- return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
250
- }
251
- //#endregion
252
- //#region src/verify.ts
253
- /**
254
- * Provider-free verification for agent machines — static lint checks plus
255
- * model-free simulation over the pure step path. Coding agents generate these
256
- * machines; this module lets them close the loop and self-verify WITHOUT any
257
- * API keys or model calls.
258
- *
259
- * - {@link lintAgentMachine} — static structural checks over a built machine
260
- * (works for TS-authored and `setupAgent.fromConfig`-compiled machines).
261
- * - {@link simulateAgent} — a deterministic, scripted playthrough.
262
- * - {@link explorePaths} — enumerates decision/external branches to a bounded
263
- * depth and reports reached states and terminal outcomes.
264
- * - {@link canReach} — a thin wrapper over {@link explorePaths} answering
265
- * "can this state (or snapshot predicate) be reached?" with a witness path.
266
- *
267
- * @module
268
- */
269
- const DECIDE_SRC = "agent.decide";
270
- function normalizeInvokes(invoke) {
271
- if (invoke === void 0 || invoke === null) return [];
272
- return Array.isArray(invoke) ? invoke : [invoke];
273
- }
274
- function buildStateIndex(rootConfig) {
275
- const index = /* @__PURE__ */ new Map();
276
- const walk = (states, parentPath) => {
277
- for (const [name, config] of Object.entries(states ?? {})) {
278
- const path = parentPath ? `${parentPath}.${name}` : name;
279
- const hasChildren = !!config.states && Object.keys(config.states).length > 0;
280
- index.set(path, {
281
- path,
282
- config,
283
- parentPath,
284
- isFinal: config.type === "final",
285
- isParallel: config.type === "parallel",
286
- isCompound: hasChildren && config.type !== "parallel",
287
- invokes: normalizeInvokes(config.invoke)
288
- });
289
- if (hasChildren) walk(config.states, path);
290
- }
291
- };
292
- walk(rootConfig.states, "");
293
- return index;
294
- }
295
- function ancestorChain(node, index) {
296
- const chain = [];
297
- let parent = node.parentPath;
298
- while (parent) {
299
- const parentNode = index.get(parent);
300
- if (!parentNode) break;
301
- chain.push(parentNode);
302
- parent = parentNode.parentPath;
303
- }
304
- return chain;
305
- }
306
- function hasNonEmptyOn(config) {
307
- return !!config.on && Object.keys(config.on).length > 0;
308
- }
309
- function isDecisionInvoke(src, actors) {
310
- if (typeof src === "string") return src === DECIDE_SRC || require_decision.isDecisionLogic(actors[src]);
311
- return require_decision.isDecisionLogic(src);
312
- }
313
- function isAgentLogicNeedingBinding(src) {
314
- return (require_event_log.isTextLogic(src) || require_decision.isDecisionLogic(src)) && !require_event_log.executorBoundLogics.has(src);
315
- }
316
- function safeJsonSchema(schema) {
317
- try {
318
- return require_event_log.getJsonSchemaSync(schema);
319
- } catch {
320
- return;
321
- }
322
- }
323
- function checkDecideWithoutEvents(ctx) {
324
- const out = [];
325
- for (const node of ctx.index.values()) for (const invoke of node.invokes) {
326
- if (!isDecisionInvoke(invoke.src, ctx.actors)) continue;
327
- const selfHandles = hasNonEmptyOn(node.config);
328
- const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
329
- const invokeObserves = invoke.onDone !== void 0;
330
- if (selfHandles || ancestorHandles || invokeObserves) continue;
331
- const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
332
- out.push({
333
- code: "decide-without-events",
334
- severity: "error",
335
- path: node.path,
336
- 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.`
337
- });
338
- }
339
- return out;
340
- }
341
- function literalAllowedEvents(json, path, index) {
342
- let node = json;
343
- for (const key of path.split(".")) node = node?.states?.[key];
344
- let input = normalizeInvokes(node?.invoke)[index]?.input;
345
- if (require_event_log.isRecord(input) && typeof input["@expr"] === "string") try {
346
- input = JSON.parse(input["@expr"]);
347
- } catch {
348
- return;
349
- }
350
- const allowedEvents = require_event_log.isRecord(input) ? input.allowedEvents : void 0;
351
- return typeof allowedEvents === "string" ? [allowedEvents] : Array.isArray(allowedEvents) ? allowedEvents : void 0;
352
- }
353
- function handlesAsHuman(config, eventType) {
354
- const transitions = config.on?.[eventType];
355
- return (Array.isArray(transitions) ? transitions : [transitions]).some((transition) => !!transition && typeof transition === "object" && transition.meta?.actor === "human");
356
- }
357
- function checkDecideAllowsHumanEvent(ctx) {
358
- const out = [];
359
- for (const node of ctx.index.values()) for (const [index, invoke] of node.invokes.entries()) {
360
- if (!isDecisionInvoke(invoke.src, ctx.actors)) continue;
361
- const allowedEvents = literalAllowedEvents(ctx.json, node.path, index);
362
- if (!allowedEvents) continue;
363
- const configs = [
364
- node.config,
365
- ...ancestorChain(node, ctx.index).map((ancestor) => ancestor.config),
366
- ctx.config
367
- ];
368
- for (const type of allowedEvents) {
369
- if (typeof type !== "string" || require_decision.isEventPattern(type) || !configs.some((config) => handlesAsHuman(config, type))) continue;
370
- out.push({
371
- code: "decide-allows-human-event",
372
- severity: "error",
373
- path: node.path,
374
- message: `State '${node.path}' lets 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.`
375
- });
376
- }
377
- }
378
- return out;
379
- }
380
- function checkDirectObjectSrc(ctx) {
381
- const out = [];
382
- for (const node of ctx.index.values()) for (const invoke of node.invokes) {
383
- const src = invoke.src;
384
- if (typeof src === "string" || !src || typeof src !== "object") continue;
385
- if (!isAgentLogicNeedingBinding(src)) continue;
386
- out.push({
387
- code: "direct-object-src",
388
- severity: "warning",
389
- path: node.path,
390
- 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.`
391
- });
392
- }
393
- return out;
394
- }
395
- function handlesActorError(config) {
396
- if (config["onError"] !== void 0) return true;
397
- return Object.keys(config.on ?? {}).some((type) => type === "*" || type.startsWith("xstate.error"));
398
- }
399
- function checkInvokeWithoutOnError(ctx) {
400
- const out = [];
401
- for (const node of ctx.index.values()) for (const invoke of node.invokes) {
402
- if (invoke.onError !== void 0 || handlesActorError(node.config)) continue;
403
- if (handlesActorError(ctx.config) || ancestorChain(node, ctx.index).some((ancestor) => handlesActorError(ancestor.config))) continue;
404
- const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
405
- out.push({
406
- code: "invoke-without-on-error",
407
- severity: "warning",
408
- path: node.path,
409
- 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).`
410
- });
411
- }
412
- return out;
413
- }
414
- const LINT_CHECKS = [
415
- checkDecideWithoutEvents,
416
- checkDecideAllowsHumanEvent,
417
- checkDirectObjectSrc,
418
- checkInvokeWithoutOnError
419
- ];
420
- /**
421
- * Runs static structural checks over a built agent machine and returns the
422
- * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
423
- * TS-authored (`setupAgent(...).createMachine(...)`) and
424
- * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
425
- * plus the schemas/actor sources the library already retains per machine.
426
- *
427
- * No model calls, no API keys — a coding agent that emits an agent machine can
428
- * call this to catch agent-specific mistakes such as undeliverable decisions,
429
- * un-rebindable request sources, and an unhandled transcript event. General
430
- * state-machine lint belongs to XState tooling.
431
- *
432
- * Pass `{ throw: true }` for the one-liner form used in tests and generation
433
- * loops: it returns silently when the machine is clean and throws
434
- * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
435
- * findings, or on warnings too with `{ throw: true, warnings: true }`.
436
- *
437
- * @example
438
- * ```ts
439
- * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
440
- * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
441
- * ```
442
- *
443
- * @example Throwing form
444
- * ```ts
445
- * test('agent machine is structurally sound', () => {
446
- * lintAgentMachine(machine, { throw: true });
447
- * });
448
- * ```
449
- */
450
- function lintAgentMachine(machine, options = {}) {
451
- const config = machine.config ?? {};
452
- const index = buildStateIndex(config);
453
- const registered = require_event_log.getRegisteredAgentExecutionOptions(machine);
454
- let json;
455
- try {
456
- json = (0, xstate.machineToJSON)(machine);
457
- } catch {
458
- json = void 0;
459
- }
460
- const ctx = {
461
- config,
462
- json,
463
- index,
464
- schemas: registered.schemas,
465
- actors: registered.actors ?? machine.sources?.actors ?? {}
466
- };
467
- const disabled = new Set(options.disable ?? []);
468
- const diagnostics = LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
469
- if (options.throw) {
470
- const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
471
- if (failing.length > 0) throw new AgentLintError(machine.id ?? "(machine)", failing);
472
- }
473
- return diagnostics;
474
- }
475
- /**
476
- * Thrown by `lintAgentMachine(machine, { throw: true })` (and its
477
- * {@link assertAgentMachine} alias) when lint finds failing diagnostics.
478
- * `diagnostics` holds the findings; the message lists them one per finding,
479
- * so a test runner's failure output reads like the CLI's lint report.
480
- */
481
- var AgentLintError = class extends require_event_log.AgentError {
482
- diagnostics;
483
- constructor(machineId, diagnostics) {
484
- const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
485
- super("lint-failed", `Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
486
- this.name = "AgentLintError";
487
- this.diagnostics = diagnostics;
488
- }
489
- };
490
- /**
491
- * Asserts a machine passes {@link lintAgentMachine}: returns silently when
492
- * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
493
- * otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
494
- * Fails on error-severity findings; set `warnings: true` to fail on warnings
495
- * too. The one-liner for tests and generation loops:
496
- *
497
- * @example
498
- * ```ts
499
- * test('agent machine is structurally sound', () => {
500
- * assertAgentMachine(machine);
501
- * });
502
- * ```
503
- */
504
- function assertAgentMachine(machine, options = {}) {
505
- lintAgentMachine(machine, {
506
- ...options,
507
- throw: true
508
- });
509
- }
510
- function pendingInvokes(step) {
511
- const out = [];
512
- for (const metadata of getPendingInvokes(step.snapshot)) if (typeof metadata.src === "string") out.push({
513
- id: metadata.id,
514
- src: metadata.src
515
- });
516
- return out;
517
- }
518
- function takeFromQueue(channel, src) {
519
- const queue = channel?.[src];
520
- if (queue && queue.length > 0) return {
521
- found: true,
522
- value: queue.shift()
523
- };
524
- return { found: false };
525
- }
526
- /**
527
- * Deterministically plays a machine through, resolving each request from a
528
- * {@link SimulationScript} instead of a model — no API keys, no model calls.
529
- * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
530
- * the real transition logic. Returns the terminal `status`, final `snapshot`,
531
- * and a `trail` of every step taken.
532
- *
533
- * Decisions run through the live run's own validation/retry core,
534
- * {@link resolveDecision}, with the script standing in for the model: each
535
- * attempt consumes the next queued {@link ChosenEvent} for that src, so an
536
- * unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
537
- * — the next queued decision is tried, exactly as a live run re-asks the
538
- * model. The decision logic's `maxRetries` caps attempts as it would live;
539
- * when retries continue past the end of the queue, the last queued decision
540
- * repeats (a scripted model that insists). The repeat applies only within one
541
- * decision request's retries — each new decision request must have its own
542
- * queued entry, or the dry-script error throws as usual. Exhausting all
543
- * attempts delivers
544
- * the resulting {@link AgentDecisionExhaustedError} to the machine as the
545
- * decision invoke's error (so an `onError` transition observes it, as it
546
- * would live); with no `onError` to catch it, it is thrown.
547
- *
548
- * Throws a descriptive error when the script runs dry mid-request, naming the
549
- * pending request's kind, src, and id so the missing scripted response is
550
- * obvious.
551
- *
552
- * @example
553
- * ```ts
554
- * const { status, snapshot } = simulateAgent(machine, {
555
- * input: { topic: 'state machines' },
556
- * script: {
557
- * decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
558
- * events: [{ type: 'APPROVE' }], // crosses the human gate
559
- * },
560
- * });
561
- * ```
562
- */
563
- async function simulateAgent(machine, options) {
564
- const maxSteps = options.maxSteps ?? 100;
565
- const script = {
566
- text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
567
- decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
568
- invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr]),
569
- errors: mapValues(options.script.errors ?? {}, (arr) => [...arr]),
570
- events: [...options.script.events ?? []]
571
- };
572
- let step = initialAgentStep(machine, options.input);
573
- const trail = [{ state: step.snapshot.value }];
574
- for (let i = 0; i < maxSteps; i++) {
575
- if (step.done) return {
576
- status: "done",
577
- snapshot: step.snapshot,
578
- trail
579
- };
580
- const request = step.requests[0];
581
- if (request) {
582
- if (request.kind === "decision") {
583
- const invokeMeta = findInvokeMetadata(step, request.id);
584
- const src = invokeMeta?.src ?? request.id;
585
- const decisionSrc = src in (script.decisions ?? {}) ? src : request.id in (script.decisions ?? {}) ? request.id : src;
586
- const errorSrc = queueKey(script.errors, src, request.id);
587
- const failure = takeFromQueue(script.errors, errorSrc);
588
- if (failure.found) {
589
- step = rejectScriptedRequest(machine, step, request.id, failure.value, {
590
- kind: "decision",
591
- src: errorSrc,
592
- trail
593
- });
594
- continue;
595
- }
596
- step = await applyScriptedDecision(machine, step, request, decisionSrc, invokeMeta?.logic, script, trail);
597
- continue;
598
- }
599
- const failure = takeFromQueue(script.errors, request.src);
600
- if (failure.found) {
601
- step = rejectScriptedRequest(machine, step, request, failure.value, {
602
- kind: "text",
603
- src: request.src,
604
- trail
605
- });
606
- continue;
607
- }
608
- const taken = takeFromQueue(script.text, request.src);
609
- if (!taken.found) throw scriptDryError("text", request.src, request.id);
610
- step = resolveAgentStep(machine, step, request, asTextResult(taken.value));
611
- trail.push({
612
- state: step.snapshot.value,
613
- resolvedRequest: {
614
- kind: "text",
615
- src: request.src,
616
- id: request.id,
617
- outcome: "output"
618
- }
619
- });
620
- continue;
621
- }
622
- const [invoke] = pendingInvokes(step);
623
- if (invoke) {
624
- const failure = takeFromQueue(script.errors, invoke.src);
625
- if (failure.found) {
626
- step = rejectScriptedRequest(machine, step, invoke.id, failure.value, {
627
- kind: "invoke",
628
- src: invoke.src,
629
- trail
630
- });
631
- continue;
632
- }
633
- const taken = takeFromQueue(script.invokes, invoke.src);
634
- if (!taken.found) throw scriptDryError("invoke", invoke.src, invoke.id);
635
- step = resolveAgentStep(machine, step, invoke.id, taken.value);
636
- trail.push({
637
- state: step.snapshot.value,
638
- resolvedRequest: {
639
- kind: "invoke",
640
- src: invoke.src,
641
- id: invoke.id,
642
- outcome: "output"
643
- }
644
- });
645
- continue;
646
- }
647
- const external = script.events;
648
- if (external.length > 0) {
649
- const event = external.shift();
650
- 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.`);
651
- step = transitionAgentStep(machine, step, event);
652
- trail.push({
653
- state: step.snapshot.value,
654
- appliedEvent: event,
655
- external: true
656
- });
657
- continue;
658
- }
659
- return {
660
- status: "idle",
661
- snapshot: step.snapshot,
662
- trail
663
- };
664
- }
665
- return {
666
- status: "exhausted",
667
- snapshot: step.snapshot,
668
- trail
669
- };
670
- }
671
- function queueKey(channel, src, id) {
672
- return channel && !(src in channel) && id in channel ? id : src;
673
- }
674
- function rejectScriptedRequest(machine, step, request, error, entry) {
675
- const id = typeof request === "string" ? request : request.id;
676
- const next = rejectAgentStep(machine, step, request, error);
677
- if (next.snapshot.status === "error") throw unhandledScriptedError(error, entry.kind, entry.src, id);
678
- entry.trail.push({
679
- state: next.snapshot.value,
680
- resolvedRequest: {
681
- kind: entry.kind,
682
- src: entry.src,
683
- id,
684
- outcome: "error",
685
- error
686
- }
687
- });
688
- return next;
689
- }
690
- function unhandledScriptedError(error, kind, src, id) {
691
- if (error instanceof Error) return error;
692
- 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 });
693
- }
694
- async function applyScriptedDecision(machine, step, request, decisionSrc, invokeLogic, script, trail) {
695
- const dequeued = [];
696
- const decide = async () => {
697
- const taken = takeFromQueue(script.decisions, decisionSrc);
698
- if (taken.found) {
699
- dequeued.push(taken.value);
700
- return { event: taken.value };
701
- }
702
- if (dequeued.length === 0) throw scriptDryError("decision", decisionSrc, request.id, request);
703
- return { event: dequeued[dequeued.length - 1] };
704
- };
705
- const logic = require_decision.isDecisionLogic(invokeLogic) ? invokeLogic : resolveRegisteredDecisionLogic(machine, decisionSrc);
706
- const maxRetries = request.maxRetries ?? logic?.maxRetries;
707
- const can = (event) => step.snapshot.can(event);
708
- const options = require_decision.acceptedDecisionOptions(request, can);
709
- const offered = options ? {
710
- ...request,
711
- options
712
- } : request;
713
- let chosen;
714
- try {
715
- chosen = await require_decision.resolveDecision(offered, { decide }, {
716
- maxRetries,
717
- canTake: can
718
- });
719
- } catch (error) {
720
- if (!(error instanceof require_decision.AgentDecisionExhaustedError)) throw error;
721
- const next = rejectAgentStep(machine, step, request.id, error);
722
- if (next.snapshot.status === "error") throw error;
723
- trail.push({
724
- state: next.snapshot.value,
725
- rejectedEvents: dequeued
726
- });
727
- return next;
728
- }
729
- const next = transitionAgentStep(machine, step, chosen);
730
- const rejected = dequeued.slice(0, -1);
731
- trail.push({
732
- state: next.snapshot.value,
733
- appliedEvent: chosen,
734
- ...rejected.length > 0 ? { rejectedEvents: rejected } : {}
735
- });
736
- return next;
737
- }
738
- function findInvokeMetadata(step, id) {
739
- for (const metadata of getPendingInvokes(step.snapshot)) {
740
- if (metadata.id !== id) continue;
741
- return {
742
- ...typeof metadata.src === "string" ? { src: metadata.src } : {},
743
- logic: metadata.logic ?? (typeof metadata.src === "object" ? metadata.src : void 0)
744
- };
745
- }
746
- }
747
- function resolveRegisteredDecisionLogic(machine, src) {
748
- const candidate = require_event_log.getRegisteredAgentExecutionOptions(machine).actors?.[src] ?? machine.sources?.actors?.[src];
749
- return require_decision.isDecisionLogic(candidate) ? candidate : void 0;
750
- }
751
- function asTextResult(value) {
752
- return {
753
- result: value,
754
- messages: []
755
- };
756
- }
757
- function mapValues(obj, fn) {
758
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
759
- }
760
- function scriptDryError(kind, src, id, request) {
761
- const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
762
- const key = kind === "text" ? `text['${src}']` : kind === "decision" ? `decisions['${src}']` : `invokes['${src}']`;
763
- 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}`);
764
- }
765
- const MAX_ADVANCE_STEPS = 1e3;
766
- const FINITE_PAYLOAD_CAP = 64;
767
- const DEFAULT_MAX_NODES = 1e5;
768
- function finiteDomain(schema) {
769
- if (!require_event_log.isRecord(schema)) return;
770
- if ("const" in schema) return [schema["const"]];
771
- if (Array.isArray(schema["enum"])) return schema["enum"];
772
- const union = schema["anyOf"] ?? schema["oneOf"];
773
- if (Array.isArray(union)) {
774
- const parts = union.map(finiteDomain);
775
- return parts.every((part) => part !== void 0) ? [...new Set(parts.flat())] : void 0;
776
- }
777
- const types = Array.isArray(schema["type"]) ? schema["type"] : [schema["type"]];
778
- if (types.every((type) => type === "boolean" || type === "null")) return types.flatMap((type) => type === "boolean" ? [true, false] : [null]);
779
- }
780
- const OMITTED = Symbol("omitted");
781
- function finitePayloads(jsonSchema) {
782
- const bare = {
783
- payloads: [{}],
784
- complete: false
785
- };
786
- if (!require_event_log.isRecord(jsonSchema) || jsonSchema["type"] !== "object" && !require_event_log.isRecord(jsonSchema["properties"])) return bare;
787
- const properties = require_event_log.isRecord(jsonSchema["properties"]) ? jsonSchema["properties"] : {};
788
- const required = new Set(Array.isArray(jsonSchema["required"]) ? jsonSchema["required"] : []);
789
- if ([...required].some((key) => key !== "type" && !(key in properties))) return bare;
790
- let product = [{}];
791
- let complete = true;
792
- for (const [key, schema] of Object.entries(properties)) {
793
- if (key === "type") continue;
794
- const domain = finiteDomain(schema);
795
- if (!domain || domain.length === 0) {
796
- if (required.has(key)) return bare;
797
- complete = false;
798
- continue;
799
- }
800
- const choices = required.has(key) ? domain : [OMITTED, ...domain];
801
- if (product.length * choices.length > FINITE_PAYLOAD_CAP) return bare;
802
- product = product.flatMap((payload) => choices.map((value) => value === OMITTED ? payload : {
803
- ...payload,
804
- [key]: value
805
- }));
806
- }
807
- return {
808
- payloads: product,
809
- complete
810
- };
811
- }
812
- function mayReadPayload(snapshot, type) {
813
- 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"));
814
- }
815
- function explore(machine, options, stopWhen) {
816
- const maxDepth = options.maxDepth ?? 8;
817
- const maxPaths = options.maxPaths ?? 200;
818
- const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
819
- const errorScript = options.errors ?? {};
820
- const outputScript = options.outputs ?? {};
821
- const eventSchemas = require_event_log.getRegisteredAgentExecutionOptions(machine).schemas?.events ?? machine.schemas?.events ?? {};
822
- const finiteCache = /* @__PURE__ */ new Map();
823
- const schemaPayloads = (type, snapshot) => {
824
- const schema = eventSchemas[type];
825
- let fill = finiteCache.get(type);
826
- if (schema && !fill) {
827
- fill = finitePayloads(safeJsonSchema(schema));
828
- finiteCache.set(type, fill);
829
- }
830
- fill ??= {
831
- payloads: [{}],
832
- complete: !mayReadPayload(snapshot, type)
833
- };
834
- if (!fill.complete && !unexpanded.has(type)) {
835
- unexpanded.add(type);
836
- unexplored.push(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`);
837
- }
838
- return fill.payloads;
839
- };
840
- const variantsOf = (type, snapshot, table, requestOptions) => {
841
- const listed = table[type];
842
- if (listed) return listed.map((payload) => ({
843
- ...payload,
844
- type
845
- }));
846
- if (requestOptions) return requestOptions.filter((option) => option.event.type === type).map((option) => option.event);
847
- return schemaPayloads(type, snapshot).map((payload) => ({
848
- ...payload,
849
- type
850
- }));
851
- };
852
- const settleFor = (id, src, isText) => {
853
- const outputs = outputScript[src] ?? [];
854
- if (src in errorScript || outputs.length > 1) return { fork: {
855
- id,
856
- ...src in errorScript ? { errorKey: src } : {},
857
- outputs,
858
- isText
859
- } };
860
- return outputs.length === 1 ? { output: outputs[0] } : { blocked: true };
861
- };
862
- const reachedStates = /* @__PURE__ */ new Set();
863
- const reachedValues = [];
864
- const terminals = [];
865
- const unexplored = [];
866
- const unexpanded = /* @__PURE__ */ new Set();
867
- let prunedByGuard = 0;
868
- let pathsExplored = 0;
869
- let nodesExpanded = 0;
870
- let hitPathCap = false;
871
- const capped = () => {
872
- if (pathsExplored >= maxPaths || nodesExpanded >= maxNodes) hitPathCap = true;
873
- return hitPathCap;
874
- };
875
- let witness;
876
- const visited = /* @__PURE__ */ new Map();
877
- const recordState = (snapshot) => {
878
- const key = JSON.stringify(snapshot.value);
879
- if (!reachedStates.has(key)) {
880
- reachedStates.add(key);
881
- reachedValues.push(snapshot.value);
882
- }
883
- };
884
- const initial = initialAgentStep(machine, options.input);
885
- recordState(initial.snapshot);
886
- if (stopWhen?.(initial.snapshot)) witness = [];
887
- const advance = (step) => {
888
- let current = step;
889
- for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
890
- if (stopWhen?.(current.snapshot)) return {
891
- step: current,
892
- hit: true
893
- };
894
- if (current.done) return { step: current };
895
- const request = current.requests[0];
896
- if (request && request.kind === "text") {
897
- const settle = settleFor(request.id, request.src, true);
898
- if ("fork" in settle) return {
899
- step: current,
900
- fork: settle.fork
901
- };
902
- if ("blocked" in settle) return {
903
- step: current,
904
- blockedSrc: request.src
905
- };
906
- current = resolveAgentStep(machine, current, request, asTextResult(settle.output));
907
- recordState(current.snapshot);
908
- continue;
909
- }
910
- if (request && request.kind === "decision") {
911
- const src = findInvokeMetadata(current, request.id)?.src;
912
- const errorSrc = src !== void 0 && src in errorScript ? src : request.id in errorScript ? request.id : void 0;
913
- return errorSrc !== void 0 ? {
914
- step: current,
915
- fork: {
916
- id: request.id,
917
- errorKey: errorSrc,
918
- outputs: [],
919
- isDecision: true
920
- }
921
- } : { step: current };
922
- }
923
- const [invoke] = pendingInvokes(current);
924
- if (invoke) {
925
- const settle = settleFor(invoke.id, invoke.src, false);
926
- if ("fork" in settle) return {
927
- step: current,
928
- fork: settle.fork
929
- };
930
- if ("blocked" in settle) return {
931
- step: current,
932
- blockedSrc: invoke.src
933
- };
934
- current = resolveAgentStep(machine, current, invoke.id, settle.output);
935
- recordState(current.snapshot);
936
- continue;
937
- }
938
- return { step: current };
939
- }
940
- return { step: current };
941
- };
942
- function* expand({ step, path, depth }) {
943
- if (witness !== void 0 || capped()) return;
944
- nodesExpanded++;
945
- const { step: settled, blockedSrc, hit, fork } = advance(step);
946
- if (hit) {
947
- witness = path;
948
- return;
949
- }
950
- if (options.dedupeBy) {
951
- const key = options.dedupeBy(settled.snapshot);
952
- const seenAt = visited.get(key);
953
- if (seenAt !== void 0 && seenAt <= depth) return;
954
- visited.set(key, depth);
955
- }
956
- if (fork) {
957
- if (depth >= maxDepth) {
958
- pathsExplored++;
959
- terminals.push({
960
- status: "max-depth",
961
- path,
962
- state: settled.snapshot.value
963
- });
964
- unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
965
- return;
966
- }
967
- if (fork.errorKey !== void 0) {
968
- const failed = rejectAgentStep(machine, settled, fork.id, errorScript[fork.errorKey]);
969
- recordState(failed.snapshot);
970
- yield {
971
- step: failed,
972
- path: [...path, { type: `xstate.error.actor.${fork.id}` }],
973
- depth: depth + 1
974
- };
975
- }
976
- if (!fork.isDecision) {
977
- for (const output of fork.outputs) {
978
- if (witness !== void 0 || capped()) return;
979
- const resolved = resolveAgentStep(machine, settled, fork.id, fork.isText ? asTextResult(output) : output);
980
- recordState(resolved.snapshot);
981
- yield {
982
- step: resolved,
983
- path: [...path, {
984
- type: `xstate.done.actor.${fork.id}`,
985
- output
986
- }],
987
- depth: depth + 1
988
- };
989
- }
990
- return;
991
- }
992
- if (witness !== void 0) return;
993
- }
994
- if (blockedSrc) {
995
- pathsExplored++;
996
- terminals.push({
997
- status: "needs-output",
998
- path,
999
- state: settled.snapshot.value,
1000
- missingSrc: blockedSrc
1001
- });
1002
- unexplored.push(`needs-output: no \`outputs\` entry for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
1003
- return;
1004
- }
1005
- if (settled.done) {
1006
- pathsExplored++;
1007
- terminals.push({
1008
- status: "done",
1009
- path,
1010
- state: settled.snapshot.value
1011
- });
1012
- return;
1013
- }
1014
- if (settled.snapshot.status === "error") {
1015
- pathsExplored++;
1016
- terminals.push({
1017
- status: "error",
1018
- path,
1019
- state: settled.snapshot.value,
1020
- error: settled.snapshot.error
1021
- });
1022
- return;
1023
- }
1024
- const request = settled.requests[0];
1025
- const snapshot = settled.snapshot;
1026
- const table = options.payloads?.(snapshot) ?? {};
1027
- const requestOptions = request?.kind === "decision" ? require_decision.acceptedDecisionOptions(request, () => true) : void 0;
1028
- const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : require_decision.getAcceptedEvents(snapshot).flatMap((descriptor) => {
1029
- if (table[descriptor.type]?.length === 0) {
1030
- unexpanded.add(descriptor.type);
1031
- unexplored.push(`skipped: payloads lists no ${descriptor.type} at path [${path.map((e) => e.type).join(", ")}], so its branches were not explored`);
1032
- }
1033
- return variantsOf(descriptor.type, snapshot, table);
1034
- });
1035
- if (branchEvents.length === 0 && request?.kind !== "decision") {
1036
- pathsExplored++;
1037
- terminals.push({
1038
- status: "idle",
1039
- path,
1040
- state: settled.snapshot.value
1041
- });
1042
- return;
1043
- }
1044
- if (depth >= maxDepth) {
1045
- pathsExplored++;
1046
- terminals.push({
1047
- status: "max-depth",
1048
- path,
1049
- state: settled.snapshot.value
1050
- });
1051
- unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
1052
- return;
1053
- }
1054
- let taken = 0;
1055
- for (const event of branchEvents) {
1056
- if (witness !== void 0 || capped()) return;
1057
- if (!snapshot.can(event)) {
1058
- prunedByGuard++;
1059
- continue;
1060
- }
1061
- taken++;
1062
- const next = transitionAgentStep(machine, settled, event);
1063
- recordState(next.snapshot);
1064
- yield {
1065
- step: next,
1066
- path: [...path, event],
1067
- depth: depth + 1
1068
- };
1069
- }
1070
- if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
1071
- pathsExplored++;
1072
- terminals.push({
1073
- status: "idle",
1074
- path,
1075
- state: settled.snapshot.value
1076
- });
1077
- const refused = [...new Set(branchEvents.map((event) => event.type))];
1078
- for (const type of refused) unexpanded.add(type);
1079
- unexplored.push(`stuck: every offered ${refused.join(", ")} event at path [${path.map((e) => e.type).join(", ")}] was refused by the machine's guards; add a payloads entry it accepts`);
1080
- return;
1081
- }
1082
- if (request?.kind === "decision" && taken === 0) {
1083
- if (witness !== void 0 || capped()) return;
1084
- const exhausted = new require_decision.AgentDecisionExhaustedError([]);
1085
- exhausted.message = `Decision '${request.name ?? request.id}' has no candidate the current snapshot accepts (explored, no model call).`;
1086
- const failed = rejectAgentStep(machine, settled, request.id, exhausted);
1087
- recordState(failed.snapshot);
1088
- yield {
1089
- step: failed,
1090
- path: [...path, { type: `xstate.error.actor.${request.id}` }],
1091
- depth: depth + 1
1092
- };
1093
- }
1094
- }
1095
- const root = {
1096
- step: initial,
1097
- path: [],
1098
- depth: 0
1099
- };
1100
- if (witness === void 0 && stopWhen) {
1101
- const levels = [[root]];
1102
- search: for (let length = 0; length < levels.length; length++) {
1103
- const level = levels[length] ?? [];
1104
- for (let i = 0; i < level.length; i++) {
1105
- const node = level[i];
1106
- level[i] = void 0;
1107
- for (const child of expand(node)) (levels[child.path.length] ??= []).push(child);
1108
- if (witness !== void 0 || hitPathCap) break search;
1109
- }
1110
- levels[length] = [];
1111
- }
1112
- } else if (witness === void 0) {
1113
- const visit = (node) => {
1114
- for (const child of expand(node)) visit(child);
1115
- };
1116
- visit(root);
1117
- }
1118
- return {
1119
- report: {
1120
- reachedStates: reachedValues,
1121
- terminals,
1122
- prunedByGuard,
1123
- unexplored,
1124
- pathsExplored,
1125
- hitPathCap,
1126
- unexpandedEvents: [...unexpanded]
1127
- },
1128
- witness
1129
- };
1130
- }
1131
- /**
1132
- * Enumerates a machine's decision and external-event branches to a bounded
1133
- * depth, model-free, and reports which states are reached and how each path
1134
- * terminates. At each decision request it forks one branch per candidate event
1135
- * (guard-rejected candidates are counted in `prunedByGuard`, not explored); a
1136
- * decision with no takeable candidate exhausts as it does live, taking its
1137
- * `onError` (an `error` terminal without one). At an idle wait it forks per
1138
- * externally-accepted event. Text requests and other
1139
- * invokes resolve from `outputs`, a by-src map of outputs to try (a
1140
- * one-element list is a canned output; several fork one branch each), and a
1141
- * missing src halts that branch with a `needs-output` terminal rather than
1142
- * throwing. A src in
1143
- * `errors` forks an extra branch where that invoke is rejected, so states
1144
- * behind an `onError` are explored too.
1145
- *
1146
- * Events are applied as `{ type }` unless a payload is known: `payloads`
1147
- * forks a type once per listed payload, a decide input's own `payloads`
1148
- * become the branch set, and an event schema whose fields are finite (enums,
1149
- * booleans, consts) expands to their product, each optional field also
1150
- * omitted. A type that could not be fully expanded is listed in
1151
- * `unexpandedEvents`, as is a type with no schema whose transition could read
1152
- * the payload (a function transition, guard, `matches`, or context mapper).
1153
- * `dedupeBy` explores each projected snapshot once, which keeps a large
1154
- * payload table tractable.
1155
- *
1156
- * Combinatorics are bounded by `maxDepth` (default 8), `maxPaths` (default
1157
- * 200), and `maxNodes` (default 100,000), the last two reported via
1158
- * `hitPathCap`.
1159
- *
1160
- * @example
1161
- * ```ts
1162
- * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
1163
- * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
1164
- * ```
1165
- */
1166
- async function explorePaths(machine, options = {}) {
1167
- return explore(machine, options).report;
1168
- }
1169
- /** Thrown when a string reachability target is not a state in the machine. */
1170
- var AgentUnknownStateError = class extends require_event_log.AgentError {
1171
- target;
1172
- constructor(machineId, target) {
1173
- super("unknown-state", `canReach: machine '${machineId}' has no state matching '${target}'.`);
1174
- this.name = "AgentUnknownStateError";
1175
- this.target = target;
1176
- }
1177
- };
1178
- function resolveStateTarget(machine, target) {
1179
- const stack = [machine.root];
1180
- while (stack.length > 0) {
1181
- const node = stack.pop();
1182
- if (node.id === target.replace(/^#/, "") || node.path.join(".") === target) return node.id;
1183
- stack.push(...Object.values(node.states));
1184
- }
1185
- throw new AgentUnknownStateError(machine.id, target);
1186
- }
1187
- /**
1188
- * Answers "can the machine reach this?" by exploring its branches (a thin
1189
- * wrapper over {@link explorePaths}). The target is either a state path string
1190
- * (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
1191
- * form checks any property (a context invariant, a tag, a state+context
1192
- * combination) without reifying a sentinel state for it. Returns
1193
- * `{ reachable: true, witness }` with the event sequence that reaches it, or
1194
- * `{ reachable: false }`. Check `complete` before treating `reachable: false`
1195
- * as a proof: it is false when a cap or `maxDepth` cut exploration short, a
1196
- * branch needed an `outputs` entry it did not have, or an event's payloads were
1197
- * not all tried.
1198
- *
1199
- * @example
1200
- * ```ts
1201
- * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
1202
- * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
1203
- * ```
1204
- *
1205
- * @example Predicate target — a violation property, no sentinel state needed
1206
- * ```ts
1207
- * const violation = await canReach(
1208
- * refundMachine,
1209
- * (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
1210
- * { input: { amount: 5000 } },
1211
- * );
1212
- * // violation.reachable → false is the safety proof
1213
- * ```
1214
- */
1215
- async function canReach(machine, target, options = {}) {
1216
- const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
1217
- const { witness, report } = explore(machine, options, typeof target === "function" ? target : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget));
1218
- if (witness !== void 0) return {
1219
- reachable: true,
1220
- witness,
1221
- complete: true,
1222
- ...resolvedTarget ? { target: resolvedTarget } : {}
1223
- };
1224
- return {
1225
- reachable: false,
1226
- complete: isExplorationComplete(report),
1227
- ...resolvedTarget ? { target: resolvedTarget } : {}
1228
- };
1229
- }
1230
- /**
1231
- * Whether an `explorePaths` report covers every path: no cap cut it short,
1232
- * every payload was expanded, and every branch ended on its own. `done`,
1233
- * `idle`, and `error` end a branch the machine itself ended; any other
1234
- * terminal stopped a branch the search did not explore.
1235
- * @internal
1236
- */
1237
- function isExplorationComplete(report) {
1238
- return !report.hitPathCap && report.unexpandedEvents.length === 0 && report.terminals.every((terminal) => terminal.status === "done" || terminal.status === "idle" || terminal.status === "error");
1239
- }
1240
- //#endregion
1241
- Object.defineProperty(exports, "AgentLintError", {
1242
- enumerable: true,
1243
- get: function() {
1244
- return AgentLintError;
1245
- }
1246
- });
1247
- Object.defineProperty(exports, "AgentUnknownStateError", {
1248
- enumerable: true,
1249
- get: function() {
1250
- return AgentUnknownStateError;
1251
- }
1252
- });
1253
- Object.defineProperty(exports, "assertAgentMachine", {
1254
- enumerable: true,
1255
- get: function() {
1256
- return assertAgentMachine;
1257
- }
1258
- });
1259
- Object.defineProperty(exports, "canReach", {
1260
- enumerable: true,
1261
- get: function() {
1262
- return canReach;
1263
- }
1264
- });
1265
- Object.defineProperty(exports, "explorePaths", {
1266
- enumerable: true,
1267
- get: function() {
1268
- return explorePaths;
1269
- }
1270
- });
1271
- Object.defineProperty(exports, "isExplorationComplete", {
1272
- enumerable: true,
1273
- get: function() {
1274
- return isExplorationComplete;
1275
- }
1276
- });
1277
- Object.defineProperty(exports, "lintAgentMachine", {
1278
- enumerable: true,
1279
- get: function() {
1280
- return lintAgentMachine;
1281
- }
1282
- });
1283
- Object.defineProperty(exports, "simulateAgent", {
1284
- enumerable: true,
1285
- get: function() {
1286
- return simulateAgent;
1287
- }
1288
- });