@statelyai/agent 1.1.6 → 2.0.0-alpha.10

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ai-sdk.cjs +342 -0
  3. package/dist/ai-sdk.d.cts +206 -0
  4. package/dist/ai-sdk.d.mts +206 -0
  5. package/dist/ai-sdk.mjs +331 -0
  6. package/dist/cli.cjs +64 -0
  7. package/dist/cli.d.cts +1 -0
  8. package/dist/cli.d.mts +1 -0
  9. package/dist/cli.mjs +65 -0
  10. package/dist/decision-CQdrKc8k.mjs +978 -0
  11. package/dist/decision-b-lkcs4L.cjs +1295 -0
  12. package/dist/index.cjs +59 -0
  13. package/dist/index.d.cts +212 -0
  14. package/dist/index.d.mts +201 -417
  15. package/dist/index.mjs +4 -588
  16. package/dist/openai-compat.cjs +319 -0
  17. package/dist/openai-compat.d.cts +98 -0
  18. package/dist/openai-compat.d.mts +98 -0
  19. package/dist/openai-compat.mjs +312 -0
  20. package/dist/run-agent-BFMkuI1F.cjs +1599 -0
  21. package/dist/run-agent-BVMd--1l.d.cts +1103 -0
  22. package/dist/run-agent-BoAOq_0Z.mjs +1540 -0
  23. package/dist/run-agent-DzYJb3CK.d.mts +1103 -0
  24. package/dist/src-D-77Ha5p.cjs +1087 -0
  25. package/dist/src-DUeIFjv-.mjs +1016 -0
  26. package/dist/text-logic-C7WJpCIc.d.mts +710 -0
  27. package/dist/text-logic-CZjyACzQ.d.cts +710 -0
  28. package/dist/types-C9QiMjre.d.cts +219 -0
  29. package/dist/types-qm00QF91.d.mts +219 -0
  30. package/dist/utils-Dri7aeEG.d.cts +108 -0
  31. package/dist/utils-Y6GDRGGE.d.mts +108 -0
  32. package/dist/zod.cjs +31 -0
  33. package/dist/zod.d.cts +30 -0
  34. package/dist/zod.d.mts +30 -0
  35. package/dist/zod.mjs +30 -0
  36. package/package.json +109 -28
  37. package/readme.md +143 -6
  38. package/schemas/agent-workflow.json +527 -0
  39. package/.changeset/README.md +0 -8
  40. package/.changeset/config.json +0 -11
  41. package/.env.template +0 -3
  42. package/.github/actions/ci-setup/action.yml +0 -24
  43. package/.github/workflows/release.yml +0 -46
  44. package/.vscode/launch.json +0 -28
  45. package/CHANGELOG.md +0 -222
  46. package/dist/index.d.ts +0 -428
  47. package/dist/index.js +0 -621
  48. package/examples/chatbot.ts +0 -71
  49. package/examples/cot.ts +0 -89
  50. package/examples/email.ts +0 -118
  51. package/examples/example.ts +0 -81
  52. package/examples/goal.ts +0 -94
  53. package/examples/helpers/helpers.ts +0 -17
  54. package/examples/helpers/loader.ts +0 -32
  55. package/examples/helpers/runner.ts +0 -27
  56. package/examples/joke.ts +0 -225
  57. package/examples/multi.ts +0 -103
  58. package/examples/newspaper.ts +0 -324
  59. package/examples/number.ts +0 -102
  60. package/examples/raffle.ts +0 -105
  61. package/examples/sandbox.ts +0 -28
  62. package/examples/simple.ts +0 -39
  63. package/examples/support.ts +0 -147
  64. package/examples/ticTacToe.ts +0 -224
  65. package/examples/todo.ts +0 -137
  66. package/examples/tutor.ts +0 -100
  67. package/examples/verify.ts +0 -120
  68. package/examples/weather.ts +0 -178
  69. package/examples/wiki.ts +0 -30
  70. package/examples/word.ts +0 -171
  71. package/src/adapters/vercel.ts +0 -7
  72. package/src/agent-experimental.ts +0 -221
  73. package/src/agent.test.ts +0 -506
  74. package/src/agent.ts +0 -300
  75. package/src/decision.test.ts +0 -179
  76. package/src/decision.ts +0 -84
  77. package/src/index.ts +0 -4
  78. package/src/memory.ts +0 -25
  79. package/src/planners/shortestPathPlanner.ts +0 -22
  80. package/src/planners/simplePlanner.ts +0 -139
  81. package/src/schemas.ts +0 -11
  82. package/src/strategies/chain-of-note.ts +0 -155
  83. package/src/templates/defaultText.ts +0 -18
  84. package/src/text.ts +0 -241
  85. package/src/types.ts +0 -499
  86. package/src/utils.ts +0 -72
  87. package/tsconfig.json +0 -109
  88. package/vitest.config.ts +0 -9
