@statelyai/agent 2.0.0-alpha.38 → 2.0.0-alpha.40

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 (137) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
  3. package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
  4. package/dist/ai-sdk.cjs +4 -4
  5. package/dist/ai-sdk.d.cts +2 -3
  6. package/dist/ai-sdk.d.mts +2 -3
  7. package/dist/ai-sdk.mjs +4 -4
  8. package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
  9. package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
  10. package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
  11. package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
  12. package/dist/effects-B9IvUPVh.mjs +23 -0
  13. package/dist/effects-DrWcUGgc.cjs +34 -0
  14. package/dist/evals.cjs +810 -0
  15. package/dist/evals.d.cts +595 -0
  16. package/dist/evals.d.mts +595 -0
  17. package/dist/evals.mjs +801 -0
  18. package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
  19. package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
  20. package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
  21. package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
  22. package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
  23. package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
  24. package/dist/index.cjs +142 -97
  25. package/dist/index.d.cts +97 -141
  26. package/dist/index.d.mts +97 -141
  27. package/dist/index.mjs +123 -74
  28. package/dist/internal-BzlpzSux.d.cts +14 -0
  29. package/dist/internal-BzlpzSux.d.mts +14 -0
  30. package/dist/log.cjs +2 -3
  31. package/dist/log.d.cts +2 -2
  32. package/dist/log.d.mts +2 -2
  33. package/dist/log.mjs +3 -3
  34. package/dist/machine-input-0YTPcnCm.mjs +27 -0
  35. package/dist/machine-input-DU3owLUr.cjs +32 -0
  36. package/dist/machines.cjs +1 -719
  37. package/dist/machines.d.cts +2 -424
  38. package/dist/machines.d.mts +2 -424
  39. package/dist/machines.mjs +2 -709
  40. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  41. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  42. package/dist/openai.cjs +3 -3
  43. package/dist/openai.d.cts +2 -3
  44. package/dist/openai.d.mts +2 -3
  45. package/dist/openai.mjs +3 -3
  46. package/dist/otel.d.cts +1 -1
  47. package/dist/otel.d.mts +1 -1
  48. package/dist/policy.cjs +77 -0
  49. package/dist/policy.d.cts +143 -0
  50. package/dist/policy.d.mts +143 -0
  51. package/dist/policy.mjs +75 -0
  52. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-BO9RSb7i.d.cts} +33 -40
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-BxkeuAYR.d.mts} +33 -40
  54. package/dist/{effects-DDseYtJk.cjs → run-agent-COdR9FpM.cjs} +175 -228
  55. package/dist/{effects-BT_cSY0j.mjs → run-agent-D3gW9wfd.mjs} +176 -211
  56. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  57. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  58. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  59. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  60. package/dist/tanstack-ai.cjs +4 -4
  61. package/dist/tanstack-ai.d.cts +2 -3
  62. package/dist/tanstack-ai.d.mts +2 -3
  63. package/dist/tanstack-ai.mjs +4 -4
  64. package/dist/testing.cjs +122 -996
  65. package/dist/testing.d.cts +36 -695
  66. package/dist/testing.d.mts +36 -695
  67. package/dist/testing.mjs +112 -977
  68. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  69. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  70. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  71. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  72. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  73. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  74. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  75. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  76. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  77. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  78. package/dist/validate.cjs +4 -4
  79. package/dist/validate.d.cts +2 -2
  80. package/dist/validate.d.mts +2 -2
  81. package/dist/validate.mjs +4 -4
  82. package/dist/{verify-DJHfEfm6.d.cts → verify-CIu4mqIZ.d.mts} +56 -6
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-CTHlmBbh.d.cts} +56 -6
  84. package/dist/{verify-ChyX6jq0.mjs → verify-Cacz6XSk.mjs} +170 -46
  85. package/dist/{verify-CwlombbC.cjs → verify-D8UDqU4l.cjs} +170 -46
  86. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  87. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  88. package/docs/advanced.md +5 -5
  89. package/docs/choosing-a-run-mode.md +7 -7
  90. package/docs/debugging.md +6 -8
  91. package/docs/decisions.md +5 -4
  92. package/docs/environment-and-policy.md +1 -1
  93. package/docs/evals.md +57 -43
  94. package/docs/event-log.md +13 -15
  95. package/docs/from-a-loop.md +3 -3
  96. package/docs/generate-machines.md +4 -4
  97. package/docs/hosts.md +25 -30
  98. package/docs/human-in-the-loop.md +5 -8
  99. package/docs/index.md +4 -4
  100. package/docs/judgments.md +5 -7
  101. package/docs/langgraph-comparison.md +6 -6
  102. package/docs/machines-as-data.md +7 -12
  103. package/docs/machines-presets.md +17 -120
  104. package/docs/machines.md +13 -13
  105. package/docs/models-and-providers.md +19 -25
  106. package/docs/multi-agent.md +1 -1
  107. package/docs/observability.md +6 -8
  108. package/docs/persistence.md +10 -20
  109. package/docs/quickstart.md +3 -3
  110. package/docs/statechart-policy-examples.md +1 -1
  111. package/docs/steps.md +5 -6
  112. package/docs/strangler-fig.md +105 -33
  113. package/docs/text-requests.md +10 -12
  114. package/docs/thinking-in-state-machines.md +8 -8
  115. package/docs/tools.md +10 -12
  116. package/docs/upgrading.md +1 -1
  117. package/docs/usage-and-budgets.md +51 -56
  118. package/docs/validate-and-repair.md +9 -14
  119. package/docs/verify.md +54 -7
  120. package/docs/xstate-4-and-5-apps.md +19 -28
  121. package/llms.txt +1 -1
  122. package/package.json +31 -6
  123. package/readme.md +32 -24
  124. package/dist/internal-C3Lqu538.d.cts +0 -43
  125. package/dist/internal-DUcdhk-i.d.mts +0 -43
  126. package/dist/types-DQUOOaZO.d.cts +0 -238
  127. package/dist/types-DQUOOaZO.d.mts +0 -238
  128. package/skills/add-evals/SKILL.md +0 -152
  129. package/skills/add-traces/SKILL.md +0 -152
  130. package/skills/build-machine/SKILL.md +0 -84
  131. package/skills/generate-machine/SKILL.md +0 -335
  132. package/skills/graph-engineering/SKILL.md +0 -43
  133. package/skills/improve-machine/SKILL.md +0 -261
  134. package/skills/improve-machine/reference.md +0 -101
  135. package/skills/loop-to-machine/SKILL.md +0 -205
  136. package/skills/loop-to-machine/policy.md +0 -154
  137. package/skills/loop-to-machine/reference.md +0 -260
