@linjz/opencode-qqbot 0.3.15 → 0.3.17

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 (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -1,96 +1,93 @@
1
- // @input: node:os/node:path(路径)、./outbox.ts、../config(Config 类型)
2
- // @output: createNotifySink / resolveNotifyRecipients / defaultOutboxPath / 常量
3
- // @pos: core - openqq notify 外部入队通道的消费端:bot 进程注册 'notify'
4
- // outbox handler,把 outbox.json 里积压的通知用 delivery 投给 QQ 用户。
5
- // @note: 入队端在 src/cli/notify.ts(只入队,不发送);本文件只负责消费——
6
- // TTL 过期丢弃 / maxAttempts 重试上限 / 失败由 outbox 退避重试。
7
- // 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1(0.3.14 现存缺口:
8
- // `opencode run` 新会话无 QQ 映射 → 镜像「无映射主人」跳过 → 结果推不到 QQ)。
9
- // 交付层不换实现:deliver 内含配额记账/被动→主动降级/分条/24h 同文去重。
10
- import { homedir } from "node:os"
11
- import { join } from "node:path"
12
- import type { Config } from "../config.js"
13
- import type { MessageContext } from "../qq/types.js"
14
- import { createOutbox } from "./outbox.js"
15
-
16
- /** 默认 TTL:bot 长期不在线时积压不会在重启后集中刷屏。 */
17
- export const DEFAULT_NOTIFY_TTL_HOURS = 24
18
- /** 单条最大投递尝试次数:配额耗尽等永久失败不无限退避。 */
19
- export const DEFAULT_NOTIFY_MAX_ATTEMPTS = 8
20
-
21
- export type DeliverLike = (ctx: MessageContext, text: string) => Promise<void>
22
-
23
- export interface NotifySinkOptions {
24
- config: Config
25
- deliver: DeliverLike
26
- /** 队列文件;缺省 QQ_OUTBOX_FILE → ~/.openqq/outbox.json(bot 与 CLI 必须一致)。 */
27
- filePath?: string
28
- ttlHours?: number
29
- maxAttempts?: number
30
- }
31
-
32
- export interface NotifySink {
33
- outbox: ReturnType<typeof createOutbox>
34
- /** 停止轮询;挂起的发送交由 outbox.drain 语义接管。 */
35
- stop: () => void
36
- }
37
-
38
- /**
39
- * 创建并启动 notify 消费端。handler 语义:
40
- * - payload.text 投给 entry.ctx(c2c 主动消息;delivery 内含配额/降级/分条/24h 去重);
41
- * - TTL 过期 → 返回 skipped 说明(outbox 记为 sent,不发送)——积压不刷屏;
42
- * - 投递抛错 → outbox 记 failed 并退避重试,到 maxAttempts 保持 failed。
43
- * start() 已含 recover(崩溃 sending→pending/failed,至少一次语义)。
44
- */
45
- export function createNotifySink(options: NotifySinkOptions): NotifySink {
46
- const ttlHours = Number(
47
- options.ttlHours ?? process.env.QQ_NOTIFY_TTL_HOURS ?? DEFAULT_NOTIFY_TTL_HOURS,
48
- )
49
- const ttlMs =
50
- (Number.isFinite(ttlHours) && ttlHours > 0 ? ttlHours : DEFAULT_NOTIFY_TTL_HOURS) *
51
- 60 * 60 * 1000
52
- const maxRaw = Number(
53
- options.maxAttempts ?? process.env.QQ_NOTIFY_MAX_ATTEMPTS ?? DEFAULT_NOTIFY_MAX_ATTEMPTS,
54
- )
55
- const maxAttempts = Number.isFinite(maxRaw) && maxRaw > 0 ? Math.floor(maxRaw) : DEFAULT_NOTIFY_MAX_ATTEMPTS
56
- const outbox = createOutbox({ ...(options.filePath ? { filePath: options.filePath } : {}) })
57
- outbox.register("notify", (entry) => {
58
- if (Date.now() - entry.createdAt > ttlMs) {
59
- return { skipped: "ttl-expired" }
60
- }
61
- const text = (entry.payload as { text?: unknown } | null)?.text
62
- if (typeof text !== "string" || !text.trim()) {
63
- return { skipped: "no-text" }
64
- }
65
- const ctx = entry.ctx as MessageContext
66
- // fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
67
- // maxAttempts 由轮询/flush 透传 maxAttempts 项在 outbox.start 后生效:这里只在
68
- // pollInterval 层用 sink 的全局退避语义,未传 outbox 最大尝试次数时由 start 循环收敛。
69
- return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }))
70
- })
71
- void maxAttempts
72
- outbox.start({ recover: true }).catch((error) => {
73
- console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
74
- })
75
- return {
76
- outbox,
77
- stop() {
78
- outbox.stop()
79
- },
80
- }
81
- }
82
-
83
- /** CLI 端收件人解析:ALLOWED_USERS 唯一项缺省生效;显式 user 必须命中名单(fail-closed)。 */
84
- export function resolveNotifyRecipients(
85
- configured: readonly string[],
86
- explicit?: string,
87
- ): string {
88
- const users = [...configured]
89
- if (explicit) return users.includes(explicit) ? explicit : ""
90
- return users.length === 1 ? users[0] : ""
91
- }
92
-
93
- /** 默认 outbox 文件路径(CLI 与 bot 共用;env 已由 createOutbox 内处理,这里供 CLI dry-judge)。 */
94
- export function defaultOutboxPath(): string {
95
- return join(homedir(), ".openqq", "outbox.json")
96
- }
1
+ // @input: node:os/node:path(路径)、./outbox.ts、../config(Config 类型)
2
+ // @output: createNotifySink / resolveNotifyRecipients / defaultOutboxPath / 常量
3
+ // @pos: core - openqq notify 外部入队通道的消费端:bot 进程注册 'notify'
4
+ // outbox handler,把 outbox.json 里积压的通知用 delivery 投给 QQ 用户。
5
+ // @note: 入队端在 src/cli/notify.ts(只入队,不发送);本文件只负责消费——
6
+ // TTL 过期丢弃 / maxAttempts 重试上限 / 失败由 outbox 退避重试。
7
+ // 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1(0.3.14 现存缺口:
8
+ // `opencode run` 新会话无 QQ 映射 → 镜像「无映射主人」跳过 → 结果推不到 QQ)。
9
+ // 交付层不换实现:deliver 内含配额记账/被动→主动降级/分条/24h 同文去重。
10
+ import { storageFile } from "./storage.js"
11
+ import type { Config } from "../config.js"
12
+ import type { MessageContext } from "../qq/types.js"
13
+ import { createOutbox } from "./outbox.js"
14
+
15
+ /** 默认 TTL:bot 长期不在线时积压不会在重启后集中刷屏。 */
16
+ export const DEFAULT_NOTIFY_TTL_HOURS = 24
17
+ /** 单条最大投递尝试次数:配额耗尽等永久失败不无限退避。 */
18
+ export const DEFAULT_NOTIFY_MAX_ATTEMPTS = 8
19
+
20
+ export type DeliverLike = (ctx: MessageContext, text: string) => Promise<boolean>
21
+
22
+ export interface NotifySinkOptions {
23
+ config: Config
24
+ deliver: DeliverLike
25
+ /** 队列文件;缺省 QQ_OUTBOX_FILE → ~/.openqq/outbox.json(bot 与 CLI 必须一致)。 */
26
+ filePath?: string
27
+ ttlHours?: number
28
+ maxAttempts?: number
29
+ }
30
+
31
+ export interface NotifySink {
32
+ outbox: ReturnType<typeof createOutbox>
33
+ /** 停止轮询;挂起的发送交由 outbox.drain 语义接管。 */
34
+ stop: () => void
35
+ }
36
+
37
+ /**
38
+ * 创建并启动 notify 消费端。handler 语义:
39
+ * - payload.text 投给 entry.ctx(c2c 主动消息;delivery 内含配额/降级/分条/24h 去重);
40
+ * - TTL 过期 → 返回 skipped 说明(outbox 记为 sent,不发送)——积压不刷屏;
41
+ * - 投递抛错 → outbox 记 failed 并退避重试,到 maxAttempts 保持 failed。
42
+ * start() 已含 recover(崩溃 sending→pending/failed,至少一次语义)。
43
+ */
44
+ export function createNotifySink(options: NotifySinkOptions): NotifySink {
45
+ const ttlHours = Number(
46
+ options.ttlHours ?? process.env.QQ_NOTIFY_TTL_HOURS ?? DEFAULT_NOTIFY_TTL_HOURS,
47
+ )
48
+ const ttlMs =
49
+ (Number.isFinite(ttlHours) && ttlHours > 0 ? ttlHours : DEFAULT_NOTIFY_TTL_HOURS) *
50
+ 60 * 60 * 1000
51
+ const maxRaw = Number(
52
+ options.maxAttempts ?? process.env.QQ_NOTIFY_MAX_ATTEMPTS ?? DEFAULT_NOTIFY_MAX_ATTEMPTS,
53
+ )
54
+ const maxAttempts = Number.isFinite(maxRaw) && maxRaw > 0 ? Math.floor(maxRaw) : DEFAULT_NOTIFY_MAX_ATTEMPTS
55
+ const outbox = createOutbox({ ...(options.filePath ? { filePath: options.filePath } : {}) })
56
+ outbox.register("notify", (entry) => {
57
+ if (Date.now() - entry.createdAt > ttlMs) {
58
+ return { skipped: "ttl-expired" }
59
+ }
60
+ const text = (entry.payload as { text?: unknown } | null)?.text
61
+ if (typeof text !== "string" || !text.trim()) {
62
+ return { skipped: "no-text" }
63
+ }
64
+ const ctx = entry.ctx as MessageContext
65
+ // fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
66
+ // maxAttempts 由 start 透传到 recover/flush:失败达到上限后保持 failed,不再无限退避。
67
+ return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }))
68
+ })
69
+ outbox.start({ recover: true, maxAttempts }).catch((error) => {
70
+ console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
71
+ })
72
+ return {
73
+ outbox,
74
+ stop() {
75
+ outbox.stop()
76
+ },
77
+ }
78
+ }
79
+
80
+ /** CLI 端收件人解析:ALLOWED_USERS 唯一项缺省生效;显式 user 必须命中名单(fail-closed)。 */
81
+ export function resolveNotifyRecipients(
82
+ configured: readonly string[],
83
+ explicit?: string,
84
+ ): string {
85
+ const users = [...configured]
86
+ if (explicit) return users.includes(explicit) ? explicit : ""
87
+ return users.length === 1 ? users[0] : ""
88
+ }
89
+
90
+ /** 默认 outbox 文件路径(CLI 与 bot 共用;env 已由 createOutbox 内处理,这里供 CLI dry-judge)。 */
91
+ export function defaultOutboxPath(): string {
92
+ return storageFile("outbox.json")
93
+ }
@@ -0,0 +1,29 @@
1
+ // @input: 纯文本(无依赖)
2
+ // @output: stripScaffolding
3
+ // @pos: core - 出站脚手架消毒(2026-11-23 学习吸收 Z 项,源=openclaw outbound/sanitize.ts P0)
4
+ //
5
+ // 背景:模型偶发把内部推理/脚手架块写进正文( thinking/system-reminder 等),
6
+ // QQ 会把原始标签渲染给用户。出站前统一剥离——主路径(formatForQQMarkdown)与
7
+ // 纯文本兜底(formatForQQ)同口径,围栏代码块内容不动(调用方在围栏外逐段应用
8
+ // 或由 sender 在剥标签后再做围栏保护,顺序:消毒 → 围栏保护/转义)。
9
+
10
+ /** 内部脚手架块:成对块先剥(含跨行),再剥残留开/闭标签;
11
+ * deepseek 反引号形态 `think`…`/think` 与 claude 尖括号形态都收。 */
12
+ const BLOCK_PATTERNS: RegExp[] = [
13
+ /<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,
14
+ /<previous_response\b[^>]*>[\s\S]*?<\/previous_response>/gi,
15
+ /`think`[\s\S]*?`\/think`/gi,
16
+ /<thinking\b[^>]*>[\s\S]*?<\/thinking>/gi,
17
+ // 残留裸标签(不成对的开/闭)
18
+ /<\s*\/?\s*(?:system-reminder|previous_response)\b[^>]*\/?\s*>/gi,
19
+ /<\s*\/?\s*think(?:ing)?\b[^>]*\/?\s*>/gi,
20
+ ]
21
+
22
+ /** 剥离内部运行时脚手架块(幂等;连续空行收敛为一行)。 */
23
+ export function stripScaffolding(text: string): string {
24
+ let result = text
25
+ for (const re of BLOCK_PATTERNS) {
26
+ result = result.replace(re, "")
27
+ }
28
+ return result.replace(/\n{3,}/g, "\n\n")
29
+ }
@@ -1,10 +1,11 @@
1
- // @input: fs/path/os/crypto + ../qq/types(MessageContext)
1
+ // @input: fs/path/os/crypto + ../qq/types(MessageContext)
2
2
  // @output: createOutbox 及 Outbox 公共类型、保留/退避常量、pruneOutboxEntries
