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

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 (38) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/{effects-CuOUNYtZ.mjs → effects-BT_cSY0j.mjs} +95 -11
  3. package/dist/{effects-B23bFZEs.cjs → effects-DDseYtJk.cjs} +95 -11
  4. package/dist/index.cjs +6 -6
  5. package/dist/index.d.cts +3 -3
  6. package/dist/index.d.mts +3 -3
  7. package/dist/index.mjs +6 -6
  8. package/dist/otel.d.cts +1 -1
  9. package/dist/otel.d.mts +1 -1
  10. package/dist/{run-agent-BcQ-9NRT.d.cts → run-agent-30mH2moE.d.cts} +2 -2
  11. package/dist/{run-agent-C86drZtN.d.mts → run-agent-DlPzBWj-.d.mts} +2 -2
  12. package/dist/{setup-agent-jlo4vtaZ.d.cts → setup-agent-BaNyz6Q3.d.cts} +1 -1
  13. package/dist/{setup-agent-BIKcbVXV.d.mts → setup-agent-C1CG_nfX.d.mts} +1 -1
  14. package/dist/testing.cjs +2411 -1799
  15. package/dist/testing.d.cts +167 -4
  16. package/dist/testing.d.mts +167 -4
  17. package/dist/testing.mjs +2412 -1801
  18. package/dist/{usage-HtnrUsl9.d.cts → usage-Bm5nvpow.d.cts} +5 -0
  19. package/dist/{usage-DoP0Oi84.d.mts → usage-BnikdOca.d.mts} +5 -0
  20. package/dist/validate.cjs +1 -1
  21. package/dist/validate.d.cts +2 -2
  22. package/dist/validate.d.mts +2 -2
  23. package/dist/validate.mjs +1 -1
  24. package/dist/{verify-Dpz1u5Pe.mjs → verify-ChyX6jq0.mjs} +75 -20
  25. package/dist/{verify-Bink-Drw.cjs → verify-CwlombbC.cjs} +75 -20
  26. package/dist/{verify-CciG8UP-.d.cts → verify-DJHfEfm6.d.cts} +9 -4
  27. package/dist/{verify-Buh8XSUr.d.mts → verify-i9Hiwc5g.d.mts} +9 -4
  28. package/docs/decisions.md +1 -1
  29. package/docs/event-log.md +3 -2
  30. package/docs/hosts.md +2 -2
  31. package/docs/machines-as-data.md +5 -5
  32. package/docs/persistence.md +76 -5
  33. package/docs/quickstart.md +1 -1
  34. package/docs/steps.md +2 -0
  35. package/docs/usage-and-budgets.md +2 -0
  36. package/docs/verify.md +7 -2
  37. package/package.json +1 -1
  38. package/skills/build-machine/SKILL.md +4 -1
@@ -12,6 +12,11 @@ interface AgentUsageEvent extends EventObject {
12
12
  src?: string;
13
13
  model?: string;
14
14
  name?: string;
15
+ /**
16
+ * The call's `info.callKey`, when the run has an event log. A call
17
+ * re-executed after a crash reports its usage again: usage counts real spend.
18
+ */
19
+ callKey?: string;
15
20
  /**
16
21
  * The run's model-call budget after this call: `modelCalls` counted against
17
22
  * `maxModelCalls` so far, including `modelCallsSpent`. Guard on
@@ -12,6 +12,11 @@ interface AgentUsageEvent extends EventObject {
12
12
  src?: string;
13
13
  model?: string;
14
14
  name?: string;
15
+ /**
16
+ * The call's `info.callKey`, when the run has an event log. A call
17
+ * re-executed after a crash reports its usage again: usage counts real spend.
18
+ */
19
+ callKey?: string;
15
20
  /**
16
21
  * The run's model-call budget after this call: `modelCalls` counted against
17
22
  * `maxModelCalls` so far, including `modelCallsSpent`. Guard on
package/dist/validate.cjs CHANGED
@@ -24,7 +24,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  const require_event_log = require("./event-log-Dkc-yIYu.cjs");
25
25
  const require_decision = require("./decision-CMeuNZ1g.cjs");
26
26
  const require_setup_agent = require("./setup-agent-CmEToB8y.cjs");
27
- const require_verify = require("./verify-Bink-Drw.cjs");
27
+ const require_verify = require("./verify-CwlombbC.cjs");
28
28
  let ajv_dist_2020_js = require("ajv/dist/2020.js");
29
29
  ajv_dist_2020_js = __toESM(ajv_dist_2020_js, 1);
30
30
  //#region schemas/agent-workflow.json
@@ -1,5 +1,5 @@
1
- import { _ as FromConfigOptions, f as AgentWorkflowConfig, y as SchemaCompiler } from "./setup-agent-jlo4vtaZ.cjs";
2
- import { u as ExplorePathsOptions } from "./verify-CciG8UP-.cjs";
1
+ import { _ as FromConfigOptions, f as AgentWorkflowConfig, y as SchemaCompiler } from "./setup-agent-BaNyz6Q3.cjs";
2
+ import { u as ExplorePathsOptions } from "./verify-DJHfEfm6.cjs";
3
3
  import { AnyActorLogic, AnyStateMachine } from "xstate";
4
4
  //#region src/validate/validate-config.d.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { _ as FromConfigOptions, f as AgentWorkflowConfig, y as SchemaCompiler } from "./setup-agent-BIKcbVXV.mjs";
2
- import { u as ExplorePathsOptions } from "./verify-Buh8XSUr.mjs";
1
+ import { _ as FromConfigOptions, f as AgentWorkflowConfig, y as SchemaCompiler } from "./setup-agent-C1CG_nfX.mjs";
2
+ import { u as ExplorePathsOptions } from "./verify-i9Hiwc5g.mjs";
3
3
  import { AnyActorLogic, AnyStateMachine } from "xstate";
4
4
  //#region src/validate/validate-config.d.ts
5
5
  /**
package/dist/validate.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { A as STREAM_TEXT_ACTOR, E as ACT_ACTOR, O as DECIDE_ACTOR, k as GENERATE_TEXT_ACTOR } from "./event-log-DkVlk3Rh.mjs";
2
2
  import { p as payloadNeedsFillModel } from "./decision-m5hGmHpF.mjs";
3
3
  import { i as setupAgentFromConfig } from "./setup-agent-BDmNr6PC.mjs";
4
- import { a as explorePaths, s as lintAgentMachine } from "./verify-Dpz1u5Pe.mjs";
4
+ import { a as explorePaths, s as lintAgentMachine } from "./verify-ChyX6jq0.mjs";
5
5
  import Ajv2020 from "ajv/dist/2020.js";
6
6
  //#region schemas/agent-workflow.json
7
7
  var agent_workflow_default = {
@@ -952,6 +952,20 @@ function declaresUsageTransition(snapshot) {
952
952
  function childSession(id, ref) {
953
953
  return typeof ref?.sessionId === "string" ? ref.sessionId : id;
954
954
  }
955
+ function withKidSnapshots(snapshot, kids) {
956
+ if (!kids || kids.size === 0) return snapshot;
957
+ const children = { ...snapshot.children ?? {} };
958
+ let changed = false;
959
+ for (const [id, ref] of Object.entries(children)) {
960
+ const kid = kids.get(childSession(id, ref));
961
+ if (!kid || !ref) continue;
962
+ const kidSnapshot = withKidSnapshots(kid.step.snapshot, kid.kids);
963
+ children[id] = Object.assign(Object.create(ref), { getSnapshot: () => kidSnapshot });
964
+ changed = true;
965
+ }
966
+ if (!changed) return snapshot;
967
+ return Object.assign(Object.create(Object.getPrototypeOf(snapshot)), snapshot, { children });
968
+ }
955
969
  function pruneDelivered(delivered, step) {
956
970
  if (delivered === void 0 || delivered.size === 0) return delivered;
957
971
  const children = step.snapshot.children ?? {};
@@ -984,7 +998,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
984
998
  const outputScript = options.outputs ?? {};
985
999
  const coupled = options.children === "coupled";
986
1000
  const timerMode = options.timers ?? "fire";
987
- const usageScript = nesting === 0 && !stepping ? options.usage ?? {} : void 0;
1001
+ const usageScript = nesting === 0 || stepping ? options.usage ?? {} : void 0;
1002
+ const charges = /* @__PURE__ */ new WeakMap();
988
1003
  const interleaving = options.interleave === "pending" || stepping;
989
1004
  const errorsFor = (key) => {
990
1005
  if (!(key in errorScript)) return;
@@ -1019,8 +1034,21 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1019
1034
  step: resolveStep(prev, id, output),
1020
1035
  completed: true
1021
1036
  };
1037
+ if (stepping) {
1038
+ const resolved = resolveStep(prev, id, output);
1039
+ charges.set(resolved, usage);
1040
+ return {
1041
+ step: resolved,
1042
+ completed: true
1043
+ };
1044
+ }
1045
+ const sessionOf = (step) => {
1046
+ const invoke = pendingInvokes(step).find((pending) => pending.id === id);
1047
+ return invoke && childSession(id, invoke.ref);
1048
+ };
1049
+ const session = sessionOf(prev);
1022
1050
  const charged = transitionStep(prev, usage);
1023
- if (!pendingInvokes(charged).some((invoke) => invoke.id === id)) return {
1051
+ if (session === void 0 || sessionOf(charged) !== session) return {
1024
1052
  step: charged,
1025
1053
  completed: false
1026
1054
  };
@@ -1036,13 +1064,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1036
1064
  };
1037
1065
  };
