@linjz/opencode-qqbot 0.3.10 → 0.3.12

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.
@@ -3154,7 +3154,13 @@ function createClient(baseUrl) {
3154
3154
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }));
3155
3155
  },
3156
3156
  async messages(opts) {
3157
- return json(await req(`/session/${opts.path.id}/message`));
3157
+ const query = new URLSearchParams;
3158
+ if (opts.query?.limit !== undefined)
3159
+ query.set("limit", String(opts.query.limit));
3160
+ if (opts.query?.cursor)
3161
+ query.set("cursor", opts.query.cursor);
3162
+ const suffix = query.size > 0 ? `?${query.toString()}` : "";
3163
+ return json(await req(`/session/${opts.path.id}/message${suffix}`));
3158
3164
  },
3159
3165
  async prompt(opts) {
3160
3166
  return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }));
@@ -6732,24 +6738,36 @@ function pendingInflight() {
6732
6738
  }
6733
6739
  function classifyInflight(entry, messages) {
6734
6740
  const ordered = [...messages].reverse();
6735
- let lastUserIdx = -1;
6736
- for (let i = ordered.length - 1;i >= 0; i--) {
6741
+ const probe = entry.text.trim().slice(0, 50);
6742
+ let userIdx = -1;
6743
+ if (probe === "") {
6744
+ for (let i = ordered.length - 1;i >= 0; i--) {
6745
+ if (ordered[i].type === "user") {
6746
+ userIdx = i;
6747
+ break;
6748
+ }
6749
+ }
6750
+ } else {
6751
+ for (let i = ordered.length - 1;i >= 0; i--) {
6752
+ if (ordered[i].type === "user" && (ordered[i].text ?? "").includes(probe)) {
6753
+ userIdx = i;
6754
+ break;
6755
+ }
6756
+ }
6757
+ }
6758
+ if (userIdx < 0)
6759
+ return { kind: "lost" };
6760
+ let turnEnd = ordered.length;
6761
+ for (let i = userIdx + 1;i < ordered.length; i++) {
6737
6762
  if (ordered[i].type === "user") {
6738
- lastUserIdx = i;
6763
+ turnEnd = i;
6739
6764
  break;
6740
6765
  }
6741
6766
  }
6742
- if (lastUserIdx < 0)
6743
- return { kind: "lost" };
6744
- const userText = (ordered[lastUserIdx].text ?? "").trim();
6745
- const probe = entry.text.trim().slice(0, 50);
6746
- const matched = probe === "" || userText.includes(probe);
6747
- if (!matched)
6748
- return { kind: "lost" };
6749
- const completed = ordered.slice(lastUserIdx + 1).some((m) => m.type === "idle");
6767
+ const completed = ordered.slice(userIdx + 1, turnEnd).some((m) => m.type === "idle");
6750
6768
  if (!completed)
6751
6769
  return { kind: "running" };
6752
- for (let i = ordered.length - 1;i > lastUserIdx; i--) {
6770
+ for (let i = turnEnd - 1;i > userIdx; i--) {
6753
6771
  const m = ordered[i];
6754
6772
  if (m.type !== "assistant")
6755
6773
  continue;
@@ -7269,8 +7287,8 @@ ${promptBody}` : promptBody;
7269
7287
  }
7270
7288
  const ctx = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text };
7271
7289
  try {
7272
- const listJson = await client.session.messages({ path: { id: entry.sessionId } });
7273
- const cls = classifyInflight(entry, listJson?.data ?? []);
7290
+ const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) };
7291
+ const cls = classifyInflight(entry, listJson.data);
7274
7292
  if (cls.kind === "answered") {
7275
7293
  await deliver(ctx, `\uD83D\uDD04 重启补投:你之前的消息已有答案
7276
7294
 
@@ -7325,6 +7343,20 @@ ${cls.answer}`);
7325
7343
  }
7326
7344
  };
7327
7345
  }
7346
+ async function fetchRecoveryMessages(client, sessionId) {
7347
+ const all = [];
7348
+ let cursor;
7349
+ for (let page = 0;page < 10; page++) {
7350
+ const res = await client.session.messages({ path: { id: sessionId }, query: { limit: 200, cursor } });
7351
+ const items = res?.data ?? [];
7352
+ all.push(...items);
7353
+ const next = res?.cursor?.next;
7354
+ if (!next || items.length === 0)
7355
+ break;
7356
+ cursor = next;
7357
+ }
7358
+ return all;
7359
+ }
7328
7360
  async function maybeHandlePendingSelection(ctx, commandContext) {
7329
7361
  const pending = commandContext.pendingSelections.get(ctx.userId);
7330
7362
  if (!pending) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.10",
3
+ "version": "0.3.12",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  "dev": "bun run --watch src/index.ts",
15
15
  "start": "bun run src/index.ts",
16
16
  "typecheck": "tsc --noEmit",
17
- "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts",
17
+ "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts",
18
18
  "test:e2e": "bun run test/watch-history-e2e.ts && bun run test/d1-subagent-ask-e2e.ts && bun run test/d2-conflict-e2e.ts && bun run test/perm-e2e.ts && bun run test/perm-real-e2e.ts",
19
19
  "verify": "bun run typecheck && bun run test",
20
20
  "verify:full": "bun run verify && bun run test:e2e",
package/src/bridge.ts CHANGED
@@ -9,7 +9,7 @@ import type { Config } from "./config.js"
9
9
  import type { MessageContext } from "./qq/types.js"
10
10
  import { getAccessToken, sendC2CInputNotify, sendC2CMessage, sendGroupMessage } from "./qq/api.js"
11
11
  import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages } from "./qq/media.js"
12
- import type { OpencodeClient } from "./opencode/client.js"
12
+ import type { OpencodeClient, SessionMessage } from "./opencode/client.js"
13
13
  import { collectReplyText } from "./opencode/client.js"
14
14
  import { createEventStream, type V2Event } from "./opencode/eventstream.js"
15
15
  import { summarizeInput, redactSecrets } from "./opencode/history.js"
@@ -720,6 +720,7 @@ export function createBridge(
720
720
  // R 项(2026-10-30 重启丢消息事故修复):启动对账——查在途台账里"已派发未销账"
721
721
  // 的回合,按会话历史分类处置:已有答案→补投;仍在执行→重挂后台等待;
722
722
  // 从未到达 opencode→30 分钟内自动重派(超期通知请用户重发)。
723
+ // 恢复读取必须覆盖原回合,而不是只看最新 20 条;否则长任务/新消息一多就误判 lost 重派。
723
724
  async function recoverInflightRounds(): Promise<void> {
724
725
  const pending = pendingInflight()
725
726
  if (pending.length === 0) return
@@ -733,8 +734,8 @@ export function createBridge(
733
734
  // 恢复投递走主动通道(原 msgId 的被动窗口早已过期)
734
735
  const ctx: MessageContext = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text }
735
736
  try {
736
- const listJson = await client.session.messages({ path: { id: entry.sessionId } })
737
- const cls = classifyInflight(entry, listJson?.data ?? [])
737
+ const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) }
738
+ const cls = classifyInflight(entry, listJson.data)
738
739
  if (cls.kind === "answered") {
739
740
  await deliver(ctx, `🔄 重启补投:你之前的消息已有答案\n\n${cls.answer}`)
740
741
  settleInflight(entry.msgId)
@@ -790,6 +791,21 @@ export function createBridge(
790
791
  }
791
792
  }
792
793
 
794
+ export async function fetchRecoveryMessages(client: OpencodeClient, sessionId: string): Promise<SessionMessage[]> {
795
+ const all: SessionMessage[] = []
796
+ let cursor: string | undefined
797
+ // 上限 2000 条防异常分页循环;常规长会话已足够覆盖原始在途回合。
798
+ for (let page = 0; page < 10; page++) {
799
+ const res = await client.session.messages({ path: { id: sessionId }, query: { limit: 200, cursor } })
800
+ const items = res?.data ?? []
801
+ all.push(...items)
802
+ const next = res?.cursor?.next
803
+ if (!next || items.length === 0) break
804
+ cursor = next
805
+ }
806
+ return all
807
+ }
808
+
793
809
  async function maybeHandlePendingSelection(
794
810
  ctx: MessageContext,
795
811
  commandContext: CommandContext,
@@ -183,28 +183,44 @@ export function classifyInflight(
183
183
  messages: HistoryMessage[],
184
184
  ): InflightClass {
185
185
  const ordered = [...messages].reverse()
186
- let lastUserIdx = -1
187
- for (let i = ordered.length - 1; i >= 0; i--) {
186
+ const probe = entry.text.trim().slice(0, 50)
187
+ let userIdx = -1
188
+ if (probe === "") {
189
+ // 纯附件没有文本锚,只能沿用最新用户消息,由 idle/答案状态兜底。
190
+ for (let i = ordered.length - 1; i >= 0; i--) {
191
+ if (ordered[i].type === "user") {
192
+ userIdx = i
193
+ break
194
+ }
195
+ }
196
+ } else {
197
+ // 长任务期间可能出现更新用户消息;必须按原文找回原回合,不能只查最后一条,
198
+ // 否则会把已到达的旧消息误判为 lost 并再次派发给 LLM。
199
+ for (let i = ordered.length - 1; i >= 0; i--) {
200
+ if (ordered[i].type === "user" && (ordered[i].text ?? "").includes(probe)) {
201
+ userIdx = i
202
+ break
203
+ }
204
+ }
205
+ }
206
+ if (userIdx < 0) return { kind: "lost" }
207
+
208
+ // 回合边界 = 原用户消息之后、下一条用户消息之前。后续新回合的 idle/答案
209
+ // 不能拿来给原回合销账。
210
+ let turnEnd = ordered.length
211
+ for (let i = userIdx + 1; i < ordered.length; i++) {
188
212
  if (ordered[i].type === "user") {
189
- lastUserIdx = i
213
+ turnEnd = i
190
214
  break
191
215
  }
192
216
  }
193
- if (lastUserIdx < 0) return { kind: "lost" }
194
-
195
- const userText = (ordered[lastUserIdx].text ?? "").trim()
196
- const probe = entry.text.trim().slice(0, 50)
197
- // 纯附件消息(无文字)无法文本匹配——探针为空视为匹配(由 answered 判定兜底)
198
- const matched = probe === "" || userText.includes(probe)
199
- if (!matched) return { kind: "lost" }
200
217
 
201
- // 有 assistant 正文 ≠ 回合完成。流式/长任务在运行中也会产生多段正文;
202
- // 必须看到该用户消息之后的 idle,才允许启动补投,否则会把半截答案提前发出。
203
- const completed = ordered.slice(lastUserIdx + 1).some((m) => m.type === "idle")
218
+ // 有 assistant 正文 ≠ 回合完成。必须在该回合边界内看到 idle,才允许补投。
219
+ const completed = ordered.slice(userIdx + 1, turnEnd).some((m) => m.type === "idle")
204
220
  if (!completed) return { kind: "running" }
205
221
 
206
- // 与直答一致:只补投最终 assistant 正文,不把流式进度/阶段前导语重复拼入。
207
- for (let i = ordered.length - 1; i > lastUserIdx; i--) {
222
+ // 与直答一致:只补投该回合最终 assistant 正文,不拼接阶段前导语。
223
+ for (let i = turnEnd - 1; i > userIdx; i--) {
208
224
  const m = ordered[i]
209
225
  if (m.type !== "assistant") continue
210
226
  const answer = (m.content ?? [])
@@ -94,7 +94,10 @@ export interface OpencodeClient {
94
94
  create(body?: Record<string, unknown>): Promise<{ data?: { id: string; title?: string } }>
95
95
  list(): Promise<{ data?: unknown[] }>
96
96
  abort(opts: { path: { id: string } }): Promise<unknown>
97
- messages(opts: { path: { id: string } }): Promise<{ data?: SessionMessage[] }>
97
+ messages(opts: {
98
+ path: { id: string }
99
+ query?: { limit?: number; cursor?: string }
100
+ }): Promise<{ data?: SessionMessage[]; cursor?: { next?: string } }>
98
101
  prompt(opts: { path: { id: string }; body: { text: string } & PromptOptions }): Promise<{ data?: { time?: { created?: number } } }>
99
102
  setModel(opts: { path: { id: string }; body: { model: { providerID: string; id: string } } }): Promise<unknown>
100
103
  setAgent(opts: { path: { id: string }; body: { agent: string } }): Promise<unknown>
@@ -205,7 +208,11 @@ export function createClient(baseUrl: string): OpencodeClient {
205
208
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }))
206
209
  },
207
210
  async messages(opts) {
208
- return json(await req(`/session/${opts.path.id}/message`))
211
+ const query = new URLSearchParams()
212
+ if (opts.query?.limit !== undefined) query.set("limit", String(opts.query.limit))
213
+ if (opts.query?.cursor) query.set("cursor", opts.query.cursor)
214
+ const suffix = query.size > 0 ? `?${query.toString()}` : ""
215
+ return json(await req(`/session/${opts.path.id}/message${suffix}`))
209
216
  },
210
217
  async prompt(opts) {
211
218
  return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }))