@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.0

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,25 @@
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
- import { type ChatTarget, isTargetEnabled, parseTargetKey, targetKey, targetLabel } from "../chat"
5
- import type { QQBotConfig } from "../config"
5
+ import { isTargetAllowed } from "../access"
6
+ import { type ChatTarget, parseTargetKey, targetKey, targetLabel } from "../chat"
7
+ import type { ModelRef, QQBotConfig } from "../config"
8
+ import type { BotHome } from "../home"
6
9
  import type { Logger } from "../logger"
10
+ import type { HistoryPosition, HistoryProvider } from "../naplink/history"
11
+ import type { ChatOverrides } from "../overrides"
12
+ import type { Tracer } from "../trace"
7
13
  import { limitFiles, type PromptFile } from "../naplink/render"
14
+ import type { WakeReason } from "../overrides"
15
+ import type { Role } from "../tools/policy"
8
16
 
9
17
  /** 插件存储里保存会话与目标绑定的键。 */
10
18
  const BINDINGS_KEY = "bindings"
11
19
  /** 插件存储里保存目标最近活跃时间的键。 */
12
20
  const ACTIVITY_KEY = "activity"
21
+ /** 插件存储里保存每个目标已投递到的消息位置的键。 */
22
+ const POSITIONS_KEY = "positions"
13
23
  /** 单个目标最多缓存的消息条数。 */
14
24
  export const MAX_BUFFER_TURNS = 100
15
25
  /** 单个目标最多缓存的文本与附件字节数。 */
@@ -18,12 +28,34 @@ export const MAX_BUFFER_BYTES = 32 * 1024 * 1024
18
28
  const MAX_TRACKED_MESSAGES = 200
19
29
  /** 刚投递的一轮还没在上游体现出忙碌状态,先跳过对账避免重复投递。 */
20
30
  export const SUBMIT_GRACE_MS = 5_000
31
+ /** 失败批次最多重试几次;超过次数就丢弃,避免一个目标被永久堵死。 */
32
+ export const PENDING_MAX_ATTEMPTS = 3
33
+ /** 缓存里还有消息时的兜底轮询间隔:上游结束事件丢了也能把消息放出去。 */
34
+ export const RESUME_INTERVAL_MS = 30_000
35
+ /** 回合失败且模型一句话都没发出时,补到聊天里的固定文案。 */
36
+ export const FAILURE_NOTICE = "⚠️ 暂时无法处理这条消息,请稍后再试。"
37
+ /** 回合被中断时的固定文案。 */
38
+ export const INTERRUPTED_NOTICE = "⏹️ 已停止"
39
+ /** 同一目标两次失败提示的最小间隔,连续失败不会刷屏。 */
40
+ export const FAILURE_NOTICE_INTERVAL_MS = 5 * 60 * 1000
41
+
42
+ /** 插件自己往聊天里补话的通道,失败兜底用。 */
43
+ export type FailureNotifier = (target: ChatTarget, text: string) => Promise<void>
21
44
  function toMillis(value: unknown): number | undefined {
22
45
  if (value instanceof Date) return value.getTime()
23
46
  if (typeof value === "number") return value
24
47
  return undefined
25
48
  }
26
49
 
50
+ /** 解析存储里的消息位置,格式不对时忽略。 */
51
+ function parsePosition(value: unknown): HistoryPosition | undefined {
52
+ if (!value || typeof value !== "object") return undefined
53
+ const record = value as { id?: unknown; time?: unknown }
54
+ if (typeof record.id !== "string" || record.id.length === 0) return undefined
55
+ if (typeof record.time !== "number" || !Number.isFinite(record.time)) return undefined
56
+ return { id: record.id, time: record.time }
57
+ }
58
+
27
59
  /** 上游会话是否仍在执行;依据 `time.busy` 是否晚于 `time.idle`。 */
