@linjz/opencode-qqbot 0.3.19 → 0.3.21

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.
@@ -4,7 +4,7 @@ import { dirname as dirname4, join as join6 } from "path";
4
4
  import { fileURLToPath as fileURLToPath2 } from "url";
5
5
 
6
6
  // src/core/bot-control.ts
7
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
7
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
8
8
  import { dirname as dirname3, join as join4 } from "path";
9
9
  import { homedir as homedir3 } from "os";
10
10
  import { fileURLToPath } from "url";
@@ -354,6 +354,33 @@ function readJson(path, fallback) {
354
354
  return fallback;
355
355
  }
356
356
  }
357
+ function defaultHoldPath() {
358
+ return join3(homedir2(), ".openqq", "supervisor-hold.json");
359
+ }
360
+ function readSupervisorHold(path = defaultHoldPath()) {
361
+ try {
362
+ const raw = JSON.parse(readFileSync3(path, "utf-8"));
363
+ if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
364
+ return raw;
365
+ }
366
+ } catch {}
367
+ return null;
368
+ }
369
+ function writeSupervisorHold(path, reason, by) {
370
+ try {
371
+ writeFileSync2(path, JSON.stringify({ version: 1, reason, by, at: Date.now() }));
372
+ } catch {}
373
+ }
374
+ function clearSupervisorHold(path) {
375
+ try {
376
+ if (!existsSync3(path))
377
+ return false;
378
+ unlinkSync2(path);
379
+ return true;
380
+ } catch {
381
+ return false;
382
+ }
383
+ }
357
384
  async function superviseOnce(deps) {
358
385
  const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
359
386
  const now = deps.now?.() ?? Date.now();
@@ -390,7 +417,25 @@ async function superviseOnce(deps) {
390
417
  try {
391
418
  const health = readBotHealth(deps.paths, now);
392
419
  const state = readJson(statePath, { restartLog: [] });
420
+ const holdPath = deps.holdPath ?? defaultHoldPath();
421
+ const hold = readSupervisorHold(holdPath);
422
+ if (hold && (!deps.request || deps.request === "health-check")) {
423
+ if (health.lockPid === null || health.pidAlive === false) {
424
+ log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`);
425
+ return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null };
426
+ }
427
+ if (clearSupervisorHold(holdPath)) {
428
+ log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`);
429
+ }
430
+ }
431
+ if (deps.request === "manual-restart" && hold) {
432
+ if (clearSupervisorHold(holdPath))
433
+ log(`[supervisor] manual-stop hold 已解除(openqq restart)`);
434
+ }
393
435
  let action = decideSupervise(health, state, now, policy);
436
+ if (deps.request === "manual-stop") {
437
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" } : { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" };
438
+ }
394
439
  if (deps.request === "manual-restart" && action.kind === "ok") {
395
440
  const windowStart = now - policy.windowMs;
396
441
  const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
@@ -434,7 +479,7 @@ async function superviseOnce(deps) {
434
479
  let killedPid = null;
435
480
  if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
436
481
  const pid = action.killPid;
437
- if (deps.request !== "manual-restart") {
482
+ if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
438
483
  await sleep(300);
439
484
  const recheck = readBotHealth(deps.paths, Date.now());
440
485
  const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
@@ -484,6 +529,31 @@ async function superviseOnce(deps) {
484
529
  if (cleared.length > 0)
485
530
  audit(`清锁:${cleared.join("、")}(${action.reason})`);
486
531
  } catch {}
532
+ if (deps.request === "manual-stop") {
533
+ writeSupervisorHold(holdPath, action.reason, "openqq stop");
534
+ const detail = killedPid ? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)` : `${action.reason};锁已清;hold 已立(巡检不拉起)`;
535
+ if (killedPid !== null) {
536
+ appendKillLog({
537
+ kind: "decision",
538
+ reason: action.reason,
539
+ health: {
540
+ lockPid: health.lockPid,
541
+ pidAlive: health.pidAlive,
542
+ heartbeatAgeMs: health.heartbeatAgeMs,
543
+ lockAgeMs: health.lockAgeMs
544
+ },
545
+ killedPid,
546
+ killEscalation: "TERM",
547
+ spawnedPid: null,
548
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
549
+ livenessVerdict: "stopped",
550
+ at: Date.now()
551
+ });
552
+ }
553
+ audit(`主动停:${detail}`);
554
+ log(`[supervisor] 主动停:${detail}`);
555
+ return { action: "stopped", detail, killedPid, spawnedPid: null };
556
+ }
487
557
  const spawnedPid = deps.spawn();
488
558
  state.restartLog.push(Date.now());
489
559
  state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
@@ -598,18 +668,30 @@ function readAppId(envPath = join4(homedir3(), ".openqq", ".env")) {
598
668
  }
599
669
  return null;
600
670
  }
601
- function inflightPath() {
602
- return join4(homedir3(), ".openqq", "inflight.json");
603
- }
604
- function countInflight(path = inflightPath()) {
671
+ function inflightPaths() {
672
+ const root = join4(homedir3(), ".openqq");
673
+ const paths = [join4(root, "inflight.json")];
605
674
  try {
606
- const raw = JSON.parse(readFileSync4(path, "utf-8"));
607
- if (!Array.isArray(raw))
608
- return 0;
609
- return raw.filter((e) => e.state === "inflight").length;
610
- } catch {
611
- return 0;
675
+ for (const name of readdirSync2(join4(root, "roles"))) {
676
+ const path = join4(root, "roles", name, "inflight.json");
677
+ if (existsSync4(path))
678
+ paths.push(path);
679
+ }
680
+ } catch {}
681
+ return paths;
682
+ }
683
+ function countInflight(paths = inflightPaths()) {
684
+ const list = Array.isArray(paths) ? paths : [paths];
685
+ let total = 0;
686
+ for (const path of list) {
687
+ try {
688
+ const raw = JSON.parse(readFileSync4(path, "utf-8"));
689
+ if (!Array.isArray(raw))
690
+ continue;
691
+ total += raw.filter((e) => e.state === "inflight").length;
692
+ } catch {}
612
693
  }
694
+ return total;
613
695
  }
614
696
  async function waitUntilIdle(opts) {
615
697
  const timeoutMs = opts?.timeoutMs ?? 60 * 60000;
@@ -672,6 +754,36 @@ async function restartBot(opts) {
672
754
  return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` };
673
755
  }
674
756
  }
757
+ async function stopBot(opts = {}) {
758
+ const log = opts.log ?? (() => {});
759
+ const appId = readAppId();
760
+ if (!appId)
761
+ throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁");
762
+ const idle = await waitUntilIdle({
763
+ timeoutMs: opts.timeoutMs,
764
+ onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲后停止`)
765
+ });
766
+ if (!idle) {
767
+ log("[bot-control] 等待空闲超时:本次不停止(请稍后重试,或先处理在途回合)");
768
+ return { action: "skipped", killedPid: null, reason: "等待空闲超时" };
769
+ }
770
+ const r = await superviseOnce({
771
+ paths: botWatchdogPaths(appId),
772
+ request: "manual-stop",
773
+ spawn: () => {
774
+ throw new Error("manual-stop 不应拉起 bot");
775
+ },
776
+ log
777
+ });
778
+ if (r.action === "stopped") {
779
+ return {
780
+ action: "stopped",
781
+ killedPid: r.killedPid,
782
+ reason: r.killedPid ? "已优雅停止并持有(巡检不拉起,restart 解除)" : "bot 未运行,已清锁并持有(巡检不拉起)"
783
+ };
784
+ }
785
+ return { action: "skipped", killedPid: null, reason: r.detail };
786
+ }
675
787
 
676
788
  // src/cli/service-main.ts
677
789
  import { spawnSync as spawnSync2 } from "child_process";
@@ -948,6 +1060,16 @@ async function main() {
948
1060
  process.exitCode = res.action === "restarted" ? 0 : 2;
949
1061
  return;
950
1062
  }
1063
+ if (cmd === "stop") {
1064
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
1065
+ const res = await stopBot({
1066
+ timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined,
1067
+ log: (line) => console.log(line)
1068
+ });
1069
+ console.log(`[stop] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"}`);
1070
+ process.exitCode = res.action === "stopped" ? 0 : 2;
1071
+ return;
1072
+ }
951
1073
  if (cmd === "service") {
952
1074
  const spec = {
953
1075
  runtimeCmd: runtimeCommand(),
@@ -956,8 +1078,22 @@ async function main() {
956
1078
  };
957
1079
  if (sub === "install")
958
1080
  return printResult("service install", serviceInstall(spec));
959
- if (sub === "uninstall")
960
- return printResult("service uninstall", serviceUninstall());
1081
+ if (sub === "uninstall") {
1082
+ const uninstall = serviceUninstall();
1083
+ printResult("service uninstall", uninstall);
1084
+ if (!process.argv.includes("--stop-bot"))
1085
+ return;
1086
+ const stop = await stopBot({
1087
+ timeoutMs: (() => {
1088
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
1089
+ return Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined;
1090
+ })(),
1091
+ log: (line) => console.log(line)
1092
+ });
1093
+ console.log(`[stop] ${stop.action}(${stop.reason})killed=${stop.killedPid ?? "-"}`);
1094
+ process.exitCode = stop.action === "stopped" ? uninstall.ok ? 0 : 1 : 2;
1095
+ return;
1096
+ }
961
1097
  if (sub === "status") {
962
1098
  const r = serviceStatus();
963
1099
  return printResult("service status", {
@@ -967,11 +1103,11 @@ script=${spec.scriptPath}
967
1103
  ${r.detail}`
968
1104
  });
969
1105
  }
970
- console.error("用法:openqq service install|uninstall|status");
1106
+ console.error("用法:openqq service install|uninstall [--stop-bot]|status");
971
1107
  process.exitCode = 2;
972
1108
  return;
973
1109
  }
974
- console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status");
1110
+ console.error("用法:openqq-cli restart [--force] [--timeout-min N] | stop [--timeout-min N] | service install|uninstall [--stop-bot]|status");
975
1111
  process.exitCode = 2;
976
1112
  }
977
1113
  main().catch((error) => {
@@ -199,6 +199,33 @@ function readJson(path, fallback) {
199
199
  return fallback;
200
200
  }
201
201
  }
202
+ function defaultHoldPath() {
203
+ return join2(homedir(), ".openqq", "supervisor-hold.json");
204
+ }
205
+ function readSupervisorHold(path = defaultHoldPath()) {
206
+ try {
207
+ const raw = JSON.parse(readFileSync2(path, "utf-8"));
208
+ if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
209
+ return raw;
210
+ }
211
+ } catch {}
212
+ return null;
213
+ }
214
+ function writeSupervisorHold(path, reason, by) {
215
+ try {
216
+ writeFileSync2(path, JSON.stringify({ version: 1, reason, by, at: Date.now() }));
217
+ } catch {}
218
+ }
219
+ function clearSupervisorHold(path) {
220
+ try {
221
+ if (!existsSync2(path))
222
+ return false;
223
+ unlinkSync2(path);
224
+ return true;
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
202
229
  async function superviseOnce(deps) {
203
230
  const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
204
231
  const now = deps.now?.() ?? Date.now();
@@ -235,7 +262,25 @@ async function superviseOnce(deps) {
235
262
  try {
236
263
  const health = readBotHealth(deps.paths, now);
237
264
  const state = readJson(statePath, { restartLog: [] });
265
+ const holdPath = deps.holdPath ?? defaultHoldPath();
266
+ const hold = readSupervisorHold(holdPath);
267
+ if (hold && (!deps.request || deps.request === "health-check")) {
268
+ if (health.lockPid === null || health.pidAlive === false) {
269
+ log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`);
270
+ return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null };
271
+ }
272
+ if (clearSupervisorHold(holdPath)) {
273
+ log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`);
274
+ }
275
+ }
276
+ if (deps.request === "manual-restart" && hold) {
277
+ if (clearSupervisorHold(holdPath))
278
+ log(`[supervisor] manual-stop hold 已解除(openqq restart)`);
279
+ }
238
280
  let action = decideSupervise(health, state, now, policy);
281
+ if (deps.request === "manual-stop") {
282
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" } : { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" };
283
+ }
239
284
  if (deps.request === "manual-restart" && action.kind === "ok") {
240
285
  const windowStart = now - policy.windowMs;
241
286
  const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
@@ -279,7 +324,7 @@ async function superviseOnce(deps) {
279
324
  let killedPid = null;
280
325
  if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
281
326
  const pid = action.killPid;
282
- if (deps.request !== "manual-restart") {
327
+ if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
283
328
  await sleep(300);
284
329
  const recheck = readBotHealth(deps.paths, Date.now());
285
330
  const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
@@ -329,6 +374,31 @@ async function superviseOnce(deps) {
329
374
  if (cleared.length > 0)
330
375
  audit(`清锁:${cleared.join("、")}(${action.reason})`);
331
376
  } catch {}
377
+ if (deps.request === "manual-stop") {
378
+ writeSupervisorHold(holdPath, action.reason, "openqq stop");
379
+ const detail = killedPid ? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)` : `${action.reason};锁已清;hold 已立(巡检不拉起)`;
380
+ if (killedPid !== null) {
381
+ appendKillLog({
382
+ kind: "decision",
383
+ reason: action.reason,
384
+ health: {
385
+ lockPid: health.lockPid,
386
+ pidAlive: health.pidAlive,
387
+ heartbeatAgeMs: health.heartbeatAgeMs,
388
+ lockAgeMs: health.lockAgeMs
389
+ },
390
+ killedPid,
391
+ killEscalation: "TERM",
392
+ spawnedPid: null,
393
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
394
+ livenessVerdict: "stopped",
395
+ at: Date.now()
396
+ });
397
+ }
398
+ audit(`主动停:${detail}`);
399
+ log(`[supervisor] 主动停:${detail}`);
400
+ return { action: "stopped", detail, killedPid, spawnedPid: null };
401
+ }
332
402
  const spawnedPid = deps.spawn();
333
403
  state.restartLog.push(Date.now());
334
404
  state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
@@ -399,7 +469,7 @@ async function superviseOnce(deps) {
399
469
  }
400
470
 
401
471
  // src/core/bot-control.ts
402
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
472
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
403
473
  import { dirname as dirname3, join as join4 } from "path";
404
474
  import { homedir as homedir3 } from "os";
405
475
  import { fileURLToPath } from "url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
- {
1
+ {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.19",
3
+ "version": "0.3.21",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -31,7 +31,9 @@
31
31
  "bin",
32
32
  "src",
33
33
  "dist",
34
- "tsconfig.json"
34
+ "tsconfig.json",
35
+ "THIRD_PARTY_NOTICES.md",
36
+ "PRIVACY.md"
35
37
  ],
36
38
  "keywords": [
37
39
  "opencode-plugin",
package/src/bridge.ts CHANGED
@@ -9,7 +9,7 @@ import { homedir } from "os"
9
9
  import type { Config } from "./config.js"
10
10
  import type { MessageContext } from "./qq/types.js"
11
11
  import { getAccessToken, sendC2CInputNotify, sendC2CMessage, sendGroupMessage } from "./qq/api.js"
12
- import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages } from "./qq/media.js"
12
+ import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages, purgeOldQQFiles } from "./qq/media.js"
13
13
  import { normalizeForCommandGate } from "./qq/gateway.js"
14
14
  import type { OpencodeClient, SessionMessage, PermissionRequest } from "./opencode/client.js"
15
15
  import {
@@ -38,6 +38,11 @@ import {
38
38
  type WatchApi,
39
39
  } from "./commands.js"
40
40
  import { createMirror } from "./core/mirror.js"
41
+ import {
42
+ createMirrorAnchorStore,
43
+ type MirrorAnchorEntry,
44
+ } from "./core/mirror-anchors.js"
45
+ import { clipDigestTitle, digestSessionLabel } from "./opencode/mirror.js"
41
46
  import { MessageQueue, laneKeyOf, laneScope, sessionIdOfLane, userIdOfLane, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
42
47
  import { classifyProviderError, rescueText } from "./core/error-rescue.js"
43
48
  import { NOTICE } from "./core/notices.js"
@@ -63,7 +68,7 @@ import {
63
68
  type PermOrigin,
64
69
  } from "./core/permission.js"
65
70
  import { truncate } from "./core/util.js"
66
- import { createDelivery, qqPromptHints } from "./core/delivery.js"
71
+ import { createDelivery, qqPromptHints, UNDELIVERED_NOTICE } from "./core/delivery.js"
67
72
  import { createNotifySink } from "./core/notify-sink.js"
68
73
  import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
69
74
  import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
@@ -103,6 +108,49 @@ export function isSessionBusyError(error: unknown): boolean {
103
108
  return /active prompt|[-−]32603/.test(message)
104
109
  }
105
110
 
111
+ export function isMirrorDigestText(text: string | null | undefined): boolean {
112
+ let value = text?.trim() ?? ""
113
+ if (value.startsWith(UNDELIVERED_NOTICE.trim())) {
114
+ value = value.slice(UNDELIVERED_NOTICE.trim().length).trimStart()
115
+ }
116
+ return value.startsWith("📋 桌面问答摘要") ||
117
+ value.startsWith("🎯 目标续跑摘要") ||
118
+ value.startsWith("📋 摘要续") ||
119
+ value.startsWith("🎯 摘要续")
120
+ }
121
+
122
+ export function commandNeedsMirrorAnchorGate(content: string): boolean {
123
+ const match = content.trim().match(/^\/(queue|amend|goal|btw)\b([\s\S]*)$/i)
124
+ if (!match) return false
125
+ const args = (match[2] ?? "").trim()
126
+ if (!args) return false
127
+ if (match[1]?.toLowerCase() === "queue" && /^(?:all(?:\s+\d+)?|clear|drop\s+\d+|\d+)$/i.test(args)) {
128
+ return false
129
+ }
130
+ return true
131
+ }
132
+
133
+ export type MirrorAnchorGateDecision =
134
+ | { kind: "pass" }
135
+ | { kind: "match"; anchor: MirrorAnchorEntry }
136
+ | { kind: "conflict"; anchor: MirrorAnchorEntry }
137
+ | { kind: "unknown" }
138
+
139
+ /** 纯路由判定:只有本人有效摘要锚点与入站绑定快照相同才允许沿摘要语境继续。 */
140
+ export function decideMirrorAnchorGate(input: {
141
+ anchor?: MirrorAnchorEntry
142
+ quoteText?: string | null
143
+ currentSessionId: string | null
144
+ }): MirrorAnchorGateDecision {
145
+ if (input.anchor) {
146
+ return input.currentSessionId && input.anchor.sessionId === input.currentSessionId
147
+ ? { kind: "match", anchor: input.anchor }
148
+ : { kind: "conflict", anchor: input.anchor }
149
+ }
150
+ if (isMirrorDigestText(input.quoteText)) return { kind: "unknown" }
151
+ return { kind: "pass" }
152
+ }
153
+
106
154
  // E 闲置回收纯函数(导出供测试,2026-10-29):返回应回收的闲置会话 id——
107
155
  // 超过 idleMs 无活动且未被观察(/status watch on)显式盯住的会话。
108
156
  export function evictableIdleSessions(
@@ -418,6 +466,7 @@ export function createBridge(
418
466
  const roleFile = (name: string): string => storageFile(name, storageAppId)
419
467
  // 在途台账按角色绑定实例(同进程多角色并发不互踩,见 inflight-journal 工厂)
420
468
  const inflight = createInflightJournal(storageAppId ? roleFile("inflight.json") : undefined)
469
+ const mirrorAnchors = createMirrorAnchorStore(roleFile("mirror-anchors.json"))
421
470
  // H2 停滞提醒文案状态开关就用现成 env 读取风格;这里同步实现⑦开关——
422
471
  // 2026-11-03 用户拍板:「已收到」回执默认不发(非调试无价值),调试期在
423
472
  // ~/.openqq/.env 设 QQ_ACK_RECEIPT=1 开启。loadEnvFile 全量注入 process.env,
@@ -471,7 +520,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
471
520
  // Q2:会话工具统计(/progress 手动查询用,本地事件源,零模型成本)
472
521
  const turnStats = new Map<string, { tools: number; failed: number; lastTool: string; lastAt: number }>()
473
522
 
474
- // E(2026-10-29 同步升级,吸收 dsh session/idle-evictor):闲置会话回收——
523
+ // E(2026-10-29 同步升级,参考 dsh session/idle-evictor):闲置会话回收——
475
524
  // 长期无活动的会话退订 SSE,降 opencode 服务端事件扇出;/watch 显式盯着的
476
525
  // 会话豁免;用户再来消息时 subscribeSession 会重新挂上。env QQ_SESSION_IDLE_HOURS。
477
526
  const sessionLastActivity = new Map<string, number>()
@@ -906,7 +955,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
906
955
  }
907
956
 
908
957
  // O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
909
- const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(
958
+ const { enqueuePush, safeDeliver, sendReply, deliver, consumePartialFailure } = createDelivery(
910
959
  config,
911
960
  lastCtx,
912
961
  isBoundSession,
@@ -929,6 +978,55 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
929
978
  }
930
979
  }
931
980
 
981
+ const mirrorQuoteCache = new WeakMap<MessageContext, { embedded: string | null; quoted: string | null }>()
982
+ function quoteContextOf(ctx: MessageContext): { embedded: string | null; quoted: string | null } {
983
+ const cached = mirrorQuoteCache.get(ctx)
984
+ if (cached) return cached
985
+ const embedded = extractEmbeddedQuote(ctx.rawEvent)
986
+ const quoted = embedded ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null)
987
+ const result = { embedded, quoted }
988
+ mirrorQuoteCache.set(ctx, result)
989
+ return result
990
+ }
991
+
992
+ function mirrorAnchorDecision(ctx: MessageContext, currentSessionId: string | null): MirrorAnchorGateDecision {
993
+ const { quoted } = quoteContextOf(ctx)
994
+ const anchor = mirrorAnchors.resolve(ctx.userId, ctx.referencedMsgId)
995
+ return decideMirrorAnchorGate({ anchor, quoteText: quoted, currentSessionId })
996
+ }
997
+
998
+ function anchorRejectText(
999
+ decision: Extract<MirrorAnchorGateDecision, { kind: "conflict" | "unknown" }>,
1000
+ currentSessionId: string | null,
1001
+ userId: string,
1002
+ ): string {
1003
+ if (decision.kind === "unknown") {
1004
+ return "⚠️ 无法确认这条旧摘要所属会话,本次未发送。请去掉引用后重发,或先通过 /sessions 切换到摘要所属会话。"
1005
+ }
1006
+ const source = `${clipDigestTitle(redactSecrets(decision.anchor.title))}(${digestSessionLabel(decision.anchor.sessionId)})`
1007
+ const current = sessions.getSession(userId)
1008
+ const currentLabel = currentSessionId
1009
+ ? `${clipDigestTitle(redactSecrets(current?.title ?? ""))}(${digestSessionLabel(currentSessionId)})`
1010
+ : "无绑定会话"
1011
+ return `⚠️ 这条回复引用的是 ${source} 的摘要,当前绑定为 ${currentLabel}。\n为避免误操作,本次未发送。请用 /sessions 切回该会话后重发;或去掉引用,明确发送到当前会话。`
1012
+ }
1013
+
1014
+ async function rejectMirrorAnchor(
1015
+ ctx: MessageContext,
1016
+ decision: Extract<MirrorAnchorGateDecision, { kind: "conflict" | "unknown" }>,
1017
+ currentSessionId: string | null,
1018
+ ): Promise<void> {
1019
+ const anchor = decision.kind === "conflict" ? decision.anchor.sessionId : "unknown"
1020
+ console.log(
1021
+ `[anchor-gate] result=${decision.kind} user=${ctx.userId.slice(0, 8)}… anchor=${anchor === "unknown" ? anchor : digestSessionLabel(anchor)} current=${currentSessionId ? digestSessionLabel(currentSessionId) : "∅"}`,
1022
+ )
1023
+ // 拒绝回执属于控制面:不得携带旧摘要锚,否则会被 notifyUser 的 push gate 自己拦掉。
1024
+ await notifyUser(
1025
+ { ...ctx, anchorSessionId: undefined },
1026
+ anchorRejectText(decision, currentSessionId, ctx.userId),
1027
+ )
1028
+ }
1029
+
932
1030
  // O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
933
1031
  // ★ 结合部契约(2026-11-17 固化):onPermission(回合内即时推送,SSE permission.asked)
934
1032
  // 与常驻交互监听(桌面端源审批 pushExternal)是同一挂起槽的两个入口——裁决/TTL/
@@ -997,9 +1095,17 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
997
1095
  // 会话隔离:审批裁决放行该用户全部有货 lane(drainQueue 自身对忙 lane 空转安全)
998
1096
  for (const lk of msgQueue.laneKeysOf(userId)) void drainQueue(userId, sessionIdOfLane(lk))
999
1097
  },
1000
- // A 项:审批卡片发送(失败自动降级文字菜单,permission 域内处理);origin 穿透到卡片正文
1001
- sendApprovalPrompt: (ctx, request, mainSessionId, origin) =>
1002
- sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId, origin),
1098
+ // A 项:审批卡片发送(失败自动降级文字菜单,permission 域内处理);origin 穿透到卡片正文;
1099
+ // isCancelled 穿透到发送层——token 后/QQ API 前再查,死卡不发。
1100
+ sendApprovalPrompt: (ctx, request, mainSessionId, origin, isCancelled) =>
1101
+ sendApprovalCard(
1102
+ { appId: config.qq.appId, clientSecret: config.qq.clientSecret },
1103
+ ctx,
1104
+ request,
1105
+ mainSessionId,
1106
+ origin,
1107
+ isCancelled,
1108
+ ),
1003
1109
  // 多角色:审批态按角色分文件(缺省 legacy 全局)
1004
1110
  persistFile: storageAppId ? roleFile("pending-permissions.json") : undefined,
1005
1111
  })
@@ -1015,6 +1121,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1015
1121
  busyUsers,
1016
1122
  // 多角色:镜像开关按角色分文件(缺省 legacy 全局)
1017
1123
  settingsFile: storageAppId ? roleFile("settings.json") : undefined,
1124
+ anchorStore: mirrorAnchors,
1018
1125
  // A 方案(owner 2026-11-23):桌面端回合的摘要同样过 cron 钩——注册提醒+剥净标记
1019
1126
  onDigest: (userId, digest) => {
1020
1127
  const hit = parseCronReminder(digest, Date.now())
@@ -1160,7 +1267,14 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1160
1267
  console.log(`[push-gate] 审批卡拦截(轮询兜底):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)}`)
1161
1268
  continue
1162
1269
  }
1163
- perm.pushExternal(uid, ctxForUser(uid), req, req.sessionID)
1270
+ // 统一发卡时序(2026-11-28 架构收口):轮询兜底发现与 SSE asked 走同一延迟闸——
1271
+ // defer 窗内被桌面自动审批处置的请求不推卡(此前轮询直推绕过延迟闸,109ms 推卡实证,
1272
+ // 1000-1500ms 延迟带的决议会漏成死卡);闸按 uid+requestID 去重,与 SSE 路径互不重复;
1273
+ // flushPermPush 内仍做悬置复查+回合归属标注,SSE 断线时本路径仍是兜底(REST 复查 fail-open)。
1274
+ console.log(
1275
+ `[perm-event] 轮询兜底发现待审(延迟 ${PERM_DEFER_MS}ms 判定)user=${uid.slice(0, 8)}… request=${req.id}`,
1276
+ )
1277
+ permPushGate.schedule(uid, req.id, () => void flushPermPush(uid, req))
1164
1278
  }
1165
1279
  }
1166
1280
  }
