@statelyai/agent 2.0.0-alpha.35 → 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 (130) hide show
  1. package/CHANGELOG.md +138 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-Ct_GZw_f.mjs → effects-BT_cSY0j.mjs} +1003 -109
  13. package/dist/{run-agent-s5D32w99.cjs → effects-DDseYtJk.cjs} +1037 -107
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-30mH2moE.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-DlPzBWj-.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BaNyz6Q3.d.cts} +4 -4
  46. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-C1CG_nfX.d.mts} +4 -4
  47. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +2493 -1502
  53. package/dist/testing.d.cts +360 -256
  54. package/dist/testing.d.mts +360 -256
  55. package/dist/testing.mjs +2489 -1503
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-Bm5nvpow.d.cts} +6 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-BnikdOca.d.mts} +6 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-ChyX6jq0.mjs +2306 -0
  69. package/dist/verify-CwlombbC.cjs +2359 -0
  70. package/dist/{verify-BQpE8hUz.d.cts → verify-DJHfEfm6.d.cts} +213 -14
  71. package/dist/{verify-CqeuEmIk.d.mts → verify-i9Hiwc5g.d.mts} +213 -14
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +312 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +207 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +56 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +518 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +492 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +84 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -192
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
@@ -1,8 +1,328 @@
1
- const require_event_log = require("./event-log-BWSSLUff.cjs");
2
- const require_decision = require("./decision-BEsATcr1.cjs");
3
- const require_event_log_store = require("./event-log-store-CleWpsp5.cjs");
1
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
3
+ const require_act = require("./act-CrX0JwWY.cjs");
4
+ const require_event_log_store = require("./event-log-store-Cl-YWDnq.cjs");
4
5
  let xstate = require("xstate");
5
6
  let xstate_durable = require("xstate/durable");
