@linjz/opencode-qqbot 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,23 +1,32 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
+ "exports": {
7
+ ".": "./src/plugin-entry.ts"
8
+ },
6
9
  "bin": {
7
- "openqq": "./bin/openqq.js"
10
+ "openqq": "./bin/openqq.js",
11
+ "openqq-setup": "./bin/openqq-setup.mjs"
8
12
  },
9
13
  "scripts": {
10
14
  "dev": "bun run --watch src/index.ts",
11
15
  "start": "bun run src/index.ts",
12
16
  "typecheck": "tsc --noEmit",
13
- "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts",
17
+ "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts",
14
18
  "test:e2e": "bun run test/watch-history-e2e.ts && bun run test/d1-subagent-ask-e2e.ts && bun run test/d2-conflict-e2e.ts && bun run test/perm-e2e.ts && bun run test/perm-real-e2e.ts",
15
19
  "verify": "bun run typecheck && bun run test",
16
- "verify:full": "bun run verify && bun run test:e2e"
20
+ "verify:full": "bun run verify && bun run test:e2e",
21
+ "build:bundle": "bun build src/index.ts --outfile=dist/openqq-bot.js --target=node",
22
+ "build:plugin": "bun build src/plugin-entry.ts --outfile=dist/opencode-qqbot-plugin.js --target=bun --external @opencode/plugin --external effect",
23
+ "deploy:plugin": "bun run build:bundle && bun run build:plugin && bun scripts/deploy-plugin.mjs",
24
+ "prepublishOnly": "bun run build:bundle && bun run build:plugin"
17
25
  },
18
26
  "files": [
19
27
  "bin",
20
28
  "src",
29
+ "dist",
21
30
  "tsconfig.json"
22
31
  ],
23
32
  "keywords": [
@@ -36,9 +45,15 @@
36
45
  "@opencode-ai/sdk": "^1.2.20",
37
46
  "ws": "^8.18.0"
38
47
  },
48
+ "peerDependencies": {
49
+ "@opencode/plugin": "^2.0.0",
50
+ "effect": "^4.0.0"
51
+ },
39
52
  "devDependencies": {
53
+ "@opencode/plugin": "^2.0.0",
40
54
  "@types/node": "^22.0.0",
41
55
  "@types/ws": "^8.5.0",
56
+ "effect": "^4.0.0",
42
57
  "typescript": "^5.9.0"
43
58
  }
44
59
  }
package/src/bridge.ts CHANGED
@@ -35,7 +35,15 @@ import { truncate } from "./core/util.js"
35
35
  import { createDelivery } from "./core/delivery.js"
36
36
  import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
37
37
  import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
38
- import { recordMessage, resolveQuote, scopeKeyOf } from "./core/context-buffer.js"
38
+ import { recordMessage, resolveQuote, scopeKeyOf, extractEmbeddedQuote } from "./core/context-buffer.js"
39
+ import {
40
+ recordInflight,
41
+ settleInflight,
42
+ pendingInflight,
43
+ classifyInflight,
44
+ INFLIGHT_MAX_AGE_MS,
45
+ redispatchMaxAgeMs,
46
+ } from "./core/inflight-journal.js"
39
47
  import { extractSendFileMarkers, sendLocalFile } from "./core/send-media.js"
40
48
  import type { InteractionEvent } from "./qq/types.js"
41
49
  // O7b:解析/格式化保持经 bridge 再导出——单测与既有调用方导入路径不变
@@ -80,6 +88,8 @@ interface Bridge {
80
88
  eventStream: ReturnType<typeof createEventStream>
81
89
  // A 项(2026-10-29):卡片按钮互动回调(index 侧挂到 QQ 网关 onInteraction)
82
90
  handleInteraction: (event: InteractionEvent) => void
91
+ // R 项(2026-10-30 重启丢消息事故修复):启动对账——补投/重挂/重派在途回合
92
+ recoverInflightRounds: () => Promise<void>
83
93
  }
84
94
 
