foliko 1.0.75 → 1.0.76

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