@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.7

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.
package/src/sensitive.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DETECTORS, redact, scan, type Detector } from "flare-redact"
2
+ import { ZERO_WIDTH } from "./text"
2
3
 
3
4
  /** 命中的敏感信息。 */
4
5
  export interface SensitiveHit {
@@ -58,9 +59,6 @@ const MIN_SECRET_LENGTH = 12
58
59
  /** 已知凭证的分片长度:够长不撞车,又短到能抓住被拆开的凭证。 */
59
60
  const FRAGMENT_LENGTH = 12
60
61
 
61
- /** 零宽字符:插在凭证中间用来骗过正则。 */
62
- const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
63
-
64
62
  /** 文本里像 base64 的片段。 */
65
63
  const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g
66
64
 
@@ -218,7 +216,7 @@ function looksLikeText(text: string): boolean {
218
216
  }
219
217
 
220
218
  /** 解一段 base64;解不出人话就返回 undefined。 */
221
- function decodeBase64(input: string): string | undefined {
219
+ function decodeBase64Text(input: string): string | undefined {
222
220
  const standard = input.replace(/-/g, "+").replace(/_/g, "/")
223
221
  const padded = standard + "=".repeat((4 - (standard.length % 4)) % 4)
224
222
  const decoded = Buffer.from(padded, "base64").toString("utf8")
@@ -233,7 +231,7 @@ function base64Variants(text: string): string[] {
233
231
  const runs = text.match(BASE64_RUN) ?? []
234
232
  const variants: string[] = []
235
233
  for (const run of runs.slice(0, MAX_BASE64_RUNS)) {
236
- const decoded = decodeBase64(run)
234
+ const decoded = decodeBase64Text(run)
237
235
  if (decoded) variants.push(decoded)
238
236
  }
239
237
  return variants
@@ -0,0 +1,45 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import type { Logger } from "../logger"
3
+
4
+ /** 会话列表最多翻几页。 */
5
+ const MAX_PAGES = 5
6
+ /** 每页抓多少条。 */
7
+ const PAGE_SIZE = 100
8
+
9
+ type ListResult = Awaited<ReturnType<Plugin.Context["session"]["list"]>>
10
+ /** 会话列表里的单条会话。 */
11
+ export type ListedSession = ListResult["data"][number]
12
+
13
+ /**
14
+ * 在指定目录下按谓词查找会话。
15
+ *
16
+ * 列表按创建时间倒序、翻页上限固定,避免会话很多时把整个列表拉一遍。
17
+ *
18
+ * @returns 命中的会话 ID;找不到或查询失败时返回 `undefined`。
19
+ */
20
+ export async function findSession(
21
+ ctx: Plugin.Context,
22
+ directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
23
+ match: (session: ListedSession) => boolean,
24
+ logger: Logger,
25
+ failure: string,
26
+ ): Promise<string | undefined> {
27
+ let cursor: ListResult["cursor"]["next"] | undefined
28
+ try {
29
+ for (let page = 0; page < MAX_PAGES; page += 1) {
30
+ const result = await ctx.session.list({
31
+ directory,
32
+ limit: PAGE_SIZE,
33
+ order: "desc",
34
+ ...(cursor ? { cursor } : {}),
35
+ })
36
+ const hit = result.data.find(match)
37
+ if (hit) return hit.id
38
+ cursor = result.cursor.next ?? undefined
39
+ if (!cursor) break
40
+ }
41
+ } catch (error) {
42
+ logger.warn(failure, error)
43
+ }
44
+ return undefined
45
+ }
@@ -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
  /** 刚投递的一轮还没在上游体现出忙碌状态,先跳过对账避免重复投递。 */
@@ -217,8 +219,6 @@ export interface HandoverState {
217
219
  pendingAttempts: number
218
220
  }
219
221
 
220
- type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
221
-
222
222
  /** 角色权限高低:数字越小权限越低。 */
223
223
  const ROLE_RANK: Record<Role, number> = {
224
224
  proactive: 0,
@@ -496,33 +496,30 @@ export class SessionManager {
496
496
  await this.writeInflight()
497
497
  }
498
498
 
499
+ /** 写插件存储;失败只记日志,不影响主流程。 */
500
+ private async store(key: string, value: StoredJson, failure: string): Promise<void> {
501
+ try {
502
+ await this.ctx.storage.set(key, value)
503
+ } catch (error) {
504
+ this.logger.error(failure, error)
505
+ }
506
+ }
507
+
499
508
  private async writeBindings(): Promise<void> {
500
509
  const bindings: Record<string, string> = {}
501
510
  for (const state of this.states.values()) {
502
511
  if (state.sessionID) bindings[targetKey(state.target)] = state.sessionID
503
512
  }
504
- try {
505
- await this.ctx.storage.set(BINDINGS_KEY, bindings)
506
- } catch (error) {
507
- this.logger.error("保存会话绑定失败", error)
508
- }
513
+ await this.store(BINDINGS_KEY, bindings, "保存会话绑定失败")
509
514
  }
510
515
 
511
516
  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
- }
517
+ await this.store(ACTIVITY_KEY, { ...this.activity }, "保存目标活跃时间失败")
517
518
  }
518
519
 
519
520
  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
- }
521
+ const data: Record<string, { id: string; time: number }> = Object.fromEntries(this.positions)
522
+ await this.store(POSITIONS_KEY, data, "保存消息位置失败")
526
523
  }
527
524
 
528
525
  /** 把正在执行的轮次写回存储,重启后据此恢复工具权限。 */
@@ -549,11 +546,7 @@ export class SessionManager {
549
546
  at: now,
550
547
  }
551
548
  }
