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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
  3. package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
  4. package/dist/ai-sdk.cjs +4 -4
  5. package/dist/ai-sdk.d.cts +2 -3
  6. package/dist/ai-sdk.d.mts +2 -3
  7. package/dist/ai-sdk.mjs +4 -4
  8. package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
  9. package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
  10. package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
  11. package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
  12. package/dist/effects-B9IvUPVh.mjs +23 -0
  13. package/dist/effects-DrWcUGgc.cjs +34 -0
  14. package/dist/evals.cjs +810 -0
  15. package/dist/evals.d.cts +595 -0
  16. package/dist/evals.d.mts +595 -0
  17. package/dist/evals.mjs +801 -0
  18. package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
  19. package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
  20. package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
  21. package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
  22. package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
  23. package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
  24. package/dist/index.cjs +131 -93
  25. package/dist/index.d.cts +73 -134
  26. package/dist/index.d.mts +73 -134
  27. package/dist/index.mjs +112 -70
  28. package/dist/internal-BzlpzSux.d.cts +14 -0
  29. package/dist/internal-BzlpzSux.d.mts +14 -0
  30. package/dist/log.cjs +2 -3
  31. package/dist/log.d.cts +2 -2
  32. package/dist/log.d.mts +2 -2
  33. package/dist/log.mjs +3 -3
  34. package/dist/machines.cjs +1 -719
  35. package/dist/machines.d.cts +2 -424
  36. package/dist/machines.d.mts +2 -424
  37. package/dist/machines.mjs +2 -709
  38. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  39. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  40. package/dist/openai.cjs +3 -3
  41. package/dist/openai.d.cts +2 -3
  42. package/dist/openai.d.mts +2 -3
  43. package/dist/openai.mjs +3 -3
  44. package/dist/otel.d.cts +1 -1
  45. package/dist/otel.d.mts +1 -1
  46. package/dist/policy.cjs +77 -0
  47. package/dist/policy.d.cts +143 -0
  48. package/dist/policy.d.mts +143 -0
  49. package/dist/policy.mjs +75 -0
  50. package/dist/{effects-BT_cSY0j.mjs → run-agent-BE7DOWD6.mjs} +150 -184
  51. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-DHlq87G7.d.mts} +18 -34
  52. package/dist/{effects-DDseYtJk.cjs → run-agent-De3xVFGw.cjs} +149 -201
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-Dq0oSFRm.d.cts} +18 -34
  54. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  55. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  56. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  57. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  58. package/dist/tanstack-ai.cjs +4 -4
  59. package/dist/tanstack-ai.d.cts +2 -3
  60. package/dist/tanstack-ai.d.mts +2 -3
  61. package/dist/tanstack-ai.mjs +4 -4
  62. package/dist/testing.cjs +122 -996
  63. package/dist/testing.d.cts +36 -695
  64. package/dist/testing.d.mts +36 -695
  65. package/dist/testing.mjs +112 -977
  66. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  67. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  68. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  69. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  70. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  71. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  72. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  73. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  74. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  75. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  76. package/dist/validate.cjs +4 -4
  77. package/dist/validate.d.cts +2 -2
  78. package/dist/validate.d.mts +2 -2
  79. package/dist/validate.mjs +4 -4
  80. package/dist/{verify-DJHfEfm6.d.cts → verify-BM0sGmsf.d.cts} +42 -6
  81. package/dist/{verify-ChyX6jq0.mjs → verify-CWlg3j7B.mjs} +153 -45
  82. package/dist/{verify-CwlombbC.cjs → verify-Dek6gHCS.cjs} +153 -45
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-H3Pr2gNw.d.mts} +42 -6
  84. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  85. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  86. package/docs/advanced.md +5 -5
  87. package/docs/choosing-a-run-mode.md +7 -7
  88. package/docs/debugging.md +6 -8
  89. package/docs/decisions.md +5 -4
  90. package/docs/environment-and-policy.md +1 -1
  91. package/docs/evals.md +57 -43
  92. package/docs/event-log.md +13 -15
  93. package/docs/from-a-loop.md +3 -3
  94. package/docs/generate-machines.md +4 -4
  95. package/docs/hosts.md +20 -27
  96. package/docs/human-in-the-loop.md +5 -8
  97. package/docs/index.md +4 -4
  98. package/docs/judgments.md +5 -7
  99. package/docs/langgraph-comparison.md +6 -6
  100. package/docs/machines-as-data.md +7 -12
  101. package/docs/machines-presets.md +17 -120
  102. package/docs/machines.md +13 -13
  103. package/docs/models-and-providers.md +19 -25
  104. package/docs/multi-agent.md +1 -1
  105. package/docs/observability.md +6 -8
  106. package/docs/persistence.md +10 -20
  107. package/docs/quickstart.md +3 -3
  108. package/docs/statechart-policy-examples.md +1 -1
  109. package/docs/steps.md +5 -6
  110. package/docs/strangler-fig.md +72 -7
  111. package/docs/text-requests.md +10 -12
  112. package/docs/thinking-in-state-machines.md +8 -8
  113. package/docs/tools.md +10 -12
  114. package/docs/upgrading.md +1 -1
  115. package/docs/usage-and-budgets.md +51 -56
  116. package/docs/validate-and-repair.md +9 -14
  117. package/docs/verify.md +53 -7
  118. package/docs/xstate-4-and-5-apps.md +19 -28
  119. package/llms.txt +1 -1
  120. package/package.json +31 -6
  121. package/readme.md +32 -24
  122. package/dist/internal-C3Lqu538.d.cts +0 -43
  123. package/dist/internal-DUcdhk-i.d.mts +0 -43
  124. package/dist/types-DQUOOaZO.d.cts +0 -238
  125. package/dist/types-DQUOOaZO.d.mts +0 -238
  126. package/skills/add-evals/SKILL.md +0 -152
  127. package/skills/add-traces/SKILL.md +0 -152
  128. package/skills/build-machine/SKILL.md +0 -84
  129. package/skills/generate-machine/SKILL.md +0 -335
  130. package/skills/graph-engineering/SKILL.md +0 -43
  131. package/skills/improve-machine/SKILL.md +0 -261
  132. package/skills/improve-machine/reference.md +0 -101
  133. package/skills/loop-to-machine/SKILL.md +0 -205
  134. package/skills/loop-to-machine/policy.md +0 -154
  135. package/skills/loop-to-machine/reference.md +0 -260
