@linjz/opencode-qqbot 0.3.14 → 0.3.15

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,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -14,14 +14,15 @@
14
14
  "dev": "bun run --watch src/index.ts",
15
15
  "start": "bun run src/index.ts",
16
16
  "typecheck": "tsc --noEmit",
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/delivery-dedupe-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 && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-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/delivery-dedupe-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 && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts && bun run test/instance-lock-cases.ts && bun run test/notify-cases.ts",
18
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",
19
19
  "verify": "bun run typecheck && bun run test",
20
20
  "verify:full": "bun run verify && bun run test:e2e",
21
21
  "build:bundle": "bun build src/index.ts --outfile=dist/openqq-bot.js --target=node",
22
+ "build:notify": "bun build src/cli/notify-main.ts --outfile=dist/notify-cli.js --target=node",
22
23
  "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"
24
+ "deploy:plugin": "bun run build:bundle && bun run build:notify && bun run build:plugin && bun scripts/deploy-plugin.mjs",
25
+ "prepublishOnly": "bun run build:bundle && bun run build:notify && bun run build:plugin"
25
26
  },
26
27
  "files": [
27
28
  "bin",
package/src/bridge.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  } from "./core/permission.js"
38
38
  import { truncate } from "./core/util.js"
39
39
  import { createDelivery } from "./core/delivery.js"
40
+ import { createNotifySink } from "./core/notify-sink.js"
40
41
  import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
41
42
  import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
42
43
  import { recordMessage, resolveQuote, scopeKeyOf, extractEmbeddedQuote } from "./core/context-buffer.js"
@@ -401,6 +402,17 @@ export function createBridge(
401
402
 
402
403
  // O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
403
404
  const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx)
405
+ // DEF-1 修复(2026-11-04,UAT 实证):通知类发送永不阻断主流程——受理回执/
406
+ // K2 拦截/排队提示/问候等裸 sendReply 一旦被平台拒(40034024/超时)会直接
407
+ // 中断 handleMessage(实证:回执失败 → 回合未派发给 AI 即结算,用户消息被吞)。
408
+ // 统一走 notifyUser 兜底:发送失败仅告警,主流程继续。
409
+ const notifyUser = async (ctx: MessageContext, text: string): Promise<void> => {
410
+ try {
411
+ await sendReply(ctx, text)
412
+ } catch (error) {
413
+ console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage(error))
414
+ }
415
+ }
404
416
 
405
417
  // O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