552
- try {
553
- await this.ctx.storage.set(INFLIGHT_KEY, inflight as unknown as StoredJson)
554
- } catch (error) {
555
- this.logger.error("保存在途轮次失败", error)
556
- }
549
+ await this.store(INFLIGHT_KEY, inflight as unknown as StoredJson, "保存在途轮次失败")
557
550
  }
558
551
 
559
552
  /** 等待所有待写入的绑定落盘。 */
@@ -561,25 +554,24 @@ export class SessionManager {
561
554
  await this.saveMutex.runExclusive(() => this.persist())
562
555
  }
563
556
 
564
- /** 取目标对应的互斥锁,保证同一目标的状态变更与投递串行执行。 */
565
- private targetMutex(target: ChatTarget): Mutex {
566
- const key = targetKey(target)
567
- let mutex = this.targetMutexes.get(key)
557
+ /** 取(必要时创建)某个键对应的互斥锁。 */
558
+ private mutexFor(map: Map<string, Mutex>, key: string): Mutex {
559
+ let mutex = map.get(key)
568
560
  if (!mutex) {
569
561
  mutex = new Mutex()
570
- this.targetMutexes.set(key, mutex)
562
+ map.set(key, mutex)
571
563
  }
572
564
  return mutex
573
565
  }
574
566
 
567
+ /** 取目标对应的互斥锁,保证同一目标的状态变更与投递串行执行。 */
568
+ private targetMutex(target: ChatTarget): Mutex {
569
+ return this.mutexFor(this.targetMutexes, targetKey(target))
570
+ }
571
+
572
+ /** 建会话专用的锁,不能和投递锁共用:`Mutex` 不可重入,投递中建会话会死锁。 */
575
573
  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
574
+ return this.mutexFor(this.ensureMutexes, targetKey(target))
583
575
  }
584
576
 
585
577
  /**
@@ -589,10 +581,7 @@ export class SessionManager {
589
581
  * 能拿到发送者时用 `roleFor` 精确判定。
590
582
  */
591
583
  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"
584
+ return roleForChat(this.config, target)
596
585
  }
597
586
 
598
587
  /** 按发送者 QQ 号还原角色;没有发送者时回退到聊天本身。 */
