@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.
- package/README.md +74 -39
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +10 -1
- package/dist/openqq-bot.js +365 -70
- package/package.json +69 -61
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +936 -796
- package/src/commands.ts +554 -514
- package/src/config.ts +121 -121
- package/src/core/bot-launcher.ts +146 -134
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +284 -284
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -0
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +304 -304
- package/src/core/inflight-journal.ts +217 -151
- package/src/core/instance-lock.ts +122 -122
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +80 -0
- package/src/core/mirror.ts +173 -173
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +387 -386
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +65 -65
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +539 -539
- package/src/qq/gateway.ts +492 -492
- package/src/qq/media.ts +219 -204
- package/src/qq/sender.ts +300 -300
- package/src/qq/types.ts +154 -152
- package/tsconfig.json +24 -24
package/src/opencode/client.ts
CHANGED
|
@@ -1,386 +1,387 @@
|
|
|
1
|
-
// V2-compatible OpenCode client (fetch-based).
|
|
2
|
-
// The bundled V1 @opencode-ai/sdk is incompatible with the V2 server API:
|
|
3
|
-
// - its client-side payload validation rejects session.create({}) before the
|
|
4
|
-
// request is even sent, and
|
|
5
|
-
// - its SSE event model differs from V2.
|
|
6
|
-
// So we talk to the V2 REST API directly instead. Endpoint contract (base = .../api):
|
|
7
|
-
// POST /session -> { data: { id } }
|
|
8
|
-
// GET /session -> { data: [...] }
|
|
9
|
-
// POST /session/{id}/prompt {text} -> { data: { time.created } }
|
|
10
|
-
// (v2 body additionalProperties:false —— model/agent 字段会被 zod 静默剥离,
|
|
11
|
-
// 模型/agent 是 session 级设置,见下面 /model /agent 端点)
|
|
12
|
-
// GET /session/{id}/message -> { data: [...] }
|
|
13
|
-
// POST /session/{id}/interrupt (v2: /abort 不存在,返回 404)
|
|
14
|
-
// POST /session/{id}/model {model:{providerID,id}} -> 204 (session 级切模型)
|
|
15
|
-
// POST /session/{id}/agent {agent} -> 204 (session 级切 agent)
|
|
16
|
-
// GET /permission/request -> { data: PermissionRequest[] } (全局待审批)
|
|
17
|
-
// POST /session/{id}/permission/{requestID}/reply {decision} -> 204
|
|
18
|
-
// GET /agent -> { data: [...] }
|
|
19
|
-
// GET /model -> { data: [ { providerID, modelID } ] } (flat)
|
|
20
|
-
export type PermissionDecision = "once" | "always" | "reject"
|
|
21
|
-
|
|
22
|
-
// L 项(2026-10-30):V2 Form(选择表单)类型——P0 实证 openapi Form.* schema。
|
|
23
|
-
// MultiselectField/StringField.options 即 "A/B/C/D 选择弹窗"的选项模型。
|
|
24
|
-
export interface FormOption {
|
|
25
|
-
value: string
|
|
26
|
-
label: string
|
|
27
|
-
description?: string
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export type FormField =
|
|
31
|
-
| { key: string; type: "string"; title?: string; description?: string; required?: boolean; options?: FormOption[]; placeholder?: string }
|
|
32
|
-
| { key: string; type: "number" | "integer"; title?: string; description?: string; required?: boolean; minimum?: number; maximum?: number }
|
|
33
|
-
| { key: string; type: "boolean"; title?: string; description?: string; required?: boolean }
|
|
34
|
-
| { key: string; type: "multiselect"; title?: string; description?: string; required?: boolean; options: FormOption[]; minItems?: number; maxItems?: number; custom?: boolean }
|
|
35
|
-
| { key: string; type: string; title?: string; description?: string; required?: boolean }
|
|
36
|
-
|
|
37
|
-
export interface FormInfo {
|
|
38
|
-
id: string
|
|
39
|
-
sessionID: string
|
|
40
|
-
title: string
|
|
41
|
-
fields: FormField[]
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export interface PermissionRequest {
|
|
45
|
-
id: string
|
|
46
|
-
sessionID: string
|
|
47
|
-
action: string
|
|
48
|
-
resources: string[]
|
|
49
|
-
save?: string[]
|
|
50
|
-
message?: string
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface PromptOptions {
|
|
54
|
-
model?: { providerID: string; modelID: string }
|
|
55
|
-
agent?: string
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export interface PromptAndWaitOptions extends PromptOptions {
|
|
59
|
-
// 原生附件(2026-10-14):prompt body 的 files(v2 PromptInput schema 内
|
|
60
|
-
// 字段,additionalProperties:false 不会剥它;model/agent 才会被剥)
|
|
61
|
-
files?: Array<{ uri: string; name?: string }>
|
|
62
|
-
// 轮询中发现待审批权限时调用;返回用户的审批决策后,promptAndWait 负责
|
|
63
|
-
// POST reply 并继续等待 idle。审批等待时间不计入 5 分钟超时。
|
|
64
|
-
onPermission?: (req: PermissionRequest) => Promise<PermissionDecision>
|
|
65
|
-
// reply POST 成功后回调(确认消息在服务端受理后再发,避免误导)
|
|
66
|
-
onPermissionReplied?: (decision: PermissionDecision) => void
|
|
67
|
-
// reply 404 = 请求已在其他端(桌面)被处理:不致命,任务继续,仅需提示
|
|
68
|
-
onPermissionConflict?: () => void
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export interface MessagePart {
|
|
72
|
-
type: string
|
|
73
|
-
text?: string
|
|
74
|
-
tool?: string
|
|
75
|
-
state?: unknown
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export interface SessionMessage {
|
|
79
|
-
type?: string
|
|
80
|
-
time?: { created?: number; completed?: number }
|
|
81
|
-
content?: MessagePart[]
|
|
82
|
-
finish?: string
|
|
83
|
-
text?: string
|
|
84
|
-
model?: { id?: string; providerID?: string }
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export interface OpencodeClient {
|
|
88
|
-
baseUrl: string
|
|
89
|
-
// HC2(2026-10-26):运行中热换基(端口漂移自愈)。原地改闭包 base,
|
|
90
|
-
// 引用不变——sessions/bridge 等持有方零感知。
|
|
91
|
-
rebase(url: string): void
|
|
92
|
-
session: {
|
|
93
|
-
create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
|
|
94
|
-
list(): Promise<{ data?: unknown[] }>
|
|
95
|
-
abort(opts: { path: { id: string } }): Promise<unknown>
|
|
96
|
-
messages(opts: { path: { id: string } }): Promise<{ data?: SessionMessage[] }>
|
|
97
|
-
prompt(opts: { path: { id: string }; body: { text: string } & PromptOptions }): Promise<{ data?: { time?: { created?: number } } }>
|
|
98
|
-
setModel(opts: { path: { id: string }; body: { model: { providerID: string; id: string } } }): Promise<unknown>
|
|
99
|
-
setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
|
|
100
|
-
}
|
|
101
|
-
permission: {
|
|
102
|
-
list(): Promise<{ data?: PermissionRequest[] }>
|
|
103
|
-
reply(opts: { path: { sessionID: string; requestID: string }; body: { decision: PermissionDecision } }): Promise<unknown>
|
|
104
|
-
}
|
|
105
|
-
// L 项(2026-10-30):V2 Form API——按会话列表(实测 GET /api/form 是 location 维度,
|
|
106
|
-
// bot 进程 cwd 与会话项目不一致会漏;会话级列表才可靠)+ 作答
|
|
107
|
-
form: {
|
|
108
|
-
list(input: { sessionID: string }): Promise<{ data?: FormInfo[] }>
|
|
109
|
-
reply(opts: { path: { sessionID: string; formID: string }; body: { answer: Record<string, unknown> } }): Promise<unknown>
|
|
110
|
-
}
|
|
111
|
-
app: {
|
|
112
|
-
agents(): Promise<{ data?: unknown[] }>
|
|
113
|
-
}
|
|
114
|
-
config: {
|
|
115
|
-
providers(): Promise<{ data?: unknown[] }>
|
|
116
|
-
}
|
|
117
|
-
// Send a prompt and poll until the assistant reply for THIS prompt is done.
|
|
118
|
-
promptAndWait(sessionId: string, text: string, options?: PromptAndWaitOptions): Promise<string>
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// 回合超时:原 5 分钟与 QQ 被动回复窗口绑定,但真实长任务(写码+多轮工具)
|
|
122
|
-
// 常超 5 分钟——超时后答案永久丢失(实测 2026-10-13)。最终回复现已有主动
|
|
123
|
-
// 消息兜底(bridge.deliver 被动失败→主动),已解耦。默认 30 分钟,
|
|
124
|
-
// 可用 env OPENCODE_TURN_TIMEOUT_MINUTES 覆盖。
|
|
125
|
-
const TURN_TIMEOUT_MINUTES = (() => {
|
|
126
|
-
const n = Number(process.env.OPENCODE_TURN_TIMEOUT_MINUTES ?? "30")
|
|
127
|
-
return Number.isFinite(n) && n > 0 ? n : 30
|
|
128
|
-
})()
|
|
129
|
-
const RESPONSE_TIMEOUT_MS = TURN_TIMEOUT_MINUTES * 60 * 1000
|
|
130
|
-
|
|
131
|
-
// 聚合某轮(baseline 之后)所有 assistant 消息的文本部件,丢弃 reasoning/tool 部件。
|
|
132
|
-
// promptAndWait 与 bridge 的后台等待共用(后台等待 = 前台超时后不放弃,完成即回传)。
|
|
133
|
-
export function collectReplyText(msgs: SessionMessage[], baseline: number): string {
|
|
134
|
-
return msgs
|
|
135
|
-
.filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline)
|
|
136
|
-
.flatMap((x) => (x.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? ""))
|
|
137
|
-
.join("\n")
|
|
138
|
-
.trim()
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
let client: OpencodeClient | null = null
|
|
142
|
-
|
|
143
|
-
function sleep(ms: number): Promise<void> {
|
|
144
|
-
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export function createClient(baseUrl: string): OpencodeClient {
|
|
148
|
-
// HC2:let 而非 const —— rebase 热换基需要
|
|
149
|
-
let base = baseUrl.replace(/\/+$/, "")
|
|
150
|
-
const password = process.env.OPENCODE_PASSWORD
|
|
151
|
-
const authHeaders: Record<string, string> = { "Content-Type": "application/json" }
|
|
152
|
-
if (password) {
|
|
153
|
-
// V2 desktop API is protected by Basic Auth (opencode:<service.json password>).
|
|
154
|
-
// fetch() forbids credentials in the URL, so inject via the Authorization header.
|
|
155
|
-
authHeaders.Authorization = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
async function req(path: string, init?: RequestInit): Promise<Response> {
|
|
159
|
-
return fetch(base + path, {
|
|
160
|
-
...init,
|
|
161
|
-
headers: { ...authHeaders, ...((init?.headers as Record<string, string>) ?? {}) },
|
|
162
|
-
})
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async function json(res: Response): Promise<any> {
|
|
166
|
-
if (!res.ok) {
|
|
167
|
-
const txt = await res.text().catch(() => "")
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
base
|
|
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
|
-
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
const
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
if (!
|
|
260
|
-
byProvider.
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
childLinkCache.
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
//
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
//
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
if (r.
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
//
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
//
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
//
|
|
355
|
-
//
|
|
356
|
-
//
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
//
|
|
361
|
-
//
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
}
|
|
1
|
+
// V2-compatible OpenCode client (fetch-based).
|
|
2
|
+
// The bundled V1 @opencode-ai/sdk is incompatible with the V2 server API:
|
|
3
|
+
// - its client-side payload validation rejects session.create({}) before the
|
|
4
|
+
// request is even sent, and
|
|
5
|
+
// - its SSE event model differs from V2.
|
|
6
|
+
// So we talk to the V2 REST API directly instead. Endpoint contract (base = .../api):
|
|
7
|
+
// POST /session -> { data: { id } }
|
|
8
|
+
// GET /session -> { data: [...] }
|
|
9
|
+
// POST /session/{id}/prompt {text} -> { data: { time.created } }
|
|
10
|
+
// (v2 body additionalProperties:false —— model/agent 字段会被 zod 静默剥离,
|
|
11
|
+
// 模型/agent 是 session 级设置,见下面 /model /agent 端点)
|
|
12
|
+
// GET /session/{id}/message -> { data: [...] }
|
|
13
|
+
// POST /session/{id}/interrupt (v2: /abort 不存在,返回 404)
|
|
14
|
+
// POST /session/{id}/model {model:{providerID,id}} -> 204 (session 级切模型)
|
|
15
|
+
// POST /session/{id}/agent {agent} -> 204 (session 级切 agent)
|
|
16
|
+
// GET /permission/request -> { data: PermissionRequest[] } (全局待审批)
|
|
17
|
+
// POST /session/{id}/permission/{requestID}/reply {decision} -> 204
|
|
18
|
+
// GET /agent -> { data: [...] }
|
|
19
|
+
// GET /model -> { data: [ { providerID, modelID } ] } (flat)
|
|
20
|
+
export type PermissionDecision = "once" | "always" | "reject"
|
|
21
|
+
|
|
22
|
+
// L 项(2026-10-30):V2 Form(选择表单)类型——P0 实证 openapi Form.* schema。
|
|
23
|
+
// MultiselectField/StringField.options 即 "A/B/C/D 选择弹窗"的选项模型。
|
|
24
|
+
export interface FormOption {
|
|
25
|
+
value: string
|
|
26
|
+
label: string
|
|
27
|
+
description?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type FormField =
|
|
31
|
+
| { key: string; type: "string"; title?: string; description?: string; required?: boolean; options?: FormOption[]; placeholder?: string }
|
|
32
|
+
| { key: string; type: "number" | "integer"; title?: string; description?: string; required?: boolean; minimum?: number; maximum?: number }
|
|
33
|
+
| { key: string; type: "boolean"; title?: string; description?: string; required?: boolean }
|
|
34
|
+
| { key: string; type: "multiselect"; title?: string; description?: string; required?: boolean; options: FormOption[]; minItems?: number; maxItems?: number; custom?: boolean }
|
|
35
|
+
| { key: string; type: string; title?: string; description?: string; required?: boolean }
|
|
36
|
+
|
|
37
|
+
export interface FormInfo {
|
|
38
|
+
id: string
|
|
39
|
+
sessionID: string
|
|
40
|
+
title: string
|
|
41
|
+
fields: FormField[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PermissionRequest {
|
|
45
|
+
id: string
|
|
46
|
+
sessionID: string
|
|
47
|
+
action: string
|
|
48
|
+
resources: string[]
|
|
49
|
+
save?: string[]
|
|
50
|
+
message?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface PromptOptions {
|
|
54
|
+
model?: { providerID: string; modelID: string }
|
|
55
|
+
agent?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface PromptAndWaitOptions extends PromptOptions {
|
|
59
|
+
// 原生附件(2026-10-14):prompt body 的 files(v2 PromptInput schema 内
|
|
60
|
+
// 字段,additionalProperties:false 不会剥它;model/agent 才会被剥)
|
|
61
|
+
files?: Array<{ uri: string; name?: string }>
|
|
62
|
+
// 轮询中发现待审批权限时调用;返回用户的审批决策后,promptAndWait 负责
|
|
63
|
+
// POST reply 并继续等待 idle。审批等待时间不计入 5 分钟超时。
|
|
64
|
+
onPermission?: (req: PermissionRequest) => Promise<PermissionDecision>
|
|
65
|
+
// reply POST 成功后回调(确认消息在服务端受理后再发,避免误导)
|
|
66
|
+
onPermissionReplied?: (decision: PermissionDecision) => void
|
|
67
|
+
// reply 404 = 请求已在其他端(桌面)被处理:不致命,任务继续,仅需提示
|
|
68
|
+
onPermissionConflict?: () => void
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface MessagePart {
|
|
72
|
+
type: string
|
|
73
|
+
text?: string
|
|
74
|
+
tool?: string
|
|
75
|
+
state?: unknown
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface SessionMessage {
|
|
79
|
+
type?: string
|
|
80
|
+
time?: { created?: number; completed?: number }
|
|
81
|
+
content?: MessagePart[]
|
|
82
|
+
finish?: string
|
|
83
|
+
text?: string
|
|
84
|
+
model?: { id?: string; providerID?: string }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface OpencodeClient {
|
|
88
|
+
baseUrl: string
|
|
89
|
+
// HC2(2026-10-26):运行中热换基(端口漂移自愈)。原地改闭包 base,
|
|
90
|
+
// 引用不变——sessions/bridge 等持有方零感知。
|
|
91
|
+
rebase(url: string): void
|
|
92
|
+
session: {
|
|
93
|
+
create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
|
|
94
|
+
list(): Promise<{ data?: unknown[] }>
|
|
95
|
+
abort(opts: { path: { id: string } }): Promise<unknown>
|
|
96
|
+
messages(opts: { path: { id: string } }): Promise<{ data?: SessionMessage[] }>
|
|
97
|
+
prompt(opts: { path: { id: string }; body: { text: string } & PromptOptions }): Promise<{ data?: { time?: { created?: number } } }>
|
|
98
|
+
setModel(opts: { path: { id: string }; body: { model: { providerID: string; id: string } } }): Promise<unknown>
|
|
99
|
+
setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
|
|
100
|
+
}
|
|
101
|
+
permission: {
|
|
102
|
+
list(): Promise<{ data?: PermissionRequest[] }>
|
|
103
|
+
reply(opts: { path: { sessionID: string; requestID: string }; body: { decision: PermissionDecision } }): Promise<unknown>
|
|
104
|
+
}
|
|
105
|
+
// L 项(2026-10-30):V2 Form API——按会话列表(实测 GET /api/form 是 location 维度,
|
|
106
|
+
// bot 进程 cwd 与会话项目不一致会漏;会话级列表才可靠)+ 作答
|
|
107
|
+
form: {
|
|
108
|
+
list(input: { sessionID: string }): Promise<{ data?: FormInfo[] }>
|
|
109
|
+
reply(opts: { path: { sessionID: string; formID: string }; body: { answer: Record<string, unknown> } }): Promise<unknown>
|
|
110
|
+
}
|
|
111
|
+
app: {
|
|
112
|
+
agents(): Promise<{ data?: unknown[] }>
|
|
113
|
+
}
|
|
114
|
+
config: {
|
|
115
|
+
providers(): Promise<{ data?: unknown[] }>
|
|
116
|
+
}
|
|
117
|
+
// Send a prompt and poll until the assistant reply for THIS prompt is done.
|
|
118
|
+
promptAndWait(sessionId: string, text: string, options?: PromptAndWaitOptions): Promise<string>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// 回合超时:原 5 分钟与 QQ 被动回复窗口绑定,但真实长任务(写码+多轮工具)
|
|
122
|
+
// 常超 5 分钟——超时后答案永久丢失(实测 2026-10-13)。最终回复现已有主动
|
|
123
|
+
// 消息兜底(bridge.deliver 被动失败→主动),已解耦。默认 30 分钟,
|
|
124
|
+
// 可用 env OPENCODE_TURN_TIMEOUT_MINUTES 覆盖。
|
|
125
|
+
const TURN_TIMEOUT_MINUTES = (() => {
|
|
126
|
+
const n = Number(process.env.OPENCODE_TURN_TIMEOUT_MINUTES ?? "30")
|
|
127
|
+
return Number.isFinite(n) && n > 0 ? n : 30
|
|
128
|
+
})()
|
|
129
|
+
const RESPONSE_TIMEOUT_MS = TURN_TIMEOUT_MINUTES * 60 * 1000
|
|
130
|
+
|
|
131
|
+
// 聚合某轮(baseline 之后)所有 assistant 消息的文本部件,丢弃 reasoning/tool 部件。
|
|
132
|
+
// promptAndWait 与 bridge 的后台等待共用(后台等待 = 前台超时后不放弃,完成即回传)。
|
|
133
|
+
export function collectReplyText(msgs: SessionMessage[], baseline: number): string {
|
|
134
|
+
return msgs
|
|
135
|
+
.filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline)
|
|
136
|
+
.flatMap((x) => (x.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? ""))
|
|
137
|
+
.join("\n")
|
|
138
|
+
.trim()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let client: OpencodeClient | null = null
|
|
142
|
+
|
|
143
|
+
function sleep(ms: number): Promise<void> {
|
|
144
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function createClient(baseUrl: string): OpencodeClient {
|
|
148
|
+
// HC2:let 而非 const —— rebase 热换基需要
|
|
149
|
+
let base = baseUrl.replace(/\/+$/, "")
|
|
150
|
+
const password = process.env.OPENCODE_PASSWORD
|
|
151
|
+
const authHeaders: Record<string, string> = { "Content-Type": "application/json" }
|
|
152
|
+
if (password) {
|
|
153
|
+
// V2 desktop API is protected by Basic Auth (opencode:<service.json password>).
|
|
154
|
+
// fetch() forbids credentials in the URL, so inject via the Authorization header.
|
|
155
|
+
authHeaders.Authorization = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function req(path: string, init?: RequestInit): Promise<Response> {
|
|
159
|
+
return fetch(base + path, {
|
|
160
|
+
...init,
|
|
161
|
+
headers: { ...authHeaders, ...((init?.headers as Record<string, string>) ?? {}) },
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function json(res: Response): Promise<any> {
|
|
166
|
+
if (!res.ok) {
|
|
167
|
+
const txt = await res.text().catch(() => "")
|
|
168
|
+
const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt
|
|
169
|
+
throw new Error(`OpenCode API ${res.status}: ${excerpt}`)
|
|
170
|
+
}
|
|
171
|
+
// 204 (如 /model /agent /permission reply) 无 body;res.json() 会抛错。
|
|
172
|
+
if (res.status === 204) return null
|
|
173
|
+
const txt = await res.text()
|
|
174
|
+
if (!txt.trim()) return null
|
|
175
|
+
return JSON.parse(txt)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const oc: OpencodeClient = {
|
|
179
|
+
get baseUrl() {
|
|
180
|
+
return base
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
rebase(nextUrl: string) {
|
|
184
|
+
const next = nextUrl.replace(/\/+$/, "")
|
|
185
|
+
if (next !== base) {
|
|
186
|
+
console.log(`[opencode] 热换基:${base} → ${next}`)
|
|
187
|
+
base = next
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
session: {
|
|
192
|
+
async create(body = {}) {
|
|
193
|
+
return json(await req("/session", { method: "POST", body: JSON.stringify(body) }))
|
|
194
|
+
},
|
|
195
|
+
async list() {
|
|
196
|
+
return json(await req("/session"))
|
|
197
|
+
},
|
|
198
|
+
async abort(opts) {
|
|
199
|
+
return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
|
|
200
|
+
},
|
|
201
|
+
async messages(opts) {
|
|
202
|
+
return json(await req(`/session/${opts.path.id}/message`))
|
|
203
|
+
},
|
|
204
|
+
async prompt(opts) {
|
|
205
|
+
return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }))
|
|
206
|
+
},
|
|
207
|
+
async setModel(opts) {
|
|
208
|
+
return json(await req(`/session/${opts.path.id}/model`, { method: "POST", body: JSON.stringify(opts.body) }))
|
|
209
|
+
},
|
|
210
|
+
async setAgent(opts) {
|
|
211
|
+
return json(await req(`/session/${opts.path.id}/agent`, { method: "POST", body: JSON.stringify(opts.body) }))
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
|
|
215
|
+
permission: {
|
|
216
|
+
async list() {
|
|
217
|
+
return json(await req("/permission/request"))
|
|
218
|
+
},
|
|
219
|
+
async reply(opts) {
|
|
220
|
+
return json(
|
|
221
|
+
await req(`/session/${opts.path.sessionID}/permission/${opts.path.requestID}/reply`, {
|
|
222
|
+
method: "POST",
|
|
223
|
+
body: JSON.stringify(opts.body),
|
|
224
|
+
}),
|
|
225
|
+
)
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
form: {
|
|
230
|
+
async list(input) {
|
|
231
|
+
return json(await req(`/session/${input.sessionID}/form`))
|
|
232
|
+
},
|
|
233
|
+
async reply(opts) {
|
|
234
|
+
return json(
|
|
235
|
+
await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}/reply`, {
|
|
236
|
+
method: "POST",
|
|
237
|
+
body: JSON.stringify(opts.body),
|
|
238
|
+
}),
|
|
239
|
+
)
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
|
|
243
|
+
app: {
|
|
244
|
+
async agents() {
|
|
245
|
+
return json(await req("/agent"))
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
config: {
|
|
250
|
+
async providers() {
|
|
251
|
+
// V2 exposes a flat model list at GET /model. Group by provider to match
|
|
252
|
+
// the shape the /model command expects: { data: [ { id, models: [ { id } ] } ] }.
|
|
253
|
+
const res = await json(await req("/model"))
|
|
254
|
+
const models = (res?.data ?? []) as Array<{ providerID?: string; modelID?: string; id?: string }>
|
|
255
|
+
const byProvider = new Map<string, { id: string; models: { id: string }[] }>()
|
|
256
|
+
for (const m of models) {
|
|
257
|
+
const pid = m.providerID
|
|
258
|
+
const mid = m.modelID ?? m.id
|
|
259
|
+
if (!pid || !mid) continue
|
|
260
|
+
if (!byProvider.has(pid)) byProvider.set(pid, { id: pid, models: [] })
|
|
261
|
+
byProvider.get(pid)!.models.push({ id: mid })
|
|
262
|
+
}
|
|
263
|
+
return { data: [...byProvider.values()] }
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
async promptAndWait(sessionId, text, options) {
|
|
268
|
+
// v2: prompt body 只接受 {text,...}(additionalProperties:false),model/agent
|
|
269
|
+
// 会被静默剥离 —— 不再往 body 里塞;模型/agent 由 SessionManager 走 session 级端点。
|
|
270
|
+
const body: { text: string; files?: Array<{ uri: string; name?: string }> } = { text }
|
|
271
|
+
if (options?.files?.length) body.files = options.files
|
|
272
|
+
|
|
273
|
+
// 债务D1:子会话(subagent)审批检测——session 详情带 parentID
|
|
274
|
+
//(2026-10-13 探针实证:task 工具的子会话 parentID 精确指向主会话)。
|
|
275
|
+
// 只做父链精确匹配,不做全局猜测;parentID 永不变,负缓存安全。
|
|
276
|
+
const childLinkCache = new Map<string, boolean>()
|
|
277
|
+
async function isChildSession(childId: string, parentId: string): Promise<boolean> {
|
|
278
|
+
const key = `${parentId}->${childId}`
|
|
279
|
+
const cached = childLinkCache.get(key)
|
|
280
|
+
if (cached !== undefined) return cached
|
|
281
|
+
let result = false
|
|
282
|
+
try {
|
|
283
|
+
const detail = await json(await req(`/session/${childId}`))
|
|
284
|
+
result = detail?.data?.parentID === parentId
|
|
285
|
+
} catch {
|
|
286
|
+
result = false
|
|
287
|
+
}
|
|
288
|
+
if (childLinkCache.size > 500) childLinkCache.clear()
|
|
289
|
+
childLinkCache.set(key, result)
|
|
290
|
+
return result
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// The prompt call returns as soon as the user message is created (~ms);
|
|
294
|
+
// the assistant reply streams in over the next few seconds.
|
|
295
|
+
const promptJson = await json(
|
|
296
|
+
await req(`/session/${sessionId}/prompt`, { method: "POST", body: JSON.stringify(body) }),
|
|
297
|
+
)
|
|
298
|
+
// Only accept assistant messages created at/after this prompt, so a prior
|
|
299
|
+
// turn's completed reply is never mistaken for this turn's answer.
|
|
300
|
+
const baseline = promptJson?.data?.time?.created ?? 0
|
|
301
|
+
|
|
302
|
+
const deadline = Date.now() + RESPONSE_TIMEOUT_MS
|
|
303
|
+
let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
|
|
304
|
+
const handledPermissions = new Set<string>()
|
|
305
|
+
|
|
306
|
+
while (Date.now() - permissionWaitMs < deadline) {
|
|
307
|
+
await sleep(1000)
|
|
308
|
+
|
|
309
|
+
// 审批检测:会话阻塞在权限请求上时不会产生 idle,必须先放行。
|
|
310
|
+
if (options?.onPermission) {
|
|
311
|
+
try {
|
|
312
|
+
const permJson = await json(await req("/permission/request"))
|
|
313
|
+
const all = (permJson?.data ?? []) as PermissionRequest[]
|
|
314
|
+
// 债务D1:主会话请求 + 子会话(subagent,parentID 指向本会话)请求
|
|
315
|
+
const pending: PermissionRequest[] = []
|
|
316
|
+
for (const r of all) {
|
|
317
|
+
if (handledPermissions.has(r.id)) continue
|
|
318
|
+
if (r.sessionID === sessionId) {
|
|
319
|
+
pending.push(r)
|
|
320
|
+
continue
|
|
321
|
+
}
|
|
322
|
+
if (await isChildSession(r.sessionID, sessionId)) pending.push(r)
|
|
323
|
+
}
|
|
324
|
+
if (pending.length > 0) {
|
|
325
|
+
const request = pending[0]
|
|
326
|
+
handledPermissions.add(request.id)
|
|
327
|
+
const waitStart = Date.now()
|
|
328
|
+
const decision = await options.onPermission(request)
|
|
329
|
+
permissionWaitMs += Date.now() - waitStart
|
|
330
|
+
// reply 用请求自带的 sessionID(与轮询会话 id 在同会话时相同,
|
|
331
|
+
// 但若请求来自子会话则必须用请求的归属会话,否则 404)。
|
|
332
|
+
const replyRes = await req(`/session/${request.sessionID}/permission/${request.id}/reply`, {
|
|
333
|
+
method: "POST",
|
|
334
|
+
body: JSON.stringify({ decision }),
|
|
335
|
+
})
|
|
336
|
+
if (replyRes.status === 404) {
|
|
337
|
+
// 债务D2:请求已被其他端(桌面)先处理——不是错误,任务继续
|
|
338
|
+
options?.onPermissionConflict?.()
|
|
339
|
+
} else {
|
|
340
|
+
await json(replyRes)
|
|
341
|
+
options?.onPermissionReplied?.(decision)
|
|
342
|
+
}
|
|
343
|
+
continue // 决策已提交,重新进入轮询
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
// 审批链路故障不能杀死本轮对话。请求在回调前已标记 handled:
|
|
347
|
+
// 不会重复推送 QQ,但 reply 失败时会留到 5 分钟超时暴露问题。
|
|
348
|
+
console.error("[opencode] 权限审批轮询失败:", error)
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const listJson = await json(await req(`/session/${sessionId}/message`))
|
|
353
|
+
const msgs: SessionMessage[] = listJson?.data ?? []
|
|
354
|
+
// Completion = the idle marker created at/after this prompt. This is the
|
|
355
|
+
// only reliable "whole turn done" signal: tool-using turns emit several
|
|
356
|
+
// assistant messages (reasoning+tool) before the final text one, so
|
|
357
|
+
// "first completed assistant" would return an empty tool message.
|
|
358
|
+
const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
|
|
359
|
+
if (idle) {
|
|
360
|
+
// Aggregate text parts from ALL assistant messages of this turn,
|
|
361
|
+
// dropping reasoning/tool parts. In practice only the final assistant
|
|
362
|
+
// carries text; earlier ones are reasoning+tool.
|
|
363
|
+
const reply = collectReplyText(msgs, baseline)
|
|
364
|
+
return reply || "(AI 未返回内容)"
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`)
|
|
368
|
+
},
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
client = oc
|
|
372
|
+
return oc
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function getClient(): OpencodeClient {
|
|
376
|
+
if (!client) throw new Error("OpenCode client not initialized")
|
|
377
|
+
return client
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export async function healthCheck(oc: OpencodeClient, quiet = false): Promise<void> {
|
|
381
|
+
try {
|
|
382
|
+
await oc.session.list()
|
|
383
|
+
if (!quiet) console.log("[opencode] 连接正常")
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw new Error(`OpenCode 连接失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
386
|
+
}
|
|
387
|
+
}
|