@linjz/opencode-qqbot 0.3.16 → 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.
- package/README.md +303 -266
- package/README.zh-CN.md +313 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +356 -92
- package/dist/openqq-bot.js +878 -226
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +2 -2
- package/src/bridge.ts +292 -3
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +36 -10
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +7 -1
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +7 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +10 -3
- package/src/plugin-entry.ts +21 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- 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 {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
let
|
|
32
|
-
let
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
installFileLog
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
//
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
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
|
+
})
|
package/src/opencode/client.ts
CHANGED
|
@@ -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
|
-
|
|
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))
|
package/src/opencode/mirror.ts
CHANGED
|
@@ -54,16 +54,23 @@ export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
|
54
54
|
export function buildDigest(messages: SessionMessage[]): string | null {
|
|
55
55
|
const ordered = [...messages].reverse()
|
|
56
56
|
|
|
57
|
+
// A 方案第三桶(owner 2026-11-23):回合边界消息 type=synthetic = 引擎自主注入
|
|
58
|
+
// (goal 续跑/自动化)——既非 QQ 派发也非桌面输入,实证 shape(11-23 goal 会话
|
|
59
|
+
// 消息流):continuation 为 synthetic 型 user 消息。此类回合标「🎯 目标续跑摘要」,
|
|
60
|
+
// 不再冒名「桌面」。
|
|
57
61
|
let lastUserIdx = -1
|
|
62
|
+
let goalDriven = false
|
|
58
63
|
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
59
|
-
|
|
64
|
+
const t = (ordered[i] as { type?: string }).type
|
|
65
|
+
if (t === "user" || t === "synthetic") {
|
|
60
66
|
lastUserIdx = i
|
|
67
|
+
goalDriven = t === "synthetic"
|
|
61
68
|
break
|
|
62
69
|
}
|
|
63
70
|
}
|
|
64
71
|
if (lastUserIdx < 0) return null
|
|
65
72
|
|
|
66
|
-
const userText = ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
|
|
73
|
+
const userText = goalDriven ? "" : ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
|
|
67
74
|
|
|
68
75
|
let answer = ""
|
|
69
76
|
for (let i = ordered.length - 1; i > lastUserIdx; i--) {
|
|
@@ -77,7 +84,7 @@ export function buildDigest(messages: SessionMessage[]): string | null {
|
|
|
77
84
|
}
|
|
78
85
|
if (!answer) return null
|
|
79
86
|
|
|
80
|
-
const lines = ["📋 桌面问答摘要"]
|
|
87
|
+
const lines = [goalDriven ? "🎯 目标续跑摘要" : "📋 桌面问答摘要"]
|
|
81
88
|
if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
|
|
82
89
|
const clipLimit = answerClipLimit()
|
|
83
90
|
if (clipLimit > 0) {
|