@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.1

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.
@@ -1,15 +1,20 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
+ import type { Location } from "@opencode/schema"
2
3
  import { SessionMessage } from "@opencode/schema"
3
4
  import { Mutex } from "async-mutex"
4
5
  import { type ChatTarget, isTargetEnabled, parseTargetKey, targetKey, targetLabel } from "../chat"
5
6
  import type { QQBotConfig } from "../config"
7
+ import type { BotHome } from "../home"
6
8
  import type { Logger } from "../logger"
9
+ import type { HistoryPosition, HistoryProvider } from "../naplink/history"
7
10
  import { limitFiles, type PromptFile } from "../naplink/render"
8
11
 
9
12
  /** 插件存储里保存会话与目标绑定的键。 */
10
13
  const BINDINGS_KEY = "bindings"
11
14
  /** 插件存储里保存目标最近活跃时间的键。 */
12
15
  const ACTIVITY_KEY = "activity"
16
+ /** 插件存储里保存每个目标已投递到的消息位置的键。 */
17
+ const POSITIONS_KEY = "positions"
13
18
  /** 单个目标最多缓存的消息条数。 */
14
19
  export const MAX_BUFFER_TURNS = 100
15
20
  /** 单个目标最多缓存的文本与附件字节数。 */
@@ -18,12 +23,25 @@ export const MAX_BUFFER_BYTES = 32 * 1024 * 1024
18
23
  const MAX_TRACKED_MESSAGES = 200
19
24
  /** 刚投递的一轮还没在上游体现出忙碌状态,先跳过对账避免重复投递。 */
20
25
  export const SUBMIT_GRACE_MS = 5_000
26
+ /** 失败批次最多重试几次;超过次数就丢弃,避免一个目标被永久堵死。 */
27
+ export const PENDING_MAX_ATTEMPTS = 3
28
+ /** 缓存里还有消息时的兜底轮询间隔:上游结束事件丢了也能把消息放出去。 */
29
+ export const RESUME_INTERVAL_MS = 30_000
21
30
  function toMillis(value: unknown): number | undefined {
22
31
  if (value instanceof Date) return value.getTime()
23
32
  if (typeof value === "number") return value
24
33
  return undefined
25
34
  }
26
35
 
36
+ /** 解析存储里的消息位置,格式不对时忽略。 */
37
+ function parsePosition(value: unknown): HistoryPosition | undefined {
38
+ if (!value || typeof value !== "object") return undefined
39
+ const record = value as { id?: unknown; time?: unknown }
40
+ if (typeof record.id !== "string" || record.id.length === 0) return undefined
41
+ if (typeof record.time !== "number" || !Number.isFinite(record.time)) return undefined
42
+ return { id: record.id, time: record.time }
43
+ }
44
+
27
45
  /** 上游会话是否仍在执行;依据 `time.busy` 是否晚于 `time.idle`。 */
