@linjz/opencode-qqbot 0.3.5 → 0.3.7

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 (42) hide show
  1. package/README.md +74 -39
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +365 -70
  6. package/package.json +69 -61
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +936 -796
  9. package/src/commands.ts +554 -514
  10. package/src/config.ts +121 -121
  11. package/src/core/bot-launcher.ts +146 -134
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +284 -284
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -0
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +304 -304
  19. package/src/core/inflight-journal.ts +217 -151
  20. package/src/core/instance-lock.ts +122 -122
  21. package/src/core/linkwatch.ts +195 -195
  22. package/src/core/message-queue.ts +80 -0
  23. package/src/core/mirror.ts +173 -173
  24. package/src/core/permission.ts +301 -301
  25. package/src/core/reply-limiter.ts +106 -106
  26. package/src/core/send-media.ts +90 -90
  27. package/src/core/util.ts +8 -8
  28. package/src/index.ts +162 -162
  29. package/src/opencode/_FOLDER.md +11 -11
  30. package/src/opencode/client.ts +387 -386
  31. package/src/opencode/eventstream.ts +138 -138
  32. package/src/opencode/history.ts +143 -143
  33. package/src/opencode/mirror.ts +65 -65
  34. package/src/opencode/sessions.ts +158 -158
  35. package/src/plugin-entry.ts +112 -112
  36. package/src/qq/_FOLDER.md +13 -13
  37. package/src/qq/api.ts +539 -539
  38. package/src/qq/gateway.ts +492 -492
  39. package/src/qq/media.ts +219 -204
  40. package/src/qq/sender.ts +300 -300
  41. package/src/qq/types.ts +154 -152
  42. package/tsconfig.json +24 -24
