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