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

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 +138 -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-Ct_GZw_f.mjs → effects-BT_cSY0j.mjs} +1003 -109
  13. package/dist/{run-agent-s5D32w99.cjs → effects-DDseYtJk.cjs} +1037 -107
  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-30mH2moE.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-DlPzBWj-.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-BaNyz6Q3.d.cts} +4 -4
  46. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-C1CG_nfX.d.mts} +4 -4
  47. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  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 +2493 -1502
  53. package/dist/testing.d.cts +360 -256
  54. package/dist/testing.d.mts +360 -256
  55. package/dist/testing.mjs +2489 -1503
  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-Bm5nvpow.d.cts} +6 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-BnikdOca.d.mts} +6 -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-ChyX6jq0.mjs +2306 -0
  69. package/dist/verify-CwlombbC.cjs +2359 -0
  70. package/dist/{verify-BQpE8hUz.d.cts → verify-DJHfEfm6.d.cts} +213 -14
  71. package/dist/{verify-CqeuEmIk.d.mts → verify-i9Hiwc5g.d.mts} +213 -14
  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 +312 -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 +207 -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 +56 -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 +518 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +492 -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 +84 -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,248 @@
1
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
3
+ //#region src/internal/decision-object.ts
4
+ /** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
5
+ function resolveDecisionMode(option, request) {
6
+ const configured = typeof option === "function" ? option(request) : option;
7
+ if (configured) return configured;
8
+ if (request.options) return "object";
9
+ return request.events.every((event) => eventPayloadBranches(event.inputSchema) !== void 0) ? "object" : "tool";
10
+ }
11
+ /**
12
+ * The JSON Schema of a decision answered as one object. An open choice is
13
+ * `{ event }`, where `event` is any one candidate: its payload's properties
14
+ * plus `type` pinned to the event type. A closed choice is `{ choice }`, an
15
+ * enum of option ids (see {@link decisionOptionIds}). The root is always an
16
+ * object, as providers' structured output requires. @internal
17
+ */
18
+ function decisionObjectSchema(request) {
19
+ if (request.options) {
20
+ const ids = require_decision.decisionOptionIds(request.options);
21
+ return {
22
+ type: "object",
23
+ properties: { choice: {
24
+ type: "string",
25
+ enum: ids,
26
+ description: `The id of the one option you choose:\n${request.options.map((option, index) => option.description ? `- ${ids[index]}: ${option.description}` : `- ${ids[index]}`).join("\n")}`
27
+ } },
28
+ required: ["choice"],
29
+ additionalProperties: false
30
+ };
31
+ }
32
+ return {
33
+ type: "object",
34
+ properties: { event: {
35
+ description: "The one event to send next.",
36
+ anyOf: request.events.flatMap((event) => eventBranches(event.type, event.inputSchema))
37
+ } },
38
+ required: ["event"],
39
+ additionalProperties: false
40
+ };
41
+ }
42
+ function eventPayloadBranches(inputSchema) {
43
+ if (!inputSchema) return [{}];
44
+ const payload = markOptional(require_event_log.getJsonSchemaSync(inputSchema));
45
+ return payload ? objectBranches(payload) : void 0;
46
+ }
47
+ function objectBranches(schema) {
48
+ if (!require_event_log.isRecord(schema)) return void 0;
49
+ const union = schema.anyOf ?? schema.oneOf;
50
+ if (Array.isArray(union) && union.length > 0) {
51
+ const variants = union.map(objectBranches);
52
+ if (variants.some((variant) => variant === void 0)) return void 0;
53
+ return variants.flatMap((variant) => variant ?? []);
54
+ }
55
+ if (schema.allOf !== void 0) return void 0;
56
+ return schema.type === "object" || require_event_log.isRecord(schema.properties) ? [schema] : void 0;
57
+ }
58
+ function eventBranches(type, inputSchema) {
59
+ const payloads = eventPayloadBranches(inputSchema);
60
+ if (!payloads) throw new Error(`Event '${type}' has a payload schema that cannot be represented in decision object mode; use decision tool mode instead.`);
61
+ return payloads.map((payload) => eventBranch(type, payload));
62
+ }
63
+ function eventBranch(type, payload) {
64
+ const pinned = {
65
+ type: "string",
66
+ enum: [type]
67
+ };
68
+ const description = typeof payload.description === "string" ? `Send '${type}'. ${payload.description}` : `Send '${type}'.`;
69
+ const properties = require_event_log.isRecord(payload.properties) ? payload.properties : {};
70
+ const required = Array.isArray(payload.required) ? payload.required.filter((key) => typeof key === "string") : [];
71
+ const { $schema: _, ...rest } = payload;
72
+ return {
73
+ ...rest,
74
+ type: "object",
75
+ description,
76
+ properties: {
77
+ ...properties,
78
+ type: pinned
79
+ },
80
+ required: ["type", ...required.filter((key) => key !== "type")]
81
+ };
82
+ }
83
+ function markOptional(schema) {
84
+ if (!require_event_log.isRecord(schema)) return void 0;
85
+ const out = { ...schema };
86
+ for (const key of [
87
+ "anyOf",
88
+ "oneOf",
89
+ "allOf",
90
+ "prefixItems"
91
+ ]) {
92
+ const children = schema[key];
93
+ if (Array.isArray(children)) out[key] = children.map((child) => markOptional(child) ?? child);
94
+ }
95
+ for (const key of [
96
+ "items",
97
+ "contains",
98
+ "not",
99
+ "if",
100
+ "then",
101
+ "else",
102
+ "propertyNames",
103
+ "additionalProperties",
104
+ "unevaluatedProperties"
105
+ ]) {
106
+ const child = schema[key];
107
+ if (require_event_log.isRecord(child)) out[key] = markOptional(child) ?? child;
108
+ }
109
+ for (const key of [
110
+ "$defs",
111
+ "definitions",
112
+ "patternProperties",
113
+ "dependentSchemas"
114
+ ]) {
115
+ const children = schema[key];
116
+ if (!require_event_log.isRecord(children)) continue;
117
+ out[key] = Object.fromEntries(Object.entries(children).map(([name, child]) => [name, markOptional(child) ?? child]));
118
+ }
119
+ if (require_event_log.isRecord(schema.properties)) {
120
+ const required = Array.isArray(schema.required) ? schema.required : [];
121
+ out.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => required.includes(key) || !require_event_log.isRecord(value) ? [key, markOptional(value) ?? value] : [key, {
122
+ ...markOptional(value) ?? value,
123
+ description: [OPTIONAL_NOTE, value.description].filter(Boolean).join(" ")
124
+ }]));
125
+ }
126
+ return out;
127
+ }
128
+ const OPTIONAL_NOTE = "Optional: leave out unless the input gives it.";
129
+ /**
130
+ * Reads a decision answered as one object (see {@link decisionObjectSchema}):
131
+ * the chosen event, or a rejection `resolveDecision` records and retries. A
132
+ * string answer is parsed as JSON first. Payload validation is left to
133
+ * `resolveDecision`. @internal
134
+ */
135
+ function fromDecisionObject(request, answer) {
136
+ let value = answer;
137
+ if (typeof value === "string") try {
138
+ value = JSON.parse(value);
139
+ } catch {
140
+ return { rejected: {
141
+ failure: "invalid-payload",
142
+ reason: "the answer was not valid JSON"
143
+ } };
144
+ }
145
+ if (request.options) return fromChoice(request.options, value);
146
+ const types = request.events.map((event) => event.type);
147
+ const valid = types.join(", ") || "none";
148
+ const event = require_event_log.isRecord(value) ? value.event : void 0;
149
+ if (!require_event_log.isRecord(event) || typeof event.type !== "string") return { rejected: {
150
+ failure: "unknown-event",
151
+ reason: `the answer named no event; answer with exactly one of: ${valid}`
152
+ } };
153
+ if (!types.includes(event.type)) return { rejected: {
154
+ failure: "unknown-event",
155
+ reason: `'${event.type}' is not among the allowed events: ${valid}`,
156
+ event
157
+ } };
158
+ return { event };
159
+ }
160
+ function fromChoice(options, value) {
161
+ const ids = require_decision.decisionOptionIds(options);
162
+ const id = require_event_log.isRecord(value) ? value.choice : void 0;
163
+ const option = typeof id === "string" ? options[ids.indexOf(id)] : void 0;
164
+ return option ? { event: option.event } : { rejected: {
165
+ failure: "unknown-event",
166
+ reason: `option ${JSON.stringify(id)} was not offered; valid ids: ${ids.join(", ") || "none"}`
167
+ } };
168
+ }
169
+ /**
170
+ * The rejection for a tool-mode answer that called more than one tool: a
171
+ * decision sends exactly one event, so it is retried. @internal
172
+ */
173
+ function multipleCallsRejection(toolNames) {
174
+ return {
175
+ failure: "unknown-event",
176
+ reason: `a decision sends exactly one event, but ${toolNames.length} tools were called (${toolNames.join(", ")}); call exactly one`
177
+ };
178
+ }
179
+ //#endregion
180
+ //#region src/internal/rejected-answer.ts
181
+ /**
182
+ * The rejection for a decision answer that names no candidate event: no tool
183
+ * call, a call to a tool that was not offered, or arguments that are not JSON.
184
+ * `resolveDecision` records it as a failed attempt and asks again. @internal
185
+ */
186
+ function rejectedAnswer(toolCall, toolNames) {
187
+ const valid = toolNames.join(", ") || "none";
188
+ if (!toolCall) return {
189
+ failure: "unknown-event",
190
+ reason: `no tool was called; call exactly one of: ${valid}`
191
+ };
192
+ if (toolCall.invalidJson) return {
193
+ failure: "invalid-payload",
194
+ reason: `the arguments for tool '${toolCall.toolName}' were not valid JSON`
195
+ };
196
+ return {
197
+ failure: "unknown-event",
198
+ reason: `tool '${toolCall.toolName}' was not offered; valid tools: ${valid}`
199
+ };
200
+ }
201
+ //#endregion
202
+ //#region src/internal/with-model-calls.ts
203
+ /**
204
+ * Records on a thrown error how many provider calls its request made, so the
205
+ * runtime counts a failed tool loop's steps too (see `getCallModelCalls`).
206
+ * @internal
207
+ */
208
+ function withModelCalls(error, modelCalls) {
209
+ if (modelCalls > 1 && typeof error === "object" && error !== null && Object.isExtensible(error)) error.modelCalls ??= modelCalls;
210
+ return error;
211
+ }
212
+ //#endregion
213
+ Object.defineProperty(exports, "decisionObjectSchema", {
214
+ enumerable: true,
215
+ get: function() {
216
+ return decisionObjectSchema;
217
+ }
218
+ });
219
+ Object.defineProperty(exports, "fromDecisionObject", {
220
+ enumerable: true,
221
+ get: function() {
222
+ return fromDecisionObject;
223
+ }
224
+ });
225
+ Object.defineProperty(exports, "multipleCallsRejection", {
226
+ enumerable: true,
227
+ get: function() {
228
+ return multipleCallsRejection;
229
+ }
230
+ });
231
+ Object.defineProperty(exports, "rejectedAnswer", {
232
+ enumerable: true,
233
+ get: function() {
234
+ return rejectedAnswer;
235
+ }
236
+ });
237
+ Object.defineProperty(exports, "resolveDecisionMode", {
238
+ enumerable: true,
239
+ get: function() {
240
+ return resolveDecisionMode;
241
+ }
242
+ });
243
+ Object.defineProperty(exports, "withModelCalls", {
244
+ enumerable: true,
245
+ get: function() {
246
+ return withModelCalls;
247
+ }
248
+ });
@@ -0,0 +1,213 @@
1
+ import { et as getJsonSchemaSync, mt as isRecord } from "./event-log-DkVlk3Rh.mjs";
2
+ import { o as decisionOptionIds } from "./decision-m5hGmHpF.mjs";
3
+ //#region src/internal/decision-object.ts
4
+ /** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
5
+ function resolveDecisionMode(option, request) {
6
+ const configured = typeof option === "function" ? option(request) : option;
7
+ if (configured) return configured;
8
+ if (request.options) return "object";
9
+ return request.events.every((event) => eventPayloadBranches(event.inputSchema) !== void 0) ? "object" : "tool";
10
+ }
11
+ /**
12
+ * The JSON Schema of a decision answered as one object. An open choice is
13
+ * `{ event }`, where `event` is any one candidate: its payload's properties
14
+ * plus `type` pinned to the event type. A closed choice is `{ choice }`, an
15
+ * enum of option ids (see {@link decisionOptionIds}). The root is always an
16
+ * object, as providers' structured output requires. @internal
17
+ */
18
+ function decisionObjectSchema(request) {
19
+ if (request.options) {
20
+ const ids = decisionOptionIds(request.options);
21
+ return {
22
+ type: "object",
23
+ properties: { choice: {
24
+ type: "string",
25
+ enum: ids,
26
+ description: `The id of the one option you choose:\n${request.options.map((option, index) => option.description ? `- ${ids[index]}: ${option.description}` : `- ${ids[index]}`).join("\n")}`
27
+ } },
28
+ required: ["choice"],
29
+ additionalProperties: false
30
+ };
31
+ }
32
+ return {
33
+ type: "object",
34
+ properties: { event: {
35
+ description: "The one event to send next.",
36
+ anyOf: request.events.flatMap((event) => eventBranches(event.type, event.inputSchema))
37
+ } },
38
+ required: ["event"],
39
+ additionalProperties: false
40
+ };
41
+ }
42
+ function eventPayloadBranches(inputSchema) {
43
+ if (!inputSchema) return [{}];
44
+ const payload = markOptional(getJsonSchemaSync(inputSchema));
45
+ return payload ? objectBranches(payload) : void 0;
46
+ }
47
+ function objectBranches(schema) {
48
+ if (!isRecord(schema)) return void 0;
49
+ const union = schema.anyOf ?? schema.oneOf;
50
+ if (Array.isArray(union) && union.length > 0) {
51
+ const variants = union.map(objectBranches);
52
+ if (variants.some((variant) => variant === void 0)) return void 0;
53
+ return variants.flatMap((variant) => variant ?? []);
54
+ }
55
+ if (schema.allOf !== void 0) return void 0;
56
+ return schema.type === "object" || isRecord(schema.properties) ? [schema] : void 0;
57
+ }
58
+ function eventBranches(type, inputSchema) {
59
+ const payloads = eventPayloadBranches(inputSchema);
60
+ if (!payloads) throw new Error(`Event '${type}' has a payload schema that cannot be represented in decision object mode; use decision tool mode instead.`);
61
+ return payloads.map((payload) => eventBranch(type, payload));
62
+ }
63
+ function eventBranch(type, payload) {
64
+ const pinned = {
65
+ type: "string",
66
+ enum: [type]
67
+ };
68
+ const description = typeof payload.description === "string" ? `Send '${type}'. ${payload.description}` : `Send '${type}'.`;
69
+ const properties = isRecord(payload.properties) ? payload.properties : {};
70
+ const required = Array.isArray(payload.required) ? payload.required.filter((key) => typeof key === "string") : [];
71
+ const { $schema: _, ...rest } = payload;
72
+ return {
73
+ ...rest,
74
+ type: "object",
75
+ description,
76
+ properties: {
77
+ ...properties,
78
+ type: pinned
79
+ },
80
+ required: ["type", ...required.filter((key) => key !== "type")]
81
+ };
82
+ }
83
+ function markOptional(schema) {
84
+ if (!isRecord(schema)) return void 0;
85
+ const out = { ...schema };
86
+ for (const key of [
87
+ "anyOf",
88
+ "oneOf",
89
+ "allOf",
90
+ "prefixItems"
91
+ ]) {
92
+ const children = schema[key];
93
+ if (Array.isArray(children)) out[key] = children.map((child) => markOptional(child) ?? child);
94
+ }
95
+ for (const key of [
96
+ "items",
97
+ "contains",
98
+ "not",
99
+ "if",
100
+ "then",
101
+ "else",
102
+ "propertyNames",
103
+ "additionalProperties",
104
+ "unevaluatedProperties"
105
+ ]) {
106
+ const child = schema[key];
107
+ if (isRecord(child)) out[key] = markOptional(child) ?? child;
108
+ }
109
+ for (const key of [
110
+ "$defs",
111
+ "definitions",
112
+ "patternProperties",
113
+ "dependentSchemas"
114
+ ]) {
115
+ const children = schema[key];
116
+ if (!isRecord(children)) continue;
117
+ out[key] = Object.fromEntries(Object.entries(children).map(([name, child]) => [name, markOptional(child) ?? child]));
118
+ }
119
+ if (isRecord(schema.properties)) {
120
+ const required = Array.isArray(schema.required) ? schema.required : [];
121
+ out.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => required.includes(key) || !isRecord(value) ? [key, markOptional(value) ?? value] : [key, {
122
+ ...markOptional(value) ?? value,
123
+ description: [OPTIONAL_NOTE, value.description].filter(Boolean).join(" ")
124
+ }]));
125
+ }
126
+ return out;
127
+ }
128
+ const OPTIONAL_NOTE = "Optional: leave out unless the input gives it.";
129
+ /**
130
+ * Reads a decision answered as one object (see {@link decisionObjectSchema}):
131
+ * the chosen event, or a rejection `resolveDecision` records and retries. A
132
+ * string answer is parsed as JSON first. Payload validation is left to
133
+ * `resolveDecision`. @internal
134
+ */
135
+ function fromDecisionObject(request, answer) {
136
+ let value = answer;
137
+ if (typeof value === "string") try {
138
+ value = JSON.parse(value);
139
+ } catch {
140
+ return { rejected: {
141
+ failure: "invalid-payload",
142
+ reason: "the answer was not valid JSON"
143
+ } };
144
+ }
145
+ if (request.options) return fromChoice(request.options, value);
146
+ const types = request.events.map((event) => event.type);
147
+ const valid = types.join(", ") || "none";
148
+ const event = isRecord(value) ? value.event : void 0;
149
+ if (!isRecord(event) || typeof event.type !== "string") return { rejected: {
150
+ failure: "unknown-event",
151
+ reason: `the answer named no event; answer with exactly one of: ${valid}`
152
+ } };
153
+ if (!types.includes(event.type)) return { rejected: {
154
+ failure: "unknown-event",
155
+ reason: `'${event.type}' is not among the allowed events: ${valid}`,
156
+ event
157
+ } };
158
+ return { event };
159
+ }
160
+ function fromChoice(options, value) {
161
+ const ids = decisionOptionIds(options);
162
+ const id = isRecord(value) ? value.choice : void 0;
163
+ const option = typeof id === "string" ? options[ids.indexOf(id)] : void 0;
164
+ return option ? { event: option.event } : { rejected: {
165
+ failure: "unknown-event",
166
+ reason: `option ${JSON.stringify(id)} was not offered; valid ids: ${ids.join(", ") || "none"}`
167
+ } };
168
+ }
169
+ /**
170
+ * The rejection for a tool-mode answer that called more than one tool: a
171
+ * decision sends exactly one event, so it is retried. @internal
172
+ */
173
+ function multipleCallsRejection(toolNames) {
174
+ return {
175
+ failure: "unknown-event",
176
+ reason: `a decision sends exactly one event, but ${toolNames.length} tools were called (${toolNames.join(", ")}); call exactly one`
177
+ };
178
+ }
179
+ //#endregion
180
+ //#region src/internal/rejected-answer.ts
181
+ /**
182
+ * The rejection for a decision answer that names no candidate event: no tool
183
+ * call, a call to a tool that was not offered, or arguments that are not JSON.
184
+ * `resolveDecision` records it as a failed attempt and asks again. @internal
185
+ */
186
+ function rejectedAnswer(toolCall, toolNames) {
187
+ const valid = toolNames.join(", ") || "none";
188
+ if (!toolCall) return {
189
+ failure: "unknown-event",
190
+ reason: `no tool was called; call exactly one of: ${valid}`
191
+ };
192
+ if (toolCall.invalidJson) return {
193
+ failure: "invalid-payload",
194
+ reason: `the arguments for tool '${toolCall.toolName}' were not valid JSON`
195
+ };
196
+ return {
197
+ failure: "unknown-event",
198
+ reason: `tool '${toolCall.toolName}' was not offered; valid tools: ${valid}`
199
+ };
200
+ }
201
+ //#endregion
202
+ //#region src/internal/with-model-calls.ts
203
+ /**
204
+ * Records on a thrown error how many provider calls its request made, so the
205
+ * runtime counts a failed tool loop's steps too (see `getCallModelCalls`).
206
+ * @internal
207
+ */
208
+ function withModelCalls(error, modelCalls) {
209
+ if (modelCalls > 1 && typeof error === "object" && error !== null && Object.isExtensible(error)) error.modelCalls ??= modelCalls;
210
+ return error;
211
+ }
212
+ //#endregion
213
+ export { multipleCallsRejection as a, fromDecisionObject as i, rejectedAnswer as n, resolveDecisionMode as o, decisionObjectSchema as r, withModelCalls as t };
package/docs/act.md ADDED
@@ -0,0 +1,102 @@
1
+ ---
2
+ title: Acting on events
3
+ description: Let the model send any number of the current state's accepted events in one tool loop, each answered with what it changed.
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
+ `agent.act` is a builtin invoke that runs one `generateText` request with a host-side tool loop. Its tools are the invoking state's accepted events, plus any plain `tools`. The loop may make multiple provider model calls. The model calls the tools in any order, zero or more times, and each call is delivered to the machine.
11
+
12
+ - `agent.decide` sends exactly one event per decision. See [Decisions](decisions.md).
13
+ - `agent.act` sends zero to many events, and sees the result of each one before it calls the next.
14
+
15
+ ## Invoking `agent.act`
16
+
17
+ ```ts
18
+ import { createAgentSchemas, setupAgent } from "@statelyai/agent";
19
+ import { z } from "zod";
20
+
21
+ const agent = setupAgent({
22
+ schemas: createAgentSchemas({
23
+ context: z.object({ items: z.array(z.string()), note: z.string() }),
24
+ events: {
25
+ ADD: z.object({ item: z.string() }),
26
+ CHECKOUT: z.object({}),
27
+ APPROVE: z.object({}),
28
+ },
29
+ }),
30
+ });
31
+
32
+ agent.createMachine({
33
+ context: { items: [], note: "" },
34
+ initial: "shopping",
35
+ states: {
36
+ shopping: {
37
+ invoke: {
38
+ src: "agent.act",
39
+ input: { model: "quick", prompt: "Add milk and eggs, then check out." },
40
+ // Runs when the loop ends while `shopping` is still active.
41
+ onDone: ({ context, event }) => ({
42
+ target: "idle",
43
+ context: { ...context, note: String(event.output) },
44
+ }),
45
+ },
46
+ on: {
47
+ ADD: ({ context, event }) => ({
48
+ context: { ...context, items: [...context.items, event.item] },
49
+ }),
50
+ CHECKOUT: ({ context }) => (context.items.length > 0 ? { target: "paid" } : undefined),
51
+ // A person sends APPROVE, so the model is not offered it.
52
+ APPROVE: { target: "paid", meta: { actor: "human" } },
53
+ },
54
+ },
55
+ idle: {},
56
+ paid: { type: "final" },
57
+ },
58
+ });
59
+ ```
60
+
61
+ The model sees two tools, one for `ADD` and one for `CHECKOUT`. It calls `ADD` twice and `CHECKOUT` once. `CHECKOUT` moves the machine to `paid`, so the loop stops and `onDone` does not run.
62
+
63
+ ## Input
64
+
65
+ | Field | Description |
66
+ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
67
+ | `model` | Model ref. Required. |
68
+ | `name` | Semantic request identity. Defaults to the invoke id. |
69
+ | `system`, `prompt`, `messages` | Same as a text request. See [Text requests](text-requests.md). |
70
+ | `allowedEvents` | Event types offered as tools, intersected with what the state accepts. Omitted means all of them. |
71
+ | `tools` | Plain tools offered beside the event tools. See [Tools](tools.md). |
72
+ | `maxSteps` | Bound on the host's tool loop. Default `DEFAULT_ACT_MAX_STEPS` (20). |
73
+ | `temperature`, `maxOutputTokens`, `topP`, `topK`, `seed`, `stopSequences`, `metadata` | Passed through to the request. |
74
+
75
+ ## Event tools
76
+
77
+ - Each accepted event becomes one tool. The tool name is the event's tool name, and its input is the event's payload schema.
78
+ - Events tagged `meta: { actor: "human" }` are never offered. See [Events a person sends](decisions.md#events-a-person-sends).
79
+ - Calls run one at a time, in call order, even when the host runs tools concurrently.
80
+ - A payload that fails the event's schema answers with the validation error. Nothing is sent.
81
+ - An event the current snapshot does not accept answers `'<type>' is not allowed in state <value>`. Nothing is sent.
82
+ - An accepted event is sent to the machine. The call waits for the transition to commit, then answers with a delta: `{ state }` when the state value changed, and `changed` with each context key that changed (values truncated to 120 characters).
83
+
84
+ ## When the loop ends
85
+
86
+ - The model stops calling tools, or the loop reaches `maxSteps`: the invoke completes with the final text as `event.output`.
87
+ - The invoking state exits, for example because an event targeted another state: every later call answers `ACT_STATE_EXITED` (`"state exited; stopped"`), the executor's signal aborts, and the invoke reports nothing.
88
+
89
+ ## Execution
90
+
91
+ - `agent.act` runs on the `generateText` executor, as one text request carrying the event tools. Any adapter with a host-side tool loop runs it. See [Hosts](hosts.md).
92
+ - Usage, the model-call budget, and traces count it like any text request. See [Usage and budgets](usage-and-budgets.md).
93
+ - Events it sends are journaled like any delivered event, in delivery order. See [The event log](event-log.md).
94
+ - `lintAgentMachine` reports `decide-allows-human-event` when its literal `allowedEvents` names a human-tagged event.
95
+
96
+ > **Warning:** An act loop does not resume mid-flight. After a crash, the events it already sent replay from the journal, and if the invoking state is still active the invoke restarts with a fresh model call.
97
+
98
+ ## Related
99
+
100
+ - [Decisions](decisions.md)
101
+ - [Tools](tools.md)
102
+ - [Hosts](hosts.md)
@@ -0,0 +1,105 @@
1
+ # Advanced: bare XState actors and hand-written executors
2
+
3
+ Most hosts call `runToQuiescence`, or drive the [runtime loop](steps.md) themselves. This page covers the two things underneath those: binding executors onto a machine so it runs as a plain XState actor, and writing an executor without an adapter.
4
+
5
+ ## `provideExecutors`: the machine as a plain actor
6
+
7
+ `provideExecutors(machine, executors)` returns a `machine.provide(...)`-ed copy whose `agent.generateText`, `agent.streamText`, and `agent.decide` sources call your executors. What comes back is an ordinary XState machine, so `createActor` runs it with no run loop around it.
8
+
9
+ ```ts no-check
10
+ import { createActor } from "xstate";
11
+ import { provideExecutors } from "@statelyai/agent";
12
+
13
+ const actor = createActor(provideExecutors(machine, executors), { input });
14
+ actor.start();
15
+ actor.send({ type: "USER_REPLIED", text: "Continue" });
16
+ ```
17
+
18
+ Reach for this when:
19
+
20
+ - **Your application already owns the actor.** A framework's XState integration (`useActor`, an actor registry, a durable actor runtime) wants a machine, not a promise of a result.
21
+ - **The agent machine is a child in a larger XState system.** Invoke or spawn the bound machine from a parent machine like any other actor logic; its decisions and requests run inside the parent's actor system.
22
+ - **The actor is long-lived.** A chat session, a game loop, or a device controller keeps one actor running across many human turns instead of resuming from a snapshot per turn.
23
+
24
+ What you give up compared with `runToQuiescence`: there is no idle settling, no `maxModelCalls` cap, no event log or `snapshot`/`event` resume options, and no `run.start`/`run.end` trace boundary. The actor runs until you stop it. Usage events (`@agent.usage`) are still delivered to the machine, and `onTrace` still receives the request-level trace.
25
+
26
+ ```ts no-check
27
+ const bound = provideExecutors(machine, executors, {
28
+ onChunk: (chunk) => stream.write(chunk),
29
+ onTrace: (event) => log.push(event),
30
+ });
31
+ ```
32
+
33
+ - `actors` merges extra actor sources before binding, the same shape as `machine.provide({ actors })`.
34
+ - `onChunk` receives every chunk of every `mode: 'stream'` request.
35
+ - `onTrace` receives `request.start`, `request.end`, `request.error`, and `stream.chunk` events with the same envelope `runToQuiescence` emits, minted per root actor. Pair it with `traceTransitions` on the actor's `inspect` option to fold `machine.transition` events into the same stream.
36
+
37
+ `provideExecutors` does not descend into invoked child machines. A child with its own agent requests needs its own `provideExecutors(...)` call, or `bindRequestExecutor` on its request logic (below). `runToQuiescence` rebinds children for you.
38
+
39
+ ## Writing an executor by hand
40
+
41
+ An executor is a plain function. `generateText` and `streamText` take the lowered request and return the same shape the machine receives in the invoke's `onDone`:
42
+
43
+ ```ts no-check
44
+ const executors = {
45
+ generateText: async (request, info) => {
46
+ const response = await mySdk.generate({
47
+ model: request.model,
48
+ system: request.system,
49
+ messages: request.messages,
50
+ signal: info?.signal,
51
+ });
52
+ return {
53
+ result: response.text,
54
+ messages: response.messages,
55
+ usage: { inputTokens: response.usage.input, outputTokens: response.usage.output },
56
+ };
57
+ },
58
+ };
59
+ ```
60
+
61
+ - `result` is the value: the text, or the structured object the request's output schema describes. Core validates it against that schema.
62
+ - `messages` are the provider's response messages for this call. They arrive on `output.messages` in `onDone`, so the machine decides what to keep.
63
+ - `usage` is this call's token usage on the flat `inputTokens`/`outputTokens`/`totalTokens` names. `runToQuiescence` folds it into the run's aggregate and the `@agent.usage` event.
64
+ - Anything else (`finishReason`, `toolCalls`, `raw`) rides along to `onResult(request, { raw })` and the `request.end` trace.
65
+
66
+ `streamText` returns the same shape once the stream finishes and calls `info.onChunk` for each chunk on the way. `decide` returns `{ event }`, the machine event the model chose from `request.events`; see [Decisions](decisions.md).
67
+
68
+ ### Structured output
69
+
70
+ A structured request carries `request.outputSchema`. Ask the provider for the schema wrapped in a root object, which every provider accepts, and return the parsed `result`:
71
+
72
+ ```ts no-check
73
+ import { getJsonSchema, parseProviderOutput, providerOutputSchema } from "@statelyai/agent";
74
+
75
+ if (request.outputSchema) {
76
+ const schema = providerOutputSchema(request.outputSchema, {
77
+ reasoning: request.includeReasoning,
78
+ });
79
+ const jsonSchema = await getJsonSchema(schema);
80
+ const raw = await mySdk.generateJson({ ...call, schema: jsonSchema });
81
+ return parseProviderOutput(request, raw); // { result, reasoning? }
82
+ }
83
+ ```
84
+
85
+ `providerOutputSchema` builds the `{ result, reasoning? }` schema to send. `parseProviderOutput` validates the provider's JSON against it and returns `{ result, reasoning? }`, which is already a valid executor result. The machine still validates `result` against the schema it declared.
86
+
87
+ ### Sharing one executor with a child machine
88
+
89
+ `bindRequestExecutor(logic, executor)` binds a request's `TextLogic` to a `generateText`-shaped function, so a parent and its child machines can share one executor without a second `provideExecutors` call:
90
+
91
+ ```ts no-check
92
+ childMachine.provide({
93
+ actors: {
94
+ researchTopic: bindRequestExecutor(childSetup.requests.researchTopic, executors.generateText),
95
+ },
96
+ });
97
+ ```
98
+
99
+ ### Helpers for the raw result
100
+
101
+ - `getCallUsage(raw)` reads a call's normalized usage off any executor result.
102
+ - `getCallFinishReason(raw)` reads its normalized finish reason.
103
+ - `parseOutput(schema, value)` validates a bare value against a request's declared schema, for hosts that unwrap provider output themselves.
104
+
105
+ The adapters in `@statelyai/agent/ai-sdk`, `@statelyai/agent/openai`, and `@statelyai/agent/tanstack-ai` are built from exactly these pieces. Read them when a provider needs something this page does not cover.