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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
  3. package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
  4. package/dist/ai-sdk.cjs +4 -4
  5. package/dist/ai-sdk.d.cts +2 -3
  6. package/dist/ai-sdk.d.mts +2 -3
  7. package/dist/ai-sdk.mjs +4 -4
  8. package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
  9. package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
  10. package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
  11. package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
  12. package/dist/effects-B9IvUPVh.mjs +23 -0
  13. package/dist/effects-DrWcUGgc.cjs +34 -0
  14. package/dist/evals.cjs +810 -0
  15. package/dist/evals.d.cts +595 -0
  16. package/dist/evals.d.mts +595 -0
  17. package/dist/evals.mjs +801 -0
  18. package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
  19. package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
  20. package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
  21. package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
  22. package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
  23. package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
  24. package/dist/index.cjs +142 -97
  25. package/dist/index.d.cts +97 -141
  26. package/dist/index.d.mts +97 -141
  27. package/dist/index.mjs +123 -74
  28. package/dist/internal-BzlpzSux.d.cts +14 -0
  29. package/dist/internal-BzlpzSux.d.mts +14 -0
  30. package/dist/log.cjs +2 -3
  31. package/dist/log.d.cts +2 -2
  32. package/dist/log.d.mts +2 -2
  33. package/dist/log.mjs +3 -3
  34. package/dist/machine-input-0YTPcnCm.mjs +27 -0
  35. package/dist/machine-input-DU3owLUr.cjs +32 -0
  36. package/dist/machines.cjs +1 -719
  37. package/dist/machines.d.cts +2 -424
  38. package/dist/machines.d.mts +2 -424
  39. package/dist/machines.mjs +2 -709
  40. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  41. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  42. package/dist/openai.cjs +3 -3
  43. package/dist/openai.d.cts +2 -3
  44. package/dist/openai.d.mts +2 -3
  45. package/dist/openai.mjs +3 -3
  46. package/dist/otel.d.cts +1 -1
  47. package/dist/otel.d.mts +1 -1
  48. package/dist/policy.cjs +77 -0
  49. package/dist/policy.d.cts +143 -0
  50. package/dist/policy.d.mts +143 -0
  51. package/dist/policy.mjs +75 -0
  52. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-BO9RSb7i.d.cts} +33 -40
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-BxkeuAYR.d.mts} +33 -40
  54. package/dist/{effects-DDseYtJk.cjs → run-agent-COdR9FpM.cjs} +175 -228
  55. package/dist/{effects-BT_cSY0j.mjs → run-agent-D3gW9wfd.mjs} +176 -211
  56. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  57. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  58. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  59. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  60. package/dist/tanstack-ai.cjs +4 -4
  61. package/dist/tanstack-ai.d.cts +2 -3
  62. package/dist/tanstack-ai.d.mts +2 -3
  63. package/dist/tanstack-ai.mjs +4 -4
  64. package/dist/testing.cjs +122 -996
  65. package/dist/testing.d.cts +36 -695
  66. package/dist/testing.d.mts +36 -695
  67. package/dist/testing.mjs +112 -977
  68. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  69. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  70. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  71. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  72. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  73. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  74. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  75. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  76. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  77. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  78. package/dist/validate.cjs +4 -4
  79. package/dist/validate.d.cts +2 -2
  80. package/dist/validate.d.mts +2 -2
  81. package/dist/validate.mjs +4 -4
  82. package/dist/{verify-DJHfEfm6.d.cts → verify-CIu4mqIZ.d.mts} +56 -6
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-CTHlmBbh.d.cts} +56 -6
  84. package/dist/{verify-ChyX6jq0.mjs → verify-Cacz6XSk.mjs} +170 -46
  85. package/dist/{verify-CwlombbC.cjs → verify-D8UDqU4l.cjs} +170 -46
  86. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  87. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  88. package/docs/advanced.md +5 -5
  89. package/docs/choosing-a-run-mode.md +7 -7
  90. package/docs/debugging.md +6 -8
  91. package/docs/decisions.md +5 -4
  92. package/docs/environment-and-policy.md +1 -1
  93. package/docs/evals.md +57 -43
  94. package/docs/event-log.md +13 -15
  95. package/docs/from-a-loop.md +3 -3
  96. package/docs/generate-machines.md +4 -4
  97. package/docs/hosts.md +25 -30
  98. package/docs/human-in-the-loop.md +5 -8
  99. package/docs/index.md +4 -4
  100. package/docs/judgments.md +5 -7
  101. package/docs/langgraph-comparison.md +6 -6
  102. package/docs/machines-as-data.md +7 -12
  103. package/docs/machines-presets.md +17 -120
  104. package/docs/machines.md +13 -13
  105. package/docs/models-and-providers.md +19 -25
  106. package/docs/multi-agent.md +1 -1
  107. package/docs/observability.md +6 -8
  108. package/docs/persistence.md +10 -20
  109. package/docs/quickstart.md +3 -3
  110. package/docs/statechart-policy-examples.md +1 -1
  111. package/docs/steps.md +5 -6
  112. package/docs/strangler-fig.md +105 -33
  113. package/docs/text-requests.md +10 -12
  114. package/docs/thinking-in-state-machines.md +8 -8
  115. package/docs/tools.md +10 -12
  116. package/docs/upgrading.md +1 -1
  117. package/docs/usage-and-budgets.md +51 -56
  118. package/docs/validate-and-repair.md +9 -14
  119. package/docs/verify.md +54 -7
  120. package/docs/xstate-4-and-5-apps.md +19 -28
  121. package/llms.txt +1 -1
  122. package/package.json +31 -6
  123. package/readme.md +32 -24
  124. package/dist/internal-C3Lqu538.d.cts +0 -43
  125. package/dist/internal-DUcdhk-i.d.mts +0 -43
  126. package/dist/types-DQUOOaZO.d.cts +0 -238
  127. package/dist/types-DQUOOaZO.d.mts +0 -238
  128. package/skills/add-evals/SKILL.md +0 -152
  129. package/skills/add-traces/SKILL.md +0 -152
  130. package/skills/build-machine/SKILL.md +0 -84
  131. package/skills/generate-machine/SKILL.md +0 -335
  132. package/skills/graph-engineering/SKILL.md +0 -43
  133. package/skills/improve-machine/SKILL.md +0 -261
  134. package/skills/improve-machine/reference.md +0 -101
  135. package/skills/loop-to-machine/SKILL.md +0 -205
  136. package/skills/loop-to-machine/policy.md +0 -154
  137. package/skills/loop-to-machine/reference.md +0 -260
