@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.
- package/README.md +21 -13
- package/doc/{features.md → features-v1.md} +28 -50
- package/doc/features-v2.md +97 -0
- package/doc/{plan.md → plan-v1.md} +23 -28
- package/doc/plan-v2.md +245 -0
- package/index.ts +68 -59
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +58 -20
- package/src/budget-status.ts +1 -1
- package/src/config.ts +9 -8
- package/src/download.ts +11 -11
- package/src/files.ts +10 -10
- package/src/format.ts +6 -1
- package/src/images.ts +25 -13
- package/src/inbound.ts +103 -26
- package/src/logger.ts +180 -0
- package/src/outbound.ts +42 -25
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +85 -102
- package/src/voice.ts +25 -0
- package/src/usage.ts +0 -93
package/src/run-feedback.ts
CHANGED
|
@@ -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
|
|
8
|
+
* F7 long-task feedback: run-level state machine (summary frames + text bubbles).
|
|
8
9
|
*
|
|
9
|
-
*
|
|
10
|
+
* Scenario: user_input → thinking/tools (10–60 minutes) → assistant message, n turns.
|
|
10
11
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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
|
-
*
|
|
18
|
-
*
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
66
|
+
/** Current streaming text snapshot (updated by message_update). */
|
|
67
67
|
snapshotText: string;
|
|
68
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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}]
|
|
86
|
+
return `[🔧] [${count}] ${name}`;
|
|
94
87
|
}
|
|
95
88
|
|
|
96
|
-
/**
|
|
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 ? "
|
|
100
|
-
if (tools.size === 0) return `⏱
|
|
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 `⏱
|
|
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; //
|
|
109
|
-
const PENDING_TTL_MS = 15_000; // QQ
|
|
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
|
-
|
|
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; //
|
|
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
|
-
|
|
143
|
+
log.debug("run", "started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
|
|
161
144
|
|
|
162
|
-
//
|
|
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
|
-
/**
|
|
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
|
|
220
|
-
*
|
|
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
|
-
//
|
|
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; //
|
|
218
|
+
run.thinkingMarked = false; // Reset the thinking marker for the next message
|
|
235
219
|
if (!this.deps.getStreamRelay()) return false;
|
|
236
220
|
|
|
237
|
-
//
|
|
238
|
-
//
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
|
|
267
|
-
|
|
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; //
|
|
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
|
-
*
|
|
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" ? "💭
|
|
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
|
-
|
|
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
|
-
|
|
353
|
-
return this.pushAppend(r, stamp + text, "text");
|
|
338
|
+
return this.pushAppend(r, text, "text");
|
|
354
339
|
}
|
|
355
340
|
|
|
356
|
-
/**
|
|
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
|
-
/**
|
|
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) =>
|
|
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
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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
|
-
}
|