@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/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 的文本回传(F4 非流式路径):
6
- * markdown → 纯文本轻量转换、超长分块、按被动回复预算发牌与降级。
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
- /** 单条文本上限。SDK 内部按 ~5000 字符切分,这里留出协议余量。 */
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 → 纯文本(features.md F4:默认机器人无 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
- // 图片:保留 alt 文本
52
+ // Images: keep alt text
53
53
  t = t.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
54
- // 链接:文字(url);文字与 url 相同则只留 url
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
- /** 绑定用户 openid:proactive 模式与无入站记录时的兜底收件人 */
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 发送失败时自动降级为 proactive 重试一次。
104
+ * Send one reply (auto-chunked, one budget ticket per chunk).
105
+ * A failed passive send retries once as proactive.
106
106
  *
107
- * QQBot 构造时 markdownSupport=true 的情况下,SDK 的 sendText 会自动使用
108
- * msg_type=2(markdown),因此调用方只需决定 payload 是否保留 Markdown,
109
- * 无需在这里区分 sendMarkdown。
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?.("被动回复失败,已降级主动发送");
@@ -1,4 +1,4 @@
1
- /** qrcode-terminal 无自带类型声明(CJS 包,此处仅声明用到的 API)。 */
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;
@@ -1,20 +1,20 @@
1
1
  import { ReplyLimiter } from "@tencent-connect/qqbot-nodejs/protocol";
2
2
 
3
3
  /**
4
- * 被动回复预算(features.md §3)。
4
+ * Passive reply budget (features-v1.md §3).
5
5
  *
6
- * QQ 平台限制:每条入站消息最多约 4 条被动回复(SDK ReplyLimiter 默认 4 条/1h),
7
- * 且 msgId 仅在到达后约 5 分钟内可用作被动回复引用;超限或过期一律降级为主动发送。
8
- * 计数复用 SDK 的 ReplyLimiter(@tencent-connect/qqbot-nodejs/protocol 子导出)。
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
- /** 最近一次入站消息的发送者;无入站记录时缺省,由调用方用绑定 openid 兜底 */
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
- /** 当前 msgId 下已创建的流式气泡数(诊断用,不计入 acquire) */
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
- * 为下一条待发送消息取发送模式。passive 只检查不计数,
65
- * 发送成功后须调用 commitPassive() 记账。
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();
@@ -4,20 +4,21 @@ import { sendReply, type ReplyChannel } from "./outbound";
4
4
  import type { ReplyBudget } from "./reply-budget";
5
5
 
6
6
  /**
7
- * F7 长任务反馈:run 级状态机(汇总帧 + 文本气泡切分版)。
7
+ * F7 long-task feedback: run-level state machine (summary frames + text bubbles).
8
8
  *
9
- * 场景:user_input → thinking+tools(10~60 分钟)→ assistant message,n 轮循环。
9
+ * Scenario: user_input → thinking/tools (10–60 minutes) → assistant message, n turns.
10
10
  *
11
- * 气泡切分规则:**assistant 文本消息与思考/工具汇总使用独立气泡**。
12
- * 文本消息(同一 assistant 消息的流式增量)独占一个文本气泡;思考/工具行组进入
13
- * 活动气泡。文本首个增量到达时封口当前活动气泡;工具/思考出现时封口当前文本气泡,
14
- * 新行组进新的活动气泡;最终回复独立成文本气泡。气泡内按 `streamFlushMs`
15
- * (默认 10000ms)固定频率发送窗口汇总帧:
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
- * 活动气泡:💭 思考中... / [2] 🔧 bash(行组按事件顺序、外层带 [HH:MM:SS] 时间戳)
18
- * 文本气泡:消息原文(流式增量,按 markdown 渲染)
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
- /** 流式汇总帧间隔(毫秒,最小 300) */
35
+ /** Stream summary frame interval in ms (minimum 300). */
35
36
  getStreamFlushMs: () => number;
36
37
  getStreamRelay: () => boolean;
37
- /** 诊断模式:SDK 日志转终端 + 文本帧也带时间戳 */
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
- /** 当前气泡:一条独立流式消息;kind 决定它只接收文本还是思考/工具行组 */
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
- /** 本窗口行组,按事件实际发生顺序记录(flush 后清空) */
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
- /** 当前流式文本快照(message_update 更新) */
67
+ /** Current streaming text snapshot (updated by message_update). */
67
68
  snapshotText: string;
68
- /** 已定稿 assistant 消息累计文本 */
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
- /** 当前气泡(null = 待惰性创建) */
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
- /** 本地时间 HH:MM:SS,用于汇总帧首行的时间戳 */
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
- /** 工具计数:`[n] 🔧 name`(行组帧外层再加一次 [HH:MM:SS] 时间戳) */
92
+ /** Tool count line: `[🔧] [n] name`; debug mode prefixes [HH:MM:SS]. */
92
93
  function formatToolCount(name: string, count: number): string {
93
- return `[${count}] 🔧 ${name}`;
94
+ return `[🔧] [${count}] ${name}`;
94
95
  }
95
96
 
96
- /** 心跳文案:仅工具名×总次数与时长,无参数无响应(features.md 决策 #3) */
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; // 平台 typing 窗口 ~60s,提前续期
109
- const PENDING_TTL_MS = 15_000; // QQ 触发标记的有效期(超过视为本地 run)
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 在注入 pi 前调用:标记接下来的 run 由 QQ 触发 */
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; // 非 QQ 触发
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
- // typing 保鲜:run 开始立即亮起"正在输入",之后每 50s 续期(0 额度)
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
- /** assistant 流式快照(message_update):只更新窗口,汇总帧统一发送 */
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 消息定稿(message_end)。
220
- * 返回 true 表示流接管(调用方跳过 sendReply);默认/流失败返回 false 走消息路径。
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
- // 出错也先封口当前气泡(结束 QQ 的生成态),错误摘要交回调用方走消息链路
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; // 下一条 assistant 消息重新计时思考标记
231
+ run.thinkingMarked = false; // Reset the thinking marker for the next message
235
232
  if (!this.deps.getStreamRelay()) return false;
236
233
 
237
- // 先把本条消息剩余的快照补发完,再把边界标记留给下一条文本消息
238
- // (若在 flush 前置位,本条消息的残余增量会被误判为新消息而切泡)
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
- /** 封口当前气泡:补发剩余窗口 + DONE。flush 可能因切泡换掉 cur,需重新读取。 */
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
- /** 关闭当前气泡并发送 DONE;DONE 失败也视为已关闭(追加模式无撤销语义)。 */
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
- /** run 结束:封口最后一个气泡(补帧 + DONE),清定时器 */
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; // 未发 DONE 的气泡会停留在生成态(追加模式无撤销语义,可接受)
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
- * 通过 promise 链串行化:限流重试期间(最长 7s)定时器再次触发也不会产生交错帧。
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" ? "💭 思考中..." : formatToolCount(line.name, line.count),
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
- /** 心跳兜底:流式路径的活性由空窗口活性行覆盖;流不可用时发消息心跳(保险丝 ≤N 条) */
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
- await sendReply(
369
- bot,
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
- /** 追加一帧(惰性建气泡;内容类型变化时先封口旧气泡);失败弃气泡并返回 false */
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;