@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.
Files changed (46) hide show
  1. package/README.md +12 -7
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +4 -4
  5. package/dist/openqq-bot.js +1072 -208
  6. package/package.json +2 -2
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +141 -15
  9. package/src/commands.ts +554 -554
  10. package/src/config.ts +118 -121
  11. package/src/core/bot-launcher.ts +146 -146
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +115 -18
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -33
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +388 -72
  19. package/src/core/form-journal.ts +214 -0
  20. package/src/core/gateway-state.ts +68 -0
  21. package/src/core/inbound-dedupe.ts +43 -0
  22. package/src/core/inflight-journal.ts +170 -22
  23. package/src/core/instance-lock.ts +28 -1
  24. package/src/core/linkwatch.ts +195 -195
  25. package/src/core/message-queue.ts +11 -0
  26. package/src/core/mirror.ts +182 -182
  27. package/src/core/outbox.ts +522 -0
  28. package/src/core/permission.ts +301 -301
  29. package/src/core/reply-limiter.ts +106 -106
  30. package/src/core/send-media.ts +90 -90
  31. package/src/core/util.ts +8 -8
  32. package/src/index.ts +162 -162
  33. package/src/opencode/_FOLDER.md +11 -11
  34. package/src/opencode/client.ts +98 -13
  35. package/src/opencode/eventstream.ts +138 -138
  36. package/src/opencode/history.ts +143 -143
  37. package/src/opencode/mirror.ts +85 -85
  38. package/src/opencode/sessions.ts +158 -158
  39. package/src/plugin-entry.ts +112 -112
  40. package/src/qq/_FOLDER.md +13 -13
  41. package/src/qq/api.ts +546 -539
  42. package/src/qq/gateway.ts +69 -20
  43. package/src/qq/media.ts +219 -219
  44. package/src/qq/sender.ts +303 -300
  45. package/src/qq/types.ts +154 -154
  46. package/tsconfig.json +24 -24
