@cmach_socket/opencode-qq-bot 2.0.1 → 2.1.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 CHANGED
@@ -50,6 +50,8 @@ opencode plugin add @cmach_socket/opencode-qq-bot
50
50
  模板见 [`config.example.json`](config.example.json);全部字段、默认值与取值限制见
51
51
  [docs/guide/configuration.md](docs/guide/configuration.md)。
52
52
 
53
+ 文件不存在时插件首次启动会自己生成一份最小模板,填上 `ownerQQ`、`napcat.url` 与 `access.allow` 就能用。
54
+
53
55
  ## 文档
54
56
 
55
57
  完整文档见 [docs/README.md](docs/README.md)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmach_socket/opencode-qq-bot",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "OpenCode V2 plugin bridging a QQ group chat (NapCat via NapLink) to an OpenCode session.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,6 @@
25
25
  "web/dist",
26
26
  "config.example.json",
27
27
  "tool-profiles.example.json",
28
- "chat-overrides.example.json",
29
28
  "NOTICE",
30
29
  "README.md"
31
30
  ],
@@ -35,6 +34,7 @@
35
34
  "format": "prettier --write .",
36
35
  "format:check": "prettier --check .",
37
36
  "test": "vitest run",
37
+ "audit:prod": "bun audit --production --audit-level=high --ignore=GHSA-25mm-r35j-6hgm --ignore=GHSA-mhqm-9wj8-w7r4 --ignore=GHSA-jmj2-9c5q-vw73 --ignore=GHSA-hqgx-p3r3-2cfg --ignore=GHSA-gvrf-jx37-rjv5 --ignore=GHSA-6wwr-g865-f46r --ignore=GHSA-4pf9-5fpx-xmr6 --ignore=GHSA-3wwj-8j6r-q339 --ignore=GHSA-98v3-7xjr-fg83",
38
38
  "web:build": "bun run --cwd web build",
39
39
  "web:dev": "bun run --cwd web dev",
40
40
  "web:check": "bun run --cwd web check",
@@ -53,35 +53,35 @@
53
53
  "license": "CC-BY-NC-SA-4.0",
54
54
  "dependencies": {
55
55
  "@bybrave/proper-lockfile2": "5.1.0",
56
- "@hono/node-server": "2.1.7",
57
- "@naplink/naplink": "1.2.0",
58
- "@opencode/plugin": "2.2.5",
59
- "@opencode/schema": "2.2.5",
56
+ "@hono/node-server": "2.1.11",
57
+ "@naplink/naplink": "1.3.0",
58
+ "@opencode/plugin": "2.4.3",
59
+ "@opencode/schema": "2.4.3",
60
60
  "async-mutex": "0.5.0",
61
61
  "chokidar": "6.0.0",
62
- "flare-redact": "1.6.1",
63
- "hono": "4.13.18",
62
+ "flare-redact": "1.13.1",
63
+ "hono": "4.13.23",
64
64
  "ipaddr.js": "2.5.0",
65
- "remove-markdown": "0.8.0",
66
- "request-filtering-agent": "3.2.1",
65
+ "remove-markdown": "0.8.3",
66
+ "request-filtering-agent": "3.3.1",
67
67
  "winston": "3.19.0",
68
68
  "winston-daily-rotate-file": "5.0.0",
69
69
  "write-file-atomic": "8.0.0",
70
70
  "zod": "4.6.7"
71
71
  },
72
72
  "devDependencies": {
73
- "@sveltejs/vite-plugin-svelte": "7.3.1",
74
- "@testing-library/svelte": "5.2.8",
75
- "@types/bun": "1.4.4",
73
+ "@sveltejs/vite-plugin-svelte": "7.3.2",
74
+ "@testing-library/svelte": "5.4.2",
75
+ "@types/bun": "1.4.5",
76
76
  "@types/write-file-atomic": "4.0.3",
77
- "@vitest/coverage-v8": "5.1.0",
78
- "eslint": "10.14.0",
79
- "jsdom": "^31.0.0",
80
- "prettier": "3.9.10",
81
- "svelte": "5.57.3",
77
+ "@vitest/coverage-v8": "5.1.2",
78
+ "eslint": "10.16.0",
79
+ "jsdom": "^31.0.1",
80
+ "prettier": "3.10.1",
81
+ "svelte": "5.59.2",
82
82
  "typescript": "6.0.3",
83
- "typescript-eslint": "8.72.1",
84
- "vitest": "5.1.0"
83
+ "typescript-eslint": "8.74.0",
84
+ "vitest": "5.1.2"
85
85
  },