1038
1066
  const usageFor = (step, request) => {
1039
- if (!usageScript || request.kind !== "text" || !declaresUsageTransition(step.snapshot)) return;
1067
+ if (!usageScript || request.kind !== "text" || !stepping && !declaresUsageTransition(step.snapshot)) return;
1040
1068
  const values = usageScript[request.src];
1041
1069
  if (!values?.length) {
1042
- vacuous.add(AGENT_USAGE_EVENT_TYPE);
1070
+ if (!stepping) vacuous.add(AGENT_USAGE_EVENT_TYPE);
1043
1071
  return;
1044
1072
  }
1045
- return values.map((usage) => ({
1073
+ const snapshot = step.snapshot;
1074
+ const events = values.map((usage) => ({
1046
1075
  type: AGENT_USAGE_EVENT_TYPE,
1047
1076
  kind: "text",
1048
1077
  id: request.id,
@@ -1051,8 +1080,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1051
1080
  ...request.input.name !== void 0 ? { name: request.input.name } : {},
1052
1081
  usage
1053
1082
  }));
1083
+ if (stepping) return events;
1084
+ const accepted = events.filter((event) => snapshot.can(event));
1085
+ if (accepted.length === 0) return;
1086
+ return accepted.length < events.length ? [...accepted, void 0] : accepted;
1054
1087
  };
1055
- const stops = (step) => stopWhen !== void 0 && (stopWhen(step.snapshot) || (transits.get(step)?.some((snapshot) => stopWhen(snapshot)) ?? false));
1088
+ const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
1056
1089
  const finiteCache = /* @__PURE__ */ new Map();
1057
1090
  const schemaPayloads = (type, snapshot) => {
1058
1091
  const schema = eventSchemas[type];
@@ -1288,10 +1321,10 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1288
1321
  return false;
1289
1322
  });
1290
1323
  const races = (step) => stepping || interleaving && (arriving(step.snapshot).length > 0 || timerMode === "fire" && armedTimers(step.snapshot).length > 0);
1291
- const advance = (step, recordEvent) => {
1324
+ const advance = (step, recordEvent, kids) => {
1292
1325
  let current = step;
1293
1326
  for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
1294
- if (stops(current)) return {
1327
+ if (!awaitsKids(current, kids) && stops(current, kids)) return {
1295
1328
  step: current,
1296
1329
  hit: true
1297
1330
  };
@@ -1323,10 +1356,10 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1323
1356
  pending: {
1324
1357
  id: request.id,
1325
1358
  output: asTextResult(settle.output),
1326
- ...usage ? { usage: usage[0] } : {}
1359
+ ...usage?.[0] ? { usage: usage[0] } : {}
1327
1360
  }
1328
1361
  };
1329
- if (usage) recordEvent(usage[0]);
1362
+ if (usage?.[0]) recordEvent(usage[0]);
1330
1363
  current = settleStep(current, request.id, asTextResult(settle.output), usage?.[0]).step;
1331
1364
  recordState(current);
1332
1365
  continue;
@@ -1457,7 +1490,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1457
1490
  if (i > 0 && (witness !== void 0 || capped())) return;
1458
1491
  const { step, completed } = settleStep(settled, fork.id, value, usage);
1459
1492
  recordState(step);
1460
- const charged = usage ? extend(path, usage) : path;
1493
+ const charged = usage && !stepping ? extend(path, usage) : path;
1461
1494
  yield {
1462
1495
  step,
1463
1496
  path: completed ? extend(charged, {
@@ -1539,6 +1572,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1539
1572
  return kids.has(session) ? session : void 0;
1540
1573
  }
1541
1574
  };
1575
+ const awaitsKids = (step, kids) => {
1576
+ if (!coupled || pumped.has(step)) return false;
1577
+ const held = kids ?? /* @__PURE__ */ new Map();
1578
+ if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1579
+ return (Array.isArray(step.actions) ? step.actions : []).some((effect) => isRecord(effect) && effect["type"] === "@xstate.sendTo" && kidSessionFor(step, effect["target"], held) !== void 0);
1580
+ };
1542
1581
  const pump = (start, link, kids, queue) => {
1543
1582
  let step = start;
1544
1583
  let overflow = false;
@@ -1604,11 +1643,19 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1604
1643
  break;
1605
1644
  }
1606
1645
  const item = queue.shift();
1607
- if ("route" in item) {
1646
+ if ("usage" in item) {
1647
+ if (stepping) {
1648
+ outbound.push(item);
1649
+ continue;
1650
+ }
1651
+ const snapshot = step.snapshot;
1652
+ if (!declaresUsageTransition(snapshot) || !snapshot.can(item.usage)) continue;
1653
+ step = transitionStep(step, item.usage);
1654
+ link = extend(link, item.usage);
1655
+ } else if ("route" in item) {
1608
1656
  if (!deliverTo(step, item.route.target, item.route.event)) unrouted(item.route);
1609
1657
  continue;
1610
- }
1611
- if ("event" in item) {
1658
+ } else if ("event" in item) {
1612
1659
  const accepted = step.snapshot.can(item.event);
1613
1660
  step = transitionStep(step, item.event);
1614
1661
  if (accepted) link = extend(link, item.event);
@@ -1635,11 +1682,11 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1635
1682
  }
1636
1683
  recordState(step);
1637
1684
  outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
1638
- if (stops(step)) {
1685
+ flush(step);
1686
+ if (!overflow && stops(step, kids)) {
1639
1687
  witness = pathOf(link);
1640
1688
  break;
1641
1689
  }
1642
- flush(step);
1643
1690
  }
1644
1691
  return {
1645
1692
  step,
@@ -1676,7 +1723,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1676
1723
  budget.nodes++;
1677
1724
  const { step: settled, blockedSrc, hit, fork, siblings, blockedSiblings, decisions, pending, kids: pendingKids } = advance(step, (event) => {
1678
1725
  path = extend(path, event);
1679
- });
1726
+ }, nodeKids);
1680
1727
  if (hit) {
1681
1728
  witness = pathOf(path);
1682
1729
  return;
@@ -1696,9 +1743,13 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1696
1743
  };
1697
1744
  return;
1698
1745
  }
1746
+ if (stops(settled, nodeKids)) {
1747
+ witness = pathOf(path);
1748
+ return;
1749
+ }
1699
1750
  }
1700
1751
  if (options.dedupeBy) {
1701
- const key = options.dedupeBy(settled.snapshot) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1752
+ const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1702
1753
  const seenAt = visited.get(key);
1703
1754
  if (seenAt !== void 0 && seenAt <= depth) return;
1704
1755
  visited.set(key, depth);
@@ -1710,7 +1761,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1710
1761
  }
1711
1762
  const resolved = settleStep(settled, pending.id, pending.output, pending.usage).step;
1712
1763
  recordState(resolved);
1713
- const charged = pending.usage ? extend(path, pending.usage) : path;
1764
+ const charged = pending.usage && !stepping ? extend(path, pending.usage) : path;
1714
1765
  yield {
1715
1766
  step: resolved,
1716
1767
  path: stepping ? extend(charged, {
@@ -2002,7 +2053,11 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2002
2053
  path: pathOf(settledMove.link),
2003
2054
  depth: node.depth,
2004
2055
  kids: settledMove.kids,
2005
- outbound: [...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children), ...settledMove.outbound]
2056
+ outbound: [
2057
+ ...charges.has(node.step) ? [{ usage: charges.get(node.step) }] : [],
2058
+ ...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children),
2059
+ ...settledMove.outbound
2060
+ ]
2006
2061
  });
2007
2062
  }
2008
2063
  return {
@@ -952,6 +952,20 @@ function declaresUsageTransition(snapshot) {
952
952
  function childSession(id, ref) {
953
953
  return typeof ref?.sessionId === "string" ? ref.sessionId : id;
954
954
  }
955
+ function withKidSnapshots(snapshot, kids) {
956
+ if (!kids || kids.size === 0) return snapshot;
957
+ const children = { ...snapshot.children ?? {} };
958
+ let changed = false;
959
+ for (const [id, ref] of Object.entries(children)) {
960
+ const kid = kids.get(childSession(id, ref));
961
+ if (!kid || !ref) continue;
962
+ const kidSnapshot = withKidSnapshots(kid.step.snapshot, kid.kids);
963
+ children[id] = Object.assign(Object.create(ref), { getSnapshot: () => kidSnapshot });
964
+ changed = true;
965
+ }
966
+ if (!changed) return snapshot;
967
+ return Object.assign(Object.create(Object.getPrototypeOf(snapshot)), snapshot, { children });
968
+ }
955
969
  function pruneDelivered(delivered, step) {
956
970
  if (delivered === void 0 || delivered.size === 0) return delivered;
957
971
  const children = step.snapshot.children ?? {};
@@ -984,7 +998,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
984
998
  const outputScript = options.outputs ?? {};
985
999
  const coupled = options.children === "coupled";
986
1000
  const timerMode = options.timers ?? "fire";
987
- const usageScript = nesting === 0 && !stepping ? options.usage ?? {} : void 0;
1001
+ const usageScript = nesting === 0 || stepping ? options.usage ?? {} : void 0;
1002
+ const charges = /* @__PURE__ */ new WeakMap();
988
1003
  const interleaving = options.interleave === "pending" || stepping;
989
1004
  const errorsFor = (key) => {
990
1005
  if (!(key in errorScript)) return;
@@ -1019,8 +1034,21 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1019
1034
  step: resolveStep(prev, id, output),
1020
1035
  completed: true
1021
1036
  };
1037
+ if (stepping) {
1038
+ const resolved = resolveStep(prev, id, output);
1039
+ charges.set(resolved, usage);
1040
+ return {
1041
+ step: resolved,
1042
+ completed: true
1043
+ };
1044
+ }
1045
+ const sessionOf = (step) => {
1046
+ const invoke = pendingInvokes(step).find((pending) => pending.id === id);
1047
+ return invoke && childSession(id, invoke.ref);
1048
+ };
1049
+ const session = sessionOf(prev);
1022
1050
  const charged = transitionStep(prev, usage);
1023
- if (!pendingInvokes(charged).some((invoke) => invoke.id === id)) return {
1051
+ if (session === void 0 || sessionOf(charged) !== session) return {
1024
1052
  step: charged,
1025
1053
  completed: false
1026
1054
  };
@@ -1036,13 +1064,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1036
1064
  };
1037
1065
  };
1038
1066
  const usageFor = (step, request) => {
1039
- if (!usageScript || request.kind !== "text" || !declaresUsageTransition(step.snapshot)) return;
1067
+ if (!usageScript || request.kind !== "text" || !stepping && !declaresUsageTransition(step.snapshot)) return;
1040
1068
  const values = usageScript[request.src];
1041
1069
  if (!values?.length) {
1042
- vacuous.add(require_event_log.AGENT_USAGE_EVENT_TYPE);
1070
+ if (!stepping) vacuous.add(require_event_log.AGENT_USAGE_EVENT_TYPE);
1043
1071
  return;
1044
1072
  }
1045
- return values.map((usage) => ({
1073
+ const snapshot = step.snapshot;
1074
+ const events = values.map((usage) => ({
1046
1075
  type: require_event_log.AGENT_USAGE_EVENT_TYPE,
1047
1076
  kind: "text",
1048
1077
  id: request.id,
@@ -1051,8 +1080,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1051
1080
  ...request.input.name !== void 0 ? { name: request.input.name } : {},
1052
1081
  usage
1053
1082
  }));
1083
+ if (stepping) return events;
1084
+ const accepted = events.filter((event) => snapshot.can(event));
1085
+ if (accepted.length === 0) return;
1086
+ return accepted.length < events.length ? [...accepted, void 0] : accepted;
1054
1087
  };
1055
- const stops = (step) => stopWhen !== void 0 && (stopWhen(step.snapshot) || (transits.get(step)?.some((snapshot) => stopWhen(snapshot)) ?? false));
1088
+ const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
1056
1089
  const finiteCache = /* @__PURE__ */ new Map();
1057
1090
  const schemaPayloads = (type, snapshot) => {
1058
1091
  const schema = eventSchemas[type];
@@ -1288,10 +1321,10 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1288
1321
  return false;
1289
1322
  });
1290
1323
  const races = (step) => stepping || interleaving && (arriving(step.snapshot).length > 0 || timerMode === "fire" && armedTimers(step.snapshot).length > 0);
1291
- const advance = (step, recordEvent) => {
1324
+ const advance = (step, recordEvent, kids) => {
1292
1325
  let current = step;
1293
1326
  for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
1294
- if (stops(current)) return {
1327
+ if (!awaitsKids(current, kids) && stops(current, kids)) return {
1295
1328
  step: current,
1296
1329
  hit: true
1297
1330
  };
@@ -1323,10 +1356,10 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1323
1356
  pending: {
1324
1357
  id: request.id,
1325
1358
  output: asTextResult(settle.output),
1326
- ...usage ? { usage: usage[0] } : {}
1359
+ ...usage?.[0] ? { usage: usage[0] } : {}
1327
1360
  }
1328
1361
  };
1329
- if (usage) recordEvent(usage[0]);
1362
+ if (usage?.[0]) recordEvent(usage[0]);
1330
1363
  current = settleStep(current, request.id, asTextResult(settle.output), usage?.[0]).step;
1331
1364
  recordState(current);
1332
1365
  continue;
@@ -1457,7 +1490,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1457
1490
  if (i > 0 && (witness !== void 0 || capped())) return;
1458
1491
  const { step, completed } = settleStep(settled, fork.id, value, usage);
1459
1492
  recordState(step);
1460
- const charged = usage ? extend(path, usage) : path;
1493
+ const charged = usage && !stepping ? extend(path, usage) : path;
1461
1494
  yield {
1462
1495
  step,
1463
1496
  path: completed ? extend(charged, {
@@ -1539,6 +1572,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1539
1572
  return kids.has(session) ? session : void 0;
1540
1573
  }
1541
1574
  };
1575
+ const awaitsKids = (step, kids) => {
1576
+ if (!coupled || pumped.has(step)) return false;
1577
+ const held = kids ?? /* @__PURE__ */ new Map();
1578
+ if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1579
+ 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
+ };
1542
1581
  const pump = (start, link, kids, queue) => {
1543
1582
  let step = start;
1544
1583
  let overflow = false;
@@ -1604,11 +1643,19 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1604
1643
  break;
1605
1644
  }
1606
1645
  const item = queue.shift();
1607
- if ("route" in item) {
1646
+ if ("usage" in item) {
1647
+ if (stepping) {
1648
+ outbound.push(item);
1649
+ continue;
1650
+ }
1651
+ const snapshot = step.snapshot;
1652
+ if (!declaresUsageTransition(snapshot) || !snapshot.can(item.usage)) continue;
1653
+ step = transitionStep(step, item.usage);
1654
+ link = extend(link, item.usage);
1655
+ } else if ("route" in item) {
1608
1656
  if (!deliverTo(step, item.route.target, item.route.event)) unrouted(item.route);
1609
1657
  continue;
1610
- }
1611
- if ("event" in item) {
1658
+ } else if ("event" in item) {
1612
1659
  const accepted = step.snapshot.can(item.event);
1613
1660
  step = transitionStep(step, item.event);
1614
1661
  if (accepted) link = extend(link, item.event);
@@ -1635,11 +1682,11 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1635
1682
  }
1636
1683
  recordState(step);
1637
1684
  outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
1638
- if (stops(step)) {
1685
+ flush(step);
1686
+ if (!overflow && stops(step, kids)) {
1639
1687
  witness = pathOf(link);
1640
1688
  break;
1641
1689
  }
1642
- flush(step);
1643
1690
  }
1644
1691
  return {
1645
1692
  step,
@@ -1676,7 +1723,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1676
1723
  budget.nodes++;
1677
1724
  const { step: settled, blockedSrc, hit, fork, siblings, blockedSiblings, decisions, pending, kids: pendingKids } = advance(step, (event) => {
1678
1725
  path = extend(path, event);
1679
- });
1726
+ }, nodeKids);
1680
1727
  if (hit) {
1681
1728
  witness = pathOf(path);
1682
1729
  return;
@@ -1696,9 +1743,13 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1696
1743
  };
1697
1744
  return;
1698
1745
  }
1746
+ if (stops(settled, nodeKids)) {
1747
+ witness = pathOf(path);
1748
+ return;
1749
+ }
1699
1750
  }
1700
1751
  if (options.dedupeBy) {
1701
- const key = options.dedupeBy(settled.snapshot) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1752
+ const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1702
1753
  const seenAt = visited.get(key);
1703
1754
  if (seenAt !== void 0 && seenAt <= depth) return;
1704
1755
  visited.set(key, depth);
@@ -1710,7 +1761,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1710
1761
  }
1711
1762
  const resolved = settleStep(settled, pending.id, pending.output, pending.usage).step;
1712
1763
  recordState(resolved);
1713
- const charged = pending.usage ? extend(path, pending.usage) : path;
1764
+ const charged = pending.usage && !stepping ? extend(path, pending.usage) : path;
1714
1765
  yield {
1715
1766
  step: resolved,
1716
1767
  path: stepping ? extend(charged, {
@@ -2002,7 +2053,11 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2002
2053
  path: pathOf(settledMove.link),
2003
2054
  depth: node.depth,
2004
2055
  kids: settledMove.kids,
2005
- outbound: [...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children), ...settledMove.outbound]
2056
+ outbound: [
2057
+ ...charges.has(node.step) ? [{ usage: charges.get(node.step) }] : [],
2058
+ ...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children),
2059
+ ...settledMove.outbound
2060
+ ]
2006
2061
  });
2007
2062
  }
2008
2063
  return {
@@ -377,7 +377,9 @@ interface ExplorePathsOptions {
377
377
  * like the parent's, and appear on a path with `actor` set to the child's
378
378
  * id (the child's own events, its choices, its settled work); the events
379
379
  * it sends the parent appear as the parent receives them. With `dedupeBy`,
380
- * each child's state is part of the key. More precise and often cheaper
380
+ * each child's state is part of the key. A target predicate and `dedupeBy`
381
+ * read each child's explored state through `snapshot.children[id]
382
+ * .getSnapshot()`. More precise and often cheaper
381
383
  * than `"explore"` for authored child machines; `"explore"` remains the
382
384
  * over-approximation for a child whose behavior you do not want to trust.
383
385
  */
@@ -445,12 +447,15 @@ interface ExplorePathsOptions {
445
447
  * settles at the root and the active states take `@agent.usage`, the
446
448
  * search delivers `{ type: '@agent.usage', kind: 'text', id, src, model,
447
449
  * name?, usage }` to the root immediately before the request's completion,
448
- * as a run does: once per listed value, each a fork that counts against
450
+ * as a run does (a value the active states refuse is dropped, as a run drops it): once per listed value, each a fork that counts against
449
451
  * `maxDepth` and records the usage event in the path. One value with one
450
452
  * canned output is no fork, but its usage event is still recorded. No `budget`
451
453
  * field is sent. A settling request with no entry while a usage transition
452
- * is active lists `@agent.usage` in `vacuous`. Requests inside child
453
- * machines and decisions deliver no usage.
454
+ * is active lists `@agent.usage` in `vacuous`. With `children:
455
+ * "coupled"`, a child's text request forks once per value and its usage
456
+ * event goes to the root, which takes or drops it the same way (no
457
+ * `vacuous` entry). Requests inside other children, and decisions, deliver
458
+ * no usage.
454
459
  */
455
460
  usage?: Record<string, AgentCallUsage[]>;
456
461
  }
@@ -377,7 +377,9 @@ interface ExplorePathsOptions {
377
377
  * like the parent's, and appear on a path with `actor` set to the child's
378
378
  * id (the child's own events, its choices, its settled work); the events
379
379
  * it sends the parent appear as the parent receives them. With `dedupeBy`,
380
- * each child's state is part of the key. More precise and often cheaper
380
+ * each child's state is part of the key. A target predicate and `dedupeBy`
381
+ * read each child's explored state through `snapshot.children[id]
382
+ * .getSnapshot()`. More precise and often cheaper
381
383
  * than `"explore"` for authored child machines; `"explore"` remains the
382
384
  * over-approximation for a child whose behavior you do not want to trust.
383
385
  */
@@ -445,12 +447,15 @@ interface ExplorePathsOptions {
445
447
  * settles at the root and the active states take `@agent.usage`, the
446
448
  * search delivers `{ type: '@agent.usage', kind: 'text', id, src, model,
447
449
  * name?, usage }` to the root immediately before the request's completion,
448
- * as a run does: once per listed value, each a fork that counts against
450
+ * as a run does (a value the active states refuse is dropped, as a run drops it): once per listed value, each a fork that counts against
449
451
  * `maxDepth` and records the usage event in the path. One value with one
450
452
  * canned output is no fork, but its usage event is still recorded. No `budget`
451
453
  * field is sent. A settling request with no entry while a usage transition
452
- * is active lists `@agent.usage` in `vacuous`. Requests inside child
453
- * machines and decisions deliver no usage.
454
+ * is active lists `@agent.usage` in `vacuous`. With `children:
455
+ * "coupled"`, a child's text request forks once per value and its usage
456
+ * event goes to the root, which takes or drops it the same way (no
457
+ * `vacuous` entry). Requests inside other children, and decisions, deliver
458
+ * no usage.
454
459
  */
455
460
  usage?: Record<string, AgentCallUsage[]>;
456
461
  }
package/docs/decisions.md CHANGED
@@ -170,7 +170,7 @@ Retry behavior:
170
170
 
171
171
  Core validates and retries. It never calls a model. Coercing the model into choosing exactly one option is the host's responsibility. The shipped AI SDK, OpenAI, and TanStack AI executors offer two modes, set by the `decideMode` option on each adapter:
172
172
 
173
- - `'object'` (default for object payloads): one structured-output call. An open choice answers `{ event }`, where `event` is one candidate event, `type` included. Root unions of object payloads become separate event variants. A closed choice answers `{ choice }`, an enum of option ids. The answer holds one event by construction.
173
+ - `'object'` (default for object payloads): one structured-output call. An open choice answers `{ event }`, where `event` is one candidate event, `type` included. Root unions of object payloads become separate event variants. A closed choice answers `{ choice }`, an enum of option ids. The schema allows only one event per answer.
174
174
  - `'tool'`: one tool per candidate event under a forced tool choice. Parallel tool calls are turned off where the provider allows it, and an answer that still calls more than one tool is rejected.
175
175
  - A function of the request picks the mode per request. Returning `undefined` uses the default: `'object'` when every payload can be represented as object variants, otherwise `'tool'`. This avoids unsupported `allOf` schemas in strict structured-output providers.
176
176
 
package/docs/event-log.md CHANGED
@@ -74,7 +74,8 @@ const result = await runToQuiescence(
74
74
  );
75
75
  ```
76
76
 
77
- - Each entry is written at its own `index` as `expectedIndex`, so a concurrent writer conflicts instead of interleaving.
77
+ - Entries are written in batches, each at its first entry's `index` as `expectedIndex`, so a concurrent writer conflicts instead of interleaving.
78
+ - A batch holds every entry since the loop last waited: an event, the child inputs its transition sent, and the events those children sent back land in one atomic append. A crash never keeps a cause without its effect.
78
79
  - No model call starts until every entry before it is durable. Pure transitions never wait.
79
80
  - A rejected write (an `AgentEventLogConflictError`, or any storage failure) aborts in-flight work and settles the run `{ status: "error", cause: "journal" }`. No further calls run.
80
81
  - A `@agent.usage` entry that arrives after the run settled is still written, but the result does not wait for it. Await `result.drain()` before terminating the process if you care about those straggler entries; it resolves once every write issued so far has landed, and never rejects (a failed write already settled the run with `cause: "journal"`).
@@ -153,7 +154,7 @@ const { snapshot, persistedSnapshot } = replay(machine, entries);
153
154
  ```
154
155
 
155
156
  - The first entry seeds the fold: `input` folds from `initialTransition`, `snapshot` restores purely and the rest of the log folds onto it.
156
- - `replay(machine, entries.slice(0, n))` rebuilds the state as of any point in the log — time travel with no side effects.
157
+ - `replay(machine, entries.slice(0, n))` rebuilds the state as of any point in the log, with no side effects.
157
158
  - Journaled child sessions are rebound to the sessions the current fold minted, so completions still apply.
158
159
 
159
160
  ## Verification
package/docs/hosts.md CHANGED
@@ -131,7 +131,7 @@ Decisions follow `decideMode`:
131
131
  - `'tool'`: one function tool per candidate event, with `tool_choice: 'required'` and `parallel_tool_calls: false`. Function tools are sent with `strict: false`, since the Responses API defaults strict mode on and arbitrary JSON Schema may fall outside it.
132
132
  - An answer the adapter cannot read as one event comes back as `rejected`, and the runtime retries it. See [Coercion](decisions.md#coercion).
133
133
 
134
- `generateText` runs the tool loop host-side. Each step that comes back with function calls runs the request's tools, appends the calls and one `function_call_output` item per result, and asks again. The replay is stateless: calls go back without their item ids, and reasoning items are left out. An incomplete turn, such as one cut off at `max_output_tokens`, never runs its calls, and an incomplete decision throws instead of choosing. A `failed` response throws on both paths, with its error code and message. The request's `maxSteps` bounds the number of OpenAI calls; the default is one, so a single-step request behaves as before. A tool that throws, a call to a tool the request did not offer, and arguments that are not JSON go back to the model as error results. The loop also ends early on a tool with no `execute` — a client-side tool, whose call is handed back with `finishReason: 'tool-calls'` and the raw response. Every step's `usage` is summed onto the one result the run aggregates. `modelCalls` reports the steps, and a loop that throws after a step records them on the error, so the run's budget counts them.
134
+ `generateText` runs the tool loop host-side. Each step that comes back with function calls runs the request's tools, appends the calls and one `function_call_output` item per result, and asks again. The replay is stateless: calls go back without their item ids, and reasoning items are left out. An incomplete turn, such as one cut off at `max_output_tokens`, never runs its calls, and an incomplete decision throws instead of choosing. A `failed` response throws on both paths, with its error code and message. The request's `maxSteps` bounds the number of OpenAI calls; the default is one, so a single-step request behaves as before. A tool that throws, a call to a tool the request did not offer, and arguments that are not JSON go back to the model as error results. The loop also ends early when the model calls a client-side tool (one with no `execute`). The call is handed back with `finishReason: 'tool-calls'` and the raw response. Every step's `usage` is summed onto the one result the run aggregates. `modelCalls` reports the steps, and a loop that throws after a step records them on the error, so the run's budget counts them.
135
135
 
136
136
  `toolChoice` maps onto `tool_choice`: `'auto'`, `'none'`, and `'required'` pass through, and `{ type: 'tool', name }` becomes `{ type: 'function', name }`. It is sent on the first step only, so a forced choice cannot re-fire every step and burn the step budget.
137
137
 
@@ -411,4 +411,4 @@ const result = await run;
411
411
 
412
412
  `provideExecutors(machine, executors)` binds the executors onto the machine so a plain `createActor` runs it, for an application that owns the actor or embeds the agent machine in a larger XState system. See [Advanced](advanced.md).
413
413
 
414
- Framework-owned concerns—storage, durable execution, retries, queues, and tool-loop interruption recovery—remain with the framework.
414
+ Framework-owned concerns (storage, durable execution, retries, queues, and tool-loop interruption recovery) remain with the framework.
@@ -408,9 +408,9 @@ The machine's `description` is its goal, so it leads the text. An excerpt:
408
408
  Machine ticket
409
409
  Goal: Answer the customer's ticket so they never write back.
410
410
  States (initial: triaging):
411
- triaging — Decide how to handle the ticket
411
+ triaging - Decide how to handle the ticket
412
412
  on ESCALATE → escalated
413
- on REPLY → drafting; sets tone — Draft a reply
413
+ on REPLY → drafting; sets tone - Draft a reply
414
414
  invoke agent.decide
415
415
  error → escalated
416
416
  checking (choice)
@@ -418,10 +418,10 @@ States (initial: triaging):
418
418
  choice if isRetryable → drafting
419
419
  choice else → escalated
420
420
  sent (final) [tags: done]
421
- escalated (final) — A human owns it now
421
+ escalated (final) - A human owns it now
422
422
  Events:
423
- REPLY — Answer the ticket directly
424
- tone: "formal" | "casual" — Reply tone
423
+ REPLY - Answer the ticket directly
424
+ tone: "formal" | "casual" - Reply tone
425
425
  ```
426
426
 
427
427
  - **States:** one line each, indented by depth, with the type, tags, `meta.interaction.label`, and description. Pass `snapshot` to mark the active states with `*`.