@@ -1,5 +1,6 @@
1
- import { G as executorBoundLogics, R as isTextLogic, et as getJsonSchemaSync, ht as AgentError, mt as isRecord, q as getRegisteredAgentExecutionOptions, w as AGENT_USAGE_EVENT_TYPE } from "./event-log-DkVlk3Rh.mjs";
2
- import { _ as isEventPattern, g as getHumanEventTypes, h as getAcceptedEvents, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision } from "./decision-m5hGmHpF.mjs";
1
+ import { $ as getJsonSchemaSync, C as AGENT_USAGE_EVENT_TYPE, K as getRegisteredAgentExecutionOptions, L as isTextLogic, W as executorBoundLogics, ft as isRecord, pt as AgentError } from "./event-log-CEq_bVXQ.mjs";
2
+ import { _ as isEventPattern, g as getHumanEventTypes, h as getAcceptedEvents, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision } from "./decision-B41YBx5U.mjs";
3
+ import { t as resolveMachineInput } from "./machine-input-0YTPcnCm.mjs";
3
4
  import { getInitialMicrosteps, getMicrosteps, getNextTransitions, initialTransition, machineToJSON, transition } from "xstate";
4
5
  //#region src/steps.ts
5
6
  /**
@@ -578,6 +579,7 @@ function takeFromQueue(channel, src) {
578
579
  * ```
579
580
  */