28
46
  function upstreamRunning(time: unknown): boolean {
29
47
  if (!time || typeof time !== "object") return false
@@ -44,6 +62,8 @@ export interface Turn {
44
62
  atMe: boolean
45
63
  /** 是否由主动说话心跳发起。 */
46
64
  proactive?: boolean
65
+ /** 本轮最后一条 QQ 消息的位置,用来记录已经投递到哪里。 */
66
+ source?: HistoryPosition
47
67
  }
48
68
 
49
69
  interface ChatState {
@@ -53,6 +73,8 @@ interface ChatState {
53
73
  buffer: Turn[]
54
74
  /** 已经尝试投递但失败的一批:内容与 id 冻结,重试时原样重发。 */
55
75
  pending?: Turn
76
+ /** 当前失败批次已经重试的次数;超过上限就丢弃这批。 */
77
+ pendingAttempts: number
56
78
  /** 最近一次投递的时间戳(毫秒)。 */
57
79
  lastDispatchAt: number
58
80
  /** 最近一次上游确认空闲的时间戳(毫秒)。 */
@@ -65,21 +87,39 @@ interface ChatState {
65
87
  reminders: number
66
88
  /** 最近一次真实用户消息的时间戳(毫秒)。 */
67
89
  lastUserMessageAt: number
90
+ /** 本次运行是否已经为该目标补过历史。 */
91
+ historyDone?: boolean
92
+ /** 会话是否是在本次运行中新建的。 */
93
+ sessionCreated?: boolean
68
94
  }
69
95
 
70
96
  type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
71
97
 
72
98
  export function mergeTurns(turns: readonly Turn[]): Turn {
99
+ // 同一条消息重复投递时只留一份。
100
+ const seen = new Set<string>()
101
+ const unique = turns.filter((turn) => {
102
+ if (!turn.source) return true
103
+ if (seen.has(turn.source.id)) return false
104
+ seen.add(turn.source.id)
105
+ return true
106
+ })
107
+ // 批次的位置取最后一条带位置的消息。
108
+ const source = unique.reduce<HistoryPosition | undefined>(
109
+ (latest, turn) => turn.source ?? latest,
110
+ undefined,
111
+ )
73
112
  return {
74
113
  // 合并后的批次沿用第一条消息的幂等键,重试时保持一致。
75
- ...(turns[0]?.id ? { id: turns[0].id } : {}),
76
- text: turns
114
+ ...(unique[0]?.id ? { id: unique[0].id } : {}),
115
+ text: unique
77
116
  .map((turn) => turn.text.trim())
78
117
  .filter((text) => text.length > 0)
79
118
  .join("\n"),
80
- files: limitFiles(turns.flatMap((turn) => turn.files)),
81
- atMe: turns.some((turn) => turn.atMe),
82
- ...(turns.some((turn) => turn.proactive) ? { proactive: true } : {}),
119
+ files: limitFiles(unique.flatMap((turn) => turn.files)),
120
+ atMe: unique.some((turn) => turn.atMe),
121
+ ...(unique.some((turn) => turn.proactive) ? { proactive: true } : {}),
122
+ ...(source ? { source } : {}),
83
123
  }
84
124
  }
85
125
 
@@ -107,13 +147,29 @@ export class SessionManager {
107
147
  private readonly saveMutex = new Mutex()
108
148
  private activity: Record<string, number> = {}
109
149
  private bindingsLoaded: Promise<void> | undefined
150
+ /** 每个目标已经投递到的位置。 */
151
+ private readonly positions = new Map<string, HistoryPosition>()
152
+ /** 启动时读到的位置快照,用于补齐重启期间错过的消息。 */
153
+ private readonly restoredPositions = new Map<string, HistoryPosition>()
154
+ /** 兜底轮询定时器:上游结束事件丢失时把缓存的消息投出去。 */
155
+ private watchdog: ReturnType<typeof setTimeout> | undefined
156
+ private disposed = false
110
157
 
111
158
  constructor(
112
159
  private readonly ctx: Plugin.Context,
113
160
  private readonly config: QQBotConfig,
114
161
  private readonly logger: Logger,
162
+ /** 机器人固定服务的工作目录,所有 QQ 会话都建在这里。 */
163
+ private readonly home: BotHome,
164
+ private readonly history?: HistoryProvider,
115
165
  ) {}
116
166
 
167
+ /** 会话统一落在机器人工作目录,避免接管后上下文散落到别的项目。 */
168
+ private get location(): Location.PublicRef {
169
+ // 目录最初就取自 location.directory,这里只是把存储里的字符串还原成品牌类型。
170
+ return { directory: this.home.directory as Location.PublicRef["directory"] }
171
+ }
172
+
117
173
  /** 载入上次运行时保存的目标与会话绑定。 */
118
174
  async load(): Promise<void> {
119
175
  await this.ensureBindings()
@@ -147,18 +203,41 @@ export class SessionManager {
147
203
 
148
204
  try {
149
205
  const activity = await this.ctx.storage.get(ACTIVITY_KEY)
150
- if (!activity || typeof activity !== "object" || Array.isArray(activity)) return
151
- for (const [key, value] of Object.entries(activity)) {
152
- const target = parseTargetKey(key)
153
- if (!target || typeof value !== "number" || !Number.isFinite(value)) continue
154
- if (!isTargetEnabled(this.config, target)) continue
155
- this.activity[targetKey(target)] = value
156
- const state = this.states.get(targetKey(target))
157
- if (state) state.lastUserMessageAt = value
206
+ if (activity && typeof activity === "object" && !Array.isArray(activity)) {
207
+ for (const [key, value] of Object.entries(activity)) {
208
+ const target = parseTargetKey(key)
209
+ if (!target || typeof value !== "number" || !Number.isFinite(value)) continue
210
+ if (!isTargetEnabled(this.config, target)) continue
211
+ this.activity[targetKey(target)] = value
212
+ const state = this.states.get(targetKey(target))
213
+ if (state) state.lastUserMessageAt = value
214
+ }
158
215
  }
159
216
  } catch (error) {
160
217
  this.logger.warn("读取目标活跃时间失败", error)
161
218
  }
219
+
220
+ await this.readPositions()
221
+ }
222
+
223
+ /** 从插件存储恢复每个目标已投递到的位置。 */
224
+ private async readPositions(): Promise<void> {
225
+ let stored: unknown
226
+ try {
227
+ stored = await this.ctx.storage.get(POSITIONS_KEY)
228
+ } catch (error) {
229
+ this.logger.warn("读取消息位置失败", error)
230
+ return
231
+ }
232
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) return
233
+ for (const [key, value] of Object.entries(stored)) {
234
+ const target = parseTargetKey(key)
235
+ if (!target || !isTargetEnabled(this.config, target)) continue
236
+ const position = parsePosition(value)
237
+ if (!position) continue
238
+ this.positions.set(key, position)
239
+ this.restoredPositions.set(key, position)
240
+ }
162
241
  }
163
242
 
164
243
  /** 绑定或活跃时间变化后写回插件存储,串行执行避免互相覆盖。 */
@@ -171,6 +250,7 @@ export class SessionManager {
171
250
  private async persist(): Promise<void> {
172
251
  await this.writeBindings()
173
252
  await this.writeActivity()
253
+ await this.writePositions()
174
254
  }
175
255
 
176
256
  private async writeBindings(): Promise<void> {
@@ -193,6 +273,15 @@ export class SessionManager {
193
273
  }
194
274
  }
195
275
 
276
+ private async writePositions(): Promise<void> {
277
+ try {
278
+ const data: Record<string, { id: string; time: number }> = Object.fromEntries(this.positions)
279
+ await this.ctx.storage.set(POSITIONS_KEY, data)
280
+ } catch (error) {
281
+ this.logger.error("保存消息位置失败", error)
282
+ }
283
+ }
284
+
196
285
  /** 等待所有待写入的绑定落盘。 */
197
286
  async flush(): Promise<void> {
198
287
  await this.saveMutex.runExclusive(() => this.persist())
@@ -226,6 +315,7 @@ export class SessionManager {
226
315
  state = {
227
316
  target,
228
317
  buffer: [],
318
+ pendingAttempts: 0,
229
319
  lastDispatchAt: 0,
230
320
  idleAt: 0,
231
321
  awaitingSend: false,
@@ -381,11 +471,37 @@ export class SessionManager {
381
471
  * `force` 仅用于上游已经明确发出结束事件的场景。
382
472
  */
383
473
  private async drain(state: ChatState, force = false): Promise<void> {
474
+ try {
475
+ await this.deliver(state, force)
476
+ } finally {
477
+ // 缓存状态变了,重新决定要不要继续兜底轮询。
478
+ this.syncWatchdog()
479
+ }
480
+ }
481
+
482
+ /** 把缓存里的消息投进上游会话。 */
483
+ private async deliver(state: ChatState, force = false): Promise<void> {
384
484
  // 上一批投递失败时,原样重试:内容与 id 都不能变。
385
485
  // 上游按 id 判定重复,同样的 id 带上不同内容会被判为冲突,那一批就永远送不进去。
386
486
  if (state.pending) {
387
- if (!(await this.dispatch(state, state.pending))) return
388
- state.pending = undefined
487
+ if (!(await this.dispatch(state, state.pending))) {
488
+ state.pendingAttempts += 1
489
+ if (state.pendingAttempts < PENDING_MAX_ATTEMPTS) {
490
+ this.logger.warn(
491
+ `${targetLabel(state.target)} 第 ${state.pendingAttempts} 次投递失败,仍会保留这批消息`,
492
+ )
493
+ return
494
+ }
495
+ // 重试到上限:上游可能永久拒绝这批内容,丢掉它,别把目标堵死。
496
+ this.logger.error(
497
+ `${targetLabel(state.target)} 连续 ${PENDING_MAX_ATTEMPTS} 次投递失败,丢弃这批消息`,
498
+ )
499
+ state.pending = undefined
500
+ state.pendingAttempts = 0
501
+ } else {
502
+ state.pending = undefined
503
+ state.pendingAttempts = 0
504
+ }
389
505
  }
390
506
  if (state.buffer.length === 0) return
391
507
  if (!force && state.sessionID && this.verifiedSessions.has(state.sessionID)) {
@@ -402,10 +518,47 @@ export class SessionManager {
402
518
 
403
519
  const turns = state.buffer
404
520
  state.buffer = []
405
- const batch = mergeTurns(turns)
521
+ // 历史在冻结 pending 之前拼好,重试时内容保持不变。
522
+ const batch = await this.prepareTurn(state, mergeTurns(turns))
406
523
  if (!(await this.dispatch(state, batch))) {
407
524
  // 冻结这一批:重试时用同一个 id、同一段内容。
408
525
  state.pending = batch
526
+ // 这次投递已经失败,算作第一次尝试。
527
+ state.pendingAttempts = 1
528
+ }
529
+ }
530
+
531
+ /**
532
+ * 在本次运行的第一轮消息前面拼上历史记录。
533
+ *
534
+ * 新建会话补最近 N 条;复用上次的会话时只补上次投递位置之后的增量,
535
+ * 这样重启期间错过的消息不会丢。历史已经实时收过的消息会被排除。
536
+ */
537
+ private async prepareTurn(state: ChatState, turn: Turn): Promise<Turn> {
538
+ const count = Math.max(0, Math.floor(this.config.history.count))
539
+ if (!this.history || count === 0 || state.historyDone) return turn
540
+
541
+ const key = targetKey(state.target)
542
+ const sessionID = await this.ensureSession(state.target)
543
+ if (!sessionID) return turn
544
+ const since = state.sessionCreated ? undefined : this.restoredPositions.get(key)
545
+ try {
546
+ const history = await this.history.fetch(state.target, {
547
+ count,
548
+ ...(since ? { since } : {}),
549
+ exclude: this.incoming.get(key),
550
+ })
551
+ // 补过才算补齐:失败时不留下标记,下一轮还会重试。
552
+ state.historyDone = true
553
+ if (!history.text) return turn
554
+ return {
555
+ ...turn,
556
+ text: `${history.text}\n${turn.text}`,
557
+ files: limitFiles([...turn.files, ...history.files]),
558
+ }
559
+ } catch (error) {
560
+ this.logger.warn(`${targetLabel(state.target)} 补齐历史失败`, error)
561
+ return turn
409
562
  }
410
563
  }
411
564
 
@@ -430,6 +583,12 @@ export class SessionManager {
430
583
  ...(turn.files.length > 0 ? { files: turn.files } : {}),
431
584
  })
432
585
  state.lastDispatchAt = Date.now()
586
+ if (turn.source) {
587
+ const key = targetKey(state.target)
588
+ this.positions.set(key, turn.source)
589
+ // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
590
+ this.scheduleSave()
591
+ }
433
592
  this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`)
434
593
  return true
435
594
  } catch (error) {
@@ -521,12 +680,65 @@ export class SessionManager {
521
680
  * 只在上游确认空闲且本轮确实结束后投递,不会打断仍在运行的长轮次。
522
681
  */
523
682
  async resumeBuffered(): Promise<void> {
524
- for (const state of this.sessions.values()) {
683
+ // 按目标遍历:还没绑定会话的目标同样可能有消息等着投递。
684
+ for (const state of this.states.values()) {
525
685
  if (state.buffer.length === 0 && !state.pending) continue
526
686
  await this.targetMutex(state.target).runExclusive(() => this.drain(state))
527
687
  }
528
688
  }
529
689
 
690
+ /** 是否还有消息等着投递。 */
691
+ private hasPendingWork(): boolean {
692
+ for (const state of this.states.values()) {
693
+ if (state.buffer.length > 0 || state.pending) return true
694
+ }
695
+ return false
696
+ }
697
+
698
+ /**
699
+ * 缓存里还有消息就保持兜底轮询,全部投出去后立刻停掉。
700
+ *
701
+ * 上游的结束事件可能丢失(断线、事件过期),没有这层兜底缓存的消息会一直压着。
702
+ */
703
+ private syncWatchdog(): void {
704
+ if (this.disposed) return
705
+ if (!this.hasPendingWork()) {
706
+ if (this.watchdog) {
707
+ clearTimeout(this.watchdog)
708
+ this.watchdog = undefined
709
+ }
710
+ return
711
+ }
712
+ if (this.watchdog) return
713
+ this.watchdog = setTimeout(() => {
714
+ this.watchdog = undefined
715
+ void this.runWatchdog()
716
+ }, RESUME_INTERVAL_MS)
717
+ const handle = this.watchdog as { unref?: () => void }
718
+ handle.unref?.()
719
+ }
720
+
721
+ /** 兜底轮询一轮:按上游会话状态把缓存的消息放出去。 */
722
+ private async runWatchdog(): Promise<void> {
723
+ if (this.disposed) return
724
+ try {
725
+ await this.resumeBuffered()
726
+ } catch (error) {
727
+ this.logger.warn("兜底轮询缓存消息失败", error)
728
+ } finally {
729
+ this.syncWatchdog()
730
+ }
731
+ }
732
+
733
+ /** 释放定时器等资源。 */
734
+ dispose(): void {
735
+ this.disposed = true
736
+ if (this.watchdog) {
737
+ clearTimeout(this.watchdog)
738
+ this.watchdog = undefined
739
+ }
740
+ }
741
+
530
742
  /** 会话状态变为 idle 后,把缓存的消息合并成新的一轮投递。 */
531
743
  async flushBuffered(sessionID: string): Promise<void> {
532
744
  const state = this.sessions.get(sessionID)
@@ -575,6 +787,7 @@ export class SessionManager {
575
787
 
576
788
  const created = await this.ctx.session.create({
577
789
  title: target.kind === "group" ? `QQ 群 ${target.id}` : `QQ 私聊 ${target.id}`,
790
+ location: this.location,
578
791
  ...(this.config.agent ? { agent: this.config.agent } : {}),
579
792
  ...(this.config.model ? { model: this.config.model } : {}),
580
793
  metadata: {
@@ -590,6 +803,7 @@ export class SessionManager {
590
803
  return undefined
591
804
  }
592
805
  this.verifiedSessions.add(created.id)
806
+ state.sessionCreated = true
593
807
  this.scheduleSave()
594
808
  this.logger.info(`${label} 新建会话 ${created.id}`)
595
809
  return created.id
@@ -642,7 +856,7 @@ export class SessionManager {
642
856
  try {
643
857
  for (let page = 0; page < 5; page += 1) {
644
858
  const result = await this.ctx.session.list({
645
- directory: this.ctx.location.directory,
859
+ directory: this.location.directory,
646
860
  limit: 100,
647
861
  order: "desc",
648
862
  ...(cursor ? { cursor } : {}),
@@ -4,7 +4,10 @@ export const SEND_MESSAGE_TOOL = "qq_send_message"
4
4
  const GUIDELINES = `
5
5
  GUIDELINES:
6
6
  你在 QQ 群聊或私聊里,你收到的消息不一定是发给你的,你需要根据上下文和语境来判断是否回复。私聊消息必须回复;群聊里只有被 @ 时才必须回复。
7
- 对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。<forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。user_name : message 是用户发给你的消息, 不同的user_name代表不同的用户,你需要根据这些消息来判断每个用户的意图和情感。
7
+ 对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。
8
+ <forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。
9
+ <history>...</history> 里面是本次会话开始之前的历史聊天记录,按时间顺序排列,用来了解之前聊过什么。
10
+ 每条消息都是 \`[26-11-07 14:33] 名字(QQ号): 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面的括号里是发送者的 QQ 号,用来区分同名的人。你需要根据这些消息来判断每个用户的意图和情感。
8
11
  重要!!!发送消息时,**必须**调用发送类工具;任何直接输出的文字都会被**完全丢弃**,不会作为消息内容发送!!!
9
12
  文本回复用 ${SEND_MESSAGE_TOOL};图片、语音、合并转发、戳一戳等用对应的 qq_* 工具,调用成功同样算作已回复。
10
13
  每轮至少调用一个发送类工具;不想回复时把 ${SEND_MESSAGE_TOOL} 的 reply 设成 false(content 可留空),相当于已读不回。群聊里不需要每一条都回复,像人一样选择性回复就行。
@@ -17,8 +17,8 @@ export interface AskGuardDeps {
17
17
  }
18
18
 
19
19
  /**
20
- * 在 QQ 会话里拦截内置 question 工具,要求模型改用 qq_send_message 询问用户。
21
- * 非 QQ 会话不受影响。
20
+ * 在 QQ 消息轮次执行期间拦截内置 question 工具,要求模型改用 qq_send_message 询问用户。
21
+ * 只绑定 QQ 目标、但没有 QQ 轮次在跑的会话(人工在 TUI 里驱动)不受影响。
22
22
  */
23
23
  export async function registerAskGuard(deps: AskGuardDeps): Promise<{ dispose(): Promise<void> }> {
24
24
  const { ctx, logger, manager } = deps
@@ -26,6 +26,7 @@ export async function registerAskGuard(deps: AskGuardDeps): Promise<{ dispose():
26
26
  if (event.tool !== QUESTION_TOOL) return
27
27
  const target = manager.targetForSession(event.sessionID)
28
28
  if (!target) return
29
+ if (!manager.hasActiveTurn(event.sessionID)) return
29
30
  logger.warn(`${targetLabel(target)} 会话里模型尝试调用 ${QUESTION_TOOL} 工具,已拒绝`)
30
31
  throw new Error(ASK_REFUSAL)
31
32
  })