3
3
  // @pos: core - 独立持久化出站 Outbox(先落账后发送,至少一次恢复)
4
4
  //
5
5
  // 文件格式:{ "version": 1, "entries": OutboxEntry[] }。所有 mutation 都在
6
6
  // <outbox>.lock 短文件锁内重新读盘,再经临时文件 + rename 原子替换。
7
7
  // 网络 handler 不持文件锁;sending + leaseOwner/leaseUntil 防跨进程并发双发。
8
+ import { storageFile } from "./storage.js"
8
9
  import {
9
10
  closeSync,
10
11
  existsSync,
@@ -16,8 +17,7 @@ import {
16
17
  unlinkSync,
17
18
  writeFileSync,
18
19
  } from "node:fs"
19
- import { homedir } from "node:os"
20
- import { dirname, join } from "node:path"
20
+ import { dirname } from "node:path"
21
21
  import { randomUUID } from "node:crypto"
22
22
  import type { MessageContext } from "../qq/types.js"
23
23
 
@@ -106,7 +106,8 @@ export interface Outbox {
106
106
  recover(options?: { ignoreLeases?: boolean; maxAttempts?: number }): Promise<OutboxRecoverResult>
107
107
  /** 扫描 pending/failed;默认只处理 nextAttemptAt 已到期的项。 */
108
108
  flush(options?: OutboxFlushOptions): Promise<OutboxEntry[]>
109
- start(options?: { recover?: boolean }): Promise<void>
109
+ /** start 的 maxAttempts 会透传 recover/flush:失败达到该次数后保持 failed,不再无限重试。 */
110
+ start(options?: { recover?: boolean; maxAttempts?: number }): Promise<void>
110
111
  /** 停止定时器,不等待正在发送的 handler;需要等待时调用 drain。 */
111
112
  stop(): void
112
113
  /** 等待当前及等待期间新启动的本实例发送全部结束。 */
@@ -207,7 +208,7 @@ export function pruneOutboxEntries(entries: OutboxEntry[], now = Date.now()): Ou
207
208
  }
208
209
 
209
210
  export function createOutbox(options: OutboxOptions = {}): Outbox {
210
- const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? join(homedir(), ".openqq", "outbox.json")
211
+ const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json")
211
212
  const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs")
212
213
  const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs")
213
214
  const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs")
@@ -494,16 +495,16 @@ export function createOutbox(options: OutboxOptions = {}): Outbox {
494
495
  dispatch,
495
496
  recover,
496
497
  flush,
497
- async start(startOptions = {}) {
498
+ async start(startOptions: { recover?: boolean; maxAttempts?: number } = {}) {
498
499
  stopped = false
499
- if (startOptions.recover !== false) await recover()
500
+ if (startOptions.recover !== false) await recover({ maxAttempts: startOptions.maxAttempts })
500
501
  if (pollIntervalMs === 0 || timer) return
501
502
  timer = setInterval(() => {
502
503
  if (stopped) return
503
- void flush().catch(() => { /* 下轮继续;失败已持久化 */ })
504
+ void flush({ maxAttempts: startOptions.maxAttempts }).catch(() => { /* 下轮继续;失败已持久化 */ })
504
505
  }, pollIntervalMs)
505
506
  timer.unref?.()
506
- void flush().catch(() => { /* 下轮继续 */ })
507
+ void flush({ maxAttempts: startOptions.maxAttempts }).catch(() => { /* 下轮继续 */ })
507
508
  },
508
509
  stop() {
509
510
  stopped = true