@linjz/opencode-qqbot 0.3.11 → 0.3.13

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 (45) hide show
  1. package/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1056 -194
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +154 -18
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +98 -10
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. package/tsconfig.json +24 -24
@@ -1,301 +1,301 @@
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
- void sendReply(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
126
- }
127
- }, PERM_PROMPT_TTL_MS)
128
-
129
- pendingPermissions.set(ctx.userId, {
130
- request,
131
- mainSessionId,
132
- resolve,
133
- timer,
134
- ctx,
135
- createdAt: Date.now(),
136
- })
137
- savePendingPermMap(pendingPermissions) // O2:落盘,重启不丢
138
- // A 项(2026-10-29):卡片按钮优先,发送失败降级文字菜单;两者都失败
139
- // 不 reject promise(用户仍可能稍后主动回复)
140
- void (async () => {
141
- const sentByCard = deps.sendApprovalPrompt
142
- ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
143
- : false
144
- if (!sentByCard) {
145
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
146
- console.error("[bridge] 发送审批请求失败:", error)
147
- })
148
- }
149
- })()
150
- })
151
- }
152
-
153
- function resolve(userId: string, decision: PermissionDecision): void {
154
- const entry = pendingPermissions.get(userId)
155
- if (!entry) return
156
- if (entry.timer) clearTimeout(entry.timer)
157
- pendingPermissions.delete(userId)
158
- savePendingPermMap(pendingPermissions)
159
- if (entry.restored) {
160
- // O2(P2-4a):跨重启——原 waiter 已随进程消失,直连 POST reply 争取
161
- // 原位生效;会话已不在等待则明确回执"重新发起",绝不灌会话当普通消息
162
- void (async () => {
163
- const label = decision === "always" ? "总是允许" : decision === "once" ? "允许" : "拒绝"
164
- try {
165
- await client.permission.reply({
166
- path: { sessionID: entry.request.sessionID, requestID: entry.request.id },
167
- body: { decision },
168
- })
169
- await safeDeliver(entry.ctx, `✅ 审批已跨重启完成(${label}),原会话已继续`)
170
- } catch {
171
- await safeDeliver(entry.ctx, "⚠️ 审批未能跨重启完成(原请求可能已失效),请重新发起原操作")
172
- }
173
- })()
174
- return
175
- }
176
- entry.resolve(decision)
177
- }
178
-
179
- // O2(P2-4a):恢复重启前挂起的审批(30min TTL 内有效);恢复条目超时则
180
- // 直连 reject 解阻塞会话(原 waiter 已不存在,无人代答)
181
- function restore(): void {
182
- const saved = loadPendingPermMap()
183
- for (const [uid, e] of Object.entries(saved)) {
184
- const left = PERM_PROMPT_TTL_MS - (Date.now() - e.createdAt)
185
- if (left <= 0) continue
186
- const timer = setTimeout(() => {
187
- if (pendingPermissions.get(uid)?.request.id === e.request.id) {
188
- pendingPermissions.delete(uid)
189
- savePendingPermMap(pendingPermissions)
190
- void client.permission
191
- .reply({
192
- path: { sessionID: e.request.sessionID, requestID: e.request.id },
193
- body: { decision: "reject" },
194
- })
195
- .catch(() => {})
196
- void safeDeliver(e.ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
197
- }
198
- }, left)
199
- pendingPermissions.set(uid, {
200
- request: e.request,
201
- mainSessionId: e.mainSessionId,
202
- resolve: () => {},
203
- timer,
204
- ctx: e.ctx,
205
- createdAt: e.createdAt,
206
- restored: true,
207
- })
208
- console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`)
209
- }
210
- }
211
-
212
- // L 项(2026-10-30):常驻交互监听器发现外部审批时的注册入口。与 restore() 同款
213
- // "无活 waiter"槽:用户在 QQ 裁决后 resolve() 走直连 POST reply(restored 路径),
214
- // 并回执"已从 QQ 批准"。同 request.id 已在挂起则去重。
215
- function pushExternalImpl(
216
- userId: string,
217
- ctx: MessageContext,
218
- request: PermissionRequest,
219
- mainSessionId: string,
220
- ): void {
221
- if (pendingPermissions.get(userId)?.request.id === request.id) return
222
- // 单一挂起槽:新审批取代旧槽
223
- const prev = pendingPermissions.get(userId)
224
- if (prev?.timer) clearTimeout(prev.timer)
225
-
226
- const timer = setTimeout(() => {
227
- if (pendingPermissions.get(userId)?.request.id !== request.id) return
228
- pendingPermissions.delete(userId)
229
- savePendingPermMap(pendingPermissions)
230
- void client.permission
231
- .reply({ path: { sessionID: request.sessionID, requestID: request.id }, body: { decision: "reject" } })
232
- .catch(() => {})
233
- void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
234
- }, PERM_PROMPT_TTL_MS)
235
-
236
- pendingPermissions.set(userId, {
237
- request,
238
- mainSessionId,
239
- resolve: () => {},
240
- timer,
241
- ctx,
242
- createdAt: Date.now(),
243
- restored: true,
244
- })
245
- savePendingPermMap(pendingPermissions)
246
- console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action}`)
247
- // 推送失败不撤槽(用户仍可能文字裁决)
248
- void (async () => {
249
- const sentByCard = deps.sendApprovalPrompt
250
- ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
251
- : false
252
- if (!sentByCard) {
253
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
254
- console.error("[bridge] 发送审批请求失败:", error)
255
- })
256
- }
257
- })()
258
- }
259
-
260
- return { hasPending, getPending, waitForDecision, resolve, restore, pushExternal: pushExternalImpl }
261
- }
262
-
263
- // 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
264
- // 优先级:绝对否定 > 总是 > 允许。
265
- // 安全方向性:审批场景下误判的代价不对称 —— 误拒只需重试,误放行会执行
266
- // 危险命令。所以否定词最优先,且「不X」前缀词(不同意/不允许/不要/别)
267
- // 必须盖住「X」(同意/允许)与「总是」(总是不允许 ≠ 总是允许)。
268
- export function parsePermissionDecision(content: string): PermissionDecision | null {
269
- const t = content
270
- .trim()
271
- .toLowerCase()
272
- .replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1")
273
- if (!t) return null
274
- // 债务D5:混合否定增强——"不ok/不太行/否决/驳回/不可以"等一律 reject。
275
- // 方向性不变:否定最优先,歧义一律倒向拒绝(误拒可重试,误放行是事故)。
276
- if (
277
- /\b(deny|reject|no|nope|nah)\b|拒绝|否决|驳回|不准|不给|^否$|别|不要|不\s*(同意|允许|批准|许可|行|ok|okay|可以)|不(太|怎么|太特么)\s*(行|ok|okay|可以)/.test(t)
278
- )
279
- return "reject"
280
- if (/\balways\b|总是(?!不)|永久/.test(t)) return "always"
281
- if (/\b(allow|approve|yes|ok|y)\b|允许|同意|批准/.test(t)) return "once"
282
- return null
283
- }
284
-
285
- export function formatPermissionPrompt(request: PermissionRequest, mainSessionId?: string): string {
286
- const lines = ["🔐 需要权限审批", `动作:${request.action || "(未知)"}`]
287
- // 债务D1:子会话(subagent)发起的审批要标注来源,用户知道批的是谁
288
- if (mainSessionId && request.sessionID && request.sessionID !== mainSessionId) {
289
- lines.push(`来源:子会话 ${request.sessionID}(subagent 发起)`)
290
- }
291
- const resources = (request.resources ?? []).slice(0, 5)
292
- if (resources.length > 0) {
293
- lines.push("资源:")
294
- for (const r of resources) lines.push(` ${truncate(r, 300)}`)
295
- }
296
- if (request.message) lines.push(`说明:${truncate(request.message, 300)}`)
297
- lines.push("")
298
- lines.push("回复「允许」= 仅本次|「总是」= 保存为项目级白名单(后续同类命令永久放行)|「拒绝」= 驳回(含本会话其他待审)")
299
- lines.push("(30 分钟无响应自动拒绝,也可用 /allow /always /deny)")
300
- return lines.join("\n")
301
- }
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
+ void sendReply(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
126
+ }
127
+ }, PERM_PROMPT_TTL_MS)
128
+
129
+ pendingPermissions.set(ctx.userId, {
130
+ request,
131
+ mainSessionId,
132
+ resolve,
133
+ timer,
134
+ ctx,
135
+ createdAt: Date.now(),
136
+ })
137
+ savePendingPermMap(pendingPermissions) // O2:落盘,重启不丢
138
+ // A 项(2026-10-29):卡片按钮优先,发送失败降级文字菜单;两者都失败
139
+ // 不 reject promise(用户仍可能稍后主动回复)
140
+ void (async () => {
141
+ const sentByCard = deps.sendApprovalPrompt
142
+ ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
143
+ : false
144
+ if (!sentByCard) {
145
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
146
+ console.error("[bridge] 发送审批请求失败:", error)
147
+ })
148
+ }
149
+ })()
150
+ })
151
+ }
152
+
153
+ function resolve(userId: string, decision: PermissionDecision): void {
154
+ const entry = pendingPermissions.get(userId)
155
+ if (!entry) return
156
+ if (entry.timer) clearTimeout(entry.timer)
157
+ pendingPermissions.delete(userId)
158
+ savePendingPermMap(pendingPermissions)
159
+ if (entry.restored) {
160
+ // O2(P2-4a):跨重启——原 waiter 已随进程消失,直连 POST reply 争取
161
+ // 原位生效;会话已不在等待则明确回执"重新发起",绝不灌会话当普通消息
162
+ void (async () => {
163
+ const label = decision === "always" ? "总是允许" : decision === "once" ? "允许" : "拒绝"
164
+ try {
165
+ await client.permission.reply({
166
+ path: { sessionID: entry.request.sessionID, requestID: entry.request.id },
167
+ body: { decision },
168
+ })
169
+ await safeDeliver(entry.ctx, `✅ 审批已跨重启完成(${label}),原会话已继续`)
170
+ } catch {
171
+ await safeDeliver(entry.ctx, "⚠️ 审批未能跨重启完成(原请求可能已失效),请重新发起原操作")
172
+ }
173
+ })()
174
+ return
175
+ }
176
+ entry.resolve(decision)
177
+ }
178
+
179
+ // O2(P2-4a):恢复重启前挂起的审批(30min TTL 内有效);恢复条目超时则
180
+ // 直连 reject 解阻塞会话(原 waiter 已不存在,无人代答)
181
+ function restore(): void {
182
+ const saved = loadPendingPermMap()
183
+ for (const [uid, e] of Object.entries(saved)) {
184
+ const left = PERM_PROMPT_TTL_MS - (Date.now() - e.createdAt)
185
+ if (left <= 0) continue
186
+ const timer = setTimeout(() => {
187
+ if (pendingPermissions.get(uid)?.request.id === e.request.id) {
188
+ pendingPermissions.delete(uid)
189
+ savePendingPermMap(pendingPermissions)
190
+ void client.permission
191
+ .reply({
192
+ path: { sessionID: e.request.sessionID, requestID: e.request.id },
193
+ body: { decision: "reject" },
194
+ })
195
+ .catch(() => {})
196
+ void safeDeliver(e.ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
197
+ }
198
+ }, left)
199
+ pendingPermissions.set(uid, {
200
+ request: e.request,
201
+ mainSessionId: e.mainSessionId,
202
+ resolve: () => {},
203
+ timer,
204
+ ctx: e.ctx,
205
+ createdAt: e.createdAt,
206
+ restored: true,
207
+ })
208
+ console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`)
209
+ }
210
+ }
211
+
212
+ // L 项(2026-10-30):常驻交互监听器发现外部审批时的注册入口。与 restore() 同款
213
+ // "无活 waiter"槽:用户在 QQ 裁决后 resolve() 走直连 POST reply(restored 路径),
214
+ // 并回执"已从 QQ 批准"。同 request.id 已在挂起则去重。
215
+ function pushExternalImpl(
216
+ userId: string,
217
+ ctx: MessageContext,
218
+ request: PermissionRequest,
219
+ mainSessionId: string,
220
+ ): void {
221
+ if (pendingPermissions.get(userId)?.request.id === request.id) return
222
+ // 单一挂起槽:新审批取代旧槽
223
+ const prev = pendingPermissions.get(userId)
224
+ if (prev?.timer) clearTimeout(prev.timer)
225
+
226
+ const timer = setTimeout(() => {
227
+ if (pendingPermissions.get(userId)?.request.id !== request.id) return
228
+ pendingPermissions.delete(userId)
229
+ savePendingPermMap(pendingPermissions)
230
+ void client.permission
231
+ .reply({ path: { sessionID: request.sessionID, requestID: request.id }, body: { decision: "reject" } })
232
+ .catch(() => {})
233
+ void safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {})
234
+ }, PERM_PROMPT_TTL_MS)
235
+
236
+ pendingPermissions.set(userId, {
237
+ request,
238
+ mainSessionId,
239
+ resolve: () => {},
240
+ timer,
241
+ ctx,
242
+ createdAt: Date.now(),
243
+ restored: true,
244
+ })
245
+ savePendingPermMap(pendingPermissions)
246
+ console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action}`)
247
+ // 推送失败不撤槽(用户仍可能文字裁决)
248
+ void (async () => {
249
+ const sentByCard = deps.sendApprovalPrompt
250
+ ? await deps.sendApprovalPrompt(ctx, request, mainSessionId).catch(() => false)
251
+ : false
252
+ if (!sentByCard) {
253
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId)).catch((error) => {
254
+ console.error("[bridge] 发送审批请求失败:", error)
255
+ })
256
+ }
257
+ })()
258
+ }
259
+
260
+ return { hasPending, getPending, waitForDecision, resolve, restore, pushExternal: pushExternalImpl }
261
+ }
262
+
263
+ // 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
264
+ // 优先级:绝对否定 > 总是 > 允许。
265
+ // 安全方向性:审批场景下误判的代价不对称 —— 误拒只需重试,误放行会执行
266
+ // 危险命令。所以否定词最优先,且「不X」前缀词(不同意/不允许/不要/别)
267
+ // 必须盖住「X」(同意/允许)与「总是」(总是不允许 ≠ 总是允许)。
268
+ export function parsePermissionDecision(content: string): PermissionDecision | null {
269
+ const t = content
270
+ .trim()
271
+ .toLowerCase()
272
+ .replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1")
273
+ if (!t) return null
274
+ // 债务D5:混合否定增强——"不ok/不太行/否决/驳回/不可以"等一律 reject。
275
+ // 方向性不变:否定最优先,歧义一律倒向拒绝(误拒可重试,误放行是事故)。
276
+ if (
277
+ /\b(deny|reject|no|nope|nah)\b|拒绝|否决|驳回|不准|不给|^否$|别|不要|不\s*(同意|允许|批准|许可|行|ok|okay|可以)|不(太|怎么|太特么)\s*(行|ok|okay|可以)/.test(t)
278
+ )
279
+ return "reject"
280
+ if (/\balways\b|总是(?!不)|永久/.test(t)) return "always"
281
+ if (/\b(allow|approve|yes|ok|y)\b|允许|同意|批准/.test(t)) return "once"
282
+ return null
283
+ }
284
+
285
+ export function formatPermissionPrompt(request: PermissionRequest, mainSessionId?: string): string {
286
+ const lines = ["🔐 需要权限审批", `动作:${request.action || "(未知)"}`]
287
+ // 债务D1:子会话(subagent)发起的审批要标注来源,用户知道批的是谁
288
+ if (mainSessionId && request.sessionID && request.sessionID !== mainSessionId) {
289
+ lines.push(`来源:子会话 ${request.sessionID}(subagent 发起)`)
290
+ }
291
+ const resources = (request.resources ?? []).slice(0, 5)
292
+ if (resources.length > 0) {
293
+ lines.push("资源:")
294
+ for (const r of resources) lines.push(` ${truncate(r, 300)}`)
295
+ }
296
+ if (request.message) lines.push(`说明:${truncate(request.message, 300)}`)
297
+ lines.push("")
298
+ lines.push("回复「允许」= 仅本次|「总是」= 保存为项目级白名单(后续同类命令永久放行)|「拒绝」= 驳回(含本会话其他待审)")
299
+ lines.push("(30 分钟无响应自动拒绝,也可用 /allow /always /deny)")
300
+ return lines.join("\n")
301
+ }