@linjz/opencode-qqbot 0.3.20 → 0.3.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/README.zh-CN.md +11 -3
- package/bin/openqq.js +1 -1
- package/dist/opencode-qqbot-plugin.js +124 -6
- package/dist/openqq-bot.js +560 -93
- package/dist/openqq-cli.js +152 -16
- package/dist/openqq-watchdog.js +72 -2
- package/package.json +2 -2
- package/src/bridge.ts +26 -6
- package/src/cli/openqq-main.ts +33 -5
- package/src/core/bot-control.ts +73 -8
- package/src/core/card-approval.ts +10 -0
- package/src/core/office-text.ts +234 -0
- package/src/core/permission.ts +157 -26
- package/src/core/watchdog.ts +108 -5
- package/src/qq/media.ts +153 -54
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// @input: node:fs/node:zlib(OOXML zip/XML 只读解析)
|
|
2
|
+
// @output: officeKindForPath, isLegacyOfficePath, extractOfficeTextFromFile
|
|
3
|
+
// @pos: core - Office Open XML 文档文本提取(docx/xlsx/pptx 及 macro 变体)
|
|
4
|
+
//
|
|
5
|
+
// 设计边界:只支持 ZIP 容器 + XML 的现代 Office 格式;传统 .doc/.xls/.ppt
|
|
6
|
+
// 是 OLE 二进制,跨平台零依赖无法安全解析,由调用方明确拒识并指引转换。
|
|
7
|
+
import { readFileSync } from "node:fs"
|
|
8
|
+
import { inflateRawSync } from "node:zlib"
|
|
9
|
+
|
|
10
|
+
export type OfficeKind = "docx" | "xlsx" | "pptx"
|
|
11
|
+
|
|
12
|
+
const MAX_ENTRY_COUNT = 10_000
|
|
13
|
+
const MAX_ENTRY_UNCOMPRESSED_BYTES = 50 * 1024 * 1024
|
|
14
|
+
export const MAX_OFFICE_TEXT_CHARS = 200_000
|
|
15
|
+
|
|
16
|
+
export function officeKindForPath(path: string): OfficeKind | null {
|
|
17
|
+
const ext = path.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? ""
|
|
18
|
+
if (ext === "docx" || ext === "docm") return "docx"
|
|
19
|
+
if (ext === "xlsx" || ext === "xlsm") return "xlsx"
|
|
20
|
+
if (ext === "pptx" || ext === "pptm") return "pptx"
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isLegacyOfficePath(path: string): boolean {
|
|
25
|
+
return /\.(doc|xls|ppt)$/i.test(path)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface ZipEntry {
|
|
29
|
+
name: string
|
|
30
|
+
flags: number
|
|
31
|
+
method: number
|
|
32
|
+
compressedSize: number
|
|
33
|
+
uncompressedSize: number
|
|
34
|
+
localHeaderOffset: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function findEndOfCentralDirectory(buf: Buffer): number {
|
|
38
|
+
const min = Math.max(0, buf.length - 65_557) // EOCD 22B + 最大 comment 65535B
|
|
39
|
+
for (let i = buf.length - 22; i >= min; i--) {
|
|
40
|
+
if (buf.readUInt32LE(i) === 0x06054b50) return i
|
|
41
|
+
}
|
|
42
|
+
throw new Error("不是有效的 ZIP/OOXML 文件")
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readZipEntries(buf: Buffer): Map<string, ZipEntry> {
|
|
46
|
+
const eocd = findEndOfCentralDirectory(buf)
|
|
47
|
+
const count = buf.readUInt16LE(eocd + 10)
|
|
48
|
+
const centralOffset = buf.readUInt32LE(eocd + 16)
|
|
49
|
+
if (count > MAX_ENTRY_COUNT) throw new Error("ZIP 条目过多")
|
|
50
|
+
const entries = new Map<string, ZipEntry>()
|
|
51
|
+
let offset = centralOffset
|
|
52
|
+
for (let i = 0; i < count; i++) {
|
|
53
|
+
if (offset + 46 > buf.length || buf.readUInt32LE(offset) !== 0x02014b50) {
|
|
54
|
+
throw new Error("ZIP 中央目录损坏")
|
|
55
|
+
}
|
|
56
|
+
const flags = buf.readUInt16LE(offset + 8)
|
|
57
|
+
const method = buf.readUInt16LE(offset + 10)
|
|
58
|
+
const compressedSize = buf.readUInt32LE(offset + 20)
|
|
59
|
+
const uncompressedSize = buf.readUInt32LE(offset + 24)
|
|
60
|
+
const nameLength = buf.readUInt16LE(offset + 28)
|
|
61
|
+
const extraLength = buf.readUInt16LE(offset + 30)
|
|
62
|
+
const commentLength = buf.readUInt16LE(offset + 32)
|
|
63
|
+
const localHeaderOffset = buf.readUInt32LE(offset + 42)
|
|
64
|
+
const name = buf.subarray(offset + 46, offset + 46 + nameLength).toString("utf8")
|
|
65
|
+
if (uncompressedSize > MAX_ENTRY_UNCOMPRESSED_BYTES) throw new Error(`ZIP 条目过大:${name}`)
|
|
66
|
+
entries.set(name, { name, flags, method, compressedSize, uncompressedSize, localHeaderOffset })
|
|
67
|
+
offset += 46 + nameLength + extraLength + commentLength
|
|
68
|
+
}
|
|
69
|
+
return entries
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readZipEntry(buf: Buffer, entry: ZipEntry): Buffer {
|
|
73
|
+
if ((entry.flags & 0x1) !== 0) throw new Error(`加密 ZIP 条目不支持:${entry.name}`)
|
|
74
|
+
const offset = entry.localHeaderOffset
|
|
75
|
+
if (offset + 30 > buf.length || buf.readUInt32LE(offset) !== 0x04034b50) {
|
|
76
|
+
throw new Error(`ZIP 本地头损坏:${entry.name}`)
|
|
77
|
+
}
|
|
78
|
+
const nameLength = buf.readUInt16LE(offset + 26)
|
|
79
|
+
const extraLength = buf.readUInt16LE(offset + 28)
|
|
80
|
+
const dataOffset = offset + 30 + nameLength + extraLength
|
|
81
|
+
const dataEnd = dataOffset + entry.compressedSize
|
|
82
|
+
if (dataEnd > buf.length) throw new Error(`ZIP 数据越界:${entry.name}`)
|
|
83
|
+
const data = buf.subarray(dataOffset, dataEnd)
|
|
84
|
+
if (entry.method === 0) return Buffer.from(data)
|
|
85
|
+
if (entry.method === 8) {
|
|
86
|
+
const out = inflateRawSync(data)
|
|
87
|
+
if (out.length !== entry.uncompressedSize) throw new Error(`ZIP 解压长度不符:${entry.name}`)
|
|
88
|
+
return out
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`ZIP 压缩方式不支持:${entry.name}`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function xmlUnescape(value: string): string {
|
|
94
|
+
return value
|
|
95
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) => String.fromCodePoint(Number.parseInt(hex, 16)))
|
|
96
|
+
.replace(/&#([0-9]+);/g, (_, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10)))
|
|
97
|
+
.replace(/</g, "<")
|
|
98
|
+
.replace(/>/g, ">")
|
|
99
|
+
.replace(/"/g, '"')
|
|
100
|
+
.replace(/'/g, "'")
|
|
101
|
+
.replace(/&/g, "&")
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function attrs(tag: string): Record<string, string> {
|
|
105
|
+
const out: Record<string, string> = {}
|
|
106
|
+
for (const match of tag.matchAll(/([\w:]+)\s*=\s*"([^"]*)"/g)) {
|
|
107
|
+
out[match[1]] = xmlUnescape(match[2])
|
|
108
|
+
}
|
|
109
|
+
return out
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function normalizeExtractedText(value: string): string {
|
|
113
|
+
const cleaned = xmlUnescape(value.replace(/<[^>]+>/g, ""))
|
|
114
|
+
.replace(/\r/g, "")
|
|
115
|
+
.split("\n")
|
|
116
|
+
.map((line) => line.replace(/ +/g, " ").trimEnd())
|
|
117
|
+
.join("\n")
|
|
118
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
119
|
+
.trim()
|
|
120
|
+
return cleaned.length > MAX_OFFICE_TEXT_CHARS
|
|
121
|
+
? `${cleaned.slice(0, MAX_OFFICE_TEXT_CHARS)}\n…(Office 文档内容过长,已截断)`
|
|
122
|
+
: cleaned
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function extractDocx(entries: Map<string, ZipEntry>, zip: Buffer): string {
|
|
126
|
+
const entry = entries.get("word/document.xml")
|
|
127
|
+
if (!entry) throw new Error("DOCX 缺少 word/document.xml")
|
|
128
|
+
const xml = readZipEntry(zip, entry).toString("utf8")
|
|
129
|
+
const text = xml
|
|
130
|
+
.replace(/<w:tab\b[^>]*\/>/g, "\t")
|
|
131
|
+
.replace(/<w:br\b[^>]*\/>/g, "\n")
|
|
132
|
+
.replace(/<\/w:p>/g, "\n")
|
|
133
|
+
.replace(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g, "$1")
|
|
134
|
+
return normalizeExtractedText(text)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function extractPptx(entries: Map<string, ZipEntry>, zip: Buffer): string {
|
|
138
|
+
const slides = [...entries.keys()]
|
|
139
|
+
.filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name))
|
|
140
|
+
.sort((a, b) => Number(a.match(/slide(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/slide(\d+)\.xml$/)?.[1] ?? 0))
|
|
141
|
+
if (slides.length === 0) throw new Error("PPTX 缺少幻灯片 XML")
|
|
142
|
+
const parts: string[] = []
|
|
143
|
+
for (const [index, name] of slides.entries()) {
|
|
144
|
+
const xml = readZipEntry(zip, entries.get(name)!).toString("utf8")
|
|
145
|
+
const text = xml
|
|
146
|
+
.replace(/<a:br\b[^>]*\/>/g, "\n")
|
|
147
|
+
.replace(/<\/a:p>/g, "\n")
|
|
148
|
+
.replace(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g, "$1")
|
|
149
|
+
const cleaned = normalizeExtractedText(text)
|
|
150
|
+
if (cleaned) parts.push(`## Slide ${index + 1}\n${cleaned}`)
|
|
151
|
+
}
|
|
152
|
+
return normalizeExtractedText(parts.join("\n\n"))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function sharedStrings(entries: Map<string, ZipEntry>, zip: Buffer): string[] {
|
|
156
|
+
const entry = entries.get("xl/sharedStrings.xml")
|
|
157
|
+
if (!entry) return []
|
|
158
|
+
const xml = readZipEntry(zip, entry).toString("utf8")
|
|
159
|
+
const out: string[] = []
|
|
160
|
+
for (const si of xml.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)) {
|
|
161
|
+
const texts = [...si[1].matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1]))
|
|
162
|
+
out.push(texts.join(""))
|
|
163
|
+
}
|
|
164
|
+
return out
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function workbookSheets(entries: Map<string, ZipEntry>, zip: Buffer): Array<{ name: string; path: string }> {
|
|
168
|
+
const workbookEntry = entries.get("xl/workbook.xml")
|
|
169
|
+
if (!workbookEntry) throw new Error("XLSX 缺少 xl/workbook.xml")
|
|
170
|
+
const workbook = readZipEntry(zip, workbookEntry).toString("utf8")
|
|
171
|
+
const rels = new Map<string, string>()
|
|
172
|
+
const relEntry = entries.get("xl/_rels/workbook.xml.rels")
|
|
173
|
+
if (relEntry) {
|
|
174
|
+
const relXml = readZipEntry(zip, relEntry).toString("utf8")
|
|
175
|
+
for (const rel of relXml.matchAll(/<Relationship\b[^>]*>/g)) {
|
|
176
|
+
const a = attrs(rel[0])
|
|
177
|
+
if (a.Id && a.Target) rels.set(a.Id, a.Target.replace(/^\//, ""))
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const sheets: Array<{ name: string; path: string }> = []
|
|
181
|
+
for (const sheet of workbook.matchAll(/<sheet\b[^>]*\/>/g)) {
|
|
182
|
+
const a = attrs(sheet[0])
|
|
183
|
+
const rid = a["r:id"] ?? a.id
|
|
184
|
+
const target = rid ? rels.get(rid) : undefined
|
|
185
|
+
const path = target?.startsWith("xl/") ? target : target ? `xl/${target}` : undefined
|
|
186
|
+
if (a.name && path && entries.has(path)) sheets.push({ name: a.name, path })
|
|
187
|
+
}
|
|
188
|
+
if (sheets.length > 0) return sheets
|
|
189
|
+
return [...entries.keys()]
|
|
190
|
+
.filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/.test(name))
|
|
191
|
+
.sort((a, b) => Number(a.match(/sheet(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/sheet(\d+)\.xml$/)?.[1] ?? 0))
|
|
192
|
+
.map((path, index) => ({ name: `Sheet${index + 1}`, path }))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function cellText(cellTag: string, body: string, shared: string[]): string {
|
|
196
|
+
const type = attrs(cellTag).t
|
|
197
|
+
if (type === "s") {
|
|
198
|
+
const index = Number(body.match(/<v>(\d+)<\/v>/)?.[1] ?? "-1")
|
|
199
|
+
return shared[index] ?? ""
|
|
200
|
+
}
|
|
201
|
+
if (type === "inlineStr") {
|
|
202
|
+
return [...body.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1])).join("")
|
|
203
|
+
}
|
|
204
|
+
const value = body.match(/<v>([\s\S]*?)<\/v>/)?.[1]
|
|
205
|
+
return value === undefined ? "" : xmlUnescape(value)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function extractXlsx(entries: Map<string, ZipEntry>, zip: Buffer): string {
|
|
209
|
+
const shared = sharedStrings(entries, zip)
|
|
210
|
+
const parts: string[] = []
|
|
211
|
+
for (const sheet of workbookSheets(entries, zip)) {
|
|
212
|
+
const xml = readZipEntry(zip, entries.get(sheet.path)!).toString("utf8")
|
|
213
|
+
const rows: string[] = []
|
|
214
|
+
for (const row of xml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
|
|
215
|
+
const cells: string[] = []
|
|
216
|
+
for (const cell of row[1].matchAll(/<c\b([^>]*)>([\s\S]*?)<\/c>/g)) {
|
|
217
|
+
cells.push(cellText(`<c ${cell[1]}>`, cell[2], shared))
|
|
218
|
+
}
|
|
219
|
+
if (cells.some((cell) => cell.trim())) rows.push(cells.join("\t").trimEnd())
|
|
220
|
+
}
|
|
221
|
+
if (rows.length > 0) parts.push(`## Sheet: ${sheet.name}\n${rows.join("\n")}`)
|
|
222
|
+
}
|
|
223
|
+
return normalizeExtractedText(parts.join("\n\n"))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function extractOfficeTextFromFile(filePath: string): string {
|
|
227
|
+
const kind = officeKindForPath(filePath)
|
|
228
|
+
if (!kind) throw new Error("不是支持的 Office 文档格式")
|
|
229
|
+
const zip = readFileSync(filePath)
|
|
230
|
+
const entries = readZipEntries(zip)
|
|
231
|
+
if (kind === "docx") return extractDocx(entries, zip)
|
|
232
|
+
if (kind === "pptx") return extractPptx(entries, zip)
|
|
233
|
+
return extractXlsx(entries, zip)
|
|
234
|
+
}
|
package/src/core/permission.ts
CHANGED
|
@@ -38,6 +38,10 @@ export interface PendingPermission {
|
|
|
38
38
|
* 属误报,只在从磁盘恢复的条目上投递。 */
|
|
39
39
|
resumedFromDisk?: boolean
|
|
40
40
|
origin?: PermOrigin // 2026-11-09:回合归属标注——bot=机器人回合,external=桌面端发起(镜像推送)
|
|
41
|
+
/** 2026-11-28:审批提示(卡片或文字菜单)已实际投递到 QQ。clearIfResolved 仅在此置位
|
|
42
|
+
* (或 resumedFromDisk)时发「自动关闭」回执——延迟判定窗/发送窗内清槽时无卡可关,
|
|
43
|
+
* 回执属误报(owner 实证:无卡却收「QQ 审批自动关闭」)。 */
|
|
44
|
+
promptDelivered?: boolean
|
|
41
45
|
/** DEF-qqbot-20261112-1:裁决 reply 的 x-opencode-directory 值(建槽时快照;
|
|
42
46
|
* 引擎待审批按 location 实例分仓,裁决/超时拒答不带目录会对项目会话 404) */
|
|
43
47
|
directory?: string
|
|
@@ -101,6 +105,15 @@ export function resolvePermDeferMs(envValue: string | undefined): number {
|
|
|
101
105
|
return Number.isFinite(n) && n >= 0 && n <= 10_000 ? n : 500
|
|
102
106
|
}
|
|
103
107
|
|
|
108
|
+
/** QQ_PERM_SEND_GRACE_MS 解析(默认 1000ms,0=关闭):审批卡真正调 QQ API 前的可取消发送窗。
|
|
109
|
+
* 默认 1000ms 与延迟判定窗 500ms 合计 1500ms 总可取消窗口(2026-11-28 owner 裁定:
|
|
110
|
+
* 覆盖桌面自动审批实测延迟分布 <500-933ms 并留余量;用户按习惯经 config.json 微调)。 */
|
|
111
|
+
export function resolvePermSendGraceMs(envValue: string | undefined): number {
|
|
112
|
+
if (envValue === undefined || envValue.trim() === "") return 1000
|
|
113
|
+
const n = Number(envValue)
|
|
114
|
+
return Number.isFinite(n) && n >= 0 && n <= 10_000 ? n : 1000
|
|
115
|
+
}
|
|
116
|
+
|
|
104
117
|
export const DECISION_LABELS: Record<PermissionDecision, string> = {
|
|
105
118
|
once: "允许(本次)",
|
|
106
119
|
always: "总是允许(已存入项目白名单)",
|
|
@@ -187,12 +200,14 @@ export interface PermissionGateDeps {
|
|
|
187
200
|
client: OpencodeClient
|
|
188
201
|
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
189
202
|
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
190
|
-
/** A 项(2026-10-29):卡片按钮审批发送通道;返回 false
|
|
203
|
+
/** A 项(2026-10-29):卡片按钮审批发送通道;返回 false 时本域自动降级文字菜单。
|
|
204
|
+
* isCancelled:发卡途中槽位被清/请求已解决时返回 true,发送层必须在 QQ API 前放弃。 */
|
|
191
205
|
sendApprovalPrompt?: (
|
|
192
206
|
ctx: MessageContext,
|
|
193
207
|
request: PermissionRequest,
|
|
194
208
|
mainSessionId: string,
|
|
195
209
|
origin?: PermOrigin,
|
|
210
|
+
isCancelled?: () => boolean,
|
|
196
211
|
) => Promise<boolean>
|
|
197
212
|
/** 槽位清空的唤醒钩子(用户裁决/TTL 自动拒绝均触发):审批挂起期间 drainQueue 被守卫
|
|
198
213
|
* 挡回,裁决后须由调用方重新放行队列——否则挂起期间入队的消息要等用户再发一条才动
|
|
@@ -200,6 +215,8 @@ export interface PermissionGateDeps {
|
|
|
200
215
|
onDecision?: (userId: string) => void
|
|
201
216
|
/** 10min 无裁决告警间隔(测试注入小值;缺省 PERM_NUDGE_MS) */
|
|
202
217
|
nudgeMs?: number
|
|
218
|
+
/** 审批卡发送窗(测试注入;缺省 QQ_PERM_SEND_GRACE_MS/500ms,0=关闭) */
|
|
219
|
+
sendGraceMs?: number
|
|
203
220
|
/** 跨重启恢复读盘入口(测试注入;缺省读 legacy 全局 pending-permissions.json) */
|
|
204
221
|
loadPending?: () => Record<string, PersistedPermission>
|
|
205
222
|
/** 多角色:落盘文件(缺省 legacy 全局 pending-permissions.json) */
|
|
@@ -226,14 +243,69 @@ export interface PermissionGate {
|
|
|
226
243
|
* 若该 requestID 在挂起槽中(无论来源 bot/external),清槽 + QQ 回执「源头已处理」,
|
|
227
244
|
* 并唤醒队列。返回 true=确有槽被清。无匹配槽返回 false(正常:QQ 已先裁决)。 */
|
|
228
245
|
clearIfResolved: (sessionID: string | undefined, requestID: string, reply: unknown) => boolean
|
|
246
|
+
/** 请求近期已被解决(清槽/裁决/TTL)——发卡全链取消判据,防在飞死卡。 */
|
|
247
|
+
wasResolvedRecently: (requestID: string) => boolean
|
|
229
248
|
}
|
|
230
249
|
|
|
231
250
|
// 审批域门面:挂起槽 + 等待/裁决 + 跨重启恢复。所有状态与文件读写收在本域。
|
|
232
251
|
export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
233
252
|
// 多角色(2026-11-17):审批态落盘文件可按角色注入;缺省 legacy 全局路径
|
|
234
253
|
const PERSIST_FILE = deps.persistFile ?? PENDING_PERM_FILE
|
|
254
|
+
const SEND_GRACE_MS = deps.sendGraceMs ?? resolvePermSendGraceMs(process.env.QQ_PERM_SEND_GRACE_MS)
|
|
235
255
|
const { client, sendReply, safeDeliver } = deps
|
|
236
256
|
const pendingPermissions = new Map<string, PendingPermission>()
|
|
257
|
+
// 发卡取消语义(2026-11-28 死卡竞态修复):请求被清槽/裁决/TTL 后短 TTL 记名——
|
|
258
|
+
// clearIfResolved 只能清槽,不能撤回已在飞的 sendApprovalPrompt;发卡全链据此放弃。
|
|
259
|
+
const RESOLVED_RECENT_TTL_MS = 5 * 60_000
|
|
260
|
+
/** 清槽时提示未投递 → 「自动关闭」回执挂起;卡若随后迟到投递成功(死卡)由发卡路径补发。 */
|
|
261
|
+
type StashedNotice = { label: string; origin?: PermOrigin; ctx: MessageContext }
|
|
262
|
+
const resolvedRecently = new Map<string, { exp: number; notice?: StashedNotice }>()
|
|
263
|
+
function markResolvedRecently(requestID: string): void {
|
|
264
|
+
const prev = resolvedRecently.get(requestID)
|
|
265
|
+
resolvedRecently.set(requestID, {
|
|
266
|
+
exp: Date.now() + RESOLVED_RECENT_TTL_MS,
|
|
267
|
+
...(prev?.notice ? { notice: prev.notice } : {}),
|
|
268
|
+
})
|
|
269
|
+
if (resolvedRecently.size > 500) {
|
|
270
|
+
const now = Date.now()
|
|
271
|
+
for (const [id, e] of resolvedRecently) if (e.exp <= now) resolvedRecently.delete(id)
|
|
272
|
+
while (resolvedRecently.size > 500) {
|
|
273
|
+
const first = resolvedRecently.keys().next().value
|
|
274
|
+
if (first === undefined) break
|
|
275
|
+
resolvedRecently.delete(first)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function wasResolvedRecently(requestID: string): boolean {
|
|
280
|
+
const e = resolvedRecently.get(requestID)
|
|
281
|
+
if (e === undefined) return false
|
|
282
|
+
if (e.exp <= Date.now()) {
|
|
283
|
+
resolvedRecently.delete(requestID)
|
|
284
|
+
return false
|
|
285
|
+
}
|
|
286
|
+
return true
|
|
287
|
+
}
|
|
288
|
+
/** 提示(卡片/文字菜单)实际投递后置标;若清槽回执因「无卡可关」被挂起且卡已迟到投递,补发回执。 */
|
|
289
|
+
function markPromptDelivered(userId: string, requestID: string): void {
|
|
290
|
+
const cur = pendingPermissions.get(userId)
|
|
291
|
+
if (cur?.request.id === requestID) cur.promptDelivered = true
|
|
292
|
+
const e = resolvedRecently.get(requestID)
|
|
293
|
+
if (!e?.notice) return
|
|
294
|
+
const n = e.notice
|
|
295
|
+
e.notice = undefined
|
|
296
|
+
void safeDeliver(
|
|
297
|
+
n.ctx,
|
|
298
|
+
`🔄 审批 ${requestID.slice(-8)} 已由${n.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${n.label}),QQ 审批自动关闭`,
|
|
299
|
+
).catch(() => {})
|
|
300
|
+
}
|
|
301
|
+
/** 发送窗:给 replied/resolve 一个取消在飞发卡的窗口;仅 SEND_GRACE_MS>0 才等待,0 保持原同步路径。 */
|
|
302
|
+
async function waitSendGrace(): Promise<void> {
|
|
303
|
+
if (SEND_GRACE_MS <= 0) return
|
|
304
|
+
await new Promise<void>((resolve) => {
|
|
305
|
+
const timer = setTimeout(resolve, SEND_GRACE_MS)
|
|
306
|
+
timer.unref?.()
|
|
307
|
+
})
|
|
308
|
+
}
|
|
237
309
|
// DEF-qqbot-20261112-5(2026-11-12 ZERO4 实测卡风暴实证):同一回合并联发起多个
|
|
238
310
|
// ask(异 request id)时,单挂槽跨请求覆写 + 双推送路径竞态会让先到的请求被重复
|
|
239
311
|
// 推卡(A 卡×2/B 卡×1 实证)。已推卡请求 id 环:同步认领(check+mark 原子,闭掉
|
|
@@ -303,6 +375,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
303
375
|
adopted.alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
|
|
304
376
|
adopted.timer = setTimeout(() => {
|
|
305
377
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
378
|
+
markResolvedRecently(request.id)
|
|
306
379
|
pendingPermissions.delete(ctx.userId)
|
|
307
380
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
308
381
|
deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
|
|
@@ -326,6 +399,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
326
399
|
const alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
|
|
327
400
|
const timer = setTimeout(() => {
|
|
328
401
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
402
|
+
markResolvedRecently(request.id)
|
|
329
403
|
pendingPermissions.delete(ctx.userId)
|
|
330
404
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
331
405
|
deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
|
|
@@ -354,13 +428,35 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
354
428
|
// 的请求(并发异请求覆写场景被其他路径推过)不再重复推卡。
|
|
355
429
|
if (claimCardPush(request.id)) {
|
|
356
430
|
void (async () => {
|
|
431
|
+
const isCancelled = () =>
|
|
432
|
+
wasResolvedRecently(request.id) || pendingPermissions.get(ctx.userId)?.request.id !== request.id
|
|
433
|
+
// 发卡前复查:clearIfResolved/resolve/TTL 可能已在异步任务起跑前清槽——死卡不得再发。
|
|
434
|
+
if (isCancelled()) {
|
|
435
|
+
console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`)
|
|
436
|
+
return
|
|
437
|
+
}
|
|
438
|
+
if (SEND_GRACE_MS > 0) {
|
|
439
|
+
await waitSendGrace()
|
|
440
|
+
if (isCancelled()) {
|
|
441
|
+
console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`)
|
|
442
|
+
return
|
|
443
|
+
}
|
|
444
|
+
}
|
|
357
445
|
const sentByCard = deps.sendApprovalPrompt
|
|
358
|
-
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot").catch(() => false)
|
|
446
|
+
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot", isCancelled).catch(() => false)
|
|
359
447
|
: false
|
|
448
|
+
if (sentByCard) markPromptDelivered(ctx.userId, request.id)
|
|
449
|
+
const stillPending = () => pendingPermissions.get(ctx.userId)?.request.id === request.id
|
|
450
|
+
if (!stillPending()) {
|
|
451
|
+
console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`)
|
|
452
|
+
return
|
|
453
|
+
}
|
|
360
454
|
if (!sentByCard) {
|
|
361
|
-
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot"))
|
|
362
|
-
|
|
363
|
-
|
|
455
|
+
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot"))
|
|
456
|
+
.then(() => markPromptDelivered(ctx.userId, request.id))
|
|
457
|
+
.catch((error) => {
|
|
458
|
+
console.error("[bridge] 发送审批请求失败:", error)
|
|
459
|
+
})
|
|
364
460
|
}
|
|
365
461
|
})()
|
|
366
462
|
}
|
|
@@ -370,6 +466,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
370
466
|
function resolve(userId: string, decision: PermissionDecision): void {
|
|
371
467
|
const entry = pendingPermissions.get(userId)
|
|
372
468
|
if (!entry) return
|
|
469
|
+
markResolvedRecently(entry.request.id)
|
|
373
470
|
clearTimers(entry)
|
|
374
471
|
pendingPermissions.delete(userId)
|
|
375
472
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
@@ -463,10 +560,13 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
463
560
|
const sentByCard = deps.sendApprovalPrompt
|
|
464
561
|
? await deps.sendApprovalPrompt(e.ctx, e.request, e.mainSessionId, e.origin).catch(() => false)
|
|
465
562
|
: false
|
|
563
|
+
if (sentByCard) markPromptDelivered(uid, e.request.id)
|
|
466
564
|
if (!sentByCard) {
|
|
467
|
-
await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin))
|
|
468
|
-
|
|
469
|
-
|
|
565
|
+
await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin))
|
|
566
|
+
.then(() => markPromptDelivered(uid, e.request.id))
|
|
567
|
+
.catch((error) => {
|
|
568
|
+
console.error("[bridge] 恢复审批推送失败:", error)
|
|
569
|
+
})
|
|
470
570
|
}
|
|
471
571
|
})()
|
|
472
572
|
}
|
|
@@ -491,6 +591,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
491
591
|
const directory = deps.directoryOf?.(userId)
|
|
492
592
|
const timer = setTimeout(() => {
|
|
493
593
|
if (pendingPermissions.get(userId)?.request.id !== request.id) return
|
|
594
|
+
markResolvedRecently(request.id)
|
|
494
595
|
pendingPermissions.delete(userId)
|
|
495
596
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
496
597
|
deps.onDecision?.(userId) // 外部审批 TTL 拒绝也要唤醒队列
|
|
@@ -519,26 +620,37 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
519
620
|
// 场景下本请求已被他路推过而重复推卡。
|
|
520
621
|
if (claimCardPush(request.id)) {
|
|
521
622
|
void (async () => {
|
|
522
|
-
// DEF-qqbot-20261114-P5
|
|
523
|
-
//
|
|
524
|
-
//
|
|
525
|
-
|
|
526
|
-
|
|
623
|
+
// DEF-qqbot-20261114-P5 + 2026-11-28 死卡竞态修复:发卡有 token+网络耗时,
|
|
624
|
+
// 期间桌面端可能已处理(联动清槽)。有效防线=①发卡前复查 ②发送层 isCancelled
|
|
625
|
+
// (token 后/QQ API 前放弃)③发送后槽位复查 ④文字降级前复查。
|
|
626
|
+
const isCancelled = () =>
|
|
627
|
+
wasResolvedRecently(request.id) || pendingPermissions.get(userId)?.request.id !== request.id
|
|
628
|
+
if (isCancelled()) {
|
|
629
|
+
console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`)
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
if (SEND_GRACE_MS > 0) {
|
|
633
|
+
await waitSendGrace()
|
|
634
|
+
if (isCancelled()) {
|
|
635
|
+
console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`)
|
|
636
|
+
return
|
|
637
|
+
}
|
|
638
|
+
}
|
|
527
639
|
const sentByCard = deps.sendApprovalPrompt
|
|
528
|
-
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin).catch(() => false)
|
|
640
|
+
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin, isCancelled).catch(() => false)
|
|
529
641
|
: false
|
|
642
|
+
if (sentByCard) markPromptDelivered(userId, request.id)
|
|
530
643
|
const stillPending = () => pendingPermissions.get(userId)?.request.id === request.id
|
|
531
644
|
if (!stillPending()) {
|
|
532
645
|
console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`)
|
|
646
|
+
return
|
|
533
647
|
}
|
|
534
648
|
if (!sentByCard) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
console.error("[bridge] 发送审批请求失败:", error)
|
|
541
|
-
})
|
|
649
|
+
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external"))
|
|
650
|
+
.then(() => markPromptDelivered(userId, request.id))
|
|
651
|
+
.catch((error) => {
|
|
652
|
+
console.error("[bridge] 发送审批请求失败:", error)
|
|
653
|
+
})
|
|
542
654
|
}
|
|
543
655
|
})()
|
|
544
656
|
}
|
|
@@ -552,6 +664,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
552
664
|
if (entry.request.id !== requestID) continue
|
|
553
665
|
if (sessionID && entry.request.sessionID && sessionID !== entry.request.sessionID) continue
|
|
554
666
|
const e = entry
|
|
667
|
+
markResolvedRecently(requestID)
|
|
555
668
|
clearTimers(e)
|
|
556
669
|
pendingPermissions.delete(uid)
|
|
557
670
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
@@ -565,16 +678,34 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
565
678
|
? "拒绝"
|
|
566
679
|
: `已处理(${String(reply ?? "未知")})`
|
|
567
680
|
console.log(`[perm] 联动清槽(源头已解决):uid=${uid.slice(0, 8)}… request=${requestID} reply=${String(reply)}`)
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
681
|
+
// 2026-11-28:「自动关闭」回执只在提示实际投递后发出——无卡可关时发回执属误报(owner 实证)。
|
|
682
|
+
// 提示未投递则挂起:卡若随后迟到投递成功(死卡)由 markPromptDelivered 补发;始终未投递则静默。
|
|
683
|
+
// resumedFromDisk 保持保守旧行为(重启前可能确有旧卡)。
|
|
684
|
+
if (e.promptDelivered || e.resumedFromDisk) {
|
|
685
|
+
void safeDeliver(
|
|
686
|
+
e.ctx,
|
|
687
|
+
`🔄 审批 ${requestID.slice(-8)} 已由${e.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${label}),QQ 审批自动关闭`,
|
|
688
|
+
).catch(() => {})
|
|
689
|
+
} else {
|
|
690
|
+
const r = resolvedRecently.get(requestID)
|
|
691
|
+
if (r) r.notice = { label, origin: e.origin, ctx: e.ctx }
|
|
692
|
+
console.log(`[perm] 提示未投递(无卡可关),自动关闭回执挂起 request=${requestID}`)
|
|
693
|
+
}
|
|
572
694
|
return true
|
|
573
695
|
}
|
|
574
696
|
return false
|
|
575
697
|
}
|
|
576
698
|
|
|
577
|
-
return {
|
|
699
|
+
return {
|
|
700
|
+
hasPending,
|
|
701
|
+
getPending,
|
|
702
|
+
waitForDecision,
|
|
703
|
+
resolve,
|
|
704
|
+
restore,
|
|
705
|
+
pushExternal: pushExternalImpl,
|
|
706
|
+
clearIfResolved,
|
|
707
|
+
wasResolvedRecently,
|
|
708
|
+
}
|
|
578
709
|
}
|
|
579
710
|
|
|
580
711
|
// 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
|