@cmach_socket/opencode-qq-bot 0.3.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,21 +1,36 @@
1
1
  import { Plugin } from "@opencode/plugin"
2
2
  import type { GroupMessageEvent, MessageEvent } from "@naplink/naplink"
3
3
  import { Mutex } from "async-mutex"
4
+ import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
4
5
  import { type ChatTarget, configuredTargets, isTargetEnabled, targetKey, targetLabel } from "./chat"
5
6
  import { resolveConfig, type QQBotConfig } from "./config"
7
+ import { resolveHome } from "./home"
6
8
  import { claimInstance } from "./instance"
7
- import { createLogger } from "./logger"
9
+ import { KeepAlive } from "./keepalive"
10
+ import { createLogger, closeLogger, flushLogger } from "./logger"
11
+ import { defaultMediaDir, OutboundMedia } from "./media-path"
12
+ import { formatModelMessage } from "./model-view"
8
13
  import { QQClient } from "./naplink/client"
14
+ import { createHistoryProvider } from "./naplink/history"
9
15
  import { createMediaStore } from "./naplink/media"
10
16
  import { mentionsUser, renderMessage, resolveUserName, shouldProcess } from "./naplink/render"
17
+ import { SendRateLimiter } from "./rate-limit"
18
+ import { collectEnvSecrets, SensitiveChecker } from "./sensitive"
11
19
  import { SessionManager } from "./session/manager"
12
20
  import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
13
21
  import { proactiveTickProbability } from "./session/proactive"
14
22
  import { packageDirectory, SoulStore } from "./session/soul"
15
23
  import { registerAskGuard } from "./tools/ask-guard"
24
+ import { registerSendGuard } from "./tools/send-guard"
16
25
  import { registerTools } from "./tools/qq"
26
+ import { registerEmojiCommand } from "./emoji/command"
27
+ import { FavoriteStore } from "./emoji/favorites"
28
+ import { FavoriteIndex } from "./emoji/favorite-index"
29
+ import { EmojiLabeler } from "./emoji/label"
17
30
 
18
31
  const RETRY_DELAY_MS = 1000
32
+ /** 机器人连接被别的实例占用时,多久重试一次接管。 */
33
+ const CLAIM_RETRY_MS = 30_000
19
34
 
