@statelyai/agent 2.0.0-alpha.10 → 2.0.0-alpha.12

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 (62) hide show
  1. package/dist/ai-sdk.cjs +62 -99
  2. package/dist/ai-sdk.d.cts +10 -117
  3. package/dist/ai-sdk.d.mts +10 -117
  4. package/dist/ai-sdk.mjs +63 -91
  5. package/dist/{decision-CQdrKc8k.mjs → decision-BezSD_YC.mjs} +120 -32
  6. package/dist/{decision-b-lkcs4L.cjs → decision-dWGhBh0P.cjs} +141 -53
  7. package/dist/errors-BQRk9eiZ.d.cts +19 -0
  8. package/dist/errors-C9rxnWbX.d.mts +19 -0
  9. package/dist/errors-CeSXQx0v.mjs +23 -0
  10. package/dist/errors-DUBBzRLP.cjs +28 -0
  11. package/dist/event-log-store-CNT_7F0V.cjs +452 -0
  12. package/dist/event-log-store-CriMgX1D.d.mts +144 -0
  13. package/dist/event-log-store-D7pWtIhb.mjs +411 -0
  14. package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
  15. package/dist/index.cjs +2844 -30
  16. package/dist/index.d.cts +1005 -12
  17. package/dist/index.d.mts +1005 -12
  18. package/dist/index.mjs +2799 -4
  19. package/dist/machines.cjs +752 -0
  20. package/dist/machines.d.cts +372 -0
  21. package/dist/machines.d.mts +372 -0
  22. package/dist/machines.mjs +741 -0
  23. package/dist/otel.cjs +268 -0
  24. package/dist/otel.d.cts +67 -0
  25. package/dist/otel.d.mts +67 -0
  26. package/dist/otel.mjs +267 -0
  27. package/dist/run-agent-B1nBa7aV.d.mts +1111 -0
  28. package/dist/run-agent-qkg0evvW.d.cts +1111 -0
  29. package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
  30. package/dist/setup-agent-DP95MFrI.cjs +1836 -0
  31. package/dist/sqlite.cjs +135 -0
  32. package/dist/sqlite.d.cts +57 -0
  33. package/dist/sqlite.d.mts +57 -0
  34. package/dist/sqlite.mjs +133 -0
  35. package/dist/{text-logic-C7WJpCIc.d.mts → text-logic-CorGzucG.d.cts} +110 -66
  36. package/dist/{text-logic-CZjyACzQ.d.cts → text-logic-DjR5PUVz.d.mts} +110 -66
  37. package/dist/{types-C9QiMjre.d.cts → types-QbEfCVny.d.cts} +1 -1
  38. package/dist/{types-qm00QF91.d.mts → types-_FXoFBGO.d.mts} +1 -1
  39. package/package.json +55 -27
  40. package/readme.md +40 -9
  41. package/schemas/agent-workflow.json +44 -26
  42. package/skills/generate-machine/SKILL.md +267 -0
  43. package/dist/cli.cjs +0 -64
  44. package/dist/cli.d.cts +0 -1
  45. package/dist/cli.d.mts +0 -1
  46. package/dist/cli.mjs +0 -65
  47. package/dist/openai-compat.cjs +0 -319
  48. package/dist/openai-compat.d.cts +0 -98
  49. package/dist/openai-compat.d.mts +0 -98
  50. package/dist/openai-compat.mjs +0 -312
  51. package/dist/run-agent-BFMkuI1F.cjs +0 -1599
  52. package/dist/run-agent-BVMd--1l.d.cts +0 -1103
  53. package/dist/run-agent-BoAOq_0Z.mjs +0 -1540
  54. package/dist/run-agent-DzYJb3CK.d.mts +0 -1103
  55. package/dist/src-D-77Ha5p.cjs +0 -1087
  56. package/dist/src-DUeIFjv-.mjs +0 -1016
  57. package/dist/utils-Dri7aeEG.d.cts +0 -108
  58. package/dist/utils-Y6GDRGGE.d.mts +0 -108
  59. package/dist/zod.cjs +0 -31
  60. package/dist/zod.d.cts +0 -30
  61. package/dist/zod.d.mts +0 -30
  62. package/dist/zod.mjs +0 -30
package/dist/ai-sdk.cjs CHANGED
@@ -1,8 +1,7 @@
1
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");
2
+ const require_decision = require("./decision-dWGhBh0P.cjs");
4
3
  let ai = require("ai");
