@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.
- package/CHANGELOG.md +111 -0
- package/dist/act-B9hLQls6.mjs +19 -0
- package/dist/act-CrX0JwWY.cjs +42 -0
- package/dist/ai-sdk.cjs +63 -7
- package/dist/ai-sdk.d.cts +13 -3
- package/dist/ai-sdk.d.mts +13 -3
- package/dist/ai-sdk.mjs +63 -7
- package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
- package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
- package/dist/decision-object-B5zGSPFp.d.mts +15 -0
- package/dist/decision-object-DBcLWVvv.d.cts +15 -0
- package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
- package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
- package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
- package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
- package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
- package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
- package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
- package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
- package/dist/index.cjs +660 -286
- package/dist/index.d.cts +168 -9
- package/dist/index.d.mts +168 -9
- package/dist/index.mjs +639 -271
- package/dist/internal-C3Lqu538.d.cts +43 -0
- package/dist/internal-DUcdhk-i.d.mts +43 -0
- package/dist/log.cjs +2 -2
- package/dist/log.d.cts +1 -1
- package/dist/log.d.mts +1 -1
- package/dist/log.mjs +2 -2
- package/dist/machines.cjs +457 -41
- package/dist/machines.d.cts +114 -43
- package/dist/machines.d.mts +114 -43
- package/dist/machines.mjs +457 -42
- package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
- package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
- package/dist/openai.cjs +149 -36
- package/dist/openai.d.cts +28 -10
- package/dist/openai.d.mts +28 -10
- package/dist/openai.mjs +149 -36
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
- package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
- package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
- package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
- package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
- package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
- package/dist/tanstack-ai.cjs +62 -4
- package/dist/tanstack-ai.d.cts +18 -6
- package/dist/tanstack-ai.d.mts +18 -6
- package/dist/tanstack-ai.mjs +62 -4
- package/dist/testing.cjs +399 -20
- package/dist/testing.d.cts +196 -255
- package/dist/testing.d.mts +196 -255
- package/dist/testing.mjs +395 -20
- package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
- package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
- package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
- package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
- package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
- package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
- package/dist/utils-7lSa4H-i.d.cts +403 -0
- package/dist/utils-CBbKw2fM.d.mts +403 -0
- package/dist/validate.cjs +44 -12
- package/dist/validate.d.cts +6 -6
- package/dist/validate.d.mts +6 -6
- package/dist/validate.mjs +44 -12
- package/dist/verify-Bink-Drw.cjs +2304 -0
- package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
- package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
- package/dist/verify-Dpz1u5Pe.mjs +2251 -0
- package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
- package/dist/with-model-calls-BkOwdroS.mjs +213 -0
- package/docs/act.md +102 -0
- package/docs/advanced.md +105 -0
- package/docs/any-stack.md +62 -0
- package/docs/choosing-a-run-mode.md +55 -0
- package/docs/debugging.md +29 -0
- package/docs/decisions.md +473 -0
- package/docs/environment-and-policy.md +188 -0
- package/docs/evals.md +509 -0
- package/docs/event-log.md +311 -0
- package/docs/from-a-loop.md +528 -0
- package/docs/generate-machines.md +110 -0
- package/docs/hosts.md +414 -0
- package/docs/human-in-the-loop.md +177 -0
- package/docs/index.md +48 -0
- package/docs/judgments.md +281 -0
- package/docs/langgraph-comparison.md +198 -0
- package/docs/machines-as-data.md +454 -0
- package/docs/machines-presets.md +198 -0
- package/docs/machines.md +497 -0
- package/docs/messages.md +67 -0
- package/docs/meta.json +52 -0
- package/docs/models-and-providers.md +268 -0
- package/docs/multi-agent.md +68 -0
- package/docs/observability.md +109 -0
- package/docs/patterns.md +31 -0
- package/docs/persistence.md +136 -0
- package/docs/quickstart.md +121 -0
- package/docs/roadmap.md +22 -0
- package/docs/scope.md +75 -0
- package/docs/statechart-policy-examples.md +69 -0
- package/docs/steps.md +54 -0
- package/docs/strangler-fig.md +323 -0
- package/docs/text-requests.md +250 -0
- package/docs/thinking-in-state-machines.md +324 -0
- package/docs/tools.md +249 -0
- package/docs/upgrading.md +37 -0
- package/docs/usage-and-budgets.md +516 -0
- package/docs/validate-and-repair.md +253 -0
- package/docs/verify.md +487 -0
- package/docs/xstate-4-and-5-apps.md +161 -0
- package/llms.txt +53 -0
- package/package.json +10 -3
- package/readme.md +30 -15
- package/skills/add-evals/SKILL.md +3 -1
- package/skills/add-traces/SKILL.md +6 -1
- package/skills/build-machine/SKILL.md +81 -0
- package/skills/generate-machine/SKILL.md +1 -1
- package/skills/graph-engineering/SKILL.md +13 -3
- package/skills/improve-machine/SKILL.md +21 -2
- package/skills/loop-to-machine/SKILL.md +147 -192
- package/skills/loop-to-machine/reference.md +260 -0
- package/dist/utils-BnXdWih3.d.mts +0 -108
- package/dist/utils-ebVpCYoF.d.cts +0 -108
- package/dist/verify-Bpahmr34.mjs +0 -1241
- package/dist/verify-DCLZa9R0.cjs +0 -1288
- package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
- package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Machines as data
|
|
3
|
+
description: Author an agent machine as a JSON or YAML config and lower it into the same runnable XState machine that setupAgent builds in TypeScript.
|
|
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
|
+
<!-- setupAgent.fromConfig lowering from src/workflow-config.ts -->
|
|
9
|
+
|
|
10
|
+
This page covers authoring an agent machine as a JSON or YAML config instead of TypeScript.
|
|
11
|
+
|
|
12
|
+
Describe the machine as a config and pass it to `setupAgent.fromConfig(...)`, imported from the same module as `setupAgent`. It produces the same runnable XState machine that `setupAgent(...)` builds by hand. Configs support states, choice routing, guard-expression transitions, emitted progress events, text requests, decisions, and human waits. Only the authoring format changes.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { setupAgent } from "@statelyai/agent";
|
|
16
|
+
|
|
17
|
+
const { machine, schemas } = setupAgent.fromConfig(config, {
|
|
18
|
+
compileSchema: ajvCompileSchema,
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
> **Bring your own `compileSchema`.** The library bundles no JSON Schema engine. `fromConfig(...)` does not run without a `compileSchema` that you supply. Use Ajv, `@cfworker/json-schema`, or anything that returns a Standard Schema. See [Schema compilation](#schema-compilation).
|
|
23
|
+
|
|
24
|
+
`fromConfig(...)` returns two values:
|
|
25
|
+
|
|
26
|
+
- `machine`: the runnable XState machine, ready for `createAgentRuntime(...)`.
|
|
27
|
+
- `schemas`: the compiled `AgentSchemaPack`. It exposes `context`, `events`, `emitted`, `input`, `output`, and `meta` as Standard Schema validators, for host-side validation and tooling.
|
|
28
|
+
|
|
29
|
+
A config is portable. You can generate it from a model, store it in a database row, or edit it in a visual builder. It runs the same way as a hand-authored [machine](machines.md).
|
|
30
|
+
|
|
31
|
+
## Config validation
|
|
32
|
+
|
|
33
|
+
<!-- schema export path from package.json exports and schemas/agent-workflow.json -->
|
|
34
|
+
|
|
35
|
+
The package ships a JSON Schema for validating and editing configs:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import workflowSchema from "@statelyai/agent/agent-workflow.json";
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Point an editor or form generator at this schema. It describes the whole config surface: `schemas` including `events` and `emitted`, plus `context`, `requests`, `actors`, `initial`, and `states`, down to choice states, transitions, invokes, and actions.
|
|
42
|
+
|
|
43
|
+
To validate a config in code, call `validateAgentConfig(config)` from `@statelyai/agent/validate`. It checks the value against the same shipped schema and returns `{ valid, errors }`. This subpath uses `ajv` as an optional peer dependency, so install `ajv` to use it.
|
|
44
|
+
|
|
45
|
+
```ts no-check
|
|
46
|
+
import { validateAgentConfig } from "@statelyai/agent/validate";
|
|
47
|
+
|
|
48
|
+
const { valid, errors } = validateAgentConfig(config);
|
|
49
|
+
// errors: { severity: 'error', path: '/states/idle/invoke', message, keyword }[]
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Validation covers shape only. It does not check that a named guard, action, or actor is implemented, which `fromConfig(...)` does when it lowers the config.
|
|
53
|
+
|
|
54
|
+
### Division of labor
|
|
55
|
+
|
|
56
|
+
Run `validateAgentConfig` first. `fromConfig(...)` does not validate the config against the JSON Schema, so a malformed config reaches lowering unchecked.
|
|
57
|
+
|
|
58
|
+
`fromConfig(...)` throws plain `Error`s for lowering problems such as an unknown
|
|
59
|
+
state target, a missing guard/action implementation, an `onDone` on an
|
|
60
|
+
`agent.decide` invoke, a reserved `'.'` in a key, or a malformed `choice` branch.
|
|
61
|
+
|
|
62
|
+
### Reserved key prefix
|
|
63
|
+
|
|
64
|
+
The `agent.` prefix belongs to the library. `setupAgent` throws when a `requests` or `actors` key starts with `agent.`, including the builtin names `agent.generateText`, `agent.streamText`, and `agent.decide`. Rename the key without the prefix. To override a builtin deliberately, do it on the created machine with `machine.provide({ actors })`.
|
|
65
|
+
|
|
66
|
+
## Expressions
|
|
67
|
+
|
|
68
|
+
The config is data, not code. Every value is either a JSON literal or a whole-string `"{{ }}"` expression. An expression is a dot path resolved against `input`, `context`, and `event`. For example, `"{{ context.ticket }}"` reads `context.ticket`. The resolver walks the path and returns the value. There is no code evaluation and no `eval`. An expression can only read values, so a config produced by a model, a database, or a visual editor cannot do anything a hand-authored machine could not do.
|
|
69
|
+
|
|
70
|
+
Two fields are exempt from template evaluation. State, invoke, and transition `meta`, and a request's `toolChoice`, are passed through verbatim. A `{{ }}` string in those fields stays a literal string.
|
|
71
|
+
|
|
72
|
+
## Example: a support ticket config
|
|
73
|
+
|
|
74
|
+
The config below drives the examples on the rest of this page. The model triages a ticket as escalate or reply, drafts a reply, then waits for a human to approve or reject. The equivalent JSON ships at [examples/json-agent/workflow.json](https://github.com/statelyai/agent/blob/next/examples/json-agent/workflow.json) and is run by [examples/json-agent/index.ts](https://github.com/statelyai/agent/blob/next/examples/json-agent/index.ts). Model IDs are illustrative. Substitute your provider's current models. The config is shown as YAML for readability.
|
|
75
|
+
|
|
76
|
+
<!-- viz: support-ticket machine: triaging (agent.decide) -> resolved on ESCALATE, -> drafting on REPLY; drafting -> awaitingApproval on draft onDone; awaitingApproval -> resolved on APPROVE or REJECT; mark awaitingApproval as the idle state -->
|
|
77
|
+
|
|
78
|
+
```yaml
|
|
79
|
+
id: support-ticket-json
|
|
80
|
+
schemas:
|
|
81
|
+
input:
|
|
82
|
+
type: object
|
|
83
|
+
properties: { ticket: { type: string } }
|
|
84
|
+
required: [ticket]
|
|
85
|
+
context:
|
|
86
|
+
type: object
|
|
87
|
+
properties:
|
|
88
|
+
ticket: { type: string }
|
|
89
|
+
reply: { type: string }
|
|
90
|
+
resolution: { type: string }
|
|
91
|
+
required: [ticket]
|
|
92
|
+
events:
|
|
93
|
+
ESCALATE:
|
|
94
|
+
type: object
|
|
95
|
+
properties: { reason: { type: string } }
|
|
96
|
+
required: [reason]
|
|
97
|
+
REPLY: { type: object, properties: {} }
|
|
98
|
+
APPROVE: { type: object, properties: {} }
|
|
99
|
+
REJECT: { type: object, properties: {} }
|
|
100
|
+
output:
|
|
101
|
+
type: object
|
|
102
|
+
properties:
|
|
103
|
+
resolution: { type: string }
|
|
104
|
+
reply: { type: string }
|
|
105
|
+
required: [resolution]
|
|
106
|
+
emitted:
|
|
107
|
+
TRIAGED:
|
|
108
|
+
type: object
|
|
109
|
+
properties: { route: { type: string } }
|
|
110
|
+
required: [route]
|
|
111
|
+
context:
|
|
112
|
+
ticket: "{{ input.ticket }}"
|
|
113
|
+
requests:
|
|
114
|
+
draftReply:
|
|
115
|
+
model: openai/gpt-6-luna
|
|
116
|
+
system: "Draft a short, courteous support reply to the customer's ticket."
|
|
117
|
+
prompt: "{{ context.ticket }}"
|
|
118
|
+
input:
|
|
119
|
+
type: object
|
|
120
|
+
properties: { ticket: { type: string } }
|
|
121
|
+
required: [ticket]
|
|
122
|
+
output:
|
|
123
|
+
type: object
|
|
124
|
+
properties: { reply: { type: string } }
|
|
125
|
+
required: [reply]
|
|
126
|
+
initial: triaging
|
|
127
|
+
states:
|
|
128
|
+
triaging:
|
|
129
|
+
invoke:
|
|
130
|
+
id: triageDecision
|
|
131
|
+
src: agent.decide
|
|
132
|
+
input:
|
|
133
|
+
model: openai/gpt-6-luna
|
|
134
|
+
system: "Decide whether this ticket needs human escalation or a drafted reply."
|
|
135
|
+
prompt: "{{ context.ticket }}"
|
|
136
|
+
allowedEvents: [ESCALATE, REPLY]
|
|
137
|
+
onError:
|
|
138
|
+
target: resolved
|
|
139
|
+
assign: { resolution: escalated }
|
|
140
|
+
on:
|
|
141
|
+
ESCALATE:
|
|
142
|
+
target: resolved
|
|
143
|
+
assign: { resolution: escalated }
|
|
144
|
+
actions: { emit: { type: TRIAGED, route: escalated } }
|
|
145
|
+
REPLY:
|
|
146
|
+
target: drafting
|
|
147
|
+
actions: { emit: { type: TRIAGED, route: reply } }
|
|
148
|
+
drafting:
|
|
149
|
+
invoke:
|
|
150
|
+
id: draft
|
|
151
|
+
src: draftReply
|
|
152
|
+
input: { ticket: "{{ context.ticket }}" }
|
|
153
|
+
onDone:
|
|
154
|
+
target: awaitingApproval
|
|
155
|
+
assign: { reply: "{{ event.output.result.reply }}" }
|
|
156
|
+
awaitingApproval:
|
|
157
|
+
on:
|
|
158
|
+
APPROVE: { target: resolved, assign: { resolution: replied } }
|
|
159
|
+
REJECT: { target: resolved, assign: { resolution: escalated } }
|
|
160
|
+
resolved:
|
|
161
|
+
type: final
|
|
162
|
+
output:
|
|
163
|
+
resolution: "{{ context.resolution }}"
|
|
164
|
+
reply: "{{ context.reply }}"
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Schema compilation
|
|
168
|
+
|
|
169
|
+
<!-- compileSchema requirement and SchemaCompiler from src/workflow-config.ts -->
|
|
170
|
+
|
|
171
|
+
The `fromConfig` call requires a `compileSchema` option.
|
|
172
|
+
|
|
173
|
+
- A config carries JSON Schemas for context, events, input, output, and each request's input and output. Those schemas need a runtime validator, and the library bundles no JSON Schema engine.
|
|
174
|
+
- `compileSchema` takes a JSON Schema object and a name, and returns a Standard Schema validator. `fromConfig(...)` calls it once per schema.
|
|
175
|
+
- Use Ajv, `@cfworker/json-schema`, or any compiler that returns a Standard Schema.
|
|
176
|
+
|
|
177
|
+
Expose the source JSON Schema on the validator you return, as `jsonSchema: { input: () => schema }`. `lintAgentMachine` reads it to run the checks that need the declared shape, `unserializable-context` and `final-without-output`. Those checks are skipped when it is absent.
|
|
178
|
+
|
|
179
|
+
With Ajv:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import Ajv from "ajv";
|
|
183
|
+
import { setupAgent, type SchemaCompiler, type StandardSchemaV1 } from "@statelyai/agent";
|
|
184
|
+
|
|
185
|
+
const ajv = new Ajv({ strict: false });
|
|
186
|
+
|
|
187
|
+
const ajvCompileSchema: SchemaCompiler = (jsonSchema, name): StandardSchemaV1 => {
|
|
188
|
+
const validate = ajv.compile(jsonSchema);
|
|
189
|
+
return {
|
|
190
|
+
"~standard": {
|
|
191
|
+
version: 1,
|
|
192
|
+
vendor: "ajv",
|
|
193
|
+
validate: (value) =>
|
|
194
|
+
validate(value)
|
|
195
|
+
? { value }
|
|
196
|
+
: {
|
|
197
|
+
issues: (validate.errors ?? []).map((e) => ({
|
|
198
|
+
message: `${name}${e.instancePath} ${e.message}`,
|
|
199
|
+
})),
|
|
200
|
+
},
|
|
201
|
+
jsonSchema: { input: () => jsonSchema },
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const { machine } = setupAgent.fromConfig(config, { compileSchema: ajvCompileSchema });
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Request tools and reasoning
|
|
210
|
+
|
|
211
|
+
<!-- Request shape from schemas/agent-workflow.json $defs.Request -->
|
|
212
|
+
|
|
213
|
+
A `requests` entry can also declare these fields.
|
|
214
|
+
|
|
215
|
+
| Field | Value | Effect |
|
|
216
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
217
|
+
| `tools` | Map of tool name to `{ description?, inputSchema?, outputSchema? }`, where the schemas are JSON Schemas | Passes the tools to the model alongside the request. |
|
|
218
|
+
| `toolChoice` | `"auto"`, `"none"`, `"required"`, or `{ type: "tool", name }` | Controls whether the model must call a tool. |
|
|
219
|
+
| `includeReasoning` | `true` | Opts into the `reasoning` field of the provider's structured output. |
|
|
220
|
+
|
|
221
|
+
```yaml
|
|
222
|
+
requests:
|
|
223
|
+
lookupOrder:
|
|
224
|
+
model: openai/gpt-6-luna
|
|
225
|
+
prompt: "{{ context.ticket }}"
|
|
226
|
+
includeReasoning: true
|
|
227
|
+
toolChoice: auto
|
|
228
|
+
tools:
|
|
229
|
+
searchOrders:
|
|
230
|
+
description: Find orders by customer email.
|
|
231
|
+
inputSchema:
|
|
232
|
+
type: object
|
|
233
|
+
properties: { email: { type: string } }
|
|
234
|
+
required: [email]
|
|
235
|
+
outputSchema:
|
|
236
|
+
type: object
|
|
237
|
+
properties: { orderIds: { type: array, items: { type: string } } }
|
|
238
|
+
input: { type: object, properties: { ticket: { type: string } } }
|
|
239
|
+
output: { type: object, properties: { summary: { type: string } } }
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## Named guards and actions
|
|
243
|
+
|
|
244
|
+
<!-- FromConfigOptions.guards / .actions from src/workflow-config.ts -->
|
|
245
|
+
|
|
246
|
+
A config cannot carry functions. Anything beyond a truthy dot-path guard uses a named reference plus a host implementation.
|
|
247
|
+
|
|
248
|
+
- A string `guard` without `{{ }}` is a **named guard** reference. Implement it in `fromConfig(config, { guards })`. The implementation is called with `{ context, event }` and returns a boolean.
|
|
249
|
+
- An action `{ type, params }` is a **named action** reference. Implement it in `fromConfig(config, { actions })`. The implementation is called with the template-resolved `params` as its only argument. To pass context or event data, use `{{ }}` templates on `params`.
|
|
250
|
+
|
|
251
|
+
```yaml
|
|
252
|
+
awaitingApproval:
|
|
253
|
+
on:
|
|
254
|
+
APPROVE:
|
|
255
|
+
target: resolved
|
|
256
|
+
guard: isReady
|
|
257
|
+
actions: { type: notify, params: { ticket: "{{ context.ticket }}" } }
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
const { machine } = setupAgent.fromConfig(config, {
|
|
262
|
+
compileSchema: ajvCompileSchema,
|
|
263
|
+
guards: { isReady: ({ context }) => Boolean(context.reply) },
|
|
264
|
+
actions: { notify: (params) => console.log("approved", params.ticket) },
|
|
265
|
+
});
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
A named reference with no implementation is a build-time error. The guard or action is never silently dropped.
|
|
269
|
+
|
|
270
|
+
## Host-provided actors
|
|
271
|
+
|
|
272
|
+
<!-- config.actors and createActorPlaceholdersFromWorkflowConfig from src/workflow-config.ts -->
|
|
273
|
+
|
|
274
|
+
The top-level `actors` key declares actor sources that the config does not implement, such as a database read or a queue round trip. Each entry takes an optional `input` and `output` JSON Schema and a `description`. States invoke the source by its key.
|
|
275
|
+
|
|
276
|
+
```yaml
|
|
277
|
+
actors:
|
|
278
|
+
fetchOrder:
|
|
279
|
+
description: Load the order referenced by the ticket.
|
|
280
|
+
input:
|
|
281
|
+
type: object
|
|
282
|
+
properties: { ticket: { type: string } }
|
|
283
|
+
output:
|
|
284
|
+
type: object
|
|
285
|
+
properties: { orderId: { type: string } }
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`fromConfig(...)` lowers each entry to a placeholder that throws when invoked, naming the key. Supply the implementation on the returned machine.
|
|
289
|
+
|
|
290
|
+
```ts no-check
|
|
291
|
+
const { machine } = setupAgent.fromConfig(config, { compileSchema: ajvCompileSchema });
|
|
292
|
+
|
|
293
|
+
const bound = machine.provide({
|
|
294
|
+
actors: { fetchOrder: createAsyncLogic({ run: ({ input }) => loadOrder(input.ticket) }) },
|
|
295
|
+
});
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
Use `actors` for work the host executes directly. Use `requests` for model calls, which the executors bind automatically.
|
|
299
|
+
|
|
300
|
+
## Running configs
|
|
301
|
+
|
|
302
|
+
A machine built by `fromConfig(...)` runs through `createAgentRuntime` like any
|
|
303
|
+
other agent machine. Pass executors and observation handlers when creating the
|
|
304
|
+
runtime; pass machine input when starting it.
|
|
305
|
+
|
|
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
|
+
);
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
Executors return these shapes.
|
|
317
|
+
|
|
318
|
+
| Executor | Returns | Notes |
|
|
319
|
+
| ---------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------ |
|
|
320
|
+
| `decide` | `{ event: { type, ...payload } }` | The chosen machine event. A bare `{ type }` throws a descriptive error. |
|
|
321
|
+
| `generateText`, `streamText` | `{ result, messages? }` | `result` matches the request's `output` schema; `messages` are the provider's response messages. |
|
|
322
|
+
|
|
323
|
+
A run settles in one of two ways.
|
|
324
|
+
|
|
325
|
+
- `{ status: 'done', output }`: the machine reached a final state.
|
|
326
|
+
- `{ status: 'idle', snapshot }`: the machine paused at an idle state. Persist `snapshot`, then resume when the event arrives.
|
|
327
|
+
|
|
328
|
+
<!-- viz: run lifecycle: createAgentRuntime -> runToQuiescence -> done or idle, with idle resuming through a fresh runtime plus snapshot and event -->
|
|
329
|
+
|
|
330
|
+
```ts no-check
|
|
331
|
+
result = await runToQuiescence(createAgentRuntime(machine, { executors }), {
|
|
332
|
+
snapshot,
|
|
333
|
+
event: { type: "APPROVE" },
|
|
334
|
+
});
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
> **Note:** A run settles idle only after its mailbox is empty and no child,
|
|
338
|
+
> request, or in-process timer remains active. `isAgentIdle(snapshot)` tells you
|
|
339
|
+
> whether that settled snapshot is waiting for an external event or interaction.
|
|
340
|
+
>
|
|
341
|
+
> **Note:** Two `prompt`-shaped fields sit at different layers. A `requests` entry's `prompt` is the text sent to the model. An `invoke`'s `input` is the data passed to the invoked source. That is either a request's typed input, or an `agent.decide` inline input carrying its own `model`, `prompt`, and `allowedEvents`.
|
|
342
|
+
|
|
343
|
+
## Decisions from JSON
|
|
344
|
+
|
|
345
|
+
A [decision](decisions.md) works from a config. Invoke `src: agent.decide` with `allowedEvents`.
|
|
346
|
+
|
|
347
|
+
```yaml
|
|
348
|
+
states:
|
|
349
|
+
choosing:
|
|
350
|
+
invoke:
|
|
351
|
+
src: agent.decide
|
|
352
|
+
input:
|
|
353
|
+
model: openai/gpt-6.1-sol
|
|
354
|
+
prompt: "{{ context.ticket }}"
|
|
355
|
+
allowedEvents: [ESCALATE, REPLY]
|
|
356
|
+
onError:
|
|
357
|
+
target: escalated
|
|
358
|
+
on:
|
|
359
|
+
ESCALATE: { target: escalated }
|
|
360
|
+
REPLY: { target: drafting }
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
The chosen event is delivered automatically. When the decision actor resolves, it sends the event to the invoking actor, in both TypeScript and JSON. Handle the chosen event with the state's `on` transitions.
|
|
364
|
+
|
|
365
|
+
A decision has no output of its own, so an `onDone` on an `agent.decide` invoke can never fire. `fromConfig(...)` rejects it as a config error. Only `onError` applies, and it fires when retries are exhausted.
|
|
366
|
+
|
|
367
|
+
<!-- viz: agent.decide flow: state invokes agent.decide with allowedEvents -> model picks one event -> actor sends the event to the invoking actor -> the state's `on` transition runs; onError branch when retries are exhausted -->
|
|
368
|
+
|
|
369
|
+
## Choice states and emitted events
|
|
370
|
+
|
|
371
|
+
Use `type: choice` with a `choice` array for routing states that do no work. This matches `type: 'choice'` authoring in TypeScript.
|
|
372
|
+
|
|
373
|
+
```yaml
|
|
374
|
+
states:
|
|
375
|
+
checking:
|
|
376
|
+
type: choice
|
|
377
|
+
choice:
|
|
378
|
+
- guard: "{{ context.score }}"
|
|
379
|
+
target: passed
|
|
380
|
+
- target: failed
|
|
381
|
+
passed:
|
|
382
|
+
entry: { emit: { type: SCORED, value: "{{ context.score }}" } }
|
|
383
|
+
type: final
|
|
384
|
+
failed:
|
|
385
|
+
entry: { emit: { type: SCORED, value: "{{ context.score }}" } }
|
|
386
|
+
type: final
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
Declare emitted event payloads under `schemas.emitted`. Hosts receive them through
|
|
390
|
+
`createAgentRuntime(machine, { on: { SCORED: handler } })`, the same as for
|
|
391
|
+
hand-authored machines that use `enq.emit(...)`.
|
|
392
|
+
|
|
393
|
+
## Machine descriptions for models
|
|
394
|
+
|
|
395
|
+
<!-- describeMachine from src/describe-machine.ts -->
|
|
396
|
+
|
|
397
|
+
`describeMachine(machine, { snapshot?, source?, helpers? })` renders any machine, from a config or from TypeScript, as plain text a model can read. Use it as the prompt for a model that proposes an improved machine, or as extra context for a decider.
|
|
398
|
+
|
|
399
|
+
```ts
|
|
400
|
+
import { describeMachine } from "@statelyai/agent";
|
|
401
|
+
|
|
402
|
+
const prompt = `Propose an improved machine for this goal.\n\n${describeMachine(machine)}`;
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
The machine's `description` is its goal, so it leads the text. An excerpt:
|
|
406
|
+
|
|
407
|
+
```text
|
|
408
|
+
Machine ticket
|
|
409
|
+
Goal: Answer the customer's ticket so they never write back.
|
|
410
|
+
States (initial: triaging):
|
|
411
|
+
triaging — Decide how to handle the ticket
|
|
412
|
+
on ESCALATE → escalated
|
|
413
|
+
on REPLY → drafting; sets tone — Draft a reply
|
|
414
|
+
invoke agent.decide
|
|
415
|
+
error → escalated
|
|
416
|
+
checking (choice)
|
|
417
|
+
choice if context.approved → sent
|
|
418
|
+
choice if isRetryable → drafting
|
|
419
|
+
choice else → escalated
|
|
420
|
+
sent (final) [tags: done]
|
|
421
|
+
escalated (final) — A human owns it now
|
|
422
|
+
Events:
|
|
423
|
+
REPLY — Answer the ticket directly
|
|
424
|
+
tone: "formal" | "casual" — Reply tone
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
- **States:** one line each, indented by depth, with the type, tags, `meta.interaction.label`, and description. Pass `snapshot` to mark the active states with `*`.
|
|
428
|
+
- **Transitions:** one line each under the state they leave: `on`, `always`, `after`, invoke `done` and `error`, and `choice` branches. Each line shows the guard (`if …`), the target, and the context keys it sets (`sets tone`).
|
|
429
|
+
- **Events:** each event schema's description and fields. Event descriptions come from the schema's JSON Schema, so a `compileSchema` must implement the Standard Schema JSON Schema extension for a config's event descriptions to appear.
|
|
430
|
+
- **Config machines:** read from the lowered config, so every target, guard, and context patch is known.
|
|
431
|
+
- **Transition functions:** parsed from their source, following every return path: ternaries, `&&` and `||`, early returns, and local constants. A function shows each target it can return, marked `(conditional)` when it can also stay, return no transition, or pick among several. It shows `(stays)` when no path names a target, and `?` for a target its own source does not spell out: a variable's value, or a transition a helper returns.
|
|
432
|
+
- **Source:** pass `source: true` to print each transition function under its line, so one read shows both where it goes and what it computes. Entry and exit actions print too.
|
|
433
|
+
- **Helpers:** pass the functions transitions call by name, such as `helpers: { withinLimit }`, to print each one's source in a `Helpers` section. A guard passed into a machine factory is then readable from the same text.
|
|
434
|
+
|
|
435
|
+
The output is deterministic. The same machine always produces the same text.
|
|
436
|
+
|
|
437
|
+
## Limits of the data form
|
|
438
|
+
|
|
439
|
+
The data form is narrower than TypeScript authoring.
|
|
440
|
+
|
|
441
|
+
- Expressions are dot paths such as `{{ context.foo.bar }}`, not arbitrary JavaScript.
|
|
442
|
+
- Guard expressions are truthy-only. They support no `!=`, no comparisons, and no boolean operators. For anything else, use a named guard. See [Named guards and actions](#named-guards-and-actions).
|
|
443
|
+
- Function-valued fields cannot appear in JSON. This includes `allowedEvents` and `input` when written as functions.
|
|
444
|
+
- `meta` and `toolChoice` are not template-evaluated.
|
|
445
|
+
|
|
446
|
+
For comparisons, or for function-valued fields that have no named-reference equivalent, author the machine in TypeScript with `setupAgent(...)` and Zod or any other Standard Schema library.
|
|
447
|
+
|
|
448
|
+
## Related
|
|
449
|
+
|
|
450
|
+
- [Testing and verification](verify.md): check a lowered machine before it runs, with no API key and no model call. Lint it with `lintAgentMachine`, simulate a scripted playthrough, or enumerate its decision branches, all from a script CI can run.
|
|
451
|
+
- [Generating machines with an LLM](generate-machines.md): the generate → validate → lint → simulate pipeline.
|
|
452
|
+
- [Agent machines](machines.md): the TypeScript authoring form a config lowers to.
|
|
453
|
+
- [Decisions](decisions.md): `agent.decide` from a config.
|
|
454
|
+
- [examples/json-agent](https://github.com/statelyai/agent/blob/next/examples/json-agent/index.ts): a hand-written config, run.
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
---
|
|
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.
|
|
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
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
`@statelyai/agent/machines` ships factories for common agent shapes. Each factory is a thin composition over `setupAgent(...).createMachine(...)`.
|
|
11
|
+
|
|
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.
|
|
15
|
+
|
|
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`
|
|
121
|
+
|
|
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.
|
|
123
|
+
|
|
124
|
+
### `createApprovalBatchMachine`
|
|
125
|
+
|
|
126
|
+
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
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { createAsyncLogic } from "xstate";
|
|
130
|
+
import { createAgentRuntime, runToQuiescence } from "@statelyai/agent";
|
|
131
|
+
import { createApprovalBatchMachine } from "@statelyai/agent/machines";
|
|
132
|
+
|
|
133
|
+
const machine = createApprovalBatchMachine({
|
|
134
|
+
policy: createAsyncLogic({
|
|
135
|
+
run: async ({ input }: { input: { call: { name: string } } }) =>
|
|
136
|
+
input.call.name === "search" ? ("allow" as const) : ("ask" as const),
|
|
137
|
+
}),
|
|
138
|
+
execute: createAsyncLogic({
|
|
139
|
+
run: async ({ input }: { input: { call: { name: string; args: unknown } } }) =>
|
|
140
|
+
`ran ${input.call.name}`,
|
|
141
|
+
}),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const paused = await runToQuiescence(createAgentRuntime(machine), {
|
|
145
|
+
input: { calls: [{ id: "call_1", name: "deleteFile", args: { path: "a.txt" } }] },
|
|
146
|
+
});
|
|
147
|
+
const result = await runToQuiescence(createAgentRuntime(machine), {
|
|
148
|
+
snapshot: paused.persist(),
|
|
149
|
+
event: { type: "APPROVE", callId: "call_1" },
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- **Input.** `{ calls: Array<{ id, name, args }> }`. Ids must be unique.
|
|
154
|
+
- **`policy`.** Actor logic over `{ call }` returning `"allow"`, `"ask"`, or `"deny"`. Default: every call is `"ask"`. A policy failure or any other value fails the call; it never executes.
|
|
155
|
+
- **`execute`.** Actor logic over `{ call }`. Its output is the call's `result`; a rejection is `status: "failed"`.
|
|
156
|
+
- **`executeWhen`.** `"allReady"` (default): nothing executes until every call has settled its approval. `"eachReady"`: each call executes once approved.
|
|
157
|
+
- **Child states.** `checking` (policy) → `awaitingApproval` → `approved` → `executing` → `executed` | `rejected` | `failed`. One spawned child per call, id `call:<id>`.
|
|
158
|
+
- **Host events.** `APPROVE`, `APPROVE_ALWAYS`, `REJECT` (optional `reason`), each with `callId`. Routed to that call's child; ignored for a call not awaiting approval. `CANCEL_ALL` ends the batch (state `cancelled`), stopping unfinished calls, including an in-flight execute, which reports `cancelled`.
|
|
159
|
+
- **Interaction.** `running` declares `meta.interaction` with one payload choice per awaiting call and verb, so `getInteraction(snapshot).choices` lists them. `context.awaiting` holds the calls themselves.
|
|
160
|
+
- **Output.** `{ results, approveAlways }`. `results` holds one `{ id, status, result?, error?, reason? }` per input call, in input order, with `status` `"executed"`, `"rejected"`, `"failed"`, or `"cancelled"`. `approveAlways` holds one `{ name }` per tool approved with `APPROVE_ALWAYS`; persist it and have `policy` return `"allow"` for those names next time.
|
|
161
|
+
- **Safety.** The per-call child reaches `executing` only from a policy `"allow"` or a person's approval. `canReach` proves the opposite unreachable with `complete: true`; see `src/machines/approval-batch.test.ts`.
|
|
162
|
+
- **Mid-run cancel.** `runtime.send({ type: "CANCEL_ALL" })` from a hand-written loop. See [Hosts](hosts.md#host-events-mid-run).
|
|
163
|
+
|
|
164
|
+
## Ejection
|
|
165
|
+
|
|
166
|
+
A preset is a starting point. When you need one more state, a human gate, a different bound, or your own typed context:
|
|
167
|
+
|
|
168
|
+
1. Open the preset's source at `src/machines/<preset>.ts`. It is one small file of states.
|
|
169
|
+
2. Copy it into your project and edit the `setupAgent(...)` call directly.
|
|
170
|
+
3. Run it as before. The copied machine runs, lints, and persists the same way.
|
|
171
|
+
|
|
172
|
+
Examples to eject toward:
|
|
173
|
+
|
|
174
|
+
- [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
|
+
|
|
178
|
+
## Versioning
|
|
179
|
+
|
|
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:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
const result = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
|
|
184
|
+
// result.persist().version === "1"
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The versioning policy:
|
|
188
|
+
|
|
189
|
+
- The version identifies the machine's topology, not the release that built it. Prompt wording can change without a version bump.
|
|
190
|
+
- A topology change that an old snapshot cannot restore bumps the version. Migrate it with XState's machine-level `migrate(snapshot, fromVersion)`.
|
|
191
|
+
|
|
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.
|
|
193
|
+
|
|
194
|
+
## Related
|
|
195
|
+
|
|
196
|
+
- Read more about [Agent machines](machines.md), including `setupAgent`, states, invokes, and guards.
|
|
197
|
+
- Read more about [Agent patterns](patterns.md), the full runnable example catalog.
|
|
198
|
+
- Read more about [Persistence](persistence.md).
|