@chen_hu_hu/pi-qq 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/bot.ts CHANGED
@@ -10,36 +10,36 @@ import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
10
10
  import type { Credentials } from "./config";
11
11
 
12
12
  /**
13
- * QQBot 实例的会话级生命周期管理:
14
- * 创建、中间件装配、连接状态跟踪、终态错误上报。
15
- * start() 阻塞至 stop()/abort,因此在后台运行(void 不等待)。
13
+ * Session-level QQBot lifecycle: creation, middleware, connection state,
14
+ * and fatal-error reporting. start() blocks until stop()/abort, so it runs
15
+ * in the background (void, not awaited).
16
16
  */
17
17
 
18
18
  export type BotState =
19
- | "stopped" // 未运行 / 已停止
20
- | "starting" // 已发起连接,等待 READY
21
- | "connected" // 在线(READY / RESUMED)
22
- | "reconnecting" // 断线,SDK 自动重连中
23
- | "blocked"; // 致命关闭(4914 下线 / 4915 封禁),需人工介入
19
+ | "stopped" // Not running/stopped
20
+ | "starting" // Connecting, waiting for READY
21
+ | "connected" // Online (READY/RESUMED)
22
+ | "reconnecting" // Disconnected; the SDK is reconnecting
23
+ | "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
24
24
 
25
25
  export interface StartBotOptions {
26
26
  credentials: Credentials;
27
27
  /** F2: QR-bound single user; production always provides it */
28
28
  allowedOpenid?: string;
29
29
  markdownSupport?: boolean;
30
- /** 诊断模式:SDK 内部日志(超时/限流/重连等)打到终端 */
30
+ /** Debug mode: print SDK logs (timeouts/rate limits/reconnects) to the terminal. */
31
31
  debug?: boolean;
32
- /** 入站消息接线点(M2 起;M1 为空) */
32
+ /** Inbound message handler. */
33
33
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
34
- /** 连接状态变化(UI 通知由调用方决定) */
34
+ /** Connection state changes; the caller decides how to notify the UI. */
35
35
  onStateChange?: (state: BotState, detail?: string) => void;
36
- /** 可恢复错误(SDK 自动重连,不打扰用户) */
36
+ /** Recoverable errors; the SDK reconnects automatically. */
37
37
  onRecoverableError?: (err: Error) => void;
38
38
  }
39
39
 
40
40
  export interface RunningBot {
41
41
  bot: QQBot;
42
- /** 幂等停止 */
42
+ /** Idempotent stop. */
43
43
  stop: () => void;
44
44
  }
45
45
 
@@ -50,13 +50,13 @@ export function startBot(opts: StartBotOptions): RunningBot {
50
50
  markdownSupport: opts.markdownSupport ?? false,
51
51
  });
52
52
 
53
- // 回声过滤 + 消息去重(SDK 默认 5s 窗口)
53
+ // Echo filtering + message deduplication (SDK default 5s window).
54
54
  bot.use(messageFilter({ skipSelfEcho: true }));
55
- // 清洗 @marker / face tags 等协议标记,只留纯文本
55
+ // Strip protocol markers such as @mentions and face tags.
56
56
  bot.use(contentSanitizer({ stripBotMention: true }));
57
57
  // Single-user allowlist for C2C; inbound also rejects when no QR login is active.
58
58
  bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
59
- // 同用户串行处理,避免流式与回复互相踩踏
59
+ // Serialize per user so streams and replies do not race.
60
60
  bot.use(concurrencyGuard());
61
61
 
62
62
  const report = (state: BotState, detail?: string) => opts.onStateChange?.(state, detail);
@@ -10,7 +10,7 @@ function mask(value: string): string {
10
10
  return `${value.slice(0, 8)}…`;
11
11
  }
12
12
 