@@ -1,9 +1,150 @@
1
- import { C as validateReplayEntries, E as ACT_ACTOR, F as getCallFinishReason, G as executorBoundLogics, I as getCallModelCalls, J as isUnboundPlaceholder, L as getCallUsage, Q as findNonSerializableContextPaths, R as isTextLogic, S as replay, T as restoreMachineSnapshot, W as responseMessagesOf, _ as getSnapshotStateHash, at as isStandardSchema, c as agentCallSite, d as canonicalEventJson, dt as canonicalJson, f as createReplayEntry, g as getLogExecutionId, ht as AgentError, i as AgentMachineVersionMismatchError, mt as isRecord, ot as resolveMachineVersion, p as foldLog, pt as isPlainObject, q as getRegisteredAgentExecutionOptions, s as agentCallOccurrence, u as assertJsonSerializable, ut as validateSchemaSync, v as getUsageFromEvents, w as AGENT_USAGE_EVENT_TYPE, y as initEntry, z as normalizeGeneratorResult } from "./event-log-DkVlk3Rh.mjs";
2
- import { _ as isEventPattern, a as createDecisionRequest, g as getHumanEventTypes, h as getAcceptedEvents, l as resolveAllowedEventTypes, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision } from "./decision-m5hGmHpF.mjs";
3
- import { i as isActLogic, t as ACT_STATE_EXITED } from "./act-B9hLQls6.mjs";
4
- import { t as AgentEventLogConflictError } from "./event-log-store-Brx9tOHt.mjs";
1
+ import { C as AGENT_USAGE_EVENT_TYPE, F as getCallModelCalls, I as getCallUsage, K as getRegisteredAgentExecutionOptions, L as isTextLogic, P as getCallFinishReason, R as normalizeGeneratorResult, S as validateReplayEntries, T as ACT_ACTOR, U as responseMessagesOf, W as executorBoundLogics, Z as findNonSerializableContextPaths, _ as getSnapshotStateHash, c as agentCallSite, ct as validateSchemaSync, d as canonicalEventJson, dt as isPlainObject, f as createReplayEntry, ft as isRecord, g as getLogExecutionId, i as AgentMachineVersionMismatchError, it as resolveMachineVersion, lt as canonicalJson, p as foldLog, pt as AgentError, q as isUnboundPlaceholder, rt as isStandardSchema, s as agentCallOccurrence, u as assertJsonSerializable, v as getUsageFromEvents, w as restoreMachineSnapshot, x as replay, y as initEntry } from "./event-log-CEq_bVXQ.mjs";
2
+ import { _ as isEventPattern, a as createDecisionRequest, g as getHumanEventTypes, h as getAcceptedEvents, l as resolveAllowedEventTypes, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision } from "./decision-B41YBx5U.mjs";
3
+ import { i as isActLogic, t as ACT_STATE_EXITED } from "./act-Bsz-hUfD.mjs";
4
+ import { t as AgentEventLogConflictError } from "./event-log-store-DLAfNM34.mjs";
5
5
  import { createAsyncLogic, deliverEvent, getNextTransitions, isMachineSnapshot, stopActor, transition } from "xstate";
