@cmach_socket/opencode-qq-bot 2.0.2 → 2.2.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.
@@ -0,0 +1,218 @@
1
+ import { readdir, readFile, stat } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { allowedTargets, isTargetAllowed } from "../access"
4
+ import { parseTargetKey, targetKey, type ChatTarget } from "../chat"
5
+ import { backupFile, writeTextAtomic } from "../fs/atomic"
6
+ import { knownSecrets } from "../known-secrets"
7
+ import { isPlainObject } from "../safe-object"
8
+ import { maskKnownSecrets } from "../sensitive"
9
+ import { userMdPath, USER_MD_NAME } from "../user/store"
10
+ import type { DocumentProblem } from "./documents"
11
+ import type { PanelRuntime } from "./runtime"
12
+
13
+ /**
14
+ * 面板里的用户档案(USER.md)。
15
+ *
16
+ * 档案按聊天隔离:每个聊天一份,路径由聊天目标算出。
17
+ * 运行时只读它,写它的只有面板:主人在面板里上传的是自己那份文件,
18
+ * 模型与工具依旧不改它。
19
+ */
20
+
21
+ /** 档案正文的大小上限:超过就不接受上传。 */
22
+ export const MAX_USER_MD_BYTES = 64 * 1024
23
+
24
+ /** 一个聊天的用户档案在接口里的样子。 */
25
+ export interface UserMdView {
26
+ /** 聊天键,例如 `group:100`。 */
27
+ chat: string
28
+ /** 档案路径。 */
29
+ path: string
30
+ /** 档案是否存在。 */
31
+ exists: boolean
32
+ /** 档案大小(字节)。 */
33
+ bytes: number
34
+ /** 这个聊天当前是否放行。 */
35
+ admitted: boolean
36
+ /** 档案正文;命中已知凭证时已掩码。没放行或正文过大时没有这一项。 */
37
+ content?: string
38
+ /** 正文超过上限,列表里没有正文:手写的大档案不整份读进内存。 */
39
+ oversized?: boolean
40
+ }
41
+
42
+ /** 用户档案列表。 */
43
+ export interface UserMdListView {
44
+ /** 每个聊天一条。 */
45
+ chats: UserMdView[]
46
+ /** 上传时接受的最大字节数,页面按它提前拦下过大的文件。 */
47
+ maxBytes: number
48
+ }
49
+
50
+ /** 上传档案的结果。 */
51
+ export interface UserMdSaveResult {
52
+ /** 写入的聊天键。 */
53
+ chat: string
54
+ /** 写入的路径。 */
55
+ path: string
56
+ /** 写入后的字节数。 */
57
+ bytes: number
58
+ /** 生效时机说明。 */
59
+ note: string
60
+ /** 保存后的档案列表。 */
61
+ chats: UserMdView[]
62
+ /** 上传时接受的最大字节数。 */
63
+ maxBytes: number
64
+ }
65
+
66
+ /** 档案路径:`<home>/chats/<kind>-<id>/USER.md`。 */
67
+ function pathOf(runtime: PanelRuntime, target: ChatTarget): string {
68
+ return userMdPath(runtime.home.directory, target)
69
+ }
70
+
71
+ /** 下载用的文件名:`group-100-USER.md`。 */
72
+ export function userMdFilename(target: ChatTarget): string {
73
+ return `${target.kind}-${target.id}-${USER_MD_NAME}`
74
+ }
75
+
76
+ /**
77
+ * 读档案原文:下载用。
78
+ *
79
+ * 面板里显示的正文是掩码过的,这里给的是原文——主人下载的是自己写的文件。
80
+ * 文件不在时返回 undefined。
81
+ */
82
+ export async function readUserMdText(
83
+ runtime: PanelRuntime,
84
+ target: ChatTarget,
85
+ ): Promise<string | undefined> {
86
+ return await readFile(pathOf(runtime, target), "utf8").catch(() => undefined)
87
+ }
88
+
89
+ /**
90
+ * 磁盘上已经写了档案的聊天。
91
+ *
92
+ * 扫聊天目录即可:目录名就是 `group-<id>` / `private-<id>`。
93
+ * 这些档案原样留着——聊天还没放行时它不生效,等放行了自然接着用。
94
+ */
95
+ async function chatsWithArchive(runtime: PanelRuntime): Promise<ChatTarget[]> {
96
+ const root = join(runtime.home.directory, "chats")
97
+ let entries: string[]
98
+ try {
99
+ entries = await readdir(root)
100
+ } catch {
101
+ return []
102
+ }
103
+ const targets: ChatTarget[] = []
104
+ for (const entry of entries) {
105
+ const match = /^(group|private)-(\d+)$/.exec(entry)
106
+ if (!match) continue
107
+ const target = parseTargetKey(`${match[1]}:${match[2]}`)
108
+ if (!target) continue
109
+ const info = await stat(pathOf(runtime, target)).catch(() => undefined)
110
+ if (!info?.isFile()) continue
111
+ targets.push(target)
112
+ }
113
+ return targets
114
+ }
115
+
116
+ /**
117
+ * 列出各聊天的档案状态。
118
+ *
119
+ * 名单里是当前放行的聊天,另有磁盘上已经写了档案的聊天:
120
+ * 后者可能还没放行,页面标出来,档案本身不动。
121
+ * 正文只给放行的聊天看:没放行的档案只报元信息。
122
+ */
123
+ export async function listUserMd(runtime: PanelRuntime): Promise<UserMdListView> {
124
+ const secrets = knownSecrets(runtime.config)
125
+ const targets = new Map<string, ChatTarget>()
126
+ for (const target of allowedTargets(runtime.config.access, runtime.config.ownerQQ)) {
127
+ targets.set(targetKey(target), target)
128
+ }
129
+ for (const target of await chatsWithArchive(runtime)) {
130
+ targets.set(targetKey(target), target)
131
+ }
132
+
133
+ const chats: UserMdView[] = []
134
+ for (const key of [...targets.keys()].sort()) {
135
+ const target = targets.get(key)
136
+ if (!target) continue
137
+ const path = pathOf(runtime, target)
138
+ const info = await stat(path).catch(() => undefined)
139
+ const exists = info?.isFile() ?? false
140
+ const view: UserMdView = {
141
+ chat: key,
142
+ path,
143
+ exists,
144
+ bytes: info?.size ?? 0,
145
+ admitted: isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ),
146
+ }
147
+ if (exists && view.admitted) {
148
+ if ((info?.size ?? 0) > MAX_USER_MD_BYTES) {
149
+ // 手写的大档案不整份读进内存:列表只给元信息。
150
+ view.oversized = true
151
+ } else {
152
+ const text = await readFile(path, "utf8").catch(() => undefined)
153
+ if (text !== undefined) view.content = maskKnownSecrets(text, secrets)
154
+ }
155
+ }
156
+ chats.push(view)
157
+ }
158
+ return { chats, maxBytes: MAX_USER_MD_BYTES }
159
+ }
160
+
161
+ /**
162
+ * 上传一个聊天的档案。
163
+ *
164
+ * 整份覆盖:上传的就是全部内容,写之前把旧内容存成 `.bak`。
165
+ * 档案只给放行的聊天写:还没放行的聊天先在准入名单里放行,再上传。
166
+ */
167
+ export async function saveUserMd(
168
+ runtime: PanelRuntime,
169
+ body: unknown,
170
+ ): Promise<{ problems: DocumentProblem[]; result?: UserMdSaveResult }> {
171
+ const problems: DocumentProblem[] = []
172
+ if (!isPlainObject(body)) {
173
+ return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
174
+ }
175
+ const target = typeof body.chat === "string" ? parseTargetKey(body.chat) : undefined
176
+ if (!target) {
177
+ problems.push({ path: "chat", message: "聊天键必须是 group:<群号> 或 private:<账号>" })
178
+ }
179
+ const content = typeof body.content === "string" ? body.content : undefined
180
+ if (content === undefined) {
181
+ problems.push({ path: "content", message: "档案内容必须是字符串" })
182
+ }
183
+ if (!target || content === undefined) return { problems }
184
+
185
+ if (content.trim() === "") {
186
+ problems.push({ path: "content", message: "档案内容不能为空" })
187
+ }
188
+ const bytes = Buffer.byteLength(content, "utf8")
189
+ if (bytes > MAX_USER_MD_BYTES) {
190
+ problems.push({
191
+ path: "content",
192
+ message: `档案太大:最多 ${MAX_USER_MD_BYTES / 1024} KiB`,
193
+ })
194
+ }
195
+ if (!isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ)) {
196
+ problems.push({
197
+ path: "chat",
198
+ message: "这个聊天还没放行:先在准入名单里放行,再上传档案",
199
+ })
200
+ }
201
+ if (problems.length > 0) return { problems }
202
+
203
+ const path = pathOf(runtime, target)
204
+ await backupFile(path)
205
+ await writeTextAtomic(path, content)
206
+ const list = await listUserMd(runtime)
207
+ return {
208
+ problems: [],
209
+ result: {
210
+ chat: targetKey(target),
211
+ path,
212
+ bytes,
213
+ note: "已保存档案:新会话开始时会带上它,进行中的会话可以用 qq_read_user_md 读取。",
214
+ chats: list.chats,
215
+ maxBytes: MAX_USER_MD_BYTES,
216
+ },
217
+ }
218
+ }
@@ -13,15 +13,27 @@ export interface ClaimTimerOptions {
13
13
  onError: (error: unknown) => void
14
14
  }
