@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
package/docs/index.md CHANGED
@@ -11,7 +11,7 @@ Stately Agent is XState plus typed model requests, decisions, and host executors
11
11
  ## Start here
12
12
 
13
13
  - Greenfield, a new agent: [Quickstart](quickstart.md), then [Thinking in state machines](thinking-in-state-machines.md) or a copied [agent pattern](patterns.md).
14
- - Brownfield, an existing agent loop: [Migrating from a loop](from-a-loop.md), or the shipped `loop-to-machine` skill in `node_modules/@statelyai/agent/skills/`.
14
+ - Brownfield, an existing agent loop: [Migrating from a loop](from-a-loop.md), or the [`loop-to-machine`](https://github.com/statelyai/skills/blob/main/plugins/stately-agent/skills/loop-to-machine/SKILL.md) skill from [statelyai/skills](https://github.com/statelyai/skills).
15
15
  - Brownfield, an existing async workflow: [Strangler-fig retrofit](strangler-fig.md). Wrap it unchanged with `wrapWorkflow`, then move one phase at a time into states, checked with `checkParity`.
16
16
  - [Choosing a run mode](choosing-a-run-mode.md)
17
17
  - [Advanced: bare XState actors and hand-written executors](advanced.md)
@@ -23,9 +23,7 @@ Stately Agent is XState plus typed model requests, decisions, and host executors
23
23
  | `runAgent` | Run a machine to done or idle; the default entry point |
24
24
  | `setupAgent` | Schema-first XState setup with Agent request actors |
25
25
  | `createAgentRuntime` | Advanced, own the loop: bind executors, expose one durable transition loop |
26
- | `runToQuiescence` | Advanced, own the loop: drive a runtime to done, idle, or error |
27
26
  | `getInteraction` / `eventFromInteraction` | Render and validate human interactions |
28
- | `decideNext` | Ask a model for one event a plain XState machine accepts |
29
27
  | `describeMachine` | Render a machine as plain text for a model |
30
28
  | `wrapWorkflow` | Wrap an existing async workflow, unchanged, as a machine |
31
29
  | `isAgentIdle` | Distinguish a human wait from a stuck settled machine |
@@ -36,13 +34,15 @@ Stately Agent is XState plus typed model requests, decisions, and host executors
36
34
  | Entry | Purpose |
37
35
  | ------------------------------ | ------------------------------------------------------------------------------------------ |
38
36
  | `@statelyai/agent` | Authoring, running, human interaction, and the executor contract |
37
+ | `@statelyai/agent/evals` | Trace analytics: `foldTraces`, `traceCoverage`, `repeatRuns`, `judgeAgreement` |
39
38
  | `@statelyai/agent/testing` | `lintAgentMachine`, `simulateAgent`, `canReach`, `checkParity`, trajectories, seams |
40
39
  | `@statelyai/agent/log` | The event log: `replay`, `forkEventLog`, `getDecisionAttempts`, hand-built entries, stores |
41
40
  | `@statelyai/agent/ai-sdk` | `createAiSdkExecutors`: the Vercel AI SDK adapter, for language and decision models |
42
41
  | `@statelyai/agent/openai` | Executors over the raw `openai` package |
43
42
  | `@statelyai/agent/tanstack-ai` | `createTanStackAiExecutors`, the TanStack AI adapter |
44
- | `@statelyai/agent/machines` | Preset machines: tool loop, sequential, parallel, router, supervisor, handoff |
43
+ | `@statelyai/agent/machines` | `createApprovalBatchMachine`, a preset that gates a turn's tool calls on approval |
45
44
  | `@statelyai/agent/otel` | OpenTelemetry trace handler |
45
+ | `@statelyai/agent/policy` | `decideNext` for any XState snapshot, and `createPolicyDecider` for a policy machine |
46
46
  | `@statelyai/agent/validate` | JSON workflow config validation and `verifyAgentConfig` pre-run gates |
47
47
 
48
48
  Core has no runtime dependency on the AI SDK.
package/docs/judgments.md CHANGED
@@ -236,7 +236,7 @@ A decision model is any object that implements the AI SDK's decision-model spec:
236
236
 
237
237
  ```ts
238
238
  import type { Experimental_DecisionModel } from "ai";
239
- import { runToQuiescence } from "@statelyai/agent";
239
+ import { runAgent } from "@statelyai/agent";
240
240
  import { expect, test } from "vitest";
241
241
 
242
242
  const scripted: Experimental_DecisionModel = {
@@ -254,12 +254,10 @@ const scripted: Experimental_DecisionModel = {
254
254
  };
255
255
 
256
256
  test("routes a double charge to billing", async () => {
257
- const result = await runToQuiescence(
258
- createAgentRuntime(triageMachine, {
259
- actors: { classifyTicket: createClassifyTicket(scripted) },
260
- }),
261
- { input: { ticket: "I was charged twice this month.", plan: "pro" } },
262
- );
257
+ const result = await runAgent(triageMachine, {
258
+ actors: { classifyTicket: createClassifyTicket(scripted) },
259
+ input: { ticket: "I was charged twice this month.", plan: "pro" },
260
+ });
263
261
 
264
262
  expect(result.status === "done" && result.output).toEqual({ team: "billing", urgent: false });
265
263
  });
@@ -21,10 +21,10 @@ Both libraries represent agent control flow explicitly. Stately Agent uses XStat
21
21
  | Conditional edge, a response to an event | A guarded [transition](machines.md#transitions); when the model picks the branch, `agent.decide` with `allowedEvents` |
22
22
  | `Annotation` reducer | No reducers. A transition returns a partial `context` patch, so the merge is written where the change happens |
23
23
  | `withStructuredOutput(schema)` | `schemas: { output }` on the request; the parsed value arrives as `output.result` in the invoke's `onDone` |
24
- | Interrupt | A resting state that settles `runToQuiescence` as idle. See [Human in the loop](human-in-the-loop.md) |
25
- | `new Command({ resume })` | A typed machine event: `runToQuiescence(createAgentRuntime(machine, {}), { snapshot, event })`, or `{ events, event }` from the log |
24
+ | Interrupt | A resting state that settles `runAgent` as idle. See [Human in the loop](human-in-the-loop.md) |
25
+ | `new Command({ resume })` | A typed machine event: `runAgent(machine, { snapshot, event })`, or `{ events, event }` from the log |
26
26
  | Checkpointer | A persisted XState snapshot the host stores. See [Persistence](persistence.md) |
27
- | `config.configurable.thread_id` | `runToQuiescence(createAgentRuntime(machine, { store, threadId }), {})`, which reads and appends the thread's [event log](event-log.md) |
27
+ | `config.configurable.thread_id` | `runAgent(machine, { store, threadId })`, which reads and appends the thread's [event log](event-log.md) |
28
28
  | Stream events | `onTrace` (`stream.chunk`) plus XState inspection |
29
29
  | Subgraph | Invoked child machine |
30
30
 
@@ -63,9 +63,9 @@ const workflow = new StateGraph(GraphState)
63
63
  .addEdge("rewriteQuery", "retrieve");
64
64
  ```
65
65
 
66
- The machine names the same three things: the model call is a request, the routing is a state, and the counter is a patch on the transition that causes it.
66
+ The machine names the same three things: the model call is a request, the routing is a state, and the counter is a patch on the transition that causes it. This excerpt omits the retrieval and generation states.
67
67
 
68
- ```ts
68
+ ```ts no-check
69
69
  import { z } from "zod";
70
70
  import { setupAgent } from "@statelyai/agent";
71
71
 
@@ -149,7 +149,7 @@ The differences worth planning for:
149
149
  - [Persistence](persistence.md) covers the checkpointer and `thread_id`: the event log, `store`, `threadId`, and host-owned `persist()`.
150
150
  - [Migrating from a hand-rolled loop](from-a-loop.md) covers the same conversion from a `while` loop.
151
151
 
152
- A machine can run with `runToQuiescence`, an application-owned XState actor, a pure `initialTransition` / `transition` loop, or XState's durable runtime. The artifact does not change. See [Choosing a run mode](choosing-a-run-mode.md).
152
+ A machine can run with `runAgent`, an application-owned XState actor, a pure `initialTransition` / `transition` loop, or XState's durable runtime. The artifact does not change. See [Choosing a run mode](choosing-a-run-mode.md).
153
153
 
154
154
  ## Ported LangGraph examples
155
155
 
@@ -304,13 +304,11 @@ other agent machine. Pass executors and observation handlers when creating the
304
304
  runtime; pass machine input when starting it.
305
305
 
306
306
  ```ts no-check
307
- const result = await runToQuiescence(
308
- createAgentRuntime(machine, {
309
- executors: { decide, generateText },
310
- on: { TRIAGED: (event) => console.log(event.route) },
311
- }),
312
- { input: { ticket: "My download link 404s." } },
313
- );
307
+ const result = await runAgent(machine, {
308
+ executors: { decide, generateText },
309
+ on: { TRIAGED: (event) => console.log(event.route) },
310
+ input: { ticket: "My download link 404s." },
311
+ });
314
312
  ```
315
313
 
316
314
  Executors return these shapes.
@@ -325,13 +323,10 @@ A run settles in one of two ways.
325
323
  - `{ status: 'done', output }`: the machine reached a final state.
326
324
  - `{ status: 'idle', snapshot }`: the machine paused at an idle state. Persist `snapshot`, then resume when the event arrives.
327
325
 
328
- <!-- viz: run lifecycle: createAgentRuntime -> runToQuiescence -> done or idle, with idle resuming through a fresh runtime plus snapshot and event -->
326
+ <!-- viz: run lifecycle: runAgent -> done or idle, with idle resuming through a fresh runAgent call plus snapshot and event -->
329
327
 
330
328
  ```ts no-check
331
- result = await runToQuiescence(createAgentRuntime(machine, { executors }), {
332
- snapshot,
333
- event: { type: "APPROVE" },
334
- });
329
+ result = await runAgent(machine, { executors, snapshot, event: { type: "APPROVE" } });
335
330
  ```
336
331
 
337
332
  > **Note:** A run settles idle only after its mailbox is empty and no child,
@@ -408,9 +403,9 @@ The machine's `description` is its goal, so it leads the text. An excerpt:
408
403
  Machine ticket
409
404
  Goal: Answer the customer's ticket so they never write back.
410
405
  States (initial: triaging):
411
- triaging — Decide how to handle the ticket
406
+ triaging - Decide how to handle the ticket
412
407
  on ESCALATE → escalated
413
- on REPLY → drafting; sets tone — Draft a reply
408
+ on REPLY → drafting; sets tone - Draft a reply
414
409
  invoke agent.decide
415
410
  error → escalated
416
411
  checking (choice)
@@ -418,10 +413,10 @@ States (initial: triaging):
418
413
  choice if isRetryable → drafting
419
414
  choice else → escalated
420
415
  sent (final) [tags: done]
421
- escalated (final) — A human owns it now
416
+ escalated (final) - A human owns it now
422
417
  Events:
423
- REPLY — Answer the ticket directly
424
- tone: "formal" | "casual" — Reply tone
418
+ REPLY - Answer the ticket directly
419
+ tone: "formal" | "casual" - Reply tone
425
420
  ```
426
421
 
427
422
  - **States:** one line each, indented by depth, with the type, tags, `meta.interaction.label`, and description. Pass `snapshot` to mark the active states with `*`.
@@ -1,133 +1,32 @@
1
1
  ---
2
2
  title: Preset machines
3
- description: Factories for proven agent shapes (tool loop, sequential, router, parallel, loop, supervisor, handoff, approval batch) that return ordinary, inspectable agent machines.
3
+ description: createApprovalBatchMachine, a factory that gates one model turn's tool calls on approval and returns an ordinary, inspectable agent machine.
4
4
  ---
5
5
 
6
6
  > **Alpha:** `@statelyai/agent` 2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: [github.com/statelyai/agent](https://github.com/statelyai/agent/issues).
7
7
 
8
8
  ## Overview
9
9
 
10
- `@statelyai/agent/machines` ships factories for common agent shapes. Each factory is a thin composition over `setupAgent(...).createMachine(...)`.
10
+ `@statelyai/agent/machines` ships `createApprovalBatchMachine`, a factory over `setupAgent(...).createMachine(...)`.
11
11
 
12
12
  - The result is an ordinary machine, with the same states, guards, snapshots, and `lintAgentMachine` support as a machine you write yourself.
13
- - Executors stay separate. Presets name no SDK, so the host passes `executors` to `runToQuiescence`.
14
- - Each preset is around 100 lines of states that you can read, diagram, and copy into your own project.
13
+ - Executors stay separate. The preset names no SDK.
15
14
 
16
- ```ts
17
- import { tool } from "ai";
18
- import { openai } from "@ai-sdk/openai";
19
- import { z } from "zod";
20
- import { runToQuiescence } from "@statelyai/agent";
21
- import { createToolLoopMachine } from "@statelyai/agent/machines";
22
- import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
23
-
24
- // Model IDs here are illustrative; substitute your provider's current models.
25
- const models = { quick: openai("gpt-6-luna") };
26
-
27
- const calculate = tool({
28
- description: "Evaluate an arithmetic expression.",
29
- inputSchema: z.object({ expression: z.string() }),
30
- execute: async ({ expression }) => Number(expression),
31
- });
32
-
33
- const machine = createToolLoopMachine({
34
- model: "quick",
35
- instructions: "Answer using the tools.",
36
- tools: { calculate },
37
- maxSteps: 5,
38
- });
39
-
40
- const result = await runToQuiescence(
41
- createAgentRuntime(machine, { executors: createAiSdkExecutors({ models }) }),
42
- { input: { prompt: "What is 42 times 17?" } },
43
- );
44
- ```
45
-
46
- Snapshots and log entries carry `machine.version` automatically. See [Versioning](#versioning).
47
-
48
- ## Preset taxonomy
49
-
50
- Three questions separate the seven model-driven presets. `createApprovalBatchMachine` is the odd one out: it makes no model call.
51
-
52
- - Who runs the work? One request in `toolLoop`, a fixed chain in `sequential`, or named sub-units in the rest.
53
- - Who picks the next unit? The author in `sequential`, `parallel`, and `loop`. The model in `router`, `supervisor`, and `handoff`.
54
- - Does control come back? Delegation returns in `supervisor`. Routing ends the run in `router`. Handoff transfers control permanently in `handoff`.
55
-
56
- | Preset | Shape | Model chooses | Control returns |
57
- | ---------------------------- | ------------------------------------------------------------ | -------------------------------- | ---------------------- |
58
- | `createToolLoopMachine` | One request, host-run tool loop | tools | n/a |
59
- | `createSequentialMachine` | Prompt chain, step by step | nothing | n/a |
60
- | `createRouterMachine` | One decision picks one destination | the route | no, the run ends there |
61
- | `createParallelMachine` | Static fan-out, joined | nothing | yes, at the join |
62
- | `createLoopMachine` | Bounded repeat | nothing | yes, each iteration |
63
- | `createSupervisorMachine` | Delegate, accumulate, repeat | the worker, or `FINISH` | yes, every turn |
64
- | `createHandoffMachine` | Peer swarm, `activeAgent` names the agent that runs the turn | n/a (host sends `transfer_to_*`) | no, transfer is final |
65
- | `createApprovalBatchMachine` | One child per proposed tool call: approve, then execute | nothing (policy or person) | n/a |
66
-
67
- ## Config names
68
-
69
- Every preset uses the same vocabulary:
70
-
71
- | Option | Meaning |
72
- | -------------- | ------------------------------------------------------------------------------------------ |
73
- | `model` | A model ref or a `models` alias. A `model` on an entry overrides the factory default. |
74
- | `instructions` | The system prompt. |
75
- | `tools` | Tools the host runs inside one request. |
76
- | `outputSchema` | Structured output. Omit it for plain text. |
77
- | `maxSteps` | The bound on a request's host-side tool loop. It lowers to the request's typed `maxSteps`. |
78
- | `maxTurns` | The bound on a machine loop or delegation count. It is enforced by a guard. |
79
-
80
- Worker, route, branch, and agent entries are a record. The key is the entry's `name`, and each entry carries a `description` that the deciding model reads.
81
-
82
- An entry is either an inline request, written as `{ description, instructions, model, outputSchema, tools }`, or a child machine, written as `{ description, machine, input? }`. Child machines are registered as actor sources, so `runToQuiescence` binds their executors too.
83
-
84
- ## The presets
85
-
86
- ### `createToolLoopMachine`
87
-
88
- One text request carries the `tools`, and the host runs the tool loop inside that request. `maxSteps` bounds the loop through the request's typed `maxSteps` field. The states are `answering` and `done`.
89
-
90
- This preset is the default for tool use. It does not add machine states, and it sets no request `metadata`. To gate the calls on approval, run them through [`createApprovalBatchMachine`](#createapprovalbatchmachine), or eject. See [Ejection](#ejection).
91
-
92
- ### `createSequentialMachine`
93
-
94
- A prompt chain with one state per step. Each step's output feeds the next step. A step's `prompt(ctx)` can read `{ prompt, results, previous }`. Without a `prompt`, the step's default prompt is the previous step's output.
95
-
96
- <!-- viz: state diagram of createSequentialMachine: step1 -> step2 -> step3 -> done, each step invoking one request and writing into results -->
97
-
98
- ### `createRouterMachine`
99
-
100
- One `agent.decide` picks exactly one declared route, then the machine runs it. Route events are named `ROUTE_<name>`. Build the string with `routeEventType(name)` when you send or assert these events. Undeclared routes have no event, no state, and no transition, so the model cannot take them. Add `fallback` to target a state when the decision fails. Without `fallback`, a failed decision errors the run.
101
-
102
- <!-- viz: state diagram of createRouterMachine: routing state invoking agent.decide, one ROUTE_<name> transition per declared route, plus the optional fallback target -->
103
-
104
- ### `createParallelMachine`
105
-
106
- Static parallel work with one region per branch. All branches run concurrently and join into a keyed `results` object. Dynamic fan-out remains ordinary XState actor composition.
107
-
108
- <!-- viz: state diagram of createParallelMachine: parallel state with one region per branch, all joining into a single done state with keyed results -->
109
-
110
- ### `createLoopMachine`
111
-
112
- A bounded repeat. The machine runs `body`, evaluates `until` over `{ prompt, iterations, results, last }`, then repeats or stops. `maxTurns` is a guard, so the loop terminates even if `until` never returns true.
113
-
114
- ### `createSupervisorMachine`
115
-
116
- Each turn, one `agent.decide` picks a worker or finishes. `maxTurns` bounds the delegations and defaults to 6. It is a machine budget, and it never lowers a request's `maxSteps`. Worker events are named `DELEGATE_<name>`, built with `delegateEventType(name)`. The finish event is `FINISH`, exported as `FINISH_EVENT_TYPE`. Results accumulate in context and are rendered into the next decision. When the `maxTurns` budget is spent, every delegate is removed from the candidate set, and a guard rejects a delegate event if one is chosen anyway.
117
-
118
- <!-- viz: state diagram of createSupervisorMachine: deciding -> DELEGATE_<name> -> worker state -> back to deciding, with FINISH -> done and the maxTurns guard -->
119
-
120
- ### `createHandoffMachine`
15
+ Other shapes are runnable examples to copy and edit. See [Agent patterns](patterns.md) for the full list.
121
16
 
122
- A peer swarm. `context.activeAgent` names the agent that runs the current turn. After the turn, the machine settles idle in `waiting`. A `transfer_to_<name>` event, built with `transferEventType(name)`, changes `activeAgent` and re-routes. There is no final state. The conversation ends when the host stops resuming it. Persist the idle snapshot between turns.
17
+ - Prompt chain: [prompt-chaining](https://github.com/statelyai/agent/blob/next/examples/prompt-chaining/index.ts)
18
+ - Supervisor: [agent-supervisor](https://github.com/statelyai/agent/blob/next/examples/agent-supervisor/index.ts)
19
+ - Handoff: [swarm-handoff](https://github.com/statelyai/agent/blob/next/examples/swarm-handoff/index.ts)
20
+ - Fan-out: [parallel-streams](https://github.com/statelyai/agent/blob/next/examples/parallel-streams/index.ts) and [map-reduce](https://github.com/statelyai/agent/blob/next/examples/map-reduce/index.ts)
21
+ - Tool calls with review: [review-tool-calls](https://github.com/statelyai/agent/blob/next/examples/review-tool-calls/index.ts)
123
22
 
124
- ### `createApprovalBatchMachine`
23
+ ## `createApprovalBatchMachine`
125
24
 
126
25
  One model turn's tool calls, each approved or rejected on its own. Only approved calls execute. No model call: the host maps the turn's calls to `input.calls` and feeds `output.results` back as tool results. See [Tools](tools.md#approval-gate).
127
26
 
128
27
  ```ts
129
28
  import { createAsyncLogic } from "xstate";
130
- import { createAgentRuntime, runToQuiescence } from "@statelyai/agent";
29
+ import { runAgent } from "@statelyai/agent";
131
30
  import { createApprovalBatchMachine } from "@statelyai/agent/machines";
132
31
 
133
32
  const machine = createApprovalBatchMachine({
@@ -141,10 +40,10 @@ const machine = createApprovalBatchMachine({
141
40
  }),
142
41
  });
143
42
 
144
- const paused = await runToQuiescence(createAgentRuntime(machine), {
43
+ const paused = await runAgent(machine, {
145
44
  input: { calls: [{ id: "call_1", name: "deleteFile", args: { path: "a.txt" } }] },
146
45
  });
147
- const result = await runToQuiescence(createAgentRuntime(machine), {
46
+ const result = await runAgent(machine, {
148
47
  snapshot: paused.persist(),
149
48
  event: { type: "APPROVE", callId: "call_1" },
150
49
  });
@@ -165,22 +64,20 @@ const result = await runToQuiescence(createAgentRuntime(machine), {
165
64
 
166
65
  A preset is a starting point. When you need one more state, a human gate, a different bound, or your own typed context:
167
66
 
168
- 1. Open the preset's source at `src/machines/<preset>.ts`. It is one small file of states.
67
+ 1. Open the preset's source at `src/machines/approval-batch.ts`.
169
68
  2. Copy it into your project and edit the `setupAgent(...)` call directly.
170
69
  3. Run it as before. The copied machine runs, lints, and persists the same way.
171
70
 
172
71
  Examples to eject toward:
173
72
 
174
73
  - [review-tool-calls](https://github.com/statelyai/agent/blob/next/examples/review-tool-calls/index.ts): an approval gate.
175
- - [reflection-writer](https://github.com/statelyai/agent/blob/next/examples/reflection-writer/index.ts): a critique loop.
176
- - [hierarchical-teams](https://github.com/statelyai/agent/blob/next/examples/hierarchical-teams/index.ts) and [swarm-handoff](https://github.com/statelyai/agent/blob/next/examples/swarm-handoff/index.ts): multi-agent topologies.
177
74
 
178
75
  ## Versioning
179
76
 
180
- Every preset machine carries `version: "1"`, using XState's standard `createMachine({ version })` prop. This is the machine's own topology version. It is unrelated to the `@statelyai/agent` package version. Native persisted snapshots and trace events carry that version:
77
+ The preset machine carries `version: "1"`, using XState's standard `createMachine({ version })` prop. This is the machine's own topology version. It is unrelated to the `@statelyai/agent` package version. Native persisted snapshots and trace events carry that version:
181
78
 
182
79
  ```ts
183
- const result = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
80
+ const result = await runAgent(machine, { executors, input });
184
81
  // result.persist().version === "1"
185
82
  ```
186
83
 
@@ -189,7 +86,7 @@ The versioning policy:
189
86
  - The version identifies the machine's topology, not the release that built it. Prompt wording can change without a version bump.
190
87
  - A topology change that an old snapshot cannot restore bumps the version. Migrate it with XState's machine-level `migrate(snapshot, fromVersion)`.
191
88
 
192
- The same prop works for your own machines. Set `version` in `createMachine(...)` and `runToQuiescence` stamps that value instead of the structural hash, which changes on any edit.
89
+ The same prop works for your own machines. Set `version` in `createMachine(...)` and `runAgent` stamps that value instead of the structural hash, which changes on any edit.
193
90
 
194
91
  ## Related
195
92
 
package/docs/machines.md CHANGED
@@ -39,7 +39,7 @@ const agentSetup = setupAgent({
39
39
 
40
40
  <!-- machine input validation from src/run-agent.ts and the input schema retained by src/setup-agent.ts -->
41
41
 
42
- `runToQuiescence` validates supplied machine input before the
42
+ `runAgent` validates supplied machine input before the
43
43
  actor starts. Defaults and transforms from the input schema reach the context
44
44
  factory and trace; invalid input throws `AgentError` with code
45
45
  `invalid-machine-input`. Calling XState's `createActor` directly does not run
@@ -65,7 +65,7 @@ In a `HEAL` transition, `event.amount` is a `number`. Reading a field the event
65
65
 
66
66
  ### Emitted event schemas
67
67
 
68
- Emitted event schemas type the progress events a machine emits with `enq.emit(...)`. Hosts receive them through `runToQuiescence`'s `on` handlers. Declare them under `emitted`:
68
+ Emitted event schemas type the progress events a machine emits with `enq.emit(...)`. Hosts receive them through `runAgent`'s `on` handlers. Declare them under `emitted`:
69
69
 
70
70
  ```ts no-check
71
71
  // setupAgent({ ... })
@@ -226,16 +226,16 @@ The canonical form covers most machines: a `models` registry, flat schema fields
226
226
 
227
227
  Each alternate form handles one specific need:
228
228
 
229
- | Form | Use it when |
230
- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
231
- | `createAgentSchemas` pack, passed as `setupAgent({ schemas })` | You share one schema set across several machines or the [step helpers](steps.md). |
232
- | String model refs with `resolveModel` (`model: 'openai/gpt-6-luna'`, `createAiSdkExecutors({ resolveModel })`) | The machine must not name concrete models, for portability or for refs loaded from JSON [config](machines-as-data.md). |
233
- | `createTextLogic`, a standalone request value | A request is exported, reused across states or machines, or unit-tested on its own. See [Text requests](text-requests.md#reusable-request-logic-with-createtextlogic). |
234
- | `logic.withExecutor(...)` | You bind execution onto one logic instead of the whole host, so a plain `createActor` runs it without [`runToQuiescence`](hosts.md#write-your-own-host-loop)'s executor slots. Registered dynamic spawns inherit through `actors`. See [Multi-agent composition](multi-agent.md#collecting-dynamic-children). |
229
+ | Form | Use it when |
230
+ | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | `createAgentSchemas` pack, passed as `setupAgent({ schemas })` | You share one schema set across several machines or the [step helpers](steps.md). |
232
+ | String model refs with `resolveModel` (`model: 'openai/gpt-6-luna'`, `createAiSdkExecutors({ resolveModel })`) | The machine must not name concrete models, for portability or for refs loaded from JSON [config](machines-as-data.md). |
233
+ | `createTextLogic`, a standalone request value | A request is exported, reused across states or machines, or unit-tested on its own. See [Text requests](text-requests.md#reusable-request-logic-with-createtextlogic). |
234
+ | `logic.withExecutor(...)` | You bind execution onto one logic instead of the whole host, so a plain `createActor` runs it without [`runAgent`](hosts.md#write-your-own-host-loop)'s executor slots. Registered dynamic spawns inherit through `actors`. See [Multi-agent composition](multi-agent.md#collecting-dynamic-children). |
235
235
 
236
236
  ## Machine creation
237
237
 
238
- `agentSetup.createMachine` is XState's `createMachine` with the agent's schemas and actors already bound. It registers the machine, so the step helpers and [`runToQuiescence`](hosts.md) resolve its schemas and actors without you passing them again.
238
+ `agentSetup.createMachine` is XState's `createMachine` with the agent's schemas and actors already bound. It registers the machine, so the step helpers and [`runAgent`](hosts.md) resolve its schemas and actors without you passing them again.
239
239
 
240
240
  <!-- viz: state diagram for the answering machine below: initial state `answering` invoking the `answerQuestion` request, onDone -> final state `done` producing { answer } -->
241
241
 
@@ -406,12 +406,12 @@ The `onDone` handler receives the actor's `output`. For a text request that is `
406
406
 
407
407
  ### Inline text requests
408
408
 
409
- <!-- inline agent.generateText + runToQuiescence, from src/setup-agent.ts and src/index.ts -->
409
+ <!-- inline agent.generateText + runAgent, from src/setup-agent.ts and src/index.ts -->
410
410
 
411
411
  For a one-off text call, invoke `agent.generateText` inline. Move it to a named [request](text-requests.md) once it is reused or worth testing:
412
412
 
413
413
  ```ts no-check
414
- import { createAgentRuntime, parseOutput, runToQuiescence } from "@statelyai/agent";
414
+ import { parseOutput, runAgent } from "@statelyai/agent";
415
415
 
416
416
  // ...
417
417
  generating: {
@@ -431,7 +431,7 @@ generating: {
431
431
  },
432
432
 
433
433
  // ...
434
- await runToQuiescence(createAgentRuntime(machine, { executors: createAiSdkExecutors({ models }) }), { input });
434
+ await runAgent(machine, { executors: createAiSdkExecutors({ models }), input });
435
435
  ```
436
436
 
437
437
  Give an invoke an explicit `id` when the host needs a stable occurrence identity. XState owns invoke identity and snapshot restoration.
@@ -487,7 +487,7 @@ waiting: {
487
487
 
488
488
  How `after` runs depends on the host:
489
489
 
490
- - Under [`runToQuiescence`](hosts.md), the timer runs live. A pending `after` does not count as idle, so `runToQuiescence` waits for it and continues.
490
+ - Under [`runAgent`](hosts.md), the timer runs live. A pending `after` does not count as idle, so `runAgent` waits for it and continues.
491
491
  - Under a custom or durable XState host, timers follow that framework's runtime adapter. See [the runtime loop](steps.md).
492
492
 
493
493
  ## Related
@@ -18,7 +18,7 @@ const executors = createAiSdkExecutors({
18
18
  models: { quick: someLanguageModel, careful: anotherLanguageModel },
19
19
  });
20
20
 
21
- await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
21
+ await runAgent(machine, { executors, input });
22
22
  ```
23
23
 
24
24
  ## Declaring models once
@@ -122,7 +122,7 @@ import { z } from "zod";
122
122
  import { Agent } from "@mastra/core/agent";
123
123
  import { createTool } from "@mastra/core/tools";
124
124
  import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
125
- import { runToQuiescence } from "@statelyai/agent";
125
+ import { runAgent } from "@statelyai/agent";
126
126
 
127
127
  const executors = createAiSdkExecutors({ models });
128
128
 
@@ -132,9 +132,7 @@ const startWorkflow = createTool({
132
132
  inputSchema: z.object({ prompt: z.string() }),
133
133
  outputSchema: z.object({ status: z.string() }),
134
134
  execute: async ({ prompt }) => {
135
- const result = await runToQuiescence(createAgentRuntime(machine, { executors }), {
136
- input: { prompt },
137
- });
135
+ const result = await runAgent(machine, { executors, input: { prompt } });
138
136
  return { status: result.status };
139
137
  },
140
138
  });
@@ -172,14 +170,12 @@ export default {
172
170
  async fetch(request, env) {
173
171
  // Model IDs here are illustrative; substitute your provider's current models.
174
172
  const workersai = createWorkersAI({ binding: env.AI });
175
- const result = await runToQuiescence(
176
- createAgentRuntime(machine, {
177
- executors: createAiSdkExecutors({
178
- models: { quick: workersai("@cf/meta/llama-3.1-8b-instruct") },
179
- }),
173
+ const result = await runAgent(machine, {
174
+ executors: createAiSdkExecutors({
175
+ models: { quick: workersai("@cf/meta/llama-3.1-8b-instruct") },
180
176
  }),
181
- { input: await request.json() },
182
- );
177
+ input: await request.json(),
178
+ });
183
179
  return Response.json(result);
184
180
  },
185
181
  };
@@ -198,14 +194,12 @@ import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
198
194
  // Model IDs here are illustrative; substitute your provider's current models.
199
195
  const ollama = createOpenAI({ baseURL: "http://localhost:11434/v1", apiKey: "ollama" });
200
196
 
201
- await runToQuiescence(
202
- createAgentRuntime(machine, {
203
- executors: createAiSdkExecutors({
204
- models: { quick: ollama("llama3.1") },
205
- }),
197
+ await runAgent(machine, {
198
+ executors: createAiSdkExecutors({
199
+ models: { quick: ollama("llama3.1") },
206
200
  }),
207
- { input },
208
- );
201
+ input,
202
+ });
209
203
  ```
210
204
 
211
205
  To use Groq, vLLM, Together, OpenRouter, or LM Studio, change `baseURL` and use the endpoint's real `apiKey`. Nothing else changes.
@@ -260,9 +254,9 @@ Each example is a runnable host for one provider stack.
260
254
  | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
261
255
  | [ai-sdk-host](https://github.com/statelyai/agent/blob/next/examples/ai-sdk-host/index.ts) | Vercel AI SDK, through the optional adapter |
262
256
  | [openai-sdk-host](https://github.com/statelyai/agent/blob/next/examples/openai-sdk-host/index.ts) | `createOpenAiExecutors` from `@statelyai/agent/openai`, over the raw `openai` package (Responses + Chat Completions) |
263
- | [tanstack-ai-stream](https://github.com/statelyai/agent/blob/next/examples/tanstack-ai-stream/index.ts) | `createTanStackAiExecutors` from `@statelyai/agent/tanstack-ai`, streamed to a `useChat` client over AG-UI |
264
- | [anthropic-sdk-host](https://github.com/statelyai/agent/blob/next/examples/anthropic-sdk-host/index.ts) | raw `@anthropic-ai/sdk` (Messages); structured via forced tool call, decisions via `tool_choice: { type: 'any' }` |
265
- | [langchain-host](https://github.com/statelyai/agent/blob/next/examples/langchain-host/index.ts) | LangChain `BaseChatModel` (`@langchain/core`), wrapped into the executor contract |
266
- | [mastra-host](https://github.com/statelyai/agent/blob/next/examples/mastra-host/index.ts) | Mastra `Agent` and `createTool`, bridging to `runToQuiescence` |
267
- | [cloudflare-agent-host](https://github.com/statelyai/agent/blob/next/examples/cloudflare-agent-host/index.ts) | Durable Object |
268
- | [cloudflare-workers-ai-host](https://github.com/statelyai/agent/blob/next/examples/cloudflare-workers-ai-host/index.ts) | Workers AI binding |
257
+ | [tanstack-ai-stream](https://github.com/statelyai/agent/blob/next/examples/tanstack-ai-stream/index.ts) | `createTanStackAiExecutors` from `@statelyai/agent/tanstack-ai`, streamed to a `useChat` client over AG-UI |
258
+ | [anthropic-sdk-host](https://github.com/statelyai/agent/blob/next/examples/anthropic-sdk-host/index.ts) | raw `@anthropic-ai/sdk` (Messages); structured via forced tool call, decisions via `tool_choice: { type: 'any' }` |
259
+ | [langchain-host](https://github.com/statelyai/agent/blob/next/examples/langchain-host/index.ts) | LangChain `BaseChatModel` (`@langchain/core`), wrapped into the executor contract |
260
+ | [mastra-host](https://github.com/statelyai/agent/blob/next/examples/mastra-host/index.ts) | Mastra `Agent` and `createTool`, bridging to `runAgent` |
261
+ | [cloudflare-agent-host](https://github.com/statelyai/agent/blob/next/examples/cloudflare-agent-host/index.ts) | Durable Object |
262
+ | [cloudflare-workers-ai-host](https://github.com/statelyai/agent/blob/next/examples/cloudflare-workers-ai-host/index.ts) | Workers AI binding |
@@ -4,7 +4,7 @@ Multi-agent systems are ordinary XState actor composition.
4
4
 
5
5
  ## Child machines
6
6
 
7
- Register a child machine under `actors`, invoke it from a state, and handle its typed output with `onDone`. `runToQuiescence` recursively binds Agent request actors in registered child machines.
7
+ Register a child machine under `actors`, invoke it from a state, and handle its typed output with `onDone`. `runAgent` recursively binds Agent request actors in registered child machines.
8
8
 
9
9
  ## Long-lived actors
10
10
 
@@ -66,14 +66,12 @@ try {
66
66
  ## Trace one run
67
67
 
68
68
  ```ts no-check
69
- await runToQuiescence(
70
- createAgentRuntime(machine, {
71
- executors,
72
- inspect: (event) => xstateInspector.next(event),
73
- onTrace: (event) => exporter.write(serializeTraceEvent(event)),
74
- }),
75
- { input },
76
- );
69
+ await runAgent(machine, {
70
+ executors,
71
+ inspect: (event) => xstateInspector.next(event),
72
+ onTrace: (event) => exporter.write(serializeTraceEvent(event)),
73
+ input,
74
+ });
77
75
  ```
78
76
 
79
77
  Agent trace kinds are `run.start`, `request.start`, `request.end`, `request.error`, `stream.chunk`, `machine.transition`, `emit`, `usage.dropped`, and `run.end`.