@huyooo/ai-chat-core 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,22 +1,115 @@
1
+ /**
2
+ * 模型路由模块
3
+ *
4
+ * 根据模型名称将请求路由到对应的 Provider
5
+ *
6
+ * 设计原则:
7
+ * 1. 配置驱动:路由规则集中管理,易于扩展
8
+ * 2. 优先级机制:高优先级规则先匹配
9
+ * 3. 多种匹配模式:支持精确、前缀、包含、正则匹配
10
+ */
11
+ /** Provider 类型(API 供应商) */
12
+ type ProviderType = 'ark' | 'qwen' | 'gemini' | 'openrouter' | 'vercel';
13
+ /** 路由规则匹配类型 */
14
+ type RouteMatchType = 'exact' | 'prefix' | 'contains' | 'regex';
15
+ /** 单条路由规则 */
16
+ interface RouteRule {
17
+ /** 规则类型 */
18
+ type: RouteMatchType;
19
+ /** 匹配模式(大小写不敏感) */
20
+ pattern: string;
21
+ /** 目标 Provider */
22
+ provider: ProviderType;
23
+ /** 规则优先级(数字越大越优先,默认 0) */
24
+ priority: number;
25
+ /** 规则描述(调试用) */
26
+ description?: string;
27
+ }
28
+ /** 路由结果 */
29
+ interface RouteResult {
30
+ /** 匹配的 Provider */
31
+ provider: ProviderType;
32
+ /** 匹配的规则(如果有) */
33
+ matchedRule?: RouteRule;
34
+ /** 是否使用了默认路由 */
35
+ isDefault: boolean;
36
+ }
37
+ /**
38
+ * 将模型路由到对应的 Provider
39
+ *
40
+ * @param model - 模型名称
41
+ * @returns Provider 类型
42
+ */
43
+ declare function routeModelToProvider(model: string): ProviderType;
44
+ /**
45
+ * 将模型路由到对应的 Provider(带详细信息)
46
+ *
47
+ * @param model - 模型名称
48
+ * @returns 路由结果(包含匹配规则信息)
49
+ */
50
+ declare function routeModelWithDetails(model: string): RouteResult;
51
+ /**
52
+ * 获取所有路由规则(调试用)
53
+ */
54
+ declare function getRouteRules(): readonly RouteRule[];
55
+ /**
56
+ * 获取默认 Provider
57
+ */
58
+ declare function getDefaultProvider(): ProviderType;
59
+ /**
60
+ * 检查模型是否匹配某个 Provider
61
+ *
62
+ * @param model - 模型名称
63
+ * @param provider - Provider 类型
64
+ * @returns 是否匹配
65
+ */
66
+ declare function isModelForProvider(model: string, provider: ProviderType): boolean;
67
+
1
68
  /**
2
69
  * AI Chat Core 类型定义
70
+ *
71
+ * 注意:事件类型已迁移到 events.ts
3
72
  */
4
73
  /** 对话模式 */
5
74
  type ChatMode = 'agent' | 'plan' | 'ask';
6
- /** 可用模型 */
7
- type ModelProvider = 'doubao' | 'deepseek' | 'qwen' | 'gemini' | 'openrouter';
8
- /** 模型配置 */
9
- interface ModelConfig {
10
- provider: ModelProvider;
11
- model: string;
75
+
76
+ /**
77
+ * 简化的模型配置
78
+ *
79
+ * - modelId: 发送给 API 的模型 ID
80
+ * - displayName: 前端显示名称
81
+ * - group: 分组名称(由后端决定,前端只负责渲染)
82
+ */
83
+ interface ModelOption {
84
+ /** 模型 ID(发送给 API) */
85
+ modelId: string;
86
+ /** 显示名称 */
12
87
  displayName: string;
13
- supportsTools: boolean;
14
- supportsWebSearch: boolean;
15
- /** 支持的深度思考模式 */
16
- supportedThinkingModes: ThinkingMode[];
88
+ /** 分组名称(由后端决定,前端只负责渲染,必填) */
89
+ group: string;
90
+ /** 是否来自 OpenRouter(保留用于兼容,后续可能移除) */
91
+ isOpenRouter?: boolean;
92
+ /** 提供商名称(保留用于兼容,后续可能移除) */
93
+ provider?: string;
17
94
  }
18
- /** 预定义模型列表 */
19
- declare const AVAILABLE_MODELS: ModelConfig[];
95
+ /**
96
+ * 预定义模型列表(从 constants.ts 映射)
97
+ *
98
+ * 分组信息由后端决定,前端只负责渲染
99
+ */
100
+ declare const MODELS: ModelOption[];
101
+ /** 获取原生模型 */
102
+ declare function getNativeModels(): ModelOption[];
103
+ /** 获取 OpenRouter 模型 */
104
+ declare function getOpenRouterModels(): ModelOption[];
105
+ /** 根据 modelId 获取模型 */
106
+ declare function getModelByModelId(modelId: string): ModelOption | undefined;
107
+ /** 工具批准回调函数 */
108
+ type ToolApprovalCallback$1 = (toolCall: {
109
+ id: string;
110
+ name: string;
111
+ args: Record<string, unknown>;
112
+ }) => Promise<boolean>;
20
113
  /** Agent 配置 */
21
114
  interface AgentConfig {
22
115
  /** 豆包/火山引擎 API Key (用于豆包和 DeepSeek) */
@@ -31,13 +124,62 @@ interface AgentConfig {
31
124
  openrouterApiKey?: string;
32
125
  /** OpenRouter API URL */
33
126
  openrouterApiUrl?: string;
34
- /** Gemini API Key (用于图片/视频) */
127
+ /** Gemini API Key (用于图片/视频,注意:中国大陆无法直接访问) */
35
128
  geminiApiKey: string;
36
- /** 工作目录 */
37
- workingDir?: string;
129
+ /** 当前工作目录(Current Working Directory) */
130
+ cwd?: string;
131
+ /**
132
+ * 工具列表(Vite 插件风格)
133
+ *
134
+ * 支持多种形式:
135
+ * - 单个工具:getCwdTool
136
+ * - 工具插件:searchPlugin({ dataDir, workspace })
137
+ * - Promise:await asyncPlugin()
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * tools: [
142
+ * getCwdTool,
143
+ * executeCommandTool,
144
+ * searchPlugin({ dataDir: '/path', workspace: '/project' }),
145
+ * ]
146
+ * ```
147
+ */
148
+ tools?: ToolConfigItem[];
149
+ /**
150
+ * plan 模式的系统提示词(可选,有默认值)
151
+ * 用于指导 AI 如何制定执行计划
152
+ */
153
+ planPrompt?: string;
154
+ /**
155
+ * 工具批准回调(manual 模式使用)
156
+ * 返回 true 表示批准执行,false 表示跳过
157
+ */
158
+ onToolApprovalRequest?: ToolApprovalCallback$1;
159
+ /**
160
+ * 动态获取自动运行配置回调
161
+ * 每次检查工具批准时调用,获取最新配置
162
+ */
163
+ getAutoRunConfig?: () => Promise<AutoRunConfig$1 | undefined>;
38
164
  }
39
165
  /** 深度思考模式 */
40
166
  type ThinkingMode = 'enabled' | 'disabled';
167
+ /** 自动运行模式 */
168
+ type AutoRunMode = 'run-everything' | 'manual';
169
+ /** 自动运行配置 */
170
+ interface AutoRunConfig$1 {
171
+ /**
172
+ * 自动运行模式
173
+ * - 'run-everything': 运行所有内容(自动执行)
174
+ * - 'manual': 手动批准(每次执行前询问)
175
+ */
176
+ mode?: AutoRunMode;
177
+ }
178
+ /** 聊天消息格式(用于传递历史) */
179
+ interface ChatHistoryMessage {
180
+ role: 'user' | 'assistant' | 'system' | 'tool';
181
+ content: string;
182
+ }
41
183
  /** 聊天配置(每次聊天可变的选项) */
42
184
  interface ChatOptions {
43
185
  /** 对话模式 */
@@ -45,7 +187,7 @@ interface ChatOptions {
45
187
  /** 使用的模型 */
46
188
  model?: string;
47
189
  /** 模型提供商 */
48
- provider?: ModelProvider;
190
+ provider?: ProviderType;
49
191
  /** 是否启用联网搜索 */
50
192
  enableWebSearch?: boolean;
51
193
  /**
@@ -54,92 +196,181 @@ interface ChatOptions {
54
196
  * - 'disabled': 强制关闭深度思考
55
197
  */
56
198
  thinkingMode?: ThinkingMode;
57
- /** 深度思考预算(token 数,仅 enabled 时有效) */
58
- thinkingBudget?: number;
59
- }
60
- /** 聊天进度事件类型 */
61
- type ChatProgressType = 'thinking' | 'search_start' | 'search_result' | 'tool_call' | 'tool_result' | 'text' | 'text_delta' | 'image' | 'video' | 'done' | 'error';
62
- /** 聊天进度事件 */
63
- interface ChatProgress {
64
- type: ChatProgressType;
65
- data: unknown;
66
- }
67
- /** 工具调用进度 */
68
- interface ToolCallProgress {
69
- type: 'tool_call';
70
- data: {
71
- name: string;
72
- args: Record<string, unknown>;
73
- };
74
- }
75
- /** 工具结果进度 */
76
- interface ToolResultProgress {
77
- type: 'tool_result';
78
- data: {
79
- name: string;
80
- result: string;
81
- };
82
- }
83
- /** 搜索开始进度 */
84
- interface SearchStartProgress {
85
- type: 'search_start';
86
- data: {
87
- query: string;
88
- };
89
- }
90
- /** 搜索结果进度 */
91
- interface SearchResultProgress {
92
- type: 'search_result';
93
- data: {
94
- results: Array<{
95
- title: string;
96
- url: string;
97
- snippet: string;
98
- }>;
99
- };
199
+ /** 自动运行配置 */
200
+ autoRunConfig?: AutoRunConfig$1;
201
+ /** 对话历史(从数据库加载,无状态架构) */
202
+ history?: ChatHistoryMessage[];
100
203
  }
101
- /** 文本进度 */
102
- interface TextProgress {
103
- type: 'text';
104
- data: string;
204
+ /**
205
+ * 副作用定义(参考 REST API 规范)
206
+ *
207
+ * @example
208
+ * // 通知
209
+ * { type: 'notification', success: true, message: '图片生成完成' }
210
+ *
211
+ * // 文件系统变更
212
+ * { type: 'filesystem', success: true, data: { paths: ['/path/to/file'] } }
213
+ *
214
+ * // 失败
215
+ * { type: 'notification', success: false, message: 'API 超时' }
216
+ */
217
+ interface SideEffect$1 {
218
+ /** 副作用类型 */
219
+ type: string;
220
+ /** 是否成功 */
221
+ success: boolean;
222
+ /** 附加数据 */
223
+ data?: unknown;
224
+ /** 消息(成功时为提示,失败时为错误信息) */
225
+ message?: string;
105
226
  }
106
- /** 流式文本增量 */
107
- interface TextDeltaProgress {
108
- type: 'text_delta';
109
- data: string;
227
+ /**
228
+ * 工具执行结果(支持动态副作用)
229
+ *
230
+ * 工具可以返回此类型来动态声明副作用
231
+ */
232
+ interface ToolResult {
233
+ /** 执行结果(字符串) */
234
+ result: string;
235
+ /** 动态副作用(覆盖静态声明) */
236
+ sideEffects?: SideEffect$1[];
110
237
  }
111
- /** 思考进度 */
112
- interface ThinkingProgress {
113
- type: 'thinking';
114
- data: {
115
- content: string;
116
- isComplete?: boolean;
117
- };
238
+ /** 工具执行上下文 */
239
+ interface ToolContext {
240
+ /** 当前工作目录(Current Working Directory) */
241
+ cwd: string;
242
+ /** Gemini 客户端(供多模态工具使用) */
243
+ geminiClient?: unknown;
244
+ /** 执行 Shell 命令(内置方法) */
245
+ executeCommand: (command: string, cwd?: string) => Promise<{
246
+ success: boolean;
247
+ output?: string;
248
+ error?: string;
249
+ }>;
250
+ /** 中断信号(用于取消长时间操作) */
251
+ signal?: AbortSignal;
118
252
  }
119
- /** 图片进度 */
120
- interface ImageProgress {
121
- type: 'image';
122
- data: {
123
- path?: string;
124
- base64?: string;
253
+ /**
254
+ * 工具接口(用户可实现此接口创建自定义工具)
255
+ *
256
+ * 示例:
257
+ * ```typescript
258
+ * const myTool: Tool = {
259
+ * name: 'my_tool',
260
+ * description: '我的自定义工具',
261
+ * parameters: { type: 'object', properties: {}, required: [] },
262
+ * sideEffects: ['filesystem'], // 声明副作用
263
+ * execute: async (args, ctx) => '执行结果'
264
+ * };
265
+ * ```
266
+ */
267
+ interface Tool {
268
+ /** 工具名称 */
269
+ name: string;
270
+ /** 工具描述(供 AI 理解) */
271
+ description: string;
272
+ /** 参数定义(JSON Schema) */
273
+ parameters: {
274
+ type: 'object';
275
+ properties: Record<string, {
276
+ type: string;
277
+ description: string;
278
+ enum?: string[];
279
+ items?: {
280
+ type: string;
281
+ };
282
+ }>;
283
+ required: string[];
125
284
  };
285
+ /**
286
+ * 静态副作用声明(可选)
287
+ *
288
+ * 用于通知前端该工具执行后可能产生的副作用
289
+ *
290
+ * @example
291
+ * sideEffects: [{ type: 'notification', message: '图片生成完成', level: 'success' }]
292
+ *
293
+ * 注意:如果 execute 返回 ToolResult 带有 sideEffects,会覆盖此静态声明
294
+ */
295
+ sideEffects?: SideEffect$1[];
296
+ /**
297
+ * 执行函数
298
+ *
299
+ * 返回值:
300
+ * - string: 简单返回结果,使用静态 sideEffects
301
+ * - ToolResult: 带动态副作用的结果,覆盖静态 sideEffects
302
+ */
303
+ execute: (args: Record<string, unknown>, context: ToolContext) => Promise<string | ToolResult>;
126
304
  }
127
- /** 工具执行器接口(可由使用方实现) */
305
+ /** 工具执行器接口(可由使用方实现,用于自定义命令执行环境) */
128
306
  interface ToolExecutor$1 {
129
307
  /** 执行 Shell 命令 */
130
- executeCommand(command: string, workingDir?: string): Promise<{
308
+ executeCommand(command: string, cwd?: string, signal?: AbortSignal): Promise<{
131
309
  success: boolean;
132
310
  output?: string;
133
311
  error?: string;
134
312
  }>;
135
- /** 读取文件 */
136
- readFile?(path: string): Promise<Buffer>;
137
- /** 写入文件 */
138
- writeFile?(path: string, data: Buffer): Promise<void>;
139
- /** 读取目录 */
140
- readDirectory?(path: string): Promise<string[]>;
141
- }
142
- /** 工具定义(OpenAI 格式) */
313
+ }
314
+ /**
315
+ * 工具插件实例
316
+ *
317
+ * 由 createXxxPlugin() 返回,可直接在 tools 数组中展开使用
318
+ */
319
+ interface ToolPlugin {
320
+ /** 插件提供的工具数组 */
321
+ tools: Tool[];
322
+ /** 插件控制方法(可选,由各插件自定义) */
323
+ [key: string]: unknown;
324
+ }
325
+ /**
326
+ * 创建单个工具插件(辅助函数)
327
+ *
328
+ * @example
329
+ * ```typescript
330
+ * export function getCwdTool(): ToolPlugin {
331
+ * return tool({
332
+ * name: 'get_cwd',
333
+ * description: '...',
334
+ * parameters: { ... },
335
+ * execute: async (args, context) => { ... }
336
+ * });
337
+ * }
338
+ * ```
339
+ */
340
+ declare function tool(t: Tool): ToolPlugin;
341
+ /**
342
+ * 创建多个工具插件(辅助函数)
343
+ *
344
+ * @example
345
+ * ```typescript
346
+ * export function myPlugin(): ToolPlugin {
347
+ * return tools([
348
+ * { name: 'tool1', ... },
349
+ * { name: 'tool2', ... },
350
+ * ]);
351
+ * }
352
+ * ```
353
+ */
354
+ declare function tools(ts: Tool[]): ToolPlugin;
355
+ /**
356
+ * 工具配置项(Vite 插件风格,只支持插件形式)
357
+ *
358
+ * @example
359
+ * ```typescript
360
+ * tools: [
361
+ * getCwdTool(), // 工具插件(函数调用)
362
+ * searchPlugin({ dataDir, workspace }), // 异步插件(返回 Promise<ToolPlugin>)
363
+ * ]
364
+ * ```
365
+ */
366
+ type ToolConfigItem = ToolPlugin | Promise<ToolPlugin>;
367
+ /**
368
+ * 解析工具配置,统一转换为 Tool[]
369
+ *
370
+ * 所有工具都必须是 ToolPlugin 形式(Vite 插件风格)
371
+ */
372
+ declare function resolveTools(items: ToolConfigItem[]): Promise<Tool[]>;
373
+ /** 工具定义(OpenAI 格式,内部使用) */
143
374
  interface ToolDefinition {
144
375
  type: 'function';
145
376
  function: {
@@ -161,11 +392,11 @@ interface ToolDefinition {
161
392
  }
162
393
  /** 聊天消息(内部格式) */
163
394
  interface ChatMessage {
164
- /** 消息 ID(豆包 Responses API 需要) */
395
+ /** 消息 ID */
165
396
  id?: string;
166
397
  role: 'system' | 'user' | 'assistant' | 'tool';
167
398
  content: string;
168
- /** 深度思考内容(DeepSeek 思考模式下需要回传) */
399
+ /** 深度思考内容 */
169
400
  reasoning_content?: string;
170
401
  tool_call_id?: string;
171
402
  tool_calls?: Array<{
@@ -177,320 +408,1027 @@ interface ChatMessage {
177
408
  };
178
409
  }>;
179
410
  }
180
- /** DeepSeek Responses API 消息格式 */
181
- interface DeepSeekMessage {
182
- role: 'user' | 'assistant';
183
- content: Array<{
184
- type: 'input_text' | 'output_text';
185
- text: string;
186
- }>;
187
- }
188
- /** DeepSeek / 火山引擎 Responses API 工具定义 */
189
- interface DeepSeekTool {
411
+ /** 火山引擎 Responses API 工具定义 */
412
+ interface ResponsesApiTool {
190
413
  type: 'function' | 'web_search';
191
- function?: {
192
- name: string;
193
- description: string;
194
- parameters: Record<string, unknown>;
195
- };
414
+ name?: string;
415
+ description?: string;
416
+ parameters?: Record<string, unknown>;
196
417
  max_keyword?: number;
197
418
  limit?: number;
198
419
  sources?: string[];
199
420
  }
200
421
 
201
422
  /**
202
- * Provider 基础接口定义
423
+ * AI Chat 事件系统
203
424
  *
204
- * 所有 AI 模型提供商都实现这个统一接口
425
+ * 模块化的事件类型定义,用于 Agent 与前端之间的通信。
426
+ *
427
+ * 设计原则:
428
+ * 1. 每种事件类型有明确的数据结构
429
+ * 2. 事件分组便于管理和扩展
430
+ * 3. 类型安全,避免 unknown
431
+ * 4. 统一的时间追踪(开始/结束/耗时)
205
432
  */
206
-
207
- /** 工具执行器类型 */
208
- type ToolExecutor = (name: string, args: Record<string, unknown>) => Promise<string>;
209
- /** 聊天上下文 */
210
- interface ChatContext {
211
- /** 对话历史 */
212
- history: ChatMessage[];
213
- /** 系统提示词 */
214
- systemPrompt: string;
215
- /** 工作目录 */
216
- workingDir: string;
217
- /** 工具执行器 */
218
- executeTool: ToolExecutor;
219
- /** 取消信号 */
220
- signal: AbortSignal;
433
+ /** 搜索结果项 */
434
+ interface SearchResult {
435
+ title: string;
436
+ url: string;
437
+ snippet: string;
221
438
  }
222
- /** 模型能力定义 */
223
- interface ModelCapabilities {
224
- supportsTools: boolean;
225
- supportsWebSearch: boolean;
226
- supportsThinking: boolean;
227
- supportedThinkingModes: Array<'enabled' | 'disabled'>;
439
+ /** 工具调用状态 */
440
+ type ToolCallStatus = 'pending' | 'running' | 'success' | 'error';
441
+ /** 工具调用信息(用于前端状态管理) */
442
+ interface ToolCallInfo {
443
+ id: string;
444
+ name: string;
445
+ args: Record<string, unknown>;
446
+ status: ToolCallStatus;
447
+ result?: string;
448
+ error?: string;
449
+ startedAt?: number;
450
+ duration?: number;
451
+ }
452
+ /** Token 使用统计 */
453
+ interface TokenUsage {
454
+ promptTokens: number;
455
+ completionTokens: number;
456
+ totalTokens: number;
457
+ /** 思考 token 数(如果有) */
458
+ reasoningTokens?: number;
459
+ /** 缓存命中 token 数(如果有) */
460
+ cachedTokens?: number;
461
+ }
462
+ /** 错误类别 - 参考 AI SDK 设计 */
463
+ type ErrorCategory = 'api' | 'rate_limit' | 'validation' | 'tool' | 'timeout' | 'abort' | 'parse' | 'unknown';
464
+ /** 错误详情 - 结构化错误信息 */
465
+ interface ErrorDetails {
466
+ /** 错误分类 */
467
+ category: ErrorCategory;
468
+ /** 人类可读的错误信息 */
469
+ message: string;
470
+ /** 错误代码(如 'RATE_LIMIT', 'NETWORK_ERROR') */
471
+ code?: string;
472
+ /** HTTP 状态码(如果适用) */
473
+ statusCode?: number;
474
+ /** HTTP 状态文本 */
475
+ statusText?: string;
476
+ /** 是否可重试 */
477
+ retryable?: boolean;
478
+ /** 重试等待时间(秒) */
479
+ retryAfter?: number;
480
+ /** 原始错误信息(用于调试) */
481
+ cause?: string;
482
+ /** 错误发生的上下文(如模型名、工具名) */
483
+ context?: string;
484
+ }
485
+ /** 思考开始事件 */
486
+ interface ThinkingStartEvent {
487
+ type: 'thinking_start';
488
+ data: {
489
+ /** 开始时间戳(毫秒) */
490
+ startedAt: number;
491
+ };
492
+ }
493
+ /** 思考内容增量事件 */
494
+ interface ThinkingDeltaEvent {
495
+ type: 'thinking_delta';
496
+ data: {
497
+ /** 增量内容 */
498
+ content: string;
499
+ };
500
+ }
501
+ /** 思考结束事件 */
502
+ interface ThinkingEndEvent {
503
+ type: 'thinking_end';
504
+ data: {
505
+ /** 结束时间戳(毫秒) */
506
+ endedAt: number;
507
+ /** 思考耗时(毫秒) */
508
+ duration: number;
509
+ };
510
+ }
511
+ /** 思考相关事件联合类型 */
512
+ type ThinkingEvent = ThinkingStartEvent | ThinkingDeltaEvent | ThinkingEndEvent;
513
+ /** 搜索开始事件 */
514
+ interface SearchStartEvent {
515
+ type: 'search_start';
516
+ data: {
517
+ /** 搜索查询词 */
518
+ query: string;
519
+ /** 开始时间戳(毫秒) */
520
+ startedAt: number;
521
+ };
522
+ }
523
+ /** 搜索结果事件(成功完成) */
524
+ interface SearchResultEvent {
525
+ type: 'search_result';
526
+ data: {
527
+ /** 搜索结果列表 */
528
+ results: SearchResult[];
529
+ /** 结束时间戳(毫秒) */
530
+ endedAt: number;
531
+ /** 搜索耗时(毫秒) */
532
+ duration: number;
533
+ };
534
+ }
535
+ /** 搜索结束事件(失败或取消) */
536
+ interface SearchEndEvent {
537
+ type: 'search_end';
538
+ data: {
539
+ /** 是否成功 */
540
+ success: boolean;
541
+ /** 错误信息(失败时) */
542
+ error?: string;
543
+ /** 结束时间戳(毫秒) */
544
+ endedAt: number;
545
+ /** 搜索耗时(毫秒) */
546
+ duration: number;
547
+ };
548
+ }
549
+ /** 搜索相关事件联合类型 */
550
+ type SearchEvent = SearchStartEvent | SearchResultEvent | SearchEndEvent;
551
+ /** 工具调用开始事件 */
552
+ interface ToolCallStartEvent {
553
+ type: 'tool_call_start';
554
+ data: {
555
+ /** 工具调用 ID */
556
+ id: string;
557
+ /** 工具名称 */
558
+ name: string;
559
+ /** 工具参数 */
560
+ args: Record<string, unknown>;
561
+ /** 开始时间戳(毫秒) */
562
+ startedAt: number;
563
+ };
564
+ }
565
+ /** 副作用定义(从 types.ts 复制,避免循环依赖) */
566
+ interface SideEffect {
567
+ type: string;
568
+ success: boolean;
569
+ data?: unknown;
570
+ message?: string;
571
+ }
572
+ /** 工具调用结果事件 */
573
+ interface ToolCallResultEvent {
574
+ type: 'tool_call_result';
575
+ data: {
576
+ /** 工具调用 ID */
577
+ id: string;
578
+ /** 工具名称 */
579
+ name: string;
580
+ /** 执行结果 */
581
+ result: string;
582
+ /** 是否成功 */
583
+ success: boolean;
584
+ /** 错误信息(失败时) */
585
+ error?: string;
586
+ /** 结束时间戳(毫秒) */
587
+ endedAt: number;
588
+ /** 执行耗时(毫秒) */
589
+ duration: number;
590
+ /**
591
+ * 工具副作用
592
+ * 前端可根据此字段处理通知、刷新文件列表等
593
+ */
594
+ sideEffects?: SideEffect[];
595
+ };
596
+ }
597
+ /** 工具执行批准请求事件(manual 模式) */
598
+ interface ToolApprovalRequestEvent {
599
+ type: 'tool_approval_request';
600
+ data: {
601
+ /** 工具调用 ID */
602
+ id: string;
603
+ /** 工具名称 */
604
+ name: string;
605
+ /** 工具参数 */
606
+ args: Record<string, unknown>;
607
+ /** 请求时间戳 */
608
+ requestedAt: number;
609
+ };
610
+ }
611
+ /** 工具相关事件联合类型 */
612
+ type ToolEvent = ToolCallStartEvent | ToolCallResultEvent | ToolApprovalRequestEvent;
613
+ /** 文本增量事件 */
614
+ interface TextDeltaEvent {
615
+ type: 'text_delta';
616
+ data: {
617
+ /** 增量文本 */
618
+ content: string;
619
+ };
620
+ }
621
+ /** 文本相关事件联合类型 */
622
+ type TextEvent = TextDeltaEvent;
623
+ /** 图片事件 */
624
+ interface ImageEvent {
625
+ type: 'image';
626
+ data: {
627
+ /** 图片路径 */
628
+ path?: string;
629
+ /** Base64 编码 */
630
+ base64?: string;
631
+ /** MIME 类型 */
632
+ mimeType?: string;
633
+ };
634
+ }
635
+ /** 视频事件 */
636
+ interface VideoEvent {
637
+ type: 'video';
638
+ data: {
639
+ /** 视频路径 */
640
+ path: string;
641
+ };
642
+ }
643
+ /** 媒体相关事件联合类型 */
644
+ type MediaEvent = ImageEvent | VideoEvent;
645
+ /** 流开始事件 */
646
+ interface StreamStartEvent {
647
+ type: 'stream_start';
648
+ data: {
649
+ /** 请求 ID */
650
+ requestId?: string;
651
+ /** 使用的模型 */
652
+ model: string;
653
+ /** 开始时间戳 */
654
+ startedAt: number;
655
+ };
656
+ }
657
+ /** 完成事件 */
658
+ interface DoneEvent {
659
+ type: 'done';
660
+ data: {
661
+ /** 完整的最终文本 */
662
+ text: string;
663
+ /** Token 使用统计 */
664
+ usage?: TokenUsage;
665
+ /** 总耗时(毫秒) */
666
+ duration?: number;
667
+ };
668
+ }
669
+ /** 错误事件 - 结构化错误信息 */
670
+ interface ErrorEvent {
671
+ type: 'error';
672
+ data: ErrorDetails;
673
+ }
674
+ /** 中止事件 - 用户主动取消 */
675
+ interface AbortEvent {
676
+ type: 'abort';
677
+ data: {
678
+ /** 中止原因 */
679
+ reason?: string;
680
+ /** 中止时间戳 */
681
+ abortedAt: number;
682
+ };
683
+ }
684
+ /** 状态相关事件联合类型 */
685
+ type StatusEvent = StreamStartEvent | DoneEvent | ErrorEvent | AbortEvent;
686
+ /** 步骤开始事件 */
687
+ interface StepStartEvent {
688
+ type: 'step_start';
689
+ data: {
690
+ /** 步骤编号(从 1 开始) */
691
+ stepNumber: number;
692
+ /** 步骤描述(可选) */
693
+ description?: string;
694
+ /** 开始时间戳 */
695
+ startedAt: number;
696
+ };
697
+ }
698
+ /** 步骤结束事件 */
699
+ interface StepEndEvent {
700
+ type: 'step_end';
701
+ data: {
702
+ /** 步骤编号 */
703
+ stepNumber: number;
704
+ /** 结束时间戳 */
705
+ endedAt: number;
706
+ /** 耗时(毫秒) */
707
+ duration: number;
708
+ };
709
+ }
710
+ /** 步骤相关事件联合类型 */
711
+ type StepEvent = StepStartEvent | StepEndEvent;
712
+ /** 所有事件类型 */
713
+ type ChatEvent = ThinkingEvent | SearchEvent | ToolEvent | TextEvent | MediaEvent | StatusEvent | StepEvent;
714
+ /** 事件类型字符串 */
715
+ type ChatEventType = ChatEvent['type'];
716
+ /**
717
+ * 创建思考开始事件
718
+ */
719
+ declare function createThinkingStart(): ThinkingStartEvent;
720
+ /**
721
+ * 创建思考增量事件
722
+ */
723
+ declare function createThinkingDelta(content: string): ThinkingDeltaEvent;
724
+ /**
725
+ * 创建思考结束事件
726
+ */
727
+ declare function createThinkingEnd(startedAt: number): ThinkingEndEvent;
728
+ /**
729
+ * 创建搜索开始事件
730
+ */
731
+ declare function createSearchStart(query: string): SearchStartEvent;
732
+ /**
733
+ * 创建搜索结果事件(成功)
734
+ */
735
+ declare function createSearchResult(results: SearchResult[], startedAt: number): SearchResultEvent;
736
+ /**
737
+ * 创建搜索结束事件(失败或取消)
738
+ */
739
+ declare function createSearchEnd(success: boolean, startedAt: number, error?: string): SearchEndEvent;
740
+ /**
741
+ * 创建工具调用开始事件
742
+ */
743
+ declare function createToolCallStart(id: string, name: string, args: Record<string, unknown>): ToolCallStartEvent;
744
+ /**
745
+ * 创建工具调用结果事件
746
+ */
747
+ declare function createToolCallResult(id: string, name: string, result: string, success: boolean, startedAt: number, error?: string, sideEffects?: SideEffect[]): ToolCallResultEvent;
748
+ /**
749
+ * 创建文本增量事件
750
+ */
751
+ declare function createTextDelta(content: string): TextDeltaEvent;
752
+ /**
753
+ * 创建流开始事件
754
+ */
755
+ declare function createStreamStart(model: string, requestId?: string): StreamStartEvent;
756
+ /**
757
+ * 创建完成事件
758
+ */
759
+ declare function createDone(text: string, usage?: TokenUsage, duration?: number): DoneEvent;
760
+ /**
761
+ * 创建错误事件(完整版)
762
+ */
763
+ declare function createError(details: ErrorDetails): ErrorEvent;
764
+ /**
765
+ * 创建 API 错误事件
766
+ */
767
+ declare function createApiError(message: string, options?: {
768
+ code?: string;
769
+ statusCode?: number;
770
+ statusText?: string;
771
+ retryable?: boolean;
772
+ retryAfter?: number;
773
+ cause?: string;
774
+ context?: string;
775
+ }): ErrorEvent;
776
+ /**
777
+ * 创建速率限制错误事件
778
+ */
779
+ declare function createRateLimitError(message: string, retryAfter?: number, context?: string): ErrorEvent;
780
+ /**
781
+ * 创建工具错误事件
782
+ */
783
+ declare function createToolError(message: string, toolName: string, cause?: string): ErrorEvent;
784
+ /**
785
+ * 创建超时错误事件
786
+ */
787
+ declare function createTimeoutError(message: string, context?: string): ErrorEvent;
788
+ /**
789
+ * 创建解析错误事件
790
+ */
791
+ declare function createParseError(message: string, cause?: string): ErrorEvent;
792
+ /**
793
+ * 创建中止事件
794
+ */
795
+ declare function createAbort(reason?: string): AbortEvent;
796
+ /**
797
+ * 创建步骤开始事件
798
+ */
799
+ declare function createStepStart(stepNumber: number, description?: string): StepStartEvent;
800
+ /**
801
+ * 创建步骤结束事件
802
+ */
803
+ declare function createStepEnd(stepNumber: number, startedAt: number): StepEndEvent;
804
+ /**
805
+ * 创建图片事件
806
+ */
807
+ declare function createImage(options: {
808
+ path?: string;
809
+ base64?: string;
810
+ mimeType?: string;
811
+ }): ImageEvent;
812
+ /**
813
+ * 创建视频事件
814
+ */
815
+ declare function createVideo(path: string): VideoEvent;
816
+ /** 检查是否为思考事件 */
817
+ declare function isThinkingEvent(event: ChatEvent): event is ThinkingEvent;
818
+ /** 检查是否为搜索事件 */
819
+ declare function isSearchEvent(event: ChatEvent): event is SearchEvent;
820
+ /** 检查是否为工具事件 */
821
+ declare function isToolEvent(event: ChatEvent): event is ToolEvent;
822
+ /** 检查是否为文本事件 */
823
+ declare function isTextEvent(event: ChatEvent): event is TextEvent;
824
+ /** 检查是否为媒体事件 */
825
+ declare function isMediaEvent(event: ChatEvent): event is MediaEvent;
826
+ /** 检查是否为状态事件 */
827
+ declare function isStatusEvent(event: ChatEvent): event is StatusEvent;
828
+ /** 检查是否为错误事件 */
829
+ declare function isErrorEvent(event: ChatEvent): event is ErrorEvent;
830
+ /** 检查是否为中止事件 */
831
+ declare function isAbortEvent(event: ChatEvent): event is AbortEvent;
832
+ /** 检查是否为步骤事件 */
833
+ declare function isStepEvent(event: ChatEvent): event is StepEvent;
834
+ /** 检查错误是否可重试 */
835
+ declare function isRetryableError(event: ChatEvent): boolean;
836
+
837
+ /** 运行时配置(API Keys 和 URLs) */
838
+ interface RuntimeConfig {
839
+ arkApiKey: string;
840
+ arkApiUrl: string;
841
+ qwenApiKey: string;
842
+ qwenApiUrl: string;
843
+ openrouterApiKey: string;
844
+ openrouterApiUrl: string;
845
+ geminiApiKey: string;
846
+ cwd: string;
847
+ planPrompt: string;
228
848
  }
229
849
  /**
230
- * ChatProvider 接口
850
+ * 混合 Agent 类
231
851
  *
232
- * 每个 AI 模型提供商都需要实现这个接口
852
+ * 职责:
853
+ * 1. 管理多个 ProviderAdapter
854
+ * 2. 路由请求到正确的 Adapter
855
+ * 3. 使用 ChatOrchestrator 统一处理工具调用
856
+ * 4. 管理对话历史和工具注册
233
857
  */
234
- interface ChatProvider {
235
- /** 提供商名称 */
236
- readonly name: string;
237
- /** 支持的模型列表 */
238
- readonly supportedModels: string[];
858
+ declare class HybridAgent {
859
+ private config;
860
+ private adapters;
861
+ private orchestrator;
862
+ private geminiClient;
863
+ private toolExecutor;
864
+ private abortController;
865
+ /** 已注册的工具 */
866
+ private tools;
867
+ /** 工具配置(用于异步初始化) */
868
+ private toolConfig;
869
+ constructor(config: AgentConfig, toolExecutor?: ToolExecutor$1);
870
+ /** 异步初始化工具(在第一次 chat 前调用) */
871
+ private asyncInit;
872
+ /** 初始化所有 Adapter */
873
+ private initializeAdapters;
239
874
  /**
240
- * 检查是否支持指定模型
875
+ * 判断模型提供商
241
876
  */
242
- supportsModel(model: string): boolean;
877
+ private getModelProvider;
878
+ /** 获取 Adapter */
879
+ private getAdapter;
243
880
  /**
244
- * 获取模型能力
881
+ * 调试:获取模型路由信息
245
882
  */
246
- getModelCapabilities(model: string): ModelCapabilities;
883
+ getModelRouteInfo(model: string): RouteResult & {
884
+ available: boolean;
885
+ };
886
+ /** 构建系统提示词 */
887
+ private buildSystemPrompt;
888
+ /** 获取默认深度思考模式 */
889
+ private getDefaultThinkingMode;
890
+ /** 创建工具执行上下文 */
891
+ private createToolContext;
892
+ /** 执行工具 */
893
+ private executeTool;
894
+ /** 获取工具定义列表 */
895
+ private getToolDefinitions;
247
896
  /**
248
- * 执行聊天
897
+ * 聊天入口
249
898
  *
250
- * @param message 用户消息
251
- * @param model 模型名称
252
- * @param options 聊天选项
253
- * @param context 聊天上下文
254
- * @returns 异步生成器,产出聊天进度事件
899
+ * 使用 ChatOrchestrator 统一处理所有 Provider 的工具调用循环
255
900
  */
256
- chat(message: string, model: string, options: ChatOptions, context: ChatContext): AsyncGenerator<ChatProgress>;
901
+ chat(message: string, options?: ChatOptions, images?: string[]): AsyncGenerator<ChatEvent>;
902
+ /** 中断当前请求 */
903
+ abort(): void;
904
+ /** 设置当前工作目录 */
905
+ setCwd(dir: string): void;
906
+ /** 获取当前配置 */
907
+ getConfig(): RuntimeConfig;
908
+ /** 获取所有支持的模型 */
909
+ getSupportedModels(): ModelOption[];
257
910
  }
258
911
 
259
912
  /**
260
- * ARK Provider (火山引擎)
261
- *
262
- * 统一使用 Responses API,支持:
263
- * - 函数调用 Function Calling
264
- * - 联网搜索 Web Search
265
- * - 深度思考 Thinking
266
- * - 上下文缓存 Caching
913
+ * Provider 统一类型定义
267
914
  *
268
- * 支持模型:豆包 (doubao-*), DeepSeek (deepseek-*)
915
+ * 核心设计原则:
916
+ * 1. Adapter 只负责 API 格式转换,不处理业务逻辑
917
+ * 2. Orchestrator 统一处理工具调用循环、消息历史、事件发射
918
+ * 3. 所有 Adapter 返回标准化的 StreamChunk
269
919
  */
270
920
 
271
- /** ARK Provider 配置 */
272
- interface ArkProviderConfig {
921
+ /** 简化的工具定义(供 Adapter 使用) */
922
+ interface SimpleToolDefinition {
923
+ name: string;
924
+ description: string;
925
+ parameters: {
926
+ type: 'object';
927
+ properties: Record<string, {
928
+ type: string;
929
+ description: string;
930
+ enum?: string[];
931
+ items?: {
932
+ type: string;
933
+ };
934
+ }>;
935
+ required: string[];
936
+ };
937
+ }
938
+ /** 流式响应块类型 */
939
+ type StreamChunkType = 'text' | 'thinking' | 'thinking_done' | 'tool_call' | 'search_result' | 'done' | 'error';
940
+ /** 工具调用请求 */
941
+ interface ToolCallRequest {
942
+ id: string;
943
+ name: string;
944
+ arguments: string;
945
+ }
946
+ /** 搜索结果项 */
947
+ interface SearchResultItem {
948
+ title: string;
949
+ url: string;
950
+ snippet: string;
951
+ }
952
+ /** 流式响应块 - 所有 Adapter 必须返回此格式 */
953
+ interface StreamChunk {
954
+ type: StreamChunkType;
955
+ text?: string;
956
+ thinking?: string;
957
+ toolCall?: ToolCallRequest;
958
+ searchResults?: SearchResultItem[];
959
+ finishReason?: 'stop' | 'tool_calls' | 'length' | 'error';
960
+ error?: string;
961
+ }
962
+ /** 标准化消息 - Orchestrator 内部使用 */
963
+ interface StandardMessage {
964
+ role: 'system' | 'user' | 'assistant' | 'tool';
965
+ content: string;
966
+ images?: string[];
967
+ toolCalls?: ToolCallRequest[];
968
+ toolCallId?: string;
969
+ toolName?: string;
970
+ }
971
+ /** Adapter 配置 */
972
+ interface AdapterConfig {
273
973
  apiKey: string;
274
974
  apiUrl?: string;
275
- /** 是否启用上下文缓存 */
276
- enableCaching?: boolean;
975
+ }
976
+ /** 单次调用选项 */
977
+ interface StreamOnceOptions {
978
+ /** 模型 ID */
979
+ model: string;
980
+ /** 是否启用思考 */
981
+ enableThinking?: boolean;
982
+ /** 是否启用搜索 */
983
+ enableSearch?: boolean;
984
+ /** 中断信号 */
985
+ signal: AbortSignal;
277
986
  }
278
987
  /**
279
- * ARK Provider 实现
988
+ * Provider Adapter 接口
280
989
  *
281
- * 统一使用 Responses API
990
+ * 职责:
991
+ * - 将标准消息转换为 API 特定格式
992
+ * - 调用 API 并返回标准化的 StreamChunk
993
+ * - 不处理工具执行、消息历史维护
282
994
  */
283
- declare class ArkProvider implements ChatProvider {
284
- readonly name = "ark";
995
+ interface ProviderAdapter {
996
+ /** 适配器名称 */
997
+ readonly name: string;
998
+ /** 支持的模型列表 */
285
999
  readonly supportedModels: string[];
286
- private apiKey;
287
- private apiUrl;
288
- private enableCaching;
289
- constructor(config: ArkProviderConfig);
1000
+ /**
1001
+ * 单次流式调用
1002
+ *
1003
+ * @param messages 标准化消息列表
1004
+ * @param tools 工具定义列表
1005
+ * @param options 调用选项
1006
+ * @returns 标准化的流式响应
1007
+ */
1008
+ streamOnce(messages: StandardMessage[], tools: SimpleToolDefinition[], options: StreamOnceOptions): AsyncGenerator<StreamChunk>;
1009
+ /**
1010
+ * 检查是否支持指定模型
1011
+ */
290
1012
  supportsModel(model: string): boolean;
291
- getModelCapabilities(model: string): ModelCapabilities;
1013
+ }
1014
+ /**
1015
+ * 工具执行器
1016
+ *
1017
+ * 返回值:
1018
+ * - string: 简单结果,使用工具的静态 sideEffects
1019
+ * - ToolResult: 带动态副作用的结果
1020
+ */
1021
+ type ToolExecutor = (name: string, args: Record<string, unknown>, signal?: AbortSignal) => Promise<string | ToolResult>;
1022
+ /** 自动运行配置 */
1023
+ interface AutoRunConfig {
292
1024
  /**
293
- * 聊天入口 - 统一使用 Responses API
1025
+ * 自动运行模式
1026
+ * - 'run-everything': 运行所有内容(自动执行)
1027
+ * - 'manual': 手动批准(每次执行前询问)
294
1028
  */
295
- chat(message: string, model: string, options: ChatOptions, context: ChatContext): AsyncGenerator<ChatProgress>;
1029
+ mode?: 'run-everything' | 'manual';
1030
+ }
1031
+ /** 工具批准回调函数 */
1032
+ type ToolApprovalCallback = (toolCall: {
1033
+ id: string;
1034
+ name: string;
1035
+ args: Record<string, unknown>;
1036
+ }) => Promise<boolean>;
1037
+ /** 获取自动运行配置回调 */
1038
+ type GetAutoRunConfigCallback = () => Promise<AutoRunConfig | undefined>;
1039
+ /** Orchestrator 配置 */
1040
+ interface OrchestratorConfig {
1041
+ /** 最大迭代次数 */
1042
+ maxIterations?: number;
1043
+ /** 工具执行器 */
1044
+ executeTool: ToolExecutor;
1045
+ /**
1046
+ * 完整的工具列表(用于获取 sideEffects)
1047
+ * key: 工具名称, value: 工具定义
1048
+ */
1049
+ tools?: Map<string, Tool>;
1050
+ /** 自动运行配置(静态配置,优先使用 getAutoRunConfig) */
1051
+ autoRunConfig?: AutoRunConfig;
1052
+ /**
1053
+ * 动态获取自动运行配置回调
1054
+ * 每次检查工具批准时调用,获取最新配置
1055
+ */
1056
+ getAutoRunConfig?: GetAutoRunConfigCallback;
1057
+ /**
1058
+ * 工具批准回调(manual 模式使用)
1059
+ * 返回 true 表示批准执行,false 表示跳过
1060
+ */
1061
+ onToolApprovalRequest?: ToolApprovalCallback;
1062
+ }
1063
+ /** Orchestrator 上下文 */
1064
+ interface OrchestratorContext {
1065
+ /** 系统提示 */
1066
+ systemPrompt: string;
1067
+ /** 对话历史(会被修改) */
1068
+ history: ChatMessage[];
1069
+ /** 工具定义 */
1070
+ tools: SimpleToolDefinition[];
1071
+ /** 中断信号 */
1072
+ signal: AbortSignal;
1073
+ /** 图片列表 */
1074
+ images?: string[];
1075
+ }
1076
+ /** Orchestrator 选项 */
1077
+ interface OrchestratorOptions {
1078
+ /** 模型 ID */
1079
+ model: string;
1080
+ /** 是否启用思考 */
1081
+ enableThinking?: boolean;
1082
+ /** 是否启用搜索 */
1083
+ enableSearch?: boolean;
1084
+ /** 自动运行配置 */
1085
+ autoRunConfig?: AutoRunConfig;
296
1086
  }
297
1087
 
298
1088
  /**
299
- * Qwen Provider (通义千问)
1089
+ * Chat Orchestrator
1090
+ *
1091
+ * 统一处理:
1092
+ * 1. 工具调用循环 (while iterations < MAX)
1093
+ * 2. 消息历史维护 (assistant + tool 消息)
1094
+ * 3. 事件发射 (ChatEvent)
1095
+ * 4. 错误处理
300
1096
  *
301
- * 使用 DashScope 原生协议以获得完整功能:
302
- * - 联网搜索引用 (search_info)
303
- * - 角标标注 (enable_citation)
304
- * - 深度思考 (enable_thinking)
1097
+ * 所有 Provider 通过此类执行,确保行为一致
305
1098
  */
306
1099
 
307
- /** Qwen Provider 配置 */
308
- interface QwenProviderConfig {
309
- apiKey: string;
310
- apiUrl?: string;
311
- }
312
1100
  /**
313
- * Qwen Provider 实现
1101
+ * Chat Orchestrator
1102
+ *
1103
+ * 核心职责:统一处理工具调用循环,所有 Provider 共享相同的逻辑
314
1104
  */
315
- declare class QwenProvider implements ChatProvider {
316
- readonly name = "qwen";
317
- readonly supportedModels: string[];
318
- private apiKey;
319
- private apiUrl;
320
- constructor(config: QwenProviderConfig);
321
- supportsModel(model: string): boolean;
322
- getModelCapabilities(model: string): ModelCapabilities;
323
- chat(message: string, model: string, options: ChatOptions, context: ChatContext): AsyncGenerator<ChatProgress>;
324
- /** 调用 DashScope API (流式) */
325
- private callDashScopeStream;
1105
+ declare class ChatOrchestrator {
1106
+ private config;
1107
+ constructor(config: OrchestratorConfig);
1108
+ /**
1109
+ * 执行聊天
1110
+ *
1111
+ * @param adapter Provider 适配器
1112
+ * @param message 用户消息
1113
+ * @param context Orchestrator 上下文
1114
+ * @param options 选项
1115
+ */
1116
+ chat(adapter: ProviderAdapter, message: string, context: OrchestratorContext, options: OrchestratorOptions): AsyncGenerator<ChatEvent>;
1117
+ /**
1118
+ * 构建标准化消息列表
1119
+ */
1120
+ private buildMessages;
326
1121
  }
1122
+ /**
1123
+ * 创建 Orchestrator 实例
1124
+ */
1125
+ declare function createOrchestrator(config: OrchestratorConfig): ChatOrchestrator;
327
1126
 
328
1127
  /**
329
- * Gemini 3 Provider (Google)
330
- *
331
- * 使用 @google/genai SDK
332
- *
333
- * Gemini 3 新特性:
334
- * - thinking_level: 'low' | 'high' (控制推理深度,替代旧的 thinking_budget)
335
- * - thoughtSignature (维持推理上下文,必须返回给模型)
336
- * - includeThoughts (返回思考摘要)
1128
+ * ARK (火山引擎) Adapter
337
1129
  *
338
- * 限制:
339
- * - Google Search + 自定义 Function Calling 仍然不兼容
340
- * - 内置工具可组合:google_search + url_context + code_execution
341
- *
342
- * 参考:https://ai.google.dev/docs/gemini-3
1130
+ * 职责:
1131
+ * - 将标准消息转换为 ARK Responses API 格式
1132
+ * - 调用 API 并解析响应为标准 StreamChunk
1133
+ * - 不处理工具执行和消息历史
343
1134
  */
344
1135
 
345
- /** Gemini Provider 配置 */
346
- interface GeminiProviderConfig {
347
- apiKey: string;
348
- }
1136
+ /** ARK 支持的模型 */
1137
+ declare const ARK_MODELS: string[];
349
1138
  /**
350
- * Gemini Provider 实现
1139
+ * ARK Adapter
1140
+ *
1141
+ * 使用 Responses API 格式
351
1142
  */
352
- declare class GeminiProvider implements ChatProvider {
353
- readonly name = "gemini";
1143
+ declare class ArkAdapter implements ProviderAdapter {
1144
+ readonly name = "ark";
354
1145
  readonly supportedModels: string[];
355
- private geminiClient;
356
1146
  private apiKey;
357
- constructor(config: GeminiProviderConfig);
358
- /** 懒加载 Gemini 客户端 */
359
- private getClient;
1147
+ private apiUrl;
1148
+ constructor(config: AdapterConfig);
360
1149
  supportsModel(model: string): boolean;
361
- getModelCapabilities(model: string): ModelCapabilities;
362
- chat(message: string, model: string, options: ChatOptions, context: ChatContext): AsyncGenerator<ChatProgress>;
363
- /** 转换消息格式为 Gemini 格式 */
364
- private convertToGeminiMessages;
365
- /** 转换工具定义为 Gemini functionDeclarations 格式 */
366
- private convertToGeminiFunctions;
1150
+ /**
1151
+ * 单次流式调用
1152
+ */
1153
+ streamOnce(messages: StandardMessage[], tools: SimpleToolDefinition[], options: StreamOnceOptions): AsyncGenerator<StreamChunk>;
1154
+ /**
1155
+ * 转换标准消息为 ARK Responses API 格式
1156
+ */
1157
+ private convertMessages;
1158
+ /**
1159
+ * 解析 ARK 流式响应
1160
+ */
1161
+ private parseStream;
367
1162
  }
1163
+ /**
1164
+ * 创建 ARK Adapter
1165
+ */
1166
+ declare function createArkAdapter(config: AdapterConfig): ArkAdapter;
368
1167
 
369
1168
  /**
370
- * OpenRouter Provider
1169
+ * OpenRouter Adapter
371
1170
  *
372
- * 使用 OpenAI 兼容格式,支持多种模型:
373
- * - Claude (anthropic/claude-*)
374
- * - GPT (openai/gpt-*)
375
- * - Gemini (google/gemini-*)
376
- *
377
- * 特性:
378
- * - Web Search 插件支持
379
- * - URL 引用 annotations
380
- * - Extended Thinking (reasoning) 支持
1171
+ * 职责:
1172
+ * - 将标准消息转换为 OpenAI 兼容格式
1173
+ * - 调用 API 并解析响应为标准 StreamChunk
1174
+ * - 不处理工具执行和消息历史
381
1175
  */
382
1176
 
383
- /** OpenRouter Provider 配置 */
384
- interface OpenRouterProviderConfig {
385
- apiKey: string;
386
- apiUrl?: string;
387
- }
1177
+ /** OpenRouter 支持的模型 */
1178
+ declare const OPENROUTER_MODELS: string[];
388
1179
  /**
389
- * OpenRouter Provider 实现
1180
+ * OpenRouter Adapter
1181
+ *
1182
+ * 使用 OpenAI 兼容 API 格式
390
1183
  */
391
- declare class OpenRouterProvider implements ChatProvider {
1184
+ declare class OpenRouterAdapter implements ProviderAdapter {
392
1185
  readonly name = "openrouter";
393
1186
  readonly supportedModels: string[];
394
1187
  private apiKey;
395
1188
  private apiUrl;
396
- constructor(config: OpenRouterProviderConfig);
1189
+ constructor(config: AdapterConfig);
397
1190
  supportsModel(model: string): boolean;
398
- getModelCapabilities(model: string): ModelCapabilities;
399
- /** 检查模型是否支持 Extended Thinking */
400
- private supportsThinking;
401
- chat(message: string, model: string, options: ChatOptions, context: ChatContext): AsyncGenerator<ChatProgress>;
402
- /** 调用 OpenRouter API */
403
- private callOpenRouter;
404
- }
405
-
406
- /**
407
- * 混合 Agent 类
408
- *
409
- * 职责:
410
- * 1. 管理多个 Provider
411
- * 2. 路由请求到正确的 Provider
412
- * 3. 管理对话历史和上下文
413
- * 4. 处理工具执行
414
- */
415
- declare class HybridAgent {
416
- private config;
417
- private providers;
418
- private geminiClient;
419
- private toolExecutor;
420
- private conversationHistory;
421
- private abortController;
422
- constructor(config: AgentConfig, toolExecutor?: ToolExecutor$1);
423
- /**
424
- * 初始化所有 Provider
425
- */
426
- private initializeProviders;
427
- /**
428
- * 判断模型提供商
429
- */
430
- private getModelProvider;
431
- /**
432
- * 获取 Provider
433
- */
434
- private getProvider;
435
- /**
436
- * 构建系统提示词
437
- */
438
- private buildSystemPrompt;
439
- /**
440
- * 获取默认深度思考模式(统一为 disabled)
441
- */
442
- private getDefaultThinkingMode;
443
1191
  /**
444
- * 执行工具
1192
+ * 单次流式调用
445
1193
  */
446
- private executeTool;
447
- /**
448
- * 聊天入口
449
- *
450
- * 使用 Provider 模式路由请求到对应的模型提供商
451
- */
452
- chat(message: string, options?: ChatOptions, images?: string[]): AsyncGenerator<ChatProgress>;
1194
+ streamOnce(messages: StandardMessage[], tools: SimpleToolDefinition[], options: StreamOnceOptions): AsyncGenerator<StreamChunk>;
453
1195
  /**
454
- * 中断当前请求
1196
+ * 转换标准消息为 OpenAI 格式
455
1197
  */
456
- abort(): void;
1198
+ private convertMessages;
457
1199
  /**
458
- * 清空对话历史
1200
+ * 解析 OpenAI 兼容流式响应
459
1201
  */
460
- clearHistory(): void;
1202
+ private parseStream;
1203
+ }
1204
+ /**
1205
+ * 创建 OpenRouter Adapter
1206
+ */
1207
+ declare function createOpenRouterAdapter(config: AdapterConfig): OpenRouterAdapter;
1208
+
1209
+ /**
1210
+ * Qwen (通义千问) Adapter
1211
+ *
1212
+ * 职责:
1213
+ * - 将标准消息转换为 DashScope 原生 API 格式
1214
+ * - 调用 API 并解析响应为标准 StreamChunk
1215
+ * - 不处理工具执行和消息历史
1216
+ */
1217
+
1218
+ /** Qwen 支持的模型 */
1219
+ declare const QWEN_MODELS: string[];
1220
+ /**
1221
+ * Qwen Adapter
1222
+ *
1223
+ * 使用 DashScope 原生协议
1224
+ */
1225
+ declare class QwenAdapter implements ProviderAdapter {
1226
+ readonly name = "qwen";
1227
+ readonly supportedModels: string[];
1228
+ private apiKey;
1229
+ private apiUrl;
1230
+ constructor(config: AdapterConfig);
1231
+ supportsModel(model: string): boolean;
461
1232
  /**
462
- * 获取对话历史
1233
+ * 单次流式调用
463
1234
  */
464
- getHistory(): ChatMessage[];
1235
+ streamOnce(messages: StandardMessage[], tools: SimpleToolDefinition[], options: StreamOnceOptions): AsyncGenerator<StreamChunk>;
465
1236
  /**
466
- * 设置工作目录
1237
+ * 转换标准消息为 Qwen 格式
467
1238
  */
468
- setWorkingDir(dir: string): void;
1239
+ private convertMessages;
469
1240
  /**
470
- * 获取当前配置
1241
+ * 解析 Qwen 流式响应
471
1242
  */
472
- getConfig(): Required<AgentConfig>;
1243
+ private parseStream;
1244
+ }
1245
+ /**
1246
+ * 创建 Qwen Adapter
1247
+ */
1248
+ declare function createQwenAdapter(config: AdapterConfig): QwenAdapter;
1249
+
1250
+ /**
1251
+ * Gemini Adapter
1252
+ *
1253
+ * 职责:
1254
+ * - 将标准消息转换为 Gemini SDK 格式
1255
+ * - 调用 SDK 并解析响应为标准 StreamChunk
1256
+ * - 不处理工具执行和消息历史
1257
+ */
1258
+
1259
+ /** Gemini 支持的模型 */
1260
+ declare const GEMINI_MODELS: string[];
1261
+ /** Gemini Adapter 配置 */
1262
+ interface GeminiAdapterConfig {
1263
+ apiKey: string;
1264
+ }
1265
+ /**
1266
+ * Gemini Adapter
1267
+ *
1268
+ * 使用 @google/genai SDK
1269
+ */
1270
+ declare class GeminiAdapter implements ProviderAdapter {
1271
+ readonly name = "gemini";
1272
+ readonly supportedModels: string[];
1273
+ private client;
1274
+ private apiKey;
1275
+ constructor(config: GeminiAdapterConfig);
1276
+ /** 懒加载客户端 */
1277
+ private getClient;
1278
+ supportsModel(model: string): boolean;
473
1279
  /**
474
- * 获取模型能力
1280
+ * 单次流式调用
475
1281
  */
476
- getModelCapabilities(model: string): ModelCapabilities | undefined;
1282
+ streamOnce(messages: StandardMessage[], tools: SimpleToolDefinition[], options: StreamOnceOptions): AsyncGenerator<StreamChunk>;
477
1283
  /**
478
- * 获取所有支持的模型
1284
+ * 转换标准消息为 Gemini 格式
479
1285
  */
480
- getSupportedModels(): ModelConfig[];
1286
+ private convertMessages;
481
1287
  }
482
-
483
1288
  /**
484
- * 工具定义和默认执行器
1289
+ * 创建 Gemini Adapter
485
1290
  */
1291
+ declare function createGeminiAdapter(config: GeminiAdapterConfig): GeminiAdapter;
1292
+
1293
+ declare const DEFAULT_MODEL: string;
486
1294
 
487
1295
  /**
488
- * 创建工具定义
1296
+ * 工具执行器
489
1297
  */
490
- declare function createToolDefinitions(workingDir?: string): ToolDefinition[];
1298
+
491
1299
  /**
492
1300
  * 创建默认工具执行器(Node.js 环境)
1301
+ *
1302
+ * 用于执行 shell 命令,包含基本安全检查
1303
+ * 支持通过 AbortSignal 取消命令执行
1304
+ */
1305
+ declare function createDefaultToolExecutor(defaultCwd?: string): ToolExecutor$1;
1306
+
1307
+ /**
1308
+ * 获取当前工作目录工具(Vite 插件风格)
1309
+ */
1310
+
1311
+ declare function getCwdTool(): ToolPlugin;
1312
+
1313
+ /**
1314
+ * 获取平台信息工具(Vite 插件风格)
1315
+ */
1316
+
1317
+ declare function getPlatformTool(): ToolPlugin;
1318
+
1319
+ /**
1320
+ * 执行命令工具(Vite 插件风格)
1321
+ */
1322
+
1323
+ declare function executeCommandTool(): ToolPlugin;
1324
+
1325
+ /**
1326
+ * 分析图片工具(Vite 插件风格)
1327
+ */
1328
+
1329
+ declare function analyzeImageTool(): ToolPlugin;
1330
+
1331
+ /**
1332
+ * 生成图片工具(Vite 插件风格)
1333
+ */
1334
+
1335
+ declare function generateImageTool(): ToolPlugin;
1336
+
1337
+ /**
1338
+ * 分析视频工具(Vite 插件风格)
1339
+ */
1340
+
1341
+ declare function analyzeVideoTool(): ToolPlugin;
1342
+
1343
+ /**
1344
+ * 天气查询工具(Vite 插件风格)
1345
+ *
1346
+ * 使用高德天气 API
1347
+ * - 稳定可靠,国内服务
1348
+ * - 支持全国 337 个地级市
1349
+ * - 中文输出
1350
+ *
1351
+ * 返回数据格式匹配 @huyooo/ai-chat-shared 的 WeatherData 类型
1352
+ */
1353
+
1354
+ declare function getWeatherTool(): ToolPlugin;
1355
+
1356
+ /**
1357
+ * UI 动作工具(Vite 插件风格)
1358
+ *
1359
+ * 将前端 UI 事件封装成 AI 可调用的工具
1360
+ * 前端通过监听 onToolComplete 的 sideEffects 来执行相应的 UI 操作
1361
+ */
1362
+
1363
+ /**
1364
+ * 显示 Toast 通知
1365
+ */
1366
+ declare function showToastTool(): ToolPlugin;
1367
+ /**
1368
+ * 打开确认对话框
1369
+ */
1370
+ declare function openConfirmDialogTool(): ToolPlugin;
1371
+ /**
1372
+ * 打开文件预览
1373
+ */
1374
+ declare function openFilePreviewTool(): ToolPlugin;
1375
+ /**
1376
+ * 跳转到指定目录
1377
+ */
1378
+ declare function navigateToDirectoryTool(): ToolPlugin;
1379
+ /**
1380
+ * 所有 UI 动作工具(已废弃,使用函数形式)
1381
+ * @deprecated 使用 showToastTool() 等函数形式
1382
+ */
1383
+ declare const uiActionTools: ToolPlugin[];
1384
+
1385
+ /**
1386
+ * 文档搜索工具集成
1387
+ *
1388
+ * 可选依赖 @huyooo/ai-search
1389
+ * 如果未安装,工具会返回友好提示
1390
+ *
1391
+ * 注意:这个模块使用 eval + require 来避免 tsup 打包时解析依赖
1392
+ */
1393
+
1394
+ /**
1395
+ * 搜索工具配置
1396
+ */
1397
+ interface SearchToolsOptions {
1398
+ /** 搜索数据存储目录 */
1399
+ dataDir?: string;
1400
+ /** 默认索引目录(首次使用时自动索引) */
1401
+ defaultDirectories?: string[];
1402
+ /** 是否在初始化时自动索引 */
1403
+ autoIndex?: boolean;
1404
+ }
1405
+ /**
1406
+ * 创建文档搜索工具
1407
+ *
1408
+ * 如果 @huyooo/ai-search 未安装,返回占位工具(提示用户安装)
1409
+ *
1410
+ * @example
1411
+ * ```typescript
1412
+ * import { createDocumentSearchTools } from '@huyooo/ai-chat-core';
1413
+ *
1414
+ * const searchTools = await createDocumentSearchTools({
1415
+ * dataDir: './.search-data',
1416
+ * defaultDirectories: ['~/Documents'],
1417
+ * });
1418
+ *
1419
+ * const agent = new HybridAgent({
1420
+ * ...config,
1421
+ * tools: [...otherTools, ...searchTools],
1422
+ * });
1423
+ * ```
1424
+ */
1425
+ declare function createDocumentSearchTools(options?: SearchToolsOptions): Promise<Tool[]>;
1426
+ /**
1427
+ * 获取搜索插件实例(高级用法)
493
1428
  */
494
- declare function createDefaultToolExecutor(workingDir?: string): ToolExecutor$1;
1429
+ declare function getDocumentSearchInstance(dataDir?: string, workspace?: string): Promise<{
1430
+ tools: Tool[];
1431
+ [key: string]: unknown;
1432
+ } | null>;
495
1433
 
496
- export { AVAILABLE_MODELS, type AgentConfig, ArkProvider, type ChatContext, type ChatMessage, type ChatMode, type ChatOptions, type ChatProgress, type ChatProgressType, type ChatProvider, type DeepSeekMessage, type DeepSeekTool, GeminiProvider, HybridAgent, type ImageProgress, type ModelCapabilities, type ModelConfig, type ModelProvider, OpenRouterProvider, type ToolExecutor as ProviderToolExecutor, QwenProvider, type SearchResultProgress, type SearchStartProgress, type TextDeltaProgress, type TextProgress, type ThinkingMode, type ThinkingProgress, type ToolCallProgress, type ToolDefinition, type ToolExecutor$1 as ToolExecutor, type ToolResultProgress, createDefaultToolExecutor, createToolDefinitions };
1434
+ export { ARK_MODELS, type AbortEvent, type AdapterConfig, type AgentConfig, ArkAdapter, type AutoRunConfig$1 as AutoRunConfig, type AutoRunMode, type ChatEvent, type ChatEventType, type ChatMessage, type ChatMode, type ChatOptions, ChatOrchestrator, DEFAULT_MODEL, type DoneEvent, type ErrorCategory, type ErrorDetails, type ErrorEvent, GEMINI_MODELS, GeminiAdapter, HybridAgent, type ImageEvent, MODELS, type MediaEvent, type ModelOption, OPENROUTER_MODELS, OpenRouterAdapter, type OrchestratorConfig, type OrchestratorContext, type OrchestratorOptions, type ToolExecutor as OrchestratorToolExecutor, type ProviderAdapter, type ProviderType, QWEN_MODELS, QwenAdapter, type ResponsesApiTool, type RouteMatchType, type RouteResult, type RouteRule, type RuntimeConfig, type SearchEndEvent, type SearchEvent, type SearchResult, type SearchResultEvent, type SearchResultItem, type SearchStartEvent, type SearchToolsOptions, type SideEffect$1 as SideEffect, type SimpleToolDefinition, type StandardMessage, type StatusEvent, type StepEndEvent, type StepEvent, type StepStartEvent, type StreamChunk, type StreamChunkType, type StreamOnceOptions, type StreamStartEvent, type TextDeltaEvent, type TextEvent, type ThinkingDeltaEvent, type ThinkingEndEvent, type ThinkingEvent, type ThinkingMode, type ThinkingStartEvent, type TokenUsage, type Tool, type ToolCallInfo, type ToolCallRequest, type ToolCallResultEvent, type ToolCallStartEvent, type ToolCallStatus, type ToolConfigItem, type ToolContext, type ToolDefinition, type ToolEvent, type ToolExecutor$1 as ToolExecutor, type ToolPlugin, type ToolResult, type VideoEvent, analyzeImageTool, analyzeVideoTool, createAbort, createApiError, createArkAdapter, createDefaultToolExecutor, createDocumentSearchTools, createDone, createError, createGeminiAdapter, createImage, createOpenRouterAdapter, createOrchestrator, createParseError, createQwenAdapter, createRateLimitError, createSearchEnd, createSearchResult, createSearchStart, createStepEnd, createStepStart, createStreamStart, createTextDelta, createThinkingDelta, createThinkingEnd, createThinkingStart, createTimeoutError, createToolCallResult, createToolCallStart, createToolError, createVideo, executeCommandTool, generateImageTool, getCwdTool, getDefaultProvider, getDocumentSearchInstance, getModelByModelId, getNativeModels, getOpenRouterModels, getPlatformTool, getRouteRules, getWeatherTool, isAbortEvent, isErrorEvent, isMediaEvent, isModelForProvider, isRetryableError, isSearchEvent, isStatusEvent, isStepEvent, isTextEvent, isThinkingEvent, isToolEvent, navigateToDirectoryTool, openConfirmDialogTool, openFilePreviewTool, resolveTools, routeModelToProvider, routeModelWithDetails, showToastTool, tool, tools, uiActionTools };