@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
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
2
|
-
import {
|
|
2
|
+
import { BubbleWriter } from "./bubble-writer";
|
|
3
3
|
import type { ReplyBudget } from "../quota/reply-quota";
|
|
4
4
|
import { log } from "../infra/file-logger";
|
|
5
|
-
import { THINKING_HEADER, formatToolLine, formatToolResult } from "./stream-block-format";
|
|
6
5
|
|
|
7
6
|
export interface RunFeedbackDeps {
|
|
8
7
|
bot: () => QQBot | undefined;
|
|
@@ -11,8 +10,6 @@ export interface RunFeedbackDeps {
|
|
|
11
10
|
onWarn: (msg: string) => void;
|
|
12
11
|
}
|
|
13
12
|
|
|
14
|
-
type BlockKind = "none" | "thinking" | "tool" | "text";
|
|
15
|
-
|
|
16
13
|
interface ToolCall {
|
|
17
14
|
id: string;
|
|
18
15
|
name: string;
|
|
@@ -27,48 +24,31 @@ interface RunState {
|
|
|
27
24
|
openid: string;
|
|
28
25
|
msgId?: string;
|
|
29
26
|
thinkingSentLen: number;
|
|
30
|
-
thinkingAtLineStart: boolean;
|
|
31
|
-
snapshotText: string;
|
|
32
27
|
finalizedText: string;
|
|
33
28
|
resultSentLen: number;
|
|
34
|
-
lastKind: BlockKind;
|
|
35
|
-
cur: AppendStream | null;
|
|
36
|
-
pendingResume?: AppendStreamCheckpoint;
|
|
37
|
-
streamDead: boolean;
|
|
38
|
-
resumeAttempts: number;
|
|
39
|
-
pushedAny: boolean;
|
|
40
|
-
bubbleChars: number;
|
|
41
|
-
fenceOpen: boolean;
|
|
42
|
-
fenceLen: number;
|
|
43
|
-
fenceQuoted: boolean;
|
|
44
|
-
lastChar: string;
|
|
45
|
-
toolOpen: boolean;
|
|
46
|
-
activeTool?: string;
|
|
47
29
|
tools: ToolCall[];
|
|
30
|
+
activeTool?: string;
|
|
48
31
|
deferredThinking: string;
|
|
49
32
|
deferredText: string;
|
|
50
|
-
blockClosed: boolean;
|
|
51
33
|
hadError: boolean;
|
|
34
|
+
writer: BubbleWriter;
|
|
52
35
|
typingTimer?: ReturnType<typeof setInterval>;
|
|
53
36
|
}
|
|
54
37
|
|
|
55
38
|
const TYPING_INTERVAL_MS = 50_000;
|
|
56
39
|
const PENDING_TTL_MS = 15_000;
|
|
57
40
|
const RECOVERY_TTL_MS = 60_000;
|
|
58
|
-
const MAX_RESUME_ATTEMPTS = 2;
|
|
59
|
-
const MAX_BUBBLE_CHARS = 12_000;
|
|
60
|
-
|
|
61
|
-
function appendThinkingDelta(delta: string, run: RunState): string {
|
|
62
|
-
run.thinkingAtLineStart = delta.endsWith("\n");
|
|
63
|
-
return delta;
|
|
64
|
-
}
|
|
65
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Coordinates a QQ-triggered agent run: target selection, tool ordering,
|
|
44
|
+
* deferred content, typing indicators, and run lifetime. Bubble layout and
|
|
45
|
+
* stream I/O are delegated to BubbleWriter.
|
|
46
|
+
*/
|
|
66
47
|
export class RunFeedback {
|
|
67
48
|
private readonly deps: RunFeedbackDeps;
|
|
68
49
|
private pending: { openid: string; msgId: string; at: number } | null = null;
|
|
69
50
|
private recovery: { openid: string; msgId: string; at: number } | null = null;
|
|
70
51
|
private run: RunState | null = null;
|
|
71
|
-
private queue: Promise<void> = Promise.resolve();
|
|
72
52
|
private endPromise: Promise<void> = Promise.resolve();
|
|
73
53
|
private endResolve?: () => void;
|
|
74
54
|
|
|
@@ -110,34 +90,29 @@ export class RunFeedback {
|
|
|
110
90
|
const bot = this.deps.bot();
|
|
111
91
|
if (!bot) return;
|
|
112
92
|
|
|
93
|
+
const startedAt = Date.now();
|
|
94
|
+
const writer = new BubbleWriter({
|
|
95
|
+
bot: this.deps.bot,
|
|
96
|
+
budget: this.deps.budget,
|
|
97
|
+
openid: target.openid,
|
|
98
|
+
msgId: target.msgId,
|
|
99
|
+
startedAt,
|
|
100
|
+
onWarn: this.deps.onWarn,
|
|
101
|
+
});
|
|
113
102
|
const run: RunState = {
|
|
114
|
-
startedAt
|
|
103
|
+
startedAt,
|
|
115
104
|
openid: target.openid,
|
|
116
105
|
msgId: target.msgId,
|
|
117
106
|
thinkingSentLen: 0,
|
|
118
|
-
thinkingAtLineStart: true,
|
|
119
|
-
snapshotText: "",
|
|
120
107
|
finalizedText: "",
|
|
121
108
|
resultSentLen: 0,
|
|
122
|
-
lastKind: "none",
|
|
123
|
-
cur: null,
|
|
124
|
-
streamDead: false,
|
|
125
|
-
resumeAttempts: 0,
|
|
126
|
-
pushedAny: false,
|
|
127
|
-
bubbleChars: 0,
|
|
128
|
-
fenceOpen: false,
|
|
129
|
-
fenceLen: 0,
|
|
130
|
-
fenceQuoted: false,
|
|
131
|
-
lastChar: "",
|
|
132
|
-
toolOpen: false,
|
|
133
109
|
tools: [],
|
|
134
110
|
deferredThinking: "",
|
|
135
111
|
deferredText: "",
|
|
136
|
-
blockClosed: false,
|
|
137
112
|
hadError: false,
|
|
113
|
+
writer,
|
|
138
114
|
};
|
|
139
115
|
this.run = run;
|
|
140
|
-
this.queue = Promise.resolve();
|
|
141
116
|
log.debug("run", "started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
|
|
142
117
|
|
|
143
118
|
const keepTyping = () => {
|
|
@@ -149,7 +124,7 @@ export class RunFeedback {
|
|
|
149
124
|
|
|
150
125
|
onToolStart(toolName: string, args?: unknown, toolCallId?: string): void {
|
|
151
126
|
const run = this.run;
|
|
152
|
-
if (!run || run.
|
|
127
|
+
if (!run || run.writer.dead) return;
|
|
153
128
|
const id = toolCallId ?? toolName;
|
|
154
129
|
if (run.tools.some((tool) => tool.id === id)) return;
|
|
155
130
|
run.tools.push({ id, name: toolName, args, started: false, finished: false });
|
|
@@ -158,7 +133,7 @@ export class RunFeedback {
|
|
|
158
133
|
|
|
159
134
|
onToolEnd(toolName: string, isError: boolean, result?: unknown, toolCallId?: string): void {
|
|
160
135
|
const run = this.run;
|
|
161
|
-
if (!run || run.
|
|
136
|
+
if (!run || run.writer.dead) return;
|
|
162
137
|
const id = toolCallId ?? toolName;
|
|
163
138
|
const tool = run.tools.find((candidate) => candidate.id === id);
|
|
164
139
|
if (!tool) return;
|
|
@@ -166,20 +141,9 @@ export class RunFeedback {
|
|
|
166
141
|
if (run.activeTool === id) this.finishTool(run, tool);
|
|
167
142
|
}
|
|
168
143
|
|
|
169
|
-
private pushText(run: RunState, text: string): void {
|
|
170
|
-
const newBubble = this.startsNewBlock(run, "text");
|
|
171
|
-
const prefix = this.beginBlock(run, "text", newBubble);
|
|
172
|
-
this.push(run, `${prefix}${text}`, prefix.length > 0 || newBubble, false, newBubble);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
private finishEnd(): void {
|
|
176
|
-
this.endResolve?.();
|
|
177
|
-
this.endResolve = undefined;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
144
|
onAssistantDelta(snapshotText: string, snapshotThinking: string): void {
|
|
181
145
|
const run = this.run;
|
|
182
|
-
if (!run || run.
|
|
146
|
+
if (!run || run.writer.dead) return;
|
|
183
147
|
|
|
184
148
|
if (snapshotThinking.length > run.thinkingSentLen) {
|
|
185
149
|
const delta = snapshotThinking.slice(run.thinkingSentLen);
|
|
@@ -188,16 +152,7 @@ export class RunFeedback {
|
|
|
188
152
|
if (this.hasPendingTools(run)) {
|
|
189
153
|
run.deferredThinking += delta;
|
|
190
154
|
} else {
|
|
191
|
-
|
|
192
|
-
const prefix = this.beginBlock(run, "thinking", newBubble);
|
|
193
|
-
this.push(
|
|
194
|
-
run,
|
|
195
|
-
`${prefix}${appendThinkingDelta(delta, run)}`,
|
|
196
|
-
prefix.length > 0 || newBubble,
|
|
197
|
-
false,
|
|
198
|
-
newBubble,
|
|
199
|
-
true,
|
|
200
|
-
);
|
|
155
|
+
run.writer.pushThinking(delta);
|
|
201
156
|
}
|
|
202
157
|
}
|
|
203
158
|
}
|
|
@@ -210,7 +165,7 @@ export class RunFeedback {
|
|
|
210
165
|
run.deferredText += delta;
|
|
211
166
|
return;
|
|
212
167
|
}
|
|
213
|
-
|
|
168
|
+
run.writer.pushText(delta);
|
|
214
169
|
}
|
|
215
170
|
|
|
216
171
|
async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
|
|
@@ -218,17 +173,16 @@ export class RunFeedback {
|
|
|
218
173
|
if (!run) return false;
|
|
219
174
|
|
|
220
175
|
run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
|
|
221
|
-
run.snapshotText = "";
|
|
222
176
|
const delta = run.finalizedText.slice(run.resultSentLen);
|
|
223
177
|
run.resultSentLen = run.finalizedText.length;
|
|
224
178
|
if (!isError && text && delta) {
|
|
225
179
|
if (this.hasPendingTools(run)) {
|
|
226
180
|
run.deferredText += delta;
|
|
227
181
|
} else {
|
|
228
|
-
|
|
182
|
+
run.writer.pushText(delta);
|
|
229
183
|
}
|
|
230
184
|
}
|
|
231
|
-
if (!isError && text) run.
|
|
185
|
+
if (!isError && text) run.writer.closeBlock();
|
|
232
186
|
|
|
233
187
|
run.thinkingSentLen = 0;
|
|
234
188
|
if (isError) {
|
|
@@ -236,12 +190,11 @@ export class RunFeedback {
|
|
|
236
190
|
this.recovery = { openid: run.openid, msgId: run.msgId ?? "", at: Date.now() };
|
|
237
191
|
}
|
|
238
192
|
|
|
239
|
-
const ok = await
|
|
193
|
+
const ok = await run.writer.flush();
|
|
240
194
|
run.finalizedText = "";
|
|
241
|
-
run.snapshotText = "";
|
|
242
195
|
run.resultSentLen = 0;
|
|
243
196
|
if (isError) return false;
|
|
244
|
-
return ok && run.
|
|
197
|
+
return ok && run.writer.hasPushed;
|
|
245
198
|
}
|
|
246
199
|
|
|
247
200
|
async onAgentEnd(): Promise<void> {
|
|
@@ -250,84 +203,39 @@ export class RunFeedback {
|
|
|
250
203
|
this.finishEnd();
|
|
251
204
|
return;
|
|
252
205
|
}
|
|
253
|
-
await
|
|
206
|
+
await run.writer.whenIdle();
|
|
254
207
|
if (!this.hasPendingTools(run)) this.flushDeferred(run);
|
|
255
|
-
await
|
|
208
|
+
await run.writer.whenIdle();
|
|
256
209
|
this.clearTimers();
|
|
257
|
-
if (!run.hadError && run.
|
|
210
|
+
if (!run.hadError && run.writer.hasPushed) this.recovery = null;
|
|
258
211
|
this.run = null;
|
|
259
212
|
log.debug("run", "ended", {
|
|
260
213
|
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
261
214
|
elapsedMs: Date.now() - run.startedAt,
|
|
262
215
|
});
|
|
263
|
-
if (!run.
|
|
264
|
-
run.
|
|
216
|
+
if (!run.writer.hasPushed) {
|
|
217
|
+
run.writer.dispose();
|
|
265
218
|
this.finishEnd();
|
|
266
219
|
return;
|
|
267
220
|
}
|
|
268
|
-
const ok = await
|
|
269
|
-
if (ok
|
|
270
|
-
|
|
271
|
-
await run.cur.done();
|
|
272
|
-
} catch (err) {
|
|
273
|
-
log.warn("stream", "DONE failed", {
|
|
274
|
-
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
275
|
-
err,
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
run.cur?.dispose();
|
|
221
|
+
const ok = await run.writer.flush();
|
|
222
|
+
if (ok) await run.writer.done();
|
|
223
|
+
run.writer.dispose();
|
|
280
224
|
this.finishEnd();
|
|
281
225
|
}
|
|
282
226
|
|
|
283
227
|
dispose(): void {
|
|
284
228
|
this.clearTimers();
|
|
285
|
-
this.run?.
|
|
229
|
+
this.run?.writer.dispose();
|
|
286
230
|
this.run = null;
|
|
231
|
+
this.pending = null;
|
|
232
|
+
this.recovery = null;
|
|
287
233
|
this.finishEnd();
|
|
288
234
|
}
|
|
289
235
|
|
|
290
|
-
private
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
run.blockClosed = false;
|
|
294
|
-
if (kind === "thinking") run.thinkingAtLineStart = true;
|
|
295
|
-
return "";
|
|
296
|
-
}
|
|
297
|
-
if (run.lastKind === kind) return "";
|
|
298
|
-
let prefix = "";
|
|
299
|
-
if (run.lastKind !== "none") {
|
|
300
|
-
if (run.lastKind === "thinking" && !run.thinkingAtLineStart) prefix += "\n";
|
|
301
|
-
prefix += run.lastKind === "text" ? "\n\n" : "\n";
|
|
302
|
-
}
|
|
303
|
-
run.lastKind = kind;
|
|
304
|
-
run.blockClosed = false;
|
|
305
|
-
if (kind === "thinking") run.thinkingAtLineStart = true;
|
|
306
|
-
return prefix;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
private startsNewBlock(run: RunState, kind: BlockKind): boolean {
|
|
310
|
-
return run.blockClosed || (run.lastKind !== "none" && run.lastKind !== kind);
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
private async closeOpenFence(run: RunState): Promise<boolean> {
|
|
314
|
-
if (!run.fenceOpen) return true;
|
|
315
|
-
const stream = this.ensureStream(run);
|
|
316
|
-
if (!stream) return false;
|
|
317
|
-
const ticks = "`".repeat(run.fenceLen);
|
|
318
|
-
const closing = `\n${run.fenceQuoted ? "> " : ""}${ticks}\n`;
|
|
319
|
-
try {
|
|
320
|
-
await stream.append(closing);
|
|
321
|
-
run.bubbleChars += closing.length;
|
|
322
|
-
run.lastChar = "\n";
|
|
323
|
-
run.fenceOpen = false;
|
|
324
|
-
run.fenceLen = 0;
|
|
325
|
-
run.fenceQuoted = false;
|
|
326
|
-
return true;
|
|
327
|
-
} catch (err) {
|
|
328
|
-
if (run.cur === stream) this.handleStreamError(run, err as Error);
|
|
329
|
-
return false;
|
|
330
|
-
}
|
|
236
|
+
private finishEnd(): void {
|
|
237
|
+
this.endResolve?.();
|
|
238
|
+
this.endResolve = undefined;
|
|
331
239
|
}
|
|
332
240
|
|
|
333
241
|
private hasPendingTools(run: RunState): boolean {
|
|
@@ -335,54 +243,35 @@ export class RunFeedback {
|
|
|
335
243
|
}
|
|
336
244
|
|
|
337
245
|
private flushDeferred(run: RunState): void {
|
|
338
|
-
if (run.
|
|
246
|
+
if (run.writer.dead) return;
|
|
339
247
|
if (run.deferredThinking) {
|
|
340
248
|
const thinking = run.deferredThinking;
|
|
341
249
|
run.deferredThinking = "";
|
|
342
|
-
|
|
343
|
-
const prefix = this.beginBlock(run, "thinking", newBubble);
|
|
344
|
-
this.push(
|
|
345
|
-
run,
|
|
346
|
-
`${prefix}${appendThinkingDelta(thinking, run)}`,
|
|
347
|
-
prefix.length > 0 || newBubble,
|
|
348
|
-
false,
|
|
349
|
-
newBubble,
|
|
350
|
-
true,
|
|
351
|
-
);
|
|
250
|
+
run.writer.pushThinking(thinking);
|
|
352
251
|
}
|
|
353
252
|
if (run.deferredText) {
|
|
354
253
|
const text = run.deferredText;
|
|
355
254
|
run.deferredText = "";
|
|
356
|
-
|
|
255
|
+
run.writer.pushText(text);
|
|
357
256
|
}
|
|
358
257
|
}
|
|
359
258
|
|
|
360
259
|
private startNextTool(run: RunState): void {
|
|
361
|
-
if (run.
|
|
260
|
+
if (run.writer.dead || run.activeTool) return;
|
|
362
261
|
const tool = run.tools.find((candidate) => !candidate.started);
|
|
363
262
|
if (!tool) return;
|
|
364
263
|
tool.started = true;
|
|
365
264
|
run.activeTool = tool.id;
|
|
366
|
-
run.
|
|
367
|
-
const newBubble = run.lastKind !== "none";
|
|
368
|
-
const prefix = this.beginBlock(run, "tool", newBubble);
|
|
369
|
-
this.push(
|
|
370
|
-
run,
|
|
371
|
-
`${prefix}${formatToolLine(tool.name, tool.args)}\n\n`,
|
|
372
|
-
prefix.length > 0 || newBubble,
|
|
373
|
-
false,
|
|
374
|
-
newBubble,
|
|
375
|
-
);
|
|
265
|
+
run.writer.pushTool(tool.name, tool.args);
|
|
376
266
|
if (tool.result) this.finishTool(run, tool);
|
|
377
267
|
}
|
|
378
268
|
|
|
379
269
|
private finishTool(run: RunState, tool: ToolCall): void {
|
|
380
270
|
if (!tool.result || tool.finished) return;
|
|
381
271
|
tool.finished = true;
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
if (this.run !== run || run.streamDead) return;
|
|
272
|
+
run.writer.pushToolResult(tool.result.result, tool.result.isError);
|
|
273
|
+
run.writer.schedule(() => {
|
|
274
|
+
if (this.run !== run) return;
|
|
386
275
|
if (run.activeTool !== tool.id) return;
|
|
387
276
|
run.activeTool = undefined;
|
|
388
277
|
this.startNextTool(run);
|
|
@@ -390,193 +279,6 @@ export class RunFeedback {
|
|
|
390
279
|
});
|
|
391
280
|
}
|
|
392
281
|
|
|
393
|
-
private push(
|
|
394
|
-
run: RunState,
|
|
395
|
-
text: string,
|
|
396
|
-
blockBoundary = false,
|
|
397
|
-
endTool = false,
|
|
398
|
-
newBubble = false,
|
|
399
|
-
thinking = false,
|
|
400
|
-
): void {
|
|
401
|
-
if (!text || run.streamDead) return;
|
|
402
|
-
void this.enqueue(async () => {
|
|
403
|
-
if (this.run !== run || run.streamDead) return;
|
|
404
|
-
if (blockBoundary && !(await this.closeOpenFence(run))) return;
|
|
405
|
-
if (newBubble && run.cur && run.bubbleChars > 0 && !run.pendingResume) {
|
|
406
|
-
await this.rotateStream(run);
|
|
407
|
-
if (this.run !== run || run.streamDead) return;
|
|
408
|
-
}
|
|
409
|
-
if (
|
|
410
|
-
!newBubble &&
|
|
411
|
-
run.bubbleChars >= MAX_BUBBLE_CHARS &&
|
|
412
|
-
run.cur &&
|
|
413
|
-
!run.pendingResume &&
|
|
414
|
-
!run.fenceOpen &&
|
|
415
|
-
!run.toolOpen &&
|
|
416
|
-
(blockBoundary || run.lastChar === "\n")
|
|
417
|
-
) {
|
|
418
|
-
await this.rotateStream(run);
|
|
419
|
-
if (this.run !== run || run.streamDead) return;
|
|
420
|
-
}
|
|
421
|
-
const stream = this.ensureStream(run);
|
|
422
|
-
if (!stream) return;
|
|
423
|
-
run.pushedAny = true;
|
|
424
|
-
const outgoing = thinking && (!run.cur || run.bubbleChars === 0) ? `${THINKING_HEADER}${text}` : text;
|
|
425
|
-
try {
|
|
426
|
-
await stream.append(outgoing);
|
|
427
|
-
run.bubbleChars += outgoing.length;
|
|
428
|
-
this.trackFences(run, outgoing);
|
|
429
|
-
run.lastChar = outgoing.slice(-1);
|
|
430
|
-
if (endTool) run.toolOpen = false;
|
|
431
|
-
} catch (err) {
|
|
432
|
-
if (run.cur === stream) this.handleStreamError(run, err as Error);
|
|
433
|
-
}
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
private trackFences(run: RunState, text: string): void {
|
|
438
|
-
const previousChar = run.lastChar;
|
|
439
|
-
for (const match of text.matchAll(/(?:^|\n)[ \t>]*(`{3,})/g)) {
|
|
440
|
-
if (match.index === 0 && previousChar && previousChar !== "\n") continue;
|
|
441
|
-
const fenceLen = match[1].length;
|
|
442
|
-
const lineEnd = text.indexOf("\n", match.index + match[0].length);
|
|
443
|
-
const restOfLine = text.slice(match.index + match[0].length, lineEnd < 0 ? undefined : lineEnd);
|
|
444
|
-
if (restOfLine.includes("`".repeat(fenceLen))) continue;
|
|
445
|
-
if (!run.fenceOpen) {
|
|
446
|
-
run.fenceOpen = true;
|
|
447
|
-
run.fenceLen = fenceLen;
|
|
448
|
-
run.fenceQuoted = match[0].includes(">");
|
|
449
|
-
} else if (fenceLen >= run.fenceLen) {
|
|
450
|
-
run.fenceOpen = false;
|
|
451
|
-
run.fenceLen = 0;
|
|
452
|
-
run.fenceQuoted = false;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
private async rotateStream(run: RunState): Promise<void> {
|
|
458
|
-
const stream = run.cur;
|
|
459
|
-
if (!stream) return;
|
|
460
|
-
try {
|
|
461
|
-
if (run.lastChar && run.lastChar !== "\n") {
|
|
462
|
-
await stream.append("\n");
|
|
463
|
-
run.bubbleChars += 1;
|
|
464
|
-
run.lastChar = "\n";
|
|
465
|
-
run.thinkingAtLineStart = true;
|
|
466
|
-
}
|
|
467
|
-
await stream.flush();
|
|
468
|
-
await stream.done();
|
|
469
|
-
} catch (err) {
|
|
470
|
-
log.warn("stream", "bubble split failed", {
|
|
471
|
-
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
472
|
-
err,
|
|
473
|
-
});
|
|
474
|
-
if (run.cur === stream) this.handleStreamError(run, err as Error);
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
stream.dispose();
|
|
478
|
-
if (run.cur === stream) run.cur = null;
|
|
479
|
-
run.bubbleChars = 0;
|
|
480
|
-
run.fenceOpen = false;
|
|
481
|
-
run.fenceLen = 0;
|
|
482
|
-
run.fenceQuoted = false;
|
|
483
|
-
run.lastChar = "";
|
|
484
|
-
run.thinkingAtLineStart = true;
|
|
485
|
-
log.debug("stream", "bubble split", {
|
|
486
|
-
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
487
|
-
elapsedMs: Date.now() - run.startedAt,
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
private async drainQueue(): Promise<void> {
|
|
492
|
-
for (;;) {
|
|
493
|
-
const current = this.queue;
|
|
494
|
-
await current;
|
|
495
|
-
if (current === this.queue) return;
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
private enqueue(op: () => Promise<void>): Promise<void> {
|
|
500
|
-
const next = this.queue.then(op, op);
|
|
501
|
-
this.queue = next.catch(() => {});
|
|
502
|
-
return next;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
private ensureStream(run: RunState): AppendStream | null {
|
|
506
|
-
if (run.streamDead) return null;
|
|
507
|
-
if (run.cur) return run.cur;
|
|
508
|
-
const bot = this.deps.bot();
|
|
509
|
-
if (!bot || !run.msgId) return null;
|
|
510
|
-
const resume = run.pendingResume;
|
|
511
|
-
run.pendingResume = undefined;
|
|
512
|
-
const stream = new AppendStream(bot.messageApi, bot.getCredentials(), run.openid, run.msgId, {
|
|
513
|
-
resume,
|
|
514
|
-
onError: (err) => {
|
|
515
|
-
void this.enqueue(async () => {
|
|
516
|
-
if (this.run !== run) return;
|
|
517
|
-
if (run.cur === stream) this.handleStreamError(run, err);
|
|
518
|
-
});
|
|
519
|
-
},
|
|
520
|
-
});
|
|
521
|
-
run.cur = stream;
|
|
522
|
-
if (!resume) this.deps.budget.noteStreamBubble(run.msgId);
|
|
523
|
-
return stream;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
private async flushStream(run: RunState): Promise<boolean> {
|
|
527
|
-
await this.drainQueue();
|
|
528
|
-
if (run.streamDead) return false;
|
|
529
|
-
if (!run.cur && !run.pendingResume) return true;
|
|
530
|
-
for (let attempt = 0; attempt <= MAX_RESUME_ATTEMPTS; attempt++) {
|
|
531
|
-
const stream = this.ensureStream(run);
|
|
532
|
-
if (!stream) return false;
|
|
533
|
-
try {
|
|
534
|
-
await stream.flush();
|
|
535
|
-
await this.queue;
|
|
536
|
-
if (run.streamDead) return false;
|
|
537
|
-
if (run.cur !== stream) continue;
|
|
538
|
-
return true;
|
|
539
|
-
} catch (err) {
|
|
540
|
-
this.handleStreamError(run, err as Error);
|
|
541
|
-
if (run.streamDead) return false;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
this.killStream(run, "resume attempts exhausted");
|
|
545
|
-
return false;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
private handleStreamError(run: RunState, err: Error): void {
|
|
549
|
-
if (run.streamDead) return;
|
|
550
|
-
const stream = run.cur;
|
|
551
|
-
const checkpoint = stream?.checkpoint() ?? null;
|
|
552
|
-
stream?.dispose();
|
|
553
|
-
run.cur = null;
|
|
554
|
-
log.warn("stream", "stream error", {
|
|
555
|
-
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
556
|
-
elapsedMs: Date.now() - run.startedAt,
|
|
557
|
-
err,
|
|
558
|
-
});
|
|
559
|
-
if (checkpoint && run.resumeAttempts < MAX_RESUME_ATTEMPTS) {
|
|
560
|
-
run.resumeAttempts += 1;
|
|
561
|
-
run.pendingResume = checkpoint;
|
|
562
|
-
return;
|
|
563
|
-
}
|
|
564
|
-
this.killStream(run, err.message);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
private killStream(run: RunState, reason: string): void {
|
|
568
|
-
if (run.streamDead) return;
|
|
569
|
-
run.streamDead = true;
|
|
570
|
-
run.pendingResume = undefined;
|
|
571
|
-
run.cur?.dispose();
|
|
572
|
-
run.cur = null;
|
|
573
|
-
log.warn("stream", "stream unavailable", {
|
|
574
|
-
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
575
|
-
reason,
|
|
576
|
-
});
|
|
577
|
-
this.deps.onWarn(`Stream unavailable; falling back to text (${reason}).`);
|
|
578
|
-
}
|
|
579
|
-
|
|
580
282
|
private clearTimers(): void {
|
|
581
283
|
const run = this.run;
|
|
582
284
|
if (!run) return;
|
|
@@ -21,9 +21,13 @@ const TOOL_ICONS: Record<string, string> = {
|
|
|
21
21
|
test: "🧪",
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
function
|
|
24
|
+
function backtickFence(text: string, minimum: number): string {
|
|
25
25
|
const runs = text.match(/`+/g) ?? [];
|
|
26
|
-
|
|
26
|
+
return "`".repeat(Math.max(minimum, ...runs.map((run) => run.length + 1)));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function inlineCode(text: string): string {
|
|
30
|
+
const ticks = backtickFence(text, 1);
|
|
27
31
|
const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";
|
|
28
32
|
return `${ticks}${pad}${text}${pad}${ticks}`;
|
|
29
33
|
}
|
|
@@ -108,7 +112,6 @@ export function formatToolResult(result: unknown, isError: boolean): string {
|
|
|
108
112
|
if (!text) text = "(no output)";
|
|
109
113
|
text = truncateText(text, RESULT_MAX_CHARS, RESULT_MAX_LINES);
|
|
110
114
|
if (isError) text = `❌ ${text}`;
|
|
111
|
-
const
|
|
112
|
-
const fence = "`".repeat(Math.max(3, ...runs.map((run) => run.length + 1)));
|
|
115
|
+
const fence = backtickFence(text, 3);
|
|
113
116
|
return `${fence}text\n${text}\n${fence}\n`;
|
|
114
117
|
}
|