@linjz/opencode-qqbot 0.3.4 → 0.3.6

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 -37
  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 +360 -69
  6. package/package.json +69 -59
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +934 -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 +212 -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
package/src/index.ts CHANGED
@@ -1,162 +1,162 @@
1
- // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
- // @output: (side-effect) 启动 Bot 进程
3
- // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
- import { loadConfig, ensureConfig } from "./config.js"
5
- import { mkdirSync, writeFileSync } from "fs"
6
- import { join } from "path"
7
- import { homedir } from "os"
8
- import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
9
- import { discoverOpencode, persistDiscovery } from "./core/discovery.js"
10
- import { startLinkWatch } from "./core/linkwatch.js"
11
- import { getAccessToken, sendC2CMessage, getNextMsgSeq } from "./qq/api.js"
12
- import { SessionManager } from "./opencode/sessions.js"
13
- import { startGateway } from "./qq/gateway.js"
14
- import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
15
- import { createBridge } from "./bridge.js"
16
- import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
17
-
18
- // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
19
- // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
20
- // 退避后服务就绪即起,不再依赖下个看门狗 tick。
21
- // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
22
- // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
23
- // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
24
- async function waitForOpencode(
25
- clientFactory: (url: string) => OpencodeClient,
26
- initialUrl: string,
27
- ): Promise<OpencodeClient> {
28
- const deadline = Date.now() + 15 * 60 * 1000
29
- let attempt = 0
30
- let url = initialUrl
31
- let client = clientFactory(url)
32
- for (;;) {
33
- try {
34
- await healthCheck(client)
35
- return client
36
- } catch (error) {
37
- attempt++
38
- if (Date.now() >= deadline) throw error
39
- console.log(
40
- `[index] OpenCode 未就绪(第 ${attempt} 次):${error instanceof Error ? error.message : error} —20s 后重试`,
41
- )
42
- if (attempt === 1 || attempt % 3 === 0) {
43
- const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
44
- if (found && found.baseUrl !== url) {
45
- console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
46
- persistDiscovery(found)
47
- url = found.baseUrl
48
- client = clientFactory(url)
49
- }
50
- }
51
- await new Promise((r) => setTimeout(r, 20_000))
52
- }
53
- }
54
- }
55
-
56
- async function main(): Promise<void> {
57
- // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
58
- // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
59
- if (process.env.QQ_LOG_FILE) {
60
- const { installFileLog } = await import("./core/file-log.js")
61
- installFileLog(process.env.QQ_LOG_FILE)
62
- }
63
- await ensureConfig()
64
- const config = loadConfig()
65
-
66
- // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
67
- // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
68
- // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
69
- // 场景:多 location 并发拉起时防待命实例堆积)。
70
- let instanceLock: InstanceLock | null = null
71
- const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
72
- if (lockMode === "try") {
73
- instanceLock = acquireInstanceLock(config.qq.appId)
74
- if (!instanceLock) {
75
- console.log("[index] 已有实例在运行(try 模式),本实例退出")
76
- process.exit(0)
77
- }
78
- } else if (lockMode !== "false") {
79
- instanceLock = await waitInstanceLock(config.qq.appId)
80
- }
81
-
82
- if (!config.opencode.baseUrl) {
83
- throw new Error("缺少 OPENCODE_BASE_URL,指向 OpenCode 桌面版 API(如 http://127.0.0.1:<端口>/api;2.1.x 端口动态,失联时启动流程会自动发现)")
84
- }
85
-
86
- const client = await waitForOpencode((u) => createClient(u), config.opencode.baseUrl)
87
-
88
- startBackgroundTokenRefresh(config.qq.appId, config.qq.clientSecret)
89
-
90
- const sessions = new SessionManager(client)
91
- const bridge = createBridge(config, client, sessions)
92
- const { eventStream } = bridge
93
-
94
- // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
95
- // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
96
- // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
97
- const alarm = async (text: string): Promise<void> => {
98
- const uid = config.allowedUsers[0]
99
- if (!uid) return
100
- const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
101
- const seq = getNextMsgSeq("")
102
- try {
103
- await sendC2CMessage(token, uid, text, undefined, seq, true)
104
- } catch (error) {
105
- console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
106
- await sendC2CMessage(token, uid, text, undefined, seq, false)
107
- }
108
- }
109
- const linkWatch = startLinkWatch({ client, onRebase: (url) => eventStream.rebase(url), alarm })
110
-
111
- const gateway = await startGateway({
112
- appId: config.qq.appId,
113
- clientSecret: config.qq.clientSecret,
114
- onMessage: bridge.handleMessage,
115
- onInteraction: (event) => bridge.handleInteraction(event),
116
- onReady: () => {
117
- console.log("[index] QQ Gateway 已就绪")
118
- },
119
- })
120
-
121
- console.log("[index] OpenCode QQ Bot 已启动")
122
-
123
- // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
124
- //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。
125
- void bridge.recoverInflightRounds()
126
-
127
- // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
128
- // 看门狗据此识别"进程在但僵死"的静默僵尸(2-day silent zombie 教训)。
129
- const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
130
- const touchHeartbeat = (): void => {
131
- try {
132
- mkdirSync(join(homedir(), ".openqq"), { recursive: true })
133
- writeFileSync(heartbeatFile, String(Date.now()))
134
- } catch (error) {
135
- console.error("[index] 心跳写入失败:", error)
136
- }
137
- }
138
- touchHeartbeat()
139
- const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
140
-
141
- let shuttingDown = false
142
- const shutdown = (signal: string): void => {
143
- if (shuttingDown) return
144
- shuttingDown = true
145
- console.log(`[index] 收到 ${signal},开始退出...`)
146
- clearInterval(heartbeatTimer)
147
- instanceLock?.release()
148
- linkWatch.stop()
149
- gateway.stop()
150
- stopBackgroundTokenRefresh()
151
- setTimeout(() => process.exit(0), 0)
152
- }
153
-
154
- process.once("SIGINT", () => shutdown("SIGINT"))
155
- process.once("SIGTERM", () => shutdown("SIGTERM"))
156
- }
157
-
158
- main().catch((error) => {
159
- console.error("[index] 启动失败:", error)
160
- stopBackgroundTokenRefresh()
161
- process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
162
- })
1
+ // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
+ // @output: (side-effect) 启动 Bot 进程
3
+ // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
+ import { loadConfig, ensureConfig } from "./config.js"
5
+ import { mkdirSync, writeFileSync } from "fs"
6
+ import { join } from "path"
7
+ import { homedir } from "os"
8
+ import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
9
+ import { discoverOpencode, persistDiscovery } from "./core/discovery.js"
10
+ import { startLinkWatch } from "./core/linkwatch.js"
11
+ import { getAccessToken, sendC2CMessage, getNextMsgSeq } from "./qq/api.js"
12
+ import { SessionManager } from "./opencode/sessions.js"
13
+ import { startGateway } from "./qq/gateway.js"
14
+ import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
15
+ import { createBridge } from "./bridge.js"
16
+ import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
17
+
18
+ // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
19
+ // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
20
+ // 退避后服务就绪即起,不再依赖下个看门狗 tick。
21
+ // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
22
+ // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
23
+ // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
24
+ async function waitForOpencode(
25
+ clientFactory: (url: string) => OpencodeClient,
26
+ initialUrl: string,
27
+ ): Promise<OpencodeClient> {
28
+ const deadline = Date.now() + 15 * 60 * 1000
29
+ let attempt = 0
30
+ let url = initialUrl
31
+ let client = clientFactory(url)
32
+ for (;;) {
33
+ try {
34
+ await healthCheck(client)
35
+ return client
36
+ } catch (error) {
37
+ attempt++
38
+ if (Date.now() >= deadline) throw error
39
+ console.log(
40
+ `[index] OpenCode 未就绪(第 ${attempt} 次):${error instanceof Error ? error.message : error} —20s 后重试`,
41
+ )
42
+ if (attempt === 1 || attempt % 3 === 0) {
43
+ const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
44
+ if (found && found.baseUrl !== url) {
45
+ console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
46
+ persistDiscovery(found)
47
+ url = found.baseUrl
48
+ client = clientFactory(url)
49
+ }
50
+ }
51
+ await new Promise((r) => setTimeout(r, 20_000))
52
+ }
53
+ }
54
+ }
55
+
56
+ async function main(): Promise<void> {
57
+ // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
58
+ // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
59
+ if (process.env.QQ_LOG_FILE) {
60
+ const { installFileLog } = await import("./core/file-log.js")
61
+ installFileLog(process.env.QQ_LOG_FILE)
62
+ }
63
+ await ensureConfig()
64
+ const config = loadConfig()
65
+
66
+ // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
67
+ // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
68
+ // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
69
+ // 场景:多 location 并发拉起时防待命实例堆积)。
70
+ let instanceLock: InstanceLock | null = null
71
+ const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
72
+ if (lockMode === "try") {
73
+ instanceLock = acquireInstanceLock(config.qq.appId)
74
+ if (!instanceLock) {
75
+ console.log("[index] 已有实例在运行(try 模式),本实例退出")
76
+ process.exit(0)
77
+ }
78
+ } else if (lockMode !== "false") {
79
+ instanceLock = await waitInstanceLock(config.qq.appId)
80
+ }
81
+
82
+ if (!config.opencode.baseUrl) {
83
+ throw new Error("缺少 OPENCODE_BASE_URL,指向 OpenCode 桌面版 API(如 http://127.0.0.1:<端口>/api;2.1.x 端口动态,失联时启动流程会自动发现)")
84
+ }
85
+
86
+ const client = await waitForOpencode((u) => createClient(u), config.opencode.baseUrl)
87
+
88
+ startBackgroundTokenRefresh(config.qq.appId, config.qq.clientSecret)
89
+
90
+ const sessions = new SessionManager(client)
91
+ const bridge = createBridge(config, client, sessions)
92
+ const { eventStream } = bridge
93
+
94
+ // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
95
+ // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
96
+ // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
97
+ const alarm = async (text: string): Promise<void> => {
98
+ const uid = config.allowedUsers[0]
99
+ if (!uid) return
100
+ const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
101
+ const seq = getNextMsgSeq("")
102
+ try {
103
+ await sendC2CMessage(token, uid, text, undefined, seq, true)
104
+ } catch (error) {
105
+ console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
106
+ await sendC2CMessage(token, uid, text, undefined, seq, false)
107
+ }
108
+ }
109
+ const linkWatch = startLinkWatch({ client, onRebase: (url) => eventStream.rebase(url), alarm })
110
+
111
+ const gateway = await startGateway({
112
+ appId: config.qq.appId,
113
+ clientSecret: config.qq.clientSecret,
114
+ onMessage: bridge.handleMessage,
115
+ onInteraction: (event) => bridge.handleInteraction(event),
116
+ onReady: () => {
117
+ console.log("[index] QQ Gateway 已就绪")
118
+ },
119
+ })
120
+
121
+ console.log("[index] OpenCode QQ Bot 已启动")
122
+
123
+ // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
124
+ //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。
125
+ void bridge.recoverInflightRounds()
126
+
127
+ // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
128
+ // 看门狗据此识别"进程在但僵死"的静默僵尸(2-day silent zombie 教训)。
129
+ const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
130
+ const touchHeartbeat = (): void => {
131
+ try {
132
+ mkdirSync(join(homedir(), ".openqq"), { recursive: true })
133
+ writeFileSync(heartbeatFile, String(Date.now()))
134
+ } catch (error) {
135
+ console.error("[index] 心跳写入失败:", error)
136
+ }
137
+ }
138
+ touchHeartbeat()
139
+ const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
140
+
141
+ let shuttingDown = false
142
+ const shutdown = (signal: string): void => {
143
+ if (shuttingDown) return
144
+ shuttingDown = true
145
+ console.log(`[index] 收到 ${signal},开始退出...`)
146
+ clearInterval(heartbeatTimer)
147
+ instanceLock?.release()
148
+ linkWatch.stop()
149
+ gateway.stop()
150
+ stopBackgroundTokenRefresh()
151
+ setTimeout(() => process.exit(0), 0)
152
+ }
153
+
154
+ process.once("SIGINT", () => shutdown("SIGINT"))
155
+ process.once("SIGTERM", () => shutdown("SIGTERM"))
156
+ }
157
+
158
+ main().catch((error) => {
159
+ console.error("[index] 启动失败:", error)
160
+ stopBackgroundTokenRefresh()
161
+ process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
162
+ })
@@ -1,11 +1,11 @@
1
- # opencode
2
-
3
- OpenCode 对接层:SDK 客户端、SSE 事件路由、会话管理。
4
-
5
- ## 文件
6
-
7
- | 文件 | 职责 |
8
- |------|------|
9
- | client.ts | OpenCode SDK 客户端封装 + 健康检查 |
10
- | events.ts | 全局 SSE 事件订阅 + 按 sessionId 分发 |
11
- | sessions.ts | QQ用户<->OpenCode Session 映射管理 |
1
+ # opencode
2
+
3
+ OpenCode 对接层:SDK 客户端、SSE 事件路由、会话管理。
4
+
5
+ ## 文件
6
+
7
+ | 文件 | 职责 |
8
+ |------|------|
9
+ | client.ts | OpenCode SDK 客户端封装 + 健康检查 |
10
+ | events.ts | 全局 SSE 事件订阅 + 按 sessionId 分发 |
11
+ | sessions.ts | QQ用户<->OpenCode Session 映射管理 |