@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/index.ts CHANGED
@@ -1,250 +1,262 @@
1
- // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
- // @output: (side-effect) 启动 Bot 进程
3
- // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
- import { loadConfig, ensureConfig, loadRoles, type Config } from "./config.js"
5
- import { storageFile } from "./core/storage.js"
6
- import { mkdirSync, writeFileSync } from "fs"
7
- import { join } from "path"
8
- import { homedir } from "os"
9
- import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
10
- import { discoverOpencode, persistDiscovery } from "./core/discovery.js"
11
- import { startLinkWatch } from "./core/linkwatch.js"
12
- import { getAccessToken, sendC2CMessage, getNextMsgSeq, registerAppEnv } from "./qq/api.js"
13
- import { SessionManager } from "./opencode/sessions.js"
14
- import { startGateway } from "./qq/gateway.js"
15
- import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
16
- import { createBridge, type Bridge } from "./bridge.js"
17
- import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
18
-
19
- // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
20
- // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
21
- // 退避后服务就绪即起,不再依赖下个看门狗 tick。
22
- // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
23
- // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
24
- // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
25
- async function waitForOpencode(
26
- clientFactory: (url: string) => OpencodeClient,
27
- initialUrl: string,
28
- ): Promise<OpencodeClient> {
29
- const deadline = Date.now() + 15 * 60 * 1000
30
- let attempt = 0
31
- let url = initialUrl
32
- let client = clientFactory(url)
33
- // 2026-11-09 掉线事故:凭据失配(401)是确定性错误,重试 15 分钟毫无意义
34
- //(事故实测:401 连刷 34 次,锁在、无心跳,整机判僵尸 15 分钟)。连续 N 次
35
- // 认证失败即快速退出,把锁交还,交给插件引导器/看门狗用干净环境重拉。
36
- const AUTH_FAIL_LIMIT = 3
37
- let authFails = 0
38
- for (;;) {
39
- try {
40
- await healthCheck(client)
41
- return client
42
- } catch (error) {
43
- attempt++
44
- const msg = error instanceof Error ? error.message : String(error)
45
- if (/\b401\b|Unauthorized/i.test(msg)) {
46
- authFails++
47
- if (authFails >= AUTH_FAIL_LIMIT) {
48
- throw new Error(
49
- `${msg}(连续 ${authFails} 次认证被拒)—— 请核对 ~/.openqq/.env 的 OPENCODE_PASSWORD 是否与当前 OpenCode 服务一致;本实例退出,等待外部拉起`,
50
- )
51
- }
52
- } else {
53
- authFails = 0
54
- }
55
- if (Date.now() >= deadline) throw error
56
- console.log(
57
- `[index] OpenCode 未就绪(第 ${attempt} 次):${msg} —20s 后重试`,
58
- )
59
- // DEF-20261119-P9:429 的 Retry-After 优先于固定节奏(UAT SY-004 注入实证:
60
- // 服务端暗示 5s,原实现死等 20s×N)。非 429/无头时维持 20s 不变。
61
- const ra = msg.match(/\[retry-after:(\d+(?:\.\d+)?)\]/)
62
- const waitMs = ra ? Math.max(20_000, Number(ra[1]) * 1000) : 20_000
63
- if (ra) console.log(`[index] 按服务端 Retry-After 退避 ${Math.round(waitMs / 1000)}s`)
64
- if (attempt === 1 || attempt % 3 === 0) {
65
- const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
66
- if (found && found.baseUrl !== url) {
67
- console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
68
- persistDiscovery(found)
69
- url = found.baseUrl
70
- client = clientFactory(url)
71
- }
72
- }
73
- await new Promise((r) => setTimeout(r, waitMs))
74
- }
75
- }
76
- }
77
-
78
- async function main(): Promise<void> {
79
- // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
80
- // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
81
- // 2026-11-05:默认开启(~/.openqq/openqq.log),堵住 bot.out.log 断流无人发现的缺口;
82
- // QQ_LOG_FILE 可覆盖路径,设 0/off/false 关闭。
83
- {
84
- const raw = (process.env.QQ_LOG_FILE ?? "").trim()
85
- if (!/^(0|off|false|no)$/i.test(raw)) {
86
- const { installFileLog } = await import("./core/file-log.js")
87
- installFileLog(raw || join(homedir(), ".openqq", "openqq.log"))
88
- }
89
- }
90
- await ensureConfig()
91
- const baseConfig = loadConfig()
92
-
93
- // 多角色(2026-11-17 owner 裁定,参考 openclaw-qqbot 具名账号表):
94
- // env QQ_BOTS=[{appId,secret,sandbox,name,allowedUsers}] 存在时单进程挂全部角色,
95
- // 角色数据落 ~/.openqq/roles/<appId>/ 物理隔离;未配置 = legacy 单角色,零变化。
96
- const roles = loadRoles()
97
- const multiRole = !!(process.env.QQ_BOTS ?? "").trim()
98
- const roleConfigOf = (r: (typeof roles)[number]): Config => ({
99
- qq: { appId: r.appId, clientSecret: r.clientSecret, sandbox: r.sandbox },
100
- opencode: baseConfig.opencode,
101
- allowedUsers: r.allowedUsers,
102
- })
103
-
104
- // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
105
- // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
106
- // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
107
- // 场景:多 location 并发拉起时防待命实例堆积)。
108
- // 多角色:锁文件按 appId 隔离(openqq-<appId>.lock),每角色各持各锁、互不阻塞。
109
- const instanceLocks: InstanceLock[] = []
110
- const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
111
- if (lockMode === "try") {
112
- for (const r of roles) {
113
- const lock = acquireInstanceLock(r.appId)
114
- if (!lock) {
115
- console.log(`[index] 角色 ${r.appId} 已有实例在运行(try 模式),本实例退出`)
116
- for (const l of instanceLocks) l.release()
117
- process.exit(0)
118
- }
119
- instanceLocks.push(lock)
120
- }
121
- } else if (lockMode !== "false") {
122
- for (const r of roles) instanceLocks.push(await waitInstanceLock(r.appId))
123
- }
124
-
125
- if (!baseConfig.opencode.baseUrl) {
126
- throw new Error("缺少 OPENCODE_BASE_URL,指向 OpenCode 桌面版 API(如 http://127.0.0.1:<端口>/api;2.1.x 端口动态,失联时启动流程会自动发现)")
127
- }
128
-
129
- // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
130
- // 2026-11-09 加固:提前到「抢锁后、连 OpenCode 前」——启动阶段(等 OpenCode /
131
- // 发现端口)同样可能持续数分钟,原先这段空白会让看门狗把健康启动判成
132
- // 「心跳陈旧」而杀掉。锁活性另由 instance-lock 的 mtime 心跳承担,两者互不替代。
133
- const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
134
- const touchHeartbeat = (): void => {
135
- try {
136
- mkdirSync(join(homedir(), ".openqq"), { recursive: true })
137
- writeFileSync(heartbeatFile, String(Date.now()))
138
- } catch (error) {
139
- console.error("[index] 心跳写入失败:", error)
140
- }
141
- }
142
- touchHeartbeat()
143
- const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
144
- heartbeatTimer.unref?.()
145
- // 事件循环漂移遥测(2026-11-09 心跳停滞事故):预期每 30s 触发一次,
146
- // 实际延迟 = 定时器被事件循环推迟了多少。漂移 >5s 说明 loop 被卡住,
147
- // 心跳/审批 TTL 等所有定时器都会被同步推迟——直接输出证据。
148
- let lastTick = Date.now()
149
- const lagTimer = setInterval(() => {
150
- const now = Date.now()
151
- const drift = now - lastTick - 30_000
152
- lastTick = now
153
- if (drift > 5_000) {
154
- console.warn(`[loop-lag] 事件循环漂移 ${Math.round(drift / 1000)}s(定时器被推迟,心跳可能失新鲜)`)
155
- }
156
- }, 30_000)
157
- lagTimer.unref?.()
158
-
159
- let client: OpencodeClient
160
- try {
161
- client = await waitForOpencode((u) => createClient(u), baseConfig.opencode.baseUrl)
162
- } catch (error) {
163
- // 启动失败立即交还锁,缩短下一次接管的等待(否则锁要等 30s 过期才回收)
164
- clearInterval(heartbeatTimer)
165
- clearInterval(lagTimer)
166
- for (const l of instanceLocks) l.release()
167
- throw error
168
- }
169
-
170
- // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
171
- // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
172
- // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
173
- // 多角色:告警用首个角色的凭据与首用户(告警是进程级事故,一份足够)。
174
- const alarmRole = roles[0]
175
- const alarm = async (text: string): Promise<void> => {
176
- const uid = alarmRole.allowedUsers[0]
177
- if (!uid) return
178
- const token = await getAccessToken(alarmRole.appId, alarmRole.clientSecret)
179
- const seq = getNextMsgSeq("")
180
- try {
181
- await sendC2CMessage(token, uid, text, undefined, seq, true)
182
- } catch (error) {
183
- console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
184
- await sendC2CMessage(token, uid, text, undefined, seq, false)
185
- }
186
- }
187
-
188
- // ── 角色装配:每角色一套 token 刷新 / 会话映射 / bridge / 网关 ──
189
- const roleBridges: Bridge[] = []
190
- const roleGateways: Array<{ stop: () => void }> = []
191
- for (const role of roles) {
192
- // §2.3 失效模式:单角色启动失败不拖垮其余角色(降级=该角色不在线,日志明示)
193
- try {
194
- registerAppEnv(role.appId, role.sandbox)
195
- startBackgroundTokenRefresh(role.appId, role.clientSecret)
196
- const roleConfig = roleConfigOf(role)
197
- // 多角色:会话映射按角色分文件;legacy 模式缺省路径零变化
198
- const sessions = new SessionManager(
199
- client,
200
- multiRole ? storageFile("sessions.json", role.appId) : undefined,
201
- )
202
- const bridge = createBridge(roleConfig, client, sessions, multiRole ? role.appId : undefined)
203
- roleBridges.push(bridge)
204
- const gateway = await startGateway({
205
- appId: role.appId,
206
- clientSecret: role.clientSecret,
207
- stateFile: multiRole ? storageFile("gateway-state.json", role.appId) : undefined,
208
- onMessage: bridge.handleMessage,
209
- onInteraction: (event) => bridge.handleInteraction(event),
210
- onReady: () => {
211
- console.log(`[index] QQ Gateway 已就绪(角色 ${role.name}/${role.appId})`)
212
- },
213
- })
214
- roleGateways.push(gateway)
215
- console.log(`[index] 角色已装配:${role.name}(appId=${role.appId},sandbox=${role.sandbox})`)
216
- } catch (error) {
217
- console.error(`[index] 角色 ${role.name}(${role.appId})装配失败,其余角色不受影响:`, error)
218
- }
219
- }
220
- const linkWatch = startLinkWatch({ client, onRebase: (url) => roleBridges[0].eventStream.rebase(url), alarm })
221
-
222
- console.log(`[index] OpenCode QQ Bot 已启动(${roles.length} 个角色)`)
223
-
224
- // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
225
- //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。每角色各自对账。
226
- for (const b of roleBridges) void b.recoverInflightRounds()
227
-
228
- let shuttingDown = false
229
- const shutdown = (signal: string): void => {
230
- if (shuttingDown) return
231
- shuttingDown = true
232
- console.log(`[index] 收到 ${signal},开始退出...`)
233
- clearInterval(heartbeatTimer)
234
- clearInterval(lagTimer)
235
- for (const l of instanceLocks) l.release()
236
- linkWatch.stop()
237
- for (const g of roleGateways) g.stop()
238
- stopBackgroundTokenRefresh()
239
- setTimeout(() => process.exit(0), 0)
240
- }
241
-
242
- process.once("SIGINT", () => shutdown("SIGINT"))
243
- process.once("SIGTERM", () => shutdown("SIGTERM"))
244
- }
245
-
246
- main().catch((error) => {
247
- console.error("[index] 启动失败:", error)
248
- stopBackgroundTokenRefresh()
249
- process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
250
- })
1
+ // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
+ // @output: (side-effect) 启动 Bot 进程
3
+ // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
+ import { loadConfig, ensureConfig, loadRoles, type Config } from "./config.js"
5
+ import { storageFile } from "./core/storage.js"
6
+ import { mkdirSync, writeFileSync } from "fs"
7
+ import { join } from "path"
8
+ import { homedir } from "os"
9
+ import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
10
+ import { discoverOpencode, persistDiscovery, readLastDiscovered, resolveInitialBaseUrl } from "./core/discovery.js"
11
+ import { formatStartupError, startupDiagnosticBundle } from "./core/start-error.js"
12
+ import { startLinkWatch } from "./core/linkwatch.js"
13
+ import { getAccessToken, sendC2CMessage, getNextMsgSeq, registerAppEnv } from "./qq/api.js"
14
+ import { SessionManager } from "./opencode/sessions.js"
15
+ import { startGateway } from "./qq/gateway.js"
16
+ import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
17
+ import { createBridge, type Bridge } from "./bridge.js"
18
+ import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
19
+
20
+ // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
21
+ // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
22
+ // 退避后服务就绪即起,不再依赖下个看门狗 tick。
23
+ // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
24
+ // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
25
+ // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
26
+ async function waitForOpencode(
27
+ clientFactory: (url: string) => OpencodeClient,
28
+ initialUrl: string,
29
+ ): Promise<OpencodeClient> {
30
+ const deadline = Date.now() + 15 * 60 * 1000
31
+ let attempt = 0
32
+ let url = initialUrl
33
+ let client = clientFactory(url)
34
+ // 2026-11-09 掉线事故:凭据失配(401)是确定性错误,重试 15 分钟毫无意义
35
+ //(事故实测:401 连刷 34 次,锁在、无心跳,整机判僵尸 15 分钟)。连续 N 次
36
+ // 认证失败即快速退出,把锁交还,交给插件引导器/看门狗用干净环境重拉。
37
+ const AUTH_FAIL_LIMIT = 3
38
+ let authFails = 0
39
+ for (;;) {
40
+ try {
41
+ await healthCheck(client)
42
+ return client
43
+ } catch (error) {
44
+ attempt++
45
+ const msg = error instanceof Error ? error.message : String(error)
46
+ if (/\b401\b|Unauthorized/i.test(msg)) {
47
+ authFails++
48
+ if (authFails >= AUTH_FAIL_LIMIT) {
49
+ throw new Error(
50
+ `${msg}(连续 ${authFails} 次认证被拒)—— 请核对 ~/.openqq/.env 的 OPENCODE_PASSWORD 是否与当前 OpenCode 服务一致;本实例退出,等待外部拉起`,
51
+ )
52
+ }
53
+ } else {
54
+ authFails = 0
55
+ }
56
+ if (Date.now() >= deadline) throw error
57
+ console.log(
58
+ `[index] OpenCode 未就绪(第 ${attempt} 次):${msg} —20s 后重试`,
59
+ )
60
+ // DEF-20261119-P9:429 的 Retry-After 优先于固定节奏(UAT SY-004 注入实证:
61
+ // 服务端暗示 5s,原实现死等 20s×N)。非 429/无头时维持 20s 不变。
62
+ const ra = msg.match(/\[retry-after:(\d+(?:\.\d+)?)\]/)
63
+ const waitMs = ra ? Math.max(20_000, Number(ra[1]) * 1000) : 20_000
64
+ if (ra) console.log(`[index] 按服务端 Retry-After 退避 ${Math.round(waitMs / 1000)}s`)
65
+ if (attempt === 1 || attempt % 3 === 0) {
66
+ const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
67
+ if (found && found.baseUrl !== url) {
68
+ console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
69
+ persistDiscovery(found)
70
+ url = found.baseUrl
71
+ client = clientFactory(url)
72
+ }
73
+ }
74
+ await new Promise((r) => setTimeout(r, waitMs))
75
+ }
76
+ }
77
+ }
78
+
79
+ async function main(): Promise<void> {
80
+ // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
81
+ // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
82
+ // 2026-11-05:默认开启(~/.openqq/openqq.log),堵住 bot.out.log 断流无人发现的缺口;
83
+ // QQ_LOG_FILE 可覆盖路径,设 0/off/false 关闭。
84
+ {
85
+ const raw = (process.env.QQ_LOG_FILE ?? "").trim()
86
+ if (!/^(0|off|false|no)$/i.test(raw)) {
87
+ const { installFileLog } = await import("./core/file-log.js")
88
+ installFileLog(raw || join(homedir(), ".openqq", "openqq.log"))
89
+ }
90
+ }
91
+ await ensureConfig()
92
+ const baseConfig = loadConfig()
93
+
94
+ // 多角色(2026-11-17 owner 裁定,参考 openclaw-qqbot 具名账号表):
95
+ // env QQ_BOTS=[{appId,secret,sandbox,name,allowedUsers}] 存在时单进程挂全部角色,
96
+ // 角色数据落 ~/.openqq/roles/<appId>/ 物理隔离;未配置 = legacy 单角色,零变化。
97
+ const roles = loadRoles()
98
+ const multiRole = !!(process.env.QQ_BOTS ?? "").trim()
99
+ const roleConfigOf = (r: (typeof roles)[number]): Config => ({
100
+ qq: { appId: r.appId, clientSecret: r.clientSecret, sandbox: r.sandbox },
101
+ opencode: baseConfig.opencode,
102
+ allowedUsers: r.allowedUsers,
103
+ })
104
+
105
+ // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
106
+ // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
107
+ // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
108
+ // 场景:多 location 并发拉起时防待命实例堆积)。
109
+ // 多角色:锁文件按 appId 隔离(openqq-<appId>.lock),每角色各持各锁、互不阻塞。
110
+ const instanceLocks: InstanceLock[] = []
111
+ const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
112
+ if (lockMode === "try") {
113
+ for (const r of roles) {
114
+ const lock = acquireInstanceLock(r.appId)
115
+ if (!lock) {
116
+ console.log(`[index] 角色 ${r.appId} 已有实例在运行(try 模式),本实例退出`)
117
+ for (const l of instanceLocks) l.release()
118
+ process.exit(0)
119
+ }
120
+ instanceLocks.push(lock)
121
+ }
122
+ } else if (lockMode !== "false") {
123
+ for (const r of roles) instanceLocks.push(await waitInstanceLock(r.appId))
124
+ }
125
+
126
+ // DEF-20261120-01c:OPENCODE_BASE_URL 可选化(owner 2026-11-20「能自动发现的
127
+ // 都不要配置」举一反三指令)——显式配置仍是第一优先(externalUrl 语义不变);
128
+ // 缺省时沿用上次自动发现档案,引擎换端口由既有重试-发现环第 1 次纠正。
129
+ const resolvedInitial = resolveInitialBaseUrl(
130
+ baseConfig.opencode.baseUrl,
131
+ baseConfig.opencode.baseUrl ? null : readLastDiscovered(),
132
+ )
133
+ if (resolvedInitial.source !== "explicit") {
134
+ console.log(
135
+ `[index] 未配置 OPENCODE_BASE_URL,初始地址=${resolvedInitial.source === "last-discovered" ? "上次自动发现" : "占位"} ${resolvedInitial.url}(失联时自动端口发现纠正)`,
136
+ )
137
+ }
138
+
139
+ // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
140
+ // 2026-11-09 加固:提前到「抢锁后、连 OpenCode 前」——启动阶段(等 OpenCode /
141
+ // 发现端口)同样可能持续数分钟,原先这段空白会让看门狗把健康启动判成
142
+ // 「心跳陈旧」而杀掉。锁活性另由 instance-lock 的 mtime 心跳承担,两者互不替代。
143
+ const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
144
+ const touchHeartbeat = (): void => {
145
+ try {
146
+ mkdirSync(join(homedir(), ".openqq"), { recursive: true })
147
+ writeFileSync(heartbeatFile, String(Date.now()))
148
+ } catch (error) {
149
+ console.error("[index] 心跳写入失败:", error)
150
+ }
151
+ }
152
+ touchHeartbeat()
153
+ const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
154
+ heartbeatTimer.unref?.()
155
+ // 事件循环漂移遥测(2026-11-09 心跳停滞事故):预期每 30s 触发一次,
156
+ // 实际延迟 = 定时器被事件循环推迟了多少。漂移 >5s 说明 loop 被卡住,
157
+ // 心跳/审批 TTL 等所有定时器都会被同步推迟——直接输出证据。
158
+ let lastTick = Date.now()
159
+ const lagTimer = setInterval(() => {
160
+ const now = Date.now()
161
+ const drift = now - lastTick - 30_000
162
+ lastTick = now
163
+ if (drift > 5_000) {
164
+ console.warn(`[loop-lag] 事件循环漂移 ${Math.round(drift / 1000)}s(定时器被推迟,心跳可能失新鲜)`)
165
+ }
166
+ }, 30_000)
167
+ lagTimer.unref?.()
168
+
169
+ let client: OpencodeClient
170
+ try {
171
+ client = await waitForOpencode((u) => createClient(u), resolvedInitial.url)
172
+ } catch (error) {
173
+ // 启动失败立即交还锁,缩短下一次接管的等待(否则锁要等 30s 过期才回收)
174
+ clearInterval(heartbeatTimer)
175
+ clearInterval(lagTimer)
176
+ for (const l of instanceLocks) l.release()
177
+ throw error
178
+ }
179
+
180
+ // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
181
+ // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
182
+ // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
183
+ // 多角色:告警用首个角色的凭据与首用户(告警是进程级事故,一份足够)。
184
+ const alarmRole = roles[0]
185
+ const alarm = async (text: string): Promise<void> => {
186
+ const uid = alarmRole.allowedUsers[0]
187
+ if (!uid) return
188
+ const token = await getAccessToken(alarmRole.appId, alarmRole.clientSecret)
189
+ const seq = getNextMsgSeq("")
190
+ try {
191
+ await sendC2CMessage(token, uid, text, undefined, seq, true)
192
+ } catch (error) {
193
+ console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
194
+ await sendC2CMessage(token, uid, text, undefined, seq, false)
195
+ }
196
+ }
197
+
198
+ // ── 角色装配:每角色一套 token 刷新 / 会话映射 / bridge / 网关 ──
199
+ const roleBridges: Bridge[] = []
200
+ const roleGateways: Array<{ stop: () => void }> = []
201
+ for (const role of roles) {
202
+ // §2.3 失效模式:单角色启动失败不拖垮其余角色(降级=该角色不在线,日志明示)
203
+ try {
204
+ registerAppEnv(role.appId, role.sandbox)
205
+ startBackgroundTokenRefresh(role.appId, role.clientSecret)
206
+ const roleConfig = roleConfigOf(role)
207
+ // 多角色:会话映射按角色分文件;legacy 模式缺省路径零变化
208
+ const sessions = new SessionManager(
209
+ client,
210
+ multiRole ? storageFile("sessions.json", role.appId) : undefined,
211
+ )
212
+ const bridge = createBridge(roleConfig, client, sessions, multiRole ? role.appId : undefined)
213
+ roleBridges.push(bridge)
214
+ const gateway = await startGateway({
215
+ appId: role.appId,
216
+ clientSecret: role.clientSecret,
217
+ stateFile: multiRole ? storageFile("gateway-state.json", role.appId) : undefined,
218
+ onMessage: bridge.handleMessage,
219
+ onInteraction: (event) => bridge.handleInteraction(event),
220
+ onReady: () => {
221
+ console.log(`[index] QQ Gateway 已就绪(角色 ${role.name}/${role.appId})`)
222
+ },
223
+ })
224
+ roleGateways.push(gateway)
225
+ console.log(`[index] 角色已装配:${role.name}(appId=${role.appId},sandbox=${role.sandbox})`)
226
+ } catch (error) {
227
+ console.error(`[index] 角色 ${role.name}(${role.appId})装配失败,其余角色不受影响:`, error)
228
+ }
229
+ }
230
+ const linkWatch = startLinkWatch({ client, onRebase: (url) => roleBridges[0].eventStream.rebase(url), alarm })
231
+
232
+ console.log(`[index] OpenCode QQ Bot 已启动(${roles.length} 个角色)`)
233
+
234
+ // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
235
+ //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。每角色各自对账。
236
+ for (const b of roleBridges) void b.recoverInflightRounds()
237
+
238
+ let shuttingDown = false
239
+ const shutdown = (signal: string): void => {
240
+ if (shuttingDown) return
241
+ shuttingDown = true
242
+ console.log(`[index] 收到 ${signal},开始退出...`)
243
+ clearInterval(heartbeatTimer)
244
+ clearInterval(lagTimer)
245
+ for (const l of instanceLocks) l.release()
246
+ linkWatch.stop()
247
+ for (const g of roleGateways) g.stop()
248
+ stopBackgroundTokenRefresh()
249
+ setTimeout(() => process.exit(0), 0)
250
+ }
251
+
252
+ process.once("SIGINT", () => shutdown("SIGINT"))
253
+ process.once("SIGTERM", () => shutdown("SIGTERM"))
254
+ }
255
+
256
+ main().catch((error) => {
257
+ // DEF-20261120-01a:非 Error 抛出必须可读({} 事故),诊断包定位拉起通道环境 delta
258
+ console.error("[index] 启动失败:", formatStartupError(error))
259
+ console.error("[index] 启动失败诊断包:", startupDiagnosticBundle())
260
+ stopBackgroundTokenRefresh()
261
+ process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
262
+ })
@@ -53,6 +53,9 @@ export interface PermissionRequest {
53
53
  export interface PromptOptions {
54
54
  model?: { providerID: string; modelID: string }
55
55
  agent?: string
56
+ /** 投递语义(Session.Inbox.Delivery,官方枚举 steer|queue):steer=并入在途回合
57
+ * (官方 TUI 忙时 Enter 同款),queue=引擎侧排队。缺省=引擎默认。 */
58
+ delivery?: "steer" | "queue"
56
59
  }
57
60
 
58
61
  export interface PromptAndWaitOptions extends PromptOptions {
@@ -120,6 +123,17 @@ export interface OpencodeClient {
120
123
  /** 设置会话项目归属(POST /session/{id}/move;directory=绝对路径) */
121
124
  move(opts: { path: { id: string }; body: { directory: string } }): Promise<unknown>
122
125
  abort(opts: { path: { id: string } }): Promise<unknown>
126
+ /** 官方斜杠命令直通(/goal /compact /redo /btw,2026-11-23):引擎内置实现,
127
+ * POST /session/{id}/command——与桌面端同一语义(goal 审查器/轮数上限在引擎侧)。 */
128
+ command(opts: { path: { id: string }; body: { name: string; text: string } }): Promise<unknown>
129
+ /**
130
+ * 会话回滚(官方 /undo 语义,opencode.ai/docs/snapshots 为准):
131
+ * stage=在指定消息处立可逆边界(files=true 恢复边界后 assistant 改动的文件);
132
+ * commit=提交暂存回滚;delete=取消暂存。会话运行中拒绝(须先 abort)。
133
+ */
134
+ revertStage(opts: { path: { id: string }; body: { messageID: string; files?: boolean } }): Promise<unknown>
135
+ revertCommit(opts: { path: { id: string } }): Promise<unknown>
136
+ revertDiscard(opts: { path: { id: string } }): Promise<unknown>
123
137
  messages(opts: {
124
138
  path: { id: string }
125
139
  query?: { limit?: number; cursor?: string }
@@ -376,9 +390,14 @@ export function createClient(baseUrl: string): OpencodeClient {
376
390
  // DEF-20261119-P9:429 带 Retry-After 时把暗示值透出(机器可读标记),
377
391
  // 让上层退避按服务端节奏走,而非固定 20s(UAT SY-004 注入实证)。
378
392
  const retryAfter = res.status === 429 ? res.headers.get("retry-after") : null
379
- throw new Error(
393
+ const err = new Error(
380
394
  `OpenCode API ${res.status}: ${excerpt}${retryAfter ? ` [retry-after:${retryAfter}]` : ""}`,
381
395
  )
396
+ // 完整响应体挂 error.body(不截断)——错误通道的结构化状态(如 goal 的
397
+ // CommandExecutionError 审计长文)由上层按 body 解析;截断的 excerpt 仅供日志
398
+ //(真机实证 11-23:200 字截断切断长 JSON,上层状态解析失配退化成失败文案)。
399
+ ;(err as { body?: string }).body = txt
400
+ throw err
382
401
  }
383
402
  // 204 (如 /model /agent /permission reply) 无 body;res.json() 会抛错。
384
403
  if (res.status === 204) return null
@@ -416,6 +435,18 @@ export function createClient(baseUrl: string): OpencodeClient {
416
435
  async abort(opts) {
417
436
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
418
437
  },
438
+ async command(opts) {
439
+ return json(await req(`/session/${opts.path.id}/command`, { method: "POST", body: JSON.stringify(opts.body) }))
440
+ },
441
+ async revertStage(opts) {
442
+ return json(await req(`/session/${opts.path.id}/revert/stage`, { method: "POST", body: JSON.stringify(opts.body) }))
443
+ },
444
+ async revertCommit(opts) {
445
+ return json(await req(`/session/${opts.path.id}/revert/commit`, { method: "POST", body: "{}" }))
446
+ },
447
+ async revertDiscard(opts) {
448
+ return json(await req(`/session/${opts.path.id}/revert`, { method: "DELETE" }))
449
+ },
419
450
  async messages(opts) {
420
451
  const query = new URLSearchParams()
421
452
  if (opts.query?.limit !== undefined) query.set("limit", String(opts.query.limit))