@chen_hu_hu/pi-qq 1.2.3 → 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 +34 -24
  2. package/README.md +26 -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 +3 -3
  11. package/src/{download.ts → attachments/attachment-download.ts} +1 -4
  12. package/src/{files.ts → attachments/file-attachments.ts} +3 -14
  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 -409
@@ -7,38 +7,20 @@ import {
7
7
  messageFilter,
8
8
  } from "@tencent-connect/qqbot-nodejs";
9
9
  import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
10
- import type { Credentials } from "./config";
11
- import { log, sdkLogger } from "./logger";
10
+ import type { Credentials } from "../infra/settings";
11
+ import { log, sdkLogger } from "../infra/file-logger";
12
12
 
13
- /**
14
- * Session-level QQBot lifecycle: creation, middleware, connection state,
15
- * and fatal-error reporting. start() blocks until stop()/abort, so it runs
16
- * in the background (void, not awaited).
17
- */
18
-
19
- export type BotState =
20
- | "stopped" // Not running/stopped
21
- | "starting" // Connecting, waiting for READY
22
- | "connected" // Online (READY/RESUMED)
23
- | "reconnecting" // Disconnected; the SDK is reconnecting
24
- | "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
13
+ export type BotState = "stopped" | "starting" | "connected" | "reconnecting" | "blocked";
25
14
 
26
15
  export interface StartBotOptions {
27
16
  credentials: Credentials;
28
- /** F2: QR-bound single user; production always provides it */
29
17
  allowedOpenid?: string;
30
- markdownSupport?: boolean;
31
- /** Inbound message handler. */
32
18
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
33
- /** Connection state changes; the caller decides how to notify the UI. */
34
19
  onStateChange?: (state: BotState, detail?: string) => void;
35
- /** Recoverable errors; the SDK reconnects automatically. */
36
- onRecoverableError?: (err: Error) => void;
37
20
  }
38
21
 
39
22
  export interface RunningBot {
40
23
  bot: QQBot;
41
- /** Idempotent stop. */
42
24
  stop: () => void;
43
25
  }
44
26
 
