@linjz/opencode-qqbot 0.3.18 → 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.
@@ -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]) => ({ userId, sessionId: s.sessionId, directory: s.directory }))
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,吸收竞品 opencode-qq-v2 postWithRetry):HTTP 429 限流时
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
  /**
package/src/qq/gateway.ts CHANGED
@@ -144,7 +144,7 @@ function scheduleReconnect(state: GatewayState, connect: () => Promise<void>, cu
144
144
  }, delayMs)
145
145
  }
146
146
 
147
- // —— AB:快断连风暴守卫(2026-11-23 学习吸收,源=hermes-agent adapter.py P0 邻接)——
147
+ // —— AB:快断连风暴守卫(2026-11-23 学习参考,源=hermes-agent adapter.py P0 邻接)——
148
148
  // 背景:指数退避(1s→30s)只放缓单个重连,挡不住「坏凭据/网络抖动」的无限循环——
149
149
  // bot 会在 1~30s 档永远空转且日志无声。守卫口径:窗口内快断连(建连后秒挂)累计
150
150
  // 达上限 → 升级 5min 静默冷却 + 高声错误日志(排障信号),冷却后再犯重新累计。
@@ -248,6 +248,17 @@ function briefAttachments(atts: MessageAttachment[]): unknown[] {
248
248
  })
249
249
  }
250
250
 
251
+ export function referencedMessageId(
252
+ event: Pick<C2CMessageEvent, "message_scene" | "message_reference">,
253
+ ): string | undefined {
254
+ const prefix = "ref_msg_idx="
255
+ const official = event.message_scene?.ext
256
+ ?.find((item) => typeof item === "string" && item.startsWith(prefix))
257
+ ?.slice(prefix.length)
258
+ .trim()
259
+ return official || event.message_reference?.message_id
260
+ }
261
+
251
262
  function toC2CMessageContext(event: C2CMessageEvent): MessageContext {
252
263
  return {
253
264
  type: "c2c",
@@ -256,7 +267,7 @@ function toC2CMessageContext(event: C2CMessageEvent): MessageContext {
256
267
  content: normalizeMessageContent(event.content),
257
268
  // DEF-qqbot-20261111-P2:纯表情标记随 ctx 传递,bridge 丢弃点据此刻回有据提示(不再静默吞)
258
269
  ...(isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {}),
259
- referencedMsgId: event.message_reference?.message_id,
270
+ referencedMsgId: referencedMessageId(event),
260
271
  attachments: event.attachments,
261
272
  timestamp: event.timestamp,
262
273
  rawEvent: event,
@@ -272,7 +283,7 @@ function toGroupMessageContext(event: GroupMessageEvent): MessageContext {
272
283
  content: stripGroupAtPrefix(event.content),
273
284
  // DEF-qqbot-20261111-P2:群聊同口径(纯表情有据提示不静默)
274
285
  ...(isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {}),
275
- referencedMsgId: event.message_reference?.message_id,
286
+ referencedMsgId: referencedMessageId(event),
276
287
  attachments: event.attachments,
277
288
  timestamp: event.timestamp,
278
289
  rawEvent: event,
@@ -300,8 +311,8 @@ function sendIdentify(ws: WebSocket, accessToken: string): void {
300
311
  shard: [0, 1],
301
312
  properties: {
302
313
  os: process.platform,
303
- browser: "opencode_qq_bot",
304
- device: "opencode_qq_bot",
314
+ browser: "opencode_qqbot",
315
+ device: "opencode_qqbot",
305
316
  },
306
317
  },
307
318
  }
package/src/qq/media.ts CHANGED
@@ -93,7 +93,7 @@ export async function downloadQQAttachment(
93
93
  if (isVoice && att.asr_refer_text?.trim()) {
94
94
  return { voice: att.asr_refer_text.trim() }
95
95
  }
96
- // AD(2026-11-23 学习吸收):QQ 内置 ASR 无转写 → 外部 STT 回退(hermes 双级链同款)。
96
+ // AD(2026-11-23 学习参考):QQ 内置 ASR 无转写 → 外部 STT 回退(hermes 双级链同款)。
97
97
  // 需 QQ_STT_BASE_URL+QQ_STT_API_KEY 齐配(QQ_STT_MODEL 默认 whisper-1);未配置保持
98
98
  // 既有「不支持」路径零变化。音频仍走 QQ 域白名单+token 重试,10MB 上限同图片口径。
99
99
  if (isVoice && sttConfigured()) {
package/src/qq/sender.ts CHANGED
@@ -5,7 +5,13 @@
5
5
  // QQ 机器人自定义 Markdown(msg_type=2)已对单聊/群聊全量开放,无需模板。
6
6
  // QQ markdown 能完整渲染标准语法: 表格、行内代码/代码块、加粗、标题、列表、链接、引用等。
7
7
  // 因此主路径直接透传 AI 的 markdown 原文,交给 QQ 渲染;仅在发送失败时回退纯文本。
8
- import { sendC2CMessage, sendGroupMessage, getNextMsgSeq, type MessageResponse } from "./api.js"
8
+ import {
9
+ sendC2CMessage,
10
+ sendGroupMessage,
11
+ getNextMsgSeq,
12
+ type MessageResponse,
13
+ type SentMessageReceipt,
14
+ } from "./api.js"
9
15
  import type { MessageContext } from "./types.js"
10
16
  import { normalizeOutboundMarkdown, matchFence, type FenceToken } from "../core/markdown.js"
11
17
  import { stripInteractionTags } from "../core/notices.js"
@@ -82,7 +88,7 @@ export function formatForQQ(text: string): string {
82
88
  processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i])
83
89
  }
84
90
 
85
- // 交互标签兜底剥离(2026-11-22 学习吸收轮):<qqbot-cmd-input> 等仅 markdown 消息生效,
91
+ // 交互标签兜底剥离(2026-11-22 学习参考):<qqbot-cmd-input> 等仅 markdown 消息生效,
86
92
  // 纯文本通道必须把标签降级为可读文本,否则尖括号原样糊给用户(AstrBot#8755 同款坑)。
87
93
  // 围栏内是代码字面量,不动。
88
94
  let inStripFence = false
@@ -145,12 +151,13 @@ function utf8Bytes(s: string): number {
145
151
  return encoder.encode(s).length
146
152
  }
147
153
 
148
- // —— 结构化分条(2026-10-29 固化:设计吸收自 dsh-qqbot 分条器 chunker,P0)——
149
- // dsh 语义:GFM 表格聚成原子单元不跨片拆散 + 按行边界打包;
150
- // 我方在 dsh 之上补两件事:① 字节预算(QQ 按 UTF-8 字节限长,dsh 按字符数会
151
- // 踩中文 3 字节坑)② 围栏修补——在代码块中间切断时给前片补闭合、后片补开围栏
152
- // (带语言),保证每片 markdown 独立可渲染。围栏识别与出站兜底共用 core/markdown
154
+ // —— 结构化分条(2026-10-29 固化)——
155
+ // 设计参考 dsh-qqbot 的 chunker:GFM 表格作为原子单元并按行边界打包。
156
+ // 本实现按项目需求独立扩展:① UTF-8 字节预算,避免中文字符数与字节数不一致;
157
+ // ② 代码块跨片时前片补闭合、后片补开围栏(带语言),使每片独立可渲染;
158
+ // ③ 超长单元按段落/换行/码点分级切分。围栏识别与出站兜底共用 core/markdown
153
159
  // (2026-11-10:补 ~~~ 与 4+ 标记长度,避免波浪围栏被当正文切碎)。
160
+ // 上游来源与许可见 THIRD_PARTY_NOTICES.md。
154
161
  const GFM_TABLE_LINE = /^\s*\|.*\|\s*$/
155
162
 
156
163
  interface LineUnit {
@@ -328,12 +335,29 @@ async function sendChunk(
328
335
  export interface ReplyToQQOptions {
329
336
  /** J-轻(2026-10-30):伪流式错峰——多片发送时片间间隔 ms(默认 0=一次性全发) */
