@linjz/opencode-qqbot 0.3.15 → 0.3.16

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.
Files changed (50) hide show
  1. package/README.md +42 -5
  2. package/bin/openqq.js +13 -0
  3. package/dist/notify-cli.js +28 -14
  4. package/dist/opencode-qqbot-plugin.js +934 -64
  5. package/dist/openqq-bot.js +3095 -677
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +8 -5
  9. package/src/bridge.ts +1310 -150
  10. package/src/cli/notify.ts +167 -158
  11. package/src/cli/openqq-main.ts +95 -0
  12. package/src/cli/service-main.ts +302 -0
  13. package/src/cli/watchdog-main.ts +77 -0
  14. package/src/commands.ts +644 -554
  15. package/src/config.ts +85 -0
  16. package/src/core/bot-control.ts +148 -0
  17. package/src/core/bot-launcher.ts +106 -13
  18. package/src/core/card-approval.ts +20 -9
  19. package/src/core/delivery.ts +145 -54
  20. package/src/core/discovery.ts +22 -4
  21. package/src/core/file-log.ts +35 -3
  22. package/src/core/form-bridge.ts +14 -5
  23. package/src/core/form-journal.ts +4 -4
  24. package/src/core/gateway-state.ts +3 -3
  25. package/src/core/inflight-journal.ts +214 -36
  26. package/src/core/instance-lock.ts +10 -2
  27. package/src/core/linkwatch.ts +3 -4
  28. package/src/core/markdown.ts +117 -0
  29. package/src/core/message-queue.ts +242 -91
  30. package/src/core/mirror.ts +222 -182
  31. package/src/core/notify-sink.ts +93 -96
  32. package/src/core/outbox.ts +10 -9
  33. package/src/core/permission.ts +627 -303
  34. package/src/core/question-form.ts +230 -0
  35. package/src/core/queue-view.ts +661 -0
  36. package/src/core/send-media.ts +32 -0
  37. package/src/core/storage.ts +34 -0
  38. package/src/core/watchdog.ts +513 -0
  39. package/src/core/zombie-reaper.ts +127 -0
  40. package/src/index.ts +140 -52
  41. package/src/opencode/client.ts +206 -27
  42. package/src/opencode/eventstream.ts +94 -12
  43. package/src/opencode/history.ts +4 -2
  44. package/src/opencode/mirror.ts +15 -2
  45. package/src/opencode/sessions.ts +135 -37
  46. package/src/plugin-entry.ts +120 -115
  47. package/src/qq/api.ts +165 -61
  48. package/src/qq/gateway.ts +79 -16
  49. package/src/qq/sender.ts +30 -18
  50. package/src/qq/types.ts +7 -0
