@statelyai/agent 2.0.0-alpha.35 → 2.0.0-alpha.36
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.
- package/CHANGELOG.md +111 -0
- package/dist/act-B9hLQls6.mjs +19 -0
- package/dist/act-CrX0JwWY.cjs +42 -0
- package/dist/ai-sdk.cjs +63 -7
- package/dist/ai-sdk.d.cts +13 -3
- package/dist/ai-sdk.d.mts +13 -3
- package/dist/ai-sdk.mjs +63 -7
- package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
- package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
- package/dist/decision-object-B5zGSPFp.d.mts +15 -0
- package/dist/decision-object-DBcLWVvv.d.cts +15 -0
- package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
- package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
- package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
- package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
- package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
- package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
- package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
- package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
- package/dist/index.cjs +660 -286
- package/dist/index.d.cts +168 -9
- package/dist/index.d.mts +168 -9
- package/dist/index.mjs +639 -271
- package/dist/internal-C3Lqu538.d.cts +43 -0
- package/dist/internal-DUcdhk-i.d.mts +43 -0
- package/dist/log.cjs +2 -2
- package/dist/log.d.cts +1 -1
- package/dist/log.d.mts +1 -1
- package/dist/log.mjs +2 -2
- package/dist/machines.cjs +457 -41
- package/dist/machines.d.cts +114 -43
- package/dist/machines.d.mts +114 -43
- package/dist/machines.mjs +457 -42
- package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
- package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
- package/dist/openai.cjs +149 -36
- package/dist/openai.d.cts +28 -10
- package/dist/openai.d.mts +28 -10
- package/dist/openai.mjs +149 -36
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
- package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
- package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
- package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
- package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
- package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
- package/dist/tanstack-ai.cjs +62 -4
- package/dist/tanstack-ai.d.cts +18 -6
- package/dist/tanstack-ai.d.mts +18 -6
- package/dist/tanstack-ai.mjs +62 -4
- package/dist/testing.cjs +399 -20
- package/dist/testing.d.cts +196 -255
- package/dist/testing.d.mts +196 -255
- package/dist/testing.mjs +395 -20
- package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
- package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
- package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
- package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
- package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
- package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
- package/dist/utils-7lSa4H-i.d.cts +403 -0
- package/dist/utils-CBbKw2fM.d.mts +403 -0
- package/dist/validate.cjs +44 -12
- package/dist/validate.d.cts +6 -6
- package/dist/validate.d.mts +6 -6
- package/dist/validate.mjs +44 -12
- package/dist/verify-Bink-Drw.cjs +2304 -0
- package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
- package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
- package/dist/verify-Dpz1u5Pe.mjs +2251 -0
- package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
- package/dist/with-model-calls-BkOwdroS.mjs +213 -0
- package/docs/act.md +102 -0
- package/docs/advanced.md +105 -0
- package/docs/any-stack.md +62 -0
- package/docs/choosing-a-run-mode.md +55 -0
- package/docs/debugging.md +29 -0
- package/docs/decisions.md +473 -0
- package/docs/environment-and-policy.md +188 -0
- package/docs/evals.md +509 -0
- package/docs/event-log.md +311 -0
- package/docs/from-a-loop.md +528 -0
- package/docs/generate-machines.md +110 -0
- package/docs/hosts.md +414 -0
- package/docs/human-in-the-loop.md +177 -0
- package/docs/index.md +48 -0
- package/docs/judgments.md +281 -0
- package/docs/langgraph-comparison.md +198 -0
- package/docs/machines-as-data.md +454 -0
- package/docs/machines-presets.md +198 -0
- package/docs/machines.md +497 -0
- package/docs/messages.md +67 -0
- package/docs/meta.json +52 -0
- package/docs/models-and-providers.md +268 -0
- package/docs/multi-agent.md +68 -0
- package/docs/observability.md +109 -0
- package/docs/patterns.md +31 -0
- package/docs/persistence.md +136 -0
- package/docs/quickstart.md +121 -0
- package/docs/roadmap.md +22 -0
- package/docs/scope.md +75 -0
- package/docs/statechart-policy-examples.md +69 -0
- package/docs/steps.md +54 -0
- package/docs/strangler-fig.md +323 -0
- package/docs/text-requests.md +250 -0
- package/docs/thinking-in-state-machines.md +324 -0
- package/docs/tools.md +249 -0
- package/docs/upgrading.md +37 -0
- package/docs/usage-and-budgets.md +516 -0
- package/docs/validate-and-repair.md +253 -0
- package/docs/verify.md +487 -0
- package/docs/xstate-4-and-5-apps.md +161 -0
- package/llms.txt +53 -0
- package/package.json +10 -3
- package/readme.md +30 -15
- package/skills/add-evals/SKILL.md +3 -1
- package/skills/add-traces/SKILL.md +6 -1
- package/skills/build-machine/SKILL.md +81 -0
- package/skills/generate-machine/SKILL.md +1 -1
- package/skills/graph-engineering/SKILL.md +13 -3
- package/skills/improve-machine/SKILL.md +21 -2
- package/skills/loop-to-machine/SKILL.md +147 -192
- package/skills/loop-to-machine/reference.md +260 -0
- package/dist/utils-BnXdWih3.d.mts +0 -108
- package/dist/utils-ebVpCYoF.d.cts +0 -108
- package/dist/verify-Bpahmr34.mjs +0 -1241
- package/dist/verify-DCLZa9R0.cjs +0 -1288
- package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
- package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
|
@@ -1,8 +1,328 @@
|
|
|
1
|
-
import { C as validateReplayEntries,
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import {
|
|
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";
|
|
5
|
+
import { createAsyncLogic, deliverEvent, getNextTransitions, isMachineSnapshot, stopActor, transition } from "xstate";
|
|
5
6
|
import { createDurable } from "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 = getAcceptedEvents(snapshot, {
|
|
49
|
+
events: schemas,
|
|
50
|
+
eventTypes: patterns
|
|
51
|
+
}).filter((event) => !isEventPattern(event.type));
|
|
52
|
+
const humanEventTypes = 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 = 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 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 = 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 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] = 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 (canonicalEventJson(before.value) !== canonicalEventJson(after.value)) changes.push({
|
|
147
|
+
key: "state",
|
|
148
|
+
before: before.value,
|
|
149
|
+
after: after.value,
|
|
150
|
+
isState: true
|
|
151
|
+
});
|
|
152
|
+
const from = isRecord(before.context) ? before.context : {};
|
|
153
|
+
const to = isRecord(after.context) ? after.context : {};
|
|
154
|
+
for (const key of keys ?? /* @__PURE__ */ new Set([...Object.keys(from), ...Object.keys(to)])) if (canonicalEventJson(from[key]) !== 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 (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
|
|
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 (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 (isDecisionLogic(logic)) {
|
|
242
567
|
if (executorBoundLogics.has(logic)) continue;
|
|
243
568
|
if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "decision");
|
|
@@ -376,85 +701,201 @@ function invokingActorOf(self, runCtx) {
|
|
|
376
701
|
* identical event shapes by construction. @internal
|
|
377
702
|
*/
|
|
378
703
|
function bindTextLogic(logic, runCtx) {
|
|
379
|
-
return logic.withExecutor(
|
|
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
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
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
|
+
const raw = await executor(requestWithTools, {
|
|
746
|
+
onChunk: (chunk) => {
|
|
747
|
+
runCtx.emitTrace?.({
|
|
748
|
+
type: "stream.chunk",
|
|
749
|
+
request: agentRequest,
|
|
750
|
+
chunk
|
|
751
|
+
}, self);
|
|
752
|
+
},
|
|
753
|
+
signal,
|
|
754
|
+
...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
|
|
755
|
+
...id !== "" ? { requestId: id } : {},
|
|
756
|
+
...callKey !== void 0 ? { callKey } : {}
|
|
757
|
+
});
|
|
758
|
+
const output = await normalizeGeneratorResult(raw, id);
|
|
759
|
+
const rawReasoning = raw?.reasoning;
|
|
760
|
+
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
761
|
+
runCtx.countModelCalls?.(getCallModelCalls(raw) - 1);
|
|
762
|
+
const usage = getCallUsage(raw);
|
|
763
|
+
const finishReason = getCallFinishReason(raw);
|
|
764
|
+
if (usage) runCtx.recordUsage?.(usage, {
|
|
393
765
|
kind: "text",
|
|
394
|
-
id,
|
|
395
|
-
src,
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
766
|
+
...id !== "" ? { id } : {},
|
|
767
|
+
...src !== "" ? { src } : {},
|
|
768
|
+
model: request.model,
|
|
769
|
+
...request.name !== void 0 ? { name: request.name } : {}
|
|
770
|
+
}, self);
|
|
771
|
+
runCtx.emitTrace?.({
|
|
772
|
+
type: "request.end",
|
|
773
|
+
request: agentRequest,
|
|
774
|
+
output,
|
|
775
|
+
raw,
|
|
776
|
+
...reasoning !== void 0 ? { reasoning } : {},
|
|
777
|
+
...usage !== void 0 ? { usage } : {},
|
|
778
|
+
...finishReason !== void 0 ? { finishReason } : {}
|
|
779
|
+
}, self);
|
|
780
|
+
return {
|
|
781
|
+
result: output,
|
|
782
|
+
messages: responseMessagesOf(raw)
|
|
400
783
|
};
|
|
401
|
-
|
|
784
|
+
} catch (error) {
|
|
785
|
+
runCtx.countModelCalls?.(getCallModelCalls(error) - 1);
|
|
402
786
|
runCtx.emitTrace?.({
|
|
403
|
-
type: "request.
|
|
404
|
-
request: agentRequest
|
|
787
|
+
type: "request.error",
|
|
788
|
+
request: agentRequest,
|
|
789
|
+
error
|
|
405
790
|
}, self);
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
791
|
+
throw error;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Builds the actor logic the runtime installs in place of the `agent.act`
|
|
796
|
+
* builtin: ONE `generateText` call (the host's tool loop, `maxSteps` default
|
|
797
|
+
* 20) whose tools are the invoking state's accepted, non-human events plus the
|
|
798
|
+
* input's plain `tools`. Each event tool call, in call order:
|
|
799
|
+
*
|
|
800
|
+
* 1. validates its payload against the event schema (error result on failure);
|
|
801
|
+
* 2. answers "not allowed" when the live snapshot cannot take the event;
|
|
802
|
+
* 3. otherwise sends it to the invoking actor (journaled like any delivered
|
|
803
|
+
* event), waits for it to commit, and answers with the delta
|
|
804
|
+
* `{ state?, changed? }` it caused.
|
|
805
|
+
*
|
|
806
|
+
* Once the invoking state exits (the invoke's `signal` aborts), every later
|
|
807
|
+
* call answers {@link ACT_STATE_EXITED} and the executor's signal aborts, so
|
|
808
|
+
* the loop stops. Completes with the final text when the state is still active.
|
|
809
|
+
*
|
|
810
|
+
* Not resumable mid-loop: a crash during the tool loop replays the events it
|
|
811
|
+
* already delivered from the journal, but the act invoke itself restarts from
|
|
812
|
+
* scratch (a fresh model call) if its state is still active.
|
|
813
|
+
*/
|
|
814
|
+
function bindActLogic(runCtx) {
|
|
815
|
+
const logic = createAsyncLogic({ run: async ({ input, signal, self: selfArg }) => {
|
|
816
|
+
const self = selfArg;
|
|
817
|
+
const { id, src } = selfIdAndSrc(self);
|
|
818
|
+
await Promise.resolve();
|
|
819
|
+
const actorRef = invokingActorOf(self, runCtx);
|
|
820
|
+
if (!actorRef) throw new Error(`'${ACT_ACTOR}' needs the invoking actor's snapshot.`);
|
|
821
|
+
const awaitDelivery = !isChildRequest(self) && actorRef === runCtx.actorHolder.actorRef ? runCtx.awaitDelivery : void 0;
|
|
822
|
+
const snapshot = actorRef.getSnapshot();
|
|
823
|
+
const events = getAcceptedEvents(snapshot, {
|
|
824
|
+
schemas: runCtx.schemas,
|
|
825
|
+
eventTypes: resolveAllowedEventTypes(input.allowedEvents, input),
|
|
826
|
+
actor: "agent"
|
|
827
|
+
});
|
|
828
|
+
const loop = new AbortController();
|
|
829
|
+
const exited = () => signal.aborted || loop.signal.aborted;
|
|
830
|
+
if (signal.aborted) loop.abort(signal.reason);
|
|
831
|
+
else signal.addEventListener("abort", () => loop.abort(signal.reason), { once: true });
|
|
832
|
+
const callEvent = async (type, schema, args) => {
|
|
833
|
+
if (exited()) return ACT_STATE_EXITED;
|
|
834
|
+
let payload = isPlainObject(args) ? { ...args } : {};
|
|
835
|
+
delete payload.type;
|
|
836
|
+
if (schema) try {
|
|
837
|
+
payload = validateSchemaSync(schema, payload);
|
|
838
|
+
} catch (error) {
|
|
839
|
+
return `'${type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`;
|
|
840
|
+
}
|
|
841
|
+
const event = {
|
|
842
|
+
...payload,
|
|
843
|
+
type
|
|
447
844
|
};
|
|
845
|
+
const before = actorRef.getSnapshot();
|
|
846
|
+
let accepted;
|
|
847
|
+
try {
|
|
848
|
+
accepted = !getHumanEventTypes(before).has(type) && before.can(event);
|
|
849
|
+
} catch {
|
|
850
|
+
accepted = false;
|
|
851
|
+
}
|
|
852
|
+
if (!accepted) return `'${type}' is not allowed in state ${JSON.stringify(before.value)}`;
|
|
853
|
+
const delivered = awaitDelivery?.(event);
|
|
854
|
+
actorRef.send(event);
|
|
855
|
+
await delivered;
|
|
856
|
+
await Promise.resolve();
|
|
857
|
+
const delta = describeSnapshotDelta(before, actorRef.getSnapshot());
|
|
858
|
+
if (signal.aborted) loop.abort(signal.reason);
|
|
859
|
+
return delta;
|
|
860
|
+
};
|
|
861
|
+
let queue = Promise.resolve();
|
|
862
|
+
const serialized = (run) => (args) => {
|
|
863
|
+
const result = queue.then(() => run(args));
|
|
864
|
+
queue = result.catch(() => {});
|
|
865
|
+
return result;
|
|
866
|
+
};
|
|
867
|
+
const tools = { ...input.tools };
|
|
868
|
+
for (const descriptor of events) tools[descriptor.toolName] = {
|
|
869
|
+
description: `Send '${descriptor.type}'. Answers with what it changed.`,
|
|
870
|
+
...descriptor.inputSchema ? { inputSchema: descriptor.inputSchema } : {},
|
|
871
|
+
execute: serialized((args) => callEvent(descriptor.type, descriptor.inputSchema, args))
|
|
872
|
+
};
|
|
873
|
+
const request = {
|
|
874
|
+
name: input.name ?? (id || src),
|
|
875
|
+
input,
|
|
876
|
+
model: input.model,
|
|
877
|
+
system: input.system,
|
|
878
|
+
prompt: input.prompt,
|
|
879
|
+
messages: input.messages,
|
|
880
|
+
tools,
|
|
881
|
+
maxSteps: input.maxSteps ?? 20,
|
|
882
|
+
temperature: input.temperature,
|
|
883
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
884
|
+
topP: input.topP,
|
|
885
|
+
topK: input.topK,
|
|
886
|
+
seed: input.seed,
|
|
887
|
+
stopSequences: input.stopSequences,
|
|
888
|
+
metadata: input.metadata
|
|
889
|
+
};
|
|
890
|
+
try {
|
|
891
|
+
const { result } = await runTextRequest(runCtx, "generate", request, self, loop.signal);
|
|
892
|
+
return result;
|
|
448
893
|
} catch (error) {
|
|
449
|
-
|
|
450
|
-
runCtx.emitTrace?.({
|
|
451
|
-
type: "request.error",
|
|
452
|
-
request: agentRequest,
|
|
453
|
-
error
|
|
454
|
-
}, self);
|
|
894
|
+
if (exited()) return void 0;
|
|
455
895
|
throw error;
|
|
456
896
|
}
|
|
457
|
-
});
|
|
897
|
+
} });
|
|
898
|
+
return Object.assign(logic, { kind: "statelyai.actLogic" });
|
|
458
899
|
}
|
|
459
900
|
function createCountingDecide(runCtx, self, recordLater) {
|
|
460
901
|
return async (attemptRequest, info) => {
|
|
@@ -507,6 +948,59 @@ function createCountingDecide(runCtx, self, recordLater) {
|
|
|
507
948
|
}
|
|
508
949
|
};
|
|
509
950
|
}
|
|
951
|
+
function createCountingFill(runCtx, self, recordLater) {
|
|
952
|
+
return async (request, info) => {
|
|
953
|
+
const { id, src } = selfIdAndSrc(self);
|
|
954
|
+
const agentRequest = {
|
|
955
|
+
kind: "text",
|
|
956
|
+
id,
|
|
957
|
+
src,
|
|
958
|
+
mode: "generate",
|
|
959
|
+
input: request,
|
|
960
|
+
tools: request.tools,
|
|
961
|
+
events: []
|
|
962
|
+
};
|
|
963
|
+
runCtx.consumeModelCall();
|
|
964
|
+
runCtx.emitTrace?.({
|
|
965
|
+
type: "request.start",
|
|
966
|
+
request: agentRequest
|
|
967
|
+
}, self);
|
|
968
|
+
try {
|
|
969
|
+
await runCtx.awaitJournal?.();
|
|
970
|
+
const raw = await runCtx.generateText(request, {
|
|
971
|
+
...info,
|
|
972
|
+
...runCtx.runId !== void 0 ? { runId: runCtx.runId } : {},
|
|
973
|
+
...info?.requestId === void 0 && id !== "" ? { requestId: id } : {}
|
|
974
|
+
});
|
|
975
|
+
runCtx.countModelCalls?.(getCallModelCalls(raw) - 1);
|
|
976
|
+
const usage = getCallUsage(raw);
|
|
977
|
+
const finishReason = getCallFinishReason(raw);
|
|
978
|
+
if (usage) recordLater(() => runCtx.recordUsage?.(usage, {
|
|
979
|
+
kind: "decision",
|
|
980
|
+
...id !== "" ? { id } : {},
|
|
981
|
+
...src !== "" ? { src } : {},
|
|
982
|
+
model: request.model
|
|
983
|
+
}, self));
|
|
984
|
+
runCtx.emitTrace?.({
|
|
985
|
+
type: "request.end",
|
|
986
|
+
request: agentRequest,
|
|
987
|
+
output: raw.result,
|
|
988
|
+
raw,
|
|
989
|
+
...usage !== void 0 ? { usage } : {},
|
|
990
|
+
...finishReason !== void 0 ? { finishReason } : {}
|
|
991
|
+
}, self);
|
|
992
|
+
return raw;
|
|
993
|
+
} catch (error) {
|
|
994
|
+
runCtx.countModelCalls?.(getCallModelCalls(error) - 1);
|
|
995
|
+
runCtx.emitTrace?.({
|
|
996
|
+
type: "request.error",
|
|
997
|
+
request: agentRequest,
|
|
998
|
+
error
|
|
999
|
+
}, self);
|
|
1000
|
+
throw error;
|
|
1001
|
+
}
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
510
1004
|
/**
|
|
511
1005
|
* Builds the decision actor logic the runtime installs in place of a
|
|
512
1006
|
* `DecisionLogic`/`agent.decide` source. `DecisionLogic.withExecutor(...)`
|
|
@@ -581,20 +1075,26 @@ function bindDecisionLogic(logic, runCtx) {
|
|
|
581
1075
|
throw error;
|
|
582
1076
|
}
|
|
583
1077
|
const usageRecords = [];
|
|
584
|
-
const
|
|
1078
|
+
const recordLater = (record) => usageRecords.push(record);
|
|
1079
|
+
const decide = createCountingDecide(runCtx, self, recordLater);
|
|
1080
|
+
const generateText = runCtx.generateText ? createCountingFill(runCtx, self, recordLater) : void 0;
|
|
1081
|
+
const invokeCallKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
|
|
585
1082
|
let priorAttempts = [];
|
|
586
1083
|
let chosen;
|
|
587
1084
|
try {
|
|
588
|
-
chosen = await resolveDecision(request, {
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
1085
|
+
chosen = await resolveDecision(request, {
|
|
1086
|
+
decide: (attemptRequest, info) => {
|
|
1087
|
+
priorAttempts = attemptRequest.attempts;
|
|
1088
|
+
return decide(attemptRequest, info);
|
|
1089
|
+
},
|
|
1090
|
+
...generateText ? { generateText } : {}
|
|
1091
|
+
}, {
|
|
1092
|
+
...invokeCallKey !== void 0 ? { callKey: invokeCallKey } : {},
|
|
592
1093
|
maxRetries: lowered.maxRetries ?? logic.maxRetries,
|
|
593
1094
|
signal,
|
|
594
1095
|
canTake: agentCan
|
|
595
1096
|
});
|
|
596
|
-
|
|
597
|
-
runCtx.noteDecision?.(chosen, priorAttempts, callKey === void 0 ? void 0 : callKey.slice(callKey.indexOf(":") + 1));
|
|
1097
|
+
runCtx.noteDecision?.(chosen, priorAttempts, invokeCallKey === void 0 ? void 0 : invokeCallKey.slice(invokeCallKey.indexOf(":") + 1));
|
|
598
1098
|
actorRef?.send(chosen);
|
|
599
1099
|
} finally {
|
|
600
1100
|
for (const record of usageRecords) record();
|
|
@@ -637,7 +1137,7 @@ function rootTraceState(root) {
|
|
|
637
1137
|
let state = rootTraceRegistry.get(root);
|
|
638
1138
|
if (!state) {
|
|
639
1139
|
const logic = root.logic;
|
|
640
|
-
const machineId = (logic?.config)?.id ?? logic?.id ?? "
|
|
1140
|
+
const machineId = (logic?.config)?.id ?? logic?.id ?? "";
|
|
641
1141
|
const machineVersion = logic ? resolveMachineVersion(logic) : "";
|
|
642
1142
|
state = {
|
|
643
1143
|
runId: `run_${nextProvideRunId++}`,
|
|
@@ -756,6 +1256,13 @@ function bindDecisionForProvide(machine, logic, executors, options) {
|
|
|
756
1256
|
return bindDecisionLogic(logic, provideBindContext(machine, executors, options));
|
|
757
1257
|
}
|
|
758
1258
|
/**
|
|
1259
|
+
* Host-binds the `agent.act` builtin for {@link provideExecutors}: the
|
|
1260
|
+
* runtime's act wrapper with the same request-level tracing. @internal
|
|
1261
|
+
*/
|
|
1262
|
+
function bindActForProvide(machine, executors, options) {
|
|
1263
|
+
return bindActLogic(provideBindContext(machine, executors, options));
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
759
1266
|
* Recursively binds an invoked child state machine for {@link provideExecutors},
|
|
760
1267
|
* with the same semantics `createAgentRuntime` applies ({@link rebindChildMachine}):
|
|
761
1268
|
* string-keyed text/decision sources at any depth inherit the host executors,
|
|
@@ -809,6 +1316,10 @@ function rebindChildMachine(childMachine, runCtx, visited, ctxFor) {
|
|
|
809
1316
|
const sources = childMachine.sources.actors;
|
|
810
1317
|
const wrapped = {};
|
|
811
1318
|
for (const [key, logic] of Object.entries(sources)) {
|
|
1319
|
+
if (isActLogic(logic)) {
|
|
1320
|
+
wrapped[key] = bindActLogic(runCtx);
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
812
1323
|
if (isDecisionLogic(logic)) {
|
|
813
1324
|
if (!executorBoundLogics.has(logic)) wrapped[key] = bindDecisionLogic(logic, runCtx);
|
|
814
1325
|
continue;
|
|
@@ -822,6 +1333,7 @@ function rebindChildMachine(childMachine, runCtx, visited, ctxFor) {
|
|
|
822
1333
|
if (rebound !== logic) wrapped[key] = rebound;
|
|
823
1334
|
continue;
|
|
824
1335
|
}
|
|
1336
|
+
if (runCtx.pendingJournal && typeof logic?.transition === "function") wrapped[key] = journalGatedLogic(logic, runCtx.pendingJournal);
|
|
825
1337
|
}
|
|
826
1338
|
const rebound = Object.keys(wrapped).length > 0 ? childMachine.provide({ actors: wrapped }) : childMachine;
|
|
827
1339
|
return runCtx.onChildEvent ? journaledMachine(rebound, runCtx.onChildEvent) : rebound;
|
|
@@ -838,6 +1350,38 @@ function journaledMachine(machine, onEvent) {
|
|
|
838
1350
|
return machine.transition(...args);
|
|
839
1351
|
} } });
|
|
840
1352
|
}
|
|
1353
|
+
/**
|
|
1354
|
+
* `logic`, with the side effects it starts (`@xstate.effect`: an async
|
|
1355
|
+
* actor's run, a callback's body) held until `pending` resolves. A child
|
|
1356
|
+
* machine runs live, so without this a plain actor it starts could do its
|
|
1357
|
+
* work (or the process could die) before the child's earlier entries are
|
|
1358
|
+
* durable, and a resume would run the earlier actor again.
|
|
1359
|
+
*/
|
|
1360
|
+
function journalGatedLogic(logic, pending) {
|
|
1361
|
+
const gate = (result, self) => {
|
|
1362
|
+
const [snapshot, effects] = result;
|
|
1363
|
+
if (!Array.isArray(effects) || !effects.some((e) => e?.type === "@xstate.effect")) return result;
|
|
1364
|
+
return [snapshot, effects.map((effect) => {
|
|
1365
|
+
if (effect?.type !== "@xstate.effect") return effect;
|
|
1366
|
+
const exec = effect.exec;
|
|
1367
|
+
const gated = (...args) => {
|
|
1368
|
+
const waiting = pending();
|
|
1369
|
+
if (waiting === void 0) return exec(...args);
|
|
1370
|
+
waiting.then(() => {
|
|
1371
|
+
if (self.getSnapshot().status === "active") exec(...args);
|
|
1372
|
+
});
|
|
1373
|
+
};
|
|
1374
|
+
return {
|
|
1375
|
+
...effect,
|
|
1376
|
+
exec: gated,
|
|
1377
|
+
action: gated
|
|
1378
|
+
};
|
|
1379
|
+
})];
|
|
1380
|
+
};
|
|
1381
|
+
const overrides = { transition: { value: (...args) => gate(logic.transition(...args), args[2].self) } };
|
|
1382
|
+
if (typeof logic.initialTransition === "function") overrides["initialTransition"] = { value: (...args) => gate(logic.initialTransition(...args), args[1].self) };
|
|
1383
|
+
return Object.create(logic, overrides);
|
|
1384
|
+
}
|
|
841
1385
|
const timerId = (timer) => JSON.stringify(timer);
|
|
842
1386
|
function toTimerInput(event) {
|
|
843
1387
|
const id = event.id;
|
|
@@ -866,6 +1410,133 @@ async function runToQuiescence(runtime, init = {}) {
|
|
|
866
1410
|
}
|
|
867
1411
|
return runtime.finish();
|
|
868
1412
|
}
|
|
1413
|
+
const inboxStates = /* @__PURE__ */ new WeakMap();
|
|
1414
|
+
/**
|
|
1415
|
+
* Creates a send handle for {@link AgentRunOptions.inbox}, typed by the
|
|
1416
|
+
* machine's events.
|
|
1417
|
+
*
|
|
1418
|
+
* @example
|
|
1419
|
+
* ```ts
|
|
1420
|
+
* const inbox = createAgentInbox<EventOf<typeof machine>>();
|
|
1421
|
+
* const run = runAgent(machine, { input, executors, inbox });
|
|
1422
|
+
* inbox.send({ type: "CANCEL" });
|
|
1423
|
+
* const result = await run;
|
|
1424
|
+
* ```
|
|
1425
|
+
*/
|
|
1426
|
+
function createAgentInbox() {
|
|
1427
|
+
const state = {
|
|
1428
|
+
queue: [],
|
|
1429
|
+
passSent: /* @__PURE__ */ new Set(),
|
|
1430
|
+
claimed: false,
|
|
1431
|
+
closed: false
|
|
1432
|
+
};
|
|
1433
|
+
const inbox = { send(event) {
|
|
1434
|
+
if (state.closed) return false;
|
|
1435
|
+
if (state.runtime) {
|
|
1436
|
+
state.passSent.add(event);
|
|
1437
|
+
const accepted = state.runtime.send(event);
|
|
1438
|
+
if (!accepted) state.closed = true;
|
|
1439
|
+
return accepted;
|
|
1440
|
+
}
|
|
1441
|
+
const waiter = state.waiter;
|
|
1442
|
+
if (waiter) {
|
|
1443
|
+
state.waiter = void 0;
|
|
1444
|
+
waiter(event);
|
|
1445
|
+
} else state.queue.push(event);
|
|
1446
|
+
return true;
|
|
1447
|
+
} };
|
|
1448
|
+
inboxStates.set(inbox, state);
|
|
1449
|
+
return inbox;
|
|
1450
|
+
}
|
|
1451
|
+
function bindInbox(runtime, inbox, openingFromInbox) {
|
|
1452
|
+
if (!inbox) return runtime;
|
|
1453
|
+
inbox.passSent = new Set(openingFromInbox === void 0 ? [] : [openingFromInbox]);
|
|
1454
|
+
for (const event of inbox.queue.splice(0)) {
|
|
1455
|
+
inbox.passSent.add(event);
|
|
1456
|
+
runtime.send(event);
|
|
1457
|
+
}
|
|
1458
|
+
inbox.runtime = runtime;
|
|
1459
|
+
let status;
|
|
1460
|
+
return {
|
|
1461
|
+
start: async (init) => {
|
|
1462
|
+
const [state, effects] = await runtime.start(init);
|
|
1463
|
+
status = state.status;
|
|
1464
|
+
return [state, effects];
|
|
1465
|
+
},
|
|
1466
|
+
transition: (state, event, options) => {
|
|
1467
|
+
const [next, effects] = runtime.transition(state, event, options);
|
|
1468
|
+
status = next.status;
|
|
1469
|
+
return [next, effects];
|
|
1470
|
+
},
|
|
1471
|
+
execute: (effects) => runtime.execute(effects),
|
|
1472
|
+
nextEvent: async () => {
|
|
1473
|
+
const event = await runtime.nextEvent();
|
|
1474
|
+
if (event === void 0) {
|
|
1475
|
+
inbox.runtime = void 0;
|
|
1476
|
+
if (status !== "active") inbox.closed = true;
|
|
1477
|
+
}
|
|
1478
|
+
return event;
|
|
1479
|
+
},
|
|
1480
|
+
send: (event) => runtime.send(event),
|
|
1481
|
+
finish: () => runtime.finish()
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
const ABORTED = Symbol("aborted");
|
|
1485
|
+
async function nextIdleEvent(snapshot, onIdle, inbox, signal) {
|
|
1486
|
+
if (signal?.aborted) return ABORTED;
|
|
1487
|
+
const queued = inbox?.queue.shift();
|
|
1488
|
+
if (queued !== void 0) return {
|
|
1489
|
+
event: queued,
|
|
1490
|
+
fromInbox: true
|
|
1491
|
+
};
|
|
1492
|
+
if (!onIdle) return void 0;
|
|
1493
|
+
let onAbort;
|
|
1494
|
+
const aborted = new Promise((resolve) => {
|
|
1495
|
+
onAbort = () => resolve(ABORTED);
|
|
1496
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1497
|
+
});
|
|
1498
|
+
try {
|
|
1499
|
+
return await waitForIdleAnswer(snapshot, onIdle, inbox, signal, aborted);
|
|
1500
|
+
} finally {
|
|
1501
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
async function waitForIdleAnswer(snapshot, onIdle, inbox, signal, aborted) {
|
|
1505
|
+
const answer = () => onIdle(snapshot, { signal });
|
|
1506
|
+
if (!inbox) return Promise.race([aborted, answer().then((event) => ({
|
|
1507
|
+
event,
|
|
1508
|
+
fromInbox: false
|
|
1509
|
+
}))]);
|
|
1510
|
+
let waiter;
|
|
1511
|
+
const sent = new Promise((resolve) => {
|
|
1512
|
+
waiter = (event) => resolve({
|
|
1513
|
+
event,
|
|
1514
|
+
fromInbox: true
|
|
1515
|
+
});
|
|
1516
|
+
inbox.waiter = waiter;
|
|
1517
|
+
});
|
|
1518
|
+
const release = () => {
|
|
1519
|
+
if (inbox.waiter === waiter) inbox.waiter = void 0;
|
|
1520
|
+
};
|
|
1521
|
+
try {
|
|
1522
|
+
return await Promise.race([
|
|
1523
|
+
aborted,
|
|
1524
|
+
sent,
|
|
1525
|
+
answer().then((event) => {
|
|
1526
|
+
release();
|
|
1527
|
+
return {
|
|
1528
|
+
event,
|
|
1529
|
+
fromInbox: false
|
|
1530
|
+
};
|
|
1531
|
+
}, (error) => {
|
|
1532
|
+
release();
|
|
1533
|
+
throw error;
|
|
1534
|
+
})
|
|
1535
|
+
]);
|
|
1536
|
+
} finally {
|
|
1537
|
+
release();
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
869
1540
|
/**
|
|
870
1541
|
* Runs `machine` to quiescence in one call: {@link createAgentRuntime} over
|
|
871
1542
|
* `options`, then {@link runToQuiescence} with the same object as its init.
|
|
@@ -891,23 +1562,69 @@ async function runToQuiescence(runtime, init = {}) {
|
|
|
891
1562
|
* ```
|
|
892
1563
|
*/
|
|
893
1564
|
async function runAgent(machine, options = {}) {
|
|
894
|
-
const { onIdle, ...rest } = options;
|
|
895
|
-
|
|
896
|
-
if (
|
|
1565
|
+
const { onIdle, inbox, ...rest } = options;
|
|
1566
|
+
const inboxState = inbox === void 0 ? void 0 : inboxStates.get(inbox);
|
|
1567
|
+
if (inbox !== void 0) {
|
|
1568
|
+
if (inboxState === void 0 || inboxState.claimed) throw new AgentError("inbox-in-use", "runAgent: `inbox` must come from createAgentInbox() and serves one runAgent call.");
|
|
1569
|
+
inboxState.claimed = true;
|
|
1570
|
+
}
|
|
1571
|
+
try {
|
|
1572
|
+
return await runAgentPasses(machine, rest, onIdle, inboxState);
|
|
1573
|
+
} finally {
|
|
1574
|
+
if (inboxState) {
|
|
1575
|
+
inboxState.closed = true;
|
|
1576
|
+
inboxState.runtime = void 0;
|
|
1577
|
+
inboxState.queue.length = 0;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
async function runAgentPasses(machine, rest, onIdle, inbox) {
|
|
1582
|
+
if (!onIdle && !inbox) return runToQuiescence(bindInbox(createAgentRuntime(machine, rest), inbox), rest);
|
|
1583
|
+
if (rest.inspect !== void 0 && !isStableInspection(rest.inspect)) {
|
|
1584
|
+
const userInspect = rest.inspect;
|
|
1585
|
+
rest = {
|
|
1586
|
+
...rest,
|
|
1587
|
+
inspect: stableInspection((event) => {
|
|
1588
|
+
if (typeof userInspect === "function") userInspect(event);
|
|
1589
|
+
else userInspect.next?.(event);
|
|
1590
|
+
})
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
const endPass = (persisted) => {
|
|
1594
|
+
if (isStableInspection(rest.inspect)) rest.inspect.endPass(persisted);
|
|
1595
|
+
};
|
|
1596
|
+
let result = await runToQuiescence(bindInbox(createAgentRuntime(machine, rest), inbox), rest);
|
|
1597
|
+
endPass(result.persist());
|
|
897
1598
|
let modelCallsSpent = (rest.modelCallsSpent ?? 0) + result.usage.modelCalls;
|
|
898
1599
|
const { input: _input, events: _events, attempts: _attempts, ...resumeOptions } = rest;
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
1600
|
+
let answer = rest.event;
|
|
1601
|
+
while (result.status === "idle" && (result.ignored === void 0 || result.ignored !== answer && inbox?.passSent.has(result.ignored) === true)) {
|
|
1602
|
+
const next = await nextIdleEvent(result.snapshot, onIdle, inbox, rest.signal);
|
|
1603
|
+
if (next === void 0) break;
|
|
1604
|
+
if (next === ABORTED) {
|
|
1605
|
+
result = await runToQuiescence(createAgentRuntime(machine, {
|
|
1606
|
+
...resumeOptions,
|
|
1607
|
+
modelCallsSpent
|
|
1608
|
+
}), {
|
|
1609
|
+
...resumeOptions,
|
|
1610
|
+
...rest.store === void 0 ? { events: result.events } : {},
|
|
1611
|
+
snapshot: result.persist()
|
|
1612
|
+
});
|
|
1613
|
+
break;
|
|
1614
|
+
}
|
|
1615
|
+
const { event, fromInbox } = next;
|
|
1616
|
+
answer = fromInbox ? void 0 : event;
|
|
1617
|
+
result = await runToQuiescence(bindInbox(createAgentRuntime(machine, {
|
|
902
1618
|
...resumeOptions,
|
|
903
1619
|
modelCallsSpent
|
|
904
|
-
}), {
|
|
1620
|
+
}), inbox, fromInbox ? event : void 0), {
|
|
905
1621
|
...resumeOptions,
|
|
906
1622
|
...rest.store === void 0 ? { events: result.events } : {},
|
|
907
1623
|
snapshot: result.persist(),
|
|
908
1624
|
event
|
|
909
1625
|
});
|
|
910
1626
|
modelCallsSpent += result.usage.modelCalls;
|
|
1627
|
+
endPass(result.persist());
|
|
911
1628
|
}
|
|
912
1629
|
return result;
|
|
913
1630
|
}
|
|
@@ -970,7 +1687,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
970
1687
|
let warnedNonSerializable = false;
|
|
971
1688
|
const runId = `run_${nextRunAgentTraceId++}`;
|
|
972
1689
|
let traceSeq = 0;
|
|
973
|
-
const machineId = machine.config.id ?? machine.id
|
|
1690
|
+
const machineId = machine.config.id ?? machine.id;
|
|
974
1691
|
const machineVersion = resolveMachineVersion(machine);
|
|
975
1692
|
if (options.metadata !== void 0) assertJsonSerializable(options.metadata, "metadata");
|
|
976
1693
|
const initMetadata = options.metadata === void 0 ? void 0 : structuredClone(options.metadata);
|
|
@@ -1113,7 +1830,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1113
1830
|
observe("onEvent", () => options.onEvent?.(entry));
|
|
1114
1831
|
return entry;
|
|
1115
1832
|
};
|
|
1116
|
-
const recordUsage = (usage, source = {}) => {
|
|
1833
|
+
const recordUsage = (usage, source = {}, self) => {
|
|
1117
1834
|
const event = {
|
|
1118
1835
|
type: AGENT_USAGE_EVENT_TYPE,
|
|
1119
1836
|
...source,
|
|
@@ -1124,7 +1841,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1124
1841
|
}
|
|
1125
1842
|
};
|
|
1126
1843
|
let delivered = false;
|
|
1127
|
-
deliverUsageEvent(event, () => rootFacade(() => delivered = true), (dropped) => {
|
|
1844
|
+
deliverUsageEvent(event, () => rootFacade(() => delivered = true, source.kind === "decision" ? void 0 : self), (dropped) => {
|
|
1128
1845
|
if (!finished) return false;
|
|
1129
1846
|
onTrace({
|
|
1130
1847
|
type: "usage.dropped",
|
|
@@ -1156,14 +1873,30 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1156
1873
|
const effectiveSources = provided.sources.actors;
|
|
1157
1874
|
const executors = { ...options.executors };
|
|
1158
1875
|
assertBindable(provided, effectiveSources, executors);
|
|
1159
|
-
const rootFacade = (onSend) => ({
|
|
1876
|
+
const rootFacade = (onSend, from) => ({
|
|
1160
1877
|
getSnapshot: () => current,
|
|
1161
1878
|
send: (event) => {
|
|
1162
1879
|
onSend?.();
|
|
1163
|
-
|
|
1880
|
+
const sender = from;
|
|
1881
|
+
let root = sender;
|
|
1882
|
+
while (root?._parent) root = root._parent;
|
|
1883
|
+
if (sender?.system?.sendEvent && root !== void 0 && root !== sender) sender.system.sendEvent(sender, root, event);
|
|
1884
|
+
else enqueue(event);
|
|
1164
1885
|
}
|
|
1165
1886
|
});
|
|
1166
1887
|
const actorHolder = { actorRef: rootFacade() };
|
|
1888
|
+
const deliveryWaiters = /* @__PURE__ */ new Map();
|
|
1889
|
+
let committedWaiters = [];
|
|
1890
|
+
const releaseCommitted = () => {
|
|
1891
|
+
const released = committedWaiters;
|
|
1892
|
+
committedWaiters = [];
|
|
1893
|
+
for (const release of released) release();
|
|
1894
|
+
};
|
|
1895
|
+
const releaseAllDeliveries = () => {
|
|
1896
|
+
committedWaiters.push(...deliveryWaiters.values());
|
|
1897
|
+
deliveryWaiters.clear();
|
|
1898
|
+
releaseCommitted();
|
|
1899
|
+
};
|
|
1167
1900
|
const runCtx = {
|
|
1168
1901
|
generateText: executors.generateText,
|
|
1169
1902
|
streamText: executors.streamText,
|
|
@@ -1174,8 +1907,13 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1174
1907
|
recordUsage,
|
|
1175
1908
|
actorHolder,
|
|
1176
1909
|
awaitJournal,
|
|
1910
|
+
awaitDelivery: (event) => new Promise((resolve) => {
|
|
1911
|
+
if (finished || stopReason !== void 0) resolve();
|
|
1912
|
+
else deliveryWaiters.set(event, resolve);
|
|
1913
|
+
}),
|
|
1177
1914
|
runId,
|
|
1178
1915
|
schemas: getRegisteredAgentExecutionOptions(machine).schemas,
|
|
1916
|
+
pendingJournal: () => store !== void 0 && journalPending > 0 ? awaitJournal().catch(() => {}) : void 0,
|
|
1179
1917
|
onChildEvent: (self, event) => {
|
|
1180
1918
|
if (finished || event.type === "xstate.stop") return;
|
|
1181
1919
|
const actorPath = actorPathOf(self);
|
|
@@ -1198,6 +1936,10 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1198
1936
|
};
|
|
1199
1937
|
const wrappedSources = {};
|
|
1200
1938
|
for (const [key, logic] of Object.entries(effectiveSources)) {
|
|
1939
|
+
if (isActLogic(logic)) {
|
|
1940
|
+
wrappedSources[key] = bindActLogic(runCtx);
|
|
1941
|
+
continue;
|
|
1942
|
+
}
|
|
1201
1943
|
if (isDecisionLogic(logic)) {
|
|
1202
1944
|
wrappedSources[key] = bindDecisionLogic(logic, runCtx);
|
|
1203
1945
|
continue;
|
|
@@ -1220,9 +1962,9 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1220
1962
|
let started = false;
|
|
1221
1963
|
let finished = false;
|
|
1222
1964
|
let ignoredEvent;
|
|
1223
|
-
const enqueue = (event) => {
|
|
1965
|
+
const enqueue = (event, fromHost = false) => {
|
|
1224
1966
|
if (finished) return;
|
|
1225
|
-
fromMailbox.add(event);
|
|
1967
|
+
if (!fromHost) fromMailbox.add(event);
|
|
1226
1968
|
const waiting = wake;
|
|
1227
1969
|
if (waiting) {
|
|
1228
1970
|
wake = void 0;
|
|
@@ -1254,10 +1996,10 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1254
1996
|
recheck();
|
|
1255
1997
|
}, delay));
|
|
1256
1998
|
};
|
|
1257
|
-
const childrenBusy = (snapshot) => Object.values(snapshot?.children ?? {}).some((child) => {
|
|
1999
|
+
const childrenBusy = (snapshot, nested = false) => Object.values(snapshot?.children ?? {}).some((child) => {
|
|
1258
2000
|
const childSnapshot = child?.getSnapshot?.();
|
|
1259
|
-
if (childSnapshot?.status !== "active") return
|
|
1260
|
-
return isMachineSnapshot(childSnapshot) ? childrenBusy(childSnapshot) : true;
|
|
2001
|
+
if (childSnapshot?.status !== "active") return nested && (childSnapshot?.status === "done" || childSnapshot?.status === "error");
|
|
2002
|
+
return isMachineSnapshot(childSnapshot) ? childrenBusy(childSnapshot, true) : true;
|
|
1261
2003
|
});
|
|
1262
2004
|
const workInFlight = () => childrenBusy(current) || timerHandles.size > 0;
|
|
1263
2005
|
let recheckScheduled = false;
|
|
@@ -1289,12 +2031,28 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1289
2031
|
persistedAtStop = current && boundMachine.getPersistedSnapshot(current);
|
|
1290
2032
|
} catch {}
|
|
1291
2033
|
stopChildren(current);
|
|
2034
|
+
releaseAllDeliveries();
|
|
1292
2035
|
recheck();
|
|
1293
2036
|
};
|
|
1294
|
-
const
|
|
2037
|
+
const abortNow = () => stopRun({
|
|
1295
2038
|
cause: "aborted",
|
|
1296
2039
|
error: options.signal?.reason ?? /* @__PURE__ */ new Error("Aborted")
|
|
1297
2040
|
});
|
|
2041
|
+
let pendingAbort;
|
|
2042
|
+
let abortApplied = false;
|
|
2043
|
+
const sentEvents = /* @__PURE__ */ new WeakSet();
|
|
2044
|
+
let abortTimer;
|
|
2045
|
+
const onAbort = () => {
|
|
2046
|
+
const abortWith = options.abortWith;
|
|
2047
|
+
if (abortWith === void 0 || runtime.send(abortWith.event) === false) {
|
|
2048
|
+
abortNow();
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
pendingAbort = abortWith.event;
|
|
2052
|
+
if (abortWith.timeout !== void 0) abortTimer = setTimeout(() => {
|
|
2053
|
+
if (current?.status === "active") abortNow();
|
|
2054
|
+
}, abortWith.timeout);
|
|
2055
|
+
};
|
|
1298
2056
|
const emitFromRoot = (event) => {
|
|
1299
2057
|
onTrace({
|
|
1300
2058
|
type: "emit",
|
|
@@ -1304,10 +2062,10 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1304
2062
|
observe(`on['${event.type}']`, () => on[event.type]?.(event));
|
|
1305
2063
|
if (event.type !== "*") observe("on['*']", () => on["*"]?.(event));
|
|
1306
2064
|
};
|
|
1307
|
-
const inspect = options.inspect === void 0 ? void 0 : (event) => {
|
|
2065
|
+
const inspect = options.inspect === void 0 ? void 0 : isStableInspection(options.inspect) ? options.inspect : stableInspection((event) => {
|
|
1308
2066
|
if (typeof options.inspect === "function") options.inspect(event);
|
|
1309
2067
|
else options.inspect?.next?.(event);
|
|
1310
|
-
};
|
|
2068
|
+
});
|
|
1311
2069
|
let execution;
|
|
1312
2070
|
execution = createDurable(boundMachine, {
|
|
1313
2071
|
startActor: (actor) => {
|
|
@@ -1373,7 +2131,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1373
2131
|
const { sessionId, actorId } = event;
|
|
1374
2132
|
return !Object.values(current?.children ?? {}).some((child) => sessionId !== void 0 ? child?.sessionId === sessionId : child?.id === actorId);
|
|
1375
2133
|
};
|
|
1376
|
-
|
|
2134
|
+
const runtime = {
|
|
1377
2135
|
async start(init = {}) {
|
|
1378
2136
|
if (started) throw new AgentError("runtime-started", "createAgentRuntime: `start` was already called.");
|
|
1379
2137
|
started = true;
|
|
@@ -1399,7 +2157,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1399
2157
|
let seedInitEntry;
|
|
1400
2158
|
const restoredPersistedSnapshot = () => {
|
|
1401
2159
|
try {
|
|
1402
|
-
const restored = logMachine
|
|
2160
|
+
const restored = restoreMachineSnapshot(logMachine, init.snapshot);
|
|
1403
2161
|
return logMachine.getPersistedSnapshot(restored);
|
|
1404
2162
|
} catch {
|
|
1405
2163
|
return;
|
|
@@ -1551,7 +2309,8 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1551
2309
|
...resumeEvent !== void 0 ? { event: resumeEvent } : {}
|
|
1552
2310
|
});
|
|
1553
2311
|
if (options.signal) {
|
|
1554
|
-
if (options.signal.aborted
|
|
2312
|
+
if (options.signal.aborted && options.abortWith !== void 0) onAbort();
|
|
2313
|
+
else if (options.signal.aborted) stopReason = {
|
|
1555
2314
|
cause: "aborted",
|
|
1556
2315
|
error: options.signal.reason ?? /* @__PURE__ */ new Error("Aborted")
|
|
1557
2316
|
};
|
|
@@ -1591,19 +2350,36 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1591
2350
|
transition(state, event, transitionOptions) {
|
|
1592
2351
|
if (finished) throw new AgentError("runtime-finished", "createAgentRuntime: the run has finished; start a new runtime to continue.");
|
|
1593
2352
|
if (stopReason !== void 0) return [state, []];
|
|
2353
|
+
if (pendingAbort !== void 0 && event !== pendingAbort && !fromMailbox.has(event) && !sentEvents.has(event)) return [state, []];
|
|
1594
2354
|
event = toTimerInput(event);
|
|
1595
2355
|
const attempts = transitionOptions?.attempts ?? attemptsByEvent.get(event);
|
|
1596
2356
|
if (transitionOptions?.attempts !== void 0) assertJsonSerializable(transitionOptions.attempts, "attempts");
|
|
1597
2357
|
const [next, effects] = execution.transition(state, event);
|
|
1598
2358
|
const ignored = !fromMailbox.has(event) && next === state && effects.length === 0;
|
|
2359
|
+
if (event === pendingAbort) {
|
|
2360
|
+
pendingAbort = void 0;
|
|
2361
|
+
abortApplied = !ignored;
|
|
2362
|
+
if (ignored) {
|
|
2363
|
+
abortNow();
|
|
2364
|
+
return [state, []];
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
1599
2367
|
if (ignored) ignoredEvent = event;
|
|
1600
2368
|
appendLogEntry(event, attempts, takeDecidedBy(event));
|
|
2369
|
+
const waiter = deliveryWaiters.get(event);
|
|
2370
|
+
if (waiter) {
|
|
2371
|
+
deliveryWaiters.delete(event);
|
|
2372
|
+
committedWaiters.push(waiter);
|
|
2373
|
+
}
|
|
1601
2374
|
if (stopReason !== void 0) return [state, []];
|
|
1602
2375
|
commit(next, event, ignored);
|
|
1603
2376
|
return [next, effects];
|
|
1604
2377
|
},
|
|
1605
2378
|
async execute(effects) {
|
|
1606
|
-
if (stopReason !== void 0 || finished || effects.length === 0)
|
|
2379
|
+
if (stopReason !== void 0 || finished || effects.length === 0) {
|
|
2380
|
+
releaseCommitted();
|
|
2381
|
+
return;
|
|
2382
|
+
}
|
|
1607
2383
|
try {
|
|
1608
2384
|
await execution.executeEffects(effects);
|
|
1609
2385
|
} catch (error) {
|
|
@@ -1612,6 +2388,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1612
2388
|
error
|
|
1613
2389
|
});
|
|
1614
2390
|
}
|
|
2391
|
+
releaseCommitted();
|
|
1615
2392
|
recheck();
|
|
1616
2393
|
},
|
|
1617
2394
|
async nextEvent() {
|
|
@@ -1623,8 +2400,17 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1623
2400
|
return event;
|
|
1624
2401
|
}
|
|
1625
2402
|
},
|
|
2403
|
+
send(event) {
|
|
2404
|
+
if (finished) throw new AgentError("runtime-finished", "createAgentRuntime: the run has finished; start a new runtime to send it events.");
|
|
2405
|
+
if (stopReason !== void 0 || current !== void 0 && current.status !== "active") return false;
|
|
2406
|
+
sentEvents.add(event);
|
|
2407
|
+
enqueue(event, true);
|
|
2408
|
+
return true;
|
|
2409
|
+
},
|
|
1626
2410
|
async finish() {
|
|
1627
2411
|
if (finished) throw new AgentError("runtime-finished", "createAgentRuntime: `finish` was already called.");
|
|
2412
|
+
clearTimeout(abortTimer);
|
|
2413
|
+
if ((pendingAbort !== void 0 || abortApplied) && current?.status === "active") abortNow();
|
|
1628
2414
|
for (const event of mailbox) if (event.type === "@agent.usage") appendLogEntry(event);
|
|
1629
2415
|
const snapshot = current;
|
|
1630
2416
|
let outcome;
|
|
@@ -1678,6 +2464,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1678
2464
|
return persistedSnapshot;
|
|
1679
2465
|
};
|
|
1680
2466
|
finished = true;
|
|
2467
|
+
releaseAllDeliveries();
|
|
1681
2468
|
const journalAtSettle = journalChain;
|
|
1682
2469
|
const result = {
|
|
1683
2470
|
...outcome,
|
|
@@ -1702,6 +2489,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1702
2489
|
return result;
|
|
1703
2490
|
}
|
|
1704
2491
|
};
|
|
2492
|
+
return runtime;
|
|
1705
2493
|
}
|
|
1706
2494
|
/**
|
|
1707
2495
|
* Wraps a `(snapshot, actorRef) => void` handler into a function usable as
|
|
@@ -1777,4 +2565,26 @@ function isAgentIdle(snapshot) {
|
|
|
1777
2565
|
}) || getAcceptedEvents(snapshot).length > 0;
|
|
1778
2566
|
}
|
|
1779
2567
|
//#endregion
|
|
1780
|
-
|
|
2568
|
+
//#region src/internal/effects.ts
|
|
2569
|
+
/**
|
|
2570
|
+
* A plain copy of an effects object with every callable effect passed
|
|
2571
|
+
* through `wrap`: own and inherited methods alike (a class instance's
|
|
2572
|
+
* prototype methods), each bound to the original object so `this` still
|
|
2573
|
+
* works. Other own properties are copied as they are.
|
|
2574
|
+
*/
|
|
2575
|
+
function mapEffects(effects, wrap) {
|
|
2576
|
+
const source = effects;
|
|
2577
|
+
const out = {};
|
|
2578
|
+
for (let level = effects; level !== null && level !== Object.prototype; level = Object.getPrototypeOf(level)) for (const name of Object.getOwnPropertyNames(level)) {
|
|
2579
|
+
if (name === "constructor" || name in out) continue;
|
|
2580
|
+
const value = source[name];
|
|
2581
|
+
out[name] = typeof value === "function" ? wrap(name, value.bind(effects)) : value;
|
|
2582
|
+
}
|
|
2583
|
+
return out;
|
|
2584
|
+
}
|
|
2585
|
+
/** A stream, as recorders and wrapped effects see one: anything `for await` reads. */
|
|
2586
|
+
function isAsyncIterable(value) {
|
|
2587
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value[Symbol.asyncIterator] === "function";
|
|
2588
|
+
}
|
|
2589
|
+
//#endregion
|
|
2590
|
+
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 };
|