dsh-postbox 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,863 @@
1
+ // lib/tools-m4.js — M4 工具面扩展(M4.5 写操作)。
2
+ //
3
+ // 为什么单独一个文件:index.js 已经 1400+ 行,再塞 5 个工具会彻底看不清边界。
4
+ // 这里只做「参数 → 存储/检索 → 文本」,依赖全部通过 deps 注入,于是可以离线单测:
5
+ // deps = { top, ensureStore, reindex, withClient, watcherState, lastCheck, archiveSearch, log, now }
6
+ //
7
+ // 每个 build*Tool 都返回 **defineTool 编译过的定义**(schema 里写错会在这里立刻炸,
8
+ // 而不是等用户在 GUI 里点到才发现)。
9
+
10
+ import { defineTool } from "./tool.js";
11
+ import { matchRules, scoreMessage } from "./importance.js";
12
+ import { archiveSearch as defaultSearch } from "./search.js";
13
+ import { parseMime } from "./mime.js";
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+
17
+ const DAY_MS = 24 * 3600 * 1000;
18
+
19
+ /** 取一封的正文:优先从落盘的 .eml 解(full 模式),拿不到就退回 snippet。
20
+ * M7 按需摘要要用它 —— 摘要质量取决于正文,没有正文就只能拿标题了。 */
21
+ function bodyOf(store, row) {
22
+ try {
23
+ const raw = store.readRaw?.(row);
24
+ if (raw) return { ...row, body: parseMime(raw).bodyText };
25
+ } catch { /* 读不到/解不开就用 snippet */ }
26
+ return { ...row, body: row.snippet ?? "" };
27
+ }
28
+
29
+ // ---------------------------------------------------------------- 小工具
30
+ const s = (v) => (v == null ? "" : String(v));
31
+
32
+ function fmtTs(ts) {
33
+ if (!Number.isFinite(Number(ts))) return "?";
34
+ const d = new Date(Number(ts));
35
+ const p = (n) => String(n).padStart(2, "0");
36
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
37
+ }
38
+
39
+ function fmtBytes(n) {
40
+ const v = Number(n) || 0;
41
+ if (v < 1024) return `${v} B`;
42
+ if (v < 1024 * 1024) return `${(v / 1024).toFixed(1)} KB`;
43
+ return `${(v / 1024 / 1024).toFixed(1)} MB`;
44
+ }
45
+
46
+ /** ISO 日期(含日)→ 毫秒;`until` 语义是**不含当日**(与 mailbox_search 一致)。 */
47
+ function tsOf(iso, { endOfDay = false } = {}) {
48
+ if (!iso) return null;
49
+ const str = String(iso).trim();
50
+ if (!str) return null;
51
+ const t = Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(str) ? `${str}T00:00:00Z` : str);
52
+ if (!Number.isFinite(t)) return null;
53
+ return endOfDay ? t + DAY_MS : t;
54
+ }
55
+
56
+ /** 证据的可读化:存的可能是纯字符串,也可能是 {subject,uid,date,folder} 这样的邮件坐标。
57
+ * 直接 JSON.stringify 出来的引号/转义会让人(和 LLM)读不懂 —— 这里是「证据回查」的入口。 */
58
+ export function evidenceText(ev) {
59
+ if (ev == null || ev === "") return null;
60
+ const raw = String(ev);
61
+ try {
62
+ const v = JSON.parse(raw);
63
+ if (typeof v === "string") return v;
64
+ if (v && typeof v === "object") {
65
+ const bits = [v.date, v.subject, v.uid != null ? `uid=${v.uid}` : null, v.folder, v.account].filter(Boolean);
66
+ if (bits.length) return bits.join(" ");
67
+ }
68
+ return JSON.stringify(v);
69
+ } catch { return raw; }
70
+ }
71
+
72
+ function mailLine(m, { showScore = false } = {}) {
73
+ const when = fmtTs(m.dateTs ?? m.first_seen_at);
74
+ const hit = showScore && Number.isFinite(m.score) && m.score > 0 ? ` ·命中 ${(m.fields ?? []).join("/") || "?"}` : "";
75
+ return `uid=${m.uid} [${when}] ${s(m.from) || "?"} | ${s(m.subject) || "(无主题)"}${m.seen ? "" : " (未读)"}${hit}`;
76
+ }
77
+
78
+ /** 统一包住「归档库不可用」这类必然失败,让工具回文本而不是抛栈。 */
79
+ async function withStore(deps, fn) {
80
+ let store;
81
+ try {
82
+ store = await deps.ensureStore();
83
+ } catch (e) {
84
+ return { text: `归档库打不开:${e?.message ?? e}` };
85
+ }
86
+ try {
87
+ return await fn(store);
88
+ } catch (e) {
89
+ return { text: `归档库操作失败:${e?.message ?? e}` };
90
+ }
91
+ }
92
+
93
+ export const MODE_HINT = {
94
+ online: "当前 archive.mode=online:不落本地归档(只有 IMAP 实时查询),无法本地检索。改成 metadata 或 full 才有归档。",
95
+ metadata: "当前 archive.mode=metadata:只归档标题/发件人/收件人,正文未入索引——搜不到正文里的词。要搜正文请改 full。",
96
+ full: "当前 archive.mode=full:正文与文本附件都已入索引。",
97
+ };
98
+
99
+ /** 扫附件目录:按 uid_N 子目录统计体积/数量,挑出最老的几个,标出超过 olderThanDays 的。 */
100
+ function scanAttachDir(dir, { olderThanDays = 0, topN = 5, now = Date.now() } = {}) {
101
+ const empty = {
102
+ exists: false, dirs: 0, files: 0, bytes: 0, oldestAt: null, top: [], pruneable: [],
103
+ summary: { dir, dirs: 0, files: 0, bytes: 0, oldestAt: null, pruneable: [], deleted: 0 },
104
+ };
105
+ if (!dir) return empty;
106
+ let entries = [];
107
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return empty; }
108
+ const rows = [];
109
+ let files = 0;
110
+ let bytes = 0;
111
+ let oldestAt = null;
112
+ for (const ent of entries) {
113
+ if (!ent.isDirectory()) continue;
114
+ const full = path.join(dir, ent.name);
115
+ let at = null;
116
+ let f = 0;
117
+ let b = 0;
118
+ try {
119
+ at = fs.statSync(full).mtimeMs;
120
+ for (const name of fs.readdirSync(full)) {
121
+ const st = fs.statSync(path.join(full, name));
122
+ if (!st.isFile()) continue;
123
+ f += 1;
124
+ b += st.size;
125
+ at = Math.min(at ?? st.mtimeMs, st.mtimeMs);
126
+ }
127
+ } catch { /* 单个目录读不动就跳过,别整块失败 */ }
128
+ files += f;
129
+ bytes += b;
130
+ if (at && (!oldestAt || at < oldestAt)) oldestAt = at;
131
+ rows.push({ name: ent.name, path: full, files: f, bytes: b, at });
132
+ }
133
+ rows.sort((a, b) => b.bytes - a.bytes);
134
+ const cutoff = olderThanDays > 0 ? now - olderThanDays * 86_400_000 : 0;
135
+ const pruneable = cutoff > 0 ? rows.filter((r) => r.at && r.at < cutoff) : [];
136
+ return {
137
+ exists: true, dirs: rows.length, files, bytes, oldestAt,
138
+ top: rows.filter((r) => r.bytes > 0).slice(0, topN).map((r) => ({ name: r.name, bytes: r.bytes })),
139
+ pruneable,
140
+ summary: {
141
+ dir, dirs: rows.length, files, bytes, oldestAt,
142
+ pruneable: pruneable.map((r) => ({ name: r.name, files: r.files, bytes: r.bytes, at: r.at })),
143
+ deleted: 0,
144
+ },
145
+ };
146
+ }
147
+
148
+ // ================================================================ mailbox_stats
149
+ export function buildStatsTool(deps) {
150
+ return defineTool({
151
+ name: "mailbox_stats",
152
+ description: "邮箱归档概览:各账户/文件夹的邮件数、未读、最近一封、同步健康、上次检查、索引规模、LLM 语义开关。纯本地读取,不联网。action=reindex 重建全文索引;action=llm_audit 看 LLM 外送审计流水(隐私护栏);action=sync_seen 立刻去服务器拉一次已读/移走状态并清未看留痕(不等下一轮轮询);action=attachments 盘点已落盘附件(体积/最老/可清理),带 olderThanDays + dryRun=false 才真删。",
153
+ parameters: {
154
+ action: { type: "string", enum: ["status", "reindex", "llm_audit", "sync_seen", "attachments"], description: "status(默认)看概览;reindex 重建倒排索引;llm_audit 看 LLM 外送审计;sync_seen 立刻刷新服务器已读状态;attachments 盘点/清理已保存的附件" },
155
+ account: { type: "string", description: "只看某个账户(可选);sync_seen 时只刷这个账户" },
156
+ limit: { type: "number", description: "llm_audit 时最多列几条,默认 20" },
157
+ onlyFailed: { type: "boolean", description: "llm_audit 时只看失败的" },
158
+ olderThanDays: { type: "number", description: "attachments:只处理超过这么多天的附件目录(不填=只盘点)" },
159
+ dryRun: { type: "boolean", description: "attachments:默认 true 只报告;要真删必须显式传 false" },
160
+ },
161
+ output: {
162
+ schema: {
163
+ type: "object", additionalProperties: false, required: ["text"],
164
+ properties: {
165
+ text: { type: "string" },
166
+ mode: { type: "string" },
167
+ folders: { type: "array", items: { type: "object", additionalProperties: true } },
168
+ index: { type: "object", additionalProperties: true },
169
+ audit: { type: "array", items: { type: "object", additionalProperties: true } },
170
+ stats: { type: "object", additionalProperties: true },
171
+ attachments: { type: "object", additionalProperties: true },
172
+ },
173
+ },
174
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
175
+ },
176
+ async execute(args = {}) {
177
+ const top = deps.top();
178
+ if (args.action === "reindex") {
179
+ const r = await deps.reindex();
180
+ if (r?.skipped) {
181
+ return { text: `没有可重建的内容:${MODE_HINT[top.archive.mode] ?? ""}`, mode: top.archive.mode };
182
+ }
183
+ return {
184
+ text: `倒排索引重建完成:扫描 ${r.scanned} 封,索引 ${r.indexed} 封,失败 ${r.failed} 封(archive.mode=${r.mode})\n${MODE_HINT[r.mode] ?? ""}`,
185
+ mode: r.mode,
186
+ };
187
+ }
188
+
189
+ // LLM 外送审计:隐私护栏的"可解释"入口 —— 用户能自己看到送过什么
190
+ if (args.action === "llm_audit") {
191
+ return withStore(deps, async (store) => {
192
+ const worker = deps.llm?.();
193
+ const s = store.llmAuditStats();
194
+ const rows = store.listLlmAudit({
195
+ limit: Math.min(Math.max(parseInt(args.limit ?? 20, 10) || 20, 1), 100),
196
+ onlyFailed: args.onlyFailed === true,
197
+ });
198
+ const lines = [`LLM 语义:${worker?.describe?.() ?? "未接线"}`];
199
+ lines.push(`审计流水 ${s.total} 条(${s.ok} 成功 / ${s.failed} 失败),累计外送 ${s.chars} 字,脱敏 ${s.redactions} 处${s.lastAt ? `,最近 ${fmtTs(s.lastAt)}` : ""}`);
200
+ if (!rows.length) {
201
+ lines.push(args.onlyFailed ? "(没有失败记录)" : "(没有外送记录 —— 没开 LLM,或者开了但还没有新邮件入库)");
202
+ }
203
+ for (const r of rows) {
204
+ lines.push(` ${fmtTs(r.at)} ${r.kind} ${r.account ?? "-"}/${r.folder ?? "-"} uid=${r.uid ?? "-"} `
205
+ + `${r.ok ? "成功" : "失败"} ${r.provider ?? "?"}/${r.model ?? "?"} ${r.chars} 字 脱敏${r.redactions}处 字段[${r.fields ?? "-"}]`
206
+ + `${r.ms != null ? ` ${r.ms}ms` : ""}${r.error ? ` — ${r.error}` : ""}`);
207
+ }
208
+ return { text: lines.join("\n"), audit: rows, stats: s };
209
+ });
210
+ }
211
+
212
+ // 按需刷新已读状态:走 watcher 的连接逻辑,但**不动水位、不抓新信**
213
+ if (args.action === "sync_seen") {
214
+ if (typeof deps.syncSeen !== "function") {
215
+ return { text: "watcher 未运行,无法刷新服务器状态(先让 watcher 起来,或调 mailbox_resync)" };
216
+ }
217
+ let r;
218
+ try { r = await deps.syncSeen({ account: args.account || null }); }
219
+ catch (e) { return { text: `刷新已读状态失败:${e?.message ?? e}` }; }
220
+ if (!r) return { text: "watcher 未运行,无法刷新服务器状态(先让 watcher 起来,或调 mailbox_resync)" };
221
+ const lines = [
222
+ r?.ok === false ? "刷新已读状态:部分失败" : "刷新已读状态:完成",
223
+ `检查 ${r?.checked ?? 0} 个文件夹 · 已读 ${r?.seen ?? 0} 封 · 自动确认提示 ${r?.acked ?? 0} 条 · 服务器已无 ${r?.gone ?? 0} 封`,
224
+ ];
225
+ for (const x of r?.results ?? []) {
226
+ lines.push(` ${x.account}/${x.folder}:已读 ${x.seen} · 提示 ${x.acked} · 已无 ${x.gone}`);
227
+ }
228
+ for (const e of r?.errors ?? []) lines.push(` ⚠ ${e}`);
229
+ if (!r?.checked) lines.push("(没有可检查的文件夹:账户未配置 folders/defaultFolder?)");
230
+ return { text: lines.join("\n"), mode: top.archive.mode, stats: r };
231
+ }
232
+
233
+ // 附件落盘盘点/清理(B9):附件是全库唯一会无限长胖的东西,必须有个口子能看见能清
234
+ if (args.action === "attachments") {
235
+ const dir = String(top.attachDir ?? "");
236
+ const olderDays = Number(args.olderThanDays ?? 0);
237
+ const dryRun = args.dryRun !== false; // 默认只报告,不删 —— 删附件是不可逆操作
238
+ const scan = scanAttachDir(dir, { olderThanDays: Number.isFinite(olderDays) && olderDays > 0 ? olderDays : 0 });
239
+ const lines = [
240
+ `附件目录:${dir || "(未配置)"}`,
241
+ dir && !scan.exists
242
+ ? "(目录还不存在 —— 没保存过附件,或附件落到了别处)"
243
+ : `共 ${scan.dirs} 个邮件目录 / ${scan.files} 个文件 / ${fmtBytes(scan.bytes)}${scan.oldestAt ? `,最早 ${fmtTs(scan.oldestAt)}` : ""}`,
244
+ ];
245
+ if (scan.top.length) {
246
+ lines.push(`最大的 ${scan.top.length} 个:`);
247
+ for (const t of scan.top) lines.push(` ${fmtBytes(t.bytes)} ${t.name}`);
248
+ }
249
+ if (scan.pruneable.length) {
250
+ const n = scan.pruneable.reduce((a, x) => a + x.files, 0);
251
+ const b = scan.pruneable.reduce((a, x) => a + x.bytes, 0);
252
+ lines.push(`超过 ${olderDays} 天的目录:${scan.pruneable.length} 个(${n} 个文件,${fmtBytes(b)})`);
253
+ if (dryRun) {
254
+ lines.push("dryRun=true(默认):上面这些**没有删**。确认要清就再调一次带 dryRun=false。");
255
+ } else {
256
+ for (const p of scan.pruneable) {
257
+ try { fs.rmSync(p.path, { recursive: true, force: true }); lines.push(` 已删除 ${p.name}(${fmtBytes(p.bytes)})`); }
258
+ catch (e) { lines.push(` ⚠ 删不掉 ${p.name}:${e?.message ?? e}`); }
259
+ }
260
+ }
261
+ } else if (olderDays > 0) {
262
+ lines.push(`没有超过 ${olderDays} 天的附件目录。`);
263
+ }
264
+ return { text: lines.join("\n"), mode: top.archive.mode, attachments: scan.summary };
265
+ }
266
+
267
+ return withStore(deps, async (store) => {
268
+ const all = store.stats();
269
+ const folders = args.account ? all.filter((x) => x.account === args.account) : all;
270
+ const index = store.indexStats();
271
+ const st = deps.watcherState?.() ?? {};
272
+ const last = deps.lastCheck?.() ?? null;
273
+ const lines = [];
274
+
275
+ lines.push(`归档库:${store.dbPath}(模式 ${top.archive.mode},schema v${store.schemaVersion})`);
276
+ lines.push(`倒排索引:${index.messages} 封 / ${index.entries} 词条 / ${index.tokens} 个词`);
277
+ lines.push(st.running
278
+ ? `watcher:运行中 · 每 ${top.pollIntervalSeconds}s${st.paused ? " · 已暂停" : ""}${last ? ` · 上次检查 ${fmtTs(last.at)}(抓 ${last.fetched ?? 0} 封,失败 ${last.failures ?? 0},下次 ${last.nextDelaySeconds ?? "?"}s 后)` : " · 尚无检查记录"}`
279
+ : `watcher:未运行(${st.reason ?? "未知原因"})`);
280
+
281
+ // 配置里有、归档里还没有的账户也要列出来——否则用户会以为"没配"
282
+ const emails = [...new Set([...top.accounts.map((a) => a.email), ...folders.map((f) => f.account)])];
283
+ for (const email of emails) {
284
+ const rows = folders.filter((f) => f.account === email);
285
+ const conf = top.accounts.find((a) => a.email === email);
286
+ lines.push(`账户 ${email}${conf ? "" : "(配置里没有)"}`);
287
+ if (!rows.length) { lines.push(" (还没有归档邮件)"); continue; }
288
+ for (const r of rows) {
289
+ // 邮箱文件夹名不分大小写(INBOX/inbox 是同一个);留空 folders = 只监控 defaultFolder。
290
+ // 老写法直接 includes() 大小写敏感比较,把正在监听的 Inbox 标成「不在监听列表」(2026-11-27 修)。
291
+ const list = (conf?.folders?.length ? conf.folders : [conf?.defaultFolder]).filter(Boolean);
292
+ const configured = !conf ? true : list.some((f) => String(f).toLowerCase() === String(r.folder).toLowerCase());
293
+ lines.push(` ${r.folder}${configured ? "" : "(不在监听列表)"}:共 ${r.total} 封(未读 ${r.unread}),最近 ${fmtTs(r.newestTs)}${r.rawBytes ? `,原始信 ${fmtBytes(r.rawBytes)}` : ""}`);
294
+ }
295
+ }
296
+
297
+ const sync = store.listSyncState();
298
+ const healthy = sync.filter((x) => x.health === "ok").length;
299
+ if (sync.length) {
300
+ lines.push(`同步水位:${sync.length} 个文件夹(${healthy} 个健康)`);
301
+ for (const x of sync.filter((y) => y.health !== "ok")) {
302
+ lines.push(` ⚠ ${x.account}/${x.folder}:${x.health}${x.lastError ? ` — ${x.lastError}` : ""}`);
303
+ }
304
+ // 已恢复但有留痕:last_error 不再被成功轮次抹掉(见 lib/sync.js),所以这里必须
305
+ // 把"已恢复"讲清楚,免得用户看到旧错误以为还在坏(M6.6)。
306
+ for (const x of sync.filter((y) => y.health === "ok" && y.lastError)) {
307
+ lines.push(` ✓ ${x.account}/${x.folder}:已恢复(最近一次失败:${x.lastError})`);
308
+ }
309
+ }
310
+ try {
311
+ lines.push(`标签 ${store.countTags()} 个 / 事实 ${store.countFacts()} 条 / 待推通知 ${store.listNotices({ limit: 5, unseenOnly: true }).length} 条 / 日报积压 ${store.digestQueueSize()} 封`);
312
+ } catch { /* online 模式没有元数据表 */ }
313
+
314
+ // M7:LLM 语义开关与审计规模(默认"未启用(零外送)",让用户一眼看到没在偷偷外送)
315
+ const worker = deps.llm?.();
316
+ if (worker) {
317
+ try {
318
+ lines.push(`LLM 语义:${worker.describe()}${store.countSummaries ? ` · 已缓存摘要 ${store.countSummaries()} 封` : ""}`);
319
+ } catch { /* 审计表不可用就跳过 */ }
320
+ }
321
+
322
+ return { text: lines.join("\n").trimEnd(), mode: top.archive.mode, folders, index };
323
+ });
324
+ },
325
+ });
326
+ }
327
+
328
+ // ================================================================ 归档检索(共用)
329
+ function archiveSearchText(res, { limit }) {
330
+ const head = [];
331
+ if (res.notes?.length) head.push(...res.notes.map((n) => `# ${n}`));
332
+ const body = res.mail.length
333
+ ? res.mail.map((m) => mailLine(m, { showScore: true })).join("\n")
334
+ : `0 命中(本地索引 ${res.indexed} 封)`;
335
+ const tail = res.partial ? "" : "";
336
+ void limit; void tail;
337
+ return [...head, body].join("\n");
338
+ }
339
+
340
+ /** `mailbox_search(source=archive)` 与 `mailbox_archive_search` 共用同一实现。 */
341
+ export async function runArchiveSearch(deps, args = {}) {
342
+ const top = deps.top();
343
+ if (top.archive.mode === "online") {
344
+ return { text: MODE_HINT.online, mode: "online", total: 0, mail: [] };
345
+ }
346
+ const search = deps.archiveSearch ?? defaultSearch;
347
+ return withStore(deps, async (store) => {
348
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 25, 10) || 25, 1), 100);
349
+ const res = search(store, {
350
+ q: args.q ?? null,
351
+ account: args.account ?? null,
352
+ folder: args.folder ?? null,
353
+ from: args.from ?? null,
354
+ subject: args.subject ?? null,
355
+ unreadOnly: args.unreadOnly === true,
356
+ sinceTs: tsOf(args.since),
357
+ untilTs: tsOf(args.until, { endOfDay: true }),
358
+ tag: args.tag ?? null,
359
+ limit,
360
+ mode: top.archive.mode,
361
+ withTags: args.withTags !== false,
362
+ });
363
+ return {
364
+ text: archiveSearchText(res, { limit }),
365
+ mode: top.archive.mode,
366
+ total: res.total,
367
+ indexed: res.indexed,
368
+ partial: res.partial,
369
+ terms: res.terms,
370
+ mail: res.mail,
371
+ };
372
+ });
373
+ }
374
+
375
+ export function buildArchiveSearchTool(deps) {
376
+ return defineTool({
377
+ name: "mailbox_archive_search",
378
+ description: "在本地归档里检索(不联网、不消耗 IMAP)。支持关键词(2 字中文词/英文均可,按相关度排序)、发件人/主题子串、日期范围、未读、标签。可用范围取决于 archive.mode:metadata 只能搜标题/发件人,full 才能搜正文;online 无本地归档。",
379
+ parameters: {
380
+ q: { type: "string", description: "关键词(空格分隔多个词;中文按二元切分)" },
381
+ account: { type: "string", description: "账户(可选)" },
382
+ folder: { type: "string", description: "文件夹(可选)" },
383
+ from: { type: "string", description: "发件人子串(可选)" },
384
+ subject: { type: "string", description: "主题子串(可选)" },
385
+ since: { type: "string", description: "起始日期 ISO(含当日)" },
386
+ until: { type: "string", description: "截止日期 ISO(不含当日)" },
387
+ unreadOnly: { type: "boolean", description: "只未读" },
388
+ tag: { type: "string", description: "标签名(可选)" },
389
+ limit: { type: "number", description: "默认 25,上限 100" },
390
+ },
391
+ output: {
392
+ schema: {
393
+ type: "object", additionalProperties: false, required: ["text"],
394
+ properties: {
395
+ text: { type: "string" },
396
+ mode: { type: "string" },
397
+ total: { type: "number" },
398
+ indexed: { type: "number" },
399
+ partial: { type: "boolean" },
400
+ terms: { type: "array", items: { type: "string" } },
401
+ mail: { type: "array", items: { type: "object", additionalProperties: true } },
402
+ },
403
+ },
404
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
405
+ },
406
+ execute: (args) => runArchiveSearch(deps, args ?? {}),
407
+ });
408
+ }
409
+
410
+ // ================================================================ mailbox_tag
411
+ export function buildTagTool(deps) {
412
+ return defineTool({
413
+ name: "mailbox_tag",
414
+ description: "标签管理:action=list 列出标签;set/unset 给某封邮件打/去标签;show 列出某标签下的邮件;auto 按 config.tags.rules 规则给最近归档的邮件自动打标(manual 打的标签不会被覆盖)。纯本地。",
415
+ parameters: {
416
+ action: { type: "string", enum: ["list", "set", "unset", "show", "auto"], description: "默认 list" },
417
+ tag: { type: "string", description: "标签名(set/unset/show 必填)" },
418
+ tags: { type: "array", items: { type: "string" }, description: "set 时的标签数组(与 tag 二选一)" },
419
+ uid: { type: "number", description: "邮件 uid(set/unset 必填)" },
420
+ account: { type: "string", description: "账户(可选,默认唯一账户)" },
421
+ folder: { type: "string", description: "文件夹(默认 INBOX)" },
422
+ limit: { type: "number", description: "show/auto 的上限,默认 show=25 / auto=200" },
423
+ },
424
+ output: {
425
+ schema: {
426
+ type: "object", additionalProperties: false, required: ["text"],
427
+ properties: {
428
+ text: { type: "string" },
429
+ action: { type: "string" },
430
+ tags: { type: "array", items: { type: "object", additionalProperties: true } },
431
+ mail: { type: "array", items: { type: "object", additionalProperties: true } },
432
+ },
433
+ },
434
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
435
+ },
436
+ async execute(args = {}) {
437
+ const top = deps.top();
438
+ const action = args.action ?? "list";
439
+ if (top.archive.mode === "online") return { text: MODE_HINT.online, action };
440
+
441
+ return withStore(deps, async (store) => {
442
+ const acc = top.accounts.length === 1 ? top.accounts[0] : top.accounts.find((a) => a.email === args.account) ?? top.accounts[0];
443
+ const folder = args.folder || acc.defaultFolder;
444
+ const ref = { account: acc.email, folder, uid: Number(args.uid) };
445
+
446
+ if (action === "list") {
447
+ const tags = store.listTags();
448
+ return {
449
+ text: tags.length
450
+ ? `标签 ${tags.length} 个:\n` + tags.map((t) => ` ${t.name}(${t.count} 封,${t.source})`).join("\n")
451
+ : "还没有任何标签。用 action=set 打标,或 action=auto 按规则打标。",
452
+ action, tags,
453
+ };
454
+ }
455
+
456
+ if (action === "show") {
457
+ if (!args.tag) return { text: "action=show 需要 tag 参数", action };
458
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 25, 10) || 25, 1), 100);
459
+ const rows = store.messagesByTag(args.tag, { limit });
460
+ const others = store.listTags().find((t) => t.name === args.tag);
461
+ return {
462
+ text: rows.length
463
+ ? `标签「${args.tag}」下 ${rows.length} 封${others && others.count > rows.length ? `(共 ${others.count})` : ""}:\n` + rows.map((r) => mailLine(r)).join("\n")
464
+ : `标签「${args.tag}」下没有邮件${others ? "" : "(这个标签不存在)"}`,
465
+ action, mail: rows,
466
+ };
467
+ }
468
+
469
+ if (action === "auto") {
470
+ const rules = top.tags?.rules ?? [];
471
+ if (!rules.length) return { text: "config.tags.rules 是空的,没有可用的规则标签。", action };
472
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 200, 10) || 200, 1), 2000);
473
+ const rows = store.listMessages({ account: args.account ?? null, folder: args.folder ?? null, limit });
474
+ const applied = [];
475
+ for (const row of rows) {
476
+ const hit = matchRules(rules, { from: row.from_addr, subject: row.subject });
477
+ if (!hit.length) continue;
478
+ const merged = [...new Set([...store.tagsOf(row), ...hit])];
479
+ if (merged.length === store.tagsOf(row).length) continue;
480
+ store.setTags(row, merged, "rule");
481
+ applied.push({ uid: row.uid, folder: row.folder, subject: row.subject, tags: hit });
482
+ }
483
+ return {
484
+ text: `规则标签:扫了最近 ${rows.length} 封,新打标 ${applied.length} 封。` +
485
+ (applied.length ? "\n" + applied.slice(0, 20).map((a) => `uid=${a.uid} ${s(a.subject) || "(无主题)"} → ${a.tags.join("/")}`).join("\n") : ""),
486
+ action, mail: applied,
487
+ };
488
+ }
489
+
490
+ // set / unset
491
+ if (!Number.isFinite(ref.uid)) return { text: `action=${action} 需要 uid 参数(可用 mailbox_archive_search 先查 uid)`, action };
492
+ const names = [...new Set([].concat(args.tags ?? [], args.tag ?? []).map((x) => s(x).trim()).filter(Boolean))];
493
+ if (!names.length) return { text: `action=${action} 需要 tag 或 tags 参数`, action };
494
+ if (!store.getMessage(ref)) {
495
+ return { text: `归档里没有 ${ref.account}/${ref.folder}/uid=${ref.uid}(先让 watcher 抓到这封,或换个 uid)`, action };
496
+ }
497
+ const before = store.tagsOf(ref);
498
+ const after = action === "set"
499
+ ? store.setTags(ref, [...new Set([...before, ...names])])
500
+ : store.setTags(ref, before.filter((n) => !names.includes(n)));
501
+ return {
502
+ text: `${action === "set" ? "已打标" : "已去标"}:${ref.account}/${ref.folder}/uid=${ref.uid}\n标签:${before.join("/") || "(无)"} → ${after.join("/") || "(无)"}`,
503
+ action,
504
+ };
505
+ });
506
+ },
507
+ });
508
+ }
509
+
510
+ // ================================================================ mailbox_facts
511
+ export function buildFactsTool(deps) {
512
+ return defineTool({
513
+ name: "mailbox_facts",
514
+ description: "长期事实库(键值 + 证据 + 核验结论 + 修订链):action=list 列全部;show 看一条的详情与历史;verify 标记已核验;set 记录/更新一条;digest 生成一份「已知事实」清单。每条都带来源与核验状态。",
515
+ parameters: {
516
+ action: { type: "string", enum: ["list", "show", "digest", "verify", "set"], description: "默认 list" },
517
+ key: { type: "string", description: "事实键(show/verify/set 必填)" },
518
+ value: { type: "string", description: "事实值(set 必填)" },
519
+ evidence: { type: "string", description: "证据(set 可选,通常写「哪封邮件/什么日期」)" },
520
+ source: { type: "string", description: "来源标记(set 可选)" },
521
+ limit: { type: "number", description: "list/digest 上限,默认 50" },
522
+ },
523
+ output: {
524
+ schema: {
525
+ type: "object", additionalProperties: false, required: ["text"],
526
+ properties: {
527
+ text: { type: "string" },
528
+ action: { type: "string" },
529
+ facts: { type: "array", items: { type: "object", additionalProperties: true } },
530
+ history: { type: "array", items: { type: "object", additionalProperties: true } },
531
+ },
532
+ },
533
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
534
+ },
535
+ async execute(args = {}) {
536
+ const action = args.action ?? "list";
537
+ return withStore(deps, async (store) => {
538
+ const brief = (f) => {
539
+ const ev = evidenceText(f.evidence_json);
540
+ const verify = f.verified_at ? `已核验 ${fmtTs(f.verified_at)}` : "**未核验**";
541
+ return `${f.key} = ${f.value}\n ${verify} · v${f.version} · 更新 ${fmtTs(f.updated_at)} · 来源 ${s(f.source) || "-"} · 证据:${ev ?? "(无)"}`;
542
+ };
543
+
544
+ if (action === "list" || action === "digest") {
545
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 50, 10) || 50, 1), 500);
546
+ const facts = store.listFacts().slice(0, limit);
547
+ if (!facts.length) return { text: "事实库是空的。用 action=set 记录第一条(key/value/evidence)。", action, facts: [] };
548
+ if (action === "digest") {
549
+ const unverified = facts.filter((f) => !f.verified_at);
550
+ return {
551
+ text: [
552
+ `已知事实 ${facts.length} 条(${unverified.length} 条未核验):`,
553
+ ...facts.map((f) => {
554
+ const ev = evidenceText(f.evidence_json);
555
+ return `- ${f.key}=${f.value}${f.verified_at ? "" : "(未核验)"}${ev ? ` [${ev}]` : ""}`;
556
+ }),
557
+ unverified.length ? `\n⚠ 有 ${unverified.length} 条未核验,引用前先 action=verify 或补证据。` : "\n全部已核验。",
558
+ ].join("\n"),
559
+ action, facts,
560
+ };
561
+ }
562
+ return { text: `事实 ${facts.length} 条:\n\n` + facts.map(brief).join("\n\n"), action, facts };
563
+ }
564
+
565
+ const key = s(args.key).trim();
566
+ if (!key) return { text: `action=${action} 需要 key 参数`, action };
567
+
568
+ if (action === "show") {
569
+ const f = store.getFact(key);
570
+ if (!f) return { text: `没有这条事实:${key}(用 action=list 看全部)`, action };
571
+ const history = store.factHistory(key);
572
+ return {
573
+ text: brief(f) + `\n\n修订链 ${history.length} 版:\n` +
574
+ history.map((x) => ` v${x.version} ${fmtTs(x.created_at)} ${x.value}${evidenceText(x.evidence_json) ? ` [${evidenceText(x.evidence_json)}]` : ""}`).join("\n"),
575
+ action, history,
576
+ };
577
+ }
578
+
579
+ if (action === "verify") {
580
+ const f = store.getFact(key);
581
+ if (!f) return { text: `没有这条事实:${key}`, action };
582
+ if (f.verified_at) return { text: `这条事实已经在 ${fmtTs(f.verified_at)} 核验过了(值:${f.value})。`, action };
583
+ store.markFactVerified(key);
584
+ const ts = store.getFact(key)?.verified_at;
585
+ return { text: `已核验:${key} = ${f.value}(${fmtTs(ts)})`, action };
586
+ }
587
+
588
+ // set
589
+ if (args.value == null || s(args.value) === "") return { text: "action=set 需要 value 参数", action };
590
+ const r = store.putFact({ key, value: args.value, evidence: args.evidence ?? null, source: args.source ?? "tool" });
591
+ return {
592
+ text: r.changed
593
+ ? `已记录:${key} = ${args.value}(v${r.version}${args.evidence ? `,证据:${args.evidence}` : ""})\n注意:新版本会清掉"已核验"标记,引用前请 action=verify。`
594
+ : `值没有变化,未产生新版本(v${r.version}):${key} = ${args.value}`,
595
+ action,
596
+ };
597
+ });
598
+ },
599
+ });
600
+ }
601
+
602
+ // ================================================================ mailbox_digest
603
+ /** 启发式要点汇总(LLM 缺席时的兜底;M7 打开 llm.enabled 后会换成 LLM 摘要)。 */
604
+ export function heuristicDigest(items = [], { rules = [], knownDomains = [], top = 8 } = {}) {
605
+ const scored = items.map((row) => ({ row, ...scoreMessage({ ...row, from: row.from_addr, snippet: row.snippet }, { rules, knownDomains }) }))
606
+ .sort((a, b) => (b.score - a.score) || ((b.row.date_ts ?? 0) - (a.row.date_ts ?? 0)));
607
+ const unread = items.filter((r) => r.seen === 0).length;
608
+ const senders = [...new Set(items.map((r) => r.from_addr).filter(Boolean))];
609
+ const promo = scored.filter((x) => x.promo).length;
610
+ const points = scored.slice(0, Math.max(1, top)).map((x, i) => {
611
+ const code = x.row.otp ? ` 🔑 ${x.row.otp}` : "";
612
+ return `${i + 1}. [${x.score}] ${fmtTs(x.row.date_ts ?? x.row.first_seen_at)} ${s(x.row.from_addr) || "?"} | ${s(x.row.subject) || "(无主题)"}${code}${x.row.seen === 0 ? " (未读)" : ""}\n ${x.reasons.join(";") || "无特别信号"}`;
613
+ });
614
+ return {
615
+ total: items.length, unread, promo, senders: senders.length,
616
+ highlights: points, scored,
617
+ };
618
+ }
619
+
620
+ export function buildDigestTool(deps) {
621
+ return defineTool({
622
+ name: "mailbox_digest",
623
+ description: "时间窗要点汇总:统计窗口内的新邮件,按重要性(验证码/截止/附件/规则标签…)排序给出要点。默认纯本地启发式(不调用 LLM);queued=true 看日报积压队列。",
624
+ parameters: {
625
+ hours: { type: "number", description: "回看小时数,默认 24" },
626
+ since: { type: "string", description: "起始时间 ISO(与 hours 二选一,优先级更高)" },
627
+ limit: { type: "number", description: "最多读多少封,默认 100" },
628
+ top: { type: "number", description: "要点条数,默认 8" },
629
+ account: { type: "string", description: "账户(可选)" },
630
+ folder: { type: "string", description: "文件夹(可选)" },
631
+ queued: { type: "boolean", description: "改为查看日报积压队列" },
632
+ clear: { type: "boolean", description: "查看积压后清空队列(queued=true 时生效)" },
633
+ llm: { type: "boolean", description: "true 时对要点里还没摘要的邮件跑一次 LLM 摘要(需 llm.digest.enabled;默认只展示已缓存摘要)" },
634
+ },
635
+ output: {
636
+ schema: {
637
+ type: "object", additionalProperties: false, required: ["text"],
638
+ properties: {
639
+ text: { type: "string" },
640
+ total: { type: "number" },
641
+ unread: { type: "number" },
642
+ mode: { type: "string" },
643
+ highlights: { type: "array", items: { type: "string" } },
644
+ llm: { type: "object", additionalProperties: true },
645
+ },
646
+ },
647
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
648
+ },
649
+ async execute(args = {}) {
650
+ const top = deps.top();
651
+ const when = deps.now?.() ?? Date.now();
652
+
653
+ if (args.queued) {
654
+ return withStore(deps, async (store) => {
655
+ const q = store.listDigestQueue({ limit: 200 });
656
+ const cleared = args.clear ? store.clearDigestQueue() : 0;
657
+ return {
658
+ text: q.length
659
+ ? `日报积压 ${q.length} 封${args.clear ? `,已清空 ${cleared} 封` : "(加 clear=true 清空)"}:\n` +
660
+ q.slice(0, 50).map((x) => `uid=${x.uid} [${fmtTs(x.date_ts ?? x.queued_at)}] ${s(x.subject) || "(无主题)"} — ${s(x.from_addr) || "?"}(score ${x.score ?? "-"})`).join("\n")
661
+ : "日报积压队列是空的。",
662
+ total: q.length, mode: top.archive.mode,
663
+ };
664
+ });
665
+ }
666
+
667
+ const sinceTs = tsOf(args.since) ?? (when - Math.max(1, Number(args.hours ?? 24) || 24) * 3600 * 1000);
668
+ const limit = Math.min(Math.max(parseInt(args.limit ?? 100, 10) || 100, 1), 1000);
669
+ const topN = Math.min(Math.max(parseInt(args.top ?? 8, 10) || 8, 1), 30);
670
+ const span = `${fmtTs(sinceTs)} 起`;
671
+
672
+ if (top.archive.mode === "online") {
673
+ // online 不落归档 → 退化成"看通知记录",仍然是本地数据
674
+ return withStore(deps, async (store) => {
675
+ const notices = store.listNotices({ limit: 100 }).filter((n) => (n.created_at ?? 0) >= sinceTs);
676
+ return {
677
+ text: `${MODE_HINT.online}\n改用通知记录汇总(${span}):${notices.length} 条\n` +
678
+ notices.slice(0, 20).map((n) => `- ${fmtTs(n.created_at)} ${s(n.title) || s(n.kind)}`).join("\n"),
679
+ total: notices.length, mode: "online",
680
+ };
681
+ });
682
+ }
683
+
684
+ return withStore(deps, async (store) => {
685
+ const rows = store.listMessages({ account: args.account ?? null, folder: args.folder ?? null, sinceTs, limit });
686
+ const d = heuristicDigest(rows, { rules: top.tags?.rules ?? [], knownDomains: top.knownDomains ?? [], top: topN });
687
+ const worker = deps.llm?.();
688
+ const llmOn = worker?.enabled?.("digest") === true;
689
+ let llmRun = null;
690
+ let llmNote = llmOn
691
+ ? `LLM 摘要已启用(${top.llm?.digest?.model || "跟随 DSH 默认模型"})`
692
+ : "启发式汇总(未调用 LLM;要开语义摘要需在部署层打开 llm.digest.enabled 并重启)";
693
+
694
+ // 按需补摘要:只补"要点里还没有摘要"的,且**受 maxPerRun 限制**——
695
+ // 一次工具调用不该悄悄把上百封邮件送给模型。
696
+ if (args.llm === true && worker) {
697
+ if (!llmOn) {
698
+ llmNote = "你要求了 LLM 摘要,但 llm.digest.enabled=false —— 本次仍用启发式,零外送";
699
+ } else {
700
+ const cap = Math.min(Number(top.llm?.digest?.maxPerRun ?? 5) || 5, d.scored.length);
701
+ const targets = d.scored.slice(0, cap).filter((x) => !x.row.llm_summary);
702
+ const results = [];
703
+ for (const t of targets) {
704
+ const ref = { account: t.row.account, folder: t.row.folder, uid: t.row.uid };
705
+ results.push({ uid: t.row.uid, ...(await worker.runOne(ref, bodyOf(store, t.row), { kinds: ["digest"] })) });
706
+ }
707
+ llmRun = { cap, requested: targets.length, results };
708
+ const okN = results.filter((r) => r.ok).length;
709
+ const skipN = results.filter((r) => r.skipped).length;
710
+ llmNote = `LLM 摘要已启用:本次处理 ${results.length} 封(${okN} 成功${skipN ? `,${skipN} 被封禁/排除` : ""}${results.length - okN - skipN ? `,${results.length - okN - skipN} 失败` : ""})`;
711
+ for (const r of results.filter((x) => !x.ok)) llmNote += `\n ⚠ uid=${r.uid}:${r.error ?? r.reason}`;
712
+ }
713
+ }
714
+
715
+ const head = d.total
716
+ ? `${span}:新归档 ${d.total} 封(未读 ${d.unread},发件人 ${d.senders} 个,疑似营销 ${d.promo} 封) · ${llmNote}`
717
+ : `${span}:没有新归档邮件。`;
718
+ const body = d.highlights.length ? "\n\n要点(按重要性):\n" + d.highlights.join("\n") : "";
719
+ // 已缓存摘要直接展示(它们是入库时算好的,不再重复外送)。
720
+ // 注意:刚跑完的那批要**重新读**才看得到 —— rows 是跑之前取的快照。
721
+ const cached = (llmRun ? store.listMessages({ account: args.account ?? null, folder: args.folder ?? null, sinceTs, limit }) : rows)
722
+ .filter((r) => r.llm_summary);
723
+ const cachedBlock = cached.length
724
+ ? `\n\nLLM 摘要(已缓存 ${cached.length} 封):\n` + cached.slice(0, topN)
725
+ .map((r) => `- uid=${r.uid} ${s(r.subject) || "(无主题)"} → ${r.llm_summary}`).join("\n")
726
+ : "";
727
+ return {
728
+ text: head + body + cachedBlock, total: d.total, unread: d.unread, mode: top.archive.mode,
729
+ highlights: d.highlights, llm: { enabled: llmOn, cached: cached.length, run: llmRun },
730
+ };
731
+ });
732
+ },
733
+ });
734
+ }
735
+
736
+ // ================================================================ M4.5 写操作工具
737
+ export const WRITE_HINT = "仅在用户明确要求时调用;本插件不做删除(EXPUNGE 不可逆)。";
738
+
739
+ export function buildMarkTool(deps) {
740
+ return defineTool({
741
+ name: "mailbox_mark",
742
+ description: `把某封邮件标记为已读/未读(服务器端 \\Seen 标志,幂等);action="mark_all_read" 时把整个文件夹的未读一次性标为已读。${WRITE_HINT} 需要部署层 write.enabled=true 才存在。`,
743
+ parameters: {
744
+ action: { type: "string", enum: ["set", "mark_all_read"], description: "set=标单封(默认);mark_all_read=把这个文件夹里所有未读标为已读" },
745
+ uid: { type: "number", description: "邮件 uid(action=set 时必填)" },
746
+ seen: { type: "boolean", description: "action=set 时:true=已读(默认),false=未读" },
747
+ account: { type: "string", description: "账户(可选,默认唯一账户)" },
748
+ folder: { type: "string", description: "文件夹(默认 INBOX)" },
749
+ },
750
+ output: {
751
+ schema: {
752
+ type: "object", additionalProperties: false, required: ["text"],
753
+ properties: {
754
+ text: { type: "string" }, uid: { type: "number" }, seen: { type: "boolean" },
755
+ folder: { type: "string" }, action: { type: "string" }, marked: { type: "number" },
756
+ },
757
+ },
758
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
759
+ },
760
+ async execute(args = {}) {
761
+ const action = s(args.action) || "set";
762
+
763
+ // ---------------- R1:整个文件夹的未读一次性标已读(2026-11-29)
764
+ if (action === "mark_all_read") {
765
+ return deps.withClient(args.account, args.folder, async (client, acc) => {
766
+ const folder = args.folder || acc.defaultFolder;
767
+ const uids = await client.uidSearch({ unseen: true });
768
+ if (!uids.length) return { text: `${acc.email}/${folder} 没有未读邮件,无需处理。`, action, marked: 0, folder };
769
+ // 一次 UID STORE 带 200 个 uid:既少往返,又不会把命令行撑得太长
770
+ let marked = 0;
771
+ for (let i = 0; i < uids.length; i += 200) {
772
+ marked += await client.setSeenBulk(uids.slice(i, i + 200), true);
773
+ }
774
+ let local = "";
775
+ try {
776
+ const store = await deps.ensureStore();
777
+ const r = store.syncSeenFlags(acc.email, folder, uids.map((uid) => ({ uid, seen: true })));
778
+ const acked = typeof store.ackNoticesForSeen === "function"
779
+ ? store.ackNoticesForSeen(acc.email, folder)?.acked ?? 0
780
+ : 0;
781
+ local = `;本地归档同步 ${r.changed} 封${acked ? `,清掉 ${acked} 条未看留痕` : ""}`;
782
+ } catch { /* 归档不可用不影响服务器动作 */ }
783
+ return {
784
+ text: `已把 ${acc.email}/${folder} 的 ${marked} 封未读标为已读${local}。重复调用结果相同。`,
785
+ action, marked, folder,
786
+ };
787
+ });
788
+ }
789
+
790
+ const uid = Number(args.uid);
791
+ if (!Number.isFinite(uid)) return { text: "需要 uid 参数(action=set 时必填)" };
792
+ const seen = args.seen !== false;
793
+ return deps.withClient(args.account, args.folder, async (client, acc) => {
794
+ const folder = args.folder || acc.defaultFolder;
795
+ await client.setSeen(uid, seen);
796
+ // 本地归档跟着改,否则 stats/检索里还会显示"未读"
797
+ let local = "本地归档没有这封(仅改了服务器)";
798
+ try {
799
+ const store = await deps.ensureStore();
800
+ const ref = { account: acc.email, folder, uid };
801
+ if (store.getMessage(ref)) {
802
+ store.upsertMessage({ ...ref, seen });
803
+ const after = store.getMessage(ref);
804
+ local = `本地归档已同步为 ${after.seen === 1 ? "已读" : "未读"}`;
805
+ }
806
+ } catch { /* 归档不可用不影响服务器动作 */ }
807
+ return {
808
+ text: `已在服务器把 uid=${uid} 标记为${seen ? "已读" : "未读"}(${acc.email}/${folder});${local}。重复调用结果相同。`,
809
+ uid, seen, folder,
810
+ };
811
+ });
812
+ },
813
+ });
814
+ }
815
+
816
+ export function buildMoveTool(deps) {
817
+ return defineTool({
818
+ name: "mailbox_move",
819
+ description: `把某封邮件移动到指定文件夹(服务器支持 MOVE 就用 MOVE,否则 COPY+\\Deleted+EXPUNGE)。${WRITE_HINT} 需要部署层 write.enabled=true 才存在。`,
820
+ parameters: {
821
+ uid: { type: "number", required: true, description: "邮件 uid" },
822
+ to: { type: "string", required: true, description: "目标文件夹(IMAP 名称,如 存档)" },
823
+ account: { type: "string", description: "账户(可选,默认唯一账户)" },
824
+ folder: { type: "string", description: "源文件夹(默认 INBOX)" },
825
+ },
826
+ output: {
827
+ schema: {
828
+ type: "object", additionalProperties: false, required: ["text"],
829
+ properties: { text: { type: "string" }, uid: { type: "number" }, to: { type: "string" }, how: { type: "string" } },
830
+ },
831
+ render: (_a, v) => [{ type: "text", text: String(v?.text ?? "") }],
832
+ },
833
+ async execute(args = {}) {
834
+ const uid = Number(args.uid);
835
+ const to = s(args.to).trim();
836
+ if (!Number.isFinite(uid)) return { text: "需要 uid 参数" };
837
+ if (!to) return { text: "需要 to 参数(目标文件夹)" };
838
+ return deps.withClient(args.account, args.folder, async (client, acc) => {
839
+ const folder = args.folder || acc.defaultFolder;
840
+ if (to === folder) return { text: `源文件夹与目标相同(${to}),没有动作。`, uid, to, how: "noop" };
841
+ const how = await client.move(uid, to);
842
+ return {
843
+ text: `已把 uid=${uid} 从 ${acc.email}/${folder} 移到 ${to}(${how === "moved" ? "服务器 MOVE" : "COPY+EXPUNGE"})。\n本地归档仍留着原文件夹的旧记录(下次同步以服务器为准)。`,
844
+ uid, to, how,
845
+ };
846
+ });
847
+ },
848
+ });
849
+ }
850
+
851
+ export function buildWriteTools(deps) {
852
+ return [buildMarkTool(deps), buildMoveTool(deps)];
853
+ }
854
+
855
+ export function buildM4Tools(deps) {
856
+ return [
857
+ buildStatsTool(deps),
858
+ buildArchiveSearchTool(deps),
859
+ buildTagTool(deps),
860
+ buildFactsTool(deps),
861
+ buildDigestTool(deps),
862
+ ];
863
+ }