@linjz/opencode-qqbot 0.0.0-stage → 0.3.1

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.
@@ -0,0 +1,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
+ 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
+ }
@@ -0,0 +1,138 @@
1
+ // @input: (none - fetch + env)
2
+ // @output: V2Event, EventStream, createEventStream
3
+ // @pos: opencode层 - V2 SSE 事件流客户端(单连接、按 sessionID 分流、自动重连)
4
+ //
5
+ // V2 事件帧实测(2026-10-13):GET /api/event 返回 text/event-stream,
6
+ // 帧以 \n\n 分隔,每帧形如 `data: {json}`(无 event: 行),JSON 结构:
7
+ // { id, type(事件名), created, location?, data: { sessionID, ... }, durable: { aggregateID, seq } }
8
+ // 分流依据 = data.sessionID(每帧必有)。断线自动重连(指数退避,无订阅者时退出)。
9
+
10
+ export interface V2Event {
11
+ id?: string
12
+ type: string
13
+ created?: number
14
+ data?: Record<string, unknown> & { sessionID?: string }
15
+ }
16
+
17
+ type EventCallback = (event: V2Event) => void
18
+
19
+ const RECONNECT_MIN_MS = 1000
20
+ const RECONNECT_MAX_MS = 30_000
21
+ const MAX_BUF_BYTES = 200_000 // 防御性上限(事件洪峰时丢弃积压而非撑爆内存)
22
+
23
+ function sleep(ms: number): Promise<void> {
24
+ return new Promise((resolve) => setTimeout(resolve, ms))
25
+ }
26
+
27
+ export class EventStream {
28
+ private base: string
29
+ private headers: Record<string, string>
30
+ private listeners = new Map<string, Set<EventCallback>>()
31
+ private running = false
32
+ private backoffMs = RECONNECT_MIN_MS
33
+
34
+ constructor(baseUrl: string) {
35
+ this.base = baseUrl.replace(/\/+$/, "")
36
+ this.headers = { Accept: "text/event-stream" }
37
+ const password = process.env.OPENCODE_PASSWORD
38
+ if (password) {
39
+ this.headers.Authorization = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
40
+ }
41
+ }
42
+
43
+ // 订阅指定会话的事件;返回取消订阅函数。首个订阅者触发连接。
44
+ subscribe(sessionID: string, callback: EventCallback): () => void {
45
+ let set = this.listeners.get(sessionID)
46
+ if (!set) {
47
+ set = new Set()
48
+ this.listeners.set(sessionID, set)
49
+ }
50
+ set.add(callback)
51
+ if (!this.running) void this.consume()
52
+ return () => {
53
+ const s = this.listeners.get(sessionID)
54
+ if (!s) return
55
+ s.delete(callback)
56
+ if (s.size === 0) {
57
+ this.listeners.delete(sessionID)
58
+ }
59
+ }
60
+ }
61
+
62
+ get activeSessions(): number {
63
+ return this.listeners.size
64
+ }
65
+
66
+ // HC2(2026-10-26):运行中热换基(端口漂移自愈)。不影响当前连接;
67
+ // 断线重连的下一轮 fetch 即走新址。复盘3-F 的单引号日志 bug 顺手修复。
68
+ rebase(nextUrl: string): void {
69
+ const next = nextUrl.replace(/\/+$/, "")
70
+ if (next !== this.base) {
71
+ console.log(`[eventstream] 热换基:${this.base} → ${next}`)
72
+ this.base = next
73
+ }
74
+ }
75
+
76
+ private async consume(): Promise<void> {
77
+ this.running = true
78
+ while (this.listeners.size > 0) {
79
+ try {
80
+ const res = await fetch(`${this.base}/event`, { headers: this.headers })
81
+ if (!res.ok || !res.body) {
82
+ throw new Error(`SSE 连接失败: HTTP ${res.status}`)
83
+ }
84
+ this.backoffMs = RECONNECT_MIN_MS // 连接成功才重置退避
85
+ console.log("[eventstream] 已连接 /api/event")
86
+ const dec = new TextDecoder()
87
+ let buf = ""
88
+ for await (const chunk of res.body) {
89
+ buf += dec.decode(chunk, { stream: true })
90
+ const frames = buf.split("\n\n")
91
+ buf = frames.pop() ?? "" // 最后一段可能不完整,留待下一块
92
+ for (const frame of frames) this.handleFrame(frame)
93
+ if (buf.length > MAX_BUF_BYTES) {
94
+ console.error("[eventstream] 缓冲超限,丢弃积压数据")
95
+ buf = ""
96
+ }
97
+ }
98
+ throw new Error("SSE 流意外结束")
99
+ } catch (error) {
100
+ if (this.listeners.size === 0) break
101
+ console.error(
102
+ `[eventstream] 连接中断,${this.backoffMs}ms 后重连:`,
103
+ error instanceof Error ? error.message : String(error),
104
+ )
105
+ await sleep(this.backoffMs)
106
+ this.backoffMs = Math.min(this.backoffMs * 2, RECONNECT_MAX_MS)
107
+ }
108
+ }
109
+ this.running = false
110
+ console.log("[eventstream] 无订阅者,连接关闭")
111
+ }
112
+
113
+ private handleFrame(frame: string): void {
114
+ for (const line of frame.split("\n")) {
115
+ if (!line.startsWith("data:")) continue
116
+ try {
117
+ const ev = JSON.parse(line.slice(5).trim()) as V2Event
118
+ const sid = ev.data?.sessionID
119
+ if (!sid) continue
120
+ const set = this.listeners.get(sid)
121
+ if (!set) continue
122
+ for (const cb of set) {
123
+ try {
124
+ cb(ev)
125
+ } catch (error) {
126
+ console.error("[eventstream] 订阅回调异常:", error)
127
+ }
128
+ }
129
+ } catch {
130
+ // 坏帧忽略(保持流存活)
131
+ }
132
+ }
133
+ }
134
+ }
135
+
136
+ export function createEventStream(baseUrl: string): EventStream {
137
+ return new EventStream(baseUrl)
138
+ }
@@ -0,0 +1,143 @@
1
+ // @input: ./client (SessionMessage 类型)
2
+ // @output: renderHistory
3
+ // @pos: opencode层 - 会话历史渲染(QQ 用)
4
+ //
5
+ // GET /session/{id}/message 实测结构(2026-10-13,倒序=新→旧):
6
+ // user: { id, time, text, type:"user" }
7
+ // assistant: { id, time, type, agent, model, content[], finish, cost, tokens }
8
+ // content 部件: {type:"text",text} | {type:"tool", tool?, state:{status,input,content,metadata}}
9
+ // idle: { id, time, type:"idle", outcome }
10
+ import type { MessagePart, SessionMessage } from "./client.js"
11
+
12
+ // H1(2026-10-30,/history 格式化重做):默认上限放宽——/history 的目的是"回看
13
+ // 内容",旧 400 字/160 字无意义;保留 env 逃生门。按字符计(投递层管字节)。
14
+ const TOOL_CLIP = 140
15
+
16
+ function historyLimit(envKey: string, fallback: number): number {
17
+ const n = Number(process.env[envKey])
18
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
19
+ }
20
+
21
+ // 块级截断:保留换行与 markdown 结构(旧 clip 折叠 \s+ 会把代码块/表格压成一行,
22
+ // 是 "/history 没格式化" 的核心病根),仅超长在尾部截断+提示。
23
+ function clipBlock(text: string, max: number): string {
24
+ if (text.length <= max) return text
25
+ return `${text.slice(0, max)}\n…(共 ${text.length} 字,已截断,回桌面看全文)`
26
+ }
27
+
28
+ interface ToolRun {
29
+ name: string
30
+ ok: boolean
31
+ detail: string
32
+ }
33
+
34
+ // 工具部件 → 结构化摘要(聚合计数 + 失败详情两用)
35
+ function toolRunOf(part: MessagePart): ToolRun {
36
+ const state = (part.state ?? part) as Record<string, any>
37
+ const status = String(state.status ?? "?")
38
+ const ok = status === "completed"
39
+ const toolName = typeof part.tool === "string" && part.tool ? part.tool : "tool"
40
+ const exit = state.metadata?.exit
41
+ const exitNote = typeof exit === "number" && exit !== 0 ? ` (exit ${exit})` : ""
42
+ const detail = `${toolName} ${clip(redactSecrets(summarizeInput(state.input)), TOOL_CLIP)} ${ok ? "✓" : `✗${exitNote}`}`
43
+ return { name: toolName, ok, detail }
44
+ }
45
+
46
+ // 渲染最近 turns 轮对话(每轮以 user 消息为界);无内容返回 null(调用方回兜底文案)。
47
+ // H1 重做:轮次头编号 + 换行保留 + 全文脱敏 + 工具行聚合(失败单列详情)。
48
+ export function renderHistory(messages: SessionMessage[], turns: number): string | null {
49
+ // 倒序转正序,按 user 消息切轮次
50
+ const ordered = [...messages].reverse()
51
+ const segments: SessionMessage[][] = []
52
+ let cur: SessionMessage[] = []
53
+ for (const m of ordered) {
54
+ if (m.type === "user" && cur.length > 0) {
55
+ segments.push(cur)
56
+ cur = []
57
+ }
58
+ cur.push(m)
59
+ }
60
+ if (cur.length > 0) segments.push(cur)
61
+
62
+ const picked = segments.slice(-turns)
63
+ if (picked.length === 0) return null
64
+
65
+ const userClip = historyLimit("QQ_HISTORY_USER_CLIP", 500)
66
+ const textClip = historyLimit("QQ_HISTORY_TEXT_CLIP", 1200)
67
+ const TOOL_DETAIL_MAX = 3
68
+
69
+ const total = picked.length
70
+ const out: string[] = []
71
+ picked.forEach((seg, idx) => {
72
+ const lines: string[] = [`▎第 ${idx + 1} 轮(共 ${total} 轮)`]
73
+ const toolStats = new Map<string, { ok: number; fail: number }>()
74
+ const failDetails: string[] = []
75
+ let failOverflow = 0
76
+
77
+ for (const m of seg) {
78
+ if (m.type === "user") {
79
+ const text = (m as { text?: string }).text ?? ""
80
+ // H1 安全修复:正文全量脱敏(旧版只脱工具行,用户/AI 正文可外泄密钥)
81
+ if (text.trim()) lines.push(`🧑 ${clipBlock(redactSecrets(text.trim()), userClip)}`)
82
+ } else if (m.type === "assistant") {
83
+ for (const p of m.content ?? []) {
84
+ if (p.type === "text" && p.text?.trim()) {
85
+ lines.push(`🤖 ${clipBlock(redactSecrets(p.text.trim()), textClip)}`)
86
+ } else if (p.type === "tool") {
87
+ const t = toolRunOf(p)
88
+ const st = toolStats.get(t.name) ?? { ok: 0, fail: 0 }
89
+ if (t.ok) st.ok += 1
90
+ else st.fail += 1
91
+ toolStats.set(t.name, st)
92
+ if (!t.ok) {
93
+ if (failDetails.length < TOOL_DETAIL_MAX) failDetails.push(`🔧 ${t.detail}`)
94
+ else failOverflow += 1
95
+ }
96
+ }
97
+ }
98
+ }
99
+ // idle 等其余类型不渲染
100
+ }
101
+
102
+ if (toolStats.size > 0) {
103
+ const agg = [...toolStats.entries()]
104
+ .map(([name, s]) => `${name}×${s.ok + s.fail}${s.fail > 0 ? `(${s.fail}✗)` : "✓"}`)
105
+ .join(" ")
106
+ lines.push(`🔧 ${agg}`)
107
+ for (const d of failDetails) lines.push(d)
108
+ if (failOverflow > 0) lines.push(`🔧 …另有 ${failOverflow} 个失败工具(回桌面看详情)`)
109
+ }
110
+
111
+ // 跳过空轮(只有轮次头没有内容)
112
+ if (lines.length > 1) out.push(lines.join("\n"))
113
+ })
114
+
115
+ return out.length > 0 ? out.join("\n\n") : null
116
+ }
117
+
118
+ // 秘钥脱敏:命令原文常含 env 赋值(如 OPENCODE_PASSWORD=xxx),
119
+ // 推送/渲染前调用,防止密码、token 随里程碑或历史外泄(2026-10-13 实测截图教训)。
120
+ const SECRET_RE =
121
+ /((?:password|passwd|secret|token|api[_-]?key|authorization|credential)["']?\s*[=:]\s*["']?(?:bearer\s+|basic\s+|token\s+)?)([^\s"']+)/gi
122
+
123
+ export function redactSecrets(text: string): string {
124
+ return text.replace(SECRET_RE, "$1***")
125
+ }
126
+
127
+ // 工具输入摘要:不同工具 input 字段不同,逐个降级猜测(与 bridge 里程碑共用思路)
128
+ export function summarizeInput(input: unknown): string {
129
+ if (input == null) return "(无输入)"
130
+ if (typeof input === "string") return input
131
+ if (typeof input !== "object") return String(input)
132
+ const obj = input as Record<string, unknown>
133
+ for (const key of ["command", "filePath", "path", "url", "pattern", "query", "agent", "description"]) {
134
+ const v = obj[key]
135
+ if (typeof v === "string" && v.trim()) return key === "pattern" ? `搜索 ${v}` : v
136
+ }
137
+ return JSON.stringify(obj)
138
+ }
139
+
140
+ function clip(value: string, max: number): string {
141
+ const s = value.replace(/\s+/g, " ").trim()
142
+ return s.length > max ? `${s.slice(0, max)}…` : s
143
+ }