@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -71
- package/chat-overrides.example.json +7 -0
- package/package.json +3 -1
- package/src/access.ts +0 -5
- package/src/async.ts +25 -0
- package/src/commands.ts +8 -13
- package/src/config.ts +56 -87
- package/src/emoji/command.ts +0 -2
- package/src/emoji/label.ts +10 -22
- package/src/events/notice.ts +0 -19
- package/src/home.ts +8 -6
- package/src/index.ts +126 -88
- package/src/keepalive.ts +10 -24
- package/src/logger.ts +2 -1
- package/src/media-path.ts +2 -4
- package/src/model-view.ts +2 -2
- package/src/naplink/media.ts +4 -8
- package/src/naplink/render.ts +41 -53
- package/src/overrides.ts +9 -20
- package/src/rate-limit.ts +2 -1
- package/src/safe-fetch.ts +1 -5
- package/src/seed.ts +31 -0
- package/src/sensitive.ts +3 -5
- package/src/session/find.ts +45 -0
- package/src/session/manager.ts +113 -94
- package/src/session/proactive.ts +8 -11
- package/src/session/soul.ts +48 -31
- package/src/text.ts +7 -0
- package/src/tools/policy-guard.ts +3 -0
- package/src/tools/policy.ts +9 -3
- package/src/tools/qq.ts +157 -67
- package/src/tui-commands.ts +1 -1
- package/tool-profiles.example.json +21 -0
package/src/emoji/label.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
2
|
import type { Location } from "@opencode/schema"
|
|
3
|
+
import { delay, unrefTimer } from "../async"
|
|
3
4
|
import type { QQBotConfig } from "../config"
|
|
4
5
|
import type { BotHome } from "../home"
|
|
5
6
|
import type { Logger } from "../logger"
|
|
7
|
+
import { findSession } from "../session/find"
|
|
6
8
|
import type { MediaStore } from "../naplink/media"
|
|
7
9
|
import type { CustomFace, FavoriteStore } from "./favorites"
|
|
8
10
|
|
|
@@ -22,10 +24,6 @@ export const LABEL_PROMPT = [
|
|
|
22
24
|
"不要调用任何工具。",
|
|
23
25
|
].join("\n")
|
|
24
26
|
|
|
25
|
-
function delay(ms: number): Promise<void> {
|
|
26
|
-
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
27
|
-
}
|
|
28
|
-
|
|
29
27
|
/**
|
|
30
28
|
* 清理模型给出的标签。
|
|
31
29
|
*
|
|
@@ -197,6 +195,7 @@ export class EmojiLabeler {
|
|
|
197
195
|
)
|
|
198
196
|
resolve(undefined)
|
|
199
197
|
}, timeoutMs)
|
|
198
|
+
unrefTimer(timer)
|
|
200
199
|
const waiters = this.waiters.get(sessionID) ?? []
|
|
201
200
|
waiters.push(onText)
|
|
202
201
|
this.waiters.set(sessionID, waiters)
|
|
@@ -264,24 +263,13 @@ export class EmojiLabeler {
|
|
|
264
263
|
|
|
265
264
|
/** 查找带标签标记的历史会话。 */
|
|
266
265
|
private async findLabelSession(): Promise<string | undefined> {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
...(cursor ? { cursor } : {}),
|
|
275
|
-
})
|
|
276
|
-
const hit = result.data.find((session) => session.metadata?.[LABEL_SESSION_MARKER] === true)
|
|
277
|
-
if (hit) return hit.id
|
|
278
|
-
cursor = result.cursor.next ?? undefined
|
|
279
|
-
if (!cursor) break
|
|
280
|
-
}
|
|
281
|
-
} catch (error) {
|
|
282
|
-
this.deps.logger.warn("查找收藏表情标签会话失败", error)
|
|
283
|
-
}
|
|
284
|
-
return undefined
|
|
266
|
+
return await findSession(
|
|
267
|
+
this.deps.ctx,
|
|
268
|
+
this.location.directory,
|
|
269
|
+
(session) => session.metadata?.[LABEL_SESSION_MARKER] === true,
|
|
270
|
+
this.deps.logger,
|
|
271
|
+
"查找收藏表情标签会话失败",
|
|
272
|
+
)
|
|
285
273
|
}
|
|
286
274
|
|
|
287
275
|
/**
|
package/src/events/notice.ts
CHANGED
|
@@ -19,25 +19,6 @@ export interface NoticePayload {
|
|
|
19
19
|
file?: { name?: string; size?: number }
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
/** 插件认识的全部通知类型。 */
|
|
23
|
-
export const NOTICE_TYPES = [
|
|
24
|
-
"group_recall",
|
|
25
|
-
"friend_recall",
|
|
26
|
-
"group_upload",
|
|
27
|
-
"group_admin",
|
|
28
|
-
"group_decrease",
|
|
29
|
-
"group_increase",
|
|
30
|
-
"friend_add",
|
|
31
|
-
"notify",
|
|
32
|
-
] as const
|
|
33
|
-
|
|
34
|
-
export type NoticeType = (typeof NOTICE_TYPES)[number]
|
|
35
|
-
|
|
36
|
-
/** 通知类型是否受支持。 */
|
|
37
|
-
export function isNoticeType(value: string): value is NoticeType {
|
|
38
|
-
return (NOTICE_TYPES as readonly string[]).includes(value)
|
|
39
|
-
}
|
|
40
|
-
|
|
41
22
|
/**
|
|
42
23
|
* 通知对应的聊天目标。
|
|
43
24
|
*
|
package/src/home.ts
CHANGED
|
@@ -30,13 +30,15 @@ export async function resolveHome(
|
|
|
30
30
|
return { directory }
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** 展开路径开头的 `~` 或 `~/`,其余原样返回。 */
|
|
34
|
+
export function expandTilde(value: string): string {
|
|
35
|
+
if (value === "~") return homedir()
|
|
36
|
+
if (value.startsWith("~/")) return join(homedir(), value.slice(2))
|
|
37
|
+
return value
|
|
38
|
+
}
|
|
39
|
+
|
|
33
40
|
function expand(configured: string, logger: Logger): string {
|
|
34
|
-
const expanded =
|
|
35
|
-
configured === "~"
|
|
36
|
-
? homedir()
|
|
37
|
-
: configured.startsWith("~/")
|
|
38
|
-
? join(homedir(), configured.slice(2))
|
|
39
|
-
: configured
|
|
41
|
+
const expanded = expandTilde(configured)
|
|
40
42
|
if (!isAbsolute(expanded)) {
|
|
41
43
|
logger.warn("机器人工作目录必须是绝对路径,已回退到默认目录", configured)
|
|
42
44
|
return defaultHome()
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { join, resolve } from "node:path"
|
|
1
2
|
import { Plugin } from "@opencode/plugin"
|
|
2
3
|
import type { GroupMessageEvent, MessageEvent, NoticeEvent } from "@naplink/naplink"
|
|
3
4
|
import { Mutex } from "async-mutex"
|
|
5
|
+
import { delay, unrefTimer } from "./async"
|
|
4
6
|
import { acquireBotLock, type BotLock, botLockPath } from "./bot-lock"
|
|
5
7
|
import { type ChatTarget, targetKey, targetLabel } from "./chat"
|
|
6
8
|
import { allowedTargets, isTargetAllowed } from "./access"
|
|
@@ -16,11 +18,12 @@ import { createHistoryProvider } from "./naplink/history"
|
|
|
16
18
|
import { createMediaStore } from "./naplink/media"
|
|
17
19
|
import { describeMentions, renderMessage, resolveUserName, shouldProcess } from "./naplink/render"
|
|
18
20
|
import { SendRateLimiter } from "./rate-limit"
|
|
21
|
+
import { packageRoot, seedFile } from "./seed"
|
|
19
22
|
import { collectEnvSecrets, redactUrl, secretsFromUrl, SensitiveChecker } from "./sensitive"
|
|
20
23
|
import { SessionManager } from "./session/manager"
|
|
21
24
|
import { currentTimeText, PROACTIVE_HINT } from "./session/prompt"
|
|
22
25
|
import { proactiveProbability } from "./session/proactive"
|
|
23
|
-
import { packageDirectory, SoulLibrary } from "./session/soul"
|
|
26
|
+
import { packageDirectory, seedSouls, SoulLibrary } from "./session/soul"
|
|
24
27
|
import { COMMANDS, handleCommand, isCommandChat } from "./commands"
|
|
25
28
|
import {
|
|
26
29
|
chatMuted,
|
|
@@ -36,7 +39,13 @@ import { registerAskGuard } from "./tools/ask-guard"
|
|
|
36
39
|
import { defaultToolProfilesPath, roleOf, ToolPolicy } from "./tools/policy"
|
|
37
40
|
import { registerToolPolicy } from "./tools/policy-guard"
|
|
38
41
|
import { registerSendGuard } from "./tools/send-guard"
|
|
39
|
-
import {
|
|
42
|
+
import {
|
|
43
|
+
createPlainSender,
|
|
44
|
+
QQ_REQUEST_REPLY_TOOL,
|
|
45
|
+
registerTools,
|
|
46
|
+
sendPlainMessage,
|
|
47
|
+
TOOL_NAMESPACE,
|
|
48
|
+
} from "./tools/qq"
|
|
40
49
|
import { createEmojiRunner, emojiCommand } from "./emoji/command"
|
|
41
50
|
import { describeNotice, noticeMatches, noticeTarget } from "./events/notice"
|
|
42
51
|
import { NoticeStore } from "./events/store"
|
|
@@ -50,10 +59,6 @@ const RETRY_DELAY_MS = 1000
|
|
|
50
59
|
/** 机器人连接被别的实例占用时,多久重试一次接管。 */
|
|
51
60
|
const CLAIM_RETRY_MS = 30_000
|
|
52
61
|
|
|
53
|
-
function delay(ms: number): Promise<void> {
|
|
54
|
-
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
55
|
-
}
|
|
56
|
-
|
|
57
62
|
/** 迁移类告警用 error 级别输出,其余保持 warn。 */
|
|
58
63
|
function reportWarnings(warnings: readonly string[], logger: Logger): void {
|
|
59
64
|
for (const warning of warnings) {
|
|
@@ -76,6 +81,43 @@ function knownSecrets(config: QQBotConfig): string[] {
|
|
|
76
81
|
].filter((secret) => secret.length > 0)
|
|
77
82
|
}
|
|
78
83
|
|
|
84
|
+
const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
|
|
85
|
+
event.message_type === "group"
|
|
86
|
+
|
|
87
|
+
/** 只取消息里的文本段,用于识别管理命令。 */
|
|
88
|
+
function messageText(event: MessageEvent): string {
|
|
89
|
+
return (event.message ?? [])
|
|
90
|
+
.filter((segment) => segment.type === "text")
|
|
91
|
+
.map((segment) => String((segment.data as { text?: unknown }).text ?? ""))
|
|
92
|
+
.join(" ")
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 必回原因对应给模型的一句话。 */
|
|
96
|
+
function wakeHint(reason: WakeReason | undefined): string {
|
|
97
|
+
switch (reason) {
|
|
98
|
+
case "private":
|
|
99
|
+
return "这是一条私聊消息,必须回复。"
|
|
100
|
+
case "all":
|
|
101
|
+
return "这个群要求每条消息都回复,必须回复。"
|
|
102
|
+
case "mention":
|
|
103
|
+
return "你被 @ 了,必须回复。"
|
|
104
|
+
case "prefix":
|
|
105
|
+
return "这条消息命中了唤醒前缀,必须回复。"
|
|
106
|
+
case "at_all":
|
|
107
|
+
return "这条消息 @ 了全体成员,必须回复。"
|
|
108
|
+
case "reply":
|
|
109
|
+
return "这条消息回复了你,必须回复。"
|
|
110
|
+
default:
|
|
111
|
+
return "这条消息没有要求你回复,可以选择不回复。"
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function eventTarget(event: MessageEvent): ChatTarget {
|
|
116
|
+
return isGroupEvent(event)
|
|
117
|
+
? { kind: "group", id: event.group_id }
|
|
118
|
+
: { kind: "private", id: event.user_id }
|
|
119
|
+
}
|
|
120
|
+
|
|
79
121
|
export default Plugin.define({
|
|
80
122
|
id: "opencode-qq-bot",
|
|
81
123
|
async setup(ctx) {
|
|
@@ -236,16 +278,16 @@ export default Plugin.define({
|
|
|
236
278
|
if (disposed) return
|
|
237
279
|
runtimeStarted = true
|
|
238
280
|
|
|
239
|
-
//
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
)
|
|
281
|
+
// 角色设定:先把随包分发的初始文件补进工作目录,之后一直读工作目录里的副本,
|
|
282
|
+
// 升级插件不会覆盖掉用户改过的设定。默认档之外还能按聊天覆盖,改完下一轮即生效。
|
|
283
|
+
const soulOptions = {
|
|
284
|
+
soulPath: config.soulPath,
|
|
285
|
+
soulName: config.soulName,
|
|
286
|
+
home: home.directory,
|
|
287
|
+
moduleDir: packageDirectory(),
|
|
288
|
+
}
|
|
289
|
+
await seedSouls(soulOptions, logger)
|
|
290
|
+
const souls = new SoulLibrary(soulOptions, logger)
|
|
249
291
|
cleanup.add("停止角色设定热重载", () => souls.dispose(), CleanupOrder.souls)
|
|
250
292
|
await souls.loadDefault()
|
|
251
293
|
|
|
@@ -259,6 +301,15 @@ export default Plugin.define({
|
|
|
259
301
|
allowedDirs: [home.directory, mediaDir, ...config.media.allowedDirs],
|
|
260
302
|
})
|
|
261
303
|
const nameCache = new Map<string, { name: string; expires: number }>()
|
|
304
|
+
/** 渲染上下文:上游 API、媒体存储与昵称缓存都在这里一次性绑定。 */
|
|
305
|
+
const renderContext = (target: ChatTarget, selfId?: string) => ({
|
|
306
|
+
api: client.api,
|
|
307
|
+
target,
|
|
308
|
+
logger,
|
|
309
|
+
media,
|
|
310
|
+
names: nameCache,
|
|
311
|
+
...(selfId ? { selfId } : {}),
|
|
312
|
+
})
|
|
262
313
|
const history = createHistoryProvider({
|
|
263
314
|
api: client.api,
|
|
264
315
|
logger,
|
|
@@ -276,12 +327,22 @@ export default Plugin.define({
|
|
|
276
327
|
// 通知缓存:通知不自己起一轮,只在下一次该聊天的上下文里附带出现。
|
|
277
328
|
const noticeStore = new NoticeStore()
|
|
278
329
|
// 工具配置:按聊天与角色决定模型能看到、能调用哪些工具。
|
|
279
|
-
|
|
330
|
+
// 走默认位置时把随包的示例复制过去,占位目标得自己改成真实的群 / 私聊。
|
|
331
|
+
const profilesPath = config.toolProfilesPath
|
|
332
|
+
? resolve(home.directory, config.toolProfilesPath)
|
|
333
|
+
: defaultToolProfilesPath(home.directory)
|
|
334
|
+
if (!config.toolProfilesPath) {
|
|
335
|
+
await seedFile(join(packageRoot, "tool-profiles.example.json"), profilesPath, logger)
|
|
336
|
+
}
|
|
337
|
+
const policy = new ToolPolicy(profilesPath, logger)
|
|
280
338
|
// 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
|
|
281
|
-
const
|
|
282
|
-
config.chatOverridesPath
|
|
283
|
-
|
|
284
|
-
)
|
|
339
|
+
const overridesPath = config.chatOverridesPath
|
|
340
|
+
? resolve(home.directory, config.chatOverridesPath)
|
|
341
|
+
: defaultChatOverridesPath(home.directory)
|
|
342
|
+
if (!config.chatOverridesPath) {
|
|
343
|
+
await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
|
|
344
|
+
}
|
|
345
|
+
const overrides = new ChatOverrides(overridesPath, logger)
|
|
285
346
|
// 调用链追踪:一条入站消息拿一个 trace_id,事后能把这轮串起来。
|
|
286
347
|
// 追踪文件与日志放在一起,容量与保留天数都有上限。
|
|
287
348
|
const tracer = config.trace.enabled
|
|
@@ -335,8 +396,7 @@ export default Plugin.define({
|
|
|
335
396
|
},
|
|
336
397
|
60 * 60 * 1000,
|
|
337
398
|
)
|
|
338
|
-
|
|
339
|
-
mediaHandle.unref?.()
|
|
399
|
+
unrefTimer(mediaCleanup)
|
|
340
400
|
cleanup.add("停止媒体清理定时器", () => clearInterval(mediaCleanup), CleanupOrder.events)
|
|
341
401
|
// 收藏表情:标签只存在 NapCat 侧,插件不保存副本;编号由插件自己维护。
|
|
342
402
|
const favorites = new FavoriteStore(
|
|
@@ -462,7 +522,7 @@ export default Plugin.define({
|
|
|
462
522
|
event.system.push({
|
|
463
523
|
type: "text",
|
|
464
524
|
text: turn?.proactive
|
|
465
|
-
? `这是一次主动发起话题,必须调用 qq_send_message 把话题发到${destination}
|
|
525
|
+
? `这是一次主动发起话题,必须调用 qq_send_message 把话题发到${destination}。${target.kind === "group" && config.reply.requirePermission ? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。" : ""}`
|
|
466
526
|
: turn?.atMe
|
|
467
527
|
? wakeHint(turn.wake)
|
|
468
528
|
: turn?.suppress
|
|
@@ -477,12 +537,21 @@ export default Plugin.define({
|
|
|
477
537
|
text: `聊天里发生过的通知(不需要回复):\n${notices.map((item) => `- ${item}`).join("\n")}`,
|
|
478
538
|
})
|
|
479
539
|
}
|
|
540
|
+
// 群里默认没有发送权限:模型得先想清楚该不该回复,说明理由才拿得到权限。
|
|
541
|
+
if (target.kind === "group" && config.reply.requirePermission) {
|
|
542
|
+
event.system.push({
|
|
543
|
+
type: "text",
|
|
544
|
+
text: `默认你没有向用户发消息的权限。要回复,先判断该不该回复,再调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;拿到权限后才能调用 qq_send_message,权限只在本轮有效。`,
|
|
545
|
+
})
|
|
546
|
+
}
|
|
480
547
|
// 本轮发送者的角色决定工具档:owner / admin 全开,其他按聊天配置。
|
|
481
548
|
// 角色按会话保留,没有在途轮次(重启、TUI 驱动)时也照样收窄。
|
|
482
549
|
{
|
|
483
550
|
const allowed = await policy.allow(role, targetKey(target), Object.keys(event.tools))
|
|
484
551
|
const removed: string[] = []
|
|
485
552
|
for (const name of Object.keys(event.tools)) {
|
|
553
|
+
// 申请回复权限的工具必须一直留着:不然模型永远拿不到发送权限。
|
|
554
|
+
if (name === QQ_REQUEST_REPLY_TOOL) continue
|
|
486
555
|
if (!allowed.has(name)) {
|
|
487
556
|
removed.push(name)
|
|
488
557
|
delete event.tools[name]
|
|
@@ -538,22 +607,25 @@ export default Plugin.define({
|
|
|
538
607
|
],
|
|
539
608
|
signal: idleAbort.signal,
|
|
540
609
|
})) {
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
sessionID
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
610
|
+
// 单条事件处理失败只记日志:连带把订阅循环拆掉会让缓存消息再也发不出去。
|
|
611
|
+
try {
|
|
612
|
+
const sessionID = event.data.sessionID
|
|
613
|
+
logger.debug(`上游事件:${event.type}`, {
|
|
614
|
+
sessionID,
|
|
615
|
+
...(event.type === "session.status" ? { status: event.data.status.type } : {}),
|
|
616
|
+
})
|
|
617
|
+
if (event.type === "session.status") {
|
|
618
|
+
if (event.data.status.type === "idle") await manager.flushBuffered(sessionID)
|
|
619
|
+
} else if (event.type === "session.execution.succeeded") {
|
|
620
|
+
await manager.flushBuffered(sessionID)
|
|
621
|
+
} else {
|
|
622
|
+
// 失败事件带上游错误信息,只进日志(logger 会脱敏),不进聊天。
|
|
623
|
+
const detail =
|
|
624
|
+
event.type === "session.execution.failed" ? event.data.error.message : undefined
|
|
625
|
+
await manager.handleExecutionEnd(sessionID, event.type, detail)
|
|
549
626
|
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
} else {
|
|
553
|
-
// 失败事件带上游错误信息,只进日志(logger 会脱敏),不进聊天。
|
|
554
|
-
const detail =
|
|
555
|
-
event.type === "session.execution.failed" ? event.data.error.message : undefined
|
|
556
|
-
await manager.handleExecutionEnd(event.data.sessionID, event.type, detail)
|
|
627
|
+
} catch (error) {
|
|
628
|
+
logger.warn("处理会话事件失败", error)
|
|
557
629
|
}
|
|
558
630
|
}
|
|
559
631
|
} catch (error) {
|
|
@@ -564,41 +636,6 @@ export default Plugin.define({
|
|
|
564
636
|
}
|
|
565
637
|
})()
|
|
566
638
|
|
|
567
|
-
const isGroupEvent = (event: MessageEvent): event is GroupMessageEvent =>
|
|
568
|
-
event.message_type === "group"
|
|
569
|
-
|
|
570
|
-
/** 只取消息里的文本段,用于识别管理命令。 */
|
|
571
|
-
const messageText = (event: MessageEvent): string =>
|
|
572
|
-
(event.message ?? [])
|
|
573
|
-
.filter((segment) => segment.type === "text")
|
|
574
|
-
.map((segment) => String((segment.data as { text?: unknown }).text ?? ""))
|
|
575
|
-
.join(" ")
|
|
576
|
-
|
|
577
|
-
/** 必回原因对应给模型的一句话。 */
|
|
578
|
-
const wakeHint = (reason: WakeReason | undefined): string => {
|
|
579
|
-
switch (reason) {
|
|
580
|
-
case "private":
|
|
581
|
-
return "这是一条私聊消息,必须回复。"
|
|
582
|
-
case "all":
|
|
583
|
-
return "这个群要求每条消息都回复,必须回复。"
|
|
584
|
-
case "mention":
|
|
585
|
-
return "你被 @ 了,必须回复。"
|
|
586
|
-
case "prefix":
|
|
587
|
-
return "这条消息命中了唤醒前缀,必须回复。"
|
|
588
|
-
case "at_all":
|
|
589
|
-
return "这条消息 @ 了全体成员,必须回复。"
|
|
590
|
-
case "reply":
|
|
591
|
-
return "这条消息回复了你,必须回复。"
|
|
592
|
-
default:
|
|
593
|
-
return "这条消息没有要求你回复,可以选择不回复。"
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
const eventTarget = (event: MessageEvent): ChatTarget =>
|
|
598
|
-
isGroupEvent(event)
|
|
599
|
-
? { kind: "group", id: event.group_id }
|
|
600
|
-
: { kind: "private", id: event.user_id }
|
|
601
|
-
|
|
602
639
|
const handleMessage = async (
|
|
603
640
|
event: MessageEvent,
|
|
604
641
|
target: ChatTarget,
|
|
@@ -629,14 +666,7 @@ export default Plugin.define({
|
|
|
629
666
|
}
|
|
630
667
|
if (!shouldProcess(event.message, selfId)) return
|
|
631
668
|
|
|
632
|
-
const renderCtx =
|
|
633
|
-
api: client.api,
|
|
634
|
-
target,
|
|
635
|
-
logger,
|
|
636
|
-
media,
|
|
637
|
-
names: nameCache,
|
|
638
|
-
selfId,
|
|
639
|
-
}
|
|
669
|
+
const renderCtx = renderContext(target, selfId)
|
|
640
670
|
const rendered = await renderMessage(renderCtx, event)
|
|
641
671
|
if (!rendered.text.trim()) return
|
|
642
672
|
|
|
@@ -657,6 +687,12 @@ export default Plugin.define({
|
|
|
657
687
|
config.wake,
|
|
658
688
|
)
|
|
659
689
|
|
|
690
|
+
logger.info(`${targetLabel(target)} 消息交给模型`, {
|
|
691
|
+
user: String(event.user_id),
|
|
692
|
+
role: senderRole,
|
|
693
|
+
required: decision.required,
|
|
694
|
+
...(decision.reason ? { reason: decision.reason } : {}),
|
|
695
|
+
})
|
|
660
696
|
await manager.enqueue(target, {
|
|
661
697
|
text: formatModelMessage({
|
|
662
698
|
sender: userName,
|
|
@@ -702,6 +738,10 @@ export default Plugin.define({
|
|
|
702
738
|
return
|
|
703
739
|
}
|
|
704
740
|
manager.touch(target)
|
|
741
|
+
logger.info(`${targetLabel(target)} 收到 QQ 消息`, {
|
|
742
|
+
user: String(event.user_id),
|
|
743
|
+
message_id: String(event.message_id),
|
|
744
|
+
})
|
|
705
745
|
|
|
706
746
|
// 一条入站消息一个追踪 id,后面各个节点都挂在它下面。
|
|
707
747
|
const traceId = tracer?.startTrace()
|
|
@@ -731,9 +771,9 @@ export default Plugin.define({
|
|
|
731
771
|
if (!target || !isTargetAllowed(config.access, target, config.ownerQQ)) return
|
|
732
772
|
void (async () => {
|
|
733
773
|
try {
|
|
734
|
-
const renderCtx = { api: client.api, target, logger, media, names: nameCache }
|
|
735
774
|
const text = await describeNotice(event, {
|
|
736
|
-
nameOf: async (userId) =>
|
|
775
|
+
nameOf: async (userId) =>
|
|
776
|
+
await resolveUserName(renderContext(target), String(userId)),
|
|
737
777
|
})
|
|
738
778
|
if (!text) return
|
|
739
779
|
logger.info(`${targetLabel(target)} 收到通知:${text}`)
|
|
@@ -793,8 +833,7 @@ export default Plugin.define({
|
|
|
793
833
|
proactiveTimer = setInterval(() => {
|
|
794
834
|
void tick().catch((error: unknown) => logger.error("主动说话心跳失败", error))
|
|
795
835
|
}, config.proactive.tickSeconds * 1000)
|
|
796
|
-
|
|
797
|
-
handle.unref?.()
|
|
836
|
+
unrefTimer(proactiveTimer)
|
|
798
837
|
}
|
|
799
838
|
|
|
800
839
|
// 工具先注册,模型这一轮就能看到 qq_*;再连 NapCat 开始消费。
|
|
@@ -827,8 +866,7 @@ export default Plugin.define({
|
|
|
827
866
|
})
|
|
828
867
|
.catch((error: unknown) => logger.error("接管机器人连接失败", error))
|
|
829
868
|
}, CLAIM_RETRY_MS)
|
|
830
|
-
|
|
831
|
-
claimHandle.unref?.()
|
|
869
|
+
unrefTimer(claimTimer)
|
|
832
870
|
cleanup.add(
|
|
833
871
|
"停止接管重试定时器",
|
|
834
872
|
() => {
|
package/src/keepalive.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { unrefTimer } from "./async"
|
|
2
3
|
import type { QQBotConfig } from "./config"
|
|
3
4
|
import type { Logger } from "./logger"
|
|
5
|
+
import { findSession } from "./session/find"
|
|
4
6
|
|
|
5
7
|
/** 插件存储里保存保活会话 ID 的键。 */
|
|
6
8
|
export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
|
|
@@ -9,8 +11,6 @@ export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
|
|
|
9
11
|
/** 保活会话标题。 */
|
|
10
12
|
export const KEEP_ALIVE_TITLE = "QQ 保活"
|
|
11
13
|
|
|
12
|
-
type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
|
|
13
|
-
|
|
14
14
|
/**
|
|
15
15
|
* 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
|
|
16
16
|
*
|
|
@@ -38,8 +38,7 @@ export class KeepAlive {
|
|
|
38
38
|
this.timer = setInterval(() => {
|
|
39
39
|
void this.ping()
|
|
40
40
|
}, this.config.keepAlive.seconds * 1000)
|
|
41
|
-
|
|
42
|
-
handle.unref?.()
|
|
41
|
+
unrefTimer(this.timer)
|
|
43
42
|
}
|
|
44
43
|
|
|
45
44
|
/**
|
|
@@ -179,26 +178,13 @@ export class KeepAlive {
|
|
|
179
178
|
|
|
180
179
|
/** 查找带保活标记的历史会话。 */
|
|
181
180
|
private async findKeepAliveSession(): Promise<string | undefined> {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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
|
|
181
|
+
return await findSession(
|
|
182
|
+
this.ctx,
|
|
183
|
+
this.ctx.location.directory,
|
|
184
|
+
(session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
|
|
185
|
+
this.logger,
|
|
186
|
+
"查找保活会话失败",
|
|
187
|
+
)
|
|
202
188
|
}
|
|
203
189
|
|
|
204
190
|
private async writeStoredSession(sessionID: string): Promise<void> {
|
package/src/logger.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { isAbsolute, join } from "node:path"
|
|
|
4
4
|
import { inspect } from "node:util"
|
|
5
5
|
import winston from "winston"
|
|
6
6
|
import DailyRotateFile from "winston-daily-rotate-file"
|
|
7
|
+
import { unrefTimer } from "./async"
|
|
7
8
|
import { maskSecrets } from "./sensitive"
|
|
8
9
|
|
|
9
10
|
/** 日志级别。 */
|
|
@@ -240,7 +241,7 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
|
|
|
240
241
|
function waitFinish(transport: DailyRotateFile): Promise<void> {
|
|
241
242
|
return new Promise<void>((resolve) => {
|
|
242
243
|
const timer = setTimeout(() => resolve(), CLOSE_TIMEOUT_MS)
|
|
243
|
-
timer
|
|
244
|
+
unrefTimer(timer)
|
|
244
245
|
transport.once("finish", () => {
|
|
245
246
|
clearTimeout(timer)
|
|
246
247
|
resolve()
|
package/src/media-path.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { realpath, stat } from "node:fs/promises"
|
|
|
3
3
|
import { homedir } from "node:os"
|
|
4
4
|
import { isAbsolute, join, resolve, sep } from "node:path"
|
|
5
5
|
import ipaddr from "ipaddr.js"
|
|
6
|
+
import { expandTilde } from "./home"
|
|
6
7
|
import { ALLOWED_PORTS } from "./safe-fetch"
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -32,10 +33,7 @@ export type MediaPlan = { kind: "local"; path: string } | { kind: "remote"; url:
|
|
|
32
33
|
|
|
33
34
|
/** 展开 `~` 并去掉首尾空白。 */
|
|
34
35
|
function expand(value: string): string {
|
|
35
|
-
|
|
36
|
-
if (trimmed === "~") return homedir()
|
|
37
|
-
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2))
|
|
38
|
-
return trimmed
|
|
36
|
+
return expandTilde(value.trim())
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
/**
|
package/src/model-view.ts
CHANGED
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
* 群友把 `<quote>` 拆成两段发过来,逐段净化匹配不到,只有整体净化才拦得住。
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { ZERO_WIDTH } from "./text"
|
|
13
|
+
|
|
12
14
|
/** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
|
|
13
15
|
const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
|
|
14
16
|
|
|
15
17
|
/** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
|
|
16
18
|
const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
|
|
17
|
-
/** 零宽字符:可以用来把标签拆成看起来正常、匹配不上的形式。 */
|
|
18
|
-
const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
|
|
19
19
|
/** 控制字符:显示名里出现会破坏结构。 */
|
|
20
20
|
const CONTROL = /[\u0000-\u001F\u007F]+/g
|
|
21
21
|
/** 私用区字符:插件用它给结构标签占位,群友文本里的必须清掉,否则能伪造占位符。 */
|
package/src/naplink/media.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { pathToFileURL } from "node:url"
|
|
|
5
5
|
import type { Logger } from "../logger"
|
|
6
6
|
import { defaultMediaDir } from "../media-path"
|
|
7
7
|
import { type SafeFetcher, safeFetchBytes } from "../safe-fetch"
|
|
8
|
+
import { truncateForLog } from "../text"
|
|
8
9
|
|
|
9
10
|
/** 单张图片下载与落盘的字节上限。 */
|
|
10
11
|
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
|
@@ -84,12 +85,7 @@ function truncateCodePoints(text: string, max: number): string {
|
|
|
84
85
|
return Array.from(text).slice(0, max).join("")
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
|
|
88
|
-
function truncateForLog(value: string, max = 120): string {
|
|
89
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function decodeBase64(value: string): Uint8Array | undefined {
|
|
88
|
+
function decodeBase64Bytes(value: string): Uint8Array | undefined {
|
|
93
89
|
if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(value)) return undefined
|
|
94
90
|
const bytes = Buffer.from(value, "base64")
|
|
95
91
|
return bytes.byteLength > MAX_IMAGE_BYTES ? undefined : new Uint8Array(bytes)
|
|
@@ -98,7 +94,7 @@ function decodeBase64(value: string): Uint8Array | undefined {
|
|
|
98
94
|
function parseDataUrl(uri: string, logger: Logger): ImageBytes | undefined {
|
|
99
95
|
const match = /^data:([^;,]+)?(?:;[^,]*)*;base64,(.*)$/s.exec(uri)
|
|
100
96
|
if (!match) return undefined
|
|
101
|
-
const bytes =
|
|
97
|
+
const bytes = decodeBase64Bytes(match[2] ?? "")
|
|
102
98
|
if (!bytes) return undefined
|
|
103
99
|
// 以魔数嗅探为准:URI 里声明的类型由消息发送方控制,不能直接信任。
|
|
104
100
|
const mime = mimeFromBytes(bytes)
|
|
@@ -143,7 +139,7 @@ export class MediaStore {
|
|
|
143
139
|
|
|
144
140
|
private async readImage(url: string): Promise<ImageBytes | undefined> {
|
|
145
141
|
if (url.startsWith("base64://")) {
|
|
146
|
-
const bytes =
|
|
142
|
+
const bytes = decodeBase64Bytes(url.slice("base64://".length))
|
|
147
143
|
if (!bytes) {
|
|
148
144
|
this.logger.warn("base64 图片无效或超过大小上限")
|
|
149
145
|
return undefined
|