@@ -0,0 +1,1295 @@
1
+ let xstate = require("xstate");
2
+ //#region src/utils.ts
3
+ /**
4
+ * Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
5
+ * shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
6
+ * JSON-serializability: functions, `undefined`, and other non-JSON values are
7
+ * dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
8
+ * plain-JSON deep clone, not a live snapshot.
9
+ */
10
+ function persistSnapshot(snapshot) {
11
+ return JSON.parse(JSON.stringify(snapshot));
12
+ }
13
+ /**
14
+ * Walks a context value and returns the dot-paths of the first few values that
15
+ * would NOT survive a JSON persist/resume round-trip (see {@link persistSnapshot}):
16
+ * `Date`, `Map`, `Set`, `RegExp`, functions, `undefined`, `bigint`, class
17
+ * instances (non-plain objects), and circular references. Plain objects,
18
+ * arrays, and JSON primitives are walked/allowed. Returns `[]` for a
19
+ * fully-JSON-safe value. Cheap and bounded (stops after `limit` findings) —
20
+ * intended for a dev-only warning at the moment persistence matters.
21
+ */
22
+ function findNonSerializableContextPaths(context, limit = 5) {
23
+ const paths = [];
24
+ const seen = /* @__PURE__ */ new WeakSet();
25
+ const walk = (value, path) => {
26
+ if (paths.length >= limit) return;
27
+ if (value === null) return;
28
+ const type = typeof value;
29
+ if (type === "string" || type === "number" || type === "boolean") return;
30
+ if (type === "undefined" || type === "bigint" || type === "function" || type === "symbol") {
31
+ paths.push(`${path} (${type})`);
32
+ return;
33
+ }
34
+ const obj = value;
35
+ if (seen.has(obj)) {
36
+ paths.push(`${path} (circular)`);
37
+ return;
38
+ }
39
+ if (Array.isArray(value)) {
40
+ seen.add(obj);
41
+ value.forEach((item, index) => walk(item, `${path}[${index}]`));
42
+ seen.delete(obj);
43
+ return;
44
+ }
45
+ const proto = Object.getPrototypeOf(value);
46
+ if (proto === Object.prototype || proto === null) {
47
+ seen.add(obj);
48
+ for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`);
49
+ seen.delete(obj);
50
+ return;
51
+ }
52
+ const ctorName = value.constructor?.name ?? "object";
53
+ paths.push(`${path} (${ctorName})`);
54
+ };
55
+ walk(context, "context");
56
+ return paths;
57
+ }
58
+ /**
59
+ * A stable, dependency-free structural fingerprint of a machine — a short hex
60
+ * `djb2` hash over its **structural** config only: state ids/nesting, transition
61
+ * event types and targets, invoke `src`s, `initial`, and any other serializable
62
+ * config fields. Function values (context/output builders, prompts, inline
63
+ * guards/actions) are excluded entirely, so two machines that differ only in
64
+ * their prompts or executors hash identically; adding/removing/retargeting a
65
+ * state or transition changes the hash.
66
+ *
67
+ * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
68
+ * detect a structurally-edited machine on resume. It is a change detector, not
69
+ * a cryptographic digest — collisions are possible but unlikely for real
70
+ * configs. Pass an explicit `machineVersion` to `runAgent` to override it.
71
+ */
72
+ function getMachineStructuralHash(machine) {
73
+ return djb2Hex(stableStructuralString(machine.config));
74
+ }
75
+ function stableStructuralString(value, seen = /* @__PURE__ */ new WeakSet()) {
76
+ if (value === null) return "null";
77
+ const type = typeof value;
78
+ if (type === "function" || type === "undefined" || type === "symbol") return "";
79
+ if (type === "string") return JSON.stringify(value);
80
+ if (type === "number" || type === "boolean") return String(value);
81
+ if (type === "bigint") return `${value}n`;
82
+ const obj = value;
83
+ if (seen.has(obj)) return "\"[circular]\"";
84
+ seen.add(obj);
85
+ let out;
86
+ if (Array.isArray(value)) out = `[${value.map((item) => stableStructuralString(item, seen)).join(",")}]`;
87
+ else {
88
+ const parts = [];
89
+ for (const key of Object.keys(obj).sort()) {
90
+ const child = obj[key];
91
+ const childType = typeof child;
92
+ if (childType === "function" || childType === "undefined" || childType === "symbol") continue;
93
+ parts.push(`${JSON.stringify(key)}:${stableStructuralString(child, seen)}`);
94
+ }
95
+ out = `{${parts.join(",")}}`;
96
+ }
97
+ seen.delete(obj);
98
+ return out;
99
+ }
100
+ function djb2Hex(input) {
101
+ let hash = 5381;
102
+ for (let i = 0; i < input.length; i++) hash = (hash << 5) + hash + input.charCodeAt(i) | 0;
103
+ return (hash >>> 0).toString(16).padStart(8, "0");
104
+ }
105
+ /** Builds a {@link UserMessage} from a string or multimodal content parts. */
106
+ function userMessage(content) {
107
+ return {
108
+ role: "user",
109
+ content
110
+ };
111
+ }
112
+ /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
113
+ function assistantMessage(content) {
114
+ return {
115
+ role: "assistant",
116
+ content
117
+ };
118
+ }
119
+ /** Builds a {@link SystemMessage}. */
120
+ function systemMessage(content) {
121
+ return {
122
+ role: "system",
123
+ content
124
+ };
125
+ }
126
+ /** Builds a {@link ToolMessage} from one or more tool-result parts. */
127
+ function toolMessage(content) {
128
+ return {
129
+ role: "tool",
130
+ content
131
+ };
132
+ }
133
+ /**
134
+ * Returns the merged `meta` of a snapshot's active state(s) — the typed
135
+ * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
136
+ *
137
+ * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
138
+ * state, but parallel/nested machines can have several. This shallow-merges
139
+ * every active state's meta into one object (later/deeper entries win) and
140
+ * returns `{}` when no active state declares meta.
141
+ *
142
+ * The return type is recovered from the snapshot's own `getMeta()` type, so a
143
+ * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
144
+ * output type. Pass an explicit `TMeta` to override when the snapshot is
145
+ * untyped (e.g. `AnyMachineSnapshot`).
146
+ *
147
+ * @example HITL: read the current state's interaction protocol off an idle
148
+ * snapshot to render for a human.
149
+ * ```ts
150
+ * const { interaction } = getStateMeta(result.snapshot);
151
+ * ```
152
+ */
153
+ function getStateMeta(snapshot) {
154
+ return Object.assign({}, ...Object.values(snapshot.getMeta()).filter((meta) => meta != null));
155
+ }
156
+ /**
157
+ * Reads the run-owned message log off a snapshot settled by a `runAgent` call
158
+ * that used `getRequests` (or `options.messages`) — the typed replacement for
159
+ * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
160
+ * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
161
+ * so it survives a JSON persist/resume round-trip; this accessor works on the
162
+ * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
163
+ * when no log was stamped (e.g. a default invoke-driven run).
164
+ *
165
+ * The write path is `runAgent(..., { messages })`: an explicit seed that
166
+ * overrides the resume snapshot's stamped log (fold in a user reply on
167
+ * resume, or start a run with prior history).
168
+ */
169
+ function getAgentMessages(snapshot) {
170
+ const stamped = snapshot?.messages;
171
+ return Array.isArray(stamped) ? stamped : [];
172
+ }
173
+ /**
174
+ * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
175
+ * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
176
+ * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
177
+ * can't read directly — see the `ai-sdk` tool pass-through and `openai-compat`
178
+ * tool serialization.
179
+ */
180
+ function isStandardSchema(value) {
181
+ return typeof value === "object" && value !== null && "~standard" in value;
182
+ }
183
+ /**
184
+ * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
185
+ * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
186
+ * `z.toJSONSchema`), awaiting it when the producer is async. Returns
187
+ * `undefined` when the schema doesn't expose the extension. Use this to build
188
+ * a provider request's `response_format`/tool `parameters` from a schema.
189
+ */
190
+ async function getJsonSchema(schema) {
191
+ const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
192
+ if (!jsonSchemaFn) return;
193
+ const result = jsonSchemaFn();
194
+ return result instanceof Promise ? await result : result;
195
+ }
196
+ /**
197
+ * Synchronous variant of {@link getJsonSchema}, for call sites that can't
198
+ * await (building tool/event descriptors inline). An async JSON Schema
199
+ * producer is treated as absent (returns `undefined`) — in practice Zod's
200
+ * `z.toJSONSchema` resolves synchronously.
201
+ */
202
+ function getJsonSchemaSync(schema) {
203
+ const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
204
+ if (!jsonSchemaFn) return;
205
+ const result = jsonSchemaFn();
206
+ return result instanceof Promise ? void 0 : result;
207
+ }
208
+ /**
209
+ * Validates `value` against a {@link StandardSchemaV1}, synchronously.
210
+ * Throws if the schema's `validate` returns a `Promise` (async validation is
211
+ * not supported anywhere in this library) or if validation reports issues —
212
+ * in which case the thrown `Error.message` joins every issue message with
213
+ * `', '`.
214
+ */
215
+ function validateSchemaSync(schema, value) {
216
+ const result = schema["~standard"].validate(value);
217
+ if (result instanceof Promise) throw new Error("Async schema validation is not supported.");
218
+ if (result.issues) throw new Error(result.issues.map((issue) => issue.message).join(", "));
219
+ return result.value;
220
+ }
221
+ //#endregion
222
+ //#region src/internal/registry.ts
223
+ const agentExecutionOptions = /* @__PURE__ */ new WeakMap();
224
+ function getRegisteredAgentModels(machine) {
225
+ return agentExecutionOptions.get(machine)?.models;
226
+ }
227
+ /**
228
+ * Machine-carried wait-state predicates, keyed on the machine's root `config`
229
+ * object. `config` is shared by reference across `machine.provide(...)` (unlike
230
+ * the machine object itself), so a predicate registered here travels with the
231
+ * machine through `.provide` — which is why it is keyed on `config`, not the
232
+ * machine. Set by `setupAgent({ isSuspended })` in `createMachine`, read by
233
+ * `runAgent` (below the host `options.isSuspended` override, above the timing
234
+ * heuristic).
235
+ */
236
+ const machineSuspensionPredicates = /* @__PURE__ */ new WeakMap();
237
+ /** Reads the {@link machineSuspensionPredicates} predicate carried by `machine` (via its root `config`), if any. */
238
+ function getMachineSuspensionPredicate(machine) {
239
+ const config = machine.config;
240
+ return config ? machineSuspensionPredicates.get(config) : void 0;
241
+ }
242
+ const unboundPlaceholderLogics = /* @__PURE__ */ new WeakSet();
243
+ /** Text/decision logics created WITH their own executor (withExecutor or the
244
+ * factory's second arg) — these are runnable as-is, so runAgent's bind check
245
+ * must not reject them as direct-object invoke srcs. */
246
+ const executorBoundLogics = /* @__PURE__ */ new WeakSet();
247
+ function missingActor(src) {
248
+ const logic = (0, xstate.createAsyncLogic)({ run: async () => {
249
+ throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${src}': ... } }).`);
250
+ } });
251
+ unboundPlaceholderLogics.add(logic);
252
+ return logic;
253
+ }
254
+ function isUnboundPlaceholder(logic) {
255
+ return !!logic && typeof logic === "object" && unboundPlaceholderLogics.has(logic);
256
+ }
257
+ function getRegisteredAgentExecutionOptions(machine, options) {
258
+ return {
259
+ ...agentExecutionOptions.get(machine),
260
+ ...options
261
+ };
262
+ }
263
+ //#endregion
264
+ //#region src/text-logic.ts
265
+ const USER_INPUT_ACTOR = "agent.userInput";
266
+ const GENERATE_TEXT_ACTOR = "agent.generateText";
267
+ const STREAM_TEXT_ACTOR = "agent.streamText";
268
+ const DECIDE_ACTOR = "agent.decide";
269
+ const PLAN_ACTOR = "agent.plan";
270
+ /** Synthetic `src` stamped on trace requests produced by `getRequests` state interpretation — NOT a registered actor source (nothing is invoked; the pass makes the call directly). */
271
+ const INTERPRET_SOURCE = "agent.interpret";
272
+ /**
273
+ * Splits a portable `"provider/model-id"` model ref (the convention JSON
274
+ * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
275
+ * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
276
+ * The standard building block for a host's `resolveModel`:
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
281
+ * ```
282
+ */
283
+ function parseModelRef(modelRef) {
284
+ const slash = modelRef.indexOf("/");
285
+ return slash === -1 ? {
286
+ provider: void 0,
287
+ modelId: modelRef
288
+ } : {
289
+ provider: modelRef.slice(0, slash),
290
+ modelId: modelRef.slice(slash + 1)
291
+ };
292
+ }
293
+ const agentTextInputSchema = { "~standard": {
294
+ version: 1,
295
+ vendor: "statelyai-agent",
296
+ validate(value) {
297
+ return !!value && typeof value === "object" && typeof value.model === "string" ? { value } : { issues: [{ message: "Expected agent text input with a model" }] };
298
+ }
299
+ } };
300
+ const unknownOutputSchema = { "~standard": {
301
+ version: 1,
302
+ vendor: "statelyai-agent",
303
+ validate(value) {
304
+ return { value };
305
+ }
306
+ } };
307
+ const stringOutputSchema = { "~standard": {
308
+ version: 1,
309
+ vendor: "statelyai-agent",
310
+ validate(value) {
311
+ return typeof value === "string" ? { value } : { issues: [{ message: "Expected string output" }] };
312
+ }
313
+ } };
314
+ function createBuiltinTextActor(src, mode, outputSchema) {
315
+ const logic = (0, xstate.createAsyncLogic)({ run: async () => {
316
+ throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${src}': ... } }) or execute the returned agent request with executeAgentRequest(...).`);
317
+ } });
318
+ return Object.assign(logic, {
319
+ kind: "statelyai.textLogic",
320
+ mode,
321
+ schemas: {
322
+ input: agentTextInputSchema,
323
+ output: outputSchema
324
+ },
325
+ request(input) {
326
+ return validateSchemaSync(agentTextInputSchema, input);
327
+ },
328
+ async execute(input, executors) {
329
+ const { output } = await executeAgentTextRequest(mode, src, validateSchemaSync(agentTextInputSchema, input), executors);
330
+ return validateSchemaSync(outputSchema, output);
331
+ },
332
+ withExecutor(execute) {
333
+ return Object.assign(createTextLogic({
334
+ mode,
335
+ schemas: {
336
+ input: agentTextInputSchema,
337
+ output: outputSchema
338
+ },
339
+ name: ({ input }) => input.name,
340
+ model: ({ input }) => input.model,
341
+ system: ({ input }) => input.system,
342
+ prompt: ({ input }) => input.prompt,
343
+ messages: ({ input }) => input.messages,
344
+ tools: ({ input }) => input.tools,
345
+ toolChoice: ({ input }) => input.toolChoice,
346
+ reasoning: ({ input }) => input.reasoning,
347
+ temperature: ({ input }) => input.temperature,
348
+ maxOutputTokens: ({ input }) => input.maxOutputTokens,
349
+ topP: ({ input }) => input.topP,
350
+ topK: ({ input }) => input.topK,
351
+ seed: ({ input }) => input.seed,
352
+ stopSequences: ({ input }) => input.stopSequences,
353
+ metadata: ({ input }) => input.metadata
354
+ }, execute));
355
+ }
356
+ });
357
+ }
358
+ /** The unbound `agent.generateText`/`agent.streamText` builtins registered by setupAgent. @internal */
359
+ const builtinTextActors = {
360
+ [GENERATE_TEXT_ACTOR]: createBuiltinTextActor(GENERATE_TEXT_ACTOR, "generate", unknownOutputSchema),
361
+ [STREAM_TEXT_ACTOR]: createBuiltinTextActor(STREAM_TEXT_ACTOR, "stream", stringOutputSchema)
362
+ };
363
+ /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). Output is `string` — what the human typed. @internal */
364
+ const userInputActor = (0, xstate.createAsyncLogic)({ run: async () => {
365
+ throw new Error(`'${USER_INPUT_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${USER_INPUT_ACTOR}': ... } }).`);
366
+ } });
367
+ unboundPlaceholderLogics.add(userInputActor);
368
+ /**
369
+ * Validates a raw model/executor output against `schema`, returning the
370
+ * parsed value. Thin wrapper over {@link validateSchemaSync} for parsing a
371
+ * text request's structured output outside of `TextLogic.execute`/
372
+ * `executeAgentRequest` (e.g. a custom host loop).
373
+ */
374
+ function parseOutput(schema, output) {
375
+ return validateSchemaSync(schema, output);
376
+ }
377
+ /** Resolves a `ResolveTextLogicValue` (calls it if it's a function, else returns it as-is). @internal */
378
+ function resolveTextLogicValue(value, args) {
379
+ return typeof value === "function" ? value(args) : value;
380
+ }
381
+ /**
382
+ * Creates reusable, standalone {@link TextLogic}: an actor that, when run,
383
+ * resolves typed input to typed output via a model call. Register the
384
+ * result under `actorSources:` and invoke it by name (equivalent to what
385
+ * `setupAgent({ requests })` builds internally for each request entry). Pass
386
+ * `execute` here, or bind it later with `.withExecutor(...)`, a runtime
387
+ * adapter's `machine.provide(...)`, or `runAgent`'s `generateText`/
388
+ * `streamText` options.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * export const tellJoke = createTextLogic({
393
+ * mode: 'stream',
394
+ * schemas: { input: z.object({ topic: z.string() }), output: z.string() },
395
+ * model: 'openai/gpt-5.4-mini',
396
+ * system: 'You tell short, punchy jokes.',
397
+ * prompt: ({ input }) => `Tell a joke about ${input.topic}.`,
398
+ * });
399
+ * ```
400
+ */
401
+ function createTextLogic(config, execute) {
402
+ const request = (input) => {
403
+ const args = { input: validateSchemaSync(config.schemas.input, input) };
404
+ return {
405
+ name: resolveTextLogicValue(config.name, args),
406
+ model: resolveTextLogicValue(config.model, args),
407
+ system: resolveTextLogicValue(config.system, args),
408
+ prompt: resolveTextLogicValue(config.prompt, args),
409
+ messages: resolveTextLogicValue(config.messages, args),
410
+ tools: resolveTextLogicValue(config.tools, args),
411
+ toolChoice: resolveTextLogicValue(config.toolChoice, args),
412
+ outputSchema: config.schemas.output,
413
+ reasoning: resolveTextLogicValue(config.reasoning, args),
414
+ temperature: resolveTextLogicValue(config.temperature, args),
415
+ maxOutputTokens: resolveTextLogicValue(config.maxOutputTokens, args),
416
+ topP: resolveTextLogicValue(config.topP, args),
417
+ topK: resolveTextLogicValue(config.topK, args),
418
+ seed: resolveTextLogicValue(config.seed, args),
419
+ stopSequences: resolveTextLogicValue(config.stopSequences, args),
420
+ metadata: resolveTextLogicValue(config.metadata, args)
421
+ };
422
+ };
423
+ const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal, system, self }, enq) => {
424
+ const resolvedRequest = request(input);
425
+ 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 extract it with getAgentRequests(..., { actorSources }).");
426
+ const result = await execute({
427
+ input,
428
+ request: resolvedRequest,
429
+ signal,
430
+ system,
431
+ self,
432
+ emit: enq.emit
433
+ });
434
+ const selfId = self?.id;
435
+ const output = await normalizeGeneratorResult(result, typeof selfId === "string" ? selfId : "text logic", { request: resolvedRequest });
436
+ return validateSchemaSync(config.schemas.output, output);
437
+ } });
438
+ const textLogic = Object.assign(logic, {
439
+ kind: "statelyai.textLogic",
440
+ mode: config.mode ?? "generate",
441
+ schemas: config.schemas,
442
+ request,
443
+ async execute(input, executors) {
444
+ const { output } = await executeAgentTextRequest(config.mode ?? "generate", "textLogic", request(input), executors);
445
+ return validateSchemaSync(config.schemas.output, output);
446
+ },
447
+ withExecutor(nextExecute) {
448
+ return createTextLogic(config, nextExecute);
449
+ }
450
+ });
451
+ if (execute) executorBoundLogics.add(textLogic);
452
+ return textLogic;
453
+ }
454
+ /**
455
+ * Binds a child machine's {@link TextLogic} to a raw
456
+ * {@link AgentRequestExecutor} (the `generateText`/`streamText` shape hosts
457
+ * implement). Encapsulates the `withExecutor` idiom child agents repeat:
458
+ * default the request's `tools` to `{}`, forward the actor `signal`, call the
459
+ * executor, and return its `{ output }` envelope. Use this to share ONE
460
+ * executor across a parent and its nested children.
461
+ *
462
+ * @example
463
+ * ```ts
464
+ * childMachine.provide({
465
+ * actorSources: {
466
+ * researchTopic: bindRequestExecutor(setup.requests.researchTopic, generateText),
467
+ * },
468
+ * });
469
+ * ```
470
+ */
471
+ function bindRequestExecutor(logic, executor, info) {
472
+ return logic.withExecutor(async ({ request, signal }) => {
473
+ const { output } = await executor({
474
+ ...request,
475
+ tools: request.tools ?? {}
476
+ }, {
477
+ signal,
478
+ onChunk: info?.onChunk
479
+ });
480
+ return { output };
481
+ });
482
+ }
483
+ /** Type guard: true for any actor logic built by createTextLogic (checks the `kind` marker). @internal */
484
+ function isTextLogic(value) {
485
+ return !!value && typeof value === "object" && value.kind === "statelyai.textLogic" && typeof value.request === "function";
486
+ }
487
+ /**
488
+ * Classifies a text request's output schema as `'structured'` (its JSON
489
+ * Schema is `type: 'object'`, `type: 'array'`, or a top-level union/
490
+ * composition — `anyOf`/`oneOf`/`allOf`, which a bare `z.union`/
491
+ * `z.discriminatedUnion` emits with no top-level `type`) or `'text'`
492
+ * (anything else, including no schema). Reads the schema's
493
+ * `~standard.jsonSchema.input()` extension — schemas without it are treated
494
+ * as `'text'`.
495
+ */
496
+ function getAgentOutputMode(schema) {
497
+ const jsonSchema = getStandardSchemaJson(schema);
498
+ if (!jsonSchema) return "text";
499
+ if (jsonSchema.type === "object" || jsonSchema.type === "array") return "structured";
500
+ if (jsonSchema.type === void 0 && ("anyOf" in jsonSchema || "oneOf" in jsonSchema || "allOf" in jsonSchema)) return "structured";
501
+ return "text";
502
+ }
503
+ /** True when {@link getAgentOutputMode} classifies `schema` as `'structured'`. */
504
+ function isStructuredOutputSchema(schema) {
505
+ return getAgentOutputMode(schema) === "structured";
506
+ }
507
+ /**
508
+ * Builds the uniform structured-output envelope schema every structured request
509
+ * is sent to the provider as: a root object `{ result: <inner> }`, plus — when
510
+ * `options.reasoning` is `true` — an optional string `reasoning` property listed
511
+ * BEFORE `result` (property order nudges the model to reason first). This is THE
512
+ * wire contract for structured output: a root object is universally accepted as
513
+ * a provider response schema, unlike a bare union/array root that many providers
514
+ * reject.
515
+ *
516
+ * The returned {@link StandardSchemaV1} validates the `{ reasoning?, result }`
517
+ * envelope (unwrapping `result` through the original schema, capturing a string
518
+ * `reasoning` when present) and exposes the enveloped JSON Schema. Adapters read
519
+ * `.result` off the provider output before the machine validates it — so this is
520
+ * transparent: user-facing output types stay the declared (un-enveloped) schema,
521
+ * and `reasoning` is surfaced only on the raw executor result, never in machine
522
+ * context/output.
523
+ */
524
+ function buildEnvelopeSchema(inner, options = {}) {
525
+ const includeReasoning = options.reasoning === true;
526
+ const buildJson = (innerJson) => ({
527
+ type: "object",
528
+ properties: {
529
+ ...includeReasoning ? { reasoning: { type: "string" } } : {},
530
+ result: innerJson ?? {}
531
+ },
532
+ required: ["result"],
533
+ additionalProperties: false
534
+ });
535
+ return { "~standard": {
536
+ version: 1,
537
+ vendor: "statelyai-agent",
538
+ validate(value) {
539
+ if (!value || typeof value !== "object" || !("result" in value)) return { issues: [{ message: "Expected a { result } envelope object" }] };
540
+ const innerResult = inner["~standard"].validate(value.result);
541
+ if (innerResult instanceof Promise) throw new Error("Async schema validation is not supported.");
542
+ if (innerResult.issues) return innerResult;
543
+ const envelope = { result: innerResult.value };
544
+ const reasoning = value.reasoning;
545
+ if (typeof reasoning === "string") envelope.reasoning = reasoning;
546
+ return { value: envelope };
547
+ },
548
+ jsonSchema: { input: () => {
549
+ const innerJson = inner["~standard"].jsonSchema?.input?.();
550
+ return innerJson instanceof Promise ? innerJson.then(buildJson) : buildJson(innerJson);
551
+ } }
552
+ } };
553
+ }
554
+ /**
555
+ * Validates a raw provider value against the structured-output envelope for
556
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
557
+ * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
558
+ * Pair with {@link buildEnvelopeSchema} (which produced the schema the
559
+ * provider was asked to satisfy).
560
+ */
561
+ function parseStructuredEnvelope(request, value) {
562
+ if (!request.outputSchema) throw new Error("parseStructuredEnvelope: the request declares no outputSchema.");
563
+ return validateSchemaSync(buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning }), value);
564
+ }
565
+ function getStandardSchemaJson(schema) {
566
+ const jsonSchema = (schema?.["~standard"])?.jsonSchema?.input?.();
567
+ return jsonSchema && !(jsonSchema instanceof Promise) ? jsonSchema : void 0;
568
+ }
569
+ /**
570
+ * Merges request-declared and call-site `tools`, dispatches to the
571
+ * `mode`-appropriate executor (`generateText`/`streamText`), and normalizes
572
+ * the raw result via {@link normalizeGeneratorResult}. Shared by
573
+ * `TextLogic.execute`, `executeAgentRequest`, and the `agent.generateText`/
574
+ * `agent.streamText` builtins. Throws if no executor is registered for
575
+ * `mode`.
576
+ *
577
+ * @internal
578
+ */
579
+ async function executeAgentTextRequest(mode, id, input, executors, tools = {}, info) {
580
+ const request = {
581
+ ...input,
582
+ tools: {
583
+ ...input.tools,
584
+ ...tools
585
+ }
586
+ };
587
+ const executor = mode === "stream" ? executors.streamText : executors.generateText;
588
+ if (!executor) throw new Error(`No executor provided for ${mode === "stream" ? "stream" : "generate"} request '${id}'.`);
589
+ const raw = await executor(request, info);
590
+ return {
591
+ output: await normalizeGeneratorResult(raw, id, {
592
+ request,
593
+ onChunk: info?.onChunk
594
+ }),
595
+ raw
596
+ };
597
+ }
598
+ function hasTextStream(value) {
599
+ return "textStream" in value && typeof value.textStream === "object" && !!value.textStream?.[Symbol.asyncIterator];
600
+ }
601
+ function parseRawAiSdkText(text, request, id) {
602
+ if (!request?.outputSchema) return text;
603
+ let parsed = text;
604
+ try {
605
+ parsed = JSON.parse(text);
606
+ } catch {}
607
+ try {
608
+ return parseOutput(request.outputSchema, parsed);
609
+ } catch (error) {
610
+ 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)}`);
611
+ }
612
+ }
613
+ /**
614
+ * Unwraps an executor result into the request's final output. Accepts three
615
+ * shapes:
616
+ * - `{ output }` (the {@link AgentRequestExecutorResult} envelope) — awaits and
617
+ * returns `output` (the fast path; unchanged).
618
+ * - a raw AI SDK `streamText` result (`{ textStream }` async iterable) — iterates
619
+ * `textStream`, forwarding each string chunk to `info.onChunk`, then resolves
620
+ * the final text from `await result.text` if present else the accumulated chunks.
621
+ * - a raw AI SDK `generateText` result (`{ text }` string or promise) — awaits `text`.
622
+ *
623
+ * For the two raw AI SDK shapes, if `info.request?.outputSchema` is set the final
624
+ * text is parsed through {@link parseOutput} (best-effort); a parse failure throws
625
+ * an error recommending `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
626
+ *
627
+ * A value matching none of these is a runtime error naming `id`. This is
628
+ * generator-result unwrapping only — decision results are extracted separately
629
+ * by `resolveDecision`.
630
+ *
631
+ * @internal
632
+ */
633
+ async function normalizeGeneratorResult(result, id = "text request", info) {
634
+ const resolved = await result;
635
+ if (!resolved || typeof resolved !== "object") throw invalidGeneratorResult(id);
636
+ if ("output" in resolved) return await resolved.output;
637
+ if (hasTextStream(resolved)) {
638
+ let accumulated = "";
639
+ for await (const chunk of resolved.textStream) {
640
+ accumulated += chunk;
641
+ info?.onChunk?.(chunk);
642
+ }
643
+ const finalText = "text" in resolved && resolved.text !== void 0 ? await resolved.text : accumulated;
644
+ return parseRawAiSdkText(String(finalText), info?.request, id);
645
+ }
646
+ if ("text" in resolved) {
647
+ const finalText = await resolved.text;
648
+ return parseRawAiSdkText(String(finalText), info?.request, id);
649
+ }
650
+ throw invalidGeneratorResult(id);
651
+ }
652
+ function invalidGeneratorResult(id) {
653
+ 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.`);
654
+ }
655
+ //#endregion
656
+ //#region src/events.ts
657
+ /** Default prefix for the synthetic tool name generated per candidate event (e.g. `send_event_ASK`). Override per-request with {@link AgentEventToolNameResolver}. */
658
+ const EVENT_TOOL_PREFIX = "send_event_";
659
+ function hashString(value) {
660
+ let hash = 5381;
661
+ for (let i = 0; i < value.length; i++) hash = hash * 33 ^ value.charCodeAt(i);
662
+ return (hash >>> 0).toString(36);
663
+ }
664
+ function sanitizeEventToolName(eventType) {
665
+ const base = `${EVENT_TOOL_PREFIX}${eventType.replace(/[^a-zA-Z0-9_-]/g, "_") || "event"}`;
666
+ if (base.length <= 64) return base;
667
+ const hash = hashString(eventType);
668
+ const prefixLength = 64 - hash.length - 1;
669
+ return `${base.slice(0, prefixLength)}_${hash}`;
670
+ }
671
+ function disambiguateEventToolName(toolName, eventType, usedToolNames) {
672
+ if (!usedToolNames.has(toolName)) {
673
+ usedToolNames.add(toolName);
674
+ return toolName;
675
+ }
676
+ const suffix = `_${hashString(eventType)}`;
677
+ const uniqueToolName = `${toolName.slice(0, 64 - suffix.length)}${suffix}`;
678
+ usedToolNames.add(uniqueToolName);
679
+ return uniqueToolName;
680
+ }
681
+ /**
682
+ * True when an event type matches an `allowedEvents` entry: an exact type,
683
+ * `'*'` (every event), or a `'prefix.*'` wildcard matching any deeper
684
+ * segment (`'todo.*'` matches `'todo.add'` and `'todo.list.clear'`, not
685
+ * `'todo'` itself — mirroring xstate's partial wildcard events).
686
+ */
687
+ function matchesEventPattern(eventType, pattern) {
688
+ if (pattern === "*") return true;
689
+ if (pattern.endsWith(".*")) return eventType.startsWith(`${pattern.slice(0, -1)}`);
690
+ return eventType === pattern;
691
+ }
692
+ /** True when an `allowedEvents` entry is a wildcard pattern rather than a concrete event type. @internal */
693
+ function isEventPattern(entry) {
694
+ return entry === "*" || entry.endsWith(".*");
695
+ }
696
+ /**
697
+ * Runtime-validates a dynamically-built `{ type, ...payload }` event against a
698
+ * snapshot's currently-accepted events (via {@link getAcceptedEvents}) and,
699
+ * when one is registered, the event type's payload schema — returning the
700
+ * event typed as the machine's event union (recovered from the snapshot type)
701
+ * so it can be sent to `runAgent({ event })` / `actor.send(...)` without an
702
+ * `as never` cast. For generic, meta-driven hosts that assemble events from
703
+ * user input or a wire message.
704
+ *
705
+ * Throws a descriptive error when `event.type` is not currently accepted
706
+ * (listing the accepted types) or when its payload fails the registered schema.
707
+ * Pass event payload schemas via `options.events`/`options.schemas` (the same
708
+ * shape {@link getAcceptedEvents} takes) — the accepted TYPES always come from
709
+ * the live snapshot; the schemas only add payload validation.
710
+ *
711
+ * @example
712
+ * ```ts
713
+ * const event = parseAgentEvent(result.snapshot, rawEvent, { events: schemas.events });
714
+ * result = await runAgent(machine, { snapshot: result.snapshot, event, executors });
715
+ * ```
716
+ */
717
+ function parseAgentEvent(snapshot, event, options = {}) {
718
+ const accepted = getAcceptedEvents(snapshot, options);
719
+ const descriptor = accepted.find((candidate) => candidate.type === event.type);
720
+ if (!descriptor) throw new Error(`parseAgentEvent: '${event.type}' is not an accepted event in the current state. Accepted: ${accepted.map((candidate) => candidate.type).join(", ") || "(none)"}.`);
721
+ if (descriptor.inputSchema) {
722
+ const { type, ...payload } = event;
723
+ try {
724
+ return {
725
+ ...validateSchemaSync(descriptor.inputSchema, payload),
726
+ type
727
+ };
728
+ } catch (error) {
729
+ throw new Error(`parseAgentEvent: '${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`);
730
+ }
731
+ }
732
+ return event;
733
+ }
734
+ function getAcceptedEvents(snapshot, options = {}) {
735
+ const eventTypes = options.eventTypes;
736
+ const seen = /* @__PURE__ */ new Set();
737
+ const usedToolNames = /* @__PURE__ */ new Set();
738
+ return (0, xstate.getNextTransitions)(snapshot).flatMap((transitionDefinition) => {
739
+ const eventType = transitionDefinition.eventType;
740
+ if (!eventType || eventType === "*" || eventType.startsWith("xstate.") || eventTypes && !eventTypes.some((pattern) => matchesEventPattern(eventType, pattern)) || seen.has(eventType)) return [];
741
+ seen.add(eventType);
742
+ const defaultToolName = sanitizeEventToolName(eventType);
743
+ const toolName = options.eventToolName ? options.eventToolName({
744
+ eventType,
745
+ defaultToolName
746
+ }) : disambiguateEventToolName(defaultToolName, eventType, usedToolNames);
747
+ const inputSchema = (options.events ?? options.schemas?.events)?.[eventType];
748
+ return [{
749
+ type: eventType,
750
+ toolName,
751
+ ...inputSchema ? { inputSchema } : {}
752
+ }];
753
+ });
754
+ }
755
+ //#endregion
756
+ //#region src/decision.ts
757
+ function decideRequestFromInput(input) {
758
+ const allowedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input) ?? [];
759
+ return {
760
+ kind: "decision",
761
+ id: "",
762
+ model: input.model,
763
+ system: input.system,
764
+ prompt: input.prompt,
765
+ messages: input.messages,
766
+ events: allowedEventTypes.filter((type) => !isEventPattern(type)).map((type) => ({
767
+ type,
768
+ toolName: sanitizeEventToolName(type)
769
+ })),
770
+ attempts: [],
771
+ temperature: input.temperature,
772
+ maxOutputTokens: input.maxOutputTokens,
773
+ topP: input.topP,
774
+ topK: input.topK,
775
+ seed: input.seed,
776
+ stopSequences: input.stopSequences,
777
+ metadata: input.metadata
778
+ };
779
+ }
780
+ function decideActorWithExecutor(execute) {
781
+ const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal }) => {
782
+ if (!execute) throw new Error(`'${DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${DECIDE_ACTOR}': ... } }) or resolve the returned agent request with resolveDecision(...).`);
783
+ const resolvedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input);
784
+ 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.`);
785
+ 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.`);
786
+ return resolveDecision(decideRequestFromInput(input), execute, {
787
+ maxRetries: input.maxRetries ?? 2,
788
+ signal
789
+ });
790
+ } });
791
+ return Object.assign(logic, {
792
+ kind: "statelyai.decisionLogic",
793
+ maxRetries: 2,
794
+ request: decideRequestFromInput,
795
+ allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input),
796
+ withExecutor: (nextExecute) => decideActorWithExecutor(nextExecute)
797
+ });
798
+ }
799
+ function createDecideActor() {
800
+ return decideActorWithExecutor();
801
+ }
802
+ /**
803
+ * Reserved event type the `agent.plan` builtin adds to every step's
804
+ * candidates as the explicit "no further action needed" move. Choosing it
805
+ * ends the plan (`stopped: 'done'`); it is never sent to the machine, so
806
+ * machines need no no-op sentinel event of their own.
807
+ */
808
+ const PLAN_DONE_EVENT_TYPE = "agent.plan.done";
809
+ function createPlanActor() {
810
+ const logic = (0, xstate.createLogic)({
811
+ context: ({ input }) => ({
812
+ applied: [],
813
+ stepsRemaining: input.maxSteps ?? 8,
814
+ stopped: null
815
+ }),
816
+ run: ({ context, event }) => event.type === "plan.applied" ? { context: {
817
+ ...context,
818
+ applied: [...context.applied, event.event],
819
+ stepsRemaining: context.stepsRemaining - 1
820
+ } } : event.type === "plan.ended" ? {
821
+ context: {
822
+ ...context,
823
+ stopped: event.stopped
824
+ },
825
+ status: "done",
826
+ output: {
827
+ steps: context.applied,
828
+ stopped: event.stopped
829
+ }
830
+ } : void 0
831
+ });
832
+ return Object.assign(logic, {
833
+ kind: "statelyai.planLogic",
834
+ maxRetries: 2,
835
+ request: decideRequestFromInput,
836
+ allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input)
837
+ });
838
+ }
839
+ const PLAN_LEDGER_SCOPE = { emit: () => {} };
840
+ /**
841
+ * Builds a fresh plan ledger snapshot from resolved plan input — the shared
842
+ * starting point for BOTH hosts (the step path reads the invoke child's own
843
+ * initial snapshot; runAgent seeds a local ledger with this). @internal
844
+ */
845
+ function initialPlanLedger(logic, input) {
846
+ return logic.getInitialSnapshot(PLAN_LEDGER_SCOPE, input);
847
+ }
848
+ /**
849
+ * Advances a plan ledger by one {@link PlanLedgerEvent}, returning the next
850
+ * snapshot (unwrapping `createLogic`'s `[snapshot, effects]` tuple). Pure — no
851
+ * mutation of the input snapshot. @internal
852
+ */
853
+ function advancePlanLedger(logic, snapshot, event) {
854
+ const result = logic.transition(snapshot, event, PLAN_LEDGER_SCOPE);
855
+ return Array.isArray(result) ? result[0] : result;
856
+ }
857
+ /** Type guard: true for the `agent.plan` builtin logic (checks the `kind` marker). @internal */
858
+ function isPlanLogic(logic) {
859
+ return !!logic && logic.kind === "statelyai.planLogic";
860
+ }
861
+ function resolveAllowedEventTypes(allowedEvents, input) {
862
+ if (allowedEvents === void 0) return;
863
+ const resolved = typeof allowedEvents === "function" ? allowedEvents({ input }) : allowedEvents;
864
+ return typeof resolved === "string" ? [resolved] : resolved;
865
+ }
866
+ /** Type guard: true for any actor logic built by createDecisionLogic/createDecideActor (checks the `kind` marker). @internal */
867
+ function isDecisionLogic(value) {
868
+ return !!value && typeof value === "object" && value.kind === "statelyai.decisionLogic" && typeof value.request === "function";
869
+ }
870
+ /**
871
+ * Thrown by {@link resolveDecision} when every attempt (up to
872
+ * `maxRetries + 1` of them) fails one of the three checks recorded in
873
+ * {@link DecisionAttempt.failure}. Carries the full `attempts` list for
874
+ * diagnostics; a machine typically routes this via the decision invoke's
875
+ * `onError`.
876
+ */
877
+ var DecisionExhaustedError = class extends Error {
878
+ attempts;
879
+ constructor(attempts) {
880
+ super(`Decision exhausted after ${attempts.length} attempt${attempts.length === 1 ? "" : "s"}: ` + attempts.map((attempt) => attempt.reason).join("; "));
881
+ this.name = "DecisionExhaustedError";
882
+ this.attempts = attempts;
883
+ }
884
+ };
885
+ /**
886
+ * Renders a decision request's prior failed `attempts` into feedback messages
887
+ * a host appends to the model call so retries converge — the transport-agnostic
888
+ * "your last choice failed because X, choose again from Y" logic every adapter
889
+ * and raw-SDK host repeats. Returns one `user`-role {@link AgentMessage} per
890
+ * attempt (empty when there are none); adapters map each onto their wire
891
+ * message shape (`attempt.content` is always a string). Core never rewrites the
892
+ * request itself — this only turns the recorded attempts into messages.
893
+ *
894
+ * @example
895
+ * ```ts
896
+ * const messages = [...baseMessages, ...renderDecisionAttempts(request)];
897
+ * ```
898
+ */
899
+ function renderDecisionAttempts(request) {
900
+ const types = request.events.map((event) => event.type).join(", ") || "(none)";
901
+ return request.attempts.map((attempt) => userMessage(`Your previous choice failed: ${attempt.reason}. Choose again from: ${types}`));
902
+ }
903
+ /**
904
+ * Validation + retry core for decisions. No provider mechanics — the
905
+ * `executor` is responsible for making the model choose an event; this
906
+ * function only validates the choice and retries on failure, up to
907
+ * `options.maxRetries` (default 2, i.e. up to 3 attempts total).
908
+ *
909
+ * Each attempt is checked in order and can fail one of three ways (recorded
910
+ * as a {@link DecisionAttempt}): `'unknown-event'` (the chosen `type` is not
911
+ * among `request.events`), `'invalid-payload'` (the payload fails that
912
+ * event's schema), or `'rejected-by-guard'` (passes both checks but
913
+ * `options.canTake` returns `false` — a type/payload-legal event the
914
+ * machine's guard rejects right now; omit `canTake` to skip this check).
915
+ * Every prior failed attempt for this call is fed back to the executor on
916
+ * the next attempt via `request.attempts`, so an adapter can render "your
917
+ * last choice failed because X — try again" into the next model call; core
918
+ * never rewrites the request itself. Exhausting all attempts throws
919
+ * {@link DecisionExhaustedError} with the full attempts list.
920
+ *
921
+ * @example
922
+ * ```ts
923
+ * const event = await resolveDecision(request, decide, {
924
+ * canTake: (e) => snapshot.can(e),
925
+ * });
926
+ * ```
927
+ */
928
+ async function resolveDecision(request, executor, options = {}) {
929
+ const maxRetries = options.maxRetries ?? 2;
930
+ const attempts = [];
931
+ const eventsByType = new Map(request.events.map((event) => [event.type, event]));
932
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
933
+ options.signal?.throwIfAborted();
934
+ const { event } = await executor({
935
+ ...request,
936
+ attempts: [...attempts],
937
+ signal: options.signal
938
+ });
939
+ const descriptor = eventsByType.get(event.type);
940
+ if (!descriptor) {
941
+ attempts.push({
942
+ event,
943
+ failure: "unknown-event",
944
+ reason: `'${event.type}' is not among the currently allowed events: ${request.events.map((candidate) => candidate.type).join(", ") || "(none)"}.`
945
+ });
946
+ continue;
947
+ }
948
+ let validatedEvent = event;
949
+ if (descriptor.inputSchema) {
950
+ const { type, ...payload } = event;
951
+ try {
952
+ validatedEvent = {
953
+ ...validateSchemaSync(descriptor.inputSchema, payload),
954
+ type
955
+ };
956
+ } catch (error) {
957
+ attempts.push({
958
+ event,
959
+ failure: "invalid-payload",
960
+ reason: `'${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`
961
+ });
962
+ continue;
963
+ }
964
+ }
965
+ if (options.canTake?.(validatedEvent) === false) {
966
+ attempts.push({
967
+ event: validatedEvent,
968
+ failure: "rejected-by-guard",
969
+ reason: `'${validatedEvent.type}' is not currently takeable (guard rejected it).`
970
+ });
971
+ continue;
972
+ }
973
+ return validatedEvent;
974
+ }
975
+ throw new DecisionExhaustedError(attempts);
976
+ }
977
+ //#endregion
978
+ Object.defineProperty(exports, "DECIDE_ACTOR", {
979
+ enumerable: true,
980
+ get: function() {
981
+ return DECIDE_ACTOR;
982
+ }
983
+ });
984
+ Object.defineProperty(exports, "DecisionExhaustedError", {
985
+ enumerable: true,
986
+ get: function() {
987
+ return DecisionExhaustedError;
988
+ }
989
+ });
990
+ Object.defineProperty(exports, "EVENT_TOOL_PREFIX", {
991
+ enumerable: true,
992
+ get: function() {
993
+ return EVENT_TOOL_PREFIX;
994
+ }
995
+ });
996
+ Object.defineProperty(exports, "INTERPRET_SOURCE", {
997
+ enumerable: true,
998
+ get: function() {
999
+ return INTERPRET_SOURCE;
1000
+ }
1001
+ });
1002
+ Object.defineProperty(exports, "PLAN_ACTOR", {
1003
+ enumerable: true,
1004
+ get: function() {
1005
+ return PLAN_ACTOR;
1006
+ }
1007
+ });
1008
+ Object.defineProperty(exports, "PLAN_DONE_EVENT_TYPE", {
1009
+ enumerable: true,
1010
+ get: function() {
1011
+ return PLAN_DONE_EVENT_TYPE;
1012
+ }
1013
+ });
1014
+ Object.defineProperty(exports, "USER_INPUT_ACTOR", {
1015
+ enumerable: true,
1016
+ get: function() {
1017
+ return USER_INPUT_ACTOR;
1018
+ }
1019
+ });
1020
+ Object.defineProperty(exports, "advancePlanLedger", {
1021
+ enumerable: true,
1022
+ get: function() {
1023
+ return advancePlanLedger;
1024
+ }
1025
+ });
1026
+ Object.defineProperty(exports, "agentExecutionOptions", {
1027
+ enumerable: true,
1028
+ get: function() {
1029
+ return agentExecutionOptions;
1030
+ }
1031
+ });
1032
+ Object.defineProperty(exports, "assistantMessage", {
1033
+ enumerable: true,
1034
+ get: function() {
1035
+ return assistantMessage;
1036
+ }
1037
+ });
1038
+ Object.defineProperty(exports, "bindRequestExecutor", {
1039
+ enumerable: true,
1040
+ get: function() {
1041
+ return bindRequestExecutor;
1042
+ }
1043
+ });
1044
+ Object.defineProperty(exports, "buildEnvelopeSchema", {
1045
+ enumerable: true,
1046
+ get: function() {
1047
+ return buildEnvelopeSchema;
1048
+ }
1049
+ });
1050
+ Object.defineProperty(exports, "builtinTextActors", {
1051
+ enumerable: true,
1052
+ get: function() {
1053
+ return builtinTextActors;
1054
+ }
1055
+ });
1056
+ Object.defineProperty(exports, "createDecideActor", {
1057
+ enumerable: true,
1058
+ get: function() {
1059
+ return createDecideActor;
1060
+ }
1061
+ });
1062
+ Object.defineProperty(exports, "createPlanActor", {
1063
+ enumerable: true,
1064
+ get: function() {
1065
+ return createPlanActor;
1066
+ }
1067
+ });
1068
+ Object.defineProperty(exports, "createTextLogic", {
1069
+ enumerable: true,
1070
+ get: function() {
1071
+ return createTextLogic;
1072
+ }
1073
+ });
1074
+ Object.defineProperty(exports, "executeAgentTextRequest", {
1075
+ enumerable: true,
1076
+ get: function() {
1077
+ return executeAgentTextRequest;
1078
+ }
1079
+ });
1080
+ Object.defineProperty(exports, "executorBoundLogics", {
1081
+ enumerable: true,
1082
+ get: function() {
1083
+ return executorBoundLogics;
1084
+ }
1085
+ });
1086
+ Object.defineProperty(exports, "findNonSerializableContextPaths", {
1087
+ enumerable: true,
1088
+ get: function() {
1089
+ return findNonSerializableContextPaths;
1090
+ }
1091
+ });
1092
+ Object.defineProperty(exports, "getAcceptedEvents", {
1093
+ enumerable: true,
1094
+ get: function() {
1095
+ return getAcceptedEvents;
1096
+ }
1097
+ });
1098
+ Object.defineProperty(exports, "getAgentMessages", {
1099
+ enumerable: true,
1100
+ get: function() {
1101
+ return getAgentMessages;
1102
+ }
1103
+ });
1104
+ Object.defineProperty(exports, "getAgentOutputMode", {
1105
+ enumerable: true,
1106
+ get: function() {
1107
+ return getAgentOutputMode;
1108
+ }
1109
+ });
1110
+ Object.defineProperty(exports, "getJsonSchema", {
1111
+ enumerable: true,
1112
+ get: function() {
1113
+ return getJsonSchema;
1114
+ }
1115
+ });
1116
+ Object.defineProperty(exports, "getJsonSchemaSync", {
1117
+ enumerable: true,
1118
+ get: function() {
1119
+ return getJsonSchemaSync;
1120
+ }
1121
+ });
1122
+ Object.defineProperty(exports, "getMachineStructuralHash", {
1123
+ enumerable: true,
1124
+ get: function() {
1125
+ return getMachineStructuralHash;
1126
+ }
1127
+ });
1128
+ Object.defineProperty(exports, "getMachineSuspensionPredicate", {
1129
+ enumerable: true,
1130
+ get: function() {
1131
+ return getMachineSuspensionPredicate;
1132
+ }
1133
+ });
1134
+ Object.defineProperty(exports, "getRegisteredAgentExecutionOptions", {
1135
+ enumerable: true,
1136
+ get: function() {
1137
+ return getRegisteredAgentExecutionOptions;
1138
+ }
1139
+ });
1140
+ Object.defineProperty(exports, "getRegisteredAgentModels", {
1141
+ enumerable: true,
1142
+ get: function() {
1143
+ return getRegisteredAgentModels;
1144
+ }
1145
+ });
1146
+ Object.defineProperty(exports, "getStateMeta", {
1147
+ enumerable: true,
1148
+ get: function() {
1149
+ return getStateMeta;
1150
+ }
1151
+ });
1152
+ Object.defineProperty(exports, "initialPlanLedger", {
1153
+ enumerable: true,
1154
+ get: function() {
1155
+ return initialPlanLedger;
1156
+ }
1157
+ });
1158
+ Object.defineProperty(exports, "isDecisionLogic", {
1159
+ enumerable: true,
1160
+ get: function() {
1161
+ return isDecisionLogic;
1162
+ }
1163
+ });
1164
+ Object.defineProperty(exports, "isPlanLogic", {
1165
+ enumerable: true,
1166
+ get: function() {
1167
+ return isPlanLogic;
1168
+ }
1169
+ });
1170
+ Object.defineProperty(exports, "isStandardSchema", {
1171
+ enumerable: true,
1172
+ get: function() {
1173
+ return isStandardSchema;
1174
+ }
1175
+ });
1176
+ Object.defineProperty(exports, "isStructuredOutputSchema", {
1177
+ enumerable: true,
1178
+ get: function() {
1179
+ return isStructuredOutputSchema;
1180
+ }
1181
+ });
1182
+ Object.defineProperty(exports, "isTextLogic", {
1183
+ enumerable: true,
1184
+ get: function() {
1185
+ return isTextLogic;
1186
+ }
1187
+ });
1188
+ Object.defineProperty(exports, "isUnboundPlaceholder", {
1189
+ enumerable: true,
1190
+ get: function() {
1191
+ return isUnboundPlaceholder;
1192
+ }
1193
+ });
1194
+ Object.defineProperty(exports, "machineSuspensionPredicates", {
1195
+ enumerable: true,
1196
+ get: function() {
1197
+ return machineSuspensionPredicates;
1198
+ }
1199
+ });
1200
+ Object.defineProperty(exports, "matchesEventPattern", {
1201
+ enumerable: true,
1202
+ get: function() {
1203
+ return matchesEventPattern;
1204
+ }
1205
+ });
1206
+ Object.defineProperty(exports, "missingActor", {
1207
+ enumerable: true,
1208
+ get: function() {
1209
+ return missingActor;
1210
+ }
1211
+ });
1212
+ Object.defineProperty(exports, "normalizeGeneratorResult", {
1213
+ enumerable: true,
1214
+ get: function() {
1215
+ return normalizeGeneratorResult;
1216
+ }
1217
+ });
1218
+ Object.defineProperty(exports, "parseAgentEvent", {
1219
+ enumerable: true,
1220
+ get: function() {
1221
+ return parseAgentEvent;
1222
+ }
1223
+ });
1224
+ Object.defineProperty(exports, "parseModelRef", {
1225
+ enumerable: true,
1226
+ get: function() {
1227
+ return parseModelRef;
1228
+ }
1229
+ });
1230
+ Object.defineProperty(exports, "parseOutput", {
1231
+ enumerable: true,
1232
+ get: function() {
1233
+ return parseOutput;
1234
+ }
1235
+ });
1236
+ Object.defineProperty(exports, "parseStructuredEnvelope", {
1237
+ enumerable: true,
1238
+ get: function() {
1239
+ return parseStructuredEnvelope;
1240
+ }
1241
+ });
1242
+ Object.defineProperty(exports, "persistSnapshot", {
1243
+ enumerable: true,
1244
+ get: function() {
1245
+ return persistSnapshot;
1246
+ }
1247
+ });
1248
+ Object.defineProperty(exports, "renderDecisionAttempts", {
1249
+ enumerable: true,
1250
+ get: function() {
1251
+ return renderDecisionAttempts;
1252
+ }
1253
+ });
1254
+ Object.defineProperty(exports, "resolveDecision", {
1255
+ enumerable: true,
1256
+ get: function() {
1257
+ return resolveDecision;
1258
+ }
1259
+ });
1260
+ Object.defineProperty(exports, "sanitizeEventToolName", {
1261
+ enumerable: true,
1262
+ get: function() {
1263
+ return sanitizeEventToolName;
1264
+ }
1265
+ });
1266
+ Object.defineProperty(exports, "systemMessage", {
1267
+ enumerable: true,
1268
+ get: function() {
1269
+ return systemMessage;
1270
+ }
1271
+ });
1272
+ Object.defineProperty(exports, "toolMessage", {
1273
+ enumerable: true,
1274
+ get: function() {
1275
+ return toolMessage;
1276
+ }
1277
+ });
1278
+ Object.defineProperty(exports, "userInputActor", {
1279
+ enumerable: true,
1280
+ get: function() {
1281
+ return userInputActor;
1282
+ }
1283
+ });
1284
+ Object.defineProperty(exports, "userMessage", {
1285
+ enumerable: true,
1286
+ get: function() {
1287
+ return userMessage;
1288
+ }
1289
+ });
1290
+ Object.defineProperty(exports, "validateSchemaSync", {
1291
+ enumerable: true,
1292
+ get: function() {
1293
+ return validateSchemaSync;
1294
+ }
1295
+ });