7
+ //#region src/decide-next.ts
8
+ /**
9
+ * Asks a model to choose the next event for ANY XState snapshot, including a
10
+ * machine built with plain `createMachine`/`setup` that knows nothing about AI.
11
+ * The candidates are the `allowedEvents` an active state handles, one option per
12
+ * payload, kept only where `snapshot.can(event)` is true and no transition
13
+ * tagged `meta: { actor: "human" }` handles the type; the rest come back as
14
+ * `withheld`. Each option is
15
+ * described from the transition's `description`, else the event schema's,
16
+ * plus (with `lookahead`) what it changes. The chosen event must equal one
17
+ * offered option; anything else is retried.
18
+ *
19
+ * It never sends. The host sends the event, re-checking `can` first, because
20
+ * the actor may have moved while the model was thinking. With no options it
21
+ * returns `{ event: null }` without calling the executor. Exhausting retries
22
+ * throws `AgentDecisionExhaustedError`.
23
+ *
24
+ * @example
25
+ * ```ts no-check
26
+ * let busy = false;
27
+ * actor.subscribe(async (snapshot) => {
28
+ * if (busy || !snapshot.matches('reviewing')) return;
29
+ * busy = true;
30
+ * try {
31
+ * const { event } = await decideNext(snapshot, {
32
+ * decide,
33
+ * model: 'quick',
34
+ * allowedEvents: 'desk.*',
35
+ * payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
36
+ * lookahead: true,
37
+ * });
38
+ * if (event && actor.getSnapshot().can(event)) actor.send(event);
39
+ * } finally {
40
+ * busy = false;
41
+ * }
42
+ * });
43
+ * ```
44
+ */
45
+ async function decideNext(snapshot, options) {
46
+ const patterns = typeof options.allowedEvents === "string" ? [options.allowedEvents] : options.allowedEvents;
47
+ const schemas = snapshot.machine.schemas?.events;
48
+ const candidates = require_decision.getAcceptedEvents(snapshot, {
49
+ events: schemas,
50
+ eventTypes: patterns
51
+ }).filter((event) => !require_decision.isEventPattern(event.type));
52
+ const humanEventTypes = require_decision.getHumanEventTypes(snapshot);
53
+ const events = candidates.filter((event) => !humanEventTypes.has(event.type));
54
+ const payloads = options.payloads?.(snapshot) ?? {};
55
+ const accepted = [];
56
+ const withheld = [];
57
+ for (const { type } of candidates) for (const payload of payloads[type] ?? [{}]) {
58
+ const event = {
59
+ ...payload,
60
+ type
61
+ };
62
+ (!humanEventTypes.has(type) && safeCan(snapshot, event) ? accepted : withheld).push(event);
63
+ }
64
+ const offered = accepted.map((event) => ({
65
+ event,
66
+ description: describeOption(snapshot, event, schemas?.[event.type], options.lookahead)
67
+ }));
68
+ const request = require_decision.createDecisionRequest({
69
+ name: options.name ?? "decideNext",
70
+ model: options.model,
71
+ system: options.system,
72
+ prompt: options.prompt,
73
+ input: {
74
+ value: snapshot.value,
75
+ context: snapshot.context
76
+ },
77
+ events,
78
+ options: offered,
79
+ withheld,
80
+ ...options.strategy !== void 0 ? { strategy: options.strategy } : {},
81
+ ...options.fillModel !== void 0 ? { fillModel: options.fillModel } : {},
82
+ ...options.groups !== void 0 ? { groups: options.groups } : {}
83
+ });
84
+ if (offered.length === 0) return {
85
+ event: null,
86
+ attempts: [],
87
+ request,
88
+ withheld
89
+ };
90
+ let attempts = [];
91
+ return {
92
+ event: await require_decision.resolveDecision(request, {
93
+ decide: (attemptRequest, info) => {
94
+ attempts = attemptRequest.attempts;
95
+ return options.decide(attemptRequest, info);
96
+ },
97
+ ...options.generateText ? { generateText: options.generateText } : {}
98
+ }, {
99
+ maxRetries: options.maxRetries,
100
+ signal: options.signal,
101
+ canTake: (chosen) => safeCan(snapshot, chosen)
102
+ }),
103
+ attempts,
104
+ request,
105
+ withheld
106
+ };
107
+ }
108
+ function safeCan(snapshot, event) {
109
+ try {
110
+ return snapshot.can(event);
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+ function describeOption(snapshot, event, schema, lookahead) {
116
+ const what = (0, xstate.getNextTransitions)(snapshot).find((candidate) => candidate.eventType === event.type && candidate.description)?.description ?? schemaDescription(schema) ?? event.type;
117
+ const fields = Object.entries(event).filter(([key]) => key !== "type").map(([key, value]) => `${key}: ${short(value)}`);
118
+ const base = fields.length ? `${what} (${fields.join("; ")})` : what;
119
+ const effect = lookahead ? describeEffect(snapshot, event, lookahead === true ? void 0 : lookahead) : void 0;
120
+ return effect ? `${base}. Then: ${effect}` : base;
121
+ }
122
+ function schemaDescription(schema) {
123
+ if (!schema) return void 0;
124
+ const direct = schema.description;
125
+ if (typeof direct === "string") return direct;
126
+ try {
127
+ const json = schema["~standard"].jsonSchema?.input?.({ target: "draft-2020-12" });
128
+ return require_event_log.isRecord(json) && typeof json.description === "string" ? json.description : void 0;
129
+ } catch {
130
+ return;
131
+ }
132
+ }
133
+ function describeEffect(snapshot, event, keys) {
134
+ let next;
135
+ try {
136
+ [next] = (0, xstate.transition)(snapshot.machine, snapshot, event);
137
+ } catch {
138
+ return;
139
+ }
140
+ const changes = snapshotChanges(snapshot, next, keys).map(({ key, before, after }) => `${key}: ${short(before, EFFECT_MAX_LENGTH)} → ${short(after, EFFECT_MAX_LENGTH)}`);
141
+ return changes.length ? changes.join("; ") : "nothing changes";
142
+ }
143
+ const EFFECT_MAX_LENGTH = 120;
144
+ function snapshotChanges(before, after, keys) {
145
+ const changes = [];
146
+ if (require_event_log.canonicalEventJson(before.value) !== require_event_log.canonicalEventJson(after.value)) changes.push({
147
+ key: "state",
148
+ before: before.value,
149
+ after: after.value,
150
+ isState: true
151
+ });
152
+ const from = require_event_log.isRecord(before.context) ? before.context : {};
153
+ const to = require_event_log.isRecord(after.context) ? after.context : {};
154
+ for (const key of keys ?? /* @__PURE__ */ new Set([...Object.keys(from), ...Object.keys(to)])) if (require_event_log.canonicalEventJson(from[key]) !== require_event_log.canonicalEventJson(to[key])) changes.push({
155
+ key,
156
+ before: from[key],
157
+ after: to[key]
158
+ });
159
+ return changes;
160
+ }
161
+ /**
162
+ * What one delivered event did, as a model reads it: the new state value when
163
+ * it moved, and each changed top-level context key's new value. A value whose
164
+ * JSON exceeds 120 characters is cut to a string. @internal
165
+ */
166
+ function describeSnapshotDelta(before, after) {
167
+ const delta = {};
168
+ for (const change of snapshotChanges(before, after)) {
169
+ const value = short(change.after, Infinity).length > EFFECT_MAX_LENGTH ? short(change.after, EFFECT_MAX_LENGTH) : change.after;
170
+ if (change.isState) delta.state = value;
171
+ else (delta.changed ??= {})[change.key] = value;
172
+ }
173
+ return delta;
174
+ }
175
+ function short(value, max = 60) {
176
+ let text;
177
+ try {
178
+ text = value === void 0 ? "(none)" : JSON.stringify(value) ?? String(value);
179
+ } catch {
180
+ text = String(value);
181
+ }
182
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
183
+ }
184
+ //#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 (require_event_log.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 = require_event_log.isRecord(persisted) ? persisted["children"] : void 0;
202
+ if (!require_event_log.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(require_event_log.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 (!require_event_log.isRecord(snapshot) || !require_event_log.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 (!require_event_log.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" && require_event_log.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 = require_event_log.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" && require_event_log.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) => require_event_log.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
6
326
  //#region src/run-agent.ts
7
327
  /**
8
328
  * Thrown by {@link AgentRuntime.start} when a resume is given BOTH an `events` log and a
@@ -64,9 +384,9 @@ const TRACE_ENVELOPE_KEYS = [
64
384
  * become `null`), non-finite numbers become `null`, `bigint`s become strings,
65
385
  * `Error`s become `{ name, message, stack?, code? }`, and anything with a
66
386
  * `toJSON()` (e.g. `Date`) is projected through it — the same losses a
67
- * `JSON.parse(JSON.stringify(...))` round-trip incurs, minus the throws.
387
+ * `JSON.parse(JSON.stringify(...))` round-trip incurs, minus the throws. @internal
68
388
  */
69
- function toJsonValue(value, ancestors) {
389
+ function toJsonValue(value, ancestors = []) {
70
390
  if (value === null) return null;
71
391
  const type = typeof value;
72
392
  if (type === "string" || type === "boolean") return value;
@@ -238,6 +558,11 @@ function assertMachineBindable(machine, effectiveSources, executors, ctx) {
238
558
  assertChildMachineBindable(logic, src, stateName, executors, ctx);
239
559
  continue;
240
560
  }
561
+ if (require_act.isActLogic(logic)) {
562
+ if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "text");
563
+ if (!executors.generateText) throw new Error(`createAgentRuntime: ${where} '${stateName}' invokes '${src}' but no 'generateText' executor was provided to createAgentRuntime(...).`);
564
+ continue;
565
+ }
241
566
  if (require_decision.isDecisionLogic(logic)) {
242
567
  if (require_event_log.executorBoundLogics.has(logic)) continue;
243
568
  if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "decision");
@@ -376,85 +701,203 @@ function invokingActorOf(self, runCtx) {
376
701
  * identical event shapes by construction. @internal
377
702
  */
378
703
  function bindTextLogic(logic, runCtx) {
379
- return logic.withExecutor(async ({ request: rawRequest, self: selfArg, signal }) => {
704
+ return logic.withExecutor(({ request: rawRequest, self: selfArg, signal }) => {
380
705
  const self = selfArg;
381
706
  const { id, src } = selfIdAndSrc(self);
382
707
  const request = {
383
708
  ...rawRequest,
384
709
  name: rawRequest.name ?? (src !== "" && src !== "agent.generateText" && src !== "agent.streamText" ? src : id || src)
385
710
  };
386
- const executor = logic.mode === "stream" ? runCtx.streamText : runCtx.generateText;
387
- if (!executor) throw new Error(`No '${logic.mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
388
- const requestWithTools = {
389
- ...request,
390
- tools: request.tools ?? {}
391
- };
392
- const agentRequest = {
711
+ return runTextRequest(runCtx, logic.mode, request, self, signal);
712
+ });
713
+ }
714
+ /**
715
+ * Runs one text/stream request through `runCtx`'s executor with the run's
716
+ * accounting: budgeted, traced (`request.start`/`stream.chunk`/`request.end`/
717
+ * `request.error`), call-keyed, usage-recorded. Shared by text requests and
718
+ * `agent.act`. @internal
719
+ */
720
+ async function runTextRequest(runCtx, mode, request, self, signal) {
721
+ const { id, src } = selfIdAndSrc(self);
722
+ const executor = mode === "stream" ? runCtx.streamText : runCtx.generateText;
723
+ if (!executor) throw new Error(`No '${mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
724
+ const requestWithTools = {
725
+ ...request,
726
+ tools: request.tools ?? {}
727
+ };
728
+ const agentRequest = {
729
+ kind: "text",
730
+ id,
731
+ src,
732
+ mode,
733
+ input: request,
734
+ tools: requestWithTools.tools,
735
+ events: []
736
+ };
737
+ runCtx.consumeModelCall();
738
+ runCtx.emitTrace?.({
739
+ type: "request.start",
740
+ request: agentRequest
741
+ }, self);
742
+ try {
743
+ const callKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
744
+ await runCtx.awaitJournal?.();
745
+ signal.throwIfAborted();
746
+ const raw = await executor(requestWithTools, {
747
+ onChunk: (chunk) => {
748
+ runCtx.emitTrace?.({
749
+ type: "stream.chunk",
750
+ request: agentRequest,
751
+ chunk
752
+ }, self);
753
+ },
754
+ signal,
755
+ ...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
756
+ ...id !== "" ? { requestId: id } : {},
757
+ ...callKey !== void 0 ? { callKey } : {}
758
+ });
759
+ const output = await require_event_log.normalizeGeneratorResult(raw, id);
760
+ const rawReasoning = raw?.reasoning;
761
+ const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
762
+ runCtx.countModelCalls?.(require_event_log.getCallModelCalls(raw) - 1);
763
+ const usage = require_event_log.getCallUsage(raw);
764
+ const finishReason = require_event_log.getCallFinishReason(raw);
765
+ if (usage) runCtx.recordUsage?.(usage, {
393
766
  kind: "text",
394
- id,
395
- src,
396
- mode: logic.mode,
397
- input: request,
398
- tools: requestWithTools.tools,
399
- events: []
767
+ ...id !== "" ? { id } : {},
768
+ ...src !== "" ? { src } : {},
769
+ model: request.model,
770
+ ...request.name !== void 0 ? { name: request.name } : {},
771
+ ...callKey !== void 0 ? { callKey } : {}
772
+ }, self);
773
+ runCtx.emitTrace?.({
774
+ type: "request.end",
775
+ request: agentRequest,
776
+ output,
777
+ raw,
778
+ ...reasoning !== void 0 ? { reasoning } : {},
779
+ ...usage !== void 0 ? { usage } : {},
780
+ ...finishReason !== void 0 ? { finishReason } : {}
781
+ }, self);
782
+ return {
783
+ result: output,
784
+ messages: require_event_log.responseMessagesOf(raw)
400
785
  };
401
- runCtx.consumeModelCall();
786
+ } catch (error) {
787
+ runCtx.countModelCalls?.(require_event_log.getCallModelCalls(error) - 1);
402
788
  runCtx.emitTrace?.({
403
- type: "request.start",
404
- request: agentRequest
789
+ type: "request.error",
790
+ request: agentRequest,
791
+ error
405
792
  }, self);
406
- try {
407
- const callKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
408
- await runCtx.awaitJournal?.();
409
- const raw = await executor(requestWithTools, {
410
- onChunk: (chunk) => {
411
- runCtx.emitTrace?.({
412
- type: "stream.chunk",
413
- request: agentRequest,
414
- chunk
415
- }, self);
416
- },
417
- signal,
418
- ...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
419
- ...id !== "" ? { requestId: id } : {},
420
- ...callKey !== void 0 ? { callKey } : {}
421
- });
422
- const output = await require_event_log.normalizeGeneratorResult(raw, id);
423
- const rawReasoning = raw?.reasoning;
424
- const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
425
- runCtx.countModelCalls?.(require_event_log.getCallModelCalls(raw) - 1);
426
- const usage = require_event_log.getCallUsage(raw);
427
- const finishReason = require_event_log.getCallFinishReason(raw);
428
- if (usage) runCtx.recordUsage?.(usage, {
429
- kind: "text",
430
- ...id !== "" ? { id } : {},
431
- ...src !== "" ? { src } : {},
432
- model: request.model,
433
- ...request.name !== void 0 ? { name: request.name } : {}
434
- }, self);
435
- runCtx.emitTrace?.({
436
- type: "request.end",
437
- request: agentRequest,
438
- output,
439
- raw,
440
- ...reasoning !== void 0 ? { reasoning } : {},
441
- ...usage !== void 0 ? { usage } : {},
442
- ...finishReason !== void 0 ? { finishReason } : {}
443
- }, self);
444
- return {
445
- result: output,
446
- messages: require_event_log.responseMessagesOf(raw)
793
+ throw error;
794
+ }
795
+ }
796
+ /**
797
+ * Builds the actor logic the runtime installs in place of the `agent.act`
798
+ * builtin: ONE `generateText` call (the host's tool loop, `maxSteps` default
799
+ * 20) whose tools are the invoking state's accepted, non-human events plus the
800
+ * input's plain `tools`. Each event tool call, in call order:
801
+ *
802
+ * 1. validates its payload against the event schema (error result on failure);
803
+ * 2. answers "not allowed" when the live snapshot cannot take the event;
804
+ * 3. otherwise sends it to the invoking actor (journaled like any delivered
805
+ * event), waits for it to commit, and answers with the delta
806
+ * `{ state?, changed? }` it caused.
807
+ *
808
+ * Once the invoking state exits (the invoke's `signal` aborts), every later
809
+ * call answers {@link ACT_STATE_EXITED} and the executor's signal aborts, so
810
+ * the loop stops. Completes with the final text when the state is still active.
811
+ *
812
+ * Not resumable mid-loop: a crash during the tool loop replays the events it
813
+ * already delivered from the journal, but the act invoke itself restarts from
814
+ * scratch (a fresh model call) if its state is still active.
815
+ */
816
+ function bindActLogic(runCtx) {
817
+ const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal, self: selfArg }) => {
818
+ const self = selfArg;
819
+ const { id, src } = selfIdAndSrc(self);
820
+ await Promise.resolve();
821
+ const actorRef = invokingActorOf(self, runCtx);
822
+ if (!actorRef) throw new Error(`'${require_event_log.ACT_ACTOR}' needs the invoking actor's snapshot.`);
823
+ const awaitDelivery = !isChildRequest(self) && actorRef === runCtx.actorHolder.actorRef ? runCtx.awaitDelivery : void 0;
824
+ const snapshot = actorRef.getSnapshot();
825
+ const events = require_decision.getAcceptedEvents(snapshot, {
826
+ schemas: runCtx.schemas,
827
+ eventTypes: require_decision.resolveAllowedEventTypes(input.allowedEvents, input),
828
+ actor: "agent"
829
+ });
830
+ const loop = new AbortController();
831
+ const exited = () => signal.aborted || loop.signal.aborted;
832
+ if (signal.aborted) loop.abort(signal.reason);
833
+ else signal.addEventListener("abort", () => loop.abort(signal.reason), { once: true });
834
+ const callEvent = async (type, schema, args) => {
835
+ if (exited()) return require_act.ACT_STATE_EXITED;
836
+ let payload = require_event_log.isPlainObject(args) ? { ...args } : {};
837
+ delete payload.type;
838
+ if (schema) try {
839
+ payload = require_event_log.validateSchemaSync(schema, payload);
840
+ } catch (error) {
841
+ return `'${type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`;
842
+ }
843
+ const event = {
844
+ ...payload,
845
+ type
447
846
  };
847
+ const before = actorRef.getSnapshot();
848
+ let accepted;
849
+ try {
850
+ accepted = !require_decision.getHumanEventTypes(before).has(type) && before.can(event);
851
+ } catch {
852
+ accepted = false;
853
+ }
854
+ if (!accepted) return `'${type}' is not allowed in state ${JSON.stringify(before.value)}`;
855
+ const delivered = awaitDelivery?.(event);
856
+ actorRef.send(event);
857
+ await delivered;
858
+ await Promise.resolve();
859
+ const delta = describeSnapshotDelta(before, actorRef.getSnapshot());
860
+ if (signal.aborted) loop.abort(signal.reason);
861
+ return delta;
862
+ };
863
+ let queue = Promise.resolve();
864
+ const serialized = (run) => (args) => {
865
+ const result = queue.then(() => run(args));
866
+ queue = result.catch(() => {});
867
+ return result;
868
+ };
869
+ const tools = { ...input.tools };
870
+ for (const descriptor of events) tools[descriptor.toolName] = {
871
+ description: `Send '${descriptor.type}'. Answers with what it changed.`,
872
+ ...descriptor.inputSchema ? { inputSchema: descriptor.inputSchema } : {},
873
+ execute: serialized((args) => callEvent(descriptor.type, descriptor.inputSchema, args))
874
+ };
875
+ const request = {
876
+ name: input.name ?? (id || src),
877
+ input,
878
+ model: input.model,
879
+ system: input.system,
880
+ prompt: input.prompt,
881
+ messages: input.messages,
882
+ tools,
883
+ maxSteps: input.maxSteps ?? 20,
884
+ temperature: input.temperature,
885
+ maxOutputTokens: input.maxOutputTokens,
886
+ topP: input.topP,
887
+ topK: input.topK,
888
+ seed: input.seed,
889
+ stopSequences: input.stopSequences,
890
+ metadata: input.metadata
891
+ };
892
+ try {
893
+ const { result } = await runTextRequest(runCtx, "generate", request, self, loop.signal);
894
+ return result;
448
895
  } catch (error) {
449
- runCtx.countModelCalls?.(require_event_log.getCallModelCalls(error) - 1);
450
- runCtx.emitTrace?.({
451
- type: "request.error",
452
- request: agentRequest,
453
- error
454
- }, self);
896
+ if (exited()) return void 0;
455
897
  throw error;
456
898
  }
457
- });
899
+ } });
900
+ return Object.assign(logic, { kind: "statelyai.actLogic" });
458
901
  }
459
902
  function createCountingDecide(runCtx, self, recordLater) {
460
903
  return async (attemptRequest, info) => {
@@ -468,6 +911,7 @@ function createCountingDecide(runCtx, self, recordLater) {
468
911
  const invokeCallKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
469
912
  const callKey = invokeCallKey === void 0 ? void 0 : `${invokeCallKey}.${attemptRequest.attempts?.length ?? 0}`;
470
913
  await runCtx.awaitJournal?.();
914
+ info?.signal?.throwIfAborted();
471
915
  const result = await runCtx.decide(runCtx.runId !== void 0 ? {
472
916
  ...attemptRequest,
473
917
  runId: runCtx.runId
@@ -485,7 +929,8 @@ function createCountingDecide(runCtx, self, recordLater) {
485
929
  kind: "decision",
486
930
  ...attemptRequest.id ? { id: attemptRequest.id } : {},
487
931
  ...src !== "" ? { src } : {},
488
- model: attemptRequest.model
932
+ model: attemptRequest.model,
933
+ ...callKey !== void 0 ? { callKey } : {}
489
934
  }, self));
490
935
  }
491
936
  runCtx.emitTrace?.({
@@ -507,6 +952,61 @@ function createCountingDecide(runCtx, self, recordLater) {
507
952
  }
508
953
  };
509
954
  }
955
+ function createCountingFill(runCtx, self, recordLater) {
956
+ return async (request, info) => {
957
+ const { id, src } = selfIdAndSrc(self);
958
+ const agentRequest = {
959
+ kind: "text",
960
+ id,
961
+ src,
962
+ mode: "generate",
963
+ input: request,
964
+ tools: request.tools,
965
+ events: []
966
+ };
967
+ runCtx.consumeModelCall();
968
+ runCtx.emitTrace?.({
969
+ type: "request.start",
970
+ request: agentRequest
971
+ }, self);
972
+ try {
973
+ await runCtx.awaitJournal?.();
974
+ info?.signal?.throwIfAborted();
975
+ const raw = await runCtx.generateText(request, {
976
+ ...info,
977
+ ...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
978
+ ...info?.requestId === void 0 && id !== "" ? { requestId: id } : {}
979
+ });
980
+ runCtx.countModelCalls?.(require_event_log.getCallModelCalls(raw) - 1);
981
+ const usage = require_event_log.getCallUsage(raw);
982
+ const finishReason = require_event_log.getCallFinishReason(raw);
983
+ if (usage) recordLater(() => runCtx.recordUsage?.(usage, {
984
+ kind: "decision",
985
+ ...id !== "" ? { id } : {},
986
+ ...src !== "" ? { src } : {},
987
+ model: request.model,
988
+ ...info?.callKey !== void 0 ? { callKey: info.callKey } : {}
989
+ }, self));
990
+ runCtx.emitTrace?.({
991
+ type: "request.end",
992
+ request: agentRequest,
993
+ output: raw.result,
994
+ raw,
995
+ ...usage !== void 0 ? { usage } : {},
996
+ ...finishReason !== void 0 ? { finishReason } : {}
997
+ }, self);
998
+ return raw;
999
+ } catch (error) {
1000
+ runCtx.countModelCalls?.(require_event_log.getCallModelCalls(error) - 1);
1001
+ runCtx.emitTrace?.({
1002
+ type: "request.error",
1003
+ request: agentRequest,
1004
+ error
1005
+ }, self);
1006
+ throw error;
1007
+ }
1008
+ };
1009
+ }
510
1010
  /**
511
1011
  * Builds the decision actor logic the runtime installs in place of a
512
1012
  * `DecisionLogic`/`agent.decide` source. `DecisionLogic.withExecutor(...)`
@@ -581,20 +1081,26 @@ function bindDecisionLogic(logic, runCtx) {
581
1081
  throw error;
582
1082
  }
583
1083
  const usageRecords = [];
584
- const decide = createCountingDecide(runCtx, self, (record) => usageRecords.push(record));
1084
+ const recordLater = (record) => usageRecords.push(record);
1085
+ const decide = createCountingDecide(runCtx, self, recordLater);
1086
+ const generateText = runCtx.generateText ? createCountingFill(runCtx, self, recordLater) : void 0;
1087
+ const invokeCallKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
585
1088
  let priorAttempts = [];
586
1089
  let chosen;
587
1090
  try {
588
- chosen = await require_decision.resolveDecision(request, { decide: (attemptRequest, info) => {
589
- priorAttempts = attemptRequest.attempts;
590
- return decide(attemptRequest, info);
591
- } }, {
1091
+ chosen = await require_decision.resolveDecision(request, {
1092
+ decide: (attemptRequest, info) => {
1093
+ priorAttempts = attemptRequest.attempts;
1094
+ return decide(attemptRequest, info);
1095
+ },
1096
+ ...generateText ? { generateText } : {}
1097
+ }, {
1098
+ ...invokeCallKey !== void 0 ? { callKey: invokeCallKey } : {},
592
1099
  maxRetries: lowered.maxRetries ?? logic.maxRetries,
593
1100
  signal,
594
1101
  canTake: agentCan
595
1102
  });
596
- const callKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
597
- runCtx.noteDecision?.(chosen, priorAttempts, callKey === void 0 ? void 0 : callKey.slice(callKey.indexOf(":") + 1));
1103
+ runCtx.noteDecision?.(chosen, priorAttempts, invokeCallKey === void 0 ? void 0 : invokeCallKey.slice(invokeCallKey.indexOf(":") + 1));
598
1104
  actorRef?.send(chosen);
599
1105
  } finally {
600
1106
  for (const record of usageRecords) record();
@@ -637,7 +1143,7 @@ function rootTraceState(root) {
637
1143
  let state = rootTraceRegistry.get(root);
638
1144
  if (!state) {
639
1145
  const logic = root.logic;
640
- const machineId = (logic?.config)?.id ?? logic?.id ?? "(machine)";
1146
+ const machineId = (logic?.config)?.id ?? logic?.id ?? "";
641
1147
  const machineVersion = logic ? require_event_log.resolveMachineVersion(logic) : "";
642
1148
  state = {
643
1149
  runId: `run_${nextProvideRunId++}`,
@@ -756,6 +1262,13 @@ function bindDecisionForProvide(machine, logic, executors, options) {
756
1262
  return bindDecisionLogic(logic, provideBindContext(machine, executors, options));
757
1263
  }
758
1264
  /**
1265
+ * Host-binds the `agent.act` builtin for {@link provideExecutors}: the
1266
+ * runtime's act wrapper with the same request-level tracing. @internal
1267
+ */
1268
+ function bindActForProvide(machine, executors, options) {
1269
+ return bindActLogic(provideBindContext(machine, executors, options));
1270
+ }
1271
+ /**
759
1272
  * Recursively binds an invoked child state machine for {@link provideExecutors},
760
1273
  * with the same semantics `createAgentRuntime` applies ({@link rebindChildMachine}):
761
1274
  * string-keyed text/decision sources at any depth inherit the host executors,
@@ -809,6 +1322,10 @@ function rebindChildMachine(childMachine, runCtx, visited, ctxFor) {
809
1322
  const sources = childMachine.sources.actors;
810
1323
  const wrapped = {};
811
1324
  for (const [key, logic] of Object.entries(sources)) {
1325
+ if (require_act.isActLogic(logic)) {
1326
+ wrapped[key] = bindActLogic(runCtx);
1327
+ continue;
1328
+ }
812
1329
  if (require_decision.isDecisionLogic(logic)) {
813
1330
  if (!require_event_log.executorBoundLogics.has(logic)) wrapped[key] = bindDecisionLogic(logic, runCtx);
814
1331
  continue;
@@ -822,6 +1339,7 @@ function rebindChildMachine(childMachine, runCtx, visited, ctxFor) {
822
1339
  if (rebound !== logic) wrapped[key] = rebound;
823
1340
  continue;
824
1341
  }
1342
+ if (runCtx.pendingJournal && typeof logic?.transition === "function") wrapped[key] = journalGatedLogic(logic, runCtx.pendingJournal);
825
1343
  }
826
1344
  const rebound = Object.keys(wrapped).length > 0 ? childMachine.provide({ actors: wrapped }) : childMachine;
827
1345
  return runCtx.onChildEvent ? journaledMachine(rebound, runCtx.onChildEvent) : rebound;
@@ -838,6 +1356,39 @@ function journaledMachine(machine, onEvent) {
838
1356
  return machine.transition(...args);
839
1357
  } } });
840
1358
  }
1359
+ /**
1360
+ * `logic`, with the side effects it starts (`@xstate.effect`: an async
1361
+ * actor's run, a callback's body) held until `pending` resolves. A child
1362
+ * machine runs live, so without this a plain actor it starts could do its
1363
+ * work (or the process could die) before the child's earlier entries are
1364
+ * durable, and a resume would run the earlier actor again.
1365
+ */
1366
+ function journalGatedLogic(logic, pending) {
1367
+ const gate = (result, self) => {
1368
+ const [snapshot, effects] = result;
1369
+ if (!Array.isArray(effects) || !effects.some((e) => e?.type === "@xstate.effect")) return result;
1370
+ const finishing = snapshot?.status === "done";
1371
+ return [snapshot, effects.map((effect) => {
1372
+ if (effect?.type !== "@xstate.effect") return effect;
1373
+ const exec = effect.exec;
1374
+ const gated = (...args) => {
1375
+ const waiting = pending();
1376
+ if (waiting === void 0) return exec(...args);
1377
+ waiting.then((ok) => {
1378
+ if (ok && (finishing || self.getSnapshot().status === "active")) exec(...args);
1379
+ });
1380
+ };
1381
+ return {
1382
+ ...effect,
1383
+ exec: gated,
1384
+ action: gated
1385
+ };
1386
+ })];
1387
+ };
1388
+ const overrides = { transition: { value: (...args) => gate(logic.transition(...args), args[2].self) } };
1389
+ if (typeof logic.initialTransition === "function") overrides["initialTransition"] = { value: (...args) => gate(logic.initialTransition(...args), args[1].self) };
1390
+ return Object.create(logic, overrides);
1391
+ }
841
1392
  const timerId = (timer) => JSON.stringify(timer);
842
1393
  function toTimerInput(event) {
843
1394
  const id = event.id;
@@ -866,6 +1417,133 @@ async function runToQuiescence(runtime, init = {}) {
866
1417
  }
867
1418
  return runtime.finish();
868
1419
  }
1420
+ const inboxStates = /* @__PURE__ */ new WeakMap();
1421
+ /**
1422
+ * Creates a send handle for {@link AgentRunOptions.inbox}, typed by the
1423
+ * machine's events.
1424
+ *
1425
+ * @example
1426
+ * ```ts
1427
+ * const inbox = createAgentInbox<EventOf<typeof machine>>();
1428
+ * const run = runAgent(machine, { input, executors, inbox });
1429
+ * inbox.send({ type: "CANCEL" });
1430
+ * const result = await run;
1431
+ * ```
1432
+ */
1433
+ function createAgentInbox() {
1434
+ const state = {
1435
+ queue: [],
1436
+ passSent: /* @__PURE__ */ new Set(),
1437
+ claimed: false,
1438
+ closed: false
1439
+ };
1440
+ const inbox = { send(event) {
1441
+ if (state.closed) return false;
1442
+ if (state.runtime) {
1443
+ state.passSent.add(event);
1444
+ const accepted = state.runtime.send(event);
1445
+ if (!accepted) state.closed = true;
1446
+ return accepted;
1447
+ }
1448
+ const waiter = state.waiter;
1449
+ if (waiter) {
1450
+ state.waiter = void 0;
1451
+ waiter(event);
1452
+ } else state.queue.push(event);
1453
+ return true;
1454
+ } };
1455
+ inboxStates.set(inbox, state);
1456
+ return inbox;
1457
+ }
1458
+ function bindInbox(runtime, inbox, openingFromInbox) {
1459
+ if (!inbox) return runtime;
1460
+ inbox.passSent = new Set(openingFromInbox === void 0 ? [] : [openingFromInbox]);
1461
+ for (const event of inbox.queue.splice(0)) {
1462
+ inbox.passSent.add(event);
1463
+ runtime.send(event);
1464
+ }
1465
+ inbox.runtime = runtime;
1466
+ let status;
1467
+ return {
1468
+ start: async (init) => {
1469
+ const [state, effects] = await runtime.start(init);
1470
+ status = state.status;
1471
+ return [state, effects];
1472
+ },
1473
+ transition: (state, event, options) => {
1474
+ const [next, effects] = runtime.transition(state, event, options);
1475
+ status = next.status;
1476
+ return [next, effects];
1477
+ },
1478
+ execute: (effects) => runtime.execute(effects),
1479
+ nextEvent: async () => {
1480
+ const event = await runtime.nextEvent();
1481
+ if (event === void 0) {
1482
+ inbox.runtime = void 0;
1483
+ if (status !== "active") inbox.closed = true;
1484
+ }
1485
+ return event;
1486
+ },
1487
+ send: (event) => runtime.send(event),
1488
+ finish: () => runtime.finish()
1489
+ };
1490
+ }
1491
+ const ABORTED = Symbol("aborted");
1492
+ async function nextIdleEvent(snapshot, onIdle, inbox, signal) {
1493
+ if (signal?.aborted) return ABORTED;
1494
+ const queued = inbox?.queue.shift();
1495
+ if (queued !== void 0) return {
1496
+ event: queued,
1497
+ fromInbox: true
1498
+ };
1499
+ if (!onIdle) return void 0;
1500
+ let onAbort;
1501
+ const aborted = new Promise((resolve) => {
1502
+ onAbort = () => resolve(ABORTED);
1503
+ signal?.addEventListener("abort", onAbort, { once: true });
1504
+ });
1505
+ try {
1506
+ return await waitForIdleAnswer(snapshot, onIdle, inbox, signal, aborted);
1507
+ } finally {
1508
+ signal?.removeEventListener("abort", onAbort);
1509
+ }
1510
+ }
1511
+ async function waitForIdleAnswer(snapshot, onIdle, inbox, signal, aborted) {
1512
+ const answer = () => onIdle(snapshot, { signal });
1513
+ if (!inbox) return Promise.race([aborted, answer().then((event) => ({
1514
+ event,
1515
+ fromInbox: false
1516
+ }))]);
1517
+ let waiter;
1518
+ const sent = new Promise((resolve) => {
1519
+ waiter = (event) => resolve({
1520
+ event,
1521
+ fromInbox: true
1522
+ });
1523
+ inbox.waiter = waiter;
1524
+ });
1525
+ const release = () => {
1526
+ if (inbox.waiter === waiter) inbox.waiter = void 0;
1527
+ };
1528
+ try {
1529
+ return await Promise.race([
1530
+ aborted,
1531
+ sent,
1532
+ answer().then((event) => {
1533
+ release();
1534
+ return {
1535
+ event,
1536
+ fromInbox: false
1537
+ };
1538
+ }, (error) => {
1539
+ release();
1540
+ throw error;
1541
+ })
1542
+ ]);
1543
+ } finally {
1544
+ release();
1545
+ }
1546
+ }
869
1547
  /**
870
1548
  * Runs `machine` to quiescence in one call: {@link createAgentRuntime} over
871
1549
  * `options`, then {@link runToQuiescence} with the same object as its init.
@@ -891,23 +1569,69 @@ async function runToQuiescence(runtime, init = {}) {
891
1569
  * ```
892
1570
  */
893
1571
  async function runAgent(machine, options = {}) {
894
- const { onIdle, ...rest } = options;
895
- let result = await runToQuiescence(createAgentRuntime(machine, rest), rest);
896
- if (!onIdle) return result;
1572
+ const { onIdle, inbox, ...rest } = options;
1573
+ const inboxState = inbox === void 0 ? void 0 : inboxStates.get(inbox);
1574
+ if (inbox !== void 0) {
1575
+ if (inboxState === void 0 || inboxState.claimed) throw new require_event_log.AgentError("inbox-in-use", "runAgent: `inbox` must come from createAgentInbox() and serves one runAgent call.");
1576
+ inboxState.claimed = true;
1577
+ }
1578
+ try {
1579
+ return await runAgentPasses(machine, rest, onIdle, inboxState);
1580
+ } finally {
1581
+ if (inboxState) {
1582
+ inboxState.closed = true;
1583
+ inboxState.runtime = void 0;
1584
+ inboxState.queue.length = 0;
1585
+ }
1586
+ }
1587
+ }
1588
+ async function runAgentPasses(machine, rest, onIdle, inbox) {
1589
+ if (!onIdle && !inbox) return runToQuiescence(bindInbox(createAgentRuntime(machine, rest), inbox), rest);
1590
+ if (rest.inspect !== void 0 && !isStableInspection(rest.inspect)) {
1591
+ const userInspect = rest.inspect;
1592
+ rest = {
1593
+ ...rest,
1594
+ inspect: stableInspection((event) => {
1595
+ if (typeof userInspect === "function") userInspect(event);
1596
+ else userInspect.next?.(event);
1597
+ })
1598
+ };
1599
+ }
1600
+ const endPass = (persisted) => {
1601
+ if (isStableInspection(rest.inspect)) rest.inspect.endPass(persisted);
1602
+ };
1603
+ let result = await runToQuiescence(bindInbox(createAgentRuntime(machine, rest), inbox), rest);
1604
+ endPass(result.persist());
897
1605
  let modelCallsSpent = (rest.modelCallsSpent ?? 0) + result.usage.modelCalls;
898
1606
  const { input: _input, events: _events, attempts: _attempts, ...resumeOptions } = rest;
899
- while (result.status === "idle" && result.ignored === void 0) {
900
- const event = await onIdle(result.snapshot);
901
- result = await runToQuiescence(createAgentRuntime(machine, {
1607
+ let answer = rest.event;
1608
+ while (result.status === "idle" && (result.ignored === void 0 || result.ignored !== answer && inbox?.passSent.has(result.ignored) === true)) {
1609
+ const next = await nextIdleEvent(result.snapshot, onIdle, inbox, rest.signal);
1610
+ if (next === void 0) break;
1611
+ if (next === ABORTED) {
1612
+ result = await runToQuiescence(createAgentRuntime(machine, {
1613
+ ...resumeOptions,
1614
+ modelCallsSpent
1615
+ }), {
1616
+ ...resumeOptions,
1617
+ ...rest.store === void 0 ? { events: result.events } : {},
1618
+ snapshot: result.persist()
1619
+ });
1620
+ break;
1621
+ }
1622
+ const { event, fromInbox } = next;
1623
+ answer = fromInbox ? void 0 : event;
1624
+ result = await runToQuiescence(bindInbox(createAgentRuntime(machine, {
902
1625
  ...resumeOptions,
903
1626
  modelCallsSpent
904
- }), {
1627
+ }), inbox, fromInbox ? event : void 0), {
905
1628
  ...resumeOptions,
906
1629
  ...rest.store === void 0 ? { events: result.events } : {},
907
1630
  snapshot: result.persist(),
908
1631
  event
909
1632
  });
910
1633
  modelCallsSpent += result.usage.modelCalls;
1634
+ endPass(result.persist());
911
1635
  }
912
1636
  return result;
913
1637
  }
@@ -970,7 +1694,7 @@ function createAgentRuntime(machine, options = {}) {
970
1694
  let warnedNonSerializable = false;
971
1695
  const runId = `run_${nextRunAgentTraceId++}`;
972
1696
  let traceSeq = 0;
973
- const machineId = machine.config.id ?? machine.id ?? "(machine)";
1697
+ const machineId = machine.config.id ?? machine.id;
974
1698
  const machineVersion = require_event_log.resolveMachineVersion(machine);
975
1699
  if (options.metadata !== void 0) require_event_log.assertJsonSerializable(options.metadata, "metadata");
976
1700
  const initMetadata = options.metadata === void 0 ? void 0 : structuredClone(options.metadata);
@@ -1008,15 +1732,23 @@ function createAgentRuntime(machine, options = {}) {
1008
1732
  let journalChain = Promise.resolve();
1009
1733
  let journalPending = 0;
1010
1734
  let journalError;
1011
- const journalEntry = (entry) => {
1012
- if (store === void 0) return;
1735
+ let unflushed = [];
1736
+ let flushWaiters = [];
1737
+ let resultOwed = false;
1738
+ const flushJournal = () => {
1739
+ const waiters = flushWaiters;
1740
+ flushWaiters = [];
1741
+ for (const resolve of waiters) resolve();
1742
+ if (store === void 0 || unflushed.length === 0) return;
1743
+ const entries = unflushed;
1744
+ unflushed = [];
1013
1745
  journalPending++;
1014
1746
  journalChain = journalChain.then(async () => {
1015
1747
  if (journalError !== void 0) return;
1016
1748
  await store.append({
1017
1749
  threadId,
1018
- expectedIndex: entry.index,
1019
- entries: [entry]
1750
+ expectedIndex: entries[0].index,
1751
+ entries
1020
1752
  });
1021
1753
  }).catch((error) => {
1022
1754
  journalError ??= error;
@@ -1028,6 +1760,29 @@ function createAgentRuntime(machine, options = {}) {
1028
1760
  journalPending--;
1029
1761
  });
1030
1762
  };
1763
+ const journalEntry = (entry) => {
1764
+ if (store === void 0) return;
1765
+ unflushed.push(entry);
1766
+ if (finished) flushJournal();
1767
+ };
1768
+ /**
1769
+ * Resolves once the entries so far are handed to the store as one settled
1770
+ * step. Mid-step (a transition's effects still running, its children's
1771
+ * replies not yet delivered), a barrier waits for the loop to finish the
1772
+ * step, so it cannot write a child's input without the reply it sends back.
1773
+ * The loop flushes when it next waits; a host that is not reading
1774
+ * `nextEvent` gets the flush on the next task instead.
1775
+ */
1776
+ const stepSettled = () => {
1777
+ if (wake !== void 0 || finished || stopReason !== void 0) {
1778
+ flushJournal();
1779
+ return Promise.resolve();
1780
+ }
1781
+ return new Promise((resolve) => {
1782
+ flushWaiters.push(resolve);
1783
+ setTimeout(flushJournal, 0);
1784
+ });
1785
+ };
1031
1786
  /**
1032
1787
  * Every journal write ISSUED SO FAR, including the stragglers appended after
1033
1788
  * the run settled. Re-reads the chain tail until it stops moving, so a write
@@ -1036,6 +1791,7 @@ function createAgentRuntime(machine, options = {}) {
1036
1791
  */
1037
1792
  const drainJournal = async () => {
1038
1793
  if (store === void 0) return;
1794
+ flushJournal();
1039
1795
  let tail = journalChain;
1040
1796
  for (;;) {
1041
1797
  await tail;
@@ -1046,6 +1802,7 @@ function createAgentRuntime(machine, options = {}) {
1046
1802
  /** The barrier: settle the pending chain, then surface any failure. */
1047
1803
  const awaitJournal = async () => {
1048
1804
  if (store === void 0) return;
1805
+ await stepSettled();
1049
1806
  while (journalPending > 0) await journalChain;
1050
1807
  if (journalError !== void 0) throw journalError;
1051
1808
  };
@@ -1113,7 +1870,7 @@ function createAgentRuntime(machine, options = {}) {
1113
1870
  observe("onEvent", () => options.onEvent?.(entry));
1114
1871
  return entry;
1115
1872
  };
1116
- const recordUsage = (usage, source = {}) => {
1873
+ const recordUsage = (usage, source = {}, self) => {
1117
1874
  const event = {
1118
1875
  type: require_event_log.AGENT_USAGE_EVENT_TYPE,
1119
1876
  ...source,
@@ -1123,8 +1880,9 @@ function createAgentRuntime(machine, options = {}) {
1123
1880
  maxModelCalls
1124
1881
  }
1125
1882
  };
1883
+ if (source.kind === "text") resultOwed = true;
1126
1884
  let delivered = false;
1127
- deliverUsageEvent(event, () => rootFacade(() => delivered = true), (dropped) => {
1885
+ deliverUsageEvent(event, () => rootFacade(() => delivered = true, source.kind === "decision" ? void 0 : self), (dropped) => {
1128
1886
  if (!finished) return false;
1129
1887
  onTrace({
1130
1888
  type: "usage.dropped",
@@ -1156,14 +1914,30 @@ function createAgentRuntime(machine, options = {}) {
1156
1914
  const effectiveSources = provided.sources.actors;
1157
1915
  const executors = { ...options.executors };
1158
1916
  assertBindable(provided, effectiveSources, executors);
1159
- const rootFacade = (onSend) => ({
1917
+ const rootFacade = (onSend, from) => ({
1160
1918
  getSnapshot: () => current,
1161
1919
  send: (event) => {
1162
1920
  onSend?.();
1163
- enqueue(event);
1921
+ const sender = from;
1922
+ let root = sender;
1923
+ while (root?._parent) root = root._parent;
1924
+ if (sender?.system?.sendEvent && root !== void 0 && root !== sender) sender.system.sendEvent(sender, root, event);
1925
+ else enqueue(event);
1164
1926
  }
1165
1927
  });
1166
1928
  const actorHolder = { actorRef: rootFacade() };
1929
+ const deliveryWaiters = /* @__PURE__ */ new Map();
1930
+ let committedWaiters = [];
1931
+ const releaseCommitted = () => {
1932
+ const released = committedWaiters;
1933
+ committedWaiters = [];
1934
+ for (const release of released) release();
1935
+ };
1936
+ const releaseAllDeliveries = () => {
1937
+ committedWaiters.push(...deliveryWaiters.values());
1938
+ deliveryWaiters.clear();
1939
+ releaseCommitted();
1940
+ };
1167
1941
  const runCtx = {
1168
1942
  generateText: executors.generateText,
1169
1943
  streamText: executors.streamText,
@@ -1174,8 +1948,13 @@ function createAgentRuntime(machine, options = {}) {
1174
1948
  recordUsage,
1175
1949
  actorHolder,
1176
1950
  awaitJournal,
1951
+ awaitDelivery: (event) => new Promise((resolve) => {
1952
+ if (finished || stopReason !== void 0) resolve();
1953
+ else deliveryWaiters.set(event, resolve);
1954
+ }),
1177
1955
  runId,
1178
1956
  schemas: require_event_log.getRegisteredAgentExecutionOptions(machine).schemas,
1957
+ pendingJournal: () => store !== void 0 && (journalPending > 0 || unflushed.length > 0) ? awaitJournal().then(() => stopReason === void 0, () => false) : void 0,
1179
1958
  onChildEvent: (self, event) => {
1180
1959
  if (finished || event.type === "xstate.stop") return;
1181
1960
  const actorPath = actorPathOf(self);
@@ -1198,6 +1977,10 @@ function createAgentRuntime(machine, options = {}) {
1198
1977
  };
1199
1978
  const wrappedSources = {};
1200
1979
  for (const [key, logic] of Object.entries(effectiveSources)) {
1980
+ if (require_act.isActLogic(logic)) {
1981
+ wrappedSources[key] = bindActLogic(runCtx);
1982
+ continue;
1983
+ }
1201
1984
  if (require_decision.isDecisionLogic(logic)) {
1202
1985
  wrappedSources[key] = bindDecisionLogic(logic, runCtx);
1203
1986
  continue;
@@ -1211,6 +1994,7 @@ function createAgentRuntime(machine, options = {}) {
1211
1994
  if (rebound !== logic) wrappedSources[key] = rebound;
1212
1995
  continue;
1213
1996
  }
1997
+ if (runCtx.pendingJournal && typeof logic?.transition === "function") wrappedSources[key] = journalGatedLogic(logic, runCtx.pendingJournal);
1214
1998
  }
1215
1999
  const boundMachine = provided.provide({ actors: wrappedSources });
1216
2000
  const mailbox = [];
@@ -1220,9 +2004,9 @@ function createAgentRuntime(machine, options = {}) {
1220
2004
  let started = false;
1221
2005
  let finished = false;
1222
2006
  let ignoredEvent;
1223
- const enqueue = (event) => {
2007
+ const enqueue = (event, fromHost = false) => {
1224
2008
  if (finished) return;
1225
- fromMailbox.add(event);
2009
+ if (!fromHost) fromMailbox.add(event);
1226
2010
  const waiting = wake;
1227
2011
  if (waiting) {
1228
2012
  wake = void 0;
@@ -1254,10 +2038,10 @@ function createAgentRuntime(machine, options = {}) {
1254
2038
  recheck();
1255
2039
  }, delay));
1256
2040
  };
1257
- const childrenBusy = (snapshot) => Object.values(snapshot?.children ?? {}).some((child) => {
2041
+ const childrenBusy = (snapshot, nested = false) => Object.values(snapshot?.children ?? {}).some((child) => {
1258
2042
  const childSnapshot = child?.getSnapshot?.();
1259
- if (childSnapshot?.status !== "active") return false;
1260
- return (0, xstate.isMachineSnapshot)(childSnapshot) ? childrenBusy(childSnapshot) : true;
2043
+ if (childSnapshot?.status !== "active") return nested && (childSnapshot?.status === "done" || childSnapshot?.status === "error");
2044
+ return (0, xstate.isMachineSnapshot)(childSnapshot) ? childrenBusy(childSnapshot, true) : true;
1261
2045
  });
1262
2046
  const workInFlight = () => childrenBusy(current) || timerHandles.size > 0;
1263
2047
  let recheckScheduled = false;
@@ -1289,12 +2073,28 @@ function createAgentRuntime(machine, options = {}) {
1289
2073
  persistedAtStop = current && boundMachine.getPersistedSnapshot(current);
1290
2074
  } catch {}
1291
2075
  stopChildren(current);
2076
+ releaseAllDeliveries();
1292
2077
  recheck();
1293
2078
  };
1294
- const onAbort = () => stopRun({
2079
+ const abortNow = () => stopRun({
1295
2080
  cause: "aborted",
1296
2081
  error: options.signal?.reason ?? /* @__PURE__ */ new Error("Aborted")
1297
2082
  });
2083
+ let pendingAbort;
2084
+ let abortApplied = false;
2085
+ const sentEvents = /* @__PURE__ */ new WeakSet();
2086
+ let abortTimer;
2087
+ const onAbort = () => {
2088
+ const abortWith = options.abortWith;
2089
+ if (abortWith === void 0 || runtime.send(abortWith.event) === false) {
2090
+ abortNow();
2091
+ return;
2092
+ }
2093
+ pendingAbort = abortWith.event;
2094
+ if (abortWith.timeout !== void 0) abortTimer = setTimeout(() => {
2095
+ if (current?.status === "active") abortNow();
2096
+ }, abortWith.timeout);
2097
+ };
1298
2098
  const emitFromRoot = (event) => {
1299
2099
  onTrace({
1300
2100
  type: "emit",
@@ -1304,9 +2104,35 @@ function createAgentRuntime(machine, options = {}) {
1304
2104
  observe(`on['${event.type}']`, () => on[event.type]?.(event));
1305
2105
  if (event.type !== "*") observe("on['*']", () => on["*"]?.(event));
1306
2106
  };
1307
- const inspect = options.inspect === void 0 ? void 0 : (event) => {
2107
+ const inspect = options.inspect === void 0 ? void 0 : isStableInspection(options.inspect) ? options.inspect : stableInspection((event) => {
1308
2108
  if (typeof options.inspect === "function") options.inspect(event);
1309
2109
  else options.inspect?.next?.(event);
2110
+ });
2111
+ const completionOf = (child) => {
2112
+ const snapshot = child.getSnapshot();
2113
+ if (snapshot.status === "done") return {
2114
+ type: "xstate.done.actor",
2115
+ output: snapshot.output,
2116
+ actorId: child.id,
2117
+ sessionId: child.sessionId
2118
+ };
2119
+ if (snapshot.status === "error") return {
2120
+ type: "xstate.error.actor",
2121
+ error: snapshot.error,
2122
+ actorId: child.id,
2123
+ sessionId: child.sessionId
2124
+ };
2125
+ };
2126
+ const restoredRootCompletions = (snapshot) => Object.values(snapshot.children ?? {}).map((child) => child ? completionOf(child) : void 0).filter((event) => event !== void 0);
2127
+ const reportRestoredCompletions = (actor) => {
2128
+ const snapshot = actor.getSnapshot();
2129
+ if (snapshot.status !== "active") return;
2130
+ for (const child of Object.values(snapshot.children ?? {})) {
2131
+ if (!child) continue;
2132
+ const event = completionOf(child);
2133
+ if (event !== void 0 && child._restored) child.system?.sendEvent?.(child, actor, event);
2134
+ else reportRestoredCompletions(child);
2135
+ }
1310
2136
  };
1311
2137
  let execution;
1312
2138
  execution = (0, xstate_durable.createDurable)(boundMachine, {
@@ -1317,12 +2143,17 @@ function createAgentRuntime(machine, options = {}) {
1317
2143
  error: recheck
1318
2144
  });
1319
2145
  actor.start();
2146
+ reportRestoredCompletions(actor);
1320
2147
  },
1321
2148
  enqueueRootEvent: (_source, event) => enqueue(event),
1322
2149
  executeAction: (action, _metadata, runtime) => action.exec(runtime),
1323
2150
  waitForEvent: () => {
1324
2151
  const queued = mailbox.shift();
1325
2152
  if (queued !== void 0) return queued;
2153
+ if (resultOwed) {
2154
+ resultOwed = false;
2155
+ setTimeout(flushJournal, 0);
2156
+ } else flushJournal();
1326
2157
  if (stopReason !== void 0 || finished || !workInFlight()) return QUIESCENT;
1327
2158
  return new Promise((resolve) => {
1328
2159
  wake = resolve;
@@ -1373,7 +2204,7 @@ function createAgentRuntime(machine, options = {}) {
1373
2204
  const { sessionId, actorId } = event;
1374
2205
  return !Object.values(current?.children ?? {}).some((child) => sessionId !== void 0 ? child?.sessionId === sessionId : child?.id === actorId);
1375
2206
  };
1376
- return {
2207
+ const runtime = {
1377
2208
  async start(init = {}) {
1378
2209
  if (started) throw new require_event_log.AgentError("runtime-started", "createAgentRuntime: `start` was already called.");
1379
2210
  started = true;
@@ -1399,7 +2230,7 @@ function createAgentRuntime(machine, options = {}) {
1399
2230
  let seedInitEntry;
1400
2231
  const restoredPersistedSnapshot = () => {
1401
2232
  try {
1402
- const restored = logMachine.restoreSnapshot(init.snapshot);
2233
+ const restored = require_event_log.restoreMachineSnapshot(logMachine, init.snapshot);
1403
2234
  return logMachine.getPersistedSnapshot(restored);
1404
2235
  } catch {
1405
2236
  return;
@@ -1551,7 +2382,8 @@ function createAgentRuntime(machine, options = {}) {
1551
2382
  ...resumeEvent !== void 0 ? { event: resumeEvent } : {}
1552
2383
  });
1553
2384
  if (options.signal) {
1554
- if (options.signal.aborted) stopReason = {
2385
+ if (options.signal.aborted && options.abortWith !== void 0) onAbort();
2386
+ else if (options.signal.aborted) stopReason = {
1555
2387
  cause: "aborted",
1556
2388
  error: options.signal.reason ?? /* @__PURE__ */ new Error("Aborted")
1557
2389
  };
@@ -1567,6 +2399,7 @@ function createAgentRuntime(machine, options = {}) {
1567
2399
  else {
1568
2400
  try {
1569
2401
  [snapshot, effects] = execution.restore(effectiveSnapshot);
2402
+ for (const event of restoredRootCompletions(snapshot)) enqueue(event);
1570
2403
  } catch (error) {
1571
2404
  try {
1572
2405
  current = execution.initialTransition(resolvedInput)[0];
@@ -1591,19 +2424,36 @@ function createAgentRuntime(machine, options = {}) {
1591
2424
  transition(state, event, transitionOptions) {
1592
2425
  if (finished) throw new require_event_log.AgentError("runtime-finished", "createAgentRuntime: the run has finished; start a new runtime to continue.");
1593
2426
  if (stopReason !== void 0) return [state, []];
2427
+ if (pendingAbort !== void 0 && event !== pendingAbort && !fromMailbox.has(event) && !sentEvents.has(event)) return [state, []];
1594
2428
  event = toTimerInput(event);
1595
2429
  const attempts = transitionOptions?.attempts ?? attemptsByEvent.get(event);
1596
2430
  if (transitionOptions?.attempts !== void 0) require_event_log.assertJsonSerializable(transitionOptions.attempts, "attempts");
1597
2431
  const [next, effects] = execution.transition(state, event);
1598
2432
  const ignored = !fromMailbox.has(event) && next === state && effects.length === 0;
2433
+ if (event === pendingAbort) {
2434
+ pendingAbort = void 0;
2435
+ abortApplied = !ignored;
2436
+ if (ignored) {
2437
+ abortNow();
2438
+ return [state, []];
2439
+ }
2440
+ }
1599
2441
  if (ignored) ignoredEvent = event;
1600
2442
  appendLogEntry(event, attempts, takeDecidedBy(event));
2443
+ const waiter = deliveryWaiters.get(event);
2444
+ if (waiter) {
2445
+ deliveryWaiters.delete(event);
2446
+ committedWaiters.push(waiter);
2447
+ }
1601
2448
  if (stopReason !== void 0) return [state, []];
1602
2449
  commit(next, event, ignored);
1603
2450
  return [next, effects];
1604
2451
  },
1605
2452
  async execute(effects) {
1606
- if (stopReason !== void 0 || finished || effects.length === 0) return;
2453
+ if (stopReason !== void 0 || finished || effects.length === 0) {
2454
+ releaseCommitted();
2455
+ return;
2456
+ }
1607
2457
  try {
1608
2458
  await execution.executeEffects(effects);
1609
2459
  } catch (error) {
@@ -1612,6 +2462,7 @@ function createAgentRuntime(machine, options = {}) {
1612
2462
  error
1613
2463
  });
1614
2464
  }
2465
+ releaseCommitted();
1615
2466
  recheck();
1616
2467
  },
1617
2468
  async nextEvent() {
@@ -1623,9 +2474,27 @@ function createAgentRuntime(machine, options = {}) {
1623
2474
  return event;
1624
2475
  }
1625
2476
  },
2477
+ send(event) {
2478
+ if (finished) throw new require_event_log.AgentError("runtime-finished", "createAgentRuntime: the run has finished; start a new runtime to send it events.");
2479
+ if (stopReason !== void 0 || current !== void 0 && current.status !== "active") return false;
2480
+ sentEvents.add(event);
2481
+ enqueue(event, true);
2482
+ return true;
2483
+ },
1626
2484
  async finish() {
1627
2485
  if (finished) throw new require_event_log.AgentError("runtime-finished", "createAgentRuntime: `finish` was already called.");
1628
- for (const event of mailbox) if (event.type === "@agent.usage") appendLogEntry(event);
2486
+ clearTimeout(abortTimer);
2487
+ if ((pendingAbort !== void 0 || abortApplied) && current?.status === "active") abortNow();
2488
+ const journaledUsage = /* @__PURE__ */ new Set();
2489
+ for (;;) {
2490
+ await drainJournal();
2491
+ const usage = mailbox.filter((event) => event.type === "@agent.usage" && !journaledUsage.has(event));
2492
+ if (usage.length === 0) break;
2493
+ for (const event of usage) {
2494
+ journaledUsage.add(event);
2495
+ appendLogEntry(event);
2496
+ }
2497
+ }
1629
2498
  const snapshot = current;
1630
2499
  let outcome;
1631
2500
  if (stopReason !== void 0) outcome = {
@@ -1678,6 +2547,8 @@ function createAgentRuntime(machine, options = {}) {
1678
2547
  return persistedSnapshot;
1679
2548
  };
1680
2549
  finished = true;
2550
+ flushJournal();
2551
+ releaseAllDeliveries();
1681
2552
  const journalAtSettle = journalChain;
1682
2553
  const result = {
1683
2554
  ...outcome,
@@ -1702,6 +2573,7 @@ function createAgentRuntime(machine, options = {}) {
1702
2573
  return result;
1703
2574
  }
1704
2575
  };
2576
+ return runtime;
1705
2577
  }
1706
2578
  /**
1707
2579
  * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
@@ -1777,6 +2649,28 @@ function isAgentIdle(snapshot) {
1777
2649
  }) || require_decision.getAcceptedEvents(snapshot).length > 0;
1778
2650
  }
1779
2651
  //#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
1780
2674
  Object.defineProperty(exports, "AGENT_TRACE_SCHEMA_VERSION", {
1781
2675
  enumerable: true,
1782
2676
  get: function() {
@@ -1795,6 +2689,12 @@ Object.defineProperty(exports, "AgentSnapshotDivergedError", {
1795
2689
  return AgentSnapshotDivergedError;
1796
2690
  }
1797
2691
  });
2692
+ Object.defineProperty(exports, "bindActForProvide", {
2693
+ enumerable: true,
2694
+ get: function() {
2695
+ return bindActForProvide;
2696
+ }
2697
+ });
1798
2698
  Object.defineProperty(exports, "bindChildMachineForProvide", {
1799
2699
  enumerable: true,
1800
2700
  get: function() {
@@ -1813,12 +2713,24 @@ Object.defineProperty(exports, "bindTextForProvide", {
1813
2713
  return bindTextForProvide;
1814
2714
  }
1815
2715
  });
2716
+ Object.defineProperty(exports, "createAgentInbox", {
2717
+ enumerable: true,
2718
+ get: function() {
2719
+ return createAgentInbox;
2720
+ }
2721
+ });
1816
2722
  Object.defineProperty(exports, "createAgentRuntime", {
1817
2723
  enumerable: true,
1818
2724
  get: function() {
1819
2725
  return createAgentRuntime;
1820
2726
  }
1821
2727
  });
2728
+ Object.defineProperty(exports, "decideNext", {
2729
+ enumerable: true,
2730
+ get: function() {
2731
+ return decideNext;
2732
+ }
2733
+ });
1822
2734
  Object.defineProperty(exports, "getConfiguredInvokeSrcs", {
1823
2735
  enumerable: true,
1824
2736
  get: function() {
@@ -1837,12 +2749,24 @@ Object.defineProperty(exports, "isAgentIdle", {
1837
2749
  return isAgentIdle;
1838
2750
  }
1839
2751
  });
2752
+ Object.defineProperty(exports, "isAsyncIterable", {
2753
+ enumerable: true,
2754
+ get: function() {
2755
+ return isAsyncIterable;
2756
+ }
2757
+ });
1840
2758
  Object.defineProperty(exports, "isStateMachineLogic", {
1841
2759
  enumerable: true,
1842
2760
  get: function() {
1843
2761
  return isStateMachineLogic;
1844
2762
  }
1845
2763
  });
2764
+ Object.defineProperty(exports, "mapEffects", {
2765
+ enumerable: true,
2766
+ get: function() {
2767
+ return mapEffects;
2768
+ }
2769
+ });
1846
2770
  Object.defineProperty(exports, "runAgent", {
1847
2771
  enumerable: true,
1848
2772
  get: function() {
@@ -1861,6 +2785,12 @@ Object.defineProperty(exports, "serializeTraceEvent", {
1861
2785
  return serializeTraceEvent;
1862
2786
  }
1863
2787
  });
2788
+ Object.defineProperty(exports, "toJsonValue", {
2789
+ enumerable: true,
2790
+ get: function() {
2791
+ return toJsonValue;
2792
+ }
2793
+ });
1864
2794
  Object.defineProperty(exports, "traceTransitions", {
1865
2795
  enumerable: true,
1866
2796
  get: function() {