@linjz/opencode-qqbot 0.3.16 → 0.3.18

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 (45) hide show
  1. package/README.md +316 -266
  2. package/README.zh-CN.md +326 -0
  3. package/dist/notify-cli.js +64 -12
  4. package/dist/opencode-qqbot-plugin.js +591 -92
  5. package/dist/openqq-bot.js +1172 -303
  6. package/dist/openqq-cli.js +253 -64
  7. package/dist/openqq-watchdog.js +373 -110
  8. package/package.json +4 -3
  9. package/src/bridge.ts +448 -32
  10. package/src/cli/notify.ts +4 -1
  11. package/src/cli/watchdog-main.ts +22 -7
  12. package/src/commands.ts +74 -58
  13. package/src/config.ts +39 -5
  14. package/src/core/bot-config.ts +66 -0
  15. package/src/core/bot-control.ts +21 -3
  16. package/src/core/bot-launcher.ts +4 -2
  17. package/src/core/cron-reminders.ts +84 -0
  18. package/src/core/delivery.ts +24 -1
  19. package/src/core/discovery.ts +207 -169
  20. package/src/core/error-rescue.ts +1 -1
  21. package/src/core/file-log.ts +16 -7
  22. package/src/core/inflight-journal.ts +1 -0
  23. package/src/core/instance-lock.ts +32 -1
  24. package/src/core/log-rotate.ts +91 -0
  25. package/src/core/mirror.ts +13 -4
  26. package/src/core/notices.ts +62 -0
  27. package/src/core/outbound-sanitize.ts +29 -0
  28. package/src/core/permission.ts +16 -0
  29. package/src/core/qq-instructions.ts +122 -0
  30. package/src/core/queue-view.ts +1 -0
  31. package/src/core/send-media.ts +29 -2
  32. package/src/core/send-requests.ts +227 -0
  33. package/src/core/start-error.ts +26 -0
  34. package/src/core/stt.ts +55 -0
  35. package/src/core/supervisor-election.ts +53 -0
  36. package/src/core/turn-correction.ts +68 -0
  37. package/src/core/watchdog.ts +171 -14
  38. package/src/index.ts +262 -250
  39. package/src/opencode/client.ts +32 -1
  40. package/src/opencode/mirror.ts +17 -4
  41. package/src/opencode/sessions.ts +20 -1
  42. package/src/plugin-entry.ts +67 -2
  43. package/src/qq/gateway.ts +35 -0
  44. package/src/qq/media.ts +21 -0
  45. package/src/qq/sender.ts +50 -1
package/src/cli/notify.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  import { existsSync, readFileSync } from "node:fs"
8
8
  import { createOutbox } from "../core/outbox.js"
9
9
  import { ENV_FILE, loadEnvFile } from "../config.js"
10
+ import { applyConfigOverlay } from "../core/bot-config.js"
10
11
  import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
11
12
 
