@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.8

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.
@@ -3,6 +3,7 @@ import type { Location } from "@opencode/schema"
3
3
  import { SessionMessage } from "@opencode/schema"
4
4
  import { Mutex } from "async-mutex"
5
5
  import { isTargetAllowed } from "../access"
6
+ import { unrefTimer } from "../async"
6
7
  import { type ChatTarget, parseTargetKey, targetKey, targetLabel } from "../chat"
7
8
  import type { ModelRef, QQBotConfig } from "../config"
8
9
  import type { BotHome } from "../home"
@@ -12,7 +13,8 @@ import type { ChatOverrides } from "../overrides"
12
13
  import type { Tracer } from "../trace"
13
14
  import { limitFiles, type PromptFile } from "../naplink/render"
14
15
  import type { WakeReason } from "../overrides"
15
- import { roleOf, type Role } from "../tools/policy"
16
+ import { roleForChat, roleOf, type Role } from "../tools/policy"
17
+ import { findSession } from "./find"
16
18
 
17
19
  /** 插件存储里保存会话与目标绑定的键。 */
18
20
  const BINDINGS_KEY = "bindings"
@@ -25,7 +27,7 @@ const INFLIGHT_KEY = "inflight"
25
27
  /** 单个目标最多缓存的消息条数。 */
26
28
  export const MAX_BUFFER_TURNS = 100
27
29
  /** 单个目标最多缓存的文本与附件字节数。 */
28
- export const MAX_BUFFER_BYTES = 32 * 1024 * 1024
30
+ const MAX_BUFFER_BYTES = 32 * 1024 * 1024
29
31
  /** 每个目标最多记录的消息 ID 数量。 */
30
32
  const MAX_TRACKED_MESSAGES = 200
31
33
  /** 刚投递的一轮还没在上游体现出忙碌状态,先跳过对账避免重复投递。 */
@@ -170,6 +172,10 @@ interface ChatState {
170
172
  lastRetireAt: number
171
173
  /** 最近一次清空当前轮次的原因与时间,仅供排查。 */
172
174
  lastClear?: { reason: string; at: number; role?: Role; traceId?: string }
175
+ /** 本轮是否已批准发送:模型先说明理由才拿到这个权限,轮次结束即失效。 */
176
+ replyAllowed: boolean
177
+ /** 批准发送的理由,仅供日志与排查。 */
178
+ replyReason?: string
173
179
  }
174
180
 
175
181
  /** 插件存储接受的值类型。 */
@@ -217,8 +223,6 @@ export interface HandoverState {
217
223
  pendingAttempts: number
218
224
  }
219
225
 
220
- type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
221
-
222
226
  /** 角色权限高低:数字越小权限越低。 */
223
227
  const ROLE_RANK: Record<Role, number> = {
224
228
  proactive: 0,
@@ -496,33 +500,30 @@ export class SessionManager {
496
500
  await this.writeInflight()
497
501
  }
498
502
 
503
+ /** 写插件存储;失败只记日志,不影响主流程。 */
504
+ private async store(key: string, value: StoredJson, failure: string): Promise<void> {
505
+ try {
506
+ await this.ctx.storage.set(key, value)
507
+ } catch (error) {
508
+ this.logger.error(failure, error)
509
+ }
510
+ }
511
+
499
512
  private async writeBindings(): Promise<void> {
500
513
  const bindings: Record<string, string> = {}
501
514
  for (const state of this.states.values()) {
502
515
  if (state.sessionID) bindings[targetKey(state.target)] = state.sessionID
503
516
  }
504
- try {
505
- await this.ctx.storage.set(BINDINGS_KEY, bindings)
506
- } catch (error) {
507
- this.logger.error("保存会话绑定失败", error)
508
- }
517
+ await this.store(BINDINGS_KEY, bindings, "保存会话绑定失败")
509
518
  }
510
519
 
511
520
  private async writeActivity(): Promise<void> {
512
- try {
513
- await this.ctx.storage.set(ACTIVITY_KEY, { ...this.activity })
514
- } catch (error) {
515
- this.logger.error("保存目标活跃时间失败", error)
516
- }
521
+ await this.store(ACTIVITY_KEY, { ...this.activity }, "保存目标活跃时间失败")
517
522
  }
518
523
 
519
524
  private async writePositions(): Promise<void> {
520
- try {
521
- const data: Record<string, { id: string; time: number }> = Object.fromEntries(this.positions)
522
- await this.ctx.storage.set(POSITIONS_KEY, data)
523
- } catch (error) {
524
- this.logger.error("保存消息位置失败", error)
525
- }
525
+ const data: Record<string, { id: string; time: number }> = Object.fromEntries(this.positions)
526
+ await this.store(POSITIONS_KEY, data, "保存消息位置失败")
526
527
  }
527
528
 
528
529
  /** 把正在执行的轮次写回存储,重启后据此恢复工具权限。 */
@@ -549,11 +550,7 @@ export class SessionManager {
549
550
  at: now,
550
551
  }
551
552
  }
