@cmach_socket/opencode-qq-bot 0.5.1 → 0.6.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.
@@ -2,12 +2,17 @@ import type { Plugin } from "@opencode/plugin"
2
2
  import type { Location } from "@opencode/schema"
3
3
  import { SessionMessage } from "@opencode/schema"
4
4
  import { Mutex } from "async-mutex"
5
- import { type ChatTarget, isTargetEnabled, parseTargetKey, targetKey, targetLabel } from "../chat"
6
- 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"
7
8
  import type { BotHome } from "../home"
8
9
  import type { Logger } from "../logger"
9
10
  import type { HistoryPosition, HistoryProvider } from "../naplink/history"
11
+ import type { ChatOverrides } from "../overrides"
12
+ import type { Tracer } from "../trace"
10
13
  import { limitFiles, type PromptFile } from "../naplink/render"
14
+ import type { WakeReason } from "../overrides"
15
+ import type { Role } from "../tools/policy"
11
16
 
12
17
  /** 插件存储里保存会话与目标绑定的键。 */
13
18
  const BINDINGS_KEY = "bindings"
@@ -27,6 +32,19 @@ export const SUBMIT_GRACE_MS = 5_000
27
32
  export const PENDING_MAX_ATTEMPTS = 3
28
33
  /** 缓存里还有消息时的兜底轮询间隔:上游结束事件丢了也能把消息放出去。 */