@@ -694,7 +683,7 @@ export class SessionManager {
694
683
  let timer: ReturnType<typeof setTimeout> | undefined
695
684
  const timeout = new Promise<void>((resolve) => {
696
685
  timer = setTimeout(resolve, HANDOVER_WAIT_MS)
697
- timer.unref?.()
686
+ unrefTimer(timer)
698
687
  })
699
688
  try {
700
689
  await Promise.race([this.targetMutex(target).runExclusive(async () => {}), timeout])
@@ -777,14 +766,23 @@ export class SessionManager {
777
766
  state.buffer = []
778
767
  state.pending = undefined
779
768
  state.pendingAttempts = 0
780
- this.endTurn(state, "resetTarget")
769
+ state.idleAt = Date.now()
770
+ this.resetTurnState(state, "resetTarget")
771
+ return { sessionID, interrupted }
772
+ }
773
+
774
+ /**
775
+ * 清掉一个聊天的轮次运行时状态并落盘。
776
+ *
777
+ * 排队消息与待重试批次由调用方决定是否一起清掉。
778
+ */
779
+ private resetTurnState(state: ChatState, reason: string): void {
780
+ this.endTurn(state, reason)
781
781
  state.awaitingSend = false
782
782
  state.reminders = 0
783
783
  state.historyDone = false
784
784
  state.sessionCreated = false
785
- state.idleAt = Date.now()
786
785
  this.scheduleSave()
787
- return { sessionID, interrupted }
788
786
  }
789
787
 
790
788
  /**
@@ -830,13 +828,8 @@ export class SessionManager {
830
828
  }
831
829
  state.lastRetireAt = now
832
830
  await this.detachSession(state)
833
- this.endTurn(state, "retireSession")
834
- state.awaitingSend = false
835
- state.reminders = 0
836
831
  // 新会话是空的,历史要重新补一次。
837
- state.historyDone = false
838
- state.sessionCreated = false
839
- this.scheduleSave()
832
+ this.resetTurnState(state, "retireSession")
840
833
  this.logger.warn(`${label} 会话 ${sessionID} 连续投递失败,已退役,下一条消息会新建会话`)
841
834
  }
842
835
 
@@ -931,15 +924,7 @@ export class SessionManager {
931
924
 
932
925
  /** 记录一条机器人发出的消息,撤回工具只能操作这些消息。 */
933
926
  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)
927
+ this.track(this.outgoing, target, messageId)
943
928
  }
944
929
 
945
930
  /** 判断消息是否是机器人发出的。 */
