@statelyai/agent 1.1.6 → 2.0.0-alpha.6
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/LICENSE +21 -0
- package/dist/ai-sdk.cjs +249 -0
- package/dist/ai-sdk.d.cts +168 -0
- package/dist/ai-sdk.d.mts +168 -0
- package/dist/ai-sdk.mjs +241 -0
- package/dist/cli.cjs +63 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +64 -0
- package/dist/decision-CX3YdwrO.cjs +1239 -0
- package/dist/decision-D1654JdD.mjs +940 -0
- package/dist/index.cjs +54 -0
- package/dist/index.d.cts +1217 -0
- package/dist/index.d.mts +1194 -405
- package/dist/index.mjs +3 -588
- package/dist/openai-compat.cjs +319 -0
- package/dist/openai-compat.d.cts +98 -0
- package/dist/openai-compat.d.mts +98 -0
- package/dist/openai-compat.mjs +312 -0
- package/dist/src-CEa947Dm.mjs +2449 -0
- package/dist/src-wBfi-kTA.cjs +2568 -0
- package/dist/text-logic-1ZQkO3zr.d.cts +682 -0
- package/dist/text-logic-2EMJIS-n.d.mts +682 -0
- package/dist/types-BHjeDdch.d.cts +208 -0
- package/dist/types-Cq1YlAQ6.d.mts +208 -0
- package/dist/utils-CWUCa3pF.d.mts +108 -0
- package/dist/utils-lK1wnL2i.d.cts +108 -0
- package/dist/zod.cjs +31 -0
- package/dist/zod.d.cts +30 -0
- package/dist/zod.d.mts +30 -0
- package/dist/zod.mjs +30 -0
- package/package.json +109 -28
- package/readme.md +144 -6
- package/schemas/agent-workflow.json +527 -0
- package/.changeset/README.md +0 -8
- package/.changeset/config.json +0 -11
- package/.env.template +0 -3
- package/.github/actions/ci-setup/action.yml +0 -24
- package/.github/workflows/release.yml +0 -46
- package/.vscode/launch.json +0 -28
- package/CHANGELOG.md +0 -222
- package/dist/index.d.ts +0 -428
- package/dist/index.js +0 -621
- package/examples/chatbot.ts +0 -71
- package/examples/cot.ts +0 -89
- package/examples/email.ts +0 -118
- package/examples/example.ts +0 -81
- package/examples/goal.ts +0 -94
- package/examples/helpers/helpers.ts +0 -17
- package/examples/helpers/loader.ts +0 -32
- package/examples/helpers/runner.ts +0 -27
- package/examples/joke.ts +0 -225
- package/examples/multi.ts +0 -103
- package/examples/newspaper.ts +0 -324
- package/examples/number.ts +0 -102
- package/examples/raffle.ts +0 -105
- package/examples/sandbox.ts +0 -28
- package/examples/simple.ts +0 -39
- package/examples/support.ts +0 -147
- package/examples/ticTacToe.ts +0 -224
- package/examples/todo.ts +0 -137
- package/examples/tutor.ts +0 -100
- package/examples/verify.ts +0 -120
- package/examples/weather.ts +0 -178
- package/examples/wiki.ts +0 -30
- package/examples/word.ts +0 -171
- package/src/adapters/vercel.ts +0 -7
- package/src/agent-experimental.ts +0 -221
- package/src/agent.test.ts +0 -506
- package/src/agent.ts +0 -300
- package/src/decision.test.ts +0 -179
- package/src/decision.ts +0 -84
- package/src/index.ts +0 -4
- package/src/memory.ts +0 -25
- package/src/planners/shortestPathPlanner.ts +0 -22
- package/src/planners/simplePlanner.ts +0 -139
- package/src/schemas.ts +0 -11
- package/src/strategies/chain-of-note.ts +0 -155
- package/src/templates/defaultText.ts +0 -18
- package/src/text.ts +0 -241
- package/src/types.ts +0 -499
- package/src/utils.ts +0 -72
- package/tsconfig.json +0 -109
- package/vitest.config.ts +0 -9
|
@@ -0,0 +1,2449 @@
|
|
|
1
|
+
import { A as userInputActor, B as getAgentMessages, C as createTextLogic, D as isTextLogic, F as isUnboundPlaceholder, H as getJsonSchemaSync, I as machineSuspensionPredicates, L as missingActor, M as executorBoundLogics, N as getMachineSuspensionPredicate, O as normalizeGeneratorResult, P as getRegisteredAgentExecutionOptions, R as assistantMessage, S as builtinTextActors, U as getMachineStructuralHash, X as validateSchemaSync, Y as userMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, j as agentExecutionOptions, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, w as executeAgentTextRequest, y as USER_INPUT_ACTOR, z as findNonSerializableContextPaths } from "./decision-D1654JdD.mjs";
|
|
2
|
+
import { createActor, createAsyncLogic, getNextTransitions, initialTransition, setup, transition } from "xstate";
|
|
3
|
+
//#region src/messages.ts
|
|
4
|
+
function addMessages(resolve) {
|
|
5
|
+
return (args) => {
|
|
6
|
+
const resolved = typeof resolve === "function" ? resolve(args) : resolve;
|
|
7
|
+
return [...args.context.messages, ...Array.isArray(resolved) ? resolved : [resolved]];
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Builds a transition-function result that appends one or more
|
|
12
|
+
* {@link AgentMessage}s to a context's `messages` array. `resolve` is either
|
|
13
|
+
* a message (or array of messages) or a function of `{ context, event }`
|
|
14
|
+
* returning them; the returned function is meant to be used directly as (or
|
|
15
|
+
* composed into) a transition's result, e.g. `on: { USER_REPLIED:
|
|
16
|
+
* agent.appendMessages(({ event }) => userMessage(event.text)) }`. Requires
|
|
17
|
+
* `messages: AgentMessage[]` on context — see {@link messagesSchema} for a
|
|
18
|
+
* ready-made schema for that field.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* on: {
|
|
23
|
+
* USER_REPLIED: appendMessages(({ event }) => userMessage(event.text)),
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
function appendMessages(resolve) {
|
|
28
|
+
return (args) => ({ context: { messages: addMessages(resolve)(args) } });
|
|
29
|
+
}
|
|
30
|
+
const KNOWN_PART_TYPES = new Set([
|
|
31
|
+
"text",
|
|
32
|
+
"image",
|
|
33
|
+
"file",
|
|
34
|
+
"tool-call",
|
|
35
|
+
"tool-result"
|
|
36
|
+
]);
|
|
37
|
+
function isKnownPart(part) {
|
|
38
|
+
return !!part && typeof part === "object" && KNOWN_PART_TYPES.has(part.type);
|
|
39
|
+
}
|
|
40
|
+
function validatePartsArray(content) {
|
|
41
|
+
if (!Array.isArray(content)) return "Expected content to be a string or an array of parts";
|
|
42
|
+
for (const part of content) if (!isKnownPart(part)) {
|
|
43
|
+
const type = part && typeof part === "object" ? part.type : void 0;
|
|
44
|
+
return `Unknown message part type: ${JSON.stringify(type)}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
|
|
49
|
+
* checks that every message has a known `role` (`system`/`user`/`assistant`/
|
|
50
|
+
* `tool`) and that `content` is either a string (where the role allows it) or
|
|
51
|
+
* an array of parts with a known `type`. Use it directly as a context
|
|
52
|
+
* schema's `messages` field when authoring with `createAgentSchemas`.
|
|
53
|
+
*/
|
|
54
|
+
const messagesSchema = { "~standard": {
|
|
55
|
+
version: 1,
|
|
56
|
+
vendor: "statelyai-agent",
|
|
57
|
+
validate(value) {
|
|
58
|
+
if (!Array.isArray(value)) return { issues: [{ message: "Expected an array of agent messages" }] };
|
|
59
|
+
for (const message of value) {
|
|
60
|
+
if (!message || typeof message !== "object") return { issues: [{ message: "Expected an array of agent messages" }] };
|
|
61
|
+
const role = message.role;
|
|
62
|
+
const content = message.content;
|
|
63
|
+
if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") return { issues: [{ message: `Unknown message role: ${JSON.stringify(role)}` }] };
|
|
64
|
+
if (role === "system") {
|
|
65
|
+
if (typeof content !== "string") return { issues: [{ message: "system message content must be a string" }] };
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (role === "tool") {
|
|
69
|
+
const error = validatePartsArray(content) ?? (content.some((part) => part.type !== "tool-result") ? "tool message content must contain only tool-result parts" : void 0);
|
|
70
|
+
if (error) return { issues: [{ message: error }] };
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (typeof content === "string") continue;
|
|
74
|
+
const error = validatePartsArray(content);
|
|
75
|
+
if (error) return { issues: [{ message: error }] };
|
|
76
|
+
}
|
|
77
|
+
return { value };
|
|
78
|
+
}
|
|
79
|
+
} };
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/workflow-config.ts
|
|
82
|
+
const workflowConfigWholeExpressionPattern = /^\{\{\s*([\s\S]*?)\s*\}\}$/;
|
|
83
|
+
const workflowConfigTemplateExpressionPattern = /\{\{\s*([\s\S]*?)\s*\}\}/g;
|
|
84
|
+
function evaluateWorkflowConfigPath(expression, scope) {
|
|
85
|
+
const parts = expression.trim().split(".").filter(Boolean);
|
|
86
|
+
let current = scope;
|
|
87
|
+
for (const part of parts) {
|
|
88
|
+
if (!current || typeof current !== "object") return;
|
|
89
|
+
current = current[part];
|
|
90
|
+
}
|
|
91
|
+
return current;
|
|
92
|
+
}
|
|
93
|
+
function evaluateWorkflowConfigValue(value, scope) {
|
|
94
|
+
if (typeof value === "string") {
|
|
95
|
+
const wholeMatch = value.match(workflowConfigWholeExpressionPattern);
|
|
96
|
+
if (wholeMatch?.[1]) return evaluateWorkflowConfigPath(wholeMatch[1], scope);
|
|
97
|
+
return value.replace(workflowConfigTemplateExpressionPattern, (_match, expression) => {
|
|
98
|
+
const resolved = evaluateWorkflowConfigPath(expression, scope);
|
|
99
|
+
return resolved === void 0 || resolved === null ? "" : String(resolved);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (Array.isArray(value)) return value.map((item) => evaluateWorkflowConfigValue(item, scope));
|
|
103
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, evaluateWorkflowConfigValue(item, scope)]));
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
function createSchemasFromWorkflowConfig(config, compileSchema) {
|
|
107
|
+
return createAgentSchemas({
|
|
108
|
+
context: compileSchema(config.schemas?.context ?? { type: "object" }, "context"),
|
|
109
|
+
events: Object.fromEntries(Object.entries(config.schemas?.events ?? {}).map(([key, schema]) => [key, compileSchema(schema, `event.${key}`)])),
|
|
110
|
+
emitted: Object.fromEntries(Object.entries(config.schemas?.emitted ?? {}).map(([key, schema]) => [key, compileSchema(schema, `emitted.${key}`)])),
|
|
111
|
+
input: compileSchema(config.schemas?.input ?? {}, "input"),
|
|
112
|
+
output: compileSchema(config.schemas?.output ?? {}, "output"),
|
|
113
|
+
meta: compileSchema(config.schemas?.meta ?? {}, "meta")
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function createRequestsFromWorkflowConfig(config, compileSchema) {
|
|
117
|
+
return Object.fromEntries(Object.entries(config.requests ?? {}).map(([key, request]) => [key, {
|
|
118
|
+
mode: request.mode,
|
|
119
|
+
description: request.description,
|
|
120
|
+
schemas: {
|
|
121
|
+
input: compileSchema(request.input, `${key}.input`),
|
|
122
|
+
output: compileSchema(request.output, `${key}.output`)
|
|
123
|
+
},
|
|
124
|
+
model: ({ input }) => String(evaluateWorkflowConfigValue(request.model, { input }) ?? ""),
|
|
125
|
+
system: request.system === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.system, { input }),
|
|
126
|
+
prompt: request.prompt === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.prompt, { input }),
|
|
127
|
+
messages: request.messages === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.messages, { input }),
|
|
128
|
+
tools: request.tools,
|
|
129
|
+
toolChoice: request.toolChoice,
|
|
130
|
+
reasoning: request.reasoning,
|
|
131
|
+
temperature: request.temperature === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.temperature, { input }),
|
|
132
|
+
maxOutputTokens: request.maxOutputTokens === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.maxOutputTokens, { input }),
|
|
133
|
+
topP: request.topP === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.topP, { input }),
|
|
134
|
+
topK: request.topK === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.topK, { input }),
|
|
135
|
+
seed: request.seed === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.seed, { input }),
|
|
136
|
+
stopSequences: request.stopSequences === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.stopSequences, { input }),
|
|
137
|
+
metadata: request.metadata === void 0 ? void 0 : ({ input }) => evaluateWorkflowConfigValue(request.metadata, { input })
|
|
138
|
+
}]));
|
|
139
|
+
}
|
|
140
|
+
function createActorPlaceholdersFromWorkflowConfig(config) {
|
|
141
|
+
return Object.fromEntries(Object.keys(config.actors ?? {}).map((key) => [key, missingActor(key)]));
|
|
142
|
+
}
|
|
143
|
+
function createAssignAction(assignConfig) {
|
|
144
|
+
return ({ context, event }) => ({ context: Object.fromEntries(Object.entries(assignConfig).map(([key, value]) => [key, evaluateWorkflowConfigValue(value, {
|
|
145
|
+
context,
|
|
146
|
+
event
|
|
147
|
+
})])) });
|
|
148
|
+
}
|
|
149
|
+
function lowerWorkflowActions(actionConfig) {
|
|
150
|
+
if (!actionConfig) return;
|
|
151
|
+
const lowered = (Array.isArray(actionConfig) ? actionConfig : [actionConfig]).map((action) => {
|
|
152
|
+
if (action.assign !== void 0) return createAssignAction(action.assign);
|
|
153
|
+
if (action.emit !== void 0) return ({ context, event }, enq) => {
|
|
154
|
+
enq.emit(evaluateWorkflowConfigValue(action.emit, {
|
|
155
|
+
context,
|
|
156
|
+
event
|
|
157
|
+
}));
|
|
158
|
+
};
|
|
159
|
+
if (!action.type) throw new Error("setupAgent.fromConfig: action must declare 'type', 'assign', or 'emit'.");
|
|
160
|
+
return {
|
|
161
|
+
type: action.type,
|
|
162
|
+
params: ({ context, event }) => evaluateWorkflowConfigValue(action.params, {
|
|
163
|
+
context,
|
|
164
|
+
event
|
|
165
|
+
})
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
return Array.isArray(actionConfig) ? lowered : lowered[0];
|
|
169
|
+
}
|
|
170
|
+
function workflowTransitionMatches(transitionConfig, scope) {
|
|
171
|
+
if (transitionConfig.guard === void 0) return true;
|
|
172
|
+
if (typeof transitionConfig.guard === "string") return Boolean(evaluateWorkflowConfigValue(transitionConfig.guard, scope));
|
|
173
|
+
return typeof transitionConfig.guard === "function" ? transitionConfig.guard(scope) : false;
|
|
174
|
+
}
|
|
175
|
+
function lowerWorkflowTransitionResult(transitionConfig, scope) {
|
|
176
|
+
return {
|
|
177
|
+
...transitionConfig.target !== void 0 ? { target: transitionConfig.target } : {},
|
|
178
|
+
...transitionConfig.assign ? { context: Object.fromEntries(Object.entries(transitionConfig.assign).map(([key, value]) => [key, evaluateWorkflowConfigValue(value, scope)])) } : {},
|
|
179
|
+
...transitionConfig.description !== void 0 ? { description: transitionConfig.description } : {},
|
|
180
|
+
...transitionConfig.reenter !== void 0 ? { reenter: transitionConfig.reenter } : {},
|
|
181
|
+
...transitionConfig.meta !== void 0 ? { meta: transitionConfig.meta } : {}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function lowerWorkflowTransition(transitionConfig) {
|
|
185
|
+
return ({ context, event }) => {
|
|
186
|
+
const scope = {
|
|
187
|
+
context,
|
|
188
|
+
event
|
|
189
|
+
};
|
|
190
|
+
if (!workflowTransitionMatches(transitionConfig, scope)) return;
|
|
191
|
+
return lowerWorkflowTransitionResult(transitionConfig, scope);
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
function lowerWorkflowTransitionOrArray(transitionConfig) {
|
|
195
|
+
if (!transitionConfig) return;
|
|
196
|
+
return Array.isArray(transitionConfig) ? ({ context, event }) => {
|
|
197
|
+
const scope = {
|
|
198
|
+
context,
|
|
199
|
+
event
|
|
200
|
+
};
|
|
201
|
+
const transition = transitionConfig.find((candidate) => workflowTransitionMatches(candidate, scope));
|
|
202
|
+
if (!transition) return;
|
|
203
|
+
return lowerWorkflowTransitionResult(transition, scope);
|
|
204
|
+
} : lowerWorkflowTransition(transitionConfig);
|
|
205
|
+
}
|
|
206
|
+
function lowerWorkflowInvoke(invokeConfig) {
|
|
207
|
+
return {
|
|
208
|
+
...invokeConfig.id !== void 0 ? { id: invokeConfig.id } : {},
|
|
209
|
+
src: invokeConfig.src,
|
|
210
|
+
...invokeConfig.input !== void 0 ? { input: ({ context, event }) => evaluateWorkflowConfigValue(invokeConfig.input, {
|
|
211
|
+
context,
|
|
212
|
+
event
|
|
213
|
+
}) } : {},
|
|
214
|
+
...invokeConfig.onDone !== void 0 ? { onDone: lowerWorkflowTransitionOrArray(invokeConfig.onDone) } : {},
|
|
215
|
+
...invokeConfig.onError !== void 0 ? { onError: lowerWorkflowTransitionOrArray(invokeConfig.onError) } : {},
|
|
216
|
+
...invokeConfig.meta !== void 0 ? { meta: invokeConfig.meta } : {}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function lowerWorkflowState(stateConfig) {
|
|
220
|
+
return {
|
|
221
|
+
...stateConfig.description !== void 0 ? { description: stateConfig.description } : {},
|
|
222
|
+
...stateConfig.type !== void 0 ? { type: stateConfig.type } : {},
|
|
223
|
+
...stateConfig.initial !== void 0 ? { initial: stateConfig.initial } : {},
|
|
224
|
+
...stateConfig.states !== void 0 ? { states: Object.fromEntries(Object.entries(stateConfig.states).map(([key, child]) => [key, lowerWorkflowState(child)])) } : {},
|
|
225
|
+
...stateConfig.choice !== void 0 ? { choice: lowerWorkflowTransitionOrArray(stateConfig.choice) } : {},
|
|
226
|
+
...stateConfig.invoke !== void 0 ? { invoke: Array.isArray(stateConfig.invoke) ? stateConfig.invoke.map(lowerWorkflowInvoke) : lowerWorkflowInvoke(stateConfig.invoke) } : {},
|
|
227
|
+
...stateConfig.on !== void 0 ? { on: Object.fromEntries(Object.entries(stateConfig.on).map(([eventType, transitionConfig]) => [eventType, lowerWorkflowTransitionOrArray(transitionConfig)])) } : {},
|
|
228
|
+
...stateConfig.always !== void 0 ? { always: lowerWorkflowTransitionOrArray(stateConfig.always) } : {},
|
|
229
|
+
...stateConfig.onDone !== void 0 ? { onDone: lowerWorkflowTransitionOrArray(stateConfig.onDone) } : {},
|
|
230
|
+
...stateConfig.after !== void 0 ? { after: Object.fromEntries(Object.entries(stateConfig.after).map(([delay, transitionConfig]) => [delay, lowerWorkflowTransitionOrArray(transitionConfig)])) } : {},
|
|
231
|
+
...stateConfig.entry !== void 0 ? { entry: lowerWorkflowActions(stateConfig.entry) } : {},
|
|
232
|
+
...stateConfig.exit !== void 0 ? { exit: lowerWorkflowActions(stateConfig.exit) } : {},
|
|
233
|
+
...stateConfig.tags !== void 0 ? { tags: stateConfig.tags } : {},
|
|
234
|
+
...stateConfig.output !== void 0 ? { output: ({ context, event }) => evaluateWorkflowConfigValue(stateConfig.output, {
|
|
235
|
+
context,
|
|
236
|
+
event
|
|
237
|
+
}) } : {},
|
|
238
|
+
...stateConfig.meta !== void 0 ? { meta: stateConfig.meta } : {}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function setupAgentFromConfig(config, options) {
|
|
242
|
+
if (!options || typeof options.compileSchema !== "function") throw new Error("setupAgent.fromConfig(...) requires a 'compileSchema' option: { compileSchema: (jsonSchema, name) => StandardSchemaV1 }. Bring your own JSON Schema engine (Ajv, @cfworker/json-schema, a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no JSON Schema engine.");
|
|
243
|
+
const { compileSchema } = options;
|
|
244
|
+
const schemas = createSchemasFromWorkflowConfig(config, compileSchema);
|
|
245
|
+
const requestActors = createRequestActors(createRequestsFromWorkflowConfig(config, compileSchema));
|
|
246
|
+
return setupAgent({
|
|
247
|
+
schemas,
|
|
248
|
+
actorSources: {
|
|
249
|
+
...createActorPlaceholdersFromWorkflowConfig(config),
|
|
250
|
+
...requestActors
|
|
251
|
+
}
|
|
252
|
+
}).createMachine({
|
|
253
|
+
...config.id !== void 0 ? { id: config.id } : {},
|
|
254
|
+
...config.description !== void 0 ? { description: config.description } : {},
|
|
255
|
+
...config.context !== void 0 ? { context: ({ input }) => validateSchemaSync(schemas.context, evaluateWorkflowConfigValue(config.context, { input })) } : {},
|
|
256
|
+
initial: config.initial,
|
|
257
|
+
states: Object.fromEntries(Object.entries(config.states).map(([key, state]) => [key, lowerWorkflowState(state)])),
|
|
258
|
+
...config.meta !== void 0 ? { meta: config.meta } : {}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/setup-agent.ts
|
|
263
|
+
/**
|
|
264
|
+
* Builds a machine's {@link AgentSchemaPack} from a partial schema
|
|
265
|
+
* declaration — only `context` is required; `events`/`input`/`output`/`meta`
|
|
266
|
+
* default to empty/unknown schemas when omitted. Pass the result as
|
|
267
|
+
* `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
|
|
268
|
+
* directly into `setupAgent({ context, events, ... })` — both forms are
|
|
269
|
+
* accepted).
|
|
270
|
+
*/
|
|
271
|
+
function createAgentSchemas(schemas) {
|
|
272
|
+
return {
|
|
273
|
+
context: schemas.context,
|
|
274
|
+
events: schemas.events ?? {},
|
|
275
|
+
input: schemas.input,
|
|
276
|
+
output: schemas.output,
|
|
277
|
+
meta: schemas.meta,
|
|
278
|
+
emitted: schemas.emitted
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Schema-first `setup(...)` for agent machines — the standard entry point
|
|
283
|
+
* for authoring a machine (the blueprint) that this library then runs (via
|
|
284
|
+
* {@link runAgent} or the step helpers) against host-supplied model/decision
|
|
285
|
+
* executors. Context, events, machine input, machine output, and
|
|
286
|
+
* state/transition meta are all standard schemas — no `{} as Type` casts —
|
|
287
|
+
* and are retained on `result.schemas` for runtime validation. Also
|
|
288
|
+
* registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
|
|
289
|
+
* `agent.decide` builtin actors and lowers `requests`/`actorSources` into the
|
|
290
|
+
* machine's actor sources. The result is the xstate `setup(...)` object with
|
|
291
|
+
* a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
|
|
292
|
+
* `requests`/`appendMessages` attached. Also has a
|
|
293
|
+
* `setupAgent.fromConfig(...)` namespace member for building a machine from
|
|
294
|
+
* a serializable {@link AgentWorkflowConfig} instead of this TS API.
|
|
295
|
+
*
|
|
296
|
+
* @example
|
|
297
|
+
* ```ts
|
|
298
|
+
* const schemas = createAgentSchemas({
|
|
299
|
+
* context: z.object({ topic: z.string(), joke: z.string().nullable() }),
|
|
300
|
+
* input: z.object({ topic: z.string() }),
|
|
301
|
+
* output: z.object({ joke: z.string() }),
|
|
302
|
+
* });
|
|
303
|
+
*
|
|
304
|
+
* const agent = setupAgent({
|
|
305
|
+
* schemas,
|
|
306
|
+
* actorSources: { tellJoke },
|
|
307
|
+
* });
|
|
308
|
+
*
|
|
309
|
+
* const jokeMachine = agent.createMachine({
|
|
310
|
+
* context: ({ input }) => ({ topic: input.topic, joke: null }),
|
|
311
|
+
* initial: 'telling',
|
|
312
|
+
* states: {
|
|
313
|
+
* telling: {
|
|
314
|
+
* invoke: {
|
|
315
|
+
* id: 'joke',
|
|
316
|
+
* src: 'tellJoke',
|
|
317
|
+
* input: ({ context }) => ({ topic: context.topic }),
|
|
318
|
+
* onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
|
|
319
|
+
* },
|
|
320
|
+
* },
|
|
321
|
+
* done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
|
|
322
|
+
* },
|
|
323
|
+
* });
|
|
324
|
+
* ```
|
|
325
|
+
*/
|
|
326
|
+
function setupAgent(config) {
|
|
327
|
+
return createSetupAgent(config);
|
|
328
|
+
}
|
|
329
|
+
function collectFinalStateOutputs(states, outputs = []) {
|
|
330
|
+
for (const state of Object.values(states ?? {})) {
|
|
331
|
+
if (state?.type === "final" && state.output !== void 0) outputs.push(state.output);
|
|
332
|
+
collectFinalStateOutputs(state?.states, outputs);
|
|
333
|
+
}
|
|
334
|
+
return outputs;
|
|
335
|
+
}
|
|
336
|
+
function withRootOutputFromSingleFinal(config) {
|
|
337
|
+
if (!config || typeof config !== "object" || "output" in config || !("states" in config)) return config;
|
|
338
|
+
const outputs = collectFinalStateOutputs(config.states);
|
|
339
|
+
return outputs.length === 1 ? {
|
|
340
|
+
...config,
|
|
341
|
+
output: outputs[0]
|
|
342
|
+
} : config;
|
|
343
|
+
}
|
|
344
|
+
(function(_setupAgent) {
|
|
345
|
+
function fromConfig(config, options) {
|
|
346
|
+
return setupAgentFromConfig(config, options);
|
|
347
|
+
}
|
|
348
|
+
_setupAgent.fromConfig = fromConfig;
|
|
349
|
+
})(setupAgent || (setupAgent = {}));
|
|
350
|
+
/** Builds one TextLogic actor per `setupAgent({ requests })` entry. @internal */
|
|
351
|
+
function createRequestActors(requests) {
|
|
352
|
+
return Object.fromEntries(Object.entries(requests).map(([key, request]) => {
|
|
353
|
+
return [key, createTextLogic({
|
|
354
|
+
...request,
|
|
355
|
+
name: key,
|
|
356
|
+
mode: request.mode ?? "generate"
|
|
357
|
+
})];
|
|
358
|
+
}));
|
|
359
|
+
}
|
|
360
|
+
function normalizeAgentSchemas(config) {
|
|
361
|
+
return "schemas" in config ? config.schemas : createAgentSchemas(config);
|
|
362
|
+
}
|
|
363
|
+
function normalizeAgentRequestInput(requests) {
|
|
364
|
+
return requests ?? {};
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Runtime guard: a key appearing in both `actorSources`/`requests` is almost
|
|
368
|
+
* certainly a mistake (whichever spread applies last would silently win) —
|
|
369
|
+
* fail fast with a clear message rather than let one implementation shadow
|
|
370
|
+
* another.
|
|
371
|
+
*/
|
|
372
|
+
function assertNoActorKeyCollisions(actorSources, requests) {
|
|
373
|
+
const seenIn = /* @__PURE__ */ new Map();
|
|
374
|
+
const groups = [["actorSources", actorSources], ["requests", requests]];
|
|
375
|
+
for (const [groupName, group] of groups) for (const key of Object.keys(group ?? {})) {
|
|
376
|
+
const existingGroup = seenIn.get(key);
|
|
377
|
+
if (existingGroup) throw new Error(`setupAgent: key '${key}' is defined in both '${existingGroup}' and '${groupName}'. Each actor source key must be unique across 'actorSources' and 'requests'.`);
|
|
378
|
+
seenIn.set(key, groupName);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const RESERVED_AGENT_ACTOR_KEYS = [
|
|
382
|
+
...Object.keys(builtinTextActors),
|
|
383
|
+
USER_INPUT_ACTOR,
|
|
384
|
+
DECIDE_ACTOR,
|
|
385
|
+
PLAN_ACTOR
|
|
386
|
+
];
|
|
387
|
+
/**
|
|
388
|
+
* Rejects a user-supplied `actorSources`/`requests` key in the reserved
|
|
389
|
+
* `agent.*` builtin namespace. Without this, the builtins-first spread in
|
|
390
|
+
* {@link createAgentActorSources} lets such a key overwrite the builtin
|
|
391
|
+
* (`agent.decide`, `agent.plan`, …) silently. Deliberate override of a builtin
|
|
392
|
+
* is still possible after the machine is created, via
|
|
393
|
+
* `machine.provide({ actorSources: { 'agent.decide': ... } })`.
|
|
394
|
+
*/
|
|
395
|
+
function assertNoReservedAgentKeys(actorSources, requests) {
|
|
396
|
+
const groups = [["actorSources", actorSources], ["requests", requests]];
|
|
397
|
+
for (const [groupName, group] of groups) for (const key of Object.keys(group ?? {})) if (RESERVED_AGENT_ACTOR_KEYS.includes(key)) throw new Error(`setupAgent: '${groupName}' key '${key}' is a reserved builtin agent actor and cannot be redefined here (it would silently clobber the builtin). Reserved keys: ${RESERVED_AGENT_ACTOR_KEYS.join(", ")}. To deliberately override a builtin, do it on the created machine instead: machine.provide({ actorSources: { '${key}': ... } }).`);
|
|
398
|
+
}
|
|
399
|
+
function createAgentActorSources(actorSources, requestActors) {
|
|
400
|
+
assertNoActorKeyCollisions(actorSources, requestActors);
|
|
401
|
+
assertNoReservedAgentKeys(actorSources, requestActors);
|
|
402
|
+
return {
|
|
403
|
+
...builtinTextActors,
|
|
404
|
+
[USER_INPUT_ACTOR]: userInputActor,
|
|
405
|
+
[DECIDE_ACTOR]: createDecideActor(),
|
|
406
|
+
[PLAN_ACTOR]: createPlanActor(),
|
|
407
|
+
...actorSources,
|
|
408
|
+
...requestActors
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
function createAgentSetupConfig(schemas, actorSources, config) {
|
|
412
|
+
return {
|
|
413
|
+
schemas: {
|
|
414
|
+
context: schemas.context,
|
|
415
|
+
events: schemas.events,
|
|
416
|
+
input: schemas.input,
|
|
417
|
+
output: schemas.output,
|
|
418
|
+
meta: schemas.meta,
|
|
419
|
+
...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
|
|
420
|
+
},
|
|
421
|
+
...config.states ? { states: config.states } : {},
|
|
422
|
+
actorSources,
|
|
423
|
+
actions: config.actions,
|
|
424
|
+
guards: config.guards,
|
|
425
|
+
delays: config.delays
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function createSetupAgent(config) {
|
|
429
|
+
const schemas = normalizeAgentSchemas(config);
|
|
430
|
+
const requestActors = createRequestActors(normalizeAgentRequestInput(config.requests));
|
|
431
|
+
const actorSources = createAgentActorSources(config.actorSources, requestActors);
|
|
432
|
+
const base = setup(createAgentSetupConfig(schemas, actorSources, config));
|
|
433
|
+
const createBaseMachine = base.createMachine.bind(base);
|
|
434
|
+
const machineOptions = {
|
|
435
|
+
schemas,
|
|
436
|
+
actorSources
|
|
437
|
+
};
|
|
438
|
+
const models = config.models ?? {};
|
|
439
|
+
return Object.assign(base, {
|
|
440
|
+
createMachine(machineConfig) {
|
|
441
|
+
const machine = createBaseMachine(withRootOutputFromSingleFinal(machineConfig));
|
|
442
|
+
agentExecutionOptions.set(machine, machineOptions);
|
|
443
|
+
if (config.isSuspended) {
|
|
444
|
+
const rootConfig = machine.config;
|
|
445
|
+
if (rootConfig) machineSuspensionPredicates.set(rootConfig, config.isSuspended);
|
|
446
|
+
}
|
|
447
|
+
return machine;
|
|
448
|
+
},
|
|
449
|
+
schemas,
|
|
450
|
+
models,
|
|
451
|
+
requests: requestActors,
|
|
452
|
+
appendMessages(resolve) {
|
|
453
|
+
return appendMessages(resolve);
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region src/steps.ts
|
|
459
|
+
/**
|
|
460
|
+
* The step path: durable, per-model-call-checkpoint hosting of an agent
|
|
461
|
+
* machine. Public vocabulary — `initialAgentStep`, `transitionAgentStep`,
|
|
462
|
+
* `resolveAgentStep`, `getAgentRequests`, `executeAgentRequest`,
|
|
463
|
+
* `resolveAgentRequests`.
|
|
464
|
+
* @module
|
|
465
|
+
*/
|
|
466
|
+
/**
|
|
467
|
+
* Scans a set of executable actions (as returned by xstate's `transition`/
|
|
468
|
+
* `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
|
|
469
|
+
* lowers each into an {@link AgentStepRequest}. The hand-passed-schemas
|
|
470
|
+
* implementation detail behind the public {@link getAgentRequests} — it needs
|
|
471
|
+
* `schemas`/`actorSources` passed explicitly, whereas `getAgentRequests`
|
|
472
|
+
* pre-fills them from the machine's registered `setupAgent` options.
|
|
473
|
+
* `options.snapshot` is required to resolve a decision's candidate events
|
|
474
|
+
* (intersecting declared `allowedEvents` with what's currently legal) — omit
|
|
475
|
+
* it and decision requests report an empty `events` list.
|
|
476
|
+
*
|
|
477
|
+
* @internal
|
|
478
|
+
*/
|
|
479
|
+
function getAgentRequestsWith(actions, options = {}) {
|
|
480
|
+
return [...actions.flatMap((action) => {
|
|
481
|
+
if (action.type !== "xstate.spawnChild" && action.type !== "@xstate.start") return [];
|
|
482
|
+
const params = action.type === "@xstate.start" ? action : action.params;
|
|
483
|
+
if (!params || typeof params.src !== "string") return [];
|
|
484
|
+
if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
|
|
485
|
+
const registeredLogic = isTextLogic(action.logic) || isDecisionLogic(action.logic) ? action.logic : options.actorSources?.[params.src];
|
|
486
|
+
if (isDecisionLogic(registeredLogic)) {
|
|
487
|
+
const decisionRequest = registeredLogic.request(params.input);
|
|
488
|
+
const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
|
|
489
|
+
const events = options.snapshot ? getAcceptedEvents(options.snapshot, {
|
|
490
|
+
events: options.events,
|
|
491
|
+
schemas: options.schemas,
|
|
492
|
+
eventTypes: allowedEventTypes,
|
|
493
|
+
eventToolName: options.eventToolName
|
|
494
|
+
}) : [];
|
|
495
|
+
return [{
|
|
496
|
+
...decisionRequest,
|
|
497
|
+
id: params.id,
|
|
498
|
+
events
|
|
499
|
+
}];
|
|
500
|
+
}
|
|
501
|
+
const textLogic = isTextLogic(registeredLogic) ? registeredLogic : void 0;
|
|
502
|
+
const input = textLogic ? textLogic.request(params.input) : void 0;
|
|
503
|
+
if (!input) return [];
|
|
504
|
+
return [{
|
|
505
|
+
kind: "text",
|
|
506
|
+
id: params.id,
|
|
507
|
+
src: params.src,
|
|
508
|
+
...textLogic ? { mode: textLogic.mode } : {},
|
|
509
|
+
input,
|
|
510
|
+
tools: input.tools ?? {},
|
|
511
|
+
events: []
|
|
512
|
+
}];
|
|
513
|
+
}), ...getActivePlanRequests(options)];
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Scans the live snapshot's children for active `agent.plan` (plan-logic)
|
|
517
|
+
* invokes and lowers each into an {@link AgentPlanRequest} — the re-surfacing
|
|
518
|
+
* half of plan discovery. Reads the applied-event trail and remaining budget
|
|
519
|
+
* from the child's own ledger `context` ({@link PlanLedgerContext}), recomputes
|
|
520
|
+
* the currently-legal candidates (∩ declared `allowedEvents`) plus the reserved
|
|
521
|
+
* `agent.plan.done` move, and takes `stepsRemaining` from the ledger (falling
|
|
522
|
+
* back to `maxSteps - applied.length` for a snapshot with no context yet).
|
|
523
|
+
* Returns `[]` when no snapshot is available (candidates need a live snapshot).
|
|
524
|
+
*
|
|
525
|
+
* @internal
|
|
526
|
+
*/
|
|
527
|
+
function getActivePlanRequests(options) {
|
|
528
|
+
const snapshot = options.snapshot;
|
|
529
|
+
if (!snapshot) return [];
|
|
530
|
+
const children = snapshot.children;
|
|
531
|
+
if (!children) return [];
|
|
532
|
+
const requests = [];
|
|
533
|
+
for (const [id, child] of Object.entries(children)) {
|
|
534
|
+
const ref = child;
|
|
535
|
+
if (typeof ref?.getSnapshot !== "function") continue;
|
|
536
|
+
const src = typeof ref.src === "string" ? ref.src : void 0;
|
|
537
|
+
const logic = (src ? options.actorSources?.[src] : void 0) ?? ref.logic;
|
|
538
|
+
if (!isPlanLogic(logic)) continue;
|
|
539
|
+
const childSnapshot = ref.getSnapshot();
|
|
540
|
+
if (childSnapshot?.status !== "active") continue;
|
|
541
|
+
const input = childSnapshot.input ?? {};
|
|
542
|
+
const maxSteps = input.maxSteps ?? 8;
|
|
543
|
+
const ledger = childSnapshot.context ?? {};
|
|
544
|
+
const applied = ledger.applied ?? [];
|
|
545
|
+
const stepsRemaining = ledger.stepsRemaining ?? maxSteps - applied.length;
|
|
546
|
+
const machineEvents = getAcceptedEvents(snapshot, {
|
|
547
|
+
events: options.events,
|
|
548
|
+
schemas: options.schemas,
|
|
549
|
+
eventTypes: logic.allowedEventTypes(input) ?? void 0,
|
|
550
|
+
eventToolName: options.eventToolName
|
|
551
|
+
});
|
|
552
|
+
const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, {
|
|
553
|
+
type: PLAN_DONE_EVENT_TYPE,
|
|
554
|
+
toolName: sanitizeEventToolName(PLAN_DONE_EVENT_TYPE)
|
|
555
|
+
}];
|
|
556
|
+
requests.push({
|
|
557
|
+
kind: "plan",
|
|
558
|
+
id,
|
|
559
|
+
src: src ?? "",
|
|
560
|
+
input,
|
|
561
|
+
events,
|
|
562
|
+
applied,
|
|
563
|
+
stepsRemaining: Math.max(0, stepsRemaining)
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
return requests;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Builds the synthetic `xstate.done.actor.<id>` event xstate's `transition()`
|
|
570
|
+
* expects to resolve a spawned invoke — the event {@link resolveAgentStep}
|
|
571
|
+
* applies internally.
|
|
572
|
+
*
|
|
573
|
+
* @internal
|
|
574
|
+
*/
|
|
575
|
+
function doneEvent(request, output) {
|
|
576
|
+
return {
|
|
577
|
+
type: `xstate.done.actor.${typeof request === "string" ? request : request.id}`,
|
|
578
|
+
output
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Applies a request's `output` as a done event via `transition(...)`,
|
|
583
|
+
* returning the raw `[snapshot, actions]` tuple. Lower-level than
|
|
584
|
+
* {@link resolveAgentStep} — that helper wraps this and also runs
|
|
585
|
+
* {@link getAgentRequests} to produce the next {@link AgentStep}.
|
|
586
|
+
*
|
|
587
|
+
* @internal
|
|
588
|
+
*/
|
|
589
|
+
function transitionResult(logic, snapshot, request, output) {
|
|
590
|
+
const event = doneEvent(request, output);
|
|
591
|
+
const result = transition(logic, snapshot, event);
|
|
592
|
+
applyFinalStateOutput(logic, result[0], event);
|
|
593
|
+
return result;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Starts a machine and returns its first {@link AgentStep} — the step-path
|
|
597
|
+
* equivalent of `initialTransition` plus request discovery. Begins the
|
|
598
|
+
* durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
|
|
599
|
+
* (via {@link executeAgentRequest} for `kind: 'text'`, or
|
|
600
|
+
* {@link resolveDecision} for `kind: 'decision'`), then advance with
|
|
601
|
+
* {@link resolveAgentStep} or {@link transitionAgentStep}.
|
|
602
|
+
*/
|
|
603
|
+
function initialAgentStep(machine, input, options) {
|
|
604
|
+
const [snapshot, actions] = initialTransition(machine, input);
|
|
605
|
+
return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Applies an externally-sent event (e.g. a decision's chosen event, or a
|
|
609
|
+
* human's reply) and returns the next {@link AgentStep}. Accepts **either**
|
|
610
|
+
* a raw snapshot **or** a prior `AgentStep` as the second argument —
|
|
611
|
+
* `.snapshot` is unwrapped automatically, so callers can thread the whole
|
|
612
|
+
* step object through without manually plucking the snapshot out.
|
|
613
|
+
*/
|
|
614
|
+
function transitionAgentStep(machine, snapshotOrStep, event, options) {
|
|
615
|
+
const [nextSnapshot, actions] = transition(machine, isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep, event);
|
|
616
|
+
return createAgentStep(machine, nextSnapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Applies a resolved text request's output (a `kind: 'text'`
|
|
620
|
+
* {@link AgentRequest} — not a decision) as a done event and returns the
|
|
621
|
+
* next {@link AgentStep}. For decisions, resolve with `resolveDecision`
|
|
622
|
+
* (which returns a {@link ChosenEvent}) and apply it with
|
|
623
|
+
* {@link transitionAgentStep} instead — a decision has no output value of
|
|
624
|
+
* its own to feed here.
|
|
625
|
+
*/
|
|
626
|
+
function resolveAgentStep(machine, step, request, output, options) {
|
|
627
|
+
const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
|
|
628
|
+
return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Snapshot in, requests out: scans executable actions for spawned agent
|
|
632
|
+
* invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
|
|
633
|
+
* the machine's registered `setupAgent` schemas/actorSources (so callers
|
|
634
|
+
* don't pass them by hand each call) — merged with any `options` passed here,
|
|
635
|
+
* which take precedence. The step path's public discovery primitive;
|
|
636
|
+
* `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
|
|
637
|
+
* internally to populate `AgentStep.requests`.
|
|
638
|
+
*/
|
|
639
|
+
function getAgentRequests(machine, actions, snapshot, options = {}) {
|
|
640
|
+
return getAgentRequestsWith(actions, {
|
|
641
|
+
...getRegisteredAgentExecutionOptions(machine, options),
|
|
642
|
+
...options,
|
|
643
|
+
snapshot
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
async function executeAgentRequest(request, executors, options) {
|
|
647
|
+
if (request.kind === "decision") throw new Error("executeAgentRequest(...) is text-only. Resolve a 'decision' request with resolveDecision(request, executors.decide, ...) instead.");
|
|
648
|
+
assertTextExecutor(request, executors);
|
|
649
|
+
const { output, raw } = await executeAgentTextRequest(request.mode ?? "generate", request.id, request.input, executors, request.tools);
|
|
650
|
+
const normalizedOutput = request.input.outputSchema ? validateSchemaSync(request.input.outputSchema, output) : output;
|
|
651
|
+
return options?.verbose ? {
|
|
652
|
+
output: normalizedOutput,
|
|
653
|
+
raw
|
|
654
|
+
} : normalizedOutput;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Resolves the current step's pending requests and returns the next
|
|
658
|
+
* {@link AgentStep} — one iteration of the durable step loop, collapsing the
|
|
659
|
+
* manual `request.kind` dispatch a host would otherwise write by hand.
|
|
660
|
+
*
|
|
661
|
+
* For each pending request, in order: a `kind: 'text'` request is run with
|
|
662
|
+
* {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
|
|
663
|
+
* `kind: 'decision'` request is resolved with `resolveDecision` (wiring
|
|
664
|
+
* `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
|
|
665
|
+
* applied with {@link transitionAgentStep}. The **current** step is re-read
|
|
666
|
+
* after each application — the machine may advance and its `requests` change —
|
|
667
|
+
* so this always resolves against the live step, never a stale list.
|
|
668
|
+
*
|
|
669
|
+
* A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
|
|
670
|
+
* step per call. It resolves a single decision from `request.events` (wiring
|
|
671
|
+
* `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
|
|
672
|
+
* move and `stopOn` events), then either applies the chosen machine event and
|
|
673
|
+
* lets the next step re-surface the plan, or completes the plan (feeding its
|
|
674
|
+
* `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
|
|
675
|
+
* exhausted budget / no legal events. The plan's applied trail is carried in
|
|
676
|
+
* the invoke child's snapshot, so persisting the step between calls resumes the
|
|
677
|
+
* plan identically.
|
|
678
|
+
*
|
|
679
|
+
* Missing the executor a request needs throws a clear error
|
|
680
|
+
* (`generateText`/`streamText` for text, `decide` for decisions and plans).
|
|
681
|
+
*
|
|
682
|
+
* A complete durable host is two lines:
|
|
683
|
+
*
|
|
684
|
+
* ```ts
|
|
685
|
+
* let step = initialAgentStep(machine, input);
|
|
686
|
+
* while (!step.done) step = await resolveAgentRequests(machine, step, executors);
|
|
687
|
+
* ```
|
|
688
|
+
*
|
|
689
|
+
* All pending **text** requests of a step are resolved in parallel
|
|
690
|
+
* (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
|
|
691
|
+
* their model calls run concurrently — then their outputs apply in
|
|
692
|
+
* **request-array order** (deterministic for durable replay regardless of which
|
|
693
|
+
* call finishes first). Decisions and plans stay **one at a time**: applying
|
|
694
|
+
* either changes the set of legal candidates for what follows, so they cannot be
|
|
695
|
+
* resolved against a stale snapshot. A host that instead wants strictly
|
|
696
|
+
* sequential text resolution loops the manual per-request helpers
|
|
697
|
+
* ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
|
|
698
|
+
*/
|
|
699
|
+
async function resolveAgentRequests(machine, step, executors, options) {
|
|
700
|
+
const [request] = step.requests;
|
|
701
|
+
if (!request) return step;
|
|
702
|
+
if (request.kind === "decision") {
|
|
703
|
+
if (!executors.decide) throw new Error(`this step's decision request '${request.id}' needs a 'decide' executor but none was provided.`);
|
|
704
|
+
return transitionAgentStep(machine, step, await resolveDecision(request, executors.decide, {
|
|
705
|
+
canTake: (event) => step.snapshot.can(event),
|
|
706
|
+
maxRetries: options?.maxRetries
|
|
707
|
+
}), options);
|
|
708
|
+
}
|
|
709
|
+
if (request.kind === "plan") return resolvePlanRequest(machine, step, request, executors, options);
|
|
710
|
+
const textRequests = step.requests.filter((candidate) => candidate.kind === "text");
|
|
711
|
+
for (const textRequest of textRequests) assertTextExecutor(textRequest, executors);
|
|
712
|
+
const outputs = await Promise.all(textRequests.map((textRequest) => executeAgentRequest(textRequest, executors)));
|
|
713
|
+
let next = step;
|
|
714
|
+
for (let index = 0; index < textRequests.length; index++) next = resolveAgentStep(machine, next, textRequests[index], outputs[index], options);
|
|
715
|
+
return next;
|
|
716
|
+
}
|
|
717
|
+
function assertTextExecutor(request, executors) {
|
|
718
|
+
const mode = request.mode ?? "generate";
|
|
719
|
+
const kind = mode === "stream" ? "streamText" : "generateText";
|
|
720
|
+
if (!(mode === "stream" ? executors.streamText : executors.generateText)) throw new Error(`this step's text request '${request.src}' needs a '${kind}' executor but none was provided.`);
|
|
721
|
+
}
|
|
722
|
+
async function resolvePlanRequest(machine, step, request, executors, options) {
|
|
723
|
+
if (!executors.decide) throw new Error(`this step's plan request '${request.src}' needs a 'decide' executor but none was provided.`);
|
|
724
|
+
const stopOn = new Set(request.input.stopOn ?? []);
|
|
725
|
+
if (request.stepsRemaining <= 0) return completePlan(machine, step, request.id, request.applied, "max-steps", options);
|
|
726
|
+
if (request.events.filter((event) => event.type !== "agent.plan.done").length === 0) return completePlan(machine, step, request.id, request.applied, "no-legal-events", options);
|
|
727
|
+
const chosen = await resolveDecision(planStepDecisionRequest(request), executors.decide, {
|
|
728
|
+
maxRetries: options?.maxRetries,
|
|
729
|
+
canTake: (event) => {
|
|
730
|
+
if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
|
|
731
|
+
return step.snapshot.can(event);
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
if (chosen.type === "agent.plan.done") return completePlan(machine, step, request.id, request.applied, "done", options);
|
|
735
|
+
const applied = [...request.applied, chosen];
|
|
736
|
+
advancePlanChildLedger(step.snapshot, request.id, {
|
|
737
|
+
type: "plan.applied",
|
|
738
|
+
event: chosen
|
|
739
|
+
});
|
|
740
|
+
const next = transitionAgentStep(machine, step, chosen, options);
|
|
741
|
+
if (stopOn.has(chosen.type)) {
|
|
742
|
+
if (isPlanActive(next.snapshot, request.id)) return completePlan(machine, next, request.id, applied, "stop-event", options);
|
|
743
|
+
}
|
|
744
|
+
return next;
|
|
745
|
+
}
|
|
746
|
+
function completePlan(machine, step, id, steps, stopped, options) {
|
|
747
|
+
return resolveAgentStep(machine, step, { id }, {
|
|
748
|
+
steps,
|
|
749
|
+
stopped
|
|
750
|
+
}, options);
|
|
751
|
+
}
|
|
752
|
+
function planStepDecisionRequest(request) {
|
|
753
|
+
const { input, applied, events, id } = request;
|
|
754
|
+
const trail = applied.length === 0 ? "" : `\n\nEvents already applied in this plan, in order:\n${applied.map((step) => JSON.stringify(step)).join("\n")}\nContinue from here; do not repeat applied events.`;
|
|
755
|
+
const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${PLAN_DONE_EVENT_TYPE}'.`;
|
|
756
|
+
return {
|
|
757
|
+
kind: "decision",
|
|
758
|
+
id: `${id}[${applied.length}]`,
|
|
759
|
+
model: input.model,
|
|
760
|
+
system: input.system,
|
|
761
|
+
prompt: `${input.prompt ?? ""}${trail}${doneHint}`,
|
|
762
|
+
messages: input.messages,
|
|
763
|
+
events,
|
|
764
|
+
attempts: [],
|
|
765
|
+
temperature: input.temperature,
|
|
766
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
767
|
+
topP: input.topP,
|
|
768
|
+
topK: input.topK,
|
|
769
|
+
seed: input.seed,
|
|
770
|
+
stopSequences: input.stopSequences,
|
|
771
|
+
metadata: input.metadata
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
function advancePlanChildLedger(snapshot, id, event) {
|
|
775
|
+
const child = snapshot.children?.[id];
|
|
776
|
+
const childSnapshot = child?.getSnapshot?.();
|
|
777
|
+
if (!isPlanLogic(child?.logic) || !childSnapshot || typeof childSnapshot !== "object") return;
|
|
778
|
+
Object.assign(childSnapshot, advancePlanLedger(child.logic, childSnapshot, event));
|
|
779
|
+
}
|
|
780
|
+
function isPlanActive(snapshot, id) {
|
|
781
|
+
return (snapshot.children?.[id])?.getSnapshot?.()?.status === "active";
|
|
782
|
+
}
|
|
783
|
+
function createAgentStep(machine, snapshot, actions, options) {
|
|
784
|
+
applyFinalStateOutput(machine, snapshot);
|
|
785
|
+
return {
|
|
786
|
+
snapshot,
|
|
787
|
+
actions,
|
|
788
|
+
requests: getAgentRequestsWith(actions, {
|
|
789
|
+
...options,
|
|
790
|
+
snapshot
|
|
791
|
+
}),
|
|
792
|
+
done: snapshot.status === "done"
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
function resolveStateValueConfig(config, value) {
|
|
796
|
+
if (typeof value === "string") return config.states?.[value];
|
|
797
|
+
if (!value || typeof value !== "object") return;
|
|
798
|
+
for (const [key, childValue] of Object.entries(value)) {
|
|
799
|
+
const childConfig = config.states?.[key];
|
|
800
|
+
if (!childConfig) continue;
|
|
801
|
+
if (childConfig.type === "final") return childConfig;
|
|
802
|
+
const nested = resolveStateValueConfig(childConfig, childValue);
|
|
803
|
+
if (nested) return nested;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
function applyFinalStateOutput(logic, snapshot, event) {
|
|
807
|
+
const machineSnapshot = snapshot;
|
|
808
|
+
if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
|
|
809
|
+
const config = logic.config;
|
|
810
|
+
if (!config) return;
|
|
811
|
+
const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
|
|
812
|
+
if (output === void 0) return;
|
|
813
|
+
machineSnapshot.output = typeof output === "function" ? output({
|
|
814
|
+
context: machineSnapshot.context,
|
|
815
|
+
event
|
|
816
|
+
}) : output;
|
|
817
|
+
}
|
|
818
|
+
function isAgentStep(value) {
|
|
819
|
+
return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
|
|
820
|
+
}
|
|
821
|
+
//#endregion
|
|
822
|
+
//#region src/internal/state-request-pass.ts
|
|
823
|
+
async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
824
|
+
const { model, system } = stateRequest;
|
|
825
|
+
const id = stateRequest.id ?? deps.nextRequestId();
|
|
826
|
+
const promptMessage = userMessage(stateRequest.prompt);
|
|
827
|
+
if (stateRequest.kind === "decision") return {
|
|
828
|
+
stateRequest,
|
|
829
|
+
id,
|
|
830
|
+
output: void 0,
|
|
831
|
+
appended: [promptMessage]
|
|
832
|
+
};
|
|
833
|
+
if (!deps.generateText) throw new Error("runAgent: a getRequests request needs a 'generateText' executor (or use kind: 'decision').");
|
|
834
|
+
const request = {
|
|
835
|
+
model,
|
|
836
|
+
...system !== void 0 ? { system } : {},
|
|
837
|
+
messages: [...baseMessages, promptMessage],
|
|
838
|
+
tools: {}
|
|
839
|
+
};
|
|
840
|
+
const agentRequest = {
|
|
841
|
+
kind: "text",
|
|
842
|
+
id,
|
|
843
|
+
src: INTERPRET_SOURCE,
|
|
844
|
+
mode: "generate",
|
|
845
|
+
input: request,
|
|
846
|
+
tools: {},
|
|
847
|
+
events: []
|
|
848
|
+
};
|
|
849
|
+
deps.consumeModelCall();
|
|
850
|
+
deps.onTrace?.({
|
|
851
|
+
type: "request.start",
|
|
852
|
+
request: agentRequest
|
|
853
|
+
});
|
|
854
|
+
let output;
|
|
855
|
+
try {
|
|
856
|
+
const raw = await deps.generateText(request, { signal: deps.signal });
|
|
857
|
+
output = await normalizeGeneratorResult(raw, id, { request });
|
|
858
|
+
const rawReasoning = raw?.reasoning;
|
|
859
|
+
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
860
|
+
deps.onResult?.(agentRequest, {
|
|
861
|
+
output,
|
|
862
|
+
raw
|
|
863
|
+
});
|
|
864
|
+
deps.onTrace?.({
|
|
865
|
+
type: "request.end",
|
|
866
|
+
request: agentRequest,
|
|
867
|
+
output,
|
|
868
|
+
raw,
|
|
869
|
+
...reasoning !== void 0 ? { reasoning } : {}
|
|
870
|
+
});
|
|
871
|
+
} catch (error) {
|
|
872
|
+
deps.onTrace?.({
|
|
873
|
+
type: "request.error",
|
|
874
|
+
request: agentRequest,
|
|
875
|
+
error
|
|
876
|
+
});
|
|
877
|
+
throw error;
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
stateRequest,
|
|
881
|
+
id,
|
|
882
|
+
output,
|
|
883
|
+
appended: [promptMessage, assistantMessage(typeof output === "string" ? output : JSON.stringify(output))]
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
async function runAdvancePhase(plan, deps) {
|
|
887
|
+
const { stateRequest, id, output } = plan;
|
|
888
|
+
const { model, system } = stateRequest;
|
|
889
|
+
deps.appendToLog(...plan.appended);
|
|
890
|
+
if (stateRequest.kind !== "decision" && stateRequest.onDone !== void 0) {
|
|
891
|
+
const snapshot = deps.getSnapshot();
|
|
892
|
+
const resolved = typeof stateRequest.onDone === "function" ? stateRequest.onDone({
|
|
893
|
+
output,
|
|
894
|
+
snapshot,
|
|
895
|
+
messages: deps.messages
|
|
896
|
+
}) : stateRequest.onDone;
|
|
897
|
+
if (!resolved) return false;
|
|
898
|
+
const acceptedTypes = getAcceptedEvents(snapshot, { schemas: deps.schemas }).map((descriptor) => descriptor.type);
|
|
899
|
+
if (!acceptedTypes.includes(resolved.type)) throw new Error(`runAgent: getRequests request '${id}' resolved onDone to event '${resolved.type}', which the current state does not accept. Accepted: ${acceptedTypes.join(", ") || "(none)"}.`);
|
|
900
|
+
if (!snapshot.can(resolved)) return false;
|
|
901
|
+
deps.send(resolved);
|
|
902
|
+
return true;
|
|
903
|
+
}
|
|
904
|
+
const events = getAcceptedEvents(deps.getSnapshot(), {
|
|
905
|
+
schemas: deps.schemas,
|
|
906
|
+
...stateRequest.allowedEvents ? { eventTypes: stateRequest.allowedEvents } : {}
|
|
907
|
+
});
|
|
908
|
+
if (events.length === 0) return false;
|
|
909
|
+
if (!deps.decide) throw new Error(`runAgent: a getRequests request without 'onDone' needs a 'decide' executor to choose between events ${events.map((descriptor) => `'${descriptor.type}'`).join(", ")}. Provide request.onDone for deterministic advancement, or a 'decide' executor.`);
|
|
910
|
+
const chosen = await resolveDecision({
|
|
911
|
+
kind: "decision",
|
|
912
|
+
id,
|
|
913
|
+
model,
|
|
914
|
+
...system !== void 0 ? { system } : {},
|
|
915
|
+
messages: [...deps.messages],
|
|
916
|
+
events,
|
|
917
|
+
attempts: []
|
|
918
|
+
}, deps.decide, {
|
|
919
|
+
signal: deps.signal,
|
|
920
|
+
canTake: (event) => deps.getSnapshot().can(event)
|
|
921
|
+
});
|
|
922
|
+
if (deps.isSettled()) return false;
|
|
923
|
+
deps.appendToLog(assistantMessage(`[chose: ${chosen.type}]`));
|
|
924
|
+
deps.send(chosen);
|
|
925
|
+
return true;
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Executes one getRequests pass: all text calls concurrently against the
|
|
929
|
+
* pass-start log, then per-request advancement sequentially in request
|
|
930
|
+
* order. Returns whether ANY request sent an event — the host settles idle
|
|
931
|
+
* when none did (otherwise an unchanged snapshot would re-produce the same
|
|
932
|
+
* pass forever). Stops early (skipping remaining appends/sends) once
|
|
933
|
+
* {@link StateRequestPassDeps.isSettled} reports the run is over. Throws on
|
|
934
|
+
* executor/`onDone` errors — the host maps them to its error settle.
|
|
935
|
+
*/
|
|
936
|
+
async function runStateRequestPass(requests, deps) {
|
|
937
|
+
const baseMessages = [...deps.messages];
|
|
938
|
+
const plans = await Promise.all(requests.map((stateRequest) => runTextPhase(stateRequest, baseMessages, deps)));
|
|
939
|
+
let sentAny = false;
|
|
940
|
+
for (const plan of plans) {
|
|
941
|
+
if (deps.isSettled()) break;
|
|
942
|
+
sentAny = await runAdvancePhase(plan, deps) || sentAny;
|
|
943
|
+
}
|
|
944
|
+
return { sentAny };
|
|
945
|
+
}
|
|
946
|
+
//#endregion
|
|
947
|
+
//#region src/run-agent.ts
|
|
948
|
+
/**
|
|
949
|
+
* Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
|
|
950
|
+
* `type` the restored state cannot accept (a type-level check via
|
|
951
|
+
* {@link getAcceptedEvents}). A programmer/integration error, in the same
|
|
952
|
+
* class as runAgent's bind-time throws — it throws rather than settling an
|
|
953
|
+
* `error` result. A type-legal event a guard rejects is NOT this error (the
|
|
954
|
+
* machine simply takes no transition). Opt out with
|
|
955
|
+
* {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
|
|
956
|
+
*/
|
|
957
|
+
var IllegalResumeEventError = class extends Error {
|
|
958
|
+
eventType;
|
|
959
|
+
acceptedTypes;
|
|
960
|
+
constructor(eventType, acceptedTypes) {
|
|
961
|
+
super(`runAgent: cannot resume with event '${eventType}' — the restored state does not accept it. Accepted event types: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
|
|
962
|
+
this.name = "IllegalResumeEventError";
|
|
963
|
+
this.eventType = eventType;
|
|
964
|
+
this.acceptedTypes = acceptedTypes;
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
/**
|
|
968
|
+
* Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
|
|
969
|
+
* `agentMeta.version` differs from the current machine's version, under the
|
|
970
|
+
* default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
|
|
971
|
+
* structural fingerprint of the machine changed since the snapshot was
|
|
972
|
+
* persisted (a state/transition/invoke was added, removed, or retargeted), so
|
|
973
|
+
* the snapshot may no longer resume cleanly. `from` is the snapshot's version,
|
|
974
|
+
* `to` the current machine's.
|
|
975
|
+
*/
|
|
976
|
+
var SnapshotVersionMismatchError = class extends Error {
|
|
977
|
+
from;
|
|
978
|
+
to;
|
|
979
|
+
machineId;
|
|
980
|
+
constructor(from, to, machineId) {
|
|
981
|
+
super(`runAgent: cannot resume snapshot stamped with machine version '${from}' against machine '${machineId}' at version '${to}' — the machine's structure changed since the snapshot was persisted. Provide options.migrateSnapshot to adapt it, or set options.onVersionMismatch to 'warn'/'ignore' to proceed anyway.`);
|
|
982
|
+
this.name = "SnapshotVersionMismatchError";
|
|
983
|
+
this.from = from;
|
|
984
|
+
this.to = to;
|
|
985
|
+
this.machineId = machineId;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
/**
|
|
989
|
+
* Thrown by {@link runAgentToCompletion} when the run settles `idle` instead of
|
|
990
|
+
* `done`: the machine paused for external input. Carries the idle `snapshot`
|
|
991
|
+
* and `acceptedTypes` (the event types that could resume it, via
|
|
992
|
+
* {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
|
|
993
|
+
* expected outcome you handle.
|
|
994
|
+
*/
|
|
995
|
+
var AgentIdleError = class extends Error {
|
|
996
|
+
snapshot;
|
|
997
|
+
acceptedTypes;
|
|
998
|
+
constructor(snapshot, acceptedTypes) {
|
|
999
|
+
super(`runAgentToCompletion: the machine paused (idle) instead of completing. Resume it by calling runAgent with one of these events: ${acceptedTypes.length > 0 ? acceptedTypes.join(", ") : "(none)"}.`);
|
|
1000
|
+
this.name = "AgentIdleError";
|
|
1001
|
+
this.snapshot = snapshot;
|
|
1002
|
+
this.acceptedTypes = acceptedTypes;
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
let nextRunAgentTraceId = 1;
|
|
1006
|
+
var MaxModelCallsExceededError = class extends Error {
|
|
1007
|
+
constructor() {
|
|
1008
|
+
super("runAgent exceeded maxModelCalls.");
|
|
1009
|
+
this.name = "MaxModelCallsExceededError";
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
function wrapsDecisionExhausted(error) {
|
|
1013
|
+
let current = error;
|
|
1014
|
+
for (let depth = 0; depth < 10 && current != null; depth++) {
|
|
1015
|
+
if (current instanceof DecisionExhaustedError) return true;
|
|
1016
|
+
current = current.cause;
|
|
1017
|
+
}
|
|
1018
|
+
return false;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Recursively collects every invoke's `src` from raw machine config (spike
|
|
1022
|
+
* S6: `machine.config` preserves authored srcs; the built `machine.root`
|
|
1023
|
+
* normalizes object srcs to synthetic string ids and loses the distinction
|
|
1024
|
+
* this walk needs). Function-valued `src` resolvers are dynamic and are not
|
|
1025
|
+
* statically analyzable, so they are skipped (pass-through, like any other
|
|
1026
|
+
* non-agent actor).
|
|
1027
|
+
*/
|
|
1028
|
+
function collectConfiguredInvokeSrcs(stateConfig, stateName, out) {
|
|
1029
|
+
if (!stateConfig) return;
|
|
1030
|
+
const invokes = stateConfig.invoke === void 0 ? [] : Array.isArray(stateConfig.invoke) ? stateConfig.invoke : [stateConfig.invoke];
|
|
1031
|
+
for (const invokeConfig of invokes) {
|
|
1032
|
+
const src = invokeConfig?.src;
|
|
1033
|
+
if (typeof src === "string" || src && typeof src === "object") out.push({
|
|
1034
|
+
stateName,
|
|
1035
|
+
src
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
for (const [childName, childConfig] of Object.entries(stateConfig.states ?? {})) collectConfiguredInvokeSrcs(childConfig, `${stateName}.${childName}`, out);
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Duck-types a state machine actor logic (an invoked child machine) vs. any
|
|
1042
|
+
* other actor logic. xstate's `StateMachine` carries `.config`, `.root`, and
|
|
1043
|
+
* a `.provide(...)` method plus an `implementations.actorSources` map — this
|
|
1044
|
+
* combination is unique to machines and survives the dual-package/version
|
|
1045
|
+
* boundary an `instanceof` check would not. Used to descend the bind-time
|
|
1046
|
+
* walk into invoked child machines (their internal agent requests are opaque
|
|
1047
|
+
* to the parent-level source walk otherwise).
|
|
1048
|
+
*/
|
|
1049
|
+
function isStateMachine(logic) {
|
|
1050
|
+
return !!logic && typeof logic === "object" && "config" in logic && "root" in logic && typeof logic.provide === "function" && typeof logic.implementations === "object" && !!logic.implementations?.actorSources;
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Fails fast (throws) at bind time — before any actor runs — when the
|
|
1054
|
+
* machine invokes an agent actor `runAgent` cannot execute. See §3.2 point 2.
|
|
1055
|
+
*
|
|
1056
|
+
* Recurses into invoked child state machines (arbitrarily deep). A child
|
|
1057
|
+
* machine's agent requests reached through string-keyed invoke srcs DO inherit
|
|
1058
|
+
* the parent runAgent's `generateText`/`streamText`/`decide` executors —
|
|
1059
|
+
* runAgent rebinds them with the same host-backed wrappers (see
|
|
1060
|
+
* {@link rebindChildMachine}) — so the only remaining bind-time errors are: a
|
|
1061
|
+
* required executor kind missing entirely (naming the invoke chain and src),
|
|
1062
|
+
* and an unbound request reached through a direct-object invoke src that can't
|
|
1063
|
+
* be rebound ({@link unrebindableChildRequestError}). A request that carries
|
|
1064
|
+
* its own executor (`.withExecutor(...)`, tracked in `executorBoundLogics`)
|
|
1065
|
+
* always runs itself; explicit binding shadows inheritance.
|
|
1066
|
+
*/
|
|
1067
|
+
function assertBindable(machine, effectiveSources, options) {
|
|
1068
|
+
assertMachineBindable(machine, effectiveSources, options, {
|
|
1069
|
+
isChild: false,
|
|
1070
|
+
childPath: "",
|
|
1071
|
+
rebindable: true,
|
|
1072
|
+
visited: new Set([machine])
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
function assertMachineBindable(machine, effectiveSources, options, ctx) {
|
|
1076
|
+
const invokes = [];
|
|
1077
|
+
collectConfiguredInvokeSrcs(machine.config, machine.config.id ?? "(root)", invokes);
|
|
1078
|
+
const where = ctx.isChild ? `child machine '${ctx.childPath}' state` : "state";
|
|
1079
|
+
for (const { stateName, src } of invokes) {
|
|
1080
|
+
if (typeof src !== "string") {
|
|
1081
|
+
if (isStateMachine(src)) {
|
|
1082
|
+
assertChildMachineBindable(src, src, stateName, options, ctx);
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
if ((isTextLogic(src) || isDecisionLogic(src) || isPlanLogic(src)) && !executorBoundLogics.has(src)) throw new Error(`runAgent: ${where} '${stateName}' invokes a direct-object actor logic (kind: '${src.kind}'). Direct-object invoke srcs cannot be rebound by runAgent — either call '.withExecutor(...)' on the logic before invoking it, or register it as a string-keyed actor source instead (machine.provide({ actorSources: { name: logic } })) and invoke it by name.`);
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
const logic = effectiveSources[src];
|
|
1089
|
+
if (logic === void 0) throw new Error(`runAgent: ${where} '${stateName}' invokes unregistered actor source '${src}'. Provide it via machine.provide({ actorSources: { '${src}': ... } }) or runAgent(machine, { actorSources: { '${src}': ... } }).`);
|
|
1090
|
+
if (isStateMachine(logic)) {
|
|
1091
|
+
assertChildMachineBindable(logic, src, stateName, options, ctx);
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
1094
|
+
if (src === "agent.userInput") continue;
|
|
1095
|
+
if (isDecisionLogic(logic)) {
|
|
1096
|
+
if (executorBoundLogics.has(logic)) continue;
|
|
1097
|
+
if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "decision");
|
|
1098
|
+
if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes decision source '${src}' but no 'decide' executor was provided to runAgent(...).`);
|
|
1099
|
+
continue;
|
|
1100
|
+
}
|
|
1101
|
+
if (isPlanLogic(logic)) {
|
|
1102
|
+
if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, "plan");
|
|
1103
|
+
if (!options.hasDecide) throw new Error(`runAgent: ${where} '${stateName}' invokes plan source '${src}' but no 'decide' executor was provided to runAgent(...).`);
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
if (isTextLogic(logic)) {
|
|
1107
|
+
if (executorBoundLogics.has(logic)) continue;
|
|
1108
|
+
if (!ctx.rebindable) throw unrebindableChildRequestError(ctx.childPath, stateName, src, logic.mode === "stream" ? "streaming text" : "text");
|
|
1109
|
+
if (logic.mode === "stream" && !options.hasStreamText) throw new Error(`runAgent: ${where} '${stateName}' invokes streaming text source '${src}' but no 'streamText' executor was provided to runAgent(...).`);
|
|
1110
|
+
if (logic.mode !== "stream" && !options.hasGenerateText) throw new Error(`runAgent: ${where} '${stateName}' invokes text source '${src}' but no 'generateText' executor was provided to runAgent(...).`);
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
if (isUnboundPlaceholder(logic)) throw new Error(`runAgent: ${where} '${stateName}' invokes actor source '${src}', which has no host execution. Provide it via machine.provide({ actorSources: { '${src}': ... } }) or runAgent(machine, { actorSources: { '${src}': ... } }).`);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
/** Descends the bind-time walk into an invoked child state machine, guarding
|
|
1117
|
+
* against a machine that (transitively) invokes itself. */
|
|
1118
|
+
function assertChildMachineBindable(childMachine, childSrc, stateName, options, ctx) {
|
|
1119
|
+
if (ctx.visited.has(childMachine)) return;
|
|
1120
|
+
const childName = typeof childSrc === "string" ? childSrc : childMachine.config.id ?? "(child machine)";
|
|
1121
|
+
const childPath = ctx.childPath ? `${ctx.childPath} > ${childName}` : childName;
|
|
1122
|
+
const childSources = childMachine.implementations.actorSources;
|
|
1123
|
+
assertMachineBindable(childMachine, childSources, options, {
|
|
1124
|
+
isChild: true,
|
|
1125
|
+
childPath,
|
|
1126
|
+
rebindable: ctx.rebindable && typeof childSrc === "string",
|
|
1127
|
+
visited: new Set([...ctx.visited, childMachine])
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
/** The loud bind-time error for an unbound agent request reached under a
|
|
1131
|
+
* direct-object invoke src, which runAgent cannot rebind (only string-keyed
|
|
1132
|
+
* sources can be swapped via `.provide`). Names the invoke chain AND the
|
|
1133
|
+
* request src, and spells out the `.withExecutor`/string-keyed remedy. Note:
|
|
1134
|
+
* requests reachable through string-keyed srcs at any depth DO inherit
|
|
1135
|
+
* runAgent's executors — this error is only for the unrebindable direct-object
|
|
1136
|
+
* case. */
|
|
1137
|
+
function unrebindableChildRequestError(childPath, stateName, requestSrc, kind) {
|
|
1138
|
+
return /* @__PURE__ */ new Error(`runAgent: child machine '${childPath}' (state '${stateName}') invokes ${kind} source '${requestSrc}', which has no host execution and is reached through a direct-object invoke src that runAgent cannot rebind. Requests reached through string-keyed actor sources inherit runAgent's generateText/streamText/decide executors automatically; a direct-object child machine does not. Either bind the request with its own executor (requestLogic.withExecutor(...)), or register the child as a string-keyed actor source (machine.provide({ actorSources: { <child>: childMachine } })) and invoke it by name.`);
|
|
1139
|
+
}
|
|
1140
|
+
/** Reads the durable invoke id/src off the async actor's own ref (`self`). */
|
|
1141
|
+
function selfIdAndSrc(self) {
|
|
1142
|
+
const ref = self;
|
|
1143
|
+
return {
|
|
1144
|
+
id: typeof ref?.id === "string" ? ref.id : "",
|
|
1145
|
+
src: typeof ref?.src === "string" ? ref.src : ""
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* The machine actor that INVOKED a decision/plan request — the actor whose
|
|
1150
|
+
* live snapshot supplies the candidate events and drives `canTake`/`send`.
|
|
1151
|
+
* For a top-level request this is the root actor (identity-equal to
|
|
1152
|
+
* `runCtx.actorHolder.actorRef`); for a request inside an invoked child
|
|
1153
|
+
* machine it is that child's actor, so a child decision/plan reads and drives
|
|
1154
|
+
* the CHILD's snapshot — not the root's. Read off `self._parent`, with the
|
|
1155
|
+
* root actor as a fallback.
|
|
1156
|
+
*/
|
|
1157
|
+
function invokingActorOf(self, runCtx) {
|
|
1158
|
+
return self?._parent ?? runCtx.actorHolder.actorRef;
|
|
1159
|
+
}
|
|
1160
|
+
function wrapTextLogicForRunAgent(logic, runCtx) {
|
|
1161
|
+
return logic.withExecutor(async ({ request, self, signal }) => {
|
|
1162
|
+
const { id, src } = selfIdAndSrc(self);
|
|
1163
|
+
const executor = logic.mode === "stream" ? runCtx.streamText : runCtx.generateText;
|
|
1164
|
+
if (!executor) throw new Error(`runAgent: no '${logic.mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
|
|
1165
|
+
const requestWithTools = {
|
|
1166
|
+
...request,
|
|
1167
|
+
tools: request.tools ?? {}
|
|
1168
|
+
};
|
|
1169
|
+
const agentRequest = {
|
|
1170
|
+
kind: "text",
|
|
1171
|
+
id,
|
|
1172
|
+
src,
|
|
1173
|
+
mode: logic.mode,
|
|
1174
|
+
input: request,
|
|
1175
|
+
tools: requestWithTools.tools,
|
|
1176
|
+
events: []
|
|
1177
|
+
};
|
|
1178
|
+
runCtx.consumeModelCall();
|
|
1179
|
+
runCtx.onTrace?.({
|
|
1180
|
+
type: "request.start",
|
|
1181
|
+
request: agentRequest
|
|
1182
|
+
});
|
|
1183
|
+
try {
|
|
1184
|
+
const raw = await executor(requestWithTools, {
|
|
1185
|
+
onChunk: (chunk) => {
|
|
1186
|
+
runCtx.onTrace?.({
|
|
1187
|
+
type: "stream.chunk",
|
|
1188
|
+
request: agentRequest,
|
|
1189
|
+
chunk
|
|
1190
|
+
});
|
|
1191
|
+
runCtx.onChunk?.(chunk, { request: agentRequest });
|
|
1192
|
+
},
|
|
1193
|
+
signal
|
|
1194
|
+
});
|
|
1195
|
+
const output = await normalizeGeneratorResult(raw, id, {
|
|
1196
|
+
request,
|
|
1197
|
+
onChunk: (chunk) => {
|
|
1198
|
+
runCtx.onTrace?.({
|
|
1199
|
+
type: "stream.chunk",
|
|
1200
|
+
request: agentRequest,
|
|
1201
|
+
chunk
|
|
1202
|
+
});
|
|
1203
|
+
runCtx.onChunk?.(chunk, { request: agentRequest });
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
1206
|
+
const rawReasoning = raw?.reasoning;
|
|
1207
|
+
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
1208
|
+
runCtx.onResult?.(agentRequest, {
|
|
1209
|
+
output,
|
|
1210
|
+
raw
|
|
1211
|
+
});
|
|
1212
|
+
runCtx.onTrace?.({
|
|
1213
|
+
type: "request.end",
|
|
1214
|
+
request: agentRequest,
|
|
1215
|
+
output,
|
|
1216
|
+
raw,
|
|
1217
|
+
...reasoning !== void 0 ? { reasoning } : {}
|
|
1218
|
+
});
|
|
1219
|
+
return { output };
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
runCtx.onTrace?.({
|
|
1222
|
+
type: "request.error",
|
|
1223
|
+
request: agentRequest,
|
|
1224
|
+
error
|
|
1225
|
+
});
|
|
1226
|
+
throw error;
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function createCountingDecide(runCtx) {
|
|
1231
|
+
return async (attemptRequest) => {
|
|
1232
|
+
runCtx.consumeModelCall();
|
|
1233
|
+
runCtx.onTrace?.({
|
|
1234
|
+
type: "request.start",
|
|
1235
|
+
request: attemptRequest
|
|
1236
|
+
});
|
|
1237
|
+
try {
|
|
1238
|
+
const result = await runCtx.decide(attemptRequest);
|
|
1239
|
+
runCtx.onResult?.(attemptRequest, {
|
|
1240
|
+
output: result.event,
|
|
1241
|
+
raw: result
|
|
1242
|
+
});
|
|
1243
|
+
runCtx.onTrace?.({
|
|
1244
|
+
type: "request.end",
|
|
1245
|
+
request: attemptRequest,
|
|
1246
|
+
output: result.event,
|
|
1247
|
+
raw: result
|
|
1248
|
+
});
|
|
1249
|
+
return result;
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
runCtx.onTrace?.({
|
|
1252
|
+
type: "request.error",
|
|
1253
|
+
request: attemptRequest,
|
|
1254
|
+
error
|
|
1255
|
+
});
|
|
1256
|
+
throw error;
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Builds the decision actor logic runAgent installs in place of a
|
|
1262
|
+
* `DecisionLogic`/`agent.decide` source. `DecisionLogic.withExecutor(...)`
|
|
1263
|
+
* can only swap the innermost per-attempt executor — the `resolveDecision(...)`
|
|
1264
|
+
* call (and its `canTake`) is hardwired inside the original logic's `run`.
|
|
1265
|
+
* To supply `canTake` (mode-3, §2.6), runAgent instead builds a fresh async
|
|
1266
|
+
* logic here that calls `resolveDecision` itself, reusing `logic.request(...)`
|
|
1267
|
+
* to build the request the same way the original logic would have.
|
|
1268
|
+
*
|
|
1269
|
+
* On success it SENDS the chosen event to the invoking actor (auto-delivery,
|
|
1270
|
+
* mirroring {@link createRunAgentPlanLogic}) and then completes with that event
|
|
1271
|
+
* as its output — so callers never wire an `onDone` to deliver it. See the
|
|
1272
|
+
* send-then-complete note inside `run` for how exit-cancels-invoke interacts
|
|
1273
|
+
* with `onDone`.
|
|
1274
|
+
*/
|
|
1275
|
+
function createRunAgentDecisionLogic(logic, runCtx) {
|
|
1276
|
+
const decisionLogic = createAsyncLogic({ run: async ({ input, signal, self }) => {
|
|
1277
|
+
if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
|
|
1278
|
+
const { id } = selfIdAndSrc(self);
|
|
1279
|
+
const declaredEventTypes = logic.allowedEventTypes?.(input);
|
|
1280
|
+
await Promise.resolve();
|
|
1281
|
+
const actorRef = invokingActorOf(self, runCtx);
|
|
1282
|
+
const events = actorRef ? getAcceptedEvents(actorRef.getSnapshot(), {
|
|
1283
|
+
schemas: runCtx.schemas,
|
|
1284
|
+
eventTypes: declaredEventTypes
|
|
1285
|
+
}) : [];
|
|
1286
|
+
const chosen = await resolveDecision({
|
|
1287
|
+
...logic.request(input),
|
|
1288
|
+
id,
|
|
1289
|
+
events
|
|
1290
|
+
}, createCountingDecide(runCtx), {
|
|
1291
|
+
maxRetries: logic.maxRetries,
|
|
1292
|
+
signal,
|
|
1293
|
+
canTake: (event) => actorRef ? actorRef.getSnapshot().can(event) : true
|
|
1294
|
+
});
|
|
1295
|
+
actorRef?.send(chosen);
|
|
1296
|
+
await Promise.resolve();
|
|
1297
|
+
return chosen;
|
|
1298
|
+
} });
|
|
1299
|
+
return Object.assign(decisionLogic, {
|
|
1300
|
+
kind: "statelyai.decisionLogic",
|
|
1301
|
+
maxRetries: logic.maxRetries,
|
|
1302
|
+
request: logic.request,
|
|
1303
|
+
withExecutor: (nextExecute) => createRunAgentDecisionLogic(logic.withExecutor(nextExecute), runCtx)
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Builds the plan actor logic runAgent installs in place of the `agent.plan`
|
|
1308
|
+
* builtin: iterated {@link resolveDecision}. Each step re-reads the live
|
|
1309
|
+
* snapshot (so the candidate set reflects everything applied so far), asks
|
|
1310
|
+
* the `decide` executor for one legal event with the same validation/retry
|
|
1311
|
+
* loop a decision gets, and sends it to the machine. The loop ends on a
|
|
1312
|
+
* `stopOn` event, at `maxSteps`, when no legal candidate remains, or when an
|
|
1313
|
+
* applied event exits the invoking state (xstate cancels this invoke — the
|
|
1314
|
+
* machine simply moves on and the pending output is discarded).
|
|
1315
|
+
*
|
|
1316
|
+
* The invoke's `input` is resolved once, so the prompt cannot re-render
|
|
1317
|
+
* context between steps; instead the applied trail is appended to the prompt
|
|
1318
|
+
* each step so the model can see plan progress.
|
|
1319
|
+
*/
|
|
1320
|
+
function createRunAgentPlanLogic(logic, runCtx) {
|
|
1321
|
+
const planLogic = createAsyncLogic({ run: async ({ input, signal, self }) => {
|
|
1322
|
+
if (!runCtx.decide) throw new Error("runAgent: no 'decide' executor provided.");
|
|
1323
|
+
const { id } = selfIdAndSrc(self);
|
|
1324
|
+
const stopOn = new Set(input.stopOn ?? []);
|
|
1325
|
+
const countingDecide = createCountingDecide(runCtx);
|
|
1326
|
+
const base = logic.request(input);
|
|
1327
|
+
let ledger = initialPlanLedger(logic, input);
|
|
1328
|
+
const end = (stopped) => {
|
|
1329
|
+
ledger = advancePlanLedger(logic, ledger, {
|
|
1330
|
+
type: "plan.ended",
|
|
1331
|
+
stopped
|
|
1332
|
+
});
|
|
1333
|
+
return ledger.output;
|
|
1334
|
+
};
|
|
1335
|
+
await Promise.resolve();
|
|
1336
|
+
const invokingActor = invokingActorOf(self, runCtx);
|
|
1337
|
+
while (ledger.context.stepsRemaining > 0) {
|
|
1338
|
+
const actorRef = invokingActor;
|
|
1339
|
+
if (!actorRef || signal.aborted) break;
|
|
1340
|
+
const machineEvents = getAcceptedEvents(actorRef.getSnapshot(), {
|
|
1341
|
+
schemas: runCtx.schemas,
|
|
1342
|
+
eventTypes: logic.allowedEventTypes(input)
|
|
1343
|
+
});
|
|
1344
|
+
if (machineEvents.length === 0) return end("no-legal-events");
|
|
1345
|
+
const doneDescriptor = {
|
|
1346
|
+
type: PLAN_DONE_EVENT_TYPE,
|
|
1347
|
+
toolName: sanitizeEventToolName(PLAN_DONE_EVENT_TYPE)
|
|
1348
|
+
};
|
|
1349
|
+
const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, doneDescriptor];
|
|
1350
|
+
const applied = ledger.context.applied;
|
|
1351
|
+
const trail = applied.length === 0 ? "" : `\n\nEvents already applied in this plan, in order:\n${applied.map((step) => JSON.stringify(step)).join("\n")}\nContinue from here; do not repeat applied events.`;
|
|
1352
|
+
const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${PLAN_DONE_EVENT_TYPE}'.`;
|
|
1353
|
+
const chosen = await resolveDecision({
|
|
1354
|
+
...base,
|
|
1355
|
+
id: `${id}[${applied.length}]`,
|
|
1356
|
+
events,
|
|
1357
|
+
prompt: `${base.prompt ?? ""}${trail}${doneHint}`,
|
|
1358
|
+
attempts: []
|
|
1359
|
+
}, countingDecide, {
|
|
1360
|
+
maxRetries: input.maxRetries ?? logic.maxRetries,
|
|
1361
|
+
signal,
|
|
1362
|
+
canTake: (event) => {
|
|
1363
|
+
if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
|
|
1364
|
+
return invokingActor ? invokingActor.getSnapshot().can(event) : true;
|
|
1365
|
+
}
|
|
1366
|
+
});
|
|
1367
|
+
if (chosen.type === "agent.plan.done") return end("done");
|
|
1368
|
+
actorRef.send(chosen);
|
|
1369
|
+
ledger = advancePlanLedger(logic, ledger, {
|
|
1370
|
+
type: "plan.applied",
|
|
1371
|
+
event: chosen
|
|
1372
|
+
});
|
|
1373
|
+
await Promise.resolve();
|
|
1374
|
+
if (stopOn.has(chosen.type)) return end("stop-event");
|
|
1375
|
+
}
|
|
1376
|
+
return end("max-steps");
|
|
1377
|
+
} });
|
|
1378
|
+
return Object.assign(planLogic, {
|
|
1379
|
+
kind: "statelyai.planLogic",
|
|
1380
|
+
maxRetries: logic.maxRetries,
|
|
1381
|
+
request: logic.request,
|
|
1382
|
+
allowedEventTypes: logic.allowedEventTypes
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Recursively rebinds an invoked child machine's own agent sources with the
|
|
1387
|
+
* SAME host-backed wrappers runAgent applies to the top-level machine, so a
|
|
1388
|
+
* child's text/stream/decision/plan requests inherit runAgent's executors and
|
|
1389
|
+
* participate in maxModelCalls counting, onTrace/onChunk/onResult exactly like
|
|
1390
|
+
* parent requests. Returns the child machine to invoke: a `.provide`-rebound
|
|
1391
|
+
* copy when any inner source needed wrapping, else the original untouched.
|
|
1392
|
+
*
|
|
1393
|
+
* Only string-keyed sources are visited — a direct-object invoke src cannot be
|
|
1394
|
+
* swapped via `.provide` (assertBindable already rejected an unbound request
|
|
1395
|
+
* under one). A source that already carries its own executor
|
|
1396
|
+
* (`executorBoundLogics`) is left as-is: explicit binding shadows inheritance.
|
|
1397
|
+
* Cycle-safe via `visited` (a machine that invokes itself is returned as-is).
|
|
1398
|
+
*/
|
|
1399
|
+
function rebindChildMachine(childMachine, runCtx, visited) {
|
|
1400
|
+
if (visited.has(childMachine)) return childMachine;
|
|
1401
|
+
const childVisited = new Set([...visited, childMachine]);
|
|
1402
|
+
const sources = childMachine.implementations.actorSources;
|
|
1403
|
+
const wrapped = {};
|
|
1404
|
+
for (const [key, logic] of Object.entries(sources)) {
|
|
1405
|
+
if (isDecisionLogic(logic)) {
|
|
1406
|
+
if (!executorBoundLogics.has(logic)) wrapped[key] = createRunAgentDecisionLogic(logic, runCtx);
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
if (isPlanLogic(logic)) {
|
|
1410
|
+
wrapped[key] = createRunAgentPlanLogic(logic, runCtx);
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
if (isTextLogic(logic)) {
|
|
1414
|
+
if (!executorBoundLogics.has(logic)) wrapped[key] = wrapTextLogicForRunAgent(logic, runCtx);
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
if (isStateMachine(logic)) {
|
|
1418
|
+
const rebound = rebindChildMachine(logic, runCtx, childVisited);
|
|
1419
|
+
if (rebound !== logic) wrapped[key] = rebound;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
return Object.keys(wrapped).length > 0 ? childMachine.provide({ actorSources: wrapped }) : childMachine;
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Runs an agent machine to completion or idle: a `createActor` host that
|
|
1427
|
+
* binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
|
|
1428
|
+
* `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
|
|
1429
|
+
* it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
|
|
1430
|
+
* the step helpers ({@link initialAgentStep} etc — a pure
|
|
1431
|
+
* transition-at-a-time path for durable hosts), `runAgent` owns a live actor
|
|
1432
|
+
* internally; there is no continuation callback, so **idle always settles**
|
|
1433
|
+
* and the caller resumes explicitly by passing the settled `{ snapshot,
|
|
1434
|
+
* event }` back in. The actor is stopped on every settle path (`done`,
|
|
1435
|
+
* `idle`, and `error` alike) — resume is always by snapshot, never by
|
|
1436
|
+
* holding a reference to a live actor.
|
|
1437
|
+
*
|
|
1438
|
+
* Binding happens **before** the actor starts: every invoke the machine
|
|
1439
|
+
* could reach is walked and checked against the effective actor sources
|
|
1440
|
+
* (`options.actorSources` merged onto the machine), so a missing
|
|
1441
|
+
* `streamText`/`decide` executor or any other unbound actor source throws
|
|
1442
|
+
* immediately — a bind-time error, not a mid-run failure. The one exception
|
|
1443
|
+
* is `agent.userInput`: unhandled, it binds as a pending placeholder that
|
|
1444
|
+
* settles the run idle (with `pendingUserInputs`) instead of erroring.
|
|
1445
|
+
*
|
|
1446
|
+
* @example
|
|
1447
|
+
* ```ts
|
|
1448
|
+
* const executors = createAiSdkExecutors({ models });
|
|
1449
|
+
* let r = await runAgent(machine, { input, executors });
|
|
1450
|
+
* while (r.status === 'idle') {
|
|
1451
|
+
* const event = await promptUser(getAcceptedEvents(r.snapshot));
|
|
1452
|
+
* r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
|
|
1453
|
+
* }
|
|
1454
|
+
* if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
|
|
1455
|
+
* console.log(r.output);
|
|
1456
|
+
* ```
|
|
1457
|
+
*
|
|
1458
|
+
* The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
|
|
1459
|
+
* functions directly (`executors: { generateText, streamText }` with them
|
|
1460
|
+
* imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
|
|
1461
|
+
* natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
|
|
1462
|
+
* lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
|
|
1463
|
+
*/
|
|
1464
|
+
async function runAgent(machine, options) {
|
|
1465
|
+
const maxModelCalls = options.maxModelCalls ?? 100;
|
|
1466
|
+
let modelCallCount = 0;
|
|
1467
|
+
let budgetExceeded = false;
|
|
1468
|
+
let warnedNonSerializable = false;
|
|
1469
|
+
const runId = `run_${nextRunAgentTraceId++}`;
|
|
1470
|
+
let traceSeq = 0;
|
|
1471
|
+
const machineId = machine.config.id ?? machine.id ?? "(machine)";
|
|
1472
|
+
const machineVersion = options.machineVersion ?? getMachineStructuralHash(machine);
|
|
1473
|
+
const agentMeta = {
|
|
1474
|
+
machineId,
|
|
1475
|
+
version: machineVersion
|
|
1476
|
+
};
|
|
1477
|
+
const stampAgentMeta = (snapshot) => {
|
|
1478
|
+
if (snapshot && typeof snapshot === "object") snapshot.agentMeta = agentMeta;
|
|
1479
|
+
};
|
|
1480
|
+
const onTrace = (event) => {
|
|
1481
|
+
options.onTrace?.({
|
|
1482
|
+
runId,
|
|
1483
|
+
seq: ++traceSeq,
|
|
1484
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1485
|
+
...event
|
|
1486
|
+
});
|
|
1487
|
+
};
|
|
1488
|
+
const consumeModelCall = () => {
|
|
1489
|
+
if (budgetExceeded) throw new MaxModelCallsExceededError();
|
|
1490
|
+
modelCallCount += 1;
|
|
1491
|
+
if (modelCallCount > maxModelCalls) {
|
|
1492
|
+
budgetExceeded = true;
|
|
1493
|
+
throw new MaxModelCallsExceededError();
|
|
1494
|
+
}
|
|
1495
|
+
};
|
|
1496
|
+
const warnNonSerializableContext = (snapshot) => {
|
|
1497
|
+
if (warnedNonSerializable || process.env.NODE_ENV === "production") return;
|
|
1498
|
+
let offending = [];
|
|
1499
|
+
try {
|
|
1500
|
+
offending = findNonSerializableContextPaths(snapshot.context);
|
|
1501
|
+
} catch {
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
if (offending.length === 0) return;
|
|
1505
|
+
warnedNonSerializable = true;
|
|
1506
|
+
console.warn(`runAgent: context holds value(s) that will not survive snapshot persist/resume (JSON round-trip): ${offending.join(", ")}. Persist only JSON-serializable context, or convert these before the run settles.`);
|
|
1507
|
+
};
|
|
1508
|
+
const provided = machine.provide({ actorSources: options.actorSources });
|
|
1509
|
+
const effectiveSources = provided.implementations.actorSources;
|
|
1510
|
+
assertBindable(provided, effectiveSources, {
|
|
1511
|
+
hasGenerateText: !!options.executors?.generateText,
|
|
1512
|
+
hasDecide: !!options.executors?.decide,
|
|
1513
|
+
hasStreamText: !!options.executors?.streamText
|
|
1514
|
+
});
|
|
1515
|
+
if (options.getRequests && !options.executors?.generateText && !options.executors?.decide) throw new Error("runAgent: 'getRequests' requires a 'generateText' and/or 'decide' executor — the returned requests run through them.");
|
|
1516
|
+
const actorHolder = { actorRef: void 0 };
|
|
1517
|
+
const runCtx = {
|
|
1518
|
+
generateText: options.executors?.generateText,
|
|
1519
|
+
streamText: options.executors?.streamText,
|
|
1520
|
+
decide: options.executors?.decide,
|
|
1521
|
+
onChunk: options.onChunk,
|
|
1522
|
+
onResult: options.onResult,
|
|
1523
|
+
onTrace,
|
|
1524
|
+
consumeModelCall,
|
|
1525
|
+
actorHolder,
|
|
1526
|
+
schemas: getRegisteredAgentExecutionOptions(machine).schemas
|
|
1527
|
+
};
|
|
1528
|
+
let userInputIsPlaceholder = false;
|
|
1529
|
+
const wrappedSources = {};
|
|
1530
|
+
for (const [key, logic] of Object.entries(effectiveSources)) {
|
|
1531
|
+
if (key === "agent.userInput") {
|
|
1532
|
+
if (options.userInput) {
|
|
1533
|
+
const userInput = options.userInput;
|
|
1534
|
+
wrappedSources[key] = createAsyncLogic({ run: async ({ input }) => await userInput(input) });
|
|
1535
|
+
} else if (isUnboundPlaceholder(logic)) {
|
|
1536
|
+
userInputIsPlaceholder = true;
|
|
1537
|
+
wrappedSources[key] = createAsyncLogic({ run: () => new Promise(() => {}) });
|
|
1538
|
+
}
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
if (isDecisionLogic(logic)) {
|
|
1542
|
+
wrappedSources[key] = createRunAgentDecisionLogic(logic, runCtx);
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
if (isPlanLogic(logic)) {
|
|
1546
|
+
wrappedSources[key] = createRunAgentPlanLogic(logic, runCtx);
|
|
1547
|
+
continue;
|
|
1548
|
+
}
|
|
1549
|
+
if (isTextLogic(logic)) {
|
|
1550
|
+
if (!executorBoundLogics.has(logic)) wrappedSources[key] = wrapTextLogicForRunAgent(logic, runCtx);
|
|
1551
|
+
continue;
|
|
1552
|
+
}
|
|
1553
|
+
if (isStateMachine(logic)) {
|
|
1554
|
+
const rebound = rebindChildMachine(logic, runCtx, new Set([machine]));
|
|
1555
|
+
if (rebound !== logic) wrappedSources[key] = rebound;
|
|
1556
|
+
continue;
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
const boundMachine = provided.provide({ actorSources: wrappedSources });
|
|
1560
|
+
const isSuspended = options.isSuspended ?? getMachineSuspensionPredicate(machine) ?? (() => false);
|
|
1561
|
+
let effectiveSnapshot = options.snapshot;
|
|
1562
|
+
if (effectiveSnapshot !== void 0) {
|
|
1563
|
+
const from = effectiveSnapshot.agentMeta?.version;
|
|
1564
|
+
if (from !== void 0 && from !== machineVersion) {
|
|
1565
|
+
const info = {
|
|
1566
|
+
from,
|
|
1567
|
+
to: machineVersion
|
|
1568
|
+
};
|
|
1569
|
+
if (options.migrateSnapshot) effectiveSnapshot = options.migrateSnapshot(effectiveSnapshot, info);
|
|
1570
|
+
else {
|
|
1571
|
+
const mode = options.onVersionMismatch ?? "throw";
|
|
1572
|
+
if (mode === "throw") throw new SnapshotVersionMismatchError(from, machineVersion, machineId);
|
|
1573
|
+
if (mode === "warn") console.warn(`runAgent: resuming a snapshot stamped with machine version '${from}' against machine '${machineId}' at version '${machineVersion}'. Structural changes may not resume cleanly.`);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
const priorMessages = getAgentMessages(effectiveSnapshot);
|
|
1578
|
+
const messages = typeof options.messages === "function" ? [...options.messages([...priorMessages])] : [...priorMessages, ...options.messages ?? []];
|
|
1579
|
+
const stampMessages = (snapshot) => {
|
|
1580
|
+
if (!options.getRequests && !options.messages && messages.length === 0) return;
|
|
1581
|
+
if (snapshot && typeof snapshot === "object") snapshot.messages = [...messages];
|
|
1582
|
+
};
|
|
1583
|
+
if (effectiveSnapshot !== void 0 && options.event !== void 0 && (options.onIllegalResumeEvent ?? "throw") === "throw") {
|
|
1584
|
+
const acceptedTypes = getAcceptedEvents(createActor(boundMachine, { snapshot: effectiveSnapshot }).getSnapshot(), { schemas: runCtx.schemas }).map((descriptor) => descriptor.type);
|
|
1585
|
+
const eventType = options.event.type;
|
|
1586
|
+
if (!acceptedTypes.includes(eventType)) throw new IllegalResumeEventError(eventType, acceptedTypes);
|
|
1587
|
+
}
|
|
1588
|
+
return new Promise((resolvePromise) => {
|
|
1589
|
+
let settled = false;
|
|
1590
|
+
let idleTimer;
|
|
1591
|
+
let actor;
|
|
1592
|
+
let deliveringResumeEvent = options.event !== void 0;
|
|
1593
|
+
const settle = (result) => {
|
|
1594
|
+
if (settled) return;
|
|
1595
|
+
settled = true;
|
|
1596
|
+
if (idleTimer !== void 0) clearTimeout(idleTimer);
|
|
1597
|
+
if (options.signal) options.signal.removeEventListener("abort", onAbort);
|
|
1598
|
+
stampAgentMeta(result.snapshot);
|
|
1599
|
+
stampMessages(result.snapshot);
|
|
1600
|
+
if ("persistedSnapshot" in result) {
|
|
1601
|
+
stampAgentMeta(result.persistedSnapshot);
|
|
1602
|
+
stampMessages(result.persistedSnapshot);
|
|
1603
|
+
}
|
|
1604
|
+
onTrace({
|
|
1605
|
+
type: "run.end",
|
|
1606
|
+
...result
|
|
1607
|
+
});
|
|
1608
|
+
actor.stop();
|
|
1609
|
+
resolvePromise(result);
|
|
1610
|
+
};
|
|
1611
|
+
const onAbort = () => {
|
|
1612
|
+
settle({
|
|
1613
|
+
status: "error",
|
|
1614
|
+
cause: "aborted",
|
|
1615
|
+
error: options.signal?.reason ?? /* @__PURE__ */ new Error("Aborted"),
|
|
1616
|
+
snapshot: actor.getSnapshot()
|
|
1617
|
+
});
|
|
1618
|
+
};
|
|
1619
|
+
const settleIdle = (current) => {
|
|
1620
|
+
warnNonSerializableContext(current);
|
|
1621
|
+
const pendingUserInputs = userInputIsPlaceholder ? collectPendingUserInputs(current) : [];
|
|
1622
|
+
settle({
|
|
1623
|
+
status: "idle",
|
|
1624
|
+
snapshot: current,
|
|
1625
|
+
...pendingUserInputs.length > 0 ? {
|
|
1626
|
+
pendingUserInputs,
|
|
1627
|
+
persistedSnapshot: actor.getPersistedSnapshot()
|
|
1628
|
+
} : {}
|
|
1629
|
+
});
|
|
1630
|
+
};
|
|
1631
|
+
let interpreting = false;
|
|
1632
|
+
let interpretSeq = 0;
|
|
1633
|
+
const appendToLog = (...items) => {
|
|
1634
|
+
messages.push(...items);
|
|
1635
|
+
if (options.onMessage) for (const item of items) options.onMessage(item);
|
|
1636
|
+
};
|
|
1637
|
+
const runErrorCause = (error) => budgetExceeded ? "max-model-calls" : wrapsDecisionExhausted(error) ? "decision-exhausted" : "machine";
|
|
1638
|
+
const settleInterpretError = (error) => {
|
|
1639
|
+
settle({
|
|
1640
|
+
status: "error",
|
|
1641
|
+
cause: runErrorCause(error),
|
|
1642
|
+
error,
|
|
1643
|
+
snapshot: actor.getSnapshot()
|
|
1644
|
+
});
|
|
1645
|
+
};
|
|
1646
|
+
const passDeps = {
|
|
1647
|
+
getSnapshot: () => actor.getSnapshot(),
|
|
1648
|
+
send: (event) => actor.send(event),
|
|
1649
|
+
isSettled: () => settled,
|
|
1650
|
+
messages,
|
|
1651
|
+
appendToLog,
|
|
1652
|
+
generateText: runCtx.generateText,
|
|
1653
|
+
decide: runCtx.decide ? createCountingDecide(runCtx) : void 0,
|
|
1654
|
+
consumeModelCall,
|
|
1655
|
+
nextRequestId: () => `interpret_${++interpretSeq}`,
|
|
1656
|
+
onTrace,
|
|
1657
|
+
onResult: runCtx.onResult,
|
|
1658
|
+
schemas: runCtx.schemas,
|
|
1659
|
+
signal: options.signal
|
|
1660
|
+
};
|
|
1661
|
+
const maybeInterpret = (snapshot) => {
|
|
1662
|
+
if (!options.getRequests || settled) return false;
|
|
1663
|
+
if (interpreting) return true;
|
|
1664
|
+
let requested;
|
|
1665
|
+
try {
|
|
1666
|
+
requested = options.getRequests(snapshot, { messages });
|
|
1667
|
+
} catch (error) {
|
|
1668
|
+
settleInterpretError(error);
|
|
1669
|
+
return true;
|
|
1670
|
+
}
|
|
1671
|
+
const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter((stateRequest) => Boolean(stateRequest));
|
|
1672
|
+
if (requests.length === 0) return false;
|
|
1673
|
+
interpreting = true;
|
|
1674
|
+
runStateRequestPass(requests, passDeps).then(({ sentAny }) => {
|
|
1675
|
+
if (settled || sentAny) return;
|
|
1676
|
+
const current = actor.getSnapshot();
|
|
1677
|
+
if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) settleIdle(current);
|
|
1678
|
+
}).catch((error) => settleInterpretError(error)).finally(() => {
|
|
1679
|
+
interpreting = false;
|
|
1680
|
+
if (!settled) scheduleIdleCheck();
|
|
1681
|
+
});
|
|
1682
|
+
return true;
|
|
1683
|
+
};
|
|
1684
|
+
const scheduleIdleCheck = () => {
|
|
1685
|
+
if (idleTimer !== void 0) clearTimeout(idleTimer);
|
|
1686
|
+
idleTimer = setTimeout(() => {
|
|
1687
|
+
idleTimer = void 0;
|
|
1688
|
+
if (settled) return;
|
|
1689
|
+
const current = actor.getSnapshot();
|
|
1690
|
+
if (isIdleSnapshot(current, { ignoreUserInputChildren: userInputIsPlaceholder })) {
|
|
1691
|
+
if (!maybeInterpret(current)) settleIdle(current);
|
|
1692
|
+
}
|
|
1693
|
+
}, 0);
|
|
1694
|
+
};
|
|
1695
|
+
actor = createActor(boundMachine, {
|
|
1696
|
+
input: options.input,
|
|
1697
|
+
snapshot: effectiveSnapshot,
|
|
1698
|
+
inspect: (event) => {
|
|
1699
|
+
options.inspect?.(event);
|
|
1700
|
+
if (settled || event.type !== "@xstate.transition" || event.actorRef !== actor.ref) return;
|
|
1701
|
+
const snapshot = event.snapshot;
|
|
1702
|
+
onTrace({
|
|
1703
|
+
type: "machine.transition",
|
|
1704
|
+
snapshot,
|
|
1705
|
+
event: event.event
|
|
1706
|
+
});
|
|
1707
|
+
options.onTransition?.(snapshot, event.event);
|
|
1708
|
+
if (snapshot.status === "done") {
|
|
1709
|
+
settle({
|
|
1710
|
+
status: "done",
|
|
1711
|
+
output: snapshot.output,
|
|
1712
|
+
snapshot
|
|
1713
|
+
});
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
if (snapshot.status === "error") {
|
|
1717
|
+
settle({
|
|
1718
|
+
status: "error",
|
|
1719
|
+
cause: runErrorCause(snapshot.error),
|
|
1720
|
+
error: snapshot.error,
|
|
1721
|
+
snapshot
|
|
1722
|
+
});
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
if (snapshot.status === "stopped") {
|
|
1726
|
+
settle({
|
|
1727
|
+
status: "error",
|
|
1728
|
+
cause: "stopped",
|
|
1729
|
+
error: /* @__PURE__ */ new Error("Actor stopped externally."),
|
|
1730
|
+
snapshot
|
|
1731
|
+
});
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
if (!deliveringResumeEvent && isSuspended(snapshot) && isIdleSnapshot(snapshot, { ignoreUserInputChildren: userInputIsPlaceholder })) {
|
|
1735
|
+
if (!maybeInterpret(snapshot)) settleIdle(snapshot);
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
scheduleIdleCheck();
|
|
1739
|
+
}
|
|
1740
|
+
});
|
|
1741
|
+
actorHolder.actorRef = actor;
|
|
1742
|
+
actor.subscribe({ error: () => {} });
|
|
1743
|
+
actor.on("*", (event) => {
|
|
1744
|
+
onTrace({
|
|
1745
|
+
type: "emit",
|
|
1746
|
+
event
|
|
1747
|
+
});
|
|
1748
|
+
});
|
|
1749
|
+
for (const [type, handler] of Object.entries(options.on ?? {})) if (typeof handler === "function") actor.on(type, handler);
|
|
1750
|
+
if (options.signal) {
|
|
1751
|
+
if (options.signal.aborted) {
|
|
1752
|
+
settle({
|
|
1753
|
+
status: "error",
|
|
1754
|
+
cause: "aborted",
|
|
1755
|
+
error: options.signal.reason ?? /* @__PURE__ */ new Error("Aborted"),
|
|
1756
|
+
snapshot: actor.getSnapshot()
|
|
1757
|
+
});
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
options.signal.addEventListener("abort", onAbort);
|
|
1761
|
+
}
|
|
1762
|
+
onTrace({
|
|
1763
|
+
type: "run.start",
|
|
1764
|
+
...options.input !== void 0 ? { input: options.input } : {},
|
|
1765
|
+
...effectiveSnapshot !== void 0 ? { snapshot: effectiveSnapshot } : {},
|
|
1766
|
+
...options.event !== void 0 ? { event: options.event } : {}
|
|
1767
|
+
});
|
|
1768
|
+
actor.start();
|
|
1769
|
+
if (options.event) {
|
|
1770
|
+
deliveringResumeEvent = false;
|
|
1771
|
+
actor.send(options.event);
|
|
1772
|
+
}
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Runs an agent machine to a **final state** and returns its output, for
|
|
1777
|
+
* run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
|
|
1778
|
+
*
|
|
1779
|
+
* - `done` → resolves with `result.output` (the machine's `OutputFrom`).
|
|
1780
|
+
* - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
|
|
1781
|
+
* event types that could resume it.
|
|
1782
|
+
* - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
|
|
1783
|
+
* in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
|
|
1784
|
+
* `.error` is the raw thrown value.
|
|
1785
|
+
*
|
|
1786
|
+
* Use {@link runAgent} directly when idle is an expected outcome you handle
|
|
1787
|
+
* (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
|
|
1788
|
+
* machine is meant to run straight through to a final state.
|
|
1789
|
+
*/
|
|
1790
|
+
async function runAgentToCompletion(machine, options) {
|
|
1791
|
+
const result = await runAgent(machine, options);
|
|
1792
|
+
if (result.status === "done") return result.output;
|
|
1793
|
+
if (result.status === "idle") {
|
|
1794
|
+
const acceptedTypes = getAcceptedEvents(result.snapshot, { schemas: getRegisteredAgentExecutionOptions(machine).schemas }).map((descriptor) => descriptor.type);
|
|
1795
|
+
throw new AgentIdleError(result.snapshot, acceptedTypes);
|
|
1796
|
+
}
|
|
1797
|
+
if (result.error instanceof Error) throw result.error;
|
|
1798
|
+
const wrapped = /* @__PURE__ */ new Error(`runAgentToCompletion: run failed with cause '${result.cause}'.`);
|
|
1799
|
+
wrapped.cause = result.cause;
|
|
1800
|
+
wrapped.error = result.error;
|
|
1801
|
+
throw wrapped;
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* Wraps a `(snapshot, actorRef) => void` handler into a function usable as
|
|
1805
|
+
* {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
|
|
1806
|
+
* `@xstate.transition` events and hands the handler the typed
|
|
1807
|
+
* {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
|
|
1808
|
+
* transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
|
|
1809
|
+
* the manual `event.type === '@xstate.transition'` filtering and the snapshot/
|
|
1810
|
+
* actorRef casts.
|
|
1811
|
+
*/
|
|
1812
|
+
function inspectTransitions(handler) {
|
|
1813
|
+
return (inspectionEvent) => {
|
|
1814
|
+
if (inspectionEvent.type !== "@xstate.transition") return;
|
|
1815
|
+
handler(inspectionEvent.snapshot, inspectionEvent.actorRef);
|
|
1816
|
+
};
|
|
1817
|
+
}
|
|
1818
|
+
function isIdleSnapshot(snapshot, { ignoreUserInputChildren }) {
|
|
1819
|
+
if (snapshot.status !== "active") return false;
|
|
1820
|
+
if (Object.values(snapshot.children ?? {}).some((child) => {
|
|
1821
|
+
const ref = child;
|
|
1822
|
+
if (ignoreUserInputChildren && ref?.src === "agent.userInput") return false;
|
|
1823
|
+
return ref?.getSnapshot?.()?.status === "active";
|
|
1824
|
+
})) return false;
|
|
1825
|
+
return !getNextTransitions(snapshot).some((transitionDef) => transitionDef.eventType === "" || transitionDef.eventType.startsWith("xstate.after"));
|
|
1826
|
+
}
|
|
1827
|
+
function collectPendingUserInputs(snapshot) {
|
|
1828
|
+
const pending = [];
|
|
1829
|
+
for (const [id, child] of Object.entries(snapshot.children ?? {})) {
|
|
1830
|
+
const ref = child;
|
|
1831
|
+
if (ref?.src !== "agent.userInput") continue;
|
|
1832
|
+
const childSnapshot = ref.getSnapshot?.();
|
|
1833
|
+
if (childSnapshot?.status !== "active") continue;
|
|
1834
|
+
pending.push({
|
|
1835
|
+
id,
|
|
1836
|
+
input: childSnapshot.input
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
return pending;
|
|
1840
|
+
}
|
|
1841
|
+
//#endregion
|
|
1842
|
+
//#region src/verify.ts
|
|
1843
|
+
const DECIDE_SRC = "agent.decide";
|
|
1844
|
+
const PLAN_SRC = "agent.plan";
|
|
1845
|
+
function normalizeInvokes(invoke) {
|
|
1846
|
+
if (invoke === void 0 || invoke === null) return [];
|
|
1847
|
+
return Array.isArray(invoke) ? invoke : [invoke];
|
|
1848
|
+
}
|
|
1849
|
+
function buildStateIndex(rootConfig) {
|
|
1850
|
+
const index = /* @__PURE__ */ new Map();
|
|
1851
|
+
const walk = (states, parentPath) => {
|
|
1852
|
+
for (const [name, config] of Object.entries(states ?? {})) {
|
|
1853
|
+
const path = parentPath ? `${parentPath}.${name}` : name;
|
|
1854
|
+
const hasChildren = !!config.states && Object.keys(config.states).length > 0;
|
|
1855
|
+
index.set(path, {
|
|
1856
|
+
path,
|
|
1857
|
+
name,
|
|
1858
|
+
config,
|
|
1859
|
+
parentPath,
|
|
1860
|
+
type: config.type,
|
|
1861
|
+
isFinal: config.type === "final",
|
|
1862
|
+
isParallel: config.type === "parallel",
|
|
1863
|
+
isCompound: hasChildren && config.type !== "parallel",
|
|
1864
|
+
invokes: normalizeInvokes(config.invoke)
|
|
1865
|
+
});
|
|
1866
|
+
if (hasChildren) walk(config.states, path);
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
walk(rootConfig.states, "");
|
|
1870
|
+
return index;
|
|
1871
|
+
}
|
|
1872
|
+
function childrenOf(index, parentPath) {
|
|
1873
|
+
const out = [];
|
|
1874
|
+
for (const node of index.values()) if (node.parentPath === parentPath) out.push(node);
|
|
1875
|
+
return out;
|
|
1876
|
+
}
|
|
1877
|
+
function collectTransitionTargets(value, fromNode, index, out) {
|
|
1878
|
+
if (value === void 0 || value === null) return;
|
|
1879
|
+
if (Array.isArray(value)) {
|
|
1880
|
+
for (const item of value) collectTransitionTargets(item, fromNode, index, out);
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
if (typeof value === "function") {
|
|
1884
|
+
out.opaque = true;
|
|
1885
|
+
return;
|
|
1886
|
+
}
|
|
1887
|
+
if (typeof value === "string") {
|
|
1888
|
+
resolveTargetString(value, fromNode, index, out);
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
if (typeof value === "object") {
|
|
1892
|
+
const target = value.target;
|
|
1893
|
+
if (target !== void 0) collectTransitionTargets(target, fromNode, index, out);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
function resolveTargetString(target, fromNode, index, out) {
|
|
1897
|
+
if (target.startsWith("#")) {
|
|
1898
|
+
out.opaque = true;
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
const resolved = target.startsWith(".") ? `${fromNode.path}.${target.slice(1)}` : fromNode.parentPath ? `${fromNode.parentPath}.${target}` : target;
|
|
1902
|
+
if (index.has(resolved)) out.targets.push(resolved);
|
|
1903
|
+
else out.opaque = true;
|
|
1904
|
+
}
|
|
1905
|
+
function outgoingTargets(node, index) {
|
|
1906
|
+
const out = {
|
|
1907
|
+
targets: [],
|
|
1908
|
+
opaque: false
|
|
1909
|
+
};
|
|
1910
|
+
const { config } = node;
|
|
1911
|
+
for (const value of Object.values(config.on ?? {})) collectTransitionTargets(value, node, index, out);
|
|
1912
|
+
collectTransitionTargets(config.always, node, index, out);
|
|
1913
|
+
collectTransitionTargets(config.choice, node, index, out);
|
|
1914
|
+
for (const value of Object.values(config.after ?? {})) collectTransitionTargets(value, node, index, out);
|
|
1915
|
+
collectTransitionTargets(config.onDone, node, index, out);
|
|
1916
|
+
for (const invoke of node.invokes) {
|
|
1917
|
+
collectTransitionTargets(invoke.onDone, node, index, out);
|
|
1918
|
+
collectTransitionTargets(invoke.onError, node, index, out);
|
|
1919
|
+
}
|
|
1920
|
+
return out;
|
|
1921
|
+
}
|
|
1922
|
+
function computeReachable(rootConfig, index) {
|
|
1923
|
+
const reachable = /* @__PURE__ */ new Set();
|
|
1924
|
+
const queue = [];
|
|
1925
|
+
const markAncestors = (path) => {
|
|
1926
|
+
let parent = index.get(path)?.parentPath ?? "";
|
|
1927
|
+
while (parent) {
|
|
1928
|
+
reachable.add(parent);
|
|
1929
|
+
parent = index.get(parent)?.parentPath ?? "";
|
|
1930
|
+
}
|
|
1931
|
+
};
|
|
1932
|
+
const enter = (path) => {
|
|
1933
|
+
if (reachable.has(path)) return;
|
|
1934
|
+
const node = index.get(path);
|
|
1935
|
+
if (!node) return;
|
|
1936
|
+
reachable.add(path);
|
|
1937
|
+
queue.push(path);
|
|
1938
|
+
markAncestors(path);
|
|
1939
|
+
if (node.isParallel) for (const child of childrenOf(index, path)) enter(child.path);
|
|
1940
|
+
else if (node.isCompound && node.config.initial) enter(`${path}.${node.config.initial}`);
|
|
1941
|
+
};
|
|
1942
|
+
if (rootConfig.type === "parallel") for (const child of childrenOf(index, "")) enter(child.path);
|
|
1943
|
+
else if (rootConfig.initial) enter(rootConfig.initial);
|
|
1944
|
+
while (queue.length > 0) {
|
|
1945
|
+
const node = index.get(queue.shift());
|
|
1946
|
+
if (!node) continue;
|
|
1947
|
+
const { targets, opaque } = outgoingTargets(node, index);
|
|
1948
|
+
for (const target of targets) enter(target);
|
|
1949
|
+
if (opaque) for (const sibling of childrenOf(index, node.parentPath)) enter(sibling.path);
|
|
1950
|
+
}
|
|
1951
|
+
return reachable;
|
|
1952
|
+
}
|
|
1953
|
+
function ancestorChain(node, index) {
|
|
1954
|
+
const chain = [];
|
|
1955
|
+
let parent = node.parentPath;
|
|
1956
|
+
while (parent) {
|
|
1957
|
+
const parentNode = index.get(parent);
|
|
1958
|
+
if (!parentNode) break;
|
|
1959
|
+
chain.push(parentNode);
|
|
1960
|
+
parent = parentNode.parentPath;
|
|
1961
|
+
}
|
|
1962
|
+
return chain;
|
|
1963
|
+
}
|
|
1964
|
+
function hasNonEmptyOn(config) {
|
|
1965
|
+
return !!config.on && Object.keys(config.on).length > 0;
|
|
1966
|
+
}
|
|
1967
|
+
function decisionKindOf(src, actorSources) {
|
|
1968
|
+
if (typeof src === "string") {
|
|
1969
|
+
if (src === DECIDE_SRC) return "decision";
|
|
1970
|
+
if (src === PLAN_SRC) return "plan";
|
|
1971
|
+
const logic = actorSources[src];
|
|
1972
|
+
if (isDecisionLogic(logic)) return "decision";
|
|
1973
|
+
if (isPlanLogic(logic)) return "plan";
|
|
1974
|
+
return;
|
|
1975
|
+
}
|
|
1976
|
+
if (isDecisionLogic(src)) return "decision";
|
|
1977
|
+
if (isPlanLogic(src)) return "plan";
|
|
1978
|
+
}
|
|
1979
|
+
function isAgentLogicNeedingBinding(src) {
|
|
1980
|
+
return (isTextLogic(src) || isDecisionLogic(src) || isPlanLogic(src)) && !executorBoundLogics.has(src);
|
|
1981
|
+
}
|
|
1982
|
+
function schemaExposesJson(schema) {
|
|
1983
|
+
if (!schema) return false;
|
|
1984
|
+
try {
|
|
1985
|
+
return getJsonSchemaSync(schema) !== void 0;
|
|
1986
|
+
} catch {
|
|
1987
|
+
return false;
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
function isDeclaredOutputSchema(schema) {
|
|
1991
|
+
if (!schema) return false;
|
|
1992
|
+
let json;
|
|
1993
|
+
try {
|
|
1994
|
+
json = getJsonSchemaSync(schema);
|
|
1995
|
+
} catch {
|
|
1996
|
+
return false;
|
|
1997
|
+
}
|
|
1998
|
+
if (!json) return false;
|
|
1999
|
+
const properties = json.properties;
|
|
2000
|
+
const required = json.required;
|
|
2001
|
+
return json.type === "object" && !!properties && Object.keys(properties).length > 0 || Array.isArray(required) && required.length > 0;
|
|
2002
|
+
}
|
|
2003
|
+
function checkUnreachableStates(ctx) {
|
|
2004
|
+
const out = [];
|
|
2005
|
+
for (const node of ctx.index.values()) if (!ctx.reachable.has(node.path)) out.push({
|
|
2006
|
+
code: "unreachable-state",
|
|
2007
|
+
severity: "error",
|
|
2008
|
+
path: node.path,
|
|
2009
|
+
message: `State '${node.path}' is unreachable: no transition, always, onDone, or onError target (from any reachable state) leads to it. Remove it or add a transition.`
|
|
2010
|
+
});
|
|
2011
|
+
return out;
|
|
2012
|
+
}
|
|
2013
|
+
function checkDecideWithoutEvents(ctx) {
|
|
2014
|
+
const out = [];
|
|
2015
|
+
for (const node of ctx.index.values()) for (const invoke of node.invokes) {
|
|
2016
|
+
const kind = decisionKindOf(invoke.src, ctx.actorSources);
|
|
2017
|
+
if (!kind) continue;
|
|
2018
|
+
const selfHandles = hasNonEmptyOn(node.config);
|
|
2019
|
+
const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
|
|
2020
|
+
const invokeObserves = invoke.onDone !== void 0;
|
|
2021
|
+
if (selfHandles || ancestorHandles || invokeObserves) continue;
|
|
2022
|
+
const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
|
|
2023
|
+
out.push({
|
|
2024
|
+
code: "decide-without-events",
|
|
2025
|
+
severity: "error",
|
|
2026
|
+
path: node.path,
|
|
2027
|
+
message: `State '${node.path}' invokes ${kind} source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the ${kind}'s chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
return out;
|
|
2031
|
+
}
|
|
2032
|
+
function checkUnserializableContext(ctx) {
|
|
2033
|
+
const contextSchema = ctx.schemas?.context;
|
|
2034
|
+
if (!contextSchema) return [];
|
|
2035
|
+
if (schemaExposesJson(contextSchema)) return [];
|
|
2036
|
+
return [{
|
|
2037
|
+
code: "unserializable-context",
|
|
2038
|
+
severity: "warning",
|
|
2039
|
+
path: "context",
|
|
2040
|
+
message: "The context schema does not expose a JSON schema (e.g. a `z.custom` without a `jsonSchema` extension, such as a messages array), so its fields cannot be statically checked for JSON persist/resume round-tripping. This is expected for message transcripts; verify any other custom-typed context is JSON-serializable."
|
|
2041
|
+
}];
|
|
2042
|
+
}
|
|
2043
|
+
function checkDirectObjectSrc(ctx) {
|
|
2044
|
+
const out = [];
|
|
2045
|
+
for (const node of ctx.index.values()) for (const invoke of node.invokes) {
|
|
2046
|
+
const src = invoke.src;
|
|
2047
|
+
if (typeof src === "string" || !src || typeof src !== "object") continue;
|
|
2048
|
+
if (!isAgentLogicNeedingBinding(src)) continue;
|
|
2049
|
+
out.push({
|
|
2050
|
+
code: "direct-object-src",
|
|
2051
|
+
severity: "warning",
|
|
2052
|
+
path: node.path,
|
|
2053
|
+
message: `State '${node.path}' invokes a direct-object agent logic. Direct-object invoke srcs cannot be rebound by runAgent, so they inherit no host executors — call '.withExecutor(...)' on the logic, or register it as a string-keyed actor source (machine.provide({ actorSources: { name: logic } })) and invoke it by name.`
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
return out;
|
|
2057
|
+
}
|
|
2058
|
+
function checkFinalWithoutOutput(ctx) {
|
|
2059
|
+
if (!isDeclaredOutputSchema(ctx.schemas?.output)) return [];
|
|
2060
|
+
if (ctx.config.output !== void 0) return [];
|
|
2061
|
+
const out = [];
|
|
2062
|
+
for (const node of ctx.index.values()) {
|
|
2063
|
+
if (node.parentPath !== "" || !node.isFinal) continue;
|
|
2064
|
+
if (node.config.output === void 0) out.push({
|
|
2065
|
+
code: "final-without-output",
|
|
2066
|
+
severity: "error",
|
|
2067
|
+
path: node.path,
|
|
2068
|
+
message: `The machine declares an output schema, but top-level final state '${node.path}' has no 'output'. Its snapshot output will be undefined and fail the schema. Add an 'output' to this final state (or a root 'output').`
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
return out;
|
|
2072
|
+
}
|
|
2073
|
+
function outputFnReadsEvent(fn) {
|
|
2074
|
+
return /\bevent\s*(?:\.|\?\.|\[)/.test(fn.toString());
|
|
2075
|
+
}
|
|
2076
|
+
function checkFinalOutputReadsEvent(ctx) {
|
|
2077
|
+
const out = [];
|
|
2078
|
+
for (const node of ctx.index.values()) {
|
|
2079
|
+
if (node.parentPath !== "" || !node.isFinal) continue;
|
|
2080
|
+
const output = node.config.output;
|
|
2081
|
+
if (typeof output !== "function") continue;
|
|
2082
|
+
if (!outputFnReadsEvent(output)) continue;
|
|
2083
|
+
out.push({
|
|
2084
|
+
code: "final-output-reads-event",
|
|
2085
|
+
severity: "warning",
|
|
2086
|
+
path: node.path,
|
|
2087
|
+
message: `Final state '${node.path}' has an 'output' function that reads 'event'. Final-state 'output' functions are evaluated more than once with different events (the entering event, then the machine-done computation) under current xstate behavior, so 'event' is unreliable here. Read 'context' only; capture what you need from the entering event into context in the transition that targets this state. (This guard can relax if xstate guarantees a stable entering event across evaluations.)`
|
|
2088
|
+
});
|
|
2089
|
+
}
|
|
2090
|
+
return out;
|
|
2091
|
+
}
|
|
2092
|
+
function checkMissingFinal(ctx) {
|
|
2093
|
+
for (const node of ctx.index.values()) if (node.isFinal && ctx.reachable.has(node.path)) return [];
|
|
2094
|
+
return [{
|
|
2095
|
+
code: "missing-final",
|
|
2096
|
+
severity: "warning",
|
|
2097
|
+
path: "(root)",
|
|
2098
|
+
message: "The machine has no reachable final state, so a run can never settle 'done' (only idle/looping). This is legal for agents that only idle, but verify it is intended."
|
|
2099
|
+
}];
|
|
2100
|
+
}
|
|
2101
|
+
const LINT_CHECKS = [
|
|
2102
|
+
checkUnreachableStates,
|
|
2103
|
+
checkDecideWithoutEvents,
|
|
2104
|
+
checkUnserializableContext,
|
|
2105
|
+
checkDirectObjectSrc,
|
|
2106
|
+
checkFinalWithoutOutput,
|
|
2107
|
+
checkFinalOutputReadsEvent,
|
|
2108
|
+
checkMissingFinal
|
|
2109
|
+
];
|
|
2110
|
+
/**
|
|
2111
|
+
* Runs static structural checks over a built agent machine and returns the
|
|
2112
|
+
* findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
|
|
2113
|
+
* TS-authored (`setupAgent(...).createMachine(...)`) and
|
|
2114
|
+
* `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
|
|
2115
|
+
* plus the schemas/actor sources the library already retains per machine.
|
|
2116
|
+
*
|
|
2117
|
+
* No model calls, no API keys — a coding agent that emits an agent machine can
|
|
2118
|
+
* call this to catch dead states, undeliverable decisions, un-rebindable
|
|
2119
|
+
* invoke srcs, and output-contract gaps before ever running it.
|
|
2120
|
+
*
|
|
2121
|
+
* @example
|
|
2122
|
+
* ```ts
|
|
2123
|
+
* const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
|
|
2124
|
+
* if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
|
|
2125
|
+
* ```
|
|
2126
|
+
*/
|
|
2127
|
+
function lintAgentMachine(machine, options = {}) {
|
|
2128
|
+
const config = machine.config ?? {};
|
|
2129
|
+
const index = buildStateIndex(config);
|
|
2130
|
+
const reachable = computeReachable(config, index);
|
|
2131
|
+
const registered = getRegisteredAgentExecutionOptions(machine);
|
|
2132
|
+
const ctx = {
|
|
2133
|
+
machine,
|
|
2134
|
+
config,
|
|
2135
|
+
index,
|
|
2136
|
+
reachable,
|
|
2137
|
+
schemas: registered.schemas,
|
|
2138
|
+
actorSources: registered.actorSources ?? machine.implementations?.actorSources ?? {}
|
|
2139
|
+
};
|
|
2140
|
+
const disabled = new Set(options.disable ?? []);
|
|
2141
|
+
return LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
|
|
2142
|
+
}
|
|
2143
|
+
function pendingInvokes(step) {
|
|
2144
|
+
const out = [];
|
|
2145
|
+
for (const action of step.actions) {
|
|
2146
|
+
const type = action.type;
|
|
2147
|
+
if (type !== "xstate.spawnChild" && type !== "@xstate.start") continue;
|
|
2148
|
+
const params = type === "@xstate.start" ? action : action.params ?? {};
|
|
2149
|
+
if (typeof params.src === "string" && typeof params.id === "string") out.push({
|
|
2150
|
+
id: params.id,
|
|
2151
|
+
src: params.src
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
return out;
|
|
2155
|
+
}
|
|
2156
|
+
function takeFromQueue(channel, src) {
|
|
2157
|
+
const queue = channel?.[src];
|
|
2158
|
+
if (queue && queue.length > 0) return {
|
|
2159
|
+
found: true,
|
|
2160
|
+
value: queue.shift()
|
|
2161
|
+
};
|
|
2162
|
+
return { found: false };
|
|
2163
|
+
}
|
|
2164
|
+
/**
|
|
2165
|
+
* Deterministically plays a machine through, resolving each request from a
|
|
2166
|
+
* {@link SimulationScript} instead of a model — no API keys, no model calls.
|
|
2167
|
+
* Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
|
|
2168
|
+
* the real transition logic. Returns the terminal `status`, final `snapshot`,
|
|
2169
|
+
* and a `trail` of every step taken.
|
|
2170
|
+
*
|
|
2171
|
+
* Throws a descriptive error when the script runs dry mid-request, naming the
|
|
2172
|
+
* pending request's kind, src, and id so the missing scripted response is
|
|
2173
|
+
* obvious.
|
|
2174
|
+
*
|
|
2175
|
+
* @example
|
|
2176
|
+
* ```ts
|
|
2177
|
+
* const { status, snapshot } = simulateAgent(machine, {
|
|
2178
|
+
* input: { topic: 'state machines' },
|
|
2179
|
+
* script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
|
|
2180
|
+
* });
|
|
2181
|
+
* ```
|
|
2182
|
+
*/
|
|
2183
|
+
async function simulateAgent(machine, options) {
|
|
2184
|
+
const maxSteps = options.maxSteps ?? 100;
|
|
2185
|
+
const script = {
|
|
2186
|
+
text: { ...options.script.text },
|
|
2187
|
+
decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
|
|
2188
|
+
userInput: mapValues(options.script.userInput ?? {}, (arr) => [...arr])
|
|
2189
|
+
};
|
|
2190
|
+
let step = initialAgentStep(machine, options.input);
|
|
2191
|
+
const trail = [];
|
|
2192
|
+
for (let i = 0; i < maxSteps; i++) {
|
|
2193
|
+
if (step.done) return {
|
|
2194
|
+
status: "done",
|
|
2195
|
+
snapshot: step.snapshot,
|
|
2196
|
+
trail
|
|
2197
|
+
};
|
|
2198
|
+
const request = step.requests[0];
|
|
2199
|
+
if (request) {
|
|
2200
|
+
if (request.kind === "decision") {
|
|
2201
|
+
const decisionSrc = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src])).get(request.id) ?? request.id;
|
|
2202
|
+
const taken = takeFromQueue(script.decisions, decisionSrc);
|
|
2203
|
+
if (!taken.found) throw scriptDryError("decision", decisionSrc, request.id, request);
|
|
2204
|
+
step = transitionAgentStep(machine, step, taken.value);
|
|
2205
|
+
trail.push({
|
|
2206
|
+
state: step.snapshot.value,
|
|
2207
|
+
appliedEvent: taken.value
|
|
2208
|
+
});
|
|
2209
|
+
continue;
|
|
2210
|
+
}
|
|
2211
|
+
if (request.kind === "plan") {
|
|
2212
|
+
const taken = takeFromQueue(script.decisions, request.src);
|
|
2213
|
+
if (!taken.found) throw scriptDryError("decision", request.src, request.id, request);
|
|
2214
|
+
const event = taken.value;
|
|
2215
|
+
step = await resolveAgentRequests(machine, step, { decide: async () => ({ event }) });
|
|
2216
|
+
trail.push({
|
|
2217
|
+
state: step.snapshot.value,
|
|
2218
|
+
appliedEvent: taken.value
|
|
2219
|
+
});
|
|
2220
|
+
continue;
|
|
2221
|
+
}
|
|
2222
|
+
const taken = takeFromQueue(script.text, request.src);
|
|
2223
|
+
if (!taken.found) throw scriptDryError("text", request.src, request.id);
|
|
2224
|
+
step = resolveAgentStep(machine, step, request, taken.value);
|
|
2225
|
+
trail.push({
|
|
2226
|
+
state: step.snapshot.value,
|
|
2227
|
+
resolvedRequest: {
|
|
2228
|
+
kind: "text",
|
|
2229
|
+
src: request.src,
|
|
2230
|
+
id: request.id
|
|
2231
|
+
}
|
|
2232
|
+
});
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
const [invoke] = pendingInvokes(step);
|
|
2236
|
+
if (invoke) {
|
|
2237
|
+
const taken = takeFromQueue(script.userInput, invoke.src);
|
|
2238
|
+
if (!taken.found) throw scriptDryError("userInput", invoke.src, invoke.id);
|
|
2239
|
+
step = resolveAgentStep(machine, step, invoke.id, taken.value);
|
|
2240
|
+
trail.push({
|
|
2241
|
+
state: step.snapshot.value,
|
|
2242
|
+
resolvedRequest: {
|
|
2243
|
+
kind: "userInput",
|
|
2244
|
+
src: invoke.src,
|
|
2245
|
+
id: invoke.id
|
|
2246
|
+
}
|
|
2247
|
+
});
|
|
2248
|
+
continue;
|
|
2249
|
+
}
|
|
2250
|
+
return {
|
|
2251
|
+
status: "idle",
|
|
2252
|
+
snapshot: step.snapshot,
|
|
2253
|
+
trail
|
|
2254
|
+
};
|
|
2255
|
+
}
|
|
2256
|
+
return {
|
|
2257
|
+
status: "exhausted",
|
|
2258
|
+
snapshot: step.snapshot,
|
|
2259
|
+
trail
|
|
2260
|
+
};
|
|
2261
|
+
}
|
|
2262
|
+
function mapValues(obj, fn) {
|
|
2263
|
+
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
|
|
2264
|
+
}
|
|
2265
|
+
function scriptDryError(kind, src, id, request) {
|
|
2266
|
+
const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
|
|
2267
|
+
return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add a '${kind}' entry for '${src}' to the script.${events}`);
|
|
2268
|
+
}
|
|
2269
|
+
async function explore(machine, options, stopWhen) {
|
|
2270
|
+
const maxDepth = options.maxDepth ?? 8;
|
|
2271
|
+
const maxPaths = options.maxPaths ?? 200;
|
|
2272
|
+
const textOutputs = options.textOutputs ?? {};
|
|
2273
|
+
const reachedStates = /* @__PURE__ */ new Set();
|
|
2274
|
+
const reachedValues = [];
|
|
2275
|
+
const terminals = [];
|
|
2276
|
+
const unexplored = [];
|
|
2277
|
+
let prunedByGuard = 0;
|
|
2278
|
+
let pathsExplored = 0;
|
|
2279
|
+
let hitPathCap = false;
|
|
2280
|
+
let witness;
|
|
2281
|
+
const recordState = (snapshot) => {
|
|
2282
|
+
const key = JSON.stringify(snapshot.value);
|
|
2283
|
+
if (!reachedStates.has(key)) {
|
|
2284
|
+
reachedStates.add(key);
|
|
2285
|
+
reachedValues.push(snapshot.value);
|
|
2286
|
+
}
|
|
2287
|
+
};
|
|
2288
|
+
const initial = initialAgentStep(machine, options.input);
|
|
2289
|
+
recordState(initial.snapshot);
|
|
2290
|
+
if (stopWhen?.(initial.snapshot)) witness = [];
|
|
2291
|
+
const advance = (step) => {
|
|
2292
|
+
let current = step;
|
|
2293
|
+
for (let i = 0; i < 1e3; i++) {
|
|
2294
|
+
if (current.done) return { step: current };
|
|
2295
|
+
const request = current.requests[0];
|
|
2296
|
+
if (request && request.kind === "text") {
|
|
2297
|
+
if (!(request.src in textOutputs)) return {
|
|
2298
|
+
step: current,
|
|
2299
|
+
blockedSrc: request.src
|
|
2300
|
+
};
|
|
2301
|
+
current = resolveAgentStep(machine, current, request, textOutputs[request.src]);
|
|
2302
|
+
recordState(current.snapshot);
|
|
2303
|
+
continue;
|
|
2304
|
+
}
|
|
2305
|
+
if (request && (request.kind === "decision" || request.kind === "plan")) return { step: current };
|
|
2306
|
+
const [invoke] = pendingInvokes(current);
|
|
2307
|
+
if (invoke) {
|
|
2308
|
+
if (!(invoke.src in textOutputs)) return {
|
|
2309
|
+
step: current,
|
|
2310
|
+
blockedSrc: invoke.src
|
|
2311
|
+
};
|
|
2312
|
+
current = resolveAgentStep(machine, current, invoke.id, textOutputs[invoke.src]);
|
|
2313
|
+
recordState(current.snapshot);
|
|
2314
|
+
continue;
|
|
2315
|
+
}
|
|
2316
|
+
return { step: current };
|
|
2317
|
+
}
|
|
2318
|
+
return { step: current };
|
|
2319
|
+
};
|
|
2320
|
+
const visit = async (step, path, depth) => {
|
|
2321
|
+
if (witness !== void 0) return;
|
|
2322
|
+
if (pathsExplored >= maxPaths) {
|
|
2323
|
+
hitPathCap = true;
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
const { step: settled, blockedSrc } = advance(step);
|
|
2327
|
+
if (stopWhen?.(settled.snapshot)) {
|
|
2328
|
+
witness = path;
|
|
2329
|
+
return;
|
|
2330
|
+
}
|
|
2331
|
+
if (blockedSrc) {
|
|
2332
|
+
pathsExplored++;
|
|
2333
|
+
terminals.push({
|
|
2334
|
+
status: "needs-output",
|
|
2335
|
+
path,
|
|
2336
|
+
state: settled.snapshot.value,
|
|
2337
|
+
missingSrc: blockedSrc
|
|
2338
|
+
});
|
|
2339
|
+
unexplored.push(`needs-output: no canned output for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
|
|
2340
|
+
return;
|
|
2341
|
+
}
|
|
2342
|
+
if (settled.done) {
|
|
2343
|
+
pathsExplored++;
|
|
2344
|
+
terminals.push({
|
|
2345
|
+
status: "done",
|
|
2346
|
+
path,
|
|
2347
|
+
state: settled.snapshot.value
|
|
2348
|
+
});
|
|
2349
|
+
return;
|
|
2350
|
+
}
|
|
2351
|
+
const request = settled.requests[0];
|
|
2352
|
+
const isPlan = request?.kind === "plan";
|
|
2353
|
+
const branchEvents = request?.kind === "decision" || request?.kind === "plan" ? request.events.map((descriptor) => ({ type: descriptor.type })) : getAcceptedEvents(settled.snapshot).map((descriptor) => ({ type: descriptor.type }));
|
|
2354
|
+
if (branchEvents.length === 0) {
|
|
2355
|
+
pathsExplored++;
|
|
2356
|
+
terminals.push({
|
|
2357
|
+
status: "idle",
|
|
2358
|
+
path,
|
|
2359
|
+
state: settled.snapshot.value
|
|
2360
|
+
});
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
if (depth >= maxDepth) {
|
|
2364
|
+
pathsExplored++;
|
|
2365
|
+
terminals.push({
|
|
2366
|
+
status: "max-depth",
|
|
2367
|
+
path,
|
|
2368
|
+
state: settled.snapshot.value
|
|
2369
|
+
});
|
|
2370
|
+
unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
|
|
2371
|
+
return;
|
|
2372
|
+
}
|
|
2373
|
+
for (const event of branchEvents) {
|
|
2374
|
+
if (witness !== void 0 || pathsExplored >= maxPaths) {
|
|
2375
|
+
if (pathsExplored >= maxPaths) hitPathCap = true;
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
if (!(isPlan && event.type === "agent.plan.done") && !settled.snapshot.can(event)) {
|
|
2379
|
+
prunedByGuard++;
|
|
2380
|
+
continue;
|
|
2381
|
+
}
|
|
2382
|
+
const next = isPlan ? await resolveAgentRequests(machine, settled, { decide: async () => ({ event }) }) : transitionAgentStep(machine, settled, event);
|
|
2383
|
+
recordState(next.snapshot);
|
|
2384
|
+
await visit(next, [...path, event], depth + 1);
|
|
2385
|
+
}
|
|
2386
|
+
};
|
|
2387
|
+
if (witness === void 0) await visit(initial, [], 0);
|
|
2388
|
+
return {
|
|
2389
|
+
report: {
|
|
2390
|
+
reachedStates: reachedValues,
|
|
2391
|
+
terminals,
|
|
2392
|
+
prunedByGuard,
|
|
2393
|
+
unexplored,
|
|
2394
|
+
pathsExplored,
|
|
2395
|
+
hitPathCap
|
|
2396
|
+
},
|
|
2397
|
+
witness
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* Enumerates a machine's decision and external-event branches to a bounded
|
|
2402
|
+
* depth, model-free, and reports which states are reached and how each path
|
|
2403
|
+
* terminates. At each decision request it forks one branch per candidate event
|
|
2404
|
+
* (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
|
|
2405
|
+
* an idle wait it forks per externally-accepted event. A `agent.plan` request
|
|
2406
|
+
* forks the same way — one branch per candidate, including the reserved
|
|
2407
|
+
* `agent.plan.done` move — advancing each branch through the real plan protocol
|
|
2408
|
+
* (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
|
|
2409
|
+
* are resolved from `textOutputs` (a by-src canned-output map) — a missing src
|
|
2410
|
+
* halts that branch with a `needs-output` terminal rather than throwing.
|
|
2411
|
+
*
|
|
2412
|
+
* Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
|
|
2413
|
+
* 200, reported via `hitPathCap`).
|
|
2414
|
+
*
|
|
2415
|
+
* @example
|
|
2416
|
+
* ```ts
|
|
2417
|
+
* const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
|
|
2418
|
+
* // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
|
|
2419
|
+
* ```
|
|
2420
|
+
*/
|
|
2421
|
+
async function explorePaths(machine, options = {}) {
|
|
2422
|
+
return (await explore(machine, options)).report;
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* Answers "can the machine reach `statePath`?" by exploring its branches (a
|
|
2426
|
+
* thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
|
|
2427
|
+
* with the event sequence that reaches it, or `{ canReach: false }`.
|
|
2428
|
+
*
|
|
2429
|
+
* @example
|
|
2430
|
+
* ```ts
|
|
2431
|
+
* const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
|
|
2432
|
+
* // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
|
|
2433
|
+
* ```
|
|
2434
|
+
*/
|
|
2435
|
+
async function canReach(machine, statePath, options = {}) {
|
|
2436
|
+
const { witness } = await explore(machine, options, (snapshot) => {
|
|
2437
|
+
try {
|
|
2438
|
+
return snapshot.matches(statePath);
|
|
2439
|
+
} catch {
|
|
2440
|
+
return false;
|
|
2441
|
+
}
|
|
2442
|
+
});
|
|
2443
|
+
return witness !== void 0 ? {
|
|
2444
|
+
canReach: true,
|
|
2445
|
+
witness
|
|
2446
|
+
} : { canReach: false };
|
|
2447
|
+
}
|
|
2448
|
+
//#endregion
|
|
2449
|
+
export { createAgentSchemas as _, AgentIdleError as a, messagesSchema as b, inspectTransitions as c, executeAgentRequest as d, getAgentRequests as f, transitionAgentStep as g, resolveAgentStep as h, simulateAgent as i, runAgent as l, resolveAgentRequests as m, explorePaths as n, IllegalResumeEventError as o, initialAgentStep as p, lintAgentMachine as r, SnapshotVersionMismatchError as s, canReach as t, runAgentToCompletion as u, setupAgent as v, appendMessages as y };
|