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

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 (135) hide show
  1. package/CHANGELOG.md +45 -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 +131 -93
  25. package/dist/index.d.cts +73 -134
  26. package/dist/index.d.mts +73 -134
  27. package/dist/index.mjs +112 -70
  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/machines.cjs +1 -719
  35. package/dist/machines.d.cts +2 -424
  36. package/dist/machines.d.mts +2 -424
  37. package/dist/machines.mjs +2 -709
  38. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  39. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  40. package/dist/openai.cjs +3 -3
  41. package/dist/openai.d.cts +2 -3
  42. package/dist/openai.d.mts +2 -3
  43. package/dist/openai.mjs +3 -3
  44. package/dist/otel.d.cts +1 -1
  45. package/dist/otel.d.mts +1 -1
  46. package/dist/policy.cjs +77 -0
  47. package/dist/policy.d.cts +143 -0
  48. package/dist/policy.d.mts +143 -0
  49. package/dist/policy.mjs +75 -0
  50. package/dist/{effects-BT_cSY0j.mjs → run-agent-BE7DOWD6.mjs} +150 -184
  51. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-DHlq87G7.d.mts} +18 -34
  52. package/dist/{effects-DDseYtJk.cjs → run-agent-De3xVFGw.cjs} +149 -201
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-Dq0oSFRm.d.cts} +18 -34
  54. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  55. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  56. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  57. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  58. package/dist/tanstack-ai.cjs +4 -4
  59. package/dist/tanstack-ai.d.cts +2 -3
  60. package/dist/tanstack-ai.d.mts +2 -3
  61. package/dist/tanstack-ai.mjs +4 -4
  62. package/dist/testing.cjs +122 -996
  63. package/dist/testing.d.cts +36 -695
  64. package/dist/testing.d.mts +36 -695
  65. package/dist/testing.mjs +112 -977
  66. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  67. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  68. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  69. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  70. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  71. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  72. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  73. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  74. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  75. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  76. package/dist/validate.cjs +4 -4
  77. package/dist/validate.d.cts +2 -2
  78. package/dist/validate.d.mts +2 -2
  79. package/dist/validate.mjs +4 -4
  80. package/dist/{verify-DJHfEfm6.d.cts → verify-BM0sGmsf.d.cts} +42 -6
  81. package/dist/{verify-ChyX6jq0.mjs → verify-CWlg3j7B.mjs} +153 -45
  82. package/dist/{verify-CwlombbC.cjs → verify-Dek6gHCS.cjs} +153 -45
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-H3Pr2gNw.d.mts} +42 -6
  84. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  85. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  86. package/docs/advanced.md +5 -5
  87. package/docs/choosing-a-run-mode.md +7 -7
  88. package/docs/debugging.md +6 -8
  89. package/docs/decisions.md +5 -4
  90. package/docs/environment-and-policy.md +1 -1
  91. package/docs/evals.md +57 -43
  92. package/docs/event-log.md +13 -15
  93. package/docs/from-a-loop.md +3 -3
  94. package/docs/generate-machines.md +4 -4
  95. package/docs/hosts.md +20 -27
  96. package/docs/human-in-the-loop.md +5 -8
  97. package/docs/index.md +4 -4
  98. package/docs/judgments.md +5 -7
  99. package/docs/langgraph-comparison.md +6 -6
  100. package/docs/machines-as-data.md +7 -12
  101. package/docs/machines-presets.md +17 -120
  102. package/docs/machines.md +13 -13
  103. package/docs/models-and-providers.md +19 -25
  104. package/docs/multi-agent.md +1 -1
  105. package/docs/observability.md +6 -8
  106. package/docs/persistence.md +10 -20
  107. package/docs/quickstart.md +3 -3
  108. package/docs/statechart-policy-examples.md +1 -1
  109. package/docs/steps.md +5 -6
  110. package/docs/strangler-fig.md +72 -7
  111. package/docs/text-requests.md +10 -12
  112. package/docs/thinking-in-state-machines.md +8 -8
  113. package/docs/tools.md +10 -12
  114. package/docs/upgrading.md +1 -1
  115. package/docs/usage-and-budgets.md +51 -56
  116. package/docs/validate-and-repair.md +9 -14
  117. package/docs/verify.md +53 -7
  118. package/docs/xstate-4-and-5-apps.md +19 -28
  119. package/llms.txt +1 -1
  120. package/package.json +31 -6
  121. package/readme.md +32 -24
  122. package/dist/internal-C3Lqu538.d.cts +0 -43
  123. package/dist/internal-DUcdhk-i.d.mts +0 -43
  124. package/dist/types-DQUOOaZO.d.cts +0 -238
  125. package/dist/types-DQUOOaZO.d.mts +0 -238
  126. package/skills/add-evals/SKILL.md +0 -152
  127. package/skills/add-traces/SKILL.md +0 -152
  128. package/skills/build-machine/SKILL.md +0 -84
  129. package/skills/generate-machine/SKILL.md +0 -335
  130. package/skills/graph-engineering/SKILL.md +0 -43
  131. package/skills/improve-machine/SKILL.md +0 -261
  132. package/skills/improve-machine/reference.md +0 -101
  133. package/skills/loop-to-machine/SKILL.md +0 -205
  134. package/skills/loop-to-machine/policy.md +0 -154
  135. package/skills/loop-to-machine/reference.md +0 -260