330
337
  staggerMs?: number
338
+ /** 每片真实发送成功立即回调;后续分片失败也不丢已发分片的锚点。 */
339
+ onReceipt?: (receipt: SentMessageReceipt) => void | Promise<void>
340
+ /** 第 2 片起的受控身份前缀;先预留字节、切分后再添加。 */
341
+ continuationPrefix?: string
342
+ }
343
+
344
+ export class PartialReplyError extends Error {
345
+ readonly name = "PartialReplyError"
346
+ constructor(
347
+ readonly receipts: readonly SentMessageReceipt[],
348
+ readonly failedChunkIndex: number,
349
+ readonly originalError: unknown,
350
+ ) {
351
+ super(`QQ 分片发送中断:第 ${failedChunkIndex + 1} 片失败,此前已成功 ${receipts.length} 片`)
352
+ }
331
353
  }
332
354
 
333
355
  export interface ReplyResult {
334
356
  chunks: number
335
- /** 服务端回执的消息 id(引用解析缓存登记用) */
357
+ /** 服务端回执的消息 id(兼容既有引用缓存调用方) */
336
358
  ids: string[]
359
+ /** 每个真实分片的完整回执:refIdx 才是摘要锚点 lookup 键。 */
360
+ receipts: SentMessageReceipt[]
337
361
  }
