@chen_hu_hu/pi-qq 1.6.1 → 1.7.0

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.
@@ -1,6 +1,7 @@
1
1
  import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
2
2
  import { sendReply, sendStreamReply, type ReplyChannel } from "./reply-sender";
3
3
  import type { ReplyBudget } from "../quota/reply-quota";
4
+ import type { RepushResult } from "../relay/run-stream-relay";
4
5
  import { formatAttachmentFailures } from "../attachments/attachment-failure";
5
6
  import {
6
7
  formatAttachmentPrompt,
@@ -9,21 +10,19 @@ import {
9
10
  type SavedFile,
10
11
  } from "../attachments/file-attachments";
11
12
  import { log } from "../infra/file-logger";
12
- import type { ReplyType } from "../infra/reply-type";
13
13
  import { t } from "../infra/i18n";
14
14
  import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
15
15
  import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
16
16
 
17
- export interface InboundDeps extends InboundCommandDeps {
17
+ interface InboundDeps extends InboundCommandDeps {
18
18
  budget: ReplyBudget;
19
19
  getAllowedOpenid: () => string | undefined;
20
20
  reloadSettings: () => void;
21
21
  getDeliverAs: () => "steer" | "followUp";
22
- getReplyType: () => ReplyType;
23
22
  getFileMaxSize: () => number;
24
23
  saveFiles?: typeof saveInboundFiles;
25
24
  streamReply?: typeof sendStreamReply;
26
- repushCurrent: (openid: string, msgId: string) => boolean;
25
+ repushCurrent: (openid: string, msgId: string) => RepushResult;
27
26
  onWarn: (msg: string) => void;
28
27
  markQQTrigger: (openid: string, msgId: string) => void;
29
28
  }
@@ -72,7 +71,7 @@ export function createInboundHandler(deps: InboundDeps) {
72
71
 
73
72
  const channel: ReplyChannel = {
74
73
  budget: deps.budget,
75
- boundOpenid: deps.getAllowedOpenid() ?? msg.senderId,
74
+ boundOpenid: allowed,
76
75
  onWarn: deps.onWarn,
77
76
  };
78
77
  const reply = (text: string) => sendReply(bot, text, channel);
@@ -103,7 +102,7 @@ export function createInboundHandler(deps: InboundDeps) {
103
102
  }
104
103
  },
105
104
  restartPush: () => {
106
- deps.repushCurrent(msg.senderId, msg.messageId);
105
+ return deps.repushCurrent(msg.senderId, msg.messageId);
107
106
  },
108
107
  });
109
108
  return;
@@ -1,6 +1,7 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { ReplyBudget } from "../quota/reply-quota";
3
3
  import { AppendStream } from "../relay/stream-session";
4
+ import { sendWithMsgSeq } from "./msg-seq-send";
4
5
  import { log } from "../infra/file-logger";
5
6
  import { t } from "../infra/i18n";
6
7
 
@@ -122,7 +123,7 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
122
123
  length: chunk.length,
123
124
  text: chunk,
124
125
  });
125
- await bot.sendText(replyTarget, chunk);
126
+ await sendWithMsgSeq(bot, { target: replyTarget, content: chunk });
126
127
  if (mode === "passive" && msgId) ch.budget.commitPassive(msgId);
127
128
  log.info("outbound", "text chunk sent", { mode, targetId, length: chunk.length });
