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

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 (135) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
  3. package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
  4. package/dist/ai-sdk.cjs +4 -4
  5. package/dist/ai-sdk.d.cts +2 -3
  6. package/dist/ai-sdk.d.mts +2 -3
  7. package/dist/ai-sdk.mjs +4 -4
  8. package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
  9. package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
  10. package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
  11. package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
  12. package/dist/effects-B9IvUPVh.mjs +23 -0
  13. package/dist/effects-DrWcUGgc.cjs +34 -0
  14. package/dist/evals.cjs +810 -0
  15. package/dist/evals.d.cts +595 -0
  16. package/dist/evals.d.mts +595 -0
  17. package/dist/evals.mjs +801 -0
  18. package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
  19. package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
  20. package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
  21. package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
  22. package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
  23. package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
  24. package/dist/index.cjs +136 -98
  25. package/dist/index.d.cts +73 -134
  26. package/dist/index.d.mts +73 -134
  27. package/dist/index.mjs +117 -75
  28. package/dist/internal-BzlpzSux.d.cts +14 -0
  29. package/dist/internal-BzlpzSux.d.mts +14 -0
  30. package/dist/log.cjs +2 -3
  31. package/dist/log.d.cts +2 -2
  32. package/dist/log.d.mts +2 -2
  33. package/dist/log.mjs +3 -3
  34. package/dist/machines.cjs +1 -719
  35. package/dist/machines.d.cts +2 -424
  36. package/dist/machines.d.mts +2 -424
  37. package/dist/machines.mjs +2 -709
  38. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  39. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  40. package/dist/openai.cjs +3 -3
  41. package/dist/openai.d.cts +2 -3
  42. package/dist/openai.d.mts +2 -3
  43. package/dist/openai.mjs +3 -3
  44. package/dist/otel.d.cts +1 -1
  45. package/dist/otel.d.mts +1 -1
  46. package/dist/policy.cjs +77 -0
  47. package/dist/policy.d.cts +143 -0
  48. package/dist/policy.d.mts +143 -0
  49. package/dist/policy.mjs +75 -0
  50. package/dist/{effects-BT_cSY0j.mjs → run-agent-BE7DOWD6.mjs} +150 -184
  51. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-DHlq87G7.d.mts} +18 -34
  52. package/dist/{effects-DDseYtJk.cjs → run-agent-De3xVFGw.cjs} +149 -201
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-Dq0oSFRm.d.cts} +18 -34
  54. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  55. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  56. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  57. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  58. package/dist/tanstack-ai.cjs +4 -4
  59. package/dist/tanstack-ai.d.cts +2 -3
  60. package/dist/tanstack-ai.d.mts +2 -3
  61. package/dist/tanstack-ai.mjs +4 -4
  62. package/dist/testing.cjs +122 -996
  63. package/dist/testing.d.cts +36 -695
  64. package/dist/testing.d.mts +36 -695
  65. package/dist/testing.mjs +112 -977
  66. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  67. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  68. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  69. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  70. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  71. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  72. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  73. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  74. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  75. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  76. package/dist/validate.cjs +4 -4
  77. package/dist/validate.d.cts +2 -2
  78. package/dist/validate.d.mts +2 -2
  79. package/dist/validate.mjs +4 -4
  80. package/dist/{verify-DJHfEfm6.d.cts → verify-BM0sGmsf.d.cts} +42 -6
  81. package/dist/{verify-ChyX6jq0.mjs → verify-CWlg3j7B.mjs} +153 -45
  82. package/dist/{verify-CwlombbC.cjs → verify-Dek6gHCS.cjs} +153 -45
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-H3Pr2gNw.d.mts} +42 -6
  84. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  85. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  86. package/docs/advanced.md +5 -5
  87. package/docs/choosing-a-run-mode.md +7 -7
  88. package/docs/debugging.md +6 -8
  89. package/docs/decisions.md +6 -5
  90. package/docs/environment-and-policy.md +1 -1
  91. package/docs/evals.md +57 -43
  92. package/docs/event-log.md +14 -16
  93. package/docs/from-a-loop.md +3 -3
  94. package/docs/generate-machines.md +4 -4
  95. package/docs/hosts.md +22 -29
  96. package/docs/human-in-the-loop.md +5 -8
  97. package/docs/index.md +4 -4
  98. package/docs/judgments.md +5 -7
  99. package/docs/langgraph-comparison.md +6 -6
  100. package/docs/machines-as-data.md +12 -17
  101. package/docs/machines-presets.md +17 -120
  102. package/docs/machines.md +13 -13
  103. package/docs/models-and-providers.md +19 -25
  104. package/docs/multi-agent.md +1 -1
  105. package/docs/observability.md +6 -8
  106. package/docs/persistence.md +15 -25
  107. package/docs/quickstart.md +4 -4
  108. package/docs/statechart-policy-examples.md +1 -1
  109. package/docs/steps.md +5 -6
  110. package/docs/strangler-fig.md +72 -7
  111. package/docs/text-requests.md +10 -12
  112. package/docs/thinking-in-state-machines.md +8 -8
  113. package/docs/tools.md +10 -12
  114. package/docs/upgrading.md +1 -1
  115. package/docs/usage-and-budgets.md +51 -56
  116. package/docs/validate-and-repair.md +9 -14
  117. package/docs/verify.md +53 -7
  118. package/docs/xstate-4-and-5-apps.md +19 -28
  119. package/llms.txt +1 -1
  120. package/package.json +31 -6
  121. package/readme.md +32 -24
  122. package/dist/internal-C3Lqu538.d.cts +0 -43
  123. package/dist/internal-DUcdhk-i.d.mts +0 -43
  124. package/dist/types-DQUOOaZO.d.cts +0 -238
  125. package/dist/types-DQUOOaZO.d.mts +0 -238
  126. package/skills/add-evals/SKILL.md +0 -152
  127. package/skills/add-traces/SKILL.md +0 -152
  128. package/skills/build-machine/SKILL.md +0 -84
  129. package/skills/generate-machine/SKILL.md +0 -335
  130. package/skills/graph-engineering/SKILL.md +0 -43
  131. package/skills/improve-machine/SKILL.md +0 -261
  132. package/skills/improve-machine/reference.md +0 -101
  133. package/skills/loop-to-machine/SKILL.md +0 -205
  134. package/skills/loop-to-machine/policy.md +0 -154
  135. package/skills/loop-to-machine/reference.md +0 -260
