@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,146 +1,146 @@
1
- // @input: ../qq/api (getAccessToken, sendC2CMessage, sendGroupMessage, InlineKeyboard),
2
- // ../qq/types (MessageContext, InteractionEvent),
3
- // ./permission (formatPermissionPrompt, PendingPermission)
4
- // @output: encodeButtonData, decodeButtonData, buildApprovalKeyboard, sendApprovalCard,
5
- // handleApprovalInteraction
6
- // @pos: core - 卡片按钮审批(A 项 2026-10-29)
7
- //
8
- // 设计吸收自 P0 官方源:dsh-qqbot src/features/{button-utils,approval-channel}.ts
9
- // (button_data 明文 JSON + t 判别字段)与 @tencent-connect/qqbot-nodejs
10
- // protocol/types.ts(KeyboardButton/InlineKeyboard 形状)。
11
- // 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
12
- // 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
13
- // button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
14
- import { getAccessToken, sendC2CMessage, sendGroupMessage, type InlineKeyboard, type KeyboardButton } from "../qq/api.js"
15
- import type { InteractionEvent, MessageContext } from "../qq/types.js"
16
- import type { PermissionDecision, PermissionRequest } from "../opencode/client.js"
17
- import { formatPermissionPrompt, type PendingPermission } from "./permission.js"
18
-
19
- /** QQ 按钮 label 长度限制(dsh P0 实证) */
20
- export const BUTTON_LABEL_MAX = 10
21
-
22
- /** button_data 统一编码:明文 JSON + t 判别字段(dsh button-utils P0 格式),
23
- * r=request.id 防伪(槽位替换后旧按钮失效) */
24
- export interface ApprovalButtonData {
25
- t: "approval"
26
- r: string
27
- d: "once" | "always" | "reject" | "ignore"
28
- }
29
-
30
- export function encodeButtonData(data: ApprovalButtonData): string {
31
- return JSON.stringify(data)
32
- }
33
-
34
- export function decodeButtonData(raw: string | undefined): ApprovalButtonData | undefined {
35
- if (!raw) return undefined
36
- try {
37
- const parsed = JSON.parse(raw) as Partial<ApprovalButtonData>
38
- if (
39
- parsed !== null &&
40
- typeof parsed === "object" &&
41
- parsed.t === "approval" &&
42
- typeof parsed.r === "string" &&
43
- (parsed.d === "once" || parsed.d === "always" || parsed.d === "reject" || parsed.d === "ignore")
44
- ) {
45
- return parsed as ApprovalButtonData
46
- }
47
- } catch {
48
- // fall through
49
- }
50
- return undefined
51
- }
52
-
53
- function clipLabel(text: string): string {
54
- const s = text.trim()
55
- return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
56
- }
57
-
58
- function makeButton(label: string, style: number, data: ApprovalButtonData, ownerOpenid: string): KeyboardButton {
59
- // visited_label = 点击后的原生回显(QQ 客户端把已点按钮渲染为已访问态、其余置灰——
60
- // 这就是"dsh 点一个其余变灰"的平台原生机制,2026-10-30 用户要求抄的效果)
61
- const visited = data.d === "once" || data.d === "always" ? `✓ ${label}` : data.d === "reject" ? `✗ ${label}` : label
62
- return {
63
- id: `approval-${data.d}-${data.r}`.slice(0, 64),
64
- render_data: { label: clipLabel(label), visited_label: clipLabel(visited), style },
65
- // permission.type=2 + specify_user_ids:仅审批发起人可点(官方 P0 字段,
66
- // 防止群里其他人代点裁决)
67
- action: { type: 1, permission: { type: 2, specify_user_ids: [ownerOpenid] }, data: encodeButtonData(data) },
68
- }
69
- }
70
-
71
- /** 审批卡片键盘:允许一次 / 总是允许 / 拒绝 / 忽略(2×2 布局) */
72
- export function buildApprovalKeyboard(request: PermissionRequest, ownerOpenid: string): InlineKeyboard {
73
- const mk = (d: ApprovalButtonData["d"], label: string, style: number): KeyboardButton =>
74
- makeButton(label, style, { t: "approval", r: request.id, d }, ownerOpenid)
75
- return {
76
- content: {
77
- rows: [
78
- { buttons: [mk("once", "允许一次", 1), mk("always", "总是允许", 1)] },
79
- { buttons: [mk("reject", "拒绝", 0), mk("ignore", "忽略", 0)] },
80
- ],
81
- },
82
- }
83
- }
84
-
85
- export interface CardApprovalDeps {
86
- appId: string
87
- clientSecret: string
88
- }
89
-
90
- /** 发送审批卡片;成功=true。失败由调用方降级文字菜单(本函数不外抛)。 */
91
- export async function sendApprovalCard(
92
- deps: CardApprovalDeps,
93
- ctx: MessageContext,
94
- request: PermissionRequest,
95
- mainSessionId: string,
96
- ): Promise<boolean> {
97
- try {
98
- const token = await getAccessToken(deps.appId, deps.clientSecret)
99
- const keyboard = buildApprovalKeyboard(request, ctx.userId)
100
- // 正文复用现有格式化(用户看到的字段与文字菜单完全一致)
101
- const text = formatPermissionPrompt(request, mainSessionId)
102
- if (ctx.type === "group" && ctx.groupId) {
103
- await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
104
- } else {
105
- await sendC2CMessage(token, ctx.userId, text, ctx.msgId, undefined, true, keyboard)
106
- }
107
- console.log(`[card-approval] 审批卡片已发送 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
108
- return true
109
- } catch (error) {
110
- console.error("[card-approval] 审批卡片发送失败,将降级文字菜单:", error instanceof Error ? error.message : error)
111
- return false
112
- }
113
- }
114
-
115
- export interface ApprovalGateLike {
116
- getPending: (userId: string) => PendingPermission | undefined
117
- resolve: (userId: string, decision: PermissionDecision) => void
118
- }
119
-
120
- /** 互动回调 → 审批裁决。返回 true=已消费(含 ignore 吞掉);false=非本域事件。
121
- * 竞态:文字回复与按钮先到先赢(resolve 后槽位即清空,后到者自然落空)。
122
- * 身份:C2C 用 user_openid;群场景点击者走 group_member_openid(与挂起槽
123
- * 对群用户的 member_openid 索引一致,自我评审 2026-10-29 修复)。 */
124
- export function handleApprovalInteraction(event: InteractionEvent, gate: ApprovalGateLike): boolean {
125
- const userId = event.user_openid ?? event.group_member_openid
126
- if (!userId) return false
127
- const button = decodeButtonData(event.data?.resolved?.button_data)
128
- if (!button) return false
129
-
130
- const pending = gate.getPending(userId)
131
- if (!pending || pending.request.id !== button.r) {
132
- // 槽位已空或已被新请求替换:旧按钮点击,拒识(fail-closed,不误裁决新请求)
133
- console.log(`[card-approval] 拒识过期按钮点击 user=${userId.slice(0, 8)}… request=${button.r}`)
134
- return true
135
- }
136
-
137
- if (button.d === "ignore") {
138
- // 忽略=不决策:权限保持挂起,用户仍可文字回复或等 TTL 自动拒绝
139
- console.log(`[card-approval] 用户忽略审批请求 user=${userId.slice(0, 8)}… request=${button.r}`)
140
- return true
141
- }
142
-
143
- console.log(`[card-approval] 按钮裁决 user=${userId.slice(0, 8)}… request=${button.r} decision=${button.d}`)
144
- gate.resolve(userId, button.d)
145
- return true
146
- }
1
+ // @input: ../qq/api (getAccessToken, sendC2CMessage, sendGroupMessage, InlineKeyboard),
2
+ // ../qq/types (MessageContext, InteractionEvent),
3
+ // ./permission (formatPermissionPrompt, PendingPermission)
4
+ // @output: encodeButtonData, decodeButtonData, buildApprovalKeyboard, sendApprovalCard,
5
+ // handleApprovalInteraction
6
+ // @pos: core - 卡片按钮审批(A 项 2026-10-29)
7
+ //
8
+ // 设计吸收自 P0 官方源:dsh-qqbot src/features/{button-utils,approval-channel}.ts
9
+ // (button_data 明文 JSON + t 判别字段)与 @tencent-connect/qqbot-nodejs
10
+ // protocol/types.ts(KeyboardButton/InlineKeyboard 形状)。
11
+ // 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
12
+ // 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
13
+ // button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
14
+ import { getAccessToken, sendC2CMessage, sendGroupMessage, type InlineKeyboard, type KeyboardButton } from "../qq/api.js"
15
+ import type { InteractionEvent, MessageContext } from "../qq/types.js"
16
+ import type { PermissionDecision, PermissionRequest } from "../opencode/client.js"
17
+ import { formatPermissionPrompt, type PendingPermission } from "./permission.js"
18
+
19
+ /** QQ 按钮 label 长度限制(dsh P0 实证) */
20
+ export const BUTTON_LABEL_MAX = 10
21
+
22
+ /** button_data 统一编码:明文 JSON + t 判别字段(dsh button-utils P0 格式),
23
+ * r=request.id 防伪(槽位替换后旧按钮失效) */
24
+ export interface ApprovalButtonData {
25
+ t: "approval"
26
+ r: string
27
+ d: "once" | "always" | "reject" | "ignore"
28
+ }
29
+
30
+ export function encodeButtonData(data: ApprovalButtonData): string {
31
+ return JSON.stringify(data)
32
+ }
33
+
34
+ export function decodeButtonData(raw: string | undefined): ApprovalButtonData | undefined {
35
+ if (!raw) return undefined
36
+ try {
37
+ const parsed = JSON.parse(raw) as Partial<ApprovalButtonData>
38
+ if (
39
+ parsed !== null &&
40
+ typeof parsed === "object" &&
41
+ parsed.t === "approval" &&
42
+ typeof parsed.r === "string" &&
43
+ (parsed.d === "once" || parsed.d === "always" || parsed.d === "reject" || parsed.d === "ignore")
44
+ ) {
45
+ return parsed as ApprovalButtonData
46
+ }
47
+ } catch {
48
+ // fall through
49
+ }
50
+ return undefined
51
+ }
52
+
53
+ function clipLabel(text: string): string {
54
+ const s = text.trim()
55
+ return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
56
+ }
57
+
58
+ function makeButton(label: string, style: number, data: ApprovalButtonData, ownerOpenid: string): KeyboardButton {
59
+ // visited_label = 点击后的原生回显(QQ 客户端把已点按钮渲染为已访问态、其余置灰——
60
+ // 这就是"dsh 点一个其余变灰"的平台原生机制,2026-10-30 用户要求抄的效果)
61
+ const visited = data.d === "once" || data.d === "always" ? `✓ ${label}` : data.d === "reject" ? `✗ ${label}` : label
62
+ return {
63
+ id: `approval-${data.d}-${data.r}`.slice(0, 64),
64
+ render_data: { label: clipLabel(label), visited_label: clipLabel(visited), style },
65
+ // permission.type=2 + specify_user_ids:仅审批发起人可点(官方 P0 字段,
66
+ // 防止群里其他人代点裁决)
67
+ action: { type: 1, permission: { type: 2, specify_user_ids: [ownerOpenid] }, data: encodeButtonData(data) },
68
+ }
69
+ }
70
+
71
+ /** 审批卡片键盘:允许一次 / 总是允许 / 拒绝 / 忽略(2×2 布局) */
72
+ export function buildApprovalKeyboard(request: PermissionRequest, ownerOpenid: string): InlineKeyboard {
73
+ const mk = (d: ApprovalButtonData["d"], label: string, style: number): KeyboardButton =>
74
+ makeButton(label, style, { t: "approval", r: request.id, d }, ownerOpenid)
75
+ return {
76
+ content: {
77
+ rows: [
78
+ { buttons: [mk("once", "允许一次", 1), mk("always", "总是允许", 1)] },
79
+ { buttons: [mk("reject", "拒绝", 0), mk("ignore", "忽略", 0)] },
80
+ ],
81
+ },
82
+ }
83
+ }
84
+
85
+ export interface CardApprovalDeps {
86
+ appId: string
87
+ clientSecret: string
88
+ }
89
+
90
+ /** 发送审批卡片;成功=true。失败由调用方降级文字菜单(本函数不外抛)。 */
91
+ export async function sendApprovalCard(
92
+ deps: CardApprovalDeps,
93
+ ctx: MessageContext,
94
+ request: PermissionRequest,
95
+ mainSessionId: string,
96
+ ): Promise<boolean> {
97
+ try {
98
+ const token = await getAccessToken(deps.appId, deps.clientSecret)
99
+ const keyboard = buildApprovalKeyboard(request, ctx.userId)
100
+ // 正文复用现有格式化(用户看到的字段与文字菜单完全一致)
101
+ const text = formatPermissionPrompt(request, mainSessionId)
102
+ if (ctx.type === "group" && ctx.groupId) {
103
+ await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
104
+ } else {
105
+ await sendC2CMessage(token, ctx.userId, text, ctx.msgId, undefined, true, keyboard)
106
+ }
107
+ console.log(`[card-approval] 审批卡片已发送 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
108
+ return true
109
+ } catch (error) {
110
+ console.error("[card-approval] 审批卡片发送失败,将降级文字菜单:", error instanceof Error ? error.message : error)
111
+ return false
112
+ }
113
+ }
114
+
115
+ export interface ApprovalGateLike {
116
+ getPending: (userId: string) => PendingPermission | undefined
117
+ resolve: (userId: string, decision: PermissionDecision) => void
118
+ }
119
+
120
+ /** 互动回调 → 审批裁决。返回 true=已消费(含 ignore 吞掉);false=非本域事件。
121
+ * 竞态:文字回复与按钮先到先赢(resolve 后槽位即清空,后到者自然落空)。
122
+ * 身份:C2C 用 user_openid;群场景点击者走 group_member_openid(与挂起槽
123
+ * 对群用户的 member_openid 索引一致,自我评审 2026-10-29 修复)。 */
124
+ export function handleApprovalInteraction(event: InteractionEvent, gate: ApprovalGateLike): boolean {
125
+ const userId = event.user_openid ?? event.group_member_openid
126
+ if (!userId) return false
127
+ const button = decodeButtonData(event.data?.resolved?.button_data)
128
+ if (!button) return false
129
+
130
+ const pending = gate.getPending(userId)
131
+ if (!pending || pending.request.id !== button.r) {
132
+ // 槽位已空或已被新请求替换:旧按钮点击,拒识(fail-closed,不误裁决新请求)
133
+ console.log(`[card-approval] 拒识过期按钮点击 user=${userId.slice(0, 8)}… request=${button.r}`)
134
+ return true
135
+ }
136
+
137
+ if (button.d === "ignore") {
138
+ // 忽略=不决策:权限保持挂起,用户仍可文字回复或等 TTL 自动拒绝
139
+ console.log(`[card-approval] 用户忽略审批请求 user=${userId.slice(0, 8)}… request=${button.r}`)
140
+ return true
141
+ }
142
+
143
+ console.log(`[card-approval] 按钮裁决 user=${userId.slice(0, 8)}… request=${button.r} decision=${button.d}`)
144
+ gate.resolve(userId, button.d)
145
+ return true
146
+ }
@@ -1,78 +1,78 @@
1
- // @input: (模块级单例缓存)
2
- // @output: recordMessage, resolveQuote, scopeKeyOf, resetContextBuffer(测试用)
3
- // @pos: core - 消息上下文索引缓存(引用消息解析)
4
- //
5
- // 设计吸收自 P0:qqbot-nodejs middleware/quote-ref.ts(MemoryRefIndexStore +
6
- // msgIdx 索引 + 解析)。QQ C2C/群消息的引用经由 message_reference.message_id
7
- // 透传;QQ 不提供 C2C 历史消息拉取,故引用解析只能靠本缓存——我方发出的回复
8
- // 也记录(消息 id 取服务端回执 MessageResponse.id),保证"引用 AI 答案"可解析。
9
- // 单进程 bot 用进程内 LRU(每域 200 条)足够;跨重启引用解析为空属可接受降级。
10
- interface RefEntry {
11
- text: string
12
- at: number
13
- }
14
-
15
- const MAX_ENTRIES_PER_SCOPE = 200
16
- const scopeBuffers = new Map<string, Map<string, RefEntry>>()
17
-
18
- /** 域键:C2C 按用户,群聊按群(引用多在群内发生) */
19
- export function scopeKeyOf(ctx: { type: string; userId: string; groupId?: string }): string {
20
- return ctx.type === "group" && ctx.groupId ? `group:${ctx.groupId}` : `c2c:${ctx.userId}`
21
- }
22
-
23
- function bufferOf(scope: string): Map<string, RefEntry> {
24
- let b = scopeBuffers.get(scope)
25
- if (!b) {
26
- b = new Map()
27
- scopeBuffers.set(scope, b)
28
- }
29
- return b
30
- }
31
-
32
- /** 记录一条消息(入站用户消息 + 我方出站回复) */
33
- export function recordMessage(scope: string, msgId: string, text: string): void {
34
- if (!msgId) return
35
- const b = bufferOf(scope)
36
- if (b.size >= MAX_ENTRIES_PER_SCOPE && !b.has(msgId)) {
37
- const first = b.keys().next().value
38
- if (first !== undefined) b.delete(first)
39
- }
40
- b.set(msgId, { text, at: Date.now() })
41
- }
42
-
43
- /** 按引用 id 解析被引消息文本;不存在返回 null */
44
- export function resolveQuote(scope: string, referencedMsgId: string): string | null {
45
- const entry = scopeBuffers.get(scope)?.get(referencedMsgId)
46
- return entry?.text ?? null
47
- }
48
-
49
- // N 项(2026-10-30,吸收竞品 opencode-qq-v2 util/quote.js):引用消息双通道——
50
- // QQ 在 message_type=103 时把被引内容嵌在 msg_elements 里随事件透传(官方未完全
51
- // 文档化结构,做防御性递归提取);命中即权威来源,不再依赖本缓存(跨重启/引用
52
- // 老消息也能解析)。提取为空时调用方回落 resolveQuote 缓存通道。
53
- export function extractEmbeddedQuote(event: { message_type?: unknown; msg_elements?: unknown } | undefined): string | null {
54
- if (!event || Number(event.message_type) !== 103 || !event.msg_elements) return null
55
- const out: string[] = []
56
- const walk = (node: unknown, depth: number): void => {
57
- if (depth > 8 || out.join("\n").length > 4000) return
58
- if (Array.isArray(node)) {
59
- for (const item of node) walk(item, depth + 1)
60
- return
61
- }
62
- if (node && typeof node === "object") {
63
- const obj = node as Record<string, unknown>
64
- if (typeof obj.content === "string" && obj.content.trim()) out.push(obj.content.trim())
65
- for (const key of Object.keys(obj)) {
66
- if (key !== "content") walk(obj[key], depth + 1)
67
- }
68
- }
69
- }
70
- walk(event.msg_elements, 0)
71
- const text = out.join("\n").trim()
72
- return (text.length > 2000 ? `${text.slice(0, 2000)}…` : text) || null // 截断必带省略号;空内容回落缓存通道
73
- }
74
-
75
- /** 测试/运维用:清空全部缓存 */
76
- export function resetContextBuffer(): void {
77
- scopeBuffers.clear()
78
- }
1
+ // @input: (模块级单例缓存)
2
+ // @output: recordMessage, resolveQuote, scopeKeyOf, resetContextBuffer(测试用)
3
+ // @pos: core - 消息上下文索引缓存(引用消息解析)
4
+ //
5
+ // 设计吸收自 P0:qqbot-nodejs middleware/quote-ref.ts(MemoryRefIndexStore +
6
+ // msgIdx 索引 + 解析)。QQ C2C/群消息的引用经由 message_reference.message_id
7
+ // 透传;QQ 不提供 C2C 历史消息拉取,故引用解析只能靠本缓存——我方发出的回复
8
+ // 也记录(消息 id 取服务端回执 MessageResponse.id),保证"引用 AI 答案"可解析。
9
+ // 单进程 bot 用进程内 LRU(每域 200 条)足够;跨重启引用解析为空属可接受降级。
10
+ interface RefEntry {
11
+ text: string
12
+ at: number
13
+ }
14
+
15
+ const MAX_ENTRIES_PER_SCOPE = 200
16
+ const scopeBuffers = new Map<string, Map<string, RefEntry>>()
17
+
18
+ /** 域键:C2C 按用户,群聊按群(引用多在群内发生) */
19
+ export function scopeKeyOf(ctx: { type: string; userId: string; groupId?: string }): string {
20
+ return ctx.type === "group" && ctx.groupId ? `group:${ctx.groupId}` : `c2c:${ctx.userId}`
21
+ }
22
+
23
+ function bufferOf(scope: string): Map<string, RefEntry> {
24
+ let b = scopeBuffers.get(scope)
25
+ if (!b) {
26
+ b = new Map()
27
+ scopeBuffers.set(scope, b)
28
+ }
29
+ return b
30
+ }
31
+
32
+ /** 记录一条消息(入站用户消息 + 我方出站回复) */
33
+ export function recordMessage(scope: string, msgId: string, text: string): void {
34
+ if (!msgId) return
35
+ const b = bufferOf(scope)
36
+ if (b.size >= MAX_ENTRIES_PER_SCOPE && !b.has(msgId)) {
37
+ const first = b.keys().next().value
38
+ if (first !== undefined) b.delete(first)
39
+ }
40
+ b.set(msgId, { text, at: Date.now() })
41
+ }
42
+
43
+ /** 按引用 id 解析被引消息文本;不存在返回 null */
44
+ export function resolveQuote(scope: string, referencedMsgId: string): string | null {
45
+ const entry = scopeBuffers.get(scope)?.get(referencedMsgId)
46
+ return entry?.text ?? null
47
+ }
48
+
49
+ // N 项(2026-10-30,吸收竞品 opencode-qq-v2 util/quote.js):引用消息双通道——
50
+ // QQ 在 message_type=103 时把被引内容嵌在 msg_elements 里随事件透传(官方未完全
51
+ // 文档化结构,做防御性递归提取);命中即权威来源,不再依赖本缓存(跨重启/引用
52
+ // 老消息也能解析)。提取为空时调用方回落 resolveQuote 缓存通道。
53
+ export function extractEmbeddedQuote(event: { message_type?: unknown; msg_elements?: unknown } | undefined): string | null {
54
+ if (!event || Number(event.message_type) !== 103 || !event.msg_elements) return null
55
+ const out: string[] = []
56
+ const walk = (node: unknown, depth: number): void => {
57
+ if (depth > 8 || out.join("\n").length > 4000) return
58
+ if (Array.isArray(node)) {
59
+ for (const item of node) walk(item, depth + 1)
60
+ return
61
+ }
62
+ if (node && typeof node === "object") {
63
+ const obj = node as Record<string, unknown>
64
+ if (typeof obj.content === "string" && obj.content.trim()) out.push(obj.content.trim())
65
+ for (const key of Object.keys(obj)) {
66
+ if (key !== "content") walk(obj[key], depth + 1)
67
+ }
68
+ }
69
+ }
70
+ walk(event.msg_elements, 0)
71
+ const text = out.join("\n").trim()
72
+ return (text.length > 2000 ? `${text.slice(0, 2000)}…` : text) || null // 截断必带省略号;空内容回落缓存通道
73
+ }
74
+
75
+ /** 测试/运维用:清空全部缓存 */
76
+ export function resetContextBuffer(): void {
77
+ scopeBuffers.clear()
78
+ }
@@ -2,7 +2,7 @@
2
2
  // @output: createDelivery
3
3
  // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
4
  // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
- import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from "fs"
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
6
6
  import { join } from "path"
7
7
  import { createHash } from "node:crypto"
8
8
  import { homedir } from "os"
@@ -57,6 +57,38 @@ function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warne
57
57
  // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
58
58
  export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
59
59
 
60
+ // QQ 渲染适配(2026-11-03 用户双端截图实证):QQ 官方 markdown 渲染器把跨
61
+ // 段落的有序列表续接编号(原文 1./2. 渲染成 3./4.),与桌面端所见不一致。
62
+ // 对策=列表标记 `N.` 统一改写为 `N)`:非 CommonMark 列表语法 → 字面保留,
63
+ // 编号所见即原文,桌面与 QQ 端逐字一致;变换幂等(N) 不再被任何渲染器续编)。
64
+ // 代码围栏(```/~~~)内不动;仅行首(含缩进)的 `N. ` 命中,行内「1.5 版本」
65
+ // 类文本无空格不受影响。导出供测试。
66
+ // 顿号实测(2026-11-03 用户截图回传):「N、」与「一、」在 QQ 被动通道 100% 保真,
67
+ // 「N.」却被整条消息全局续编(连行内点号数字都会渗染起始值)。所以平面化目标
68
+ // 从 N) 升级为 N、——与原生顿号列表视觉一致,编号所见即原文。
69
+ // 变换幂等(N、 再进来不匹配行首 N. 模式,原样通过)。
70
+ export function qqListNormalize(text: string): string {
71
+ const lines = text.split("\n")
72
+ let fence = false
73
+ let fenceMarker = ""
74
+ for (let i = 0; i < lines.length; i++) {
75
+ const fm = lines[i].trim().match(/^(```|~~~)/)
76
+ if (fm) {
77
+ if (!fence) {
78
+ fence = true
79
+ fenceMarker = fm[1]
80
+ } else if (fm[1] === fenceMarker) {
81
+ fence = false
82
+ fenceMarker = ""
83
+ }
84
+ continue
85
+ }
86
+ if (fence) continue
87
+ lines[i] = lines[i].replace(/^(\s*)(\d+)\. /, "$1$2、")
88
+ }
89
+ return lines.join("\n")
90
+ }
91
+
60
92
  export interface DeliveryAttempt {
61
93
  text: string
62
94
  at: number
@@ -75,8 +107,10 @@ export function shouldSuppressDuplicate(
75
107
  text: string,
76
108
  now: number,
77
109
  ttlMs = DELIVERY_DEDUPE_TTL_MS,
110
+ identity = text,
78
111
  ): boolean {
79
- return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs
112
+ // 长度必须看原始正文;identity 可能是较短的 userId:sha256 键,不能拿它做长文门槛。
113
+ return text.length >= 200 && previous?.text === identity && now - previous.at < ttlMs
80
114
  }
81
115
 
82
116
  // 仅存用户键+内容哈希,不把回复正文写进运行数据。跨重启也能识别同文回复。
@@ -102,9 +136,69 @@ function saveDeliveryAttempts(entries: ReadonlyMap<string, DeliveryAttempt>): vo
102
136
  .filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS)
103
137
  .map((entry) => ({ key: entry.text, at: entry.at }))
104
138
  mkdirSync(join(DELIVERY_DEDUPE_FILE, ".."), { recursive: true })
105
- const tmp = `${DELIVERY_DEDUPE_FILE}.tmp`
106
- writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 })
107
- renameSync(tmp, DELIVERY_DEDUPE_FILE)
139
+ const tmp = `${DELIVERY_DEDUPE_FILE}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
140
+ try {
141
+ writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 })
142
+ renameSync(tmp, DELIVERY_DEDUPE_FILE)
143
+ } catch (error) {
144
+ try { unlinkSync(tmp) } catch { /* 已改名或清理失败 */ }
145
+ throw error
146
+ }
147
+ }
148
+
149
+ // 多执行体共用同一把短文件锁:读取→判定→占位必须原子完成,否则不同进程会同时放行同文回复。
150
+ const DELIVERY_LOCK_STALE_MS = 30_000
151
+ const DELIVERY_LOCK_WAIT_MS = 5_000
152
+ const deliverySleepArray = new Int32Array(new SharedArrayBuffer(4))
153
+
154
+ function withDeliveryLock<T>(fn: () => T): T {
155
+ mkdirSync(join(DELIVERY_DEDUPE_FILE, ".."), { recursive: true })
156
+ const lockPath = `${DELIVERY_DEDUPE_FILE}.lock`
157
+ const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
158
+ const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS
159
+ for (;;) {
160
+ try {
161
+ const fd = openSync(lockPath, "wx", 0o600)
162
+ try { writeFileSync(fd, token) } finally { closeSync(fd) }
163
+ break
164
+ } catch (error) {
165
+ try {
166
+ if (Date.now() - statSync(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS) unlinkSync(lockPath)
167
+ } catch { /* 锁不存在/另一进程正在接管 */ }
168
+ if (Date.now() >= deadline) throw new Error(`同文投递锁等待超时: ${error instanceof Error ? error.message : error}`)
169
+ Atomics.wait(deliverySleepArray, 0, 0, 10)
170
+ }
171
+ }
172
+ try {
173
+ return fn()
174
+ } finally {
175
+ try {
176
+ if (readFileSync(lockPath, "utf-8") === token) unlinkSync(lockPath)
177
+ } catch { /* 已被 stale 清理 */ }
178
+ }
179
+ }
180
+
181
+ /** 返回占位键;24h 内同文长回复已占位时返回 null。发送失败必须按原时间戳释放。 */
182
+ export function reserveDeliveryAttempt(userId: string, text: string, now = Date.now()): string | null {
183
+ const attemptKey = deliveryAttemptKey(userId, text)
184
+ return withDeliveryLock(() => {
185
+ const entries = loadDeliveryAttempts()
186
+ if (shouldSuppressDuplicate(entries.get(attemptKey), text, now, DELIVERY_DEDUPE_TTL_MS, attemptKey)) return null
187
+ entries.set(attemptKey, { text: attemptKey, at: now })
188
+ saveDeliveryAttempts(entries)
189
+ return attemptKey
190
+ })
191
+ }
192
+
193
+ export function releaseDeliveryAttempt(userId: string, text: string, at: number): void {
194
+ const attemptKey = deliveryAttemptKey(userId, text)
195
+ withDeliveryLock(() => {
196
+ const entries = loadDeliveryAttempts()
197
+ if (entries.get(attemptKey)?.at === at) {
198
+ entries.delete(attemptKey)
199
+ saveDeliveryAttempts(entries)
200
+ }
201
+ })
108
202
  }
109
203
 
110
204
  // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
@@ -162,8 +256,6 @@ export function createDelivery(
162
256
  const pushQueues = new Map<string, PushQueue>()
163
257
  // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
164
258
  const undelivered = new Set<string>()
165
- // 同文长回复幂等(跨重启 24h);尝试前占位防并发,失败立即释放允许重试。
166
- const recentDeliveries = loadDeliveryAttempts()
167
259
  const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
168
260
  // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
169
261
  // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
@@ -214,20 +306,20 @@ export function createDelivery(
214
306
  // 投递失败则把贴条放回(留待下次),成功才算消化。
215
307
  async function deliver(ctx: MessageContext, text: string): Promise<void> {
216
308
  const now = Date.now()
217
- const attemptKey = deliveryAttemptKey(ctx.userId, text)
218
- if (shouldSuppressDuplicate(recentDeliveries.get(attemptKey), attemptKey, now)) {
309
+ // 跨进程原子占位:直答/镜像/恢复即使落在不同执行体,同文长回复也只放行一次。
310
+ const attemptKey = reserveDeliveryAttempt(ctx.userId, text, now)
311
+ if (!attemptKey) {
219
312
  console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`)
220
313
  return
221
314
  }
222
- recentDeliveries.set(attemptKey, { text: attemptKey, at: now })
223
315
  const hadNotice = undelivered.delete(ctx.userId)
224
- const body = hadNotice ? UNDELIVERED_NOTICE + text : text
316
+ // QQ 渲染适配:有序列表改写,防 QQ 端跨段落续编(桌面所见=QQ 所见)
317
+ const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text)
225
318
  try {
226
319
  await deliverCore(ctx, body)
227
- saveDeliveryAttempts(recentDeliveries)
228
320
  } catch (error) {
229
321
  // 发送失败不占去重位,后续恢复/重试仍可送达。
230
- if (recentDeliveries.get(attemptKey)?.at === now) recentDeliveries.delete(attemptKey)
322
+ releaseDeliveryAttempt(ctx.userId, text, now)
231
323
  if (hadNotice) undelivered.add(ctx.userId)
232
324
  throw error
233
325
  }