@linjz/opencode-qqbot 0.3.15 → 0.3.16
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 +42 -5
- package/bin/openqq.js +13 -0
- package/dist/notify-cli.js +28 -14
- package/dist/opencode-qqbot-plugin.js +934 -64
- package/dist/openqq-bot.js +3095 -677
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +8 -5
- package/src/bridge.ts +1310 -150
- package/src/cli/notify.ts +167 -158
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +77 -0
- package/src/commands.ts +644 -554
- package/src/config.ts +85 -0
- package/src/core/bot-control.ts +148 -0
- package/src/core/bot-launcher.ts +106 -13
- package/src/core/card-approval.ts +20 -9
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +22 -4
- package/src/core/file-log.ts +35 -3
- package/src/core/form-bridge.ts +14 -5
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +214 -36
- package/src/core/instance-lock.ts +10 -2
- package/src/core/linkwatch.ts +3 -4
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +222 -182
- package/src/core/notify-sink.ts +93 -96
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -303
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +661 -0
- package/src/core/send-media.ts +32 -0
- package/src/core/storage.ts +34 -0
- package/src/core/watchdog.ts +513 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +140 -52
- package/src/opencode/client.ts +206 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +15 -2
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +120 -115
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +79 -16
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
package/src/opencode/client.ts
CHANGED
|
@@ -63,13 +63,21 @@ export interface PromptAndWaitOptions extends PromptOptions {
|
|
|
63
63
|
// promptId = 本回合 user 消息 id,是「直答归属本回合」的精确锚点(共享会话下
|
|
64
64
|
// 「baseline 后第一条 assistant」会抓到别回合的产物)。
|
|
65
65
|
onAccepted?: (info: { promptId: string; baseline: number }) => void
|
|
66
|
+
// DEF-qqbot-20261112-1:本回合会话的项目目录——权限轮询 list 与裁决 reply 的
|
|
67
|
+
// x-opencode-directory 值;引擎待审按 location 实例分仓,不带必查空/404。
|
|
68
|
+
// ★ 头链路边界(2026-11-17 固化):全链仅本文件 4 处注入(list/reply ×2 组),
|
|
69
|
+
// 新增引擎调用若涉权限/待审数据,必须评估是否带 directory——「漏带」的失效
|
|
70
|
+
// 模式是静默查空(404 被 catch 吞),不留痕——审计靠 grep 本字段的全量命中点。
|
|
71
|
+
// 锚定≠绑定时目录必须来自锚定会话服务端回读(bridge.ts 1461-1466),禁沿用绑定缓存。
|
|
72
|
+
directory?: string
|
|
66
73
|
// 轮询中发现待审批权限时调用;返回用户的审批决策后,promptAndWait 负责
|
|
67
74
|
// POST reply 并继续等待 idle。审批等待时间不计入 5 分钟超时。
|
|
68
75
|
onPermission?: (req: PermissionRequest) => Promise<PermissionDecision>
|
|
69
76
|
// reply POST 成功后回调(确认消息在服务端受理后再发,避免误导)
|
|
70
77
|
onPermissionReplied?: (decision: PermissionDecision) => void
|
|
71
|
-
// reply 404 =
|
|
72
|
-
|
|
78
|
+
// reply 404 = 请求已在其他端(桌面/引擎自动放行)被处理:不致命,任务继续。
|
|
79
|
+
// 2026-11-07:回调带裁决值——「拒绝」遇 404 说明动作可能已执行,须告警(DEF-qqbot-20261107-1)。
|
|
80
|
+
onPermissionConflict?: (decision: PermissionDecision) => void
|
|
73
81
|
}
|
|
74
82
|
|
|
75
83
|
export interface MessagePart {
|
|
@@ -82,8 +90,10 @@ export interface MessagePart {
|
|
|
82
90
|
export interface SessionMessage {
|
|
83
91
|
id?: string
|
|
84
92
|
type?: string
|
|
85
|
-
time?: { created?: number; completed?: number }
|
|
93
|
+
time?: { created?: number; firstToken?: number; streamed?: number; completed?: number }
|
|
86
94
|
content?: MessagePart[]
|
|
95
|
+
/** 运行时工具段(REST 实际返回 tool parts;类型补录 2026-11-10 终稿提取用) */
|
|
96
|
+
parts?: Array<{ type?: string; tool?: string; state?: { status?: string } }>
|
|
87
97
|
finish?: string
|
|
88
98
|
text?: string
|
|
89
99
|
model?: { id?: string; providerID?: string }
|
|
@@ -97,6 +107,18 @@ export interface OpencodeClient {
|
|
|
97
107
|
session: {
|
|
98
108
|
create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
|
|
99
109
|
list(): Promise<{ data?: unknown[] }>
|
|
110
|
+
/** 会话详情(location.directory=项目归属;model/agent=会话级设置,切换回读/显示锚点用) */
|
|
111
|
+
get(opts: { path: { id: string } }): Promise<{
|
|
112
|
+
data?: {
|
|
113
|
+
id?: string
|
|
114
|
+
title?: string
|
|
115
|
+
location?: { directory?: string }
|
|
116
|
+
model?: { id?: string; providerID?: string; variant?: string }
|
|
117
|
+
agent?: string
|
|
118
|
+
}
|
|
119
|
+
}>
|
|
120
|
+
/** 设置会话项目归属(POST /session/{id}/move;directory=绝对路径) */
|
|
121
|
+
move(opts: { path: { id: string }; body: { directory: string } }): Promise<unknown>
|
|
100
122
|
abort(opts: { path: { id: string } }): Promise<unknown>
|
|
101
123
|
messages(opts: {
|
|
102
124
|
path: { id: string }
|
|
@@ -107,8 +129,18 @@ export interface OpencodeClient {
|
|
|
107
129
|
setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
|
|
108
130
|
}
|
|
109
131
|
permission: {
|
|
110
|
-
|
|
111
|
-
|
|
132
|
+
/** DEF-qqbot-20261112-1:引擎待审批按 location 实例分仓,裸查只命中服务端 cwd
|
|
133
|
+
* 实例——必须带会话自身目录(x-opencode-directory);缺省=裸查(旧行为兼容) */
|
|
134
|
+
list(opts?: { directory?: string }): Promise<{ data?: PermissionRequest[] }>
|
|
135
|
+
/** DEF-qqbot-20261112-4(抄袭桌面形态):引擎对该端点按会话自身实例路由
|
|
136
|
+
* (FormLocationMiddleware 同款模式)——跨实例天然正确,零 directory 簿记 */
|
|
137
|
+
forSession(sessionID: string): Promise<{ data?: PermissionRequest[] }>
|
|
138
|
+
reply(opts: {
|
|
139
|
+
path: { sessionID: string; requestID: string }
|
|
140
|
+
body: { decision: PermissionDecision }
|
|
141
|
+
/** 同 list:reply 端点按调用方上下文实例解析请求,不带目录对项目会话必 404 */
|
|
142
|
+
directory?: string
|
|
143
|
+
}): Promise<unknown>
|
|
112
144
|
}
|
|
113
145
|
// L 项(2026-10-30):V2 Form API——按会话列表(实测 GET /api/form 是 location 维度,
|
|
114
146
|
// bot 进程 cwd 与会话项目不一致会漏;会话级列表才可靠)+ 作答
|
|
@@ -140,6 +172,13 @@ function turnTimeoutMinutes(): number {
|
|
|
140
172
|
function responseTimeoutMs(): number {
|
|
141
173
|
return turnTimeoutMinutes() * 60 * 1000
|
|
142
174
|
}
|
|
175
|
+
// DEF-20261119-P11:单 API 调用超时(req 层 AbortSignal.timeout)。须显著小于
|
|
176
|
+
// 回合 deadline,保证「挂起的调用先抛错、deadline 判定仍可达」。env 可覆盖。
|
|
177
|
+
function apiCallTimeoutMs(): number {
|
|
178
|
+
const n = Number(process.env.QQ_API_CALL_TIMEOUT_MS ?? "30000")
|
|
179
|
+
return Number.isFinite(n) && n > 0 ? n : 30_000
|
|
180
|
+
}
|
|
181
|
+
const API_CALL_TIMEOUT_MS = apiCallTimeoutMs()
|
|
143
182
|
|
|
144
183
|
// 取 baseline 之后最后一个有正文的 assistant 消息,丢弃 reasoning/tool 与阶段前导语。
|
|
145
184
|
// 长回合会产生多条“正在检查/进度总结”assistant 文本;全部拼接会把过程包装成多条
|
|
@@ -170,6 +209,24 @@ export interface TurnState {
|
|
|
170
209
|
hasIdle: boolean
|
|
171
210
|
/** 本回合(或旧判据窗口内)最终 assistant 正文;无正文为空串 */
|
|
172
211
|
text: string
|
|
212
|
+
/** DEF-qqbot-20261107-P2:本回合已被同会话新输入接管(runner 接管语义,
|
|
213
|
+
* 回合已死,idle/正文永远不会到来);前台/后台等待方据此按「被打断」终态结算 */
|
|
214
|
+
superseded: boolean
|
|
215
|
+
/** DEF-qqbot-20261112-2:text 所在 assistant 消息是否已终结(time.completed)。
|
|
216
|
+
* 正文可能已流式落库但消息未完成(典型=工具阻塞在权限审批)——此时正文≠回合已完,
|
|
217
|
+
* 完成判定必须继续等 idle/正文终结;引擎 step.ended/failed/interrupted 均落 completed,
|
|
218
|
+
* 被杀回合不受影响。未锚定回落路径不应用该守卫,恒 true。 */
|
|
219
|
+
textCompleted: boolean
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** DEF-qqbot-20261107-P2(2026-11-07):本回合被同会话新输入接管。
|
|
223
|
+
* 前台/后台等待方捕获后给用户可见交代并按 superseded 销账——不等 30 分钟超时、
|
|
224
|
+
* 不谎称「转后台继续执行」、不再交付占位符。 */
|
|
225
|
+
export class SupersededError extends Error {
|
|
226
|
+
constructor(readonly sessionId: string) {
|
|
227
|
+
super(`superseded: 会话 ${sessionId} 的回合被同会话新输入接管`)
|
|
228
|
+
this.name = "SupersededError"
|
|
229
|
+
}
|
|
173
230
|
}
|
|
174
231
|
|
|
175
232
|
export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline: number): TurnState {
|
|
@@ -194,7 +251,13 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
|
|
|
194
251
|
if (userIdx < 0) {
|
|
195
252
|
// 回落旧判据:行为与 collectReplyText 时代一致,不引入新风险
|
|
196
253
|
const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
|
|
197
|
-
return {
|
|
254
|
+
return {
|
|
255
|
+
anchored: false,
|
|
256
|
+
hasIdle: Boolean(idle),
|
|
257
|
+
text: collectReplyText(msgs, baseline),
|
|
258
|
+
superseded: false,
|
|
259
|
+
textCompleted: true, // 回落路径不应用 textCompleted 守卫(后台 finish 只信 anchored)
|
|
260
|
+
}
|
|
198
261
|
}
|
|
199
262
|
let end = ordered.length
|
|
200
263
|
for (let i = userIdx + 1; i < ordered.length; i++) {
|
|
@@ -205,6 +268,7 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
|
|
|
205
268
|
}
|
|
206
269
|
const boundary = ordered.slice(userIdx + 1, end)
|
|
207
270
|
let text = ""
|
|
271
|
+
let textCompleted = false
|
|
208
272
|
for (let i = boundary.length - 1; i >= 0; i--) {
|
|
209
273
|
const m = boundary[i]
|
|
210
274
|
if (m.type !== "assistant") continue
|
|
@@ -215,18 +279,69 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
|
|
|
215
279
|
.trim()
|
|
216
280
|
if (joined) {
|
|
217
281
|
text = joined
|
|
282
|
+
// DEF-qqbot-20261112-2:正文消息是否已终结——权限挂起中消息 streamed 但无
|
|
283
|
+
// completed,正文已见而回合未完(2026-11-12 ZERO2 实证:此类回合被误结、
|
|
284
|
+
// 交付「无文本产出」假完成)
|
|
285
|
+
textCompleted = Boolean(m.time?.completed)
|
|
218
286
|
break
|
|
219
287
|
}
|
|
220
288
|
}
|
|
289
|
+
// 防线 A 修正(2026-11-07 第二版,实测早交后钉死):下一 user 接替判 done 必须
|
|
290
|
+
// 以「本回合正文已落库」为守卫——POST /prompt 受理即建 user 行(排队消息不等
|
|
291
|
+
// 前回合结束),无守卫会把「正文未生成的进行中回合」判 done,交付
|
|
292
|
+
// (AI 未返回内容) 且丢失真实答案(11-07 10:16 实证)。正文在=回合实质已完,
|
|
293
|
+
// 接替判据才安全;正文空则继续等 idle/正文。
|
|
294
|
+
const nextTurnStarted = end < ordered.length && Boolean(text)
|
|
295
|
+
// DEF-qqbot-20261107-P2(11-07 10:16/10:29 实证 ×2):OpenCode V2 runner 对忙会话的
|
|
296
|
+
// 新 /prompt 是「接管」语义——新 user 行受理即在途回合被 打断(消息链实证:assistant
|
|
297
|
+
// finish=tool_calls 后无第二步,死回合)。防线 A 守卫只防早交占位符,防不了「等一个
|
|
298
|
+
// 永远不会来的 idle/正文」:死回合会挂到前台 30 分钟超时,转后台还谎称任务继续执行。
|
|
299
|
+
// 判定口径:边界内无正文、无 idle(回合未完),但边界外(下一条 user 行之后)已出现
|
|
300
|
+
// assistant/idle 活动 → runner 已在推进后续回合,本回合死亡。正文已落库或本回合 idle
|
|
301
|
+
// 已现时不适用(superseded 仅在 !text 下计算,正常终结维持原判定)。
|
|
302
|
+
let superseded = false
|
|
303
|
+
if (!text && end < ordered.length) {
|
|
304
|
+
const lastBoundaryCreated = boundary.length
|
|
305
|
+
? (boundary[boundary.length - 1].time?.created ?? 0)
|
|
306
|
+
: (ordered[userIdx].time?.created ?? 0)
|
|
307
|
+
superseded = ordered
|
|
308
|
+
.slice(end + 1)
|
|
309
|
+
.some((m) => (m.type === "assistant" || m.type === "idle") && (m.time?.created ?? 0) > lastBoundaryCreated)
|
|
310
|
+
}
|
|
221
311
|
return {
|
|
222
312
|
anchored: true,
|
|
223
|
-
hasIdle: boundary.some((m) => m.type === "idle"),
|
|
313
|
+
hasIdle: boundary.some((m) => m.type === "idle") || nextTurnStarted,
|
|
224
314
|
text,
|
|
315
|
+
superseded,
|
|
316
|
+
textCompleted,
|
|
225
317
|
}
|
|
226
318
|
}
|
|
227
319
|
|
|
228
320
|
let client: OpencodeClient | null = null
|
|
229
321
|
|
|
322
|
+
/**
|
|
323
|
+
* DEF-qqbot-20261110-9 归属守卫(纯函数,导出供测试):
|
|
324
|
+
* anchored=false 的回落命中是否属于「邻回合答案」——命中的 assistant 正文若位于
|
|
325
|
+
* 消息窗口中最后一条 user 行之前,则它属于更早的回合(本回合 user 尚未落库),
|
|
326
|
+
* 回落不得取用它(否则该回合被假完成,内容再被 24h 去重拦截后无声消失)。
|
|
327
|
+
*/
|
|
328
|
+
export function fallbackAnswerStolen(msgs: Array<{ type?: string; content?: Array<{ type?: string; text?: string }> }>, text: string): boolean {
|
|
329
|
+
if (!text.trim()) return false
|
|
330
|
+
let lastUserIdx = -1
|
|
331
|
+
msgs.forEach((m, i) => {
|
|
332
|
+
if (m.type === "user") lastUserIdx = i
|
|
333
|
+
})
|
|
334
|
+
if (lastUserIdx < 0) return false
|
|
335
|
+
const needle = text.trim()
|
|
336
|
+
const idx = msgs.findIndex(
|
|
337
|
+
(m, i) =>
|
|
338
|
+
m.type === "assistant" &&
|
|
339
|
+
i < lastUserIdx &&
|
|
340
|
+
(m.content ?? []).some((p) => p.type === "text" && typeof p.text === "string" && p.text.trim() === needle),
|
|
341
|
+
)
|
|
342
|
+
return idx >= 0
|
|
343
|
+
}
|
|
344
|
+
|
|
230
345
|
function sleep(ms: number): Promise<void> {
|
|
231
346
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
232
347
|
}
|
|
@@ -245,6 +360,11 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
245
360
|
async function req(path: string, init?: RequestInit): Promise<Response> {
|
|
246
361
|
return fetch(base + path, {
|
|
247
362
|
...init,
|
|
363
|
+
// DEF-20261119-P11:per-call 超时兜底——引擎挂起时裸 fetch 无限等,把
|
|
364
|
+
// promptAndWait 的 deadline 判定彻底封死(10:00 实证:/message 挂 33 分钟,
|
|
365
|
+
// 转后台/停滞提醒/对账全链停摆;亦是 DEF-20261119-P7 僵尸 bgWait 的同根候选)。
|
|
366
|
+
// 显式 signal 优先;AbortSignal.timeout 缺失(旧运行时)静默降级为原行为。
|
|
367
|
+
signal: init?.signal ?? AbortSignal.timeout?.(API_CALL_TIMEOUT_MS),
|
|
248
368
|
headers: { ...authHeaders, ...((init?.headers as Record<string, string>) ?? {}) },
|
|
249
369
|
})
|
|
250
370
|
}
|
|
@@ -253,7 +373,12 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
253
373
|
if (!res.ok) {
|
|
254
374
|
const txt = await res.text().catch(() => "")
|
|
255
375
|
const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt
|
|
256
|
-
|
|
376
|
+
// DEF-20261119-P9:429 带 Retry-After 时把暗示值透出(机器可读标记),
|
|
377
|
+
// 让上层退避按服务端节奏走,而非固定 20s(UAT SY-004 注入实证)。
|
|
378
|
+
const retryAfter = res.status === 429 ? res.headers.get("retry-after") : null
|
|
379
|
+
throw new Error(
|
|
380
|
+
`OpenCode API ${res.status}: ${excerpt}${retryAfter ? ` [retry-after:${retryAfter}]` : ""}`,
|
|
381
|
+
)
|
|
257
382
|
}
|
|
258
383
|
// 204 (如 /model /agent /permission reply) 无 body;res.json() 会抛错。
|
|
259
384
|
if (res.status === 204) return null
|
|
@@ -282,6 +407,12 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
282
407
|
async list() {
|
|
283
408
|
return json(await req("/session"))
|
|
284
409
|
},
|
|
410
|
+
async get(opts) {
|
|
411
|
+
return json(await req(`/session/${opts.path.id}`))
|
|
412
|
+
},
|
|
413
|
+
async move(opts) {
|
|
414
|
+
return json(await req(`/session/${opts.path.id}/move`, { method: "POST", body: JSON.stringify(opts.body) }))
|
|
415
|
+
},
|
|
285
416
|
async abort(opts) {
|
|
286
417
|
return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
|
|
287
418
|
},
|
|
@@ -304,14 +435,22 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
304
435
|
},
|
|
305
436
|
|
|
306
437
|
permission: {
|
|
307
|
-
async list() {
|
|
308
|
-
return json(
|
|
438
|
+
async list(opts) {
|
|
439
|
+
return json(
|
|
440
|
+
await req("/permission/request", {
|
|
441
|
+
headers: opts?.directory ? { "x-opencode-directory": opts.directory } : undefined,
|
|
442
|
+
}),
|
|
443
|
+
)
|
|
444
|
+
},
|
|
445
|
+
async forSession(sessionID) {
|
|
446
|
+
return json(await req(`/session/${sessionID}/permission`))
|
|
309
447
|
},
|
|
310
448
|
async reply(opts) {
|
|
311
449
|
return json(
|
|
312
450
|
await req(`/session/${opts.path.sessionID}/permission/${opts.path.requestID}/reply`, {
|
|
313
451
|
method: "POST",
|
|
314
452
|
body: JSON.stringify(opts.body),
|
|
453
|
+
headers: opts.directory ? { "x-opencode-directory": opts.directory } : undefined,
|
|
315
454
|
}),
|
|
316
455
|
)
|
|
317
456
|
},
|
|
@@ -359,9 +498,14 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
359
498
|
},
|
|
360
499
|
|
|
361
500
|
async promptAndWait(sessionId, text, options) {
|
|
362
|
-
// v2:
|
|
363
|
-
//
|
|
364
|
-
|
|
501
|
+
// v2: model/agent 会被 additionalProperties:false 静默剥离 —— 不往 body 里塞;
|
|
502
|
+
// 模型/agent 由 SessionManager 走 session 级端点。
|
|
503
|
+
// delivery:"steer"(SDK V2SessionPromptData.body 已实证支持):声明前台在场,
|
|
504
|
+
// 引擎审批门据此闭合(design §3.2/§4「steer 前台在场语义」)。
|
|
505
|
+
const body: { text: string; files?: Array<{ uri: string; name?: string }>; delivery: "steer" } = {
|
|
506
|
+
text,
|
|
507
|
+
delivery: "steer",
|
|
508
|
+
}
|
|
365
509
|
if (options?.files?.length) body.files = options.files
|
|
366
510
|
|
|
367
511
|
// 债务D1:子会话(subagent)审批检测——session 详情带 parentID
|
|
@@ -401,6 +545,7 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
401
545
|
const deadline = Date.now() + responseTimeoutMs()
|
|
402
546
|
let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
|
|
403
547
|
const handledPermissions = new Set<string>()
|
|
548
|
+
let consecutivePollFails = 0 // P11:引擎瞬时挂起按次容错,连续 N 次才按超时终态抛
|
|
404
549
|
|
|
405
550
|
while (Date.now() - permissionWaitMs < deadline) {
|
|
406
551
|
await sleep(1000)
|
|
@@ -408,7 +553,11 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
408
553
|
// 审批检测:会话阻塞在权限请求上时不会产生 idle,必须先放行。
|
|
409
554
|
if (options?.onPermission) {
|
|
410
555
|
try {
|
|
411
|
-
const permJson = await json(
|
|
556
|
+
const permJson = await json(
|
|
557
|
+
await req("/permission/request", {
|
|
558
|
+
headers: options.directory ? { "x-opencode-directory": options.directory } : undefined,
|
|
559
|
+
}),
|
|
560
|
+
)
|
|
412
561
|
const all = (permJson?.data ?? []) as PermissionRequest[]
|
|
413
562
|
// 债务D1:主会话请求 + 子会话(subagent,parentID 指向本会话)请求
|
|
414
563
|
const pending: PermissionRequest[] = []
|
|
@@ -431,10 +580,11 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
431
580
|
const replyRes = await req(`/session/${request.sessionID}/permission/${request.id}/reply`, {
|
|
432
581
|
method: "POST",
|
|
433
582
|
body: JSON.stringify({ decision }),
|
|
583
|
+
headers: options.directory ? { "x-opencode-directory": options.directory } : undefined,
|
|
434
584
|
})
|
|
435
585
|
if (replyRes.status === 404) {
|
|
436
586
|
// 债务D2:请求已被其他端(桌面)先处理——不是错误,任务继续
|
|
437
|
-
options?.onPermissionConflict?.()
|
|
587
|
+
options?.onPermissionConflict?.(decision)
|
|
438
588
|
} else {
|
|
439
589
|
await json(replyRes)
|
|
440
590
|
options?.onPermissionReplied?.(decision)
|
|
@@ -448,18 +598,47 @@ export function createClient(baseUrl: string): OpencodeClient {
|
|
|
448
598
|
}
|
|
449
599
|
}
|
|
450
600
|
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
//
|
|
456
|
-
//
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
601
|
+
// DEF-qqbot-20261105-P1 防线 A 配套(2026-11-07):裸 /message 默认只回
|
|
602
|
+
// 50 条——长会话里占回合之后的 idle/下一 user 证据被窗口截断,回合
|
|
603
|
+
// 完成却判不出 done,悬挂至 30 分钟超时(11-07 实证 6 分钟悬挂+完整
|
|
604
|
+
// 消息链取证)。显式 limit=200 扩大判定窗口(与 fetchRecoveryMessages
|
|
605
|
+
// 同档;极端长会话由防线 A 的「下一 user 接替」判据兜住边界)。
|
|
606
|
+
// P11(2026-11-19):整个判定迭代包在容错里——req 层 AbortSignal.timeout
|
|
607
|
+
// 会抛错,瞬时挂起计入连续失败次数后继续轮询;连续 3 次才按「引擎持续
|
|
608
|
+
// 无响应」终态抛错(走调用方响应超时→转后台路径接管)。SupersededError
|
|
609
|
+
// 是正常终态不是故障,必须穿透不计数。
|
|
610
|
+
try {
|
|
611
|
+
const listJson = await json(await req(`/session/${sessionId}/message?limit=200`))
|
|
612
|
+
consecutivePollFails = 0
|
|
613
|
+
const msgs: SessionMessage[] = listJson?.data ?? []
|
|
614
|
+
// Completion = the idle marker of THIS turn (修复⑧ 回合边界归属)。
|
|
615
|
+
// Tool-using turns emit several assistant messages (reasoning+tool) before
|
|
616
|
+
// the final text one, so "first completed assistant" would return an empty
|
|
617
|
+
// tool message. 共享会话下别回合的 idle/assistant 都不再计入本回合判定。
|
|
618
|
+
const turn = turnStateOf(msgs, promptId, baseline)
|
|
619
|
+
if (turn.hasIdle) {
|
|
620
|
+
// DEF-qqbot-20261110-9(2026-11-10 回归实证):anchored=false 回落命中时
|
|
621
|
+
// 必须校验答案归属——若命中正文属于「最后一条 user 行之前」的更早回合
|
|
622
|
+
//(本回合 user 尚未落库、回落把邻回合答案亮出来),不得张冠李戴,
|
|
623
|
+
// 继续等本回合落库;否则该回合会被邻回合答案"假完成"并在去重拦截后
|
|
624
|
+
// 无声消失。
|
|
625
|
+
if (!turn.anchored && turn.text && fallbackAnswerStolen(msgs, turn.text)) {
|
|
626
|
+
console.log(`[opencode] 回落答案归属邻回合,弃用继续等 prompt=${promptId}`)
|
|
627
|
+
} else {
|
|
628
|
+
// Aggregate text parts from ALL assistant messages of this turn,
|
|
629
|
+
// dropping reasoning/tool parts. In practice only the final assistant
|
|
630
|
+
// carries text; earlier ones are reasoning+tool.
|
|
631
|
+
return turn.text || "(AI 未返回内容)"
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (turn.superseded) throw new SupersededError(sessionId)
|
|
635
|
+
} catch (error) {
|
|
636
|
+
if (error instanceof SupersededError) throw error
|
|
637
|
+
consecutivePollFails++
|
|
638
|
+
console.error(`[opencode] 回合轮询失败(第${consecutivePollFails}次):`, error instanceof Error ? error.message : error)
|
|
639
|
+
if (consecutivePollFails >= 3) {
|
|
640
|
+
throw new Error(`AI 响应超时(引擎连续 ${consecutivePollFails} 次无响应)`)
|
|
641
|
+
}
|
|
463
642
|
}
|
|
464
643
|
}
|
|
465
644
|
throw new Error(`AI 响应超时(${turnTimeoutMinutes()} 分钟)`)
|
|
@@ -18,18 +18,35 @@ type EventCallback = (event: V2Event) => void
|
|
|
18
18
|
|
|
19
19
|
const RECONNECT_MIN_MS = 1000
|
|
20
20
|
const RECONNECT_MAX_MS = 30_000
|
|
21
|
+
// DEF-20261119-P8:SSE 静默死亡阈值。对端断连在部分路径下迭代器不抛错(注入实证),
|
|
22
|
+
// 以「N 秒零字节」判死。120s 是权衡值:远小于「断线无感」的失效时长,闲置期即便
|
|
23
|
+
// 引擎零 keepalive 导致的周期性重连也无副作用(监听器内存映射复用,无需重订阅)。
|
|
24
|
+
// 可用 QQ_SSE_SILENCE_MS 覆盖(测试注入小值验证重连链,生产调大容忍更闲的引擎)。
|
|
25
|
+
const SSE_SILENCE_MS = Number(process.env.QQ_SSE_SILENCE_MS ?? 120_000)
|
|
21
26
|
const MAX_BUF_BYTES = 200_000 // 防御性上限(事件洪峰时丢弃积压而非撑爆内存)
|
|
22
27
|
|
|
23
28
|
function sleep(ms: number): Promise<void> {
|
|
24
29
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
25
30
|
}
|
|
26
31
|
|
|
27
|
-
export
|
|
32
|
+
export // DEF-20261119-P12:SSE 事件洪峰饿死事件循环——超长输出回合(实测 2 万整数任务)
|
|
33
|
+
// 的事件洪流使同步 handleFrame 独占事件循环:转后台 deadline/心跳/日志全停摆
|
|
34
|
+
// 17 分钟(10:23-10:40 实证)。修法=帧队列化:读循环只入队(快),处理器按批
|
|
35
|
+
// 消化(每批 DRAIN_BATCH 帧让出一次事件循环),超 MAX_PENDING 背压丢弃并计数。
|
|
36
|
+
const DRAIN_BATCH = 100
|
|
37
|
+
const MAX_PENDING_FRAMES = 20_000
|
|
38
|
+
|
|
39
|
+
class EventStream {
|
|
28
40
|
private base: string
|
|
29
41
|
private headers: Record<string, string>
|
|
30
42
|
private listeners = new Map<string, Set<EventCallback>>()
|
|
43
|
+
private allListeners = new Set<EventCallback>()
|
|
31
44
|
private running = false
|
|
32
45
|
private backoffMs = RECONNECT_MIN_MS
|
|
46
|
+
// P12:帧队列与背压计数(读循环入队、drain 批量消化)。
|
|
47
|
+
private pendingFrames: string[] = []
|
|
48
|
+
private draining = false
|
|
49
|
+
private droppedFrames = 0
|
|
33
50
|
|
|
34
51
|
constructor(baseUrl: string) {
|
|
35
52
|
this.base = baseUrl.replace(/\/+$/, "")
|
|
@@ -59,6 +76,17 @@ export class EventStream {
|
|
|
59
76
|
}
|
|
60
77
|
}
|
|
61
78
|
|
|
79
|
+
// 全量订阅(2026-11-08):不按 sessionID 过滤,供权限/表单等全局事件使用。
|
|
80
|
+
// 权限请求必须在事件到达时即时推送——实测桌面端走同源 SSE,引擎会停在裁决前;
|
|
81
|
+
// bot 若只靠 12s 轮询,取到时请求往往已被引擎自行放行。
|
|
82
|
+
subscribeAll(callback: EventCallback): () => void {
|
|
83
|
+
this.allListeners.add(callback)
|
|
84
|
+
if (!this.running) void this.consume()
|
|
85
|
+
return () => {
|
|
86
|
+
this.allListeners.delete(callback)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
62
90
|
get activeSessions(): number {
|
|
63
91
|
return this.listeners.size
|
|
64
92
|
}
|
|
@@ -75,7 +103,7 @@ export class EventStream {
|
|
|
75
103
|
|
|
76
104
|
private async consume(): Promise<void> {
|
|
77
105
|
this.running = true
|
|
78
|
-
while (this.listeners.size > 0) {
|
|
106
|
+
while (this.listeners.size > 0 || this.allListeners.size > 0) {
|
|
79
107
|
try {
|
|
80
108
|
const res = await fetch(`${this.base}/event`, { headers: this.headers })
|
|
81
109
|
if (!res.ok || !res.body) {
|
|
@@ -85,19 +113,36 @@ export class EventStream {
|
|
|
85
113
|
console.log("[eventstream] 已连接 /api/event")
|
|
86
114
|
const dec = new TextDecoder()
|
|
87
115
|
let buf = ""
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
116
|
+
// DEF-20261119-P8:静默看门狗——SSE 是长连接,对端 FIN/RST 在某些路径下
|
|
117
|
+
// body 迭代器不抛出也不结束(06:11 注入实证:掐断后 43 分钟零感知零重连)。
|
|
118
|
+
// 不依赖「迭代器会不会醒」,以「N 秒无任何字节到达」为死亡定义:到点主动
|
|
119
|
+
// 掐掉本地流并抛错,走既有指数退避重连。心跳间隔大于 45s 的环境可调大。
|
|
120
|
+
let lastChunkAt = Date.now()
|
|
121
|
+
const silenceTimer = setInterval(() => {
|
|
122
|
+
if (Date.now() - lastChunkAt > SSE_SILENCE_MS) {
|
|
123
|
+
console.error(`[eventstream] ${SSE_SILENCE_MS}ms 无数据,判定连接已死,掐线重连`)
|
|
124
|
+
res.body?.cancel().catch(() => {})
|
|
125
|
+
}
|
|
126
|
+
}, 10_000)
|
|
127
|
+
silenceTimer.unref?.()
|
|
128
|
+
try {
|
|
129
|
+
for await (const chunk of res.body) {
|
|
130
|
+
lastChunkAt = Date.now()
|
|
131
|
+
buf += dec.decode(chunk, { stream: true })
|
|
132
|
+
const frames = buf.split("\n\n")
|
|
133
|
+
buf = frames.pop() ?? "" // 最后一段可能不完整,留待下一块
|
|
134
|
+
for (const frame of frames) this.enqueueFrame(frame)
|
|
135
|
+
if (buf.length > MAX_BUF_BYTES) {
|
|
136
|
+
console.error("[eventstream] 缓冲超限,丢弃积压数据")
|
|
137
|
+
buf = ""
|
|
138
|
+
}
|
|
96
139
|
}
|
|
140
|
+
throw new Error("SSE 流意外结束")
|
|
141
|
+
} finally {
|
|
142
|
+
clearInterval(silenceTimer)
|
|
97
143
|
}
|
|
98
|
-
throw new Error("SSE 流意外结束")
|
|
99
144
|
} catch (error) {
|
|
100
|
-
if (this.listeners.size === 0) break
|
|
145
|
+
if (this.listeners.size === 0 && this.allListeners.size === 0) break
|
|
101
146
|
console.error(
|
|
102
147
|
`[eventstream] 连接中断,${this.backoffMs}ms 后重连:`,
|
|
103
148
|
error instanceof Error ? error.message : String(error),
|
|
@@ -110,11 +155,48 @@ export class EventStream {
|
|
|
110
155
|
console.log("[eventstream] 无订阅者,连接关闭")
|
|
111
156
|
}
|
|
112
157
|
|
|
158
|
+
/** P12:读循环只入队(O(1) 不阻塞);超背压上限丢弃并计数(洪峰保护)。 */
|
|
159
|
+
private enqueueFrame(frame: string): void {
|
|
160
|
+
if (this.pendingFrames.length >= MAX_PENDING_FRAMES) {
|
|
161
|
+
this.droppedFrames++
|
|
162
|
+
if (this.droppedFrames % 1000 === 1) {
|
|
163
|
+
console.error(`[eventstream] 事件洪峰背压:已丢弃 ${this.droppedFrames} 帧(DEF-20261119-P12)`)
|
|
164
|
+
}
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
this.pendingFrames.push(frame)
|
|
168
|
+
this.kickDrain()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** P12:批量处理器——每批 DRAIN_BATCH 帧后经 setImmediate 让出事件循环,
|
|
172
|
+
* 保证 deadline 检查/心跳/日志等定时器在洪峰期间仍能运行。 */
|
|
173
|
+
private kickDrain(): void {
|
|
174
|
+
if (this.draining) return
|
|
175
|
+
this.draining = true
|
|
176
|
+
const drain = (): void => {
|
|
177
|
+
const batch = this.pendingFrames.splice(0, DRAIN_BATCH)
|
|
178
|
+
for (const frame of batch) this.handleFrame(frame)
|
|
179
|
+
if (this.pendingFrames.length > 0) {
|
|
180
|
+
setImmediate(drain)
|
|
181
|
+
} else {
|
|
182
|
+
this.draining = false
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
setImmediate(drain)
|
|
186
|
+
}
|
|
187
|
+
|
|
113
188
|
private handleFrame(frame: string): void {
|
|
114
189
|
for (const line of frame.split("\n")) {
|
|
115
190
|
if (!line.startsWith("data:")) continue
|
|
116
191
|
try {
|
|
117
192
|
const ev = JSON.parse(line.slice(5).trim()) as V2Event
|
|
193
|
+
for (const cb of this.allListeners) {
|
|
194
|
+
try {
|
|
195
|
+
cb(ev)
|
|
196
|
+
} catch (error) {
|
|
197
|
+
console.error("[eventstream] 全局订阅回调异常:", error)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
118
200
|
const sid = ev.data?.sessionID
|
|
119
201
|
if (!sid) continue
|
|
120
202
|
const set = this.listeners.get(sid)
|
package/src/opencode/history.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// content 部件: {type:"text",text} | {type:"tool", tool?, state:{status,input,content,metadata}}
|
|
9
9
|
// idle: { id, time, type:"idle", outcome }
|
|
10
10
|
import type { MessagePart, SessionMessage } from "./client.js"
|
|
11
|
+
import { labelBlock } from "../core/markdown.js"
|
|
11
12
|
|
|
12
13
|
// H1(2026-10-30,/history 格式化重做):默认上限放宽——/history 的目的是"回看
|
|
13
14
|
// 内容",旧 400 字/160 字无意义;保留 env 逃生门。按字符计(投递层管字节)。
|
|
@@ -78,11 +79,12 @@ export function renderHistory(messages: SessionMessage[], turns: number): string
|
|
|
78
79
|
if (m.type === "user") {
|
|
79
80
|
const text = (m as { text?: string }).text ?? ""
|
|
80
81
|
// H1 安全修复:正文全量脱敏(旧版只脱工具行,用户/AI 正文可外泄密钥)
|
|
81
|
-
|
|
82
|
+
// 2026-11-10:标签走 labelBlock,正文以围栏/标题/列表开头时标签独占一行。
|
|
83
|
+
if (text.trim()) lines.push(labelBlock("🧑", clipBlock(redactSecrets(text.trim()), userClip)))
|
|
82
84
|
} else if (m.type === "assistant") {
|
|
83
85
|
for (const p of m.content ?? []) {
|
|
84
86
|
if (p.type === "text" && p.text?.trim()) {
|
|
85
|
-
lines.push(
|
|
87
|
+
lines.push(labelBlock("🤖", clipBlock(redactSecrets(p.text.trim()), textClip)))
|
|
86
88
|
} else if (p.type === "tool") {
|
|
87
89
|
const t = toolRunOf(p)
|
|
88
90
|
const st = toolStats.get(t.name) ?? { ok: 0, fail: 0 }
|
package/src/opencode/mirror.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import type { SessionMessage } from "./client.js"
|
|
9
9
|
import { redactSecrets } from "./history.js"
|
|
10
|
+
import { labelBlock } from "../core/markdown.js"
|
|
10
11
|
|
|
11
12
|
const USER_CLIP = 160
|
|
12
13
|
|
|
@@ -21,6 +22,16 @@ function answerClipLimit(): number {
|
|
|
21
22
|
|
|
22
23
|
// 逻辑回合并发幂等键:同一用户消息 + 最终 assistant。不同 location 的
|
|
23
24
|
// execution.succeeded 事件 ID 可以不同,但同一逻辑回合仍只应镜像一次。
|
|
25
|
+
// 摘要锚定用户消息 id(DEF-20261118-P6 来源身份守卫用):与 digestTurnKey 同一
|
|
26
|
+
// 锚点口径——时间序最后的 user 消息。无 user 消息返回 undefined(守卫放行给既有逻辑)。
|
|
27
|
+
export function digestAnchorUserId(messages: SessionMessage[]): string | undefined {
|
|
28
|
+
const ordered = [...messages].reverse()
|
|
29
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
30
|
+
if (ordered[i].type === "user") return ordered[i].id ?? undefined
|
|
31
|
+
}
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
24
35
|
export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
25
36
|
const ordered = [...messages].reverse()
|
|
26
37
|
let lastUserIdx = -1
|
|
@@ -73,8 +84,10 @@ export function buildDigest(messages: SessionMessage[]): string | null {
|
|
|
73
84
|
lines.push(`🤖 ${clip(answer, clipLimit)}`)
|
|
74
85
|
if (answer.length > clipLimit) lines.push(`(答案共 ${answer.length} 字,回 /history 看更多)`)
|
|
75
86
|
} else {
|
|
76
|
-
// 全文模式:保留原文换行/排版(clip
|
|
77
|
-
|
|
87
|
+
// 全文模式:保留原文换行/排版(clip 的空白折叠只用于截断模式)。
|
|
88
|
+
// 标签必须走 labelBlock:正文以 ```/标题/列表等块级语法开头时独占一行,
|
|
89
|
+
// 否则 "🤖 ```" 让开围栏不顶格 → QQ 渲染空代码卡 + 正文外泄(2026-11-10 截图实证)。
|
|
90
|
+
lines.push(labelBlock("🤖", answer))
|
|
78
91
|
}
|
|
79
92
|
return redactSecrets(lines.join("\n"))
|
|
80
93
|
}
|