@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.
- package/CHANGELOG.md +138 -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-Ct_GZw_f.mjs → effects-BT_cSY0j.mjs} +1003 -109
- package/dist/{run-agent-s5D32w99.cjs → effects-DDseYtJk.cjs} +1037 -107
- 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-30mH2moE.d.cts} +91 -9
- package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-DlPzBWj-.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-BaNyz6Q3.d.cts} +4 -4
- package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-C1CG_nfX.d.mts} +4 -4
- package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
- 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 +2493 -1502
- package/dist/testing.d.cts +360 -256
- package/dist/testing.d.mts +360 -256
- package/dist/testing.mjs +2489 -1503
- 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-Bm5nvpow.d.cts} +6 -1
- package/dist/{usage-DOoVUGVq.d.mts → usage-BnikdOca.d.mts} +6 -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-ChyX6jq0.mjs +2306 -0
- package/dist/verify-CwlombbC.cjs +2359 -0
- package/dist/{verify-BQpE8hUz.d.cts → verify-DJHfEfm6.d.cts} +213 -14
- package/dist/{verify-CqeuEmIk.d.mts → verify-i9Hiwc5g.d.mts} +213 -14
- 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 +312 -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 +207 -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 +56 -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 +518 -0
- package/docs/validate-and-repair.md +253 -0
- package/docs/verify.md +492 -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 +84 -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
|
@@ -0,0 +1,2306 @@
|
|
|
1
|
+
import { G as executorBoundLogics, R as isTextLogic, et as getJsonSchemaSync, ht as AgentError, mt as isRecord, q as getRegisteredAgentExecutionOptions, w as AGENT_USAGE_EVENT_TYPE } from "./event-log-DkVlk3Rh.mjs";
|
|
2
|
+
import { _ as isEventPattern, g as getHumanEventTypes, h as getAcceptedEvents, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as resolveDecision } from "./decision-m5hGmHpF.mjs";
|
|
3
|
+
import { getInitialMicrosteps, getMicrosteps, getNextTransitions, initialTransition, machineToJSON, transition } from "xstate";
|
|
4
|
+
//#region src/steps.ts
|
|
5
|
+
/**
|
|
6
|
+
* Internal: the pure `(state, event) => (nextState, requests)` view of an
|
|
7
|
+
* agent machine, used by model-free simulation (`simulateAgent`) and tests.
|
|
8
|
+
* An {@link AgentStep} is a snapshot plus the model requests the machine is
|
|
9
|
+
* now waiting on; nothing here executes anything. Hosts use
|
|
10
|
+
* `createAgentRuntime`.
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
/** @internal Normalizes current and legacy XState invoke effect shapes. */
|
|
14
|
+
function getInvokeEffectMetadata(action) {
|
|
15
|
+
if (action.type === "@xstate.spawn") return action;
|
|
16
|
+
if (action.type === "xstate.spawnChild") {
|
|
17
|
+
const params = action.params;
|
|
18
|
+
return params ? {
|
|
19
|
+
...params,
|
|
20
|
+
logic: action.logic
|
|
21
|
+
} : void 0;
|
|
22
|
+
}
|
|
23
|
+
if (action.type === "@xstate.start" && typeof action.src === "string") return action;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The invokes a snapshot is still waiting on, lowered to the same spawn-effect
|
|
27
|
+
* shape {@link getAgentRequests} reads. Derived from the snapshot's live
|
|
28
|
+
* children rather than the last transition's actions, so a state that invokes
|
|
29
|
+
* several actors at once (an `invoke: [...]` array, or parallel regions each
|
|
30
|
+
* invoking) keeps reporting the siblings after the first one settles —
|
|
31
|
+
* including when the settled invoke's `onDone` is targetless and starts
|
|
32
|
+
* nothing new.
|
|
33
|
+
*
|
|
34
|
+
* Entries are ordered by invoke id, so a walker that resolves one invoke per
|
|
35
|
+
* step is deterministic.
|
|
36
|
+
*
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
function getPendingInvokes(snapshot) {
|
|
40
|
+
const children = snapshot.children ?? {};
|
|
41
|
+
return Object.keys(children).sort().flatMap((id) => {
|
|
42
|
+
const child = children[id];
|
|
43
|
+
const childSnapshot = child?.getSnapshot?.();
|
|
44
|
+
if (!child || childSnapshot?.status !== "active") return [];
|
|
45
|
+
return [{
|
|
46
|
+
type: "@xstate.spawn",
|
|
47
|
+
id,
|
|
48
|
+
src: child.src,
|
|
49
|
+
input: childSnapshot.input,
|
|
50
|
+
logic: child.logic
|
|
51
|
+
}];
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Scans a set of executable actions (as returned by xstate's `transition`/
|
|
56
|
+
* `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
|
|
57
|
+
* lowers each into an {@link AgentStepRequest}. Pass `options.machine` to
|
|
58
|
+
* pre-fill `schemas`/`actors` from the machine's registered `setupAgent`
|
|
59
|
+
* options instead of passing them by hand.
|
|
60
|
+
* `options.snapshot` is required to resolve a decision's candidate events
|
|
61
|
+
* (intersecting declared `allowedEvents` with what's currently legal) — omit
|
|
62
|
+
* it and decision requests report an empty `events` list.
|
|
63
|
+
*
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
function getAgentRequests(actions, { machine, ...options } = {}) {
|
|
67
|
+
if (machine) options = {
|
|
68
|
+
...getRegisteredAgentExecutionOptions(machine),
|
|
69
|
+
...options
|
|
70
|
+
};
|
|
71
|
+
return actions.flatMap((action) => {
|
|
72
|
+
const metadata = getInvokeEffectMetadata(action);
|
|
73
|
+
const params = metadata && typeof metadata.src !== "string" && typeof metadata.id === "string" && (isTextLogic(metadata.logic) || isDecisionLogic(metadata.logic)) ? {
|
|
74
|
+
...metadata,
|
|
75
|
+
src: metadata.id
|
|
76
|
+
} : metadata;
|
|
77
|
+
if (!params || typeof params.src !== "string") return [];
|
|
78
|
+
if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
|
|
79
|
+
const registeredLogic = isTextLogic(params.logic) || isDecisionLogic(params.logic) ? params.logic : options.actors?.[params.src];
|
|
80
|
+
if (isDecisionLogic(registeredLogic)) {
|
|
81
|
+
const decisionRequest = registeredLogic.request(params.input);
|
|
82
|
+
const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
|
|
83
|
+
const events = options.snapshot ? getAcceptedEvents(options.snapshot, {
|
|
84
|
+
events: options.events,
|
|
85
|
+
schemas: options.schemas,
|
|
86
|
+
eventTypes: allowedEventTypes,
|
|
87
|
+
actor: "agent"
|
|
88
|
+
}) : [];
|
|
89
|
+
const humanEventTypes = options.snapshot ? getHumanEventTypes(options.snapshot) : /* @__PURE__ */ new Set();
|
|
90
|
+
return [{
|
|
91
|
+
...decisionRequest,
|
|
92
|
+
id: params.id,
|
|
93
|
+
events,
|
|
94
|
+
...decisionRequest.options ? { options: decisionRequest.options.filter((option) => !humanEventTypes.has(option.event.type)) } : {}
|
|
95
|
+
}];
|
|
96
|
+
}
|
|
97
|
+
const textLogic = isTextLogic(registeredLogic) ? registeredLogic : void 0;
|
|
98
|
+
const input = textLogic ? textLogic.request(params.input) : void 0;
|
|
99
|
+
if (!input) return [];
|
|
100
|
+
return [{
|
|
101
|
+
kind: "text",
|
|
102
|
+
id: params.id,
|
|
103
|
+
src: params.src,
|
|
104
|
+
...textLogic ? { mode: textLogic.mode } : {},
|
|
105
|
+
input,
|
|
106
|
+
tools: input.tools ?? {},
|
|
107
|
+
events: []
|
|
108
|
+
}];
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Builds the canonical `xstate.done.actor` event xstate's `transition()`
|
|
113
|
+
* expects to resolve a spawned invoke — including the child session identity
|
|
114
|
+
* that rejects a stale completion from an earlier incarnation.
|
|
115
|
+
*
|
|
116
|
+
* @internal
|
|
117
|
+
*/
|
|
118
|
+
function doneEvent(snapshot, request, output) {
|
|
119
|
+
const id = typeof request === "string" ? request : request.id;
|
|
120
|
+
const child = snapshot.children[id];
|
|
121
|
+
return {
|
|
122
|
+
type: "xstate.done.actor",
|
|
123
|
+
actorId: id,
|
|
124
|
+
...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
|
|
125
|
+
output
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* The `xstate.error.actor` counterpart of {@link doneEvent} — the event a
|
|
130
|
+
* failed invoke delivers, which `onError` transitions observe. Carries the
|
|
131
|
+
* same child session identity, so xstate does not discard it as stale.
|
|
132
|
+
*
|
|
133
|
+
* @internal
|
|
134
|
+
*/
|
|
135
|
+
function errorEvent(snapshot, request, error) {
|
|
136
|
+
const id = typeof request === "string" ? request : request.id;
|
|
137
|
+
const child = snapshot.children[id];
|
|
138
|
+
return {
|
|
139
|
+
type: "xstate.error.actor",
|
|
140
|
+
actorId: id,
|
|
141
|
+
...typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {},
|
|
142
|
+
error
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Applies a request's `output` as a done event (or, with `outcome: 'error'`,
|
|
147
|
+
* its `output` as the invoke's error) via `transition(...)`, returning the raw
|
|
148
|
+
* `[snapshot, actions]` tuple. Lower-level than {@link resolveAgentStep} /
|
|
149
|
+
* {@link rejectAgentStep} — those helpers wrap this and also run
|
|
150
|
+
* {@link getAgentRequests} to produce the next {@link AgentStep}.
|
|
151
|
+
*
|
|
152
|
+
* @internal
|
|
153
|
+
*/
|
|
154
|
+
function transitionResult(logic, snapshot, request, output, outcome = "output") {
|
|
155
|
+
const event = outcome === "error" ? errorEvent(snapshot, request, output) : doneEvent(snapshot, request, output);
|
|
156
|
+
const result = transition(logic, snapshot, event);
|
|
157
|
+
applyFinalStateOutput(logic, result[0], event);
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Starts a machine and returns its first {@link AgentStep} — the step-path
|
|
162
|
+
* equivalent of `initialTransition` plus request discovery. Begins the
|
|
163
|
+
* durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
|
|
164
|
+
* (via {@link executeAgentRequest} for `kind: 'text'`, or
|
|
165
|
+
* {@link resolveDecision} for `kind: 'decision'`), then advance with
|
|
166
|
+
* {@link resolveAgentStep} or {@link transitionAgentStep}.
|
|
167
|
+
*/
|
|
168
|
+
function initialAgentStep(machine, input, options) {
|
|
169
|
+
const [snapshot, actions] = initialTransition(machine, input);
|
|
170
|
+
return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Applies an externally-sent event (e.g. a decision's chosen event, or a
|
|
174
|
+
* human's reply) and returns the next {@link AgentStep}. Accepts **either**
|
|
175
|
+
* a raw snapshot **or** a prior `AgentStep` as the second argument —
|
|
176
|
+
* `.snapshot` is unwrapped automatically, so callers can thread the whole
|
|
177
|
+
* step object through without manually plucking the snapshot out.
|
|
178
|
+
*/
|
|
179
|
+
function transitionAgentStep(machine, snapshotOrStep, event, options) {
|
|
180
|
+
const snapshot = isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep;
|
|
181
|
+
const [nextSnapshot, actions] = transition(machine, snapshot, event);
|
|
182
|
+
return createAgentStep(machine, nextSnapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Applies a resolved text request's output (a `kind: 'text'`
|
|
186
|
+
* {@link AgentRequest} — not a decision) as a done event and returns the
|
|
187
|
+
* next {@link AgentStep}. For decisions, resolve with `resolveDecision`
|
|
188
|
+
* (which returns a {@link ChosenEvent}) and apply it with
|
|
189
|
+
* {@link transitionAgentStep} instead — a decision has no output value of
|
|
190
|
+
* its own to feed here.
|
|
191
|
+
*/
|
|
192
|
+
function resolveAgentStep(machine, step, request, output, options) {
|
|
193
|
+
const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
|
|
194
|
+
return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Rejects a pending invoke — the failure counterpart of
|
|
198
|
+
* {@link resolveAgentStep}. Delivers `error` as the invoke's
|
|
199
|
+
* `xstate.error.actor` event, so the machine takes that invoke's `onError`
|
|
200
|
+
* transition and returns the next {@link AgentStep}. With no `onError` in
|
|
201
|
+
* scope the returned step's snapshot has `status: 'error'`, exactly as a live
|
|
202
|
+
* run's failed invoke does.
|
|
203
|
+
*
|
|
204
|
+
* A durable host replays a failed call with this: the log says the call
|
|
205
|
+
* failed, so the replay rejects the invoke instead of resolving it. Scripted
|
|
206
|
+
* playthroughs use it too — see `simulateAgent`'s `script.errors`.
|
|
207
|
+
*
|
|
208
|
+
* `error` can be any value. An `Error` instance is the usual one, but a plain
|
|
209
|
+
* object (`{ code: 'truncated' }`) reaches the `onError` transition as
|
|
210
|
+
* `event.error` untouched, so a machine that branches on a failure code is
|
|
211
|
+
* testable without constructing a provider's error class.
|
|
212
|
+
*/
|
|
213
|
+
function rejectAgentStep(machine, step, request, error, options) {
|
|
214
|
+
const [snapshot, actions] = transitionResult(machine, step.snapshot, request, error, "error");
|
|
215
|
+
return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
216
|
+
}
|
|
217
|
+
function createAgentStep(machine, snapshot, actions, options) {
|
|
218
|
+
applyFinalStateOutput(machine, snapshot);
|
|
219
|
+
return {
|
|
220
|
+
snapshot,
|
|
221
|
+
actions,
|
|
222
|
+
requests: getAgentRequests(getPendingInvokes(snapshot), {
|
|
223
|
+
...options,
|
|
224
|
+
snapshot
|
|
225
|
+
}),
|
|
226
|
+
done: snapshot.status === "done"
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function resolveStateValueConfig(config, value) {
|
|
230
|
+
if (typeof value === "string") return config.states?.[value];
|
|
231
|
+
if (!value || typeof value !== "object") return;
|
|
232
|
+
for (const [key, childValue] of Object.entries(value)) {
|
|
233
|
+
const childConfig = config.states?.[key];
|
|
234
|
+
if (!childConfig) continue;
|
|
235
|
+
if (childConfig.type === "final") return childConfig;
|
|
236
|
+
const nested = resolveStateValueConfig(childConfig, childValue);
|
|
237
|
+
if (nested) return nested;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function applyFinalStateOutput(logic, snapshot, event) {
|
|
241
|
+
const machineSnapshot = snapshot;
|
|
242
|
+
if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
|
|
243
|
+
const config = logic.config;
|
|
244
|
+
if (!config) return;
|
|
245
|
+
const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
|
|
246
|
+
if (output === void 0) return;
|
|
247
|
+
machineSnapshot.output = typeof output === "function" ? output({
|
|
248
|
+
context: machineSnapshot.context,
|
|
249
|
+
event
|
|
250
|
+
}) : output;
|
|
251
|
+
}
|
|
252
|
+
function isAgentStep(value) {
|
|
253
|
+
return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
|
|
254
|
+
}
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/verify.ts
|
|
257
|
+
/**
|
|
258
|
+
* Provider-free verification for agent machines — static lint checks plus
|
|
259
|
+
* model-free simulation over the pure step path. Coding agents generate these
|
|
260
|
+
* machines; this module lets them close the loop and self-verify WITHOUT any
|
|
261
|
+
* API keys or model calls.
|
|
262
|
+
*
|
|
263
|
+
* - {@link lintAgentMachine} — static structural checks over a built machine
|
|
264
|
+
* (works for TS-authored and `setupAgent.fromConfig`-compiled machines).
|
|
265
|
+
* - {@link simulateAgent} — a deterministic, scripted playthrough.
|
|
266
|
+
* - {@link explorePaths} — enumerates decision/external branches to a bounded
|
|
267
|
+
* depth and reports reached states and terminal outcomes.
|
|
268
|
+
* - {@link canReach} — a thin wrapper over {@link explorePaths} answering
|
|
269
|
+
* "can this state (or snapshot predicate) be reached?" with a witness path.
|
|
270
|
+
*
|
|
271
|
+
* @module
|
|
272
|
+
*/
|
|
273
|
+
const DECIDE_SRC = "agent.decide";
|
|
274
|
+
const ACT_SRC = "agent.act";
|
|
275
|
+
function normalizeInvokes(invoke) {
|
|
276
|
+
if (invoke === void 0 || invoke === null) return [];
|
|
277
|
+
return Array.isArray(invoke) ? invoke : [invoke];
|
|
278
|
+
}
|
|
279
|
+
function buildStateIndex(rootConfig) {
|
|
280
|
+
const index = /* @__PURE__ */ new Map();
|
|
281
|
+
const walk = (states, parentPath) => {
|
|
282
|
+
for (const [name, config] of Object.entries(states ?? {})) {
|
|
283
|
+
const path = parentPath ? `${parentPath}.${name}` : name;
|
|
284
|
+
const hasChildren = !!config.states && Object.keys(config.states).length > 0;
|
|
285
|
+
index.set(path, {
|
|
286
|
+
path,
|
|
287
|
+
config,
|
|
288
|
+
parentPath,
|
|
289
|
+
isFinal: config.type === "final",
|
|
290
|
+
isParallel: config.type === "parallel",
|
|
291
|
+
isCompound: hasChildren && config.type !== "parallel",
|
|
292
|
+
invokes: normalizeInvokes(config.invoke)
|
|
293
|
+
});
|
|
294
|
+
if (hasChildren) walk(config.states, path);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
walk(rootConfig.states, "");
|
|
298
|
+
return index;
|
|
299
|
+
}
|
|
300
|
+
function ancestorChain(node, index) {
|
|
301
|
+
const chain = [];
|
|
302
|
+
let parent = node.parentPath;
|
|
303
|
+
while (parent) {
|
|
304
|
+
const parentNode = index.get(parent);
|
|
305
|
+
if (!parentNode) break;
|
|
306
|
+
chain.push(parentNode);
|
|
307
|
+
parent = parentNode.parentPath;
|
|
308
|
+
}
|
|
309
|
+
return chain;
|
|
310
|
+
}
|
|
311
|
+
function hasNonEmptyOn(config) {
|
|
312
|
+
return !!config.on && Object.keys(config.on).length > 0;
|
|
313
|
+
}
|
|
314
|
+
function isDecisionInvoke(src, actors) {
|
|
315
|
+
if (typeof src === "string") return src === DECIDE_SRC || isDecisionLogic(actors[src]);
|
|
316
|
+
return isDecisionLogic(src);
|
|
317
|
+
}
|
|
318
|
+
function isAgentLogicNeedingBinding(src) {
|
|
319
|
+
return (isTextLogic(src) || isDecisionLogic(src)) && !executorBoundLogics.has(src);
|
|
320
|
+
}
|
|
321
|
+
function safeJsonSchema(schema) {
|
|
322
|
+
try {
|
|
323
|
+
return getJsonSchemaSync(schema);
|
|
324
|
+
} catch {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function checkDecideWithoutEvents(ctx) {
|
|
329
|
+
const out = [];
|
|
330
|
+
for (const node of ctx.index.values()) for (const invoke of node.invokes) {
|
|
331
|
+
if (!isDecisionInvoke(invoke.src, ctx.actors)) continue;
|
|
332
|
+
const selfHandles = hasNonEmptyOn(node.config);
|
|
333
|
+
const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
|
|
334
|
+
const invokeObserves = invoke.onDone !== void 0;
|
|
335
|
+
if (selfHandles || ancestorHandles || invokeObserves) continue;
|
|
336
|
+
const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
|
|
337
|
+
out.push({
|
|
338
|
+
code: "decide-without-events",
|
|
339
|
+
severity: "error",
|
|
340
|
+
path: node.path,
|
|
341
|
+
message: `State '${node.path}' invokes decision source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the decision's chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
function literalAllowedEvents(json, path, index) {
|
|
347
|
+
let node = json;
|
|
348
|
+
for (const key of path.split(".")) node = node?.states?.[key];
|
|
349
|
+
let input = normalizeInvokes(node?.invoke)[index]?.input;
|
|
350
|
+
if (isRecord(input) && typeof input["@expr"] === "string") try {
|
|
351
|
+
input = JSON.parse(input["@expr"]);
|
|
352
|
+
} catch {
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const allowedEvents = isRecord(input) ? input.allowedEvents : void 0;
|
|
356
|
+
return typeof allowedEvents === "string" ? [allowedEvents] : Array.isArray(allowedEvents) ? allowedEvents : void 0;
|
|
357
|
+
}
|
|
358
|
+
function handlesAsHuman(config, eventType) {
|
|
359
|
+
const transitions = config.on?.[eventType];
|
|
360
|
+
return (Array.isArray(transitions) ? transitions : [transitions]).some((transition) => !!transition && typeof transition === "object" && transition.meta?.actor === "human");
|
|
361
|
+
}
|
|
362
|
+
function checkDecideAllowsHumanEvent(ctx) {
|
|
363
|
+
const out = [];
|
|
364
|
+
for (const node of ctx.index.values()) for (const [index, invoke] of node.invokes.entries()) {
|
|
365
|
+
const isAct = invoke.src === ACT_SRC;
|
|
366
|
+
if (!isAct && !isDecisionInvoke(invoke.src, ctx.actors)) continue;
|
|
367
|
+
const allowedEvents = literalAllowedEvents(ctx.json, node.path, index);
|
|
368
|
+
if (!allowedEvents) continue;
|
|
369
|
+
const configs = [
|
|
370
|
+
node.config,
|
|
371
|
+
...ancestorChain(node, ctx.index).map((ancestor) => ancestor.config),
|
|
372
|
+
ctx.config
|
|
373
|
+
];
|
|
374
|
+
for (const type of allowedEvents) {
|
|
375
|
+
if (typeof type !== "string" || isEventPattern(type) || !configs.some((config) => handlesAsHuman(config, type))) continue;
|
|
376
|
+
out.push({
|
|
377
|
+
code: "decide-allows-human-event",
|
|
378
|
+
severity: "error",
|
|
379
|
+
path: node.path,
|
|
380
|
+
message: `State '${node.path}' lets ${isAct ? "'agent.act'" : "a decision"} choose '${type}', but a transition tagged 'meta: { actor: "human" }' handles it, so the model is never offered it. Remove '${type}' from 'allowedEvents', or drop the tag if a model may send it.`
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
function checkDirectObjectSrc(ctx) {
|
|
387
|
+
const out = [];
|
|
388
|
+
for (const node of ctx.index.values()) for (const invoke of node.invokes) {
|
|
389
|
+
const src = invoke.src;
|
|
390
|
+
if (typeof src === "string" || !src || typeof src !== "object") continue;
|
|
391
|
+
if (!isAgentLogicNeedingBinding(src)) continue;
|
|
392
|
+
out.push({
|
|
393
|
+
code: "direct-object-src",
|
|
394
|
+
severity: "warning",
|
|
395
|
+
path: node.path,
|
|
396
|
+
message: `State '${node.path}' invokes a direct-object agent logic. Direct-object invoke srcs cannot be rebound by the agent runtime, so they inherit no host executors — call '.withExecutor(...)' on the logic, or register it as a string-keyed actor source (machine.provide({ actors: { name: logic } })) and invoke it by name.`
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
function handlesActorError(config) {
|
|
402
|
+
if (config["onError"] !== void 0) return true;
|
|
403
|
+
return Object.keys(config.on ?? {}).some((type) => type === "*" || type.startsWith("xstate.error"));
|
|
404
|
+
}
|
|
405
|
+
function checkInvokeWithoutOnError(ctx) {
|
|
406
|
+
const out = [];
|
|
407
|
+
for (const node of ctx.index.values()) for (const invoke of node.invokes) {
|
|
408
|
+
if (invoke.onError !== void 0 || handlesActorError(node.config)) continue;
|
|
409
|
+
if (handlesActorError(ctx.config) || ancestorChain(node, ctx.index).some((ancestor) => handlesActorError(ancestor.config))) continue;
|
|
410
|
+
const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
|
|
411
|
+
out.push({
|
|
412
|
+
code: "invoke-without-on-error",
|
|
413
|
+
severity: "warning",
|
|
414
|
+
path: node.path,
|
|
415
|
+
message: `State '${node.path}' invokes '${srcName}' with no 'onError' transition, and no ancestor handles an actor error. A rejected request or actor puts the machine in an error state with no modeled recovery. Add 'onError' (a 'failed' final state, or a bounded retry).`
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
const LINT_CHECKS = [
|
|
421
|
+
checkDecideWithoutEvents,
|
|
422
|
+
checkDecideAllowsHumanEvent,
|
|
423
|
+
checkDirectObjectSrc,
|
|
424
|
+
checkInvokeWithoutOnError
|
|
425
|
+
];
|
|
426
|
+
/**
|
|
427
|
+
* Runs static structural checks over a built agent machine and returns the
|
|
428
|
+
* findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
|
|
429
|
+
* TS-authored (`setupAgent(...).createMachine(...)`) and
|
|
430
|
+
* `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
|
|
431
|
+
* plus the schemas/actor sources the library already retains per machine.
|
|
432
|
+
*
|
|
433
|
+
* No model calls, no API keys — a coding agent that emits an agent machine can
|
|
434
|
+
* call this to catch agent-specific mistakes such as undeliverable decisions,
|
|
435
|
+
* un-rebindable request sources, and an unhandled transcript event. General
|
|
436
|
+
* state-machine lint belongs to XState tooling.
|
|
437
|
+
*
|
|
438
|
+
* Pass `{ throw: true }` for the one-liner form used in tests and generation
|
|
439
|
+
* loops: it returns silently when the machine is clean and throws
|
|
440
|
+
* {@link AgentLintError} (findings on `.diagnostics`) on error-severity
|
|
441
|
+
* findings, or on warnings too with `{ throw: true, warnings: true }`.
|
|
442
|
+
*
|
|
443
|
+
* @example
|
|
444
|
+
* ```ts
|
|
445
|
+
* const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
|
|
446
|
+
* if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
|
|
447
|
+
* ```
|
|
448
|
+
*
|
|
449
|
+
* @example Throwing form
|
|
450
|
+
* ```ts
|
|
451
|
+
* test('agent machine is structurally sound', () => {
|
|
452
|
+
* lintAgentMachine(machine, { throw: true });
|
|
453
|
+
* });
|
|
454
|
+
* ```
|
|
455
|
+
*/
|
|
456
|
+
function lintAgentMachine(machine, options = {}) {
|
|
457
|
+
const config = machine.config ?? {};
|
|
458
|
+
const index = buildStateIndex(config);
|
|
459
|
+
const registered = getRegisteredAgentExecutionOptions(machine);
|
|
460
|
+
let json;
|
|
461
|
+
try {
|
|
462
|
+
json = machineToJSON(machine);
|
|
463
|
+
} catch {
|
|
464
|
+
json = void 0;
|
|
465
|
+
}
|
|
466
|
+
const ctx = {
|
|
467
|
+
config,
|
|
468
|
+
json,
|
|
469
|
+
index,
|
|
470
|
+
schemas: registered.schemas,
|
|
471
|
+
actors: registered.actors ?? machine.sources?.actors ?? {}
|
|
472
|
+
};
|
|
473
|
+
const disabled = new Set(options.disable ?? []);
|
|
474
|
+
const ignored = options.ignore ?? [];
|
|
475
|
+
const diagnostics = LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code) && !ignored.some((entry) => entry.code === d.code && entry.path === d.path));
|
|
476
|
+
if (options.throw) {
|
|
477
|
+
const failing = options.warnings ? diagnostics : diagnostics.filter((d) => d.severity === "error");
|
|
478
|
+
if (failing.length > 0) throw new AgentLintError(machine.id, failing);
|
|
479
|
+
}
|
|
480
|
+
return diagnostics;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Thrown by `lintAgentMachine(machine, { throw: true })` (and its
|
|
484
|
+
* {@link assertAgentMachine} alias) when lint finds failing diagnostics.
|
|
485
|
+
* `diagnostics` holds the findings; the message lists them one per finding,
|
|
486
|
+
* so a test runner's failure output reads like the CLI's lint report.
|
|
487
|
+
*/
|
|
488
|
+
var AgentLintError = class extends AgentError {
|
|
489
|
+
diagnostics;
|
|
490
|
+
constructor(machineId, diagnostics) {
|
|
491
|
+
const lines = diagnostics.map((d) => ` ${d.severity === "error" ? "error" : "warn "} ${d.code} ${d.path}\n ${d.message}`);
|
|
492
|
+
super("lint-failed", `Agent machine '${machineId}' failed lint (${diagnostics.length} finding(s)):\n${lines.join("\n")}`);
|
|
493
|
+
this.name = "AgentLintError";
|
|
494
|
+
this.diagnostics = diagnostics;
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
/**
|
|
498
|
+
* Asserts a machine passes {@link lintAgentMachine}: returns silently when
|
|
499
|
+
* clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
|
|
500
|
+
* otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
|
|
501
|
+
* Fails on error-severity findings; set `warnings: true` to fail on warnings
|
|
502
|
+
* too. The one-liner for tests and generation loops:
|
|
503
|
+
*
|
|
504
|
+
* @example
|
|
505
|
+
* ```ts
|
|
506
|
+
* test('agent machine is structurally sound', () => {
|
|
507
|
+
* assertAgentMachine(machine);
|
|
508
|
+
* });
|
|
509
|
+
* ```
|
|
510
|
+
*/
|
|
511
|
+
function assertAgentMachine(machine, options = {}) {
|
|
512
|
+
lintAgentMachine(machine, {
|
|
513
|
+
...options,
|
|
514
|
+
throw: true
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
function pendingInvokes(step) {
|
|
518
|
+
const out = [];
|
|
519
|
+
const children = step.snapshot.children ?? {};
|
|
520
|
+
for (const metadata of getPendingInvokes(step.snapshot)) {
|
|
521
|
+
const src = typeof metadata.src === "string" ? metadata.src : metadata.id;
|
|
522
|
+
if (typeof src === "string") {
|
|
523
|
+
const ref = children[metadata.id];
|
|
524
|
+
out.push({
|
|
525
|
+
id: metadata.id,
|
|
526
|
+
src,
|
|
527
|
+
input: metadata.input ?? ref?.options?.input,
|
|
528
|
+
logic: metadata.logic,
|
|
529
|
+
ref
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return out;
|
|
534
|
+
}
|
|
535
|
+
function takeFromQueue(channel, src) {
|
|
536
|
+
const queue = channel?.[src];
|
|
537
|
+
if (queue && queue.length > 0) return {
|
|
538
|
+
found: true,
|
|
539
|
+
value: queue.shift()
|
|
540
|
+
};
|
|
541
|
+
return { found: false };
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Deterministically plays a machine through, resolving each request from a
|
|
545
|
+
* {@link SimulationScript} instead of a model — no API keys, no model calls.
|
|
546
|
+
* Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
|
|
547
|
+
* the real transition logic. Returns the terminal `status`, final `snapshot`,
|
|
548
|
+
* and a `trail` of every step taken.
|
|
549
|
+
*
|
|
550
|
+
* Decisions run through the live run's own validation/retry core,
|
|
551
|
+
* {@link resolveDecision}, with the script standing in for the model: each
|
|
552
|
+
* attempt consumes the next queued {@link ChosenEvent} for that src, so an
|
|
553
|
+
* unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
|
|
554
|
+
* — the next queued decision is tried, exactly as a live run re-asks the
|
|
555
|
+
* model. The decision logic's `maxRetries` caps attempts as it would live;
|
|
556
|
+
* when retries continue past the end of the queue, the last queued decision
|
|
557
|
+
* repeats (a scripted model that insists). The repeat applies only within one
|
|
558
|
+
* decision request's retries — each new decision request must have its own
|
|
559
|
+
* queued entry, or the dry-script error throws as usual. Exhausting all
|
|
560
|
+
* attempts delivers
|
|
561
|
+
* the resulting {@link AgentDecisionExhaustedError} to the machine as the
|
|
562
|
+
* decision invoke's error (so an `onError` transition observes it, as it
|
|
563
|
+
* would live); with no `onError` to catch it, it is thrown.
|
|
564
|
+
*
|
|
565
|
+
* Throws a descriptive error when the script runs dry mid-request, naming the
|
|
566
|
+
* pending request's kind, src, and id so the missing scripted response is
|
|
567
|
+
* obvious.
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* ```ts
|
|
571
|
+
* const { status, snapshot } = simulateAgent(machine, {
|
|
572
|
+
* input: { topic: 'state machines' },
|
|
573
|
+
* script: {
|
|
574
|
+
* decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
|
|
575
|
+
* events: [{ type: 'APPROVE' }], // crosses the human gate
|
|
576
|
+
* },
|
|
577
|
+
* });
|
|
578
|
+
* ```
|
|
579
|
+
*/
|
|
580
|
+
async function simulateAgent(machine, options) {
|
|
581
|
+
const maxSteps = options.maxSteps ?? 100;
|
|
582
|
+
const script = {
|
|
583
|
+
text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
|
|
584
|
+
decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
|
|
585
|
+
invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr]),
|
|
586
|
+
errors: mapValues(options.script.errors ?? {}, (arr) => [...arr]),
|
|
587
|
+
events: [...options.script.events ?? []]
|
|
588
|
+
};
|
|
589
|
+
let step = initialAgentStep(machine, options.input);
|
|
590
|
+
const trail = [{ state: step.snapshot.value }];
|
|
591
|
+
for (let i = 0; i < maxSteps; i++) {
|
|
592
|
+
if (step.done) return {
|
|
593
|
+
status: "done",
|
|
594
|
+
snapshot: step.snapshot,
|
|
595
|
+
trail
|
|
596
|
+
};
|
|
597
|
+
const request = step.requests[0];
|
|
598
|
+
if (request) {
|
|
599
|
+
if (request.kind === "decision") {
|
|
600
|
+
const invokeMeta = findInvokeMetadata(step, request.id);
|
|
601
|
+
const src = invokeMeta?.src ?? request.id;
|
|
602
|
+
const decisionSrc = src in (script.decisions ?? {}) ? src : request.id in (script.decisions ?? {}) ? request.id : src;
|
|
603
|
+
const errorSrc = queueKey(script.errors, src, request.id);
|
|
604
|
+
const failure = takeFromQueue(script.errors, errorSrc);
|
|
605
|
+
if (failure.found) {
|
|
606
|
+
step = rejectScriptedRequest(machine, step, request.id, failure.value, {
|
|
607
|
+
kind: "decision",
|
|
608
|
+
src: errorSrc,
|
|
609
|
+
trail
|
|
610
|
+
});
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
step = await applyScriptedDecision(machine, step, request, decisionSrc, invokeMeta?.logic, script, trail);
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
const failure = takeFromQueue(script.errors, request.src);
|
|
617
|
+
if (failure.found) {
|
|
618
|
+
step = rejectScriptedRequest(machine, step, request, failure.value, {
|
|
619
|
+
kind: "text",
|
|
620
|
+
src: request.src,
|
|
621
|
+
trail
|
|
622
|
+
});
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
const taken = takeFromQueue(script.text, request.src);
|
|
626
|
+
if (!taken.found) throw scriptDryError("text", request.src, request.id);
|
|
627
|
+
step = resolveAgentStep(machine, step, request, asTextResult(taken.value));
|
|
628
|
+
trail.push({
|
|
629
|
+
state: step.snapshot.value,
|
|
630
|
+
resolvedRequest: {
|
|
631
|
+
kind: "text",
|
|
632
|
+
src: request.src,
|
|
633
|
+
id: request.id,
|
|
634
|
+
outcome: "output"
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
const [invoke] = pendingInvokes(step);
|
|
640
|
+
if (invoke) {
|
|
641
|
+
const failure = takeFromQueue(script.errors, invoke.src);
|
|
642
|
+
if (failure.found) {
|
|
643
|
+
step = rejectScriptedRequest(machine, step, invoke.id, failure.value, {
|
|
644
|
+
kind: "invoke",
|
|
645
|
+
src: invoke.src,
|
|
646
|
+
trail
|
|
647
|
+
});
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
const taken = takeFromQueue(script.invokes, invoke.src);
|
|
651
|
+
if (!taken.found) throw scriptDryError("invoke", invoke.src, invoke.id);
|
|
652
|
+
step = resolveAgentStep(machine, step, invoke.id, taken.value);
|
|
653
|
+
trail.push({
|
|
654
|
+
state: step.snapshot.value,
|
|
655
|
+
resolvedRequest: {
|
|
656
|
+
kind: "invoke",
|
|
657
|
+
src: invoke.src,
|
|
658
|
+
id: invoke.id,
|
|
659
|
+
outcome: "output"
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const external = script.events;
|
|
665
|
+
if (external.length > 0) {
|
|
666
|
+
const event = external.shift();
|
|
667
|
+
if (!step.snapshot.can(event)) throw new Error(`simulateAgent: scripted external event '${event.type}' cannot be taken in state ${JSON.stringify(step.snapshot.value)} (no handler, or its guard rejected it). A live run's send would be silently dropped here; fix the script's \`events\` queue.`);
|
|
668
|
+
step = transitionAgentStep(machine, step, event);
|
|
669
|
+
trail.push({
|
|
670
|
+
state: step.snapshot.value,
|
|
671
|
+
appliedEvent: event,
|
|
672
|
+
external: true
|
|
673
|
+
});
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
return {
|
|
677
|
+
status: "idle",
|
|
678
|
+
snapshot: step.snapshot,
|
|
679
|
+
trail
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
return {
|
|
683
|
+
status: "exhausted",
|
|
684
|
+
snapshot: step.snapshot,
|
|
685
|
+
trail
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
function queueKey(channel, src, id) {
|
|
689
|
+
return channel && !(src in channel) && id in channel ? id : src;
|
|
690
|
+
}
|
|
691
|
+
function rejectScriptedRequest(machine, step, request, error, entry) {
|
|
692
|
+
const id = typeof request === "string" ? request : request.id;
|
|
693
|
+
const next = rejectAgentStep(machine, step, request, error);
|
|
694
|
+
if (next.snapshot.status === "error") throw unhandledScriptedError(error, entry.kind, entry.src, id);
|
|
695
|
+
entry.trail.push({
|
|
696
|
+
state: next.snapshot.value,
|
|
697
|
+
resolvedRequest: {
|
|
698
|
+
kind: entry.kind,
|
|
699
|
+
src: entry.src,
|
|
700
|
+
id,
|
|
701
|
+
outcome: "error",
|
|
702
|
+
error
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
return next;
|
|
706
|
+
}
|
|
707
|
+
function unhandledScriptedError(error, kind, src, id) {
|
|
708
|
+
if (error instanceof Error) return error;
|
|
709
|
+
return new Error(`simulateAgent: the scripted error for the ${kind} request '${src}' (id '${id}') reached no onError transition, so the machine errored. Add an onError to that invoke, or drop the errors['${src}'] entry.`, { cause: error });
|
|
710
|
+
}
|
|
711
|
+
async function applyScriptedDecision(machine, step, request, decisionSrc, invokeLogic, script, trail) {
|
|
712
|
+
const dequeued = [];
|
|
713
|
+
const decide = async () => {
|
|
714
|
+
const taken = takeFromQueue(script.decisions, decisionSrc);
|
|
715
|
+
if (taken.found) {
|
|
716
|
+
dequeued.push(taken.value);
|
|
717
|
+
return { event: taken.value };
|
|
718
|
+
}
|
|
719
|
+
if (dequeued.length === 0) throw scriptDryError("decision", decisionSrc, request.id, request);
|
|
720
|
+
return { event: dequeued[dequeued.length - 1] };
|
|
721
|
+
};
|
|
722
|
+
const logic = isDecisionLogic(invokeLogic) ? invokeLogic : resolveRegisteredDecisionLogic(machine, decisionSrc);
|
|
723
|
+
const maxRetries = request.maxRetries ?? logic?.maxRetries;
|
|
724
|
+
const can = (event) => step.snapshot.can(event);
|
|
725
|
+
const options = acceptedDecisionOptions(request, can);
|
|
726
|
+
const offered = options ? {
|
|
727
|
+
...request,
|
|
728
|
+
options
|
|
729
|
+
} : request;
|
|
730
|
+
let chosen;
|
|
731
|
+
try {
|
|
732
|
+
chosen = await resolveDecision(offered, { decide }, {
|
|
733
|
+
maxRetries,
|
|
734
|
+
canTake: can
|
|
735
|
+
});
|
|
736
|
+
} catch (error) {
|
|
737
|
+
if (!(error instanceof AgentDecisionExhaustedError)) throw error;
|
|
738
|
+
const next = rejectAgentStep(machine, step, request.id, error);
|
|
739
|
+
if (next.snapshot.status === "error") throw error;
|
|
740
|
+
trail.push({
|
|
741
|
+
state: next.snapshot.value,
|
|
742
|
+
rejectedEvents: dequeued
|
|
743
|
+
});
|
|
744
|
+
return next;
|
|
745
|
+
}
|
|
746
|
+
const next = transitionAgentStep(machine, step, chosen);
|
|
747
|
+
const rejected = dequeued.slice(0, -1);
|
|
748
|
+
trail.push({
|
|
749
|
+
state: next.snapshot.value,
|
|
750
|
+
appliedEvent: chosen,
|
|
751
|
+
...rejected.length > 0 ? { rejectedEvents: rejected } : {}
|
|
752
|
+
});
|
|
753
|
+
return next;
|
|
754
|
+
}
|
|
755
|
+
function findInvokeMetadata(step, id) {
|
|
756
|
+
for (const metadata of getPendingInvokes(step.snapshot)) {
|
|
757
|
+
if (metadata.id !== id) continue;
|
|
758
|
+
return {
|
|
759
|
+
...typeof metadata.src === "string" ? { src: metadata.src } : {},
|
|
760
|
+
logic: metadata.logic ?? (typeof metadata.src === "object" ? metadata.src : void 0)
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
function resolveRegisteredDecisionLogic(machine, src) {
|
|
765
|
+
const candidate = getRegisteredAgentExecutionOptions(machine).actors?.[src] ?? machine.sources?.actors?.[src];
|
|
766
|
+
return isDecisionLogic(candidate) ? candidate : void 0;
|
|
767
|
+
}
|
|
768
|
+
const textOutputs = /* @__PURE__ */ new WeakSet();
|
|
769
|
+
/**
|
|
770
|
+
* Marks a canned text-request output for {@link explorePaths},
|
|
771
|
+
* {@link canReach}, or {@link simulateAgent} as the whole
|
|
772
|
+
* `{ result, messages }` envelope the invoke resolves with, so a machine that
|
|
773
|
+
* reads `output.messages` sees them. A plain canned value is the `result`,
|
|
774
|
+
* with `messages: []`.
|
|
775
|
+
*
|
|
776
|
+
* @example
|
|
777
|
+
* ```ts
|
|
778
|
+
* await explorePaths(machine, {
|
|
779
|
+
* outputs: { reply: [textOutput('hi', { messages: [{ role: 'assistant', content: 'hi' }] })] },
|
|
780
|
+
* });
|
|
781
|
+
* ```
|
|
782
|
+
*/
|
|
783
|
+
function textOutput(result, options = {}) {
|
|
784
|
+
const envelope = {
|
|
785
|
+
result,
|
|
786
|
+
messages: options.messages ?? []
|
|
787
|
+
};
|
|
788
|
+
textOutputs.add(envelope);
|
|
789
|
+
return envelope;
|
|
790
|
+
}
|
|
791
|
+
function asTextResult(value) {
|
|
792
|
+
return isRecord(value) && textOutputs.has(value) ? value : {
|
|
793
|
+
result: value,
|
|
794
|
+
messages: []
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
function mapValues(obj, fn) {
|
|
798
|
+
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
|
|
799
|
+
}
|
|
800
|
+
function scriptDryError(kind, src, id, request) {
|
|
801
|
+
const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
|
|
802
|
+
const key = kind === "text" ? `text['${src}']` : kind === "decision" ? `decisions['${src}']` : `invokes['${src}']`;
|
|
803
|
+
return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add an entry to the script's \`${key}\` queue.${events}`);
|
|
804
|
+
}
|
|
805
|
+
const MAX_ADVANCE_STEPS = 1e3;
|
|
806
|
+
const FINITE_PAYLOAD_CAP = 64;
|
|
807
|
+
const DEFAULT_MAX_NODES = 1e5;
|
|
808
|
+
const MAX_CHILD_NESTING = 4;
|
|
809
|
+
const DEFAULT_BUDGET_NODES = 25e4;
|
|
810
|
+
const DEFAULT_CHILD_CACHE = 64;
|
|
811
|
+
function startBudget(budget) {
|
|
812
|
+
const started = Date.now();
|
|
813
|
+
return {
|
|
814
|
+
nodes: 0,
|
|
815
|
+
maxNodes: budget?.nodes ?? DEFAULT_BUDGET_NODES,
|
|
816
|
+
started,
|
|
817
|
+
deadline: budget?.ms === void 0 ? void 0 : started + budget.ms
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
const logicIds = /* @__PURE__ */ new WeakMap();
|
|
821
|
+
let nextLogicId = 0;
|
|
822
|
+
function logicId(logic) {
|
|
823
|
+
let id = logicIds.get(logic);
|
|
824
|
+
if (id === void 0) {
|
|
825
|
+
id = nextLogicId++;
|
|
826
|
+
logicIds.set(logic, id);
|
|
827
|
+
}
|
|
828
|
+
return id;
|
|
829
|
+
}
|
|
830
|
+
function isMachineLogic(logic) {
|
|
831
|
+
return isRecord(logic) && "root" in logic && "config" in logic && typeof logic["transition"] === "function";
|
|
832
|
+
}
|
|
833
|
+
function pushDistinct(values, seen, value) {
|
|
834
|
+
let key;
|
|
835
|
+
try {
|
|
836
|
+
key = value instanceof Error ? `Error:${value.name}:${value.message}` : JSON.stringify(value) ?? String(value);
|
|
837
|
+
} catch {
|
|
838
|
+
values.push(value);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (!seen.has(key)) {
|
|
842
|
+
seen.add(key);
|
|
843
|
+
values.push(value);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function eventsToParent(effects, parent) {
|
|
847
|
+
if (parent === void 0 || !Array.isArray(effects)) return [];
|
|
848
|
+
return effects.flatMap((effect) => isRecord(effect) && effect["type"] === "@xstate.sendTo" && effect["target"] === parent && isRecord(effect["event"]) && typeof effect["event"]["type"] === "string" ? [effect["event"]] : []);
|
|
849
|
+
}
|
|
850
|
+
function outboundOf(effects, parent, own) {
|
|
851
|
+
if (parent === void 0 || !Array.isArray(effects)) return [];
|
|
852
|
+
const children = Object.entries(isRecord(own) ? own : {});
|
|
853
|
+
const out = [];
|
|
854
|
+
for (const effect of effects) {
|
|
855
|
+
if (!isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
|
|
856
|
+
const target = effect["target"];
|
|
857
|
+
const event = effect["event"];
|
|
858
|
+
if (target === parent) out.push({ event });
|
|
859
|
+
else if (!children.some(([id, ref]) => ref === target || id === target)) out.push({ route: {
|
|
860
|
+
target,
|
|
861
|
+
event
|
|
862
|
+
} });
|
|
863
|
+
}
|
|
864
|
+
return out;
|
|
865
|
+
}
|
|
866
|
+
function finiteDomain(schema) {
|
|
867
|
+
if (!isRecord(schema)) return;
|
|
868
|
+
if ("const" in schema) return [schema["const"]];
|
|
869
|
+
if (Array.isArray(schema["enum"])) return schema["enum"];
|
|
870
|
+
const union = schema["anyOf"] ?? schema["oneOf"];
|
|
871
|
+
if (Array.isArray(union)) {
|
|
872
|
+
const parts = union.map(finiteDomain);
|
|
873
|
+
return parts.every((part) => part !== void 0) ? [...new Set(parts.flat())] : void 0;
|
|
874
|
+
}
|
|
875
|
+
const types = Array.isArray(schema["type"]) ? schema["type"] : [schema["type"]];
|
|
876
|
+
if (types.every((type) => type === "boolean" || type === "null")) return types.flatMap((type) => type === "boolean" ? [true, false] : [null]);
|
|
877
|
+
}
|
|
878
|
+
const OMITTED = Symbol("omitted");
|
|
879
|
+
function finitePayloads(jsonSchema) {
|
|
880
|
+
const bare = {
|
|
881
|
+
payloads: [{}],
|
|
882
|
+
complete: false
|
|
883
|
+
};
|
|
884
|
+
if (!isRecord(jsonSchema) || jsonSchema["type"] !== "object" && !isRecord(jsonSchema["properties"])) return bare;
|
|
885
|
+
const properties = isRecord(jsonSchema["properties"]) ? jsonSchema["properties"] : {};
|
|
886
|
+
const required = new Set(Array.isArray(jsonSchema["required"]) ? jsonSchema["required"] : []);
|
|
887
|
+
if ([...required].some((key) => key !== "type" && !(key in properties))) return bare;
|
|
888
|
+
let product = [{}];
|
|
889
|
+
let complete = true;
|
|
890
|
+
for (const [key, schema] of Object.entries(properties)) {
|
|
891
|
+
if (key === "type") continue;
|
|
892
|
+
const domain = finiteDomain(schema);
|
|
893
|
+
if (!domain || domain.length === 0) {
|
|
894
|
+
if (required.has(key)) return bare;
|
|
895
|
+
complete = false;
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
const choices = required.has(key) ? domain : [OMITTED, ...domain];
|
|
899
|
+
if (product.length * choices.length > FINITE_PAYLOAD_CAP) return bare;
|
|
900
|
+
product = product.flatMap((payload) => choices.map((value) => value === OMITTED ? payload : {
|
|
901
|
+
...payload,
|
|
902
|
+
[key]: value
|
|
903
|
+
}));
|
|
904
|
+
}
|
|
905
|
+
return {
|
|
906
|
+
payloads: product,
|
|
907
|
+
complete
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
function mayReadPayload(snapshot, type) {
|
|
911
|
+
return getNextTransitions(snapshot).some((transition) => transition.eventType === type && (transition.to !== void 0 || transition.guard !== void 0 || transition.matches !== void 0 || typeof transition.context === "function"));
|
|
912
|
+
}
|
|
913
|
+
function extend(prev, event) {
|
|
914
|
+
return {
|
|
915
|
+
event,
|
|
916
|
+
prev,
|
|
917
|
+
length: (prev?.length ?? 0) + 1
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
function pathOf(link) {
|
|
921
|
+
const path = Array.from({ length: link?.length ?? 0 });
|
|
922
|
+
for (let at = link; at; at = at.prev) path[at.length - 1] = at.event;
|
|
923
|
+
return path;
|
|
924
|
+
}
|
|
925
|
+
function pathTypes(link) {
|
|
926
|
+
return pathOf(link).map((event) => typeof event.actorId === "string" ? `${event.type}(${event.actorId})` : event.type).join(", ");
|
|
927
|
+
}
|
|
928
|
+
const MAX_PUMP = 1e3;
|
|
929
|
+
function childStartStep(machine, input, ref) {
|
|
930
|
+
const fresh = initialAgentStep(machine, input);
|
|
931
|
+
const snapshot = ref?.getSnapshot?.();
|
|
932
|
+
return withLiveRequests(isRecord(snapshot) && snapshot["status"] === "active" ? {
|
|
933
|
+
...fresh,
|
|
934
|
+
snapshot
|
|
935
|
+
} : fresh);
|
|
936
|
+
}
|
|
937
|
+
function withLiveRequests(step) {
|
|
938
|
+
if (step.requests.length === 0) return step;
|
|
939
|
+
const children = step.snapshot.children ?? {};
|
|
940
|
+
const requests = step.requests.filter((request) => {
|
|
941
|
+
const logic = children[request.id]?.logic;
|
|
942
|
+
return logic === void 0 || isTextLogic(logic) || isDecisionLogic(logic);
|
|
943
|
+
});
|
|
944
|
+
return requests.length === step.requests.length ? step : {
|
|
945
|
+
...step,
|
|
946
|
+
requests
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
function declaresUsageTransition(snapshot) {
|
|
950
|
+
return getNextTransitions(snapshot).some((transition) => transition.eventType === "@agent.usage" || transition.eventType === "*");
|
|
951
|
+
}
|
|
952
|
+
function childSession(id, ref) {
|
|
953
|
+
return typeof ref?.sessionId === "string" ? ref.sessionId : id;
|
|
954
|
+
}
|
|
955
|
+
function withKidSnapshots(snapshot, kids) {
|
|
956
|
+
if (!kids || kids.size === 0) return snapshot;
|
|
957
|
+
const children = { ...snapshot.children ?? {} };
|
|
958
|
+
let changed = false;
|
|
959
|
+
for (const [id, ref] of Object.entries(children)) {
|
|
960
|
+
const kid = kids.get(childSession(id, ref));
|
|
961
|
+
if (!kid || !ref) continue;
|
|
962
|
+
const kidSnapshot = withKidSnapshots(kid.step.snapshot, kid.kids);
|
|
963
|
+
children[id] = Object.assign(Object.create(ref), { getSnapshot: () => kidSnapshot });
|
|
964
|
+
changed = true;
|
|
965
|
+
}
|
|
966
|
+
if (!changed) return snapshot;
|
|
967
|
+
return Object.assign(Object.create(Object.getPrototypeOf(snapshot)), snapshot, { children });
|
|
968
|
+
}
|
|
969
|
+
function pruneDelivered(delivered, step) {
|
|
970
|
+
if (delivered === void 0 || delivered.size === 0) return delivered;
|
|
971
|
+
const children = step.snapshot.children ?? {};
|
|
972
|
+
const running = new Set(Object.entries(children).map(([id, ref]) => childSession(id, ref)));
|
|
973
|
+
const kept = [...delivered].filter((key) => running.has(key.slice(0, key.indexOf("\0"))));
|
|
974
|
+
return kept.length === delivered.size ? delivered : new Set(kept);
|
|
975
|
+
}
|
|
976
|
+
function hasTransientStates(node) {
|
|
977
|
+
const visit = (node) => {
|
|
978
|
+
if (!isRecord(node)) return false;
|
|
979
|
+
if (node["type"] === "choice" || Array.isArray(node["always"]) && node["always"].length > 0) return true;
|
|
980
|
+
return Object.values(isRecord(node["states"]) ? node["states"] : {}).some(visit);
|
|
981
|
+
};
|
|
982
|
+
return visit(node);
|
|
983
|
+
}
|
|
984
|
+
function transientStateIds(node, ids = []) {
|
|
985
|
+
if (!isRecord(node)) return ids;
|
|
986
|
+
if (node["type"] === "choice" || Array.isArray(node["always"]) && node["always"].length > 0) ids.push(String(node["id"]));
|
|
987
|
+
for (const child of Object.values(isRecord(node["states"]) ? node["states"] : {})) transientStateIds(child, ids);
|
|
988
|
+
return ids;
|
|
989
|
+
}
|
|
990
|
+
function hasParallelStates(node) {
|
|
991
|
+
return isRecord(node) && (node["type"] === "parallel" || Object.values(isRecord(node["states"]) ? node["states"] : {}).some(hasParallelStates));
|
|
992
|
+
}
|
|
993
|
+
function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false) {
|
|
994
|
+
const maxDepth = options.maxDepth ?? 8;
|
|
995
|
+
const maxPaths = options.maxPaths ?? 200;
|
|
996
|
+
const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
|
|
997
|
+
const errorScript = options.errors ?? {};
|
|
998
|
+
const outputScript = options.outputs ?? {};
|
|
999
|
+
const coupled = options.children === "coupled";
|
|
1000
|
+
const timerMode = options.timers ?? "fire";
|
|
1001
|
+
const usageScript = nesting === 0 || stepping ? options.usage ?? {} : void 0;
|
|
1002
|
+
const charges = /* @__PURE__ */ new WeakMap();
|
|
1003
|
+
const interleaving = options.interleave === "pending" || stepping;
|
|
1004
|
+
const errorsFor = (key) => {
|
|
1005
|
+
if (!(key in errorScript)) return;
|
|
1006
|
+
const entry = errorScript[key];
|
|
1007
|
+
if (Array.isArray(entry)) return entry.length > 0 ? {
|
|
1008
|
+
values: entry,
|
|
1009
|
+
record: true
|
|
1010
|
+
} : void 0;
|
|
1011
|
+
return {
|
|
1012
|
+
values: [entry],
|
|
1013
|
+
record: false
|
|
1014
|
+
};
|
|
1015
|
+
};
|
|
1016
|
+
const eventSchemas = getRegisteredAgentExecutionOptions(machine).schemas?.events ?? machine.schemas?.events ?? {};
|
|
1017
|
+
const unseenTransient = new Set(trackTransits ? transientStateIds(machine.root) : []);
|
|
1018
|
+
const keepTracking = trackTransits && hasParallelStates(machine.root);
|
|
1019
|
+
const transits = /* @__PURE__ */ new WeakMap();
|
|
1020
|
+
const withTransits = (next, microsteps) => {
|
|
1021
|
+
next = withLiveRequests(next);
|
|
1022
|
+
if (unseenTransient.size > 0 || keepTracking) {
|
|
1023
|
+
const passed = microsteps().slice(0, -1).map(([snapshot]) => snapshot);
|
|
1024
|
+
for (const snapshot of passed) for (const node of snapshot.nodes) unseenTransient.delete(node.id);
|
|
1025
|
+
transits.set(next, passed);
|
|
1026
|
+
}
|
|
1027
|
+
return next;
|
|
1028
|
+
};
|
|
1029
|
+
const resolveStep = (prev, id, output) => withTransits(resolveAgentStep(machine, prev, id, output), () => getMicrosteps(machine, prev.snapshot, doneEvent(prev.snapshot, id, output)));
|
|
1030
|
+
const rejectStep = (prev, id, error) => withTransits(rejectAgentStep(machine, prev, id, error), () => getMicrosteps(machine, prev.snapshot, errorEvent(prev.snapshot, id, error)));
|
|
1031
|
+
const transitionStep = (prev, event) => withTransits(transitionAgentStep(machine, prev, event), () => getMicrosteps(machine, prev.snapshot, event));
|
|
1032
|
+
const settleStep = (prev, id, output, usage) => {
|
|
1033
|
+
if (!usage) return {
|
|
1034
|
+
step: resolveStep(prev, id, output),
|
|
1035
|
+
completed: true
|
|
1036
|
+
};
|
|
1037
|
+
if (stepping) {
|
|
1038
|
+
const resolved = resolveStep(prev, id, output);
|
|
1039
|
+
charges.set(resolved, usage);
|
|
1040
|
+
return {
|
|
1041
|
+
step: resolved,
|
|
1042
|
+
completed: true
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
const sessionOf = (step) => {
|
|
1046
|
+
const invoke = pendingInvokes(step).find((pending) => pending.id === id);
|
|
1047
|
+
return invoke && childSession(id, invoke.ref);
|
|
1048
|
+
};
|
|
1049
|
+
const session = sessionOf(prev);
|
|
1050
|
+
const charged = transitionStep(prev, usage);
|
|
1051
|
+
if (session === void 0 || sessionOf(charged) !== session) return {
|
|
1052
|
+
step: charged,
|
|
1053
|
+
completed: false
|
|
1054
|
+
};
|
|
1055
|
+
const resolved = resolveStep(charged, id, output);
|
|
1056
|
+
transits.set(resolved, [
|
|
1057
|
+
...transits.get(charged) ?? [],
|
|
1058
|
+
charged.snapshot,
|
|
1059
|
+
...transits.get(resolved) ?? []
|
|
1060
|
+
]);
|
|
1061
|
+
return {
|
|
1062
|
+
step: resolved,
|
|
1063
|
+
completed: true
|
|
1064
|
+
};
|
|
1065
|
+
};
|
|
1066
|
+
const usageFor = (step, request) => {
|
|
1067
|
+
if (!usageScript || request.kind !== "text" || !stepping && !declaresUsageTransition(step.snapshot)) return;
|
|
1068
|
+
const values = usageScript[request.src];
|
|
1069
|
+
if (!values?.length) {
|
|
1070
|
+
if (!stepping) vacuous.add(AGENT_USAGE_EVENT_TYPE);
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const snapshot = step.snapshot;
|
|
1074
|
+
const events = values.map((usage) => ({
|
|
1075
|
+
type: AGENT_USAGE_EVENT_TYPE,
|
|
1076
|
+
kind: "text",
|
|
1077
|
+
id: request.id,
|
|
1078
|
+
src: request.src,
|
|
1079
|
+
model: request.input.model,
|
|
1080
|
+
...request.input.name !== void 0 ? { name: request.input.name } : {},
|
|
1081
|
+
usage
|
|
1082
|
+
}));
|
|
1083
|
+
if (stepping) return events;
|
|
1084
|
+
const accepted = events.filter((event) => snapshot.can(event));
|
|
1085
|
+
if (accepted.length === 0) return;
|
|
1086
|
+
return accepted.length < events.length ? [...accepted, void 0] : accepted;
|
|
1087
|
+
};
|
|
1088
|
+
const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
|
|
1089
|
+
const finiteCache = /* @__PURE__ */ new Map();
|
|
1090
|
+
const schemaPayloads = (type, snapshot) => {
|
|
1091
|
+
const schema = eventSchemas[type];
|
|
1092
|
+
let fill = finiteCache.get(type);
|
|
1093
|
+
if (schema && !fill) {
|
|
1094
|
+
fill = finitePayloads(safeJsonSchema(schema));
|
|
1095
|
+
finiteCache.set(type, fill);
|
|
1096
|
+
}
|
|
1097
|
+
fill ??= {
|
|
1098
|
+
payloads: [{}],
|
|
1099
|
+
complete: !mayReadPayload(snapshot, type)
|
|
1100
|
+
};
|
|
1101
|
+
if (!fill.complete && fill.payloads.length === 1 && Object.keys(fill.payloads[0]).length === 0 && mayReadPayload(snapshot, type)) vacuous.add(type);
|
|
1102
|
+
if (!fill.complete && !unexpanded.has(type)) {
|
|
1103
|
+
unexpanded.add(type);
|
|
1104
|
+
note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
|
|
1105
|
+
}
|
|
1106
|
+
return fill.payloads;
|
|
1107
|
+
};
|
|
1108
|
+
const variantsOf = (type, snapshot, table, requestOptions) => {
|
|
1109
|
+
const listed = table[type];
|
|
1110
|
+
if (listed) return listed.map((payload) => ({
|
|
1111
|
+
...payload,
|
|
1112
|
+
type
|
|
1113
|
+
}));
|
|
1114
|
+
if (requestOptions) return requestOptions.filter((option) => option.event.type === type).map((option) => option.event);
|
|
1115
|
+
return schemaPayloads(type, snapshot).map((payload) => ({
|
|
1116
|
+
...payload,
|
|
1117
|
+
type
|
|
1118
|
+
}));
|
|
1119
|
+
};
|
|
1120
|
+
const childCache = /* @__PURE__ */ new Map();
|
|
1121
|
+
const childCacheSize = options.budget?.childCache ?? DEFAULT_CHILD_CACHE;
|
|
1122
|
+
const exploreChild = (src, logic, input, ref) => {
|
|
1123
|
+
if (nesting >= MAX_CHILD_NESTING) {
|
|
1124
|
+
note(() => `child: src '${src}' is nested deeper than ${MAX_CHILD_NESTING} machines; not explored`);
|
|
1125
|
+
return {
|
|
1126
|
+
outputs: [],
|
|
1127
|
+
errors: [],
|
|
1128
|
+
events: [],
|
|
1129
|
+
stalls: false,
|
|
1130
|
+
complete: false
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
let key;
|
|
1134
|
+
try {
|
|
1135
|
+
key = `${logicId(logic)}\u0000${src}\u0000${JSON.stringify(input) ?? "undefined"}`;
|
|
1136
|
+
} catch {
|
|
1137
|
+
key = void 0;
|
|
1138
|
+
}
|
|
1139
|
+
const cached = key === void 0 ? void 0 : childCache.get(key);
|
|
1140
|
+
if (cached) {
|
|
1141
|
+
childCache.delete(key);
|
|
1142
|
+
childCache.set(key, cached);
|
|
1143
|
+
return cached;
|
|
1144
|
+
}
|
|
1145
|
+
const child = explore(logic, {
|
|
1146
|
+
...options,
|
|
1147
|
+
input
|
|
1148
|
+
}, void 0, nesting + 1, new Set(options.childEvents?.[src] ?? []), ref, false, budget);
|
|
1149
|
+
if (child.undeliverable.length > 0) note(() => `child: src '${src}' waits for ${child.undeliverable.join(", ")}, which childEvents does not list as reaching it; list each event the parent forwards`);
|
|
1150
|
+
for (const type of child.report.unexpandedEvents) unexpanded.add(type);
|
|
1151
|
+
for (const type of child.report.vacuous) vacuous.add(type);
|
|
1152
|
+
const outcome = {
|
|
1153
|
+
outputs: child.doneOutputs,
|
|
1154
|
+
errors: child.failures,
|
|
1155
|
+
events: child.parentEvents,
|
|
1156
|
+
stalls: child.stalls,
|
|
1157
|
+
complete: !child.unfinished && isExplorationComplete(child.report) && child.undeliverable.length === 0
|
|
1158
|
+
};
|
|
1159
|
+
if (!outcome.complete) note(() => `child: exploring src '${src}' was incomplete, so its outputs may be partial; add an outputs entry for it`);
|
|
1160
|
+
if (key !== void 0 && childCacheSize > 0) {
|
|
1161
|
+
childCache.set(key, outcome);
|
|
1162
|
+
if (childCache.size > childCacheSize) childCache.delete(childCache.keys().next().value);
|
|
1163
|
+
}
|
|
1164
|
+
return outcome;
|
|
1165
|
+
};
|
|
1166
|
+
const neverSettles = (src) => outputScript[src]?.length === 0 && !errorsFor(src);
|
|
1167
|
+
const settleFor = (id, src, isText, invoke, usage) => {
|
|
1168
|
+
const failures = errorsFor(src);
|
|
1169
|
+
if (neverSettles(src)) return { never: true };
|
|
1170
|
+
if (options.children === "explore" && !(src in outputScript) && !failures && isMachineLogic(invoke?.logic)) {
|
|
1171
|
+
const child = exploreChild(src, invoke.logic, invoke.input, invoke.ref);
|
|
1172
|
+
if (child.outputs.length === 1 && child.errors.length === 0 && child.events.length === 0 && !child.stalls && child.complete) return { output: child.outputs[0] };
|
|
1173
|
+
if (child.outputs.length === 0 && child.errors.length === 0 && child.events.length === 0 && !child.stalls) return { blocked: true };
|
|
1174
|
+
return { fork: {
|
|
1175
|
+
id,
|
|
1176
|
+
errors: child.errors,
|
|
1177
|
+
recordError: true,
|
|
1178
|
+
outputs: child.outputs,
|
|
1179
|
+
events: child.events,
|
|
1180
|
+
session: childSession(id, invoke.ref),
|
|
1181
|
+
stalls: child.stalls,
|
|
1182
|
+
...child.complete ? {} : { incompleteSrc: src }
|
|
1183
|
+
} };
|
|
1184
|
+
}
|
|
1185
|
+
const outputs = outputScript[src] ?? [];
|
|
1186
|
+
if (failures || outputs.length > 1 || outputs.length === 1 && (usage?.length ?? 0) > 1) return { fork: {
|
|
1187
|
+
id,
|
|
1188
|
+
errors: failures?.values ?? [],
|
|
1189
|
+
recordError: failures?.record ?? false,
|
|
1190
|
+
outputs,
|
|
1191
|
+
isText,
|
|
1192
|
+
...usage ? { usage } : {}
|
|
1193
|
+
} };
|
|
1194
|
+
return outputs.length === 1 ? { output: outputs[0] } : { blocked: true };
|
|
1195
|
+
};
|
|
1196
|
+
const isExploredChild = (invoke) => (options.children === "explore" || coupled) && !(invoke.src in outputScript) && !errorsFor(invoke.src) && isMachineLogic(invoke.logic);
|
|
1197
|
+
const concurrentForks = (step) => {
|
|
1198
|
+
if (options.children !== "explore" && !coupled) return;
|
|
1199
|
+
const invokes = pendingInvokes(step);
|
|
1200
|
+
if (!invokes.some(isExploredChild)) return;
|
|
1201
|
+
const kids = coupled ? invokes.filter(isExploredChild) : [];
|
|
1202
|
+
const blocked = [];
|
|
1203
|
+
const asFork = (settle, id, src, isText, usage) => {
|
|
1204
|
+
if ("fork" in settle) return [settle.fork];
|
|
1205
|
+
if ("blocked" in settle) {
|
|
1206
|
+
blocked.push(src);
|
|
1207
|
+
return [];
|
|
1208
|
+
}
|
|
1209
|
+
if ("never" in settle) return [];
|
|
1210
|
+
return [{
|
|
1211
|
+
id,
|
|
1212
|
+
errors: [],
|
|
1213
|
+
outputs: [settle.output],
|
|
1214
|
+
isText,
|
|
1215
|
+
...usage ? { usage } : {}
|
|
1216
|
+
}];
|
|
1217
|
+
};
|
|
1218
|
+
const texts = step.requests.filter((request) => request.kind === "text");
|
|
1219
|
+
const requestIds = new Set(step.requests.map((request) => request.id));
|
|
1220
|
+
const forks = [...texts.flatMap((request) => {
|
|
1221
|
+
const usage = usageFor(step, request);
|
|
1222
|
+
return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
|
|
1223
|
+
}), ...invokes.filter((invoke) => !requestIds.has(invoke.id) && !kids.includes(invoke)).flatMap((invoke) => asFork(settleFor(invoke.id, invoke.src, false, invoke), invoke.id, invoke.src, false))];
|
|
1224
|
+
const decisions = step.requests.filter((request) => request.kind === "decision");
|
|
1225
|
+
for (const decision of decisions) {
|
|
1226
|
+
const src = findInvokeMetadata(step, decision.id)?.src;
|
|
1227
|
+
const failed = (src !== void 0 ? errorsFor(src) : void 0) ?? errorsFor(decision.id);
|
|
1228
|
+
if (failed) forks.push({
|
|
1229
|
+
id: decision.id,
|
|
1230
|
+
errors: failed.values,
|
|
1231
|
+
recordError: failed.record,
|
|
1232
|
+
outputs: []
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
if (coupled) return {
|
|
1236
|
+
forks,
|
|
1237
|
+
blocked,
|
|
1238
|
+
decisions,
|
|
1239
|
+
kids
|
|
1240
|
+
};
|
|
1241
|
+
return forks.length > 0 && forks.length + blocked.length + decisions.length > 1 ? {
|
|
1242
|
+
forks,
|
|
1243
|
+
blocked,
|
|
1244
|
+
decisions
|
|
1245
|
+
} : void 0;
|
|
1246
|
+
};
|
|
1247
|
+
const reachedStates = /* @__PURE__ */ new Set();
|
|
1248
|
+
const reachedValues = [];
|
|
1249
|
+
const terminals = [];
|
|
1250
|
+
const unexplored = [];
|
|
1251
|
+
const unexpanded = /* @__PURE__ */ new Set();
|
|
1252
|
+
const vacuous = /* @__PURE__ */ new Set();
|
|
1253
|
+
const doneOutputs = [];
|
|
1254
|
+
const failures = [];
|
|
1255
|
+
const seenOutputs = /* @__PURE__ */ new Set();
|
|
1256
|
+
const seenFailures = /* @__PURE__ */ new Set();
|
|
1257
|
+
const seenParentEvents = /* @__PURE__ */ new Set();
|
|
1258
|
+
let stalls = false;
|
|
1259
|
+
let unfinished = false;
|
|
1260
|
+
const note = (text) => {
|
|
1261
|
+
if (nesting === 0) unexplored.push(text());
|
|
1262
|
+
};
|
|
1263
|
+
let captured;
|
|
1264
|
+
const endPath = (path, terminal) => {
|
|
1265
|
+
if (captured) {
|
|
1266
|
+
captured.push({
|
|
1267
|
+
status: terminal.status,
|
|
1268
|
+
...terminal.missingSrc === void 0 ? {} : { missingSrc: terminal.missingSrc }
|
|
1269
|
+
});
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
pathsExplored++;
|
|
1273
|
+
if (terminal.status === "idle") stalls = true;
|
|
1274
|
+
else if (terminal.status !== "done" && terminal.status !== "error") unfinished = true;
|
|
1275
|
+
if (nesting === 0) terminals.push({
|
|
1276
|
+
...terminal,
|
|
1277
|
+
path: pathOf(path)
|
|
1278
|
+
});
|
|
1279
|
+
};
|
|
1280
|
+
let prunedByGuard = 0;
|
|
1281
|
+
let pathsExplored = 0;
|
|
1282
|
+
let nodesExpanded = 0;
|
|
1283
|
+
let hitPathCap = false;
|
|
1284
|
+
const capped = () => {
|
|
1285
|
+
if (!stepping && (pathsExplored >= maxPaths || nodesExpanded >= maxNodes)) hitPathCap = true;
|
|
1286
|
+
if (budget.exhausted === void 0) {
|
|
1287
|
+
if (budget.nodes >= budget.maxNodes) budget.exhausted = "nodes";
|
|
1288
|
+
else if (budget.deadline !== void 0 && Date.now() >= budget.deadline) budget.exhausted = "ms";
|
|
1289
|
+
}
|
|
1290
|
+
return hitPathCap || budget.exhausted !== void 0;
|
|
1291
|
+
};
|
|
1292
|
+
let witness;
|
|
1293
|
+
const visited = /* @__PURE__ */ new Map();
|
|
1294
|
+
const parentEvents = [];
|
|
1295
|
+
const parent = childRef?._parent;
|
|
1296
|
+
const recordState = (step, effects = step.actions) => {
|
|
1297
|
+
const key = JSON.stringify(step.snapshot.value);
|
|
1298
|
+
if (!reachedStates.has(key)) {
|
|
1299
|
+
reachedStates.add(key);
|
|
1300
|
+
reachedValues.push(step.snapshot.value);
|
|
1301
|
+
}
|
|
1302
|
+
for (const event of eventsToParent(effects, parent)) pushDistinct(parentEvents, seenParentEvents, event);
|
|
1303
|
+
for (const snapshot of transits.get(step) ?? []) {
|
|
1304
|
+
const transitKey = JSON.stringify(snapshot.value);
|
|
1305
|
+
if (!reachedStates.has(transitKey)) {
|
|
1306
|
+
reachedStates.add(transitKey);
|
|
1307
|
+
reachedValues.push(snapshot.value);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
};
|
|
1311
|
+
const initial = stepping ? void 0 : withTransits(childStartStep(machine, options.input, childRef), () => getInitialMicrosteps(machine, options.input));
|
|
1312
|
+
if (initial) {
|
|
1313
|
+
recordState(initial, childRef?._initialEffects ?? initial.actions);
|
|
1314
|
+
if (stops(initial)) witness = [];
|
|
1315
|
+
}
|
|
1316
|
+
const undeliverable = /* @__PURE__ */ new Set();
|
|
1317
|
+
const external = deliverable ?? (options.hostEvents === void 0 ? void 0 : new Set(options.hostEvents));
|
|
1318
|
+
const arriving = (snapshot) => getAcceptedEvents(snapshot).filter((descriptor) => {
|
|
1319
|
+
if (external === void 0 || external.has(descriptor.type)) return true;
|
|
1320
|
+
if (deliverable !== void 0) undeliverable.add(descriptor.type);
|
|
1321
|
+
return false;
|
|
1322
|
+
});
|
|
1323
|
+
const races = (step) => stepping || interleaving && (arriving(step.snapshot).length > 0 || timerMode === "fire" && armedTimers(step.snapshot).length > 0);
|
|
1324
|
+
const advance = (step, recordEvent, kids) => {
|
|
1325
|
+
let current = step;
|
|
1326
|
+
for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
|
|
1327
|
+
if (!awaitsKids(current, kids) && stops(current, kids)) return {
|
|
1328
|
+
step: current,
|
|
1329
|
+
hit: true
|
|
1330
|
+
};
|
|
1331
|
+
if (current.done) return { step: current };
|
|
1332
|
+
const request = current.requests.find((pending) => pending.kind !== "text" || !neverSettles(pending.src));
|
|
1333
|
+
const concurrent = concurrentForks(current);
|
|
1334
|
+
if (concurrent) return {
|
|
1335
|
+
step: current,
|
|
1336
|
+
fork: concurrent.forks[0],
|
|
1337
|
+
siblings: concurrent.forks.slice(1),
|
|
1338
|
+
blockedSiblings: concurrent.blocked,
|
|
1339
|
+
decisions: concurrent.decisions,
|
|
1340
|
+
...concurrent.kids?.length ? { kids: concurrent.kids } : {}
|
|
1341
|
+
};
|
|
1342
|
+
if (request && request.kind === "text") {
|
|
1343
|
+
const usage = usageFor(current, request);
|
|
1344
|
+
const settle = settleFor(request.id, request.src, true, void 0, usage);
|
|
1345
|
+
if ("fork" in settle) return {
|
|
1346
|
+
step: current,
|
|
1347
|
+
fork: settle.fork
|
|
1348
|
+
};
|
|
1349
|
+
if ("blocked" in settle) return {
|
|
1350
|
+
step: current,
|
|
1351
|
+
blockedSrc: request.src
|
|
1352
|
+
};
|
|
1353
|
+
if ("never" in settle) return { step: current };
|
|
1354
|
+
if (races(current)) return {
|
|
1355
|
+
step: current,
|
|
1356
|
+
pending: {
|
|
1357
|
+
id: request.id,
|
|
1358
|
+
output: asTextResult(settle.output),
|
|
1359
|
+
...usage?.[0] ? { usage: usage[0] } : {}
|
|
1360
|
+
}
|
|
1361
|
+
};
|
|
1362
|
+
if (usage?.[0]) recordEvent(usage[0]);
|
|
1363
|
+
current = settleStep(current, request.id, asTextResult(settle.output), usage?.[0]).step;
|
|
1364
|
+
recordState(current);
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
if (request && request.kind === "decision") {
|
|
1368
|
+
const src = findInvokeMetadata(current, request.id)?.src;
|
|
1369
|
+
const failed = (src !== void 0 ? errorsFor(src) : void 0) ?? errorsFor(request.id);
|
|
1370
|
+
return failed ? {
|
|
1371
|
+
step: current,
|
|
1372
|
+
fork: {
|
|
1373
|
+
id: request.id,
|
|
1374
|
+
errors: failed.values,
|
|
1375
|
+
recordError: failed.record,
|
|
1376
|
+
outputs: [],
|
|
1377
|
+
isDecision: true
|
|
1378
|
+
}
|
|
1379
|
+
} : { step: current };
|
|
1380
|
+
}
|
|
1381
|
+
const [invoke] = pendingInvokes(current).filter((pending) => !neverSettles(pending.src));
|
|
1382
|
+
if (invoke) {
|
|
1383
|
+
const settle = settleFor(invoke.id, invoke.src, false, invoke);
|
|
1384
|
+
if ("fork" in settle) return {
|
|
1385
|
+
step: current,
|
|
1386
|
+
fork: settle.fork
|
|
1387
|
+
};
|
|
1388
|
+
if ("blocked" in settle) return {
|
|
1389
|
+
step: current,
|
|
1390
|
+
blockedSrc: invoke.src
|
|
1391
|
+
};
|
|
1392
|
+
if ("never" in settle) return { step: current };
|
|
1393
|
+
if (races(current)) return {
|
|
1394
|
+
step: current,
|
|
1395
|
+
pending: {
|
|
1396
|
+
id: invoke.id,
|
|
1397
|
+
output: settle.output
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
current = resolveStep(current, invoke.id, settle.output);
|
|
1401
|
+
recordState(current);
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
return { step: current };
|
|
1405
|
+
}
|
|
1406
|
+
return { step: current };
|
|
1407
|
+
};
|
|
1408
|
+
const acceptedVariants = (snapshot, path, table, except) => [...arriving(snapshot).flatMap((descriptor) => {
|
|
1409
|
+
if (except?.has(descriptor.type)) return [];
|
|
1410
|
+
if (table[descriptor.type]?.length === 0) {
|
|
1411
|
+
unexpanded.add(descriptor.type);
|
|
1412
|
+
note(() => `skipped: payloads lists no ${descriptor.type} at path [${pathTypes(path)}], so its branches were not explored`);
|
|
1413
|
+
}
|
|
1414
|
+
return variantsOf(descriptor.type, snapshot, table);
|
|
1415
|
+
}), ...timerEvents(snapshot, path)];
|
|
1416
|
+
const timerFires = /* @__PURE__ */ new WeakMap();
|
|
1417
|
+
const applied = (event) => timerFires.get(event) ?? event;
|
|
1418
|
+
const ignoredTimers = /* @__PURE__ */ new Set();
|
|
1419
|
+
function armedTimers(snapshot) {
|
|
1420
|
+
const timers = snapshot.timers;
|
|
1421
|
+
if (!Array.isArray(timers) || timers.length === 0) return [];
|
|
1422
|
+
return timers.flatMap((timer) => {
|
|
1423
|
+
if (!isRecord(timer) || timer["target"] !== "self" || !isRecord(timer["event"]) || typeof timer["event"]["type"] !== "string") return [];
|
|
1424
|
+
const event = timer["event"];
|
|
1425
|
+
if (!snapshot.can(event)) return [];
|
|
1426
|
+
return [{
|
|
1427
|
+
event,
|
|
1428
|
+
key: typeof timer["id"] === "string" ? { id: timer["id"] } : typeof timer["seq"] === "number" ? { seq: timer["seq"] } : { event }
|
|
1429
|
+
}];
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
const timerEvents = (snapshot, path) => {
|
|
1433
|
+
const armed = armedTimers(snapshot);
|
|
1434
|
+
if (timerMode === "ignore") {
|
|
1435
|
+
for (const { event } of armed) {
|
|
1436
|
+
unexpanded.add(event.type);
|
|
1437
|
+
const key = JSON.stringify(event);
|
|
1438
|
+
if (!ignoredTimers.has(key)) {
|
|
1439
|
+
ignoredTimers.add(key);
|
|
1440
|
+
note(() => `timers: ${key} is armed at path [${pathTypes(path)}], and timers: "ignore" never fires it`);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return [];
|
|
1444
|
+
}
|
|
1445
|
+
return armed.map(({ event, key }) => {
|
|
1446
|
+
const entry = { ...event };
|
|
1447
|
+
timerFires.set(entry, {
|
|
1448
|
+
type: "xstate.timer",
|
|
1449
|
+
...key
|
|
1450
|
+
});
|
|
1451
|
+
return entry;
|
|
1452
|
+
});
|
|
1453
|
+
};
|
|
1454
|
+
function* raceBranches(settled, path, depth, except) {
|
|
1455
|
+
const snapshot = settled.snapshot;
|
|
1456
|
+
const table = options.payloads?.(snapshot) ?? {};
|
|
1457
|
+
for (const event of acceptedVariants(snapshot, path, table, except)) {
|
|
1458
|
+
if (witness !== void 0 || capped()) return;
|
|
1459
|
+
if (!snapshot.can(event)) {
|
|
1460
|
+
prunedByGuard++;
|
|
1461
|
+
continue;
|
|
1462
|
+
}
|
|
1463
|
+
const next = transitionStep(settled, applied(event));
|
|
1464
|
+
recordState(next);
|
|
1465
|
+
yield {
|
|
1466
|
+
step: next,
|
|
1467
|
+
path: extend(path, event),
|
|
1468
|
+
depth: depth + 1
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
const failBranch = (settled, path, depth, fork, error) => {
|
|
1473
|
+
const failed = rejectStep(settled, fork.id, error);
|
|
1474
|
+
recordState(failed);
|
|
1475
|
+
return {
|
|
1476
|
+
step: failed,
|
|
1477
|
+
path: extend(path, {
|
|
1478
|
+
type: "xstate.error.actor",
|
|
1479
|
+
actorId: fork.id,
|
|
1480
|
+
...fork.recordError ? { error } : {}
|
|
1481
|
+
}),
|
|
1482
|
+
depth: depth + 1
|
|
1483
|
+
};
|
|
1484
|
+
};
|
|
1485
|
+
function* doneBranches(settled, path, depth, fork, output) {
|
|
1486
|
+
const value = fork.isText ? asTextResult(output) : output;
|
|
1487
|
+
const recorded = fork.isText ? value.result : output;
|
|
1488
|
+
const usages = fork.usage?.length ? fork.usage : [void 0];
|
|
1489
|
+
for (const [i, usage] of usages.entries()) {
|
|
1490
|
+
if (i > 0 && (witness !== void 0 || capped())) return;
|
|
1491
|
+
const { step, completed } = settleStep(settled, fork.id, value, usage);
|
|
1492
|
+
recordState(step);
|
|
1493
|
+
const charged = usage && !stepping ? extend(path, usage) : path;
|
|
1494
|
+
yield {
|
|
1495
|
+
step,
|
|
1496
|
+
path: completed ? extend(charged, {
|
|
1497
|
+
type: "xstate.done.actor",
|
|
1498
|
+
actorId: fork.id,
|
|
1499
|
+
output: recorded
|
|
1500
|
+
}) : charged,
|
|
1501
|
+
depth: depth + 1
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
const maxDepthTerminal = (settled, path) => {
|
|
1506
|
+
endPath(path, {
|
|
1507
|
+
status: "max-depth",
|
|
1508
|
+
state: settled.snapshot.value
|
|
1509
|
+
});
|
|
1510
|
+
note(() => `max-depth: stopped at path [${pathTypes(path)}]`);
|
|
1511
|
+
};
|
|
1512
|
+
const steppers = /* @__PURE__ */ new Map();
|
|
1513
|
+
const stepperFor = (src, logic) => {
|
|
1514
|
+
if (nesting >= MAX_CHILD_NESTING) {
|
|
1515
|
+
note(() => `child: src '${src}' is nested deeper than ${MAX_CHILD_NESTING} machines; not explored`);
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
const key = `${logicId(logic)}\u0000${src}`;
|
|
1519
|
+
let stepper = steppers.get(key);
|
|
1520
|
+
if (!stepper) {
|
|
1521
|
+
stepper = explore(logic, {
|
|
1522
|
+
...options,
|
|
1523
|
+
input: void 0,
|
|
1524
|
+
dedupeBy: void 0
|
|
1525
|
+
}, void 0, nesting + 1, new Set(options.childEvents?.[src] ?? []), void 0, false, budget, true).stepper;
|
|
1526
|
+
steppers.set(key, stepper);
|
|
1527
|
+
}
|
|
1528
|
+
return stepper;
|
|
1529
|
+
};
|
|
1530
|
+
const pumped = /* @__PURE__ */ new WeakSet();
|
|
1531
|
+
let outParent;
|
|
1532
|
+
const register = (step, kids, queue) => {
|
|
1533
|
+
const live = pendingInvokes(step).filter(isExploredChild);
|
|
1534
|
+
const sessions = new Set(live.map((invoke) => childSession(invoke.id, invoke.ref)));
|
|
1535
|
+
for (const session of kids.keys()) if (!sessions.has(session)) kids.delete(session);
|
|
1536
|
+
for (const invoke of live) {
|
|
1537
|
+
const session = childSession(invoke.id, invoke.ref);
|
|
1538
|
+
if (kids.has(session)) continue;
|
|
1539
|
+
const logic = invoke.logic;
|
|
1540
|
+
const engine = stepperFor(invoke.src, logic);
|
|
1541
|
+
if (!engine) continue;
|
|
1542
|
+
const fresh = childStartStep(logic, invoke.input, invoke.ref);
|
|
1543
|
+
const start = invoke.ref?._initialEffects === void 0 ? fresh : {
|
|
1544
|
+
...fresh,
|
|
1545
|
+
actions: invoke.ref._initialEffects
|
|
1546
|
+
};
|
|
1547
|
+
const parentRef = invoke.ref?._parent;
|
|
1548
|
+
const kid = {
|
|
1549
|
+
id: invoke.id,
|
|
1550
|
+
src: invoke.src,
|
|
1551
|
+
engine,
|
|
1552
|
+
step: start,
|
|
1553
|
+
parent: parentRef,
|
|
1554
|
+
kids: void 0
|
|
1555
|
+
};
|
|
1556
|
+
const primed = engine.prime(kid);
|
|
1557
|
+
if (primed.overflow) return false;
|
|
1558
|
+
kids.set(session, {
|
|
1559
|
+
...kid,
|
|
1560
|
+
step: primed.step,
|
|
1561
|
+
kids: primed.kids
|
|
1562
|
+
});
|
|
1563
|
+
queue.push(...outboundOf(start.actions, parentRef, start.snapshot.children), ...primed.outbound);
|
|
1564
|
+
if (primed.step.snapshot.status !== "active") queue.push({ settle: session });
|
|
1565
|
+
}
|
|
1566
|
+
return true;
|
|
1567
|
+
};
|
|
1568
|
+
const kidSessionFor = (step, target, kids) => {
|
|
1569
|
+
const children = step.snapshot.children ?? {};
|
|
1570
|
+
for (const [id, ref] of Object.entries(children)) if (ref === target || id === target) {
|
|
1571
|
+
const session = childSession(id, ref);
|
|
1572
|
+
return kids.has(session) ? session : void 0;
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
const awaitsKids = (step, kids) => {
|
|
1576
|
+
if (!coupled || pumped.has(step)) return false;
|
|
1577
|
+
const held = kids ?? /* @__PURE__ */ new Map();
|
|
1578
|
+
if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
|
|
1579
|
+
return (Array.isArray(step.actions) ? step.actions : []).some((effect) => isRecord(effect) && effect["type"] === "@xstate.sendTo" && kidSessionFor(step, effect["target"], held) !== void 0);
|
|
1580
|
+
};
|
|
1581
|
+
const pump = (start, link, kids, queue) => {
|
|
1582
|
+
let step = start;
|
|
1583
|
+
let overflow = false;
|
|
1584
|
+
const outbound = [];
|
|
1585
|
+
const deliverTo = (at, target, event) => {
|
|
1586
|
+
const session = kidSessionFor(at, target, kids);
|
|
1587
|
+
const kid = session === void 0 ? void 0 : kids.get(session);
|
|
1588
|
+
if (!kid) return false;
|
|
1589
|
+
if (kid.step.snapshot.status !== "active") return true;
|
|
1590
|
+
const delivered = kid.engine.deliver(kid, event);
|
|
1591
|
+
if (delivered.overflow) {
|
|
1592
|
+
overflow = true;
|
|
1593
|
+
endPath(link, {
|
|
1594
|
+
status: "max-depth",
|
|
1595
|
+
state: at.snapshot.value
|
|
1596
|
+
});
|
|
1597
|
+
return true;
|
|
1598
|
+
}
|
|
1599
|
+
kids.set(session, {
|
|
1600
|
+
...kid,
|
|
1601
|
+
step: delivered.step,
|
|
1602
|
+
kids: delivered.kids
|
|
1603
|
+
});
|
|
1604
|
+
queue.push(...delivered.outbound);
|
|
1605
|
+
if (delivered.step.snapshot.status !== "active") queue.push({ settle: session });
|
|
1606
|
+
return true;
|
|
1607
|
+
};
|
|
1608
|
+
const unrouted = (route) => {
|
|
1609
|
+
if (stepping) {
|
|
1610
|
+
outbound.push({ route });
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
unexpanded.add(route.event.type);
|
|
1614
|
+
note(() => `coupled: a child sent '${route.event.type}' to an actor the search does not model, at path [${pathTypes(link)}]`);
|
|
1615
|
+
};
|
|
1616
|
+
const flush = (at) => {
|
|
1617
|
+
if (pumped.has(at)) return;
|
|
1618
|
+
pumped.add(at);
|
|
1619
|
+
if (!register(at, kids, queue)) {
|
|
1620
|
+
overflow = true;
|
|
1621
|
+
endPath(link, {
|
|
1622
|
+
status: "max-depth",
|
|
1623
|
+
state: at.snapshot.value
|
|
1624
|
+
});
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
for (const effect of Array.isArray(at.actions) ? at.actions : []) {
|
|
1628
|
+
if (!isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
|
|
1629
|
+
deliverTo(at, effect["target"], effect["event"]);
|
|
1630
|
+
if (overflow) return;
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
flush(step);
|
|
1634
|
+
for (let i = 0; queue.length > 0 && !overflow; i++) {
|
|
1635
|
+
if (step.done || step.snapshot.status !== "active" || witness !== void 0) break;
|
|
1636
|
+
if (i >= MAX_PUMP) {
|
|
1637
|
+
endPath(link, {
|
|
1638
|
+
status: "max-depth",
|
|
1639
|
+
state: step.snapshot.value
|
|
1640
|
+
});
|
|
1641
|
+
note(() => `coupled: more than ${MAX_PUMP} deliveries at path [${pathTypes(link)}]`);
|
|
1642
|
+
overflow = true;
|
|
1643
|
+
break;
|
|
1644
|
+
}
|
|
1645
|
+
const item = queue.shift();
|
|
1646
|
+
if ("usage" in item) {
|
|
1647
|
+
if (stepping) {
|
|
1648
|
+
outbound.push(item);
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
const snapshot = step.snapshot;
|
|
1652
|
+
if (!declaresUsageTransition(snapshot) || !snapshot.can(item.usage)) continue;
|
|
1653
|
+
step = transitionStep(step, item.usage);
|
|
1654
|
+
link = extend(link, item.usage);
|
|
1655
|
+
} else if ("route" in item) {
|
|
1656
|
+
if (!deliverTo(step, item.route.target, item.route.event)) unrouted(item.route);
|
|
1657
|
+
continue;
|
|
1658
|
+
} else if ("event" in item) {
|
|
1659
|
+
const accepted = step.snapshot.can(item.event);
|
|
1660
|
+
step = transitionStep(step, item.event);
|
|
1661
|
+
if (accepted) link = extend(link, item.event);
|
|
1662
|
+
} else {
|
|
1663
|
+
const kid = kids.get(item.settle);
|
|
1664
|
+
if (!kid) continue;
|
|
1665
|
+
kids.delete(item.settle);
|
|
1666
|
+
const settledKid = kid.step.snapshot;
|
|
1667
|
+
if (settledKid.status === "done") {
|
|
1668
|
+
step = resolveStep(step, kid.id, settledKid.output);
|
|
1669
|
+
link = extend(link, {
|
|
1670
|
+
type: "xstate.done.actor",
|
|
1671
|
+
actorId: kid.id,
|
|
1672
|
+
output: settledKid.output
|
|
1673
|
+
});
|
|
1674
|
+
} else {
|
|
1675
|
+
step = rejectStep(step, kid.id, settledKid.error);
|
|
1676
|
+
link = extend(link, {
|
|
1677
|
+
type: "xstate.error.actor",
|
|
1678
|
+
actorId: kid.id,
|
|
1679
|
+
error: settledKid.error
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
recordState(step);
|
|
1684
|
+
outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
|
|
1685
|
+
flush(step);
|
|
1686
|
+
if (!overflow && stops(step, kids)) {
|
|
1687
|
+
witness = pathOf(link);
|
|
1688
|
+
break;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
return {
|
|
1692
|
+
step,
|
|
1693
|
+
link,
|
|
1694
|
+
kids,
|
|
1695
|
+
outbound,
|
|
1696
|
+
overflow
|
|
1697
|
+
};
|
|
1698
|
+
};
|
|
1699
|
+
let unkeyable = 0;
|
|
1700
|
+
const kidsKey = (kids) => {
|
|
1701
|
+
if (!kids || kids.size === 0) return "";
|
|
1702
|
+
return `\u0003${[...kids.values()].map((kid) => `${kid.id}\u0000${kid.src}\u0000${kid.engine.stateKey(kid)}`).sort().join("")}`;
|
|
1703
|
+
};
|
|
1704
|
+
const stateKey = (kid) => {
|
|
1705
|
+
const snapshot = kid.step.snapshot;
|
|
1706
|
+
try {
|
|
1707
|
+
return JSON.stringify([
|
|
1708
|
+
snapshot.value,
|
|
1709
|
+
snapshot.context,
|
|
1710
|
+
snapshot.status,
|
|
1711
|
+
snapshot.historyValue ?? null,
|
|
1712
|
+
kid.step.requests.map((request) => request.id),
|
|
1713
|
+
Object.keys(snapshot.children ?? {}),
|
|
1714
|
+
pumped.has(kid.step)
|
|
1715
|
+
]) + kidsKey(kid.kids);
|
|
1716
|
+
} catch {
|
|
1717
|
+
return `\u0002${unkeyable++}`;
|
|
1718
|
+
}
|
|
1719
|
+
};
|
|
1720
|
+
function* expand({ step, path, depth, delivered, kids: nodeKids }) {
|
|
1721
|
+
if (witness !== void 0 || capped()) return;
|
|
1722
|
+
nodesExpanded++;
|
|
1723
|
+
budget.nodes++;
|
|
1724
|
+
const { step: settled, blockedSrc, hit, fork, siblings, blockedSiblings, decisions, pending, kids: pendingKids } = advance(step, (event) => {
|
|
1725
|
+
path = extend(path, event);
|
|
1726
|
+
}, nodeKids);
|
|
1727
|
+
if (hit) {
|
|
1728
|
+
witness = pathOf(path);
|
|
1729
|
+
return;
|
|
1730
|
+
}
|
|
1731
|
+
if (pendingKids) {
|
|
1732
|
+
const kids = new Map(nodeKids ?? []);
|
|
1733
|
+
const sizeBefore = kids.size;
|
|
1734
|
+
const synced = pump(settled, path, kids, []);
|
|
1735
|
+
if (synced.overflow) return;
|
|
1736
|
+
if (witness !== void 0 || synced.step !== settled || synced.kids.size !== sizeBefore || [...synced.kids].some(([session, kid]) => nodeKids?.get(session) !== kid)) {
|
|
1737
|
+
if (witness === void 0) yield {
|
|
1738
|
+
step: synced.step,
|
|
1739
|
+
path: synced.link,
|
|
1740
|
+
depth,
|
|
1741
|
+
kids: synced.kids,
|
|
1742
|
+
outbound: synced.outbound
|
|
1743
|
+
};
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
if (stops(settled, nodeKids)) {
|
|
1747
|
+
witness = pathOf(path);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
if (options.dedupeBy) {
|
|
1752
|
+
const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
|
|
1753
|
+
const seenAt = visited.get(key);
|
|
1754
|
+
if (seenAt !== void 0 && seenAt <= depth) return;
|
|
1755
|
+
visited.set(key, depth);
|
|
1756
|
+
}
|
|
1757
|
+
if (pending) {
|
|
1758
|
+
if (depth >= maxDepth) {
|
|
1759
|
+
maxDepthTerminal(settled, path);
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
const resolved = settleStep(settled, pending.id, pending.output, pending.usage).step;
|
|
1763
|
+
recordState(resolved);
|
|
1764
|
+
const charged = pending.usage && !stepping ? extend(path, pending.usage) : path;
|
|
1765
|
+
yield {
|
|
1766
|
+
step: resolved,
|
|
1767
|
+
path: stepping ? extend(charged, {
|
|
1768
|
+
type: "xstate.done.actor",
|
|
1769
|
+
actorId: pending.id,
|
|
1770
|
+
output: pending.output
|
|
1771
|
+
}) : charged,
|
|
1772
|
+
depth
|
|
1773
|
+
};
|
|
1774
|
+
yield* raceBranches(settled, path, depth);
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
if (pendingKids) {
|
|
1778
|
+
if (depth >= maxDepth) {
|
|
1779
|
+
maxDepthTerminal(settled, path);
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
let moved = false;
|
|
1783
|
+
let quiet = true;
|
|
1784
|
+
for (const [session, kid] of nodeKids ?? []) {
|
|
1785
|
+
const { moves, blocked, idle } = kid.engine.moves(kid, depth);
|
|
1786
|
+
if (!idle && moves.length > 0) quiet = false;
|
|
1787
|
+
for (const type of kid.engine.unexpanded) unexpanded.add(type);
|
|
1788
|
+
for (const type of kid.engine.vacuous) vacuous.add(type);
|
|
1789
|
+
for (const terminal of blocked) {
|
|
1790
|
+
if (witness !== void 0 || capped()) return;
|
|
1791
|
+
if (terminal.status === "idle" || terminal.status === "done" || terminal.status === "error") continue;
|
|
1792
|
+
endPath(path, {
|
|
1793
|
+
status: terminal.status,
|
|
1794
|
+
state: settled.snapshot.value,
|
|
1795
|
+
...terminal.status === "needs-output" ? { missingSrc: terminal.missingSrc ?? kid.src } : {}
|
|
1796
|
+
});
|
|
1797
|
+
note(() => `child: src '${kid.src}' (actor '${kid.id}') stopped ${terminal.status} at path [${pathTypes(path)}]`);
|
|
1798
|
+
}
|
|
1799
|
+
for (const move of moves) {
|
|
1800
|
+
if (witness !== void 0 || capped()) return;
|
|
1801
|
+
moved = true;
|
|
1802
|
+
const kids = new Map(nodeKids);
|
|
1803
|
+
kids.set(session, {
|
|
1804
|
+
...kid,
|
|
1805
|
+
step: move.step,
|
|
1806
|
+
kids: move.kids
|
|
1807
|
+
});
|
|
1808
|
+
const queue = [...move.outbound];
|
|
1809
|
+
if (move.step.snapshot.status !== "active") queue.push({ settle: session });
|
|
1810
|
+
let link = path;
|
|
1811
|
+
for (const event of move.path) {
|
|
1812
|
+
const actor = typeof event["actor"] === "string" ? `${kid.id}.${event["actor"]}` : kid.id;
|
|
1813
|
+
link = extend(link, {
|
|
1814
|
+
...event,
|
|
1815
|
+
actor
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
let next = {
|
|
1819
|
+
step: settled,
|
|
1820
|
+
link,
|
|
1821
|
+
kids,
|
|
1822
|
+
outbound: []
|
|
1823
|
+
};
|
|
1824
|
+
for (const item of queue) {
|
|
1825
|
+
const after = pump(next.step, next.link, next.kids, [item]);
|
|
1826
|
+
next = {
|
|
1827
|
+
...after,
|
|
1828
|
+
outbound: [...next.outbound, ...after.outbound]
|
|
1829
|
+
};
|
|
1830
|
+
if (after.overflow || witness !== void 0 || after.step.snapshot.status !== "active") break;
|
|
1831
|
+
}
|
|
1832
|
+
if (witness !== void 0) return;
|
|
1833
|
+
if (next.overflow) continue;
|
|
1834
|
+
yield {
|
|
1835
|
+
step: next.step,
|
|
1836
|
+
path: next.link,
|
|
1837
|
+
depth: move.depth,
|
|
1838
|
+
kids: next.kids,
|
|
1839
|
+
outbound: next.outbound
|
|
1840
|
+
};
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
const registered = new Set([...(nodeKids ?? /* @__PURE__ */ new Map()).values()].map((kid) => kid.id));
|
|
1844
|
+
for (const kid of pendingKids.filter((invoke) => !registered.has(invoke.id))) {
|
|
1845
|
+
if (witness !== void 0 || capped()) return;
|
|
1846
|
+
endPath(path, {
|
|
1847
|
+
status: "needs-output",
|
|
1848
|
+
state: settled.snapshot.value,
|
|
1849
|
+
missingSrc: kid.src
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
const others = [...fork ? [fork] : [], ...siblings ?? []];
|
|
1853
|
+
for (const other of others) {
|
|
1854
|
+
for (const error of other.errors) {
|
|
1855
|
+
if (witness !== void 0 || capped()) return;
|
|
1856
|
+
yield failBranch(settled, path, depth, other, error);
|
|
1857
|
+
}
|
|
1858
|
+
for (const output of other.outputs) {
|
|
1859
|
+
if (witness !== void 0 || capped()) return;
|
|
1860
|
+
yield* doneBranches(settled, path, depth, other, output);
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
for (const src of blockedSiblings ?? []) {
|
|
1864
|
+
if (witness !== void 0 || capped()) return;
|
|
1865
|
+
endPath(path, {
|
|
1866
|
+
status: "needs-output",
|
|
1867
|
+
state: settled.snapshot.value,
|
|
1868
|
+
missingSrc: src
|
|
1869
|
+
});
|
|
1870
|
+
note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
|
|
1871
|
+
}
|
|
1872
|
+
if (!decisions?.length && (moved || others.length > 0 || (blockedSiblings ?? []).length > 0)) {
|
|
1873
|
+
if (interleaving || quiet && others.length === 0 && !blockedSiblings?.length) yield* raceBranches(settled, path, depth);
|
|
1874
|
+
return;
|
|
1875
|
+
}
|
|
1876
|
+
if (witness !== void 0) return;
|
|
1877
|
+
}
|
|
1878
|
+
if (fork && !pendingKids) {
|
|
1879
|
+
if (depth >= maxDepth) {
|
|
1880
|
+
maxDepthTerminal(settled, path);
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
for (const error of fork.errors) {
|
|
1884
|
+
if (witness !== void 0 || capped()) return;
|
|
1885
|
+
yield failBranch(settled, path, depth, fork, error);
|
|
1886
|
+
}
|
|
1887
|
+
if (!fork.isDecision) {
|
|
1888
|
+
for (const output of fork.outputs) {
|
|
1889
|
+
if (witness !== void 0 || capped()) return;
|
|
1890
|
+
yield* doneBranches(settled, path, depth, fork, output);
|
|
1891
|
+
}
|
|
1892
|
+
for (const other of siblings ?? []) {
|
|
1893
|
+
for (const error of other.errors) {
|
|
1894
|
+
if (witness !== void 0 || capped()) return;
|
|
1895
|
+
yield failBranch(settled, path, depth, other, error);
|
|
1896
|
+
}
|
|
1897
|
+
for (const output of other.outputs) {
|
|
1898
|
+
if (witness !== void 0 || capped()) return;
|
|
1899
|
+
yield* doneBranches(settled, path, depth, other, output);
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
for (const child of [fork, ...siblings ?? []]) for (const event of child.events ?? []) {
|
|
1903
|
+
if (witness !== void 0 || capped()) return;
|
|
1904
|
+
const key = `${child.session ?? child.id}\u0000${JSON.stringify(event)}`;
|
|
1905
|
+
if (delivered?.has(key) || !settled.snapshot.can(event)) continue;
|
|
1906
|
+
const next = transitionStep(settled, event);
|
|
1907
|
+
recordState(next);
|
|
1908
|
+
yield {
|
|
1909
|
+
step: next,
|
|
1910
|
+
path: extend(path, event),
|
|
1911
|
+
depth: depth + 1,
|
|
1912
|
+
delivered: /* @__PURE__ */ new Set([...delivered ?? [], key])
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
if (fork.stalls && witness === void 0 && !capped()) endPath(path, {
|
|
1916
|
+
status: "idle",
|
|
1917
|
+
state: settled.snapshot.value
|
|
1918
|
+
});
|
|
1919
|
+
for (const src of blockedSiblings ?? []) note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
|
|
1920
|
+
for (const incompleteSrc of [...[fork, ...siblings ?? []].flatMap((child) => child.incompleteSrc === void 0 ? [] : [child.incompleteSrc]), ...blockedSiblings ?? []]) {
|
|
1921
|
+
if (witness !== void 0 || capped()) break;
|
|
1922
|
+
endPath(path, {
|
|
1923
|
+
status: "needs-output",
|
|
1924
|
+
state: settled.snapshot.value,
|
|
1925
|
+
missingSrc: incompleteSrc
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
if (!decisions?.length) {
|
|
1929
|
+
if (interleaving) yield* raceBranches(settled, path, depth);
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
if (witness !== void 0) return;
|
|
1934
|
+
}
|
|
1935
|
+
if (blockedSrc) {
|
|
1936
|
+
endPath(path, {
|
|
1937
|
+
status: "needs-output",
|
|
1938
|
+
state: settled.snapshot.value,
|
|
1939
|
+
missingSrc: blockedSrc
|
|
1940
|
+
});
|
|
1941
|
+
note(() => `needs-output: no \`outputs\` entry for src '${blockedSrc}' at path [${pathTypes(path)}]`);
|
|
1942
|
+
if (interleaving && depth < maxDepth) yield* raceBranches(settled, path, depth);
|
|
1943
|
+
return;
|
|
1944
|
+
}
|
|
1945
|
+
if (settled.done) {
|
|
1946
|
+
const output = settled.snapshot.output;
|
|
1947
|
+
endPath(path, {
|
|
1948
|
+
status: "done",
|
|
1949
|
+
state: settled.snapshot.value,
|
|
1950
|
+
...output === void 0 ? {} : { output }
|
|
1951
|
+
});
|
|
1952
|
+
pushDistinct(doneOutputs, seenOutputs, output);
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
if (settled.snapshot.status === "error") {
|
|
1956
|
+
const error = settled.snapshot.error;
|
|
1957
|
+
endPath(path, {
|
|
1958
|
+
status: "error",
|
|
1959
|
+
state: settled.snapshot.value,
|
|
1960
|
+
error
|
|
1961
|
+
});
|
|
1962
|
+
pushDistinct(failures, seenFailures, error);
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
const snapshot = settled.snapshot;
|
|
1966
|
+
const table = options.payloads?.(snapshot) ?? {};
|
|
1967
|
+
const branchRequests = decisions?.length ? decisions : [settled.requests.find((request) => request.kind !== "text" || !neverSettles(request.src))];
|
|
1968
|
+
for (const request of branchRequests) {
|
|
1969
|
+
const requestOptions = request?.kind === "decision" ? acceptedDecisionOptions(request, () => true) : void 0;
|
|
1970
|
+
const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : acceptedVariants(snapshot, path, table);
|
|
1971
|
+
if (branchEvents.length === 0 && request?.kind !== "decision") {
|
|
1972
|
+
endPath(path, {
|
|
1973
|
+
status: "idle",
|
|
1974
|
+
state: settled.snapshot.value
|
|
1975
|
+
});
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
if (depth >= maxDepth) {
|
|
1979
|
+
endPath(path, {
|
|
1980
|
+
status: "max-depth",
|
|
1981
|
+
state: settled.snapshot.value
|
|
1982
|
+
});
|
|
1983
|
+
note(() => `max-depth: stopped at path [${pathTypes(path)}]`);
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
let taken = 0;
|
|
1987
|
+
for (const event of branchEvents) {
|
|
1988
|
+
if (witness !== void 0 || capped()) return;
|
|
1989
|
+
if (!snapshot.can(event)) {
|
|
1990
|
+
prunedByGuard++;
|
|
1991
|
+
continue;
|
|
1992
|
+
}
|
|
1993
|
+
taken++;
|
|
1994
|
+
const next = transitionStep(settled, applied(event));
|
|
1995
|
+
recordState(next);
|
|
1996
|
+
yield {
|
|
1997
|
+
step: next,
|
|
1998
|
+
path: extend(path, event),
|
|
1999
|
+
depth: depth + 1
|
|
2000
|
+
};
|
|
2001
|
+
}
|
|
2002
|
+
if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
|
|
2003
|
+
endPath(path, {
|
|
2004
|
+
status: "idle",
|
|
2005
|
+
state: settled.snapshot.value
|
|
2006
|
+
});
|
|
2007
|
+
const refused = [...new Set(branchEvents.map((event) => event.type))];
|
|
2008
|
+
for (const type of refused) unexpanded.add(type);
|
|
2009
|
+
note(() => `stuck: every offered ${refused.join(", ")} event at path [${pathTypes(path)}] was refused by the machine's guards; add a payloads entry it accepts`);
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
if (request?.kind === "decision" && taken === 0) {
|
|
2013
|
+
if (witness !== void 0 || capped()) return;
|
|
2014
|
+
const exhausted = new AgentDecisionExhaustedError([]);
|
|
2015
|
+
exhausted.message = `Decision '${request.name ?? request.id}' has no candidate the current snapshot accepts (explored, no model call).`;
|
|
2016
|
+
const failed = rejectStep(settled, request.id, exhausted);
|
|
2017
|
+
recordState(failed);
|
|
2018
|
+
yield {
|
|
2019
|
+
step: failed,
|
|
2020
|
+
path: extend(path, {
|
|
2021
|
+
type: "xstate.error.actor",
|
|
2022
|
+
actorId: request.id
|
|
2023
|
+
}),
|
|
2024
|
+
depth: depth + 1
|
|
2025
|
+
};
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
const offered = branchRequests.filter((request) => request?.kind === "decision");
|
|
2029
|
+
if (interleaving && offered.length > 0) yield* raceBranches(settled, path, depth, new Set(offered.flatMap((request) => request.events.map((descriptor) => descriptor.type))));
|
|
2030
|
+
}
|
|
2031
|
+
if (stepping) {
|
|
2032
|
+
const stepper = {
|
|
2033
|
+
moves(kid, depth) {
|
|
2034
|
+
const outer = {
|
|
2035
|
+
captured,
|
|
2036
|
+
outParent
|
|
2037
|
+
};
|
|
2038
|
+
captured = [];
|
|
2039
|
+
outParent = kid.parent;
|
|
2040
|
+
try {
|
|
2041
|
+
const idle = stepper.quiet(kid);
|
|
2042
|
+
const moves = [];
|
|
2043
|
+
for (const node of expand({
|
|
2044
|
+
step: kid.step,
|
|
2045
|
+
path: void 0,
|
|
2046
|
+
depth,
|
|
2047
|
+
kids: kid.kids
|
|
2048
|
+
})) {
|
|
2049
|
+
const settledMove = pump(node.step, node.path, new Map(node.kids ?? kid.kids ?? []), []);
|
|
2050
|
+
if (settledMove.overflow) continue;
|
|
2051
|
+
moves.push({
|
|
2052
|
+
step: settledMove.step,
|
|
2053
|
+
path: pathOf(settledMove.link),
|
|
2054
|
+
depth: node.depth,
|
|
2055
|
+
kids: settledMove.kids,
|
|
2056
|
+
outbound: [
|
|
2057
|
+
...charges.has(node.step) ? [{ usage: charges.get(node.step) }] : [],
|
|
2058
|
+
...node.outbound ?? outboundOf(node.step.actions, kid.parent, node.step.snapshot.children),
|
|
2059
|
+
...settledMove.outbound
|
|
2060
|
+
]
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
return {
|
|
2064
|
+
moves,
|
|
2065
|
+
blocked: captured,
|
|
2066
|
+
idle
|
|
2067
|
+
};
|
|
2068
|
+
} finally {
|
|
2069
|
+
captured = outer.captured;
|
|
2070
|
+
outParent = outer.outParent;
|
|
2071
|
+
}
|
|
2072
|
+
},
|
|
2073
|
+
deliver(kid, event) {
|
|
2074
|
+
const outer = outParent;
|
|
2075
|
+
outParent = kid.parent;
|
|
2076
|
+
try {
|
|
2077
|
+
const primed = pump(kid.step, void 0, new Map(kid.kids ?? []), []);
|
|
2078
|
+
if (primed.overflow) return {
|
|
2079
|
+
...primed,
|
|
2080
|
+
overflow: true
|
|
2081
|
+
};
|
|
2082
|
+
const next = transitionStep(primed.step, event);
|
|
2083
|
+
recordState(next);
|
|
2084
|
+
const pumpedKids = pump(next, void 0, primed.kids, []);
|
|
2085
|
+
return {
|
|
2086
|
+
step: pumpedKids.step,
|
|
2087
|
+
kids: pumpedKids.kids,
|
|
2088
|
+
outbound: [
|
|
2089
|
+
...primed.outbound,
|
|
2090
|
+
...outboundOf(next.actions, kid.parent, next.snapshot.children),
|
|
2091
|
+
...pumpedKids.outbound
|
|
2092
|
+
],
|
|
2093
|
+
...pumpedKids.overflow ? { overflow: true } : {}
|
|
2094
|
+
};
|
|
2095
|
+
} finally {
|
|
2096
|
+
outParent = outer;
|
|
2097
|
+
}
|
|
2098
|
+
},
|
|
2099
|
+
prime(kid) {
|
|
2100
|
+
const outer = outParent;
|
|
2101
|
+
outParent = kid.parent;
|
|
2102
|
+
try {
|
|
2103
|
+
return pump(kid.step, void 0, new Map(kid.kids ?? []), []);
|
|
2104
|
+
} finally {
|
|
2105
|
+
outParent = outer;
|
|
2106
|
+
}
|
|
2107
|
+
},
|
|
2108
|
+
quiet(kid) {
|
|
2109
|
+
if (kid.step.requests.length > 0) return false;
|
|
2110
|
+
const held = [...(kid.kids ?? /* @__PURE__ */ new Map()).values()];
|
|
2111
|
+
return pendingInvokes(kid.step).every((invoke) => {
|
|
2112
|
+
const child = held.find((candidate) => candidate.id === invoke.id);
|
|
2113
|
+
return child !== void 0 && child.engine.quiet(child);
|
|
2114
|
+
});
|
|
2115
|
+
},
|
|
2116
|
+
stateKey,
|
|
2117
|
+
unexpanded,
|
|
2118
|
+
vacuous
|
|
2119
|
+
};
|
|
2120
|
+
return {
|
|
2121
|
+
report: void 0,
|
|
2122
|
+
doneOutputs,
|
|
2123
|
+
failures,
|
|
2124
|
+
undeliverable: [],
|
|
2125
|
+
parentEvents,
|
|
2126
|
+
stalls,
|
|
2127
|
+
unfinished,
|
|
2128
|
+
stepper
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
const root = {
|
|
2132
|
+
step: initial,
|
|
2133
|
+
path: void 0,
|
|
2134
|
+
depth: 0
|
|
2135
|
+
};
|
|
2136
|
+
if (witness === void 0 && stopWhen) {
|
|
2137
|
+
const levels = [[root]];
|
|
2138
|
+
search: for (let length = 0; length < levels.length; length++) {
|
|
2139
|
+
const level = levels[length] ?? [];
|
|
2140
|
+
for (let i = 0; i < level.length; i++) {
|
|
2141
|
+
const node = level[i];
|
|
2142
|
+
level[i] = void 0;
|
|
2143
|
+
for (const child of expand(node)) {
|
|
2144
|
+
child.delivered = pruneDelivered(child.delivered ?? node.delivered, child.step);
|
|
2145
|
+
child.kids ??= node.kids;
|
|
2146
|
+
(levels[child.path?.length ?? 0] ??= []).push(child);
|
|
2147
|
+
}
|
|
2148
|
+
if (witness !== void 0 || hitPathCap || budget.exhausted !== void 0) break search;
|
|
2149
|
+
}
|
|
2150
|
+
levels[length] = [];
|
|
2151
|
+
}
|
|
2152
|
+
} else if (witness === void 0) {
|
|
2153
|
+
const visit = (node) => {
|
|
2154
|
+
for (const child of expand(node)) {
|
|
2155
|
+
child.delivered = pruneDelivered(child.delivered ?? node.delivered, child.step);
|
|
2156
|
+
child.kids ??= node.kids;
|
|
2157
|
+
visit(child);
|
|
2158
|
+
}
|
|
2159
|
+
};
|
|
2160
|
+
visit(root);
|
|
2161
|
+
}
|
|
2162
|
+
if (nesting === 0 && budget.exhausted !== void 0) unexplored.push(`budget-exhausted: ${budget.exhausted} (${budget.nodes} nodes expanded in ${Date.now() - budget.started} ms, child searches included)`);
|
|
2163
|
+
const partial = hitPathCap || budget.exhausted !== void 0;
|
|
2164
|
+
const report = {
|
|
2165
|
+
reachedStates: reachedValues,
|
|
2166
|
+
terminals,
|
|
2167
|
+
prunedByGuard,
|
|
2168
|
+
unexplored,
|
|
2169
|
+
pathsExplored,
|
|
2170
|
+
hitPathCap,
|
|
2171
|
+
partial,
|
|
2172
|
+
complete: false,
|
|
2173
|
+
unexpandedEvents: [...unexpanded],
|
|
2174
|
+
vacuous: [...vacuous]
|
|
2175
|
+
};
|
|
2176
|
+
report.complete = isExplorationComplete(report);
|
|
2177
|
+
return {
|
|
2178
|
+
report,
|
|
2179
|
+
witness,
|
|
2180
|
+
doneOutputs,
|
|
2181
|
+
failures,
|
|
2182
|
+
undeliverable: [...undeliverable],
|
|
2183
|
+
parentEvents,
|
|
2184
|
+
stalls,
|
|
2185
|
+
unfinished
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
/**
|
|
2189
|
+
* Enumerates a machine's decision and external-event branches to a bounded
|
|
2190
|
+
* depth, model-free, and reports which states are reached and how each path
|
|
2191
|
+
* terminates. At each decision request it forks one branch per candidate event
|
|
2192
|
+
* (guard-rejected candidates are counted in `prunedByGuard`, not explored); a
|
|
2193
|
+
* decision with no takeable candidate exhausts as it does live, taking its
|
|
2194
|
+
* `onError` (an `error` terminal without one). At an idle wait it forks per
|
|
2195
|
+
* externally-accepted event. Text requests and other
|
|
2196
|
+
* invokes resolve from `outputs`, a by-src map of outputs to try (a
|
|
2197
|
+
* one-element list is a canned output; several fork one branch each), and a
|
|
2198
|
+
* missing src halts that branch with a `needs-output` terminal rather than
|
|
2199
|
+
* throwing. A src in
|
|
2200
|
+
* `errors` forks an extra branch where that invoke is rejected, so states
|
|
2201
|
+
* behind an `onError` are explored too.
|
|
2202
|
+
*
|
|
2203
|
+
* Events are applied as `{ type }` unless a payload is known: `payloads`
|
|
2204
|
+
* forks a type once per listed payload, a decide input's own `payloads`
|
|
2205
|
+
* become the branch set, and an event schema whose fields are finite (enums,
|
|
2206
|
+
* booleans, consts) expands to their product, each optional field also
|
|
2207
|
+
* omitted. A type that could not be fully expanded is listed in
|
|
2208
|
+
* `unexpandedEvents`, as is a type with no schema whose transition could read
|
|
2209
|
+
* the payload (a function transition, guard, `matches`, or context mapper).
|
|
2210
|
+
* `dedupeBy` explores each projected snapshot once, which keeps a large
|
|
2211
|
+
* payload table tractable.
|
|
2212
|
+
*
|
|
2213
|
+
* Combinatorics are bounded by `maxDepth` (default 8), `maxPaths` (default
|
|
2214
|
+
* 200), and `maxNodes` (default 100,000) per search, the last two reported
|
|
2215
|
+
* via `hitPathCap`, and by `budget` across the whole call, child searches
|
|
2216
|
+
* included. A cut-short report is `partial` and not `complete`.
|
|
2217
|
+
*
|
|
2218
|
+
* @example
|
|
2219
|
+
* ```ts
|
|
2220
|
+
* const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
|
|
2221
|
+
* // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
|
|
2222
|
+
* ```
|
|
2223
|
+
*/
|
|
2224
|
+
async function explorePaths(machine, options = {}) {
|
|
2225
|
+
return explore(machine, options).report;
|
|
2226
|
+
}
|
|
2227
|
+
/** Thrown when a string reachability target is not a state in the machine. */
|
|
2228
|
+
var AgentUnknownStateError = class extends AgentError {
|
|
2229
|
+
target;
|
|
2230
|
+
constructor(machineId, target) {
|
|
2231
|
+
super("unknown-state", `canReach: machine '${machineId}' has no state matching '${target}'.`);
|
|
2232
|
+
this.name = "AgentUnknownStateError";
|
|
2233
|
+
this.target = target;
|
|
2234
|
+
}
|
|
2235
|
+
};
|
|
2236
|
+
function resolveStateTarget(machine, target) {
|
|
2237
|
+
const stack = [machine.root];
|
|
2238
|
+
while (stack.length > 0) {
|
|
2239
|
+
const node = stack.pop();
|
|
2240
|
+
if (node.id === target.replace(/^#/, "") || node.path.join(".") === target) return node.id;
|
|
2241
|
+
stack.push(...Object.values(node.states));
|
|
2242
|
+
}
|
|
2243
|
+
throw new AgentUnknownStateError(machine.id, target);
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* Answers "can the machine reach this?" by exploring its branches (a thin
|
|
2247
|
+
* wrapper over {@link explorePaths}). The target is either a state path string
|
|
2248
|
+
* (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
|
|
2249
|
+
* form checks any property (a context invariant, a tag, a state+context
|
|
2250
|
+
* combination) without reifying a sentinel state for it. Returns
|
|
2251
|
+
* `{ reachable: true, witness }` with the event sequence that reaches it, or
|
|
2252
|
+
* `{ reachable: false }`. Check `complete` before treating `reachable: false`
|
|
2253
|
+
* as a proof: it is false when a cap or `maxDepth` cut exploration short, a
|
|
2254
|
+
* branch needed an `outputs` entry it did not have, or an event's payloads were
|
|
2255
|
+
* not all tried.
|
|
2256
|
+
*
|
|
2257
|
+
* @example
|
|
2258
|
+
* ```ts
|
|
2259
|
+
* const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
|
|
2260
|
+
* // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
|
|
2261
|
+
* ```
|
|
2262
|
+
*
|
|
2263
|
+
* @example Predicate target — a violation property, no sentinel state needed
|
|
2264
|
+
* ```ts
|
|
2265
|
+
* const violation = await canReach(
|
|
2266
|
+
* refundMachine,
|
|
2267
|
+
* (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
|
|
2268
|
+
* { input: { amount: 5000 } },
|
|
2269
|
+
* );
|
|
2270
|
+
* // violation.reachable → false is the safety proof
|
|
2271
|
+
* ```
|
|
2272
|
+
*/
|
|
2273
|
+
async function canReach(machine, target, options = {}) {
|
|
2274
|
+
const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
|
|
2275
|
+
const { witness, report } = explore(machine, options, typeof target === "function" ? target : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget), 0, void 0, void 0, resolvedTarget !== void 0 && hasTransientStates(machine.getStateNodeById(resolvedTarget)));
|
|
2276
|
+
if (witness !== void 0) return {
|
|
2277
|
+
reachable: true,
|
|
2278
|
+
witness,
|
|
2279
|
+
complete: true,
|
|
2280
|
+
...resolvedTarget ? { target: resolvedTarget } : {}
|
|
2281
|
+
};
|
|
2282
|
+
const complete = isExplorationComplete(report);
|
|
2283
|
+
return {
|
|
2284
|
+
reachable: false,
|
|
2285
|
+
complete,
|
|
2286
|
+
...resolvedTarget ? { target: resolvedTarget } : {},
|
|
2287
|
+
...complete ? {} : { unexplored: [
|
|
2288
|
+
...report.unexplored,
|
|
2289
|
+
...report.hitPathCap ? [`path-cap: maxPaths or maxNodes cut the search short after ${report.pathsExplored} paths`] : [],
|
|
2290
|
+
...report.unexpandedEvents.length ? [`unexpanded-events: not every payload variant was explored for ${report.unexpandedEvents.join(", ")}`] : [],
|
|
2291
|
+
...report.terminals.some((terminal) => terminal.status === "max-depth") ? ["max-depth: a path reached maxDepth before settling"] : []
|
|
2292
|
+
] }
|
|
2293
|
+
};
|
|
2294
|
+
}
|
|
2295
|
+
/**
|
|
2296
|
+
* Whether an `explorePaths` report covers every path: no cap cut it short,
|
|
2297
|
+
* every payload was expanded, and every branch ended on its own. `done`,
|
|
2298
|
+
* `idle`, and `error` end a branch the machine itself ended; any other
|
|
2299
|
+
* terminal stopped a branch the search did not explore.
|
|
2300
|
+
* @internal
|
|
2301
|
+
*/
|
|
2302
|
+
function isExplorationComplete(report) {
|
|
2303
|
+
return !report.hitPathCap && !report.partial && report.unexpandedEvents.length === 0 && report.terminals.every((terminal) => terminal.status === "done" || terminal.status === "idle" || terminal.status === "error");
|
|
2304
|
+
}
|
|
2305
|
+
//#endregion
|
|
2306
|
+
export { explorePaths as a, simulateAgent as c, canReach as i, textOutput as l, AgentUnknownStateError as n, isExplorationComplete as o, assertAgentMachine as r, lintAgentMachine as s, AgentLintError as t };
|