128
129
  } catch (err) {
@@ -135,7 +136,10 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
135
136
  if (mode === "passive") {
136
137
  try {
137
138
  log.warn("outbound", "passive send failed; retrying proactively", { targetId: ch.boundOpenid });
138
- await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
139
+ await sendWithMsgSeq(bot, {
140
+ target: { scope: "c2c", targetId: ch.boundOpenid },
141
+ content: chunk,
142
+ });
139
143
  ch.onWarn?.(t("outbound.passiveFailed"));
140
144
  continue;
141
145
  } catch (retryErr) {
@@ -38,19 +38,7 @@ function maskOpenid(openid: string): string {
38
38
  return `${openid.slice(0, 8)}…`;
39
39
  }
40
40
 
41
- function label(
42
- key:
43
- | "status.agent"
44
- | "status.context"
45
- | "status.model"
46
- | "status.login"
47
- | "status.connection"
48
- | "status.qqUser"
49
- | "status.battery"
50
- | "status.replyType"
51
- | "status.settings",
52
- value: string,
53
- ): string {
41
+ function label(key: TranslationKey, value: string): string {
54
42
  return `${t(key)}${t("status.separator")}${value}`;
55
43
  }
56
44
 
@@ -1,8 +1,8 @@
1
1
  import { ReplyLimiter } from "@tencent-connect/qqbot-nodejs/protocol";
2
2
 
3
- export type ReplyMode = "passive" | "proactive";
3
+ type ReplyMode = "passive" | "proactive";
4
4
 
5
- export interface AcquireResult {
5
+ interface AcquireResult {
6
6
  mode: ReplyMode;
7
7
  openid?: string;
8
8
  msgId?: string;
@@ -16,6 +16,26 @@ type BlockKind = "none" | "thinking" | "tool" | "text";
16
16
  const MAX_RESUME_ATTEMPTS = 2;
17
17
  const MAX_BUBBLE_CHARS = 12_000;
18
18
 
19
+ function isDuplicateMsgSeqError(err: unknown): boolean {
20
+ const e = err as { code?: number; err_code?: number; bizCode?: number; message?: string };
21
+ return (
22
+ e?.code === 40054005 ||
23
+ e?.err_code === 40054005 ||
24
+ e?.bizCode === 40054005 ||
25
+ /40054005|消息被去重|msgseq/i.test(String(e?.message ?? ""))
26
+ );
27
+ }
28
+
29
+ export interface RepushTool {
30
+ name: string;
31
+ args?: unknown;
32
+ skillName?: string;
33
+ result?: { isError: boolean; result?: unknown };
34
+ }
35
+
36
+ export type RepushBlock =
37
+ { kind: "thinking"; text: string } | { kind: "tool"; tool: RepushTool } | { kind: "text"; text: string };
38
+
19
39
  export interface BubbleWriterDeps {
20
40
  bot: () => QQBot | undefined;
21
41
  budget: ReplyBudget;
@@ -89,14 +109,14 @@ export class BubbleWriter {
89
109
  const newBubble = this.startsNewBlock("thinking");
90
110
  const prefix = this.beginBlock("thinking", newBubble);
91
111
  this.thinkingAtLineStart = delta.endsWith("\n");
92
- this.push(`${prefix}${delta}`, prefix.length > 0 || newBubble, false, newBubble, true);
112
+ this.push(`${prefix}${delta}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble, thinking: true });
93
113
  }
94
114
 
95
115
  pushText(text: string): void {
96
116
  if (this.streamDead || this.disposed) return;
97
117
  const newBubble = this.startsNewBlock("text");
98
118
  const prefix = this.beginBlock("text", newBubble);
99
- this.push(`${prefix}${text}`, prefix.length > 0 || newBubble, false, newBubble);
119
+ this.push(`${prefix}${text}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble });
100
120
  }
101
121
 
102
122
  pushTool(name: string, args: unknown): void {
@@ -114,14 +134,11 @@ export class BubbleWriter {
114
134
  budget: this.deps.budget.snapshot(),
115
135
  });
116
136
  }
117
- this.push(
118
- `${prefix}${formatToolLine(name, args)}\n\n`,
119
- prefix.length > 0 || newBubble,
120
- false,
137
+ this.push(`${prefix}${formatToolLine(name, args)}\n\n`, {
138
+ blockBoundary: prefix.length > 0 || newBubble,
121
139
  newBubble,
122
- false,
123
- "tool",
124
- );
140
+ trace: "tool",
141
+ });
125
142
  }
126
143
 
127
144
  pushSkill(name: string): void {
@@ -129,25 +146,25 @@ export class BubbleWriter {
129
146
  this.toolOpen = false;
130
147
  const newBubble = true;
131
148
  const prefix = this.beginBlock("tool", newBubble);
132
- this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble, false, "skill");
149
+ this.push(`${prefix}${formatSkillBlock(name)}`, {
150
+ blockBoundary: prefix.length > 0 || newBubble,
151
+ newBubble,
152
+ trace: "skill",
153
+ });
133
154
  }
134
155
 
135
156
  pushToolResult(result: unknown, isError: boolean, toolName?: string, args?: unknown): void {
136
157
  if (this.streamDead || this.disposed) return;
137
158
  const prefix = this.beginBlock("tool");
138
159
  const language = toolName ? resultLanguage(toolName, args, isError) : "text";
139
- this.push(`${prefix}${formatToolResult(result, isError, language)}`, prefix.length > 0, true);
140
- }
141
-
142
- schedule(op: () => void): void {
143
- void this.enqueue(async () => {
144
- if (this.streamDead || this.disposed) return;
145
- op();
160
+ this.push(`${prefix}${formatToolResult(result, isError, language)}`, {
161
+ blockBoundary: prefix.length > 0,
162
+ endTool: true,
146
163
  });
147
164
  }
148
165
 
149
- restartText(text: string, target?: { openid: string; msgId: string }): void {
150
- if (!text || this.disposed) return;
166
+ restartSnapshot(blocks: RepushBlock[], target?: { openid: string; msgId: string }): void {
167
+ if (this.disposed || blocks.length === 0) return;
151
168
  void this.enqueue(async () => {
152
169
  if (this.disposed) return;
153
170
  if (this.fenceOpen) await this.closeOpenFence();
@@ -157,19 +174,21 @@ export class BubbleWriter {
157
174
  this.deps.openid = target.openid;
158
175
  this.deps.msgId = target.msgId;
159
176
  }
160
- this.streamDead = false;
161
- this.pendingResume = undefined;
162
- this.resumeAttempts = 0;
163
- this.lastKind = "none";
164
- this.blockClosed = false;
165
- this.toolOpen = false;
166
- this.fenceOpen = false;
167
- this.fenceLen = 0;
168
- this.fenceQuoted = false;
169
- this.lastChar = "";
170
- this.thinkingAtLineStart = true;
171
- this.bubbleChars = 0;
172
- this.pushText(text);
177
+ this.resetForRestart();
178
+ for (const block of blocks) {
179
+ if (block.kind === "thinking") {
180
+ this.pushThinking(block.text);
181
+ } else if (block.kind === "text") {
182
+ this.pushText(block.text);
183
+ } else if (block.tool.skillName) {
184
+ this.pushSkill(block.tool.skillName);
185
+ } else {
186
+ this.pushTool(block.tool.name, block.tool.args);
187
+ if (block.tool.result) {
188
+ this.pushToolResult(block.tool.result.result, block.tool.result.isError, block.tool.name, block.tool.args);
189
+ }
190
+ }
191
+ }
173
192
  });
174
193
  }
175
194
 
@@ -177,6 +196,23 @@ export class BubbleWriter {
177
196
  await this.drainQueue();
178
197
  }
179
198
 
199
+ private resetForRestart(): void {
200
+ this.cur?.dispose();
201
+ this.cur = null;
202
+ this.streamDead = false;
203
+ this.pendingResume = undefined;
204
+ this.resumeAttempts = 0;
205
+ this.lastKind = "none";
206
+ this.blockClosed = false;
207
+ this.toolOpen = false;
208
+ this.fenceOpen = false;
209
+ this.fenceLen = 0;
210
+ this.fenceQuoted = false;
211
+ this.lastChar = "";
212
+ this.thinkingAtLineStart = true;
213
+ this.bubbleChars = 0;
214
+ }
215
+
180
216
  async flush(): Promise<boolean> {
181
217
  await this.drainQueue();
182
218
  if (this.streamDead || this.disposed) return false;
@@ -263,12 +299,15 @@ export class BubbleWriter {
263
299
 
264
300
  private push(
265
301
  text: string,
266
- blockBoundary = false,
267
- endTool = false,
268
- newBubble = false,
269
- thinking = false,
270
- trace?: string,
302
+ options: {
303
+ blockBoundary?: boolean;
304
+ endTool?: boolean;
305
+ newBubble?: boolean;
306
+ thinking?: boolean;
307
+ trace?: string;
308
+ } = {},
271
309
  ): void {
310
+ const { blockBoundary = false, endTool = false, newBubble = false, thinking = false, trace } = options;
272
311
  if (!text || this.streamDead || this.disposed) return;
273
312
  const queuedAt = trace ? Date.now() : 0;
274
313
  void this.enqueue(async () => {
@@ -471,9 +510,11 @@ export class BubbleWriter {
471
510
  const checkpoint = stream?.checkpoint() ?? null;
472
511
  stream?.dispose();
473
512
  this.cur = null;
513
+ const resetSeq = isDuplicateMsgSeqError(err);
474
514
  log.warn("stream", "stream error", {
475
515
  msgId: this.logMsgId(),
476
516
  elapsedMs: Date.now() - this.deps.startedAt,
517
+ resetSeq,
477
518
  checkpoint: checkpoint
478
519
  ? {
479
520
  index: checkpoint.index,
@@ -487,7 +528,12 @@ export class BubbleWriter {
487
528
  });
488
529
  if (checkpoint && this.resumeAttempts < MAX_RESUME_ATTEMPTS) {
489
530
  this.resumeAttempts += 1;
490
- this.pendingResume = checkpoint;
531
+ this.pendingResume = resetSeq
532
+ ? {
533
+ index: 0,
534
+ ...(checkpoint.buffer ? { buffer: checkpoint.buffer } : {}),
535
+ }
536
+ : checkpoint;
491
537
  return;
492
538
  }
493
539
  this.killStream(err.message);
@@ -0,0 +1,15 @@
1
+ const MAX_MSG_SEQ = 0xffff;
2
+ const nextByMsgId = new Map<string, number>();
3
+
4
+ export function allocateMsgSeq(msgId: string): number {
5
+ const next = nextByMsgId.get(msgId) ?? 0;
6
+ if (next > MAX_MSG_SEQ) {
7
+ throw new Error("msg_seq exhausted for message");
8
+ }
9
+ nextByMsgId.set(msgId, next + 1);
10
+ return next;
11
+ }
12
+
13
+ export function resetMsgSeqAllocator(): void {
14
+ nextByMsgId.clear();
15
+ }
@@ -3,32 +3,19 @@ import type { ReplyType } from "../infra/reply-type";
3
3
  export interface ReplyPolicy {
4
4
  relayThinking: boolean;
5
5
  relayTools: boolean;
6
- relayTextLive: boolean;
7
6
  deferTextWhileToolsPending: boolean;
8
- deliverLastAtEnd: boolean;
9
7
  }
10
8
 
11
9
  const POLICIES: Record<ReplyType, ReplyPolicy> = {
12
10
  full: {
13
11
  relayThinking: true,
14
12
  relayTools: true,
15
- relayTextLive: true,
16
13
  deferTextWhileToolsPending: true,
17
- deliverLastAtEnd: false,
18
14
  },
19
15
  simple: {
20
16
  relayThinking: false,
21
17
  relayTools: false,
22
- relayTextLive: true,
23
18
  deferTextWhileToolsPending: false,
24
- deliverLastAtEnd: false,
25
- },
26
- last: {
27
- relayThinking: false,
28
- relayTools: false,
29
- relayTextLive: false,
30
- deferTextWhileToolsPending: false,
31
- deliverLastAtEnd: true,
32
19
  },
33
20
  };
34
21