86
86
  "overrides": {
87
87
  "cross-spawn": "7.1.2"
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 首次启动时生成到 `config/config.json` 的内容。
3
+ *
4
+ * 配置文件是唯一来源:缺文件时先落一份默认配置,主人改掉需要的那几项即可,
5
+ * 不然插件只能拒绝启动。
6
+ */
7
+
8
+ /** 新装时写进配置文件的 NapCat 地址:NapCat 默认监听的 WebSocket 端口。 */
9
+ export const INITIAL_NAPCAT_URL = "ws://127.0.0.1:3001"
10
+
11
+ /**
12
+ * 配置文件里始终保留的路径。
13
+ *
14
+ * 这几项是主人上手要填的:留在文件里,配置文件自己就说明了该改哪几处。
15
+ */
16
+ export const TEMPLATE_PATHS: readonly string[] = [
17
+ "ownerQQ",
18
+ "napcat.url",
19
+ "access.allow.groups",
20
+ "access.allow.users",
21
+ ]
22
+
23
+ /**
24
+ * 生成初始配置内容。
25
+ *
26
+ * 只写主人要填的几项,其余交给注册表里的默认值:
27
+ * 默认值以后调整,已经装好的机器也得跟着变。
28
+ * `ownerQQ` 写 `null` 表示「还没填」,解析时按未配置处理。
29
+ */
30
+ export function initialConfig(): Record<string, unknown> {
31
+ return {
32
+ ownerQQ: null,
33
+ napcat: { url: INITIAL_NAPCAT_URL },
34
+ access: { allow: { groups: [], users: [] } },
35
+ }
36
+ }
@@ -1,9 +1,10 @@
1
1
  import { randomBytes } from "node:crypto"
2
2
  import { applyHotFields, resolveConfig, type ConfigWarning, type QQBotConfig } from "../config"
3
3
  import { CONFIG_FIELDS } from "../config/fields"
4
- import { requiredFieldProblem } from "../config/registry"
4
+ import { pruneDefaultEntries, requiredFieldProblem } from "../config/registry"
5
+ import { initialConfig, TEMPLATE_PATHS } from "./initial"
5
6
  import type { Logger } from "../logger"
6
- import type { ConfigPatch, ConfigStore } from "./store"
7
+ import { ConfigMissingError, type ConfigPatch, type ConfigStore } from "./store"
7
8
 
8
9
  /**
9
10
  * 生效中的配置:文件内容、内存配置与热更新都归它管。
@@ -67,15 +68,57 @@ export class ConfigController {
67
68
  /**
68
69
  * 读取配置文件并解析成生效配置。
69
70
  *
70
- * @throws 配置文件不存在或内容非法时抛出:配置来源只有一个,缺文件不能静默按默认值跑。
71
+ * 文件不存在时先生成一份默认配置落盘,主人改掉需要的那几项即可。
72
+ *
73
+ * @throws 配置文件内容非法时抛出:配置来源只有一个,写坏了不能静默按默认值跑。
71
74
  */
72
75
  async load(): Promise<QQBotConfig> {
73
- this.raw = await this.options.store.read()
76
+ this.raw = await this.readOrCreate()
77
+ this.raw = await this.pruneDefaults(this.raw)
74
78
  this.config = this.resolve(this.raw)
75
79
  await this.ensureSecrets()
76
80
  return this.config
77
81
  }
78
82
 
83
+ /**
84
+ * 把配置文件里与默认值相同的项删掉并落盘。
85
+ *
86
+ * 配置文件只留主人改过的值:默认值以后调整,已经装好的机器也跟着变。
87
+ * 写不进去只告警:这一份配置照常用,只是默认值暂时传不过来。
88
+ */
89
+ private async pruneDefaults(raw: Record<string, unknown>): Promise<Record<string, unknown>> {
90
+ const pruned = pruneDefaultEntries(raw, TEMPLATE_PATHS)
91
+ if (JSON.stringify(pruned) === JSON.stringify(raw)) return raw
92
+ try {
93
+ await this.options.store.write(pruned)
94
+ } catch (error) {
95
+ this.warn(
96
+ `配置文件精简失败,继续沿用原文件:${error instanceof Error ? error.message : String(error)}`,
97
+ )
98
+ return raw
99
+ }
100
+ return pruned
101
+ }
102
+
103
+ /**
104
+ * 读配置文件;文件不存在时先生成一份默认配置。
105
+ *
106
+ * 缺文件不该让插件起不来:生成一份落盘,主人改完接着用。
107
+ */
108
+ private async readOrCreate(): Promise<Record<string, unknown>> {
109
+ try {
110
+ return await this.options.store.read()
111
+ } catch (error) {
112
+ if (!(error instanceof ConfigMissingError)) throw error
113
+ const raw = initialConfig()
114
+ await this.options.store.write(raw)
115
+ this.warn(
116
+ `配置文件不存在,已生成默认配置:${this.options.store.path}(请填写 ownerQQ 与 access.allow)`,
117
+ )
118
+ return raw
119
+ }
120
+ }
121
+
79
122
  /**
80
123
  * 补齐缺失的随机凭据。
81
124
  *
@@ -462,6 +462,60 @@ export function warnUnknownFileKeys(raw: Record<string, unknown>, warn: ConfigWa
462
462
  walk(raw, "")
463
463
  }
464
464
 
465
+ /**
466
+ * 删掉配置文件里与默认值相同的项。
467
+ *
468
+ * 配置文件只保留主人改过的值:默认值以后调整,已经装好的机器也跟着变。
469
+ * `keep` 里的路径原样留下,首次启动生成的模板就靠它们提示主人该填哪几项。
470
+ */
471
+ export function pruneDefaultEntries(
472
+ raw: Record<string, unknown>,
473
+ keep: readonly string[] = [],
474
+ ): Record<string, unknown> {
475
+ const kept = new Set(keep)
476
+ const result = structuredClone(raw) as Record<string, unknown>
477
+ for (const field of CONFIG_FIELDS) {
478
+ if (field.default === undefined) continue
479
+ if (kept.has(field.path)) continue
480
+ const value = getConfigValue(result, field.path)
481
+ if (value === undefined) continue
482
+ if (!sameValue(value, field.default)) continue
483
+ deletePath(result, field.path)
484
+ }
485
+ return result
486
+ }
487
+
488
+ /** 值是否与默认值相同:数组逐项比较,其余按引用比。 */
489
+ function sameValue(left: unknown, right: unknown): boolean {
490
+ if (left === right) return true
491
+ if (!Array.isArray(left) || !Array.isArray(right)) return false
492
+ return left.length === right.length && left.every((item, index) => sameValue(item, right[index]))
493
+ }
494
+
495
+ /** 删掉一个路径,顺手清掉因此变空的上层对象。 */
496
+ function deletePath(target: Record<string, unknown>, path: string): void {
497
+ const segments = path.split(".")
498
+ const parents: Array<{ parent: Record<string, unknown>; key: string }> = []
499
+ let current = target
500
+ for (const segment of segments.slice(0, -1)) {
501
+ const child = current[segment]
502
+ if (!child || typeof child !== "object" || Array.isArray(child)) return
503
+ parents.push({ parent: current, key: segment })
504
+ current = child as Record<string, unknown>
505
+ }
506
+ const leaf = segments[segments.length - 1]
507
+ if (leaf === undefined) return
508
+ delete current[leaf]
509
+ for (let index = parents.length - 1; index >= 0; index -= 1) {
510
+ const entry = parents[index]
511
+ if (!entry) continue
512
+ const child = entry.parent[entry.key]
513
+ if (!child || typeof child !== "object" || Array.isArray(child)) break
514
+ if (Object.keys(child).length > 0) break
515
+ delete entry.parent[entry.key]
516
+ }
517
+ }
518
+
465
519
  /** 注册表里声明为热更新的字段。 */
466
520
  export const HOT_FIELDS: readonly ConfigField[] = CONFIG_FIELDS.filter((field) => field.hot)
467
521
 
@@ -16,7 +16,7 @@ export class ConfigMissingError extends Error {
16
16
  constructor(path: string) {
17
17
  super(
18
18
  `配置文件不存在:${path}\n` +
19
- "请创建该文件并按 docs/guide/configuration.md 的字段表填写(至少要有 napcat.url),然后重启插件。",
19
+ "插件启动时会自动生成一份默认配置;也可以手动创建,并按 docs/guide/configuration.md 的字段表填写(至少要有 napcat.url)。",
20
20
  )
21
21
  this.name = "ConfigMissingError"
22
22
  }
package/src/index.ts CHANGED
@@ -35,6 +35,7 @@ import type { PanelAuth } from "./panel/auth"
35
35
  import { PanelRuntime } from "./panel/runtime"
36
36
  import { createModelProvider } from "./panel/models"
37
37
  import { PanelServer } from "./panel/server"
38
+ import { createToolNameProvider } from "./panel/tools"
38
39
  import { RestartableSetup, type SetupGeneration } from "./restartable"
39
40
  import { SendRateLimiter } from "./rate-limit"
40
41
  import { startClaimTimer } from "./runtime/claim"
@@ -233,6 +234,7 @@ const initializer = {
233
234
  controller,
234
235
  runtime: panelRuntime,
235
236
  models: createModelProvider(ctx.model),
237
+ tools: createToolNameProvider(ctx.tool),
236
238
  logger,
237
239
  ...(carry?.panel ? { auth: carry.panel } : {}),
238
240
  ...(restart ? { onRestart: restart } : {}),
@@ -474,10 +476,9 @@ const initializer = {
474
476
  const policy = new ToolPolicy(profilesPath, logger)
475
477
  panelRuntime.policy = policy
476
478
  // 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
479
+ // 不复制随包示例:覆盖的对象就是准入放行的聊天,
480
+ // 机器人不替用户凭空造一份默认配置,文件没有就不动。
477
481
  const overridesPath = resolveChatOverridesPath(config, home.directory)
478
- if (!config.chatOverridesPath) {
479
- await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
480
- }
481
482
  const overrides = new ChatOverrides(overridesPath, logger, {
482
483
  home: home.directory,
483
484
  allowedPaths: config.soul.allowedPaths,
package/src/panel/api.ts CHANGED
@@ -6,6 +6,8 @@ import { getCookie, setCookie } from "hono/cookie"
6
6
  import { csrf } from "hono/csrf"
7
7
  import { secureHeaders } from "hono/secure-headers"
8
8
  import { streamSSE } from "hono/streaming"
9
+ import { isTargetAllowed } from "../access"
10
+ import { parseTargetKey } from "../chat"
9
11
  import type { ConfigController } from "../config/live"
10
12
  import { CONFIG_FIELDS, CONFIG_GROUPS } from "../config/fields"
11
13
  import {
@@ -25,6 +27,8 @@ import {
25
27
  import type { ModelProvider } from "./models"
26
28
  import { collectStatus } from "./status"
27
29
  import type { PanelRuntime } from "./runtime"
30
+ import type { ToolNameProvider } from "./tools"
31
+ import { listUserMd, readUserMdText, saveUserMd, userMdFilename } from "./user-md"
28
32
 
29
33
  /**
30
34
  * 面板的 HTTP 接口。
@@ -46,6 +50,8 @@ export interface PanelAppOptions {
46
50
  runtime: PanelRuntime
47
51
  /** 可用模型列表。 */
48
52
  models: ModelProvider
53
+ /** 可用工具名:工具档案的 allow/deny 从这里选。 */
54
+ tools: ToolNameProvider
49
55
  /** 前端构建产物目录;没有就不托管静态资源。 */
50
56
  staticDir?: string
51
57
  /** 面板触发重启时调用;不传表示当前环境不支持重启。 */
@@ -250,6 +256,69 @@ export function createPanelApp(options: PanelAppOptions): Hono {
250
256
  return c.json({ ok: true, ...result })
251
257
  })
252
258
 
259
+ // 用户档案:每个聊天一份,面板里可上传。
260
+ app.get("/api/user-md", async (c) => {
261
+ return c.json(await listUserMd(runtime))
262
+ })
263
+
264
+ // 下载档案原文:面板里显示的是掩码过的正文,这里给的是原文件。
265
+ app.get("/api/user-md/file", async (c) => {
266
+ const chat = c.req.query("chat") ?? ""
267
+ const target = parseTargetKey(chat)
268
+ if (!target) {
269
+ return c.json(
270
+ {
271
+ error: "validation_failed",
272
+ message: "用户档案校验不通过",
273
+ fields: [{ path: "chat", message: "聊天键必须是 group:<群号> 或 private:<账号>" }],
274
+ },
275
+ 400,
276
+ )
277
+ }
278
+ // 和上传一样只认已放行的聊天:写不进去的聊天也读不出来。
279
+ if (!isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ)) {
280
+ return c.json(
281
+ { error: "forbidden", message: "这个聊天还没放行:先在准入名单里放行,再下载档案" },
282
+ 403,
283
+ )
284
+ }
285
+ const text = await readUserMdText(runtime, target)
286
+ if (text === undefined) {
287
+ return c.json({ error: "not_found", message: "这个聊天还没有 USER.md" }, 404)
288
+ }
289
+ return c.body(text, 200, {
290
+ "Content-Type": "text/markdown; charset=utf-8",
291
+ "Content-Disposition": `attachment; filename="${userMdFilename(target)}"`,
292
+ })
293
+ })
294
+
295
+ // 上传用户档案:整份覆盖,只写已放行的聊天。
296
+ app.put("/api/user-md", async (c) => {
297
+ const contentType = c.req.header("Content-Type") ?? ""
298
+ if (!contentType.toLowerCase().includes("application/json")) {
299
+ return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
300
+ }
301
+ const body = await readJson(c.req.raw)
302
+ try {
303
+ const { problems, result } = await saveUserMd(runtime, body)
304
+ if (!result) {
305
+ return c.json(
306
+ { error: "validation_failed", message: "用户档案校验不通过", fields: problems },
307
+ 400,
308
+ )
309
+ }
310
+ return c.json({ ok: true, ...result })
311
+ } catch (error) {
312
+ return c.json(
313
+ {
314
+ error: "write_failed",
315
+ message: error instanceof Error ? error.message : String(error),
316
+ },
317
+ 500,
318
+ )
319
+ }
320
+ })
321
+
253
322
  // 可用模型列表。
254
323
  app.get("/api/models", async (c) => {
255
324
  try {
@@ -262,6 +331,18 @@ export function createPanelApp(options: PanelAppOptions): Hono {
262
331
  }
263
332
  })
264
333
 
334
+ // 可用工具名:工具档案里的 allow/deny 按这份清单给下拉选项。
335
+ app.get("/api/tools", async (c) => {
336
+ try {
337
+ return c.json({ tools: await options.tools.list() })
338
+ } catch (error) {
339
+ return c.json(
340
+ { error: "tools_failed", message: error instanceof Error ? error.message : String(error) },
341
+ 502,
342
+ )
343
+ }
344
+ })
345
+
265
346
  // 运行状态快照。
266
347
  app.get("/api/status", async (c) => {
267
348
  return c.json(await collectStatus(runtime))
@@ -1,6 +1,7 @@
1
1
  import { mkdir, readFile, stat } from "node:fs/promises"
2
2
  import { basename, dirname, join } from "node:path"
3
- import { parseTargetKey } from "../chat"
3
+ import { allowedTargets, isTargetAllowed } from "../access"
4
+ import { parseTargetKey, targetKey } from "../chat"
4
5
  import { backupFile, DIR_MODE, writeJsonAtomic } from "../fs/atomic"
5
6
  import { knownSecrets } from "../known-secrets"
6
7
  import type { Logger } from "../logger"
@@ -11,7 +12,7 @@ import {
11
12
  type ChatOverrideParseOptions,
12
13
  } from "../overrides"
13
14
  import { maskKnownSecrets } from "../sensitive"
14
- import { copyToSafeMap, hasKey, isSafeKey, safeMap } from "../safe-object"
15
+ import { copyToSafeMap, hasKey, isPlainObject, isSafeKey, safeMap } from "../safe-object"
15
16
  import { acquireStateLock, type StateLock } from "../state-lock"
16
17
  import { defaultToolPolicy, parseToolPolicy, resolveToolProfilesPath } from "../tools/policy"
17
18
  import type { PanelRuntime } from "./runtime"
@@ -49,9 +50,9 @@ export interface DocumentView {
49
50
  }
50
51
 
51
52
  /** 保存之后的结果。 */
52
- export interface DocumentSaveResult {
53
+ export interface DocumentSaveResult<T extends DocumentView = DocumentView> {
53
54
  /** 保存后的文档视图。 */
54
- document: DocumentView
55
+ document: T
55
56
  /** 这次改动里的告警。 */
56
57
  warnings: string[]
57
58
  /** 是否需要重启才能生效。 */
@@ -60,6 +61,20 @@ export interface DocumentSaveResult {
60
61
  note: string
61
62
  }
62
63
 
64
+ /** 当前准入放行的聊天。 */
65
+ export interface AdmittedChats {
66
+ /** 配置里明确放行的聊天键。 */
67
+ keys: string[]
68
+ /** 有一整类聊天是「名单为空就全放行」:放行范围无法枚举,不能断言某个聊天没放行。 */
69
+ allowAll: boolean
70
+ }
71
+
72
+ /** 会话覆盖文件的视图:多带一份当前放行的聊天。 */
73
+ export interface ChatOverridesView extends DocumentView {
74
+ /** 当前准入放行的聊天。 */
75
+ admitted: AdmittedChats
76
+ }
77
+
63
78
  /** 会话覆盖里允许出现的字段;与 `ChatOverride` 一一对应。 */
64
79
  const CHAT_OVERRIDE_FIELDS = [
65
80
  "wake",
@@ -102,11 +117,6 @@ function isProfileName(name: string): boolean {
102
117
  return isSafeKey(name) && PROFILE_NAME.test(name)
103
118
  }
104
119
 
105
- /** 判断是不是普通对象(数组与 null 都不算)。 */
106
- function isPlainObject(value: unknown): value is Record<string, unknown> {
107
- return !!value && typeof value === "object" && !Array.isArray(value)
108
- }
109
-
110
120
  /**
111
121
  * 掩码文档里的已知凭证。
112
122
  *
@@ -246,8 +256,25 @@ export function toolProfilesPath(runtime: PanelRuntime): string {
246
256
  return resolveToolProfilesPath(runtime.config, runtime.home.directory)
247
257
  }
248
258
 
259
+ /**
260
+ * 当前准入放行的聊天。
261
+ *
262
+ * 会话覆盖的对象就是准入放行的聊天:面板据此给出候选项,
263
+ * 也据此标出「还没放行」的条目。没有放行的条目原样留着,
264
+ * 等这个聊天被放行时自然生效。
265
+ */
266
+ export function admittedChats(runtime: PanelRuntime): AdmittedChats {
267
+ const access = runtime.config.access
268
+ const keys = allowedTargets(access, runtime.config.ownerQQ).map(targetKey)
269
+ // 某一类名单为空且打开「名单为空时全放行」时,这一类的放行范围无法枚举。
270
+ const allowAll =
271
+ access.allowAllWhenEmpty &&
272
+ (access.allow.groups.length === 0 || access.allow.users.length === 0)
273
+ return { keys, allowAll }
274
+ }
275
+
249
276
  /** 读取会话覆盖文件并给出视图。 */
250
- export async function readChatOverrides(runtime: PanelRuntime): Promise<DocumentView> {
277
+ export async function readChatOverrides(runtime: PanelRuntime): Promise<ChatOverridesView> {
251
278
  const path = chatOverridesPath(runtime)
252
279
  const { raw, exists } = await readJsonFile(path)
253
280
  const warnings: string[] = []
@@ -267,6 +294,7 @@ export async function readChatOverrides(runtime: PanelRuntime): Promise<Document
267
294
  // 告警去重:同一句话出现两次时,页面上不该挂两个一模一样的条目。
268
295
  warnings: [...new Set(warnings)],
269
296
  masked: [...new Set([...maskedValue.masked, ...maskedFile.masked])],
297
+ admitted: admittedChats(runtime),
270
298
  }
271
299
  }
272
300
 
@@ -298,7 +326,7 @@ export async function readToolProfiles(runtime: PanelRuntime): Promise<DocumentV
298
326
  export async function saveChatOverrides(
299
327
  runtime: PanelRuntime,
300
328
  body: unknown,
301
- ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult }> {
329
+ ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult<ChatOverridesView> }> {
302
330
  const problems: DocumentProblem[] = []
303
331
  if (!isPlainObject(body)) {
304
332
  return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
@@ -318,8 +346,9 @@ export async function saveChatOverrides(
318
346
  const chats = isPlainObject(patch) ? patch : {}
319
347
  const warnings: string[] = []
320
348
  // 配置档名字来自 config/tool-profiles.json:写进去的档位必须真的存在。
321
- const policyFile = await runtime.policy?.current()
322
- const profileNames = policyFile ? Object.keys(policyFile.profiles) : []
349
+ // 直接读文件,不依赖运行时:面板比运行时先监听,不能因为还没接好就拒绝写入。
350
+ const { raw: policyRaw } = await readJsonFile(toolProfilesPath(runtime))
351
+ const profileNames = Object.keys(parseToolPolicy(policyRaw, () => undefined).profiles)
323
352
  for (const key of Object.keys(body)) {
324
353
  if (!(CHAT_OVERRIDE_KEYS as readonly string[]).includes(key)) {
325
354
  warnings.push(`未知字段 ${key},已忽略`)
@@ -328,7 +357,8 @@ export async function saveChatOverrides(
328
357
 
329
358
  for (const [key, entry] of Object.entries(chats)) {
330
359
  const field = `chats.${key}`
331
- if (!parseTargetKey(key)) {
360
+ const target = parseTargetKey(key)
361
+ if (!target) {
332
362
  problems.push({ path: field, message: "聊天键必须是 group:<群号> 或 private:<账号>" })
333
363
  continue
334
364
  }
@@ -340,6 +370,15 @@ export async function saveChatOverrides(
340
370
  delete base[key]
341
371
  continue
342
372
  }
373
+ // 覆盖只对已放行的聊天有效:和档案上传一样,没放行的聊天先放行再配。
374
+ // 删掉旧条目不受这条限制:清理不需要放行。
375
+ if (!isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ)) {
376
+ problems.push({
377
+ path: field,
378
+ message: "这个聊天还没放行:先在准入名单里放行,再配置会话覆盖",
379
+ })
380
+ continue
381
+ }
343
382
  if (!isPlainObject(entry)) {
344
383
  problems.push({ path: field, message: "会话覆盖必须是对象" })
345
384
  continue
@@ -407,10 +446,7 @@ export async function saveChatOverrides(
407
446
  if (normalized.profile && !profileNames.includes(normalized.profile)) {
408
447
  problems.push({
409
448
  path: `${field}.profile`,
410
- message:
411
- profileNames.length > 0
412
- ? `配置档 ${normalized.profile} 不存在`
413
- : `读不到工具配置,无法确认配置档 ${normalized.profile} 是否存在`,
449
+ message: `配置档 ${normalized.profile} 不存在`,
414
450
  })
415
451
  continue
416
452
  }
@@ -8,6 +8,7 @@ import { createPanelApp } from "./api"
8
8
  import { PanelAuth } from "./auth"
9
9
  import type { ModelProvider } from "./models"
10
10
  import type { PanelRuntime } from "./runtime"
11
+ import type { ToolNameProvider } from "./tools"
11
12
 
12
13
  /**
13
14
  * 面板的 HTTP 服务。
@@ -23,6 +24,8 @@ export interface PanelServerOptions {
23
24
  runtime: PanelRuntime
24
25
  /** 可用模型列表。 */
25
26
  models: ModelProvider
27
+ /** 可用工具名。 */
28
+ tools: ToolNameProvider
26
29
  /** 日志器。 */
27
30
  logger: Logger
28
31
  /** 跨重启复用的面板鉴权;令牌变化时自动换成新的。 */
@@ -156,6 +159,7 @@ export class PanelServer {
156
159
  controller: this.options.controller,
157
160
  runtime: this.options.runtime,
158
161
  models: this.options.models,
162
+ tools: this.options.tools,
159
163
  ...(existsSync(panelStaticDir()) ? { staticDir: panelStaticDir() } : {}),
160
164
  ...(this.options.onRestart ? { onRestart: this.options.onRestart } : {}),
161
165
  ...(this.options.restartDelayMs !== undefined
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 可用于工具档案的工具名。
3
+ *
4
+ * 清单来自 OpenCode 的工具注册表(内置工具、插件工具与 MCP 工具),
5
+ * 插件只是借 `ctx.tool` 转述;工具的增减要重载插件才会同步。
6
+ */
7
+
8
+ /** 工具名列表的来源。 */
9
+ export interface ToolNameProvider {
10
+ /** 取当前可用的工具名。 */
11
+ list(): Promise<string[]>
12
+ }
13
+
14
+ /** OpenCode 的工具接口:只用 list 一个方法。 */
15
+ interface ToolApiLike {
16
+ list(): Promise<ReadonlyArray<{ id?: string }>>
17
+ }
18
+
19
+ /**
20
+ * 把 OpenCode 的工具接口包成面板要的形状。
21
+ *
22
+ * @param api `ctx.tool`。
23
+ */
24
+ export function createToolNameProvider(api: ToolApiLike): ToolNameProvider {
25
+ return {
26
+ async list(): Promise<string[]> {
27
+ const tools = await api.list()
28
+ const names = tools.map((tool) => tool.id ?? "").filter((id) => id !== "")
29
+ return [...new Set(names)].sort()
30
+ },
31
+ }
32
+ }