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,461 +1,461 @@
1
- /**
2
- * Email 插件 - 邮件处理器
3
- */
4
-
5
- const Imap = require('imap-mkl')
6
- const { simpleParser } = require('mailparser')
7
- const { getConfig, processAttachment } = require('./utils')
8
- const { DEFAULT_IMAP, IMAP_CLIENT_INFO } = require('./constants')
9
-
10
- /**
11
- * 创建 IMAP 配置
12
- * @param {Object} config - 用户配置
13
- * @returns {Object} IMAP 配置
14
- */
15
- function createImapConfig(config = {}) {
16
- const cfg = getConfig(config)
17
- return {
18
- ...DEFAULT_IMAP,
19
- user: cfg.user,
20
- password: cfg.password,
21
- host: cfg.host,
22
- port: cfg.port,
23
- id: IMAP_CLIENT_INFO
24
- }
25
- }
26
-
27
- /**
28
- * 发送邮件
29
- * @param {Object} emailPlugin - EmailPlugin 实例
30
- * @param {Object} args - 发送参数
31
- * @returns {Promise<Object>} 发送结果
32
- */
33
- async function sendEmail(emailPlugin, args) {
34
- try {
35
- const nodemailer = require('nodemailer')
36
- const { DEFAULT_SMTP } = require('./constants')
37
-
38
- const smtpConfig = {
39
- ...DEFAULT_SMTP,
40
- auth: {
41
- user: process.env.SMTP_USER,
42
- pass: process.env.SMTP_PASS
43
- }
44
- }
45
-
46
- const transporter = nodemailer.createTransport(smtpConfig)
47
-
48
- const mailOptions = {
49
- from: process.env.FROM_EMAIL || smtpConfig.auth.user,
50
- to: args.to,
51
- subject: args.subject,
52
- text: args.isHtml ? undefined : args.body,
53
- html: args.isHtml ? args.body : undefined,
54
- cc: args.cc,
55
- bcc: args.bcc,
56
- inReplyTo: args.inReplyTo,
57
- references: args.references
58
- }
59
-
60
- // 处理附件
61
- if (args.attachments && args.attachments.length > 0) {
62
- mailOptions.attachments = []
63
- for (const att of args.attachments) {
64
- const processed = await processAttachment(att)
65
- mailOptions.attachments.push(processed)
66
- }
67
- }
68
-
69
- const info = await transporter.sendMail(mailOptions)
70
- return {
71
- success: true,
72
- message: '邮件发送成功',
73
- messageId: info.messageId,
74
- accepted: info.accepted,
75
- rejected: info.rejected
76
- }
77
- } catch (error) {
78
- return {
79
- success: false,
80
- error: error.message,
81
- details: '请检查 SMTP 配置是否正确'
82
- }
83
- }
84
- }
85
-
86
- /**
87
- * 读取邮件
88
- * @param {Object} emailPlugin - EmailPlugin 实例
89
- * @param {Object} args - 读取参数
90
- * @returns {Promise<Object>} 读取结果
91
- */
92
- async function readEmails(emailPlugin, args) {
93
- try {
94
- const box = args.box || 'INBOX'
95
- const limit = args.limit || 10
96
- const unreadOnly = args.unreadOnly || false
97
-
98
- const imapConfig = createImapConfig(args)
99
- const emails = await fetchEmails(imapConfig, box, limit, unreadOnly, args.searchCriteria)
100
-
101
- return {
102
- success: true,
103
- count: emails.length,
104
- emails
105
- }
106
- } catch (error) {
107
- return {
108
- success: false,
109
- error: error.message,
110
- details: '请检查 IMAP 配置是否正确'
111
- }
112
- }
113
- }
114
-
115
- /**
116
- * 获取未读邮件数量
117
- * @param {Object} emailPlugin - EmailPlugin 实例
118
- * @param {Object} args - 参数
119
- * @returns {Promise<Object>} 未读数量
120
- */
121
- async function getUnreadCount(emailPlugin, args) {
122
- try {
123
- const imapConfig = createImapConfig(args)
124
- const box = args.box || 'INBOX'
125
- const count = await fetchUnreadCount(imapConfig, box)
126
-
127
- return {
128
- success: true,
129
- unreadCount: count,
130
- box
131
- }
132
- } catch (error) {
133
- return {
134
- success: false,
135
- error: error.message
136
- }
137
- }
138
- }
139
-
140
- /**
141
- * 标记邮件为已读
142
- * @param {Object} emailPlugin - EmailPlugin 实例
143
- * @param {Object} args - 参数 { uid: 邮件UID }
144
- * @returns {Promise<Object>} 操作结果
145
- */
146
- async function markAsRead(emailPlugin, args) {
147
- try {
148
- const imapConfig = createImapConfig(args)
149
- await markEmailAsRead(imapConfig, args.uid)
150
-
151
- return {
152
- success: true,
153
- message: '邮件已标记为已读'
154
- }
155
- } catch (error) {
156
- return {
157
- success: false,
158
- error: error.message
159
- }
160
- }
161
- }
162
-
163
- /**
164
- * 删除邮件
165
- * @param {Object} emailPlugin - EmailPlugin 实例
166
- * @param {Object} args - 参数 { uid: 邮件UID, box?: 文件夹 }
167
- * @returns {Promise<Object>} 操作结果
168
- */
169
- async function deleteEmail(emailPlugin, args) {
170
- try {
171
- const messageId = args.messageId || args.uid
172
- if (!messageId) {
173
- return {
174
- success: false,
175
- error: 'messageId 是必填参数'
176
- }
177
- }
178
-
179
- const imapConfig = createImapConfig(args)
180
- const box = args.box || 'INBOX'
181
- await moveToTrash(imapConfig, box, messageId)
182
-
183
- return {
184
- success: true,
185
- message: '邮件已删除'
186
- }
187
- } catch (error) {
188
- return {
189
- success: false,
190
- error: error.message
191
- }
192
- }
193
- }
194
-
195
- /**
196
- * 获取邮箱配置信息
197
- * @returns {Object} 配置信息
198
- */
199
- function getEmailConfig() {
200
- return {
201
- success: true,
202
- message: '邮箱配置通过环境变量设置',
203
- config: {
204
- smtp_host: process.env.SMTP_HOST || 'smtp.gmail.com',
205
- smtp_port: process.env.SMTP_PORT || 587,
206
- smtp_secure: process.env.SMTP_SECURE || 'false',
207
- imap_host: process.env.IMAP_HOST || 'imap.gmail.com',
208
- imap_port: process.env.IMAP_PORT || 993,
209
- from_email: process.env.FROM_EMAIL || '(未设置)',
210
- client_name: process.env.IMAP_CLIENT_NAME || 'FolikoAgent',
211
- client_version: process.env.IMAP_CLIENT_VERSION || '1.0.0'
212
- }
213
- }
214
- }
215
-
216
- // ============ 内部方法 ============
217
-
218
- /**
219
- * 获取邮件列表
220
- */
221
- function fetchEmails(imapConfig, box, limit, unreadOnly, searchCriteria) {
222
- return new Promise((resolve, reject) => {
223
- const imap = new Imap(imapConfig)
224
- const emails = []
225
-
226
- const cleanup = () => {
227
- try { imap.end() } catch (e) {}
228
- }
229
-
230
- imap.on('ready', () => {
231
- imap.openBox(box, true, (err) => {
232
- if (err) {
233
- cleanup()
234
- return reject(err)
235
- }
236
-
237
- let searchFilter = searchCriteria
238
- ? searchCriteria.split(' ').filter(Boolean)
239
- : ['ALL']
240
- if (unreadOnly) {
241
- searchFilter = ['UNSEEN']
242
- }
243
-
244
- imap.search(searchFilter, (err, results) => {
245
- if (err) {
246
- cleanup()
247
- return reject(err)
248
- }
249
-
250
- if (!results || results.length === 0) {
251
- cleanup()
252
- return resolve([])
253
- }
254
-
255
- const fetchIds = results.slice(-limit)
256
- const f = imap.fetch(fetchIds, { bodies: '' })
257
-
258
- f.on('message', (msg) => {
259
- let email = {}
260
- let bodyParsed = false
261
- let uid = null // 在 attributes 事件中获取 UID
262
-
263
- // 先获取 UID(比 body 更可靠)
264
- msg.on('attributes', (attrs) => {
265
- uid = attrs.uid
266
- email.uid = uid
267
- email.id = uid
268
- email.flags = attrs.flags
269
- })
270
-
271
- msg.on('body', (stream) => {
272
- simpleParser(stream).then(mail => {
273
- // 确保 uid 已设置(如果 attributes 先触发)
274
- if (!email.uid && uid) {
275
- email.uid = uid
276
- email.id = uid
277
- }
278
- email.subject = mail.subject
279
- email.from = mail.from?.text || ''
280
- email.to = mail.to?.text || ''
281
- email.date = mail.date?.toISOString() || ''
282
- email.text = mail.text || mail.textAsHtml || ''
283
- email.html = mail.html
284
- email.attachments = mail.attachments?.map(a => ({
285
- filename: a.filename,
286
- contentType: a.contentType
287
- })) || []
288
- bodyParsed = true
289
- }).catch(err => {
290
- email.error = err.message
291
- bodyParsed = true
292
- })
293
- })
294
-
295
- msg.on('end', () => {
296
- const checkDone = () => {
297
- if (bodyParsed) {
298
- // 再次确保 uid 已设置
299
- if (!email.uid && uid) {
300
- email.uid = uid
301
- email.id = uid
302
- }
303
- emails.push(email)
304
- } else {
305
- setTimeout(checkDone, 10)
306
- }
307
- }
308
- checkDone()
309
- })
310
- })
311
-
312
- f.on('error', (err) => {
313
- cleanup()
314
- reject(err)
315
- })
316
-
317
- f.on('end', () => {
318
- // 添加超时保护,避免永久等待
319
- const timeoutMs = 30000
320
- const startTime = Date.now()
321
-
322
- const waitForAll = () => {
323
- if (emails.length === fetchIds.length) {
324
- cleanup()
325
- resolve(emails)
326
- } else if (Date.now() - startTime > timeoutMs) {
327
- cleanup()
328
- resolve(emails) // 返回已获取的邮件
329
- } else {
330
- setTimeout(waitForAll, 50)
331
- }
332
- }
333
- waitForAll()
334
- })
335
- })
336
- })
337
- })
338
-
339
- imap.on('error', (err) => reject(err))
340
- imap.on('end', () => {})
341
-
342
- imap.connect()
343
- })
344
- }
345
-
346
- /**
347
- * 获取未读邮件数量
348
- */
349
- function fetchUnreadCount(imapConfig, box) {
350
- return new Promise((resolve, reject) => {
351
- const imap = new Imap(imapConfig)
352
-
353
- const cleanup = () => {
354
- try { imap.end() } catch (e) {}
355
- }
356
-
357
- imap.on('ready', () => {
358
- imap.openBox(box, true, (err, boxObj) => {
359
- if (err) {
360
- cleanup()
361
- return reject(err)
362
- }
363
- const unreadCount = boxObj.messages.unread
364
- cleanup()
365
- resolve(unreadCount)
366
- })
367
- })
368
-
369
- imap.on('error', (err) => reject(err))
370
- imap.on('end', () => {})
371
-
372
- imap.connect()
373
- })
374
- }
375
-
376
- /**
377
- * 标记邮件为已读
378
- * @param {Object} imapConfig - IMAP 配置
379
- * @param {number|string} uid - 邮件 UID
380
- */
381
- function markEmailAsRead(imapConfig, uid) {
382
- return new Promise((resolve, reject) => {
383
- const imap = new Imap(imapConfig)
384
-
385
- const cleanup = () => {
386
- try { imap.end() } catch (e) {}
387
- }
388
-
389
- imap.on('ready', () => {
390
- imap.openBox('INBOX', true, (err) => {
391
- if (err) {
392
- cleanup()
393
- return reject(err)
394
- }
395
- imap.addFlags(uid, '\\Seen', (err) => {
396
- cleanup()
397
- if (err) reject(err)
398
- else resolve()
399
- })
400
- })
401
- })
402
-
403
- imap.on('error', (err) => reject(err))
404
- imap.on('end', () => {})
405
-
406
- imap.connect()
407
- })
408
- }
409
-
410
- /**
411
- * 移动邮件到垃圾箱
412
- * @param {Object} imapConfig - IMAP 配置
413
- * @param {string} box - 邮箱文件夹
414
- * @param {number|string} uid - 邮件 UID
415
- */
416
- function moveToTrash(imapConfig, box, uid) {
417
- return new Promise((resolve, reject) => {
418
- const imap = new Imap(imapConfig)
419
-
420
- const cleanup = () => {
421
- try { imap.end() } catch (e) {}
422
- }
423
-
424
- imap.on('ready', () => {
425
- imap.openBox(box, true, (err) => {
426
- if (err) {
427
- cleanup()
428
- return reject(err)
429
- }
430
- // 标记邮件为已删除
431
- imap.addFlags(uid, '\\Deleted', (err) => {
432
- if (err) {
433
- cleanup()
434
- return reject(err)
435
- }
436
- // 执行 expunge 永久删除
437
- imap.expunge((err) => {
438
- cleanup()
439
- if (err) reject(err)
440
- else resolve()
441
- })
442
- })
443
- })
444
- })
445
-
446
- imap.on('error', (err) => reject(err))
447
- imap.on('end', () => {})
448
-
449
- imap.connect()
450
- })
451
- }
452
-
453
- module.exports = {
454
- sendEmail,
455
- readEmails,
456
- getUnreadCount,
457
- markAsRead,
458
- deleteEmail,
459
- getEmailConfig,
460
- createImapConfig
461
- }
1
+ /**
2
+ * Email 插件 - 邮件处理器
3
+ */
4
+
5
+ const Imap = require('imap-mkl')
6
+ const { simpleParser } = require('mailparser')
7
+ const { getConfig, processAttachment } = require('./utils')
8
+ const { DEFAULT_IMAP, IMAP_CLIENT_INFO } = require('./constants')
9
+
10
+ /**
11
+ * 创建 IMAP 配置
12
+ * @param {Object} config - 用户配置
13
+ * @returns {Object} IMAP 配置
14
+ */
15
+ function createImapConfig(config = {}) {
16
+ const cfg = getConfig(config)
17
+ return {
18
+ ...DEFAULT_IMAP,
19
+ user: cfg.user,
20
+ password: cfg.password,
21
+ host: cfg.host,
22
+ port: cfg.port,
23
+ id: IMAP_CLIENT_INFO
24
+ }
25
+ }
26
+
27
+ /**
28
+ * 发送邮件
29
+ * @param {Object} emailPlugin - EmailPlugin 实例
30
+ * @param {Object} args - 发送参数
31
+ * @returns {Promise<Object>} 发送结果
32
+ */
33
+ async function sendEmail(emailPlugin, args) {
34
+ try {
35
+ const nodemailer = require('nodemailer')
36
+ const { DEFAULT_SMTP } = require('./constants')
37
+
38
+ const smtpConfig = {
39
+ ...DEFAULT_SMTP,
40
+ auth: {
41
+ user: process.env.SMTP_USER,
42
+ pass: process.env.SMTP_PASS
43
+ }
44
+ }
45
+
46
+ const transporter = nodemailer.createTransport(smtpConfig)
47
+
48
+ const mailOptions = {
49
+ from: process.env.FROM_EMAIL || smtpConfig.auth.user,
50
+ to: args.to,
51
+ subject: args.subject,
52
+ text: args.isHtml ? undefined : args.body,
53
+ html: args.isHtml ? args.body : undefined,
54
+ cc: args.cc,
55
+ bcc: args.bcc,
56
+ inReplyTo: args.inReplyTo,
57
+ references: args.references
58
+ }
59
+
60
+ // 处理附件
61
+ if (args.attachments && args.attachments.length > 0) {
62
+ mailOptions.attachments = []
63
+ for (const att of args.attachments) {
64
+ const processed = await processAttachment(att)
65
+ mailOptions.attachments.push(processed)
66
+ }
67
+ }
68
+
69
+ const info = await transporter.sendMail(mailOptions)
70
+ return {
71
+ success: true,
72
+ message: '邮件发送成功',
73
+ messageId: info.messageId,
74
+ accepted: info.accepted,
75
+ rejected: info.rejected
76
+ }
77
+ } catch (error) {
78
+ return {
79
+ success: false,
80
+ error: error.message,
81
+ details: '请检查 SMTP 配置是否正确'
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 读取邮件
88
+ * @param {Object} emailPlugin - EmailPlugin 实例
89
+ * @param {Object} args - 读取参数
90
+ * @returns {Promise<Object>} 读取结果
91
+ */
92
+ async function readEmails(emailPlugin, args) {
93
+ try {
94
+ const box = args.box || 'INBOX'
95
+ const limit = args.limit || 10
96
+ const unreadOnly = args.unreadOnly || false
97
+
98
+ const imapConfig = createImapConfig(args)
99
+ const emails = await fetchEmails(imapConfig, box, limit, unreadOnly, args.searchCriteria)
100
+
101
+ return {
102
+ success: true,
103
+ count: emails.length,
104
+ emails
105
+ }
106
+ } catch (error) {
107
+ return {
108
+ success: false,
109
+ error: error.message,
110
+ details: '请检查 IMAP 配置是否正确'
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 获取未读邮件数量
117
+ * @param {Object} emailPlugin - EmailPlugin 实例
118
+ * @param {Object} args - 参数
119
+ * @returns {Promise<Object>} 未读数量
120
+ */
121
+ async function getUnreadCount(emailPlugin, args) {
122
+ try {
123
+ const imapConfig = createImapConfig(args)
124
+ const box = args.box || 'INBOX'
125
+ const count = await fetchUnreadCount(imapConfig, box)
126
+
127
+ return {
128
+ success: true,
129
+ unreadCount: count,
130
+ box
131
+ }
132
+ } catch (error) {
133
+ return {
134
+ success: false,
135
+ error: error.message
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * 标记邮件为已读
142
+ * @param {Object} emailPlugin - EmailPlugin 实例
143
+ * @param {Object} args - 参数 { uid: 邮件UID }
144
+ * @returns {Promise<Object>} 操作结果
145
+ */
146
+ async function markAsRead(emailPlugin, args) {
147
+ try {
148
+ const imapConfig = createImapConfig(args)
149
+ await markEmailAsRead(imapConfig, args.uid)
150
+
151
+ return {
152
+ success: true,
153
+ message: '邮件已标记为已读'
154
+ }
155
+ } catch (error) {
156
+ return {
157
+ success: false,
158
+ error: error.message
159
+ }
160
+ }
161
+ }
162
+
163
+ /**
164
+ * 删除邮件
165
+ * @param {Object} emailPlugin - EmailPlugin 实例
166
+ * @param {Object} args - 参数 { uid: 邮件UID, box?: 文件夹 }
167
+ * @returns {Promise<Object>} 操作结果
168
+ */
169
+ async function deleteEmail(emailPlugin, args) {
170
+ try {
171
+ const messageId = args.messageId || args.uid
172
+ if (!messageId) {
173
+ return {
174
+ success: false,
175
+ error: 'messageId 是必填参数'
176
+ }
177
+ }
178
+
179
+ const imapConfig = createImapConfig(args)
180
+ const box = args.box || 'INBOX'
181
+ await moveToTrash(imapConfig, box, messageId)
182
+
183
+ return {
184
+ success: true,
185
+ message: '邮件已删除'
186
+ }
187
+ } catch (error) {
188
+ return {
189
+ success: false,
190
+ error: error.message
191
+ }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * 获取邮箱配置信息
197
+ * @returns {Object} 配置信息
198
+ */
199
+ function getEmailConfig() {
200
+ return {
201
+ success: true,
202
+ message: '邮箱配置通过环境变量设置',
203
+ config: {
204
+ smtp_host: process.env.SMTP_HOST || 'smtp.gmail.com',
205
+ smtp_port: process.env.SMTP_PORT || 587,
206
+ smtp_secure: process.env.SMTP_SECURE || 'false',
207
+ imap_host: process.env.IMAP_HOST || 'imap.gmail.com',
208
+ imap_port: process.env.IMAP_PORT || 993,
209
+ from_email: process.env.FROM_EMAIL || '(未设置)',
210
+ client_name: process.env.IMAP_CLIENT_NAME || 'FolikoAgent',
211
+ client_version: process.env.IMAP_CLIENT_VERSION || '1.0.0'
212
+ }
213
+ }
214
+ }
215
+
216
+ // ============ 内部方法 ============
217
+
218
+ /**
219
+ * 获取邮件列表
220
+ */
221
+ function fetchEmails(imapConfig, box, limit, unreadOnly, searchCriteria) {
222
+ return new Promise((resolve, reject) => {
223
+ const imap = new Imap(imapConfig)
224
+ const emails = []
225
+
226
+ const cleanup = () => {
227
+ try { imap.end() } catch (e) {}
228
+ }
229
+
230
+ imap.on('ready', () => {
231
+ imap.openBox(box, true, (err) => {
232
+ if (err) {
233
+ cleanup()
234
+ return reject(err)
235
+ }
236
+
237
+ let searchFilter = searchCriteria
238
+ ? searchCriteria.split(' ').filter(Boolean)
239
+ : ['ALL']
240
+ if (unreadOnly) {
241
+ searchFilter = ['UNSEEN']
242
+ }
243
+
244
+ imap.search(searchFilter, (err, results) => {
245
+ if (err) {
246
+ cleanup()
247
+ return reject(err)
248
+ }
249
+
250
+ if (!results || results.length === 0) {
251
+ cleanup()
252
+ return resolve([])
253
+ }
254
+
255
+ const fetchIds = results.slice(-limit)
256
+ const f = imap.fetch(fetchIds, { bodies: '' })
257
+
258
+ f.on('message', (msg) => {
259
+ let email = {}
260
+ let bodyParsed = false
261
+ let uid = null // 在 attributes 事件中获取 UID
262
+
263
+ // 先获取 UID(比 body 更可靠)
264
+ msg.on('attributes', (attrs) => {
265
+ uid = attrs.uid
266
+ email.uid = uid
267
+ email.id = uid
268
+ email.flags = attrs.flags
269
+ })
270
+
271
+ msg.on('body', (stream) => {
272
+ simpleParser(stream).then(mail => {
273
+ // 确保 uid 已设置(如果 attributes 先触发)
274
+ if (!email.uid && uid) {
275
+ email.uid = uid
276
+ email.id = uid
277
+ }
278
+ email.subject = mail.subject
279
+ email.from = mail.from?.text || ''
280
+ email.to = mail.to?.text || ''
281
+ email.date = mail.date?.toISOString() || ''
282
+ email.text = mail.text || mail.textAsHtml || ''
283
+ email.html = mail.html
284
+ email.attachments = mail.attachments?.map(a => ({
285
+ filename: a.filename,
286
+ contentType: a.contentType
287
+ })) || []
288
+ bodyParsed = true
289
+ }).catch(err => {
290
+ email.error = err.message
291
+ bodyParsed = true
292
+ })
293
+ })
294
+
295
+ msg.on('end', () => {
296
+ const checkDone = () => {
297
+ if (bodyParsed) {
298
+ // 再次确保 uid 已设置
299
+ if (!email.uid && uid) {
300
+ email.uid = uid
301
+ email.id = uid
302
+ }
303
+ emails.push(email)
304
+ } else {
305
+ setTimeout(checkDone, 10)
306
+ }
307
+ }
308
+ checkDone()
309
+ })
310
+ })
311
+
312
+ f.on('error', (err) => {
313
+ cleanup()
314
+ reject(err)
315
+ })
316
+
317
+ f.on('end', () => {
318
+ // 添加超时保护,避免永久等待
319
+ const timeoutMs = 30000
320
+ const startTime = Date.now()
321
+
322
+ const waitForAll = () => {
323
+ if (emails.length === fetchIds.length) {
324
+ cleanup()
325
+ resolve(emails)
326
+ } else if (Date.now() - startTime > timeoutMs) {
327
+ cleanup()
328
+ resolve(emails) // 返回已获取的邮件
329
+ } else {
330
+ setTimeout(waitForAll, 50)
331
+ }
332
+ }
333
+ waitForAll()
334
+ })
335
+ })
336
+ })
337
+ })
338
+
339
+ imap.on('error', (err) => reject(err))
340
+ imap.on('end', () => {})
341
+
342
+ imap.connect()
343
+ })
344
+ }
345
+
346
+ /**
347
+ * 获取未读邮件数量
348
+ */
349
+ function fetchUnreadCount(imapConfig, box) {
350
+ return new Promise((resolve, reject) => {
351
+ const imap = new Imap(imapConfig)
352
+
353
+ const cleanup = () => {
354
+ try { imap.end() } catch (e) {}
355
+ }
356
+
357
+ imap.on('ready', () => {
358
+ imap.openBox(box, true, (err, boxObj) => {
359
+ if (err) {
360
+ cleanup()
361
+ return reject(err)
362
+ }
363
+ const unreadCount = boxObj.messages.unread
364
+ cleanup()
365
+ resolve(unreadCount)
366
+ })
367
+ })
368
+
369
+ imap.on('error', (err) => reject(err))
370
+ imap.on('end', () => {})
371
+
372
+ imap.connect()
373
+ })
374
+ }
375
+
376
+ /**
377
+ * 标记邮件为已读
378
+ * @param {Object} imapConfig - IMAP 配置
379
+ * @param {number|string} uid - 邮件 UID
380
+ */
381
+ function markEmailAsRead(imapConfig, uid) {
382
+ return new Promise((resolve, reject) => {
383
+ const imap = new Imap(imapConfig)
384
+
385
+ const cleanup = () => {
386
+ try { imap.end() } catch (e) {}
387
+ }
388
+
389
+ imap.on('ready', () => {
390
+ imap.openBox('INBOX', true, (err) => {
391
+ if (err) {
392
+ cleanup()
393
+ return reject(err)
394
+ }
395
+ imap.addFlags(uid, '\\Seen', (err) => {
396
+ cleanup()
397
+ if (err) reject(err)
398
+ else resolve()
399
+ })
400
+ })
401
+ })
402
+
403
+ imap.on('error', (err) => reject(err))
404
+ imap.on('end', () => {})
405
+
406
+ imap.connect()
407
+ })
408
+ }
409
+
410
+ /**
411
+ * 移动邮件到垃圾箱
412
+ * @param {Object} imapConfig - IMAP 配置
413
+ * @param {string} box - 邮箱文件夹
414
+ * @param {number|string} uid - 邮件 UID
415
+ */
416
+ function moveToTrash(imapConfig, box, uid) {
417
+ return new Promise((resolve, reject) => {
418
+ const imap = new Imap(imapConfig)
419
+
420
+ const cleanup = () => {
421
+ try { imap.end() } catch (e) {}
422
+ }
423
+
424
+ imap.on('ready', () => {
425
+ imap.openBox(box, true, (err) => {
426
+ if (err) {
427
+ cleanup()
428
+ return reject(err)
429
+ }
430
+ // 标记邮件为已删除
431
+ imap.addFlags(uid, '\\Deleted', (err) => {
432
+ if (err) {
433
+ cleanup()
434
+ return reject(err)
435
+ }
436
+ // 执行 expunge 永久删除
437
+ imap.expunge((err) => {
438
+ cleanup()
439
+ if (err) reject(err)
440
+ else resolve()
441
+ })
442
+ })
443
+ })
444
+ })
445
+
446
+ imap.on('error', (err) => reject(err))
447
+ imap.on('end', () => {})
448
+
449
+ imap.connect()
450
+ })
451
+ }
452
+
453
+ module.exports = {
454
+ sendEmail,
455
+ readEmails,
456
+ getUnreadCount,
457
+ markAsRead,
458
+ deleteEmail,
459
+ getEmailConfig,
460
+ createImapConfig
461
+ }