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,83 @@
1
+ // lib/importance.js — 规则驱动的「重要性」评分(M3)。
2
+ //
3
+ // 为什么需要:用户要的是「**重要**信息 summary」。收件箱里营销/月报占比很高,
4
+ // 不加评分就会变成噪音。评分必须**确定性、可解释、可配置**(不用 LLM,零成本)。
5
+ //
6
+ // 输出 0–100 与 reasons[],调用方据阈值决定「立即推」还是「合并进日报」。
7
+
8
+ const CODE_WORDS = ["验证码", "一次性代码", "安全代码", "校验码", "驗證碼",
9
+ "security code", "one-time code", "one time code", "verification code", "otp", "passcode"];
10
+ const ACTION_WORDS = ["截止", "到期", "逾期", "发票", "付款", "付款通知", "请回复", "请确认", "签署", "签名",
11
+ "年结", "年結", "审计", "審計", "报税", "報稅", "续期", "續期", "期限",
12
+ // 商务往来(2026-10-16 补):实测一封标题「报价单」的邮件得 0 分才进日报 —— 词表覆盖不足。
13
+ "报价", "報價", "询价", "詢價", "议价", "訂單", "订单", "合同", "合约", "合約", "协议", "協議",
14
+ "对账", "對賬", "账单", "帳單", "应收", "應收", "应付", "應付", "采购", "採購", "供货", "供貨",
15
+ "发货", "發貨", "物流", "提单", "提單", "报关", "報關", "清关", "清關", "验收", "驗收",
16
+ "deadline", "due", "due date", "invoice", "payment", "remittance", "action required",
17
+ "quotation", "quote", "purchase order", "p/o", "contract", "statement of account",
18
+ "urgent", "asap", "please confirm", "please sign", "signature required", "renewal", "expires", "expiry"];
19
+ const PROMO_WORDS = ["unsubscribe", "退订", "取消订阅", "营销", "營銷", "优惠", "優惠", "折扣", "促销", "推廣", "推广",
20
+ "newsletter", "订阅", "電子報", "电子报", "% off", "limited time", "广告", "廣告", "webinar", "eDM"];
21
+
22
+ const has = (text, words) => words.some((w) => text.includes(w));
23
+
24
+ /** 规则匹配:tags.rules 里 {name, from?, subject?, tag?} → 命中的标签名(M4 的标签引擎也复用)。 */
25
+ export function matchRules(rules = [], msg = {}) {
26
+ const from = String(msg.from ?? "").toLowerCase();
27
+ const subject = String(msg.subject ?? "").toLowerCase();
28
+ const out = [];
29
+ for (const r of rules) {
30
+ if (!r) continue;
31
+ if (r.from && !from.includes(String(r.from).toLowerCase())) continue;
32
+ if (r.subject && !subject.includes(String(r.subject).toLowerCase())) continue;
33
+ const name = String(r.tag ?? r.name ?? "").trim();
34
+ if (name) out.push(name);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** 营销/批量邮件特征(这类永远不该"立即推")。 */
40
+ export function isPromotional(msg = {}) {
41
+ const hay = `${msg.subject ?? ""}\n${msg.snippet ?? ""}\n${msg.from ?? ""}`.toLowerCase();
42
+ return has(hay, PROMO_WORDS);
43
+ }
44
+
45
+ /**
46
+ * 评分。确定性规则,便于测试与解释。
47
+ * @returns { score: 0..100, reasons: string[], promo: boolean, tags: string[] }
48
+ */
49
+ export function scoreMessage(msg = {}, { rules = [], knownDomains = [] } = {}) {
50
+ const subject = String(msg.subject ?? "").toLowerCase();
51
+ const snippet = String(msg.snippet ?? "").toLowerCase();
52
+ const from = String(msg.from ?? "").toLowerCase();
53
+ const hay = `${subject}\n${snippet}`;
54
+ const reasons = [];
55
+ let score = 0;
56
+
57
+ // 验证码/安全代码单独就应越过阈值(默认 60):10 分钟有效的东西进日报毫无意义
58
+ const codeHit = has(hay, CODE_WORDS);
59
+ if (codeHit) { score += 70; reasons.push("含验证码/安全代码(时效性强)"); }
60
+ // 正文里已抽出验证码(store.otp):关键词可能只写在主题之外的地方,或根本没用词表里的说法
61
+ if (msg.otp && !codeHit) { score += 70; reasons.push(`已抽取验证码(${msg.otp})`); }
62
+ if (has(hay, ACTION_WORDS)) { score += 25; reasons.push("含行动词(截止/付款/签署…)"); }
63
+ if (msg.hasAttachment) { score += 10; reasons.push("带附件"); }
64
+
65
+ const tags = matchRules(rules, msg);
66
+ if (tags.length) { score += 20; reasons.push(`命中规则标签 ${tags.join("/")}`); }
67
+
68
+ if (knownDomains.length && knownDomains.some((d) => from.includes(String(d).toLowerCase()))) {
69
+ score += 15; reasons.push("来自已知域名");
70
+ }
71
+
72
+ const promo = isPromotional(msg);
73
+ if (promo) { score = Math.min(score, 20); reasons.push("疑似营销/批量邮件(压到 20 以下)"); }
74
+ // 抽到了验证码就是时效性邮件,营销压制也不能让它掉进日报(用户 2026-11-26 的明确诉求)
75
+ if (msg.otp && score < 80) { score = 80; reasons.push("含验证码 → 强制即时通知"); }
76
+
77
+ return { score: Math.max(0, Math.min(100, score)), reasons, promo, tags };
78
+ }
79
+
80
+ /** 批量评分,方便调用方一次算完。 */
81
+ export function scoreAll(items = [], opts = {}) {
82
+ return items.map((it) => ({ item: it, ...scoreMessage(it.row ?? it, opts) }));
83
+ }
package/lib/llm.js ADDED
@@ -0,0 +1,411 @@
1
+ // lib/llm.js — M7 语义能力:LLM 摘要 + 语义标签。
2
+ //
3
+ // 这个文件的重点**不是**"怎么调模型",而是 ROADMAP M7 的隐私护栏:
4
+ // 1. 默认关:两个能力都 off 时,连 `ctx.get("llm")` 都不会被碰(零外送)
5
+ // 2. 只送 subject / 发件人 / 正文前 N 字;**附件永不外送**
6
+ // 3. 可按账户、文件夹排除(企业内网邮件/私人文件夹不进模型)
7
+ // 4. 外送前按规则脱敏(验证码/卡号/手机号/身份证/API Key/JWT/口令)
8
+ // 5. 每次**真的外送**都写审计流水:哪封、送了哪些字段、多少字、几次脱敏、模型、成败、耗时
9
+ // 6. 任何失败都降级:单封失败不阻塞入库,拿不到模型就退回启发式
10
+ //
11
+ // 依赖注入:`service()` 返回 ctx.get("llm")(DSH 抽象的 llm 服务),
12
+ // `defaultSelection()` 返回 ctx.get("agentDefaultModel").currentSelection()。
13
+ // 两者都**延迟读取**,插件没加载 LLM 能力时不会崩。
14
+ //
15
+ // 调用形状(已按 DSH 0.2.0-rc.2 的类型核对):
16
+ // llm.stream({ provider, model, system?, maxTokens?, messages:[{role:"user",content:[{type:"text",text}]}] })
17
+ // → AsyncIterable<{type:"text-delta",text} | {type:"finish",reason} | …>
18
+
19
+ export const LLM_SYSTEM_SUMMARY =
20
+ "你是邮件助理。用**一句中文**概括这封邮件:谁发的、要做什么、期限是什么。"
21
+ + "只输出这句话本身,不要称呼、不要 markdown、不要复述『这是摘要』、不要编造邮件里没有的信息。"
22
+ + "如果邮件里没有任何需要我处理的事,就直接说『无待办』。";
23
+
24
+ export const LLM_SYSTEM_TAGS =
25
+ "你是邮件分类器。只从用户给定的候选标签里挑,不要发明新标签,不要解释理由。"
26
+ + "输出格式:逗号分隔的标签,不要编号、不要 markdown。没有合适的就输出『无』。";
27
+
28
+ /** 摘要正文上限(字符):再长就不像"摘要"了,也没必要多送。 */
29
+ export const SUMMARY_MAX = 200;
30
+
31
+ // ------------------------------------------------------------------ 脱敏
32
+ /** 规则按「越具体越先跑」排序:先拿走验证码/密钥,再处理裸露的长数字。 */
33
+ export const REDACT_RULES = [
34
+ // 「验证码是 123456」「验证码:123456」「code 1234」都要盖住 —— 关键词与数字之间
35
+ // 允许少量非数字字符(是/为/:/:/空格),但不能无限远(否则会把整段吞进来)。
36
+ { name: "验证码", re: /((?:验证码|校验码|动态码|一次性密码|verification code|one[- ]time code|code|pin)[^\d]{0,6}?)(\d{4,8})/gi, mask: (m, p1) => `${p1}${"*".repeat(m.length - p1.length)}` },
37
+ { name: "口令", re: /((?:password|passwd|pwd|密码|口令)\s*[::=]?\s*)(\S+)/gi, mask: (m, p1) => `${p1}***` },
38
+ { name: "密钥", re: /\b(?:sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g, mask: () => "***KEY***" },
39
+ { name: "JWT", re: /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}\b/g, mask: () => "***TOKEN***" },
40
+ { name: "身份证", re: /\b\d{17}[\dXx]\b/g, mask: (m) => `${m.slice(0, 4)}${"*".repeat(10)}${m.slice(-4)}` },
41
+ { name: "手机号", re: /(?<!\d)1[3-9]\d{9}(?!\d)/g, mask: (m) => `${m.slice(0, 3)}****${m.slice(-4)}` },
42
+ { name: "银行卡", re: /(?<!\d)(?:\d[ -]?){15,19}\d(?!\d)/g, mask: (m) => `****${m.replace(/\D/g, "").slice(-4)}` },
43
+ ];
44
+
45
+ /** 按规则抹掉敏感串。返回 { text, hits:[{name,count}], total }。 */
46
+ export function redactSecrets(input) {
47
+ let text = String(input ?? "");
48
+ const hits = [];
49
+ let total = 0;
50
+ for (const rule of REDACT_RULES) {
51
+ let n = 0;
52
+ text = text.replace(rule.re, (...args) => { n++; return rule.mask(...args); });
53
+ if (n) { hits.push({ name: rule.name, count: n }); total += n; }
54
+ }
55
+ return { text, hits, total };
56
+ }
57
+
58
+ /** 截断到 maxChars(按字符,不切半个代理对)。 */
59
+ export function excerpt(input, maxChars) {
60
+ const text = String(input ?? "");
61
+ const cap = Math.max(0, Number(maxChars) || 0);
62
+ if (!cap || text.length <= cap) return { text, truncated: false, chars: text.length };
63
+ let cut = text.slice(0, cap);
64
+ const last = cut.charCodeAt(cut.length - 1);
65
+ if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1); // 别把 emoji 劈两半
66
+ return { text: cut, truncated: true, chars: cut.length };
67
+ }
68
+
69
+ /** 组装要外送的内容。**这是唯一决定"什么会被送出去"的地方** —— 附件/原始 .eml 不在其中。 */
70
+ export function buildPayload(msg, { maxChars = 1200, redact = true } = {}) {
71
+ const subject = String(msg?.subject ?? "");
72
+ const from = String(msg?.from ?? msg?.from_addr ?? "");
73
+ const to = String(msg?.to ?? msg?.to_addr ?? "");
74
+ const bodyRaw = String(msg?.body ?? msg?.snippet ?? "");
75
+ const ex = excerpt(bodyRaw, maxChars);
76
+ const body = redact ? redactSecrets(ex.text) : { text: ex.text, hits: [], total: 0 };
77
+ // 字段清单写进审计:事后能回答"到底送了哪些字段",而不是只写"送了一封邮件"
78
+ const fields = ["subject", "from", "body"];
79
+ if (to) fields.push("to");
80
+ return {
81
+ subject: redact ? redactSecrets(subject).text : subject,
82
+ from,
83
+ to,
84
+ body: body.text,
85
+ fields,
86
+ chars: body.text.length + subject.length + from.length,
87
+ bodyChars: body.text.length,
88
+ truncated: ex.truncated,
89
+ redactions: body.total,
90
+ redactionNames: body.hits.map((x) => x.name),
91
+ attachments: [], // 恒空:附件永不外送(留字段是为了显式可见)
92
+ };
93
+ }
94
+
95
+ export function promptOfSummary(p, { redactions = 0 } = {}) {
96
+ const lines = [`发件人:${p.from || "(未知)"}`, `主题:${p.subject || "(无主题)"}`];
97
+ if (p.to) lines.push(`收件人:${p.to}`);
98
+ lines.push(`正文${p.truncated ? "(已截断)" : ""}${redactions ? `(已脱敏 ${redactions} 处)` : ""}:`);
99
+ lines.push(p.body || "(无正文)");
100
+ return lines.join("\n");
101
+ }
102
+
103
+ export function promptOfTags(p, candidates, maxTags) {
104
+ return [
105
+ `候选标签:${candidates.join("、")}`,
106
+ `最多选 ${maxTags} 个,必须来自候选。`,
107
+ "",
108
+ `发件人:${p.from || "(未知)"}`,
109
+ `主题:${p.subject || "(无主题)"}`,
110
+ `正文${p.truncated ? "(已截断)" : ""}:`,
111
+ p.body || "(无正文)",
112
+ ].join("\n");
113
+ }
114
+
115
+ // ------------------------------------------------------------------ 隐私闸门
116
+ /** 判定"这封能不能送出去"。返回 { allowed, reason } —— 拒绝也要有明确理由,便于解释给用户。 */
117
+ export function guardOf(ref, { guard = {}, allowAttachments = false } = {}) {
118
+ const account = String(ref?.account ?? "");
119
+ const folder = String(ref?.folder ?? "");
120
+ if (allowAttachments) return { allowed: false, reason: "llm.guard.allowAttachments 不受支持:附件永不外送" };
121
+ const exAcc = (guard.excludeAccounts ?? []).map(String);
122
+ const exFolder = (guard.excludeFolders ?? []).map(String);
123
+ if (exAcc.includes(account)) return { allowed: false, reason: `账户 ${account} 在排除名单里(llm.guard.excludeAccounts)` };
124
+ if (exFolder.includes(folder)) return { allowed: false, reason: `文件夹 ${folder} 在排除名单里(llm.guard.excludeFolders)` };
125
+ // 主题/发件人明显是机密或验证码的,直接不外送(比"脱敏后外送"更保守)
126
+ return { allowed: true, reason: null };
127
+ }
128
+
129
+ // ------------------------------------------------------------------ 模型调用
130
+ /** 从流式响应里拼出文本。DSH 的 chunk:`{type:'text-delta',text}` / `{type:'finish',reason}`。 */
131
+ export async function collectStream(chunks) {
132
+ let text = "";
133
+ let reason = null;
134
+ let usage = null;
135
+ for await (const c of chunks) {
136
+ if (c?.type === "text-delta") text += c.text ?? "";
137
+ else if (c?.type === "finish") reason = c.reason ?? "finish";
138
+ else if (c?.type === "usage") usage = c.usage ?? null;
139
+ }
140
+ return { text: text.trim(), reason, usage };
141
+ }
142
+
143
+ /**
144
+ * 调一次模型。**永不抛**:所有失败都变成 { ok:false, error } —— 语义能力绝不能拖垮归档。
145
+ * timeoutMs 到了就 abort,不让一封邮件把整条流水线挂住。
146
+ */
147
+ export async function callModel(service, {
148
+ provider, model, system, prompt, maxTokens = 400, timeoutMs = 20000, now = Date.now,
149
+ setTimer = setTimeout, clearTimer = clearTimeout,
150
+ } = {}) {
151
+ const t0 = now();
152
+ if (!service || typeof service.stream !== "function") {
153
+ return { ok: false, error: "llm 服务不可用(ctx.get('llm') 为空或没有 stream)", ms: 0, text: "" };
154
+ }
155
+ if (!provider || !model) return { ok: false, error: "缺少 provider/model", ms: 0, text: "" };
156
+ const controller = new AbortController();
157
+ let timedOut = false;
158
+ const timer = setTimer(() => { timedOut = true; try { controller.abort(); } catch { /* 已中止 */ } }, Math.max(1, timeoutMs));
159
+ try {
160
+ const messages = [{ role: "user", content: [{ type: "text", text: String(prompt ?? "") }] }];
161
+ const out = await collectStream(service.stream({
162
+ provider, model, messages, system, maxTokens, signal: controller.signal,
163
+ }));
164
+ const ms = now() - t0;
165
+ if (timedOut) return { ok: false, error: `模型调用超时(${timeoutMs}ms)`, ms, text: out.text };
166
+ if (!out.text) return { ok: false, error: `模型没有返回文本(finish=${out.reason ?? "?"})`, ms, text: "" };
167
+ return { ok: true, text: out.text, error: null, ms, reason: out.reason, usage: out.usage };
168
+ } catch (e) {
169
+ return { ok: false, error: timedOut ? `模型调用超时(${timeoutMs}ms)` : (e?.message ?? String(e)), ms: now() - t0, text: "" };
170
+ } finally {
171
+ clearTimer(timer);
172
+ }
173
+ }
174
+
175
+ // ------------------------------------------------------------------ 结果清洗
176
+ /** 洗掉模型的客套与包装:去掉"摘要:"前缀、引号、markdown、尾部追问。 */
177
+ export function sanitizeSummary(reply, max = SUMMARY_MAX) {
178
+ let t = String(reply ?? "").trim();
179
+ t = t.replace(/^```[a-z]*\n?/i, "").replace(/```\s*$/i, "").trim();
180
+ t = t.replace(/^(?:摘要|总结|概括|Summary)\s*[::]\s*/i, "");
181
+ t = t.replace(/^["'“”『「]+|["'“”』」]+$/g, "").trim();
182
+ t = t.replace(/\s*\n+\s*/g, " ");
183
+ t = t.replace(/(?:需要我|要不要我|希望(?:这|以上)?(?:对你有帮助|有帮助)|如需).*$/u, "").trim();
184
+ if (t.length > max) t = t.slice(0, max - 1) + "…";
185
+ return t;
186
+ }
187
+
188
+ /** 从模型回复里挑标签:只认候选表里出现过的,按出现顺序去重,最多 maxTags 个。 */
189
+ export function parseTags(reply, candidates = [], maxTags = 3) {
190
+ const text = String(reply ?? "");
191
+ const pool = candidates.map(String).filter(Boolean);
192
+ if (!pool.length) return [];
193
+ const found = [];
194
+ for (const tag of pool) {
195
+ const i = text.toLowerCase().indexOf(tag.toLowerCase());
196
+ if (i >= 0) found.push({ tag, i });
197
+ }
198
+ found.sort((a, b) => a.i - b.i);
199
+ const seen = new Set();
200
+ const out = [];
201
+ for (const f of found) {
202
+ if (seen.has(f.tag)) continue;
203
+ seen.add(f.tag);
204
+ out.push(f.tag);
205
+ if (out.length >= Math.max(1, maxTags)) break;
206
+ }
207
+ return out;
208
+ }
209
+
210
+ // ------------------------------------------------------------------ 工作器
211
+ const uniq = (arr) => [...new Set(arr)];
212
+
213
+ /**
214
+ * 语义工作器:排队、限流(串行)、审计、降级。
215
+ * · `enqueue(ref, msg)` **同步返回**,真正的调用在后台跑 —— 抓取循环一秒都不会被它拖住
216
+ * · 队列为空 → 什么也不做;两个能力都关 → 连 service() 都不读
217
+ */
218
+ export class LlmWorker {
219
+ constructor({ top, store, log = () => {}, now = Date.now, service = () => null,
220
+ defaultSelection = () => null, timeoutMs = 20000, maxQueue = 50 } = {}) {
221
+ this.topOf = top; // () => top
222
+ this.storeOf = store; // () => store | null
223
+ this.log = log;
224
+ this.now = now;
225
+ this.serviceOf = service;
226
+ this.selectionOf = defaultSelection;
227
+ this.timeoutMs = timeoutMs;
228
+ this.maxQueue = maxQueue;
229
+ this.queue = [];
230
+ this.pumping = null;
231
+ this.stopped = false;
232
+ this.stats = { queued: 0, done: 0, failed: 0, skipped: 0, dropped: 0 };
233
+ }
234
+
235
+ get top() { return this.topOf?.() ?? {}; }
236
+ get llmCfg() { return this.top.llm ?? {}; }
237
+ get store() {
238
+ const s = this.storeOf?.();
239
+ return s && typeof s.addLlmAudit === "function" ? s : null;
240
+ }
241
+
242
+ /** 能力是否打开(部署层配置决定,热改变不了已注册的工具,但这里读的是当前值)。 */
243
+ enabled(kind) {
244
+ const c = this.llmCfg;
245
+ if (kind === "semantic") return c.semantic?.enabled === true;
246
+ return c.digest?.enabled === true;
247
+ }
248
+
249
+ targetOf(kind) {
250
+ const c = this.llmCfg;
251
+ const node = kind === "semantic" ? (c.semantic ?? {}) : (c.digest ?? {});
252
+ const sel = (() => { try { return this.selectionOf?.() ?? null; } catch { return null; } })();
253
+ return {
254
+ provider: node.provider || sel?.provider || "",
255
+ model: node.model || sel?.model || "",
256
+ source: node.provider || node.model ? "config" : (sel ? "default-model" : "none"),
257
+ };
258
+ }
259
+
260
+ /** 隐私闸门。**能力关 = 一律拒绝**:默认关必须意味着"任何入口都送不出去",
261
+ * 而不是"只有 enqueue 那条路送不出去"。 */
262
+ guard(ref, kind) {
263
+ if (!this.enabled(kind)) {
264
+ const key = kind === "semantic" ? "llm.semantic.enabled" : "llm.digest.enabled";
265
+ return { allowed: false, reason: `LLM 能力未启用(${key}=false)` };
266
+ }
267
+ return guardOf(ref, { guard: this.llmCfg.guard ?? {} });
268
+ }
269
+
270
+ /** 审计:只记**真的发出去**的调用(以及它们的失败);被闸门拦下的不写,避免流水被噪音淹没。 */
271
+ audit(entry) {
272
+ try { this.store?.addLlmAudit(entry); } catch (e) { this.log("warn", `LLM 审计写入失败(不影响主流程):${e?.message ?? e}`); }
273
+ }
274
+
275
+ async summarize(ref, msg) {
276
+ const cfg = this.llmCfg.digest ?? {};
277
+ // 闸门必须在这里(而不是只在 runOne 里):summarize 也是对外方法,
278
+ // 少一层就等于给了绕开隐私检查的后门。
279
+ const gate = this.guard(ref, "digest");
280
+ if (!gate.allowed) return { ok: false, skipped: true, kind: "digest", reason: gate.reason, summary: null };
281
+ const p = buildPayload(msg, { maxChars: cfg.maxChars ?? 1200, redact: this.llmCfg.guard?.redact !== false });
282
+ const target = this.targetOf("digest");
283
+ if (!target.provider || !target.model) {
284
+ return { ok: false, kind: "digest", error: "没有可用的模型:配置 llm.digest.provider/model,或在 DSH 里选一个默认模型", payload: p };
285
+ }
286
+ const r = await callModel(this.serviceOf?.(), {
287
+ provider: target.provider, model: target.model, system: LLM_SYSTEM_SUMMARY,
288
+ prompt: promptOfSummary(p, { redactions: p.redactions }),
289
+ maxTokens: cfg.maxTokens ?? 400, timeoutMs: this.timeoutMs, now: this.now,
290
+ });
291
+ const summary = r.ok ? sanitizeSummary(r.text) : null;
292
+ if (r.ok && summary) { try { this.store?.setLlmSummary(ref, summary); } catch { /* 存不下就只留审计 */ } }
293
+ this.audit({
294
+ account: ref.account, folder: ref.folder, uid: ref.uid, kind: "digest",
295
+ provider: target.provider, model: target.model, chars: p.chars, fields: p.fields.join(","),
296
+ redactions: p.redactions, ok: r.ok && !!summary, error: r.error, ms: r.ms, at: this.now(),
297
+ });
298
+ return { ok: r.ok && !!summary, kind: "digest", summary, error: r.error, payload: p, model: `${target.provider}/${target.model}`, ms: r.ms };
299
+ }
300
+
301
+ async semanticTags(ref, msg) {
302
+ const gate = this.guard(ref, "semantic");
303
+ if (!gate.allowed) return { ok: false, skipped: true, kind: "semantic", reason: gate.reason, tags: [] };
304
+ const cfg = this.llmCfg.semantic ?? {};
305
+ const candidates = cfg.candidates ?? [];
306
+ if (!candidates.length) return { ok: false, kind: "semantic", error: "没有候选标签:配置 llm.semantic.candidates", tags: [] };
307
+ const p = buildPayload(msg, { maxChars: cfg.maxChars ?? 1200, redact: this.llmCfg.guard?.redact !== false });
308
+ const target = this.targetOf("semantic");
309
+ if (!target.provider || !target.model) return { ok: false, kind: "semantic", error: "没有可用的模型", tags: [] };
310
+ const r = await callModel(this.serviceOf?.(), {
311
+ provider: target.provider, model: target.model, system: LLM_SYSTEM_TAGS,
312
+ prompt: promptOfTags(p, candidates, cfg.maxTags ?? 3),
313
+ maxTokens: 60, timeoutMs: this.timeoutMs, now: this.now,
314
+ });
315
+ const tags = r.ok ? parseTags(r.text, candidates, cfg.maxTags ?? 3) : [];
316
+ if (tags.length) {
317
+ try {
318
+ const existing = this.store?.tagsOf?.(ref) ?? [];
319
+ this.store?.setTags?.(ref, uniq([...existing, ...tags]), "llm");
320
+ } catch (e) { this.log("warn", `语义标签写库失败:${e?.message ?? e}`); }
321
+ }
322
+ this.audit({
323
+ account: ref.account, folder: ref.folder, uid: ref.uid, kind: "semantic",
324
+ provider: target.provider, model: target.model, chars: p.chars, fields: p.fields.join(","),
325
+ redactions: p.redactions, ok: r.ok, error: r.error, ms: r.ms, at: this.now(),
326
+ });
327
+ return { ok: r.ok, kind: "semantic", tags, error: r.error, payload: p, model: `${target.provider}/${target.model}`, ms: r.ms };
328
+ }
329
+
330
+ /** 跑一封:先过闸门,再按能力跑。返回统一结构,便于 digest 工具汇总说明。 */
331
+ async runOne(ref, msg, { kinds = null } = {}) {
332
+ const want = kinds ?? ["digest", "semantic"].filter((k) => this.enabled(k));
333
+ const active = want.filter((k) => this.enabled(k));
334
+ if (!active.length) return { ok: false, skipped: true, reason: "LLM 能力未启用(llm.digest.enabled / llm.semantic.enabled)", results: [] };
335
+ const gate = this.guard(ref, active[0]);
336
+ if (!gate.allowed) return { ok: false, skipped: true, reason: gate.reason, results: [] };
337
+ const results = [];
338
+ for (const kind of active) {
339
+ results.push(kind === "semantic" ? await this.semanticTags(ref, msg) : await this.summarize(ref, msg));
340
+ }
341
+ return { ok: results.some((x) => x.ok), skipped: false, results, summary: results.find((x) => x.summary)?.summary ?? null, tags: results.find((x) => x.tags)?.tags ?? [] };
342
+ }
343
+
344
+ /** 入库钩子入口:**同步返回**。真正的工作在后台串行跑。 */
345
+ enqueue(ref, msg, opts = {}) {
346
+ if (this.stopped) return { queued: false, reason: "worker 已停止" };
347
+ if (!this.enabled("digest") && !this.enabled("semantic")) return { queued: false, reason: "LLM 能力未启用" };
348
+ if (this.queue.length >= this.maxQueue) {
349
+ this.stats.dropped++;
350
+ this.log("warn", `LLM 队列已满(${this.maxQueue}),丢弃 ${ref.account}/${ref.uid} 的语义任务`);
351
+ return { queued: false, reason: "队列已满" };
352
+ }
353
+ this.queue.push({ ref, msg, opts });
354
+ this.stats.queued++;
355
+ if (!this.pumping) {
356
+ this.pumping = this.pump().finally(() => { this.pumping = null; });
357
+ }
358
+ return { queued: true, depth: this.queue.length };
359
+ }
360
+
361
+ /** 串行消费队列。**串行**是有意的:一次只外送一封,便于限流与审计对账。 */
362
+ async pump() {
363
+ while (this.queue.length) {
364
+ const job = this.queue.shift();
365
+ try {
366
+ const r = await this.runOne(job.ref, job.msg, job.opts);
367
+ if (r.skipped) this.stats.skipped++;
368
+ else if (r.ok) this.stats.done++;
369
+ else this.stats.failed++;
370
+ } catch (e) {
371
+ this.stats.failed++;
372
+ this.log("warn", `LLM 任务异常(忽略):${e?.message ?? e}`);
373
+ }
374
+ }
375
+ }
376
+
377
+ /** 等队列跑空(测试与关停用)。 */
378
+ async drain() {
379
+ while (this.pumping) { const p = this.pumping; await p; }
380
+ return this.stats;
381
+ }
382
+
383
+ stop() { this.stopped = true; }
384
+
385
+ /** 给 mailbox_stats / mailbox_digest 用的一行说明:开启状态、模型、审计规模。 */
386
+ describe() {
387
+ const c = this.llmCfg;
388
+ const g = c.guard ?? {};
389
+ const parts = [];
390
+ parts.push(`摘要 ${c.digest?.enabled ? "开" : "关"}`);
391
+ parts.push(`语义标签 ${c.semantic?.enabled ? "开" : "关"}`);
392
+ if (c.enabled) {
393
+ const t = this.targetOf(c.semantic?.enabled && !c.digest?.enabled ? "semantic" : "digest");
394
+ parts.push(t.provider && t.model ? `模型 ${t.provider}/${t.model}` : "模型 未配置");
395
+ parts.push(`脱敏 ${g.redact === false ? "关" : "开"}`);
396
+ const ex = [...(g.excludeAccounts ?? []), ...(g.excludeFolders ?? [])];
397
+ if (ex.length) parts.push(`排除 ${ex.join("/")}`);
398
+ } else {
399
+ parts.push("未启用(零外送)");
400
+ }
401
+ const a = this.store?.llmAuditStats?.();
402
+ // 0 条也要报:只写"摘要 开"而不写"审计 0",用户无法区分"没外送过"与"审计坏了"
403
+ if (a) parts.push(`审计 ${a.ok} 成功/${a.failed} 失败`);
404
+ return parts.join(" · ");
405
+ }
406
+ }
407
+
408
+ /** 工厂:index.js 只调这一句。 */
409
+ export function makeLlmWorker(deps = {}) {
410
+ return new LlmWorker(deps);
411
+ }
package/lib/log.js ADDED
@@ -0,0 +1,75 @@
1
+ // lib/log.js — 插件自己的日志(零依赖)。
2
+ //
3
+ // 为什么需要:插件的 console 输出落在 host 进程的 stdout,桌面版默认**没有落盘**
4
+ // (AppData\Roaming\@deepseek-ai\dsh-desktop\logs 里只有崩溃日志)。没有日志文件,
5
+ // 出问题只能靠猜 —— M2 首次真机启动就吃了这个亏。
6
+ //
7
+ // 设计:双通道 —— ① 回显给宿主(console / cordis ctx.logger 由调用方接);
8
+ // ② 追加写 <dataDir>/mailbox.log,超过上限自动轮转成 mailbox.log.1。
9
+ // 写文件失败绝不影响主流程(标记 broken 后静默降级)。
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+
14
+ const LEVELS = new Set(["error", "warn", "info", "debug"]);
15
+ const DEFAULT_MAX_BYTES = 512 * 1024;
16
+
17
+ export function createLogger({ file = null, maxBytes = DEFAULT_MAX_BYTES, echo = null, now = () => new Date() } = {}) {
18
+ let broken = false;
19
+
20
+ // 用**本地时间**记日志:toISOString() 是 UTC,+08:00 的用户会看到差 8 小时的时间戳(实测被问过)
21
+ const stamp = () => {
22
+ const d = now();
23
+ const p = (n) => String(n).padStart(2, "0");
24
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
25
+ };
26
+ const line = (level, msg) => `${stamp()} ${String(level).toUpperCase().padEnd(5)} ${msg}\n`;
27
+
28
+ const rotateIfNeeded = () => {
29
+ if (!file || !maxBytes) return;
30
+ try {
31
+ if (fs.statSync(file).size < maxBytes) return;
32
+ const bak = file + ".1";
33
+ try { fs.rmSync(bak, { force: true }); } catch { /* 覆盖旧备份 */ }
34
+ fs.renameSync(file, bak);
35
+ } catch { /* 文件不存在等,直接继续 */ }
36
+ };
37
+
38
+ const write = (level, msg) => {
39
+ const lv = LEVELS.has(level) ? level : "info";
40
+ const text = line(lv, String(msg));
41
+ if (typeof echo === "function") { try { echo(lv, text.trimEnd()); } catch { /* 回显失败不影响 */ } }
42
+ if (file && !broken) {
43
+ try {
44
+ fs.mkdirSync(path.dirname(file), { recursive: true });
45
+ rotateIfNeeded();
46
+ fs.appendFileSync(file, text);
47
+ } catch { broken = true; } // 磁盘/权限问题:降级为只回显
48
+ }
49
+ };
50
+
51
+ return {
52
+ filePath: file,
53
+ get broken() { return broken; },
54
+ log: write,
55
+ error: (m) => write("error", m),
56
+ warn: (m) => write("warn", m),
57
+ info: (m) => write("info", m),
58
+ debug: (m) => write("debug", m),
59
+ };
60
+ }
61
+
62
+ /** 读日志尾部(供未来配置页/工具展示)。最多读 maxBytes 字节,避免整文件载入。 */
63
+ export function tailLog(file, { lines = 50, maxBytes = 128 * 1024 } = {}) {
64
+ try {
65
+ const st = fs.statSync(file);
66
+ const start = Math.max(0, st.size - maxBytes);
67
+ const fd = fs.openSync(file, "r");
68
+ const buf = Buffer.alloc(st.size - start);
69
+ fs.readSync(fd, buf, 0, buf.length, start);
70
+ fs.closeSync(fd);
71
+ return buf.toString("utf8").split("\n").slice(-lines).join("\n");
72
+ } catch {
73
+ return "";
74
+ }
75
+ }