406
418
  const perm = createPermissionGate({
@@ -415,6 +427,15 @@ export function createBridge(
415
427
  // O7d:摘要镜像域门面(订阅/回合标记/延迟解锁/摘要投递全在 core/mirror.ts)
416
428
  const mirror = createMirror({ sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers })
417
429
 
430
+ // openqq notify 外部入队通道(feature:headless 定时任务结果推送,2026-11-05 外部提案 Part1):
431
+ // cron/CI 任意进程经 `openqq notify` 写 ~/.openqq/outbox.json(只入队),bot 进程消费投递。
432
+ // delivery 全量复用(配额/降级/分条/24h 同文去重);TTL 过期丢弃;失败退避重试到上限。
433
+ createNotifySink({
434
+ config,
435
+ deliver: (ctx, text) => deliver(ctx, text),
436
+ ...(process.env.QQ_OUTBOX_FILE ? { filePath: process.env.QQ_OUTBOX_FILE } : {}),
437
+ })
438
+
418
439
  // L 项(2026-10-30):表单桥(选择弹窗 A/B/C/D 的 QQ 同步与作答回传)。
419
440
  // 与审批共用"每用户单一交互槽"心智:表单挂起时优先消费用户回复。
420
441
  // 按钮卡片(弹窗验证前置):选项直点直交,失败自动降级文字编号作答。
@@ -580,7 +601,7 @@ export function createBridge(
580
601
  // 途径获取自己的 openid 填 ALLOWED_USERS,首配死锁;白名单内不打印(无需)。
581
602
  if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
582
603
  console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`)
583
- await sendReply(ctx, "你不在允许使用的名单里")
604
+ await notifyUser(ctx, "你不在允许使用的名单里")
584
605
  return
585
606
  }
586
607
 
@@ -597,7 +618,7 @@ export function createBridge(
597
618
  if (!greeted.has(ctx.userId) && !isCommand(content)) {
598
619
  greeted.add(ctx.userId)
599
620
  saveGreetedSet(greeted)
600
- await sendReply(ctx, buildHelpText())
621
+ await notifyUser(ctx, buildHelpText())
601
622
  }
602
623
 
603
624
  // 权限审批决策优先于命令/普通消息:原 prompt 在 promptAndWait 里
@@ -619,20 +640,20 @@ export function createBridge(
619
640
 
620
641
  if (isCommand(content)) {
621
642
  const reply = await handleCommand(ctx, commandContext)
622
- await sendReply(ctx, reply)
643
+ await notifyUser(ctx, reply)
623
644
  return
624
645
  }
625
646
 
626
647
  const pendingReply = await maybeHandlePendingSelection(ctx, commandContext)
627
648
  if (pendingReply !== null) {
628
- await sendReply(ctx, pendingReply)
649
+ await notifyUser(ctx, pendingReply)
629
650
  return
630
651
  }
631
652
 
632
653
  // 审批待决时,普通消息不进新 prompt(会话正阻塞在审批上),重发审批菜单
633
654
  const pendingPerm = perm.getPending(ctx.userId)
634
655
  if (pendingPerm) {
635
- await sendReply(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId))
656
+ await notifyUser(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId))
636
657
  return
637
658
  }
638
659
 
@@ -656,7 +677,7 @@ export function createBridge(
656
677
  // P3(2026-11-03,外部复盘核验 R4):提示带在途内容摘要提升体感
657
678
  const pend = pendingInflight().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey))
658
679
  const digest = pend ? `(在途内容:${previewText(pend.text)})` : ""
659
- await sendReply(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`)
680
+ await notifyUser(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`)
660
681
  return
661
682
  }
662
683
  claimedContexts.add(ctx)
@@ -684,11 +705,11 @@ export function createBridge(
684
705
  const queued = msgQueue.push(ctx.userId, ctx)
685
706
  if (!queued) {
686
707
  if (claimedMsgId) settleInflight(claimedMsgId) // 已满回执即终态,不能留账让启动对账再次执行
687
- await sendReply(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`)
708
+ await notifyUser(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`)
688
709
  return
689
710
  }
690
711
  // 入队前已由 claimInflight 落账;drain 重入时回填 sessionId,不重复写账。
691
- await sendReply(
712
+ await notifyUser(
692
713
  ctx,
693
714
  `已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。\n发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`,
694
715
  )
@@ -704,7 +725,7 @@ export function createBridge(
704
725
  // 通知——这三处都不进本分支,同一 intent 不重复点头。
705
726
  // (同日迭代:改为开关制、默认不发——见顶部 ackReceiptEnabled。)
706
727
  if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
707
- await sendReply(ctx, "✅ 已收到,正在处理,完成后自动回复你")
728
+ await notifyUser(ctx, "✅ 已收到,正在处理,完成后自动回复你")
708
729
  }
709
730
 
710
731
  // B3(2026-10-29 同步升级):C2C typing 指示——长回合处理中给用户
@@ -768,7 +789,7 @@ export function createBridge(
768
789
  void safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`)
769
790
  },
770
791
  onPermissionConflict: () => {
771
- void safeDeliver(ctx, "⚠️ 该审批已在桌面端处理,AI 继续执行…")
792
+ void safeDeliver(ctx, "⚠️ 该审批请求状态不明(可能在桌面端处理或已超时)。如命令未执行,请重新发起原操作")
772
793
  },
773
794
  })
774
795
 
