@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.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/src/overrides.ts CHANGED
@@ -1,8 +1,16 @@
1
1
  import { readFile, stat } from "node:fs/promises"
2
- import { join } from "node:path"
2
+ import { join, resolve } from "node:path"
3
3
  import { type ChatTarget, targetKey } from "./chat"
4
- import { DEFAULT_CONFIG, parseModelRef, type ModelRef, type WakeConfig } from "./config"
4
+ import {
5
+ DEFAULT_CONFIG,
6
+ parseModelRef,
7
+ type CollectConfig,
8
+ type ModelRef,
9
+ type WakeConfig,
10
+ } from "./config"
5
11
  import type { Logger } from "./logger"
12
+ import { safeMap } from "./safe-object"
13
+ import { SOUL_DIR, soulRoots, withinRoots } from "./session/soul-guard"
6
14
 
7
15
  /** 唤醒方式:决定群里的消息要不要让模型必须回复。 */
8
16
  export type WakeMode = "all" | "mention" | "prefix" | "none"
@@ -36,6 +44,12 @@ export const DEFAULT_WAKE_POLICY: WakePolicy = {
36
44
  prefixes: [...DEFAULT_CONFIG.wake.prefixes],
37
45
  }
38
46
 
47
+ /** 全局收集窗口策略:与配置项 `collect` 同构。 */
48
+ export type CollectPolicy = CollectConfig
49
+
50
+ /** 内置的全局收集窗口策略,取自配置默认值。 */
51
+ export const DEFAULT_COLLECT_POLICY: CollectPolicy = { ...DEFAULT_CONFIG.collect }
52
+
39
53
  /** 唤醒判定的结果。 */