6
6
  import { createDurable } from "xstate/durable";
7
+ //#region src/internal/stable-inspection.ts
8
+ const stableInspections = /* @__PURE__ */ new WeakSet();
9
+ /** Whether `inspect` already came from {@link stableInspection}. */
10
+ function isStableInspection(inspect) {
11
+ return typeof inspect === "function" && stableInspections.has(inspect);
12
+ }
13
+ function actorPath(ref) {
14
+ const ids = [];
15
+ let current = ref;
16
+ while (isRecord(current)) {
17
+ ids.unshift(current["id"]);
18
+ current = current["_parent"];
19
+ }
20
+ return JSON.stringify(ids);
21
+ }
22
+ function persistedChildPaths(persisted, prefix = [], paths = /* @__PURE__ */ new Set()) {
23
+ const children = isRecord(persisted) ? persisted["children"] : void 0;
24
+ if (!isRecord(children)) return paths;
25
+ for (const [id, child] of Object.entries(children)) {
26
+ const path = [...prefix, id];
27
+ paths.add(JSON.stringify(path));
28
+ persistedChildPaths(isRecord(child) ? child["snapshot"] : void 0, path, paths);
29
+ }
30
+ return paths;
31
+ }
32
+ /**
33
+ * Makes a durable run's inspection stream look like one live actor system to
34
+ * an inspector. The durable runtime re-creates an actor object for each step
35
+ * under the same `sessionId` and announces it again, so an inspector that
36
+ * tracks actors by object (`@statelyai/sdk`) sees a duplicate and drops the
37
+ * rest of the run. Each `sessionId` gets one stable handle that reads from the
38
+ * newest actor object, and is announced once. Across runtimes (`runAgent`'s
39
+ * `onIdle` passes), {@link StableInspection.endPass} carries live actors over.
40
+ */
41
+ function stableInspection(inspect) {
42
+ const handles = /* @__PURE__ */ new Map();
43
+ const announced = /* @__PURE__ */ new Set();
44
+ const snapshots = /* @__PURE__ */ new WeakMap();
45
+ const aliases = /* @__PURE__ */ new Map();
46
+ const live = /* @__PURE__ */ new Map();
47
+ const stopped = /* @__PURE__ */ new Map();
48
+ let carried = /* @__PURE__ */ new Map();
49
+ const stableSnapshot = (snapshot) => {
50
+ if (!isRecord(snapshot) || !isRecord(snapshot["children"])) return snapshot;
51
+ const cached = snapshots.get(snapshot);
52
+ if (cached) return cached;
53
+ const copy = Object.create(Object.getPrototypeOf(snapshot), Object.getOwnPropertyDescriptors(snapshot));
54
+ copy["children"] = Object.fromEntries(Object.entries(snapshot["children"]).map(([id, child]) => [id, stable(child)]));
55
+ snapshots.set(snapshot, copy);
56
+ return copy;
57
+ };
58
+ const stable = (ref, adopt = false) => {
59
+ if (!isRecord(ref) || typeof ref["sessionId"] !== "string") return ref;
60
+ const sessionId = aliases.get(ref["sessionId"]) ?? ref["sessionId"];
61
+ const known = handles.get(sessionId);
62
+ if (known) {
63
+ if (adopt) known.latest = ref;
64
+ return known.handle;
65
+ }
66
+ const entry = {
67
+ latest: ref,
68
+ handle: ref
69
+ };
70
+ entry.handle = new Proxy(ref, {
71
+ get(_target, key) {
72
+ const value = Reflect.get(entry.latest, key, entry.latest);
73
+ if (key === "_parent") return stable(value);
74
+ if (key === "ref") return entry.handle;
75
+ if (key === "sessionId") return sessionId;
76
+ if (key === "getSnapshot") return () => stableSnapshot(entry.latest.getSnapshot());
77
+ if (key === "_snapshot") return stableSnapshot(value);
78
+ if (key === "options" && isRecord(value) && value["parent"] !== void 0) return {
79
+ ...value,
80
+ parent: stable(value["parent"])
81
+ };
82
+ return typeof value === "function" ? value.bind(entry.latest) : value;
83
+ },
84
+ has: (_target, key) => key in entry.latest
85
+ });
86
+ handles.set(sessionId, entry);
87
+ return entry.handle;
88
+ };
89
+ const stableInspect = ((event) => {
90
+ const raw = event;
91
+ const actorRef = raw["actorRef"];
92
+ const rawSessionId = isRecord(actorRef) ? actorRef["sessionId"] : void 0;
93
+ if (raw["type"] === "@xstate.actor" && typeof rawSessionId === "string") {
94
+ const path = actorPath(actorRef);
95
+ const previous = carried.get(path);
96
+ if (previous !== void 0 && previous !== rawSessionId) {
97
+ carried.delete(path);
98
+ aliases.set(rawSessionId, previous);
99
+ }
100
+ const sessionId = aliases.get(rawSessionId) ?? rawSessionId;
101
+ live.set(sessionId, path);
102
+ if (announced.has(sessionId)) {
103
+ stable(actorRef, true);
104
+ return;
105
+ }
106
+ announced.add(sessionId);
107
+ }
108
+ if (typeof rawSessionId === "string" && isRecord(raw["snapshot"])) {
109
+ const status = raw["snapshot"]["status"];
110
+ if (status !== void 0 && status !== "active") {
111
+ const sessionId = aliases.get(rawSessionId) ?? rawSessionId;
112
+ const path = live.get(sessionId);
113
+ live.delete(sessionId);
114
+ if (status === "stopped" && path !== void 0) stopped.set(sessionId, path);
115
+ }
116
+ }
117
+ const next = {
118
+ ...raw,
119
+ actorRef: stable(actorRef, true)
120
+ };
121
+ if (raw["snapshot"] !== void 0) next["snapshot"] = stableSnapshot(raw["snapshot"]);
122
+ if (Array.isArray(raw["sent"])) next["sent"] = raw["sent"].map((sent) => isRecord(sent) && sent["targetRef"] !== void 0 ? {
123
+ ...sent,
124
+ targetRef: stable(sent["targetRef"])
125
+ } : sent);
126
+ for (const key of [
127
+ "parentRef",
128
+ "sourceRef",
129
+ "targetRef"
130
+ ]) if (raw[key] !== void 0) next[key] = stable(raw[key]);
131
+ inspect(next);
132
+ });
133
+ stableInspect.endPass = (persisted) => {
134
+ const kept = persistedChildPaths(persisted);
135
+ const root = [...live.values(), ...stopped.values()].find((path) => JSON.parse(path).length === 1);
136
+ const rootId = root === void 0 ? void 0 : JSON.parse(root)[0];
137
+ const carriedStopped = [...stopped].filter(([, path]) => {
138
+ const [id, ...rest] = JSON.parse(path);
139
+ return id === rootId && kept.has(JSON.stringify(rest));
140
+ });
141
+ stopped.clear();
142
+ carried = new Map([...live, ...carriedStopped].map(([sessionId, path]) => [path, sessionId]));
143
+ };
144
+ stableInspections.add(stableInspect);
145
+ return stableInspect;
146
+ }
147
+ //#endregion
7
148
  //#region src/decide-next.ts
