@cmach_socket/opencode-qq-bot 1.0.0 → 2.0.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.
- package/README.md +15 -319
- package/chat-overrides.example.json +13 -3
- package/package.json +4 -1
- package/src/commands.ts +7 -7
- package/src/config/fields.ts +3 -27
- package/src/config/live.ts +2 -2
- package/src/config/store.ts +9 -0
- package/src/config/types.ts +2 -8
- package/src/config.ts +5 -12
- package/src/diary/command.ts +10 -8
- package/src/diary/scheduler.ts +11 -11
- package/src/diary/scope.ts +14 -23
- package/src/diary/summary.ts +91 -57
- package/src/fs/atomic.ts +17 -5
- package/src/home.ts +7 -7
- package/src/index.ts +57 -41
- package/src/media-path.ts +2 -12
- package/src/naplink/client.ts +50 -1
- package/src/naplink/history.ts +9 -2
- package/src/naplink/media.ts +3 -5
- package/src/naplink/render.ts +10 -3
- package/src/overrides.ts +43 -36
- package/src/panel/documents.ts +32 -44
- package/src/panel/server.ts +8 -1
- package/src/panel/status.ts +7 -1
- package/src/session/find.ts +2 -3
- package/src/session/manager.ts +27 -40
- package/src/tools/policy-guard.ts +9 -5
- package/src/tools/policy.ts +59 -37
- package/src/tools/qq.ts +132 -41
- package/src/user/inject.ts +66 -0
- package/src/user/store.ts +93 -0
- package/src/workspace.ts +113 -0
- package/tool-profiles.example.json +0 -4
- package/web/dist/assets/{index-B-3ZGYMq.js → index-Be9cCNMT.js} +2 -2
- package/web/dist/index.html +1 -1
package/src/panel/documents.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { defaultToolPolicy, parseToolPolicy, resolveToolProfilesPath } from "../
|
|
|
17
17
|
import type { PanelRuntime } from "./runtime"
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
|
-
* 面板里的两个独立配置文件:`chat-overrides.json` 与 `tool-profiles.json`。
|
|
20
|
+
* 面板里的两个独立配置文件:`config/chat-overrides.json` 与 `config/tool-profiles.json`。
|
|
21
21
|
*
|
|
22
22
|
* 两个文件都不是全局配置,粒度与生命周期都不一样,所以各自独立成页。
|
|
23
23
|
* 校验一律复用运行时的解析函数:面板不该自己写一套规则,
|
|
@@ -67,12 +67,14 @@ const CHAT_OVERRIDE_FIELDS = [
|
|
|
67
67
|
"wake.ignorePrefixes",
|
|
68
68
|
"proactive.enabled",
|
|
69
69
|
"proactive.startProbability",
|
|
70
|
+
"diary.enabled",
|
|
70
71
|
"collect.privateMs",
|
|
71
72
|
"collect.groupMs",
|
|
72
73
|
"agent",
|
|
73
74
|
"model",
|
|
74
75
|
"soulPath",
|
|
75
76
|
"soulName",
|
|
77
|
+
"profile",
|
|
76
78
|
] as const
|
|
77
79
|
|
|
78
80
|
/** 配置档名字的约束:不为空、不含空格与控制字符、最长 64 个字符。 */
|
|
@@ -85,7 +87,7 @@ const BUILTIN_PROFILES = Object.keys(defaultToolPolicy().profiles)
|
|
|
85
87
|
const CHAT_OVERRIDE_KEYS = ["chats"] as const
|
|
86
88
|
|
|
87
89
|
/** 工具配置文件里允许出现的顶层字段。 */
|
|
88
|
-
const TOOL_POLICY_KEYS = ["defaultProfile", "profiles"
|
|
90
|
+
const TOOL_POLICY_KEYS = ["defaultProfile", "profiles"] as const
|
|
89
91
|
|
|
90
92
|
/** 保存文档时的锁重试参数。 */
|
|
91
93
|
const LOCK_RETRIES = { retries: 10, factor: 1.5, minTimeout: 20, maxTimeout: 200 }
|
|
@@ -181,7 +183,7 @@ async function readJsonFile(path: string): Promise<{ raw: unknown; exists: boole
|
|
|
181
183
|
}
|
|
182
184
|
}
|
|
183
185
|
|
|
184
|
-
/** 写文件:先备份,再原子写。权限与 `config.json` 一致。 */
|
|
186
|
+
/** 写文件:先备份,再原子写。权限与 `config/config.json` 一致。 */
|
|
185
187
|
async function writeDocument(path: string, value: unknown): Promise<void> {
|
|
186
188
|
await backupFile(path)
|
|
187
189
|
await writeJsonAtomic(path, value)
|
|
@@ -315,6 +317,9 @@ export async function saveChatOverrides(
|
|
|
315
317
|
const base = isPlainObject(source.chats) ? copyToSafeMap(source.chats) : safeMap()
|
|
316
318
|
const chats = isPlainObject(patch) ? patch : {}
|
|
317
319
|
const warnings: string[] = []
|
|
320
|
+
// 配置档名字来自 config/tool-profiles.json:写进去的档位必须真的存在。
|
|
321
|
+
const policyFile = await runtime.policy?.current()
|
|
322
|
+
const profileNames = policyFile ? Object.keys(policyFile.profiles) : []
|
|
318
323
|
for (const key of Object.keys(body)) {
|
|
319
324
|
if (!(CHAT_OVERRIDE_KEYS as readonly string[]).includes(key)) {
|
|
320
325
|
warnings.push(`未知字段 ${key},已忽略`)
|
|
@@ -398,6 +403,17 @@ export async function saveChatOverrides(
|
|
|
398
403
|
if (typeof current.soulName === "string" && normalized.soulName === undefined) {
|
|
399
404
|
normalized.soulName = current.soulName
|
|
400
405
|
}
|
|
406
|
+
// 档名必须真的存在:读不到工具配置时一律拒绝写入,而不是放行任意档名。
|
|
407
|
+
if (normalized.profile && !profileNames.includes(normalized.profile)) {
|
|
408
|
+
problems.push({
|
|
409
|
+
path: `${field}.profile`,
|
|
410
|
+
message:
|
|
411
|
+
profileNames.length > 0
|
|
412
|
+
? `配置档 ${normalized.profile} 不存在`
|
|
413
|
+
: `读不到工具配置,无法确认配置档 ${normalized.profile} 是否存在`,
|
|
414
|
+
})
|
|
415
|
+
continue
|
|
416
|
+
}
|
|
401
417
|
base[key] = normalized
|
|
402
418
|
}
|
|
403
419
|
if (problems.length > 0) return { status: "invalid" }
|
|
@@ -447,13 +463,9 @@ export async function saveToolProfiles(
|
|
|
447
463
|
return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
|
|
448
464
|
}
|
|
449
465
|
const profilePatch = body.profiles
|
|
450
|
-
const chatPatch = body.chats
|
|
451
466
|
if (profilePatch !== undefined && !isPlainObject(profilePatch)) {
|
|
452
467
|
problems.push({ path: "profiles", message: "profiles 必须是对象" })
|
|
453
468
|
}
|
|
454
|
-
if (chatPatch !== undefined && !isPlainObject(chatPatch)) {
|
|
455
|
-
problems.push({ path: "chats", message: "chats 必须是对象" })
|
|
456
|
-
}
|
|
457
469
|
if (problems.length > 0) return { problems }
|
|
458
470
|
|
|
459
471
|
const path = toolProfilesPath(runtime)
|
|
@@ -463,9 +475,6 @@ export async function saveToolProfiles(
|
|
|
463
475
|
const baseProfiles: Record<string, unknown> = isPlainObject(source.profiles)
|
|
464
476
|
? copyToSafeMap(source.profiles)
|
|
465
477
|
: safeMap()
|
|
466
|
-
const baseChats: Record<string, unknown> = isPlainObject(source.chats)
|
|
467
|
-
? copyToSafeMap(source.chats)
|
|
468
|
-
: safeMap()
|
|
469
478
|
let defaultProfile = typeof source.defaultProfile === "string" ? source.defaultProfile : ""
|
|
470
479
|
// 置空表示回到内置默认档:文件里干脆不写这个键,界面也就能显示「跟随默认」。
|
|
471
480
|
let omitDefault = false
|
|
@@ -537,25 +546,10 @@ export async function saveToolProfiles(
|
|
|
537
546
|
baseProfiles[name] = parsed.profiles[name] ?? { allow: [], deny: [] }
|
|
538
547
|
}
|
|
539
548
|
|
|
540
|
-
for (const
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
continue
|
|
545
|
-
}
|
|
546
|
-
if (value === null) {
|
|
547
|
-
if (!hasKey(baseChats, key)) {
|
|
548
|
-
problems.push({ path: field, message: `聊天映射 ${key} 不存在` })
|
|
549
|
-
continue
|
|
550
|
-
}
|
|
551
|
-
delete baseChats[key]
|
|
552
|
-
continue
|
|
553
|
-
}
|
|
554
|
-
if (typeof value !== "string" || !value.trim()) {
|
|
555
|
-
problems.push({ path: field, message: "聊天映射必须是一个配置档名字" })
|
|
556
|
-
continue
|
|
557
|
-
}
|
|
558
|
-
baseChats[key] = value.trim()
|
|
549
|
+
for (const key of Object.keys(isPlainObject(body.chats) ? body.chats : {})) {
|
|
550
|
+
warnings.push(
|
|
551
|
+
`chats 段已迁移到 config/chat-overrides.json 的 chats.<聊天>.profile,已忽略 ${key}`,
|
|
552
|
+
)
|
|
559
553
|
}
|
|
560
554
|
|
|
561
555
|
if (body.defaultProfile !== undefined) {
|
|
@@ -573,9 +567,8 @@ export async function saveToolProfiles(
|
|
|
573
567
|
if (problems.length > 0) return { status: "invalid" }
|
|
574
568
|
|
|
575
569
|
// 引用检查:档名必须存在,否则运行时会落到默认档,页面上写的意图等于白写。
|
|
576
|
-
const effective = parseToolPolicy(
|
|
577
|
-
|
|
578
|
-
(message) => warnings.push(message),
|
|
570
|
+
const effective = parseToolPolicy({ defaultProfile, profiles: baseProfiles }, (message) =>
|
|
571
|
+
warnings.push(message),
|
|
579
572
|
)
|
|
580
573
|
if (defaultProfile && !hasKey(effective.profiles, defaultProfile)) {
|
|
581
574
|
problems.push({
|
|
@@ -585,29 +578,24 @@ export async function saveToolProfiles(
|
|
|
585
578
|
: `defaultProfile 指向不存在的配置档 ${defaultProfile}`,
|
|
586
579
|
})
|
|
587
580
|
}
|
|
588
|
-
for (const [key, name] of Object.entries(effective.chats)) {
|
|
589
|
-
if (!hasKey(effective.profiles, name)) {
|
|
590
|
-
problems.push({
|
|
591
|
-
path: `chats.${key}`,
|
|
592
|
-
message: deletedProfiles.has(name)
|
|
593
|
-
? `配置档 ${name} 已被删除,但 chats.${key} 还在引用它`
|
|
594
|
-
: `chats.${key} 指向不存在的配置档 ${name}`,
|
|
595
|
-
})
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
581
|
if (problems.length > 0) return { status: "invalid" }
|
|
599
582
|
|
|
600
583
|
// 文件里的其它顶层键原样保留:面板只管自己那几个字段,不该把别的抹掉。
|
|
601
584
|
const next = copyToSafeMap(source)
|
|
602
585
|
delete next.defaultProfile
|
|
603
586
|
delete next.profiles
|
|
604
|
-
|
|
587
|
+
// 旧的 chats 段不再有效:按聊天的配置档写在 config/chat-overrides.json 里。
|
|
588
|
+
if (hasKey(source, "chats")) {
|
|
589
|
+
warnings.push(
|
|
590
|
+
"config/tool-profiles.json 的 chats 段已迁移到 config/chat-overrides.json,已删除",
|
|
591
|
+
)
|
|
592
|
+
delete next.chats
|
|
593
|
+
}
|
|
605
594
|
// 默认档没被指定过就不写进文件:写死了就分不清「用户选的」与「内置的」。
|
|
606
595
|
if (!omitDefault && (defaultProfile || hasKey(source, "defaultProfile"))) {
|
|
607
596
|
next.defaultProfile = defaultProfile || effective.defaultProfile
|
|
608
597
|
}
|
|
609
598
|
next.profiles = baseProfiles
|
|
610
|
-
next.chats = baseChats
|
|
611
599
|
await writeDocument(path, next)
|
|
612
600
|
|
|
613
601
|
const document = await readToolProfiles(runtime)
|
package/src/panel/server.ts
CHANGED
|
@@ -200,7 +200,14 @@ export class PanelServer {
|
|
|
200
200
|
*/
|
|
201
201
|
private async bind(app: ReturnType<typeof createPanelApp>, host: string, port: number) {
|
|
202
202
|
for (let attempt = 0; ; attempt++) {
|
|
203
|
-
|
|
203
|
+
// 面板和 OpenCode 宿主同进程,不能劫持宿主的全局 Request/Response:
|
|
204
|
+
// @hono/node-server 默认会用轻量版替换全局对象,宿主里的原生 HTTP 路径
|
|
205
|
+
// 会因此报 "Expected a Response object, but received 'Response (lightweight)'"。
|
|
206
|
+
const server = createAdaptorServer({
|
|
207
|
+
fetch: app.fetch,
|
|
208
|
+
hostname: host,
|
|
209
|
+
overrideGlobalObjects: false,
|
|
210
|
+
})
|
|
204
211
|
try {
|
|
205
212
|
await new Promise<void>((resolve, reject) => {
|
|
206
213
|
const onError = (error: Error) => {
|
package/src/panel/status.ts
CHANGED
|
@@ -135,6 +135,12 @@ export async function collectStatus(runtime: PanelRuntime): Promise<StatusSnapsh
|
|
|
135
135
|
const sessions = await collectSessions(runtime)
|
|
136
136
|
const policy = await runtime.policy?.current()
|
|
137
137
|
const diary = runtime.diary
|
|
138
|
+
// 按聊天指定的配置档写在会话覆盖里。
|
|
139
|
+
const overrideFile = await runtime.overrides?.current()
|
|
140
|
+
const chatProfiles: Record<string, string> = {}
|
|
141
|
+
for (const [key, override] of Object.entries(overrideFile?.chats ?? {})) {
|
|
142
|
+
if (override.profile) chatProfiles[key] = override.profile
|
|
143
|
+
}
|
|
138
144
|
return {
|
|
139
145
|
version: runtime.version,
|
|
140
146
|
startedAt: runtime.startedAt,
|
|
@@ -178,7 +184,7 @@ export async function collectStatus(runtime: PanelRuntime): Promise<StatusSnapsh
|
|
|
178
184
|
policy: {
|
|
179
185
|
defaultProfile: policy?.defaultProfile ?? "chat",
|
|
180
186
|
profiles: policy ? Object.keys(policy.profiles) : [],
|
|
181
|
-
chats:
|
|
187
|
+
chats: chatProfiles,
|
|
182
188
|
},
|
|
183
189
|
}
|
|
184
190
|
}
|
package/src/session/find.ts
CHANGED
|
@@ -24,13 +24,12 @@ export interface FindOptions {
|
|
|
24
24
|
* 在指定目录下按谓词查找会话。
|
|
25
25
|
*
|
|
26
26
|
* 列表按创建时间倒序、翻页上限固定,避免会话很多时把整个列表拉一遍。
|
|
27
|
-
* 不传目录时查的是全部目录:老版本把会话建在项目目录里,只按工作目录找会漏掉。
|
|
28
27
|
*
|
|
29
28
|
* @returns 命中的会话;找不到或查询失败时返回空数组。
|
|
30
29
|
*/
|
|
31
30
|
export async function findSessions(
|
|
32
31
|
ctx: Plugin.Context,
|
|
33
|
-
directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"]
|
|
32
|
+
directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
|
|
34
33
|
match: (session: ListedSession) => boolean,
|
|
35
34
|
logger: Logger,
|
|
36
35
|
failure: string,
|
|
@@ -44,7 +43,7 @@ export async function findSessions(
|
|
|
44
43
|
try {
|
|
45
44
|
for (let page = 0; page < maxPages && found.length < limit; page += 1) {
|
|
46
45
|
const result = await ctx.session.list({
|
|
47
|
-
|
|
46
|
+
directory,
|
|
48
47
|
limit: pageSize,
|
|
49
48
|
order: "desc",
|
|
50
49
|
...(cursor ? { cursor } : {}),
|
package/src/session/manager.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolve } from "node:path"
|
|
1
2
|
import type { Plugin } from "@opencode/plugin"
|
|
2
3
|
import type { Location } from "@opencode/schema"
|
|
3
4
|
import { SessionMessage } from "@opencode/schema"
|
|
@@ -21,6 +22,7 @@ import { acquireStateLock, type StateLock } from "../state-lock"
|
|
|
21
22
|
import { limitFiles, type PromptFile } from "../naplink/render"
|
|
22
23
|
import type { WakeReason } from "../overrides"
|
|
23
24
|
import { roleForChat, roleOf, type Role } from "../tools/policy"
|
|
25
|
+
import { chatWorkspace } from "../workspace"
|
|
24
26
|
import { findSessions, type ListedSession } from "./find"
|
|
25
27
|
|
|
26
28
|
/** 插件存储里保存会话与目标绑定的键。 */
|
|
@@ -57,8 +59,6 @@ export const SESSION_RETIRE_COOLDOWN_MS = 10 * 60 * 1000
|
|
|
57
59
|
const HANDOVER_WAIT_MS = 3_000
|
|
58
60
|
/** 找回历史会话时最多比较几个候选。 */
|
|
59
61
|
const SESSION_CANDIDATES = 5
|
|
60
|
-
/** 全局找历史会话时最多翻几页。 */
|
|
61
|
-
const SESSION_SEARCH_PAGES = 5
|
|
62
62
|
/** 共享状态写锁被占用时最多重试几次。 */
|
|
63
63
|
const PERSIST_RETRY_LIMIT = 5
|
|
64
64
|
/** 第一次重试等待多久(毫秒),之后按倍数退避。 */
|
|
@@ -488,10 +488,11 @@ export class SessionManager {
|
|
|
488
488
|
private readonly canWrite?: () => boolean,
|
|
489
489
|
) {}
|
|
490
490
|
|
|
491
|
-
/**
|
|
492
|
-
private
|
|
493
|
-
|
|
494
|
-
|
|
491
|
+
/** 每个聊天的会话各自落在自己的工作目录里。 */
|
|
492
|
+
private locationFor(target: ChatTarget): Location.PublicRef {
|
|
493
|
+
const { directory } = chatWorkspace(this.home.directory, target)
|
|
494
|
+
// 目录由聊天目标拼出来,这里只是把字符串还原成品牌类型。
|
|
495
|
+
return { directory: directory as Location.PublicRef["directory"] }
|
|
495
496
|
}
|
|
496
497
|
|
|
497
498
|
/** 载入上次运行时保存的目标与会话绑定。 */
|
|
@@ -1147,7 +1148,7 @@ export class SessionManager {
|
|
|
1147
1148
|
)
|
|
1148
1149
|
continue
|
|
1149
1150
|
}
|
|
1150
|
-
if (item.sessionID && !(await this.sessionExists(item.sessionID))) {
|
|
1151
|
+
if (item.sessionID && !(await this.sessionExists(item.target, item.sessionID))) {
|
|
1151
1152
|
this.logger.warn(
|
|
1152
1153
|
`${targetLabel(item.target)} 交接时会话 ${item.sessionID} 已不存在,丢弃这轮状态`,
|
|
1153
1154
|
)
|
|
@@ -2150,7 +2151,7 @@ export class SessionManager {
|
|
|
2150
2151
|
// 已经失效的会话:复用时也不能再选它,否则会绑到一个不存在的会话上。
|
|
2151
2152
|
let stale: string | undefined
|
|
2152
2153
|
if (state.sessionID) {
|
|
2153
|
-
if (await this.sessionExists(state.sessionID)) {
|
|
2154
|
+
if (await this.sessionExists(target, state.sessionID)) {
|
|
2154
2155
|
await this.applyOverride(state.sessionID, label, agent, model)
|
|
2155
2156
|
return state.sessionID
|
|
2156
2157
|
}
|
|
@@ -2181,7 +2182,7 @@ export class SessionManager {
|
|
|
2181
2182
|
|
|
2182
2183
|
const created = await this.ctx.session.create({
|
|
2183
2184
|
title: targetSessionTitle(target),
|
|
2184
|
-
location: this.
|
|
2185
|
+
location: this.locationFor(target),
|
|
2185
2186
|
...(agent ? { agent } : {}),
|
|
2186
2187
|
...(model ? { model } : {}),
|
|
2187
2188
|
metadata: {
|
|
@@ -2249,40 +2250,19 @@ export class SessionManager {
|
|
|
2249
2250
|
if (metadata["qqTargetId"] !== target.id) return false
|
|
2250
2251
|
return session.id !== exclude
|
|
2251
2252
|
}
|
|
2252
|
-
const title = targetSessionTitle(target)
|
|
2253
|
-
const byTitle = (session: ListedSession) => session.title === title && session.id !== exclude
|
|
2254
2253
|
const collect = async (
|
|
2255
|
-
directory: string
|
|
2254
|
+
directory: string,
|
|
2256
2255
|
failure: string,
|
|
2257
2256
|
options: { limit: number; maxPages?: number },
|
|
2258
2257
|
match: (session: ListedSession) => boolean,
|
|
2259
2258
|
): Promise<ListedSession[]> =>
|
|
2260
2259
|
await findSessions(this.ctx, directory, match, this.logger, failure, options)
|
|
2261
|
-
|
|
2262
|
-
this.
|
|
2260
|
+
return await collect(
|
|
2261
|
+
this.locationFor(target).directory,
|
|
2263
2262
|
`查找历史会话失败 ${targetLabel(target)}`,
|
|
2264
2263
|
{ limit: SESSION_CANDIDATES },
|
|
2265
2264
|
byMetadata,
|
|
2266
2265
|
)
|
|
2267
|
-
if (inWorkspace.length > 0) return inWorkspace
|
|
2268
|
-
const titled = await collect(
|
|
2269
|
-
this.location.directory,
|
|
2270
|
-
`查找历史会话失败 ${targetLabel(target)}`,
|
|
2271
|
-
{ limit: SESSION_CANDIDATES },
|
|
2272
|
-
byTitle,
|
|
2273
|
-
)
|
|
2274
|
-
if (titled.length > 0) return titled
|
|
2275
|
-
// 工作目录里没有:老版本把会话建在项目目录里,再全局找一次。
|
|
2276
|
-
// 跨目录只认标记:标记带群号与私聊号,不会认错人。
|
|
2277
|
-
return await collect(
|
|
2278
|
-
undefined,
|
|
2279
|
-
`全局查找历史会话失败 ${targetLabel(target)}`,
|
|
2280
|
-
{
|
|
2281
|
-
limit: SESSION_CANDIDATES,
|
|
2282
|
-
maxPages: SESSION_SEARCH_PAGES,
|
|
2283
|
-
},
|
|
2284
|
-
byMetadata,
|
|
2285
|
-
)
|
|
2286
2266
|
}
|
|
2287
2267
|
|
|
2288
2268
|
/** 选出消息最多的那条会话。 */
|
|
@@ -2344,17 +2324,24 @@ export class SessionManager {
|
|
|
2344
2324
|
this.appliedOverrides.set(sessionID, { agent, model })
|
|
2345
2325
|
}
|
|
2346
2326
|
|
|
2347
|
-
/**
|
|
2348
|
-
private async sessionExists(sessionID: string): Promise<boolean> {
|
|
2327
|
+
/** 确认绑定仍存在,并且确实属于这个聊天的工作目录。 */
|
|
2328
|
+
private async sessionExists(target: ChatTarget, sessionID: string): Promise<boolean> {
|
|
2349
2329
|
if (this.verifiedSessions.has(sessionID)) return true
|
|
2330
|
+
const directory = this.locationFor(target).directory
|
|
2350
2331
|
try {
|
|
2351
|
-
await this.ctx.session.get({ sessionID })
|
|
2332
|
+
const info = await this.ctx.session.get({ sessionID })
|
|
2333
|
+
const actual = (info as { location?: { directory?: unknown } }).location?.directory
|
|
2334
|
+
// 旧布局里的会话不在聊天目录下:不做兼容,按过期绑定处理。
|
|
2335
|
+
if (typeof actual === "string" && resolve(actual) !== resolve(directory)) {
|
|
2336
|
+
this.logger.warn(`会话 ${sessionID} 不在 ${targetLabel(target)} 的工作目录,将重新建立绑定`)
|
|
2337
|
+
return false
|
|
2338
|
+
}
|
|
2352
2339
|
this.verifiedSessions.add(sessionID)
|
|
2353
2340
|
return true
|
|
2354
2341
|
} catch (error) {
|
|
2355
2342
|
// 直查只认 sessionID,列表查询才按目录过滤:两种口径不一致时,
|
|
2356
2343
|
// 明明还在的会话会被当成已删除。直查失败后再按目录确认一次。
|
|
2357
|
-
if (await this.sessionInDirectory(sessionID)) {
|
|
2344
|
+
if (await this.sessionInDirectory(target, sessionID)) {
|
|
2358
2345
|
this.logger.warn(`会话 ${sessionID} 直查失败,但目录列表里仍然存在,继续沿用`)
|
|
2359
2346
|
this.verifiedSessions.add(sessionID)
|
|
2360
2347
|
return true
|
|
@@ -2364,11 +2351,11 @@ export class SessionManager {
|
|
|
2364
2351
|
}
|
|
2365
2352
|
}
|
|
2366
2353
|
|
|
2367
|
-
/**
|
|
2368
|
-
private async sessionInDirectory(sessionID: string): Promise<boolean> {
|
|
2354
|
+
/** 会话是否还在这个聊天的工作目录里;直查口径不一致时的兜底判断。 */
|
|
2355
|
+
private async sessionInDirectory(target: ChatTarget, sessionID: string): Promise<boolean> {
|
|
2369
2356
|
const found = await findSessions(
|
|
2370
2357
|
this.ctx,
|
|
2371
|
-
this.
|
|
2358
|
+
this.locationFor(target).directory,
|
|
2372
2359
|
(session) => session.id === sessionID,
|
|
2373
2360
|
this.logger,
|
|
2374
2361
|
`查找会话 ${sessionID} 失败`,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
|
-
import {
|
|
2
|
+
import { targetLabel } from "../chat"
|
|
3
3
|
import type { Logger } from "../logger"
|
|
4
|
+
import type { ChatOverrides } from "../overrides"
|
|
4
5
|
import type { SessionManager } from "../session/manager"
|
|
5
6
|
import type { ToolPolicy } from "./policy"
|
|
6
7
|
import { QQ_REQUEST_REPLY_TOOL } from "./qq"
|
|
@@ -13,6 +14,8 @@ export interface ToolPolicyGuardDeps {
|
|
|
13
14
|
logger: Logger
|
|
14
15
|
manager: SessionManager
|
|
15
16
|
policy: ToolPolicy
|
|
17
|
+
/** 会话覆盖:按聊天指定工具配置档。 */
|
|
18
|
+
overrides: ChatOverrides
|
|
16
19
|
}
|
|
17
20
|
|
|
18
21
|
/**
|
|
@@ -26,7 +29,7 @@ export interface ToolPolicyGuardDeps {
|
|
|
26
29
|
export async function registerToolPolicy(
|
|
27
30
|
deps: ToolPolicyGuardDeps,
|
|
28
31
|
): Promise<{ dispose(): Promise<void> }> {
|
|
29
|
-
const { ctx, logger, manager, policy } = deps
|
|
32
|
+
const { ctx, logger, manager, policy, overrides } = deps
|
|
30
33
|
return await ctx.tool.hook("execute.before", async (event) => {
|
|
31
34
|
const target = manager.targetForSession(event.sessionID)
|
|
32
35
|
if (!target) return
|
|
@@ -38,10 +41,11 @@ export async function registerToolPolicy(
|
|
|
38
41
|
}
|
|
39
42
|
// 申请回复权限的工具必须一直放行:不然模型永远拿不到发送权限。
|
|
40
43
|
if (event.tool === QQ_REQUEST_REPLY_TOOL) return
|
|
41
|
-
const
|
|
44
|
+
const override = await overrides.for(target)
|
|
45
|
+
const allowed = await policy.allow(role, override.profile, [event.tool])
|
|
42
46
|
logger.debug(`${targetLabel(target)} 工具策略检查`, {
|
|
43
47
|
role,
|
|
44
|
-
profile: await policy.profileOf(role,
|
|
48
|
+
profile: await policy.profileOf(role, override.profile),
|
|
45
49
|
tool: event.tool,
|
|
46
50
|
allowed: allowed.size > 0,
|
|
47
51
|
})
|
|
@@ -50,7 +54,7 @@ export async function registerToolPolicy(
|
|
|
50
54
|
`${targetLabel(target)} 会话里 ${role} 尝试调用工具 ${event.tool},已被工具配置拒绝`,
|
|
51
55
|
)
|
|
52
56
|
throw new Error(
|
|
53
|
-
`当前用户不能使用工具 ${event.tool}:工具权限由 tool-profiles.json
|
|
57
|
+
`当前用户不能使用工具 ${event.tool}:工具权限由 config/tool-profiles.json 的配置档决定,config/chat-overrides.json 可以按聊天指定配置档。`,
|
|
54
58
|
)
|
|
55
59
|
})
|
|
56
60
|
}
|
package/src/tools/policy.ts
CHANGED
|
@@ -32,14 +32,12 @@ export interface ToolProfile {
|
|
|
32
32
|
deny: string[]
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
/** `tool-profiles.json` 的结构。 */
|
|
35
|
+
/** `config/tool-profiles.json` 的结构。 */
|
|
36
36
|
export interface ToolPolicyFile {
|
|
37
37
|
/** 没有按聊天指定的配置时用哪一档。 */
|
|
38
38
|
defaultProfile: string
|
|
39
39
|
/** 配置档:名字 → 允许 / 禁止的工具。 */
|
|
40
40
|
profiles: Record<string, ToolProfile>
|
|
41
|
-
/** 按聊天指定的配置档:`group:100` / `private:200` → 档名。 */
|
|
42
|
-
chats: Record<string, string>
|
|
43
41
|
}
|
|
44
42
|
|
|
45
43
|
/**
|
|
@@ -57,8 +55,11 @@ const ADMIN_DENY = ["qq_diary_*", "qq_send_file", "qq_collect_sticker", "qq_down
|
|
|
57
55
|
*
|
|
58
56
|
* owner 与 admin 共用 `admin` 档,所以「admin 不能用日记」只能在这里按角色判定,
|
|
59
57
|
* 不能写进 `admin` 档的 deny:那会把 owner 一起禁掉。
|
|
58
|
+
*
|
|
59
|
+
* 写用户画像的工具也在表里:画像正文会以系统提示的身份回到模型上下文,
|
|
60
|
+
* 群友能写就等于能在后续会话里留下持久指令。
|
|
60
61
|
*/
|
|
61
|
-
const OWNER_ONLY = ["qq_diary_*"]
|
|
62
|
+
const OWNER_ONLY = ["qq_diary_*", "qq_user_profile_write"]
|
|
62
63
|
|
|
63
64
|
/**
|
|
64
65
|
* 只有管理角色(owner 与 admin)能用的工具。
|
|
@@ -78,13 +79,12 @@ export function defaultToolPolicy(): ToolPolicyFile {
|
|
|
78
79
|
return {
|
|
79
80
|
defaultProfile: "chat",
|
|
80
81
|
profiles,
|
|
81
|
-
chats: safeMap<string>(),
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
/**
|
|
85
|
+
/** 默认的配置文件位置:工作目录 `config/` 下的 `tool-profiles.json`。 */
|
|
86
86
|
export function defaultToolProfilesPath(home: string): string {
|
|
87
|
-
return join(home, "tool-profiles.json")
|
|
87
|
+
return join(home, "config", "tool-profiles.json")
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
/**
|
|
@@ -177,42 +177,43 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
177
177
|
if (!hasKey(profiles, defaultProfile)) {
|
|
178
178
|
warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
|
|
179
179
|
}
|
|
180
|
-
const chats = safeMap<string>()
|
|
181
180
|
if (raw.chats !== undefined) {
|
|
182
|
-
|
|
183
|
-
warn("chats 必须是对象,已忽略")
|
|
184
|
-
} else {
|
|
185
|
-
for (const [key, name] of Object.entries(raw.chats as Record<string, unknown>)) {
|
|
186
|
-
if (typeof name !== "string" || !name.trim()) {
|
|
187
|
-
warn(`chats.${key} 必须是配置档名字,已忽略`)
|
|
188
|
-
continue
|
|
189
|
-
}
|
|
190
|
-
chats[key] = name.trim()
|
|
191
|
-
}
|
|
192
|
-
}
|
|
181
|
+
warn("chats 段已迁移到 config/chat-overrides.json 的 chats.<聊天>.profile,已忽略")
|
|
193
182
|
}
|
|
194
183
|
return {
|
|
195
184
|
defaultProfile: hasKey(profiles, defaultProfile) ? defaultProfile : fallback.defaultProfile,
|
|
196
185
|
profiles,
|
|
197
|
-
chats,
|
|
198
186
|
}
|
|
199
187
|
}
|
|
200
188
|
|
|
201
189
|
/**
|
|
202
|
-
* 角色对应的配置档名字:owner 与 admin
|
|
190
|
+
* 角色对应的配置档名字:owner 与 admin 用管理档,其他按聊天指定的档位。
|
|
203
191
|
*
|
|
204
192
|
* 主动说话(`proactive`)固定用主动说话档:它没有人参与,
|
|
205
193
|
* 不能因为聊天里有 owner 或管理员说过话就借到管理档的全开权限。
|
|
194
|
+
*
|
|
195
|
+
* 聊天指定的档名不存在时按默认档处理,并通过 `warn` 说一声:
|
|
196
|
+
* 档名写错会静默放宽工具面,不出声就没人知道。
|
|
197
|
+
*
|
|
198
|
+
* @param profile 聊天在 `config/chat-overrides.json` 里指定的配置档名。
|
|
199
|
+
* @param warn 档名不存在时的告警回调。
|
|
206
200
|
*/
|
|
207
|
-
export function profileNameFor(
|
|
201
|
+
export function profileNameFor(
|
|
202
|
+
file: ToolPolicyFile,
|
|
203
|
+
role: Role,
|
|
204
|
+
profile?: string,
|
|
205
|
+
warn?: (message: string) => void,
|
|
206
|
+
): string {
|
|
208
207
|
if (role === "owner" || role === "admin") {
|
|
209
208
|
return hasKey(file.profiles, "admin") ? "admin" : file.defaultProfile
|
|
210
209
|
}
|
|
211
210
|
if (role === "proactive") {
|
|
212
211
|
return hasKey(file.profiles, "proactive") ? "proactive" : file.defaultProfile
|
|
213
212
|
}
|
|
214
|
-
|
|
215
|
-
if (
|
|
213
|
+
if (profile && hasKey(file.profiles, profile)) return profile
|
|
214
|
+
if (profile) {
|
|
215
|
+
warn?.(`配置档 ${profile} 不存在,按默认档 ${file.defaultProfile} 处理`)
|
|
216
|
+
}
|
|
216
217
|
return file.defaultProfile
|
|
217
218
|
}
|
|
218
219
|
|
|
@@ -230,6 +231,8 @@ export function allowedTools(profile: ToolProfile, names: readonly string[]): st
|
|
|
230
231
|
/** 工具配置的读取与热加载。 */
|
|
231
232
|
export class ToolPolicy {
|
|
232
233
|
private cached?: { mtime: number; file: ToolPolicyFile }
|
|
234
|
+
/** 已经告警过的档名:同一个档名只提醒一次,别把日志刷满。 */
|
|
235
|
+
private readonly warnedProfiles = new Set<string>()
|
|
233
236
|
|
|
234
237
|
constructor(
|
|
235
238
|
private readonly path: string,
|
|
@@ -259,35 +262,54 @@ export class ToolPolicy {
|
|
|
259
262
|
}
|
|
260
263
|
}
|
|
261
264
|
|
|
262
|
-
/**
|
|
263
|
-
|
|
265
|
+
/**
|
|
266
|
+
* 某个角色在某个聊天里能用的工具子集。
|
|
267
|
+
*
|
|
268
|
+
* @param profile 聊天在 `config/chat-overrides.json` 里指定的配置档名。
|
|
269
|
+
*/
|
|
270
|
+
async allow(
|
|
271
|
+
role: Role,
|
|
272
|
+
profile: string | undefined,
|
|
273
|
+
names: readonly string[],
|
|
274
|
+
): Promise<Set<string>> {
|
|
264
275
|
const file = await this.current()
|
|
265
|
-
const name = profileNameFor(file, role,
|
|
266
|
-
const
|
|
267
|
-
if (!
|
|
276
|
+
const name = profileNameFor(file, role, profile, (message) => this.warnProfile(message))
|
|
277
|
+
const definition = hasKey(file.profiles, name) ? file.profiles[name] : undefined
|
|
278
|
+
if (!definition) {
|
|
268
279
|
// 找不到配置档时一律不放行:让配置坏了就等于机器人失去工具,比崩掉好。
|
|
269
280
|
this.logger.warn(`工具配置 ${this.path}:找不到配置档 ${name},本轮不放行任何工具`)
|
|
270
281
|
return new Set<string>()
|
|
271
282
|
}
|
|
272
|
-
const allowed = new Set(allowedTools(
|
|
283
|
+
const allowed = new Set(allowedTools(definition, names))
|
|
273
284
|
// 配置档只按工具名分配,日记这类只给 owner 的工具要在这里再按角色收一次。
|
|
274
285
|
if (role !== "owner") {
|
|
275
|
-
for (const
|
|
276
|
-
if (OWNER_ONLY.some((pattern) => globMatch(pattern,
|
|
286
|
+
for (const tool of allowed) {
|
|
287
|
+
if (OWNER_ONLY.some((pattern) => globMatch(pattern, tool))) allowed.delete(tool)
|
|
277
288
|
}
|
|
278
289
|
}
|
|
279
290
|
// 收藏表情会往本机写文件:只有管理角色能用,配置档放开也不行。
|
|
280
291
|
if (role !== "owner" && role !== "admin") {
|
|
281
|
-
for (const
|
|
282
|
-
if (ADMIN_ONLY.some((pattern) => globMatch(pattern,
|
|
292
|
+
for (const tool of allowed) {
|
|
293
|
+
if (ADMIN_ONLY.some((pattern) => globMatch(pattern, tool))) allowed.delete(tool)
|
|
283
294
|
}
|
|
284
295
|
}
|
|
285
296
|
return allowed
|
|
286
297
|
}
|
|
287
298
|
|
|
288
|
-
/**
|
|
289
|
-
|
|
299
|
+
/**
|
|
300
|
+
* 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。
|
|
301
|
+
*
|
|
302
|
+
* @param profile 聊天在 `config/chat-overrides.json` 里指定的配置档名。
|
|
303
|
+
*/
|
|
304
|
+
async profileOf(role: Role, profile: string | undefined): Promise<string> {
|
|
290
305
|
const file = await this.current()
|
|
291
|
-
return profileNameFor(file, role,
|
|
306
|
+
return profileNameFor(file, role, profile, (message) => this.warnProfile(message))
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** 档名写错时告警一次:同一个档名只说一次,别把日志刷满。 */
|
|
310
|
+
private warnProfile(message: string): void {
|
|
311
|
+
if (this.warnedProfiles.has(message)) return
|
|
312
|
+
this.warnedProfiles.add(message)
|
|
313
|
+
this.logger.warn(`工具配置 ${this.path}:${message}`)
|
|
292
314
|
}
|
|
293
315
|
}
|