338
362
 
339
363
  export async function replyToQQ(
@@ -347,18 +371,44 @@ export async function replyToQQ(
347
371
 
348
372
  // 关键:按 UTF-8 字节切分(上限见文件头考据注释:2 万字实测),不能用字符数 maxLength,
349
373
  // 否则中文长消息会超限被 QQ 静默丢弃(看似"答非所问",实则是答案没发出去)。
350
- const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES)
351
- const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES)
374
+ const continuationPrefix = options?.continuationPrefix ?? ""
375
+ const continuationBytes = utf8Bytes(continuationPrefix)
376
+ if (continuationBytes >= Math.min(MARKDOWN_MAX_BYTES, PLAIN_MAX_BYTES) - 1024) {
377
+ throw new Error("continuationPrefix 过长,无法为正文预留分片空间")
378
+ }
379
+ // 所有片都预留续片前缀字节,续片在切分后再加标记——身份绝不会被切到上一片。
380
+ const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES - continuationBytes)
381
+ .map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk)
382
+ const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES - continuationBytes)
383
+ .map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk)
352
384
 
353
385
  const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0)
354
- const ids: string[] = []
386
+ const receipts: SentMessageReceipt[] = []
355
387
  for (let i = 0; i < mdChunks.length; i++) {
356
388
  if (i > 0 && delays[i - 1]) await sleep(delays[i - 1])
357
389
  const msgSeq = getNextMsgSeq(ctx.msgId)
358
390
  // 纯文本分片可能与 markdown 分片数量不一致,按索引兜底取对应/最后一片
359
391
  const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i]
360
- const res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq)
361
- if (res?.id) ids.push(res.id)
392
+ let res: MessageResponse | null
393
+ try {
394
+ res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq)
395
+ } catch (error) {
396
+ if (receipts.length > 0) throw new PartialReplyError(receipts, i, error)
397
+ throw error
398
+ }
399
+ if (res?.id) {
400
+ const receipt: SentMessageReceipt = {
401
+ id: res.id,
402
+ ...(res.ext_info?.ref_idx ? { refIdx: res.ext_info.ref_idx } : {}),
403
+ }
404
+ receipts.push(receipt)
405
+ try {
406
+ await options?.onReceipt?.(receipt)
407
+ } catch (error) {
408
+ // 已发分片的簿记错误不得中断后续发送,更不能触发上层降级重发。
409
+ console.error("[qq-sender] 分片回执回调失败:", error)
410
+ }
411
+ }
362
412
  }
363
- return { chunks: mdChunks.length, ids }
413
+ return { chunks: mdChunks.length, ids: receipts.map((receipt) => receipt.id), receipts }
364
414
  }
package/src/qq/types.ts CHANGED
@@ -35,6 +35,8 @@ export interface C2CMessageEvent {
35
35
  timestamp: string
36
36
  message_scene?: {
37
37
  source: string
38
+ /** 官方 103 引用事件:ref_msg_idx=<发送响应 ext_info.ref_idx> */
39
+ ext?: string[]
38
40
  }
39
41
  attachments?: MessageAttachment[]
40
42
  /** 长按回复引用的消息 id(QQ 客户端引用消息) */
@@ -78,6 +80,7 @@ export interface GroupMessageEvent {
78
80
  timestamp: string
79
81
  group_id: string
80
82
  group_openid: string
83
+ message_scene?: { source: string; ext?: string[] }
81
84
  attachments?: MessageAttachment[]
82
85
  /** 长按回复引用的消息 id(QQ 客户端引用消息) */
83
86
  message_reference?: { message_id: string }
@@ -141,7 +144,7 @@ export interface MessageContext {
141
144
  groupId?: string
142
145
  msgId: string
143
146
  content: string
144
- /** 长按回复引用的消息 id(经 message_reference 透传) */
147
+ /** 长按回复的引用索引:官方 ref_msg_idx 优先,兼容 message_reference.message_id */
145
148
  referencedMsgId?: string
146
149
  /** 解析后的引用上文(bridge 从 context-buffer 解析得到,注入 prompt 前缀) */
147
150
  quoteText?: string