8
149
  /**
9
150
  * Asks a model to choose the next event for ANY XState snapshot, including a
@@ -182,147 +323,6 @@ function short(value, max = 60) {
182
323
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
183
324
  }
184
325
  //#endregion
185
- //#region src/internal/stable-inspection.ts
186
- const stableInspections = /* @__PURE__ */ new WeakSet();
187
- /** Whether `inspect` already came from {@link stableInspection}. */
188
- function isStableInspection(inspect) {
189
- return typeof inspect === "function" && stableInspections.has(inspect);
190
- }
191
- function actorPath(ref) {
192
- const ids = [];
193
- let current = ref;
194
- while (isRecord(current)) {
195
- ids.unshift(current["id"]);
196
- current = current["_parent"];
197
- }
198
- return JSON.stringify(ids);
199
- }
200
- function persistedChildPaths(persisted, prefix = [], paths = /* @__PURE__ */ new Set()) {
201
- const children = isRecord(persisted) ? persisted["children"] : void 0;
202
- if (!isRecord(children)) return paths;
203
- for (const [id, child] of Object.entries(children)) {
204
- const path = [...prefix, id];
205
- paths.add(JSON.stringify(path));
206
- persistedChildPaths(isRecord(child) ? child["snapshot"] : void 0, path, paths);
207
- }
208
- return paths;
209
- }
210
- /**
211
- * Makes a durable run's inspection stream look like one live actor system to
212
- * an inspector. The durable runtime re-creates an actor object for each step
213
- * under the same `sessionId` and announces it again, so an inspector that
214
- * tracks actors by object (`@statelyai/sdk`) sees a duplicate and drops the
215
- * rest of the run. Each `sessionId` gets one stable handle that reads from the
216
- * newest actor object, and is announced once. Across runtimes (`runAgent`'s
217
- * `onIdle` passes), {@link StableInspection.endPass} carries live actors over.
218
- */
219
- function stableInspection(inspect) {
220
- const handles = /* @__PURE__ */ new Map();
221
- const announced = /* @__PURE__ */ new Set();
222
- const snapshots = /* @__PURE__ */ new WeakMap();
223
- const aliases = /* @__PURE__ */ new Map();
224
- const live = /* @__PURE__ */ new Map();
225
- const stopped = /* @__PURE__ */ new Map();
226
- let carried = /* @__PURE__ */ new Map();
227
- const stableSnapshot = (snapshot) => {
228
- if (!isRecord(snapshot) || !isRecord(snapshot["children"])) return snapshot;
229
- const cached = snapshots.get(snapshot);
230
- if (cached) return cached;
231
- const copy = Object.create(Object.getPrototypeOf(snapshot), Object.getOwnPropertyDescriptors(snapshot));
232
- copy["children"] = Object.fromEntries(Object.entries(snapshot["children"]).map(([id, child]) => [id, stable(child)]));
233
- snapshots.set(snapshot, copy);
234
- return copy;
235
- };
236
- const stable = (ref, adopt = false) => {
237
- if (!isRecord(ref) || typeof ref["sessionId"] !== "string") return ref;
238
- const sessionId = aliases.get(ref["sessionId"]) ?? ref["sessionId"];
239
- const known = handles.get(sessionId);
240
- if (known) {
241
- if (adopt) known.latest = ref;
242
- return known.handle;
243
- }
244
- const entry = {
245
- latest: ref,
246
- handle: ref
247
- };
248
- entry.handle = new Proxy(ref, {
249
- get(_target, key) {
250
- const value = Reflect.get(entry.latest, key, entry.latest);
251
- if (key === "_parent") return stable(value);
252
- if (key === "ref") return entry.handle;
253
- if (key === "sessionId") return sessionId;
254
- if (key === "getSnapshot") return () => stableSnapshot(entry.latest.getSnapshot());
255
- if (key === "_snapshot") return stableSnapshot(value);
256
- if (key === "options" && isRecord(value) && value["parent"] !== void 0) return {
257
- ...value,
258
- parent: stable(value["parent"])
259
- };
260
- return typeof value === "function" ? value.bind(entry.latest) : value;
261
- },
262
- has: (_target, key) => key in entry.latest
263
- });
264
- handles.set(sessionId, entry);
265
- return entry.handle;
266
- };
267
- const stableInspect = ((event) => {
268
- const raw = event;
269
- const actorRef = raw["actorRef"];
270
- const rawSessionId = isRecord(actorRef) ? actorRef["sessionId"] : void 0;
271
- if (raw["type"] === "@xstate.actor" && typeof rawSessionId === "string") {
272
- const path = actorPath(actorRef);
273
- const previous = carried.get(path);
274
- if (previous !== void 0 && previous !== rawSessionId) {
275
- carried.delete(path);
276
- aliases.set(rawSessionId, previous);
277
- }
278
- const sessionId = aliases.get(rawSessionId) ?? rawSessionId;
279
- live.set(sessionId, path);
280
- if (announced.has(sessionId)) {
281
- stable(actorRef, true);
282
- return;
283
- }
284
- announced.add(sessionId);
285
- }
286
- if (typeof rawSessionId === "string" && isRecord(raw["snapshot"])) {
287
- const status = raw["snapshot"]["status"];
288
- if (status !== void 0 && status !== "active") {
289
- const sessionId = aliases.get(rawSessionId) ?? rawSessionId;
290
- const path = live.get(sessionId);
291
- live.delete(sessionId);
292
- if (status === "stopped" && path !== void 0) stopped.set(sessionId, path);
293
- }
294
- }
295
- const next = {
296
- ...raw,
297
- actorRef: stable(actorRef, true)
298
- };
299
- if (raw["snapshot"] !== void 0) next["snapshot"] = stableSnapshot(raw["snapshot"]);
300
- if (Array.isArray(raw["sent"])) next["sent"] = raw["sent"].map((sent) => isRecord(sent) && sent["targetRef"] !== void 0 ? {
301
- ...sent,
302
- targetRef: stable(sent["targetRef"])
303
- } : sent);
304
- for (const key of [
305
- "parentRef",
306
- "sourceRef",
307
- "targetRef"
308
- ]) if (raw[key] !== void 0) next[key] = stable(raw[key]);
309
- inspect(next);
310
- });
311
- stableInspect.endPass = (persisted) => {
312
- const kept = persistedChildPaths(persisted);
313
- const root = [...live.values(), ...stopped.values()].find((path) => JSON.parse(path).length === 1);
314
- const rootId = root === void 0 ? void 0 : JSON.parse(root)[0];
315
- const carriedStopped = [...stopped].filter(([, path]) => {
316
- const [id, ...rest] = JSON.parse(path);
317
- return id === rootId && kept.has(JSON.stringify(rest));
318
- });
319
- stopped.clear();
320
- carried = new Map([...live, ...carriedStopped].map(([sessionId, path]) => [path, sessionId]));
321
- };
322
- stableInspections.add(stableInspect);
323
- return stableInspect;
324
- }
325
- //#endregion
326
326
  //#region src/run-agent.ts
