@statelyai/agent 1.1.5 → 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 -583
  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 +110 -29
  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 -215
  46. package/dist/index.d.ts +0 -428
  47. package/dist/index.js +0 -616
  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 -236
  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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License Copyright (c) 2025 Stately Software, Inc.
2
+
3
+ Permission is hereby granted,
4
+ free of charge, to any person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use, copy, modify, merge,
7
+ publish, distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice
12
+ (including the next paragraph) shall be included in all copies or substantial
13
+ portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
18
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,342 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_run_agent = require("./run-agent-BFMkuI1F.cjs");
3
+ const require_decision = require("./decision-b-lkcs4L.cjs");
4
+ let ai = require("ai");
5
+ //#region src/ai-sdk/index.ts
6
+ /**
7
+ * Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
8
+ * already carries its own Standard Schema `inputSchema` — an AI SDK
9
+ * `tool({...})`, or any equivalent descriptor — is passed through **unchanged**,
10
+ * so the SDK applies its own validation, calls `execute(input, options)`, and
11
+ * every extra property (`providerOptions`, `toModelOutput`, …) survives. A bare
12
+ * `AgentToolExecute` function becomes a tool with an unconstrained input schema;
13
+ * a minimal descriptor with no readable schema is converted with a permissive
14
+ * fallback. Used internally by {@link toAiSdkCallSettings}; exported for callers
15
+ * building AI SDK calls by hand outside `createAiSdkExecutors`.
16
+ */
17
+ function toAiSdkTools(tools) {
18
+ const entries = [];
19
+ for (const [name, descriptor] of Object.entries(tools)) {
20
+ if (!descriptor) continue;
21
+ if (typeof descriptor === "function") {
22
+ entries.push([name, (0, ai.tool)({
23
+ inputSchema: unknownSchema,
24
+ execute: (input) => descriptor(input)
25
+ })]);
26
+ continue;
27
+ }
28
+ if (require_decision.isStandardSchema(descriptor.inputSchema)) {
29
+ entries.push([name, descriptor]);
30
+ continue;
31
+ }
32
+ const inputSchema = descriptor.inputSchema ?? descriptor.schemas?.input;
33
+ const toolOptions = {
34
+ description: descriptor.description,
35
+ inputSchema: inputSchema ? inputSchema : unknownSchema
36
+ };
37
+ if (descriptor.execute) {
38
+ entries.push([name, (0, ai.tool)({
39
+ ...toolOptions,
40
+ execute: (input) => descriptor.execute?.(input)
41
+ })]);
42
+ continue;
43
+ }
44
+ entries.push([name, (0, ai.tool)(toolOptions)]);
45
+ }
46
+ return Object.fromEntries(entries);
47
+ }
48
+ function maxStepsSetting(request) {
49
+ return typeof request.metadata?.maxSteps === "number" ? { stopWhen: (0, ai.stepCountIs)(request.metadata.maxSteps) } : {};
50
+ }
51
+ const unknownSchema = { "~standard": {
52
+ version: 1,
53
+ vendor: "statelyai-agent",
54
+ validate: (value) => ({ value }),
55
+ jsonSchema: { input: () => ({}) }
56
+ } };
57
+ /**
58
+ * Identity helper for a `models` map whose value is exported. Returns the map
59
+ * unchanged, but types it as {@link AiSdkModelMap}`<keyof T & string>` — a
60
+ * portable, nameable type — so an exported `const models = defineModels({...})`
61
+ * needs no `Record<'a' | 'b', LanguageModel>` annotation and never triggers
62
+ * TS2742 ("inferred type cannot be named without a reference to …"). The exact
63
+ * ref keys survive, so `createAiSdkExecutors({ models })` and
64
+ * `setupAgent({ models })` still infer/autocomplete them.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * export const models = defineModels({
69
+ * quick: openai('gpt-5.4-mini'),
70
+ * deep: openai('gpt-5.4'),
71
+ * });
72
+ * // typeof models === AiSdkModelMap<'quick' | 'deep'>
73
+ * ```
74
+ */
75
+ function defineModels(models) {
76
+ return models;
77
+ }
78
+ function resolveAiSdkModel(options, modelRef) {
79
+ if (options.resolveModel) return options.resolveModel(modelRef);
80
+ const models = options.models;
81
+ if (!models) throw new Error(`createAiSdkExecutors: no model resolver configured for '${modelRef}'.`);
82
+ const model = models[modelRef];
83
+ if (!model) throw new Error(`createAiSdkExecutors: unknown model '${modelRef}'.`);
84
+ return model;
85
+ }
86
+ /**
87
+ * AI SDK request-mapping settings shared by `generateText`/`streamText`.
88
+ * `AgentTextRequest.messages` (`AgentMessage[]`) and AI SDK's `ModelMessage[]`
89
+ * are structurally compatible by design (§1 of .scratch/p0-design.md) — the cast
90
+ * below is a typed identity mapping, not a semantic conversion.
91
+ */
92
+ function toAiSdkCallSettings(request) {
93
+ const messages = request.messages;
94
+ return {
95
+ system: request.system,
96
+ ...messages ? { messages } : { prompt: request.prompt ?? "" },
97
+ temperature: request.temperature,
98
+ maxOutputTokens: request.maxOutputTokens,
99
+ topP: request.topP,
100
+ topK: request.topK,
101
+ seed: request.seed,
102
+ stopSequences: request.stopSequences,
103
+ tools: request.tools ? toAiSdkTools(request.tools) : void 0,
104
+ toolChoice: toAiSdkToolChoice(request.toolChoice)
105
+ };
106
+ }
107
+ /** Maps an {@link AgentToolChoice} to AI SDK's tool-choice shape — `{ type: 'tool'; name }` becomes `{ type: 'tool'; toolName }`; `'auto'`/`'none'`/`'required'`/`undefined` pass through unchanged. */
108
+ function toAiSdkToolChoice(toolChoice) {
109
+ return typeof toolChoice === "object" ? {
110
+ type: "tool",
111
+ toolName: toolChoice.name
112
+ } : toolChoice;
113
+ }
114
+ /** `true` when the request should use AI SDK structured `Output.object`. */
115
+ function isStructuredOutputRequest(request) {
116
+ return require_decision.getAgentOutputMode(request.outputSchema) === "structured";
117
+ }
118
+ /**
119
+ * Extracts the first complete top-level JSON value from `text`, or returns
120
+ * `undefined` when there is nothing to repair (no complete value, or the value
121
+ * already spans the whole text). Models occasionally emit two structured-output
122
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
123
+ * parsing wholesale; the balanced scan below recovers the first value and
124
+ * drops the rest.
125
+ */
126
+ function extractFirstJsonValue(text) {
127
+ const start = text.search(/[{[]/);
128
+ if (start === -1) return;
129
+ let depth = 0;
130
+ let inString = false;
131
+ let escaped = false;
132
+ for (let i = start; i < text.length; i++) {
133
+ const char = text[i];
134
+ if (inString) {
135
+ if (escaped) escaped = false;
136
+ else if (char === "\\") escaped = true;
137
+ else if (char === "\"") inString = false;
138
+ continue;
139
+ }
140
+ if (char === "\"") inString = true;
141
+ else if (char === "{" || char === "[") depth++;
142
+ else if (char === "}" || char === "]") {
143
+ depth--;
144
+ if (depth === 0) {
145
+ const value = text.slice(start, i + 1);
146
+ return value === text.trim() ? void 0 : value;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ function withJsonRepair(output) {
152
+ return {
153
+ ...output,
154
+ parseCompleteOutput: async (options, context) => {
155
+ try {
156
+ return await output.parseCompleteOutput(options, context);
157
+ } catch (error) {
158
+ const repaired = extractFirstJsonValue(options.text);
159
+ if (repaired === void 0) throw error;
160
+ return await output.parseCompleteOutput({
161
+ ...options,
162
+ text: repaired
163
+ }, context);
164
+ }
165
+ }
166
+ };
167
+ }
168
+ /**
169
+ * The canonical Vercel AI SDK adapter: builds the `{ generateText, streamText,
170
+ * decide }` executor set consumed by `runAgent`/`executeAgentRequest`. `ai`
171
+ * must not become a dependency of core `src/` files — this subpath is the one
172
+ * place it's imported, and callers must supply their own model resolver so no
173
+ * concrete provider package (e.g. `@ai-sdk/openai`) becomes a dependency here
174
+ * either.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const executors = createAiSdkExecutors({ models: { quick: openai('gpt-5.4-mini') } });
179
+ * const result = await runAgent(machine, { input, executors });
180
+ * ```
181
+ */
182
+ function createAiSdkExecutors(options) {
183
+ const generateText = async (request, info) => {
184
+ const common = {
185
+ model: resolveAiSdkModel(options, request.model),
186
+ abortSignal: info?.signal,
187
+ ...toAiSdkCallSettings(request),
188
+ ...maxStepsSetting(request)
189
+ };
190
+ if (isStructuredOutputRequest(request)) {
191
+ const envelope = require_decision.buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning });
192
+ const structuredOutput = withJsonRepair(ai.Output.object({ schema: envelope }));
193
+ const canRetry = !request.tools || Object.keys(request.tools).length === 0;
194
+ let result;
195
+ try {
196
+ result = await (0, ai.generateText)({
197
+ ...common,
198
+ output: structuredOutput
199
+ });
200
+ } catch (error) {
201
+ if (!canRetry || !ai.NoObjectGeneratedError.isInstance(error) || info?.signal?.aborted) throw error;
202
+ result = await (0, ai.generateText)({
203
+ ...common,
204
+ output: structuredOutput
205
+ });
206
+ }
207
+ const { result: output, reasoning } = result.output;
208
+ return {
209
+ output,
210
+ ...reasoning !== void 0 ? { reasoning } : {},
211
+ usage: result.usage,
212
+ finishReason: result.finishReason,
213
+ toolCalls: result.toolCalls,
214
+ toolResults: result.toolResults
215
+ };
216
+ }
217
+ const result = await (0, ai.generateText)(common);
218
+ return {
219
+ output: result.text,
220
+ usage: result.usage,
221
+ finishReason: result.finishReason,
222
+ toolCalls: result.toolCalls,
223
+ toolResults: result.toolResults
224
+ };
225
+ };
226
+ const streamText = async (request, info) => {
227
+ const result = (0, ai.streamText)({
228
+ model: resolveAiSdkModel(options, request.model),
229
+ abortSignal: info?.signal,
230
+ ...toAiSdkCallSettings(request),
231
+ ...maxStepsSetting(request)
232
+ });
233
+ for await (const chunk of result.textStream) info?.onChunk?.(chunk);
234
+ return {
235
+ output: await result.text,
236
+ usage: await result.usage,
237
+ finishReason: await result.finishReason
238
+ };
239
+ };
240
+ const decide = async (request) => {
241
+ const model = resolveAiSdkModel(options, request.model);
242
+ const tools = toAiSdkEventTools(request.events);
243
+ const messages = toDecisionMessages(request);
244
+ const result = await (0, ai.generateText)({
245
+ model,
246
+ abortSignal: request.signal,
247
+ system: request.system,
248
+ ...messages ? { messages } : { prompt: request.prompt ?? "" },
249
+ tools,
250
+ toolChoice: "required",
251
+ stopWhen: (0, ai.stepCountIs)(1),
252
+ temperature: request.temperature,
253
+ maxOutputTokens: request.maxOutputTokens,
254
+ topP: request.topP,
255
+ topK: request.topK,
256
+ seed: request.seed,
257
+ stopSequences: request.stopSequences
258
+ });
259
+ const toolCall = result.toolCalls[0];
260
+ if (!toolCall) throw new Error("createAiSdkExecutors: decide — model did not call an event tool.");
261
+ const chosenEvent = request.events.find((event) => event.toolName === toolCall.toolName);
262
+ if (!chosenEvent) throw new Error(`createAiSdkExecutors: decide — model called unknown tool '${toolCall.toolName}'.`);
263
+ return {
264
+ event: {
265
+ ...toolCall.input && typeof toolCall.input === "object" ? toolCall.input : {},
266
+ type: chosenEvent.type
267
+ },
268
+ usage: result.usage,
269
+ finishReason: result.finishReason
270
+ };
271
+ };
272
+ return {
273
+ generateText,
274
+ streamText,
275
+ decide
276
+ };
277
+ }
278
+ /** AI SDK host for a machine authored with `setupAgent({ models })`. */
279
+ function runAgent(machine, options) {
280
+ const models = require_decision.getRegisteredAgentModels(machine);
281
+ if (!models || Object.keys(models).length === 0) throw new Error("AI SDK runAgent: machine has no models. Pass `models` to setupAgent, or use core runAgent with explicit executors.");
282
+ return require_run_agent.runAgent(machine, {
283
+ ...options,
284
+ executors: createAiSdkExecutors({ models })
285
+ });
286
+ }
287
+ function createAgent(config) {
288
+ const { model, models: configuredModels, schemas, ...machineConfig } = config;
289
+ const models = configuredModels ?? { default: model };
290
+ const executors = createAiSdkExecutors({ models });
291
+ const machine = require_run_agent.setupAgent({
292
+ ...schemas,
293
+ models
294
+ }).createMachine(machineConfig);
295
+ return {
296
+ machine,
297
+ run(runInput, options = {}) {
298
+ return require_run_agent.runAgent(machine, {
299
+ ...options,
300
+ input: runInput,
301
+ executors
302
+ });
303
+ }
304
+ };
305
+ }
306
+ /** One AI SDK `tool()` per candidate event — the "tool-per-event +
307
+ * toolChoice: 'required'" recipe from .scratch/p0-design.md §2.6. */
308
+ function toAiSdkEventTools(events) {
309
+ return Object.fromEntries(events.map((event) => [event.toolName, (0, ai.tool)({
310
+ description: `Choose the '${event.type}' move.`,
311
+ inputSchema: event.inputSchema ? event.inputSchema : unknownSchema
312
+ })]));
313
+ }
314
+ /**
315
+ * Messages for a decision request, with prior failed `attempts` (§2.6)
316
+ * rendered as appended user messages (via core's {@link renderDecisionAttempts})
317
+ * so retries converge. Core never rewrites prompts — this is adapter business.
318
+ */
319
+ function toDecisionMessages(request) {
320
+ if (!request.messages && request.attempts.length === 0) return;
321
+ const messages = [...request.messages ?? (request.prompt !== void 0 ? [{
322
+ role: "user",
323
+ content: request.prompt
324
+ }] : [])];
325
+ for (const attempt of require_decision.renderDecisionAttempts(request)) messages.push({
326
+ role: "user",
327
+ content: attempt.content
328
+ });
329
+ return messages;
330
+ }
331
+ //#endregion
332
+ exports.createAgent = createAgent;
333
+ exports.createAiSdkExecutors = createAiSdkExecutors;
334
+ exports.defineModels = defineModels;
335
+ exports.extractFirstJsonValue = extractFirstJsonValue;
336
+ exports.isStructuredOutputRequest = isStructuredOutputRequest;
337
+ exports.runAgent = runAgent;
338
+ exports.toAiSdkCallSettings = toAiSdkCallSettings;
339
+ exports.toAiSdkEventTools = toAiSdkEventTools;
340
+ exports.toAiSdkToolChoice = toAiSdkToolChoice;
341
+ exports.toAiSdkTools = toAiSdkTools;
342
+ exports.toDecisionMessages = toDecisionMessages;
@@ -0,0 +1,206 @@
1
+ import { C as StandardSchemaV1, m as ChosenEvent, n as AgentEventSchemaInputMap, u as AgentTools } from "./types-C9QiMjre.cjs";
2
+ import { H as AgentEventDescriptor, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-CZjyACzQ.cjs";
3
+ import { D as AgentMachine, O as AgentMachineConfig, l as RunAgentOptions, u as RunAgentResult } from "./run-agent-BVMd--1l.cjs";
4
+ import * as _$xstate from "xstate";
5
+ import { FinishReason, LanguageModel, LanguageModelUsage, ModelMessage, Tool, ToolSet, TypedToolCall, TypedToolResult } from "ai";
6
+
7
+ //#region src/ai-sdk/index.d.ts
8
+ /**
9
+ * Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
10
+ * already carries its own Standard Schema `inputSchema` — an AI SDK
11
+ * `tool({...})`, or any equivalent descriptor — is passed through **unchanged**,
12
+ * so the SDK applies its own validation, calls `execute(input, options)`, and
13
+ * every extra property (`providerOptions`, `toModelOutput`, …) survives. A bare
14
+ * `AgentToolExecute` function becomes a tool with an unconstrained input schema;
15
+ * a minimal descriptor with no readable schema is converted with a permissive
16
+ * fallback. Used internally by {@link toAiSdkCallSettings}; exported for callers
17
+ * building AI SDK calls by hand outside `createAiSdkExecutors`.
18
+ */
19
+ declare function toAiSdkTools(tools: AgentTools): {
20
+ [k: string]: Tool<unknown, unknown> | Tool<unknown, never>;
21
+ };
22
+ /** AI SDK model registry: maps model refs (as used in `setupAgent({ models })`/`AgentTextRequest.model`) to AI SDK `LanguageModel` values. The optional `TKey` parameter pins the ref keys (see {@link defineModels}); it defaults to `string`, so bare `AiSdkModelMap` stays `Record<string, LanguageModel>`. */
23
+ type AiSdkModelMap<TKey extends string = string> = Record<TKey, LanguageModel>;
24
+ /**
25
+ * Identity helper for a `models` map whose value is exported. Returns the map
26
+ * unchanged, but types it as {@link AiSdkModelMap}`<keyof T & string>` — a
27
+ * portable, nameable type — so an exported `const models = defineModels({...})`
28
+ * needs no `Record<'a' | 'b', LanguageModel>` annotation and never triggers
29
+ * TS2742 ("inferred type cannot be named without a reference to …"). The exact
30
+ * ref keys survive, so `createAiSdkExecutors({ models })` and
31
+ * `setupAgent({ models })` still infer/autocomplete them.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * export const models = defineModels({
36
+ * quick: openai('gpt-5.4-mini'),
37
+ * deep: openai('gpt-5.4'),
38
+ * });
39
+ * // typeof models === AiSdkModelMap<'quick' | 'deep'>
40
+ * ```
41
+ */
42
+ declare function defineModels<T extends Record<string, LanguageModel>>(models: T): AiSdkModelMap<keyof T & string>;
43
+ /**
44
+ * Options for {@link createAiSdkExecutors}: either a static `models` map
45
+ * (model refs resolved by lookup), a `resolveModel` function (refs resolved
46
+ * dynamically, e.g. `"openai/gpt-5.4-mini"` → `openai('gpt-5.4-mini')`), or
47
+ * both — `resolveModel` takes precedence when both are supplied.
48
+ */
49
+ type CreateAiSdkExecutorsOptions<TModels extends AiSdkModelMap = AiSdkModelMap> = {
50
+ models: TModels;
51
+ resolveModel?: (modelRef: keyof TModels & string) => LanguageModel;
52
+ } | {
53
+ models?: TModels;
54
+ resolveModel: (modelRef: string) => LanguageModel;
55
+ };
56
+ /**
57
+ * AI SDK request-mapping settings shared by `generateText`/`streamText`.
58
+ * `AgentTextRequest.messages` (`AgentMessage[]`) and AI SDK's `ModelMessage[]`
59
+ * are structurally compatible by design (§1 of .scratch/p0-design.md) — the cast
60
+ * below is a typed identity mapping, not a semantic conversion.
61
+ */
62
+ declare function toAiSdkCallSettings(request: AgentTextRequest & {
63
+ tools?: AgentTools;
64
+ }): {
65
+ temperature: number | undefined;
66
+ maxOutputTokens: number | undefined;
67
+ topP: number | undefined;
68
+ topK: number | undefined;
69
+ seed: number | undefined;
70
+ stopSequences: string[] | undefined;
71
+ tools: {
72
+ [k: string]: Tool<unknown, unknown> | Tool<unknown, never>;
73
+ } | undefined;
74
+ toolChoice: "auto" | "none" | "required" | {
75
+ type: "tool";
76
+ toolName: string;
77
+ } | undefined;
78
+ messages: ModelMessage[];
79
+ system: string | undefined;
80
+ } | {
81
+ temperature: number | undefined;
82
+ maxOutputTokens: number | undefined;
83
+ topP: number | undefined;
84
+ topK: number | undefined;
85
+ seed: number | undefined;
86
+ stopSequences: string[] | undefined;
87
+ tools: {
88
+ [k: string]: Tool<unknown, unknown> | Tool<unknown, never>;
89
+ } | undefined;
90
+ toolChoice: "auto" | "none" | "required" | {
91
+ type: "tool";
92
+ toolName: string;
93
+ } | undefined;
94
+ prompt: string;
95
+ system: string | undefined;
96
+ };
97
+ /** Maps an {@link AgentToolChoice} to AI SDK's tool-choice shape — `{ type: 'tool'; name }` becomes `{ type: 'tool'; toolName }`; `'auto'`/`'none'`/`'required'`/`undefined` pass through unchanged. */
98
+ declare function toAiSdkToolChoice(toolChoice: AgentTextRequest["toolChoice"]): "auto" | "none" | "required" | {
99
+ type: "tool";
100
+ toolName: string;
101
+ } | undefined;
102
+ /** `true` when the request should use AI SDK structured `Output.object`. */
103
+ declare function isStructuredOutputRequest(request: Pick<AgentTextRequest, "outputSchema">): boolean;
104
+ /**
105
+ * Extracts the first complete top-level JSON value from `text`, or returns
106
+ * `undefined` when there is nothing to repair (no complete value, or the value
107
+ * already spans the whole text). Models occasionally emit two structured-output
108
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
109
+ * parsing wholesale; the balanced scan below recovers the first value and
110
+ * drops the rest.
111
+ */
112
+ declare function extractFirstJsonValue(text: string): string | undefined;
113
+ /**
114
+ * Raw result shape from {@link AiSdkExecutors.generateText} — the `{ output }`
115
+ * envelope (the validated structured object for structured-output requests,
116
+ * or the accumulated text string otherwise; unwrapped by
117
+ * `normalizeGeneratorResult`) plus the AI SDK call metadata. Core only reads
118
+ * `output`; everything else flows verbatim to `runAgent`'s
119
+ * `onResult(request, { raw })`, so `raw as AiSdkGenerateResult` is the
120
+ * supported cast for token accounting and tracing.
121
+ */
122
+ type AiSdkGenerateResult = {
123
+ output: unknown;
124
+ /** The model's reasoning, present only when the request opted in via
125
+ * `reasoning: true` and the model produced it (see the structured-output
126
+ * envelope in {@link buildEnvelopeSchema}). Never enters machine context/output. */
127
+ reasoning?: string;
128
+ usage: LanguageModelUsage;
129
+ finishReason: FinishReason;
130
+ toolCalls: TypedToolCall<ToolSet>[];
131
+ toolResults: TypedToolResult<ToolSet>[];
132
+ };
133
+ /** Raw result shape from {@link AiSdkExecutors.streamText} — the `{ output }` envelope carrying the fully-accumulated text once the stream finishes (chunks are delivered separately via `onChunk`), plus the stream's final usage/finish metadata for `onResult`. */
134
+ type AiSdkStreamResult = {
135
+ output: string;
136
+ usage: LanguageModelUsage;
137
+ finishReason: FinishReason;
138
+ };
139
+ /** Raw result shape from {@link AiSdkExecutors.decide} — the chosen event plus the AI SDK call metadata, delivered per decision attempt to `onResult`. */
140
+ type AiSdkDecideResult = {
141
+ event: ChosenEvent;
142
+ usage: LanguageModelUsage;
143
+ finishReason: FinishReason;
144
+ };
145
+ /** `createAiSdkExecutors` always populates all three slots (unlike the
146
+ * general `AgentRequestExecutors`, where `streamText`/`decide` are optional),
147
+ * and its `generateText`/`streamText` results are concretely typed. */
148
+ interface AiSdkExecutors extends AgentRequestExecutors<AiSdkGenerateResult, AiSdkStreamResult> {
149
+ streamText: AgentRequestExecutor<AiSdkStreamResult>;
150
+ decide: AgentDecisionExecutor;
151
+ }
152
+ /**
153
+ * The canonical Vercel AI SDK adapter: builds the `{ generateText, streamText,
154
+ * decide }` executor set consumed by `runAgent`/`executeAgentRequest`. `ai`
155
+ * must not become a dependency of core `src/` files — this subpath is the one
156
+ * place it's imported, and callers must supply their own model resolver so no
157
+ * concrete provider package (e.g. `@ai-sdk/openai`) becomes a dependency here
158
+ * either.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * const executors = createAiSdkExecutors({ models: { quick: openai('gpt-5.4-mini') } });
163
+ * const result = await runAgent(machine, { input, executors });
164
+ * ```
165
+ */
166
+ declare function createAiSdkExecutors<TModels extends AiSdkModelMap>(options: CreateAiSdkExecutorsOptions<TModels>): AiSdkExecutors;
167
+ /** AI SDK host for a machine authored with `setupAgent({ models })`. */
168
+ declare function runAgent<TMachine extends _$xstate.AnyStateMachine>(machine: TMachine, options: Omit<RunAgentOptions<TMachine>, "executors">): Promise<RunAgentResult<TMachine>>;
169
+ type CreateAgentMachineConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap, TOutputSchema extends StandardSchemaV1, TModels extends AiSdkModelMap> = Omit<AgentMachineConfig<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, TModels>, "schemas">;
170
+ type CreateAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap, TOutputSchema extends StandardSchemaV1, TModels extends AiSdkModelMap> = CreateAgentMachineConfig<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, TModels> & {
171
+ schemas: {
172
+ context: TContextSchema;
173
+ input: TInputSchema;
174
+ events?: TEventSchemas;
175
+ output?: TOutputSchema;
176
+ };
177
+ };
178
+ interface CreatedAgent<TMachine extends _$xstate.AnyStateMachine> {
179
+ machine: TMachine;
180
+ run(input: _$xstate.InputFrom<TMachine>, options?: Omit<RunAgentOptions<TMachine>, "input" | "executors">): Promise<RunAgentResult<TMachine>>;
181
+ }
182
+ /**
183
+ * One-call AI SDK entry point for the common case: creates a typed machine and
184
+ * a `run(input)` method with model executors already wired.
185
+ */
186
+ declare function createAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap = {}, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1>(config: CreateAgentBaseConfig<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, AiSdkModelMap<"default">> & {
187
+ model: LanguageModel;
188
+ models?: never;
189
+ }): CreatedAgent<AgentMachine<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, AiSdkModelMap<"default">>>;
190
+ declare function createAgent<TModels extends AiSdkModelMap, TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap = {}, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1>(config: CreateAgentBaseConfig<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, TModels> & {
191
+ models: TModels;
192
+ model?: never;
193
+ }): CreatedAgent<AgentMachine<TContextSchema, TInputSchema, TEventSchemas, TOutputSchema, TModels>>;
194
+ /** One AI SDK `tool()` per candidate event — the "tool-per-event +
195
+ * toolChoice: 'required'" recipe from .scratch/p0-design.md §2.6. */
196
+ declare function toAiSdkEventTools(events: AgentEventDescriptor[]): {
197
+ [k: string]: Tool<unknown, never>;
198
+ };
199
+ /**
200
+ * Messages for a decision request, with prior failed `attempts` (§2.6)
201
+ * rendered as appended user messages (via core's {@link renderDecisionAttempts})
202
+ * so retries converge. Core never rewrites prompts — this is adapter business.
203
+ */
204
+ declare function toDecisionMessages(request: Pick<AgentDecisionRequest, "messages" | "prompt" | "events" | "attempts">): ModelMessage[] | undefined;
205
+ //#endregion
206
+ export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, CreatedAgent, createAgent, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, runAgent, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };