foliko 1.0.80 → 1.0.81

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 (235) hide show
  1. package/.agent/agents/code-assistant.json +14 -0
  2. package/.agent/agents/email-assistant.json +14 -0
  3. package/.agent/agents/file-assistant.json +15 -0
  4. package/.agent/agents/system-assistant.json +15 -0
  5. package/.agent/agents/web-assistant.json +12 -0
  6. package/.agent/data/ambient/goals.json +50 -0
  7. package/.agent/data/ambient/memories.json +7 -0
  8. package/.agent/data/default.json +15 -31894
  9. package/.agent/data/plugins-state.json +146 -181
  10. package/.agent/data/scheduler/tasks.json +1 -0
  11. package/.agent/mcp_config.json +1 -0
  12. package/.agent/package.json +8 -0
  13. package/.agent/plugins/__pycache__/test_plugin.cpython-312.pyc +0 -0
  14. package/.agent/plugins/system-info/index.js +387 -0
  15. package/.agent/plugins/system-info/package.json +4 -0
  16. package/.agent/plugins/system-info/test.js +40 -0
  17. package/.agent/plugins/test_plugin.py +304 -0
  18. package/.agent/plugins.json +14 -5
  19. package/.agent/python-scripts/test_sample.py +24 -0
  20. package/.agent/skills/sysinfo/SKILL.md +38 -0
  21. package/.agent/skills/sysinfo/system-info.sh +130 -0
  22. package/.agent/skills/workflow/SKILL.md +324 -0
  23. package/.agent/workflows/email-digest.json +50 -0
  24. package/.agent/workflows/file-backup.json +21 -0
  25. package/.agent/workflows/get-ip-notify.json +32 -0
  26. package/.agent/workflows/news-aggregator.json +93 -0
  27. package/.agent/workflows/news-dashboard-v2.json +94 -0
  28. package/.agent/workflows/notification-batch.json +32 -0
  29. package/.claude/settings.local.json +171 -171
  30. package/.env.example +56 -56
  31. package/cli/bin/foliko.js +12 -12
  32. package/cli/src/commands/chat.js +143 -143
  33. package/cli/src/commands/list.js +93 -93
  34. package/cli/src/index.js +75 -75
  35. package/cli/src/ui/chat-ui.js +201 -201
  36. package/cli/src/utils/ansi.js +40 -40
  37. package/cli/src/utils/markdown.js +292 -292
  38. package/examples/ambient-example.js +194 -194
  39. package/examples/basic.js +115 -115
  40. package/examples/bootstrap.js +121 -121
  41. package/examples/mcp-example.js +56 -56
  42. package/examples/skill-example.js +49 -49
  43. package/examples/test-chat.js +137 -137
  44. package/examples/test-mcp.js +85 -85
  45. package/examples/test-reload.js +59 -59
  46. package/examples/test-telegram.js +50 -50
  47. package/examples/test-tg-bot.js +45 -45
  48. package/examples/test-tg-simple.js +47 -47
  49. package/examples/test-tg.js +62 -62
  50. package/examples/test-think.js +43 -43
  51. package/examples/test-web-plugin.js +103 -103
  52. package/examples/test-weixin-feishu.js +103 -103
  53. package/examples/workflow.js +158 -158
  54. package/package.json +83 -83
  55. package/plugins/ai-plugin.js +102 -102
  56. package/plugins/ambient-agent/EventWatcher.js +113 -113
  57. package/plugins/ambient-agent/ExplorerLoop.js +640 -640
  58. package/plugins/ambient-agent/GoalManager.js +197 -197
  59. package/plugins/ambient-agent/Reflector.js +95 -95
  60. package/plugins/ambient-agent/StateStore.js +90 -90
  61. package/plugins/ambient-agent/constants.js +101 -101
  62. package/plugins/ambient-agent/index.js +579 -579
  63. package/plugins/audit-plugin.js +187 -187
  64. package/plugins/default-plugins.js +548 -548
  65. package/plugins/email/constants.js +64 -64
  66. package/plugins/email/handlers.js +461 -461
  67. package/plugins/email/index.js +278 -278
  68. package/plugins/email/monitor.js +269 -269
  69. package/plugins/email/parser.js +138 -138
  70. package/plugins/email/reply.js +151 -151
  71. package/plugins/email/utils.js +124 -124
  72. package/plugins/extension-executor-plugin.js +326 -326
  73. package/plugins/feishu-plugin.js +481 -481
  74. package/plugins/file-system-plugin.js +920 -877
  75. package/plugins/gate-trading.js +747 -747
  76. package/plugins/install-plugin.js +199 -199
  77. package/plugins/python-executor-plugin.js +367 -367
  78. package/plugins/python-plugin-loader.js +651 -651
  79. package/plugins/rules-plugin.js +294 -294
  80. package/plugins/scheduler-plugin.js +691 -691
  81. package/plugins/session-plugin.js +494 -494
  82. package/plugins/shell-executor-plugin.js +197 -197
  83. package/plugins/storage-plugin.js +263 -263
  84. package/plugins/subagent-plugin.js +845 -845
  85. package/plugins/telegram-plugin.js +482 -482
  86. package/plugins/think-plugin.js +345 -345
  87. package/plugins/tools-plugin.js +196 -196
  88. package/plugins/web-plugin.js +637 -637
  89. package/plugins/weixin-plugin.js +545 -545
  90. package/skills/find-skills/AGENTS.md +162 -162
  91. package/skills/find-skills/SKILL.md +133 -133
  92. package/skills/foliko-dev/SKILL.md +563 -583
  93. package/skills/python-plugin-dev/SKILL.md +238 -238
  94. package/src/capabilities/index.js +11 -11
  95. package/src/capabilities/skill-manager.js +609 -609
  96. package/src/capabilities/workflow-engine.js +1109 -1109
  97. package/src/core/agent-chat.js +141 -134
  98. package/src/core/agent.js +958 -958
  99. package/src/core/framework.js +465 -465
  100. package/src/core/index.js +19 -19
  101. package/src/core/plugin-base.js +262 -262
  102. package/src/core/plugin-manager.js +863 -863
  103. package/src/core/provider.js +114 -114
  104. package/src/core/sub-agent-config.js +264 -264
  105. package/src/core/system-prompt-builder.js +120 -120
  106. package/src/core/tool-registry.js +517 -517
  107. package/src/core/tool-router.js +297 -297
  108. package/src/executors/executor-base.js +58 -58
  109. package/src/executors/mcp-executor.js +845 -845
  110. package/src/index.js +25 -25
  111. package/src/utils/circuit-breaker.js +301 -301
  112. package/src/utils/error-boundary.js +363 -363
  113. package/src/utils/error.js +374 -374
  114. package/src/utils/event-emitter.js +97 -97
  115. package/src/utils/id.js +133 -133
  116. package/src/utils/index.js +217 -217
  117. package/src/utils/logger.js +181 -181
  118. package/src/utils/plugin-helpers.js +90 -90
  119. package/src/utils/retry.js +122 -122
  120. package/src/utils/sandbox.js +292 -292
  121. package/test/tool-registry-validation.test.js +218 -218
  122. package/website/script.js +136 -136
  123. package/.agent/.shared/ui-ux-pro-max/data/charts.csv +0 -26
  124. package/.agent/.shared/ui-ux-pro-max/data/colors.csv +0 -97
  125. package/.agent/.shared/ui-ux-pro-max/data/icons.csv +0 -101
  126. package/.agent/.shared/ui-ux-pro-max/data/landing.csv +0 -31
  127. package/.agent/.shared/ui-ux-pro-max/data/products.csv +0 -97
  128. package/.agent/.shared/ui-ux-pro-max/data/prompts.csv +0 -24
  129. package/.agent/.shared/ui-ux-pro-max/data/react-performance.csv +0 -45
  130. package/.agent/.shared/ui-ux-pro-max/data/stacks/flutter.csv +0 -53
  131. package/.agent/.shared/ui-ux-pro-max/data/stacks/html-tailwind.csv +0 -56
  132. package/.agent/.shared/ui-ux-pro-max/data/stacks/jetpack-compose.csv +0 -53
  133. package/.agent/.shared/ui-ux-pro-max/data/stacks/nextjs.csv +0 -53
  134. package/.agent/.shared/ui-ux-pro-max/data/stacks/nuxt-ui.csv +0 -51
  135. package/.agent/.shared/ui-ux-pro-max/data/stacks/nuxtjs.csv +0 -59
  136. package/.agent/.shared/ui-ux-pro-max/data/stacks/react-native.csv +0 -52
  137. package/.agent/.shared/ui-ux-pro-max/data/stacks/react.csv +0 -54
  138. package/.agent/.shared/ui-ux-pro-max/data/stacks/shadcn.csv +0 -61
  139. package/.agent/.shared/ui-ux-pro-max/data/stacks/svelte.csv +0 -54
  140. package/.agent/.shared/ui-ux-pro-max/data/stacks/swiftui.csv +0 -51
  141. package/.agent/.shared/ui-ux-pro-max/data/stacks/vue.csv +0 -50
  142. package/.agent/.shared/ui-ux-pro-max/data/styles.csv +0 -59
  143. package/.agent/.shared/ui-ux-pro-max/data/typography.csv +0 -58
  144. package/.agent/.shared/ui-ux-pro-max/data/ui-reasoning.csv +0 -101
  145. package/.agent/.shared/ui-ux-pro-max/data/ux-guidelines.csv +0 -100
  146. package/.agent/.shared/ui-ux-pro-max/data/web-interface.csv +0 -31
  147. package/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/core.cpython-313.pyc +0 -0
  148. package/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-313.pyc +0 -0
  149. package/.agent/.shared/ui-ux-pro-max/scripts/core.py +0 -258
  150. package/.agent/.shared/ui-ux-pro-max/scripts/design_system.py +0 -1067
  151. package/.agent/.shared/ui-ux-pro-max/scripts/search.py +0 -106
  152. package/.agent/ARCHITECTURE.md +0 -288
  153. package/.agent/agents/ambient-agent.md +0 -57
  154. package/.agent/agents/debugger.md +0 -55
  155. package/.agent/agents/email-assistant.md +0 -49
  156. package/.agent/agents/file-manager.md +0 -42
  157. package/.agent/agents/python-developer.md +0 -60
  158. package/.agent/agents/scheduler.md +0 -59
  159. package/.agent/agents/web-developer.md +0 -45
  160. package/.agent/mcp_config_updated.json +0 -12
  161. package/.agent/rules/GEMINI.md +0 -273
  162. package/.agent/rules/allow-rule.md +0 -77
  163. package/.agent/rules/log-rule.md +0 -83
  164. package/.agent/rules/security-rule.md +0 -93
  165. package/.agent/scripts/auto_preview.py +0 -148
  166. package/.agent/scripts/checklist.py +0 -217
  167. package/.agent/scripts/session_manager.py +0 -120
  168. package/.agent/scripts/verify_all.py +0 -327
  169. package/.agent/skills/api-patterns/SKILL.md +0 -81
  170. package/.agent/skills/api-patterns/api-style.md +0 -42
  171. package/.agent/skills/api-patterns/auth.md +0 -24
  172. package/.agent/skills/api-patterns/documentation.md +0 -26
  173. package/.agent/skills/api-patterns/graphql.md +0 -41
  174. package/.agent/skills/api-patterns/rate-limiting.md +0 -31
  175. package/.agent/skills/api-patterns/response.md +0 -37
  176. package/.agent/skills/api-patterns/rest.md +0 -40
  177. package/.agent/skills/api-patterns/scripts/api_validator.py +0 -211
  178. package/.agent/skills/api-patterns/security-testing.md +0 -122
  179. package/.agent/skills/api-patterns/trpc.md +0 -41
  180. package/.agent/skills/api-patterns/versioning.md +0 -22
  181. package/.agent/skills/app-builder/SKILL.md +0 -75
  182. package/.agent/skills/app-builder/agent-coordination.md +0 -71
  183. package/.agent/skills/app-builder/feature-building.md +0 -53
  184. package/.agent/skills/app-builder/project-detection.md +0 -34
  185. package/.agent/skills/app-builder/scaffolding.md +0 -118
  186. package/.agent/skills/app-builder/tech-stack.md +0 -40
  187. package/.agent/skills/app-builder/templates/SKILL.md +0 -39
  188. package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +0 -76
  189. package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +0 -92
  190. package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +0 -88
  191. package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +0 -88
  192. package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +0 -83
  193. package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +0 -90
  194. package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +0 -90
  195. package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +0 -122
  196. package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +0 -122
  197. package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +0 -169
  198. package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +0 -134
  199. package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +0 -83
  200. package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +0 -119
  201. package/.agent/skills/architecture/SKILL.md +0 -55
  202. package/.agent/skills/architecture/context-discovery.md +0 -43
  203. package/.agent/skills/architecture/examples.md +0 -94
  204. package/.agent/skills/architecture/pattern-selection.md +0 -68
  205. package/.agent/skills/architecture/patterns-reference.md +0 -50
  206. package/.agent/skills/architecture/trade-off-analysis.md +0 -77
  207. package/.agent/skills/clean-code/SKILL.md +0 -201
  208. package/.agent/skills/doc.md +0 -177
  209. package/.agent/skills/frontend-design/SKILL.md +0 -418
  210. package/.agent/skills/frontend-design/animation-guide.md +0 -331
  211. package/.agent/skills/frontend-design/color-system.md +0 -311
  212. package/.agent/skills/frontend-design/decision-trees.md +0 -418
  213. package/.agent/skills/frontend-design/motion-graphics.md +0 -306
  214. package/.agent/skills/frontend-design/scripts/accessibility_checker.py +0 -183
  215. package/.agent/skills/frontend-design/scripts/ux_audit.py +0 -722
  216. package/.agent/skills/frontend-design/typography-system.md +0 -345
  217. package/.agent/skills/frontend-design/ux-psychology.md +0 -1116
  218. package/.agent/skills/frontend-design/visual-effects.md +0 -383
  219. package/.agent/skills/i18n-localization/SKILL.md +0 -154
  220. package/.agent/skills/i18n-localization/scripts/i18n_checker.py +0 -241
  221. package/.agent/skills/mcp-builder/SKILL.md +0 -176
  222. package/.agent/skills/web-design-guidelines/SKILL.md +0 -57
  223. package/.agent/workflows/brainstorm.md +0 -113
  224. package/.agent/workflows/create.md +0 -59
  225. package/.agent/workflows/debug.md +0 -103
  226. package/.agent/workflows/deploy.md +0 -176
  227. package/.agent/workflows/enhance.md +0 -63
  228. package/.agent/workflows/orchestrate.md +0 -237
  229. package/.agent/workflows/plan.md +0 -89
  230. package/.agent/workflows/preview.md +0 -81
  231. package/.agent/workflows/simple-test.md +0 -42
  232. package/.agent/workflows/status.md +0 -86
  233. package/.agent/workflows/structured-orchestrate.md +0 -180
  234. package/.agent/workflows/test.md +0 -144
  235. package/.agent/workflows/ui-ux-pro-max.md +0 -296
