@linjz/opencode-qqbot 0.3.4 → 0.3.6
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 +74 -37
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +10 -1
- package/dist/openqq-bot.js +360 -69
- package/package.json +69 -59
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +934 -796
- package/src/commands.ts +554 -514
- package/src/config.ts +121 -121
- package/src/core/bot-launcher.ts +146 -134
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +284 -284
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -0
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +304 -304
- package/src/core/inflight-journal.ts +212 -151
- package/src/core/instance-lock.ts +122 -122
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +80 -0
- package/src/core/mirror.ts +173 -173
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +387 -386
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +65 -65
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +539 -539
- package/src/qq/gateway.ts +492 -492
- package/src/qq/media.ts +219 -204
- package/src/qq/sender.ts +300 -300
- package/src/qq/types.ts +154 -152
- 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 || 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
|
+
}
|