327
327
  /**
328
328
  * Thrown by {@link AgentRuntime.start} when a resume is given BOTH an `events` log and a
@@ -1909,7 +1909,10 @@ function createAgentRuntime(machine, options = {}) {
1909
1909
  warnedNonSerializable = true;
1910
1910
  console.warn(`createAgentRuntime: context holds value(s) that will not survive snapshot persist/resume (JSON round-trip): ${offending.join(", ")}. Persist only JSON-serializable context, or convert these before the run settles.`);
1911
1911
  };
1912
- const provided = machine.provide({ actors: options.actors });
1912
+ const provided = machine.provide({
1913
+ actors: options.actors,
1914
+ ...options.actions && { actions: options.actions }
1915
+ });
1913
1916
  logMachine = provided;
1914
1917
  const effectiveSources = provided.sources.actors;
1915
1918
  const executors = { ...options.executors };
@@ -2576,21 +2579,6 @@ function createAgentRuntime(machine, options = {}) {
2576
2579
  return runtime;
2577
2580
  }
2578
2581
  /**
2579
- * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
2580
- * {@link AgentRuntimeOptions.inspect}: it filters the raw inspection stream to
2581
- * `@xstate.transition` events and hands the handler the typed
2582
- * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
2583
- * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
2584
- * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
2585
- * actorRef casts.
2586
- */
2587
- function inspectTransitions(handler) {
2588
- return (inspectionEvent) => {
2589
- if (inspectionEvent.type !== "@xstate.transition") return;
2590
- handler(inspectionEvent.snapshot, inspectionEvent.actorRef);
2591
- };
2592
- }
2593
- /**
2594
2582
  * An xstate `inspect` handler that emits `machine.transition` trace events onto
2595
2583
  * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
2596
2584
  * registry as {@link provideExecutors}' `onTrace`. Pair the two on one actor to
@@ -2649,26 +2637,4 @@ function isAgentIdle(snapshot) {
2649
2637
  }) || getAcceptedEvents(snapshot).length > 0;
2650
2638
  }
2651
2639
  //#endregion
2652
- //#region src/internal/effects.ts
2653
- /**
2654
- * A plain copy of an effects object with every callable effect passed
2655
- * through `wrap`: own and inherited methods alike (a class instance's
2656
- * prototype methods), each bound to the original object so `this` still
2657
- * works. Other own properties are copied as they are.
2658
- */
2659
- function mapEffects(effects, wrap) {
2660
- const source = effects;
2661
- const out = {};
2662
- for (let level = effects; level !== null && level !== Object.prototype; level = Object.getPrototypeOf(level)) for (const name of Object.getOwnPropertyNames(level)) {
2663
- if (name === "constructor" || name in out) continue;
2664
- const value = source[name];
2665
- out[name] = typeof value === "function" ? wrap(name, value.bind(effects)) : value;
2666
- }
2667
- return out;
2668
- }
2669
- /** A stream, as recorders and wrapped effects see one: anything `for await` reads. */
2670
- function isAsyncIterable(value) {
2671
- return value !== null && (typeof value === "object" || typeof value === "function") && typeof value[Symbol.asyncIterator] === "function";
2672
- }
2673
- //#endregion
2674
- export { runToQuiescence as _, AgentSnapshotDivergedError as a, traceTransitions as b, bindDecisionForProvide as c, createAgentRuntime as d, getConfiguredInvokeSrcs as f, runAgent as g, isStateMachineLogic as h, AgentMaxModelCallsExceededError as i, bindTextForProvide as l, isAgentIdle as m, mapEffects as n, bindActForProvide as o, inspectTransitions as p, AGENT_TRACE_SCHEMA_VERSION as r, bindChildMachineForProvide as s, isAsyncIterable as t, createAgentInbox as u, serializeTraceEvent as v, decideNext as x, toJsonValue as y };
2640
+ export { traceTransitions as _, bindChildMachineForProvide as a, createAgentInbox as c, isAgentIdle as d, isStateMachineLogic as f, toJsonValue as g, serializeTraceEvent as h, bindActForProvide as i, createAgentRuntime as l, runToQuiescence as m, AgentMaxModelCallsExceededError as n, bindDecisionForProvide as o, runAgent as p, AgentSnapshotDivergedError as r, bindTextForProvide as s, AGENT_TRACE_SCHEMA_VERSION as t, getConfiguredInvokeSrcs as u, decideNext as v };
@@ -1,8 +1,7 @@
1
- import { C as StandardSchemaV1, j as WithAgentInputSchema, l as AgentTools, y as InferInput } from "./types-DQUOOaZO.mjs";
2
- import { B as DecisionAttempt, L as AgentDecisionRequest, Z as AgentEventDescriptor, at as AgentError, d as AgentRequestMode, et as AgentRequestSource, f as AgentTextRequest, m as AgentUsage, r as AgentFinishReason, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-BqxalgMr.mjs";
3
- import { n as AgentUsageEvent } from "./usage-BnikdOca.mjs";
4
- import { c as AgentLogEntry, h as JsonValue$1, n as AgentEventLogStore } from "./event-log-store-BBS8so8a.mjs";
5
- import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, StateValue } from "xstate";
1
+ import { B as DecisionAttempt, L as AgentDecisionRequest, Lt as WithAgentInputSchema, Tt as InferInput, Z as AgentEventDescriptor, at as AgentError, d as AgentRequestMode, et as AgentRequestSource, f as AgentTextRequest, ht as AgentTools, kt as StandardSchemaV1, m as AgentUsage, r as AgentFinishReason, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-x17uLBwA.mjs";
2
+ import { n as AgentUsageEvent } from "./usage-B4B-TQSV.mjs";
3
+ import { c as AgentLogEntry, h as JsonValue$1, n as AgentEventLogStore } from "./event-log-store-DYun526m.mjs";
4
+ import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, StateValue } from "xstate";
6
5
  import { DurableExecution } from "xstate/durable";
