@chen_hu_hu/pi-qq 1.0.1 → 1.1.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.
@@ -2,22 +2,24 @@ import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { AppendStream } from "./append-stream";
3
3
  import { sendReply, type ReplyChannel } from "./outbound";
4
4
  import type { ReplyBudget } from "./reply-budget";
5
+ import { log } from "./logger";
5
6
 
6
7
  /**
7
- * F7 长任务反馈:run 级状态机(汇总帧 + 文本气泡切分版)。
8
+ * F7 long-task feedback: run-level state machine (summary frames + text bubbles).
8
9
  *
9
- * 场景:user_input → thinking+tools(10~60 分钟)→ assistant message,n 轮循环。
10
+ * Scenario: user_input → thinking/tools (10–60 minutes) → assistant message, n turns.
10
11
  *
11
- * 气泡切分规则:**assistant 文本消息与思考/工具汇总使用独立气泡**。
12
- * 文本消息(同一 assistant 消息的流式增量)独占一个文本气泡;思考/工具行组进入
13
- * 活动气泡。文本首个增量到达时封口当前活动气泡;工具/思考出现时封口当前文本气泡,
14
- * 新行组进新的活动气泡;最终回复独立成文本气泡。气泡内按 `streamFlushMs`
15
- * (默认 10000ms)固定频率发送窗口汇总帧:
12
+ * Bubble rules: **assistant text and thinking/tool summaries use separate bubbles.**
13
+ * Each text message (streaming increments of one assistant message) owns a text
14
+ * bubble; thinking/tool line groups go to an activity bubble. The first text delta
15
+ * closes the current activity bubble; a line group closes the current text bubble.
16
+ * The final reply is its own text bubble. Frames are sent every `streamFlushMs`
17
+ * (default 10000ms):
16
18
  *
17
- * 活动气泡:💭 思考中... / [2] 🔧 bash(行组按事件顺序、外层带 [HH:MM:SS] 时间戳)
18
- * 文本气泡:消息原文(流式增量,按 markdown 渲染)
19
+ * Activity: [💭] Thinking... / [🔧] [2] bash (event order)
20
+ * Text: message text (streamed increments, rendered as Markdown)
19
21
  *
20
- * 任何一帧失败即弃气泡:未发出的结果文本自动转消息路径补发;下一个文本消息重试新气泡。
22
+ * Any failed frame discards the bubble; unsent text falls back to the message path.
21
23
  */
22
24
 
