@chen_hu_hu/pi-qq 1.3.5 → 1.4.0

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/src/infra/i18n.ts CHANGED
@@ -214,6 +214,8 @@ const enUS = {
214
214
  "log.messageReceived": "message received",
215
215
  "log.ended": "ended",
216
216
  "log.starting": "starting",
217
+ "log.streamTiming": "stream timing",
218
+ "log.eventLoopDelay": "event loop delay",
217
219
  } as const;
218
220
 
219
221
  export type TranslationKey = keyof typeof enUS;
@@ -426,6 +428,8 @@ const zhCN: Record<TranslationKey, string> = {
426
428
  "log.messageReceived": "收到消息",
427
429
  "log.ended": "已结束",
428
430
  "log.starting": "启动中",
431
+ "log.streamTiming": "流式时序",
432
+ "log.eventLoopDelay": "事件循环延迟",
429
433
  };
430
434
 
431
435
  const dictionaries: Record<Language, Record<TranslationKey, string>> = {
@@ -500,6 +504,8 @@ const LOG_MESSAGE_KEYS: Record<string, TranslationKey> = {
500
504
  start: "log.toolStart",
501
505
  started: "log.sessionStarted",
502
506
  starting: "log.botStarting",
507
+ "stream timing": "log.streamTiming",
508
+ "event loop delay": "log.eventLoopDelay",
503
509
  "starting bot": "log.sessionStartingBot",
504
510
  "starting bot after login failed": "log.startBotAfterLoginFailed",
505
511
  "stream error": "log.streamError",
@@ -1,4 +1,5 @@
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
5
  /** The slice of ExtensionContext used by QQ inbound handling. */
@@ -54,7 +55,13 @@ export async function handleInboundCommand(
54
55
  await reply(t("commands.stop.none"));
55
56
  } else {
56
57
  deps.ctx.abort();
58
+ const waitStartedAt = Date.now();
59
+ log.debug("inbound", "stream timing", { phase: "/stop wait start" });
57
60
  await deps.waitForEnd?.();
61
+ log.debug("inbound", "stream timing", {
62
+ phase: "/stop wait done",
63
+ waitedMs: Date.now() - waitStartedAt,
64
+ });
58
65
  await reply(t("commands.stop.abort"));
59
66
  }
60
67
  break;
@@ -108,13 +108,13 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
108
108
 
109
109
  stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
110
110
  await stream.append(
111
- `${thinkingHeader()}${t("diagnostics.probeThinking")}\n\n**💻 bash**\n\n\`echo probe\`\n\n\`\`\`text\n${t("diagnostics.probeCode")}\n\`\`\`\n`,
111
+ `${thinkingHeader()}${t("diagnostics.probeThinking")}\n\n## 💻 bash\n\n\`\`\`bash\necho probe\n\`\`\`\n\n\`\`\`text\n${t("diagnostics.probeCode")}\n\`\`\`\n`,
112
112
  );
113
113
  await sleep(1200);
114
114
  await stream.append(`\n${t("diagnostics.probeIntermediate")}\n`);
115
115
  await sleep(1200);
116
116
  await stream.append(
117
- `\n**📖 read**\n\n\`src/index.ts\`\n\n\`\`\`text\n${t("diagnostics.probeReadFile")}\n\`\`\`\n`,
117
+ `\n## 📖 read\n\n\`src/index.ts\`\n\n\`\`\`typescript\n${t("diagnostics.probeReadFile")}\n\`\`\`\n`,
118
118
  );
119
119
  await sleep(800);
120
120
  await stream.append(`\n${t("diagnostics.probeFinal")}`);
@@ -94,6 +94,11 @@ export async function sendStreamReply(
94
94
  target: StreamTarget,
95
95
  budget?: ReplyBudget,
96
96
  ): Promise<void> {
97
+ log.debug("stream", "stream timing", {
98
+ phase: "last reply stream",
99
+ msgId: target.msgId.slice(0, 8),
100
+ textLength: text.length,
101
+ });
97
102
  const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
98
103
  budget?.noteStreamBubble(target.msgId);
99
104
  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";
@@ -31,6 +37,7 @@ export class BubbleWriter {
31
37
  private resumeAttempts = 0;
32
38
  private pushedAny = false;
33
39
  private bubbleChars = 0;
40
+ private lastFrameAt = 0;
34
41
  private fenceOpen = false;
35
42
  private fenceLen = 0;
36
43
  private fenceQuoted = false;
@@ -52,6 +59,33 @@ export class BubbleWriter {
52
59
  return this.streamDead;
53
60
  }
54
61
 
62
+ /** Snapshot used by debug logs to explain stalls without changing relay behavior. */
63
+ stats(now = Date.now()): {
64
+ dead: boolean;
65
+ disposed: boolean;
66
+ hasStream: boolean;
67
+ hasPendingResume: boolean;
68
+ resumeAttempts: number;
69
+ bubbleChars: number;
70
+ hasPushed: boolean;
71
+ lastKind: string;
72
+ toolOpen: boolean;
73
+ lastFrameAgeMs: number | null;
74
+ } {
75
+ return {
76
+ dead: this.streamDead,
77
+ disposed: this.disposed,
78
+ hasStream: Boolean(this.cur),
79
+ hasPendingResume: Boolean(this.pendingResume),
80
+ resumeAttempts: this.resumeAttempts,
81
+ bubbleChars: this.bubbleChars,
82
+ hasPushed: this.pushedAny,
83
+ lastKind: this.lastKind,
84
+ toolOpen: this.toolOpen,
85
+ lastFrameAgeMs: this.lastFrameAt ? now - this.lastFrameAt : null,
86
+ };
87
+ }
88
+
55
89
  /** Mark the current block as complete so the next content starts a new bubble. */
56
90
  closeBlock(): void {
57
91
  this.blockClosed = true;
@@ -77,7 +111,24 @@ export class BubbleWriter {
77
111
  this.toolOpen = true;
78
112
  const newBubble = this.lastKind !== "none";
79
113
  const prefix = this.beginBlock("tool", newBubble);
80
- this.push(`${prefix}${formatToolLine(name, args)}\n\n`, prefix.length > 0 || newBubble, false, newBubble);
114
+ if (isLogEnabled("debug")) {
115
+ log.debug("stream", "stream timing", {
116
+ phase: "tool queued",
117
+ msgId: this.logMsgId(),
118
+ tool: name,
119
+ at: Date.now(),
120
+ stats: this.stats(),
121
+ budget: this.deps.budget.snapshot(),
122
+ });
123
+ }
124
+ this.push(
125
+ `${prefix}${formatToolLine(name, args)}\n\n`,
126
+ prefix.length > 0 || newBubble,
127
+ false,
128
+ newBubble,
129
+ false,
130
+ "tool",
131
+ );
81
132
  }
82
133
 
83
134
  pushSkill(name: string): void {
@@ -85,13 +136,14 @@ export class BubbleWriter {
85
136
  this.toolOpen = false;
86
137
  const newBubble = true;
87
138
  const prefix = this.beginBlock("tool", newBubble);
88
- this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble);
139
+ this.push(`${prefix}${formatSkillBlock(name)}`, prefix.length > 0 || newBubble, false, newBubble, false, "skill");
89
140
  }
90
141
 
91
- pushToolResult(result: unknown, isError: boolean): void {
142
+ pushToolResult(result: unknown, isError: boolean, toolName?: string, args?: unknown): void {
92
143
  if (this.streamDead || this.disposed) return;
93
144
  const prefix = this.beginBlock("tool");
94
- this.push(`${prefix}${formatToolResult(result, isError)}`, prefix.length > 0, true);
145
+ const language = toolName ? resultLanguage(toolName, args, isError) : "text";
146
+ this.push(`${prefix}${formatToolResult(result, isError, language)}`, prefix.length > 0, true);
95
147
  }
96
148
 
97
149
  /** Run `op` after all currently queued appends, unless the stream died first. */
@@ -221,10 +273,28 @@ export class BubbleWriter {
221
273
  }
222
274
  }
223
275
 
224
- private push(text: string, blockBoundary = false, endTool = false, newBubble = false, thinking = false): void {
276
+ private push(
277
+ text: string,
278
+ blockBoundary = false,
279
+ endTool = false,
280
+ newBubble = false,
281
+ thinking = false,
282
+ trace?: string,
283
+ ): void {
225
284
  if (!text || this.streamDead || this.disposed) return;
285
+ const queuedAt = trace ? Date.now() : 0;
226
286
  void this.enqueue(async () => {
227
287
  if (this.streamDead || this.disposed) return;
288
+ if (trace && isLogEnabled("debug")) {
289
+ const now = Date.now();
290
+ log.debug("stream", "stream timing", {
291
+ phase: "append start",
292
+ trace,
293
+ msgId: this.logMsgId(),
294
+ waitedMs: now - queuedAt,
295
+ stats: this.stats(now),
296
+ });
297
+ }
228
298
  if (blockBoundary && !(await this.closeOpenFence())) return;
229
299
  if (newBubble && this.cur && this.bubbleChars > 0 && !this.pendingResume) {
230
300
  await this.rotateStream();
@@ -249,9 +319,19 @@ export class BubbleWriter {
249
319
  try {
250
320
  await stream.append(outgoing);
251
321
  this.bubbleChars += outgoing.length;
322
+ this.lastFrameAt = Date.now();
252
323
  this.trackFences(outgoing);
253
324
  this.lastChar = outgoing.slice(-1);
254
325
  if (endTool) this.toolOpen = false;
326
+ if (trace && isLogEnabled("debug")) {
327
+ log.debug("stream", "stream timing", {
328
+ phase: "append done",
329
+ trace,
330
+ msgId: this.logMsgId(),
331
+ totalMs: Date.now() - queuedAt,
332
+ stats: this.stats(),
333
+ });
334
+ }
255
335
  } catch (err) {
256
336
  if (this.cur === stream) this.handleStreamError(err as Error);
257
337
  }
@@ -303,10 +383,13 @@ export class BubbleWriter {
303
383
  this.fenceQuoted = false;
304
384
  this.lastChar = "";
305
385
  this.thinkingAtLineStart = true;
306
- log.debug("stream", "bubble split", {
307
- msgId: this.logMsgId(),
308
- elapsedMs: Date.now() - this.deps.startedAt,
309
- });
386
+ if (isLogEnabled("debug")) {
387
+ log.debug("stream", "bubble split", {
388
+ msgId: this.logMsgId(),
389
+ elapsedMs: Date.now() - this.deps.startedAt,
390
+ stats: this.stats(),
391
+ });
392
+ }
310
393
  }
311
394
 
312
395
  private drainQueue(): Promise<void> {
@@ -340,10 +423,42 @@ export class BubbleWriter {
340
423
  this.handleStreamError(err);
341
424
  });
342
425
  },
426
+ onFrameError: (err, info) => {
427
+ if (!isLogEnabled("debug")) return;
428
+ const e = err as { name?: string; message?: string; httpStatus?: number; bizCode?: number; path?: string };
429
+ log.debug("stream", "stream error", {
430
+ phase: "frame failed",
431
+ msgId: this.logMsgId(),
432
+ ...info,
433
+ errorName: e?.name ?? null,
434
+ errorMessage: e?.message ?? String(err),
435
+ httpStatus: e?.httpStatus ?? null,
436
+ bizCode: e?.bizCode ?? null,
437
+ path: e?.path ?? null,
438
+ stats: this.stats(),
439
+ budget: this.deps.budget.snapshot(),
440
+ });
441
+ },
343
442
  onDebug: (message) => log.debug("stream", message, { msgId: this.logMsgId() }),
344
443
  });
345
444
  this.cur = stream;
346
445
  if (!resume) this.deps.budget.noteStreamBubble(this.deps.msgId);
446
+ if (isLogEnabled("debug")) {
447
+ log.debug("stream", "stream timing", {
448
+ phase: "stream open",
449
+ msgId: this.logMsgId(),
450
+ resumed: Boolean(resume),
451
+ resume: resume
452
+ ? {
453
+ index: resume.index,
454
+ hasStreamMsgId: Boolean(resume.streamMsgId),
455
+ bufferLength: resume.buffer?.length ?? 0,
456
+ }
457
+ : null,
458
+ stats: this.stats(),
459
+ budget: this.deps.budget.snapshot(),
460
+ });
461
+ }
347
462
  return stream;
348
463
  }
349
464
 
@@ -356,6 +471,15 @@ export class BubbleWriter {
356
471
  log.warn("stream", "stream error", {
357
472
  msgId: this.logMsgId(),
358
473
  elapsedMs: Date.now() - this.deps.startedAt,
474
+ checkpoint: checkpoint
475
+ ? {
476
+ index: checkpoint.index,
477
+ hasStreamMsgId: Boolean(checkpoint.streamMsgId),
478
+ bufferLength: checkpoint.buffer?.length ?? 0,
479
+ }
480
+ : null,
481
+ stats: this.stats(),
482
+ budget: this.deps.budget.snapshot(),
359
483
  err,
360
484
  });
361
485
  if (checkpoint && this.resumeAttempts < MAX_RESUME_ATTEMPTS) {
@@ -372,7 +496,12 @@ export class BubbleWriter {
372
496
  this.pendingResume = undefined;
373
497
  this.cur?.dispose();
374
498
  this.cur = null;
375
- log.warn("stream", "stream unavailable", { msgId: this.logMsgId(), reason });
499
+ log.warn("stream", "stream unavailable", {
500
+ msgId: this.logMsgId(),
501
+ reason,
502
+ stats: this.stats(),
503
+ budget: this.deps.budget.snapshot(),
504
+ });
376
505
  this.deps.onWarn(t("stream.unavailable", { reason }));
377
506
  }
378
507
  }
@@ -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 {
@@ -93,7 +93,21 @@ export class RunFeedback {
93
93
  repushCurrent(openid: string, msgId: string): boolean {
94
94
  const run = this.run;
95
95
  const text = run?.currentText;
96
- if (!run || !text?.trim()) return false;
96
+ if (!run || !text?.trim()) {
97
+ log.debug("run", "stream timing", {
98
+ phase: "last repush ignored",
99
+ hasRun: Boolean(run),
100
+ textLength: text?.length ?? 0,
101
+ ...(run ? this.diagnostics(run) : {}),
102
+ });
103
+ return false;
104
+ }
105
+ log.debug("run", "stream timing", {
106
+ phase: "last repush",
107
+ msgId: msgId.slice(0, 8),
108
+ textLength: text.length,
109
+ ...this.diagnostics(run),
110
+ });
97
111
  // Rebind to the /last message so the new stream has a fresh passive window.
98
112
  run.openid = openid;
99
113
  run.msgId = msgId;
@@ -117,9 +131,21 @@ export class RunFeedback {
117
131
  : this.recovery && now - this.recovery.at <= RECOVERY_TTL_MS
118
132
  ? this.recovery
119
133
  : undefined;
120
- if (!target) return;
134
+ if (!target) {
135
+ log.debug("run", "run started", {
136
+ phase: "no qq target",
137
+ pendingAgeMs: pending ? now - pending.at : null,
138
+ recoveryAgeMs: this.recovery ? now - this.recovery.at : null,
139
+ pendingTtlMs: PENDING_TTL_MS,
140
+ recoveryTtlMs: RECOVERY_TTL_MS,
141
+ });
142
+ return;
143
+ }
121
144
  const bot = this.deps.bot();
122
- if (!bot) return;
145
+ if (!bot) {
146
+ log.debug("run", "run started", { phase: "no bot", msgId: target.msgId.slice(0, 8) });
147
+ return;
148
+ }
123
149
 
124
150
  const startedAt = Date.now();
125
151
  const writer = new BubbleWriter({
@@ -145,7 +171,14 @@ export class RunFeedback {
145
171
  writer,
146
172
  };
147
173
  this.run = run;
148
- log.debug("run", "run started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
174
+ if (isLogEnabled("debug")) {
175
+ log.debug("run", "run started", {
176
+ msgId: run.msgId?.slice(0, 8) ?? "?",
177
+ source: target === pending ? "pending" : "recovery",
178
+ targetAgeMs: now - target.at,
179
+ budget: this.deps.budget.snapshot(),
180
+ });
181
+ }
149
182
 
150
183
  const keepTyping = () => {
151
184
  void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
@@ -156,8 +189,20 @@ export class RunFeedback {
156
189
 
157
190
  onToolStart(toolName: string, args?: unknown, toolCallId?: string): void {
158
191
  const run = this.run;
159
- if (!run || run.writer.dead) return;
160
192
  const id = toolCallId ?? toolName;
193
+ if (!run) {
194
+ log.debug("run", "tool start", { phase: "ignored: no active run", toolName, toolCallId: id });
195
+ return;
196
+ }
197
+ if (run.writer.dead) {
198
+ log.debug("run", "tool start", {
199
+ phase: "ignored: stream dead",
200
+ toolName,
201
+ toolCallId: id,
202
+ ...this.diagnostics(run),
203
+ });
204
+ return;
205
+ }
161
206
  if (run.tools.some((tool) => tool.id === id)) return;
162
207
  const skill = detectSkillRead(toolName, args);
163
208
  run.tools.push({
@@ -168,16 +213,46 @@ export class RunFeedback {
168
213
  started: false,
169
214
  finished: false,
170
215
  });
216
+ log.debug("run", "tool start", {
217
+ phase: "queued",
218
+ toolName,
219
+ toolCallId: id,
220
+ skillName: skill?.name ?? null,
221
+ ...this.diagnostics(run),
222
+ });
171
223
  this.startNextTool(run);
172
224
  }
173
225
 
174
226
  onToolEnd(toolName: string, isError: boolean, result?: unknown, toolCallId?: string): void {
175
227
  const run = this.run;
176
- if (!run || run.writer.dead) return;
177
228
  const id = toolCallId ?? toolName;
229
+ if (!run) {
230
+ log.debug("run", "tool end", { phase: "ignored: no active run", toolName, toolCallId: id });
231
+ return;
232
+ }
178
233
  const tool = run.tools.find((candidate) => candidate.id === id);
179
- if (!tool) return;
234
+ if (!tool) {
235
+ log.debug("run", "tool end", { phase: "ignored: unknown tool", toolName, toolCallId: id });
236
+ return;
237
+ }
238
+ if (run.writer.dead) {
239
+ log.debug("run", "tool end", {
240
+ phase: "ignored: stream dead",
241
+ toolName,
242
+ toolCallId: id,
243
+ isError,
244
+ ...this.diagnostics(run),
245
+ });
246
+ return;
247
+ }
180
248
  tool.result = { isError, result };
249
+ log.debug("run", "tool end", {
250
+ phase: "result recorded",
251
+ toolName,
252
+ toolCallId: id,
253
+ isError,
254
+ ...this.diagnostics(run),
255
+ });
181
256
  if (run.activeTool === id) this.finishTool(run, tool);
182
257
  }
183
258
 
@@ -214,7 +289,14 @@ export class RunFeedback {
214
289
 
215
290
  async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
216
291
  const run = this.run;
217
- if (!run) return false;
292
+ if (!run) {
293
+ log.debug("run", "stream takeover decision", {
294
+ phase: "assistant final ignored: no active run",
295
+ textLength: text.length,
296
+ isError,
297
+ });
298
+ return false;
299
+ }
218
300
 
219
301
  run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
220
302
  if (text.trim()) run.currentText = text;
@@ -235,11 +317,26 @@ export class RunFeedback {
235
317
  this.recovery = { openid: run.openid, msgId: run.msgId ?? "", at: Date.now() };
236
318
  }
237
319
 
320
+ const hadPendingTools = this.hasPendingTools(run);
238
321
  const ok = await run.writer.flush();
322
+ const streamTookOver = !isError && ok && run.writer.hasPushed;
323
+ log.debug("run", "stream takeover decision", {
324
+ phase: "assistant final",
325
+ textLength: text.length,
326
+ deltaLength: delta.length,
327
+ isError,
328
+ hadPendingTools,
329
+ flushOk: ok,
330
+ hasPushed: run.writer.hasPushed,
331
+ streamTookOver,
332
+ deferredTextLen: run.deferredText.length,
333
+ deferredThinkingLen: run.deferredThinking.length,
334
+ ...this.diagnostics(run),
335
+ });
239
336
  run.finalizedText = "";
240
337
  run.resultSentLen = 0;
241
338
  if (isError) return false;
242
- return ok && run.writer.hasPushed;
339
+ return streamTookOver;
243
340
  }
244
341
 
245
342
  async onAgentEnd(): Promise<void> {
@@ -249,13 +346,24 @@ export class RunFeedback {
249
346
  return;
250
347
  }
251
348
  await run.writer.whenIdle();
252
- if (!this.hasPendingTools(run)) this.flushDeferred(run);
349
+ const hasPendingTools = this.hasPendingTools(run);
350
+ if (!hasPendingTools) this.flushDeferred(run);
253
351
  await run.writer.whenIdle();
254
352
  this.clearTimers();
255
353
  if (run.currentText.trim()) this.lastCompletedText = run.currentText;
256
354
  if (!run.hadError && run.writer.hasPushed) this.recovery = null;
355
+ log.debug("run", "run ended", {
356
+ phase: "cleanup",
357
+ msgId: run.msgId?.slice(0, 8) ?? "?",
358
+ elapsedMs: Date.now() - run.startedAt,
359
+ hasPendingTools,
360
+ hasPushed: run.writer.hasPushed,
361
+ lastCompletedTextLength: this.lastCompletedText?.length ?? 0,
362
+ ...this.diagnostics(run),
363
+ });
257
364
  this.run = null;
258
365
  log.debug("run", "run ended", {
366
+ phase: "finished",
259
367
  msgId: run.msgId?.slice(0, 8) ?? "?",
260
368
  elapsedMs: Date.now() - run.startedAt,
261
369
  });
@@ -271,6 +379,10 @@ export class RunFeedback {
271
379
  }
272
380
 
273
381
  dispose(): void {
382
+ const run = this.run;
383
+ if (run) {
384
+ log.debug("run", "run ended", { phase: "dispose", ...this.diagnostics(run) });
385
+ }
274
386
  this.clearTimers();
275
387
  this.run?.writer.dispose();
276
388
  this.run = null;
@@ -309,6 +421,13 @@ export class RunFeedback {
309
421
  if (!tool) return;
310
422
  tool.started = true;
311
423
  run.activeTool = tool.id;
424
+ log.debug("run", "tool start", {
425
+ phase: "output started",
426
+ toolName: tool.name,
427
+ toolCallId: tool.id,
428
+ skillName: tool.skillName ?? null,
429
+ ...this.diagnostics(run),
430
+ });
312
431
  if (tool.skillName) {
313
432
  run.writer.pushSkill(tool.skillName);
314
433
  } else {
@@ -320,8 +439,15 @@ export class RunFeedback {
320
439
  private finishTool(run: RunState, tool: ToolCall): void {
321
440
  if (!tool.result || tool.finished) return;
322
441
  tool.finished = true;
442
+ log.debug("run", "tool end", {
443
+ phase: "output finished",
444
+ toolName: tool.name,
445
+ toolCallId: tool.id,
446
+ isError: tool.result.isError,
447
+ ...this.diagnostics(run),
448
+ });
323
449
  if (!tool.skillName) {
324
- run.writer.pushToolResult(tool.result.result, tool.result.isError);
450
+ run.writer.pushToolResult(tool.result.result, tool.result.isError, tool.name, tool.args);
325
451
  }
326
452
  run.writer.schedule(() => {
327
453
  if (this.run !== run) return;
@@ -338,4 +464,32 @@ export class RunFeedback {
338
464
  if (run.typingTimer) clearInterval(run.typingTimer);
339
465
  run.typingTimer = undefined;
340
466
  }
467
+
468
+ /** Structured snapshot for debug logs; must not be called on hot paths. */
469
+ private diagnostics(run: RunState): Record<string, unknown> {
470
+ if (!isLogEnabled("debug")) return {};
471
+ return {
472
+ runElapsedMs: Date.now() - run.startedAt,
473
+ activeTool: run.activeTool ?? null,
474
+ toolCount: run.tools.length,
475
+ pendingToolCount: run.tools.filter((tool) => !tool.finished).length,
476
+ tools: run.tools.map((tool) => ({
477
+ id: tool.id,
478
+ name: tool.name,
479
+ started: tool.started,
480
+ finished: tool.finished,
481
+ hasResult: Boolean(tool.result),
482
+ isError: tool.result?.isError ?? null,
483
+ })),
484
+ deferredTextLen: run.deferredText.length,
485
+ deferredThinkingLen: run.deferredThinking.length,
486
+ currentTextLen: run.currentText.length,
487
+ finalizedTextLen: run.finalizedText.length,
488
+ resultSentLen: run.resultSentLen,
489
+ thinkingSentLen: run.thinkingSentLen,
490
+ hadError: run.hadError,
491
+ writer: run.writer.stats(),
492
+ budget: this.deps.budget.snapshot(),
493
+ };
494
+ }
341
495
  }