@chen_hu_hu/pi-qq 1.2.3 → 1.3.1

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 (35) hide show
  1. package/README-zh.md +76 -46
  2. package/README.md +79 -49
  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 +189 -0
  8. package/doc/delivery-v3.md +189 -0
  9. package/index.ts +66 -156
  10. package/package.json +6 -3
  11. package/src/{download.ts → attachments/attachment-download.ts} +1 -4
  12. package/src/attachments/attachment-failure.ts +12 -0
  13. package/src/{files.ts → attachments/file-attachments.ts} +19 -33
  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 -31
  17. package/src/infra/settings.ts +103 -0
  18. package/src/{bot.ts → qq/qq-bot.ts} +6 -31
  19. package/src/qq/qq-diagnostics.ts +129 -0
  20. package/src/{inbound.ts → qq/qq-message-handler.ts} +58 -94
  21. package/src/{login.ts → qq/qr-login.ts} +24 -17
  22. package/src/{outbound.ts → qq/reply-sender.ts} +7 -37
  23. package/src/qrcode-terminal.d.ts +0 -2
  24. package/src/{budget-status.ts → quota/reply-quota-report.ts} +2 -3
  25. package/src/{reply-budget.ts → quota/reply-quota.ts} +0 -21
  26. package/src/relay/run-stream-relay.ts +576 -0
  27. package/src/relay/stream-block-format.ts +117 -0
  28. package/src/{append-stream.ts → relay/stream-session.ts} +46 -29
  29. package/doc/features-v1.md +0 -239
  30. package/doc/features-v2.md +0 -210
  31. package/doc/plan-v1.md +0 -190
  32. package/doc/plan-v2.md +0 -332
  33. package/src/config.ts +0 -82
  34. package/src/images.ts +0 -149
  35. package/src/run-feedback.ts +0 -409
@@ -1,50 +1,38 @@
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
+ import { formatAttachmentFailures, type AttachmentFailure } from "../attachments/attachment-failure";
5
6
  import {
6
- buildImageMessageContent,
7
- formatImageFailures,
8
- isImageAttachment,
9
- resolveInboundImages,
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
- */
7
+ formatAttachmentPrompt,
8
+ saveInboundFiles,
9
+ sessionUploadDir,
10
+ type SavedFile,
11
+ } from "../attachments/file-attachments";
12
+ import { log } from "../infra/file-logger";
13
+ import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
21
14
 
