@statelyai/agent 2.0.0-alpha.24 → 2.0.0-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/ai-sdk.cjs +30 -34
  2. package/dist/ai-sdk.d.cts +27 -31
  3. package/dist/ai-sdk.d.mts +27 -31
  4. package/dist/ai-sdk.mjs +27 -31
  5. package/dist/decision-CM9CYZ6t.cjs +519 -0
  6. package/dist/decision-DzSv1NpD.mjs +453 -0
  7. package/dist/event-log-store-Ba2fsc4E.mjs +576 -0
  8. package/dist/event-log-store-DQmImLYk.cjs +702 -0
  9. package/dist/event-log-store-DvOcs10J.d.cts +338 -0
  10. package/dist/event-log-store-DxyVgnas.d.mts +338 -0
  11. package/dist/index.cjs +429 -4272
  12. package/dist/index.d.cts +104 -1005
  13. package/dist/index.d.mts +104 -1005
  14. package/dist/index.mjs +389 -4202
  15. package/dist/log.cjs +392 -0
  16. package/dist/log.d.cts +32 -0
  17. package/dist/log.d.mts +32 -0
  18. package/dist/log.mjs +371 -0
  19. package/dist/machines.cjs +27 -16
  20. package/dist/machines.d.cts +1 -1
  21. package/dist/machines.d.mts +1 -1
  22. package/dist/machines.mjs +27 -16
  23. package/dist/openai.cjs +16 -15
  24. package/dist/openai.d.cts +9 -9
  25. package/dist/openai.d.mts +9 -9
  26. package/dist/openai.mjs +10 -9
  27. package/dist/otel.d.cts +1 -1
  28. package/dist/otel.d.mts +1 -1
  29. package/dist/{run-agent-Ck7Sa3Tb.d.mts → run-agent-BOfoJg5B.d.cts} +86 -387
  30. package/dist/{run-agent-DWqA8KiI.d.cts → run-agent-CG343kFs.d.mts} +86 -387
  31. package/dist/run-agent-Cb1-LS5P.cjs +1783 -0
  32. package/dist/run-agent-DvDQd4If.mjs +1669 -0
  33. package/dist/{setup-agent-CeO2fARv.mjs → setup-agent-CFW-jPI8.mjs} +9 -20
  34. package/dist/{setup-agent-Dl2VELLi.cjs → setup-agent-CPf7MxnG.cjs} +20 -37
  35. package/dist/testing.cjs +1088 -0
  36. package/dist/testing.d.cts +617 -0
  37. package/dist/testing.d.mts +617 -0
  38. package/dist/testing.mjs +1079 -0
  39. package/dist/{text-logic-DJBK3LbG.d.mts → text-logic-BFEOxyxv.d.cts} +71 -147
  40. package/dist/text-logic-Bl_ZRxDi.mjs +833 -0
  41. package/dist/text-logic-C8xyr6Ag.cjs +1091 -0
  42. package/dist/{text-logic-C7bSnH_B.d.cts → text-logic-hZSiRUo1.d.mts} +71 -147
  43. package/dist/{types-CjHk5OdH.d.cts → types-B1Qs2q3q.d.cts} +2 -1
  44. package/dist/{types-DWA6X9R-.d.mts → types-tA3SdczG.d.mts} +2 -1
  45. package/dist/usage-BdEjFuIi.mjs +5 -0
  46. package/dist/usage-efOQPdf_.cjs +10 -0
  47. package/dist/utils-C2DPqomn.d.mts +109 -0
  48. package/dist/utils-ceStNCOh.d.cts +109 -0
  49. package/package.json +26 -5
  50. package/readme.md +5 -3
  51. package/skills/generate-machine/SKILL.md +4 -6
  52. package/dist/decision-BBZ2jMO1.mjs +0 -1490
  53. package/dist/decision-Cv6SfNWl.cjs +0 -1856