13
- /** Render `/qq-budget` output lines; pure function for tests. */
13
+ /** Render `/qq-test-budget` output lines; pure function for tests. */
14
14
  export function formatBudgetStatus(
15
15
  snapshot: BudgetSnapshot,
16
16
  last: BudgetTarget | undefined,
package/src/config.ts CHANGED
@@ -9,14 +9,12 @@ import { join } from "node:path";
9
9
  * process memory, so restarting pi requires scanning a new QR code.
10
10
  */
11
11
 
12
- /** Runtime settings (features.md §4). */
12
+ /** Runtime settings (features-v1.md §4). */
13
13
  export interface PiQQSettings {
14
14
  /** F4: stream assistant replies */
15
15
  streamAssistant?: boolean;
16
16
  /** F4: bot has QQ markdown permission; pass Markdown through when true */
17
17
  markdownSupport?: boolean;
18
- /** F5/F6: usage summary switch */
19
- usageRelay?: boolean;
20
18
  /** F2: how a busy agent handles new messages */
21
19
  deliverAs?: "steer" | "followUp";
22
20
  /** F3: QQ image download limit (bytes) */
@@ -63,12 +61,11 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
63
61
 
64
62
  export interface ResolvedSettings extends Required<PiQQSettings> {}
65
63
 
66
- /** Settings with defaults applied (features.md §4). */
64
+ /** Settings with defaults applied (features-v1.md §4). */
67
65
  export function getSettings(config: PiQQConfig): ResolvedSettings {
68
66
  return {
69
67
  streamAssistant: config.streamAssistant ?? true,
70
68
  markdownSupport: config.markdownSupport ?? false,
71
- usageRelay: config.usageRelay ?? true,
72
69
  deliverAs: config.deliverAs ?? "steer",
73
70
  imageMaxSize: config.imageMaxSize ?? 10 * 1024 * 1024,
74
71
  fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
package/src/download.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { formatBytes } from "./format";
2
2
 
3
- /** QQ 入站附件的最小结构(图片与文件共用)。 */
3
+ /** Minimal QQ inbound attachment shape shared by images and files. */
4
4
  export interface InboundAttachmentLike {
5
5
  content_type: string;
6
6
  url: string;
@@ -12,7 +12,7 @@ export interface DownloadOptions {
12
12
  url: string;
13
13
  maxSize: number;
14
14
  timeoutMs: number;
15
- /** 错误文案中的类型名,如“图片”/“文件” */
15
+ /** Kind label used in errors, e.g. "image" or "file". */
16
16
  kind: string;
17
17
  fetchImpl?: typeof fetch;
18
18
  }
@@ -48,7 +48,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
48
48
  return Buffer.concat(chunks, total);
49
49
  }
50
50
 
51
- /** 带超时与流式大小上限的附件下载。 */
51
+ /** Download an attachment with a timeout and streaming size cap. */
52
52
  export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
53
53
  const limit = Math.max(1, opts.maxSize);
54
54
  let parsed: URL;
package/src/files.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** QQ 非图片附件 → 当前工作空间保存,并在提示词中给出路径供 pi 使用。 */
1
+ /** Save QQ non-image attachments in the workspace and reference them in the prompt. */
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
3
  import { basename, extname, join } from "node:path";
4
4
  import { downloadLimited, type InboundAttachmentLike } from "./download";
@@ -20,9 +20,9 @@ export interface FileFailure {
20
20
 
21
21
  export interface SaveFilesOptions {
22
22
  maxSize: number;
23
- /** 测试可覆盖;默认 <cwd>/.pi/pi-qq */
23
+ /** Test override; defaults to <cwd>/.pi/pi-qq. */
24
24
  baseDir?: string;
25
- /** 用于隔离同一消息的文件目录(通常传 msgId) */
25
+ /** Directory key for one message (usually msgId). */
26
26
  dirKey?: string;
27
27
  now?: Date;
28
28
  fetchImpl?: typeof fetch;
@@ -47,7 +47,7 @@ function withSuffix(filename: string, suffix: number): string {
47
47
  return `${stem}-${suffix}${ext}`;
48
48
  }
49
49
 
50
- /** 只保留安全文件名(去掉路径、控制符和 Windows 非法字符),超长时截断 stem。 */
50
+ /** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
51
51
  export function sanitizeFilename(filename: string | undefined, fallback: string): string {
52
52
  const raw = basename((filename ?? "").trim());
53
53
  const cleaned = raw
@@ -81,7 +81,7 @@ async function writeUnique(dir: string, filename: string, body: Buffer): Promise
81
81
  throw new Error("无法分配唯一文件名");
82
82
  }
83
83
 
84
- /** 将非图片附件按原顺序保存到本地,单文件失败不影响其他文件。 */
84
+ /** Save non-image attachments in order; one failure does not stop the others. */
85
85
  export async function saveInboundFiles(
86
86
  attachments: readonly InboundAttachmentLike[],
87
87
  options: SaveFilesOptions,
@@ -124,7 +124,7 @@ export async function saveInboundFiles(
124
124
  return { files, failures };
125
125
  }
126
126
 
127
- /** 将保存路径与用户原消息组合成 pi 提示词。 */
127
+ /** Combine saved paths and the original user message into the pi prompt. */
128
128
  export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
129
129
  if (files.length === 0) return userText;
130
130
 
package/src/format.ts CHANGED
@@ -1,6 +1,11 @@
1
- /** 人类可读的大小格式化,供图片/文件下载与提示词共享。 */
1
+ /** Human-readable size formatting shared by image/file downloads and prompts. */
2
2
  export function formatBytes(bytes: number): string {
3
3
  if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
4
4
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}KB`;
5
5
  return `${bytes}B`;
6
6
  }
7
+
8
+ /** Compact token count used by /qq-status. */
9
+ export function formatTokenCount(n: number): string {
10
+ return n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n);
11
+ }
package/src/images.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** QQ 图片附件 → pi ImageContent:类型/大小校验、带超时的受限下载。 */
1
+ /** QQ image attachments to pi ImageContent: validation and timeout-limited download. */
2
2
  import { downloadLimited, type InboundAttachmentLike } from "./download";
3
3
  import { formatBytes } from "./format";
4
4
 
@@ -44,12 +44,12 @@ const MIME_BY_EXTENSION: Record<string, string> = {
44
44
  gif: "image/gif",
45
45
  };
46
46
 
47
- /** 按 content_type 优先、文件名扩展名兜底,返回可注入的 mime;不支持返回 null。 */
47
+ /** Prefer content_type, fall back to extension; return injectable mime or null. */
48
48
  export function resolveImageMime(contentType: string | undefined, filename: string | undefined): string | null {
49
49
  const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
50
50
  if (type) {
51
51
  if (MIME_BY_CONTENT_TYPE[type]) return MIME_BY_CONTENT_TYPE[type];
52
- // 明确声明为 image/* 但不支持(如 svg)时拒绝,避免错误扩展名绕过校验
52
+ // Reject unsupported image/* types (e.g. svg) so a wrong extension cannot bypass validation.
53
53
  if (type.startsWith("image/")) return null;
54
54
  }
55
55
 
@@ -57,14 +57,14 @@ export function resolveImageMime(contentType: string | undefined, filename: stri
57
57
  return ext ? (MIME_BY_EXTENSION[ext] ?? null) : null;
58
58
  }
59
59
 
60
- /** 是否为图片附件(含不支持的 image/*,由图片流程给出失败提示)。 */
60
+ /** Whether the attachment is an image (unsupported image/* is handled by the image path). */
61
61
  export function isImageAttachment(attachment: InboundAttachmentLike): boolean {
62
62
  const type = (attachment.content_type ?? "").toLowerCase();
63
63
  if (type.startsWith("image/")) return true;
64
64
  return resolveImageMime(attachment.content_type, attachment.filename) !== null;
65
65
  }
66
66
 
67
- /** 文本 + 图片组合为 pi.sendUserMessage 的内容;无图片时保持纯字符串。 */
67
+ /** Build pi.sendUserMessage content; keep a plain string when there are no images. */
68
68
  export function buildImageMessageContent(
69
69
  text: string,
70
70
  images: readonly ImageContentLike[],
@@ -116,7 +116,7 @@ async function downloadOne(
116
116
  }
117
117
  }
118
118
 
119
- /** 按原顺序下载所有图片;单张失败不影响其他图片。 */
119
+ /** Download images in order; one failure does not stop the others. */
120
120
  export async function resolveInboundImages(
121
121
  attachments: readonly InboundAttachmentLike[],
122
122
  maxSize: number,
package/src/inbound.ts CHANGED
@@ -20,20 +20,20 @@ import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
20
20
 
21
21
  export interface InboundDeps {
22
22
  pi: ExtensionAPI;
23
- /** session_start 时捕获的会话上下文:ui/isIdle/abort/compact/getContextUsage */
23
+ /** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
24
24
  ctx: ExtensionContext;
25
25
  budget: ReplyBudget;
26
- /** 均实时读配置,绑定关系变更即时生效 */
26
+ /** Read settings live so changes apply immediately. */
27
27
  getAllowedOpenid: () => string | undefined;
28
28
  getBoundOpenid: () => string | undefined;
29
29
  getDeliverAs: () => "steer" | "followUp";
30
30
  getImageMaxSize: () => number;
31
31
  getFileMaxSize: () => number;
32
- /** 测试可注入;默认 saveInboundFiles */
32
+ /** Test override; defaults to saveInboundFiles. */
33
33
  saveFiles?: typeof saveInboundFiles;
34
34
  getStatusLines: () => string[];
35
35
  onWarn: (msg: string) => void;
36
- /** F7:标记接下来的 run 由 QQ 触发(供 RunFeedback 建立确认/心跳/typing) */
36
+ /** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
37
37
  markQQTrigger: (openid: string, msgId: string) => void;
38
38
  }
39
39
 
@@ -67,7 +67,7 @@ export function createInboundHandler(deps: InboundDeps) {
67
67
  return;
68
68
  }
69
69
 
70
- // F3:图片转 ImageContent,非图片附件保存到本地并在提示词中给出路径
70
+ // F3: images become ImageContent; other attachments are saved and referenced by path.
71
71
  const imageAttachments = attachments.filter(isImageAttachment);
72
72
  const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
73
73
  const failures: Array<{ filename: string; reason: string }> = [];
@@ -100,7 +100,7 @@ export function createInboundHandler(deps: InboundDeps) {
100
100
  }
101
101
  if (!text && images.length === 0 && files.length === 0) return;
102
102
 
103
- // F7:标记 QQ 触发的 run(RunFeedback 据此建立 typing/时间线),不发送开始确认
103
+ // F7: mark a QQ-triggered run; do not send a start confirmation.
104
104
  deps.markQQTrigger(msg.senderId, msg.messageId);
105
105
  const promptText = formatFilePrompt(files, text);
106
106
  deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
@@ -147,7 +147,7 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
147
147
  await reply("任务运行中,请先 /stop 再重置会话");
148
148
  } else {
149
149
  await reply("正在重置会话…");
150
- // 内置 /new 仅在交互模式处理;这里通过扩展命令调用 ctx.newSession
150
+ // Built-in /new is interactive-only; dispatch the extension command instead.
151
151
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
152
152
  }
153
153
  break;
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();