@chen_hu_hu/pi-qq 1.3.0 → 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.
- package/CHANGELOG.md +61 -0
- package/README-zh.md +67 -47
- package/README.md +70 -50
- package/doc/archive/README.md +18 -0
- package/doc/{delivery-v1-zh.md → archive/delivery-v1-zh.md} +9 -8
- package/doc/{delivery-v1.md → archive/delivery-v1.md} +4 -3
- package/doc/{delivery-v2-zh.md → archive/delivery-v2-zh.md} +3 -2
- package/doc/{delivery-v2.md → archive/delivery-v2.md} +3 -2
- package/doc/{delivery-v3-zh.md → archive/delivery-v3-zh.md} +5 -2
- package/doc/{delivery-v3.md → archive/delivery-v3.md} +6 -3
- package/index.ts +70 -156
- package/package.json +5 -1
- package/src/attachments/attachment-failure.ts +12 -0
- package/src/attachments/file-attachments.ts +16 -19
- package/src/infra/file-logger.ts +21 -9
- package/src/infra/settings.ts +62 -8
- package/src/qq/inbound-attachments.ts +101 -0
- package/src/qq/inbound-command.ts +74 -0
- package/src/qq/qq-bot.ts +2 -2
- package/src/qq/qq-diagnostics.ts +129 -0
- package/src/qq/qq-message-handler.ts +42 -156
- package/src/qq/qr-login.ts +4 -1
- package/src/qq/reply-sender.ts +5 -4
- package/src/relay/bubble-writer.ts +338 -0
- package/src/relay/run-stream-relay.ts +50 -348
- package/src/relay/stream-block-format.ts +7 -4
- package/src/attachments/image-attachments.ts +0 -142
|
@@ -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
|
+
}
|