@@ -1,637 +1,637 @@
1
- /**
2
- * Web 服务插件
3
- * 支持 HTTP 服务、路由注册、Webhook(自动生成 /webhook/{id} 链接)
4
- */
5
-
6
- const { Plugin } = require('../src/core/plugin-base')
7
- const { logger } = require('../src/utils/logger')
8
- const { runInSandbox } = require('../src/utils/sandbox')
9
- const log = logger.child('Web')
10
- const { z } = require('zod')
11
- const { serve } = require('@hono/node-server')
12
- const { Hono } = require('hono')
13
- const fs = require('fs')
14
- const path = require('path')
15
-
16
- class WebPlugin extends Plugin {
17
- constructor(config = {}) {
18
- super()
19
- this.name = 'web'
20
- this.version = '3.1.0'
21
- this.description = 'Web 服务插件,支持 HTTP 服务、路由注册、Webhook'
22
- this.priority = 50
23
-
24
- this.system = true
25
-
26
- // 服务器配置
27
- this._port = process.env.WEB_PORT || 3000
28
- this._host = process.env.WEB_HOST || '127.0.0.1'
29
- this._baseUrl = process.env.WEB_BASE_URL || null // 公网可访问的域名
30
-
31
- // 运行时状态
32
- this._server = null
33
- this._app = null
34
- this._framework = null
35
-
36
- this.tools = {}
37
-
38
- // 数据存储(始终保持原始类型)
39
- this._routes = [] // 路由列表
40
- this._webhooks = new Map() // webhook Map: id -> {id, path, prompt, sessionId}
41
- this._statics = [] // 静态文件夹列表
42
- }
43
-
44
- // ==================== 生命周期 ====================
45
-
46
- install(framework) {
47
- this._framework = framework
48
- this._registerTools()
49
-
50
- // 将 WEB_BASE_URL 注入到 framework 的元数据,供所有 agent 使用
51
- if (this._baseUrl && framework._mainAgent) {
52
- framework._mainAgent.setMetadata('WEB_BASE_URL', this._baseUrl)
53
- }
54
-
55
- return this
56
- }
57
-
58
- start() {
59
- return this
60
- }
61
-
62
- reload(framework) {
63
- this._framework = framework
64
- // 重新注入 WEB_BASE_URL
65
- if (this._baseUrl && framework._mainAgent) {
66
- framework._mainAgent.setMetadata('WEB_BASE_URL', this._baseUrl)
67
- }
68
- }
69
-
70
- uninstall() {
71
- this._stopServer()
72
- this._framework = null
73
- }
74
-
75
- // ==================== 工具注册 ====================
76
-
77
- _registerTools() {
78
- // 启动 Web 服务
79
- this.tools.web_start = {
80
- name: 'web_start',
81
- description: '启动 Web 服务',
82
- inputSchema: z.object({
83
- port: z.number().optional().describe('端口号,默认 3000'),
84
- host: z.string().optional().describe('主机地址,默认 0.0.0.0')
85
- }),
86
- execute: async (args) => this._startServer(args.port, args.host)
87
- }
88
-
89
- // 停止 Web 服务
90
- this.tools.web_stop = {
91
- name: 'web_stop',
92
- description: '停止 Web 服务',
93
- inputSchema: z.object({}),
94
- execute: async () => this._stopServer()
95
- }
96
-
97
- // 注册 HTTP 路由
98
- this.tools.web_register_route = {
99
- name: 'web_register_route',
100
- description: '注册 HTTP 路由',
101
- inputSchema: z.object({
102
- method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP 方法'),
103
- path: z.string().describe('路由路径,如 /api/user'),
104
- handler: z.string().describe(
105
- '处理逻辑,JavaScript 代码字符串,必须用 return 返回内容。' +
106
- '优先使用 tools.{toolName}(args) 调用工具获取真实数据。' +
107
- '可用变量:context.params, context.query, context.body, tools。' +
108
- '示例:return await tools.get_user({ id: context.params.id })'
109
- ),
110
- description: z.string().optional().describe('路由描述')
111
- }),
112
- execute: async (args) => this._registerRoute(args.method, args.path, args.handler, args.description)
113
- }
114
-
115
- // 注册 Webhook(自动生成 /webhook/{id} 链接)
116
- this.tools.web_register_webhook = {
117
- name: 'web_register_webhook',
118
- description: '注册 Webhook,接收的数据会交给 LLM 处理。自动生成唯一 URL',
119
- inputSchema: z.object({
120
- prompt: z.string().optional().describe('提示词,描述如何处理请求'),
121
- awaitResponse: z.boolean().optional().describe('是否等待 LLM 处理完成再返回响应,默认 false')
122
- }),
123
- execute: async (args) => this._registerWebhook(args.prompt, args.awaitResponse)
124
- }
125
-
126
- // 注册静态资源
127
- this.tools.web_register_static = {
128
- name: 'web_register_static',
129
- description: '注册静态资源文件夹',
130
- inputSchema: z.object({
131
- urlPath: z.string().describe('URL 路径前缀,如 /public'),
132
- folder: z.string().describe('本地文件夹路径,如 ./static'),
133
- options: z.object({
134
- dotfiles: z.enum(['ignore', 'allow', 'deny']).optional(),
135
- index: z.string().optional()
136
- }).optional()
137
- }),
138
- execute: async (args) => this._registerStatic(args.urlPath, args.folder, args.options)
139
- }
140
-
141
- // 列出所有路由
142
- this.tools.web_list_routes = {
143
- name: 'web_list_routes',
144
- description: '列出所有已注册的路由和 Webhook',
145
- inputSchema: z.object({}),
146
- execute: async () => this._listRoutes()
147
- }
148
-
149
- // 发送 HTTP 请求
150
- this.tools.web_request = {
151
- name: 'web_request',
152
- description: '发送 HTTP 请求',
153
- inputSchema: z.object({
154
- method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP 方法'),
155
- path: z.string().describe('请求路径'),
156
- body: z.any().optional().describe('请求体'),
157
- headers: z.record(z.string()).optional().describe('请求头')
158
- }),
159
- execute: async (args) => this._sendRequest(args.method, args.path, args.body, args.headers)
160
- }
161
- }
162
-
163
- // ==================== 服务器控制 ====================
164
-
165
- async _startServer(port, host) {
166
- if (this._server) {
167
- return { success: true, message: 'Server already running', port: this._port }
168
- }
169
-
170
- this._port = port || this._port
171
- this._host = host || this._host
172
-
173
- this._app = new Hono()
174
- this._setupMiddleware()
175
-
176
- try {
177
- this._server = serve({
178
- fetch: this._app.fetch,
179
- port: this._port,
180
- hostname: this._host
181
- })
182
- const serverUrl = this._getUrl()
183
- log.info(` Server started on ${serverUrl}`)
184
- return {
185
- success: true,
186
- message: `Server started on ${serverUrl}`,
187
- // port: this._port,
188
- // host: this._host,
189
- host: serverUrl,
190
- url:serverUrl,
191
- }
192
- } catch (err) {
193
- this._server = null
194
- this._app = null
195
- if (err.code === 'EADDRINUSE') {
196
- return { success: false, error: `Port ${this._port} is already in use` }
197
- }
198
- return { success: false, error: err.message }
199
- }
200
- }
201
-
202
- async _stopServer() {
203
- if (!this._server) {
204
- return { success: true, message: 'Server not running' }
205
- }
206
- this._server.close()
207
- this._server = null
208
- this._app = null
209
- log.info(' Server stopped')
210
- return { success: true, message: 'Server stopped' }
211
- }
212
-
213
- // ==================== 中间件 ====================
214
-
215
- _setupMiddleware() {
216
- this._app.use('*', async (c) => {
217
- const pathname = c.req.path
218
-
219
- // CORS 预检
220
- if (c.req.method === 'OPTIONS') {
221
- return c.text('', 200, {
222
- 'Access-Control-Allow-Origin': '*',
223
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
224
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
225
- })
226
- }
227
-
228
- // 1. 静态文件
229
- const staticResult = this._serveStatic(pathname)
230
- if (staticResult) {
231
- if (staticResult.type === 'file') {
232
- return c.newResponse(staticResult.content, {
233
- headers: { 'Content-Type': staticResult.contentType }
234
- })
235
- }
236
- if (staticResult.type === 'notFound') {
237
- return c.json({ error: 'Not Found' }, 404)
238
- }
239
- if (staticResult.type === 'forbidden') {
240
- return c.json({ error: 'Forbidden' }, 403)
241
- }
242
- if (staticResult.type === 'error') {
243
- return c.json({ error: staticResult.message }, 500)
244
- }
245
- }
246
-
247
- // 2. Webhook(仅接受 POST)
248
- const webhook = this._webhooks.get(pathname)
249
- if (webhook) {
250
- if (c.req.method !== 'POST') {
251
- return c.json({ success: false, error: 'Method Not Allowed. Webhook only accepts POST.' }, 405)
252
- }
253
- const result = await this._handleWebhook(c, webhook)
254
- return c.json(result)
255
- }
256
-
257
- // 3. 路由(支持参数)
258
- for (const route of this._routes) {
259
- if (route.method === c.req.method && this._matchPath(route.path, pathname)) {
260
- return await this._handleRoute(c, route, pathname)
261
- }
262
- }
263
-
264
- // 404
265
- return c.json({ success: false, error: 'Not Found', path: pathname }, 404)
266
- })
267
- }
268
-
269
- // ==================== 请求处理 ====================
270
-
271
- async _handleRoute(c, route, pathname) {
272
- const params = this._extractParams(route.path, pathname)
273
- const query = this._parseQuery(c)
274
- const body = await this._parseBody(c)
275
-
276
- const context = { params, query, body }
277
-
278
- // 构建 tools 代理对象,允许 handler 以函数方式直接调用工具
279
- // 例如: const user = await tools.get_user({ id: 1 })
280
- const registry = this._framework.toolRegistry
281
- const tools = new Proxy({}, {
282
- get: (_, name) => {
283
- if (name === 'call') {
284
- // 保留 call 方式作为后备
285
- return async (toolName, args) => registry.execute(toolName, args || {}, this._framework)
286
- }
287
- return async (args) => registry.execute(name, args || {}, this._framework)
288
- }
289
- })
290
-
291
- const result = await this._executeHandler(route.handler, context, tools)
292
- return c.json(result)
293
- }
294
-
295
- async _handleWebhook(c, webhook) {
296
- const query = this._parseQuery(c)
297
- const body = await this._parseBody(c)
298
- const webhookData = {
299
- path: webhook.path,
300
- method: c.req.method,
301
- query,
302
- body,
303
- timestamp: new Date().toISOString()
304
- }
305
-
306
- // 从执行上下文获取 sessionId
307
- const ctx = this._framework.getExecutionContext()
308
- const sessionId = ctx?.sessionId || null
309
-
310
- // 获取 Agent
311
- const agent = this._getAgent(sessionId)
312
- if (!agent) {
313
- log.error(' No agent available')
314
- return { success: false, error: 'No agent available' }
315
- }
316
-
317
- const prompt = webhook.prompt || '处理以下 webhook 数据,返回适当的响应:'
318
- const finalSessionId = sessionId || `web_${Date.now()}`
319
-
320
- // 触发 webhook 接收事件
321
- this._framework.emit('webhook:received', { webhook, data: webhookData, sessionId: finalSessionId })
322
-
323
- // 使用子Agent处理 webhook
324
- const webhookAgent = this._framework.createSubAgent({
325
- name: 'webhook_handler',
326
- role: 'Webhook处理助手,专注于处理webhook数据并生成适当响应'
327
- })
328
-
329
- if (!webhook.awaitResponse) {
330
- // 不等待,立即返回
331
- webhookAgent.chat(`${prompt}\n\n数据:\n${JSON.stringify(webhookData, null, 2)}`).then(result => {
332
- const responseText = result.message || result.text || ''
333
- log.info(` Webhook processed (${webhook.path}), LLM response (${responseText.length} chars)`)
334
-
335
- // 添加到 session 历史
336
- if (sessionId) {
337
- const sessionPlugin = this._framework.pluginManager.get('session')
338
- if (sessionPlugin) {
339
- sessionPlugin.addMessage(sessionId, { role: 'user', content: `【Webhook 数据】\n${JSON.stringify(webhookData, null, 2)}` })
340
- sessionPlugin.addMessage(sessionId, { role: 'assistant', content: responseText })
341
- }
342
- }
343
-
344
- // 触发 webhook 处理完成事件
345
- this._framework.emit('webhook:processed', { webhook, data: webhookData, response: responseText, sessionId: finalSessionId })
346
- }).catch(err => {
347
- log.error(' Webhook error:', err.message)
348
- })
349
-
350
- return { success: true, message: 'Webhook received, processing in background' }
351
- }
352
-
353
- // 等待 LLM 处理完成
354
- try {
355
- const result = await webhookAgent.chat(`${prompt}\n\n数据:\n${JSON.stringify(webhookData, null, 2)}`)
356
- const responseText = result.message || result.text || ''
357
- log.info(` Webhook processed (${webhook.path}), LLM response (${responseText.length} chars)`)
358
-
359
- // 添加到 session 历史
360
- if (sessionId) {
361
- const sessionPlugin = this._framework.pluginManager.get('session')
362
- if (sessionPlugin) {
363
- sessionPlugin.addMessage(sessionId, { role: 'user', content: `【Webhook 数据】\n${JSON.stringify(webhookData, null, 2)}` })
364
- sessionPlugin.addMessage(sessionId, { role: 'assistant', content: responseText })
365
- }
366
- }
367
-
368
- // 触发 webhook 处理完成事件
369
- this._framework.emit('webhook:received', { webhook, data: webhookData, response: responseText, sessionId: finalSessionId })
370
-
371
- return { success: true, message: 'Webhook processed', response: responseText }
372
- } catch (err) {
373
- log.error(' Webhook error:', err.message)
374
- return { success: false, error: err.message }
375
- }
376
- }
377
-
378
- // ==================== 路由注册 ====================
379
-
380
- async _registerRoute(method, path, handler, description) {
381
- if (!path.startsWith('/') || path.length < 2) {
382
- return { success: false, error: 'Invalid path format' }
383
- }
384
-
385
- if (!this._server) {
386
- await this._startServer()
387
- }
388
-
389
- const route = { method: method.toUpperCase(), path, handler, description: description || '' }
390
- const index = this._routes.findIndex(r => r.method === route.method && r.path === path)
391
- if (index >= 0) {
392
- this._routes[index] = route
393
- } else {
394
- this._routes.push(route)
395
- }
396
-
397
- log.info(` Route registered: ${method} ${path}`)
398
- return { success: true, message: `Route ${method} ${path} registered`, url: this._getUrl(path), route: { method, path, description } }
399
- }
400
-
401
- async _registerWebhook(prompt, awaitResponse = false) {
402
- if (!this._server) {
403
- await this._startServer()
404
- }
405
-
406
- // 生成唯一 ID 和路径:/webhook/{id}
407
- const id = this._generateId()
408
- const webhookPath = `/webhook/${id}`
409
-
410
- this._webhooks.set(webhookPath, {
411
- id,
412
- path: webhookPath,
413
- prompt: prompt || '处理以下 webhook 数据,返回适当的响应:',
414
- awaitResponse
415
- })
416
-
417
- log.info(` Webhook registered: ${webhookPath}`)
418
- return {
419
- success: true,
420
- message: `Webhook registered`,
421
- webhook: {
422
- id,
423
- path: webhookPath,
424
- url: this._getUrl(webhookPath)
425
- }
426
- }
427
- }
428
-
429
- async _registerStatic(urlPath, folder, options = {}) {
430
- if (!this._server) {
431
- await this._startServer()
432
- }
433
-
434
- const normalizedPath = urlPath.endsWith('/') ? urlPath : urlPath + '/'
435
- this._statics.push({
436
- urlPath: normalizedPath,
437
- folder: path.resolve(folder),
438
- options: {
439
- dotfiles: options.dotfiles || 'ignore',
440
- index: options.index || 'index.html'
441
- }
442
- })
443
-
444
- log.info(` Static registered: ${normalizedPath} -> ${folder}`)
445
- return {
446
- success: true,
447
- message: `Static folder registered`,
448
- url: this._getUrl(normalizedPath)
449
- }
450
- }
451
-
452
- _listRoutes() {
453
- const baseUrl = this._getUrl()
454
-
455
- return {
456
- success: true,
457
- server: this._server ? { running: true, host: this._host, port: this._port } : { running: false },
458
- routes: this._routes.map(r => ({ type: 'route', method: r.method, path: r.path, description: r.description })),
459
- webhooks: Array.from(this._webhooks.values()).map(w => ({ type: 'webhook', id: w.id, path: w.path, url: `${baseUrl}${w.path}`, prompt: w.prompt })),
460
- statics: this._statics.map(s => ({ type: 'static', path: s.urlPath, folder: s.folder, url: `${baseUrl}${s.urlPath}` }))
461
- }
462
- }
463
-
464
- // ==================== HTTP 客户端 ====================
465
-
466
- async _sendRequest(method, urlPath, body, headers) {
467
- if (!this._server) {
468
- return { success: false, error: 'Server not started' }
469
- }
470
-
471
- const url = this._getUrl(urlPath)
472
- try {
473
- const options = {
474
- method: method.toUpperCase(),
475
- headers: headers || {}
476
- }
477
-
478
- if (body && !['GET', 'HEAD'].includes(options.method)) {
479
- options.body = JSON.stringify(body)
480
- options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/json'
481
- }
482
-
483
- const response = await fetch(url, options)
484
- const text = await response.text()
485
- let parsed = text
486
- try { parsed = JSON.parse(text) } catch { /* not JSON */ }
487
-
488
- return { success: true, status: response.status, headers: Object.fromEntries(response.headers.entries()), body: parsed }
489
- } catch (err) {
490
- return { success: false, error: err.message }
491
- }
492
- }
493
-
494
- // ==================== 工具方法 ====================
495
-
496
- _matchPath(routePath, reqPath) {
497
- const routeParts = routePath.split('/').filter(Boolean)
498
- const reqParts = reqPath.split('/').filter(Boolean)
499
- if (routeParts.length !== reqParts.length) return false
500
- return routeParts.every((part, i) => part.startsWith(':') || part === reqParts[i])
501
- }
502
-
503
- _extractParams(routePath, reqPath) {
504
- const params = {}
505
- const routeParts = routePath.split('/').filter(Boolean)
506
- const reqParts = reqPath.split('/').filter(Boolean)
507
- routeParts.forEach((part, i) => {
508
- if (part.startsWith(':')) {
509
- params[part.substring(1)] = reqParts[i]
510
- }
511
- })
512
- return params
513
- }
514
-
515
- _parseQuery(c) {
516
- const raw = c.req.queries() || {}
517
- const query = {}
518
- for (const [key, value] of Object.entries(raw)) {
519
- query[key] = value.length === 1 ? value[0] : value
520
- }
521
- return query
522
- }
523
-
524
- async _parseBody(c) {
525
- try {
526
- const rawText = await c.req.text()
527
- log.info(rawText)
528
- if (!rawText) return {}
529
- return JSON.parse(rawText)
530
- } catch (e) {
531
- return {}
532
- }
533
- }
534
-
535
- _getUrl(path='') {
536
- if (this._baseUrl) {
537
- return `${this._baseUrl}${path}`
538
- }
539
- return `http://${this._host}:${this._port}${path}`
540
- }
541
-
542
- async _executeHandler(handlerCode, context, tools) {
543
- try {
544
- // 辅助函数
545
- const helpers = {
546
- // 基础工具
547
- echo: (val) => val,
548
- json: (val) => JSON.stringify(val),
549
- JSON: JSON,
550
- // 日期时间
551
- Date: Date,
552
- now: () => Date.now(),
553
- // 字符串
554
- Str: String,
555
- // 编码
556
- btoa: (str) => Buffer.from(str).toString('base64'),
557
- atob: (str) => Buffer.from(str, 'base64').toString(),
558
- // 格式化
559
- template: (str, vars) => str.replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k] ?? `{{${k}}}`),
560
- // 随机
561
- uuid: () => Math.random().toString(36).substring(2) + Date.now().toString(36),
562
- // HTTP 请求(通过 fetch)
563
- fetch: async (url, options = {}) => {
564
- const { method = 'GET', headers = {}, body } = options
565
- const res = await fetch(url, { method, headers, body })
566
- return { status: res.status, headers: Object.fromEntries(res.headers), body: await res.text() }
567
- }
568
- }
569
- // 使用沙箱执行用户代码,防止恶意代码执行
570
- return await runInSandbox(handlerCode, { context, tools, ...helpers }, { timeout: 10000 })
571
- } catch (err) {
572
- return { success: false, error: `Handler error: ${err.message}` }
573
- }
574
- }
575
-
576
- _serveStatic(pathname) {
577
- for (const staticFolder of this._statics) {
578
- if (pathname.startsWith(staticFolder.urlPath)) {
579
- const relativePath = pathname.substring(staticFolder.urlPath.length) || staticFolder.options.index
580
- const filePath = path.join(staticFolder.folder, relativePath)
581
-
582
- // 安全检查
583
- if (!filePath.startsWith(staticFolder.folder)) {
584
- return { type: 'forbidden' }
585
- }
586
- if (staticFolder.options.dotfiles === 'deny' && path.basename(filePath).startsWith('.')) {
587
- return { type: 'notFound' }
588
- }
589
-
590
- try {
591
- const content = fs.readFileSync(filePath)
592
- const ext = path.extname(filePath).toLowerCase()
593
- const contentTypes = {
594
- '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
595
- '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
596
- '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
597
- '.txt': 'text/plain'
598
- }
599
- const contentType = contentTypes[ext] || 'application/octet-stream'
600
- return { type: 'file', content, contentType }
601
- } catch (err) {
602
- if (err.code === 'ENOENT') {
603
- return { type: 'notFound' }
604
- }
605
- return { type: 'error', message: err.message }
606
- }
607
- }
608
- }
609
- return null
610
- }
611
-
612
- _generateId() {
613
- return Math.random().toString(36).substring(2, 10) + Date.now().toString(36)
614
- }
615
-
616
- _getAgent(sessionId) {
617
- const finalSessionId = sessionId || `web_${Date.now()}`
618
-
619
- // 尝试从对应平台插件获取 Agent
620
- const platformPrefixes = ['weixin_', 'telegram_', 'feishu_']
621
- for (const prefix of platformPrefixes) {
622
- if (finalSessionId.startsWith(prefix)) {
623
- const pluginName = prefix.replace('_', '')
624
- const plugin = this._framework.pluginManager.get(pluginName)
625
- if (plugin?._sessionAgents?.size > 0) {
626
- const firstAgent = plugin._sessionAgents.values().next().value
627
- if (firstAgent) return firstAgent
628
- }
629
- }
630
- }
631
-
632
- // 返回主 Agent
633
- return this._framework._mainAgent || this._framework._agents?.[0]
634
- }
635
- }
636
-
637
- module.exports = WebPlugin
1
+ /**
2
+ * Web 服务插件
3
+ * 支持 HTTP 服务、路由注册、Webhook(自动生成 /webhook/{id} 链接)
4
+ */
5
+
6
+ const { Plugin } = require('../src/core/plugin-base')
7
+ const { logger } = require('../src/utils/logger')
8
+ const { runInSandbox } = require('../src/utils/sandbox')
9
+ const log = logger.child('Web')
10
+ const { z } = require('zod')
11
+ const { serve } = require('@hono/node-server')
12
+ const { Hono } = require('hono')
13
+ const fs = require('fs')
14
+ const path = require('path')
15
+
16
+ class WebPlugin extends Plugin {
17
+ constructor(config = {}) {
18
+ super()
19
+ this.name = 'web'
20
+ this.version = '3.1.0'
21
+ this.description = 'Web 服务插件,支持 HTTP 服务、路由注册、Webhook'
22
+ this.priority = 50
23
+
24
+ this.system = true
25
+
26
+ // 服务器配置
27
+ this._port = process.env.WEB_PORT || 3000
28
+ this._host = process.env.WEB_HOST || '127.0.0.1'
29
+ this._baseUrl = process.env.WEB_BASE_URL || null // 公网可访问的域名
30
+
31
+ // 运行时状态
32
+ this._server = null
33
+ this._app = null
34
+ this._framework = null
35
+
36
+ this.tools = {}
37
+
38
+ // 数据存储(始终保持原始类型)
39
+ this._routes = [] // 路由列表
40
+ this._webhooks = new Map() // webhook Map: id -> {id, path, prompt, sessionId}
41
+ this._statics = [] // 静态文件夹列表
42
+ }
43
+
44
+ // ==================== 生命周期 ====================
45
+
46
+ install(framework) {
47
+ this._framework = framework
48
+ this._registerTools()
49
+
50
+ // 将 WEB_BASE_URL 注入到 framework 的元数据,供所有 agent 使用
51
+ if (this._baseUrl && framework._mainAgent) {
52
+ framework._mainAgent.setMetadata('WEB_BASE_URL', this._baseUrl)
53
+ }
54
+
55
+ return this
56
+ }
57
+
58
+ start() {
59
+ return this
60
+ }
61
+
62
+ reload(framework) {
63
+ this._framework = framework
64
+ // 重新注入 WEB_BASE_URL
65
+ if (this._baseUrl && framework._mainAgent) {
66
+ framework._mainAgent.setMetadata('WEB_BASE_URL', this._baseUrl)
67
+ }
68
+ }
69
+
70
+ uninstall() {
71
+ this._stopServer()
72
+ this._framework = null
73
+ }
74
+
75
+ // ==================== 工具注册 ====================
76
+
77
+ _registerTools() {
78
+ // 启动 Web 服务
79
+ this.tools.web_start = {
80
+ name: 'web_start',
81
+ description: '启动 Web 服务',
82
+ inputSchema: z.object({
83
+ port: z.number().optional().describe('端口号,默认 3000'),
84
+ host: z.string().optional().describe('主机地址,默认 0.0.0.0')
85
+ }),
86
+ execute: async (args) => this._startServer(args.port, args.host)
87
+ }
88
+
89
+ // 停止 Web 服务
90
+ this.tools.web_stop = {
91
+ name: 'web_stop',
92
+ description: '停止 Web 服务',
93
+ inputSchema: z.object({}),
94
+ execute: async () => this._stopServer()
95
+ }
96
+
97
+ // 注册 HTTP 路由
98
+ this.tools.web_register_route = {
99
+ name: 'web_register_route',
100
+ description: '注册 HTTP 路由',
101
+ inputSchema: z.object({
102
+ method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP 方法'),
103
+ path: z.string().describe('路由路径,如 /api/user'),
104
+ handler: z.string().describe(
105
+ '处理逻辑,JavaScript 代码字符串,必须用 return 返回内容。' +
106
+ '优先使用 tools.{toolName}(args) 调用工具获取真实数据。' +
107
+ '可用变量:context.params, context.query, context.body, tools。' +
108
+ '示例:return await tools.get_user({ id: context.params.id })'
109
+ ),
110
+ description: z.string().optional().describe('路由描述')
111
+ }),
112
+ execute: async (args) => this._registerRoute(args.method, args.path, args.handler, args.description)
113
+ }
114
+
115
+ // 注册 Webhook(自动生成 /webhook/{id} 链接)
116
+ this.tools.web_register_webhook = {
117
+ name: 'web_register_webhook',
118
+ description: '注册 Webhook,接收的数据会交给 LLM 处理。自动生成唯一 URL',
119
+ inputSchema: z.object({
120
+ prompt: z.string().optional().describe('提示词,描述如何处理请求'),
121
+ awaitResponse: z.boolean().optional().describe('是否等待 LLM 处理完成再返回响应,默认 false')
122
+ }),
123
+ execute: async (args) => this._registerWebhook(args.prompt, args.awaitResponse)
124
+ }
125
+
126
+ // 注册静态资源
127
+ this.tools.web_register_static = {
128
+ name: 'web_register_static',
129
+ description: '注册静态资源文件夹',
130
+ inputSchema: z.object({
131
+ urlPath: z.string().describe('URL 路径前缀,如 /public'),
132
+ folder: z.string().describe('本地文件夹路径,如 ./static'),
133
+ options: z.object({
134
+ dotfiles: z.enum(['ignore', 'allow', 'deny']).optional(),
135
+ index: z.string().optional()
136
+ }).optional()
137
+ }),
138
+ execute: async (args) => this._registerStatic(args.urlPath, args.folder, args.options)
139
+ }
140
+
141
+ // 列出所有路由
142
+ this.tools.web_list_routes = {
143
+ name: 'web_list_routes',
144
+ description: '列出所有已注册的路由和 Webhook',
145
+ inputSchema: z.object({}),
146
+ execute: async () => this._listRoutes()
147
+ }
148
+
149
+ // 发送 HTTP 请求
150
+ this.tools.web_request = {
151
+ name: 'web_request',
152
+ description: '发送 HTTP 请求',
153
+ inputSchema: z.object({
154
+ method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP 方法'),
155
+ path: z.string().describe('请求路径'),
156
+ body: z.any().optional().describe('请求体'),
157
+ headers: z.record(z.string()).optional().describe('请求头')
158
+ }),
159
+ execute: async (args) => this._sendRequest(args.method, args.path, args.body, args.headers)
160
+ }
161
+ }
162
+
163
+ // ==================== 服务器控制 ====================
164
+
165
+ async _startServer(port, host) {
166
+ if (this._server) {
167
+ return { success: true, message: 'Server already running', port: this._port }
168
+ }
169
+
170
+ this._port = port || this._port
171
+ this._host = host || this._host
172
+
173
+ this._app = new Hono()
174
+ this._setupMiddleware()
175
+
176
+ try {
177
+ this._server = serve({
178
+ fetch: this._app.fetch,
179
+ port: this._port,
180
+ hostname: this._host
181
+ })
182
+ const serverUrl = this._getUrl()
183
+ log.info(` Server started on ${serverUrl}`)
184
+ return {
185
+ success: true,
186
+ message: `Server started on ${serverUrl}`,
187
+ // port: this._port,
188
+ // host: this._host,
189
+ host: serverUrl,
190
+ url:serverUrl,
191
+ }
192
+ } catch (err) {
193
+ this._server = null
194
+ this._app = null
195
+ if (err.code === 'EADDRINUSE') {
196
+ return { success: false, error: `Port ${this._port} is already in use` }
197
+ }
198
+ return { success: false, error: err.message }
199
+ }
200
+ }
201
+
202
+ async _stopServer() {
203
+ if (!this._server) {
204
+ return { success: true, message: 'Server not running' }
205
+ }
206
+ this._server.close()
207
+ this._server = null
208
+ this._app = null
209
+ log.info(' Server stopped')
210
+ return { success: true, message: 'Server stopped' }
211
+ }
212
+
213
+ // ==================== 中间件 ====================
214
+
215
+ _setupMiddleware() {
216
+ this._app.use('*', async (c) => {
217
+ const pathname = c.req.path
218
+
219
+ // CORS 预检
220
+ if (c.req.method === 'OPTIONS') {
221
+ return c.text('', 200, {
222
+ 'Access-Control-Allow-Origin': '*',
223
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
224
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
225
+ })
226
+ }
227
+
228
+ // 1. 静态文件
229
+ const staticResult = this._serveStatic(pathname)
230
+ if (staticResult) {
231
+ if (staticResult.type === 'file') {
232
+ return c.newResponse(staticResult.content, {
233
+ headers: { 'Content-Type': staticResult.contentType }
234
+ })
235
+ }
236
+ if (staticResult.type === 'notFound') {
237
+ return c.json({ error: 'Not Found' }, 404)
238
+ }
239
+ if (staticResult.type === 'forbidden') {
240
+ return c.json({ error: 'Forbidden' }, 403)
241
+ }
242
+ if (staticResult.type === 'error') {
243
+ return c.json({ error: staticResult.message }, 500)
244
+ }
245
+ }
246
+
247
+ // 2. Webhook(仅接受 POST)
248
+ const webhook = this._webhooks.get(pathname)
249
+ if (webhook) {
250
+ if (c.req.method !== 'POST') {
251
+ return c.json({ success: false, error: 'Method Not Allowed. Webhook only accepts POST.' }, 405)
252
+ }
253
+ const result = await this._handleWebhook(c, webhook)
254
+ return c.json(result)
255
+ }
256
+
257
+ // 3. 路由(支持参数)
258
+ for (const route of this._routes) {
259
+ if (route.method === c.req.method && this._matchPath(route.path, pathname)) {
260
+ return await this._handleRoute(c, route, pathname)
261
+ }
262
+ }
263
+
264
+ // 404
265
+ return c.json({ success: false, error: 'Not Found', path: pathname }, 404)
266
+ })
267
+ }
268
+
269
+ // ==================== 请求处理 ====================
270
+
271
+ async _handleRoute(c, route, pathname) {
272
+ const params = this._extractParams(route.path, pathname)
273
+ const query = this._parseQuery(c)
274
+ const body = await this._parseBody(c)
275
+
276
+ const context = { params, query, body }
277
+
278
+ // 构建 tools 代理对象,允许 handler 以函数方式直接调用工具
279
+ // 例如: const user = await tools.get_user({ id: 1 })
280
+ const registry = this._framework.toolRegistry
281
+ const tools = new Proxy({}, {
282
+ get: (_, name) => {
283
+ if (name === 'call') {
284
+ // 保留 call 方式作为后备
285
+ return async (toolName, args) => registry.execute(toolName, args || {}, this._framework)
286
+ }
287
+ return async (args) => registry.execute(name, args || {}, this._framework)
288
+ }
289
+ })
290
+
291
+ const result = await this._executeHandler(route.handler, context, tools)
292
+ return c.json(result)
293
+ }
294
+
295
+ async _handleWebhook(c, webhook) {
296
+ const query = this._parseQuery(c)
297
+ const body = await this._parseBody(c)
298
+ const webhookData = {
299
+ path: webhook.path,
300
+ method: c.req.method,
301
+ query,
302
+ body,
303
+ timestamp: new Date().toISOString()
304
+ }
305
+
306
+ // 从执行上下文获取 sessionId
307
+ const ctx = this._framework.getExecutionContext()
308
+ const sessionId = ctx?.sessionId || null
309
+
310
+ // 获取 Agent
311
+ const agent = this._getAgent(sessionId)
312
+ if (!agent) {
313
+ log.error(' No agent available')
314
+ return { success: false, error: 'No agent available' }
315
+ }
316
+
317
+ const prompt = webhook.prompt || '处理以下 webhook 数据,返回适当的响应:'
318
+ const finalSessionId = sessionId || `web_${Date.now()}`
319
+
320
+ // 触发 webhook 接收事件
321
+ this._framework.emit('webhook:received', { webhook, data: webhookData, sessionId: finalSessionId })
322
+
323
+ // 使用子Agent处理 webhook
324
+ const webhookAgent = this._framework.createSubAgent({
325
+ name: 'webhook_handler',
326
+ role: 'Webhook处理助手,专注于处理webhook数据并生成适当响应'
327
+ })
328
+
329
+ if (!webhook.awaitResponse) {
330
+ // 不等待,立即返回
331
+ webhookAgent.chat(`${prompt}\n\n数据:\n${JSON.stringify(webhookData, null, 2)}`).then(result => {
332
+ const responseText = result.message || result.text || ''
333
+ log.info(` Webhook processed (${webhook.path}), LLM response (${responseText.length} chars)`)
334
+
335
+ // 添加到 session 历史
336
+ if (sessionId) {
337
+ const sessionPlugin = this._framework.pluginManager.get('session')
338
+ if (sessionPlugin) {
339
+ sessionPlugin.addMessage(sessionId, { role: 'user', content: `【Webhook 数据】\n${JSON.stringify(webhookData, null, 2)}` })
340
+ sessionPlugin.addMessage(sessionId, { role: 'assistant', content: responseText })
341
+ }
342
+ }
343
+
344
+ // 触发 webhook 处理完成事件
345
+ this._framework.emit('webhook:processed', { webhook, data: webhookData, response: responseText, sessionId: finalSessionId })
346
+ }).catch(err => {
347
+ log.error(' Webhook error:', err.message)
348
+ })
349
+
350
+ return { success: true, message: 'Webhook received, processing in background' }
351
+ }
352
+
353
+ // 等待 LLM 处理完成
354
+ try {
355
+ const result = await webhookAgent.chat(`${prompt}\n\n数据:\n${JSON.stringify(webhookData, null, 2)}`)
356
+ const responseText = result.message || result.text || ''
357
+ log.info(` Webhook processed (${webhook.path}), LLM response (${responseText.length} chars)`)
358
+
359
+ // 添加到 session 历史
360
+ if (sessionId) {
361
+ const sessionPlugin = this._framework.pluginManager.get('session')
362
+ if (sessionPlugin) {
363
+ sessionPlugin.addMessage(sessionId, { role: 'user', content: `【Webhook 数据】\n${JSON.stringify(webhookData, null, 2)}` })
364
+ sessionPlugin.addMessage(sessionId, { role: 'assistant', content: responseText })
365
+ }
366
+ }
367
+
368
+ // 触发 webhook 处理完成事件
369
+ this._framework.emit('webhook:received', { webhook, data: webhookData, response: responseText, sessionId: finalSessionId })
370
+
371
+ return { success: true, message: 'Webhook processed', response: responseText }
372
+ } catch (err) {
373
+ log.error(' Webhook error:', err.message)
374
+ return { success: false, error: err.message }
375
+ }
376
+ }
377
+
378
+ // ==================== 路由注册 ====================
379
+
380
+ async _registerRoute(method, path, handler, description) {
381
+ if (!path.startsWith('/') || path.length < 2) {
382
+ return { success: false, error: 'Invalid path format' }
383
+ }
384
+
385
+ if (!this._server) {
386
+ await this._startServer()
387
+ }
388
+
389
+ const route = { method: method.toUpperCase(), path, handler, description: description || '' }
390
+ const index = this._routes.findIndex(r => r.method === route.method && r.path === path)
391
+ if (index >= 0) {
392
+ this._routes[index] = route
393
+ } else {
394
+ this._routes.push(route)
395
+ }
396
+
397
+ log.info(` Route registered: ${method} ${path}`)
398
+ return { success: true, message: `Route ${method} ${path} registered`, url: this._getUrl(path), route: { method, path, description } }
399
+ }
400
+
401
+ async _registerWebhook(prompt, awaitResponse = false) {
402
+ if (!this._server) {
403
+ await this._startServer()
404
+ }
405
+
406
+ // 生成唯一 ID 和路径:/webhook/{id}
407
+ const id = this._generateId()
408
+ const webhookPath = `/webhook/${id}`
409
+
410
+ this._webhooks.set(webhookPath, {
411
+ id,
412
+ path: webhookPath,
413
+ prompt: prompt || '处理以下 webhook 数据,返回适当的响应:',
414
+ awaitResponse
415
+ })
416
+
417
+ log.info(` Webhook registered: ${webhookPath}`)
418
+ return {
419
+ success: true,
420
+ message: `Webhook registered`,
421
+ webhook: {
422
+ id,
423
+ path: webhookPath,
424
+ url: this._getUrl(webhookPath)
425
+ }
426
+ }
427
+ }
428
+
429
+ async _registerStatic(urlPath, folder, options = {}) {
430
+ if (!this._server) {
431
+ await this._startServer()
432
+ }
433
+
434
+ const normalizedPath = urlPath.endsWith('/') ? urlPath : urlPath + '/'
435
+ this._statics.push({
436
+ urlPath: normalizedPath,
437
+ folder: path.resolve(folder),
438
+ options: {
439
+ dotfiles: options.dotfiles || 'ignore',
440
+ index: options.index || 'index.html'
441
+ }
442
+ })
443
+
444
+ log.info(` Static registered: ${normalizedPath} -> ${folder}`)
445
+ return {
446
+ success: true,
447
+ message: `Static folder registered`,
448
+ url: this._getUrl(normalizedPath)
449
+ }
450
+ }
451
+
452
+ _listRoutes() {
453
+ const baseUrl = this._getUrl()
454
+
455
+ return {
456
+ success: true,
457
+ server: this._server ? { running: true, host: this._host, port: this._port } : { running: false },
458
+ routes: this._routes.map(r => ({ type: 'route', method: r.method, path: r.path, description: r.description })),
459
+ webhooks: Array.from(this._webhooks.values()).map(w => ({ type: 'webhook', id: w.id, path: w.path, url: `${baseUrl}${w.path}`, prompt: w.prompt })),
460
+ statics: this._statics.map(s => ({ type: 'static', path: s.urlPath, folder: s.folder, url: `${baseUrl}${s.urlPath}` }))
461
+ }
462
+ }
463
+
464
+ // ==================== HTTP 客户端 ====================
465
+
466
+ async _sendRequest(method, urlPath, body, headers) {
467
+ if (!this._server) {
468
+ return { success: false, error: 'Server not started' }
469
+ }
470
+
471
+ const url = this._getUrl(urlPath)
472
+ try {
473
+ const options = {
474
+ method: method.toUpperCase(),
475
+ headers: headers || {}
476
+ }
477
+
478
+ if (body && !['GET', 'HEAD'].includes(options.method)) {
479
+ options.body = JSON.stringify(body)
480
+ options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/json'
481
+ }
482
+
483
+ const response = await fetch(url, options)
484
+ const text = await response.text()
485
+ let parsed = text
486
+ try { parsed = JSON.parse(text) } catch { /* not JSON */ }
487
+
488
+ return { success: true, status: response.status, headers: Object.fromEntries(response.headers.entries()), body: parsed }
489
+ } catch (err) {
490
+ return { success: false, error: err.message }
491
+ }
492
+ }
493
+
494
+ // ==================== 工具方法 ====================
495
+
496
+ _matchPath(routePath, reqPath) {
497
+ const routeParts = routePath.split('/').filter(Boolean)
498
+ const reqParts = reqPath.split('/').filter(Boolean)
499
+ if (routeParts.length !== reqParts.length) return false
500
+ return routeParts.every((part, i) => part.startsWith(':') || part === reqParts[i])
501
+ }
502
+
503
+ _extractParams(routePath, reqPath) {
504
+ const params = {}
505
+ const routeParts = routePath.split('/').filter(Boolean)
506
+ const reqParts = reqPath.split('/').filter(Boolean)
507
+ routeParts.forEach((part, i) => {
508
+ if (part.startsWith(':')) {
509
+ params[part.substring(1)] = reqParts[i]
510
+ }
511
+ })
512
+ return params
513
+ }
514
+
515
+ _parseQuery(c) {
516
+ const raw = c.req.queries() || {}
517
+ const query = {}
518
+ for (const [key, value] of Object.entries(raw)) {
519
+ query[key] = value.length === 1 ? value[0] : value
520
+ }
521
+ return query
522
+ }
523
+
524
+ async _parseBody(c) {
525
+ try {
526
+ const rawText = await c.req.text()
527
+ log.info(rawText)
528
+ if (!rawText) return {}
529
+ return JSON.parse(rawText)
530
+ } catch (e) {
531
+ return {}
532
+ }
533
+ }
534
+
535
+ _getUrl(path='') {
536
+ if (this._baseUrl) {
537
+ return `${this._baseUrl}${path}`
538
+ }
539
+ return `http://${this._host}:${this._port}${path}`
540
+ }
541
+
542
+ async _executeHandler(handlerCode, context, tools) {
543
+ try {
544
+ // 辅助函数
545
+ const helpers = {
546
+ // 基础工具
547
+ echo: (val) => val,
548
+ json: (val) => JSON.stringify(val),
549
+ JSON: JSON,
550
+ // 日期时间
551
+ Date: Date,
552
+ now: () => Date.now(),
553
+ // 字符串
554
+ Str: String,
555
+ // 编码
556
+ btoa: (str) => Buffer.from(str).toString('base64'),
557
+ atob: (str) => Buffer.from(str, 'base64').toString(),
558
+ // 格式化
559
+ template: (str, vars) => str.replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k] ?? `{{${k}}}`),
560
+ // 随机
561
+ uuid: () => Math.random().toString(36).substring(2) + Date.now().toString(36),
562
+ // HTTP 请求(通过 fetch)
563
+ fetch: async (url, options = {}) => {
564
+ const { method = 'GET', headers = {}, body } = options
565
+ const res = await fetch(url, { method, headers, body })
566
+ return { status: res.status, headers: Object.fromEntries(res.headers), body: await res.text() }
567
+ }
568
+ }
569
+ // 使用沙箱执行用户代码,防止恶意代码执行
570
+ return await runInSandbox(handlerCode, { context, tools, ...helpers }, { timeout: 10000 })
571
+ } catch (err) {
572
+ return { success: false, error: `Handler error: ${err.message}` }
573
+ }
574
+ }
575
+
576
+ _serveStatic(pathname) {
577
+ for (const staticFolder of this._statics) {
578
+ if (pathname.startsWith(staticFolder.urlPath)) {
579
+ const relativePath = pathname.substring(staticFolder.urlPath.length) || staticFolder.options.index
580
+ const filePath = path.join(staticFolder.folder, relativePath)
581
+
582
+ // 安全检查
583
+ if (!filePath.startsWith(staticFolder.folder)) {
584
+ return { type: 'forbidden' }
585
+ }
586
+ if (staticFolder.options.dotfiles === 'deny' && path.basename(filePath).startsWith('.')) {
587
+ return { type: 'notFound' }
588
+ }
589
+
590
+ try {
591
+ const content = fs.readFileSync(filePath)
592
+ const ext = path.extname(filePath).toLowerCase()
593
+ const contentTypes = {
594
+ '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
595
+ '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
596
+ '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
597
+ '.txt': 'text/plain'
598
+ }
599
+ const contentType = contentTypes[ext] || 'application/octet-stream'
600
+ return { type: 'file', content, contentType }
601
+ } catch (err) {
602
+ if (err.code === 'ENOENT') {
603
+ return { type: 'notFound' }
604
+ }
605
+ return { type: 'error', message: err.message }
606
+ }
607
+ }
608
+ }
609
+ return null
610
+ }
611
+
612
+ _generateId() {
613
+ return Math.random().toString(36).substring(2, 10) + Date.now().toString(36)
614
+ }
615
+
616
+ _getAgent(sessionId) {
617
+ const finalSessionId = sessionId || `web_${Date.now()}`
618
+
619
+ // 尝试从对应平台插件获取 Agent
620
+ const platformPrefixes = ['weixin_', 'telegram_', 'feishu_']
621
+ for (const prefix of platformPrefixes) {
622
+ if (finalSessionId.startsWith(prefix)) {
623
+ const pluginName = prefix.replace('_', '')
624
+ const plugin = this._framework.pluginManager.get(pluginName)
625
+ if (plugin?._sessionAgents?.size > 0) {
626
+ const firstAgent = plugin._sessionAgents.values().next().value
627
+ if (firstAgent) return firstAgent
628
+ }
629
+ }
630
+ }
631
+
632
+ // 返回主 Agent
633
+ return this._framework._mainAgent || this._framework._agents?.[0]
634
+ }
635
+ }
636
+
637
+ module.exports = WebPlugin