7
6
  //#region src/steps.d.ts
8
7
  /**
@@ -208,6 +207,8 @@ declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "t
208
207
  declare function serializeTraceEvent(event: AgentTraceEvent, options?: {
209
208
  includeRaw?: boolean;
210
209
  }): JsonSerializableTraceEvent;
210
+ /** The action implementations `machine.provide` accepts for `TMachine`. */
211
+ type ProvidedActions<TMachine extends AnyStateMachine> = NonNullable<Parameters<TMachine["provide"]>[0]["actions"]>;
211
212
  /**
212
213
  * Options for {@link createAgentRuntime}: what the runtime binds and observes.
213
214
  * The run's `input`/`snapshot`/`events` go to {@link AgentRuntime.start} (or
@@ -272,6 +273,13 @@ interface AgentRuntimeOptions<TMachine extends AnyStateMachine> {
272
273
  metadata?: Record<string, JsonValue$1>;
273
274
  /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actors })` ahead of the run. */
274
275
  actors?: Record<string, AnyActorLogic>;
276
+ /**
277
+ * Action implementations for this run, merged onto the machine before
278
+ * binding: sugar for `machine.provide({ actions })`. Each key must be an
279
+ * action declared in `setupAgent`, with the same params. Build them per run
280
+ * to close over live objects (a store, a session) that cannot go in context.
281
+ */
282
+ actions?: ProvidedActions<TMachine>;
275
283
  /**
276
284
  * Sugar over {@link onTrace}'s `stream.chunk` events: fires for each streamed
277
285
  * chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest}
@@ -655,13 +663,6 @@ interface AgentRunInit<TMachine extends AnyStateMachine> extends AgentRunStart<T
655
663
  */
