@linjz/opencode-qqbot 0.3.12 → 0.3.14
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 +12 -7
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +4 -4
- package/dist/openqq-bot.js +1072 -208
- package/package.json +2 -2
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +141 -15
- package/src/commands.ts +554 -554
- package/src/config.ts +118 -121
- package/src/core/bot-launcher.ts +146 -146
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +115 -18
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -33
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +388 -72
- package/src/core/form-journal.ts +214 -0
- package/src/core/gateway-state.ts +68 -0
- package/src/core/inbound-dedupe.ts +43 -0
- package/src/core/inflight-journal.ts +170 -22
- package/src/core/instance-lock.ts +28 -1
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +11 -0
- package/src/core/mirror.ts +182 -182
- package/src/core/outbox.ts +522 -0
- 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 +98 -13
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +85 -85
- 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 +546 -539
- package/src/qq/gateway.ts +69 -20
- package/src/qq/media.ts +219 -219
- package/src/qq/sender.ts +303 -300
- package/src/qq/types.ts +154 -154
- package/tsconfig.json +24 -24
|
@@ -1,138 +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
|
-
}
|
|
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
|
+
}
|
package/src/opencode/history.ts
CHANGED
|
@@ -1,143 +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
|
-
}
|
|
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
|
+
}
|