foliko 1.1.92 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/.claude/settings.local.json +2 -1
  2. package/CLAUDE.md +56 -30
  3. package/REFACTORING_PLAN.md +645 -0
  4. package/docs/architecture.md +131 -0
  5. package/docs/migration.md +57 -0
  6. package/docs/public-api.md +138 -0
  7. package/docs/usage.md +385 -0
  8. package/examples/ambient-example.js +20 -137
  9. package/examples/basic.js +21 -48
  10. package/examples/bootstrap.js +16 -74
  11. package/examples/mcp-example.js +6 -29
  12. package/examples/skill-example.js +6 -19
  13. package/examples/workflow.js +8 -56
  14. package/package.json +8 -4
  15. package/plugins/README.md +49 -0
  16. package/plugins/{ambient-agent → ambient}/EventWatcher.js +1 -1
  17. package/plugins/{ambient-agent → ambient}/ExplorerLoop.js +3 -3
  18. package/plugins/{ambient-agent → ambient}/GoalManager.js +2 -2
  19. package/plugins/ambient/README.md +14 -0
  20. package/plugins/{ambient-agent → ambient}/Reflector.js +1 -1
  21. package/plugins/{ambient-agent → ambient}/StateStore.js +1 -1
  22. package/plugins/{ambient-agent → ambient}/index.js +2 -2
  23. package/plugins/{ai-plugin.js → core/ai/index.js} +14 -30
  24. package/plugins/{audit-plugin.js → core/audit/index.js} +3 -30
  25. package/plugins/{coordinator-plugin.js → core/coordinator/index.js} +3 -35
  26. package/plugins/core/default/bootstrap.js +202 -0
  27. package/plugins/core/default/config.js +220 -0
  28. package/plugins/core/default/index.js +58 -0
  29. package/plugins/core/mcp/index.js +1 -0
  30. package/plugins/{python-plugin-loader.js → core/python-loader/index.js} +7 -187
  31. package/plugins/{rules-plugin.js → core/rules/index.js} +121 -64
  32. package/plugins/{scheduler-plugin.js → core/scheduler/index.js} +12 -114
  33. package/plugins/{session-plugin.js → core/session/index.js} +9 -73
  34. package/{src/capabilities/skill-manager.js → plugins/core/skill-manager/index.js} +64 -18
  35. package/plugins/{storage-plugin.js → core/storage/index.js} +5 -29
  36. package/plugins/{subagent-plugin.js → core/sub-agent/index.js} +10 -171
  37. package/plugins/{think-plugin.js → core/think/index.js} +24 -91
  38. package/{src/capabilities/workflow-engine.js → plugins/core/workflow/index.js} +87 -85
  39. package/plugins/default-plugins.js +6 -720
  40. package/plugins/{data-splitter-plugin.js → executors/data-splitter/index.js} +9 -83
  41. package/plugins/{extension-executor-plugin.js → executors/extension/index.js} +13 -97
  42. package/plugins/{python-executor-plugin.js → executors/python/index.js} +6 -31
  43. package/plugins/{shell-executor-plugin.js → executors/shell/index.js} +2 -5
  44. package/plugins/install/README.md +9 -0
  45. package/plugins/{install-plugin.js → install/index.js} +3 -3
  46. package/plugins/{file-system-plugin.js → io/file-system/index.js} +34 -236
  47. package/plugins/{web-plugin.js → io/web/index.js} +11 -113
  48. package/plugins/memory/README.md +13 -0
  49. package/plugins/{memory-plugin.js → memory/index.js} +4 -18
  50. package/plugins/messaging/email/README.md +19 -0
  51. package/plugins/{email → messaging/email}/index.js +2 -2
  52. package/plugins/{feishu-plugin.js → messaging/feishu/index.js} +3 -3
  53. package/plugins/{qq-plugin.js → messaging/qq/index.js} +5 -16
  54. package/plugins/{telegram-plugin.js → messaging/telegram/index.js} +3 -3
  55. package/plugins/{weixin-plugin.js → messaging/weixin/index.js} +15 -15
  56. package/plugins/{plugin-manager-plugin.js → plugin-manager/index.js} +36 -180
  57. package/plugins/{tools-plugin.js → tools/index.js} +68 -116
  58. package/plugins/trading/README.md +15 -0
  59. package/plugins/{gate-trading.js → trading/index.js} +8 -8
  60. package/{examples → sandbox}/test-concurrent-chat.js +2 -2
  61. package/{examples → sandbox}/test-long-chat.js +2 -2
  62. package/{examples → sandbox}/test-session-chat.js +2 -2
  63. package/{examples → sandbox}/test-web-plugin.js +1 -1
  64. package/{examples → sandbox}/test-weixin-feishu.js +2 -2
  65. package/src/agent/base.js +56 -0
  66. package/src/{core/agent-chat.js → agent/chat.js} +11 -11
  67. package/src/{core/coordinator-manager.js → agent/coordinator.js} +3 -3
  68. package/src/agent/index.js +111 -0
  69. package/src/agent/main.js +337 -0
  70. package/src/agent/prompt.js +78 -0
  71. package/src/agent/sub.js +198 -0
  72. package/src/agent/worker.js +104 -0
  73. package/{cli/bin/foliko.js → src/cli/bin.js} +1 -1
  74. package/{cli/src → src/cli}/commands/chat.js +25 -21
  75. package/{cli/src → src/cli}/index.js +1 -0
  76. package/{cli/src → src/cli}/ui/chat-ui-old.js +40 -178
  77. package/{cli/src → src/cli}/ui/chat-ui.js +3 -3
  78. package/{cli/src → src/cli}/ui/components/footer-bar.js +1 -1
  79. package/src/{core → common}/constants.js +3 -0
  80. package/src/common/errors.js +402 -0
  81. package/src/{utils → common}/logger.js +33 -0
  82. package/src/{utils/chat-queue.js → common/queue.js} +2 -2
  83. package/src/config/plugin-config.js +50 -0
  84. package/src/context/agent.js +32 -0
  85. package/src/context/compaction-prompts.js +170 -0
  86. package/src/context/compaction-utils.js +191 -0
  87. package/src/context/compressor.js +413 -0
  88. package/src/context/index.js +9 -0
  89. package/src/{core/context-manager.js → context/manager.js} +1 -1
  90. package/src/context/request.js +50 -0
  91. package/src/context/session.js +33 -0
  92. package/src/context/storage.js +30 -0
  93. package/src/executors/mcp-client.js +153 -0
  94. package/src/executors/mcp-desc.js +236 -0
  95. package/src/executors/mcp-executor.js +91 -956
  96. package/src/{core → framework}/command-registry.js +1 -1
  97. package/src/framework/framework.js +300 -0
  98. package/src/framework/index.js +18 -0
  99. package/src/framework/lifecycle.js +203 -0
  100. package/src/framework/loader.js +78 -0
  101. package/src/framework/registry.js +86 -0
  102. package/src/{core/ui-extension-context.js → framework/ui-extension.js} +1 -1
  103. package/src/index.js +130 -15
  104. package/src/llm/index.js +26 -0
  105. package/src/llm/provider.js +212 -0
  106. package/src/llm/registry.js +11 -0
  107. package/src/{core/token-counter.js → llm/tokens.js} +4 -37
  108. package/src/{core/plugin-base.js → plugin/base.js} +10 -136
  109. package/src/plugin/index.js +14 -0
  110. package/src/plugin/loader.js +101 -0
  111. package/src/plugin/manager.js +261 -0
  112. package/src/{core → session}/branch-summary-auto.js +2 -2
  113. package/src/{core/chat-session.js → session/chat.js} +2 -2
  114. package/src/session/index.js +7 -0
  115. package/src/{core/session-manager.js → session/session.js} +2 -2
  116. package/src/session/ttl.js +92 -0
  117. package/src/{core/jsonl-storage.js → storage/jsonl.js} +1 -1
  118. package/src/tool/executor.js +85 -0
  119. package/src/tool/index.js +15 -0
  120. package/src/tool/registry.js +143 -0
  121. package/src/{core/tool-router.js → tool/router.js} +17 -124
  122. package/src/tool/schema.js +108 -0
  123. package/src/utils/data-splitter.js +1 -1
  124. package/src/utils/download.js +1 -1
  125. package/src/utils/index.js +6 -6
  126. package/src/utils/message-validator.js +1 -1
  127. package/tests/core/context-storage.test.js +46 -0
  128. package/tests/core/llm.test.js +54 -0
  129. package/tests/core/plugin.test.js +42 -0
  130. package/tests/core/tool.test.js +60 -0
  131. package/tests/setup.js +10 -0
  132. package/tests/smoke.test.js +58 -0
  133. package/vitest.config.js +9 -0
  134. package/cli/src/daemon.js +0 -149
  135. package/docs/CONTEXT_DESIGN.md +0 -1596
  136. package/docs/ai-sdk-optimization.md +0 -655
  137. package/docs/features.md +0 -120
  138. package/docs/qq-bot.md +0 -976
  139. package/docs/quick-reference.md +0 -160
  140. package/docs/user-manual.md +0 -1391
  141. package/images/geometric_shapes.jpg +0 -0
  142. package/images/sunset_mountain_lake.jpg +0 -0
  143. package/skills/poster-guide/SKILL.md +0 -792
  144. package/src/capabilities/index.js +0 -11
  145. package/src/core/agent.js +0 -808
  146. package/src/core/context-compressor.js +0 -959
  147. package/src/core/enhanced-context-compressor.js +0 -210
  148. package/src/core/framework.js +0 -1422
  149. package/src/core/index.js +0 -30
  150. package/src/core/plugin-manager.js +0 -961
  151. package/src/core/provider-registry.js +0 -159
  152. package/src/core/provider.js +0 -156
  153. package/src/core/request-context.js +0 -98
  154. package/src/core/subagent.js +0 -442
  155. package/src/core/system-prompt-builder.js +0 -120
  156. package/src/core/tool-executor.js +0 -202
  157. package/src/core/tool-registry.js +0 -517
  158. package/src/core/worker-agent.js +0 -192
  159. package/src/executors/executor-base.js +0 -58
  160. package/src/utils/error-boundary.js +0 -363
  161. package/src/utils/error.js +0 -374
  162. package/system.md +0 -1645
  163. package/website_v2/README.md +0 -57
  164. package/website_v2/SPEC.md +0 -1
  165. package/website_v2/docs/api.html +0 -128
  166. package/website_v2/docs/configuration.html +0 -147
  167. package/website_v2/docs/plugin-development.html +0 -129
  168. package/website_v2/docs/project-structure.html +0 -89
  169. package/website_v2/docs/skill-development.html +0 -85
  170. package/website_v2/index.html +0 -489
  171. package/website_v2/scripts/main.js +0 -93
  172. package/website_v2/styles/animations.css +0 -8
  173. package/website_v2/styles/docs.css +0 -83
  174. package/website_v2/styles/main.css +0 -417
  175. package/xhs_auth.json +0 -268
  176. package//346/265/267/346/212/245/346/217/222/344/273/266.md +0 -621
  177. /package/plugins/{ambient-agent → ambient}/constants.js +0 -0
  178. /package/plugins/{email → messaging/email}/constants.js +0 -0
  179. /package/plugins/{email → messaging/email}/handlers.js +0 -0
  180. /package/plugins/{email → messaging/email}/monitor.js +0 -0
  181. /package/plugins/{email → messaging/email}/parser.js +0 -0
  182. /package/plugins/{email → messaging/email}/reply.js +0 -0
  183. /package/plugins/{email → messaging/email}/utils.js +0 -0
  184. /package/{examples → sandbox}/test-chat.js +0 -0
  185. /package/{examples → sandbox}/test-mcp.js +0 -0
  186. /package/{examples → sandbox}/test-reload.js +0 -0
  187. /package/{examples → sandbox}/test-telegram.js +0 -0
  188. /package/{examples → sandbox}/test-tg-bot.js +0 -0
  189. /package/{examples → sandbox}/test-tg-simple.js +0 -0
  190. /package/{examples → sandbox}/test-tg.js +0 -0
  191. /package/{examples → sandbox}/test-think.js +0 -0
  192. /package/src/{core/sub-agent-config.js → agent/sub-config.js} +0 -0
  193. /package/{cli/src → src/cli}/commands/daemon.js +0 -0
  194. /package/{cli/src → src/cli}/commands/list.js +0 -0
  195. /package/{cli/src → src/cli}/commands/plugin.js +0 -0
  196. /package/{cli/src → src/cli}/ui/components/agent-mention-provider.js +0 -0
  197. /package/{cli/src → src/cli}/ui/components/chained-autocomplete-provider.js +0 -0
  198. /package/{cli/src → src/cli}/ui/components/message-bubble.js +0 -0
  199. /package/{cli/src → src/cli}/ui/components/status-bar.js +0 -0
  200. /package/{cli/src → src/cli}/utils/ansi.js +0 -0
  201. /package/{cli/src → src/cli}/utils/config.js +0 -0
  202. /package/{cli/src → src/cli}/utils/markdown.js +0 -0
  203. /package/{cli/src → src/cli}/utils/plugin-config.js +0 -0
  204. /package/{cli/src → src/cli}/utils/render-diff.js +0 -0
  205. /package/src/{utils/circuit-breaker.js → common/circuit.js} +0 -0
  206. /package/src/{utils/edit-diff.js → common/diff.js} +0 -0
  207. /package/src/{utils/event-emitter.js → common/events.js} +0 -0
  208. /package/src/{utils → common}/id.js +0 -0
  209. /package/src/{utils → common}/retry.js +0 -0
  210. /package/src/{core/notification-manager.js → notification/manager.js} +0 -0
  211. /package/src/{core/session-entry.js → session/entry.js} +0 -0
  212. /package/src/{core/storage-manager.js → storage/manager.js} +0 -0