@@ -4,22 +4,20 @@ The [event log](event-log.md) is the durable artifact. A snapshot is a cache ove
4
4
 
5
5
  - The log is an ordered array of the external inputs the machine received. A run is fully reconstructed from it.
6
6
  - The persisted snapshot is the machine's serialized state at one point. It lets a resume skip the fold.
7
- - Live run state — the actor, in-flight requests, stream chunks — is derived and disposable.
7
+ - Live run state (the actor, in-flight requests, stream chunks) is derived and disposable.
8
8
 
9
9
  ## Persist the log
10
10
 
11
- Hand `runToQuiescence` a [store](event-log.md#stores) and the thread it owns. Entries are written as they are accepted, and no model call runs against a log that is not yet durable.
11
+ Hand `runAgent` a [store](event-log.md#stores) and the thread it owns. Entries are written as they are accepted, and no model call runs against a log that is not yet durable.
12
12
 
13
13
  ```ts no-check
14
- const result = await runToQuiescence(createAgentRuntime(machine, { store, threadId, executors }), {
15
- input,
16
- });
14
+ const result = await runAgent(machine, { store, threadId, executors, input });
17
15
  ```
18
16
 
19
17
  - A rejected write stops the run: `{ status: "error", cause: "journal" }`.
20
18
  - `threadId` is required whenever `store` is given.
21
19
 
22
- `onEvent` remains the observer seam — synchronous, never awaited. Persisting there is at-least-once: a crash between an entry and the host's flush loses it. See [Record a log](event-log.md#record-a-log).
20
+ `onEvent` remains the observer seam. It is synchronous and never awaited. Persisting there is at-least-once: a crash between an entry and the host's flush loses it. See [Record a log](event-log.md#record-a-log).
23
21
 
24
22
  `result.events` is a complete, self-contained segment: its first entry is the reserved `@agent.init` entry, so it replays with no side channel.
25
23
 
@@ -28,9 +26,7 @@ const result = await runToQuiescence(createAgentRuntime(machine, { store, thread
28
26
  With a `store`, the thread's log is the resume: pass no `events` and no snapshot.
29
27
 
30
28
  ```ts no-check
31
- const resumed = await runToQuiescence(createAgentRuntime(machine, { store, threadId, executors }), {
32
- event: { type: "APPROVE" },
33
- });
29
+ const resumed = await runAgent(machine, { store, threadId, executors, event: { type: "APPROVE" } });
34
30
  ```
35
31
 
36
32
  An empty thread starts fresh from `input`. Pass `events` explicitly to resume from a log the host holds itself (the store's thread length must then match it).
@@ -47,9 +43,7 @@ try {
47
43
  return Response.json({ error: String(error) }, { status: 400 });
48
44
  }
49
45
 
50
- const result = await runToQuiescence(createAgentRuntime(machine, { store, threadId, executors }), {
51
- event,
52
- });
46
+ const result = await runAgent(machine, { store, threadId, executors, event });
53
47
 
54
48
  if (result.ignored) {
55
49
  return Response.json(
@@ -62,7 +56,7 @@ if (result.ignored) {
62
56
  - `parseAgentEvent` takes `unknown`: hand over the parsed JSON body as-is. It accepts the machine itself (reading the event schemas `setupAgent` registered) or any snapshot of it, and returns the event typed as the machine's event union.
63
57
  - It throws `AgentInvalidEventPayloadError` (code `invalid-event-payload`) when the payload is not an object with a string `type`, when the type is a reserved `@agent.*` type, or when the fields fail the registered schema. Answer that with a 400.
64
58
  - On success the schema-parsed event is returned: defaults filled, transforms applied.
65
- - `parseAgentEvent` does not check whether the current state handles the event, and `runToQuiescence` adds no validation of its own.
59
+ - `parseAgentEvent` does not check whether the current state handles the event, and `runAgent` adds no validation of its own.
66
60
  - An event the resumed state has no transition for is ignored. The run settles normally and `result.ignored` carries the event. It is journaled like any other external input, so replay ignores it again.
67
61
 
68
62
  - Recorded results are replayed, never re-executed.
@@ -143,35 +137,33 @@ Run it in CI next to the machine's other tests. It needs no API key.
143
137
 
144
138
  ## Snapshot as cache
145
139
 
146
- `persist()` output carries `agentMeta: { machineId, version, logId, logIndex }` — the lineage and position of the log it caches.
140
+ `persist()` output carries `agentMeta: { machineId, version, logId, logIndex }`: the lineage and position of the log it caches.
147
141
 
148
142
  Pass `snapshot` alongside `events` to skip the fold:
149
143
 
150
144
  ```ts no-check
151
- const resumed = await runToQuiescence(createAgentRuntime(machine, { executors }), {
145
+ const resumed = await runAgent(machine, {
146
+ executors,
152
147
  events: await store.read(threadId),
153
148
  snapshot: await snapshots.get(threadId),
154
149
  event: { type: "APPROVE" },
155
150
  });
156
151
  ```
157
152
 
158
- - Fast path: `agentMeta.logId` names the log, `logIndex` equals the log length, and the snapshot's state hash matches the tail entry's `verification.stateHash`. Length alone is not enough — a fork or a sibling thread can sit at the same index.
153
+ - Fast path: `agentMeta.logId` names the log, `logIndex` equals the log length, and the snapshot's state hash matches the tail entry's `verification.stateHash`. Length alone is not enough, because a fork or a sibling thread can sit at the same index.
159
154
  - Otherwise the log is replayed and the run resumes from the replayed state.
160
155
  - A cache that disagrees with the state the log replays to throws `AgentSnapshotDivergedError` (code `snapshot-diverged`). Drop the snapshot and resume from `events` alone.
161
156
 
162
157
  A snapshot is never authoritative within a version. Snapshot only at quiescent points: a mid-flight snapshot cannot carry in-flight request state, but the log can.
163
158
 
164
- Resuming from a snapshot with no log also yields a self-contained log — the new segment's init entry carries that snapshot — so every result is replayable.
159
+ Resuming from a snapshot with no log also yields a self-contained log (the new segment's init entry carries that snapshot), so every result is replayable.
165
160
 
166
161
  ## Version bridge
167
162
 
168
163
  A log is truth within one `machine.version`. Across a version change, pass the old `events` together with a `snapshot`:
169
164
 
170
165
  ```ts no-check
171
- const migrated = await runToQuiescence(createAgentRuntime(machine, { executors }), {
172
- events: oldEntries,
173
- snapshot: oldSnapshot,
174
- });
166
+ const migrated = await runAgent(machine, { executors, events: oldEntries, snapshot: oldSnapshot });
175
167
  ```
176
168
 
177
169
  - XState's machine-owned `migrate` runs on the snapshot.
@@ -196,12 +188,10 @@ const machine = setup.createMachine({
196
188
 
197
189
  Implement `AgentEventLogStore` against the host's database, or append through the framework's own mechanism: a Durable Object, workflow checkpoint, or server action store. See [Stores](event-log.md#stores) and [Hosts and executors](hosts.md).
198
190
 
199
- The recipe per turn is one call: `runToQuiescence` reads the thread, runs, and writes back.
191
+ The recipe per turn is one call: `runAgent` reads the thread, runs, and writes back.
200
192
 
201
193
  ```ts no-check
202
- const result = await runToQuiescence(createAgentRuntime(machine, { store, threadId, executors }), {
203
- event: incoming,
204
- });
194
+ const result = await runAgent(machine, { store, threadId, executors, event: incoming });
205
195
  ```
206
196
 
207
197
  The framework remains responsible for transactionality, retries, interruption recovery, and retention.
@@ -1,12 +1,12 @@
1
1
  # Quickstart
2
2
 
3
- Install core:
3
+ Install the published agent and its matching XState peer:
4
4
 
5
5
  ```sh
6
- pnpm add @statelyai/agent@alpha xstate@6.0.0-beta.0 zod
6
+ pnpm add @statelyai/agent@2.0.0-alpha.38 xstate@6.0.0-beta.0 zod
7
7
  ```
8
8
 
9
- XState is pinned to the exact version the package's peer dependency names, because its experimental durable restoration API (`xstate/durable`) can still change between prereleases. `xstate@beta` can resolve to a newer prerelease that the package does not support.
9
+ This is the published pair as of November 11, 2026. This source checkout requires XState `6.0.0-beta.2`. XState is pinned to the exact version the installed package's peer dependency names, because its experimental durable restoration API (`xstate/durable`) can still change between prereleases. `xstate@beta` can resolve to a newer prerelease that the package does not support.
10
10
 
11
11
  Add `ai` and a provider only when using the optional AI SDK adapter.
12
12
 
@@ -85,7 +85,7 @@ Requests have a semantic `name`, resolved `input`, model reference, schemas,
85
85
  prompt/messages, and tools. The machine owns control flow; the executor owns
86
86
  the provider call.
87
87
 
88
- An executor is just a function, so the machine runs anywhere a function does.
88
+ An executor is a function, so the machine runs anywhere a function does.
89
89
  When several requests each need their own canned answer, the executor routes on
90
90
  `request.name`. See [Evals](evals.md#testing-without-a-provider).
91
91
 
@@ -28,7 +28,7 @@ Trust is a machine rule, not a prompt instruction. The patch text is in all thre
28
28
 
29
29
  Each reviewer is a named parallel region invoking the same Jev judgment actor, `review`, with its own reviewer brief. No host `Promise.all` hides the topology. All regions reach a final state even when their call fails; the parent then counts votes. Human review persists both successful votes and abstentions.
30
30
 
31
- The tests execute the same artifact through both `runToQuiescence` and `createActor(provideExecutors(...))`. This establishes those host modes' behavior for this example; it is not certification of every model SDK.
31
+ The tests execute the same artifact through both `runAgent` and `createActor(provideExecutors(...))`. This establishes those host modes' behavior for this example; it is not certification of every model SDK.
32
32
 
33
33
  ## Booking compensation
34
34
 
package/docs/steps.md CHANGED
@@ -3,9 +3,9 @@
3
3
  <!-- public AgentRuntime loop from src/run-agent.ts -->
4
4
 
5
5
  `createAgentRuntime(machine, options)` binds executors and returns the operations
6
- for one run. `runToQuiescence(runtime, init)` drives that loop until the machine
7
- finishes or no work remains. Use the explicit loop when a host needs to persist,
8
- schedule, or observe each transition itself.
6
+ for one run. `runAgent` drives that loop until the machine finishes or no work
7
+ remains. Use the explicit loop when a host needs to persist, schedule, or observe
8
+ each transition itself.
9
9
 
10
10
  ```ts
11
11
  import { createAgentRuntime } from "@statelyai/agent";
@@ -38,7 +38,7 @@ Root `after` timers run in process by default. A durable host can provide
38
38
  `timers: { schedule, cancel }` to `createAgentRuntime`. The runtime then settles
39
39
  with an external timer pending. When it fires, deliver
40
40
  `{ type: "xstate.timer", id }` through `transition` or as the `event` passed to
41
- `runToQuiescence`.
41
+ `runAgent`.
42
42
 
43
43
  A resumed run calls `schedule` again for each timer still pending, with what is left of its delay by the wall clock. Treat `schedule` as an upsert by `id`: a host that already holds that timer keeps its own due time. An `id` names a timer by its state and delay, not by arming, so a state entered again schedules the same `id` once the earlier timer has fired or been cancelled.
44
44
 
@@ -47,8 +47,7 @@ waits for them, whichever `timers` option you pass.
47
47
 
48
48
  ## Other hosts
49
49
 
50
- - `runToQuiescence(createAgentRuntime(...), init)` for scripts, tests, and
51
- request handlers.
50
+ - `runAgent(machine, options)` for scripts, tests, and request handlers.
52
51
  - `provideExecutors` when an application owns a live XState actor.
53
52
  - An explicit `AgentRuntime` loop when a workflow engine owns persistence,
54
53
  retries, messaging, timers, and child execution.
@@ -24,19 +24,21 @@ export async function runTicket(ticket: Ticket, effects: SupportEffects): Promis
24
24
  }
25
25
  ```
26
26
 
27
- - Each effect is an async function.
27
+ - Each effect is an async function. A wrapped or recorded effect returns a Promise even when the original returns an async iterable at once: write `yield* await effects.stream()`.
28
28
  - A call made around `effects` (a module-level client, `fetch`) is invisible to the machine, to traces, and to recordings. Move it into `effects` first.
29
29
  - Keep effect arguments and results JSON-shaped where you can: they are journaled and recorded. Pass live objects (a chat session, an `AbortSignal`) by closure, not as arguments.
30
- - An effect whose natural result is a live object (an agent instance) returns its name or id instead. The host keeps a registry from id to object.
30
+ - An effect whose natural result is a live object (an agent instance) returns its name or id instead. The function that starts the run keeps a `Map` from id to object, created per run. See [Live objects](#live-objects).
31
31
  - An effect that writes host state by reference (a tool mutating a shared `state` object) returns the change instead, and the wrapper applies it.
32
32
  - A synchronous host callback (a stop predicate) or a diagnostic logger is not an effect. The workflow or the machine factory closes over it.
33
33
 
34
34
  ### Class-shaped code
35
35
 
36
- When the loop is a class method that calls its own private methods for the model and the tools, there is no `(input, effects)` function to pass. Wrap it with no edit to the class:
36
+ When the loop is a class method that calls its own private methods for the model and the tools, there is no `(input, effects)` function to pass. Wrap it with no edit to the class (a phase in the middle of a method is extracted at step 0, see [A phase in the middle of a method](#a-phase-in-the-middle-of-a-method)):
37
37
 
38
38
  - `run: (input, effects) => { const executor = createExecutor(input); executor.callModel = (...args) => effects.callModel(...args); return executor.run(); }`, with each effect calling the original method.
39
39
  - Route the old test suite through the wrap with a factory or a static `create` stand-in, not a subclass, when the constructor is private.
40
+ - Install each replacement with `Object.defineProperty` (non-enumerable). A plain assignment adds an own enumerable field, which the repo's state snapshots then serialize.
41
+ - The seam is on both sides of `checkParity`: `before` runs the class with the seam installed, so a serialization bug in the seam shows up on both sides and parity reports equivalent. Also compare the untouched class against the port by output, with no seam on the original, and add scenarios for edge results: empty, `null`, non-JSON values, `BigInt`.
40
42
 
41
43
  ### Seams for other shapes
42
44
 
@@ -46,6 +48,7 @@ When the loop is a class method that calls its own private methods for the model
46
48
  | Redux thunk | The thunk's `extra` argument plus its nested dispatches. Wrap `dispatch` so every nested thunk gets the effects-backed `extra`. |
47
49
  | LangGraph graph | Wrap `graph.invoke`. Fake the model factory with the test runner's module mock (`vi.mock`); the fake calls the run's effects. |
48
50
  | A closure inside a DI or Layer factory | Copy the module, identical outside the carved function, and swap it in with a module mock. |
51
+ | Async generator the consumer pulls (yields events, `.return()` on break, `.throw()` to interrupt) | Step 0: wrap the host call that drains the generator, with the collected events as the output. Carve: the machine runs the loop head and each pass is an actor. `createGeneratorBridge` carries the pull contract across: the actor calls `bridge.forward(legacyPass())` and the original generator becomes `yield* bridge.stream(runAgent(...))`. Each value waits for the consumer's next pull, `.throw()` reaches the legacy generator, and `.return()` unwinds it and awaits the run before it resolves. Code after the `yield*` does not run on `.return()`; put cleanup in a `finally`. |
49
52
  | A step loop inside the model SDK (`stopWhen`, `maxSteps`) | No loop to carve. The SDK call stays one effect; carve the control flow around it, such as handoff or approval. |
50
53
 
51
54
  ## Step 0: wrap
@@ -179,11 +182,68 @@ resolving: {
179
182
  - A legacy body that owns abort (it returns its own `stopped` result): pass the `signal` to the legacy body only, not to `runAgent`. Its result then reaches the machine as a normal final; `runAgent`'s `signal` would settle the run as `aborted` instead.
180
183
  - An invoke whose error must reach the caller unchanged: omit `onError`. The run settles `{ status: "error", error }` with the original error, and the runner rethrows it. Pass `disable: ["invoke-without-on-error"]` to `lintAgentMachine` for that machine, or `ignore: [{ code: "invoke-without-on-error", path }]` for one state.
181
184
 
185
+ ### Live objects
186
+
187
+ A store, a class instance, a session or a cancellation token cannot go in context, input or events: those are journaled JSON. Bind the actors and actions that need them per run, as closures, in the function that starts the run.
188
+
189
+ ```ts no-check
190
+ const machine = setupAgent({
191
+ // ...schemas
192
+ actions: { setStatus: (_params: { status: string }) => {} }, // default for tests and explorePaths
193
+ actors: { think: createAsyncLogic({ run: async () => ({ kind: "final" }) }) },
194
+ }).createMachine({
195
+ // ...
196
+ entry: ({ actions }, enq) => enq(actions.setStatus, { status: "thinking" }),
197
+ });
198
+
199
+ async function agenticLoop(agent: Agent, task: Task) {
200
+ return runAgent(machine, {
201
+ input: { taskId: task.id },
202
+ actions: { setStatus: ({ status }) => agent.store.setStatus(task, status) },
203
+ actors: {
204
+ think: createAsyncLogic({ run: () => legacy.executeThinking.call(agent, agent, task) }),
205
+ },
206
+ });
207
+ }
208
+ ```
209
+
210
+ - `runAgent`'s `actions` and `actors` are merged onto the machine for that run only. Concurrent runs each see their own objects.
211
+ - `actions` keys and params are checked against the actions declared in `setupAgent`. Declare a no-op for each; it is the default for tests and `explorePaths`.
212
+ - Only actors and actions read live objects. A guard, a `choice` or a transition function that reads one makes a decision the log does not record, so replay, resume and `explorePaths` can reach another state. Copy what the machine branches on into an actor's output.
213
+ - An action runs through `enq(...)`, after the transition. A `{ context }` it returns is ignored.
214
+ - Resume binds the same way: the host builds the actors and actions again and passes them with the snapshot or `store`. Nothing about the live objects is journaled.
215
+ - An effect whose result is a live object (an agent instance) records an id. Keep the id-to-object `Map` in the same function, created per run, never at module level.
216
+
182
217
  ### A phase in the middle of a method
183
218
 
184
- - Copy only that phase's lines into the carved actor, with a comment listing the copied line ranges. `checkParity` call-args keep the copy honest: a drifted copy calls its effects with other arguments.
219
+ Extract the phase first, then carve. The carved actor calls the extracted method or function, and nothing is copied.
220
+
221
+ - The extract is a step 0 edit: move the loop body or the phase into its own method or function, with no change in behavior. In a class, make it a protected method when the carve is a subclass that builds its actors inside the class body (the drop-in runner the old suite swaps in). An actor built outside the class calls a public method instead, marked `@internal`. Either way the actor calls it on the instance, bound per run.
222
+ - Commit it on its own, before any carve, so the diff is a pure move.
223
+ - Gate it like step 0: the old suite passes unchanged, and `checkParity` against the code before the extract is equivalent on every scenario. `examples/strangler-fig/before-extract.ts` is the one-function original; `index.test.ts` checks the extracted `runTicket` against it.
224
+ - A loop whose head lives in a private method: extract the body (`this._cycle(state)`), so the loop head is the only line the carve replaces.
185
225
  - When the class has a public per-turn hook, replace that method on the instance instead, and let the machine decide at that boundary. The rest of the method stays legacy.
186
226
 
227
+ #### Code you can't edit
228
+
229
+ For vendored or third-party code (in `node_modules` or a pinned fork), copy only that phase's lines into the carved actor, with a comment listing the copied line ranges.
230
+
231
+ - `checkParity` call-args catch a drifted copy only when the drift changes an effect's arguments.
232
+ - Add a drift test that hashes each copied range in the original, so an upstream change fails CI:
233
+
234
+ ```ts no-check
235
+ import { createHash } from "node:crypto";
236
+ import { readFileSync } from "node:fs";
237
+
238
+ const lines = readFileSync(require.resolve("vendor-lib/dist/runtime.js"), "utf8").split("\n");
239
+ const hash = (from: number, to: number) =>
240
+ createHash("sha256").update(lines.slice(from - 1, to).join("\n")).digest("hex");
241
+
242
+ test("copied ranges match the original", () => {
243
+ expect(hash(412, 470)).toBe("<sha256 recorded when you copied>");
244
+ });
245
+ ```
246
+
187
247
  ## Check parity
188
248
 
189
249
  `checkParity` from `@statelyai/agent/testing` checks a step against the original, scenario by scenario.
@@ -223,10 +283,14 @@ What it does per scenario:
223
283
  | `row.divergences` | `compareRecordings` divergences: `call-args`, `missing-effect`, … |
224
284
  | `row.before` / `row.after` | `{ output }` or `{ error }` |
225
285
  | `row.recording` / `row.replay` | The baseline recording, and what `after` did in replay |
286
+ | `report.scenarios` | The rows, one per scenario, in order |
226
287
 
227
288
  - An `after` that throws is a row with `after: { error }`, never a thrown `checkParity`. A call the recording cannot answer throws `RecordingDivergenceError` inside `after`.
228
289
  - When both sides throw, they match on the error's name and message.
290
+ - Replay throws a recorded error with its name, message, number and boolean fields, `cause`, and an `AggregateError`'s `errors`. It is a plain `Error` or `AggregateError`. When the code branches on `instanceof`, pass `reviveError` to build its own class: `reviveError: (recorded) => recorded.name === "AbortError" ? new AbortError(recorded.message) : undefined`. A recorder takes the same option.
291
+ - An effect result that is not JSON (a class instance, a `Response`) records as its JSON and replays as a plain value. Pass `recordOptions: { lookupOrder: { serialize, revive } }` to `checkParity` or `wrapWorkflow().run` to keep the class in replay.
229
292
  - `compare` passes options through to `compareRecordings`, such as `normalize` for generated ids.
293
+ - `setup: (scenario, side) => liveObject` builds what one side runs on (a class instance, a session). It is called once for `before` and once for `after`, and its result is the last argument of `effects`, `before` and `after`. Effects then bind to the object without a module-level slot, and a mutable object does not carry state from `before` into `after`.
230
294
 
231
295
  ### Generated ids
232
296
 
@@ -279,6 +343,7 @@ Run the module's own tests against the port by swapping the module.
279
343
  - Snapshot files are named after the test file that runs them. A swap file that imports the old suite writes fresh snapshots on its first run, and `toMatchSnapshot` passes without comparing. Copy the old `__snapshots__/<old>.snap` to the swap file's name, and run with `CI=true` so a missing snapshot fails.
280
344
  - A module mock whose factory imports the port deadlocks or recurses when the port imports the mocked module. Load the port with a dynamic import in `beforeAll`, and call it from inside the mocked functions.
281
345
  - When a module mock does not reach the code's own import of the module (one runner did not apply it to a relative import inside the package), patch the class prototype from a setup file instead. Import both modules dynamically in its `beforeAll`: a static import loads the module before the test file's mocks apply.
346
+ - Old code that registers its in-flight call with a host registry synchronously (a store's tracked promises, a map of `AbortController`s), so that pause or stop can cancel it: register the run in the same tick, before calling `runAgent`, with a promise that settles when the run does, and pass the registry's signal as `signal`. An abort in the same tick as the `runAgent` call settles the run `aborted` before any actor starts. Otherwise a pause and resume that land before the run starts leave the first run going next to the resumed one.
282
347
  - `runAgent` starts asynchronously. Fire-and-forget work the old code starts at the same time may settle in a different order. An old test that asserts the exact order of actions across concurrent tasks is a structural failure only when those actions commute and their order is not part of the contract; an order that reaches users or storage is behavioral.
283
348
 
284
349
  ## Repeat
@@ -310,7 +375,7 @@ Step 0 cannot give this proof: its one `running` state holds the whole function.
310
375
  - No resume in the middle of the function. A resumed run starts the workflow again.
311
376
  - `canReach` and `explorePaths` prove nothing about the wrapped function's inside.
312
377
  - Effect arguments and results are journaled JSON-safe. A value that is not JSON (a class instance) loses what JSON cannot hold. A stream is journaled as the chunks read through `for await` or `next()`; one read another way (a `ReadableStream` reader) never settles its effect.
313
- - Parity cannot see an effect that mutates host state by reference, or one whose result is a live object. Return a change, a name, or an id, and keep a registry on the host side.
378
+ - Parity cannot see an effect that mutates host state by reference, or one whose result is a live object. Return a change, a name, or an id, and keep a per-run map from id to object.
314
379
  - `checkParity` runs `before` on the effects you give it for real. Give it fakes or an isolated fixture, never production writes.
315
380
  - `effects` are async functions only. A sync function or a client object goes behind an async function first.
316
381
  - Parity covers what goes through `effects` and the output. A change in a call made around `effects` is not seen.
@@ -318,6 +383,6 @@ Step 0 cannot give this proof: its one `running` state holds the whole function.
318
383
  ## Related
319
384
 
320
385
  - [Migrating from a hand-rolled loop](from-a-loop.md): port a whole loop at once.
321
- - [Evals](evals.md#parity-with-the-code-you-replace): `createRecorder`, `compareRecordings`, and `compareRuns`.
386
+ - [Evals](evals.md#parity-with-the-code-you-replace): which of `checkParity`, `createRecorder` with `compareRecordings`, and `compareRuns` fits the code you replace.
322
387
  - [Verify](verify.md): `canReach` and `explorePaths`.
323
- - [`skills/loop-to-machine`](https://github.com/statelyai/agent/blob/next/skills/loop-to-machine/SKILL.md): the retrofit, run by a coding agent.
388
+ - [`loop-to-machine`](https://github.com/statelyai/skills/blob/main/plugins/stately-agent/skills/loop-to-machine/SKILL.md): the retrofit, run by a coding agent.
@@ -128,16 +128,16 @@ export const triageTicket = createTextLogic({
128
128
  });
129
129
  ```
130
130
 
131
- The reasoning never enters machine context or output. It surfaces in three places: on the raw executor result as `result.reasoning` from the `generateText` executor of `createAiSdkExecutors`, on `runToQuiescence`'s `onResult(request, { raw })`, and as a `reasoning` field on the `request.end` `onTrace` event. Text-mode requests ignore the option.
131
+ The reasoning never enters machine context or output. It surfaces in three places: on the raw executor result as `result.reasoning` from the `generateText` executor of `createAiSdkExecutors`, on `runAgent`'s `onResult(request, { raw })`, and as a `reasoning` field on the `request.end` `onTrace` event. Text-mode requests ignore the option.
132
132
 
133
133
  `includeReasoning` is not the provider's reasoning-effort setting. Effort is the host's business, because what it means differs per provider: an enum for one, a thinking-token budget for another, nothing at all for a third. A machine that named an effort level would stop being portable. Set it where the executors are built, with [`createAiSdkExecutors({ settings })`](models-and-providers.md#host-owned-model-settings).
134
134
 
135
135
  ## Streaming requests
136
136
 
137
137
  <!-- stream mode from src/text-logic.ts and examples/joke -->
138
- <!-- viz: sequence diagram of a streaming request: state invokes the request -> host streamText executor -> chunks delivered to runToQuiescence onChunk while the invoke is pending -> final text resolves onDone -->
138
+ <!-- viz: sequence diagram of a streaming request: state invokes the request -> host streamText executor -> chunks delivered to runAgent onChunk while the invoke is pending -> final text resolves onDone -->
139
139
 
140
- A request streams when its `mode` is `'stream'`. Without `mode`, the request is single-shot, equivalent to `'generate'`. A streaming request resolves to the final text and delivers intermediate chunks to `runToQuiescence`'s `onChunk`.
140
+ A request streams when its `mode` is `'stream'`. Without `mode`, the request is single-shot, equivalent to `'generate'`. A streaming request resolves to the final text and delivers intermediate chunks to `runAgent`'s `onChunk`.
141
141
 
142
142
  ```ts no-check
143
143
  export const tellJoke = createTextLogic({
@@ -148,18 +148,16 @@ export const tellJoke = createTextLogic({
148
148
  prompt: ({ input }) => `Tell a joke about ${input.topic}.`,
149
149
  });
150
150
 
151
- const result = await runToQuiescence(
152
- createAgentRuntime(machine, {
153
- executors: createAiSdkExecutors({ models }),
154
- onChunk: (chunk) => process.stdout.write(chunk),
155
- }),
156
- { input: { topic: "state machines" } },
157
- );
151
+ const result = await runAgent(machine, {
152
+ executors: createAiSdkExecutors({ models }),
153
+ onChunk: (chunk) => process.stdout.write(chunk),
154
+ input: { topic: "state machines" },
155
+ });
158
156
  ```
159
157
 
160
158
  - `onChunk` fires once per chunk and receives the request that produced it, so parallel streams stay distinguishable.
161
159
  - `onChunk` is observational only. It cannot change the run.
162
- - A `mode: 'stream'` request needs a `streamText` executor. Without one, `runToQuiescence` fails at bind time.
160
+ - A `mode: 'stream'` request needs a `streamText` executor. Without one, `runAgent` fails at bind time.
163
161
 
164
162
  See [parallel-streams](https://github.com/statelyai/agent/blob/next/examples/parallel-streams/index.ts).
165
163
 
@@ -169,7 +167,7 @@ See [parallel-streams](https://github.com/statelyai/agent/blob/next/examples/par
169
167
 
170
168
  An executor result can report why the call stopped, as a normalized `finishReason`: `'stop'`, `'length'`, `'tool-calls'`, `'content-filter'`, or `'other'`. `createAiSdkExecutors` sets it on every text, structured, and streamed result, mapping the provider's own vocabulary onto those five; the provider's raw value stays on the result's `raw`.
171
169
 
172
- The reason reaches observability the way per-call usage does: `runToQuiescence` lifts it onto the `request.end` [trace event](observability.md), next to `usage`.
170
+ The reason reaches observability the way per-call usage does: `runAgent` lifts it onto the `request.end` [trace event](observability.md), next to `usage`.
173
171
 
174
172
  `'length'` means the output token limit cut the call off. What that costs depends on the request:
175
173
 
@@ -13,7 +13,7 @@ For the mechanical refactor of an existing codebase, see [Migrating from a hand-
13
13
 
14
14
  <!-- xstate version requirement from package.json#peerDependencies -->
15
15
 
16
- > **Version requirement.** Build the machine with the exact `xstate` version this package peers on, `6.0.0-beta.0`. See the [Quickstart](quickstart.md). Machines authored for XState v5 usually port with few changes, but a machine object imported from a separate `xstate@5` install does not bind. Write event-transition guards as functions that return `undefined`. XState v6 drops named string guards on `on`, and the function form is what makes `snapshot.can(event)` reflect the guard.
16
+ > **Version requirement.** Build the machine with the exact `xstate` version this package peers on, `6.0.0-beta.2`. See the [Quickstart](quickstart.md). Machines authored for XState v5 usually port with few changes, but a machine object imported from a separate `xstate@5` install does not bind. Write event-transition guards as functions that return `undefined`. XState v6 drops named string guards on `on`, and the function form is what makes `snapshot.can(event)` reflect the guard.
17
17
 
18
18
  ## The loop to model
19
19
 
@@ -154,7 +154,7 @@ awaitingHuman: {
154
154
  },
155
155
  ```
156
156
 
157
- When no work is in flight, `runToQuiescence` settles with `{ status: 'idle', snapshot }` instead of hanging. Persist the snapshot and show the person their options. [`getAcceptedEvents(snapshot)`](human-in-the-loop.md) lists the legal events. To resume later, in the same process or another one, pass the snapshot back with the event. See [Human in the loop](human-in-the-loop.md).
157
+ When no work is in flight, `runAgent` settles with `{ status: 'idle', snapshot }` instead of hanging. Persist the snapshot and show the person their options. [`getAcceptedEvents(snapshot)`](human-in-the-loop.md) lists the legal events. To resume later, in the same process or another one, pass the snapshot back with the event. See [Human in the loop](human-in-the-loop.md).
158
158
 
159
159
  ## The finished machine
160
160
 
@@ -163,7 +163,7 @@ The machine below makes the same four model calls and applies the same policy as
163
163
  ```ts
164
164
  import { z } from "zod";
165
165
  import { openai } from "@ai-sdk/openai";
166
- import { createTextLogic, runToQuiescence, setupAgent } from "@statelyai/agent";
166
+ import { createTextLogic, setupAgent, runAgent } from "@statelyai/agent";
167
167
  import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
168
168
 
169
169
  // Model IDs here are illustrative; substitute your provider's current models.
@@ -284,10 +284,10 @@ const triageMachine = agentSetup.createMachine({
284
284
  },
285
285
  });
286
286
 
287
- const result = await runToQuiescence(
288
- createAgentRuntime(triageMachine, { executors: createAiSdkExecutors({ models }) }),
289
- { input: { ticket: "I was charged twice for March." } },
290
- );
287
+ const result = await runAgent(triageMachine, {
288
+ executors: createAiSdkExecutors({ models }),
289
+ input: { ticket: "I was charged twice for March." },
290
+ });
291
291
  if (result.status === "done") console.log(result.output.reply);
292
292
  if (result.status === "idle") console.log("waiting on a human", result.snapshot);
293
293
  ```
@@ -314,7 +314,7 @@ The design work above assumes you are writing the machine. Existing machines can
314
314
 
315
315
  - The machine already exists and contains nothing agent-specific. Any machine whose invokes resolve to values and whose events you can enumerate can be driven. Use [`getAcceptedEvents(snapshot)`](human-in-the-loop.md) for the candidates and call `resolveDecision` gated by `snapshot.can(event)`. See [plain-xstate](https://github.com/statelyai/agent/blob/next/examples/plain-xstate/index.ts).
316
316
 
317
- Prompts do not have to live in the machine. Leave bare `src` strings and bind a separate prompt map through the `actors` option of `runToQuiescence`, which is shorthand for `machine.provide({ actors })`. The explicit invokes remain part of the graph, which is what lets a machine round-trip through JSON with `setupAgent.fromConfig`. See [Machines as data](machines-as-data.md).
317
+ Prompts do not have to live in the machine. Leave bare `src` strings and bind a separate prompt map through the `actors` option of `runAgent`, which is shorthand for `machine.provide({ actors })`. The explicit invokes remain part of the graph, which is what lets a machine round-trip through JSON with `setupAgent.fromConfig`. See [Machines as data](machines-as-data.md).
318
318
 
319
319
  ## Related
320
320
 
package/docs/tools.md CHANGED
@@ -105,13 +105,13 @@ export const toolCallingMachine = agentSetup.createMachine({
105
105
  Run the machine with any executor set. The machine is the same for scripted and real models.
106
106
 
107
107
  ```ts
108
- import { runToQuiescence } from "@statelyai/agent";
108
+ import { runAgent } from "@statelyai/agent";
109
109
  import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
110
110
 
111
- const result = await runToQuiescence(
112
- createAgentRuntime(toolCallingMachine, { executors: createAiSdkExecutors({ models }) }),
113
- { input: { query: "What is 42 times 17?" } },
114
- );
111
+ const result = await runAgent(toolCallingMachine, {
112
+ executors: createAiSdkExecutors({ models }),
113
+ input: { query: "What is 42 times 17?" },
114
+ });
115
115
  ```
116
116
 
117
117
  For approval and progress around real tools, see [review-tool-calls](https://github.com/statelyai/agent/blob/next/examples/review-tool-calls/index.ts).
@@ -135,7 +135,7 @@ Two consequences follow:
135
135
  - Tool-carrying requests do not retry. The AI SDK adapter retries invalid structured output only when the request has no tools, because a tool loop may already have caused side effects.
136
136
  - `metadata` is host-owned. A host that does not understand a key ignores it, so requests stay portable.
137
137
 
138
- The raw executor result, including tool calls and results, reaches host code through `runToQuiescence`'s `onResult(request, { raw })` and the `request.end` trace event. See [Observability](observability.md).
138
+ The raw executor result, including tool calls and results, reaches host code through `runAgent`'s `onResult(request, { raw })` and the `request.end` trace event. See [Observability](observability.md).
139
139
 
140
140
  ## Tool results in messages
141
141
 
@@ -161,14 +161,12 @@ answering: {
161
161
 
162
162
  Build these parts by hand only when the machine owns the loop, such as in a ReAct-style machine or when replaying a transcript. With a host-run tool loop, the intermediate calls stay inside the executor. See [Messages](messages.md).
163
163
 
164
- ## Presets and ejecting
165
-
166
- `createToolLoopMachine` from `@statelyai/agent/machines` is a prebuilt version of the machine above: one `answering` state and one tool-carrying request. See [Preset machines](machines-presets.md) for its options, including `maxSteps`.
164
+ ## Beyond one request
167
165
 
168
- Eject from the preset when the tool loop needs machine states of its own:
166
+ Model the tool loop as machine states when it needs states of its own:
169
167
 
170
168
  - To approve or reject each of a turn's tool calls before it runs, use `createApprovalBatchMachine`. See [Approval gate](#approval-gate).
171
- - To model approval as machine states, with approve, edit, and reject steps that persist and resume, eject to [examples/review-tool-calls](https://github.com/statelyai/agent/blob/next/examples/review-tool-calls/index.ts).
169
+ - To model approval as machine states, with approve, edit, and reject steps that persist and resume, start from [examples/review-tool-calls](https://github.com/statelyai/agent/blob/next/examples/review-tool-calls/index.ts).
172
170
  - To model each think, act, and observe turn as its own transition, use explicit request, tool, and observation states.
173
171
 
174
172
  > **Note:** There is no built-in MCP client. MCP discovery, auth, and transport are the host's responsibility. Pass the discovered tool descriptors into `tools` like any other tool. See [Scope](scope.md).
@@ -246,4 +244,4 @@ await generateText({
246
244
  - Read more about [Text requests](text-requests.md), the request a tool attaches to, including structured and streaming output.
247
245
  - Read more about [Hosts](hosts.md), including executors, model aliases, and writing your own adapter.
248
246
  - Read more about [Messages](messages.md), the message model that tool parts live in.
249
- - Read more about [Preset machines](machines-presets.md), including `createToolLoopMachine`.
247
+ - Read more about [Preset machines](machines-presets.md), including `createApprovalBatchMachine`.
package/docs/upgrading.md CHANGED
@@ -9,7 +9,7 @@ This page lists the breaking changes an app on an earlier 2.0 alpha is most like
9
9
 
10
10
  ## Peer versions
11
11
 
12
- - **XState:** exactly the version in the package's `peerDependencies` (`6.0.0-beta.0` today). Upgrade it in the same change as the agent package.
12
+ - **XState:** exactly the version in the package's `peerDependencies` (`6.0.0-beta.2` today). Upgrade it in the same change as the agent package.
13
13
  - **AI SDK:** `ai` 7.0.128 or newer for `@statelyai/agent/ai-sdk`, which imports `experimental_decide`. An older `ai` fails at import time with `does not provide an export named 'experimental_decide'`. Adapter SDKs are optional peers with no version range, so npm installs the core next to any `ai`, `openai`, `@tanstack/ai`, or `ajv`.
14
14
  - **Ajv:** `ajv` 8.20.0 or newer for `@statelyai/agent/validate`, which imports `ajv/dist/2020.js`. Ajv 6 installs, then fails when that subpath is imported.
15
15