23
25
  export interface ToolStat {
@@ -31,11 +33,9 @@ export interface RunFeedbackDeps {
31
33
  boundOpenid: () => string | undefined;
32
34
  getHeartbeatMinutes: () => number;
33
35
  getHeartbeatMaxMessages: () => number;
34
- /** 流式汇总帧间隔(毫秒,最小 300) */
36
+ /** Stream summary frame interval in ms (minimum 300). */
35
37
  getStreamFlushMs: () => number;
36
38
  getStreamRelay: () => boolean;
37
- /** 诊断模式:SDK 日志转终端 + 文本帧也带时间戳 */
38
- getDebug: () => boolean;
39
39
  makeChannel: () => ReplyChannel;
40
40
  onWarn: (msg: string) => void;
41
41
  }
@@ -45,7 +45,7 @@ interface ToolStat2 {
45
45
  errors: number;
46
46
  }
47
47
 
48
- /** 当前气泡:一条独立流式消息;kind 决定它只接收文本还是思考/工具行组 */
48
+ /** Current bubble: one stream message; kind selects text or activity rows. */
49
49
  interface Bubble {
50
50
  stream: AppendStream;
51
51
  kind: "activity" | "text";
@@ -57,23 +57,23 @@ interface RunState {
57
57
  startedAt: number;
58
58
  openid: string;
59
59
  msgId?: string;
60
- /** 工具总计(心跳 ⏱ 行用) */
60
+ /** Total tool counts (for the heartbeat line). */
61
61
  tools: Map<string, ToolStat2>;
62
- /** 本窗口行组,按事件实际发生顺序记录(flush 后清空) */
62
+ /** Line groups in this window, in event order (cleared after flush). */
63
63
  winLines: WindowLine[];
64
- /** 本消息已打过思考标记(逐消息复位,避免长思考刷屏) */
64
+ /** Thinking marker for the current message (reset per message). */
65
65
  thinkingMarked: boolean;
66
- /** 当前流式文本快照(message_update 更新) */
66
+ /** Current streaming text snapshot (updated by message_update). */
67
67
  snapshotText: string;
68
- /** 已定稿 assistant 消息累计文本 */
68
+ /** Accumulated finalized assistant text. */
69
69
  finalizedText: string;
70
- /** 已追加到流的结果文本长度(增量计算基准,跨气泡累计) */
70
+ /** Length of result text already sent (delta baseline across bubbles). */
71
71
  resultSentLen: number;
72
- /** 上一条文本消息已定稿:下一条文本消息首个增量到达时封口当前文本气泡 */
72
+ /** Previous text message finalized: close the current text bubble on the next text delta. */
73
73
  startNewBubble: boolean;
74
- /** 当前气泡(null = 待惰性创建) */
74
+ /** Current bubble (null = create lazily). */
75
75
  cur: Bubble | null;
76
- /** 最近一次成功追加的时间戳(空窗口活性线用) */
76
+ /** Timestamp of the last successful append (for liveness). */
77
77
  lastAppendAt: number;
78
78
  typingTimer?: ReturnType<typeof setInterval>;
79
79
  flushTimer?: ReturnType<typeof setInterval>;
@@ -81,32 +81,25 @@ interface RunState {
81
81
  messageHeartbeats: number;
82
82
  }
83
83
 
84
- /** 本地时间 HH:MM:SS,用于汇总帧首行的时间戳 */
85
- function nowStamp(): string {
86
- const d = new Date();
87
- const p = (n: number) => String(n).padStart(2, "0");
88
- return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
89
- }
90
-
91
- /** 工具计数:`[n] 🔧 name`(行组帧外层再加一次 [HH:MM:SS] 时间戳) */
84
+ /** Tool count line: `[🔧] [n] name`. */
92
85
  function formatToolCount(name: string, count: number): string {
93
- return `[${count}] 🔧 ${name}`;
86
+ return `[🔧] [${count}] ${name}`;
94
87
  }
95
88
 
96
- /** 心跳文案:仅工具名×总次数与时长,无参数无响应(features.md 决策 #3) */
89
+ /** Heartbeat text: tool totals and elapsed time only (features-v1.md decision #3). */
97
90
  export function formatHeartbeat(elapsedMs: number, tools: Map<string, ToolStat2>): string {
98
91
  const minutes = Math.floor(elapsedMs / 60_000);
99
- const elapsedText = minutes < 1 ? "不到 1 分钟" : `${minutes} 分钟`;
100
- if (tools.size === 0) return `⏱ 已运行 ${elapsedText}(尚未产生工具调用)`;
92
+ const elapsedText = minutes < 1 ? "less than 1 minute" : `${minutes} minute${minutes === 1 ? "" : "s"}`;
93
+ if (tools.size === 0) return `⏱ Running for ${elapsedText} (no tool calls yet)`;
101
94
  const parts = [...tools.entries()].map(([name, s]) => formatToolCount(name, s.count));
102
95
  const errors = [...tools.values()].reduce((n, s) => n + s.errors, 0);
103
- const suffix = errors > 0 ? ` · ${errors} 失败` : "";
104
- return `⏱ 已运行 ${elapsedText} · ${parts.join(" · ")}${suffix}`;
96
+ const suffix = errors > 0 ? ` · ${errors} failed` : "";
97
+ return `⏱ Running for ${elapsedText} · ${parts.join(" · ")}${suffix}`;
105
98
  }
106
99
 
107
- const STREAM_LIVENESS_MS = 60_000; // 空窗口静默超过该时长时补活性心跳行
108
- const TYPING_INTERVAL_MS = 50_000; // 平台 typing 窗口 ~60s,提前续期
109
- const PENDING_TTL_MS = 15_000; // QQ 触发标记的有效期(超过视为本地 run)
100
+ const STREAM_LIVENESS_MS = 60_000; // Add a liveness row after this much silence
101
+ const TYPING_INTERVAL_MS = 50_000; // Platform typing window ~60s; renew early
102
+ const PENDING_TTL_MS = 15_000; // QQ trigger TTL (older means a local run)
110
103
 
111
104
  export class RunFeedback {
112
105
  private readonly deps: RunFeedbackDeps;
@@ -118,25 +111,15 @@ export class RunFeedback {
118
111
  this.deps = deps;
119
112
  }
120
113
 
121
- private debug(message: string): void {
122
- if (!this.deps.getDebug()) return;
123
- console.error(`[pi-qq debug ${nowStamp()}] ${message}`);
124
- }
125
-
126
- /** inbound 在注入 pi 前调用:标记接下来的 run 由 QQ 触发 */
114
+ /** Called by inbound before injecting: mark the next run as QQ-triggered. */
127
115
  markQQTrigger(openid: string, msgId: string): void {
128
116
  this.pending = { openid, msgId, at: Date.now() };
129
117
  }
130
118
 
131
- /** 当前 run 是否由 QQ 触发(用量摘要只对 QQ 会话发送) */
132
- isQQTriggeredRun(): boolean {
133
- return this.run !== null;
134
- }
135
-
136
119
  onAgentStart(): void {
137
120
  const pending = this.pending;
138
121
  this.pending = null;
139
- if (!pending || Date.now() - pending.at > PENDING_TTL_MS) return; // 非 QQ 触发
122
+ if (!pending || Date.now() - pending.at > PENDING_TTL_MS) return; // Not QQ-triggered
140
123
  const bot = this.deps.bot();
141
124
  if (!bot) return;
142
125
 
@@ -157,16 +140,16 @@ export class RunFeedback {
157
140
  messageHeartbeats: 0,
158
141
  };
159
142
  this.run = run;
160
- this.debug(`run start msgId=${run.msgId?.slice(0, 8) ?? "?"}`);
143
+ log.debug("run", "started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
161
144
 
162
- // typing 保鲜:run 开始立即亮起"正在输入",之后每 50s 续期(0 额度)
145
+ // Typing keepalive: start immediately, renew every 50s (zero quota).
163
146
  const keepTyping = () => {
164
147
  void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
165
148
  };
166
149
  keepTyping();
167
150
  run.typingTimer = setInterval(keepTyping, TYPING_INTERVAL_MS);
168
151
 
169
- // 固定频率汇总帧(间隔可配,毫秒)
152
+ // Fixed-interval summary frames (configurable in ms).
170
153
  run.flushTimer = setInterval(
171
154
  () => {
172
155
  void this.flushWindow(run);
@@ -174,7 +157,7 @@ export class RunFeedback {
174
157
  Math.max(this.deps.getStreamFlushMs(), 300),
175
158
  );
176
159
 
177
- // 心跳兜底(流式路径的活性由空窗口活性行覆盖)
160
+ // Heartbeat fallback (liveness is covered by empty-window rows).
178
161
  if (hbMinutes > 0) {
179
162
  run.heartbeatTimer = setInterval(() => {
180
163
  void this.beat();
@@ -182,7 +165,7 @@ export class RunFeedback {
182
165
  }
183
166
  }
184
167
 
185
- /** 工具开始:按事件顺序记录;连续同名工具合并计数 */
168
+ /** Tool start: record in event order; merge consecutive same-tool calls. */
186
169
  onToolStart(toolName: string): void {
187
170
  const run = this.run;
188
171
  if (!run) return;
@@ -194,7 +177,7 @@ export class RunFeedback {
194
177
  }
195
178
  }
196
179
 
197
- /** 工具结束:总计计数(心跳 ⏱ 行用) */
180
+ /** Tool end: update totals for the heartbeat line. */
198
181
  onToolEnd(toolName: string, isError: boolean): void {
199
182
  const run = this.run;
200
183
  if (!run) return;
@@ -204,7 +187,7 @@ export class RunFeedback {
204
187
  run.tools.set(toolName, stat);
205
188
  }
206
189
 
207
- /** assistant 流式快照(message_update):只更新窗口,汇总帧统一发送 */
190
+ /** Assistant snapshot: update the window; frames are sent by flush. */
208
191
  async onAssistantDelta(snapshotText: string, snapshotThinking: string): Promise<void> {
209
192
  const run = this.run;
210
193
  if (!run) return;
@@ -216,38 +199,39 @@ export class RunFeedback {
216
199
  }
217
200
 
218
201
  /**
219
- * assistant 消息定稿(message_end)。
220
- * 返回 true 表示流接管(调用方跳过 sendReply);默认/流失败返回 false 走消息路径。
202
+ * Finalize an assistant message (message_end).
203
+ * Returns true when the stream took over (caller skips sendReply); false falls
204
+ * back to the message path.
221
205
  */
222
206
  async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
223
207
  const run = this.run;
224
208
  if (!run) return false;
225
209
 
226
210
  if (isError) {
227
- // 出错也先封口当前气泡(结束 QQ 的生成态),错误摘要交回调用方走消息链路
211
+ // Seal the current bubble even on error; the caller sends the error message.
228
212
  await this.closeBubble(run);
229
213
  return false;
230
214
  }
231
215
 
232
216
  run.finalizedText = [run.finalizedText, text].filter((s) => s.trim()).join("\n\n");
233
217
  run.snapshotText = "";
234
- run.thinkingMarked = false; // 下一条 assistant 消息重新计时思考标记
218
+ run.thinkingMarked = false; // Reset the thinking marker for the next message
235
219
  if (!this.deps.getStreamRelay()) return false;
236
220
 
237
- // 先把本条消息剩余的快照补发完,再把边界标记留给下一条文本消息
238
- // (若在 flush 前置位,本条消息的残余增量会被误判为新消息而切泡)
221
+ // Flush remaining text first, then set the boundary for the next text message.
222
+ // Setting it earlier would misclassify leftover deltas as a new message.
239
223
  const handled = await this.flushWindow(run);
240
224
  run.startNewBubble = true;
241
225
  return handled;
242
226
  }
243
227
 
244
- /** 封口当前气泡:补发剩余窗口 + DONE。flush 可能因切泡换掉 cur,需重新读取。 */
228
+ /** Seal the current bubble: flush the window + DONE; re-read cur after flush. */
245
229
  private async sealBubble(run: RunState): Promise<void> {
246
230
  await this.flushWindow(run);
247
231
  await this.closeBubble(run);
248
232
  }
249
233
 
250
- /** 关闭当前气泡并发送 DONE;DONE 失败也视为已关闭(追加模式无撤销语义)。 */
234
+ /** Close the current bubble and send DONE; DONE failure still counts as closed. */
251
235
  private async closeBubble(run: RunState): Promise<void> {
252
236
  const cur = run.cur;
253
237
  if (!cur) return;
@@ -257,25 +241,28 @@ export class RunFeedback {
257
241
  } catch {}
258
242
  }
259
243
 
260
- /** run 结束:封口最后一个气泡(补帧 + DONE),清定时器 */
244
+ /** Run end: seal the last bubble (flush + DONE) and clear timers. */
261
245
  async onAgentEnd(): Promise<void> {
262
246
  const run = this.run;
263
247
  this.clearTimers();
264
248
  this.run = null;
265
249
  if (run) {
266
- this.debug(`run end elapsed=${Math.round((Date.now() - run.startedAt) / 1000)}s`);
267
- // DONE 失败不补发——内容已随汇总帧展示(避免双发)
250
+ log.debug("run", "ended", {
251
+ msgId: run.msgId?.slice(0, 8) ?? "?",
252
+ elapsedMs: Date.now() - run.startedAt,
253
+ });
254
+ // Do not resend on DONE failure; content was already shown.
268
255
  try {
269
256
  await this.sealBubble(run);
270
257
  } catch {}
271
258
  }
272
259
  }
273
260
 
274
- /** session_shutdown 等异常路径的清理 */
261
+ /** Cleanup for session_shutdown and other error paths. */
275
262
  dispose(): void {
276
263
  this.clearTimers();
277
264
  this.run?.cur?.stream.dispose();
278
- this.run = null; // 未发 DONE 的气泡会停留在生成态(追加模式无撤销语义,可接受)
265
+ this.run = null; // A bubble without DONE may stay generating (append mode cannot undo).
279
266
  }
280
267
 
281
268
  private clearTimers(): void {
@@ -290,9 +277,10 @@ export class RunFeedback {
290
277
  }
291
278
 
292
279
  /**
293
- * 把窗口增量写入对应气泡:思考/工具行组进活动气泡,文本进文本气泡。
294
- * 文本消息首个增量或行组到达时切换气泡;同一消息的后续增量不切泡。
295
- * 通过 promise 链串行化:限流重试期间(最长 7s)定时器再次触发也不会产生交错帧。
280
+ * Write window increments to bubbles: activity rows to activity bubbles, text
281
+ * to text bubbles. A new text message or line group switches bubbles; later
282
+ * deltas of the same message do not. A promise chain serializes flushes so
283
+ * retries cannot interleave frames.
296
284
  */
297
285
  flushWindow(run?: RunState): Promise<boolean> {
298
286
  const p = this.flushQueue.then(() => this.doFlushWindow(run));
@@ -309,51 +297,48 @@ export class RunFeedback {
309
297
  const textDelta = full.slice(r.resultSentLen);
310
298
  const textVisible = textDelta.trim().length > 0;
311
299
 
312
- // 行组(思考/工具计数)——无文本的窗口也照常汇总
300
+ // Line groups (thinking/tool counts) are summarized even without text.
313
301
  const okLines = await this.appendLineGroups(r);
314
302
  if (!okLines) return false;
315
303
 
316
- // 文本消息独立成泡(空白增量只推进基准,不追加)
304
+ // Text gets its own bubble (whitespace-only deltas only advance the baseline).
317
305
  if (textVisible) {
318
306
  const okText = await this.appendText(r, textDelta);
319
307
  if (!okText) return false;
320
- // 关键:推进已发送基准,否则下一帧会把同一段全文再追加一次
308
+ // Advance the sent baseline or the next frame will append the same text again.
321
309
  r.resultSentLen = full.length;
322
310
  r.startNewBubble = false;
323
311
  } else if (textDelta) {
324
312
  r.resultSentLen = full.length;
325
313
  }
326
314
 
327
- // 重置窗口
315
+ // Reset the window
328
316
  r.winLines = [];
329
317
  return true;
330
318
  }
331
319
 
332
- /** 收集本窗口行组:严格按事件发生顺序(连续同名工具已合并计数) */
320
+ /** Collect window rows in event order (consecutive same tools merged). */
333
321
  private collectWindowLines(r: RunState): string[] {
334
322
  return r.winLines.map((line) =>
335
- line.kind === "thinking" ? "💭 思考中..." : formatToolCount(line.name, line.count),
323
+ line.kind === "thinking" ? "[💭] Thinking..." : formatToolCount(line.name, line.count),
336
324
  );
337
325
  }
338
326
 
339
- /** 追加行组:只进活动气泡;首行带时间戳;行与行相邻不空行,跨帧直接续行 */
327
+ /** Append activity rows; rows continue across frames. */
340
328
  private async appendLineGroups(r: RunState, lines?: string[]): Promise<boolean> {
341
329
  const group = lines ?? this.collectWindowLines(r);
342
330
  if (group.length === 0) return true;
343
- const stamp = `[${nowStamp()}] `;
344
- const frame = stamp + group.join(`\n${stamp}`) + "\n";
345
- return this.pushAppend(r, frame, "activity");
331
+ return this.pushAppend(r, `${group.join("\n")}\n`, "activity");
346
332
  }
347
333
 
348
- /** 追加文本:文本消息独占气泡,同一消息续写直接拼接;诊断模式带内联时间戳 */
334
+ /** Append text: text messages own bubbles. */
349
335
  private async appendText(r: RunState, text: string): Promise<boolean> {
350
- // 上一条文本消息已定稿 → 封口旧文本气泡,本条消息另起一泡
336
+ // Previous text message finalized: seal it and start a new bubble.
351
337
  if (r.startNewBubble) await this.closeBubble(r);
352
- const stamp = this.deps.getDebug() ? `[${nowStamp()}] ` : "";
353
- return this.pushAppend(r, stamp + text, "text");
338
+ return this.pushAppend(r, text, "text");
354
339
  }
355
340
 
356
- /** 心跳兜底:流式路径的活性由空窗口活性行覆盖;流不可用时发消息心跳(保险丝 ≤N 条) */
341
+ /** Heartbeat fallback when streaming is unavailable (max N messages per run). */
357
342
  private async beat(): Promise<void> {
358
343
  const run = this.run;
359
344
  if (!run) return;
@@ -365,14 +350,10 @@ export class RunFeedback {
365
350
  const bot = this.deps.bot();
366
351
  if (!bot) return;
367
352
  run.messageHeartbeats += 1;
368
- await sendReply(
369
- bot,
370
- `[${nowStamp()}] ${formatHeartbeat(Date.now() - run.startedAt, run.tools)}`,
371
- this.deps.makeChannel(),
372
- );
353
+ await sendReply(bot, formatHeartbeat(Date.now() - run.startedAt, run.tools), this.deps.makeChannel());
373
354
  }
374
355
 
375
- /** 追加一帧(惰性建气泡;内容类型变化时先封口旧气泡);失败弃气泡并返回 false */
356
+ /** Append a frame (lazy bubble; close on kind change); discard on failure. */
376
357
  private async pushAppend(run: RunState, delta: string, kind: "activity" | "text"): Promise<boolean> {
377
358
  if (!delta) return true;
378
359
  const bot = this.deps.bot();
@@ -386,7 +367,7 @@ export class RunFeedback {
386
367
  run.cur = {
387
368
  stream: new AppendStream(bot.messageApi, bot.getCredentials(), run.openid, run.msgId, {
388
369
  onError: (err) => this.handleStreamError(run, err),
389
- onDebug: (message) => this.debug(`stream msgId=${run.msgId?.slice(0, 8) ?? "?"} ${message}`),
370
+ onDebug: (message) => log.debug("stream", message, { msgId: run.msgId?.slice(0, 8) ?? "?" }),
390
371
  }),
391
372
  kind,
392
373
  };
@@ -401,14 +382,16 @@ export class RunFeedback {
401
382
  }
402
383
  }
403
384
 
404
- /** 流不可信:丢弃当前气泡,并把尚未追加到流的结果文本用消息路径补发(避免结果丢失) */
385
+ /** Stream is untrusted: discard the bubble and resend unsent text via messages. */
405
386
  private handleStreamError(run: RunState, err: Error): void {
406
387
  const had = run.cur !== null;
407
388
  run.cur = null;
408
- this.debug(
409
- `stream error msgId=${run.msgId?.slice(0, 8) ?? "?"} elapsed=${Math.round((Date.now() - run.startedAt) / 1000)}s: ${err.message}`,
410
- );
411
- if (had) this.deps.onWarn(`流式通道不可用,本回合已降级(${err.message})`);
389
+ log.warn("stream", "stream error", {
390
+ msgId: run.msgId?.slice(0, 8) ?? "?",
391
+ elapsedMs: Date.now() - run.startedAt,
392
+ err,
393
+ });
394
+ if (had) this.deps.onWarn(`Stream unavailable; falling back to text (${err.message}).`);
412
395
  const rest = run.finalizedText.slice(run.resultSentLen);
413
396
  if (rest) {
414
397
  const bound = this.deps.boundOpenid();
package/src/voice.ts ADDED
@@ -0,0 +1,25 @@
1
+ /** QQ voice attachments: identify voice messages and extract platform ASR text. */
2
+ import type { InboundAttachmentLike } from "./download";
3
+
4
+ export interface VoiceAttachmentLike extends InboundAttachmentLike {
5
+ asr_refer_text?: string;
6
+ }
7
+
8
+ /** A QQ voice message has content_type "voice"; other media/file types are excluded. */
9
+ export function isVoiceAttachment(attachment: { content_type?: string }): boolean {
10
+ return (attachment.content_type ?? "").toLowerCase() === "voice";
11
+ }
12
+
13
+ /**
14
+ * Collect non-empty ASR text from voice attachments in order.
15
+ * Returns undefined when no attachment has a usable transcript.
16
+ */
17
+ export function resolveVoiceTranscript(attachments: readonly VoiceAttachmentLike[]): string | undefined {
18
+ const transcripts: string[] = [];
19
+ for (const attachment of attachments) {
20
+ if (!isVoiceAttachment(attachment)) continue;
21
+ const text = attachment.asr_refer_text?.trim();
22
+ if (text) transcripts.push(text);
23
+ }
24
+ return transcripts.length > 0 ? transcripts.join("\n") : undefined;
25
+ }
package/src/usage.ts DELETED
@@ -1,93 +0,0 @@
1
- import type { ContextUsage } from "@earendil-works/pi-coding-agent";
2
-
3
- /**
4
- * F5/F6 用量摘要:本次 agent run 的累计输入/输出/缓存命中率 + 当前上下文占比。
5
- *
6
- * pi 的 ExtensionContext 没有现成的 token 总和;只能从消息的 `usage`
7
- * 字段聚合。这里按 agent_end 的 `event.messages` 统计本次 run:
8
- * assistant 消息 + toolResult 自带的嵌套 usage(如 codemode/subagent)。
9
- */
10
-
11
- /** 只依赖 message.usage 的结构化子集,便于单测与跨版本兼容 */
12
- export interface UsageLike {
13
- input: number;
14
- output: number;
15
- cacheRead: number;
16
- cacheWrite: number;
17
- }
18
-
19
- export interface UsageTotals {
20
- input: number;
21
- output: number;
22
- cacheRead: number;
23
- cacheWrite: number;
24
- }
25
-
26
- /** 供 sumUsageMessages 使用的最小消息结构(不直接依赖 AgentMessage 导出) */
27
- export interface UsageMessageLike {
28
- role: string;
29
- usage?: UsageLike | null;
30
- }
31
-
32
- export interface UsageSummaryInput {
33
- /** 本次 agent run 的累计用量 */
34
- usage: UsageTotals;
35
- context?: ContextUsage;
36
- }
37
-
38
- export function emptyUsageTotals(): UsageTotals {
39
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
40
- }
41
-
42
- /** 累加一次 usage,返回新对象(不修改入参) */
43
- export function addUsage(totals: UsageTotals, usage: UsageLike | null | undefined): UsageTotals {
44
- if (!usage) return totals;
45
- return {
46
- input: totals.input + usage.input,
47
- output: totals.output + usage.output,
48
- cacheRead: totals.cacheRead + usage.cacheRead,
49
- cacheWrite: totals.cacheWrite + usage.cacheWrite,
50
- };
51
- }
52
-
53
- /** 汇总本次 run 的消息用量:assistant + toolResult 的嵌套 usage */
54
- export function sumUsageMessages(messages: readonly UsageMessageLike[]): UsageTotals {
55
- let totals = emptyUsageTotals();
56
- for (const message of messages) {
57
- if (message.role === "assistant" || message.role === "toolResult") {
58
- totals = addUsage(totals, message.usage);
59
- }
60
- }
61
- return totals;
62
- }
63
-
64
- export function formatTokenCount(n: number): string {
65
- return n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n);
66
- }
67
-
68
- function formatPercent(percent: number): string {
69
- return `${percent.toFixed(1)}%`;
70
- }
71
-
72
- function formatContextPercent(context: ContextUsage | undefined): string {
73
- if (!context) return "未知";
74
- if (context.tokens === null) return "重建中";
75
-
76
- const percent =
77
- context.percent ?? (context.contextWindow > 0 ? (context.tokens / context.contextWindow) * 100 : null);
78
- return percent === null ? "未知" : formatPercent(percent);
79
- }
80
-
81
- /** 生成严格三行的用量摘要 */
82
- export function formatUsageSummary(input: UsageSummaryInput): string {
83
- const { usage, context } = input;
84
- const totalInput = usage.input + usage.cacheRead + usage.cacheWrite;
85
- const cacheHitRate = totalInput > 0 ? (usage.cacheRead / totalInput) * 100 : 0;
86
-
87
- return [
88
- "📊 用量摘要",
89
- `• 输入:${formatTokenCount(totalInput)} (${formatPercent(cacheHitRate)})`,
90
- `• 输出:${formatTokenCount(usage.output)}`,
91
- `• 上下文:${formatContextPercent(context)}`,
92
- ].join("\n");
93
- }