@@ -895,7 +916,7 @@ export function createBridge(
895
916
  if (!job) return
896
917
  draining.add(userId)
897
918
  try {
898
- await sendReply(job.ctx, `开始执行队列 #${job.id}`)
919
+ await notifyUser(job.ctx, `开始执行队列 #${job.id}`)
899
920
  drainReentries.add(job.ctx) // 修复⑦:drain 重入跳过受理回执
900
921
  await handleMessage(job.ctx)
901
922
  } catch (error) {
@@ -0,0 +1,6 @@
1
+ // @input: ./notify.ts(runNotifyCli)
2
+ // @output:(无导出)——notify CLI 的自执行入口(构建目标:dist/notify-cli.js)
3
+ // @pos: cli - bin/openqq.js notify 子命令的落点;测试请 import ./notify.ts(不要引入本文件)。
4
+ import { main } from "./notify.js"
5
+
6
+ process.exitCode = await main(process.argv.slice(2))
@@ -0,0 +1,158 @@
1
+ // @input: node:fs/homedir/join、../config(ENV_FILE/loadEnvFile)、../qq/api(getAccessToken 校准用不入队)、./outbox.ts、../core/notify-sink.ts(resolveNotifyRecipients/defaultOutboxPath)
2
+ // @output: runNotifyCli(argv)(供 bin/openqq.js 与测试调用),只入队不发送。
3
+ // @pos: cli - openqq notify 外部入队通道(feature:headless 定时任务结果推送)。
4
+ // BOT(notify-sink)进程消费投递;CLI 不取 token、不连 OpenCode、不抢实例锁。
5
+ // @note: 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1;
6
+ // 收件人 fail-closed:缺省取 ALLOWED_USERS 唯一项;显式 --user 必须命中名单。
7
+ import { existsSync, readFileSync } from "node:fs"
8
+ import { createOutbox } from "../core/outbox.js"
9
+ import { ENV_FILE, loadEnvFile } from "../config.js"
10
+ import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
11
+
12
+ export interface NotifyCliOptions {
13
+ filePath?: string
14
+ now?: number
15
+ env?: { allowedUsers: readonly string[] }
16
+ }
17
+
18
+ /** CLI 结果(--json 输出同 shape;dry-run 时 queued=false 并附 wouldEnqueue)。 */
19
+ export interface NotifyCliResult {
20
+ ok: boolean
21
+ queued: boolean
22
+ id: string
23
+ user: string
24
+ chars: number
25
+ truncated: boolean
26
+ dryRun: boolean
27
+ reason?: string
28
+ }
29
+
30
+ /** 保守截断:默认 1500 字(主动消息日配额 100/天——长输出拆几十条会吃光);0=不截断。 */
31
+ export const NOTIFY_DEFAULT_MAX_CHARS = 1500
32
+
33
+ interface ParsedArgs {
34
+ text?: string
35
+ filePath?: string
36
+ stdin?: boolean
37
+ user?: string
38
+ id?: string
39
+ maxChars: number
40
+ ttlHours?: number
41
+ dryRun: boolean
42
+ json: boolean
43
+ help: boolean
44
+ }
45
+
46
+ function parseArgs(argv: readonly string[]): ParsedArgs {
47
+ const parsed: ParsedArgs = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false }
48
+ for (let i = 0; i < argv.length; i++) {
49
+ const a = argv[i]
50
+ const next = argv[i + 1]
51
+ switch (a) {
52
+ case "--text": parsed.text = next; i++; break
53
+ case "--file": parsed.filePath = next; i++; break
54
+ case "--stdin": parsed.stdin = true; break
55
+ case "--user": parsed.user = next; i++; break
56
+ case "--id": parsed.id = next; i++; break
57
+ case "--max-chars": parsed.maxChars = Number(next); i++; break
58
+ case "--ttl-hours": parsed.ttlHours = Number(next); i++; break
59
+ case "--dry-run": parsed.dryRun = true; break
60
+ case "--json": parsed.json = true; break
61
+ case "--help": case "-h": parsed.help = true; i++; break
62
+ default:
63
+ throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`)
64
+ }
65
+ }
66
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
67
+ throw new Error("必须提供正文来源:--text / --file / --stdin 三选一")
68
+ }
69
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
70
+ throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)")
71
+ }
72
+ return parsed
73
+ }
74
+
75
+ /** 收件人 fail-closed:显式 --user 必须命中名单;缺省仅取 ALLOWED_USERS 唯一项。 */
76
+ export function resolveUser(envAllowed: readonly string[], explicit?: string): string {
77
+ return resolveNotifyRecipients(envAllowed, explicit)
78
+ }
79
+
80
+ /** 正文来源:--text / --file / --stdin;--file - 读 stdin(同步可读)。 */
81
+ function readBody(parsed: ParsedArgs): string {
82
+ if (parsed.text !== undefined) return parsed.text
83
+ if (parsed.filePath !== undefined) {
84
+ if (parsed.filePath === "-") return readFileSync(0 as unknown as number, "utf8")
85
+ if (!existsSync(parsed.filePath)) throw new Error(`--file 不存在:${parsed.filePath}`)
86
+ return readFileSync(parsed.filePath, "utf8")
87
+ }
88
+ if (parsed.stdin) return readFileSync(0 as unknown as number, "utf8")
89
+ return ""
90
+ }
91
+
92
+ export async function runNotifyCli(
93
+ argv: readonly string[],
94
+ options: NotifyCliOptions = {},
95
+ ): Promise<NotifyCliResult> {
96
+ const now = options.now ?? Date.now()
97
+ const parsed = parseArgs(argv)
98
+ if (parsed.help) {
99
+ const help = [
100
+ "用法:openqq notify --text \"…\" | --file <路径> | --stdin",
101
+ " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
102
+ " --id <key> 幂等键(同 key 不重复投递)",
103
+ " --max-chars <n> 截断上限,默认 1500,0 不截断",
104
+ " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
105
+ " --dry-run / --json 不入队 / 机器可读输出",
106
+ ].join("\n")
107
+ console.log(help)
108
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, reason: "help" }
109
+ }
110
+ // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
111
+ if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
112
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
113
+ .split(/[,\s]+/).filter(Boolean)
114
+ const user = resolveUser(allowedUsers, parsed.user)
115
+ if (!user) {
116
+ throw new Error(
117
+ allowedUsers.length === 0
118
+ ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)"
119
+ : "多用户名单必须用 --user <openid> 显式指定收件人",
120
+ )
121
+ }
122
+ const raw = readBody(parsed)
123
+ const max = parsed.maxChars
124
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw
125
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
126
+ const filePath = options.filePath ?? defaultOutboxPath()
127
+ if (parsed.dryRun) {
128
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true }
129
+ }
130
+ const ttlHours =
131
+ parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24)
132
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
133
+ ? now + ttlHours * 60 * 60 * 1000
134
+ : now
135
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 })
136
+ const entry = await outbox.enqueue({
137
+ ...(parsed.id ? { id: parsed.id } : {}),
138
+ kind: "notify",
139
+ payload: { text: content },
140
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
141
+ sessionId: "",
142
+ nextAttemptAt,
143
+ })
144
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false }
145
+ }
146
+
147
+ /** bin/openqq.js 入口:返回进程退出码(0=已入队;1=参数/配置错误)。 */
148
+ export async function main(argv: readonly string[]): Promise<number> {
149
+ try {
150
+ const result = await runNotifyCli(argv)
151
+ if (result.reason === "help") return 0
152
+ if (result.queued && !result.dryRun) console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
153
+ return result.ok ? 0 : 1
154
+ } catch (error) {
155
+ console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`)
156
+ return 1
157
+ }
158
+ }
package/src/config.ts CHANGED
@@ -20,7 +20,7 @@ export interface Config {
20
20
  }
21
21
 
22
22
  const CONFIG_DIR = join(homedir(), ".openqq")
23
- const ENV_FILE = join(CONFIG_DIR, ".env")
23
+ export const ENV_FILE = join(CONFIG_DIR, ".env")
24
24
 
25
25
  function askTwo(q1: string, q2: string): Promise<[string, string]> {
26
26
  return new Promise((resolve, reject) => {
@@ -76,7 +76,7 @@ export async function ensureConfig(): Promise<void> {
76
76
  process.env.QQ_APP_SECRET = appSecret
77
77
  }
78
78
 
79
- function loadEnvFile(path: string): void {
79
+ export function loadEnvFile(path: string): void {
80
80
  const content = readFileSync(path, "utf-8")
81
81
  for (const line of content.split("\n")) {
82
82
  const trimmed = line.trim()
@@ -327,7 +327,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
327
327
  if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
328
328
  // 桌面端先答/先取消是终态;只有明确的服务端冲突才清理。
329
329
  if (isCurrent(userId, entry)) clearEntry(userId, entry)
330
- await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效")
330
+ await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
331
331
  } else {
332
332
  // submitting + answer 保留在内存和磁盘,可手动重试或由 reconcile 续交。
333
333
  await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`)
@@ -381,7 +381,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
381
381
  }
382
382
  clearEntry(userId, entry)
383
383
  }
384
- await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;如需继续请回桌面重试")
384
+ await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
385
385
  }
386
386
 
387
387
  function scheduleExpiry(userId: string, entry: InternalPendingForm): void {
@@ -38,8 +38,15 @@ function touch(path: string): void {
38
38
  utimesSync(path, now, now)
39
39
  }
40
40
 
41
- /** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null */
42
- export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE_MS): InstanceLock | null {
41
+ /** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null
42
+ * opts 仅供测试注入时序(默认行为与生产一致):heartbeatMs 心跳间隔、selfCheckMs 自检周期 */
43
+ export function acquireInstanceLockAt(
44
+ path: string,
45
+ staleMs: number = LOCK_STALE_MS,
46
+ opts?: { heartbeatMs?: number; selfCheckMs?: number },
47
+ ): InstanceLock | null {
48
+ const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS
49
+ const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS
43
50
  try {
44
51
  mkdirSync(join(path, ".."), { recursive: true })
45
52
  // wx = 原子排他创建,已存在则抛 EEXIST
@@ -67,7 +74,7 @@ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE
67
74
  } catch {
68
75
  /* 锁文件被外部删除时心跳失败,下轮仍试;不致命 */
69
76
  }
70
- }, LOCK_UPDATE_MS)
77
+ }, heartbeatMs)
71
78
  // 测试场景不拖累进程退出
72
79
  heartbeat.unref?.()
73
80
 
@@ -89,7 +96,7 @@ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE
89
96
  console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出")
90
97
  process.exit(1)
91
98
  }
92
- }, LOCK_SELF_CHECK_MS)
99
+ }, selfCheckMs)
93
100
  selfCheck.unref?.()
94
101
 
95
102
  let released = false
@@ -0,0 +1,96 @@
1
+ // @input: node:os/node:path(路径)、./outbox.ts、../config(Config 类型)
2
+ // @output: createNotifySink / resolveNotifyRecipients / defaultOutboxPath / 常量
3
+ // @pos: core - openqq notify 外部入队通道的消费端:bot 进程注册 'notify'
4
+ // outbox handler,把 outbox.json 里积压的通知用 delivery 投给 QQ 用户。
5
+ // @note: 入队端在 src/cli/notify.ts(只入队,不发送);本文件只负责消费——
6
+ // TTL 过期丢弃 / maxAttempts 重试上限 / 失败由 outbox 退避重试。
7
+ // 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1(0.3.14 现存缺口:
8
+ // `opencode run` 新会话无 QQ 映射 → 镜像「无映射主人」跳过 → 结果推不到 QQ)。
9
+ // 交付层不换实现:deliver 内含配额记账/被动→主动降级/分条/24h 同文去重。
10
+ import { homedir } from "node:os"
11
+ import { join } from "node:path"
12
+ import type { Config } from "../config.js"
13
+ import type { MessageContext } from "../qq/types.js"
14
+ import { createOutbox } from "./outbox.js"
15
+
16
+ /** 默认 TTL:bot 长期不在线时积压不会在重启后集中刷屏。 */
17
+ export const DEFAULT_NOTIFY_TTL_HOURS = 24
18
+ /** 单条最大投递尝试次数:配额耗尽等永久失败不无限退避。 */
19
+ export const DEFAULT_NOTIFY_MAX_ATTEMPTS = 8
20
+
21
+ export type DeliverLike = (ctx: MessageContext, text: string) => Promise<void>
22
+
23
+ export interface NotifySinkOptions {
24
+ config: Config
25
+ deliver: DeliverLike
26
+ /** 队列文件;缺省 QQ_OUTBOX_FILE → ~/.openqq/outbox.json(bot 与 CLI 必须一致)。 */
27
+ filePath?: string
28
+ ttlHours?: number
29
+ maxAttempts?: number
30
+ }
31
+
32
+ export interface NotifySink {
33
+ outbox: ReturnType<typeof createOutbox>
34
+ /** 停止轮询;挂起的发送交由 outbox.drain 语义接管。 */
35
+ stop: () => void
36
+ }
37
+
38
+ /**
39
+ * 创建并启动 notify 消费端。handler 语义:
40
+ * - payload.text 投给 entry.ctx(c2c 主动消息;delivery 内含配额/降级/分条/24h 去重);
41
+ * - TTL 过期 → 返回 skipped 说明(outbox 记为 sent,不发送)——积压不刷屏;
42
+ * - 投递抛错 → outbox 记 failed 并退避重试,到 maxAttempts 保持 failed。
43
+ * start() 已含 recover(崩溃 sending→pending/failed,至少一次语义)。
44
+ */
45
+ export function createNotifySink(options: NotifySinkOptions): NotifySink {
46
+ const ttlHours = Number(
47
+ options.ttlHours ?? process.env.QQ_NOTIFY_TTL_HOURS ?? DEFAULT_NOTIFY_TTL_HOURS,
48
+ )
49
+ const ttlMs =
50
+ (Number.isFinite(ttlHours) && ttlHours > 0 ? ttlHours : DEFAULT_NOTIFY_TTL_HOURS) *
51
+ 60 * 60 * 1000
52
+ const maxRaw = Number(
53
+ options.maxAttempts ?? process.env.QQ_NOTIFY_MAX_ATTEMPTS ?? DEFAULT_NOTIFY_MAX_ATTEMPTS,
54
+ )
55
+ const maxAttempts = Number.isFinite(maxRaw) && maxRaw > 0 ? Math.floor(maxRaw) : DEFAULT_NOTIFY_MAX_ATTEMPTS
56
+ const outbox = createOutbox({ ...(options.filePath ? { filePath: options.filePath } : {}) })
57
+ outbox.register("notify", (entry) => {
58
+ if (Date.now() - entry.createdAt > ttlMs) {
59
+ return { skipped: "ttl-expired" }
60
+ }
61
+ const text = (entry.payload as { text?: unknown } | null)?.text
62
+ if (typeof text !== "string" || !text.trim()) {
63
+ return { skipped: "no-text" }
64
+ }
65
+ const ctx = entry.ctx as MessageContext
66
+ // fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
67
+ // maxAttempts 由轮询/flush 透传 maxAttempts 项在 outbox.start 后生效:这里只在
68
+ // pollInterval 层用 sink 的全局退避语义,未传 outbox 最大尝试次数时由 start 循环收敛。
69
+ return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }))
70
+ })
71
+ void maxAttempts
72
+ outbox.start({ recover: true }).catch((error) => {
73
+ console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
74
+ })
75
+ return {
76
+ outbox,
77
+ stop() {
78
+ outbox.stop()
79
+ },
80
+ }
81
+ }
82
+
83
+ /** CLI 端收件人解析:ALLOWED_USERS 唯一项缺省生效;显式 user 必须命中名单(fail-closed)。 */
84
+ export function resolveNotifyRecipients(
85
+ configured: readonly string[],
86
+ explicit?: string,
87
+ ): string {
88
+ const users = [...configured]
89
+ if (explicit) return users.includes(explicit) ? explicit : ""
90
+ return users.length === 1 ? users[0] : ""
91
+ }
92
+
93
+ /** 默认 outbox 文件路径(CLI 与 bot 共用;env 已由 createOutbox 内处理,这里供 CLI dry-judge)。 */
94
+ export function defaultOutboxPath(): string {
95
+ return join(homedir(), ".openqq", "outbox.json")
96
+ }
@@ -122,7 +122,9 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
122
122
  pendingPermissions.delete(ctx.userId)
123
123
  savePendingPermMap(pendingPermissions)
124
124
  resolve("reject")
125
- void sendReply(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
125
+ // 2026-11-04 修复(DEF-qqbot-20261104-3):超时回执改走 safeDeliver——
126
+ // 原裸 sendReply 投递失败被 .catch 静默吞掉,用户收不到任何超时通知。
127
+ void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
126
128
  }
127
129
  }, PERM_PROMPT_TTL_MS)
128
130
 
@@ -16,7 +16,10 @@ import { isInstanceAlive } from "./core/instance-lock.js"
16
16
  import { resolveRuntime, buildLaunchPlan, spawnBotDetached, resolveBotEntry, readDotEnvField, botLogPath } from "./core/bot-launcher.js"
17
17
 
18
18
  const ENV_FILE = join(homedir(), ".openqq", ".env")
19
- const CHECK_INTERVAL_MS = 5 * 60 * 1000 // 看门狗巡检间隔(插件重载会重置,兜底是每小时 reload)
19
+ const CHECK_INTERVAL_MS = (() => {
20
+ const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000")
21
+ return Number.isFinite(n) && n > 0 ? n : 300_000
22
+ })() // 看门狗巡检间隔(env QQ_WATCHDOG_INTERVAL_MS 可调;插件重载会重置,兜底是每小时 reload)
20
23
 
21
24
  // —— 事件探针(2026-10-30 自 qqbot-event-probe.ts 并入,默认关)——
22
25
  // 原独立探针已完成 spike 取证使命(form/permission 事件流实证);保留为可选诊断:
package/src/qq/gateway.ts CHANGED
@@ -186,7 +186,7 @@ function briefAttachments(atts: MessageAttachment[]): unknown[] {
186
186
  } catch {
187
187
  /* 保留 ? */
188
188
  }
189
- return { host, content_type: a.content_type, size: a.size, filename: a.filename }
189
+ return { host, content_type: a.content_type, size: a.size, filename: a.filename, asr: a.asr_refer_text ? 1 : 0 }
190
190
  })
191
191
  }
192
192
 
package/src/qq/media.ts CHANGED
@@ -85,7 +85,11 @@ export async function downloadQQAttachment(
85
85
  ): Promise<AttachmentOutcome> {
86
86
  // 语音消息:优先用 QQ 内置 ASR 的 asr_refer_text(免费、零下载);无转写才按附件流程走
87
87
  const ctype = (att.content_type || "").toLowerCase()
88
- if (ctype.startsWith("audio/") && att.asr_refer_text?.trim()) {
88
+ // 2026-11-04 修复(UAT 实测 DEF-qqbot-20261104-1):QQ 语音附件 content_type
89
+ // 实测为 "voice"(非 audio/*),原 audio/ 前缀判断漏接 → 语音被误判为
90
+ //「暂不支持的附件类型」。asr 转写存在即优先消费,与具体 content_type 解耦。
91
+ const isVoice = ctype.startsWith("audio/") || ctype === "voice" || ctype === "amr" || ctype.endsWith("/amr")
92
+ if (isVoice && att.asr_refer_text?.trim()) {
89
93
  return { voice: att.asr_refer_text.trim() }
90
94
  }
91
95
  const ext = extForImageMime(att.content_type || "")