15
15
 
16
+ /** 接管重试定时器的句柄。 */
17
+ export interface ClaimTimer {
18
+ /** 停掉定时器。 */
19
+ stop: () => void
20
+ /** 立刻试一次:被通知锁空出来了时不必等下一个周期。 */
21
+ wake: () => void
22
+ }
23
+
16
24
  /**
17
25
  * 启动接管重试定时器。
18
26
  *
19
27
  * 装上它就意味着后面还有重试的机会:首次初始化失败时靠它再搭一次,
20
28
  * 所以它必须先于第一次抢锁装好。
21
29
  */
22
- export function startClaimTimer(options: ClaimTimerOptions): { stop: () => void } {
23
- const timer = setInterval(() => {
30
+ export function startClaimTimer(options: ClaimTimerOptions): ClaimTimer {
31
+ // 同一时刻只跑一次尝试:唤醒和周期触发可能撞在一起。
32
+ let running = false
33
+ const attempt = (): void => {
34
+ if (running) return
24
35
  if (!options.shouldTry()) return
36
+ running = true
25
37
  void options
26
38
  .claim()
27
39
  .then(async (ok) => {
@@ -29,9 +41,14 @@ export function startClaimTimer(options: ClaimTimerOptions): { stop: () => void
29
41
  await options.onClaimed()
30
42
  })
31
43
  .catch((error: unknown) => options.onError(error))
32
- }, options.intervalMs)
44
+ .finally(() => {
45
+ running = false
46
+ })
47
+ }
48
+ const timer = setInterval(attempt, options.intervalMs)
33
49
  unrefTimer(timer)
34
50
  return {
35
51
  stop: () => clearInterval(timer),
52
+ wake: attempt,
36
53
  }
37
54
  }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 上游会话事件的订阅。
3
+ *
4
+ * 上游的事件流是全局的:订阅选项里没有按 location 过滤的条件。
5
+ * 每个 location 各订阅一份会把同一条事件处理 N 遍,
6
+ * 而运行时(会话管理器)全进程只有一份,所以整条链路只订阅一次。
7
+ */
8
+
9
+ import type { Plugin } from "@opencode/plugin"
10
+ import { delay } from "../async"
11
+ import type { Logger } from "../logger"
12
+ import type { SessionManager } from "../session/manager"
13
+
14
+ /** 事件订阅断了以后,隔多久重连。 */
15
+ const RETRY_DELAY_MS = 1000
16
+
17
+ /**
18
+ * 订阅上游会话事件。
19
+ *
20
+ * 会话空闲后把队列里缓存的消息合并成新的一轮。
21
+ * `session.status` 是官方推荐的状态信号;2.2.5 实际只在执行结束时发
22
+ * `session.execution.succeeded`,所以两者都要监听。失败或中断单独结束轮次。
23
+ * 订阅断掉后自动重连。
24
+ *
25
+ * @returns 中断订阅的函数。
26
+ */
27
+ export function subscribeSessionEvents(
28
+ ctx: Plugin.Context,
29
+ manager: SessionManager,
30
+ logger: Logger,
31
+ ): () => void {
32
+ const abort = new AbortController()
33
+ void (async () => {
34
+ while (!abort.signal.aborted) {
35
+ try {
36
+ for await (const event of ctx.event.subscribe({
37
+ types: [
38
+ "session.status",
39
+ "session.execution.succeeded",
40
+ "session.execution.failed",
41
+ "session.execution.interrupted",
42
+ ],
43
+ signal: abort.signal,
44
+ })) {
45
+ // 单条事件处理失败只记日志:连带把订阅循环拆掉会让缓存消息再也发不出去。
46
+ try {
47
+ const sessionID = event.data.sessionID
48
+ logger.debug(`上游事件:${event.type}`, {
49
+ sessionID,
50
+ ...(event.type === "session.status" ? { status: event.data.status.type } : {}),
51
+ })
52
+ if (event.type === "session.status") {
53
+ if (event.data.status.type === "idle") await manager.flushBuffered(sessionID)
54
+ } else if (event.type === "session.execution.succeeded") {
55
+ await manager.flushBuffered(sessionID)
56
+ } else {
57
+ // 失败事件带上游错误信息,只进日志(logger 会脱敏),不进聊天。
58
+ const detail =
59
+ event.type === "session.execution.failed" ? event.data.error.message : undefined
60
+ await manager.handleExecutionEnd(sessionID, event.type, detail)
61
+ }
62
+ } catch (error) {
63
+ logger.warn("处理会话事件失败", error)
64
+ }
65
+ }
66
+ } catch (error) {
67
+ if (abort.signal.aborted) break
68
+ logger.error("订阅会话事件失败,稍后重试", error)
69
+ }
70
+ if (!abort.signal.aborted) await delay(RETRY_DELAY_MS)
71
+ }
72
+ })()
73
+ return () => abort.abort()
74
+ }
@@ -0,0 +1,336 @@
1
+ /**
2
+ * 按 location 注册的本地服务。
3
+ *
4
+ * OpenCode 会为每个用到的目录各加载一次插件,工具与钩子按 location 隔离:
5
+ * 目录里的会话只能用这一侧注册的工具。NapCat 连接只有一条:
6
+ * 拿到机器级锁的实例搭好运行时并发布,其它 location 的实例在这里
7
+ * 用那份运行时注册自己这一侧的工具与钩子。
8
+ */
9
+
10
+ import type { Plugin } from "@opencode/plugin"
11
+ import { parseTargetKey, targetKey, targetLabel } from "../chat"
12
+ import { Cleanup, CleanupOrder } from "../cleanup"
13
+ import type { CommandDefinition } from "../commands"
14
+ import type { QQBotConfig } from "../config"
15
+ import type { DiaryStore } from "../diary/store"
16
+ import type { DiarySummarizer } from "../diary/summary"
17
+ import type { CollectionStore, RecentImages } from "../emoji/collection"
18
+ import type { FavoriteIndex } from "../emoji/favorite-index"
19
+ import type { FavoriteStore } from "../emoji/favorites"
20
+ import type { EmojiLabeler } from "../emoji/label"
21
+ import type { NoticeStore } from "../events/store"
22
+ import type { Logger } from "../logger"
23
+ import type { QQClient } from "../naplink/client"
24
+ import { type ChatOverrides, type WakeReason } from "../overrides"
25
+ import type { SendRateLimiter } from "../rate-limit"
26
+ import type { SensitiveChecker } from "../sensitive"
27
+ import type { SessionManager } from "../session/manager"
28
+ import { currentTimeText } from "../session/prompt"
29
+ import type { SoulLibrary } from "../session/soul"
30
+ import { registerAskGuard } from "../tools/ask-guard"
31
+ import { registerSendGuard } from "../tools/send-guard"
32
+ import type { ToolPolicy } from "../tools/policy"
33
+ import { registerToolPolicy } from "../tools/policy-guard"
34
+ import { QQ_REQUEST_REPLY_TOOL, registerTools, TOOL_NAMESPACE } from "../tools/qq"
35
+ import type { Tracer } from "../trace"
36
+ import { registerTuiCommands } from "../tui-commands"
37
+ import type { UserInjector } from "../user/inject"
38
+ import type { UserStore } from "../user/store"
39
+ import type { ChatWorkspaces } from "../workspace"
40
+
41
+ /** 必回原因对应给模型的一句话。 */
42
+ function wakeHint(reason: WakeReason | undefined): string {
43
+ switch (reason) {
44
+ case "private":
45
+ return "这是一条私聊消息,必须回复。"
46
+ case "all":
47
+ return "这个群要求每条消息都回复,必须回复。"
48
+ case "mention":
49
+ return "你被 @ 了,必须回复。"
50
+ case "prefix":
51
+ return "这条消息命中了唤醒前缀,必须回复。"
52
+ case "at_all":
53
+ return "这条消息 @ 了全体成员,必须回复。"
54
+ case "reply":
55
+ return "这条消息回复了你,必须回复。"
56
+ default:
57
+ return "这条消息没有要求你回复,可以选择不回复。"
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 进程内共享的运行时。
63
+ *
64
+ * 持有机器级锁的实例搭好它并发布:NapCat 连接、会话管理器、角色设定这些
65
+ * 全机器只有一份,其它 location 的实例复用同一份。
66
+ */
67
+ export interface QQBotRuntime {
68
+ souls: SoulLibrary
69
+ client: QQClient
70
+ workspaces: ChatWorkspaces
71
+ users: UserStore
72
+ userInjector: UserInjector
73
+ limiter: SendRateLimiter
74
+ sensitive: SensitiveChecker
75
+ noticeStore: NoticeStore
76
+ policy: ToolPolicy
77
+ overrides: ChatOverrides
78
+ tracer: Tracer | undefined
79
+ manager: SessionManager
80
+ favorites: FavoriteStore
81
+ favoriteIndex: FavoriteIndex
82
+ collection: CollectionStore
83
+ recentImages: RecentImages
84
+ labeler: EmojiLabeler
85
+ diaryStore: DiaryStore
86
+ diarySummarizer: DiarySummarizer
87
+ commands: readonly CommandDefinition[]
88
+ /**
89
+ * 机器级锁还在不在:不在就不能发送。
90
+ *
91
+ * 这个闭包来自持锁的实例:复用运行时的其它 location 读到的也是持有者的锁状态。
92
+ * 机器锁全机器一把,这样才是对的。
93
+ */
94
+ canSend: () => boolean
95
+ }
96
+
97
+ /**
98
+ * 在当前 location 注册工具与钩子。
99
+ *
100
+ * 注册的是这一侧的工具表:目录里的会话因此能用 QQ 工具。
101
+ * 返回注销函数:运行时换代时先撤掉这一份,再按新运行时注册一遍。
102
+ */
103
+ export async function registerLocalServices(
104
+ ctx: Plugin.Context,
105
+ config: QQBotConfig,
106
+ logger: Logger,
107
+ runtime: QQBotRuntime,
108
+ ): Promise<() => Promise<void>> {
109
+ const cleanup = new Cleanup()
110
+ try {
111
+ await registerLocal(ctx, config, logger, runtime, cleanup)
112
+ } catch (error) {
113
+ // 注册中途失败:已经注册成功的部分先撤掉,不能留在这一侧。
114
+ await cleanup.run(logger)
115
+ throw error
116
+ }
117
+ return () => cleanup.run(logger)
118
+ }
119
+
120
+ /**
121
+ * 把这一侧的本地服务注册上去。
122
+ *
123
+ * 注销动作都记在 `cleanup` 里:中途失败时调用方拿它把已注册的部分撤掉。
124
+ */
125
+ async function registerLocal(
126
+ ctx: Plugin.Context,
127
+ config: QQBotConfig,
128
+ logger: Logger,
129
+ runtime: QQBotRuntime,
130
+ cleanup: Cleanup,
131
+ ): Promise<void> {
132
+ const {
133
+ manager,
134
+ client,
135
+ policy,
136
+ overrides,
137
+ limiter,
138
+ souls,
139
+ labeler,
140
+ diarySummarizer,
141
+ userInjector,
142
+ noticeStore,
143
+ tracer,
144
+ favorites,
145
+ favoriteIndex,
146
+ collection,
147
+ recentImages,
148
+ sensitive,
149
+ workspaces,
150
+ diaryStore,
151
+ users,
152
+ commands,
153
+ } = runtime
154
+
155
+ const registration = await registerTools({
156
+ ctx,
157
+ config,
158
+ logger,
159
+ manager,
160
+ client,
161
+ favorites,
162
+ favoriteIndex,
163
+ collection,
164
+ recentImages,
165
+ limiter,
166
+ sensitive,
167
+ workspaces,
168
+ diary: diaryStore,
169
+ users,
170
+ overrides,
171
+ tracer,
172
+ // 没有机器级锁就发不出去:那是别的实例的机器人。
173
+ canSend: runtime.canSend,
174
+ })
175
+ cleanup.add("注销工具", () => registration.dispose(), CleanupOrder.tools)
176
+
177
+ const tuiCommands = await registerTuiCommands({
178
+ ctx,
179
+ config,
180
+ logger,
181
+ manager,
182
+ policy,
183
+ overrides,
184
+ client,
185
+ limiter,
186
+ commands,
187
+ })
188
+ cleanup.add("注销 TUI 命令", () => tuiCommands.dispose(), CleanupOrder.tui)
189
+
190
+ // QQ 会话里禁止模型调用内置 question 工具,改用 qq_send_message 询问用户。
191
+ const askGuard = await registerAskGuard({ ctx, logger, manager })
192
+ // 禁止连续调用发送工具,避免同一条消息被重复发送。
193
+ const sendGuard = await registerSendGuard({ ctx, logger, manager })
194
+ // 按聊天与角色收窄工具:上下文里先删,执行前再挡一次。
195
+ const toolPolicy = await registerToolPolicy({ ctx, logger, manager, policy, overrides })
196
+ cleanup.add(
197
+ "注销工具守卫",
198
+ async () => {
199
+ await askGuard.dispose()
200
+ await sendGuard.dispose()
201
+ await toolPolicy.dispose()
202
+ },
203
+ CleanupOrder.guards,
204
+ )
205
+
206
+ // 系统提示:角色设定、当前时间、本轮是否必须回复。
207
+ const contextRegistration = await ctx.session.hook("context", async (event) => {
208
+ const target = manager.targetForSession(event.sessionID)
209
+ if (target === undefined) {
210
+ // 表情标签会话不绑定 QQ 目标,拿不到按聊天的工具限制;
211
+ // 它的输入是一张图片,工具一律摘掉,只让模型输出标签。
212
+ if (await labeler.isLabelSession(event.sessionID)) {
213
+ for (const name of Object.keys(event.tools)) delete event.tools[name]
214
+ return
215
+ }
216
+ // 日记生成会话的输入是群友可控的聊天记录,同样不带任何工具;
217
+ // 但它仍是一轮正常对话,先注入角色设定,日记才有人格。
218
+ if (await diarySummarizer.isSummarySession(event.sessionID)) {
219
+ // 人格取这个生成会话所属聊天上的覆盖,没有覆盖就用默认档。
220
+ const chat = await diarySummarizer.chatForSession(event.sessionID)
221
+ const scopeTarget = chat ? parseTargetKey(chat) : undefined
222
+ const override = scopeTarget ? await overrides.for(scopeTarget) : undefined
223
+ const soul = await souls.at(override?.soulPath, override?.soulName)
224
+ // 只注入角色设定正文:`soul.prompt` 还带着「必须调用 qq_send_message」
225
+ // 的 QQ 守则,而生成会话没有任何工具,带上会让模型无所适从。
226
+ const persona = soul.text.trim()
227
+ if (persona) event.system.push({ type: "text", text: persona })
228
+ for (const name of Object.keys(event.tools)) delete event.tools[name]
229
+ }
230
+ return
231
+ }
232
+ // 角色设定可以按聊天覆盖:先看覆盖里写的 soulPath / soulName,没有就用默认档。
233
+ const override = await overrides.for(target)
234
+ const soul = await souls.at(override.soulPath, override.soulName)
235
+ event.system.push({ type: "text", text: soul.prompt })
236
+ event.system.push({
237
+ type: "text",
238
+ text: `当前时间:${currentTimeText(config.timezone)}`,
239
+ })
240
+ // 用户档案与画像:每个会话只在开头注入一次,之后模型自己按需用工具取。
241
+ const userContext = await userInjector.injectOnce(event.sessionID, target)
242
+ if (userContext) {
243
+ event.system.push({ type: "text", text: userContext })
244
+ }
245
+ const active = manager.activeTurn(event.sessionID)
246
+ const turn = active?.turn
247
+ const role = active?.role ?? manager.currentRole(event.sessionID)
248
+ logger.debug(`上下文钩子:会话 ${event.sessionID}`, {
249
+ target: targetLabel(target),
250
+ role,
251
+ proactive: turn?.proactive === true,
252
+ atMe: turn?.atMe,
253
+ suppress: turn?.suppress,
254
+ tools: Object.keys(event.tools).length,
255
+ ...(turn?.traceId ? { trace_id: turn.traceId } : {}),
256
+ })
257
+ const destination = target.kind === "group" ? "群里" : "私聊里"
258
+ // 模型开始处理这一轮:记一个追踪节点。
259
+ if (turn?.traceId) {
260
+ await tracer?.record(
261
+ "handler_start",
262
+ turn.traceId,
263
+ { session_id: event.sessionID },
264
+ targetKey(target),
265
+ )
266
+ }
267
+ event.system.push({
268
+ type: "text",
269
+ text: turn?.proactive
270
+ ? `这是一次主动发起话题,必须调用 qq_send_message 把话题发到${destination}。${target.kind === "group" && config.reply.requirePermission ? "群里要先调用 qq_request_reply 说明为什么要回复,说明之后才能发送。" : ""}`
271
+ : turn?.atMe
272
+ ? wakeHint(turn.wake)
273
+ : turn?.suppress
274
+ ? "这条消息不是在跟你说话,不要回复。"
275
+ : wakeHint(undefined),
276
+ })
277
+ // 待注入的通知:作为附带信息出现,不要求模型回复。
278
+ const notices = noticeStore.take(target)
279
+ if (notices.length > 0) {
280
+ event.system.push({
281
+ type: "text",
282
+ text: `聊天里发生过的通知(不需要回复):\n${notices.map((item) => `- ${item}`).join("\n")}`,
283
+ })
284
+ }
285
+ // 群里默认不主动发言:模型得先想清楚该不该回复,说明理由才发。
286
+ if (target.kind === "group" && config.reply.requirePermission) {
287
+ event.system.push({
288
+ type: "text",
289
+ text: `按约定,你在群里不会主动发消息。要回复,先判断该不该回复,再调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;说明之后才能调用 qq_send_message,这个约定只在本轮有效。`,
290
+ })
291
+ }
292
+ // 本轮发送者的角色决定工具档:owner / admin 全开,其他按聊天配置。
293
+ // 角色按会话保留,没有在途轮次(重启、TUI 驱动)时也照样收窄。
294
+ {
295
+ const allowed = await policy.allow(role, override.profile, Object.keys(event.tools))
296
+ const removed: string[] = []
297
+ for (const name of Object.keys(event.tools)) {
298
+ // 申请回复权限的工具必须一直留着:不然模型永远拿不到发送权限。
299
+ if (name === QQ_REQUEST_REPLY_TOOL) continue
300
+ if (!allowed.has(name)) {
301
+ removed.push(name)
302
+ delete event.tools[name]
303
+ }
304
+ }
305
+ const profile = await policy.profileOf(role, override.profile)
306
+ // 模型这一轮实际能用的 QQ 工具:模型只认这些名字,缺一个就发不出消息。
307
+ const qqTools = Object.keys(event.tools).filter((name) =>
308
+ name.startsWith(`${TOOL_NAMESPACE}_`),
309
+ )
310
+ logger.debug(`上下文钩子:按角色收窄工具`, {
311
+ target: targetLabel(target),
312
+ role,
313
+ profile,
314
+ removed,
315
+ qqTools,
316
+ })
317
+ if (!qqTools.includes("qq_send_message")) {
318
+ logger.warn(`${targetLabel(target)} 模型这一轮看不到 qq_send_message,发不出消息`, {
319
+ role,
320
+ profile,
321
+ removed,
322
+ })
323
+ }
324
+ }
325
+ })
326
+ cleanup.add("注销上下文钩子", () => contextRegistration.dispose(), CleanupOrder.hooks)
327
+
328
+ // 会话空闲:冲刷缓存消息,或提醒模型补一次发送。
329
+ const idleRegistration = await ctx.session.hook("experimental.idle", async (event) => {
330
+ logger.debug(`experimental.idle 钩子:会话 ${event.sessionID}`, {
331
+ background: event.background.map((task) => task.sessionID),
332
+ })
333
+ await manager.handleIdle(event.sessionID, event.background)
334
+ })
335
+ cleanup.add("注销空闲钩子", () => idleRegistration.dispose(), CleanupOrder.hooks)
336
+ }