@lleverage-ai/agent-sdk 0.0.1
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/LICENSE +21 -0
- package/README.md +2321 -0
- package/dist/agent.d.ts +52 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +2122 -0
- package/dist/agent.js.map +1 -0
- package/dist/backend.d.ts +378 -0
- package/dist/backend.d.ts.map +1 -0
- package/dist/backend.js +71 -0
- package/dist/backend.js.map +1 -0
- package/dist/backends/composite.d.ts +258 -0
- package/dist/backends/composite.d.ts.map +1 -0
- package/dist/backends/composite.js +437 -0
- package/dist/backends/composite.js.map +1 -0
- package/dist/backends/filesystem.d.ts +268 -0
- package/dist/backends/filesystem.d.ts.map +1 -0
- package/dist/backends/filesystem.js +623 -0
- package/dist/backends/filesystem.js.map +1 -0
- package/dist/backends/index.d.ts +14 -0
- package/dist/backends/index.d.ts.map +1 -0
- package/dist/backends/index.js +14 -0
- package/dist/backends/index.js.map +1 -0
- package/dist/backends/persistent.d.ts +312 -0
- package/dist/backends/persistent.d.ts.map +1 -0
- package/dist/backends/persistent.js +519 -0
- package/dist/backends/persistent.js.map +1 -0
- package/dist/backends/sandbox.d.ts +315 -0
- package/dist/backends/sandbox.d.ts.map +1 -0
- package/dist/backends/sandbox.js +490 -0
- package/dist/backends/sandbox.js.map +1 -0
- package/dist/backends/state.d.ts +225 -0
- package/dist/backends/state.d.ts.map +1 -0
- package/dist/backends/state.js +396 -0
- package/dist/backends/state.js.map +1 -0
- package/dist/checkpointer/file-saver.d.ts +182 -0
- package/dist/checkpointer/file-saver.d.ts.map +1 -0
- package/dist/checkpointer/file-saver.js +298 -0
- package/dist/checkpointer/file-saver.js.map +1 -0
- package/dist/checkpointer/index.d.ts +40 -0
- package/dist/checkpointer/index.d.ts.map +1 -0
- package/dist/checkpointer/index.js +40 -0
- package/dist/checkpointer/index.js.map +1 -0
- package/dist/checkpointer/kv-saver.d.ts +142 -0
- package/dist/checkpointer/kv-saver.d.ts.map +1 -0
- package/dist/checkpointer/kv-saver.js +176 -0
- package/dist/checkpointer/kv-saver.js.map +1 -0
- package/dist/checkpointer/memory-saver.d.ts +158 -0
- package/dist/checkpointer/memory-saver.d.ts.map +1 -0
- package/dist/checkpointer/memory-saver.js +222 -0
- package/dist/checkpointer/memory-saver.js.map +1 -0
- package/dist/checkpointer/types.d.ts +353 -0
- package/dist/checkpointer/types.d.ts.map +1 -0
- package/dist/checkpointer/types.js +159 -0
- package/dist/checkpointer/types.js.map +1 -0
- package/dist/context-manager.d.ts +627 -0
- package/dist/context-manager.d.ts.map +1 -0
- package/dist/context-manager.js +1039 -0
- package/dist/context-manager.js.map +1 -0
- package/dist/context.d.ts +57 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +76 -0
- package/dist/context.js.map +1 -0
- package/dist/errors/index.d.ts +611 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +1023 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/generation-helpers.d.ts +126 -0
- package/dist/generation-helpers.d.ts.map +1 -0
- package/dist/generation-helpers.js +181 -0
- package/dist/generation-helpers.js.map +1 -0
- package/dist/hooks/audit.d.ts +210 -0
- package/dist/hooks/audit.d.ts.map +1 -0
- package/dist/hooks/audit.js +305 -0
- package/dist/hooks/audit.js.map +1 -0
- package/dist/hooks/cache.d.ts +180 -0
- package/dist/hooks/cache.d.ts.map +1 -0
- package/dist/hooks/cache.js +273 -0
- package/dist/hooks/cache.js.map +1 -0
- package/dist/hooks/guardrails.d.ts +145 -0
- package/dist/hooks/guardrails.d.ts.map +1 -0
- package/dist/hooks/guardrails.js +326 -0
- package/dist/hooks/guardrails.js.map +1 -0
- package/dist/hooks/index.d.ts +18 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +32 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/logging.d.ts +193 -0
- package/dist/hooks/logging.d.ts.map +1 -0
- package/dist/hooks/logging.js +345 -0
- package/dist/hooks/logging.js.map +1 -0
- package/dist/hooks/parallel-guardrails.d.ts +268 -0
- package/dist/hooks/parallel-guardrails.d.ts.map +1 -0
- package/dist/hooks/parallel-guardrails.js +416 -0
- package/dist/hooks/parallel-guardrails.js.map +1 -0
- package/dist/hooks/rate-limit.d.ts +305 -0
- package/dist/hooks/rate-limit.d.ts.map +1 -0
- package/dist/hooks/rate-limit.js +372 -0
- package/dist/hooks/rate-limit.js.map +1 -0
- package/dist/hooks/retry.d.ts +144 -0
- package/dist/hooks/retry.d.ts.map +1 -0
- package/dist/hooks/retry.js +210 -0
- package/dist/hooks/retry.js.map +1 -0
- package/dist/hooks/secrets.d.ts +174 -0
- package/dist/hooks/secrets.d.ts.map +1 -0
- package/dist/hooks/secrets.js +306 -0
- package/dist/hooks/secrets.js.map +1 -0
- package/dist/hooks.d.ts +229 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +352 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +182 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/env.d.ts +25 -0
- package/dist/mcp/env.d.ts.map +1 -0
- package/dist/mcp/env.js +18 -0
- package/dist/mcp/env.js.map +1 -0
- package/dist/mcp/index.d.ts +16 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +17 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +184 -0
- package/dist/mcp/manager.d.ts.map +1 -0
- package/dist/mcp/manager.js +446 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/types.d.ts +58 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +7 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/mcp/validation.d.ts +119 -0
- package/dist/mcp/validation.d.ts.map +1 -0
- package/dist/mcp/validation.js +407 -0
- package/dist/mcp/validation.js.map +1 -0
- package/dist/mcp/virtual-server.d.ts +78 -0
- package/dist/mcp/virtual-server.d.ts.map +1 -0
- package/dist/mcp/virtual-server.js +137 -0
- package/dist/mcp/virtual-server.js.map +1 -0
- package/dist/memory/filesystem-store.d.ts +217 -0
- package/dist/memory/filesystem-store.d.ts.map +1 -0
- package/dist/memory/filesystem-store.js +343 -0
- package/dist/memory/filesystem-store.js.map +1 -0
- package/dist/memory/index.d.ts +46 -0
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/index.js +46 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/memory/loader.d.ts +396 -0
- package/dist/memory/loader.d.ts.map +1 -0
- package/dist/memory/loader.js +419 -0
- package/dist/memory/loader.js.map +1 -0
- package/dist/memory/permissions.d.ts +282 -0
- package/dist/memory/permissions.d.ts.map +1 -0
- package/dist/memory/permissions.js +297 -0
- package/dist/memory/permissions.js.map +1 -0
- package/dist/memory/rules.d.ts +249 -0
- package/dist/memory/rules.d.ts.map +1 -0
- package/dist/memory/rules.js +362 -0
- package/dist/memory/rules.js.map +1 -0
- package/dist/memory/store.d.ts +286 -0
- package/dist/memory/store.d.ts.map +1 -0
- package/dist/memory/store.js +263 -0
- package/dist/memory/store.js.map +1 -0
- package/dist/middleware/apply.d.ts +73 -0
- package/dist/middleware/apply.d.ts.map +1 -0
- package/dist/middleware/apply.js +219 -0
- package/dist/middleware/apply.js.map +1 -0
- package/dist/middleware/context.d.ts +33 -0
- package/dist/middleware/context.d.ts.map +1 -0
- package/dist/middleware/context.js +176 -0
- package/dist/middleware/context.js.map +1 -0
- package/dist/middleware/index.d.ts +31 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +32 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/logging.d.ts +137 -0
- package/dist/middleware/logging.d.ts.map +1 -0
- package/dist/middleware/logging.js +374 -0
- package/dist/middleware/logging.js.map +1 -0
- package/dist/middleware/types.d.ts +183 -0
- package/dist/middleware/types.d.ts.map +1 -0
- package/dist/middleware/types.js +11 -0
- package/dist/middleware/types.js.map +1 -0
- package/dist/observability/events.d.ts +183 -0
- package/dist/observability/events.d.ts.map +1 -0
- package/dist/observability/events.js +305 -0
- package/dist/observability/events.js.map +1 -0
- package/dist/observability/index.d.ts +55 -0
- package/dist/observability/index.d.ts.map +1 -0
- package/dist/observability/index.js +87 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/observability/logger.d.ts +318 -0
- package/dist/observability/logger.d.ts.map +1 -0
- package/dist/observability/logger.js +436 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/metrics.d.ts +341 -0
- package/dist/observability/metrics.d.ts.map +1 -0
- package/dist/observability/metrics.js +490 -0
- package/dist/observability/metrics.js.map +1 -0
- package/dist/observability/preset.d.ts +161 -0
- package/dist/observability/preset.d.ts.map +1 -0
- package/dist/observability/preset.js +133 -0
- package/dist/observability/preset.js.map +1 -0
- package/dist/observability/streaming.d.ts +113 -0
- package/dist/observability/streaming.d.ts.map +1 -0
- package/dist/observability/streaming.js +114 -0
- package/dist/observability/streaming.js.map +1 -0
- package/dist/observability/tracing.d.ts +378 -0
- package/dist/observability/tracing.d.ts.map +1 -0
- package/dist/observability/tracing.js +539 -0
- package/dist/observability/tracing.js.map +1 -0
- package/dist/plugins.d.ts +55 -0
- package/dist/plugins.d.ts.map +1 -0
- package/dist/plugins.js +63 -0
- package/dist/plugins.js.map +1 -0
- package/dist/presets/index.d.ts +7 -0
- package/dist/presets/index.d.ts.map +1 -0
- package/dist/presets/index.js +7 -0
- package/dist/presets/index.js.map +1 -0
- package/dist/presets/production.d.ts +262 -0
- package/dist/presets/production.d.ts.map +1 -0
- package/dist/presets/production.js +295 -0
- package/dist/presets/production.js.map +1 -0
- package/dist/security/index.d.ts +179 -0
- package/dist/security/index.d.ts.map +1 -0
- package/dist/security/index.js +323 -0
- package/dist/security/index.js.map +1 -0
- package/dist/subagents/advanced.d.ts +413 -0
- package/dist/subagents/advanced.d.ts.map +1 -0
- package/dist/subagents/advanced.js +396 -0
- package/dist/subagents/advanced.js.map +1 -0
- package/dist/subagents/index.d.ts +14 -0
- package/dist/subagents/index.d.ts.map +1 -0
- package/dist/subagents/index.js +15 -0
- package/dist/subagents/index.js.map +1 -0
- package/dist/subagents.d.ts +73 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +213 -0
- package/dist/subagents.js.map +1 -0
- package/dist/task-store/file-store.d.ts +76 -0
- package/dist/task-store/file-store.d.ts.map +1 -0
- package/dist/task-store/file-store.js +190 -0
- package/dist/task-store/file-store.js.map +1 -0
- package/dist/task-store/index.d.ts +11 -0
- package/dist/task-store/index.d.ts.map +1 -0
- package/dist/task-store/index.js +10 -0
- package/dist/task-store/index.js.map +1 -0
- package/dist/task-store/kv-store.d.ts +140 -0
- package/dist/task-store/kv-store.d.ts.map +1 -0
- package/dist/task-store/kv-store.js +169 -0
- package/dist/task-store/kv-store.js.map +1 -0
- package/dist/task-store/memory-store.d.ts +66 -0
- package/dist/task-store/memory-store.d.ts.map +1 -0
- package/dist/task-store/memory-store.js +125 -0
- package/dist/task-store/memory-store.js.map +1 -0
- package/dist/task-store/types.d.ts +235 -0
- package/dist/task-store/types.d.ts.map +1 -0
- package/dist/task-store/types.js +110 -0
- package/dist/task-store/types.js.map +1 -0
- package/dist/testing/assertions.d.ts +401 -0
- package/dist/testing/assertions.d.ts.map +1 -0
- package/dist/testing/assertions.js +630 -0
- package/dist/testing/assertions.js.map +1 -0
- package/dist/testing/index.d.ts +343 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +360 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mock-agent.d.ts +214 -0
- package/dist/testing/mock-agent.d.ts.map +1 -0
- package/dist/testing/mock-agent.js +448 -0
- package/dist/testing/mock-agent.js.map +1 -0
- package/dist/testing/recorder.d.ts +288 -0
- package/dist/testing/recorder.d.ts.map +1 -0
- package/dist/testing/recorder.js +499 -0
- package/dist/testing/recorder.js.map +1 -0
- package/dist/tools/execute.d.ts +104 -0
- package/dist/tools/execute.d.ts.map +1 -0
- package/dist/tools/execute.js +191 -0
- package/dist/tools/execute.js.map +1 -0
- package/dist/tools/factory.d.ts +260 -0
- package/dist/tools/factory.d.ts.map +1 -0
- package/dist/tools/factory.js +241 -0
- package/dist/tools/factory.js.map +1 -0
- package/dist/tools/filesystem.d.ts +215 -0
- package/dist/tools/filesystem.d.ts.map +1 -0
- package/dist/tools/filesystem.js +311 -0
- package/dist/tools/filesystem.js.map +1 -0
- package/dist/tools/index.d.ts +33 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +33 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/search.d.ts +59 -0
- package/dist/tools/search.d.ts.map +1 -0
- package/dist/tools/search.js +94 -0
- package/dist/tools/search.js.map +1 -0
- package/dist/tools/skills.d.ts +354 -0
- package/dist/tools/skills.d.ts.map +1 -0
- package/dist/tools/skills.js +413 -0
- package/dist/tools/skills.js.map +1 -0
- package/dist/tools/task.d.ts +272 -0
- package/dist/tools/task.d.ts.map +1 -0
- package/dist/tools/task.js +521 -0
- package/dist/tools/task.js.map +1 -0
- package/dist/tools/todos.d.ts +131 -0
- package/dist/tools/todos.d.ts.map +1 -0
- package/dist/tools/todos.js +120 -0
- package/dist/tools/todos.js.map +1 -0
- package/dist/tools/tool-registry.d.ts +424 -0
- package/dist/tools/tool-registry.d.ts.map +1 -0
- package/dist/tools/tool-registry.js +607 -0
- package/dist/tools/tool-registry.js.map +1 -0
- package/dist/tools/user-interaction.d.ts +116 -0
- package/dist/tools/user-interaction.d.ts.map +1 -0
- package/dist/tools/user-interaction.js +147 -0
- package/dist/tools/user-interaction.js.map +1 -0
- package/dist/tools/utils.d.ts +124 -0
- package/dist/tools/utils.d.ts.map +1 -0
- package/dist/tools/utils.js +189 -0
- package/dist/tools/utils.js.map +1 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +73 -0
- package/dist/tools.js.map +1 -0
- package/dist/types.d.ts +2421 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +55 -0
- package/dist/types.js.map +1 -0
- package/package.json +81 -0
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,2421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core type definitions for the agent SDK.
|
|
3
|
+
*
|
|
4
|
+
* This module re-exports AI SDK types where possible and defines
|
|
5
|
+
* agent-specific extensions for features like subagents, skills, and hooks.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import type { LanguageModel, LanguageModelUsage, ModelMessage, Output, streamText, Tool, ToolExecutionOptions, ToolSet, UIDataTypes, UIMessage, UIMessageStreamWriter } from "ai";
|
|
10
|
+
import type { BackendProtocol } from "./backend.js";
|
|
11
|
+
import type { AgentState } from "./backends/state.js";
|
|
12
|
+
import type { BaseCheckpointSaver, Interrupt } from "./checkpointer/types.js";
|
|
13
|
+
/**
|
|
14
|
+
* Re-export AI SDK message and tool types for convenience.
|
|
15
|
+
* Users can import these directly from this package instead of 'ai'.
|
|
16
|
+
*/
|
|
17
|
+
export type { ModelMessage, LanguageModel, LanguageModelUsage, Tool, ToolExecutionOptions, ToolSet, UIMessage, };
|
|
18
|
+
/**
|
|
19
|
+
* Function that tools can call to request an interrupt and wait for a response.
|
|
20
|
+
*
|
|
21
|
+
* When called, this function will either:
|
|
22
|
+
* - Return immediately with the response (if resuming from a previous interrupt)
|
|
23
|
+
* - Throw an InterruptSignal to pause execution (if first time)
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* const askUserTool = tool({
|
|
28
|
+
* description: "Ask the user a question",
|
|
29
|
+
* parameters: z.object({ question: z.string() }),
|
|
30
|
+
* execute: async ({ question }, options) => {
|
|
31
|
+
* // Get the interrupt function from extended options
|
|
32
|
+
* const { interrupt } = options as ExtendedToolExecutionOptions;
|
|
33
|
+
*
|
|
34
|
+
* // Request interrupt - will either return response or throw
|
|
35
|
+
* const { answer } = await interrupt<
|
|
36
|
+
* { question: string },
|
|
37
|
+
* { answer: string }
|
|
38
|
+
* >({ question });
|
|
39
|
+
*
|
|
40
|
+
* return { userSaid: answer };
|
|
41
|
+
* },
|
|
42
|
+
* });
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* @category Types
|
|
46
|
+
*/
|
|
47
|
+
/**
|
|
48
|
+
* Request an interrupt and wait for a response.
|
|
49
|
+
*
|
|
50
|
+
* @param request - Data to include in the interrupt (sent to the client)
|
|
51
|
+
* @param options - Optional configuration for the interrupt
|
|
52
|
+
* @returns Promise that resolves with the response when resumed
|
|
53
|
+
*/
|
|
54
|
+
export type InterruptFunction = <TRequest = unknown, TResponse = unknown>(request: TRequest, options?: {
|
|
55
|
+
/** Custom interrupt type (default: "custom") */
|
|
56
|
+
type?: string;
|
|
57
|
+
}) => Promise<TResponse>;
|
|
58
|
+
/**
|
|
59
|
+
* Extended tool execution options that include interrupt capability.
|
|
60
|
+
*
|
|
61
|
+
* This extends the AI SDK's ToolExecutionOptions to add the `interrupt`
|
|
62
|
+
* function for requesting user input during tool execution.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* execute: async (input, options) => {
|
|
67
|
+
* const { interrupt } = options as ExtendedToolExecutionOptions;
|
|
68
|
+
*
|
|
69
|
+
* if (needsConfirmation) {
|
|
70
|
+
* const { confirmed } = await interrupt<
|
|
71
|
+
* { message: string },
|
|
72
|
+
* { confirmed: boolean }
|
|
73
|
+
* >({ message: "Are you sure?" });
|
|
74
|
+
*
|
|
75
|
+
* if (!confirmed) {
|
|
76
|
+
* return { cancelled: true };
|
|
77
|
+
* }
|
|
78
|
+
* }
|
|
79
|
+
*
|
|
80
|
+
* return performAction(input);
|
|
81
|
+
* }
|
|
82
|
+
* ```
|
|
83
|
+
*
|
|
84
|
+
* @category Types
|
|
85
|
+
*/
|
|
86
|
+
export interface ExtendedToolExecutionOptions extends ToolExecutionOptions {
|
|
87
|
+
/**
|
|
88
|
+
* Function to request an interrupt during tool execution.
|
|
89
|
+
* Available when the agent has a checkpointer configured.
|
|
90
|
+
*/
|
|
91
|
+
interrupt: InterruptFunction;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Metadata identifying the source of streamed data.
|
|
95
|
+
*
|
|
96
|
+
* Used to identify which agent or subagent produced data in multi-agent
|
|
97
|
+
* streaming scenarios, similar to LangGraph's namespace pattern.
|
|
98
|
+
*
|
|
99
|
+
* @category Types
|
|
100
|
+
*/
|
|
101
|
+
export interface StreamingMetadata {
|
|
102
|
+
/** The type of agent (e.g., "ui-builder", "researcher") */
|
|
103
|
+
agentType: string;
|
|
104
|
+
/** Unique identifier for this agent instance */
|
|
105
|
+
agentId: string;
|
|
106
|
+
/** Parent agent ID if this is a subagent */
|
|
107
|
+
parentAgentId?: string;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Context for streaming data from tools to the client.
|
|
111
|
+
*
|
|
112
|
+
* This is passed to streaming-aware tools created via function-based plugin tools.
|
|
113
|
+
* Tools can use `writer.write()` to send custom data parts to the client
|
|
114
|
+
* incrementally during execution.
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* ```typescript
|
|
118
|
+
* const plugin = definePlugin({
|
|
119
|
+
* name: "my-plugin",
|
|
120
|
+
* tools: (ctx) => ({
|
|
121
|
+
* myTool: tool({
|
|
122
|
+
* description: "Streams data",
|
|
123
|
+
* inputSchema: z.object({ data: z.string() }),
|
|
124
|
+
* execute: async ({ data }) => {
|
|
125
|
+
* if (ctx.writer) {
|
|
126
|
+
* // Write custom data parts to the stream
|
|
127
|
+
* ctx.writer.write({
|
|
128
|
+
* type: "data",
|
|
129
|
+
* data: { progress: 50 },
|
|
130
|
+
* });
|
|
131
|
+
* }
|
|
132
|
+
* return { success: true };
|
|
133
|
+
* },
|
|
134
|
+
* }),
|
|
135
|
+
* }),
|
|
136
|
+
* });
|
|
137
|
+
* ```
|
|
138
|
+
*
|
|
139
|
+
* @category Types
|
|
140
|
+
*/
|
|
141
|
+
export interface StreamingContext {
|
|
142
|
+
/**
|
|
143
|
+
* UI Message stream writer for sending custom data to client.
|
|
144
|
+
* Only available when using `streamDataResponse()`.
|
|
145
|
+
* Will be `null` when using `generate()` or regular `streamResponse()`.
|
|
146
|
+
*/
|
|
147
|
+
writer: UIMessageStreamWriter | null;
|
|
148
|
+
/**
|
|
149
|
+
* Metadata identifying the source of streamed data.
|
|
150
|
+
* Automatically included when streaming from subagents.
|
|
151
|
+
*/
|
|
152
|
+
metadata?: StreamingMetadata;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Factory function for creating streaming-aware tools.
|
|
156
|
+
*
|
|
157
|
+
* This allows plugins to create tools that can access the streaming context
|
|
158
|
+
* and send incremental data to the client via `ctx.writer`.
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```typescript
|
|
162
|
+
* const streamingTools: StreamingToolsFactory = (ctx) => ({
|
|
163
|
+
* renderUI: tool({
|
|
164
|
+
* description: "Renders UI with streaming updates",
|
|
165
|
+
* inputSchema: z.object({ tree: UITreeSchema }),
|
|
166
|
+
* execute: async ({ tree }) => {
|
|
167
|
+
* if (ctx.writer) {
|
|
168
|
+
* ctx.writer.write({ type: "data", value: { type: "ui-patch", op: "set", path: "/root", value: tree.root } });
|
|
169
|
+
* }
|
|
170
|
+
* return { success: true };
|
|
171
|
+
* },
|
|
172
|
+
* }),
|
|
173
|
+
* });
|
|
174
|
+
* ```
|
|
175
|
+
*
|
|
176
|
+
* @category Types
|
|
177
|
+
*/
|
|
178
|
+
export type StreamingToolsFactory = (ctx: StreamingContext) => ToolSet;
|
|
179
|
+
/**
|
|
180
|
+
* Factory function for creating backends lazily.
|
|
181
|
+
*
|
|
182
|
+
* Backends can be provided as an instance or as a factory function.
|
|
183
|
+
* Factory functions receive the agent state and return a backend instance,
|
|
184
|
+
* allowing backends to be initialized with the shared state.
|
|
185
|
+
*
|
|
186
|
+
* @example
|
|
187
|
+
* ```typescript
|
|
188
|
+
* // Direct instance
|
|
189
|
+
* const agent = createAgent({
|
|
190
|
+
* model,
|
|
191
|
+
* backend: new FilesystemBackend({ rootDir: process.cwd() }),
|
|
192
|
+
* });
|
|
193
|
+
*
|
|
194
|
+
* // Factory function (receives shared state)
|
|
195
|
+
* const agent = createAgent({
|
|
196
|
+
* model,
|
|
197
|
+
* backend: (state) => new StateBackend(state),
|
|
198
|
+
* });
|
|
199
|
+
* ```
|
|
200
|
+
*
|
|
201
|
+
* @category Backend
|
|
202
|
+
*/
|
|
203
|
+
export type BackendFactory = (state: AgentState) => BackendProtocol;
|
|
204
|
+
/**
|
|
205
|
+
* Custom data types for agent-specific streaming events.
|
|
206
|
+
* These extend AI SDK's UIDataTypes to add subagent, progress, and other events.
|
|
207
|
+
*
|
|
208
|
+
* @category Types
|
|
209
|
+
*/
|
|
210
|
+
export interface AgentDataTypes extends UIDataTypes {
|
|
211
|
+
/** Emitted when a subagent is spawned */
|
|
212
|
+
"subagent-spawn": {
|
|
213
|
+
agentId: string;
|
|
214
|
+
type: string;
|
|
215
|
+
prompt: string;
|
|
216
|
+
parentToolUseId: string;
|
|
217
|
+
};
|
|
218
|
+
/** Emitted when a subagent completes */
|
|
219
|
+
"subagent-complete": {
|
|
220
|
+
agentId: string;
|
|
221
|
+
summary: string;
|
|
222
|
+
duration: number;
|
|
223
|
+
};
|
|
224
|
+
/** Progress updates during agent execution */
|
|
225
|
+
"agent-progress": {
|
|
226
|
+
message: string;
|
|
227
|
+
percent?: number;
|
|
228
|
+
};
|
|
229
|
+
/** Emitted when context compaction occurs */
|
|
230
|
+
"context-compaction": {
|
|
231
|
+
tokensBefore: number;
|
|
232
|
+
tokensAfter: number;
|
|
233
|
+
summary: string;
|
|
234
|
+
};
|
|
235
|
+
/** Emitted when a skill is loaded */
|
|
236
|
+
"skill-loaded": {
|
|
237
|
+
skillName: string;
|
|
238
|
+
prompt: string;
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Agent-specific UIMessage type with custom data types.
|
|
243
|
+
*
|
|
244
|
+
* @category Types
|
|
245
|
+
*/
|
|
246
|
+
export type AgentUIMessage = UIMessage<AgentDataTypes>;
|
|
247
|
+
/**
|
|
248
|
+
* Configuration options for creating an agent.
|
|
249
|
+
*
|
|
250
|
+
* @example
|
|
251
|
+
* ```typescript
|
|
252
|
+
* const agent = createAgent({
|
|
253
|
+
* model: anthropic("claude-sonnet-4-20250514"),
|
|
254
|
+
* systemPrompt: "You are a helpful assistant.",
|
|
255
|
+
* tools: {
|
|
256
|
+
* weather: tool({
|
|
257
|
+
* description: "Get weather",
|
|
258
|
+
* inputSchema: z.object({ city: z.string() }),
|
|
259
|
+
* execute: async ({ city }) => `Weather in ${city}: sunny`,
|
|
260
|
+
* }),
|
|
261
|
+
* },
|
|
262
|
+
* });
|
|
263
|
+
* ```
|
|
264
|
+
*
|
|
265
|
+
* @category Agent
|
|
266
|
+
*/
|
|
267
|
+
export interface AgentOptions {
|
|
268
|
+
/** The AI model to use for generation */
|
|
269
|
+
model: LanguageModel;
|
|
270
|
+
/**
|
|
271
|
+
* Fallback model to use when the primary model fails.
|
|
272
|
+
*
|
|
273
|
+
* When specified, the agent will automatically retry failed requests with the
|
|
274
|
+
* fallback model if the primary model encounters certain errors:
|
|
275
|
+
* - Rate limits (429 errors, "rate limit" messages)
|
|
276
|
+
* - Timeouts ("timeout" messages)
|
|
277
|
+
* - Model unavailable (503 errors, "unavailable" messages)
|
|
278
|
+
*
|
|
279
|
+
* The fallback model should typically be a faster or more available alternative,
|
|
280
|
+
* such as switching from a premium model to a standard one.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* ```typescript
|
|
284
|
+
* import { anthropic } from "@ai-sdk/anthropic";
|
|
285
|
+
*
|
|
286
|
+
* const agent = createAgent({
|
|
287
|
+
* model: anthropic("claude-sonnet-4-20250514"),
|
|
288
|
+
* fallbackModel: anthropic("claude-3-5-haiku-20241022"), // Fallback to faster model
|
|
289
|
+
* });
|
|
290
|
+
* ```
|
|
291
|
+
*
|
|
292
|
+
* @defaultValue undefined
|
|
293
|
+
*/
|
|
294
|
+
fallbackModel?: LanguageModel;
|
|
295
|
+
/**
|
|
296
|
+
* System prompt that defines the agent's behavior and personality.
|
|
297
|
+
* @defaultValue undefined
|
|
298
|
+
*/
|
|
299
|
+
systemPrompt?: string;
|
|
300
|
+
/**
|
|
301
|
+
* Maximum number of tool call steps allowed per generation.
|
|
302
|
+
* @defaultValue 10
|
|
303
|
+
*/
|
|
304
|
+
maxSteps?: number;
|
|
305
|
+
/**
|
|
306
|
+
* Tools available to the agent.
|
|
307
|
+
* Use AI SDK's `tool()` function to define tools.
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* ```typescript
|
|
311
|
+
* import { tool } from "ai";
|
|
312
|
+
*
|
|
313
|
+
* tools: {
|
|
314
|
+
* myTool: tool({
|
|
315
|
+
* description: "Does something",
|
|
316
|
+
* inputSchema: z.object({ input: z.string() }),
|
|
317
|
+
* execute: async ({ input }) => `Result: ${input}`,
|
|
318
|
+
* }),
|
|
319
|
+
* }
|
|
320
|
+
* ```
|
|
321
|
+
*/
|
|
322
|
+
tools?: ToolSet;
|
|
323
|
+
/** Plugins to load into the agent */
|
|
324
|
+
plugins?: AgentPlugin[];
|
|
325
|
+
/** Skills providing contextual instructions for the agent */
|
|
326
|
+
skills?: SkillDefinition[];
|
|
327
|
+
/**
|
|
328
|
+
* Middleware to apply to the agent.
|
|
329
|
+
*
|
|
330
|
+
* Middleware provides a clean API for adding cross-cutting concerns like
|
|
331
|
+
* logging, metrics, caching, and rate limiting. Middleware are processed
|
|
332
|
+
* in order and register hooks via a context object.
|
|
333
|
+
*
|
|
334
|
+
* This is the recommended way to add observability and cross-cutting
|
|
335
|
+
* concerns. For fine-grained hook control, use the `hooks` option instead.
|
|
336
|
+
*
|
|
337
|
+
* @example
|
|
338
|
+
* ```typescript
|
|
339
|
+
* import { createLoggingMiddleware, createConsoleTransport } from "@lleverage-ai/agent-sdk";
|
|
340
|
+
*
|
|
341
|
+
* const agent = createAgent({
|
|
342
|
+
* model,
|
|
343
|
+
* middleware: [
|
|
344
|
+
* createLoggingMiddleware({ transport: createConsoleTransport() }),
|
|
345
|
+
* ],
|
|
346
|
+
* });
|
|
347
|
+
* ```
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* ```typescript
|
|
351
|
+
* // Multiple middleware
|
|
352
|
+
* const agent = createAgent({
|
|
353
|
+
* model,
|
|
354
|
+
* middleware: [
|
|
355
|
+
* createLoggingMiddleware({ transport: consoleTransport }),
|
|
356
|
+
* createMetricsMiddleware({ registry }),
|
|
357
|
+
* ],
|
|
358
|
+
* });
|
|
359
|
+
* ```
|
|
360
|
+
*/
|
|
361
|
+
middleware?: import("./middleware/types.js").AgentMiddleware[];
|
|
362
|
+
/**
|
|
363
|
+
* Unified hook registrations with enhanced control flow.
|
|
364
|
+
* Supports permission decisions, input/output transformation, caching, and retry.
|
|
365
|
+
*
|
|
366
|
+
* When both `middleware` and `hooks` are provided, middleware hooks are
|
|
367
|
+
* processed first, followed by explicit hooks.
|
|
368
|
+
*
|
|
369
|
+
* @example
|
|
370
|
+
* ```typescript
|
|
371
|
+
* const agent = createAgent({
|
|
372
|
+
* model,
|
|
373
|
+
* hooks: {
|
|
374
|
+
* PreGenerate: [cacheCheckHook],
|
|
375
|
+
* PostGenerate: [cacheStoreHook, auditLogHook],
|
|
376
|
+
* PreToolUse: [{ matcher: 'Write|Edit', hooks: [protectFilesHook] }],
|
|
377
|
+
* },
|
|
378
|
+
* });
|
|
379
|
+
* ```
|
|
380
|
+
*/
|
|
381
|
+
hooks?: HookRegistration;
|
|
382
|
+
/**
|
|
383
|
+
* Context manager for automatic message compaction and token tracking.
|
|
384
|
+
*
|
|
385
|
+
* When provided, the agent will automatically manage conversation context
|
|
386
|
+
* by tracking token usage and compacting old messages into summaries when
|
|
387
|
+
* the token budget is exceeded.
|
|
388
|
+
*
|
|
389
|
+
* @example
|
|
390
|
+
* ```typescript
|
|
391
|
+
* import { createContextManager } from "@lleverage-ai/agent-sdk";
|
|
392
|
+
*
|
|
393
|
+
* const agent = createAgent({
|
|
394
|
+
* model,
|
|
395
|
+
* contextManager: createContextManager({
|
|
396
|
+
* maxTokens: 100000,
|
|
397
|
+
* summarization: {
|
|
398
|
+
* tokenThreshold: 0.75, // Compact at 75% capacity
|
|
399
|
+
* keepMessageCount: 10, // Keep last 10 messages
|
|
400
|
+
* },
|
|
401
|
+
* onCompact: (result) => {
|
|
402
|
+
* console.log(`Compacted ${result.messagesBefore} messages to ${result.messagesAfter}`);
|
|
403
|
+
* },
|
|
404
|
+
* }),
|
|
405
|
+
* });
|
|
406
|
+
* ```
|
|
407
|
+
*/
|
|
408
|
+
contextManager?: import("./context-manager.js").ContextManager;
|
|
409
|
+
/**
|
|
410
|
+
* Storage backend for file operations.
|
|
411
|
+
*
|
|
412
|
+
* Can be a backend instance or a factory function that receives the agent state.
|
|
413
|
+
* If not provided, a StateBackend is created automatically with a fresh state.
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* ```typescript
|
|
417
|
+
* // Use filesystem backend for real file operations
|
|
418
|
+
* const agent = createAgent({
|
|
419
|
+
* model,
|
|
420
|
+
* backend: new FilesystemBackend({ rootDir: process.cwd() }),
|
|
421
|
+
* });
|
|
422
|
+
*
|
|
423
|
+
* // Use factory to access shared state
|
|
424
|
+
* const agent = createAgent({
|
|
425
|
+
* model,
|
|
426
|
+
* backend: (state) => new CompositeBackend(
|
|
427
|
+
* new StateBackend(state),
|
|
428
|
+
* { '/persistent/': new PersistentBackend({ store }) }
|
|
429
|
+
* ),
|
|
430
|
+
* });
|
|
431
|
+
*
|
|
432
|
+
* // Default: StateBackend with fresh state
|
|
433
|
+
* const agent = createAgent({ model });
|
|
434
|
+
* ```
|
|
435
|
+
*
|
|
436
|
+
* @defaultValue StateBackend with empty state
|
|
437
|
+
*/
|
|
438
|
+
backend?: BackendProtocol | BackendFactory;
|
|
439
|
+
/**
|
|
440
|
+
* Checkpoint saver for session persistence.
|
|
441
|
+
*
|
|
442
|
+
* When provided, the agent will automatically save checkpoints after each
|
|
443
|
+
* generation step and restore state when a matching threadId is found.
|
|
444
|
+
*
|
|
445
|
+
* @example
|
|
446
|
+
* ```typescript
|
|
447
|
+
* import { FileSaver, createAgent } from "@lleverage-ai/agent-sdk";
|
|
448
|
+
*
|
|
449
|
+
* const agent = createAgent({
|
|
450
|
+
* model,
|
|
451
|
+
* checkpointer: new FileSaver({ dir: "./.checkpoints" }),
|
|
452
|
+
* });
|
|
453
|
+
*
|
|
454
|
+
* // First interaction - creates checkpoint
|
|
455
|
+
* await agent.generate({
|
|
456
|
+
* prompt: "Hello",
|
|
457
|
+
* threadId: "session-123",
|
|
458
|
+
* });
|
|
459
|
+
*
|
|
460
|
+
* // Later - restores from checkpoint
|
|
461
|
+
* await agent.generate({
|
|
462
|
+
* prompt: "Continue our conversation",
|
|
463
|
+
* threadId: "session-123",
|
|
464
|
+
* });
|
|
465
|
+
* ```
|
|
466
|
+
*/
|
|
467
|
+
checkpointer?: BaseCheckpointSaver;
|
|
468
|
+
/**
|
|
469
|
+
* Plugin loading mode for tool registration.
|
|
470
|
+
*
|
|
471
|
+
* Controls how plugin tools are made available to the agent:
|
|
472
|
+
* - `"eager"` - Load all plugin tools immediately (current behavior)
|
|
473
|
+
* - `"lazy"` - Register tools with metadata only, load on-demand via use_tools
|
|
474
|
+
* - `"explicit"` - Don't register plugin tools, require manual registration
|
|
475
|
+
*
|
|
476
|
+
* When using "lazy" mode, the agent gets a `use_tools` tool that allows
|
|
477
|
+
* it to search and load tools on-demand, keeping initial context small.
|
|
478
|
+
*
|
|
479
|
+
* @defaultValue "eager"
|
|
480
|
+
*
|
|
481
|
+
* @example
|
|
482
|
+
* ```typescript
|
|
483
|
+
* const agent = createAgent({
|
|
484
|
+
* model,
|
|
485
|
+
* plugins: [stripePlugin, twilioPlugin, ...manyPlugins],
|
|
486
|
+
* pluginLoading: "lazy", // Tools loaded on-demand
|
|
487
|
+
* });
|
|
488
|
+
* ```
|
|
489
|
+
*/
|
|
490
|
+
pluginLoading?: PluginLoadingMode;
|
|
491
|
+
/**
|
|
492
|
+
* Plugins to preload when using lazy loading mode.
|
|
493
|
+
*
|
|
494
|
+
* These plugins will have their tools loaded immediately regardless
|
|
495
|
+
* of the pluginLoading setting.
|
|
496
|
+
*
|
|
497
|
+
* @example
|
|
498
|
+
* ```typescript
|
|
499
|
+
* const agent = createAgent({
|
|
500
|
+
* model,
|
|
501
|
+
* plugins: [stripePlugin, twilioPlugin, coreUtilsPlugin],
|
|
502
|
+
* pluginLoading: "lazy",
|
|
503
|
+
* preloadPlugins: ["core-utils"], // Always load core-utils
|
|
504
|
+
* });
|
|
505
|
+
* ```
|
|
506
|
+
*/
|
|
507
|
+
preloadPlugins?: string[];
|
|
508
|
+
/**
|
|
509
|
+
* Restrict which tools the agent can use.
|
|
510
|
+
*
|
|
511
|
+
* When provided, only tools whose names exactly match entries in this array
|
|
512
|
+
* will be available to the agent. For MCP tools, use the full name format:
|
|
513
|
+
* `mcp__<plugin>__<tool>` (e.g., `mcp__github__list_issues`).
|
|
514
|
+
*
|
|
515
|
+
* This is useful for:
|
|
516
|
+
* - Security: limiting agent capabilities in production
|
|
517
|
+
* - Testing: isolating specific tool functionality
|
|
518
|
+
* - Subagents: restricting tools to those relevant for the task
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* ```typescript
|
|
522
|
+
* // Only allow read operations
|
|
523
|
+
* const agent = createAgent({
|
|
524
|
+
* model,
|
|
525
|
+
* tools: { read, write, edit, bash },
|
|
526
|
+
* allowedTools: ["read", "glob", "grep"],
|
|
527
|
+
* });
|
|
528
|
+
*
|
|
529
|
+
* // Allow all filesystem tools but not bash
|
|
530
|
+
* const agent = createAgent({
|
|
531
|
+
* model,
|
|
532
|
+
* tools: { read, write, edit, bash },
|
|
533
|
+
* allowedTools: ["read", "write", "edit", "glob", "grep"],
|
|
534
|
+
* });
|
|
535
|
+
* ```
|
|
536
|
+
*/
|
|
537
|
+
allowedTools?: string[];
|
|
538
|
+
/**
|
|
539
|
+
* Block specific tools from being used by the agent.
|
|
540
|
+
*
|
|
541
|
+
* When provided, tools whose names exactly match entries in this array
|
|
542
|
+
* will be removed from the available tool set. This is the opposite of
|
|
543
|
+
* `allowedTools` and is useful for:
|
|
544
|
+
* - Security: blocking dangerous operations (e.g., bash, rm)
|
|
545
|
+
* - Testing: disabling specific tools without listing all others
|
|
546
|
+
* - Production hardening: preventing access to risky tools
|
|
547
|
+
*
|
|
548
|
+
* For MCP tools, use the full name format: `mcp__<plugin>__<tool>`
|
|
549
|
+
* (e.g., `mcp__github__delete_repo`).
|
|
550
|
+
*
|
|
551
|
+
* **Priority**: If a tool appears in both `allowedTools` and `disallowedTools`,
|
|
552
|
+
* the tool is blocked (disallow takes precedence).
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
* ```typescript
|
|
556
|
+
* // Block shell access and file deletion
|
|
557
|
+
* const agent = createAgent({
|
|
558
|
+
* model,
|
|
559
|
+
* tools: { read, write, edit, bash, rm },
|
|
560
|
+
* disallowedTools: ["bash", "rm"],
|
|
561
|
+
* });
|
|
562
|
+
*
|
|
563
|
+
* // Block dangerous MCP operations
|
|
564
|
+
* const agent = createAgent({
|
|
565
|
+
* model,
|
|
566
|
+
* plugins: [githubPlugin],
|
|
567
|
+
* disallowedTools: [
|
|
568
|
+
* "mcp__github__delete_repo",
|
|
569
|
+
* "mcp__github__force_push",
|
|
570
|
+
* ],
|
|
571
|
+
* });
|
|
572
|
+
* ```
|
|
573
|
+
*
|
|
574
|
+
* @example
|
|
575
|
+
* ```typescript
|
|
576
|
+
* // Combine with allowedTools - disallow wins
|
|
577
|
+
* const agent = createAgent({
|
|
578
|
+
* model,
|
|
579
|
+
* allowedTools: ["read", "write", "bash"], // Allow these
|
|
580
|
+
* disallowedTools: ["bash"], // But block bash
|
|
581
|
+
* // Result: only "read" and "write" are available
|
|
582
|
+
* });
|
|
583
|
+
* ```
|
|
584
|
+
*/
|
|
585
|
+
disallowedTools?: string[];
|
|
586
|
+
/**
|
|
587
|
+
* Permission mode controlling default tool approval behavior.
|
|
588
|
+
*
|
|
589
|
+
* Aligned with Claude Agent SDK permission modes:
|
|
590
|
+
* - `default`: Unmatched tools use canUseTool callback or hooks (default behavior)
|
|
591
|
+
* - `acceptEdits`: Auto-approve file edit operations (Write, Edit, mkdir, touch, rm, mv, cp)
|
|
592
|
+
* - `bypassPermissions`: Auto-approve all tools (dangerous - use only for testing/demos)
|
|
593
|
+
* - `plan`: Block all tool execution (planning/analysis only, no actions)
|
|
594
|
+
*
|
|
595
|
+
* Permission checking order:
|
|
596
|
+
* 1. Hooks (PreToolUse with permissionDecision)
|
|
597
|
+
* 2. Permission mode
|
|
598
|
+
* 3. canUseTool callback (if provided)
|
|
599
|
+
*
|
|
600
|
+
* @defaultValue "default"
|
|
601
|
+
*
|
|
602
|
+
* @example
|
|
603
|
+
* ```typescript
|
|
604
|
+
* // Auto-approve file edits for smoother development experience
|
|
605
|
+
* const agent = createAgent({
|
|
606
|
+
* model,
|
|
607
|
+
* permissionMode: "acceptEdits",
|
|
608
|
+
* });
|
|
609
|
+
*
|
|
610
|
+
* // Plan mode for analysis without actions
|
|
611
|
+
* const planner = createAgent({
|
|
612
|
+
* model,
|
|
613
|
+
* permissionMode: "plan",
|
|
614
|
+
* });
|
|
615
|
+
* ```
|
|
616
|
+
*/
|
|
617
|
+
permissionMode?: PermissionMode;
|
|
618
|
+
/**
|
|
619
|
+
* When true and permissionMode is "acceptEdits", automatically configures the
|
|
620
|
+
* sandbox backend (if present) to block shell-based file operations.
|
|
621
|
+
*
|
|
622
|
+
* This prevents bash commands like `echo > file`, `rm`, `mv`, `cp`, etc. from
|
|
623
|
+
* bypassing the file edit tool permission checks in acceptEdits mode.
|
|
624
|
+
*
|
|
625
|
+
* When set to `false` with acceptEdits mode, a warning will be logged to
|
|
626
|
+
* alert you that shell-based file operations can bypass the permission checks.
|
|
627
|
+
*
|
|
628
|
+
* This option only has an effect when:
|
|
629
|
+
* - `permissionMode` is set to `"acceptEdits"`
|
|
630
|
+
* - The `backend` is a sandbox backend (e.g., `LocalSandbox`)
|
|
631
|
+
*
|
|
632
|
+
* @defaultValue true
|
|
633
|
+
*
|
|
634
|
+
* @example
|
|
635
|
+
* ```typescript
|
|
636
|
+
* // Default: shell file ops are blocked in acceptEdits mode
|
|
637
|
+
* const agent = createAgent({
|
|
638
|
+
* model,
|
|
639
|
+
* backend: new LocalSandbox({ cwd: process.cwd() }),
|
|
640
|
+
* permissionMode: "acceptEdits",
|
|
641
|
+
* // blockShellFileOps: true is the default
|
|
642
|
+
* });
|
|
643
|
+
*
|
|
644
|
+
* // Explicitly allow shell file ops (not recommended)
|
|
645
|
+
* const agent = createAgent({
|
|
646
|
+
* model,
|
|
647
|
+
* backend: new LocalSandbox({ cwd: process.cwd() }),
|
|
648
|
+
* permissionMode: "acceptEdits",
|
|
649
|
+
* blockShellFileOps: false, // Warning will be logged
|
|
650
|
+
* });
|
|
651
|
+
* ```
|
|
652
|
+
*/
|
|
653
|
+
blockShellFileOps?: boolean;
|
|
654
|
+
/**
|
|
655
|
+
* Runtime callback for tool approval decisions.
|
|
656
|
+
*
|
|
657
|
+
* Called when a tool is not handled by hooks or permission mode.
|
|
658
|
+
* This provides fine-grained runtime control over tool execution,
|
|
659
|
+
* allowing you to implement custom approval logic based on tool name,
|
|
660
|
+
* input, or external state.
|
|
661
|
+
*
|
|
662
|
+
* The callback should return:
|
|
663
|
+
* - `"allow"` - Allow the tool to execute
|
|
664
|
+
* - `"deny"` - Block the tool and throw an error
|
|
665
|
+
* - `"ask"` - Request user approval (requires approval flow integration)
|
|
666
|
+
*
|
|
667
|
+
* Permission checking order:
|
|
668
|
+
* 1. Hooks (PreToolUse with permissionDecision) - checked first
|
|
669
|
+
* 2. Permission mode - checked second
|
|
670
|
+
* 3. canUseTool callback (this option) - checked last
|
|
671
|
+
*
|
|
672
|
+
* @param toolName - Name of the tool being invoked
|
|
673
|
+
* @param input - Input arguments passed to the tool
|
|
674
|
+
* @returns Permission decision ("allow", "deny", or "ask")
|
|
675
|
+
*
|
|
676
|
+
* @example
|
|
677
|
+
* ```typescript
|
|
678
|
+
* const agent = createAgent({
|
|
679
|
+
* model,
|
|
680
|
+
* canUseTool: async (toolName, input) => {
|
|
681
|
+
* // Block bash commands entirely
|
|
682
|
+
* if (toolName === "bash") return "deny";
|
|
683
|
+
*
|
|
684
|
+
* // Require approval for file writes
|
|
685
|
+
* if (toolName === "write" || toolName === "edit") {
|
|
686
|
+
* return "ask";
|
|
687
|
+
* }
|
|
688
|
+
*
|
|
689
|
+
* // Allow everything else
|
|
690
|
+
* return "allow";
|
|
691
|
+
* },
|
|
692
|
+
* });
|
|
693
|
+
* ```
|
|
694
|
+
*
|
|
695
|
+
* @example
|
|
696
|
+
* ```typescript
|
|
697
|
+
* // Custom approval logic based on file paths
|
|
698
|
+
* const agent = createAgent({
|
|
699
|
+
* model,
|
|
700
|
+
* canUseTool: async (toolName, input) => {
|
|
701
|
+
* if (toolName === "write") {
|
|
702
|
+
* const filePath = (input as { file_path?: string }).file_path;
|
|
703
|
+
* if (filePath?.startsWith("/etc/")) {
|
|
704
|
+
* return "deny"; // Block system directory writes
|
|
705
|
+
* }
|
|
706
|
+
* if (filePath?.endsWith(".env")) {
|
|
707
|
+
* return "ask"; // Require approval for sensitive files
|
|
708
|
+
* }
|
|
709
|
+
* }
|
|
710
|
+
* return "allow";
|
|
711
|
+
* },
|
|
712
|
+
* });
|
|
713
|
+
* ```
|
|
714
|
+
*/
|
|
715
|
+
canUseTool?: (toolName: string, input: unknown) => Promise<PermissionDecision> | PermissionDecision;
|
|
716
|
+
/**
|
|
717
|
+
* Disable specific core tools.
|
|
718
|
+
*
|
|
719
|
+
* Core tools are included by default. Use this to exclude specific
|
|
720
|
+
* tools that should not be available to this agent.
|
|
721
|
+
*
|
|
722
|
+
* @example
|
|
723
|
+
* ```typescript
|
|
724
|
+
* const safeAgent = createAgent({
|
|
725
|
+
* model,
|
|
726
|
+
* disabledCoreTools: ["bash"], // No shell access
|
|
727
|
+
* });
|
|
728
|
+
* ```
|
|
729
|
+
*/
|
|
730
|
+
disabledCoreTools?: CoreToolName[];
|
|
731
|
+
/**
|
|
732
|
+
* Tool search configuration for progressive disclosure.
|
|
733
|
+
*/
|
|
734
|
+
toolSearch?: {
|
|
735
|
+
/**
|
|
736
|
+
* When to enable tool search.
|
|
737
|
+
* - `"auto"` - Enable when tools exceed threshold
|
|
738
|
+
* - `"always"` - Always enable
|
|
739
|
+
* - `"never"` - Never enable
|
|
740
|
+
* @defaultValue "auto"
|
|
741
|
+
*/
|
|
742
|
+
enabled?: "auto" | "always" | "never";
|
|
743
|
+
/**
|
|
744
|
+
* Tool count threshold for auto mode.
|
|
745
|
+
* Deferred loading activates when plugin tool count exceeds this value.
|
|
746
|
+
* @defaultValue 20
|
|
747
|
+
*/
|
|
748
|
+
threshold?: number;
|
|
749
|
+
/**
|
|
750
|
+
* Maximum results from search.
|
|
751
|
+
* @defaultValue 10
|
|
752
|
+
*/
|
|
753
|
+
maxResults?: number;
|
|
754
|
+
};
|
|
755
|
+
/**
|
|
756
|
+
* Subagent definitions for task delegation.
|
|
757
|
+
*
|
|
758
|
+
* When provided, a `task` tool is automatically created that allows
|
|
759
|
+
* the agent to delegate work to specialized subagents.
|
|
760
|
+
*
|
|
761
|
+
* For subagents with `streaming: true`, the task tool will pass
|
|
762
|
+
* the streaming context, allowing them to write directly to the
|
|
763
|
+
* parent's data stream. This requires using `streamDataResponse()`.
|
|
764
|
+
*
|
|
765
|
+
* @example
|
|
766
|
+
* ```typescript
|
|
767
|
+
* const agent = createAgent({
|
|
768
|
+
* model,
|
|
769
|
+
* subagents: [
|
|
770
|
+
* {
|
|
771
|
+
* type: "researcher",
|
|
772
|
+
* description: "Searches for information",
|
|
773
|
+
* create: (ctx) => createSubagent(agent, { model: ctx.model, ... }),
|
|
774
|
+
* },
|
|
775
|
+
* {
|
|
776
|
+
* type: "ui-builder",
|
|
777
|
+
* description: "Generates UI components",
|
|
778
|
+
* streaming: true, // Can write to parent's stream
|
|
779
|
+
* create: (ctx) => createSubagent(agent, { model: ctx.model, ... }),
|
|
780
|
+
* },
|
|
781
|
+
* ],
|
|
782
|
+
* });
|
|
783
|
+
*
|
|
784
|
+
* // Use streamDataResponse for streaming subagents
|
|
785
|
+
* return agent.streamDataResponse({ messages });
|
|
786
|
+
* ```
|
|
787
|
+
*/
|
|
788
|
+
subagents?: SubagentDefinition[];
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Plugin loading mode.
|
|
792
|
+
*
|
|
793
|
+
* - `"eager"` - Load all plugin tools immediately into context
|
|
794
|
+
* - `"lazy"` - Register tools with metadata only, load on-demand
|
|
795
|
+
* - `"explicit"` - Don't auto-register, require manual registration
|
|
796
|
+
*
|
|
797
|
+
* @category Plugins
|
|
798
|
+
*/
|
|
799
|
+
export type PluginLoadingMode = "eager" | "lazy" | "explicit";
|
|
800
|
+
/**
|
|
801
|
+
* An agent instance capable of generating responses and executing tools.
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```typescript
|
|
805
|
+
* const agent = createAgent({ model, systemPrompt: "..." });
|
|
806
|
+
*
|
|
807
|
+
* // Generate a response
|
|
808
|
+
* const result = await agent.generate({ prompt: "Hello" });
|
|
809
|
+
*
|
|
810
|
+
* // Stream for use with useChat
|
|
811
|
+
* const response = await agent.streamResponse({ prompt: "Hello" });
|
|
812
|
+
* ```
|
|
813
|
+
*
|
|
814
|
+
* @category Agent
|
|
815
|
+
*/
|
|
816
|
+
export interface Agent {
|
|
817
|
+
/** Unique identifier for this agent instance */
|
|
818
|
+
readonly id: string;
|
|
819
|
+
/** The options used to create this agent */
|
|
820
|
+
readonly options: AgentOptions;
|
|
821
|
+
/**
|
|
822
|
+
* The storage backend used by this agent.
|
|
823
|
+
*
|
|
824
|
+
* Provides access to the underlying file operations backend,
|
|
825
|
+
* useful for passing to tools or performing file operations.
|
|
826
|
+
*/
|
|
827
|
+
readonly backend: BackendProtocol;
|
|
828
|
+
/**
|
|
829
|
+
* The agent state managed by this agent.
|
|
830
|
+
*
|
|
831
|
+
* Contains todos and virtual filesystem data when using StateBackend.
|
|
832
|
+
* The state is shared with the backend if a factory function was used.
|
|
833
|
+
*/
|
|
834
|
+
readonly state: AgentState;
|
|
835
|
+
/**
|
|
836
|
+
* Promise that resolves when the agent is fully initialized.
|
|
837
|
+
*
|
|
838
|
+
* This includes:
|
|
839
|
+
* - MCP server connections for plugins with mcpServer config
|
|
840
|
+
* - Plugin setup functions
|
|
841
|
+
*
|
|
842
|
+
* Await this before using the agent if you need MCP tools to be available.
|
|
843
|
+
*
|
|
844
|
+
* @example
|
|
845
|
+
* ```typescript
|
|
846
|
+
* const agent = createAgent({ model, plugins: [mcpPlugin] });
|
|
847
|
+
* await agent.ready; // Wait for MCP connections
|
|
848
|
+
* return agent.streamResponse({ messages });
|
|
849
|
+
* ```
|
|
850
|
+
*/
|
|
851
|
+
readonly ready: Promise<void>;
|
|
852
|
+
/**
|
|
853
|
+
* Generate a complete response.
|
|
854
|
+
*
|
|
855
|
+
* @param options - Generation options including the prompt
|
|
856
|
+
* @returns The complete generation result
|
|
857
|
+
*/
|
|
858
|
+
generate(options: GenerateOptions): Promise<GenerateResult>;
|
|
859
|
+
/**
|
|
860
|
+
* Generate a streaming response as an AsyncGenerator.
|
|
861
|
+
* For internal use or custom stream handling.
|
|
862
|
+
*
|
|
863
|
+
* @param options - Generation options including the prompt
|
|
864
|
+
* @yields Stream parts as they're generated
|
|
865
|
+
*/
|
|
866
|
+
stream(options: GenerateOptions): AsyncGenerator<StreamPart>;
|
|
867
|
+
/**
|
|
868
|
+
* Generate a streaming Response for use with useChat/AI SDK UI.
|
|
869
|
+
* Returns a web-standard Response with proper stream protocol.
|
|
870
|
+
*
|
|
871
|
+
* @param options - Generation options including the prompt
|
|
872
|
+
* @returns A web Response that can be returned from API routes
|
|
873
|
+
*
|
|
874
|
+
* @example
|
|
875
|
+
* ```typescript
|
|
876
|
+
* // In a Next.js API route
|
|
877
|
+
* export async function POST(req: Request) {
|
|
878
|
+
* const { messages } = await req.json();
|
|
879
|
+
* return agent.streamResponse({ messages });
|
|
880
|
+
* }
|
|
881
|
+
* ```
|
|
882
|
+
*/
|
|
883
|
+
streamResponse(options: GenerateOptions): Promise<Response>;
|
|
884
|
+
/**
|
|
885
|
+
* Get the underlying streamText result for advanced use cases.
|
|
886
|
+
* Allows calling toUIMessageStream(), toTextStreamResponse(), etc.
|
|
887
|
+
*
|
|
888
|
+
* @param options - Generation options
|
|
889
|
+
* @returns Promise of the raw streamText result from AI SDK
|
|
890
|
+
*/
|
|
891
|
+
streamRaw(options: GenerateOptions): Promise<ReturnType<typeof streamText>>;
|
|
892
|
+
/**
|
|
893
|
+
* Generate a streaming Response with data stream support.
|
|
894
|
+
*
|
|
895
|
+
* This method enables tools to stream custom data to the client using
|
|
896
|
+
* `ctx.writer.write()`. The data is delivered alongside the text stream
|
|
897
|
+
* and can be accessed via `useChat`'s `data` property.
|
|
898
|
+
*
|
|
899
|
+
* Use this method when you need:
|
|
900
|
+
* - Progressive UI updates during tool execution
|
|
901
|
+
* - Streaming structured data to the client
|
|
902
|
+
* - Real-time feedback from long-running tools
|
|
903
|
+
*
|
|
904
|
+
* @param options - Generation options including the prompt
|
|
905
|
+
* @returns A web Response that streams text and custom data
|
|
906
|
+
*
|
|
907
|
+
* @example
|
|
908
|
+
* ```typescript
|
|
909
|
+
* // In a Next.js API route
|
|
910
|
+
* export async function POST(req: Request) {
|
|
911
|
+
* const { messages } = await req.json();
|
|
912
|
+
* return agent.streamDataResponse({ messages });
|
|
913
|
+
* }
|
|
914
|
+
*
|
|
915
|
+
* // On the client with useChat
|
|
916
|
+
* const { messages, data } = useChat({ api: "/api/agent" });
|
|
917
|
+
* // `data` contains custom data streamed from tools
|
|
918
|
+
* ```
|
|
919
|
+
*/
|
|
920
|
+
streamDataResponse(options: GenerateOptions): Promise<Response>;
|
|
921
|
+
/**
|
|
922
|
+
* Get all skills registered with this agent.
|
|
923
|
+
* @returns Array of skill definitions
|
|
924
|
+
*/
|
|
925
|
+
getSkills(): SkillDefinition[];
|
|
926
|
+
/**
|
|
927
|
+
* Get all currently active tools.
|
|
928
|
+
*
|
|
929
|
+
* Returns the combined set of core tools and dynamically loaded tools.
|
|
930
|
+
* In lazy loading mode, this includes tools loaded via use_tools.
|
|
931
|
+
*
|
|
932
|
+
* @returns ToolSet containing all active tools
|
|
933
|
+
*/
|
|
934
|
+
getActiveTools(): ToolSet;
|
|
935
|
+
/**
|
|
936
|
+
* Load tools from the registry by name.
|
|
937
|
+
*
|
|
938
|
+
* Only available when using lazy plugin loading mode.
|
|
939
|
+
* Tools loaded through this method become available for use.
|
|
940
|
+
*
|
|
941
|
+
* @param toolNames - Names of tools to load
|
|
942
|
+
* @returns Object with loaded tool names and any errors
|
|
943
|
+
*/
|
|
944
|
+
loadTools(toolNames: string[]): {
|
|
945
|
+
loaded: string[];
|
|
946
|
+
notFound: string[];
|
|
947
|
+
};
|
|
948
|
+
/**
|
|
949
|
+
* Dynamically change the permission mode.
|
|
950
|
+
*
|
|
951
|
+
* Allows switching permission behavior at runtime, useful for
|
|
952
|
+
* transitioning between planning and execution phases or adjusting
|
|
953
|
+
* security posture based on user actions.
|
|
954
|
+
*
|
|
955
|
+
* @param mode - The new permission mode
|
|
956
|
+
*
|
|
957
|
+
* @example
|
|
958
|
+
* ```typescript
|
|
959
|
+
* // Start in plan mode
|
|
960
|
+
* const agent = createAgent({
|
|
961
|
+
* model,
|
|
962
|
+
* permissionMode: "plan",
|
|
963
|
+
* });
|
|
964
|
+
*
|
|
965
|
+
* // After planning, switch to execution
|
|
966
|
+
* agent.setPermissionMode("acceptEdits");
|
|
967
|
+
* ```
|
|
968
|
+
*/
|
|
969
|
+
setPermissionMode(mode: PermissionMode): void;
|
|
970
|
+
/**
|
|
971
|
+
* Get the pending interrupt for a thread.
|
|
972
|
+
*
|
|
973
|
+
* Returns the interrupt from the checkpoint if there is a pending interrupt
|
|
974
|
+
* (e.g., tool approval request, custom question). Useful for displaying
|
|
975
|
+
* prompts to users.
|
|
976
|
+
*
|
|
977
|
+
* @param threadId - The thread ID to check for pending interrupts
|
|
978
|
+
* @returns The interrupt if one is pending, undefined otherwise
|
|
979
|
+
*
|
|
980
|
+
* @example
|
|
981
|
+
* ```typescript
|
|
982
|
+
* const interrupt = await agent.getInterrupt(threadId);
|
|
983
|
+
* if (interrupt) {
|
|
984
|
+
* if (isApprovalInterrupt(interrupt)) {
|
|
985
|
+
* console.log(`Waiting for approval of ${interrupt.toolName}`);
|
|
986
|
+
* console.log(`Arguments:`, interrupt.request.args);
|
|
987
|
+
* }
|
|
988
|
+
* }
|
|
989
|
+
* ```
|
|
990
|
+
*/
|
|
991
|
+
getInterrupt(threadId: string): Promise<Interrupt | undefined>;
|
|
992
|
+
/**
|
|
993
|
+
* Resume execution after responding to an interrupt.
|
|
994
|
+
*
|
|
995
|
+
* Use this method to continue the agent's execution after providing a response
|
|
996
|
+
* to an interrupt. For approval interrupts, the response should be an
|
|
997
|
+
* `ApprovalResponse` with `{ approved: boolean }`. For custom interrupts,
|
|
998
|
+
* provide the appropriate response type.
|
|
999
|
+
*
|
|
1000
|
+
* @param threadId - The thread ID to resume
|
|
1001
|
+
* @param interruptId - The ID of the interrupt being responded to
|
|
1002
|
+
* @param response - The response to the interrupt
|
|
1003
|
+
* @param options - Optional generation options to override defaults
|
|
1004
|
+
* @returns The generation result after resuming
|
|
1005
|
+
*
|
|
1006
|
+
* @example
|
|
1007
|
+
* ```typescript
|
|
1008
|
+
* const result = await agent.generate({ prompt, threadId });
|
|
1009
|
+
*
|
|
1010
|
+
* if (result.status === "interrupted") {
|
|
1011
|
+
* const { interrupt } = result;
|
|
1012
|
+
*
|
|
1013
|
+
* if (isApprovalInterrupt(interrupt)) {
|
|
1014
|
+
* const approved = await askUser(`Run ${interrupt.request.toolName}?`);
|
|
1015
|
+
* return agent.resume(threadId, interrupt.id, { approved });
|
|
1016
|
+
* }
|
|
1017
|
+
*
|
|
1018
|
+
* // Custom interrupt
|
|
1019
|
+
* const response = await handleCustomInterrupt(interrupt.request);
|
|
1020
|
+
* return agent.resume(threadId, interrupt.id, response);
|
|
1021
|
+
* }
|
|
1022
|
+
* ```
|
|
1023
|
+
*/
|
|
1024
|
+
resume(threadId: string, interruptId: string, response: unknown, options?: Partial<GenerateOptions>): Promise<GenerateResult>;
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Options for generating a response.
|
|
1028
|
+
*
|
|
1029
|
+
* @example
|
|
1030
|
+
* ```typescript
|
|
1031
|
+
* const result = await agent.generate({
|
|
1032
|
+
* prompt: "What's the weather like?",
|
|
1033
|
+
* maxTokens: 1000,
|
|
1034
|
+
* temperature: 0.7,
|
|
1035
|
+
* });
|
|
1036
|
+
* ```
|
|
1037
|
+
*
|
|
1038
|
+
* @category Agent
|
|
1039
|
+
*/
|
|
1040
|
+
export interface GenerateOptions {
|
|
1041
|
+
/** The user message/prompt */
|
|
1042
|
+
prompt?: string;
|
|
1043
|
+
/** Conversation history - accepts AI SDK message types */
|
|
1044
|
+
messages?: ModelMessage[];
|
|
1045
|
+
/**
|
|
1046
|
+
* Thread identifier for session persistence.
|
|
1047
|
+
*
|
|
1048
|
+
* When provided with a checkpointer, the agent will:
|
|
1049
|
+
* - Load existing checkpoint for this thread (if any)
|
|
1050
|
+
* - Save checkpoint after each step
|
|
1051
|
+
*
|
|
1052
|
+
* @example
|
|
1053
|
+
* ```typescript
|
|
1054
|
+
* // Resume a conversation
|
|
1055
|
+
* const result = await agent.generate({
|
|
1056
|
+
* prompt: "Continue",
|
|
1057
|
+
* threadId: "session-123",
|
|
1058
|
+
* });
|
|
1059
|
+
* ```
|
|
1060
|
+
*/
|
|
1061
|
+
threadId?: string;
|
|
1062
|
+
/**
|
|
1063
|
+
* Fork an existing session into a new thread.
|
|
1064
|
+
*
|
|
1065
|
+
* When provided with a checkpointer and threadId, creates a new session
|
|
1066
|
+
* that starts from the current state of the source thread. Useful for
|
|
1067
|
+
* exploring alternative conversation paths without affecting the original.
|
|
1068
|
+
*
|
|
1069
|
+
* @example
|
|
1070
|
+
* ```typescript
|
|
1071
|
+
* // Fork a session to explore alternatives
|
|
1072
|
+
* const result = await agent.generate({
|
|
1073
|
+
* threadId: "session-123",
|
|
1074
|
+
* forkSession: "session-123-alternative",
|
|
1075
|
+
* prompt: "Let's try a different approach",
|
|
1076
|
+
* });
|
|
1077
|
+
* // Original session-123 remains unchanged
|
|
1078
|
+
* // session-123-alternative contains a copy of session-123's state
|
|
1079
|
+
* ```
|
|
1080
|
+
*/
|
|
1081
|
+
forkSession?: string;
|
|
1082
|
+
/** Maximum tokens to generate */
|
|
1083
|
+
maxTokens?: number;
|
|
1084
|
+
/**
|
|
1085
|
+
* Temperature for sampling (higher = more random).
|
|
1086
|
+
* @defaultValue Model default
|
|
1087
|
+
*/
|
|
1088
|
+
temperature?: number;
|
|
1089
|
+
/** Sequences that will stop generation */
|
|
1090
|
+
stopSequences?: string[];
|
|
1091
|
+
/** Abort signal for cancellation */
|
|
1092
|
+
signal?: AbortSignal;
|
|
1093
|
+
/**
|
|
1094
|
+
* Enable incremental checkpointing during streaming.
|
|
1095
|
+
*
|
|
1096
|
+
* When enabled, the agent will save a checkpoint after each step (tool call)
|
|
1097
|
+
* during streaming, not just at the end. This provides better crash recovery
|
|
1098
|
+
* for long-running streams with multiple tool calls.
|
|
1099
|
+
*
|
|
1100
|
+
* If the process crashes mid-stream, you can resume from the last completed
|
|
1101
|
+
* step instead of losing all progress.
|
|
1102
|
+
*
|
|
1103
|
+
* @defaultValue false
|
|
1104
|
+
*
|
|
1105
|
+
* @example
|
|
1106
|
+
* ```typescript
|
|
1107
|
+
* // Enable incremental checkpointing for long-running streams
|
|
1108
|
+
* const stream = await agent.stream({
|
|
1109
|
+
* prompt: "Analyze this large dataset",
|
|
1110
|
+
* threadId: "session-123",
|
|
1111
|
+
* checkpointAfterToolCall: true,
|
|
1112
|
+
* });
|
|
1113
|
+
* ```
|
|
1114
|
+
*/
|
|
1115
|
+
checkpointAfterToolCall?: boolean;
|
|
1116
|
+
/**
|
|
1117
|
+
* Structured output specification.
|
|
1118
|
+
* @see https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data
|
|
1119
|
+
*
|
|
1120
|
+
* @example
|
|
1121
|
+
* ```typescript
|
|
1122
|
+
* import { Output } from "ai";
|
|
1123
|
+
*
|
|
1124
|
+
* output: Output.object({
|
|
1125
|
+
* schema: z.object({ summary: z.string() })
|
|
1126
|
+
* })
|
|
1127
|
+
* ```
|
|
1128
|
+
*/
|
|
1129
|
+
output?: ReturnType<typeof Output.object> | ReturnType<typeof Output.array>;
|
|
1130
|
+
/**
|
|
1131
|
+
* Provider-specific options passed directly to generateText/streamText.
|
|
1132
|
+
* Use this for features like extended thinking, reasoning effort, etc.
|
|
1133
|
+
*
|
|
1134
|
+
* @example
|
|
1135
|
+
* ```typescript
|
|
1136
|
+
* providerOptions: {
|
|
1137
|
+
* anthropic: { thinking: { type: 'enabled', budgetTokens: 10000 } }
|
|
1138
|
+
* }
|
|
1139
|
+
* ```
|
|
1140
|
+
*/
|
|
1141
|
+
providerOptions?: any;
|
|
1142
|
+
/**
|
|
1143
|
+
* Additional headers for API requests.
|
|
1144
|
+
* Useful for custom authentication or provider-specific headers.
|
|
1145
|
+
*/
|
|
1146
|
+
headers?: Record<string, string>;
|
|
1147
|
+
/**
|
|
1148
|
+
* Callback invoked when the stream writer becomes available.
|
|
1149
|
+
*
|
|
1150
|
+
* This is only called by `streamDataResponse()` and provides access to the
|
|
1151
|
+
* underlying `UIMessageStreamWriter` for custom data streaming. Useful for
|
|
1152
|
+
* setting up log transports that write to the stream.
|
|
1153
|
+
*
|
|
1154
|
+
* @example
|
|
1155
|
+
* ```typescript
|
|
1156
|
+
* // Stream logs to the client via the writer
|
|
1157
|
+
* const logEntries: LogEntry[] = [];
|
|
1158
|
+
* const logTransport: LogTransport = {
|
|
1159
|
+
* name: "stream",
|
|
1160
|
+
* write: (entry) => {
|
|
1161
|
+
* // Will be updated when writer is ready
|
|
1162
|
+
* if (writerRef.current) {
|
|
1163
|
+
* writerRef.current.write({ type: "data", value: { type: "log", entry } });
|
|
1164
|
+
* }
|
|
1165
|
+
* },
|
|
1166
|
+
* };
|
|
1167
|
+
*
|
|
1168
|
+
* return agent.streamDataResponse({
|
|
1169
|
+
* messages,
|
|
1170
|
+
* onStreamWriterReady: (writer) => {
|
|
1171
|
+
* writerRef.current = writer;
|
|
1172
|
+
* },
|
|
1173
|
+
* });
|
|
1174
|
+
* ```
|
|
1175
|
+
*/
|
|
1176
|
+
onStreamWriterReady?: (writer: UIMessageStreamWriter) => void;
|
|
1177
|
+
/**
|
|
1178
|
+
* Internal flag to skip compaction during summary generation.
|
|
1179
|
+
* @internal
|
|
1180
|
+
*/
|
|
1181
|
+
_skipCompaction?: boolean;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Result from a completed generation request.
|
|
1185
|
+
*
|
|
1186
|
+
* This is returned when the agent completes successfully without interruption.
|
|
1187
|
+
*
|
|
1188
|
+
* @category Agent
|
|
1189
|
+
*/
|
|
1190
|
+
export interface GenerateResultComplete {
|
|
1191
|
+
/** Status indicating the generation completed successfully */
|
|
1192
|
+
status: "complete";
|
|
1193
|
+
/** The generated text */
|
|
1194
|
+
text: string;
|
|
1195
|
+
/** Token usage information (AI SDK type) */
|
|
1196
|
+
usage?: LanguageModelUsage;
|
|
1197
|
+
/** Reason why generation finished */
|
|
1198
|
+
finishReason: FinishReason;
|
|
1199
|
+
/** Structured output if responseSchema was provided */
|
|
1200
|
+
output?: unknown;
|
|
1201
|
+
/** All steps from the generation (includes tool calls) */
|
|
1202
|
+
steps: GenerateStep[];
|
|
1203
|
+
/** New session ID if session was forked via forkSession option */
|
|
1204
|
+
forkedSessionId?: string;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Partial result data available when generation is interrupted.
|
|
1208
|
+
*
|
|
1209
|
+
* @category Agent
|
|
1210
|
+
*/
|
|
1211
|
+
export interface PartialGenerateResult {
|
|
1212
|
+
/** Text generated before the interrupt */
|
|
1213
|
+
text: string;
|
|
1214
|
+
/** Steps completed before the interrupt */
|
|
1215
|
+
steps: GenerateStep[];
|
|
1216
|
+
/** Token usage up to the point of interruption */
|
|
1217
|
+
usage?: LanguageModelUsage;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Result from an interrupted generation request.
|
|
1221
|
+
*
|
|
1222
|
+
* This is returned when the agent pauses for user input (e.g., tool approval,
|
|
1223
|
+
* custom questions during tool execution).
|
|
1224
|
+
*
|
|
1225
|
+
* @example
|
|
1226
|
+
* ```typescript
|
|
1227
|
+
* const result = await agent.generate({ prompt, threadId });
|
|
1228
|
+
*
|
|
1229
|
+
* if (result.status === "interrupted") {
|
|
1230
|
+
* const { interrupt } = result;
|
|
1231
|
+
*
|
|
1232
|
+
* if (isApprovalInterrupt(interrupt)) {
|
|
1233
|
+
* const approved = await askUser(`Run ${interrupt.request.toolName}?`);
|
|
1234
|
+
* return agent.resume(threadId, interrupt.id, { approved });
|
|
1235
|
+
* }
|
|
1236
|
+
* }
|
|
1237
|
+
* ```
|
|
1238
|
+
*
|
|
1239
|
+
* @category Agent
|
|
1240
|
+
*/
|
|
1241
|
+
export interface GenerateResultInterrupted {
|
|
1242
|
+
/** Status indicating the generation was interrupted */
|
|
1243
|
+
status: "interrupted";
|
|
1244
|
+
/** The interrupt that caused the pause */
|
|
1245
|
+
interrupt: Interrupt;
|
|
1246
|
+
/** Partial results available at the time of interruption */
|
|
1247
|
+
partial?: PartialGenerateResult;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Result from a generation request.
|
|
1251
|
+
*
|
|
1252
|
+
* This is a discriminated union - check `status` to determine the result type:
|
|
1253
|
+
* - `"complete"`: Generation finished successfully
|
|
1254
|
+
* - `"interrupted"`: Generation paused for user input
|
|
1255
|
+
*
|
|
1256
|
+
* @example
|
|
1257
|
+
* ```typescript
|
|
1258
|
+
* const result = await agent.generate({ prompt, threadId });
|
|
1259
|
+
*
|
|
1260
|
+
* if (result.status === "complete") {
|
|
1261
|
+
* console.log(result.text);
|
|
1262
|
+
* } else {
|
|
1263
|
+
* // Handle interrupt
|
|
1264
|
+
* const response = await handleInterrupt(result.interrupt);
|
|
1265
|
+
* return agent.resume(threadId, result.interrupt.id, response);
|
|
1266
|
+
* }
|
|
1267
|
+
* ```
|
|
1268
|
+
*
|
|
1269
|
+
* @category Agent
|
|
1270
|
+
*/
|
|
1271
|
+
export type GenerateResult = GenerateResultComplete | GenerateResultInterrupted;
|
|
1272
|
+
/**
|
|
1273
|
+
* Type guard to check if a generation result is complete.
|
|
1274
|
+
*
|
|
1275
|
+
* @param result - The generation result to check
|
|
1276
|
+
* @returns True if the result is a complete result
|
|
1277
|
+
*
|
|
1278
|
+
* @example
|
|
1279
|
+
* ```typescript
|
|
1280
|
+
* const result = await agent.generate({ prompt, threadId });
|
|
1281
|
+
*
|
|
1282
|
+
* if (isCompleteResult(result)) {
|
|
1283
|
+
* console.log("Generation complete:", result.text);
|
|
1284
|
+
* } else {
|
|
1285
|
+
* console.log("Generation interrupted:", result.interrupt.type);
|
|
1286
|
+
* }
|
|
1287
|
+
* ```
|
|
1288
|
+
*
|
|
1289
|
+
* @category Agent
|
|
1290
|
+
*/
|
|
1291
|
+
export declare function isCompleteResult(result: GenerateResult): result is GenerateResultComplete;
|
|
1292
|
+
/**
|
|
1293
|
+
* Type guard to check if a generation result is interrupted.
|
|
1294
|
+
*
|
|
1295
|
+
* @param result - The generation result to check
|
|
1296
|
+
* @returns True if the result is an interrupted result
|
|
1297
|
+
*
|
|
1298
|
+
* @example
|
|
1299
|
+
* ```typescript
|
|
1300
|
+
* const result = await agent.generate({ prompt, threadId });
|
|
1301
|
+
*
|
|
1302
|
+
* if (isInterruptedResult(result)) {
|
|
1303
|
+
* const { interrupt } = result;
|
|
1304
|
+
* // Handle the interrupt...
|
|
1305
|
+
* }
|
|
1306
|
+
* ```
|
|
1307
|
+
*
|
|
1308
|
+
* @category Agent
|
|
1309
|
+
*/
|
|
1310
|
+
export declare function isInterruptedResult(result: GenerateResult): result is GenerateResultInterrupted;
|
|
1311
|
+
/**
|
|
1312
|
+
* A single step in the generation process.
|
|
1313
|
+
*
|
|
1314
|
+
* @category Agent
|
|
1315
|
+
*/
|
|
1316
|
+
export interface GenerateStep {
|
|
1317
|
+
/** Text generated in this step */
|
|
1318
|
+
text: string;
|
|
1319
|
+
/** Tool calls made in this step */
|
|
1320
|
+
toolCalls: ToolCallResult[];
|
|
1321
|
+
/** Tool results from this step */
|
|
1322
|
+
toolResults: ToolResultPart[];
|
|
1323
|
+
/** Finish reason for this step */
|
|
1324
|
+
finishReason: FinishReason;
|
|
1325
|
+
/** Usage for this step */
|
|
1326
|
+
usage?: LanguageModelUsage;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* A tool call made by the model.
|
|
1330
|
+
*
|
|
1331
|
+
* @category Agent
|
|
1332
|
+
*/
|
|
1333
|
+
export interface ToolCallResult {
|
|
1334
|
+
/** Unique identifier for this tool call */
|
|
1335
|
+
toolCallId: string;
|
|
1336
|
+
/** Name of the tool that was called */
|
|
1337
|
+
toolName: string;
|
|
1338
|
+
/** Arguments passed to the tool */
|
|
1339
|
+
input: unknown;
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Result from a tool execution.
|
|
1343
|
+
*
|
|
1344
|
+
* @category Agent
|
|
1345
|
+
*/
|
|
1346
|
+
export interface ToolResultPart {
|
|
1347
|
+
/** The tool call ID this result corresponds to */
|
|
1348
|
+
toolCallId: string;
|
|
1349
|
+
/** Name of the tool */
|
|
1350
|
+
toolName: string;
|
|
1351
|
+
/** The result from the tool */
|
|
1352
|
+
output: unknown;
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Reason why the model finished generating.
|
|
1356
|
+
*
|
|
1357
|
+
* - `stop` - Model generated a stop sequence or natural end
|
|
1358
|
+
* - `length` - Maximum tokens reached
|
|
1359
|
+
* - `tool-calls` - Model requested tool calls
|
|
1360
|
+
* - `error` - An error occurred
|
|
1361
|
+
* - `other` - Other/unknown reason
|
|
1362
|
+
*
|
|
1363
|
+
* @category Types
|
|
1364
|
+
*/
|
|
1365
|
+
export type FinishReason = "stop" | "length" | "tool-calls" | "error" | "other";
|
|
1366
|
+
/**
|
|
1367
|
+
* Core tool names that can be disabled.
|
|
1368
|
+
*
|
|
1369
|
+
* @category Types
|
|
1370
|
+
*/
|
|
1371
|
+
export type CoreToolName = "read" | "write" | "edit" | "glob" | "grep" | "bash" | "todo_write" | "task" | "skill" | "search_tools";
|
|
1372
|
+
/**
|
|
1373
|
+
* A part from streaming generation.
|
|
1374
|
+
* Aligns with AI SDK stream parts plus agent-specific events.
|
|
1375
|
+
*
|
|
1376
|
+
* @category Agent
|
|
1377
|
+
*/
|
|
1378
|
+
export type StreamPart = {
|
|
1379
|
+
type: "text-delta";
|
|
1380
|
+
text: string;
|
|
1381
|
+
} | {
|
|
1382
|
+
type: "tool-call";
|
|
1383
|
+
toolCallId: string;
|
|
1384
|
+
toolName: string;
|
|
1385
|
+
input: unknown;
|
|
1386
|
+
} | {
|
|
1387
|
+
type: "tool-result";
|
|
1388
|
+
toolCallId: string;
|
|
1389
|
+
toolName: string;
|
|
1390
|
+
output: unknown;
|
|
1391
|
+
} | {
|
|
1392
|
+
type: "finish";
|
|
1393
|
+
finishReason: FinishReason;
|
|
1394
|
+
usage?: LanguageModelUsage;
|
|
1395
|
+
} | {
|
|
1396
|
+
type: "error";
|
|
1397
|
+
error: Error;
|
|
1398
|
+
} | {
|
|
1399
|
+
type: "subagent-spawn";
|
|
1400
|
+
data: AgentDataTypes["subagent-spawn"];
|
|
1401
|
+
} | {
|
|
1402
|
+
type: "subagent-complete";
|
|
1403
|
+
data: AgentDataTypes["subagent-complete"];
|
|
1404
|
+
} | {
|
|
1405
|
+
type: "agent-progress";
|
|
1406
|
+
data: AgentDataTypes["agent-progress"];
|
|
1407
|
+
};
|
|
1408
|
+
/**
|
|
1409
|
+
* A plugin that extends agent functionality.
|
|
1410
|
+
*
|
|
1411
|
+
* Plugins can provide tools, skills, hooks, and initialization logic.
|
|
1412
|
+
*
|
|
1413
|
+
* @example
|
|
1414
|
+
* ```typescript
|
|
1415
|
+
* const plugin: AgentPlugin = {
|
|
1416
|
+
* name: "my-plugin",
|
|
1417
|
+
* description: "Adds useful tools",
|
|
1418
|
+
* tools: { myTool: tool({ ... }) },
|
|
1419
|
+
* setup: async (agent) => {
|
|
1420
|
+
* console.log("Plugin initialized for agent:", agent.id);
|
|
1421
|
+
* },
|
|
1422
|
+
* };
|
|
1423
|
+
* ```
|
|
1424
|
+
*
|
|
1425
|
+
* @category Plugins
|
|
1426
|
+
*/
|
|
1427
|
+
export interface AgentPlugin {
|
|
1428
|
+
/** Unique name identifying this plugin */
|
|
1429
|
+
name: string;
|
|
1430
|
+
/** Human-readable description of what this plugin does */
|
|
1431
|
+
description?: string;
|
|
1432
|
+
/**
|
|
1433
|
+
* Initialize the plugin when it's loaded into an agent.
|
|
1434
|
+
* @param agent - The agent instance loading this plugin
|
|
1435
|
+
*/
|
|
1436
|
+
setup?(agent: Agent): void | Promise<void>;
|
|
1437
|
+
/**
|
|
1438
|
+
* Tools provided by this plugin.
|
|
1439
|
+
*
|
|
1440
|
+
* Can be a static ToolSet or a function that receives StreamingContext.
|
|
1441
|
+
* Use a function when you need to stream data to the client during tool execution.
|
|
1442
|
+
*
|
|
1443
|
+
* @example
|
|
1444
|
+
* ```typescript
|
|
1445
|
+
* // Static tools (no streaming)
|
|
1446
|
+
* tools: {
|
|
1447
|
+
* myTool: tool({ ... }),
|
|
1448
|
+
* }
|
|
1449
|
+
*
|
|
1450
|
+
* // Streaming-aware tools
|
|
1451
|
+
* tools: (ctx) => ({
|
|
1452
|
+
* myTool: tool({
|
|
1453
|
+
* execute: async (input) => {
|
|
1454
|
+
* if (ctx.writer) {
|
|
1455
|
+
* ctx.writer.write({ type: "data", value: { type: "progress", value: 50 } });
|
|
1456
|
+
* }
|
|
1457
|
+
* return result;
|
|
1458
|
+
* },
|
|
1459
|
+
* }),
|
|
1460
|
+
* })
|
|
1461
|
+
* ```
|
|
1462
|
+
*/
|
|
1463
|
+
tools?: ToolSet | StreamingToolsFactory;
|
|
1464
|
+
/**
|
|
1465
|
+
* MCP server configuration for external tool integration.
|
|
1466
|
+
*
|
|
1467
|
+
* When provided, the agent will connect to this MCP server and expose
|
|
1468
|
+
* its tools with the naming pattern `mcp__<plugin-name>__<tool-name>`.
|
|
1469
|
+
*
|
|
1470
|
+
* @example
|
|
1471
|
+
* ```typescript
|
|
1472
|
+
* const githubPlugin = definePlugin({
|
|
1473
|
+
* name: "github",
|
|
1474
|
+
* mcpServer: {
|
|
1475
|
+
* type: "stdio",
|
|
1476
|
+
* command: "npx",
|
|
1477
|
+
* args: ["-y", "@modelcontextprotocol/server-github"],
|
|
1478
|
+
* env: { GITHUB_TOKEN: "${GITHUB_TOKEN}" },
|
|
1479
|
+
* },
|
|
1480
|
+
* });
|
|
1481
|
+
* ```
|
|
1482
|
+
*/
|
|
1483
|
+
mcpServer?: MCPServerConfig;
|
|
1484
|
+
/** Skills provided by this plugin */
|
|
1485
|
+
skills?: SkillDefinition[];
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Options for the {@link definePlugin} helper function.
|
|
1489
|
+
*
|
|
1490
|
+
* @category Plugins
|
|
1491
|
+
*/
|
|
1492
|
+
export interface PluginOptions {
|
|
1493
|
+
/** Unique name identifying this plugin */
|
|
1494
|
+
name: string;
|
|
1495
|
+
/** Human-readable description of what this plugin does */
|
|
1496
|
+
description?: string;
|
|
1497
|
+
/**
|
|
1498
|
+
* Initialize the plugin when it's loaded into an agent.
|
|
1499
|
+
* @param agent - The agent instance loading this plugin
|
|
1500
|
+
*/
|
|
1501
|
+
setup?: (agent: Agent) => void | Promise<void>;
|
|
1502
|
+
/**
|
|
1503
|
+
* Tools provided by this plugin.
|
|
1504
|
+
*
|
|
1505
|
+
* Can be a static ToolSet or a function that receives StreamingContext.
|
|
1506
|
+
* Use a function when you need to stream data to the client during tool execution.
|
|
1507
|
+
*/
|
|
1508
|
+
tools?: ToolSet | StreamingToolsFactory;
|
|
1509
|
+
/**
|
|
1510
|
+
* MCP server configuration for external tool integration.
|
|
1511
|
+
*/
|
|
1512
|
+
mcpServer?: MCPServerConfig;
|
|
1513
|
+
/** Skills provided by this plugin */
|
|
1514
|
+
skills?: SkillDefinition[];
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Definition of a skill providing contextual instructions for agents.
|
|
1518
|
+
*
|
|
1519
|
+
* Skills serve multiple purposes:
|
|
1520
|
+
* - **Tool guidance**: Bundle with plugin tools to explain how to use them
|
|
1521
|
+
* - **Instructions only**: Load dynamic instructions without tools
|
|
1522
|
+
* - **Progressive disclosure**: Include tools that load on-demand
|
|
1523
|
+
*
|
|
1524
|
+
* @example
|
|
1525
|
+
* ```typescript
|
|
1526
|
+
* // Skill bundled with plugin tools
|
|
1527
|
+
* const dataSkill: SkillDefinition = {
|
|
1528
|
+
* name: "data-exploration",
|
|
1529
|
+
* description: "Query and visualize data",
|
|
1530
|
+
* prompt: "Use getSchema first to see available columns.",
|
|
1531
|
+
* };
|
|
1532
|
+
*
|
|
1533
|
+
* // Skill with tools for progressive disclosure
|
|
1534
|
+
* const analyzeSkill: SkillDefinition = {
|
|
1535
|
+
* name: "analyze",
|
|
1536
|
+
* description: "Deep code analysis",
|
|
1537
|
+
* prompt: "Perform detailed analysis.",
|
|
1538
|
+
* tools: { lint, typeCheck },
|
|
1539
|
+
* };
|
|
1540
|
+
* ```
|
|
1541
|
+
*
|
|
1542
|
+
* @category Tools
|
|
1543
|
+
*/
|
|
1544
|
+
export interface SkillDefinition {
|
|
1545
|
+
/** Unique name identifying this skill */
|
|
1546
|
+
name: string;
|
|
1547
|
+
/** Description of what this skill does */
|
|
1548
|
+
description: string;
|
|
1549
|
+
/**
|
|
1550
|
+
* The prompt to use when this skill is invoked.
|
|
1551
|
+
* Can be a string or a function that receives arguments and returns a prompt.
|
|
1552
|
+
*/
|
|
1553
|
+
prompt: string | ((args?: string) => string);
|
|
1554
|
+
/** Optional tools that are only available when this skill is active */
|
|
1555
|
+
tools?: ToolSet;
|
|
1556
|
+
}
|
|
1557
|
+
/**
|
|
1558
|
+
* Options for the {@link defineSkill} helper function.
|
|
1559
|
+
*
|
|
1560
|
+
* @category Tools
|
|
1561
|
+
*/
|
|
1562
|
+
export interface SkillOptions {
|
|
1563
|
+
/** Name of the skill */
|
|
1564
|
+
name: string;
|
|
1565
|
+
/** Description of what this skill does */
|
|
1566
|
+
description: string;
|
|
1567
|
+
/** The prompt template */
|
|
1568
|
+
prompt: string | ((args?: string) => string);
|
|
1569
|
+
/** Optional tools specific to this skill (AI SDK ToolSet) */
|
|
1570
|
+
tools?: ToolSet;
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Types of events that can trigger hooks.
|
|
1574
|
+
*
|
|
1575
|
+
* Hook names follow Claude Code conventions for consistency.
|
|
1576
|
+
* @see https://code.claude.com/docs/en/hooks
|
|
1577
|
+
*
|
|
1578
|
+
* @category Hooks
|
|
1579
|
+
*/
|
|
1580
|
+
export type HookEvent = "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreGenerate" | "PostGenerate" | "PostGenerateFailure" | "PreToolUse" | "PostToolUse" | "PostToolUseFailure" | "SubagentStart" | "SubagentStop" | "Stop" | "PreCompact" | "PostCompact" | "PreCheckpointSave" | "PostCheckpointSave" | "PreCheckpointLoad" | "PostCheckpointLoad" | "InterruptRequested" | "InterruptResolved" | "MCPConnectionFailed" | "MCPConnectionRestored" | "ToolRegistered" | "ToolLoadError";
|
|
1581
|
+
/**
|
|
1582
|
+
* Common fields in all hook inputs.
|
|
1583
|
+
* @category Hooks
|
|
1584
|
+
*/
|
|
1585
|
+
export interface BaseHookInput {
|
|
1586
|
+
/** The event type that triggered this hook */
|
|
1587
|
+
hook_event_name: HookEvent;
|
|
1588
|
+
/** Session identifier */
|
|
1589
|
+
session_id: string;
|
|
1590
|
+
/** Current working directory */
|
|
1591
|
+
cwd: string;
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Input for PreToolUse hooks.
|
|
1595
|
+
* @category Hooks
|
|
1596
|
+
*/
|
|
1597
|
+
export interface PreToolUseInput extends BaseHookInput {
|
|
1598
|
+
hook_event_name: "PreToolUse";
|
|
1599
|
+
/** Name of the tool about to be executed */
|
|
1600
|
+
tool_name: string;
|
|
1601
|
+
/** Input parameters for the tool */
|
|
1602
|
+
tool_input: Record<string, unknown>;
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* Input for PostToolUse hooks.
|
|
1606
|
+
* @category Hooks
|
|
1607
|
+
*/
|
|
1608
|
+
export interface PostToolUseInput extends BaseHookInput {
|
|
1609
|
+
hook_event_name: "PostToolUse";
|
|
1610
|
+
/** Name of the tool that was executed */
|
|
1611
|
+
tool_name: string;
|
|
1612
|
+
/** Input parameters for the tool */
|
|
1613
|
+
tool_input: Record<string, unknown>;
|
|
1614
|
+
/** Result from the tool execution */
|
|
1615
|
+
tool_response: unknown;
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Input for PostToolUseFailure hooks.
|
|
1619
|
+
* @category Hooks
|
|
1620
|
+
*/
|
|
1621
|
+
export interface PostToolUseFailureInput extends BaseHookInput {
|
|
1622
|
+
hook_event_name: "PostToolUseFailure";
|
|
1623
|
+
/** Name of the tool that failed */
|
|
1624
|
+
tool_name: string;
|
|
1625
|
+
/** Input parameters for the tool */
|
|
1626
|
+
tool_input: Record<string, unknown>;
|
|
1627
|
+
/** Error message or error object */
|
|
1628
|
+
error: string | Error;
|
|
1629
|
+
}
|
|
1630
|
+
/**
|
|
1631
|
+
* Input for PreGenerate hooks.
|
|
1632
|
+
* @category Hooks
|
|
1633
|
+
*/
|
|
1634
|
+
export interface PreGenerateInput extends BaseHookInput {
|
|
1635
|
+
hook_event_name: "PreGenerate";
|
|
1636
|
+
/** Generation options */
|
|
1637
|
+
options: GenerateOptions;
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Input for PostGenerate hooks.
|
|
1641
|
+
* @category Hooks
|
|
1642
|
+
*/
|
|
1643
|
+
export interface PostGenerateInput extends BaseHookInput {
|
|
1644
|
+
hook_event_name: "PostGenerate";
|
|
1645
|
+
/** Generation options */
|
|
1646
|
+
options: GenerateOptions;
|
|
1647
|
+
/**
|
|
1648
|
+
* Generated result.
|
|
1649
|
+
* Note: PostGenerate is only called for complete results - interrupts
|
|
1650
|
+
* are returned immediately without calling PostGenerate hooks.
|
|
1651
|
+
*/
|
|
1652
|
+
result: GenerateResultComplete;
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* Input for PostGenerateFailure hooks.
|
|
1656
|
+
* @category Hooks
|
|
1657
|
+
*/
|
|
1658
|
+
export interface PostGenerateFailureInput extends BaseHookInput {
|
|
1659
|
+
hook_event_name: "PostGenerateFailure";
|
|
1660
|
+
/** Generation options */
|
|
1661
|
+
options: GenerateOptions;
|
|
1662
|
+
/** Error that occurred */
|
|
1663
|
+
error: Error;
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* Input for SubagentStart hooks.
|
|
1667
|
+
* @category Hooks
|
|
1668
|
+
*/
|
|
1669
|
+
export interface SubagentStartInput extends BaseHookInput {
|
|
1670
|
+
hook_event_name: "SubagentStart";
|
|
1671
|
+
/** Unique identifier for the subagent */
|
|
1672
|
+
agent_id: string;
|
|
1673
|
+
/** Type of subagent */
|
|
1674
|
+
agent_type: string;
|
|
1675
|
+
/** Task prompt for the subagent */
|
|
1676
|
+
prompt?: string;
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* Input for SubagentStop hooks.
|
|
1680
|
+
* @category Hooks
|
|
1681
|
+
*/
|
|
1682
|
+
export interface SubagentStopInput extends BaseHookInput {
|
|
1683
|
+
hook_event_name: "SubagentStop";
|
|
1684
|
+
/** Unique identifier for the subagent */
|
|
1685
|
+
agent_id: string;
|
|
1686
|
+
/** Type of subagent */
|
|
1687
|
+
agent_type: string;
|
|
1688
|
+
/** Result from subagent execution */
|
|
1689
|
+
result?: unknown;
|
|
1690
|
+
/** Error from subagent execution */
|
|
1691
|
+
error?: Error;
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Input for MCPConnectionFailed hooks.
|
|
1695
|
+
* @category Hooks
|
|
1696
|
+
*/
|
|
1697
|
+
export interface MCPConnectionFailedInput extends BaseHookInput {
|
|
1698
|
+
hook_event_name: "MCPConnectionFailed";
|
|
1699
|
+
/** Name of the MCP server that failed to connect */
|
|
1700
|
+
server_name: string;
|
|
1701
|
+
/** Server configuration */
|
|
1702
|
+
config: MCPServerConfig;
|
|
1703
|
+
/** Error that occurred during connection */
|
|
1704
|
+
error: Error;
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Input for MCPConnectionRestored hooks.
|
|
1708
|
+
* @category Hooks
|
|
1709
|
+
*/
|
|
1710
|
+
export interface MCPConnectionRestoredInput extends BaseHookInput {
|
|
1711
|
+
hook_event_name: "MCPConnectionRestored";
|
|
1712
|
+
/** Name of the MCP server that was restored */
|
|
1713
|
+
server_name: string;
|
|
1714
|
+
/** Number of tools now available from this server */
|
|
1715
|
+
tool_count: number;
|
|
1716
|
+
}
|
|
1717
|
+
/**
|
|
1718
|
+
* Input for ToolRegistered hooks.
|
|
1719
|
+
* @category Hooks
|
|
1720
|
+
*/
|
|
1721
|
+
export interface ToolRegisteredInput extends BaseHookInput {
|
|
1722
|
+
hook_event_name: "ToolRegistered";
|
|
1723
|
+
/** Name of the tool that was registered */
|
|
1724
|
+
tool_name: string;
|
|
1725
|
+
/** Tool description */
|
|
1726
|
+
description: string;
|
|
1727
|
+
/** Source plugin or server (if any) */
|
|
1728
|
+
source?: string;
|
|
1729
|
+
}
|
|
1730
|
+
/**
|
|
1731
|
+
* Input for ToolLoadError hooks.
|
|
1732
|
+
* @category Hooks
|
|
1733
|
+
*/
|
|
1734
|
+
export interface ToolLoadErrorInput extends BaseHookInput {
|
|
1735
|
+
hook_event_name: "ToolLoadError";
|
|
1736
|
+
/** Name of the tool that failed to load */
|
|
1737
|
+
tool_name: string;
|
|
1738
|
+
/** Error that occurred during loading */
|
|
1739
|
+
error: Error;
|
|
1740
|
+
/** Source plugin or server (if any) */
|
|
1741
|
+
source?: string;
|
|
1742
|
+
}
|
|
1743
|
+
/**
|
|
1744
|
+
* Input for PreCompact hooks.
|
|
1745
|
+
* @category Hooks
|
|
1746
|
+
*/
|
|
1747
|
+
export interface PreCompactInput extends BaseHookInput {
|
|
1748
|
+
hook_event_name: "PreCompact";
|
|
1749
|
+
/** Number of messages before compaction */
|
|
1750
|
+
message_count: number;
|
|
1751
|
+
/** Estimated token count before compaction */
|
|
1752
|
+
tokens_before: number;
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Input for PostCompact hooks.
|
|
1756
|
+
* @category Hooks
|
|
1757
|
+
*/
|
|
1758
|
+
export interface PostCompactInput extends BaseHookInput {
|
|
1759
|
+
hook_event_name: "PostCompact";
|
|
1760
|
+
/** Number of messages before compaction */
|
|
1761
|
+
messages_before: number;
|
|
1762
|
+
/** Number of messages after compaction */
|
|
1763
|
+
messages_after: number;
|
|
1764
|
+
/** Token count before compaction */
|
|
1765
|
+
tokens_before: number;
|
|
1766
|
+
/** Token count after compaction */
|
|
1767
|
+
tokens_after: number;
|
|
1768
|
+
/** Token savings from compaction */
|
|
1769
|
+
tokens_saved: number;
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Input for InterruptRequested hooks.
|
|
1773
|
+
*
|
|
1774
|
+
* Emitted when an interrupt is created (approval request, custom interrupt, etc.).
|
|
1775
|
+
* @category Hooks
|
|
1776
|
+
*/
|
|
1777
|
+
export interface InterruptRequestedInput extends BaseHookInput {
|
|
1778
|
+
hook_event_name: "InterruptRequested";
|
|
1779
|
+
/** Unique identifier for the interrupt */
|
|
1780
|
+
interrupt_id: string;
|
|
1781
|
+
/** Type of interrupt (e.g., "approval", "custom") */
|
|
1782
|
+
interrupt_type: string;
|
|
1783
|
+
/** Tool call ID if related to a tool call */
|
|
1784
|
+
tool_call_id?: string;
|
|
1785
|
+
/** Tool name if related to a tool call */
|
|
1786
|
+
tool_name?: string;
|
|
1787
|
+
/** The interrupt request data */
|
|
1788
|
+
request: unknown;
|
|
1789
|
+
}
|
|
1790
|
+
/**
|
|
1791
|
+
* Input for InterruptResolved hooks.
|
|
1792
|
+
*
|
|
1793
|
+
* Emitted when an interrupt is resolved (approved, denied, or custom response).
|
|
1794
|
+
* @category Hooks
|
|
1795
|
+
*/
|
|
1796
|
+
export interface InterruptResolvedInput extends BaseHookInput {
|
|
1797
|
+
hook_event_name: "InterruptResolved";
|
|
1798
|
+
/** Unique identifier for the interrupt */
|
|
1799
|
+
interrupt_id: string;
|
|
1800
|
+
/** Type of interrupt (e.g., "approval", "custom") */
|
|
1801
|
+
interrupt_type: string;
|
|
1802
|
+
/** Tool call ID if related to a tool call */
|
|
1803
|
+
tool_call_id?: string;
|
|
1804
|
+
/** Tool name if related to a tool call */
|
|
1805
|
+
tool_name?: string;
|
|
1806
|
+
/** The response that resolved the interrupt */
|
|
1807
|
+
response: unknown;
|
|
1808
|
+
/** For approval interrupts: whether the request was approved */
|
|
1809
|
+
approved?: boolean;
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Union type of all hook input types.
|
|
1813
|
+
* @category Hooks
|
|
1814
|
+
*/
|
|
1815
|
+
export type HookInput = PreToolUseInput | PostToolUseInput | PostToolUseFailureInput | PreGenerateInput | PostGenerateInput | PostGenerateFailureInput | SubagentStartInput | SubagentStopInput | MCPConnectionFailedInput | MCPConnectionRestoredInput | ToolRegisteredInput | ToolLoadErrorInput | PreCompactInput | PostCompactInput | InterruptRequestedInput | InterruptResolvedInput;
|
|
1816
|
+
/**
|
|
1817
|
+
* Permission decision for a tool or generation operation.
|
|
1818
|
+
* @category Hooks
|
|
1819
|
+
*/
|
|
1820
|
+
export type PermissionDecision = "allow" | "deny" | "ask";
|
|
1821
|
+
/**
|
|
1822
|
+
* Permission mode controlling default tool approval behavior.
|
|
1823
|
+
*
|
|
1824
|
+
* Aligned with Claude Agent SDK permission modes:
|
|
1825
|
+
* - `default`: Unmatched tools trigger canUseTool callback or hooks
|
|
1826
|
+
* - `acceptEdits`: Auto-approve file edit operations (Write, Edit, filesystem commands)
|
|
1827
|
+
* - `bypassPermissions`: Auto-approve all tools (dangerous - use only for testing/demos)
|
|
1828
|
+
* - `plan`: Block all tool execution (planning/analysis only)
|
|
1829
|
+
*
|
|
1830
|
+
* @category Permissions
|
|
1831
|
+
*/
|
|
1832
|
+
export type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";
|
|
1833
|
+
/**
|
|
1834
|
+
* Hook-specific output that controls operation behavior.
|
|
1835
|
+
* @category Hooks
|
|
1836
|
+
*/
|
|
1837
|
+
export interface HookSpecificOutput {
|
|
1838
|
+
/** Required: identifies which hook type this output is for */
|
|
1839
|
+
hookEventName: HookEvent;
|
|
1840
|
+
/** Permission decision for the operation */
|
|
1841
|
+
permissionDecision?: PermissionDecision;
|
|
1842
|
+
/** Explanation for the decision (shown to model and logs) */
|
|
1843
|
+
permissionDecisionReason?: string;
|
|
1844
|
+
/** Message IDs that caused the block (for client-side cleanup) */
|
|
1845
|
+
blockedMessageIds?: string[];
|
|
1846
|
+
/** Modified input (PreToolUse: tool input, PreGenerate: options) */
|
|
1847
|
+
updatedInput?: unknown;
|
|
1848
|
+
/** Short-circuit with cached/mock result (skips actual execution) */
|
|
1849
|
+
respondWith?: unknown;
|
|
1850
|
+
/** Modified output (transform result before returning) */
|
|
1851
|
+
updatedResult?: unknown;
|
|
1852
|
+
/** Signal to retry the failed operation */
|
|
1853
|
+
retry?: boolean;
|
|
1854
|
+
/** Delay before retry in milliseconds */
|
|
1855
|
+
retryDelayMs?: number;
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* Output from a hook callback.
|
|
1859
|
+
*
|
|
1860
|
+
* Hooks return control information via `hookSpecificOutput`, which contains
|
|
1861
|
+
* event-specific fields like permission decisions, input/output transformations,
|
|
1862
|
+
* cache responses, and retry signals.
|
|
1863
|
+
*
|
|
1864
|
+
* @category Hooks
|
|
1865
|
+
*/
|
|
1866
|
+
export interface HookOutput {
|
|
1867
|
+
/** Hook-specific control fields */
|
|
1868
|
+
hookSpecificOutput?: HookSpecificOutput;
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* Context passed to hook callbacks.
|
|
1872
|
+
* @category Hooks
|
|
1873
|
+
*/
|
|
1874
|
+
export interface HookCallbackContext {
|
|
1875
|
+
/** AbortSignal for cancellation (pass to fetch, etc.) */
|
|
1876
|
+
signal: AbortSignal;
|
|
1877
|
+
/** Agent instance */
|
|
1878
|
+
agent: Agent;
|
|
1879
|
+
/** Current retry attempt (0 = first attempt) */
|
|
1880
|
+
retryAttempt?: number;
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* Hook callback function signature.
|
|
1884
|
+
* @category Hooks
|
|
1885
|
+
*/
|
|
1886
|
+
export type HookCallback = (input: HookInput, toolUseId: string | null, context: HookCallbackContext) => Promise<HookOutput> | HookOutput;
|
|
1887
|
+
/**
|
|
1888
|
+
* Matcher for filtering which tools trigger hooks.
|
|
1889
|
+
* @category Hooks
|
|
1890
|
+
*/
|
|
1891
|
+
export interface HookMatcher {
|
|
1892
|
+
/**
|
|
1893
|
+
* Regex pattern to match tool names (omit for all tools).
|
|
1894
|
+
* Examples:
|
|
1895
|
+
* - 'Write|Edit' - File modification tools
|
|
1896
|
+
* - '^mcp__' - All MCP tools
|
|
1897
|
+
* - 'mcp__playwright__' - Specific MCP server
|
|
1898
|
+
* - undefined - All tools (no filter)
|
|
1899
|
+
*/
|
|
1900
|
+
matcher?: string;
|
|
1901
|
+
/** Hook callbacks to run when pattern matches */
|
|
1902
|
+
hooks: HookCallback[];
|
|
1903
|
+
/**
|
|
1904
|
+
* Timeout in milliseconds for hook execution.
|
|
1905
|
+
* @defaultValue 60000 (60 seconds)
|
|
1906
|
+
*/
|
|
1907
|
+
timeout?: number;
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Configuration for registering hooks with matchers.
|
|
1911
|
+
* @category Hooks
|
|
1912
|
+
*/
|
|
1913
|
+
export interface HookRegistration {
|
|
1914
|
+
/**
|
|
1915
|
+
* Tool lifecycle hooks with matchers.
|
|
1916
|
+
* Array of matchers, each with optional regex pattern and hook callbacks.
|
|
1917
|
+
*/
|
|
1918
|
+
PreToolUse?: HookMatcher[];
|
|
1919
|
+
PostToolUse?: HookMatcher[];
|
|
1920
|
+
PostToolUseFailure?: HookMatcher[];
|
|
1921
|
+
/**
|
|
1922
|
+
* Generation lifecycle hooks (no matchers - not tool-specific).
|
|
1923
|
+
* Array of hook callbacks.
|
|
1924
|
+
*/
|
|
1925
|
+
PreGenerate?: HookCallback[];
|
|
1926
|
+
PostGenerate?: HookCallback[];
|
|
1927
|
+
PostGenerateFailure?: HookCallback[];
|
|
1928
|
+
/**
|
|
1929
|
+
* Session lifecycle hooks.
|
|
1930
|
+
* Array of hook callbacks.
|
|
1931
|
+
*/
|
|
1932
|
+
SessionStart?: HookCallback[];
|
|
1933
|
+
SessionEnd?: HookCallback[];
|
|
1934
|
+
/**
|
|
1935
|
+
* Subagent lifecycle hooks.
|
|
1936
|
+
* Array of hook callbacks.
|
|
1937
|
+
*/
|
|
1938
|
+
SubagentStart?: HookCallback[];
|
|
1939
|
+
SubagentStop?: HookCallback[];
|
|
1940
|
+
/**
|
|
1941
|
+
* MCP connection lifecycle hooks.
|
|
1942
|
+
* Array of hook callbacks.
|
|
1943
|
+
*/
|
|
1944
|
+
MCPConnectionFailed?: HookCallback[];
|
|
1945
|
+
MCPConnectionRestored?: HookCallback[];
|
|
1946
|
+
/**
|
|
1947
|
+
* Tool registry lifecycle hooks.
|
|
1948
|
+
* Array of hook callbacks.
|
|
1949
|
+
*/
|
|
1950
|
+
ToolRegistered?: HookCallback[];
|
|
1951
|
+
ToolLoadError?: HookCallback[];
|
|
1952
|
+
/**
|
|
1953
|
+
* Context compaction lifecycle hooks.
|
|
1954
|
+
* Array of hook callbacks.
|
|
1955
|
+
*/
|
|
1956
|
+
PreCompact?: HookCallback[];
|
|
1957
|
+
PostCompact?: HookCallback[];
|
|
1958
|
+
/**
|
|
1959
|
+
* Interrupt lifecycle hooks.
|
|
1960
|
+
* Called when interrupts are requested (approval, custom) and resolved.
|
|
1961
|
+
*/
|
|
1962
|
+
InterruptRequested?: HookCallback[];
|
|
1963
|
+
InterruptResolved?: HookCallback[];
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* Configuration for creating a subagent.
|
|
1967
|
+
*
|
|
1968
|
+
* @category Subagents
|
|
1969
|
+
*/
|
|
1970
|
+
export interface SubagentOptions extends Omit<AgentOptions, "model" | "allowedTools"> {
|
|
1971
|
+
/** Name for the subagent */
|
|
1972
|
+
name: string;
|
|
1973
|
+
/** Description of what this subagent does */
|
|
1974
|
+
description: string;
|
|
1975
|
+
/** Model to use (inherits from parent if not specified) */
|
|
1976
|
+
model?: LanguageModel;
|
|
1977
|
+
/**
|
|
1978
|
+
* Control hook inheritance from parent agent.
|
|
1979
|
+
*
|
|
1980
|
+
* Options:
|
|
1981
|
+
* - `true`: Inherit all hooks from parent (default for backward compatibility)
|
|
1982
|
+
* - `false`: No hook inheritance, use only hooks defined in this subagent
|
|
1983
|
+
* - `string[]`: Inherit only specific hook events (e.g., ["PreToolUse", "PostGenerate"])
|
|
1984
|
+
*
|
|
1985
|
+
* @example
|
|
1986
|
+
* ```typescript
|
|
1987
|
+
* // Inherit all hooks from parent
|
|
1988
|
+
* const subagent1 = createSubagent(parentAgent, {
|
|
1989
|
+
* name: "helper",
|
|
1990
|
+
* description: "Inherits parent hooks",
|
|
1991
|
+
* inheritHooks: true, // Default
|
|
1992
|
+
* });
|
|
1993
|
+
*
|
|
1994
|
+
* // No hook inheritance - isolated execution
|
|
1995
|
+
* const subagent2 = createSubagent(parentAgent, {
|
|
1996
|
+
* name: "sandbox",
|
|
1997
|
+
* description: "Runs without parent hooks",
|
|
1998
|
+
* inheritHooks: false,
|
|
1999
|
+
* });
|
|
2000
|
+
*
|
|
2001
|
+
* // Selective inheritance - only tool hooks
|
|
2002
|
+
* const subagent3 = createSubagent(parentAgent, {
|
|
2003
|
+
* name: "monitored",
|
|
2004
|
+
* description: "Inherits only tool lifecycle hooks",
|
|
2005
|
+
* inheritHooks: ["PreToolUse", "PostToolUse", "PostToolUseFailure"],
|
|
2006
|
+
* });
|
|
2007
|
+
* ```
|
|
2008
|
+
*
|
|
2009
|
+
* @defaultValue true
|
|
2010
|
+
*/
|
|
2011
|
+
inheritHooks?: boolean | HookEvent[];
|
|
2012
|
+
/**
|
|
2013
|
+
* Restrict which tools this subagent can use.
|
|
2014
|
+
*
|
|
2015
|
+
* When provided, only tools whose names are in this array will be
|
|
2016
|
+
* available to the subagent. This applies on top of any tools
|
|
2017
|
+
* inherited from the parent agent.
|
|
2018
|
+
*
|
|
2019
|
+
* @example
|
|
2020
|
+
* ```typescript
|
|
2021
|
+
* const subagent = createSubagent(parentAgent, {
|
|
2022
|
+
* name: "reader",
|
|
2023
|
+
* description: "Read-only research agent",
|
|
2024
|
+
* allowedTools: ["read", "glob", "grep"], // No write access
|
|
2025
|
+
* });
|
|
2026
|
+
* ```
|
|
2027
|
+
*/
|
|
2028
|
+
allowedTools?: string[];
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Configuration for creating a task delegation tool.
|
|
2032
|
+
*
|
|
2033
|
+
* @category Subagents
|
|
2034
|
+
*/
|
|
2035
|
+
export interface TaskToolOptions {
|
|
2036
|
+
/**
|
|
2037
|
+
* Name for the task tool.
|
|
2038
|
+
* @defaultValue "task"
|
|
2039
|
+
*/
|
|
2040
|
+
name?: string;
|
|
2041
|
+
/** Description of what the task tool does */
|
|
2042
|
+
description?: string;
|
|
2043
|
+
/** Available subagent types that can be delegated to */
|
|
2044
|
+
subagents: SubagentDefinition[];
|
|
2045
|
+
}
|
|
2046
|
+
/**
|
|
2047
|
+
* Definition of a subagent type for task delegation.
|
|
2048
|
+
*
|
|
2049
|
+
* @category Subagents
|
|
2050
|
+
*/
|
|
2051
|
+
export interface SubagentDefinition {
|
|
2052
|
+
/** Unique type identifier for this subagent */
|
|
2053
|
+
type: string;
|
|
2054
|
+
/** Description of what this subagent specializes in */
|
|
2055
|
+
description: string;
|
|
2056
|
+
/**
|
|
2057
|
+
* Model to use for this subagent.
|
|
2058
|
+
*
|
|
2059
|
+
* - If not specified, inherits from parent agent
|
|
2060
|
+
* - Use `"inherit"` to explicitly inherit from parent
|
|
2061
|
+
* - Provide a LanguageModel instance to override
|
|
2062
|
+
*
|
|
2063
|
+
* @example
|
|
2064
|
+
* ```typescript
|
|
2065
|
+
* const subagents = [
|
|
2066
|
+
* {
|
|
2067
|
+
* type: "fast-researcher",
|
|
2068
|
+
* description: "Quick research tasks",
|
|
2069
|
+
* model: anthropic("claude-haiku-4.5"), // Use faster model
|
|
2070
|
+
* },
|
|
2071
|
+
* {
|
|
2072
|
+
* type: "deep-analyst",
|
|
2073
|
+
* description: "Complex analysis",
|
|
2074
|
+
* model: anthropic("claude-sonnet-4-20250514"), // Use more capable model
|
|
2075
|
+
* },
|
|
2076
|
+
* ];
|
|
2077
|
+
* ```
|
|
2078
|
+
*/
|
|
2079
|
+
model?: LanguageModel | "inherit";
|
|
2080
|
+
/**
|
|
2081
|
+
* Restrict which tools this subagent can use.
|
|
2082
|
+
*
|
|
2083
|
+
* When provided, only the specified tools will be available to
|
|
2084
|
+
* the subagent, even if more tools are available in the parent.
|
|
2085
|
+
* This provides security and context control for delegated tasks.
|
|
2086
|
+
*
|
|
2087
|
+
* @example
|
|
2088
|
+
* ```typescript
|
|
2089
|
+
* const subagents = [
|
|
2090
|
+
* {
|
|
2091
|
+
* type: "reader",
|
|
2092
|
+
* description: "Read-only research agent",
|
|
2093
|
+
* allowedTools: ["read", "glob", "grep"], // No write access
|
|
2094
|
+
* },
|
|
2095
|
+
* {
|
|
2096
|
+
* type: "coder",
|
|
2097
|
+
* description: "Code writing agent",
|
|
2098
|
+
* allowedTools: ["read", "write", "edit", "bash"],
|
|
2099
|
+
* },
|
|
2100
|
+
* ];
|
|
2101
|
+
* ```
|
|
2102
|
+
*/
|
|
2103
|
+
allowedTools?: string[];
|
|
2104
|
+
/**
|
|
2105
|
+
* Plugins to load for this subagent.
|
|
2106
|
+
*
|
|
2107
|
+
* Unlike tools inherited from the parent, these plugins are loaded
|
|
2108
|
+
* exclusively for this subagent. This is useful for giving a subagent
|
|
2109
|
+
* access to an MCP server without polluting the parent's tool set.
|
|
2110
|
+
*
|
|
2111
|
+
* @example
|
|
2112
|
+
* ```typescript
|
|
2113
|
+
* const subagents = [
|
|
2114
|
+
* {
|
|
2115
|
+
* type: "web-researcher",
|
|
2116
|
+
* description: "Web research specialist",
|
|
2117
|
+
* plugins: [webSearchPlugin], // Only this subagent gets web search
|
|
2118
|
+
* allowedTools: [webSearch("search")],
|
|
2119
|
+
* create: (ctx) => createSubagent(parentAgent, {
|
|
2120
|
+
* name: "web-researcher",
|
|
2121
|
+
* plugins: ctx.plugins,
|
|
2122
|
+
* allowedTools: ctx.allowedTools,
|
|
2123
|
+
* }),
|
|
2124
|
+
* },
|
|
2125
|
+
* ];
|
|
2126
|
+
* ```
|
|
2127
|
+
*/
|
|
2128
|
+
plugins?: PluginOptions[];
|
|
2129
|
+
/**
|
|
2130
|
+
* Enable streaming from this subagent to the parent's data stream.
|
|
2131
|
+
*
|
|
2132
|
+
* When true, the subagent receives a StreamingContext and can write
|
|
2133
|
+
* custom data directly to the parent's stream. This enables:
|
|
2134
|
+
* - Progressive UI rendering
|
|
2135
|
+
* - Real-time progress updates
|
|
2136
|
+
* - Streaming structured data to the client
|
|
2137
|
+
*
|
|
2138
|
+
* The streaming context includes metadata identifying this subagent
|
|
2139
|
+
* as the source, similar to LangGraph's namespace pattern.
|
|
2140
|
+
*
|
|
2141
|
+
* @defaultValue false
|
|
2142
|
+
*
|
|
2143
|
+
* @example
|
|
2144
|
+
* ```typescript
|
|
2145
|
+
* const subagents = [
|
|
2146
|
+
* {
|
|
2147
|
+
* type: "ui-builder",
|
|
2148
|
+
* description: "Generates UI components with streaming",
|
|
2149
|
+
* streaming: true,
|
|
2150
|
+
* create: (ctx) => createSubagent(parentAgent, {
|
|
2151
|
+
* name: "ui-builder",
|
|
2152
|
+
* systemPrompt: generateCatalogPrompt(catalog),
|
|
2153
|
+
* // Subagent can use ctx.streamingContext.writer
|
|
2154
|
+
* }),
|
|
2155
|
+
* },
|
|
2156
|
+
* ];
|
|
2157
|
+
* ```
|
|
2158
|
+
*/
|
|
2159
|
+
streaming?: boolean;
|
|
2160
|
+
/**
|
|
2161
|
+
* Factory function to create the subagent.
|
|
2162
|
+
*
|
|
2163
|
+
* Receives a context object containing the resolved model and any
|
|
2164
|
+
* tool restrictions. Use these values when calling createSubagent.
|
|
2165
|
+
*
|
|
2166
|
+
* @param context - Context for subagent creation
|
|
2167
|
+
* @returns The subagent instance
|
|
2168
|
+
*
|
|
2169
|
+
* @example
|
|
2170
|
+
* ```typescript
|
|
2171
|
+
* const subagents = [
|
|
2172
|
+
* {
|
|
2173
|
+
* type: "researcher",
|
|
2174
|
+
* description: "Research agent",
|
|
2175
|
+
* model: anthropic("claude-haiku-4.5"),
|
|
2176
|
+
* allowedTools: ["read", "glob", "grep"],
|
|
2177
|
+
* create: (ctx) => createSubagent(parentAgent, {
|
|
2178
|
+
* name: "researcher",
|
|
2179
|
+
* description: "Research agent",
|
|
2180
|
+
* model: ctx.model, // Use resolved model
|
|
2181
|
+
* allowedTools: ctx.allowedTools, // Use tool restrictions
|
|
2182
|
+
* }),
|
|
2183
|
+
* },
|
|
2184
|
+
* ];
|
|
2185
|
+
* ```
|
|
2186
|
+
*/
|
|
2187
|
+
create: (context: SubagentCreateContext) => Agent | Promise<Agent>;
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Context passed to subagent factory functions.
|
|
2191
|
+
*
|
|
2192
|
+
* @category Subagents
|
|
2193
|
+
*/
|
|
2194
|
+
export interface SubagentCreateContext {
|
|
2195
|
+
/**
|
|
2196
|
+
* The resolved model to use for the subagent.
|
|
2197
|
+
*
|
|
2198
|
+
* This is determined by priority:
|
|
2199
|
+
* 1. SubagentDefinition.model (if not "inherit")
|
|
2200
|
+
* 2. TaskToolOptions.defaultModel
|
|
2201
|
+
* 3. Parent agent's model
|
|
2202
|
+
*/
|
|
2203
|
+
model: LanguageModel;
|
|
2204
|
+
/**
|
|
2205
|
+
* Tool restrictions for this subagent, if any.
|
|
2206
|
+
* Comes from SubagentDefinition.allowedTools.
|
|
2207
|
+
*/
|
|
2208
|
+
allowedTools?: string[];
|
|
2209
|
+
/**
|
|
2210
|
+
* Plugins to load for this subagent.
|
|
2211
|
+
* Comes from SubagentDefinition.plugins.
|
|
2212
|
+
*/
|
|
2213
|
+
plugins?: PluginOptions[];
|
|
2214
|
+
/**
|
|
2215
|
+
* Streaming context from the parent agent.
|
|
2216
|
+
*
|
|
2217
|
+
* Only provided when SubagentDefinition.streaming is true and the
|
|
2218
|
+
* parent agent is using streamDataResponse(). Allows the subagent
|
|
2219
|
+
* to write custom data directly to the parent's data stream.
|
|
2220
|
+
*
|
|
2221
|
+
* The context includes metadata identifying this subagent as the
|
|
2222
|
+
* source of any streamed data.
|
|
2223
|
+
*
|
|
2224
|
+
* @example
|
|
2225
|
+
* ```typescript
|
|
2226
|
+
* create: (ctx) => {
|
|
2227
|
+
* // Subagent can pass streaming context to its tools
|
|
2228
|
+
* const tools = createStreamingTools(ctx.streamingContext);
|
|
2229
|
+
* return createSubagent(parent, { tools });
|
|
2230
|
+
* }
|
|
2231
|
+
* ```
|
|
2232
|
+
*/
|
|
2233
|
+
streamingContext?: StreamingContext;
|
|
2234
|
+
/**
|
|
2235
|
+
* Parent span context for distributed tracing.
|
|
2236
|
+
*
|
|
2237
|
+
* When provided, the subagent should create child spans linked to
|
|
2238
|
+
* this parent span, enabling cross-agent trace correlation in
|
|
2239
|
+
* distributed tracing systems.
|
|
2240
|
+
*
|
|
2241
|
+
* This allows you to track the full request flow across parent
|
|
2242
|
+
* and child agents in tools like Jaeger, Zipkin, or OpenTelemetry
|
|
2243
|
+
* collectors.
|
|
2244
|
+
*
|
|
2245
|
+
* @example
|
|
2246
|
+
* ```typescript
|
|
2247
|
+
* import { createTracer, SemanticAttributes } from "@lleverage-ai/agent-sdk";
|
|
2248
|
+
*
|
|
2249
|
+
* const tracer = createTracer({ name: "my-agent" });
|
|
2250
|
+
*
|
|
2251
|
+
* const subagentDef: SubagentDefinition = {
|
|
2252
|
+
* type: "researcher",
|
|
2253
|
+
* create: (ctx) => {
|
|
2254
|
+
* const subagent = createSubagent(parentAgent, { ... });
|
|
2255
|
+
*
|
|
2256
|
+
* // Create child spans from parent context
|
|
2257
|
+
* if (ctx.parentSpanContext) {
|
|
2258
|
+
* const span = tracer.startSpan("subagent-execution", {
|
|
2259
|
+
* parent: ctx.parentSpanContext,
|
|
2260
|
+
* attributes: {
|
|
2261
|
+
* [SemanticAttributes.SUBAGENT_TYPE]: "researcher",
|
|
2262
|
+
* },
|
|
2263
|
+
* });
|
|
2264
|
+
* // ... perform work ...
|
|
2265
|
+
* span.end();
|
|
2266
|
+
* }
|
|
2267
|
+
*
|
|
2268
|
+
* return subagent;
|
|
2269
|
+
* },
|
|
2270
|
+
* };
|
|
2271
|
+
* ```
|
|
2272
|
+
*/
|
|
2273
|
+
parentSpanContext?: import("./observability/tracing.js").SpanContext;
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* Context for managing state during agent execution.
|
|
2277
|
+
*
|
|
2278
|
+
* @example
|
|
2279
|
+
* ```typescript
|
|
2280
|
+
* const ctx = createContext();
|
|
2281
|
+
* ctx.set("user", { id: 123, name: "Alice" });
|
|
2282
|
+
*
|
|
2283
|
+
* const user = ctx.get<{ id: number; name: string }>("user");
|
|
2284
|
+
* ```
|
|
2285
|
+
*
|
|
2286
|
+
* @category Context
|
|
2287
|
+
*/
|
|
2288
|
+
export interface AgentContext {
|
|
2289
|
+
/** The underlying data store */
|
|
2290
|
+
data: Map<string, unknown>;
|
|
2291
|
+
/**
|
|
2292
|
+
* Get a value from context.
|
|
2293
|
+
* @typeParam T - The expected type of the value
|
|
2294
|
+
* @param key - The key to look up
|
|
2295
|
+
* @returns The value, or undefined if not found
|
|
2296
|
+
*/
|
|
2297
|
+
get<T>(key: string): T | undefined;
|
|
2298
|
+
/**
|
|
2299
|
+
* Set a value in context.
|
|
2300
|
+
* @typeParam T - The type of the value
|
|
2301
|
+
* @param key - The key to set
|
|
2302
|
+
* @param value - The value to store
|
|
2303
|
+
*/
|
|
2304
|
+
set<T>(key: string, value: T): void;
|
|
2305
|
+
/**
|
|
2306
|
+
* Check if a key exists in context.
|
|
2307
|
+
* @param key - The key to check
|
|
2308
|
+
*/
|
|
2309
|
+
has(key: string): boolean;
|
|
2310
|
+
/**
|
|
2311
|
+
* Delete a key from context.
|
|
2312
|
+
* @param key - The key to delete
|
|
2313
|
+
* @returns True if the key existed and was deleted
|
|
2314
|
+
*/
|
|
2315
|
+
delete(key: string): boolean;
|
|
2316
|
+
/** Clear all values from context. */
|
|
2317
|
+
clear(): void;
|
|
2318
|
+
}
|
|
2319
|
+
/**
|
|
2320
|
+
* Base configuration for MCP servers.
|
|
2321
|
+
*
|
|
2322
|
+
* @category MCP
|
|
2323
|
+
*/
|
|
2324
|
+
interface MCPServerConfigBase {
|
|
2325
|
+
/**
|
|
2326
|
+
* Environment variables for the MCP server.
|
|
2327
|
+
* Supports `${VAR}` syntax for expansion at runtime.
|
|
2328
|
+
*/
|
|
2329
|
+
env?: Record<string, string>;
|
|
2330
|
+
/**
|
|
2331
|
+
* Security: Allowlist of permitted tool names from this server.
|
|
2332
|
+
* If specified, only tools in this list will be loaded and available for use.
|
|
2333
|
+
* Tool names should be the original names (without the mcp__ prefix).
|
|
2334
|
+
*
|
|
2335
|
+
* @example
|
|
2336
|
+
* ```typescript
|
|
2337
|
+
* // Only allow specific GitHub tools
|
|
2338
|
+
* allowedTools: ["get_issue", "list_issues"]
|
|
2339
|
+
* ```
|
|
2340
|
+
*/
|
|
2341
|
+
allowedTools?: string[];
|
|
2342
|
+
/**
|
|
2343
|
+
* Security: Validate tool inputs against their declared JSON Schema.
|
|
2344
|
+
* When enabled, tool inputs will be validated before execution.
|
|
2345
|
+
* Invalid inputs will throw an error instead of being passed to the server.
|
|
2346
|
+
*
|
|
2347
|
+
* @default false
|
|
2348
|
+
*/
|
|
2349
|
+
validateInputs?: boolean;
|
|
2350
|
+
/**
|
|
2351
|
+
* Security: Reject tools that don't have a proper input schema.
|
|
2352
|
+
* When enabled, tools without schemas or with empty schemas will not be loaded.
|
|
2353
|
+
* Useful for enforcing that all tools have explicit input validation.
|
|
2354
|
+
*
|
|
2355
|
+
* @default false
|
|
2356
|
+
*/
|
|
2357
|
+
requireSchema?: boolean;
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Configuration for stdio-based MCP servers.
|
|
2361
|
+
* These run as local processes communicating via stdin/stdout.
|
|
2362
|
+
*
|
|
2363
|
+
* @example
|
|
2364
|
+
* ```typescript
|
|
2365
|
+
* const config: StdioMCPServerConfig = {
|
|
2366
|
+
* type: "stdio",
|
|
2367
|
+
* command: "npx",
|
|
2368
|
+
* args: ["-y", "@modelcontextprotocol/server-github"],
|
|
2369
|
+
* env: { GITHUB_TOKEN: "${GITHUB_TOKEN}" },
|
|
2370
|
+
* };
|
|
2371
|
+
* ```
|
|
2372
|
+
*
|
|
2373
|
+
* @category MCP
|
|
2374
|
+
*/
|
|
2375
|
+
export interface StdioMCPServerConfig extends MCPServerConfigBase {
|
|
2376
|
+
type: "stdio";
|
|
2377
|
+
/** Command to execute */
|
|
2378
|
+
command: string;
|
|
2379
|
+
/** Arguments for the command */
|
|
2380
|
+
args?: string[];
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Configuration for HTTP-based MCP servers.
|
|
2384
|
+
*
|
|
2385
|
+
* @example
|
|
2386
|
+
* ```typescript
|
|
2387
|
+
* const config: HttpMCPServerConfig = {
|
|
2388
|
+
* type: "http",
|
|
2389
|
+
* url: "https://api.example.com/mcp",
|
|
2390
|
+
* headers: { Authorization: "Bearer ${TOKEN}" },
|
|
2391
|
+
* };
|
|
2392
|
+
* ```
|
|
2393
|
+
*
|
|
2394
|
+
* @category MCP
|
|
2395
|
+
*/
|
|
2396
|
+
export interface HttpMCPServerConfig extends MCPServerConfigBase {
|
|
2397
|
+
type: "http";
|
|
2398
|
+
/** Server URL */
|
|
2399
|
+
url: string;
|
|
2400
|
+
/** HTTP headers (supports ${VAR} expansion) */
|
|
2401
|
+
headers?: Record<string, string>;
|
|
2402
|
+
}
|
|
2403
|
+
/**
|
|
2404
|
+
* Configuration for SSE-based MCP servers (streaming).
|
|
2405
|
+
*
|
|
2406
|
+
* @category MCP
|
|
2407
|
+
*/
|
|
2408
|
+
export interface SseMCPServerConfig extends MCPServerConfigBase {
|
|
2409
|
+
type: "sse";
|
|
2410
|
+
/** Server URL */
|
|
2411
|
+
url: string;
|
|
2412
|
+
/** HTTP headers (supports ${VAR} expansion) */
|
|
2413
|
+
headers?: Record<string, string>;
|
|
2414
|
+
}
|
|
2415
|
+
/**
|
|
2416
|
+
* Union type for all MCP server configurations.
|
|
2417
|
+
*
|
|
2418
|
+
* @category MCP
|
|
2419
|
+
*/
|
|
2420
|
+
export type MCPServerConfig = StdioMCPServerConfig | HttpMCPServerConfig | SseMCPServerConfig;
|
|
2421
|
+
//# sourceMappingURL=types.d.ts.map
|