@linjz/opencode-qqbot 0.3.19 → 0.3.20
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/PRIVACY.md +87 -0
- package/README.md +10 -1
- package/README.zh-CN.md +10 -1
- package/THIRD_PARTY_NOTICES.md +136 -0
- package/dist/openqq-bot.js +565 -164
- package/package.json +4 -2
- package/src/bridge.ts +130 -7
- package/src/core/card-approval.ts +4 -3
- package/src/core/context-buffer.ts +6 -6
- package/src/core/cron-reminders.ts +1 -1
- package/src/core/delivery.ts +131 -37
- package/src/core/instance-lock.ts +1 -1
- package/src/core/mirror-anchors.ts +145 -0
- package/src/core/mirror.ts +112 -22
- package/src/core/notices.ts +2 -2
- package/src/core/notify-sink.ts +1 -1
- package/src/core/outbound-sanitize.ts +3 -1
- package/src/core/reply-limiter.ts +3 -2
- package/src/core/send-media.ts +6 -6
- package/src/core/stt.ts +1 -1
- package/src/index.ts +1 -1
- package/src/opencode/mirror.ts +54 -2
- package/src/opencode/sessions.ts +28 -2
- package/src/qq/api.ts +9 -1
- package/src/qq/gateway.ts +16 -5
- package/src/qq/media.ts +1 -1
- package/src/qq/sender.ts +64 -14
- package/src/qq/types.ts +4 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linjz/opencode-qqbot",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.20",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
|
|
6
6
|
"exports": {
|
|
@@ -31,7 +31,9 @@
|
|
|
31
31
|
"bin",
|
|
32
32
|
"src",
|
|
33
33
|
"dist",
|
|
34
|
-
"tsconfig.json"
|
|
34
|
+
"tsconfig.json",
|
|
35
|
+
"THIRD_PARTY_NOTICES.md",
|
|
36
|
+
"PRIVACY.md"
|
|
35
37
|
],
|
|
36
38
|
"keywords": [
|
|
37
39
|
"opencode-plugin",
|
package/src/bridge.ts
CHANGED
|
@@ -38,6 +38,11 @@ import {
|
|
|
38
38
|
type WatchApi,
|
|
39
39
|
} from "./commands.js"
|
|
40
40
|
import { createMirror } from "./core/mirror.js"
|
|
41
|
+
import {
|
|
42
|
+
createMirrorAnchorStore,
|
|
43
|
+
type MirrorAnchorEntry,
|
|
44
|
+
} from "./core/mirror-anchors.js"
|
|
45
|
+
import { clipDigestTitle, digestSessionLabel } from "./opencode/mirror.js"
|
|
41
46
|
import { MessageQueue, laneKeyOf, laneScope, sessionIdOfLane, userIdOfLane, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
|
|
42
47
|
import { classifyProviderError, rescueText } from "./core/error-rescue.js"
|
|
43
48
|
import { NOTICE } from "./core/notices.js"
|
|
@@ -63,7 +68,7 @@ import {
|
|
|
63
68
|
type PermOrigin,
|
|
64
69
|
} from "./core/permission.js"
|
|
65
70
|
import { truncate } from "./core/util.js"
|
|
66
|
-
import { createDelivery, qqPromptHints } from "./core/delivery.js"
|
|
71
|
+
import { createDelivery, qqPromptHints, UNDELIVERED_NOTICE } from "./core/delivery.js"
|
|
67
72
|
import { createNotifySink } from "./core/notify-sink.js"
|
|
68
73
|
import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
|
|
69
74
|
import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
|
|
@@ -103,6 +108,49 @@ export function isSessionBusyError(error: unknown): boolean {
|
|
|
103
108
|
return /active prompt|[-−]32603/.test(message)
|
|
104
109
|
}
|
|
105
110
|
|
|
111
|
+
export function isMirrorDigestText(text: string | null | undefined): boolean {
|
|
112
|
+
let value = text?.trim() ?? ""
|
|
113
|
+
if (value.startsWith(UNDELIVERED_NOTICE.trim())) {
|
|
114
|
+
value = value.slice(UNDELIVERED_NOTICE.trim().length).trimStart()
|
|
115
|
+
}
|
|
116
|
+
return value.startsWith("📋 桌面问答摘要") ||
|
|
117
|
+
value.startsWith("🎯 目标续跑摘要") ||
|
|
118
|
+
value.startsWith("📋 摘要续") ||
|
|
119
|
+
value.startsWith("🎯 摘要续")
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function commandNeedsMirrorAnchorGate(content: string): boolean {
|
|
123
|
+
const match = content.trim().match(/^\/(queue|amend|goal|btw)\b([\s\S]*)$/i)
|
|
124
|
+
if (!match) return false
|
|
125
|
+
const args = (match[2] ?? "").trim()
|
|
126
|
+
if (!args) return false
|
|
127
|
+
if (match[1]?.toLowerCase() === "queue" && /^(?:all(?:\s+\d+)?|clear|drop\s+\d+|\d+)$/i.test(args)) {
|
|
128
|
+
return false
|
|
129
|
+
}
|
|
130
|
+
return true
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type MirrorAnchorGateDecision =
|
|
134
|
+
| { kind: "pass" }
|
|
135
|
+
| { kind: "match"; anchor: MirrorAnchorEntry }
|
|
136
|
+
| { kind: "conflict"; anchor: MirrorAnchorEntry }
|
|
137
|
+
| { kind: "unknown" }
|
|
138
|
+
|
|
139
|
+
/** 纯路由判定:只有本人有效摘要锚点与入站绑定快照相同才允许沿摘要语境继续。 */
|
|
140
|
+
export function decideMirrorAnchorGate(input: {
|
|
141
|
+
anchor?: MirrorAnchorEntry
|
|
142
|
+
quoteText?: string | null
|
|
143
|
+
currentSessionId: string | null
|
|
144
|
+
}): MirrorAnchorGateDecision {
|
|
145
|
+
if (input.anchor) {
|
|
146
|
+
return input.currentSessionId && input.anchor.sessionId === input.currentSessionId
|
|
147
|
+
? { kind: "match", anchor: input.anchor }
|
|
148
|
+
: { kind: "conflict", anchor: input.anchor }
|
|
149
|
+
}
|
|
150
|
+
if (isMirrorDigestText(input.quoteText)) return { kind: "unknown" }
|
|
151
|
+
return { kind: "pass" }
|
|
152
|
+
}
|
|
153
|
+
|
|
106
154
|
// E 闲置回收纯函数(导出供测试,2026-10-29):返回应回收的闲置会话 id——
|
|
107
155
|
// 超过 idleMs 无活动且未被观察(/status watch on)显式盯住的会话。
|
|
108
156
|
export function evictableIdleSessions(
|
|
@@ -418,6 +466,7 @@ export function createBridge(
|
|
|
418
466
|
const roleFile = (name: string): string => storageFile(name, storageAppId)
|
|
419
467
|
// 在途台账按角色绑定实例(同进程多角色并发不互踩,见 inflight-journal 工厂)
|
|
420
468
|
const inflight = createInflightJournal(storageAppId ? roleFile("inflight.json") : undefined)
|
|
469
|
+
const mirrorAnchors = createMirrorAnchorStore(roleFile("mirror-anchors.json"))
|
|
421
470
|
// H2 停滞提醒文案状态开关就用现成 env 读取风格;这里同步实现⑦开关——
|
|
422
471
|
// 2026-11-03 用户拍板:「已收到」回执默认不发(非调试无价值),调试期在
|
|
423
472
|
// ~/.openqq/.env 设 QQ_ACK_RECEIPT=1 开启。loadEnvFile 全量注入 process.env,
|
|
@@ -471,7 +520,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
471
520
|
// Q2:会话工具统计(/progress 手动查询用,本地事件源,零模型成本)
|
|
472
521
|
const turnStats = new Map<string, { tools: number; failed: number; lastTool: string; lastAt: number }>()
|
|
473
522
|
|
|
474
|
-
// E(2026-10-29
|
|
523
|
+
// E(2026-10-29 同步升级,参考 dsh session/idle-evictor):闲置会话回收——
|
|
475
524
|
// 长期无活动的会话退订 SSE,降 opencode 服务端事件扇出;/watch 显式盯着的
|
|
476
525
|
// 会话豁免;用户再来消息时 subscribeSession 会重新挂上。env QQ_SESSION_IDLE_HOURS。
|
|
477
526
|
const sessionLastActivity = new Map<string, number>()
|
|
@@ -906,7 +955,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
906
955
|
}
|
|
907
956
|
|
|
908
957
|
// O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
|
|
909
|
-
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(
|
|
958
|
+
const { enqueuePush, safeDeliver, sendReply, deliver, consumePartialFailure } = createDelivery(
|
|
910
959
|
config,
|
|
911
960
|
lastCtx,
|
|
912
961
|
isBoundSession,
|
|
@@ -929,6 +978,55 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
929
978
|
}
|
|
930
979
|
}
|
|
931
980
|
|
|
981
|
+
const mirrorQuoteCache = new WeakMap<MessageContext, { embedded: string | null; quoted: string | null }>()
|
|
982
|
+
function quoteContextOf(ctx: MessageContext): { embedded: string | null; quoted: string | null } {
|
|
983
|
+
const cached = mirrorQuoteCache.get(ctx)
|
|
984
|
+
if (cached) return cached
|
|
985
|
+
const embedded = extractEmbeddedQuote(ctx.rawEvent)
|
|
986
|
+
const quoted = embedded ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null)
|
|
987
|
+
const result = { embedded, quoted }
|
|
988
|
+
mirrorQuoteCache.set(ctx, result)
|
|
989
|
+
return result
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function mirrorAnchorDecision(ctx: MessageContext, currentSessionId: string | null): MirrorAnchorGateDecision {
|
|
993
|
+
const { quoted } = quoteContextOf(ctx)
|
|
994
|
+
const anchor = mirrorAnchors.resolve(ctx.userId, ctx.referencedMsgId)
|
|
995
|
+
return decideMirrorAnchorGate({ anchor, quoteText: quoted, currentSessionId })
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
function anchorRejectText(
|
|
999
|
+
decision: Extract<MirrorAnchorGateDecision, { kind: "conflict" | "unknown" }>,
|
|
1000
|
+
currentSessionId: string | null,
|
|
1001
|
+
userId: string,
|
|
1002
|
+
): string {
|
|
1003
|
+
if (decision.kind === "unknown") {
|
|
1004
|
+
return "⚠️ 无法确认这条旧摘要所属会话,本次未发送。请去掉引用后重发,或先通过 /sessions 切换到摘要所属会话。"
|
|
1005
|
+
}
|
|
1006
|
+
const source = `${clipDigestTitle(redactSecrets(decision.anchor.title))}(${digestSessionLabel(decision.anchor.sessionId)})`
|
|
1007
|
+
const current = sessions.getSession(userId)
|
|
1008
|
+
const currentLabel = currentSessionId
|
|
1009
|
+
? `${clipDigestTitle(redactSecrets(current?.title ?? ""))}(${digestSessionLabel(currentSessionId)})`
|
|
1010
|
+
: "无绑定会话"
|
|
1011
|
+
return `⚠️ 这条回复引用的是 ${source} 的摘要,当前绑定为 ${currentLabel}。\n为避免误操作,本次未发送。请用 /sessions 切回该会话后重发;或去掉引用,明确发送到当前会话。`
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
async function rejectMirrorAnchor(
|
|
1015
|
+
ctx: MessageContext,
|
|
1016
|
+
decision: Extract<MirrorAnchorGateDecision, { kind: "conflict" | "unknown" }>,
|
|
1017
|
+
currentSessionId: string | null,
|
|
1018
|
+
): Promise<void> {
|
|
1019
|
+
const anchor = decision.kind === "conflict" ? decision.anchor.sessionId : "unknown"
|
|
1020
|
+
console.log(
|
|
1021
|
+
`[anchor-gate] result=${decision.kind} user=${ctx.userId.slice(0, 8)}… anchor=${anchor === "unknown" ? anchor : digestSessionLabel(anchor)} current=${currentSessionId ? digestSessionLabel(currentSessionId) : "∅"}`,
|
|
1022
|
+
)
|
|
1023
|
+
// 拒绝回执属于控制面:不得携带旧摘要锚,否则会被 notifyUser 的 push gate 自己拦掉。
|
|
1024
|
+
await notifyUser(
|
|
1025
|
+
{ ...ctx, anchorSessionId: undefined },
|
|
1026
|
+
anchorRejectText(decision, currentSessionId, ctx.userId),
|
|
1027
|
+
)
|
|
1028
|
+
}
|
|
1029
|
+
|
|
932
1030
|
// O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
|
|
933
1031
|
// ★ 结合部契约(2026-11-17 固化):onPermission(回合内即时推送,SSE permission.asked)
|
|
934
1032
|
// 与常驻交互监听(桌面端源审批 pushExternal)是同一挂起槽的两个入口——裁决/TTL/
|
|
@@ -1015,6 +1113,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
1015
1113
|
busyUsers,
|
|
1016
1114
|
// 多角色:镜像开关按角色分文件(缺省 legacy 全局)
|
|
1017
1115
|
settingsFile: storageAppId ? roleFile("settings.json") : undefined,
|
|
1116
|
+
anchorStore: mirrorAnchors,
|
|
1018
1117
|
// A 方案(owner 2026-11-23):桌面端回合的摘要同样过 cron 钩——注册提醒+剥净标记
|
|
1019
1118
|
onDigest: (userId, digest) => {
|
|
1020
1119
|
const hit = parseCronReminder(digest, Date.now())
|
|
@@ -1862,6 +1961,12 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
1862
1961
|
inflight.settle(ctx.msgId, undefined, reason)
|
|
1863
1962
|
console.log(`[queue] release-early msg=${shortId(ctx.msgId)} reason=${reason}${note ? ` note=${note}` : ""}`)
|
|
1864
1963
|
}
|
|
1964
|
+
const releaseAnchorClaim = (note: "anchor-conflict" | "anchor-unknown"): void => {
|
|
1965
|
+
if (ctx.msgId && claimedContexts.has(ctx)) {
|
|
1966
|
+
inflight.markStage(ctx.msgId, "claimed", { lastError: note }, { force: true })
|
|
1967
|
+
}
|
|
1968
|
+
releaseClaimed("blocked", note)
|
|
1969
|
+
}
|
|
1865
1970
|
try {
|
|
1866
1971
|
// P1 修复(2026-11-03,外部复盘核验):拒绝时记录 openid——新用户无任何
|
|
1867
1972
|
// 途径获取自己的 openid 填 ALLOWED_USERS,首配死锁;白名单内不打印(无需)。
|
|
@@ -1916,6 +2021,14 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
1916
2021
|
const gateContent = normalizeForCommandGate(content)
|
|
1917
2022
|
if (isCommand(gateContent)) {
|
|
1918
2023
|
const gateCtx = gateContent === content ? ctx : { ...ctx, content: gateContent }
|
|
2024
|
+
if (commandNeedsMirrorAnchorGate(gateContent)) {
|
|
2025
|
+
const decision = mirrorAnchorDecision(gateCtx, anchorSid)
|
|
2026
|
+
if (decision.kind === "conflict" || decision.kind === "unknown") {
|
|
2027
|
+
releaseAnchorClaim(decision.kind === "conflict" ? "anchor-conflict" : "anchor-unknown")
|
|
2028
|
+
await rejectMirrorAnchor(ctx, decision, anchorSid)
|
|
2029
|
+
return
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
1919
2032
|
const reply = await handleCommand(gateCtx, commandContext)
|
|
1920
2033
|
await notifyUser(ctx, reply)
|
|
1921
2034
|
releaseClaimed("dropped")
|
|
@@ -1974,6 +2087,13 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
1974
2087
|
claimedMsgId = ctx.msgId
|
|
1975
2088
|
}
|
|
1976
2089
|
|
|
2090
|
+
const mirrorGate = mirrorAnchorDecision(ctx, anchorSid)
|
|
2091
|
+
if (mirrorGate.kind === "conflict" || mirrorGate.kind === "unknown") {
|
|
2092
|
+
releaseAnchorClaim(mirrorGate.kind === "conflict" ? "anchor-conflict" : "anchor-unknown")
|
|
2093
|
+
await rejectMirrorAnchor(ctx, mirrorGate, anchorSid)
|
|
2094
|
+
return
|
|
2095
|
+
}
|
|
2096
|
+
|
|
1977
2097
|
if (busyUsers.has(lane) && !claimedContexts.has(ctx)) {
|
|
1978
2098
|
const duplicateIntent = activeIntents.get(lane) === intentKey || msgQueue.hasIntent(lane, intentKey)
|
|
1979
2099
|
if (duplicateIntent) {
|
|
@@ -2081,12 +2201,11 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
2081
2201
|
anchorDirectory
|
|
2082
2202
|
}
|
|
2083
2203
|
|
|
2084
|
-
// 缺口 1
|
|
2204
|
+
// 缺口 1(引用上下文,参考官方 quote-ref 中间件的解析思路):本条消息的引用解析
|
|
2085
2205
|
// 先于本条登记(顺序不可反:本条入缓存后才能被后续消息引用)
|
|
2086
2206
|
// N 项(2026-10-30):双通道——QQ 事件内嵌被引内容(message_type=103)
|
|
2087
2207
|
// 为权威来源优先;缺失才回落本地缓存(跨重启/老消息引用也能解析)。
|
|
2088
|
-
const
|
|
2089
|
-
const quoted = embeddedQuote ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null)
|
|
2208
|
+
const { quoted } = quoteContextOf(ctx)
|
|
2090
2209
|
if (quoted) ctx.quoteText = quoted
|
|
2091
2210
|
recordMessage(scopeKeyOf(ctx), ctx.msgId, ctx.content)
|
|
2092
2211
|
// 新回合取代旧的后台等待(steer 合并运行时只投递一次合并结果)
|
|
@@ -2189,7 +2308,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
2189
2308
|
// 超长回合可能已超被动窗口:deliver 被动失败自动降级主动,答案不丢
|
|
2190
2309
|
// 直答出口统一脱敏(DEF-qqbot-20261106-2):与 history/mirror/form 同一脱敏器,
|
|
2191
2310
|
// 防 AI 复述的密钥/令牌经直答气泡明文外泄。
|
|
2192
|
-
// Y-1 cron 提醒(2026-11-23
|
|
2311
|
+
// Y-1 cron 提醒(2026-11-23 学习参考 openclaw):正文内嵌 QQBOT_PAYLOAD 标记
|
|
2193
2312
|
// → 注册一次性提醒并剥离标记;剥净为空则以确认句回执(不留脚手架痕迹)。
|
|
2194
2313
|
let outboundText = extracted.text
|
|
2195
2314
|
const cronHit = parseCronReminder(extracted.text, Date.now())
|
|
@@ -2209,6 +2328,10 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
|
2209
2328
|
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
2210
2329
|
console.log(`[push-gate] 回合结果按历史可回读结清 answered msg=${shortId(trackId)}`)
|
|
2211
2330
|
inflight.settle(trackId, undefined, "answered")
|
|
2331
|
+
} else if (consumePartialFailure(ctx)) {
|
|
2332
|
+
// 部分失败告警已由 delivery 发出;不得再冒称「24h 同文去重」。
|
|
2333
|
+
inflight.settle(trackId, undefined, "error")
|
|
2334
|
+
console.log(`[journal] 分片部分失败结清 error msg=${shortId(trackId)}`)
|
|
2212
2335
|
} else {
|
|
2213
2336
|
await safeDeliver(ctx, "⚠️ 本轮结果与 24h 内已发送内容重复,已被防重拦截(未重复投递)。如非预期请重发或换个说法")
|
|
2214
2337
|
inflight.settle(trackId, undefined, "error")
|
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// handleApprovalInteraction
|
|
6
6
|
// @pos: core - 卡片按钮审批(A 项 2026-10-29)
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
8
|
+
// 设计参考 dsh-qqbot 的 button-data 判别及 approval-channel 的挂起、旧卡防伪机制,
|
|
9
|
+
// 以及 @tencent-connect/qqbot-nodejs protocol/types.ts 的 KeyboardButton/InlineKeyboard 形状。
|
|
10
|
+
// 本项目改用 request.id 防伪,并扩展四键决策、文字降级和项目权限状态机;
|
|
11
|
+
// 上游来源与许可见 THIRD_PARTY_NOTICES.md。
|
|
11
12
|
// 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
|
|
12
13
|
// 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
|
|
13
14
|
// button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// @output: recordMessage, resolveQuote, scopeKeyOf, resetContextBuffer(测试用)
|
|
3
3
|
// @pos: core - 消息上下文索引缓存(引用消息解析)
|
|
4
4
|
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
5
|
+
// 引用索引与回退思路参考 qqbot-nodejs 的 quote-ref 中间件。
|
|
6
|
+
// QQ C2C/群消息的引用经由 message_reference.message_id 透传;QQ 不提供 C2C 历史
|
|
7
|
+
// 消息拉取,故引用解析需本地缓存——我方发出的回复也记录(消息 id 取服务端回执
|
|
8
|
+
// MessageResponse.id;0.3.20 起同时登记 ext_info.ref_idx),保证"引用 AI 答案"可解析。此处按项目会话域以 Map 实现
|
|
9
|
+
// 每域 200 条的进程内缓存;跨重启引用解析为空属可接受降级。上游见 THIRD_PARTY_NOTICES.md。
|
|
10
10
|
interface RefEntry {
|
|
11
11
|
text: string
|
|
12
12
|
at: number
|
|
@@ -46,7 +46,7 @@ export function resolveQuote(scope: string, referencedMsgId: string): string | n
|
|
|
46
46
|
return entry?.text ?? null
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
// N 项(2026-10-30
|
|
49
|
+
// N 项(2026-10-30,参考竞品 opencode-qq-v2 的引用消息双通道思路):
|
|
50
50
|
// QQ 在 message_type=103 时把被引内容嵌在 msg_elements 里随事件透传(官方未完全
|
|
51
51
|
// 文档化结构,做防御性递归提取);命中即权威来源,不再依赖本缓存(跨重启/引用
|
|
52
52
|
// 老消息也能解析)。提取为空时调用方回落 resolveQuote 缓存通道。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @input: 纯文本(无依赖)+ setTimeout(调度器)
|
|
2
2
|
// @output: parseCronReminder / ReminderScheduler
|
|
3
|
-
// @pos: core - 定时提醒(2026-11-23
|
|
3
|
+
// @pos: core - 定时提醒(2026-11-23 学习参考 Y-1,源=openclaw outbound/cron-scheduler.ts P0)
|
|
4
4
|
//
|
|
5
5
|
// 触发形态(AI 在正文内嵌标记,与 openclaw 同款):
|
|
6
6
|
// QQBOT_PAYLOAD: {"type":"cron_reminder","at":"in 30m","text":"去开评审会"}
|
package/src/core/delivery.ts
CHANGED
|
@@ -8,8 +8,15 @@ import { join } from "path"
|
|
|
8
8
|
import { createHash } from "node:crypto"
|
|
9
9
|
import type { Config } from "../config.js"
|
|
10
10
|
import type { MessageContext } from "../qq/types.js"
|
|
11
|
-
import {
|
|
12
|
-
|
|
11
|
+
import {
|
|
12
|
+
getAccessToken,
|
|
13
|
+
sendC2CMessage,
|
|
14
|
+
sendGroupMessage,
|
|
15
|
+
getNextMsgSeq,
|
|
16
|
+
type MessageResponse,
|
|
17
|
+
type SentMessageReceipt,
|
|
18
|
+
} from "../qq/api.js"
|
|
19
|
+
import { PartialReplyError, replyToQQ } from "../qq/sender.js"
|
|
13
20
|
import { matchFence, normalizeOutboundMarkdown } from "./markdown.js"
|
|
14
21
|
import { ReplyLimiter } from "./reply-limiter.js"
|
|
15
22
|
import { recordMessage, scopeKeyOf } from "./context-buffer.js"
|
|
@@ -57,9 +64,11 @@ function saveQuotaMap(file: string, m: ReadonlyMap<string, { day: string; count:
|
|
|
57
64
|
}
|
|
58
65
|
}
|
|
59
66
|
|
|
60
|
-
// P 项(2026-10-30
|
|
67
|
+
// P 项(2026-10-30,参考竞品 pendingNotice 模式):发送彻底失败不静默——
|
|
61
68
|
// 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
|
|
62
69
|
export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
|
|
70
|
+
export const PARTIAL_DELIVERY_NOTICE =
|
|
71
|
+
"⚠️ 本轮消息仅部分送达。为避免重复,已阻止自动全文重发;完整结果请发 /history 查看,或重新提问。"
|
|
63
72
|
|
|
64
73
|
// QQ 渲染适配(2026-11-03 用户双端截图实证):QQ 官方 markdown 渲染器把跨
|
|
65
74
|
// 段落的有序列表续接编号(原文 1./2. 渲染成 3./4.),与桌面端所见不一致。
|
|
@@ -279,14 +288,23 @@ export function selectRideMsgId(
|
|
|
279
288
|
return last.msgId
|
|
280
289
|
}
|
|
281
290
|
|
|
291
|
+
export type OnSentMessage = (receipt: SentMessageReceipt) => void | Promise<void>
|
|
292
|
+
|
|
293
|
+
export interface DeliveryContentOptions {
|
|
294
|
+
/** 仅加到第 2 片及后续分片;切分后添加,保证身份标记不会留在上一片。 */
|
|
295
|
+
continuationPrefix?: string
|
|
296
|
+
}
|
|
297
|
+
|
|
282
298
|
export interface Delivery {
|
|
283
299
|
/** anchorSessionId=该观察行的锚定会话(出站推送门按它校验当前绑定,design §3.4) */
|
|
284
300
|
enqueuePush: (userId: string, line: string, anchorSessionId?: string) => void
|
|
285
|
-
/** 返回 true
|
|
286
|
-
deliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
301
|
+
/** 返回 true=完整出站成功;false=24h 去重、推送门或分片部分失败(调用方据此刻画销账口径) */
|
|
302
|
+
deliver: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<boolean>
|
|
287
303
|
/** 同 deliver;彻底失败时贴条待下次消化并返回 false */
|
|
288
|
-
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
289
|
-
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
304
|
+
safeDeliver: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<boolean>
|
|
305
|
+
sendReply: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<void>
|
|
306
|
+
/** 消费一次部分失败标记,供 bridge 区分「部分失败」与「24h 同文去重」。 */
|
|
307
|
+
consumePartialFailure: (ctx: MessageContext) => boolean
|
|
290
308
|
}
|
|
291
309
|
|
|
292
310
|
// 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
|
|
@@ -312,8 +330,8 @@ export function createDelivery(
|
|
|
312
330
|
// 该用户最近主动发送时刻(滚动 60s 窗,内存态——重启即清空,天预算仍落盘兜底)
|
|
313
331
|
const activeMinuteLog = new Map<string, number[]>()
|
|
314
332
|
|
|
315
|
-
// B-msgid(2026-10-29
|
|
316
|
-
// "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
|
|
333
|
+
// B-msgid(2026-10-29,被动目标缓存思路参考 dsh-qqbot 的 msgid-cache):
|
|
334
|
+
// 主动降级前尝试让发送"骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
|
|
317
335
|
// 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
|
|
318
336
|
// 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
|
|
319
337
|
const RIDE_WINDOW_MS = (() => {
|
|
@@ -331,9 +349,11 @@ export function createDelivery(
|
|
|
331
349
|
const pushQueues = new Map<string, PushQueue>()
|
|
332
350
|
// P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
|
|
333
351
|
const undelivered = new Set<string>()
|
|
352
|
+
const partialFailures = new WeakSet<MessageContext>()
|
|
334
353
|
const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
|
|
335
|
-
// B1(2026-10-29
|
|
354
|
+
// B1(2026-10-29,限额规则与降级方式参考 openclaw-qqbot reply-limiter):
|
|
336
355
|
// 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
|
|
356
|
+
// 该派生实现的上游版权与许可见 THIRD_PARTY_NOTICES.md。
|
|
337
357
|
// 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
|
|
338
358
|
const passiveLimiter = new ReplyLimiter()
|
|
339
359
|
// O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
|
|
@@ -390,13 +410,33 @@ export function createDelivery(
|
|
|
390
410
|
}
|
|
391
411
|
}
|
|
392
412
|
|
|
413
|
+
function recordSent(scope: string, text: string, receipt: SentMessageReceipt): void {
|
|
414
|
+
recordMessage(scope, receipt.id, text)
|
|
415
|
+
if (receipt.refIdx && receipt.refIdx !== receipt.id) recordMessage(scope, receipt.refIdx, text)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function emitSent(onSent: OnSentMessage | undefined, receipt: SentMessageReceipt): Promise<void> {
|
|
419
|
+
if (!onSent) return
|
|
420
|
+
try {
|
|
421
|
+
await onSent(receipt)
|
|
422
|
+
} catch (error) {
|
|
423
|
+
// QQ 已真实发送:回执簿记失败绝不能触发被动→主动降级而重复发一条。
|
|
424
|
+
console.error("[delivery] onSent 回执处理失败(QQ 消息已发送):", error)
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
393
428
|
// 统一投递:被动回复优先(ctx.msg_id,5 分钟窗口内、无配额消耗);
|
|
394
429
|
// 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
|
|
395
430
|
// 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
|
|
396
431
|
//(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
|
|
397
432
|
// P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
|
|
398
433
|
// 投递失败则把贴条放回(留待下次),成功才算消化。
|
|
399
|
-
async function deliver(
|
|
434
|
+
async function deliver(
|
|
435
|
+
ctx: MessageContext,
|
|
436
|
+
text: string,
|
|
437
|
+
onSent?: OnSentMessage,
|
|
438
|
+
content?: DeliveryContentOptions,
|
|
439
|
+
): Promise<boolean> {
|
|
400
440
|
// 出站推送门(design §3.4,owner 2026-11-14 会话隔离裁定):QQ 窗只呈现当前绑定
|
|
401
441
|
// 会话——锚定会话≠当前绑定即不推(结果已入锚定会话历史,可经历史/桌面端回读)。
|
|
402
442
|
if (ctx.anchorSessionId && pushGate && !pushGate(ctx.userId, ctx.anchorSessionId)) {
|
|
@@ -416,17 +456,36 @@ export function createDelivery(
|
|
|
416
456
|
// QQ 渲染适配:有序列表改写,防 QQ 端跨段落续编(桌面所见=QQ 所见)
|
|
417
457
|
const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text)
|
|
418
458
|
try {
|
|
419
|
-
await deliverCore(ctx, body)
|
|
459
|
+
await deliverCore(ctx, body, onSent, content)
|
|
420
460
|
return true
|
|
421
461
|
} catch (error) {
|
|
422
|
-
|
|
462
|
+
if (error instanceof PartialReplyError) {
|
|
463
|
+
partialFailures.add(ctx)
|
|
464
|
+
console.error(
|
|
465
|
+
`[delivery] 分片部分失败,禁止全文降级 sent=${error.receipts.length} failedChunk=${error.failedChunkIndex + 1}`,
|
|
466
|
+
)
|
|
467
|
+
// 已发前缀不能重复;保留原去重占位,阻止 outbox/恢复路径立即重发同一全文。
|
|
468
|
+
try {
|
|
469
|
+
await sendActive(ctx, PARTIAL_DELIVERY_NOTICE)
|
|
470
|
+
} catch (alertError) {
|
|
471
|
+
undelivered.add(ctx.userId)
|
|
472
|
+
console.error("[delivery] 部分失败告警也未能送达:", alertError)
|
|
473
|
+
}
|
|
474
|
+
return false
|
|
475
|
+
}
|
|
476
|
+
// 完全未发出时不占去重位,后续恢复/重试仍可送达。
|
|
423
477
|
releaseDeliveryAttempt(ctx.userId, text, now)
|
|
424
478
|
if (hadNotice) undelivered.add(ctx.userId)
|
|
425
479
|
throw error
|
|
426
480
|
}
|
|
427
481
|
}
|
|
428
482
|
|
|
429
|
-
async function deliverCore(
|
|
483
|
+
async function deliverCore(
|
|
484
|
+
ctx: MessageContext,
|
|
485
|
+
text: string,
|
|
486
|
+
onSent?: OnSentMessage,
|
|
487
|
+
content?: DeliveryContentOptions,
|
|
488
|
+
): Promise<void> {
|
|
430
489
|
// B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
|
|
431
490
|
const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
|
|
432
491
|
if (passive?.shouldFallbackToProactive) {
|
|
@@ -435,9 +494,10 @@ export function createDelivery(
|
|
|
435
494
|
)
|
|
436
495
|
} else {
|
|
437
496
|
try {
|
|
438
|
-
await sendReply(ctx, text)
|
|
497
|
+
await sendReply(ctx, text, onSent, content)
|
|
439
498
|
return
|
|
440
499
|
} catch (error) {
|
|
500
|
+
if (error instanceof PartialReplyError) throw error
|
|
441
501
|
console.warn(
|
|
442
502
|
"[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:",
|
|
443
503
|
error instanceof Error ? error.message : error,
|
|
@@ -445,15 +505,18 @@ export function createDelivery(
|
|
|
445
505
|
}
|
|
446
506
|
}
|
|
447
507
|
|
|
448
|
-
// B-msgid
|
|
508
|
+
// B-msgid(参考 dsh-qqbot msgid-cache 的被动目标缓存思路,2026-10-29):主动降级前尝试"骑"该用户最近
|
|
449
509
|
// 的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额、记 B1 账本);
|
|
450
510
|
// 骑失败无副作用,回落下方真主动流程。
|
|
451
511
|
const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS)
|
|
452
512
|
if (rideMsgId) {
|
|
453
513
|
try {
|
|
454
|
-
const
|
|
514
|
+
const rideReceipts = await sendActive(ctx, text, rideMsgId)
|
|
455
515
|
passiveLimiter.record(rideMsgId)
|
|
456
|
-
for (const
|
|
516
|
+
for (const receipt of rideReceipts) {
|
|
517
|
+
recordSent(scopeKeyOf(ctx), text, receipt)
|
|
518
|
+
await emitSent(onSent, receipt)
|
|
519
|
+
}
|
|
457
520
|
console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`)
|
|
458
521
|
return
|
|
459
522
|
} catch {
|
|
@@ -480,15 +543,23 @@ export function createDelivery(
|
|
|
480
543
|
}
|
|
481
544
|
throw new Error("主动消息已达 QQ 官方日上限,本条无法送达")
|
|
482
545
|
}
|
|
483
|
-
const
|
|
484
|
-
for (const
|
|
546
|
+
const activeReceipts = await sendActive(ctx, text)
|
|
547
|
+
for (const receipt of activeReceipts) {
|
|
548
|
+
recordSent(scopeKeyOf(ctx), text, receipt)
|
|
549
|
+
await emitSent(onSent, receipt)
|
|
550
|
+
}
|
|
485
551
|
q.count++
|
|
486
552
|
saveQuotaMap(QUOTA_FILE, activeQuota) // O5:计数落盘,跨重启不归零
|
|
487
553
|
}
|
|
488
554
|
|
|
489
|
-
async function safeDeliver(
|
|
555
|
+
async function safeDeliver(
|
|
556
|
+
c: MessageContext,
|
|
557
|
+
text: string,
|
|
558
|
+
onSent?: OnSentMessage,
|
|
559
|
+
content?: DeliveryContentOptions,
|
|
560
|
+
): Promise<boolean> {
|
|
490
561
|
try {
|
|
491
|
-
return await deliver(c, text)
|
|
562
|
+
return await deliver(c, text, onSent, content)
|
|
492
563
|
} catch (error) {
|
|
493
564
|
undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
|
|
494
565
|
console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
|
|
@@ -498,8 +569,8 @@ export function createDelivery(
|
|
|
498
569
|
|
|
499
570
|
// 主动消息(不带 msg_id):markdown 优先,失败回退纯文本。
|
|
500
571
|
// passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
|
|
501
|
-
//
|
|
502
|
-
async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<
|
|
572
|
+
// 返回每个服务端消息回执(id + 可选 refIdx)。
|
|
573
|
+
async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<SentMessageReceipt[]> {
|
|
503
574
|
// 分钟维节流(官方 20 条/分钟,2026-11-18 严格官方化):滚动窗满 → 睡到窗口滑动再发。
|
|
504
575
|
// 骑被动窗口的投递(passiveMsgId 非空)平台按被动计,不占主动分钟窗。
|
|
505
576
|
if (!passiveMsgId) {
|
|
@@ -514,45 +585,68 @@ export function createDelivery(
|
|
|
514
585
|
const isGroup = ctx.type === "group" && ctx.groupId
|
|
515
586
|
// 主动 markdown 同样走围栏归一(与被动回复同口径,防未闭合/空围栏对渲染成空卡片)
|
|
516
587
|
const mdText = normalizeOutboundMarkdown(text)
|
|
517
|
-
const record = (
|
|
588
|
+
const record = (response: MessageResponse | undefined): SentMessageReceipt[] => {
|
|
589
|
+
const receipts = response?.id ? [{
|
|
590
|
+
id: response.id,
|
|
591
|
+
...(response.ext_info?.ref_idx ? { refIdx: response.ext_info.ref_idx } : {}),
|
|
592
|
+
}] : []
|
|
518
593
|
// 发送成功才记主动分钟窗(失败不计,同被动限额器口径)
|
|
519
|
-
if (!passiveMsgId &&
|
|
520
|
-
return
|
|
594
|
+
if (!passiveMsgId && receipts.length > 0) logActiveSend(activeMinuteLog, ctx.userId, Date.now())
|
|
595
|
+
return receipts
|
|
521
596
|
}
|
|
522
597
|
try {
|
|
523
598
|
if (isGroup) {
|
|
524
599
|
const r = await sendGroupMessage(token, ctx.groupId!, mdText, passiveMsgId, seq, true)
|
|
525
|
-
return record(r
|
|
600
|
+
return record(r)
|
|
526
601
|
}
|
|
527
602
|
const r = await sendC2CMessage(token, ctx.userId, mdText, passiveMsgId, seq, true)
|
|
528
|
-
return record(r
|
|
603
|
+
return record(r)
|
|
529
604
|
} catch (error) {
|
|
530
605
|
console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
|
|
531
606
|
}
|
|
532
607
|
if (isGroup) {
|
|
533
608
|
const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
|
|
534
|
-
return record(r
|
|
609
|
+
return record(r)
|
|
535
610
|
}
|
|
536
611
|
const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
|
|
537
|
-
return record(r
|
|
612
|
+
return record(r)
|
|
538
613
|
}
|
|
539
614
|
|
|
540
|
-
async function sendReply(
|
|
615
|
+
async function sendReply(
|
|
616
|
+
ctx: MessageContext,
|
|
617
|
+
text: string,
|
|
618
|
+
onSent?: OnSentMessage,
|
|
619
|
+
content?: DeliveryContentOptions,
|
|
620
|
+
): Promise<void> {
|
|
541
621
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
542
|
-
|
|
622
|
+
const scope = scopeKeyOf(ctx)
|
|
623
|
+
// J-轻:伪流式错峰(多片时隔 300ms 逐段到达)。每片成功立即登记,后续片失败
|
|
624
|
+
// 也不丢已发片的引用缓存/摘要锚点;严禁等整批成功后才补记。
|
|
543
625
|
const result = await replyToQQ(accessToken, ctx, text, {
|
|
544
626
|
staggerMs: STREAM_STAGGER_MS,
|
|
627
|
+
continuationPrefix: content?.continuationPrefix,
|
|
628
|
+
onReceipt: async (receipt) => {
|
|
629
|
+
recordSent(scope, text, receipt)
|
|
630
|
+
await emitSent(onSent, receipt)
|
|
631
|
+
},
|
|
545
632
|
})
|
|
546
633
|
// B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
|
|
547
634
|
// 多片回复此前少计 N-1(J-轻顺手修正);bridge 直调与 deliver 共用此出口
|
|
548
635
|
if (ctx.msgId) {
|
|
549
636
|
for (let i = 0; i < result.chunks; i++) passiveLimiter.record(ctx.msgId)
|
|
550
637
|
}
|
|
551
|
-
// 缺口 1:我方出站回复登记进上下文缓存(引用解析可命中 AI 答案)
|
|
552
|
-
const scope = scopeKeyOf(ctx)
|
|
553
|
-
for (const id of result.ids) recordMessage(scope, id, text)
|
|
554
638
|
}
|
|
555
639
|
|
|
556
|
-
return {
|
|
640
|
+
return {
|
|
641
|
+
enqueuePush,
|
|
642
|
+
deliver,
|
|
643
|
+
safeDeliver,
|
|
644
|
+
sendReply,
|
|
645
|
+
consumePartialFailure(ctx): boolean {
|
|
646
|
+
if (!partialFailures.has(ctx)) return false
|
|
647
|
+
partialFailures.delete(ctx)
|
|
648
|
+
return true
|
|
649
|
+
},
|
|
650
|
+
}
|
|
557
651
|
}
|
|
558
652
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @output: acquireInstanceLock, acquireInstanceLockAt(测试用), waitInstanceLock, INSTANCE_LOCK_DISABLED_ENV
|
|
3
3
|
// @pos: core - 单实例锁(防多开:双实例互踩 QQ 网关会互踢下线)
|
|
4
4
|
//
|
|
5
|
-
// M 项(2026-10-30
|
|
5
|
+
// M 项(2026-10-30,方案参考竞品 opencode-qq-v2 的 proper-lockfile 设计,
|
|
6
6
|
// 零依赖手写以守"官方/三方包不进 dependencies"红线):
|
|
7
7
|
// - wx 原子创建锁文件(含 pid+启动时间),抢到即宿主
|
|
8
8
|
// - 持锁者每 10s 刷新 mtime 作心跳
|