@@ -1,1391 +0,0 @@
1
- # Foliko Framework 用户手册
2
-
3
- > 简约的插件化 Agent 框架
4
-
5
- ## 目录
6
-
7
- 1. [项目概述](#1-项目概述)
8
- 2. [快速开始](#2-快速开始)
9
- 3. [核心概念](#3-核心概念)
10
- 4. [内置插件](#4-内置插件)
11
- 5. [插件开发](#5-插件开发)
12
- 6. [技能系统](#6-技能系统)
13
- 7. [子 Agent 系统](#7-子-agent-系统)
14
- 8. [工具路由](#8-工具路由)
15
- 9. [配置说明](#9-配置说明)
16
- 10. [事件系统](#10-事件系统)
17
- 11. [API 参考](#11-api-参考)
18
-
19
- ---
20
-
21
- ## 1. 项目概述
22
-
23
- Foliko 是一个基于插件的 Agent 框架,具有以下特性:
24
-
25
- - **纯 JS 实现** - 无 TypeScript,简单易懂
26
- - **插件化架构** - 通过插件扩展功能
27
- - **工具路由** - 智能选择相关工具,减少 token 消耗
28
- - **多子 Agent 支持** - 支持子 Agent 分工处理
29
- - **热重载** - 支持动态加载/重载插件
30
-
31
- ### 项目结构
32
-
33
- ```
34
- foliko/
35
- ├── src/ # 核心源码
36
- │ ├── core/ # 核心模块
37
- │ │ ├── framework.js # 框架容器
38
- │ │ ├── agent.js # Agent 类
39
- │ │ ├── plugin-base.js # 插件基类
40
- │ │ ├── plugin-manager.js # 插件管理器
41
- │ │ ├── tool-registry.js # 工具注册表
42
- │ │ ├── tool-router.js # 工具路由
43
- │ │ └── agent-chat.js # 聊天处理器
44
- │ ├── capabilities/ # 能力插件
45
- │ │ └── skill-manager.js # 技能管理器
46
- │ ├── executors/ # 执行器
47
- │ │ └── mcp-executor.js # MCP 执行器
48
- │ └── utils/ # 工具模块
49
- ├── plugins/ # 内置插件
50
- ├── skills/ # 技能目录
51
- ├── .foliko/ # Foliko 配置目录
52
- │ ├── plugins/ # 用户插件目录
53
- │ ├── skills/ # 用户技能目录
54
- │ └── mcp_config.json # MCP 配置
55
- ├── examples/ # 示例代码
56
- └── test-chat.js # 聊天测试
57
- ```
58
-
59
- ---
60
-
61
- ## 2. 快速开始
62
-
63
- ### 2.1 安装
64
-
65
- ```bash
66
- npm install
67
- ```
68
-
69
- ### 2.2 创建聊天机器人
70
-
71
- ```javascript
72
- const { Framework } = require('./src');
73
-
74
- async function main() {
75
- // 创建框架
76
- const framework = new Framework({ debug: false });
77
-
78
- // Bootstrap(加载所有配置和插件)
79
- await framework.bootstrap({
80
- agentDir: './.foliko',
81
- aiConfig: {
82
- provider: 'deepseek',
83
- model: 'deepseek-chat',
84
- apiKey: process.env.DEEPSEEK_API_KEY,
85
- },
86
- });
87
-
88
- // 创建 Agent
89
- const agent = framework.createAgent({
90
- name: 'MyAgent',
91
- systemPrompt: '你是一个有帮助的助手。',
92
- });
93
-
94
- // 对话
95
- for await (const chunk of agent.chatStream('你好')) {
96
- if (chunk.type === 'text') {
97
- process.stdout.write(chunk.text);
98
- }
99
- }
100
- }
101
-
102
- main().catch(console.error);
103
- ```
104
-
105
- ### 2.3 运行测试聊天
106
-
107
- ```bash
108
- node test-chat.js
109
- ```
110
-
111
- ---
112
-
113
- ## 3. 核心概念
114
-
115
- ### 3.1 Framework(框架)
116
-
117
- 框架是整个系统的容器,管理插件和工具注册。
118
-
119
- ```javascript
120
- const framework = new Framework({ debug: false });
121
-
122
- // 加载插件
123
- await framework.loadPlugin(myPlugin);
124
-
125
- // 创建 Agent
126
- const agent = framework.createAgent(config);
127
-
128
- // 执行工具
129
- const result = await framework.executeTool('tool_name', { arg: 'value' });
130
- ```
131
-
132
- ### 3.2 Agent(智能体)
133
-
134
- Agent 负责对话和推理,拥有独立的工具集和系统提示。
135
-
136
- ```javascript
137
- const agent = framework.createAgent({
138
- name: 'MyAgent', // Agent 名称
139
- systemPrompt: '你是一个...', // 系统提示
140
- sharedPrompt: '{{WORK_DIR}}', // 共享提示(支持占位符)
141
- metadata: {
142
- // 元数据
143
- projectName: 'MyProject',
144
- },
145
- enableToolRouting: true, // 启用工具路由(默认 true)
146
- });
147
-
148
- // 发送消息(非流式)
149
- const result = await agent.chat('你好');
150
-
151
- // 发送消息(流式)
152
- for await (const chunk of agent.chatStream('你好')) {
153
- if (chunk.type === 'text') process.stdout.write(chunk.text);
154
- }
155
- ```
156
-
157
- ### 3.3 Plugin(插件)
158
-
159
- 插件是功能扩展的基本单元。
160
-
161
- ```javascript
162
- const { Plugin } = require('./src/core/plugin-base');
163
-
164
- class MyPlugin extends Plugin {
165
- constructor() {
166
- super();
167
- this.name = 'my-plugin';
168
- this.version = '1.0.0';
169
- this.description = '我的插件';
170
- this.priority = 10; // 加载优先级(数字越小越先加载)
171
- }
172
-
173
- install(framework) {
174
- this._framework = framework;
175
- // 安装时调用
176
- return this;
177
- }
178
-
179
- start(framework) {
180
- // 注册工具
181
- framework.registerTool({
182
- name: 'my_tool',
183
- description: '我的工具',
184
- inputSchema: {
185
- /* zod schema */
186
- },
187
- execute: async (args) => {
188
- return { result: 'done' };
189
- },
190
- });
191
- return this;
192
- }
193
-
194
- reload(framework) {
195
- // 热重载时调用
196
- return this;
197
- }
198
-
199
- uninstall(framework) {
200
- // 卸载时调用
201
- return this;
202
- }
203
- }
204
-
205
- module.exports = MyPlugin;
206
- ```
207
-
208
- ### 3.4 免引入写法
209
-
210
- 支持更简洁的插件写法:
211
-
212
- ```javascript
213
- // 直接导出函数
214
- module.exports = function (Plugin) {
215
- return class extends Plugin {
216
- constructor() {
217
- super();
218
- this.name = 'my-plugin';
219
- this.description = '我的插件';
220
- }
221
-
222
- start(framework) {
223
- framework.registerTool({
224
- name: 'hello',
225
- execute: async (args) => `Hello, ${args.name}!`,
226
- });
227
- return this;
228
- }
229
- };
230
- };
231
- ```
232
-
233
- ---
234
-
235
- ## 4. 内置插件
236
-
237
- ### 4.1 AI 插件 (ai-plugin)
238
-
239
- 提供 AI 对话能力。
240
-
241
- ```javascript
242
- await framework.loadPlugin(
243
- new AIPlugin({
244
- provider: 'deepseek', // AI 提供商
245
- model: 'deepseek-chat', // 模型名称
246
- apiKey: 'your-api-key', // API Key
247
- baseURL: 'https://api.deepseek.com', // 可选:自定义 API 地址
248
- })
249
- );
250
- ```
251
-
252
- **热重载支持:** 更新 AI 配置后执行 `reload_plugins('ai')`,所有已有 Agent 会自动使用新的 LLM 设置。
253
-
254
- ```javascript
255
- // 1. 更新 LLM 配置
256
- await framework.executeTool('update_plugin_config', {
257
- name: 'ai',
258
- config: {
259
- model: 'gpt-4o',
260
- apiKey: 'new-key',
261
- },
262
- });
263
-
264
- // 2. 热重载 AI 插件
265
- await framework.executeTool('reload_plugins', { pluginName: 'ai' });
266
- ```
267
-
268
- ### 4.2 存储插件 (storage-plugin)
269
-
270
- 键值对存储,支持 JSON 文件持久化。
271
-
272
- ```javascript
273
- // 注册的工具
274
- storage_set(key, value); // 存储值
275
- storage_get(key); // 获取值
276
- storage_delete(key); // 删除值
277
- storage_list(); // 列出所有键
278
- storage_clear(); // 清空存储
279
- ```
280
-
281
- ### 4.3 工具插件 (tools-plugin)
282
-
283
- 内置工具管理功能。
284
-
285
- ```javascript
286
- // 注册的工具
287
- reload_plugins(pluginName?) // 热重载插件(可选指定插件名)
288
- list_plugins() // 列出已加载插件
289
- list_tools() // 列出所有工具
290
- enable_plugin(name) // 启用指定插件
291
- disable_plugin(name) // 禁用指定插件
292
- get_plugin_config(name) // 获取插件当前配置
293
- update_plugin_config(name, config) // 更新插件配置(持久化)
294
- ```
295
-
296
- ### 4.4 文件系统插件 (file-system-plugin)
297
-
298
- 文件系统操作。
299
-
300
- ```javascript
301
- // 注册的工具
302
- read_directory(path) // 读取目录
303
- create_directory(path) // 创建目录
304
- read_file(path) // 读取文件
305
- write_file(path, content) // 写入文件
306
- delete_file(path) // 删除文件
307
- modify_file(path, oldText, newText) // 修改文件
308
- search_file(pattern, path?) // 搜索文件
309
- execute_command(cmd) // 执行命令
310
- ```
311
-
312
- ### 4.5 Shell 执行器 (shell-executor-plugin)
313
-
314
- 执行 Shell 命令。
315
-
316
- ```javascript
317
- // 注册的工具
318
- shell(command); // 执行 Shell 命令
319
- powershell(command); // 执行 PowerShell(仅 Windows)
320
- ```
321
-
322
- ### 4.6 Python 执行器 (python-executor-plugin)
323
-
324
- 执行 Python 代码。
325
-
326
- ```javascript
327
- // 注册的工具
328
- python(code); // 执行 Python 代码
329
- python_script(scriptPath); // 执行 Python 脚本
330
- pip_install(package); // 安装 Python 包
331
- ```
332
-
333
- ### 4.7 MCP 执行器 (mcp-executor)
334
-
335
- 连接 MCP 服务器。
336
-
337
- ```json
338
- // .foliko/mcp_config.json
339
- {
340
- "mcpServers": {
341
- "fetch": {
342
- "command": "uvx",
343
- "args": ["mcp-server-fetch"]
344
- }
345
- }
346
- }
347
- ```
348
-
349
- ```javascript
350
- // 注册的工具
351
- mcp_call(server, tool, args); // 调用 MCP 工具
352
- mcp_list_servers(); // 列出已连接的 MCP 服务器
353
- ```
354
-
355
- ### 4.8 会话插件 (session-plugin)
356
-
357
- 多会话管理。
358
-
359
- ```javascript
360
- // 注册的工具
361
- session_create(sessionId?) // 创建会话
362
- session_get(sessionId) // 获取会话
363
- session_list() // 列出所有会话
364
- session_delete(sessionId) // 删除会话
365
- session_history(sessionId) // 获取会话历史
366
- session_stats() // 获取会话统计
367
- ```
368
-
369
- ### 4.9 审计插件 (audit-plugin)
370
-
371
- 记录操作日志。
372
-
373
- ```javascript
374
- // 注册的工具
375
- audit_query(options); // 查询日志
376
- audit_stats(); // 获取统计
377
- audit_export(format); // 导出日志
378
- ```
379
-
380
- ### 4.10 规则插件 (rules-plugin)
381
-
382
- 规则引擎,控制工具调用权限。
383
-
384
- ```javascript
385
- // 注册的工具
386
- rules_list(); // 列出规则
387
- rules_add(rule); // 添加规则
388
- rules_remove(ruleId); // 移除规则
389
- rules_test(input); // 测试规则匹配
390
- rules_stats(); // 获取统计
391
- ```
392
-
393
- ### 4.11 调度插件 (scheduler-plugin)
394
-
395
- 定时任务。
396
-
397
- ```javascript
398
- // 注册的工具
399
- schedule_cron(expression, task); // 创建 Cron 任务
400
- schedule_once(datetime, task); // 创建一次性任务
401
- schedule_list(); // 列出所有任务
402
- schedule_cancel(taskId); // 取消任务
403
- schedule_now(taskId); // 立即执行任务
404
- ```
405
-
406
- ### 4.12 子 Agent 插件 (subagent-plugin)
407
-
408
- 多 Agent 分工,支持独立工具集。
409
-
410
- **方式1:配置 `this.agents = []` 自动注册**
411
-
412
- ```javascript
413
- const { Plugin } = require('../src/core/plugin-base');
414
- const { tool } = require('ai');
415
- const { z } = require('zod');
416
-
417
- class MyPlugin extends Plugin {
418
- name = 'my-plugin';
419
-
420
- // 配置式注册子Agent,插件启动时自动创建
421
- agents = [
422
- {
423
- name: 'code-agent',
424
- role: '代码专家',
425
- description: '处理代码开发任务',
426
- tools: {
427
- compile: tool({
428
- description: '编译代码',
429
- parameters: z.object({
430
- language: z.string(),
431
- code: z.string(),
432
- }),
433
- execute: async (args) => ({ success: true }),
434
- }),
435
- },
436
- parentTools: ['read_file', 'write_file'], // 从父Agent继承的工具
437
- },
438
- ];
439
- }
440
- ```
441
-
442
- **方式2:手动调用 `this.registerSubAgent()`**
443
-
444
- ```javascript
445
- const { Plugin } = require('../src/core/plugin-base');
446
- const { tool } = require('ai');
447
- const { z } = require('zod');
448
-
449
- class MyPlugin extends Plugin {
450
- start(framework) {
451
- // 手动注册子Agent
452
- this.registerSubAgent({
453
- name: 'code-agent',
454
- role: '代码专家',
455
- tools: {
456
- compile: tool({
457
- description: '编译代码',
458
- parameters: z.object({ language: z.string(), code: z.string() }),
459
- execute: async (args) => ({ success: true }),
460
- }),
461
- },
462
- parentTools: ['read_file'],
463
- });
464
- }
465
- }
466
- ```
467
-
468
- **子Agent配置说明:**
469
-
470
- | 字段 | 类型 | 说明 |
471
- | ------------- | ------ | ----------------------------------------------- |
472
- | `name` | string | 子Agent名称(唯一标识) |
473
- | `role` | string | 角色描述 |
474
- | `description` | string | 详细描述(供主Agent智能选择) |
475
- | `tools` | object | 自定义工具 `{ name: toolDef }`,只属于此子Agent |
476
- | `parentTools` | array | 从父Agent继承的工具名称列表 |
477
-
478
- ### 4.13 技能管理器 (skill-manager)
479
-
480
- 技能加载和管理。
481
-
482
- ```javascript
483
- // 注册的工具
484
- loadSkill(skill); // 加载指定技能
485
-
486
- // 技能存放在 skills/ 或 .foliko/skills/ 目录
487
- ```
488
-
489
- ### 4.14 Email 插件 (email-plugin)
490
-
491
- 邮件收发插件,支持 SMTP 发送和 IMAP 读取。
492
-
493
- ```javascript
494
- // 配置
495
- await framework.loadPlugin(
496
- new EmailPlugin({
497
- smtp_host: 'smtp.gmail.com',
498
- smtp_port: 587,
499
- smtp_secure: false,
500
- smtp_user: 'your-email@gmail.com',
501
- smtp_pass: 'your-app-password',
502
- imap_host: 'imap.gmail.com',
503
- imap_port: 993,
504
- imap_user: 'your-email@gmail.com',
505
- imap_pass: 'your-app-password',
506
- from_email: 'your-email@gmail.com',
507
- })
508
- );
509
-
510
- // 或通过工具配置
511
- email_configure({
512
- smtp_host: 'smtp.gmail.com',
513
- smtp_user: 'your-email@gmail.com',
514
- smtp_pass: 'your-app-password',
515
- });
516
- ```
517
-
518
- **注册的工具:**
519
-
520
- | 工具 | 说明 |
521
- | -------------------- | -------------------- |
522
- | `email_send` | 发送电子邮件 |
523
- | `email_read` | 读取电子邮件(IMAP) |
524
- | `email_unread_count` | 获取未读邮件数量 |
525
- | `email_mark_read` | 标记邮件为已读 |
526
- | `email_configure` | 配置邮箱连接参数 |
527
-
528
- ```javascript
529
- // 发送邮件
530
- email_send({
531
- to: 'recipient@example.com',
532
- subject: '主题',
533
- body: '正文内容',
534
- cc: 'cc@example.com', // 可选
535
- isHtml: false,
536
- });
537
-
538
- // 读取邮件
539
- email_read({
540
- box: 'INBOX',
541
- limit: 10,
542
- unreadOnly: false,
543
- });
544
-
545
- // 获取未读数量
546
- email_unread_count({ box: 'INBOX' });
547
-
548
- // 标记为已读
549
- email_mark_read({ messageId: '12345' });
550
- ```
551
-
552
- ### 4.15 Telegram 插件 (telegram-plugin)
553
-
554
- Telegram 对话插件,绑定主 Agent 进行持续对话。
555
-
556
- ```javascript
557
- // 配置
558
- await framework.loadPlugin(
559
- new TelegramPlugin({
560
- botToken: 'YOUR_BOT_TOKEN', // 必需
561
- allowedChats: ['123456789'], // 可选:允许的聊天ID
562
- groupMode: false, // 可选:是否启用群组模式
563
- prefix: '/', // 可选:命令前缀
564
- systemPrompt: '你是一个有帮助的AI助手。',
565
- })
566
- );
567
- ```
568
-
569
- **功能特性:**
570
-
571
- - 支持私聊和群组模式
572
- - MarkdownV2 格式支持(自动转义特殊字符)
573
- - 持续对话(基于 sessionId)
574
- - 支持图片和文档接收
575
- - 媒体文件自动保存到 `.foliko/data/`
576
-
577
- **命令:**
578
-
579
- | 命令 | 说明 |
580
- | ---------- | ------------ |
581
- | `/start` | 显示帮助信息 |
582
- | `/clear` | 清除对话历史 |
583
- | `/history` | 查看对话状态 |
584
-
585
- ### 4.16 插件管理扩展
586
-
587
- #### 插件启用/禁用
588
-
589
- ```javascript
590
- // 启用插件
591
- await framework.enablePlugin('telegram');
592
-
593
- // 禁用插件
594
- await framework.disablePlugin('telegram');
595
- ```
596
-
597
- #### 插件配置更新
598
-
599
- ```javascript
600
- // 更新插件配置(会自动保存到 .foliko/data/plugins-state.json)
601
- await framework.executeTool('update_plugin_config', {
602
- name: 'telegram',
603
- config: {
604
- allowedChats: ['123456789', '987654321'],
605
- groupMode: true,
606
- },
607
- });
608
-
609
- // 获取插件当前配置
610
- await framework.executeTool('get_plugin_config', {
611
- name: 'telegram',
612
- });
613
- ```
614
-
615
- **配置持久化:**
616
-
617
- - 插件的 `enabled` 状态和 `config` 会自动保存到 `.foliko/data/plugins-state.json`
618
- - 重启后自动恢复配置
619
-
620
- ---
621
-
622
- ## 5. 插件开发
623
-
624
- ### 5.1 插件存放位置
625
-
626
- | 位置 | 说明 | 加载方式 |
627
- | ----------------- | -------- | -------------------- |
628
- | `plugins/` | 内置插件 | 框架初始化时加载 |
629
- | `.foliko/plugins/` | 用户插件 | Bootstrap 时自动加载 |
630
-
631
- ### 5.2 开发步骤
632
-
633
- 1. 创建插件文件 `.foliko/plugins/my-plugin.js`
634
- 2. 实现插件类
635
- 3. 使用 `reload_plugins` 重载插件
636
-
637
- ### 5.3 完整示例
638
-
639
- ```javascript
640
- // .foliko/plugins/system-info.js
641
- const { Plugin } = require('../../src/core/plugin-base');
642
- const os = require('os');
643
- const { z } = require('zod');
644
-
645
- class SystemInfoPlugin extends Plugin {
646
- constructor() {
647
- super();
648
- this.name = 'system-info';
649
- this.version = '1.0.0';
650
- this.description = '系统信息查看插件';
651
- this.priority = 5;
652
- }
653
-
654
- start(framework) {
655
- framework.registerTool({
656
- name: 'get_system_info',
657
- description: '获取系统基本信息',
658
- inputSchema: z.object({}),
659
- execute: async () => {
660
- return {
661
- platform: os.platform(),
662
- hostname: os.hostname(),
663
- arch: os.arch(),
664
- homedir: os.homedir(),
665
- cwd: process.cwd(),
666
- };
667
- },
668
- });
669
-
670
- framework.registerTool({
671
- name: 'get_memory_usage',
672
- description: '获取内存使用情况',
673
- inputSchema: z.object({}),
674
- execute: async () => {
675
- const total = os.totalmem();
676
- const free = os.freemem();
677
- const used = total - free;
678
- return {
679
- total: `${(total / 1024 / 1024 / 1024).toFixed(2)} GB`,
680
- used: `${(used / 1024 / 1024 / 1024).toFixed(2)} GB`,
681
- free: `${(free / 1024 / 1024 / 1024).toFixed(2)} GB`,
682
- percent: `${((used / total) * 100).toFixed(1)}%`,
683
- };
684
- },
685
- });
686
-
687
- return this;
688
- }
689
- }
690
-
691
- module.exports = SystemInfoPlugin;
692
- ```
693
-
694
- ### 5.4 免引入写法
695
-
696
- ```javascript
697
- // .foliko/plugins/my-plugin.js
698
- const { z } = require('zod');
699
-
700
- module.exports = function (Plugin) {
701
- return class extends Plugin {
702
- constructor() {
703
- super();
704
- this.name = 'my-plugin';
705
- this.description = '我的插件';
706
- }
707
-
708
- start(framework) {
709
- framework.registerTool({
710
- name: 'hello',
711
- description: '打招呼',
712
- inputSchema: z.object({
713
- name: z.string().describe('姓名'),
714
- }),
715
- execute: async (args) => {
716
- return `Hello, ${args.name}!`;
717
- },
718
- });
719
- return this;
720
- }
721
- };
722
- };
723
- ```
724
-
725
- ---
726
-
727
- ## 6. 技能系统
728
-
729
- ### 6.1 技能目录
730
-
731
- | 位置 | 说明 |
732
- | ------------------- | -------------------- |
733
- | `skills/` | 项目级技能 |
734
- | `.foliko/skills/` | Agent 专属技能 |
735
- | `~/.folikos/skills/` | 全局技能(未来支持) |
736
-
737
- ### 6.2 技能格式
738
-
739
- 技能是 Markdown 文件,包含 frontmatter 元数据。
740
-
741
- ```markdown
742
- ---
743
- name: my-skill
744
- description: 我的技能描述
745
- license: MIT
746
- compatibility: foliko >= 1.0.0
747
- metadata:
748
- author: Your Name
749
- version: 1.0.0
750
- allowed-tools:
751
- - read_file
752
- - write_file
753
- ---
754
-
755
- # 我的技能
756
-
757
- 这里是技能的详细说明和使用指南。
758
- ```
759
-
760
- ### 6.3 使用技能
761
-
762
- Agent 可以通过 `loadSkill` 工具加载技能:
763
-
764
- ```
765
- 用户: 帮我创建一个系统信息插件
766
- Agent: [调用 loadSkill 技能 foliko-dev]
767
- Agent: [获取插件开发指南后,按照指南创建插件]
768
- ```
769
-
770
- ### 6.4 内置技能
771
-
772
- - **foliko-dev** - Foliko 插件开发指南
773
- - **api-patterns** - API 设计模式
774
- - **app-builder** - 应用程序构建
775
- - **architecture** - 架构设计
776
- - ...(共 39+ 技能)
777
-
778
- ---
779
-
780
- ## 7. 子 Agent 系统
781
-
782
- ### 7.1 概念
783
-
784
- 子 Agent 是主 Agent 的专家分身,专门处理特定领域任务。
785
-
786
- ```
787
- 主 Agent
788
- ├── 代码专家 (code-agent)
789
- │ ├── read_file
790
- │ ├── write_file
791
- │ └── execute_command
792
- ├── 数据专家 (data-agent)
793
- │ ├── python
794
- │ └── execute_command
795
- └── ...
796
- ```
797
-
798
- ### 7.2 使用方式
799
-
800
- ```javascript
801
- // 创建子 Agent
802
- await framework.loadPlugin(
803
- new SubAgentPlugin({
804
- name: 'code-agent',
805
- role: '代码专家',
806
- description: '负责代码开发、调试和重构',
807
- tools: ['read_file', 'write_file', 'execute_command'],
808
- })
809
- );
810
-
811
- // 主 Agent 自动获得 code-agent 工具
812
- // 使用: "帮我写一个排序算法"
813
- // Agent 自动调用 code-agent 工具
814
- ```
815
-
816
- ### 7.3 系统提示中的子 Agent
817
-
818
- ```markdown
819
- 【子 Agent 分配规则 - 必须遵守】
820
-
821
- 1. 每个子Agent有固定的专业领域,必须委托给对应的专家:
822
-
823
- - code-agent: 代码专家
824
- - data-agent: 数据专家
825
-
826
- 2. 你需要对任务进行拆分,传递给对应的子Agent执行。
827
-
828
- 【可委托的子 Agent】
829
-
830
- - code-agent: 代码专家
831
- - data-agent: 数据专家
832
-
833
- 使用相应子Agent名称的工具将任务委托给相应子代理。
834
- ```
835
-
836
- ---
837
-
838
- ## 8. 工具路由
839
-
840
- ### 8.1 问题
841
-
842
- 44 个工具全部传给 LLM 会:
843
-
844
- - 消耗大量 token
845
- - 降低推理速度
846
- - 增加成本
847
-
848
- ### 8.2 解决方案
849
-
850
- 智能工具路由:根据用户输入选择相关工具。
851
-
852
- ```javascript
853
- const agent = framework.createAgent({
854
- name: 'MyAgent',
855
- enableToolRouting: true, // 默认启用
856
- });
857
- ```
858
-
859
- ### 8.3 意图分类
860
-
861
- | 意图 | 关键词 | 工具 |
862
- | ----------------- | ---------------- | ---------------------------- |
863
- | file_operation | 文件、读取、写入 | read_file, write_file, ... |
864
- | code_development | 代码、开发、插件 | loadSkill, read_file, ... |
865
- | system_info | 系统、信息、内存 | get_system_info, ... |
866
- | plugin_management | 插件、重载 | reload_plugins, list_plugins |
867
-
868
- ### 8.4 工作原理
869
-
870
- ```
871
- 用户: "查看系统信息"
872
-
873
- 意图分析: system_info (匹配度 100%)
874
-
875
- 工具选择: get_system_info, get_memory_usage, get_cpu_info, ...
876
-
877
- 传给 LLM: 仅 7 个工具(而非全部 44 个)
878
- ```
879
-
880
- ---
881
-
882
- ## 9. 配置说明
883
-
884
- ### 9.1 .foliko 目录结构
885
-
886
- ```
887
- .foliko/
888
- ├── config # 配置文件(key=value 格式)
889
- ├── ai.json # AI 配置
890
- ├── plugins.json # 插件配置
891
- ├── mcp_config.json # MCP 服务器配置
892
- ├── skills/ # Agent 专属技能
893
- └── plugins/ # 用户插件
894
- ```
895
-
896
- ### 9.2 AI 配置
897
-
898
- ```json
899
- // .foliko/ai.json
900
- {
901
- "provider": "deepseek",
902
- "model": "deepseek-chat",
903
- "apiKey": "your-api-key",
904
- "baseURL": "https://api.deepseek.com"
905
- }
906
- ```
907
-
908
- ### 9.3 MCP 配置
909
-
910
- ```json
911
- // .foliko/mcp_config.json
912
- {
913
- "mcpServers": {
914
- "fetch": {
915
- "command": "uvx",
916
- "args": ["mcp-server-fetch"]
917
- }
918
- }
919
- }
920
- ```
921
-
922
- ---
923
-
924
- ## 10. 事件系统
925
-
926
- Foliko 基于 EventEmitter,提供完整的事件系统。
927
-
928
- ### 10.1 事件基础
929
-
930
- ```javascript
931
- // 监听事件
932
- agent.on('eventName', (data) => {
933
- console.log('事件触发:', data);
934
- });
935
-
936
- // 监听一次
937
- agent.once('eventName', (data) => {
938
- console.log('只触发一次');
939
- });
940
-
941
- // 移除监听
942
- agent.off('eventName', handler);
943
-
944
- // 触发事件
945
- agent.emit('eventName', { key: 'value' });
946
- ```
947
-
948
- ### 10.2 Framework 事件
949
-
950
- | 事件名 | 参数 | 说明 |
951
- | --------------------- | ----------- | ------------ |
952
- | `framework:ready` | `framework` | 框架就绪 |
953
- | `framework:destroyed` | - | 框架销毁 |
954
- | `plugin:registered` | `plugin` | 插件注册 |
955
- | `plugin:loaded` | `plugin` | 插件加载完成 |
956
- | `plugin:unloaded` | `plugin` | 插件卸载 |
957
- | `plugin:reloaded` | `plugin` | 插件重载 |
958
- | `plugin:enabled` | `plugin` | 插件启用 |
959
- | `plugin:disabled` | `plugin` | 插件禁用 |
960
- | `tool:registered` | `tool` | 工具注册 |
961
- | `agent:created` | `agent` | Agent 创建 |
962
-
963
- ```javascript
964
- framework.on('framework:ready', (fw) => {
965
- console.log('框架就绪');
966
- });
967
-
968
- framework.on('plugin:loaded', (plugin) => {
969
- console.log('插件已加载:', plugin.name);
970
- });
971
-
972
- framework.on('tool:registered', (tool) => {
973
- console.log('工具已注册:', tool.name);
974
- });
975
- ```
976
-
977
- ### 10.3 Agent 事件
978
-
979
- | 事件名 | 参数 | 说明 |
980
- | ------------- | ------------------------ | ------------------------------- |
981
- | `status` | `{ status }` | 状态变化:`idle`/`busy`/`error` |
982
- | `message` | `msg` | 非流式消息响应 |
983
- | `chunk` | `chunk` | 流式响应片段 |
984
- | `tool-call` | `{ name, args }` | 工具调用 |
985
- | `tool-result` | `{ name, args, result }` | 工具结果 |
986
- | `error` | `{ error }` | 错误发生 |
987
- | `destroyed` | - | Agent 销毁 |
988
-
989
- ```javascript
990
- // 状态监听
991
- agent.on('status', ({ status }) => {
992
- console.log('Agent 状态:', status);
993
- });
994
-
995
- // 流式输出
996
- agent.on('chunk', (chunk) => {
997
- if (chunk.type === 'text') {
998
- process.stdout.write(chunk.text);
999
- }
1000
- });
1001
-
1002
- // 工具调用
1003
- agent.on('tool-call', ({ name, args }) => {
1004
- console.log('调用工具:', name, args);
1005
- });
1006
-
1007
- agent.on('tool-result', ({ name, result }) => {
1008
- console.log('工具结果:', name, result);
1009
- });
1010
-
1011
- // 错误处理
1012
- agent.on('error', ({ error }) => {
1013
- console.error('Agent 错误:', error);
1014
- });
1015
- ```
1016
-
1017
- ### 10.4 子 Agent 事件
1018
-
1019
- | 事件名 | 参数 | 说明 |
1020
- | --------------------- | ------------------------------------------------- | ----------------- |
1021
- | `subagent:chat:start` | `{ parentAgent, subAgent, subAgentName, task }` | 子 Agent 开始处理 |
1022
- | `subagent:chat:end` | `{ parentAgent, subAgent, subAgentName, result }` | 子 Agent 完成 |
1023
- | `subagent:chunk` | `{ parentAgent, subAgent, subAgentName, chunk }` | 子 Agent 流式输出 |
1024
- | `subagent:error` | `{ parentAgent, subAgent, subAgentName, error }` | 子 Agent 错误 |
1025
-
1026
- ```javascript
1027
- // 监听所有子 Agent 事件
1028
- agent.on('subagent:chat:start', ({ subAgentName, task }) => {
1029
- console.log(`子 Agent ${subAgentName} 开始处理:`, task);
1030
- });
1031
-
1032
- agent.on('subagent:chat:end', ({ subAgentName, result }) => {
1033
- console.log(`子 Agent ${subAgentName} 完成:`, result);
1034
- });
1035
-
1036
- agent.on('subagent:chunk', ({ subAgentName, chunk }) => {
1037
- console.log(`子 Agent ${subAgentName} 输出:`, chunk);
1038
- });
1039
-
1040
- agent.on('subagent:error', ({ subAgentName, error }) => {
1041
- console.error(`子 Agent ${subAgentName} 错误:`, error);
1042
- });
1043
- ```
1044
-
1045
- ### 10.5 工具执行事件
1046
-
1047
- | 事件名 | 参数 | 说明 |
1048
- | ------------- | ------------------------ | ------------ |
1049
- | `tool:call` | `{ name, args }` | 工具被调用 |
1050
- | `tool:result` | `{ name, args, result }` | 工具执行结果 |
1051
- | `tool:error` | `{ name, args, error }` | 工具执行错误 |
1052
-
1053
- ```javascript
1054
- // 通过 toolRegistry 监听
1055
- framework.toolRegistry.on('tool:call', ({ name, args }) => {
1056
- console.log('工具调用:', name, args);
1057
- });
1058
-
1059
- framework.toolRegistry.on('tool:result', ({ name, result }) => {
1060
- console.log('工具结果:', name, result);
1061
- });
1062
-
1063
- framework.toolRegistry.on('tool:error', ({ name, error }) => {
1064
- console.error('工具错误:', name, error);
1065
- });
1066
- ```
1067
-
1068
- ### 10.6 完整示例
1069
-
1070
- ```javascript
1071
- const { Framework } = require('./src');
1072
-
1073
- async function main() {
1074
- const framework = new Framework({ debug: false });
1075
- await framework.bootstrap({ agentDir: './.foliko' });
1076
-
1077
- const agent = framework.createAgent({
1078
- name: 'MyAgent',
1079
- systemPrompt: '你是一个有帮助的助手。',
1080
- });
1081
-
1082
- // 监听所有事件
1083
- framework.on('*', (event, ...args) => {
1084
- console.log(`[Framework Event] ${event}`);
1085
- });
1086
-
1087
- agent.on('status', ({ status }) => {
1088
- console.log(`[Agent Status] ${status}`);
1089
- });
1090
-
1091
- agent.on('tool-call', ({ name, args }) => {
1092
- console.log(`[Tool Call] ${name}:`, args);
1093
- });
1094
-
1095
- agent.on('subagent:*', (event, data) => {
1096
- console.log(`[SubAgent Event] ${event}:`, data);
1097
- });
1098
-
1099
- // 对话
1100
- for await (const chunk of agent.chatStream('你好')) {
1101
- if (chunk.type === 'text') {
1102
- process.stdout.write(chunk.text);
1103
- }
1104
- }
1105
- }
1106
-
1107
- main();
1108
- ```
1109
-
1110
- ### 10.7 Chat Stream Chunk 类型
1111
-
1112
- `chatStream` 返回的 chunk 对象有以下类型:
1113
-
1114
- | type | 字段 | 说明 |
1115
- | ------------- | -------------------- | -------- |
1116
- | `text` | `text` | 文本片段 |
1117
- | `tool-call` | `toolName`, `args` | 工具调用 |
1118
- | `tool-result` | `toolName`, `result` | 工具结果 |
1119
- | `error` | `error` | 错误信息 |
1120
-
1121
- ```javascript
1122
- for await (const chunk of agent.chatStream('帮我读取文件')) {
1123
- switch (chunk.type) {
1124
- case 'text':
1125
- process.stdout.write(chunk.text);
1126
- break;
1127
- case 'tool-call':
1128
- console.log('调用:', chunk.toolName, chunk.args);
1129
- break;
1130
- case 'tool-result':
1131
- console.log('结果:', chunk.toolName, chunk.result);
1132
- break;
1133
- case 'error':
1134
- console.error('错误:', chunk.error);
1135
- break;
1136
- }
1137
- }
1138
- ```
1139
-
1140
- ---
1141
-
1142
- ## 11. API 参考
1143
-
1144
- ### 11.1 Framework
1145
-
1146
- ```javascript
1147
- // 创建框架
1148
- const framework = new Framework({ debug: false });
1149
-
1150
- // Bootstrap(加载所有配置和插件)
1151
- await framework.bootstrap({
1152
- agentDir: './.foliko',
1153
- aiConfig: { provider, model, apiKey },
1154
- });
1155
-
1156
- // 创建 Agent
1157
- const agent = framework.createAgent({
1158
- name,
1159
- systemPrompt,
1160
- sharedPrompt,
1161
- metadata,
1162
- enableToolRouting,
1163
- });
1164
-
1165
- // 注册/加载插件
1166
- await framework.loadPlugin(plugin);
1167
- await framework.reloadPlugin(name);
1168
- await framework.reloadAllPlugins();
1169
-
1170
- // 启用/禁用插件
1171
- await framework.enablePlugin(name);
1172
- await framework.disablePlugin(name);
1173
-
1174
- // 更新插件配置
1175
- framework.updatePluginConfig(name, config);
1176
-
1177
- // 执行工具
1178
- const result = await framework.executeTool(name, args);
1179
-
1180
- // 获取插件/工具
1181
- const plugin = framework.pluginManager.get(name);
1182
- const tools = framework.getTools();
1183
-
1184
- // 销毁
1185
- await framework.destroy();
1186
- ```
1187
-
1188
- ### 11.2 Agent
1189
-
1190
- ```javascript
1191
- // 创建(在 framework.createAgent() 后)
1192
- const agent = framework.createAgent(config);
1193
-
1194
- // 发送消息
1195
- const result = await agent.chat(message);
1196
- for await (const chunk of agent.chatStream(message)) {
1197
- // chunk.type: 'text' | 'tool-call' | 'tool-result' | 'error'
1198
- }
1199
-
1200
- // 注册工具
1201
- agent.registerTool(toolDef);
1202
-
1203
- // 子 Agent
1204
- agent.registerSubAgent(name, agent, role, goal);
1205
- agent.getSubAgents();
1206
-
1207
- // 元数据
1208
- agent.setMetadata(key, value);
1209
- agent.getMetadata(key);
1210
-
1211
- // 状态
1212
- agent.getStatus(); // 'idle' | 'busy' | 'error'
1213
- agent.resetStatus(); // 重置状态
1214
-
1215
- // 清空历史
1216
- agent.clearHistory();
1217
-
1218
- // 销毁
1219
- agent.destroy();
1220
- ```
1221
-
1222
- ### 11.3 Plugin
1223
-
1224
- ```javascript
1225
- class MyPlugin extends Plugin {
1226
- constructor() {
1227
- super();
1228
- this.name = 'my-plugin';
1229
- this.version = '1.0.0';
1230
- this.description = '我的插件';
1231
- this.priority = 10;
1232
- }
1233
-
1234
- install(framework) {
1235
- /* 安装 */ return this;
1236
- }
1237
- start(framework) {
1238
- /* 启动 */ return this;
1239
- }
1240
- reload(framework) {
1241
- /* 重载 */ return this;
1242
- }
1243
- uninstall(framework) {
1244
- /* 卸载 */ return this;
1245
- }
1246
- }
1247
- ```
1248
-
1249
- ### 11.4 工具定义
1250
-
1251
- ```javascript
1252
- {
1253
- name: 'tool_name',
1254
- description: '工具描述',
1255
- inputSchema: z.object({
1256
- arg1: z.string().describe('参数1'),
1257
- arg2: z.number().optional()
1258
- }),
1259
- execute: async (args, framework) => {
1260
- // args: { arg1: '...', arg2: 123 }
1261
- // framework: Framework 实例
1262
- return { success: true, result: '...' }
1263
- }
1264
- }
1265
- ```
1266
-
1267
- ---
1268
-
1269
- ## 示例代码
1270
-
1271
- ### 基础对话
1272
-
1273
- ```javascript
1274
- const { Framework } = require('./src');
1275
-
1276
- async function main() {
1277
- const framework = new Framework();
1278
- await framework.bootstrap({ agentDir: './.foliko' });
1279
-
1280
- const agent = framework.createAgent({
1281
- systemPrompt: '你是一个有帮助的助手。',
1282
- });
1283
-
1284
- const result = await agent.chat('你好');
1285
- console.log(result.message);
1286
- }
1287
-
1288
- main();
1289
- ```
1290
-
1291
- ### 带工具的对话
1292
-
1293
- ```javascript
1294
- const { Framework } = require('./src');
1295
-
1296
- async function main() {
1297
- const framework = new Framework();
1298
- await framework.bootstrap({ agentDir: './.foliko' });
1299
-
1300
- const agent = framework.createAgent({
1301
- systemPrompt: '你是一个有帮助的助手,擅长文件操作。',
1302
- });
1303
-
1304
- for await (const chunk of agent.chatStream('帮我读取 package.json')) {
1305
- if (chunk.type === 'text') process.stdout.write(chunk.text);
1306
- if (chunk.type === 'tool-call') console.log('调用工具:', chunk.toolName);
1307
- if (chunk.type === 'tool-result') console.log('结果:', chunk.result);
1308
- }
1309
- }
1310
-
1311
- main();
1312
- ```
1313
-
1314
- ### 子 Agent 分工
1315
-
1316
- ```javascript
1317
- const { Framework } = require('./src');
1318
- const { SubAgentPlugin } = require('./plugins/subagent-plugin');
1319
-
1320
- async function main() {
1321
- const framework = new Framework();
1322
- await framework.bootstrap({ agentDir: './.foliko' });
1323
-
1324
- // 创建主 Agent
1325
- const mainAgent = framework.createAgent({
1326
- systemPrompt: '你是主 Agent,负责协调子 Agent 工作。',
1327
- });
1328
-
1329
- // 添加子 Agent
1330
- await framework.loadPlugin(
1331
- new SubAgentPlugin({
1332
- name: 'code-agent',
1333
- role: '代码专家',
1334
- description: '负责代码开发',
1335
- tools: {
1336
- compile: {
1337
- description: '编译代码',
1338
- inputSchema: z.object({ language: z.string(), code: z.string() }),
1339
- execute: async (args) => ({ success: true }),
1340
- },
1341
- },
1342
- parentTools: ['read_file', 'write_file'],
1343
- })
1344
- );
1345
-
1346
- // 对话
1347
- const result = await mainAgent.chat('帮我创建一个 Hello World 程序');
1348
- console.log(result.message);
1349
- }
1350
-
1351
- main();
1352
- ```
1353
-
1354
- ---
1355
-
1356
- ## 常见问题
1357
-
1358
- ### Q: 如何调试插件?
1359
-
1360
- ```javascript
1361
- const framework = new Framework({ debug: true });
1362
- ```
1363
-
1364
- ### Q: MCP 连接失败怎么办?
1365
-
1366
- 1. 检查 `.foliko/mcp_config.json` 配置
1367
- 2. 确认 MCP 服务器命令已安装
1368
- 3. 查看日志中的错误信息
1369
-
1370
- ### Q: 如何查看所有可用工具?
1371
-
1372
- 调用 `list_tools` 工具,或在系统提示中查看【可用工具】部分。
1373
-
1374
- ---
1375
-
1376
- ## 更新日志
1377
-
1378
- ### v1.0.0
1379
-
1380
- - 插件化架构
1381
- - 工具注册系统
1382
- - 技能管理
1383
- - 子 Agent 支持
1384
- - 工具路由
1385
- - 热重载
1386
-
1387
- ---
1388
-
1389
- ## License
1390
-
1391
- MIT