@chen_hu_hu/pi-qq 1.2.2 → 1.3.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.
Files changed (33) hide show
  1. package/README-zh.md +48 -24
  2. package/README.md +40 -16
  3. package/doc/delivery-v1-zh.md +160 -0
  4. package/doc/delivery-v1.md +160 -0
  5. package/doc/delivery-v2-zh.md +100 -0
  6. package/doc/delivery-v2.md +98 -0
  7. package/doc/delivery-v3-zh.md +187 -0
  8. package/doc/delivery-v3.md +187 -0
  9. package/index.ts +71 -66
  10. package/package.json +8 -2
  11. package/src/{download.ts → attachments/attachment-download.ts} +2 -5
  12. package/src/{files.ts → attachments/file-attachments.ts} +4 -15
  13. package/src/{images.ts → attachments/image-attachments.ts} +3 -10
  14. package/src/{voice.ts → attachments/voice-transcript.ts} +1 -7
  15. package/src/{format.ts → infra/display-format.ts} +0 -2
  16. package/src/{logger.ts → infra/file-logger.ts} +6 -28
  17. package/src/infra/settings.ts +49 -0
  18. package/src/{bot.ts → qq/qq-bot.ts} +4 -29
  19. package/src/{inbound.ts → qq/qq-message-handler.ts} +10 -23
  20. package/src/{login.ts → qq/qr-login.ts} +20 -16
  21. package/src/{outbound.ts → qq/reply-sender.ts} +3 -34
  22. package/src/qrcode-terminal.d.ts +0 -2
  23. package/src/{budget-status.ts → quota/reply-quota-report.ts} +2 -3
  24. package/src/{reply-budget.ts → quota/reply-quota.ts} +0 -21
  25. package/src/relay/run-stream-relay.ts +586 -0
  26. package/src/relay/stream-block-format.ts +114 -0
  27. package/src/{append-stream.ts → relay/stream-session.ts} +46 -29
  28. package/doc/features-v1.md +0 -239
  29. package/doc/features-v2.md +0 -210
  30. package/doc/plan-v1.md +0 -190
  31. package/doc/plan-v2.md +0 -332
  32. package/src/config.ts +0 -82
  33. package/src/run-feedback.ts +0 -410