656
664
  attempts?: DecisionAttempt[];
657
665
  }
658
- /**
659
- * The blocking host: opens the run, delivers `event` if given, then applies
660
- * every event that arrives until the run is quiescent, and returns the
661
- * outcome. A request handler or durable engine writes the same loop with its
662
- * own stop policy; this one is for scripts and tests.
663
- */
664
- declare function runToQuiescence<TMachine extends AnyStateMachine>(runtime: AgentRuntime<TMachine>, init?: AgentRunInit<TMachine>): Promise<AgentRunResult<TMachine>>;
665
666
  /** Everything {@link runAgent} takes: the runtime's options plus how to open the run. */
666
667
  interface AgentRunOptions<TMachine extends AnyStateMachine> extends AgentRuntimeOptions<TMachine>, AgentRunInit<TMachine> {
667
668
  /**
@@ -691,7 +692,10 @@ interface AgentRunOptions<TMachine extends AnyStateMachine> extends AgentRuntime
691
692
  * {@link AgentRuntime.send}; one sent before the run starts is delivered
692
693
  * after the opening `event`. An inbox event that arrives while the run is
693
694
  * idle resumes it, ahead of a pending `onIdle` answer (that answer is then
694
- * dropped). One inbox serves one `runAgent` call.
695
+ * dropped). Without `onIdle`, the run returns at the first idle state
696
+ * (an event that lands while that pass is finishing still resumes it), and
697
+ * a `send` after `runAgent` returns gets `false`: a pause that waits for a
698
+ * resume needs `onIdle` as well. One inbox serves one `runAgent` call.
695
699
  */
696
700
  inbox?: AgentInbox<EventFromLogic<TMachine>>;
697
701
  }
