@cmach_socket/opencode-qq-bot 0.8.0 → 0.9.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.
Files changed (39) hide show
  1. package/NOTICE +48 -15
  2. package/README.md +130 -398
  3. package/config.example.json +12 -0
  4. package/package.json +11 -1
  5. package/src/cleanup.ts +1 -0
  6. package/src/config/fields.ts +780 -0
  7. package/src/config/live.ts +189 -0
  8. package/src/config/registry.ts +654 -0
  9. package/src/config/store.ts +175 -0
  10. package/src/config/types.ts +253 -0
  11. package/src/config.ts +77 -1023
  12. package/src/diary/scheduler.ts +39 -1
  13. package/src/emoji/collection.ts +289 -0
  14. package/src/emoji/favorite-index.ts +40 -3
  15. package/src/emoji/favorites.ts +7 -1
  16. package/src/home.ts +11 -16
  17. package/src/index.ts +117 -25
  18. package/src/logger.ts +104 -1
  19. package/src/naplink/client.ts +16 -0
  20. package/src/panel/api.ts +345 -0
  21. package/src/panel/auth.ts +65 -0
  22. package/src/panel/models.ts +56 -0
  23. package/src/panel/runtime.ts +51 -0
  24. package/src/panel/server.ts +220 -0
  25. package/src/panel/status.ts +201 -0
  26. package/src/rate-limit.ts +46 -0
  27. package/src/sensitive.ts +6 -1
  28. package/src/session/manager.ts +4 -3
  29. package/src/tools/qq.ts +83 -10
  30. package/web/dist/assets/index-7eMQEM7-.css +1 -0
  31. package/web/dist/assets/index-DCkgUY7y.js +15 -0
  32. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  33. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  34. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  35. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  36. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  37. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  38. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  39. package/web/dist/index.html +13 -0
