dsh-postbox 0.0.0-stage → 0.2.1

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.
package/index.js ADDED
@@ -0,0 +1,2312 @@
1
+ // dsh-postbox — 通用个人邮箱 Host 插件(Outlook/Hotmail)。
2
+ //
3
+ // 纯 Node 零依赖实现:OAuth2 设备码流 + IMAP(XOAUTH2) + SMTP(STARTTLS/XOAUTH2)。
4
+ // 支持多账户,细节可配置;只给**通用**邮件客户端能力,不做行业/流程定制。
5
+ //
6
+ // 分三层理解:
7
+ // · 工具层(6 个基础工具 + mailbox_notify):对模型暴露的能力面
8
+ // · 常驻层(watcher):轮询归档 + 通知 + 每日汇总(单实例锁保证不重复)
9
+ // · 配置层:cordis config(部署层,改完要重启) ⊕ <dataDir>/settings.json
10
+ // (用户运行时层,**改完下一轮生效,不用重启**)
11
+ //
12
+ // 工具面(对模型):
13
+ // mailbox_auth 设备码授权(两段式:device → complete)、status、signout
14
+ // mailbox_folders 列文件夹(带未读数/UID 信息)
15
+ // mailbox_list 列邮件信封(最近 N 封 / 未读 / 日期范围)
16
+ // mailbox_read 读一封:正文(截断)+ 附件清单,可落盘附件
17
+ // mailbox_search 按发件人/主题/日期/未检索
18
+ // mailbox_send 发信(纯文本/HTML/附件),主备服务器兜底
19
+ // mailbox_notify 通知渠道与运行时设置(status/targets/set-target/set/off/on/reset)
20
+ // mailbox_update 插件自更新(status/check/install/reset,装完需手动重启)
21
+ //
22
+ // 细节配置走 patch 的 config(见 cordis.patch.yml 注释);默认值在 lib/config.js。
23
+ // **用户运行时层**(改完免重启的字段)在 <dataDir>/settings.json,见 lib/settings.js。
24
+
25
+ import fs from "node:fs";
26
+ import os from "node:os";
27
+ import path from "node:path";
28
+ import crypto from "node:crypto";
29
+ import { fileURLToPath } from "node:url";
30
+ // ⚠️ DEFAULT_SCOPES 曾在这里漏掉(2026-10-17 真机踩坑):persistAccounts 引用了它,
31
+ // 加载不炸、每次添加账号才炸 ReferenceError —— 离线测试没真跑那条路径,一直没被发现。
32
+ import { resolveTop, pickAccount, checkImStateSync, DEFAULTS, DEFAULT_CLIENT_ID, DEFAULT_AUTHORITY, DEFAULT_SCOPES, ARCHIVE_MODES, tokenSlug, dedupeFolders } from "./lib/config.js";
33
+ import { defineTool } from "./lib/tool.js";
34
+ import {
35
+ deviceCodeStart, deviceCodePoll,
36
+ writeToken, deleteToken, readToken, getAccessToken, tokenStatus,
37
+ } from "./lib/oauth.js";
38
+ import { ImapClient } from "./lib/imap.js";
39
+ import { sendMail } from "./lib/smtp.js";
40
+ import { parseMime, buildMessage, saveAttachments } from "./lib/mime.js";
41
+ import { openStore, modeFlags } from "./lib/store.js";
42
+ import { reindexArchive, Watcher } from "./lib/sync.js";
43
+ import { buildM4Tools, buildWriteTools, runArchiveSearch } from "./lib/tools-m4.js";
44
+ import { makeLlmWorker } from "./lib/llm.js";
45
+ import { Notifier, resolveImTarget, buildDailyDigestText, normalizeFilter } from "./lib/notify.js";
46
+ import { scoreMessage } from "./lib/importance.js";
47
+ // 命名空间导入:这里只借两个纯函数(验证码抽取/HTML 清洗),
48
+ // 顺便避免 host-settings.test 的「lib 导出名必须在 import 名单里」静态看守
49
+ // 把 top.dailyDigest 这类**同名配置键**误判成漏 import。
50
+ import * as digestLib from "./lib/digest.js";
51
+ import { createLogger } from "./lib/log.js";
52
+ import {
53
+ createUpdateService, inspectRuntime, gtSemver,
54
+ PACKAGE_NAME, PUBLIC_ERRORS as UPDATE_PUBLIC_ERRORS,
55
+ } from "./lib/update.js";
56
+ import {
57
+ SettingsStore, applySettings, diffLive, expandPatch, normalizeSettings,
58
+ SETTINGS_FIELDS, STRUCTURAL_FIELDS,
59
+ } from "./lib/settings.js";
60
+ import {
61
+ createHostSettings, migrateLegacyFile, resolveSources, sourceLabel,
62
+ MAILBOX_NS, VOLATILE_KEY,
63
+ } from "./lib/host-settings.js";
64
+ import { makeBridgeHandlers, makeBridgeRoutes, MAILBOX_BRIDGE_PREFIX } from "./lib/bridge.js";
65
+
66
+ export const name = "mailbox";
67
+ export const inject = ["tools"];
68
+
69
+ /** 本插件的版本(自更新要用:runningVersion)。
70
+ * 从自己的 package.json 读,不硬编码 —— 硬编码的话每次发包都可能忘记改,
71
+ * 而版本号错了会让「更新到哪里」整个判断失效。 */
72
+ export const PKG_VERSION = (() => {
73
+ for (const dir of [path.dirname(fileURLToPath(import.meta.url))]) {
74
+ try {
75
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
76
+ if (typeof pkg.version === "string") return pkg.version;
77
+ } catch { /* 读不到就往下走 */ }
78
+ }
79
+ return "0.0.0";
80
+ })();
81
+
82
+ // ---- 行级 config schema ----
83
+ // 为什么用真 schemastery(2026-10-15 勘误,ROADMAP §2.4 / 内部复核记录(不随包发布)):
84
+ // 宿主 **配置页只认 `Config` 里 `.volatile()` 节点的子树** —— dsh-settings 的 schema()
85
+ // 要求 `"toJSON" in Config`,volatileForm()/isVolatilePath() 还要读节点上的 `dict` / `meta`。
86
+ // 自造 facade(lib/schema.js)三样都没有 ⇒ 宿主看不见本插件,配置页不可能出现。
87
+ // 依赖解析:`profile` 用 link: 把本包链到源码目录,ESM bare-specifier 从源码目录向上走**不到**
88
+ // profile 的 node_modules —— 所以依赖装在本包自己的 `node_modules/`(与 link: 安装不冲突)。
89
+ // `mailbox/node_modules/@deepseek-ai/schemastery` = 3.18.4(与宿主同版本;profile 那份是
90
+ // 3.18.2 且**没有** `.volatile()`,别用)。
91
+ // 跨副本安全:宿主只按结构判断(`meta.volatile` / `dict` / `~standard.vendor` / `toJSON()`),
92
+ // volatile 引用的协议符号是 `Symbol.for('cosmokit.volatile.write')`,与实例身份无关。
93
+ import Schema from "@deepseek-ai/schemastery";
94
+
95
+ const AccountSchema = Schema.object({
96
+ email: Schema.string().required().description("邮箱地址,如 x@outlook.com"),
97
+ alias: Schema.string().description("友好别名,工具里可用它指代账户"),
98
+ clientId: Schema.string().description(`OAuth client id(默认 Thunderbird 公共: ${DEFAULT_CLIENT_ID})`),
99
+ authority: Schema.string().description(`OAuth authority(默认 ${DEFAULT_AUTHORITY})`),
100
+ scopes: Schema.array(Schema.string()).description("OAuth scope 列表"),
101
+ imapHost: Schema.string().description(`IMAP 服务器(默认 ${DEFAULTS.imapHost})`),
102
+ imapPort: Schema.number().description(`IMAP 端口(默认 ${DEFAULTS.imapPort})`),
103
+ smtpHost: Schema.string().description(`SMTP 服务器(默认 ${DEFAULTS.smtpHost})`),
104
+ smtpPort: Schema.number().description(`SMTP 端口(默认 ${DEFAULTS.smtpPort})`),
105
+ defaultFolder: Schema.string().description(`默认文件夹(默认 ${DEFAULTS.defaultFolder})`),
106
+ // 监控文件夹选项(2026-10-30):留空/缺省 = 只监控 defaultFolder(通常 INBOX);
107
+ // 填了就**只**监控列出的这些(数据隔离:比如只看 INBOX + INBOX/Projects,Junk/其他子文件夹一概不碰)。
108
+ // 文件夹名与 IMAP 一致(层级用 / 分隔)。schema 里必须显式声明:volatile 写入要过这道校验,
109
+ // 缺了它宿主配置页/卡片写的 folders 会被丢弃或拒收。
110
+ folders: Schema.array(Schema.string()).description("监控的文件夹列表(留空=只监控默认文件夹;如 [\"INBOX\",\"INBOX/Projects\"])"),
111
+ }).required();
112
+
113
+ /** 单个运行时字段 → schemastery 叶子。
114
+ * **字段表(SETTINGS_FIELDS)是唯一事实来源**:配置页的 volatile 节点由它派生,
115
+ * 所以"卡片上能改什么"与"settings.json 能写什么"永远一致;加字段只改一处。 */
116
+ function runtimeLeaf(field) {
117
+ switch (field.kind) {
118
+ case "bool": return Schema.boolean().default(field.unset ?? true);
119
+ case "int": {
120
+ let s = Schema.number();
121
+ if (typeof field.min === "number") s = s.min(field.min);
122
+ if (typeof field.max === "number") s = s.max(field.max);
123
+ return s.default(field.unset ?? 0);
124
+ }
125
+ case "mode": return Schema.union(ARCHIVE_MODES).default(field.unset ?? "metadata");
126
+ case "enum": return Schema.union(field.options ?? []).default(field.unset ?? field.options?.[0]);
127
+ case "list": return Schema.array(Schema.string()).default(field.unset ?? []);
128
+ case "str": return Schema.string().default(field.unset ?? "");
129
+ case "hhmm": return Schema.string().default(field.unset ?? "08:00");
130
+ case "quiet": return Schema.string(); // 无默认:未设置时不出现在 volatile 快照里
131
+ default: throw new Error(`SETTINGS_FIELDS 有未知 kind:"${field.kind}"(${field.path})`);
132
+ }
133
+ }
134
+
135
+ /** 由 SETTINGS_FIELDS 的路径建嵌套对象树(leaf 由 runtimeLeaf 给)。
136
+ * `notify.dailyDigest.at` 这类多级路径要逐级建节点,不能拍平。 */
137
+ function buildRuntimeTree(fields) {
138
+ const root = {};
139
+ for (const field of fields) {
140
+ const parts = String(field.path).split(".");
141
+ let node = root;
142
+ for (let i = 0; i < parts.length - 1; i += 1) {
143
+ node[parts[i]] ??= { __children: {} };
144
+ node = node[parts[i]].__children;
145
+ }
146
+ node[parts[parts.length - 1]] = { __leaf: field };
147
+ }
148
+ const toSchema = (node) => Schema.object(Object.fromEntries(
149
+ Object.entries(node).map(([key, value]) => [key, value.__leaf ? runtimeLeaf(value.__leaf) : toSchema(value.__children)]),
150
+ ));
151
+ return toSchema(root);
152
+ }
153
+
154
+ export const Config = Schema.object({
155
+ // ⚠️ **不可加 `.required()`**(M6.10 真机回归,2026-10-28):
156
+ // Schema 校验的是**部署层 config 本身**,在 apply() 之前执行 ——
157
+ // 它看不到 volatile `runtime.accounts`。一旦标 required,「部署层留空、
158
+ // 账号全放运行层」这种(推荐的)配法会在启动时直接失败:
159
+ // ValidationError: invalid config: $.accounts missing required value
160
+ // ⇒ 条目根本没激活("1 entry did not activate")。
161
+ // 真正的「至少一个账号」由 resolveTop() 兜底(lib/config.js:90 抛
162
+ // "config.accounts 为空,至少配置一个邮箱"),而且它看得到合并后的结果
163
+ // (runtimeRawOf 先把运行层并进来,index.js:224-231)—— 那才是该报错的地方。
164
+ accounts: Schema.array(AccountSchema).description("邮箱账户列表(部署层;留空则全部账号来自运行层 runtime.accounts)"),
165
+ tokenDir: Schema.string().description("token 文件目录(默认 <DSH_PROFILE_DIR>/mailbox/tokens)"),
166
+ attachDir: Schema.string().description("附件落盘根目录(默认 <DSH_PROFILE_DIR>/mailbox/attachments)"),
167
+ attachMaxBytes: Schema.number().description(`单封邮件附件落盘上限(字节,默认 ${DEFAULTS.attachMaxBytes};填 0 表示不限制)`),
168
+ bodyLimit: Schema.number().description(`正文截断字符数(默认 ${DEFAULTS.bodyLimit})`),
169
+ // 运行层同名字段的部署层入口(两处都写时以运行层为准,见 lib/config.js 的 resolveTop)
170
+ mail: Schema.object({
171
+ bodyLimit: Schema.number().description("正文截断字符数(同顶层 bodyLimit;运行层可覆盖)"),
172
+ attachMaxBytes: Schema.number().description("单封邮件附件落盘上限(字节,0 = 不限)"),
173
+ }).description("收发与内容(可选;通常用运行层设置)"),
174
+ // M4 自更新:更新源。不写则按安装形态自动推导(link 安装没有上游,会如实报 source-install)。
175
+ // "npm:@scope/name" —— 从 npm registry 更新
176
+ // "github:owner/repo" —— 从 GitHub releases 更新
177
+ update: Schema.object({
178
+ source: Schema.string().description('更新源,如 "npm:@scope/mailbox" 或 "github:owner/repo";留空按安装形态推导'),
179
+ }).description("自更新设置(M4)"),
180
+ // ⚠️ **恰好一个** `.volatile()` 节点(D15):宿主配置页读的就是它,子树 = 可编辑字段全集。
181
+ // schemastery 的硬约束:volatile 必须是固定路径且**不得嵌套**("volatile fields require a fixed
182
+ // object path without an enclosing volatile field"),所以只能标这一个节点,不能逐字段标。
183
+ // 命名空间 = Loader 行 id(= cordis.patch.yml 里那行的 `id: mailbox`),由宿主决定,客户端硬写同一字面量。
184
+ runtime: buildRuntimeTree(SETTINGS_FIELDS)
185
+ .set('accounts', Schema.array(AccountSchema).description("免重启添加的邮箱账号(与部署层账号合并,以 email 为主键;同 email 的运行时层账号覆盖部署层)"))
186
+ .volatile().description("运行时设置(宿主配置页 + mailbox_notify 共同编辑;改完免重启)"),
187
+ });
188
+
189
+ /** 读 volatile 引用:宿主给的是**稳定引用**(`{ get() }`);单测里可能直接给普通对象。 */
190
+ export function readRuntime(value) {
191
+ if (value === undefined || value === null) return {};
192
+ if (typeof value.get === "function") {
193
+ try { return value.get() ?? {}; } catch { return {}; }
194
+ }
195
+ return typeof value === "object" ? value : {};
196
+ }
197
+
198
+ /** volatile `runtime` 快照 → `resolveTop()` 认得的形状。
199
+ * 两者键名刻意不同:volatile 用**用户视角**路径(`watcher.pollIntervalSeconds`,
200
+ * 与 SETTINGS_FIELDS 一致),`resolveTop` 用内部扁平键(`pollIntervalSeconds`)。
201
+ * 历史坑见 lib/settings.js:40-43 —— 所以要显式映射,不能盲目展开。 */
202
+ export function runtimeToConfigLayer(rt) {
203
+ if (!rt || typeof rt !== "object") return {};
204
+ const out = {};
205
+ if (rt.pollIntervalSeconds !== undefined) out.pollIntervalSeconds = rt.pollIntervalSeconds;
206
+ if (rt.watcher && typeof rt.watcher === "object") {
207
+ const { pollIntervalSeconds, ...rest } = rt.watcher;
208
+ if (Object.keys(rest).length) out.watcher = rest;
209
+ if (pollIntervalSeconds !== undefined && out.pollIntervalSeconds === undefined) out.pollIntervalSeconds = pollIntervalSeconds;
210
+ }
211
+ if (rt.archive && typeof rt.archive === "object") out.archive = rt.archive;
212
+ // 2026-11-30:收发与内容(group `mail`)也进运行层 —— 正文截断/附件上限在调用时现取,能热生效
213
+ if (rt.mail && typeof rt.mail === "object") out.mail = rt.mail;
214
+ if (rt.notify && typeof rt.notify === "object") out.notify = rt.notify;
215
+ if (rt.accounts && Array.isArray(rt.accounts)) out.accounts = rt.accounts;
216
+ return out;
217
+ }
218
+
219
+ /** 日报队列的可读摘要(供 `mailbox_notify status` 回答"为什么没提醒")。
220
+ * 实测场景:测试邮件评分为 0,阈值 60 ⇒ 只进日报、不即时推 —— 用户看不到任何东西,只能靠猜。 */
221
+ export function describeDigestQueue(rows = [], threshold = 60) {
222
+ if (!Array.isArray(rows) || rows.length === 0) return "";
223
+ const items = rows.slice(0, 4).map((r) => `uid ${r.uid} score ${r.score}`).join(" · ");
224
+ const more = rows.length > 4 ? ` …共 ${rows.length} 封` : "";
225
+ return `日报队列(低优先,到点合并发送):${items}${more}`
226
+ + ` —— 当前阈值 ${threshold}:评分低于它的邮件**不会即时推**(想立刻收到就调低 notify.importanceThreshold,`
227
+ + `或让邮件带"验证码/安全代码"(+70)之类特征)`;
228
+ }
229
+
230
+ /** Telegram bot token 形状:`<数字>:<35 位左右>`。用于识破"把 token 填进 botId"。 */
231
+ const TELEGRAM_TOKEN_RE = /^\d{6,}:[A-Za-z0-9_-]{20,}$/;
232
+
233
+ /**
234
+ * 浮动栏「点开附件」的预览上限(B9 的姊妹条款)。
235
+ * 面板走 HTTP JSON 传 base64,单封 10 MB 已经是 13 MB 抖动字符串;更大的文件应当
236
+ * 用 `mailbox_read saveAttachments=true` 落盘后用系统应用打开,而不是塞进浏览器内存。
237
+ */
238
+ const MAX_ATTACH_PREVIEW = 10 * 1024 * 1024;
239
+ export function looksLikeBotToken(value) {
240
+ return TELEGRAM_TOKEN_RE.test(String(value ?? "").trim());
241
+ }
242
+ /** 回显敏感值时只留头尾(日志/工具输出不该出现完整 token)。 */
243
+ export function maskSecret(value) {
244
+ const s = String(value ?? "");
245
+ return s.length <= 12 ? s : `${s.slice(0, 4)}…${s.slice(-4)}`;
246
+ }
247
+
248
+ /** 把插件的 config(**含 volatile 引用**)摊平成 `resolveTop()` 认得的 raw 形状。
249
+ * volatile 节点用「用户视角」路径(`watcher.pollIntervalSeconds`),resolveTop 用内部扁平键,
250
+ * 所以必须显式映射,不能盲目展开(历史坑见 lib/settings.js:40-43)。
251
+ *
252
+ * accounts 合并策略:部署层 `config.accounts` 与运行时层 `runtime.accounts` 以 email 为主键合并,
253
+ * 运行时层同 email 的账号覆盖部署层,其余部署层账号保留。这样用户在配置页免重启添加的账号
254
+ * 会与部署层账号并存,下一轮 watcher 即可抓取。 */
255
+ export function runtimeRawOf(pluginConfig) {
256
+ const cfg = pluginConfig ?? {};
257
+ const raw = { ...cfg, ...runtimeToConfigLayer(readRuntime(cfg.runtime)) };
258
+ const deployed = Array.isArray(cfg.accounts) ? cfg.accounts : [];
259
+ const runtime = Array.isArray(raw.accounts) ? raw.accounts : [];
260
+ const byEmail = new Map();
261
+ for (const a of deployed) byEmail.set(String(a.email), a);
262
+ for (const a of runtime) byEmail.set(String(a.email), a);
263
+ raw.accounts = byEmail.size ? [...byEmail.values()] : undefined;
264
+ return raw;
265
+ }
266
+
267
+ /** 重新计算「生效配置」的**唯一入口**:摊平 volatile 层 → `resolveTop` → 叠 settings.json。
268
+ * ⚠️ 不要用 `applySettings(top, …)` 代替:`applySettings` 只叠 settings.json
269
+ * (`lib/settings.js:312-330`,它对 rawConfig 只做「来源标注」,不写值)——
270
+ * volatile 引用里的新值必须先过 `resolveTop` 才会进来。
271
+ * 2026-10-16 真机 bug:改动前卡片改了 botId、内存 top 不变,日志只报「热应用 0 项」。 */
272
+ export function buildTop(pluginConfig, settings = {}) {
273
+ const raw = runtimeRawOf(pluginConfig);
274
+ return applySettings(resolveTop(raw), settings, raw);
275
+ }
276
+
277
+ // 待完成设备码流的暂存目录(工具两段式)。
278
+ function pendingDir() {
279
+ const profileDir = process.env.DSH_PROFILE_DIR
280
+ ?? path.join(process.env.DSH_HOME ?? path.join(process.env.HOME ?? "", ".dsh"), "profiles", process.env.DSH_PROFILE ?? "desktop");
281
+ const dir = path.join(profileDir, "mailbox", "pending");
282
+ fs.mkdirSync(dir, { recursive: true });
283
+ return dir;
284
+ }
285
+
286
+ function pendingPath(alias) {
287
+ return path.join(pendingDir(), `${String(alias).replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
288
+ }
289
+
290
+ // ---- 输出:文本 + 可选结构化字段 ----
291
+ function textOutput(extraProps) {
292
+ return {
293
+ schema: {
294
+ type: "object",
295
+ additionalProperties: false,
296
+ required: ["text"],
297
+ properties: {
298
+ text: { type: "string" },
299
+ ...(extraProps ?? {}),
300
+ },
301
+ },
302
+ render: (_args, value) => [{ type: "text", text: String(value?.text ?? "") }],
303
+ };
304
+ }
305
+
306
+ function apply(ctx, config) {
307
+ // ---- 三个来源合成一份「生效配置」 ----
308
+ // ① cordis 行 config(patch 手写:accounts/tokenDir/主机端口…)
309
+ // ② volatile `runtime`(宿主配置页写的;D15 —— 免重启)
310
+ // ③ settings.json(M3.3 私有层;M6.1 起降级为一次性迁移源)
311
+ // ①②由 runtimeRawOf 摊平后过 resolveTop;③由 applySettings 在之后叠加。
312
+ // ⚠️ 统一走 buildTop():早期版本在这里用 applySettings(top,…) 重算,volatile 新值进不来。
313
+ const rawConfig = () => runtimeRawOf(config);
314
+
315
+ let top;
316
+ try {
317
+ top = resolveTop(rawConfig());
318
+ } catch (err) {
319
+ // config 不合法时仍要注册「一个」工具让用户知道问题
320
+ ctx.tools.register(defineTool({
321
+ name: "mailbox_auth",
322
+ description: "个人邮箱授权。当前 config 无法解析,先修复配置。",
323
+ parameters: {},
324
+ output: textOutput(),
325
+ async execute() {
326
+ return { text: `config 错误: ${err.message}` };
327
+ },
328
+ }));
329
+ return () => {};
330
+ }
331
+
332
+ const single = top.accounts.length === 1;
333
+ const accountParam = {
334
+ type: "string",
335
+ required: !single,
336
+ description: single ? `唯一账户 ${top.accounts[0].alias}(自动使用)` : "账户 alias 或 email",
337
+ };
338
+
339
+ // ---- 早期日志出口 ----
340
+ // logger(<dataDir>/mailbox.log)要到开库前后才建,但设置层/配置层在此之前就要记账。
341
+ // log0 先打到 console(桌面版 stdout 不落盘,所以真正重要的行之后会由 log 重记一遍)。
342
+ let log0 = (level, msg) => { try { (level === "error" ? console.error : console.log)(`[mailbox:${level}] ${msg}`); } catch { /* ignore */ } };
343
+
344
+ // ---- 读宿主服务的公共姿势 ----
345
+ // **必须**用 ctx.get(name):直接访问未注入的服务属性会抛
346
+ // `cannot get property "dshIm" without inject`
347
+ // —— M2 首次真机启动就是死在这一行(而且当时没有日志,只能靠读库反推)。
348
+ // 位置说明:定义在设置层之前,因为 M6.1 的 settings.json→宿主迁移(在 ctx.inject 回调里)
349
+ // 也要用 probe;放在后面会踩 const 的 TDZ。
350
+ const probe = (c, name) => {
351
+ try {
352
+ if (typeof c?.get === "function") return c.get(name) ?? null; // cordis 官方:未提供时返回 undefined
353
+ return c?.[name] ?? null; // 兜底:非 cordis 上下文
354
+ } catch { return null; }
355
+ };
356
+ const withTimeout = (p, ms, label) => Promise.race([
357
+ p,
358
+ new Promise((_, rej) => setTimeout(() => rej(new Error(`${label}超时(${ms}ms)`)), ms)),
359
+ ]);
360
+
361
+ // ---- 运行时设置层(M3.3 · ROADMAP §2.3 阶段一) ----
362
+ // 分层优先级:settings.json(用户,免重启) > cordis config(部署层,要重启) > DEFAULTS。
363
+ // 这一层存在的理由:此前 notify.botId/targetId 只能写在 cordis.patch.yml,
364
+ // 用户每改一个字都要重启 DSH —— 整个通知渠道就是卡在这里。
365
+ const settingsStore = new SettingsStore(path.join(top.dataDir, "settings.json"));
366
+ settingsStore.load();
367
+ if (settingsStore.lastError) log0("warn", settingsStore.lastError);
368
+
369
+ let layer = buildTop(config, settingsStore.get());
370
+ top = layer.top;
371
+
372
+ // ---- 宿主配置页适配层(M6.1) ----
373
+ // 懒取服务:settings 可能比 apply() 晚就绪,所以传 getter 而不是快照。
374
+ const hostSettings = createHostSettings({ getService: () => probe(ctx, "settings"), log: log0 });
375
+ /** 宿主层是否**真的在服务本命名空间**(服务在 ≠ 本行被服务:mailbox 行没插进组合时是后者)。 */
376
+ const hostState = () => {
377
+ if (!hostSettings.available()) return { ok: false, reason: "no-settings-service" };
378
+ return hostSettings.read();
379
+ };
380
+
381
+ /** 深合并(只用于把不同层拼成「用户视角的一份值」,不写回任何对象)。 */
382
+ const deepAssign = (dst, src) => {
383
+ for (const [k, v] of Object.entries(src ?? {})) {
384
+ if (v && typeof v === "object" && !Array.isArray(v)) {
385
+ if (!dst[k] || typeof dst[k] !== "object" || Array.isArray(dst[k])) dst[k] = {};
386
+ deepAssign(dst[k], v);
387
+ } else dst[k] = v;
388
+ }
389
+ return dst;
390
+ };
391
+
392
+ /** **生效的用户层**(宿主 volatile 子树 ⊕ settings.json 过渡层),只保留已知字段。
393
+ * 与卡片里看到的是同一份来源,正是 M6.1 要消灭「页面改了、工具显示另一个值」的那份值。 */
394
+ const effectiveSettings = () => {
395
+ const merged = {};
396
+ const st = hostState();
397
+ if (st.ok) deepAssign(merged, st.runtime);
398
+ deepAssign(merged, settingsStore.get());
399
+ const n = normalizeSettings(merged, { lenient: true });
400
+ return n.ok ? n.value : merged;
401
+ };
402
+
403
+ /** 每字段「谁说了算」,与**实际生效顺序**一致:
404
+ * settings.json(过渡) > 宿主配置页 > cordis 部署层 > 默认值。
405
+ * ⚠️ 不能直接用 layer.sources:它只认 settings/config/default,
406
+ * 会把「用户刚在配置页改的值」标成 config,让用户以为没保存成功。 */
407
+ const currentSources = () => {
408
+ const st = hostState();
409
+ return resolveSources({
410
+ hostRuntime: st.ok ? st.user : {},
411
+ fileLayer: settingsStore.get(),
412
+ deploymentConfig: config ?? {},
413
+ });
414
+ };
415
+
416
+ /**
417
+ * M6.1:运行时设置的**唯一写入口**。
418
+ * · 宿主配置页在场且服务本命名空间 → 写宿主(唯一真相,改完免重启);
419
+ * · 否则退回 `settings.json`(精简组合/headless 没有配置页,私有层仍是唯一可行方案)。
420
+ * 宿主写入失败(含 revision 冲突)**绝不回退写文件**:那会当场制造第二份真相,
421
+ * 正是 M6.1 要消灭的东西。宁可让用户重试。
422
+ */
423
+ const persistSettings = async (section, { mode = "merge" } = {}) => {
424
+ const st = hostState();
425
+ if (st.ok) {
426
+ const r = mode === "replace" ? await hostSettings.reset() : await hostSettings.update(section);
427
+ if (r.ok) return { ok: true, via: "host" };
428
+ return { ok: false, via: "host", reason: r.reason, error: r.error, conflict: !!r.conflict };
429
+ }
430
+ if (settingsStore.importedTo) {
431
+ return {
432
+ ok: false, via: "host", reason: "migrated",
433
+ error: `settings.json 已迁移到宿主配置页(${settingsStore.importedTo}),但宿主 settings 服务当前不可用(${st.reason})`,
434
+ };
435
+ }
436
+ const r = mode === "replace" ? settingsStore.reset() : settingsStore.update(section);
437
+ if (!r.ok) return { ok: false, via: "file", reason: "invalid", error: r.error };
438
+ return { ok: true, via: "file" };
439
+ };
440
+
441
+ // ============== 配置页免重启账号管理(与 M6.1 宿主配置页共享 runtime 节点) ==============
442
+
443
+ /** 配置页:免重启添加/更新一个邮箱账号。写入运行时层 volatile `runtime.accounts`,
444
+ * 与部署层 `config.accounts` 以 email 为主键合并,运行时层同 email 的覆盖部署层。
445
+ * 写入后触发 loader/volatile-update → applySettingsChange → watcher 热更新账号列表。 */
446
+ const persistAccounts = async (account) => {
447
+ if (!account || !account.email) return { ok: false, reason: "missing-email" };
448
+ const acc = {
449
+ email: String(account.email).trim(),
450
+ alias: String(account.alias ?? account.email).trim(),
451
+ clientId: String(account.clientId ?? DEFAULT_CLIENT_ID),
452
+ authority: String(account.authority ?? DEFAULT_AUTHORITY).replace(/\/+$/, ""),
453
+ scopes: Array.isArray(account.scopes) && account.scopes.length ? account.scopes : DEFAULT_SCOPES,
454
+ imapHost: String(account.imapHost ?? DEFAULTS.imapHost),
455
+ imapPort: Number(account.imapPort ?? DEFAULTS.imapPort) || DEFAULTS.imapPort,
456
+ smtpHost: String(account.smtpHost ?? DEFAULTS.smtpHost),
457
+ smtpPort: Number(account.smtpPort ?? DEFAULTS.smtpPort) || DEFAULTS.smtpPort,
458
+ defaultFolder: String(account.defaultFolder ?? DEFAULTS.defaultFolder),
459
+ // 监控文件夹(2026-10-30):只在请求**带了**这个字段时才覆盖 ——
460
+ // 旧表单/旧调用方没传 folders 时,不能把它抹掉(否则"改个别名"顺手把监控范围重置回默认)。
461
+ // 2026-10-30 需求:落库前按大小写不敏感去重(保留首个书写形式),防止 INBOX/inbox 双轮询。
462
+ ...(Array.isArray(account.folders)
463
+ ? { folders: dedupeFolders(account.folders) }
464
+ : {}),
465
+ };
466
+ if (!acc.email) return { ok: false, reason: "missing-email" };
467
+
468
+ const st = hostState();
469
+ const currentRuntime = st.ok ? st.runtime : {};
470
+ const runtimeAccounts = Array.isArray(currentRuntime.accounts) ? [...currentRuntime.accounts] : [];
471
+ const byEmail = new Map(runtimeAccounts.map((a) => [a.email, a]));
472
+ // 请求没带 folders 且运行层里已有该账号 → 沿用旧值(同上:保住已配置的监控范围)
473
+ if (!Array.isArray(account.folders) && Array.isArray(byEmail.get(acc.email)?.folders)) {
474
+ acc.folders = byEmail.get(acc.email).folders;
475
+ }
476
+ byEmail.set(acc.email, acc);
477
+ const nextAccounts = [...byEmail.values()];
478
+
479
+ if (st.ok) {
480
+ // ⚠️ 传**裸 section**,别再包 runtime: —— 适配器 update() 内部会做 toFormShape()
481
+ // 包装,多包一层会写成 {runtime:{runtime:{accounts}}}:账号落进没人读的路径,
482
+ // 响应却还是 ok:true(2026-10-17 离线端到端测试抓到的第二个真机坑)。
483
+ const r = await hostSettings.update({ accounts: nextAccounts });
484
+ if (!r.ok) return { ok: false, via: "host", reason: r.reason, error: r.error, conflict: !!r.conflict };
485
+ await new Promise((res) => setTimeout(res, 0));
486
+ applySettingsChange();
487
+ return { ok: true, via: "host" };
488
+ }
489
+ if (settingsStore.importedTo) {
490
+ return {
491
+ ok: false, via: "host", reason: "migrated",
492
+ error: `settings.json 已迁移到宿主配置页(${settingsStore.importedTo}),但宿主 settings 服务当前不可用(${st.reason})`,
493
+ };
494
+ }
495
+ const r = settingsStore.update({ accounts: nextAccounts });
496
+ if (!r.ok) return { ok: false, via: "file", reason: "invalid", error: r.error };
497
+ applySettingsChange();
498
+ return { ok: true, via: "file" };
499
+ };
500
+
501
+ /** 当前**运行时层**(volatile `runtime.accounts`)的账号;宿主不可用时退回 settings.json 过渡层。
502
+ * 删除账号只动这一层 —— 部署层(cordis.patch.yml)那份删不掉,因为生效账号是并集
503
+ * (runtimeRawOf),少写一份运行时副本也去不掉部署层那一份。 */
504
+ const runtimeAccountsNow = () => {
505
+ const st = hostState();
506
+ if (st.ok) return Array.isArray(st.runtime?.accounts) ? st.runtime.accounts : [];
507
+ const file = settingsStore.get();
508
+ return Array.isArray(file?.accounts) ? file.accounts : [];
509
+ };
510
+
511
+ /** 配置页:替换整个运行时层账号列表(用于删除账号)。写入后热应用,watcher 下一轮用新列表。 */
512
+ const replaceRuntimeAccounts = async (accounts) => {
513
+ const st = hostState();
514
+ if (!st.ok) {
515
+ return { ok: false, via: "host", reason: "no-settings-service" };
516
+ }
517
+ // 同 persistAccounts:传裸 section,适配器负责包 runtime —— 双重包装会让删除"假成功"
518
+ const r = await hostSettings.update({ accounts });
519
+ if (!r.ok) return { ok: false, via: "host", reason: r.reason, error: r.error, conflict: !!r.conflict };
520
+ await new Promise((res) => setTimeout(res, 0));
521
+ applySettingsChange();
522
+ return { ok: true, via: "host" };
523
+ };
524
+
525
+ /** 配置页:账号 token 授权状态(哪些已授权,哪些还没,用于账号列表显示)。 */
526
+ const accountTokenStatus = () => {
527
+ try { return tokenStatus(top); } catch { return []; }
528
+ };
529
+
530
+ /** 配置页:为指定账号发起 OAuth2 设备码流(返回 userCode + 微软验证链接)。 */
531
+ const authDevice = async (email) => {
532
+ const acc = pickAccount(top, email);
533
+ if (!acc) return { ok: false, reason: `unknown-account:${email}` };
534
+ const r = await deviceCodeStart(acc);
535
+ fs.writeFileSync(pendingPath(acc.alias), JSON.stringify({
536
+ deviceCode: r.state.deviceCode, deviceCodeAccount: acc.email,
537
+ clientId: acc.clientId, authority: acc.authority, scopes: acc.scopes,
538
+ userCode: r.userCode, startedAt: Date.now(),
539
+ }, null, 2));
540
+ return { ok: true, userCode: r.userCode, verificationUri: r.verificationUri, expires: r.expires };
541
+ };
542
+
543
+ /** 配置页:完成 OAuth2 设备码流,写入本地 token。 */
544
+ const authComplete = async (email) => {
545
+ const acc = pickAccount(top, email) ?? top.accounts[0];
546
+ const p = pendingPath(acc.alias);
547
+ if (!fs.existsSync(p)) return { ok: false, reason: `no-pending:${acc.alias}` };
548
+ const st = JSON.parse(fs.readFileSync(p, "utf8"));
549
+ const res = await deviceCodePoll(st);
550
+ if (!res.ok) {
551
+ if (res.reason === "expired") fs.unlinkSync(p);
552
+ return { ok: false, reason: res.reason, detail: res.detail };
553
+ }
554
+ fs.unlinkSync(p);
555
+ writeToken(top, { email: st.deviceCodeAccount, clientId: st.clientId }, res);
556
+ return { ok: true, email: st.deviceCodeAccount };
557
+ };
558
+
559
+ /** 写入目标 → 用户可读的一句话(让用户知道值到底落到哪)。 */
560
+ const writeTargetText = (via) => (via === "host"
561
+ ? `宿主配置页(命名空间 ${MAILBOX_NS},落 profile 的 cordis.patch.yml)`
562
+ : `settings.json(${settingsStore.file})`);
563
+
564
+ /** 宿主写入是异步提交进 volatile 引用的:等一拍再算 diff,
565
+ * 避免「刚保存成功,日志却说热应用 0 项」这种自相矛盾的反馈(2026-10-16 真机踩过)。 */
566
+ const settleTick = () => new Promise((r) => setTimeout(r, 0));
567
+ const applyAfterWrite = async (via) => {
568
+ let applied = applySettingsChange();
569
+ if (via === "host" && !applied.diff.length) { await settleTick(); applied = applySettingsChange(); }
570
+ return applied;
571
+ };
572
+
573
+ /** 写失败 → 一句能行动的话(冲突 / 服务不可用 / 已迁移,话术必须不同,否则用户只能猜)。 */
574
+ const writeFailure = (w) => {
575
+ if (w.conflict) {
576
+ return "宿主拒绝了这次写入(revision 冲突:配置页或另一个入口刚改过同一字段)。"
577
+ + "请先用 action=status 重新读取,再重试 —— 你的改动**没有**被写入,也**没有**退化成第二份配置文件(那正是 M6.1 要消灭的)。";
578
+ }
579
+ if (w.reason === "migrated") return w.error;
580
+ if (w.reason === "invalid") return `设置未写入: ${w.error}`;
581
+ return `写入失败(${w.reason ?? "error"}): ${w.error ?? "(无细节)"}`;
582
+ };
583
+
584
+ /** 设置变更 → 重算分层 + 热应用到运行中的 watcher/notifier/通道缓存。
585
+ * 返回 { diff, sources };调用方负责把结果讲给用户听。
586
+ * 每次都用 rawConfig() **重新读 volatile 引用** —— 宿主提交保存在同一个引用对象里,
587
+ * 引用是不变的,里面的快照会变(get() 每次拿当前值)。 */
588
+ const settingsListeners = [];
589
+ let watcherRef = null;
590
+ /** watcher 的**活**状态(桥与 status 都要看:为什么没在跑、有几个文件夹、是不是暂停了)。 */
591
+ let storeRef = null;
592
+ /** 归档库只开一次(同一个 promise):watcher 与 M4/M5 工具共用同一份连接。
593
+ * ⚠️ 必须**不依赖 watcher.enabled** —— 关掉轮询也要能查归档、打标签、存事实。 */
594
+ let storePromise = null;
595
+ const ensureStore = () => {
596
+ if (!storePromise) {
597
+ storePromise = openStore({ dir: top.storeDir, ...modeFlags(top.archive.mode) })
598
+ .then((s) => {
599
+ storeRef = s;
600
+ log("info", `归档库就绪:${s.dbPath}(模式 ${top.archive.mode},schema v${s.schemaVersion})`);
601
+ return s;
602
+ })
603
+ .catch((e) => { storePromise = null; throw e; }); // 失败可重试
604
+ }
605
+ return storePromise;
606
+ };
607
+ const watcherStateRef = { running: false, locked: false, paused: false, reason: "watcher 尚未启动", folders: 0 };
608
+
609
+ /** 上一次检查的对外视图。桥(M6.3)、浮动栏(M6.4)、mailbox_stats 共用一份口径,
610
+ * 免得三处各算一遍「抓了几封」算出三个数。 */
611
+ const lastCheckView = () => {
612
+ const t = watcherRef?.lastTick;
613
+ if (!t) return null;
614
+ const results = Array.isArray(t.results) ? t.results : [];
615
+ return {
616
+ at: t.now ?? null,
617
+ fetched: results.reduce((n, r) => n + (r?.fetched ?? 0), 0),
618
+ failures: t.failures ?? 0,
619
+ folders: t.total ?? results.length,
620
+ nextDelaySeconds: Math.round((t.nextDelayMs ?? 0) / 1000),
621
+ paused: t.paused === true,
622
+ };
623
+ };
624
+
625
+ // ---- M4/M5 工具依赖 ----
626
+ // 用「取值函数」而不是快照:`top` 会被热应用替换,`log` 在 apply 后半段才生成
627
+ // (这里直接用 log 会撞 TDZ),所以全部延迟到 execute 时才读。
628
+ const m4Deps = {
629
+ top: () => top,
630
+ ensureStore,
631
+ reindex: async () => reindexArchive(await ensureStore(), { log: (level, msg) => log(level, msg) }),
632
+ watcherState: () => watcherStateRef,
633
+ lastCheck: lastCheckView,
634
+ /** 按需刷新服务器已读状态(mailbox_stats action=sync_seen);watcher 未起来 → 返回 null 由工具层解释 */
635
+ syncSeen: async (opts) => {
636
+ const w = watcherRef;
637
+ if (!w || typeof w.syncStateNow !== "function") return null;
638
+ return w.syncStateNow(opts ?? {});
639
+ },
640
+ // M7:语义工作器(延迟取值,LlmWorker 在 log 之后才建立)
641
+ llm: () => llmWorker,
642
+ now: () => Date.now(),
643
+ log: (level, msg) => log(level, msg),
644
+ /** 联网写操作(标记/移动)统一入口:连接 → 选中文件夹 → 跑 → 关连接。 */
645
+ withClient: async (alias, folder, fn) => {
646
+ const acc = pickAccount(top, alias) ?? top.accounts[0];
647
+ const token = await getAccessToken(top, acc);
648
+ const client = new ImapClient(acc, token);
649
+ await client.connect();
650
+ try {
651
+ await client.open(folder || acc.defaultFolder);
652
+ return await fn(client, acc);
653
+ } finally { client.close(); }
654
+ },
655
+ };
656
+ const applySettingsChange = () => {
657
+ const before = top;
658
+ // ⚠️ 必须走 buildTop(内部先 resolveTop 再叠 settings.json):
659
+ // 只调 applySettings(before, …) 是**错的** —— 它只叠 settings.json,
660
+ // 不会把 volatile 引用里的新值带进来。2026-10-16 真机暴露:日志报"热应用 0 项",
661
+ // 卡片里改了 botId 但内存里的 top 没变(要重启才生效)。
662
+ const after = buildTop(config, settingsStore.get());
663
+ top = after.top;
664
+ const diff = diffLive(before, top);
665
+ // 账号列表/监控范围变化(增删 email 或改 folders):让 watcher 下一轮用新列表,不用重启
666
+ const accountsChanged = accountsSig(before.accounts) !== accountsSig(top.accounts);
667
+ for (const fn of settingsListeners) {
668
+ try { fn(diff, top); } catch (e) { log0("warn", `运行时设置热应用失败: ${e?.message ?? e}`); }
669
+ }
670
+ // archive.mode 要同步改存储开关;其余 watcher 字段交给 applyRuntimeSettings
671
+ if (watcherRef) {
672
+ try { watcherRef.applyRuntimeSettings(diff); }
673
+ catch (e) { log0("warn", `watcher 应用运行时设置失败: ${e?.message ?? e}`); }
674
+ if (accountsChanged && typeof watcherRef.setAccounts === "function") {
675
+ watcherRef.setAccounts(top.accounts);
676
+ log("info", `watcher 账号列表/监控文件夹已热更新(${top.accounts.length} 个账号)`);
677
+ }
678
+ // 桥/浮动栏看到的状态也要跟着变(否则关掉开关后浮动栏还显示"运行中")
679
+ watcherStateRef.paused = watcherRef.paused === true;
680
+ watcherStateRef.reason = watcherStateRef.paused
681
+ ? "watcher 已暂停(watcher.enabled=false)"
682
+ : (watcherStateRef.locked ? null : watcherStateRef.reason);
683
+ }
684
+ return { diff, sources: after.sources };
685
+ };
686
+
687
+ /** 账号身份签名(email + 生效监控文件夹),用于判断 accounts 是否变化。
688
+ * 2026-10-30 起含 folders:只改监控文件夹(不动 email)也要触发 setAccounts 热应用,
689
+ * 否则用户改完文件夹要重启才生效。文件夹取与 tick 相同的归一化口径
690
+ * (folders 非空用 folders,否则 defaultFolder),两处口径不一致会出现"变了却没热应用"。 */
691
+ function accountsSig(accounts) {
692
+ return (accounts ?? [])
693
+ .map((a) => `${a.email}[${(Array.isArray(a.folders) && a.folders.length ? a.folders : [a.defaultFolder]).join("|")}]`)
694
+ .sort()
695
+ .join(",");
696
+ }
697
+
698
+ // ---- 宿主配置页的保存怎么进来(M6.0) ----
699
+ // 宿主把卡片里的保存提交进 volatile 引用后,会 emit **fiber 作用域**的
700
+ // `loader/volatile-update`(cordis-plugin-loader src/config/entry.ts:189),且**不重挂 fiber**。
701
+ // 监听它 → 重算分层 + 热应用,就是"改完立即生效"。
702
+ // 拿不到事件总线(旧宿主/单测)也不影响正确性:下一次 readRuntime() 一样是新值。
703
+ const onVolatileUpdate = () => {
704
+ try {
705
+ const { diff } = applySettingsChange();
706
+ log0("info", `宿主配置页更新已热应用(${diff.length} 项)`);
707
+ } catch (e) {
708
+ log0("warn", `宿主配置页更新热应用失败: ${e?.message ?? e}`);
709
+ }
710
+ };
711
+ try { if (typeof ctx.on === "function") ctx.on("loader/volatile-update", onVolatileUpdate); }
712
+ catch { /* 事件总线不可用 → 静默(下轮读取仍生效) */ }
713
+
714
+ // 声明"自带页面":dsh-settings 的 configure({auto:false}) —— 避免宿主再生成一份自动表单。
715
+ // settings 服务缺席(headless/精简组合)时整段跳过,不影响工具与 watcher。
716
+ //
717
+ // M6.1:这里同时做 **settings.json → 宿主配置页的一次性迁移**(D15)。
718
+ // 为什么必须是"一次性":两份可写真相必然漂移。迁移**成功后才**改名留档;
719
+ // 失败(或宿主没服务本命名空间)就保留文件继续兜底 —— 绝不删用户数据。
720
+ try {
721
+ if (typeof ctx.inject === "function") {
722
+ void Promise.resolve(ctx.inject(["settings"], async (sctx) => {
723
+ try {
724
+ if (typeof sctx.effect === "function") sctx.effect(() => sctx.settings.configure({ auto: false }, ctx.fiber));
725
+ else sctx.settings.configure({ auto: false }, ctx.fiber);
726
+ } catch (e) { log0("warn", `声明自带配置页失败: ${e?.message ?? e}`); }
727
+ try {
728
+ const legacyFile = settingsStore.file;
729
+ if (!settingsStore.importedTo && legacyFile && fs.existsSync(legacyFile)) {
730
+ const m = await migrateLegacyFile({
731
+ host: hostSettings,
732
+ file: legacyFile,
733
+ legacyValue: settingsStore.get(),
734
+ log: log0,
735
+ });
736
+ if (m.ok) {
737
+ // 关键:内存层必须立刻清空。否则本进程内 settings.json 仍然压住同名字段,
738
+ // "迁移完还是旧值"——用户会以为页面里的修改没生效。
739
+ settingsStore.markImported(m.renamedTo);
740
+ const applied = applySettingsChange();
741
+ log0("info", `settings.json 迁移完成(${m.reason}),热应用 ${applied.diff.length} 项`);
742
+ }
743
+ }
744
+ } catch (e) { log0("warn", `settings.json 迁移异常(已忽略): ${e?.message ?? e}`); }
745
+ })).catch(() => { /* 没有 settings 服务 */ });
746
+ }
747
+ } catch { /* 同上 */ }
748
+
749
+ // ---- mailbox_auth: 设备码授权 / 状态 / 登出 ----
750
+ const authDispose = ctx.tools.register(defineTool({
751
+ name: "mailbox_auth",
752
+ description:
753
+ "个人邮箱 OAuth2 授权管理。action=device: 发起设备码流,返回 microsoft.com 链接和验证码,交给用户;用户完成后调用 action=complete 领取 token。action=status: 各账户 token 新鲜度。action=signout: 删除本地 token。",
754
+ parameters: {
755
+ action: { type: "string", required: true, enum: ["device", "complete", "status", "signout"], description: "操作" },
756
+ account: accountParam,
757
+ },
758
+ output: textOutput({
759
+ userCode: { type: "string" },
760
+ verificationUri: { type: "string" },
761
+ statuses: { type: "array", items: { type: "object", additionalProperties: true } },
762
+ }),
763
+ async execute(args) {
764
+ switch (args.action) {
765
+ case "device": {
766
+ const acc = pickAccount(top, args.account);
767
+ const r = await deviceCodeStart(acc);
768
+ fs.writeFileSync(pendingPath(acc.alias), JSON.stringify({
769
+ deviceCode: r.state.deviceCode, deviceCodeAccount: acc.email,
770
+ clientId: acc.clientId, authority: acc.authority, scopes: acc.scopes,
771
+ userCode: r.userCode, startedAt: Date.now(),
772
+ }, null, 2));
773
+ return {
774
+ text:
775
+ `授权 ${acc.email}:\n` +
776
+ `1. 打开 ${r.verificationUri}\n` +
777
+ `2. 输入验证码 ${r.userCode}(约 ${r.expires} 秒内有效)\n` +
778
+ `完成后调用 mailbox_auth(action="complete") 领取 token。`,
779
+ userCode: r.userCode,
780
+ verificationUri: r.verificationUri,
781
+ };
782
+ }
783
+ case "complete": {
784
+ const acc = pickAccount(top, args.account) ?? top.accounts[0];
785
+ const p = pendingPath(acc.alias);
786
+ if (!fs.existsSync(p)) return { text: `没有进行中的设备码流;先调用 action=device(${acc.alias})` };
787
+ const st = JSON.parse(fs.readFileSync(p, "utf8"));
788
+ const res = await deviceCodePoll(st);
789
+ if (!res.ok) {
790
+ if (res.reason === "pending" || res.reason === "slow_down") {
791
+ return { text: `用户尚未完成授权(或服务器要求降速)。稍后重试 action=complete。${res.reason === "slow_down" ? " 已自动等待。" : ""}` };
792
+ }
793
+ if (res.reason === "expired") fs.unlinkSync(p);
794
+ return { text: `授权${res.reason === "declined" ? "被拒绝" : "已过期"}: ${res.reason}${res.detail ? " " + JSON.stringify(res.detail) : ""}。可重新 action=device。` };
795
+ }
796
+ fs.unlinkSync(p);
797
+ writeToken(top, { email: st.deviceCodeAccount, clientId: st.clientId }, res);
798
+ return { text: `${st.deviceCodeAccount} 授权成功,token 已保存。` };
799
+ }
800
+ case "status": {
801
+ const sts = tokenStatus(top);
802
+ // 「方便拿到 token」的最后一公里:状态里直接给出 token 文件路径。
803
+ // 原文只有本地 JSON 这一个来源(工具不回显 access_token,防止泄漏进对话上下文),
804
+ // 不告诉路径的话,用户只能翻文档才知道文件在哪(2026-10-17 用户反馈)。
805
+ return {
806
+ text: sts.map((s) =>
807
+ s.authorized
808
+ ? `${s.alias}(${s.email}): ${s.expired ? "已过期,需刷新" : `有效(余 ${Math.round(s.remainSeconds / 60)} 分钟)`}`
809
+ : `${s.alias}(${s.email}): 未授权`
810
+ ).join("\n")
811
+ + `\ntoken 目录:${top.tokenDir}(每账号一个 JSON:access_token/refresh_token/expires_at;access_token 只存文件,不经工具回显)`
812
+ + `\n${sts.map((s) => `${s.alias} → ${path.join(top.tokenDir, tokenSlug(s.email))}`).join("\n")}`,
813
+ statuses: sts.map((s) => ({ ...s, tokenFile: path.join(top.tokenDir, tokenSlug(s.email)) })),
814
+ };
815
+ }
816
+ case "signout": {
817
+ const sacc = pickAccount(top, args.account);
818
+ deleteToken(top, sacc);
819
+ return { text: `${sacc.email} 本地 token 已删除。` };
820
+ }
821
+ }
822
+ },
823
+ }));
824
+
825
+ // ---- mailbox_folders ----
826
+ const foldersDispose = ctx.tools.register(defineTool({
827
+ name: "mailbox_folders",
828
+ description: "列出账户的 IMAP 文件夹(名称/标志),并对每个文件夹取 MESSAGES/UNSEEN/UIDVALIDITY。只读。",
829
+ parameters: {
830
+ account: accountParam,
831
+ },
832
+ output: textOutput({ count: { type: "number" }, folders: { type: "array", items: { type: "object", additionalProperties: true } } }),
833
+ async execute(args) {
834
+ const acc = pickAccount(top, args.account);
835
+ const token = await getAccessToken(top, acc);
836
+ const client = new ImapClient(acc, token);
837
+ await client.connect();
838
+ try {
839
+ const folders = await client.listFolders();
840
+ const withInfo = [];
841
+ for (const f of folders) {
842
+ let st = {};
843
+ try { st = await client.status(f.name); } catch { /* 部分文件夹可能不允许 STATUS */ }
844
+ withInfo.push({ name: f.name, flags: f.flags, ...st });
845
+ }
846
+ return {
847
+ text: withInfo.map((f) =>
848
+ `${f.name} [${(f.flags ?? []).join(",")}] 共 ${f.messages ?? "?"} 封,未读 ${f.unseen ?? "?"},UIDVALIDITY ${f.uidvalidity ?? "?"}`).join("\n"),
849
+ count: withInfo.length,
850
+ folders: withInfo,
851
+ };
852
+ } finally { client.close(); }
853
+ },
854
+ }));
855
+
856
+ // ---- mailbox_resync(2026-10-31)----
857
+ const resyncDispose = ctx.tools.register(defineTool({
858
+ name: "mailbox_resync",
859
+ description: "重置账户(可选单文件夹)的同步水位并回填历史:下一轮轮询起把监控文件夹的全部邮件抓进本地库,≤重置时刻水位的邮件只入库不通知。用于让本地归档与邮箱内容保持一致。online 模式不落库,只重置水位。",
860
+ parameters: {
861
+ account: accountParam,
862
+ folder: { type: "string", description: "只重置这一个文件夹(大小写不敏感);缺省 = 该账户全部已跟踪文件夹" },
863
+ },
864
+ output: textOutput({ count: { type: "number" }, reset: { type: "array", items: { type: "object", additionalProperties: true } } }),
865
+ async execute(args) {
866
+ const acc = pickAccount(top, args.account);
867
+ const store = await ensureStore();
868
+ const out = store.resetSyncState({ account: acc.email, folder: args.folder });
869
+ log("info", `[${acc.email}] mailbox_resync: ${out.reset.map((r) => `${r.folder}(≤${r.mark})`).join(", ") || "(无已跟踪文件夹)"}`);
870
+ return {
871
+ text: out.reset.length
872
+ ? `已重置 ${out.reset.length} 个文件夹的水位,下一轮轮询起回填历史:\n` +
873
+ out.reset.map((r) => `- ${r.folder}:截止标记 uid≤${r.mark}(只入库不通知)`).join("\n") +
874
+ `\n(每轮最多 ${Math.round(top.maxMessagesPerCycle ?? 20)} 封,分多轮补完;可在浮动栏/归档里看到进度)`
875
+ : "该账户还没有已跟踪的文件夹(watcher 还没跑过第一轮),无需回填。",
876
+ count: out.reset.length,
877
+ reset: out.reset,
878
+ };
879
+ },
880
+ }));
881
+
882
+ // ---- mailbox_list ----
883
+ const listDispose = ctx.tools.register(defineTool({
884
+ name: "mailbox_list",
885
+ description: "列文件夹里最近的邮件信封(主题/发件人/日期/已读)。默认 INBOX、最近 25 封。unreadOnly=true 只列未读;since/until 为 ISO 日期。只读。",
886
+ parameters: {
887
+ account: accountParam,
888
+ folder: { type: "string", description: `默认 ${DEFAULTS.defaultFolder}` },
889
+ limit: { type: "number", description: "最多列多少封,默认 25,上限 100" },
890
+ unreadOnly: { type: "boolean", description: "只列未读" },
891
+ since: { type: "string", description: "起始日期(ISO 8601,含当日)" },
892
+ until: { type: "string", description: "截止日期(ISO 8601,不含当日)" },
893
+ },
894
+ output: textOutput({ total: { type: "number" }, mail: { type: "array", items: { type: "object", additionalProperties: true } } }),
895
+ async execute(args) {
896
+ const acc = pickAccount(top, args.account);
897
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 25, 10) || 25, 1), 100);
898
+ const token = await getAccessToken(top, acc);
899
+ const client = new ImapClient(acc, token);
900
+ await client.connect();
901
+ try {
902
+ await client.open(args.folder || acc.defaultFolder);
903
+ const uids = await client.uidSearch({
904
+ unseen: args.unreadOnly ? true : undefined,
905
+ since: args.since, until: args.until,
906
+ });
907
+ // 取最近的 limit 封:uids 升序,取尾部
908
+ const slice = uids.slice(-limit).reverse();
909
+ const envs = await client.fetchEnvelopes(slice);
910
+ return {
911
+ text: envs.map((e) =>
912
+ e.error
913
+ ? `uid=${e.uid} 取信封失败: ${e.error}`
914
+ : `${e.seen ? "已读" : "未读"} uid=${e.uid} [${e.date ?? "?"}] ${e.from ?? "?"} | ${e.subject ?? "(无主题)"}`).join("\n") || "没有匹配邮件",
915
+ total: uids.length,
916
+ mail: envs,
917
+ };
918
+ } finally { client.close(); }
919
+ },
920
+ }));
921
+
922
+ // ---- mailbox_read ----
923
+ const readDispose = ctx.tools.register(defineTool({
924
+ name: "mailbox_read",
925
+ description: `读一封邮件的完整正文(截断 ${DEFAULTS.bodyLimit} 字符)与附件清单;saveAttachments=true 时把附件落到 attachDir。默认只读(**不**改服务器已读状态):只在列表/摘要里扫一眼不该把邮件变已读。\n` +
926
+ `用户**明确要求查看某封邮件的内容/详情**时(例如"看看这封信说了什么""把验证码读出来"),应传 markSeen=true —— 这等于承认"我读了它",会把该封在服务器上标为已读,其他客户端也会同步看到已读;仅做筛选、摘要、批量处理时保持默认 false。`,
927
+ parameters: {
928
+ account: accountParam,
929
+ uid: { type: "number", required: true, description: "邮件 uid(来自 mailbox_list/mailbox_search)" },
930
+ folder: { type: "string", description: "邮件所在文件夹" },
931
+ saveAttachments: { type: "boolean", description: "是否把附件写到本地(默认 false)" },
932
+ markSeen: { type: "boolean", description: "读完是否标为已读(默认 false;开了就不会每次只读都改状态)" },
933
+ },
934
+ output: textOutput({
935
+ uid: { type: "number" },
936
+ subject: { type: "string" },
937
+ from: { type: "string" },
938
+ date: { type: "string" },
939
+ messageId: { type: "string" },
940
+ markedSeen: { type: "boolean" },
941
+ attachments: { type: "array", items: { type: "object", additionalProperties: true } },
942
+ saved: { type: "array", items: { type: "object", additionalProperties: true } },
943
+ }),
944
+ async execute(args) {
945
+ const acc = pickAccount(top, args.account);
946
+ const token = await getAccessToken(top, acc);
947
+ const client = new ImapClient(acc, token);
948
+ await client.connect();
949
+ try {
950
+ await client.open(args.folder || acc.defaultFolder);
951
+ const raw = await client.fetchFull(args.uid);
952
+ const parsed = parseMime(raw);
953
+ const body = parsed.bodyText.slice(0, top.bodyLimit);
954
+ const truncated = parsed.bodyText.length > top.bodyLimit;
955
+ // 验证码直接提到抬头(2026-11-26):正文里 2FA 码常在第 300+ 字,用户不想翻
956
+ const otp = digestLib.extractCode(digestLib.cleanText(parsed.bodyText), { subject: parsed.subject ?? "" });
957
+ const otpLine = otp?.code
958
+ ? `🔑 验证码 ${otp.code}${otp.ttlMinutes ? `(${otp.ttlMinutes} 分钟内有效)` : ""}\n`
959
+ : "";
960
+ let saved = [];
961
+ if (args.saveAttachments && parsed.attachments.length) {
962
+ // 只回清单(name/path/size/status):payload 是 Buffer,带进工具输出会变成
963
+ // "value is not lossless JSON"(2026-11-30 真机踩到)
964
+ saved = saveAttachments(parsed.attachments, top.attachDir, args.uid, { maxBytes: top.attachMaxBytes })
965
+ .map((m) => ({ name: m.name, path: m.path, size: m.size, status: m.status }));
966
+ }
967
+ // 超上限的附件要明说,别让用户以为都存下来了
968
+ const oversize = saved.filter((m) => m.status === "too-large");
969
+ const savedLine = saved.length
970
+ ? `\n已保存附件 ${saved.length - oversize.length}/${saved.length} 个到 ${path.dirname(saved[0].path)}` +
971
+ (oversize.length ? `;跳过 ${oversize.length} 个(超过单封 ${Math.round((top.attachMaxBytes ?? 0) / 1024 / 1024)} MB 上限):` +
972
+ oversize.map((m) => m.name).join("、") : "")
973
+ : "";
974
+ // R1(2026-11-29):已读状态双向 —— 默认不动,显式 markSeen 才回写服务器 + 本地
975
+ let markedSeen = false;
976
+ if (args.markSeen === true) {
977
+ try {
978
+ await client.setSeen(args.uid, true);
979
+ markedSeen = true;
980
+ const store = await ensureStore();
981
+ const ref = { account: acc.email, folder: args.folder || acc.defaultFolder, uid: args.uid };
982
+ if (store.getMessage(ref)) store.upsertMessage({ ...ref, seen: true });
983
+ } catch (e) {
984
+ log("warn", `标已读失败(不影响读信)uid=${args.uid}:${String(e?.message ?? e)}`);
985
+ }
986
+ }
987
+ return {
988
+ text:
989
+ `uid=${args.uid} ${parsed.subject ?? ""}\n` +
990
+ `From: ${parsed.from ?? "?"}\nDate: ${parsed.date ?? "?"}\n` + otpLine +
991
+ (markedSeen ? "已在服务器标为已读\n" : "") + `\n` +
992
+ (body || "(无正文)") + (truncated ? `\n…(正文已截断,共 ${parsed.bodyText.length} 字符)` : "") +
993
+ (parsed.attachments.length ? `\n\n附件 ${parsed.attachments.length} 个:\n` +
994
+ parsed.attachments.map((a) => ` - ${a.name} (${a.size} B, ${a.contentType})`).join("\n") : "") +
995
+ savedLine,
996
+ uid: args.uid,
997
+ subject: parsed.subject ?? "",
998
+ from: parsed.from ?? "",
999
+ date: parsed.date ?? "",
1000
+ messageId: parsed.messageId ?? "",
1001
+ attachments: parsed.attachments.map((a) => ({ name: a.name, size: a.size, contentType: a.contentType })),
1002
+ saved,
1003
+ markedSeen,
1004
+ };
1005
+ } finally { client.close(); }
1006
+ },
1007
+ }));
1008
+
1009
+ // ---- mailbox_search ----
1010
+ const searchDispose = ctx.tools.register(defineTool({
1011
+ name: "mailbox_search",
1012
+ description:
1013
+ "检索邮件。source=live(默认)直接查服务器 IMAP(快、看最新);source=archive 查本地归档(支持 q 关键词全文检索,可用范围取决于 archive.mode)。\n" +
1014
+ "live 支持 from/to/subject/text(正文任意位置)/since/until/unreadOnly —— 这些都是**服务端 SEARCH**,覆盖整个文件夹。" +
1015
+ "但如果条件里含中文,Outlook/Exchange 会拒绝服务端检索(实测 `A0004 BAD`),此时自动退化为「最近 200 封本地过滤」;" +
1016
+ "要全文找更早的中文邮件,用 source=archive + q。",
1017
+ parameters: {
1018
+ account: accountParam,
1019
+ folder: { type: "string", description: `默认 ${DEFAULTS.defaultFolder}` },
1020
+ from: { type: "string", description: "发件人(子串匹配)" },
1021
+ to: { type: "string", description: "收件人/抄送(子串匹配,仅 source=live)" },
1022
+ subject: { type: "string", description: "主题(子串匹配)" },
1023
+ text: { type: "string", description: "正文任意位置(IMAP TEXT;仅 source=live)。中文会退化为本地扫描最近 200 封" },
1024
+ since: { type: "string", description: "起始日期(ISO)" },
1025
+ until: { type: "string", description: "截止日期(ISO)" },
1026
+ unreadOnly: { type: "boolean", description: "只未读" },
1027
+ limit: { type: "number", description: "默认 25,上限 100" },
1028
+ source: { type: "string", enum: ["live", "archive"], description: "live=查服务器(默认);archive=查本地归档" },
1029
+ q: { type: "string", description: "关键词全文检索(仅 source=archive;live 用 text)" },
1030
+ tag: { type: "string", description: "标签过滤(仅 source=archive)" },
1031
+ },
1032
+ output: textOutput({ total: { type: "number" }, localScan: { type: "boolean" }, mail: { type: "array", items: { type: "object", additionalProperties: true } } }),
1033
+ async execute(args) {
1034
+ // ---- source=archive:本地归档(含关键词全文检索,M5) ----
1035
+ if ((args.source ?? "live") === "archive") {
1036
+ // text 在归档侧就是「全文」:没给 q 时直接当 q 用,别让调用方为两个名字困惑
1037
+ const r = await runArchiveSearch(m4Deps, args.q ? args : { ...args, q: args.text, text: undefined });
1038
+ // 本工具的输出 schema 只有 text/total/mail(additionalProperties:false)→ 只挑这几个
1039
+ return { text: r.text, total: r.total ?? 0, mail: r.mail ?? [] };
1040
+ }
1041
+ if (args.q) {
1042
+ return {
1043
+ text: "关键词全文检索只在 source=archive 下可用:服务器 IMAP 检索不支持任意词全文(它只能按发件人/主题/正文词/日期/未读)。\n请改用 mailbox_search(source=\"archive\", q=\"…\")(需要 archive.mode=metadata 或 full)。",
1044
+ total: 0, mail: [],
1045
+ };
1046
+ }
1047
+ if (args.tag) {
1048
+ return { text: "tag 过滤只在 source=archive 下可用(标签是本地元数据,服务器不知道)。", total: 0, mail: [] };
1049
+ }
1050
+ const acc = pickAccount(top, args.account);
1051
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 25, 10) || 25, 1), 100);
1052
+ const token = await getAccessToken(top, acc);
1053
+ const client = new ImapClient(acc, token);
1054
+ await client.connect();
1055
+ try {
1056
+ await client.open(args.folder || acc.defaultFolder);
1057
+ const found = await client.uidSearch({
1058
+ unseen: args.unreadOnly, since: args.since, until: args.until,
1059
+ from: args.from, to: args.to, subject: args.subject, body: args.text,
1060
+ });
1061
+ const uids = Array.isArray(found) ? found : [];
1062
+ const localScan = found?.localScan === true;
1063
+ const slice = uids.slice(-limit).reverse();
1064
+ const envs = await client.fetchEnvelopes(slice);
1065
+ const note = localScan
1066
+ ? "\n(条件含中文,服务端不支持 → 只在最近 200 封里本地过滤;更早的全文请用 source=archive)"
1067
+ : "";
1068
+ return {
1069
+ text: (envs.length
1070
+ ? envs.map((e) => e.error ? `uid=${e.uid} 取信封失败: ${e.error}` : `uid=${e.uid} [${e.date ?? "?"}] ${e.from ?? "?"} | ${e.subject ?? "(无主题)"}${e.seen ? "" : " (未读)"}`).join("\n")
1071
+ : "0 命中") + note,
1072
+ total: uids.length,
1073
+ localScan,
1074
+ mail: envs,
1075
+ };
1076
+ } finally { client.close(); }
1077
+ },
1078
+ }));
1079
+
1080
+ // ---- mailbox_send ----
1081
+ const sendDispose = ctx.tools.register(defineTool({
1082
+ name: "mailbox_send",
1083
+ description:
1084
+ "发信:to/cc/subject/body(纯文本),可选 html 正文与附件(路径数组,读本地文件)。" +
1085
+ "SMTP 走 STARTTLS+XOAUTH2,主服务器认证失败自动换备服务器。发信不可撤回,调用前确认收件人正确。\n" +
1086
+ "**回复某封邮件**时用 replyToUid(配合 folder)而不是自己拼收件人:工具会自动补 `Re: 主题`、" +
1087
+ "`In-Reply-To`/`References`(对方 Outlook 归到同一会话)、默认把原文逐行引用在正文末尾;" +
1088
+ "replyAll=true 时收件人取原 To+Cc 并去掉自己。此时 to/subject 可省略(从原信推导),body 写你新说的话即可。",
1089
+ parameters: {
1090
+ account: accountParam,
1091
+ to: { type: "array", items: { type: "string" }, description: "收件人列表(回复时可省略,从原信 From 推导)" },
1092
+ cc: { type: "array", items: { type: "string" }, description: "抄送" },
1093
+ bcc: { type: "array", items: { type: "string" }, description: "密送(不进头部,只进收件人)" },
1094
+ subject: { type: "string", description: "主题(回复时可省略,自动加 Re:)" },
1095
+ body: { type: "string", required: true, description: "纯文本正文(回复时写你新说的话,原文会另行引用)" },
1096
+ html: { type: "string", description: "HTML 正文(可选,与纯文本并列成 alternative)" },
1097
+ attachments: { type: "array", items: { type: "string" }, description: "本地文件路径数组" },
1098
+ // ---- R8(2026-11-30)回复链路 ----
1099
+ replyToUid: { type: "number", description: "要回复的那封邮件的 uid(与 folder 配套);给了它就自动补 Re:/In-Reply-To/References" },
1100
+ replyAll: { type: "boolean", description: "回复全部(原 To+Cc 去掉自己,默认 false 只回 From)" },
1101
+ quote: { type: "boolean", description: "是否在正文末尾引用原文(默认 true)" },
1102
+ },
1103
+ output: textOutput({
1104
+ server: { type: "string" },
1105
+ accepted: { type: "number" },
1106
+ messageId: { type: "string" },
1107
+ // B4(2026-11-29):是否已把同一份原文追加进「已发送」,以及落到了哪个文件夹
1108
+ appended: { type: "boolean" },
1109
+ sentFolder: { type: "string" },
1110
+ appendSource: { type: "string" },
1111
+ // R8:回复时的线程凭据,方便后续追问同一话题
1112
+ inReplyTo: { type: "string" },
1113
+ references: { type: "string" },
1114
+ }),
1115
+ async execute(args) {
1116
+ const acc = pickAccount(top, args.account);
1117
+ const token = await getAccessToken(top, acc);
1118
+ const attachments = (args.attachments ?? []).map((p) => ({
1119
+ name: path.basename(String(p)),
1120
+ payload: fs.readFileSync(String(p)),
1121
+ }));
1122
+ // ---- R8:回复模式先取原信,补线程头与收件人 ----
1123
+ let orig = null;
1124
+ let inReplyTo = null;
1125
+ let references = null;
1126
+ if (args.replyToUid !== undefined && args.replyToUid !== null) {
1127
+ const folder = args.folder || acc.defaultFolder;
1128
+ const client = new ImapClient(acc, token);
1129
+ await client.connect();
1130
+ try {
1131
+ await client.open(folder);
1132
+ orig = parseMime(await client.fetchFull(args.replyToUid));
1133
+ } finally { client.close(); }
1134
+ if (!orig.messageId) {
1135
+ // 没有 Message-ID 就串不进会话,但也不能因此发不出信:如实提示,照常发出
1136
+ log("warn", `原信 uid=${args.replyToUid} 没有 Message-ID,只能按新会话发送`);
1137
+ } else {
1138
+ inReplyTo = orig.messageId;
1139
+ references = orig.references ? `${orig.references} ${orig.messageId}` : orig.messageId;
1140
+ }
1141
+ }
1142
+ const derived = orig ? replyRecipients(orig, { self: acc.email, replyAll: args.replyAll === true }) : null;
1143
+ const toAddrs = (Array.isArray(args.to) && args.to.length ? args.to : derived?.to ?? []).filter(Boolean);
1144
+ const ccAddrs = Array.isArray(args.cc) ? args.cc : (derived?.cc ?? []);
1145
+ if (!toAddrs.length) {
1146
+ return {
1147
+ text: orig
1148
+ ? `没能从 uid=${args.replyToUid} 的 From 头里解析出收件人地址(${orig.from ?? "空"}),请显式传 to。`
1149
+ : "需要 to(收件人列表);或给 replyToUid 让工具从原信推导。",
1150
+ };
1151
+ }
1152
+ const subject = String(args.subject ?? "").trim() || (orig ? replySubject(orig.subject) : "");
1153
+ if (!subject) return { text: "需要 subject(主题);或给 replyToUid 自动生成 Re: 主题。" };
1154
+ const quoted = orig && args.quote !== false ? quoteOriginal(orig) : "";
1155
+ const bodyText = `${String(args.body ?? "")}${quoted}`;
1156
+ const raw = buildMessage({
1157
+ from: acc.email,
1158
+ to: toAddrs,
1159
+ cc: ccAddrs,
1160
+ bcc: args.bcc,
1161
+ subject,
1162
+ bodyText,
1163
+ bodyHtml: args.html,
1164
+ attachments,
1165
+ inReplyTo,
1166
+ references,
1167
+ });
1168
+ let lastErr;
1169
+ for (const host of uniqueServers(acc)) {
1170
+ try {
1171
+ const r = await sendMail({
1172
+ user: acc.email, token,
1173
+ host, port: acc.smtpPort,
1174
+ to: toAddrs, cc: ccAddrs, bcc: args.bcc,
1175
+ rawMime: raw.toString("utf8"),
1176
+ });
1177
+ const messageId = genIdFor(raw) ?? "";
1178
+ // B4(2026-11-29):把**同一份原文**追加进「已发送」。
1179
+ // 只是发送成功后的补充动作:失败不影响「已发出」这个事实,只在文本里提示。
1180
+ let appended = false, sentFolder = null, appendError = null, appendSource = "";
1181
+ try {
1182
+ const client = new ImapClient(acc, token);
1183
+ await client.connect();
1184
+ try {
1185
+ sentFolder = await client.findSentFolder();
1186
+ const exist = await client.findUidByMessageId(sentFolder, messageId);
1187
+ if (exist) {
1188
+ appended = true; // 已经有了(重试/兜底路径)→ 不重复追加
1189
+ appendSource = "message-id";
1190
+ } else {
1191
+ // Outlook/Exchange 收下 SMTP 的这封信后,会自己往「已发送」存一份,
1192
+ // 而且**重新生成 Message-ID**(2026-11-29 真机实测,延迟约 1~2 秒),
1193
+ // 所以只按 Message-ID 查重挡不住,先等它一会儿再按「主题+收件人+时间窗」找一遍。
1194
+ let dup = await client.findJustSent(sentFolder, {
1195
+ subject, to: [...toAddrs, ...ccAddrs],
1196
+ }).catch(() => null);
1197
+ for (let i = 0; i < 3 && !dup; i += 1) {
1198
+ await new Promise((res) => setTimeout(res, 500));
1199
+ dup = await client
1200
+ .findJustSent(sentFolder, { subject, to: [...toAddrs, ...ccAddrs] })
1201
+ .catch(() => null);
1202
+ }
1203
+ if (dup) {
1204
+ appended = true; // 服务器已自动保存 → 不再追加,否则 Sent 里会出现两份
1205
+ appendSource = "server-autosave";
1206
+ } else {
1207
+ await client.append(sentFolder, raw);
1208
+ appended = true;
1209
+ appendSource = "append";
1210
+ }
1211
+ }
1212
+ } finally {
1213
+ client.close();
1214
+ }
1215
+ } catch (e) {
1216
+ appendError = String(e?.message ?? e);
1217
+ log("warn", `已发出但未能存入「已发送」(${acc.email}):${appendError}`);
1218
+ }
1219
+ const note = !appended
1220
+ ? `\n⚠️ 已发出,但没能存进「已发送」:${appendError ?? "未知原因"}(收件人已收到,不影响发送)`
1221
+ : appendSource === "server-autosave"
1222
+ ? `\n「${sentFolder}」里已有服务器自动保存的副本,未重复追加`
1223
+ : appendSource === "message-id"
1224
+ ? `\n「${sentFolder}」里已有同一封(Message-ID 命中),未重复追加`
1225
+ : `\n已存入「${sentFolder}」${messageId ? `(Message-ID ${messageId})` : ""}`;
1226
+ const replyNote = inReplyTo ? `\n已作为回复发出(In-Reply-To: ${inReplyTo})` : "";
1227
+ return {
1228
+ text: `已发送到 ${r.accepted} 个收件人(${host}): ${toAddrs.join(", ")}${note}${replyNote}`,
1229
+ server: r.server, accepted: r.accepted,
1230
+ messageId,
1231
+ appended, sentFolder: sentFolder ?? "",
1232
+ appendSource,
1233
+ inReplyTo: inReplyTo ?? "",
1234
+ references: references ?? "",
1235
+ };
1236
+ } catch (e) {
1237
+ lastErr = e;
1238
+ }
1239
+ }
1240
+ return { text: `发信失败: ${String(lastErr?.message ?? lastErr)}` };
1241
+ },
1242
+ }));
1243
+
1244
+ // ---- 读宿主服务的公共姿势见文件上部(probe / withTimeout,设置层之前) ----
1245
+
1246
+ /** 分层后的当前值 + 每个值是谁说了算(与生效顺序一致,见 currentSources)。 */
1247
+ const layerRows = () => {
1248
+ const n = top.notify, w = top.watcher, a = top.archive, s = currentSources();
1249
+ return [
1250
+ `通知开关 notify.enabled = ${n.enabled} [${sourceLabel(s["notify.enabled"])}]`,
1251
+ `通知方式 notify.channel = ${n.channel} [${sourceLabel(s["notify.channel"])}]`,
1252
+ `投递机器人 notify.botId = ${looksLikeBotToken(n.botId) ? `${maskSecret(n.botId)} ⚠️这是 token,不是 botId` : (n.botId || "(未填→自动发现)")} [${sourceLabel(s["notify.botId"])}]`,
1253
+ `投递目标 notify.targetId = ${n.targetId || "(未填→自动发现)"} [${sourceLabel(s["notify.targetId"])}]`,
1254
+ `重要度阈值 notify.importanceThreshold = ${n.importanceThreshold} [${sourceLabel(s["notify.importanceThreshold"])}]`,
1255
+ `合并条数 notify.batch = ${n.batch} [${sourceLabel(s["notify.batch"])}]`,
1256
+ `验证码明文 notify.includeCodes = ${n.includeCodes !== false}${n.includeCodes === false ? "(推送里不显示验证码)" : "(推送里显示 🔑 验证码)"} [${sourceLabel(s["notify.includeCodes"])}]`,
1257
+ `静音时段 notify.quietHours = ${n.quietHours ?? "(无)"} [${sourceLabel(s["notify.quietHours"])}]`,
1258
+ `每日汇总开关 notify.dailyDigest.enabled = ${n.dailyDigest.enabled} [${sourceLabel(s["notify.dailyDigest.enabled"])}]`,
1259
+ `每日汇总时间 notify.dailyDigest.at = ${n.dailyDigest.at} [${sourceLabel(s["notify.dailyDigest.at"])}]`,
1260
+ `跳过关键词 notify.filter.skip = ${n.filter.skip.length ? n.filter.skip.join(", ") : "(无)"} [${sourceLabel(s["notify.filter.skip"])}]`,
1261
+ `只看关键词 notify.filter.only = ${n.filter.only.length ? n.filter.only.join(", ") : "(无)"} [${sourceLabel(s["notify.filter.only"])}]`,
1262
+ `watcher 开关 watcher.enabled = ${w.enabled} [${sourceLabel(s["watcher.enabled"])}]`,
1263
+ `轮询间隔 watcher.pollIntervalSeconds = ${top.pollIntervalSeconds}s [${sourceLabel(s["watcher.pollIntervalSeconds"])}]`,
1264
+ `归档模式 archive.mode = ${a.mode} [${sourceLabel(s["archive.mode"])}]`,
1265
+ `抓正文抽摘要 archive.snippet = ${a.snippet} [${sourceLabel(s["archive.snippet"])}]`,
1266
+ `原文保留天数 archive.retentionDays = ${a.retentionDays} [${sourceLabel(s["archive.retentionDays"])}]`,
1267
+ `原文大小上限 archive.maxBytes = ${a.maxBytes} [${sourceLabel(s["archive.maxBytes"])}]`,
1268
+ `元数据维护窗口 archive.maintenanceDays = ${a.maintenanceDays}${a.maintenanceDays > 0 ? " 天" : "(关闭,库只增不减)"} [${sourceLabel(s["archive.maintenanceDays"])}]`,
1269
+ `正文截断 mail.bodyLimit = ${top.bodyLimit} 字符 [${sourceLabel(s["mail.bodyLimit"])}]`,
1270
+ `附件落盘上限 mail.attachMaxBytes = ${top.attachMaxBytes > 0 ? `${Math.round(top.attachMaxBytes / 1048576)} MB` : "(不限)"} [${sourceLabel(s["mail.attachMaxBytes"])}]`,
1271
+ ].join("\n");
1272
+ };
1273
+
1274
+ // ---- 通道自测(2026-11-30):配置页「发测试消息」按钮与 mailbox_notify action=test 共用 ----
1275
+ // 以前这段逻辑只活在工具分支里,配置页想加个按钮就得复制一份 —— 复制就有分歧。
1276
+ // 这里返回结构化结果,工具负责渲染成中文段落,桥负责原样给前端。
1277
+ async function notifyTestCore({ top: t = top, im: imSvc = null, nowMs = Date.now() } = {}) {
1278
+ if (!imSvc) return { ok: false, code: "im-not-installed", message: "dshIm 服务未就绪,无法测试投递。" };
1279
+ if (looksLikeBotToken(t?.notify?.botId)) {
1280
+ return { ok: false, code: "bot-id-is-token", message: "notify.botId 里填的是 Telegram bot token,不是 dsh-im 的 bot id。" };
1281
+ }
1282
+ if (String(t?.notify?.channel ?? "") === "local") {
1283
+ return { ok: false, code: "local-only", message: "当前通知方式=local(只在 DSH 内留痕),不投递。" };
1284
+ }
1285
+ const resolved = await resolveImTarget(imSvc, { botId: t?.notify?.botId, targetId: t?.notify?.targetId, requireExisting: true });
1286
+ if (!resolved.ok) {
1287
+ return {
1288
+ ok: false, code: "no-target", reason: resolved.reason,
1289
+ candidates: (resolved.candidates ?? []).slice(0, 6).map((c) => `${c.botId}/${c.targetId}`),
1290
+ message: `找不到可投递目标(${resolved.reason})。`,
1291
+ };
1292
+ }
1293
+ const stamp = new Date(nowMs).toLocaleString();
1294
+ const text = `📬 mailbox 测试消息\n通道验证于 ${stamp}\nbot=${resolved.botId} target=${resolved.targetId}(来源 ${resolved.source})`;
1295
+ try {
1296
+ const res = await withTimeout(Promise.resolve(imSvc.send(resolved.botId, resolved.targetId, text)), 8000, "send");
1297
+ if (res && res.sent === false) {
1298
+ return { ok: false, code: "send-refused", botId: resolved.botId, targetId: resolved.targetId, stamp, message: `投递被拒:sent=false(目标 ${resolved.targetId})` };
1299
+ }
1300
+ return {
1301
+ ok: true, code: "sent", botId: resolved.botId, targetId: resolved.targetId,
1302
+ source: resolved.source, stamp,
1303
+ message: `测试消息已提交:bot=${resolved.botId} target=${resolved.targetId}(${stamp})`,
1304
+ };
1305
+ } catch (e) {
1306
+ return { ok: false, code: "send-failed", botId: resolved.botId, targetId: resolved.targetId, message: `测试投递失败: ${e?.message ?? e}` };
1307
+ }
1308
+ }
1309
+
1310
+ // ---- mailbox_notify: 通知渠道 + 运行时设置(M3.3 阶段一) ----
1311
+ // 这就是「配置页」在 agentic harness 里的形态:用户通过对话完成配置,
1312
+ // 改完 **下一轮(≤60s)生效,不用重启 DSH**。
1313
+ const notifyDispose = ctx.tools.register(defineTool({
1314
+ name: "mailbox_notify",
1315
+ description:
1316
+ "邮件通知的配置入口。action=status:看当前配置与每个值的来源层(宿主配置页 / settings.json 过渡层 / cordis / 默认)、以及**最近一轮抓取与去向**;" +
1317
+ "action=targets:列出 dsh-im 里可用的投递目标(listBots→listTargets),多目标时列出来供选择;" +
1318
+ "action=test:立刻往已选目标发一条测试消息(验证通道,不必等真邮件);" +
1319
+ "action=set-target:选定 botId/targetId;**免重启**;action=set:批量设置任意可配置项(如 notify.channel 或改阈值);**免重启**;" +
1320
+ "action=off/on:只关/开通知(off 时进入只留痕模式,归档不受影响);" +
1321
+ "action=reset:清空用户覆盖,回到 cordis 部署层。写入目标是**宿主配置页**(M6.1:与设置→插件里的卡片是同一份真相;宿主没有 settings 服务时才退回 settings.json)。结构性字段(accounts/tokenDir/host/port)只能改 cordis.patch.yml 并重启。",
1322
+ parameters: {
1323
+ action: {
1324
+ type: "string", required: true,
1325
+ enum: ["status", "targets", "explain", "test", "set-target", "set", "off", "on", "reset"],
1326
+ description: "status 查看 / targets 列候选 / explain 解释某封邮件的评分 / test 发测试消息 / set-target 选定 / set 批量设置 / off 关 / on 开 / reset 清空",
1327
+ },
1328
+ uid: { type: "number", description: "邮件 uid(action=explain 用,从 mailbox_list 或日报队列里取)" },
1329
+ botId: { type: "string", description: "投递机器人 ID(action=set-target 用)" },
1330
+ targetId: { type: "string", description: "投递目标 ID(action=set-target 用)" },
1331
+ patch: { type: "object", additionalProperties: true, description: "要设置的字段对象,如 {\"notify.importanceThreshold\":70}" },
1332
+ },
1333
+ output: textOutput({
1334
+ state: { type: "string" },
1335
+ profile: { type: "string" },
1336
+ imInstalled: { type: "boolean" },
1337
+ settingsFile: { type: "string" },
1338
+ settings: { type: "object", additionalProperties: true },
1339
+ sources: { type: "object", additionalProperties: true },
1340
+ applied: { type: "array", items: { type: "object", additionalProperties: true } },
1341
+ writeTarget: { type: "string" },
1342
+ availableTargets: { type: "array", items: { type: "object", additionalProperties: true } },
1343
+ // targets:机器人数量(0 = 没接机器人;>0 但 availableTargets 为空 = 接了但还没有投递目标)
1344
+ bots: { type: "number" },
1345
+ delivered: { type: "boolean" },
1346
+ // explain:某封邮件的评分与判定结果
1347
+ // (2026-10-23:verdict 此前未声明,被 dsh-tools 0.2.1-rc.2 的输出校验整次拒掉)
1348
+ score: { type: "number" },
1349
+ threshold: { type: "number" },
1350
+ verdict: { type: "string" },
1351
+ }),
1352
+ async execute(args) {
1353
+ const im = probe(ctx, "dshIm");
1354
+ const base = checkImStateSync(top, ctx);
1355
+ const settingsFile = path.join(top.dataDir, "settings.json");
1356
+
1357
+ switch (args.action) {
1358
+ case "status": {
1359
+ const hs = hostState();
1360
+ const lines = [
1361
+ `profile: ${base.profile} IM 服务: ${base.imInstalled ? "已就绪" : "未就绪"}`,
1362
+ `通知状态: ${base.state}`,
1363
+ hs.ok
1364
+ ? `设置真相: 宿主配置页(命名空间 ${MAILBOX_NS} · volatile 节点 ${VOLATILE_KEY} · revision ${hs.revision}`
1365
+ + ` · 覆盖字段 ${hostSettings.overriddenPaths().size} 个 · 自带页面 ${hs.autoGenerate === false ? "已声明" : "未声明"})`
1366
+ : `设置真相: settings.json(宿主配置页不可用:${hostSettings.available() ? hs.reason : "没有 settings 服务"})`,
1367
+ settingsStore.importedTo
1368
+ ? `settings.json: 已迁移留档 → ${settingsStore.importedTo}`
1369
+ : `settings.json: ${settingsFile}(存在:${fs.existsSync(settingsFile) ? "是" : "否"} · 修订号 ${settingsStore.rev})`,
1370
+ "",
1371
+ layerRows(),
1372
+ ];
1373
+ // 最近一轮 watcher:用户问"为什么没提醒"时,这一行给出因果(抓了几封 / 去哪了)
1374
+ const tick = watcherRef?.lastTick;
1375
+ if (tick) {
1376
+ const fetched = (tick.results ?? []).reduce((n, r) => n + (r?.total ?? 0), 0);
1377
+ lines.push(
1378
+ "",
1379
+ `最近一轮:${tick.now ? new Date(tick.now).toLocaleString() : "(未知时间)"}`
1380
+ + ` · 抓取 ${fetched} 封 · 失败 ${tick.failures ?? 0}`
1381
+ + (tick.digest ? ` · 日报:${tick.digest.reason ?? "已发"}${tick.digest.count ? `(${tick.digest.count} 封)` : ""}` : "")
1382
+ + (tick.paused ? " · watcher 已暂停" : ""),
1383
+ );
1384
+ }
1385
+ // 本地痕迹:没有 IM 通道时,这是唯一能看见"有新邮件"的地方(浮动栏 M6.4 的数据源)
1386
+ try {
1387
+ const st = watcherRef?.store;
1388
+ if (st) {
1389
+ const recent = st.listNotices({ limit: 3 }) ?? [];
1390
+ lines.push(`本地留痕:${recent.length ? recent.map((n) => `[${n.kind}] ${n.title ?? n.body ?? ""}`.trim()).join(" · ") : "(暂无)"}`
1391
+ + ` · 日报积压 ${st.digestQueueSize()} 封(到点会汇总发送)`);
1392
+ // "为什么没提醒"的直接答案:把队列里的分数摊开给用户看
1393
+ const q = describeDigestQueue(st.listDigestQueue({ limit: 6 }) ?? [], top.notify.importanceThreshold);
1394
+ if (q) lines.push(q);
1395
+ }
1396
+ } catch { /* store 未就绪时忽略 */ }
1397
+ if (base.state === "pending-auto-discovery") {
1398
+ lines.push("", "⚠️ 未指定投递目标 ⇒ **不会有任何 IM 提醒**(邮件仍会入库/留痕)。",
1399
+ " 目标在 dsh-im 的「投递设置 → 新建目标」里创建(给机器人发消息不会自动创建);",
1400
+ " 建好后用 action=\"targets\" 看候选 → action=\"set-target\" 选定;action=\"test\" 可验证投递。");
1401
+ }
1402
+ // 已填目标 ≠ 目标存在:拿 dsh-im 的真实列表核一遍(2026-10-16:有人把展示名/token 填了进去)
1403
+ if (looksLikeBotToken(top.notify.botId)) {
1404
+ lines.push("", "🚫 `notify.botId` 里是 **Telegram bot token**(不是 dsh-im 的 bot id):",
1405
+ " · 它现在**明文**存在 cordis.patch.yml 里,也会显示在配置页上;",
1406
+ " · token 应该填在 **DSH → 设置 → IM机器人** 的接入表单里;",
1407
+ " · 强烈建议去 @BotFather 用 `/revoke` 换一个新 token(旧的已落到配置文件与截图);",
1408
+ " · 本字段留空(自动发现)或填 dsh-im 给出的 bot id。");
1409
+ }
1410
+ if (im) {
1411
+ try {
1412
+ const resolved = await withTimeout(
1413
+ Promise.resolve(resolveImTarget(im, { botId: top.notify.botId, targetId: top.notify.targetId, requireExisting: true })),
1414
+ 5000, "resolveImTarget",
1415
+ );
1416
+ if (!resolved.ok) {
1417
+ const cands = (resolved.candidates ?? []).slice(0, 6).map((c) => `${c.botId}/${c.targetId}`).join(" · ");
1418
+ lines.push("", `⚠️ 当前填的目标在 dsh-im 里**找不到**(${resolved.reason})⇒ 通知发不出去,只会留痕。`,
1419
+ cands ? ` 真实候选:${cands}` : " 现在没有任何候选 —— 到 设置 → IM机器人 → 该机器人 →「投递设置」→「新建目标」建一个(给机器人发消息不会自动创建)。",
1420
+ " 用 action=targets 看全部,再 action=set-target 选定;action=test 可直接验证投递。");
1421
+ } else {
1422
+ lines.push(`✅ 投递目标已核对:dsh-im 里存在 ${resolved.botId}/${resolved.targetId}(来源 ${resolved.source})`);
1423
+ }
1424
+ } catch (e) {
1425
+ lines.push("", `⚠️ 目标校验失败: ${e?.message ?? e}`);
1426
+ }
1427
+ }
1428
+ if (!base.imInstalled) {
1429
+ lines.push("", "⚠️ dshIm 未就绪:通知会退化为「只留痕」,归档与水位不受影响。", " 若已安装 @xmanrui/dsh-im,重启 DSH 后再看本状态。");
1430
+ }
1431
+ return { text: lines.join("\n"), state: base.state, profile: base.profile, imInstalled: base.imInstalled, settingsFile, settings: effectiveSettings(), sources: currentSources() };
1432
+ }
1433
+
1434
+ case "explain": {
1435
+ // 解释"这封邮件为什么是这个分"(2026-10-16 用户要求:reasons 一直在算但从未暴露)
1436
+ const uid = Number(args.uid);
1437
+ if (!Number.isFinite(uid) || uid <= 0) {
1438
+ return { text: "需要 uid(正整数),例如 action=\"explain\" uid=1001。", state: base.state };
1439
+ }
1440
+ const st = watcherRef?.store;
1441
+ if (!st) return { text: "存储未就绪(需要 watcher 已启动)。", state: base.state };
1442
+ const msg = st.getMessage({ account: top.accounts[0]?.email ?? "", folder: "INBOX", uid });
1443
+ if (!msg) return { text: `未找到 uid=${uid}(可能还没入库,或不在 INBOX)。`, state: base.state };
1444
+ const scored = scoreMessage(msg, { rules: top.tags.rules, knownDomains: top.knownDomains });
1445
+ const threshold = top.notify.importanceThreshold;
1446
+ const verdict = scored.score >= threshold ? "即时推送" : "进日报缓冲";
1447
+ const lines = [
1448
+ `uid=${uid} · ${String(msg.subject ?? "(无主题)").slice(0, 60)}`,
1449
+ `评分:${scored.score}(阈值 ${threshold} ⇒ ${verdict})`,
1450
+ ];
1451
+ if (scored.reasons.length) {
1452
+ lines.push("", "命中项:");
1453
+ for (const r of scored.reasons) lines.push(` · ${r}`);
1454
+ } else {
1455
+ lines.push("", "未命中任何加分项(验证码 +70 / 行动词 +25 / 附件 +10 / 规则标签 +20 / 已知域名 +15)。");
1456
+ }
1457
+ if (scored.promo) lines.push("", "⚠️ 疑似营销邮件(分数被压到 ≤20)。");
1458
+ return { text: lines.join("\n"), state: base.state, score: scored.score, threshold, verdict };
1459
+ }
1460
+
1461
+ case "test": {
1462
+ // 验证投递通道是否真的能发出去(用户排错用:不用等真邮件)
1463
+ // 逻辑本体在 notifyTestCore —— 配置页的「发测试消息」按钮走同一条路径,避免两处分歧。
1464
+ const r = await notifyTestCore({ top, im });
1465
+ if (r.code === "bot-id-is-token") {
1466
+ return {
1467
+ text: "⛔ 先修配置:`notify.botId` 里填的是 **Telegram bot token**,而本字段要的是 **dsh-im 的 bot id**。\n"
1468
+ + " · token 请填在 DSH → 设置 → IM机器人 的接入表单;然后 action=\"targets\" 会列出 botId/targetId;\n"
1469
+ + " · 用 action=\"set-target\" 选定真实 id,再回来 action=\"test\";\n"
1470
+ + " · 该 token 现已明文落盘,建议去 @BotFather `/revoke` 更换。",
1471
+ state: base.state, delivered: false,
1472
+ };
1473
+ }
1474
+ if (r.code === "im-not-installed") return { text: "dshIm 服务未就绪,无法测试投递。", state: "im-not-installed" };
1475
+ if (r.code === "local-only") {
1476
+ return { text: "当前通知方式=local(只在 DSH 内留痕),不投递。要真发消息请先 action=set 把 notify.channel 改成 auto 或 im。", state: base.state };
1477
+ }
1478
+ if (r.code === "no-target") {
1479
+ const cands = (r.candidates ?? []).join(" · ");
1480
+ return {
1481
+ text: `找不到可投递目标(${r.reason})。`
1482
+ + (cands ? `\n当前候选:${cands}` : "\n现在 dsh-im 里没有任何候选 —— 先到 设置 → IM机器人 接入一个机器人。"),
1483
+ state: base.state, delivered: false,
1484
+ };
1485
+ }
1486
+ if (r.code === "send-refused") return { text: `投递被拒:sent=false(目标 ${r.targetId})`, state: base.state };
1487
+ if (r.code === "send-failed") return { text: r.message, state: base.state, delivered: false };
1488
+ return { text: `✅ ${r.message}`, state: base.state, delivered: true };
1489
+ }
1490
+
1491
+ case "targets": {
1492
+ if (!im || typeof im.listBots !== "function") {
1493
+ return { text: "dshIm 服务未就绪,拿不到目标列表。\n若已安装 @xmanrui/dsh-im,请重启 DSH 后用 action=status 确认 IM 服务为「已就绪」。", state: "im-not-installed", profile: base.profile, imInstalled: false, availableTargets: [] };
1494
+ }
1495
+ let bots = [];
1496
+ try { bots = (await withTimeout(Promise.resolve(im.listBots()), 5000, "listBots")) ?? []; }
1497
+ catch (e) { return { text: `列出机器人失败: ${e?.message ?? e}`, state: "error" }; }
1498
+ const rows = [];
1499
+ for (const b of bots) {
1500
+ const botId = typeof b === "string" ? b : (b?.botId ?? b?.id);
1501
+ if (!botId) continue;
1502
+ const botName = typeof b === "string" ? "" : (b?.name ?? "");
1503
+ let targets = [];
1504
+ try { targets = (await withTimeout(Promise.resolve(im.listTargets(botId)), 5000, `listTargets(${botId})`)) ?? []; }
1505
+ catch { continue; }
1506
+ for (const t of targets) {
1507
+ const tid = t?.targetId ?? t?.id;
1508
+ if (tid) rows.push({ botId, targetId: tid, name: t?.name ?? "", kind: t?.kind ?? "", botName });
1509
+ }
1510
+ }
1511
+ if (!rows.length) {
1512
+ // 2026-10-16:必须区分"没接机器人"与"接了但没有投递目标"——两者的下一步完全不同。
1513
+ // 实测教训:给机器人发消息**不会**创建投递目标;target 是 dsh-im 里的显式对象,
1514
+ // 要在面板的「投递设置 → 新建目标」里建,id 由 dsh-im 生成(形如 tgt_xxxx)。
1515
+ if (bots.length) {
1516
+ const names = bots.map((b) => (typeof b === "string" ? b : `@${String(b?.name ?? b?.botId ?? "").replace(/^@/, "")}`)).join(" · ");
1517
+ return {
1518
+ text: `机器人已接入(${bots.length} 个:${names}),但**还没有投递目标**(给机器人发消息不会自动创建)。\n`
1519
+ + " ① DSH → 设置 → IM机器人 → 选该机器人 → **「投递设置」** → 「新建目标」;\n"
1520
+ + " ② 从「已聊过的会话」里选一个(只支持已建立会话的私聊),保存;\n"
1521
+ + " ③ 目标 id 由 dsh-im 生成(形如 tgt_xxxx);回来重跑本命令或用配置页的「刷新 dsh-im 候选」下拉选择;\n"
1522
+ + " ④ action=\"test\" 验证投递(也可在 dsh-im 那边点「测试投递目标」)。",
1523
+ state: "no-targets", profile: base.profile, imInstalled: true, availableTargets: [], bots: bots.length,
1524
+ };
1525
+ }
1526
+ return {
1527
+ text: "dsh-im 里还没有接入任何机器人。\n请先到 DSH → 设置 → IM机器人 里接入一个(Telegram 需要 BotFather 的 token),再回来执行 action=targets。",
1528
+ state: "no-bots", profile: base.profile, imInstalled: true, availableTargets: [], bots: 0,
1529
+ };
1530
+ }
1531
+ const lines = [`可选投递目标 ${rows.length} 个:`, ""];
1532
+ rows.forEach((r, i) => {
1533
+ const label = [r.botName, r.name, r.kind].filter(Boolean).join(" · ");
1534
+ lines.push(` ${i + 1}. botId="${r.botId}" targetId="${r.targetId}"${label ? ` (${label})` : ""}`);
1535
+ });
1536
+ lines.push("", "选定后用 action=set-target 传入 botId/targetId,改完下一轮生效,不需要重启。");
1537
+ return { text: lines.join("\n"), state: "ok", profile: base.profile, imInstalled: true, availableTargets: rows };
1538
+ }
1539
+
1540
+ case "set-target": {
1541
+ const botId = String(args.botId ?? "").trim();
1542
+ const targetId = String(args.targetId ?? "").trim();
1543
+ if (!botId || !targetId) return { text: "需要同时提供 botId 与 targetId。先用 action=targets 看可选列表。", state: "missing-args" };
1544
+ // 能验证就验证:避免把不存在的目标写进去,然后Notification 全都发不出去还不知道为什么
1545
+ if (im && typeof im.listTargets === "function") {
1546
+ try {
1547
+ const targets = (await withTimeout(Promise.resolve(im.listTargets(botId)), 5000, `listTargets(${botId})`)) ?? [];
1548
+ const hit = targets.find((t) => (t?.targetId ?? t?.id) === targetId);
1549
+ if (!hit) {
1550
+ const known = targets.map((t) => t?.targetId ?? t?.id).filter(Boolean).join(", ");
1551
+ return { text: `目标 "${targetId}" 不属于机器人 "${botId}"。该机器人可用目标:${known || "(无)"}`, state: "target-not-found" };
1552
+ }
1553
+ } catch (e) {
1554
+ // 验证失败不阻塞:也许只是 listTargets 暂时不可用。写进去,由后续投递结果说话
1555
+ log0("warn", `set-target 校验跳过(listTargets 失败): ${e?.message ?? e}`);
1556
+ }
1557
+ }
1558
+ const w = await persistSettings({ notify: { botId, targetId } });
1559
+ if (!w.ok) return { text: writeFailure(w), state: w.conflict ? "conflict" : "write-failed" };
1560
+ const applied = await applyAfterWrite(w.via);
1561
+ return {
1562
+ text: `已选定投递目标 ${botId}/${targetId},写入 ${writeTargetText(w.via)}。\n下一轮(≤${top.pollIntervalSeconds}s)生效,**不需要重启**。`,
1563
+ state: "configured", profile: base.profile, imInstalled: base.imInstalled,
1564
+ settingsFile, settings: effectiveSettings(), sources: currentSources(),
1565
+ applied: applied.diff, availableTargets: [{ botId, targetId }], writeTarget: w.via,
1566
+ };
1567
+ }
1568
+
1569
+ case "set": {
1570
+ const patch = args.patch;
1571
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
1572
+ return { text: `请用 patch 传一个对象,例如 {"notify.importanceThreshold":70}。可配置项:\n${SETTINGS_FIELDS.map((f) => ` ${f.path}`).join("\n")}`, state: "missing-args" };
1573
+ }
1574
+ // 扁平点号键与规范嵌套都接受,统一摊开(便利形态 ≠ 放松校验)
1575
+ const expanded = expandPatch(patch);
1576
+ // ① **先本地严格校验**:字段名/类型/范围错了就在本地拒掉,别拿脏值去打扰宿主
1577
+ // (宿主也会校验,但它的话术是给开发者看的;用户需要的是"哪个字段、为什么")。
1578
+ const norm = normalizeSettings(expanded, { lenient: false, expand: true });
1579
+ if (!norm.ok) {
1580
+ return {
1581
+ text: `设置未写入: ${norm.error}\n可配置项(改完免重启):\n${SETTINGS_FIELDS.map((f) => ` ${f.path}`).join("\n")}\n结构性字段(需改 cordis.patch.yml 并重启):\n${STRUCTURAL_FIELDS.map((f) => ` ${f}`).join("\n")}`,
1582
+ state: "invalid",
1583
+ };
1584
+ }
1585
+ // ② 写唯一真相(M6.1:宿主配置页;没有 settings 服务才退回 settings.json)
1586
+ const w = await persistSettings(norm.value);
1587
+ if (!w.ok) {
1588
+ return {
1589
+ text: `${writeFailure(w)}\n可配置项(改完免重启):\n${SETTINGS_FIELDS.map((f) => ` ${f.path}`).join("\n")}\n结构性字段(需改 cordis.patch.yml 并重启):\n${STRUCTURAL_FIELDS.map((f) => ` ${f}`).join("\n")}`,
1590
+ state: w.reason === "invalid" ? "invalid" : (w.conflict ? "conflict" : "write-failed"),
1591
+ };
1592
+ }
1593
+ const applied = await applyAfterWrite(w.via);
1594
+ return {
1595
+ text: `已更新 ${applied.diff.length} 个字段 → 写入 ${writeTargetText(w.via)},下一轮(≤${top.pollIntervalSeconds}s)生效,**不需要重启**。\n变更:\n${applied.diff.map((d) => ` ${d.path} → ${JSON.stringify(d.value)}`).join("\n") || " (无变化)"}`,
1596
+ state: "ok", profile: base.profile, imInstalled: base.imInstalled,
1597
+ settingsFile, settings: effectiveSettings(), sources: currentSources(), applied: applied.diff, writeTarget: w.via,
1598
+ };
1599
+ }
1600
+
1601
+ case "off": {
1602
+ const w = await persistSettings({ notify: { enabled: false } });
1603
+ if (!w.ok) return { text: writeFailure(w), state: w.conflict ? "conflict" : "write-failed" };
1604
+ await applyAfterWrite(w.via);
1605
+ return { text: `通知已关闭(写入 ${writeTargetText(w.via)}):邮件仍会归档、水位照常推进,只不再推送(留痕与浮动栏展示保留)。\n用 action=on 重新开启。`, state: "disabled", profile: base.profile, imInstalled: base.imInstalled, settingsFile, settings: effectiveSettings(), writeTarget: w.via };
1606
+ }
1607
+
1608
+ case "on": {
1609
+ const w = await persistSettings({ notify: { enabled: true } });
1610
+ if (!w.ok) return { text: writeFailure(w), state: w.conflict ? "conflict" : "write-failed" };
1611
+ await applyAfterWrite(w.via);
1612
+ return { text: `通知已开启(写入 ${writeTargetText(w.via)})。`, state: "enabled", profile: base.profile, imInstalled: base.imInstalled, settingsFile, settings: effectiveSettings(), writeTarget: w.via };
1613
+ }
1614
+
1615
+ case "reset": {
1616
+ const before = effectiveSettings();
1617
+ const hadOverride = Object.keys(before).length > 0;
1618
+ const w = await persistSettings({}, { mode: "replace" });
1619
+ if (!w.ok) return { text: writeFailure(w), state: w.conflict ? "conflict" : "write-failed" };
1620
+ await applyAfterWrite(w.via);
1621
+ return {
1622
+ text: hadOverride
1623
+ ? `已清空用户覆盖(${writeTargetText(w.via)}),所有配置回到 cordis 层 / 默认值。`
1624
+ : "本来就是空的(没有任何用户覆盖),无需清理。",
1625
+ state: "reset", profile: base.profile, settingsFile, settings: effectiveSettings(), writeTarget: w.via,
1626
+ };
1627
+ }
1628
+
1629
+ default:
1630
+ return { text: `未知 action:${args.action}`, state: "unknown-action" };
1631
+ }
1632
+ },
1633
+ }));
1634
+
1635
+
1636
+ // 三通道:console(开发时可见)+ cordis ctx.logger(宿主自有 sink)+ <dataDir>/mailbox.log
1637
+ const logFile = path.join(top.dataDir, "mailbox.log");
1638
+ const cordisLog = (() => { try { return typeof ctx.logger === "function" ? ctx.logger("mailbox") : null; } catch { return null; } })();
1639
+ const logger = createLogger({
1640
+ file: logFile,
1641
+ echo: (level, text) => {
1642
+ try { (level === "error" ? console.error : console.log)(text); } catch { /* 控制台不可用 */ }
1643
+ try { cordisLog?.[level]?.(text); } catch { /* 宿主 logger 不可用 */ }
1644
+ },
1645
+ });
1646
+ const log = (level, msg) => logger.log(level, msg);
1647
+
1648
+ // ---- M7 语义工作器(LLM 摘要 + 语义标签)----
1649
+ // service 与 defaultSelection 都是**延迟取值**:插件跑在没有 LLM 的部署里也不会崩。
1650
+ const llmWorker = makeLlmWorker({
1651
+ top: () => top,
1652
+ store: () => storeRef,
1653
+ log,
1654
+ service: () => (typeof ctx.get === "function" ? ctx.get("llm") : ctx.llm) ?? null,
1655
+ defaultSelection: () => {
1656
+ const svc = typeof ctx.get === "function" ? ctx.get("agentDefaultModel") : ctx.agentDefaultModel;
1657
+ try { return svc?.currentSelection?.() ?? null; } catch { return null; }
1658
+ },
1659
+ });
1660
+ log("info", `LLM 语义:${llmWorker.describe()}`);
1661
+
1662
+ // ---- mailbox_update: 自更新(M4) ----
1663
+ // 契约照搬 @xmanrui/dsh-im 的更新器:status / check / install 三段式,install 必须带
1664
+ // checkId(带 TTL 的确认票据),**绝不自己重启** —— 装完只报 restart-required。
1665
+ // 之所以要这个功能:2026-10-15 升级 opencode2dsh 时发现 Desktop 插件管理器里
1666
+ // **没有更新按钮**,只能手工 pnpm;本工具让 mailbox 自己能检查并安装新版本。
1667
+ /** dsh-tools 0.2.1-rc.2 起运行时按声明的 output schema 严格校验工具返回值:
1668
+ * 未声明字段与非声明类型的 null 都会让整次调用失败。snapshot() 在「未检查/未安装」
1669
+ * 时会给出一批 null —— 这里剔除而不是返回(声明侧只写非 null 类型,语义进 text)。 */
1670
+ const omitNull = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== null && v !== undefined));
1671
+
1672
+ const updateDispose = ctx.tools.register(defineTool({
1673
+ name: "mailbox_update",
1674
+ description:
1675
+ "插件自更新。action=status:看运行版本/已装版本/最新版本、安装形态与是否可更新;" +
1676
+ "action=check:查最新版并返回 checkId;**action=install:必须带上一步的 checkId**,才会执行 pnpm 安装;" +
1677
+ "action=reset:清掉卡住的本地更新记录(不影响已装版本)。" +
1678
+ "注意:① 安装由本工具完成,但**不会自动重启 DSH** —— 装完需手动重启才生效;" +
1679
+ "② 当前若是 link(源码)安装则没有上游,会如实返回 source-install,需先在 config 里配 update.source;" +
1680
+ "③ 安装前会快照 profile 的 package.json/pnpm-lock.yaml/pnpm-workspace.yaml。",
1681
+ parameters: {
1682
+ action: {
1683
+ type: "string", required: true, enum: ["status", "check", "install", "reset"],
1684
+ description: "status 查看 / check 检查新版本 / install 安装(需 checkId) / reset 清理本地更新记录",
1685
+ },
1686
+ checkId: { type: "string", description: "action=install 必填:上一步 check 返回的 checkId" },
1687
+ },
1688
+ output: textOutput({
1689
+ state: { type: "string" },
1690
+ runningVersion: { type: "string" },
1691
+ installedVersion: { type: "string" },
1692
+ latestVersion: { type: "string" },
1693
+ environmentKind: { type: "string" },
1694
+ sourceSpec: { type: "string" },
1695
+ canInstall: { type: "boolean" },
1696
+ checkId: { type: "string" },
1697
+ job: { type: "object", additionalProperties: true },
1698
+ stateDirectory: { type: "string" },
1699
+ // 2026-10-23:dsh-tools 0.2.1-rc.2 起运行时按本 schema 强制校验返回值
1700
+ // (additionalProperties:false ⇒ 未声明字段直接拒),snapshot()/wrap() 实际会
1701
+ // 返回以下字段,必须声明;它们的 null 值由 omitNull 在返回前剔除。
1702
+ profileName: { type: "string" },
1703
+ sourceInstall: { type: "boolean" },
1704
+ blockedReason: { type: "string" },
1705
+ checkedAt: { type: "number" },
1706
+ ok: { type: "boolean" },
1707
+ cleared: { type: "boolean" },
1708
+ directory: { type: "string" },
1709
+ error: { type: "string" },
1710
+ detail: { type: "string" },
1711
+ }),
1712
+ async execute(args) {
1713
+ const profileDir = process.env.DSH_PROFILE_DIR
1714
+ ?? path.join(process.env.DSH_HOME ?? path.join(os.homedir(), ".dsh"), "profiles", process.env.DSH_PROFILE ?? "desktop");
1715
+ const cfgSource = String(config?.update?.source ?? "");
1716
+ const svc = createUpdateService({
1717
+ runningVersion: PKG_VERSION,
1718
+ log,
1719
+ inspect: (opts) => inspectRuntime({ ...opts, profileDir }),
1720
+ });
1721
+
1722
+ const wrap = async (fn) => {
1723
+ try { return await fn(); }
1724
+ catch (e) {
1725
+ const code = UPDATE_PUBLIC_ERRORS.has(e?.code) ? e.code : "update-failed";
1726
+ const detail = e?.detail ? `\n${e.detail}` : "";
1727
+ const text = code === "source-install"
1728
+ ? `当前安装形态没有可更新的上游${detail}`
1729
+ : `自更新失败[${code}]${detail}`;
1730
+ return omitNull({ text, state: code, error: code, detail: e?.detail ?? null });
1731
+ }
1732
+ };
1733
+
1734
+ switch (args.action) {
1735
+ case "status": {
1736
+ const s = await wrap(() => svc.status({ profileDir, source: cfgSource }));
1737
+ if (s.state && UPDATE_PUBLIC_ERRORS.has(s.state)) return s;
1738
+ const newer = s.latestVersion && s.runningVersion && gtSemver(s.latestVersion, s.runningVersion);
1739
+ const lines = [
1740
+ `包名 ${PACKAGE_NAME}`,
1741
+ `运行版本 ${s.runningVersion ?? "(未知)"}`,
1742
+ `已装版本 ${s.installedVersion ?? "(未安装)"}`,
1743
+ `最新版本 ${s.latestVersion ?? "(未检查,用 action=check)"}`,
1744
+ `安装形态 ${s.environmentKind}${s.sourceSpec ? ` · 更新源 ${s.sourceSpec}` : ""}`,
1745
+ `可更新 ${s.canInstall ? "是" : "否"}${s.blockedReason ? `(${s.blockedReason})` : ""}`,
1746
+ `更新作业 ${s.job ? `${s.job.state}${s.job.targetVersion ? ` → ${s.job.targetVersion}` : ""}${s.job.message ? ` (${s.job.message})` : ""}` : "(无)"}`,
1747
+ ];
1748
+ if (s.sourceInstall) {
1749
+ lines.push("", "⚠️ 这是 link(源码)安装 —— 没有上游可自动更新。", " 发布到 npm/GitHub 后,在 cordis.patch.yml 的 config 里写:");
1750
+ lines.push(' update: { source: "npm:@your-scope/mailbox" } 或 update: { source: "github:owner/repo" }');
1751
+ }
1752
+ if (s.blockedReason === "pending-restart") {
1753
+ lines.push("", `⏸ 已装上新版但**尚未重启 DSH**,所以运行版本仍是 ${s.runningVersion}。重启后生效。`);
1754
+ }
1755
+ if (s.blockedReason === "recovery-required") {
1756
+ lines.push("", "⚠️ 上一次更新被中断且状态存疑。确认当前安装没问题后,用 action=reset 清理记录再来。");
1757
+ }
1758
+ return omitNull({ ...s, state: "ok", text: lines.join("\n") });
1759
+ }
1760
+
1761
+ case "check": {
1762
+ const s = await wrap(() => svc.check({ profileDir, source: cfgSource }));
1763
+ if (s.state && UPDATE_PUBLIC_ERRORS.has(s.state)) return s;
1764
+ const newer = s.latestVersion && s.runningVersion && gtSemver(s.latestVersion, s.runningVersion);
1765
+ const lines = [
1766
+ `运行版本 ${s.runningVersion ?? "?"} · 最新 ${s.latestVersion ?? "?"}`,
1767
+ newer ? "✅ 有新版本可用。" : "已是最新。",
1768
+ `安装形态 ${s.environmentKind}${s.sourceSpec ? ` · 更新源 ${s.sourceSpec}` : ""}`,
1769
+ ];
1770
+ if (newer && s.checkId) {
1771
+ lines.push("", `确认票据 ${s.checkId}(10 分钟内有效)`, '执行安装:mailbox_update(action="install", checkId="<上面的票据>")', "安装完成后**需手动重启 DSH** 才生效。");
1772
+ }
1773
+ return omitNull({ ...s, state: "ok", text: lines.join("\n") });
1774
+ }
1775
+
1776
+ case "install": {
1777
+ if (!args.checkId) {
1778
+ return { text: "安装需要带上一步 check 返回的 checkId(确认票据,10 分钟内有效)。\n先执行 action=check。", state: "check-expired" };
1779
+ }
1780
+ const s = await wrap(() => svc.install({
1781
+ checkId: String(args.checkId), requestId: crypto.randomUUID(), configSource: { profileDir, source: cfgSource },
1782
+ }));
1783
+ if (s.state && UPDATE_PUBLIC_ERRORS.has(s.state)) return s;
1784
+ const job = s.job ?? {};
1785
+ const lines = [
1786
+ `更新作业:${job.state ?? "(未知)"}${job.targetVersion ? ` → ${job.targetVersion}` : ""}`,
1787
+ job.state === "restart-required"
1788
+ ? `✅ 已安装 ${job.targetVersion}。**请手动重启 DSH**,重启后运行版本才会变成新版本。`
1789
+ : job.state === "failed" || job.state === "interrupted"
1790
+ ? `❌ 更新未完成(${job.message ?? "未知原因"})。账户/归档/设置都不受影响;可 action=reset 后重试。`
1791
+ : "安装进行中,稍后用 action=status 查看结果。",
1792
+ ];
1793
+ return omitNull({ ...s, text: lines.join("\n") });
1794
+ }
1795
+
1796
+ case "reset": {
1797
+ const s = await wrap(() => svc.reset({ profileDir, source: cfgSource }));
1798
+ if (s.state && UPDATE_PUBLIC_ERRORS.has(s.state)) return s;
1799
+ return omitNull({ ...s, state: "ok", text: s.cleared ? `已清理本地更新记录:${s.directory}` : "本来就没有更新记录。" });
1800
+ }
1801
+
1802
+ default:
1803
+ return { text: `未知 action:${args.action}`, state: "unknown-action" };
1804
+ }
1805
+ },
1806
+ }));
1807
+
1808
+ // ---- M4 工具面扩展(5 个)+ M4.5 写操作工具(默认不注册) ----
1809
+ // 写工具是**能力开关**:注册发生在 apply 阶段,热改变不了"工具存不存在",
1810
+ // 所以 write.enabled 只在部署层(patch + 重启)生效,这也是 D13 的本意。
1811
+ const m4Disposers = buildM4Tools(m4Deps).map((d) => ctx.tools.register(d));
1812
+ const writeDisposers = top.write.enabled
1813
+ ? buildWriteTools(m4Deps).map((d) => ctx.tools.register(d))
1814
+ : [];
1815
+ log("info", `工具面已注册:${9 + m4Disposers.length + writeDisposers.length} 个${writeDisposers.length ? "(含写操作 mark/move)" : "(写操作未启用:write.enabled=false)"}`);
1816
+
1817
+ // logger 就位后,把早期 log0 的重要行补写进 mailbox.log(桌面版 stdout 不落盘)
1818
+ log0 = log;
1819
+ const settingsFile0 = path.join(top.dataDir, "settings.json");
1820
+ log("info", `插件加载:日志 ${logFile};数据目录 ${top.dataDir}`);
1821
+ log("info", `运行时设置层:${settingsFile0}(存在:${fs.existsSync(settingsFile0) ? "是" : "否,首次运行"};修订号 ${settingsStore.rev};免重启字段 ${SETTINGS_FIELDS.length} 个)`);
1822
+ const imBase = checkImStateSync(top, ctx);
1823
+ log("info", `当前 profile: ${imBase.profile} · IM 服务: ${imBase.imInstalled ? "已就绪" : "未就绪"} · 配置状态: ${imBase.state}${top.notify.botId && top.notify.targetId ? `(${top.notify.botId}/${top.notify.targetId})` : ""}`);
1824
+
1825
+ // ---- 常驻 watcher(M2) ----
1826
+ // 用 ctx.inject(["timer"]) 等时钟服务就绪再起,而不是把 timer 写进模块级 inject —
1827
+ // 这样即使某个部署没有 timer 服务,工具仍然照常可用(软依赖)。
1828
+ let watcherHandle = null;
1829
+ if (top.watcher.enabled) {
1830
+ const bootWatcher = (scope) => {
1831
+ void (async () => {
1832
+ const store = await ensureStore(); // 与 M4/M5 工具共用同一个连接
1833
+
1834
+ // ---- 通知通道(M3 / M3.3) ----
1835
+ // 1) 有 dshIm 就自动发现投递目标(用户没手填也能用已配置的);
1836
+ // 2) **无论有没有通道都先留痕**(notices 表)→ 输入框浮动栏作为兜底展示面;
1837
+ // 3) 低优先进「日报缓冲」,每天在 dailyDigest.at 汇总一次(决策 B);
1838
+ // 4) **所有 notify.* 字段运行时可变**:on/off、阈值、静音、日报、目标
1839
+ // 改完下一轮生效,不需要重启(settings.json 说了算)。
1840
+ // ⚠️ 整段包在 try/catch 里:**通知的任何问题都不允许拖垮 watcher**
1841
+ // (M2 首次真机启动就是死在这里,而且因为没日志只能靠猜)
1842
+
1843
+ // 留痕与通知开关无关:就算 notify.enabled=false,浮动栏也能看到有什么新邮件
1844
+ // (M6.7:返回 notice id,投递成功后由 Notifier 回写 delivered_at)
1845
+ const record = async ({ kind, account, folder, title, body, items }) =>
1846
+ store.addNotice({ kind, account, folder, title: title ?? null, body: body ?? null, items: items ?? null });
1847
+
1848
+ // 这三可变引用放在外层:设置变更时要能改到它们
1849
+ let digester = null; // { notifier, notify, digest } | null
1850
+ let channelCache = null; // { im, botId, targetId } | false | null(要重新解析)
1851
+
1852
+ /** 构造通知器。失败返回 null(调用方只记日志,绝不影响 watcher)。 */
1853
+ const buildNotifier = () => {
1854
+ // 投递目标**惰性解析**:本插件在 profile 的 bundles 里排在 @xmanrui/dsh-im **之前**,
1855
+ // 启动时 dshIm 往往还没被提供(ctx.get 对未激活的服务返回 undefined)。
1856
+ // 所以不在启动时定死通道,而是首次真要发通知时再找,并缓存结果。
1857
+ // 注意:失败**不缓存 false**(ambiguous/未就绪都保持 null),这样用户改完
1858
+ // 设置或 dshIm 稍后就绪,下一轮会重新探测 —— 不用重启。
1859
+ const ensureChannel = async () => {
1860
+ if (channelCache === false) return null; // 已核实配置目标不存在:等设置变更再重试(原语义保留)
1861
+ // ⚠️ 2026-10-23 踩坑:profile 热升级 dsh-im(4.38.0→5.4.0)会**换代服务实例**,
1862
+ // 旧实例随旧纤维卸载了 bot 表,send 报 "Unknown bot"、水位卡住反复重发。
1863
+ // 所以服务对象**每次现取**,缓存只复用「同一实例」下解析过的 botId/targetId;
1864
+ // 实例换代 → 自动重新核对,无需重启 mailbox。
1865
+ const im = probe(ctx, "dshIm");
1866
+ if (!im) return null; // 还没就绪:不缓存失败,下次再试
1867
+ if (channelCache && channelCache.im === im) return channelCache;
1868
+ if (top.notify.botId && top.notify.targetId) {
1869
+ // ⚠️ 2026-10-16:过去这里**不校验就直接用**(填了就 configured)⇒ 用户把 Telegram bot token
1870
+ // 填进 botId 时,状态显示健康、实际每次都投递失败、水位被卡住反复重发。
1871
+ // 现在去 dsh-im 的真实列表里核对;核对不过就**当作没有通道**(只留痕),绝不 hard-fail。
1872
+ const verify = await withTimeout(
1873
+ Promise.resolve(resolveImTarget(im, { botId: top.notify.botId, targetId: top.notify.targetId, requireExisting: true })),
1874
+ 5000, "IM 目标校验",
1875
+ ).catch((e) => ({ ok: false, reason: String(e?.message ?? e) }));
1876
+ if (verify.ok) {
1877
+ channelCache = { im, botId: verify.botId, targetId: verify.targetId };
1878
+ log("info", `通知通道就绪(配置目标):${channelCache.botId}/${channelCache.targetId}(来源 ${verify.source})`);
1879
+ return channelCache;
1880
+ }
1881
+ channelCache = false; // settings 变更时会被清空重试
1882
+ const cands = (verify.candidates ?? []).slice(0, 6).map((c) => `${c.botId}/${c.targetId}${c.name ? `(${c.name})` : ""}`).join(" | ");
1883
+ log("warn", `配置的 IM 目标在 dsh-im 里**不存在**(${verify.reason})⇒ 通知只留痕。`
1884
+ + `请用 mailbox_notify(action="targets") 看真实候选${cands ? `;当前候选:${cands}` : "(现在没有任何候选:到 设置 → IM机器人 →「投递设置」→「新建目标」建一个)"}`);
1885
+ return null;
1886
+ }
1887
+ const r = await withTimeout(resolveImTarget(im, {}), 5000, "IM 目标发现");
1888
+ if (r.ok) {
1889
+ channelCache = { im, botId: r.botId, targetId: r.targetId };
1890
+ log("info", `通知通道就绪(自动选定):${channelCache.botId}/${channelCache.targetId}(来源 ${r.source})`);
1891
+ return channelCache;
1892
+ }
1893
+ if (r.reason === "ambiguous") {
1894
+ log("warn", `IM 里有多个投递目标,请用 mailbox_notify(action="targets") 看列表并选定;候选:${(r.candidates ?? []).map((c) => `${c.botId}/${c.targetId}${c.name ? `(${c.name})` : ""}`).join(" | ")}`);
1895
+ channelCache = null; // 保持 null → 下一轮重新探测,用户选定后自动生效
1896
+ } else {
1897
+ channelCache = false;
1898
+ log("warn", `未找到可用的 IM 投递目标(${r.reason});通知只留痕(浮动栏可见)`);
1899
+ }
1900
+ return null;
1901
+ };
1902
+
1903
+ const deliver = async ({ text }) => {
1904
+ // 通知方式=local:明确"不走 IM"。notify 路径更早就会短路,这里兜住**日报**路径。
1905
+ if (top.notify.channel === "local") {
1906
+ const e = new Error("通知方式=local:仅留痕");
1907
+ e.code = "NO_CHANNEL";
1908
+ throw e;
1909
+ }
1910
+ const ch = await ensureChannel();
1911
+ if (!ch) {
1912
+ const e = new Error("没有可用的 IM 投递通道");
1913
+ e.code = "NO_CHANNEL";
1914
+ throw e;
1915
+ }
1916
+ const res = await ch.im.send(ch.botId, ch.targetId, text);
1917
+ if (res && res.sent === false) throw new Error("dshIm 未接受投递");
1918
+ };
1919
+
1920
+ const n = new Notifier({
1921
+ deliver,
1922
+ record,
1923
+ // M6.7:投递成功后回写 notices.delivered_at —— 以前投递成功只打日志,
1924
+ // delivered_at 永远 null,「待推通知」永远虚高(2026-10-30 实测:
1925
+ // 3 条早已推到 Telegram 的通知一直显示待推)。
1926
+ markDelivered: (id) => {
1927
+ try { store.markNotices({ ids: [Number(id)].filter(Boolean), deliveredAt: Date.now() }); }
1928
+ catch { /* 留痕表不可写时只影响统计,不影响通知主流程 */ }
1929
+ },
1930
+ // 传函数而不是值:卡片里改了通知方式要**立刻**生效,无需重建 Notifier
1931
+ channel: () => top.notify.channel,
1932
+ threshold: top.notify.importanceThreshold,
1933
+ batch: top.notify.batch,
1934
+ filter: top.notify.filter,
1935
+ quietHours: top.notify.quietHours,
1936
+ rules: top.tags.rules,
1937
+ knownDomains: top.knownDomains,
1938
+ queueBatched: top.notify.dailyDigest.enabled ? ((items) => store.queueDigest(items)) : null,
1939
+ // B3(2026-11-29):通知幂等账本 —— 投递失败不推进水位时,下一轮重抓同一批
1940
+ // 邮件也不会重复推送/重复留痕(schema v8 的 notice_ledger)。
1941
+ filterUnnotified: ({ account, folder, uids }) => store.notifiedUids(account, folder, uids),
1942
+ markNotified: ({ account, folder, uids, noticeId }) => store.markNotified(account, folder, uids, { noticeId }),
1943
+ // 2026-11-30 用户诉求:验证码默认给、可关掉。传函数 → 卡片里一改就生效;
1944
+ // 注意它只控制「推不推那行 🔑」,分级仍由 importance.js 的含码加分决定。
1945
+ includeCodes: () => top.notify.includeCodes !== false,
1946
+ log,
1947
+ });
1948
+ digester = {
1949
+ notifier: n,
1950
+ notify: (ev) => n.notify(ev),
1951
+ digest: async ({ items }) => {
1952
+ const text = buildDailyDigestText(items, { limit: 40 });
1953
+ if (!text) return { ok: true };
1954
+ const noticeId = Number(await record({ kind: "digest", title: `邮件日报(${items.length} 封)`, body: text })) || null;
1955
+ try {
1956
+ await deliver({ text });
1957
+ // M6.7:日报也回写 delivered_at(统计一致性;失败只影响统计)
1958
+ try { if (noticeId != null) store.markNotices({ ids: [noticeId], deliveredAt: Date.now() }); } catch { /* 忽略 */ }
1959
+ return { ok: true };
1960
+ }
1961
+ catch (e) {
1962
+ // 没有通道**不算发成功**:交给 sync 保留队列(否则这几封会在 08:00 无声消失)
1963
+ if (e?.code === "NO_CHANNEL") return { ok: true, noChannel: true };
1964
+ return { ok: false, error: String(e?.message ?? e) };
1965
+ }
1966
+ },
1967
+ };
1968
+ return digester;
1969
+ };
1970
+
1971
+ if (top.notify.enabled) {
1972
+ try {
1973
+ digester = buildNotifier();
1974
+ log("info", "通知器就绪(通道将在首次通知时惰性解析)");
1975
+ } catch (e) {
1976
+ log("error", `通知初始化失败,已跳过通知(归档不受影响):${e?.stack ?? e?.message ?? e}`);
1977
+ digester = null;
1978
+ }
1979
+ } else {
1980
+ log("info", "通知已关闭(notify.enabled=false):只归档 + 留痕");
1981
+ }
1982
+
1983
+ // watcher 收到的两个回调:**每次都看当前设置**,所以 on/off、阈值、日报
1984
+ // 全部可以免重启切换。没有通知器时返回 ok:true(只留痕)——
1985
+ // 绝不能因为没通道就把水位卡死。
1986
+ const onNewMessages = async (ev) => {
1987
+ try { return await digester.notify(ev); }
1988
+ catch (e) {
1989
+ log("warn", `通知异常(水位不推进): ${e?.message ?? e}`);
1990
+ return { ok: false, error: String(e?.message ?? e) };
1991
+ }
1992
+ };
1993
+ const onDailyDigest = async (ev) => {
1994
+ if (!top.notify.dailyDigest.enabled || !digester) return { ok: true, skipped: true };
1995
+ try { return await digester.digest(ev); }
1996
+ catch (e) {
1997
+ if (e?.code === "NO_CHANNEL") return { ok: true };
1998
+ return { ok: false, error: String(e?.message ?? e) };
1999
+ }
2000
+ };
2001
+
2002
+ // ---- 运行时设置热应用(M3.3):settings.json 改了 → 立刻同步到通知器 ----
2003
+ settingsListeners.push((diff) => {
2004
+ // 投递目标变了(或通知开关变了)→ 通道缓存作废,下一轮重新解析
2005
+ if (diff.some((d) => d.path === "notify.botId" || d.path === "notify.targetId" || d.path === "notify.enabled")) {
2006
+ channelCache = null;
2007
+ }
2008
+ // 通知从关到开:boot 时没建通知器,这里补建
2009
+ if (top.notify.enabled && !digester) {
2010
+ try { digester = buildNotifier(); log("info", "通知已开启:通知器补建完成"); }
2011
+ catch (e) { log("error", `通知器补建失败: ${e?.message ?? e}`); digester = null; }
2012
+ }
2013
+ if (digester?.notifier) {
2014
+ const n = digester.notifier;
2015
+ n.threshold = top.notify.importanceThreshold;
2016
+ n.batch = top.notify.batch;
2017
+ n.quietHours = top.notify.quietHours;
2018
+ n.filter = normalizeFilter(top.notify.filter);
2019
+ n.queueBatched = top.notify.dailyDigest.enabled ? ((items) => store.queueDigest(items)) : null;
2020
+ }
2021
+ if (diff.length) log("info", `运行时设置热应用:${diff.map((d) => d.path).join(", ")}`);
2022
+ });
2023
+
2024
+
2025
+ // ---- 时钟:必须校验 API,拿不到就明确报错,而不是静默不启动 ----
2026
+ let scheduler;
2027
+ try {
2028
+ const t = probe(scope, "timer") ?? scope;
2029
+ if (typeof t?.timeout !== "function") throw new Error("timer 服务没有 timeout 方法");
2030
+ scheduler = { timeout: (fn, ms) => t.timeout(fn, ms) };
2031
+ } catch (e) {
2032
+ log("error", `watcher 未启动:${e?.message ?? e}`);
2033
+ return;
2034
+ }
2035
+
2036
+ const watcher = new Watcher({
2037
+ accounts: top.accounts,
2038
+ store,
2039
+ tokenProvider: (acc) => getAccessToken(top, acc),
2040
+ archive: top.archive,
2041
+ pollIntervalSeconds: top.pollIntervalSeconds,
2042
+ maxBackoffSeconds: top.maxBackoffSeconds,
2043
+ maxMessagesPerCycle: top.maxMessagesPerCycle,
2044
+ onNewMessages,
2045
+ dailyDigest: top.notify.dailyDigest,
2046
+ onDailyDigest,
2047
+ // M7:每入库一封丢给语义工作器(**不 await**:内部自己排队/串行/限流)
2048
+ onIngested: (ref, msg) => llmWorker.enqueue(ref, msg),
2049
+ log,
2050
+ });
2051
+ log("info", `watcher 配置:账户 ${top.accounts.map((a) => `${a.email}[${a.folders.join(",")}]`).join(" ")};每 ${top.pollIntervalSeconds}s;模式 ${top.archive.mode};通知${top.notify.enabled ? "开" : "关"};日报${top.notify.dailyDigest.enabled ? `开(${top.notify.dailyDigest.at})` : "关"}`);
2052
+ watcherRef = watcher; // 供 mailbox_notify 热应用运行时设置
2053
+ watcherHandle = watcher.start(scheduler);
2054
+ watcherStateRef.running = true;
2055
+ watcherStateRef.paused = watcher.paused === true;
2056
+ watcherStateRef.folders = top.accounts.reduce((n, a) => n + (a.folders?.length || 1), 0);
2057
+ watcherStateRef.locked = watcherHandle?.locked !== false;
2058
+ watcherStateRef.reason = watcherHandle?.locked === false
2059
+ ? `未取到单实例锁(pid ${watcherHandle?.holder?.pid ?? "?"} 正在跑?)`
2060
+ : (watcherStateRef.paused ? "watcher 已暂停(watcher.enabled=false)" : null);
2061
+ if (watcherHandle?.locked === false) log("warn", "watcher 未启动:未取得单实例锁(可能已有实例在跑)");
2062
+ })().catch((e) => log("error", `watcher 启动失败:${e?.stack ?? e?.message ?? e}`));
2063
+ };
2064
+ if (typeof ctx.inject === "function") {
2065
+ try { ctx.inject(["timer"], bootWatcher); }
2066
+ catch (e) { log("error", `watcher 未启动:注入 timer 失败:${e?.message ?? e}`); }
2067
+ } else if (ctx.timer) {
2068
+ bootWatcher(ctx);
2069
+ } else {
2070
+ log("warn", "watcher 未启动:timer 服务不可用(工具仍可用)");
2071
+ }
2072
+ } else {
2073
+ watcherStateRef.reason = "运行时开关已关闭(watcher.enabled=false)";
2074
+ watcherStateRef.paused = true;
2075
+ }
2076
+
2077
+ // ---- M6.3:回环 HTTP 桥 ----
2078
+ // 浮动栏(M6.4)要用它读运行状态、点"检查"。webServer 缺席(精简组合)时整段跳过 ——
2079
+ // 桥只是**展示面**,不是功能本体:没有它,工具与 watcher 一模一样。
2080
+ //
2081
+ // 只在 webServer 服务出现后挂路由(ctx.inject),并用 effect 把注销挂在 fiber 上,
2082
+ // 这样插件卸载/重挂不会留下野路由。
2083
+ let bridgeDisposers = [];
2084
+ try {
2085
+ if (typeof ctx.inject === "function") {
2086
+ void Promise.resolve(ctx.inject(["webServer"], (bctx) => {
2087
+ if (!bctx?.webServer || typeof bctx.webServer.register !== "function") return;
2088
+ const handlers = makeBridgeHandlers({
2089
+ now: () => Date.now(),
2090
+ top: () => top,
2091
+ watcher: () => watcherRef,
2092
+ watcherState: () => watcherStateRef,
2093
+ store: () => storeRef,
2094
+ imReady: () => checkImStateSync(top, ctx).imInstalled === true,
2095
+ // 配置卡的候选下拉:直接读 dsh-im 的真实 bots/targets
2096
+ im: () => probe(ctx, "dshIm"),
2097
+ settingsTarget: () => (hostState().ok ? "host" : (settingsStore.importedTo ? "host" : "file")),
2098
+ // 配置页免重启账号管理
2099
+ persistAccounts,
2100
+ replaceRuntimeAccounts,
2101
+ // 配置卡「监控文件夹」多选框:真连 IMAP LIST 拿该账号的文件夹名
2102
+ // (mailbox_folders 工具同源逻辑;失败时桥回 folders-list-failed,卡片退回手输)
2103
+ foldersList: async (account) => {
2104
+ const acc = pickAccount(top, account);
2105
+ const token = await getAccessToken(top, acc);
2106
+ const client = new ImapClient(acc, token);
2107
+ await client.connect();
2108
+ // 2026-10-30 需求:服务器列表也按大小写不敏感去重,勾选框不出现同义重复项
2109
+ try { return dedupeFolders((await client.listFolders()).map((f) => f.name)); }
2110
+ finally { client.close(); }
2111
+ },
2112
+ // 重置水位回填历史(2026-10-31):把该账户(可选单文件夹)的水位清零并记
2113
+ // 「回填截止标记」,下一轮 tick 起把监控文件夹的全部历史抓进本地库 ——
2114
+ // ≤ 标记的邮件只入库不通知。是"本地库与邮箱内容保持一致"的入口。
2115
+ resync: async ({ account, folder } = {}) => {
2116
+ const acc = pickAccount(top, account);
2117
+ const out = storeRef.resetSyncState({ account: acc.email, folder });
2118
+ log("info", `[${acc.email}] 已重置水位(回填历史): ${out.reset.map((r) => `${r.folder}(≤${r.mark} 只入库不通知)`).join(", ") || "(该账户还没有已跟踪的文件夹)"}`);
2119
+ return out;
2120
+ },
2121
+ // 部署层账号在配置页删不掉(要去改 cordis.patch.yml + 重启):卡片据此显示来源、
2122
+ // 禁用「删除」的按钮,桥也据此拒绝假成功。
2123
+ deployedEmails: () => new Set(
2124
+ (Array.isArray(config?.accounts) ? config.accounts : [])
2125
+ .map((a) => String(a?.email ?? "").trim())
2126
+ .filter(Boolean)),
2127
+ runtimeAccounts: runtimeAccountsNow,
2128
+ accountTokenStatus,
2129
+ authDevice,
2130
+ authComplete,
2131
+ // 配置页「发测试消息」:与工具 action=test 共用一个实现,免得分出两套口径。
2132
+ notifyTest: async () => notifyTestCore({ top, im: probe(ctx, "dshIm") }),
2133
+ // 立刻检查:一轮完整 tick(含日报检查/保留策略),与定时轮次走同一条路径 ——
2134
+ // 不另写一套,免得"手动能抓、自动抓不到"这类分歧。
2135
+ check: async () => {
2136
+ const t = await watcherRef.tick();
2137
+ const results = Array.isArray(t?.results) ? t.results : [];
2138
+ return {
2139
+ at: t?.now ?? Date.now(),
2140
+ fetched: results.reduce((n, r) => n + (r?.fetched ?? 0), 0),
2141
+ failures: t?.failures ?? 0,
2142
+ folders: t?.total ?? results.length,
2143
+ nextDelaySeconds: Math.round((t?.nextDelayMs ?? 0) / 1000),
2144
+ };
2145
+ },
2146
+ // 标已读/未读(2026-11-29 需求):浮动栏里直接改**服务器**上的 \Seen,并同步本地归档。
2147
+ // 给了 uid = 只改这一封;没给 uid = 把该文件夹里所有未读一次标掉(一条 UID STORE 带 200 个)。
2148
+ markSeen: async ({ account, folder, uid = null, seen = true } = {}) => {
2149
+ const acc = pickAccount(top, account);
2150
+ const folderKey = String(folder || "").trim() || acc.defaultFolder || "INBOX";
2151
+ const token = await getAccessToken(top, acc);
2152
+ const client = new ImapClient(acc, token);
2153
+ await client.connect();
2154
+ let uids = [];
2155
+ try {
2156
+ await client.open(folderKey);
2157
+ if (uid == null) {
2158
+ uids = (await client.uidSearch({ unseen: true })) ?? [];
2159
+ let marked = 0;
2160
+ for (let i = 0; i < uids.length; i += 200) marked += await client.setSeenBulk(uids.slice(i, i + 200), seen);
2161
+ uids = marked > 0 ? uids.slice(0, marked) : [];
2162
+ if (marked === 0) return { account: acc.email, folder: folderKey, marked: 0, seen };
2163
+ // 本地归档跟着改;失败不影响服务器已生效的动作
2164
+ try { storeRef.syncSeenFlags(acc.email, folderKey, uids.map((u) => ({ uid: Number(u), seen }))); } catch { /* 归档未启用 */ }
2165
+ if (seen) { try { storeRef.ackNoticesForSeen(acc.email, folderKey); } catch { /* 同上 */ } }
2166
+ log("info", `[${acc.email}/${folderKey}] 浮动栏:已标${seen ? "已读" : "未读"} ${marked} 封`);
2167
+ return { account: acc.email, folder: folderKey, marked, seen };
2168
+ }
2169
+ await client.setSeen(uid, seen);
2170
+ uids = [uid];
2171
+ try { storeRef.syncSeenFlags(acc.email, folderKey, [{ uid: Number(uid), seen }]); } catch { /* 归档未启用 */ }
2172
+ if (seen) { try { storeRef.ackNoticesForUids(acc.email, folderKey, [Number(uid)]); } catch { /* 同上 */ } }
2173
+ log("info", `[${acc.email}/${folderKey}] 浮动栏:uid=${uid} 已标${seen ? "已读" : "未读"}`);
2174
+ return { account: acc.email, folder: folderKey, marked: 1, seen, uid };
2175
+ } finally {
2176
+ client.close();
2177
+ }
2178
+ },
2179
+ // 浮动栏点 📎:读这封的附件清单(只回名字/大小/类型,不落盘)。2026-11-29 需求。
2180
+ listAttachments: async ({ account, folder, uid } = {}) => {
2181
+ const acc = pickAccount(top, account);
2182
+ const folderKey = String(folder || "").trim() || acc.defaultFolder || "INBOX";
2183
+ const token = await getAccessToken(top, acc);
2184
+ const client = new ImapClient(acc, token);
2185
+ await client.connect();
2186
+ try {
2187
+ await client.open(folderKey);
2188
+ const parsed = parseMime(await client.fetchFull(Number(uid)));
2189
+ const attachments = (parsed.attachments ?? []).map((a, i) => ({
2190
+ index: i + 1,
2191
+ name: a.name,
2192
+ size: a.size,
2193
+ contentType: a.contentType || "application/octet-stream",
2194
+ }));
2195
+ return { account: acc.email, folder: folderKey, uid: Number(uid), attachments };
2196
+ } finally {
2197
+ client.close();
2198
+ }
2199
+ },
2200
+ // 浮动栏:取单个附件字节给浏览器直接打开(不写盘)。超过 10 MB 不传,提示走 mailbox_read 落盘。
2201
+ getAttachment: async ({ account, folder, uid, index } = {}) => {
2202
+ const acc = pickAccount(top, account);
2203
+ const folderKey = String(folder || "").trim() || acc.defaultFolder || "INBOX";
2204
+ const token = await getAccessToken(top, acc);
2205
+ const client = new ImapClient(acc, token);
2206
+ await client.connect();
2207
+ try {
2208
+ await client.open(folderKey);
2209
+ const parsed = parseMime(await client.fetchFull(Number(uid)));
2210
+ const list = parsed.attachments ?? [];
2211
+ const att = list[Number(index) - 1];
2212
+ if (!att) {
2213
+ throw Object.assign(new Error(`第 ${index} 个附件不存在(这封共 ${list.length} 个)`), { code: "no-such-attachment" });
2214
+ }
2215
+ const buf = Buffer.from(att.payload ?? []);
2216
+ if (buf.length > MAX_ATTACH_PREVIEW) {
2217
+ throw Object.assign(new Error(`附件 ${att.name} 约 ${(buf.length / 1048576).toFixed(1)} MB,超过面板预览上限 ${MAX_ATTACH_PREVIEW / 1048576} MB;用 mailbox_read saveAttachments=true 落盘后打开`), { code: "attachment-too-large" });
2218
+ }
2219
+ log("info", `[${acc.email}/${folderKey}] 浮动栏:打开附件 uid=${uid} #${index} ${att.name}(${buf.length} 字节)`);
2220
+ return {
2221
+ name: att.name,
2222
+ contentType: att.contentType || "application/octet-stream",
2223
+ size: buf.length,
2224
+ base64: buf.toString("base64"),
2225
+ };
2226
+ } finally {
2227
+ client.close();
2228
+ }
2229
+ },
2230
+ });
2231
+ bridgeDisposers = makeBridgeRoutes(handlers).map((route) => bctx.webServer.register(route));
2232
+ log("info", `邮件桥已挂载:${MAILBOX_BRIDGE_PREFIX}/status · ${MAILBOX_BRIDGE_PREFIX}/check · ${MAILBOX_BRIDGE_PREFIX}/mark-seen · ${MAILBOX_BRIDGE_PREFIX}/attachments · ${MAILBOX_BRIDGE_PREFIX}/notify-test(回环 + 同源,仅 POST)`);
2233
+ if (typeof bctx.effect === "function") {
2234
+ bctx.effect(() => () => {
2235
+ for (const d of bridgeDisposers) { try { d?.(); } catch { /* 已注销 */ } }
2236
+ bridgeDisposers = [];
2237
+ });
2238
+ }
2239
+ })).catch(() => { /* 没有 webServer 服务 */ });
2240
+ }
2241
+ } catch { /* 同上 */ }
2242
+
2243
+ return () => {
2244
+ [authDispose, foldersDispose, listDispose, readDispose, searchDispose, sendDispose, notifyDispose, updateDispose]
2245
+ .forEach((d) => { if (typeof d === "function") d(); });
2246
+ for (const d of [...m4Disposers, ...writeDisposers]) { try { d?.(); } catch { /* 已注销 */ } }
2247
+ try { watcherHandle?.stop?.(); } catch { /* 已停 */ }
2248
+ for (const d of bridgeDisposers) { try { d?.(); } catch { /* 已注销 */ } }
2249
+ };
2250
+ }
2251
+
2252
+ function uniqueServers(acc) {
2253
+ const seen = new Set();
2254
+ const out = [];
2255
+ for (const h of [acc.smtpHost, DEFAULTS.smtpHost, "smtp.office365.com"]) {
2256
+ if (h && !seen.has(h)) { seen.add(h); out.push(h); }
2257
+ }
2258
+ return out;
2259
+ }
2260
+
2261
+ function genIdFor(rawMime) {
2262
+ const m = rawMime.toString("utf8").match(/Message-ID:\s*<([^>]+)>/i);
2263
+ return m ? m[1] : null;
2264
+ }
2265
+
2266
+ // ---- R8(2026-11-30):回复链路辅助 ----
2267
+ /** 从 `From: 张三 <a@b.com>` 里抠出地址;拿不到地址就原样返回(宁可发错也别静默丢收件人)。 */
2268
+ export function addrOf(headerValue) {
2269
+ const s = String(headerValue ?? "").trim();
2270
+ if (!s) return "";
2271
+ const m = s.match(/<([^<>\s]+@[^<>\s]+)>/);
2272
+ if (m) return m[1];
2273
+ const bare = s.match(/[^\s,;<"]+@[^\s,;>"]+/);
2274
+ return bare ? bare[0] : "";
2275
+ }
2276
+
2277
+ /** 主题加 Re:(已经以 Re:/答复:/Re:开头就不重复加)。 */
2278
+ export function replySubject(subject) {
2279
+ const s = String(subject ?? "").trim();
2280
+ if (!s) return "Re:";
2281
+ return /^(re|答复|回覆|回复)\s*[::]/i.test(s) ? s : `Re: ${s}`;
2282
+ }
2283
+
2284
+ /** 引用原文:保留「谁在什么时候写的」+ 逐行 `> `。只取前 limit 字符,别把整封信塞回去。 */
2285
+ export function quoteOriginal(orig = {}, { limit = 2000 } = {}) {
2286
+ // 纯 HTML 的来信也别丢掉引用:退回剥过标签的正文,总比空引用好
2287
+ const body = String(orig.bodyText ?? "").trim() || (orig.html ? digestLib.cleanText(orig.html) : "");
2288
+ const clipped = String(body ?? "").replace(/\s+$/u, "");
2289
+ if (!clipped) return "";
2290
+ const who = String(orig.from ?? "").trim() || "对方";
2291
+ const when = String(orig.date ?? "").trim();
2292
+ const clip = clipped.length > limit ? `${clipped.slice(0, limit)}\n…(引用已截断)` : clipped;
2293
+ const lines = clip.split(/\r?\n/).map((l) => (l ? `> ${l}` : ">")).join("\n");
2294
+ return `\n\n--- 原始邮件 ---\n${who}${when ? ` 于 ${when} 写道:` : " 写道:"}\n${lines}`;
2295
+ }
2296
+
2297
+ /** 回复收件人:replyAll 时取「原 To+Cc 去掉自己」,否则只回 From。
2298
+ * 自己发给自己的信(From 就是自己)退回「原 To 去掉自己」,否则会算出空收件人。 */
2299
+ export function replyRecipients(orig = {}, { self = "", replyAll = false } = {}) {
2300
+ const me = String(self).toLowerCase();
2301
+ const split = (v) => String(v ?? "").split(/[,;]/).map((x) => addrOf(x)).filter(Boolean);
2302
+ const notMe = (a) => a.toLowerCase() !== me;
2303
+ let to = split(orig.from).filter(notMe);
2304
+ if (!to.length) to = split(orig.to).filter(notMe);
2305
+ if (!replyAll) return { to, cc: [] };
2306
+ const cc = [...split(orig.to), ...split(orig.cc)]
2307
+ .filter(notMe)
2308
+ .filter((a) => !to.some((t) => t.toLowerCase() === a.toLowerCase()));
2309
+ return { to, cc };
2310
+ }
2311
+
2312
+ export { apply };