@statelyai/agent 2.0.0-alpha.38 → 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 +45 -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 +131 -93
  25. package/dist/index.d.cts +73 -134
  26. package/dist/index.d.mts +73 -134
  27. package/dist/index.mjs +112 -70
  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 +5 -4
  90. package/docs/environment-and-policy.md +1 -1
  91. package/docs/evals.md +57 -43
  92. package/docs/event-log.md +13 -15
  93. package/docs/from-a-loop.md +3 -3
  94. package/docs/generate-machines.md +4 -4
  95. package/docs/hosts.md +20 -27
  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 +7 -12
  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 +10 -20
  107. package/docs/quickstart.md +3 -3
  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
@@ -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
 
@@ -17,7 +17,7 @@ Usage is available at three layers, listed from coarsest to finest.
17
17
 
18
18
  The first two layers are observational. Only the third can change what the agent does.
19
19
 
20
- <!-- viz: usage flow: executor result -> runToQuiescence aggregation into result.usage, -> onResult/onTrace on the host, -> @agent.usage event into machine context and guards -->
20
+ <!-- viz: usage flow: executor result -> runAgent aggregation into result.usage, -> onResult/onTrace on the host, -> @agent.usage event into machine context and guards -->
21
21
 
22
22
  ## The usage result
23
23
 
@@ -26,7 +26,7 @@ The first two layers are observational. Only the third can change what the agent
26
26
  Every settled `AgentRunResult` carries `usage`, on all three variants: `done`, `idle`, and `error`.
27
27
 
28
28
  ```ts
29
- const result = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
29
+ const result = await runAgent(machine, { executors, input });
30
30
 
31
31
  result.usage.modelCalls; // number, always present
32
32
  result.usage.totalTokens; // number | undefined (only calls that reported it)
@@ -44,7 +44,7 @@ Four things affect how you read these numbers.
44
44
  - Usage is per run, not per conversation. A resumed run counts only its own calls, not the history behind `snapshot` or `events`. Add prior results' totals yourself for a conversation-wide figure.
45
45
  - A tool loop is one request but several model calls. An executor reports its steps as `modelCalls` on its result, and the adapters do. An executor that reports none counts as one call.
46
46
  - Judgments are not counted. An `experimental_decide` actor is an ordinary actor, so its calls appear in neither `usage` nor `maxModelCalls`. See [Judgments](judgments.md).
47
- - Usage comes from your executor. `runToQuiescence` reads `usage` from the raw executor result. That is the `usage` field alongside `result`, on the flat field names the AI SDK also uses, from an adapter or any custom executor following that shape. Non-finite values are dropped.
47
+ - Usage comes from your executor. `runAgent` reads `usage` from the raw executor result. That is the `usage` field alongside `result`, on the flat field names the AI SDK also uses, from an adapter or any custom executor following that shape. Non-finite values are dropped.
48
48
 
49
49
  ### Billing
50
50
 
@@ -80,23 +80,21 @@ Two callbacks report usage per call. Both are live and read-only.
80
80
  - `onTrace` on a `request.end` event: `usage?: AgentCallUsage` is normalized, and present only when the executor reported usage. See [Observability](observability.md#trace-one-run).
81
81
 
82
82
  ```ts
83
- await runToQuiescence(
84
- createAgentRuntime(machine, {
85
- executors,
86
- onResult: (request, { raw }) => {
87
- const usage = (raw as { usage?: AgentCallUsage }).usage;
88
- if (usage) {
89
- console.log(request.kind, request.id, usage);
90
- }
91
- },
92
- onTrace: (event) => {
93
- if (event.type === "request.end" && event.usage) {
94
- console.log(event.request.id, event.usage.totalTokens);
95
- }
96
- },
97
- }),
98
- { input },
99
- );
83
+ await runAgent(machine, {
84
+ executors,
85
+ onResult: (request, { raw }) => {
86
+ const usage = (raw as { usage?: AgentCallUsage }).usage;
87
+ if (usage) {
88
+ console.log(request.kind, request.id, usage);
89
+ }
90
+ },
91
+ onTrace: (event) => {
92
+ if (event.type === "request.end" && event.usage) {
93
+ console.log(event.request.id, event.usage.totalTokens);
94
+ }
95
+ },
96
+ input,
97
+ });
100
98
  ```
101
99
 
102
100
  Use these for dashboards, per-tenant metering, and cost alerts. Neither can stop the run. To deliver usage to the machine, use [`@agent.usage`](#the-agentusage-event).
@@ -106,10 +104,7 @@ Use these for dashboards, per-tenant metering, and cost alerts. Neither can stop
106
104
  `maxModelCalls` caps the number of model and decision calls one run may make. The default is `100`. Decision retries count separately.
107
105
 
108
106
  ```ts
109
- const result = await runToQuiescence(
110
- createAgentRuntime(machine, { executors, maxModelCalls: 20 }),
111
- { input },
112
- );
107
+ const result = await runAgent(machine, { executors, maxModelCalls: 20, input });
113
108
 
