foliko 1.0.81 → 1.0.83

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 (88) hide show
  1. package/cli/bin/foliko.js +12 -12
  2. package/cli/src/commands/chat.js +143 -143
  3. package/cli/src/commands/list.js +93 -93
  4. package/cli/src/index.js +75 -75
  5. package/cli/src/ui/chat-ui.js +201 -201
  6. package/cli/src/utils/ansi.js +40 -40
  7. package/cli/src/utils/markdown.js +292 -292
  8. package/examples/ambient-example.js +194 -194
  9. package/examples/basic.js +115 -115
  10. package/examples/bootstrap.js +121 -121
  11. package/examples/mcp-example.js +56 -56
  12. package/examples/skill-example.js +49 -49
  13. package/examples/test-chat.js +137 -137
  14. package/examples/test-mcp.js +85 -85
  15. package/examples/test-reload.js +59 -59
  16. package/examples/test-telegram.js +50 -50
  17. package/examples/test-tg-bot.js +45 -45
  18. package/examples/test-tg-simple.js +47 -47
  19. package/examples/test-tg.js +62 -62
  20. package/examples/test-think.js +43 -43
  21. package/examples/test-web-plugin.js +103 -103
  22. package/examples/test-weixin-feishu.js +103 -103
  23. package/examples/workflow.js +158 -158
  24. package/package.json +83 -83
  25. package/plugins/ai-plugin.js +102 -102
  26. package/plugins/ambient-agent/EventWatcher.js +113 -113
  27. package/plugins/ambient-agent/ExplorerLoop.js +640 -640
  28. package/plugins/ambient-agent/GoalManager.js +197 -197
  29. package/plugins/ambient-agent/Reflector.js +95 -95
  30. package/plugins/ambient-agent/StateStore.js +90 -90
  31. package/plugins/ambient-agent/constants.js +101 -101
  32. package/plugins/ambient-agent/index.js +579 -579
  33. package/plugins/audit-plugin.js +187 -187
  34. package/plugins/default-plugins.js +548 -548
  35. package/plugins/email/constants.js +64 -64
  36. package/plugins/email/handlers.js +461 -461
  37. package/plugins/email/index.js +278 -278
  38. package/plugins/email/monitor.js +269 -269
  39. package/plugins/email/parser.js +138 -138
  40. package/plugins/email/reply.js +151 -151
  41. package/plugins/email/utils.js +124 -124
  42. package/plugins/extension-executor-plugin.js +326 -326
  43. package/plugins/feishu-plugin.js +481 -481
  44. package/plugins/file-system-plugin.js +920 -920
  45. package/plugins/gate-trading.js +747 -747
  46. package/plugins/install-plugin.js +199 -199
  47. package/plugins/python-executor-plugin.js +367 -367
  48. package/plugins/python-plugin-loader.js +651 -651
  49. package/plugins/rules-plugin.js +294 -294
  50. package/plugins/scheduler-plugin.js +691 -691
  51. package/plugins/session-plugin.js +494 -494
  52. package/plugins/shell-executor-plugin.js +197 -197
  53. package/plugins/storage-plugin.js +263 -263
  54. package/plugins/subagent-plugin.js +845 -845
  55. package/plugins/telegram-plugin.js +482 -482
  56. package/plugins/think-plugin.js +345 -345
  57. package/plugins/tools-plugin.js +196 -196
  58. package/plugins/web-plugin.js +637 -637
  59. package/plugins/weixin-plugin.js +545 -545
  60. package/src/capabilities/index.js +11 -11
  61. package/src/capabilities/skill-manager.js +609 -609
  62. package/src/capabilities/workflow-engine.js +1109 -1109
  63. package/src/core/agent-chat.js +1 -1
  64. package/src/core/agent.js +958 -958
  65. package/src/core/framework.js +465 -465
  66. package/src/core/index.js +19 -19
  67. package/src/core/plugin-base.js +262 -262
  68. package/src/core/plugin-manager.js +863 -863
  69. package/src/core/provider.js +114 -114
  70. package/src/core/sub-agent-config.js +264 -264
  71. package/src/core/system-prompt-builder.js +120 -120
  72. package/src/core/tool-registry.js +517 -517
  73. package/src/core/tool-router.js +297 -297
  74. package/src/executors/executor-base.js +58 -58
  75. package/src/executors/mcp-executor.js +845 -845
  76. package/src/index.js +25 -25
  77. package/src/utils/circuit-breaker.js +301 -301
  78. package/src/utils/error-boundary.js +363 -363
  79. package/src/utils/error.js +374 -374
  80. package/src/utils/event-emitter.js +97 -97
  81. package/src/utils/id.js +133 -133
  82. package/src/utils/index.js +217 -217
  83. package/src/utils/logger.js +181 -181
  84. package/src/utils/plugin-helpers.js +90 -90
  85. package/src/utils/retry.js +122 -122
  86. package/src/utils/sandbox.js +292 -292
  87. package/test/tool-registry-validation.test.js +218 -218
  88. package/website/script.js +136 -136
@@ -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