40
54
  export interface WakeDecision {
41
55
  /** 本轮是否必须回复。 */
@@ -54,22 +68,32 @@ export interface ProactiveScope {
54
68
  allowUsers: number[]
55
69
  }
56
70
 
57
- /** 单个聊天的行为覆盖。 */
71
+ /**
72
+ * 单个聊天的行为覆盖。
73
+ *
74
+ * 键名与全局配置项一致:会话能改哪一项,就用那一项在 `config.json` 里的名字。
75
+ */
58
76
  export interface ChatOverride {
59
- /** 唤醒方式,缺省按被 @ 才必回。 */
77
+ /** 唤醒方式,缺省按被 @ 才必回;全局没有对应项,只在会话层出现。 */
60
78
  wake?: WakeMode
61
- /** 唤醒前缀,`wake` 为 `prefix` 时用。 */
62
- prefix?: string
63
- /** 是否允许主动说话,false 表示这个聊天不主动开口。 */
64
- proactive?: boolean
65
- /** 这个聊天主动说话的概率,0 到 1;缺省按全局公式计算。 */
66
- proactiveProbability?: number
79
+ /** 唤醒前缀,`wake` 为 `prefix` 时用;与全局 `wake.prefixes` 同名同形。 */
80
+ "wake.prefixes"?: string[]
81
+ /** 是否允许主动说话,对应全局 `proactive.enabled`。 */
82
+ "proactive.enabled"?: boolean
83
+ /** 这个聊天单次心跳的触发概率,对应全局 `proactive.startProbability`。 */
84
+ "proactive.startProbability"?: number
85
+ /** 私聊的消息收集窗口(毫秒),对应全局 `collect.privateMs`。 */
86
+ "collect.privateMs"?: number
87
+ /** 群聊的消息收集窗口(毫秒),对应全局 `collect.groupMs`。 */
88
+ "collect.groupMs"?: number
67
89
  /** 覆盖该聊天使用的 OpenCode agent。 */
68
90
  agent?: string
69
91
  /** 覆盖该聊天使用的模型,格式 `provider/model[/variant]`。 */
70
92
  model?: ModelRef
71
- /** 覆盖该聊天使用的角色设定文件路径。 */
72
- soul?: string
93
+ /** 覆盖该聊天使用的角色设定文件或目录,对应全局 `soulPath`。 */
94
+ soulPath?: string
95
+ /** 覆盖该聊天使用的角色设定文件名,对应全局 `soulName`。 */
96
+ soulName?: string
73
97
  }
74
98
 
75
99
  /** `chat-overrides.json` 的结构。 */
@@ -88,6 +112,61 @@ export function defaultChatOverridesPath(home: string): string {
88
112
  return join(home, "chat-overrides.json")
89
113
  }
90
114
 
115
+ /**
116
+ * 解析会话覆盖文件的实际位置。
117
+ *
118
+ * 配置里写了 `chatOverridesPath` 就按工作目录解析(绝对路径原样使用),
119
+ * 没写就用工作目录下的默认位置。启动与面板共用这一份解析。
120
+ */
121
+ export function resolveChatOverridesPath(
122
+ config: { chatOverridesPath?: string },
123
+ home: string,
124
+ ): string {
125
+ const configured = config.chatOverridesPath?.trim()
126
+ return configured ? resolve(home, configured) : defaultChatOverridesPath(home)
127
+ }
128
+
129
+ /** 解析会话覆盖时的边界选项。 */
130
+ export interface ChatOverrideParseOptions {
131
+ /** 机器人工作目录:角色设定路径默认在它下面。 */
132
+ home?: string
133
+ /** 额外允许的角色设定根目录。 */
134
+ allowedPaths?: readonly string[]
135
+ }
136
+
137
+ /** 角色设定路径是否在允许的目录之内。 */
138
+ function soulPathAllowed(value: string, options: ChatOverrideParseOptions): boolean {
139
+ if (!options.home) return true
140
+ const roots = soulRoots({ home: options.home, allowedPaths: options.allowedPaths })
141
+ return withinRoots(resolve(options.home, value), roots)
142
+ }
143
+
144
+ /** 角色设定文件名是否落在允许的目录之内。 */
145
+ function soulNameAllowed(value: string, options: ChatOverrideParseOptions): boolean {
146
+ if (!options.home) return true
147
+ const roots = soulRoots({ home: options.home, allowedPaths: options.allowedPaths })
148
+ return withinRoots(join(options.home, SOUL_DIR, value), roots)
149
+ }
150
+
151
+ /** 从聊天键判断聊天类型:键形不对就返回 undefined。 */
152
+ function chatKindOf(key: string): ChatTarget["kind"] | undefined {
153
+ if (key.startsWith("group:")) return "group"
154
+ if (key.startsWith("private:")) return "private"
155
+ return undefined
156
+ }
157
+
158
+ /** 解析收集窗口的毫秒数:不是 0 或更大的数字就返回 undefined。 */
159
+ function parseCollectMs(raw: unknown): number | undefined {
160
+ const value =
161
+ typeof raw === "number"
162
+ ? raw
163
+ : typeof raw === "string" && raw.trim()
164
+ ? Number(raw.trim())
165
+ : Number.NaN
166
+ if (!Number.isFinite(value) || value < 0) return undefined
167
+ return Math.floor(value)
168
+ }
169
+
91
170
  /**
92
171
  * 解析并校验覆盖配置。
93
172
  *
@@ -96,6 +175,7 @@ export function defaultChatOverridesPath(home: string): string {
96
175
  export function parseChatOverrides(
97
176
  value: unknown,
98
177
  warn: (message: string) => void,
178
+ options: ChatOverrideParseOptions = {},
99
179
  ): ChatOverridesFile {
100
180
  if (!value || typeof value !== "object" || Array.isArray(value)) {
101
181
  warn("会话覆盖必须是对象,已忽略")
@@ -108,7 +188,7 @@ export function parseChatOverrides(
108
188
  warn("chats 必须是对象,已忽略")
109
189
  return defaultChatOverrides()
110
190
  }
111
- const chats: Record<string, ChatOverride> = {}
191
+ const chats = safeMap<ChatOverride>()
112
192
  for (const [key, entry] of Object.entries(source as Record<string, unknown>)) {
113
193
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
114
194
  warn(`会话覆盖 ${key} 必须是对象,已忽略`)
@@ -123,23 +203,28 @@ export function parseChatOverrides(
123
203
  warn(`会话覆盖 ${key} 的 wake 只能是 ${WAKE_MODES.join(" / ")},已忽略`)
124
204
  }
125
205
  }
126
- if (record.prefix !== undefined) {
127
- if (typeof record.prefix === "string") {
128
- const prefix = record.prefix.trim()
129
- if (prefix) override.prefix = prefix
206
+ if (record["wake.prefixes"] !== undefined) {
207
+ const raw = record["wake.prefixes"]
208
+ if (!Array.isArray(raw)) {
209
+ warn(`会话覆盖 ${key} 的 wake.prefixes 必须是字符串数组,已忽略`)
130
210
  } else {
131
- warn(`会话覆盖 ${key} 的 prefix 必须是字符串,已忽略`)
211
+ const prefixes = raw
212
+ .filter((item): item is string => typeof item === "string")
213
+ .map((item) => item.trim())
214
+ .filter((item) => item.length > 0)
215
+ if (prefixes.length > 0) override["wake.prefixes"] = prefixes
216
+ else warn(`会话覆盖 ${key} 的 wake.prefixes 至少要有一个非空前缀,已忽略`)
132
217
  }
133
218
  }
134
- if (record.proactive !== undefined) {
135
- if (typeof record.proactive === "boolean") {
136
- override.proactive = record.proactive
219
+ if (record["proactive.enabled"] !== undefined) {
220
+ if (typeof record["proactive.enabled"] === "boolean") {
221
+ override["proactive.enabled"] = record["proactive.enabled"]
137
222
  } else {
138
- warn(`会话覆盖 ${key} 的 proactive 必须是布尔值,已忽略`)
223
+ warn(`会话覆盖 ${key} 的 proactive.enabled 必须是布尔值,已忽略`)
139
224
  }
140
225
  }
141
- if (record.proactiveProbability !== undefined) {
142
- const raw = record.proactiveProbability
226
+ if (record["proactive.startProbability"] !== undefined) {
227
+ const raw = record["proactive.startProbability"]
143
228
  const value =
144
229
  typeof raw === "number"
145
230
  ? raw
@@ -147,9 +232,9 @@ export function parseChatOverrides(
147
232
  ? Number(raw.trim())
148
233
  : Number.NaN
149
234
  if (Number.isFinite(value) && value >= 0 && value <= 1) {
150
- override.proactiveProbability = value
235
+ override["proactive.startProbability"] = value
151
236
  } else {
152
- warn(`会话覆盖 ${key} 的 proactiveProbability 必须是 0 到 1 之间的数字,已忽略`)
237
+ warn(`会话覆盖 ${key} 的 proactive.startProbability 必须是 0 到 1 之间的数字,已忽略`)
153
238
  }
154
239
  }
155
240
  if (record.agent !== undefined) {
@@ -164,16 +249,49 @@ export function parseChatOverrides(
164
249
  if (model) override.model = model
165
250
  else warn(`会话覆盖 ${key} 的 model 必须是 provider/model[/variant],已忽略`)
166
251
  }
167
- if (record.soul !== undefined) {
168
- if (typeof record.soul === "string" && record.soul.trim()) {
169
- override.soul = record.soul.trim()
252
+ if (record.soulPath !== undefined) {
253
+ const value = typeof record.soulPath === "string" ? record.soulPath.trim() : ""
254
+ if (!value) {
255
+ warn(`会话覆盖 ${key} 的 soulPath 必须是非空字符串,已忽略`)
256
+ } else if (!soulPathAllowed(value, options)) {
257
+ warn(`会话覆盖 ${key} 的 soulPath 超出允许的目录,已忽略`)
258
+ } else {
259
+ override.soulPath = value
260
+ }
261
+ }
262
+ if (record.soulName !== undefined) {
263
+ const value = typeof record.soulName === "string" ? record.soulName.trim() : ""
264
+ if (!value) {
265
+ warn(`会话覆盖 ${key} 的 soulName 必须是非空字符串,已忽略`)
266
+ } else if (!soulNameAllowed(value, options)) {
267
+ warn(`会话覆盖 ${key} 的 soulName 超出允许的目录,已忽略`)
268
+ } else {
269
+ override.soulName = value
270
+ }
271
+ }
272
+ if (record["collect.privateMs"] !== undefined) {
273
+ const value = parseCollectMs(record["collect.privateMs"])
274
+ if (value === undefined) {
275
+ warn(`会话覆盖 ${key} 的 collect.privateMs 必须是 0 或更大的毫秒数,已忽略`)
276
+ } else if (chatKindOf(key) === "group") {
277
+ warn(`会话覆盖 ${key} 是群聊,collect.privateMs 不适用,已忽略`)
170
278
  } else {
171
- warn(`会话覆盖 ${key} 的 soul 必须是非空字符串,已忽略`)
279
+ override["collect.privateMs"] = value
172
280
  }
173
281
  }
174
- if (override.wake === "prefix" && !override.prefix) {
282
+ if (record["collect.groupMs"] !== undefined) {
283
+ const value = parseCollectMs(record["collect.groupMs"])
284
+ if (value === undefined) {
285
+ warn(`会话覆盖 ${key} 的 collect.groupMs 必须是 0 或更大的毫秒数,已忽略`)
286
+ } else if (chatKindOf(key) === "private") {
287
+ warn(`会话覆盖 ${key} 是私聊,collect.groupMs 不适用,已忽略`)
288
+ } else {
289
+ override["collect.groupMs"] = value
290
+ }
291
+ }
292
+ if (override.wake === "prefix" && !override["wake.prefixes"]?.length) {
175
293
  // 没有前缀就没法判断,改回被 @ 才必回,别让群变成完全不回话。
176
- warn(`会话覆盖 ${key} 使用 prefix 唤醒但没有写 prefix,已按被 @ 才必回处理`)
294
+ warn(`会话覆盖 ${key} 使用 prefix 唤醒但没有写 wake.prefixes,已按被 @ 才必回处理`)
177
295
  delete override.wake
178
296
  }
179
297
  chats[key] = override
@@ -188,6 +306,7 @@ export class ChatOverrides {
188
306
  constructor(
189
307
  private readonly path: string,
190
308
  private readonly logger: Logger,
309
+ private readonly options: ChatOverrideParseOptions = {},
191
310
  ) {}
192
311
 
193
312
  /** 当前生效的覆盖配置;文件改动后按 mtime 重新读取。 */
@@ -200,9 +319,13 @@ export class ChatOverrides {
200
319
  if (this.cached && this.cached.mtime === info.mtimeMs) return this.cached.file
201
320
  try {
202
321
  const text = await readFile(this.path, "utf8")
203
- const file = parseChatOverrides(JSON.parse(text), (message) => {
204
- this.logger.warn(`会话覆盖 ${this.path}:${message}`)
205
- })
322
+ const file = parseChatOverrides(
323
+ JSON.parse(text),
324
+ (message) => {
325
+ this.logger.warn(`会话覆盖 ${this.path}:${message}`)
326
+ },
327
+ this.options,
328
+ )
206
329
  this.cached = { mtime: info.mtimeMs, file }
207
330
  return file
208
331
  } catch (error) {
@@ -250,8 +373,9 @@ export function wakeDecision(
250
373
  if (policy.ignoreAtOthers && context.atOthersFirst) return { required: false, suppress: true }
251
374
  // 前缀模式只看这个聊天自己的前缀。
252
375
  if (override.wake === "prefix") {
253
- const prefix = override.prefix
254
- return prefix && context.text.trimStart().startsWith(prefix)
376
+ const text = context.text.trimStart()
377
+ const prefixes = override["wake.prefixes"] ?? []
378
+ return prefixes.some((prefix) => prefix && text.startsWith(prefix))
255
379
  ? { required: true, reason: "prefix" }
256
380
  : { required: false }
257
381
  }
@@ -272,40 +396,78 @@ export function wakeDecision(
272
396
  * 这个聊天允不允许主动说话。
273
397
  *
274
398
  * 默认拒绝:白名单为空表示一个都不放行,必须显式配置才会主动开口。
275
- * 聊天自己的覆盖里写了 `proactive: true` 才算显式打开,那一条不受白名单限制。
399
+ * 聊天自己的覆盖里写了 `proactive.enabled: true` 才算显式打开,那一条不受白名单限制。
276
400
  */
277
401
  export function proactiveAllowed(
278
402
  override: ChatOverride,
279
403
  target: ChatTarget,
280
404
  scope: ProactiveScope,
281
405
  ): boolean {
282
- if (override.proactive === false) return false
406
+ if (override["proactive.enabled"] === false) return false
283
407
  if (chatMuted(override, target)) return false
284
408
  // 写死打开的聊天不受白名单限制。
285
- if (override.proactive === true) return true
409
+ if (override["proactive.enabled"] === true) return true
286
410
  const list = target.kind === "group" ? scope.allowGroups : scope.allowUsers
287
411
  // 名单为空表示这一类一个都不放行。
288
412
  if (list.length === 0) return false
289
413
  return list.includes(target.id)
290
414
  }
291
415
 
416
+ /**
417
+ * 这个聊天实际生效的消息收集窗口(毫秒)。
418
+ *
419
+ * 聊天自己写的覆盖优先,没写就用全局的。私聊看 `collect.privateMs`,
420
+ * 群聊看 `collect.groupMs`。0 表示不收集:收到消息就立刻回复。
421
+ */
422
+ export function collectWindowMs(
423
+ override: ChatOverride,
424
+ target: ChatTarget,
425
+ policy: CollectPolicy = DEFAULT_COLLECT_POLICY,
426
+ ): number {
427
+ const own = target.kind === "group" ? override["collect.groupMs"] : override["collect.privateMs"]
428
+ const fallback = target.kind === "group" ? policy.groupMs : policy.privateMs
429
+ const value = typeof own === "number" ? own : fallback
430
+ if (!Number.isFinite(value) || value <= 0) return 0
431
+ return Math.floor(value)
432
+ }
433
+
434
+ /** 收集窗口的简明写法:0 表示立即回复。 */
435
+ function describeCollectMs(ms: number): string {
436
+ return ms > 0 ? `${ms}ms` : "立即"
437
+ }
438
+
292
439
  /** 覆盖配置的简明描述,给 `/status` 看。 */
293
- export function describeOverride(override: ChatOverride): string {
440
+ export function describeOverride(
441
+ override: ChatOverride,
442
+ target?: ChatTarget,
443
+ policy: CollectPolicy = DEFAULT_COLLECT_POLICY,
444
+ ): string {
294
445
  const parts: string[] = []
295
446
  parts.push(override.wake ? `唤醒 ${override.wake}` : "唤醒 mention(默认)")
296
- if (override.wake === "prefix") parts.push(`前缀 ${override.prefix ?? "(未设置)"}`)
447
+ if (override.wake === "prefix") {
448
+ const prefixes = override["wake.prefixes"]?.join(" / ")
449
+ parts.push(`前缀 ${prefixes ?? "(未设置)"}`)
450
+ }
297
451
  parts.push(
298
- override.proactive === true
452
+ override["proactive.enabled"] === true
299
453
  ? "主动说话"
300
- : override.proactive === false
454
+ : override["proactive.enabled"] === false
301
455
  ? "不主动说话"
302
456
  : "主动说话跟随白名单",
303
457
  )
304
- if (override.proactiveProbability !== undefined) {
305
- parts.push(`主动概率 ${override.proactiveProbability}`)
458
+ if (override["proactive.startProbability"] !== undefined) {
459
+ parts.push(`主动概率 ${override["proactive.startProbability"]}`)
306
460
  }
307
461
  if (override.agent) parts.push(`agent ${override.agent}`)
308
462
  if (override.model) parts.push(`模型 ${override.model.providerID}/${override.model.id}`)
309
- if (override.soul) parts.push(`角色设定 ${override.soul}`)
463
+ if (override.soulPath) parts.push(`角色设定 ${override.soulPath}`)
464
+ else if (override.soulName) parts.push(`角色设定 ${override.soulName}`)
465
+ if (target) {
466
+ parts.push(`收集 ${describeCollectMs(collectWindowMs(override, target, policy))}`)
467
+ } else if (override["collect.privateMs"] !== undefined) {
468
+ parts.push(`私聊收集 ${describeCollectMs(override["collect.privateMs"])}`)
469
+ } else if (override["collect.groupMs"] !== undefined) {
470
+ parts.push(`群聊收集 ${describeCollectMs(override["collect.groupMs"])}`)
471
+ }
310
472
  return parts.join(",")
311
473
  }
package/src/panel/api.ts CHANGED
@@ -16,6 +16,12 @@ import {
16
16
  } from "../config/registry"
17
17
  import { readLogTail, subscribeLogs, type LogEntry } from "../logger"
18
18
  import { PanelAuth, SESSION_COOKIE } from "./auth"
19
+ import {
20
+ readChatOverrides,
21
+ readToolProfiles,
22
+ saveChatOverrides,
23
+ saveToolProfiles,
24
+ } from "./documents"
19
25
  import type { ModelProvider } from "./models"
20
26
  import { collectStatus } from "./status"
21
27
  import type { PanelRuntime } from "./runtime"
@@ -90,20 +96,24 @@ export function createPanelApp(options: PanelAppOptions): Hono {
90
96
  }),
91
97
  )
92
98
 
93
- // 写接口校验 Origin:带 Origin 的请求必须同源,不带的(curl)放行。
99
+ // 写接口校验 Origin:带 Origin 的请求必须同源。
100
+ // 带会话 Cookie 的请求必须带 Origin:Cookie 会被浏览器自动带上,
101
+ // 没有 Origin 的请求才可能是脚本伪造的。Bearer 令牌走命令行,不带 Origin 是正常的。
94
102
  app.use("/api/*", async (c, next) => {
95
103
  if (SAFE_METHODS.has(c.req.method)) return await next()
96
104
  const origin = c.req.header("Origin")
105
+ let expected = ""
106
+ try {
107
+ expected = new URL(c.req.url).origin
108
+ } catch {
109
+ expected = ""
110
+ }
97
111
  if (origin) {
98
- let expected = ""
99
- try {
100
- expected = new URL(c.req.url).origin
101
- } catch {
102
- expected = ""
103
- }
104
112
  if (origin !== expected) {
105
113
  return c.json({ error: "forbidden", message: "跨站请求已被拒绝" }, 403)
106
114
  }
115
+ } else if (getCookie(c, SESSION_COOKIE)) {
116
+ return c.json({ error: "forbidden", message: "缺少 Origin 头,请求已被拒绝" }, 403)
107
117
  }
108
118
  return await next()
109
119
  })
@@ -192,6 +202,50 @@ export function createPanelApp(options: PanelAppOptions): Hono {
192
202
  }
193
203
  })
194
204
 
205
+ // 会话覆盖文件:生效值、文件值与告警。
206
+ app.get("/api/chat-overrides", async (c) => {
207
+ return c.json(await readChatOverrides(runtime))
208
+ })
209
+
210
+ // 保存会话覆盖:稀疏改动,校验在服务端做。
211
+ app.put("/api/chat-overrides", async (c) => {
212
+ const contentType = c.req.header("Content-Type") ?? ""
213
+ if (!contentType.toLowerCase().includes("application/json")) {
214
+ return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
215
+ }
216
+ const body = await readJson(c.req.raw)
217
+ const { problems, result } = await saveChatOverrides(runtime, body)
218
+ if (!result) {
219
+ return c.json(
220
+ { error: "validation_failed", message: "会话覆盖校验不通过", fields: problems },
221
+ 400,
222
+ )
223
+ }
224
+ return c.json({ ok: true, ...result })
225
+ })
226
+
227
+ // 工具配置文件:生效值、文件值与告警。
228
+ app.get("/api/tool-profiles", async (c) => {
229
+ return c.json(await readToolProfiles(runtime))
230
+ })
231
+
232
+ // 保存工具配置:稀疏改动,校验在服务端做。
233
+ app.put("/api/tool-profiles", async (c) => {
234
+ const contentType = c.req.header("Content-Type") ?? ""
235
+ if (!contentType.toLowerCase().includes("application/json")) {
236
+ return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
237
+ }
238
+ const body = await readJson(c.req.raw)
239
+ const { problems, result } = await saveToolProfiles(runtime, body)
240
+ if (!result) {
241
+ return c.json(
242
+ { error: "validation_failed", message: "工具配置校验不通过", fields: problems },
243
+ 400,
244
+ )
245
+ }
246
+ return c.json({ ok: true, ...result })
247
+ })
248
+
195
249
  // 可用模型列表。
196
250
  app.get("/api/models", async (c) => {
197
251
  try {