29
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
+ export const SESSION_RETIRE_COOLDOWN_MS = 10 * 60 * 1000
43
+ /** 交接时等在途投递落地的最长时间(毫秒)。 */
44
+ const HANDOVER_WAIT_MS = 3_000
45
+
46
+ /** 插件自己往聊天里补话的通道,失败兜底用。 */
47
+ export type FailureNotifier = (target: ChatTarget, text: string) => Promise<void>
30
48
  function toMillis(value: unknown): number | undefined {
31
49
  if (value instanceof Date) return value.getTime()
32
50
  if (typeof value === "number") return value
@@ -58,12 +76,20 @@ export interface Turn {
58
76
  text: string
59
77
  /** 图片附件。 */
60
78
  files: PromptFile[]
61
- /** 本轮是否 @ 了机器人。 */
79
+ /** 本轮是否必须回复:私聊、被 @ 或命中唤醒条件时为 true。 */
62
80
  atMe: boolean
81
+ /** 触发必回的原因,缺省按被 @ 处理。 */
82
+ wake?: WakeReason
63
83
  /** 是否由主动说话心跳发起。 */
64
84
  proactive?: boolean
65
85
  /** 本轮最后一条 QQ 消息的位置,用来记录已经投递到哪里。 */
66
86
  source?: HistoryPosition
87
+ /** 发送者角色;决定这一轮能用哪些工具,缺省按普通成员处理。 */
88
+ role?: Role
89
+ /** 调用链追踪 id,用来把这一轮的各个节点串起来。 */
90
+ traceId?: string
91
+ /** 这条消息明确不是在跟机器人说话,不要插话。 */
92
+ suppress?: boolean
67
93
  }
68
94
 
69
95
  interface ChatState {
@@ -91,10 +117,46 @@ interface ChatState {
91
117
  historyDone?: boolean
92
118
  /** 会话是否是在本次运行中新建的。 */
93
119
  sessionCreated?: boolean
120
+ /** 最近一次自动退役会话的时间戳(毫秒)。 */
121
+ lastRetireAt: number
122
+ /** 最近一次清空当前轮次的原因与时间,仅供排查。 */
123
+ lastClear?: { reason: string; at: number; role?: Role; traceId?: string }
124
+ }
125
+
126
+ /** 实例交接时移交的会话状态。 */
127
+ export interface HandoverState {
128
+ /** 这个聊天对应的目标。 */
129
+ target: ChatTarget
130
+ /** 绑定的上游会话。 */
131
+ sessionID?: string
132
+ /** 正在执行的一轮;为空表示上游已经空闲。 */
133
+ current?: Turn
134
+ /** 当前轮次模型是否还没调用发送工具。 */
135
+ awaitingSend: boolean
136
+ /** 连续提醒次数,防止死循环。 */
137
+ reminders: number
138
+ /** 最近一次投递的时间戳(毫秒)。 */
139
+ lastDispatchAt: number
140
+ /** 最近一次上游确认空闲的时间戳(毫秒)。 */
141
+ idleAt: number
142
+ /** 上游还在跑时排队的消息。 */
143
+ buffer: Turn[]
144
+ /** 已经尝试投递但失败的一批。 */
145
+ pending?: Turn
146
+ /** 当前失败批次已经重试的次数。 */
147
+ pendingAttempts: number
94
148
  }
95
149
 
96
150
  type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
97
151
 
152
+ /** 角色权限高低:数字越小权限越低。 */
153
+ const ROLE_RANK: Record<Role, number> = {
154
+ proactive: 0,
155
+ member: 1,
156
+ admin: 2,
157
+ owner: 3,
158
+ }
159
+
98
160
  export function mergeTurns(turns: readonly Turn[]): Turn {
99
161
  // 同一条消息重复投递时只留一份。
100
162
  const seen = new Set<string>()
@@ -104,11 +166,25 @@ export function mergeTurns(turns: readonly Turn[]): Turn {
104
166
  seen.add(turn.source.id)
105
167
  return true
106
168
  })
169
+ // 必回原因跟着真正要求回复的那条消息走。
170
+ const wake = unique.find((turn) => turn.atMe && turn.wake)?.wake
171
+ // 追踪 id 跟着这批消息里的第一条走。
172
+ const traceId = unique.find((turn) => turn.traceId)?.traceId
173
+ // 只要有一条要求必回,整批都要回;否则只要有消息不是在跟机器人说话,就不要插话。
174
+ const atMe = unique.some((turn) => turn.atMe)
175
+ const suppress = !atMe && unique.some((turn) => turn.suppress)
107
176
  // 批次的位置取最后一条带位置的消息。
108
177
  const source = unique.reduce<HistoryPosition | undefined>(
109
178
  (latest, turn) => turn.source ?? latest,
110
179
  undefined,
111
180
  )
181
+ // 一批消息可能来自不同的人:按最低权限执行,避免普通成员的话借到管理员的工具。
182
+ // 主动说话没有人参与,它带进来的上下文同样不可信,权限比普通成员还低。
183
+ const roles = unique.map((turn) => turn.role ?? "member")
184
+ const role = roles.reduce<Role>(
185
+ (lowest, current) => (ROLE_RANK[current] < ROLE_RANK[lowest] ? current : lowest),
186
+ "owner",
187
+ )
112
188
  return {
113
189
  // 合并后的批次沿用第一条消息的幂等键,重试时保持一致。
114
190
  ...(unique[0]?.id ? { id: unique[0].id } : {}),
@@ -117,12 +193,25 @@ export function mergeTurns(turns: readonly Turn[]): Turn {
117
193
  .filter((text) => text.length > 0)
118
194
  .join("\n"),
119
195
  files: limitFiles(unique.flatMap((turn) => turn.files)),
120
- atMe: unique.some((turn) => turn.atMe),
196
+ atMe,
197
+ ...(wake ? { wake } : {}),
198
+ role,
121
199
  ...(unique.some((turn) => turn.proactive) ? { proactive: true } : {}),
200
+ ...(traceId ? { traceId } : {}),
201
+ ...(suppress ? { suppress: true } : {}),
122
202
  ...(source ? { source } : {}),
123
203
  }
124
204
  }
125
205
 
206
+ /** 判断两个模型引用是不是同一个。 */
207
+ function sameModel(left: ModelRef | undefined, right: ModelRef | undefined): boolean {
208
+ if (left === right) return true
209
+ if (!left || !right) return false
210
+ return (
211
+ left.id === right.id && left.providerID === right.providerID && left.variant === right.variant
212
+ )
213
+ }
214
+
126
215
  function turnBytes(turn: Turn): number {
127
216
  return (
128
217
  turn.text.length * 2 +
@@ -153,6 +242,10 @@ export class SessionManager {
153
242
  private readonly restoredPositions = new Map<string, HistoryPosition>()
154
243
  /** 兜底轮询定时器:上游结束事件丢失时把缓存的消息投出去。 */
155
244
  private watchdog: ReturnType<typeof setTimeout> | undefined
245
+ /** 每个目标上一次失败提示的时间戳。 */
246
+ private readonly noticeAt = new Map<string, number>()
247
+ /** 每个会话已经应用过的 agent / 模型覆盖,避免每条消息都切一次。 */
248
+ private readonly appliedOverrides = new Map<string, { agent?: string; model?: ModelRef }>()
156
249
  private disposed = false
157
250
 
158
251
  constructor(
@@ -162,6 +255,12 @@ export class SessionManager {
162
255
  /** 机器人固定服务的工作目录,所有 QQ 会话都建在这里。 */
163
256
  private readonly home: BotHome,
164
257
  private readonly history?: HistoryProvider,
258
+ /** 失败兜底通道;不传就只写日志。 */
259
+ private readonly notify?: FailureNotifier,
260
+ /** 按聊天覆盖 agent / 模型;不传就只用全局配置。 */
261
+ private readonly overrides?: ChatOverrides,
262
+ /** 调用链追踪器;不传就不记追踪。 */
263
+ private readonly tracer?: Tracer,
165
264
  ) {}
166
265
 
167
266
  /** 会话统一落在机器人工作目录,避免接管后上下文散落到别的项目。 */
@@ -194,7 +293,7 @@ export class SessionManager {
194
293
  const target = parseTargetKey(key)
195
294
  if (!target || typeof value !== "string" || value.length === 0) continue
196
295
  // 配置里已经移除的目标不再恢复,避免旧绑定继续获得工具权限。
197
- if (!isTargetEnabled(this.config, target)) continue
296
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
198
297
  if (!this.bindSession(this.state(target), value)) continue
199
298
  restored += 1
200
299
  }
@@ -207,7 +306,7 @@ export class SessionManager {
207
306
  for (const [key, value] of Object.entries(activity)) {
208
307
  const target = parseTargetKey(key)
209
308
  if (!target || typeof value !== "number" || !Number.isFinite(value)) continue
210
- if (!isTargetEnabled(this.config, target)) continue
309
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
211
310
  this.activity[targetKey(target)] = value
212
311
  const state = this.states.get(targetKey(target))
213
312
  if (state) state.lastUserMessageAt = value
@@ -232,7 +331,7 @@ export class SessionManager {
232
331
  if (!stored || typeof stored !== "object" || Array.isArray(stored)) return
233
332
  for (const [key, value] of Object.entries(stored)) {
234
333
  const target = parseTargetKey(key)
235
- if (!target || !isTargetEnabled(this.config, target)) continue
334
+ if (!target || !isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
236
335
  const position = parsePosition(value)
237
336
  if (!position) continue
238
337
  this.positions.set(key, position)
@@ -321,6 +420,7 @@ export class SessionManager {
321
420
  awaitingSend: false,
322
421
  reminders: 0,
323
422
  lastUserMessageAt: this.activity[key] ?? Date.now(),
423
+ lastRetireAt: 0,
324
424
  }
325
425
  this.states.set(key, state)
326
426
  }
@@ -337,9 +437,287 @@ export class SessionManager {
337
437
  return this.sessions.get(sessionID)?.current
338
438
  }
339
439
 
440
+ /** 当前轮次发送者的角色;没有轮次时按普通成员处理。 */
441
+ currentRole(sessionID: string): Role {
442
+ return this.sessions.get(sessionID)?.current?.role ?? "member"
443
+ }
444
+
445
+ /**
446
+ * 正在执行的 QQ 轮次:目标、轮次本身与发送者角色。
447
+ *
448
+ * 没有轮次(TUI 里人工驱动)或会话没有绑定 QQ 目标时返回 undefined。
449
+ */
450
+ activeTurn(
451
+ sessionID: string,
452
+ ): { target: ChatTarget; turn: Turn; role: Role; replied: boolean } | undefined {
453
+ const state = this.sessions.get(sessionID)
454
+ if (!state?.current) return undefined
455
+ return {
456
+ target: state.target,
457
+ turn: state.current,
458
+ role: state.current.role ?? "member",
459
+ // 这一轮已经调用过发送工具(含被限流拒绝),别再发一遍。
460
+ replied: !state.awaitingSend,
461
+ }
462
+ }
463
+
464
+ /**
465
+ * 导处在途状态,供实例交接时交给新实例。
466
+ *
467
+ * 只导出还有事情要做的聊天:正在执行的一轮、排队的消息、冻结的失败批次。
468
+ */
469
+ async exportHandover(): Promise<HandoverState[]> {
470
+ const handover: HandoverState[] = []
471
+ for (const state of this.states.values()) {
472
+ if (!state.current && state.buffer.length === 0 && !state.pending) continue
473
+ // 轮次挂上了但会话还没定下来:说明正卡在投递中途。等它落地再导出,
474
+ // 否则接手的实例拿到的是一个投不到上游的空壳轮次。
475
+ if (state.current && !state.sessionID) {
476
+ await this.waitDispatch(state.target)
477
+ if (!state.current && state.buffer.length === 0 && !state.pending) continue
478
+ }
479
+ handover.push({
480
+ target: state.target,
481
+ ...(state.sessionID ? { sessionID: state.sessionID } : {}),
482
+ ...(state.current ? { current: state.current } : {}),
483
+ awaitingSend: state.awaitingSend,
484
+ reminders: state.reminders,
485
+ lastDispatchAt: state.lastDispatchAt,
486
+ idleAt: state.idleAt,
487
+ buffer: [...state.buffer],
488
+ ...(state.pending ? { pending: state.pending } : {}),
489
+ pendingAttempts: state.pendingAttempts,
490
+ })
491
+ }
492
+ return handover
493
+ }
494
+
495
+ /** 等这个聊天正在进行的投递结束,最多等 HANDOVER_WAIT_MS。 */
496
+ private async waitDispatch(target: ChatTarget): Promise<void> {
497
+ let timer: ReturnType<typeof setTimeout> | undefined
498
+ const timeout = new Promise<void>((resolve) => {
499
+ timer = setTimeout(resolve, HANDOVER_WAIT_MS)
500
+ timer.unref?.()
501
+ })
502
+ try {
503
+ await Promise.race([this.targetMutex(target).runExclusive(async () => {}), timeout])
504
+ } finally {
505
+ if (timer) clearTimeout(timer)
506
+ }
507
+ }
508
+
509
+ /**
510
+ * 接管上一实例留下的状态。
511
+ *
512
+ * 实例被接管时,正在执行的一轮还在上游跑着;不接手的话,
513
+ * 这一轮模型再调用发送工具就会被当成没有轮次而拒绝,回复直接丢掉。
514
+ *
515
+ * @returns 实际接手的聊天数量。
516
+ */
517
+ async adoptHandover(handover: readonly HandoverState[]): Promise<number> {
518
+ let adopted = 0
519
+ let changed = false
520
+ for (const item of handover) {
521
+ // 配置里已经移除的目标不再接管,避免旧状态继续获得工具权限。
522
+ if (!isTargetAllowed(this.config.access, item.target, this.config.ownerQQ)) continue
523
+ const state = this.state(item.target)
524
+ // 已经有在途的事情就不接手,别把新实例自己的轮次顶掉。
525
+ if (state.current || state.buffer.length > 0 || state.pending) continue
526
+ if (state.sessionID && item.sessionID && state.sessionID !== item.sessionID) {
527
+ this.logger.warn(
528
+ `${targetLabel(item.target)} 交接时会话不一致(${state.sessionID} / ${item.sessionID}),保留原绑定`,
529
+ )
530
+ continue
531
+ }
532
+ if (item.sessionID && !(await this.sessionExists(item.sessionID))) {
533
+ this.logger.warn(
534
+ `${targetLabel(item.target)} 交接时会话 ${item.sessionID} 已不存在,丢弃这轮状态`,
535
+ )
536
+ continue
537
+ }
538
+ if (item.sessionID && !this.bindSession(state, item.sessionID)) continue
539
+ // 没有会话的轮次根本没投到上游,接过来也只是个空壳。
540
+ const current = item.current && item.sessionID ? item.current : undefined
541
+ if (item.current && !current) {
542
+ this.logger.warn(`${targetLabel(item.target)} 交接的轮次没有绑定会话,丢弃这一轮`)
543
+ }
544
+ state.current = current
545
+ state.awaitingSend = current ? item.awaitingSend : false
546
+ state.reminders = current ? item.reminders : 0
547
+ state.lastDispatchAt = item.lastDispatchAt
548
+ state.idleAt = item.idleAt
549
+ state.buffer = [...item.buffer]
550
+ state.pending = item.pending
551
+ state.pendingAttempts = item.pendingAttempts
552
+ // 缓存里的消息已经收过,补历史时别再重复一遍。
553
+ for (const turn of state.buffer) {
554
+ if (turn.source) this.rememberIncoming(item.target, turn.source.id)
555
+ }
556
+ // 这一轮已经投递过,位置跟着走,别再补一次同样的历史。
557
+ const source = current?.source
558
+ if (source) {
559
+ const key = targetKey(item.target)
560
+ this.positions.set(key, source)
561
+ this.restoredPositions.set(key, source)
562
+ }
563
+ if (item.sessionID || source) changed = true
564
+ adopted += 1
565
+ }
566
+ // 接手的绑定与位置要落盘,重启后才知道这一轮已经投递到哪里。
567
+ if (changed) this.scheduleSave()
568
+ return adopted
569
+ }
570
+
571
+ /**
572
+ * 重置一个聊天:先打断正在执行的回合,再解绑并删除会话。
573
+ *
574
+ * 下一条消息会新建会话并正常补历史;返回是否真的打断过。
575
+ */
576
+ async resetTarget(target: ChatTarget): Promise<{ sessionID?: string; interrupted: boolean }> {
577
+ const state = this.state(target)
578
+ const { sessionID, interrupted } = await this.detachSession(state)
579
+ state.buffer = []
580
+ state.pending = undefined
581
+ state.pendingAttempts = 0
582
+ this.endTurn(state, "resetTarget")
583
+ state.awaitingSend = false
584
+ state.reminders = 0
585
+ state.historyDone = false
586
+ state.sessionCreated = false
587
+ state.idleAt = Date.now()
588
+ this.scheduleSave()
589
+ return { sessionID, interrupted }
590
+ }
591
+
592
+ /**
593
+ * 退役绑定的会话:先打断,再删掉上游会话。
594
+ *
595
+ * 会话删掉后,下一条消息会新建会话并重新补历史。
596
+ */
597
+ private async detachSession(
598
+ state: ChatState,
599
+ ): Promise<{ sessionID?: string; interrupted: boolean }> {
600
+ const sessionID = state.sessionID
601
+ if (!sessionID) return { interrupted: false }
602
+ let interrupted = false
603
+ if (await this.sessionRunning(sessionID)) {
604
+ try {
605
+ await this.ctx.session.interrupt({ sessionID })
606
+ interrupted = true
607
+ } catch (error) {
608
+ this.logger.warn(`${targetLabel(state.target)} 打断会话 ${sessionID} 失败`, error)
609
+ }
610
+ }
611
+ this.clearBinding(state)
612
+ await this.ctx.session.remove({ sessionID }).catch((error: unknown) => {
613
+ this.logger.warn(`${targetLabel(state.target)} 删除会话 ${sessionID} 失败`, error)
614
+ })
615
+ return { sessionID, interrupted }
616
+ }
617
+
618
+ /**
619
+ * 连续投递失败后退役会话,让这个聊天重新能说话。
620
+ *
621
+ * 缓存里新到的消息保留:退役后由新会话接手,历史照常补齐。
622
+ * 冷却时间内的重复失败不再重建,避免上游整体故障时反复新建会话。
623
+ */
624
+ private async retireSession(state: ChatState): Promise<void> {
625
+ const sessionID = state.sessionID
626
+ if (!sessionID) return
627
+ const label = targetLabel(state.target)
628
+ const now = Date.now()
629
+ if (now - state.lastRetireAt < SESSION_RETIRE_COOLDOWN_MS) {
630
+ this.logger.warn(`${label} 会话 ${sessionID} 刚退役过,暂时不再重建`)
631
+ return
632
+ }
633
+ state.lastRetireAt = now
634
+ await this.detachSession(state)
635
+ this.endTurn(state, "retireSession")
636
+ state.awaitingSend = false
637
+ state.reminders = 0
638
+ // 新会话是空的,历史要重新补一次。
639
+ state.historyDone = false
640
+ state.sessionCreated = false
641
+ this.scheduleSave()
642
+ this.logger.warn(`${label} 会话 ${sessionID} 连续投递失败,已退役,下一条消息会新建会话`)
643
+ }
644
+
645
+ /** 各聊天当前状态的快照,供管理命令展示。 */
646
+ snapshot(): Array<{
647
+ target: ChatTarget
648
+ sessionID?: string
649
+ busy: boolean
650
+ buffered: number
651
+ pending: boolean
652
+ }> {
653
+ return [...this.states.values()]
654
+ .map((state) => ({
655
+ target: state.target,
656
+ ...(state.sessionID ? { sessionID: state.sessionID } : {}),
657
+ busy: state.current !== undefined,
658
+ buffered: state.buffer.length,
659
+ pending: state.pending !== undefined,
660
+ }))
661
+ .sort((left, right) => targetKey(left.target).localeCompare(targetKey(right.target)))
662
+ }
663
+
664
+ /**
665
+ * 结束当前轮次,并记下是哪条路径清的。
666
+ *
667
+ * 所有清空 `current` 的地方都走这里,线上排查时能看出轮次是何时、被谁清掉的。
668
+ */
669
+ private endTurn(state: ChatState, reason: string): void {
670
+ if (!state.current) {
671
+ // 不清空也要保留上一次真正的原因,别让空跑覆盖掉关键证据。
672
+ this.logger.debug(`${targetLabel(state.target)} 清轮次时已经没有轮次:${reason}`)
673
+ return
674
+ }
675
+ const now = Date.now()
676
+ state.lastClear = {
677
+ reason,
678
+ at: now,
679
+ role: state.current.role ?? "member",
680
+ ...(state.current.traceId ? { traceId: state.current.traceId } : {}),
681
+ }
682
+ this.logger.debug(`${targetLabel(state.target)} 清空当前轮次:${reason}`, {
683
+ role: state.lastClear.role,
684
+ ...(state.lastClear.traceId ? { trace_id: state.lastClear.traceId } : {}),
685
+ })
686
+ state.current = undefined
687
+ }
688
+
340
689
  /** 当前是否有 QQ 消息轮次正在执行,用于阻止手动 prompt 调用 QQ 工具。 */
341
690
  hasActiveTurn(sessionID: string): boolean {
342
- return this.sessions.get(sessionID)?.current !== undefined
691
+ const active = this.sessions.get(sessionID)?.current !== undefined
692
+ if (!active) {
693
+ this.logger.debug(`会话 ${sessionID} 没有在执行的 QQ 轮次`, this.describeTurn(sessionID))
694
+ }
695
+ return active
696
+ }
697
+
698
+ /** 当前轮次的状态快照,供拒绝工具调用时定位原因。 */
699
+ describeTurn(sessionID: string): Record<string, unknown> {
700
+ const state = this.sessions.get(sessionID)
701
+ if (!state) return { bound: false, now: Date.now() }
702
+ return {
703
+ bound: true,
704
+ target: targetLabel(state.target),
705
+ current: state.current
706
+ ? {
707
+ role: state.current.role ?? "member",
708
+ proactive: state.current.proactive === true,
709
+ ...(state.current.traceId ? { traceId: state.current.traceId } : {}),
710
+ }
711
+ : undefined,
712
+ awaitingSend: state.awaitingSend,
713
+ reminders: state.reminders,
714
+ buffer: state.buffer.length,
715
+ pending: state.pending !== undefined,
716
+ lastDispatchAt: state.lastDispatchAt,
717
+ idleAt: state.idleAt,
718
+ lastClear: state.lastClear,
719
+ now: Date.now(),
720
+ }
343
721
  }
344
722
 
345
723
  /** 标记模型已经调用过发送工具。 */
@@ -459,7 +837,13 @@ export class SessionManager {
459
837
  const info = await this.ctx.session.get({ sessionID: state.sessionID })
460
838
  const time = (info as { time?: { idle?: unknown } }).time
461
839
  const idleAt = toMillis(time?.idle)
462
- return idleAt !== undefined && idleAt < state.lastDispatchAt
840
+ const stale = idleAt !== undefined && idleAt < state.lastDispatchAt
841
+ this.logger.debug(`${targetLabel(state.target)} 结束信号时间比对`, {
842
+ idleAt,
843
+ lastDispatchAt: state.lastDispatchAt,
844
+ stale,
845
+ })
846
+ return stale
463
847
  } catch (error) {
464
848
  this.logger.debug(`${targetLabel(state.target)} 查询会话结束时间失败`, error)
465
849
  return false
@@ -498,6 +882,10 @@ export class SessionManager {
498
882
  )
499
883
  state.pending = undefined
500
884
  state.pendingAttempts = 0
885
+ // 这批消息再也进不了会话,群里得有个交代。
886
+ await this.notifyFailure(state, FAILURE_NOTICE)
887
+ // 连着几轮都收不下消息的会话已经废了,继续绑着只会让这个聊天一直不回话。
888
+ await this.retireSession(state)
501
889
  } else {
502
890
  state.pending = undefined
503
891
  state.pendingAttempts = 0
@@ -569,13 +957,30 @@ export class SessionManager {
569
957
  // 新的用户轮次重新给一份提醒预算,否则连续几轮不调工具就再也提醒不了。
570
958
  state.reminders = 0
571
959
  const label = targetLabel(state.target)
960
+ this.logger.debug(`${label} 开始投递一轮`, {
961
+ role: turn.role ?? "member",
962
+ proactive: turn.proactive === true,
963
+ atMe: turn.atMe,
964
+ ...(turn.traceId ? { trace_id: turn.traceId } : {}),
965
+ ...(turn.source ? { source: turn.source } : {}),
966
+ })
967
+ let sessionID: string | undefined
572
968
  try {
573
- const sessionID = await this.ensureSession(state.target)
969
+ sessionID = await this.ensureSession(state.target)
574
970
  if (!sessionID) {
575
- state.current = undefined
971
+ this.endTurn(state, "dispatch: 没有会话")
576
972
  state.awaitingSend = false
577
973
  return false
578
974
  }
975
+ // 模型起跑:从这里开始计时,看这一轮花了多久。
976
+ if (turn.traceId) {
977
+ await this.tracer?.record(
978
+ "agent_start",
979
+ turn.traceId,
980
+ { session_id: sessionID, chars: turn.text.length },
981
+ targetKey(state.target),
982
+ )
983
+ }
579
984
  await this.ctx.session.prompt({
580
985
  sessionID,
581
986
  ...(turn.id ? { id: turn.id } : {}),
@@ -589,12 +994,14 @@ export class SessionManager {
589
994
  // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
590
995
  this.scheduleSave()
591
996
  }
592
- this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`)
997
+ this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`, {
998
+ ...(turn.traceId ? { trace_id: turn.traceId } : {}),
999
+ })
593
1000
  return true
594
1001
  } catch (error) {
595
- state.current = undefined
1002
+ this.endTurn(state, "dispatch: 投递失败")
596
1003
  state.awaitingSend = false
597
- this.logger.error(`${label} 投递消息失败`, error)
1004
+ this.logger.error(`${label} 投递消息失败${sessionID ? `(会话 ${sessionID})` : ""}`, error)
598
1005
  return false
599
1006
  }
600
1007
  }
@@ -612,6 +1019,7 @@ export class SessionManager {
612
1019
  if (!state) return
613
1020
  await this.targetMutex(state.target).runExclusive(async () => {
614
1021
  const label = targetLabel(state.target)
1022
+ this.logger.debug(`${label} 收到 idle 钩子`, this.describeTurn(sessionID))
615
1023
 
616
1024
  if (background.some((task) => task.sessionID === sessionID)) {
617
1025
  this.logger.debug(`${label} 仍有后台任务,暂不投递缓存`)
@@ -630,13 +1038,20 @@ export class SessionManager {
630
1038
  return
631
1039
  }
632
1040
 
633
- state.current = undefined
1041
+ // 提醒沿用它正在提醒的那一轮的角色,别把 owner / 管理员降成普通成员。
1042
+ const reminderRole = state.current?.role
1043
+ this.endTurn(state, "handleIdle")
634
1044
 
635
1045
  if (
636
1046
  !state.awaitingSend ||
637
1047
  !this.config.reminder.enabled ||
638
1048
  state.reminders >= this.config.reminder.max
639
1049
  ) {
1050
+ this.logger.debug(`${label} 空闲结束,不再提醒`, {
1051
+ awaitingSend: state.awaitingSend,
1052
+ reminderEnabled: this.config.reminder.enabled,
1053
+ reminders: state.reminders,
1054
+ })
640
1055
  state.idleAt = Date.now()
641
1056
  return
642
1057
  }
@@ -644,7 +1059,12 @@ export class SessionManager {
644
1059
  state.reminders += 1
645
1060
  state.idleAt = 0
646
1061
  state.lastDispatchAt = Date.now()
647
- state.current = { text: "[提醒]", files: [], atMe: false }
1062
+ state.current = {
1063
+ text: "[提醒]",
1064
+ files: [],
1065
+ atMe: false,
1066
+ ...(reminderRole ? { role: reminderRole } : {}),
1067
+ }
648
1068
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
649
1069
  try {
650
1070
  await this.ctx.session.synthetic({
@@ -658,17 +1078,52 @@ export class SessionManager {
658
1078
  })
659
1079
  }
660
1080
 
661
- /** 模型执行失败或被中断:结束事件之后直接放行缓存。 */
662
- async handleExecutionEnd(sessionID: string, reason: string): Promise<void> {
1081
+ /**
1082
+ * 往聊天里补一条固定提示。
1083
+ *
1084
+ * 同一目标有冷却,连续失败只提示一次;发送失败也只写日志,不影响接下来的缓存投递。
1085
+ */
1086
+ private async notifyFailure(state: ChatState, text: string): Promise<void> {
1087
+ if (!this.notify) return
1088
+ const key = targetKey(state.target)
1089
+ const now = Date.now()
1090
+ const last = this.noticeAt.get(key)
1091
+ if (last !== undefined && now - last < FAILURE_NOTICE_INTERVAL_MS) return
1092
+ this.noticeAt.set(key, now)
1093
+ try {
1094
+ await this.notify(state.target, text)
1095
+ this.logger.debug(`${targetLabel(state.target)} 已补发失败提示`)
1096
+ } catch (error) {
1097
+ this.logger.warn(`${targetLabel(state.target)} 补发失败提示失败`, error)
1098
+ }
1099
+ }
1100
+
1101
+ /**
1102
+ * 回合失败或被中断:结束事件之后直接放行缓存。
1103
+ *
1104
+ * 模型一句话都没发出时往聊天里补一条固定提示,否则群里表现为「不回话」。
1105
+ * 上游异常原文只进日志,绝不发到 QQ。
1106
+ */
1107
+ async handleExecutionEnd(sessionID: string, reason: string, detail?: string): Promise<void> {
663
1108
  const state = this.sessions.get(sessionID)
664
1109
  if (!state) return
665
1110
  await this.targetMutex(state.target).runExclusive(async () => {
1111
+ this.logger.debug(
1112
+ `${targetLabel(state.target)} 收到执行结束事件(${reason})`,
1113
+ this.describeTurn(sessionID),
1114
+ )
666
1115
  if (await this.idleIsStale(state)) {
667
1116
  this.logger.debug(`${targetLabel(state.target)} 忽略上一轮迟到的结束事件(${reason})`)
668
1117
  return
669
1118
  }
670
- this.logger.warn(`${targetLabel(state.target)} 会话执行结束(${reason})`)
671
- state.current = undefined
1119
+ const label = targetLabel(state.target)
1120
+ const interrupted = reason === "session.execution.interrupted"
1121
+ this.logger.warn(`${label} 会话执行结束(${reason})${detail ? `:${detail}` : ""}`)
1122
+ // 模型已经发过东西就不用再补提示;主动搭话失败也不往群里道歉。
1123
+ if (state.awaitingSend && !state.current?.proactive) {
1124
+ await this.notifyFailure(state, interrupted ? INTERRUPTED_NOTICE : FAILURE_NOTICE)
1125
+ }
1126
+ this.endTurn(state, `handleExecutionEnd: ${reason}`)
672
1127
  state.awaitingSend = false
673
1128
  state.idleAt = Date.now()
674
1129
  await this.drain(state, true)
@@ -744,6 +1199,10 @@ export class SessionManager {
744
1199
  const state = this.sessions.get(sessionID)
745
1200
  if (!state) return
746
1201
  await this.targetMutex(state.target).runExclusive(async () => {
1202
+ this.logger.debug(
1203
+ `${targetLabel(state.target)} 收到空闲状态事件`,
1204
+ this.describeTurn(sessionID),
1205
+ )
747
1206
  if (await this.idleIsStale(state)) {
748
1207
  this.logger.debug(`${targetLabel(state.target)} 忽略上一轮迟到的结束信号`)
749
1208
  return
@@ -752,7 +1211,7 @@ export class SessionManager {
752
1211
  // 只有没有新轮次时,idle 时间才代表当前状态;投递缓存时若也写入,
753
1212
  // 会与紧接着的 dispatch 落在同一毫秒,误判为新一轮已经结束。
754
1213
  state.idleAt = Date.now()
755
- state.current = undefined
1214
+ this.endTurn(state, "flushBuffered: 空闲且无缓存")
756
1215
  return
757
1216
  }
758
1217
  this.logger.debug(`${targetLabel(state.target)} 空闲,投递 ${state.buffer.length} 条缓存消息`)
@@ -769,8 +1228,15 @@ export class SessionManager {
769
1228
  await this.ensureBindings()
770
1229
  const state = this.state(target)
771
1230
  const label = targetLabel(target)
1231
+ // 覆盖优先于全局配置;没写覆盖就用全局的。
1232
+ const override = await this.overrides?.for(target)
1233
+ const agent = override?.agent ?? this.config.agent
1234
+ const model = override?.model ?? this.config.model
772
1235
  if (state.sessionID) {
773
- if (await this.sessionExists(state.sessionID)) return state.sessionID
1236
+ if (await this.sessionExists(state.sessionID)) {
1237
+ await this.applyOverride(state.sessionID, label, agent, model)
1238
+ return state.sessionID
1239
+ }
774
1240
  this.unbind(state)
775
1241
  }
776
1242
 
@@ -781,6 +1247,7 @@ export class SessionManager {
781
1247
  this.verifiedSessions.add(reused)
782
1248
  this.scheduleSave()
783
1249
  this.logger.info(`${label} 复用已有会话 ${reused}`)
1250
+ await this.applyOverride(reused, label, agent, model)
784
1251
  return reused
785
1252
  }
786
1253
  }
@@ -788,8 +1255,8 @@ export class SessionManager {
788
1255
  const created = await this.ctx.session.create({
789
1256
  title: target.kind === "group" ? `QQ 群 ${target.id}` : `QQ 私聊 ${target.id}`,
790
1257
  location: this.location,
791
- ...(this.config.agent ? { agent: this.config.agent } : {}),
792
- ...(this.config.model ? { model: this.config.model } : {}),
1258
+ ...(agent ? { agent } : {}),
1259
+ ...(model ? { model } : {}),
793
1260
  metadata: {
794
1261
  qqTargetKind: target.kind,
795
1262
  qqTargetId: target.id,
@@ -804,11 +1271,45 @@ export class SessionManager {
804
1271
  }
805
1272
  this.verifiedSessions.add(created.id)
806
1273
  state.sessionCreated = true
1274
+ // 新建时已经带上覆盖值,记下来就不必再切一次。
1275
+ this.appliedOverrides.set(created.id, { agent, model })
807
1276
  this.scheduleSave()
808
1277
  this.logger.info(`${label} 新建会话 ${created.id}`)
809
1278
  return created.id
810
1279
  }
811
1280
 
1281
+ /**
1282
+ * 把 agent / 模型覆盖应用到已有会话。
1283
+ *
1284
+ * 只在覆盖真的变了的时候切换,避免每条消息都动一次会话。
1285
+ */
1286
+ private async applyOverride(
1287
+ sessionID: string,
1288
+ label: string,
1289
+ agent: string | undefined,
1290
+ model: ModelRef | undefined,
1291
+ ): Promise<void> {
1292
+ const applied = this.appliedOverrides.get(sessionID)
1293
+ if (applied?.agent === agent && sameModel(applied?.model, model)) return
1294
+ if (agent !== undefined && applied?.agent !== agent) {
1295
+ try {
1296
+ await this.ctx.session.switchAgent({ sessionID, agent })
1297
+ this.logger.info(`${label} 会话 ${sessionID} 切换到 agent ${agent}`)
1298
+ } catch (error) {
1299
+ this.logger.warn(`${label} 切换 agent ${agent} 失败`, error)
1300
+ }
1301
+ }
1302
+ if (model !== undefined && !sameModel(applied?.model, model)) {
1303
+ try {
1304
+ await this.ctx.session.switchModel({ sessionID, model })
1305
+ this.logger.info(`${label} 会话 ${sessionID} 切换到模型 ${model.providerID}/${model.id}`)
1306
+ } catch (error) {
1307
+ this.logger.warn(`${label} 切换模型失败`, error)
1308
+ }
1309
+ }
1310
+ this.appliedOverrides.set(sessionID, { agent, model })
1311
+ }
1312
+
812
1313
  /** 确认恢复的会话仍然存在,避免陈旧绑定让每条消息都失败。 */
813
1314
  private async sessionExists(sessionID: string): Promise<boolean> {
814
1315
  if (this.verifiedSessions.has(sessionID)) return true
@@ -823,11 +1324,18 @@ export class SessionManager {
823
1324
  }
824
1325
 
825
1326
  private unbind(state: ChatState): void {
1327
+ if (!state.sessionID) return
1328
+ this.clearBinding(state)
1329
+ this.scheduleSave()
1330
+ }
1331
+
1332
+ /** 清掉会话绑定,不动上游会话。 */
1333
+ private clearBinding(state: ChatState): void {
826
1334
  if (!state.sessionID) return
827
1335
  this.sessions.delete(state.sessionID)
828
1336
  this.verifiedSessions.delete(state.sessionID)
1337
+ this.appliedOverrides.delete(state.sessionID)
829
1338
  state.sessionID = undefined
830
- this.scheduleSave()
831
1339
  }
832
1340
 
833
1341
  /** 绑定会话到目标;一个会话只能绑定一个目标,已有绑定不能被覆盖。 */
@@ -885,31 +1393,48 @@ export class SessionManager {
885
1393
  const state = this.state(target)
886
1394
  await this.targetMutex(target).runExclusive(async () => {
887
1395
  if (state.buffer.length > 0 || state.current) return
1396
+ const traceId = this.tracer?.startTrace()
888
1397
  // 先占位,避免用户消息或下一次心跳同时投递。
889
1398
  state.idleAt = 0
890
1399
  state.lastDispatchAt = Date.now()
891
- state.current = { text, files: [], atMe: true, proactive: true }
1400
+ state.current = {
1401
+ text,
1402
+ files: [],
1403
+ atMe: true,
1404
+ proactive: true,
1405
+ // 主动说话没有人参与,上下文完全来自聊天内容,权限按最低算。
1406
+ role: "proactive",
1407
+ ...(traceId ? { traceId } : {}),
1408
+ }
892
1409
  state.awaitingSend = true
893
1410
  state.reminders = 0
894
1411
  try {
895
1412
  if (state.sessionID && (await this.sessionRunning(state.sessionID))) {
896
- state.current = undefined
1413
+ this.endTurn(state, "proactive: 上游仍在执行")
897
1414
  state.awaitingSend = false
898
1415
  return
899
1416
  }
900
1417
  const sessionID = await this.ensureSession(target)
901
1418
  if (!sessionID) {
902
- state.current = undefined
1419
+ this.endTurn(state, "proactive: 没有会话")
903
1420
  state.awaitingSend = false
904
1421
  return
905
1422
  }
906
1423
  state.lastUserMessageAt = Date.now()
907
1424
  this.activity[targetKey(target)] = state.lastUserMessageAt
908
1425
  this.scheduleSave()
1426
+ if (traceId) {
1427
+ await this.tracer?.record(
1428
+ "agent_start",
1429
+ traceId,
1430
+ { session_id: sessionID, proactive: true },
1431
+ targetKey(target),
1432
+ )
1433
+ }
909
1434
  await this.ctx.session.synthetic({ sessionID, text })
910
1435
  } catch (error) {
911
1436
  state.awaitingSend = false
912
- state.current = undefined
1437
+ this.endTurn(state, "proactive: 投递失败")
913
1438
  this.logger.error(`${targetLabel(target)} 主动说话失败`, error)
914
1439
  }
915
1440
  })