@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
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// @input: fs/path/crypto(角色级摘要锚点持久化)
|
|
2
|
+
// @output: createMirrorAnchorStore、pruneMirrorAnchorEntries、MirrorAnchorEntry
|
|
3
|
+
// @pos: core - QQ 发送回执 ref_idx → (用户,会话) 的有界持久化索引
|
|
4
|
+
import {
|
|
5
|
+
existsSync,
|
|
6
|
+
mkdirSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
unlinkSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from "node:fs"
|
|
12
|
+
import { dirname } from "node:path"
|
|
13
|
+
import { randomUUID } from "node:crypto"
|
|
14
|
+
|
|
15
|
+
export const MIRROR_ANCHOR_TTL_MS = 24 * 60 * 60 * 1000
|
|
16
|
+
export const MIRROR_ANCHOR_MAX_PER_USER = 500
|
|
17
|
+
|
|
18
|
+
export interface MirrorAnchorEntry {
|
|
19
|
+
/** 发送响应 ext_info.ref_idx;入站 ref_msg_idx 的 lookup 主键 */
|
|
20
|
+
refIdx: string
|
|
21
|
+
/** 发送响应 id;仅诊断/撤回关联,不参与引用 lookup */
|
|
22
|
+
messageId: string
|
|
23
|
+
userId: string
|
|
24
|
+
sessionId: string
|
|
25
|
+
title: string
|
|
26
|
+
sentAt: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface MirrorAnchorStore {
|
|
30
|
+
readonly filePath: string
|
|
31
|
+
record: (entry: MirrorAnchorEntry) => void
|
|
32
|
+
resolve: (userId: string, refIdx: string | undefined, now?: number) => MirrorAnchorEntry | undefined
|
|
33
|
+
list: () => MirrorAnchorEntry[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface AnchorDocument {
|
|
37
|
+
version: 1
|
|
38
|
+
entries: MirrorAnchorEntry[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validEntry(value: unknown): value is MirrorAnchorEntry {
|
|
42
|
+
const entry = value as Partial<MirrorAnchorEntry> | null
|
|
43
|
+
return !!entry &&
|
|
44
|
+
typeof entry.refIdx === "string" && !!entry.refIdx &&
|
|
45
|
+
typeof entry.messageId === "string" && !!entry.messageId &&
|
|
46
|
+
typeof entry.userId === "string" && !!entry.userId &&
|
|
47
|
+
typeof entry.sessionId === "string" && !!entry.sessionId &&
|
|
48
|
+
typeof entry.title === "string" &&
|
|
49
|
+
typeof entry.sentAt === "number" && Number.isFinite(entry.sentAt) && entry.sentAt > 0
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** TTL + 每用户 LRU;返回按 sentAt 升序排列,便于稳定落盘与测试。 */
|
|
53
|
+
export function pruneMirrorAnchorEntries(
|
|
54
|
+
input: readonly MirrorAnchorEntry[],
|
|
55
|
+
now = Date.now(),
|
|
56
|
+
): MirrorAnchorEntry[] {
|
|
57
|
+
const fresh = input.filter((entry) =>
|
|
58
|
+
validEntry(entry) && entry.sentAt <= now && now - entry.sentAt < MIRROR_ANCHOR_TTL_MS,
|
|
59
|
+
)
|
|
60
|
+
const newestFirst = [...fresh].sort((a, b) => b.sentAt - a.sentAt)
|
|
61
|
+
const counts = new Map<string, number>()
|
|
62
|
+
const seen = new Set<string>()
|
|
63
|
+
const retained: MirrorAnchorEntry[] = []
|
|
64
|
+
for (const entry of newestFirst) {
|
|
65
|
+
const identity = `${entry.userId}\u0000${entry.refIdx}`
|
|
66
|
+
if (seen.has(identity)) continue
|
|
67
|
+
const count = counts.get(entry.userId) ?? 0
|
|
68
|
+
if (count >= MIRROR_ANCHOR_MAX_PER_USER) continue
|
|
69
|
+
seen.add(identity)
|
|
70
|
+
counts.set(entry.userId, count + 1)
|
|
71
|
+
retained.push(entry)
|
|
72
|
+
}
|
|
73
|
+
return retained.sort((a, b) => a.sentAt - b.sentAt)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function createMirrorAnchorStore(filePath: string): MirrorAnchorStore {
|
|
77
|
+
let entries: MirrorAnchorEntry[] = []
|
|
78
|
+
|
|
79
|
+
function save(nextEntries: MirrorAnchorEntry[] = entries): void {
|
|
80
|
+
const document: AnchorDocument = { version: 1, entries: nextEntries }
|
|
81
|
+
mkdirSync(dirname(filePath), { recursive: true })
|
|
82
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`
|
|
83
|
+
try {
|
|
84
|
+
writeFileSync(temporary, JSON.stringify(document, null, 2), { mode: 0o600 })
|
|
85
|
+
renameSync(temporary, filePath)
|
|
86
|
+
} catch (error) {
|
|
87
|
+
try { unlinkSync(temporary) } catch { /* 已 rename 或清理失败 */ }
|
|
88
|
+
throw error
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
if (existsSync(filePath)) {
|
|
94
|
+
const parsed = JSON.parse(readFileSync(filePath, "utf8").replace(/^\uFEFF/, "")) as Partial<AnchorDocument>
|
|
95
|
+
if (parsed.version !== 1 || !Array.isArray(parsed.entries)) throw new Error("锚点文件格式无效")
|
|
96
|
+
const loaded = parsed.entries.filter(validEntry)
|
|
97
|
+
const pruned = pruneMirrorAnchorEntries(loaded)
|
|
98
|
+
entries = pruned
|
|
99
|
+
if (loaded.length !== parsed.entries.length || pruned.length !== loaded.length) save()
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
// 原字节保留在诊断副本;空表意味着旧摘要一律按未知锚点 fail-closed。
|
|
103
|
+
try {
|
|
104
|
+
const backup = `${filePath}.corrupt-${Date.now()}`
|
|
105
|
+
renameSync(filePath, backup)
|
|
106
|
+
console.error(`[mirror-anchor] 锚点文件损坏,已保留诊断副本:${backup}`)
|
|
107
|
+
} catch (backupError) {
|
|
108
|
+
console.error("[mirror-anchor] 损坏文件备份失败:", backupError)
|
|
109
|
+
}
|
|
110
|
+
entries = []
|
|
111
|
+
console.error("[mirror-anchor] 锚点恢复失败,按空表 fail-closed:", error)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
filePath,
|
|
116
|
+
record(entry): void {
|
|
117
|
+
if (!validEntry(entry)) throw new Error("摘要锚点字段不完整")
|
|
118
|
+
// 同步读改写:单角色事件循环内天然串行;原子 rename 防半截文件。
|
|
119
|
+
const next = pruneMirrorAnchorEntries([
|
|
120
|
+
...entries.filter((item) => !(item.userId === entry.userId && item.refIdx === entry.refIdx)),
|
|
121
|
+
entry,
|
|
122
|
+
])
|
|
123
|
+
// 先盘后备内存:落盘失败的锚点绝不可在本进程内侥幸放行。
|
|
124
|
+
save(next)
|
|
125
|
+
entries = next
|
|
126
|
+
},
|
|
127
|
+
resolve(userId, refIdx, now = Date.now()): MirrorAnchorEntry | undefined {
|
|
128
|
+
if (!refIdx) return undefined
|
|
129
|
+
const entry = entries.find((item) => item.userId === userId && item.refIdx === refIdx)
|
|
130
|
+
if (!entry) return undefined
|
|
131
|
+
if (entry.sentAt > now || now - entry.sentAt >= MIRROR_ANCHOR_TTL_MS) {
|
|
132
|
+
const before = entries.length
|
|
133
|
+
entries = pruneMirrorAnchorEntries(entries, now)
|
|
134
|
+
if (entries.length !== before) {
|
|
135
|
+
try { save() } catch (error) { console.error("[mirror-anchor] 过期锚点清理失败:", error) }
|
|
136
|
+
}
|
|
137
|
+
return undefined
|
|
138
|
+
}
|
|
139
|
+
return { ...entry }
|
|
140
|
+
},
|
|
141
|
+
list(): MirrorAnchorEntry[] {
|
|
142
|
+
return entries.map((entry) => ({ ...entry }))
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
}
|
package/src/core/mirror.ts
CHANGED
|
@@ -7,8 +7,17 @@ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
|
|
|
7
7
|
import type { MessageContext } from "../qq/types.js"
|
|
8
8
|
import type { OpencodeClient } from "../opencode/client.js"
|
|
9
9
|
import { createEventStream } from "../opencode/eventstream.js"
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
buildDigest,
|
|
12
|
+
clipDigestTitle,
|
|
13
|
+
digestAnchorUserId,
|
|
14
|
+
digestSessionLabel,
|
|
15
|
+
digestTurnKey,
|
|
16
|
+
} from "../opencode/mirror.js"
|
|
11
17
|
import { laneKeyOf } from "./message-queue.js"
|
|
18
|
+
import { redactSecrets } from "../opencode/history.js"
|
|
19
|
+
import type { DeliveryContentOptions, OnSentMessage } from "./delivery.js"
|
|
20
|
+
import type { MirrorAnchorStore } from "./mirror-anchors.js"
|
|
12
21
|
import type { SessionManager } from "../opencode/sessions.js"
|
|
13
22
|
import type { MirrorApi } from "../commands.js"
|
|
14
23
|
|
|
@@ -55,11 +64,18 @@ export interface MirrorDeps {
|
|
|
55
64
|
eventStream: EventStream
|
|
56
65
|
client: OpencodeClient
|
|
57
66
|
lastCtx: ReadonlyMap<string, MessageContext> // bridge 拥有写权,本域只读
|
|
58
|
-
safeDeliver: (
|
|
67
|
+
safeDeliver: (
|
|
68
|
+
ctx: MessageContext,
|
|
69
|
+
text: string,
|
|
70
|
+
onSent?: OnSentMessage,
|
|
71
|
+
content?: DeliveryContentOptions,
|
|
72
|
+
) => Promise<boolean>
|
|
59
73
|
bgWaits: ReadonlyMap<string, { cancel: () => void }> // 后台等待在途则不解锁
|
|
60
74
|
busyUsers: ReadonlySet<string> // 会话主人在忙则不解锁(5 秒宽限内再判定)
|
|
61
75
|
/** 多角色(2026-11-17):镜像开关文件可按角色注入;缺省 legacy 全局 settings.json */
|
|
62
76
|
settingsFile?: string
|
|
77
|
+
/** 角色级摘要回复锚点;缺省仅用于轻量组件测试,不持久化。 */
|
|
78
|
+
anchorStore?: MirrorAnchorStore
|
|
63
79
|
/** A 方案(2026-11-23):摘要投递前过 cron 标记钩——注册提醒并返回剥净正文。
|
|
64
80
|
* 桌面端发起的回合也会输出 QQBOT_PAYLOAD,不经此钩会原样泄漏到 QQ。 */
|
|
65
81
|
onDigest?: (userId: string, digest: string) => string
|
|
@@ -89,28 +105,52 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
89
105
|
// 本册,镜像前核对摘要锚定的用户消息 id 是否命中——重放再迟也改变不了消息来源。
|
|
90
106
|
const qqPromptIds = new Map<string, Set<string>>() // sessionId -> QQ 派发过的 promptId 环
|
|
91
107
|
const QQ_PROMPT_ID_CAP = 200
|
|
108
|
+
const MIRROR_SESSION_STATE_CAP = 500
|
|
92
109
|
function markQqPrompt(sessionId: string, promptId: string): void {
|
|
93
110
|
if (!promptId) return
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
set = new Set()
|
|
97
|
-
qqPromptIds.set(sessionId, set)
|
|
98
|
-
}
|
|
111
|
+
const set = qqPromptIds.get(sessionId) ?? new Set<string>()
|
|
112
|
+
qqPromptIds.delete(sessionId) // LRU:最近使用移到末尾
|
|
99
113
|
if (set.size >= QQ_PROMPT_ID_CAP) {
|
|
100
114
|
const first = set.values().next().value
|
|
101
115
|
if (first !== undefined) set.delete(first)
|
|
102
116
|
}
|
|
103
117
|
set.add(promptId)
|
|
118
|
+
qqPromptIds.set(sessionId, set)
|
|
119
|
+
while (qqPromptIds.size > MIRROR_SESSION_STATE_CAP) {
|
|
120
|
+
const oldest = qqPromptIds.keys().next().value
|
|
121
|
+
if (oldest === undefined) break
|
|
122
|
+
qqPromptIds.delete(oldest)
|
|
123
|
+
}
|
|
104
124
|
}
|
|
105
125
|
const mirroredTurns = new Map<string, string>() // 逻辑回合幂等:多 location/重复完成事件只投一次
|
|
126
|
+
function rememberMirroredTurn(sessionId: string, turnKey: string): void {
|
|
127
|
+
mirroredTurns.delete(sessionId)
|
|
128
|
+
mirroredTurns.set(sessionId, turnKey)
|
|
129
|
+
while (mirroredTurns.size > MIRROR_SESSION_STATE_CAP) {
|
|
130
|
+
const oldest = mirroredTurns.keys().next().value
|
|
131
|
+
if (oldest === undefined) break
|
|
132
|
+
mirroredTurns.delete(oldest)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
106
135
|
const mirrorState = { enabled: loadMirrorEnabled(deps.settingsFile) }
|
|
107
136
|
|
|
108
137
|
// ===== 摘要镜像(E 阶段 A 方案):桌面会话轮次完成 → QQ 摘要卡 =====
|
|
109
138
|
// 与 /watch 观察推送互补:观察给过程里程碑,镜像给问答正文摘要。
|
|
110
139
|
// QQ 自己发起的轮次由 promptAndWait 正常回复,不重复镜像(qqTurnActive 守卫)。
|
|
140
|
+
// 订阅不是历史累加:始终是「当前绑定 sessionId 去重集」的幂等投影。
|
|
111
141
|
function ensureMirrorSubs(): void {
|
|
112
|
-
|
|
113
|
-
|
|
142
|
+
const desired = new Set(
|
|
143
|
+
(mirrorState.enabled ? sessions.all() : []).map((binding) => binding.sessionId),
|
|
144
|
+
)
|
|
145
|
+
let added = 0
|
|
146
|
+
let removed = 0
|
|
147
|
+
for (const [sessionId, unsub] of [...mirrorUnsubs]) {
|
|
148
|
+
if (desired.has(sessionId)) continue
|
|
149
|
+
unsub()
|
|
150
|
+
mirrorUnsubs.delete(sessionId)
|
|
151
|
+
removed++
|
|
152
|
+
}
|
|
153
|
+
for (const sessionId of desired) {
|
|
114
154
|
if (mirrorUnsubs.has(sessionId)) continue
|
|
115
155
|
mirrorUnsubs.set(
|
|
116
156
|
sessionId,
|
|
@@ -124,13 +164,21 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
124
164
|
void mirrorTurn(sessionId)
|
|
125
165
|
}),
|
|
126
166
|
)
|
|
167
|
+
added++
|
|
168
|
+
}
|
|
169
|
+
if (added > 0 || removed > 0) {
|
|
170
|
+
console.log(
|
|
171
|
+
`[mirror-reconcile] desired=${desired.size} added=${added} removed=${removed} actual=${mirrorUnsubs.size}`,
|
|
172
|
+
)
|
|
127
173
|
}
|
|
128
174
|
}
|
|
129
175
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
176
|
+
// 所有绑定变更即时对账;60s 周期只作遗漏兜底。定时器不阻止进程退出。
|
|
177
|
+
if (typeof sessions.onBindingChange === "function") {
|
|
178
|
+
sessions.onBindingChange(() => ensureMirrorSubs())
|
|
133
179
|
}
|
|
180
|
+
const reconcileTimer = setInterval(ensureMirrorSubs, 60_000)
|
|
181
|
+
reconcileTimer.unref?.()
|
|
134
182
|
|
|
135
183
|
// QQ 轮次结束后延迟解锁镜像:SSE 完成事件可能晚于 promptAndWait 返回,
|
|
136
184
|
// 5 秒宽限内若又有新 QQ 回合/后台等待在途则不解锁(防竞态开窗)。
|
|
@@ -149,11 +197,21 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
149
197
|
|
|
150
198
|
async function mirrorTurn(sessionID: string): Promise<void> {
|
|
151
199
|
try {
|
|
152
|
-
const
|
|
200
|
+
const bindings = sessions.all().filter((x) => x.sessionId === sessionID)
|
|
201
|
+
const owners = bindings.map((x) => x.userId)
|
|
153
202
|
if (owners.length === 0) {
|
|
154
203
|
console.log(`[mirror] 跳过:会话无映射主人 session=${sessionID}`)
|
|
155
204
|
return
|
|
156
205
|
}
|
|
206
|
+
let title: string | undefined
|
|
207
|
+
if (typeof client.session.get === "function") {
|
|
208
|
+
try {
|
|
209
|
+
title = (await client.session.get({ path: { id: sessionID } }))?.data?.title
|
|
210
|
+
} catch {
|
|
211
|
+
// 标题只是展示元数据:服务端读取失败走映射缓存,不阻断摘要正文。
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
title ??= bindings.find((binding) => binding.title?.trim())?.title
|
|
157
215
|
const listJson = await client.session.messages({ path: { id: sessionID } })
|
|
158
216
|
const messages = listJson?.data ?? []
|
|
159
217
|
const turnKey = digestTurnKey(messages)
|
|
@@ -167,16 +225,19 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
167
225
|
const anchorId = digestAnchorUserId(messages)
|
|
168
226
|
if (anchorId && qqPromptIds.get(sessionID)?.has(anchorId)) {
|
|
169
227
|
console.log(`[mirror] 跳过:QQ 直答回合(来源身份核对命中)session=${sessionID} prompt=${anchorId}`)
|
|
170
|
-
if (turnKey)
|
|
228
|
+
if (turnKey) rememberMirroredTurn(sessionID, turnKey)
|
|
171
229
|
return
|
|
172
230
|
}
|
|
173
|
-
const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID)
|
|
231
|
+
const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID), {
|
|
232
|
+
sessionId: sessionID,
|
|
233
|
+
title,
|
|
234
|
+
})
|
|
174
235
|
if (!digest) {
|
|
175
236
|
console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`)
|
|
176
237
|
return
|
|
177
238
|
}
|
|
178
239
|
// 在投递前占位:两个完成事件并发到达时,后到的回调也会命中同一回合并被去重。
|
|
179
|
-
if (turnKey)
|
|
240
|
+
if (turnKey) rememberMirroredTurn(sessionID, turnKey)
|
|
180
241
|
for (const userId of owners) {
|
|
181
242
|
// 无最近 ctx(重启后尚未收到新消息)→ 构造主动通道 ctx,
|
|
182
243
|
// deliver 的被动尝试失败会自然降级为主动消息(D4 配额内)。
|
|
@@ -188,7 +249,33 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
188
249
|
const cronHook = deps.onDigest
|
|
189
250
|
const outText = cronHook ? cronHook(userId, digest) : digest
|
|
190
251
|
if (!outText.trim()) continue // 纯提醒标记的摘要:注册即全部语义,无可镜像内容
|
|
191
|
-
|
|
252
|
+
const onSent: OnSentMessage = (receipt) => {
|
|
253
|
+
if (!deps.anchorStore) return
|
|
254
|
+
if (!receipt.refIdx) {
|
|
255
|
+
console.warn(
|
|
256
|
+
`[mirror-anchor] QQ 未返回 ref_idx,摘要不可安全路由 session=${sessionID} user=${userId.slice(0, 8)}…`,
|
|
257
|
+
)
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
deps.anchorStore.record({
|
|
262
|
+
refIdx: receipt.refIdx,
|
|
263
|
+
messageId: receipt.id,
|
|
264
|
+
userId,
|
|
265
|
+
sessionId: sessionID,
|
|
266
|
+
title: clipDigestTitle(redactSecrets(title ?? "")),
|
|
267
|
+
sentAt: Date.now(),
|
|
268
|
+
})
|
|
269
|
+
console.log(
|
|
270
|
+
`[mirror-anchor] 已登记 session=${digestSessionLabel(sessionID)} user=${userId.slice(0, 8)}…`,
|
|
271
|
+
)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.error("[mirror-anchor] 锚点落盘失败,后续引用将 fail-closed:", error)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
await safeDeliver(ctx, outText, onSent, {
|
|
277
|
+
continuationPrefix: `📋 摘要续 · ${digestSessionLabel(sessionID)}\n`,
|
|
278
|
+
})
|
|
192
279
|
}
|
|
193
280
|
console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`)
|
|
194
281
|
} catch (error) {
|
|
@@ -204,17 +291,20 @@ export function createMirror(deps: MirrorDeps): Mirror {
|
|
|
204
291
|
if (enabled) {
|
|
205
292
|
if (!prev) ensureMirrorSubs()
|
|
206
293
|
} else {
|
|
207
|
-
|
|
294
|
+
ensureMirrorSubs()
|
|
208
295
|
}
|
|
209
296
|
return enabled
|
|
210
297
|
? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要"
|
|
211
298
|
: "🔇 摘要镜像已关闭(/status mirror on 重新开启)"
|
|
212
299
|
},
|
|
213
300
|
status() {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
301
|
+
if (!mirrorState.enabled) return "📋 摘要镜像:关(/status mirror on 开启)"
|
|
302
|
+
const desired = new Set(sessions.all().map((binding) => binding.sessionId))
|
|
303
|
+
const actual = mirrorUnsubs.size
|
|
304
|
+
const aligned = desired.size === actual && [...desired].every((sessionId) => mirrorUnsubs.has(sessionId))
|
|
305
|
+
return aligned
|
|
306
|
+
? "📋 摘要镜像:开"
|
|
307
|
+
: `⚠️ 摘要镜像:开 · 订阅对账异常(期望 ${desired.size} / 实际 ${actual})`
|
|
218
308
|
},
|
|
219
309
|
}
|
|
220
310
|
|
package/src/core/notices.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @input: 无依赖(纯文本工具)
|
|
2
2
|
// @output: cmdInput/cmdEnter 标签构造、stripInteractionTags 兜底剥离、NOTICE 文案目录
|
|
3
|
-
// @pos: core - 通知文案目录(2026-11-22
|
|
4
|
-
//
|
|
3
|
+
// @pos: core - 通知文案目录(2026-11-22:参考 dsh-qqbot errors.ts/session-notice.ts
|
|
4
|
+
// 的文案目录化设计,用户可见文案单一出口、可测;P0 佐证=QQ 官方文档「文本交互」
|
|
5
5
|
// bot.q.qq.com/wiki api-v2,2026-10-26 更新版,<qqbot-cmd-input>/<qqbot-cmd-enter> 形状确认)
|
|
6
6
|
//
|
|
7
7
|
// ⚠️ 平台边界(官方文档原文):
|
package/src/core/notify-sink.ts
CHANGED
|
@@ -64,7 +64,7 @@ export function createNotifySink(options: NotifySinkOptions): NotifySink {
|
|
|
64
64
|
const ctx = entry.ctx as MessageContext
|
|
65
65
|
// fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
|
|
66
66
|
// maxAttempts 由 start 透传到 recover/flush:失败达到上限后保持 failed,不再无限退避。
|
|
67
|
-
return options.deliver(ctx, text).then(() => ({ delivered
|
|
67
|
+
return options.deliver(ctx, text).then((delivered) => ({ delivered, text: text.slice(0, 120) }))
|
|
68
68
|
})
|
|
69
69
|
outbox.start({ recover: true, maxAttempts }).catch((error) => {
|
|
70
70
|
console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// @input: 纯文本(无依赖)
|
|
2
2
|
// @output: stripScaffolding
|
|
3
|
-
// @pos: core - 出站脚手架消毒(2026-11-23
|
|
3
|
+
// @pos: core - 出站脚手架消毒(2026-11-23 派生修订 Z 项,源=openclaw outbound/sanitize.ts P0)
|
|
4
|
+
// 本文件保留上游主要正则与剥离顺序,合并残留标签规则并调整返回处理,属于派生修订。
|
|
5
|
+
// 上游版权与许可见 THIRD_PARTY_NOTICES.md。
|
|
4
6
|
//
|
|
5
7
|
// 背景:模型偶发把内部推理/脚手架块写进正文( thinking/system-reminder 等),
|
|
6
8
|
// QQ 会把原始标签渲染给用户。出站前统一剥离——主路径(formatForQQMarkdown)与
|
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
// 限额耗尽或窗口过期后继续"被动回复"必然被平台拒绝,白白浪费一次 API 往返
|
|
7
7
|
// 且推迟送达。本模块在被动尝试前预判:不可被动 → 直接走主动通道(调用方
|
|
8
8
|
// 负责主动配额记账),可被动 → 放行并在发送成功后记账。
|
|
9
|
-
//
|
|
10
|
-
//
|
|
9
|
+
// 实现参考 tencent-connect/openclaw-qqbot(MIT):src/outbound/reply-limiter.ts。
|
|
10
|
+
// 本文件与该实现具有相同的接口、默认参数和核心状态机,属于派生修订而非独立原创。
|
|
11
|
+
// 上游版权与许可全文见 THIRD_PARTY_NOTICES.md;本项目保留来源声明,不删除或淡化归属。
|
|
11
12
|
export interface ReplyLimiterConfig {
|
|
12
13
|
/** 每条消息最大被动回复次数(官方规则 4) */
|
|
13
14
|
limit?: number
|
package/src/core/send-media.ts
CHANGED
|
@@ -87,10 +87,10 @@ export interface SendLocalFileDeps {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
*
|
|
91
|
-
* file:// 前缀剥离(含 Windows file:///C:/ 三斜杠形态)→ URL decode(非法编码按原样)
|
|
92
|
-
* → ~
|
|
93
|
-
*
|
|
90
|
+
* normalizeLocalPath 派生修订自 openclaw local-file-router 的 normalizePath:
|
|
91
|
+
* 保留 file:// 前缀剥离(含 Windows file:///C:/ 三斜杠形态)→ URL decode(非法编码按原样)
|
|
92
|
+
* → ~ 展开为家目录的相同处理顺序。白名单/拒绝名单判定必须先于或基于规范化结果,
|
|
93
|
+
* 否则同一文件因写法不同得到两种判定。该函数来源见 THIRD_PARTY_NOTICES.md。
|
|
94
94
|
*/
|
|
95
95
|
export function normalizeLocalPath(p: string): string {
|
|
96
96
|
let r = p.trim()
|
|
@@ -115,8 +115,8 @@ export async function sendLocalFile(
|
|
|
115
115
|
filePath: string,
|
|
116
116
|
deps: SendLocalFileDeps,
|
|
117
117
|
): Promise<string> {
|
|
118
|
-
// X 项(2026-11-22
|
|
119
|
-
//
|
|
118
|
+
// X 项(2026-11-22):上述 normalizeLocalPath 为派生修订,来源已登记;其余发送、
|
|
119
|
+
// 拒绝名单/白名单、上传流程为项目实现。规范化在拒绝名单/白名单之前(否则
|
|
120
120
|
// file:///C:/x 与 C:/x 同一文件两种判定结果)。非法编码按原样不炸。
|
|
121
121
|
const trimmed = normalizeLocalPath(filePath)
|
|
122
122
|
// DEF-qqbot-20261112-03:文件级拒绝优先于目录白名单(穿越解析落白名单根也拦)
|
package/src/core/stt.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @input: 音频字节 + OpenAI 兼容 STT 端点配置(fetch 可注入,测试用)
|
|
2
2
|
// @output: sttConfigured / sttTranscribe
|
|
3
|
-
// @pos: core - 语音外部转写回退(2026-11-23
|
|
3
|
+
// @pos: core - 语音外部转写回退(2026-11-23 学习参考 AD 项,源=hermes-agent adapter.py P0 邻接)
|
|
4
4
|
//
|
|
5
5
|
// 链路:QQ 内置 ASR(asr_refer_text,免费优先)→ 空时回退本模块(GLM-ASR/Whisper/
|
|
6
6
|
// 任意 OpenAI 兼容 /audio/transcriptions 端点)。未配置三键时本模块整体离线——
|
package/src/index.ts
CHANGED
|
@@ -102,7 +102,7 @@ async function main(): Promise<void> {
|
|
|
102
102
|
allowedUsers: r.allowedUsers,
|
|
103
103
|
})
|
|
104
104
|
|
|
105
|
-
// M 项(2026-10-30
|
|
105
|
+
// M 项(2026-10-30,参考竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
|
|
106
106
|
// 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
|
|
107
107
|
// 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
|
|
108
108
|
// 场景:多 location 并发拉起时防待命实例堆积)。
|
package/src/opencode/mirror.ts
CHANGED
|
@@ -10,6 +10,43 @@ import { redactSecrets } from "./history.js"
|
|
|
10
10
|
import { labelBlock } from "../core/markdown.js"
|
|
11
11
|
|
|
12
12
|
const USER_CLIP = 160
|
|
13
|
+
export const DIGEST_TITLE_MAX_WIDTH = 20 // 10 个中文,或 20 个 ASCII 的等效显示宽度
|
|
14
|
+
|
|
15
|
+
function isWideCodePoint(cp: number): boolean {
|
|
16
|
+
return cp >= 0x1100 && (
|
|
17
|
+
cp <= 0x115f || cp === 0x2329 || cp === 0x232a ||
|
|
18
|
+
(cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
|
|
19
|
+
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
20
|
+
(cp >= 0xf900 && cp <= 0xfaff) ||
|
|
21
|
+
(cp >= 0xfe10 && cp <= 0xfe19) ||
|
|
22
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) ||
|
|
23
|
+
(cp >= 0xff00 && cp <= 0xff60) ||
|
|
24
|
+
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
|
25
|
+
(cp >= 0x1f000 && cp <= 0x1faff) ||
|
|
26
|
+
(cp >= 0x20000 && cp <= 0x3fffd)
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 会话标题按终端等效显示宽度截断:中文/全角/emoji 2 列,ASCII 1 列。 */
|
|
31
|
+
export function clipDigestTitle(value: string | undefined, maxWidth = DIGEST_TITLE_MAX_WIDTH): string {
|
|
32
|
+
const title = (value ?? "").replace(/\s+/g, " ").trim() || "未命名会话"
|
|
33
|
+
let width = 0
|
|
34
|
+
let out = ""
|
|
35
|
+
for (const char of title) {
|
|
36
|
+
const cp = char.codePointAt(0) ?? 0
|
|
37
|
+
const charWidth = /\p{Mark}/u.test(char) || cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f)
|
|
38
|
+
? 0
|
|
39
|
+
: isWideCodePoint(cp) ? 2 : 1
|
|
40
|
+
if (width + charWidth > maxWidth) return `${out}...`
|
|
41
|
+
out += char
|
|
42
|
+
width += charWidth
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function digestSessionLabel(sessionId: string): string {
|
|
48
|
+
return sessionId.length > 10 ? `${sessionId.slice(0, 10)}…` : sessionId
|
|
49
|
+
}
|
|
13
50
|
|
|
14
51
|
// E2(2026-10-29,用户要求"摘要回全文"):答案截断上限改为运行时可配——
|
|
15
52
|
// 默认 0=不截断回全文(投递层 splitMessage 自动分条送达);设
|
|
@@ -50,8 +87,17 @@ export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
|
50
87
|
return null
|
|
51
88
|
}
|
|
52
89
|
|
|
90
|
+
export interface DigestIdentity {
|
|
91
|
+
sessionId: string
|
|
92
|
+
title?: string
|
|
93
|
+
}
|
|
94
|
+
|
|
53
95
|
// 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
|
|
54
|
-
export function buildDigest(
|
|
96
|
+
export function buildDigest(
|
|
97
|
+
messages: SessionMessage[],
|
|
98
|
+
goalObjective?: string,
|
|
99
|
+
identity?: DigestIdentity,
|
|
100
|
+
): string | null {
|
|
55
101
|
const ordered = [...messages].reverse()
|
|
56
102
|
|
|
57
103
|
// A 方案第三桶(owner 2026-11-23):回合边界消息 type=synthetic = 引擎自主注入
|
|
@@ -90,7 +136,13 @@ export function buildDigest(messages: SessionMessage[], goalObjective?: string):
|
|
|
90
136
|
}
|
|
91
137
|
if (!answer) return null
|
|
92
138
|
|
|
93
|
-
const
|
|
139
|
+
const kind = goalDriven ? "🎯 目标续跑摘要" : "📋 桌面问答摘要"
|
|
140
|
+
const lines = [
|
|
141
|
+
identity
|
|
142
|
+
? `${kind} · ${clipDigestTitle(identity.title)} · ${digestSessionLabel(identity.sessionId)}`
|
|
143
|
+
: kind,
|
|
144
|
+
]
|
|
145
|
+
if (identity) lines.push("↩️ 引用回复仅在该会话仍为当前绑定时受理")
|
|
94
146
|
if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
|
|
95
147
|
const clipLimit = answerClipLimit()
|
|
96
148
|
if (clipLimit > 0) {
|
package/src/opencode/sessions.ts
CHANGED
|
@@ -18,9 +18,12 @@ interface UserSession {
|
|
|
18
18
|
|
|
19
19
|
const STORE_FILE = storageFile("sessions.json")
|
|
20
20
|
|
|
21
|
+
export type SessionBindingListener = (userId: string, sessionId: string | null) => void
|
|
22
|
+
|
|
21
23
|
export class SessionManager {
|
|
22
24
|
private sessions = new Map<string, UserSession>()
|
|
23
25
|
private client: OpencodeClient
|
|
26
|
+
private readonly bindingListeners = new Set<SessionBindingListener>()
|
|
24
27
|
/** DEF-qqbot-20261112-7:持久化路径可注入——单测必须写临时文件,禁写生产映射
|
|
25
28
|
* (2026-11-12 实证:session-model/status-title 套件直写 ~/.openqq/sessions.json,
|
|
26
29
|
* 夹具 u1-u4/sid2-4 垃圾入库;多管理器陈旧整图回写还把 owner 绑定顶回去) */
|
|
@@ -67,6 +70,20 @@ export class SessionManager {
|
|
|
67
70
|
}
|
|
68
71
|
}
|
|
69
72
|
|
|
73
|
+
/** 绑定目标变化通知:只在新增、换绑、驱逐后触发;标题/目录/模型回写不触发。 */
|
|
74
|
+
onBindingChange(listener: SessionBindingListener): () => void {
|
|
75
|
+
this.bindingListeners.add(listener)
|
|
76
|
+
return () => this.bindingListeners.delete(listener)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private emitBindingChange(userId: string, sessionId: string | null): void {
|
|
80
|
+
for (const listener of this.bindingListeners) {
|
|
81
|
+
try { listener(userId, sessionId) } catch (error) {
|
|
82
|
+
console.error("[sessions] 绑定变化通知失败:", error)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
70
87
|
async getOrCreate(userId: string): Promise<UserSession> {
|
|
71
88
|
const existing = this.sessions.get(userId)
|
|
72
89
|
if (existing) return existing
|
|
@@ -79,6 +96,7 @@ export class SessionManager {
|
|
|
79
96
|
}
|
|
80
97
|
this.sessions.set(userId, session)
|
|
81
98
|
this.saveSessions()
|
|
99
|
+
this.emitBindingChange(userId, session.sessionId)
|
|
82
100
|
await this.enforceLocation(userId, session.sessionId, directory)
|
|
83
101
|
return session
|
|
84
102
|
}
|
|
@@ -99,6 +117,7 @@ export class SessionManager {
|
|
|
99
117
|
}
|
|
100
118
|
this.sessions.set(userId, session)
|
|
101
119
|
this.saveSessions()
|
|
120
|
+
if (!prev || prev.sessionId !== session.sessionId) this.emitBindingChange(userId, session.sessionId)
|
|
102
121
|
if (inheritedModel) {
|
|
103
122
|
void this.client.session
|
|
104
123
|
.setModel({ path: { id: session.sessionId }, body: { model: inheritedModel } })
|
|
@@ -132,6 +151,7 @@ export class SessionManager {
|
|
|
132
151
|
// 是会话级状态(桌面端同语义),不得用本用户在此前会话的偏好覆盖目标会话;
|
|
133
152
|
// 反向从目标会话回读真实设置写回映射(/status 与后续 /model 以目标为准)。
|
|
134
153
|
if (changed) {
|
|
154
|
+
this.emitBindingChange(userId, sessionId)
|
|
135
155
|
void this.refreshSettingsFromServer(userId)
|
|
136
156
|
}
|
|
137
157
|
}
|
|
@@ -219,8 +239,13 @@ export class SessionManager {
|
|
|
219
239
|
}
|
|
220
240
|
|
|
221
241
|
// 枚举全部映射(摘要镜像订阅、会话→用户反查、interactionTick 权限分仓轮询用)
|
|
222
|
-
all(): Array<{ userId: string; sessionId: string; directory?: string }> {
|
|
223
|
-
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
242
|
+
all(): Array<{ userId: string; sessionId: string; title?: string; directory?: string }> {
|
|
243
|
+
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
244
|
+
userId,
|
|
245
|
+
sessionId: s.sessionId,
|
|
246
|
+
...(s.title ? { title: s.title } : {}),
|
|
247
|
+
directory: s.directory,
|
|
248
|
+
}))
|
|
224
249
|
}
|
|
225
250
|
|
|
226
251
|
/**
|
|
@@ -231,6 +256,7 @@ export class SessionManager {
|
|
|
231
256
|
const had = this.sessions.delete(userId)
|
|
232
257
|
if (had) {
|
|
233
258
|
this.saveSessions()
|
|
259
|
+
this.emitBindingChange(userId, null)
|
|
234
260
|
console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`)
|
|
235
261
|
}
|
|
236
262
|
return had
|
package/src/qq/api.ts
CHANGED
|
@@ -263,7 +263,7 @@ export async function apiRequest<T = unknown>(
|
|
|
263
263
|
console.log("[qqbot-api] >>> Body:", JSON.stringify(logBody, null, 2))
|
|
264
264
|
}
|
|
265
265
|
|
|
266
|
-
// O 项(2026-10-30
|
|
266
|
+
// O 项(2026-10-30,参考竞品 opencode-qq-v2 postWithRetry):HTTP 429 限流时
|
|
267
267
|
// 尊重 Retry-After 退避重试(最多再试 2 次,单次等待封顶 30s);其余错误不重试。
|
|
268
268
|
// 429 语义=请求被拒绝未生效,重试无副作用。
|
|
269
269
|
let res: Response | undefined
|
|
@@ -346,8 +346,16 @@ export async function getGatewayUrl(accessToken: string): Promise<string> {
|
|
|
346
346
|
* QQ 发消息成功后的通用响应结构。
|
|
347
347
|
*/
|
|
348
348
|
export interface MessageResponse {
|
|
349
|
+
/** 新发出的 QQ 消息 ID(撤回等用途),不是后续引用 lookup 的键。 */
|
|
349
350
|
id: string
|
|
350
351
|
timestamp: number | string
|
|
352
|
+
/** 官方引用索引:机器人消息被长按回复时,入站 ref_msg_idx 对应此 ref_idx。 */
|
|
353
|
+
ext_info?: { ref_idx?: string }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export interface SentMessageReceipt {
|
|
357
|
+
id: string
|
|
358
|
+
refIdx?: string
|
|
351
359
|
}
|
|
352
360
|
|
|
353
361
|
/**
|