@@ -1,5 +1,5 @@
1
- const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
- const require_decision = require("./decision-CMeuNZ1g.cjs");
1
+ const require_event_log = require("./event-log-dSOnXHuG.cjs");
2
+ const require_decision = require("./decision-D8bcIGXQ.cjs");
3
3
  let xstate = require("xstate");
4
4
  //#region src/steps.ts
5
5
  /**
@@ -990,7 +990,67 @@ function transientStateIds(node, ids = []) {
990
990
  function hasParallelStates(node) {
991
991
  return require_event_log.isRecord(node) && (node["type"] === "parallel" || Object.values(require_event_log.isRecord(node["states"]) ? node["states"] : {}).some(hasParallelStates));
992
992
  }
993
- function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false) {
993
+ function childSrcs(step) {
994
+ const children = step.snapshot.children ?? {};
995
+ const invoked = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src]));
996
+ return Object.entries(children).flatMap(([id, ref]) => {
997
+ if (!ref) return [];
998
+ const own = ref.src;
999
+ const src = invoked.get(id) ?? (typeof own === "string" ? own : id);
1000
+ return [{
1001
+ id,
1002
+ session: childSession(id, ref),
1003
+ src
1004
+ }];
1005
+ });
1006
+ }
1007
+ function exploreStep(prev, next, event) {
1008
+ const before = prev ? childSrcs(prev) : [];
1009
+ const sessions = new Set(before.map((child) => child.session));
1010
+ const actorId = event.actorId;
1011
+ const settles = (event.type === "xstate.done.actor" || event.type === "xstate.error.actor") && typeof actorId === "string";
1012
+ return {
1013
+ event,
1014
+ state: next.snapshot.value,
1015
+ started: childSrcs(next).filter((child) => !sessions.has(child.session)).map((child) => child.src),
1016
+ settled: settles ? before.filter((child) => child.id === actorId).map((child) => child.src) : []
1017
+ };
1018
+ }
1019
+ function stepsOf(log) {
1020
+ const steps = Array.from({ length: log?.length ?? 0 });
1021
+ for (let at = log; at; at = at.prev) steps[at.length - 1] = at.step;
1022
+ return steps;
1023
+ }
1024
+ function finishedInvokes(step) {
1025
+ const children = step.snapshot.children ?? {};
1026
+ return finishedChildren(step).map(({ id }) => {
1027
+ const ref = children[id];
1028
+ const own = ref;
1029
+ return {
1030
+ id,
1031
+ src: typeof own.src === "string" ? own.src : id,
1032
+ input: ref.options?.input,
1033
+ logic: own.logic,
1034
+ ref
1035
+ };
1036
+ });
1037
+ }
1038
+ function finishedChildren(step) {
1039
+ const children = step.snapshot.children ?? {};
1040
+ return Object.keys(children).sort().flatMap((id) => {
1041
+ const snapshot = children[id]?.getSnapshot?.();
1042
+ if (snapshot?.status === "done") return [{
1043
+ id,
1044
+ output: snapshot.output
1045
+ }];
1046
+ if (snapshot?.status === "error") return [{
1047
+ id,
1048
+ error: snapshot.error
1049
+ }];
1050
+ return [];
1051
+ });
1052
+ }
1053
+ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false, ordering, stateTarget = false) {
994
1054
  const maxDepth = options.maxDepth ?? 8;
995
1055
  const maxPaths = options.maxPaths ?? 200;
996
1056
  const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
@@ -1026,9 +1086,33 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1026
1086
  }
1027
1087
  return next;
1028
1088
  };
1029
- const resolveStep = (prev, id, output) => withTransits(resolveAgentStep(machine, prev, id, output), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, doneEvent(prev.snapshot, id, output)));
1030
- const rejectStep = (prev, id, error) => withTransits(rejectAgentStep(machine, prev, id, error), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, errorEvent(prev.snapshot, id, error)));
1031
- const transitionStep = (prev, event) => withTransits(transitionAgentStep(machine, prev, event), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event));
1089
+ const logging = nesting === 0 && !stepping && (options.steps === true || ordering !== void 0);
1090
+ const logs = /* @__PURE__ */ new WeakMap();
1091
+ const timerDelivers = /* @__PURE__ */ new WeakMap();
1092
+ const logged = (prev, next, event) => {
1093
+ if (!logging) return next;
1094
+ const before = prev && logs.get(prev);
1095
+ const step = exploreStep(prev, next, timerDelivers.get(event) ?? event);
1096
+ const after = before?.after ?? false;
1097
+ const trigger = ordering?.after;
1098
+ logs.set(next, {
1099
+ step,
1100
+ prev: before,
1101
+ length: (before?.length ?? 0) + 1,
1102
+ after: after || trigger !== void 0 && (typeof trigger === "string" ? step.event.type === trigger : trigger(step)),
1103
+ violated: (before?.violated ?? false) || after && ordering.reach(step)
1104
+ });
1105
+ return next;
1106
+ };
1107
+ const resolveStep = (prev, id, output) => {
1108
+ const event = doneEvent(prev.snapshot, id, output);
1109
+ return logged(prev, withTransits(resolveAgentStep(machine, prev, id, output), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
1110
+ };
1111
+ const rejectStep = (prev, id, error) => {
1112
+ const event = errorEvent(prev.snapshot, id, error);
1113
+ return logged(prev, withTransits(rejectAgentStep(machine, prev, id, error), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
1114
+ };
1115
+ const transitionStep = (prev, event) => logged(prev, withTransits(transitionAgentStep(machine, prev, event), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
1032
1116
  const settleStep = (prev, id, output, usage) => {
1033
1117
  if (!usage) return {
1034
1118
  step: resolveStep(prev, id, output),
@@ -1085,7 +1169,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1085
1169
  if (accepted.length === 0) return;
1086
1170
  return accepted.length < events.length ? [...accepted, void 0] : accepted;
1087
1171
  };
1088
- const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
1172
+ const stops = (step, kids) => ordering !== void 0 && logs.get(step)?.violated === true || stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
1089
1173
  const finiteCache = /* @__PURE__ */ new Map();
1090
1174
  const schemaPayloads = (type, snapshot) => {
1091
1175
  const schema = eventSchemas[type];
@@ -1096,12 +1180,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1096
1180
  }
1097
1181
  fill ??= {
1098
1182
  payloads: [{}],
1099
- complete: !mayReadPayload(snapshot, type)
1183
+ complete: ordering === void 0 && !mayReadPayload(snapshot, type)
1100
1184
  };
1101
1185
  if (!fill.complete && fill.payloads.length === 1 && Object.keys(fill.payloads[0]).length === 0 && mayReadPayload(snapshot, type)) vacuous.add(type);
1102
1186
  if (!fill.complete && !unexpanded.has(type)) {
1103
1187
  unexpanded.add(type);
1104
- note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
1188
+ note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : ordering !== void 0 && !mayReadPayload(snapshot, type) ? `unexpanded: event '${type}' has no schema, and the ordering target may read its payload; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
1105
1189
  }
1106
1190
  return fill.payloads;
1107
1191
  };
@@ -1197,8 +1281,9 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1197
1281
  const concurrentForks = (step) => {
1198
1282
  if (options.children !== "explore" && !coupled) return;
1199
1283
  const invokes = pendingInvokes(step);
1200
- if (!invokes.some(isExploredChild)) return;
1201
- const kids = coupled ? invokes.filter(isExploredChild) : [];
1284
+ const finishedKids = coupled ? finishedInvokes(step).filter(isExploredChild) : [];
1285
+ if (!invokes.some(isExploredChild) && finishedKids.length === 0) return;
1286
+ const kids = coupled ? [...invokes.filter(isExploredChild), ...finishedKids] : [];
1202
1287
  const blocked = [];
1203
1288
  const asFork = (settle, id, src, isText, usage) => {
1204
1289
  if ("fork" in settle) return [settle.fork];
@@ -1217,10 +1302,22 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1217
1302
  };
1218
1303
  const texts = step.requests.filter((request) => request.kind === "text");
1219
1304
  const requestIds = new Set(step.requests.map((request) => request.id));
1220
- const forks = [...texts.flatMap((request) => {
1221
- const usage = usageFor(step, request);
1222
- return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
1223
- }), ...invokes.filter((invoke) => !requestIds.has(invoke.id) && !kids.includes(invoke)).flatMap((invoke) => asFork(settleFor(invoke.id, invoke.src, false, invoke), invoke.id, invoke.src, false))];
1305
+ const forks = [
1306
+ ...texts.flatMap((request) => {
1307
+ const usage = usageFor(step, request);
1308
+ return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
1309
+ }),
1310
+ ...invokes.filter((invoke) => !requestIds.has(invoke.id) && !kids.includes(invoke)).flatMap((invoke) => asFork(settleFor(invoke.id, invoke.src, false, invoke), invoke.id, invoke.src, false)),
1311
+ ...finishedChildren(step).filter((finished) => !finishedKids.some((kid) => kid.id === finished.id)).map((finished) => "error" in finished ? {
1312
+ id: finished.id,
1313
+ errors: [finished.error],
1314
+ outputs: []
1315
+ } : {
1316
+ id: finished.id,
1317
+ errors: [],
1318
+ outputs: [finished.output]
1319
+ })
1320
+ ];
1224
1321
  const decisions = step.requests.filter((request) => request.kind === "decision");
1225
1322
  for (const decision of decisions) {
1226
1323
  const src = findInvokeMetadata(step, decision.id)?.src;
@@ -1261,7 +1358,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1261
1358
  if (nesting === 0) unexplored.push(text());
1262
1359
  };
1263
1360
  let captured;
1264
- const endPath = (path, terminal) => {
1361
+ const endPath = (path, step, terminal) => {
1265
1362
  if (captured) {
1266
1363
  captured.push({
1267
1364
  status: terminal.status,
@@ -1274,7 +1371,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1274
1371
  else if (terminal.status !== "done" && terminal.status !== "error") unfinished = true;
1275
1372
  if (nesting === 0) terminals.push({
1276
1373
  ...terminal,
1277
- path: pathOf(path)
1374
+ path: pathOf(path),
1375
+ ...options.steps ? { steps: stepsOf(logs.get(step)) } : {}
1278
1376
  });
1279
1377
  };
1280
1378
  let prunedByGuard = 0;
@@ -1308,11 +1406,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1308
1406
  }
1309
1407
  }
1310
1408
  };
1311
- const initial = stepping ? void 0 : withTransits(childStartStep(machine, options.input, childRef), () => (0, xstate.getInitialMicrosteps)(machine, options.input));
1312
- if (initial) {
1313
- recordState(initial, childRef?._initialEffects ?? initial.actions);
1314
- if (stops(initial)) witness = [];
1315
- }
1409
+ const initial = stepping ? void 0 : logged(void 0, withTransits(childStartStep(machine, options.input, childRef), () => (0, xstate.getInitialMicrosteps)(machine, options.input)), { type: "xstate.init" });
1410
+ if (initial) recordState(initial, childRef?._initialEffects ?? initial.actions);
1316
1411
  const undeliverable = /* @__PURE__ */ new Set();
1317
1412
  const external = deliverable ?? (options.hostEvents === void 0 ? void 0 : new Set(options.hostEvents));
1318
1413
  const arriving = (snapshot) => require_decision.getAcceptedEvents(snapshot).filter((descriptor) => {
@@ -1324,7 +1419,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1324
1419
  const advance = (step, recordEvent, kids) => {
1325
1420
  let current = step;
1326
1421
  for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
1327
- if (!awaitsKids(current, kids) && stops(current, kids)) return {
1422
+ if ((stateTarget || !awaitsKids(current, kids)) && stops(current, kids)) return {
1328
1423
  step: current,
1329
1424
  hit: true
1330
1425
  };
@@ -1339,6 +1434,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1339
1434
  decisions: concurrent.decisions,
1340
1435
  ...concurrent.kids?.length ? { kids: concurrent.kids } : {}
1341
1436
  };
1437
+ const [finished] = finishedChildren(current);
1438
+ if (finished) {
1439
+ current = "error" in finished ? rejectStep(current, finished.id, finished.error) : resolveStep(current, finished.id, finished.output);
1440
+ recordState(current);
1441
+ continue;
1442
+ }
1342
1443
  if (request && request.kind === "text") {
1343
1444
  const usage = usageFor(current, request);
1344
1445
  const settle = settleFor(request.id, request.src, true, void 0, usage);
@@ -1444,10 +1545,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1444
1545
  }
1445
1546
  return armed.map(({ event, key }) => {
1446
1547
  const entry = { ...event };
1447
- timerFires.set(entry, {
1548
+ const command = {
1448
1549
  type: "xstate.timer",
1449
1550
  ...key
1450
- });
1551
+ };
1552
+ timerFires.set(entry, command);
1553
+ timerDelivers.set(command, event);
1451
1554
  return entry;
1452
1555
  });
1453
1556
  };
@@ -1503,7 +1606,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1503
1606
  }
1504
1607
  }
1505
1608
  const maxDepthTerminal = (settled, path) => {
1506
- endPath(path, {
1609
+ endPath(path, settled, {
1507
1610
  status: "max-depth",
1508
1611
  state: settled.snapshot.value
1509
1612
  });
@@ -1530,7 +1633,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1530
1633
  const pumped = /* @__PURE__ */ new WeakSet();
1531
1634
  let outParent;
1532
1635
  const register = (step, kids, queue) => {
1533
- const live = pendingInvokes(step).filter(isExploredChild);
1636
+ const live = [...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
1534
1637
  const sessions = new Set(live.map((invoke) => childSession(invoke.id, invoke.ref)));
1535
1638
  for (const session of kids.keys()) if (!sessions.has(session)) kids.delete(session);
1536
1639
  for (const invoke of live) {
@@ -1575,7 +1678,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1575
1678
  const awaitsKids = (step, kids) => {
1576
1679
  if (!coupled || pumped.has(step)) return false;
1577
1680
  const held = kids ?? /* @__PURE__ */ new Map();
1578
- if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1681
+ if ([...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1579
1682
  return (Array.isArray(step.actions) ? step.actions : []).some((effect) => require_event_log.isRecord(effect) && effect["type"] === "@xstate.sendTo" && kidSessionFor(step, effect["target"], held) !== void 0);
1580
1683
  };
1581
1684
  const pump = (start, link, kids, queue) => {
@@ -1590,7 +1693,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1590
1693
  const delivered = kid.engine.deliver(kid, event);
1591
1694
  if (delivered.overflow) {
1592
1695
  overflow = true;
1593
- endPath(link, {
1696
+ endPath(link, at, {
1594
1697
  status: "max-depth",
1595
1698
  state: at.snapshot.value
1596
1699
  });
@@ -1613,17 +1716,20 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1613
1716
  unexpanded.add(route.event.type);
1614
1717
  note(() => `coupled: a child sent '${route.event.type}' to an actor the search does not model, at path [${pathTypes(link)}]`);
1615
1718
  };
1719
+ const starting = /* @__PURE__ */ new WeakSet();
1616
1720
  const flush = (at) => {
1617
1721
  if (pumped.has(at)) return;
1618
1722
  pumped.add(at);
1723
+ const queued = queue.length;
1619
1724
  if (!register(at, kids, queue)) {
1620
1725
  overflow = true;
1621
- endPath(link, {
1726
+ endPath(link, at, {
1622
1727
  status: "max-depth",
1623
1728
  state: at.snapshot.value
1624
1729
  });
1625
1730
  return;
1626
1731
  }
1732
+ for (const item of queue.slice(queued)) starting.add(item);
1627
1733
  for (const effect of Array.isArray(at.actions) ? at.actions : []) {
1628
1734
  if (!require_event_log.isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !require_event_log.isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
1629
1735
  deliverTo(at, effect["target"], effect["event"]);
@@ -1634,7 +1740,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1634
1740
  for (let i = 0; queue.length > 0 && !overflow; i++) {
1635
1741
  if (step.done || step.snapshot.status !== "active" || witness !== void 0) break;
1636
1742
  if (i >= MAX_PUMP) {
1637
- endPath(link, {
1743
+ endPath(link, step, {
1638
1744
  status: "max-depth",
1639
1745
  state: step.snapshot.value
1640
1746
  });
@@ -1683,7 +1789,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1683
1789
  recordState(step);
1684
1790
  outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
1685
1791
  flush(step);
1686
- if (!overflow && stops(step, kids)) {
1792
+ if (!overflow && (stateTarget || !queue.some((queuedItem) => starting.has(queuedItem))) && stops(step, kids)) {
1687
1793
  witness = pathOf(link);
1688
1794
  break;
1689
1795
  }
@@ -1749,7 +1855,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1749
1855
  }
1750
1856
  }
1751
1857
  if (options.dedupeBy) {
1752
- const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1858
+ const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids) + (logs.get(settled)?.after ? "after" : "");
1753
1859
  const seenAt = visited.get(key);
1754
1860
  if (seenAt !== void 0 && seenAt <= depth) return;
1755
1861
  visited.set(key, depth);
@@ -1789,7 +1895,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1789
1895
  for (const terminal of blocked) {
1790
1896
  if (witness !== void 0 || capped()) return;
1791
1897
  if (terminal.status === "idle" || terminal.status === "done" || terminal.status === "error") continue;
1792
- endPath(path, {
1898
+ endPath(path, settled, {
1793
1899
  status: terminal.status,
1794
1900
  state: settled.snapshot.value,
1795
1901
  ...terminal.status === "needs-output" ? { missingSrc: terminal.missingSrc ?? kid.src } : {}
@@ -1843,7 +1949,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1843
1949
  const registered = new Set([...(nodeKids ?? /* @__PURE__ */ new Map()).values()].map((kid) => kid.id));
1844
1950
  for (const kid of pendingKids.filter((invoke) => !registered.has(invoke.id))) {
1845
1951
  if (witness !== void 0 || capped()) return;
1846
- endPath(path, {
1952
+ endPath(path, settled, {
1847
1953
  status: "needs-output",
1848
1954
  state: settled.snapshot.value,
1849
1955
  missingSrc: kid.src
@@ -1862,7 +1968,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1862
1968
  }
1863
1969
  for (const src of blockedSiblings ?? []) {
1864
1970
  if (witness !== void 0 || capped()) return;
1865
- endPath(path, {
1971
+ endPath(path, settled, {
1866
1972
  status: "needs-output",
1867
1973
  state: settled.snapshot.value,
1868
1974
  missingSrc: src
@@ -1912,14 +2018,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1912
2018
  delivered: /* @__PURE__ */ new Set([...delivered ?? [], key])
1913
2019
  };
1914
2020
  }
1915
- if (fork.stalls && witness === void 0 && !capped()) endPath(path, {
2021
+ if (fork.stalls && witness === void 0 && !capped()) endPath(path, settled, {
1916
2022
  status: "idle",
1917
2023
  state: settled.snapshot.value
1918
2024
  });
1919
2025
  for (const src of blockedSiblings ?? []) note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
1920
2026
  for (const incompleteSrc of [...[fork, ...siblings ?? []].flatMap((child) => child.incompleteSrc === void 0 ? [] : [child.incompleteSrc]), ...blockedSiblings ?? []]) {
1921
2027
  if (witness !== void 0 || capped()) break;
1922
- endPath(path, {
2028
+ endPath(path, settled, {
1923
2029
  status: "needs-output",
1924
2030
  state: settled.snapshot.value,
1925
2031
  missingSrc: incompleteSrc
@@ -1933,7 +2039,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1933
2039
  if (witness !== void 0) return;
1934
2040
  }
1935
2041
  if (blockedSrc) {
1936
- endPath(path, {
2042
+ endPath(path, settled, {
1937
2043
  status: "needs-output",
1938
2044
  state: settled.snapshot.value,
1939
2045
  missingSrc: blockedSrc
@@ -1944,7 +2050,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1944
2050
  }
1945
2051
  if (settled.done) {
1946
2052
  const output = settled.snapshot.output;
1947
- endPath(path, {
2053
+ endPath(path, settled, {
1948
2054
  status: "done",
1949
2055
  state: settled.snapshot.value,
1950
2056
  ...output === void 0 ? {} : { output }
@@ -1954,7 +2060,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1954
2060
  }
1955
2061
  if (settled.snapshot.status === "error") {
1956
2062
  const error = settled.snapshot.error;
1957
- endPath(path, {
2063
+ endPath(path, settled, {
1958
2064
  status: "error",
1959
2065
  state: settled.snapshot.value,
1960
2066
  error
@@ -1969,14 +2075,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1969
2075
  const requestOptions = request?.kind === "decision" ? require_decision.acceptedDecisionOptions(request, () => true) : void 0;
1970
2076
  const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : acceptedVariants(snapshot, path, table);
1971
2077
  if (branchEvents.length === 0 && request?.kind !== "decision") {
1972
- endPath(path, {
2078
+ endPath(path, settled, {
1973
2079
  status: "idle",
1974
2080
  state: settled.snapshot.value
1975
2081
  });
1976
2082
  return;
1977
2083
  }
1978
2084
  if (depth >= maxDepth) {
1979
- endPath(path, {
2085
+ endPath(path, settled, {
1980
2086
  status: "max-depth",
1981
2087
  state: settled.snapshot.value
1982
2088
  });
@@ -2000,7 +2106,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2000
2106
  };
2001
2107
  }
2002
2108
  if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
2003
- endPath(path, {
2109
+ endPath(path, settled, {
2004
2110
  status: "idle",
2005
2111
  state: settled.snapshot.value
2006
2112
  });
@@ -2128,6 +2234,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2128
2234
  stepper
2129
2235
  };
2130
2236
  }
2237
+ if (initial && (stateTarget || !awaitsKids(initial, void 0)) && stops(initial)) witness = [];
2131
2238
  const root = {
2132
2239
  step: initial,
2133
2240
  path: void 0,
@@ -2272,7 +2379,8 @@ function resolveStateTarget(machine, target) {
2272
2379
  */
2273
2380
  async function canReach(machine, target, options = {}) {
2274
2381
  const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
2275
- const { witness, report } = explore(machine, options, typeof target === "function" ? target : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget), 0, void 0, void 0, resolvedTarget !== void 0 && hasTransientStates(machine.getStateNodeById(resolvedTarget)));
2382
+ const ordering = typeof target === "object" ? target : void 0;
2383
+ const { witness, report } = explore(machine, options, typeof target === "function" ? target : ordering ? () => false : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget), 0, void 0, void 0, resolvedTarget !== void 0 && hasTransientStates(machine.getStateNodeById(resolvedTarget)), void 0, false, ordering, resolvedTarget !== void 0);
2276
2384
  if (witness !== void 0) return {
2277
2385
  reachable: true,
2278
2386
  witness,
@@ -1,6 +1,5 @@
1
- import { p as ChosenEvent, r as AgentMessage } from "./types-DQUOOaZO.mjs";
2
- import { at as AgentError, p as AgentTextResult, t as AgentCallUsage } from "./text-logic-BqxalgMr.mjs";
3
- import { AnyMachineSnapshot, AnyStateMachine } from "xstate";
1
+ import { at as AgentError, lt as AgentMessage, p as AgentTextResult, t as AgentCallUsage, yt as ChosenEvent } from "./text-logic-x17uLBwA.mjs";
2
+ import { AnyMachineSnapshot, AnyStateMachine, EventObject } from "xstate";
4
3
  //#region src/verify.d.ts
5
4
  /** Severity of an {@link AgentLintDiagnostic}. `error` findings fail CI/the CLI; `warning`s are advisory. */
6
5
  type AgentLintSeverity = "error" | "warning";
@@ -244,8 +243,36 @@ declare function textOutput<TResult>(result: TResult, options?: {
244
243
  * own `xstate`, which can be another version than the one this package uses.
245
244
  */
246
245
  type ExploreSnapshot = AnyMachineSnapshot;
247
- /** What {@link canReach} looks for: a state id or path, or a snapshot predicate. */
248
- type CanReachTarget = string | ((snapshot: ExploreSnapshot) => boolean);
246
+ /**
247
+ * One macrostep on an explored path, recorded with `steps: true` or for an
248
+ * ordering target: every event the machine processed, not only branch points.
249
+ */
250
+ interface ExploreStep {
251
+ /**
252
+ * The event this macrostep processed: a host event, a fork, a canned
253
+ * output settling (`xstate.done.actor`), or `xstate.init` for the start.
254
+ */
255
+ event: EventObject;
256
+ /** The state value after the step. */
257
+ state: unknown;
258
+ /** Srcs of the invokes and spawned actors that started in this step. */
259
+ started: string[];
260
+ /** Srcs of the actors that settled (done or error) in this step. */
261
+ settled: string[];
262
+ }
263
+ /**
264
+ * An ordering target for {@link canReach}: a step matching `reach` after a
265
+ * step matching `after`. `reachable: false` with `complete: true` proves
266
+ * `reach` never happens after `after`.
267
+ */
268
+ interface CanReachOrdering {
269
+ /** The trigger: an event type, or a step predicate. */
270
+ after: string | ((step: ExploreStep) => boolean);
271
+ /** Checked on every step after the first `after` step, not on that step itself. */
272
+ reach: (step: ExploreStep) => boolean;
273
+ }
274
+ /** What {@link canReach} looks for: a state id or path, a snapshot predicate, or an ordering. */
275
+ type CanReachTarget = string | ((snapshot: ExploreSnapshot) => boolean) | CanReachOrdering;
249
276
  interface ExplorePathsOptions {
250
277
  input?: unknown;
251
278
  /** Max branch points (decisions + external-event forks) along any path. Default 8. */
@@ -458,6 +485,13 @@ interface ExplorePathsOptions {
458
485
  * no usage.
459
486
  */
460
487
  usage?: Record<string, AgentCallUsage[]>;
488
+ /**
489
+ * Record every macrostep of each path in its terminal's `steps`, with the
490
+ * srcs each step started and settled. `path` lists only branch points, so
491
+ * an invoke with one canned output never appears there. Off by default:
492
+ * it costs memory per step of every path.
493
+ */
494
+ steps?: boolean;
461
495
  }
462
496
  /** A single explored path's terminal outcome. */
463
497
  interface AgentPathTerminal {
@@ -476,6 +510,8 @@ interface AgentPathTerminal {
476
510
  error?: unknown;
477
511
  /** For `done`: the machine's output (absent when it has none). */
478
512
  output?: unknown;
513
+ /** With `steps: true`: every macrostep on this path, from the start. */
514
+ steps?: ExploreStep[];
479
515
  }
480
516
  /** The report returned by {@link explorePaths}. */
481
517
  interface AgentPathReport {
@@ -618,4 +654,4 @@ declare class AgentUnknownStateError extends AgentError {
618
654
  */
619
655
  declare function canReach(machine: AnyStateMachine, target: CanReachTarget, options?: ExplorePathsOptions): Promise<CanReachResult>;
620
656
  //#endregion
621
- export { textOutput as S, assertAgentMachine as _, AgentPathTerminal as a, lintAgentMachine as b, CanReachResult as c, ExploreSnapshot as d, LintAgentMachineOptions as f, SimulationTrailEntry as g, SimulationScript as h, AgentPathReport as i, CanReachTarget as l, SimulateAgentResult as m, AgentLintError as n, AgentUnknownStateError as o, SimulateAgentOptions as p, AgentLintSeverity as r, AssertAgentMachineOptions as s, AgentLintDiagnostic as t, ExplorePathsOptions as u, canReach as v, simulateAgent as x, explorePaths as y };
657
+ export { simulateAgent as C, lintAgentMachine as S, SimulationScript as _, AgentPathTerminal as a, canReach as b, CanReachOrdering as c, ExplorePathsOptions as d, ExploreSnapshot as f, SimulateAgentResult as g, SimulateAgentOptions as h, AgentPathReport as i, CanReachResult as l, LintAgentMachineOptions as m, AgentLintError as n, AgentUnknownStateError as o, ExploreStep as p, AgentLintSeverity as r, AssertAgentMachineOptions as s, AgentLintDiagnostic as t, CanReachTarget as u, SimulationTrailEntry as v, textOutput as w, explorePaths as x, assertAgentMachine as y };
@@ -1,5 +1,5 @@
1
- const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
- const require_decision = require("./decision-CMeuNZ1g.cjs");
1
+ const require_event_log = require("./event-log-dSOnXHuG.cjs");
2
+ const require_decision = require("./decision-D8bcIGXQ.cjs");
3
3
  //#region src/internal/decision-object.ts
4
4
  /** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
5
5
  function resolveDecisionMode(option, request) {
@@ -1,5 +1,5 @@
1
- import { et as getJsonSchemaSync, mt as isRecord } from "./event-log-DkVlk3Rh.mjs";
2
- import { o as decisionOptionIds } from "./decision-m5hGmHpF.mjs";
1
+ import { $ as getJsonSchemaSync, ft as isRecord } from "./event-log-CEq_bVXQ.mjs";
2
+ import { o as decisionOptionIds } from "./decision-B41YBx5U.mjs";
3
3
  //#region src/internal/decision-object.ts
4
4
  /** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
5
5
  function resolveDecisionMode(option, request) {
package/docs/advanced.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Advanced: bare XState actors and hand-written executors
2
2
 
3
- Most hosts call `runToQuiescence`, or drive the [runtime loop](steps.md) themselves. This page covers the two things underneath those: binding executors onto a machine so it runs as a plain XState actor, and writing an executor without an adapter.
3
+ Most hosts call `runAgent`, or drive the [runtime loop](steps.md) themselves. This page covers the two things underneath those: binding executors onto a machine so it runs as a plain XState actor, and writing an executor without an adapter.
4
4
 
5
5
  ## `provideExecutors`: the machine as a plain actor
6
6
 
@@ -21,7 +21,7 @@ Reach for this when:
21
21
  - **The agent machine is a child in a larger XState system.** Invoke or spawn the bound machine from a parent machine like any other actor logic; its decisions and requests run inside the parent's actor system.
22
22
  - **The actor is long-lived.** A chat session, a game loop, or a device controller keeps one actor running across many human turns instead of resuming from a snapshot per turn.
23
23
 
24
- What you give up compared with `runToQuiescence`: there is no idle settling, no `maxModelCalls` cap, no event log or `snapshot`/`event` resume options, and no `run.start`/`run.end` trace boundary. The actor runs until you stop it. Usage events (`@agent.usage`) are still delivered to the machine, and `onTrace` still receives the request-level trace.
24
+ What you give up compared with `runAgent`: there is no idle settling, no `maxModelCalls` cap, no event log or `snapshot`/`event` resume options, and no `run.start`/`run.end` trace boundary. The actor runs until you stop it. Usage events (`@agent.usage`) are still delivered to the machine, and `onTrace` still receives the request-level trace.
25
25
 
26
26
  ```ts no-check
27
27
  const bound = provideExecutors(machine, executors, {
@@ -32,9 +32,9 @@ const bound = provideExecutors(machine, executors, {
32
32
 
33
33
  - `actors` merges extra actor sources before binding, the same shape as `machine.provide({ actors })`.
34
34
  - `onChunk` receives every chunk of every `mode: 'stream'` request.
35
- - `onTrace` receives `request.start`, `request.end`, `request.error`, and `stream.chunk` events with the same envelope `runToQuiescence` emits, minted per root actor. Pair it with `traceTransitions` on the actor's `inspect` option to fold `machine.transition` events into the same stream.
35
+ - `onTrace` receives `request.start`, `request.end`, `request.error`, and `stream.chunk` events with the same envelope `runAgent` emits, minted per root actor. Pair it with `traceTransitions` on the actor's `inspect` option to fold `machine.transition` events into the same stream.
36
36
 
37
- `provideExecutors` does not descend into invoked child machines. A child with its own agent requests needs its own `provideExecutors(...)` call, or `bindRequestExecutor` on its request logic (below). `runToQuiescence` rebinds children for you.
37
+ `provideExecutors` does not descend into invoked child machines. A child with its own agent requests needs its own `provideExecutors(...)` call, or `bindRequestExecutor` on its request logic (below). `runAgent` rebinds children for you.
38
38
 
39
39
  ## Writing an executor by hand
40
40
 
@@ -60,7 +60,7 @@ const executors = {
60
60
 
61
61
  - `result` is the value: the text, or the structured object the request's output schema describes. Core validates it against that schema.
62
62
  - `messages` are the provider's response messages for this call. They arrive on `output.messages` in `onDone`, so the machine decides what to keep.
63
- - `usage` is this call's token usage on the flat `inputTokens`/`outputTokens`/`totalTokens` names. `runToQuiescence` folds it into the run's aggregate and the `@agent.usage` event.
63
+ - `usage` is this call's token usage on the flat `inputTokens`/`outputTokens`/`totalTokens` names. `runAgent` folds it into the run's aggregate and the `@agent.usage` event.
64
64
  - Anything else (`finishReason`, `toolCalls`, `raw`) rides along to `onResult(request, { raw })` and the `request.end` trace.
65
65
 
66
66
  `streamText` returns the same shape once the stream finishes and calls `info.onChunk` for each chunk on the way. `decide` returns `{ event }`, the machine event the model chose from `request.events`; see [Decisions](decisions.md).
@@ -4,34 +4,34 @@ The machine is the artifact. Runners only decide how one host executes its XStat
4
4
 
5
5
  | Need | Use |
6
6
  | -------------------------------- | ---------------------------------------------------------------------- |
7
- | One request/response run | `runToQuiescence(createAgentRuntime(...), init)` |
8
- | Several idle/resume turns | `runToQuiescence` in a loop over `result.persist()` |
7
+ | One request/response run | `runAgent(machine, options)` |
8
+ | Several idle/resume turns | `runAgent` in a loop over `result.persist()`, or `onIdle` |
9
9
  | Transition-by-transition control | The explicit `AgentRuntime` loop |
10
10
  | A long-lived actor | `provideExecutors` + XState `createActor`, see [Advanced](advanced.md) |
11
11
 
12
12
  ## Managed run
13
13
 
14
14
  ```ts no-check
15
- const result = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
15
+ const result = await runAgent(machine, { executors, input });
16
16
 
17
17
  if (result.status === "idle") {
18
18
  await storage.save(result.persist());
19
19
  }
20
20
  ```
21
21
 
22
- `createAgentRuntime` binds request executors. `runToQuiescence` drives its durable
23
- transition loop until the run is done, idle, or errors. Storage remains host-owned.
22
+ `runAgent` binds request executors and drives the durable transition loop until
23
+ the run is done, idle, or errors. Storage remains host-owned.
24
24
 
25
25
  ## Idle/resume loop
26
26
 
27
27
  ```ts no-check
28
- let result = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
28
+ let result = await runAgent(machine, { executors, input });
29
29
 
30
30
  while (result.status === "idle") {
31
31
  const snapshot = result.persist();
32
32
  await storage.save(snapshot);
33
33
  const event = await nextExternalEvent(result.snapshot);
34
- result = await runToQuiescence(createAgentRuntime(machine, { executors }), { snapshot, event });
34
+ result = await runAgent(machine, { executors, snapshot, event });
35
35
  }
36
36
  ```
37
37
 
package/docs/debugging.md CHANGED
@@ -3,14 +3,12 @@
3
3
  Use the XState inspection protocol for framework behavior and Agent traces for request behavior.
4
4
 
5
5
  ```ts no-check
6
- const result = await runToQuiescence(
7
- createAgentRuntime(machine, {
8
- executors,
9
- inspect: (event) => inspector.next(event),
10
- onTrace: (event) => logger.write(serializeTraceEvent(event)),
11
- }),
12
- { input },
13
- );
6
+ const result = await runAgent(machine, {
7
+ executors,
8
+ inspect: (event) => inspector.next(event),
9
+ onTrace: (event) => logger.write(serializeTraceEvent(event)),
10
+ input,
11
+ });
14
12
  ```
15
13
 
16
14
  `inspect` is the raw XState stream. `onTrace` adds Agent request start/end/error, chunks, usage, emitted events, transitions, and the terminal run result.