@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
package/docs/verify.md ADDED
@@ -0,0 +1,487 @@
1
+ ---
2
+ title: Testing and verification
3
+ description: Statically lint, simulate, and explore agent machines without any API keys or model calls.
4
+ ---
5
+
6
+ > **Alpha:** `@statelyai/agent` 2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: [github.com/statelyai/agent](https://github.com/statelyai/agent/issues).
7
+
8
+ This page covers the APIs that check an agent machine before it runs. None of them need an API key or a model call. They all live in `@statelyai/agent/testing`.
9
+
10
+ - `lintAgentMachine` statically catches undeliverable decisions, unrebindable invoke sources, and invokes with no error path. Pass `{ throw: true }` for the throwing form.
11
+ - `assertAgentMachine` is the one-line throwing form for tests and generation loops.
12
+ - `simulateAgent` drives a deterministic scripted playthrough to a known outcome.
13
+ - `explorePaths` and `canReach` enumerate decision branches and check that a target state is reachable.
14
+
15
+ Use these APIs to check that an LLM-generated machine is legal before you run it. See [authoring from scratch](quickstart.md). You can also use them to confirm that a refactor preserved behavior, so a machine converted [from a loop](from-a-loop.md) is safe to ship.
16
+
17
+ > **Note:** Everything on this page runs on `machine.config` and deterministic transition traversal, with no provider, no network, and no keys. These checks work as ordinary unit tests in any test runner, such as vitest or jest, and as CI checks.
18
+
19
+ ## Machine linting
20
+
21
+ <!-- lintAgentMachine, assertAgentMachine, and related options from src/verify.ts -->
22
+
23
+ `lintAgentMachine(machine, options?)` runs static structural checks over a built machine. It accepts machines authored in TypeScript with `setupAgent(...).createMachine(...)` and machines compiled with `setupAgent.fromConfig(...)`. It returns `AgentLintDiagnostic[]`, where each diagnostic is `{ code, severity, path, message }`. The array is empty when the machine is clean.
24
+
25
+ ```ts
26
+ import { lintAgentMachine } from "@statelyai/agent/testing";
27
+ const errors = lintAgentMachine(machine).filter((d) => d.severity === "error");
28
+ if (errors.length) {
29
+ throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
30
+ }
31
+ ```
32
+
33
+ To throw instead of returning findings, call `assertAgentMachine(machine, options?)`
34
+ or pass `{ throw: true }` to `lintAgentMachine`. Both are silent when clean and
35
+ throw `AgentLintError` on error-severity findings, with the findings on
36
+ `.diagnostics`. Add `warnings: true` to fail on warnings too. Pass `disable` to
37
+ skip checks by code.
38
+
39
+ ```ts no-check
40
+ assertAgentMachine(machine, { warnings: true });
41
+ ```
42
+
43
+ | Code | Severity | Fires when |
44
+ | --------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | `decide-without-events` | error | A state invokes `agent.decide` but neither it nor any ancestor handles any event, so the chosen event can never be delivered. |
46
+ | `decide-allows-human-event` | error | A decision's literal `allowedEvents` names an event the state or an ancestor handles through a transition tagged `meta: { actor: "human" }`, so the model is never offered it. See [Events a person sends](decisions.md#events-a-person-sends). |
47
+ | `invoke-without-on-error` | warning | An invoke declares no `onError`, and neither its state nor any ancestor handles an actor error, so a rejected request or actor lands the machine in an error state with no modeled recovery. Add `onError` targeting a `failed` final state or a bounded retry. |
48
+ | `direct-object-src` | warning | An invoke `src` is a direct object or machine value that `runToQuiescence` cannot rebind, so it inherits no host executors. |
49
+
50
+ ## Test assertions
51
+
52
+ Every check is a plain function, so you can assert structural soundness, reachability, and scripted playthroughs directly in vitest or jest.
53
+
54
+ ```ts no-check
55
+ import { assertAgentMachine, canReach, simulateAgent } from "@statelyai/agent/testing";
56
+ import { supportMachine } from "./support-machine";
57
+
58
+ test("machine is structurally sound", () => {
59
+ assertAgentMachine(supportMachine);
60
+ });
61
+
62
+ test("escalation is reachable", async () => {
63
+ const { reachable } = await canReach(supportMachine, "escalated", {
64
+ input: { question: "refund?" },
65
+ });
66
+ expect(reachable).toBe(true);
67
+ });
68
+
69
+ test("happy path settles done", async () => {
70
+ const result = await simulateAgent(supportMachine, {
71
+ input: { question: "refund?" },
72
+ script: { decisions: { "agent.decide": [{ type: "RESOLVE" }] } },
73
+ });
74
+ expect(result.status).toBe("done");
75
+ });
76
+ ```
77
+
78
+ Guards stay in force throughout. `canReach` and `simulateAgent` traverse the same machine transitions as `runToQuiescence`, so a graph path that a guard rejects never counts as reachable. These tests pin the machine's shape as prompts and models change.
79
+
80
+ ## Deterministic executors
81
+
82
+ Executors are plain functions, so a test can supply scripted executors and never touch the network. Bind them onto a logic with `.withExecutor(...)`.
83
+
84
+ ```ts no-check
85
+ const machine = emailDrafter.provide({
86
+ actors: {
87
+ draftEmail: draftEmail.withExecutor(async ({ request }) => {
88
+ return { result: { to: "sam@example.com", subject: "Hello", body: "Hi Sam!" } };
89
+ }),
90
+ },
91
+ });
92
+ ```
93
+
94
+ [examples/email-drafter/agent-logic.ts](https://github.com/statelyai/agent/blob/next/examples/email-drafter/agent-logic.ts) drives a full run this way, with fixed values and no model call.
95
+
96
+ Use deterministic executors when the test should exercise the real `runToQuiescence` path with canned model output. Use [`simulateAgent`](#scripted-playthroughs) when a model-free transition playthrough is enough.
97
+
98
+ ## Scripted playthroughs
99
+
100
+ `simulateAgent(machine, { input, script, maxSteps? })` runs a deterministic, model-free transition playthrough. The `script` supplies responses as FIFO queues, so runs are reproducible.
101
+
102
+ This script keys by invoke **src**, not by request name. Executors that run the real `runToQuiescence` path route by request name instead. See [Testing without a provider](evals.md#testing-without-a-provider).
103
+
104
+ - `decisions` holds the `ChosenEvent` to apply per decision, keyed by decision src, usually `agent.decide`.
105
+ - `text` holds output values for text requests, keyed by request src.
106
+ - `invokes` holds answers for scripted invokes, keyed by invoke src.
107
+ - `errors` holds failure values that reject a request instead of resolving it, keyed by the same srcs the other channels use.
108
+
109
+ A decide input with `payloads` is a closed choice. A scripted decision that matches none of the options the snapshot accepts is rejected and retried, as in a live run.
110
+
111
+ Pending work is read off the snapshot's live invoked actors, not off the last transition. A state that invokes several actors at once keeps every one of them pending until it settles, including when an invoke's `onDone` targets nothing. `simulateAgent` settles one invoke per step, in invoke-id order, and keeps going until none are left, so an `always` join that waits on all of them fires.
112
+
113
+ ```ts
114
+ import { simulateAgent } from "@statelyai/agent/testing";
115
+ const { status, snapshot, trail } = await simulateAgent(machine, {
116
+ input: { questionsRemaining: 20 },
117
+ script: {
118
+ decisions: { "agent.decide": [{ type: "GUESS", guess: "a cat" }] },
119
+ events: [{ type: "GUESS_RIGHT" }, { type: "PLAY_AGAIN_NO" }],
120
+ text: {
121
+ classifyGuessFeedback: [{ correct: true, reasoning: "matched" }],
122
+ classifyPlayAgain: [{ playAgain: false, reasoning: "stop" }],
123
+ },
124
+ },
125
+ });
126
+ // status: 'done' | 'idle' | 'exhausted'
127
+ ```
128
+
129
+ `simulateAgent` returns `{ status, snapshot, trail }`. The status is one of three values:
130
+
131
+ - `'done'`: the machine reached a final state.
132
+ - `'idle'`: the machine came to rest waiting on an external event that the script does not supply.
133
+ - `'exhausted'`: the playthrough hit the `maxSteps` bound, which defaults to 100, before reaching either of the above. Raise `maxSteps` or shorten the script.
134
+
135
+ For a `'done'` run, the output is on `snapshot.output`. The snapshot is typed as the generic `AnyMachineSnapshot`, so the output needs a cast to your output type.
136
+
137
+ ```ts
138
+ if (result.status === "done") {
139
+ const output = result.snapshot.output as { correct: boolean };
140
+ }
141
+ ```
142
+
143
+ > **Note:** When a script queue runs dry mid-request, `simulateAgent` throws a descriptive error naming the pending request's kind, src, and id.
144
+
145
+ ### Scripted failures
146
+
147
+ A state behind an invoke's `onError` is unreachable through outputs alone. Script the failure instead. An `errors[src]` entry is consumed before that src's output queue, so the first call fails and later calls fall through to `text`, `invokes`, or `decisions` as usual.
148
+
149
+ ```ts
150
+ const result = await simulateAgent(machine, {
151
+ script: {
152
+ errors: { parse: [{ code: "truncated" }] },
153
+ text: { parse: [{ total: 42 }] }, // still queued: the error was taken first
154
+ },
155
+ });
156
+ // result.snapshot.value → the target of the `parse` invoke's onError
157
+ ```
158
+
159
+ A failure value is any value. An `Error` is the usual one. A plain object reaches the `onError` transition as `event.error` untouched, so a machine that branches on `event.error.code` is testable without constructing a provider's error class.
160
+
161
+ An entry keyed by a decision src, usually `agent.decide`, stands in for retry exhaustion: the decision invoke is rejected, and its `onError` observes the failure the way it observes a real `AgentDecisionExhaustedError`.
162
+
163
+ A rejection that reaches no `onError` errors the machine, as it does in a live run, and `simulateAgent` throws. It throws the scripted value itself when that value is an `Error`, and otherwise a descriptive error carrying the value on `cause`.
164
+
165
+ Each rejection is on the trail. Every `resolvedRequest` entry carries an `outcome` of `'output'` or `'error'`, and a rejected one also carries the failure value on `error`.
166
+
167
+ ```ts
168
+ const [, settled] = result.trail;
169
+ settled?.resolvedRequest; // { kind: 'text', src: 'parse', id: 'parse', outcome: 'error', error: { code: 'truncated' } }
170
+ ```
171
+
172
+ ## Branch exploration
173
+
174
+ `explorePaths(machine, { input, maxDepth?, maxPaths?, maxNodes?, budget?, outputs?, errors?, payloads?, dedupeBy?, interleave?, children?, timers?, usage? })` enumerates decision and external-event branches without a model, and reports coverage.
175
+
176
+ - At each decision, it forks one branch per candidate event. Guard-rejected candidates count in `prunedByGuard` and are not explored.
177
+ - A decision with no candidate the snapshot takes, because its guards refuse every one or the closed choice offers nothing, exhausts as it does in a live run. That branch records `{ type: 'xstate.error.actor', actorId }` and takes the invoke's `onError`. With no `onError`, it ends in an `error` terminal.
178
+ - At an idle wait, it forks one branch per externally accepted event and per armed timer. See [Timers](#timers).
179
+ - `outputs` is a map of output lists, keyed by src: a text request's src or any other invoked actor's src. A one-element list is a canned output, reused every time that src is reached. A text request resolves with it as its `result`. A longer list forks one branch per output. See [Payloads and invoke outputs](#payloads-and-invoke-outputs).
180
+ - A src with one canned output resolves without a fork, so it does not appear in the path.
181
+ - Each `done` terminal carries the machine's `output`, so one report lists every output the search reached.
182
+ - A src with no `outputs` entry halts that branch with a `needs-output` terminal instead of throwing. The terminal's `missingSrc` names it.
183
+ - `errors` is a map of canned failures per src. A src listed there forks an extra branch where that invoke is rejected, so states behind an `onError` are explored. A decision keys on its src, usually `agent.decide`, or on its invoke id; its success branch stays the per-candidate-event fork, so the failure is explored in addition to the candidates. The failure and the candidates are sibling branches: each spends one level of `maxDepth`.
184
+ - An `errors` array forks one failing branch per element, each recording `{ type: 'xstate.error.actor', actorId, error }`. `[]` is no entry. Any other value is one failure, recorded without `error`. Wrap a single array-valued failure: `[[...]]`.
185
+ - A rejection that reaches no `onError` errors the machine, and that path ends in an `error` terminal carrying the failure value on `error`.
186
+ - Every invoke a state is still waiting on counts as work, concurrent ones included. They are settled one per branch, in invoke-id order, and a src in `errors` forks per invoke.
187
+
188
+ <!-- viz: branch exploration tree for the refund machine: deciding -> AUTO_APPROVE (pruned by guard) / NEEDS_REVIEW -> awaitingHuman -> refunded, denied -->
189
+
190
+ ```ts
191
+ import { explorePaths } from "@statelyai/agent/testing";
192
+ const report = await explorePaths(refundMachine, {
193
+ input: { request: "Refund my duplicate charge", amount: 5000 },
194
+ });
195
+ // report.terminals → both 'refunded' and 'denied'
196
+ // report.prunedByGuard → 1 (AUTO_APPROVE guarded off for amount > 100)
197
+ // report.reachedStates → ['deciding', 'awaitingHuman', 'refunded', 'denied']
198
+ ```
199
+
200
+ Exploration is bounded by three limits per search, plus a [budget](#budgets) for the whole call:
201
+
202
+ - `maxDepth`: branch points along any path. Default 8.
203
+ - `maxPaths`: terminals in the report. Default 200.
204
+ - `maxNodes`: branch points expanded in total. Default 100,000. It bounds work and memory on a loopy machine, which expands many nodes per terminal.
205
+
206
+ `report.hitPathCap` is true when `maxPaths` or `maxNodes` cut exploration short. `report.partial` is true when any cap or the budget did, and `report.complete` is true only when the report covers every path.
207
+
208
+ A src in `errors` is a branch point, and counts against `maxDepth` like a decision does. When the src has an output too, both branches are explored. When it has only an error, only the failing branch is. The failing branch records `{ type: 'xstate.error.actor', actorId }` in the path, where `actorId` is the invoke's id, and the output branch records `{ type: 'xstate.done.actor', actorId, output }`.
209
+
210
+ - For a plain invoke, `output` is the canned value: what the machine's `onDone` receives.
211
+ - For a text request, `output` is the canned value as the parsed `result`. The machine receives `{ result, messages }`.
212
+ - For a [`textOutput`](#payloads-and-invoke-outputs) envelope, `output` is its `result`.
213
+
214
+ ```ts
215
+ const report = await explorePaths(machine, {
216
+ outputs: { parse: [{ total: 42 }] },
217
+ errors: { parse: new Error("truncated response") },
218
+ });
219
+ // report.terminals → one path per branch: the parsed state and the onError state
220
+ ```
221
+
222
+ ### Payloads and invoke outputs
223
+
224
+ By default, events are applied as `{ type }`. A guard that reads the payload, such as `event.amount <= 100`, rejects every such event, so its target is never explored. Supply payloads to explore it.
225
+
226
+ - `payloads` is a function of the snapshot at each branch point. It returns payloads per event type. A type with an entry forks once per payload as `{ ...payload, type }`, at decisions and idle waits alike.
227
+ - Guard-rejected variants count in `prunedByGuard`.
228
+ - A decide input's own `payloads` become that decision's branch set. An explorer `payloads` entry for the same type overrides them.
229
+ - A type with no entry is filled from its event schema. Each field that is an `enum`, `const`, `boolean`, `null`, or a union of those contributes its values, and an optional one also contributes the omitted case. Exploration forks over their product, up to 64 combinations. The schema is the agent machine's, or a plain XState machine's own `schemas.events`, and must expose JSON Schema through Standard JSON Schema, as Zod 4 does.
230
+ - A type the fill cannot enumerate is listed in `report.unexpandedEvents`: a required field with no finite domain, a product over 64, or a schema with no JSON Schema is applied as `{ type }`, and an optional field with no finite domain is left out. Add a `payloads` entry for each listed type. A type with no schema at all stays `{ type }`. It is listed too when a transition for it in the active states could read the payload: a function transition, a guard, a `matches` pattern, or a `context` mapper. An object transition with none of these cannot, so the type is not listed.
231
+ - A wait where the machine refuses every offered event is recorded as an `idle` terminal, and its event types are listed in `unexpandedEvents`. The payload table offered nothing the machine accepts there, so the search is not a proof until it does.
232
+ - An explorer `payloads` entry of `[]` for a type the wait accepts skips that type, which also lists it in `unexpandedEvents`. A decide input's `[]` is different: it withholds the type at run time too, so exploration matches the run.
233
+ - `outputs` lists every output to try per src. An empty list is a src that never settles, such as a callback bridge: its invoke stays pending and only events move the machine on. Two or more outputs fork one branch each, and an `errors` entry for the same src adds the failing branch. Each forked branch records `{ type: 'xstate.done.actor', actorId, output }` in the path.
234
+ - A src is a text request when the logic the machine runs is a text request, as in `runAgent`. A `setupAgent({ requests })` src replaced by `.provide({ actors })` with a plain actor resolves with its bare canned value.
235
+ - A text request's canned value is its `result`, with `messages: []`. Wrap it in `textOutput(result, { messages })` from `@statelyai/agent/testing` when the machine reads `output.messages`.
236
+ - `dedupeBy` projects a settled snapshot to a key. Each key is explored once, or again when reached at a shallower depth. The key must include every field a guard, choice, or `onDone` reads, or the search misses paths. Include `snapshot.timers` when a delayed `enq.raise` outlives the state that scheduled it.
237
+ - Under `dedupeBy`, `terminals` are representative paths, not every path: a revisited key is not explored again, so the paths below it appear once.
238
+
239
+ ```ts
240
+ const amounts = [0, 1, 100, 100.01, 500];
241
+ const violation = await canReach(refundMachine, "illegallyIssued", {
242
+ payloads: () => ({ ISSUE: amounts.map((amount) => ({ amount })) }),
243
+ outputs: { lookupOrder: [{ found: true }, { found: false }] },
244
+ errors: { lookupOrder: new Error("down") },
245
+ dedupeBy: (snapshot) => JSON.stringify([snapshot.value, snapshot.context]),
246
+ });
247
+ // violation.reachable → false across every amount and lookup outcome
248
+ // violation.complete → true, so the false is a proof, not a cut-off search
249
+ ```
250
+
251
+ ```ts no-check
252
+ import { explorePaths, textOutput } from "@statelyai/agent/testing";
253
+ const report = await explorePaths(chatMachine, {
254
+ outputs: { reply: [textOutput("hi", { messages: [{ role: "assistant", content: "hi" }] })] },
255
+ });
256
+ // the reply invoke resolves with { result: 'hi', messages: [...] }
257
+ ```
258
+
259
+ Pick boundary values for numeric payloads: each guard threshold on both sides. Values between two boundaries take the same branch as one of them.
260
+
261
+ `report.vacuous` lists event types offered only as the bare `{ type }` at a snapshot where a transition for them may read the payload: no `payloads` entry, no decision option, and no schema variant beyond `{ type }`.
262
+
263
+ - Covers a type with no schema, or a schema the fill cannot enumerate (a required free-form field, a product over 64, an object of only optional free-form fields).
264
+ - Not listed: a partial fill with real variants, such as finite fields plus an optional free-form one. That type is only in `unexpandedEvents`.
265
+ - Also lists `@agent.usage` when a text request settled while a usage transition was active and `usage` had no entry for its src. See [Usage events](#usage-events).
266
+ - Otherwise a subset of `unexpandedEvents`. Data only: completeness is unchanged.
267
+
268
+ ### Interleaved events
269
+
270
+ By default, external events fork only at idle waits. A host event that arrives while an invoke is still running is never explored. `interleave: "pending"` explores it.
271
+
272
+ | `interleave` | External events fork at |
273
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
274
+ | `"idle"` (default) | Idle waits. |
275
+ | `"pending"` | Idle waits, plus every point an invoke is outstanding: before a text or scripted invoke resolves, at an output or error fork, at a `needs-output` block, and at a decision. |
276
+
277
+ - Each event the active states (or ancestors) accept forks once per payload variant, the same variants as an idle wait. A decision races only the events it does not offer as candidates.
278
+ - Each race branch spends one level of `maxDepth`. Resolving a single canned output does not.
279
+ - `payloads`, `dedupeBy`, and guard pruning apply as at idle waits.
280
+ - A state that accepts no external event resolves straight through, as before.
281
+
282
+ ```ts no-check
283
+ const report = await explorePaths(lookupMachine, {
284
+ outputs: { lookup: [{ found: true }] },
285
+ interleave: "pending",
286
+ });
287
+ // report.terminals → 'found' (no race), and 'cancelled' via [{ type: 'CANCEL' }]
288
+ ```
289
+
290
+ ### Timers
291
+
292
+ An armed timer is an event that may arrive. The search reads `snapshot.timers`: `after` delays, state and invoke `timeout`s, and delayed `enq.raise` events.
293
+
294
+ - Each armed timer whose event the active states take forks a branch, where host events fork: at idle waits, and while work is pending under `interleave: "pending"`.
295
+ - Timers fire in any order, regardless of their delays. A witness may fire a long timer before a short one.
296
+ - A fired timer records its event in the path, such as `{ type: 'xstate.after', delay: 1000, stateId: 'm.waiting' }`, and is disarmed, as in a run.
297
+ - An explored or coupled child's timers fire in the child's own search.
298
+ - `timers: "ignore"` never fires a timer. A wait with an armed timer adds a `timers:` note to `unexplored` and lists the timer's event type in `unexpandedEvents`, so the report is not complete.
299
+
300
+ ```ts no-check
301
+ const result = await canReach(waitingMachine, "timedOut");
302
+ // result.witness → [{ type: 'xstate.after', delay: 1000, stateId: 'm.waiting' }]
303
+ ```
304
+
305
+ ### Usage events
306
+
307
+ `usage` lists usage values per text-request src, so a budget guard on `@agent.usage` can be proved.
308
+
309
+ - When a root text request with an entry settles and the active states take `@agent.usage`, the search delivers the usage event to the root immediately before the request's completion, as a run does.
310
+ - The event is `{ type: '@agent.usage', kind: 'text', id, src, model, name?, usage }`, the run's shape without `budget`.
311
+ - Each listed value forks one branch, recorded in the path before `xstate.done.actor`.
312
+ - One value with one canned output is no fork: the output resolves straight through, but the usage event is still recorded in the path.
313
+ - A usage transition that leaves the invoking state cancels the request: its completion is not recorded.
314
+ - A settling request with no `usage` entry while a usage transition is active lists `@agent.usage` in `vacuous`. Completeness is unchanged.
315
+ - Requests inside child machines and decisions deliver no usage.
316
+
317
+ ```ts no-check
318
+ const overBudget = await canReach(researchMachine, "outOfBudget", {
319
+ outputs: { summarize: ["notes"] },
320
+ usage: { summarize: [{ totalTokens: 10 }, { totalTokens: 5000 }] },
321
+ });
322
+ // overBudget.witness → [{ type: '@agent.usage', ..., usage: { totalTokens: 5000 } }]
323
+ ```
324
+
325
+ ### Child machines
326
+
327
+ By default, a child machine is a src like any other: with no `outputs` entry, its branch ends `needs-output`. `children: "explore"` explores the child instead. It covers invoked children and children spawned with `enq.spawn(actors.x, { id, input })`.
328
+
329
+ - Applies when the src has no `outputs` or `errors` entry and its logic is a state machine.
330
+ - The child is explored on its own, from its invoke or spawn input, with the same options and caps, to at most 4 nested levels.
331
+ - Events reach the child only as `childEvents` lists them: `{ [src]: eventTypes }`, the types the parent forwards (`sendTo`/`forwardTo`) or the host sends the child. Default none. A child wait that accepts an unlisted type makes the child search incomplete, never a reachable parent path.
332
+ - Each distinct `output` of the child's `done` terminals forks the parent as an output. One output resolves straight through.
333
+ - Each distinct failure of the child's `error` terminals forks a failing branch, recorded with `error`.
334
+ - Each distinct event the child sends its parent (`sendTo(parent, …)`) on any explored path forks the parent receiving it, recorded as the event itself.
335
+ - A child that can end `idle` adds an `idle` terminal to the parent: the parent can wait there forever.
336
+ - Bounded:
337
+ - Child idle waits are not parent fork points. The child is explored to its finals, and its distinct outputs fork the parent.
338
+ - N children are explored independently, not as a product of their states. While an explored child is pending, it and every other pending invoke or text request settle in any order; one with no `outputs` entry adds a `needs-output` terminal, and a pending decision's choices branch from the same point. Other combinations are not enumerated beyond `interleave`.
339
+ - A child's events and outputs are not correlated: each event reaches the parent at most once per path, in any order, before or without the others, and before any of the child's outputs. This over-approximates the child, so a witness may not be a live path. A child that sends the same event twice is covered once. For witnesses that are live runs, use `children: "coupled"`.
340
+ - An incomplete child search, such as one with its own `needs-output` or `max-depth`, also ends the parent branch `needs-output` for that src, so the parent report is not complete. The child's `unexpandedEvents` and `vacuous` join the parent's.
341
+
342
+ ```ts no-check
343
+ const report = await explorePaths(parentMachine, {
344
+ children: "explore",
345
+ childEvents: { approval: ["YES", "NO"] }, // the parent forwards both
346
+ });
347
+ // report.terminals → one branch per distinct child output, e.g.
348
+ // [{ type: 'xstate.done.actor', actorId: 'approval', output: { ok: true } }]
349
+ ```
350
+
351
+ ### Coupled child machines
352
+
353
+ `children: "coupled"` steps each child machine inside the parent's search, one move at a time. A witness is then a run the parent and its children can make together. Use it for child machines you wrote, such as one machine per tool call in a batch.
354
+
355
+ - The same children qualify as for `"explore"`: invoked or spawned state machines with no `outputs` or `errors` entry.
356
+ - A child's events reach the parent in the order the child sends them on its own path. Its output follows them.
357
+ - An event the parent sends a child with `sendTo`/`forwardTo` is applied to that child's state at once, in order. It does not need a `childEvents` entry.
358
+ - `childEvents` lists only the types the host sends the child directly. Default none.
359
+ - A child's pending work races the events that can reach it, as with `interleave: "pending"`.
360
+ - The parent's host events arrive at its idle waits, including while every child waits on the host. While a child or the parent has work pending, they race it only with `interleave: "pending"`.
361
+ - What a child's move sends its own children, and their replies, happen in the same move. A child's send to a sibling is delivered to that sibling, entry sends included. A child's sends reach their targets in the order it made them, each run to quiescence before the next, as a live run does. A send to an actor the search does not model lists the event type in `unexpandedEvents`, so the report is not complete.
362
+ - Child moves count against `maxDepth` like the parent's own branches. On a path they carry `actor` with the child's id (a grandchild's as `child.grandchild`): the host events it received, its choices, its settled work. The events it sends the parent appear as the parent receives them.
363
+ - With `dedupeBy`, each child's state joins the key. Without it, every interleaving is explored in full.
364
+ - A child that stops on `needs-output` or `max-depth` ends the parent branch the same way, so the parent report is not complete.
365
+
366
+ Pass `hostEvents` when some types the parent accepts come only from its children, such as a child's status events. The search then offers only the listed types at the parent's waits.
367
+
368
+ ```ts no-check
369
+ const result = await canReach(batchMachine, executedWhileAwaiting, {
370
+ input: { calls: [read, write] },
371
+ children: "coupled",
372
+ childEvents: { call: [] }, // every event a call receives comes through the batch
373
+ hostEvents: ["APPROVE", "REJECT", "CANCEL_ALL"], // CALL_READY comes only from calls
374
+ outputs: { policy: ["allow", "ask"], execute: ["ok"] },
375
+ dedupeBy: (snapshot) => JSON.stringify([snapshot.value, snapshot.context]),
376
+ });
377
+ // → { reachable: false, complete: true }: no call runs while another awaits a person
378
+ ```
379
+
380
+ `"explore"` stays the over-approximation: it sends a child's events in any order and does not correlate them with its outputs. A witness there may not be a live run. Prefer it only when you do not want the proof to depend on the child's own logic.
381
+
382
+ ### Budgets
383
+
384
+ `maxPaths` and `maxNodes` apply to each search on its own. With `children: "explore"`, every explored child is a search of its own with the same caps, so a parent with two loopy children can expand far more than `maxNodes`. `budget` bounds the whole call.
385
+
386
+ - `budget.nodes`: branch points expanded in total, by the top-level search and every child search it triggers. A cached child outcome counts once, when it is computed. Default 250,000, so a search with loopy children stops instead of growing without bound. Raise it explicitly for a bigger machine.
387
+ - `budget.ms`: wall-clock milliseconds from the start of the call. It is checked at each branch point, in child searches too. A slow `payloads` or guard call is not interrupted. No default.
388
+ - `budget.childCache`: explored-child outcomes kept for reuse, keyed by logic, src, and input. The least recently used one is evicted first. An evicted child is explored again when reached, and counts against `budget.nodes` again. Default 64.
389
+
390
+ When a budget runs out, the search stops and returns what it has:
391
+
392
+ - `report.partial` is true and `report.complete` is false.
393
+ - `report.unexplored` has one note, `budget-exhausted: nodes` or `budget-exhausted: ms`, with the nodes expanded and the milliseconds spent so far.
394
+ - `canReach` returns `reachable: true` with its witness if it found one first. Otherwise it returns `{ reachable: false, complete: false }` with the budget note in `unexplored`, which proves nothing: the target may be reachable on a branch the search did not reach.
395
+
396
+ ```ts no-check
397
+ const report = await explorePaths(parentMachine, {
398
+ children: "explore",
399
+ budget: { nodes: 50_000, ms: 10_000 },
400
+ });
401
+ // report.partial → true when the budget ran out
402
+ // report.unexplored → [..., 'budget-exhausted: nodes (50000 nodes expanded in 812 ms, child searches included)']
403
+ ```
404
+
405
+ Set `budget.ms` under the test runner's timeout, so a long search fails its assertion instead of the worker.
406
+
407
+ ## Reachability checks
408
+
409
+ <!-- canReach contract from src/verify.ts -->
410
+
411
+ `canReach(machine, target, opts)` wraps `explorePaths` to answer whether a target is reachable, with a witness path when it is. The target (`CanReachTarget`) is one of:
412
+
413
+ - A state path or state-node ID.
414
+ - A snapshot predicate, `(snapshot) => boolean`, for a property no single state names: a context invariant, a tag, a state plus context.
415
+
416
+ ```ts no-check
417
+ const violation = await canReach(
418
+ refundMachine,
419
+ (snapshot) => snapshot.matches("issued") && !snapshot.context.approved,
420
+ { input: { amount: 5000 } },
421
+ );
422
+ // violation.reachable → false with complete: true is the safety proof
423
+ ```
424
+
425
+ A state the machine only passes through within one step counts as reached: one left at once by an `always` transition, or a `choice` state. `canReach` returns the path that transits it, and `explorePaths` lists it in `reachedStates`.
426
+
427
+ `reachable: false` proves unreachability only when `complete` is true. `complete` is false when the search left a branch it could not rule out:
428
+
429
+ - `maxPaths`, `maxNodes`, or the `budget` cut the search short.
430
+ - A path reached `maxDepth`.
431
+ - A branch stopped on a `needs-output` terminal, with no `outputs` entry for its src, or an explored child machine whose own search was incomplete.
432
+ - An event type was not expanded to all its payload variants, as `explorePaths` lists in `unexpandedEvents`.
433
+
434
+ When `complete` is false, `unexplored` lists why, in the wording of the `explorePaths` report's `unexplored` notes, such as `needs-output: no \`outputs\` entry for src 'resume' at path []`. A cap adds a `path-cap` note.
435
+
436
+ Raise the caps, add `dedupeBy`, supply the missing outputs, or add `payloads` entries until it is true.
437
+
438
+ A long-lived machine that never finishes, such as a chat loop, ends every path at `maxDepth`, so `complete` is never true. Its proofs are bounded:
439
+
440
+ - `reachable: false` whose only `unexplored` notes are `max-depth` notes means no path of up to `maxDepth` branch points reaches the target.
441
+ - Any other note, such as `needs-output` or `unexpanded`, is a gap within that bound too.
442
+ - Raise `maxDepth` to extend the bound. `dedupeBy` keeps a deep bound tractable.
443
+
444
+ ```ts
445
+ import { canReach } from "@statelyai/agent/testing";
446
+ const { reachable, witness } = await canReach(refundMachine, "denied", {
447
+ input: { request: "x", amount: 5000 },
448
+ });
449
+ // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
450
+ ```
451
+
452
+ `witness` is the sequence of chosen and applied events that reaches the state, which is the proof that it is reachable. It is absent when `reachable` is `false`.
453
+
454
+ - The witness is a shortest one: no path within `maxDepth` reaches the target in fewer events. A recorded `xstate.error.actor` or `xstate.done.actor` entry counts as one event.
455
+ - `canReach` searches breadth first to find it, so a retry loop never pads the witness. `explorePaths` stays depth first, and its terminal order is unchanged.
456
+
457
+ `canReach` forwards `errors`, so a state that only a failure reaches is checkable the same way.
458
+
459
+ ```ts
460
+ const failure = await canReach(machine, "failed", {
461
+ errors: { parse: new Error("truncated response") },
462
+ });
463
+ // failure.reachable → true; failure.witness → [{ type: 'xstate.error.actor', actorId: 'parse' }]
464
+ ```
465
+
466
+ ## CI checks
467
+
468
+ Everything on this page runs without an API key, so a small script is enough for CI or a generation loop.
469
+
470
+ ```ts no-check
471
+ // check.ts (run with: npx tsx check.ts)
472
+ import { assertAgentMachine } from "@statelyai/agent/testing";
473
+ import { machine } from "./machine";
474
+
475
+ assertAgentMachine(machine); // throws AgentLintError on error-severity findings
476
+ ```
477
+
478
+ For machines authored as data, validate the config with `validateAgentConfig(config)` from `@statelyai/agent/validate` first, then compile it and lint the machine: `assertAgentMachine(setupAgent.fromConfig(config, { compileSchema }).machine)`. See [Machines as data](machines-as-data.md). Every check applies, including reachability. The lowering keeps the config's transition targets, so `unreachable-state` reads the real graph even where the JSON layer folds a target into a resolver function. `verifyAgentConfig` runs validation, lowering, lint, and exploration in one call. See [Generating machines with an LLM](generate-machines.md).
479
+
480
+ ## Related
481
+
482
+ - [Debugging](debugging.md): scripted reproduction and the diagnostic codes in context.
483
+ - [Evals](evals.md): scoring runs on output, trajectory, and budget.
484
+ - [Quickstart](quickstart.md#define-and-run-one-artifact): a plain-function executor for `runToQuiescence`.
485
+ - [Machines as data](machines-as-data.md): verifying a machine lowered from a config.
486
+ - [Migrating from a hand-rolled loop](from-a-loop.md): pinning behavior across a refactor.
487
+ - [examples/verification](https://github.com/statelyai/agent/blob/next/examples/verification/index.ts): every API on this page run over one refund-approval machine, with no API key, including `canReach` proving that an over-limit payout without human approval is unreachable.
@@ -0,0 +1,161 @@
1
+ ---
2
+ title: Use in an XState 4 or 5 app
3
+ description: Isolate @statelyai/agent behind a workspace package so an app on XState 4 or 5 can call an agent without upgrading.
4
+ ---
5
+
6
+ > **Alpha:** `@statelyai/agent` 2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: [github.com/statelyai/agent](https://github.com/statelyai/agent/issues).
7
+
8
+ <!-- versions from package.json version and peerDependencies.xstate -->
9
+
10
+ `@statelyai/agent` peers on exactly `xstate@6.0.0-beta.0`. An app already using XState 4 or 5 for its own machines cannot install both versions into one `node_modules` tree and have each resolve the one it needs. This page isolates the agent in its own workspace package so the app keeps its XState version and never imports XState 6.
11
+
12
+ The same page applies to an app with no XState at all that cannot take a prerelease dependency in its main tree.
13
+
14
+ ## The constraints
15
+
16
+ - **XState versions do not mix in one package.** `@statelyai/agent` builds machines with XState 6's `setup` API. Handing an XState 6 machine to an XState 4 or 5 `interpret`/`createActor` does not work, and neither does the reverse.
17
+ - **`overrides` and `resolutions` are not the fix.** A `pnpm.overrides` or a yarn `resolutions` entry forces one version for every consumer, which is the problem restated. Forcing XState 5 breaks the agent; forcing XState 6 breaks the app's own machines.
18
+ - **Zod must be 4, or 3.24 and later.** Schemas reach the library through [Standard Schema](https://standardschema.dev), which zod implements from 3.24. Zod 3.23 and earlier expose no `~standard` property and are rejected. Valibot, ArkType, and hand-written validators work on the same terms.
19
+
20
+ ## The recipe
21
+
22
+ Put the agent in a workspace package that owns its own dependencies, and give the app one plain async function to call. The machine never crosses the package boundary; only JSON-safe input and output do.
23
+
24
+ ### The package
25
+
26
+ ```json
27
+ // packages/agent/package.json
28
+ {
29
+ "name": "@acme/agent",
30
+ "private": true,
31
+ "type": "module",
32
+ "exports": { ".": "./src/index.ts" },
33
+ "dependencies": {
34
+ "@statelyai/agent": "2.0.0-alpha.29",
35
+ "@ai-sdk/openai": "^4.0.0",
36
+ "ai": "^7.0.128",
37
+ "xstate": "6.0.0-beta.0",
38
+ "zod": "^4.4.3"
39
+ }
40
+ }
41
+ ```
42
+
43
+ Pin the alpha exactly. With pnpm workspaces this package gets its own `node_modules` with XState 6 in it, while the app keeps XState 5 in its own. npm and yarn workspaces hoist by default, so add the package to `nohoist` (yarn 1) or keep the app's XState version pinned in the app's own `package.json`; check with `npm ls xstate` that two versions resolve.
44
+
45
+ ### The export
46
+
47
+ One async function in, one JSON-safe object out. Everything XState is inside it.
48
+
49
+ ```ts no-check
50
+ // packages/agent/src/index.ts
51
+ import { createAgentRuntime, runToQuiescence } from "@statelyai/agent";
52
+ import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
53
+ import { models, generationMachine } from "./machine.js";
54
+
55
+ export interface GenerationInput {
56
+ prompt: string;
57
+ }
58
+
59
+ export interface GenerationOutput {
60
+ summary: string;
61
+ draft: string | null;
62
+ }
63
+
64
+ export interface GenerationDeps {
65
+ /** Called once per state change, for the app's progress UI. */
66
+ onProgress?: (state: string) => void;
67
+ /** The app's own resource, wrapped as an actor inside this package. */
68
+ lookup: (query: string) => Promise<string[]>;
69
+ }
70
+
71
+ export async function runGeneration(
72
+ input: GenerationInput,
73
+ deps: GenerationDeps,
74
+ ): Promise<GenerationOutput> {
75
+ const result = await runToQuiescence(
76
+ createAgentRuntime(generationMachine(deps.lookup), {
77
+ executors: createAiSdkExecutors({ models }),
78
+ onTransition: (snapshot) => deps.onProgress?.(String(snapshot.value)),
79
+ }),
80
+ { input },
81
+ );
82
+ if (result.status !== "done") {
83
+ throw new Error(`Generation did not complete: ${result.status}`);
84
+ }
85
+ return result.output;
86
+ }
87
+ ```
88
+
89
+ Two rules keep the boundary intact:
90
+
91
+ - **Nothing XState-typed is in the signature.** No machine, no snapshot, no `ActorRef`. Input and output are plain objects the app can also serialize, log, and store.
92
+ - **Host resources come in as callbacks.** `deps.lookup` is the app's database or search client, passed as a function. The package wraps it in an actor with `machine.provide({ actors })`. The app never sees the actor.
93
+
94
+ ### The call site
95
+
96
+ The app imports one function. Its own XState version is untouched.
97
+
98
+ ```ts no-check
99
+ // apps/web/src/routes/generate.ts
100
+ import { runGeneration } from "@acme/agent";
101
+ import { db } from "../db.js";
102
+
103
+ export async function POST(request: Request) {
104
+ const { prompt } = await request.json();
105
+ const output = await runGeneration({ prompt }, { lookup: (query) => db.search(query) });
106
+ return Response.json(output);
107
+ }
108
+ ```
109
+
110
+ ## What can cross the boundary
111
+
112
+ Persisted snapshots are JSON. `result.persist()` returns a plain JSON value, and `runToQuiescence(createAgentRuntime(machine, {}), { snapshot, event })` takes one back, so a paused run can be stored by the app, in its own database, and resumed by a later call into the package. Pair `snapshot` with the `event` that unblocks the idle state: a resume with `snapshot` alone starts the run back at the same wait.
113
+
114
+ <!-- runToQuiescence snapshot/event resume from src/run-agent.ts; exercised by src/docs-integration-recipes.test.ts -->
115
+
116
+ ```ts no-check
117
+ // Inside the package: the app stores and returns the value, and never reads it.
118
+ import type { Snapshot } from "xstate";
119
+
120
+ export async function startGeneration(
121
+ input: GenerationInput,
122
+ deps: GenerationDeps,
123
+ ): Promise<{ snapshot: unknown }> {
124
+ const result = await runToQuiescence(
125
+ createAgentRuntime(generationMachine(deps.lookup), {
126
+ executors: createAiSdkExecutors({ models }),
127
+ }),
128
+ { input },
129
+ );
130
+ return { snapshot: result.status === "idle" ? result.persist() : null };
131
+ }
132
+
133
+ export async function resumeGeneration(
134
+ snapshot: unknown,
135
+ answer: string,
136
+ deps: GenerationDeps,
137
+ ): Promise<GenerationOutput> {
138
+ const result = await runToQuiescence(
139
+ createAgentRuntime(generationMachine(deps.lookup), {
140
+ executors: createAiSdkExecutors({ models }),
141
+ }),
142
+ {
143
+ // Opaque to the app, typed again here at the package boundary.
144
+ snapshot: snapshot as Snapshot<unknown>,
145
+ event: { type: "ANSWER", answer },
146
+ },
147
+ );
148
+ if (result.status !== "done") {
149
+ throw new Error(`Generation did not complete: ${result.status}`);
150
+ }
151
+ return result.output;
152
+ }
153
+ ```
154
+
155
+ Treat the snapshot as opaque in the app: it is the agent package's format, and its shape changes when the machine does. See [Persistence](persistence.md).
156
+
157
+ ## Related
158
+
159
+ - [Use in any stack](any-stack.md): the same isolation applied to a framework's request lifecycle.
160
+ - [Persistence](persistence.md): what a snapshot contains and how to migrate one.
161
+ - [Machines](machines.md): the schemas that carry the Standard Schema requirement.