@linjz/opencode-qqbot 0.3.5 → 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 -39
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +360 -69
  6. package/package.json +69 -61
  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
@@ -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
- throw new Error(`OpenCode API ${res.status}: ${txt.substring(0, 200)}`)
169
- }
170
- // 204 (如 /model /agent /permission reply) 无 body;res.json() 会抛错。
171
- if (res.status === 204) return null
172
- const txt = await res.text()
173
- if (!txt.trim()) return null
174
- return JSON.parse(txt)
175
- }
176
-
177
- const oc: OpencodeClient = {
178
- get baseUrl() {
179
- return base
180
- },
181
-
182
- rebase(nextUrl: string) {
183
- const next = nextUrl.replace(/\/+$/, "")
184
- if (next !== base) {
185
- console.log(`[opencode] 热换基:${base} → ${next}`)
186
- base = next
187
- }
188
- },
189
-
190
- session: {
191
- async create(body = {}) {
192
- return json(await req("/session", { method: "POST", body: JSON.stringify(body) }))
193
- },
194
- async list() {
195
- return json(await req("/session"))
196
- },
197
- async abort(opts) {
198
- return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
199
- },
200
- async messages(opts) {
201
- return json(await req(`/session/${opts.path.id}/message`))
202
- },
203
- async prompt(opts) {
204
- return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }))
205
- },
206
- async setModel(opts) {
207
- return json(await req(`/session/${opts.path.id}/model`, { method: "POST", body: JSON.stringify(opts.body) }))
208
- },
209
- async setAgent(opts) {
210
- return json(await req(`/session/${opts.path.id}/agent`, { method: "POST", body: JSON.stringify(opts.body) }))
211
- },
212
- },
213
-
214
- permission: {
215
- async list() {
216
- return json(await req("/permission/request"))
217
- },
218
- async reply(opts) {
219
- return json(
220
- await req(`/session/${opts.path.sessionID}/permission/${opts.path.requestID}/reply`, {
221
- method: "POST",
222
- body: JSON.stringify(opts.body),
223
- }),
224
- )
225
- },
226
- },
227
-
228
- form: {
229
- async list(input) {
230
- return json(await req(`/session/${input.sessionID}/form`))
231
- },
232
- async reply(opts) {
233
- return json(
234
- await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}/reply`, {
235
- method: "POST",
236
- body: JSON.stringify(opts.body),
237
- }),
238
- )
239
- },
240
- },
241
-
242
- app: {
243
- async agents() {
244
- return json(await req("/agent"))
245
- },
246
- },
247
-
248
- config: {
249
- async providers() {
250
- // V2 exposes a flat model list at GET /model. Group by provider to match
251
- // the shape the /model command expects: { data: [ { id, models: [ { id } ] } ] }.
252
- const res = await json(await req("/model"))
253
- const models = (res?.data ?? []) as Array<{ providerID?: string; modelID?: string; id?: string }>
254
- const byProvider = new Map<string, { id: string; models: { id: string }[] }>()
255
- for (const m of models) {
256
- const pid = m.providerID
257
- const mid = m.modelID ?? m.id
258
- if (!pid || !mid) continue
259
- if (!byProvider.has(pid)) byProvider.set(pid, { id: pid, models: [] })
260
- byProvider.get(pid)!.models.push({ id: mid })
261
- }
262
- return { data: [...byProvider.values()] }
263
- },
264
- },
265
-
266
- async promptAndWait(sessionId, text, options) {
267
- // v2: prompt body 只接受 {text,...}(additionalProperties:false),model/agent
268
- // 会被静默剥离 —— 不再往 body 里塞;模型/agent 由 SessionManager 走 session 级端点。
269
- const body: { text: string; files?: Array<{ uri: string; name?: string }> } = { text }
270
- if (options?.files?.length) body.files = options.files
271
-
272
- // 债务D1:子会话(subagent)审批检测——session 详情带 parentID
273
- //(2026-10-13 探针实证:task 工具的子会话 parentID 精确指向主会话)。
274
- // 只做父链精确匹配,不做全局猜测;parentID 永不变,负缓存安全。
275
- const childLinkCache = new Map<string, boolean>()
276
- async function isChildSession(childId: string, parentId: string): Promise<boolean> {
277
- const key = `${parentId}->${childId}`
278
- const cached = childLinkCache.get(key)
279
- if (cached !== undefined) return cached
280
- let result = false
281
- try {
282
- const detail = await json(await req(`/session/${childId}`))
283
- result = detail?.data?.parentID === parentId
284
- } catch {
285
- result = false
286
- }
287
- if (childLinkCache.size > 500) childLinkCache.clear()
288
- childLinkCache.set(key, result)
289
- return result
290
- }
291
-
292
- // The prompt call returns as soon as the user message is created (~ms);
293
- // the assistant reply streams in over the next few seconds.
294
- const promptJson = await json(
295
- await req(`/session/${sessionId}/prompt`, { method: "POST", body: JSON.stringify(body) }),
296
- )
297
- // Only accept assistant messages created at/after this prompt, so a prior
298
- // turn's completed reply is never mistaken for this turn's answer.
299
- const baseline = promptJson?.data?.time?.created ?? 0
300
-
301
- const deadline = Date.now() + RESPONSE_TIMEOUT_MS
302
- let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
303
- const handledPermissions = new Set<string>()
304
-
305
- while (Date.now() - permissionWaitMs < deadline) {
306
- await sleep(1000)
307
-
308
- // 审批检测:会话阻塞在权限请求上时不会产生 idle,必须先放行。
309
- if (options?.onPermission) {
310
- try {
311
- const permJson = await json(await req("/permission/request"))
312
- const all = (permJson?.data ?? []) as PermissionRequest[]
313
- // 债务D1:主会话请求 + 子会话(subagent,parentID 指向本会话)请求
314
- const pending: PermissionRequest[] = []
315
- for (const r of all) {
316
- if (handledPermissions.has(r.id)) continue
317
- if (r.sessionID === sessionId) {
318
- pending.push(r)
319
- continue
320
- }
321
- if (await isChildSession(r.sessionID, sessionId)) pending.push(r)
322
- }
323
- if (pending.length > 0) {
324
- const request = pending[0]
325
- handledPermissions.add(request.id)
326
- const waitStart = Date.now()
327
- const decision = await options.onPermission(request)
328
- permissionWaitMs += Date.now() - waitStart
329
- // reply 用请求自带的 sessionID(与轮询会话 id 在同会话时相同,
330
- // 但若请求来自子会话则必须用请求的归属会话,否则 404)。
331
- const replyRes = await req(`/session/${request.sessionID}/permission/${request.id}/reply`, {
332
- method: "POST",
333
- body: JSON.stringify({ decision }),
334
- })
335
- if (replyRes.status === 404) {
336
- // 债务D2:请求已被其他端(桌面)先处理——不是错误,任务继续
337
- options?.onPermissionConflict?.()
338
- } else {
339
- await json(replyRes)
340
- options?.onPermissionReplied?.(decision)
341
- }
342
- continue // 决策已提交,重新进入轮询
343
- }
344
- } catch (error) {
345
- // 审批链路故障不能杀死本轮对话。请求在回调前已标记 handled:
346
- // 不会重复推送 QQ,但 reply 失败时会留到 5 分钟超时暴露问题。
347
- console.error("[opencode] 权限审批轮询失败:", error)
348
- }
349
- }
350
-
351
- const listJson = await json(await req(`/session/${sessionId}/message`))
352
- const msgs: SessionMessage[] = listJson?.data ?? []
353
- // Completion = the idle marker created at/after this prompt. This is the
354
- // only reliable "whole turn done" signal: tool-using turns emit several
355
- // assistant messages (reasoning+tool) before the final text one, so
356
- // "first completed assistant" would return an empty tool message.
357
- const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
358
- if (idle) {
359
- // Aggregate text parts from ALL assistant messages of this turn,
360
- // dropping reasoning/tool parts. In practice only the final assistant
361
- // carries text; earlier ones are reasoning+tool.
362
- const reply = collectReplyText(msgs, baseline)
363
- return reply || "(AI 未返回内容)"
364
- }
365
- }
366
- throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`)
367
- },
368
- }
369
-
370
- client = oc
371
- return oc
372
- }
373
-
374
- export function getClient(): OpencodeClient {
375
- if (!client) throw new Error("OpenCode client not initialized")
376
- return client
377
- }
378
-
379
- export async function healthCheck(oc: OpencodeClient, quiet = false): Promise<void> {
380
- try {
381
- await oc.session.list()
382
- if (!quiet) console.log("[opencode] 连接正常")
383
- } catch (error) {
384
- throw new Error(`OpenCode 连接失败: ${error instanceof Error ? error.message : String(error)}`)
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
+ }