package/dist/machines.mjs CHANGED
@@ -1,10 +1,6 @@
1
- import { r as setupAgent } from "./setup-agent-BDmNr6PC.mjs";
1
+ import { r as setupAgent } from "./setup-agent-CLm6QVGy.mjs";
2
2
  import { createAsyncLogic } from "xstate";
3
3
  //#region src/machines/internal.ts
4
- /** The builtin inline text request every preset lowers a request entry to. */
5
- const GENERATE_TEXT_SRC = "agent.generateText";
6
- /** The builtin decision actor the router and supervisor presets invoke. */
7
- const DECIDE_SRC = "agent.decide";
8
4
  /**
9
5
  * A permissive Standard Schema that carries a JSON Schema. Presets build their
10
6
  * own context/input/output schemas this way so the module stays dependency-free
@@ -59,8 +55,6 @@ const emptyPayload = objectSchema({});
59
55
  /** JSON Schema fragments reused across preset context schemas. @internal */
60
56
  const jsonString = { type: "string" };
61
57
  /** @internal */
62
- const jsonNumber = { type: "number" };
63
- /** @internal */
64
58
  const jsonRecord = {
65
59
  type: "object",
66
60
  additionalProperties: true
@@ -69,707 +63,6 @@ const jsonRecord = {
69
63
  const jsonArray = { type: "array" };
70
64
  /** @internal */
71
65
  const jsonAny = {};
72
- /** True when `entry` delegates to a child machine rather than an inline request. @internal */
73
- function isMachineEntry(entry) {
74
- return "machine" in entry && !!entry.machine;
75
- }
76
- /** The actor sources a preset must register: one per child-machine entry. @internal */
77
- function machineActors(entries) {
78
- return Object.fromEntries(Object.entries(entries).filter(([, entry]) => isMachineEntry(entry)).map(([name, entry]) => [name, entry.machine]));
79
- }
80
- /** The `src` an entry invokes: its own actor key (child machine) or the inline text builtin. @internal */
81
- function entrySrc(name, entry) {
82
- return isMachineEntry(entry) ? name : GENERATE_TEXT_SRC;
83
- }
84
- /**
85
- * The value an entry's invoke produced: a child machine's output as-is, or the
86
- * validated `result` off the `{ result, messages }` a text request
87
- * resolves with. @internal
88
- */
89
- function entryOutput(entry, output) {
90
- return isMachineEntry(entry) ? output : output.result;
91
- }
92
- /** Builds an entry's invoke `input` from the current prompt. @internal */
93
- function entryInput(name, entry, defaultModel, prompt) {
94
- if (isMachineEntry(entry)) return entry.input ? entry.input({ prompt }) : { prompt };
95
- return requestInput(name, entry, defaultModel, prompt);
96
- }
97
- /** Builds the inline `agent.generateText` input for a request entry. @internal */
98
- function requestInput(name, entry, defaultModel, prompt) {
99
- const model = entry.model ?? defaultModel;
100
- if (!model) throw new Error(`Preset request '${name}' has no model. Set 'model' on the entry or on the factory config.`);
101
- return {
102
- name,
103
- model,
104
- ...entry.instructions ? { system: entry.instructions } : {},
105
- prompt,
106
- ...entry.tools ? { tools: entry.tools } : {},
107
- ...entry.outputSchema ? { outputSchema: entry.outputSchema } : {},
108
- ...entry.maxSteps !== void 0 ? { maxSteps: entry.maxSteps } : {}
109
- };
110
- }
111
- /**
112
- * Rejects an entry name that would collide with a preset's own state names or
113
- * with the reserved `agent.*` actor namespace. A collision is otherwise a
114
- * confusing machine-build failure far from its cause.
115
- *
116
- * @internal
117
- */
118
- function assertEntryNames(kind, names, reserved) {
119
- if (names.length === 0) throw new Error(`Preset requires at least one ${kind}.`);
120
- for (const name of names) {
121
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`Invalid ${kind} name '${name}'. Names must be identifier-like (letters, digits, underscore; not starting with a digit) — they become state names and event types.`);
122
- if (reserved.includes(name)) throw new Error(`Invalid ${kind} name '${name}': it collides with a state this preset already declares (${reserved.join(", ")}). Rename it.`);
123
- }
124
- }
125
- /** Renders the `name: description` list a routing/supervising model chooses from. @internal */
126
- function renderEntryList(entries) {
127
- return Object.entries(entries).map(([name, entry]) => `- ${name}: ${entry.description ?? "(no description)"}`).join("\n");
128
- }
129
- //#endregion
130
- //#region src/machines/tool-loop.ts
131
- const contextSchema$7 = objectSchema({
132
- prompt: jsonString,
133
- result: jsonAny
134
- }, ["prompt"]);
135
- const inputSchema$7 = objectSchema({ prompt: jsonString }, ["prompt"]);
136
- const outputSchema$6 = objectSchema({ result: jsonAny }, ["result"]);
137
- /**
138
- * The single-state tool loop: one text request carries the `tools`, and the
139
- * host runs the tool loop inside it (`maxSteps` bounds it). Selecting and
140
- * executing tools is the model + host's business, not machine states.
141
- *
142
- * States: `answering` → `done`.
143
- *
144
- * ```ts
145
- * const machine = createToolLoopMachine({
146
- * model: "quick",
147
- * instructions: "Answer using the tools.",
148
- * tools: { calculate },
149
- * maxSteps: 5,
150
- * });
151
- *
152
- * const result = await runToQuiescence(createAgentRuntime(machine, { executors }), {
153
- * input: { prompt: "What is 42 * 17?" },
154
- * });
155
- * // Snapshots and log entries carry machine.version ("1") automatically.
156
- * ```
157
- */
158
- function createToolLoopMachine(config) {
159
- const { model, instructions, tools, outputSchema: resultSchema, maxSteps } = config;
160
- return setupAgent({
161
- context: contextSchema$7,
162
- input: inputSchema$7,
163
- output: outputSchema$6
164
- }).createMachine({
165
- id: "tool-loop",
166
- version: "1",
167
- context: ({ input }) => ({
168
- prompt: input.prompt,
169
- result: null
170
- }),
171
- initial: "answering",
172
- states: {
173
- answering: { invoke: {
174
- id: "answer",
175
- src: GENERATE_TEXT_SRC,
176
- input: ({ context }) => ({
177
- name: "answer",
178
- model,
179
- ...instructions ? { system: instructions } : {},
180
- prompt: context.prompt,
181
- ...tools ? { tools } : {},
182
- ...resultSchema ? { outputSchema: resultSchema } : {},
183
- ...maxSteps !== void 0 ? { maxSteps } : {}
184
- }),
185
- onDone: ({ output }) => ({
186
- target: "done",
187
- context: { result: output.result }
188
- })
189
- } },
190
- done: {
191
- type: "final",
192
- output: ({ context }) => ({ result: context.result })
193
- }
194
- }
195
- });
196
- }
197
- //#endregion
198
- //#region src/machines/sequential.ts
199
- const contextSchema$6 = objectSchema({
200
- prompt: jsonString,
201
- results: jsonRecord,
202
- previous: jsonAny
203
- }, ["prompt", "results"]);
204
- const inputSchema$6 = objectSchema({ prompt: jsonString }, ["prompt"]);
205
- const outputSchema$5 = objectSchema({
206
- results: jsonRecord,
207
- output: jsonAny
208
- }, ["results"]);
209
- /**
210
- * A prompt chain: each step is one state, and each step's output feeds the
211
- * next. The default prompt for a step is the previous step's output, so a
212
- * chain needs no `prompt` functions at all.
213
- *
214
- * States: one per step, in order → `done`.
215
- *
216
- * ```ts
217
- * const machine = createSequentialMachine({
218
- * model: "quick",
219
- * steps: [
220
- * { name: "outline", instructions: "Outline the post." },
221
- * { name: "draft", instructions: "Write the post from the outline." },
222
- * { name: "polish", instructions: "Tighten the prose." },
223
- * ],
224
- * });
225
- * ```
226
- */
227
- function createSequentialMachine(config) {
228
- const { model, steps } = config;
229
- assertEntryNames("step", steps.map((step) => step.name), ["done"]);
230
- const agentSetup = setupAgent({
231
- context: contextSchema$6,
232
- input: inputSchema$6,
233
- output: outputSchema$5
234
- });
235
- const states = {};
236
- steps.forEach((step, index) => {
237
- const next = steps[index + 1]?.name ?? "done";
238
- states[step.name] = { invoke: {
239
- id: step.name,
240
- src: GENERATE_TEXT_SRC,
241
- input: ({ context }) => requestInput(step.name, {
242
- instructions: step.instructions,
243
- model: step.model,
244
- outputSchema: step.outputSchema,
245
- tools: step.tools,
246
- maxSteps: step.maxSteps
247
- }, model, step.prompt ? step.prompt({
248
- prompt: context.prompt,
249
- results: context.results,
250
- previous: context.previous
251
- }) : context.previous === null || context.previous === void 0 ? context.prompt : String(context.previous)),
252
- onDone: ({ context, output }) => ({
253
- target: next,
254
- context: {
255
- results: {
256
- ...context.results,
257
- [step.name]: output.result
258
- },
259
- previous: output.result
260
- }
261
- })
262
- } };
263
- });
264
- states.done = {
265
- type: "final",
266
- output: ({ context }) => ({
267
- results: context.results,
268
- output: context.previous
269
- })
270
- };
271
- const machineConfig = {
272
- id: "sequential",
273
- version: "1",
274
- context: ({ input }) => ({
275
- prompt: input.prompt,
276
- results: {},
277
- previous: null
278
- }),
279
- initial: steps[0].name,
280
- states
281
- };
282
- return agentSetup.createMachine(machineConfig);
283
- }
284
- //#endregion
285
- //#region src/machines/router.ts
286
- const contextSchema$5 = objectSchema({
287
- prompt: jsonString,
288
- route: { type: ["string", "null"] },
289
- result: jsonAny
290
- }, ["prompt"]);
291
- const inputSchema$5 = objectSchema({ prompt: jsonString }, ["prompt"]);
292
- const outputSchema$4 = objectSchema({
293
- route: { type: ["string", "null"] },
294
- result: jsonAny
295
- }, ["route"]);
296
- /** The event a route decision chooses: `ROUTE_<name>`. */
297
- function routeEventType(route) {
298
- return `ROUTE_${route}`;
299
- }
300
- /**
301
- * One `agent.decide` picks exactly one declared route, then the machine runs
302
- * it. Only the declared routes have events and transitions, so a model naming
303
- * anything else is rejected before any work happens — illegal routes are
304
- * impossible, not discouraged.
305
- *
306
- * States: `routing` → one state per route → `done`.
307
- *
308
- * ```ts
309
- * const machine = createRouterMachine({
310
- * model: "quick",
311
- * routes: {
312
- * billing: { description: "Payments and invoices", instructions: "Answer the billing question." },
313
- * technical: { description: "Bugs and outages", machine: technicalMachine },
314
- * },
315
- * fallback: "technical",
316
- * });
317
- * ```
318
- */
319
- function createRouterMachine(config) {
320
- const { model, instructions, routes, fallback } = config;
321
- const names = Object.keys(routes);
322
- assertEntryNames("route", names, ["routing", "done"]);
323
- if (fallback !== void 0 && !names.includes(fallback)) throw new Error(`createRouterMachine: fallback '${fallback}' is not a declared route (${names.join(", ")}).`);
324
- const agentSetup = setupAgent({
325
- context: contextSchema$5,
326
- input: inputSchema$5,
327
- output: outputSchema$4,
328
- events: Object.fromEntries(names.map((name) => [routeEventType(name), emptyPayload])),
329
- actors: machineActors(routes)
330
- });
331
- const routeList = renderEntryList(routes);
332
- const states = {
333
- routing: {
334
- invoke: {
335
- id: "route",
336
- src: DECIDE_SRC,
337
- input: ({ context }) => ({
338
- model,
339
- system: instructions ?? "Route the request to exactly one destination. Choose the single best fit.",
340
- prompt: `Request:\n${context.prompt}\n\nDestinations:\n${routeList}`,
341
- allowedEvents: names.map(routeEventType)
342
- }),
343
- ...fallback ? { onError: {
344
- target: fallback,
345
- context: { route: fallback }
346
- } } : {}
347
- },
348
- on: Object.fromEntries(names.map((name) => [routeEventType(name), {
349
- target: name,
350
- context: { route: name }
351
- }]))
352
- },
353
- done: {
354
- type: "final",
355
- output: ({ context }) => ({
356
- route: context.route,
357
- result: context.result
358
- })
359
- }
360
- };
361
- for (const [name, entry] of Object.entries(routes)) states[name] = { invoke: {
362
- id: name,
363
- src: entrySrc(name, entry),
364
- input: ({ context }) => entryInput(name, entry, model, context.prompt),
365
- onDone: ({ output }) => ({
366
- target: "done",
367
- context: { result: entryOutput(entry, output) }
368
- })
369
- } };
370
- const machineConfig = {
371
- id: "router",
372
- version: "1",
373
- context: ({ input }) => ({
374
- prompt: input.prompt,
375
- route: null,
376
- result: null
377
- }),
378
- initial: "routing",
379
- states
380
- };
381
- return agentSetup.createMachine(machineConfig);
382
- }
383
- //#endregion
384
- //#region src/machines/parallel.ts
385
- const contextSchema$4 = objectSchema({
386
- prompt: jsonString,
387
- results: jsonRecord
388
- }, ["prompt", "results"]);
389
- const inputSchema$4 = objectSchema({ prompt: jsonString }, ["prompt"]);
390
- const outputSchema$3 = objectSchema({ results: jsonRecord }, ["results"]);
391
- /**
392
- * Static fan-out: every branch runs concurrently as its own region of one
393
- * parallel state, and the run joins when all of them finish. Results are keyed
394
- * by branch name.
395
- *
396
- * Branch count is fixed at author time. For an N decided at run time (a planner
397
- * choosing subtopics), eject to `examples/fan-out`, which spawns branches
398
- * dynamically.
399
- *
400
- * States: `running` (one region per branch) → `done`.
401
- *
402
- * ```ts
403
- * const machine = createParallelMachine({
404
- * model: "quick",
405
- * branches: {
406
- * security: { instructions: "Review for security issues." },
407
- * performance: { instructions: "Review for performance issues." },
408
- * },
409
- * });
410
- * ```
411
- */
412
- function createParallelMachine(config) {
413
- const { model, branches } = config;
414
- assertEntryNames("branch", Object.keys(branches), ["running", "done"]);
415
- const agentSetup = setupAgent({
416
- context: contextSchema$4,
417
- input: inputSchema$4,
418
- output: outputSchema$3,
419
- actors: machineActors(branches)
420
- });
421
- const regions = {};
422
- for (const [name, entry] of Object.entries(branches)) regions[name] = {
423
- initial: "running",
424
- states: {
425
- running: { invoke: {
426
- id: name,
427
- src: entrySrc(name, entry),
428
- input: ({ context }) => entryInput(name, entry, model, context.prompt),
429
- onDone: ({ context, output }) => ({
430
- target: "done",
431
- context: { results: {
432
- ...context.results,
433
- [name]: entryOutput(entry, output)
434
- } }
435
- })
436
- } },
437
- done: { type: "final" }
438
- }
439
- };
440
- const machineConfig = {
441
- id: "parallel",
442
- version: "1",
443
- context: ({ input }) => ({
444
- prompt: input.prompt,
445
- results: {}
446
- }),
447
- initial: "running",
448
- states: {
449
- running: {
450
- type: "parallel",
451
- states: regions,
452
- onDone: { target: "done" }
453
- },
454
- done: {
455
- type: "final",
456
- output: ({ context }) => ({ results: context.results })
457
- }
458
- }
459
- };
460
- return agentSetup.createMachine(machineConfig);
461
- }
462
- //#endregion
463
- //#region src/machines/loop.ts
464
- const contextSchema$3 = objectSchema({
465
- prompt: jsonString,
466
- iterations: jsonNumber,
467
- results: jsonArray,
468
- last: jsonAny
469
- }, [
470
- "prompt",
471
- "iterations",
472
- "results"
473
- ]);
474
- const inputSchema$3 = objectSchema({ prompt: jsonString }, ["prompt"]);
475
- const outputSchema$2 = objectSchema({
476
- iterations: jsonNumber,
477
- results: jsonArray,
478
- last: jsonAny
479
- }, ["iterations", "results"]);
480
- /**
481
- * A bounded repeat: run the body, check `until` over the accumulated state,
482
- * and either stop or go again. `maxTurns` is a guard, so the loop cannot
483
- * run away even if `until` never returns `true`.
484
- *
485
- * States: `running` → `checking` → (`running` | `done`).
486
- *
487
- * ```ts
488
- * const machine = createLoopMachine({
489
- * model: "quick",
490
- * body: { instructions: "Improve the draft. Return only the draft." },
491
- * until: ({ last }) => String(last).length > 500,
492
- * maxTurns: 4,
493
- * });
494
- * ```
495
- */
496
- function createLoopMachine(config) {
497
- const { model, body, until, maxTurns } = config;
498
- if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new Error("createLoopMachine: maxTurns must be an integer >= 1.");
499
- const agentSetup = setupAgent({
500
- context: contextSchema$3,
501
- input: inputSchema$3,
502
- output: outputSchema$2,
503
- actors: isMachineEntry(body) ? { body: body.machine } : {}
504
- });
505
- const loopState = (context) => ({
506
- prompt: context.prompt,
507
- iterations: context.iterations,
508
- results: context.results,
509
- last: context.last
510
- });
511
- const machineConfig = {
512
- id: "loop",
513
- version: "1",
514
- context: ({ input }) => ({
515
- prompt: input.prompt,
516
- iterations: 0,
517
- results: [],
518
- last: null
519
- }),
520
- initial: "running",
521
- states: {
522
- running: { invoke: {
523
- id: "body",
524
- src: entrySrc("body", body),
525
- input: ({ context }) => entryInput("body", body, model, body.prompt ? body.prompt(loopState(context)) : context.prompt),
526
- onDone: ({ context, output }) => {
527
- const result = entryOutput(body, output);
528
- return {
529
- target: "checking",
530
- context: {
531
- iterations: context.iterations + 1,
532
- results: [...context.results, result],
533
- last: result
534
- }
535
- };
536
- }
537
- } },
538
- checking: {
539
- type: "choice",
540
- choice: ({ context }) => context.iterations >= maxTurns || until(loopState(context)) ? { target: "done" } : { target: "running" }
541
- },
542
- done: {
543
- type: "final",
544
- output: ({ context }) => ({
545
- iterations: context.iterations,
546
- results: context.results,
547
- last: context.last
548
- })
549
- }
550
- }
551
- };
552
- return agentSetup.createMachine(machineConfig);
553
- }
554
- //#endregion
555
- //#region src/machines/supervisor.ts
556
- const contextSchema$2 = objectSchema({
557
- task: jsonString,
558
- results: jsonRecord,
559
- turns: jsonNumber,
560
- worker: { type: ["string", "null"] }
561
- }, [
562
- "task",
563
- "results",
564
- "turns"
565
- ]);
566
- const inputSchema$2 = objectSchema({ task: jsonString }, ["task"]);
567
- const outputSchema$1 = objectSchema({
568
- results: jsonRecord,
569
- turns: jsonNumber
570
- }, ["results", "turns"]);
571
- /** The event a supervising decision chooses to delegate to a worker: `DELEGATE_<name>`. */
572
- function delegateEventType(worker) {
573
- return `DELEGATE_${worker}`;
574
- }
575
- /** The event a supervising decision chooses to stop. */
576
- const FINISH_EVENT_TYPE = "FINISH";
577
- /**
578
- * A supervisor delegating to typed workers: each turn, one `agent.decide`
579
- * picks a worker or `FINISH`. Worker results accumulate in context and are fed
580
- * back into the next decision.
581
- *
582
- * Control always returns to the supervisor after a worker finishes — that is
583
- * what separates this from {@link createHandoffMachine}, where control
584
- * transfers and does not come back.
585
- *
586
- * `maxTurns` bounds the delegations twice over: a spent budget removes every
587
- * `DELEGATE_*` from the decision's candidate events, and a guard on each
588
- * delegate transition rejects one anyway. `FINISH` is all that is left.
589
- *
590
- * States: `supervising` → one state per worker → `supervising` → … → `done`.
591
- *
592
- * ```ts
593
- * const machine = createSupervisorMachine({
594
- * model: "quick",
595
- * workers: {
596
- * researcher: { description: "Facts and background", instructions: "Research it." },
597
- * writer: { description: "Prose and summaries", instructions: "Write it up." },
598
- * },
599
- * maxTurns: 4,
600
- * });
601
- * ```
602
- */
603
- function createSupervisorMachine(config) {
604
- const { model, instructions, workers, maxTurns = 6 } = config;
605
- const names = Object.keys(workers);
606
- assertEntryNames("worker", names, ["supervising", "done"]);
607
- if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new Error("createSupervisorMachine: maxTurns must be an integer >= 1.");
608
- const agentSetup = setupAgent({
609
- context: contextSchema$2,
610
- input: inputSchema$2,
611
- output: outputSchema$1,
612
- events: {
613
- ...Object.fromEntries(names.map((name) => [delegateEventType(name), emptyPayload])),
614
- [FINISH_EVENT_TYPE]: emptyPayload
615
- },
616
- actors: machineActors(workers)
617
- });
618
- const workerList = renderEntryList(workers);
619
- const states = {
620
- supervising: {
621
- invoke: {
622
- id: "supervise",
623
- src: DECIDE_SRC,
624
- input: ({ context }) => ({
625
- model,
626
- system: instructions ?? "You are a supervisor. Delegate the task to one worker at a time, then finish once the accumulated results answer it.",
627
- prompt: `Task:\n${context.task}\n\nWorkers:\n${workerList}\n\nResults so far:\n${renderResults(context.results)}\n\nTurns used: ${context.turns} of ${maxTurns}.`,
628
- allowedEvents: context.turns < maxTurns ? [...names.map(delegateEventType), FINISH_EVENT_TYPE] : [FINISH_EVENT_TYPE]
629
- })
630
- },
631
- on: {
632
- ...Object.fromEntries(names.map((name) => [delegateEventType(name), ({ context }) => context.turns < maxTurns ? {
633
- target: name,
634
- context: { worker: name }
635
- } : void 0])),
636
- [FINISH_EVENT_TYPE]: { target: "done" }
637
- }
638
- },
639
- done: {
640
- type: "final",
641
- output: ({ context }) => ({
642
- results: context.results,
643
- turns: context.turns
644
- })
645
- }
646
- };
647
- for (const [name, entry] of Object.entries(workers)) states[name] = { invoke: {
648
- id: name,
649
- src: entrySrc(name, entry),
650
- input: ({ context }) => entryInput(name, entry, model, context.task),
651
- onDone: ({ context, output }) => ({
652
- target: "supervising",
653
- context: {
654
- results: {
655
- ...context.results,
656
- [name]: entryOutput(entry, output)
657
- },
658
- turns: context.turns + 1
659
- }
660
- })
661
- } };
662
- const machineConfig = {
663
- id: "supervisor",
664
- version: "1",
665
- context: ({ input }) => ({
666
- task: input.task,
667
- results: {},
668
- turns: 0,
669
- worker: null
670
- }),
671
- initial: "supervising",
672
- states
673
- };
674
- return agentSetup.createMachine(machineConfig);
675
- }
676
- function renderResults(results) {
677
- const entries = Object.entries(results);
678
- if (entries.length === 0) return "(none yet)";
679
- return entries.map(([name, value]) => `- ${name}: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("\n");
680
- }
681
- //#endregion
682
- //#region src/machines/handoff.ts
683
- const contextSchema$1 = objectSchema({
684
- message: jsonString,
685
- activeAgent: jsonString,
686
- reply: jsonAny
687
- }, ["message", "activeAgent"]);
688
- const inputSchema$1 = objectSchema({
689
- message: jsonString,
690
- activeAgent: jsonString
691
- }, ["message"]);
692
- const transferPayload = objectSchema({ message: jsonString });
693
- /** The event that hands the mic to a peer: `transfer_to_<name>`. */
694
- function transferEventType(agent) {
695
- return `transfer_to_${agent}`;
696
- }
697
- /**
698
- * Peer handoff (the swarm shape): `context.activeAgent` holds the mic, runs one
699
- * turn, then the machine settles idle in `waiting`. A `transfer_to_<name>`
700
- * event moves the mic to a peer and re-routes.
701
- *
702
- * Control TRANSFERS and does not return — the opposite of
703
- * {@link createSupervisorMachine}, where every worker hands control back.
704
- *
705
- * There is no final state: a conversation ends when the host stops resuming it.
706
- * Persist the idle snapshot between turns; `activeAgent` round-trips with it.
707
- *
708
- * States: `routing` → one turn state per agent → `waiting` → `routing` → …
709
- *
710
- * ```ts
711
- * const machine = createHandoffMachine({
712
- * model: "quick",
713
- * defaultActiveAgent: "travel",
714
- * agents: {
715
- * travel: { description: "Destinations and itineraries", instructions: "You are a travel concierge." },
716
- * food: { description: "Restaurants and dishes", instructions: "You are a food concierge." },
717
- * },
718
- * });
719
- *
720
- * const next = await runToQuiescence(createAgentRuntime(machine, { executors }), {
721
- * snapshot,
722
- * event: { type: "transfer_to_food", message: "What should I eat there?" },
723
- * });
724
- * ```
725
- */
726
- function createHandoffMachine(config) {
727
- const { agents, defaultActiveAgent, model } = config;
728
- const names = Object.keys(agents);
729
- assertEntryNames("agent", names, ["routing", "waiting"]);
730
- if (!names.includes(defaultActiveAgent)) throw new Error(`createHandoffMachine: defaultActiveAgent '${defaultActiveAgent}' is not a declared agent (${names.join(", ")}).`);
731
- const agentSetup = setupAgent({
732
- context: contextSchema$1,
733
- input: inputSchema$1,
734
- events: Object.fromEntries(names.map((name) => [transferEventType(name), transferPayload])),
735
- actors: machineActors(agents)
736
- });
737
- const turnState = (name) => `${name}Turn`;
738
- const states = {
739
- routing: {
740
- type: "choice",
741
- choice: ({ context }) => ({ target: names.includes(context.activeAgent) ? turnState(context.activeAgent) : turnState(defaultActiveAgent) })
742
- },
743
- waiting: { on: Object.fromEntries(names.map((name) => [transferEventType(name), ({ context, event }) => ({
744
- target: "routing",
745
- context: {
746
- activeAgent: name,
747
- message: event.message ?? context.message
748
- }
749
- })])) }
750
- };
751
- for (const [name, entry] of Object.entries(agents)) states[turnState(name)] = { invoke: {
752
- id: name,
753
- src: entrySrc(name, entry),
754
- input: ({ context }) => entryInput(name, entry, model, context.message),
755
- onDone: ({ output }) => ({
756
- target: "waiting",
757
- context: { reply: entryOutput(entry, output) }
758
- })
759
- } };
760
- const machineConfig = {
761
- id: "handoff",
762
- version: "1",
763
- context: ({ input }) => ({
764
- message: input.message,
765
- activeAgent: input.activeAgent ?? defaultActiveAgent,
766
- reply: null
767
- }),
768
- initial: "routing",
769
- states
770
- };
771
- return agentSetup.createMachine(machineConfig);
772
- }
773
66
  //#endregion
774
67
  //#region src/machines/approval-batch.ts
775
68
  const CHILD_PREFIX = "call:";
@@ -1185,4 +478,4 @@ function createApprovalBatchMachine(config) {
1185
478
  return agentSetup.createMachine(machineConfig);
1186
479
  }
1187
480
  //#endregion
1188
- export { FINISH_EVENT_TYPE, createApprovalBatchMachine, createHandoffMachine, createLoopMachine, createParallelMachine, createRouterMachine, createSequentialMachine, createSupervisorMachine, createToolLoopMachine, delegateEventType, routeEventType, transferEventType };
481
+ export { createApprovalBatchMachine };