12
13
  export interface NotifyCliOptions {
@@ -108,7 +109,9 @@ export async function runNotifyCli(
108
109
  console.log(help)
109
110
  return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" }
110
111
  }
111
- // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
112
+ // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)。
113
+ // config.json 先叠加(最低层),.env 后加载自然覆盖它——与 bot 入口同一层级序。
114
+ applyConfigOverlay()
112
115
  if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
113
116
  const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
114
117
  .split(/[,\s]+/).filter(Boolean)
@@ -10,11 +10,10 @@
10
10
  //
11
11
  // 2026-11-09 重构:裸 healOnce 升级为 superviseOnce——优雅杀(TERM→宽限→KILL)、
12
12
  // 冷却(防互踢)、重启强度(超限 give-up 并告警,不当永动机)、监督者认领互斥。
13
- import { botWatchdogPaths, readEnvField, appendWatchdogLog, superviseOnce } from "../core/watchdog.js"
13
+ import { botWatchdogPaths, appendWatchdogLog, superviseOnce, readBotHealth, isBotDown } from "../core/watchdog.js"
14
14
  import { readAppId, startBot } from "../core/bot-control.js"
15
+ import { electSupervisor } from "../core/supervisor-election.js"
15
16
  import { runNotifyCli } from "./notify.js"
16
- import { join } from "path"
17
- import { homedir } from "os"
18
17
 
19
18
  const DEFAULT_INTERVAL_MIN = 10
20
19
 
@@ -27,7 +26,8 @@ function parseArgs(argv: string[]): { loop: boolean; intervalMin: number } {
27
26
  }
28
27
 
29
28
  function currentAppId(): string | null {
30
- return readAppId() ?? readEnvField(join(homedir(), ".openqq", ".env"), "QQ_APP_ID")
29
+ // readAppId 已含 QQ_BOTS 首角色回退(2026-11-20 应修尽修批)
30
+ return readAppId()
31
31
  }
32
32
 
33
33
  /** give-up 上报:入队 QQ 通知(bot 恢复后送达)+本进程日志;失败静默(fail-open)。 */
@@ -39,8 +39,19 @@ function alert(message: string): void {
39
39
  }
40
40
 
41
41
  async function tick(appId: string): Promise<void> {
42
+ const paths = botWatchdogPaths(appId)
43
+ // 双触发器归一(2026-11-20 owner 批):service 与 plugin 两通道租约选主。
44
+ // 破格条款(11-20 灵魂不在线复发实证):让贤仅当 bot 健康——bot 失能时无人
45
+ // 监督的空窗比双触发干扰致命(14:56-15:07 bot 死而两通道互相让贤实录)。
46
+ if (!electSupervisor("service")) {
47
+ if (!isBotDown(readBotHealth(paths, Date.now()))) {
48
+ appendWatchdogLog("[supervisor] 让贤:plugin 通道持监督租约中,本轮跳过")
49
+ return
50
+ }
51
+ appendWatchdogLog("[supervisor] 破格接管:plugin 持租约但 bot 失能——让贤条款不适用")
52
+ }
42
53
  const result = await superviseOnce({
43
- paths: botWatchdogPaths(appId),
54
+ paths,
44
55
  spawn: () => startBot(import.meta.url, (line) => console.log(line)),
45
56
  log: (line) => console.log(line),
46
57
  alert,
@@ -54,14 +65,17 @@ async function main(): Promise<void> {
54
65
  const args = parseArgs(process.argv.slice(2))
55
66
  const appId = currentAppId()
56
67
  if (!appId) {
57
- console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁")
68
+ console.error("[watchdog] 未找到任何角色凭据(~/.openqq/.env 缺 QQ_APP_ID/QQ_APP_SECRET 且 QQ_BOTS 无合法角色),无法定位实例锁")
58
69
  process.exit(1)
59
70
  }
60
71
  console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`)
61
72
  await tick(appId)
62
73
  if (!args.loop) return
63
74
  const timer = setInterval(() => {
64
- void tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error))
75
+ void tick(appId).catch((error) => {
76
+ appendWatchdogLog(`[watchdog] 巡检失败: ${error instanceof Error ? error.message : String(error)}`)
77
+ console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error)
78
+ })
65
79
  }, args.intervalMin * 60_000)
66
80
  const stop = (): void => {
67
81
  clearInterval(timer)
@@ -72,6 +86,7 @@ async function main(): Promise<void> {
72
86
  }
73
87
 
74
88
  void main().catch((error) => {
89
+ appendWatchdogLog(`[watchdog] 致命错误: ${error instanceof Error ? error.message : String(error)}`)
75
90
  console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error)
76
91
  process.exit(1)
77
92
  })
package/src/commands.ts CHANGED
@@ -1,6 +1,6 @@
1
- // @input: ./config, ./qq/types, ./opencode/* (client, sessions)
1
+ // @input: ./config, ./qq/types, ./opencode/* (client, sessions)
2
2
  // @output: isCommand, handleCommand, handlePendingSelection, CommandContext, PendingSelection
3
- // @pos: 根层 - 命令系统: /new /stop /status /sessions /help /model /agent /rename
3
+ // @pos: 根层 - 命令系统: /new /cancel /status /sessions /help /models /agents /rename /history /send /progress /queue /ledger /goal /compact /redo /btw /undo /amend
4
4
  import type { Config } from "./config.js"
5
5
  import type { MessageContext } from "./qq/types.js"
6
6
  import type { OpencodeClient, SessionMessage } from "./opencode/client.js"
@@ -61,6 +61,14 @@ export interface CommandContext {
61
61
  progress: ProgressApi
62
62
  /** P1 防线 B:/cancel 彻底复位(清队列+abort+杀后台等待+结清在途账+drain) */
63
63
  stopAll: (userId: string) => Promise<{ cleared: number; title: string | undefined }>
64
+ /** steer 降级版:/amend <补充> 打断当前任务并以「原 prompt+补充」续跑(2026-11-22,参考 Hermes update_prompt) */
65
+ amend: (userId: string, amendment: string) => Promise<string>
66
+ /** 对齐官方 /undo:回滚上一回合并恢复文件,回执带被撤 prompt(2026-11-23,opencode.ai/docs/snapshots 为准) */
67
+ undo: (userId: string) => Promise<string>
68
+ /** 显性入队(/queue <文本>,owner 2026-11-23):steer 默认下的显式排队动词——排进 FIFO,当前任务跑完才执行 */
69
+ enqueue: (ctx: MessageContext, text: string) => Promise<string>
70
+ /** 官方斜杠命令直通(owner 2026-11-23):/goal /compact /redo /btw 走引擎内置实现,与桌面端同语义 */
71
+ engineCommand: (userId: string, name: string, text: string) => Promise<string>
64
72
  }
65
73
 
66
74
  export interface PendingSelection {
@@ -106,9 +114,20 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
106
114
  switch (parsed.name) {
107
115
  case "new":
108
116
  return handleNew(ctx, cmdCtx)
109
- case "stop":
110
- case "cancel": // /cancel 与 /stop 同义(用户自然习惯 + pi-qqbot 同款,UAT S3 实证缺口)
117
+ case "cancel": // 唯一中止命令(owner 2026-11-23 裁定:不收别名减负担;UAT 实证 /cancel 是用户自然习惯)
111
118
  return handleStop(ctx, cmdCtx)
119
+ case "amend": // steer 降级版:忙时插话并入当前任务(参考 Hermes update_prompt)
120
+ return cmdCtx.amend(ctx.userId, parsed.args)
121
+ case "undo": // 对齐官方 TUI /undo:回滚上一回合+恢复文件(prompt 回盒由回执承担)
122
+ return cmdCtx.undo(ctx.userId)
123
+ case "goal": // 官方引擎内置(v2.2.1+,PR#59437):目标模式直通——审查器/50轮上限在引擎侧
124
+ return cmdCtx.engineCommand(ctx.userId, "goal", parsed.args)
125
+ case "compact": // 官方引擎命令:会话压缩
126
+ return cmdCtx.engineCommand(ctx.userId, "compact", parsed.args)
127
+ case "redo": // 官方引擎命令:撤销暂存回滚的恢复
128
+ return cmdCtx.engineCommand(ctx.userId, "redo", parsed.args)
129
+ case "btw": // 官方引擎命令:侧问(不写入会话上下文)
130
+ return cmdCtx.engineCommand(ctx.userId, "btw", parsed.args)
112
131
  case "queue":
113
132
  return handleQueue(ctx, parsed.args, cmdCtx)
114
133
  case "ledger":
@@ -116,25 +135,29 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
116
135
  case "progress":
117
136
  return cmdCtx.progress.query(ctx.userId)
118
137
  case "status":
119
- return handleStatus(ctx, cmdCtx)
138
+ return handleStatus(ctx, parsed.args, cmdCtx)
139
+ case "watch": // 已退役(owner 2026-11-23 定案):开关迁入 /status 驾驶舱
140
+ return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)"
141
+ case "mirror": // 已退役:迁入 /status 驾驶舱
142
+ return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off"
120
143
  case "sessions":
121
144
  return handleSessions(ctx, cmdCtx)
122
145
  case "help":
123
146
  return buildHelpText()
124
- case "model":
147
+ case "models": // 官方 TUI 同名(owner 2026-11-23:严格对齐官方,单数别名已收编不留负担)
125
148
  return handleModel(ctx, parsed.args, cmdCtx)
126
- case "agent":
149
+ case "agents": // 官方 TUI 同名
127
150
  return handleAgent(ctx, parsed.args, cmdCtx)
128
151
  case "rename":
129
152
  return handleRename(ctx, parsed.args, cmdCtx)
130
153
  case "history":
131
154
  return handleHistory(ctx, parsed.args, cmdCtx)
132
- case "watch":
133
- return handleWatch(ctx, parsed.args, cmdCtx)
155
+ case "watch": // 已退役(owner 2026-11-23 定案):开关迁入 /status 驾驶舱
156
+ return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)"
134
157
  case "send":
135
158
  return handleSend(ctx, parsed.args, cmdCtx)
136
- case "mirror":
137
- return handleMirror(parsed.args, cmdCtx)
159
+ case "mirror": // 已退役:迁入 /status 驾驶舱
160
+ return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off"
138
161
  default:
139
162
  return `不支持的命令:/${parsed.name}\n发送 /help 查看可用命令`
140
163
  }
@@ -226,7 +249,7 @@ async function handleStop(ctx: MessageContext, cmdCtx: CommandContext): Promise<
226
249
  }
227
250
 
228
251
  // Q1:/queue 查看与管理忙碌队列(2026-11-05:默认视图 join 台账,不再只看内存)
229
- function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext): string {
252
+ function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext): string | Promise<string> {
230
253
  const parts = args.trim().split(/\s+/).filter(Boolean)
231
254
  const sub = parts[0]?.toLowerCase() ?? ""
232
255
  if (sub === "clear") {
@@ -245,6 +268,11 @@ function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext):
245
268
  if (/^\d+$/.test(sub)) {
246
269
  return cmdCtx.queue.listAll(ctx.userId, Math.max(1, Number(sub)))
247
270
  }
271
+ // 显性入队动词(owner 2026-11-23):steer 默认模式下,/queue <文本>=把这条文本
272
+ // 排进 FIFO(当前任务跑完才执行),而不是默认的并入当前任务。
273
+ if (args.trim()) {
274
+ return cmdCtx.enqueue(ctx, args.trim())
275
+ }
248
276
  return cmdCtx.queue.list(ctx.userId)
249
277
  }
250
278
 
@@ -291,7 +319,24 @@ export async function resolveStatusSessionTitle(
291
319
  return { title: session.title, sessionId: session.sessionId }
292
320
  }
293
321
 
294
- async function handleStatus(ctx: MessageContext, cmdCtx: CommandContext): Promise<string> {
322
+ async function handleStatus(ctx: MessageContext, args: string, cmdCtx: CommandContext): Promise<string> {
323
+ // 驾驶舱开关(owner 2026-11-23 定案):/status watch|mirror on|off = 观察/镜像唯一开关
324
+ // 入口(/watch /mirror 命令已退役);裸 /status 保持纯读。
325
+ const parts = args.trim().split(/\s+/).filter(Boolean)
326
+ if (parts.length > 0) {
327
+ const target = parts[0].toLowerCase()
328
+ const sw = parts[1]?.toLowerCase()
329
+ if ((target === "watch" || target === "mirror") && (sw === "on" || sw === "off")) {
330
+ if (target === "mirror") return cmdCtx.mirror.set(sw === "on")
331
+ if (sw === "on") {
332
+ const session = await cmdCtx.sessions.getOrCreate(ctx.userId)
333
+ return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx)
334
+ }
335
+ return cmdCtx.watch.stop(ctx.userId)
336
+ }
337
+ return "用法:/status 查看状态|/status watch on|off 观察开关|/status mirror on|off 镜像开关"
338
+ }
339
+
295
340
  const sessionInfo = await resolveStatusSessionTitle(cmdCtx.sessions, cmdCtx.client, ctx.userId)
296
341
  const { providerId, modelId } = cmdCtx.sessions.getModel(ctx.userId)
297
342
  const agentId = cmdCtx.sessions.getAgent(ctx.userId)
@@ -314,6 +359,8 @@ async function handleStatus(ctx: MessageContext, cmdCtx: CommandContext): Promis
314
359
  `会话:${sessionInfo.sessionId ? `${sessionInfo.title ?? "未命名会话"} (${sessionInfo.sessionId})` : "未创建"}`,
315
360
  `模型:${providerId && modelId ? `${providerId} / ${modelId}` : "默认"}`,
316
361
  `Agent:${agentId ?? "默认"}`,
362
+ cmdCtx.watch.status(ctx.userId),
363
+ cmdCtx.mirror.status(),
317
364
  cmdCtx.queue.summary(ctx.userId),
318
365
  logLine,
319
366
  ].join("\n")
@@ -359,17 +406,17 @@ async function handleModel(ctx: MessageContext, args: string, cmdCtx: CommandCon
359
406
  return `${index + 1}. ${isCurrent ? "[当前] " : ""}${model.label}`
360
407
  })
361
408
 
362
- return ["可用模型:", ...lines, "回复序号或 /model <provider/model> 切换(60 秒内有效)"].join("\n")
409
+ return ["可用模型:", ...lines, "回复序号或 /models <provider/model> 切换(60 秒内有效)"].join("\n")
363
410
  }
364
411
 
365
412
  if (/^\d+$/.test(args)) {
366
413
  const result = await handlePendingSelection(ctx.userId, Number(args), cmdCtx)
367
- return result ?? "没有待选择的模型列表,请先发送 /model"
414
+ return result ?? "没有待选择的模型列表,请先发送 /models"
368
415
  }
369
416
 
370
417
  const model = splitModelId(args)
371
418
  if (!model) {
372
- return "模型格式不对,请使用 /model <provider/model>"
419
+ return "模型格式不对,请使用 /models <provider/model>"
373
420
  }
374
421
 
375
422
  // DEF-qqbot-20261111-01:存在性校验——此前仅校格式直写映射,假模型也回「已切换成功」误导用户
@@ -402,7 +449,7 @@ async function handleAgent(ctx: MessageContext, args: string, cmdCtx: CommandCon
402
449
  return `${index + 1}. ${isCurrent ? "[当前] " : ""}${agent.label}`
403
450
  })
404
451
 
405
- return ["可用 Agent:", ...lines, "回复 /agent <name> 切换"].join("\n")
452
+ return ["可用 Agent:", ...lines, "回复 /agents <name> 切换"].join("\n")
406
453
  }
407
454
 
408
455
  const normalized = args.trim().toLowerCase()
@@ -447,34 +494,6 @@ async function handleHistory(ctx: MessageContext, args: string, cmdCtx: CommandC
447
494
  return `📜 ${session.title ?? session.sessionId} · 最近 ${n} 轮\n\n${body}`
448
495
  }
449
496
 
450
- async function handleWatch(ctx: MessageContext, args: string, cmdCtx: CommandContext): Promise<string> {
451
- const a = args.trim()
452
- const lower = a.toLowerCase()
453
-
454
- if (lower === "off" || lower === "stop") {
455
- return cmdCtx.watch.stop(ctx.userId)
456
- }
457
-
458
- if (!a) {
459
- const session = await cmdCtx.sessions.getOrCreate(ctx.userId)
460
- return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx)
461
- }
462
-
463
- if (/^ses_/i.test(a)) {
464
- return cmdCtx.watch.start(ctx.userId, a, ctx)
465
- }
466
-
467
- return "用法:/watch 观察当前会话|/watch <会话ID> 观察指定会话|/watch off 停止观察"
468
- }
469
-
470
- function handleMirror(args: string, cmdCtx: CommandContext): string {
471
- const a = args.trim().toLowerCase()
472
- if (!a) return cmdCtx.mirror.status()
473
- if (["on", "1", "开", "打开"].includes(a)) return cmdCtx.mirror.set(true)
474
- if (["off", "0", "关", "关闭"].includes(a)) return cmdCtx.mirror.set(false)
475
- return "用法:/mirror 查看状态|/mirror on 开启|/mirror off 关闭"
476
- }
477
-
478
497
  async function ensureSession(userId: string, cmdCtx: CommandContext): Promise<void> {
479
498
  await cmdCtx.sessions.getOrCreate(userId)
480
499
  }
@@ -587,28 +606,25 @@ export function buildHelpText(): string {
587
606
  return [
588
607
  "可用命令:",
589
608
  "/new - 创建新会话",
590
- "/stop - 停止当前 AI 运行",
591
- "/status - 查看服务器和当前会话状态",
609
+ "/cancel - 中止当前生成并清空忙碌队列",
610
+ "/status - 驾驶舱:服务器/会话/模型/Agent/观察/镜像/队列/日志;/status watch on|off 观察开关;/status mirror on|off 镜像开关",
592
611
  "/sessions - 列出历史会话并回复序号切换",
593
612
  "/help - 查看帮助",
594
- "/model - 列出可用模型",
595
- "/model <provider/model> - 切换模型",
596
- "/agent - 列出可用 Agent",
597
- "/agent <name> - 切换 Agent",
613
+ "/models - 列出可用模型|/models <provider/model> 切换(session 级)",
614
+ "/agents - 列出可用 Agent|/agents <name> 切换",
598
615
  "/rename <name> - 重命名当前会话",
599
616
  "/history [N] - 查看当前会话最近 N 轮历史(默认 3,最多 10)",
600
617
  "/send <路径> - 把白名单目录内的文件/图片发到 QQ",
601
- "/watch - 观察当前会话实时过程(工具调用/完成会推送摘要)",
602
- "/watch <会话ID> - 观察指定会话",
603
- "/watch off - 停止观察",
604
618
  "/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
605
- "/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除",
619
+ "/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除;/queue <文本> 显性入队(steer 默认下排进 FIFO)",
620
+ "/goal <目标> - 官方目标模式(引擎内置 v2.2.1+);/goal 查状态;pause/resume/clear 控制",
621
+ "/compact /redo /btw - 官方引擎命令直通(压缩会话 / 恢复撤销 / 侧问)",
606
622
  "/ledger - 台账快照(在途/孤儿/最近拒绝);/ledger check 对账会话历史;/ledger settle <尾号> confirm 人工结清",
607
- "/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
608
- "/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",
623
+ "/undo - 对齐官方:撤销上一回合,并恢复文件",
624
+ "/amend <补充> - 忙时插话并入当前任务(官方 steer 语义)",
609
625
  "",
610
626
  "权限审批(AI 请求权限时):",
611
- "回复「允许」= 本次允许|「总是」= 总是允许|「拒绝」= 拒绝",
627
+ "点卡片按钮(允许一次/总是允许/拒绝/忽略),或回复「允许」= 本次允许|「总是」= 总是允许|「拒绝」= 拒绝",
612
628
  "(30 分钟无响应自动拒绝)",
613
629
  ].join("\n")
614
630
  }
package/src/config.ts CHANGED
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
5
5
  import { join } from "path"
6
6
  import { homedir } from "os"
7
7
  import { createInterface } from "readline"
8
+ import { applyConfigOverlay } from "./core/bot-config.js"
8
9
 
9
10
  export interface Config {
10
11
  qq: {
@@ -40,14 +41,41 @@ export interface RoleConfig {
40
41
  * 行为与 2026-11-17 之前完全一致——存量部署零迁移。
41
42
  * 多角色模式下 ALLOWED_USERS/QQ_SANDBOX/QQ_APP_* 只作兜底缺项,不再单独生效。
42
43
  */
43
- export function loadRoles(): RoleConfig[] {
44
- const raw = (process.env.QQ_BOTS ?? "").trim()
44
+ /**
45
+ * 可用凭据判定(纯函数,2026-11-20 应修尽修批):legacy 字段齐全 或 QQ_BOTS
46
+ * 解析出 ≥1 合法角色。ensureConfig 用它做早退——纯 QQ_BOTS 部署(无 legacy 字段)
47
+ * 不再掉进交互提问分支(detached 进程 stdin 无TTY会挂起)。
48
+ */
49
+ export function hasUsableCredentials(env: NodeJS.ProcessEnv = process.env): boolean {
50
+ if ((env.QQ_APP_ID ?? "").trim() && (env.QQ_APP_SECRET ?? "").trim()) return true
51
+ const raw = (env.QQ_BOTS ?? "").trim()
52
+ if (!raw) return false
53
+ return parseRolesJson(raw).length > 0
54
+ }
55
+
56
+ /**
57
+ * 主角色 appId(纯函数):legacy QQ_APP_ID 优先,缺省回退 QQ_BOTS 首角色——
58
+ * restart/看门狗/插件引导器等单点探活调用方的锁路径锚点,在纯多角色部署下不再瞎。
59
+ */
60
+ export function primaryAppId(env: NodeJS.ProcessEnv = process.env): string | null {
61
+ const legacy = (env.QQ_APP_ID ?? "").trim()
62
+ if (legacy) return legacy
63
+ const raw = (env.QQ_BOTS ?? "").trim()
64
+ if (!raw) return null
65
+ return parseRolesJson(raw)[0]?.appId ?? null
66
+ }
67
+
68
+ export function loadRoles(): RoleConfig[] { const raw = (process.env.QQ_BOTS ?? "").trim()
45
69
  if (raw) {
46
70
  const roles = parseRolesJson(raw)
47
71
  if (roles.length > 0) return roles
48
72
  console.warn("[config] QQ_BOTS 配置存在但解析结果为空,回退 legacy 单角色模式")
49
73
  }
50
74
  const single = loadConfig()
75
+ console.warn(
76
+ "[config] legacy 单角色配置(QQ_APP_ID/QQ_APP_SECRET)已弃用——QQ_BOTS 多角色表是唯一角色源;" +
77
+ "legacy 兜底将于 2026-12-31 移除,请迁移 .env:QQ_BOTS=[{\"appId\":\"…\",\"secret\":\"…\",\"sandbox\":false,\"name\":\"角色名\"}]",
78
+ )
51
79
  return [{
52
80
  name: single.qq.appId,
53
81
  appId: single.qq.appId,
@@ -123,17 +151,21 @@ function askTwo(q1: string, q2: string): Promise<[string, string]> {
123
151
  }
124
152
 
125
153
  export async function ensureConfig(): Promise<void> {
126
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
154
+ // P2 配置分层(2026-11-23 owner 裁定):config.json 最低用户层,先叠加——
155
+ // 「已设不覆盖」使其落在继承环境与 .env 之下(.env 在其后加载自然覆盖它)。
156
+ applyConfigOverlay()
157
+
158
+ if (hasUsableCredentials()) return
127
159
 
128
160
  if (existsSync(ENV_FILE)) {
129
161
  loadEnvFile(ENV_FILE)
130
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
162
+ if (hasUsableCredentials()) return
131
163
  }
132
164
 
133
165
  const localEnv = join(process.cwd(), ".env")
134
166
  if (existsSync(localEnv)) {
135
167
  loadEnvFile(localEnv)
136
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
168
+ if (hasUsableCredentials()) return
137
169
  }
138
170
 
139
171
  console.log("首次运行,需要配置 QQ 机器人凭证")
@@ -147,6 +179,8 @@ export async function ensureConfig(): Promise<void> {
147
179
 
148
180
  mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }) // POSIX 凭据目录仅本人可入
149
181
  const envContent = [
182
+ `# 多角色(唯一角色源,推荐):QQ_BOTS=[{"appId":"…","secret":"…","sandbox":false,"name":"开发角色","allowedUsers":[]}]`,
183
+ `# 以下 legacy 单角色字段已弃用,将于 2026-12-31 移除`,
150
184
  `QQ_APP_ID=${appId}`,
151
185
  `QQ_APP_SECRET=${appSecret}`,
152
186
  `QQ_SANDBOX=false`,
@@ -0,0 +1,66 @@
1
+ // @input: node:fs/path/os、process.env(QQ_CONFIG_FILE 测试覆盖)
2
+ // @output: parseConfigJson/computeOverlay/applyConfigOverlay/configJsonPath
3
+ // @pos: core - 行为配置分层(2026-11-23 owner 裁定 P2:对齐官方「json=行为、env=密钥」)
4
+ //
5
+ // 层级(高→低):继承环境 > ~/.openqq/.env > ~/.openqq/config.json > 内置默认。
6
+ // config.json 为平铺 JSON,键名与 env 相同(零映射表,文档一句讲清);
7
+ // 只收行为键,密钥(QQ_APP_SECRET/OPENCODE_PASSWORD 等)仍必须走 .env——
8
+ // 叠加规则「已设不覆盖」:在 .env 加载前应用,天然落位最低用户层。
9
+ // 叠加方式是写入 process.env——业务代码 51 处读取点零改动(最小侵入)。
10
+
11
+ import { existsSync, readFileSync } from "node:fs"
12
+ import { homedir } from "node:os"
13
+ import { join } from "node:path"
14
+
15
+ /** config.json 路径:QQ_CONFIG_FILE 覆盖(测试/多实例隔离用),默认 ~/.openqq/config.json */
16
+ export function configJsonPath(env: NodeJS.ProcessEnv = process.env): string {
17
+ return env.QQ_CONFIG_FILE?.trim() || join(homedir(), ".openqq", "config.json")
18
+ }
19
+
20
+ /** 解析平铺配置(纯函数供测试):只收 string/number/boolean 叶值并转字符串;嵌套对象忽略。 */
21
+ export function parseConfigJson(raw: string): Record<string, string> {
22
+ let parsed: unknown
23
+ try {
24
+ parsed = JSON.parse(raw)
25
+ } catch {
26
+ console.warn("[config] config.json 不是合法 JSON,已忽略")
27
+ return {}
28
+ }
29
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
30
+ console.warn("[config] config.json 必须是平铺 JSON 对象,已忽略")
31
+ return {}
32
+ }
33
+ const out: Record<string, string> = {}
34
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
35
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
36
+ out[k] = String(v)
37
+ }
38
+ }
39
+ return out
40
+ }
41
+
42
+ /** 计算应叠加的键(纯函数供测试):config 中 env 已存在的键跳过(继承环境最高优先)。 */
43
+ export function computeOverlay(
44
+ env: NodeJS.ProcessEnv,
45
+ config: Record<string, string>,
46
+ ): Array<[string, string]> {
47
+ return Object.entries(config).filter(([k]) => env[k] === undefined)
48
+ }
49
+
50
+ /** 读 config.json 并叠加进 env(缺省 process.env);返回叠加条数;文件缺失/读失败静默 0。 */
51
+ export function applyConfigOverlay(env: NodeJS.ProcessEnv = process.env): number {
52
+ const path = configJsonPath(env)
53
+ if (!existsSync(path)) return 0
54
+ let raw: string
55
+ try {
56
+ raw = readFileSync(path, "utf-8")
57
+ } catch {
58
+ return 0
59
+ }
60
+ const overlay = computeOverlay(env, parseConfigJson(raw))
61
+ for (const [k, v] of overlay) env[k] = v
62
+ if (overlay.length > 0) {
63
+ console.log(`[config] config.json 已叠加 ${overlay.length} 项(env/.env 优先): ${path}`)
64
+ }
65
+ return overlay.length
66
+ }
@@ -34,16 +34,34 @@ export function resolveInstalledBotEntry(fromUrl: string, exists: (p: string) =>
34
34
  }
35
35
 
36
36
  export function readAppId(envPath = join(homedir(), ".openqq", ".env")): string | null {
37
+ // 2026-11-20 应修尽修批:legacy 字段优先,缺省回退 QQ_BOTS 首角色(纯多角色部署的
38
+ // restart/探活锚点——此前只认 legacy 字段,纯 QQ_BOTS 部署下 restart/看门狗全瞎)。
39
+ let botsRaw: string | null = null
37
40
  try {
38
41
  for (const line of readFileSync(envPath, "utf-8").split("\n")) {
39
42
  const t = line.trim()
40
43
  if (!t || t.startsWith("#")) continue
41
44
  const eq = t.indexOf("=")
42
- if (eq > 0 && t.slice(0, eq).trim() === "QQ_APP_ID") return t.slice(eq + 1).trim() || null
45
+ if (eq < 0) continue
46
+ const key = t.slice(0, eq).trim()
47
+ if (key === "QQ_APP_ID") {
48
+ const v = t.slice(eq + 1).trim()
49
+ if (v) return v
50
+ }
51
+ if (key === "QQ_BOTS") botsRaw = t.slice(eq + 1).trim()
43
52
  }
44
53
  } catch {
45
54
  /* 无 .env */
46
55
  }
56
+ if (botsRaw) {
57
+ try {
58
+ const arr = JSON.parse(botsRaw) as Array<{ appId?: unknown }>
59
+ const first = Array.isArray(arr) ? arr[0]?.appId : undefined
60
+ if (typeof first === "string" && first) return first
61
+ } catch {
62
+ /* 坏 JSON 视为无 */
63
+ }
64
+ }
47
65
  return null
48
66
  }
49
67
 
@@ -111,12 +129,12 @@ export interface RestartResult {
111
129
  * design §3.9.1 归一:杀/拉唯一权威 = superviseOnce(request=manual-restart)。
112
130
  * 复用同一 grace-kill(TERM→宽限→KILL→确认死亡才拉)+ spawn 原语,
113
131
  * 受 supervisor.json 强度账(15min/3 次 give-up、2min 冷却)与认领互斥约束,
114
- * 审计分家(主动杀/验尸拉新)落 watchdog.log——restart 不再有独立杀逻辑。
132
+ * 审计分家(主动杀/验尸拉新)落统一日志 openqq.log——restart 不再有独立杀逻辑。
115
133
  */
116
134
  export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
117
135
  const log = opts.log ?? (() => {})
118
136
  const appId = readAppId()
119
- if (!appId) throw new Error("缺少 ~/.openqq/.env 的 QQ_APP_ID,无法定位实例锁")
137
+ if (!appId) throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁")
120
138
  if (!opts.force) {
121
139
  const idle = await waitUntilIdle({
122
140
  timeoutMs: opts.timeoutMs,
@@ -195,9 +195,11 @@ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: strin
195
195
  return { command: resolveRuntimeCommand("node"), args: [entry], env }
196
196
  }
197
197
 
198
- /** bot 输出日志(detached 后 stdout/stderr 的唯一去向) */
198
+ /** bot 输出日志(detached 后 stdout/stderr 的唯一去向)。
199
+ * 2026-11-20 合并批:统一为 ~/.openqq/openqq.log(bot 与看门狗同文件,
200
+ * 滚动/预算归 core/log-rotate.ts;旧名 bot.out.log 停止写入保留备查)。 */
199
201
  export function botLogPath(): string {
200
- return join(homedir(), ".openqq", "bot.out.log")
202
+ return join(homedir(), ".openqq", "openqq.log")
201
203
  }
202
204
 
203
205
  /**
@@ -0,0 +1,84 @@
1
+ // @input: 纯文本(无依赖)+ setTimeout(调度器)
2
+ // @output: parseCronReminder / ReminderScheduler
3
+ // @pos: core - 定时提醒(2026-11-23 学习吸收 Y-1,源=openclaw outbound/cron-scheduler.ts P0)
4
+ //
5
+ // 触发形态(AI 在正文内嵌标记,与 openclaw 同款):
6
+ // QQBOT_PAYLOAD: {"type":"cron_reminder","at":"in 30m","text":"去开评审会"}
7
+ // at 支持:ISO 8601 / Unix ms(>1e12)/ "in Nm/Nh/Nd";过去时刻拒收。
8
+ // 标记从用户可见正文剥离(不留脚手架痕迹);剥完为空则以确认句回执。
9
+ // 单次提醒(setTimeout,进程内存态)——重启即失,与 openclaw 同口径;
10
+ // 每用户同时在册上限防标记轰炸。
11
+
12
+ /** 解析 cron 标记(纯函数供测试)。命中并合法 → 绝对时刻/提醒文本/剥净正文;否则 null。 */
13
+ export function parseCronReminder(
14
+ text: string,
15
+ now: number,
16
+ ): { atMs: number; reminderText: string; cleanedText: string } | null {
17
+ const m = /QQBOT_PAYLOAD:\s*(\{[\s\S]*?\})/.exec(text)
18
+ if (!m) return null
19
+ let payload: { type?: unknown; at?: unknown; text?: unknown }
20
+ try {
21
+ payload = JSON.parse(m[1]) as typeof payload
22
+ } catch {
23
+ return null
24
+ }
25
+ if (payload?.type !== "cron_reminder") return null
26
+ const reminderText = typeof payload.text === "string" ? payload.text.trim().slice(0, 200) : ""
27
+ if (!reminderText) return null
28
+ const atMs = resolveAt(payload.at, now)
29
+ if (atMs === null || atMs <= now + 5_000) return null
30
+ // 剥净:含标记的整行移除,残余空行收敛
31
+ const cleanedText = text
32
+ .split("\n")
33
+ .filter((line) => !line.includes("QQBOT_PAYLOAD:"))
34
+ .join("\n")
35
+ .replace(/\n{3,}/g, "\n\n")
36
+ .trim()
37
+ return { atMs, reminderText, cleanedText }
38
+ }
39
+
40
+ /** at 字段解析(纯函数):ISO / Unix ms / "in Nm|Nh|Nd"。 */
41
+ export function resolveAt(at: unknown, now: number): number | null {
42
+ if (typeof at === "number" && Number.isFinite(at)) {
43
+ return at > 1e12 ? at : null // 小于 1e12 按秒记的可能性不存在于本域,拒收防误用
44
+ }
45
+ if (typeof at !== "string") return null
46
+ const rel = /^in\s+(\d+)\s*([mhd])$/i.exec(at.trim())
47
+ if (rel) {
48
+ const n = Number(rel[1])
49
+ const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[rel[2].toLowerCase()] ?? 0
50
+ return now + n * unit
51
+ }
52
+ const t = Date.parse(at)
53
+ return Number.isNaN(t) ? null : t
54
+ }
55
+
56
+ /** 进程内单次提醒调度:每用户同时在册上限(防标记轰炸),到点投递并出册。 */
57
+ export class ReminderScheduler {
58
+ private readonly pending = new Map<string, Set<ReturnType<typeof setTimeout>>>()
59
+ constructor(private readonly maxPerUser = 10) {}
60
+
61
+ /** 注册。返回 false=被拒(超上限/参数非法),调用方如实回执。 */
62
+ schedule(userId: string, atMs: number, text: string, deliver: (userId: string, text: string) => void): boolean {
63
+ if (!userId || !text.trim() || atMs <= Date.now()) return false
64
+ const set = this.pending.get(userId) ?? new Set()
65
+ if (set.size >= this.maxPerUser) return false
66
+ const timer = setTimeout(() => {
67
+ set.delete(timer)
68
+ console.log(`[cron] 提醒到点 user=${userId.slice(0, 8)}… text=${text.slice(0, 30)}`)
69
+ try {
70
+ deliver(userId, `⏰ 提醒:${text}`)
71
+ } catch (error) {
72
+ console.error("[cron] 提醒投递失败:", error)
73
+ }
74
+ }, atMs - Date.now())
75
+ set.add(timer)
76
+ this.pending.set(userId, set)
77
+ return true
78
+ }
79
+
80
+ /** 在册数(测试断言用)。 */
81
+ size(userId: string): number {
82
+ return this.pending.get(userId)?.size ?? 0
83
+ }
84
+ }