@statelyai/agent 2.0.0-alpha.36 → 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 (34) hide show
  1. package/CHANGELOG.md +27 -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 +1 -1
  5. package/dist/index.d.cts +3 -3
  6. package/dist/index.d.mts +3 -3
  7. package/dist/index.mjs +1 -1
  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/event-log.md +2 -1
  29. package/docs/persistence.md +71 -0
  30. package/docs/steps.md +2 -0
  31. package/docs/usage-and-budgets.md +2 -0
  32. package/docs/verify.md +7 -2
  33. package/package.json +1 -1
  34. 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/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"`).
@@ -70,6 +70,77 @@ if (result.ignored) {
70
70
  - A log that already reached a final state settles immediately with the recorded output.
71
71
  - The resumed result's `events` extends the same log, so the whole history stays replayable.
72
72
 
73
+ ## Crash testing
74
+
75
+ `checkCrashRecovery` from `@statelyai/agent/testing` kills a run at every point it could die and checks that the resume matches a run that never died.
76
+
77
+ ```ts
78
+ import { createAsyncLogic } from "xstate";
79
+ import { z } from "zod";
80
+ import { setupAgent, createTextLogic } from "@statelyai/agent";
81
+ import { checkCrashRecovery } from "@statelyai/agent/testing";
82
+
83
+ const machine = setupAgent({
84
+ context: z.object({ order: z.string() }),
85
+ events: {},
86
+ actors: {
87
+ lookup: createAsyncLogic({ run: async () => "order-7" }),
88
+ reply: createTextLogic({ model: "m", prompt: "Reply." }),
89
+ },
90
+ }).createMachine({
91
+ context: { order: "" },
92
+ initial: "lookup",
93
+ states: {
94
+ lookup: {
95
+ invoke: {
96
+ src: "lookup",
97
+ onDone: ({ event }) => ({ target: "reply", context: { order: event.output } }),
98
+ },
99
+ },
100
+ reply: { invoke: { src: "reply", onDone: { target: "done" } } },
101
+ done: { type: "final" },
102
+ },
103
+ });
104
+
105
+ const report = await checkCrashRecovery(machine, {
106
+ executors: { generateText: async () => ({ result: "Your order shipped." }) },
107
+ });
108
+ report.failures; // [] when every crash point recovers
109
+ ```
110
+
111
+ It runs the machine once uninterrupted, then once per crash point, each resumed from the store's log by a fresh runtime:
112
+
113
+ - **Log points:** before the first append, and after each append. The next write never lands.
114
+ - **Effect points:** while each model call or plain actor is in flight. It ran, but its result was never recorded.
115
+
116
+ Each resumed run is checked against the uninterrupted one. Each failure names its crash point and one of these problems:
117
+
118
+ | `problem` | Meaning |
119
+ | ----------------- | ------------------------------------------------------------------------------------------- |
120
+ | `reran` | An effect ran again although its completion was durable before the crash |
121
+ | `skipped` | An effect of the uninterrupted run never ran |
122
+ | `unexpected` | An effect ran that the uninterrupted run never made, such as a call under a new `callKey` |
123
+ | `request-changed` | A model call re-executed under its `callKey` with a different request |
124
+ | `outcome` | The resume ended with a different status, output, state, or context |
125
+ | `replay` | The final log does not replay to the resumed state |
126
+ | `undelivered` | A `sendDuring` event the crash lost, which the resume never reached the point to send again |
127
+ | `stuck` | The crashed run or its resume did not settle within `timeout` (default 5000 ms) |
128
+ | `threw` | The crashed run, its resume, or the `store` factory threw |
129
+
130
+ - `report.unreached` lists the points no run died at, with why: the crashed run never started that effect, or one write took the log past that length. A point is tried 3 times before it counts, since concurrent effects can settle in another order and merge two writes. Their resumes were not checked, so `report.ok` is `false`. An effect point is the n-th run of its key, so concurrent effects starting in another order still hit it.
131
+ - An effect in flight at the crash may run twice. That is the at-least-once contract (see [Idempotency keys](hosts.md#idempotency-keys)), and it is not reported.
132
+ - Model calls are keyed by `callKey` without the execution id, and plain actors by invoke site. Only actors bound through string-keyed sources are seen.
133
+ - Model calls run live only in the uninterrupted run. After a crash, a call it made gets its recorded answer, after the same delay, so a fake may answer by call order.
134
+ - Plain actors run live every time, so they must give the same result however often they run. A fake that keeps state passes `reset`, which runs before the baseline and each crashed run. It does not run before the resume, so the fake keeps what the crashed run did, as a real dependency would.
135
+ - The outcome check compares the root's final status, output, state, and context, not spawned children's. A child's progress counts only through what it reports to the root. It compares final states, so a machine whose result depends on which concurrent call finishes first can fail it after a crash. Make the result order-independent, or test that part without concurrency.
136
+ - `events` are host events, delivered one per idle settle. A resume skips the ones its log already holds.
137
+ - `sendDuring` sends host events while the run is busy: `{ during: "draft#1", event: { type: "CANCEL" } }` goes out the first time that effect starts, keyed as in `report.baseline.effects`: `<site>#<n>` for a model call, `actor:<site>` for a plain actor. Pass `occurrence` (from 0) to target a later start of the same key, such as a retry's second POST. After a crash, one the log does not hold is sent again, as a retrying host would, as its effect starts again or, when that effect's completion was durable, at the point the uninterrupted log holds it, so it lands in the same order. A `during` key (or `occurrence`) the uninterrupted run never starts throws, so a typo cannot pass silently.
138
+ - `timers: "host"` makes the harness the host scheduler for root `after` timers (see [Host-owned timers](steps.md#host-owned-timers)). The run settles `idle` with them pending. An id-less `{ type: "xstate.timer" }` in `events` is a timer's turn: the timer due soonest fires there. Once `events` run out, the pending timers fire in due order, without waiting for their delays. Each is due its delay after it was scheduled, on a clock that advances as timers fire. The default, in-process timers, fire after their real delay.
139
+ - An uninterrupted run that ends with some of `events` undelivered throws, so an event a final state never sees cannot pass silently.
140
+ - `store` takes a factory for your own store adapter, one fresh store per run. A store that acknowledges a write it then loses shows up as `reran`.
141
+
142
+ Run it in CI next to the machine's other tests. It needs no API key.
143
+
73
144
  ## Snapshot as cache
74
145
 
75
146
  `persist()` output carries `agentMeta: { machineId, version, logId, logIndex }` — the lineage and position of the log it caches.
package/docs/steps.md CHANGED
@@ -40,6 +40,8 @@ with an external timer pending. When it fires, deliver
40
40
  `{ type: "xstate.timer", id }` through `transition` or as the `event` passed to
41
41
  `runToQuiescence`.
42
42
 
43
+ A resumed run calls `schedule` again for each timer still pending, with what is left of its delay by the wall clock. Treat `schedule` as an upsert by `id`: a host that already holds that timer keeps its own due time. An `id` names a timer by its state and delay, not by arming, so a state entered again schedules the same `id` once the earlier timer has fired or been cancelled.
44
+
43
45
  An invoked child machine's `after` timers always run in process, and the run
44
46
  waits for them, whichever `timers` option you pass.
45
47