@cmach_socket/opencode-qq-bot 2.0.2 → 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,7 +50,7 @@ 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` 与 `access.allow` 就能用。
53
+ 文件不存在时插件首次启动会自己生成一份最小模板,填上 `ownerQQ`、`napcat.url` 与 `access.allow` 就能用。
54
54
 
55
55
  ## 文档
56
56
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmach_socket/opencode-qq-bot",
3
- "version": "2.0.2",
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",
@@ -34,6 +34,7 @@
34
34
  "format": "prettier --write .",
35
35
  "format:check": "prettier --check .",
36
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",
37
38
  "web:build": "bun run --cwd web build",
38
39
  "web:dev": "bun run --cwd web dev",
39
40
  "web:check": "bun run --cwd web check",
@@ -52,35 +53,35 @@
52
53
  "license": "CC-BY-NC-SA-4.0",
53
54
  "dependencies": {
54
55
  "@bybrave/proper-lockfile2": "5.1.0",
55
- "@hono/node-server": "2.1.7",
56
- "@naplink/naplink": "1.2.0",
57
- "@opencode/plugin": "2.2.5",
58
- "@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",
59
60
  "async-mutex": "0.5.0",
60
61
  "chokidar": "6.0.0",
61
- "flare-redact": "1.6.1",
62
- "hono": "4.13.18",
62
+ "flare-redact": "1.13.1",
63
+ "hono": "4.13.23",
63
64
  "ipaddr.js": "2.5.0",
64
- "remove-markdown": "0.8.0",
65
- "request-filtering-agent": "3.2.1",
65
+ "remove-markdown": "0.8.3",
66
+ "request-filtering-agent": "3.3.1",
66
67
  "winston": "3.19.0",
67
68
  "winston-daily-rotate-file": "5.0.0",
68
69
  "write-file-atomic": "8.0.0",
69
70
  "zod": "4.6.7"
70
71
  },
71
72
  "devDependencies": {
72
- "@sveltejs/vite-plugin-svelte": "7.3.1",
73
- "@testing-library/svelte": "5.2.8",
74
- "@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",
75
76
  "@types/write-file-atomic": "4.0.3",
76
- "@vitest/coverage-v8": "5.1.0",
77
- "eslint": "10.14.0",
78
- "jsdom": "^31.0.0",
79
- "prettier": "3.9.10",
80
- "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",
81
82
  "typescript": "6.0.3",
82
- "typescript-eslint": "8.72.1",
83
- "vitest": "5.1.0"
83
+ "typescript-eslint": "8.74.0",
84
+ "vitest": "5.1.2"
84
85
  },
85
86
  "overrides": {
86
87
  "cross-spawn": "7.1.2"
@@ -4,18 +4,33 @@
4
4
  * 配置文件是唯一来源:缺文件时先落一份默认配置,主人改掉需要的那几项即可,
5
5
  * 不然插件只能拒绝启动。
6
6
  */
7
- import { DEFAULT_CONFIG } from "./registry"
8
7
 
9
8
  /** 新装时写进配置文件的 NapCat 地址:NapCat 默认监听的 WebSocket 端口。 */
10
9
  export const INITIAL_NAPCAT_URL = "ws://127.0.0.1:3001"
11
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
+
12
23
  /**
13
24
  * 生成初始配置内容。
14
25
  *
15
- * 写的是全部默认项加上必填的 `napcat.url` 占位;
16
- * 每次调用都返回新对象,调用方改它不会影响注册表里的默认值。
26
+ * 只写主人要填的几项,其余交给注册表里的默认值:
27
+ * 默认值以后调整,已经装好的机器也得跟着变。
28
+ * `ownerQQ` 写 `null` 表示「还没填」,解析时按未配置处理。
17
29
  */
18
30
  export function initialConfig(): Record<string, unknown> {
19
- const defaults = structuredClone(DEFAULT_CONFIG) as Record<string, unknown>
20
- return { ...defaults, napcat: { url: INITIAL_NAPCAT_URL } }
31
+ return {
32
+ ownerQQ: null,
33
+ napcat: { url: INITIAL_NAPCAT_URL },
34
+ access: { allow: { groups: [], users: [] } },
35
+ }
21
36
  }
@@ -1,8 +1,8 @@
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"
5
- import { initialConfig } from "./initial"
4
+ import { pruneDefaultEntries, requiredFieldProblem } from "../config/registry"
5
+ import { initialConfig, TEMPLATE_PATHS } from "./initial"
6
6
  import type { Logger } from "../logger"
7
7
  import { ConfigMissingError, type ConfigPatch, type ConfigStore } from "./store"
8
8
 
@@ -74,11 +74,32 @@ export class ConfigController {
74
74
  */
75
75
  async load(): Promise<QQBotConfig> {
76
76
  this.raw = await this.readOrCreate()
77
+ this.raw = await this.pruneDefaults(this.raw)
77
78
  this.config = this.resolve(this.raw)
78
79
  await this.ensureSecrets()
79
80
  return this.config
80
81
  }
81
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
+
82
103
  /**
83
104
  * 读配置文件;文件不存在时先生成一份默认配置。
84
105
  *
@@ -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
 
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 } : {}),
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,6 @@
1
1
  import { mkdir, readFile, stat } from "node:fs/promises"
2
2
  import { basename, dirname, join } from "node:path"
3
- import { allowedTargets } from "../access"
3
+ import { allowedTargets, isTargetAllowed } from "../access"
4
4
  import { parseTargetKey, targetKey } from "../chat"
5
5
  import { backupFile, DIR_MODE, writeJsonAtomic } from "../fs/atomic"
6
6
  import { knownSecrets } from "../known-secrets"
@@ -12,7 +12,7 @@ import {
12
12
  type ChatOverrideParseOptions,
13
13
  } from "../overrides"
14
14
  import { maskKnownSecrets } from "../sensitive"
15
- import { copyToSafeMap, hasKey, isSafeKey, safeMap } from "../safe-object"
15
+ import { copyToSafeMap, hasKey, isPlainObject, isSafeKey, safeMap } from "../safe-object"
16
16
  import { acquireStateLock, type StateLock } from "../state-lock"
17
17
  import { defaultToolPolicy, parseToolPolicy, resolveToolProfilesPath } from "../tools/policy"
18
18
  import type { PanelRuntime } from "./runtime"
@@ -117,11 +117,6 @@ function isProfileName(name: string): boolean {
117
117
  return isSafeKey(name) && PROFILE_NAME.test(name)
118
118
  }
119
119
 
120
- /** 判断是不是普通对象(数组与 null 都不算)。 */
121
- function isPlainObject(value: unknown): value is Record<string, unknown> {
122
- return !!value && typeof value === "object" && !Array.isArray(value)
123
- }
124
-
125
120
  /**
126
121
  * 掩码文档里的已知凭证。
127
122
  *
@@ -351,8 +346,9 @@ export async function saveChatOverrides(
351
346
  const chats = isPlainObject(patch) ? patch : {}
352
347
  const warnings: string[] = []
353
348
  // 配置档名字来自 config/tool-profiles.json:写进去的档位必须真的存在。
354
- const policyFile = await runtime.policy?.current()
355
- 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)
356
352
  for (const key of Object.keys(body)) {
357
353
  if (!(CHAT_OVERRIDE_KEYS as readonly string[]).includes(key)) {
358
354
  warnings.push(`未知字段 ${key},已忽略`)
@@ -361,7 +357,8 @@ export async function saveChatOverrides(
361
357
 
362
358
  for (const [key, entry] of Object.entries(chats)) {
363
359
  const field = `chats.${key}`
364
- if (!parseTargetKey(key)) {
360
+ const target = parseTargetKey(key)
361
+ if (!target) {
365
362
  problems.push({ path: field, message: "聊天键必须是 group:<群号> 或 private:<账号>" })
366
363
  continue
367
364
  }
@@ -373,6 +370,15 @@ export async function saveChatOverrides(
373
370
  delete base[key]
374
371
  continue
375
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
+ }
376
382
  if (!isPlainObject(entry)) {
377
383
  problems.push({ path: field, message: "会话覆盖必须是对象" })
378
384
  continue
@@ -440,10 +446,7 @@ export async function saveChatOverrides(
440
446
  if (normalized.profile && !profileNames.includes(normalized.profile)) {
441
447
  problems.push({
442
448
  path: `${field}.profile`,
443
- message:
444
- profileNames.length > 0
445
- ? `配置档 ${normalized.profile} 不存在`
446
- : `读不到工具配置,无法确认配置档 ${normalized.profile} 是否存在`,
449
+ message: `配置档 ${normalized.profile} 不存在`,
447
450
  })
448
451
  continue
449
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
+ }