mocode-ai 1.8.7 → 1.8.8

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.
@@ -0,0 +1,804 @@
1
+ // 邮件远程介入(SMTP 发提醒 + IMAP 轮询回复)。
2
+ //
3
+ // 设计:
4
+ // - 本地能答就不碰邮箱:promptWithMail 先弹本地 TUI 面板;只有超过提醒阈值仍无人应答时,
5
+ // 才发一封带编号选项的提醒邮件并惰性启动 IMAP 轮询。本地先答则零网络连接。
6
+ // - 一封邮件 = 一个待决介入(pending Map,key=短 id)。用户回复数字=选中选项;
7
+ // 权限类只认 1=允许 / 2=拒绝,映射回本地化选项 label,与既有 prompt 契约零改动。
8
+ // - 发件人白名单:只接受配置邮箱(MOCODE_MAIL_FROM/USER)自己发来的回复,防第三方伪造放行。
9
+ // - best-effort:任何邮件/网络失败都不影响本地面板与主任务,仅放弃该远程通道。
10
+ // - 轮询定时器 .unref():不吊住进程退出;无待决介入时自动停止,不做无谓轮询。
11
+ import crypto from 'node:crypto';
12
+ import { promptIntervention, dismissActiveIntervention } from '../ui/intervention.js';
13
+ import { t } from '../i18n/index.js';
14
+ function numEnv(key, fallback) {
15
+ const n = Number(process.env[key]);
16
+ return Number.isFinite(n) && n > 0 ? n : fallback;
17
+ }
18
+ let cached;
19
+ /** 读取邮件配置。必填项(SMTP/IMAP host、账号、密码、收件人)缺失即视为未启用。 */
20
+ export function getMailConfig() {
21
+ if (cached !== undefined)
22
+ return applyEnabled(cached);
23
+ const user = (process.env.MOCODE_MAIL_USER ?? '').trim();
24
+ const pass = (process.env.MOCODE_MAIL_PASS ?? '').trim();
25
+ const smtpHost = (process.env.MOCODE_SMTP_HOST ?? '').trim();
26
+ const imapHost = (process.env.MOCODE_IMAP_HOST ?? '').trim();
27
+ const to = (process.env.MOCODE_MAIL_TO ?? user).trim();
28
+ const ready = !!user && !!pass && !!smtpHost && !!imapHost && !!to;
29
+ const cfg = ready
30
+ ? {
31
+ enabled: true,
32
+ idleMs: numEnv('MOCODE_MAIL_IDLE_MS', 60_000),
33
+ pollMs: numEnv('MOCODE_MAIL_POLL_MS', 15_000),
34
+ smtpHost,
35
+ smtpPort: numEnv('MOCODE_SMTP_PORT', 465),
36
+ smtpSecure: process.env.MOCODE_SMTP_SECURE !== 'false',
37
+ imapHost,
38
+ imapPort: numEnv('MOCODE_IMAP_PORT', 993),
39
+ imapSecure: process.env.MOCODE_IMAP_SECURE !== 'false',
40
+ user,
41
+ pass,
42
+ to,
43
+ }
44
+ : null;
45
+ cached = cfg;
46
+ return applyEnabled(cfg);
47
+ }
48
+ /** MOCODE_MAIL_ENABLED=false 时即便凭据完整也不启用。 */
49
+ function applyEnabled(cfg) {
50
+ if (!cfg)
51
+ return null;
52
+ return process.env.MOCODE_MAIL_ENABLED === 'false' ? null : cfg;
53
+ }
54
+ /** 测试/重配置用:清空 env 缓存(/mail on|off 改 env 后调用)。 */
55
+ export function resetMailConfigCache() {
56
+ cached = undefined;
57
+ }
58
+ /**
59
+ * 忽略启用开关,只看凭据是否完整(/mail test 与状态展示用):
60
+ * 返回 {cfg: 完整凭据, enabled: 开关是否打开}。凭据缺失 cfg=null。
61
+ */
62
+ export function getMailStatus() {
63
+ resetMailConfigCache();
64
+ const enabledCfg = getMailConfig();
65
+ if (enabledCfg)
66
+ return { cfg: enabledCfg, enabled: true };
67
+ // 被开关关掉时 getMailConfig 返 null,临时放开探测凭据是否其实完整。
68
+ const saved = process.env.MOCODE_MAIL_ENABLED;
69
+ delete process.env.MOCODE_MAIL_ENABLED;
70
+ resetMailConfigCache();
71
+ const probe = getMailConfig();
72
+ if (saved === undefined)
73
+ delete process.env.MOCODE_MAIL_ENABLED;
74
+ else
75
+ process.env.MOCODE_MAIL_ENABLED = saved;
76
+ resetMailConfigCache();
77
+ return { cfg: probe, enabled: false };
78
+ }
79
+ const pending = new Map();
80
+ function newId() {
81
+ return crypto.randomBytes(4).toString('hex').toUpperCase(); // 8 位十六进制,如 A1B2C3D4
82
+ }
83
+ // ── 邮件正文 / 主题 ─────────────────────────────────────────────────────────
84
+ /** 主题前缀,回复解析靠它定位待决介入。 */
85
+ export const MAIL_SUBJECT_PREFIX = '[mocode]';
86
+ /**
87
+ * 提醒邮件的机器可读首行标记。163/Coremail 会改写 Message-ID,没法靠 header 认出
88
+ * "提醒自己",故用这行固定标记(含介入编号)在轮询里识别并跳过。
89
+ * 用户真实回复不会以此开头;标记与语言无关,中英文界面都不会误判。
90
+ */
91
+ function reminderMark(id) {
92
+ return `[mocode-intervention: ${id}]`;
93
+ }
94
+ /** 本地时间 "YYYY-MM-DD HH:mm"(邮件里给人看,不带时区噪声)。 */
95
+ function formatTime(d) {
96
+ const pad = (n) => String(n).padStart(2, '0');
97
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
98
+ }
99
+ export function buildSubject(title) {
100
+ const oneLine = title.replace(/\s+/g, ' ').trim().slice(0, 60);
101
+ const tag = t('mail.subjectTag');
102
+ // 主题不带介入编号:编号对用户没有信息量,且会顶在标题最显眼处。
103
+ // 回复归属改由 In-Reply-To(提醒真实 Message-ID)/正文引用/单待决兜底判定。
104
+ return `${MAIL_SUBJECT_PREFIX} ${tag} · ${oneLine}`.trim();
105
+ }
106
+ /**
107
+ * 构造提醒邮件正文(纯文本,兼作邮件客户端的降级展示)。
108
+ * 分段式排版:问题 / 背景 / 选项 / 怎么回复 / 其他信息,让用户在手机上也能一眼看懂。
109
+ * 编号与面板选项顺序一致(含权限面板,故 1=允许一次、末项=拒绝)。
110
+ */
111
+ export function buildBody(cfg, p) {
112
+ const options = optionPairs(p.req);
113
+ const idle = Math.max(1, Math.round(cfg.idleMs / 1000));
114
+ const lines = [];
115
+ lines.push(reminderMark(p.id));
116
+ lines.push('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
117
+ lines.push(` ${t('mail.bodyTitle')}`);
118
+ lines.push('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
119
+ lines.push('');
120
+ lines.push(t('mail.bodyIntro', { idle }));
121
+ lines.push('');
122
+ lines.push(`■ ${t('mail.bodyProblem')}`);
123
+ for (const l of p.req.title.split(/\r?\n/))
124
+ lines.push(` ${l}`);
125
+ if (p.req.detail && p.req.detail.trim()) {
126
+ lines.push('');
127
+ lines.push(`■ ${t('mail.bodyBackground')}`);
128
+ for (const l of p.req.detail.split(/\r?\n/))
129
+ lines.push(` ${l}`);
130
+ }
131
+ if (options.length > 0) {
132
+ lines.push('');
133
+ lines.push(`■ ${t('mail.bodyOptions')}`);
134
+ for (let i = 0; i < options.length; i++) {
135
+ const { label, detail } = options[i];
136
+ lines.push(` ${i + 1}. ${label}`);
137
+ // 选项详情(取舍/含义)单独缩进一行,让用户不看终端也能凭邮件做决定。
138
+ if (detail)
139
+ lines.push(` ${detail}`);
140
+ }
141
+ }
142
+ lines.push('');
143
+ lines.push(`■ ${t('mail.bodyReply')}`);
144
+ const reply = options.length > 0
145
+ ? t('mail.bodyReplyChoice', { example: '1', marker: MAIL_SUBJECT_PREFIX })
146
+ : t('mail.bodyReplyInput');
147
+ for (const l of reply.split('\n'))
148
+ lines.push(` ${l}`);
149
+ lines.push('');
150
+ lines.push(`■ ${t('mail.bodyMeta')}`);
151
+ lines.push(` ${t('mail.bodyMetaId')}: ${p.id}`);
152
+ lines.push(` ${t('mail.bodyMetaCwd')}: ${process.cwd()}`);
153
+ lines.push(` ${t('mail.bodyMetaTime')}: ${formatTime(new Date())}`);
154
+ lines.push('');
155
+ lines.push(t('mail.bodyTrusted', { to: cfg.to }));
156
+ lines.push(t('mail.bodyFooter'));
157
+ return lines.join('\n');
158
+ }
159
+ /** HTML 转义:标题/详情/选项都来自模型,绝不能原样塞进邮件 HTML。 */
160
+ function escapeHtml(s) {
161
+ return s
162
+ .replace(/&/g, '&amp;')
163
+ .replace(/</g, '&lt;')
164
+ .replace(/>/g, '&gt;')
165
+ .replace(/"/g, '&quot;')
166
+ .replace(/'/g, '&#39;');
167
+ }
168
+ /**
169
+ * 构造 HTML 版提醒邮件(网页/手机客户端优先渲染这版,纯文本作为降级)。
170
+ * 只用行内样式 + table 布局:邮件客户端普遍不支持 <style>/flex/grid。
171
+ */
172
+ export function buildHtmlBody(cfg, p) {
173
+ const options = optionPairs(p.req);
174
+ const idle = Math.max(1, Math.round(cfg.idleMs / 1000));
175
+ const esc = escapeHtml;
176
+ const sectionLabel = (text) => `<div style="font-size:12px;letter-spacing:.06em;color:#6b7280;margin:0 0 8px">${esc(text)}</div>`;
177
+ const optionRows = options
178
+ .map((o, i) => {
179
+ const detail = o.detail
180
+ ? `<div style="font-size:13px;line-height:1.6;color:#6b7280;margin-top:4px">${esc(o.detail)}</div>`
181
+ : '';
182
+ return `<tr>
183
+ <td style="vertical-align:top;padding:10px 12px;border-top:1px solid #f1f5f9;width:44px">
184
+ <span style="display:inline-block;width:24px;height:24px;line-height:24px;text-align:center;border-radius:12px;background:#eef2ff;color:#4338ca;font-size:13px;font-weight:600">${i + 1}</span>
185
+ </td>
186
+ <td style="vertical-align:top;padding:10px 12px 10px 0;border-top:1px solid #f1f5f9">
187
+ <div style="font-size:14px;font-weight:600;color:#111827;line-height:1.5">${esc(o.label)}</div>
188
+ ${detail}
189
+ </td>
190
+ </tr>`;
191
+ })
192
+ .join('');
193
+ const replyBox = options.length > 0
194
+ ? `<div style="background:#eef2ff;border:1px solid #e0e7ff;border-radius:10px;padding:14px 16px;margin:22px 0 0">
195
+ <div style="font-size:13px;font-weight:600;color:#3730a3;margin-bottom:6px">${esc(t('mail.bodyReply'))}</div>
196
+ <div style="font-size:13px;line-height:1.8;color:#374151">${esc(t('mail.htmlReplyChoice', { marker: MAIL_SUBJECT_PREFIX }))}</div>
197
+ <div style="margin-top:10px;font-family:Consolas,Menlo,monospace;font-size:20px;font-weight:700;color:#4338ca;background:#ffffff;border:1px dashed #c7d2fe;border-radius:8px;padding:8px 14px;display:inline-block">1</div>
198
+ </div>`
199
+ : `<div style="background:#eef2ff;border:1px solid #e0e7ff;border-radius:10px;padding:14px 16px;margin:22px 0 0">
200
+ <div style="font-size:13px;font-weight:600;color:#3730a3;margin-bottom:6px">${esc(t('mail.bodyReply'))}</div>
201
+ <div style="font-size:13px;line-height:1.8;color:#374151">${esc(t('mail.bodyReplyInput'))}</div>
202
+ </div>`;
203
+ const detailBlock = p.req.detail?.trim()
204
+ ? `<div style="margin:0 0 20px">
205
+ ${sectionLabel(t('mail.bodyBackground'))}
206
+ <div style="font-size:14px;line-height:1.8;color:#374151;white-space:pre-wrap">${esc(p.req.detail)}</div>
207
+ </div>`
208
+ : '';
209
+ const optionsBlock = options.length > 0
210
+ ? `<div style="margin:0 0 4px">
211
+ ${sectionLabel(t('mail.bodyOptions'))}
212
+ <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;background:#ffffff">${optionRows}</table>
213
+ </div>`
214
+ : '';
215
+ return `<!doctype html>
216
+ <html><body style="margin:0;padding:24px 12px;background:#f3f4f6">
217
+ <div style="max-width:640px;margin:0 auto;font-family:-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,'PingFang SC','Microsoft YaHei',sans-serif;background:#ffffff;border:1px solid #e5e7eb;border-radius:14px;overflow:hidden">
218
+ <div style="background:#111827;padding:18px 24px">
219
+ <div style="font-size:11px;letter-spacing:.18em;color:#9ca3af">MOCODE</div>
220
+ <div style="font-size:19px;font-weight:600;color:#ffffff;margin-top:4px">${esc(t('mail.htmlTitle'))}</div>
221
+ </div>
222
+ <div style="padding:24px 24px 22px">
223
+ <div style="font-size:15px;line-height:1.75;color:#374151;margin:0 0 20px">${esc(t('mail.bodyIntro', { idle }))}</div>
224
+ <div style="background:#f9fafb;border-left:3px solid #6366f1;border-radius:0 8px 8px 0;padding:14px 16px;margin:0 0 20px">
225
+ ${sectionLabel(t('mail.bodyProblem'))}
226
+ <div style="font-size:17px;font-weight:600;line-height:1.5;color:#111827">${esc(p.req.title)}</div>
227
+ </div>
228
+ ${detailBlock}
229
+ ${optionsBlock}
230
+ ${replyBox}
231
+ <div style="border-top:1px solid #e5e7eb;margin:22px 0 14px"></div>
232
+ <table role="presentation" cellpadding="0" cellspacing="0" width="100%">
233
+ <tr><td style="font-size:12px;color:#9ca3af;padding:2px 0">${esc(t('mail.bodyMetaId'))}</td><td style="font-size:12px;color:#6b7280;padding:2px 0;text-align:right;font-family:Consolas,Menlo,monospace">${esc(p.id)}</td></tr>
234
+ <tr><td style="font-size:12px;color:#9ca3af;padding:2px 0">${esc(t('mail.bodyMetaCwd'))}</td><td style="font-size:12px;color:#6b7280;padding:2px 0;text-align:right;word-break:break-all">${esc(process.cwd())}</td></tr>
235
+ <tr><td style="font-size:12px;color:#9ca3af;padding:2px 0">${esc(t('mail.bodyMetaTime'))}</td><td style="font-size:12px;color:#6b7280;padding:2px 0;text-align:right">${esc(formatTime(new Date()))}</td></tr>
236
+ </table>
237
+ <div style="font-size:11px;color:#9ca3af;line-height:1.8;margin-top:12px">${esc(t('mail.bodyTrusted', { to: cfg.to }))}<br>${esc(t('mail.bodyFooter'))}</div>
238
+ </div>
239
+ </div>
240
+ </body></html>`;
241
+ }
242
+ /** 选项的 label + 可选详情(choice 用);字符串选项或 input 模式无详情。 */
243
+ export function optionPairs(req) {
244
+ if (req.type !== 'choice' || !Array.isArray(req.options))
245
+ return [];
246
+ const out = [];
247
+ for (const o of req.options) {
248
+ if (typeof o === 'string') {
249
+ const label = o.trim();
250
+ if (label)
251
+ out.push({ label });
252
+ }
253
+ else {
254
+ const label = (o?.label ?? '').trim();
255
+ if (!label)
256
+ continue;
257
+ const detail = o?.detail?.trim();
258
+ out.push(detail ? { label, detail } : { label });
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+ /** 把 InterventionRequest.options 归一为 label 字符串数组(choice 用);input 返 []。 */
264
+ export function normalizedOptions(req) {
265
+ return optionPairs(req).map((o) => o.label);
266
+ }
267
+ // ── SMTP 发送 ───────────────────────────────────────────────────────────────
268
+ /** 生成提醒邮件的确定性 Message-ID(无尖括号),便于轮询识别并跳过自发自收的提醒本身。 */
269
+ function selfMessageId(id, user) {
270
+ const domain = user.includes('@') ? user.split('@')[1] : 'localhost';
271
+ return `mocode-${id.toLowerCase()}@${domain}`;
272
+ }
273
+ /** 归一化 Message-ID:去尖括号/空白、转小写。 */
274
+ function normMessageId(raw) {
275
+ return (raw ?? '')
276
+ .trim()
277
+ .replace(/^<+|>+$/g, '')
278
+ .toLowerCase();
279
+ }
280
+ async function sendMail(cfg, subject, text, messageId, html) {
281
+ const nodemailer = await import('nodemailer');
282
+ const transporter = nodemailer.createTransport({
283
+ host: cfg.smtpHost,
284
+ port: cfg.smtpPort,
285
+ secure: cfg.smtpSecure,
286
+ auth: { user: cfg.user, pass: cfg.pass },
287
+ // 连接/发送各 10s 超时,避免挂死主任务的 Promise 竞态。
288
+ connectionTimeout: 10_000,
289
+ greetingTimeout: 10_000,
290
+ socketTimeout: 15_000,
291
+ });
292
+ try {
293
+ await transporter.sendMail({
294
+ from: cfg.user,
295
+ to: cfg.to,
296
+ subject,
297
+ text,
298
+ // 同时给 text + html:客户端优先渲染 HTML,不支持时自动降级到纯文本。
299
+ ...(html ? { html } : {}),
300
+ // 显式钉死 Message-ID(加回尖括号):保留自定义 Message-ID 的服务端可据此识别
301
+ // "提醒本身";163 会改写它,故另有 isSelfReminder 正文标记兜底。
302
+ messageId: `<${messageId}>`,
303
+ });
304
+ }
305
+ finally {
306
+ transporter.close();
307
+ }
308
+ }
309
+ /**
310
+ * 只解析"用户想要什么"(编号或自由文本),不关心属于哪一次介入。
311
+ * 归属由 resolvePending 依据主题/引用头/正文编号/单待决兜底判定。
312
+ */
313
+ export function parseIntent(body, optionCount) {
314
+ const cleaned = firstReplyLine(body);
315
+ const numMatch = /^(\d{1,2})\b/.exec(cleaned);
316
+ const option = numMatch ? Number(numMatch[1]) : 0;
317
+ if (optionCount > 0 && option >= 1)
318
+ return { kind: 'choice', option, text: '' };
319
+ if (optionCount === 0 && cleaned)
320
+ return { kind: 'text', option: 0, text: cleaned };
321
+ return null;
322
+ }
323
+ /**
324
+ * 从回复邮件的主题 + 正文解析介入编号与意图。
325
+ * - 主题优先匹配 [mocode] <ID>(兼容旧版提醒);缺失时从正文找"介入编号: XXXX"。
326
+ * - 选项:正文首个有效 token 是数字;自由文本取正文首行。
327
+ * 无法解析出 id 返 null。
328
+ */
329
+ export function parseReply(subject, body, optionCount) {
330
+ const subjectMatch = new RegExp(`${escapeRegExp(MAIL_SUBJECT_PREFIX)}\\s*([0-9A-Fa-f]{8})`, 'i').exec(subject ?? '');
331
+ let id = subjectMatch?.[1]?.toUpperCase();
332
+ if (!id) {
333
+ const bodyMatch = /(?:介入编号|ID)\s*[::]?\s*([0-9A-Fa-f]{8})/i.exec(body ?? '');
334
+ id = bodyMatch?.[1]?.toUpperCase();
335
+ }
336
+ if (!id)
337
+ return null;
338
+ const intent = parseIntent(body, optionCount);
339
+ if (!intent)
340
+ return null;
341
+ return { id, ...intent };
342
+ }
343
+ /**
344
+ * 判定一封回复属于哪个待决介入。顺序(强 → 弱):
345
+ * 1. 主题里的旧式编号 `[mocode] <ID>`(兼容历史提醒邮件);
346
+ * 2. In-Reply-To / References 命中提醒的 Message-ID(可能是服务端改写后的真实 ID);
347
+ * 3. 正文引用了"介入编号: XXXX"(客户端把原文引用下来时);
348
+ * 4. 只有一个待决介入 → 就是它(绝大多数场景:agent 被该介入阻塞)。
349
+ * 无法唯一确定时返 null,宁可不处理也不猜错选项。
350
+ */
351
+ export function resolvePending(pendings, meta) {
352
+ const subjectId = new RegExp(`${escapeRegExp(MAIL_SUBJECT_PREFIX)}\\s*([0-9A-Fa-f]{8})\\b`, 'i')
353
+ .exec(meta.subject ?? '')?.[1]
354
+ ?.toUpperCase();
355
+ if (subjectId)
356
+ return pendings.find((p) => p.id === subjectId) ?? null;
357
+ const refs = new Set();
358
+ for (const raw of [meta.inReplyTo, ...(meta.references ?? [])]) {
359
+ const n = normMessageId(raw);
360
+ if (n)
361
+ refs.add(n);
362
+ }
363
+ if (refs.size > 0) {
364
+ const hit = pendings.find((p) => (!!p.actualMessageId && refs.has(p.actualMessageId)) || (!!p.selfMessageId && refs.has(p.selfMessageId)));
365
+ if (hit)
366
+ return hit;
367
+ }
368
+ const bodyId = /(?:介入编号|ID)\s*[::]\s*([0-9A-Fa-f]{8})\b/i.exec(meta.body ?? '')?.[1]?.toUpperCase();
369
+ if (bodyId)
370
+ return pendings.find((p) => p.id === bodyId) ?? null;
371
+ return pendings.length === 1 ? pendings[0] : null;
372
+ }
373
+ /**
374
+ * 从回复正文里取"用户真正写的第一行"。网页/客户端回复会自动带上原文引用块
375
+ * (">" 行、"在 ... 写道:"、"发件人:"、"原邮件"、签名分隔 "-- ")。
376
+ * 规则:
377
+ * - 行首引用符 ">" 先剥掉;纯选项数字(如 "> 1")即便在引用行里也采信——
378
+ * 很多手机端回复会把光标放进引用块里写数字;
379
+ * - 文字行若原本带 ">"(引用块里的原文)则跳过,避免把原问题当自由文本回复;
380
+ * - 邮件头/署名等噪声行一律跳过。
381
+ */
382
+ export function firstReplyLine(body) {
383
+ const noise = /^(?:在[^。\n]{0,80}(?:写道|wrote):|"[^"]*"\s*<[^>]*>\s*(?:写道|wrote):|发件人[::]|收件人[::]|主题[::]|时间[::]|日期[::]|date:|from:|to:|subject:|sent:|-{2,}$|_{3,}$|原邮件|原始邮件|回复:?$|re:?$)/i;
384
+ for (const raw of (body ?? '').split(/\r?\n/)) {
385
+ const wasQuoted = /^\s*>/.test(raw);
386
+ const line = raw.replace(/^[>\s]+/, '').trim();
387
+ if (!line)
388
+ continue;
389
+ if (noise.test(line))
390
+ continue;
391
+ // 纯选项数字(可带 ". "、")" 等标点):无论是否在引用块里都采信。
392
+ const digits = /^(\d{1,2})/.exec(line);
393
+ if (digits && /^\d{1,2}[\s.。::)]*$/.test(line))
394
+ return digits[1];
395
+ // 自由文本:只采信用户自己写的非引用行。
396
+ if (!wasQuoted)
397
+ return line;
398
+ }
399
+ return '';
400
+ }
401
+ function escapeRegExp(s) {
402
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
403
+ }
404
+ /** 发件人是否为受信地址(白名单 = 配置的收件邮箱本身,大小写不敏感)。 */
405
+ function isTrustedSender(from, cfg) {
406
+ if (!from)
407
+ return false;
408
+ const addr = extractAddress(from).toLowerCase();
409
+ return addr === cfg.to.toLowerCase() || addr === cfg.user.toLowerCase();
410
+ }
411
+ /** 从 "Name <a@b.com>" 或裸地址里取出邮箱部分。 */
412
+ export function extractAddress(raw) {
413
+ const m = /<([^>]+)>/.exec(raw);
414
+ return (m ? m[1] : raw).trim();
415
+ }
416
+ /**
417
+ * 这封邮件是不是我们自己发出的提醒(回投到收件箱)而不是用户回复?
418
+ * - 正文首个非空行(允许被引用的 ">")是 `[mocode-intervention: <ID>]` 标记。
419
+ * 用户回复只会以自己写的内容开头,不会被误判;标记与语言无关,对 163(改写
420
+ * Message-ID)同样有效。公开以便单元测试。
421
+ */
422
+ export function isSelfReminder(p, body) {
423
+ const first = (body ?? '')
424
+ .split(/\r?\n/)
425
+ .map((l) => l.replace(/^[>\s]+/, '').trim())
426
+ .find((l) => l.length > 0);
427
+ return !!first && first.includes(reminderMark(p.id));
428
+ }
429
+ // ── IMAP 轮询 ───────────────────────────────────────────────────────────────
430
+ let pollTimer = null;
431
+ let polling = false;
432
+ /** 惰性启动轮询:已有定时器或无待决介入时不重复启动。 */
433
+ function ensurePolling() {
434
+ const cfg = getMailConfig();
435
+ if (!cfg || pollTimer)
436
+ return;
437
+ const timer = setInterval(() => {
438
+ void pollOnce().catch(() => { });
439
+ }, cfg.pollMs);
440
+ timer.unref?.(); // 关键:不吊住进程退出(对齐 idle-guard 教训)
441
+ pollTimer = timer;
442
+ void pollOnce().catch(() => { }); // 立即先查一次
443
+ }
444
+ /** 无待决介入时停止轮询(全部应答/取消后回收句柄)。 */
445
+ function stopPollingIfIdle() {
446
+ if (pollTimer && pending.size === 0) {
447
+ clearInterval(pollTimer);
448
+ pollTimer = null;
449
+ }
450
+ }
451
+ /** 同步停止(退出钩子用):清定时器。IMAP 客户端为每轮短连接,无需额外关闭。 */
452
+ export function stopMailPollerSync() {
453
+ if (pollTimer) {
454
+ clearInterval(pollTimer);
455
+ pollTimer = null;
456
+ }
457
+ }
458
+ /** 邮件 IMAP 连接工厂(与 /mail test 同参数)。 */
459
+ function connectImap(cfg) {
460
+ let ctor;
461
+ return import('imapflow').then(({ ImapFlow }) => {
462
+ ctor = ImapFlow;
463
+ const client = new ctor({
464
+ host: cfg.imapHost,
465
+ port: cfg.imapPort,
466
+ secure: cfg.imapSecure,
467
+ auth: { user: cfg.user, pass: cfg.pass },
468
+ logger: false,
469
+ tls: { rejectUnauthorized: true },
470
+ });
471
+ return client.connect().then(() => client);
472
+ });
473
+ }
474
+ /**
475
+ * 读取 INBOX 当前**最高一封邮件的 UID**(空邮箱返 0),作为水位基线。
476
+ * 不依赖 STATUS uidNext——163 邮箱实测 STATUS/SELECT 都不返回 uidNext(只给
477
+ * messages/unseen),改用 IMAP `UID SEARCH *`(`search({uid:'*'}, {uid:true})`),
478
+ * 各主流服务端都支持。必须在已 open/lock INBOX 的连接上调用。
479
+ */
480
+ async function fetchHighestUid(client) {
481
+ try {
482
+ const r = await client.search({ uid: '*' }, { uid: true });
483
+ const last = Array.isArray(r) ? r[r.length - 1] : undefined;
484
+ return typeof last === 'number' && Number.isFinite(last) ? last : 0;
485
+ }
486
+ catch {
487
+ return 0;
488
+ }
489
+ }
490
+ /**
491
+ * 自管理短连接地 best-effort 预取一次"发信前最高 UID"(用于精确设定水位,
492
+ * 把自发自收的提醒自身排除:水位 = 当前最高,提醒自身 UID > 水位时才被处理,
493
+ * 而它发出后下一轮水位会先被它推进——因此实际靠"发信前快照 + 下轮增量"语义)。
494
+ * 任何失败/超时都静默返 0,绝不阻断发信。
495
+ */
496
+ async function probeHighestUidBestEffort(cfg) {
497
+ // 连接/查询放在独立 IIFE 里:超时只是放弃等待,后台任务自己收尾(lock/logout),
498
+ // 故 client 句柄不跨 await 暴露给外层,避免类型窄化与悬挂连接。
499
+ const attempt = (async () => {
500
+ let client = null;
501
+ try {
502
+ client = await connectImap(cfg);
503
+ const lock = await client.getMailboxLock('INBOX');
504
+ try {
505
+ return await fetchHighestUid(client);
506
+ }
507
+ finally {
508
+ lock.release();
509
+ }
510
+ }
511
+ finally {
512
+ await client?.logout().catch(() => { });
513
+ }
514
+ })();
515
+ attempt.catch(() => { }); // 超时后后台任务若最终失败,不要变成 unhandled rejection
516
+ const timeout = new Promise((resolve) => {
517
+ const t = setTimeout(() => resolve(0), 8000);
518
+ t.unref?.();
519
+ });
520
+ try {
521
+ const highest = await Promise.race([attempt, timeout]);
522
+ return Number.isFinite(highest) && highest > 0 ? highest : 0;
523
+ }
524
+ catch {
525
+ return 0;
526
+ }
527
+ }
528
+ let lastPoll = { at: 0, highest: 0, candidates: 0, handled: 0, skipped: null, error: null };
529
+ /** 只读诊断快照:让用户在 TUI 里看到"轮询有没有真的在跑、跑到哪一步"。 */
530
+ export function getMailPollState() {
531
+ return lastPoll;
532
+ }
533
+ /** 当前待决介入数(/mail 状态页展示;>0 才会有轮询在跑)。 */
534
+ export function pendingInterventionCount() {
535
+ return pending.size;
536
+ }
537
+ /**
538
+ * 列出本轮要检查的候选 UID(升序),取所有待决介入的公共下界。
539
+ * - 水位全部已知:直接 `UID SEARCH <min(watermark)+1>:*`,无时间上限,晚几天的回复也能收。
540
+ * - 任一水位未知(发信前预取失败):退化为"最早发信日回溯 1 天"的日期搜索,
541
+ * 绝不把 watermark 直接设成当前最高——那会把发信后立刻到达的回复永久跳过。
542
+ */
543
+ async function candidateUids(client, list) {
544
+ const watermarks = list.map((p) => p.watermark);
545
+ const known = watermarks.every((w) => w > 0);
546
+ const query = known
547
+ ? { uid: `${Math.min(...watermarks) + 1}:*` }
548
+ : { since: new Date(Math.min(...list.map((p) => p.sentAt)) - 24 * 3600_000) };
549
+ const found = await client.search(query, { uid: true });
550
+ const uids = Array.isArray(found) ? found : [];
551
+ const floor = known ? Math.min(...watermarks) : 0;
552
+ return uids
553
+ .filter((n) => typeof n === 'number' && Number.isFinite(n) && n > floor)
554
+ .sort((a, b) => a - b);
555
+ }
556
+ async function pollOnce() {
557
+ const cfg = getMailConfig();
558
+ if (!cfg || polling || pending.size === 0)
559
+ return;
560
+ polling = true;
561
+ const state = { at: Date.now(), highest: 0, candidates: 0, handled: 0, skipped: null, error: null };
562
+ lastPoll = state;
563
+ try {
564
+ const { simpleParser } = await import('mailparser');
565
+ const client = await connectImap(cfg);
566
+ try {
567
+ const lock = await client.getMailboxLock('INBOX');
568
+ try {
569
+ // 当前最高 UID(163 不支持 STATUS uidNext,用 UID SEARCH * 取)。
570
+ const highest = await fetchHighestUid(client);
571
+ state.highest = highest;
572
+ if (highest <= 0)
573
+ return; // 空邮箱或服务端异常:本轮无可拉取,下轮重试。
574
+ // 全局扫一遍候选:一封回复只处理一次,归属靠 resolvePending 判定。
575
+ const list = [...pending.values()];
576
+ const uids = await candidateUids(client, list);
577
+ state.candidates = uids.length;
578
+ for (const uid of uids) {
579
+ // 单封按 UID 取(第三参 { uid: true } 不可省,否则 range 被当序列号)。
580
+ const fetched = await client.fetchOne(String(uid), { source: true }, { uid: true }).catch(() => null);
581
+ if (!fetched || !fetched.source)
582
+ continue;
583
+ let parsed;
584
+ try {
585
+ parsed = await simpleParser(fetched.source);
586
+ }
587
+ catch {
588
+ state.skipped = 'parse';
589
+ continue; // 不推进水位:下轮重试这封,别把不可解析的邮件当已处理
590
+ }
591
+ // 解析成功才推进水位:这封已纳入判断,下轮不再重复拉取。
592
+ for (const q of pending.values())
593
+ q.watermark = Math.max(q.watermark, uid);
594
+ const from = Array.isArray(parsed.from) ? parsed.from[0]?.text : parsed.from?.text;
595
+ if (!isTrustedSender(from, cfg)) {
596
+ state.skipped = 'sender';
597
+ continue;
598
+ }
599
+ const subject = parsed.subject ?? '';
600
+ const body = (parsed.text ?? '').trim();
601
+ // 先认"提醒自己的副本":命中则记下服务端改写后的真实 Message-ID
602
+ // (用户回复的 In-Reply-To 指向它),并跳过,绝不当成用户答复。
603
+ const owner = [...pending.values()].find((q) => (!!q.selfMessageId && normMessageId(parsed.messageId) === q.selfMessageId) || isSelfReminder(q, body));
604
+ if (owner) {
605
+ if (!owner.actualMessageId)
606
+ owner.actualMessageId = normMessageId(parsed.messageId) || null;
607
+ state.skipped = 'self';
608
+ continue;
609
+ }
610
+ const refs = (Array.isArray(parsed.references) ? parsed.references : [parsed.references]).filter((r) => typeof r === 'string');
611
+ const meta = { subject, body, inReplyTo: parsed.inReplyTo ?? null, references: refs };
612
+ const target = resolvePending([...pending.values()], meta);
613
+ if (!target) {
614
+ // 多个待决介入且无法归属:宁可不动,也不猜错选项。
615
+ state.skipped = 'ambiguous';
616
+ continue;
617
+ }
618
+ if (routeReply(target, body)) {
619
+ state.handled++;
620
+ await client.messageFlagsAdd(String(uid), ['\\Seen'], { uid: true }).catch(() => { });
621
+ }
622
+ }
623
+ }
624
+ finally {
625
+ lock.release();
626
+ }
627
+ }
628
+ finally {
629
+ await client.logout().catch(() => { });
630
+ }
631
+ }
632
+ catch (e) {
633
+ // 以前这里静默吞错,导致"邮件到了却什么都不发生"。留痕到诊断快照,便于 /mail 查看。
634
+ state.error = e instanceof Error ? e.message : String(e);
635
+ }
636
+ finally {
637
+ polling = false;
638
+ stopPollingIfIdle();
639
+ }
640
+ }
641
+ /**
642
+ * 尝试用一封回复满足指定待决介入。命中并 resolve 返 true。
643
+ * 归属由 resolvePending 决定,这里只把正文解析成意图(编号/自由文本)。
644
+ */
645
+ function routeReply(p, body) {
646
+ const intent = parseIntent(body, normalizedOptions(p.req).length);
647
+ if (!intent)
648
+ return false;
649
+ const result = toInterventionResult(p, intent);
650
+ if (!result)
651
+ return false; // 越界选项:忽略,继续等待有效回复
652
+ pending.delete(p.id);
653
+ p.settled(result);
654
+ // 邮件到达时若本地面板仍开着,等价于用户在面板上做了同一选择,收起它。
655
+ dismissActiveIntervention(result);
656
+ return true;
657
+ }
658
+ /** ReplyIntent → InterventionResult;choice 越界返 null。 */
659
+ function toInterventionResult(p, intent) {
660
+ if (intent.kind === 'text') {
661
+ return { action: 'submitted', value: intent.text };
662
+ }
663
+ const options = normalizedOptions(p.req);
664
+ const label = options[intent.option - 1];
665
+ if (!label)
666
+ return null;
667
+ return { action: 'selected', value: label };
668
+ }
669
+ // ── 中介:本地面板 + 超时邮件,先应答者胜 ───────────────────────────────────
670
+ /**
671
+ * 弹本地介入面板;若 idleMs 内无人应答,发提醒邮件并启动 IMAP 轮询。
672
+ * 本地按键与邮件回复谁先到用谁,后到者被 settled 守卫忽略。邮件未配置/发送失败时
673
+ * 退化为纯本地面板(行为等同 promptIntervention)。
674
+ */
675
+ export function promptWithMail(req) {
676
+ const cfg = getMailConfig();
677
+ // 未配置邮件:直接走原面板,零额外行为。
678
+ if (!cfg)
679
+ return promptIntervention(req);
680
+ const id = newId();
681
+ let timer = null;
682
+ let settled = false;
683
+ const p = {
684
+ id,
685
+ req,
686
+ watermark: 0,
687
+ sentAt: Date.now(),
688
+ selfMessageId: null,
689
+ actualMessageId: null,
690
+ settled: () => { },
691
+ };
692
+ const result = new Promise((resolve) => {
693
+ const finish = (r) => {
694
+ if (settled)
695
+ return;
696
+ settled = true;
697
+ if (timer)
698
+ clearTimeout(timer);
699
+ pending.delete(id);
700
+ stopPollingIfIdle();
701
+ resolve(r);
702
+ };
703
+ p.settled = finish;
704
+ // 本地面板:用户按键 → finish;我们 race 它。
705
+ const local = promptIntervention(req).then((r) => finish(r));
706
+ // 超时仍未决 → 取 UID 水位 → 发提醒 → 启动轮询。
707
+ timer = setTimeout(() => {
708
+ if (settled)
709
+ return;
710
+ void notifyByMail(cfg, id, req, p, () => settled);
711
+ }, cfg.idleMs);
712
+ timer.unref?.();
713
+ // local 拒绝(理论上不 reject)兜底:避免 unhandled rejection。
714
+ local.catch(() => finish({ action: 'cancelled' }));
715
+ });
716
+ return result;
717
+ }
718
+ /**
719
+ * 超时后发提醒邮件并把待决项挂进轮询。isSettled 用于在异步预取/发信期间
720
+ * 检测用户是否已在终端作答,若是则放弃。发信绝不因 IMAP 失败而被阻断:
721
+ * 发信前 best-effort 预取"当前最高 UID"作为水位;预取失败也照发,轮询退化为
722
+ * "发信时间之后"的日期搜索(不会跳过发信后立即到达的回复)。
723
+ * 提醒自身靠 isSelfReminder(正文特征)+ Message-ID 在轮询中被跳过。
724
+ */
725
+ async function notifyByMail(cfg, id, req, p, isSettled) {
726
+ // 发信前快照"当前最高 UID":水位之下全是历史邮件;提醒自身 UID 虽高于水位,
727
+ // 但会被 isSelfReminder/Message-ID 判断跳过,只处理其后真正的用户回复。
728
+ const highest = await probeHighestUidBestEffort(cfg);
729
+ if (isSettled())
730
+ return;
731
+ if (highest > 0)
732
+ p.watermark = highest;
733
+ p.sentAt = Date.now();
734
+ p.selfMessageId = selfMessageId(id, cfg.user);
735
+ pending.set(id, p);
736
+ try {
737
+ await sendMail(cfg, buildSubject(req.title), buildBody(cfg, p), p.selfMessageId, buildHtmlBody(cfg, p));
738
+ }
739
+ catch {
740
+ // 发信失败:撤销注册,避免空等;本地面板仍在,用户可终端作答。
741
+ pending.delete(id);
742
+ stopPollingIfIdle();
743
+ return;
744
+ }
745
+ if (isSettled()) {
746
+ // 发信期间用户已在终端作答:撤销注册即可,无需再轮询。
747
+ pending.delete(id);
748
+ stopPollingIfIdle();
749
+ return;
750
+ }
751
+ ensurePolling();
752
+ }
753
+ /**
754
+ * 发一封测试邮件到配置邮箱,并尝试 IMAP 登录自检(不依赖刚发的信已送达)。
755
+ * 仅当配置完整时可调用;任一步失败都在对应字段标记并返回原因,不抛错。
756
+ */
757
+ export async function sendTestMail() {
758
+ // 用状态探测取完整凭据:即便当前被 /mail off 关闭,也允许发测试信验证配置。
759
+ const { cfg: statusCfg } = getMailStatus();
760
+ if (!statusCfg) {
761
+ return { ok: false, smtp: 'fail', imap: 'skipped', error: 'mail-not-configured' };
762
+ }
763
+ // 测试信无视启用开关,补 enabled 字段以满足内部连接函数的 MailConfig 形参。
764
+ const cfg = { ...statusCfg, enabled: true };
765
+ const result = { ok: false, smtp: 'fail', imap: 'skipped' };
766
+ try {
767
+ const stamp = new Date().toISOString();
768
+ await sendMail(cfg, `${MAIL_SUBJECT_PREFIX} test ${stamp}`, [
769
+ '这是一封来自 mocode 的测试邮件。',
770
+ '如果你收到了它,说明 SMTP 发送配置正确。',
771
+ `时间: ${stamp}`,
772
+ '',
773
+ '人工介入提醒也会发到这个邮箱;直接回复提醒邮件即可让 mocode 继续执行。',
774
+ ].join('\n'),
775
+ // 测试信也要显式 Message-ID(与提醒邮件同款),避免服务端留空导致后续排障困难。
776
+ `mocode-test-${Date.now().toString(36)}@${cfg.user.includes('@') ? cfg.user.split('@')[1] : 'localhost'}`);
777
+ result.smtp = 'ok';
778
+ }
779
+ catch (e) {
780
+ result.error = e instanceof Error ? e.message : String(e);
781
+ return result;
782
+ }
783
+ try {
784
+ const { ImapFlow } = await import('imapflow');
785
+ const client = new ImapFlow({
786
+ host: cfg.imapHost,
787
+ port: cfg.imapPort,
788
+ secure: cfg.imapSecure,
789
+ auth: { user: cfg.user, pass: cfg.pass },
790
+ logger: false,
791
+ tls: { rejectUnauthorized: true },
792
+ });
793
+ await client.connect();
794
+ await client.mailboxOpen('INBOX');
795
+ await client.logout().catch(() => { });
796
+ result.imap = 'ok';
797
+ }
798
+ catch (e) {
799
+ result.imap = 'fail';
800
+ result.error = result.error ?? (e instanceof Error ? e.message : String(e));
801
+ }
802
+ result.ok = result.smtp === 'ok' && result.imap === 'ok';
803
+ return result;
804
+ }