28
60
  function upstreamRunning(time: unknown): boolean {
29
61
  if (!time || typeof time !== "object") return false
@@ -40,10 +72,20 @@ export interface Turn {
40
72
  text: string
41
73
  /** 图片附件。 */
42
74
  files: PromptFile[]
43
- /** 本轮是否 @ 了机器人。 */
75
+ /** 本轮是否必须回复:私聊、被 @ 或命中唤醒条件时为 true。 */
44
76
  atMe: boolean
77
+ /** 触发必回的原因,缺省按被 @ 处理。 */
78
+ wake?: WakeReason
45
79
  /** 是否由主动说话心跳发起。 */
46
80
  proactive?: boolean
81
+ /** 本轮最后一条 QQ 消息的位置,用来记录已经投递到哪里。 */
82
+ source?: HistoryPosition
83
+ /** 发送者角色;决定这一轮能用哪些工具,缺省按普通成员处理。 */
84
+ role?: Role
85
+ /** 调用链追踪 id,用来把这一轮的各个节点串起来。 */
86
+ traceId?: string
87
+ /** 这条消息明确不是在跟机器人说话,不要插话。 */
88
+ suppress?: boolean
47
89
  }
48
90
 
49
91
  interface ChatState {
@@ -53,6 +95,8 @@ interface ChatState {
53
95
  buffer: Turn[]
54
96
  /** 已经尝试投递但失败的一批:内容与 id 冻结,重试时原样重发。 */
55
97
  pending?: Turn
98
+ /** 当前失败批次已经重试的次数;超过上限就丢弃这批。 */
99
+ pendingAttempts: number
56
100
  /** 最近一次投递的时间戳(毫秒)。 */
57
101
  lastDispatchAt: number
58
102
  /** 最近一次上游确认空闲的时间戳(毫秒)。 */
@@ -65,24 +109,69 @@ interface ChatState {
65
109
  reminders: number
66
110
  /** 最近一次真实用户消息的时间戳(毫秒)。 */
67
111
  lastUserMessageAt: number
112
+ /** 本次运行是否已经为该目标补过历史。 */
113
+ historyDone?: boolean
114
+ /** 会话是否是在本次运行中新建的。 */
115
+ sessionCreated?: boolean
68
116
  }
69
117
 
70
118
  type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
71
119
 
72
120
  export function mergeTurns(turns: readonly Turn[]): Turn {
121
+ // 同一条消息重复投递时只留一份。
122
+ const seen = new Set<string>()
123
+ const unique = turns.filter((turn) => {
124
+ if (!turn.source) return true
125
+ if (seen.has(turn.source.id)) return false
126
+ seen.add(turn.source.id)
127
+ return true
128
+ })
129
+ // 必回原因跟着真正要求回复的那条消息走。
130
+ const wake = unique.find((turn) => turn.atMe && turn.wake)?.wake
131
+ // 追踪 id 跟着这批消息里的第一条走。
132
+ const traceId = unique.find((turn) => turn.traceId)?.traceId
133
+ // 只要有一条要求必回,整批都要回;否则只要有消息不是在跟机器人说话,就不要插话。
134
+ const atMe = unique.some((turn) => turn.atMe)
135
+ const suppress = !atMe && unique.some((turn) => turn.suppress)
136
+ // 批次的位置取最后一条带位置的消息。
137
+ const source = unique.reduce<HistoryPosition | undefined>(
138
+ (latest, turn) => turn.source ?? latest,
139
+ undefined,
140
+ )
141
+ // 一批消息可能来自不同的人:按最低权限执行,避免普通成员的话借到管理员的工具。
142
+ const roles = unique.map((turn) => turn.role ?? "member")
143
+ const role: Role = roles.includes("member")
144
+ ? "member"
145
+ : roles.includes("admin")
146
+ ? "admin"
147
+ : "owner"
73
148
  return {
74
149
  // 合并后的批次沿用第一条消息的幂等键,重试时保持一致。
75
- ...(turns[0]?.id ? { id: turns[0].id } : {}),
76
- text: turns
150
+ ...(unique[0]?.id ? { id: unique[0].id } : {}),
151
+ text: unique
77
152
  .map((turn) => turn.text.trim())
78
153
  .filter((text) => text.length > 0)
79
154
  .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 } : {}),
155
+ files: limitFiles(unique.flatMap((turn) => turn.files)),
156
+ atMe,
157
+ ...(wake ? { wake } : {}),
158
+ role,
159
+ ...(unique.some((turn) => turn.proactive) ? { proactive: true } : {}),
160
+ ...(traceId ? { traceId } : {}),
161
+ ...(suppress ? { suppress: true } : {}),
162
+ ...(source ? { source } : {}),
83
163
  }
84
164
  }
85
165
 
166
+ /** 判断两个模型引用是不是同一个。 */
167
+ function sameModel(left: ModelRef | undefined, right: ModelRef | undefined): boolean {
168
+ if (left === right) return true
169
+ if (!left || !right) return false
170
+ return (
171
+ left.id === right.id && left.providerID === right.providerID && left.variant === right.variant
172
+ )
173
+ }
174
+
86
175
  function turnBytes(turn: Turn): number {
87
176
  return (
88
177
  turn.text.length * 2 +
@@ -107,13 +196,39 @@ export class SessionManager {
107
196
  private readonly saveMutex = new Mutex()
108
197
  private activity: Record<string, number> = {}
109
198
  private bindingsLoaded: Promise<void> | undefined
199
+ /** 每个目标已经投递到的位置。 */
200
+ private readonly positions = new Map<string, HistoryPosition>()
201
+ /** 启动时读到的位置快照,用于补齐重启期间错过的消息。 */
202
+ private readonly restoredPositions = new Map<string, HistoryPosition>()
203
+ /** 兜底轮询定时器:上游结束事件丢失时把缓存的消息投出去。 */
204
+ private watchdog: ReturnType<typeof setTimeout> | undefined
205
+ /** 每个目标上一次失败提示的时间戳。 */
206
+ private readonly noticeAt = new Map<string, number>()
207
+ /** 每个会话已经应用过的 agent / 模型覆盖,避免每条消息都切一次。 */
208
+ private readonly appliedOverrides = new Map<string, { agent?: string; model?: ModelRef }>()
209
+ private disposed = false
110
210
 
111
211
  constructor(
112
212
  private readonly ctx: Plugin.Context,
113
213
  private readonly config: QQBotConfig,
114
214
  private readonly logger: Logger,
215
+ /** 机器人固定服务的工作目录,所有 QQ 会话都建在这里。 */
216
+ private readonly home: BotHome,
217
+ private readonly history?: HistoryProvider,
218
+ /** 失败兜底通道;不传就只写日志。 */
219
+ private readonly notify?: FailureNotifier,
220
+ /** 按聊天覆盖 agent / 模型;不传就只用全局配置。 */
221
+ private readonly overrides?: ChatOverrides,
222
+ /** 调用链追踪器;不传就不记追踪。 */
223
+ private readonly tracer?: Tracer,
115
224
  ) {}
116
225
 
226
+ /** 会话统一落在机器人工作目录,避免接管后上下文散落到别的项目。 */
227
+ private get location(): Location.PublicRef {
228
+ // 目录最初就取自 location.directory,这里只是把存储里的字符串还原成品牌类型。
229
+ return { directory: this.home.directory as Location.PublicRef["directory"] }
230
+ }
231
+
117
232
  /** 载入上次运行时保存的目标与会话绑定。 */
118
233
  async load(): Promise<void> {
119
234
  await this.ensureBindings()
@@ -138,7 +253,7 @@ export class SessionManager {
138
253
  const target = parseTargetKey(key)
139
254
  if (!target || typeof value !== "string" || value.length === 0) continue
140
255
  // 配置里已经移除的目标不再恢复,避免旧绑定继续获得工具权限。
141
- if (!isTargetEnabled(this.config, target)) continue
256
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
142
257
  if (!this.bindSession(this.state(target), value)) continue
143
258
  restored += 1
144
259
  }
@@ -147,18 +262,41 @@ export class SessionManager {
147
262
 
148
263
  try {
149
264
  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
265
+ if (activity && typeof activity === "object" && !Array.isArray(activity)) {
266
+ for (const [key, value] of Object.entries(activity)) {
267
+ const target = parseTargetKey(key)
268
+ if (!target || typeof value !== "number" || !Number.isFinite(value)) continue
269
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
270
+ this.activity[targetKey(target)] = value
271
+ const state = this.states.get(targetKey(target))
272
+ if (state) state.lastUserMessageAt = value
273
+ }
158
274
  }
159
275
  } catch (error) {
160
276
  this.logger.warn("读取目标活跃时间失败", error)
161
277
  }
278
+
279
+ await this.readPositions()
280
+ }
281
+
282
+ /** 从插件存储恢复每个目标已投递到的位置。 */
283
+ private async readPositions(): Promise<void> {
284
+ let stored: unknown
285
+ try {
286
+ stored = await this.ctx.storage.get(POSITIONS_KEY)
287
+ } catch (error) {
288
+ this.logger.warn("读取消息位置失败", error)
289
+ return
290
+ }
291
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) return
292
+ for (const [key, value] of Object.entries(stored)) {
293
+ const target = parseTargetKey(key)
294
+ if (!target || !isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
295
+ const position = parsePosition(value)
296
+ if (!position) continue
297
+ this.positions.set(key, position)
298
+ this.restoredPositions.set(key, position)
299
+ }
162
300
  }
163
301
 
164
302
  /** 绑定或活跃时间变化后写回插件存储,串行执行避免互相覆盖。 */
@@ -171,6 +309,7 @@ export class SessionManager {
171
309
  private async persist(): Promise<void> {
172
310
  await this.writeBindings()
173
311
  await this.writeActivity()
312
+ await this.writePositions()
174
313
  }
175
314
 
176
315
  private async writeBindings(): Promise<void> {
@@ -193,6 +332,15 @@ export class SessionManager {
193
332
  }
194
333
  }
195
334
 
335
+ private async writePositions(): Promise<void> {
336
+ try {
337
+ const data: Record<string, { id: string; time: number }> = Object.fromEntries(this.positions)
338
+ await this.ctx.storage.set(POSITIONS_KEY, data)
339
+ } catch (error) {
340
+ this.logger.error("保存消息位置失败", error)
341
+ }
342
+ }
343
+
196
344
  /** 等待所有待写入的绑定落盘。 */
197
345
  async flush(): Promise<void> {
198
346
  await this.saveMutex.runExclusive(() => this.persist())
@@ -226,6 +374,7 @@ export class SessionManager {
226
374
  state = {
227
375
  target,
228
376
  buffer: [],
377
+ pendingAttempts: 0,
229
378
  lastDispatchAt: 0,
230
379
  idleAt: 0,
231
380
  awaitingSend: false,
@@ -247,6 +396,79 @@ export class SessionManager {
247
396
  return this.sessions.get(sessionID)?.current
248
397
  }
249
398
 
399
+ /** 当前轮次发送者的角色;没有轮次时按普通成员处理。 */
400
+ currentRole(sessionID: string): Role {
401
+ return this.sessions.get(sessionID)?.current?.role ?? "member"
402
+ }
403
+
404
+ /**
405
+ * 正在执行的 QQ 轮次:目标、轮次本身与发送者角色。
406
+ *
407
+ * 没有轮次(TUI 里人工驱动)或会话没有绑定 QQ 目标时返回 undefined。
408
+ */
409
+ activeTurn(sessionID: string): { target: ChatTarget; turn: Turn; role: Role } | undefined {
410
+ const state = this.sessions.get(sessionID)
411
+ if (!state?.current) return undefined
412
+ return { target: state.target, turn: state.current, role: state.current.role ?? "member" }
413
+ }
414
+
415
+ /**
416
+ * 重置一个聊天:先打断正在执行的回合,再解绑并删除会话。
417
+ *
418
+ * 下一条消息会新建会话并正常补历史;返回是否真的打断过。
419
+ */
420
+ async resetTarget(target: ChatTarget): Promise<{ sessionID?: string; interrupted: boolean }> {
421
+ const state = this.state(target)
422
+ const sessionID = state.sessionID
423
+ let interrupted = false
424
+ if (sessionID && (await this.sessionRunning(sessionID))) {
425
+ try {
426
+ await this.ctx.session.interrupt({ sessionID })
427
+ interrupted = true
428
+ } catch (error) {
429
+ this.logger.warn(`${targetLabel(target)} 打断会话 ${sessionID} 失败`, error)
430
+ }
431
+ }
432
+ if (sessionID) {
433
+ this.sessions.delete(sessionID)
434
+ this.verifiedSessions.delete(sessionID)
435
+ await this.ctx.session.remove({ sessionID }).catch((error: unknown) => {
436
+ this.logger.warn(`${targetLabel(target)} 删除会话 ${sessionID} 失败`, error)
437
+ })
438
+ state.sessionID = undefined
439
+ }
440
+ state.buffer = []
441
+ state.pending = undefined
442
+ state.pendingAttempts = 0
443
+ state.current = undefined
444
+ state.awaitingSend = false
445
+ state.reminders = 0
446
+ state.historyDone = false
447
+ state.sessionCreated = false
448
+ state.idleAt = Date.now()
449
+ this.scheduleSave()
450
+ return { sessionID, interrupted }
451
+ }
452
+
453
+ /** 各聊天当前状态的快照,供管理命令展示。 */
454
+ snapshot(): Array<{
455
+ target: ChatTarget
456
+ sessionID?: string
457
+ busy: boolean
458
+ buffered: number
459
+ pending: boolean
460
+ }> {
461
+ return [...this.states.values()]
462
+ .map((state) => ({
463
+ target: state.target,
464
+ ...(state.sessionID ? { sessionID: state.sessionID } : {}),
465
+ busy: state.current !== undefined,
466
+ buffered: state.buffer.length,
467
+ pending: state.pending !== undefined,
468
+ }))
469
+ .sort((left, right) => targetKey(left.target).localeCompare(targetKey(right.target)))
470
+ }
471
+
250
472
  /** 当前是否有 QQ 消息轮次正在执行,用于阻止手动 prompt 调用 QQ 工具。 */
251
473
  hasActiveTurn(sessionID: string): boolean {
252
474
  return this.sessions.get(sessionID)?.current !== undefined
@@ -381,11 +603,39 @@ export class SessionManager {
381
603
  * `force` 仅用于上游已经明确发出结束事件的场景。
382
604
  */
383
605
  private async drain(state: ChatState, force = false): Promise<void> {
606
+ try {
607
+ await this.deliver(state, force)
608
+ } finally {
609
+ // 缓存状态变了,重新决定要不要继续兜底轮询。
610
+ this.syncWatchdog()
611
+ }
612
+ }
613
+
614
+ /** 把缓存里的消息投进上游会话。 */
615
+ private async deliver(state: ChatState, force = false): Promise<void> {
384
616
  // 上一批投递失败时,原样重试:内容与 id 都不能变。
385
617
  // 上游按 id 判定重复,同样的 id 带上不同内容会被判为冲突,那一批就永远送不进去。
386
618
  if (state.pending) {
387
- if (!(await this.dispatch(state, state.pending))) return
388
- state.pending = undefined
619
+ if (!(await this.dispatch(state, state.pending))) {
620
+ state.pendingAttempts += 1
621
+ if (state.pendingAttempts < PENDING_MAX_ATTEMPTS) {
622
+ this.logger.warn(
623
+ `${targetLabel(state.target)} 第 ${state.pendingAttempts} 次投递失败,仍会保留这批消息`,
624
+ )
625
+ return
626
+ }
627
+ // 重试到上限:上游可能永久拒绝这批内容,丢掉它,别把目标堵死。
628
+ this.logger.error(
629
+ `${targetLabel(state.target)} 连续 ${PENDING_MAX_ATTEMPTS} 次投递失败,丢弃这批消息`,
630
+ )
631
+ state.pending = undefined
632
+ state.pendingAttempts = 0
633
+ // 这批消息再也进不了会话,群里得有个交代。
634
+ await this.notifyFailure(state, FAILURE_NOTICE)
635
+ } else {
636
+ state.pending = undefined
637
+ state.pendingAttempts = 0
638
+ }
389
639
  }
390
640
  if (state.buffer.length === 0) return
391
641
  if (!force && state.sessionID && this.verifiedSessions.has(state.sessionID)) {
@@ -402,10 +652,47 @@ export class SessionManager {
402
652
 
403
653
  const turns = state.buffer
404
654
  state.buffer = []
405
- const batch = mergeTurns(turns)
655
+ // 历史在冻结 pending 之前拼好,重试时内容保持不变。
656
+ const batch = await this.prepareTurn(state, mergeTurns(turns))
406
657
  if (!(await this.dispatch(state, batch))) {
407
658
  // 冻结这一批:重试时用同一个 id、同一段内容。
408
659
  state.pending = batch
660
+ // 这次投递已经失败,算作第一次尝试。
661
+ state.pendingAttempts = 1
662
+ }
663
+ }
664
+
665
+ /**
666
+ * 在本次运行的第一轮消息前面拼上历史记录。
667
+ *
668
+ * 新建会话补最近 N 条;复用上次的会话时只补上次投递位置之后的增量,
669
+ * 这样重启期间错过的消息不会丢。历史已经实时收过的消息会被排除。
670
+ */
671
+ private async prepareTurn(state: ChatState, turn: Turn): Promise<Turn> {
672
+ const count = Math.max(0, Math.floor(this.config.history.count))
673
+ if (!this.history || count === 0 || state.historyDone) return turn
674
+
675
+ const key = targetKey(state.target)
676
+ const sessionID = await this.ensureSession(state.target)
677
+ if (!sessionID) return turn
678
+ const since = state.sessionCreated ? undefined : this.restoredPositions.get(key)
679
+ try {
680
+ const history = await this.history.fetch(state.target, {
681
+ count,
682
+ ...(since ? { since } : {}),
683
+ exclude: this.incoming.get(key),
684
+ })
685
+ // 补过才算补齐:失败时不留下标记,下一轮还会重试。
686
+ state.historyDone = true
687
+ if (!history.text) return turn
688
+ return {
689
+ ...turn,
690
+ text: `${history.text}\n${turn.text}`,
691
+ files: limitFiles([...turn.files, ...history.files]),
692
+ }
693
+ } catch (error) {
694
+ this.logger.warn(`${targetLabel(state.target)} 补齐历史失败`, error)
695
+ return turn
409
696
  }
410
697
  }
411
698
 
@@ -423,6 +710,15 @@ export class SessionManager {
423
710
  state.awaitingSend = false
424
711
  return false
425
712
  }
713
+ // 模型起跑:从这里开始计时,看这一轮花了多久。
714
+ if (turn.traceId) {
715
+ await this.tracer?.record(
716
+ "agent_start",
717
+ turn.traceId,
718
+ { session_id: sessionID, chars: turn.text.length },
719
+ targetKey(state.target),
720
+ )
721
+ }
426
722
  await this.ctx.session.prompt({
427
723
  sessionID,
428
724
  ...(turn.id ? { id: turn.id } : {}),
@@ -430,7 +726,15 @@ export class SessionManager {
430
726
  ...(turn.files.length > 0 ? { files: turn.files } : {}),
431
727
  })
432
728
  state.lastDispatchAt = Date.now()
433
- this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`)
729
+ if (turn.source) {
730
+ const key = targetKey(state.target)
731
+ this.positions.set(key, turn.source)
732
+ // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
733
+ this.scheduleSave()
734
+ }
735
+ this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`, {
736
+ ...(turn.traceId ? { trace_id: turn.traceId } : {}),
737
+ })
434
738
  return true
435
739
  } catch (error) {
436
740
  state.current = undefined
@@ -471,6 +775,8 @@ export class SessionManager {
471
775
  return
472
776
  }
473
777
 
778
+ // 提醒沿用它正在提醒的那一轮的角色,别把 owner / 管理员降成普通成员。
779
+ const reminderRole = state.current?.role
474
780
  state.current = undefined
475
781
 
476
782
  if (
@@ -485,7 +791,12 @@ export class SessionManager {
485
791
  state.reminders += 1
486
792
  state.idleAt = 0
487
793
  state.lastDispatchAt = Date.now()
488
- state.current = { text: "[提醒]", files: [], atMe: false }
794
+ state.current = {
795
+ text: "[提醒]",
796
+ files: [],
797
+ atMe: false,
798
+ ...(reminderRole ? { role: reminderRole } : {}),
799
+ }
489
800
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
490
801
  try {
491
802
  await this.ctx.session.synthetic({
@@ -499,8 +810,33 @@ export class SessionManager {
499
810
  })
500
811
  }
501
812
 
502
- /** 模型执行失败或被中断:结束事件之后直接放行缓存。 */
503
- async handleExecutionEnd(sessionID: string, reason: string): Promise<void> {
813
+ /**
814
+ * 往聊天里补一条固定提示。
815
+ *
816
+ * 同一目标有冷却,连续失败只提示一次;发送失败也只写日志,不影响接下来的缓存投递。
817
+ */
818
+ private async notifyFailure(state: ChatState, text: string): Promise<void> {
819
+ if (!this.notify) return
820
+ const key = targetKey(state.target)
821
+ const now = Date.now()
822
+ const last = this.noticeAt.get(key)
823
+ if (last !== undefined && now - last < FAILURE_NOTICE_INTERVAL_MS) return
824
+ this.noticeAt.set(key, now)
825
+ try {
826
+ await this.notify(state.target, text)
827
+ this.logger.debug(`${targetLabel(state.target)} 已补发失败提示`)
828
+ } catch (error) {
829
+ this.logger.warn(`${targetLabel(state.target)} 补发失败提示失败`, error)
830
+ }
831
+ }
832
+
833
+ /**
834
+ * 回合失败或被中断:结束事件之后直接放行缓存。
835
+ *
836
+ * 模型一句话都没发出时往聊天里补一条固定提示,否则群里表现为「不回话」。
837
+ * 上游异常原文只进日志,绝不发到 QQ。
838
+ */
839
+ async handleExecutionEnd(sessionID: string, reason: string, detail?: string): Promise<void> {
504
840
  const state = this.sessions.get(sessionID)
505
841
  if (!state) return
506
842
  await this.targetMutex(state.target).runExclusive(async () => {
@@ -508,7 +844,13 @@ export class SessionManager {
508
844
  this.logger.debug(`${targetLabel(state.target)} 忽略上一轮迟到的结束事件(${reason})`)
509
845
  return
510
846
  }
511
- this.logger.warn(`${targetLabel(state.target)} 会话执行结束(${reason})`)
847
+ const label = targetLabel(state.target)
848
+ const interrupted = reason === "session.execution.interrupted"
849
+ this.logger.warn(`${label} 会话执行结束(${reason})${detail ? `:${detail}` : ""}`)
850
+ // 模型已经发过东西就不用再补提示;主动搭话失败也不往群里道歉。
851
+ if (state.awaitingSend && !state.current?.proactive) {
852
+ await this.notifyFailure(state, interrupted ? INTERRUPTED_NOTICE : FAILURE_NOTICE)
853
+ }
512
854
  state.current = undefined
513
855
  state.awaitingSend = false
514
856
  state.idleAt = Date.now()
@@ -521,12 +863,65 @@ export class SessionManager {
521
863
  * 只在上游确认空闲且本轮确实结束后投递,不会打断仍在运行的长轮次。
522
864
  */
523
865
  async resumeBuffered(): Promise<void> {
524
- for (const state of this.sessions.values()) {
866
+ // 按目标遍历:还没绑定会话的目标同样可能有消息等着投递。
867
+ for (const state of this.states.values()) {
525
868
  if (state.buffer.length === 0 && !state.pending) continue
526
869
  await this.targetMutex(state.target).runExclusive(() => this.drain(state))
527
870
  }
528
871
  }
529
872
 
873
+ /** 是否还有消息等着投递。 */
874
+ private hasPendingWork(): boolean {
875
+ for (const state of this.states.values()) {
876
+ if (state.buffer.length > 0 || state.pending) return true
877
+ }
878
+ return false
879
+ }
880
+
881
+ /**
882
+ * 缓存里还有消息就保持兜底轮询,全部投出去后立刻停掉。
883
+ *
884
+ * 上游的结束事件可能丢失(断线、事件过期),没有这层兜底缓存的消息会一直压着。
885
+ */
886
+ private syncWatchdog(): void {
887
+ if (this.disposed) return
888
+ if (!this.hasPendingWork()) {
889
+ if (this.watchdog) {
890
+ clearTimeout(this.watchdog)
891
+ this.watchdog = undefined
892
+ }
893
+ return
894
+ }
895
+ if (this.watchdog) return
896
+ this.watchdog = setTimeout(() => {
897
+ this.watchdog = undefined
898
+ void this.runWatchdog()
899
+ }, RESUME_INTERVAL_MS)
900
+ const handle = this.watchdog as { unref?: () => void }
901
+ handle.unref?.()
902
+ }
903
+
904
+ /** 兜底轮询一轮:按上游会话状态把缓存的消息放出去。 */
905
+ private async runWatchdog(): Promise<void> {
906
+ if (this.disposed) return
907
+ try {
908
+ await this.resumeBuffered()
909
+ } catch (error) {
910
+ this.logger.warn("兜底轮询缓存消息失败", error)
911
+ } finally {
912
+ this.syncWatchdog()
913
+ }
914
+ }
915
+
916
+ /** 释放定时器等资源。 */
917
+ dispose(): void {
918
+ this.disposed = true
919
+ if (this.watchdog) {
920
+ clearTimeout(this.watchdog)
921
+ this.watchdog = undefined
922
+ }
923
+ }
924
+
530
925
  /** 会话状态变为 idle 后,把缓存的消息合并成新的一轮投递。 */
531
926
  async flushBuffered(sessionID: string): Promise<void> {
532
927
  const state = this.sessions.get(sessionID)
@@ -557,8 +952,15 @@ export class SessionManager {
557
952
  await this.ensureBindings()
558
953
  const state = this.state(target)
559
954
  const label = targetLabel(target)
955
+ // 覆盖优先于全局配置;没写覆盖就用全局的。
956
+ const override = await this.overrides?.for(target)
957
+ const agent = override?.agent ?? this.config.agent
958
+ const model = override?.model ?? this.config.model
560
959
  if (state.sessionID) {
561
- if (await this.sessionExists(state.sessionID)) return state.sessionID
960
+ if (await this.sessionExists(state.sessionID)) {
961
+ await this.applyOverride(state.sessionID, label, agent, model)
962
+ return state.sessionID
963
+ }
562
964
  this.unbind(state)
563
965
  }
564
966
 
@@ -569,14 +971,16 @@ export class SessionManager {
569
971
  this.verifiedSessions.add(reused)
570
972
  this.scheduleSave()
571
973
  this.logger.info(`${label} 复用已有会话 ${reused}`)
974
+ await this.applyOverride(reused, label, agent, model)
572
975
  return reused
573
976
  }
574
977
  }
575
978
 
576
979
  const created = await this.ctx.session.create({
577
980
  title: target.kind === "group" ? `QQ 群 ${target.id}` : `QQ 私聊 ${target.id}`,
578
- ...(this.config.agent ? { agent: this.config.agent } : {}),
579
- ...(this.config.model ? { model: this.config.model } : {}),
981
+ location: this.location,
982
+ ...(agent ? { agent } : {}),
983
+ ...(model ? { model } : {}),
580
984
  metadata: {
581
985
  qqTargetKind: target.kind,
582
986
  qqTargetId: target.id,
@@ -590,11 +994,46 @@ export class SessionManager {
590
994
  return undefined
591
995
  }
592
996
  this.verifiedSessions.add(created.id)
997
+ state.sessionCreated = true
998
+ // 新建时已经带上覆盖值,记下来就不必再切一次。
999
+ this.appliedOverrides.set(created.id, { agent, model })
593
1000
  this.scheduleSave()
594
1001
  this.logger.info(`${label} 新建会话 ${created.id}`)
595
1002
  return created.id
596
1003
  }
597
1004
 
1005
+ /**
1006
+ * 把 agent / 模型覆盖应用到已有会话。
1007
+ *
1008
+ * 只在覆盖真的变了的时候切换,避免每条消息都动一次会话。
1009
+ */
1010
+ private async applyOverride(
1011
+ sessionID: string,
1012
+ label: string,
1013
+ agent: string | undefined,
1014
+ model: ModelRef | undefined,
1015
+ ): Promise<void> {
1016
+ const applied = this.appliedOverrides.get(sessionID)
1017
+ if (applied?.agent === agent && sameModel(applied?.model, model)) return
1018
+ if (agent !== undefined && applied?.agent !== agent) {
1019
+ try {
1020
+ await this.ctx.session.switchAgent({ sessionID, agent })
1021
+ this.logger.info(`${label} 会话 ${sessionID} 切换到 agent ${agent}`)
1022
+ } catch (error) {
1023
+ this.logger.warn(`${label} 切换 agent ${agent} 失败`, error)
1024
+ }
1025
+ }
1026
+ if (model !== undefined && !sameModel(applied?.model, model)) {
1027
+ try {
1028
+ await this.ctx.session.switchModel({ sessionID, model })
1029
+ this.logger.info(`${label} 会话 ${sessionID} 切换到模型 ${model.providerID}/${model.id}`)
1030
+ } catch (error) {
1031
+ this.logger.warn(`${label} 切换模型失败`, error)
1032
+ }
1033
+ }
1034
+ this.appliedOverrides.set(sessionID, { agent, model })
1035
+ }
1036
+
598
1037
  /** 确认恢复的会话仍然存在,避免陈旧绑定让每条消息都失败。 */
599
1038
  private async sessionExists(sessionID: string): Promise<boolean> {
600
1039
  if (this.verifiedSessions.has(sessionID)) return true
@@ -612,6 +1051,7 @@ export class SessionManager {
612
1051
  if (!state.sessionID) return
613
1052
  this.sessions.delete(state.sessionID)
614
1053
  this.verifiedSessions.delete(state.sessionID)
1054
+ this.appliedOverrides.delete(state.sessionID)
615
1055
  state.sessionID = undefined
616
1056
  this.scheduleSave()
617
1057
  }
@@ -642,7 +1082,7 @@ export class SessionManager {
642
1082
  try {
643
1083
  for (let page = 0; page < 5; page += 1) {
644
1084
  const result = await this.ctx.session.list({
645
- directory: this.ctx.location.directory,
1085
+ directory: this.location.directory,
646
1086
  limit: 100,
647
1087
  order: "desc",
648
1088
  ...(cursor ? { cursor } : {}),
@@ -671,10 +1111,19 @@ export class SessionManager {
671
1111
  const state = this.state(target)
672
1112
  await this.targetMutex(target).runExclusive(async () => {
673
1113
  if (state.buffer.length > 0 || state.current) return
1114
+ const traceId = this.tracer?.startTrace()
674
1115
  // 先占位,避免用户消息或下一次心跳同时投递。
675
1116
  state.idleAt = 0
676
1117
  state.lastDispatchAt = Date.now()
677
- state.current = { text, files: [], atMe: true, proactive: true }
1118
+ state.current = {
1119
+ text,
1120
+ files: [],
1121
+ atMe: true,
1122
+ proactive: true,
1123
+ // 主动说话由配置放行的聊天自动触发,按 owner 的角色执行,不降级成普通成员。
1124
+ role: "owner",
1125
+ ...(traceId ? { traceId } : {}),
1126
+ }
678
1127
  state.awaitingSend = true
679
1128
  state.reminders = 0
680
1129
  try {
@@ -692,6 +1141,14 @@ export class SessionManager {
692
1141
  state.lastUserMessageAt = Date.now()
693
1142
  this.activity[targetKey(target)] = state.lastUserMessageAt
694
1143
  this.scheduleSave()
1144
+ if (traceId) {
1145
+ await this.tracer?.record(
1146
+ "agent_start",
1147
+ traceId,
1148
+ { session_id: sessionID, proactive: true },
1149
+ targetKey(target),
1150
+ )
1151
+ }
695
1152
  await this.ctx.session.synthetic({ sessionID, text })
696
1153
  } catch (error) {
697
1154
  state.awaitingSend = false