@linjz/opencode-qqbot 0.3.11 → 0.3.13

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 (45) hide show
  1. package/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1056 -194
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +154 -18
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +98 -10
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. 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>
@@ -94,7 +98,10 @@ export interface OpencodeClient {
94
98
  create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
95
99
  list(): Promise<{ data?: unknown[] }>
96
100
  abort(opts: { path: { id: string } }): Promise<unknown>
97
- messages(opts: { path: { id: string } }): Promise<{ data?: SessionMessage[] }>
101
+ messages(opts: {
102
+ path: { id: string }
103
+ query?: { limit?: number; cursor?: string }
104
+ }): Promise<{ data?: SessionMessage[]; cursor?: { next?: string } }>
98
105
  prompt(opts: { path: { id: string }; body: { text: string } & PromptOptions }): Promise<{ data?: { time?: { created?: number } } }>
99
106
  setModel(opts: { path: { id: string }; body: { model: { providerID: string; id: string } } }): Promise<unknown>
100
107
  setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
@@ -108,6 +115,7 @@ export interface OpencodeClient {
108
115
  form: {
109
116
  list(input: { sessionID: string }): Promise<{ data?: FormInfo[] }>
110
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>
111
119
  }
112
120
  app: {
113
121
  agents(): Promise<{ data?: unknown[] }>
@@ -144,6 +152,75 @@ export function collectReplyText(msgs: SessionMessage[], baseline: number): stri
144
152
  .trim()
145
153
  }
146
154
 
155
+ // 修复⑧(2026-11-03 定案):回合边界归属——共享会话错误源实证(expA 等 21 分钟
156
+ // 拿到桌面排障报告):collectReplyText 的「baseline 后最新 assistant」在共享会话
157
+ // 会抓到别回合产物。正确口径=只取本回合自己:
158
+ // ① 定位本回合 user 行——promptId 精确匹配(prompt API 受理返回值);
159
+ // ② 兜底时间锚:created == baseline 的 user 行(受理即落库,±1s 容差错 skew);
160
+ // ③ 边界=该 user 行 → 下一条 user 行之前;hasIdle/text 都只看边界内。
161
+ // 锚点全部失配(形状变化/兼容旧数据)→ 回落旧 baseline 判据(anchored=false)。
162
+ export interface TurnState {
163
+ /** true=已按回合边界定位(text/hasIdle 只关乎本回合);false=回落旧判据 */
164
+ anchored: boolean
165
+ /** 本回合(或旧判据窗口内)是否已出现 idle 终结标记 */
166
+ hasIdle: boolean
167
+ /** 本回合(或旧判据窗口内)最终 assistant 正文;无正文为空串 */
168
+ text: string
169
+ }
170
+
171
+ export function turnStateOf(msgs: SessionMessage[], promptId: string, baseline: number): TurnState {
172
+ const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0))
173
+ let userIdx = -1
174
+ if (promptId) userIdx = ordered.findIndex((m) => m.type === "user" && m.id === promptId)
175
+ if (userIdx < 0 && baseline > 0) {
176
+ // 修复⑧时间锚兜底:baseline 即本回合 user 行 created(受理即落库),取最近命中;
177
+ // 容差 200ms 仅吸收毫秒级落库偏差,防同窗紧邻行误绑(17:37 定案:5 连发行距 ms 级,锚必最准)。
178
+ let best = -1
179
+ let bestDelta = Number.POSITIVE_INFINITY
180
+ for (let i = ordered.length - 1; i >= 0; i--) {
181
+ if (ordered[i].type !== "user") continue
182
+ const delta = Math.abs((ordered[i].time?.created ?? 0) - baseline)
183
+ if (delta < bestDelta) {
184
+ bestDelta = delta
185
+ best = i
186
+ }
187
+ }
188
+ if (best >= 0 && bestDelta <= 200) userIdx = best
189
+ }
190
+ if (userIdx < 0) {
191
+ // 回落旧判据:行为与 collectReplyText 时代一致,不引入新风险
192
+ const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
193
+ return { anchored: false, hasIdle: Boolean(idle), text: collectReplyText(msgs, baseline) }
194
+ }
195
+ let end = ordered.length
196
+ for (let i = userIdx + 1; i < ordered.length; i++) {
197
+ if (ordered[i].type === "user") {
198
+ end = i
199
+ break
200
+ }
201
+ }
202
+ const boundary = ordered.slice(userIdx + 1, end)
203
+ let text = ""
204
+ for (let i = boundary.length - 1; i >= 0; i--) {
205
+ const m = boundary[i]
206
+ if (m.type !== "assistant") continue
207
+ const joined = (m.content ?? [])
208
+ .filter((p) => p.type === "text" && p.text?.trim())
209
+ .map((p) => p.text ?? "")
210
+ .join("\n")
211
+ .trim()
212
+ if (joined) {
213
+ text = joined
214
+ break
215
+ }
216
+ }
217
+ return {
218
+ anchored: true,
219
+ hasIdle: boundary.some((m) => m.type === "idle"),
220
+ text,
221
+ }
222
+ }
223
+
147
224
  let client: OpencodeClient | null = null