22
15
  export interface InboundDeps {
23
16
  pi: ExtensionAPI;
24
- /** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
25
17
  ctx: ExtensionContext;
26
18
  budget: ReplyBudget;
27
- /** Read settings live so changes apply immediately. */
28
19
  getAllowedOpenid: () => string | undefined;
29
- getBoundOpenid: () => string | undefined;
30
20
  getDeliverAs: () => "steer" | "followUp";
31
- getImageMaxSize: () => number;
32
21
  getFileMaxSize: () => number;
33
- /** Test override; defaults to saveInboundFiles. */
34
22
  saveFiles?: typeof saveInboundFiles;
35
23
  getStatusLines: () => string[];
36
24
  onWarn: (msg: string) => void;
37
- /** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
38
25
  markQQTrigger: (openid: string, msgId: string) => void;
26
+ waitForEnd?: () => Promise<void>;
27
+ onStop?: () => void;
39
28
  }
40
29
 
41
30
  export function createInboundHandler(deps: InboundDeps) {
42
- // F10: files uploaded without text wait for the next text/voice instruction.
43
- let pendingFiles: SavedFile[] = [];
44
- const takePendingFiles = (): SavedFile[] => {
45
- const files = pendingFiles;
46
- pendingFiles = [];
47
- return files;
31
+ let pendingAttachments: SavedFile[] = [];
32
+ const takePendingAttachments = (): SavedFile[] => {
33
+ const attachments = pendingAttachments;
34
+ pendingAttachments = [];
35
+ return attachments;
48
36
  };
49
37
 
50
38
  return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
@@ -77,7 +65,6 @@ export function createInboundHandler(deps: InboundDeps) {
77
65
  return;
78
66
  }
79
67
 
80
- // Record passive reply target/freshness for outbound budget.
81
68
  deps.budget.observeInbound(msg.senderId, msg.messageId);
82
69
  log.info("inbound", "message received", {
83
70
  messageId: msg.messageId,
@@ -88,32 +75,32 @@ export function createInboundHandler(deps: InboundDeps) {
88
75
 
89
76
  const channel: ReplyChannel = {
90
77
  budget: deps.budget,
91
- boundOpenid: deps.getBoundOpenid() ?? msg.senderId,
78
+ boundOpenid: deps.getAllowedOpenid() ?? msg.senderId,
92
79
  onWarn: deps.onWarn,
93
80
  };
94
81
  const reply = (text: string) => sendReply(bot, text, channel);
95
82
  const saveFiles = deps.saveFiles ?? saveInboundFiles;
96
83
 
97
- const text = (msg.content ?? "").trim();
98
- if (text.startsWith("/")) {
99
- const command = text.split(/\s+/)[0];
84
+ const contentText = (msg.content ?? "").trim();
85
+ if (contentText.startsWith("/")) {
86
+ const command = contentText.split(/\s+/)[0];
100
87
  log.info("inbound", "QQ command", { command });
101
- if (command === "/new" && deps.ctx.isIdle() && pendingFiles.length > 0) {
102
- log.info("inbound", "cleared pending files for /new", { count: pendingFiles.length });
103
- pendingFiles = [];
88
+ if (command === "/new" && deps.ctx.isIdle() && pendingAttachments.length > 0) {
89
+ log.info("inbound", "cleared pending attachments for /new", { count: pendingAttachments.length });
90
+ pendingAttachments = [];
104
91
  }
105
- await handleCommand(text, reply, deps);
92
+ await handleCommand(contentText, reply, deps);
106
93
  return;
107
94
  }
108
95
 
109
96
  const attachments = msg.attachments ?? [];
110
- if (!text && attachments.length === 0) {
97
+ if (!contentText && attachments.length === 0) {
111
98
  log.warn("inbound", "unsupported message: no text and no attachments", { messageId: msg.messageId });
112
99
  await reply("Unsupported message type.");
113
100
  return;
114
101
  }
115
102
 
116
- // F8: voice messages use QQ built-in ASR; never download or save the audio.
103
+ let text = contentText;
117
104
  const voiceAttachments = attachments.filter(isVoiceAttachment);
118
105
  if (voiceAttachments.length > 0) {
119
106
  const transcript = resolveVoiceTranscript(voiceAttachments);
@@ -123,53 +110,31 @@ export function createInboundHandler(deps: InboundDeps) {
123
110
  asrLength: transcript?.length ?? 0,
124
111
  });
125
112
  if (!transcript) {
126
- log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
127
- await reply("Could not transcribe this voice message; please resend or type it.");
128
- return;
129
- }
130
- log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
131
- const pending = takePendingFiles();
132
- const promptText = formatFilePrompt(pending, transcript);
133
- deps.markQQTrigger(msg.senderId, msg.messageId);
134
- deps.pi.sendUserMessage(promptText, { deliverAs: deps.getDeliverAs() });
135
- log.info("inbound", "voice sent to pi", {
136
- messageId: msg.messageId,
137
- asrLength: transcript.length,
138
- pendingFiles: pending.length,
139
- });
140
- return;
141
- }
142
-
143
- // F3: images become ImageContent; other attachments are saved and referenced by path.
144
- const imageAttachments = attachments.filter(isImageAttachment);
145
- const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
146
- const failures: Array<{ filename: string; reason: string }> = [];
147
-
148
- let images: ImageContentLike[] = [];
149
- if (imageAttachments.length > 0) {
150
- const supportsImages = deps.ctx.model?.input.includes("image") ?? false;
151
- if (!supportsImages) {
152
- log.warn("inbound", "model does not support images; skipped", {
153
- messageId: msg.messageId,
154
- count: imageAttachments.length,
155
- });
156
- await reply(`Model does not support image input; skipped ${imageAttachments.length} image(s).`);
113
+ if (!contentText) {
114
+ log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
115
+ await reply("Could not transcribe this voice message; please resend or type it.");
116
+ return;
117
+ }
118
+ log.warn("inbound", "voice ASR returned no text; using text content", { messageId: msg.messageId });
157
119
  } else {
158
- const result = await resolveInboundImages(imageAttachments, deps.getImageMaxSize());
159
- images = result.images;
160
- failures.push(...result.failures);
120
+ log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
121
+ text = contentText ? `${contentText}\n${transcript}` : transcript;
161
122
  }
162
123
  }
163
124
 
125
+ // Voice attachments are handled above; all other attachments are stored as files.
126
+ const attachmentsToSave = attachments.filter((attachment) => !isVoiceAttachment(attachment));
127
+ const failures: AttachmentFailure[] = [];
128
+
164
129
  let files: SavedFile[] = [];
165
- if (fileAttachments.length > 0) {
130
+ if (attachmentsToSave.length > 0) {
166
131
  const uploadDir = sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId());
167
- log.debug("inbound", "saving files", {
132
+ log.debug("inbound", "saving attachments", {
168
133
  messageId: msg.messageId,
169
- count: fileAttachments.length,
134
+ count: attachmentsToSave.length,
170
135
  uploadDir,
171
136
  });
172
- const result = await saveFiles(fileAttachments, {
137
+ const result = await saveFiles(attachmentsToSave, {
173
138
  maxSize: deps.getFileMaxSize(),
174
139
  uploadDir,
175
140
  });
@@ -181,11 +146,11 @@ export function createInboundHandler(deps: InboundDeps) {
181
146
  log.warn("inbound", "attachment failure summary", {
182
147
  messageId: msg.messageId,
183
148
  failures,
184
- successCount: images.length + files.length,
149
+ successCount: files.length,
185
150
  });
186
- await reply(formatImageFailures(failures, images.length + files.length));
151
+ await reply(formatAttachmentFailures(failures, files.length));
187
152
  }
188
- if (!text && images.length === 0 && files.length === 0) {
153
+ if (!text && files.length === 0) {
189
154
  log.warn("inbound", "no injectable content after attachment handling", {
190
155
  messageId: msg.messageId,
191
156
  failures: failures.length,
@@ -193,29 +158,27 @@ export function createInboundHandler(deps: InboundDeps) {
193
158
  return;
194
159
  }
195
160
 
196
- // F10: a file-only message waits for the next text/voice instruction.
197
- if (!text && images.length === 0 && files.length > 0) {
198
- pendingFiles.push(...files);
199
- log.info("inbound", "files pending for instruction", {
161
+ if (!text && files.length > 0) {
162
+ pendingAttachments.push(...files);
163
+ log.info("inbound", "attachments pending for instruction", {
200
164
  messageId: msg.messageId,
201
165
  count: files.length,
202
- pendingCount: pendingFiles.length,
166
+ pendingCount: pendingAttachments.length,
203
167
  });
204
168
  return;
205
169
  }
206
170
 
207
- // F7: mark a QQ-triggered run; do not send a start confirmation.
208
171
  deps.markQQTrigger(msg.senderId, msg.messageId);
209
- const pending = text ? takePendingFiles() : [];
172
+ const pending = text ? takePendingAttachments() : [];
210
173
  const promptFiles = [...pending, ...files];
211
- const promptText = formatFilePrompt(promptFiles, text);
212
- deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
174
+ const promptText = formatAttachmentPrompt(promptFiles, text, deps.ctx.cwd);
175
+ deps.pi.sendUserMessage(promptText, { deliverAs: deps.getDeliverAs() });
213
176
  log.info("inbound", "sent to pi", {
214
177
  messageId: msg.messageId,
215
178
  textLength: text.length,
216
- images: images.length,
217
- files: promptFiles.length,
218
- pendingFiles: pending.length,
179
+ voice: voiceAttachments.length > 0,
180
+ attachments: promptFiles.length,
181
+ pendingAttachments: pending.length,
219
182
  deliverAs: deps.getDeliverAs(),
220
183
  });
221
184
  };
@@ -238,10 +201,12 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
238
201
  );
239
202
  break;
240
203
  case "/stop":
204
+ deps.onStop?.();
241
205
  if (deps.ctx.isIdle()) {
242
206
  await reply("No task is running.");
243
207
  } else {
244
208
  deps.ctx.abort();
209
+ await deps.waitForEnd?.();
245
210
  await reply("Abort requested.");
246
211
  }
247
212
  break;
@@ -261,7 +226,6 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
261
226
  await reply("Task is running; use /stop before resetting.");
262
227
  } else {
263
228
  await reply("Resetting the session…");
264
- // Built-in /new is interactive-only; dispatch the extension command instead.
265
229
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
266
230
  }
267
231
  break;
@@ -1,29 +1,22 @@
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;
25
18
 
26
- return await new Promise<QrLoginResult | undefined>((resolve) => {
19
+ return new Promise<QrLoginResult | undefined>((resolve) => {
27
20
  let settled = false;
28
21
  const finish = (result?: QrLoginResult) => {
29
22
  if (settled) return;
@@ -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
  }
@@ -81,6 +86,9 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
81
86
  },
82
87
  handleInput(data: string): void {
83
88
  if (keybindings.matches(data, "tui.select.cancel") || data === "\x1b") {
89
+ // Mark the login settled before aborting: the connector reports an
90
+ // AbortError through onFailure, which must not look like a failure.
91
+ finish();
84
92
  ac.abort();
85
93
  done();
86
94
  }
@@ -89,7 +97,6 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
89
97
  };
90
98
  })
91
99
  .then(() => {
92
- // Overlay closed by user; success/failure paths already called finish().
93
100
  if (!settled) finish();
94
101
  });
95
102
  });
@@ -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,14 @@ 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
- if (text.length <= limit) return [text];
63
+ const max = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : TEXT_CHUNK_LIMIT;
64
+ if (text.length <= max) return [text];
84
65
  const chunks: string[] = [];
85
66
  let rest = text;
86
- while (rest.length > limit) {
87
- let cut = rest.lastIndexOf("\n", limit);
88
- cut = cut <= 0 ? limit : cut + 1; // +1 keeps the newline at the end of the chunk
67
+ while (rest.length > max) {
68
+ let cut = rest.lastIndexOf("\n", max);
69
+ cut = cut <= 0 ? max : cut + 1;
89
70
  chunks.push(rest.slice(0, cut));
90
71
  rest = rest.slice(cut);
91
72
  }
@@ -93,22 +74,12 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
93
74
  return chunks;
94
75
  }
95
76
 
96
- /** Send-channel dependencies: budget, fallback recipient, warning sink. */
97
77
  export interface ReplyChannel {
98
78
  budget: ReplyBudget;
99
- /** Bound user openid: fallback recipient for proactive sends. */
100
79
  boundOpenid: string;
101
80
  onWarn?: (msg: string) => void;
102
81
  }
103
82
 
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
83
  export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
113
84
  for (const chunk of chunkText(text)) {
114
85
  const { mode, openid, msgId } = ch.budget.acquire();
@@ -134,7 +105,6 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
134
105
  err,
135
106
  });
136
107
  if (mode === "passive") {
137
- // Passive failure (e.g. stale msgId) → retry once proactively.
138
108
  try {
139
109
  log.warn("outbound", "passive send failed; retrying proactively", { targetId: ch.boundOpenid });
140
110
  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();