@@ -779,26 +783,6 @@ declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, o
779
783
  * `createOpenAiExecutors` from '@statelyai/agent/openai' supply all three.
780
784
  */
781
785
  declare function createAgentRuntime<TMachine extends AnyStateMachine>(machine: TMachine, options?: AgentRuntimeOptions<TMachine>): AgentRuntime<TMachine>;
782
- /**
783
- * The actor handed to an {@link inspectTransitions} handler: an
784
- * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
785
- * transition to the root machine or a specific invoked child (xstate's static
786
- * `ActorRef` type omits them, but they are always present at runtime).
787
- */
788
- type InspectedActorRef = AnyActorRef & {
789
- id: string;
790
- src?: string | AnyActorLogic;
791
- };
792
- /**
793
- * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
794
- * {@link AgentRuntimeOptions.inspect}: it filters the raw inspection stream to
795
- * `@xstate.transition` events and hands the handler the typed
796
- * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
797
- * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
798
- * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
799
- * actorRef casts.
800
- */
801
- declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
802
786
  /**
803
787
  * An xstate `inspect` handler that emits `machine.transition` trace events onto
804
788
  * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
@@ -835,4 +819,4 @@ declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMac
835
819
  */
836
820
  declare function isAgentIdle(snapshot: AnyMachineSnapshot): boolean;
837
821
  //#endregion
838
- export { AgentStepRequest as A, inspectTransitions as C, serializeTraceEvent as D, runToQuiescence as E, traceTransitions as O, createAgentRuntime as S, runAgent as T, AgentTraceEvent as _, AgentMaxModelCallsExceededError as a, JsonSerializableTraceEvent as b, AgentRunMeta as c, AgentRunStart as d, AgentRuntime as f, AgentTimerScheduler as g, AgentTimerEvent as h, AgentInputFrom as i, AgentRequest as k, AgentRunOptions as l, AgentSnapshotDivergedError as m, AgentEffects as n, AgentRunErrorCause as o, AgentRuntimeOptions as p, AgentInbox as r, AgentRunInit as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentRunResult as u, AgentTransitionHandler as v, isAgentIdle as w, createAgentInbox as x, InspectedActorRef as y };
822
+ export { runAgent as C, AgentStepRequest as D, AgentRequest as E, isAgentIdle as S, traceTransitions as T, AgentTraceEvent as _, AgentMaxModelCallsExceededError as a, createAgentInbox as b, AgentRunMeta as c, AgentRunStart as d, AgentRuntime as f, AgentTimerScheduler as g, AgentTimerEvent as h, AgentInputFrom as i, AgentRunOptions as l, AgentSnapshotDivergedError as m, AgentEffects as n, AgentRunErrorCause as o, AgentRuntimeOptions as p, AgentInbox as r, AgentRunInit as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentRunResult as u, AgentTransitionHandler as v, serializeTraceEvent as w, createAgentRuntime as x, JsonSerializableTraceEvent as y };