@chen_hu_hu/pi-qq 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -6
- package/doc/{features.md → features-v1.md} +28 -50
- package/doc/{plan.md → plan-v1.md} +22 -27
- package/index.ts +14 -54
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +16 -16
- package/src/budget-status.ts +1 -1
- package/src/config.ts +2 -5
- package/src/download.ts +3 -3
- package/src/files.ts +6 -6
- package/src/format.ts +6 -1
- package/src/images.ts +6 -6
- package/src/inbound.ts +7 -7
- package/src/outbound.ts +22 -22
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +70 -75
- package/src/usage.ts +0 -93
package/src/run-feedback.ts
CHANGED
|
@@ -4,20 +4,21 @@ import { sendReply, type ReplyChannel } from "./outbound";
|
|
|
4
4
|
import type { ReplyBudget } from "./reply-budget";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* F7
|
|
7
|
+
* F7 long-task feedback: run-level state machine (summary frames + text bubbles).
|
|
8
8
|
*
|
|
9
|
-
*
|
|
9
|
+
* Scenario: user_input → thinking/tools (10–60 minutes) → assistant message, n turns.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
11
|
+
* Bubble rules: **assistant text and thinking/tool summaries use separate bubbles.**
|
|
12
|
+
* Each text message (streaming increments of one assistant message) owns a text
|
|
13
|
+
* bubble; thinking/tool line groups go to an activity bubble. The first text delta
|
|
14
|
+
* closes the current activity bubble; a line group closes the current text bubble.
|
|
15
|
+
* The final reply is its own text bubble. Frames are sent every `streamFlushMs`
|
|
16
|
+
* (default 10000ms):
|
|
16
17
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
18
|
+
* Activity: [💭] Thinking... / [🔧] [2] bash (event order; timestamps only in debug)
|
|
19
|
+
* Text: message text (streamed increments, rendered as Markdown)
|
|
19
20
|
*
|
|
20
|
-
*
|
|
21
|
+
* Any failed frame discards the bubble; unsent text falls back to the message path.
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
24
|
export interface ToolStat {
|
|
@@ -31,10 +32,10 @@ export interface RunFeedbackDeps {
|
|
|
31
32
|
boundOpenid: () => string | undefined;
|
|
32
33
|
getHeartbeatMinutes: () => number;
|
|
33
34
|
getHeartbeatMaxMessages: () => number;
|
|
34
|
-
/**
|
|
35
|
+
/** Stream summary frame interval in ms (minimum 300). */
|
|
35
36
|
getStreamFlushMs: () => number;
|
|
36
37
|
getStreamRelay: () => boolean;
|
|
37
|
-
/**
|
|
38
|
+
/** Debug mode: SDK logs plus timestamps on stream frames. */
|
|
38
39
|
getDebug: () => boolean;
|
|
39
40
|
makeChannel: () => ReplyChannel;
|
|
40
41
|
onWarn: (msg: string) => void;
|
|
@@ -45,7 +46,7 @@ interface ToolStat2 {
|
|
|
45
46
|
errors: number;
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
/**
|
|
49
|
+
/** Current bubble: one stream message; kind selects text or activity rows. */
|
|
49
50
|
interface Bubble {
|
|
50
51
|
stream: AppendStream;
|
|
51
52
|
kind: "activity" | "text";
|
|
@@ -57,23 +58,23 @@ interface RunState {
|
|
|
57
58
|
startedAt: number;
|
|
58
59
|
openid: string;
|
|
59
60
|
msgId?: string;
|
|
60
|
-
/**
|
|
61
|
+
/** Total tool counts (for the heartbeat line). */
|
|
61
62
|
tools: Map<string, ToolStat2>;
|
|
62
|
-
/**
|
|
63
|
+
/** Line groups in this window, in event order (cleared after flush). */
|
|
63
64
|
winLines: WindowLine[];
|
|
64
|
-
/**
|
|
65
|
+
/** Thinking marker for the current message (reset per message). */
|
|
65
66
|
thinkingMarked: boolean;
|
|
66
|
-
/**
|
|
67
|
+
/** Current streaming text snapshot (updated by message_update). */
|
|
67
68
|
snapshotText: string;
|
|
68
|
-
/**
|
|
69
|
+
/** Accumulated finalized assistant text. */
|
|
69
70
|
finalizedText: string;
|
|
70
|
-
/**
|
|
71
|
+
/** Length of result text already sent (delta baseline across bubbles). */
|
|
71
72
|
resultSentLen: number;
|
|
72
|
-
/**
|
|
73
|
+
/** Previous text message finalized: close the current text bubble on the next text delta. */
|
|
73
74
|
startNewBubble: boolean;
|
|
74
|
-
/**
|
|
75
|
+
/** Current bubble (null = create lazily). */
|
|
75
76
|
cur: Bubble | null;
|
|
76
|
-
/**
|
|
77
|
+
/** Timestamp of the last successful append (for liveness). */
|
|
77
78
|
lastAppendAt: number;
|
|
78
79
|
typingTimer?: ReturnType<typeof setInterval>;
|
|
79
80
|
flushTimer?: ReturnType<typeof setInterval>;
|
|
@@ -81,19 +82,19 @@ interface RunState {
|
|
|
81
82
|
messageHeartbeats: number;
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
/**
|
|
85
|
+
/** Local HH:MM:SS timestamp for debug frames. */
|
|
85
86
|
function nowStamp(): string {
|
|
86
87
|
const d = new Date();
|
|
87
88
|
const p = (n: number) => String(n).padStart(2, "0");
|
|
88
89
|
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
/**
|
|
92
|
+
/** Tool count line: `[🔧] [n] name`; debug mode prefixes [HH:MM:SS]. */
|
|
92
93
|
function formatToolCount(name: string, count: number): string {
|
|
93
|
-
return `[${count}]
|
|
94
|
+
return `[🔧] [${count}] ${name}`;
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
/**
|
|
97
|
+
/** Heartbeat text: tool totals and elapsed time only (features-v1.md decision #3). */
|
|
97
98
|
export function formatHeartbeat(elapsedMs: number, tools: Map<string, ToolStat2>): string {
|
|
98
99
|
const minutes = Math.floor(elapsedMs / 60_000);
|
|
99
100
|
const elapsedText = minutes < 1 ? "不到 1 分钟" : `${minutes} 分钟`;
|
|
@@ -104,9 +105,9 @@ export function formatHeartbeat(elapsedMs: number, tools: Map<string, ToolStat2>
|
|
|
104
105
|
return `⏱ 已运行 ${elapsedText} · ${parts.join(" · ")}${suffix}`;
|
|
105
106
|
}
|
|
106
107
|
|
|
107
|
-
const STREAM_LIVENESS_MS = 60_000; //
|
|
108
|
-
const TYPING_INTERVAL_MS = 50_000; //
|
|
109
|
-
const PENDING_TTL_MS = 15_000; // QQ
|
|
108
|
+
const STREAM_LIVENESS_MS = 60_000; // Add a liveness row after this much silence
|
|
109
|
+
const TYPING_INTERVAL_MS = 50_000; // Platform typing window ~60s; renew early
|
|
110
|
+
const PENDING_TTL_MS = 15_000; // QQ trigger TTL (older means a local run)
|
|
110
111
|
|
|
111
112
|
export class RunFeedback {
|
|
112
113
|
private readonly deps: RunFeedbackDeps;
|
|
@@ -123,20 +124,15 @@ export class RunFeedback {
|
|
|
123
124
|
console.error(`[pi-qq debug ${nowStamp()}] ${message}`);
|
|
124
125
|
}
|
|
125
126
|
|
|
126
|
-
/** inbound
|
|
127
|
+
/** Called by inbound before injecting: mark the next run as QQ-triggered. */
|
|
127
128
|
markQQTrigger(openid: string, msgId: string): void {
|
|
128
129
|
this.pending = { openid, msgId, at: Date.now() };
|
|
129
130
|
}
|
|
130
131
|
|
|
131
|
-
/** 当前 run 是否由 QQ 触发(用量摘要只对 QQ 会话发送) */
|
|
132
|
-
isQQTriggeredRun(): boolean {
|
|
133
|
-
return this.run !== null;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
132
|
onAgentStart(): void {
|
|
137
133
|
const pending = this.pending;
|
|
138
134
|
this.pending = null;
|
|
139
|
-
if (!pending || Date.now() - pending.at > PENDING_TTL_MS) return; //
|
|
135
|
+
if (!pending || Date.now() - pending.at > PENDING_TTL_MS) return; // Not QQ-triggered
|
|
140
136
|
const bot = this.deps.bot();
|
|
141
137
|
if (!bot) return;
|
|
142
138
|
|
|
@@ -159,14 +155,14 @@ export class RunFeedback {
|
|
|
159
155
|
this.run = run;
|
|
160
156
|
this.debug(`run start msgId=${run.msgId?.slice(0, 8) ?? "?"}`);
|
|
161
157
|
|
|
162
|
-
//
|
|
158
|
+
// Typing keepalive: start immediately, renew every 50s (zero quota).
|
|
163
159
|
const keepTyping = () => {
|
|
164
160
|
void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
|
|
165
161
|
};
|
|
166
162
|
keepTyping();
|
|
167
163
|
run.typingTimer = setInterval(keepTyping, TYPING_INTERVAL_MS);
|
|
168
164
|
|
|
169
|
-
//
|
|
165
|
+
// Fixed-interval summary frames (configurable in ms).
|
|
170
166
|
run.flushTimer = setInterval(
|
|
171
167
|
() => {
|
|
172
168
|
void this.flushWindow(run);
|
|
@@ -174,7 +170,7 @@ export class RunFeedback {
|
|
|
174
170
|
Math.max(this.deps.getStreamFlushMs(), 300),
|
|
175
171
|
);
|
|
176
172
|
|
|
177
|
-
//
|
|
173
|
+
// Heartbeat fallback (liveness is covered by empty-window rows).
|
|
178
174
|
if (hbMinutes > 0) {
|
|
179
175
|
run.heartbeatTimer = setInterval(() => {
|
|
180
176
|
void this.beat();
|
|
@@ -182,7 +178,7 @@ export class RunFeedback {
|
|
|
182
178
|
}
|
|
183
179
|
}
|
|
184
180
|
|
|
185
|
-
/**
|
|
181
|
+
/** Tool start: record in event order; merge consecutive same-tool calls. */
|
|
186
182
|
onToolStart(toolName: string): void {
|
|
187
183
|
const run = this.run;
|
|
188
184
|
if (!run) return;
|
|
@@ -194,7 +190,7 @@ export class RunFeedback {
|
|
|
194
190
|
}
|
|
195
191
|
}
|
|
196
192
|
|
|
197
|
-
/**
|
|
193
|
+
/** Tool end: update totals for the heartbeat line. */
|
|
198
194
|
onToolEnd(toolName: string, isError: boolean): void {
|
|
199
195
|
const run = this.run;
|
|
200
196
|
if (!run) return;
|
|
@@ -204,7 +200,7 @@ export class RunFeedback {
|
|
|
204
200
|
run.tools.set(toolName, stat);
|
|
205
201
|
}
|
|
206
202
|
|
|
207
|
-
/**
|
|
203
|
+
/** Assistant snapshot: update the window; frames are sent by flush. */
|
|
208
204
|
async onAssistantDelta(snapshotText: string, snapshotThinking: string): Promise<void> {
|
|
209
205
|
const run = this.run;
|
|
210
206
|
if (!run) return;
|
|
@@ -216,38 +212,39 @@ export class RunFeedback {
|
|
|
216
212
|
}
|
|
217
213
|
|
|
218
214
|
/**
|
|
219
|
-
* assistant
|
|
220
|
-
*
|
|
215
|
+
* Finalize an assistant message (message_end).
|
|
216
|
+
* Returns true when the stream took over (caller skips sendReply); false falls
|
|
217
|
+
* back to the message path.
|
|
221
218
|
*/
|
|
222
219
|
async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
|
|
223
220
|
const run = this.run;
|
|
224
221
|
if (!run) return false;
|
|
225
222
|
|
|
226
223
|
if (isError) {
|
|
227
|
-
//
|
|
224
|
+
// Seal the current bubble even on error; the caller sends the error message.
|
|
228
225
|
await this.closeBubble(run);
|
|
229
226
|
return false;
|
|
230
227
|
}
|
|
231
228
|
|
|
232
229
|
run.finalizedText = [run.finalizedText, text].filter((s) => s.trim()).join("\n\n");
|
|
233
230
|
run.snapshotText = "";
|
|
234
|
-
run.thinkingMarked = false; //
|
|
231
|
+
run.thinkingMarked = false; // Reset the thinking marker for the next message
|
|
235
232
|
if (!this.deps.getStreamRelay()) return false;
|
|
236
233
|
|
|
237
|
-
//
|
|
238
|
-
//
|
|
234
|
+
// Flush remaining text first, then set the boundary for the next text message.
|
|
235
|
+
// Setting it earlier would misclassify leftover deltas as a new message.
|
|
239
236
|
const handled = await this.flushWindow(run);
|
|
240
237
|
run.startNewBubble = true;
|
|
241
238
|
return handled;
|
|
242
239
|
}
|
|
243
240
|
|
|
244
|
-
/**
|
|
241
|
+
/** Seal the current bubble: flush the window + DONE; re-read cur after flush. */
|
|
245
242
|
private async sealBubble(run: RunState): Promise<void> {
|
|
246
243
|
await this.flushWindow(run);
|
|
247
244
|
await this.closeBubble(run);
|
|
248
245
|
}
|
|
249
246
|
|
|
250
|
-
/**
|
|
247
|
+
/** Close the current bubble and send DONE; DONE failure still counts as closed. */
|
|
251
248
|
private async closeBubble(run: RunState): Promise<void> {
|
|
252
249
|
const cur = run.cur;
|
|
253
250
|
if (!cur) return;
|
|
@@ -257,25 +254,25 @@ export class RunFeedback {
|
|
|
257
254
|
} catch {}
|
|
258
255
|
}
|
|
259
256
|
|
|
260
|
-
/**
|
|
257
|
+
/** Run end: seal the last bubble (flush + DONE) and clear timers. */
|
|
261
258
|
async onAgentEnd(): Promise<void> {
|
|
262
259
|
const run = this.run;
|
|
263
260
|
this.clearTimers();
|
|
264
261
|
this.run = null;
|
|
265
262
|
if (run) {
|
|
266
263
|
this.debug(`run end elapsed=${Math.round((Date.now() - run.startedAt) / 1000)}s`);
|
|
267
|
-
// DONE
|
|
264
|
+
// Do not resend on DONE failure; content was already shown.
|
|
268
265
|
try {
|
|
269
266
|
await this.sealBubble(run);
|
|
270
267
|
} catch {}
|
|
271
268
|
}
|
|
272
269
|
}
|
|
273
270
|
|
|
274
|
-
/** session_shutdown
|
|
271
|
+
/** Cleanup for session_shutdown and other error paths. */
|
|
275
272
|
dispose(): void {
|
|
276
273
|
this.clearTimers();
|
|
277
274
|
this.run?.cur?.stream.dispose();
|
|
278
|
-
this.run = null; //
|
|
275
|
+
this.run = null; // A bubble without DONE may stay generating (append mode cannot undo).
|
|
279
276
|
}
|
|
280
277
|
|
|
281
278
|
private clearTimers(): void {
|
|
@@ -290,9 +287,10 @@ export class RunFeedback {
|
|
|
290
287
|
}
|
|
291
288
|
|
|
292
289
|
/**
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
*
|
|
290
|
+
* Write window increments to bubbles: activity rows to activity bubbles, text
|
|
291
|
+
* to text bubbles. A new text message or line group switches bubbles; later
|
|
292
|
+
* deltas of the same message do not. A promise chain serializes flushes so
|
|
293
|
+
* retries cannot interleave frames.
|
|
296
294
|
*/
|
|
297
295
|
flushWindow(run?: RunState): Promise<boolean> {
|
|
298
296
|
const p = this.flushQueue.then(() => this.doFlushWindow(run));
|
|
@@ -309,51 +307,51 @@ export class RunFeedback {
|
|
|
309
307
|
const textDelta = full.slice(r.resultSentLen);
|
|
310
308
|
const textVisible = textDelta.trim().length > 0;
|
|
311
309
|
|
|
312
|
-
//
|
|
310
|
+
// Line groups (thinking/tool counts) are summarized even without text.
|
|
313
311
|
const okLines = await this.appendLineGroups(r);
|
|
314
312
|
if (!okLines) return false;
|
|
315
313
|
|
|
316
|
-
//
|
|
314
|
+
// Text gets its own bubble (whitespace-only deltas only advance the baseline).
|
|
317
315
|
if (textVisible) {
|
|
318
316
|
const okText = await this.appendText(r, textDelta);
|
|
319
317
|
if (!okText) return false;
|
|
320
|
-
//
|
|
318
|
+
// Advance the sent baseline or the next frame will append the same text again.
|
|
321
319
|
r.resultSentLen = full.length;
|
|
322
320
|
r.startNewBubble = false;
|
|
323
321
|
} else if (textDelta) {
|
|
324
322
|
r.resultSentLen = full.length;
|
|
325
323
|
}
|
|
326
324
|
|
|
327
|
-
//
|
|
325
|
+
// Reset the window
|
|
328
326
|
r.winLines = [];
|
|
329
327
|
return true;
|
|
330
328
|
}
|
|
331
329
|
|
|
332
|
-
/**
|
|
330
|
+
/** Collect window rows in event order (consecutive same tools merged). */
|
|
333
331
|
private collectWindowLines(r: RunState): string[] {
|
|
334
332
|
return r.winLines.map((line) =>
|
|
335
|
-
line.kind === "thinking" ? "💭
|
|
333
|
+
line.kind === "thinking" ? "[💭] Thinking..." : formatToolCount(line.name, line.count),
|
|
336
334
|
);
|
|
337
335
|
}
|
|
338
336
|
|
|
339
|
-
/**
|
|
337
|
+
/** Append activity rows; debug mode prefixes timestamps; rows continue across frames. */
|
|
340
338
|
private async appendLineGroups(r: RunState, lines?: string[]): Promise<boolean> {
|
|
341
339
|
const group = lines ?? this.collectWindowLines(r);
|
|
342
340
|
if (group.length === 0) return true;
|
|
343
|
-
const stamp = `[${nowStamp()}]
|
|
341
|
+
const stamp = this.deps.getDebug() ? `[${nowStamp()}] ` : "";
|
|
344
342
|
const frame = stamp + group.join(`\n${stamp}`) + "\n";
|
|
345
343
|
return this.pushAppend(r, frame, "activity");
|
|
346
344
|
}
|
|
347
345
|
|
|
348
|
-
/**
|
|
346
|
+
/** Append text: text messages own bubbles; debug mode adds inline timestamps. */
|
|
349
347
|
private async appendText(r: RunState, text: string): Promise<boolean> {
|
|
350
|
-
//
|
|
348
|
+
// Previous text message finalized: seal it and start a new bubble.
|
|
351
349
|
if (r.startNewBubble) await this.closeBubble(r);
|
|
352
350
|
const stamp = this.deps.getDebug() ? `[${nowStamp()}] ` : "";
|
|
353
351
|
return this.pushAppend(r, stamp + text, "text");
|
|
354
352
|
}
|
|
355
353
|
|
|
356
|
-
/**
|
|
354
|
+
/** Heartbeat fallback when streaming is unavailable (max N messages per run). */
|
|
357
355
|
private async beat(): Promise<void> {
|
|
358
356
|
const run = this.run;
|
|
359
357
|
if (!run) return;
|
|
@@ -365,14 +363,11 @@ export class RunFeedback {
|
|
|
365
363
|
const bot = this.deps.bot();
|
|
366
364
|
if (!bot) return;
|
|
367
365
|
run.messageHeartbeats += 1;
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
`[${nowStamp()}] ${formatHeartbeat(Date.now() - run.startedAt, run.tools)}`,
|
|
371
|
-
this.deps.makeChannel(),
|
|
372
|
-
);
|
|
366
|
+
const stamp = this.deps.getDebug() ? `[${nowStamp()}] ` : "";
|
|
367
|
+
await sendReply(bot, `${stamp}${formatHeartbeat(Date.now() - run.startedAt, run.tools)}`, this.deps.makeChannel());
|
|
373
368
|
}
|
|
374
369
|
|
|
375
|
-
/**
|
|
370
|
+
/** Append a frame (lazy bubble; close on kind change); discard on failure. */
|
|
376
371
|
private async pushAppend(run: RunState, delta: string, kind: "activity" | "text"): Promise<boolean> {
|
|
377
372
|
if (!delta) return true;
|
|
378
373
|
const bot = this.deps.bot();
|
|
@@ -401,7 +396,7 @@ export class RunFeedback {
|
|
|
401
396
|
}
|
|
402
397
|
}
|
|
403
398
|
|
|
404
|
-
/**
|
|
399
|
+
/** Stream is untrusted: discard the bubble and resend unsent text via messages. */
|
|
405
400
|
private handleStreamError(run: RunState, err: Error): void {
|
|
406
401
|
const had = run.cur !== null;
|
|
407
402
|
run.cur = null;
|
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
|
-
}
|