@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ import { parseTargetKey, targetLabel } from "../chat"
2
+
1
3
  /**
2
4
  * 日记的文件格式:日期键、聊天目录名与 front matter。
3
5
  *
@@ -14,6 +16,8 @@ export interface DiaryMeta {
14
16
  date: string
15
17
  /** 聊天键,形如 `group:123`。 */
16
18
  chat: string
19
+ /** 聊天可读标识,形如 `群 123`;旧文件里可能没有。 */
20
+ chat_label?: string
17
21
  /** 来源。 */
18
22
  source: DiarySource
19
23
  /** 首次写入时间(ISO 字符串)。 */
@@ -87,6 +91,17 @@ export function fallbackTitle(date: string): string {
87
91
  return `${date} 的日记`
88
92
  }
89
93
 
94
+ /**
95
+ * 聊天键的可读名称。
96
+ *
97
+ * 日记的正文、列表与发送说明都要让人一眼看出是群聊还是私聊,
98
+ * 所以统一用「群 123」「私聊 456」,解析不了时原样返回。
99
+ */
100
+ export function chatLabel(chat: string): string {
101
+ const target = parseTargetKey(chat)
102
+ return target ? targetLabel(target) : chat
103
+ }
104
+
90
105
  /**
91
106
  * 序列化一篇日记。
92
107
  *
@@ -97,6 +112,7 @@ export function serializeDiary(entry: DiaryEntry): string {
97
112
  "---",
98
113
  `date: ${entry.date}`,
99
114
  `chat: ${entry.chat}`,
115
+ `chat_label: ${chatLabel(entry.chat)}`,
100
116
  `source: ${entry.source}`,
101
117
  `created: ${entry.created}`,
102
118
  `updated: ${entry.updated}`,
@@ -147,6 +163,7 @@ export function parseDiary(content: string): ParsedDiary | undefined {
147
163
  meta: {
148
164
  date,
149
165
  chat: meta.chat ?? "",
166
+ ...(meta.chat_label ? { chat_label: meta.chat_label } : {}),
150
167
  source,
151
168
  created: meta.created ?? "",
152
169
  updated: meta.updated ?? "",
@@ -187,7 +187,7 @@ export class DiaryScheduler {
187
187
  }
188
188
  const text = toOwner
189
189
  ? `${targetLabel(chat)} ${date} 的日记已生成\n文件:${file}`
190
- : `${date} 的日记已生成`
190
+ : `${targetLabel(chat)} ${date} 的日记已生成`
191
191
  // 推送走插件自己的通道,不经过模型侧的出站检查,这里自己过一遍。
192
192
  const verdict = this.deps.sensitive.check(text)
193
193
  if (!verdict.allowed) {
@@ -10,7 +10,7 @@ import { toPlainText } from "../outbound"
10
10
  import { findSession } from "../session/find"
11
11
  import { softTruncate } from "../text"
12
12
  import type { DiaryCollector, DiaryLine } from "./collector"
13
- import { fallbackTitle } from "./format"
13
+ import { chatLabel, fallbackTitle } from "./format"
14
14
  import type { DiaryStore } from "./store"
15
15
 
16
16
  /** 插件存储里保存总结会话 ID 的键。 */
@@ -30,9 +30,10 @@ const RETRY_DELAY_MS = 10_000
30
30
  * 生成总结用的提示词。
31
31
  *
32
32
  * 素材是群友可控文本,所以先净化结构标签再包进 `<chat>`,
33
- * 并在提示词里说明标签内是素材而不是指令。
33
+ * 并在提示词里说明标签内是素材而不是指令;聊天标识写进提示词,
34
+ * 让模型知道素材来自群聊还是私聊。
34
35
  */