5
- //#region src/ai-sdk/index.ts
4
+ //#region src/ai-sdk/mappers.ts
6
5
  /**
7
6
  * Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
8
7
  * already carries its own Standard Schema `inputSchema` — an AI SDK
@@ -11,8 +10,7 @@ let ai = require("ai");
11
10
  * every extra property (`providerOptions`, `toModelOutput`, …) survives. A bare
12
11
  * `AgentToolExecute` function becomes a tool with an unconstrained input schema;
13
12
  * 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`.
13
+ * fallback. Used by {@link toAiSdkCallSettings}.
16
14
  */
17
15
  function toAiSdkTools(tools) {
18
16
  const entries = [];
@@ -45,9 +43,6 @@ function toAiSdkTools(tools) {
45
43
  }
46
44
  return Object.fromEntries(entries);
47
45
  }
48
- function maxStepsSetting(request) {
49
- return typeof request.metadata?.maxSteps === "number" ? { stopWhen: (0, ai.stepCountIs)(request.metadata.maxSteps) } : {};
50
- }
51
46
  const unknownSchema = { "~standard": {
52
47
  version: 1,
53
48
  vendor: "statelyai-agent",
@@ -55,35 +50,6 @@ const unknownSchema = { "~standard": {
55
50
  jsonSchema: { input: () => ({}) }
56
51
  } };
57
52
  /**
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
53
  * AI SDK request-mapping settings shared by `generateText`/`streamText`.
88
54
  * `AgentTextRequest.messages` (`AgentMessage[]`) and AI SDK's `ModelMessage[]`
89
55
  * are structurally compatible by design (§1 of .scratch/p0-design.md) — the cast
@@ -148,6 +114,65 @@ function extractFirstJsonValue(text) {
148
114
  }
149
115
  }
150
116
  }
117
+ /** One AI SDK `tool()` per candidate event — the "tool-per-event +
118
+ * toolChoice: 'required'" recipe from .scratch/p0-design.md §2.6. */
119
+ function toAiSdkEventTools(events) {
120
+ return Object.fromEntries(events.map((event) => [event.toolName, (0, ai.tool)({
121
+ description: `Choose the '${event.type}' move.`,
122
+ inputSchema: event.inputSchema ? event.inputSchema : unknownSchema
123
+ })]));
124
+ }
125
+ /**
126
+ * Messages for a decision request, with prior failed `attempts` (§2.6)
127
+ * rendered as appended user messages (via core's {@link renderDecisionAttempts})
128
+ * so retries converge. Core never rewrites prompts — this is adapter business.
129
+ */
130
+ function toDecisionMessages(request) {
131
+ if (!request.messages && request.attempts.length === 0) return;
132
+ const messages = [...request.messages ?? (request.prompt !== void 0 ? [{
133
+ role: "user",
134
+ content: request.prompt
135
+ }] : [])];
136
+ for (const attempt of require_decision.renderDecisionAttempts(request)) messages.push({
137
+ role: "user",
138
+ content: attempt.content
139
+ });
140
+ return messages;
141
+ }
142
+ //#endregion
143
+ //#region src/ai-sdk/index.ts
144
+ function maxStepsSetting(request) {
145
+ return typeof request.metadata?.maxSteps === "number" ? { stopWhen: (0, ai.stepCountIs)(request.metadata.maxSteps) } : {};
146
+ }
147
+ /**
148
+ * Identity helper for a `models` map whose value is exported. Returns the map
149
+ * unchanged, but types it as {@link AiSdkModelMap}`<keyof T & string>` — a
150
+ * portable, nameable type — so an exported `const models = defineModels({...})`
151
+ * needs no `Record<'a' | 'b', LanguageModel>` annotation and never triggers
152
+ * TS2742 ("inferred type cannot be named without a reference to …"). The exact
153
+ * ref keys survive, so `createAiSdkExecutors({ models })` and
154
+ * `setupAgent({ models })` still infer/autocomplete them.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * export const models = defineModels({
159
+ * quick: openai('gpt-5.4-mini'),
160
+ * deep: openai('gpt-5.4'),
161
+ * });
162
+ * // typeof models === AiSdkModelMap<'quick' | 'deep'>
163
+ * ```
164
+ */
165
+ function defineModels(models) {
166
+ return models;
167
+ }
168
+ function resolveAiSdkModel(options, modelRef) {
169
+ if (options.resolveModel) return options.resolveModel(modelRef);
170
+ const models = options.models;
171
+ if (!models) throw new Error(`createAiSdkExecutors: no model resolver configured for '${modelRef}'.`);
172
+ const model = models[modelRef];
173
+ if (!model) throw new Error(`createAiSdkExecutors: unknown model '${modelRef}'.`);
174
+ return model;
175
+ }
151
176
  function withJsonRepair(output) {
152
177
  return {
153
178
  ...output,
@@ -275,68 +300,6 @@ function createAiSdkExecutors(options) {
275
300
  decide
276
301
  };
277
302
  }
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
303
  //#endregion
332
- exports.createAgent = createAgent;
333
304
  exports.createAiSdkExecutors = createAiSdkExecutors;
334
305
  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;
package/dist/ai-sdk.d.cts CHANGED
@@ -1,24 +1,8 @@
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";
1
+ import { d as ChosenEvent } from "./types-QbEfCVny.cjs";
2
+ import { O as AgentDecisionExecutor, a as AgentRequestExecutor, c as AgentRequestExecutors } from "./text-logic-CorGzucG.cjs";
3
+ import { FinishReason, LanguageModel, LanguageModelUsage, ToolSet, TypedToolCall, TypedToolResult } from "ai";
6
4
 
7
5
  //#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
6
  /** 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
7
  type AiSdkModelMap<TKey extends string = string> = Record<TKey, LanguageModel>;
24
8
  /**
@@ -53,63 +37,6 @@ type CreateAiSdkExecutorsOptions<TModels extends AiSdkModelMap = AiSdkModelMap>
53
37
  models?: TModels;
54
38
  resolveModel: (modelRef: string) => LanguageModel;
55
39
  };
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
40
  /**
114
41
  * Raw result shape from {@link AiSdkExecutors.generateText} — the `{ output }`
115
42
  * envelope (the validated structured object for structured-output requests,
@@ -125,6 +52,9 @@ type AiSdkGenerateResult = {
125
52
  * `reasoning: true` and the model produced it (see the structured-output
126
53
  * envelope in {@link buildEnvelopeSchema}). Never enters machine context/output. */
127
54
  reasoning?: string;
55
+ /** The call's token usage. Its flat `inputTokens`/`outputTokens`/`totalTokens`/
56
+ * `reasoningTokens`/`cachedInputTokens` fields are what `runAgent` folds into
57
+ * the run result's aggregated `AgentUsage`. */
128
58
  usage: LanguageModelUsage;
129
59
  finishReason: FinishReason;
130
60
  toolCalls: TypedToolCall<ToolSet>[];
@@ -132,13 +62,13 @@ type AiSdkGenerateResult = {
132
62
  };
133
63
  /** 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
64
  type AiSdkStreamResult = {
135
- output: string;
65
+ output: string; /** The stream's final (awaited) usage; aggregated into the run result's `AgentUsage`. */
136
66
  usage: LanguageModelUsage;
137
67
  finishReason: FinishReason;
138
68
  };
139
69
  /** Raw result shape from {@link AiSdkExecutors.decide} — the chosen event plus the AI SDK call metadata, delivered per decision attempt to `onResult`. */
140
70
  type AiSdkDecideResult = {
141
- event: ChosenEvent;
71
+ event: ChosenEvent; /** This attempt's usage; aggregated into the run result's `AgentUsage`. */
142
72
  usage: LanguageModelUsage;
143
73
  finishReason: FinishReason;
144
74
  };
@@ -146,6 +76,7 @@ type AiSdkDecideResult = {
146
76
  * general `AgentRequestExecutors`, where `streamText`/`decide` are optional),
147
77
  * and its `generateText`/`streamText` results are concretely typed. */
148
78
  interface AiSdkExecutors extends AgentRequestExecutors<AiSdkGenerateResult, AiSdkStreamResult> {
79
+ generateText: AgentRequestExecutor<AiSdkGenerateResult>;
149
80
  streamText: AgentRequestExecutor<AiSdkStreamResult>;
150
81
  decide: AgentDecisionExecutor;
151
82
  }
@@ -164,43 +95,5 @@ interface AiSdkExecutors extends AgentRequestExecutors<AiSdkGenerateResult, AiSd
164
95
  * ```
165
96
  */
166
97
  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
98
  //#endregion
206
- export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, CreatedAgent, createAgent, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, runAgent, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
99
+ export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels };
package/dist/ai-sdk.d.mts CHANGED
@@ -1,24 +1,8 @@
1
- import { C as StandardSchemaV1, m as ChosenEvent, n as AgentEventSchemaInputMap, u as AgentTools } from "./types-qm00QF91.mjs";
2
- import { H as AgentEventDescriptor, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-C7WJpCIc.mjs";
3
- import { D as AgentMachine, O as AgentMachineConfig, l as RunAgentOptions, u as RunAgentResult } from "./run-agent-DzYJb3CK.mjs";
4
- import * as _$xstate from "xstate";
5
- import { FinishReason, LanguageModel, LanguageModelUsage, ModelMessage, Tool, ToolSet, TypedToolCall, TypedToolResult } from "ai";
1
+ import { d as ChosenEvent } from "./types-_FXoFBGO.mjs";
2
+ import { O as AgentDecisionExecutor, a as AgentRequestExecutor, c as AgentRequestExecutors } from "./text-logic-DjR5PUVz.mjs";
3
+ import { FinishReason, LanguageModel, LanguageModelUsage, ToolSet, TypedToolCall, TypedToolResult } from "ai";
6
4
 
7
5
  //#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
6
  /** 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
7
  type AiSdkModelMap<TKey extends string = string> = Record<TKey, LanguageModel>;
24
8
  /**
@@ -53,63 +37,6 @@ type CreateAiSdkExecutorsOptions<TModels extends AiSdkModelMap = AiSdkModelMap>
53
37
  models?: TModels;
54
38
  resolveModel: (modelRef: string) => LanguageModel;
55
39
  };
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
40
  /**
114
41
  * Raw result shape from {@link AiSdkExecutors.generateText} — the `{ output }`
115
42
  * envelope (the validated structured object for structured-output requests,
@@ -125,6 +52,9 @@ type AiSdkGenerateResult = {
125
52
  * `reasoning: true` and the model produced it (see the structured-output
126
53
  * envelope in {@link buildEnvelopeSchema}). Never enters machine context/output. */
127
54
  reasoning?: string;
55
+ /** The call's token usage. Its flat `inputTokens`/`outputTokens`/`totalTokens`/
56
+ * `reasoningTokens`/`cachedInputTokens` fields are what `runAgent` folds into
57
+ * the run result's aggregated `AgentUsage`. */
128
58
  usage: LanguageModelUsage;
129
59
  finishReason: FinishReason;
130
60
  toolCalls: TypedToolCall<ToolSet>[];
@@ -132,13 +62,13 @@ type AiSdkGenerateResult = {
132
62
  };
133
63
  /** 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
64
  type AiSdkStreamResult = {
135
- output: string;
65
+ output: string; /** The stream's final (awaited) usage; aggregated into the run result's `AgentUsage`. */
136
66
  usage: LanguageModelUsage;
137
67
  finishReason: FinishReason;
138
68
  };
139
69
  /** Raw result shape from {@link AiSdkExecutors.decide} — the chosen event plus the AI SDK call metadata, delivered per decision attempt to `onResult`. */
140
70
  type AiSdkDecideResult = {
141
- event: ChosenEvent;
71
+ event: ChosenEvent; /** This attempt's usage; aggregated into the run result's `AgentUsage`. */
142
72
  usage: LanguageModelUsage;
143
73
  finishReason: FinishReason;
144
74
  };
@@ -146,6 +76,7 @@ type AiSdkDecideResult = {
146
76
  * general `AgentRequestExecutors`, where `streamText`/`decide` are optional),
147
77
  * and its `generateText`/`streamText` results are concretely typed. */
148
78
  interface AiSdkExecutors extends AgentRequestExecutors<AiSdkGenerateResult, AiSdkStreamResult> {
79
+ generateText: AgentRequestExecutor<AiSdkGenerateResult>;
149
80
  streamText: AgentRequestExecutor<AiSdkStreamResult>;
150
81
  decide: AgentDecisionExecutor;
151
82
  }
@@ -164,43 +95,5 @@ interface AiSdkExecutors extends AgentRequestExecutors<AiSdkGenerateResult, AiSd
164
95
  * ```
165
96
  */
166
97
  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
98
  //#endregion
206
- export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, CreatedAgent, createAgent, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, runAgent, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
99
+ export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels };