@cmach_socket/opencode-qq-bot 2.0.0 → 2.0.2

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` 与 `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.0",
3
+ "version": "2.0.2",
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
  ],
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 首次启动时生成到 `config/config.json` 的内容。
3
+ *
4
+ * 配置文件是唯一来源:缺文件时先落一份默认配置,主人改掉需要的那几项即可,
5
+ * 不然插件只能拒绝启动。
6
+ */
7
+ import { DEFAULT_CONFIG } from "./registry"
8
+
9
+ /** 新装时写进配置文件的 NapCat 地址:NapCat 默认监听的 WebSocket 端口。 */
10
+ export const INITIAL_NAPCAT_URL = "ws://127.0.0.1:3001"
11
+
12
+ /**
13
+ * 生成初始配置内容。
14
+ *
15
+ * 写的是全部默认项加上必填的 `napcat.url` 占位;
16
+ * 每次调用都返回新对象,调用方改它不会影响注册表里的默认值。
17
+ */
18
+ export function initialConfig(): Record<string, unknown> {
19
+ const defaults = structuredClone(DEFAULT_CONFIG) as Record<string, unknown>
20
+ return { ...defaults, napcat: { url: INITIAL_NAPCAT_URL } }
21
+ }
@@ -2,8 +2,9 @@ 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
4
  import { requiredFieldProblem } from "../config/registry"
5
+ import { initialConfig } 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,36 @@ 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()
74
77
  this.config = this.resolve(this.raw)
75
78
  await this.ensureSecrets()
76
79
  return this.config
77
80
  }
78
81
 
82
+ /**
83
+ * 读配置文件;文件不存在时先生成一份默认配置。
84
+ *
85
+ * 缺文件不该让插件起不来:生成一份落盘,主人改完接着用。
86
+ */
87
+ private async readOrCreate(): Promise<Record<string, unknown>> {
88
+ try {
89
+ return await this.options.store.read()
90
+ } catch (error) {
91
+ if (!(error instanceof ConfigMissingError)) throw error
92
+ const raw = initialConfig()
93
+ await this.options.store.write(raw)
94
+ this.warn(
95
+ `配置文件不存在,已生成默认配置:${this.options.store.path}(请填写 ownerQQ 与 access.allow)`,
96
+ )
97
+ return raw
98
+ }
99
+ }
100
+
79
101
  /**
80
102
  * 补齐缺失的随机凭据。
81
103
  *
@@ -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/home.ts CHANGED
@@ -3,12 +3,6 @@ import { homedir } from "node:os"
3
3
  import { isAbsolute, join } from "node:path"
4
4
  import type { Logger } from "./logger"
5
5
 
6
- /**
7
- * 机器人固定服务的工作目录。
8
- *
9
- * 工作目录不再可配置:`config/` 自己就放在这个目录里,位置固定才不会自举。
10
- */
11
-
12
6
  /** 机器人固定服务的工作目录。 */
