@cicctencent/agent-core 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +14 -927
  2. package/dist/cjs/agent/engine.d.ts.map +1 -1
  3. package/dist/cjs/agent/engine.js +1 -0
  4. package/dist/cjs/agent/engine.js.map +1 -1
  5. package/dist/cjs/agent/tool-executor.d.ts +4 -0
  6. package/dist/cjs/agent/tool-executor.d.ts.map +1 -1
  7. package/dist/cjs/agent/tool-executor.js +13 -0
  8. package/dist/cjs/agent/tool-executor.js.map +1 -1
  9. package/dist/cjs/index.d.ts +1 -0
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js.map +1 -1
  12. package/dist/cjs/security/guard.d.ts +1 -6
  13. package/dist/cjs/security/guard.d.ts.map +1 -1
  14. package/dist/cjs/security/guard.js +89 -27
  15. package/dist/cjs/security/guard.js.map +1 -1
  16. package/dist/cjs/security/types.d.ts +6 -2
  17. package/dist/cjs/security/types.d.ts.map +1 -1
  18. package/dist/cjs/tool/registry.d.ts +26 -1
  19. package/dist/cjs/tool/registry.d.ts.map +1 -1
  20. package/dist/cjs/tool/registry.js +30 -0
  21. package/dist/cjs/tool/registry.js.map +1 -1
  22. package/dist/esm/agent/engine.d.ts.map +1 -1
  23. package/dist/esm/agent/engine.js +1 -0
  24. package/dist/esm/agent/engine.js.map +1 -1
  25. package/dist/esm/agent/tool-executor.d.ts +4 -0
  26. package/dist/esm/agent/tool-executor.d.ts.map +1 -1
  27. package/dist/esm/agent/tool-executor.js +13 -0
  28. package/dist/esm/agent/tool-executor.js.map +1 -1
  29. package/dist/esm/index.d.ts +1 -0
  30. package/dist/esm/index.d.ts.map +1 -1
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/security/guard.d.ts +1 -6
  33. package/dist/esm/security/guard.d.ts.map +1 -1
  34. package/dist/esm/security/guard.js +89 -27
  35. package/dist/esm/security/guard.js.map +1 -1
  36. package/dist/esm/security/types.d.ts +6 -2
  37. package/dist/esm/security/types.d.ts.map +1 -1
  38. package/dist/esm/tool/registry.d.ts +26 -1
  39. package/dist/esm/tool/registry.d.ts.map +1 -1
  40. package/dist/esm/tool/registry.js +30 -0
  41. package/dist/esm/tool/registry.js.map +1 -1
  42. package/package.json +4 -5
package/README.md CHANGED
@@ -1,952 +1,39 @@
1
1
  # @cicctencent/agent-core
2
2
 
3
- > Core engine for AI agent — LLM orchestration, ReAct loop, tool execution, MCP integration, skill routing, security guard, and memory pipeline.
3
+ > **内部库,仅供项目内部使用,不对外发布。**
4
4
 
5
- 一个框架无关的 AI Agent 核心引擎库。提供完整的 ReAct 循环编排、多 LLM 供应商抽象、工具注册与执行、MCP 协议集成、Skill 路由、安全守卫和渐进式记忆管道。不绑定任何特定框架或运行时,通过接口注入实现上层适配。
5
+ AI Agent 核心引擎,提供 ReAct 循环编排、多 LLM 供应商抽象、工具注册与执行、MCP 协议集成、Skill 路由、安全守卫和渐进式记忆管道。
6
6
 
7
- ---
7
+ ## 文档
8
8
 