@@ -1,195 +1,195 @@
1
- // HC2(2026-10-26):运行中链路自愈巡检。
2
- // 复盘3 教训:bot 与 opencode 平时零流量 + 看门狗只验进程心跳 → 下游死亡
3
- // 不可观测(2026-10-26 实证:端口漂移后黑暗 3 天,直到用户消息撞上)。
4
- // 本模块给链路装独立心跳:
5
- // 每 OPENCODE_LINKWATCH_MINUTES(默认 30)分钟静默 healthCheck;
6
- // 失败 → 立即端口发现 → 命中即原地热换基(client.rebase + onRebase 联动
7
- // eventstream)→ 立即复验;
8
- // 事故状态机落盘 ~/.openqq/incident.json(open/closed/attempts/rebasedTo,
9
- // 跨重启延续计数、重启不洗白);
10
- // 告警走 QQ 主动消息(每事故 open + fixed 各 ≤1 条,去重不骚扰)。
11
- // @input: client(healthCheck/rebase)、discoverOpencode、alarm 回调、fs
12
- // @output: startLinkWatch, LinkWatchDeps, IncidentRecord, incidentPath
13
- // @pos: core - 链路巡检(HC2)
14
- import { existsSync, readFileSync, writeFileSync } from "fs"
15
- import { join } from "path"
16
- import { homedir } from "os"
17
- import { discoverOpencode, persistDiscovery, type OpencodeDiscovery } from "./discovery.js"
18
- import { healthCheck, type OpencodeClient } from "../opencode/client.js"
19
-
20
- export interface LinkWatchDeps {
21
- client: OpencodeClient
22
- // 热换基联动:eventstream 等持有同源 base 的组件在此同步换址
23
- onRebase?: (baseUrl: string, discovery: OpencodeDiscovery) => void
24
- // 告警通道(QQ 主动消息);未提供则仅落盘+日志
25
- alarm?: (text: string) => Promise<void>
26
- intervalMin?: number
27
- // 测试注入:跳过 netstat 全扫描
28
- discover?: (password?: string) => Promise<OpencodeDiscovery | null>
29
- // 测试注入:事故文件路径(默认 ~/.openqq/incident.json)
30
- incidentFile?: string
31
- }
32
-
33
- export interface IncidentRecord {
34
- state: "open" | "closed"
35
- since: string // ISO:首次失败时刻
36
- lastCheck: string // ISO
37
- lastError: string
38
- attempts: number
39
- rebasedTo?: string
40
- }
41
-
42
- export function incidentPath(): string {
43
- return join(homedir(), ".openqq", "incident.json")
44
- }
45
-
46
- function saveIncident(path: string, rec: IncidentRecord): void {
47
- try {
48
- writeFileSync(path, JSON.stringify(rec, null, 2))
49
- } catch (error) {
50
- console.error("[linkwatch] incident 落盘失败:", error instanceof Error ? error.message : error)
51
- }
52
- }
53
-
54
- function nowIso(): string {
55
- return new Date().toISOString()
56
- }
57
-
58
- export interface LinkWatch {
59
- stop(): void
60
- // 测试/手动触发一轮巡检(与定时循环共用同一状态机,busy 互斥)
61
- runOnce(): Promise<void>
62
- }
63
-
64
- export function startLinkWatch(deps: LinkWatchDeps): LinkWatch {
65
- const envMin = Number(process.env.OPENCODE_LINKWATCH_MINUTES)
66
- const intervalMs = Math.max(1, deps.intervalMin ?? (Number.isFinite(envMin) && envMin > 0 ? envMin : 30)) * 60_000
67
- const file = deps.incidentFile ?? incidentPath()
68
- const discover = deps.discover ?? ((p?: string) => discoverOpencode({ password: p }))
69
- const password = process.env.OPENCODE_PASSWORD
70
-
71
- let rec: IncidentRecord | null = null
72
- let alarmOpenSent = false // 去重:每事故 open 告警只发一次(含跨重启)
73
- let stopped = false
74
- let busy = false
75
- let loopTimer: ReturnType<typeof setTimeout> | null = null
76
-
77
- // 恢复落盘的未结事故(跨重启延续;重启后不重发 open 告警,避免看门狗
78
- // 周期重启导致告警风暴)
79
- try {
80
- if (existsSync(file)) {
81
- const raw = JSON.parse(readFileSync(file, "utf-8")) as IncidentRecord
82
- if (raw?.state === "open" && typeof raw.since === "string") {
83
- rec = raw
84
- alarmOpenSent = true
85
- console.log(`[linkwatch] 恢复未结事故:自 ${raw.since}(attempts=${raw.attempts}),继续自愈`)
86
- }
87
- }
88
- } catch {
89
- // 损坏即视为无事故
90
- }
91
-
92
- async function fire(text: string): Promise<void> {
93
- try {
94
- await deps.alarm?.(text)
95
- } catch (error) {
96
- console.error("[linkwatch] 告警发送失败:", error instanceof Error ? error.message : error)
97
- }
98
- }
99
-
100
- async function tick(): Promise<void> {
101
- if (stopped || busy) return
102
- busy = true
103
- try {
104
- try {
105
- await healthCheck(deps.client, true)
106
- // 健康:若有未结事故 → 结案(含恢复告警)
107
- if (rec?.state === "open") {
108
- const open = rec
109
- const durMin = Math.max(1, Math.round((Date.now() - new Date(open.since).getTime()) / 60_000))
110
- console.log(`[linkwatch] 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
111
- if (!open.rebasedTo) {
112
- // rebase 恢复路径在切换时已发过 fixed 告警;只有自然恢复才发恢复通知
113
- await fire(`✅ OpenCode 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
114
- }
115
- saveIncident(file, { ...open, state: "closed", lastCheck: nowIso() })
116
- rec = null
117
- alarmOpenSent = false
118
- }
119
- return
120
- } catch (error) {
121
- const msg = error instanceof Error ? error.message : String(error)
122
- if (!rec) {
123
- rec = { state: "open", since: nowIso(), lastCheck: nowIso(), lastError: msg, attempts: 0 }
124
- console.error(`[linkwatch] ⚠️ 链路失联开始(${msg}),转入自愈巡检`)
125
- }
126
- const inc = rec
127
- inc.attempts++
128
- inc.lastError = msg
129
- inc.lastCheck = nowIso()
130
-
131
- // 首次失败才发 open 告警(去重)
132
- if (!alarmOpenSent) {
133
- alarmOpenSent = true
134
- await fire(
135
- `⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.slice(0, 80)})。已转入自动自愈:发现新端口会自动切换并通知。`,
136
- )
137
- }
138
-
139
- // 自愈:端口发现 → 热换基 → 复验
140
- const found = await discover(password)
141
- if (found && found.baseUrl !== deps.client.baseUrl) {
142
- deps.client.rebase(found.baseUrl)
143
- deps.onRebase?.(found.baseUrl, found)
144
- persistDiscovery(found)
145
- inc.rebasedTo = found.baseUrl
146
- saveIncident(file, inc)
147
- console.log(`[linkwatch] 热换基完成 → ${found.baseUrl}(v${found.version}),复验中…`)
148
- try {
149
- await healthCheck(deps.client, true)
150
- console.log("[linkwatch] ✅ 换基复验通过,链路恢复")
151
- await fire(`✅ OpenCode 端口已漂移,已自动切换旧地址 → ${found.baseUrl}(v${found.version}),链路恢复。`)
152
- saveIncident(file, { ...inc, state: "closed", lastCheck: nowIso() })
153
- rec = null
154
- alarmOpenSent = false
155
- } catch (e2) {
156
- inc.lastError = e2 instanceof Error ? e2.message : String(e2)
157
- inc.lastCheck = nowIso()
158
- saveIncident(file, inc)
159
- console.error("[linkwatch] 换基后仍失联,下轮继续:", inc.lastError)
160
- }
161
- } else {
162
- // 未发现新端口(服务真宕/同口抖动):保持 open,下一轮再试
163
- saveIncident(file, inc)
164
- console.error(`[linkwatch] 第 ${inc.attempts} 次巡检失败,未发现新端口(${msg.slice(0, 80)})`)
165
- }
166
- }
167
- } finally {
168
- busy = false
169
- }
170
- }
171
-
172
- // 可取消 sleep:stop() 清掉 pending 定时器,独立脚本(runOnce 后退出)不再悬挂
173
- function waitInterval(): Promise<void> {
174
- return new Promise((resolve) => {
175
- loopTimer = setTimeout(resolve, intervalMs)
176
- })
177
- }
178
-
179
- const loop = async (): Promise<void> => {
180
- while (!stopped) {
181
- await waitInterval()
182
- if (stopped) break
183
- await tick()
184
- }
185
- }
186
- void loop()
187
-
188
- return {
189
- stop: () => {
190
- stopped = true
191
- if (loopTimer) clearTimeout(loopTimer)
192
- },
193
- runOnce: tick,
194
- }
195
- }
1
+ // HC2(2026-10-26):运行中链路自愈巡检。
2
+ // 复盘3 教训:bot 与 opencode 平时零流量 + 看门狗只验进程心跳 → 下游死亡
3
+ // 不可观测(2026-10-26 实证:端口漂移后黑暗 3 天,直到用户消息撞上)。
4
+ // 本模块给链路装独立心跳:
5
+ // 每 OPENCODE_LINKWATCH_MINUTES(默认 30)分钟静默 healthCheck;
6
+ // 失败 → 立即端口发现 → 命中即原地热换基(client.rebase + onRebase 联动
7
+ // eventstream)→ 立即复验;
8
+ // 事故状态机落盘 ~/.openqq/incident.json(open/closed/attempts/rebasedTo,
9
+ // 跨重启延续计数、重启不洗白);
10
+ // 告警走 QQ 主动消息(每事故 open + fixed 各 ≤1 条,去重不骚扰)。
11
+ // @input: client(healthCheck/rebase)、discoverOpencode、alarm 回调、fs
12
+ // @output: startLinkWatch, LinkWatchDeps, IncidentRecord, incidentPath
13
+ // @pos: core - 链路巡检(HC2)
14
+ import { existsSync, readFileSync, writeFileSync } from "fs"
15
+ import { join } from "path"
16
+ import { homedir } from "os"
17
+ import { discoverOpencode, persistDiscovery, type OpencodeDiscovery } from "./discovery.js"
18
+ import { healthCheck, type OpencodeClient } from "../opencode/client.js"
19
+
20
+ export interface LinkWatchDeps {
21
+ client: OpencodeClient
22
+ // 热换基联动:eventstream 等持有同源 base 的组件在此同步换址
23
+ onRebase?: (baseUrl: string, discovery: OpencodeDiscovery) => void
24
+ // 告警通道(QQ 主动消息);未提供则仅落盘+日志
25
+ alarm?: (text: string) => Promise<void>
26
+ intervalMin?: number
27
+ // 测试注入:跳过 netstat 全扫描
28
+ discover?: (password?: string) => Promise<OpencodeDiscovery | null>
29
+ // 测试注入:事故文件路径(默认 ~/.openqq/incident.json)
30
+ incidentFile?: string
31
+ }
32
+
33
+ export interface IncidentRecord {
34
+ state: "open" | "closed"
35
+ since: string // ISO:首次失败时刻
36
+ lastCheck: string // ISO
37
+ lastError: string
38
+ attempts: number
39
+ rebasedTo?: string
40
+ }
41
+
42
+ export function incidentPath(): string {
43
+ return join(homedir(), ".openqq", "incident.json")
44
+ }
45
+
46
+ function saveIncident(path: string, rec: IncidentRecord): void {
47
+ try {
48
+ writeFileSync(path, JSON.stringify(rec, null, 2))
49
+ } catch (error) {
50
+ console.error("[linkwatch] incident 落盘失败:", error instanceof Error ? error.message : error)
51
+ }
52
+ }
53
+
54
+ function nowIso(): string {
55
+ return new Date().toISOString()
56
+ }
57
+
58
+ export interface LinkWatch {
59
+ stop(): void
60
+ // 测试/手动触发一轮巡检(与定时循环共用同一状态机,busy 互斥)
61
+ runOnce(): Promise<void>
62
+ }
63
+
64
+ export function startLinkWatch(deps: LinkWatchDeps): LinkWatch {
65
+ const envMin = Number(process.env.OPENCODE_LINKWATCH_MINUTES)
66
+ const intervalMs = Math.max(1, deps.intervalMin ?? (Number.isFinite(envMin) && envMin > 0 ? envMin : 30)) * 60_000
67
+ const file = deps.incidentFile ?? incidentPath()
68
+ const discover = deps.discover ?? ((p?: string) => discoverOpencode({ password: p }))
69
+ const password = process.env.OPENCODE_PASSWORD
70
+
71
+ let rec: IncidentRecord | null = null
72
+ let alarmOpenSent = false // 去重:每事故 open 告警只发一次(含跨重启)
73
+ let stopped = false
74
+ let busy = false
75
+ let loopTimer: ReturnType<typeof setTimeout> | null = null
76
+
77
+ // 恢复落盘的未结事故(跨重启延续;重启后不重发 open 告警,避免看门狗
78
+ // 周期重启导致告警风暴)
79
+ try {
80
+ if (existsSync(file)) {
81
+ const raw = JSON.parse(readFileSync(file, "utf-8")) as IncidentRecord
82
+ if (raw?.state === "open" && typeof raw.since === "string") {
83
+ rec = raw
84
+ alarmOpenSent = true
85
+ console.log(`[linkwatch] 恢复未结事故:自 ${raw.since}(attempts=${raw.attempts}),继续自愈`)
86
+ }
87
+ }
88
+ } catch {
89
+ // 损坏即视为无事故
90
+ }
91
+
92
+ async function fire(text: string): Promise<void> {
93
+ try {
94
+ await deps.alarm?.(text)
95
+ } catch (error) {
96
+ console.error("[linkwatch] 告警发送失败:", error instanceof Error ? error.message : error)
97
+ }
98
+ }
99
+
100
+ async function tick(): Promise<void> {
101
+ if (stopped || busy) return
102
+ busy = true
103
+ try {
104
+ try {
105
+ await healthCheck(deps.client, true)
106
+ // 健康:若有未结事故 → 结案(含恢复告警)
107
+ if (rec?.state === "open") {
108
+ const open = rec
109
+ const durMin = Math.max(1, Math.round((Date.now() - new Date(open.since).getTime()) / 60_000))
110
+ console.log(`[linkwatch] 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
111
+ if (!open.rebasedTo) {
112
+ // rebase 恢复路径在切换时已发过 fixed 告警;只有自然恢复才发恢复通知
113
+ await fire(`✅ OpenCode 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
114
+ }
115
+ saveIncident(file, { ...open, state: "closed", lastCheck: nowIso() })
116
+ rec = null
117
+ alarmOpenSent = false
118
+ }
119
+ return
120
+ } catch (error) {
121
+ const msg = error instanceof Error ? error.message : String(error)
122
+ if (!rec) {
123
+ rec = { state: "open", since: nowIso(), lastCheck: nowIso(), lastError: msg, attempts: 0 }
124
+ console.error(`[linkwatch] ⚠️ 链路失联开始(${msg}),转入自愈巡检`)
125
+ }
126
+ const inc = rec
127
+ inc.attempts++
128
+ inc.lastError = msg
129
+ inc.lastCheck = nowIso()
130
+
131
+ // 首次失败才发 open 告警(去重)
132
+ if (!alarmOpenSent) {
133
+ alarmOpenSent = true
134
+ await fire(
135
+ `⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.length > 80 ? `${msg.slice(0, 80)}…` : msg})。已转入自动自愈:发现新端口会自动切换并通知。`,
136
+ )
137
+ }
138
+
139
+ // 自愈:端口发现 → 热换基 → 复验
140
+ const found = await discover(password)
141
+ if (found && found.baseUrl !== deps.client.baseUrl) {
142
+ deps.client.rebase(found.baseUrl)
143
+ deps.onRebase?.(found.baseUrl, found)
144
+ persistDiscovery(found)
145
+ inc.rebasedTo = found.baseUrl
146
+ saveIncident(file, inc)
147
+ console.log(`[linkwatch] 热换基完成 → ${found.baseUrl}(v${found.version}),复验中…`)
148
+ try {
149
+ await healthCheck(deps.client, true)
150
+ console.log("[linkwatch] ✅ 换基复验通过,链路恢复")
151
+ await fire(`✅ OpenCode 端口已漂移,已自动切换旧地址 → ${found.baseUrl}(v${found.version}),链路恢复。`)
152
+ saveIncident(file, { ...inc, state: "closed", lastCheck: nowIso() })
153
+ rec = null
154
+ alarmOpenSent = false
155
+ } catch (e2) {
156
+ inc.lastError = e2 instanceof Error ? e2.message : String(e2)
157
+ inc.lastCheck = nowIso()
158
+ saveIncident(file, inc)
159
+ console.error("[linkwatch] 换基后仍失联,下轮继续:", inc.lastError)
160
+ }
161
+ } else {
162
+ // 未发现新端口(服务真宕/同口抖动):保持 open,下一轮再试
163
+ saveIncident(file, inc)
164
+ console.error(`[linkwatch] 第 ${inc.attempts} 次巡检失败,未发现新端口(${msg.slice(0, 80)})`)
165
+ }
166
+ }
167
+ } finally {
168
+ busy = false
169
+ }
170
+ }
171
+
172
+ // 可取消 sleep:stop() 清掉 pending 定时器,独立脚本(runOnce 后退出)不再悬挂
173
+ function waitInterval(): Promise<void> {
174
+ return new Promise((resolve) => {
175
+ loopTimer = setTimeout(resolve, intervalMs)
176
+ })
177
+ }
178
+
179
+ const loop = async (): Promise<void> => {
180
+ while (!stopped) {
181
+ await waitInterval()
182
+ if (stopped) break
183
+ await tick()
184
+ }
185
+ }
186
+ void loop()
187
+
188
+ return {
189
+ stop: () => {
190
+ stopped = true
191
+ if (loopTimer) clearTimeout(loopTimer)
192
+ },
193
+ runOnce: tick,
194
+ }
195
+ }
@@ -0,0 +1,80 @@
1
+ // @input: ../qq/types(MessageContext)
2
+ // @output: MessageQueue, QueuedJob, previewText, agoLabel
3
+ // @pos: core - 忙碌消息队列(Q1 学习自 pi-qqbot queue.ts 的 UX 语义)
4
+ //
5
+ // 旧行为:忙碌时直接拒绝"上一条消息还在处理中"。新行为(学习竞品):
6
+ // 忙时消息 FIFO 排队并回执,当前回合结束自动 drain 下一条;/cancel 清队。
7
+ // 控制面(/queue、审批作答、表单作答)永远即时处理,不进队列。
8
+ import type { MessageContext } from "../qq/types.js"
9
+
10
+ export interface QueuedJob {
11
+ id: number
12
+ userId: string
13
+ ctx: MessageContext
14
+ text: string
15
+ enqueuedAt: number
16
+ }
17
+
18
+ const PREVIEW_MAX = 48
19
+
20
+ export function previewText(text: string, max = PREVIEW_MAX): string {
21
+ const flat = text.replace(/\s+/g, " ").trim()
22
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)"
23
+ }
24
+
25
+ export function agoLabel(at: number, now = Date.now()): string {
26
+ const seconds = Math.max(0, Math.round((now - at) / 1000))
27
+ if (seconds < 60) return `${seconds}s 前`
28
+ const minutes = Math.floor(seconds / 60)
29
+ if (minutes < 60) return `${minutes}m 前`
30
+ return `${Math.floor(minutes / 60)}h 前`
31
+ }
32
+
33
+ export class MessageQueue {
34
+ private jobs = new Map<string, QueuedJob[]>()
35
+ private nextId = 1
36
+
37
+ constructor(private limit = 20) {}
38
+
39
+ /** 入队;满员返回 null(调用方回绝并提示) */
40
+ push(userId: string, ctx: MessageContext): { job: QueuedJob; ahead: number } | null {
41
+ const list = this.jobs.get(userId) ?? []
42
+ if (list.length >= this.limit) return null
43
+ const job: QueuedJob = { id: this.nextId++, userId, ctx, text: ctx.content, enqueuedAt: Date.now() }
44
+ list.push(job)
45
+ this.jobs.set(userId, list)
46
+ return { job, ahead: list.length - 1 }
47
+ }
48
+
49
+ shift(userId: string): QueuedJob | undefined {
50
+ const list = this.jobs.get(userId)
51
+ const job = list?.shift()
52
+ if (list && list.length === 0) this.jobs.delete(userId)
53
+ return job
54
+ }
55
+
56
+ list(userId: string): readonly QueuedJob[] {
57
+ return this.jobs.get(userId) ?? []
58
+ }
59
+
60
+ drop(userId: string, id: number): boolean {
61
+ const list = this.jobs.get(userId)
62
+ if (!list) return false
63
+ const idx = list.findIndex((j) => j.id === id)
64
+ if (idx < 0) return false
65
+ list.splice(idx, 1)
66
+ if (list.length === 0) this.jobs.delete(userId)
67
+ return true
68
+ }
69
+
70
+ /** 清空该用户队列,返回清掉的条数 */
71
+ clear(userId: string): number {
72
+ const n = this.jobs.get(userId)?.length ?? 0
73
+ this.jobs.delete(userId)
74
+ return n
75
+ }
76
+
77
+ size(userId: string): number {
78
+ return this.jobs.get(userId)?.length ?? 0
79
+ }
80
+ }