85
95
  export function createBridge(
@@ -171,7 +181,7 @@ export function createBridge(
171
181
  const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000
172
182
  const STALL_NUDGE_MAX = 3
173
183
 
174
- function startBackgroundWait(sessionId: string, ctx: MessageContext, baseline: number): void {
184
+ function startBackgroundWait(sessionId: string, ctx: MessageContext, baseline: number, trackId?: string): void {
175
185
  let cancelled = false
176
186
  let finished = false
177
187
  const startedAt = Date.now()
@@ -193,6 +203,8 @@ export function createBridge(
193
203
  if (cancelled || finished) return
194
204
  finished = true
195
205
  cleanup()
206
+ // R 项:后台等待到达终态(完成投递/放弃告知)即销账
207
+ if (trackId) settleInflight(trackId)
196
208
  if (kind === "giveup") {
197
209
  await safeDeliver(ctx, "⚠️ 后台任务 24 小时仍未完成,停止自动跟进;结果可随时用 /history 查询")
198
210
  return
@@ -289,7 +301,7 @@ export function createBridge(
289
301
  }
290
302
 
291
303
  // O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
292
- const { enqueuePush, safeDeliver, sendReply } = createDelivery(config, lastCtx)
304
+ const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx)
293
305
 
294
306
  // O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
295
307
  const perm = createPermissionGate({
@@ -484,7 +496,8 @@ export function createBridge(
484
496
 
485
497
  // B3(2026-10-29 同步升级):C2C typing 指示——长回合处理中给用户
486
498
  // "对方正在输入"体感(官方 input_notify,仅 C2C;失败静默不阻塞主流程)
487
- if (ctx.type === "c2c") {
499
+ // R 项:重派回合无真实 msgId(空串),跳过 typing 防无效请求
500
+ if (ctx.type === "c2c" && ctx.msgId) {
488
501
  void getAccessToken(config.qq.appId, config.qq.clientSecret)
489
502
  .then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60))
490
503
  .catch(() => {})
@@ -492,6 +505,7 @@ export function createBridge(
492
505
 
493
506
  let sessionId = ""
494
507
  let turnStart = 0
508
+ let trackId = "" // R 项:在途台账跟踪键(try/catch 跨块可见)
495
509
  try {
496
510
  const session = await sessions.getOrCreate(ctx.userId)
497
511
  sessionId = session.sessionId
@@ -499,10 +513,11 @@ export function createBridge(
499
513
 
500
514
  // 缺口 1(引用上下文,吸收自官方 quote-ref 中间件):本条消息的引用解析
501
515
  // 先于本条登记(顺序不可反:本条入缓存后才能被后续消息引用)
502
- if (ctx.referencedMsgId) {
503
- const quoted = resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId)
504
- if (quoted) ctx.quoteText = quoted
505
- }
516
+ // N 项(2026-10-30):双通道——QQ 事件内嵌被引内容(message_type=103)
517
+ // 为权威来源优先;缺失才回落本地缓存(跨重启/老消息引用也能解析)。
518
+ const embeddedQuote = extractEmbeddedQuote(ctx.rawEvent)
519
+ const quoted = embeddedQuote ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null)
520
+ if (quoted) ctx.quoteText = quoted
506
521
  recordMessage(scopeKeyOf(ctx), ctx.msgId, ctx.content)
507
522
  // 新回合取代旧的后台等待(steer 合并运行时只投递一次合并结果)
508
523
  bgWaits.get(sessionId)?.cancel()
@@ -520,6 +535,10 @@ export function createBridge(
520
535
  const { text: promptBody, files } = augmentPromptWithAttachments(content, prepared)
521
536
  // 缺口 1:引用上文注入——让 AI 明确知道用户引用了哪条消息
522
537
  const promptText = ctx.quoteText ? `> 引用上文:${ctx.quoteText}\n\n${promptBody}` : promptBody
538
+ // R 项(2026-10-30):在途台账落账——派发前记录,送达才销账;
539
+ // 进程中途死亡时启动对账据此恢复。重派回合无真实 msgId,用合成键跟踪。
540
+ trackId = ctx.msgId || `redispatch-${sessionId}-${turnStart}`
541
+ recordInflight({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() })
523
542
  const replyText = await client.promptAndWait(sessionId, promptText, {
524
543
  files: files.length ? files : undefined,
525
544
  onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
@@ -547,17 +566,20 @@ export function createBridge(
547
566
  // 超长回合可能已超被动窗口:deliver 被动失败自动降级主动,答案不丢
548
567
  if (extracted.text) await safeDeliver(ctx, extracted.text)
549
568
  }
569
+ settleInflight(trackId) // R 项:回合处理到终态(答案已投递尝试),销账
550
570
  } catch (error) {
551
571
  if (sessionId && turnStart > 0 && error instanceof Error && error.message.includes("响应超时")) {
552
572
  // 前台时限到 ≠ 放弃:任务继续跑,转入后台等待(SSE + 5 分钟轮询兜底,
553
573
  // 最长 24 小时),完成时经 deliver 被动/主动回传 —— 12 小时长任务的答案也不丢。
574
+ // R 项:不销账——bgWait 完成投递时才销(完成前死亡由启动对账接管)。
554
575
  await safeDeliver(
555
576
  ctx,
556
577
  "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。",
557
578
  )
558
- startBackgroundWait(sessionId, ctx, turnStart)
579
+ startBackgroundWait(sessionId, ctx, turnStart, trackId)
559
580
  } else {
560
581
  await safeDeliver(ctx, `处理失败:${toErrorMessage(error)}`)
582
+ settleInflight(trackId) // R 项:失败反馈已送达 = 终态,销账
561
583
  }
562
584
  } finally {
563
585
  if (sessionId) unsubscribeSession(sessionId, ctx.userId) // /watch 若仍挂着则保留订阅
@@ -575,9 +597,52 @@ export function createBridge(
575
597
  }
576
598
  }
577
599
 
600
+ // R 项(2026-10-30 重启丢消息事故修复):启动对账——查在途台账里"已派发未销账"
601
+ // 的回合,按会话历史分类处置:已有答案→补投;仍在执行→重挂后台等待;
602
+ // 从未到达 opencode→30 分钟内自动重派(超期通知请用户重发)。
603
+ async function recoverInflightRounds(): Promise<void> {
604
+ const pending = pendingInflight()
605
+ if (pending.length === 0) return
606
+ console.log(`[bridge] 启动对账:${pending.length} 条在途消息待恢复`)
607
+ for (const entry of pending) {
608
+ const ageMs = Date.now() - entry.at
609
+ if (ageMs > INFLIGHT_MAX_AGE_MS) {
610
+ settleInflight(entry.msgId) // 超 24h:清账不追溯
611
+ continue
612
+ }
613
+ // 恢复投递走主动通道(原 msgId 的被动窗口早已过期)
614
+ const ctx: MessageContext = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text }
615
+ try {
616
+ const listJson = await client.session.messages({ path: { id: entry.sessionId } })
617
+ const cls = classifyInflight(entry, listJson?.data ?? [])
618
+ if (cls.kind === "answered") {
619
+ await deliver(ctx, `🔄 重启补投:你之前的消息已有答案\n\n${cls.answer}`)
620
+ settleInflight(entry.msgId)
621
+ console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`)
622
+ } else if (cls.kind === "running") {
623
+ await deliver(ctx, "🔄 重启恢复:你之前的任务仍在执行,完成即回传结果")
624
+ startBackgroundWait(entry.sessionId, ctx, Date.now(), entry.msgId)
625
+ console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`)
626
+ } else if (ageMs <= redispatchMaxAgeMs()) {
627
+ settleInflight(entry.msgId) // 旧账结清,重派回合走新账(合成 trackId)
628
+ await deliver(ctx, `🔄 重启恢复:重新处理你之前的消息「${entry.text.slice(0, 50)}」`)
629
+ void handleMessage(ctx)
630
+ console.log(`[bridge] 启动对账:丢失消息已重派 msgId=${entry.msgId}`)
631
+ } else {
632
+ await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.slice(0, 50)}」(超过自动重派窗口未重发),需要的话请重发一次`)
633
+ settleInflight(entry.msgId)
634
+ console.log(`[bridge] 启动对账:超期消息仅通知 msgId=${entry.msgId}`)
635
+ }
636
+ } catch (error) {
637
+ console.error(`[bridge] 启动对账单条失败 msgId=${entry.msgId}:`, error)
638
+ }
639
+ }
640
+ }
641
+
578
642
  return {
579
643
  handleMessage,
580
644
  eventStream,
645
+ recoverInflightRounds,
581
646
  handleInteraction: (event) => {
582
647
  if (handleApprovalInteraction(event, perm)) return
583
648
  void formBridge.handleButton(event)
@@ -0,0 +1,105 @@
1
+ // @input: fs/child_process/os(运行时探测、detached 拉起)
2
+ // @output: resolveRuntime, buildLaunchPlan, spawnBotDetached, readDotEnvField
3
+ // @pos: core - bot 进程拉起器(D 路径:插件引导器的服务端;跨平台 Windows/Linux/macOS)
4
+ //
5
+ // 设计:插件(opencode serve 内)检测 bot 不存活时,以 detached 子进程拉起——
6
+ // 子进程脱离 serve 生命周期(serve 重载/重启不碰 bot)。运行时解析 bun→node:
7
+ // bun 直接跑源码(.js→.ts 映射);node 跑发布时预打的 dist/openqq-bot.js bundle。
8
+ import { spawn, spawnSync } from "child_process"
9
+ import { existsSync, mkdirSync, openSync, readFileSync } from "fs"
10
+ import { join, dirname } from "path"
11
+ import { homedir } from "os"
12
+
13
+ export type Runtime = "bun" | "node"
14
+
15
+ /** 探测命令可用性(跨平台:spawnSync ENOENT=不存在) */
16
+ export function resolveRuntime(probe: (cmd: string) => boolean = defaultProbe): Runtime | null {
17
+ if (probe("bun")) return "bun"
18
+ if (probe("node")) return "node"
19
+ return null
20
+ }
21
+
22
+ function defaultProbe(cmd: string): boolean {
23
+ try {
24
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore" })
25
+ return r.status === 0
26
+ } catch {
27
+ return false
28
+ }
29
+ }
30
+
31
+ export interface LaunchPlan {
32
+ command: string
33
+ args: string[]
34
+ /** 子进程环境:继承当前环境 + try 模式单实例锁 */
35
+ env: NodeJS.ProcessEnv
36
+ }
37
+
38
+ /**
39
+ * 解析 bot 入口文件(按安装形态探测,纯函数供测试):
40
+ * 1. 插件同目录 bot.js(plugins 目录自包含安装形态——官方规范的一键安装)
41
+ * 2. 包根 dist/openqq-bot.js(npm 包形态,prepublish 预打)
42
+ * 3. 包根 src/index.ts(dev 形态,需 bun 直跑 TS)
43
+ * 全缺 → null(调用方给指引)
44
+ */
45
+ export function resolveBotEntry(
46
+ pluginFilePath: string,
47
+ exists: (p: string) => boolean = existsSync,
48
+ ): string | null {
49
+ const dir = dirname(pluginFilePath)
50
+ const candidates = [
51
+ join(dir, "bot.js"), // 形态 1:自包含插件目录(bot.js 是同目录兄弟)
52
+ join(homedir(), ".openqq", "plugin-payload", "bot.js"), // 形态 1b:单文件形态的有效载荷位
53
+ join(dir, "..", "dist", "openqq-bot.js"), // 形态 2:npm 包(plugin-entry 在 src/ 下)
54
+ join(dir, "..", "src", "index.ts"), // 形态 3:dev 源码
55
+ ]
56
+ for (const c of candidates) if (exists(c)) return c
57
+ return null
58
+ }
59
+
60
+ /** 构造拉起计划(纯函数供测试)。entry 由 resolveBotEntry 解析。 */
61
+ export function buildLaunchPlan(runtime: Runtime, entry: string): LaunchPlan {
62
+ const env = { ...process.env, QQ_INSTANCE_LOCK: "try" } // 拉起即抢锁,抢不到自动退出
63
+ if (runtime === "bun") return { command: "bun", args: ["run", entry], env }
64
+ return { command: "node", args: [entry], env }
65
+ }
66
+
67
+ /** bot 输出日志(detached 后 stdout/stderr 的唯一去向) */
68
+ export function botLogPath(): string {
69
+ return join(homedir(), ".openqq", "bot.out.log")
70
+ }
71
+
72
+ /**
73
+ * detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
74
+ * 返回 pid;拉起失败抛错(调用方记日志)。
75
+ */
76
+ export function spawnBotDetached(plan: LaunchPlan, logPath: string = botLogPath()): number {
77
+ mkdirSync(join(logPath, ".."), { recursive: true })
78
+ const out = openSync(logPath, "a")
79
+ const child = spawn(plan.command, plan.args, {
80
+ detached: true,
81
+ stdio: ["ignore", out, out],
82
+ env: plan.env,
83
+ windowsHide: true,
84
+ })
85
+ child.unref() // 父进程(serve)退出不带走 bot
86
+ if (typeof child.pid !== "number") throw new Error("spawn 未返回 pid")
87
+ return child.pid
88
+ }
89
+
90
+ /** 极简 .env 字段读取(插件侧用,不经 config 模块——避免其 process.env 副作用与 throw) */
91
+ export function readDotEnvField(envPath: string, key: string): string | null {
92
+ try {
93
+ if (!existsSync(envPath)) return null
94
+ for (const line of readFileSync(envPath, "utf-8").split("\n")) {
95
+ const trimmed = line.trim()
96
+ if (!trimmed || trimmed.startsWith("#")) continue
97
+ const eq = trimmed.indexOf("=")
98
+ if (eq < 0) continue
99
+ if (trimmed.slice(0, eq).trim() === key) return trimmed.slice(eq + 1).trim()
100
+ }
101
+ return null
102
+ } catch {
103
+ return null
104
+ }
105
+ }
@@ -46,6 +46,32 @@ export function resolveQuote(scope: string, referencedMsgId: string): string | n
46
46
  return entry?.text ?? null
47
47
  }
48
48
 
49
+ // N 项(2026-10-30,吸收竞品 opencode-qq-v2 util/quote.js):引用消息双通道——
50
+ // QQ 在 message_type=103 时把被引内容嵌在 msg_elements 里随事件透传(官方未完全
51
+ // 文档化结构,做防御性递归提取);命中即权威来源,不再依赖本缓存(跨重启/引用
52
+ // 老消息也能解析)。提取为空时调用方回落 resolveQuote 缓存通道。
53
+ export function extractEmbeddedQuote(event: { message_type?: unknown; msg_elements?: unknown } | undefined): string | null {
54
+ if (!event || Number(event.message_type) !== 103 || !event.msg_elements) return null
55
+ const out: string[] = []
56
+ const walk = (node: unknown, depth: number): void => {
57
+ if (depth > 8 || out.join("\n").length > 4000) return
58
+ if (Array.isArray(node)) {
59
+ for (const item of node) walk(item, depth + 1)
60
+ return
61
+ }
62
+ if (node && typeof node === "object") {
63
+ const obj = node as Record<string, unknown>
64
+ if (typeof obj.content === "string" && obj.content.trim()) out.push(obj.content.trim())
65
+ for (const key of Object.keys(obj)) {
66
+ if (key !== "content") walk(obj[key], depth + 1)
67
+ }
68
+ }
69
+ }
70
+ walk(event.msg_elements, 0)
71
+ const text = out.join("\n").trim().slice(0, 2000)
72
+ return text || null
73
+ }
74
+
49
75
  /** 测试/运维用:清空全部缓存 */
50
76
  export function resetContextBuffer(): void {
51
77
  scopeBuffers.clear()
@@ -52,6 +52,10 @@ function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warne
52
52
  }
53
53
  }
54
54
 
55
+ // P 项(2026-10-30,吸收竞品 pendingNotice 模式):发送彻底失败不静默——
56
+ // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
57
+ export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
58
+
55
59
  // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
56
60
  // 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
57
61
  export function selectRideMsgId(
@@ -105,6 +109,8 @@ export function createDelivery(
105
109
  })()
106
110
 
107
111
  const pushQueues = new Map<string, PushQueue>()
112
+ // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
113
+ const undelivered = new Set<string>()
108
114
  const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
109
115
  // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
110
116
  // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
@@ -142,6 +148,7 @@ export function createDelivery(
142
148
  try {
143
149
  await deliver(ctx, text)
144
150
  } catch (error) {
151
+ undelivered.add(userId) // P 项:观察推送彻底失败 → 贴条待下次消化
145
152
  console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
146
153
  }
147
154
  }
@@ -150,7 +157,20 @@ export function createDelivery(
150
157
  // 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
151
158
  // 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
152
159
  //(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
160
+ // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
161
+ // 投递失败则把贴条放回(留待下次),成功才算消化。
153
162
  async function deliver(ctx: MessageContext, text: string): Promise<void> {
163
+ const hadNotice = undelivered.delete(ctx.userId)
164
+ const body = hadNotice ? UNDELIVERED_NOTICE + text : text
165
+ try {
166
+ await deliverCore(ctx, body)
167
+ } catch (error) {
168
+ if (hadNotice) undelivered.add(ctx.userId)
169
+ throw error
170
+ }
171
+ }
172
+
173
+ async function deliverCore(ctx: MessageContext, text: string): Promise<void> {
154
174
  // B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
155
175
  const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
156
176
  if (passive?.shouldFallbackToProactive) {
@@ -214,6 +234,7 @@ export function createDelivery(
214
234
  try {
215
235
  await deliver(c, text)
216
236
  } catch (error) {
237
+ undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
217
238
  console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
218
239
  }
219
240
  }
@@ -0,0 +1,149 @@
1
+ // @input: fs/path/os(台账落盘)
2
+ // @output: recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
3
+ // resetInflightJournal(测试用), INFLIGHT_MAX_AGE_MS, REDISPATCH_MAX_AGE_MS
4
+ // @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
5
+ //
6
+ // 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
7
+ // 丢失无反馈——在途回合状态全在内存,进程换代即蒸发。本模块把"派发→送达"责任
8
+ // 落盘到 ~/.openqq/inflight.json,启动时对账恢复(bridge.recoverInflightRounds)。
9
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from "fs"
10
+ import { join } from "path"
11
+ import { homedir } from "os"
12
+
13
+ export interface InflightEntry {
14
+ /** 跟踪键:真实 QQ msgId;重派回合为合成键 redispatch-<sessionId>-<ts> */
15
+ msgId: string
16
+ userId: string
17
+ sessionId: string
18
+ /** 用户消息原文(截 300 字,对账匹配与通知展示用) */
19
+ text: string
20
+ at: number
21
+ state: "inflight" | "settled"
22
+ }
23
+
24
+ // 对账年龄上限:超 24h 的在途账不再追溯(直接清账)。
25
+ // 注意:这也是"重派窗口不限时间"的天然上限——重派窗口设得再大,超 24h 的账已清。
26
+ export const INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000
27
+ // 丢失消息自动重派窗口(2026-10-30 用户拍板:默认 2 小时,env QQ_REDISPATCH_MAX_AGE_MS
28
+ // 可调;0=关闭自动重派一律通知)。窗口内视为"意图仍然新鲜"自动重派;超期只通知请用户
29
+ // 重发——防"陈旧意图"在重启时被意外执行。
30
+ export function redispatchMaxAgeMs(): number {
31
+ const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000")
32
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7_200_000
33
+ }
34
+
35
+ // 测试可经 QQ_INFLIGHT_FILE 指向临时文件
36
+ function journalPath(): string {
37
+ return process.env.QQ_INFLIGHT_FILE || join(homedir(), ".openqq", "inflight.json")
38
+ }
39
+
40
+ let cache: InflightEntry[] | null = null
41
+
42
+ function load(): InflightEntry[] {
43
+ if (cache) return cache
44
+ let entries: InflightEntry[] = []
45
+ try {
46
+ if (existsSync(journalPath())) {
47
+ const raw = JSON.parse(readFileSync(journalPath(), "utf-8"))
48
+ if (Array.isArray(raw)) entries = raw
49
+ }
50
+ } catch {
51
+ entries = [] // 损坏即空,不阻塞启动
52
+ }
53
+ // 修剪:已销账超 24h 的不再保留
54
+ cache = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS)
55
+ return cache
56
+ }
57
+
58
+ function save(): void {
59
+ if (!cache) return
60
+ try {
61
+ const path = journalPath()
62
+ mkdirSync(join(path, ".."), { recursive: true })
63
+ // 原子写:先写临时文件再改名,防写一半被杀留坏账
64
+ const tmp = `${path}.tmp`
65
+ writeFileSync(tmp, JSON.stringify(cache, null, 2))
66
+ renameSync(tmp, path)
67
+ } catch (error) {
68
+ console.warn("[inflight] 台账落盘失败:", error instanceof Error ? error.message : error)
69
+ }
70
+ }
71
+
72
+ /** 派发落账:QQ 消息进入 AI 派发管线前调用 */
73
+ export function recordInflight(entry: Omit<InflightEntry, "state">): void {
74
+ const entries = load()
75
+ entries.push({ ...entry, state: "inflight" })
76
+ save()
77
+ }
78
+
79
+ /** 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈) */
80
+ export function settleInflight(msgId: string): void {
81
+ const entry = load().find((e) => e.msgId === msgId && e.state === "inflight")
82
+ if (!entry) return
83
+ entry.state = "settled"
84
+ save()
85
+ }
86
+
87
+ /** 待对账清单(启动恢复用) */
88
+ export function pendingInflight(): InflightEntry[] {
89
+ return load().filter((e) => e.state === "inflight")
90
+ }
91
+
92
+ /** 测试用:清空台账缓存与文件状态 */
93
+ export function resetInflightJournal(): void {
94
+ cache = []
95
+ save()
96
+ }
97
+
98
+ // —— 对账分类(纯函数)——
99
+ // 与 opencode/mirror.ts buildDigest 同源的消息形状(最小依赖,避免跨层 import)。
100
+ interface HistoryMessage {
101
+ type?: string
102
+ text?: string
103
+ content?: Array<{ type?: string; text?: string }>
104
+ }
105
+
106
+ export type InflightClass =
107
+ | { kind: "answered"; answer: string }
108
+ | { kind: "running" }
109
+ | { kind: "lost" }
110
+
111
+ /**
112
+ * 对账分类:台账条目 × 会话历史 → 该回合的真实状态。
113
+ * - answered:历史里找到该用户消息且其后已有 assistant 正文 → 答案在库里没投出,补投
114
+ * - running:找到该用户消息但尚无 assistant 正文 → 回合在跑(或被中断),重挂后台等待
115
+ * - lost:历史里找不到该用户消息 → 消息从未到达 opencode(网关窗口丢失),重派/通知
116
+ * 匹配口径:历史 user 文本包含台账原文前 50 字(prompt 会加引用前缀/附件注记,不能全等)。
117
+ */
118
+ export function classifyInflight(
119
+ entry: Pick<InflightEntry, "text">,
120
+ messages: HistoryMessage[],
121
+ ): InflightClass {
122
+ const ordered = [...messages].reverse()
123
+ let lastUserIdx = -1
124
+ for (let i = ordered.length - 1; i >= 0; i--) {
125
+ if (ordered[i].type === "user") {
126
+ lastUserIdx = i
127
+ break
128
+ }
129
+ }
130
+ if (lastUserIdx < 0) return { kind: "lost" }
131
+
132
+ const userText = (ordered[lastUserIdx].text ?? "").trim()
133
+ const probe = entry.text.trim().slice(0, 50)
134
+ // 纯附件消息(无文字)无法文本匹配——探针为空视为匹配(由 answered 判定兜底)
135
+ const matched = probe === "" || userText.includes(probe)
136
+ if (!matched) return { kind: "lost" }
137
+
138
+ const answerParts: string[] = []
139
+ for (let i = lastUserIdx + 1; i < ordered.length; i++) {
140
+ const m = ordered[i]
141
+ if (m.type === "assistant") {
142
+ for (const p of m.content ?? []) {
143
+ if (p.type === "text" && p.text?.trim()) answerParts.push(p.text.trim())
144
+ }
145
+ }
146
+ }
147
+ const answer = answerParts.join("\n").trim()
148
+ return answer ? { kind: "answered", answer } : { kind: "running" }
149
+ }