@anvia/core 0.1.1 → 0.1.3
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/dist/agent/index.d.ts +6 -3
- package/dist/agent/index.js +2 -1
- package/dist/{agent-Bj0UqYMp.d.ts → agent-D5KKP9_z.d.ts} +8 -1
- package/dist/{chunk-JQCRURY2.js → chunk-BIJ5ZBCO.js} +49 -1
- package/dist/chunk-BIJ5ZBCO.js.map +1 -0
- package/dist/{chunk-X6FBOU2P.js → chunk-J23SIK6Y.js} +7 -1
- package/dist/chunk-J23SIK6Y.js.map +1 -0
- package/dist/{chunk-KSIY7KJA.js → chunk-JDPPZCOY.js} +53 -42
- package/dist/chunk-JDPPZCOY.js.map +1 -0
- package/dist/{chunk-C7XTEV5W.js → chunk-U524PWC6.js} +2 -2
- package/dist/chunk-YK4WAAS4.js +18 -0
- package/dist/chunk-YK4WAAS4.js.map +1 -0
- package/dist/{chunk-O3TUS5RB.js → chunk-ZCKIAMMR.js} +2 -2
- package/dist/evals/index.d.ts +2 -2
- package/dist/evals/index.js +6 -5
- package/dist/extractor/index.d.ts +2 -2
- package/dist/extractor/index.js +5 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +23 -20
- package/dist/pipeline/index.d.ts +2 -2
- package/dist/skills/index.js +3 -2
- package/dist/tool/index.d.ts +2 -2
- package/dist/tool/index.js +3 -1
- package/dist/{zod-schema-DJTEgQBq.d.ts → zod-schema-Cq_9zlmJ.d.ts} +15 -1
- package/package.json +2 -2
- package/dist/chunk-JQCRURY2.js.map +0 -1
- package/dist/chunk-KSIY7KJA.js.map +0 -1
- package/dist/chunk-X6FBOU2P.js.map +0 -1
- /package/dist/{chunk-C7XTEV5W.js.map → chunk-U524PWC6.js.map} +0 -0
- /package/dist/{chunk-O3TUS5RB.js.map → chunk-ZCKIAMMR.js.map} +0 -0
package/dist/agent/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { MemoryStore, MemoryOptions } from '../memory/index.js';
|
|
2
2
|
export { MemoryAppendInput, MemoryContext, MemoryErrorInput, MemoryRegistration, MemorySavePolicy, ResolvedMemoryOptions, SessionOptions, resolveMemoryOptions } from '../memory/index.js';
|
|
3
|
-
import { f as DynamicContextOptions, h as DynamicToolOptions, P as PromptHook, A as Agent } from '../agent-
|
|
4
|
-
export { a as AgentOptions, b as AgentSession, c as AgentStreamEvent, d as AgentToolOptions, C as CompletionCallHookArgs, e as CompletionResponseHookArgs, D as DEFAULT_MAX_TURNS, g as DynamicContextRegistration, i as DynamicToolRegistration, H as HookAction, j as HookResult, k as PromptRequest, l as PromptResponse, R as RunControl, T as ToolCallControl, m as ToolCallHookAction, n as ToolCallHookArgs, o as ToolCallHookResult, p as ToolHookArgs, q as ToolResultHookArgs, r as cancelPrompt, s as createHook, t as runControl, u as skipTool, v as toolCallControl } from '../agent-
|
|
3
|
+
import { f as DynamicContextOptions, h as DynamicToolOptions, P as PromptHook, A as Agent } from '../agent-D5KKP9_z.js';
|
|
4
|
+
export { a as AgentOptions, b as AgentSession, c as AgentStreamEvent, d as AgentToolOptions, C as CompletionCallHookArgs, e as CompletionResponseHookArgs, D as DEFAULT_MAX_TURNS, g as DynamicContextRegistration, i as DynamicToolRegistration, H as HookAction, j as HookResult, k as PromptRequest, l as PromptResponse, R as RunControl, T as ToolCallControl, m as ToolCallHookAction, n as ToolCallHookArgs, o as ToolCallHookResult, p as ToolHookArgs, q as ToolResultHookArgs, r as cancelPrompt, s as createHook, t as runControl, u as skipTool, v as toolCallControl } from '../agent-D5KKP9_z.js';
|
|
5
5
|
import { b as CompletionModel, j as JsonValue, o as ToolChoice, M as Message } from '../types-BrxLd7ay.js';
|
|
6
6
|
import { c as McpServer } from '../types-B5B8Sdl4.js';
|
|
7
7
|
import { AgentObserver, ObserveOptions } from '../observability/index.js';
|
|
8
|
-
import {
|
|
8
|
+
import { b as ToolSearchDocument, c as ToolSet, T as ToolMiddleware, Z as ZodSchema } from '../zod-schema-Cq_9zlmJ.js';
|
|
9
9
|
import { b as SkillSet } from '../types-HvopERm0.js';
|
|
10
10
|
import { A as AnyTool } from '../tool-DhuBQ3yb.js';
|
|
11
11
|
import { VectorSearchIndex } from '../vector-store/index.js';
|
|
@@ -32,6 +32,7 @@ declare class AgentBuilder<M extends CompletionModel = CompletionModel> {
|
|
|
32
32
|
private observerRegistrations;
|
|
33
33
|
private dynamicContextRegistrations;
|
|
34
34
|
private dynamicToolRegistrations;
|
|
35
|
+
private middlewareRegistrations;
|
|
35
36
|
private memoryRegistration;
|
|
36
37
|
private activeToolSet;
|
|
37
38
|
constructor(agentId: string, completionModel: M);
|
|
@@ -52,6 +53,8 @@ declare class AgentBuilder<M extends CompletionModel = CompletionModel> {
|
|
|
52
53
|
toolChoice(toolChoice: ToolChoice): this;
|
|
53
54
|
defaultMaxTurns(defaultMaxTurns: number): this;
|
|
54
55
|
hook(hook: PromptHook): this;
|
|
56
|
+
toolMiddleware(middleware: ToolMiddleware): this;
|
|
57
|
+
toolMiddlewares(middlewares: ToolMiddleware[]): this;
|
|
55
58
|
observe(observer: AgentObserver, options?: ObserveOptions): this;
|
|
56
59
|
memory(store: MemoryStore, options?: MemoryOptions): this;
|
|
57
60
|
outputSchema(schema: ZodSchema): this;
|
package/dist/agent/index.js
CHANGED
|
@@ -11,10 +11,11 @@ import {
|
|
|
11
11
|
runControl,
|
|
12
12
|
skipTool,
|
|
13
13
|
toolCallControl
|
|
14
|
-
} from "../chunk-
|
|
14
|
+
} from "../chunk-BIJ5ZBCO.js";
|
|
15
15
|
import {
|
|
16
16
|
resolveMemoryOptions
|
|
17
17
|
} from "../chunk-XXT2UCAR.js";
|
|
18
|
+
import "../chunk-YK4WAAS4.js";
|
|
18
19
|
import "../chunk-XUUY2L2D.js";
|
|
19
20
|
import "../chunk-GNWMOSNR.js";
|
|
20
21
|
import "../chunk-B4QHQN5K.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { M as Message, e as CompletionResponse, b as CompletionModel, U as Usage, l as ReasoningContentType, n as ToolCall, D as Document, j as JsonValue, o as ToolChoice, J as JsonObject } from './types-BrxLd7ay.js';
|
|
2
2
|
import { MemoryContext, MemoryRegistration, SessionOptions } from './memory/index.js';
|
|
3
3
|
import { AgentTraceOptions, AgentTraceInfo, AgentObserverRegistration } from './observability/index.js';
|
|
4
|
-
import {
|
|
4
|
+
import { T as ToolMiddleware, c as ToolSet, b as ToolSearchDocument } from './zod-schema-Cq_9zlmJ.js';
|
|
5
5
|
import { T as Tool, A as AnyTool } from './tool-DhuBQ3yb.js';
|
|
6
6
|
import { VectorSearchIndex, VectorFilter, VectorSearchResult } from './vector-store/index.js';
|
|
7
7
|
|
|
@@ -126,6 +126,7 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
|
|
|
126
126
|
private activeHook;
|
|
127
127
|
private concurrency;
|
|
128
128
|
private traceOptions;
|
|
129
|
+
private requestToolMiddlewares;
|
|
129
130
|
private constructor();
|
|
130
131
|
static fromAgent<M extends CompletionModel>(agent: Agent<M>, prompt: string | Message | Message[], options?: {
|
|
131
132
|
memoryContext?: MemoryContext | undefined;
|
|
@@ -133,12 +134,15 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
|
|
|
133
134
|
maxTurns(maxTurns: number): this;
|
|
134
135
|
requestHook(hook: PromptHook): this;
|
|
135
136
|
withToolConcurrency(concurrency: number): this;
|
|
137
|
+
withToolMiddleware(middleware: ToolMiddleware): this;
|
|
138
|
+
withToolMiddlewares(middlewares: ToolMiddleware[]): this;
|
|
136
139
|
withTrace(trace: AgentTraceOptions): this;
|
|
137
140
|
send(): Promise<PromptResponse>;
|
|
138
141
|
stream(): AsyncIterable<AgentStreamEvent>;
|
|
139
142
|
readableStream(): ReadableStream<Uint8Array>;
|
|
140
143
|
private runCompletion;
|
|
141
144
|
private executeToolCalls;
|
|
145
|
+
private runToolResultMiddlewares;
|
|
142
146
|
private startRunObservers;
|
|
143
147
|
private fetchDynamicContext;
|
|
144
148
|
private fetchToolDefinitions;
|
|
@@ -173,6 +177,7 @@ type AgentOptions<M extends CompletionModel = CompletionModel> = {
|
|
|
173
177
|
observers?: AgentObserverRegistration[] | undefined;
|
|
174
178
|
dynamicContexts?: DynamicContextRegistration[] | undefined;
|
|
175
179
|
dynamicTools?: DynamicToolRegistration[] | undefined;
|
|
180
|
+
toolMiddlewares?: ToolMiddleware[] | undefined;
|
|
176
181
|
memory?: MemoryRegistration | undefined;
|
|
177
182
|
};
|
|
178
183
|
declare const DEFAULT_MAX_TURNS = 20;
|
|
@@ -218,6 +223,7 @@ declare class Agent<M extends CompletionModel = CompletionModel> {
|
|
|
218
223
|
readonly observers: AgentObserverRegistration[];
|
|
219
224
|
readonly dynamicContexts: DynamicContextRegistration[];
|
|
220
225
|
readonly dynamicTools: DynamicToolRegistration[];
|
|
226
|
+
readonly toolMiddlewares: ToolMiddleware[];
|
|
221
227
|
readonly memory: MemoryRegistration | undefined;
|
|
222
228
|
constructor(options: AgentOptions<M>);
|
|
223
229
|
prompt(prompt: string | Message | Message[]): PromptRequest<M>;
|
|
@@ -227,6 +233,7 @@ declare class Agent<M extends CompletionModel = CompletionModel> {
|
|
|
227
233
|
}, string>;
|
|
228
234
|
getTool(toolName: string): AnyTool | undefined;
|
|
229
235
|
callTool(toolName: string, args: string): Promise<string>;
|
|
236
|
+
shouldApplyToolMiddleware(toolName: string): boolean;
|
|
230
237
|
}
|
|
231
238
|
declare class AgentSession<M extends CompletionModel = CompletionModel> {
|
|
232
239
|
private readonly agent;
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveMemoryOptions
|
|
3
3
|
} from "./chunk-XXT2UCAR.js";
|
|
4
|
+
import {
|
|
5
|
+
isSkillTool
|
|
6
|
+
} from "./chunk-YK4WAAS4.js";
|
|
4
7
|
import {
|
|
5
8
|
toReadableStream
|
|
6
9
|
} from "./chunk-XUUY2L2D.js";
|
|
@@ -474,6 +477,7 @@ var PromptRequest = class _PromptRequest {
|
|
|
474
477
|
activeHook;
|
|
475
478
|
concurrency = 1;
|
|
476
479
|
traceOptions;
|
|
480
|
+
requestToolMiddlewares = [];
|
|
477
481
|
static fromAgent(agent, prompt, options = {}) {
|
|
478
482
|
const normalized = normalizePromptInput(prompt);
|
|
479
483
|
return new _PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);
|
|
@@ -490,6 +494,14 @@ var PromptRequest = class _PromptRequest {
|
|
|
490
494
|
this.concurrency = Math.max(1, concurrency);
|
|
491
495
|
return this;
|
|
492
496
|
}
|
|
497
|
+
withToolMiddleware(middleware) {
|
|
498
|
+
this.requestToolMiddlewares.push(middleware);
|
|
499
|
+
return this;
|
|
500
|
+
}
|
|
501
|
+
withToolMiddlewares(middlewares) {
|
|
502
|
+
this.requestToolMiddlewares.push(...middlewares);
|
|
503
|
+
return this;
|
|
504
|
+
}
|
|
493
505
|
withTrace(trace) {
|
|
494
506
|
this.traceOptions = trace;
|
|
495
507
|
return this;
|
|
@@ -756,6 +768,14 @@ var PromptRequest = class _PromptRequest {
|
|
|
756
768
|
output = error instanceof Error ? error.toString() : String(error);
|
|
757
769
|
}
|
|
758
770
|
}
|
|
771
|
+
if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {
|
|
772
|
+
output = await this.runToolResultMiddlewares({
|
|
773
|
+
...hookArgs,
|
|
774
|
+
result: output,
|
|
775
|
+
originalResult: output,
|
|
776
|
+
turn: observation?.turn ?? 0
|
|
777
|
+
});
|
|
778
|
+
}
|
|
759
779
|
const resultAction = await this.activeHook?.onToolResult?.({
|
|
760
780
|
...hookArgs,
|
|
761
781
|
result: output,
|
|
@@ -787,6 +807,19 @@ var PromptRequest = class _PromptRequest {
|
|
|
787
807
|
return ToolContent.toolResult(toolCall.id, output, toolCall.callId);
|
|
788
808
|
});
|
|
789
809
|
}
|
|
810
|
+
async runToolResultMiddlewares(args) {
|
|
811
|
+
let result = args.result;
|
|
812
|
+
for (const middleware of [...this.agent.toolMiddlewares, ...this.requestToolMiddlewares]) {
|
|
813
|
+
const replacement = await middleware.onResult?.({
|
|
814
|
+
...args,
|
|
815
|
+
result
|
|
816
|
+
});
|
|
817
|
+
if (replacement !== void 0) {
|
|
818
|
+
result = replacement;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return result;
|
|
822
|
+
}
|
|
790
823
|
async startRunObservers() {
|
|
791
824
|
const failOnObserverError = this.traceOptions?.failOnObserverError === true || this.agent.observers.some((registration) => registration.failOnObserverError === true);
|
|
792
825
|
return startAgentRunObservers(
|
|
@@ -1095,6 +1128,7 @@ var Agent = class {
|
|
|
1095
1128
|
observers;
|
|
1096
1129
|
dynamicContexts;
|
|
1097
1130
|
dynamicTools;
|
|
1131
|
+
toolMiddlewares;
|
|
1098
1132
|
memory;
|
|
1099
1133
|
constructor(options) {
|
|
1100
1134
|
this.id = normalizeAgentId(options.id);
|
|
@@ -1114,6 +1148,7 @@ var Agent = class {
|
|
|
1114
1148
|
this.observers = options.observers ?? [];
|
|
1115
1149
|
this.dynamicContexts = options.dynamicContexts ?? [];
|
|
1116
1150
|
this.dynamicTools = options.dynamicTools ?? [];
|
|
1151
|
+
this.toolMiddlewares = options.toolMiddlewares ?? [];
|
|
1117
1152
|
this.memory = options.memory;
|
|
1118
1153
|
}
|
|
1119
1154
|
prompt(prompt) {
|
|
@@ -1174,6 +1209,9 @@ var Agent = class {
|
|
|
1174
1209
|
}
|
|
1175
1210
|
return this.toolSet.call(toolName, args);
|
|
1176
1211
|
}
|
|
1212
|
+
shouldApplyToolMiddleware(toolName) {
|
|
1213
|
+
return !isSkillTool(this.getTool(toolName));
|
|
1214
|
+
}
|
|
1177
1215
|
};
|
|
1178
1216
|
var AgentSession = class {
|
|
1179
1217
|
constructor(agent, context) {
|
|
@@ -1241,6 +1279,7 @@ var AgentBuilder = class {
|
|
|
1241
1279
|
observerRegistrations = [];
|
|
1242
1280
|
dynamicContextRegistrations = [];
|
|
1243
1281
|
dynamicToolRegistrations = [];
|
|
1282
|
+
middlewareRegistrations = [];
|
|
1244
1283
|
memoryRegistration;
|
|
1245
1284
|
activeToolSet = new ToolSet();
|
|
1246
1285
|
name(name) {
|
|
@@ -1319,6 +1358,14 @@ var AgentBuilder = class {
|
|
|
1319
1358
|
this.requestHook = hook;
|
|
1320
1359
|
return this;
|
|
1321
1360
|
}
|
|
1361
|
+
toolMiddleware(middleware) {
|
|
1362
|
+
this.middlewareRegistrations.push(middleware);
|
|
1363
|
+
return this;
|
|
1364
|
+
}
|
|
1365
|
+
toolMiddlewares(middlewares) {
|
|
1366
|
+
this.middlewareRegistrations.push(...middlewares);
|
|
1367
|
+
return this;
|
|
1368
|
+
}
|
|
1322
1369
|
observe(observer, options = {}) {
|
|
1323
1370
|
this.observerRegistrations.push({
|
|
1324
1371
|
observer,
|
|
@@ -1356,6 +1403,7 @@ var AgentBuilder = class {
|
|
|
1356
1403
|
observers: this.observerRegistrations,
|
|
1357
1404
|
dynamicContexts: this.dynamicContextRegistrations,
|
|
1358
1405
|
dynamicTools: this.dynamicToolRegistrations,
|
|
1406
|
+
toolMiddlewares: this.middlewareRegistrations,
|
|
1359
1407
|
memory: this.memoryRegistration
|
|
1360
1408
|
});
|
|
1361
1409
|
}
|
|
@@ -1391,4 +1439,4 @@ export {
|
|
|
1391
1439
|
AgentSession,
|
|
1392
1440
|
AgentBuilder
|
|
1393
1441
|
};
|
|
1394
|
-
//# sourceMappingURL=chunk-
|
|
1442
|
+
//# sourceMappingURL=chunk-BIJ5ZBCO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/agent.ts","../src/observability/group.ts","../src/agent/errors.ts","../src/agent/hooks.ts","../src/agent/utils.ts","../src/agent/stream-accumulator.ts","../src/agent/request.ts","../src/agent/builder.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type {\n CompletionModel,\n Document,\n JsonObject,\n JsonValue,\n Message as MessageType,\n ToolChoice,\n} from \"../completion/index\";\nimport type { MemoryRegistration, SessionOptions } from \"../memory\";\nimport type { AgentObserverRegistration } from \"../observability\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { ToolSearchDocument } from \"../tool/dynamic-tools\";\nimport type { ToolMiddleware } from \"../tool/middleware\";\nimport { isSkillTool } from \"../tool/skill-tool-marker\";\nimport type { AnyTool, Tool } from \"../tool/tool\";\nimport { ToolSet } from \"../tool/tool-set\";\nimport type { VectorFilter, VectorSearchIndex, VectorSearchResult } from \"../vector-store\";\nimport type { PromptHook } from \"./hooks\";\nimport { PromptRequest } from \"./request\";\n\nexport type AgentOptions<M extends CompletionModel = CompletionModel> = {\n id: string;\n name?: string | undefined;\n description?: string | undefined;\n model: M;\n instructions?: string | undefined;\n staticContext?: Document[];\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n additionalParams?: JsonValue | undefined;\n toolSet?: ToolSet | undefined;\n toolChoice?: ToolChoice | undefined;\n defaultMaxTurns?: number | undefined;\n hook?: PromptHook | undefined;\n outputSchema?: JsonObject | undefined;\n observers?: AgentObserverRegistration[] | undefined;\n dynamicContexts?: DynamicContextRegistration[] | undefined;\n dynamicTools?: DynamicToolRegistration[] | undefined;\n toolMiddlewares?: ToolMiddleware[] | undefined;\n memory?: MemoryRegistration | undefined;\n};\n\nexport const DEFAULT_MAX_TURNS = 20;\n\nexport type AgentToolOptions = {\n name: string;\n description?: string | undefined;\n maxTurns?: number | undefined;\n};\n\nexport type DynamicContextOptions<T = unknown> = {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n format?: ((result: VectorSearchResult<T>) => Document) | undefined;\n};\n\nexport type DynamicContextRegistration<T = unknown> = {\n index: VectorSearchIndex<T>;\n options: DynamicContextOptions<T>;\n};\n\nexport type DynamicToolOptions = {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n};\n\nexport type DynamicToolRegistration = {\n index: VectorSearchIndex<ToolSearchDocument>;\n options: DynamicToolOptions;\n};\n\nexport class Agent<M extends CompletionModel = CompletionModel> {\n readonly id: string;\n readonly name: string | undefined;\n readonly description: string | undefined;\n readonly model: M;\n readonly instructions: string | undefined;\n readonly staticContext: Document[];\n readonly temperature: number | undefined;\n readonly maxTokens: number | undefined;\n readonly additionalParams: JsonValue | undefined;\n readonly toolSet: ToolSet;\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly hook: PromptHook | undefined;\n readonly outputSchema: JsonObject | undefined;\n readonly observers: AgentObserverRegistration[];\n readonly dynamicContexts: DynamicContextRegistration[];\n readonly dynamicTools: DynamicToolRegistration[];\n readonly toolMiddlewares: ToolMiddleware[];\n readonly memory: MemoryRegistration | undefined;\n\n constructor(options: AgentOptions<M>) {\n this.id = normalizeAgentId(options.id);\n this.name = options.name;\n this.description = options.description;\n this.model = options.model;\n this.instructions = options.instructions;\n this.staticContext = options.staticContext ?? [];\n this.temperature = options.temperature;\n this.maxTokens = options.maxTokens;\n this.additionalParams = options.additionalParams;\n this.toolSet = options.toolSet ?? new ToolSet();\n this.toolChoice = options.toolChoice;\n this.defaultMaxTurns = options.defaultMaxTurns ?? DEFAULT_MAX_TURNS;\n this.hook = options.hook;\n this.outputSchema = options.outputSchema;\n this.observers = options.observers ?? [];\n this.dynamicContexts = options.dynamicContexts ?? [];\n this.dynamicTools = options.dynamicTools ?? [];\n this.toolMiddlewares = options.toolMiddlewares ?? [];\n this.memory = options.memory;\n }\n\n prompt(prompt: string | MessageType | MessageType[]): PromptRequest<M> {\n return PromptRequest.fromAgent(this, prompt);\n }\n\n session(sessionId: string, options: SessionOptions = {}): AgentSession<M> {\n if (this.memory === undefined) {\n throw new Error(`Agent \"${this.id}\" has no memory store configured.`);\n }\n const normalized = sessionId.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Session id must be a non-empty string.\");\n }\n return new AgentSession(this, {\n sessionId: normalized,\n ...(options.userId === undefined ? {} : { userId: options.userId }),\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n });\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, string> {\n const description =\n options.description ?? this.description ?? `Prompt the ${options.name} agent.`;\n\n return createTool({\n name: options.name,\n description,\n input: z.object({\n prompt: z.string().describe(\"The prompt to send to the agent.\"),\n }),\n output: z.string(),\n execute: async ({ prompt }) => {\n const request = this.prompt(prompt);\n const response =\n options.maxTurns === undefined\n ? await request.send()\n : await request.maxTurns(options.maxTurns).send();\n return response.output;\n },\n });\n }\n\n getTool(toolName: string): AnyTool | undefined {\n const staticTool = this.toolSet.get(toolName);\n if (staticTool !== undefined) {\n return staticTool;\n }\n\n for (const registration of this.dynamicTools) {\n const dynamicTool = dynamicToolSetFromIndex(registration.index)?.get(toolName);\n if (dynamicTool !== undefined) {\n return dynamicTool;\n }\n }\n\n return undefined;\n }\n\n async callTool(toolName: string, args: string): Promise<string> {\n if (this.toolSet.contains(toolName)) {\n return this.toolSet.call(toolName, args);\n }\n\n for (const registration of this.dynamicTools) {\n const toolSet = dynamicToolSetFromIndex(registration.index);\n if (toolSet?.contains(toolName)) {\n return toolSet.call(toolName, args);\n }\n }\n\n return this.toolSet.call(toolName, args);\n }\n\n shouldApplyToolMiddleware(toolName: string): boolean {\n return !isSkillTool(this.getTool(toolName));\n }\n}\n\nexport class AgentSession<M extends CompletionModel = CompletionModel> {\n constructor(\n private readonly agent: Agent<M>,\n private readonly context: {\n sessionId: string;\n userId?: string | undefined;\n metadata?: JsonObject | undefined;\n },\n ) {}\n\n prompt(prompt: string | MessageType): PromptRequest<M> {\n if (Array.isArray(prompt)) {\n throw new TypeError(\"AgentSession.prompt does not accept Message[] transcripts.\");\n }\n return PromptRequest.fromAgent(this.agent, prompt, { memoryContext: this.context });\n }\n\n async messages(): Promise<MessageType[]> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n return memory.store.load(this.context);\n }\n\n async clear(): Promise<void> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n await memory.store.clear(this.context);\n }\n}\n\nfunction dynamicToolSetFromIndex(\n index: VectorSearchIndex<ToolSearchDocument>,\n): ToolSet | undefined {\n const maybeIndex = index as { toolSet?: unknown };\n return maybeIndex.toolSet instanceof ToolSet ? maybeIndex.toolSet : undefined;\n}\n\nfunction normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n","import type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentObserverRegistration,\n AgentRunEndArgs,\n AgentRunErrorArgs,\n AgentRunObserver,\n AgentRunStartArgs,\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolObserver,\n AgentToolStartArgs,\n AgentTraceInfo,\n} from \"./types\";\n\nexport async function startAgentRunObservers(\n registrations: AgentObserverRegistration[],\n args: AgentRunStartArgs,\n failOnObserverError: boolean,\n): Promise<ActiveAgentRunObservers> {\n const runObservers: AgentRunObserver[] = [];\n for (const registration of registrations) {\n try {\n const runObserver = await registration.observer.startRun(args);\n if (runObserver !== undefined) {\n runObservers.push(runObserver);\n }\n } catch (error) {\n if (failOnObserverError || registration.failOnObserverError === true) {\n throw error;\n }\n }\n }\n\n return new ActiveAgentRunObservers(runObservers, failOnObserverError);\n}\n\nexport class ActiveAgentRunObservers {\n readonly trace: AgentTraceInfo | undefined;\n\n constructor(\n private readonly runObservers: AgentRunObserver[],\n private readonly failOnObserverError: boolean,\n ) {\n this.trace = runObservers.find((observer) => observer.trace !== undefined)?.trace;\n }\n\n async startGeneration(args: AgentGenerationStartArgs): Promise<ActiveGenerationObservers> {\n const generationObservers: AgentGenerationObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startGeneration === undefined) {\n continue;\n }\n try {\n const generationObserver = await runObserver.startGeneration(args);\n if (generationObserver !== undefined) {\n generationObservers.push(generationObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);\n }\n\n async startTool(args: AgentToolStartArgs): Promise<ActiveToolObservers> {\n const toolObservers: AgentToolObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startTool === undefined) {\n continue;\n }\n try {\n const toolObserver = await runObserver.startTool(args);\n if (toolObserver !== undefined) {\n toolObservers.push(toolObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveToolObservers(toolObservers, this.failOnObserverError);\n }\n\n async end(args: AgentRunEndArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n try {\n await runObserver.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentRunErrorArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.error === undefined) {\n continue;\n }\n try {\n await runObserver.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveGenerationObservers {\n constructor(\n private readonly generationObservers: AgentGenerationObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async end(args: AgentGenerationEndArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentGenerationErrorArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveToolObservers {\n constructor(\n private readonly toolObservers: AgentToolObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async end(args: AgentToolEndArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n","import type { Message } from \"../completion/index\";\n\nexport class MaxTurnsError extends Error {\n constructor(\n readonly maxTurns: number,\n readonly chatHistory: Message[],\n readonly prompt: Message,\n ) {\n super(`Reached max turn limit: ${maxTurns}`);\n this.name = \"MaxTurnsError\";\n }\n}\n\nexport class PromptCancelledError extends Error {\n constructor(\n readonly chatHistory: Message[],\n readonly reason: string,\n ) {\n super(`Prompt cancelled: ${reason}`);\n this.name = \"PromptCancelledError\";\n }\n}\n","import type { CompletionResponse, Message } from \"../completion/index\";\n\nexport type HookAction = { type: \"continue\" } | { type: \"terminate\"; reason: string };\nexport type ToolCallHookAction =\n | { type: \"continue\" }\n | { type: \"skip\"; reason: string }\n | { type: \"terminate\"; reason: string };\n\nexport type RunControl = {\n continue(): HookAction;\n cancel(reason: string): HookAction;\n};\n\nexport type ToolCallControl = {\n run(): ToolCallHookAction;\n skip(reason: string): ToolCallHookAction;\n cancel(reason: string): ToolCallHookAction;\n};\n\nexport type HookResult = HookAction | undefined;\nexport type ToolCallHookResult = ToolCallHookAction | undefined;\n\ntype HookCallback<Args> = (\n args: Args,\n) => HookAction | Promise<HookAction | undefined> | Promise<void> | void;\ntype ToolCallHookCallback<Args> = (\n args: Args,\n) => ToolCallHookAction | Promise<ToolCallHookAction | undefined> | Promise<void> | void;\n\nexport type CompletionCallHookArgs = {\n prompt: Message;\n history: Message[];\n run: RunControl;\n};\n\nexport type CompletionResponseHookArgs<RawResponse = unknown> = {\n prompt: Message;\n response: CompletionResponse<RawResponse>;\n run: RunControl;\n};\n\nexport type ToolHookArgs = {\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n};\n\nexport type ToolCallHookArgs = ToolHookArgs & {\n tool: ToolCallControl;\n};\n\nexport type ToolResultHookArgs = ToolHookArgs & {\n result: string;\n run: RunControl;\n};\n\nexport function createHook<RawResponse = unknown>(\n hook: PromptHook<RawResponse>,\n): PromptHook<RawResponse> {\n return hook;\n}\n\nexport function cancelPrompt(reason: string): HookAction {\n return { type: \"terminate\", reason };\n}\n\nexport function skipTool(reason: string): ToolCallHookAction {\n return { type: \"skip\", reason };\n}\n\nexport const runControl: RunControl = {\n continue() {\n return { type: \"continue\" };\n },\n cancel(reason: string) {\n return cancelPrompt(reason);\n },\n};\n\nexport const toolCallControl: ToolCallControl = {\n run() {\n return { type: \"continue\" };\n },\n skip(reason: string) {\n return skipTool(reason);\n },\n cancel(reason: string) {\n return { type: \"terminate\", reason };\n },\n};\n\nexport interface PromptHook<RawResponse = unknown> {\n onCompletionCall?: HookCallback<CompletionCallHookArgs>;\n onCompletionResponse?: HookCallback<CompletionResponseHookArgs<RawResponse>>;\n onToolCall?: ToolCallHookCallback<ToolCallHookArgs>;\n onToolResult?: HookCallback<ToolResultHookArgs>;\n}\n","import type {\n CompletionModel,\n JsonValue,\n Message as MessageType,\n StreamingCompletionModel,\n} from \"../completion/index\";\n\nexport function isStreamingCompletionModel(\n model: CompletionModel,\n): model is StreamingCompletionModel {\n return \"streamCompletion\" in model && typeof model.streamCompletion === \"function\";\n}\n\nexport function extractRagText(message: MessageType): string | undefined {\n if (message.role === \"user\") {\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n if (message.role === \"tool\") {\n return message.content\n .flatMap((item) => item.content.flatMap((part) => (part.type === \"text\" ? [part.text] : [])))\n .join(\"\\n\");\n }\n\n return undefined;\n}\n\nexport function parseJsonValue(text: string): JsonValue {\n if (text.trim().length === 0) {\n return {};\n }\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n\nexport async function mapWithConcurrency<T, R>(\n items: T[],\n concurrency: number,\n mapper: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n\n async function worker(): Promise<void> {\n while (next < items.length) {\n const index = next;\n next += 1;\n const item = items[index];\n if (item !== undefined) {\n results[index] = await mapper(item);\n }\n }\n }\n\n const workerCount = Math.min(concurrency, items.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n return results;\n}\n","import type {\n AssistantContent as AssistantContentType,\n CompletionResponse,\n CompletionStreamEvent,\n ReasoningContent,\n ReasoningContentType,\n ToolCall,\n} from \"../completion/index\";\nimport { Usage } from \"../completion/index\";\nimport { parseJsonValue } from \"./utils\";\n\nexport type AgentDeltaEvent =\n | { type: \"text_delta\"; delta: string }\n | {\n type: \"reasoning_delta\";\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | { type: \"tool_call\"; toolCall: ToolCall };\n\ntype ReasoningState = {\n text: string;\n content?: ReasoningContent[];\n};\n\ntype PartialToolCall = {\n id: string;\n callId?: string;\n name: string;\n argumentsText: string;\n signature?: string;\n};\n\nexport class CompletionStreamAccumulator<RawResponse = unknown> {\n private static readonly defaultReasoningKey = \"reasoning\";\n private text = \"\";\n private reasoningById = new Map<string, ReasoningState>();\n private reasoningOrder: string[] = [];\n private toolCalls = new Map<string, PartialToolCall>();\n private toolCallOrder: string[] = [];\n private finalResponse: CompletionResponse<RawResponse> | undefined;\n private messageId: string | undefined;\n\n accept(event: CompletionStreamEvent<RawResponse>): AgentDeltaEvent | undefined {\n if (event.type === \"text_delta\") {\n this.text += event.delta;\n return { type: \"text_delta\", delta: event.delta };\n }\n\n if (event.type === \"reasoning_delta\") {\n const key = event.id ?? CompletionStreamAccumulator.defaultReasoningKey;\n const existing = this.reasoningById.get(key);\n const reasoning = existing ?? { text: \"\" };\n if (!existing) {\n this.reasoningOrder.push(key);\n }\n this.appendReasoning(reasoning, event);\n this.reasoningById.set(key, reasoning);\n return reasoningDeltaEvent(event);\n }\n\n if (event.type === \"tool_call_delta\") {\n const existing = this.toolCalls.get(event.id);\n const toolCall = existing ?? {\n id: event.id,\n name: \"\",\n argumentsText: \"\",\n };\n if (!existing) {\n this.toolCallOrder.push(event.id);\n }\n if (event.callId !== undefined) toolCall.callId = event.callId;\n if (event.name !== undefined) toolCall.name = event.name;\n if (event.signature !== undefined) toolCall.signature = event.signature;\n if (event.argumentsDelta !== undefined) {\n toolCall.argumentsText += event.argumentsDelta;\n }\n this.toolCalls.set(event.id, toolCall);\n return undefined;\n }\n\n if (event.type === \"tool_call\") {\n this.upsertToolCall(event.toolCall);\n return undefined;\n }\n\n if (event.type === \"message_id\") {\n this.messageId = event.id;\n return undefined;\n }\n\n if (event.type === \"final\") {\n this.finalResponse = event.response;\n return undefined;\n }\n\n return undefined;\n }\n\n response(): CompletionResponse<RawResponse> {\n if (this.finalResponse !== undefined) {\n if (this.finalResponse.choice.length === 0) {\n const response = {\n ...this.buildAccumulatedResponse(),\n usage: this.finalResponse.usage,\n rawResponse: this.finalResponse.rawResponse,\n };\n if (this.finalResponse.messageId !== undefined) {\n response.messageId = this.finalResponse.messageId;\n }\n return response;\n }\n return this.finalResponse;\n }\n\n return this.buildAccumulatedResponse();\n }\n\n private buildAccumulatedResponse(): CompletionResponse<RawResponse> {\n const choice: AssistantContentType[] = [];\n if (this.text.length > 0) {\n choice.push({ type: \"text\", text: this.text });\n }\n for (const key of this.reasoningOrder) {\n const reasoning = this.reasoningById.get(key) ?? { text: \"\" };\n const id = key === CompletionStreamAccumulator.defaultReasoningKey ? undefined : key;\n const content =\n reasoning.content === undefined\n ? { type: \"reasoning\" as const, text: reasoning.text }\n : { type: \"reasoning\" as const, text: reasoning.text, content: reasoning.content };\n choice.push(id === undefined ? content : { ...content, id });\n }\n for (const id of this.toolCallOrder) {\n const toolCall = this.toolCalls.get(id);\n if (toolCall !== undefined) {\n const content: ToolCall = {\n type: \"tool_call\",\n id: toolCall.id,\n function: {\n name: toolCall.name,\n arguments: parseJsonValue(toolCall.argumentsText),\n },\n };\n if (toolCall.callId !== undefined) {\n content.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n content.signature = toolCall.signature;\n }\n choice.push(content);\n }\n }\n\n const response: CompletionResponse<RawResponse> = {\n choice,\n usage: Usage.empty(),\n rawResponse: undefined as RawResponse,\n };\n if (this.messageId !== undefined) {\n response.messageId = this.messageId;\n }\n return response;\n }\n\n private upsertToolCall(toolCall: ToolCall): void {\n if (!this.toolCalls.has(toolCall.id)) {\n this.toolCallOrder.push(toolCall.id);\n }\n const partial: PartialToolCall = {\n id: toolCall.id,\n name: toolCall.function.name,\n argumentsText: JSON.stringify(toolCall.function.arguments ?? {}),\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n partial.signature = toolCall.signature;\n }\n this.toolCalls.set(toolCall.id, partial);\n }\n\n private appendReasoning(\n reasoning: ReasoningState,\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): void {\n const contentType = event.contentType ?? \"text\";\n if (contentType === \"text\" || contentType === \"summary\") {\n reasoning.text += event.delta;\n }\n\n if (event.contentType === undefined && event.signature === undefined) {\n return;\n }\n\n reasoning.content ??= [];\n const last = reasoning.content.at(-1);\n if (contentType === \"text\") {\n if (last?.type === \"text\") {\n last.text += event.delta;\n if (event.signature !== undefined) {\n last.signature = event.signature;\n }\n } else {\n reasoning.content.push(\n event.signature === undefined\n ? { type: \"text\", text: event.delta }\n : { type: \"text\", text: event.delta, signature: event.signature },\n );\n }\n return;\n }\n\n if (contentType === \"summary\") {\n if (last?.type === \"summary\") {\n last.text += event.delta;\n } else {\n reasoning.content.push({ type: \"summary\", text: event.delta });\n }\n return;\n }\n\n if (contentType === \"encrypted\") {\n reasoning.content.push({ type: \"encrypted\", data: event.delta });\n return;\n }\n\n reasoning.content.push({ type: \"redacted\", data: event.delta });\n }\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionStreamEvent, { type: \"reasoning_delta\" }>,\n): AgentDeltaEvent {\n const mapped: AgentDeltaEvent = { type: \"reasoning_delta\", delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n}\n","import {\n assertCompletionRequestSupported,\n type CompletionModel,\n CompletionRequestBuilder,\n type CompletionResponse,\n type Document,\n Message,\n type Message as MessageType,\n type ReasoningContentType,\n type ToolCall,\n ToolContent,\n type ToolDefinition,\n type ToolResult,\n textFromAssistantContent,\n Usage,\n} from \"../completion/index\";\nimport type { MemoryContext, MemoryRegistration, MemorySavePolicy } from \"../memory\";\nimport {\n type ActiveAgentRunObservers,\n type ActiveToolObservers,\n startAgentRunObservers,\n} from \"../observability/group\";\nimport type { AgentTraceInfo, AgentTraceOptions } from \"../observability/types\";\nimport { toReadableStream } from \"../streaming\";\nimport type { ToolMiddleware, ToolResultMiddlewareArgs } from \"../tool/middleware\";\nimport type { Agent } from \"./agent\";\nimport { MaxTurnsError, PromptCancelledError } from \"./errors\";\nimport type { PromptHook, ToolHookArgs } from \"./hooks\";\nimport { runControl, toolCallControl } from \"./hooks\";\nimport { type AgentDeltaEvent, CompletionStreamAccumulator } from \"./stream-accumulator\";\nimport { extractRagText, isStreamingCompletionModel, mapWithConcurrency } from \"./utils\";\n\nexport type PromptResponse = {\n output: string;\n usage: Usage;\n messages: MessageType[];\n trace?: AgentTraceInfo | undefined;\n};\n\nexport type AgentStreamEvent<RawResponse = unknown> =\n | {\n type: \"turn_start\";\n turn: number;\n prompt: MessageType;\n history: MessageType[];\n }\n | {\n type: \"text_delta\";\n turn: number;\n delta: string;\n }\n | {\n type: \"reasoning_delta\";\n turn: number;\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | {\n type: \"tool_call\";\n turn: number;\n toolCall: ToolCall;\n }\n | {\n type: \"tool_result\";\n turn: number;\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n }\n | {\n type: \"turn_end\";\n turn: number;\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"final\";\n output: string;\n usage: Usage;\n messages: MessageType[];\n trace?: AgentTraceInfo | undefined;\n }\n | {\n type: \"error\";\n error: unknown;\n };\n\nexport class PromptRequest<M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: PromptHook | undefined;\n private concurrency = 1;\n private traceOptions: AgentTraceOptions | undefined;\n private requestToolMiddlewares: ToolMiddleware[] = [];\n\n private constructor(\n private readonly agent: Agent<M>,\n private readonly promptMessage: MessageType,\n private readonly initialHistory: MessageType[] = [],\n private readonly memoryContext: MemoryContext | undefined = undefined,\n ) {\n this.chatHistory = initialHistory;\n this.maxTurnCount = agent.defaultMaxTurns ?? 0;\n this.activeHook = agent.hook;\n }\n\n static fromAgent<M extends CompletionModel>(\n agent: Agent<M>,\n prompt: string | MessageType | MessageType[],\n options: { memoryContext?: MemoryContext | undefined } = {},\n ): PromptRequest<M> {\n const normalized = normalizePromptInput(prompt);\n return new PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);\n }\n\n maxTurns(maxTurns: number): this {\n this.maxTurnCount = maxTurns;\n return this;\n }\n\n requestHook(hook: PromptHook): this {\n this.activeHook = hook;\n return this;\n }\n\n withToolConcurrency(concurrency: number): this {\n this.concurrency = Math.max(1, concurrency);\n return this;\n }\n\n withToolMiddleware(middleware: ToolMiddleware): this {\n this.requestToolMiddlewares.push(middleware);\n return this;\n }\n\n withToolMiddlewares(middlewares: ToolMiddleware[]): this {\n this.requestToolMiddlewares.push(...middlewares);\n return this;\n }\n\n withTrace(trace: AgentTraceOptions): this {\n this.traceOptions = trace;\n return this;\n }\n\n async send(): Promise<PromptResponse> {\n const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n await this.prepareMemoryRun(runId, newMessages);\n const pendingTurnMessages = this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n const runObservers = await this.startRunObservers();\n\n try {\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await this.fetchDynamicContext(ragText);\n const toolDefs = await this.fetchToolDefinitions(ragText);\n const request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n\n const response = await this.runCompletion(request, currentTurns, runObservers);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.commitMemoryMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n if (toolCalls.length === 0) {\n await this.commitCompletedMemoryRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n const result: PromptResponse = {\n output: textFromAssistantContent(response.choice),\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n };\n await runObservers.end(result);\n return result;\n }\n\n const toolResults = await this.executeToolCalls(toolCalls, newMessages, undefined, {\n turn: currentTurns,\n runObservers,\n });\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);\n await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n await runObservers.error({ error, usage, messages: [...newMessages] });\n await this.recordMemoryError(runId, error, newMessages);\n throw error;\n }\n }\n\n async *stream(): AsyncIterable<AgentStreamEvent> {\n if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n\n const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n await this.prepareMemoryRun(runId, newMessages);\n const pendingTurnMessages = this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n const runObservers = await this.startRunObservers();\n\n try {\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n yield {\n type: \"turn_start\",\n turn: currentTurns,\n prompt,\n history: historyForRequest,\n };\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await this.fetchDynamicContext(ragText);\n const toolDefs = await this.fetchToolDefinitions(ragText);\n const request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const generationObservers = await runObservers.startGeneration({\n turn: currentTurns,\n request,\n });\n const accumulator = new CompletionStreamAccumulator();\n const generationStartedAt = Date.now();\n let firstDeltaMs: number | undefined;\n try {\n for await (const event of this.agent.model.streamCompletion(request)) {\n if (firstDeltaMs === undefined && isGenerationDeltaEvent(event.type)) {\n firstDeltaMs = Date.now() - generationStartedAt;\n }\n const mapped = accumulator.accept(event);\n if (event.type === \"error\") {\n throw event.error;\n }\n if (mapped !== undefined) {\n yield addTurn(currentTurns, mapped);\n }\n }\n } catch (error) {\n await generationObservers.error({ turn: currentTurns, error });\n throw error;\n }\n\n const response = accumulator.response();\n await generationObservers.end({\n turn: currentTurns,\n response,\n ...(firstDeltaMs === undefined ? {} : { firstDeltaMs }),\n });\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.commitMemoryMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n for (const toolCall of toolCalls) {\n yield { type: \"tool_call\", turn: currentTurns, toolCall };\n }\n yield { type: \"turn_end\", turn: currentTurns, response };\n\n if (toolCalls.length === 0) {\n const output = textFromAssistantContent(response.choice);\n await this.commitCompletedMemoryRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n yield {\n type: \"final\",\n output,\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n };\n await runObservers.end({ output, usage, messages: [...newMessages] });\n return;\n }\n\n const toolResultEvents = createAsyncQueue<ToolResultEventPayload>();\n const toolResultsPromise = this.executeToolCalls(\n toolCalls,\n newMessages,\n (result) => {\n toolResultEvents.enqueue(result);\n },\n {\n turn: currentTurns,\n runObservers,\n },\n );\n toolResultsPromise.then(\n () => toolResultEvents.close(),\n (error: unknown) => toolResultEvents.throw(error),\n );\n for await (const result of toolResultEvents) {\n yield { type: \"tool_result\", turn: currentTurns, ...result };\n }\n const toolResults = await toolResultsPromise;\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);\n await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n await runObservers.error({ error, usage, messages: [...newMessages] });\n await this.recordMemoryError(runId, error, newMessages);\n yield { type: \"error\", error };\n throw error;\n }\n }\n\n readableStream(): ReadableStream<Uint8Array> {\n return toReadableStream(this.stream());\n }\n\n private async runCompletion(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n const generationObservers = await runObservers.startGeneration({ turn, request });\n try {\n const response = await this.agent.model.completion(request);\n await generationObservers.end({ turn, response });\n return response;\n } catch (error) {\n await generationObservers.error({ turn, error });\n throw error;\n }\n }\n\n private async executeToolCalls(\n toolCalls: ToolCall[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n observation?: {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n },\n ): Promise<ToolResult[]> {\n return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {\n const args = JSON.stringify(toolCall.function.arguments ?? {});\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.function.name,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.toolCallId = toolCall.callId;\n }\n\n const toolObservers = await observation?.runObservers.startTool({\n turn: observation.turn,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n toolCallId: toolCall.callId,\n });\n\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n await this.recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n args,\n callAction.reason,\n );\n throw this.cancelled(newMessages, callAction.reason);\n }\n\n let output: string;\n let skipped = false;\n if (callAction?.type === \"skip\") {\n output = callAction.reason;\n skipped = true;\n } else {\n try {\n output = await this.agent.callTool(toolCall.function.name, args);\n } catch (error) {\n output = error instanceof Error ? error.toString() : String(error);\n }\n }\n\n if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {\n output = await this.runToolResultMiddlewares({\n ...hookArgs,\n result: output,\n originalResult: output,\n turn: observation?.turn ?? 0,\n });\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n result: output,\n run: runControl,\n });\n await toolObservers?.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n result: output,\n skipped,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancelled(newMessages, resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n toolName: toolCall.function.name,\n internalCallId,\n args,\n result: output,\n };\n if (toolCall.callId !== undefined) {\n resultPayload.toolCallId = toolCall.callId;\n }\n onResult?.(resultPayload);\n return ToolContent.toolResult(toolCall.id, output, toolCall.callId);\n });\n }\n\n private async runToolResultMiddlewares(args: ToolResultMiddlewareArgs): Promise<string> {\n let result = args.result;\n for (const middleware of [...this.agent.toolMiddlewares, ...this.requestToolMiddlewares]) {\n const replacement = await middleware.onResult?.({\n ...args,\n result,\n });\n if (replacement !== undefined) {\n result = replacement;\n }\n }\n return result;\n }\n\n private async startRunObservers(): Promise<ActiveAgentRunObservers> {\n const failOnObserverError =\n this.traceOptions?.failOnObserverError === true ||\n this.agent.observers.some((registration) => registration.failOnObserverError === true);\n return startAgentRunObservers(\n this.agent.observers,\n {\n agentName: this.agent.name,\n agentDescription: this.agent.description,\n instructions: this.agent.instructions,\n trace: this.traceOptions,\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n },\n failOnObserverError,\n );\n }\n\n private async fetchDynamicContext(ragText: string | undefined): Promise<Document[]> {\n if (ragText === undefined || ragText.length === 0 || this.agent.dynamicContexts.length === 0) {\n return [];\n }\n\n const documents: Document[] = [];\n for (const registration of this.agent.dynamicContexts) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n const formatted = registration.options.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n } else {\n const metadata = formatMetadata(result.metadata);\n documents.push({\n id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n ...(metadata === undefined ? {} : { additionalProps: metadata }),\n });\n }\n }\n }\n return documents;\n }\n\n private async fetchToolDefinitions(ragText: string | undefined): Promise<ToolDefinition[]> {\n const staticDefinitions = await this.agent.toolSet.getToolDefinitions(ragText);\n if (ragText === undefined || ragText.length === 0 || this.agent.dynamicTools.length === 0) {\n return staticDefinitions;\n }\n\n const definitions = [...staticDefinitions];\n const names = new Set(staticDefinitions.map((definition) => definition.name));\n for (const registration of this.agent.dynamicTools) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n if (names.has(result.document.toolName)) {\n continue;\n }\n names.add(result.document.toolName);\n definitions.push(result.document.definition);\n }\n }\n return definitions;\n }\n\n private async recordToolError(\n toolObservers: ActiveToolObservers | undefined,\n turn: number | undefined,\n toolCall: ToolCall,\n internalCallId: string,\n args: string,\n error: unknown,\n ): Promise<void> {\n await toolObservers?.error({\n turn: turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n error,\n toolCallId: toolCall.callId,\n });\n }\n\n private async runCompletionCallHook(\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionCall?.({\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionResponseHook(\n prompt: MessageType,\n response:\n | Awaited<ReturnType<M[\"completion\"]>>\n | Awaited<ReturnType<CompletionModel[\"completion\"]>>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionResponse?.({\n prompt,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private cancelled(newMessages: MessageType[], reason: string): PromptCancelledError {\n return new PromptCancelledError([...this.chatHistory, ...newMessages], reason);\n }\n\n private memory(): MemoryRegistration | undefined {\n return this.memoryContext === undefined ? undefined : this.agent.memory;\n }\n\n private memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.options.savePolicy;\n }\n\n private async prepareMemoryRun(runId: string, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n this.chatHistory = this.initialHistory;\n return;\n }\n\n const memoryHistory = await memory.store.load(this.memoryContext);\n this.chatHistory = [...memoryHistory, ...this.initialHistory];\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn: 1,\n messages: newMessages,\n });\n }\n }\n\n private async commitMemoryMessages(\n runId: string,\n turn: number,\n messages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined || messages.length === 0) {\n return;\n }\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages,\n });\n } else if (memory.options.savePolicy === \"turn\") {\n pendingTurnMessages.push(...messages);\n }\n }\n\n private async commitCompletedMemoryTurn(\n runId: string,\n turn: number,\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...pendingTurnMessages],\n });\n pendingTurnMessages.length = 0;\n }\n\n private async commitCompletedMemoryRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedMemoryTurn(runId, turn, pendingTurnMessages);\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"run\"\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...newMessages],\n });\n }\n\n private async recordMemoryError(\n runId: string,\n error: unknown,\n newMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return;\n }\n await memory.store.recordError?.({\n context: this.memoryContext,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n}\n\nfunction normalizePromptInput(prompt: string | MessageType | MessageType[]): {\n prompt: MessageType;\n history: MessageType[];\n} {\n if (typeof prompt === \"string\") {\n return { prompt: Message.user(prompt), history: [] };\n }\n if (!Array.isArray(prompt)) {\n return { prompt, history: [] };\n }\n if (prompt.length === 0) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n const activePrompt = prompt.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n return {\n prompt: activePrompt,\n history: prompt.slice(0, -1),\n };\n}\n\ntype ToolResultEventPayload = {\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n};\n\ntype AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nfunction createAsyncQueue<T>(): AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n} {\n const values: T[] = [];\n const waiters: AsyncQueueWaiter<T>[] = [];\n let closed = false;\n let error: unknown;\n\n function flush(): void {\n while (waiters.length > 0 && values.length > 0) {\n const waiter = waiters.shift();\n const value = values.shift() as T;\n if (waiter !== undefined) {\n waiter.resolve({ value, done: false });\n }\n }\n\n if (values.length > 0 || waiters.length === 0 || !closed) {\n return;\n }\n\n while (waiters.length > 0) {\n const waiter = waiters.shift();\n if (waiter === undefined) {\n continue;\n }\n if (error !== undefined) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined, done: true });\n }\n }\n }\n\n return {\n enqueue(value: T): void {\n if (closed) {\n return;\n }\n values.push(value);\n flush();\n },\n close(): void {\n closed = true;\n flush();\n },\n throw(thrown: unknown): void {\n closed = true;\n error = thrown;\n flush();\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (values.length > 0) {\n const value = values.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (error !== undefined) {\n return Promise.reject(error);\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n waiters.push({ resolve, reject });\n });\n },\n };\n },\n };\n}\n\nfunction addTurn(turn: number, event: AgentDeltaEvent): AgentStreamEvent {\n if (event.type === \"text_delta\") {\n return { type: \"text_delta\", turn, delta: event.delta };\n }\n if (event.type === \"reasoning_delta\") {\n const mapped: AgentStreamEvent = { type: \"reasoning_delta\", turn, delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n }\n return { type: \"tool_call\", turn, toolCall: event.toolCall };\n}\n\nfunction isGenerationDeltaEvent(type: string): boolean {\n return (\n type === \"text_delta\" ||\n type === \"reasoning_delta\" ||\n type === \"tool_call_delta\" ||\n type === \"tool_call\"\n );\n}\n\nfunction formatMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n if (metadata === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));\n}\n","import type { CompletionModel, Document, JsonObject, JsonValue, ToolChoice } from \"../completion\";\nimport type { McpServer } from \"../mcp\";\nimport {\n type MemoryOptions,\n type MemoryRegistration,\n type MemoryStore,\n resolveMemoryOptions,\n} from \"../memory\";\nimport type { AgentObserver, AgentObserverRegistration, ObserveOptions } from \"../observability\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { SkillSet } from \"../skills\";\nimport type { ToolSearchDocument } from \"../tool/dynamic-tools\";\nimport type { ToolMiddleware } from \"../tool/middleware\";\nimport type { AnyTool } from \"../tool/tool\";\nimport { ToolSet } from \"../tool/tool-set\";\nimport type { VectorSearchIndex } from \"../vector-store\";\nimport {\n Agent,\n type DynamicContextOptions,\n type DynamicContextRegistration,\n type DynamicToolOptions,\n type DynamicToolRegistration,\n} from \"./agent\";\nimport type { PromptHook } from \"./hooks\";\n\nexport class AgentBuilder<M extends CompletionModel = CompletionModel> {\n private readonly agentId: string;\n private agentName: string | undefined;\n private agentDescription: string | undefined;\n private instructionBlocks: string[] = [];\n private contextDocs: Document[] = [];\n private temp: number | undefined;\n private maxTokenCount: number | undefined;\n private params: JsonValue | undefined;\n private choice: ToolChoice | undefined;\n private turns: number | undefined;\n private requestHook: PromptHook | undefined;\n private schema: JsonObject | undefined;\n private skillInstructionBlocks: string[] = [];\n private observerRegistrations: AgentObserverRegistration[] = [];\n private dynamicContextRegistrations: DynamicContextRegistration[] = [];\n private dynamicToolRegistrations: DynamicToolRegistration[] = [];\n private middlewareRegistrations: ToolMiddleware[] = [];\n private memoryRegistration: MemoryRegistration | undefined;\n private activeToolSet = new ToolSet();\n\n constructor(\n agentId: string,\n private readonly completionModel: M,\n ) {\n this.agentId = normalizeAgentId(agentId);\n }\n\n name(name: string): this {\n this.agentName = name;\n return this;\n }\n\n description(description: string): this {\n this.agentDescription = description;\n return this;\n }\n\n instructions(instructions: string): this {\n if (instructions.length > 0) {\n this.instructionBlocks.push(instructions);\n }\n return this;\n }\n\n context(text: string, id = `static_doc_${this.contextDocs.length}`): this {\n this.contextDocs.push({ id, text });\n return this;\n }\n\n dynamicContext<T>(index: VectorSearchIndex<T>, options: DynamicContextOptions<T>): this {\n this.dynamicContextRegistrations.push({ index, options } as DynamicContextRegistration);\n return this;\n }\n\n dynamicTools(index: VectorSearchIndex<ToolSearchDocument>, options: DynamicToolOptions): this {\n this.dynamicToolRegistrations.push({ index, options });\n return this;\n }\n\n tool(tool: AnyTool): this {\n this.activeToolSet.addTool(tool);\n return this;\n }\n\n tools(tools: AnyTool[]): this {\n this.activeToolSet.addTools(tools);\n return this;\n }\n\n mcp(servers: McpServer[]): this {\n for (const server of servers) {\n this.activeToolSet.addTools(server.tools);\n }\n return this;\n }\n\n skills(skillSet: SkillSet): this {\n if (skillSet.instructions.length > 0) {\n this.skillInstructionBlocks.push(skillSet.instructions);\n }\n this.activeToolSet.addTools(skillSet.tools);\n return this;\n }\n\n useToolSet(toolSet: ToolSet): this {\n toolSet.addTools(this.activeToolSet);\n this.activeToolSet = toolSet;\n return this;\n }\n\n temperature(temperature: number): this {\n this.temp = temperature;\n return this;\n }\n\n maxTokens(maxTokens: number): this {\n this.maxTokenCount = maxTokens;\n return this;\n }\n\n additionalParams(params: JsonValue): this {\n this.params = params;\n return this;\n }\n\n toolChoice(toolChoice: ToolChoice): this {\n this.choice = toolChoice;\n return this;\n }\n\n defaultMaxTurns(defaultMaxTurns: number): this {\n this.turns = defaultMaxTurns;\n return this;\n }\n\n hook(hook: PromptHook): this {\n this.requestHook = hook;\n return this;\n }\n\n toolMiddleware(middleware: ToolMiddleware): this {\n this.middlewareRegistrations.push(middleware);\n return this;\n }\n\n toolMiddlewares(middlewares: ToolMiddleware[]): this {\n this.middlewareRegistrations.push(...middlewares);\n return this;\n }\n\n observe(observer: AgentObserver, options: ObserveOptions = {}): this {\n this.observerRegistrations.push({\n observer,\n failOnObserverError: options.failOnObserverError,\n });\n return this;\n }\n\n memory(store: MemoryStore, options: MemoryOptions = {}): this {\n this.memoryRegistration = {\n store,\n options: resolveMemoryOptions(options),\n };\n return this;\n }\n\n outputSchema(schema: ZodSchema): this {\n this.schema = toProviderJsonSchema(schema);\n return this;\n }\n\n build(): Agent<M> {\n return new Agent({\n id: this.agentId,\n name: this.agentName,\n description: this.agentDescription,\n model: this.completionModel,\n instructions: this.buildInstructions(),\n staticContext: this.contextDocs,\n temperature: this.temp,\n maxTokens: this.maxTokenCount,\n additionalParams: this.params,\n toolSet: this.activeToolSet,\n toolChoice: this.choice,\n defaultMaxTurns: this.turns,\n hook: this.requestHook,\n outputSchema: this.schema,\n observers: this.observerRegistrations,\n dynamicContexts: this.dynamicContextRegistrations,\n dynamicTools: this.dynamicToolRegistrations,\n toolMiddlewares: this.middlewareRegistrations,\n memory: this.memoryRegistration,\n });\n }\n\n private buildInstructions(): string | undefined {\n const parts = [...this.instructionBlocks, ...this.skillInstructionBlocks].filter(\n (part): part is string => part !== undefined && part.length > 0,\n );\n return parts.length === 0 ? undefined : parts.join(\"\\n\\n\");\n }\n}\n\nfunction normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACiBlB,eAAsB,uBACpB,eACA,MACA,qBACkC;AAClC,QAAM,eAAmC,CAAC;AAC1C,aAAW,gBAAgB,eAAe;AACxC,QAAI;AACF,YAAM,cAAc,MAAM,aAAa,SAAS,SAAS,IAAI;AAC7D,UAAI,gBAAgB,QAAW;AAC7B,qBAAa,KAAK,WAAW;AAAA,MAC/B;AAAA,IACF,SAAS,OAAO;AACd,UAAI,uBAAuB,aAAa,wBAAwB,MAAM;AACpE,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,IAAI,wBAAwB,cAAc,mBAAmB;AACtE;AAEO,IAAM,0BAAN,MAA8B;AAAA,EAGnC,YACmB,cACA,qBACjB;AAFiB;AACA;AAEjB,SA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AAM,KAAK;AAAA,MACX,aAAa,KAAK;AAAA,MAClB,OAAO,KAAK;AAAA,MACZ,cAAc,KAAK,kBAAkB;AAAA,MACrC,eAAe,KAAK;AAAA,MACpB,aAAa,KAAK;AAAA,MAClB,WAAW,KAAK;AAAA,MAChB,kBAAkB,KAAK;AAAA,MACvB,SAAS,KAAK;AAAA,MACd,YAAY,KAAK;AAAA,MACjB,iBAAiB,KAAK;AAAA,MACtB,MAAM,KAAK;AAAA,MACX,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,iBAAiB,KAAK;AAAA,MACtB,cAAc,KAAK;AAAA,MACnB,iBAAiB,KAAK;AAAA,MACtB,QAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEQ,oBAAwC;AAC9C,UAAM,QAAQ,CAAC,GAAG,KAAK,mBAAmB,GAAG,KAAK,sBAAsB,EAAE;AAAA,MACxE,CAAC,SAAyB,SAAS,UAAa,KAAK,SAAS;AAAA,IAChE;AACA,WAAO,MAAM,WAAW,IAAI,SAAY,MAAM,KAAK,MAAM;AAAA,EAC3D;AACF;AAEA,SAASA,kBAAiB,IAAoB;AAC5C,MAAI,OAAO,OAAO,UAAU;AAC1B,UAAM,IAAI,UAAU,4BAA4B;AAAA,EAClD;AAEA,QAAM,aAAa,GAAG,KAAK;AAC3B,MAAI,WAAW,WAAW,GAAG;AAC3B,UAAM,IAAI,UAAU,sCAAsC;AAAA,EAC5D;AAEA,SAAO;AACT;","names":["normalizeAgentId"]}
|
|
@@ -71,6 +71,11 @@ function defaultToolEmbeddingText(definition) {
|
|
|
71
71
|
return [definition.name, definition.description, JSON.stringify(definition.parameters)];
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
// src/tool/middleware.ts
|
|
75
|
+
function createToolMiddleware(middleware) {
|
|
76
|
+
return middleware;
|
|
77
|
+
}
|
|
78
|
+
|
|
74
79
|
// src/tool/think-tool.ts
|
|
75
80
|
import { z } from "zod";
|
|
76
81
|
var defaultThinkToolDescription = "Use this tool to record a thought while reasoning through a complex task. It does not retrieve information, store memory, or change external state.";
|
|
@@ -91,6 +96,7 @@ export {
|
|
|
91
96
|
embedTools,
|
|
92
97
|
createToolIndex,
|
|
93
98
|
isDynamicToolIndex,
|
|
99
|
+
createToolMiddleware,
|
|
94
100
|
createThinkTool
|
|
95
101
|
};
|
|
96
|
-
//# sourceMappingURL=chunk-
|
|
102
|
+
//# sourceMappingURL=chunk-J23SIK6Y.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tool/dynamic-tools.ts","../src/tool/middleware.ts","../src/tool/think-tool.ts"],"sourcesContent":["import type { ToolDefinition } from \"../completion\";\nimport type { EmbeddedDocument, EmbeddingModel, VectorMetadata } from \"../embeddings\";\nimport { embedDocuments } from \"../embeddings\";\nimport type { VectorSearchResult, VectorSearchToolOptions } from \"../vector-store\";\nimport {\n InMemoryVectorStore,\n type VectorSearchIndex,\n type VectorSearchRequest,\n} from \"../vector-store\";\nimport type { AnyTool, Tool } from \"./tool\";\nimport { ToolSet } from \"./tool-set\";\n\nexport type ToolSearchDocument<Metadata extends VectorMetadata = VectorMetadata> = {\n toolName: string;\n definition: ToolDefinition;\n text: string;\n metadata?: Metadata | undefined;\n};\n\nexport type EmbedToolsOptions<Metadata extends VectorMetadata = VectorMetadata> = {\n content?: ((tool: AnyTool, definition: ToolDefinition) => string | string[]) | undefined;\n metadata?: ((tool: AnyTool, definition: ToolDefinition) => Metadata | undefined) | undefined;\n concurrency?: number | undefined;\n};\n\nexport interface DynamicToolIndex<Metadata extends VectorMetadata = VectorMetadata>\n extends VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata> {\n readonly toolSet: ToolSet;\n}\n\nexport async function embedTools<Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n tools: AnyTool[] | ToolSet,\n options: EmbedToolsOptions<Metadata> = {},\n): Promise<Array<EmbeddedDocument<ToolSearchDocument<Metadata>, Metadata>>> {\n const toolList = Array.isArray(tools) ? tools : tools.values();\n const definitions = await Promise.all(\n toolList.map(async (tool) => ({ tool, definition: await tool.definition(\"\") })),\n );\n const documents = definitions.map(({ tool, definition }) => {\n const content = options.content?.(tool, definition) ?? defaultToolEmbeddingText(definition);\n const texts = Array.isArray(content) ? content : [content];\n const metadata = options.metadata?.(tool, definition);\n const document: ToolSearchDocument<Metadata> = {\n toolName: tool.name,\n definition,\n text: texts.join(\"\\n\"),\n ...(metadata === undefined ? {} : { metadata }),\n };\n return { tool, document, texts, metadata };\n });\n\n return embedDocuments(model, documents, {\n id: (item) => item.tool.name,\n content: (item) => item.texts,\n metadata: (item) => item.metadata,\n concurrency: options.concurrency,\n }).then((embedded) =>\n embedded.map((item) => ({\n ...item,\n document: item.document.document,\n })),\n );\n}\n\nexport async function createToolIndex<Metadata extends VectorMetadata = VectorMetadata>(\n model: EmbeddingModel,\n tools: AnyTool[] | ToolSet,\n options: EmbedToolsOptions<Metadata> = {},\n): Promise<DynamicToolIndex<Metadata>> {\n const toolSet = Array.isArray(tools) ? ToolSet.fromTools(tools) : tools;\n const embedded = await embedTools(model, toolSet, options);\n const index = InMemoryVectorStore.fromDocuments(embedded).index(model);\n return new DynamicToolSearchIndex(index, toolSet);\n}\n\nexport function isDynamicToolIndex(value: unknown): value is DynamicToolIndex {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"toolSet\" in value &&\n (value as { toolSet?: unknown }).toolSet instanceof ToolSet\n );\n}\n\nclass DynamicToolSearchIndex<Metadata extends VectorMetadata>\n implements DynamicToolIndex<Metadata>\n{\n constructor(\n private readonly index: VectorSearchIndex<ToolSearchDocument<Metadata>, Metadata>,\n readonly toolSet: ToolSet,\n ) {}\n\n search(\n request: VectorSearchRequest,\n ): Promise<Array<VectorSearchResult<ToolSearchDocument<Metadata>, Metadata>>> {\n return this.index.search(request);\n }\n\n searchIds(request: VectorSearchRequest): Promise<Array<{ score: number; id: string }>> {\n return this.index.searchIds(request);\n }\n\n asTool(options: VectorSearchToolOptions): Tool<{ query: string; topK?: number }, unknown> {\n return this.index.asTool(options);\n }\n}\n\nfunction defaultToolEmbeddingText(definition: ToolDefinition): string[] {\n return [definition.name, definition.description, JSON.stringify(definition.parameters)];\n}\n","export type ToolResultMiddlewareArgs = {\n toolName: string;\n args: string;\n result: string;\n originalResult: string;\n turn: number;\n toolCallId?: string | undefined;\n internalCallId: string;\n};\n\nexport interface ToolMiddleware {\n onResult?(args: ToolResultMiddlewareArgs): string | undefined | Promise<string | undefined>;\n}\n\nexport function createToolMiddleware(middleware: ToolMiddleware): ToolMiddleware {\n return middleware;\n}\n","import { z } from \"zod\";\nimport { createTool } from \"./create-tool\";\n\nconst defaultThinkToolDescription =\n \"Use this tool to record a thought while reasoning through a complex task. It does not retrieve information, store memory, or change external state.\";\n\nconst thinkToolInput = z.object({\n thought: z.string().describe(\"A thought to record while reasoning through a task.\"),\n});\n\nexport type CreateThinkToolOptions = {\n name?: string;\n description?: string;\n};\n\nexport function createThinkTool(options: CreateThinkToolOptions = {}) {\n return createTool({\n name: options.name ?? \"think\",\n description: options.description ?? defaultThinkToolDescription,\n input: thinkToolInput,\n output: z.string(),\n execute: (args) => args.thought,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,eAAsB,WACpB,OACA,OACA,UAAuC,CAAC,GACkC;AAC1E,QAAM,WAAW,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM,OAAO;AAC7D,QAAM,cAAc,MAAM,QAAQ;AAAA,IAChC,SAAS,IAAI,OAAO,UAAU,EAAE,MAAM,YAAY,MAAM,KAAK,WAAW,EAAE,EAAE,EAAE;AAAA,EAChF;AACA,QAAM,YAAY,YAAY,IAAI,CAAC,EAAE,MAAM,WAAW,MAAM;AAC1D,UAAM,UAAU,QAAQ,UAAU,MAAM,UAAU,KAAK,yBAAyB,UAAU;AAC1F,UAAM,QAAQ,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO;AACzD,UAAM,WAAW,QAAQ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OAAO;AAAA,EAClC;AACF;AAEA,SAAS,yBAAyB,YAAsC;AACtE,SAAO,CAAC,WAAW,MAAM,WAAW,aAAa,KAAK,UAAU,WAAW,UAAU,CAAC;AACxF;;;AChGO,SAAS,qBAAqB,YAA4C;AAC/E,SAAO;AACT;;;AChBA,SAAS,SAAS;AAGlB,IAAM,8BACJ;AAEF,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,SAAS,EAAE,OAAO,EAAE,SAAS,qDAAqD;AACpF,CAAC;AAOM,SAAS,gBAAgB,UAAkC,CAAC,GAAG;AACpE,SAAO,WAAW;AAAA,IAChB,MAAM,QAAQ,QAAQ;AAAA,IACtB,aAAa,QAAQ,eAAe;AAAA,IACpC,OAAO;AAAA,IACP,QAAQ,EAAE,OAAO;AAAA,IACjB,SAAS,CAAC,SAAS,KAAK;AAAA,EAC1B,CAAC;AACH;","names":[]}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
markSkillTool
|
|
3
|
+
} from "./chunk-YK4WAAS4.js";
|
|
1
4
|
import {
|
|
2
5
|
createTool
|
|
3
6
|
} from "./chunk-B4QHQN5K.js";
|
|
@@ -42,47 +45,55 @@ var MAX_OUTPUT_CHARS = 2e4;
|
|
|
42
45
|
function createSkillTools(skills) {
|
|
43
46
|
const registry = new SkillRegistry(skills);
|
|
44
47
|
return [
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
48
|
+
markSkillTool(
|
|
49
|
+
createTool({
|
|
50
|
+
name: "get_skill_instructions",
|
|
51
|
+
description: "Load the full SKILL.md instructions for an Agent Skill.",
|
|
52
|
+
input: z.object({
|
|
53
|
+
skillName: z.string().describe("The name of the skill to load.")
|
|
54
|
+
}),
|
|
55
|
+
output: z.string(),
|
|
56
|
+
execute: ({ skillName }) => registry.get(skillName).instructions
|
|
57
|
+
})
|
|
58
|
+
),
|
|
59
|
+
markSkillTool(
|
|
60
|
+
createTool({
|
|
61
|
+
name: "get_skill_reference",
|
|
62
|
+
description: "Read a reference file from an Agent Skill.",
|
|
63
|
+
input: z.object({
|
|
64
|
+
skillName: z.string().describe("The name of the skill."),
|
|
65
|
+
referencePath: z.string().describe("A path listed in the skill references.")
|
|
66
|
+
}),
|
|
67
|
+
output: z.string(),
|
|
68
|
+
execute: ({ skillName, referencePath }) => registry.readReference(skillName, referencePath)
|
|
69
|
+
})
|
|
70
|
+
),
|
|
71
|
+
markSkillTool(
|
|
72
|
+
createTool({
|
|
73
|
+
name: "get_skill_script",
|
|
74
|
+
description: "Read a script file from an Agent Skill.",
|
|
75
|
+
input: z.object({
|
|
76
|
+
skillName: z.string().describe("The name of the skill."),
|
|
77
|
+
scriptPath: z.string().describe("A path listed in the skill scripts.")
|
|
78
|
+
}),
|
|
79
|
+
output: z.string(),
|
|
80
|
+
execute: ({ skillName, scriptPath }) => registry.readScript(skillName, scriptPath)
|
|
81
|
+
})
|
|
82
|
+
),
|
|
83
|
+
markSkillTool(
|
|
84
|
+
createTool({
|
|
85
|
+
name: "run_skill_script",
|
|
86
|
+
description: "Execute a script from an Agent Skill with optional arguments.",
|
|
87
|
+
input: z.object({
|
|
88
|
+
skillName: z.string().describe("The name of the skill."),
|
|
89
|
+
scriptPath: z.string().describe("A path listed in the skill scripts."),
|
|
90
|
+
args: z.array(z.string()).optional().describe("Arguments passed to the script."),
|
|
91
|
+
timeoutMs: z.number().int().positive().optional().describe("Execution timeout in ms.")
|
|
92
|
+
}),
|
|
93
|
+
output: z.string(),
|
|
94
|
+
execute: ({ skillName, scriptPath, args = [], timeoutMs = DEFAULT_TIMEOUT_MS }) => registry.runScript(skillName, scriptPath, args, timeoutMs)
|
|
95
|
+
})
|
|
96
|
+
)
|
|
86
97
|
];
|
|
87
98
|
}
|
|
88
99
|
var SkillRegistry = class {
|
|
@@ -384,4 +395,4 @@ export {
|
|
|
384
395
|
SkillValidationError,
|
|
385
396
|
skill
|
|
386
397
|
};
|
|
387
|
-
//# sourceMappingURL=chunk-
|
|
398
|
+
//# sourceMappingURL=chunk-JDPPZCOY.js.map
|