@@ -1,1490 +0,0 @@
1
- import { createAsyncLogic, getNextTransitions } from "xstate";
2
- //#region src/errors.ts
3
- /**
4
- * Base class for every error this package throws. Carries a stable, kebab-case
5
- * `code` so hosts can branch on the failure without `instanceof` (useful across
6
- * bundle/realm boundaries and after serialization).
7
- *
8
- * @example
9
- * ```ts
10
- * catch (error) {
11
- * if (error instanceof AgentError && error.code === 'agent-idle') { ... }
12
- * }
13
- * ```
14
- */
15
- var AgentError = class extends Error {
16
- code;
17
- constructor(code, message, options) {
18
- super(message, options);
19
- this.name = "AgentError";
20
- this.code = code;
21
- }
22
- };
23
- /**
24
- * A model call ran out of output tokens before it produced anything usable.
25
- * Core never throws this: it is the adapter's signal that a `'length'` finish
26
- * reason left nothing to return — a structured request whose envelope never
27
- * closed, say. A text request that WAS cut off still returns its text, with
28
- * `finishReason: 'length'`.
29
- *
30
- * The code is `'truncated'`, so an invoke's `onError` can branch on it without
31
- * `instanceof`:
32
- *
33
- * @example
34
- * ```ts
35
- * onError: [
36
- * { guard: ({ event }) => event.error.code === 'truncated', target: 'retryShorter' },
37
- * { target: 'failed' },
38
- * ]
39
- * ```
40
- */
41
- var AgentTruncatedError = class extends AgentError {
42
- /** The request that was cut off — `AgentTextRequest.name`. */
43
- requestName;
44
- /** The durable invoke id of the request, when the host knows it. */
45
- requestId;
46
- /** Whatever the model did produce before it hit the limit, if anything. */
47
- partialOutput;
48
- constructor(message, options) {
49
- super("truncated", message, { cause: options.cause });
50
- this.name = "AgentTruncatedError";
51
- this.requestName = options.requestName;
52
- if (options.requestId !== void 0) this.requestId = options.requestId;
53
- if (options.partialOutput !== void 0) this.partialOutput = options.partialOutput;
54
- }
55
- };
56
- //#endregion
57
- //#region src/messages.ts
58
- /** Ordinary machine event emitted after a request returns framework-native messages. */
59
- const AGENT_MESSAGES_EVENT_TYPE = "agent.messages";
60
- /** Runtime schema for the framework-neutral `agent.messages` envelope. */
61
- const agentMessagesEventSchema = { "~standard": {
62
- version: 1,
63
- vendor: "statelyai-agent",
64
- validate(value) {
65
- if (!value || typeof value !== "object") return { issues: [{ message: "Expected an 'agent.messages' payload object" }] };
66
- const event = value;
67
- const issues = [];
68
- if (typeof event.request !== "string") issues.push({
69
- message: "Expected a string",
70
- path: ["request"]
71
- });
72
- if (typeof event.actorId !== "string") issues.push({
73
- message: "Expected a string",
74
- path: ["actorId"]
75
- });
76
- if (!Array.isArray(event.messages)) issues.push({
77
- message: "Expected an array",
78
- path: ["messages"]
79
- });
80
- return issues.length > 0 ? { issues } : { value: event };
81
- }
82
- } };
83
- function appendMessages(options) {
84
- const key = options?.key ?? "messages";
85
- return (({ context, event }) => {
86
- const current = context[key];
87
- const messages = event.messages;
88
- return { context: { [key]: [...Array.isArray(current) ? current : [], ...messages ?? []] } };
89
- });
90
- }
91
- const KNOWN_PART_TYPES = new Set([
92
- "text",
93
- "image",
94
- "file",
95
- "tool-call",
96
- "tool-result"
97
- ]);
98
- const USER_PART_TYPES = new Set([
99
- "text",
100
- "image",
101
- "file"
102
- ]);
103
- const ASSISTANT_PART_TYPES = new Set([
104
- "text",
105
- "file",
106
- "tool-call",
107
- "tool-result"
108
- ]);
109
- const TOOL_PART_TYPES = new Set(["tool-result"]);
110
- const TOOL_RESULT_CONTENT_PART_TYPES = new Set(["text", "image"]);
111
- function isKnownPart(part) {
112
- const type = part && typeof part === "object" ? part.type : void 0;
113
- return typeof type === "string" && KNOWN_PART_TYPES.has(type);
114
- }
115
- function requireString(part, type, field) {
116
- return typeof part[field] === "string" ? void 0 : `${type} part requires a string "${field}"`;
117
- }
118
- function isMediaData(value) {
119
- return typeof value === "string" || value instanceof Uint8Array || value instanceof ArrayBuffer || value instanceof URL;
120
- }
121
- function requireMediaData(part, type, field) {
122
- return isMediaData(part[field]) ? void 0 : `${type} part requires "${field}" to be a string, Uint8Array, ArrayBuffer, or URL`;
123
- }
124
- const TOOL_RESULT_OUTPUT_TYPES = new Set([
125
- "text",
126
- "json",
127
- "error-text",
128
- "error-json",
129
- "content"
130
- ]);
131
- function validateToolResultOutput(output) {
132
- if (!output || typeof output !== "object" || Array.isArray(output)) return "tool-result part requires an \"output\" object";
133
- const record = output;
134
- const outputType = record.type;
135
- if (typeof outputType !== "string" || !TOOL_RESULT_OUTPUT_TYPES.has(outputType)) return `Unknown tool-result output type: ${JSON.stringify(outputType)}`;
136
- if (outputType === "text" || outputType === "error-text") {
137
- if (typeof record.value !== "string") return `tool-result output of type "${outputType}" requires a string "value"`;
138
- return;
139
- }
140
- if (outputType === "content") {
141
- if (!Array.isArray(record.value)) return "tool-result output of type \"content\" requires an array \"value\"";
142
- for (const contentPart of record.value) {
143
- const error = validatePart(contentPart, TOOL_RESULT_CONTENT_PART_TYPES, "tool-result output content");
144
- if (error) return error;
145
- }
146
- return;
147
- }
148
- return record.value !== void 0 ? void 0 : `tool-result output of type "${outputType}" requires a "value"`;
149
- }
150
- function validatePart(part, allowedTypes, location) {
151
- if (!isKnownPart(part)) {
152
- const type = part && typeof part === "object" ? part.type : void 0;
153
- return `Unknown message part type: ${JSON.stringify(type)}`;
154
- }
155
- if (!allowedTypes.has(part.type)) return `${location} does not allow "${part.type}" parts`;
156
- const record = part;
157
- switch (record.type) {
158
- case "text": return requireString(record, "text", "text");
159
- case "image": return requireMediaData(record, "image", "image");
160
- case "file": return requireMediaData(record, "file", "data") ?? requireString(record, "file", "mediaType");
161
- case "tool-call": return requireString(record, "tool-call", "toolCallId") ?? requireString(record, "tool-call", "toolName") ?? ("input" in record ? void 0 : "tool-call part requires an \"input\" value");
162
- case "tool-result": return requireString(record, "tool-result", "toolCallId") ?? requireString(record, "tool-result", "toolName") ?? validateToolResultOutput(record.output);
163
- default: return;
164
- }
165
- }
166
- function validatePartsArray(content, allowedTypes, location) {
167
- if (!Array.isArray(content)) return "Expected content to be a string or an array of parts";
168
- for (const part of content) {
169
- const error = validatePart(part, allowedTypes, location);
170
- if (error) return error;
171
- }
172
- }
173
- /**
174
- * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
175
- * checks that every message has a known `role` (`system`/`user`/`assistant`/
176
- * `tool`) and that `content` is either a string (where the role allows it) or
177
- * an array of role-appropriate parts whose required fields and media payloads
178
- * have the right runtime types (extra fields are allowed). Use it directly as
179
- * a context schema's `messages` field when authoring with `createAgentSchemas`
180
- * or `fromConfig`. A zod object cannot nest a Standard Schema, so in a zod
181
- * context schema write `z.custom<AgentMessage[]>(isAgentMessages)`, which runs
182
- * this same validator (see {@link isAgentMessages}).
183
- */
184
- const messagesSchema = { "~standard": {
185
- version: 1,
186
- vendor: "statelyai-agent",
187
- validate(value) {
188
- if (!Array.isArray(value)) return { issues: [{ message: "Expected an array of agent messages" }] };
189
- for (const message of value) {
190
- if (!message || typeof message !== "object") return { issues: [{ message: "Expected an array of agent messages" }] };
191
- const role = message.role;
192
- const content = message.content;
193
- if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") return { issues: [{ message: `Unknown message role: ${JSON.stringify(role)}` }] };
194
- if (role === "system") {
195
- if (typeof content !== "string") return { issues: [{ message: "system message content must be a string" }] };
196
- continue;
197
- }
198
- if (role === "tool") {
199
- const error = validatePartsArray(content, TOOL_PART_TYPES, "tool message content");
200
- if (error) return { issues: [{ message: error }] };
201
- continue;
202
- }
203
- if (typeof content === "string") continue;
204
- const error = validatePartsArray(content, role === "user" ? USER_PART_TYPES : ASSISTANT_PART_TYPES, `${role} message content`);
205
- if (error) return { issues: [{ message: error }] };
206
- }
207
- return { value };
208
- }
209
- } };
210
- /**
211
- * Type guard over {@link messagesSchema}: `true` when `value` is a valid
212
- * `AgentMessage[]`. The one-liner for zod context schemas:
213
- * `messages: z.custom<AgentMessage[]>(isAgentMessages)`.
214
- */
215
- function isAgentMessages(value) {
216
- const result = messagesSchema["~standard"].validate(value);
217
- return !(result instanceof Promise) && !("issues" in result && result.issues);
218
- }
219
- //#endregion
220
- //#region src/utils.ts
221
- /** Returns the human-readable text carried by a message, ignoring non-text parts. */
222
- function getMessageText(message) {
223
- if (typeof message.content === "string") return message.content;
224
- const text = [];
225
- for (const part of message.content) {
226
- if (part.type === "text") {
227
- text.push(part.text);
228
- continue;
229
- }
230
- if (part.type !== "tool-result") continue;
231
- if (part.output.type === "text" || part.output.type === "error-text") text.push(part.output.value);
232
- else if (part.output.type === "content") text.push(...part.output.value.flatMap((item) => item.type === "text" ? [item.text] : []));
233
- }
234
- return text.join("\n");
235
- }
236
- /**
237
- * Walks a context value and returns the dot-paths of the first few values that
238
- * would NOT survive a JSON persist/resume round-trip (persist with XState's
239
- * `actor.getPersistedSnapshot()`, resume with `createActor(machine, { snapshot })`):
240
- * `Date`, `Map`, `Set`, `RegExp`, functions, `undefined`, `bigint`, class
241
- * instances (non-plain objects), and circular references. Plain objects,
242
- * arrays, and JSON primitives are walked/allowed. Returns `[]` for a
243
- * fully-JSON-safe value. Cheap and bounded (stops after `limit` findings) —
244
- * intended for a dev-only warning at the moment persistence matters.
245
- */
246
- function findNonSerializableContextPaths(context, limit = 5) {
247
- const paths = [];
248
- const seen = /* @__PURE__ */ new WeakSet();
249
- const walk = (value, path) => {
250
- if (paths.length >= limit) return;
251
- if (value === null) return;
252
- const type = typeof value;
253
- if (type === "string" || type === "number" || type === "boolean") return;
254
- if (type === "undefined" || type === "bigint" || type === "function" || type === "symbol") {
255
- paths.push(`${path} (${type})`);
256
- return;
257
- }
258
- const obj = value;
259
- if (seen.has(obj)) {
260
- paths.push(`${path} (circular)`);
261
- return;
262
- }
263
- if (Array.isArray(value)) {
264
- seen.add(obj);
265
- value.forEach((item, index) => walk(item, `${path}[${index}]`));
266
- seen.delete(obj);
267
- return;
268
- }
269
- const proto = Object.getPrototypeOf(value);
270
- if (proto === Object.prototype || proto === null) {
271
- seen.add(obj);
272
- for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`);
273
- seen.delete(obj);
274
- return;
275
- }
276
- const ctorName = value.constructor?.name ?? "object";
277
- paths.push(`${path} (${ctorName})`);
278
- };
279
- walk(context, "context");
280
- return paths;
281
- }
282
- /**
283
- * A stable, dependency-free structural fingerprint of a machine — a short hex
284
- * `djb2` hash over its **structural** config only: state ids/nesting, transition
285
- * event types and targets, invoke `src`s, `initial`, and any other serializable
286
- * config fields. Function values (context/output builders, prompts, inline
287
- * guards/actions) are excluded entirely, so two machines that differ only in
288
- * their prompts or executors hash identically; adding/removing/retargeting a
289
- * state or transition changes the hash.
290
- *
291
- * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
292
- * detect a structurally-edited machine on resume. It is a change detector, not
293
- * a cryptographic digest — collisions are possible but unlikely for real
294
- * configs. Declare `createMachine({ version })` to pin an explicit version instead.
295
- */
296
- function getMachineStructuralHash(machine) {
297
- return djb2Hex(stableStructuralString(machine.config));
298
- }
299
- /**
300
- * The version a machine is stamped with everywhere: an explicitly declared
301
- * `createMachine({ version })` when present, else its
302
- * {@link getMachineStructuralHash}. Single source of truth so `runAgent`,
303
- * `provideExecutors`/`traceTransitions` trace envelopes agree.
304
- * @internal
305
- */
306
- function resolveMachineVersion(machine) {
307
- return machine.version ?? getMachineStructuralHash(machine);
308
- }
309
- function stableStructuralString(value, seen = /* @__PURE__ */ new WeakSet()) {
310
- if (value === null) return "null";
311
- const type = typeof value;
312
- if (type === "function" || type === "undefined" || type === "symbol") return "";
313
- if (type === "string") return JSON.stringify(value);
314
- if (type === "number" || type === "boolean") return String(value);
315
- if (type === "bigint") return `${value}n`;
316
- const obj = value;
317
- if (seen.has(obj)) return "\"[circular]\"";
318
- seen.add(obj);
319
- let out;
320
- if (Array.isArray(value)) out = `[${value.map((item) => stableStructuralString(item, seen)).join(",")}]`;
321
- else {
322
- const parts = [];
323
- for (const key of Object.keys(obj).sort()) {
324
- const child = obj[key];
325
- const childType = typeof child;
326
- if (childType === "function" || childType === "undefined" || childType === "symbol") continue;
327
- parts.push(`${JSON.stringify(key)}:${stableStructuralString(child, seen)}`);
328
- }
329
- out = `{${parts.join(",")}}`;
330
- }
331
- seen.delete(obj);
332
- return out;
333
- }
334
- /**
335
- * djb2 → unsigned 32-bit → 8-char hex. No dependencies. A change detector, not
336
- * a cryptographic digest.
337
- *
338
- * @internal
339
- */
340
- function djb2Hex(input) {
341
- let hash = 5381;
342
- for (let i = 0; i < input.length; i++) hash = (hash << 5) + hash + input.charCodeAt(i) | 0;
343
- return (hash >>> 0).toString(16).padStart(8, "0");
344
- }
345
- /** Builds a {@link UserMessage} from a string or multimodal content parts. */
346
- function userMessage(content) {
347
- return {
348
- role: "user",
349
- content
350
- };
351
- }
352
- /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
353
- function assistantMessage(content) {
354
- return {
355
- role: "assistant",
356
- content
357
- };
358
- }
359
- /** Builds a {@link SystemMessage}. */
360
- function systemMessage(content) {
361
- return {
362
- role: "system",
363
- content
364
- };
365
- }
366
- /** Builds a {@link ToolMessage} from one or more tool-result parts. */
367
- function toolMessage(content) {
368
- return {
369
- role: "tool",
370
- content
371
- };
372
- }
373
- /**
374
- * Returns the merged `meta` of a snapshot's active state(s) — the typed
375
- * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
376
- *
377
- * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
378
- * state, but parallel/nested machines can have several. This shallow-merges
379
- * every active state's meta into one object and returns `{}` when no active
380
- * state declares meta.
381
- *
382
- * Merge order is fixed and does not depend on XState's internal node order:
383
- * entries are sorted by structural depth (the state node's distance from the
384
- * root, regardless of custom `id` strings), then by state id lexicographically,
385
- * and merged in that order. So a deeper state's key wins over an ancestor's,
386
- * and between equal-depth parallel siblings the later state id alphabetically
387
- * wins.
388
- *
389
- * The return type is recovered from the snapshot's own `getMeta()` type, so a
390
- * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
391
- * output type. Pass an explicit `TMeta` to override when the snapshot is
392
- * untyped (e.g. `AnyMachineSnapshot`).
393
- *
394
- * @example HITL: read the current state's interaction protocol off an idle
395
- * snapshot to render for a human.
396
- * ```ts
397
- * const { interaction } = getStateMeta(result.snapshot);
398
- * ```
399
- */
400
- function getStateMeta(snapshot) {
401
- const nodes = snapshot.nodes;
402
- const depthById = new Map(nodes?.map((node) => [node.id, node.path.length]));
403
- const depth = (id) => depthById.get(id) ?? id.split(".").length;
404
- const entries = Object.entries(snapshot.getMeta()).filter((entry) => entry[1] != null).sort(([a], [b]) => depth(a) - depth(b) || (a < b ? -1 : a > b ? 1 : 0));
405
- return Object.assign({}, ...entries.map(([, meta]) => meta));
406
- }
407
- /**
408
- * Renders a snapshot's state value as one deterministic string, so a log line,
409
- * a progress field, or a test assertion reads the same on every run.
410
- *
411
- * - An atomic state is its own name: `'writing'`.
412
- * - A nested state joins with dots: `{ review: { editing: 'draft' } }` →
413
- * `'review.editing.draft'`.
414
- * - A parallel state brackets its regions, sorted by region name, so key order
415
- * never leaks into the string: `{ p: { left: 'x', right: { a: 'b' } } }` →
416
- * `'p:{left.x,right.a.b}'`.
417
- *
418
- * Prefer this over `String(snapshot.value)`, which renders every non-atomic
419
- * value as `[object Object]`.
420
- *
421
- * @example
422
- * ```ts
423
- * onTransition: (snapshot) => console.log(getStatePath(snapshot));
424
- * ```
425
- */
426
- function getStatePath(snapshot) {
427
- return serializeStateValue(typeof snapshot === "object" && snapshot !== null && "value" in snapshot && ("status" in snapshot || typeof snapshot.matches === "function") ? snapshot.value : snapshot);
428
- }
429
- function serializeStateValue(value) {
430
- if (typeof value === "string") return value;
431
- const entries = Object.entries(value).map(([key, child]) => {
432
- const rendered = serializeStateValue(child);
433
- if (!rendered) return [key, key];
434
- return [key, `${key}${rendered.startsWith("{") ? ":" : "."}${rendered}`];
435
- }).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
436
- if (entries.length === 0) return "";
437
- if (entries.length === 1) return entries[0][1];
438
- return `{${entries.map(([, rendered]) => rendered).join(",")}}`;
439
- }
440
- /**
441
- * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
442
- * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
443
- * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
444
- * can't read directly — see the `ai-sdk` tool pass-through.
445
- */
446
- function isStandardSchema(value) {
447
- return typeof value === "object" && value !== null && "~standard" in value;
448
- }
449
- /**
450
- * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
451
- * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
452
- * `z.toJSONSchema`), awaiting it when the producer is async. Returns
453
- * `undefined` when the schema doesn't expose the extension. Use this to build
454
- * a provider request's `response_format`/tool `parameters` from a schema.
455
- */
456
- async function getJsonSchema(schema) {
457
- const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
458
- if (!jsonSchemaFn) return;
459
- const result = jsonSchemaFn();
460
- return result instanceof Promise ? await result : result;
461
- }
462
- /**
463
- * Synchronous variant of {@link getJsonSchema}, for call sites that can't
464
- * await (building tool/event descriptors inline). An async JSON Schema
465
- * producer is treated as absent (returns `undefined`) — in practice Zod's
466
- * `z.toJSONSchema` resolves synchronously.
467
- */
468
- function getJsonSchemaSync(schema) {
469
- const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
470
- if (!jsonSchemaFn) return;
471
- const result = jsonSchemaFn();
472
- return result instanceof Promise ? void 0 : result;
473
- }
474
- /**
475
- * Validates `value` against a {@link StandardSchemaV1}, synchronously.
476
- * Throws if the schema's `validate` returns a `Promise` (async validation is
477
- * not supported anywhere in this library) or if validation reports issues —
478
- * in which case the thrown `Error.message` joins every issue message with
479
- * `', '`.
480
- */
481
- function validateSchemaSync(schema, value) {
482
- const result = schema["~standard"].validate(value);
483
- if (result instanceof Promise) throw new Error("Async schema validation is not supported.");
484
- if (result.issues) throw new Error(result.issues.map((issue) => issue.message).join(", "));
485
- return result.value;
486
- }
487
- //#endregion
488
- //#region src/internal/registry.ts
489
- /** Non-enumerable hook an optional adapter can attach to a model registry. */
490
- const DEFAULT_AGENT_EXECUTORS = Symbol.for("@statelyai/agent.defaultExecutors");
491
- /**
492
- * Registered execution options, keyed on BOTH the machine object and its root
493
- * `config` object. `config` is shared by reference across `machine.provide(...)`
494
- * (unlike the machine itself), so the `config` key is what lets a machine
495
- * rebound by `runAgent` — or by any host `.provide(...)` — still resolve the
496
- * schemas/actors `setupAgent` registered. Always write through
497
- * {@link setAgentExecutionOptions} and read through
498
- * {@link getAgentExecutionOptions}.
499
- */
500
- const agentExecutionOptions = /* @__PURE__ */ new WeakMap();
501
- /** The root `config` object a machine shares with every `.provide(...)` of itself. */
502
- function machineConfigKey(machine) {
503
- const config = machine?.config;
504
- return config && typeof config === "object" ? config : void 0;
505
- }
506
- /** Registers `options` for `machine` and for every `.provide(...)` of it. */
507
- function setAgentExecutionOptions(machine, options) {
508
- if (!machine || typeof machine !== "object") return;
509
- agentExecutionOptions.set(machine, options);
510
- const config = machineConfigKey(machine);
511
- if (config) agentExecutionOptions.set(config, options);
512
- }
513
- /**
514
- * Reads the options registered for `machine`, falling back to the root `config`
515
- * key so a `.provide(...)`-rebound machine (e.g. the one behind a `runAgent`
516
- * result snapshot) resolves the same pack.
517
- */
518
- function getAgentExecutionOptions(machine) {
519
- if (!machine || typeof machine !== "object") return void 0;
520
- const direct = agentExecutionOptions.get(machine);
521
- if (direct) return direct;
522
- const config = machineConfigKey(machine);
523
- return config ? agentExecutionOptions.get(config) : void 0;
524
- }
525
- /**
526
- * Machine-carried wait-state predicates, keyed on the machine's root `config`
527
- * object. `config` is shared by reference across `machine.provide(...)` (unlike
528
- * the machine object itself), so a predicate registered here travels with the
529
- * machine through `.provide` — which is why it is keyed on `config`, not the
530
- * machine. Set by `setupAgent({ isIdle })` in `createMachine` and by
531
- * `setupAgent.fromConfig` (its `isIdle` option or the config's
532
- * `idleTags`), read by `runAgent` before its structural default.
533
- */
534
- const machineIdlePredicates = /* @__PURE__ */ new WeakMap();
535
- /** Reads the {@link machineIdlePredicates} predicate carried by `machine` (via its root `config`), if any. */
536
- function getMachineIdlePredicate(machine) {
537
- const config = machine.config;
538
- return config ? machineIdlePredicates.get(config) : void 0;
539
- }
540
- const unboundPlaceholderLogics = /* @__PURE__ */ new WeakSet();
541
- /** Text/decision logics created WITH their own executor (withExecutor or the
542
- * factory's second arg) — these are runnable as-is, so runAgent's bind check
543
- * must not reject them as direct-object invoke srcs. */
544
- const executorBoundLogics = /* @__PURE__ */ new WeakSet();
545
- function missingActor(src) {
546
- const logic = createAsyncLogic({ run: async () => {
547
- throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actors: { '${src}': ... } }).`);
548
- } });
549
- unboundPlaceholderLogics.add(logic);
550
- return logic;
551
- }
552
- function isUnboundPlaceholder(logic) {
553
- return !!logic && typeof logic === "object" && unboundPlaceholderLogics.has(logic);
554
- }
555
- function getRegisteredAgentExecutionOptions(machine, options) {
556
- return {
557
- ...getAgentExecutionOptions(machine),
558
- ...options
559
- };
560
- }
561
- //#endregion
562
- //#region src/text-logic.ts
563
- const USER_INPUT_ACTOR = "agent.userInput";
564
- const GENERATE_TEXT_ACTOR = "agent.generateText";
565
- const STREAM_TEXT_ACTOR = "agent.streamText";
566
- const DECIDE_ACTOR = "agent.decide";
567
- /**
568
- * Splits a portable `"provider/model-id"` model ref (the convention JSON
569
- * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
570
- * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
571
- * The standard building block for a host's `resolveModel`:
572
- *
573
- * @example
574
- * ```ts
575
- * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
576
- * ```
577
- */
578
- function parseModelRef(modelRef) {
579
- const slash = modelRef.indexOf("/");
580
- return slash === -1 ? {
581
- provider: void 0,
582
- modelId: modelRef
583
- } : {
584
- provider: modelRef.slice(0, slash),
585
- modelId: modelRef.slice(slash + 1)
586
- };
587
- }
588
- const AGENT_FINISH_REASONS = new Set([
589
- "stop",
590
- "length",
591
- "tool-calls",
592
- "content-filter",
593
- "other"
594
- ]);
595
- /**
596
- * Reads a settled call's {@link AgentFinishReason} off a RAW executor result's
597
- * `finishReason` field — the finish-reason sibling of {@link getCallUsage},
598
- * applied by `runAgent` before it puts the reason on the `request.end` trace.
599
- * A provider's `'error'` normalizes to `'other'`; anything else the union does
600
- * not name (an un-normalized provider string, a missing field) returns
601
- * `undefined`.
602
- */
603
- function getCallFinishReason(raw) {
604
- const value = raw?.finishReason;
605
- if (typeof value !== "string") return;
606
- if (value === "error") return "other";
607
- return AGENT_FINISH_REASONS.has(value) ? value : void 0;
608
- }
609
- /** The token fields {@link AgentUsage} aggregates. @internal */
610
- const AGENT_USAGE_TOKEN_FIELDS = [
611
- "inputTokens",
612
- "outputTokens",
613
- "totalTokens",
614
- "reasoningTokens",
615
- "cachedInputTokens"
616
- ];
617
- /**
618
- * Reads a settled call's per-call {@link AgentCallUsage} off a RAW executor
619
- * result's `usage` field, keeping only finite numbers — the same normalization
620
- * `runAgent` applies before it delivers `'@agent.usage'`. Returns `undefined`
621
- * when the result reports no usage at all. Works for our `{ output, usage }`
622
- * envelope, for a raw Vercel AI SDK result (its `LanguageModelUsage` carries
623
- * the same flat field names), and for any custom executor that follows the
624
- * shape.
625
- *
626
- * The seam for the step-loop path, where the host holds the raw result itself:
627
- *
628
- * ```ts
629
- * const { output, raw } = await executeAgentRequest(effect, executors);
630
- * const usage = getCallUsage(raw);
631
- * if (usage) append({ type: AGENT_USAGE_EVENT_TYPE, usage }); // journal + transition, like any event
632
- * append(effect.toDoneEvent(output));
633
- * ```
634
- *
635
- * See "Token usage on this path" in docs/steps.md for the full loop.
636
- */
637
- function getCallUsage(raw) {
638
- const usage = raw?.usage;
639
- if (!usage || typeof usage !== "object") return;
640
- let out;
641
- for (const field of AGENT_USAGE_TOKEN_FIELDS) {
642
- const value = usage[field];
643
- if (typeof value === "number" && Number.isFinite(value)) (out ??= {})[field] = value;
644
- }
645
- return out;
646
- }
647
- function textRequestSourceIssue(request) {
648
- const hasPrompt = typeof request.prompt === "string" && request.prompt.length > 0;
649
- const hasMessages = Array.isArray(request.messages) && request.messages.length > 0;
650
- const label = request.name ? ` '${request.name}'` : "";
651
- if (hasPrompt && hasMessages) return `Agent text request${label} has both a non-empty \`prompt\` and \`messages\` — provide exactly one so the model has a single input source.`;
652
- if (!hasPrompt && !hasMessages) return `Agent text request${label} has neither a non-empty \`prompt\` nor \`messages\` — provide at least one so the model has something to respond to.`;
653
- }
654
- const agentTextInputSchema = { "~standard": {
655
- version: 1,
656
- vendor: "statelyai-agent",
657
- validate(value) {
658
- if (!value || typeof value !== "object") return { issues: [{ message: "Expected agent text input object" }] };
659
- const request = value;
660
- if (typeof request.model !== "string") return { issues: [{ message: "Expected agent text input with a string `model`" }] };
661
- const issue = textRequestSourceIssue(request);
662
- if (issue) return { issues: [{ message: issue }] };
663
- return { value: request };
664
- }
665
- } };
666
- const passthroughSchema = { "~standard": {
667
- version: 1,
668
- vendor: "statelyai-agent",
669
- validate(value) {
670
- return { value };
671
- }
672
- } };
673
- const unknownOutputSchema = passthroughSchema;
674
- const stringOutputSchema = { "~standard": {
675
- version: 1,
676
- vendor: "statelyai-agent",
677
- validate(value) {
678
- return typeof value === "string" ? { value } : { issues: [{ message: "Expected string output" }] };
679
- }
680
- } };
681
- const noInputSchema = passthroughSchema;
682
- function createBuiltinTextActor(src, mode, outputSchema) {
683
- const logic = createAsyncLogic({ run: async () => {
684
- throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actors: { '${src}': ... } }) or execute the returned agent request with executeAgentRequest(...).`);
685
- } });
686
- return Object.assign(logic, {
687
- kind: "statelyai.textLogic",
688
- mode,
689
- schemas: {
690
- input: agentTextInputSchema,
691
- output: outputSchema
692
- },
693
- request(input) {
694
- return validateSchemaSync(agentTextInputSchema, input);
695
- },
696
- async execute(input, executors) {
697
- const { output } = await executeAgentTextRequest(mode, src, validateSchemaSync(agentTextInputSchema, input), executors);
698
- return validateSchemaSync(outputSchema, output);
699
- },
700
- withExecutor(execute) {
701
- return createTextLogic({
702
- mode,
703
- schemas: {
704
- input: agentTextInputSchema,
705
- output: outputSchema
706
- },
707
- name: ({ input }) => input.name,
708
- model: ({ input }) => input.model,
709
- system: ({ input }) => input.system,
710
- prompt: ({ input }) => input.prompt,
711
- messages: ({ input }) => input.messages,
712
- tools: ({ input }) => input.tools,
713
- toolChoice: ({ input }) => input.toolChoice,
714
- includeReasoning: ({ input }) => input.includeReasoning,
715
- temperature: ({ input }) => input.temperature,
716
- maxOutputTokens: ({ input }) => input.maxOutputTokens,
717
- topP: ({ input }) => input.topP,
718
- topK: ({ input }) => input.topK,
719
- seed: ({ input }) => input.seed,
720
- stopSequences: ({ input }) => input.stopSequences,
721
- maxSteps: ({ input }) => input.maxSteps,
722
- metadata: ({ input }) => input.metadata
723
- }, execute);
724
- }
725
- });
726
- }
727
- /** The unbound `agent.generateText`/`agent.streamText` builtins registered by setupAgent. @internal */
728
- const builtinTextActors = {
729
- [GENERATE_TEXT_ACTOR]: createBuiltinTextActor(GENERATE_TEXT_ACTOR, "generate", unknownOutputSchema),
730
- [STREAM_TEXT_ACTOR]: createBuiltinTextActor(STREAM_TEXT_ACTOR, "stream", stringOutputSchema)
731
- };
732
- /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). Output is `string` — what the human typed. @internal */
733
- const userInputActor = createAsyncLogic({ run: async () => {
734
- throw new Error(`'${USER_INPUT_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actors: { '${USER_INPUT_ACTOR}': ... } }).`);
735
- } });
736
- unboundPlaceholderLogics.add(userInputActor);
737
- /**
738
- * Validates a raw model/executor output against `schema`, returning the
739
- * parsed value. Thin wrapper over {@link validateSchemaSync} for parsing a
740
- * text request's structured output outside of `TextLogic.execute`/
741
- * `executeAgentRequest` (e.g. a custom host loop).
742
- */
743
- function parseOutput(schema, output) {
744
- return validateSchemaSync(schema, output);
745
- }
746
- /** Resolves a `ResolveTextLogicValue` (calls it if it's a function, else returns it as-is). @internal */
747
- function resolveTextLogicValue(value, args) {
748
- return typeof value === "function" ? value(args) : value;
749
- }
750
- /**
751
- * Creates reusable, standalone {@link TextLogic}: an actor that, when run,
752
- * resolves typed input to typed output via a model call. Register the
753
- * result under `actors:` and invoke it by name (equivalent to what
754
- * `setupAgent({ requests })` builds internally for each request entry). Pass
755
- * `execute` here, or bind it later with `.withExecutor(...)`, a runtime
756
- * adapter's `machine.provide(...)`, or `runAgent`'s `generateText`/
757
- * `streamText` options.
758
- *
759
- * @example
760
- * ```ts
761
- * export const tellJoke = createTextLogic({
762
- * mode: 'stream',
763
- * schemas: { input: z.object({ topic: z.string() }), output: z.string() },
764
- * model: 'openai/gpt-5.4-mini',
765
- * system: 'You tell short, punchy jokes.',
766
- * prompt: ({ input }) => `Tell a joke about ${input.topic}.`,
767
- * });
768
- * ```
769
- */
770
- function createTextLogic(config, execute) {
771
- const schemas = {
772
- input: config.schemas?.input ?? noInputSchema,
773
- output: config.schemas?.output ?? stringOutputSchema
774
- };
775
- const request = (input) => {
776
- const parsedInput = validateSchemaSync(schemas.input, input);
777
- const args = { input: parsedInput };
778
- const name = resolveTextLogicValue(config.name, args);
779
- const prompt = resolveTextLogicValue(config.prompt, args);
780
- const messages = resolveTextLogicValue(config.messages, args);
781
- const sourceIssue = textRequestSourceIssue({
782
- name,
783
- prompt,
784
- messages
785
- });
786
- if (sourceIssue) throw new Error(sourceIssue);
787
- return {
788
- name,
789
- input: parsedInput,
790
- model: resolveTextLogicValue(config.model, args),
791
- system: resolveTextLogicValue(config.system, args),
792
- prompt,
793
- messages,
794
- tools: resolveTextLogicValue(config.tools, args),
795
- toolChoice: resolveTextLogicValue(config.toolChoice, args),
796
- outputSchema: schemas.output,
797
- includeReasoning: resolveTextLogicValue(config.includeReasoning, args),
798
- temperature: resolveTextLogicValue(config.temperature, args),
799
- maxOutputTokens: resolveTextLogicValue(config.maxOutputTokens, args),
800
- topP: resolveTextLogicValue(config.topP, args),
801
- topK: resolveTextLogicValue(config.topK, args),
802
- seed: resolveTextLogicValue(config.seed, args),
803
- stopSequences: resolveTextLogicValue(config.stopSequences, args),
804
- maxSteps: resolveTextLogicValue(config.maxSteps, args),
805
- metadata: resolveTextLogicValue(config.metadata, args)
806
- };
807
- };
808
- const logic = createAsyncLogic({ run: async ({ input, signal, system, self }, enq) => {
809
- const resolvedRequest = request(input);
810
- if (!execute) throw new Error("Text logic has no host execution. Pass an executor as the second argument to createTextLogic(...), provide a runtime adapter, or bind it through runAgent/provideExecutors, or execute the XState effect in your host.");
811
- const result = await execute({
812
- input,
813
- request: resolvedRequest,
814
- signal,
815
- system,
816
- self,
817
- emit: enq.emit
818
- });
819
- const selfId = self?.id;
820
- const output = await normalizeGeneratorResult(result, typeof selfId === "string" ? selfId : "text logic", { request: resolvedRequest });
821
- return validateSchemaSync(schemas.output, output);
822
- } });
823
- const textLogic = Object.assign(logic, {
824
- kind: "statelyai.textLogic",
825
- mode: config.mode ?? "generate",
826
- schemas,
827
- request,
828
- async execute(input, executors) {
829
- const { output } = await executeAgentTextRequest(config.mode ?? "generate", "textLogic", request(input), executors);
830
- return validateSchemaSync(schemas.output, output);
831
- },
832
- withExecutor(nextExecute) {
833
- return createTextLogic(config, nextExecute);
834
- }
835
- });
836
- if (execute) executorBoundLogics.add(textLogic);
837
- return textLogic;
838
- }
839
- /**
840
- * Binds a child machine's {@link TextLogic} to a raw
841
- * {@link AgentRequestExecutor} (the `generateText`/`streamText` shape hosts
842
- * implement). Encapsulates the `withExecutor` idiom child agents repeat:
843
- * default the request's `tools` to `{}`, forward the actor `signal`, call the
844
- * executor, and return its `{ output }` envelope. Use this to share ONE
845
- * executor across a parent and its nested children.
846
- *
847
- * @example
848
- * ```ts
849
- * childMachine.provide({
850
- * actors: {
851
- * researchTopic: bindRequestExecutor(setup.requests.researchTopic, generateText),
852
- * },
853
- * });
854
- * ```
855
- */
856
- function bindRequestExecutor(logic, executor, info) {
857
- return logic.withExecutor(async ({ request, signal }) => {
858
- const { output } = await executor({
859
- ...request,
860
- tools: request.tools ?? {}
861
- }, {
862
- signal,
863
- onChunk: info?.onChunk
864
- });
865
- return { output };
866
- });
867
- }
868
- /** Type guard: true for any actor logic built by createTextLogic (checks the `kind` marker). @internal */
869
- function isTextLogic(value) {
870
- return !!value && typeof value === "object" && value.kind === "statelyai.textLogic" && typeof value.request === "function";
871
- }
872
- /**
873
- * Classifies a text request's output schema as `'structured'` (its JSON
874
- * Schema is `type: 'object'`, `type: 'array'`, or a top-level union/
875
- * composition — `anyOf`/`oneOf`/`allOf`, which a bare `z.union`/
876
- * `z.discriminatedUnion` emits with no top-level `type`) or `'text'`
877
- * (anything else, including no schema). Reads the schema's
878
- * `~standard.jsonSchema.input()` extension — schemas without it are treated
879
- * as `'text'`.
880
- */
881
- function getAgentOutputMode(schema) {
882
- const jsonSchema = getJsonSchemaSync(schema);
883
- if (!jsonSchema) return "text";
884
- if (jsonSchema.type === "object" || jsonSchema.type === "array") return "structured";
885
- if (jsonSchema.type === void 0 && ("anyOf" in jsonSchema || "oneOf" in jsonSchema || "allOf" in jsonSchema)) return "structured";
886
- return "text";
887
- }
888
- /**
889
- * Builds the uniform structured-output envelope schema every structured request
890
- * is sent to the provider as: a root object `{ result: <inner> }`, plus — when
891
- * `options.reasoning` is `true` — an optional string `reasoning` property listed
892
- * BEFORE `result` (property order nudges the model to reason first). This is THE
893
- * wire contract for structured output: a root object is universally accepted as
894
- * a provider response schema, unlike a bare union/array root that many providers
895
- * reject.
896
- *
897
- * The returned {@link StandardSchemaV1} validates the `{ reasoning?, result }`
898
- * envelope (unwrapping `result` through the original schema, capturing a string
899
- * `reasoning` when present) and exposes the enveloped JSON Schema. Adapters read
900
- * `.result` off the provider output before the machine validates it — so this is
901
- * transparent: user-facing output types stay the declared (un-enveloped) schema,
902
- * and `reasoning` is surfaced only on the raw executor result, never in machine
903
- * context/output.
904
- */
905
- function buildEnvelopeSchema(inner, options = {}) {
906
- const includeReasoning = options.reasoning === true;
907
- const buildJson = (innerJson) => ({
908
- type: "object",
909
- properties: {
910
- ...includeReasoning ? { reasoning: { type: "string" } } : {},
911
- result: innerJson ?? {}
912
- },
913
- required: ["result"],
914
- additionalProperties: false
915
- });
916
- return { "~standard": {
917
- version: 1,
918
- vendor: "statelyai-agent",
919
- validate(value) {
920
- if (!value || typeof value !== "object" || !("result" in value)) return { issues: [{ message: "Expected a { result } envelope object" }] };
921
- const innerResult = inner["~standard"].validate(value.result);
922
- if (innerResult instanceof Promise) throw new Error("Async schema validation is not supported.");
923
- if (innerResult.issues) return innerResult;
924
- const envelope = { result: innerResult.value };
925
- const reasoning = value.reasoning;
926
- if (typeof reasoning === "string") envelope.reasoning = reasoning;
927
- return { value: envelope };
928
- },
929
- jsonSchema: { input: () => {
930
- const innerJson = inner["~standard"].jsonSchema?.input?.();
931
- return innerJson instanceof Promise ? innerJson.then(buildJson) : buildJson(innerJson);
932
- } }
933
- } };
934
- }
935
- /**
936
- * Validates a raw provider value against the structured-output envelope for
937
- * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
938
- * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
939
- * Pair with {@link buildEnvelopeSchema} (which produced the schema the
940
- * provider was asked to satisfy).
941
- */
942
- function parseStructuredEnvelope(request, value) {
943
- if (!request.outputSchema) throw new Error("parseStructuredEnvelope: the request declares no outputSchema.");
944
- return validateSchemaSync(buildEnvelopeSchema(request.outputSchema, { reasoning: request.includeReasoning }), value);
945
- }
946
- /**
947
- * Merges request-declared and call-site `tools`, dispatches to the
948
- * `mode`-appropriate executor (`generateText`/`streamText`), and normalizes
949
- * the raw result via {@link normalizeGeneratorResult}. Shared by
950
- * `TextLogic.execute`, `executeAgentRequest`, and the `agent.generateText`/
951
- * `agent.streamText` builtins. Throws if no executor is registered for
952
- * `mode`.
953
- *
954
- * @internal
955
- */
956
- async function executeAgentTextRequest(mode, id, input, executors, tools = {}, info) {
957
- const request = {
958
- ...input,
959
- name: input.name ?? id,
960
- tools: {
961
- ...input.tools,
962
- ...tools
963
- }
964
- };
965
- const sourceIssue = textRequestSourceIssue(request);
966
- if (sourceIssue) throw new Error(sourceIssue);
967
- const executor = mode === "stream" ? executors.streamText : executors.generateText;
968
- if (!executor) throw new Error(`No executor provided for ${mode === "stream" ? "stream" : "generate"} request '${id}'.`);
969
- const raw = await executor(request, info);
970
- return {
971
- output: await normalizeGeneratorResult(raw, id, {
972
- request,
973
- onChunk: info?.onChunk
974
- }),
975
- raw
976
- };
977
- }
978
- function hasTextStream(value) {
979
- return "textStream" in value && typeof value.textStream === "object" && !!value.textStream?.[Symbol.asyncIterator];
980
- }
981
- function parseRawAiSdkText(text, request, id) {
982
- if (!request?.outputSchema) return text;
983
- let parsed = text;
984
- try {
985
- parsed = JSON.parse(text);
986
- } catch {}
987
- try {
988
- return parseOutput(request.outputSchema, parsed);
989
- } catch (error) {
990
- throw new Error(`Executor for '${id}' returned a raw AI SDK result whose text could not be parsed against the request's outputSchema. Structured-output requests through raw AI SDK generateText/streamText functions are best-effort — for reliable structured output, use createAiSdkExecutors from '@statelyai/agent/ai-sdk'. Cause: ${error instanceof Error ? error.message : String(error)}`);
991
- }
992
- }
993
- /**
994
- * Unwraps an executor result into the request's final output. Accepts three
995
- * shapes:
996
- * - `{ output }` (the {@link AgentRequestExecutorResult} envelope) — awaits and
997
- * returns `output` (the fast path; unchanged).
998
- * - a raw AI SDK `streamText` result (`{ textStream }` async iterable) — iterates
999
- * `textStream`, forwarding each string chunk to `info.onChunk`, then resolves
1000
- * the final text from `await result.text` if present else the accumulated chunks.
1001
- * - a raw AI SDK `generateText` result (`{ text }` string or promise) — awaits `text`.
1002
- *
1003
- * For the two raw AI SDK shapes, if `info.request?.outputSchema` is set the final
1004
- * text is parsed through {@link parseOutput} (best-effort); a parse failure throws
1005
- * an error recommending `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
1006
- *
1007
- * A value matching none of these is a runtime error naming `id`. This is
1008
- * generator-result unwrapping only — decision results are extracted separately
1009
- * by `resolveDecision`.
1010
- *
1011
- * @internal
1012
- */
1013
- async function normalizeGeneratorResult(result, id = "text request", info) {
1014
- const resolved = await result;
1015
- if (!resolved || typeof resolved !== "object") throw invalidGeneratorResult(id);
1016
- if ("output" in resolved) return await resolved.output;
1017
- if (hasTextStream(resolved)) {
1018
- let accumulated = "";
1019
- for await (const chunk of resolved.textStream) {
1020
- accumulated += chunk;
1021
- info?.onChunk?.(chunk);
1022
- }
1023
- const finalText = "text" in resolved && resolved.text !== void 0 ? await resolved.text : accumulated;
1024
- return parseRawAiSdkText(String(finalText), info?.request, id);
1025
- }
1026
- if ("text" in resolved) {
1027
- const finalText = await resolved.text;
1028
- return parseRawAiSdkText(String(finalText), info?.request, id);
1029
- }
1030
- throw invalidGeneratorResult(id);
1031
- }
1032
- function invalidGeneratorResult(id) {
1033
- return /* @__PURE__ */ new Error(`Executor for '${id}' returned an invalid result: executors must return { output } (an envelope with the text string or structured object as \`output\`, plus optional passthrough fields). Raw Vercel AI SDK generateText/streamText results ({ text } or { textStream }) are also accepted.`);
1034
- }
1035
- //#endregion
1036
- //#region src/internal/is-record.ts
1037
- /** True for a plain object-like value (arrays excluded). @internal */
1038
- function isRecord(value) {
1039
- return typeof value === "object" && value !== null && !Array.isArray(value);
1040
- }
1041
- //#endregion
1042
- //#region src/events.ts
1043
- /**
1044
- * Thrown by {@link parseAgentEvent} (and {@link eventFromInteraction}) when a
1045
- * wire payload is not a usable event: it is not an object with a string
1046
- * `type`, it names a reserved `@agent.*` type, or its fields fail the schema
1047
- * the machine registered for that type. A host turns it into a 400.
1048
- *
1049
- * Not handling an event is NOT this error — a state machine ignores events it
1050
- * has no transition for, so an event the current state does not handle parses
1051
- * fine and settles the run with `result.ignored` set.
1052
- */
1053
- var AgentInvalidEventPayloadError = class extends AgentError {
1054
- eventType;
1055
- constructor(eventType, detail) {
1056
- super("invalid-event-payload", `Invalid event payload for '${eventType}': ${detail}`);
1057
- this.name = "AgentInvalidEventPayloadError";
1058
- this.eventType = eventType;
1059
- }
1060
- };
1061
- /** Default prefix for the synthetic tool name generated per candidate event (e.g. `send_event_ASK`). Override per-request with {@link AgentEventToolNameResolver}. @internal */
1062
- const EVENT_TOOL_PREFIX = "send_event_";
1063
- function hashString(value) {
1064
- let hash = 5381;
1065
- for (let i = 0; i < value.length; i++) hash = hash * 33 ^ value.charCodeAt(i);
1066
- return (hash >>> 0).toString(36);
1067
- }
1068
- function sanitizeEventToolName(eventType) {
1069
- const base = `${EVENT_TOOL_PREFIX}${eventType.replace(/[^a-zA-Z0-9_-]/g, "_") || "event"}`;
1070
- if (base.length <= 64) return base;
1071
- const hash = hashString(eventType);
1072
- const prefixLength = 64 - hash.length - 1;
1073
- return `${base.slice(0, prefixLength)}_${hash}`;
1074
- }
1075
- function disambiguateEventToolName(toolName, eventType, usedToolNames) {
1076
- if (!usedToolNames.has(toolName)) {
1077
- usedToolNames.add(toolName);
1078
- return toolName;
1079
- }
1080
- const suffix = `_${hashString(eventType)}`;
1081
- const uniqueToolName = `${toolName.slice(0, 64 - suffix.length)}${suffix}`;
1082
- usedToolNames.add(uniqueToolName);
1083
- return uniqueToolName;
1084
- }
1085
- /**
1086
- * True when an event type matches an `allowedEvents` entry: an exact type,
1087
- * `'*'` (every event), or a `'prefix.*'` wildcard matching any deeper
1088
- * segment (`'todo.*'` matches `'todo.add'` and `'todo.list.clear'`, not
1089
- * `'todo'` itself — mirroring xstate's partial wildcard events).
1090
- */
1091
- function matchesEventPattern(eventType, pattern) {
1092
- if (pattern === "*") return true;
1093
- if (pattern.endsWith(".*")) return eventType.startsWith(`${pattern.slice(0, -1)}`);
1094
- return eventType === pattern;
1095
- }
1096
- /**
1097
- * Event types reserved for delivery by the library (`@agent.*` and
1098
- * `agent.messages`). A machine may declare transitions on them,
1099
- * but they are never model-facing: {@link getAcceptedEvents} drops them before
1100
- * any `allowedEvents` matching, so they cannot be offered as a decision
1101
- * candidate (not even under a `'*'` wildcard) and {@link parseAgentEvent}
1102
- * rejects them — a model or a wire message must not be able to forge one.
1103
- * @internal
1104
- */
1105
- const RESERVED_AGENT_EVENT_PREFIX = "@agent.";
1106
- function isReservedAgentEvent(eventType) {
1107
- return eventType.startsWith(RESERVED_AGENT_EVENT_PREFIX) || eventType === "agent.messages";
1108
- }
1109
- /** True when an `allowedEvents` entry is a wildcard pattern rather than a concrete event type. @internal */
1110
- function isEventPattern(entry) {
1111
- return entry === "*" || entry.endsWith(".*");
1112
- }
1113
- /**
1114
- * Parses a wire payload (a request body, a socket frame) into an
1115
- * event typed as the machine's event union, so it can go straight to
1116
- * `runAgent({ event })` / `actor.send(...)` without a cast. Pass the machine
1117
- * itself, or any snapshot of it.
1118
- *
1119
- * It checks exactly what a schema can check: the payload is an object with a
1120
- * string `type`, that type is not one of the library-reserved `@agent.*` types,
1121
- * and — when the machine registered a schema for it — the fields satisfy that
1122
- * schema (defaults filled, transforms applied). Anything else throws
1123
- * {@link AgentInvalidEventPayloadError}, which a host answers with a 400.
1124
- *
1125
- * It deliberately does NOT check whether the current state handles the event.
1126
- * State machines ignore events they have no transition for; that is normal
1127
- * behavior, not a validation failure. Send the parsed event and read
1128
- * `result.ignored` if the host wants to tell the client nothing happened.
1129
- *
1130
- * @example
1131
- * ```ts
1132
- * const event = parseAgentEvent(machine, await request.json());
1133
- * const result = await runAgent(machine, { store, threadId, event, executors });
1134
- * ```
1135
- */
1136
- function parseAgentEvent(source, payload, options = {}) {
1137
- if (!isRecord(payload) || typeof payload.type !== "string") throw new AgentInvalidEventPayloadError("(unknown)", "expected an object with a string `type`.");
1138
- const event = payload;
1139
- if (isReservedAgentEvent(event.type)) throw new AgentInvalidEventPayloadError(event.type, "this event type is reserved for the library and cannot be sent from outside.");
1140
- const registered = getAgentExecutionOptions(typeof source.provide === "function" ? source : source.machine)?.schemas;
1141
- const inputSchema = (options.events ?? options.schemas?.events ?? registered?.events)?.[event.type];
1142
- if (!inputSchema) return event;
1143
- const { type, ...fields } = event;
1144
- try {
1145
- return {
1146
- ...validateSchemaSync(inputSchema, fields),
1147
- type
1148
- };
1149
- } catch (error) {
1150
- throw new AgentInvalidEventPayloadError(event.type, error instanceof Error ? error.message : String(error));
1151
- }
1152
- }
1153
- /**
1154
- * Lists the events a snapshot can currently accept, as {@link AgentEventDescriptor}s
1155
- * a model can be offered (via `resolveDecision`/an adapter's tool-per-event
1156
- * mapping). **Filters by event TYPE only** — it does not evaluate guards, so
1157
- * a type-legal-but-guard-rejected event can still appear here. Guard
1158
- * legality is checked separately, at decision-resolution time, via
1159
- * `snapshot.can(event)` (the `canTake` option of {@link resolveDecision} /
1160
- * {@link ResolveDecisionOptions}). Pass `eventTypes` to further narrow to a
1161
- * declared `allowedEvents` set — entries may be exact types or wildcard
1162
- * patterns (`'*'`, `'todo.*'`; see {@link matchesEventPattern}).
1163
- *
1164
- * XState-internal (`xstate.*`) and library-reserved
1165
- * ({@link RESERVED_AGENT_EVENT_PREFIX}) event types are always excluded, before
1166
- * any `allowedEvents` matching — a machine that handles `'@agent.usage'` still
1167
- * never offers it to a model.
1168
- */
1169
- function getAcceptedEvents(snapshot, options = {}) {
1170
- const eventTypes = options.eventTypes;
1171
- const seen = /* @__PURE__ */ new Set();
1172
- const usedToolNames = /* @__PURE__ */ new Set();
1173
- return getNextTransitions(snapshot).flatMap((transitionDefinition) => {
1174
- const eventType = transitionDefinition.eventType;
1175
- if (!eventType || eventType === "*" || eventType.startsWith("xstate.") || isReservedAgentEvent(eventType) || eventTypes && !eventTypes.some((pattern) => matchesEventPattern(eventType, pattern)) || seen.has(eventType)) return [];
1176
- seen.add(eventType);
1177
- const defaultToolName = sanitizeEventToolName(eventType);
1178
- const toolName = options.eventToolName ? options.eventToolName({
1179
- eventType,
1180
- defaultToolName
1181
- }) : disambiguateEventToolName(defaultToolName, eventType, usedToolNames);
1182
- const inputSchema = (options.events ?? options.schemas?.events)?.[eventType];
1183
- return [{
1184
- type: eventType,
1185
- toolName,
1186
- ...inputSchema ? { inputSchema } : {}
1187
- }];
1188
- });
1189
- }
1190
- //#endregion
1191
- //#region src/decision.ts
1192
- function decideRequestFromInput(input) {
1193
- const allowedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input) ?? [];
1194
- return {
1195
- kind: "decision",
1196
- id: "",
1197
- name: input.name,
1198
- input,
1199
- model: input.model,
1200
- system: input.system,
1201
- prompt: input.prompt,
1202
- messages: input.messages,
1203
- events: allowedEventTypes.filter((type) => !isEventPattern(type)).map((type) => ({
1204
- type,
1205
- toolName: sanitizeEventToolName(type)
1206
- })),
1207
- attempts: [],
1208
- temperature: input.temperature,
1209
- maxOutputTokens: input.maxOutputTokens,
1210
- topP: input.topP,
1211
- topK: input.topK,
1212
- seed: input.seed,
1213
- stopSequences: input.stopSequences,
1214
- metadata: input.metadata
1215
- };
1216
- }
1217
- function decideActorWithExecutor(execute) {
1218
- const logic = createAsyncLogic({ run: async ({ input, signal }) => {
1219
- if (!execute) throw new Error(`'${DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actors: { '${DECIDE_ACTOR}': ... } }) or resolve the returned agent request with resolveDecision(...).`);
1220
- const resolvedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input);
1221
- if (resolvedEventTypes === void 0) throw new Error(`'${DECIDE_ACTOR}' input has omitted \`allowedEvents\`, which means "all currently-legal events" — but that requires a snapshot-aware host (runAgent or the step path) to resolve. Under a bare createActor(...), declare \`allowedEvents\` explicitly to use this actor here.`);
1222
- if (resolvedEventTypes.some(isEventPattern)) throw new Error(`'${DECIDE_ACTOR}' input uses wildcard \`allowedEvents\` patterns, which expand against the live snapshot — that requires a snapshot-aware host (runAgent or the step path). Under a bare createActor(...), list event types explicitly.`);
1223
- return resolveDecision(decideRequestFromInput(input), { decide: execute }, {
1224
- maxRetries: input.maxRetries ?? 2,
1225
- signal
1226
- });
1227
- } });
1228
- return Object.assign(logic, {
1229
- kind: "statelyai.decisionLogic",
1230
- maxRetries: 2,
1231
- request: decideRequestFromInput,
1232
- allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input),
1233
- withExecutor: (nextExecute) => decideActorWithExecutor(nextExecute)
1234
- });
1235
- }
1236
- function createDecideActor() {
1237
- return decideActorWithExecutor();
1238
- }
1239
- function resolveAllowedEventTypes(allowedEvents, input) {
1240
- if (allowedEvents === void 0) return;
1241
- const resolved = typeof allowedEvents === "function" ? allowedEvents({ input }) : allowedEvents;
1242
- return typeof resolved === "string" ? [resolved] : resolved;
1243
- }
1244
- /**
1245
- * Creates reusable, standalone {@link DecisionLogic}: an actor that, when
1246
- * run, resolves to exactly one currently-legal {@link ChosenEvent} by
1247
- * calling the host `decide` executor (passed here as `execute`, or supplied
1248
- * later via {@link DecisionLogic.withExecutor}, `machine.provide(...)`, or
1249
- * `runAgent`'s `decide` option). Register the result under `actors:` and
1250
- * invoke it by name; for a one-off, state-local decision, prefer the
1251
- * `agent.decide` builtin invoke instead — it needs no separate declaration
1252
- * and types `allowedEvents` against the machine's own event schemas.
1253
- *
1254
- * @example
1255
- * ```ts
1256
- * import { createDecisionLogic } from '@statelyai/agent';
1257
- * import { z } from 'zod';
1258
- *
1259
- * export const chooseMove = createDecisionLogic({
1260
- * schemas: { input: z.object({ playerHp: z.number(), enemyHp: z.number() }) },
1261
- * model: 'openai/gpt-5.4-mini',
1262
- * system: 'You are playing a turn-based game. Choose exactly one legal move.',
1263
- * prompt: ({ input }) => `Player HP: ${input.playerHp}\nEnemy HP: ${input.enemyHp}`,
1264
- * allowedEvents: ({ input }) =>
1265
- * input.playerHp <= 6
1266
- * ? ['ATTACK', 'DEFEND', 'HEAL', 'FLEE']
1267
- * : ['ATTACK', 'DEFEND', 'FLEE'],
1268
- * });
1269
- * ```
1270
- */
1271
- function createDecisionLogic(config, execute) {
1272
- const maxRetries = config.maxRetries ?? 2;
1273
- const request = (input) => {
1274
- const parsedInput = config.schemas ? validateSchemaSync(config.schemas.input, input) : input;
1275
- const args = { input: parsedInput };
1276
- const allowedEventTypes = resolveAllowedEventTypes(config.allowedEvents, parsedInput);
1277
- return {
1278
- kind: "decision",
1279
- id: "",
1280
- name: resolveTextLogicValue(config.name, args),
1281
- input: parsedInput,
1282
- model: resolveTextLogicValue(config.model, args),
1283
- system: resolveTextLogicValue(config.system, args),
1284
- prompt: resolveTextLogicValue(config.prompt, args),
1285
- messages: resolveTextLogicValue(config.messages, args),
1286
- events: (allowedEventTypes ?? []).map((type) => ({
1287
- type,
1288
- toolName: sanitizeEventToolName(type)
1289
- })),
1290
- attempts: [],
1291
- temperature: resolveTextLogicValue(config.temperature, args),
1292
- maxOutputTokens: resolveTextLogicValue(config.maxOutputTokens, args),
1293
- topP: resolveTextLogicValue(config.topP, args),
1294
- topK: resolveTextLogicValue(config.topK, args),
1295
- seed: resolveTextLogicValue(config.seed, args),
1296
- stopSequences: resolveTextLogicValue(config.stopSequences, args),
1297
- metadata: resolveTextLogicValue(config.metadata, args)
1298
- };
1299
- };
1300
- const logic = createAsyncLogic({ run: async ({ input, signal }) => {
1301
- if (!execute) throw new Error("Decision logic has no host execution. Pass an executor as the second argument to createDecisionLogic(...), provide a runtime adapter, or bind it through runAgent/provideExecutors, or call resolveDecision from your host.");
1302
- const allowedEventTypes = resolveAllowedEventTypes(config.allowedEvents, input);
1303
- if (allowedEventTypes === void 0) throw new Error("Decision logic has omitted `allowedEvents`, which means \"all currently-legal events\" — but that requires a snapshot-aware host (runAgent or the step path) to resolve. Under a bare createActor(...), declare `allowedEvents` explicitly on this logic to use it here.");
1304
- if (allowedEventTypes.some(isEventPattern)) throw new Error("Decision logic uses wildcard `allowedEvents` patterns, which expand against the live snapshot — that requires a snapshot-aware host (runAgent or the step path). Under a bare createActor(...), list event types explicitly.");
1305
- return resolveDecision(request(input), { decide: execute }, {
1306
- maxRetries,
1307
- signal
1308
- });
1309
- } });
1310
- const decisionLogic = Object.assign(logic, {
1311
- kind: "statelyai.decisionLogic",
1312
- maxRetries,
1313
- request,
1314
- allowedEventTypes: (input) => resolveAllowedEventTypes(config.allowedEvents, input),
1315
- withExecutor(nextExecute) {
1316
- return createDecisionLogic(config, nextExecute);
1317
- }
1318
- });
1319
- if (execute) executorBoundLogics.add(decisionLogic);
1320
- return decisionLogic;
1321
- }
1322
- /** Type guard: true for any actor logic built by createDecisionLogic/createDecideActor (checks the `kind` marker). @internal */
1323
- function isDecisionLogic(value) {
1324
- return !!value && typeof value === "object" && value.kind === "statelyai.decisionLogic" && typeof value.request === "function";
1325
- }
1326
- /**
1327
- * Builds an {@link AgentDecisionRequest} for {@link resolveDecision}, filling
1328
- * in the fields a hand-written literal has to restate every time: `kind`, an
1329
- * `id`, an empty `attempts` list, and each candidate event's `toolName`.
1330
- *
1331
- * @example
1332
- * ```ts
1333
- * const chosen = await resolveDecision(
1334
- * createDecisionRequest({
1335
- * name: 'judge',
1336
- * model: 'reviewer',
1337
- * prompt: `Judge this draft.\n\n${snapshot.context.draft}`,
1338
- * events: getAcceptedEvents(snapshot),
1339
- * }),
1340
- * { decide },
1341
- * { canTake: (event) => snapshot.can(event) },
1342
- * );
1343
- * ```
1344
- */
1345
- function createDecisionRequest(options) {
1346
- const { id, name, events, attempts, ...rest } = options;
1347
- return {
1348
- ...rest,
1349
- kind: "decision",
1350
- id: id ?? name ?? "decision",
1351
- ...name === void 0 ? {} : { name },
1352
- events: dedupeToolNames(events.map((event) => typeof event === "string" ? {
1353
- type: event,
1354
- toolName: sanitizeEventToolName(event)
1355
- } : event)),
1356
- attempts: attempts ?? []
1357
- };
1358
- }
1359
- function dedupeToolNames(candidates) {
1360
- const taken = /* @__PURE__ */ new Set();
1361
- return candidates.map((candidate) => {
1362
- if (candidate.toolName === void 0) return candidate;
1363
- let toolName = candidate.toolName;
1364
- for (let n = 2; taken.has(toolName); n++) {
1365
- const suffix = `_${n}`;
1366
- toolName = `${candidate.toolName.slice(0, 64 - suffix.length)}${suffix}`;
1367
- }
1368
- taken.add(toolName);
1369
- return toolName === candidate.toolName ? candidate : {
1370
- ...candidate,
1371
- toolName
1372
- };
1373
- });
1374
- }
1375
- /**
1376
- * Thrown by {@link resolveDecision} when every attempt (up to
1377
- * `maxRetries + 1` of them) fails one of the three checks recorded in
1378
- * {@link DecisionAttempt.failure}. Carries the full `attempts` list for
1379
- * diagnostics; a machine typically routes this via the decision invoke's
1380
- * `onError`.
1381
- */
1382
- var AgentDecisionExhaustedError = class extends AgentError {
1383
- attempts;
1384
- constructor(attempts) {
1385
- super("decision-exhausted", `Decision exhausted after ${attempts.length} attempt${attempts.length === 1 ? "" : "s"}: ` + attempts.map((attempt) => attempt.reason).join("; "));
1386
- this.name = "AgentDecisionExhaustedError";
1387
- this.attempts = attempts;
1388
- }
1389
- };
1390
- /**
1391
- * Renders a decision request's prior failed `attempts` into feedback messages
1392
- * a host appends to the model call so retries converge — the transport-agnostic
1393
- * "your last choice failed because X, choose again from Y" logic every adapter
1394
- * and raw-SDK host repeats. Returns one `user`-role {@link AgentMessage} per
1395
- * attempt (empty when there are none); adapters map each onto their wire
1396
- * message shape (`attempt.content` is always a string). Core never rewrites the
1397
- * request itself — this only turns the recorded attempts into messages.
1398
- *
1399
- * @example
1400
- * ```ts
1401
- * const messages = [...baseMessages, ...renderDecisionAttempts(request)];
1402
- * ```
1403
- */
1404
- function renderDecisionAttempts(request) {
1405
- const types = request.events.map((event) => event.type).join(", ") || "(none)";
1406
- return request.attempts.map((attempt) => userMessage(`Your previous choice failed: ${attempt.reason}. Choose again from: ${types}`));
1407
- }
1408
- /**
1409
- * Validation + retry core for decisions. No provider mechanics — the
1410
- * `executors.decide` is responsible for making the model choose an event; this
1411
- * function only validates the choice and retries on failure, up to
1412
- * `options.maxRetries` (default 2, i.e. up to 3 attempts total).
1413
- *
1414
- * Each attempt is checked in order and can fail one of three ways (recorded
1415
- * as a {@link DecisionAttempt}): `'unknown-event'` (the chosen `type` is not
1416
- * among `request.events`), `'invalid-payload'` (the payload fails that
1417
- * event's schema), or `'rejected-by-guard'` (passes both checks but
1418
- * `options.canTake` returns `false` — a type/payload-legal event the
1419
- * machine's guard rejects right now; omit `canTake` to skip this check).
1420
- * Every prior failed attempt for this call is fed back to the executor on
1421
- * the next attempt via `request.attempts`, so an adapter can render "your
1422
- * last choice failed because X — try again" into the next model call; core
1423
- * never rewrites the request itself. Exhausting all attempts throws
1424
- * {@link AgentDecisionExhaustedError} with the full attempts list.
1425
- *
1426
- * @example
1427
- * ```ts
1428
- * const event = await resolveDecision(request, executors, {
1429
- * canTake: (e) => snapshot.can(e),
1430
- * });
1431
- * ```
1432
- */
1433
- async function resolveDecision(request, executors, options = {}) {
1434
- const executor = executors?.decide;
1435
- if (typeof executor !== "function") throw new AgentError("missing-decide-executor", "resolveDecision(request, executors, ...) takes the EXECUTOR SET (the same object executeAgentRequest takes), and this one has no 'decide' function. Build one with createAiSdkExecutors({ models }), or pass { decide }.");
1436
- const maxRetries = options.maxRetries ?? 2;
1437
- const attempts = [];
1438
- const eventsByType = new Map(request.events.map((event) => [event.type, event]));
1439
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1440
- options.signal?.throwIfAborted();
1441
- const result = await executor({
1442
- ...request,
1443
- name: request.name ?? (request.id || "agent.decide"),
1444
- attempts: [...attempts]
1445
- }, {
1446
- ...options.signal !== void 0 ? { signal: options.signal } : {},
1447
- ...request.id ? { requestId: request.id } : {}
1448
- });
1449
- if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
1450
- const { event } = result;
1451
- const descriptor = eventsByType.get(event.type);
1452
- if (!descriptor) {
1453
- attempts.push({
1454
- event,
1455
- failure: "unknown-event",
1456
- reason: `'${event.type}' is not among the currently allowed events: ${request.events.map((candidate) => candidate.type).join(", ") || "(none)"}.`
1457
- });
1458
- continue;
1459
- }
1460
- let validatedEvent = event;
1461
- if (descriptor.inputSchema) {
1462
- const { type, ...payload } = event;
1463
- try {
1464
- validatedEvent = {
1465
- ...validateSchemaSync(descriptor.inputSchema, payload),
1466
- type
1467
- };
1468
- } catch (error) {
1469
- attempts.push({
1470
- event,
1471
- failure: "invalid-payload",
1472
- reason: `'${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`
1473
- });
1474
- continue;
1475
- }
1476
- }
1477
- if (options.canTake?.(validatedEvent) === false) {
1478
- attempts.push({
1479
- event: validatedEvent,
1480
- failure: "rejected-by-guard",
1481
- reason: `'${validatedEvent.type}' is not currently takeable (guard rejected it).`
1482
- });
1483
- continue;
1484
- }
1485
- return validatedEvent;
1486
- }
1487
- throw new AgentDecisionExhaustedError(attempts);
1488
- }
1489
- //#endregion
1490
- export { userMessage as $, userInputActor as A, assistantMessage as B, getCallFinishReason as C, parseModelRef as D, normalizeGeneratorResult as E, getRegisteredAgentExecutionOptions as F, getMachineStructuralHash as G, findNonSerializableContextPaths as H, isUnboundPlaceholder as I, getStatePath as J, getMessageText as K, machineIdlePredicates as L, executorBoundLogics as M, getAgentExecutionOptions as N, parseOutput as O, getMachineIdlePredicate as P, toolMessage as Q, missingActor as R, getAgentOutputMode as S, isTextLogic as T, getJsonSchema as U, djb2Hex as V, getJsonSchemaSync as W, resolveMachineVersion as X, isStandardSchema as Y, systemMessage as Z, bindRequestExecutor as _, isDecisionLogic as a, messagesSchema as at, createTextLogic as b, AgentInvalidEventPayloadError as c, isRecord as d, validateSchemaSync as et, AGENT_USAGE_TOKEN_FIELDS as f, USER_INPUT_ACTOR as g, STREAM_TEXT_ACTOR as h, createDecisionRequest as i, isAgentMessages as it, DEFAULT_AGENT_EXECUTORS as j, parseStructuredEnvelope as k, getAcceptedEvents as l, GENERATE_TEXT_ACTOR as m, createDecideActor as n, agentMessagesEventSchema as nt, renderDecisionAttempts as o, AgentError as ot, DECIDE_ACTOR as p, getStateMeta as q, createDecisionLogic as r, appendMessages as rt, resolveDecision as s, AgentTruncatedError as st, AgentDecisionExhaustedError as t, AGENT_MESSAGES_EVENT_TYPE as tt, parseAgentEvent as u, buildEnvelopeSchema as v, getCallUsage as w, executeAgentTextRequest as x, builtinTextActors as y, setAgentExecutionOptions as z };