package/src/index.ts CHANGED
@@ -1,162 +1,162 @@
1
- // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
- // @output: (side-effect) 启动 Bot 进程
3
- // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
- import { loadConfig, ensureConfig } from "./config.js"
5
- import { mkdirSync, writeFileSync } from "fs"
6
- import { join } from "path"
7
- import { homedir } from "os"
8
- import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
9
- import { discoverOpencode, persistDiscovery } from "./core/discovery.js"
10
- import { startLinkWatch } from "./core/linkwatch.js"
11
- import { getAccessToken, sendC2CMessage, getNextMsgSeq } from "./qq/api.js"
12
- import { SessionManager } from "./opencode/sessions.js"
13
- import { startGateway } from "./qq/gateway.js"
14
- import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
15
- import { createBridge } from "./bridge.js"
16
- import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
17
-
18
- // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
19
- // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
20
- // 退避后服务就绪即起,不再依赖下个看门狗 tick。
21
- // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
22
- // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
23
- // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
24
- async function waitForOpencode(
25
- clientFactory: (url: string) => OpencodeClient,
26
- initialUrl: string,
27
- ): Promise<OpencodeClient> {
28
- const deadline = Date.now() + 15 * 60 * 1000
29
- let attempt = 0
30
- let url = initialUrl
31
- let client = clientFactory(url)
32
- for (;;) {
33
- try {
34
- await healthCheck(client)
35
- return client
36
- } catch (error) {
37
- attempt++
38
- if (Date.now() >= deadline) throw error
39
- console.log(
40
- `[index] OpenCode 未就绪(第 ${attempt} 次):${error instanceof Error ? error.message : error} —20s 后重试`,
41
- )
42
- if (attempt === 1 || attempt % 3 === 0) {
43
- const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
44
- if (found && found.baseUrl !== url) {
45
- console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
46
- persistDiscovery(found)
47
- url = found.baseUrl
48
- client = clientFactory(url)
49
- }
50
- }
51
- await new Promise((r) => setTimeout(r, 20_000))
52
- }
53
- }
54
- }
55
-
56
- async function main(): Promise<void> {
57
- // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
58
- // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
59
- if (process.env.QQ_LOG_FILE) {
60
- const { installFileLog } = await import("./core/file-log.js")
61
- installFileLog(process.env.QQ_LOG_FILE)
62
- }
63
- await ensureConfig()
64
- const config = loadConfig()
65
-
66
- // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
67
- // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
68
- // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
69
- // 场景:多 location 并发拉起时防待命实例堆积)。
70
- let instanceLock: InstanceLock | null = null
71
- const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
72
- if (lockMode === "try") {
73
- instanceLock = acquireInstanceLock(config.qq.appId)
74
- if (!instanceLock) {
75
- console.log("[index] 已有实例在运行(try 模式),本实例退出")
76
- process.exit(0)
77
- }
78
- } else if (lockMode !== "false") {
79
- instanceLock = await waitInstanceLock(config.qq.appId)
80
- }
81
-
82
- if (!config.opencode.baseUrl) {
83
- throw new Error("缺少 OPENCODE_BASE_URL,指向 OpenCode 桌面版 API(如 http://127.0.0.1:<端口>/api;2.1.x 端口动态,失联时启动流程会自动发现)")
84
- }
85
-
86
- const client = await waitForOpencode((u) => createClient(u), config.opencode.baseUrl)
87
-
88
- startBackgroundTokenRefresh(config.qq.appId, config.qq.clientSecret)
89
-
90
- const sessions = new SessionManager(client)
91
- const bridge = createBridge(config, client, sessions)
92
- const { eventStream } = bridge
93
-
94
- // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
95
- // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
96
- // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
97
- const alarm = async (text: string): Promise<void> => {
98
- const uid = config.allowedUsers[0]
99
- if (!uid) return
100
- const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
101
- const seq = getNextMsgSeq("")
102
- try {
103
- await sendC2CMessage(token, uid, text, undefined, seq, true)
104
- } catch (error) {
105
- console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
106
- await sendC2CMessage(token, uid, text, undefined, seq, false)
107
- }
108
- }
109
- const linkWatch = startLinkWatch({ client, onRebase: (url) => eventStream.rebase(url), alarm })
110
-
111
- const gateway = await startGateway({
112
- appId: config.qq.appId,
113
- clientSecret: config.qq.clientSecret,
114
- onMessage: bridge.handleMessage,
115
- onInteraction: (event) => bridge.handleInteraction(event),
116
- onReady: () => {
117
- console.log("[index] QQ Gateway 已就绪")
118
- },
119
- })
120
-
121
- console.log("[index] OpenCode QQ Bot 已启动")
122
-
123
- // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
124
- //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。
125
- void bridge.recoverInflightRounds()
126
-
127
- // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
128
- // 看门狗据此识别"进程在但僵死"的静默僵尸(2-day silent zombie 教训)。
129
- const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
130
- const touchHeartbeat = (): void => {
131
- try {
132
- mkdirSync(join(homedir(), ".openqq"), { recursive: true })
133
- writeFileSync(heartbeatFile, String(Date.now()))
134
- } catch (error) {
135
- console.error("[index] 心跳写入失败:", error)
136
- }
137
- }
138
- touchHeartbeat()
139
- const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
140
-
141
- let shuttingDown = false
142
- const shutdown = (signal: string): void => {
143
- if (shuttingDown) return
144
- shuttingDown = true
145
- console.log(`[index] 收到 ${signal},开始退出...`)
146
- clearInterval(heartbeatTimer)
147
- instanceLock?.release()
148
- linkWatch.stop()
149
- gateway.stop()
150
- stopBackgroundTokenRefresh()
151
- setTimeout(() => process.exit(0), 0)
152
- }
153
-
154
- process.once("SIGINT", () => shutdown("SIGINT"))
155
- process.once("SIGTERM", () => shutdown("SIGTERM"))
156
- }
157
-
158
- main().catch((error) => {
159
- console.error("[index] 启动失败:", error)
160
- stopBackgroundTokenRefresh()
161
- process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
162
- })
1
+ // @input: ./config, ./opencode/*, ./qq/*, ./bridge, @opencode-ai/sdk (createOpencodeServer)
2
+ // @output: (side-effect) 启动 Bot 进程
3
+ // @pos: 根层 - 入口: 启动编排 + 优雅关闭
4
+ import { loadConfig, ensureConfig } from "./config.js"
5
+ import { mkdirSync, writeFileSync } from "fs"
6
+ import { join } from "path"
7
+ import { homedir } from "os"
8
+ import { createClient, healthCheck, type OpencodeClient } from "./opencode/client.js"
9
+ import { discoverOpencode, persistDiscovery } from "./core/discovery.js"
10
+ import { startLinkWatch } from "./core/linkwatch.js"
11
+ import { getAccessToken, sendC2CMessage, getNextMsgSeq } from "./qq/api.js"
12
+ import { SessionManager } from "./opencode/sessions.js"
13
+ import { startGateway } from "./qq/gateway.js"
14
+ import { startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./qq/api.js"
15
+ import { createBridge } from "./bridge.js"
16
+ import { waitInstanceLock, acquireInstanceLock, INSTANCE_LOCK_DISABLED_ENV, type InstanceLock } from "./core/instance-lock.js"
17
+
18
+ // O1(2026-10-15):开机竞态退避等待——桌面服务未就绪时 20s 重试、15 分钟
19
+ // 上限。今晨实证(09:04–09:31):fail-fast 秒退 → 看门狗 10 分钟粒度空转 4 次;
20
+ // 退避后服务就绪即起,不再依赖下个看门狗 tick。
21
+ // HC1(2026-10-26):2.1.3 服务端口动态化(实证 49374→28894)。连不上时在
22
+ // 第 1/4/7… 次重试前触发回环端口签名扫描,命中即重建 client 并落盘
23
+ // ~/.openqq/last-discovered.json。.env 配置仍是第一优先,配置可达时零扫描。
24
+ async function waitForOpencode(
25
+ clientFactory: (url: string) => OpencodeClient,
26
+ initialUrl: string,
27
+ ): Promise<OpencodeClient> {
28
+ const deadline = Date.now() + 15 * 60 * 1000
29
+ let attempt = 0
30
+ let url = initialUrl
31
+ let client = clientFactory(url)
32
+ for (;;) {
33
+ try {
34
+ await healthCheck(client)
35
+ return client
36
+ } catch (error) {
37
+ attempt++
38
+ if (Date.now() >= deadline) throw error
39
+ console.log(
40
+ `[index] OpenCode 未就绪(第 ${attempt} 次):${error instanceof Error ? error.message : error} —20s 后重试`,
41
+ )
42
+ if (attempt === 1 || attempt % 3 === 0) {
43
+ const found = await discoverOpencode({ password: process.env.OPENCODE_PASSWORD })
44
+ if (found && found.baseUrl !== url) {
45
+ console.log(`[index] 端口漂移自动发现:${url} → ${found.baseUrl}(v${found.version}),改用之`)
46
+ persistDiscovery(found)
47
+ url = found.baseUrl
48
+ client = clientFactory(url)
49
+ }
50
+ }
51
+ await new Promise((r) => setTimeout(r, 20_000))
52
+ }
53
+ }
54
+ }
55
+
56
+ async function main(): Promise<void> {
57
+ // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
58
+ // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
59
+ if (process.env.QQ_LOG_FILE) {
60
+ const { installFileLog } = await import("./core/file-log.js")
61
+ installFileLog(process.env.QQ_LOG_FILE)
62
+ }
63
+ await ensureConfig()
64
+ const config = loadConfig()
65
+
66
+ // M 项(2026-10-30,吸收竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
67
+ // 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
68
+ // 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
69
+ // 场景:多 location 并发拉起时防待命实例堆积)。
70
+ let instanceLock: InstanceLock | null = null
71
+ const lockMode = process.env[INSTANCE_LOCK_DISABLED_ENV] ?? ""
72
+ if (lockMode === "try") {
73
+ instanceLock = acquireInstanceLock(config.qq.appId)
74
+ if (!instanceLock) {
75
+ console.log("[index] 已有实例在运行(try 模式),本实例退出")
76
+ process.exit(0)
77
+ }
78
+ } else if (lockMode !== "false") {
79
+ instanceLock = await waitInstanceLock(config.qq.appId)
80
+ }
81
+
82
+ if (!config.opencode.baseUrl) {
83
+ throw new Error("缺少 OPENCODE_BASE_URL,指向 OpenCode 桌面版 API(如 http://127.0.0.1:<端口>/api;2.1.x 端口动态,失联时启动流程会自动发现)")
84
+ }
85
+
86
+ const client = await waitForOpencode((u) => createClient(u), config.opencode.baseUrl)
87
+
88
+ startBackgroundTokenRefresh(config.qq.appId, config.qq.clientSecret)
89
+
90
+ const sessions = new SessionManager(client)
91
+ const bridge = createBridge(config, client, sessions)
92
+ const { eventStream } = bridge
93
+
94
+ // HC2(2026-10-26):运行中链路自愈巡检 + QQ 告警。
95
+ // 告警走主动消息(allowlist 首个用户),markdown 失败回退纯文本;
96
+ // 去重由 linkwatch 状态机保证(每事故 open + fixed 各 ≤1 条)。
97
+ const alarm = async (text: string): Promise<void> => {
98
+ const uid = config.allowedUsers[0]
99
+ if (!uid) return
100
+ const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
101
+ const seq = getNextMsgSeq("")
102
+ try {
103
+ await sendC2CMessage(token, uid, text, undefined, seq, true)
104
+ } catch (error) {
105
+ console.warn("[index] 告警 markdown 发送失败,回退纯文本:", error instanceof Error ? error.message : error)
106
+ await sendC2CMessage(token, uid, text, undefined, seq, false)
107
+ }
108
+ }
109
+ const linkWatch = startLinkWatch({ client, onRebase: (url) => eventStream.rebase(url), alarm })
110
+
111
+ const gateway = await startGateway({
112
+ appId: config.qq.appId,
113
+ clientSecret: config.qq.clientSecret,
114
+ onMessage: bridge.handleMessage,
115
+ onInteraction: (event) => bridge.handleInteraction(event),
116
+ onReady: () => {
117
+ console.log("[index] QQ Gateway 已就绪")
118
+ },
119
+ })
120
+
121
+ console.log("[index] OpenCode QQ Bot 已启动")
122
+
123
+ // R 项(2026-10-30):启动对账——恢复重启窗口内"已派发未回答"的在途回合
124
+ //(补投答案/重挂后台等待/重派丢失消息)。异步执行不阻塞心跳建立。
125
+ void bridge.recoverInflightRounds()
126
+
127
+ // E4 心跳:每 60 秒写一次时间戳 = 事件循环存活证明。
128
+ // 看门狗据此识别"进程在但僵死"的静默僵尸(2-day silent zombie 教训)。
129
+ const heartbeatFile = join(homedir(), ".openqq", "heartbeat")
130
+ const touchHeartbeat = (): void => {
131
+ try {
132
+ mkdirSync(join(homedir(), ".openqq"), { recursive: true })
133
+ writeFileSync(heartbeatFile, String(Date.now()))
134
+ } catch (error) {
135
+ console.error("[index] 心跳写入失败:", error)
136
+ }
137
+ }
138
+ touchHeartbeat()
139
+ const heartbeatTimer = setInterval(touchHeartbeat, 60_000)
140
+
141
+ let shuttingDown = false
142
+ const shutdown = (signal: string): void => {
143
+ if (shuttingDown) return
144
+ shuttingDown = true
145
+ console.log(`[index] 收到 ${signal},开始退出...`)
146
+ clearInterval(heartbeatTimer)
147
+ instanceLock?.release()
148
+ linkWatch.stop()
149
+ gateway.stop()
150
+ stopBackgroundTokenRefresh()
151
+ setTimeout(() => process.exit(0), 0)
152
+ }
153
+
154
+ process.once("SIGINT", () => shutdown("SIGINT"))
155
+ process.once("SIGTERM", () => shutdown("SIGTERM"))
156
+ }
157
+
158
+ main().catch((error) => {
159
+ console.error("[index] 启动失败:", error)
160
+ stopBackgroundTokenRefresh()
161
+ process.exit(1) // 锁文件随之成僵尸,30s 后待命实例自动接管
162
+ })
@@ -1,11 +1,11 @@
1
- # opencode
2
-
3
- OpenCode 对接层:SDK 客户端、SSE 事件路由、会话管理。
4
-
5
- ## 文件
6
-
7
- | 文件 | 职责 |
8
- |------|------|
9
- | client.ts | OpenCode SDK 客户端封装 + 健康检查 |
10
- | events.ts | 全局 SSE 事件订阅 + 按 sessionId 分发 |
11
- | sessions.ts | QQ用户<->OpenCode Session 映射管理 |
1
+ # opencode
2
+
3
+ OpenCode 对接层:SDK 客户端、SSE 事件路由、会话管理。
4
+
5
+ ## 文件
6
+
7
+ | 文件 | 职责 |
8
+ |------|------|
9
+ | client.ts | OpenCode SDK 客户端封装 + 健康检查 |
10
+ | events.ts | 全局 SSE 事件订阅 + 按 sessionId 分发 |
11
+ | sessions.ts | QQ用户<->OpenCode Session 映射管理 |
@@ -59,6 +59,10 @@ export interface PromptAndWaitOptions extends PromptOptions {
59
59
  // 原生附件(2026-10-14):prompt body 的 files(v2 PromptInput schema 内
60
60
  // 字段,additionalProperties:false 不会剥它;model/agent 才会被剥)
61
61
  files?: Array<{ uri: string; name?: string }>
62
+ // 修复⑧(2026-11-03):受领回调——prompt 落库即回传 { promptId, baseline }。
63
+ // promptId = 本回合 user 消息 id,是「直答归属本回合」的精确锚点(共享会话下
64
+ // 「baseline 后第一条 assistant」会抓到别回合的产物)。
65
+ onAccepted?: (info: { promptId: string; baseline: number }) => void
62
66
  // 轮询中发现待审批权限时调用;返回用户的审批决策后,promptAndWait 负责
63
67
  // POST reply 并继续等待 idle。审批等待时间不计入 5 分钟超时。
64
68
  onPermission?: (req: PermissionRequest) => Promise<PermissionDecision>
@@ -111,6 +115,7 @@ export interface OpencodeClient {
111
115
  form: {
112
116
  list(input: { sessionID: string }): Promise<{ data?: FormInfo[] }>
113
117
  reply(opts: { path: { sessionID: string; formID: string }; body: { answer: Record<string, unknown> } }): Promise<unknown>
118
+ cancel(opts: { path: { sessionID: string; formID: string } }): Promise<unknown>
114
119
  }
115
120
  app: {
116
121
  agents(): Promise<{ data?: unknown[] }>
@@ -126,11 +131,15 @@ export interface OpencodeClient {
126
131
  // 常超 5 分钟——超时后答案永久丢失(实测 2026-10-13)。最终回复现已有主动
127
132
  // 消息兜底(bridge.deliver 被动失败→主动),已解耦。默认 30 分钟,
128
133
  // 可用 env OPENCODE_TURN_TIMEOUT_MINUTES 覆盖。
129
- const TURN_TIMEOUT_MINUTES = (() => {
134
+ // ★ P0 同族修复(2026-11-03):静态 const 在模块加载期捕获 env,.env 运行时才
135
+ // 注入——发布包装后 OVERRIDE 永远赶不上。改惰性函数:每次调用现场取值。
136
+ function turnTimeoutMinutes(): number {
130
137
  const n = Number(process.env.OPENCODE_TURN_TIMEOUT_MINUTES ?? "30")
131
138
  return Number.isFinite(n) && n > 0 ? n : 30
132
- })()
133
- const RESPONSE_TIMEOUT_MS = TURN_TIMEOUT_MINUTES * 60 * 1000
139
+ }
140
+ function responseTimeoutMs(): number {
141
+ return turnTimeoutMinutes() * 60 * 1000
142
+ }
134
143
 
135
144
  // 取 baseline 之后最后一个有正文的 assistant 消息,丢弃 reasoning/tool 与阶段前导语。
136
145
  // 长回合会产生多条“正在检查/进度总结”assistant 文本;全部拼接会把过程包装成多条
@@ -147,6 +156,75 @@ export function collectReplyText(msgs: SessionMessage[], baseline: number): stri
147
156
  .trim()
148
157
  }
149
158
 
159
+ // 修复⑧(2026-11-03 定案):回合边界归属——共享会话错误源实证(expA 等 21 分钟
160
+ // 拿到桌面排障报告):collectReplyText 的「baseline 后最新 assistant」在共享会话
161
+ // 会抓到别回合产物。正确口径=只取本回合自己:
162
+ // ① 定位本回合 user 行——promptId 精确匹配(prompt API 受理返回值);
163
+ // ② 兜底时间锚:created == baseline 的 user 行(受理即落库,±1s 容差错 skew);
164
+ // ③ 边界=该 user 行 → 下一条 user 行之前;hasIdle/text 都只看边界内。
165
+ // 锚点全部失配(形状变化/兼容旧数据)→ 回落旧 baseline 判据(anchored=false)。
166
+ export interface TurnState {
167
+ /** true=已按回合边界定位(text/hasIdle 只关乎本回合);false=回落旧判据 */
168
+ anchored: boolean
169
+ /** 本回合(或旧判据窗口内)是否已出现 idle 终结标记 */
170
+ hasIdle: boolean
171
+ /** 本回合(或旧判据窗口内)最终 assistant 正文;无正文为空串 */
172
+ text: string
173
+ }
174
+
175
+ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline: number): TurnState {
176
+ const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0))
177
+ let userIdx = -1
178
+ if (promptId) userIdx = ordered.findIndex((m) => m.type === "user" && m.id === promptId)
179
+ if (userIdx < 0 && baseline > 0) {
180
+ // 修复⑧时间锚兜底:baseline 即本回合 user 行 created(受理即落库),取最近命中;
181
+ // 容差 200ms 仅吸收毫秒级落库偏差,防同窗紧邻行误绑(17:37 定案:5 连发行距 ms 级,锚必最准)。
182
+ let best = -1
183
+ let bestDelta = Number.POSITIVE_INFINITY
184
+ for (let i = ordered.length - 1; i >= 0; i--) {
185
+ if (ordered[i].type !== "user") continue
186
+ const delta = Math.abs((ordered[i].time?.created ?? 0) - baseline)
187
+ if (delta < bestDelta) {
188
+ bestDelta = delta
189
+ best = i
190
+ }
191
+ }
192
+ if (best >= 0 && bestDelta <= 200) userIdx = best
193
+ }
194
+ if (userIdx < 0) {
195
+ // 回落旧判据:行为与 collectReplyText 时代一致,不引入新风险
196
+ const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
197
+ return { anchored: false, hasIdle: Boolean(idle), text: collectReplyText(msgs, baseline) }
198
+ }
199
+ let end = ordered.length
200
+ for (let i = userIdx + 1; i < ordered.length; i++) {
201
+ if (ordered[i].type === "user") {
202
+ end = i
203
+ break
204
+ }
205
+ }
206
+ const boundary = ordered.slice(userIdx + 1, end)
207
+ let text = ""
208
+ for (let i = boundary.length - 1; i >= 0; i--) {
209
+ const m = boundary[i]
210
+ if (m.type !== "assistant") continue
211
+ const joined = (m.content ?? [])
212
+ .filter((p) => p.type === "text" && p.text?.trim())
213
+ .map((p) => p.text ?? "")
214
+ .join("\n")
215
+ .trim()
216
+ if (joined) {
217
+ text = joined
218
+ break
219
+ }
220
+ }
221
+ return {
222
+ anchored: true,
223
+ hasIdle: boundary.some((m) => m.type === "idle"),
224
+ text,
225
+ }
226
+ }
227
+
150
228
  let client: OpencodeClient | null = null
151
229
 
152
230
  function sleep(ms: number): Promise<void> {
@@ -251,6 +329,9 @@ export function createClient(baseUrl: string): OpencodeClient {
251
329
  }),
252
330
  )