580
581
  async function simulateAgent(machine, options) {
582
+ options = withMachineInput(machine, options, "simulateAgent");
581
583
  const maxSteps = options.maxSteps ?? 100;
582
584
  const script = {
583
585
  text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
@@ -990,7 +992,67 @@ function transientStateIds(node, ids = []) {
990
992
  function hasParallelStates(node) {
991
993
  return isRecord(node) && (node["type"] === "parallel" || Object.values(isRecord(node["states"]) ? node["states"] : {}).some(hasParallelStates));
992
994
  }
993
- function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false) {
995
+ function childSrcs(step) {
996
+ const children = step.snapshot.children ?? {};
997
+ const invoked = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src]));
998
+ return Object.entries(children).flatMap(([id, ref]) => {
999
+ if (!ref) return [];
1000
+ const own = ref.src;
1001
+ const src = invoked.get(id) ?? (typeof own === "string" ? own : id);
1002
+ return [{
1003
+ id,
1004
+ session: childSession(id, ref),
1005
+ src
1006
+ }];
1007
+ });
1008
+ }
1009
+ function exploreStep(prev, next, event) {
1010
+ const before = prev ? childSrcs(prev) : [];
1011
+ const sessions = new Set(before.map((child) => child.session));
1012
+ const actorId = event.actorId;
1013
+ const settles = (event.type === "xstate.done.actor" || event.type === "xstate.error.actor") && typeof actorId === "string";
1014
+ return {
1015
+ event,
1016
+ state: next.snapshot.value,
1017
+ started: childSrcs(next).filter((child) => !sessions.has(child.session)).map((child) => child.src),
1018
+ settled: settles ? before.filter((child) => child.id === actorId).map((child) => child.src) : []
1019
+ };
1020
+ }
1021
+ function stepsOf(log) {
1022
+ const steps = Array.from({ length: log?.length ?? 0 });
1023
+ for (let at = log; at; at = at.prev) steps[at.length - 1] = at.step;
1024
+ return steps;
1025
+ }
1026
+ function finishedInvokes(step) {
1027
+ const children = step.snapshot.children ?? {};
1028
+ return finishedChildren(step).map(({ id }) => {
1029
+ const ref = children[id];
1030
+ const own = ref;
1031
+ return {
1032
+ id,
1033
+ src: typeof own.src === "string" ? own.src : id,
1034
+ input: ref.options?.input,
1035
+ logic: own.logic,
1036
+ ref
1037
+ };
1038
+ });
1039
+ }
1040
+ function finishedChildren(step) {
1041
+ const children = step.snapshot.children ?? {};
1042
+ return Object.keys(children).sort().flatMap((id) => {
1043
+ const snapshot = children[id]?.getSnapshot?.();
1044
+ if (snapshot?.status === "done") return [{
1045
+ id,
1046
+ output: snapshot.output
1047
+ }];
1048
+ if (snapshot?.status === "error") return [{
1049
+ id,
1050
+ error: snapshot.error
1051
+ }];
1052
+ return [];
1053
+ });
1054
+ }
1055
+ 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
1056
  const maxDepth = options.maxDepth ?? 8;
995
1057
  const maxPaths = options.maxPaths ?? 200;
996
1058
  const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
@@ -1026,9 +1088,33 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1026
1088
  }
1027
1089
  return next;
1028
1090
  };