@@ -1236,6 +1350,10 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1236
1350
  // DEF-qqbot-20261112-1:反查必须带会话自身目录——引擎待审按 location 实例分仓,
1237
1351
  // 裸查只命中服务端 cwd 实例,项目会话的请求永远查空 → 恒弃推(ZERO2 实证挂起 5h24m 被误弃)。
1238
1352
  async function flushPermPush(uid: string, req: PermissionRequest): Promise<void> {
1353
+ if (perm.wasResolvedRecently(req.id)) {
1354
+ console.log(`[perm-event] 延迟判定:请求近期已解决,弃推 user=${uid.slice(0, 8)}… request=${req.id}`)
1355
+ return
1356
+ }
1239
1357
  const bound = sessions.getSession(uid)
1240
1358
  try {
1241
1359
  const res = await client.permission.list({ directory: bound?.directory })
@@ -1842,8 +1960,9 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1842
1960
 
1843
1961
  // 摘要镜像:启动时对全部映射会话挂常驻订阅
1844
1962
  mirror.ensureSubs()
1845
- // 图片落盘:清理 7 天前的 QQ 图片(原生附件接入)
1963
+ // 附件落盘:清理 7 天前的 QQ 图片与文件附件(原生附件接入)
1846
1964
  purgeOldQQImages()
1965
+ purgeOldQQFiles()
1847
1966
 
1848
1967
  const handleMessage = async (ctx: MessageContext): Promise<void> => {
1849
1968
  let claimedMsgId = ""
@@ -1862,6 +1981,12 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1862
1981
  inflight.settle(ctx.msgId, undefined, reason)
1863
1982
  console.log(`[queue] release-early msg=${shortId(ctx.msgId)} reason=${reason}${note ? ` note=${note}` : ""}`)
1864
1983
  }
1984
+ const releaseAnchorClaim = (note: "anchor-conflict" | "anchor-unknown"): void => {
1985
+ if (ctx.msgId && claimedContexts.has(ctx)) {
1986
+ inflight.markStage(ctx.msgId, "claimed", { lastError: note }, { force: true })
1987
+ }
1988
+ releaseClaimed("blocked", note)
1989
+ }
1865
1990
  try {
1866
1991
  // P1 修复(2026-11-03,外部复盘核验):拒绝时记录 openid——新用户无任何
1867
1992
  // 途径获取自己的 openid 填 ALLOWED_USERS,首配死锁;白名单内不打印(无需)。
@@ -1916,6 +2041,14 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1916
2041
  const gateContent = normalizeForCommandGate(content)
1917
2042
  if (isCommand(gateContent)) {
1918
2043
  const gateCtx = gateContent === content ? ctx : { ...ctx, content: gateContent }
2044
+ if (commandNeedsMirrorAnchorGate(gateContent)) {
2045
+ const decision = mirrorAnchorDecision(gateCtx, anchorSid)
2046
+ if (decision.kind === "conflict" || decision.kind === "unknown") {
2047
+ releaseAnchorClaim(decision.kind === "conflict" ? "anchor-conflict" : "anchor-unknown")
2048
+ await rejectMirrorAnchor(ctx, decision, anchorSid)
2049
+ return
2050
+ }
2051
+ }
1919
2052
  const reply = await handleCommand(gateCtx, commandContext)
1920
2053
  await notifyUser(ctx, reply)
1921
2054
  releaseClaimed("dropped")
@@ -1974,6 +2107,13 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1974
2107
  claimedMsgId = ctx.msgId
1975
2108
  }
1976
2109
 
2110
+ const mirrorGate = mirrorAnchorDecision(ctx, anchorSid)
2111
+ if (mirrorGate.kind === "conflict" || mirrorGate.kind === "unknown") {
2112
+ releaseAnchorClaim(mirrorGate.kind === "conflict" ? "anchor-conflict" : "anchor-unknown")
2113
+ await rejectMirrorAnchor(ctx, mirrorGate, anchorSid)
2114
+ return
2115
+ }
2116
+
1977
2117
  if (busyUsers.has(lane) && !claimedContexts.has(ctx)) {
1978
2118
  const duplicateIntent = activeIntents.get(lane) === intentKey || msgQueue.hasIntent(lane, intentKey)
1979
2119
  if (duplicateIntent) {
@@ -2081,12 +2221,11 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
2081
2221
  anchorDirectory
2082
2222
  }
2083
2223
 
2084
- // 缺口 1(引用上下文,吸收自官方 quote-ref 中间件):本条消息的引用解析
2224
+ // 缺口 1(引用上下文,参考官方 quote-ref 中间件的解析思路):本条消息的引用解析
2085
2225
  // 先于本条登记(顺序不可反:本条入缓存后才能被后续消息引用)
2086
2226
  // N 项(2026-10-30):双通道——QQ 事件内嵌被引内容(message_type=103)
2087
2227
  // 为权威来源优先;缺失才回落本地缓存(跨重启/老消息引用也能解析)。
2088
- const embeddedQuote = extractEmbeddedQuote(ctx.rawEvent)
2089
- const quoted = embeddedQuote ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null)
2228
+ const { quoted } = quoteContextOf(ctx)
2090
2229
  if (quoted) ctx.quoteText = quoted
2091
2230
  recordMessage(scopeKeyOf(ctx), ctx.msgId, ctx.content)
2092
2231
  // 新回合取代旧的后台等待(steer 合并运行时只投递一次合并结果)
@@ -2189,7 +2328,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
2189
2328
  // 超长回合可能已超被动窗口:deliver 被动失败自动降级主动,答案不丢
2190
2329
  // 直答出口统一脱敏(DEF-qqbot-20261106-2):与 history/mirror/form 同一脱敏器,
2191
2330
  // 防 AI 复述的密钥/令牌经直答气泡明文外泄。
2192
- // Y-1 cron 提醒(2026-11-23 学习吸收 openclaw):正文内嵌 QQBOT_PAYLOAD 标记
2331
+ // Y-1 cron 提醒(2026-11-23 学习参考 openclaw):正文内嵌 QQBOT_PAYLOAD 标记
2193
2332
  // → 注册一次性提醒并剥离标记;剥净为空则以确认句回执(不留脚手架痕迹)。
2194
2333
  let outboundText = extracted.text
2195
2334
  const cronHit = parseCronReminder(extracted.text, Date.now())
@@ -2209,6 +2348,10 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
2209
2348
  if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
2210
2349
  console.log(`[push-gate] 回合结果按历史可回读结清 answered msg=${shortId(trackId)}`)
2211
2350
  inflight.settle(trackId, undefined, "answered")
2351
+ } else if (consumePartialFailure(ctx)) {
2352
+ // 部分失败告警已由 delivery 发出;不得再冒称「24h 同文去重」。
2353
+ inflight.settle(trackId, undefined, "error")
2354
+ console.log(`[journal] 分片部分失败结清 error msg=${shortId(trackId)}`)
2212
2355
  } else {
2213
2356
  await safeDeliver(ctx, "⚠️ 本轮结果与 24h 内已发送内容重复,已被防重拦截(未重复投递)。如非预期请重发或换个说法")
2214
2357
  inflight.settle(trackId, undefined, "error")