114
109
  if (result.status === "error" && result.cause === "max-model-calls") {
115
110
  result.usage.modelCalls; // 20
@@ -128,10 +123,13 @@ if (result.status === "error" && result.cause === "max-model-calls") {
128
123
  `maxModelCalls` is per run. For a conversation that resumes once per turn, pass the calls earlier turns spent as `modelCallsSpent`. They count against `maxModelCalls` and appear in `budget.modelCalls`, but not in this run's `usage.modelCalls`.
129
124
 
130
125
  ```ts no-check
131
- const result = await runToQuiescence(
132
- createAgentRuntime(machine, { executors, maxModelCalls: 30, modelCallsSpent: thread.modelCalls }),
133
- { snapshot, event },
134
- );
126
+ const result = await runAgent(machine, {
127
+ executors,
128
+ maxModelCalls: 30,
129
+ modelCallsSpent: thread.modelCalls,
130
+ snapshot,
131
+ event,
132
+ });
135
133
  thread.modelCalls += result.usage.modelCalls;
136
134
  ```
137
135
 
@@ -172,9 +170,7 @@ function withBudget(base: AgentRequestExecutors, maxCalls: number): AgentRequest
172
170
  };
173
171
  }
174
172
 
175
- await runToQuiescence(createAgentRuntime(machine, { executors: withBudget(executors, 20) }), {
176
- input,
177
- });
173
+ await runAgent(machine, { executors: withBudget(executors, 20), input });
178
174
  ```
179
175
 
180
176
  A wrapper is still host-side. The machine cannot read its counts or react to them. For that, use `@agent.usage` and a guard.
@@ -215,7 +211,7 @@ Model-call results reach the machine with usage stripped out.
215
211
  - A text invoke's `onDone` receives `{ result, messages }` only: the validated result and the executor's response messages. The runner drops the rest of the executor result, including usage (`src/run-agent.ts`).
216
212
  - A decision delivers only the chosen event. `resolveDecision` returns the validated event and drops the executor's `usage` (`src/decision.ts`).
217
213
 
218
- `@agent.usage` carries the tokens instead. After every settled model call that reported usage, `runToQuiescence` delivers the event to the machine, so `context` can fold it and guards can read it. You can then keep both counters in `context`: increment turns in `onDone`, and fold tokens in the `@agent.usage` handler.
214
+ `@agent.usage` carries the tokens instead. After every settled model call that reported usage, `runAgent` delivers the event to the machine, so `context` can fold it and guards can read it. You can then keep both counters in `context`: increment turns in `onDone`, and fold tokens in the `@agent.usage` handler.
219
215
 
220
216
  ### Rules
221
217
 
@@ -224,8 +220,8 @@ Model-call results reach the machine with usage stripped out.
224
220
  | **Not model-facing** | The `@agent.*` namespace is excluded from `getAcceptedEvents` and `parseAgentEvent`. The event is never a decision candidate, even under `allowedEvents: ['*']`, and cannot be forged from a wire message. |
225
221
  | **Durability** | The event is folded into machine context, so a native snapshot from `result.persist()` retains the counters when a later runtime resumes with `{ snapshot }`. |
226
222
  | **Run scope** | `result.usage` counts calls made during that run only. Persist cumulative counters in machine context when they must survive snapshot resume. |
227
- | **Stragglers** | A call that settles after a `runToQuiescence` leg resolved still folds into `result.usage`, but its machine event is dropped. Watch `usage.dropped` on `onTrace` if a counter looks short. |
228
- | **Coverage** | Only usage your executor reports is delivered. No `usage` on the result means no event. [`simulateAgent`](verify.md) scripts return no usage, so a token counter stays `0` under simulation. Test budgets with `runToQuiescence` and a usage-reporting mock. |
223
+ | **Stragglers** | A call that settles after a `runAgent` leg resolved still folds into `result.usage`, but its machine event is dropped. Watch `usage.dropped` on `onTrace` if a counter looks short. |
224
+ | **Coverage** | Only usage your executor reports is delivered. No `usage` on the result means no event. [`simulateAgent`](verify.md) scripts return no usage, so a token counter stays `0` under simulation. Test budgets with `runAgent` and a usage-reporting mock. |
229
225
 
230
226
  Opt in with a transition.
231
227
 
@@ -267,8 +263,8 @@ import {
267
263
  AGENT_USAGE_EVENT_TYPE,
268
264
  createAgentSchemas,
269
265
  createTextLogic,
270
- runToQuiescence,
271
266
  setupAgent,
267
+ runAgent,
272
268
  } from "@statelyai/agent";
273
269
 
274
270
  const researchStep = createTextLogic({
@@ -357,10 +353,11 @@ const executors = {
357
353
  }),
358
354
  };
359
355
 
360
- const result = await runToQuiescence(
361
- createAgentRuntime(machine, { maxModelCalls: 20, executors }),
362
- { input: { topic: "otter migration", maxTurns: 5, maxTokens: 1500 } },
363
- );
356
+ const result = await runAgent(machine, {
357
+ maxModelCalls: 20,
358
+ executors,
359
+ input: { topic: "otter migration", maxTurns: 5, maxTokens: 1500 },
360
+ });
364
361
 
365
362
  if (result.status === "done") {
366
363
  result.output.stoppedBy; // 'tokens' (3 calls, 1560 >= 1500)
@@ -397,11 +394,11 @@ deciding: {
397
394
  }
398
395
  ```
