@chen_hu_hu/pi-qq 1.3.1 → 1.3.2

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,8 +1,7 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
1
  import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
3
2
  import { sendReply, type ReplyChannel } from "./reply-sender";
4
3
  import type { ReplyBudget } from "../quota/reply-quota";
5
- import { formatAttachmentFailures, type AttachmentFailure } from "../attachments/attachment-failure";
4
+ import { formatAttachmentFailures } from "../attachments/attachment-failure";
6
5
  import {
7
6
  formatAttachmentPrompt,
8
7
  saveInboundFiles,
@@ -10,30 +9,21 @@ import {
10
9
  type SavedFile,
11
10
  } from "../attachments/file-attachments";
12
11
  import { log } from "../infra/file-logger";
13
- import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
12
+ import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
13
+ import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
14
14
 
15
- export interface InboundDeps {
16
- pi: ExtensionAPI;
17
- ctx: ExtensionContext;
15
+ export interface InboundDeps extends InboundCommandDeps {
18
16
  budget: ReplyBudget;
19
17
  getAllowedOpenid: () => string | undefined;
20
18
  getDeliverAs: () => "steer" | "followUp";
21
19
  getFileMaxSize: () => number;
22
20
  saveFiles?: typeof saveInboundFiles;
23
- getStatusLines: () => string[];
24
21
  onWarn: (msg: string) => void;
25
22
  markQQTrigger: (openid: string, msgId: string) => void;
26
- waitForEnd?: () => Promise<void>;
27
- onStop?: () => void;
28
23
  }
29
24
 
30
25
  export function createInboundHandler(deps: InboundDeps) {
31
- let pendingAttachments: SavedFile[] = [];
32
- const takePendingAttachments = (): SavedFile[] => {
33
- const attachments = pendingAttachments;
34
- pendingAttachments = [];
35
- return attachments;
36
- };
26
+ const pending = new PendingAttachments();
37
27
 
38
28
  return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
39
29
  log.debug("inbound", "message received", {
@@ -79,17 +69,16 @@ export function createInboundHandler(deps: InboundDeps) {
79
69
  onWarn: deps.onWarn,
80
70
  };
81
71
  const reply = (text: string) => sendReply(bot, text, channel);
82
- const saveFiles = deps.saveFiles ?? saveInboundFiles;
83
72
 
84
73
  const contentText = (msg.content ?? "").trim();
85
74
  if (contentText.startsWith("/")) {
86
75
  const command = contentText.split(/\s+/)[0];
87
76
  log.info("inbound", "QQ command", { command });
88
- if (command === "/new" && deps.ctx.isIdle() && pendingAttachments.length > 0) {
89
- log.info("inbound", "cleared pending attachments for /new", { count: pendingAttachments.length });
90
- pendingAttachments = [];
77
+ if (command === "/new" && deps.ctx.isIdle() && pending.count > 0) {
78
+ log.info("inbound", "cleared pending attachments for /new", { count: pending.count });
79
+ pending.clear();
91
80
  }
92
- await handleCommand(contentText, reply, deps);
81
+ await handleInboundCommand(contentText, reply, deps);
93
82
  return;
94
83
  }
95
84
 
@@ -100,47 +89,17 @@ export function createInboundHandler(deps: InboundDeps) {
100
89
  return;
101
90
  }
102
91
 
103
- let text = contentText;
104
- const voiceAttachments = attachments.filter(isVoiceAttachment);
105
- if (voiceAttachments.length > 0) {
106
- const transcript = resolveVoiceTranscript(voiceAttachments);
107
- log.info("inbound", "voice message", {
108
- messageId: msg.messageId,
109
- hasAsr: Boolean(transcript),
110
- asrLength: transcript?.length ?? 0,
111
- });
112
- if (!transcript) {
113
- if (!contentText) {
114
- log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
115
- await reply("Could not transcribe this voice message; please resend or type it.");
116
- return;
117
- }
118
- log.warn("inbound", "voice ASR returned no text; using text content", { messageId: msg.messageId });
119
- } else {
120
- log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
121
- text = contentText ? `${contentText}\n${transcript}` : transcript;
122
- }
123
- }
124
-
125
- // Voice attachments are handled above; all other attachments are stored as files.
126
- const attachmentsToSave = attachments.filter((attachment) => !isVoiceAttachment(attachment));
127
- const failures: AttachmentFailure[] = [];
128
-
129
- let files: SavedFile[] = [];
130
- if (attachmentsToSave.length > 0) {
131
- const uploadDir = sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId());
132
- log.debug("inbound", "saving attachments", {
133
- messageId: msg.messageId,
134
- count: attachmentsToSave.length,
135
- uploadDir,
136
- });
137
- const result = await saveFiles(attachmentsToSave, {
138
- maxSize: deps.getFileMaxSize(),
139
- uploadDir,
140
- });
141
- files = result.files;
142
- failures.push(...result.failures);
92
+ const resolved = await resolveInboundContent(msg, {
93
+ contentText,
94
+ maxSize: deps.getFileMaxSize(),
95
+ uploadDir: sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId()),
96
+ saveFiles: deps.saveFiles ?? saveInboundFiles,
97
+ });
98
+ if (resolved.status === "rejected") {
99
+ await reply(resolved.reply);
100
+ return;
143
101
  }
102
+ const { text, files, failures, voiceCount } = resolved;
144
103
 
145
104
  if (failures.length > 0) {
146
105
  log.warn("inbound", "attachment failure summary", {
@@ -159,77 +118,27 @@ export function createInboundHandler(deps: InboundDeps) {
159
118
  }
160
119
 
161
120
  if (!text && files.length > 0) {
162
- pendingAttachments.push(...files);
121
+ pending.add(files);
163
122
  log.info("inbound", "attachments pending for instruction", {
164
123
  messageId: msg.messageId,
165
124
  count: files.length,
166
- pendingCount: pendingAttachments.length,
125
+ pendingCount: pending.count,
167
126
  });
168
127
  return;
169
128
  }
170
129
 
171
130
  deps.markQQTrigger(msg.senderId, msg.messageId);
172
- const pending = text ? takePendingAttachments() : [];
173
- const promptFiles = [...pending, ...files];
131
+ const pendingFiles = text ? pending.take() : [];
132
+ const promptFiles: SavedFile[] = [...pendingFiles, ...files];
174
133
  const promptText = formatAttachmentPrompt(promptFiles, text, deps.ctx.cwd);
175
134
  deps.pi.sendUserMessage(promptText, { deliverAs: deps.getDeliverAs() });
176
135
  log.info("inbound", "sent to pi", {
177
136
  messageId: msg.messageId,
178
137
  textLength: text.length,
179
- voice: voiceAttachments.length > 0,
138
+ voice: voiceCount > 0,
180
139
  attachments: promptFiles.length,
181
- pendingAttachments: pending.length,
140
+ pendingAttachments: pendingFiles.length,
182
141
  deliverAs: deps.getDeliverAs(),
183
142
  });
184
143
  };
185
144
  }
186
-
187
- async function handleCommand(text: string, reply: (t: string) => Promise<void>, deps: InboundDeps): Promise<void> {
188
- const cmd = text.split(/\s+/)[0];
189
- switch (cmd) {
190
- case "/help":
191
- await reply(
192
- [
193
- "pi-qq commands:",
194
- "• /stop — abort the current task",
195
- "• /compact — compact the context",
196
- "• /status — show status",
197
- "• /new — reset the session",
198
- "• /help — this help",
199
- "Other text is sent to pi.",
200
- ].join("\n"),
201
- );
202
- break;
203
- case "/stop":
204
- deps.onStop?.();
205
- if (deps.ctx.isIdle()) {
206
- await reply("No task is running.");
207
- } else {
208
- deps.ctx.abort();
209
- await deps.waitForEnd?.();
210
- await reply("Abort requested.");
211
- }
212
- break;
213
- case "/compact":
214
- if (deps.ctx.isIdle()) {
215
- deps.ctx.compact();
216
- await reply("Context compaction triggered.");
217
- } else {
218
- await reply("Task is running; use /stop before /compact.");
219
- }
220
- break;
221
- case "/status":
222
- await reply(deps.getStatusLines().join("\n"));
223
- break;
224
- case "/new":
225
- if (!deps.ctx.isIdle()) {
226
- await reply("Task is running; use /stop before resetting.");
227
- } else {
228
- await reply("Resetting the session…");
229
- deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
230
- }
231
- break;
232
- default:
233
- await reply(`Unknown command ${cmd}; use /help.`);
234
- }
235
- }
@@ -0,0 +1,338 @@
1
+ import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
+ import { AppendStream, type AppendStreamCheckpoint } from "./stream-session";
3
+ import type { ReplyBudget } from "../quota/reply-quota";
4
+ import { log } from "../infra/file-logger";
5
+ import { THINKING_HEADER, formatToolLine, formatToolResult } from "./stream-block-format";
6
+
7
+ type BlockKind = "none" | "thinking" | "tool" | "text";
8
+
9
+ const MAX_RESUME_ATTEMPTS = 2;
10
+ const MAX_BUBBLE_CHARS = 12_000;
11
+
12
+ export interface BubbleWriterDeps {
13
+ bot: () => QQBot | undefined;
14
+ budget: ReplyBudget;
15
+ openid: string;
16
+ msgId?: string;
17
+ startedAt: number;
18
+ onWarn: (msg: string) => void;
19
+ }
20
+
21
+ /**
22
+ * Owns one run's QQ stream: block layout, bubble rotation, fence tracking, and
23
+ * stream recovery. Operations are serialized so callers can enqueue in event
24
+ * order without waiting for network round-trips.
25
+ */
26
+ export class BubbleWriter {
27
+ private cur: AppendStream | null = null;
28
+ private pendingResume?: AppendStreamCheckpoint;
29
+ private streamDead = false;
30
+ private resumeAttempts = 0;
31
+ private pushedAny = false;
32
+ private bubbleChars = 0;
33
+ private fenceOpen = false;
34
+ private fenceLen = 0;
35
+ private fenceQuoted = false;
36
+ private lastChar = "";
37
+ private lastKind: BlockKind = "none";
38
+ private blockClosed = false;
39
+ private thinkingAtLineStart = true;
40
+ private toolOpen = false;
41
+ private queue: Promise<void> = Promise.resolve();
42
+ private disposed = false;
43
+
44
+ constructor(private readonly deps: BubbleWriterDeps) {}
45
+
46
+ get hasPushed(): boolean {
47
+ return this.pushedAny;
48
+ }
49
+
50
+ get dead(): boolean {
51
+ return this.streamDead;
52
+ }
53
+
54
+ /** Mark the current block as complete so the next content starts a new bubble. */
55
+ closeBlock(): void {
56
+ this.blockClosed = true;
57
+ }
58
+
59
+ pushThinking(delta: string): void {
60
+ if (this.streamDead || this.disposed) return;
61
+ const newBubble = this.startsNewBlock("thinking");
62
+ const prefix = this.beginBlock("thinking", newBubble);
63
+ this.thinkingAtLineStart = delta.endsWith("\n");
64
+ this.push(`${prefix}${delta}`, prefix.length > 0 || newBubble, false, newBubble, true);
65
+ }
66
+
67
+ pushText(text: string): void {
68
+ if (this.streamDead || this.disposed) return;
69
+ const newBubble = this.startsNewBlock("text");
70
+ const prefix = this.beginBlock("text", newBubble);
71
+ this.push(`${prefix}${text}`, prefix.length > 0 || newBubble, false, newBubble);
72
+ }
73
+
74
+ pushTool(name: string, args: unknown): void {
75
+ if (this.streamDead || this.disposed) return;
76
+ this.toolOpen = true;
77
+ const newBubble = this.lastKind !== "none";
78
+ const prefix = this.beginBlock("tool", newBubble);
79
+ this.push(`${prefix}${formatToolLine(name, args)}\n\n`, prefix.length > 0 || newBubble, false, newBubble);
80
+ }
81
+
82
+ pushToolResult(result: unknown, isError: boolean): void {
83
+ if (this.streamDead || this.disposed) return;
84
+ const prefix = this.beginBlock("tool");
85
+ this.push(`${prefix}${formatToolResult(result, isError)}`, prefix.length > 0, true);
86
+ }
87
+
88
+ /** Run `op` after all currently queued appends, unless the stream died first. */
89
+ schedule(op: () => void): void {
90
+ void this.enqueue(async () => {
91
+ if (this.streamDead || this.disposed) return;
92
+ op();
93
+ });
94
+ }
95
+
96
+ async whenIdle(): Promise<void> {
97
+ await this.drainQueue();
98
+ }
99
+
100
+ async flush(): Promise<boolean> {
101
+ await this.drainQueue();
102
+ if (this.streamDead || this.disposed) return false;
103
+ if (!this.cur && !this.pendingResume) return true;
104
+ for (let attempt = 0; attempt <= MAX_RESUME_ATTEMPTS; attempt++) {
105
+ const stream = this.ensureStream();
106
+ if (!stream) return false;
107
+ try {
108
+ await stream.flush();
109
+ await this.queue;
110
+ if (this.streamDead) return false;
111
+ if (this.cur !== stream) continue;
112
+ return true;
113
+ } catch (err) {
114
+ this.handleStreamError(err as Error);
115
+ if (this.streamDead) return false;
116
+ }
117
+ }
118
+ this.killStream("resume attempts exhausted");
119
+ return false;
120
+ }
121
+
122
+ async done(): Promise<void> {
123
+ if (this.streamDead || this.disposed || !this.cur) return;
124
+ try {
125
+ await this.cur.done();
126
+ } catch (err) {
127
+ log.warn("stream", "DONE failed", { msgId: this.logMsgId(), err });
128
+ }
129
+ }
130
+
131
+ dispose(): void {
132
+ this.disposed = true;
133
+ this.cur?.dispose();
134
+ this.cur = null;
135
+ }
136
+
137
+ private logMsgId(): string {
138
+ return this.deps.msgId?.slice(0, 8) ?? "?";
139
+ }
140
+
141
+ private beginBlock(kind: BlockKind, newBubble = false): string {
142
+ if (newBubble) {
143
+ this.lastKind = kind;
144
+ this.blockClosed = false;
145
+ if (kind === "thinking") this.thinkingAtLineStart = true;
146
+ return "";
147
+ }
148
+ if (this.lastKind === kind) return "";
149
+ let prefix = "";
150
+ if (this.lastKind !== "none") {
151
+ if (this.lastKind === "thinking" && !this.thinkingAtLineStart) prefix += "\n";
152
+ prefix += this.lastKind === "text" ? "\n\n" : "\n";
153
+ }
154
+ this.lastKind = kind;
155
+ this.blockClosed = false;
156
+ if (kind === "thinking") this.thinkingAtLineStart = true;
157
+ return prefix;
158
+ }
159
+
160
+ private startsNewBlock(kind: BlockKind): boolean {
161
+ return this.blockClosed || (this.lastKind !== "none" && this.lastKind !== kind);
162
+ }
163
+
164
+ private async closeOpenFence(): Promise<boolean> {
165
+ if (!this.fenceOpen) return true;
166
+ const stream = this.ensureStream();
167
+ if (!stream) return false;
168
+ const ticks = "`".repeat(this.fenceLen);
169
+ const closing = `\n${this.fenceQuoted ? "> " : ""}${ticks}\n`;
170
+ try {
171
+ await stream.append(closing);
172
+ this.bubbleChars += closing.length;
173
+ this.lastChar = "\n";
174
+ this.fenceOpen = false;
175
+ this.fenceLen = 0;
176
+ this.fenceQuoted = false;
177
+ return true;
178
+ } catch (err) {
179
+ if (this.cur === stream) this.handleStreamError(err as Error);
180
+ return false;
181
+ }
182
+ }
183
+
184
+ private push(text: string, blockBoundary = false, endTool = false, newBubble = false, thinking = false): void {
185
+ if (!text || this.streamDead || this.disposed) return;
186
+ void this.enqueue(async () => {
187
+ if (this.streamDead || this.disposed) return;
188
+ if (blockBoundary && !(await this.closeOpenFence())) return;
189
+ if (newBubble && this.cur && this.bubbleChars > 0 && !this.pendingResume) {
190
+ await this.rotateStream();
191
+ if (this.streamDead || this.disposed) return;
192
+ }
193
+ if (
194
+ !newBubble &&
195
+ this.bubbleChars >= MAX_BUBBLE_CHARS &&
196
+ this.cur &&
197
+ !this.pendingResume &&
198
+ !this.fenceOpen &&
199
+ !this.toolOpen &&
200
+ (blockBoundary || this.lastChar === "\n")
201
+ ) {
202
+ await this.rotateStream();
203
+ if (this.streamDead || this.disposed) return;
204
+ }
205
+ const stream = this.ensureStream();
206
+ if (!stream) return;
207
+ this.pushedAny = true;
208
+ const outgoing = thinking && (!this.cur || this.bubbleChars === 0) ? `${THINKING_HEADER}${text}` : text;
209
+ try {
210
+ await stream.append(outgoing);
211
+ this.bubbleChars += outgoing.length;
212
+ this.trackFences(outgoing);
213
+ this.lastChar = outgoing.slice(-1);
214
+ if (endTool) this.toolOpen = false;
215
+ } catch (err) {
216
+ if (this.cur === stream) this.handleStreamError(err as Error);
217
+ }
218
+ });
219
+ }
220
+
221
+ private trackFences(text: string): void {
222
+ const previousChar = this.lastChar;
223
+ for (const match of text.matchAll(/(?:^|\n)[ \t>]*(`{3,})/g)) {
224
+ if (match.index === 0 && previousChar && previousChar !== "\n") continue;
225
+ const fenceLen = match[1].length;
226
+ const lineEnd = text.indexOf("\n", match.index + match[0].length);
227
+ const restOfLine = text.slice(match.index + match[0].length, lineEnd < 0 ? undefined : lineEnd);
228
+ if (restOfLine.includes("`".repeat(fenceLen))) continue;
229
+ if (!this.fenceOpen) {
230
+ this.fenceOpen = true;
231
+ this.fenceLen = fenceLen;
232
+ this.fenceQuoted = match[0].includes(">");
233
+ } else if (fenceLen >= this.fenceLen) {
234
+ this.fenceOpen = false;
235
+ this.fenceLen = 0;
236
+ this.fenceQuoted = false;
237
+ }
238
+ }
239
+ }
240
+
241
+ private async rotateStream(): Promise<void> {
242
+ const stream = this.cur;
243
+ if (!stream) return;
244
+ try {
245
+ if (this.lastChar && this.lastChar !== "\n") {
246
+ await stream.append("\n");
247
+ this.bubbleChars += 1;
248
+ this.lastChar = "\n";
249
+ this.thinkingAtLineStart = true;
250
+ }
251
+ await stream.flush();
252
+ await stream.done();
253
+ } catch (err) {
254
+ log.warn("stream", "bubble split failed", { msgId: this.logMsgId(), err });
255
+ if (this.cur === stream) this.handleStreamError(err as Error);
256
+ return;
257
+ }
258
+ stream.dispose();
259
+ if (this.cur === stream) this.cur = null;
260
+ this.bubbleChars = 0;
261
+ this.fenceOpen = false;
262
+ this.fenceLen = 0;
263
+ this.fenceQuoted = false;
264
+ this.lastChar = "";
265
+ this.thinkingAtLineStart = true;
266
+ log.debug("stream", "bubble split", {
267
+ msgId: this.logMsgId(),
268
+ elapsedMs: Date.now() - this.deps.startedAt,
269
+ });
270
+ }
271
+
272
+ private drainQueue(): Promise<void> {
273
+ return (async () => {
274
+ for (;;) {
275
+ const current = this.queue;
276
+ await current;
277
+ if (current === this.queue) return;
278
+ }
279
+ })();
280
+ }
281
+
282
+ private enqueue(op: () => Promise<void>): Promise<void> {
283
+ const next = this.queue.then(op, op);
284
+ this.queue = next.catch(() => {});
285
+ return next;
286
+ }
287
+
288
+ private ensureStream(): AppendStream | null {
289
+ if (this.streamDead || this.disposed) return null;
290
+ if (this.cur) return this.cur;
291
+ const bot = this.deps.bot();
292
+ if (!bot || !this.deps.msgId) return null;
293
+ const resume = this.pendingResume;
294
+ this.pendingResume = undefined;
295
+ const stream = new AppendStream(bot.messageApi, bot.getCredentials(), this.deps.openid, this.deps.msgId, {
296
+ resume,
297
+ onError: (err) => {
298
+ void this.enqueue(async () => {
299
+ if (this.disposed || this.cur !== stream) return;
300
+ this.handleStreamError(err);
301
+ });
302
+ },
303
+ onDebug: (message) => log.debug("stream", message, { msgId: this.logMsgId() }),
304
+ });
305
+ this.cur = stream;
306
+ if (!resume) this.deps.budget.noteStreamBubble(this.deps.msgId);
307
+ return stream;
308
+ }
309
+
310
+ private handleStreamError(err: Error): void {
311
+ if (this.streamDead) return;
312
+ const stream = this.cur;
313
+ const checkpoint = stream?.checkpoint() ?? null;
314
+ stream?.dispose();
315
+ this.cur = null;
316
+ log.warn("stream", "stream error", {
317
+ msgId: this.logMsgId(),
318
+ elapsedMs: Date.now() - this.deps.startedAt,
319
+ err,
320
+ });
321
+ if (checkpoint && this.resumeAttempts < MAX_RESUME_ATTEMPTS) {
322
+ this.resumeAttempts += 1;
323
+ this.pendingResume = checkpoint;
324
+ return;
325
+ }
326
+ this.killStream(err.message);
327
+ }
328
+
329
+ private killStream(reason: string): void {
330
+ if (this.streamDead) return;
331
+ this.streamDead = true;
332
+ this.pendingResume = undefined;
333
+ this.cur?.dispose();
334
+ this.cur = null;
335
+ log.warn("stream", "stream unavailable", { msgId: this.logMsgId(), reason });
336
+ this.deps.onWarn(`Stream unavailable; falling back to text (${reason}).`);
337
+ }
338
+ }