@statelyai/agent 2.0.0-alpha.23 → 2.0.0-alpha.25

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 +1222 -0
  36. package/dist/testing.d.cts +602 -0
  37. package/dist/testing.d.mts +602 -0
  38. package/dist/testing.mjs +1212 -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-C1p37X_c.d.mts +209 -0
  48. package/dist/utils-RalRn9sk.d.cts +209 -0
  49. package/package.json +24 -4
  50. package/readme.md +2 -2
  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
@@ -0,0 +1,833 @@
1
+ import { createAsyncLogic } 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 JSON 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/utils.ts
58
+ /** Returns the human-readable text carried by a message, ignoring non-text parts. */
59
+ function getMessageText(message) {
60
+ if (typeof message.content === "string") return message.content;
61
+ const text = [];
62
+ for (const part of message.content) {
63
+ if (part.type === "text") {
64
+ text.push(part.text);
65
+ continue;
66
+ }
67
+ if (part.type !== "tool-result") continue;
68
+ if (part.output.type === "text" || part.output.type === "error-text") text.push(part.output.value);
69
+ else if (part.output.type === "content") text.push(...part.output.value.flatMap((item) => item.type === "text" ? [item.text] : []));
70
+ }
71
+ return text.join("\n");
72
+ }
73
+ /**
74
+ * Walks a context value and returns the dot-paths of the first few values that
75
+ * would NOT survive a JSON persist/resume round-trip (persist with XState's
76
+ * `actor.getPersistedSnapshot()`, resume with `createActor(machine, { snapshot })`):
77
+ * `Date`, `Map`, `Set`, `RegExp`, functions, `undefined`, `bigint`, class
78
+ * instances (non-plain objects), and circular references. Plain objects,
79
+ * arrays, and JSON primitives are walked/allowed. Returns `[]` for a
80
+ * fully-JSON-safe value. Cheap and bounded (stops after `limit` findings) —
81
+ * intended for a dev-only warning at the moment persistence matters.
82
+ */
83
+ function findNonSerializableContextPaths(context, limit = 5) {
84
+ const paths = [];
85
+ const seen = /* @__PURE__ */ new WeakSet();
86
+ const walk = (value, path) => {
87
+ if (paths.length >= limit) return;
88
+ if (value === null) return;
89
+ const type = typeof value;
90
+ if (type === "string" || type === "number" || type === "boolean") return;
91
+ if (type === "undefined" || type === "bigint" || type === "function" || type === "symbol") {
92
+ paths.push(`${path} (${type})`);
93
+ return;
94
+ }
95
+ const obj = value;
96
+ if (seen.has(obj)) {
97
+ paths.push(`${path} (circular)`);
98
+ return;
99
+ }
100
+ if (Array.isArray(value)) {
101
+ seen.add(obj);
102
+ value.forEach((item, index) => walk(item, `${path}[${index}]`));
103
+ seen.delete(obj);
104
+ return;
105
+ }
106
+ const proto = Object.getPrototypeOf(value);
107
+ if (proto === Object.prototype || proto === null) {
108
+ seen.add(obj);
109
+ for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`);
110
+ seen.delete(obj);
111
+ return;
112
+ }
113
+ const ctorName = value.constructor?.name ?? "object";
114
+ paths.push(`${path} (${ctorName})`);
115
+ };
116
+ walk(context, "context");
117
+ return paths;
118
+ }
119
+ /**
120
+ * A stable, dependency-free structural fingerprint of a machine — a short hex
121
+ * `djb2` hash over its **structural** config only: state ids/nesting, transition
122
+ * event types and targets, invoke `src`s, `initial`, and any other serializable
123
+ * config fields. Function values (context/output builders, prompts, inline
124
+ * guards/actions) are excluded entirely, so two machines that differ only in
125
+ * their prompts or executors hash identically; adding/removing/retargeting a
126
+ * state or transition changes the hash.
127
+ *
128
+ * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
129
+ * detect a structurally-edited machine on resume. It is a change detector, not
130
+ * a cryptographic digest — collisions are possible but unlikely for real
131
+ * configs. Declare `createMachine({ version })` to pin an explicit version instead.
132
+ */
133
+ function getMachineStructuralHash(machine) {
134
+ return djb2Hex(stableStructuralString(machine.config));
135
+ }
136
+ /**
137
+ * The version a machine is stamped with everywhere: an explicitly declared
138
+ * `createMachine({ version })` when present, else its
139
+ * {@link getMachineStructuralHash}. Single source of truth so `runAgent`,
140
+ * `provideExecutors`/`traceTransitions` trace envelopes agree.
141
+ * @internal
142
+ */
143
+ function resolveMachineVersion(machine) {
144
+ return machine.version ?? getMachineStructuralHash(machine);
145
+ }
146
+ function stableStructuralString(value, seen = /* @__PURE__ */ new WeakSet()) {
147
+ if (value === null) return "null";
148
+ const type = typeof value;
149
+ if (type === "function" || type === "undefined" || type === "symbol") return "";
150
+ if (type === "string") return JSON.stringify(value);
151
+ if (type === "number" || type === "boolean") return String(value);
152
+ if (type === "bigint") return `${value}n`;
153
+ const obj = value;
154
+ if (seen.has(obj)) return "\"[circular]\"";
155
+ seen.add(obj);
156
+ let out;
157
+ if (Array.isArray(value)) out = `[${value.map((item) => stableStructuralString(item, seen)).join(",")}]`;
158
+ else {
159
+ const parts = [];
160
+ for (const key of Object.keys(obj).sort()) {
161
+ const child = obj[key];
162
+ const childType = typeof child;
163
+ if (childType === "function" || childType === "undefined" || childType === "symbol") continue;
164
+ parts.push(`${JSON.stringify(key)}:${stableStructuralString(child, seen)}`);
165
+ }
166
+ out = `{${parts.join(",")}}`;
167
+ }
168
+ seen.delete(obj);
169
+ return out;
170
+ }
171
+ /**
172
+ * djb2 → unsigned 32-bit → 8-char hex. No dependencies. A change detector, not
173
+ * a cryptographic digest.
174
+ *
175
+ * @internal
176
+ */
177
+ function djb2Hex(input) {
178
+ let hash = 5381;
179
+ for (let i = 0; i < input.length; i++) hash = (hash << 5) + hash + input.charCodeAt(i) | 0;
180
+ return (hash >>> 0).toString(16).padStart(8, "0");
181
+ }
182
+ /** Builds a {@link UserMessage} from a string or multimodal content parts. */
183
+ function userMessage(content) {
184
+ return {
185
+ role: "user",
186
+ content
187
+ };
188
+ }
189
+ /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
190
+ function assistantMessage(content) {
191
+ return {
192
+ role: "assistant",
193
+ content
194
+ };
195
+ }
196
+ /** Builds a {@link SystemMessage}. */
197
+ function systemMessage(content) {
198
+ return {
199
+ role: "system",
200
+ content
201
+ };
202
+ }
203
+ /** Builds a {@link ToolMessage} from one or more tool-result parts. */
204
+ function toolMessage(content) {
205
+ return {
206
+ role: "tool",
207
+ content
208
+ };
209
+ }
210
+ /**
211
+ * Returns the merged `meta` of a snapshot's active state(s) — the typed
212
+ * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
213
+ *
214
+ * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
215
+ * state, but parallel/nested machines can have several. This shallow-merges
216
+ * every active state's meta into one object and returns `{}` when no active
217
+ * state declares meta.
218
+ *
219
+ * Merge order is fixed and does not depend on XState's internal node order:
220
+ * entries are sorted by structural depth (the state node's distance from the
221
+ * root, regardless of custom `id` strings), then by state id lexicographically,
222
+ * and merged in that order. So a deeper state's key wins over an ancestor's,
223
+ * and between equal-depth parallel siblings the later state id alphabetically
224
+ * wins.
225
+ *
226
+ * The return type is recovered from the snapshot's own `getMeta()` type, so a
227
+ * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
228
+ * output type. Pass an explicit `TMeta` to override when the snapshot is
229
+ * untyped (e.g. `AnyMachineSnapshot`).
230
+ *
231
+ * @example HITL: read the current state's interaction protocol off an idle
232
+ * snapshot to render for a human.
233
+ * ```ts
234
+ * const { interaction } = getStateMeta(result.snapshot);
235
+ * ```
236
+ */
237
+ function getStateMeta(snapshot) {
238
+ const nodes = snapshot.nodes;
239
+ const depthById = new Map(nodes?.map((node) => [node.id, node.path.length]));
240
+ const depth = (id) => depthById.get(id) ?? id.split(".").length;
241
+ 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));
242
+ return Object.assign({}, ...entries.map(([, meta]) => meta));
243
+ }
244
+ /**
245
+ * Renders a snapshot's state value as one deterministic string, so a log line,
246
+ * a progress field, or a test assertion reads the same on every run.
247
+ *
248
+ * - An atomic state is its own name: `'writing'`.
249
+ * - A nested state joins with dots: `{ review: { editing: 'draft' } }` →
250
+ * `'review.editing.draft'`.
251
+ * - A parallel state brackets its regions, sorted by region name, so key order
252
+ * never leaks into the string: `{ p: { left: 'x', right: { a: 'b' } } }` →
253
+ * `'p:{left.x,right.a.b}'`.
254
+ *
255
+ * Prefer this over `String(snapshot.value)`, which renders every non-atomic
256
+ * value as `[object Object]`.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * onTransition: (snapshot) => console.log(getStatePath(snapshot));
261
+ * ```
262
+ */
263
+ function getStatePath(snapshot) {
264
+ return serializeStateValue(typeof snapshot === "object" && snapshot !== null && "value" in snapshot && ("status" in snapshot || typeof snapshot.matches === "function") ? snapshot.value : snapshot);
265
+ }
266
+ function serializeStateValue(value) {
267
+ if (typeof value === "string") return value;
268
+ const entries = Object.entries(value).map(([key, child]) => {
269
+ const rendered = serializeStateValue(child);
270
+ if (!rendered) return [key, key];
271
+ return [key, `${key}${rendered.startsWith("{") ? ":" : "."}${rendered}`];
272
+ }).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
273
+ if (entries.length === 0) return "";
274
+ if (entries.length === 1) return entries[0][1];
275
+ return `{${entries.map(([, rendered]) => rendered).join(",")}}`;
276
+ }
277
+ /**
278
+ * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
279
+ * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
280
+ * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
281
+ * can't read directly — see the `ai-sdk` tool pass-through.
282
+ */
283
+ function isStandardSchema(value) {
284
+ return typeof value === "object" && value !== null && "~standard" in value;
285
+ }
286
+ /**
287
+ * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
288
+ * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
289
+ * `z.toJSONSchema`), awaiting it when the producer is async. Returns
290
+ * `undefined` when the schema doesn't expose the extension. Use this to build
291
+ * a provider request's `response_format`/tool `parameters` from a schema.
292
+ */
293
+ async function getJsonSchema(schema) {
294
+ const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
295
+ if (!jsonSchemaFn) return;
296
+ const result = jsonSchemaFn();
297
+ return result instanceof Promise ? await result : result;
298
+ }
299
+ /**
300
+ * Synchronous variant of {@link getJsonSchema}, for call sites that can't
301
+ * await (building tool/event descriptors inline). An async JSON Schema
302
+ * producer is treated as absent (returns `undefined`) — in practice Zod's
303
+ * `z.toJSONSchema` resolves synchronously.
304
+ */
305
+ function getJsonSchemaSync(schema) {
306
+ const jsonSchemaFn = schema?.["~standard"].jsonSchema?.input;
307
+ if (!jsonSchemaFn) return;
308
+ const result = jsonSchemaFn();
309
+ return result instanceof Promise ? void 0 : result;
310
+ }
311
+ /**
312
+ * Validates `value` against a {@link StandardSchemaV1}, synchronously.
313
+ * Throws if the schema's `validate` returns a `Promise` (async validation is
314
+ * not supported anywhere in this library) or if validation reports issues —
315
+ * in which case the thrown `Error.message` joins every issue message with
316
+ * `', '`.
317
+ */
318
+ function validateSchemaSync(schema, value) {
319
+ const result = schema["~standard"].validate(value);
320
+ if (result instanceof Promise) throw new Error("Async schema validation is not supported.");
321
+ if (result.issues) throw new Error(result.issues.map((issue) => issue.message).join(", "));
322
+ return result.value;
323
+ }
324
+ //#endregion
325
+ //#region src/internal/registry.ts
326
+ /**
327
+ * Registered execution options, keyed on BOTH the machine object and its root
328
+ * `config` object. `config` is shared by reference across `machine.provide(...)`
329
+ * (unlike the machine itself), so the `config` key is what lets a machine
330
+ * rebound by `runAgent` — or by any host `.provide(...)` — still resolve the
331
+ * schemas/actors `setupAgent` registered. Always write through
332
+ * {@link setAgentExecutionOptions} and read through
333
+ * {@link getAgentExecutionOptions}.
334
+ */
335
+ const agentExecutionOptions = /* @__PURE__ */ new WeakMap();
336
+ /** The root `config` object a machine shares with every `.provide(...)` of itself. */
337
+ function machineConfigKey(machine) {
338
+ const config = machine?.config;
339
+ return config && typeof config === "object" ? config : void 0;
340
+ }
341
+ /** Registers `options` for `machine` and for every `.provide(...)` of it. */
342
+ function setAgentExecutionOptions(machine, options) {
343
+ if (!machine || typeof machine !== "object") return;
344
+ agentExecutionOptions.set(machine, options);
345
+ const config = machineConfigKey(machine);
346
+ if (config) agentExecutionOptions.set(config, options);
347
+ }
348
+ /**
349
+ * Reads the options registered for `machine`, falling back to the root `config`
350
+ * key so a `.provide(...)`-rebound machine (e.g. the one behind a `runAgent`
351
+ * result snapshot) resolves the same pack.
352
+ */
353
+ function getAgentExecutionOptions(machine) {
354
+ if (!machine || typeof machine !== "object") return void 0;
355
+ const direct = agentExecutionOptions.get(machine);
356
+ if (direct) return direct;
357
+ const config = machineConfigKey(machine);
358
+ return config ? agentExecutionOptions.get(config) : void 0;
359
+ }
360
+ /**
361
+ * Machine-carried wait-state predicates, keyed on the machine's root `config`
362
+ * object. `config` is shared by reference across `machine.provide(...)` (unlike
363
+ * the machine object itself), so a predicate registered here travels with the
364
+ * machine through `.provide` — which is why it is keyed on `config`, not the
365
+ * machine. Set by `setupAgent({ isIdle })` in `createMachine` and by
366
+ * `setupAgent.fromConfig` (its `isIdle` option or the config's
367
+ * `idleTags`), read by `runAgent` before its structural default.
368
+ */
369
+ const machineIdlePredicates = /* @__PURE__ */ new WeakMap();
370
+ /** Reads the {@link machineIdlePredicates} predicate carried by `machine` (via its root `config`), if any. */
371
+ function getMachineIdlePredicate(machine) {
372
+ const config = machine.config;
373
+ return config ? machineIdlePredicates.get(config) : void 0;
374
+ }
375
+ const unboundPlaceholderLogics = /* @__PURE__ */ new WeakSet();
376
+ /** Text/decision logics created WITH their own executor (withExecutor or the
377
+ * factory's second arg) — these are runnable as-is, so runAgent's bind check
378
+ * must not reject them as direct-object invoke srcs. */
379
+ const executorBoundLogics = /* @__PURE__ */ new WeakSet();
380
+ function missingActor(src) {
381
+ const logic = createAsyncLogic({ run: async () => {
382
+ throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actors: { '${src}': ... } }).`);
383
+ } });
384
+ unboundPlaceholderLogics.add(logic);
385
+ return logic;
386
+ }
387
+ function isUnboundPlaceholder(logic) {
388
+ return !!logic && typeof logic === "object" && unboundPlaceholderLogics.has(logic);
389
+ }
390
+ function getRegisteredAgentExecutionOptions(machine, options) {
391
+ return {
392
+ ...getAgentExecutionOptions(machine),
393
+ ...options
394
+ };
395
+ }
396
+ //#endregion
397
+ //#region src/text-logic.ts
398
+ const GENERATE_TEXT_ACTOR = "agent.generateText";
399
+ const STREAM_TEXT_ACTOR = "agent.streamText";
400
+ const DECIDE_ACTOR = "agent.decide";
401
+ const AGENT_FINISH_REASONS = new Set([
402
+ "stop",
403
+ "length",
404
+ "tool-calls",
405
+ "content-filter",
406
+ "other"
407
+ ]);
408
+ /**
409
+ * Reads a settled call's {@link AgentFinishReason} off a RAW executor result's
410
+ * `finishReason` field — the finish-reason sibling of {@link getCallUsage},
411
+ * applied by `runAgent` before it puts the reason on the `request.end` trace.
412
+ * A provider's `'error'` normalizes to `'other'`; anything else the union does
413
+ * not name (an un-normalized provider string, a missing field) returns
414
+ * `undefined`.
415
+ */
416
+ function getCallFinishReason(raw) {
417
+ const value = raw?.finishReason;
418
+ if (typeof value !== "string") return;
419
+ if (value === "error") return "other";
420
+ return AGENT_FINISH_REASONS.has(value) ? value : void 0;
421
+ }
422
+ /** The token fields {@link AgentUsage} aggregates. @internal */
423
+ const AGENT_USAGE_TOKEN_FIELDS = [
424
+ "inputTokens",
425
+ "outputTokens",
426
+ "totalTokens",
427
+ "reasoningTokens",
428
+ "cachedInputTokens"
429
+ ];
430
+ /**
431
+ * Reads a settled call's per-call {@link AgentCallUsage} off a RAW executor
432
+ * result's `usage` field, keeping only finite numbers — the same normalization
433
+ * `runAgent` applies before it delivers `'@agent.usage'`. Returns `undefined`
434
+ * when the result reports no usage at all. Works for our `{ result, usage }`
435
+ * shape, for a raw Vercel AI SDK result (its `LanguageModelUsage` carries
436
+ * the same flat field names), and for any custom executor that follows the
437
+ * shape.
438
+ *
439
+ * The seam for the step-loop path, where the host holds the raw result itself:
440
+ *
441
+ * ```ts
442
+ * const { result, messages } = await executeAgentRequest(effect, executors);
443
+ * const usage = getCallUsage(raw);
444
+ * if (usage) append({ type: AGENT_USAGE_EVENT_TYPE, usage }); // journal + transition, like any event
445
+ * append(effect.toDoneEvent(output));
446
+ * ```
447
+ *
448
+ * See "Token usage on this path" in docs/steps.md for the full loop.
449
+ */
450
+ function getCallUsage(raw) {
451
+ const usage = raw?.usage;
452
+ if (!usage || typeof usage !== "object") return;
453
+ let out;
454
+ for (const field of AGENT_USAGE_TOKEN_FIELDS) {
455
+ const value = usage[field];
456
+ if (typeof value === "number" && Number.isFinite(value)) (out ??= {})[field] = value;
457
+ }
458
+ return out;
459
+ }
460
+ /**
461
+ * The response messages off an executor result, or none. Fields
462
+ * holding `undefined` are dropped on the way in: SDK message objects often
463
+ * carry optional slots as explicit `undefined` (the AI SDK's
464
+ * `providerOptions`, for one), and the messages now travel inside the
465
+ * invoke's done event, which the event log requires to be strict JSON.
466
+ * @internal
467
+ */
468
+ function responseMessagesOf(raw) {
469
+ const messages = raw?.messages;
470
+ return Array.isArray(messages) ? dropUndefined(messages) : [];
471
+ }
472
+ function dropUndefined(value) {
473
+ if (Array.isArray(value)) return value.map(dropUndefined);
474
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
475
+ const out = {};
476
+ for (const [key, entry] of Object.entries(value)) if (entry !== void 0) out[key] = dropUndefined(entry);
477
+ return out;
478
+ }
479
+ return value;
480
+ }
481
+ function textRequestSourceIssue(request) {
482
+ const hasPrompt = typeof request.prompt === "string" && request.prompt.length > 0;
483
+ const hasMessages = Array.isArray(request.messages) && request.messages.length > 0;
484
+ const label = request.name ? ` '${request.name}'` : "";
485
+ 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.`;
486
+ 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.`;
487
+ }
488
+ const agentTextInputSchema = { "~standard": {
489
+ version: 1,
490
+ vendor: "statelyai-agent",
491
+ validate(value) {
492
+ if (!value || typeof value !== "object") return { issues: [{ message: "Expected agent text input object" }] };
493
+ const request = value;
494
+ if (typeof request.model !== "string") return { issues: [{ message: "Expected agent text input with a string `model`" }] };
495
+ const issue = textRequestSourceIssue(request);
496
+ if (issue) return { issues: [{ message: issue }] };
497
+ return { value: request };
498
+ }
499
+ } };
500
+ const passthroughSchema = { "~standard": {
501
+ version: 1,
502
+ vendor: "statelyai-agent",
503
+ validate(value) {
504
+ return { value };
505
+ }
506
+ } };
507
+ const unknownOutputSchema = passthroughSchema;
508
+ const stringOutputSchema = { "~standard": {
509
+ version: 1,
510
+ vendor: "statelyai-agent",
511
+ validate(value) {
512
+ return typeof value === "string" ? { value } : { issues: [{ message: "Expected string output" }] };
513
+ }
514
+ } };
515
+ const noInputSchema = passthroughSchema;
516
+ function createBuiltinTextActor(src, mode, outputSchema) {
517
+ const logic = createAsyncLogic({ run: async () => {
518
+ throw new Error(`'${src}' has no host execution. Provide an implementation with machine.provide({ actors: { '${src}': ... } }) or execute the returned agent request with executeAgentRequest(...).`);
519
+ } });
520
+ return Object.assign(logic, {
521
+ kind: "statelyai.textLogic",
522
+ mode,
523
+ schemas: {
524
+ input: agentTextInputSchema,
525
+ output: outputSchema
526
+ },
527
+ request(input) {
528
+ return validateSchemaSync(agentTextInputSchema, input);
529
+ },
530
+ async execute(input, executors) {
531
+ const { result: output, raw } = await executeAgentTextRequest(mode, src, validateSchemaSync(agentTextInputSchema, input), executors);
532
+ return {
533
+ result: validateSchemaSync(outputSchema, output),
534
+ messages: responseMessagesOf(raw)
535
+ };
536
+ },
537
+ withExecutor(execute) {
538
+ return createTextLogic({
539
+ mode,
540
+ schemas: {
541
+ input: agentTextInputSchema,
542
+ output: outputSchema
543
+ },
544
+ name: ({ input }) => input.name,
545
+ model: ({ input }) => input.model,
546
+ system: ({ input }) => input.system,
547
+ prompt: ({ input }) => input.prompt,
548
+ messages: ({ input }) => input.messages,
549
+ tools: ({ input }) => input.tools,
550
+ toolChoice: ({ input }) => input.toolChoice,
551
+ includeReasoning: ({ input }) => input.includeReasoning,
552
+ temperature: ({ input }) => input.temperature,
553
+ maxOutputTokens: ({ input }) => input.maxOutputTokens,
554
+ topP: ({ input }) => input.topP,
555
+ topK: ({ input }) => input.topK,
556
+ seed: ({ input }) => input.seed,
557
+ stopSequences: ({ input }) => input.stopSequences,
558
+ maxSteps: ({ input }) => input.maxSteps,
559
+ metadata: ({ input }) => input.metadata
560
+ }, execute);
561
+ }
562
+ });
563
+ }
564
+ /** The unbound `agent.generateText`/`agent.streamText` builtins registered by setupAgent. @internal */
565
+ const builtinTextActors = {
566
+ [GENERATE_TEXT_ACTOR]: createBuiltinTextActor(GENERATE_TEXT_ACTOR, "generate", unknownOutputSchema),
567
+ [STREAM_TEXT_ACTOR]: createBuiltinTextActor(STREAM_TEXT_ACTOR, "stream", stringOutputSchema)
568
+ };
569
+ /**
570
+ * Validates a raw model/executor output against `schema`, returning the
571
+ * parsed value. Thin wrapper over {@link validateSchemaSync} for parsing a
572
+ * text request's structured output outside of `TextLogic.execute`/
573
+ * `executeAgentRequest` (e.g. a custom host loop).
574
+ */
575
+ function parseOutput(schema, output) {
576
+ return validateSchemaSync(schema, output);
577
+ }
578
+ /** Resolves a `ResolveTextLogicValue` (calls it if it's a function, else returns it as-is). @internal */
579
+ function resolveTextLogicValue(value, args) {
580
+ return typeof value === "function" ? value(args) : value;
581
+ }
582
+ /**
583
+ * Creates reusable, standalone {@link TextLogic}: an actor that, when run,
584
+ * resolves typed input to typed output via a model call. Register the
585
+ * result under `actors:` and invoke it by name (equivalent to what
586
+ * `setupAgent({ requests })` builds internally for each request entry). Pass
587
+ * `execute` here, or bind it later with `.withExecutor(...)`, a runtime
588
+ * adapter's `machine.provide(...)`, or `runAgent`'s `generateText`/
589
+ * `streamText` options.
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * export const tellJoke = createTextLogic({
594
+ * mode: 'stream',
595
+ * schemas: { input: z.object({ topic: z.string() }), output: z.string() },
596
+ * model: 'openai/gpt-5.4-mini',
597
+ * system: 'You tell short, punchy jokes.',
598
+ * prompt: ({ input }) => `Tell a joke about ${input.topic}.`,
599
+ * });
600
+ * ```
601
+ */
602
+ function createTextLogic(config, execute) {
603
+ const schemas = {
604
+ input: config.schemas?.input ?? noInputSchema,
605
+ output: config.schemas?.output ?? stringOutputSchema
606
+ };
607
+ const request = (input) => {
608
+ const parsedInput = validateSchemaSync(schemas.input, input);
609
+ const args = { input: parsedInput };
610
+ const name = resolveTextLogicValue(config.name, args);
611
+ const prompt = resolveTextLogicValue(config.prompt, args);
612
+ const messages = resolveTextLogicValue(config.messages, args);
613
+ const sourceIssue = textRequestSourceIssue({
614
+ name,
615
+ prompt,
616
+ messages
617
+ });
618
+ if (sourceIssue) throw new Error(sourceIssue);
619
+ return {
620
+ name,
621
+ input: parsedInput,
622
+ model: resolveTextLogicValue(config.model, args),
623
+ system: resolveTextLogicValue(config.system, args),
624
+ prompt,
625
+ messages,
626
+ tools: resolveTextLogicValue(config.tools, args),
627
+ toolChoice: resolveTextLogicValue(config.toolChoice, args),
628
+ outputSchema: schemas.output,
629
+ includeReasoning: resolveTextLogicValue(config.includeReasoning, args),
630
+ temperature: resolveTextLogicValue(config.temperature, args),
631
+ maxOutputTokens: resolveTextLogicValue(config.maxOutputTokens, args),
632
+ topP: resolveTextLogicValue(config.topP, args),
633
+ topK: resolveTextLogicValue(config.topK, args),
634
+ seed: resolveTextLogicValue(config.seed, args),
635
+ stopSequences: resolveTextLogicValue(config.stopSequences, args),
636
+ maxSteps: resolveTextLogicValue(config.maxSteps, args),
637
+ metadata: resolveTextLogicValue(config.metadata, args)
638
+ };
639
+ };
640
+ const logic = createAsyncLogic({ run: async ({ input, signal, system, self }, enq) => {
641
+ const resolvedRequest = request(input);
642
+ 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.");
643
+ const result = await execute({
644
+ input,
645
+ request: resolvedRequest,
646
+ signal,
647
+ system,
648
+ self,
649
+ emit: enq.emit
650
+ });
651
+ const selfId = self?.id;
652
+ const output = await normalizeGeneratorResult(result, typeof selfId === "string" ? selfId : "text logic");
653
+ return {
654
+ result: validateSchemaSync(schemas.output, output),
655
+ messages: responseMessagesOf(result)
656
+ };
657
+ } });
658
+ const textLogic = Object.assign(logic, {
659
+ kind: "statelyai.textLogic",
660
+ mode: config.mode ?? "generate",
661
+ schemas,
662
+ request,
663
+ async execute(input, executors) {
664
+ const { result: output, raw } = await executeAgentTextRequest(config.mode ?? "generate", "textLogic", request(input), executors);
665
+ return {
666
+ result: validateSchemaSync(schemas.output, output),
667
+ messages: responseMessagesOf(raw)
668
+ };
669
+ },
670
+ withExecutor(nextExecute) {
671
+ return createTextLogic(config, nextExecute);
672
+ }
673
+ });
674
+ if (execute) executorBoundLogics.add(textLogic);
675
+ return textLogic;
676
+ }
677
+ /**
678
+ * Binds a child machine's {@link TextLogic} to a raw
679
+ * {@link AgentRequestExecutor} (the `generateText`/`streamText` shape hosts
680
+ * implement). Encapsulates the `withExecutor` idiom child agents repeat:
681
+ * default the request's `tools` to `{}`, forward the actor `signal`, call the
682
+ * executor, and return its `{ result }`. Use this to share ONE
683
+ * executor across a parent and its nested children.
684
+ *
685
+ * @example
686
+ * ```ts
687
+ * childMachine.provide({
688
+ * actors: {
689
+ * researchTopic: bindRequestExecutor(setup.requests.researchTopic, generateText),
690
+ * },
691
+ * });
692
+ * ```
693
+ */
694
+ function bindRequestExecutor(logic, executor, info) {
695
+ return logic.withExecutor(async ({ request, signal }) => {
696
+ const { result, messages } = await executor({
697
+ ...request,
698
+ tools: request.tools ?? {}
699
+ }, {
700
+ signal,
701
+ onChunk: info?.onChunk
702
+ });
703
+ return {
704
+ result,
705
+ messages
706
+ };
707
+ });
708
+ }
709
+ /** Type guard: true for any actor logic built by createTextLogic (checks the `kind` marker). @internal */
710
+ function isTextLogic(value) {
711
+ return !!value && typeof value === "object" && value.kind === "statelyai.textLogic" && typeof value.request === "function";
712
+ }
713
+ /**
714
+ * Classifies a text request's output schema as `'structured'` (its JSON
715
+ * Schema is `type: 'object'`, `type: 'array'`, or a top-level union/
716
+ * composition — `anyOf`/`oneOf`/`allOf`, which a bare `z.union`/
717
+ * `z.discriminatedUnion` emits with no top-level `type`) or `'text'`
718
+ * (anything else, including no schema). Reads the schema's
719
+ * `~standard.jsonSchema.input()` extension — schemas without it are treated
720
+ * as `'text'`.
721
+ */
722
+ function getAgentOutputMode(schema) {
723
+ const jsonSchema = getJsonSchemaSync(schema);
724
+ if (!jsonSchema) return "text";
725
+ if (jsonSchema.type === "object" || jsonSchema.type === "array") return "structured";
726
+ if (jsonSchema.type === void 0 && ("anyOf" in jsonSchema || "oneOf" in jsonSchema || "allOf" in jsonSchema)) return "structured";
727
+ return "text";
728
+ }
729
+ /**
730
+ * Builds the schema every structured request is sent to the provider as: a
731
+ * root object `{ result: <inner> }` wrapping the declared schema, plus — when
732
+ * `options.reasoning` is `true` — an optional string `reasoning` property listed
733
+ * BEFORE `result` (property order nudges the model to reason first). This is THE
734
+ * wire contract for structured output: a root object is universally accepted as
735
+ * a provider response schema, unlike a bare union/array root that many providers
736
+ * reject.
737
+ *
738
+ * The returned {@link StandardSchemaV1} validates the `{ reasoning?, result }`
739
+ * object (validating `result` through the original schema, capturing a string
740
+ * `reasoning` when present) and exposes the wrapped JSON Schema. An executor
741
+ * returns the parsed `{ result, reasoning? }` as-is: `result` is what the
742
+ * machine validates against the declared schema, and `reasoning` stays on the
743
+ * raw executor result, never in machine context/output.
744
+ */
745
+ function providerOutputSchema(inner, options = {}) {
746
+ const includeReasoning = options.reasoning === true;
747
+ const buildJson = (innerJson) => ({
748
+ type: "object",
749
+ properties: {
750
+ ...includeReasoning ? { reasoning: { type: "string" } } : {},
751
+ result: innerJson ?? {}
752
+ },
753
+ required: ["result"],
754
+ additionalProperties: false
755
+ });
756
+ return { "~standard": {
757
+ version: 1,
758
+ vendor: "statelyai-agent",
759
+ validate(value) {
760
+ if (!value || typeof value !== "object" || !("result" in value)) return { issues: [{ message: "Expected a { result } object" }] };
761
+ const innerResult = inner["~standard"].validate(value.result);
762
+ if (innerResult instanceof Promise) throw new Error("Async schema validation is not supported.");
763
+ if (innerResult.issues) return innerResult;
764
+ const parsed = { result: innerResult.value };
765
+ const reasoning = value.reasoning;
766
+ if (typeof reasoning === "string") parsed.reasoning = reasoning;
767
+ return { value: parsed };
768
+ },
769
+ jsonSchema: { input: () => {
770
+ const innerJson = inner["~standard"].jsonSchema?.input?.();
771
+ return innerJson instanceof Promise ? innerJson.then(buildJson) : buildJson(innerJson);
772
+ } }
773
+ } };
774
+ }
775
+ /**
776
+ * Validates a raw provider value against the provider output schema for
777
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
778
+ * replacement for `raw as ProviderStructuredOutput` in hand-written hosts.
779
+ * Pair with {@link providerOutputSchema} (which produced the schema the
780
+ * provider was asked to satisfy).
781
+ */
782
+ function parseProviderOutput(request, value) {
783
+ if (!request.outputSchema) throw new Error("parseProviderOutput: the request declares no outputSchema.");
784
+ return validateSchemaSync(providerOutputSchema(request.outputSchema, { reasoning: request.includeReasoning }), value);
785
+ }
786
+ /**
787
+ * Merges request-declared and call-site `tools`, dispatches to the
788
+ * `mode`-appropriate executor (`generateText`/`streamText`), and normalizes
789
+ * the raw result via {@link normalizeGeneratorResult}. Shared by
790
+ * `TextLogic.execute`, `executeAgentRequest`, and the `agent.generateText`/
791
+ * `agent.streamText` builtins. Throws if no executor is registered for
792
+ * `mode`.
793
+ *
794
+ * @internal
795
+ */
796
+ async function executeAgentTextRequest(mode, id, input, executors, tools = {}, info) {
797
+ const request = {
798
+ ...input,
799
+ name: input.name ?? id,
800
+ tools: {
801
+ ...input.tools,
802
+ ...tools
803
+ }
804
+ };
805
+ const sourceIssue = textRequestSourceIssue(request);
806
+ if (sourceIssue) throw new Error(sourceIssue);
807
+ const executor = mode === "stream" ? executors.streamText : executors.generateText;
808
+ if (!executor) throw new Error(`No executor provided for ${mode === "stream" ? "stream" : "generate"} request '${id}'.`);
809
+ const raw = await executor(request, info);
810
+ return {
811
+ result: await normalizeGeneratorResult(raw, id),
812
+ raw
813
+ };
814
+ }
815
+ /**
816
+ * Unwraps an executor result into the request's final value: awaits and
817
+ * returns `result` from the `{ result }` {@link AgentRequestExecutorResult}.
818
+ * Anything else is a runtime error naming `id`. This is
819
+ * generator-result unwrapping only — decision results are extracted separately
820
+ * by `resolveDecision`.
821
+ *
822
+ * @internal
823
+ */
824
+ async function normalizeGeneratorResult(result, id = "text request") {
825
+ const resolved = await result;
826
+ if (!resolved || typeof resolved !== "object" || !("result" in resolved)) throw invalidGeneratorResult(id);
827
+ return await resolved.result;
828
+ }
829
+ function invalidGeneratorResult(id) {
830
+ return /* @__PURE__ */ new Error(`Executor for '${id}' returned an invalid result: executors must return { result } (the text string or structured object as \`result\`, plus optional \`messages\`, \`usage\` and other passthrough fields). Wrap a raw SDK result with an adapter such as createAiSdkExecutors.`);
831
+ }
832
+ //#endregion
833
+ export { getJsonSchema as A, userMessage as B, isUnboundPlaceholder as C, assistantMessage as D, setAgentExecutionOptions as E, getStatePath as F, AgentError as H, isStandardSchema as I, resolveMachineVersion as L, getMachineStructuralHash as M, getMessageText as N, djb2Hex as O, getStateMeta as P, systemMessage as R, getRegisteredAgentExecutionOptions as S, missingActor as T, AgentTruncatedError as U, validateSchemaSync as V, resolveTextLogicValue as _, bindRequestExecutor as a, getAgentExecutionOptions as b, executeAgentTextRequest as c, getCallUsage as d, isTextLogic as f, providerOutputSchema as g, parseProviderOutput as h, STREAM_TEXT_ACTOR as i, getJsonSchemaSync as j, findNonSerializableContextPaths as k, getAgentOutputMode as l, parseOutput as m, DECIDE_ACTOR as n, builtinTextActors as o, normalizeGeneratorResult as p, GENERATE_TEXT_ACTOR as r, createTextLogic as s, AGENT_USAGE_TOKEN_FIELDS as t, getCallFinishReason as u, responseMessagesOf as v, machineIdlePredicates as w, getMachineIdlePredicate as x, executorBoundLogics as y, toolMessage as z };