20
35
  function delay(ms: number): Promise<void> {
21
36
  return new Promise((resolve) => setTimeout(resolve, ms))
@@ -24,24 +39,54 @@ function delay(ms: number): Promise<void> {
24
39
  export default Plugin.define({
25
40
  id: "opencode-qq-bot",
26
41
  async setup(ctx) {
27
- const logger = createLogger("[qq-bot]")
42
+ // 配置还没解析出来,先用一个只写控制台的日志器兜底,解析完再换成正式日志器。
43
+ const bootstrap = createLogger("[qq-bot]", { file: false })
28
44
  let config: QQBotConfig
45
+ const warnings: string[] = []
29
46
  try {
30
- config = resolveConfig(ctx.options, process.env, (message) => logger.warn(message))
47
+ config = resolveConfig(ctx.options, process.env, (message) => warnings.push(message))
31
48
  } catch (error) {
32
- logger.error(error instanceof Error ? error.message : String(error))
49
+ for (const warning of warnings) bootstrap.warn(warning)
50
+ bootstrap.error(error instanceof Error ? error.message : String(error))
51
+ await closeLogger(bootstrap)
33
52
  return
34
53
  }
35
54
 
55
+ const logger = createLogger("[qq-bot]", {
56
+ level: config.log.level,
57
+ dir: config.log.dir,
58
+ maxSize: config.log.maxSize,
59
+ maxFiles: config.log.maxFiles,
60
+ knownSecrets: [...collectEnvSecrets(process.env), config.napcat.token ?? ""].filter(
61
+ (secret) => secret.length > 0,
62
+ ),
63
+ })
64
+ for (const warning of warnings) logger.warn(warning)
65
+ // 正式日志器已经接管,兜底日志器只写控制台,用完就关掉。
66
+ await closeLogger(bootstrap)
67
+
36
68
  if (config.groups.length === 0 && config.users.length === 0) {
37
69
  logger.warn(
38
70
  "未配置目标群号或私聊 QQ 号,插件不会响应任何消息(请设置 groups/users 或 QQ_TARGET_GROUPS/QQ_TARGET_USERS)",
39
71
  )
40
72
  }
41
73
 
42
- // OpenCode 重新加载插件时未必调用旧的清理函数,接管同一连接的单例并主动卸载旧实例。
43
- const { previous, lease } = claimInstance(`${ctx.location.directory}\n${config.napcat.url}`)
74
+ // 机器人固定服务的工作目录:配置优先,否则固定使用 XDG 数据目录下的工作区。
75
+ const home = await resolveHome(config.home, logger)
76
+
77
+ // 同一台机器只允许一个插件实例:OpenCode 可能为不同项目目录加载插件,
78
+ // 新实例接管旧实例并让旧实例整体卸载,避免多条 NapCat 连接与重复投递。
79
+ const { previous, occupied, lease } = claimInstance(
80
+ home.directory,
81
+ `${ctx.location.directory}\n${config.napcat.url}`,
82
+ )
83
+ if (occupied) {
84
+ logger.warn("本机机器人已绑定到其它工作目录,本实例不会运行", `工作目录:${occupied}`)
85
+ await closeLogger(logger)
86
+ return
87
+ }
44
88
  if (previous?.dispose) {
89
+ logger.info("接管已有的插件实例并卸载它", previous.label)
45
90
  try {
46
91
  await previous.dispose()
47
92
  } catch (error) {
@@ -49,6 +94,10 @@ export default Plugin.define({
49
94
  }
50
95
  }
51
96
 
97
+ // 机器级锁:抢不到就保持安静,等持有者退出后再接管。
98
+ let botLock: BotLock | undefined
99
+ let disposed = false
100
+
52
101
  // 角色设定:读取生效文件并监听改动,改完下一轮即生效。
53
102
  const soul = new SoulStore(
54
103
  {
@@ -62,9 +111,29 @@ export default Plugin.define({
62
111
  await soul.load()
63
112
 
64
113
  const client = new QQClient(config.napcat, logger)
65
- const manager = new SessionManager(ctx, config, logger)
114
+ const mediaDir = defaultMediaDir()
115
+ const media = await createMediaStore(logger, { root: mediaDir })
116
+ // 出站媒体把关:只允许工作目录、媒体目录和配置里放开的目录,远端地址只允许公网。
117
+ const outbound = new OutboundMedia({
118
+ workspace: home.directory,
119
+ allowedDirs: [home.directory, mediaDir, ...config.media.allowedDirs],
120
+ })
121
+ const nameCache = new Map<string, { name: string; expires: number }>()
122
+ const history = createHistoryProvider({ api: client.api, logger, media, names: nameCache })
123
+ // 出站限流:模型驱动的发送与插件自己发的消息共用一个限流器。
124
+ const limiter = new SendRateLimiter(config.rateLimit)
125
+ // 出站敏感信息拦截:环境变量里的凭证与 NapCat 令牌都当作已知凭证。
126
+ const sensitive = new SensitiveChecker({
127
+ enabled: config.sensitive.enabled,
128
+ knownSecrets: [...collectEnvSecrets(process.env), config.napcat.token ?? ""].filter(
129
+ (secret) => secret.length > 0,
130
+ ),
131
+ })
132
+ const manager = new SessionManager(ctx, config, logger, home, history)
66
133
  await manager.load()
67
- const media = await createMediaStore(logger)
134
+ // 保活心跳:OpenCode 长时间没有会话活动时会卸载 location,插件随之被卸载。
135
+ const keepAlive = new KeepAlive(ctx, config, logger)
136
+ keepAlive.start()
68
137
  const mediaCleanup = setInterval(
69
138
  () => {
70
139
  void media.cleanup()
@@ -73,10 +142,37 @@ export default Plugin.define({
73
142
  )
74
143
  const mediaHandle = mediaCleanup as { unref?: () => void }
75
144
  mediaHandle.unref?.()
76
- const toolRegistration = await registerTools({ ctx, config, logger, manager, client })
145
+ // 收藏表情:标签只存在 NapCat 侧,插件不保存副本;编号由插件自己维护。
146
+ const favorites = new FavoriteStore((method, params) => client.callApi(method, params), logger)
147
+ const favoriteIndex = new FavoriteIndex(ctx.storage, logger)
148
+ const labeler = new EmojiLabeler({ ctx, config, home, logger, media, favorites })
149
+ const toolRegistration = await registerTools({
150
+ ctx,
151
+ config,
152
+ logger,
153
+ manager,
154
+ client,
155
+ favorites,
156
+ favoriteIndex,
157
+ limiter,
158
+ sensitive,
159
+ outbound,
160
+ })
161
+ const emojiCommandRegistration = await registerEmojiCommand({
162
+ ctx,
163
+ config,
164
+ logger,
165
+ manager,
166
+ client,
167
+ favorites,
168
+ favoriteIndex,
169
+ labeler,
170
+ limiter,
171
+ })
77
172
  // QQ 会话里禁止模型调用内置 question 工具,改用 qq_send_message 询问用户。
78
173
  const askGuardRegistration = await registerAskGuard({ ctx, logger, manager })
79
- const nameCache = new Map<string, { name: string; expires: number }>()
174
+ // 禁止连续调用发送工具,避免同一条消息被重复发送。
175
+ const sendGuardRegistration = await registerSendGuard({ ctx, logger, manager })
80
176
 
81
177
  // 系统提示:角色设定、当前时间、本轮是否必须回复。
82
178
  const contextRegistration = await ctx.session.hook("context", (event) => {
@@ -151,7 +247,6 @@ export default Plugin.define({
151
247
  if (!isTargetEnabled(config, target)) return
152
248
  if (!shouldProcess(event.message, selfId)) return
153
249
 
154
- await client.hydrate(event.message)
155
250
  const renderCtx = {
156
251
  api: client.api,
157
252
  target,
@@ -167,9 +262,15 @@ export default Plugin.define({
167
262
  const atMe = target.kind === "private" || mentionsUser(event.message, selfId)
168
263
 
169
264
  await manager.enqueue(target, {
170
- text: `${userName}: ${rendered.text}`,
265
+ text: formatModelMessage({
266
+ sender: userName,
267
+ userId: String(event.user_id),
268
+ text: rendered.text,
269
+ time: event.time,
270
+ }),
171
271
  files: rendered.files,
172
272
  atMe,
273
+ source: { id: String(event.message_id), time: event.time },
173
274
  })
174
275
  } catch (error) {
175
276
  logger.error(`处理 ${targetLabel(target)} 消息失败`, error)
@@ -187,6 +288,8 @@ export default Plugin.define({
187
288
  return mutex
188
289
  }
189
290
  const scheduleMessage = (event: MessageEvent) => {
291
+ // 没有占用机器人连接时不消费消息,避免和别的实例重复投递。
292
+ if (!botLock) return
190
293
  const target = eventTarget(event)
191
294
  if (!isTargetEnabled(config, target)) return
192
295
  const selfId = String(event.self_id ?? client.selfId ?? "")
@@ -203,11 +306,69 @@ export default Plugin.define({
203
306
  .catch((error: unknown) => logger.error(`处理 ${targetLabel(target)} 消息失败`, error))
204
307
  }
205
308
 
206
- // 先注册监听再连接:NapCat 连接期间推送的消息也会被收到。
207
- client.onGroupMessage(scheduleMessage)
208
- client.onPrivateMessage(scheduleMessage)
309
+ let subscribed = false
310
+ const startConsuming = async () => {
311
+ // 先注册监听再连接:NapCat 连接期间推送的消息也会被收到。
312
+ if (!subscribed) {
313
+ subscribed = true
314
+ client.onGroupMessage(scheduleMessage)
315
+ client.onPrivateMessage(scheduleMessage)
316
+ }
317
+ await client.connectSafe()
318
+ }
209
319
 
210
- await client.connectSafe()
320
+ /**
321
+ * 抢占机器级锁。
322
+ *
323
+ * 拿到锁才能消费消息流;锁被占用说明别的实例已经在消费,这里保持安静。
324
+ */
325
+ const claimBot = async (): Promise<boolean> => {
326
+ if (botLock) return true
327
+ if (disposed) return false
328
+ let lock: BotLock | undefined
329
+ try {
330
+ lock = await acquireBotLock({
331
+ onCompromised: (error) => {
332
+ // 心跳失效意味着锁已不再独占,立刻停止投递,等重新抢到锁再消费。
333
+ logger.error("机器人连接锁失效,停止接收 QQ 消息", error)
334
+ botLock = undefined
335
+ },
336
+ })
337
+ } catch (error) {
338
+ // 锁目录异常(tmpdir 不可写、权限不足)不能拖垮插件,退化成不消费消息,稍后重试。
339
+ logger.error("获取机器人连接锁失败,稍后重试", error)
340
+ return false
341
+ }
342
+ if (!lock) return false
343
+ if (disposed) {
344
+ // 卸载与抢锁并发:立刻交回锁,不要在卸载之后重新连接 NapCat。
345
+ await lock.release().catch((error: unknown) => logger.error("释放机器人连接锁失败", error))
346
+ return false
347
+ }
348
+ botLock = lock
349
+ logger.info("已占用机器级锁", botLockPath())
350
+ await startConsuming()
351
+ return true
352
+ }
353
+
354
+ const claimed = await claimBot().catch((error: unknown) => {
355
+ logger.error("抢占机器人连接失败,稍后重试", error)
356
+ return false
357
+ })
358
+ if (!claimed) {
359
+ logger.warn(
360
+ "同一台机器上已有另一个实例在运行,本实例不会接收 QQ 消息",
361
+ `锁目录:${botLockPath()}`,
362
+ )
363
+ }
364
+
365
+ // 持有者退出后接管机器人,避免消息流一直无人消费。
366
+ const claimTimer = setInterval(() => {
367
+ if (botLock) return
368
+ void claimBot().catch((error: unknown) => logger.error("接管机器人连接失败", error))
369
+ }, CLAIM_RETRY_MS)
370
+ const claimHandle = claimTimer as { unref?: () => void }
371
+ claimHandle.unref?.()
211
372
 
212
373
  // 主动说话心跳。
213
374
  let timer: ReturnType<typeof setInterval> | undefined
@@ -217,6 +378,8 @@ export default Plugin.define({
217
378
  if (tickMutex.isLocked()) return
218
379
  await tickMutex.runExclusive(async () => {
219
380
  for (const target of configuredTargets(config)) {
381
+ // 没有机器人连接就发不出去,不主动发起话题。
382
+ if (!botLock) continue
220
383
  const probability = proactiveTickProbability(
221
384
  config.proactive,
222
385
  manager.silenceSeconds(target),
@@ -241,22 +404,41 @@ export default Plugin.define({
241
404
  agent: config.agent ?? "(默认)",
242
405
  })
243
406
 
244
- let disposed = false
245
407
  const dispose = async () => {
246
408
  if (disposed) return
247
409
  disposed = true
248
410
  if (timer) clearInterval(timer)
411
+ clearInterval(claimTimer)
249
412
  clearInterval(mediaCleanup)
413
+ await keepAlive.dispose()
250
414
  idleAbort.abort()
415
+ manager.dispose()
251
416
  await manager.flush()
252
417
  soul.dispose()
253
418
  await toolRegistration.dispose()
419
+ await emojiCommandRegistration.dispose()
420
+ await labeler.dispose()
254
421
  await askGuardRegistration.dispose()
422
+ await sendGuardRegistration.dispose()
255
423
  await contextRegistration.dispose()
256
424
  await idleRegistration.dispose()
257
425
  client.dispose()
426
+ // 先断开 NapCat 再释放机器级锁,避免新实例接管时出现两条连接。
427
+ try {
428
+ await botLock?.release()
429
+ } catch (error) {
430
+ // 释放失败也要继续释放实例租约,否则旧实例的租约会一直占着槽位。
431
+ logger.error("释放机器人连接锁失败", error)
432
+ }
433
+ botLock = undefined
258
434
  lease.release()
259
- logger.info("插件已卸载")
435
+ logger.info(
436
+ "插件已卸载",
437
+ "若是被 OpenCode 卸载(长时间没有会话活动),可在 opencode.json 里设置 experimental.location_idle_timeout: false",
438
+ )
439
+ // 关闭日志器,等文件传输把最后的日志写完,避免丢日志。
440
+ await flushLogger(logger)
441
+ await closeLogger(logger)
260
442
  }
261
443
  lease.setDispose(dispose)
262
444
  return dispose
package/src/instance.ts CHANGED
@@ -1,14 +1,18 @@
1
1
  /**
2
- * Cross-reload singleton registry.
2
+ * 进程内单实例注册表。
3
3
  *
4
- * OpenCode may load a plugin again without invoking the previous instance's
5
- * cleanup, which would leave duplicate WebSocket connections and duplicate
6
- * message handlers behind. The registry lives on globalThis so it survives
7
- * module reloads within the same server process.
4
+ * 同一台机器上只允许一个插件实例:OpenCode 可能为不同项目目录加载插件,
5
+ * 新实例会接管旧实例并让旧实例整体卸载,避免同时存在多条 NapCat 连接
6
+ * 与重复的消息处理。注册表挂在 globalThis 上,模块重载后依然有效。
7
+ *
8
+ * 槽位绑定到机器人固定的工作目录:只有同一目录的实例才能互相接管,
9
+ * 否则会话上下文会落在不同项目里。
8
10
  */
9
11
 
10
12
  export interface PluginInstance {
11
13
  dispose?: () => Promise<void>
14
+ /** 实例来源描述,仅用于日志。 */
15
+ label?: string
12
16
  }
13
17
 
14
18
  export interface InstanceLease {
@@ -18,8 +22,16 @@ export interface InstanceLease {
18
22
  release(): void
19
23
  }
20
24
 
25
+ export interface InstanceClaim {
26
+ /** 同一工作目录下被接管的旧实例。 */
27
+ previous?: PluginInstance
28
+ /** 槽位已被其它工作目录占用时给出该目录,调用方应停止运行。 */
29
+ occupied?: string
30
+ lease: InstanceLease
31
+ }
32
+
21
33
  interface Host {
22
- active?: { key: string; instance: PluginInstance }
34
+ active?: { directory: string; instance: PluginInstance }
23
35
  }
24
36
 
25
37
  const HOST_KEY = "__opencodeQQBotHost__"
@@ -34,20 +46,21 @@ function host(): Host {
34
46
  }
35
47
 
36
48
  /**
37
- * Claims the singleton slot for `key` and returns any previous instance with
38
- * the same key so the caller can dispose it. Instances with different keys
39
- * (for example another project) are left untouched.
49
+ * 占用进程内唯一的实例槽位。
50
+ *
51
+ * @param directory 机器人固定服务的工作目录。
52
+ * @param label 实例来源描述,通常是项目目录与 NapCat 地址,仅用于日志。
40
53
  */
41
- export function claimInstance(key: string): {
42
- previous: PluginInstance | undefined
43
- lease: InstanceLease
44
- } {
54
+ export function claimInstance(directory: string, label: string): InstanceClaim {
45
55
  const state = host()
46
- const previous = state.active?.key === key ? state.active.instance : undefined
47
- const instance: PluginInstance = {}
48
- state.active = { key, instance }
56
+ const active = state.active
57
+ if (active && active.directory !== directory) {
58
+ return { occupied: active.directory, lease: { setDispose() {}, release() {} } }
59
+ }
60
+ const instance: PluginInstance = { label }
61
+ state.active = { directory, instance }
49
62
  return {
50
- previous,
63
+ previous: active?.instance,
51
64
  lease: {
52
65
  setDispose(dispose) {
53
66
  instance.dispose = dispose
@@ -0,0 +1,222 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import type { QQBotConfig } from "./config"
3
+ import type { Logger } from "./logger"
4
+
5
+ /** 插件存储里保存保活会话 ID 的键。 */
6
+ export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
7
+ /** 会话标记:用来找回已经建好的保活会话。 */
8
+ export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
9
+ /** 保活会话标题。 */
10
+ export const KEEP_ALIVE_TITLE = "QQ 保活"
11
+
12
+ type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
13
+
14
+ /**
15
+ * 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
16
+ *
17
+ * OpenCode 按 location 统计会话活动,默认空闲 60 分钟后卸载该 location 的服务,
18
+ * 插件随之被卸载,NapCat 连接断开后机器人就不再响应。
19
+ * 写回一次会话元数据会发布 durable 的 `session.metadata.updated` 事件,
20
+ * 事件带着插件所在 location,于是该 location 的空闲计时被重置。
21
+ */
22
+ export class KeepAlive {
23
+ private timer: ReturnType<typeof setInterval> | undefined
24
+ private sessionID: string | undefined
25
+ private creating: Promise<string> | undefined
26
+ private stopped = false
27
+
28
+ constructor(
29
+ private readonly ctx: Plugin.Context,
30
+ private readonly config: QQBotConfig,
31
+ private readonly logger: Logger,
32
+ ) {}
33
+
34
+ /** 启动保活心跳。 */
35
+ start(): void {
36
+ if (this.timer || !this.config.keepAlive.enabled) return
37
+ void this.ping()
38
+ this.timer = setInterval(() => {
39
+ void this.ping()
40
+ }, this.config.keepAlive.seconds * 1000)
41
+ const handle = this.timer as { unref?: () => void }
42
+ handle.unref?.()
43
+ }
44
+
45
+ /**
46
+ * 停止保活心跳,并删掉保活会话。
47
+ *
48
+ * 会话只服务于保活,插件卸载后留着它只会在项目目录里留下垃圾,
49
+ * 所以卸载时顺手删掉,存储里的记录也一起清掉。
50
+ */
51
+ async dispose(): Promise<void> {
52
+ this.stopped = true
53
+ if (this.timer) clearInterval(this.timer)
54
+ this.timer = undefined
55
+ const sessionID = this.sessionID
56
+ this.sessionID = undefined
57
+ if (!sessionID) return
58
+ try {
59
+ await this.ctx.session.remove({ sessionID })
60
+ this.logger.info(`保活会话 ${sessionID} 已删除`)
61
+ } catch (error) {
62
+ this.logger.warn("删除保活会话失败", error)
63
+ }
64
+ await this.clearStoredSession(sessionID)
65
+ }
66
+
67
+ /**
68
+ * 写回一次会话元数据,刷新 location 的空闲计时。
69
+ *
70
+ * 元数据是整体替换的,所以先读出当前值再原样写回。
71
+ */
72
+ async ping(): Promise<void> {
73
+ if (this.stopped) return
74
+ let sessionID: string
75
+ try {
76
+ sessionID = await this.ensureSession()
77
+ } catch (error) {
78
+ this.logger.warn("保活心跳失败:取不到保活会话", error)
79
+ return
80
+ }
81
+ if (this.stopped) return
82
+
83
+ let metadata: NonNullable<Parameters<Plugin.Context["session"]["update"]>[0]["metadata"]>
84
+ try {
85
+ const info = await this.ctx.session.get({ sessionID })
86
+ metadata = info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true }
87
+ } catch (error) {
88
+ // 会话已经被删除:丢掉缓存,下一次心跳重建一个。
89
+ this.logger.warn("保活会话已失效,将重建", error)
90
+ this.sessionID = undefined
91
+ return
92
+ }
93
+
94
+ try {
95
+ await this.ctx.session.update({ sessionID, metadata })
96
+ this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
97
+ } catch (error) {
98
+ this.logger.warn("保活心跳失败", error)
99
+ }
100
+ }
101
+
102
+ /** 取得(必要时创建)保活会话;并发调用串行执行,避免重复建会话。 */
103
+ private async ensureSession(): Promise<string> {
104
+ if (this.sessionID) return this.sessionID
105
+ this.creating ??= this.resolveSession().finally(() => {
106
+ this.creating = undefined
107
+ })
108
+ return this.creating
109
+ }
110
+
111
+ private async resolveSession(): Promise<string> {
112
+ const stored = await this.readStoredSession()
113
+ if (stored) {
114
+ this.sessionID = stored
115
+ await this.ensureArchived(stored)
116
+ return stored
117
+ }
118
+ const found = await this.findKeepAliveSession()
119
+ if (found) {
120
+ this.sessionID = found
121
+ await this.writeStoredSession(found)
122
+ await this.ensureArchived(found)
123
+ this.logger.info(`复用保活会话 ${found}`)
124
+ return found
125
+ }
126
+ const created = await this.ctx.session.create({
127
+ title: KEEP_ALIVE_TITLE,
128
+ metadata: { [KEEP_ALIVE_SESSION_MARKER]: true },
129
+ })
130
+ this.sessionID = created.id
131
+ await this.writeStoredSession(created.id)
132
+ await this.ensureArchived(created.id)
133
+ this.logger.info(`新建保活会话 ${created.id}`)
134
+ return created.id
135
+ }
136
+
137
+ /**
138
+ * 归档保活会话,让它不出现在会话列表里。
139
+ *
140
+ * 上游的插件接口目前只处理 title/metadata/permissions,archived 会被忽略,
141
+ * 所以调用之后要再读一次,确认到底有没有归档成功。
142
+ */
143
+ private async ensureArchived(sessionID: string): Promise<void> {
144
+ try {
145
+ await this.ctx.session.update({ sessionID, archived: true })
146
+ } catch (error) {
147
+ this.logger.debug("归档保活会话失败", error)
148
+ return
149
+ }
150
+ try {
151
+ const info = await this.ctx.session.get({ sessionID })
152
+ if (info?.time?.archived !== undefined) {
153
+ this.logger.info(`保活会话 ${sessionID} 已归档`)
154
+ } else {
155
+ this.logger.info(`上游未支持归档保活会话 ${sessionID},它会显示在会话列表里`)
156
+ }
157
+ } catch (error) {
158
+ this.logger.debug("确认保活会话归档状态失败", error)
159
+ }
160
+ }
161
+
162
+ /** 读取上次保存的保活会话;会话已经不存在或属于别的目录时返回 undefined。 */
163
+ private async readStoredSession(): Promise<string | undefined> {
164
+ try {
165
+ const stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
166
+ if (typeof stored !== "string" || stored.length === 0) return undefined
167
+ const info = await this.ctx.session.get({ sessionID: stored })
168
+ // 插件存储是机器级共享的,别的目录留下的会话不能拿来用。
169
+ if (info?.location?.directory !== this.ctx.location.directory) {
170
+ this.logger.debug(`存储里的保活会话 ${stored} 不在当前目录,忽略`)
171
+ return undefined
172
+ }
173
+ return stored
174
+ } catch (error) {
175
+ this.logger.debug("读取保活会话失败,将新建会话", error)
176
+ return undefined
177
+ }
178
+ }
179
+
180
+ /** 查找带保活标记的历史会话。 */
181
+ private async findKeepAliveSession(): Promise<string | undefined> {
182
+ let cursor: SessionListCursor | undefined
183
+ try {
184
+ for (let page = 0; page < 5; page += 1) {
185
+ const result = await this.ctx.session.list({
186
+ directory: this.ctx.location.directory,
187
+ limit: 100,
188
+ order: "desc",
189
+ ...(cursor ? { cursor } : {}),
190
+ })
191
+ const hit = result.data.find(
192
+ (session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
193
+ )
194
+ if (hit) return hit.id
195
+ cursor = result.cursor.next ?? undefined
196
+ if (!cursor) break
197
+ }
198
+ } catch (error) {
199
+ this.logger.warn("查找保活会话失败", error)
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ private async writeStoredSession(sessionID: string): Promise<void> {
205
+ try {
206
+ await this.ctx.storage.set(KEEP_ALIVE_SESSION_KEY, sessionID)
207
+ } catch (error) {
208
+ this.logger.warn("保存保活会话失败", error)
209
+ }
210
+ }
211
+
212
+ /** 清掉存储里的会话记录;记录已经被别的项目改写时不动它。 */
213
+ private async clearStoredSession(sessionID: string): Promise<void> {
214
+ try {
215
+ const stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
216
+ if (stored !== sessionID) return
217
+ await this.ctx.storage.remove(KEEP_ALIVE_SESSION_KEY)
218
+ } catch (error) {
219
+ this.logger.warn("清除保活会话记录失败", error)
220
+ }
221
+ }
222
+ }