@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
package/dist/machines.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_setup_agent = require("./setup-agent-CXEBURdo.cjs");
2
+ const require_setup_agent = require("./setup-agent-CmEToB8y.cjs");
3
+ let xstate = require("xstate");
3
4
  //#region src/machines/internal.ts
4
5
  /** The builtin inline text request every preset lowers a request entry to. */
5
6
  const GENERATE_TEXT_SRC = "agent.generateText";
@@ -128,12 +129,12 @@ function renderEntryList(entries) {
128
129
  }
129
130
  //#endregion
130
131
  //#region src/machines/tool-loop.ts
131
- const contextSchema$6 = objectSchema({
132
+ const contextSchema$7 = objectSchema({
132
133
  prompt: jsonString,
133
134
  result: jsonAny
134
135
  }, ["prompt"]);
135
- const inputSchema$6 = objectSchema({ prompt: jsonString }, ["prompt"]);
136
- const outputSchema$5 = objectSchema({ result: jsonAny }, ["result"]);
136
+ const inputSchema$7 = objectSchema({ prompt: jsonString }, ["prompt"]);
137
+ const outputSchema$6 = objectSchema({ result: jsonAny }, ["result"]);
137
138
  /**
138
139
  * The single-state tool loop: one text request carries the `tools`, and the
139
140
  * host runs the tool loop inside it (`maxSteps` bounds it). Selecting and
@@ -158,9 +159,9 @@ const outputSchema$5 = objectSchema({ result: jsonAny }, ["result"]);
158
159
  function createToolLoopMachine(config) {
159
160
  const { model, instructions, tools, outputSchema: resultSchema, maxSteps } = config;
160
161
  return require_setup_agent.setupAgent({
161
- context: contextSchema$6,
162
- input: inputSchema$6,
163
- output: outputSchema$5
162
+ context: contextSchema$7,
163
+ input: inputSchema$7,
164
+ output: outputSchema$6
164
165
  }).createMachine({
165
166
  id: "tool-loop",
166
167
  version: "1",
@@ -196,13 +197,13 @@ function createToolLoopMachine(config) {
196
197
  }
197
198
  //#endregion
198
199
  //#region src/machines/sequential.ts
199
- const contextSchema$5 = objectSchema({
200
+ const contextSchema$6 = objectSchema({
200
201
  prompt: jsonString,
201
202
  results: jsonRecord,
202
203
  previous: jsonAny
203
204
  }, ["prompt", "results"]);
204
- const inputSchema$5 = objectSchema({ prompt: jsonString }, ["prompt"]);
205
- const outputSchema$4 = objectSchema({
205
+ const inputSchema$6 = objectSchema({ prompt: jsonString }, ["prompt"]);
206
+ const outputSchema$5 = objectSchema({
206
207
  results: jsonRecord,
207
208
  output: jsonAny
208
209
  }, ["results"]);
@@ -228,9 +229,9 @@ function createSequentialMachine(config) {
228
229
  const { model, steps } = config;
229
230
  assertEntryNames("step", steps.map((step) => step.name), ["done"]);
230
231
  const agentSetup = require_setup_agent.setupAgent({
231
- context: contextSchema$5,
232
- input: inputSchema$5,
233
- output: outputSchema$4
232
+ context: contextSchema$6,
233
+ input: inputSchema$6,
234
+ output: outputSchema$5
234
235
  });
235
236
  const states = {};
236
237
  steps.forEach((step, index) => {
@@ -283,13 +284,13 @@ function createSequentialMachine(config) {
283
284
  }
284
285
  //#endregion
285
286
  //#region src/machines/router.ts
286
- const contextSchema$4 = objectSchema({
287
+ const contextSchema$5 = objectSchema({
287
288
  prompt: jsonString,
288
289
  route: { type: ["string", "null"] },
289
290
  result: jsonAny
290
291
  }, ["prompt"]);
291
- const inputSchema$4 = objectSchema({ prompt: jsonString }, ["prompt"]);
292
- const outputSchema$3 = objectSchema({
292
+ const inputSchema$5 = objectSchema({ prompt: jsonString }, ["prompt"]);
293
+ const outputSchema$4 = objectSchema({
293
294
  route: { type: ["string", "null"] },
294
295
  result: jsonAny
295
296
  }, ["route"]);
@@ -322,9 +323,9 @@ function createRouterMachine(config) {
322
323
  assertEntryNames("route", names, ["routing", "done"]);
323
324
  if (fallback !== void 0 && !names.includes(fallback)) throw new Error(`createRouterMachine: fallback '${fallback}' is not a declared route (${names.join(", ")}).`);
324
325
  const agentSetup = require_setup_agent.setupAgent({
325
- context: contextSchema$4,
326
- input: inputSchema$4,
327
- output: outputSchema$3,
326
+ context: contextSchema$5,
327
+ input: inputSchema$5,
328
+ output: outputSchema$4,
328
329
  events: Object.fromEntries(names.map((name) => [routeEventType(name), emptyPayload])),
329
330
  actors: machineActors(routes)
330
331
  });
@@ -382,12 +383,12 @@ function createRouterMachine(config) {
382
383
  }
383
384
  //#endregion
384
385
  //#region src/machines/parallel.ts
385
- const contextSchema$3 = objectSchema({
386
+ const contextSchema$4 = objectSchema({
386
387
  prompt: jsonString,
387
388
  results: jsonRecord
388
389
  }, ["prompt", "results"]);
389
- const inputSchema$3 = objectSchema({ prompt: jsonString }, ["prompt"]);
390
- const outputSchema$2 = objectSchema({ results: jsonRecord }, ["results"]);
390
+ const inputSchema$4 = objectSchema({ prompt: jsonString }, ["prompt"]);
391
+ const outputSchema$3 = objectSchema({ results: jsonRecord }, ["results"]);
391
392
  /**
392
393
  * Static fan-out: every branch runs concurrently as its own region of one
393
394
  * parallel state, and the run joins when all of them finish. Results are keyed
@@ -413,9 +414,9 @@ function createParallelMachine(config) {
413
414
  const { model, branches } = config;
414
415
  assertEntryNames("branch", Object.keys(branches), ["running", "done"]);
415
416
  const agentSetup = require_setup_agent.setupAgent({
416
- context: contextSchema$3,
417
- input: inputSchema$3,
418
- output: outputSchema$2,
417
+ context: contextSchema$4,
418
+ input: inputSchema$4,
419
+ output: outputSchema$3,
419
420
  actors: machineActors(branches)
420
421
  });
421
422
  const regions = {};
@@ -461,7 +462,7 @@ function createParallelMachine(config) {
461
462
  }
462
463
  //#endregion
463
464
  //#region src/machines/loop.ts
464
- const contextSchema$2 = objectSchema({
465
+ const contextSchema$3 = objectSchema({
465
466
  prompt: jsonString,
466
467
  iterations: jsonNumber,
467
468
  results: jsonArray,
@@ -471,8 +472,8 @@ const contextSchema$2 = objectSchema({
471
472
  "iterations",
472
473
  "results"
473
474
  ]);
474
- const inputSchema$2 = objectSchema({ prompt: jsonString }, ["prompt"]);
475
- const outputSchema$1 = objectSchema({
475
+ const inputSchema$3 = objectSchema({ prompt: jsonString }, ["prompt"]);
476
+ const outputSchema$2 = objectSchema({
476
477
  iterations: jsonNumber,
477
478
  results: jsonArray,
478
479
  last: jsonAny
@@ -497,9 +498,9 @@ function createLoopMachine(config) {
497
498
  const { model, body, until, maxTurns } = config;
498
499
  if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new Error("createLoopMachine: maxTurns must be an integer >= 1.");
499
500
  const agentSetup = require_setup_agent.setupAgent({
500
- context: contextSchema$2,
501
- input: inputSchema$2,
502
- output: outputSchema$1,
501
+ context: contextSchema$3,
502
+ input: inputSchema$3,
503
+ output: outputSchema$2,
503
504
  actors: isMachineEntry(body) ? { body: body.machine } : {}
504
505
  });
505
506
  const loopState = (context) => ({
@@ -553,7 +554,7 @@ function createLoopMachine(config) {
553
554
  }
554
555
  //#endregion
555
556
  //#region src/machines/supervisor.ts
556
- const contextSchema$1 = objectSchema({
557
+ const contextSchema$2 = objectSchema({
557
558
  task: jsonString,
558
559
  results: jsonRecord,
559
560
  turns: jsonNumber,
@@ -563,8 +564,8 @@ const contextSchema$1 = objectSchema({
563
564
  "results",
564
565
  "turns"
565
566
  ]);
566
- const inputSchema$1 = objectSchema({ task: jsonString }, ["task"]);
567
- const outputSchema = objectSchema({
567
+ const inputSchema$2 = objectSchema({ task: jsonString }, ["task"]);
568
+ const outputSchema$1 = objectSchema({
568
569
  results: jsonRecord,
569
570
  turns: jsonNumber
570
571
  }, ["results", "turns"]);
@@ -606,9 +607,9 @@ function createSupervisorMachine(config) {
606
607
  assertEntryNames("worker", names, ["supervising", "done"]);
607
608
  if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new Error("createSupervisorMachine: maxTurns must be an integer >= 1.");
608
609
  const agentSetup = require_setup_agent.setupAgent({
609
- context: contextSchema$1,
610
- input: inputSchema$1,
611
- output: outputSchema,
610
+ context: contextSchema$2,
611
+ input: inputSchema$2,
612
+ output: outputSchema$1,
612
613
  events: {
613
614
  ...Object.fromEntries(names.map((name) => [delegateEventType(name), emptyPayload])),
614
615
  [FINISH_EVENT_TYPE]: emptyPayload
@@ -680,12 +681,12 @@ function renderResults(results) {
680
681
  }
681
682
  //#endregion
682
683
  //#region src/machines/handoff.ts
683
- const contextSchema = objectSchema({
684
+ const contextSchema$1 = objectSchema({
684
685
  message: jsonString,
685
686
  activeAgent: jsonString,
686
687
  reply: jsonAny
687
688
  }, ["message", "activeAgent"]);
688
- const inputSchema = objectSchema({
689
+ const inputSchema$1 = objectSchema({
689
690
  message: jsonString,
690
691
  activeAgent: jsonString
691
692
  }, ["message"]);
@@ -729,8 +730,8 @@ function createHandoffMachine(config) {
729
730
  assertEntryNames("agent", names, ["routing", "waiting"]);
730
731
  if (!names.includes(defaultActiveAgent)) throw new Error(`createHandoffMachine: defaultActiveAgent '${defaultActiveAgent}' is not a declared agent (${names.join(", ")}).`);
731
732
  const agentSetup = require_setup_agent.setupAgent({
732
- context: contextSchema,
733
- input: inputSchema,
733
+ context: contextSchema$1,
734
+ input: inputSchema$1,
734
735
  events: Object.fromEntries(names.map((name) => [transferEventType(name), transferPayload])),
735
736
  actors: machineActors(agents)
736
737
  });
@@ -771,7 +772,422 @@ function createHandoffMachine(config) {
771
772
  return agentSetup.createMachine(machineConfig);
772
773
  }
773
774
  //#endregion
775
+ //#region src/machines/approval-batch.ts
776
+ const CHILD_PREFIX = "call:";
777
+ /** The actor source key the per-call child machine is registered under. */
778
+ const CALL_SRC = "call";
779
+ const askEveryCall = (0, xstate.createAsyncLogic)({ run: async () => "ask" });
780
+ const callSchema = {
781
+ type: "object",
782
+ properties: {
783
+ id: jsonString,
784
+ name: jsonString
785
+ }
786
+ };
787
+ const callIdPayload = objectSchema({ callId: jsonString }, ["callId"]);
788
+ function settledResult(results, id) {
789
+ return Object.hasOwn(results, id) ? results[id] : void 0;
790
+ }
791
+ function errorMessage(error) {
792
+ return error instanceof Error ? error.message : String(error);
793
+ }
794
+ function createCallMachine(config) {
795
+ const callSetup = require_setup_agent.setupAgent({
796
+ context: objectSchema({
797
+ call: callSchema,
798
+ decision: { type: ["string", "null"] },
799
+ approvedBy: { type: ["string", "null"] },
800
+ result: jsonAny,
801
+ error: { type: ["string", "null"] },
802
+ reason: { type: ["string", "null"] }
803
+ }, ["call"]),
804
+ input: objectSchema({ call: callSchema }, ["call"]),
805
+ output: objectSchema({
806
+ id: jsonString,
807
+ status: jsonString
808
+ }, ["id", "status"]),
809
+ events: {
810
+ APPROVE: emptyPayload,
811
+ APPROVE_ALWAYS: emptyPayload,
812
+ REJECT: objectSchema({ reason: jsonString }),
813
+ RELEASE: emptyPayload
814
+ },
815
+ actors: {
816
+ policy: config.policy ?? askEveryCall,
817
+ execute: config.execute
818
+ }
819
+ });
820
+ const toParent = ({ context, parent }, enq, type) => {
821
+ if (parent) enq.sendTo(parent, {
822
+ type,
823
+ callId: context.call.id
824
+ });
825
+ };
826
+ return callSetup.createMachine({
827
+ id: "approval-call",
828
+ version: "1",
829
+ context: ({ input }) => ({
830
+ call: input.call,
831
+ decision: null,
832
+ approvedBy: null,
833
+ result: null,
834
+ error: null,
835
+ reason: null
836
+ }),
837
+ initial: "checking",
838
+ states: {
839
+ checking: { invoke: {
840
+ id: "policy",
841
+ src: "policy",
842
+ input: ({ context }) => ({ call: context.call }),
843
+ onDone: ({ output }) => {
844
+ switch (output) {
845
+ case "allow": return {
846
+ target: "approved",
847
+ context: {
848
+ decision: "allow",
849
+ approvedBy: "policy"
850
+ }
851
+ };
852
+ case "ask": return {
853
+ target: "awaitingApproval",
854
+ context: { decision: "ask" }
855
+ };
856
+ case "deny": return {
857
+ target: "rejected",
858
+ context: {
859
+ decision: "deny",
860
+ reason: "denied by policy"
861
+ }
862
+ };
863
+ default: return {
864
+ target: "failed",
865
+ context: { error: `policy returned ${JSON.stringify(output)}` }
866
+ };
867
+ }
868
+ },
869
+ onError: ({ event }) => ({
870
+ target: "failed",
871
+ context: { error: errorMessage(event.error) }
872
+ })
873
+ } },
874
+ awaitingApproval: {
875
+ entry: (args, enq) => toParent(args, enq, "CALL_ASKING"),
876
+ meta: { interaction: {
877
+ label: "Run {call.name}?",
878
+ events: {
879
+ APPROVE: {
880
+ label: "Approve",
881
+ style: "primary"
882
+ },
883
+ APPROVE_ALWAYS: "Always approve",
884
+ REJECT: {
885
+ label: "Reject",
886
+ style: "danger"
887
+ }
888
+ },
889
+ textEvent: {
890
+ type: "REJECT",
891
+ field: "reason"
892
+ }
893
+ } },
894
+ on: {
895
+ APPROVE: {
896
+ target: "approved",
897
+ context: { approvedBy: "user" }
898
+ },
899
+ APPROVE_ALWAYS: {
900
+ target: "approved",
901
+ context: { approvedBy: "user" }
902
+ },
903
+ REJECT: ({ event }) => ({
904
+ target: "rejected",
905
+ context: { reason: event.reason ?? "rejected" }
906
+ })
907
+ }
908
+ },
909
+ approved: {
910
+ entry: (args, enq) => toParent(args, enq, "CALL_READY"),
911
+ on: { RELEASE: { target: "executing" } }
912
+ },
913
+ executing: { invoke: {
914
+ id: "execute",
915
+ src: "execute",
916
+ input: ({ context }) => ({ call: context.call }),
917
+ onDone: ({ output }) => ({
918
+ target: "executed",
919
+ context: { result: output }
920
+ }),
921
+ onError: ({ event }) => ({
922
+ target: "failed",
923
+ context: { error: errorMessage(event.error) }
924
+ })
925
+ } },
926
+ executed: {
927
+ type: "final",
928
+ output: ({ context }) => ({
929
+ id: context.call.id,
930
+ status: "executed",
931
+ result: context.result
932
+ })
933
+ },
934
+ rejected: {
935
+ type: "final",
936
+ output: ({ context }) => ({
937
+ id: context.call.id,
938
+ status: "rejected",
939
+ reason: context.reason ?? "rejected"
940
+ })
941
+ },
942
+ failed: {
943
+ type: "final",
944
+ output: ({ context }) => ({
945
+ id: context.call.id,
946
+ status: "failed",
947
+ error: context.error ?? "failed"
948
+ })
949
+ }
950
+ }
951
+ });
952
+ }
953
+ function choicesFor(awaiting) {
954
+ return awaiting.flatMap((call) => [
955
+ {
956
+ label: `Approve ${call.name} (${call.id})`,
957
+ event: {
958
+ type: "APPROVE",
959
+ callId: call.id
960
+ }
961
+ },
962
+ {
963
+ label: `Always approve ${call.name} (${call.id})`,
964
+ event: {
965
+ type: "APPROVE_ALWAYS",
966
+ callId: call.id
967
+ }
968
+ },
969
+ {
970
+ label: `Reject ${call.name} (${call.id})`,
971
+ event: {
972
+ type: "REJECT",
973
+ callId: call.id
974
+ }
975
+ }
976
+ ]);
977
+ }
978
+ const contextSchema = objectSchema({
979
+ calls: jsonArray,
980
+ awaiting: jsonArray,
981
+ choices: jsonArray,
982
+ ready: jsonArray,
983
+ results: jsonRecord,
984
+ approveAlways: jsonArray
985
+ }, [
986
+ "calls",
987
+ "awaiting",
988
+ "choices",
989
+ "ready",
990
+ "results",
991
+ "approveAlways"
992
+ ]);
993
+ const inputSchema = objectSchema({ calls: jsonArray }, ["calls"]);
994
+ const outputSchema = objectSchema({
995
+ results: jsonArray,
996
+ approveAlways: jsonArray
997
+ }, ["results", "approveAlways"]);
998
+ /**
999
+ * One model turn's tool calls, each approved or rejected individually; only
1000
+ * approved calls execute. One child actor per call:
1001
+ *
1002
+ * `checking` (policy) → `awaitingApproval` (person) → `approved` → `executing`
1003
+ * → `executed` | `rejected` | `failed`.
1004
+ *
1005
+ * The parent routes `APPROVE` / `APPROVE_ALWAYS` / `REJECT` to the child by
1006
+ * `callId`, holds approved calls at the `executeWhen` barrier, and collects
1007
+ * outputs. `CANCEL_ALL` stops every unfinished child and ends the batch; those
1008
+ * calls report `cancelled`, including one whose execute was in flight.
1009
+ *
1010
+ * States: `running` → `done` | `cancelled`.
1011
+ *
1012
+ * ```ts
1013
+ * const machine = createApprovalBatchMachine({
1014
+ * policy: createAsyncLogic({
1015
+ * run: async ({ input }) => (input.call.name === "search" ? "allow" : "ask"),
1016
+ * }),
1017
+ * execute: createAsyncLogic({
1018
+ * run: async ({ input }) => tools[input.call.name](input.call.args),
1019
+ * }),
1020
+ * });
1021
+ * ```
1022
+ */
1023
+ function createApprovalBatchMachine(config) {
1024
+ const executeWhen = config.executeWhen ?? "allReady";
1025
+ const callMachine = createCallMachine(config);
1026
+ const agentSetup = require_setup_agent.setupAgent({
1027
+ context: contextSchema,
1028
+ input: inputSchema,
1029
+ output: outputSchema,
1030
+ events: {
1031
+ APPROVE: callIdPayload,
1032
+ APPROVE_ALWAYS: callIdPayload,
1033
+ REJECT: objectSchema({
1034
+ callId: jsonString,
1035
+ reason: jsonString
1036
+ }, ["callId"]),
1037
+ CANCEL_ALL: emptyPayload,
1038
+ CALL_ASKING: callIdPayload,
1039
+ CALL_READY: callIdPayload
1040
+ },
1041
+ actors: { [CALL_SRC]: callMachine }
1042
+ });
1043
+ const child = (children, id) => children[`${CHILD_PREFIX}${id}`];
1044
+ const settle = (args, enq, result) => {
1045
+ const { context } = args;
1046
+ const results = {
1047
+ ...context.results,
1048
+ [result.id]: result
1049
+ };
1050
+ const awaiting = context.awaiting.filter((call) => call.id !== result.id);
1051
+ const next = {
1052
+ results,
1053
+ awaiting,
1054
+ ready: context.ready.filter((id) => id !== result.id),
1055
+ choices: choicesFor(awaiting)
1056
+ };
1057
+ if (Object.keys(results).length === context.calls.length) return {
1058
+ target: "done",
1059
+ context: next
1060
+ };
1061
+ return { context: {
1062
+ ...next,
1063
+ ready: release({
1064
+ ...args,
1065
+ context: {
1066
+ ...context,
1067
+ ...next
1068
+ }
1069
+ }, enq)
1070
+ } };
1071
+ };
1072
+ const release = ({ context, children }, enq) => {
1073
+ const settled = Object.keys(context.results).length + context.ready.length;
1074
+ if (context.ready.length === 0 || settled < context.calls.length) return context.ready;
1075
+ for (const id of context.ready) enq.sendTo(child(children, id), { type: "RELEASE" });
1076
+ return [];
1077
+ };
1078
+ const forward = (type) => ({ context, event, children }, enq) => {
1079
+ const call = context.awaiting.find((candidate) => candidate.id === event.callId);
1080
+ if (!call) return void 0;
1081
+ enq.sendTo(child(children, call.id), type === "REJECT" && event.reason !== void 0 ? {
1082
+ type,
1083
+ reason: event.reason
1084
+ } : { type });
1085
+ const awaiting = context.awaiting.filter((candidate) => candidate.id !== call.id);
1086
+ const approveAlways = type === "APPROVE_ALWAYS" && !context.approveAlways.some((rule) => rule.name === call.name) ? [...context.approveAlways, { name: call.name }] : context.approveAlways;
1087
+ return { context: {
1088
+ awaiting,
1089
+ choices: choicesFor(awaiting),
1090
+ approveAlways
1091
+ } };
1092
+ };
1093
+ const output = ({ context }) => ({
1094
+ results: context.calls.map((call) => settledResult(context.results, call.id) ?? {
1095
+ id: call.id,
1096
+ status: "cancelled"
1097
+ }),
1098
+ approveAlways: context.approveAlways
1099
+ });
1100
+ const machineConfig = {
1101
+ id: "approval-batch",
1102
+ version: "1",
1103
+ context: ({ input }) => {
1104
+ if (new Set(input.calls.map((call) => call.id)).size !== input.calls.length) throw new Error("createApprovalBatchMachine: call ids must be unique.");
1105
+ return {
1106
+ calls: input.calls,
1107
+ awaiting: [],
1108
+ choices: [],
1109
+ ready: [],
1110
+ results: {},
1111
+ approveAlways: []
1112
+ };
1113
+ },
1114
+ initial: "running",
1115
+ states: {
1116
+ running: {
1117
+ entry: ({ context }, enq) => {
1118
+ for (const call of context.calls) enq.spawn(CALL_SRC, {
1119
+ id: `${CHILD_PREFIX}${call.id}`,
1120
+ input: { call }
1121
+ });
1122
+ },
1123
+ always: ({ context }) => context.calls.length === 0 ? { target: "done" } : void 0,
1124
+ meta: { interaction: {
1125
+ label: "Approve the proposed tool calls.",
1126
+ choices: "choices"
1127
+ } },
1128
+ on: {
1129
+ CALL_ASKING: ({ context, event }) => {
1130
+ const call = context.calls.find((candidate) => candidate.id === event.callId);
1131
+ if (!call || settledResult(context.results, call.id) || context.awaiting.some((candidate) => candidate.id === call.id)) return;
1132
+ const awaiting = [...context.awaiting, call];
1133
+ return { context: {
1134
+ awaiting,
1135
+ choices: choicesFor(awaiting)
1136
+ } };
1137
+ },
1138
+ CALL_READY: (args, enq) => {
1139
+ const { context, event, children } = args;
1140
+ const id = event.callId;
1141
+ if (!id || !context.calls.some((call) => call.id === id)) return void 0;
1142
+ if (context.ready.includes(id) || settledResult(context.results, id)) return void 0;
1143
+ if (executeWhen === "eachReady") {
1144
+ enq.sendTo(child(children, id), { type: "RELEASE" });
1145
+ return {};
1146
+ }
1147
+ const ready = [...context.ready, id];
1148
+ return { context: { ready: release({
1149
+ ...args,
1150
+ context: {
1151
+ ...context,
1152
+ ready
1153
+ }
1154
+ }, enq) } };
1155
+ },
1156
+ APPROVE: forward("APPROVE"),
1157
+ APPROVE_ALWAYS: forward("APPROVE_ALWAYS"),
1158
+ REJECT: forward("REJECT"),
1159
+ CANCEL_ALL: { target: "cancelled" },
1160
+ "xstate.done.actor": (args, enq) => {
1161
+ const { actorId, output: result } = args.event;
1162
+ if (!actorId?.startsWith(CHILD_PREFIX)) return void 0;
1163
+ return settle(args, enq, result);
1164
+ },
1165
+ "xstate.error.actor": (args, enq) => {
1166
+ const { actorId } = args.event;
1167
+ if (!actorId?.startsWith(CHILD_PREFIX)) return void 0;
1168
+ return settle(args, enq, {
1169
+ id: actorId.slice(5),
1170
+ status: "failed",
1171
+ error: errorMessage(args.event.error)
1172
+ });
1173
+ }
1174
+ }
1175
+ },
1176
+ done: {
1177
+ type: "final",
1178
+ output
1179
+ },
1180
+ cancelled: {
1181
+ type: "final",
1182
+ output
1183
+ }
1184
+ }
1185
+ };
1186
+ return agentSetup.createMachine(machineConfig);
1187
+ }
1188
+ //#endregion
774
1189
  exports.FINISH_EVENT_TYPE = FINISH_EVENT_TYPE;
1190
+ exports.createApprovalBatchMachine = createApprovalBatchMachine;
775
1191
  exports.createHandoffMachine = createHandoffMachine;
776
1192
  exports.createLoopMachine = createLoopMachine;
777
1193
  exports.createParallelMachine = createParallelMachine;