@@ -1,303 +1,627 @@
1
- // @input: ../opencode/client, ../qq/types, fs/path/os
2
- // @output: createPermissionGate, parsePermissionDecision, formatPermissionPrompt, DECISION_LABELS, PERM_PROMPT_TTL_MS
3
- // @pos: 根层/core - 审批域(O7b 2026-10-15 自 bridge.ts 拆出:挂起槽、等待/
4
- // 裁决、跨重启恢复、自然语言决策解析、菜单格式化、中断态落盘)
5
- import { existsSync, readFileSync, writeFileSync } from "fs"
6
- import { join } from "path"
7
- import { homedir } from "os"
8
- import type { MessageContext } from "../qq/types.js"
9
- import type { OpencodeClient, PermissionDecision, PermissionRequest } from "../opencode/client.js"
10
- import { truncate } from "./util.js"
11
-
12
- // 用户级单槽:一次只有一个待审批请求在等该用户回复
13
- export interface PendingPermission {
14
- request: PermissionRequest
15
- mainSessionId: string // 审批发起时的主会话(子会话请求需要它做来源标注)
16
- resolve: (decision: PermissionDecision) => void
17
- timer: ReturnType<typeof setTimeout> | null
18
- ctx: MessageContext // O2:落盘快照,跨重启直答用
19
- createdAt: number // O2:TTL 基准(落盘与恢复共用)
20
- restored?: boolean // O2:启动恢复条目(无活 waiter,走直连 reply)
21
- }
22
-
23
- export const PERM_PROMPT_TTL_MS = 30 * 60 * 1000
24
-
25
- export const DECISION_LABELS: Record<PermissionDecision, string> = {
26
- once: "允许(本次)",
27
- always: "总是允许(已存入项目白名单)",
28
- reject: "拒绝",
29
- }
30
-
31
- // O2(2026-10-15,P2-4a):审批中断态落盘——重启前挂起的审批重启后仍可
32
- // 处置(直连 reply 或明确回执),不再出现"回复允许灌进会话当普通消息"的
33
- // 误导路径。与 greeted/watch.json 同款风格(损坏即空)。
34
- const PENDING_PERM_FILE = join(homedir(), ".openqq", "pending-permissions.json")
35
-
36
- type PersistedPermission = {
37
- request: PermissionRequest
38
- mainSessionId: string
39
- createdAt: number
40
- ctx: MessageContext
41
- }
42
-
43
- function loadPendingPermMap(): Record<string, PersistedPermission> {
44
- try {
45
- if (existsSync(PENDING_PERM_FILE)) {
46
- const raw = readFileSync(PENDING_PERM_FILE, "utf-8")
47
- const obj = JSON.parse(raw)
48
- if (obj && typeof obj === "object" && !Array.isArray(obj)) {
49
- const out: Record<string, PersistedPermission> = {}
50
- for (const [k, v] of Object.entries(obj)) {
51
- const e = v as PersistedPermission
52
- if (e && e.request?.id && e.ctx?.userId && typeof e.createdAt === "number") out[k] = e
53
- }
54
- return out
55
- }
56
- }
57
- } catch {
58
- // 损坏即空
59
- }
60
- return {}
61
- }
62
-
63
- function savePendingPermMap(m: ReadonlyMap<string, PendingPermission>): void {
64
- try {
65
- const out: Record<string, PersistedPermission> = {}
66
- for (const [uid, e] of m) {
67
- if (!e.ctx) continue
68
- out[uid] = { request: e.request, mainSessionId: e.mainSessionId, createdAt: e.createdAt, ctx: e.ctx }
69
- }
70
- writeFileSync(PENDING_PERM_FILE, JSON.stringify(out))
71
- } catch (error) {
72
- console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error)
73
- }
74
- }
75
-
76
- export interface PermissionGateDeps {
77
- client: OpencodeClient
78
- sendReply: (ctx: MessageContext, text: string) => Promise<void>
79
- safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
80
- /** A 项(2026-10-29):卡片按钮审批发送通道;返回 false 时本域自动降级文字菜单 */
81
- sendApprovalPrompt?: (ctx: MessageContext, request: PermissionRequest, mainSessionId: string) => Promise<boolean>
82
- }
83
-
84
- export interface PermissionGate {
85
- hasPending: (userId: string) => boolean
86
- getPending: (userId: string) => PendingPermission | undefined
87
- waitForDecision: (
88
- ctx: MessageContext,
89
- request: PermissionRequest,
90
- mainSessionId: string,
91
- ) => Promise<PermissionDecision>
92
- resolve: (userId: string, decision: PermissionDecision) => void
93
- restore: () => void
94
- // L 项(2026-10-30):常驻监听器发现的外部审批(如桌面端回合发起)——注册
95
- // "无活 waiter"槽(restored 语义:裁决走直连 reply),推卡片/文字菜单
96
- pushExternal: (userId: string, ctx: MessageContext, request: PermissionRequest, mainSessionId: string) => void
97
- }
98
-
99
- // 审批域门面:挂起槽 + 等待/裁决 + 跨重启恢复。所有状态与文件读写收在本域。
100
- export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
101
- const { client, sendReply, safeDeliver } = deps
102
- const pendingPermissions = new Map<string, PendingPermission>()
103
-
104
- function hasPending(userId: string): boolean {
105
- return pendingPermissions.has(userId)
106
- }
107
-
108
- function getPending(userId: string): PendingPermission | undefined {
109
- return pendingPermissions.get(userId)
110
- }
111
-
112
- // promptAndWait 的 onPermission 回调:推 QQ 审批菜单,挂起等待用户回复。
113
- // 只有 用户回复 或 30 分钟 TTL 会 resolve —— 后者自动拒绝,避免永久挂起。
114
- function waitForDecision(
115
- ctx: MessageContext,
116
- request: PermissionRequest,
117
- mainSessionId: string,
118
- ): Promise<PermissionDecision> {
119
- return new Promise<PermissionDecision>((resolve) => {
120
- const timer = setTimeout(() => {
121
- if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
122
- pendingPermissions.delete(ctx.userId)
123
- savePendingPermMap(pendingPermissions)
124
- resolve("reject")
125
- // 2026-11-04 修复(DEF-qqbot-20261104-3):超时回执改走 safeDeliver——
126
- // 原裸 sendReply 投递失败被 .catch 静默吞掉,用户收不到任何超时通知。
127
- void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
128
- }
129
- }, PERM_PROMPT_TTL_MS)
130
-
131
- pendingPermissions.set(ctx.userId, {
132
- request,
133
- mainSessionId,
134
- resolve,
135
- timer,
136
- ctx,
137
- createdAt: Date.now(),
138
- })
139
- savePendingPermMap(pendingPermissions) // O2:落盘,重启不丢
140
- // A 项(2026-10-29):卡片按钮优先,发送失败降级文字菜单;两者都失败
141
- // 不 reject promise(用户仍可能稍后主动回复)
142
- void (async () => {
143
- const sentByCard = deps.sendApprovalPrompt
144
- ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
145
- : false
146
- if (!sentByCard) {
147
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
148
- console.error("[bridge] 发送审批请求失败:", error)
149
- })
150
- }
151
- })()
152
- })
153
- }
154
-
155
- function resolve(userId: string, decision: PermissionDecision): void {
156
- const entry = pendingPermissions.get(userId)
157
- if (!entry) return
158
- if (entry.timer) clearTimeout(entry.timer)
159
- pendingPermissions.delete(userId)
160
- savePendingPermMap(pendingPermissions)
161
- if (entry.restored) {
162
- // O2(P2-4a):跨重启——原 waiter 已随进程消失,直连 POST reply 争取
163
- // 原位生效;会话已不在等待则明确回执"重新发起",绝不灌会话当普通消息
164
- void (async () => {
165
- const label = decision === "always" ? "总是允许" : decision === "once" ? "允许" : "拒绝"
166
- try {
167
- await client.permission.reply({
168
- path: { sessionID: entry.request.sessionID, requestID: entry.request.id },
169
- body: { decision },
170
- })
171
- await safeDeliver(entry.ctx, `✅ 审批已跨重启完成(${label}),原会话已继续`)
172
- } catch {
173
- await safeDeliver(entry.ctx, "⚠️ 审批未能跨重启完成(原请求可能已失效),请重新发起原操作")
174
- }
175
- })()
176
- return
177
- }
178
- entry.resolve(decision)
179
- }
180
-
181
- // O2(P2-4a):恢复重启前挂起的审批(30min TTL 内有效);恢复条目超时则
182
- // 直连 reject 解阻塞会话(原 waiter 已不存在,无人代答)
183
- function restore(): void {
184
- const saved = loadPendingPermMap()
185
- for (const [uid, e] of Object.entries(saved)) {
186
- const left = PERM_PROMPT_TTL_MS - (Date.now() - e.createdAt)
187
- if (left <= 0) continue
188
- const timer = setTimeout(() => {
189
- if (pendingPermissions.get(uid)?.request.id === e.request.id) {
190
- pendingPermissions.delete(uid)
191
- savePendingPermMap(pendingPermissions)
192
- void client.permission
193
- .reply({
194
- path: { sessionID: e.request.sessionID, requestID: e.request.id },
195
- body: { decision: "reject" },
196
- })
197
- .catch(() => {})
198
- void safeDeliver(e.ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
199
- }
200
- }, left)
201
- pendingPermissions.set(uid, {
202
- request: e.request,
203
- mainSessionId: e.mainSessionId,
204
- resolve: () => {},
205
- timer,
206
- ctx: e.ctx,
207
- createdAt: e.createdAt,
208
- restored: true,
209
- })
210
- console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`)
211
- }
212
- }
213
-
214
- // L 项(2026-10-30):常驻交互监听器发现外部审批时的注册入口。与 restore() 同款
215
- // "无活 waiter"槽:用户在 QQ 裁决后 resolve() 走直连 POST reply(restored 路径),
216
- // 并回执"已从 QQ 批准"。同 request.id 已在挂起则去重。
217
- function pushExternalImpl(
218
- userId: string,
219
- ctx: MessageContext,
220
- request: PermissionRequest,
221
- mainSessionId: string,
222
- ): void {
223
- if (pendingPermissions.get(userId)?.request.id === request.id) return
224
- // 单一挂起槽:新审批取代旧槽
225
- const prev = pendingPermissions.get(userId)
226
- if (prev?.timer) clearTimeout(prev.timer)
227
-
228
- const timer = setTimeout(() => {
229
- if (pendingPermissions.get(userId)?.request.id !== request.id) return
230
- pendingPermissions.delete(userId)
231
- savePendingPermMap(pendingPermissions)
232
- void client.permission
233
- .reply({ path: { sessionID: request.sessionID, requestID: request.id }, body: { decision: "reject" } })
234
- .catch(() => {})
235
- void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
236
- }, PERM_PROMPT_TTL_MS)
237
-
238
- pendingPermissions.set(userId, {
239
- request,
240
- mainSessionId,
241
- resolve: () => {},
242
- timer,
243
- ctx,
244
- createdAt: Date.now(),
245
- restored: true,
246
- })
247
- savePendingPermMap(pendingPermissions)
248
- console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action}`)
249
- // 推送失败不撤槽(用户仍可能文字裁决)
250
- void (async () => {
251
- const sentByCard = deps.sendApprovalPrompt
252
- ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
253
- : false
254
- if (!sentByCard) {
255
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
256
- console.error("[bridge] 发送审批请求失败:", error)
257
- })
258
- }
259
- })()
260
- }
261
-
262
- return { hasPending, getPending, waitForDecision, resolve, restore, pushExternal: pushExternalImpl }
263
- }
264
-
265
- // 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
266
- // 优先级:绝对否定 > 总是 > 允许。
267
- // 安全方向性:审批场景下误判的代价不对称 —— 误拒只需重试,误放行会执行
268
- // 危险命令。所以否定词最优先,且「不X」前缀词(不同意/不允许/不要/别)
269
- // 必须盖住「X」(同意/允许)与「总是」(总是不允许 ≠ 总是允许)。
270
- export function parsePermissionDecision(content: string): PermissionDecision | null {
271
- const t = content
272
- .trim()
273
- .toLowerCase()
274
- .replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1")
275
- if (!t) return null
276
- // 债务D5:混合否定增强——"不ok/不太行/否决/驳回/不可以"等一律 reject。
277
- // 方向性不变:否定最优先,歧义一律倒向拒绝(误拒可重试,误放行是事故)。
278
- if (
279
- /\b(deny|reject|no|nope|nah)\b|拒绝|否决|驳回|不准|不给|^否$|别|不要|不\s*(同意|允许|批准|许可|行|ok|okay|可以)|不(太|怎么|太特么)\s*(行|ok|okay|可以)/.test(t)
280
- )
281
- return "reject"
282
- if (/\balways\b|总是(?!不)|永久/.test(t)) return "always"
283
- if (/\b(allow|approve|yes|ok|y)\b|允许|同意|批准/.test(t)) return "once"
284
- return null
285
- }
286
-
287
- export function formatPermissionPrompt(request: PermissionRequest, mainSessionId?: string): string {
288
- const lines = ["🔐 需要权限审批", `动作:${request.action || "(未知)"}`]
289
- // 债务D1:子会话(subagent)发起的审批要标注来源,用户知道批的是谁
290
- if (mainSessionId && request.sessionID && request.sessionID !== mainSessionId) {
291
- lines.push(`来源:子会话 ${request.sessionID}(subagent 发起)`)
292
- }
293
- const resources = (request.resources ?? []).slice(0, 5)
294
- if (resources.length > 0) {
295
- lines.push("资源:")
296
- for (const r of resources) lines.push(` ${truncate(r, 300)}`)
297
- }
298
- if (request.message) lines.push(`说明:${truncate(request.message, 300)}`)
299
- lines.push("")
300
- lines.push("回复「允许」= 仅本次|「总是」= 保存为项目级白名单(后续同类命令永久放行)|「拒绝」= 驳回(含本会话其他待审)")
301
- lines.push("(30 分钟无响应自动拒绝,也可用 /allow /always /deny)")
302
- return lines.join("\n")
303
- }
1
+ // @input: ../opencode/client, ../qq/types, fs/path/os
2
+ // @output: createPermissionGate, parsePermissionDecision, formatPermissionPrompt, DECISION_LABELS,
3
+ // PERM_PROMPT_TTL_MS, PERM_NUDGE_MS, createPushGate(弹卡延迟闸),
4
+ // classifyApprovalReplyError, formatPermissionConflictNotice(纯函数供测试), ApprovalReplyFailure
5
+ // @pos: 根层/core - 审批域(O7b 2026-10-15 自 bridge.ts 拆出:挂起槽、等待/
6
+ // 裁决、跨重启恢复、自然语言决策解析、菜单格式化、中断态落盘)
7
+ //
8
+ // ★ 链路契约(2026-11-17 owner 批注固化——改动本文件前必读):
9
+ // 引擎对【所有连接客户端】SSE 广播 permission.asked(桌面端弹原生窗,bot 走本域);
10
+ // 全生命周期四不变量:①挂起槽 per-userId 单槽,跨角色/跨用户物理隔离
11
+ // (pending-permissions.json 按 roles/<appId>/ 分桶,多角色改造后不得回退共享);
12
+ // ②轮询/裁决必带会话项目目录头(DEF-qqbot-20261112-1:x-opencode-directory 快照于建槽,
13
+ // 裸查/裸 reply=404 失明);③裁决先 ACK 引擎 deferred 再清槽(reject=DeclinedError 自释放);
14
+ // ④桌面端先决时 QQ 侧自动关槽(clearIfResolved,双向同步不双发)。
15
+ // 失效模式锚点:11-13 DEF-20261113-P1(引擎 fail-open 不发 ask=本域无事件可收,
16
+ // 非本域缺陷);11-17 20:17 实测全生命周期 ✅(Remove-Item 触发→卡→QQ 裁决→回验)。
17
+ // 双实证日:2026-11-17(17:29 桌面源裁决同步 / 20:17 QQ 源全生命周期)。
18
+ import { storageFile } from "./storage.js"
19
+ import { existsSync, readFileSync, writeFileSync } from "fs"
20
+ import type { MessageContext } from "../qq/types.js"
21
+ import type { OpencodeClient, PermissionDecision, PermissionRequest } from "../opencode/client.js"
22
+ import { truncate } from "./util.js"
23
+
24
+ // 用户级单槽:一次只有一个待审批请求在等该用户回复
25
+ export interface PendingPermission {
26
+ request: PermissionRequest
27
+ mainSessionId: string // 审批发起时的主会话(子会话请求需要它做来源标注)
28
+ resolve: (decision: PermissionDecision) => void
29
+ timer: ReturnType<typeof setTimeout> | null
30
+ /** design §3.6 保险网:10min 无裁决告警计时器(裁决/TTL/清槽即取消;只报一次) */
31
+ alertTimer?: ReturnType<typeof setTimeout> | null
32
+ ctx: MessageContext // O2:落盘快照,跨重启直答用
33
+ createdAt: number // O2:TTL 基准(落盘与恢复共用)
34
+ restored?: boolean // O2:无活 waiter 槽(裁决走直连 reply)——restore() 与 pushExternal() 都会置位
35
+ /** DEF-qqbot-20261110-7:真跨重启恢复标记,仅 restore() 置位。
36
+ * restored 表达的是"无活 waiter、裁决走直连 reply"的行为语义,实时推送(pushExternal)
37
+ * 同样置位;但实时审批的卡片/文字菜单在点击后已有选择回显,再补一条"跨重启"回执
38
+ * 属误报,只在从磁盘恢复的条目上投递。 */
39
+ resumedFromDisk?: boolean
40
+ origin?: PermOrigin // 2026-11-09:回合归属标注——bot=机器人回合,external=桌面端发起(镜像推送)
41
+ /** DEF-qqbot-20261112-1:裁决 reply 的 x-opencode-directory 值(建槽时快照;
42
+ * 引擎待审批按 location 实例分仓,裁决/超时拒答不带目录会对项目会话 404) */
43
+ directory?: string
44
+ }
45
+
46
+ /** 审批发起来源(卡片/文字菜单标注 + 联动清槽决策用) */
47
+ export type PermOrigin = "bot" | "external"
48
+
49
+ export const PERM_PROMPT_TTL_MS = 30 * 60 * 1000
50
+
51
+ /** design §3.6 权限保险网:挂起 10 分钟仍无裁决则告警提醒(TTL 30min 自动拒前的兜底) */
52
+ export const PERM_NUDGE_MS = 10 * 60 * 1000
53
+
54
+ /**
55
+ * 弹卡延迟闸(owner 2026-11-10 拍板):SSE permission.asked 到达后不立即推 QQ 卡,
56
+ * 延迟 deferMs 判定——桌面端 autoApprove 实测 20~500ms 内秒回 once,窗口内被处置的
57
+ * ask 不再推卡(与桌面「静默放行不打扰」表现一致);超时仍悬置才推。
58
+ * cancel 按 requestID 撤定时器(replied 事件到达即弃推);schedule 同键去重。
59
+ */
60
+ export interface PushGate {
61
+ schedule: (userId: string, requestID: string, run: () => void) => void
62
+ /** 按 requestID 撤掉所有待决 schedule(不关心 uid) */
63
+ cancel: (requestID: string) => void
64
+ dispose: () => void
65
+ }
66
+
67
+ export function createPushGate(deferMs: number): PushGate {
68
+ const timers = new Map<string, ReturnType<typeof setTimeout>>()
69
+
70
+ return {
71
+ schedule(userId, requestID, run) {
72
+ const key = `${userId}\u0000${requestID}`
73
+ if (timers.has(key)) return
74
+ const timer = setTimeout(() => {
75
+ timers.delete(key)
76
+ run()
77
+ }, deferMs)
78
+ timer.unref?.()
79
+ timers.set(key, timer)
80
+ },
81
+ cancel(requestID) {
82
+ for (const [key, timer] of timers) {
83
+ if (key.endsWith(`\u0000${requestID}`)) {
84
+ clearTimeout(timer)
85
+ timers.delete(key)
86
+ }
87
+ }
88
+ },
89
+ dispose() {
90
+ for (const timer of timers.values()) clearTimeout(timer)
91
+ timers.clear()
92
+ },
93
+ }
94
+ }
95
+
96
+ /** QQ_PERM_DEFER_MS 解析(owner 拍板默认 500ms):空值/非法回退默认——
97
+ * 注意 Number("")===0,必须先判空再 Number(2026-11-10 回归实证默认值曾因此失效为 0)。 */
98
+ export function resolvePermDeferMs(envValue: string | undefined): number {
99
+ if (envValue === undefined || envValue.trim() === "") return 500
100
+ const n = Number(envValue)
101
+ return Number.isFinite(n) && n >= 0 && n <= 10_000 ? n : 500
102
+ }
103
+
104
+ export const DECISION_LABELS: Record<PermissionDecision, string> = {
105
+ once: "允许(本次)",
106
+ always: "总是允许(已存入项目白名单)",
107
+ reject: "拒绝",
108
+ }
109
+
110
+ /**
111
+ * 拒绝裁决遇到「他端已处理(404)」时的用户告警(纯函数,供单测)。
112
+ * 2026-11-07 DEF-qqbot-20261107-1:引擎 ask fail-open 下,用户点「拒绝」时
113
+ * 操作可能已被服务端先行放行并执行。此时静默继续=用户误以为已阻断,
114
+ * 必须给出明确告警;允许类冲突仍走 10 分钟保险网,不在此处噪音。
115
+ */
116
+ export function formatPermissionConflictNotice(decision: PermissionDecision): string | null {
117
+ if (decision !== "reject") return null
118
+ return "⚠️ 已收到「拒绝」,但服务端在该裁决前已放行此操作(引擎 ask fail-open),命令可能已执行。本条结果请勿视为已授权;若为破坏性命令请立即核对现场。"
119
+ }
120
+
121
+ /**
122
+ * 跨重启审批转发失败的分类(纯函数,供单测)。
123
+ * - expired:404/410——请求已不在服务端(等待超时已被自动拒绝/已裁决),
124
+ * 用户点的是"重启后恢复的过期副本",重试无意义,只能重新发起原操作;
125
+ * - transient:网络错误/5xx 等——可能只是服务端暂时不可达,可稍后重试。
126
+ * 错误形状来自 opencode/client.ts 的 `OpenCode API {status}: {excerpt}`。
127
+ */
128
+ export type ApprovalReplyFailure = "expired" | "transient"
129
+ export function classifyApprovalReplyError(error: unknown): ApprovalReplyFailure {
130
+ const msg = error instanceof Error ? error.message : String(error)
131
+ return /\bAPI\s+(404|410)\b/.test(msg) ? "expired" : "transient"
132
+ }
133
+
134
+ // O2(2026-10-15,P2-4a):审批中断态落盘——重启前挂起的审批重启后仍可
135
+ // 处置(直连 reply 或明确回执),不再出现"回复允许灌进会话当普通消息"的
136
+ // 误导路径。与 greeted/watch.json 同款风格(损坏即空)。
137
+ const PENDING_PERM_FILE = storageFile("pending-permissions.json")
138
+
139
+ export type PersistedPermission = {
140
+ request: PermissionRequest
141
+ mainSessionId: string
142
+ createdAt: number
143
+ ctx: MessageContext
144
+ origin?: PermOrigin
145
+ }
146
+
147
+ function loadPendingPermMap(file: string = PENDING_PERM_FILE): Record<string, PersistedPermission> {
148
+ try {
149
+ if (existsSync(file)) {
150
+ const raw = readFileSync(file, "utf-8")
151
+ const obj = JSON.parse(raw)
152
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) {
153
+ const out: Record<string, PersistedPermission> = {}
154
+ for (const [k, v] of Object.entries(obj)) {
155
+ const e = v as PersistedPermission
156
+ if (e && e.request?.id && e.ctx?.userId && typeof e.createdAt === "number") out[k] = e
157
+ }
158
+ return out
159
+ }
160
+ }
161
+ } catch {
162
+ // 损坏即空
163
+ }
164
+ return {}
165
+ }
166
+
167
+ function savePendingPermMap(m: ReadonlyMap<string, PendingPermission>, file: string = PENDING_PERM_FILE): void {
168
+ try {
169
+ const out: Record<string, PersistedPermission> = {}
170
+ for (const [uid, e] of m) {
171
+ if (!e.ctx) continue
172
+ out[uid] = {
173
+ request: e.request,
174
+ mainSessionId: e.mainSessionId,
175
+ createdAt: e.createdAt,
176
+ ctx: e.ctx,
177
+ ...(e.origin ? { origin: e.origin } : {}),
178
+ }
179
+ }
180
+ writeFileSync(file, JSON.stringify(out))
181
+ } catch (error) {
182
+ console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error)
183
+ }
184
+ }
185
+
186
+ export interface PermissionGateDeps {
187
+ client: OpencodeClient
188
+ sendReply: (ctx: MessageContext, text: string) => Promise<void>
189
+ safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
190
+ /** A 项(2026-10-29):卡片按钮审批发送通道;返回 false 时本域自动降级文字菜单 */
191
+ sendApprovalPrompt?: (
192
+ ctx: MessageContext,
193
+ request: PermissionRequest,
194
+ mainSessionId: string,
195
+ origin?: PermOrigin,
196
+ ) => Promise<boolean>
197
+ /** 槽位清空的唤醒钩子(用户裁决/TTL 自动拒绝均触发):审批挂起期间 drainQueue 被守卫
198
+ * 挡回,裁决后须由调用方重新放行队列——否则挂起期间入队的消息要等用户再发一条才动
199
+ * (2026-11-05 举一反三:permission 域的"终态无人唤醒"漏洞)。 */
200
+ onDecision?: (userId: string) => void
201
+ /** 10min 无裁决告警间隔(测试注入小值;缺省 PERM_NUDGE_MS) */
202
+ nudgeMs?: number
203
+ /** 跨重启恢复读盘入口(测试注入;缺省读 legacy 全局 pending-permissions.json) */
204
+ loadPending?: () => Record<string, PersistedPermission>
205
+ /** 多角色:落盘文件(缺省 legacy 全局 pending-permissions.json) */
206
+ persistFile?: string
207
+ /** DEF-qqbot-20261112-1:按用户查会话项目目录——裁决/超时拒答 reply 的
208
+ * x-opencode-directory(引擎待审按 location 实例分仓;bridge 注入 sessions 映射) */
209
+ directoryOf?: (userId: string) => string | undefined
210
+ }
211
+
212
+ export interface PermissionGate {
213
+ hasPending: (userId: string) => boolean
214
+ getPending: (userId: string) => PendingPermission | undefined
215
+ waitForDecision: (
216
+ ctx: MessageContext,
217
+ request: PermissionRequest,
218
+ mainSessionId: string,
219
+ ) => Promise<PermissionDecision>
220
+ resolve: (userId: string, decision: PermissionDecision) => void
221
+ restore: () => void
222
+ // L 项(2026-10-30):常驻监听器发现的外部审批(如桌面端回合发起)——注册
223
+ // "无活 waiter"槽(restored 语义:裁决走直连 reply),推卡片/文字菜单
224
+ pushExternal: (userId: string, ctx: MessageContext, request: PermissionRequest, mainSessionId: string, origin?: PermOrigin) => void
225
+ /** 联动清槽(2026-11-09):SSE permission.replied={sessionID,requestID,reply} 到达时,
226
+ * 若该 requestID 在挂起槽中(无论来源 bot/external),清槽 + QQ 回执「源头已处理」,
227
+ * 并唤醒队列。返回 true=确有槽被清。无匹配槽返回 false(正常:QQ 已先裁决)。 */
228
+ clearIfResolved: (sessionID: string | undefined, requestID: string, reply: unknown) => boolean
229
+ }
230
+
231
+ // 审批域门面:挂起槽 + 等待/裁决 + 跨重启恢复。所有状态与文件读写收在本域。
232
+ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
233
+ // 多角色(2026-11-17):审批态落盘文件可按角色注入;缺省 legacy 全局路径
234
+ const PERSIST_FILE = deps.persistFile ?? PENDING_PERM_FILE
235
+ const { client, sendReply, safeDeliver } = deps
236
+ const pendingPermissions = new Map<string, PendingPermission>()
237
+ // DEF-qqbot-20261112-5(2026-11-12 ZERO4 实测卡风暴实证):同一回合并联发起多个
238
+ // ask(异 request id)时,单挂槽跨请求覆写 + 双推送路径竞态会让先到的请求被重复
239
+ // 推卡(A 卡×2/B 卡×1 实证)。已推卡请求 id 环:同步认领(check+mark 原子,闭掉
240
+ // 双路径并发 race),推过的请求绝不再推。进程内有效——跨重启 restore 的重推送是
241
+ // 有意重通知(新进程集合自然为空),不受影响。
242
+ const pushedCardIds = new Set<string>()
243
+ function claimCardPush(requestId: string): boolean {
244
+ if (pushedCardIds.has(requestId)) return false
245
+ if (pushedCardIds.size >= 500) pushedCardIds.delete(pushedCardIds.values().next().value as string)
246
+ pushedCardIds.add(requestId)
247
+ return true
248
+ }
249
+
250
+ function hasPending(userId: string): boolean {
251
+ return pendingPermissions.has(userId)
252
+ }
253
+
254
+ function getPending(userId: string): PendingPermission | undefined {
255
+ return pendingPermissions.get(userId)
256
+ }
257
+
258
+ // design §3.6 权限保险网:10min 无裁决告警。只报一次(计时器随建槽设置、
259
+ // 随裁决/TTL/清槽取消);到点时槽位仍属于同一请求才发,防误报旧请求。
260
+ function startNudgeTimer(userId: string, requestId: string, ctx: MessageContext): ReturnType<typeof setTimeout> {
261
+ const t = setTimeout(() => {
262
+ if (pendingPermissions.get(userId)?.request.id !== requestId) return
263
+ console.log(`[perm] 10min 无裁决告警 user=${userId.slice(0, 8)}… request=${requestId}`)
264
+ void safeDeliver(
265
+ ctx,
266
+ "⏳ 一条审批已等待 10 分钟未裁决,30 分钟到期将自动拒绝。如需继续请尽快裁决(允许/总是/拒绝)。",
267
+ ).catch(() => {})
268
+ }, deps.nudgeMs ?? PERM_NUDGE_MS)
269
+ t.unref?.()
270
+ return t
271
+ }
272
+
273
+ function clearTimers(entry: PendingPermission): void {
274
+ if (entry.timer) clearTimeout(entry.timer)
275
+ if (entry.alertTimer) clearTimeout(entry.alertTimer)
276
+ }
277
+
278
+ // promptAndWait 的 onPermission 回调:推 QQ 审批菜单,挂起等待用户回复。
279
+ // 只有 用户回复 或 30 分钟 TTL 会 resolve —— 后者自动拒绝,避免永久挂起。
280
+ function waitForDecision(
281
+ ctx: MessageContext,
282
+ request: PermissionRequest,
283
+ mainSessionId: string,
284
+ ): Promise<PermissionDecision> {
285
+ return new Promise<PermissionDecision>((resolve) => {
286
+ // DEF-qqbot-20261112-3(2026-11-12 ZERO3 实测双卡实证):SSE 即时推送路径
287
+ // (flushPermPush→pushExternal)可能已为同一请求建槽推卡——promptAndWait 轮询
288
+ // 路径随后发现同请求再进 waitForDecision 时,必须收养既有槽(换真 resolver、
289
+ // 刷 TTL、清 restored),绝不再推第二张卡。修复前轮询失明掩盖了该竞态。
290
+ const existing = pendingPermissions.get(ctx.userId)
291
+ if (existing && existing.request.id === request.id) {
292
+ clearTimers(existing)
293
+ const adopted: PendingPermission = {
294
+ ...existing,
295
+ resolve,
296
+ mainSessionId,
297
+ ctx,
298
+ createdAt: Date.now(),
299
+ restored: false, // 收养后裁决走 entry.resolve(真 waiter),非直连 reply
300
+ directory: deps.directoryOf?.(ctx.userId),
301
+ origin: "bot",
302
+ }
303
+ adopted.alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
304
+ adopted.timer = setTimeout(() => {
305
+ if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
306
+ pendingPermissions.delete(ctx.userId)
307
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
308
+ deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
309
+ resolve("reject")
310
+ void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
311
+ }
312
+ }, PERM_PROMPT_TTL_MS)
313
+ adopted.timer.unref?.()
314
+ pendingPermissions.set(ctx.userId, adopted)
315
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
316
+ console.log(`[perm] 同请求收养既有审批槽(不重复推卡)user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
317
+ return
318
+ }
319
+ const createdAt = Date.now()
320
+ // DEF-qqbot-20261110-3(P2,2026-11-10 实战实证):覆写单一槽前必须先清旧槽
321
+ // 计时器——SSE pushExternal 先建的 external 槽被本 waiter 覆写后,其 TTL/告警
322
+ // 计时器仍按同 request.id 挂表,30min 到点会误删新 waiter 槽、把正在等的
323
+ // 回合自动拒绝(旧 restored 槽 resolve 为 noop,无需代答)。
324
+ const stale = pendingPermissions.get(ctx.userId)
325
+ if (stale) clearTimers(stale)
326
+ const alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
327
+ const timer = setTimeout(() => {
328
+ if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
329
+ pendingPermissions.delete(ctx.userId)
330
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
331
+ deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
332
+ resolve("reject")
333
+ // 2026-11-04 修复(DEF-qqbot-20261104-3):超时回执改走 safeDeliver——
334
+ // 原裸 sendReply 投递失败被 .catch 静默吞掉,用户收不到任何超时通知。
335
+ void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
336
+ }
337
+ }, PERM_PROMPT_TTL_MS)
338
+ timer.unref?.() // 不阻塞进程退出(测试链收尾;生产为长驻进程无影响)
339
+
340
+ pendingPermissions.set(ctx.userId, {
341
+ request,
342
+ mainSessionId,
343
+ resolve,
344
+ timer,
345
+ alertTimer,
346
+ ctx,
347
+ createdAt,
348
+ origin: "bot", // 机器人自己回合的权限(bridge onPermission 直答路径)
349
+ directory: deps.directoryOf?.(ctx.userId),
350
+ })
351
+ savePendingPermMap(pendingPermissions, PERSIST_FILE) // O2:落盘,重启不丢
352
+ // A 项(2026-10-29):卡片按钮优先,发送失败降级文字菜单;两者都失败
353
+ // 不 reject promise(用户仍可能稍后主动回复)。DEF-5:同步认领制——已推过
354
+ // 的请求(并发异请求覆写场景被其他路径推过)不再重复推卡。
355
+ if (claimCardPush(request.id)) {
356
+ void (async () => {
357
+ const sentByCard = deps.sendApprovalPrompt
358
+ ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot").catch(() => false)
359
+ : false
360
+ if (!sentByCard) {
361
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot")).catch((error) => {
362
+ console.error("[bridge] 发送审批请求失败:", error)
363
+ })
364
+ }
365
+ })()
366
+ }
367
+ })
368
+ }
369
+
370
+ function resolve(userId: string, decision: PermissionDecision): void {
371
+ const entry = pendingPermissions.get(userId)
372
+ if (!entry) return
373
+ clearTimers(entry)
374
+ pendingPermissions.delete(userId)
375
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
376
+ deps.onDecision?.(userId) // 裁决即唤醒队列(drainQueue 的 pendingPerm 守卫此刻已放行)
377
+ if (entry.restored) {
378
+ // O2(P2-4a):跨重启——原 waiter 已随进程消失,直连 POST reply 争取
379
+ // 原位生效;会话已不在等待则明确回执"重新发起",绝不灌会话当普通消息
380
+ void (async () => {
381
+ const label = decision === "always" ? "总是允许" : decision === "once" ? "允许" : "拒绝"
382
+ try {
383
+ await client.permission.reply({
384
+ path: { sessionID: entry.request.sessionID, requestID: entry.request.id },
385
+ body: { decision },
386
+ directory: entry.directory,
387
+ })
388
+ // DEF-qqbot-20261110-7:只有真跨重启恢复的条目才补回执。实时推送
389
+ // (pushExternal)的审批在 QQ 点击后卡片/菜单本身已有选择回显,
390
+ // 再发"已跨重启完成"既是误报也会重复刷屏。
391
+ if (entry.resumedFromDisk) {
392
+ await safeDeliver(entry.ctx, `✅ 审批已跨重启完成(${label}),原会话已继续`)
393
+ } else {
394
+ console.log(
395
+ `[perm] 实时审批已裁决 user=${userId.slice(0, 8)}… request=${entry.request.id} decision=${decision}`,
396
+ )
397
+ }
398
+ } catch (error) {
399
+ // 2026-11-05 用户拍板:失败按类型区分文案——过期副本(点的是旧卡片)明确说
400
+ // "重新发起",服务异常才说"稍后重试",不再一句"可能已失效"糊在一起。
401
+ if (classifyApprovalReplyError(error) === "expired") {
402
+ await safeDeliver(
403
+ entry.ctx,
404
+ "⚠️ 审批等待超时:服务端已自动拒绝。请重新发起原操作,新审批会正常生效",
405
+ )
406
+ } else {
407
+ await safeDeliver(
408
+ entry.ctx,
409
+ `⚠️ 审批转发失败(${error instanceof Error ? error.message : String(error)}),请稍后重试;若仍未生效请重新发起原操作`,
410
+ )
411
+ }
412
+ }
413
+ })()
414
+ return
415
+ }
416
+ entry.resolve(decision)
417
+ }
418
+
419
+ // O2(P2-4a):恢复重启前挂起的审批(30min TTL 内有效);恢复条目超时则
420
+ // 直连 reject 解阻塞会话(原 waiter 已不存在,无人代答)
421
+ function restore(): void {
422
+ const saved = (deps.loadPending ?? loadPendingPermMap)()
423
+ for (const [uid, e] of Object.entries(saved)) {
424
+ const left = PERM_PROMPT_TTL_MS - (Date.now() - e.createdAt)
425
+ if (left <= 0) continue
426
+ // 保险网告警按 createdAt 对齐:恢复时若 10min 点已过则不再补报
427
+ const nudgeLeft = PERM_NUDGE_MS - (Date.now() - e.createdAt)
428
+ const alertTimer = nudgeLeft > 0 ? startNudgeTimer(uid, e.request.id, e.ctx) : null
429
+ const timer = setTimeout(() => {
430
+ if (pendingPermissions.get(uid)?.request.id === e.request.id) {
431
+ pendingPermissions.delete(uid)
432
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
433
+ void client.permission
434
+ .reply({
435
+ path: { sessionID: e.request.sessionID, requestID: e.request.id },
436
+ body: { decision: "reject" },
437
+ directory: deps.directoryOf?.(uid),
438
+ })
439
+ .catch(() => {})
440
+ void safeDeliver(e.ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
441
+ deps.onDecision?.(uid) // 恢复槽 TTL 拒绝也要唤醒队列
442
+ }
443
+ }, left)
444
+ timer.unref?.()
445
+ pendingPermissions.set(uid, {
446
+ request: e.request,
447
+ mainSessionId: e.mainSessionId,
448
+ resolve: () => {},
449
+ timer,
450
+ alertTimer,
451
+ ctx: e.ctx,
452
+ createdAt: e.createdAt,
453
+ restored: true,
454
+ resumedFromDisk: true, // DEF-qqbot-20261110-7:真跨重启条目,裁决后补回执
455
+ ...(e.origin ? { origin: e.origin } : {}),
456
+ directory: deps.directoryOf?.(uid),
457
+ })
458
+ console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`)
459
+ // 恢复即重推审批卡片(卡片优先,失败降级文字)——重启后用户必须能重新
460
+ // 看到可点按钮;旧行为只注册槽位不推送,用户收不到任何审批入口(2026-11-05
461
+ // 按钮丢失事故:重启后只剩文字重发路径,按钮再也出不来)。
462
+ void (async () => {
463
+ const sentByCard = deps.sendApprovalPrompt
464
+ ? await deps.sendApprovalPrompt(e.ctx, e.request, e.mainSessionId, e.origin).catch(() => false)
465
+ : false
466
+ if (!sentByCard) {
467
+ await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin)).catch((error) => {
468
+ console.error("[bridge] 恢复审批推送失败:", error)
469
+ })
470
+ }
471
+ })()
472
+ }
473
+ }
474
+
475
+ // L 项(2026-10-30):常驻交互监听器发现外部审批时的注册入口。与 restore() 同款
476
+ // "无活 waiter"槽:用户在 QQ 裁决后 resolve() 走直连 POST reply(restored 路径),
477
+ // 并回执"已从 QQ 批准"。同 request.id 已在挂起则去重。
478
+ function pushExternalImpl(
479
+ userId: string,
480
+ ctx: MessageContext,
481
+ request: PermissionRequest,
482
+ mainSessionId: string,
483
+ origin: PermOrigin = "external",
484
+ ): void {
485
+ if (pendingPermissions.get(userId)?.request.id === request.id) return
486
+ // 单一挂起槽:新审批取代旧槽
487
+ const prev = pendingPermissions.get(userId)
488
+ if (prev) clearTimers(prev)
489
+
490
+ const alertTimer = startNudgeTimer(userId, request.id, ctx)
491
+ const directory = deps.directoryOf?.(userId)
492
+ const timer = setTimeout(() => {
493
+ if (pendingPermissions.get(userId)?.request.id !== request.id) return
494
+ pendingPermissions.delete(userId)
495
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
496
+ deps.onDecision?.(userId) // 外部审批 TTL 拒绝也要唤醒队列
497
+ void client.permission
498
+ .reply({ path: { sessionID: request.sessionID, requestID: request.id }, body: { decision: "reject" }, directory })
499
+ .catch(() => {})
500
+ void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
501
+ }, PERM_PROMPT_TTL_MS)
502
+ timer.unref?.()
503
+
504
+ pendingPermissions.set(userId, {
505
+ request,
506
+ mainSessionId,
507
+ resolve: () => {},
508
+ timer,
509
+ alertTimer,
510
+ ctx,
511
+ createdAt: Date.now(),
512
+ restored: true,
513
+ origin, // DEF-qqbot-20261110-4:来源按回合归属传入(bot=QQ 回合 / external=桌面回合),不再一律桌面
514
+ directory,
515
+ })
516
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
517
+ console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action} origin=${origin}`)
518
+ // 推送失败不撤槽(用户仍可能文字裁决)。DEF-5:同步认领制,防并发异请求覆写
519
+ // 场景下本请求已被他路推过而重复推卡。
520
+ if (claimCardPush(request.id)) {
521
+ void (async () => {
522
+ // DEF-qqbot-20261114-P5(owner 2026-11-14「全修剩下缺陷」批):发卡有 token+网络
523
+ // 耗时(实测 834ms 慢管道),期间桌面端可能已处理(联动清槽)。单线程语义下推卡
524
+ // 与清槽同 tick 不可交错——卡的「发送前复查」是死守卫(如实移除);有效防线=
525
+ // ①发送后槽被清→日志留痕(卡在途不可撤,平台无撤回 API,至少时序可归因)
526
+ // ②文字降级前复查槽位——不发迟到死菜单(否则时序上早于「已处理」通知,用户困惑)。
527
+ const sentByCard = deps.sendApprovalPrompt
528
+ ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin).catch(() => false)
529
+ : false
530
+ const stillPending = () => pendingPermissions.get(userId)?.request.id === request.id
531
+ if (!stillPending()) {
532
+ console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`)
533
+ }
534
+ if (!sentByCard) {
535
+ if (!stillPending()) {
536
+ console.log(`[perm] 文字降级前复查:槽已清(他端已处理),跳过文字菜单 request=${request.id}`)
537
+ return
538
+ }
539
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external")).catch((error) => {
540
+ console.error("[bridge] 发送审批请求失败:", error)
541
+ })
542
+ }
543
+ })()
544
+ }
545
+ }
546
+
547
+ // 联动清槽(2026-11-09):SSE permission.replied={sessionID,requestID,reply} 到达时,
548
+ // 若该 requestID 在挂起槽中(无论来源 bot/external),清槽 + QQ 回执「源头已处理」,
549
+ // 并唤醒队列。返回 true=确有槽被清;无匹配槽返回 false(正常:QQ 已先裁决 兜底 TTL 已走)。
550
+ function clearIfResolved(sessionID: string | undefined, requestID: string, reply: unknown): boolean {
551
+ for (const [uid, entry] of pendingPermissions) {
552
+ if (entry.request.id !== requestID) continue
553
+ if (sessionID && entry.request.sessionID && sessionID !== entry.request.sessionID) continue
554
+ const e = entry
555
+ clearTimers(e)
556
+ pendingPermissions.delete(uid)
557
+ savePendingPermMap(pendingPermissions, PERSIST_FILE)
558
+ deps.onDecision?.(uid) // 槽清空即唤醒该用户队列(与裁决/TTL 同口径)
559
+ const label =
560
+ reply === "allow" || reply === "once"
561
+ ? "允许(本次)"
562
+ : reply === "always"
563
+ ? "总是允许"
564
+ : reply === "reject"
565
+ ? "拒绝"
566
+ : `已处理(${String(reply ?? "未知")})`
567
+ console.log(`[perm] 联动清槽(源头已解决):uid=${uid.slice(0, 8)}… request=${requestID} reply=${String(reply)}`)
568
+ void safeDeliver(
569
+ e.ctx,
570
+ `🔄 审批 ${requestID.slice(-8)} 已由${e.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${label}),QQ 审批自动关闭`,
571
+ ).catch(() => {})
572
+ return true
573
+ }
574
+ return false
575
+ }
576
+
577
+ return { hasPending, getPending, waitForDecision, resolve, restore, pushExternal: pushExternalImpl, clearIfResolved }
578
+ }
579
+
580
+ // 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
581
+ // 优先级:绝对否定 > 总是 > 允许。
582
+ // 安全方向性:审批场景下误判的代价不对称 —— 误拒只需重试,误放行会执行
583
+ // 危险命令。所以否定词最优先,且「不X」前缀词(不同意/不允许/不要/别)
584
+ // 必须盖住「X」(同意/允许)与「总是」(总是不允许 ≠ 总是允许)。
585
+ export function parsePermissionDecision(content: string): PermissionDecision | null {
586
+ const t = content
587
+ .trim()
588
+ .toLowerCase()
589
+ .replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1")
590
+ if (!t) return null
591
+ // 债务D5:混合否定增强——"不ok/不太行/否决/驳回/不可以"等一律 reject。
592
+ // 方向性不变:否定最优先,歧义一律倒向拒绝(误拒可重试,误放行是事故)。
593
+ if (
594
+ /\b(deny|reject|no|nope|nah)\b|拒绝|否决|驳回|不准|不给|^否$|别|不要|不\s*(同意|允许|批准|许可|行|ok|okay|可以)|不(太|怎么|太特么)\s*(行|ok|okay|可以)/.test(t)
595
+ )
596
+ return "reject"
597
+ if (/\balways\b|总是(?!不)|永久/.test(t)) return "always"
598
+ if (/\b(allow|approve|yes|ok|y)\b|允许|同意|批准/.test(t)) return "once"
599
+ return null
600
+ }
601
+
602
+ export function formatPermissionPrompt(
603
+ request: PermissionRequest,
604
+ mainSessionId?: string,
605
+ origin?: PermOrigin,
606
+ ): string {
607
+ const lines = ["🔐 需要权限审批", `动作:${request.action || "(未知)"}`]
608
+ if (origin === "external") {
609
+ // 2026-11-09 联动修复:桌面端发起的回合经事件流镜像到 QQ——标注来源,
610
+ // 用户一眼知道这卡是桌面 AI 的活;QQ 与桌面审批等效(先到先解)。
611
+ lines.push("来源:桌面端回合(bot 镜像推送;QQ 与桌面放行等效)")
612
+ }
613
+ // 债务D1:子会话(subagent)发起的审批要标注来源,用户知道批的是谁
614
+ if (mainSessionId && request.sessionID && request.sessionID !== mainSessionId) {
615
+ lines.push(`来源:子会话 ${request.sessionID}(subagent 发起)`)
616
+ }
617
+ const resources = (request.resources ?? []).slice(0, 5)
618
+ if (resources.length > 0) {
619
+ lines.push("资源:")
620
+ for (const r of resources) lines.push(` ${truncate(r, 300)}`)
621
+ }
622
+ if (request.message) lines.push(`说明:${truncate(request.message, 300)}`)
623
+ lines.push("")
624
+ lines.push("回复「允许」= 仅本次|「总是」= 保存为项目级白名单(后续同类命令永久放行)|「拒绝」= 驳回(含本会话其他待审)")
625
+ lines.push("(30 分钟无响应自动拒绝,也可用 /allow /always /deny)")
626
+ return lines.join("\n")
627
+ }