148
225
 
149
226
  function sleep(ms: number): Promise<void> {
@@ -205,7 +282,11 @@ export function createClient(baseUrl: string): OpencodeClient {
205
282
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
206
283
  },
207
284
  async messages(opts) {
208
- return json(await req(`/session/${opts.path.id}/message`))
285
+ const query = new URLSearchParams()
286
+ if (opts.query?.limit !== undefined) query.set("limit", String(opts.query.limit))
287
+ if (opts.query?.cursor) query.set("cursor", opts.query.cursor)
288
+ const suffix = query.size > 0 ? `?${query.toString()}` : ""
289
+ return json(await req(`/session/${opts.path.id}/message${suffix}`))
209
290
  },
210
291
  async prompt(opts) {
211
292
  return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }))
@@ -244,6 +325,9 @@ export function createClient(baseUrl: string): OpencodeClient {
244
325
  }),
245
326
  )
246
327
  },
328
+ async cancel(opts) {
329
+ return json(await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}`, { method: "DELETE" }))
330
+ },
247
331
  },
248
332
 
249
333
  app: {
@@ -304,6 +388,11 @@ export function createClient(baseUrl: string): OpencodeClient {
304
388
  // Only accept assistant messages created at/after this prompt, so a prior
305
389
  // turn's completed reply is never mistaken for this turn's answer.
306
390
  const baseline = promptJson?.data?.time?.created ?? 0
391
+ const promptId = promptJson?.data?.id ?? ""
392
+ // 修复⑧:受领即回传锚点(调用方存台账/挑选直答归属用)
393
+ if (options?.onAccepted) options.onAccepted({ promptId, baseline })
394
+ // LLM 入口实证:user 记录可核对每次真实 /prompt 受理,不再由 QQ 出站反推执行次数。
395
+ console.log(`[opencode] LLM prompt 已受理 pid=${process.pid} session=${sessionId} user=${promptJson?.data?.id ?? "?"} baseline=${baseline}`)
307
396
 
308
397
  const deadline = Date.now() + RESPONSE_TIMEOUT_MS
309
398
  let permissionWaitMs = 0 // 审批等待时间不计入 5 分钟超时(用户可能几分钟才回复)
@@ -357,17 +446,16 @@ export function createClient(baseUrl: string): OpencodeClient {
357
446
 
358
447
  const listJson = await json(await req(`/session/${sessionId}/message`))
359
448
  const msgs: SessionMessage[] = listJson?.data ?? []
360
- // Completion = the idle marker created at/after this prompt. This is the
361
- // only reliable "whole turn done" signal: tool-using turns emit several
362
- // assistant messages (reasoning+tool) before the final text one, so
363
- // "first completed assistant" would return an empty tool message.
364
- const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)
365
- if (idle) {
449
+ // Completion = the idle marker of THIS turn (修复⑧ 回合边界归属)。
450
+ // Tool-using turns emit several assistant messages (reasoning+tool) before
451
+ // the final text one, so "first completed assistant" would return an empty
452
+ // tool message. 共享会话下别回合的 idle/assistant 都不再计入本回合判定。
453
+ const turn = turnStateOf(msgs, promptId, baseline)
454
+ if (turn.hasIdle) {
366
455
  // Aggregate text parts from ALL assistant messages of this turn,
367
456
  // dropping reasoning/tool parts. In practice only the final assistant
368
457
  // carries text; earlier ones are reasoning+tool.
369
- const reply = collectReplyText(msgs, baseline)
370
- return reply || "(AI 未返回内容)"
458
+ return turn.text || "(AI 未返回内容)"
371
459
  }
372
460
  }
373
461
  throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`)