253
331
  },
332
+ async cancel(opts) {
333
+ return json(await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}`, { method: "DELETE" }))
334
+ },
254
335
  },
255
336
 
256
337
  app: {
@@ -311,8 +392,13 @@ export function createClient(baseUrl: string): OpencodeClient {
311
392
  // Only accept assistant messages created at/after this prompt, so a prior
312
393
  // turn's completed reply is never mistaken for this turn's answer.
313
394
  const baseline = promptJson?.data?.time?.created ?? 0
395
+ const promptId = promptJson?.data?.id ?? ""
396
+ // 修复⑧:受领即回传锚点(调用方存台账/挑选直答归属用)
397
+ if (options?.onAccepted) options.onAccepted({ promptId, baseline })
398
+ // LLM 入口实证:user 记录可核对每次真实 /prompt 受理,不再由 QQ 出站反推执行次数。
399
+ console.log(`[opencode] LLM prompt 已受理 pid=${process.pid} session=${sessionId} user=${promptJson?.data?.id ?? "?"} baseline=${baseline}`)
314
400
 
315
- const deadline = Date.now() + RESPONSE_TIMEOUT_MS
401
+ const deadline = Date.now() + responseTimeoutMs()
316
402
  let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
317
403
  const handledPermissions = new Set<string>()
318
404
 
@@ -364,20 +450,19 @@ export function createClient(baseUrl: string): OpencodeClient {
364
450
 
365
451
  const listJson = await json(await req(`/session/${sessionId}/message`))
366
452
  const msgs: SessionMessage[] = listJson?.data ?? []
367
- // Completion = the idle marker created at/after this prompt. This is the
368
- // only reliable "whole turn done" signal: tool-using turns emit several
369
- // assistant messages (reasoning+tool) before the final text one, so
370
- // "first completed assistant" would return an empty tool message.
371
- const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
372
- if (idle) {
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) {
373
459
  // Aggregate text parts from ALL assistant messages of this turn,
374
460
  // dropping reasoning/tool parts. In practice only the final assistant
375
461
  // carries text; earlier ones are reasoning+tool.
376
- const reply = collectReplyText(msgs, baseline)
377
- return reply || "(AI 未返回内容)"
462
+ return turn.text || "(AI 未返回内容)"
378
463
  }
379
464
  }
380
- throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`)
465
+ throw new Error(`AI 响应超时(${turnTimeoutMinutes()} 分钟)`)
381
466
  },
382
467
  }
383
468