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