13
7
  export interface BotHome {
14
8
  /** 工作目录:配置、日记、全局媒体与各聊天目录都在这里。 */
@@ -17,21 +11,32 @@ export interface BotHome {
17
11
  lockPath?: string
18
12
  }
19
13
 
20
- /** 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot`。 */
14
+ /**
15
+ * 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot`。
16
+ *
17
+ * 目录固定且不可配置:`config/` 就在这个目录里,位置固定才不会自举。
18
+ */
21
19
  export function defaultHome(): string {
22
20
  const data = process.env.XDG_DATA_HOME
23
21
  const base = data && isAbsolute(data) ? data : join(homedir(), ".local", "share")
24
22
  return join(base, "opencode-qq-bot")
25
23
  }
26
24
 
25
+ /** 启动时就建好的基础目录:配置、角色设定、日记、全局媒体与各聊天目录。 */
26
+ const BASE_DIRS = ["config", "souls", "diary", "media", "chats"] as const
27
+
27
28
  /**
28
29
  * 解析机器人工作目录并确保它存在。
29
30
  *
30
- * 目录固定在 XDG 数据目录下的工作区,启动时自动创建。
31
+ * 目录固定在 XDG 数据目录下,启动时把基础目录一并建好,
32
+ * 免得第一次用到某个目录时才临时创建。
31
33
  */
32
34
  export async function resolveHome(logger: Logger): Promise<BotHome> {
33
35
  const directory = defaultHome()
34
36
  await mkdir(directory, { recursive: true, mode: 0o700 })
37
+ await Promise.all(
38
+ BASE_DIRS.map((name) => mkdir(join(directory, name), { recursive: true, mode: 0o700 })),
39
+ )
35
40
  // 写锁和数据目录里的其它状态放在一起,不另占 XDG 根目录。
36
41
  const lockPath = join(directory, "state.lock")
37
42
  logger.debug(`机器人工作目录:${directory}`)
package/src/index.ts CHANGED
@@ -474,10 +474,9 @@ const initializer = {
474
474
  const policy = new ToolPolicy(profilesPath, logger)
475
475
  panelRuntime.policy = policy
476
476
  // 会话行为覆盖:按聊天决定怎么唤醒、要不要主动说话。
477
+ // 不复制随包示例:覆盖的对象就是准入放行的聊天,
478
+ // 机器人不替用户凭空造一份默认配置,文件没有就不动。
477
479
  const overridesPath = resolveChatOverridesPath(config, home.directory)
478
- if (!config.chatOverridesPath) {
479
- await seedFile(join(packageRoot, "chat-overrides.example.json"), overridesPath, logger)
480
- }
481
480
  const overrides = new ChatOverrides(overridesPath, logger, {
482
481
  home: home.directory,
483
482
  allowedPaths: config.soul.allowedPaths,
@@ -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 } 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"
@@ -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",
@@ -246,8 +261,25 @@ export function toolProfilesPath(runtime: PanelRuntime): string {
246
261
  return resolveToolProfilesPath(runtime.config, runtime.home.directory)
247
262
  }
248
263
 
264
+ /**
265
+ * 当前准入放行的聊天。
266
+ *
267
+ * 会话覆盖的对象就是准入放行的聊天:面板据此给出候选项,
268
+ * 也据此标出「还没放行」的条目。没有放行的条目原样留着,
269
+ * 等这个聊天被放行时自然生效。
270
+ */
271
+ export function admittedChats(runtime: PanelRuntime): AdmittedChats {
272
+ const access = runtime.config.access
273
+ const keys = allowedTargets(access, runtime.config.ownerQQ).map(targetKey)
274
+ // 某一类名单为空且打开「名单为空时全放行」时,这一类的放行范围无法枚举。
275
+ const allowAll =
276
+ access.allowAllWhenEmpty &&
277
+ (access.allow.groups.length === 0 || access.allow.users.length === 0)
278
+ return { keys, allowAll }
279
+ }
280
+
249
281
  /** 读取会话覆盖文件并给出视图。 */
250
- export async function readChatOverrides(runtime: PanelRuntime): Promise<DocumentView> {
282
+ export async function readChatOverrides(runtime: PanelRuntime): Promise<ChatOverridesView> {
251
283
  const path = chatOverridesPath(runtime)
252
284
  const { raw, exists } = await readJsonFile(path)
253
285
  const warnings: string[] = []
@@ -267,6 +299,7 @@ export async function readChatOverrides(runtime: PanelRuntime): Promise<Document
267
299
  // 告警去重:同一句话出现两次时,页面上不该挂两个一模一样的条目。
268
300
  warnings: [...new Set(warnings)],
269
301
  masked: [...new Set([...maskedValue.masked, ...maskedFile.masked])],
302
+ admitted: admittedChats(runtime),
270
303
  }
271
304
  }
272
305
 
@@ -298,7 +331,7 @@ export async function readToolProfiles(runtime: PanelRuntime): Promise<DocumentV
298
331
  export async function saveChatOverrides(
299
332
  runtime: PanelRuntime,
300
333
  body: unknown,
301
- ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult }> {
334
+ ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult<ChatOverridesView> }> {
302
335
  const problems: DocumentProblem[] = []
303
336
  if (!isPlainObject(body)) {
304
337
  return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
@@ -1,3 +1,4 @@
1
+ import { mkdirSync } from "node:fs"
1
2
  import { resolve } from "node:path"
2
3
  import type { Plugin } from "@opencode/plugin"
3
4
  import type { Location } from "@opencode/schema"
@@ -489,6 +490,11 @@ export class SessionManager {
489
490
  ) {}
490
491
 
491
492
  /** 每个聊天的会话各自落在自己的工作目录里。 */
493
+ /** 聊天目录是会话的工作目录,创建会话之前必须先落到磁盘上。 */
494
+ private ensureChatDirectory(target: ChatTarget): void {
495
+ mkdirSync(this.locationFor(target).directory as string, { recursive: true, mode: 0o700 })
496
+ }
497
+
492
498
  private locationFor(target: ChatTarget): Location.PublicRef {
493
499
  const { directory } = chatWorkspace(this.home.directory, target)
494
500
  // 目录由聊天目标拼出来,这里只是把字符串还原成品牌类型。
@@ -2142,6 +2148,7 @@ export class SessionManager {
2142
2148
 
2143
2149
  private async resolveSession(target: ChatTarget): Promise<string | undefined> {
2144
2150
  await this.ensureBindings()
2151
+ this.ensureChatDirectory(target)
2145
2152
  const state = this.state(target)
2146
2153
  const label = targetLabel(target)
2147
2154
  // 覆盖优先于全局配置;没写覆盖就用全局的。
@@ -2243,6 +2250,7 @@ export class SessionManager {
2243
2250
  target: ChatTarget,
2244
2251
  exclude?: string,
2245
2252
  ): Promise<ListedSession[]> {
2253
+ this.ensureChatDirectory(target)
2246
2254
  const byMetadata = (session: ListedSession) => {
2247
2255
  const metadata = session.metadata
2248
2256
  if (!metadata) return false
@@ -2353,6 +2361,7 @@ export class SessionManager {
2353
2361
 
2354
2362
  /** 会话是否还在这个聊天的工作目录里;直查口径不一致时的兜底判断。 */
2355
2363
  private async sessionInDirectory(target: ChatTarget, sessionID: string): Promise<boolean> {
2364
+ this.ensureChatDirectory(target)
2356
2365
  const found = await findSessions(
2357
2366
  this.ctx,
2358
2367
  this.locationFor(target).directory,