@@ -953,8 +938,17 @@ export class SessionManager {
953
938
  * 返回该 ID 是否首次出现,用于忽略 NapCat 重连后重放的同一条消息。
954
939
  */
955
940
  rememberIncoming(target: ChatTarget, messageId: string): boolean {
941
+ return this.track(this.incoming, target, messageId)
942
+ }
943
+
944
+ /**
945
+ * 把消息 ID 记进目标的集合,超出上限时丢弃最旧的一条。
946
+ *
947
+ * @returns 该 ID 是否是首次记录。
948
+ */
949
+ private track(map: Map<string, Set<string>>, target: ChatTarget, messageId: string): boolean {
956
950
  const key = targetKey(target)
957
- const ids = this.incoming.get(key) ?? new Set<string>()
951
+ const ids = map.get(key) ?? new Set<string>()
958
952
  const isNew = !ids.has(messageId)
959
953
  ids.add(messageId)
960
954
  while (ids.size > MAX_TRACKED_MESSAGES) {
@@ -962,7 +956,7 @@ export class SessionManager {
962
956
  if (oldest === undefined) break
963
957
  ids.delete(oldest)
964
958
  }
965
- this.incoming.set(key, ids)
959
+ map.set(key, ids)
966
960
  return isNew
967
961
  }
968
962
 
@@ -1012,7 +1006,7 @@ export class SessionManager {
1012
1006
  if (state.buffer.length === 1 && bytes > MAX_BUFFER_BYTES) {
1013
1007
  this.logger.warn(`${targetLabel(state.target)} 单条消息超过缓存上限,仍保留该消息`)
1014
1008
  }
1015
- this.logger.debug(`${targetLabel(state.target)} 消息已入队(累计 ${state.buffer.length} 条)`)
1009
+ this.logger.info(`${targetLabel(state.target)} 消息已入队(累计 ${state.buffer.length} 条)`)
1016
1010
  }
1017
1011
 
1018
1012
  /** 上游会话是否仍在执行。 */
@@ -1095,7 +1089,7 @@ export class SessionManager {
1095
1089
  if (state.buffer.length === 0) return
1096
1090
  if (!force && state.sessionID && this.verifiedSessions.has(state.sessionID)) {
1097
1091
  if (await this.sessionRunning(state.sessionID)) {
1098
- this.logger.debug(
1092
+ this.logger.info(
1099
1093
  `${targetLabel(state.target)} 上游仍在执行,保留 ${state.buffer.length} 条消息`,
1100
1094
  )
1101
1095
  return
@@ -1200,7 +1194,7 @@ export class SessionManager {
1200
1194
  // restoredPositions 是启动时的快照,用来算重启期间的增量,不能被本轮的投递改写。
1201
1195
  this.scheduleSave()
1202
1196
  }
1203
- this.logger.debug(`${label} 已投递消息到会话 ${sessionID}`, {
1197
+ this.logger.info(`${label} 已投递消息到会话 ${sessionID}`, {
1204
1198
  ...(turn.traceId ? { trace_id: turn.traceId } : {}),
1205
1199
  })
1206
1200
  return true
@@ -1375,8 +1369,7 @@ export class SessionManager {
1375
1369
  this.watchdog = undefined
1376
1370
  void this.runWatchdog()
1377
1371
  }, RESUME_INTERVAL_MS)
1378
- const handle = this.watchdog as { unref?: () => void }
1379
- handle.unref?.()
1372
+ unrefTimer(this.watchdog)
1380
1373
  }
1381
1374
 
1382
1375
  /** 兜底轮询一轮:按上游会话状态把缓存的消息放出去。 */
@@ -1566,32 +1559,16 @@ export class SessionManager {
1566
1559
 
1567
1560
  /** 查找带相同目标标记的历史会话,按最近优先分页查找。 */
1568
1561
  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
1562
+ return await findSession(
1563
+ this.ctx,
1564
+ this.location.directory,
1565
+ (session) => {
1566
+ const metadata = session.metadata
1567
+ return metadata?.["qqTargetKind"] === target.kind && metadata["qqTargetId"] === target.id
1568
+ },
1569
+ this.logger,
1570
+ `查找历史会话失败 ${targetLabel(target)}`,
1571
+ )
1595
1572
  }
1596
1573
 
1597
1574
  /** 主动说话:向目标对应的会话投递一条合成消息。 */
@@ -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,7 @@
1
- import { readFile } from "node:fs/promises"
1
+ import { copyFile, 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"
4
5
  import type { Logger } from "../logger"
5
6
  import { buildSystemPrompt } from "./prompt"
6
7
 
@@ -18,21 +19,22 @@ export interface SoulOptions {
18
19
  soulPath?: string
19
20
  /** souls 目录里的文件名。 */
20
21
  soulName?: string
21
- /** 插件所在目录,用于向上查找包内 souls 目录。 */
22
+ /** 机器人工作目录:角色设定放这里,升级插件不会覆盖。 */
23
+ home: string
24
+ /** 插件所在目录,用于查找随包分发的初始角色设定。 */
22
25
  moduleDir: string
23
- /** 相对路径的基准目录。 */
24
- cwd: string
25
26
  }
26
27
 
27
- /** 从 startDir 向上逐级查找 souls/<name>。 */
28
- export function findSoulFile(
29
- startDir: string,
30
- name: string = DEFAULT_SOUL_NAME,
31
- maxDepth = 5,
32
- ): string | undefined {
28
+ /** 工作目录里的角色设定目录。 */
29
+ export function soulsDirectory(home: string): string {
30
+ return join(home, SOUL_DIR)
31
+ }
32
+
33
+ /** 从 startDir 向上逐级查找随包分发的 souls 目录。 */
34
+ export function findSoulsDirectory(startDir: string, maxDepth = 5): string | undefined {
33
35
  let current = resolve(startDir)
34
36
  for (let depth = 0; depth <= maxDepth; depth += 1) {
35
- const candidate = join(current, SOUL_DIR, name)
37
+ const candidate = join(current, SOUL_DIR)
36
38
  if (existsSync(candidate)) return candidate
37
39
  const parent = dirname(current)
38
40
  if (parent === current) break
@@ -41,28 +43,51 @@ export function findSoulFile(
41
43
  return undefined
42
44
  }
43
45
 
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
46
+ /**
47
+ * 把随包分发的角色设定补进工作目录。
48
+ *
49
+ * 只补缺失的文件:插件升级不会覆盖用户改过的设定,首次启动则拿到一份能直接用的默认档。
50
+ */
51
+ export async function seedSouls(
52
+ options: Pick<SoulOptions, "home" | "moduleDir">,
53
+ logger: Logger,
54
+ ): Promise<void> {
55
+ const target = soulsDirectory(options.home)
56
+ await mkdir(target, { recursive: true, mode: 0o700 })
57
+ const template = findSoulsDirectory(options.moduleDir)
58
+ if (!template || resolve(template) === resolve(target)) return
59
+ let entries
60
+ try {
61
+ entries = await readdir(template, { withFileTypes: true })
62
+ } catch (error) {
63
+ logger.debug("读取随包角色设定失败", error)
64
+ return
65
+ }
66
+ for (const entry of entries) {
67
+ if (!entry.isFile()) continue
68
+ const destination = join(target, entry.name)
69
+ // 已有同名文件说明用户改过或换过,别动。
70
+ if (existsSync(destination)) continue
71
+ try {
72
+ await copyFile(join(template, entry.name), destination)
73
+ logger.info(`角色设定已就位:${destination}`)
74
+ } catch (error) {
75
+ logger.warn(`复制角色设定失败:${entry.name}`, error)
76
+ }
53
77
  }
54
- return join(resolve(startDir), SOUL_DIR, name)
55
78
  }
56
79
 
57
- /** 定位角色设定文件:显式路径优先,其次 souls 目录里的指定文件。 */
80
+ /**
81
+ * 定位角色设定文件:显式路径优先,否则取工作目录 `souls/` 里的指定文件。
82
+ *
83
+ * 相对路径按工作目录解析,与项目目录无关。
84
+ */
58
85
  export function resolveSoulPath(options: SoulOptions): string {
59
86
  const name = options.soulName?.trim() || DEFAULT_SOUL_NAME
60
87
  const explicit = options.soulPath?.trim()
61
- if (!explicit) {
62
- return findSoulFile(options.moduleDir, name) ?? expectedSoulPath(options.moduleDir, name)
63
- }
88
+ if (!explicit) return join(soulsDirectory(options.home), name)
64
89
 
65
- const target = isAbsolute(explicit) ? explicit : resolve(options.cwd, explicit)
90
+ const target = isAbsolute(explicit) ? explicit : resolve(options.home, explicit)
66
91
  if (existsSync(target) && statSync(target).isDirectory()) return join(target, name)
67
92
  return target
68
93
  }
@@ -154,8 +179,7 @@ export class SoulStore {
154
179
  this.#logger.warn("角色设定监听失败,改动后需要重载插件", error)
155
180
  return
156
181
  }
157
- const handle = this.#watcher as { unref?: () => void }
158
- handle.unref?.()
182
+ unrefTimer(this.#watcher)
159
183
  }
160
184
 
161
185
  #matches(filename: string, directory: string): boolean {
@@ -169,8 +193,7 @@ export class SoulStore {
169
193
  this.#timer = undefined
170
194
  void this.reload()
171
195
  }, RELOAD_DEBOUNCE_MS)
172
- const handle = this.#timer as { unref?: () => void }
173
- handle.unref?.()
196
+ unrefTimer(this.#timer)
174
197
  }
175
198
  }
176
199
 
@@ -209,7 +232,7 @@ export class SoulLibrary {
209
232
  async at(path: string | undefined): Promise<SoulStore> {
210
233
  const explicit = path?.trim()
211
234
  if (!explicit) return this.loadDefault()
212
- const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.cwd, explicit)
235
+ const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.home, explicit)
213
236
  const cached = this.#stores.get(absolute)
214
237
  if (cached) return cached
215
238
  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
+ }
@@ -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[]