@@ -1,410 +0,0 @@
1
- import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
- import { AppendStream } from "./append-stream";
3
- import { sendReply, type ReplyChannel } from "./outbound";
4
- import type { ReplyBudget } from "./reply-budget";
5
- import { log } from "./logger";
6
-
7
- /**
8
- * F7 long-task feedback: run-level state machine (summary frames + text bubbles).
9
- *
10
- * Scenario: user_input → thinking/tools (10–60 minutes) → assistant message, n turns.
11
- *
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):
18
- *
19
- * Activity: [💭] Thinking... / [🔧] [2] bash (event order)
20
- * Text: message text (streamed increments, rendered as Markdown)
21
- *
22
- * Any failed frame discards the bubble; unsent text falls back to the message path.
23
- */
24
-
25
- export interface ToolStat {
26
- count: number;
27
- errors: number;
28
- }
29
-
30
- export interface RunFeedbackDeps {
31
- bot: () => QQBot | undefined;
32
- budget: ReplyBudget;
33
- boundOpenid: () => string | undefined;
34
- getHeartbeatMinutes: () => number;
35
- getHeartbeatMaxMessages: () => number;
36
- /** Stream summary frame interval in ms (minimum 300). */
37
- getStreamFlushMs: () => number;
38
- getStreamRelay: () => boolean;
39
- makeChannel: () => ReplyChannel;
40
- onWarn: (msg: string) => void;
41
- }
42
-
43
- interface ToolStat2 {
44
- count: number;
45
- errors: number;
46
- }
47
-
48
- /** Current bubble: one stream message; kind selects text or activity rows. */
49
- interface Bubble {
50
- stream: AppendStream;
51
- kind: "activity" | "text";
52
- }
53
-
54
- type WindowLine = { kind: "thinking" } | { kind: "tool"; name: string; count: number };
55
-
56
- interface RunState {
57
- startedAt: number;
58
- openid: string;
59
- msgId?: string;
60
- /** Total tool counts (for the heartbeat line). */
61
- tools: Map<string, ToolStat2>;
62
- /** Line groups in this window, in event order (cleared after flush). */
63
- winLines: WindowLine[];
64
- /** Thinking marker for the current message (reset per message). */
65
- thinkingMarked: boolean;
66
- /** Current streaming text snapshot (updated by message_update). */
67
- snapshotText: string;
68
- /** Accumulated finalized assistant text. */
69
- finalizedText: string;
70
- /** Length of result text already sent (delta baseline across bubbles). */
71
- resultSentLen: number;
72
- /** Previous text message finalized: close the current text bubble on the next text delta. */
73
- startNewBubble: boolean;
74
- /** Current bubble (null = create lazily). */
75
- cur: Bubble | null;
76
- /** Timestamp of the last successful append (for liveness). */
77
- lastAppendAt: number;
78
- typingTimer?: ReturnType<typeof setInterval>;
79
- flushTimer?: ReturnType<typeof setInterval>;
80
- heartbeatTimer?: ReturnType<typeof setInterval>;
81
- messageHeartbeats: number;
82
- }
83
-
84
- /** Tool count line: `[🔧] [n] name`. */
85
- function formatToolCount(name: string, count: number): string {
86
- return `[🔧] [${count}] ${name}`;
87
- }
88
-
89
- /** Heartbeat text: tool totals and elapsed time only (features-v1.md decision #3). */
90
- export function formatHeartbeat(elapsedMs: number, tools: Map<string, ToolStat2>): string {
91
- const minutes = Math.floor(elapsedMs / 60_000);
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)`;
94
- const parts = [...tools.entries()].map(([name, s]) => formatToolCount(name, s.count));
95
- const errors = [...tools.values()].reduce((n, s) => n + s.errors, 0);
96
- const suffix = errors > 0 ? ` · ${errors} failed` : "";
97
- return `⏱ Running for ${elapsedText} · ${parts.join(" · ")}${suffix}`;
98
- }
99
-
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)
103
-
104
- export class RunFeedback {
105
- private readonly deps: RunFeedbackDeps;
106
- private pending: { openid: string; msgId: string; at: number } | null = null;
107
- private run: RunState | null = null;
108
- private flushQueue: Promise<boolean> = Promise.resolve(true);
109
-
110
- constructor(deps: RunFeedbackDeps) {
111
- this.deps = deps;
112
- }
113
-
114
- /** Called by inbound before injecting: mark the next run as QQ-triggered. */
115
- markQQTrigger(openid: string, msgId: string): void {
116
- this.pending = { openid, msgId, at: Date.now() };
117
- }
118
-
119
- /** Whether a QQ-triggered run is active. Local pi runs have no RunFeedback state. */
120
- isQQRunActive(): boolean {
121
- return this.run !== null;
122
- }
123
-
124
- onAgentStart(): void {
125
- const pending = this.pending;
126
- this.pending = null;
127
- if (!pending || Date.now() - pending.at > PENDING_TTL_MS) return; // Not QQ-triggered
128
- const bot = this.deps.bot();
129
- if (!bot) return;
130
-
131
- const hbMinutes = this.deps.getHeartbeatMinutes();
132
- const run: RunState = {
133
- startedAt: Date.now(),
134
- openid: pending.openid,
135
- msgId: pending.msgId,
136
- tools: new Map(),
137
- winLines: [],
138
- thinkingMarked: false,
139
- snapshotText: "",
140
- finalizedText: "",
141
- resultSentLen: 0,
142
- startNewBubble: false,
143
- cur: null,
144
- lastAppendAt: Date.now(),
145
- messageHeartbeats: 0,
146
- };
147
- this.run = run;
148
- log.debug("run", "started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
149
-
150
- // Typing keepalive: start immediately, renew every 50s (zero quota).
151
- const keepTyping = () => {
152
- void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
153
- };
154
- keepTyping();
155
- run.typingTimer = setInterval(keepTyping, TYPING_INTERVAL_MS);
156
-
157
- // Fixed-interval summary frames (configurable in ms).
158
- run.flushTimer = setInterval(
159
- () => {
160
- void this.flushWindow(run);
161
- },
162
- Math.max(this.deps.getStreamFlushMs(), 300),
163
- );
164
-
165
- // Heartbeat fallback (liveness is covered by empty-window rows).
166
- if (hbMinutes > 0) {
167
- run.heartbeatTimer = setInterval(() => {
168
- void this.beat();
169
- }, hbMinutes * 60_000);
170
- }
171
- }
172
-
173
- /** Tool start: record in event order; merge consecutive same-tool calls. */
174
- onToolStart(toolName: string): void {
175
- const run = this.run;
176
- if (!run) return;
177
- const last = run.winLines.at(-1);
178
- if (last?.kind === "tool" && last.name === toolName) {
179
- last.count += 1;
180
- } else {
181
- run.winLines.push({ kind: "tool", name: toolName, count: 1 });
182
- }
183
- }
184
-
185
- /** Tool end: update totals for the heartbeat line. */
186
- onToolEnd(toolName: string, isError: boolean): void {
187
- const run = this.run;
188
- if (!run) return;
189
- const stat = run.tools.get(toolName) ?? { count: 0, errors: 0 };
190
- stat.count += 1;
191
- if (isError) stat.errors += 1;
192
- run.tools.set(toolName, stat);
193
- }
194
-
195
- /** Assistant snapshot: update the window; frames are sent by flush. */
196
- async onAssistantDelta(snapshotText: string, snapshotThinking: string): Promise<void> {
197
- const run = this.run;
198
- if (!run) return;
199
- if (snapshotThinking && !run.thinkingMarked) {
200
- run.thinkingMarked = true;
201
- run.winLines.push({ kind: "thinking" });
202
- }
203
- run.snapshotText = snapshotText;
204
- }
205
-
206
- /**
207
- * Finalize an assistant message (message_end).
208
- * Returns true when the stream took over (caller skips sendReply); false falls
209
- * back to the message path.
210
- */
211
- async onAssistantFinal(text: string, isError: boolean): Promise<boolean> {
212
- const run = this.run;
213
- if (!run) return false;
214
-
215
- if (isError) {
216
- // Seal the current bubble even on error; the caller sends the error message.
217
- await this.closeBubble(run);
218
- return false;
219
- }
220
-
221
- run.finalizedText = [run.finalizedText, text].filter((s) => s.trim()).join("\n\n");
222
- run.snapshotText = "";
223
- run.thinkingMarked = false; // Reset the thinking marker for the next message
224
- if (!this.deps.getStreamRelay()) return false;
225
-
226
- // Flush remaining text first, then set the boundary for the next text message.
227
- // Setting it earlier would misclassify leftover deltas as a new message.
228
- const handled = await this.flushWindow(run);
229
- run.startNewBubble = true;
230
- return handled;
231
- }
232
-
233
- /** Seal the current bubble: flush the window + DONE; re-read cur after flush. */
234
- private async sealBubble(run: RunState): Promise<void> {
235
- await this.flushWindow(run);
236
- await this.closeBubble(run);
237
- }
238
-
239
- /** Close the current bubble and send DONE; DONE failure still counts as closed. */
240
- private async closeBubble(run: RunState): Promise<void> {
241
- const cur = run.cur;
242
- if (!cur) return;
243
- run.cur = null;
244
- try {
245
- await cur.stream.done();
246
- } catch {}
247
- }
248
-
249
- /** Run end: seal the last bubble (flush + DONE) and clear timers. */
250
- async onAgentEnd(): Promise<void> {
251
- const run = this.run;
252
- this.clearTimers();
253
- this.run = null;
254
- if (run) {
255
- log.debug("run", "ended", {
256
- msgId: run.msgId?.slice(0, 8) ?? "?",
257
- elapsedMs: Date.now() - run.startedAt,
258
- });
259
- // Do not resend on DONE failure; content was already shown.
260
- try {
261
- await this.sealBubble(run);
262
- } catch {}
263
- }
264
- }
265
-
266
- /** Cleanup for session_shutdown and other error paths. */
267
- dispose(): void {
268
- this.clearTimers();
269
- this.run?.cur?.stream.dispose();
270
- this.run = null; // A bubble without DONE may stay generating (append mode cannot undo).
271
- }
272
-
273
- private clearTimers(): void {
274
- const run = this.run;
275
- if (!run) return;
276
- if (run.typingTimer) clearInterval(run.typingTimer);
277
- if (run.flushTimer) clearInterval(run.flushTimer);
278
- if (run.heartbeatTimer) clearInterval(run.heartbeatTimer);
279
- run.typingTimer = undefined;
280
- run.flushTimer = undefined;
281
- run.heartbeatTimer = undefined;
282
- }
283
-
284
- /**
285
- * Write window increments to bubbles: activity rows to activity bubbles, text
286
- * to text bubbles. A new text message or line group switches bubbles; later
287
- * deltas of the same message do not. A promise chain serializes flushes so
288
- * retries cannot interleave frames.
289
- */
290
- flushWindow(run?: RunState): Promise<boolean> {
291
- const p = this.flushQueue.then(() => this.doFlushWindow(run));
292
- this.flushQueue = p.catch(() => false);
293
- return p;
294
- }
295
-
296
- private async doFlushWindow(run?: RunState): Promise<boolean> {
297
- const r = run ?? this.run;
298
- if (!r) return false;
299
- if (!this.deps.getStreamRelay()) return false;
300
-
301
- const full = [r.finalizedText, r.snapshotText].filter((s) => s.trim()).join("\n\n");
302
- const textDelta = full.slice(r.resultSentLen);
303
- const textVisible = textDelta.trim().length > 0;
304
-
305
- // Line groups (thinking/tool counts) are summarized even without text.
306
- const okLines = await this.appendLineGroups(r);
307
- if (!okLines) return false;
308
-
309
- // Text gets its own bubble (whitespace-only deltas only advance the baseline).
310
- if (textVisible) {
311
- const okText = await this.appendText(r, textDelta);
312
- if (!okText) return false;
313
- // Advance the sent baseline or the next frame will append the same text again.
314
- r.resultSentLen = full.length;
315
- r.startNewBubble = false;
316
- } else if (textDelta) {
317
- r.resultSentLen = full.length;
318
- }
319
-
320
- // Reset the window
321
- r.winLines = [];
322
- return true;
323
- }
324
-
325
- /** Collect window rows in event order (consecutive same tools merged). */
326
- private collectWindowLines(r: RunState): string[] {
327
- return r.winLines.map((line) =>
328
- line.kind === "thinking" ? "[💭] Thinking..." : formatToolCount(line.name, line.count),
329
- );
330
- }
331
-
332
- /** Append activity rows; rows continue across frames. */
333
- private async appendLineGroups(r: RunState, lines?: string[]): Promise<boolean> {
334
- const group = lines ?? this.collectWindowLines(r);
335
- if (group.length === 0) return true;
336
- return this.pushAppend(r, `${group.join("\n")}\n`, "activity");
337
- }
338
-
339
- /** Append text: text messages own bubbles. */
340
- private async appendText(r: RunState, text: string): Promise<boolean> {
341
- // Previous text message finalized: seal it and start a new bubble.
342
- if (r.startNewBubble) await this.closeBubble(r);
343
- return this.pushAppend(r, text, "text");
344
- }
345
-
346
- /** Heartbeat fallback when streaming is unavailable (max N messages per run). */
347
- private async beat(): Promise<void> {
348
- const run = this.run;
349
- if (!run) return;
350
- if (this.deps.getStreamRelay()) return;
351
-
352
- if (run.messageHeartbeats >= this.deps.getHeartbeatMaxMessages()) return;
353
- const bound = this.deps.boundOpenid();
354
- if (!bound) return;
355
- const bot = this.deps.bot();
356
- if (!bot) return;
357
- run.messageHeartbeats += 1;
358
- await sendReply(bot, formatHeartbeat(Date.now() - run.startedAt, run.tools), this.deps.makeChannel());
359
- }
360
-
361
- /** Append a frame (lazy bubble; close on kind change); discard on failure. */
362
- private async pushAppend(run: RunState, delta: string, kind: "activity" | "text"): Promise<boolean> {
363
- if (!delta) return true;
364
- const bot = this.deps.bot();
365
- if (!bot) return false;
366
- try {
367
- if (run.cur && run.cur.kind !== kind) {
368
- await this.closeBubble(run);
369
- }
370
- if (!run.cur) {
371
- if (!run.msgId) return false;
372
- run.cur = {
373
- stream: new AppendStream(bot.messageApi, bot.getCredentials(), run.openid, run.msgId, {
374
- onError: (err) => this.handleStreamError(run, err),
375
- onDebug: (message) => log.debug("stream", message, { msgId: run.msgId?.slice(0, 8) ?? "?" }),
376
- }),
377
- kind,
378
- };
379
- this.deps.budget.noteStreamBubble(run.msgId);
380
- }
381
- await run.cur.stream.append(delta);
382
- run.lastAppendAt = Date.now();
383
- return true;
384
- } catch (err) {
385
- this.handleStreamError(run, err as Error);
386
- return false;
387
- }
388
- }
389
-
390
- /** Stream is untrusted: discard the bubble and resend unsent text via messages. */
391
- private handleStreamError(run: RunState, err: Error): void {
392
- const had = run.cur !== null;
393
- run.cur = null;
394
- log.warn("stream", "stream error", {
395
- msgId: run.msgId?.slice(0, 8) ?? "?",
396
- elapsedMs: Date.now() - run.startedAt,
397
- err,
398
- });
399
- if (had) this.deps.onWarn(`Stream unavailable; falling back to text (${err.message}).`);
400
- const rest = run.finalizedText.slice(run.resultSentLen);
401
- if (rest) {
402
- const bound = this.deps.boundOpenid();
403
- const bot = this.deps.bot();
404
- if (bound && bot) {
405
- run.resultSentLen = run.finalizedText.length;
406
- void sendReply(bot, rest, this.deps.makeChannel());
407
- }
408
- }
409
- }
410
- }