552
- try {
553
- await this.ctx.storage.set(INFLIGHT_KEY, inflight as unknown as StoredJson)
554
- } catch (error) {
555
- this.logger.error("保存在途轮次失败", error)
556
- }
553
+ await this.store(INFLIGHT_KEY, inflight as unknown as StoredJson, "保存在途轮次失败")
557
554
  }
558
555
 
559
556
  /** 等待所有待写入的绑定落盘。 */
@@ -561,25 +558,24 @@ export class SessionManager {
561
558
  await this.saveMutex.runExclusive(() => this.persist())
562
559
  }
563
560
 
564
- /** 取目标对应的互斥锁,保证同一目标的状态变更与投递串行执行。 */
565
- private targetMutex(target: ChatTarget): Mutex {
566
- const key = targetKey(target)
567
- let mutex = this.targetMutexes.get(key)
561
+ /** 取(必要时创建)某个键对应的互斥锁。 */
562
+ private mutexFor(map: Map<string, Mutex>, key: string): Mutex {
563
+ let mutex = map.get(key)
568
564
  if (!mutex) {
569
565
  mutex = new Mutex()
570
- this.targetMutexes.set(key, mutex)
566
+ map.set(key, mutex)
571
567
  }
572
568
  return mutex
573
569
  }
574
570
 
571
+ /** 取目标对应的互斥锁,保证同一目标的状态变更与投递串行执行。 */
572
+ private targetMutex(target: ChatTarget): Mutex {
573
+ return this.mutexFor(this.targetMutexes, targetKey(target))
574
+ }
575
+
576
+ /** 建会话专用的锁,不能和投递锁共用:`Mutex` 不可重入,投递中建会话会死锁。 */
575
577
  private ensureMutex(target: ChatTarget): Mutex {
576
- const key = targetKey(target)
577
- let mutex = this.ensureMutexes.get(key)
578
- if (!mutex) {
579
- mutex = new Mutex()
580
- this.ensureMutexes.set(key, mutex)
581
- }
582
- return mutex
578
+ return this.mutexFor(this.ensureMutexes, targetKey(target))
583
579
  }
584
580
 
585
581
  /**
@@ -589,10 +585,7 @@ export class SessionManager {
589
585
  * 能拿到发送者时用 `roleFor` 精确判定。
590
586
  */
591
587
  private defaultRole(target: ChatTarget): Role {
592
- if (target.kind !== "private") return "member"
593
- if (target.id === this.config.ownerQQ) return "owner"
594
- if (this.config.admins.includes(target.id)) return "admin"
595
- return "member"
588
+ return roleForChat(this.config, target)
596
589
  }
597
590
 
598
591
  /** 按发送者 QQ 号还原角色;没有发送者时回退到聊天本身。 */
@@ -616,6 +609,7 @@ export class SessionManager {
616
609
  reminders: 0,
617
610
  lastUserMessageAt: this.activity[key] ?? Date.now(),
618
611
  lastRetireAt: 0,
612
+ replyAllowed: false,
619
613
  }
620
614
  this.states.set(key, state)
621
615
  }
