@chen_hu_hu/pi-qq 1.3.6 → 1.4.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.
@@ -22,10 +22,6 @@ export type ResolvedInbound =
22
22
  voiceCount: number;
23
23
  };
24
24
 
25
- /**
26
- * Turn one inbound message into injectable content: prefer ASR for voice,
27
- * persist every non-voice attachment, and report per-file failures.
28
- */
29
25
  export async function resolveInboundContent(
30
26
  msg: QQBotInboundMessage,
31
27
  options: ResolveInboundOptions,
@@ -56,7 +52,6 @@ export async function resolveInboundContent(
56
52
  }
57
53
  }
58
54
 
59
- // Voice attachments are handled above; all other attachments are stored as files.
60
55
  const attachmentsToSave = attachments.filter((attachment) => !isVoiceAttachment(attachment));
61
56
  const failures: AttachmentFailure[] = [];
62
57
  let files: SavedFile[] = [];
@@ -78,7 +73,6 @@ export async function resolveInboundContent(
78
73
  return { status: "resolved", text, files, failures, voiceCount: voiceAttachments.length };
79
74
  }
80
75
 
81
- /** Attachments that arrived without an instruction, consumed by the next text or voice message. */
82
76
  export class PendingAttachments {
83
77
  private files: SavedFile[] = [];
84
78
 
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { log } from "../infra/file-logger";
2
3
  import { t } from "../infra/i18n";
3
4
 
4
- /** The slice of ExtensionContext used by QQ inbound handling. */
5
5
  export interface InboundContext {
6
6
  readonly cwd: string;
7
7
  isIdle(): boolean;
@@ -54,7 +54,13 @@ export async function handleInboundCommand(
54
54
  await reply(t("commands.stop.none"));
55
55
  } else {
56
56
  deps.ctx.abort();
57
+ const waitStartedAt = Date.now();
58
+ log.debug("inbound", "stream timing", { phase: "/stop wait start" });
57
59
  await deps.waitForEnd?.();
60
+ log.debug("inbound", "stream timing", {
61
+ phase: "/stop wait done",
62
+ waitedMs: Date.now() - waitStartedAt,
63
+ });
58
64
  await reply(t("commands.stop.abort"));
59
65
  }
60
66
  break;
@@ -12,10 +12,6 @@ export interface QQDiagnosticsDeps {
12
12
  getBoundOpenid: () => string | undefined;
13
13
  }
14
14
 
15
- /**
16
- * Terminal-only protocol probes. Kept out of the entrypoint so index.ts stays
17
- * a composition root and does not construct stream frames directly.
18
- */
19
15
  export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps): void {
20
16
  const diagTarget = () => {
21
17
  const last = deps.budget.lastTarget;
@@ -108,13 +104,13 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
108
104
 
109
105
  stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
110
106
  await stream.append(
111
- `${thinkingHeader()}${t("diagnostics.probeThinking")}\n\n**💻 bash**\n\n\`echo probe\`\n\n\`\`\`text\n${t("diagnostics.probeCode")}\n\`\`\`\n`,
107
+ `${thinkingHeader()}${t("diagnostics.probeThinking")}\n\n## 💻 bash\n\n\`\`\`bash\necho probe\n\`\`\`\n\n\`\`\`text\n${t("diagnostics.probeCode")}\n\`\`\`\n`,
112
108
  );
113
109
  await sleep(1200);
114
110
  await stream.append(`\n${t("diagnostics.probeIntermediate")}\n`);
115
111
  await sleep(1200);
116
112
  await stream.append(
117
- `\n**📖 read**\n\n\`src/index.ts\`\n\n\`\`\`text\n${t("diagnostics.probeReadFile")}\n\`\`\`\n`,
113
+ `\n## 📖 read\n\n\`src/index.ts\`\n\n\`\`\`typescript\n${t("diagnostics.probeReadFile")}\n\`\`\`\n`,
118
114
  );
119
115
  await sleep(800);
120
116
  await stream.append(`\n${t("diagnostics.probeFinal")}`);
@@ -87,8 +87,6 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
87
87
  },
88
88
  handleInput(data: string): void {
89
89
  if (keybindings.matches(data, "tui.select.cancel") || data === "\x1b") {
90
- // Mark the login settled before aborting: the connector reports an
91
- // AbortError through onFailure, which must not look like a failure.
92
90
  finish();
93
91
  ac.abort();
94
92
  done();
@@ -87,13 +87,17 @@ export interface StreamTarget {
87
87
  msgId: string;
88
88
  }
89
89
 
90
- /** Send a complete message as one new stream bubble. */
91
90
  export async function sendStreamReply(
92
91
  bot: QQBot,
93
92
  text: string,
94
93
  target: StreamTarget,
95
94
  budget?: ReplyBudget,
96
95
  ): Promise<void> {
96
+ log.debug("stream", "stream timing", {
97
+ phase: "last reply stream",
98
+ msgId: target.msgId.slice(0, 8),
99
+ textLength: text.length,
100
+ });
97
101
  const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
98
102
  budget?.noteStreamBubble(target.msgId);
99
103
  try {
@@ -1,8 +1,14 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { AppendStream, type AppendStreamCheckpoint } from "./stream-session";
3
3
  import type { ReplyBudget } from "../quota/reply-quota";
4
- import { log } from "../infra/file-logger";
5
- import { formatSkillBlock, formatToolLine, formatToolResult, thinkingHeader } from "./stream-block-format";
4
+ import { isLogEnabled, log } from "../infra/file-logger";
5
+ import {
6
+ formatSkillBlock,
7
+ formatToolLine,
8
+ formatToolResult,
9
+ resultLanguage,
10
+ thinkingHeader,
11
+ } from "./stream-block-format";
6
12
  import { t } from "../infra/i18n";
7
13
 
8
14
  type BlockKind = "none" | "thinking" | "tool" | "text";
@@ -19,11 +25,6 @@ export interface BubbleWriterDeps {
19
25
  onWarn: (msg: string) => void;
20
26
  }
21
27
 
22
- /**
23
- * Owns one run's QQ stream: block layout, bubble rotation, fence tracking, and
24
- * stream recovery. Operations are serialized so callers can enqueue in event
25
- * order without waiting for network round-trips.
26
- */
27
28
  export class BubbleWriter {
28
29
  private cur: AppendStream | null = null;
29
30
  private pendingResume?: AppendStreamCheckpoint;
@@ -31,6 +32,7 @@ export class BubbleWriter {
31
32
  private resumeAttempts = 0;
32
33
  private pushedAny = false;
33
34
  private bubbleChars = 0;
35
+ private lastFrameAt = 0;
34
36
  private fenceOpen = false;
35
37
  private fenceLen = 0;
36
38
  private fenceQuoted = false;
@@ -52,7 +54,32 @@ export class BubbleWriter {
52
54
  return this.streamDead;
53
55
  }
54
56
 
55
- /** Mark the current block as complete so the next content starts a new bubble. */
57
+ stats(now = Date.now()): {
58
+ dead: boolean;
59
+ disposed: boolean;
60
+ hasStream: boolean;
61
+ hasPendingResume: boolean;
62
+ resumeAttempts: number;
63
+ bubbleChars: number;
64
+ hasPushed: boolean;
65
+ lastKind: string;
66
+ toolOpen: boolean;
67
+ lastFrameAgeMs: number | null;
68
+ } {
69
+ return {
70
+ dead: this.streamDead,
71
+ disposed: this.disposed,
72
+ hasStream: Boolean(this.cur),
73
+ hasPendingResume: Boolean(this.pendingResume),
74
+ resumeAttempts: this.resumeAttempts,
75
+ bubbleChars: this.bubbleChars,
76
+ hasPushed: this.pushedAny,
77
+ lastKind: this.lastKind,
78
+ toolOpen: this.toolOpen,
79
+ lastFrameAgeMs: this.lastFrameAt ? now - this.lastFrameAt : null,
80
+ };
81
+ }
82
+
56
83
  closeBlock(): void {
57
84
  this.blockClosed = true;
58
85
  }
@@ -77,13 +104,16 @@ export class BubbleWriter {
77
104
  this.toolOpen = true;
78
105
  const newBubble = this.lastKind !== "none";
79
106
  const prefix = this.beginBlock("tool", newBubble);
80
- log.debug("stream", "stream timing", {
81
- phase: "tool queued",
82
- msgId: this.logMsgId(),
83
- tool: name,
84
- at: Date.now(),
85
- hasStream: Boolean(this.cur),
86
- });
107
+ if (isLogEnabled("debug")) {
108
+ log.debug("stream", "stream timing", {
109
+ phase: "tool queued",
110
+ msgId: this.logMsgId(),
111
+ tool: name,
112
+ at: Date.now(),
113
+ stats: this.stats(),
114
+ budget: this.deps.budget.snapshot(),
115
+ });
116
+ }
87
117
  this.push(
88
118
  `${prefix}${formatToolLine(name, args)}\n\n`,
89
119
  prefix.length > 0 || newBubble,
@@ -102,13 +132,13 @@ export class BubbleWriter {
102
132
  this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble, false, "skill");
103
133
  }
104
134
 
105
- pushToolResult(result: unknown, isError: boolean): void {
135
+ pushToolResult(result: unknown, isError: boolean, toolName?: string, args?: unknown): void {
106
136
  if (this.streamDead || this.disposed) return;
107
137
  const prefix = this.beginBlock("tool");
108
- this.push(`${prefix}${formatToolResult(result, isError)}`, prefix.length > 0, true);
138
+ const language = toolName ? resultLanguage(toolName, args, isError) : "text";
139
+ this.push(`${prefix}${formatToolResult(result, isError, language)}`, prefix.length > 0, true);
109
140
  }
110
141
 
111
- /** Run `op` after all currently queued appends, unless the stream died first. */
112
142
  schedule(op: () => void): void {
113
143
  void this.enqueue(async () => {
114
144
  if (this.streamDead || this.disposed) return;
@@ -116,10 +146,6 @@ export class BubbleWriter {
116
146
  });
117
147
  }
118
148
 
119
- /**
120
- * Start a fresh bubble and push the current text again, reviving a stream
121
- * that died while the phone was offline. Later deltas continue in this bubble.
122
- */
123
149
  restartText(text: string, target?: { openid: string; msgId: string }): void {
124
150
  if (!text || this.disposed) return;
125
151
  void this.enqueue(async () => {
@@ -247,13 +273,14 @@ export class BubbleWriter {
247
273
  const queuedAt = trace ? Date.now() : 0;
248
274
  void this.enqueue(async () => {
249
275
  if (this.streamDead || this.disposed) return;
250
- if (trace) {
276
+ if (trace && isLogEnabled("debug")) {
277
+ const now = Date.now();
251
278
  log.debug("stream", "stream timing", {
252
279
  phase: "append start",
253
280
  trace,
254
281
  msgId: this.logMsgId(),
255
- waitedMs: Date.now() - queuedAt,
256
- hasStream: Boolean(this.cur),
282
+ waitedMs: now - queuedAt,
283
+ stats: this.stats(now),
257
284
  });
258
285
  }
259
286
  if (blockBoundary && !(await this.closeOpenFence())) return;
@@ -280,16 +307,17 @@ export class BubbleWriter {
280
307
  try {
281
308
  await stream.append(outgoing);
282
309
  this.bubbleChars += outgoing.length;
310
+ this.lastFrameAt = Date.now();
283
311
  this.trackFences(outgoing);
284
312
  this.lastChar = outgoing.slice(-1);
285
313
  if (endTool) this.toolOpen = false;
286
- if (trace) {
314
+ if (trace && isLogEnabled("debug")) {
287
315
  log.debug("stream", "stream timing", {
288
316
  phase: "append done",
289
317
  trace,
290
318
  msgId: this.logMsgId(),
291
319
  totalMs: Date.now() - queuedAt,
292
- bubbleChars: this.bubbleChars,
320
+ stats: this.stats(),
293
321
  });
294
322
  }
295
323
  } catch (err) {
@@ -343,10 +371,13 @@ export class BubbleWriter {
343
371
  this.fenceQuoted = false;
344
372
  this.lastChar = "";
345
373
  this.thinkingAtLineStart = true;
346
- log.debug("stream", "bubble split", {
347
- msgId: this.logMsgId(),
348
- elapsedMs: Date.now() - this.deps.startedAt,
349
- });
374
+ if (isLogEnabled("debug")) {
375
+ log.debug("stream", "bubble split", {
376
+ msgId: this.logMsgId(),
377
+ elapsedMs: Date.now() - this.deps.startedAt,
378
+ stats: this.stats(),
379
+ });
380
+ }
350
381
  }
351
382
 
352
383
  private drainQueue(): Promise<void> {
@@ -380,10 +411,42 @@ export class BubbleWriter {
380
411
  this.handleStreamError(err);
381
412
  });
382
413
  },
414
+ onFrameError: (err, info) => {
415
+ if (!isLogEnabled("debug")) return;
416
+ const e = err as { name?: string; message?: string; httpStatus?: number; bizCode?: number; path?: string };
417
+ log.debug("stream", "stream error", {
418
+ phase: "frame failed",
419
+ msgId: this.logMsgId(),
420
+ ...info,
421
+ errorName: e?.name ?? null,
422
+ errorMessage: e?.message ?? String(err),
423
+ httpStatus: e?.httpStatus ?? null,
424
+ bizCode: e?.bizCode ?? null,
425
+ path: e?.path ?? null,
426
+ stats: this.stats(),
427
+ budget: this.deps.budget.snapshot(),
428
+ });
429
+ },
383
430
  onDebug: (message) => log.debug("stream", message, { msgId: this.logMsgId() }),
384
431
  });
385
432
  this.cur = stream;
386
433
  if (!resume) this.deps.budget.noteStreamBubble(this.deps.msgId);
434
+ if (isLogEnabled("debug")) {
435
+ log.debug("stream", "stream timing", {
436
+ phase: "stream open",
437
+ msgId: this.logMsgId(),
438
+ resumed: Boolean(resume),
439
+ resume: resume
440
+ ? {
441
+ index: resume.index,
442
+ hasStreamMsgId: Boolean(resume.streamMsgId),
443
+ bufferLength: resume.buffer?.length ?? 0,
444
+ }
445
+ : null,
446
+ stats: this.stats(),
447
+ budget: this.deps.budget.snapshot(),
448
+ });
449
+ }
387
450
  return stream;
388
451
  }
389
452
 
@@ -396,6 +459,15 @@ export class BubbleWriter {
396
459
  log.warn("stream", "stream error", {
397
460
  msgId: this.logMsgId(),
398
461
  elapsedMs: Date.now() - this.deps.startedAt,
462
+ checkpoint: checkpoint
463
+ ? {
464
+ index: checkpoint.index,
465
+ hasStreamMsgId: Boolean(checkpoint.streamMsgId),
466
+ bufferLength: checkpoint.buffer?.length ?? 0,
467
+ }
468
+ : null,
469
+ stats: this.stats(),
470
+ budget: this.deps.budget.snapshot(),
399
471
  err,
400
472
  });
401
473
  if (checkpoint && this.resumeAttempts < MAX_RESUME_ATTEMPTS) {
@@ -412,7 +484,12 @@ export class BubbleWriter {
412
484
  this.pendingResume = undefined;
413
485
  this.cur?.dispose();
414
486
  this.cur = null;
415
- log.warn("stream", "stream unavailable", { msgId: this.logMsgId(), reason });
487
+ log.warn("stream", "stream unavailable", {
488
+ msgId: this.logMsgId(),
489
+ reason,
490
+ stats: this.stats(),
491
+ budget: this.deps.budget.snapshot(),
492
+ });
416
493
  this.deps.onWarn(t("stream.unavailable", { reason }));
417
494
  }
418
495
  }
@@ -1,7 +1,7 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { BubbleWriter } from "./bubble-writer";
3
3
  import type { ReplyBudget } from "../quota/reply-quota";
4
- import { log } from "../infra/file-logger";
4
+ import { isLogEnabled, log } from "../infra/file-logger";
5
5
  import { detectSkillRead } from "./stream-block-format";
6
6
 
7
7
  export interface RunFeedbackDeps {
@@ -27,7 +27,6 @@ interface RunState {
27
27
  msgId?: string;
28
28
  thinkingSentLen: number;
29
29
  finalizedText: string;
30
- /** Latest text of the current run, kept for the QQ /last command. */
31
30
  currentText: string;
32
31
  resultSentLen: number;
33
32
  tools: ToolCall[];
@@ -43,11 +42,6 @@ const TYPING_INTERVAL_MS = 50_000;
43
42
  const PENDING_TTL_MS = 15_000;
44
43
  const RECOVERY_TTL_MS = 60_000;
45
44
 
46
- /**
47
- * Coordinates a QQ-triggered agent run: target selection, tool ordering,
48
- * deferred content, typing indicators, and run lifetime. Bubble layout and
49
- * stream I/O are delegated to BubbleWriter.
50
- */
51
45
  export class RunFeedback {
52
46
  private readonly deps: RunFeedbackDeps;
53
47
  private pending: { openid: string; msgId: string; at: number } | null = null;
@@ -78,28 +72,30 @@ export class RunFeedback {
78
72
  return this.run ? this.endPromise : Promise.resolve();
79
73
  }
80
74
 
81
- /**
82
- * The final assistant text of the most recently completed QQ run.
83
- * No transcript is retained.
84
- */
85
75
  getLastMessage(): string | undefined {
86
76
  return this.lastCompletedText;
87
77
  }
88
78
 
89
- /**
90
- * Restart the current run's push with its latest text. This revives a stream
91
- * that may have died while the phone was offline; later deltas continue.
92
- */
93
79
  repushCurrent(openid: string, msgId: string): boolean {
94
80
  const run = this.run;
95
81
  const text = run?.currentText;
96
- if (!run || !text?.trim()) return false;
97
- // Rebind to the /last message so the new stream has a fresh passive window.
82
+ if (!run || !text?.trim()) {
83
+ log.debug("run", "stream timing", {
84
+ phase: "last repush ignored",
85
+ hasRun: Boolean(run),
86
+ textLength: text?.length ?? 0,
87
+ ...(run ? this.diagnostics(run) : {}),
88
+ });
89
+ return false;
90
+ }
91
+ log.debug("run", "stream timing", {
92
+ phase: "last repush",
93
+ msgId: msgId.slice(0, 8),
94
+ textLength: text.length,
95
+ ...this.diagnostics(run),
96
+ });
98
97
  run.openid = openid;
99
98
  run.msgId = msgId;
100
- // Push the current text in full. Do not rewrite resultSentLen: it belongs to
101
- // the assistant message currently being diffed, and changing it could drop
102
- // the beginning of the next message.
103
99
  run.writer.restartText(text, { openid, msgId });
104
100
  return true;
105
101
  }
@@ -117,9 +113,21 @@ export class RunFeedback {
117
113
  : this.recovery && now - this.recovery.at <= RECOVERY_TTL_MS
118
114
  ? this.recovery
119
115
  : undefined;
120
- if (!target) return;
116
+ if (!target) {
117
+ log.debug("run", "run started", {
118
+ phase: "no qq target",
119
+ pendingAgeMs: pending ? now - pending.at : null,
120
+ recoveryAgeMs: this.recovery ? now - this.recovery.at : null,
121
+ pendingTtlMs: PENDING_TTL_MS,
122
+ recoveryTtlMs: RECOVERY_TTL_MS,
123
+ });
124
+ return;
125
+ }
121
126
  const bot = this.deps.bot();
122
- if (!bot) return;
127
+ if (!bot) {
128
+ log.debug("run", "run started", { phase: "no bot", msgId: target.msgId.slice(0, 8) });
129
+ return;
130
+ }
123
131
 
124
132
  const startedAt = Date.now();
125
133
  const writer = new BubbleWriter({
@@ -145,7 +153,14 @@ export class RunFeedback {
145
153
  writer,
146
154
  };
147
155
  this.run = run;
148
- log.debug("run", "run started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
156
+ if (isLogEnabled("debug")) {
157
+ log.debug("run", "run started", {
158
+ msgId: run.msgId?.slice(0, 8) ?? "?",
159
+ source: target === pending ? "pending" : "recovery",
160
+ targetAgeMs: now - target.at,
161
+ budget: this.deps.budget.snapshot(),
162
+ });
163
+ }
149
164
 
150
165
  const keepTyping = () => {
151
166
  void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
@@ -156,8 +171,20 @@ export class RunFeedback {
156
171
 
157
172
  onToolStart(toolName: string, args?: unknown, toolCallId?: string): void {
158
173
  const run = this.run;
159
- if (!run || run.writer.dead) return;
160
174
  const id = toolCallId ?? toolName;
175
+ if (!run) {
176
+ log.debug("run", "tool start", { phase: "ignored: no active run", toolName, toolCallId: id });
177
+ return;
178
+ }
179
+ if (run.writer.dead) {
180
+ log.debug("run", "tool start", {
181
+ phase: "ignored: stream dead",
182
+ toolName,
183
+ toolCallId: id,
184
+ ...this.diagnostics(run),
185
+ });
186
+ return;
187
+ }
161
188
  if (run.tools.some((tool) => tool.id === id)) return;
162
189
  const skill = detectSkillRead(toolName, args);
163
190
  run.tools.push({
@@ -168,16 +195,46 @@ export class RunFeedback {
168
195
  started: false,
169
196
  finished: false,
170
197
  });
198
+ log.debug("run", "tool start", {
199
+ phase: "queued",
200
+ toolName,
201
+ toolCallId: id,
202
+ skillName: skill?.name ?? null,
203
+ ...this.diagnostics(run),
204
+ });
171
205
  this.startNextTool(run);
172
206
  }
173
207
 
174
208
  onToolEnd(toolName: string, isError: boolean, result?: unknown, toolCallId?: string): void {
175
209
  const run = this.run;
176
- if (!run || run.writer.dead) return;
177
210
  const id = toolCallId ?? toolName;
211
+ if (!run) {
212
+ log.debug("run", "tool end", { phase: "ignored: no active run", toolName, toolCallId: id });
213
+ return;
214
+ }
178
215
  const tool = run.tools.find((candidate) => candidate.id === id);
179
- if (!tool) return;
216
+ if (!tool) {
217
+ log.debug("run", "tool end", { phase: "ignored: unknown tool", toolName, toolCallId: id });
218
+ return;
219
+ }
220
+ if (run.writer.dead) {
221
+ log.debug("run", "tool end", {
222
+ phase: "ignored: stream dead",
223
+ toolName,
224
+ toolCallId: id,
225
+ isError,
226
+ ...this.diagnostics(run),
227
+ });
228
+ return;
229
+ }
180
230
  tool.result = { isError, result };
231
+ log.debug("run", "tool end", {
232
+ phase: "result recorded",
233
+ toolName,
234
+ toolCallId: id,
235
+ isError,
236
+ ...this.diagnostics(run),
237
+ });
181
238
  if (run.activeTool === id) this.finishTool(run, tool);
182
239
  }
183
240
 
@@ -214,7 +271,14 @@ export class RunFeedback {
214
271
 
215
272
  async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
216
273
  const run = this.run;
217
- if (!run) return false;
274
+ if (!run) {
275
+ log.debug("run", "stream takeover decision", {
276
+ phase: "assistant final ignored: no active run",
277
+ textLength: text.length,
278
+ isError,
279
+ });
280
+ return false;
281
+ }
218
282
 
219
283
  run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
220
284
  if (text.trim()) run.currentText = text;
@@ -235,11 +299,26 @@ export class RunFeedback {
235
299
  this.recovery = { openid: run.openid, msgId: run.msgId ?? "", at: Date.now() };
236
300
  }
237
301
 
302
+ const hadPendingTools = this.hasPendingTools(run);
238
303
  const ok = await run.writer.flush();
304
+ const streamTookOver = !isError && ok && run.writer.hasPushed;
305
+ log.debug("run", "stream takeover decision", {
306
+ phase: "assistant final",
307
+ textLength: text.length,
308
+ deltaLength: delta.length,
309
+ isError,
310
+ hadPendingTools,
311
+ flushOk: ok,
312
+ hasPushed: run.writer.hasPushed,
313
+ streamTookOver,
314
+ deferredTextLen: run.deferredText.length,
315
+ deferredThinkingLen: run.deferredThinking.length,
316
+ ...this.diagnostics(run),
317
+ });
239
318
  run.finalizedText = "";
240
319
  run.resultSentLen = 0;
241
320
  if (isError) return false;
242
- return ok && run.writer.hasPushed;
321
+ return streamTookOver;
243
322
  }
244
323
 
245
324
  async onAgentEnd(): Promise<void> {
@@ -249,13 +328,24 @@ export class RunFeedback {
249
328
  return;
250
329
  }
251
330
  await run.writer.whenIdle();
252
- if (!this.hasPendingTools(run)) this.flushDeferred(run);
331
+ const hasPendingTools = this.hasPendingTools(run);
332
+ if (!hasPendingTools) this.flushDeferred(run);
253
333
  await run.writer.whenIdle();
254
334
  this.clearTimers();
255
335
  if (run.currentText.trim()) this.lastCompletedText = run.currentText;
256
336
  if (!run.hadError && run.writer.hasPushed) this.recovery = null;
337
+ log.debug("run", "run ended", {
338
+ phase: "cleanup",
339
+ msgId: run.msgId?.slice(0, 8) ?? "?",
340
+ elapsedMs: Date.now() - run.startedAt,
341
+ hasPendingTools,
342
+ hasPushed: run.writer.hasPushed,
343
+ lastCompletedTextLength: this.lastCompletedText?.length ?? 0,
344
+ ...this.diagnostics(run),
345
+ });
257
346
  this.run = null;
258
347
  log.debug("run", "run ended", {
348
+ phase: "finished",
259
349
  msgId: run.msgId?.slice(0, 8) ?? "?",
260
350
  elapsedMs: Date.now() - run.startedAt,
261
351
  });
@@ -271,6 +361,10 @@ export class RunFeedback {
271
361
  }
272
362
 
273
363
  dispose(): void {
364
+ const run = this.run;
365
+ if (run) {
366
+ log.debug("run", "run ended", { phase: "dispose", ...this.diagnostics(run) });
367
+ }
274
368
  this.clearTimers();
275
369
  this.run?.writer.dispose();
276
370
  this.run = null;
@@ -309,6 +403,13 @@ export class RunFeedback {
309
403
  if (!tool) return;
310
404
  tool.started = true;
311
405
  run.activeTool = tool.id;
406
+ log.debug("run", "tool start", {
407
+ phase: "output started",
408
+ toolName: tool.name,
409
+ toolCallId: tool.id,
410
+ skillName: tool.skillName ?? null,
411
+ ...this.diagnostics(run),
412
+ });
312
413
  if (tool.skillName) {
313
414
  run.writer.pushSkill(tool.skillName);
314
415
  } else {
@@ -320,8 +421,15 @@ export class RunFeedback {
320
421
  private finishTool(run: RunState, tool: ToolCall): void {
321
422
  if (!tool.result || tool.finished) return;
322
423
  tool.finished = true;
424
+ log.debug("run", "tool end", {
425
+ phase: "output finished",
426
+ toolName: tool.name,
427
+ toolCallId: tool.id,
428
+ isError: tool.result.isError,
429
+ ...this.diagnostics(run),
430
+ });
323
431
  if (!tool.skillName) {
324
- run.writer.pushToolResult(tool.result.result, tool.result.isError);
432
+ run.writer.pushToolResult(tool.result.result, tool.result.isError, tool.name, tool.args);
325
433
  }
326
434
  run.writer.schedule(() => {
327
435
  if (this.run !== run) return;
@@ -338,4 +446,31 @@ export class RunFeedback {
338
446
  if (run.typingTimer) clearInterval(run.typingTimer);
339
447
  run.typingTimer = undefined;
340
448
  }
449
+
450
+ private diagnostics(run: RunState): Record<string, unknown> {
451
+ if (!isLogEnabled("debug")) return {};
452
+ return {
453
+ runElapsedMs: Date.now() - run.startedAt,
454
+ activeTool: run.activeTool ?? null,
455
+ toolCount: run.tools.length,
456
+ pendingToolCount: run.tools.filter((tool) => !tool.finished).length,
457
+ tools: run.tools.map((tool) => ({
458
+ id: tool.id,
459
+ name: tool.name,
460
+ started: tool.started,
461
+ finished: tool.finished,
462
+ hasResult: Boolean(tool.result),
463
+ isError: tool.result?.isError ?? null,
464
+ })),
465
+ deferredTextLen: run.deferredText.length,
466
+ deferredThinkingLen: run.deferredThinking.length,
467
+ currentTextLen: run.currentText.length,
468
+ finalizedTextLen: run.finalizedText.length,
469
+ resultSentLen: run.resultSentLen,
470
+ thinkingSentLen: run.thinkingSentLen,
471
+ hadError: run.hadError,
472
+ writer: run.writer.stats(),
473
+ budget: this.deps.budget.snapshot(),
474
+ };
475
+ }
341
476
  }