35
- export function buildDiaryPrompt(date: string, lines: readonly DiaryLine[]): string {
36
+ export function buildDiaryPrompt(date: string, chat: string, lines: readonly DiaryLine[]): string {
36
37
  const body = lines
37
38
  .map((line) => {
38
39
  const stamp = formatClock(line.time)
@@ -45,7 +46,7 @@ export function buildDiaryPrompt(date: string, lines: readonly DiaryLine[]): str
45
46
  })
46
47
  .join("\n")
47
48
  return [
48
- `下面是这个聊天在 ${date} 的聊天记录摘录。请把它整理成一篇当天的日记。`,
49
+ `下面是${chatLabel(chat)}在 ${date} 的聊天记录摘录。请把它整理成一篇当天的日记。`,
49
50
  "",
50
51
  "要求:",
51
52
  "1. 只依据下面的记录写,不要补充记录里没有的信息,也不要猜测。",
@@ -360,7 +361,7 @@ export class DiarySummarizer {
360
361
  return undefined
361
362
  }
362
363
  this.start()
363
- const prompt = buildDiaryPrompt(date, lines)
364
+ const prompt = buildDiaryPrompt(date, chat, lines)
364
365
  const timeoutMs = this.deps.timeoutMs ?? DIARY_SUMMARY_TIMEOUT_MS
365
366
 
366
367
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto"
2
2
  import { chmod, copyFile, mkdir, open, readFile, unlink } from "node:fs/promises"
3
- import { extname, join } from "node:path"
3
+ import { extname, join, resolve, sep } from "node:path"
4
4
  import { fileURLToPath } from "node:url"
5
5
  import type { Plugin } from "@opencode/plugin"
6
6
  import { Mutex } from "async-mutex"
@@ -123,6 +123,8 @@ export class CollectionStore {
123
123
  while (this.items.length > MAX_COLLECTED_STICKERS) {
124
124
  const oldest = this.items.shift()
125
125
  if (!oldest) break
126
+ // 只删收藏目录里的文件:存储被污染过时不能让它去删别处的文件。
127
+ if (!this.insideCollection(oldest.file)) continue
126
128
  try {
127
129
  await unlink(oldest.file)
128
130
  } catch {
@@ -131,6 +133,13 @@ export class CollectionStore {
131
133
  }
132
134
  }
133
135
 
136
+ /** 这个路径是不是收藏目录里的文件。 */
137
+ private insideCollection(file: string): boolean {
138
+ const dir = resolve(this.root, COLLECTION_DIR)
139
+ const target = resolve(file)
140
+ return target.startsWith(`${dir}${sep}`)
141
+ }
142
+
134
143
  /** 从插件存储恢复清单;读取失败下次重试。 */
135
144
  private ensureLoaded(): Promise<void> {
136
145
  if (this.loaded) return Promise.resolve()
@@ -156,6 +165,11 @@ export class CollectionStore {
156
165
  if (typeof md5 !== "string" || md5.length === 0) continue
157
166
  if (typeof description !== "string" || description.length === 0) continue
158
167
  if (typeof file !== "string" || file.length === 0) continue
168
+ // 存储里的路径必须落在收藏目录里:清单被污染时不至于指到别处。
169
+ if (!this.insideCollection(file)) {
170
+ this.logger.warn(`收藏清单里的文件路径不在收藏目录内,已忽略:${file}`)
171
+ continue
172
+ }
159
173
  items.push({
160
174
  md5,
161
175
  description,
@@ -180,6 +194,8 @@ export class CollectionStore {
180
194
  export const RECENT_IMAGE_TTL_MS = 30 * 60 * 1000
181
195
  /** 每个聊天最多保留多少张最近收到的图片。 */
182
196
  export const MAX_RECENT_IMAGES = 12
197
+ /** 同时记着多少个聊天:聊天数不封顶时这张表会一直涨。 */
198
+ export const MAX_TRACKED_CHATS = 64
183
199
 
184
200
  /** 收到的一张图片。 */
185
201
  export interface ReceivedImage {
@@ -262,11 +278,27 @@ export class RecentImages {
262
278
  }
263
279
  if (images.length === 0) return
264
280
  const key = targetKey(target)
281
+ if (!this.chats.has(key)) this.evictChat()
265
282
  const items = [...(this.chats.get(key) ?? []), ...images]
266
283
  while (items.length > MAX_RECENT_IMAGES) items.shift()
267
284
  this.chats.set(key, items)
268
285
  }
269
286
 
287
+ /** 聊天太多时丢掉最久没更新的那个。 */
288
+ private evictChat(): void {
289
+ if (this.chats.size < MAX_TRACKED_CHATS) return
290
+ let oldestKey: string | undefined
291
+ let oldestAt = Number.POSITIVE_INFINITY
292
+ for (const [key, items] of this.chats) {
293
+ const at = items[items.length - 1]?.at ?? 0
294
+ if (at < oldestAt) {
295
+ oldestAt = at
296
+ oldestKey = key
297
+ }
298
+ }
299
+ if (oldestKey !== undefined) this.chats.delete(oldestKey)
300
+ }
301
+
270
302
  /** 这个聊天最近收到的图片,只返回还在保留期内的。 */
271
303
  list(target: ChatTarget): ReceivedImage[] {
272
304
  const key = targetKey(target)
@@ -0,0 +1,82 @@
1
+ import { lstat, mkdir, open, readFile } from "node:fs/promises"
2
+ import { dirname } from "node:path"
3
+ import writeFileAtomic from "write-file-atomic"
4
+
5
+ /**
6
+ * 配置文件的原子写。
7
+ *
8
+ * 临时文件 + fsync + rename:中途失败不会留下半截文件;
9
+ * 写之前把旧内容存成 `.bak`,写坏了还能翻回去。
10
+ * `config.json`、`chat-overrides.json` 与 `tool-profiles.json` 共用这一份实现。
11
+ *
12
+ * 目标必须是普通文件:符号链接一律拒绝写。`write-file-atomic` 会把临时文件
13
+ * rename 到链接指向的真实文件上,链接本身还在,但替换的是别人的 inode;
14
+ * 链接要是被别处种下的,写出去的内容就落到了意料之外的地方。
15
+ */
16
+
17
+ /** 配置文件权限:只有本人可读写。 */
18
+ export const FILE_MODE = 0o600
19
+
20
+ /** 配置文件所在目录的权限:只有本人可进入。 */
21
+ export const DIR_MODE = 0o700
22
+
23
+ /** 目标是否是指向别处的符号链接。 */
24
+ async function isSymlink(path: string): Promise<boolean> {
25
+ const info = await lstat(path).catch(() => undefined)
26
+ return info?.isSymbolicLink() ?? false
27
+ }
28
+
29
+ /**
30
+ * 目录 fsync:把 rename 之后的目录项刷盘。
31
+ *
32
+ * 文件本身已经 fsync 过,但没有这一步,断电时目录项可能还没落盘。
33
+ * 不是所有平台都支持对目录 fsync,失败就跳过:这一步只是加固,不是唯一保障。
34
+ */
35
+ async function fsyncDirectory(path: string): Promise<void> {
36
+ let handle: Awaited<ReturnType<typeof open>> | undefined
37
+ try {
38
+ handle = await open(path, "r")
39
+ await handle.sync()
40
+ } catch {
41
+ // 平台或文件系统不支持对目录 fsync:跳过。
42
+ } finally {
43
+ await handle?.close().catch(() => {})
44
+ }
45
+ }
46
+
47
+ /**
48
+ * 原子写 JSON 文件。
49
+ *
50
+ * 目录按 `0700` 创建,文件按 `0600` 写;备份由调用方单独做。
51
+ *
52
+ * @throws 目标是符号链接时抛错,避免写穿到别处。
53
+ */
54
+ export async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
55
+ await mkdir(dirname(path), { recursive: true, mode: DIR_MODE })
56
+ if (await isSymlink(path)) {
57
+ throw new Error(`拒绝写入符号链接:${path}(请把它换成普通文件再试)`)
58
+ }
59
+ const text = `${JSON.stringify(value, null, 2)}\n`
60
+ await writeFileAtomic(path, text, { mode: FILE_MODE, fsync: true })
61
+ await fsyncDirectory(dirname(path))
62
+ }
63
+
64
+ /**
65
+ * 把当前内容存成 `.bak`。
66
+ *
67
+ * 文件不存在时跳过;`.bak` 是符号链接时拒绝写;其它错误照常抛出,
68
+ * 由调用方决定是记日志还是中断。
69
+ */
70
+ export async function backupFile(path: string): Promise<void> {
71
+ const target = `${path}.bak`
72
+ if (await isSymlink(target)) {
73
+ throw new Error(`拒绝写入符号链接:${target}(请把它换成普通文件再试)`)
74
+ }
75
+ try {
76
+ const text = await readFile(path, "utf8")
77
+ await writeFileAtomic(target, text, { mode: FILE_MODE })
78
+ } catch (error) {
79
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return
80
+ throw error
81
+ }
82
+ }
package/src/home.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { mkdir } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
- import { isAbsolute, join } from "node:path"
3
+ import { dirname, isAbsolute, join } from "node:path"
4
4
  import type { Logger } from "./logger"
5
5
 
6
6
  /**
@@ -13,6 +13,8 @@ import type { Logger } from "./logger"
13
13
  export interface BotHome {
14
14
  /** 会话统一所在的绝对路径。 */
15
15
  directory: string
16
+ /** 共享状态的跨进程写锁路径;不设就不加文件锁。 */
17
+ lockPath?: string
16
18
  }
17
19
 
18
20
  /** 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot/workspace`。 */
@@ -30,8 +32,10 @@ export function defaultHome(): string {
30
32
  export async function resolveHome(logger: Logger): Promise<BotHome> {
31
33
  const directory = defaultHome()
32
34
  await mkdir(directory, { recursive: true, mode: 0o700 })
35
+ // 写锁放在工作目录的同级:工作目录本身是会话目录,不往里面塞杂物。
36
+ const lockPath = join(dirname(directory), "state.lock")
33
37
  logger.debug(`机器人工作目录:${directory}`)
34
- return { directory }
38
+ return { directory, lockPath }
35
39
  }
36
40
 
37
41
  /** 展开路径开头的 `~` 或 `~/`,其余原样返回。 */
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@ import { ConfigStore, CONFIG_FILE_NAME } from "./config/store"
12
12
  import { DiaryCollector, isSelfSpeaker } from "./diary/collector"
13
13
  import { createDiaryRunner, diaryCommand } from "./diary/command"
14
14
  import { DiaryScheduler } from "./diary/scheduler"
15
- import { isDiaryScopeChat } from "./diary/scope"
15
+ import { diaryScopeChat, isDiaryScopeChat } from "./diary/scope"
16
16
  import { DiaryStore } from "./diary/store"
17
17
  import { DiarySummarizer } from "./diary/summary"
18
18
  import { resolveHome } from "./home"
@@ -38,7 +38,8 @@ import { SendRateLimiter } from "./rate-limit"
38
38
  import { startClaimTimer } from "./runtime/claim"
39
39
  import { RuntimeStart } from "./runtime/start"
40
40
  import { packageRoot, seedFile } from "./seed"
41
- import { collectEnvSecrets, redactUrl, secretsFromUrl, SensitiveChecker } from "./sensitive"
41
+ import { redactUrl, SensitiveChecker } from "./sensitive"
42
+ import { knownSecrets } from "./known-secrets"
42
43
  import { SessionManager } from "./session/manager"
43
44
  import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
44
45
  import { proactiveProbability } from "./session/proactive"
@@ -47,15 +48,15 @@ import { COMMANDS, handleCommand, isCommandChat } from "./commands"
47
48
  import {
48
49
  chatMuted,
49
50
  ChatOverrides,
50
- defaultChatOverridesPath,
51
51
  proactiveAllowed,
52
+ resolveChatOverridesPath,
52
53
  wakeDecision,
53
54
  type WakeReason,
54
55
  } from "./overrides"
55
56
  import { Tracer } from "./trace"
56
57
  import { Cleanup, CleanupOrder } from "./cleanup"
57
58
  import { registerAskGuard } from "./tools/ask-guard"
58
- import { defaultToolProfilesPath, roleOf, ToolPolicy } from "./tools/policy"
59
+ import { resolveToolProfilesPath, roleOf, ToolPolicy } from "./tools/policy"
59
60
  import { registerToolPolicy } from "./tools/policy-guard"
60
61
  import { registerSendGuard } from "./tools/send-guard"
61
62
  import {
@@ -99,15 +100,7 @@ function agentFromOptions(options: unknown): string | undefined {
99
100
  * 除了环境变量与 NapCat 令牌,地址查询串里挂着的 token 也要算进来,
100
101
  * 否则它会原样落进日志文件。面板令牌同样算进来:它能进日志文件就等于面板失守。
101
102
  */
102
- export function knownSecrets(config: QQBotConfig): string[] {
103
- return [
104
- ...collectEnvSecrets(process.env),
105
- config.napcat.token ?? "",
106
- // 面板令牌能进日志文件就等于面板失守,日志里一律掩码。
107
- config.panel.token ?? "",
108
- ...secretsFromUrl(config.napcat.url),
109
- ].filter((secret) => secret.length > 0)
110
- }
103
+ export { knownSecrets }
111
104
 
112
105
  const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
113
106
  event.message_type === "group"
@@ -373,6 +366,10 @@ export default Plugin.define({
373
366
  soulName: config.soulName,
374
367
  home: home.directory,
375
368
  moduleDir: packageDirectory(),
369
+ // 允许根之外的目录要显式放开;角色设定的内容会随每一轮发给模型服务商。
370
+ allowedPaths: config.soul.allowedPaths,
371
+ // 已知凭证明文:人格文件里出现就拒绝加载或掩码。
372
+ secrets: knownSecrets(config),
376
373
  }
377
374
  await seedSouls(soulOptions, logger)
378
375
  const souls = new SoulLibrary(soulOptions, logger)
@@ -428,22 +425,21 @@ export default Plugin.define({
428
425
  const noticeStore = new NoticeStore()
429
426
  // 工具配置:按聊天与角色决定模型能看到、能调用哪些工具。
430
427
  // 走默认位置时把随包的示例复制过去,占位目标得自己改成真实的群 / 私聊。
431
- const profilesPath = config.toolProfilesPath
432
- ? resolve(home.directory, config.toolProfilesPath)
433
- : defaultToolProfilesPath(home.directory)
428
+ const profilesPath = resolveToolProfilesPath(config, home.directory)
434
429
  if (!config.toolProfilesPath) {
435
430
  await seedFile(join(packageRoot, "tool-profiles.example.json"), profilesPath, logger)
436
431
  }
437
432
  const policy = new ToolPolicy(profilesPath, logger)
438
433
  panelRuntime.policy = policy
439
434
  // 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
440
- const overridesPath = config.chatOverridesPath
441
- ? resolve(home.directory, config.chatOverridesPath)
442
- : defaultChatOverridesPath(home.directory)
435
+ const overridesPath = resolveChatOverridesPath(config, home.directory)
443
436
  if (!config.chatOverridesPath) {
444
437
  await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
445
438
  }
446
- const overrides = new ChatOverrides(overridesPath, logger)
439
+ const overrides = new ChatOverrides(overridesPath, logger, {
440
+ home: home.directory,
441
+ allowedPaths: config.soul.allowedPaths,
442
+ })
447
443
  panelRuntime.overrides = overrides
448
444
  // 调用链追踪:一条入站消息拿一个 trace_id,事后能把这轮串起来。
449
445
  // 追踪文件与日志放在一起,容量与保留天数都有上限。
@@ -469,6 +465,9 @@ export default Plugin.define({
469
465
  },
470
466
  overrides,
471
467
  tracer,
468
+ // 只有独占机器的实例才能写共享状态:机器锁已经易主时,
469
+ // 旧实例写出去的状态会把接管者刚建的绑定冲掉。
470
+ () => botLock !== undefined,
472
471
  )
473
472
  cleanup.add("停止会话管理", () => manager.dispose(), CleanupOrder.manager)
474
473
  panelRuntime.manager = manager
@@ -651,15 +650,24 @@ export default Plugin.define({
651
650
  for (const name of Object.keys(event.tools)) delete event.tools[name]
652
651
  return
653
652
  }
654
- // 日记总结会话的输入是群友可控的聊天记录,同样不带任何工具。
653
+ // 日记总结会话的输入是群友可控的聊天记录,同样不带任何工具;
654
+ // 但它仍是一轮正常对话,先注入角色设定,日记才有人格。
655
655
  if (await diarySummarizer.isSummarySession(event.sessionID)) {
656
+ // 人格取日记范围那条私聊(owner 私聊)上的覆盖,没有覆盖就用默认档。
657
+ const scope = diaryScopeChat(config)
658
+ const override = scope ? await overrides.for(scope) : undefined
659
+ const soul = await souls.at(override?.soulPath, override?.soulName)
660
+ // 只注入角色设定正文:`soul.prompt` 还带着「必须调用 qq_send_message」
661
+ // 的 QQ 守则,而总结会话没有任何工具,带上会让模型无所适从。
662
+ const persona = soul.text.trim()
663
+ if (persona) event.system.push({ type: "text", text: persona })
656
664
  for (const name of Object.keys(event.tools)) delete event.tools[name]
657
665
  }
658
666
  return
659
667
  }
660
- // 角色设定可以按聊天覆盖:先看覆盖里写的路径,没有就用默认档。
668
+ // 角色设定可以按聊天覆盖:先看覆盖里写的 soulPath / soulName,没有就用默认档。
661
669
  const override = await overrides.for(target)
662
- const soul = await souls.at(override.soul)
670
+ const soul = await souls.at(override.soulPath, override.soulName)
663
671
  event.system.push({ type: "text", text: soul.prompt })
664
672
  event.system.push({ type: "text", text: `当前时间:${currentTimeText()}` })
665
673
  const active = manager.activeTurn(event.sessionID)
package/src/keepalive.ts CHANGED
@@ -10,6 +10,20 @@ export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
10
10
  export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
11
11
  /** 保活会话标题。 */
12
12
  export const KEEP_ALIVE_TITLE = "QQ 保活"
13
+ /** 上游表示“会话不存在”的错误名。 */
14
+ const SESSION_NOT_FOUND = "Session.NotFoundError"
15
+
16
+ /**
17
+ * 判断错误是不是上游的“会话不存在”。
18
+ *
19
+ * 上游的 Session.NotFoundError 没有 message,只有 name 和 _tag,
20
+ * 所以只能靠名字判断,不然日志里只剩一段没有内容的栈。
21
+ */
22
+ function isSessionNotFound(error: unknown): boolean {
23
+ if (typeof error !== "object" || error === null) return false
24
+ const candidate = error as { name?: unknown; _tag?: unknown }
25
+ return candidate.name === SESSION_NOT_FOUND || candidate._tag === SESSION_NOT_FOUND
26
+ }
13
27
 
14
28
  /**
15
29
  * 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
@@ -84,7 +98,13 @@ export class KeepAlive {
84
98
  const info = await this.ctx.session.get({ sessionID })
85
99
  metadata = info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true }
86
100
  } catch (error) {
87
- // 会话已经被删除:丢掉缓存,下一次心跳重建一个。
101
+ if (isSessionNotFound(error)) {
102
+ // 会话已经被删掉了:当场重建,不等下一个心跳。
103
+ this.logger.warn(`保活会话 ${sessionID} 已不存在,正在重建`)
104
+ await this.rebuild(sessionID)
105
+ return
106
+ }
107
+ // 会话暂时读不出来:丢掉缓存,下一次心跳重建一个。
88
108
  this.logger.warn("保活会话已失效,将重建", error)
89
109
  this.sessionID = undefined
90
110
  return
@@ -94,10 +114,38 @@ export class KeepAlive {
94
114
  await this.ctx.session.update({ sessionID, metadata })
95
115
  this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
96
116
  } catch (error) {
117
+ if (isSessionNotFound(error)) {
118
+ this.logger.warn(`保活会话 ${sessionID} 已不存在,正在重建`)
119
+ await this.rebuild(sessionID)
120
+ return
121
+ }
97
122
  this.logger.warn("保活心跳失败", error)
98
123
  }
99
124
  }
100
125
 
126
+ /**
127
+ * 保活会话已经不存在时的重建。
128
+ *
129
+ * 不当场重建的话要等到下一个心跳才补上,这段时间里插件可能被 OpenCode 当成空闲卸载,
130
+ * 保活也就失效了,所以当场重建并刷新一次元数据。
131
+ */
132
+ private async rebuild(staleSessionID: string): Promise<void> {
133
+ this.sessionID = undefined
134
+ await this.clearStoredSession(staleSessionID)
135
+ try {
136
+ const sessionID = await this.resolveSession()
137
+ if (this.stopped) return
138
+ const info = await this.ctx.session.get({ sessionID })
139
+ await this.ctx.session.update({
140
+ sessionID,
141
+ metadata: info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true },
142
+ })
143
+ this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
144
+ } catch (error) {
145
+ this.logger.warn("重建保活会话失败", error)
146
+ }
147
+ }
148
+
101
149
  /** 取得(必要时创建)保活会话;并发调用串行执行,避免重复建会话。 */
102
150
  private async ensureSession(): Promise<string> {
103
151
  if (this.sessionID) return this.sessionID
@@ -143,6 +191,10 @@ export class KeepAlive {
143
191
  try {
144
192
  await this.ctx.session.update({ sessionID, archived: true })
145
193
  } catch (error) {
194
+ if (isSessionNotFound(error)) {
195
+ this.logger.debug(`保活会话 ${sessionID} 已不存在,跳过归档`)
196
+ return
197
+ }
146
198
  this.logger.debug("归档保活会话失败", error)
147
199
  return
148
200
  }
@@ -160,8 +212,9 @@ export class KeepAlive {
160
212
 
161
213
  /** 读取上次保存的保活会话;会话已经不存在或属于别的目录时返回 undefined。 */
162
214
  private async readStoredSession(): Promise<string | undefined> {
215
+ let stored: unknown
163
216
  try {
164
- const stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
217
+ stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
165
218
  if (typeof stored !== "string" || stored.length === 0) return undefined
166
219
  const info = await this.ctx.session.get({ sessionID: stored })
167
220
  // 插件存储是机器级共享的,别的目录留下的会话不能拿来用。
@@ -171,6 +224,11 @@ export class KeepAlive {
171
224
  }
172
225
  return stored
173
226
  } catch (error) {
227
+ if (isSessionNotFound(error)) {
228
+ this.logger.debug(`存储里的保活会话 ${String(stored)} 已不存在,将新建会话`)
229
+ await this.clearStoredSession(String(stored))
230
+ return undefined
231
+ }
174
232
  this.logger.debug("读取保活会话失败,将新建会话", error)
175
233
  return undefined
176
234
  }
@@ -0,0 +1,20 @@
1
+ import type { QQBotConfig } from "./config"
2
+ import { collectEnvSecrets, secretsFromUrl } from "./sensitive"
3
+
4
+ /**
5
+ * 已知凭证明文:日志逐行打码与出站拦截都靠它。
6
+ *
7
+ * 除了环境变量与 NapCat 令牌,地址查询串里挂着的 token 也要算进来,
8
+ * 否则它会原样落进日志文件。面板令牌同样算进来:它能进日志文件就等于面板失守。
9
+ *
10
+ * 单独成模块是为了让面板也能用:面板不需要把整个插件入口拉进来。
11
+ */
12
+ export function knownSecrets(config: QQBotConfig): string[] {
13
+ return [
14
+ ...collectEnvSecrets(process.env),
15
+ config.napcat.token ?? "",
16
+ // 面板令牌能进日志文件就等于面板失守,日志里一律掩码。
17
+ config.panel.token ?? "",
18
+ ...secretsFromUrl(config.napcat.url),
19
+ ].filter((secret) => secret.length > 0)
20
+ }
package/src/logger.ts CHANGED
@@ -181,7 +181,8 @@ function normalizeValue(value: unknown, depth: number): unknown {
181
181
  if (value instanceof Error) {
182
182
  return {
183
183
  name: value.name,
184
- message: value.message,
184
+ // 有些上游错误(例如 opencode 的 Session.NotFoundError)没有 message,只能用名字顶上。
185
+ message: value.message || value.name,
185
186
  stack: value.stack ? value.stack.replace(/\s*\n\s*/g, " ") : undefined,
186
187
  }
187
188
  }