1029
- const resolveStep = (prev, id, output) => withTransits(resolveAgentStep(machine, prev, id, output), () => getMicrosteps(machine, prev.snapshot, doneEvent(prev.snapshot, id, output)));
1030
- const rejectStep = (prev, id, error) => withTransits(rejectAgentStep(machine, prev, id, error), () => getMicrosteps(machine, prev.snapshot, errorEvent(prev.snapshot, id, error)));
1031
- const transitionStep = (prev, event) => withTransits(transitionAgentStep(machine, prev, event), () => getMicrosteps(machine, prev.snapshot, event));
1091
+ const logging = nesting === 0 && !stepping && (options.steps === true || ordering !== void 0);
1092
+ const logs = /* @__PURE__ */ new WeakMap();
1093
+ const timerDelivers = /* @__PURE__ */ new WeakMap();
1094
+ const logged = (prev, next, event) => {
1095
+ if (!logging) return next;
1096
+ const before = prev && logs.get(prev);
1097
+ const step = exploreStep(prev, next, timerDelivers.get(event) ?? event);
1098
+ const trigger = ordering?.after;
1099
+ const after = (before?.after ?? false) || trigger !== void 0 && (typeof trigger === "string" ? step.event.type === trigger : trigger(step));
1100
+ logs.set(next, {
1101
+ step,
1102
+ prev: before,
1103
+ length: (before?.length ?? 0) + 1,
1104
+ after,
1105
+ violated: (before?.violated ?? false) || after && ordering.reach(step)
1106
+ });
1107
+ return next;
1108
+ };
1109
+ const resolveStep = (prev, id, output) => {
1110
+ const event = doneEvent(prev.snapshot, id, output);
1111
+ return logged(prev, withTransits(resolveAgentStep(machine, prev, id, output), () => getMicrosteps(machine, prev.snapshot, event)), event);
1112
+ };
1113
+ const rejectStep = (prev, id, error) => {
1114
+ const event = errorEvent(prev.snapshot, id, error);
1115
+ return logged(prev, withTransits(rejectAgentStep(machine, prev, id, error), () => getMicrosteps(machine, prev.snapshot, event)), event);
1116
+ };
1117
+ const transitionStep = (prev, event) => logged(prev, withTransits(transitionAgentStep(machine, prev, event), () => getMicrosteps(machine, prev.snapshot, event)), event);
1032
1118
  const settleStep = (prev, id, output, usage) => {
1033
1119
  if (!usage) return {
1034
1120
  step: resolveStep(prev, id, output),
@@ -1085,7 +1171,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1085
1171
  if (accepted.length === 0) return;
1086
1172
  return accepted.length < events.length ? [...accepted, void 0] : accepted;
1087
1173
  };
1088
- const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
1174
+ 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
1175
  const finiteCache = /* @__PURE__ */ new Map();
1090
1176
  const schemaPayloads = (type, snapshot) => {
1091
1177
  const schema = eventSchemas[type];
@@ -1096,12 +1182,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1096
1182
  }
1097
1183
  fill ??= {
1098
1184
  payloads: [{}],
1099
- complete: !mayReadPayload(snapshot, type)
1185
+ complete: ordering === void 0 && !mayReadPayload(snapshot, type)
1100
1186
  };
1101
1187
  if (!fill.complete && fill.payloads.length === 1 && Object.keys(fill.payloads[0]).length === 0 && mayReadPayload(snapshot, type)) vacuous.add(type);
1102
1188
  if (!fill.complete && !unexpanded.has(type)) {
1103
1189
  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`);
1190
+ 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
1191
  }
1106
1192
  return fill.payloads;
1107
1193
  };
@@ -1197,8 +1283,9 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1197
1283
  const concurrentForks = (step) => {
1198
1284
  if (options.children !== "explore" && !coupled) return;
1199
1285
  const invokes = pendingInvokes(step);
1200
- if (!invokes.some(isExploredChild)) return;
1201
- const kids = coupled ? invokes.filter(isExploredChild) : [];
1286
+ const finishedKids = coupled ? finishedInvokes(step).filter(isExploredChild) : [];
1287
+ if (!invokes.some(isExploredChild) && finishedKids.length === 0) return;
1288
+ const kids = coupled ? [...invokes.filter(isExploredChild), ...finishedKids] : [];
1202
1289
  const blocked = [];
1203
1290
  const asFork = (settle, id, src, isText, usage) => {
1204
1291
  if ("fork" in settle) return [settle.fork];
@@ -1217,10 +1304,22 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1217
1304
  };
1218
1305
  const texts = step.requests.filter((request) => request.kind === "text");
1219
1306
  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))];
1307
+ const forks = [
1308
+ ...texts.flatMap((request) => {
1309
+ const usage = usageFor(step, request);
1310
+ return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
1311
+ }),
1312
+ ...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)),
1313
+ ...finishedChildren(step).filter((finished) => !finishedKids.some((kid) => kid.id === finished.id)).map((finished) => "error" in finished ? {
1314
+ id: finished.id,
1315
+ errors: [finished.error],
1316
+ outputs: []
1317
+ } : {
1318
+ id: finished.id,
1319
+ errors: [],
1320
+ outputs: [finished.output]
1321
+ })
1322
+ ];
1224
1323
  const decisions = step.requests.filter((request) => request.kind === "decision");
1225
1324
  for (const decision of decisions) {
1226
1325
  const src = findInvokeMetadata(step, decision.id)?.src;
@@ -1261,7 +1360,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1261
1360
  if (nesting === 0) unexplored.push(text());
1262
1361
  };
1263
1362
  let captured;
1264
- const endPath = (path, terminal) => {
1363
+ const endPath = (path, step, terminal) => {
1265
1364
  if (captured) {
1266
1365
  captured.push({
1267
1366
  status: terminal.status,
@@ -1274,7 +1373,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1274
1373
  else if (terminal.status !== "done" && terminal.status !== "error") unfinished = true;
1275
1374
  if (nesting === 0) terminals.push({
1276
1375
  ...terminal,
1277
- path: pathOf(path)
1376
+ path: pathOf(path),
1377
+ ...options.steps ? { steps: stepsOf(logs.get(step)) } : {}
1278
1378
  });
1279
1379
  };
1280
1380
  let prunedByGuard = 0;
@@ -1308,11 +1408,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1308
1408
  }
1309
1409
  }
1310
1410
  };
1311
- const initial = stepping ? void 0 : withTransits(childStartStep(machine, options.input, childRef), () => getInitialMicrosteps(machine, options.input));
1312
- if (initial) {
1313
- recordState(initial, childRef?._initialEffects ?? initial.actions);
1314
- if (stops(initial)) witness = [];
1315
- }
1411
+ const initial = stepping ? void 0 : logged(void 0, withTransits(childStartStep(machine, options.input, childRef), () => getInitialMicrosteps(machine, options.input)), { type: "xstate.init" });
1412
+ if (initial) recordState(initial, childRef?._initialEffects ?? initial.actions);
1316
1413
  const undeliverable = /* @__PURE__ */ new Set();
1317
1414
  const external = deliverable ?? (options.hostEvents === void 0 ? void 0 : new Set(options.hostEvents));
1318
1415
  const arriving = (snapshot) => getAcceptedEvents(snapshot).filter((descriptor) => {
@@ -1324,7 +1421,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1324
1421
  const advance = (step, recordEvent, kids) => {
1325
1422
  let current = step;
1326
1423
  for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
1327
- if (!awaitsKids(current, kids) && stops(current, kids)) return {
1424
+ if ((stateTarget || !awaitsKids(current, kids)) && stops(current, kids)) return {
1328
1425
  step: current,
1329
1426
  hit: true
1330
1427
  };
@@ -1339,6 +1436,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1339
1436
  decisions: concurrent.decisions,
1340
1437
  ...concurrent.kids?.length ? { kids: concurrent.kids } : {}
1341
1438
  };
1439
+ const [finished] = finishedChildren(current);
1440
+ if (finished) {
1441
+ current = "error" in finished ? rejectStep(current, finished.id, finished.error) : resolveStep(current, finished.id, finished.output);
1442
+ recordState(current);
1443
+ continue;
1444
+ }
1342
1445
  if (request && request.kind === "text") {
1343
1446
  const usage = usageFor(current, request);
1344
1447
  const settle = settleFor(request.id, request.src, true, void 0, usage);
@@ -1444,10 +1547,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1444
1547
  }
1445
1548
  return armed.map(({ event, key }) => {
1446
1549
  const entry = { ...event };
1447
- timerFires.set(entry, {
1550
+ const command = {
1448
1551
  type: "xstate.timer",
1449
1552
  ...key
1450
- });
1553
+ };
1554
+ timerFires.set(entry, command);
1555
+ timerDelivers.set(command, event);
1451
1556
  return entry;
1452
1557
  });
1453
1558
  };
@@ -1503,7 +1608,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1503
1608
  }
1504
1609
  }
1505
1610
  const maxDepthTerminal = (settled, path) => {
1506
- endPath(path, {
1611
+ endPath(path, settled, {
1507
1612
  status: "max-depth",
1508
1613
  state: settled.snapshot.value
1509
1614
  });
@@ -1530,7 +1635,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1530
1635
  const pumped = /* @__PURE__ */ new WeakSet();
1531
1636
  let outParent;
1532
1637
  const register = (step, kids, queue) => {
1533
- const live = pendingInvokes(step).filter(isExploredChild);
1638
+ const live = [...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
1534
1639
  const sessions = new Set(live.map((invoke) => childSession(invoke.id, invoke.ref)));
1535
1640
  for (const session of kids.keys()) if (!sessions.has(session)) kids.delete(session);
1536
1641
  for (const invoke of live) {
@@ -1575,7 +1680,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1575
1680
  const awaitsKids = (step, kids) => {
1576
1681
  if (!coupled || pumped.has(step)) return false;
1577
1682
  const held = kids ?? /* @__PURE__ */ new Map();
1578
- if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1683
+ if ([...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
1579
1684
  return (Array.isArray(step.actions) ? step.actions : []).some((effect) => isRecord(effect) && effect["type"] === "@xstate.sendTo" && kidSessionFor(step, effect["target"], held) !== void 0);
1580
1685
  };
1581
1686
  const pump = (start, link, kids, queue) => {
@@ -1590,7 +1695,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1590
1695
  const delivered = kid.engine.deliver(kid, event);
1591
1696
  if (delivered.overflow) {
1592
1697
  overflow = true;
1593
- endPath(link, {
1698
+ endPath(link, at, {
1594
1699
  status: "max-depth",
1595
1700
  state: at.snapshot.value
1596
1701
  });
@@ -1613,17 +1718,20 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1613
1718
  unexpanded.add(route.event.type);
1614
1719
  note(() => `coupled: a child sent '${route.event.type}' to an actor the search does not model, at path [${pathTypes(link)}]`);
1615
1720
  };
1721
+ const starting = /* @__PURE__ */ new WeakSet();
1616
1722
  const flush = (at) => {
1617
1723
  if (pumped.has(at)) return;
1618
1724
  pumped.add(at);
1725
+ const queued = queue.length;
1619
1726
  if (!register(at, kids, queue)) {
1620
1727
  overflow = true;
1621
- endPath(link, {
1728
+ endPath(link, at, {
1622
1729
  status: "max-depth",
1623
1730
  state: at.snapshot.value
1624
1731
  });
1625
1732
  return;
1626
1733
  }
1734
+ for (const item of queue.slice(queued)) starting.add(item);
1627
1735
  for (const effect of Array.isArray(at.actions) ? at.actions : []) {
1628
1736
  if (!isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
1629
1737
  deliverTo(at, effect["target"], effect["event"]);
@@ -1634,7 +1742,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1634
1742
  for (let i = 0; queue.length > 0 && !overflow; i++) {
1635
1743
  if (step.done || step.snapshot.status !== "active" || witness !== void 0) break;
1636
1744
  if (i >= MAX_PUMP) {
1637
- endPath(link, {
1745
+ endPath(link, step, {
1638
1746
  status: "max-depth",
1639
1747
  state: step.snapshot.value
1640
1748
  });
@@ -1683,7 +1791,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1683
1791
  recordState(step);
1684
1792
  outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
1685
1793
  flush(step);
1686
- if (!overflow && stops(step, kids)) {
1794
+ if (!overflow && (stateTarget || !queue.some((queuedItem) => starting.has(queuedItem))) && stops(step, kids)) {
1687
1795
  witness = pathOf(link);
1688
1796
  break;
1689
1797
  }
@@ -1749,7 +1857,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1749
1857
  }
1750
1858
  }
1751
1859
  if (options.dedupeBy) {
1752
- const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
1860
+ const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids) + (logs.get(settled)?.after ? "after" : "");
1753
1861
  const seenAt = visited.get(key);
1754
1862
  if (seenAt !== void 0 && seenAt <= depth) return;
1755
1863
  visited.set(key, depth);
@@ -1789,7 +1897,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1789
1897
  for (const terminal of blocked) {
1790
1898
  if (witness !== void 0 || capped()) return;
1791
1899
  if (terminal.status === "idle" || terminal.status === "done" || terminal.status === "error") continue;
1792
- endPath(path, {
1900
+ endPath(path, settled, {
1793
1901
  status: terminal.status,
1794
1902
  state: settled.snapshot.value,
1795
1903
  ...terminal.status === "needs-output" ? { missingSrc: terminal.missingSrc ?? kid.src } : {}
@@ -1843,7 +1951,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1843
1951
  const registered = new Set([...(nodeKids ?? /* @__PURE__ */ new Map()).values()].map((kid) => kid.id));
1844
1952
  for (const kid of pendingKids.filter((invoke) => !registered.has(invoke.id))) {
1845
1953
  if (witness !== void 0 || capped()) return;
1846
- endPath(path, {
1954
+ endPath(path, settled, {
1847
1955
  status: "needs-output",
1848
1956
  state: settled.snapshot.value,
1849
1957
  missingSrc: kid.src
@@ -1862,7 +1970,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1862
1970
  }
1863
1971
  for (const src of blockedSiblings ?? []) {
1864
1972
  if (witness !== void 0 || capped()) return;
1865
- endPath(path, {
1973
+ endPath(path, settled, {
1866
1974
  status: "needs-output",
1867
1975
  state: settled.snapshot.value,
1868
1976
  missingSrc: src
@@ -1912,14 +2020,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1912
2020
  delivered: /* @__PURE__ */ new Set([...delivered ?? [], key])
1913
2021
  };
1914
2022
  }
1915
- if (fork.stalls && witness === void 0 && !capped()) endPath(path, {
2023
+ if (fork.stalls && witness === void 0 && !capped()) endPath(path, settled, {
1916
2024
  status: "idle",
1917
2025
  state: settled.snapshot.value
1918
2026
  });
1919
2027
  for (const src of blockedSiblings ?? []) note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
1920
2028
  for (const incompleteSrc of [...[fork, ...siblings ?? []].flatMap((child) => child.incompleteSrc === void 0 ? [] : [child.incompleteSrc]), ...blockedSiblings ?? []]) {
1921
2029
  if (witness !== void 0 || capped()) break;
1922
- endPath(path, {
2030
+ endPath(path, settled, {
1923
2031
  status: "needs-output",
1924
2032
  state: settled.snapshot.value,
1925
2033
  missingSrc: incompleteSrc
@@ -1933,7 +2041,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1933
2041
  if (witness !== void 0) return;
1934
2042
  }
1935
2043
  if (blockedSrc) {
1936
- endPath(path, {
2044
+ endPath(path, settled, {
1937
2045
  status: "needs-output",
1938
2046
  state: settled.snapshot.value,
1939
2047
  missingSrc: blockedSrc
@@ -1944,7 +2052,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1944
2052
  }
1945
2053
  if (settled.done) {
1946
2054
  const output = settled.snapshot.output;
1947
- endPath(path, {
2055
+ endPath(path, settled, {
1948
2056
  status: "done",
1949
2057
  state: settled.snapshot.value,
1950
2058
  ...output === void 0 ? {} : { output }
@@ -1954,7 +2062,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1954
2062
  }
1955
2063
  if (settled.snapshot.status === "error") {
1956
2064
  const error = settled.snapshot.error;
1957
- endPath(path, {
2065
+ endPath(path, settled, {
1958
2066
  status: "error",
1959
2067
  state: settled.snapshot.value,
1960
2068
  error
@@ -1969,14 +2077,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
1969
2077
  const requestOptions = request?.kind === "decision" ? acceptedDecisionOptions(request, () => true) : void 0;
1970
2078
  const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : acceptedVariants(snapshot, path, table);
1971
2079
  if (branchEvents.length === 0 && request?.kind !== "decision") {
1972
- endPath(path, {
2080
+ endPath(path, settled, {
1973
2081
  status: "idle",
1974
2082
  state: settled.snapshot.value
1975
2083
  });
1976
2084
  return;
1977
2085
  }
1978
2086
  if (depth >= maxDepth) {
1979
- endPath(path, {
2087
+ endPath(path, settled, {
1980
2088
  status: "max-depth",
1981
2089
  state: settled.snapshot.value
1982
2090
  });
@@ -2000,7 +2108,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2000
2108
  };
2001
2109
  }
2002
2110
  if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
2003
- endPath(path, {
2111
+ endPath(path, settled, {
2004
2112
  status: "idle",
2005
2113
  state: settled.snapshot.value
2006
2114
  });
@@ -2128,6 +2236,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2128
2236
  stepper
2129
2237
  };
2130
2238
  }
2239
+ if (initial && (stateTarget || !awaitsKids(initial, void 0)) && stops(initial)) witness = [];
2131
2240
  const root = {
2132
2241
  step: initial,
2133
2242
  path: void 0,
@@ -2186,6 +2295,19 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2186
2295
  };
2187
2296
  }
2188
2297
  /**
2298
+ * Validates `options.input` against the machine's input schema, as a run
2299
+ * would, and seeds the search with the parsed value (defaults filled). Input
2300
+ * the machine would reject throws `invalid-machine-input` instead of giving a
2301
+ * proof over a start state no run can reach.
2302
+ */
2303
+ function withMachineInput(machine, options, caller) {
2304
+ if (options.input === void 0) return options;
2305
+ return {
2306
+ ...options,
2307
+ input: resolveMachineInput(machine, options.input, caller)
2308
+ };
2309
+ }
2310
+ /**
2189
2311
  * Enumerates a machine's decision and external-event branches to a bounded
2190
2312
  * depth, model-free, and reports which states are reached and how each path
2191
2313
  * terminates. At each decision request it forks one branch per candidate event
@@ -2222,7 +2344,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
2222
2344
  * ```
2223
2345
  */
2224
2346
  async function explorePaths(machine, options = {}) {
2225
- return explore(machine, options).report;
2347
+ return explore(machine, withMachineInput(machine, options, "explorePaths")).report;
2226
2348
  }
2227
2349
  /** Thrown when a string reachability target is not a state in the machine. */
2228
2350
  var AgentUnknownStateError = class extends AgentError {
@@ -2271,8 +2393,10 @@ function resolveStateTarget(machine, target) {
2271
2393
  * ```
2272
2394
  */
2273
2395
  async function canReach(machine, target, options = {}) {
2396
+ options = withMachineInput(machine, options, "canReach");
2274
2397
  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)));
2398
+ const ordering = typeof target === "object" ? target : void 0;
2399
+ 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
2400
  if (witness !== void 0) return {
2277
2401
  reachable: true,
2278
2402
  witness,