399
396
 
400
- ## Usage without runToQuiescence
397
+ ## Usage without runAgent
401
398
 
402
399
  ### Uncontrolled: `provideExecutors` + `createActor`
403
400
 
404
- Delivery is built in, but it follows the binding boundary. `provideExecutors` does not descend into invoked child machines, so a child with its own agent invokes needs its own `provideExecutors(...)` call. Until it has one, its calls report no usage anywhere. `runToQuiescence` rebinds children and reports their usage to the root. A [long-lived actor](choosing-a-run-mode.md#long-lived-actor) has no run cycle, so no stragglers are dropped either.
401
+ Delivery is built in, but it follows the binding boundary. `provideExecutors` does not descend into invoked child machines, so a child with its own agent invokes needs its own `provideExecutors(...)` call. Until it has one, its calls report no usage anywhere. `runAgent` rebinds children and reports their usage to the root. A [long-lived actor](choosing-a-run-mode.md#long-lived-actor) has no run cycle, so no stragglers are dropped either.
405
402
 
406
403
  ```ts no-check
407
404
  import { createActor, toPromise } from "xstate";
@@ -481,21 +478,19 @@ estimateCost("openai/gpt-6-luna", result.usage);
481
478
  ```ts no-check
482
479
  let spentUsd = 0;
483
480
 
484
- await runToQuiescence(
485
- createAgentRuntime(machine, {
486
- executors,
487
- onTrace: (event) => {
488
- if (event.type !== "request.end" || !event.usage) {
489
- return;
490
- }
491
- // A decision carries `model` directly; a text request carries it on `input`.
492
- const model =
493
- event.request.kind === "decision" ? event.request.model : event.request.input.model;
494
- spentUsd += estimateCost(model, event.usage);
495
- },
496
- }),
497
- { input },
498
- );
481
+ await runAgent(machine, {
482
+ executors,
483
+ onTrace: (event) => {
484
+ if (event.type !== "request.end" || !event.usage) {
485
+ return;
486
+ }
487
+ // A decision carries `model` directly; a text request carries it on `input`.
488
+ const model =
489
+ event.request.kind === "decision" ? event.request.model : event.request.input.model;
490
+ spentUsd += estimateCost(model, event.usage);
491
+ },
492
+ input,
493
+ });
499
494
  ```
500
495
 
501
496
  `@agent.usage` carries the same `model` attribution, so the machine can keep a per-model spend counter in `context` and guard on it, instead of only reporting one from the host.
@@ -163,10 +163,7 @@ The machine's own cap is `checkingRepairBudget`. It is the one the app reasons a
163
163
  `maxModelCalls` is the second cap, and a different kind. It is the host's runaway backstop, it counts every model and decision call in the run, and the machine cannot read it. See [Usage and budgets](usage-and-budgets.md#the-global-backstop-maxmodelcalls).
164
164
 
165
165
  ```ts no-check
166
- const result = await runToQuiescence(
167
- createAgentRuntime(machine, { executors, maxModelCalls: 10 }),
168
- { input },
169
- );
166
+ const result = await runAgent(machine, { executors, maxModelCalls: 10, input });
170
167
  ```
171
168
 
172
169
  With three author calls and `maxRepairs: 2`, a worst-case run makes five calls, so `result.usage.modelCalls` is `5`.
@@ -182,17 +179,15 @@ const answers: Record<string, string[]> = {
182
179
  };
183
180
  const calls: string[] = [];
184
181
 
185
- const result = await runToQuiescence(
186
- createAgentRuntime(machine, {
187
- executors: {
188
- generateText: async (request) => {
189
- calls.push(request.name);
190
- return { result: answers[request.name].shift() };
191
- },
182
+ const result = await runAgent(machine, {
183
+ executors: {
184
+ generateText: async (request) => {
185
+ calls.push(request.name);
186
+ return { result: answers[request.name].shift() };
192
187
  },
193
- }),
194
- { input: { prompt: "a turnstile" } },
195
- );
188
+ },
189
+ input: { prompt: "a turnstile" },
190
+ });
196
191
 
197
192
  expect(result.output.repairs).toBe(1);
198
193
  expect(calls).toEqual(["generateConfig", "generateConfig", "generateConfig", "repairConfig"]);