@@ -0,0 +1,175 @@
1
+ import { mkdir, readFile } from "node:fs/promises"
2
+ import { dirname } from "node:path"
3
+ import chokidar, { type FSWatcher } from "chokidar"
4
+ import writeFileAtomic from "write-file-atomic"
5
+ import type { Logger } from "../logger"
6
+
7
+ /**
8
+ * `config.json` 的读写。
9
+ *
10
+ * 写入用 `write-file-atomic`:临时文件 + fsync + rename,中途失败不会留下半截文件;
11
+ * 保留一份 `.bak`,写坏了还能翻回去。
12
+ */
13
+
14
+ /** 配置文件不存在。 */
15
+ export class ConfigMissingError extends Error {
16
+ constructor(path: string) {
17
+ super(
18
+ `配置文件不存在:${path}\n` +
19
+ "请创建该文件并按 docs/configuration.md 的字段表填写(至少要有 napcat.url),然后重启插件。",
20
+ )
21
+ this.name = "ConfigMissingError"
22
+ }
23
+ }
24
+
25
+ /** 配置文件不是合法的 JSON 对象。 */
26
+ export class ConfigParseError extends Error {
27
+ constructor(path: string, cause: unknown) {
28
+ super(`配置文件解析失败:${path}(${cause instanceof Error ? cause.message : String(cause)})`)
29
+ this.name = "ConfigParseError"
30
+ }
31
+ }
32
+
33
+ /** 配置文件的存放约定。 */
34
+ export const CONFIG_FILE_NAME = "config.json"
35
+ /** 配置文件的备份名。 */
36
+ export const CONFIG_BACKUP_NAME = "config.json.bak"
37
+ /** 配置文件权限:只有本人可读写。 */
38
+ export const CONFIG_FILE_MODE = 0o600
39
+ /** 配置目录权限:只有本人可进入。 */
40
+ export const CONFIG_DIR_MODE = 0o700
41
+ /** 外部改写配置文件后,去抖再通知的等待时间(毫秒)。 */
42
+ const WATCH_DEBOUNCE_MS = 150
43
+
44
+ /** 稀疏补丁:路径 → 新值;值为 `null` 表示删掉这个键。 */
45
+ export type ConfigPatch = Record<string, unknown>
46
+
47
+ /** 配置文件读写器。 */
48
+ export class ConfigStore {
49
+ /** 配置文件路径。 */
50
+ readonly path: string
51
+
52
+ constructor(
53
+ path: string,
54
+ private readonly logger?: Logger,
55
+ ) {
56
+ this.path = path
57
+ }
58
+
59
+ /** 备份文件路径。 */
60
+ get backupPath(): string {
61
+ return `${this.path}.bak`
62
+ }
63
+
64
+ /**
65
+ * 读取配置文件。
66
+ *
67
+ * @returns 文件里的原始内容;文件不存在时抛 `ConfigMissingError`。
68
+ */
69
+ async read(): Promise<Record<string, unknown>> {
70
+ let text: string
71
+ try {
72
+ text = await readFile(this.path, "utf8")
73
+ } catch (error) {
74
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
75
+ throw new ConfigMissingError(this.path)
76
+ }
77
+ throw error
78
+ }
79
+ try {
80
+ const parsed = JSON.parse(text) as unknown
81
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
82
+ throw new Error("顶层必须是一个 JSON 对象")
83
+ }
84
+ return parsed as Record<string, unknown>
85
+ } catch (error) {
86
+ throw new ConfigParseError(this.path, error)
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 写配置文件。
92
+ *
93
+ * 原子写 + `0600` 权限;写之前把旧内容存成 `.bak`。
94
+ */
95
+ async write(raw: Record<string, unknown>): Promise<void> {
96
+ await mkdir(dirname(this.path), { recursive: true, mode: CONFIG_DIR_MODE })
97
+ await this.backup()
98
+ const text = `${JSON.stringify(raw, null, 2)}\n`
99
+ await writeFileAtomic(this.path, text, { mode: CONFIG_FILE_MODE, fsync: true })
100
+ }
101
+
102
+ /** 把当前内容存成备份;没有旧文件时跳过。 */
103
+ private async backup(): Promise<void> {
104
+ try {
105
+ const text = await readFile(this.path, "utf8")
106
+ await writeFileAtomic(this.backupPath, text, { mode: CONFIG_FILE_MODE })
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return
109
+ this.logger?.warn("备份配置文件失败", error)
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 在现有内容上应用稀疏补丁。
115
+ *
116
+ * 只改动补丁里出现的路径;值为 `null` 表示删掉这个键,回到默认值。
117
+ *
118
+ * @returns 应用后的完整内容。
119
+ */
120
+ async patch(patch: ConfigPatch): Promise<Record<string, unknown>> {
121
+ const raw = await this.read()
122
+ for (const [path, value] of Object.entries(patch)) {
123
+ const segments = path.split(".").filter(Boolean)
124
+ if (segments.length === 0) continue
125
+ let current = raw
126
+ for (const segment of segments.slice(0, -1)) {
127
+ const child = current[segment]
128
+ if (!child || typeof child !== "object" || Array.isArray(child)) {
129
+ const next: Record<string, unknown> = {}
130
+ current[segment] = next
131
+ current = next
132
+ continue
133
+ }
134
+ current = child as Record<string, unknown>
135
+ }
136
+ const leaf = segments[segments.length - 1]
137
+ if (leaf === undefined) continue
138
+ if (value === null) delete current[leaf]
139
+ else current[leaf] = value
140
+ }
141
+ return raw
142
+ }
143
+
144
+ /**
145
+ * 监听配置文件的外部改动。
146
+ *
147
+ * @param onChange 文件内容变化时调用;读取失败只记日志,不打断监听。
148
+ * @returns 停止监听的函数。
149
+ */
150
+ async watch(onChange: (raw: Record<string, unknown>) => void): Promise<() => void> {
151
+ const watcher: FSWatcher = chokidar.watch(this.path, {
152
+ ignoreInitial: true,
153
+ awaitWriteFinish: { stabilityThreshold: WATCH_DEBOUNCE_MS, pollInterval: 50 },
154
+ })
155
+ let timer: ReturnType<typeof setTimeout> | undefined
156
+ const handler = () => {
157
+ if (timer) clearTimeout(timer)
158
+ timer = setTimeout(() => {
159
+ timer = undefined
160
+ void this.read()
161
+ .then((raw) => onChange(raw))
162
+ .catch((error: unknown) => this.logger?.warn("读取改动后的配置文件失败", error))
163
+ }, WATCH_DEBOUNCE_MS)
164
+ timer.unref?.()
165
+ }
166
+ watcher.on("change", handler).on("add", handler)
167
+ await new Promise<void>((resolve) => {
168
+ watcher.once("ready", () => resolve())
169
+ })
170
+ return () => {
171
+ if (timer) clearTimeout(timer)
172
+ void watcher.close()
173
+ }
174
+ }
175
+ }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * 配置对象的类型定义。
3
+ *
4
+ * 字段清单以 `src/config/fields.ts` 的注册表为准;这里的类型描述运行时
5
+ * 解析后的形状,两边由一致性测试盯着。
6
+ */
7
+
8
+ export interface NapcatConfig {
9
+ /** NapCat 正向 WebSocket 地址,必填。 */
10
+ url: string
11
+ /** NapCat 访问令牌,可选。 */
12
+ token?: string
13
+ }
14
+
15
+ export interface ProactiveConfig {
16
+ /** 是否启用主动说话心跳。 */
17
+ enabled: boolean
18
+ /** 群沉默多少秒后才开始参与主动说话的概率计算。 */
19
+ silenceThresholdSeconds: number
20
+ /** 刚跨过阈值时的初始概率。 */
21
+ startProbability: number
22
+ /** 每多沉默一小时概率的增量。 */
23
+ probabilityPerHour: number
24
+ /** 心跳间隔(秒)。 */
25
+ tickSeconds: number
26
+ /** 只在这些群里主动说话;为空表示不限制。 */
27
+ allowGroups: number[]
28
+ /** 只在这些私聊里主动说话;为空表示不限制。 */
29
+ allowUsers: number[]
30
+ }
31
+
32
+ /** 唤醒判定配置:全局的触发条件。 */
33
+ export interface WakeConfig {
34
+ /** 全局唤醒前缀,命中即必回。 */
35
+ prefixes: string[]
36
+ /** 是否忽略 @全体成员。 */
37
+ ignoreAtAll: boolean
38
+ /** 回复机器人自己的消息是否必回。 */
39
+ replyToSelf: boolean
40
+ /** 群里第一条 @ 的是别人时是否不唤醒机器人。 */
41
+ ignoreAtOthers: boolean
42
+ }
43
+
44
+ /** 回复节奏配置:怎么拆段、怎么发。 */
45
+ export interface ReplyConfig {
46
+ /** 分段之间的最小间隔(毫秒)。 */
47
+ minDelayMs: number
48
+ /** 分段之间的最大间隔(毫秒),0 表示沿用 `sendDelayMs`。 */
49
+ maxDelayMs: number
50
+ /** 单条消息超过该字数就拆成多段发送。 */
51
+ segmentChars: number
52
+ /** 单条回复超过该字数就改用合并转发,0 表示关闭。 */
53
+ forwardThresholdChars: number
54
+ /** 是否要求模型先说明理由才能发送:默认开启。 */
55
+ requirePermission: boolean
56
+ }
57
+
58
+ /** 调用链追踪配置。 */
59
+ export interface TraceConfig {
60
+ /** 是否记录调用链追踪。 */
61
+ enabled: boolean
62
+ /** 追踪文件目录,空表示与日志同目录。 */
63
+ dir: string
64
+ /** 追踪文件总容量上限(MB)。 */
65
+ maxSizeMb: number
66
+ /** 追踪文件保留天数。 */
67
+ retentionDays: number
68
+ }
69
+
70
+ export interface ReminderConfig {
71
+ /** 模型一轮结束时没有调用 qq_send_message 时,是否提醒它补一次。 */
72
+ enabled: boolean
73
+ /** 连续提醒次数上限,避免死循环。 */
74
+ max: number
75
+ }
76
+
77
+ export interface KeepAliveConfig {
78
+ /** 是否启用保活心跳。 */
79
+ enabled: boolean
80
+ /** 保活心跳间隔(秒),必须小于 OpenCode 的 location 空闲超时。 */
81
+ seconds: number
82
+ }
83
+
84
+ export interface HistoryConfig {
85
+ /** 新建会话时补齐的历史消息条数,0 表示关闭。 */
86
+ count: number
87
+ }
88
+
89
+ export interface RateLimitConfig {
90
+ /** 每分钟最多发出多少条消息,0 表示不限制。 */
91
+ maxPerMinute: number
92
+ /** 每小时最多发出多少条消息,0 表示不限制。 */
93
+ maxPerHour: number
94
+ /** 相邻两次发送之间的最小间隔(毫秒),0 表示不限制。 */
95
+ minGapMs: number
96
+ /** 触顶时是否等窗口结束再发;关闭时直接拒绝这次发送。 */
97
+ stall: boolean
98
+ /** 单次等待窗口结束的上限(毫秒)。 */
99
+ stallMaxWaitMs: number
100
+ }
101
+
102
+ export interface SensitiveConfig {
103
+ /** 是否拦截含敏感信息(凭证、令牌)的出站消息。 */
104
+ enabled: boolean
105
+ }
106
+
107
+ /** 日志配置。 */
108
+ export interface LogConfig {
109
+ /** 最低日志级别。 */
110
+ level: LogLevel
111
+ /** 日志目录,空表示用 XDG 状态目录。 */
112
+ dir: string
113
+ /** 单个日志文件的大小上限。 */
114
+ maxSize: string
115
+ /** 保留的历史日志份数。 */
116
+ maxFiles: number
117
+ }
118
+
119
+ /** 事件订阅配置。 */
120
+ export interface EventsConfig {
121
+ /** 订阅哪些事件类别:`message` / `notice`。 */
122
+ subscribe: string[]
123
+ /** notice 类别里具体关心哪些通知;留空表示全收。 */
124
+ notices: string[]
125
+ /** 通知是否注入会话上下文。 */
126
+ inject: boolean
127
+ }
128
+
129
+ /** 媒体配置。 */
130
+ export interface MediaConfig {
131
+ /** 额外允许发送媒体的目录。 */
132
+ allowedDirs: string[]
133
+ }
134
+
135
+ /** 日记的推送方式。 */
136
+ export type DiaryPush = "owner" | "group" | "none"
137
+
138
+ /** 日记配置。 */
139
+ export interface DiaryConfig {
140
+ /** 日记根目录;空表示用机器人工作目录下的 `diary` 子目录。 */
141
+ path: string
142
+ /** 是否启用日记功能。 */
143
+ enabled: boolean
144
+ /** 聊天素材保留天数;只影响素材,不影响日记成品。 */
145
+ retentionDays: number
146
+ /** 每天生成日记的时刻,格式 `HH:mm`,本地时间。 */
147
+ summaryTime: string
148
+ /** 调度轮询间隔(秒)。 */
149
+ tickSeconds: number
150
+ /** 要生成日记的聊天,`group:123` / `private:456`;空表示按准入名单推导。 */
151
+ summaryTargets: string[]
152
+ /** 日记生成后往哪儿推:`owner` 推给所有者,`group` 推回聊天,`none` 不推。 */
153
+ push: DiaryPush
154
+ /** 是否回补历史聊天记录。 */
155
+ backfill: boolean
156
+ /** 回补时最多取多少条历史消息。 */
157
+ backfillMax: number
158
+ /** 单条素材的最大字符数。 */
159
+ maxLineChars: number
160
+ /** 单个聊天单天最多保留多少条素材。 */
161
+ maxLinesPerDay: number
162
+ /** 等待模型总结的超时时间(毫秒)。 */
163
+ timeoutMs: number
164
+ }
165
+
166
+ /** 状态面板配置。 */
167
+ export interface PanelConfig {
168
+ /** 是否启用面板。 */
169
+ enabled: boolean
170
+ /** 监听地址。 */
171
+ host: string
172
+ /** 监听端口。 */
173
+ port: number
174
+ /** 访问令牌;留空时自动生成并写回配置文件。 */
175
+ token: string
176
+ }
177
+
178
+ export interface ModelRef {
179
+ providerID: string
180
+ id: string
181
+ variant?: string
182
+ }
183
+
184
+ /** 日志级别。 */
185
+ export type LogLevel = "debug" | "info" | "warn" | "error"
186
+
187
+ export interface QQBotConfig {
188
+ napcat: NapcatConfig
189
+ /** 准入配置:放行名单、拒绝名单与名单为空时的行为。 */
190
+ access: AccessConfig
191
+ /** 机器人所有者 QQ 号:可用管理命令,并拥有全部工具权限。 */
192
+ ownerQQ?: number
193
+ /** 管理员 QQ 号:拥有全部工具权限。 */
194
+ admins: number[]
195
+ /** 工具配置文件路径;相对路径按机器人工作目录解析,空表示工作目录下的 `tool-profiles.json`。 */
196
+ toolProfilesPath?: string
197
+ /** 会话行为覆盖文件路径;相对路径按机器人工作目录解析,空表示工作目录下的 `chat-overrides.json`。 */
198
+ chatOverridesPath?: string
199
+ /** 角色设定文件路径;相对路径按机器人工作目录解析,默认取工作目录里的 souls/。 */
200
+ soulPath?: string
201
+ /** 工作目录 souls 里的角色设定文件名,默认 default.txt。 */
202
+ soulName?: string
203
+ /** QQ 会话使用的 OpenCode agent。 */
204
+ agent?: string
205
+ /** QQ 会话使用的模型。 */
206
+ model?: ModelRef
207
+ /** 拆行发送时每条消息之间的间隔(毫秒)。 */
208
+ sendDelayMs: number
209
+ /** 单次发送的内容超过该长度时告警(不截断)。 */
210
+ warnLength: number
211
+ /** 重启后是否复用上一次的会话。 */
212
+ reuseSession: boolean
213
+ proactive: ProactiveConfig
214
+ wake: WakeConfig
215
+ reply: ReplyConfig
216
+ trace: TraceConfig
217
+ reminder: ReminderConfig
218
+ keepAlive: KeepAliveConfig
219
+ history: HistoryConfig
220
+ rateLimit: RateLimitConfig
221
+ sensitive: SensitiveConfig
222
+ events: EventsConfig
223
+ log: LogConfig
224
+ media: MediaConfig
225
+ diary: DiaryConfig
226
+ panel: PanelConfig
227
+ }
228
+
229
+ /** 准入配置。 */
230
+ export interface AccessConfig {
231
+ /** 放行名单。 */
232
+ allow: { groups: number[]; users: number[] }
233
+ /** 拒绝名单。 */
234
+ deny: { groups: number[]; users: number[] }
235
+ /** 放行名单为空时是否放行全部目标。 */
236
+ allowAllWhenEmpty: boolean
237
+ }
238
+
239
+ /** 解析前的配置形状:文件里没写的字段都是空的。 */
240
+ export type RawConfig = Record<string, unknown>
241
+
242
+ /** zod 解析后的形状:没写的可选项是空的。 */
243
+ export type ParsedConfig = Omit<
244
+ QQBotConfig,
245
+ "napcat" | "ownerQQ" | "model" | "soulPath" | "soulName"
246
+ > & {
247
+ /** NapCat 连接信息:地址必填但可能缺失,令牌可选。 */
248
+ napcat: { url?: string; token?: string }
249
+ ownerQQ?: number
250
+ model?: ModelRef
251
+ soulPath?: string
252
+ soulName?: string
253
+ }