@cmach_socket/opencode-qq-bot 0.3.4 → 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/NOTICE +63 -0
- package/README.md +170 -20
- package/package.json +20 -2
- package/src/bot-lock.ts +17 -26
- package/src/config.ts +218 -3
- package/src/emoji/command.ts +189 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/home.ts +45 -0
- package/src/index.ts +156 -32
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +130 -0
- package/src/naplink/client.ts +10 -19
- package/src/naplink/history.ts +258 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +96 -32
- package/src/outbound.ts +146 -0
- package/src/rate-limit.ts +161 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +232 -18
- package/src/session/prompt.ts +4 -1
- package/src/tools/ask-guard.ts +3 -2
- package/src/tools/qq.ts +218 -36
- package/src/tools/send-guard.ts +72 -0
package/src/index.ts
CHANGED
|
@@ -1,20 +1,32 @@
|
|
|
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,
|
|
4
|
+
import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
|
|
5
5
|
import { type ChatTarget, configuredTargets, isTargetEnabled, targetKey, targetLabel } from "./chat"
|
|
6
6
|
import { resolveConfig, type QQBotConfig } from "./config"
|
|
7
|
+
import { resolveHome } from "./home"
|
|
7
8
|
import { claimInstance } from "./instance"
|
|
8
|
-
import {
|
|
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"
|
|
9
13
|
import { QQClient } from "./naplink/client"
|
|
14
|
+
import { createHistoryProvider } from "./naplink/history"
|
|
10
15
|
import { createMediaStore } from "./naplink/media"
|
|
11
16
|
import { mentionsUser, renderMessage, resolveUserName, shouldProcess } from "./naplink/render"
|
|
17
|
+
import { SendRateLimiter } from "./rate-limit"
|
|
18
|
+
import { collectEnvSecrets, SensitiveChecker } from "./sensitive"
|
|
12
19
|
import { SessionManager } from "./session/manager"
|
|
13
20
|
import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
|
|
14
21
|
import { proactiveTickProbability } from "./session/proactive"
|
|
15
22
|
import { packageDirectory, SoulStore } from "./session/soul"
|
|
16
23
|
import { registerAskGuard } from "./tools/ask-guard"
|
|
24
|
+
import { registerSendGuard } from "./tools/send-guard"
|
|
17
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"
|
|
18
30
|
|
|
19
31
|
const RETRY_DELAY_MS = 1000
|
|
20
32
|
/** 机器人连接被别的实例占用时,多久重试一次接管。 */
|
|
@@ -27,24 +39,54 @@ function delay(ms: number): Promise<void> {
|
|
|
27
39
|
export default Plugin.define({
|
|
28
40
|
id: "opencode-qq-bot",
|
|
29
41
|
async setup(ctx) {
|
|
30
|
-
|
|
42
|
+
// 配置还没解析出来,先用一个只写控制台的日志器兜底,解析完再换成正式日志器。
|
|
43
|
+
const bootstrap = createLogger("[qq-bot]", { file: false })
|
|
31
44
|
let config: QQBotConfig
|
|
45
|
+
const warnings: string[] = []
|
|
32
46
|
try {
|
|
33
|
-
config = resolveConfig(ctx.options, process.env, (message) =>
|
|
47
|
+
config = resolveConfig(ctx.options, process.env, (message) => warnings.push(message))
|
|
34
48
|
} catch (error) {
|
|
35
|
-
|
|
49
|
+
for (const warning of warnings) bootstrap.warn(warning)
|
|
50
|
+
bootstrap.error(error instanceof Error ? error.message : String(error))
|
|
51
|
+
await closeLogger(bootstrap)
|
|
36
52
|
return
|
|
37
53
|
}
|
|
38
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
|
+
|
|
39
68
|
if (config.groups.length === 0 && config.users.length === 0) {
|
|
40
69
|
logger.warn(
|
|
41
70
|
"未配置目标群号或私聊 QQ 号,插件不会响应任何消息(请设置 groups/users 或 QQ_TARGET_GROUPS/QQ_TARGET_USERS)",
|
|
42
71
|
)
|
|
43
72
|
}
|
|
44
73
|
|
|
45
|
-
//
|
|
46
|
-
const
|
|
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
|
+
}
|
|
47
88
|
if (previous?.dispose) {
|
|
89
|
+
logger.info("接管已有的插件实例并卸载它", previous.label)
|
|
48
90
|
try {
|
|
49
91
|
await previous.dispose()
|
|
50
92
|
} catch (error) {
|
|
@@ -52,10 +94,9 @@ export default Plugin.define({
|
|
|
52
94
|
}
|
|
53
95
|
}
|
|
54
96
|
|
|
55
|
-
//
|
|
56
|
-
// 多个实例各自连接,NapCat 会把同一条消息推给所有连接,模型就会收到重复消息。
|
|
57
|
-
const identity = botIdentity(config.napcat)
|
|
97
|
+
// 机器级锁:抢不到就保持安静,等持有者退出后再接管。
|
|
58
98
|
let botLock: BotLock | undefined
|
|
99
|
+
let disposed = false
|
|
59
100
|
|
|
60
101
|
// 角色设定:读取生效文件并监听改动,改完下一轮即生效。
|
|
61
102
|
const soul = new SoulStore(
|
|
@@ -70,9 +111,29 @@ export default Plugin.define({
|
|
|
70
111
|
await soul.load()
|
|
71
112
|
|
|
72
113
|
const client = new QQClient(config.napcat, logger)
|
|
73
|
-
const
|
|
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)
|
|
74
133
|
await manager.load()
|
|
75
|
-
|
|
134
|
+
// 保活心跳:OpenCode 长时间没有会话活动时会卸载 location,插件随之被卸载。
|
|
135
|
+
const keepAlive = new KeepAlive(ctx, config, logger)
|
|
136
|
+
keepAlive.start()
|
|
76
137
|
const mediaCleanup = setInterval(
|
|
77
138
|
() => {
|
|
78
139
|
void media.cleanup()
|
|
@@ -81,10 +142,37 @@ export default Plugin.define({
|
|
|
81
142
|
)
|
|
82
143
|
const mediaHandle = mediaCleanup as { unref?: () => void }
|
|
83
144
|
mediaHandle.unref?.()
|
|
84
|
-
|
|
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
|
+
})
|
|
85
172
|
// QQ 会话里禁止模型调用内置 question 工具,改用 qq_send_message 询问用户。
|
|
86
173
|
const askGuardRegistration = await registerAskGuard({ ctx, logger, manager })
|
|
87
|
-
|
|
174
|
+
// 禁止连续调用发送工具,避免同一条消息被重复发送。
|
|
175
|
+
const sendGuardRegistration = await registerSendGuard({ ctx, logger, manager })
|
|
88
176
|
|
|
89
177
|
// 系统提示:角色设定、当前时间、本轮是否必须回复。
|
|
90
178
|
const contextRegistration = await ctx.session.hook("context", (event) => {
|
|
@@ -159,7 +247,6 @@ export default Plugin.define({
|
|
|
159
247
|
if (!isTargetEnabled(config, target)) return
|
|
160
248
|
if (!shouldProcess(event.message, selfId)) return
|
|
161
249
|
|
|
162
|
-
await client.hydrate(event.message)
|
|
163
250
|
const renderCtx = {
|
|
164
251
|
api: client.api,
|
|
165
252
|
target,
|
|
@@ -175,9 +262,15 @@ export default Plugin.define({
|
|
|
175
262
|
const atMe = target.kind === "private" || mentionsUser(event.message, selfId)
|
|
176
263
|
|
|
177
264
|
await manager.enqueue(target, {
|
|
178
|
-
text:
|
|
265
|
+
text: formatModelMessage({
|
|
266
|
+
sender: userName,
|
|
267
|
+
userId: String(event.user_id),
|
|
268
|
+
text: rendered.text,
|
|
269
|
+
time: event.time,
|
|
270
|
+
}),
|
|
179
271
|
files: rendered.files,
|
|
180
272
|
atMe,
|
|
273
|
+
source: { id: String(event.message_id), time: event.time },
|
|
181
274
|
})
|
|
182
275
|
} catch (error) {
|
|
183
276
|
logger.error(`处理 ${targetLabel(target)} 消息失败`, error)
|
|
@@ -225,31 +318,47 @@ export default Plugin.define({
|
|
|
225
318
|
}
|
|
226
319
|
|
|
227
320
|
/**
|
|
228
|
-
*
|
|
321
|
+
* 抢占机器级锁。
|
|
229
322
|
*
|
|
230
323
|
* 拿到锁才能消费消息流;锁被占用说明别的实例已经在消费,这里保持安静。
|
|
231
324
|
*/
|
|
232
325
|
const claimBot = async (): Promise<boolean> => {
|
|
233
326
|
if (botLock) return true
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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
|
+
}
|
|
241
342
|
if (!lock) return false
|
|
343
|
+
if (disposed) {
|
|
344
|
+
// 卸载与抢锁并发:立刻交回锁,不要在卸载之后重新连接 NapCat。
|
|
345
|
+
await lock.release().catch((error: unknown) => logger.error("释放机器人连接锁失败", error))
|
|
346
|
+
return false
|
|
347
|
+
}
|
|
242
348
|
botLock = lock
|
|
243
|
-
logger.info("
|
|
349
|
+
logger.info("已占用机器级锁", botLockPath())
|
|
244
350
|
await startConsuming()
|
|
245
351
|
return true
|
|
246
352
|
}
|
|
247
353
|
|
|
248
|
-
const claimed = await claimBot()
|
|
354
|
+
const claimed = await claimBot().catch((error: unknown) => {
|
|
355
|
+
logger.error("抢占机器人连接失败,稍后重试", error)
|
|
356
|
+
return false
|
|
357
|
+
})
|
|
249
358
|
if (!claimed) {
|
|
250
359
|
logger.warn(
|
|
251
|
-
"
|
|
252
|
-
`锁目录:${botLockPath(
|
|
360
|
+
"同一台机器上已有另一个实例在运行,本实例不会接收 QQ 消息",
|
|
361
|
+
`锁目录:${botLockPath()}`,
|
|
253
362
|
)
|
|
254
363
|
}
|
|
255
364
|
|
|
@@ -295,26 +404,41 @@ export default Plugin.define({
|
|
|
295
404
|
agent: config.agent ?? "(默认)",
|
|
296
405
|
})
|
|
297
406
|
|
|
298
|
-
let disposed = false
|
|
299
407
|
const dispose = async () => {
|
|
300
408
|
if (disposed) return
|
|
301
409
|
disposed = true
|
|
302
410
|
if (timer) clearInterval(timer)
|
|
303
411
|
clearInterval(claimTimer)
|
|
304
412
|
clearInterval(mediaCleanup)
|
|
413
|
+
await keepAlive.dispose()
|
|
305
414
|
idleAbort.abort()
|
|
415
|
+
manager.dispose()
|
|
306
416
|
await manager.flush()
|
|
307
417
|
soul.dispose()
|
|
308
418
|
await toolRegistration.dispose()
|
|
419
|
+
await emojiCommandRegistration.dispose()
|
|
420
|
+
await labeler.dispose()
|
|
309
421
|
await askGuardRegistration.dispose()
|
|
422
|
+
await sendGuardRegistration.dispose()
|
|
310
423
|
await contextRegistration.dispose()
|
|
311
424
|
await idleRegistration.dispose()
|
|
312
425
|
client.dispose()
|
|
313
|
-
// 先断开 NapCat
|
|
314
|
-
|
|
426
|
+
// 先断开 NapCat 再释放机器级锁,避免新实例接管时出现两条连接。
|
|
427
|
+
try {
|
|
428
|
+
await botLock?.release()
|
|
429
|
+
} catch (error) {
|
|
430
|
+
// 释放失败也要继续释放实例租约,否则旧实例的租约会一直占着槽位。
|
|
431
|
+
logger.error("释放机器人连接锁失败", error)
|
|
432
|
+
}
|
|
315
433
|
botLock = undefined
|
|
316
434
|
lease.release()
|
|
317
|
-
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)
|
|
318
442
|
}
|
|
319
443
|
lease.setDispose(dispose)
|
|
320
444
|
return dispose
|
package/src/instance.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 进程内单实例注册表。
|
|
3
3
|
*
|
|
4
|
-
* OpenCode
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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?: {
|
|
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
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
49
|
+
* 占用进程内唯一的实例槽位。
|
|
50
|
+
*
|
|
51
|
+
* @param directory 机器人固定服务的工作目录。
|
|
52
|
+
* @param label 实例来源描述,通常是项目目录与 NapCat 地址,仅用于日志。
|
|
40
53
|
*/
|
|
41
|
-
export function claimInstance(
|
|
42
|
-
previous: PluginInstance | undefined
|
|
43
|
-
lease: InstanceLease
|
|
44
|
-
} {
|
|
54
|
+
export function claimInstance(directory: string, label: string): InstanceClaim {
|
|
45
55
|
const state = host()
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
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
|
package/src/keepalive.ts
ADDED
|
@@ -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
|
+
}
|