@@ -46,23 +28,17 @@ export function startBot(opts: StartBotOptions): RunningBot {
46
28
  log.info("bot", "starting", {
47
29
  appId: opts.credentials.appId,
48
30
  allowedOpenid: opts.allowedOpenid,
49
- markdownSupport: opts.markdownSupport,
50
31
  });
51
32
 
52
33
  const bot = new QQBot({
53
34
  appId: opts.credentials.appId,
54
35
  appSecret: opts.credentials.appSecret,
55
- markdownSupport: opts.markdownSupport ?? false,
56
36
  logger: sdkLogger,
57
37
  });
58
38
 
59
- // Echo filtering + message deduplication (SDK default 5s window).
60
39
  bot.use(messageFilter({ skipSelfEcho: true }));
61
- // Strip protocol markers such as @mentions and face tags.
62
40
  bot.use(contentSanitizer({ stripBotMention: true }));
63
- // Single-user allowlist for C2C; inbound also rejects when no QR login is active.
64
41
  bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
65
- // Serialize per user so streams and replies do not race.
66
42
  bot.use(concurrencyGuard());
67
43
 
68
44
  const report = (state: BotState, detail?: string) => {
@@ -81,7 +57,6 @@ export function startBot(opts: StartBotOptions): RunningBot {
81
57
  bot.on("disconnected", ({ willReconnect }) => report(willReconnect ? "reconnecting" : "stopped"));
82
58
  bot.on("error", (err) => {
83
59
  log.error("bot", "error event", { err });
84
- opts.onRecoverableError?.(err);
85
60
  });
86
61
  bot.on("message", async (_ctx, msg) => {
87
62
  log.debug("bot", "inbound message", {
@@ -112,7 +87,7 @@ export function startBot(opts: StartBotOptions): RunningBot {
112
87
  let stopped = false;
113
88
  report("starting");
114
89
  void bot.start().catch((err: unknown) => {
115
- if (stopped) return; // Normal return from an explicit stop().
90
+ if (stopped) return;
116
91
  const code = (err as { code?: string }).code;
117
92
  if (code === GatewayErrorCode.FATAL_CLOSE) {
118
93
  const closeCode = (err as { closeCode?: number }).closeCode;
@@ -1,45 +1,36 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
3
- import { sendReply, type ReplyChannel } from "./outbound";
4
- import type { ReplyBudget } from "./reply-budget";
3
+ import { sendReply, type ReplyChannel } from "./reply-sender";
4
+ import type { ReplyBudget } from "../quota/reply-quota";
5
5
  import {
6
6
  buildImageMessageContent,
7
7
  formatImageFailures,
8
8
  isImageAttachment,
9
9
  resolveInboundImages,
10
10
  type ImageContentLike,
11
- } from "./images";
12
- import { formatFilePrompt, saveInboundFiles, sessionUploadDir, type SavedFile } from "./files";
13
- import { log } from "./logger";
14
- import { isVoiceAttachment, resolveVoiceTranscript } from "./voice";
15
-
16
- /**
17
- * F2: QQ → pi inbound handling.
18
- * Chain: C2C filter → QR-bound user whitelist → QQ commands → text/image/file injection.
19
- * Use pi.sendUserMessage (ExtensionContext has no such API).
20
- */
11
+ } from "../attachments/image-attachments";
12
+ import { formatFilePrompt, saveInboundFiles, sessionUploadDir, type SavedFile } from "../attachments/file-attachments";
13
+ import { log } from "../infra/file-logger";
14
+ import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
21
15
 
22
16
  export interface InboundDeps {
23
17
  pi: ExtensionAPI;
24
- /** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
25
18
  ctx: ExtensionContext;
26
19
  budget: ReplyBudget;
27
- /** Read settings live so changes apply immediately. */
28
20
  getAllowedOpenid: () => string | undefined;
29
21
  getBoundOpenid: () => string | undefined;
30
22
  getDeliverAs: () => "steer" | "followUp";
31
23
  getImageMaxSize: () => number;
32
24
  getFileMaxSize: () => number;
33
- /** Test override; defaults to saveInboundFiles. */
34
25
  saveFiles?: typeof saveInboundFiles;
35
26
  getStatusLines: () => string[];
36
27
  onWarn: (msg: string) => void;
37
- /** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
38
28
  markQQTrigger: (openid: string, msgId: string) => void;
29
+ waitForEnd?: () => Promise<void>;
30
+ onStop?: () => void;
39
31
  }
40
32
 
41
33
  export function createInboundHandler(deps: InboundDeps) {
42
- // F10: files uploaded without text wait for the next text/voice instruction.
43
34
  let pendingFiles: SavedFile[] = [];
44
35
  const takePendingFiles = (): SavedFile[] => {
45
36
  const files = pendingFiles;
@@ -77,7 +68,6 @@ export function createInboundHandler(deps: InboundDeps) {
77
68
  return;
78
69
  }
79
70
 
80
- // Record passive reply target/freshness for outbound budget.
81
71
  deps.budget.observeInbound(msg.senderId, msg.messageId);
82
72
  log.info("inbound", "message received", {
83
73
  messageId: msg.messageId,
@@ -113,7 +103,6 @@ export function createInboundHandler(deps: InboundDeps) {
113
103
  return;
114
104
  }
115
105
 
116
- // F8: voice messages use QQ built-in ASR; never download or save the audio.
117
106
  const voiceAttachments = attachments.filter(isVoiceAttachment);
118
107
  if (voiceAttachments.length > 0) {
119
108
  const transcript = resolveVoiceTranscript(voiceAttachments);
@@ -140,7 +129,6 @@ export function createInboundHandler(deps: InboundDeps) {
140
129
  return;
141
130
  }
142
131
 
143
- // F3: images become ImageContent; other attachments are saved and referenced by path.
144
132
  const imageAttachments = attachments.filter(isImageAttachment);
145
133
  const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
146
134
  const failures: Array<{ filename: string; reason: string }> = [];
@@ -193,7 +181,6 @@ export function createInboundHandler(deps: InboundDeps) {
193
181
  return;
194
182
  }
195
183
 
196
- // F10: a file-only message waits for the next text/voice instruction.
197
184
  if (!text && images.length === 0 && files.length > 0) {
198
185
  pendingFiles.push(...files);
199
186
  log.info("inbound", "files pending for instruction", {
@@ -204,7 +191,6 @@ export function createInboundHandler(deps: InboundDeps) {
204
191
  return;
205
192
  }
206
193
 
207
- // F7: mark a QQ-triggered run; do not send a start confirmation.
208
194
  deps.markQQTrigger(msg.senderId, msg.messageId);
209
195
  const pending = text ? takePendingFiles() : [];
210
196
  const promptFiles = [...pending, ...files];
@@ -241,7 +227,9 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
241
227
  if (deps.ctx.isIdle()) {
242
228
  await reply("No task is running.");
243
229
  } else {
230
+ deps.onStop?.();
244
231
  deps.ctx.abort();
232
+ await deps.waitForEnd?.();
245
233
  await reply("Abort requested.");
246
234
  }
247
235
  break;
@@ -261,7 +249,6 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
261
249
  await reply("Task is running; use /stop before resetting.");
262
250
  } else {
263
251
  await reply("Resetting the session…");
264
- // Built-in /new is interactive-only; dispatch the extension command instead.
265
252
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
266
253
  }
267
254
  break;
@@ -1,24 +1,17 @@
1
1
  import { startQrConnect } from "@tencent-connect/qqbot-connector";
2
2
  import { generate } from "qrcode-terminal";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import type { Credentials } from "./config";
5
-
6
- /**
7
- * F1: QR-code login only.
8
- * - TUI: show an ASCII QR code in ctx.ui.custom; Esc cancels.
9
- * - Non-TUI: print the QR URL and poll until the scan completes.
10
- * Credentials are returned to the caller and kept in memory only.
11
- */
4
+ import type { Credentials } from "../infra/settings";
5
+ import { log } from "../infra/file-logger";
12
6
 
13
7
  export interface QrLoginResult extends Credentials {
14
- /** openid of the scanning user, used as the single bound QQ user */
15
8
  userOpenid?: string;
16
9
  }
17
10
 
18
11
  export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult | undefined> {
19
12
  const ac = new AbortController();
13
+ log.info("login", "QR login started");
20
14
 
21
- // Shared QR state so polling callbacks and the TUI component stay decoupled.
22
15
  const qr = { lines: [] as string[], hint: "Fetching QR code…" };
23
16
  let requestRender: (() => void) | undefined;
24
17
  let closeOverlay: (() => void) | undefined;
@@ -34,27 +27,40 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
34
27
 
35
28
  const stopPolling = startQrConnect(
36
29
  {
37
- // The connector currently returns one entry; iterate for future compatibility.
38
30
  onSuccess: ([first]) => {
31
+ log.info("login", "QR login succeeded", {
32
+ appId: first?.appId ?? null,
33
+ hasOpenid: Boolean(first?.userOpenid),
34
+ });
39
35
  finish(first ? { appId: first.appId, appSecret: first.appSecret, userOpenid: first.userOpenid } : undefined);
40
36
  closeOverlay?.();
41
37
  },
42
38
  onFailure: (err) => {
43
- if (settled) return; // User cancelled (abort); no error toast.
44
- ctx.ui.notify(`QR login failed: ${err.message}`, "error");
39
+ if (settled) return;
40
+ const cause = (err as { cause?: unknown }).cause;
41
+ log.error("login", "QR login failed", {
42
+ err,
43
+ name: err.name,
44
+ code: (err as NodeJS.ErrnoException).code,
45
+ causeName: cause instanceof Error ? cause.name : undefined,
46
+ causeCode: cause && typeof cause === "object" ? (cause as NodeJS.ErrnoException).code : undefined,
47
+ causeMessage: cause instanceof Error ? cause.message : undefined,
48
+ });
49
+ ctx.ui.notify("Error: QR login failed", "error");
45
50
  finish();
46
51
  closeOverlay?.();
47
52
  },
48
53
  onQrDisplayed: (url) => {
54
+ log.debug("login", "QR code displayed");
49
55
  qr.hint = "Scan with mobile QQ";
50
56
  generate(url, { small: true }, (ascii) => {
51
57
  qr.lines = ascii.split("\n").filter((line) => line.trim().length > 0);
52
58
  });
53
59
  requestRender?.();
54
- // Non-TUI mode has no overlay; show the URL.
55
60
  if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq QR URL: ${url}`, "info");
56
61
  },
57
62
  onQrExpired: () => {
63
+ log.warn("login", "QR code expired; refreshing");
58
64
  qr.hint = "QR code expired; refreshing…";
59
65
  requestRender?.();
60
66
  },
@@ -63,7 +69,6 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
63
69
  );
64
70
 
65
71
  if (ctx.mode !== "tui") {
66
- // Non-TUI: no overlay or cancel affordance; wait for the scan.
67
72
  ctx.ui.notify("pi-qq: waiting for mobile QQ scan…", "info");
68
73
  return;
69
74
  }
@@ -89,7 +94,6 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
89
94
  };
90
95
  })
91
96
  .then(() => {
92
- // Overlay closed by user; success/failure paths already called finish().
93
97
  if (!settled) finish();
94
98
  });
95
99
  });
@@ -1,25 +1,14 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
- import { ReplyBudget } from "./reply-budget";
3
- import { log } from "./logger";
2
+ import { ReplyBudget } from "../quota/reply-quota";
3
+ import { log } from "../infra/file-logger";
4
4
 
5
- /**
6
- * pi → QQ text relay (F4 non-streaming path): lightweight Markdown-to-plain
7
- * conversion, long-text chunking, and passive-reply budget with fallback.
8
- */
9
-
10
- /** Single-text limit; SDK splits around 5000 chars, leaving protocol headroom. */
11
5
  export const TEXT_CHUNK_LIMIT = 4500;
12
6
 
13
- /**
14
- * Markdown → plain text (features-v1.md F4: no Markdown permission by default).
15
- * Keep mobile readability; preserve fenced code content and drop only the fences.
16
- */
17
7
  export function markdownToPlain(md: string): string {
18
8
  const out: string[] = [];
19
9
  let inFence = false;
20
10
 
21
11
  for (const raw of md.split("\n")) {
22
- // Code fences: toggle state; drop fence lines, keep content as-is.
23
12
  if (/^\s*(```|~~~)/.test(raw)) {
24
13
  inFence = !inFence;
25
14
  continue;
@@ -31,7 +20,6 @@ export function markdownToPlain(md: string): string {
31
20
 
32
21
  let t = raw;
33
22
 
34
- // Tables: drop separator rows; strip edge pipes and trim data rows.
35
23
  if (/^\s*\|?[\s:|-]+\|?\s*$/.test(t) && t.includes("-") && t.includes("|")) {
36
24
  continue;
37
25
  }
@@ -42,7 +30,6 @@ export function markdownToPlain(md: string): string {
42
30
  .trim();
43
31
  }
44
32
 
45
- // Headings / quotes / horizontal rules
46
33
  t = t.replace(/^\s{0,3}#{1,6}\s+/, "");
47
34
  t = t.replace(/^\s{0,3}>\s?/, "");
48
35
  if (/^\s{0,3}([-*_]\s*){3,}$/.test(t)) {
@@ -50,13 +37,10 @@ export function markdownToPlain(md: string): string {
50
37
  continue;
51
38
  }
52
39
 
53
- // Images: keep alt text
54
40
  t = t.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
55
- // Links: text (url); keep only url when text equals url
56
41
  t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, url: string) =>
57
42
  text === url ? url : `${text}(${url})`,
58
43
  );
59
- // Emphasis / inline code / strikethrough
60
44
  t = t.replace(/\*\*([^*]+)\*\*/g, "$1");
61
45
  t = t.replace(/__([^_]+)__/g, "$1");
62
46
  t = t.replace(/`([^`]+)`/g, "$1");
@@ -64,7 +48,6 @@ export function markdownToPlain(md: string): string {
64
48
  t = t.replace(/\*([^*\n]+)\*/g, "$1");
65
49
  t = t.replace(/(?<![A-Za-z0-9_])_([^_\n]+)_(?![A-Za-z0-9_])/g, "$1");
66
50
 
67
- // Unordered lists → •; ordered lists unchanged
68
51
  t = t.replace(/^(\s*)[-*+]\s+/, "$1• ");
69
52
 
70
53
  out.push(t);
@@ -76,16 +59,13 @@ export function markdownToPlain(md: string): string {
76
59
  .trim();
77
60
  }
78
61
 
79
- /**
80
- * Chunk long text at newlines when possible; hard-cut when there is no newline.
81
- */
82
62
  export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
83
63
  if (text.length <= limit) return [text];
84
64
  const chunks: string[] = [];
85
65
  let rest = text;
86
66
  while (rest.length > limit) {
87
67
  let cut = rest.lastIndexOf("\n", limit);
88
- cut = cut <= 0 ? limit : cut + 1; // +1 keeps the newline at the end of the chunk
68
+ cut = cut <= 0 ? limit : cut + 1;
89
69
  chunks.push(rest.slice(0, cut));
90
70
  rest = rest.slice(cut);
91
71
  }
@@ -93,22 +73,12 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
93
73
  return chunks;
94
74
  }
95
75
 
96
- /** Send-channel dependencies: budget, fallback recipient, warning sink. */
97
76
  export interface ReplyChannel {
98
77
  budget: ReplyBudget;
99
- /** Bound user openid: fallback recipient for proactive sends. */
100
78
  boundOpenid: string;
101
79
  onWarn?: (msg: string) => void;
102
80
  }
103
81
 
104
- /**
105
- * Send one reply (auto-chunked, one budget ticket per chunk).
106
- * A failed passive send retries once as proactive.
107
- *
108
- * When QQBot is constructed with markdownSupport=true, the SDK's sendText
109
- * automatically uses msg_type=2 (markdown); callers only decide whether the
110
- * payload keeps Markdown, with no separate sendMarkdown path needed here.
111
- */
112
82
  export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
113
83
  for (const chunk of chunkText(text)) {
114
84
  const { mode, openid, msgId } = ch.budget.acquire();
@@ -134,7 +104,6 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
134
104
  err,
135
105
  });
136
106
  if (mode === "passive") {
137
- // Passive failure (e.g. stale msgId) → retry once proactively.
138
107
  try {
139
108
  log.warn("outbound", "passive send failed; retrying proactively", { targetId: ch.boundOpenid });
140
109
  await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
@@ -1,5 +1,3 @@
1
- /** qrcode-terminal has no bundled types (CJS); declare only the API we use. */
2
1
  declare module "qrcode-terminal" {
3
2
  export function generate(text: string, options?: { small?: boolean }, cb?: (ascii: string) => void): void;
4
- export function setErrorLevel(level: number): void;
5
3
  }
@@ -1,6 +1,6 @@
1
- import type { BudgetSnapshot } from "./reply-budget";
1
+ import type { BudgetSnapshot } from "./reply-quota";
2
2
 
3
- export interface BudgetTarget {
3
+ interface BudgetTarget {
4
4
  openid: string;
5
5
  msgId: string;
6
6
  arrivedAt: number;
@@ -10,7 +10,6 @@ function mask(value: string): string {
10
10
  return `${value.slice(0, 8)}…`;
11
11
  }
12
12
 
13
- /** Render `/qq-test-budget` output lines; pure function for tests. */
14
13
  export function formatBudgetStatus(
15
14
  snapshot: BudgetSnapshot,
16
15
  last: BudgetTarget | undefined,
@@ -1,20 +1,10 @@
1
1
  import { ReplyLimiter } from "@tencent-connect/qqbot-nodejs/protocol";
2
2
 
3
- /**
4
- * Passive reply budget (features-v1.md §3).
5
- *
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
- */
10
-
11
3
  export type ReplyMode = "passive" | "proactive";
12
4
 
13
5
  export interface AcquireResult {
14
6
  mode: ReplyMode;
15
- /** Sender of the latest inbound message; the caller falls back to the bound openid. */
16
7
  openid?: string;
17
- /** Present when mode=passive. */
18
8
  msgId?: string;
19
9
  }
20
10
 
@@ -27,9 +17,7 @@ export interface BudgetSnapshot {
27
17
  remaining: number;
28
18
  totalReplies: number;
29
19
  trackedMessages: number;
30
- /** Stream bubbles created for the current msgId (diagnostic only, not used by acquire). */
31
20
  streamBubbles: number;
32
- /** Total stream bubbles in this process. */
33
21
  streamBubblesTotal: number;
34
22
  }
35
23
 
@@ -46,7 +34,6 @@ export class ReplyBudget {
46
34
  this.freshMs = opts?.freshMs ?? 5 * 60_000;
47
35
  }
48
36
 
49
- /** Called on inbound: update the passive target and freshness start. */
50
37
  observeInbound(openid: string, msgId: string, now = Date.now()): void {
51
38
  if (this.last?.msgId !== msgId) {
52
39
  this.streamMsgId = msgId;
@@ -55,15 +42,10 @@ export class ReplyBudget {
55
42
  this.last = { openid, msgId, arrivedAt: now };
56
43
  }
57
44
 
58
- /** Latest inbound target (diagnostics/passive sends). */
59
45
  get lastTarget(): { openid: string; msgId: string; arrivedAt: number } | undefined {
60
46
  return this.last;
61
47
  }
62
48
 
63
- /**
64
- * Pick the send mode for the next message. Passive only checks; callers must
65
- * call commitPassive() after a successful passive send.
66
- */
67
49
  acquire(now = Date.now()): AcquireResult {
68
50
  const last = this.last;
69
51
  if (!last) return { mode: "proactive" };
@@ -74,12 +56,10 @@ export class ReplyBudget {
74
56
  return { mode: "proactive", openid: last.openid };
75
57
  }
76
58
 
77
- /** Record a successful passive send. */
78
59
  commitPassive(msgId: string): void {
79
60
  this.limiter.record(msgId);
80
61
  }
81
62
 
82
- /** Diagnostic: record one new stream bubble (does not affect passive limits). */
83
63
  noteStreamBubble(msgId: string): void {
84
64
  if (this.streamMsgId !== msgId) {
85
65
  this.streamMsgId = msgId;
@@ -89,7 +69,6 @@ export class ReplyBudget {
89
69
  this.streamBubblesTotal += 1;
90
70
  }
91
71
 
92
- /** Diagnostic snapshot: passive budget, target freshness, and send counts. */
93
72
  snapshot(now = Date.now()): BudgetSnapshot {
94
73
  const config = this.limiter.getConfig();
95
74
  const stats = this.limiter.getStats();