@@ -694,7 +688,7 @@ export class SessionManager {
694
688
  let timer: ReturnType<typeof setTimeout> | undefined
695
689
  const timeout = new Promise<void>((resolve) => {
696
690
  timer = setTimeout(resolve, HANDOVER_WAIT_MS)
697
- timer.unref?.()
691
+ unrefTimer(timer)
698
692
  })
699
693
  try {
700
694
  await Promise.race([this.targetMutex(target).runExclusive(async () => {}), timeout])
@@ -777,14 +771,23 @@ export class SessionManager {
777
771
  state.buffer = []
778
772
  state.pending = undefined
779
773
  state.pendingAttempts = 0
780
- this.endTurn(state, "resetTarget")
774
+ state.idleAt = Date.now()
775
+ this.resetTurnState(state, "resetTarget")
776
+ return { sessionID, interrupted }
777
+ }
778
+
779
+ /**
780
+ * 清掉一个聊天的轮次运行时状态并落盘。
781
+ *
782
+ * 排队消息与待重试批次由调用方决定是否一起清掉。
783
+ */
784
+ private resetTurnState(state: ChatState, reason: string): void {
785
+ this.endTurn(state, reason)
781
786
  state.awaitingSend = false
782
787
  state.reminders = 0
783
788
  state.historyDone = false
784
789
  state.sessionCreated = false
785
- state.idleAt = Date.now()
786
790
  this.scheduleSave()
787
- return { sessionID, interrupted }
788
791
  }
789
792
 
790
793
  /**
@@ -830,13 +833,8 @@ export class SessionManager {
830
833
  }
831
834
  state.lastRetireAt = now
832
835
  await this.detachSession(state)
833
- this.endTurn(state, "retireSession")
834
- state.awaitingSend = false
835
- state.reminders = 0
836
836
  // 新会话是空的,历史要重新补一次。
837
- state.historyDone = false
838
- state.sessionCreated = false
839
- this.scheduleSave()
837
+ this.resetTurnState(state, "retireSession")
840
838
  this.logger.warn(`${label} 会话 ${sessionID} 连续投递失败,已退役,下一条消息会新建会话`)
841
839
  }
842
840
 
@@ -882,6 +880,9 @@ export class SessionManager {
882
880
  ...(state.lastClear.traceId ? { trace_id: state.lastClear.traceId } : {}),
883
881
  })
884
882
  state.current = undefined
883
+ // 发送权限只在本轮有效:轮次结束就收回,下一轮要重新说明理由。
884
+ state.replyAllowed = false
885
+ state.replyReason = undefined
885
886
  // 在途轮次落盘,重启后不会把已经结束的一轮又恢复出来。
886
887
  this.scheduleSave()
887
888
  }
@@ -916,6 +917,8 @@ export class SessionManager {
916
917
  lastDispatchAt: state.lastDispatchAt,
917
918
  idleAt: state.idleAt,
918
919
  lastClear: state.lastClear,
920
+ replyAllowed: state.replyAllowed,
921
+ replyReason: state.replyReason,
919
922
  now: Date.now(),
920
923
  }
921
924
  }
@@ -929,17 +932,36 @@ export class SessionManager {
929
932
  this.scheduleSave()
930
933
  }
931
934
 
935
+ /**
936
+ * 模型申请本轮的发送权限。
937
+ *
938
+ * 默认不给发送权限:模型得先说明为什么回复,拿到权限后才能调用发送工具。
939
+ * 权限只在本轮有效,轮次结束就失效。
940
+ *
941
+ * @returns 是否批准。会话没有绑定或已经有权限时不算失败。
942
+ */
943
+ requestReply(sessionID: string, reason: string): { granted: boolean; reason: string } {
944
+ const state = this.sessions.get(sessionID)
945
+ if (!state) return { granted: false, reason }
946
+ // 权限只在本轮有效:没有进行中的轮次就不给。
947
+ if (!state.current) {
948
+ this.logger.warn(`${targetLabel(state.target)} 没有进行中的轮次,不给发送权限`)
949
+ return { granted: false, reason }
950
+ }
951
+ state.replyAllowed = true
952
+ state.replyReason = reason
953
+ this.logger.info(`${targetLabel(state.target)} 模型申请本轮发送权限:${reason}`)
954
+ return { granted: true, reason }
955
+ }
956
+
957
+ /** 本轮是否已经拿到发送权限。 */
958
+ canReply(sessionID: string): boolean {
959
+ return this.sessions.get(sessionID)?.replyAllowed === true
960
+ }
961
+
932
962
  /** 记录一条机器人发出的消息,撤回工具只能操作这些消息。 */
933
963
  rememberOutgoing(target: ChatTarget, messageId: string): void {
934
- const key = targetKey(target)
935
- const ids = this.outgoing.get(key) ?? new Set<string>()
936
- ids.add(messageId)
937
- while (ids.size > MAX_TRACKED_MESSAGES) {
938
- const oldest = ids.values().next().value
939
- if (oldest === undefined) break
940
- ids.delete(oldest)
941
- }
942
- this.outgoing.set(key, ids)
964
+ this.track(this.outgoing, target, messageId)
943
965
  }
944
966
 
945
967
  /** 判断消息是否是机器人发出的。 */
@@ -953,8 +975,17 @@ export class SessionManager {
953
975
  * 返回该 ID 是否首次出现,用于忽略 NapCat 重连后重放的同一条消息。
954
976
  */
955
977
  rememberIncoming(target: ChatTarget, messageId: string): boolean {
978
+ return this.track(this.incoming, target, messageId)
979
+ }
980
+
981
+ /**
982
+ * 把消息 ID 记进目标的集合,超出上限时丢弃最旧的一条。
983
+ *
984
+ * @returns 该 ID 是否是首次记录。
985
+ */
986
+ private track(map: Map<string, Set<string>>, target: ChatTarget, messageId: string): boolean {
956
987
  const key = targetKey(target)
957
- const ids = this.incoming.get(key) ?? new Set<string>()
988
+ const ids = map.get(key) ?? new Set<string>()
958
989
  const isNew = !ids.has(messageId)
959
990
  ids.add(messageId)
960
991
  while (ids.size > MAX_TRACKED_MESSAGES) {
@@ -962,7 +993,7 @@ export class SessionManager {
962
993
  if (oldest === undefined) break
963
994
  ids.delete(oldest)
964
995
  }
965
- this.incoming.set(key, ids)
996
+ map.set(key, ids)
966
997
  return isNew
967
998
  }
968
999
 
@@ -1012,7 +1043,7 @@ export class SessionManager {
1012
1043
  if (state.buffer.length === 1 && bytes > MAX_BUFFER_BYTES) {
1013
1044
  this.logger.warn(`${targetLabel(state.target)} 单条消息超过缓存上限,仍保留该消息`)
1014
1045
  }
1015
- this.logger.debug(`${targetLabel(state.target)} 消息已入队(累计 ${state.buffer.length} 条)`)
1046
+ this.logger.info(`${targetLabel(state.target)} 消息已入队(累计 ${state.buffer.length} 条)`)
1016
1047
  }
1017
1048
 
1018
1049
  /** 上游会话是否仍在执行。 */
@@ -1095,7 +1126,7 @@ export class SessionManager {
1095
1126
  if (state.buffer.length === 0) return
1096
1127
  if (!force && state.sessionID && this.verifiedSessions.has(state.sessionID)) {
1097
1128
  if (await this.sessionRunning(state.sessionID)) {
1098
- this.logger.debug(
1129
+ this.logger.info(
1099
1130
  `${targetLabel(state.target)} 上游仍在执行,保留 ${state.buffer.length} 条消息`,
1100
1131
  )
1101
1132
  return
@@ -1200,7 +1231,7 @@ export class SessionManager {
1200
1231
  // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
1201
1232
  this.scheduleSave()
1202
1233
  }
1203
- this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`, {
1234
+ this.logger.info(`${label} 已投递消息到会话 ${sessionID}`, {
1204
1235
  ...(turn.traceId ? { trace_id: turn.traceId } : {}),
1205
1236
  })
1206
1237
  return true
@@ -1272,10 +1303,15 @@ export class SessionManager {
1272
1303
  ...(reminderRole ? { role: reminderRole } : {}),
1273
1304
  }
1274
1305
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
1306
+ // 群里默认没有发送权限,提醒里得说清楚先申请再发。
1307
+ const permissionHint =
1308
+ this.config.reply.requirePermission && state.target.kind === "group"
1309
+ ? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。"
1310
+ : ""
1275
1311
  try {
1276
1312
  await this.ctx.session.synthetic({
1277
1313
  sessionID,
1278
- text: `[提醒] 你这一轮没有调用任何发送工具,直接输出的文字会被丢弃。请调用 qq_send_message 工具:想回复就 reply=true 并给出 content,不想回复就 reply=false;发送图片、语音、转发或戳一戳也视为已回复。`,
1314
+ text: `[提醒] 你这一轮没有调用任何发送工具,直接输出的文字会被丢弃。请调用 qq_send_message 工具:想回复就 reply=true 并给出 content,不想回复就 reply=false;发送图片、语音、转发或戳一戳也视为已回复。${permissionHint}`,
1279
1315
  })
1280
1316
  } catch (error) {
1281
1317
  state.awaitingSend = false
@@ -1375,8 +1411,7 @@ export class SessionManager {
1375
1411
  this.watchdog = undefined
1376
1412
  void this.runWatchdog()
1377
1413
  }, RESUME_INTERVAL_MS)
1378
- const handle = this.watchdog as { unref?: () => void }
1379
- handle.unref?.()
1414
+ unrefTimer(this.watchdog)
1380
1415
  }
1381
1416
 
1382
1417
  /** 兜底轮询一轮:按上游会话状态把缓存的消息放出去。 */
@@ -1566,32 +1601,16 @@ export class SessionManager {
1566
1601
 
1567
1602
  /** 查找带相同目标标记的历史会话,按最近优先分页查找。 */
1568
1603
  private async findExistingSession(target: ChatTarget): Promise<string | undefined> {
1569
- let cursor: SessionListCursor | undefined
1570
- try {
1571
- for (let page = 0; page < 5; page += 1) {
1572
- const result = await this.ctx.session.list({
1573
- directory: this.location.directory,
1574
- limit: 100,
1575
- order: "desc",
1576
- ...(cursor ? { cursor } : {}),
1577
- })
1578
- const hit = result.data.find((session) => {
1579
- const metadata = session.metadata
1580
- return metadata?.["qqTargetKind"] === target.kind && metadata["qqTargetId"] === target.id
1581
- })
1582
- if (hit) return hit.id
1583
- cursor = result.cursor.next ?? undefined
1584
- if (!cursor) break
1585
- }
1586
- } catch (error) {
1587
- this.logger.warn(`查找历史会话失败 ${targetLabel(target)}`, error)
1588
- }
1589
- return undefined
1590
- }
1591
-
1592
- /** 该目标是否已经建立过会话。 */
1593
- hasSession(target: ChatTarget): boolean {
1594
- return this.states.get(targetKey(target))?.sessionID !== undefined
1604
+ return await findSession(
1605
+ this.ctx,
1606
+ this.location.directory,
1607
+ (session) => {
1608
+ const metadata = session.metadata
1609
+ return metadata?.["qqTargetKind"] === target.kind && metadata["qqTargetId"] === target.id
1610
+ },
1611
+ this.logger,
1612
+ `查找历史会话失败 ${targetLabel(target)}`,
1613
+ )
1595
1614
  }
1596
1615
 
1597
1616
  /** 主动说话:向目标对应的会话投递一条合成消息。 */
@@ -1,19 +1,19 @@
1
1
  import type { ProactiveConfig } from "../config"
2
2
  import type { ChatOverride } from "../overrides"
3
3
 
4
+ /** 概率换算需要的配置项。 */
5
+ export type ProactiveRate = Pick<
6
+ ProactiveConfig,
7
+ "startProbability" | "probabilityPerHour" | "silenceThresholdSeconds" | "tickSeconds"
8
+ >
9
+
4
10
  /**
5
11
  * 把“每小时目标概率”换算成单次心跳的触发概率。
6
12
  *
7
13
  * 直接在每个 tick 上抽 `startProbability + probabilityPerHour * hours` 会让实际频率
8
14
  * 随 tickSeconds 放大;这里按 tick 占一小时的比例做指数换算。
9
15
  */
10
- export function proactiveTickProbability(
11
- config: Pick<
12
- ProactiveConfig,
13
- "startProbability" | "probabilityPerHour" | "silenceThresholdSeconds" | "tickSeconds"
14
- >,
15
- silenceSeconds: number,
16
- ): number {
16
+ export function proactiveTickProbability(config: ProactiveRate, silenceSeconds: number): number {
17
17
  const silenceHours = (silenceSeconds - config.silenceThresholdSeconds) / 3600
18
18
  if (silenceHours <= 0) return 0
19
19
  const target = Math.min(1, config.startProbability + config.probabilityPerHour * silenceHours)
@@ -30,10 +30,7 @@ export function proactiveTickProbability(
30
30
  */
31
31
  export function proactiveProbability(
32
32
  override: ChatOverride,
33
- config: Pick<
34
- ProactiveConfig,
35
- "startProbability" | "probabilityPerHour" | "silenceThresholdSeconds" | "tickSeconds"
36
- >,
33
+ config: ProactiveRate,
37
34
  silenceSeconds: number,
38
35
  ): number {
39
36
  const silenceHours = (silenceSeconds - config.silenceThresholdSeconds) / 3600
@@ -1,6 +1,8 @@
1
- import { readFile } from "node:fs/promises"
1
+ import { mkdir, readdir, readFile } from "node:fs/promises"
2
2
  import { existsSync, statSync, watch, type FSWatcher } from "node:fs"
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path"
4
+ import { unrefTimer } from "../async"
5
+ import { seedFile } from "../seed"
4
6
  import type { Logger } from "../logger"
5
7
  import { buildSystemPrompt } from "./prompt"
6
8
 
@@ -18,21 +20,22 @@ export interface SoulOptions {
18
20
  soulPath?: string
19
21
  /** souls 目录里的文件名。 */
20
22
  soulName?: string
21
- /** 插件所在目录,用于向上查找包内 souls 目录。 */
23
+ /** 机器人工作目录:角色设定放这里,升级插件不会覆盖。 */
24
+ home: string
25
+ /** 插件所在目录,用于查找随包分发的初始角色设定。 */
22
26
  moduleDir: string
23
- /** 相对路径的基准目录。 */
24
- cwd: string
25
27
  }
26
28
 
27
- /** 从 startDir 向上逐级查找 souls/<name>。 */
28
- export function findSoulFile(
29
- startDir: string,
30
- name: string = DEFAULT_SOUL_NAME,
31
- maxDepth = 5,
32
- ): string | undefined {
29
+ /** 工作目录里的角色设定目录。 */
30
+ export function soulsDirectory(home: string): string {
31
+ return join(home, SOUL_DIR)
32
+ }
33
+
34
+ /** 从 startDir 向上逐级查找随包分发的 souls 目录。 */
35
+ export function findSoulsDirectory(startDir: string, maxDepth = 5): string | undefined {
33
36
  let current = resolve(startDir)
34
37
  for (let depth = 0; depth <= maxDepth; depth += 1) {
35
- const candidate = join(current, SOUL_DIR, name)
38
+ const candidate = join(current, SOUL_DIR)
36
39
  if (existsSync(candidate)) return candidate
37
40
  const parent = dirname(current)
38
41
  if (parent === current) break
@@ -41,28 +44,44 @@ export function findSoulFile(
41
44
  return undefined
42
45
  }
43
46
 
44
- /** 找不到文件时给出预期路径,文件补齐后可被监听器捡到。 */
45
- export function expectedSoulPath(startDir: string, name: string, maxDepth = 5): string {
46
- let current = resolve(startDir)
47
- for (let depth = 0; depth <= maxDepth; depth += 1) {
48
- const directory = join(current, SOUL_DIR)
49
- if (existsSync(directory)) return join(directory, name)
50
- const parent = dirname(current)
51
- if (parent === current) break
52
- current = parent
47
+ /**
48
+ * 把随包分发的角色设定补进工作目录。
49
+ *
50
+ * 只补缺失的文件:插件升级不会覆盖用户改过的设定,首次启动则拿到一份能直接用的默认档。
51
+ */
52
+ export async function seedSouls(
53
+ options: Pick<SoulOptions, "home" | "moduleDir">,
54
+ logger: Logger,
55
+ ): Promise<void> {
56
+ const target = soulsDirectory(options.home)
57
+ await mkdir(target, { recursive: true, mode: 0o700 })
58
+ const template = findSoulsDirectory(options.moduleDir)
59
+ if (!template || resolve(template) === resolve(target)) return
60
+ let entries
61
+ try {
62
+ entries = await readdir(template, { withFileTypes: true })
63
+ } catch (error) {
64
+ logger.debug("读取随包角色设定失败", error)
65
+ return
66
+ }
67
+ for (const entry of entries) {
68
+ if (!entry.isFile()) continue
69
+ // 已有同名文件说明用户改过或换过,seedFile 不会动它。
70
+ await seedFile(join(template, entry.name), join(target, entry.name), logger)
53
71
  }
54
- return join(resolve(startDir), SOUL_DIR, name)
55
72
  }
56
73
 
57
- /** 定位角色设定文件:显式路径优先,其次 souls 目录里的指定文件。 */
74
+ /**
75
+ * 定位角色设定文件:显式路径优先,否则取工作目录 `souls/` 里的指定文件。
76
+ *
77
+ * 相对路径按工作目录解析,与项目目录无关。
78
+ */
58
79
  export function resolveSoulPath(options: SoulOptions): string {
59
80
  const name = options.soulName?.trim() || DEFAULT_SOUL_NAME
60
81
  const explicit = options.soulPath?.trim()
61
- if (!explicit) {
62
- return findSoulFile(options.moduleDir, name) ?? expectedSoulPath(options.moduleDir, name)
63
- }
82
+ if (!explicit) return join(soulsDirectory(options.home), name)
64
83
 
65
- const target = isAbsolute(explicit) ? explicit : resolve(options.cwd, explicit)
84
+ const target = isAbsolute(explicit) ? explicit : resolve(options.home, explicit)
66
85
  if (existsSync(target) && statSync(target).isDirectory()) return join(target, name)
67
86
  return target
68
87
  }
@@ -154,8 +173,7 @@ export class SoulStore {
154
173
  this.#logger.warn("角色设定监听失败,改动后需要重载插件", error)
155
174
  return
156
175
  }
157
- const handle = this.#watcher as { unref?: () => void }
158
- handle.unref?.()
176
+ unrefTimer(this.#watcher)
159
177
  }
160
178
 
161
179
  #matches(filename: string, directory: string): boolean {
@@ -169,8 +187,7 @@ export class SoulStore {
169
187
  this.#timer = undefined
170
188
  void this.reload()
171
189
  }, RELOAD_DEBOUNCE_MS)
172
- const handle = this.#timer as { unref?: () => void }
173
- handle.unref?.()
190
+ unrefTimer(this.#timer)
174
191
  }
175
192
  }
176
193
 
@@ -209,7 +226,7 @@ export class SoulLibrary {
209
226
  async at(path: string | undefined): Promise<SoulStore> {
210
227
  const explicit = path?.trim()
211
228
  if (!explicit) return this.loadDefault()
212
- const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.cwd, explicit)
229
+ const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.home, explicit)
213
230
  const cached = this.#stores.get(absolute)
214
231
  if (cached) return cached
215
232
  const store = new SoulStore({ ...this.options, soulPath: absolute }, this.logger)
package/src/text.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** 零宽字符:可以用来把关键字拆成看起来正常、匹配不上的形式。 */
2
+ export const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
3
+
4
+ /** 截断过长的地址,避免日志被超长 URL 淹没。 */
5
+ export function truncateForLog(value: string, max = 120): string {
6
+ return value.length > max ? `${value.slice(0, max)}…` : value
7
+ }
@@ -3,6 +3,7 @@ import { targetKey, targetLabel } from "../chat"
3
3
  import type { Logger } from "../logger"
4
4
  import type { SessionManager } from "../session/manager"
5
5
  import type { ToolPolicy } from "./policy"
6
+ import { QQ_REQUEST_REPLY_TOOL } from "./qq"
6
7
 
7
8
  /** 会开启独立会话的工具名;不同版本分别叫 subagent 与 task。 */
8
9
  const SUBAGENT_TOOLS = new Set(["subagent", "task"])
@@ -35,6 +36,8 @@ export async function registerToolPolicy(
35
36
  logger.warn(`${targetLabel(target)} 会话里拒绝创建子代理 ${event.tool}`)
36
37
  throw new Error("QQ 聊天会话里不能创建子代理:子会话不会继承按聊天的工具限制。")
37
38
  }
39
+ // 申请回复权限的工具必须一直放行:不然模型永远拿不到发送权限。
40
+ if (event.tool === QQ_REQUEST_REPLY_TOOL) return
38
41
  const allowed = await policy.allow(role, targetKey(target), [event.tool])
39
42
  logger.debug(`${targetLabel(target)} 工具策略检查`, {
40
43
  role,
@@ -1,5 +1,6 @@
1
1
  import { readFile, stat } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
+ import type { ChatTarget } from "../chat"
3
4
  import type { QQBotConfig } from "../config"
4
5
  import type { Logger } from "../logger"
5
6
 
@@ -19,6 +20,11 @@ export function roleOf(config: QQBotConfig, senderQQ: string): Role {
19
20
  return "member"
20
21
  }
21
22
 
23
+ /** 聊天本身对应的角色:私聊按主人身份,群聊统一按普通成员。 */
24
+ export function roleForChat(config: QQBotConfig, target: ChatTarget): Role {
25
+ return target.kind === "private" ? roleOf(config, String(target.id)) : "member"
26
+ }
27
+
22
28
  /** 一档工具配置:allow 命中且 deny 不命中的工具才放行。 */
23
29
  export interface ToolProfile {
24
30
  allow: string[]
@@ -50,9 +56,9 @@ export function defaultToolPolicy(): ToolPolicyFile {
50
56
  }
51
57
  }
52
58
 
53
- /** 默认的配置文件位置:当前工作目录下的 `tool-profiles.json`。 */
54
- export function defaultToolProfilesPath(): string {
55
- return join(process.cwd(), "tool-profiles.json")
59
+ /** 默认的配置文件位置:工作目录下的 `tool-profiles.json`。 */
60
+ export function defaultToolProfilesPath(home: string): string {
61
+ return join(home, "tool-profiles.json")
56
62
  }
57
63
 
58
64
  /**