@funkai/agents 0.1.0
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.
- package/.generated/req.txt +1 -0
- package/.turbo/turbo-build.log +21 -0
- package/.turbo/turbo-test$colon$coverage.log +109 -0
- package/.turbo/turbo-test.log +141 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/CHANGELOG.md +16 -0
- package/ISSUES.md +540 -0
- package/LICENSE +21 -0
- package/README.md +128 -0
- package/banner.svg +97 -0
- package/coverage/lcov-report/base.css +224 -0
- package/coverage/lcov-report/block-navigation.js +87 -0
- package/coverage/lcov-report/core/agents/base/agent.ts.html +1705 -0
- package/coverage/lcov-report/core/agents/base/index.html +146 -0
- package/coverage/lcov-report/core/agents/base/output.ts.html +256 -0
- package/coverage/lcov-report/core/agents/base/utils.ts.html +694 -0
- package/coverage/lcov-report/core/agents/flow/engine.ts.html +928 -0
- package/coverage/lcov-report/core/agents/flow/flow-agent.ts.html +1462 -0
- package/coverage/lcov-report/core/agents/flow/index.html +146 -0
- package/coverage/lcov-report/core/agents/flow/messages.ts.html +508 -0
- package/coverage/lcov-report/core/agents/flow/steps/factory.ts.html +1975 -0
- package/coverage/lcov-report/core/agents/flow/steps/index.html +116 -0
- package/coverage/lcov-report/core/index.html +131 -0
- package/coverage/lcov-report/core/logger.ts.html +541 -0
- package/coverage/lcov-report/core/models/providers/index.html +116 -0
- package/coverage/lcov-report/core/models/providers/openai.ts.html +337 -0
- package/coverage/lcov-report/core/provider/index.html +131 -0
- package/coverage/lcov-report/core/provider/provider.ts.html +346 -0
- package/coverage/lcov-report/core/provider/usage.ts.html +376 -0
- package/coverage/lcov-report/core/tool.ts.html +577 -0
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +221 -0
- package/coverage/lcov-report/lib/hooks.ts.html +262 -0
- package/coverage/lcov-report/lib/index.html +161 -0
- package/coverage/lcov-report/lib/middleware.ts.html +274 -0
- package/coverage/lcov-report/lib/runnable.ts.html +151 -0
- package/coverage/lcov-report/lib/trace.ts.html +520 -0
- package/coverage/lcov-report/prettify.css +1 -0
- package/coverage/lcov-report/prettify.js +2 -0
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +210 -0
- package/coverage/lcov-report/utils/attempt.ts.html +199 -0
- package/coverage/lcov-report/utils/error.ts.html +421 -0
- package/coverage/lcov-report/utils/index.html +176 -0
- package/coverage/lcov-report/utils/resolve.ts.html +208 -0
- package/coverage/lcov-report/utils/result.ts.html +538 -0
- package/coverage/lcov-report/utils/zod.ts.html +178 -0
- package/coverage/lcov.info +1566 -0
- package/dist/index.d.mts +2883 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2312 -0
- package/dist/index.mjs.map +1 -0
- package/docs/core/agent.md +231 -0
- package/docs/core/hooks.md +95 -0
- package/docs/core/overview.md +87 -0
- package/docs/core/step.md +279 -0
- package/docs/core/tools.md +98 -0
- package/docs/core/workflow.md +235 -0
- package/docs/guides/create-agent.md +224 -0
- package/docs/guides/create-tool.md +137 -0
- package/docs/guides/create-workflow.md +374 -0
- package/docs/overview.md +244 -0
- package/docs/provider/models.md +55 -0
- package/docs/provider/overview.md +106 -0
- package/docs/provider/usage.md +100 -0
- package/docs/research/experimental-context.md +167 -0
- package/docs/research/gap-analysis.md +86 -0
- package/docs/research/prepare-step-and-active-tools.md +138 -0
- package/docs/research/sub-agent-model.md +249 -0
- package/docs/troubleshooting.md +60 -0
- package/logo.svg +17 -0
- package/models.config.json +18 -0
- package/package.json +60 -0
- package/scripts/generate-models.ts +324 -0
- package/src/core/agents/base/agent.test.ts +1522 -0
- package/src/core/agents/base/agent.ts +547 -0
- package/src/core/agents/base/output.test.ts +93 -0
- package/src/core/agents/base/output.ts +57 -0
- package/src/core/agents/base/types.test-d.ts +69 -0
- package/src/core/agents/base/types.ts +503 -0
- package/src/core/agents/base/utils.test.ts +397 -0
- package/src/core/agents/base/utils.ts +197 -0
- package/src/core/agents/flow/engine.test.ts +452 -0
- package/src/core/agents/flow/engine.ts +281 -0
- package/src/core/agents/flow/flow-agent.test.ts +1027 -0
- package/src/core/agents/flow/flow-agent.ts +473 -0
- package/src/core/agents/flow/messages.test.ts +198 -0
- package/src/core/agents/flow/messages.ts +141 -0
- package/src/core/agents/flow/steps/agent.test.ts +280 -0
- package/src/core/agents/flow/steps/agent.ts +87 -0
- package/src/core/agents/flow/steps/all.test.ts +300 -0
- package/src/core/agents/flow/steps/all.ts +73 -0
- package/src/core/agents/flow/steps/builder.ts +124 -0
- package/src/core/agents/flow/steps/each.test.ts +257 -0
- package/src/core/agents/flow/steps/each.ts +61 -0
- package/src/core/agents/flow/steps/factory.test-d.ts +50 -0
- package/src/core/agents/flow/steps/factory.test.ts +1025 -0
- package/src/core/agents/flow/steps/factory.ts +645 -0
- package/src/core/agents/flow/steps/map.test.ts +273 -0
- package/src/core/agents/flow/steps/map.ts +75 -0
- package/src/core/agents/flow/steps/race.test.ts +290 -0
- package/src/core/agents/flow/steps/race.ts +59 -0
- package/src/core/agents/flow/steps/reduce.test.ts +310 -0
- package/src/core/agents/flow/steps/reduce.ts +73 -0
- package/src/core/agents/flow/steps/result.ts +27 -0
- package/src/core/agents/flow/steps/step.test.ts +402 -0
- package/src/core/agents/flow/steps/step.ts +51 -0
- package/src/core/agents/flow/steps/while.test.ts +283 -0
- package/src/core/agents/flow/steps/while.ts +75 -0
- package/src/core/agents/flow/types.ts +348 -0
- package/src/core/logger.test.ts +163 -0
- package/src/core/logger.ts +152 -0
- package/src/core/models/index.test.ts +137 -0
- package/src/core/models/index.ts +152 -0
- package/src/core/models/providers/openai.ts +84 -0
- package/src/core/provider/provider.test.ts +128 -0
- package/src/core/provider/provider.ts +99 -0
- package/src/core/provider/types.ts +98 -0
- package/src/core/provider/usage.test.ts +304 -0
- package/src/core/provider/usage.ts +97 -0
- package/src/core/tool.test.ts +65 -0
- package/src/core/tool.ts +164 -0
- package/src/core/types.ts +66 -0
- package/src/index.ts +95 -0
- package/src/lib/context.test.ts +86 -0
- package/src/lib/context.ts +49 -0
- package/src/lib/hooks.test.ts +102 -0
- package/src/lib/hooks.ts +59 -0
- package/src/lib/middleware.test.ts +122 -0
- package/src/lib/middleware.ts +63 -0
- package/src/lib/runnable.test.ts +41 -0
- package/src/lib/runnable.ts +22 -0
- package/src/lib/trace.test.ts +291 -0
- package/src/lib/trace.ts +145 -0
- package/src/models/index.ts +123 -0
- package/src/models/providers/index.ts +15 -0
- package/src/models/providers/openai.ts +84 -0
- package/src/testing/context.ts +32 -0
- package/src/testing/index.ts +2 -0
- package/src/testing/logger.ts +19 -0
- package/src/utils/attempt.test.ts +127 -0
- package/src/utils/attempt.ts +38 -0
- package/src/utils/error.test.ts +179 -0
- package/src/utils/error.ts +112 -0
- package/src/utils/resolve.test.ts +38 -0
- package/src/utils/resolve.ts +41 -0
- package/src/utils/result.test.ts +79 -0
- package/src/utils/result.ts +151 -0
- package/src/utils/zod.test.ts +69 -0
- package/src/utils/zod.ts +31 -0
- package/tsconfig.json +25 -0
- package/tsdown.config.ts +15 -0
- package/vitest.config.ts +46 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,2883 @@
|
|
|
1
|
+
import { AsyncIterableStream, AsyncIterableStream as AsyncIterableStream$1, LanguageModel as LanguageModel$1, ModelMessage, Output, Output as Output$1, TextStreamPart, TextStreamPart as TextStreamPart$1, ToolSet, ToolSet as ToolSet$1, tool as tool$1 } from "ai";
|
|
2
|
+
import { ZodType } from "zod";
|
|
3
|
+
import { OpenRouterProvider, OpenRouterProviderSettings } from "@openrouter/ai-sdk-provider";
|
|
4
|
+
import { LiteralUnion } from "type-fest";
|
|
5
|
+
|
|
6
|
+
//#region src/core/tool.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Configuration for creating a tool.
|
|
9
|
+
*
|
|
10
|
+
* @typeParam TInput - Input type, inferred from the `inputSchema` Zod schema.
|
|
11
|
+
* @typeParam TOutput - Output type, inferred from the `execute` return.
|
|
12
|
+
*/
|
|
13
|
+
interface ToolConfig<TInput, TOutput> {
|
|
14
|
+
/**
|
|
15
|
+
* Human-readable description of what the tool does.
|
|
16
|
+
*
|
|
17
|
+
* Shown to the model alongside the tool name. A good description
|
|
18
|
+
* helps the model decide when and how to call the tool.
|
|
19
|
+
*/
|
|
20
|
+
description: string;
|
|
21
|
+
/**
|
|
22
|
+
* Display title for the tool.
|
|
23
|
+
*
|
|
24
|
+
* Optional human-readable title shown in UIs and logs.
|
|
25
|
+
*/
|
|
26
|
+
title?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Zod schema for validating and typing tool input.
|
|
29
|
+
*
|
|
30
|
+
* The schema is serialized to JSON Schema and sent to the model.
|
|
31
|
+
* Input from the model is validated against it before `execute`
|
|
32
|
+
* is called.
|
|
33
|
+
*/
|
|
34
|
+
inputSchema: ZodType<TInput>;
|
|
35
|
+
/**
|
|
36
|
+
* Zod schema for validating tool output.
|
|
37
|
+
*
|
|
38
|
+
* When provided, the return value of `execute` is validated
|
|
39
|
+
* against this schema before being sent back to the model.
|
|
40
|
+
*/
|
|
41
|
+
outputSchema?: ZodType<TOutput>;
|
|
42
|
+
/**
|
|
43
|
+
* Example inputs to guide the model.
|
|
44
|
+
*
|
|
45
|
+
* Helps the model understand expected input structure. Natively
|
|
46
|
+
* supported by Anthropic; for other providers, use
|
|
47
|
+
* `addToolInputExamplesMiddleware` to inject examples into the
|
|
48
|
+
* tool description.
|
|
49
|
+
*/
|
|
50
|
+
inputExamples?: Array<{
|
|
51
|
+
input: TInput;
|
|
52
|
+
}>;
|
|
53
|
+
/**
|
|
54
|
+
* Execute the tool with validated input.
|
|
55
|
+
*
|
|
56
|
+
* Called by the framework after the model requests a tool call and
|
|
57
|
+
* the input passes schema validation.
|
|
58
|
+
*
|
|
59
|
+
* @param input - The validated tool input.
|
|
60
|
+
* @returns The tool output returned to the model.
|
|
61
|
+
*/
|
|
62
|
+
execute: (input: TInput) => Promise<TOutput>;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A tool instance — the return type of `tool()` / `ai.tool()`.
|
|
66
|
+
*
|
|
67
|
+
* Defaults use `any` so `Record<string, Tool>` accepts concrete
|
|
68
|
+
* typed tools without contravariance issues (same pattern as
|
|
69
|
+
* {@link SubAgents}).
|
|
70
|
+
*
|
|
71
|
+
* @typeParam TInput - Tool input type.
|
|
72
|
+
* @typeParam TOutput - Tool output type.
|
|
73
|
+
*/
|
|
74
|
+
type Tool<TInput = any, TOutput = any> = ReturnType<typeof tool$1<TInput, TOutput>>;
|
|
75
|
+
/**
|
|
76
|
+
* Create a tool for AI agent function calling.
|
|
77
|
+
*
|
|
78
|
+
* Wraps the AI SDK's `tool()` helper. The `inputSchema` (and optional
|
|
79
|
+
* `outputSchema`) are wrapped via `zodSchema()` so the AI SDK can
|
|
80
|
+
* convert them to JSON Schema and validate model I/O at runtime.
|
|
81
|
+
*
|
|
82
|
+
* @see https://ai-sdk.dev/docs/reference/ai-sdk-core/tool
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* const fetchPage = tool({
|
|
87
|
+
* description: 'Fetch the contents of a web page by URL',
|
|
88
|
+
* inputSchema: z.object({
|
|
89
|
+
* url: z.url(),
|
|
90
|
+
* }),
|
|
91
|
+
* execute: async ({ url }) => {
|
|
92
|
+
* const res = await fetch(url)
|
|
93
|
+
* return {
|
|
94
|
+
* url,
|
|
95
|
+
* status: res.status,
|
|
96
|
+
* body: await res.text(),
|
|
97
|
+
* }
|
|
98
|
+
* },
|
|
99
|
+
* })
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
declare function tool<TInput, TOutput>(config: ToolConfig<TInput, TOutput>): Tool<TInput, TOutput>;
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/core/agents/base/output.d.ts
|
|
105
|
+
/**
|
|
106
|
+
* Base constraint for AI SDK output strategies.
|
|
107
|
+
*
|
|
108
|
+
* Reaches through the `Output` namespace to the underlying
|
|
109
|
+
* `Output<OUTPUT, PARTIAL, ELEMENT>` interface. Use this as the
|
|
110
|
+
* type for any field that accepts `Output.text()`, `Output.object()`, etc.
|
|
111
|
+
*/
|
|
112
|
+
type OutputSpec = Output$1.Output<unknown, unknown>;
|
|
113
|
+
/**
|
|
114
|
+
* Accepted values for the `output` config field.
|
|
115
|
+
*
|
|
116
|
+
* Allows either:
|
|
117
|
+
* - An AI SDK `Output` strategy (`Output.text()`, `Output.object()`, etc.)
|
|
118
|
+
* - A raw Zod schema — automatically wrapped in `Output.object()` or
|
|
119
|
+
* `Output.array()` depending on the schema type.
|
|
120
|
+
*/
|
|
121
|
+
type OutputParam = OutputSpec | ZodType;
|
|
122
|
+
/**
|
|
123
|
+
* Resolve an `OutputParam` into an `OutputSpec`.
|
|
124
|
+
*
|
|
125
|
+
* If the value is already an `OutputSpec`, it is returned as-is.
|
|
126
|
+
* If it is a raw Zod schema:
|
|
127
|
+
* - `z.array(...)` → `Output.array({ element: innerSchema })`
|
|
128
|
+
* - Anything else → `Output.object({ schema })`
|
|
129
|
+
*
|
|
130
|
+
* @internal
|
|
131
|
+
*/
|
|
132
|
+
declare function resolveOutput(output: OutputParam): OutputSpec;
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/core/logger.d.ts
|
|
135
|
+
/**
|
|
136
|
+
* Pino-compatible leveled logger with child logger support.
|
|
137
|
+
*
|
|
138
|
+
* Consumers inject a pino instance (or any compatible logger);
|
|
139
|
+
* the SDK defines only the interface. Each method supports both
|
|
140
|
+
* `(msg, meta?)` and `(meta, msg)` call signatures to match pino's API.
|
|
141
|
+
*
|
|
142
|
+
* Child loggers accumulate bindings from parents — the framework
|
|
143
|
+
* uses `child()` at each scope boundary (workflow, step, agent)
|
|
144
|
+
* so log output automatically includes execution context.
|
|
145
|
+
*/
|
|
146
|
+
interface Logger {
|
|
147
|
+
/**
|
|
148
|
+
* Log a message at the DEBUG level.
|
|
149
|
+
*
|
|
150
|
+
* Use for verbose diagnostic output that is typically silenced
|
|
151
|
+
* in production (e.g. intermediate state, resolved config).
|
|
152
|
+
*
|
|
153
|
+
* @param msg - Human-readable log message.
|
|
154
|
+
* @param meta - Optional structured metadata merged into the log entry.
|
|
155
|
+
*/
|
|
156
|
+
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
157
|
+
/**
|
|
158
|
+
* Log a message at the DEBUG level (pino object-first overload).
|
|
159
|
+
*
|
|
160
|
+
* @param meta - Structured metadata merged into the log entry.
|
|
161
|
+
* @param msg - Human-readable log message.
|
|
162
|
+
*/
|
|
163
|
+
debug(meta: Record<string, unknown>, msg: string): void;
|
|
164
|
+
/**
|
|
165
|
+
* Log a message at the INFO level.
|
|
166
|
+
*
|
|
167
|
+
* Use for routine operational events worth recording — step
|
|
168
|
+
* transitions, successful completions, and notable state changes.
|
|
169
|
+
*
|
|
170
|
+
* @param msg - Human-readable log message.
|
|
171
|
+
* @param meta - Optional structured metadata merged into the log entry.
|
|
172
|
+
*/
|
|
173
|
+
info(msg: string, meta?: Record<string, unknown>): void;
|
|
174
|
+
/**
|
|
175
|
+
* Log a message at the INFO level (pino object-first overload).
|
|
176
|
+
*
|
|
177
|
+
* @param meta - Structured metadata merged into the log entry.
|
|
178
|
+
* @param msg - Human-readable log message.
|
|
179
|
+
*/
|
|
180
|
+
info(meta: Record<string, unknown>, msg: string): void;
|
|
181
|
+
/**
|
|
182
|
+
* Log a message at the WARN level.
|
|
183
|
+
*
|
|
184
|
+
* Use for recoverable problems that do not halt execution but
|
|
185
|
+
* may indicate degraded behavior (e.g. retries, fallback paths).
|
|
186
|
+
*
|
|
187
|
+
* @param msg - Human-readable log message.
|
|
188
|
+
* @param meta - Optional structured metadata merged into the log entry.
|
|
189
|
+
*/
|
|
190
|
+
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
191
|
+
/**
|
|
192
|
+
* Log a message at the WARN level (pino object-first overload).
|
|
193
|
+
*
|
|
194
|
+
* @param meta - Structured metadata merged into the log entry.
|
|
195
|
+
* @param msg - Human-readable log message.
|
|
196
|
+
*/
|
|
197
|
+
warn(meta: Record<string, unknown>, msg: string): void;
|
|
198
|
+
/**
|
|
199
|
+
* Log a message at the ERROR level.
|
|
200
|
+
*
|
|
201
|
+
* Use for failures that prevent an operation from completing
|
|
202
|
+
* successfully — unhandled exceptions, rejected promises, or
|
|
203
|
+
* invariant violations.
|
|
204
|
+
*
|
|
205
|
+
* @param msg - Human-readable log message.
|
|
206
|
+
* @param meta - Optional structured metadata merged into the log entry.
|
|
207
|
+
*/
|
|
208
|
+
error(msg: string, meta?: Record<string, unknown>): void;
|
|
209
|
+
/**
|
|
210
|
+
* Log a message at the ERROR level (pino object-first overload).
|
|
211
|
+
*
|
|
212
|
+
* @param meta - Structured metadata merged into the log entry.
|
|
213
|
+
* @param msg - Human-readable log message.
|
|
214
|
+
*/
|
|
215
|
+
error(meta: Record<string, unknown>, msg: string): void;
|
|
216
|
+
/**
|
|
217
|
+
* Create a child logger that inherits all parent bindings.
|
|
218
|
+
*
|
|
219
|
+
* The returned logger automatically includes the merged bindings
|
|
220
|
+
* in every log entry. The framework calls `child()` at each scope
|
|
221
|
+
* boundary (workflow, step, agent) so downstream logs carry full
|
|
222
|
+
* execution context without manual threading.
|
|
223
|
+
*
|
|
224
|
+
* @param bindings - Key-value pairs merged into every log entry
|
|
225
|
+
* produced by the child (and its descendants).
|
|
226
|
+
* @returns A new {@link Logger} with the accumulated bindings.
|
|
227
|
+
*/
|
|
228
|
+
child(bindings: Record<string, unknown>): Logger;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Create a minimal console-based logger satisfying the {@link Logger} interface.
|
|
232
|
+
*
|
|
233
|
+
* Supports `child()` by merging bindings into a prefix object.
|
|
234
|
+
* Each log call prepends the accumulated bindings to the output.
|
|
235
|
+
*
|
|
236
|
+
* Used as the default when no pino-compatible logger is injected.
|
|
237
|
+
*/
|
|
238
|
+
declare function createDefaultLogger(bindings?: Record<string, unknown>): Logger;
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/core/models/index.d.ts
|
|
241
|
+
declare const GENERATED_MODELS: readonly [{
|
|
242
|
+
readonly id: "openai/gpt-5.2-codex";
|
|
243
|
+
readonly category: "coding";
|
|
244
|
+
readonly pricing: {
|
|
245
|
+
readonly prompt: 0.00000175;
|
|
246
|
+
readonly completion: 0.000014;
|
|
247
|
+
readonly inputCacheRead: 1.75e-7;
|
|
248
|
+
readonly webSearch: 0.01;
|
|
249
|
+
};
|
|
250
|
+
}, {
|
|
251
|
+
readonly id: "openai/gpt-5.2";
|
|
252
|
+
readonly category: "chat";
|
|
253
|
+
readonly pricing: {
|
|
254
|
+
readonly prompt: 0.00000175;
|
|
255
|
+
readonly completion: 0.000014;
|
|
256
|
+
readonly inputCacheRead: 1.75e-7;
|
|
257
|
+
readonly webSearch: 0.01;
|
|
258
|
+
};
|
|
259
|
+
}, {
|
|
260
|
+
readonly id: "openai/gpt-5.1";
|
|
261
|
+
readonly category: "chat";
|
|
262
|
+
readonly pricing: {
|
|
263
|
+
readonly prompt: 0.00000125;
|
|
264
|
+
readonly completion: 0.00001;
|
|
265
|
+
readonly inputCacheRead: 1.25e-7;
|
|
266
|
+
readonly webSearch: 0.01;
|
|
267
|
+
};
|
|
268
|
+
}, {
|
|
269
|
+
readonly id: "openai/gpt-5";
|
|
270
|
+
readonly category: "chat";
|
|
271
|
+
readonly pricing: {
|
|
272
|
+
readonly prompt: 0.00000125;
|
|
273
|
+
readonly completion: 0.00001;
|
|
274
|
+
readonly inputCacheRead: 1.25e-7;
|
|
275
|
+
readonly webSearch: 0.01;
|
|
276
|
+
};
|
|
277
|
+
}, {
|
|
278
|
+
readonly id: "openai/gpt-5-mini";
|
|
279
|
+
readonly category: "chat";
|
|
280
|
+
readonly pricing: {
|
|
281
|
+
readonly prompt: 2.5e-7;
|
|
282
|
+
readonly completion: 0.000002;
|
|
283
|
+
readonly inputCacheRead: 2.5e-8;
|
|
284
|
+
readonly webSearch: 0.01;
|
|
285
|
+
};
|
|
286
|
+
}, {
|
|
287
|
+
readonly id: "openai/gpt-5-nano";
|
|
288
|
+
readonly category: "chat";
|
|
289
|
+
readonly pricing: {
|
|
290
|
+
readonly prompt: 5e-8;
|
|
291
|
+
readonly completion: 4e-7;
|
|
292
|
+
readonly inputCacheRead: 5e-9;
|
|
293
|
+
readonly webSearch: 0.01;
|
|
294
|
+
};
|
|
295
|
+
}, {
|
|
296
|
+
readonly id: "openai/gpt-4.1";
|
|
297
|
+
readonly category: "chat";
|
|
298
|
+
readonly pricing: {
|
|
299
|
+
readonly prompt: 0.000002;
|
|
300
|
+
readonly completion: 0.000008;
|
|
301
|
+
readonly inputCacheRead: 5e-7;
|
|
302
|
+
readonly webSearch: 0.01;
|
|
303
|
+
};
|
|
304
|
+
}, {
|
|
305
|
+
readonly id: "openai/gpt-4.1-mini";
|
|
306
|
+
readonly category: "chat";
|
|
307
|
+
readonly pricing: {
|
|
308
|
+
readonly prompt: 4e-7;
|
|
309
|
+
readonly completion: 0.0000016;
|
|
310
|
+
readonly inputCacheRead: 1e-7;
|
|
311
|
+
readonly webSearch: 0.01;
|
|
312
|
+
};
|
|
313
|
+
}, {
|
|
314
|
+
readonly id: "openai/gpt-4.1-nano";
|
|
315
|
+
readonly category: "chat";
|
|
316
|
+
readonly pricing: {
|
|
317
|
+
readonly prompt: 1e-7;
|
|
318
|
+
readonly completion: 4e-7;
|
|
319
|
+
readonly inputCacheRead: 2.5e-8;
|
|
320
|
+
readonly webSearch: 0.01;
|
|
321
|
+
};
|
|
322
|
+
}, {
|
|
323
|
+
readonly id: "openai/gpt-4o";
|
|
324
|
+
readonly category: "chat";
|
|
325
|
+
readonly pricing: {
|
|
326
|
+
readonly prompt: 0.0000025;
|
|
327
|
+
readonly completion: 0.00001;
|
|
328
|
+
readonly inputCacheRead: 0.00000125;
|
|
329
|
+
};
|
|
330
|
+
}, {
|
|
331
|
+
readonly id: "openai/gpt-4o-mini";
|
|
332
|
+
readonly category: "chat";
|
|
333
|
+
readonly pricing: {
|
|
334
|
+
readonly prompt: 1.5e-7;
|
|
335
|
+
readonly completion: 6e-7;
|
|
336
|
+
readonly inputCacheRead: 7.5e-8;
|
|
337
|
+
};
|
|
338
|
+
}, {
|
|
339
|
+
readonly id: "openai/o3";
|
|
340
|
+
readonly category: "reasoning";
|
|
341
|
+
readonly pricing: {
|
|
342
|
+
readonly prompt: 0.000002;
|
|
343
|
+
readonly completion: 0.000008;
|
|
344
|
+
readonly inputCacheRead: 5e-7;
|
|
345
|
+
readonly webSearch: 0.01;
|
|
346
|
+
};
|
|
347
|
+
}, {
|
|
348
|
+
readonly id: "openai/o3-mini";
|
|
349
|
+
readonly category: "reasoning";
|
|
350
|
+
readonly pricing: {
|
|
351
|
+
readonly prompt: 0.0000011;
|
|
352
|
+
readonly completion: 0.0000044;
|
|
353
|
+
readonly inputCacheRead: 5.5e-7;
|
|
354
|
+
};
|
|
355
|
+
}, {
|
|
356
|
+
readonly id: "openai/o4-mini";
|
|
357
|
+
readonly category: "reasoning";
|
|
358
|
+
readonly pricing: {
|
|
359
|
+
readonly prompt: 0.0000011;
|
|
360
|
+
readonly completion: 0.0000044;
|
|
361
|
+
readonly inputCacheRead: 2.75e-7;
|
|
362
|
+
readonly webSearch: 0.01;
|
|
363
|
+
};
|
|
364
|
+
}];
|
|
365
|
+
/**
|
|
366
|
+
* Supported OpenRouter model identifiers, derived from the generated {@link MODELS} array.
|
|
367
|
+
*/
|
|
368
|
+
type OpenRouterLanguageModelId = (typeof GENERATED_MODELS)[number]["id"];
|
|
369
|
+
/**
|
|
370
|
+
* A model identifier that suggests known OpenRouter models but accepts any string.
|
|
371
|
+
*
|
|
372
|
+
* Provides autocomplete for cataloged models while allowing arbitrary
|
|
373
|
+
* model IDs for new or custom models not yet in the catalog.
|
|
374
|
+
*/
|
|
375
|
+
type ModelId = LiteralUnion<OpenRouterLanguageModelId, string>;
|
|
376
|
+
/**
|
|
377
|
+
* Model category for classification and filtering.
|
|
378
|
+
*/
|
|
379
|
+
type ModelCategory = "chat" | "coding" | "reasoning";
|
|
380
|
+
/**
|
|
381
|
+
* Per-model pricing in USD per token.
|
|
382
|
+
*
|
|
383
|
+
* Field names match the OpenRouter API convention. All values are
|
|
384
|
+
* per-token (or per-unit) rates as numbers. Optional fields are
|
|
385
|
+
* omitted when the provider does not support them.
|
|
386
|
+
*/
|
|
387
|
+
interface ModelPricing {
|
|
388
|
+
/** Cost per input (prompt) token. */
|
|
389
|
+
prompt: number;
|
|
390
|
+
/** Cost per output (completion) token. */
|
|
391
|
+
completion: number;
|
|
392
|
+
/** Cost per cached input token (read). */
|
|
393
|
+
inputCacheRead?: number;
|
|
394
|
+
/** Cost per cached input token (write). */
|
|
395
|
+
inputCacheWrite?: number;
|
|
396
|
+
/** Cost per web search request. */
|
|
397
|
+
webSearch?: number;
|
|
398
|
+
/** Cost per internal reasoning token. */
|
|
399
|
+
internalReasoning?: number;
|
|
400
|
+
/** Cost per image input token. */
|
|
401
|
+
image?: number;
|
|
402
|
+
/** Cost per audio input second. */
|
|
403
|
+
audio?: number;
|
|
404
|
+
/** Cost per audio output second. */
|
|
405
|
+
audioOutput?: number;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Model definition with metadata and pricing.
|
|
409
|
+
*/
|
|
410
|
+
interface ModelDefinition {
|
|
411
|
+
/** OpenRouter model identifier (e.g. `"openai/gpt-5.2-codex"`). */
|
|
412
|
+
id: string;
|
|
413
|
+
/** Model category for classification. */
|
|
414
|
+
category: ModelCategory;
|
|
415
|
+
/** Token pricing rates. */
|
|
416
|
+
pricing: ModelPricing;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Look up a model definition by its identifier.
|
|
420
|
+
*
|
|
421
|
+
* @param id - The model identifier to look up.
|
|
422
|
+
* @returns The matching model definition.
|
|
423
|
+
* @throws {Error} If no model matches the given ID.
|
|
424
|
+
*
|
|
425
|
+
* @example
|
|
426
|
+
* ```typescript
|
|
427
|
+
* const m = model('openai/gpt-5.2-codex')
|
|
428
|
+
* console.log(m.pricing.prompt) // 0.00000175
|
|
429
|
+
* console.log(m.category) // 'coding'
|
|
430
|
+
* ```
|
|
431
|
+
*/
|
|
432
|
+
declare function model(id: ModelId): ModelDefinition;
|
|
433
|
+
/**
|
|
434
|
+
* Look up a model definition by its identifier, returning `undefined` if not found.
|
|
435
|
+
*
|
|
436
|
+
* Unlike {@link model}, this does not throw for unknown IDs — useful when
|
|
437
|
+
* the caller can gracefully handle missing pricing (e.g. non-OpenRouter models).
|
|
438
|
+
*
|
|
439
|
+
* @param id - The model identifier to look up.
|
|
440
|
+
* @returns The matching model definition, or `undefined`.
|
|
441
|
+
*
|
|
442
|
+
* @example
|
|
443
|
+
* ```typescript
|
|
444
|
+
* const m = tryModel('anthropic/claude-sonnet-4-20250514')
|
|
445
|
+
* if (m) {
|
|
446
|
+
* console.log(m.pricing.prompt)
|
|
447
|
+
* }
|
|
448
|
+
* ```
|
|
449
|
+
*/
|
|
450
|
+
declare function tryModel(id: ModelId): ModelDefinition | undefined;
|
|
451
|
+
/**
|
|
452
|
+
* Return supported model definitions, optionally filtered.
|
|
453
|
+
*
|
|
454
|
+
* @param filter - Optional predicate to filter models.
|
|
455
|
+
* @returns A readonly array of matching model definitions.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```typescript
|
|
459
|
+
* const all = models()
|
|
460
|
+
* const reasoning = models((m) => m.category === 'reasoning')
|
|
461
|
+
* ```
|
|
462
|
+
*/
|
|
463
|
+
declare function models(filter?: (m: ModelDefinition) => boolean): readonly ModelDefinition[];
|
|
464
|
+
//#endregion
|
|
465
|
+
//#region src/core/provider/types.d.ts
|
|
466
|
+
/**
|
|
467
|
+
* AI SDK v3 language model type.
|
|
468
|
+
*
|
|
469
|
+
* Narrowed to the v3 specification version for type safety.
|
|
470
|
+
* All models created via `openrouter()` or `wrapModel()` satisfy this type.
|
|
471
|
+
*/
|
|
472
|
+
type LanguageModel = Extract<LanguageModel$1, {
|
|
473
|
+
specificationVersion: "v3";
|
|
474
|
+
}>;
|
|
475
|
+
/**
|
|
476
|
+
* Base token counts shared by raw tracking records and final output.
|
|
477
|
+
*
|
|
478
|
+
* All fields are resolved `number` (0 when absent).
|
|
479
|
+
*/
|
|
480
|
+
interface TokenUsage {
|
|
481
|
+
/** Number of input (prompt) tokens. */
|
|
482
|
+
readonly inputTokens: number;
|
|
483
|
+
/** Number of output (completion) tokens. */
|
|
484
|
+
readonly outputTokens: number;
|
|
485
|
+
/** Total tokens (input + output). */
|
|
486
|
+
readonly totalTokens: number;
|
|
487
|
+
/** Tokens served from the provider's prompt cache. */
|
|
488
|
+
readonly cacheReadTokens: number;
|
|
489
|
+
/** Tokens written into the provider's prompt cache. */
|
|
490
|
+
readonly cacheWriteTokens: number;
|
|
491
|
+
/** Tokens consumed by the model's internal reasoning (e.g. o3/o4). */
|
|
492
|
+
readonly reasoningTokens: number;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Raw tracking record from a single AI model invocation.
|
|
496
|
+
*
|
|
497
|
+
* Fields are `number | undefined` because providers may not report all fields.
|
|
498
|
+
* Carries `modelId` so that consumers can look up pricing if needed.
|
|
499
|
+
*/
|
|
500
|
+
interface TokenUsageRecord {
|
|
501
|
+
/**
|
|
502
|
+
* The model identifier that produced this usage
|
|
503
|
+
* (e.g. `"openai/gpt-5.2-codex"`).
|
|
504
|
+
*/
|
|
505
|
+
readonly modelId: ModelId;
|
|
506
|
+
/** Number of input (prompt) tokens. */
|
|
507
|
+
readonly inputTokens: number | undefined;
|
|
508
|
+
/** Number of output (completion) tokens. */
|
|
509
|
+
readonly outputTokens: number | undefined;
|
|
510
|
+
/** Total tokens (input + output). */
|
|
511
|
+
readonly totalTokens: number | undefined;
|
|
512
|
+
/** Tokens served from the provider's prompt cache. */
|
|
513
|
+
readonly cacheReadTokens: number | undefined;
|
|
514
|
+
/** Tokens written into the provider's prompt cache. */
|
|
515
|
+
readonly cacheWriteTokens: number | undefined;
|
|
516
|
+
/** Tokens consumed by the model's internal reasoning (e.g. o3/o4). */
|
|
517
|
+
readonly reasoningTokens: number | undefined;
|
|
518
|
+
/**
|
|
519
|
+
* Populated by the framework — identifies which component produced this usage.
|
|
520
|
+
*/
|
|
521
|
+
readonly source?: {
|
|
522
|
+
readonly workflowId?: string;
|
|
523
|
+
readonly stepId?: string;
|
|
524
|
+
readonly agentId: string;
|
|
525
|
+
readonly scope: readonly string[];
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Final agent-level usage — tokens flat, with agentId.
|
|
530
|
+
*
|
|
531
|
+
* Produced by `agentUsage()` at the end of an agent's execution.
|
|
532
|
+
*/
|
|
533
|
+
interface AgentTokenUsage extends TokenUsage {
|
|
534
|
+
/** The agent that produced this usage. */
|
|
535
|
+
readonly agentId: string;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Final flow agent-level usage — per-agent breakdown.
|
|
539
|
+
*
|
|
540
|
+
* Produced by `flowAgentUsage()` at the end of a flow agent's execution.
|
|
541
|
+
*/
|
|
542
|
+
interface FlowAgentTokenUsage {
|
|
543
|
+
/** Per-agent usage entries. */
|
|
544
|
+
readonly usages: readonly AgentTokenUsage[];
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/utils/result.d.ts
|
|
548
|
+
/**
|
|
549
|
+
* Error information returned when an SDK operation fails.
|
|
550
|
+
*
|
|
551
|
+
* Every public method returns `Result<T>` instead of throwing.
|
|
552
|
+
* When `ok` is `false`, the error details are available on this interface.
|
|
553
|
+
*/
|
|
554
|
+
interface ResultError {
|
|
555
|
+
/**
|
|
556
|
+
* Machine-readable error code.
|
|
557
|
+
*
|
|
558
|
+
* Identifies the category of failure. Stable across versions —
|
|
559
|
+
* safe to match against in application code.
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```typescript
|
|
563
|
+
* switch (result.error.code) {
|
|
564
|
+
* case 'VALIDATION_ERROR': // input schema failed
|
|
565
|
+
* case 'ABORT_ERROR': // signal was aborted
|
|
566
|
+
* case 'AGENT_ERROR': // agent execution failed
|
|
567
|
+
* }
|
|
568
|
+
* ```
|
|
569
|
+
*/
|
|
570
|
+
code: string;
|
|
571
|
+
/**
|
|
572
|
+
* Human-readable error description.
|
|
573
|
+
*
|
|
574
|
+
* Suitable for logging but not for programmatic matching —
|
|
575
|
+
* use `code` for that.
|
|
576
|
+
*/
|
|
577
|
+
message: string;
|
|
578
|
+
/**
|
|
579
|
+
* Original thrown error, if any.
|
|
580
|
+
*
|
|
581
|
+
* Preserved so callers can inspect the root cause when the
|
|
582
|
+
* SDK catches and wraps an exception.
|
|
583
|
+
*/
|
|
584
|
+
cause?: Error;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Discriminated union for SDK operation results.
|
|
588
|
+
*
|
|
589
|
+
* Success fields are **flat on the object** — no `.value` wrapper.
|
|
590
|
+
* Callers pattern-match on `ok` instead of using try/catch.
|
|
591
|
+
*
|
|
592
|
+
* @typeParam T - The success payload shape. All fields from `T` are
|
|
593
|
+
* spread directly onto the success branch alongside `ok: true`.
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ```typescript
|
|
597
|
+
* const result = await agent.generate({ topic: 'TypeScript' })
|
|
598
|
+
*
|
|
599
|
+
* if (!result.ok) {
|
|
600
|
+
* // Error branch — only `ok` and `error` are present.
|
|
601
|
+
* console.error(result.error.code, result.error.message)
|
|
602
|
+
* return
|
|
603
|
+
* }
|
|
604
|
+
*
|
|
605
|
+
* // Success branch — all fields from T are directly on result.
|
|
606
|
+
* console.log(result.output)
|
|
607
|
+
* console.log(result.duration)
|
|
608
|
+
* console.log(result.trace)
|
|
609
|
+
* ```
|
|
610
|
+
*/
|
|
611
|
+
type Result<T> = (T & {
|
|
612
|
+
ok: true;
|
|
613
|
+
}) | {
|
|
614
|
+
ok: false;
|
|
615
|
+
error: ResultError;
|
|
616
|
+
};
|
|
617
|
+
/**
|
|
618
|
+
* Create a success `Result`.
|
|
619
|
+
*
|
|
620
|
+
* Spreads the payload flat onto the object alongside `ok: true`.
|
|
621
|
+
*
|
|
622
|
+
* @param value - The success payload.
|
|
623
|
+
* @returns A success `Result<T>`.
|
|
624
|
+
*
|
|
625
|
+
* @example
|
|
626
|
+
* ```typescript
|
|
627
|
+
* return ok({ output: 'hello', messages: [] })
|
|
628
|
+
* // → { ok: true, output: 'hello', messages: [] }
|
|
629
|
+
* ```
|
|
630
|
+
*/
|
|
631
|
+
declare function ok<T extends Record<string, unknown>>(value: T): T & {
|
|
632
|
+
ok: true;
|
|
633
|
+
};
|
|
634
|
+
/**
|
|
635
|
+
* Create a failure `Result`.
|
|
636
|
+
*
|
|
637
|
+
* @param code - Machine-readable error code.
|
|
638
|
+
* @param message - Human-readable error description.
|
|
639
|
+
* @param cause - Optional original thrown error.
|
|
640
|
+
* @returns A failure `Result` for any `T`.
|
|
641
|
+
*
|
|
642
|
+
* @example
|
|
643
|
+
* ```typescript
|
|
644
|
+
* return err('VALIDATION_ERROR', 'Name is required')
|
|
645
|
+
* return err('AGENT_ERROR', error.message, error)
|
|
646
|
+
* ```
|
|
647
|
+
*/
|
|
648
|
+
declare function err(code: string, message: string, cause?: Error): {
|
|
649
|
+
ok: false;
|
|
650
|
+
error: ResultError;
|
|
651
|
+
};
|
|
652
|
+
/**
|
|
653
|
+
* Narrow a `Result<T>` to its success branch.
|
|
654
|
+
*
|
|
655
|
+
* @param result - The result to check.
|
|
656
|
+
* @returns `true` when `result.ok` is `true`.
|
|
657
|
+
*
|
|
658
|
+
* @example
|
|
659
|
+
* ```typescript
|
|
660
|
+
* const result = await agent.generate('hello')
|
|
661
|
+
* if (isOk(result)) {
|
|
662
|
+
* console.log(result.output)
|
|
663
|
+
* }
|
|
664
|
+
* ```
|
|
665
|
+
*/
|
|
666
|
+
declare function isOk<T>(result: Result<T>): result is T & {
|
|
667
|
+
ok: true;
|
|
668
|
+
};
|
|
669
|
+
/**
|
|
670
|
+
* Narrow a `Result<T>` to its failure branch.
|
|
671
|
+
*
|
|
672
|
+
* @param result - The result to check.
|
|
673
|
+
* @returns `true` when `result.ok` is `false`.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* ```typescript
|
|
677
|
+
* const result = await agent.generate('hello')
|
|
678
|
+
* if (isErr(result)) {
|
|
679
|
+
* console.error(result.error.code, result.error.message)
|
|
680
|
+
* }
|
|
681
|
+
* ```
|
|
682
|
+
*/
|
|
683
|
+
declare function isErr<T>(result: Result<T>): result is {
|
|
684
|
+
ok: false;
|
|
685
|
+
error: ResultError;
|
|
686
|
+
};
|
|
687
|
+
//#endregion
|
|
688
|
+
//#region src/core/types.d.ts
|
|
689
|
+
/**
|
|
690
|
+
* A model reference.
|
|
691
|
+
*
|
|
692
|
+
* Accepts either:
|
|
693
|
+
* - A **string model ID** (e.g. `'openai/gpt-4.1'`) resolved via
|
|
694
|
+
* OpenRouter at runtime.
|
|
695
|
+
* - An **AI SDK `LanguageModel` instance** — including models wrapped
|
|
696
|
+
* with middleware via `wrapLanguageModel()`.
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* ```typescript
|
|
700
|
+
* // String ID — resolved via OpenRouter
|
|
701
|
+
* const agent1 = agent({
|
|
702
|
+
* name: 'my-agent',
|
|
703
|
+
* model: 'openai/gpt-4.1',
|
|
704
|
+
* system: 'You are helpful.',
|
|
705
|
+
* })
|
|
706
|
+
*
|
|
707
|
+
* // AI SDK provider instance
|
|
708
|
+
* import { openai } from '@ai-sdk/openai'
|
|
709
|
+
* const agent2 = agent({
|
|
710
|
+
* name: 'my-agent',
|
|
711
|
+
* model: openai('gpt-4.1'),
|
|
712
|
+
* system: 'You are helpful.',
|
|
713
|
+
* })
|
|
714
|
+
*
|
|
715
|
+
* // Middleware-wrapped model
|
|
716
|
+
* import { wrapLanguageModel, extractReasoningMiddleware } from 'ai'
|
|
717
|
+
* import { anthropic } from '@ai-sdk/anthropic'
|
|
718
|
+
* const agent3 = agent({
|
|
719
|
+
* name: 'reasoner',
|
|
720
|
+
* model: wrapLanguageModel({
|
|
721
|
+
* model: anthropic('claude-sonnet-4-5-20250929'),
|
|
722
|
+
* middleware: extractReasoningMiddleware({ tagName: 'think' }),
|
|
723
|
+
* }),
|
|
724
|
+
* system: 'Think step by step.',
|
|
725
|
+
* })
|
|
726
|
+
* ```
|
|
727
|
+
*/
|
|
728
|
+
type Model = string | LanguageModel$1;
|
|
729
|
+
/** @deprecated Use `Model` instead. */
|
|
730
|
+
type ModelRef = Model;
|
|
731
|
+
/**
|
|
732
|
+
* A value that can be generated against — the shared contract
|
|
733
|
+
* between Agent and Workflow.
|
|
734
|
+
*
|
|
735
|
+
* Both `Agent` and `Workflow` satisfy this interface. Any API that
|
|
736
|
+
* accepts a `Runnable` works with either.
|
|
737
|
+
*/
|
|
738
|
+
interface Runnable<TInput = unknown, TOutput = unknown> {
|
|
739
|
+
generate(input: TInput, config?: any): Promise<Result<{
|
|
740
|
+
output: TOutput;
|
|
741
|
+
}>>;
|
|
742
|
+
stream(input: TInput, config?: any): Promise<Result<{
|
|
743
|
+
output: Promise<TOutput>;
|
|
744
|
+
fullStream: AsyncIterableStream$1<StreamPart>;
|
|
745
|
+
}>>;
|
|
746
|
+
fn(): (input: TInput, config?: any) => Promise<Result<{
|
|
747
|
+
output: TOutput;
|
|
748
|
+
}>>;
|
|
749
|
+
}
|
|
750
|
+
//#endregion
|
|
751
|
+
//#region src/core/agents/base/types.d.ts
|
|
752
|
+
/**
|
|
753
|
+
* Concrete stream event type re-exported from the Vercel AI SDK.
|
|
754
|
+
*
|
|
755
|
+
* This is `TextStreamPart<ToolSet>` — the discriminated union of all
|
|
756
|
+
* possible stream events (`text-delta`, `tool-call`, `tool-result`,
|
|
757
|
+
* `finish`, `error`, etc.). Use `part.type` to discriminate.
|
|
758
|
+
*/
|
|
759
|
+
type StreamPart = TextStreamPart$1<ToolSet$1>;
|
|
760
|
+
type SubAgents = Record<string, Agent<any, any, any, any>>;
|
|
761
|
+
/**
|
|
762
|
+
* Chat message type.
|
|
763
|
+
*
|
|
764
|
+
* Re-exported from the Vercel AI SDK (`ModelMessage`). Used for
|
|
765
|
+
* multi-turn conversations, message arrays, and tool-call history.
|
|
766
|
+
*/
|
|
767
|
+
type Message = ModelMessage;
|
|
768
|
+
/**
|
|
769
|
+
* Result of a completed agent generation.
|
|
770
|
+
*
|
|
771
|
+
* Mirrors the AI SDK's `GenerateTextResult`. The `output` field is
|
|
772
|
+
* typed based on the agent's configured Output variant.
|
|
773
|
+
*
|
|
774
|
+
* @typeParam TOutput - The output type.
|
|
775
|
+
* - `string` for `Output.text()` (the default).
|
|
776
|
+
* - `T` for `Output.object({ schema })`.
|
|
777
|
+
* - `T[]` for `Output.array({ element })`.
|
|
778
|
+
* - `T` for `Output.choice({ options })`.
|
|
779
|
+
*/
|
|
780
|
+
interface GenerateResult<TOutput = string> {
|
|
781
|
+
/**
|
|
782
|
+
* The generation output.
|
|
783
|
+
*
|
|
784
|
+
* Type depends on the configured `Output` variant:
|
|
785
|
+
* - `string` when using `Output.text()` (default).
|
|
786
|
+
* - `T` when using `Output.object<T>({ schema })`.
|
|
787
|
+
* - `T[]` when using `Output.array<T>({ element })`.
|
|
788
|
+
* - One of the option strings when using `Output.choice()`.
|
|
789
|
+
*/
|
|
790
|
+
output: TOutput;
|
|
791
|
+
/**
|
|
792
|
+
* Full message history including tool calls.
|
|
793
|
+
*
|
|
794
|
+
* Contains the complete conversation from the generation,
|
|
795
|
+
* including system messages, user prompts, assistant responses,
|
|
796
|
+
* and tool call/result pairs.
|
|
797
|
+
*/
|
|
798
|
+
messages: Message[];
|
|
799
|
+
/**
|
|
800
|
+
* Aggregated token usage across all tool-loop steps.
|
|
801
|
+
*
|
|
802
|
+
* Includes input, output, cache, and reasoning token counts.
|
|
803
|
+
* All fields are resolved numbers (0 when the provider does not
|
|
804
|
+
* report a given field).
|
|
805
|
+
*/
|
|
806
|
+
usage: TokenUsage;
|
|
807
|
+
/**
|
|
808
|
+
* The reason the model stopped generating.
|
|
809
|
+
*
|
|
810
|
+
* Common values: `"stop"`, `"length"`, `"content-filter"`,
|
|
811
|
+
* `"tool-calls"`, `"error"`, `"other"`.
|
|
812
|
+
*/
|
|
813
|
+
finishReason: string;
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Result of a streaming agent generation.
|
|
817
|
+
*
|
|
818
|
+
* The `fullStream` emits typed `StreamPart` events as they arrive —
|
|
819
|
+
* text deltas, tool calls, tool results, step boundaries, finish,
|
|
820
|
+
* and errors. Implements both `AsyncIterable` and `ReadableStream`
|
|
821
|
+
* so consumers can use `for await...of` or `.getReader()`.
|
|
822
|
+
*
|
|
823
|
+
* `output` and `messages` are promises that resolve once the stream
|
|
824
|
+
* has been fully consumed.
|
|
825
|
+
*
|
|
826
|
+
* @typeParam TOutput - The output type (available after stream completes).
|
|
827
|
+
*/
|
|
828
|
+
interface StreamResult<TOutput = string> {
|
|
829
|
+
/**
|
|
830
|
+
* The generation output.
|
|
831
|
+
*
|
|
832
|
+
* Resolves after the stream completes. Same typing rules as
|
|
833
|
+
* `GenerateResult.output`.
|
|
834
|
+
*/
|
|
835
|
+
output: Promise<TOutput>;
|
|
836
|
+
/**
|
|
837
|
+
* Full message history.
|
|
838
|
+
*
|
|
839
|
+
* Resolves after the stream completes. Contains the complete
|
|
840
|
+
* conversation including tool calls.
|
|
841
|
+
*/
|
|
842
|
+
messages: Promise<Message[]>;
|
|
843
|
+
/**
|
|
844
|
+
* Aggregated token usage across all tool-loop steps.
|
|
845
|
+
*
|
|
846
|
+
* Resolves after the stream completes. Includes input, output,
|
|
847
|
+
* cache, and reasoning token counts.
|
|
848
|
+
*/
|
|
849
|
+
usage: Promise<TokenUsage>;
|
|
850
|
+
/**
|
|
851
|
+
* The reason the model stopped generating.
|
|
852
|
+
*
|
|
853
|
+
* Resolves after the stream completes. Common values: `"stop"`,
|
|
854
|
+
* `"length"`, `"content-filter"`, `"tool-calls"`, `"error"`, `"other"`.
|
|
855
|
+
*/
|
|
856
|
+
finishReason: Promise<string>;
|
|
857
|
+
/**
|
|
858
|
+
* The full stream of typed events.
|
|
859
|
+
*
|
|
860
|
+
* Emits `StreamPart` events (a discriminated union from the AI SDK)
|
|
861
|
+
* including `text-delta`, `tool-call`, `tool-result`, `finish`,
|
|
862
|
+
* `error`, and more. Use `part.type` to discriminate.
|
|
863
|
+
*
|
|
864
|
+
* Supports both `for await (const part of fullStream)` and
|
|
865
|
+
* `fullStream.getReader()`.
|
|
866
|
+
*/
|
|
867
|
+
fullStream: AsyncIterableStream$1<StreamPart>;
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Per-call overrides for agent generation.
|
|
871
|
+
*
|
|
872
|
+
* Passed as the optional second parameter to `.generate()` or `.stream()`.
|
|
873
|
+
* Override fields replace the base config for that call only. Per-call
|
|
874
|
+
* hooks **merge** with base hooks — base fires first, then call-level.
|
|
875
|
+
*
|
|
876
|
+
* @typeParam TTools - The agent's tool record type.
|
|
877
|
+
* @typeParam TSubAgents - The agent's subagent record type.
|
|
878
|
+
*/
|
|
879
|
+
interface AgentOverrides<TTools extends Record<string, Tool> = Record<string, Tool>, TSubAgents extends SubAgents = Record<string, never>> {
|
|
880
|
+
/**
|
|
881
|
+
* Override the logger for this call.
|
|
882
|
+
*
|
|
883
|
+
* When an agent runs inside a workflow step (`$.agent()`), the
|
|
884
|
+
* framework passes the step's scoped logger so agent logs include
|
|
885
|
+
* workflow and step context bindings.
|
|
886
|
+
*/
|
|
887
|
+
logger?: Logger;
|
|
888
|
+
/**
|
|
889
|
+
* Abort signal for cancellation.
|
|
890
|
+
*
|
|
891
|
+
* When fired, the agent should stop generation and clean up.
|
|
892
|
+
*/
|
|
893
|
+
signal?: AbortSignal;
|
|
894
|
+
/**
|
|
895
|
+
* Override the model for this call.
|
|
896
|
+
*
|
|
897
|
+
* Accepts a string model ID or an AI SDK `LanguageModel` instance.
|
|
898
|
+
*/
|
|
899
|
+
model?: Model;
|
|
900
|
+
/**
|
|
901
|
+
* Override the system prompt for this call.
|
|
902
|
+
*
|
|
903
|
+
* Can be a static string or a function that receives the input
|
|
904
|
+
* and returns the system prompt.
|
|
905
|
+
*/
|
|
906
|
+
system?: string | ((params: {
|
|
907
|
+
input: unknown;
|
|
908
|
+
}) => string);
|
|
909
|
+
/**
|
|
910
|
+
* Override or extend tools for this call.
|
|
911
|
+
*
|
|
912
|
+
* Merged with the agent's base tools. Use `Partial<TTools>` to
|
|
913
|
+
* replace specific tools, or add new ones via the index signature.
|
|
914
|
+
*/
|
|
915
|
+
tools?: Partial<TTools> & Record<string, Tool>;
|
|
916
|
+
/**
|
|
917
|
+
* Override or extend subagents for this call.
|
|
918
|
+
*
|
|
919
|
+
* Merged with the agent's base subagents.
|
|
920
|
+
*/
|
|
921
|
+
agents?: Partial<TSubAgents> & Record<string, Agent>;
|
|
922
|
+
/**
|
|
923
|
+
* Override max tool-loop steps for this call.
|
|
924
|
+
*
|
|
925
|
+
* Controls how many tool-loop iterations the agent will run
|
|
926
|
+
* before stopping.
|
|
927
|
+
*/
|
|
928
|
+
maxSteps?: number;
|
|
929
|
+
/**
|
|
930
|
+
* Override or set the output type for this call.
|
|
931
|
+
*
|
|
932
|
+
* Accepts an AI SDK `Output` strategy or a raw Zod schema:
|
|
933
|
+
* - `Output.text()`, `Output.object()`, `Output.array()`, `Output.choice()`
|
|
934
|
+
* - `z.object({ ... })` → auto-wrapped as `Output.object({ schema })`
|
|
935
|
+
* - `z.array(z.object({ ... }))` → auto-wrapped as `Output.array({ element })`
|
|
936
|
+
*/
|
|
937
|
+
output?: OutputParam;
|
|
938
|
+
/**
|
|
939
|
+
* Per-call hook — fires after base `onStart`.
|
|
940
|
+
*
|
|
941
|
+
* @param event - Event containing the input.
|
|
942
|
+
* @param event.input - The input passed to `.generate()` or `.stream()`.
|
|
943
|
+
*/
|
|
944
|
+
onStart?: (event: {
|
|
945
|
+
input: unknown;
|
|
946
|
+
}) => void | Promise<void>;
|
|
947
|
+
/**
|
|
948
|
+
* Per-call hook — fires after base `onFinish`.
|
|
949
|
+
*
|
|
950
|
+
* @param event - Event containing the input, result, and duration.
|
|
951
|
+
* @param event.input - The input passed to `.generate()` or `.stream()`.
|
|
952
|
+
* @param event.result - The generation result.
|
|
953
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
954
|
+
*/
|
|
955
|
+
onFinish?: (event: {
|
|
956
|
+
input: unknown;
|
|
957
|
+
result: GenerateResult;
|
|
958
|
+
duration: number;
|
|
959
|
+
}) => void | Promise<void>;
|
|
960
|
+
/**
|
|
961
|
+
* Per-call hook — fires after base `onError`.
|
|
962
|
+
*
|
|
963
|
+
* @param event - Event containing the input and error.
|
|
964
|
+
* @param event.input - The input passed to `.generate()` or `.stream()`.
|
|
965
|
+
* @param event.error - The error that occurred.
|
|
966
|
+
*/
|
|
967
|
+
onError?: (event: {
|
|
968
|
+
input: unknown;
|
|
969
|
+
error: Error;
|
|
970
|
+
}) => void | Promise<void>;
|
|
971
|
+
/**
|
|
972
|
+
* Per-call hook — fires after base `onStepFinish`.
|
|
973
|
+
*
|
|
974
|
+
* @param event - Event containing the step ID.
|
|
975
|
+
* @param event.stepId - The ID of the tool-loop step that completed.
|
|
976
|
+
*/
|
|
977
|
+
onStepFinish?: (event: {
|
|
978
|
+
stepId: string;
|
|
979
|
+
toolCalls: readonly {
|
|
980
|
+
toolName: string;
|
|
981
|
+
argsTextLength: number;
|
|
982
|
+
}[];
|
|
983
|
+
toolResults: readonly {
|
|
984
|
+
toolName: string;
|
|
985
|
+
resultTextLength: number;
|
|
986
|
+
}[];
|
|
987
|
+
usage: {
|
|
988
|
+
inputTokens: number;
|
|
989
|
+
outputTokens: number;
|
|
990
|
+
totalTokens: number;
|
|
991
|
+
};
|
|
992
|
+
}) => void | Promise<void>;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Configuration for creating an agent.
|
|
996
|
+
*
|
|
997
|
+
* Supports two modes:
|
|
998
|
+
*
|
|
999
|
+
* | Config | `.generate()` first param | How prompt is built |
|
|
1000
|
+
* |---|---|---|
|
|
1001
|
+
* | `input` + `prompt` provided | Typed `TInput` | `prompt({ input })` renders it |
|
|
1002
|
+
* | Both omitted | `string \| Message[]` | Passed directly to the model |
|
|
1003
|
+
*
|
|
1004
|
+
* @typeParam TInput - Agent input type (default: `string | Message[]`).
|
|
1005
|
+
* @typeParam TOutput - Agent output type (default: `string`).
|
|
1006
|
+
* @typeParam TTools - Record of tools available to this agent.
|
|
1007
|
+
* @typeParam TSubAgents - Record of subagents available to this agent.
|
|
1008
|
+
*/
|
|
1009
|
+
interface AgentConfig<TInput, TOutput, TTools extends Record<string, Tool>, TSubAgents extends SubAgents> {
|
|
1010
|
+
/**
|
|
1011
|
+
* Unique agent name.
|
|
1012
|
+
*
|
|
1013
|
+
* Used in logging, trace entries, and hook events.
|
|
1014
|
+
*/
|
|
1015
|
+
name: string;
|
|
1016
|
+
/**
|
|
1017
|
+
* Model to use for generation.
|
|
1018
|
+
*
|
|
1019
|
+
* Accepts a string model ID (resolved via OpenRouter) or an
|
|
1020
|
+
* AI SDK `LanguageModel` instance — including middleware-wrapped models.
|
|
1021
|
+
*
|
|
1022
|
+
* @see {@link Model}
|
|
1023
|
+
*/
|
|
1024
|
+
model: Model;
|
|
1025
|
+
/**
|
|
1026
|
+
* Zod schema for the agent's typed input.
|
|
1027
|
+
*
|
|
1028
|
+
* When provided alongside `prompt`, `.generate()` accepts `TInput`
|
|
1029
|
+
* as its first param and validates it against this schema.
|
|
1030
|
+
*
|
|
1031
|
+
* When omitted, `.generate()` accepts a raw `string` or `Message[]`
|
|
1032
|
+
* instead (simple mode).
|
|
1033
|
+
*/
|
|
1034
|
+
input?: ZodType<TInput>;
|
|
1035
|
+
/**
|
|
1036
|
+
* Map typed input to the prompt sent to the model.
|
|
1037
|
+
*
|
|
1038
|
+
* Required when `input` is provided. Ignored when `input` is
|
|
1039
|
+
* omitted (the raw string/messages are used directly in simple mode).
|
|
1040
|
+
*
|
|
1041
|
+
* @param params - Object containing the validated input.
|
|
1042
|
+
* @param params.input - The validated input value.
|
|
1043
|
+
* @returns The prompt string or message array to send to the model.
|
|
1044
|
+
*/
|
|
1045
|
+
prompt?: (params: {
|
|
1046
|
+
input: TInput;
|
|
1047
|
+
}) => string | Message[];
|
|
1048
|
+
/**
|
|
1049
|
+
* System prompt.
|
|
1050
|
+
*
|
|
1051
|
+
* Can be a static string or a function that receives the validated
|
|
1052
|
+
* input and returns the system prompt dynamically.
|
|
1053
|
+
*/
|
|
1054
|
+
system?: string | ((params: {
|
|
1055
|
+
input: TInput;
|
|
1056
|
+
}) => string);
|
|
1057
|
+
/**
|
|
1058
|
+
* Tools available to this agent for function calling.
|
|
1059
|
+
*
|
|
1060
|
+
* Each tool is exposed to the model in the tool-loop. The model
|
|
1061
|
+
* can call these tools to gather information or perform actions.
|
|
1062
|
+
*/
|
|
1063
|
+
tools?: TTools;
|
|
1064
|
+
/**
|
|
1065
|
+
* Subagents — automatically wrapped as tools the agent can delegate to.
|
|
1066
|
+
*
|
|
1067
|
+
* Each subagent becomes a callable tool that the parent agent can
|
|
1068
|
+
* invoke. Abort signals propagate automatically from parent to child.
|
|
1069
|
+
*/
|
|
1070
|
+
agents?: TSubAgents;
|
|
1071
|
+
/**
|
|
1072
|
+
* Maximum tool-loop iterations.
|
|
1073
|
+
*
|
|
1074
|
+
* Controls how many times the agent will call tools before stopping.
|
|
1075
|
+
* Set higher for complex multi-step tasks, lower for simple queries.
|
|
1076
|
+
*
|
|
1077
|
+
* @default 20
|
|
1078
|
+
*/
|
|
1079
|
+
maxSteps?: number;
|
|
1080
|
+
/**
|
|
1081
|
+
* Output type strategy.
|
|
1082
|
+
*
|
|
1083
|
+
* Controls the shape of the generation output. Accepts an AI SDK
|
|
1084
|
+
* `Output` strategy or a raw Zod schema:
|
|
1085
|
+
* - `Output.text()` — plain string (default).
|
|
1086
|
+
* - `Output.object({ schema })` — validated structured object.
|
|
1087
|
+
* - `Output.array({ element })` — validated array of elements.
|
|
1088
|
+
* - `Output.choice({ options })` — enum/classification.
|
|
1089
|
+
* - `z.object({ ... })` — auto-wrapped as `Output.object({ schema })`.
|
|
1090
|
+
* - `z.array(z.object({ ... }))` — auto-wrapped as `Output.array({ element })`.
|
|
1091
|
+
*
|
|
1092
|
+
* @default Output.text()
|
|
1093
|
+
*/
|
|
1094
|
+
output?: OutputParam;
|
|
1095
|
+
/**
|
|
1096
|
+
* Pino-compatible logger.
|
|
1097
|
+
*
|
|
1098
|
+
* When omitted, the SDK creates a default pino instance at `info`
|
|
1099
|
+
* level. The framework automatically creates scoped child loggers
|
|
1100
|
+
* with contextual bindings (`agentId`).
|
|
1101
|
+
*/
|
|
1102
|
+
logger?: Logger;
|
|
1103
|
+
/**
|
|
1104
|
+
* Hook: fires when the agent starts execution.
|
|
1105
|
+
*
|
|
1106
|
+
* @param event - Event containing the input.
|
|
1107
|
+
* @param event.input - The validated input value.
|
|
1108
|
+
*/
|
|
1109
|
+
onStart?: (event: {
|
|
1110
|
+
input: TInput;
|
|
1111
|
+
}) => void | Promise<void>;
|
|
1112
|
+
/**
|
|
1113
|
+
* Hook: fires when the agent finishes successfully.
|
|
1114
|
+
*
|
|
1115
|
+
* @param event - Event containing the input, result, and duration.
|
|
1116
|
+
* @param event.input - The validated input value.
|
|
1117
|
+
* @param event.result - The generation result.
|
|
1118
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1119
|
+
*/
|
|
1120
|
+
onFinish?: (event: {
|
|
1121
|
+
input: TInput;
|
|
1122
|
+
result: GenerateResult<TOutput>;
|
|
1123
|
+
duration: number;
|
|
1124
|
+
}) => void | Promise<void>;
|
|
1125
|
+
/**
|
|
1126
|
+
* Hook: fires when the agent encounters an error.
|
|
1127
|
+
*
|
|
1128
|
+
* @param event - Event containing the input and error.
|
|
1129
|
+
* @param event.input - The validated input value.
|
|
1130
|
+
* @param event.error - The error that occurred.
|
|
1131
|
+
*/
|
|
1132
|
+
onError?: (event: {
|
|
1133
|
+
input: TInput;
|
|
1134
|
+
error: Error;
|
|
1135
|
+
}) => void | Promise<void>;
|
|
1136
|
+
/**
|
|
1137
|
+
* Hook: fires after each tool-loop step completes.
|
|
1138
|
+
*
|
|
1139
|
+
* @param event - Event containing the step ID.
|
|
1140
|
+
* @param event.stepId - The ID of the completed tool-loop step.
|
|
1141
|
+
*/
|
|
1142
|
+
onStepFinish?: (event: {
|
|
1143
|
+
stepId: string;
|
|
1144
|
+
toolCalls: readonly {
|
|
1145
|
+
toolName: string;
|
|
1146
|
+
argsTextLength: number;
|
|
1147
|
+
}[];
|
|
1148
|
+
toolResults: readonly {
|
|
1149
|
+
toolName: string;
|
|
1150
|
+
resultTextLength: number;
|
|
1151
|
+
}[];
|
|
1152
|
+
usage: {
|
|
1153
|
+
inputTokens: number;
|
|
1154
|
+
outputTokens: number;
|
|
1155
|
+
totalTokens: number;
|
|
1156
|
+
};
|
|
1157
|
+
}) => void | Promise<void>;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* A created agent — exposes `.generate()`, `.stream()`, and `.fn()`.
|
|
1161
|
+
*
|
|
1162
|
+
* Under the hood, agents run a tool loop (like `generateText` with tools)
|
|
1163
|
+
* until a stop condition is met. Everything is wrapped in `Result`
|
|
1164
|
+
* so callers never need try/catch.
|
|
1165
|
+
*
|
|
1166
|
+
* @typeParam TInput - Agent input type.
|
|
1167
|
+
* @typeParam TOutput - Agent output type.
|
|
1168
|
+
* @typeParam TTools - Record of tools.
|
|
1169
|
+
* @typeParam TSubAgents - Record of subagents.
|
|
1170
|
+
*/
|
|
1171
|
+
interface Agent<TInput = string | Message[], TOutput = string, TTools extends Record<string, Tool> = Record<string, Tool>, TSubAgents extends SubAgents = Record<string, never>> {
|
|
1172
|
+
/**
|
|
1173
|
+
* Run the agent to completion.
|
|
1174
|
+
*
|
|
1175
|
+
* Executes the tool loop until the model produces a final response
|
|
1176
|
+
* or `maxSteps` is reached. Returns a `Result` wrapping the
|
|
1177
|
+
* generation result.
|
|
1178
|
+
*
|
|
1179
|
+
* @param input - Typed input (when `input` schema is configured)
|
|
1180
|
+
* or `string | Message[]` in simple mode.
|
|
1181
|
+
* @param config - Optional per-call overrides for model, tools,
|
|
1182
|
+
* output, hooks, etc.
|
|
1183
|
+
* @returns A `Result` wrapping the `GenerateResult`. On success,
|
|
1184
|
+
* `result.ok` is `true` and generation fields are flat on the object.
|
|
1185
|
+
*/
|
|
1186
|
+
generate(input: TInput, config?: AgentOverrides<TTools, TSubAgents>): Promise<Result<GenerateResult<TOutput>>>;
|
|
1187
|
+
/**
|
|
1188
|
+
* Run the agent with streaming output.
|
|
1189
|
+
*
|
|
1190
|
+
* Returns immediately with `fullStream` — an `AsyncIterableStream`
|
|
1191
|
+
* of typed `StreamPart` events. `output` and `messages` are
|
|
1192
|
+
* promises that resolve after the stream completes.
|
|
1193
|
+
*
|
|
1194
|
+
* @param input - Typed input (when `input` schema is configured)
|
|
1195
|
+
* or `string | Message[]` in simple mode.
|
|
1196
|
+
* @param config - Optional per-call overrides.
|
|
1197
|
+
* @returns A `Result` wrapping the `StreamResult`. On success,
|
|
1198
|
+
* consume `result.fullStream` for typed events; await
|
|
1199
|
+
* `result.output` / `result.messages` after the stream ends.
|
|
1200
|
+
*/
|
|
1201
|
+
stream(input: TInput, config?: AgentOverrides<TTools, TSubAgents>): Promise<Result<StreamResult<TOutput>>>;
|
|
1202
|
+
/**
|
|
1203
|
+
* Returns a plain function that calls `.generate()`.
|
|
1204
|
+
*
|
|
1205
|
+
* Use for clean single-function exports where you want to hide
|
|
1206
|
+
* the agent object and just expose a callable.
|
|
1207
|
+
*
|
|
1208
|
+
* @returns A function with the same signature as `.generate()`.
|
|
1209
|
+
*
|
|
1210
|
+
* @example
|
|
1211
|
+
* ```typescript
|
|
1212
|
+
* export const analyzeFile = fileAnalyzer.fn()
|
|
1213
|
+
* // Usage: const result = await analyzeFile({ filePath: '...' })
|
|
1214
|
+
* ```
|
|
1215
|
+
*/
|
|
1216
|
+
fn(): (input: TInput, config?: AgentOverrides<TTools, TSubAgents>) => Promise<Result<GenerateResult<TOutput>>>;
|
|
1217
|
+
}
|
|
1218
|
+
//#endregion
|
|
1219
|
+
//#region src/core/agents/base/agent.d.ts
|
|
1220
|
+
/**
|
|
1221
|
+
* Create an agent with typed input, tools, subagents, and hooks.
|
|
1222
|
+
*
|
|
1223
|
+
* Agents run a tool loop (via the AI SDK's `generateText`) until a
|
|
1224
|
+
* stop condition is met. They support:
|
|
1225
|
+
* - **Typed input** via Zod schema + prompt template.
|
|
1226
|
+
* - **Simple mode** — pass a string or messages directly.
|
|
1227
|
+
* - **Tools** for function calling.
|
|
1228
|
+
* - **Subagents** auto-wrapped as delegatable tools.
|
|
1229
|
+
* - **Inline overrides** per call.
|
|
1230
|
+
* - **Hooks** for observability.
|
|
1231
|
+
* - **Result return type** that never throws.
|
|
1232
|
+
*
|
|
1233
|
+
* @typeParam TInput - Agent input type (default: `string | Message[]`).
|
|
1234
|
+
* @typeParam TOutput - Agent output type (default: `string`).
|
|
1235
|
+
* @typeParam TTools - Record of tools.
|
|
1236
|
+
* @typeParam TSubAgents - Record of subagents.
|
|
1237
|
+
* @param config - Agent configuration including name, model, schemas,
|
|
1238
|
+
* tools, subagents, hooks, and logger.
|
|
1239
|
+
* @returns An `Agent` instance with `.generate()`, `.stream()`, and `.fn()`.
|
|
1240
|
+
*
|
|
1241
|
+
* @example
|
|
1242
|
+
* ```typescript
|
|
1243
|
+
* // Simple mode — pass a string directly
|
|
1244
|
+
* const helper = agent({
|
|
1245
|
+
* name: 'helper',
|
|
1246
|
+
* model: 'openai/gpt-4.1',
|
|
1247
|
+
* system: 'You are a helpful assistant.',
|
|
1248
|
+
* })
|
|
1249
|
+
* await helper.generate('What is TypeScript?')
|
|
1250
|
+
*
|
|
1251
|
+
* // Typed mode — input schema + prompt template
|
|
1252
|
+
* const summarizer = agent({
|
|
1253
|
+
* name: 'summarizer',
|
|
1254
|
+
* input: z.object({ text: z.string() }),
|
|
1255
|
+
* model: 'openai/gpt-4.1',
|
|
1256
|
+
* prompt: ({ input }) => `Summarize:\n\n${input.text}`,
|
|
1257
|
+
* })
|
|
1258
|
+
* await summarizer.generate({ text: '...' })
|
|
1259
|
+
*
|
|
1260
|
+
* // Export as a plain function
|
|
1261
|
+
* export const summarize = summarizer.fn()
|
|
1262
|
+
* ```
|
|
1263
|
+
*/
|
|
1264
|
+
declare function agent<TInput = string | Message[], TOutput = string, TTools extends Record<string, Tool> = {}, TSubAgents extends SubAgents = {}>(config: AgentConfig<TInput, TOutput, TTools, TSubAgents>): Agent<TInput, TOutput, TTools, TSubAgents>;
|
|
1265
|
+
//#endregion
|
|
1266
|
+
//#region src/lib/trace.d.ts
|
|
1267
|
+
/**
|
|
1268
|
+
* Known trace operation types.
|
|
1269
|
+
*
|
|
1270
|
+
* Each `$` method registers a specific operation type in the execution
|
|
1271
|
+
* trace. This discriminant allows consumers to filter or group trace
|
|
1272
|
+
* entries by kind.
|
|
1273
|
+
*/
|
|
1274
|
+
type OperationType = "step" | "agent" | "map" | "each" | "reduce" | "while" | "all" | "race";
|
|
1275
|
+
/** @deprecated Use `OperationType` instead. */
|
|
1276
|
+
type TraceType = OperationType;
|
|
1277
|
+
/**
|
|
1278
|
+
* A single entry in the execution trace.
|
|
1279
|
+
*
|
|
1280
|
+
* Every tracked `$` operation produces a TraceEntry. Nested operations
|
|
1281
|
+
* (e.g. agent calls inside a map iteration) appear as children,
|
|
1282
|
+
* forming a tree that represents the full execution graph.
|
|
1283
|
+
*
|
|
1284
|
+
* @internal
|
|
1285
|
+
* Part of the internal execution context. Exposed on
|
|
1286
|
+
* `WorkflowResult.trace` for observability but not directly
|
|
1287
|
+
* constructed by user code.
|
|
1288
|
+
*/
|
|
1289
|
+
interface TraceEntry {
|
|
1290
|
+
/**
|
|
1291
|
+
* Unique id of this operation.
|
|
1292
|
+
*
|
|
1293
|
+
* Corresponds to the `id` field from the `$` config that
|
|
1294
|
+
* produced this entry.
|
|
1295
|
+
*/
|
|
1296
|
+
id: string;
|
|
1297
|
+
/**
|
|
1298
|
+
* What kind of operation produced this entry.
|
|
1299
|
+
*
|
|
1300
|
+
* Discriminant for filtering or grouping trace entries.
|
|
1301
|
+
*/
|
|
1302
|
+
type: OperationType;
|
|
1303
|
+
/**
|
|
1304
|
+
* Input snapshot.
|
|
1305
|
+
*
|
|
1306
|
+
* Captured when the operation starts. May be `undefined` for
|
|
1307
|
+
* operations that have no meaningful input (e.g. `$.all`).
|
|
1308
|
+
*/
|
|
1309
|
+
input?: unknown;
|
|
1310
|
+
/**
|
|
1311
|
+
* Output snapshot.
|
|
1312
|
+
*
|
|
1313
|
+
* Captured when the operation completes successfully. `undefined`
|
|
1314
|
+
* if the operation is still running or failed.
|
|
1315
|
+
*/
|
|
1316
|
+
output?: unknown;
|
|
1317
|
+
/**
|
|
1318
|
+
* Start time in Unix milliseconds.
|
|
1319
|
+
*
|
|
1320
|
+
* Set when the operation begins execution.
|
|
1321
|
+
*/
|
|
1322
|
+
startedAt: number;
|
|
1323
|
+
/**
|
|
1324
|
+
* End time in Unix milliseconds.
|
|
1325
|
+
*
|
|
1326
|
+
* Set when the operation completes (success or failure).
|
|
1327
|
+
* `undefined` while the operation is still running.
|
|
1328
|
+
*/
|
|
1329
|
+
finishedAt?: number;
|
|
1330
|
+
/**
|
|
1331
|
+
* Error instance if the operation failed.
|
|
1332
|
+
*
|
|
1333
|
+
* `undefined` on success or while still running.
|
|
1334
|
+
*/
|
|
1335
|
+
error?: Error;
|
|
1336
|
+
/**
|
|
1337
|
+
* Token usage from this operation.
|
|
1338
|
+
*
|
|
1339
|
+
* Populated for `agent` type entries that complete successfully.
|
|
1340
|
+
* `undefined` for non-agent steps or failed operations.
|
|
1341
|
+
*/
|
|
1342
|
+
usage?: TokenUsage;
|
|
1343
|
+
/**
|
|
1344
|
+
* Nested trace entries for child operations.
|
|
1345
|
+
*
|
|
1346
|
+
* Present when this operation spawns sub-operations
|
|
1347
|
+
* (e.g. individual iterations inside `$.map`, or nested
|
|
1348
|
+
* `$.step` calls inside a step's `execute` callback).
|
|
1349
|
+
*/
|
|
1350
|
+
children?: readonly TraceEntry[];
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Recursively collect all {@link TokenUsage} values from a trace tree.
|
|
1354
|
+
*
|
|
1355
|
+
* Walks every entry (including nested children) and returns a flat
|
|
1356
|
+
* array of usage objects. Entries without usage are skipped.
|
|
1357
|
+
*
|
|
1358
|
+
* @param trace - The trace array to collect from.
|
|
1359
|
+
* @returns Flat array of {@link TokenUsage} values found in the tree.
|
|
1360
|
+
*/
|
|
1361
|
+
declare function collectUsages(trace: readonly TraceEntry[]): TokenUsage[];
|
|
1362
|
+
//#endregion
|
|
1363
|
+
//#region src/lib/context.d.ts
|
|
1364
|
+
/**
|
|
1365
|
+
* Public execution context for custom step factories.
|
|
1366
|
+
*
|
|
1367
|
+
* Provides the abort signal and scoped logger — the minimal surface
|
|
1368
|
+
* needed to integrate with framework cancellation and logging.
|
|
1369
|
+
* The mutable trace is internal-only.
|
|
1370
|
+
*/
|
|
1371
|
+
interface ExecutionContext {
|
|
1372
|
+
readonly signal: AbortSignal;
|
|
1373
|
+
readonly log: Logger;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Internal execution context.
|
|
1377
|
+
*
|
|
1378
|
+
* Created by the framework when a workflow or flow agent starts.
|
|
1379
|
+
* Threaded through every `$` call automatically. Users never create,
|
|
1380
|
+
* pass, or interact with this directly.
|
|
1381
|
+
*
|
|
1382
|
+
* @internal
|
|
1383
|
+
* Only accessible to framework internals. Custom step factories
|
|
1384
|
+
* receive {@link ExecutionContext} instead.
|
|
1385
|
+
*/
|
|
1386
|
+
interface Context extends ExecutionContext {
|
|
1387
|
+
/**
|
|
1388
|
+
* Execution trace — every tracked operation is recorded here.
|
|
1389
|
+
*
|
|
1390
|
+
* The framework appends entries as `$` operations start and complete.
|
|
1391
|
+
* Read this after workflow/flow agent completion to inspect the full
|
|
1392
|
+
* execution graph.
|
|
1393
|
+
*/
|
|
1394
|
+
readonly trace: TraceEntry[];
|
|
1395
|
+
/**
|
|
1396
|
+
* Synthetic messages produced by `$` steps.
|
|
1397
|
+
*
|
|
1398
|
+
* Each tracked operation pushes a tool-call (assistant) message when
|
|
1399
|
+
* it starts and a tool-result (tool) message when it finishes.
|
|
1400
|
+
* The array is flat — nested steps push to the same array so messages
|
|
1401
|
+
* appear in execution order.
|
|
1402
|
+
*
|
|
1403
|
+
* Used by `flowAgent` to populate `GenerateResult.messages`.
|
|
1404
|
+
*/
|
|
1405
|
+
readonly messages: Message[];
|
|
1406
|
+
}
|
|
1407
|
+
//#endregion
|
|
1408
|
+
//#region src/core/agents/flow/steps/agent.d.ts
|
|
1409
|
+
/**
|
|
1410
|
+
* Configuration for `$.agent()` — execute an agent call as a tracked operation.
|
|
1411
|
+
*
|
|
1412
|
+
* The `input` field matches whatever the agent accepts — typed `TInput`
|
|
1413
|
+
* if the agent has a schema, or `string | Message[]` for simple agents.
|
|
1414
|
+
*
|
|
1415
|
+
* @typeParam TInput - The agent's input type.
|
|
1416
|
+
*/
|
|
1417
|
+
interface AgentStepConfig<TInput> {
|
|
1418
|
+
/**
|
|
1419
|
+
* Unique step identifier.
|
|
1420
|
+
*
|
|
1421
|
+
* Appears in the execution trace, hook events, and error messages.
|
|
1422
|
+
*/
|
|
1423
|
+
id: string;
|
|
1424
|
+
/**
|
|
1425
|
+
* The agent to invoke.
|
|
1426
|
+
*
|
|
1427
|
+
* The framework calls `agent.generate()` internally with the
|
|
1428
|
+
* provided `input` and optional `config` overrides.
|
|
1429
|
+
*/
|
|
1430
|
+
agent: Runnable<TInput>;
|
|
1431
|
+
/**
|
|
1432
|
+
* Input to pass to the agent.
|
|
1433
|
+
*
|
|
1434
|
+
* Same as what you'd pass to `agent.generate()` — typed `TInput`
|
|
1435
|
+
* for agents with an input schema, or `string | Message[]` for
|
|
1436
|
+
* simple agents.
|
|
1437
|
+
*/
|
|
1438
|
+
input: TInput;
|
|
1439
|
+
/**
|
|
1440
|
+
* Optional inline overrides for this agent call.
|
|
1441
|
+
*
|
|
1442
|
+
* Accepts the same fields as `AgentOverrides` — model, output,
|
|
1443
|
+
* tools, hooks, etc.
|
|
1444
|
+
*/
|
|
1445
|
+
config?: AgentOverrides;
|
|
1446
|
+
/**
|
|
1447
|
+
* When `true`, call `agent.stream()` instead of `agent.generate()`
|
|
1448
|
+
* and pipe the agent's text output through the parent flow's stream.
|
|
1449
|
+
*
|
|
1450
|
+
* Only has an effect when the flow agent is streaming (i.e., when
|
|
1451
|
+
* a stream writer is available). Falls back to `agent.generate()`
|
|
1452
|
+
* when the flow agent is not streaming.
|
|
1453
|
+
*
|
|
1454
|
+
* @default false
|
|
1455
|
+
*/
|
|
1456
|
+
stream?: boolean;
|
|
1457
|
+
/**
|
|
1458
|
+
* Hook: fires when this agent step starts.
|
|
1459
|
+
*
|
|
1460
|
+
* @param event - Event containing the step id.
|
|
1461
|
+
* @param event.id - The step's unique identifier.
|
|
1462
|
+
*/
|
|
1463
|
+
onStart?: (event: {
|
|
1464
|
+
id: string;
|
|
1465
|
+
}) => void | Promise<void>;
|
|
1466
|
+
/**
|
|
1467
|
+
* Hook: fires when this agent step finishes.
|
|
1468
|
+
*
|
|
1469
|
+
* @param event - Event containing the step id, result, and duration.
|
|
1470
|
+
* @param event.id - The step's unique identifier.
|
|
1471
|
+
* @param event.result - The agent's `GenerateResult`.
|
|
1472
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1473
|
+
*/
|
|
1474
|
+
onFinish?: (event: {
|
|
1475
|
+
id: string;
|
|
1476
|
+
result: GenerateResult;
|
|
1477
|
+
duration: number;
|
|
1478
|
+
}) => void | Promise<void>;
|
|
1479
|
+
/**
|
|
1480
|
+
* Hook: fires when this agent step encounters an error.
|
|
1481
|
+
*
|
|
1482
|
+
* @param event - Event containing the step id and error.
|
|
1483
|
+
* @param event.id - The step's unique identifier.
|
|
1484
|
+
* @param event.error - The error that occurred.
|
|
1485
|
+
*/
|
|
1486
|
+
onError?: (event: {
|
|
1487
|
+
id: string;
|
|
1488
|
+
error: Error;
|
|
1489
|
+
}) => void | Promise<void>;
|
|
1490
|
+
}
|
|
1491
|
+
//#endregion
|
|
1492
|
+
//#region src/core/agents/flow/steps/all.d.ts
|
|
1493
|
+
/**
|
|
1494
|
+
* A factory that receives an abort signal and returns a promise.
|
|
1495
|
+
*
|
|
1496
|
+
* Used by `$.all()` and `$.race()` so the framework controls when
|
|
1497
|
+
* work starts and can cancel entries via the signal.
|
|
1498
|
+
*
|
|
1499
|
+
* The optional `$` parameter provides a child step builder whose
|
|
1500
|
+
* trace entries nest under the parent `all`/`race` step. Using it
|
|
1501
|
+
* is recommended for correct trace hierarchy.
|
|
1502
|
+
*/
|
|
1503
|
+
type EntryFactory = (signal: AbortSignal, $: StepBuilder) => Promise<unknown>;
|
|
1504
|
+
/**
|
|
1505
|
+
* Configuration for `$.all()` — concurrent heterogeneous operations.
|
|
1506
|
+
*
|
|
1507
|
+
* Like `Promise.all` — takes an array of factory functions that the
|
|
1508
|
+
* framework starts concurrently. Returns results as a tuple in the
|
|
1509
|
+
* same order. Fails fast on the first error.
|
|
1510
|
+
*/
|
|
1511
|
+
interface AllConfig {
|
|
1512
|
+
/**
|
|
1513
|
+
* Unique step identifier.
|
|
1514
|
+
*
|
|
1515
|
+
* Appears in the execution trace.
|
|
1516
|
+
*/
|
|
1517
|
+
id: string;
|
|
1518
|
+
/**
|
|
1519
|
+
* Array of factory functions to run concurrently.
|
|
1520
|
+
*
|
|
1521
|
+
* Each factory receives an `AbortSignal` and should return a
|
|
1522
|
+
* promise. The framework starts all factories at the same time
|
|
1523
|
+
* so timing and traces are accurate.
|
|
1524
|
+
*
|
|
1525
|
+
* @example
|
|
1526
|
+
* ```typescript
|
|
1527
|
+
* entries: [
|
|
1528
|
+
* (signal) => $.step({ id: 'a', execute: () => fetchA(signal) }),
|
|
1529
|
+
* (signal) => $.step({ id: 'b', execute: () => fetchB(signal) }),
|
|
1530
|
+
* ]
|
|
1531
|
+
* ```
|
|
1532
|
+
*/
|
|
1533
|
+
entries: EntryFactory[];
|
|
1534
|
+
/**
|
|
1535
|
+
* Hook: fires when the all operation starts.
|
|
1536
|
+
*
|
|
1537
|
+
* @param event - Event containing the step id.
|
|
1538
|
+
* @param event.id - The step's unique identifier.
|
|
1539
|
+
*/
|
|
1540
|
+
onStart?: (event: {
|
|
1541
|
+
id: string;
|
|
1542
|
+
}) => void | Promise<void>;
|
|
1543
|
+
/**
|
|
1544
|
+
* Hook: fires when all entries complete.
|
|
1545
|
+
*
|
|
1546
|
+
* @param event - Event containing the step id, results, and duration.
|
|
1547
|
+
* @param event.id - The step's unique identifier.
|
|
1548
|
+
* @param event.result - Array of results in entry order.
|
|
1549
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1550
|
+
*/
|
|
1551
|
+
onFinish?: (event: {
|
|
1552
|
+
id: string;
|
|
1553
|
+
result: unknown[];
|
|
1554
|
+
duration: number;
|
|
1555
|
+
}) => void | Promise<void>;
|
|
1556
|
+
/**
|
|
1557
|
+
* Hook: fires if any entry encounters an error.
|
|
1558
|
+
*
|
|
1559
|
+
* @param event - Event containing the step id and error.
|
|
1560
|
+
* @param event.id - The step's unique identifier.
|
|
1561
|
+
* @param event.error - The error that occurred.
|
|
1562
|
+
*/
|
|
1563
|
+
onError?: (event: {
|
|
1564
|
+
id: string;
|
|
1565
|
+
error: Error;
|
|
1566
|
+
}) => void | Promise<void>;
|
|
1567
|
+
}
|
|
1568
|
+
//#endregion
|
|
1569
|
+
//#region src/core/agents/flow/steps/each.d.ts
|
|
1570
|
+
/**
|
|
1571
|
+
* Configuration for `$.each()` — sequential side effects.
|
|
1572
|
+
*
|
|
1573
|
+
* Runs items one at a time in order. Returns `void`. If you need
|
|
1574
|
+
* accumulated results from sequential iteration, use `$.reduce()`.
|
|
1575
|
+
*
|
|
1576
|
+
* @typeParam T - Input item type.
|
|
1577
|
+
*/
|
|
1578
|
+
interface EachConfig<T> {
|
|
1579
|
+
/**
|
|
1580
|
+
* Unique step identifier.
|
|
1581
|
+
*
|
|
1582
|
+
* Appears in the execution trace.
|
|
1583
|
+
*/
|
|
1584
|
+
id: string;
|
|
1585
|
+
/**
|
|
1586
|
+
* Array of items to process sequentially.
|
|
1587
|
+
*
|
|
1588
|
+
* Each item is passed to the `execute` callback in order.
|
|
1589
|
+
*/
|
|
1590
|
+
input: readonly T[];
|
|
1591
|
+
/**
|
|
1592
|
+
* Process a single item (side effect).
|
|
1593
|
+
*
|
|
1594
|
+
* @param params - Execution parameters.
|
|
1595
|
+
* @param params.item - The current item from the input array.
|
|
1596
|
+
* @param params.index - The item's zero-based index in the input array.
|
|
1597
|
+
* @param params.$ - The step builder for nesting further operations.
|
|
1598
|
+
*/
|
|
1599
|
+
execute: (params: {
|
|
1600
|
+
item: T;
|
|
1601
|
+
index: number;
|
|
1602
|
+
$: StepBuilder;
|
|
1603
|
+
}) => Promise<void>;
|
|
1604
|
+
/**
|
|
1605
|
+
* Hook: fires when the each operation starts.
|
|
1606
|
+
*
|
|
1607
|
+
* @param event - Event containing the step id.
|
|
1608
|
+
* @param event.id - The step's unique identifier.
|
|
1609
|
+
*/
|
|
1610
|
+
onStart?: (event: {
|
|
1611
|
+
id: string;
|
|
1612
|
+
}) => void | Promise<void>;
|
|
1613
|
+
/**
|
|
1614
|
+
* Hook: fires when all items are processed.
|
|
1615
|
+
*
|
|
1616
|
+
* @param event - Event containing the step id and duration.
|
|
1617
|
+
* @param event.id - The step's unique identifier.
|
|
1618
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1619
|
+
*/
|
|
1620
|
+
onFinish?: (event: {
|
|
1621
|
+
id: string;
|
|
1622
|
+
duration: number;
|
|
1623
|
+
}) => void | Promise<void>;
|
|
1624
|
+
/**
|
|
1625
|
+
* Hook: fires if the each operation encounters an error.
|
|
1626
|
+
*
|
|
1627
|
+
* @param event - Event containing the step id and error.
|
|
1628
|
+
* @param event.id - The step's unique identifier.
|
|
1629
|
+
* @param event.error - The error that occurred.
|
|
1630
|
+
*/
|
|
1631
|
+
onError?: (event: {
|
|
1632
|
+
id: string;
|
|
1633
|
+
error: Error;
|
|
1634
|
+
}) => void | Promise<void>;
|
|
1635
|
+
}
|
|
1636
|
+
//#endregion
|
|
1637
|
+
//#region src/core/agents/flow/steps/map.d.ts
|
|
1638
|
+
/**
|
|
1639
|
+
* Configuration for `$.map()` — parallel map with optional concurrency limit.
|
|
1640
|
+
*
|
|
1641
|
+
* Each item is processed as a tracked operation. All run concurrently
|
|
1642
|
+
* (up to `concurrency` limit). Returns results in input order.
|
|
1643
|
+
*
|
|
1644
|
+
* @typeParam T - Input item type.
|
|
1645
|
+
* @typeParam R - Output item type.
|
|
1646
|
+
*/
|
|
1647
|
+
interface MapConfig<T, R> {
|
|
1648
|
+
/**
|
|
1649
|
+
* Unique step identifier.
|
|
1650
|
+
*
|
|
1651
|
+
* Appears in the execution trace. Individual iterations appear
|
|
1652
|
+
* as children of this entry.
|
|
1653
|
+
*/
|
|
1654
|
+
id: string;
|
|
1655
|
+
/**
|
|
1656
|
+
* Array of items to process.
|
|
1657
|
+
*
|
|
1658
|
+
* Each item is passed to the `execute` callback along with its index.
|
|
1659
|
+
*/
|
|
1660
|
+
input: readonly T[];
|
|
1661
|
+
/**
|
|
1662
|
+
* Maximum number of parallel executions.
|
|
1663
|
+
*
|
|
1664
|
+
* When set, limits how many `execute` callbacks run concurrently.
|
|
1665
|
+
* Results are still returned in input order regardless.
|
|
1666
|
+
*
|
|
1667
|
+
* @default Infinity
|
|
1668
|
+
*/
|
|
1669
|
+
concurrency?: number;
|
|
1670
|
+
/**
|
|
1671
|
+
* Process a single item.
|
|
1672
|
+
*
|
|
1673
|
+
* @param params - Execution parameters.
|
|
1674
|
+
* @param params.item - The current item from the input array.
|
|
1675
|
+
* @param params.index - The item's zero-based index in the input array.
|
|
1676
|
+
* @param params.$ - The step builder for nesting further operations.
|
|
1677
|
+
* @returns The processed result for this item.
|
|
1678
|
+
*/
|
|
1679
|
+
execute: (params: {
|
|
1680
|
+
item: T;
|
|
1681
|
+
index: number;
|
|
1682
|
+
$: StepBuilder;
|
|
1683
|
+
}) => Promise<R>;
|
|
1684
|
+
/**
|
|
1685
|
+
* Hook: fires when the map operation starts.
|
|
1686
|
+
*
|
|
1687
|
+
* @param event - Event containing the step id.
|
|
1688
|
+
* @param event.id - The step's unique identifier.
|
|
1689
|
+
*/
|
|
1690
|
+
onStart?: (event: {
|
|
1691
|
+
id: string;
|
|
1692
|
+
}) => void | Promise<void>;
|
|
1693
|
+
/**
|
|
1694
|
+
* Hook: fires when all items are processed.
|
|
1695
|
+
*
|
|
1696
|
+
* @param event - Event containing the step id, results, and duration.
|
|
1697
|
+
* @param event.id - The step's unique identifier.
|
|
1698
|
+
* @param event.result - Array of results in input order.
|
|
1699
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1700
|
+
*/
|
|
1701
|
+
onFinish?: (event: {
|
|
1702
|
+
id: string;
|
|
1703
|
+
result: R[];
|
|
1704
|
+
duration: number;
|
|
1705
|
+
}) => void | Promise<void>;
|
|
1706
|
+
/**
|
|
1707
|
+
* Hook: fires if the map operation encounters an error.
|
|
1708
|
+
*
|
|
1709
|
+
* @param event - Event containing the step id and error.
|
|
1710
|
+
* @param event.id - The step's unique identifier.
|
|
1711
|
+
* @param event.error - The error that occurred.
|
|
1712
|
+
*/
|
|
1713
|
+
onError?: (event: {
|
|
1714
|
+
id: string;
|
|
1715
|
+
error: Error;
|
|
1716
|
+
}) => void | Promise<void>;
|
|
1717
|
+
}
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/core/agents/flow/steps/race.d.ts
|
|
1720
|
+
/**
|
|
1721
|
+
* Configuration for `$.race()` — first-to-finish wins.
|
|
1722
|
+
*
|
|
1723
|
+
* Like `Promise.race` — takes an array of factory functions. Returns
|
|
1724
|
+
* the first resolved value. Losers are cancelled via abort signal.
|
|
1725
|
+
*/
|
|
1726
|
+
interface RaceConfig {
|
|
1727
|
+
/**
|
|
1728
|
+
* Unique step identifier.
|
|
1729
|
+
*
|
|
1730
|
+
* Appears in the execution trace.
|
|
1731
|
+
*/
|
|
1732
|
+
id: string;
|
|
1733
|
+
/**
|
|
1734
|
+
* Array of factory functions to race.
|
|
1735
|
+
*
|
|
1736
|
+
* Each factory receives an `AbortSignal`. The first to resolve
|
|
1737
|
+
* wins; losers are cancelled by aborting the signal.
|
|
1738
|
+
*
|
|
1739
|
+
* @example
|
|
1740
|
+
* ```typescript
|
|
1741
|
+
* entries: [
|
|
1742
|
+
* (signal) => $.step({ id: 'fast', execute: () => fetchFast(signal) }),
|
|
1743
|
+
* (signal) => $.step({ id: 'slow', execute: () => fetchSlow(signal) }),
|
|
1744
|
+
* ]
|
|
1745
|
+
* ```
|
|
1746
|
+
*/
|
|
1747
|
+
entries: EntryFactory[];
|
|
1748
|
+
/**
|
|
1749
|
+
* Hook: fires when the race starts.
|
|
1750
|
+
*
|
|
1751
|
+
* @param event - Event containing the step id.
|
|
1752
|
+
* @param event.id - The step's unique identifier.
|
|
1753
|
+
*/
|
|
1754
|
+
onStart?: (event: {
|
|
1755
|
+
id: string;
|
|
1756
|
+
}) => void | Promise<void>;
|
|
1757
|
+
/**
|
|
1758
|
+
* Hook: fires when the first entry completes.
|
|
1759
|
+
*
|
|
1760
|
+
* @param event - Event containing the step id, winner result, and duration.
|
|
1761
|
+
* @param event.id - The step's unique identifier.
|
|
1762
|
+
* @param event.result - The first resolved value.
|
|
1763
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1764
|
+
*/
|
|
1765
|
+
onFinish?: (event: {
|
|
1766
|
+
id: string;
|
|
1767
|
+
result: unknown;
|
|
1768
|
+
duration: number;
|
|
1769
|
+
}) => void | Promise<void>;
|
|
1770
|
+
/**
|
|
1771
|
+
* Hook: fires if the race encounters an error.
|
|
1772
|
+
*
|
|
1773
|
+
* @param event - Event containing the step id and error.
|
|
1774
|
+
* @param event.id - The step's unique identifier.
|
|
1775
|
+
* @param event.error - The error that occurred.
|
|
1776
|
+
*/
|
|
1777
|
+
onError?: (event: {
|
|
1778
|
+
id: string;
|
|
1779
|
+
error: Error;
|
|
1780
|
+
}) => void | Promise<void>;
|
|
1781
|
+
}
|
|
1782
|
+
//#endregion
|
|
1783
|
+
//#region src/core/agents/flow/steps/reduce.d.ts
|
|
1784
|
+
/**
|
|
1785
|
+
* Configuration for `$.reduce()` — sequential accumulation.
|
|
1786
|
+
*
|
|
1787
|
+
* Each step depends on the previous result. Returns the final
|
|
1788
|
+
* accumulated value.
|
|
1789
|
+
*
|
|
1790
|
+
* @typeParam T - Input item type.
|
|
1791
|
+
* @typeParam R - Accumulator/result type.
|
|
1792
|
+
*/
|
|
1793
|
+
interface ReduceConfig<T, R> {
|
|
1794
|
+
/**
|
|
1795
|
+
* Unique step identifier.
|
|
1796
|
+
*
|
|
1797
|
+
* Appears in the execution trace.
|
|
1798
|
+
*/
|
|
1799
|
+
id: string;
|
|
1800
|
+
/**
|
|
1801
|
+
* Array of items to reduce over.
|
|
1802
|
+
*
|
|
1803
|
+
* Each item is passed to the `execute` callback along with the
|
|
1804
|
+
* current accumulator value.
|
|
1805
|
+
*/
|
|
1806
|
+
input: readonly T[];
|
|
1807
|
+
/**
|
|
1808
|
+
* Initial accumulator value.
|
|
1809
|
+
*
|
|
1810
|
+
* Used as the `accumulator` parameter for the first `execute` call.
|
|
1811
|
+
*/
|
|
1812
|
+
initial: R;
|
|
1813
|
+
/**
|
|
1814
|
+
* Reduce function — processes one item and returns the new accumulator.
|
|
1815
|
+
*
|
|
1816
|
+
* @param params - Execution parameters.
|
|
1817
|
+
* @param params.item - The current item from the input array.
|
|
1818
|
+
* @param params.accumulator - The current accumulated value.
|
|
1819
|
+
* @param params.index - The item's zero-based index in the input array.
|
|
1820
|
+
* @param params.$ - The step builder for nesting further operations.
|
|
1821
|
+
* @returns The updated accumulator value.
|
|
1822
|
+
*/
|
|
1823
|
+
execute: (params: {
|
|
1824
|
+
item: T;
|
|
1825
|
+
accumulator: R;
|
|
1826
|
+
index: number;
|
|
1827
|
+
$: StepBuilder;
|
|
1828
|
+
}) => Promise<R>;
|
|
1829
|
+
/**
|
|
1830
|
+
* Hook: fires when the reduce operation starts.
|
|
1831
|
+
*
|
|
1832
|
+
* @param event - Event containing the step id.
|
|
1833
|
+
* @param event.id - The step's unique identifier.
|
|
1834
|
+
*/
|
|
1835
|
+
onStart?: (event: {
|
|
1836
|
+
id: string;
|
|
1837
|
+
}) => void | Promise<void>;
|
|
1838
|
+
/**
|
|
1839
|
+
* Hook: fires when all items are reduced.
|
|
1840
|
+
*
|
|
1841
|
+
* @param event - Event containing the step id, final result, and duration.
|
|
1842
|
+
* @param event.id - The step's unique identifier.
|
|
1843
|
+
* @param event.result - The final accumulated value.
|
|
1844
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1845
|
+
*/
|
|
1846
|
+
onFinish?: (event: {
|
|
1847
|
+
id: string;
|
|
1848
|
+
result: R;
|
|
1849
|
+
duration: number;
|
|
1850
|
+
}) => void | Promise<void>;
|
|
1851
|
+
/**
|
|
1852
|
+
* Hook: fires if the reduce operation encounters an error.
|
|
1853
|
+
*
|
|
1854
|
+
* @param event - Event containing the step id and error.
|
|
1855
|
+
* @param event.id - The step's unique identifier.
|
|
1856
|
+
* @param event.error - The error that occurred.
|
|
1857
|
+
*/
|
|
1858
|
+
onError?: (event: {
|
|
1859
|
+
id: string;
|
|
1860
|
+
error: Error;
|
|
1861
|
+
}) => void | Promise<void>;
|
|
1862
|
+
}
|
|
1863
|
+
//#endregion
|
|
1864
|
+
//#region src/core/agents/flow/steps/result.d.ts
|
|
1865
|
+
/**
|
|
1866
|
+
* Error information for a failed step.
|
|
1867
|
+
*
|
|
1868
|
+
* Extends {@link ResultError} with the step's `id` so error handlers
|
|
1869
|
+
* can correlate failures back to a specific `$` call.
|
|
1870
|
+
*/
|
|
1871
|
+
interface StepError extends ResultError {
|
|
1872
|
+
/**
|
|
1873
|
+
* The `id` from the step config that failed.
|
|
1874
|
+
*/
|
|
1875
|
+
stepId: string;
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Discriminated union for step operation results.
|
|
1879
|
+
*
|
|
1880
|
+
* The success value is available via `.value`. Callers pattern-match
|
|
1881
|
+
* on `ok` instead of using try/catch.
|
|
1882
|
+
*
|
|
1883
|
+
* @typeParam T - The success payload type.
|
|
1884
|
+
*/
|
|
1885
|
+
type StepResult<T> = {
|
|
1886
|
+
ok: true;
|
|
1887
|
+
value: T;
|
|
1888
|
+
step: StepInfo;
|
|
1889
|
+
duration: number;
|
|
1890
|
+
} | {
|
|
1891
|
+
ok: false;
|
|
1892
|
+
error: StepError;
|
|
1893
|
+
step: StepInfo;
|
|
1894
|
+
duration: number;
|
|
1895
|
+
};
|
|
1896
|
+
//#endregion
|
|
1897
|
+
//#region src/core/agents/flow/steps/step.d.ts
|
|
1898
|
+
/**
|
|
1899
|
+
* Configuration for `$.step()` — execute and register a unit of work.
|
|
1900
|
+
*
|
|
1901
|
+
* @typeParam T - The return type of the step's execute function.
|
|
1902
|
+
*/
|
|
1903
|
+
interface StepConfig<T> {
|
|
1904
|
+
/**
|
|
1905
|
+
* Unique step identifier.
|
|
1906
|
+
*
|
|
1907
|
+
* Appears in the execution trace, hook events, and error messages.
|
|
1908
|
+
*/
|
|
1909
|
+
id: string;
|
|
1910
|
+
/**
|
|
1911
|
+
* Execute the step's logic.
|
|
1912
|
+
*
|
|
1913
|
+
* @param params - Execution parameters.
|
|
1914
|
+
* @param params.$ - The step builder for nesting further operations.
|
|
1915
|
+
* @returns The step result.
|
|
1916
|
+
*/
|
|
1917
|
+
execute: (params: {
|
|
1918
|
+
$: StepBuilder;
|
|
1919
|
+
}) => Promise<T>;
|
|
1920
|
+
/**
|
|
1921
|
+
* Hook: fires when this step starts.
|
|
1922
|
+
*
|
|
1923
|
+
* @param event - Event containing the step id.
|
|
1924
|
+
* @param event.id - The step's unique identifier.
|
|
1925
|
+
*/
|
|
1926
|
+
onStart?: (event: {
|
|
1927
|
+
id: string;
|
|
1928
|
+
}) => void | Promise<void>;
|
|
1929
|
+
/**
|
|
1930
|
+
* Hook: fires when this step finishes successfully.
|
|
1931
|
+
*
|
|
1932
|
+
* @param event - Event containing the step id, result, and duration.
|
|
1933
|
+
* @param event.id - The step's unique identifier.
|
|
1934
|
+
* @param event.result - The value returned by `execute`.
|
|
1935
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
1936
|
+
*/
|
|
1937
|
+
onFinish?: (event: {
|
|
1938
|
+
id: string;
|
|
1939
|
+
result: T;
|
|
1940
|
+
duration: number;
|
|
1941
|
+
}) => void | Promise<void>;
|
|
1942
|
+
/**
|
|
1943
|
+
* Hook: fires when this step encounters an error.
|
|
1944
|
+
*
|
|
1945
|
+
* @param event - Event containing the step id and error.
|
|
1946
|
+
* @param event.id - The step's unique identifier.
|
|
1947
|
+
* @param event.error - The error that occurred.
|
|
1948
|
+
*/
|
|
1949
|
+
onError?: (event: {
|
|
1950
|
+
id: string;
|
|
1951
|
+
error: Error;
|
|
1952
|
+
}) => void | Promise<void>;
|
|
1953
|
+
}
|
|
1954
|
+
//#endregion
|
|
1955
|
+
//#region src/core/agents/flow/steps/while.d.ts
|
|
1956
|
+
/**
|
|
1957
|
+
* Configuration for `$.while()` — conditional loop.
|
|
1958
|
+
*
|
|
1959
|
+
* Runs while a condition holds. Each iteration is tracked. Returns
|
|
1960
|
+
* the **last value** (`undefined` if the condition was false on
|
|
1961
|
+
* first check).
|
|
1962
|
+
*
|
|
1963
|
+
* @typeParam T - The value type produced by each iteration.
|
|
1964
|
+
*/
|
|
1965
|
+
interface WhileConfig<T> {
|
|
1966
|
+
/**
|
|
1967
|
+
* Unique step identifier.
|
|
1968
|
+
*
|
|
1969
|
+
* Appears in the execution trace. Individual iterations appear
|
|
1970
|
+
* as children of this entry.
|
|
1971
|
+
*/
|
|
1972
|
+
id: string;
|
|
1973
|
+
/**
|
|
1974
|
+
* Loop condition — evaluated before each iteration.
|
|
1975
|
+
*
|
|
1976
|
+
* Called with the last iteration's value (or `undefined` before
|
|
1977
|
+
* the first iteration) and the current iteration index.
|
|
1978
|
+
*
|
|
1979
|
+
* @param params - Condition parameters.
|
|
1980
|
+
* @param params.value - The last iteration's value, or `undefined`
|
|
1981
|
+
* before the first iteration.
|
|
1982
|
+
* @param params.index - The zero-based iteration index.
|
|
1983
|
+
* @returns `true` to continue looping, `false` to stop.
|
|
1984
|
+
*/
|
|
1985
|
+
condition: (params: {
|
|
1986
|
+
value: T | undefined;
|
|
1987
|
+
index: number;
|
|
1988
|
+
}) => boolean;
|
|
1989
|
+
/**
|
|
1990
|
+
* Execute one iteration.
|
|
1991
|
+
*
|
|
1992
|
+
* @param params - Execution parameters.
|
|
1993
|
+
* @param params.index - The zero-based iteration index.
|
|
1994
|
+
* @param params.$ - The step builder for nesting further operations.
|
|
1995
|
+
* @returns The value for this iteration.
|
|
1996
|
+
*/
|
|
1997
|
+
execute: (params: {
|
|
1998
|
+
index: number;
|
|
1999
|
+
$: StepBuilder;
|
|
2000
|
+
}) => Promise<T>;
|
|
2001
|
+
/**
|
|
2002
|
+
* Hook: fires when the while loop starts.
|
|
2003
|
+
*
|
|
2004
|
+
* @param event - Event containing the step id.
|
|
2005
|
+
* @param event.id - The step's unique identifier.
|
|
2006
|
+
*/
|
|
2007
|
+
onStart?: (event: {
|
|
2008
|
+
id: string;
|
|
2009
|
+
}) => void | Promise<void>;
|
|
2010
|
+
/**
|
|
2011
|
+
* Hook: fires when the while loop finishes.
|
|
2012
|
+
*
|
|
2013
|
+
* @param event - Event containing the step id, last value, and duration.
|
|
2014
|
+
* @param event.id - The step's unique identifier.
|
|
2015
|
+
* @param event.result - The last iteration's value, or `undefined`.
|
|
2016
|
+
* @param event.duration - Wall-clock time in milliseconds.
|
|
2017
|
+
*/
|
|
2018
|
+
onFinish?: (event: {
|
|
2019
|
+
id: string;
|
|
2020
|
+
result: T | undefined;
|
|
2021
|
+
duration: number;
|
|
2022
|
+
}) => void | Promise<void>;
|
|
2023
|
+
/**
|
|
2024
|
+
* Hook: fires if the while loop encounters an error.
|
|
2025
|
+
*
|
|
2026
|
+
* @param event - Event containing the step id and error.
|
|
2027
|
+
* @param event.id - The step's unique identifier.
|
|
2028
|
+
* @param event.error - The error that occurred.
|
|
2029
|
+
*/
|
|
2030
|
+
onError?: (event: {
|
|
2031
|
+
id: string;
|
|
2032
|
+
error: Error;
|
|
2033
|
+
}) => void | Promise<void>;
|
|
2034
|
+
}
|
|
2035
|
+
//#endregion
|
|
2036
|
+
//#region src/core/agents/flow/steps/builder.d.ts
|
|
2037
|
+
/**
|
|
2038
|
+
* The `$` object — composable step utilities.
|
|
2039
|
+
*
|
|
2040
|
+
* Provides tracked operations that register data flow for observability.
|
|
2041
|
+
* Every call through `$` becomes an entry in the execution trace.
|
|
2042
|
+
*
|
|
2043
|
+
* `$` is passed into every callback, enabling composition and nesting.
|
|
2044
|
+
* You can always skip `$` and use plain imperative code — it just
|
|
2045
|
+
* won't appear in the trace.
|
|
2046
|
+
*/
|
|
2047
|
+
interface StepBuilder {
|
|
2048
|
+
/**
|
|
2049
|
+
* Execute and register a single unit of work.
|
|
2050
|
+
*
|
|
2051
|
+
* @typeParam T - The return type of the step.
|
|
2052
|
+
* @param config - Step configuration with id, execute function,
|
|
2053
|
+
* and optional hooks.
|
|
2054
|
+
* @returns A `StepResult` with `.value` containing the step's
|
|
2055
|
+
* return value on success, or a `StepError` on failure.
|
|
2056
|
+
*/
|
|
2057
|
+
step<T>(config: StepConfig<T>): Promise<StepResult<T>>;
|
|
2058
|
+
/**
|
|
2059
|
+
* Execute an agent call as a tracked operation.
|
|
2060
|
+
*
|
|
2061
|
+
* The framework records the agent name, input, and output in the
|
|
2062
|
+
* trace. Calls `agent.generate()` internally and unwraps the result —
|
|
2063
|
+
* agent errors become `StepError`, agent success becomes
|
|
2064
|
+
* `StepResult<GenerateResult>`.
|
|
2065
|
+
*
|
|
2066
|
+
* @typeParam TInput - The agent's input type.
|
|
2067
|
+
* @param config - Agent step configuration with id, agent, input,
|
|
2068
|
+
* optional overrides, and optional hooks.
|
|
2069
|
+
* @returns A `StepResult` wrapping the agent's `GenerateResult`.
|
|
2070
|
+
*/
|
|
2071
|
+
agent<TInput>(config: AgentStepConfig<TInput>): Promise<StepResult<GenerateResult>>;
|
|
2072
|
+
/**
|
|
2073
|
+
* Parallel map — each item is a tracked operation.
|
|
2074
|
+
*
|
|
2075
|
+
* All items run concurrently (up to `concurrency` limit).
|
|
2076
|
+
* Returns results in input order.
|
|
2077
|
+
*
|
|
2078
|
+
* @typeParam T - Input item type.
|
|
2079
|
+
* @typeParam R - Output item type.
|
|
2080
|
+
* @param config - Map configuration with id, input array, execute
|
|
2081
|
+
* function, optional concurrency, and optional hooks.
|
|
2082
|
+
* @returns A `StepResult` wrapping the array of results in input order.
|
|
2083
|
+
*/
|
|
2084
|
+
map<T, R>(config: MapConfig<T, R>): Promise<StepResult<R[]>>;
|
|
2085
|
+
/**
|
|
2086
|
+
* Sequential side effects — runs one item at a time.
|
|
2087
|
+
*
|
|
2088
|
+
* Returns `void`. Use `$.reduce()` if you need accumulated results.
|
|
2089
|
+
*
|
|
2090
|
+
* @typeParam T - Input item type.
|
|
2091
|
+
* @param config - Each configuration with id, input array, execute
|
|
2092
|
+
* function, and optional hooks.
|
|
2093
|
+
* @returns A `StepResult` wrapping void when all items are processed.
|
|
2094
|
+
*/
|
|
2095
|
+
each<T>(config: EachConfig<T>): Promise<StepResult<void>>;
|
|
2096
|
+
/**
|
|
2097
|
+
* Sequential accumulation — each step depends on the previous result.
|
|
2098
|
+
*
|
|
2099
|
+
* @typeParam T - Input item type.
|
|
2100
|
+
* @typeParam R - Accumulator/result type.
|
|
2101
|
+
* @param config - Reduce configuration with id, input array, initial
|
|
2102
|
+
* value, execute function, and optional hooks.
|
|
2103
|
+
* @returns A `StepResult` wrapping the final accumulated value.
|
|
2104
|
+
*/
|
|
2105
|
+
reduce<T, R>(config: ReduceConfig<T, R>): Promise<StepResult<R>>;
|
|
2106
|
+
/**
|
|
2107
|
+
* Conditional loop — runs while a condition holds.
|
|
2108
|
+
*
|
|
2109
|
+
* Returns the last value, or `undefined` if the condition was
|
|
2110
|
+
* false on the first check.
|
|
2111
|
+
*
|
|
2112
|
+
* @typeParam T - The value type produced by each iteration.
|
|
2113
|
+
* @param config - While configuration with id, condition, execute
|
|
2114
|
+
* function, and optional hooks.
|
|
2115
|
+
* @returns A `StepResult` wrapping the last iteration's value, or `undefined`.
|
|
2116
|
+
*/
|
|
2117
|
+
while<T>(config: WhileConfig<T>): Promise<StepResult<T | undefined>>;
|
|
2118
|
+
/**
|
|
2119
|
+
* Run heterogeneous operations concurrently — like `Promise.all`.
|
|
2120
|
+
*
|
|
2121
|
+
* Entries are factory functions that receive an `AbortSignal` and
|
|
2122
|
+
* return a promise. The framework starts all factories at the same
|
|
2123
|
+
* time so timing and traces are accurate.
|
|
2124
|
+
*
|
|
2125
|
+
* @param config - All configuration with id, entry factories,
|
|
2126
|
+
* and optional hooks.
|
|
2127
|
+
* @returns A `StepResult` wrapping the array of results in entry order.
|
|
2128
|
+
*/
|
|
2129
|
+
all(config: AllConfig): Promise<StepResult<unknown[]>>;
|
|
2130
|
+
/**
|
|
2131
|
+
* Run operations concurrently — first to finish wins.
|
|
2132
|
+
*
|
|
2133
|
+
* Entries are factory functions that receive an `AbortSignal`.
|
|
2134
|
+
* The first to resolve wins; losers are cancelled by aborting
|
|
2135
|
+
* the signal.
|
|
2136
|
+
*
|
|
2137
|
+
* @param config - Race configuration with id, entry factories,
|
|
2138
|
+
* and optional hooks.
|
|
2139
|
+
* @returns A `StepResult` wrapping the first resolved value.
|
|
2140
|
+
*/
|
|
2141
|
+
race(config: RaceConfig): Promise<StepResult<unknown>>;
|
|
2142
|
+
}
|
|
2143
|
+
//#endregion
|
|
2144
|
+
//#region src/core/agents/flow/types.d.ts
|
|
2145
|
+
/**
|
|
2146
|
+
* Information about a step in a flow agent execution.
|
|
2147
|
+
*
|
|
2148
|
+
* Passed to flow agent-level hooks (`onStepStart`, `onStepFinish`)
|
|
2149
|
+
* and included in step events.
|
|
2150
|
+
*/
|
|
2151
|
+
interface StepInfo {
|
|
2152
|
+
/**
|
|
2153
|
+
* The id from the `$` config.
|
|
2154
|
+
*
|
|
2155
|
+
* Matches the `id` field on the step config that produced this event.
|
|
2156
|
+
*/
|
|
2157
|
+
id: string;
|
|
2158
|
+
/**
|
|
2159
|
+
* Auto-incrementing index within the flow agent execution.
|
|
2160
|
+
*
|
|
2161
|
+
* Starts at `0` for the first `$` call and increments for each
|
|
2162
|
+
* subsequent tracked operation.
|
|
2163
|
+
*/
|
|
2164
|
+
index: number;
|
|
2165
|
+
/**
|
|
2166
|
+
* What kind of `$` call produced this step.
|
|
2167
|
+
*
|
|
2168
|
+
* Discriminant for filtering or grouping step events.
|
|
2169
|
+
*/
|
|
2170
|
+
type: OperationType;
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* Result of a completed flow agent generation.
|
|
2174
|
+
*
|
|
2175
|
+
* Extends `GenerateResult` with flow-specific fields (`trace`, `duration`).
|
|
2176
|
+
* Consumers who only care about the `Runnable` / `Agent` contract see
|
|
2177
|
+
* `{ output, messages, usage, finishReason }`. Consumers who know they
|
|
2178
|
+
* have a `FlowAgent` can access `trace` and `duration`.
|
|
2179
|
+
*
|
|
2180
|
+
* @typeParam TOutput - The validated output type.
|
|
2181
|
+
*/
|
|
2182
|
+
interface FlowAgentGenerateResult<TOutput> extends GenerateResult<TOutput> {
|
|
2183
|
+
/**
|
|
2184
|
+
* The full execution trace.
|
|
2185
|
+
*
|
|
2186
|
+
* A frozen tree of `TraceEntry` nodes representing every tracked `$`
|
|
2187
|
+
* operation that ran during the flow.
|
|
2188
|
+
*/
|
|
2189
|
+
trace: readonly TraceEntry[];
|
|
2190
|
+
/**
|
|
2191
|
+
* Total wall-clock time in milliseconds.
|
|
2192
|
+
*
|
|
2193
|
+
* Measured from the start of the flow to the completion
|
|
2194
|
+
* of all operations.
|
|
2195
|
+
*/
|
|
2196
|
+
duration: number;
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* Shared configuration fields for all flow agent variants.
|
|
2200
|
+
*
|
|
2201
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2202
|
+
*/
|
|
2203
|
+
interface FlowAgentConfigBase<TInput> {
|
|
2204
|
+
/**
|
|
2205
|
+
* Unique flow agent name.
|
|
2206
|
+
*
|
|
2207
|
+
* Used in logging, trace entries, and hook events.
|
|
2208
|
+
*/
|
|
2209
|
+
name: string;
|
|
2210
|
+
/**
|
|
2211
|
+
* Zod schema for validating flow agent input.
|
|
2212
|
+
*
|
|
2213
|
+
* The raw input passed to `.generate()` is validated against this
|
|
2214
|
+
* schema before the handler is called.
|
|
2215
|
+
*/
|
|
2216
|
+
input: ZodType<TInput>;
|
|
2217
|
+
/**
|
|
2218
|
+
* Pino-compatible logger.
|
|
2219
|
+
*
|
|
2220
|
+
* When omitted, the SDK creates a default console-based instance.
|
|
2221
|
+
* The framework automatically creates scoped child loggers
|
|
2222
|
+
* with contextual bindings (`flowAgentId`, `stepId`).
|
|
2223
|
+
*/
|
|
2224
|
+
logger?: Logger;
|
|
2225
|
+
/**
|
|
2226
|
+
* Hook: fires when the flow agent starts execution.
|
|
2227
|
+
*
|
|
2228
|
+
* @param event - Event containing the validated input.
|
|
2229
|
+
*/
|
|
2230
|
+
onStart?: (event: {
|
|
2231
|
+
input: TInput;
|
|
2232
|
+
}) => void | Promise<void>;
|
|
2233
|
+
/**
|
|
2234
|
+
* Hook: fires when the flow agent encounters an error.
|
|
2235
|
+
*
|
|
2236
|
+
* @param event - Event containing the input and error.
|
|
2237
|
+
*/
|
|
2238
|
+
onError?: (event: {
|
|
2239
|
+
input: TInput;
|
|
2240
|
+
error: Error;
|
|
2241
|
+
}) => void | Promise<void>;
|
|
2242
|
+
/**
|
|
2243
|
+
* Hook: fires when any tracked `$` step starts.
|
|
2244
|
+
*
|
|
2245
|
+
* @param event - Event containing step info.
|
|
2246
|
+
*/
|
|
2247
|
+
onStepStart?: (event: {
|
|
2248
|
+
step: StepInfo;
|
|
2249
|
+
}) => void | Promise<void>;
|
|
2250
|
+
/**
|
|
2251
|
+
* Hook: fires when any tracked `$` step finishes.
|
|
2252
|
+
*
|
|
2253
|
+
* @param event - Event containing step info, result, and duration.
|
|
2254
|
+
*/
|
|
2255
|
+
onStepFinish?: (event: {
|
|
2256
|
+
step: StepInfo;
|
|
2257
|
+
result: unknown;
|
|
2258
|
+
duration: number;
|
|
2259
|
+
}) => void | Promise<void>;
|
|
2260
|
+
}
|
|
2261
|
+
/**
|
|
2262
|
+
* Flow agent config with a structured output schema.
|
|
2263
|
+
*
|
|
2264
|
+
* The handler must return a value matching `TOutput`, which is
|
|
2265
|
+
* validated against the `output` Zod schema before being returned.
|
|
2266
|
+
*
|
|
2267
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2268
|
+
* @typeParam TOutput - Output type, inferred from the `output` Zod schema.
|
|
2269
|
+
*/
|
|
2270
|
+
interface FlowAgentConfigWithOutput<TInput, TOutput> extends FlowAgentConfigBase<TInput> {
|
|
2271
|
+
/**
|
|
2272
|
+
* Zod schema for validating flow agent output.
|
|
2273
|
+
*
|
|
2274
|
+
* The handler's return value is validated against this schema
|
|
2275
|
+
* before being returned to the caller.
|
|
2276
|
+
*/
|
|
2277
|
+
output: ZodType<TOutput>;
|
|
2278
|
+
/**
|
|
2279
|
+
* Hook: fires when the flow agent finishes successfully.
|
|
2280
|
+
*
|
|
2281
|
+
* @param event - Event containing input, result, and duration.
|
|
2282
|
+
*/
|
|
2283
|
+
onFinish?: (event: {
|
|
2284
|
+
input: TInput;
|
|
2285
|
+
result: FlowAgentGenerateResult<TOutput>;
|
|
2286
|
+
duration: number;
|
|
2287
|
+
}) => void | Promise<void>;
|
|
2288
|
+
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Flow agent config without an output schema.
|
|
2291
|
+
*
|
|
2292
|
+
* The handler returns `void` — it orchestrates sub-agents and steps
|
|
2293
|
+
* without producing structured output. The collected text from
|
|
2294
|
+
* sub-agent responses becomes the `string` output.
|
|
2295
|
+
*
|
|
2296
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2297
|
+
*/
|
|
2298
|
+
interface FlowAgentConfigWithoutOutput<TInput> extends FlowAgentConfigBase<TInput> {
|
|
2299
|
+
/**
|
|
2300
|
+
* No output schema — the flow agent collects text from sub-agent
|
|
2301
|
+
* responses and returns it as a `string`.
|
|
2302
|
+
*/
|
|
2303
|
+
output?: undefined;
|
|
2304
|
+
/**
|
|
2305
|
+
* Hook: fires when the flow agent finishes successfully.
|
|
2306
|
+
*
|
|
2307
|
+
* @param event - Event containing input, result (with string output), and duration.
|
|
2308
|
+
*/
|
|
2309
|
+
onFinish?: (event: {
|
|
2310
|
+
input: TInput;
|
|
2311
|
+
result: FlowAgentGenerateResult<string>;
|
|
2312
|
+
duration: number;
|
|
2313
|
+
}) => void | Promise<void>;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Configuration for creating a flow agent.
|
|
2317
|
+
*
|
|
2318
|
+
* Two variants:
|
|
2319
|
+
* - **With output**: Provide an `output` Zod schema. The handler returns
|
|
2320
|
+
* `TOutput`, which is validated against the schema.
|
|
2321
|
+
* - **Without output**: Omit `output`. The handler returns `void` and
|
|
2322
|
+
* the collected text from sub-agent responses becomes the `string` output.
|
|
2323
|
+
*
|
|
2324
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2325
|
+
* @typeParam TOutput - Output type, inferred from the `output` Zod schema.
|
|
2326
|
+
*/
|
|
2327
|
+
type FlowAgentConfig<TInput, TOutput = void> = FlowAgentConfigWithOutput<TInput, TOutput> | FlowAgentConfigWithoutOutput<TInput>;
|
|
2328
|
+
/**
|
|
2329
|
+
* Per-call overrides for flow agent generation.
|
|
2330
|
+
*
|
|
2331
|
+
* Passed as the optional second parameter to `.generate()` or `.stream()`.
|
|
2332
|
+
*/
|
|
2333
|
+
interface FlowAgentOverrides {
|
|
2334
|
+
/**
|
|
2335
|
+
* Abort signal for cancellation.
|
|
2336
|
+
*
|
|
2337
|
+
* When fired, all in-flight operations should clean up and exit.
|
|
2338
|
+
* Propagated through the entire execution tree.
|
|
2339
|
+
*/
|
|
2340
|
+
signal?: AbortSignal;
|
|
2341
|
+
/**
|
|
2342
|
+
* Override the logger for this call.
|
|
2343
|
+
*
|
|
2344
|
+
* When provided, replaces the logger configured at creation time.
|
|
2345
|
+
*/
|
|
2346
|
+
logger?: Logger;
|
|
2347
|
+
/**
|
|
2348
|
+
* Per-call hook — fires after base `onStart`.
|
|
2349
|
+
*/
|
|
2350
|
+
onStart?: (event: {
|
|
2351
|
+
input: unknown;
|
|
2352
|
+
}) => void | Promise<void>;
|
|
2353
|
+
/**
|
|
2354
|
+
* Per-call hook — fires after base `onFinish`.
|
|
2355
|
+
*/
|
|
2356
|
+
onFinish?: (event: {
|
|
2357
|
+
input: unknown;
|
|
2358
|
+
result: GenerateResult;
|
|
2359
|
+
duration: number;
|
|
2360
|
+
}) => void | Promise<void>;
|
|
2361
|
+
/**
|
|
2362
|
+
* Per-call hook — fires after base `onError`.
|
|
2363
|
+
*/
|
|
2364
|
+
onError?: (event: {
|
|
2365
|
+
input: unknown;
|
|
2366
|
+
error: Error;
|
|
2367
|
+
}) => void | Promise<void>;
|
|
2368
|
+
/**
|
|
2369
|
+
* Per-call hook — fires after base `onStepFinish`.
|
|
2370
|
+
*/
|
|
2371
|
+
onStepFinish?: (event: {
|
|
2372
|
+
step: StepInfo;
|
|
2373
|
+
result: unknown;
|
|
2374
|
+
duration: number;
|
|
2375
|
+
}) => void | Promise<void>;
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* Parameters passed to the flow agent handler function.
|
|
2379
|
+
*
|
|
2380
|
+
* @typeParam TInput - The validated input type.
|
|
2381
|
+
*/
|
|
2382
|
+
interface FlowAgentParams<TInput> {
|
|
2383
|
+
/**
|
|
2384
|
+
* Validated input.
|
|
2385
|
+
*/
|
|
2386
|
+
input: TInput;
|
|
2387
|
+
/**
|
|
2388
|
+
* Composable step builder utilities.
|
|
2389
|
+
*
|
|
2390
|
+
* Provides tracked operations (`$.step`, `$.agent`, `$.map`, etc.)
|
|
2391
|
+
* that register data flow for observability and produce synthetic
|
|
2392
|
+
* tool-call messages.
|
|
2393
|
+
*/
|
|
2394
|
+
$: StepBuilder;
|
|
2395
|
+
/**
|
|
2396
|
+
* Scoped logger for the current flow execution.
|
|
2397
|
+
*/
|
|
2398
|
+
log: Logger;
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* The flow agent handler function.
|
|
2402
|
+
*
|
|
2403
|
+
* This IS the flow — no step arrays, no definition objects.
|
|
2404
|
+
* State is just variables. `$` is passed in for tracked operations.
|
|
2405
|
+
*
|
|
2406
|
+
* @typeParam TInput - The validated input type.
|
|
2407
|
+
* @typeParam TOutput - The output type to return.
|
|
2408
|
+
*/
|
|
2409
|
+
type FlowAgentHandler<TInput, TOutput> = (params: FlowAgentParams<TInput>) => Promise<TOutput>;
|
|
2410
|
+
/**
|
|
2411
|
+
* A created flow agent — exposes `.generate()`, `.stream()`, and `.fn()`.
|
|
2412
|
+
*
|
|
2413
|
+
* Flow agents are imperative handlers that use `$` for tracked operations.
|
|
2414
|
+
* They satisfy the same `Runnable` interface as regular agents, so they
|
|
2415
|
+
* can be used as sub-agents, tool-wrapped delegatees, etc.
|
|
2416
|
+
*
|
|
2417
|
+
* @typeParam TInput - Validated input type.
|
|
2418
|
+
* @typeParam TOutput - Validated output type.
|
|
2419
|
+
*/
|
|
2420
|
+
interface FlowAgent<TInput, TOutput> {
|
|
2421
|
+
/**
|
|
2422
|
+
* Run the flow agent to completion.
|
|
2423
|
+
*
|
|
2424
|
+
* Validates input, executes the handler, validates output, and
|
|
2425
|
+
* returns the result with messages, trace, and timing.
|
|
2426
|
+
*
|
|
2427
|
+
* @param input - Raw input (validated against the `input` Zod schema).
|
|
2428
|
+
* @param config - Optional per-call overrides.
|
|
2429
|
+
* @returns A `Result` wrapping the `FlowAgentGenerateResult`.
|
|
2430
|
+
*/
|
|
2431
|
+
generate(input: TInput, config?: FlowAgentOverrides): Promise<Result<FlowAgentGenerateResult<TOutput>>>;
|
|
2432
|
+
/**
|
|
2433
|
+
* Run the flow agent with streaming step progress.
|
|
2434
|
+
*
|
|
2435
|
+
* Returns immediately with `fullStream` — an `AsyncIterableStream`
|
|
2436
|
+
* of typed `StreamPart` events for each step. `output`, `messages`,
|
|
2437
|
+
* and `usage` are promises that resolve after the flow completes.
|
|
2438
|
+
*
|
|
2439
|
+
* @param input - Raw input (validated against the `input` Zod schema).
|
|
2440
|
+
* @param config - Optional per-call overrides.
|
|
2441
|
+
* @returns A `Result` wrapping the `StreamResult`.
|
|
2442
|
+
*/
|
|
2443
|
+
stream(input: TInput, config?: FlowAgentOverrides): Promise<Result<StreamResult<TOutput>>>;
|
|
2444
|
+
/**
|
|
2445
|
+
* Returns a plain function that calls `.generate()`.
|
|
2446
|
+
*/
|
|
2447
|
+
fn(): (input: TInput, config?: FlowAgentOverrides) => Promise<Result<FlowAgentGenerateResult<TOutput>>>;
|
|
2448
|
+
}
|
|
2449
|
+
/**
|
|
2450
|
+
* @internal
|
|
2451
|
+
* Options that the engine uses to inject custom step augmentation
|
|
2452
|
+
* into flowAgent(). Not exported — only accessible within the package.
|
|
2453
|
+
*/
|
|
2454
|
+
interface InternalFlowAgentOptions {
|
|
2455
|
+
augment$?: ($: StepBuilder, ctx: Context) => StepBuilder;
|
|
2456
|
+
}
|
|
2457
|
+
//#endregion
|
|
2458
|
+
//#region src/core/agents/flow/flow-agent.d.ts
|
|
2459
|
+
/**
|
|
2460
|
+
* Create a flow agent with typed input/output, tracked steps, and hooks.
|
|
2461
|
+
*
|
|
2462
|
+
* A flow agent is an agent whose behavior is defined by code, not by an LLM.
|
|
2463
|
+
* You write the orchestration logic — calling sub-agents, running steps,
|
|
2464
|
+
* using concurrency primitives — and the framework wraps it in the same
|
|
2465
|
+
* API surface as a regular `agent`.
|
|
2466
|
+
*
|
|
2467
|
+
* To consumers, a `FlowAgent` IS an `Agent`. Same `.generate()`, same
|
|
2468
|
+
* `.stream()`, same `.fn()`. Same `GenerateResult` return type. Same
|
|
2469
|
+
* `messages` array. The only difference is internal: an `agent` runs
|
|
2470
|
+
* an LLM tool loop, a `flowAgent` runs your handler function.
|
|
2471
|
+
*
|
|
2472
|
+
* Each `$` step is modeled as a synthetic tool call in the message history.
|
|
2473
|
+
*
|
|
2474
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2475
|
+
* @typeParam TOutput - Output type, inferred from the `output` Zod schema.
|
|
2476
|
+
* @param config - Flow agent configuration including name, schemas,
|
|
2477
|
+
* hooks, and logger.
|
|
2478
|
+
* @param handler - The flow agent handler function that receives
|
|
2479
|
+
* validated input and the `$` step builder.
|
|
2480
|
+
* @param _internal - Internal options used by the engine. Not public API.
|
|
2481
|
+
* @returns A `FlowAgent` instance with `.generate()`, `.stream()`,
|
|
2482
|
+
* and `.fn()`.
|
|
2483
|
+
*
|
|
2484
|
+
* @example
|
|
2485
|
+
* ```typescript
|
|
2486
|
+
* const pipeline = flowAgent({
|
|
2487
|
+
* name: 'doc-pipeline',
|
|
2488
|
+
* input: z.object({ repo: z.string() }),
|
|
2489
|
+
* output: z.object({ docs: z.array(z.string()) }),
|
|
2490
|
+
* }, async ({ input, $ }) => {
|
|
2491
|
+
* const files = await $.step({
|
|
2492
|
+
* id: 'scan-repo',
|
|
2493
|
+
* execute: () => scanRepo(input.repo),
|
|
2494
|
+
* })
|
|
2495
|
+
*
|
|
2496
|
+
* if (!files.ok) throw files.error
|
|
2497
|
+
*
|
|
2498
|
+
* const docs = await $.map({
|
|
2499
|
+
* id: 'generate-docs',
|
|
2500
|
+
* input: files.value,
|
|
2501
|
+
* execute: async ({ item, $ }) => {
|
|
2502
|
+
* const result = await $.agent({
|
|
2503
|
+
* id: 'write-doc',
|
|
2504
|
+
* agent: writerAgent,
|
|
2505
|
+
* input: item,
|
|
2506
|
+
* })
|
|
2507
|
+
* return result.ok ? result.value.output : ''
|
|
2508
|
+
* },
|
|
2509
|
+
* concurrency: 3,
|
|
2510
|
+
* })
|
|
2511
|
+
*
|
|
2512
|
+
* return { docs: docs.ok ? docs.value : [] }
|
|
2513
|
+
* })
|
|
2514
|
+
* ```
|
|
2515
|
+
*/
|
|
2516
|
+
/**
|
|
2517
|
+
* Create a flow agent with structured output.
|
|
2518
|
+
*
|
|
2519
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2520
|
+
* @typeParam TOutput - Output type, inferred from the `output` Zod schema.
|
|
2521
|
+
*/
|
|
2522
|
+
declare function flowAgent<TInput, TOutput>(config: FlowAgentConfigWithOutput<TInput, TOutput>, handler: FlowAgentHandler<TInput, TOutput>, _internal?: InternalFlowAgentOptions): FlowAgent<TInput, TOutput>;
|
|
2523
|
+
/**
|
|
2524
|
+
* Create a flow agent without structured output.
|
|
2525
|
+
*
|
|
2526
|
+
* The handler returns `void` — sub-agent text is collected as the
|
|
2527
|
+
* `string` output. Ideal for orchestration-only flows where the
|
|
2528
|
+
* sub-agents produce the final text.
|
|
2529
|
+
*
|
|
2530
|
+
* @typeParam TInput - Input type, inferred from the `input` Zod schema.
|
|
2531
|
+
*/
|
|
2532
|
+
declare function flowAgent<TInput>(config: FlowAgentConfigWithoutOutput<TInput>, handler: FlowAgentHandler<TInput, void>, _internal?: InternalFlowAgentOptions): FlowAgent<TInput, string>;
|
|
2533
|
+
//#endregion
|
|
2534
|
+
//#region src/core/agents/flow/engine.d.ts
|
|
2535
|
+
/**
|
|
2536
|
+
* Factory function for a custom step type.
|
|
2537
|
+
*
|
|
2538
|
+
* Receives the internal context (for signal, logging) and the
|
|
2539
|
+
* user-provided config. Returns the step result.
|
|
2540
|
+
*
|
|
2541
|
+
* @typeParam TConfig - The config shape users pass to `$.myStep({ ... })`.
|
|
2542
|
+
* @typeParam TResult - The return type of the step.
|
|
2543
|
+
*/
|
|
2544
|
+
type CustomStepFactory<TConfig, TResult> = (params: {
|
|
2545
|
+
/**
|
|
2546
|
+
* Execution context.
|
|
2547
|
+
*/
|
|
2548
|
+
ctx: ExecutionContext;
|
|
2549
|
+
/**
|
|
2550
|
+
* The config object the user passed to the custom step.
|
|
2551
|
+
*/
|
|
2552
|
+
config: TConfig;
|
|
2553
|
+
}) => Promise<TResult>;
|
|
2554
|
+
/**
|
|
2555
|
+
* Map of custom step names to their factory functions.
|
|
2556
|
+
*
|
|
2557
|
+
* Uses `config: never` as the base constraint so that any concrete
|
|
2558
|
+
* `CustomStepFactory<TConfig, TResult>` is assignable via function
|
|
2559
|
+
* parameter contravariance — `never extends TConfig` is always true.
|
|
2560
|
+
*/
|
|
2561
|
+
type CustomStepDefinitions = Record<string, (params: {
|
|
2562
|
+
ctx: ExecutionContext;
|
|
2563
|
+
config: never;
|
|
2564
|
+
}) => Promise<unknown>>;
|
|
2565
|
+
/**
|
|
2566
|
+
* Derive typed custom step methods from a definitions map.
|
|
2567
|
+
*
|
|
2568
|
+
* @typeParam T - The `CustomStepDefinitions` map.
|
|
2569
|
+
*/
|
|
2570
|
+
type TypedCustomSteps<T extends CustomStepDefinitions> = { [K in keyof T]: T[K] extends CustomStepFactory<infer TConfig, infer TResult> ? (config: TConfig) => Promise<TResult> : never };
|
|
2571
|
+
/**
|
|
2572
|
+
* Configuration for creating a custom flow engine.
|
|
2573
|
+
*
|
|
2574
|
+
* @typeParam TCustomSteps - The custom step definitions map.
|
|
2575
|
+
*/
|
|
2576
|
+
interface FlowEngineConfig<TCustomSteps extends CustomStepDefinitions> {
|
|
2577
|
+
/**
|
|
2578
|
+
* Custom step types to add to `$`.
|
|
2579
|
+
*/
|
|
2580
|
+
$?: TCustomSteps;
|
|
2581
|
+
/**
|
|
2582
|
+
* Default hook: fires when any flow agent starts.
|
|
2583
|
+
*/
|
|
2584
|
+
onStart?: (event: {
|
|
2585
|
+
input: unknown;
|
|
2586
|
+
}) => void | Promise<void>;
|
|
2587
|
+
/**
|
|
2588
|
+
* Default hook: fires when any flow agent finishes.
|
|
2589
|
+
*/
|
|
2590
|
+
onFinish?: (event: {
|
|
2591
|
+
input: unknown;
|
|
2592
|
+
result: unknown;
|
|
2593
|
+
duration: number;
|
|
2594
|
+
}) => void | Promise<void>;
|
|
2595
|
+
/**
|
|
2596
|
+
* Default hook: fires when any flow agent errors.
|
|
2597
|
+
*/
|
|
2598
|
+
onError?: (event: {
|
|
2599
|
+
input: unknown;
|
|
2600
|
+
error: Error;
|
|
2601
|
+
}) => void | Promise<void>;
|
|
2602
|
+
/**
|
|
2603
|
+
* Default hook: fires when any step starts.
|
|
2604
|
+
*/
|
|
2605
|
+
onStepStart?: (event: {
|
|
2606
|
+
step: StepInfo;
|
|
2607
|
+
}) => void | Promise<void>;
|
|
2608
|
+
/**
|
|
2609
|
+
* Default hook: fires when any step finishes.
|
|
2610
|
+
*/
|
|
2611
|
+
onStepFinish?: (event: {
|
|
2612
|
+
step: StepInfo;
|
|
2613
|
+
result: unknown;
|
|
2614
|
+
duration: number;
|
|
2615
|
+
}) => void | Promise<void>;
|
|
2616
|
+
}
|
|
2617
|
+
/**
|
|
2618
|
+
* A `flowAgent` factory with custom steps merged into `$`.
|
|
2619
|
+
*
|
|
2620
|
+
* @typeParam TCustomSteps - The custom step definitions map.
|
|
2621
|
+
*/
|
|
2622
|
+
type FlowFactory<TCustomSteps extends CustomStepDefinitions> = <TInput, TOutput>(config: FlowAgentConfigWithOutput<TInput, TOutput>, handler: (params: {
|
|
2623
|
+
input: TInput;
|
|
2624
|
+
$: StepBuilder & TypedCustomSteps<TCustomSteps>;
|
|
2625
|
+
log: Logger;
|
|
2626
|
+
}) => Promise<TOutput>) => FlowAgent<TInput, TOutput>;
|
|
2627
|
+
/**
|
|
2628
|
+
* Create a custom flow engine with additional step types
|
|
2629
|
+
* and/or default hooks.
|
|
2630
|
+
*
|
|
2631
|
+
* Returns a `flowAgent()`-like factory. Any custom steps defined
|
|
2632
|
+
* in `$` are merged into the handler's `$` parameter and fully typed.
|
|
2633
|
+
*
|
|
2634
|
+
* @typeParam TCustomSteps - The custom step definitions map.
|
|
2635
|
+
* @param config - Engine configuration including custom steps
|
|
2636
|
+
* and default hooks.
|
|
2637
|
+
* @returns A `FlowFactory` that creates flow agents with custom
|
|
2638
|
+
* `$` steps and engine-level default hooks.
|
|
2639
|
+
*
|
|
2640
|
+
* @example
|
|
2641
|
+
* ```typescript
|
|
2642
|
+
* const engine = createFlowEngine({
|
|
2643
|
+
* $: {
|
|
2644
|
+
* retry: async ({ ctx, config }) => {
|
|
2645
|
+
* let lastError: Error | undefined
|
|
2646
|
+
* for (let attempt = 0; attempt < config.attempts; attempt++) {
|
|
2647
|
+
* try {
|
|
2648
|
+
* return await config.execute({ attempt })
|
|
2649
|
+
* } catch (err) {
|
|
2650
|
+
* lastError = err as Error
|
|
2651
|
+
* }
|
|
2652
|
+
* }
|
|
2653
|
+
* throw lastError
|
|
2654
|
+
* },
|
|
2655
|
+
* },
|
|
2656
|
+
* onStart: ({ input }) => telemetry.trackStart(input),
|
|
2657
|
+
* })
|
|
2658
|
+
*
|
|
2659
|
+
* const myFlow = engine({
|
|
2660
|
+
* name: 'my-flow',
|
|
2661
|
+
* input: MyInput,
|
|
2662
|
+
* output: MyOutput,
|
|
2663
|
+
* }, async ({ input, $ }) => {
|
|
2664
|
+
* const data = await $.retry({
|
|
2665
|
+
* attempts: 3,
|
|
2666
|
+
* execute: async () => fetch('https://api.example.com/data'),
|
|
2667
|
+
* })
|
|
2668
|
+
* return data
|
|
2669
|
+
* })
|
|
2670
|
+
* ```
|
|
2671
|
+
*/
|
|
2672
|
+
declare function createFlowEngine<TCustomSteps extends CustomStepDefinitions = Record<string, never>>(engineConfig: FlowEngineConfig<TCustomSteps>): FlowFactory<TCustomSteps>;
|
|
2673
|
+
//#endregion
|
|
2674
|
+
//#region src/core/provider/provider.d.ts
|
|
2675
|
+
/**
|
|
2676
|
+
* Create an OpenRouter provider instance with automatic API key resolution.
|
|
2677
|
+
*
|
|
2678
|
+
* Falls back to the `OPENROUTER_API_KEY` environment variable when
|
|
2679
|
+
* no explicit `apiKey` is provided in the options.
|
|
2680
|
+
*
|
|
2681
|
+
* @param options - Provider settings forwarded to `@openrouter/ai-sdk-provider`.
|
|
2682
|
+
* @returns A configured {@link OpenRouterProvider} instance.
|
|
2683
|
+
*
|
|
2684
|
+
* @example
|
|
2685
|
+
* ```typescript
|
|
2686
|
+
* const openrouter = createOpenRouter({ apiKey: 'sk-...' })
|
|
2687
|
+
* const m = openrouter('openai/gpt-5.2-codex')
|
|
2688
|
+
* ```
|
|
2689
|
+
*/
|
|
2690
|
+
declare function createOpenRouter(options?: OpenRouterProviderSettings): OpenRouterProvider;
|
|
2691
|
+
/**
|
|
2692
|
+
* Shorthand for creating a single OpenRouter language model.
|
|
2693
|
+
*
|
|
2694
|
+
* Resolves the API key from the environment and returns a ready-to-use
|
|
2695
|
+
* {@link LanguageModel} that can be passed directly to AI SDK functions.
|
|
2696
|
+
*
|
|
2697
|
+
* The provider instance is cached at module scope and reused across
|
|
2698
|
+
* calls. If `OPENROUTER_API_KEY` changes at runtime, the cache is
|
|
2699
|
+
* invalidated and a new provider is created.
|
|
2700
|
+
*
|
|
2701
|
+
* @param modelId - An OpenRouter model identifier (e.g. `"openai/gpt-5.2-codex"`).
|
|
2702
|
+
* @returns A configured {@link LanguageModel} instance.
|
|
2703
|
+
*
|
|
2704
|
+
* @example
|
|
2705
|
+
* ```typescript
|
|
2706
|
+
* const m = openrouter('openai/gpt-5.2-codex')
|
|
2707
|
+
* ```
|
|
2708
|
+
*/
|
|
2709
|
+
declare const openrouter: (modelId: ModelId) => LanguageModel;
|
|
2710
|
+
//#endregion
|
|
2711
|
+
//#region src/core/provider/usage.d.ts
|
|
2712
|
+
/**
|
|
2713
|
+
* Compute final usage for a single agent call.
|
|
2714
|
+
*
|
|
2715
|
+
* Aggregates token counts from one or more raw tracking records.
|
|
2716
|
+
* Returns a flat object with tokens + agentId.
|
|
2717
|
+
*
|
|
2718
|
+
* @param agentId - The agent that produced these records.
|
|
2719
|
+
* @param records - Raw tracking records from the agent's execution.
|
|
2720
|
+
* @returns Flat {@link AgentTokenUsage} with resolved token counts.
|
|
2721
|
+
*/
|
|
2722
|
+
declare function agentUsage(agentId: string, records: TokenUsageRecord | TokenUsageRecord[]): AgentTokenUsage;
|
|
2723
|
+
/**
|
|
2724
|
+
* Compute final usage for a flow agent with multiple agent calls.
|
|
2725
|
+
*
|
|
2726
|
+
* Groups raw tracking records by `source.agentId`, computes per-agent
|
|
2727
|
+
* usage via {@link agentUsage}.
|
|
2728
|
+
*
|
|
2729
|
+
* @param records - Raw tracking records from all agents in the flow.
|
|
2730
|
+
* @returns {@link FlowAgentTokenUsage} with per-agent breakdown.
|
|
2731
|
+
*/
|
|
2732
|
+
declare function flowAgentUsage(records: TokenUsageRecord[]): FlowAgentTokenUsage;
|
|
2733
|
+
/**
|
|
2734
|
+
* Sum multiple {@link TokenUsage} objects field-by-field.
|
|
2735
|
+
*
|
|
2736
|
+
* Pure function — returns a new object without mutating any input.
|
|
2737
|
+
* Returns zero-valued usage when given an empty array.
|
|
2738
|
+
*
|
|
2739
|
+
* @param usages - Array of usage objects to sum.
|
|
2740
|
+
* @returns A new `TokenUsage` with each field summed.
|
|
2741
|
+
*/
|
|
2742
|
+
declare function sumTokenUsage(usages: TokenUsage[]): TokenUsage;
|
|
2743
|
+
//#endregion
|
|
2744
|
+
//#region src/core/agents/flow/steps/factory.d.ts
|
|
2745
|
+
/**
|
|
2746
|
+
* Options for {@link createStepBuilder}.
|
|
2747
|
+
*/
|
|
2748
|
+
interface StepBuilderOptions {
|
|
2749
|
+
/**
|
|
2750
|
+
* Internal execution context.
|
|
2751
|
+
*
|
|
2752
|
+
* Provides the abort signal, logger, and trace array.
|
|
2753
|
+
*/
|
|
2754
|
+
ctx: Context;
|
|
2755
|
+
/**
|
|
2756
|
+
* Parent flow agent hooks forwarded to each step.
|
|
2757
|
+
*
|
|
2758
|
+
* These fire after the step's own hooks, giving the flow agent
|
|
2759
|
+
* visibility into every `$` call.
|
|
2760
|
+
*/
|
|
2761
|
+
parentHooks?: {
|
|
2762
|
+
onStepStart?: (event: {
|
|
2763
|
+
step: StepInfo;
|
|
2764
|
+
}) => void | Promise<void>;
|
|
2765
|
+
onStepFinish?: (event: {
|
|
2766
|
+
step: StepInfo;
|
|
2767
|
+
result: unknown;
|
|
2768
|
+
duration: number;
|
|
2769
|
+
}) => void | Promise<void>;
|
|
2770
|
+
};
|
|
2771
|
+
/**
|
|
2772
|
+
* Stream writer for emitting typed `StreamPart` events.
|
|
2773
|
+
*
|
|
2774
|
+
* When provided, step start/finish events are written as typed
|
|
2775
|
+
* AI SDK stream events. Used by `flowAgent.stream()` to pipe
|
|
2776
|
+
* step events through the readable stream.
|
|
2777
|
+
*/
|
|
2778
|
+
writer?: WritableStreamDefaultWriter<StreamPart>;
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* Create a `StepBuilder` (`$`) instance.
|
|
2782
|
+
*
|
|
2783
|
+
* The returned builder is the `$` object passed into every flow agent
|
|
2784
|
+
* handler and step callback. It owns the full step lifecycle:
|
|
2785
|
+
* trace registration, hook firing, error wrapping,
|
|
2786
|
+
* and `StepResult<T>` construction.
|
|
2787
|
+
*
|
|
2788
|
+
* @param options - Factory configuration with context, optional parent
|
|
2789
|
+
* hooks, and optional stream writer.
|
|
2790
|
+
* @returns A `StepBuilder` instance.
|
|
2791
|
+
*/
|
|
2792
|
+
declare function createStepBuilder(options: StepBuilderOptions): StepBuilder;
|
|
2793
|
+
//#endregion
|
|
2794
|
+
//#region src/utils/error.d.ts
|
|
2795
|
+
/**
|
|
2796
|
+
* Coerces an unknown thrown value into a proper `Error` instance.
|
|
2797
|
+
*
|
|
2798
|
+
* Handles the common cases where libraries throw non-`Error` values
|
|
2799
|
+
* (e.g. plain API response bodies, arrays, Maps) that would otherwise
|
|
2800
|
+
* serialize as `[object Object]` in error messages.
|
|
2801
|
+
*
|
|
2802
|
+
* @param thrown - The caught value from a `catch` block.
|
|
2803
|
+
* @returns An `Error` with a meaningful `.message`. If `thrown` is
|
|
2804
|
+
* already an `Error`, it is returned as-is. The original value is
|
|
2805
|
+
* preserved as `.cause` for debugging.
|
|
2806
|
+
*
|
|
2807
|
+
* @example
|
|
2808
|
+
* ```typescript
|
|
2809
|
+
* try {
|
|
2810
|
+
* await riskyCall()
|
|
2811
|
+
* } catch (thrown) {
|
|
2812
|
+
* const error = toError(thrown)
|
|
2813
|
+
* console.error(error.message)
|
|
2814
|
+
* }
|
|
2815
|
+
* ```
|
|
2816
|
+
*/
|
|
2817
|
+
declare function toError(thrown: unknown): Error;
|
|
2818
|
+
/**
|
|
2819
|
+
* Produce a human-readable string from any unknown value.
|
|
2820
|
+
*
|
|
2821
|
+
* Uses `JSON.stringify` for structured types (plain objects, arrays)
|
|
2822
|
+
* so the message contains actual content instead of `[object Object]`.
|
|
2823
|
+
* Maps and Sets are converted to their array representation first.
|
|
2824
|
+
* Falls back to `String()` for primitives or when serialization fails
|
|
2825
|
+
* (e.g. circular references).
|
|
2826
|
+
*
|
|
2827
|
+
* @param value - The value to stringify.
|
|
2828
|
+
* @returns A meaningful string representation.
|
|
2829
|
+
*
|
|
2830
|
+
* @example
|
|
2831
|
+
* ```typescript
|
|
2832
|
+
* safeStringify({ status: 400 }) // '{"status":400}'
|
|
2833
|
+
* safeStringify(new Map([['k', 'v']])) // '[["k","v"]]'
|
|
2834
|
+
* safeStringify(null) // 'null'
|
|
2835
|
+
* safeStringify(42) // '42'
|
|
2836
|
+
* ```
|
|
2837
|
+
*/
|
|
2838
|
+
declare function safeStringify(value: unknown): string;
|
|
2839
|
+
/**
|
|
2840
|
+
* Safely serializes a value to a JSON string without throwing.
|
|
2841
|
+
*
|
|
2842
|
+
* Converts types that `JSON.stringify` handles poorly (Maps, Sets)
|
|
2843
|
+
* into serializable equivalents before stringifying. Returns an empty
|
|
2844
|
+
* string when serialization fails (e.g. circular references).
|
|
2845
|
+
*
|
|
2846
|
+
* @param value - The value to serialize.
|
|
2847
|
+
* @returns The JSON string, or an empty string if serialization fails.
|
|
2848
|
+
*
|
|
2849
|
+
* @example
|
|
2850
|
+
* ```typescript
|
|
2851
|
+
* safeStringifyJSON({ status: 400 }) // '{"status":400}'
|
|
2852
|
+
* safeStringifyJSON(new Map([['k', 'v']])) // '[["k","v"]]'
|
|
2853
|
+
* safeStringifyJSON(circularObj) // ''
|
|
2854
|
+
* ```
|
|
2855
|
+
*/
|
|
2856
|
+
declare function safeStringifyJSON(value: unknown): string;
|
|
2857
|
+
//#endregion
|
|
2858
|
+
//#region src/utils/resolve.d.ts
|
|
2859
|
+
/**
|
|
2860
|
+
* A value that is either static or dynamically resolved from context.
|
|
2861
|
+
*
|
|
2862
|
+
* Use this for agent/workflow definition fields that may depend on
|
|
2863
|
+
* runtime state (e.g. tools, instructions, prompt).
|
|
2864
|
+
*
|
|
2865
|
+
* @typeParam T - The resolved value type.
|
|
2866
|
+
* @typeParam TCtx - The context type passed when resolving dynamically.
|
|
2867
|
+
*
|
|
2868
|
+
* @example
|
|
2869
|
+
* ```typescript
|
|
2870
|
+
* // Static
|
|
2871
|
+
* instructions: 'You are a helpful assistant'
|
|
2872
|
+
*
|
|
2873
|
+
* // Dynamic (sync)
|
|
2874
|
+
* instructions: (ctx) => `Analyze ${ctx.input.repoName}`
|
|
2875
|
+
*
|
|
2876
|
+
* // Dynamic (async)
|
|
2877
|
+
* instructions: async (ctx) => fetchPrompt(ctx.input.repoName)
|
|
2878
|
+
* ```
|
|
2879
|
+
*/
|
|
2880
|
+
type ResolveParam<T, TCtx> = T | ((ctx: TCtx) => T | Promise<T>);
|
|
2881
|
+
//#endregion
|
|
2882
|
+
export { type Agent, type AgentConfig, type AgentOverrides, type AgentStepConfig, type AgentTokenUsage, type AllConfig, type AsyncIterableStream, type Context, type EachConfig, type EntryFactory, type ExecutionContext, type FlowAgent, type FlowAgentConfig, type FlowAgentConfigBase, type FlowAgentConfigWithOutput, type FlowAgentConfigWithoutOutput, type FlowAgentGenerateResult, type FlowAgentHandler, type FlowAgentOverrides, type FlowAgentParams, type FlowAgentTokenUsage, type CustomStepDefinitions as FlowCustomStepDefinitions, type CustomStepFactory as FlowCustomStepFactory, type FlowEngineConfig, type FlowFactory, type TypedCustomSteps as FlowTypedCustomSteps, type GenerateResult, type LanguageModel, type Logger, type MapConfig, type Message, type Model, type ModelCategory, type ModelDefinition, type ModelId, type ModelPricing, type ModelRef, type OpenRouterLanguageModelId, type OperationType, type Output, type OutputParam, type OutputSpec, type RaceConfig, type ReduceConfig, type ResolveParam, type Result, type ResultError, type Runnable, type StepBuilder, type StepBuilderOptions, type StepConfig, type StepError, type StepInfo, type StepResult, type StreamPart, type StreamResult, type SubAgents, type TextStreamPart, type TokenUsage, type TokenUsageRecord, type Tool, type ToolConfig, type ToolSet, type TraceEntry, type TraceType, type WhileConfig, agent, agentUsage, collectUsages, createDefaultLogger, createFlowEngine, createOpenRouter, createStepBuilder, err, flowAgent, flowAgentUsage, isErr, isOk, model, models, ok, openrouter, resolveOutput, safeStringify, safeStringifyJSON, sumTokenUsage, toError, tool, tryModel };
|
|
2883
|
+
//# sourceMappingURL=index.d.mts.map
|