9
- ## 目录
10
-
11
- - [架构概览](#架构概览)
12
- - [快速开始](#快速开始)
13
- - [模块详解](#模块详解)
14
- - [AgentEngine — ReAct 循环引擎](#agentengine--react-循环引擎)
15
- - [LLM Provider — 多供应商抽象](#llm-provider--多供应商抽象)
16
- - [Tool Registry — 工具注册与执行](#tool-registry--工具注册与执行)
17
- - [MCP — 模型上下文协议](#mcp--模型上下文协议)
18
- - [Skill — 技能管理与路由](#skill--技能管理与路由)
19
- - [Security — 安全守卫](#security--安全守卫)
20
- - [Sandbox — 沙箱类型定义](#sandbox--沙箱类型定义)
21
- - [Context — 上下文构建](#context--上下文构建)
22
- - [Hooks — 生命周期钩子](#hooks--生命周期钩子)
23
- - [Middleware — 中间件管道](#middleware--中间件管道)
24
- - [Memory — 渐进式记忆管道](#memory--渐进式记忆管道)
25
- - [Workflow — 复杂工作流模板](#workflow--复杂工作流模板)
26
- - [TypeScript 配置](#typescript-配置)
27
- - [依赖说明](#依赖说明)
28
-
29
- ---
30
-
31
- ## 架构概览
32
-
33
- ```
34
- ┌──────────────────────────────────────────────────────────┐
35
- │ 上层应用 (Server/App) │
36
- │ 提供:ShellExecutor, FileSystemExecutor, MemoryService, │
37
- │ SubAgentRunner, SSE 事件流, 沙箱实现 │
38
- └────────────────────────┬─────────────────────────────────┘
39
- │ 接口注入
40
- ┌────────────────────────▼─────────────────────────────────┐
41
- │ @cicctencent/agent-core │
42
- │ │
43
- │ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
44
- │ │ AgentEngine │ │ ToolRegistry │ │ SecurityGuard │ │
45
- │ │ (ReAct 循环) │←→│ (工具注册表) │ │ (安全守卫) │ │
46
- │ └──────┬──────┘ └──────┬───────┘ └──────────────────┘ │
47
- │ │ │ │
48
- │ ┌──────▼──────┐ ┌──────▼───────┐ ┌──────────────────┐ │
49
- │ │ LLMCaller │ │ MCP Clients │ │ SkillRouter │ │
50
- │ │ (LLM 调用) │ │ (远程工具) │ │ (技能路由) │ │
51
- │ └──────┬──────┘ └──────────────┘ └──────────────────┘ │
52
- │ │ │
53
- │ ┌──────▼──────────────────────────────────────────────┐ │
54
- │ │ LLM Provider (OpenAI / Anthropic / Ollama / Custom) │ │
55
- │ └─────────────────────────────────────────────────────┘ │
56
- │ │
57
- │ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
58
- │ │ MemoryPipe │ │ Hooks/MW │ │ ContextManager │ │
59
- │ │ (L1→L2→L3) │ │ (生命周期) │ │ (消息构建) │ │
60
- │ └─────────────┘ └──────────────┘ └──────────────────┘ │
61
- └──────────────────────────────────────────────────────────┘
62
- ```
63
-
64
- **核心设计原则**:
65
- - **接口隔离**:Core 不实现 Shell、文件系统、沙箱、持久化等能力,由上层通过 `ShellExecutor`、`FileSystemExecutor`、`Sandbox` 等接口注入
66
- - **ESM 原生**:所有内部导入使用显式 `.ts` 扩展名,兼容 Node.js ESM 和 TypeScript bundler
67
- - **流式优先**:Agent 执行通过 `AsyncGenerator<AgentEvent>` 逐事件推送,支持 SSE 实时流
68
-
69
- ---
9
+ 完整 API 文档请查阅 [docs/API.md](./docs/API.md)。
70
10
 
71
11
  ## 快速开始
72
12
 
73
- ### 安装
74
-
75
13
  ```bash
76
14
  pnpm add @cicctencent/agent-core
77
15
  ```
78
16
 
79
- ### 最小示例
80
-
81
17
  ```typescript
82
- import {
83
- AgentEngine,
84
- createLLMProvider,
85
- ToolRegistry,
86
- ContextManager,
87
- } from '@cicctencent/agent-core';
18
+ import { AgentEngine, createLLMProvider, ToolRegistry, ContextManager } from '@cicctencent/agent-core';
88
19
 
89
- // 1. 创建 LLM Provider
90
- const llm = createLLMProvider({
91
- provider: 'openai',
92
- model: 'gpt-4o',
93
- apiKey: process.env.OPENAI_API_KEY!,
94
- });
95
-
96
- // 2. 创建工具注册表并注册工具
20
+ const llm = createLLMProvider({ provider: 'openai', model: 'gpt-4o', apiKey: process.env.OPENAI_API_KEY! });
97
21
  const toolRegistry = new ToolRegistry();
98
- toolRegistry.register({
99
- definition: {
100
- type: 'function',
101
- function: {
102
- name: 'get_time',
103
- description: 'Get current time',
104
- parameters: { type: 'object', properties: {}, required: [] },
105
- },
106
- },
107
- executor: async () => new Date().toISOString(),
108
- category: 'builtin',
109
- });
110
-
111
- // 3. 创建引擎
112
- const engine = new AgentEngine({
113
- llmProvider: llm,
114
- toolRegistry,
115
- contextManager: new ContextManager(),
116
- maxIterations: 10,
117
- });
118
-
119
- // 4. 运行(流式事件推送)
120
- const events = engine.run({
121
- sessionId: 'session-001',
122
- message: 'What time is it?',
123
- });
22
+ const engine = new AgentEngine({ llmProvider: llm, toolRegistry, contextManager: new ContextManager(), maxIterations: 10 });
124
23
 
125
- for await (const event of events) {
24
+ for await (const event of engine.run({ sessionId: 'session-001', message: 'Hello' })) {
126
25
  if (event.type === 'message') process.stdout.write(event.content);
127
26
  if (event.type === 'done') console.log('\nDone:', event.content);
128
- if (event.type === 'error') console.error('Error:', event.error);
129
- }
130
- ```
131
-
132
- ---
133
-
134
- ## 模块详解
135
-
136
- ### AgentEngine — ReAct 循环引擎
137
-
138
- **文件**:`agent/engine.ts` | **导出**:`AgentEngine`
139
-
140
- 核心编排层,实现 Reasoning + Acting 循环:
141
-
142
- ```
143
- 用户消息 → [构建上下文] → [LLM 推理] → [解析响应]
144
-
145
- ┌─────────────────────────┤
146
- ▼ ▼
147
- tool_calls 存在? 纯文本响应
148
- │ │
149
- [执行工具] → [结果回注] [done 事件]
150
-
151
- 回到 LLM 推理(下一轮迭代)
152
- ```
153
-
154
- #### 构造参数 `AgentConfig`
155
-
156
- | 参数 | 类型 | 默认值 | 说明 |
157
- |---|---|---|---|
158
- | `llmProvider` | `LLMProvider` | **必填** | LLM 供应商实例 |
159
- | `toolRegistry` | `ToolRegistry` | **必填** | 工具注册表实例 |
160
- | `contextManager` | `ContextManager` | **必填** | 上下文构建器 |
161
- | `maxIterations` | `number` | `15` | 单次任务最大迭代轮次 |
162
- | `maxMessages` | `number` | `50` | 消息历史滑动窗口大小 |
163
- | `toolTimeout` | `number` | `30000` | 单工具执行超时(ms) |
164
- | `llmTimeout` | `number` | `120000` | LLM 推理超时(ms) |
165
- | `basePrompt` | `string` | 内置默认 | Agent 系统提示词基础模板 |
166
- | `skillManager` | `SkillManager` | — | Skill 管理器(可选) |
167
- | `skillRouter` | `SkillRouter` | — | Skill 路由器(可选) |
168
- | `securityGuard` | `SecurityGuard` | — | 安全守卫(可选) |
169
- | `hooks` | `Hook[]` | — | 生命周期钩子列表 |
170
- | `middleware` | `Middleware[]` | — | 中间件管道 |
171
- | `retryPolicy` | `RetryPolicy` | — | LLM 调用重试策略 |
172
- | `fallbackProvider` | `LLMProvider` | — | 降级 LLM Provider |
173
- | `toolResultStore` | `ToolResultStore` | — | 大结果存储(写文件,按需读取) |
174
- | `contextBudget` | `object` | — | 上下文压缩配置 |
175
- | `contextBudget.maxToolOutput` | `number` | `8000` | 单工具输出最大字符数 |
176
- | `contextBudget.compactThreshold` | `number` | `maxMessages*0.8` | 触发压缩的消息数阈值 |
177
- | `contextBudget.maxContextTokens` | `number` | `100000` | 上下文总 token 预算 |
178
- | `toolDiscovery` | `'full' \| 'summary'` | `'full'` | 工具发现模式 |
179
- | `deniedTools` | `string[]` | — | 全局禁止的工具名 |
180
- | `defaultTools` | `string[]` | — | 默认工具列表 |
181
- | `dataFetchTools` | `string[]` | 内置列表 | 数据获取类工具(循环检测用) |
182
- | `outputTools` | `string[]` | 内置列表 | 产出型工具(免循环检测) |
183
-
184
- #### 运行方法 `engine.run(options)`
185
-
186
- ```typescript
187
- const events = engine.run({
188
- sessionId: string; // 会话 ID
189
- message: string; // 用户输入
190
- skillId?: string; // 指定 Skill(跳过路由)
191
- extraTools?: string[]; // 动态注入额外工具名
192
- context?: SessionContext; // 会话上下文
193
- abortSignal?: AbortSignal; // 取消信号
194
- systemPromptOverride?: string; // 覆盖 system prompt 片段
195
- });
196
-
197
- // 返回 AsyncGenerator<AgentEvent>
198
- for await (const event of events) { /* 处理事件 */ }
199
- ```
200
-
201
- #### 事件流 `AgentEvent`(discriminated union)
202
-
203
- ```typescript
204
- type AgentEvent =
205
- | ThinkingEvent // { type: 'thinking', content?: string } LLM 推理
206
- | ToolCallEvent // { type: 'tool_call', tool, args, callId } 请求工具
207
- | ToolResultEvent // { type: 'tool_result', tool, result, isError, duration, callId }
208
- | MessageEvent // { type: 'message', content, delta } 流式文本
209
- | DoneEvent // { type: 'done', content, iterations, usage } 完成
210
- | ErrorEvent // { type: 'error', error, recoverable } 出错
211
- | SteeringEvent // { type: 'steering', messages, count } 实时转向
212
- | RetryEvent; // { type: 'retry', attempt, maxRetries, delay, error, provider }
213
- ```
214
-
215
- 所有事件都继承 `BaseEvent`:`{ timestamp, sessionId, metadata? }`
216
-
217
- ---
218
-
219
- ### LLM Provider — 多供应商抽象
220
-
221
- **文件**:`llm/types.ts`, `llm/factory.ts`, `llm/openai-provider.ts`, `llm/anthropic-provider.ts`, `llm/ollama-provider.ts`
222
-
223
- #### 接口 `LLMProvider`
224
-
225
- ```typescript
226
- interface LLMProvider {
227
- chat(params: ChatParams): Promise<ChatResponse>; // 非流式推理
228
- chatStream(params: ChatParams): AsyncGenerator<ChatChunk>; // 流式推理
229
- getModel(): ModelInfo; // 模型信息
230
- ping(): Promise<boolean>; // 连接测试
231
- }
232
- ```
233
-
234
- #### 工厂 `createLLMProvider(config)`
235
-
236
- ```typescript
237
- import { createLLMProvider } from '@cicctencent/agent-core';
238
-
239
- const llm = createLLMProvider({
240
- provider: 'openai', // 'openai' | 'anthropic' | 'ollama' | 任意 OpenAI 兼容供应商
241
- model: 'gpt-4o',
242
- apiKey: 'sk-...',
243
- baseUrl: 'https://api.openai.com/v1', // 可选,自定义端点
244
- temperature: 0.7,
245
- maxTokens: 4096,
246
- timeout: 60000,
247
- extra: {}, // 供应商特定参数透传
248
- proxy: dispatcher, // undici Dispatcher(运行时注入)
249
- });
250
- ```
251
-
252
- 内置供应商:`'openai'` → `OpenAIProvider`、`'anthropic'` → `AnthropicProvider`、`'ollama'` → `OllamaProvider`。其他任意字符串均使用 `OpenAIProvider`(兼容 DeepSeek/vLLM/Together 等)。
253
-
254
- #### 请求参数 `ChatParams`
255
-
256
- ```typescript
257
- interface ChatParams {
258
- messages: Message[];
259
- tools?: ToolDefinition[];
260
- toolChoice?: 'auto' | 'none' | { type: 'function'; function: { name: string } };
261
- temperature?: number;
262
- maxTokens?: number;
263
- abortSignal?: AbortSignal;
264
- }
265
- ```
266
-
267
- #### 消息格式 `Message`
268
-
269
- 兼容 OpenAI Chat Completion 格式:
270
-
271
- ```typescript
272
- interface Message {
273
- role: 'system' | 'user' | 'assistant' | 'tool';
274
- content: string | null;
275
- tool_calls?: ToolCall[]; // assistant 的工具调用请求
276
- tool_call_id?: string; // tool 消息对应的 call id
277
- name?: string;
278
- reasoning_content?: string | null; // DeepSeek R1 推理内容
279
- metadata?: Record<string, unknown>;
280
- }
281
- ```
282
-
283
- ---
284
-
285
- ### Tool Registry — 工具注册与执行
286
-
287
- **文件**:`tool/registry.ts`, `tool/types.ts`, `tool/delegate.ts`
288
-
289
- #### `ToolRegistry` 类
290
-
291
- ```typescript
292
- import { ToolRegistry } from '@cicctencent/agent-core';
293
-
294
- const registry = new ToolRegistry();
295
-
296
- // 注册单个工具
297
- registry.register({
298
- definition: { /* OpenAI Function Calling schema */ },
299
- executor: async (args, ctx) => { /* 执行逻辑 */ return 'result'; },
300
- category: 'builtin', // 'builtin' | 'skill' | 'mcp' | 'custom'
301
- concurrent: false, // 是否支持并行执行
302
- metadata: {},
303
- });
304
-
305
- // 批量注册
306
- registry.registerAll(tools);
307
-
308
- // 查询
309
- registry.has('get_time'); // boolean
310
- registry.get('get_time'); // RegisteredTool | undefined
311
- registry.listNames(); // string[]
312
- registry.getDefinitions({ // ToolDefinition[](传给 LLM)
313
- category: 'builtin',
314
- names: ['get_time', 'calc'],
315
- });
316
-
317
- // 执行(内部调用)
318
- await registry.execute('get_time', {}, ctx);
319
-
320
- // 注销
321
- registry.unregister('get_time');
322
- ```
323
-
324
- #### 工具定义格式 `ToolDefinition`
325
-
326
- 遵循 OpenAI Function Calling 规范:
327
-
328
- ```typescript
329
- interface ToolDefinition {
330
- type: 'function';
331
- function: {
332
- name: string;
333
- description: string;
334
- parameters: {
335
- type: 'object';
336
- properties: Record<string, { type: string; description: string; enum?: string[]; /* ... */ }>;
337
- required?: string[];
338
- };
339
- };
340
- }
341
- ```
342
-
343
- #### 工具执行上下文 `ToolContext`
344
-
345
- 由 `AgentEngine` 自动注入到每个 executor:
346
-
347
- ```typescript
348
- interface ToolContext {
349
- sessionId: string;
350
- shell: ShellExecutor; // Shell 执行能力(上层注入)
351
- fs?: FileSystemExecutor; // 文件系统操作(上层注入)
352
- env?: EnvInfo; // 环境信息
353
- abortSignal: AbortSignal; // 取消信号
354
- custom?: Record<string, unknown>; // 上层自定义能力
355
- emitSubEvent?: SubAgentEventEmitter; // 子 Agent 事件转发
356
- emitWidget?: WidgetEventEmitter; // Widget 事件发射
357
- emitArtifact?: ArtifactEventEmitter; // Artifact 事件发射
358
- currentToolCallId?: string;
359
- }
360
- ```
361
-
362
- #### 上层需实现的接口
363
-
364
- ```typescript
365
- // Shell 执行器
366
- interface ShellExecutor {
367
- exec(command: string, timeout?: number): Promise<string>;
368
- write(data: string): void;
369
- read(lines?: number): string;
370
- }
371
-
372
- // 文件系统执行器
373
- interface FileSystemExecutor {
374
- readFile(path: string): Promise<string>;
375
- readFileBuffer?(path: string): Promise<Buffer>;
376
- writeFile(path: string, content: string): Promise<void>;
377
- appendFile?(path: string, content: string): Promise<void>;
378
- listDir(path: string): Promise<string[]>;
379
- }
380
- ```
381
-
382
- #### DelegateTool — 任务分发
383
-
384
- ```typescript
385
- import { createDelegateTool } from '@cicctencent/agent-core';
386
-
387
- const delegateTool = createDelegateTool([
388
- { name: 'researcher', description: 'Deep research and analysis', run: async (task, ctx) => '...' },
389
- { name: 'coder', description: 'Code generation and review', run: async (task, ctx) => '...' },
390
- ]);
391
-
392
- if (delegateTool) registry.register(delegateTool);
393
- ```
394
-
395
- 生成 `delegate_task` 工具,LLM 可根据 agent name/description 智能分发子任务。
396
-
397
- ---
398
-
399
- ### MCP — 模型上下文协议
400
-
401
- **文件**:`mcp/types.ts`, `mcp/factory.ts`, `mcp/client.ts`, `mcp/stdio-client.ts`, `mcp/http-client.ts`
402
-
403
- #### MCP 客户端接口
404
-
405
- ```typescript
406
- interface MCPClient {
407
- connect(config: MCPServerConfig): Promise<void>;
408
- listTools(): Promise<ToolDefinition[]>;
409
- callTool(name: string, args: Record<string, unknown>): Promise<string>;
410
- listResources?(): Promise<Array<{ uri: string; name: string; description?: string }>>;
411
- readResource?(uri: string): Promise<string>;
412
- disconnect(): void;
413
- isConnected(): boolean;
414
- }
415
- ```
416
-
417
- #### 工厂 `createMCPClient(config)`
418
-
419
- ```typescript
420
- import { createMCPClient, registerTransport } from '@cicctencent/agent-core';
421
-
422
- // 内置 transport:stdio / http / sse / streamableHttp
423
- const client = createMCPClient({
424
- name: 'my-server',
425
- transport: 'stdio',
426
- command: 'node',
427
- args: ['server.js'],
428
- env: { API_KEY: '...' },
429
- });
430
-
431
- // HTTP/SSE transport
432
- const httpClient = createMCPClient({
433
- name: 'remote-server',
434
- transport: 'http',
435
- endpoint: 'https://mcp.example.com',
436
- headers: { Authorization: 'Bearer ...' },
437
- auth: { type: 'bearer', value: 'token123' },
438
- proxy: 'socks5://proxy:1080', // 支持 HTTP/HTTPS/SOCKS 代理
439
- });
440
-
441
- // 注册自定义 transport
442
- registerTransport('api-bridge', () => new MyCustomClient());
443
- const customClient = createMCPClient({ name: 'custom', transport: 'api-bridge' });
444
- ```
445
-
446
- #### 服务器配置 `MCPServerConfig`
447
-
448
- ```typescript
449
- interface MCPServerConfig {
450
- name: string;
451
- transport: 'stdio' | 'http' | 'sse' | 'streamableHttp' | string;
452
- command?: string; // stdio: 启动命令
453
- args?: string[]; // stdio: 命令参数
454
- env?: Record<string, string>; // stdio: 环境变量
455
- endpoint?: string; // HTTP/SSE: 服务端点
456
- headers?: Record<string, string>; // HTTP/SSE: 自定义请求头
457
- auth?: { type: 'bearer' | 'basic' | 'apiKey' | 'custom'; value: string; name?: string };
458
- timeout?: number;
459
- autoReconnect?: boolean | { maxRetries?: number; interval?: number };
460
- proxy?: string; // 代理 URL(HTTP/HTTPS/SOCKS4/SOCKS5)
461
- extra?: Record<string, unknown>; // 扩展配置
462
- }
463
- ```
464
-
465
- #### 工具注册辅助
466
-
467
- ```typescript
468
- import { registerMCPTools, buildMCPToolName, MCP_TOOL_PREFIX } from '@cicctencent/agent-core';
469
-
470
- // 自动发现并注册 MCP 远程工具到 ToolRegistry
471
- await registerMCPTools(toolRegistry, mcpClient, {
472
- serverName: 'my-server',
473
- connectorId: 'my-connector', // 可选,用于命名空间隔离
474
- });
475
-
476
- // 工具名格式:mcp_{connectorId}_{serverName}_{toolName} 或 mcp_{serverName}_{toolName}
477
- const name = buildMCPToolName('search', 'brave', 'my-connector');
478
- // → "mcp_my_connector_brave_search"
479
- ```
480
-
481
- ---
482
-
483
- ### Skill — 技能管理与路由
484
-
485
- **文件**:`skill/types.ts`, `skill/manager.ts`, `skill/router.ts`
486
-
487
- #### SkillManager — 懒加载技能管理
488
-
489
- ```typescript
490
- import { SkillManager } from '@cicctencent/agent-core';
491
-
492
- const skillManager = new SkillManager({
493
- skills: [], // 初始 Skill 列表
494
- lazy: true, // 启用懒加载(仅加载 manifest,content 按需读取)
495
- cacheSize: 50, // LRU 缓存大小
496
- });
497
-
498
- // 注册 Skill
499
- skillManager.register(skill);
500
-
501
- // 获取(懒加载时自动从 filePath 读取 content)
502
- const skill = skillManager.get('stock-analysis');
503
-
504
- // 获取所有 manifest(轻量,不含 content)
505
- const manifests = skillManager.getAllManifests();
506
-
507
- // 获取所有完整 Skill
508
- const allSkills = skillManager.getAll();
509
- ```
510
-
511
- #### Skill 数据结构
512
-
513
- ```typescript
514
- interface SkillManifest {
515
- id: string;
516
- name: string;
517
- description: string;
518
- tags: string[]; // 关键词(路由匹配用)
519
- aliases: string[]; // 同义词
520
- source: 'system' | 'user' | 'remote';
521
- version?: string;
522
- requires?: string[]; // 依赖的 MCP 工具名
523
- referencedSkills?: string[]; // 引用的其他 Skill ID
524
- filePath?: string; // 懒加载路径
525
- contentSize?: number;
526
- metadata?: Record<string, unknown>;
527
- }
528
-
529
- interface Skill extends SkillManifest {
530
- content: string; // Skill 正文(懒加载时可能为空)
531
- }
532
- ```
533
-
534
- #### SkillRouter — 三级路由
535
-
536
- ```typescript
537
- import { SkillRouter } from '@cicctencent/agent-core';
538
-
539
- const router = new SkillRouter(skillManager);
540
-
541
- // 添加自定义路由策略
542
- router.addStrategy({
543
- name: 'priority',
544
- match: async (message, skills) => {
545
- if (message.includes('urgent')) return { skill: skills[0], message, matchType: 'custom', confidence: 1 };
546
- return null;
547
- },
548
- });
549
-
550
- // 路由(三级:自定义策略 → 显式 /command → 关键词匹配)
551
- const result = await router.route('/stock-analysis AAPL');
552
- // → { skill: Skill, message: 'AAPL', matchType: 'explicit', confidence: 1 }
553
-
554
- // 未命中时返回 { skill: null },Engine 会在 system prompt 注入 skill catalog
555
- ```
556
-
557
- ---
558
-
559
- ### Security — 安全守卫
560
-
561
- **文件**:`security/guard.ts`, `security/types.ts`
562
-
563
- #### SecurityGuard
564
-
565
- ```typescript
566
- import { SecurityGuard } from '@cicctencent/agent-core';
567
-
568
- const guard = new SecurityGuard({
569
- deleteProtection: true, // rm → mv 到回收站
570
- trashDir: '~/.workagent/.trash',
571
- blacklistEnabled: true,
572
- rules: [
573
- {
574
- name: 'block-format',
575
- pattern: /^mkfs\b/,
576
- severity: 'blocked',
577
- action: 'block',
578
- description: 'Block disk format',
579
- },
580
- {
581
- name: 'rewrite-rm',
582
- pattern: /^rm\s+-rf\s+(?!\/)/,
583
- severity: 'danger',
584
- action: 'rewrite',
585
- rewriter: (cmd) => cmd.replace('rm -rf', 'mv'),
586
- },
587
- ],
588
- });
589
-
590
- // 检查命令
591
- const result = guard.sanitize('rm -rf /tmp/test');
592
- // → { safe: false, severity: 'blocked', reason: '...' }
593
-
594
- // 检查凭证泄露
595
- const leaked = guard.detectCredentials('export API_KEY=sk-abc123...');
596
- // → [{ name: 'openai-key', match: 'sk-abc123...' }]
597
- ```
598
-
599
- #### SanitizeResult
600
-
601
- ```typescript
602
- interface SanitizeResult {
603
- safe: boolean;
604
- rewritten?: string; // 改写后的命令
605
- reason?: string; // 拒绝/警告原因
606
- severity: 'safe' | 'warn' | 'danger' | 'blocked';
607
- }
608
- ```
609
-
610
- ---
611
-
612
- ### Sandbox — 沙箱类型定义
613
-
614
- **文件**:`sandbox/types.ts`
615
-
616
- Core 层仅定义沙箱接口和安全规则常量,**不提供实现**(由上层实现)。
617
-
618
- ```typescript
619
- interface Sandbox {
620
- readonly id: string;
621
- readonly rootDir: string;
622
- getShellExecutor(): ShellExecutor;
623
- getFileSystemExecutor(): FileSystemExecutor;
624
- runScript(language: 'python' | 'nodejs' | 'shell', code: string, timeout?: number): Promise<string>;
625
- destroy(): Promise<void>;
626
- }
627
-
628
- interface SandboxManager {
629
- create(id: string, config?: Partial<SandboxConfig>): Promise<Sandbox>;
630
- get(id: string): Sandbox | undefined;
631
- destroy(id: string): Promise<void>;
632
- destroyAll(): Promise<void>;
633
- }
634
- ```
635
-
636
- 内置安全常量(上层实现沙箱时可直接使用):
637
-
638
- ```typescript
639
- import { SANDBOX_BLOCKED_COMMANDS, SANDBOX_SAFE_ENV_KEYS, DEFAULT_SANDBOX_CONFIG } from '@cicctencent/agent-core';
640
- ```
641
-
642
- ---
643
-
644
- ### Context — 上下文构建
645
-
646
- **文件**:`context/manager.ts`, `context/types.ts`, `context/collector.ts`
647
-
648
- #### ContextManager(纯函数式,无状态)
649
-
650
- ```typescript
651
- import { ContextManager } from '@cicctencent/agent-core';
652
-
653
- const ctx = new ContextManager();
654
- const messages = ctx.buildMessages({
655
- systemPrompt: 'You are a helpful assistant...',
656
- extraSystemPrompt: 'Current time: 2025-01-01',
657
- history: previousMessages,
658
- userMessage: 'Hello',
659
- });
660
- // → [{ role: 'system', content: '...' }, ...history, { role: 'user', content: 'Hello' }]
661
- ```
662
-
663
- #### EnvCollector — 环境采集接口
664
-
665
- ```typescript
666
- interface EnvCollector {
667
- collect(): Promise<EnvInfo>;
668
- format(info: EnvInfo): string;
669
- }
670
-
671
- interface EnvInfo {
672
- os: string;
673
- platform: 'linux' | 'darwin' | 'win32';
674
- cpuCores: number;
675
- memory: string;
676
- disk: string;
677
- shell: string;
678
- hostname?: string;
679
- user?: string;
680
- custom?: Record<string, string>;
681
- }
682
- ```
683
-
684
- `LocalEnvCollector` 提供本地环境采集的默认实现。
685
-
686
- ---
687
-
688
- ### Hooks — 生命周期钩子
689
-
690
- **文件**:`hooks/types.ts`
691
-
692
- 7 个事件点,支持拦截、修改、注入:
693
-
694
- ```typescript
695
- import type { Hook } from '@cicctencent/agent-core';
696
-
697
- const auditHook: Hook = {
698
- name: 'audit-tool-calls',
699
- event: 'before_tool',
700
- handler: async (ctx) => {
701
- console.log(`Tool: ${ctx.tool}, Args:`, ctx.args);
702
- // 阻止危险操作
703
- if (ctx.tool === 'rm_file') return { block: true, reason: 'File deletion not allowed' };
704
- // 修改参数
705
- if (ctx.tool === 'write_file') return { modify: { backup: true } };
706
- },
707
- };
708
-
709
- const logHook: Hook = {
710
- name: 'log-completion',
711
- event: 'on_complete',
712
- handler: async (ctx) => {
713
- console.log(`Completed in ${ctx.totalIterations} iterations, tokens:`, ctx.usage);
714
- },
715
- };
716
-
717
- // 注入到引擎
718
- new AgentEngine({ ..., hooks: [auditHook, logHook] });
719
- ```
720
-
721
- **事件类型**:
722
-
723
- | 事件 | 时机 | 可用上下文 | 有效返回值 |
724
- |---|---|---|---|
725
- | `before_tool` | 工具执行前 | `tool`, `args` | `{ block, reason, modify }` |
726
- | `after_tool` | 工具执行后 | `tool`, `args`, `result`, `isError`, `duration` | `{ inject }` |
727
- | `before_ll_call` | LLM 调用前 | `messages`, `tools` | — |
728
- | `after_ll_call` | LLM 调用后 | `response` | — |
729
- | `on_iteration_start` | 每轮开始 | `iteration` | — |
730
- | `on_error` | 出错时 | `error`, `recoverable` | — |
731
- | `on_complete` | 完成时 | `totalIterations`, `usage` | — |
732
-
733
- ---
734
-
735
- ### Middleware — 中间件管道
736
-
737
- **文件**:`middleware/types.ts`
738
-
739
- 与 Hook 共存的结构化增强层,提供更清晰的 before/after 生命周期:
740
-
741
- ```typescript
742
- import type { Middleware } from '@cicctencent/agent-core';
743
-
744
- const timingMiddleware: Middleware = {
745
- name: 'timing',
746
- before: async (ctx) => { console.log(`Iteration ${ctx.iteration} start`); },
747
- after: async (ctx) => { console.log(`Iteration ${ctx.iteration} end`); },
748
- onToolBefore: async (ctx) => { /* 工具执行前,返回 HookResult */ },
749
- onToolAfter: async (ctx) => { /* 工具执行后,返回 HookResult */ },
750
- };
751
- ```
752
-
753
- **执行顺序**:
754
- ```
755
- Middleware.before → Hook.on_iteration_start → ... → Hook.before_tool → Middleware.onToolBefore → [工具执行] → Hook.after_tool → Middleware.onToolAfter → ... → Middleware.after
756
- ```
757
-
758
- ---
759
-
760
- ### Memory — 渐进式记忆管道
761
-
762
- **文件**:`memory/pipeline.ts`, `memory/extractor.ts`, `memory/scene.ts`, `memory/persona.ts`, `memory/recall.ts`, `memory/checkpoint.ts`
763
-
764
- 四级记忆架构(L0→L1→L2→L3):
765
-
766
- | 层级 | 含义 | 来源 |
767
- |---|---|---|
768
- | L0 | 原始对话 | 直接存储 |
769
- | L1 | 原子事实 | LLM 从对话中提取 |
770
- | L2 | 场景块 | L1 聚合 |
771
- | L3 | 用户画像 | L2 提炼 |
772
-
773
- #### MemoryPipeline — 管道调度器
774
-
775
- ```typescript
776
- import { MemoryPipeline } from '@cicctencent/agent-core/memory/pipeline';
777
-
778
- const pipeline = new MemoryPipeline({
779
- llmProvider: llm,
780
- l2Threshold: 5, // L1 累积 5 条触发 L2
781
- l3Threshold: 3, // L2 累积 3 条触发 L3
782
- });
783
-
784
- // 对话结束后 fire-and-forget
785
- const result = await pipeline.run(messages, sessionId, memoryService);
786
- // → { l1Extracted: 3, l2Triggered: false, l3Triggered: false }
787
- ```
788
-
789
- 上层需实现 `MemoryServiceLike` 接口:
790
-
791
- ```typescript
792
- interface MemoryServiceLike {
793
- getKeys(): string[];
794
- getAllEntries(layer?: MemoryLayer): MemoryEntry[];
795
- save(key, content, category, importance, extras?): MemoryEntry;
796
- }
797
- ```
798
-
799
- #### MemoryExtractor — L1 原子事实提取
800
-
801
- ```typescript
802
- import { MemoryExtractor } from '@cicctencent/agent-core/memory/extractor';
803
-
804
- const extractor = new MemoryExtractor({ llmProvider, maxFactsPerSession: 5 });
805
- const facts = await extractor.extract(messages, sessionId, existingKeys);
806
- // → AtomFact[]: [{ key: 'user_pref_language', content: '用户偏好中文', category: 'user_preference', importance: 4 }]
807
- ```
808
-
809
- #### SceneAggregator — L2 场景聚合
810
-
811
- ```typescript
812
- import { SceneAggregator } from '@cicctencent/agent-core/memory/scene';
813
-
814
- const aggregator = new SceneAggregator({ llmProvider });
815
- const scenes = await aggregator.aggregate(atoms, existingScenes);
816
- // → SceneBlock[]: [{ sceneId, title, description, atomIds }]
817
- ```
818
-
819
- #### PersonaGenerator — L3 用户画像
820
-
821
- ```typescript
822
- import { PersonaGenerator } from '@cicctencent/agent-core/memory/persona';
823
-
824
- const generator = new PersonaGenerator({ llmProvider });
825
- const persona = await generator.generate(scenes, existingPersona);
826
- // → string: 用户画像文本
827
- ```
828
-
829
- #### MemoryRecallEngine — 智能召回
830
-
831
- ```typescript
832
- import { MemoryRecallEngine, formatRecallForPrompt } from '@cicctencent/agent-core/memory/recall';
833
-
834
- const recall = new MemoryRecallEngine(allEntries);
835
- const result = await recall.recall('用户偏好', {
836
- maxResults: 5,
837
- timeoutMs: 3000,
838
- layers: ['L1', 'L2', 'L3'],
839
- });
840
-
841
- // 格式化为 prompt 片段
842
- const promptFragment = formatRecallForPrompt(result);
843
- ```
844
-
845
- 召回策略:关键词匹配 + 重要性加权 + 时效性衰减。
846
-
847
- #### MemoryCheckpoint — 增量检查点
848
-
849
- ```typescript
850
- import { getMemoryCheckpoint, resetMemoryCheckpoint } from '@cicctencent/agent-core/memory/checkpoint';
851
-
852
- const checkpoint = getMemoryCheckpoint();
853
- checkpoint.shouldTriggerL2(l1Count, threshold); // boolean
854
- checkpoint.updateL2(l1Count);
855
- ```
856
-
857
- ---
858
-
859
- ### Workflow — 复杂工作流模板
860
-
861
- **文件**:`agent/workflow.ts`
862
-
863
- 支持结构化输出、辩论模式、多角色工作流:
864
-
865
- ```typescript
866
- import {
867
- getWorkflowTemplate,
868
- formatWorkflowTemplateForPrompt,
869
- parseStructuredAgentOutput,
870
- DEFAULT_COMPLEX_WORKFLOW_TEMPLATE,
871
- } from '@cicctencent/agent-core';
872
-
873
- // 获取工作流模板
874
- const template = getWorkflowTemplate('complex');
875
-
876
- // 格式化为 prompt 指令
877
- const instruction = formatWorkflowTemplateForPrompt(template);
878
-
879
- // 解析结构化输出
880
- const output = parseStructuredAgentOutput(rawText);
881
- // → { findings: [...], risks: [...], recommendation: '...', confidence: 0.85, next_actions: [...] }
882
- ```
883
-
884
- **类型**:
885
-
886
- ```typescript
887
- type WorkflowRole = 'researcher' | 'implementer' | 'reviewer' | 'critic' | 'risk_checker' | 'final_approver';
888
-
889
- interface StructuredAgentOutput {
890
- findings: Array<{ title: string; detail: string; evidence?: string }>;
891
- risks: Array<{ description: string; severity: 'low' | 'medium' | 'high' | 'critical'; mitigation?: string }>;
892
- recommendation: string;
893
- confidence: number;
894
- next_actions: string[];
895
27
  }
896
28
  ```
897
29
 
898
- ---
899
-
900
- ## TypeScript 配置
901
-
902
- ### 使用方 tsconfig
903
-
904
- ```jsonc
905
- {
906
- "compilerOptions": {
907
- "moduleResolution": "bundler",
908
- "allowImportingTsExtensions": true, // 必须:agent-core 内部使用 .ts 扩展名
909
- "noEmit": true, // 或 emitDeclarationOnly
910
- "paths": {
911
- "@cicctencent/agent-core": ["./node_modules/@cicctencent/agent-core/src"],
912
- "@cicctencent/agent-core/*": ["./node_modules/@cicctencent/agent-core/src/*"]
913
- }
914
- }
915
- }
916
- ```
917
-
918
- ### 子路径导入
919
-
920
- 包支持子路径直接导入:
921
-
922
- ```typescript
923
- import { MemoryPipeline } from '@cicctencent/agent-core/memory/pipeline';
924
- import { MemoryRecallEngine } from '@cicctencent/agent-core/memory/recall';
925
- import { createMCPClient } from '@cicctencent/agent-core/mcp/factory';
926
- import { SecurityGuard } from '@cicctencent/agent-core/security/guard';
927
- import type { ToolContext } from '@cicctencent/agent-core/tool/types';
928
- ```
929
-
930
- ---
931
-
932
- ## 依赖说明
933
-
934
- | 依赖 | 用途 |
935
- |---|---|
936
- | `js-tiktoken` | Token 计数(上下文预算管理) |
937
- | `undici` | HTTP 客户端(LLM API 调用、MCP HTTP transport) |
938
- | `socks-proxy-agent` | SOCKS 代理支持(MCP proxy 配置) |
939
-
940
- **运行时要求**:Node.js >= 18
941
-
942
- ---
943
-
944
30
  ## 构建
945
31
 
946
32
  ```bash
947
- # 类型检查
948
- pnpm typecheck
949
-
950
- # 生成类型声明文件(.d.ts)
951
- pnpm build
33
+ pnpm typecheck # 类型检查
34
+ pnpm build # 生成 .d.ts
952
35
  ```
36
+
37
+ ## 运行时要求
38
+
39
+ Node.js >= 18