@chen_hu_hu/pi-qq 1.0.0 → 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 +70 -104
- package/doc/{features.md → features-v1.md} +55 -92
- package/doc/{plan.md → plan-v1.md} +38 -43
- package/index.ts +111 -159
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +23 -23
- package/src/budget-status.ts +9 -9
- package/src/config.ts +22 -80
- package/src/download.ts +3 -3
- package/src/files.ts +9 -9
- package/src/format.ts +6 -1
- package/src/images.ts +6 -6
- package/src/inbound.ts +12 -19
- package/src/login.ts +19 -20
- 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/outbound.ts
CHANGED
|
@@ -2,23 +2,23 @@ import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
|
2
2
|
import { ReplyBudget } from "./reply-budget";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* pi → QQ
|
|
6
|
-
*
|
|
5
|
+
* pi → QQ text relay (F4 non-streaming path): lightweight Markdown-to-plain
|
|
6
|
+
* conversion, long-text chunking, and passive-reply budget with fallback.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
/**
|
|
9
|
+
/** Single-text limit; SDK splits around 5000 chars, leaving protocol headroom. */
|
|
10
10
|
export const TEXT_CHUNK_LIMIT = 4500;
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Markdown →
|
|
14
|
-
*
|
|
13
|
+
* Markdown → plain text (features-v1.md F4: no Markdown permission by default).
|
|
14
|
+
* Keep mobile readability; preserve fenced code content and drop only the fences.
|
|
15
15
|
*/
|
|
16
16
|
export function markdownToPlain(md: string): string {
|
|
17
17
|
const out: string[] = [];
|
|
18
18
|
let inFence = false;
|
|
19
19
|
|
|
20
20
|
for (const raw of md.split("\n")) {
|
|
21
|
-
//
|
|
21
|
+
// Code fences: toggle state; drop fence lines, keep content as-is.
|
|
22
22
|
if (/^\s*(```|~~~)/.test(raw)) {
|
|
23
23
|
inFence = !inFence;
|
|
24
24
|
continue;
|
|
@@ -30,7 +30,7 @@ export function markdownToPlain(md: string): string {
|
|
|
30
30
|
|
|
31
31
|
let t = raw;
|
|
32
32
|
|
|
33
|
-
//
|
|
33
|
+
// Tables: drop separator rows; strip edge pipes and trim data rows.
|
|
34
34
|
if (/^\s*\|?[\s:|-]+\|?\s*$/.test(t) && t.includes("-") && t.includes("|")) {
|
|
35
35
|
continue;
|
|
36
36
|
}
|
|
@@ -41,7 +41,7 @@ export function markdownToPlain(md: string): string {
|
|
|
41
41
|
.trim();
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
//
|
|
44
|
+
// Headings / quotes / horizontal rules
|
|
45
45
|
t = t.replace(/^\s{0,3}#{1,6}\s+/, "");
|
|
46
46
|
t = t.replace(/^\s{0,3}>\s?/, "");
|
|
47
47
|
if (/^\s{0,3}([-*_]\s*){3,}$/.test(t)) {
|
|
@@ -49,13 +49,13 @@ export function markdownToPlain(md: string): string {
|
|
|
49
49
|
continue;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
//
|
|
52
|
+
// Images: keep alt text
|
|
53
53
|
t = t.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
54
|
-
//
|
|
54
|
+
// Links: text (url); keep only url when text equals url
|
|
55
55
|
t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, url: string) =>
|
|
56
56
|
text === url ? url : `${text}(${url})`,
|
|
57
57
|
);
|
|
58
|
-
//
|
|
58
|
+
// Emphasis / inline code / strikethrough
|
|
59
59
|
t = t.replace(/\*\*([^*]+)\*\*/g, "$1");
|
|
60
60
|
t = t.replace(/__([^_]+)__/g, "$1");
|
|
61
61
|
t = t.replace(/`([^`]+)`/g, "$1");
|
|
@@ -63,7 +63,7 @@ export function markdownToPlain(md: string): string {
|
|
|
63
63
|
t = t.replace(/\*([^*\n]+)\*/g, "$1");
|
|
64
64
|
t = t.replace(/(?<![A-Za-z0-9_])_([^_\n]+)_(?![A-Za-z0-9_])/g, "$1");
|
|
65
65
|
|
|
66
|
-
//
|
|
66
|
+
// Unordered lists → •; ordered lists unchanged
|
|
67
67
|
t = t.replace(/^(\s*)[-*+]\s+/, "$1• ");
|
|
68
68
|
|
|
69
69
|
out.push(t);
|
|
@@ -76,7 +76,7 @@ export function markdownToPlain(md: string): string {
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
/**
|
|
79
|
-
*
|
|
79
|
+
* Chunk long text at newlines when possible; hard-cut when there is no newline.
|
|
80
80
|
*/
|
|
81
81
|
export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
82
82
|
if (text.length <= limit) return [text];
|
|
@@ -84,7 +84,7 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
84
84
|
let rest = text;
|
|
85
85
|
while (rest.length > limit) {
|
|
86
86
|
let cut = rest.lastIndexOf("\n", limit);
|
|
87
|
-
cut = cut <= 0 ? limit : cut + 1; // +1
|
|
87
|
+
cut = cut <= 0 ? limit : cut + 1; // +1 keeps the newline at the end of the chunk
|
|
88
88
|
chunks.push(rest.slice(0, cut));
|
|
89
89
|
rest = rest.slice(cut);
|
|
90
90
|
}
|
|
@@ -92,21 +92,21 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
92
92
|
return chunks;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
/**
|
|
95
|
+
/** Send-channel dependencies: budget, fallback recipient, warning sink. */
|
|
96
96
|
export interface ReplyChannel {
|
|
97
97
|
budget: ReplyBudget;
|
|
98
|
-
/**
|
|
98
|
+
/** Bound user openid: fallback recipient for proactive sends. */
|
|
99
99
|
boundOpenid: string;
|
|
100
100
|
onWarn?: (msg: string) => void;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
/**
|
|
104
|
-
*
|
|
105
|
-
* passive
|
|
104
|
+
* Send one reply (auto-chunked, one budget ticket per chunk).
|
|
105
|
+
* A failed passive send retries once as proactive.
|
|
106
106
|
*
|
|
107
|
-
* QQBot
|
|
108
|
-
* msg_type=2
|
|
109
|
-
*
|
|
107
|
+
* When QQBot is constructed with markdownSupport=true, the SDK's sendText
|
|
108
|
+
* automatically uses msg_type=2 (markdown); callers only decide whether the
|
|
109
|
+
* payload keeps Markdown, with no separate sendMarkdown path needed here.
|
|
110
110
|
*/
|
|
111
111
|
export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
|
|
112
112
|
for (const chunk of chunkText(text)) {
|
|
@@ -119,7 +119,7 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
|
|
|
119
119
|
if (mode === "passive" && msgId) ch.budget.commitPassive(msgId);
|
|
120
120
|
} catch (err) {
|
|
121
121
|
if (mode === "passive") {
|
|
122
|
-
// msgId
|
|
122
|
+
// Passive failure (e.g. stale msgId) → retry once proactively.
|
|
123
123
|
try {
|
|
124
124
|
await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
|
|
125
125
|
ch.onWarn?.("被动回复失败,已降级主动发送");
|
package/src/qrcode-terminal.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** qrcode-terminal
|
|
1
|
+
/** qrcode-terminal has no bundled types (CJS); declare only the API we use. */
|
|
2
2
|
declare module "qrcode-terminal" {
|
|
3
3
|
export function generate(text: string, options?: { small?: boolean }, cb?: (ascii: string) => void): void;
|
|
4
4
|
export function setErrorLevel(level: number): void;
|
package/src/reply-budget.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { ReplyLimiter } from "@tencent-connect/qqbot-nodejs/protocol";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Passive reply budget (features-v1.md §3).
|
|
5
5
|
*
|
|
6
|
-
* QQ
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* QQ allows about 4 passive replies per inbound message (SDK ReplyLimiter default
|
|
7
|
+
* 4/1h); a msgId is usable for about 5 minutes after arrival. Over-limit or stale
|
|
8
|
+
* sends fall back to proactive mode. Counting reuses the SDK ReplyLimiter.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
export type ReplyMode = "passive" | "proactive";
|
|
12
12
|
|
|
13
13
|
export interface AcquireResult {
|
|
14
14
|
mode: ReplyMode;
|
|
15
|
-
/**
|
|
15
|
+
/** Sender of the latest inbound message; the caller falls back to the bound openid. */
|
|
16
16
|
openid?: string;
|
|
17
|
-
/** mode=passive
|
|
17
|
+
/** Present when mode=passive. */
|
|
18
18
|
msgId?: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -27,9 +27,9 @@ export interface BudgetSnapshot {
|
|
|
27
27
|
remaining: number;
|
|
28
28
|
totalReplies: number;
|
|
29
29
|
trackedMessages: number;
|
|
30
|
-
/**
|
|
30
|
+
/** Stream bubbles created for the current msgId (diagnostic only, not used by acquire). */
|
|
31
31
|
streamBubbles: number;
|
|
32
|
-
/**
|
|
32
|
+
/** Total stream bubbles in this process. */
|
|
33
33
|
streamBubblesTotal: number;
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -46,7 +46,7 @@ export class ReplyBudget {
|
|
|
46
46
|
this.freshMs = opts?.freshMs ?? 5 * 60_000;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
/**
|
|
49
|
+
/** Called on inbound: update the passive target and freshness start. */
|
|
50
50
|
observeInbound(openid: string, msgId: string, now = Date.now()): void {
|
|
51
51
|
if (this.last?.msgId !== msgId) {
|
|
52
52
|
this.streamMsgId = msgId;
|
|
@@ -55,14 +55,14 @@ export class ReplyBudget {
|
|
|
55
55
|
this.last = { openid, msgId, arrivedAt: now };
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/**
|
|
58
|
+
/** Latest inbound target (diagnostics/passive sends). */
|
|
59
59
|
get lastTarget(): { openid: string; msgId: string; arrivedAt: number } | undefined {
|
|
60
60
|
return this.last;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
64
|
+
* Pick the send mode for the next message. Passive only checks; callers must
|
|
65
|
+
* call commitPassive() after a successful passive send.
|
|
66
66
|
*/
|
|
67
67
|
acquire(now = Date.now()): AcquireResult {
|
|
68
68
|
const last = this.last;
|
|
@@ -74,12 +74,12 @@ export class ReplyBudget {
|
|
|
74
74
|
return { mode: "proactive", openid: last.openid };
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
/**
|
|
77
|
+
/** Record a successful passive send. */
|
|
78
78
|
commitPassive(msgId: string): void {
|
|
79
79
|
this.limiter.record(msgId);
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
/**
|
|
82
|
+
/** Diagnostic: record one new stream bubble (does not affect passive limits). */
|
|
83
83
|
noteStreamBubble(msgId: string): void {
|
|
84
84
|
if (this.streamMsgId !== msgId) {
|
|
85
85
|
this.streamMsgId = msgId;
|
|
@@ -89,7 +89,7 @@ export class ReplyBudget {
|
|
|
89
89
|
this.streamBubblesTotal += 1;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
/**
|
|
92
|
+
/** Diagnostic snapshot: passive budget, target freshness, and send counts. */
|
|
93
93
|
snapshot(now = Date.now()): BudgetSnapshot {
|
|
94
94
|
const config = this.limiter.getConfig();
|
|
95
95
|
const stats = this.limiter.getStats();
|
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;
|