@cmach_socket/opencode-qq-bot 0.5.1 → 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.
@@ -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,15 @@ 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
+ /** 插件自己往聊天里补话的通道,失败兜底用。 */
43
+ export type FailureNotifier = (target: ChatTarget, text: string) => Promise<void>
30
44
  function toMillis(value: unknown): number | undefined {
31
45
  if (value instanceof Date) return value.getTime()
32
46
  if (typeof value === "number") return value
@@ -58,12 +72,20 @@ export interface Turn {
58
72
  text: string
59
73
  /** 图片附件。 */
60
74
  files: PromptFile[]
61
- /** 本轮是否 @ 了机器人。 */
75
+ /** 本轮是否必须回复:私聊、被 @ 或命中唤醒条件时为 true。 */
62
76
  atMe: boolean
77
+ /** 触发必回的原因,缺省按被 @ 处理。 */
78
+ wake?: WakeReason
63
79
  /** 是否由主动说话心跳发起。 */
64
80
  proactive?: boolean
65
81
  /** 本轮最后一条 QQ 消息的位置,用来记录已经投递到哪里。 */
66
82
  source?: HistoryPosition
83
+ /** 发送者角色;决定这一轮能用哪些工具,缺省按普通成员处理。 */
84
+ role?: Role
85
+ /** 调用链追踪 id,用来把这一轮的各个节点串起来。 */
86
+ traceId?: string
87
+ /** 这条消息明确不是在跟机器人说话,不要插话。 */
88
+ suppress?: boolean
67
89
  }
68
90
 
69
91
  interface ChatState {
@@ -104,11 +126,25 @@ export function mergeTurns(turns: readonly Turn[]): Turn {
104
126
  seen.add(turn.source.id)
105
127
  return true
106
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)
107
136
  // 批次的位置取最后一条带位置的消息。
108
137
  const source = unique.reduce<HistoryPosition | undefined>(
109
138
  (latest, turn) => turn.source ?? latest,
110
139
  undefined,
111
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"
112
148
  return {
113
149
  // 合并后的批次沿用第一条消息的幂等键,重试时保持一致。
114
150
  ...(unique[0]?.id ? { id: unique[0].id } : {}),
@@ -117,12 +153,25 @@ export function mergeTurns(turns: readonly Turn[]): Turn {
117
153
  .filter((text) => text.length > 0)
118
154
  .join("\n"),
119
155
  files: limitFiles(unique.flatMap((turn) => turn.files)),
120
- atMe: unique.some((turn) => turn.atMe),
156
+ atMe,
157
+ ...(wake ? { wake } : {}),
158
+ role,
121
159
  ...(unique.some((turn) => turn.proactive) ? { proactive: true } : {}),
160
+ ...(traceId ? { traceId } : {}),
161
+ ...(suppress ? { suppress: true } : {}),
122
162
  ...(source ? { source } : {}),
123
163
  }
124
164
  }
125
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
+
126
175
  function turnBytes(turn: Turn): number {
127
176
  return (
128
177
  turn.text.length * 2 +
@@ -153,6 +202,10 @@ export class SessionManager {
153
202
  private readonly restoredPositions = new Map<string, HistoryPosition>()
154
203
  /** 兜底轮询定时器:上游结束事件丢失时把缓存的消息投出去。 */
155
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 }>()
156
209
  private disposed = false
157
210
 
158
211
  constructor(
@@ -162,6 +215,12 @@ export class SessionManager {
162
215
  /** 机器人固定服务的工作目录,所有 QQ 会话都建在这里。 */
163
216
  private readonly home: BotHome,
164
217
  private readonly history?: HistoryProvider,
218
+ /** 失败兜底通道;不传就只写日志。 */
219
+ private readonly notify?: FailureNotifier,
220
+ /** 按聊天覆盖 agent / 模型;不传就只用全局配置。 */
221
+ private readonly overrides?: ChatOverrides,
222
+ /** 调用链追踪器;不传就不记追踪。 */
223
+ private readonly tracer?: Tracer,
165
224
  ) {}
166
225
 
167
226
  /** 会话统一落在机器人工作目录,避免接管后上下文散落到别的项目。 */
@@ -194,7 +253,7 @@ export class SessionManager {
194
253
  const target = parseTargetKey(key)
195
254
  if (!target || typeof value !== "string" || value.length === 0) continue
196
255
  // 配置里已经移除的目标不再恢复,避免旧绑定继续获得工具权限。
197
- if (!isTargetEnabled(this.config, target)) continue
256
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
198
257
  if (!this.bindSession(this.state(target), value)) continue
199
258
  restored += 1
200
259
  }
@@ -207,7 +266,7 @@ export class SessionManager {
207
266
  for (const [key, value] of Object.entries(activity)) {
208
267
  const target = parseTargetKey(key)
209
268
  if (!target || typeof value !== "number" || !Number.isFinite(value)) continue
210
- if (!isTargetEnabled(this.config, target)) continue
269
+ if (!isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
211
270
  this.activity[targetKey(target)] = value
212
271
  const state = this.states.get(targetKey(target))
213
272
  if (state) state.lastUserMessageAt = value
@@ -232,7 +291,7 @@ export class SessionManager {
232
291
  if (!stored || typeof stored !== "object" || Array.isArray(stored)) return
233
292
  for (const [key, value] of Object.entries(stored)) {
234
293
  const target = parseTargetKey(key)
235
- if (!target || !isTargetEnabled(this.config, target)) continue
294
+ if (!target || !isTargetAllowed(this.config.access, target, this.config.ownerQQ)) continue
236
295
  const position = parsePosition(value)
237
296
  if (!position) continue
238
297
  this.positions.set(key, position)
@@ -337,6 +396,79 @@ export class SessionManager {
337
396
  return this.sessions.get(sessionID)?.current
338
397
  }
339
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
+
340
472
  /** 当前是否有 QQ 消息轮次正在执行,用于阻止手动 prompt 调用 QQ 工具。 */
341
473
  hasActiveTurn(sessionID: string): boolean {
342
474
  return this.sessions.get(sessionID)?.current !== undefined
@@ -498,6 +630,8 @@ export class SessionManager {
498
630
  )
499
631
  state.pending = undefined
500
632
  state.pendingAttempts = 0
633
+ // 这批消息再也进不了会话,群里得有个交代。
634
+ await this.notifyFailure(state, FAILURE_NOTICE)
501
635
  } else {
502
636
  state.pending = undefined
503
637
  state.pendingAttempts = 0
@@ -576,6 +710,15 @@ export class SessionManager {
576
710
  state.awaitingSend = false
577
711
  return false
578
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
+ }
579
722
  await this.ctx.session.prompt({
580
723
  sessionID,
581
724
  ...(turn.id ? { id: turn.id } : {}),
@@ -589,7 +732,9 @@ export class SessionManager {
589
732
  // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
590
733
  this.scheduleSave()
591
734
  }
592
- this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`)
735
+ this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`, {
736
+ ...(turn.traceId ? { trace_id: turn.traceId } : {}),
737
+ })
593
738
  return true
594
739
  } catch (error) {
595
740
  state.current = undefined
@@ -630,6 +775,8 @@ export class SessionManager {
630
775
  return
631
776
  }
632
777
 
778
+ // 提醒沿用它正在提醒的那一轮的角色,别把 owner / 管理员降成普通成员。
779
+ const reminderRole = state.current?.role
633
780
  state.current = undefined
634
781
 
635
782
  if (
@@ -644,7 +791,12 @@ export class SessionManager {
644
791
  state.reminders += 1
645
792
  state.idleAt = 0
646
793
  state.lastDispatchAt = Date.now()
647
- state.current = { text: "[提醒]", files: [], atMe: false }
794
+ state.current = {
795
+ text: "[提醒]",
796
+ files: [],
797
+ atMe: false,
798
+ ...(reminderRole ? { role: reminderRole } : {}),
799
+ }
648
800
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
649
801
  try {
650
802
  await this.ctx.session.synthetic({
@@ -658,8 +810,33 @@ export class SessionManager {
658
810
  })
659
811
  }
660
812
 
661
- /** 模型执行失败或被中断:结束事件之后直接放行缓存。 */
662
- 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> {
663
840
  const state = this.sessions.get(sessionID)
664
841
  if (!state) return
665
842
  await this.targetMutex(state.target).runExclusive(async () => {
@@ -667,7 +844,13 @@ export class SessionManager {
667
844
  this.logger.debug(`${targetLabel(state.target)} 忽略上一轮迟到的结束事件(${reason})`)
668
845
  return
669
846
  }
670
- 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
+ }
671
854
  state.current = undefined
672
855
  state.awaitingSend = false
673
856
  state.idleAt = Date.now()
@@ -769,8 +952,15 @@ export class SessionManager {
769
952
  await this.ensureBindings()
770
953
  const state = this.state(target)
771
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
772
959
  if (state.sessionID) {
773
- 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
+ }
774
964
  this.unbind(state)
775
965
  }
776
966
 
@@ -781,6 +971,7 @@ export class SessionManager {
781
971
  this.verifiedSessions.add(reused)
782
972
  this.scheduleSave()
783
973
  this.logger.info(`${label} 复用已有会话 ${reused}`)
974
+ await this.applyOverride(reused, label, agent, model)
784
975
  return reused
785
976
  }
786
977
  }
@@ -788,8 +979,8 @@ export class SessionManager {
788
979
  const created = await this.ctx.session.create({
789
980
  title: target.kind === "group" ? `QQ 群 ${target.id}` : `QQ 私聊 ${target.id}`,
790
981
  location: this.location,
791
- ...(this.config.agent ? { agent: this.config.agent } : {}),
792
- ...(this.config.model ? { model: this.config.model } : {}),
982
+ ...(agent ? { agent } : {}),
983
+ ...(model ? { model } : {}),
793
984
  metadata: {
794
985
  qqTargetKind: target.kind,
795
986
  qqTargetId: target.id,
@@ -804,11 +995,45 @@ export class SessionManager {
804
995
  }
805
996
  this.verifiedSessions.add(created.id)
806
997
  state.sessionCreated = true
998
+ // 新建时已经带上覆盖值,记下来就不必再切一次。
999
+ this.appliedOverrides.set(created.id, { agent, model })
807
1000
  this.scheduleSave()
808
1001
  this.logger.info(`${label} 新建会话 ${created.id}`)
809
1002
  return created.id
810
1003
  }
811
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
+
812
1037
  /** 确认恢复的会话仍然存在,避免陈旧绑定让每条消息都失败。 */
813
1038
  private async sessionExists(sessionID: string): Promise<boolean> {
814
1039
  if (this.verifiedSessions.has(sessionID)) return true
@@ -826,6 +1051,7 @@ export class SessionManager {
826
1051
  if (!state.sessionID) return
827
1052
  this.sessions.delete(state.sessionID)
828
1053
  this.verifiedSessions.delete(state.sessionID)
1054
+ this.appliedOverrides.delete(state.sessionID)
829
1055
  state.sessionID = undefined
830
1056
  this.scheduleSave()
831
1057
  }
@@ -885,10 +1111,19 @@ export class SessionManager {
885
1111
  const state = this.state(target)
886
1112
  await this.targetMutex(target).runExclusive(async () => {
887
1113
  if (state.buffer.length > 0 || state.current) return
1114
+ const traceId = this.tracer?.startTrace()
888
1115
  // 先占位,避免用户消息或下一次心跳同时投递。
889
1116
  state.idleAt = 0
890
1117
  state.lastDispatchAt = Date.now()
891
- 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
+ }
892
1127
  state.awaitingSend = true
893
1128
  state.reminders = 0
894
1129
  try {
@@ -906,6 +1141,14 @@ export class SessionManager {
906
1141
  state.lastUserMessageAt = Date.now()
907
1142
  this.activity[targetKey(target)] = state.lastUserMessageAt
908
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
+ }
909
1152
  await this.ctx.session.synthetic({ sessionID, text })
910
1153
  } catch (error) {
911
1154
  state.awaitingSend = false
@@ -1,4 +1,5 @@
1
1
  import type { ProactiveConfig } from "../config"
2
+ import type { ChatOverride } from "../overrides"
2
3
 
3
4
  /**
4
5
  * 把“每小时目标概率”换算成单次心跳的触发概率。
@@ -20,3 +21,23 @@ export function proactiveTickProbability(
20
21
  const fraction = Math.min(1, config.tickSeconds / 3600)
21
22
  return 1 - Math.pow(1 - target, fraction)
22
23
  }
24
+
25
+ /**
26
+ * 这个聊天这一轮主动说话的概率。
27
+ *
28
+ * 聊天自己写了概率就用它:那是单次心跳的触发概率,不再随沉默时长增长。
29
+ * 沉默阈值对所有聊天一视同仁,没到阈值就不主动开口。
30
+ */
31
+ export function proactiveProbability(
32
+ override: ChatOverride,
33
+ config: Pick<
34
+ ProactiveConfig,
35
+ "startProbability" | "probabilityPerHour" | "silenceThresholdSeconds" | "tickSeconds"
36
+ >,
37
+ silenceSeconds: number,
38
+ ): number {
39
+ const silenceHours = (silenceSeconds - config.silenceThresholdSeconds) / 3600
40
+ if (silenceHours <= 0) return 0
41
+ if (override.proactiveProbability !== undefined) return override.proactiveProbability
42
+ return proactiveTickProbability(config, silenceSeconds)
43
+ }
@@ -178,3 +178,49 @@ export class SoulStore {
178
178
  export function packageDirectory(): string {
179
179
  return import.meta.dirname
180
180
  }
181
+
182
+ /**
183
+ * 多份角色设定的持有者:默认档 + 按路径懒加载。
184
+ *
185
+ * 每个聊天可以用覆盖配置指定自己的角色设定文件;同一路径只加载一次,
186
+ * 每份设定各自监听文件变化,改完下一轮即生效。
187
+ */
188
+ export class SoulLibrary {
189
+ readonly #stores = new Map<string, SoulStore>()
190
+ #defaultStore: SoulStore | undefined
191
+
192
+ constructor(
193
+ private readonly options: SoulOptions,
194
+ private readonly logger: Logger,
195
+ ) {}
196
+
197
+ /** 加载并返回默认角色设定。 */
198
+ async loadDefault(): Promise<SoulStore> {
199
+ if (this.#defaultStore) return this.#defaultStore
200
+ const path = resolveSoulPath(this.options)
201
+ const store = new SoulStore({ ...this.options, soulPath: path }, this.logger)
202
+ await store.load()
203
+ this.#defaultStore = store
204
+ this.#stores.set(path, store)
205
+ return store
206
+ }
207
+
208
+ /** 某个路径的角色设定;路径为空时用默认档。 */
209
+ async at(path: string | undefined): Promise<SoulStore> {
210
+ const explicit = path?.trim()
211
+ if (!explicit) return this.loadDefault()
212
+ const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.cwd, explicit)
213
+ const cached = this.#stores.get(absolute)
214
+ if (cached) return cached
215
+ const store = new SoulStore({ ...this.options, soulPath: absolute }, this.logger)
216
+ await store.load()
217
+ this.#stores.set(absolute, store)
218
+ return store
219
+ }
220
+
221
+ dispose(): void {
222
+ for (const store of this.#stores.values()) store.dispose()
223
+ this.#stores.clear()
224
+ this.#defaultStore = undefined
225
+ }
226
+ }
@@ -24,10 +24,9 @@ export async function registerAskGuard(deps: AskGuardDeps): Promise<{ dispose():
24
24
  const { ctx, logger, manager } = deps
25
25
  return await ctx.tool.hook("execute.before", async (event) => {
26
26
  if (event.tool !== QUESTION_TOOL) return
27
- const target = manager.targetForSession(event.sessionID)
28
- if (!target) return
29
- if (!manager.hasActiveTurn(event.sessionID)) return
30
- logger.warn(`${targetLabel(target)} 会话里模型尝试调用 ${QUESTION_TOOL} 工具,已拒绝`)
27
+ const active = manager.activeTurn(event.sessionID)
28
+ if (!active) return
29
+ logger.warn(`${targetLabel(active.target)} 会话里模型尝试调用 ${QUESTION_TOOL} 工具,已拒绝`)
31
30
  throw new Error(ASK_REFUSAL)
32
31
  })
33
32
  }
@@ -0,0 +1,45 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import { targetKey, targetLabel } from "../chat"
3
+ import type { Logger } from "../logger"
4
+ import type { SessionManager } from "../session/manager"
5
+ import type { ToolPolicy } from "./policy"
6
+
7
+ /** 会开启独立会话的工具名;不同版本分别叫 subagent 与 task。 */
8
+ const SUBAGENT_TOOLS = new Set(["subagent", "task"])
9
+
10
+ export interface ToolPolicyGuardDeps {
11
+ ctx: Plugin.Context
12
+ logger: Logger
13
+ manager: SessionManager
14
+ policy: ToolPolicy
15
+ }
16
+
17
+ /**
18
+ * 按聊天与角色拦截工具调用。
19
+ *
20
+ * 上下文钩子会把不允许的工具从列表里删掉,这里是第二道闸:
21
+ * Code Mode、并发调用或子代理绕过列表时仍然执行不了。
22
+ * 只对正在执行 QQ 轮次的会话生效,人工在 TUI 里驱动的会话不受影响。
23
+ */
24
+ export async function registerToolPolicy(
25
+ deps: ToolPolicyGuardDeps,
26
+ ): Promise<{ dispose(): Promise<void> }> {
27
+ const { ctx, logger, manager, policy } = deps
28
+ return await ctx.tool.hook("execute.before", async (event) => {
29
+ const active = manager.activeTurn(event.sessionID)
30
+ if (!active) return
31
+ // 子代理会开一个不受 QQ 聊天约束的新会话,哪怕配置档放行也一律拒绝。
32
+ if (SUBAGENT_TOOLS.has(event.tool)) {
33
+ logger.warn(`${targetLabel(active.target)} 会话里拒绝创建子代理 ${event.tool}`)
34
+ throw new Error("QQ 聊天会话里不能创建子代理:子会话不会继承按聊天的工具限制。")
35
+ }
36
+ const allowed = await policy.allow(active.role, targetKey(active.target), [event.tool])
37
+ if (allowed.size > 0) return
38
+ logger.warn(
39
+ `${targetLabel(active.target)} 会话里 ${active.role} 尝试调用工具 ${event.tool},已被工具配置拒绝`,
40
+ )
41
+ throw new Error(
42
+ `当前用户不能使用工具 ${event.tool}:工具权限由 tool-profiles.json 按聊天分配。`,
43
+ )
44
+ })
45
+ }