@linjz/opencode-qqbot 0.3.15 → 0.3.17

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 (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -53,6 +53,9 @@ export interface PermissionRequest {
53
53
  export interface PromptOptions {
54
54
  model?: { providerID: string; modelID: string }
55
55
  agent?: string
56
+ /** 投递语义(Session.Inbox.Delivery,官方枚举 steer|queue):steer=并入在途回合
57
+ * (官方 TUI 忙时 Enter 同款),queue=引擎侧排队。缺省=引擎默认。 */
58
+ delivery?: "steer" | "queue"
56
59
  }
57
60
 
58
61
  export interface PromptAndWaitOptions extends PromptOptions {
@@ -63,13 +66,21 @@ export interface PromptAndWaitOptions extends PromptOptions {
63
66
  // promptId = 本回合 user 消息 id,是「直答归属本回合」的精确锚点(共享会话下
64
67
  // 「baseline 后第一条 assistant」会抓到别回合的产物)。
65
68
  onAccepted?: (info: { promptId: string; baseline: number }) => void
69
+ // DEF-qqbot-20261112-1:本回合会话的项目目录——权限轮询 list 与裁决 reply 的
70
+ // x-opencode-directory 值;引擎待审按 location 实例分仓,不带必查空/404。
71
+ // ★ 头链路边界(2026-11-17 固化):全链仅本文件 4 处注入(list/reply ×2 组),
72
+ // 新增引擎调用若涉权限/待审数据,必须评估是否带 directory——「漏带」的失效
73
+ // 模式是静默查空(404 被 catch 吞),不留痕——审计靠 grep 本字段的全量命中点。
74
+ // 锚定≠绑定时目录必须来自锚定会话服务端回读(bridge.ts 1461-1466),禁沿用绑定缓存。
75
+ directory?: string
66
76
  // 轮询中发现待审批权限时调用;返回用户的审批决策后,promptAndWait 负责
67
77
  // POST reply 并继续等待 idle。审批等待时间不计入 5 分钟超时。
68
78
  onPermission?: (req: PermissionRequest) => Promise<PermissionDecision>
69
79
  // reply POST 成功后回调(确认消息在服务端受理后再发,避免误导)
70
80
  onPermissionReplied?: (decision: PermissionDecision) => void
71
- // reply 404 = 请求已在其他端(桌面)被处理:不致命,任务继续,仅需提示
72
- onPermissionConflict?: () => void
81
+ // reply 404 = 请求已在其他端(桌面/引擎自动放行)被处理:不致命,任务继续。
82
+ // 2026-11-07:回调带裁决值——「拒绝」遇 404 说明动作可能已执行,须告警(DEF-qqbot-20261107-1)。
83
+ onPermissionConflict?: (decision: PermissionDecision) => void
73
84
  }
74
85
 
75
86
  export interface MessagePart {
@@ -82,8 +93,10 @@ export interface MessagePart {
82
93
  export interface SessionMessage {
83
94
  id?: string
84
95
  type?: string
85
- time?: { created?: number; completed?: number }
96
+ time?: { created?: number; firstToken?: number; streamed?: number; completed?: number }
86
97
  content?: MessagePart[]
98
+ /** 运行时工具段(REST 实际返回 tool parts;类型补录 2026-11-10 终稿提取用) */
99
+ parts?: Array<{ type?: string; tool?: string; state?: { status?: string } }>
87
100
  finish?: string
88
101
  text?: string
89
102
  model?: { id?: string; providerID?: string }
@@ -97,7 +110,30 @@ export interface OpencodeClient {
97
110
  session: {
98
111
  create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
99
112
  list(): Promise<{ data?: unknown[] }>
113
+ /** 会话详情(location.directory=项目归属;model/agent=会话级设置,切换回读/显示锚点用) */
114
+ get(opts: { path: { id: string } }): Promise<{
115
+ data?: {
116
+ id?: string
117
+ title?: string
118
+ location?: { directory?: string }
119
+ model?: { id?: string; providerID?: string; variant?: string }
120
+ agent?: string
121
+ }
122
+ }>
123
+ /** 设置会话项目归属(POST /session/{id}/move;directory=绝对路径) */
124
+ move(opts: { path: { id: string }; body: { directory: string } }): Promise<unknown>
100
125
  abort(opts: { path: { id: string } }): Promise<unknown>
126
+ /** 官方斜杠命令直通(/goal /compact /redo /btw,2026-11-23):引擎内置实现,
127
+ * POST /session/{id}/command——与桌面端同一语义(goal 审查器/轮数上限在引擎侧)。 */
128
+ command(opts: { path: { id: string }; body: { name: string; text: string } }): Promise<unknown>
129
+ /**
130
+ * 会话回滚(官方 /undo 语义,opencode.ai/docs/snapshots 为准):
131
+ * stage=在指定消息处立可逆边界(files=true 恢复边界后 assistant 改动的文件);
132
+ * commit=提交暂存回滚;delete=取消暂存。会话运行中拒绝(须先 abort)。
133
+ */
134
+ revertStage(opts: { path: { id: string }; body: { messageID: string; files?: boolean } }): Promise<unknown>
135
+ revertCommit(opts: { path: { id: string } }): Promise<unknown>
136
+ revertDiscard(opts: { path: { id: string } }): Promise<unknown>
101
137
  messages(opts: {
102
138
  path: { id: string }
103
139
  query?: { limit?: number; cursor?: string }
@@ -107,8 +143,18 @@ export interface OpencodeClient {
107
143
  setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
108
144
  }
109
145
  permission: {
110
- list(): Promise<{ data?: PermissionRequest[] }>
111
- reply(opts: { path: { sessionID: string; requestID: string }; body: { decision: PermissionDecision } }): Promise<unknown>
146
+ /** DEF-qqbot-20261112-1:引擎待审批按 location 实例分仓,裸查只命中服务端 cwd
147
+ * 实例——必须带会话自身目录(x-opencode-directory);缺省=裸查(旧行为兼容) */
148
+ list(opts?: { directory?: string }): Promise<{ data?: PermissionRequest[] }>
149
+ /** DEF-qqbot-20261112-4(抄袭桌面形态):引擎对该端点按会话自身实例路由
150
+ * (FormLocationMiddleware 同款模式)——跨实例天然正确,零 directory 簿记 */
151
+ forSession(sessionID: string): Promise<{ data?: PermissionRequest[] }>
152
+ reply(opts: {
153
+ path: { sessionID: string; requestID: string }
154
+ body: { decision: PermissionDecision }
155
+ /** 同 list:reply 端点按调用方上下文实例解析请求,不带目录对项目会话必 404 */
156
+ directory?: string
157
+ }): Promise<unknown>
112
158
  }
113
159
  // L 项(2026-10-30):V2 Form API——按会话列表(实测 GET /api/form 是 location 维度,
114
160
  // bot 进程 cwd 与会话项目不一致会漏;会话级列表才可靠)+ 作答
@@ -140,6 +186,13 @@ function turnTimeoutMinutes(): number {
140
186
  function responseTimeoutMs(): number {
141
187
  return turnTimeoutMinutes() * 60 * 1000
142
188
  }
189
+ // DEF-20261119-P11:单 API 调用超时(req 层 AbortSignal.timeout)。须显著小于
190
+ // 回合 deadline,保证「挂起的调用先抛错、deadline 判定仍可达」。env 可覆盖。
191
+ function apiCallTimeoutMs(): number {
192
+ const n = Number(process.env.QQ_API_CALL_TIMEOUT_MS ?? "30000")
193
+ return Number.isFinite(n) && n > 0 ? n : 30_000
194
+ }
195
+ const API_CALL_TIMEOUT_MS = apiCallTimeoutMs()
143
196
 
144
197
  // 取 baseline 之后最后一个有正文的 assistant 消息,丢弃 reasoning/tool 与阶段前导语。
145
198
  // 长回合会产生多条“正在检查/进度总结”assistant 文本;全部拼接会把过程包装成多条
@@ -170,6 +223,24 @@ export interface TurnState {
170
223
  hasIdle: boolean
171
224
  /** 本回合(或旧判据窗口内)最终 assistant 正文;无正文为空串 */
172
225
  text: string
226
+ /** DEF-qqbot-20261107-P2:本回合已被同会话新输入接管(runner 接管语义,
227
+ * 回合已死,idle/正文永远不会到来);前台/后台等待方据此按「被打断」终态结算 */
228
+ superseded: boolean
229
+ /** DEF-qqbot-20261112-2:text 所在 assistant 消息是否已终结(time.completed)。
230
+ * 正文可能已流式落库但消息未完成(典型=工具阻塞在权限审批)——此时正文≠回合已完,
231
+ * 完成判定必须继续等 idle/正文终结;引擎 step.ended/failed/interrupted 均落 completed,
232
+ * 被杀回合不受影响。未锚定回落路径不应用该守卫,恒 true。 */
233
+ textCompleted: boolean
234
+ }
235
+
236
+ /** DEF-qqbot-20261107-P2(2026-11-07):本回合被同会话新输入接管。
237
+ * 前台/后台等待方捕获后给用户可见交代并按 superseded 销账——不等 30 分钟超时、
238
+ * 不谎称「转后台继续执行」、不再交付占位符。 */
239
+ export class SupersededError extends Error {
240
+ constructor(readonly sessionId: string) {
241
+ super(`superseded: 会话 ${sessionId} 的回合被同会话新输入接管`)
242
+ this.name = "SupersededError"
243
+ }
173
244
  }
174
245
 
175
246
  export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline: number): TurnState {
@@ -194,7 +265,13 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
194
265
  if (userIdx < 0) {
195
266
  // 回落旧判据:行为与 collectReplyText 时代一致,不引入新风险
196
267
  const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
197
- return { anchored: false, hasIdle: Boolean(idle), text: collectReplyText(msgs, baseline) }
268
+ return {
269
+ anchored: false,
270
+ hasIdle: Boolean(idle),
271
+ text: collectReplyText(msgs, baseline),
272
+ superseded: false,
273
+ textCompleted: true, // 回落路径不应用 textCompleted 守卫(后台 finish 只信 anchored)
274
+ }
198
275
  }
199
276
  let end = ordered.length
200
277
  for (let i = userIdx + 1; i < ordered.length; i++) {
@@ -205,6 +282,7 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
205
282
  }
206
283
  const boundary = ordered.slice(userIdx + 1, end)
207
284
  let text = ""
285
+ let textCompleted = false
208
286
  for (let i = boundary.length - 1; i >= 0; i--) {
209
287
  const m = boundary[i]
210
288
  if (m.type !== "assistant") continue
@@ -215,18 +293,69 @@ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline:
215
293
  .trim()
216
294
  if (joined) {
217
295
  text = joined
296
+ // DEF-qqbot-20261112-2:正文消息是否已终结——权限挂起中消息 streamed 但无
297
+ // completed,正文已见而回合未完(2026-11-12 ZERO2 实证:此类回合被误结、
298
+ // 交付「无文本产出」假完成)
299
+ textCompleted = Boolean(m.time?.completed)
218
300
  break
219
301
  }
220
302
  }
303
+ // 防线 A 修正(2026-11-07 第二版,实测早交后钉死):下一 user 接替判 done 必须
304
+ // 以「本回合正文已落库」为守卫——POST /prompt 受理即建 user 行(排队消息不等
305
+ // 前回合结束),无守卫会把「正文未生成的进行中回合」判 done,交付
306
+ // (AI 未返回内容) 且丢失真实答案(11-07 10:16 实证)。正文在=回合实质已完,
307
+ // 接替判据才安全;正文空则继续等 idle/正文。
308
+ const nextTurnStarted = end < ordered.length && Boolean(text)
309
+ // DEF-qqbot-20261107-P2(11-07 10:16/10:29 实证 ×2):OpenCode V2 runner 对忙会话的
310
+ // 新 /prompt 是「接管」语义——新 user 行受理即在途回合被 打断(消息链实证:assistant
311
+ // finish=tool_calls 后无第二步,死回合)。防线 A 守卫只防早交占位符,防不了「等一个
312
+ // 永远不会来的 idle/正文」:死回合会挂到前台 30 分钟超时,转后台还谎称任务继续执行。
313
+ // 判定口径:边界内无正文、无 idle(回合未完),但边界外(下一条 user 行之后)已出现
314
+ // assistant/idle 活动 → runner 已在推进后续回合,本回合死亡。正文已落库或本回合 idle
315
+ // 已现时不适用(superseded 仅在 !text 下计算,正常终结维持原判定)。
316
+ let superseded = false
317
+ if (!text && end < ordered.length) {
318
+ const lastBoundaryCreated = boundary.length
319
+ ? (boundary[boundary.length - 1].time?.created ?? 0)
320
+ : (ordered[userIdx].time?.created ?? 0)
321
+ superseded = ordered
322
+ .slice(end + 1)
323
+ .some((m) => (m.type === "assistant" || m.type === "idle") && (m.time?.created ?? 0) > lastBoundaryCreated)
324
+ }
221
325
  return {
222
326
  anchored: true,
223
- hasIdle: boundary.some((m) => m.type === "idle"),
327
+ hasIdle: boundary.some((m) => m.type === "idle") || nextTurnStarted,
224
328
  text,
329
+ superseded,
330
+ textCompleted,
225
331
  }
226
332
  }
227
333
 
228
334
  let client: OpencodeClient | null = null
229
335
 
336
+ /**
337
+ * DEF-qqbot-20261110-9 归属守卫(纯函数,导出供测试):
338
+ * anchored=false 的回落命中是否属于「邻回合答案」——命中的 assistant 正文若位于
339
+ * 消息窗口中最后一条 user 行之前,则它属于更早的回合(本回合 user 尚未落库),
340
+ * 回落不得取用它(否则该回合被假完成,内容再被 24h 去重拦截后无声消失)。
341
+ */
342
+ export function fallbackAnswerStolen(msgs: Array<{ type?: string; content?: Array<{ type?: string; text?: string }> }>, text: string): boolean {
343
+ if (!text.trim()) return false
344
+ let lastUserIdx = -1
345
+ msgs.forEach((m, i) => {
346
+ if (m.type === "user") lastUserIdx = i
347
+ })
348
+ if (lastUserIdx < 0) return false
349
+ const needle = text.trim()
350
+ const idx = msgs.findIndex(
351
+ (m, i) =>
352
+ m.type === "assistant" &&
353
+ i < lastUserIdx &&
354
+ (m.content ?? []).some((p) => p.type === "text" && typeof p.text === "string" && p.text.trim() === needle),
355
+ )
356
+ return idx >= 0
357
+ }
358
+
230
359
  function sleep(ms: number): Promise<void> {
231
360
  return new Promise((resolve) => setTimeout(resolve, ms))
232
361
  }
@@ -245,6 +374,11 @@ export function createClient(baseUrl: string): OpencodeClient {
245
374
  async function req(path: string, init?: RequestInit): Promise<Response> {
246
375
  return fetch(base + path, {
247
376
  ...init,
377
+ // DEF-20261119-P11:per-call 超时兜底——引擎挂起时裸 fetch 无限等,把
378
+ // promptAndWait 的 deadline 判定彻底封死(10:00 实证:/message 挂 33 分钟,
379
+ // 转后台/停滞提醒/对账全链停摆;亦是 DEF-20261119-P7 僵尸 bgWait 的同根候选)。
380
+ // 显式 signal 优先;AbortSignal.timeout 缺失(旧运行时)静默降级为原行为。
381
+ signal: init?.signal ?? AbortSignal.timeout?.(API_CALL_TIMEOUT_MS),
248
382
  headers: { ...authHeaders, ...((init?.headers as Record<string, string>) ?? {}) },
249
383
  })
250
384
  }
@@ -253,7 +387,17 @@ export function createClient(baseUrl: string): OpencodeClient {
253
387
  if (!res.ok) {
254
388
  const txt = await res.text().catch(() => "")
255
389
  const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt
256
- throw new Error(`OpenCode API ${res.status}: ${excerpt}`)
390
+ // DEF-20261119-P9:429 带 Retry-After 时把暗示值透出(机器可读标记),
391
+ // 让上层退避按服务端节奏走,而非固定 20s(UAT SY-004 注入实证)。
392
+ const retryAfter = res.status === 429 ? res.headers.get("retry-after") : null
393
+ const err = new Error(
394
+ `OpenCode API ${res.status}: ${excerpt}${retryAfter ? ` [retry-after:${retryAfter}]` : ""}`,
395
+ )
396
+ // 完整响应体挂 error.body(不截断)——错误通道的结构化状态(如 goal 的
397
+ // CommandExecutionError 审计长文)由上层按 body 解析;截断的 excerpt 仅供日志
398
+ //(真机实证 11-23:200 字截断切断长 JSON,上层状态解析失配退化成失败文案)。
399
+ ;(err as { body?: string }).body = txt
400
+ throw err
257
401
  }
258
402
  // 204 (如 /model /agent /permission reply) 无 body;res.json() 会抛错。
259
403
  if (res.status === 204) return null
@@ -282,9 +426,27 @@ export function createClient(baseUrl: string): OpencodeClient {
282
426
  async list() {
283
427
  return json(await req("/session"))
284
428
  },
429
+ async get(opts) {
430
+ return json(await req(`/session/${opts.path.id}`))
431
+ },
432
+ async move(opts) {
433
+ return json(await req(`/session/${opts.path.id}/move`, { method: "POST", body: JSON.stringify(opts.body) }))
434
+ },
285
435
  async abort(opts) {
286
436
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
287
437
  },
438
+ async command(opts) {
439
+ return json(await req(`/session/${opts.path.id}/command`, { method: "POST", body: JSON.stringify(opts.body) }))
440
+ },
441
+ async revertStage(opts) {
442
+ return json(await req(`/session/${opts.path.id}/revert/stage`, { method: "POST", body: JSON.stringify(opts.body) }))
443
+ },
444
+ async revertCommit(opts) {
445
+ return json(await req(`/session/${opts.path.id}/revert/commit`, { method: "POST", body: "{}" }))
446
+ },
447
+ async revertDiscard(opts) {
448
+ return json(await req(`/session/${opts.path.id}/revert`, { method: "DELETE" }))
449
+ },
288
450
  async messages(opts) {
289
451
  const query = new URLSearchParams()
290
452
  if (opts.query?.limit !== undefined) query.set("limit", String(opts.query.limit))
@@ -304,14 +466,22 @@ export function createClient(baseUrl: string): OpencodeClient {
304
466
  },
305
467
 
306
468
  permission: {
307
- async list() {
308
- return json(await req("/permission/request"))
469
+ async list(opts) {
470
+ return json(
471
+ await req("/permission/request", {
472
+ headers: opts?.directory ? { "x-opencode-directory": opts.directory } : undefined,
473
+ }),
474
+ )
475
+ },
476
+ async forSession(sessionID) {
477
+ return json(await req(`/session/${sessionID}/permission`))
309
478
  },
310
479
  async reply(opts) {
311
480
  return json(
312
481
  await req(`/session/${opts.path.sessionID}/permission/${opts.path.requestID}/reply`, {
313
482
  method: "POST",
314
483
  body: JSON.stringify(opts.body),
484
+ headers: opts.directory ? { "x-opencode-directory": opts.directory } : undefined,
315
485
  }),
316
486
  )
317
487
  },
@@ -359,9 +529,14 @@ export function createClient(baseUrl: string): OpencodeClient {
359
529
  },
360
530
 
361
531
  async promptAndWait(sessionId, text, options) {
362
- // v2: prompt body 只接受 {text,...}(additionalProperties:false),model/agent
363
- // 会被静默剥离 —— 不再往 body 里塞;模型/agent 由 SessionManager 走 session 级端点。
364
- const body: { text: string; files?: Array<{ uri: string; name?: string }> } = { text }
532
+ // v2: model/agent 会被 additionalProperties:false 静默剥离 —— 不往 body 里塞;
533
+ // 模型/agent 由 SessionManager 走 session 级端点。
534
+ // delivery:"steer"(SDK V2SessionPromptData.body 已实证支持):声明前台在场,
535
+ // 引擎审批门据此闭合(design §3.2/§4「steer 前台在场语义」)。
536
+ const body: { text: string; files?: Array<{ uri: string; name?: string }>; delivery: "steer" } = {
537
+ text,
538
+ delivery: "steer",
539
+ }
365
540
  if (options?.files?.length) body.files = options.files
366
541
 
367
542
  // 债务D1:子会话(subagent)审批检测——session 详情带 parentID
@@ -401,6 +576,7 @@ export function createClient(baseUrl: string): OpencodeClient {
401
576
  const deadline = Date.now() + responseTimeoutMs()
402
577
  let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
403
578
  const handledPermissions = new Set<string>()
579
+ let consecutivePollFails = 0 // P11:引擎瞬时挂起按次容错,连续 N 次才按超时终态抛
404
580
 
405
581
  while (Date.now() - permissionWaitMs < deadline) {
406
582
  await sleep(1000)
@@ -408,7 +584,11 @@ export function createClient(baseUrl: string): OpencodeClient {
408
584
  // 审批检测:会话阻塞在权限请求上时不会产生 idle,必须先放行。
409
585
  if (options?.onPermission) {
410
586
  try {
411
- const permJson = await json(await req("/permission/request"))
587
+ const permJson = await json(
588
+ await req("/permission/request", {
589
+ headers: options.directory ? { "x-opencode-directory": options.directory } : undefined,
590
+ }),
591
+ )
412
592
  const all = (permJson?.data ?? []) as PermissionRequest[]
413
593
  // 债务D1:主会话请求 + 子会话(subagent,parentID 指向本会话)请求
414
594
  const pending: PermissionRequest[] = []
@@ -431,10 +611,11 @@ export function createClient(baseUrl: string): OpencodeClient {
431
611
  const replyRes = await req(`/session/${request.sessionID}/permission/${request.id}/reply`, {
432
612
  method: "POST",
433
613
  body: JSON.stringify({ decision }),
614
+ headers: options.directory ? { "x-opencode-directory": options.directory } : undefined,
434
615
  })
435
616
  if (replyRes.status === 404) {
436
617
  // 债务D2:请求已被其他端(桌面)先处理——不是错误,任务继续
437
- options?.onPermissionConflict?.()
618
+ options?.onPermissionConflict?.(decision)
438
619
  } else {
439
620
  await json(replyRes)
440
621
  options?.onPermissionReplied?.(decision)
@@ -448,18 +629,47 @@ export function createClient(baseUrl: string): OpencodeClient {
448
629
  }
449
630
  }
450
631
 
451
- const listJson = await json(await req(`/session/${sessionId}/message`))
452
- const msgs: SessionMessage[] = listJson?.data ?? []
453
- // Completion = the idle marker of THIS turn (修复⑧ 回合边界归属)。
454
- // Tool-using turns emit several assistant messages (reasoning+tool) before
455
- // the final text one, so "first completed assistant" would return an empty
456
- // tool message. 共享会话下别回合的 idle/assistant 都不再计入本回合判定。
457
- const turn = turnStateOf(msgs, promptId, baseline)
458
- if (turn.hasIdle) {
459
- // Aggregate text parts from ALL assistant messages of this turn,
460
- // dropping reasoning/tool parts. In practice only the final assistant
461
- // carries text; earlier ones are reasoning+tool.
462
- return turn.text || "(AI 未返回内容)"
632
+ // DEF-qqbot-20261105-P1 防线 A 配套(2026-11-07):裸 /message 默认只回
633
+ // 50 条——长会话里占回合之后的 idle/下一 user 证据被窗口截断,回合
634
+ // 完成却判不出 done,悬挂至 30 分钟超时(11-07 实证 6 分钟悬挂+完整
635
+ // 消息链取证)。显式 limit=200 扩大判定窗口(与 fetchRecoveryMessages
636
+ // 同档;极端长会话由防线 A 的「下一 user 接替」判据兜住边界)。
637
+ // P11(2026-11-19):整个判定迭代包在容错里——req 层 AbortSignal.timeout
638
+ // 会抛错,瞬时挂起计入连续失败次数后继续轮询;连续 3 次才按「引擎持续
639
+ // 无响应」终态抛错(走调用方响应超时→转后台路径接管)。SupersededError
640
+ // 是正常终态不是故障,必须穿透不计数。
641
+ try {
642
+ const listJson = await json(await req(`/session/${sessionId}/message?limit=200`))
643
+ consecutivePollFails = 0
644
+ const msgs: SessionMessage[] = listJson?.data ?? []
645
+ // Completion = the idle marker of THIS turn (修复⑧ 回合边界归属)。
646
+ // Tool-using turns emit several assistant messages (reasoning+tool) before
647
+ // the final text one, so "first completed assistant" would return an empty
648
+ // tool message. 共享会话下别回合的 idle/assistant 都不再计入本回合判定。
649
+ const turn = turnStateOf(msgs, promptId, baseline)
650
+ if (turn.hasIdle) {
651
+ // DEF-qqbot-20261110-9(2026-11-10 回归实证):anchored=false 回落命中时
652
+ // 必须校验答案归属——若命中正文属于「最后一条 user 行之前」的更早回合
653
+ //(本回合 user 尚未落库、回落把邻回合答案亮出来),不得张冠李戴,
654
+ // 继续等本回合落库;否则该回合会被邻回合答案"假完成"并在去重拦截后
655
+ // 无声消失。
656
+ if (!turn.anchored && turn.text && fallbackAnswerStolen(msgs, turn.text)) {
657
+ console.log(`[opencode] 回落答案归属邻回合,弃用继续等 prompt=${promptId}`)
658
+ } else {
659
+ // Aggregate text parts from ALL assistant messages of this turn,
660
+ // dropping reasoning/tool parts. In practice only the final assistant
661
+ // carries text; earlier ones are reasoning+tool.
662
+ return turn.text || "(AI 未返回内容)"
663
+ }
664
+ }
665
+ if (turn.superseded) throw new SupersededError(sessionId)
666
+ } catch (error) {
667
+ if (error instanceof SupersededError) throw error
668
+ consecutivePollFails++
669
+ console.error(`[opencode] 回合轮询失败(第${consecutivePollFails}次):`, error instanceof Error ? error.message : error)
670
+ if (consecutivePollFails >= 3) {
671
+ throw new Error(`AI 响应超时(引擎连续 ${consecutivePollFails} 次无响应)`)
672
+ }
463
673
  }
464
674
  }
465
675
  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 class EventStream {
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
- 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 = ""
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)
@@ -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
- if (text.trim()) lines.push(`🧑 ${clipBlock(redactSecrets(text.trim()), userClip)}`)
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(`🤖 ${clipBlock(redactSecrets(p.text.trim()), textClip)}`)
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 }