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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
  13. package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
  46. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  47. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +399 -20
  53. package/dist/testing.d.cts +196 -255
  54. package/dist/testing.d.mts +196 -255
  55. package/dist/testing.mjs +395 -20
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-Bink-Drw.cjs +2304 -0
  69. package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
  70. package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
  71. package/dist/verify-Dpz1u5Pe.mjs +2251 -0
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +311 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +136 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +54 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +516 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +487 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +81 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -192
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
@@ -0,0 +1,121 @@
1
+ # Quickstart
2
+
3
+ Install core:
4
+
5
+ ```sh
6
+ pnpm add @statelyai/agent@alpha xstate@6.0.0-beta.0 zod
7
+ ```
8
+
9
+ XState is pinned to the exact version the package's peer dependency names, because its experimental durable restoration API (`xstate/durable`) can still change between prereleases. `xstate@beta` can resolve to a newer prerelease that the package does not support.
10
+
11
+ Add `ai` and a provider only when using the optional AI SDK adapter.
12
+
13
+ ## Define and run one artifact
14
+
15
+ Save this as `agent.mts`. It uses a deterministic executor, so it needs no API
16
+ key or model SDK.
17
+
18
+ ```ts
19
+ import { z } from "zod";
20
+ import { runAgent, setupAgent } from "@statelyai/agent";
21
+
22
+ const answerOutputSchema = z.object({ answer: z.string() });
23
+
24
+ const agent = setupAgent({
25
+ context: z.object({ prompt: z.string(), answer: z.string().nullable() }),
26
+ input: z.object({ prompt: z.string() }),
27
+ output: answerOutputSchema,
28
+ requests: {
29
+ answer: {
30
+ model: "fast",
31
+ schemas: { input: z.object({ prompt: z.string() }), output: z.string() },
32
+ prompt: ({ input }) => input.prompt,
33
+ },
34
+ },
35
+ });
36
+
37
+ const machine = agent.createMachine({
38
+ context: ({ input }) => ({ prompt: input.prompt, answer: null }),
39
+ initial: "answering",
40
+ states: {
41
+ answering: {
42
+ invoke: {
43
+ src: "answer",
44
+ input: ({ context }) => ({ prompt: context.prompt }),
45
+ onDone: ({ output }) => ({
46
+ target: "done",
47
+ context: { answer: output.result },
48
+ }),
49
+ },
50
+ },
51
+ done: {
52
+ type: "final",
53
+ output: ({ context }) => ({ answer: context.answer ?? "" }),
54
+ },
55
+ },
56
+ });
57
+
58
+ const result = await runAgent(machine, {
59
+ input: { prompt: "Why state machines?" },
60
+ executors: {
61
+ generateText: async () => ({ result: "Because transitions constrain behavior." }),
62
+ },
63
+ });
64
+
65
+ if (result.status !== "done") {
66
+ throw new Error(`Unexpected status: ${result.status}`);
67
+ }
68
+
69
+ console.log(result.output.answer);
70
+ ```
71
+
72
+ Run it:
73
+
74
+ ```sh
75
+ npx tsx agent.mts
76
+ ```
77
+
78
+ It prints:
79
+
80
+ ```text
81
+ Because transitions constrain behavior.
82
+ ```
83
+
84
+ Requests have a semantic `name`, resolved `input`, model reference, schemas,
85
+ prompt/messages, and tools. The machine owns control flow; the executor owns
86
+ the provider call.
87
+
88
+ An executor is just a function, so the machine runs anywhere a function does.
89
+ When several requests each need their own canned answer, the executor routes on
90
+ `request.name`. See [Evals](evals.md#testing-without-a-provider).
91
+
92
+ ## Use a real model
93
+
94
+ Leave the states unchanged. Declare the model once by adding `models` to the
95
+ `setupAgent` call, then hand the machine to the AI SDK adapter, which reads
96
+ those models:
97
+
98
+ ```ts
99
+ import { openai } from "@ai-sdk/openai";
100
+ import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
101
+
102
+ // In the setupAgent({ ... }) call above:
103
+ // models: { fast: openai("gpt-6-luna") },
104
+
105
+ const liveResult = await runAgent(machine, {
106
+ input: { prompt: "Why state machines?" },
107
+ executors: createAiSdkExecutors(machine),
108
+ });
109
+
110
+ if (liveResult.status === "done") {
111
+ console.log(liveResult.output);
112
+ }
113
+ ```
114
+
115
+ A host that owns its own model map passes it instead:
116
+ `createAiSdkExecutors({ models: { fast: openai("gpt-6-luna") } })`.
117
+
118
+ Continue with [Choosing a run mode](choosing-a-run-mode.md),
119
+ [Messages](messages.md), and [Persistence](persistence.md). A host that drives
120
+ the transition loop itself uses `createAgentRuntime`; see
121
+ [Write your own host loop](hosts.md#write-your-own-host-loop).
@@ -0,0 +1,22 @@
1
+ # Roadmap
2
+
3
+ The design rule is XState++: add Agent logic without replacing framework behavior.
4
+
5
+ ## In scope
6
+
7
+ - Stronger request/output/event inference
8
+ - Better interaction typing
9
+ - Stream adapters
10
+ - Eval and verification ergonomics
11
+ - More Agent-specific diagnostics
12
+ - Provider adapters as optional entry points
13
+
14
+ ## Upstream or framework-owned
15
+
16
+ - Durable execution and effect recovery: XState / `xstate/durable`
17
+ - Generic fan-out and child-actor collection: XState
18
+ - State-machine lint: XState tooling
19
+ - Storage, queues, retries, and interruption policy: host frameworks
20
+ - Provider tool-loop semantics: provider SDK/executor
21
+
22
+ Stately Agent should forward these capabilities transparently rather than create parallel adapter layers.
package/docs/scope.md ADDED
@@ -0,0 +1,75 @@
1
+ ---
2
+ title: Scope and ecosystem boundaries
3
+ description: What Stately Agent owns, what the host owns, and where specialized libraries fit.
4
+ ---
5
+
6
+ > **Alpha:** `@statelyai/agent` 2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: [github.com/statelyai/agent](https://github.com/statelyai/agent/issues).
7
+
8
+ This page describes what `@statelyai/agent` implements, what your host implements, and where other libraries fit.
9
+
10
+ `@statelyai/agent` is a control-flow library, not an agent framework. It owns the executable machine: states, legal transitions, typed requests, decisions, composition, suspension, resume, and deterministic testing. The host owns every external capability.
11
+
12
+ This boundary is what makes a machine portable. An agent framework that bundles a model client, a search client, a memory store, and a server ties your control flow to those choices. Here, the machine describes work and the host decides how the work happens. The same machine runs against a different SDK, provider, or database without edits.
13
+
14
+ The machine declares what happens:
15
+
16
+ <!-- viz: ownership boundary diagram: machine (states, requests, decisions) | executors/actors seam | host capabilities (model SDK, search, memory, sandbox, store, telemetry) -->
17
+
18
+ ```ts no-check
19
+ searching: {
20
+ invoke: { src: "searchWeb", input: ({ context }) => ({ query: context.query }) },
21
+ }
22
+ ```
23
+
24
+ The host decides how it happens, binding `searchWeb` to the search client, cache, and auth it uses.
25
+
26
+ ## Ownership boundary
27
+
28
+ <!-- ownership boundaries derived from src/run-agent.ts, src/steps.ts, src/types.ts, and the host/example adapters -->
29
+
30
+ | Concern | Owner | Stately Agent integration point |
31
+ | ----------------------------------------------------------------------- | -------------------------------- | ---------------------------------------------------- |
32
+ | Workflow states, branching, loops, parallelism, retries, approval gates | Machine | Machine configuration |
33
+ | Model calls and structured output | Host or model SDK | `AgentRequestExecutors` |
34
+ | Tools and tool loops | Host or model SDK | Request `tools` and `metadata` |
35
+ | Search, RAG, crawling, data APIs | Specialized library or service | Request `tools`, executors, or `actors` |
36
+ | Long-term and semantic memory | Database or memory library | Machine `input`, plus `actors` for reads and writes |
37
+ | Sandboxes, filesystems, generated artifacts | Sandbox or workspace library | `actors`, plus artifact handles in machine context |
38
+ | MCP discovery, auth, sessions, and transport | MCP client or host framework | Request `tools` |
39
+ | Evaluation datasets, scorers, experiments, and dashboards | Evaluation library | `onTrace`, `onResult`, snapshots, and machine output |
40
+ | Snapshot persistence | Host store | XState persisted snapshots from `result.persist()` |
41
+ | Queues, schedules, leases, deployment, HTTP/SSE/WebSocket | Runtime or application framework | XState snapshots, callbacks, and emitted events |
42
+ | Telemetry export | Observability library | `onTrace` and `inspect` |
43
+
44
+ The repository examples show the orchestration shape. They are not replacement implementations of the systems listed above.
45
+
46
+ - [Deep research](https://github.com/statelyai/agent/blob/next/examples/deep-research/index.ts) models planning, concurrent research, reflection, and synthesis. The host still supplies the search implementation.
47
+ - [Hierarchical teams](https://github.com/statelyai/agent/blob/next/examples/hierarchical-teams/index.ts) models specialized child agents. External data and side effects remain host-owned.
48
+
49
+ ## Core criteria
50
+
51
+ The rules for what belongs in core live in [CONTRIBUTING.md](https://github.com/statelyai/agent/blob/next/CONTRIBUTING.md).
52
+
53
+ ## Non-goals
54
+
55
+ - A bundled visualizer. Inspection and visualization are still part of what an agent machine gives you: XState's `inspect` stream feeds the Stately inspector; Stately Studio and the VS Code extension are authoring tools. See [Inspect a run](observability.md#inspect-a-run).
56
+ - Search clients, vector stores, browser automation, code sandboxes, skills, prompt registries, eval scorers, and deployment servers. These evolve independently as specialized libraries.
57
+
58
+ ## Integration recipes
59
+
60
+ The seam between tools and actors is fixed. Tools are chosen by the model within one request. Actors are steps the machine orchestrates.
61
+
62
+ - Wrap an async capability as an XState actor and provide it through `actors`.
63
+ - Pass SDK-native tools through a request's `tools` map.
64
+ - Put host-only hints in request `metadata`. Core preserves `metadata` without interpreting it.
65
+ - Close over auth, tenant, tracing, and service clients when you construct executors or actors.
66
+ - Store JSON-safe snapshots and external artifact handles in machine context. Do not store live clients or binary resources there.
67
+ - Send traces to an evaluation or observability library through `onTrace`. The machine does not need to know the destination.
68
+
69
+ ## Related
70
+
71
+ - [Hosts and executors](hosts.md): the executor contract the host implements.
72
+ - [Use in any stack](any-stack.md): the same machine across local, server, and edge hosts.
73
+ - [The runtime loop](steps.md): the transition loop custom and durable hosts own.
74
+ - [Multi-agent composition](multi-agent.md): composing machines without an orchestration layer.
75
+ - [Post-alpha roadmap](roadmap.md): what is deliberately not shipped yet.
@@ -0,0 +1,69 @@
1
+ # Statechart policy examples
2
+
3
+ Three examples put consequential decisions in visible machine states. Each exports its machine and a runner accepting `AgentRuntimeOptions & AgentRunInit`. The consensus-review runner takes `patch` instead of `input`, because the host, not the caller, decides whether a patch is trusted. The booking-compensation and deadline-escalation runners default to real AI SDK executors (`openai("gpt-6-luna")`), which need `OPENAI_API_KEY`; pass `executors` to swap the model layer. The consensus-review runner uses no text model: each reviewer is a [judgment](judgments.md) actor built by `createReview(model)` that asks Jev one `choice` question through the AI SDK's `experimental_decide`, which needs `TYPESAFE_AI_API_KEY`; pass `judge` to swap the decision model. Override booking actors through native XState `actors` bindings.
4
+
5
+ <!-- policy example catalog derived from examples/consensus-review, examples/booking-compensation, and examples/deadline-escalation -->
6
+
7
+ | Example | Machine policy | Verification |
8
+ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
9
+ | [consensus-review](https://github.com/statelyai/agent/blob/next/examples/consensus-review/index.ts) | Three concurrent reviewers, two approvals required, failures abstain, external patches always reach a human, human fallback | Concurrent starts, reordered completions, malformed votes, an adversarial external patch, JSON restoration, native XState host parity |
10
+ | [booking-compensation](https://github.com/statelyai/agent/blob/next/examples/booking-compensation/index.ts) | Human approval before reservations; confirmed hotel unavailability compensates the flight; uncertain outcomes require reconciliation | No reservation before approval, compensation order, compensation failure, uncertain outcome, success/cancel paths |
11
+ | [deadline-escalation](https://github.com/statelyai/agent/blob/next/examples/deadline-escalation/index.ts) | Matching request identity and host timestamp determine whether approval or expiry is accepted | Deadline equality, stale identities, early expiry, late approval, JSON restoration |
12
+
13
+ Run against a real model:
14
+
15
+ ```sh
16
+ TYPESAFE_AI_API_KEY=... pnpm tsx examples/consensus-review/index.ts
17
+ OPENAI_API_KEY=... pnpm tsx examples/booking-compensation/index.ts
18
+ OPENAI_API_KEY=... pnpm tsx examples/deadline-escalation/index.ts
19
+ ```
20
+
21
+ The first CLI collects three Jev votes. The second restores an approval checkpoint and demonstrates compensation using simulated bookings. The third restores a checkpoint and delivers a simulated scheduler expiry. Tests need no key: they answer consensus-review's `verdict` choice through a scripted decision model passed as `judge`, script the model by request name (`plan`, `propose`) through the AI SDK's mock model, and also run the alternate outcomes.
22
+
23
+ ## Reviewer quorum
24
+
25
+ [Anthropic's voting pattern](https://www.anthropic.com/engineering/building-effective-agents) motivates independent reviews aggregated by policy. This example uses a two-of-three approval threshold, not unanimity: a security dissent can be outweighed. Change the machine policy if a particular reviewer must veto. Model votes do not prove a patch is safe.
26
+
27
+ Trust is a machine rule, not a prompt instruction. The patch text is in all three reviewers' state, so a patch the host did not author is untrusted input. Input carries `source: "trusted" | "external"` with no default. Host code decides it, never the caller who supplied the patch: the example runner marks only its built-in patch `"trusted"` and any patch passed in `"external"`, and it does not let a caller set `source`. The `counting` choice state routes any `"external"` patch to `humanReview` regardless of the tally, so model votes can only auto-accept trusted input, and the interaction label tells the human why they were asked. A native XState host parses no input schema and supplies `source` itself.
28
+
29
+ Each reviewer is a named parallel region invoking the same Jev judgment actor, `review`, with its own reviewer brief. No host `Promise.all` hides the topology. All regions reach a final state even when their call fails; the parent then counts votes. Human review persists both successful votes and abstentions.
30
+
31
+ The tests execute the same artifact through both `runToQuiescence` and `createActor(provideExecutors(...))`. This establishes those host modes' behavior for this example; it is not certification of every model SDK.
32
+
33
+ ## Booking compensation
34
+
35
+ [Microsoft's compensating-transaction pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/compensating-transaction) motivates explicit recovery after partially completed work. The model proposes an itinerary; deterministic states control approval, reservations, and compensation.
36
+
37
+ ```mermaid
38
+ stateDiagram-v2
39
+ [*] --> planning
40
+ planning --> approval: itinerary
41
+ approval --> flight: APPROVE
42
+ approval --> cancelled: CANCEL
43
+ flight --> hotel: reserved
44
+ flight --> manualRecovery: uncertain
45
+ hotel --> hotelResult: outcome
46
+ hotel --> manualRecovery: uncertain
47
+ hotelResult --> booked: reserved
48
+ hotelResult --> compensating: unavailable
49
+ compensating --> compensated: acknowledged
50
+ compensating --> manualRecovery: uncertain
51
+ ```
52
+
53
+ All reservation actors are simulated. A real host supplies idempotent implementations keyed by `bookingId` and operation name. A confirmed unavailable hotel returns `{ status: "unavailable" }`; an exception means the outcome is uncertain and leads to `manualRecovery`. Flight and cancellation exceptions also require reconciliation. The result preserves `bookingId` and known reservation references.
54
+
55
+ Compensation records an attempted business reversal; it does not roll back time. Snapshots cannot guarantee exactly-once external effects. A host must reconcile timeouts and crashes against the provider before retrying or compensating. The test checkpoint is before reservations, not in the middle of a partially committed provider request.
56
+
57
+ ## Approval deadlines
58
+
59
+ [LangGraph interrupts](https://docs.langchain.com/oss/javascript/langgraph/interrupts) provide a useful comparison for persisted human waits. This example adds a scheduler-owned deadline with a machine-owned acceptance rule.
60
+
61
+ Persist the `awaitingApproval` checkpoint before scheduling expiry. Store an absolute deadline, use an authenticated host clock for `observedAt`, and correlate every delivery with `requestId`. Never trust a client to supply the timestamp. Approval requires `observedAt < deadline`; expiry requires `observedAt >= deadline`.
62
+
63
+ Serialize deliveries per request, or use storage compare-and-swap with conflict handling. Two independent resumes of one snapshot can otherwise produce conflicting outcomes. Retry scheduler deliveries that arrive before the waiting checkpoint exists. Scheduling, authentication, durable storage, and delivery retries belong to the host.
64
+
65
+ This example is marked manual in the demo catalog because generic chat cannot supply that clock/scheduler contract. Its CLI drafts the proposal with a real model and simulates the scheduler delivery. It exports an ordinary XState machine that a dedicated host can visualize and execute.
66
+
67
+ ## Visualization and validation
68
+
69
+ Every example exposes named states, typed inputs/events, and schema-validated model output. The tests require `lintAgentMachine` to report no structural errors. These checks establish specific paths and structure; they are not exhaustive safety proofs. Payload-sensitive guards, provider side effects, and concurrent storage require their own verification.
package/docs/steps.md ADDED
@@ -0,0 +1,54 @@
1
+ # The runtime loop
2
+
3
+ <!-- public AgentRuntime loop from src/run-agent.ts -->
4
+
5
+ `createAgentRuntime(machine, options)` binds executors and returns the operations
6
+ for one run. `runToQuiescence(runtime, init)` drives that loop until the machine
7
+ finishes or no work remains. Use the explicit loop when a host needs to persist,
8
+ schedule, or observe each transition itself.
9
+
10
+ ```ts
11
+ import { createAgentRuntime } from "@statelyai/agent";
12
+
13
+ const runtime = createAgentRuntime(machine, { executors });
14
+ let [state, effects] = await runtime.start({ input });
15
+ await runtime.execute(effects);
16
+
17
+ for (let event; (event = await runtime.nextEvent()); ) {
18
+ [state, effects] = runtime.transition(state, event);
19
+ await runtime.execute(effects);
20
+ }
21
+
22
+ const result = await runtime.finish();
23
+ ```
24
+
25
+ - `start({ input | snapshot | events })` opens or resumes a run.
26
+ - `execute(effects)` starts work and returns when that work is accepted.
27
+ - `nextEvent()` returns the next completion, child message, or timer event. It
28
+ returns `undefined` when the run is quiescent.
29
+ - `transition(state, event)` applies and journals one event.
30
+ - `finish()` stops remaining work and returns `done`, `idle`, or `error`.
31
+
32
+ Every state is a native XState snapshot. `result.persist()` returns plain JSON
33
+ for another process to resume with `start({ snapshot })`.
34
+
35
+ ## Host-owned timers
36
+
37
+ Root `after` timers run in process by default. A durable host can provide
38
+ `timers: { schedule, cancel }` to `createAgentRuntime`. The runtime then settles
39
+ with an external timer pending. When it fires, deliver
40
+ `{ type: "xstate.timer", id }` through `transition` or as the `event` passed to
41
+ `runToQuiescence`.
42
+
43
+ An invoked child machine's `after` timers always run in process, and the run
44
+ waits for them, whichever `timers` option you pass.
45
+
46
+ ## Other hosts
47
+
48
+ - `runToQuiescence(createAgentRuntime(...), init)` for scripts, tests, and
49
+ request handlers.
50
+ - `provideExecutors` when an application owns a live XState actor.
51
+ - An explicit `AgentRuntime` loop when a workflow engine owns persistence,
52
+ retries, messaging, timers, and child execution.
53
+
54
+ The machine artifact does not change between hosts.