@chen_hu_hu/pi-qq 1.3.2 → 1.3.4

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.
@@ -2,12 +2,14 @@ import { readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { normalizeLogLevel, type LogLevel } from "./file-logger";
5
+ import { DEFAULT_LANGUAGE, getLanguage, isLanguage, translate, type Language } from "./i18n";
5
6
 
6
7
  export interface PiQQSettings {
7
8
  thinkingRelay?: boolean;
8
9
  deliverAs?: "steer" | "followUp";
9
10
  fileMaxSize?: number;
10
11
  logLevel?: LogLevel;
12
+ language?: Language;
11
13
  debug?: boolean;
12
14
  }
13
15
 
@@ -43,36 +45,47 @@ export function parseConfig(raw: unknown): ReadConfigResult {
43
45
  if (!isRecord(raw)) {
44
46
  return {
45
47
  config: {},
46
- error: `Invalid config file (${CONFIG_PATH}): expected a JSON object; using defaults.`,
48
+ error: translate(getLanguage(), "settings.invalidRoot", { path: CONFIG_PATH }),
47
49
  };
48
50
  }
49
51
 
52
+ const language = isLanguage(raw.language) ? raw.language : getLanguage();
50
53
  const config: PiQQSettings = {};
51
54
  const errors: string[] = [];
52
55
 
56
+ if (raw.language !== undefined) {
57
+ if (isLanguage(raw.language)) config.language = raw.language;
58
+ else errors.push(translate(language, "settings.language"));
59
+ }
53
60
  if (raw.thinkingRelay !== undefined) {
54
61
  if (typeof raw.thinkingRelay === "boolean") config.thinkingRelay = raw.thinkingRelay;
55
- else errors.push("thinkingRelay must be a boolean");
62
+ else errors.push(translate(language, "settings.thinkingRelay"));
56
63
  }
57
64
  if (raw.deliverAs !== undefined) {
58
65
  if (raw.deliverAs === "steer" || raw.deliverAs === "followUp") config.deliverAs = raw.deliverAs;
59
- else errors.push('deliverAs must be "steer" or "followUp"');
66
+ else errors.push(translate(language, "settings.deliverAs"));
60
67
  }
61
68
  if (raw.fileMaxSize !== undefined) {
62
69
  if (isPositiveSize(raw.fileMaxSize)) config.fileMaxSize = raw.fileMaxSize;
63
- else errors.push("fileMaxSize must be a positive finite number");
70
+ else errors.push(translate(language, "settings.fileMaxSize"));
64
71
  }
65
72
  if (raw.logLevel !== undefined) {
66
73
  if (isLogLevel(raw.logLevel)) config.logLevel = raw.logLevel;
67
- else errors.push('logLevel must be "silent", "error", "warn", "info", or "debug"');
74
+ else errors.push(translate(language, "settings.logLevel"));
68
75
  }
69
76
  if (raw.debug !== undefined) {
70
77
  if (typeof raw.debug === "boolean") config.debug = raw.debug;
71
- else errors.push("debug must be a boolean");
78
+ else errors.push(translate(language, "settings.debug"));
72
79
  }
73
80
 
74
81
  return errors.length > 0
75
- ? { config, error: `Invalid config file (${CONFIG_PATH}): ${errors.join("; ")}; invalid values were ignored.` }
82
+ ? {
83
+ config,
84
+ error: translate(language, "settings.invalidFields", {
85
+ path: CONFIG_PATH,
86
+ errors: errors.join("; "),
87
+ }),
88
+ }
76
89
  : { config };
77
90
  }
78
91
 
@@ -86,7 +99,13 @@ export function readConfig(): ReadConfigResult {
86
99
  try {
87
100
  return parseConfig(JSON.parse(raw));
88
101
  } catch (e) {
89
- return { config: {}, error: `Failed to parse config file (${CONFIG_PATH}): ${(e as Error).message}` };
102
+ return {
103
+ config: {},
104
+ error: translate(getLanguage(), "settings.parseFailed", {
105
+ path: CONFIG_PATH,
106
+ message: (e as Error).message,
107
+ }),
108
+ };
90
109
  }
91
110
  }
92
111
 
@@ -99,5 +118,6 @@ export function getSettings(config: PiQQSettings): ResolvedSettings {
99
118
  deliverAs: config.deliverAs ?? "steer",
100
119
  fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
101
120
  logLevel,
121
+ language: config.language ?? DEFAULT_LANGUAGE,
102
122
  };
103
123
  }
@@ -2,6 +2,7 @@ import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
2
2
  import type { AttachmentFailure } from "../attachments/attachment-failure";
3
3
  import { saveInboundFiles, type SavedFile } from "../attachments/file-attachments";
4
4
  import { log } from "../infra/file-logger";
5
+ import { t } from "../infra/i18n";
5
6
  import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
6
7
 
7
8
  export interface ResolveInboundOptions {
@@ -45,7 +46,7 @@ export async function resolveInboundContent(
45
46
  log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
46
47
  return {
47
48
  status: "rejected",
48
- reply: "Could not transcribe this voice message; please resend or type it.",
49
+ reply: t("inbound.voiceFailed"),
49
50
  };
50
51
  }
51
52
  log.warn("inbound", "voice ASR returned no text; using text content", { messageId: msg.messageId });
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { t } from "../infra/i18n";
2
3
 
3
4
  /** The slice of ExtensionContext used by QQ inbound handling. */
4
5
  export interface InboundContext {
@@ -15,60 +16,85 @@ export interface InboundCommandDeps {
15
16
  pi: InboundPi;
16
17
  ctx: InboundContext;
17
18
  getStatusLines: () => string[];
19
+ getLastMessage?: () => string | undefined;
18
20
  onStop?: () => void;
19
21
  waitForEnd?: () => Promise<void>;
20
22
  }
21
23
 
24
+ export interface InboundCommandExtras {
25
+ streamReply?: (text: string) => Promise<void>;
26
+ restartPush?: () => void;
27
+ }
28
+
22
29
  export async function handleInboundCommand(
23
30
  text: string,
24
31
  reply: (t: string) => Promise<void>,
25
32
  deps: InboundCommandDeps,
33
+ extras: InboundCommandExtras = {},
26
34
  ): Promise<void> {
27
35
  const cmd = text.split(/\s+/)[0];
28
36
  switch (cmd) {
29
37
  case "/help":
30
38
  await reply(
31
39
  [
32
- "pi-qq commands:",
33
- "• /stop — abort the current task",
34
- "• /compact — compact the context",
35
- "• /status — show status",
36
- "• /new — reset the session",
37
- "• /help — this help",
38
- "Other text is sent to pi.",
40
+ t("commands.help.title"),
41
+ t("commands.help.stop"),
42
+ t("commands.help.compact"),
43
+ t("commands.help.status"),
44
+ t("commands.help.last"),
45
+ t("commands.help.new"),
46
+ t("commands.help.help"),
47
+ t("commands.help.other"),
39
48
  ].join("\n"),
40
49
  );
41
50
  break;
42
51
  case "/stop":
43
52
  deps.onStop?.();
44
53
  if (deps.ctx.isIdle()) {
45
- await reply("No task is running.");
54
+ await reply(t("commands.stop.none"));
46
55
  } else {
47
56
  deps.ctx.abort();
48
57
  await deps.waitForEnd?.();
49
- await reply("Abort requested.");
58
+ await reply(t("commands.stop.abort"));
50
59
  }
51
60
  break;
52
61
  case "/compact":
53
62
  if (deps.ctx.isIdle()) {
54
63
  deps.ctx.compact();
55
- await reply("Context compaction triggered.");
64
+ await reply(t("commands.compact.done"));
56
65
  } else {
57
- await reply("Task is running; use /stop before /compact.");
66
+ await reply(t("commands.compact.busy"));
58
67
  }
59
68
  break;
60
69
  case "/status":
61
70
  await reply(deps.getStatusLines().join("\n"));
62
71
  break;
72
+ case "/last": {
73
+ if (!deps.ctx.isIdle()) {
74
+ extras.restartPush?.();
75
+ } else {
76
+ const text = deps.getLastMessage?.();
77
+ if (text) {
78
+ if (extras.streamReply) {
79
+ await extras.streamReply(text);
80
+ } else {
81
+ await reply(text);
82
+ }
83
+ } else {
84
+ await reply(t("commands.last.none"));
85
+ }
86
+ }
87
+ break;
88
+ }
63
89
  case "/new":
64
90
  if (!deps.ctx.isIdle()) {
65
- await reply("Task is running; use /stop before resetting.");
91
+ await reply(t("commands.new.busy"));
66
92
  } else {
67
- await reply("Resetting the session…");
93
+ await reply(t("commands.new.resetting"));
68
94
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
69
95
  }
70
96
  break;
71
97
  default:
72
- await reply(`Unknown command ${cmd}; use /help.`);
98
+ await reply(t("commands.unknown", { cmd }));
73
99
  }
74
100
  }
package/src/qq/qq-bot.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
10
10
  import type { Credentials } from "../infra/settings";
11
11
  import { log, sdkLogger } from "../infra/file-logger";
12
+ import { t } from "../infra/i18n";
12
13
 
13
14
  export type BotState = "stopped" | "starting" | "connected" | "reconnecting" | "blocked";
14
15
 
@@ -91,15 +92,11 @@ export function startBot(opts: StartBotOptions): RunningBot {
91
92
  const code = (err as { code?: string }).code;
92
93
  if (code === GatewayErrorCode.FATAL_CLOSE) {
93
94
  const closeCode = (err as { closeCode?: number }).closeCode;
94
- report(
95
- "blocked",
96
- `Connection closed by the server (${closeCode ?? "unknown"}, 4914=offline/sandbox, 4915=banned). ` +
97
- `Check the bot status on the QQ Open Platform, or run /qq-login again.`,
98
- );
95
+ report("blocked", t("bot.fatalClose", { code: closeCode ?? "unknown" }));
99
96
  } else if (code === GatewayErrorCode.RETRY_EXHAUSTED) {
100
- report("stopped", `Reconnect budget exhausted: ${(err as Error).message}; run /qq-login to retry.`);
97
+ report("stopped", t("bot.retryExhausted", { message: (err as Error).message }));
101
98
  } else {
102
- report("stopped", `Startup failed: ${(err as Error).message}; check credentials and network.`);
99
+ report("stopped", t("bot.startupFailed", { message: (err as Error).message }));
103
100
  }
104
101
  });
105
102
 
@@ -3,6 +3,8 @@ import type { ReplyBudget } from "../quota/reply-quota";
3
3
  import { formatBudgetStatus } from "../quota/reply-quota-report";
4
4
  import { AppendStream } from "../relay/stream-session";
5
5
  import type { RunningBot } from "./qq-bot";
6
+ import { t } from "../infra/i18n";
7
+ import { thinkingHeader } from "../relay/stream-block-format";
6
8
 
7
9
  export interface QQDiagnosticsDeps {
8
10
  getRunning: () => RunningBot | undefined;
@@ -23,46 +25,46 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
23
25
  };
24
26
 
25
27
  pi.registerCommand("qq-test-budget", {
26
- description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
28
+ description: t("diagnostics.descBudget"),
27
29
  handler: async (_args, ctx) => {
28
30
  ctx.ui.notify(formatBudgetStatus(deps.budget.snapshot(), deps.budget.lastTarget).join("\n"), "info");
29
31
  },
30
32
  });
31
33
 
32
34
  pi.registerCommand("qq-test-md", {
33
- description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
35
+ description: t("diagnostics.descMd"),
34
36
  handler: async (args, ctx) => {
35
37
  const running = deps.getRunning();
36
38
  if (!running) {
37
- ctx.ui.notify("pi-qq is not connected.", "warning");
39
+ ctx.ui.notify(t("diagnostics.notConnected"), "warning");
38
40
  return;
39
41
  }
40
42
  const target = diagTarget();
41
43
  if (!target) {
42
- ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
44
+ ctx.ui.notify(t("diagnostics.noTarget"), "warning");
43
45
  return;
44
46
  }
45
47
  const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
46
48
  try {
47
49
  await running.bot.sendMarkdown(target, content);
48
- ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
50
+ ctx.ui.notify(t("diagnostics.mdSent"), "info");
49
51
  } catch (err) {
50
- ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
52
+ ctx.ui.notify(t("diagnostics.mdFailed", { message: (err as Error).message }), "error");
51
53
  }
52
54
  },
53
55
  });
54
56
 
55
57
  pi.registerCommand("qq-test-stream", {
56
- description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text) or resume probe",
58
+ description: t("diagnostics.descStream"),
57
59
  handler: async (args, ctx) => {
58
60
  const running = deps.getRunning();
59
61
  if (!running) {
60
- ctx.ui.notify("pi-qq is not connected.", "warning");
62
+ ctx.ui.notify(t("diagnostics.notConnected"), "warning");
61
63
  return;
62
64
  }
63
65
  const last = deps.budget.lastTarget;
64
66
  if (!last) {
65
- ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
67
+ ctx.ui.notify(t("diagnostics.streamNoTarget"), "warning");
66
68
  return;
67
69
  }
68
70
 
@@ -72,13 +74,13 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
72
74
  if (args?.trim() === "resume") {
73
75
  const first = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
74
76
  stream = first;
75
- await first.append("**Resume probe** frame 1\n");
77
+ await first.append(t("diagnostics.probeResumeFrame1"));
76
78
  await first.flush();
77
79
  const checkpoint = first.checkpoint();
78
80
  first.dispose();
79
81
  stream = undefined;
80
82
  if (!checkpoint?.streamMsgId) {
81
- ctx.ui.notify("Resume probe: frame 1 sent but stream_msg_id is missing; cannot resume.", "error");
83
+ ctx.ui.notify(t("diagnostics.resumeNoStream"), "error");
82
84
  return;
83
85
  }
84
86
  await sleep(800);
@@ -90,12 +92,15 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
90
92
  { resume: checkpoint },
91
93
  );
92
94
  stream = second;
93
- await second.append("frame 2 after resume\n");
95
+ await second.append(t("diagnostics.probeResumeFrame2"));
94
96
  await second.done();
95
97
  second.dispose();
96
98
  stream = undefined;
97
99
  ctx.ui.notify(
98
- `Resume probe: frame 2 sent with index ${checkpoint.index} and stream_msg_id ${checkpoint.streamMsgId}. Check whether both frames are in the same bubble.`,
100
+ t("diagnostics.resumeResult", {
101
+ index: checkpoint.index,
102
+ streamMsgId: checkpoint.streamMsgId,
103
+ }),
99
104
  "info",
100
105
  );
101
106
  return;
@@ -103,26 +108,28 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
103
108
 
104
109
  stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
105
110
  await stream.append(
106
- "**💭 思考**\n\nprobe thinking\nsecond line\n\n**💻 bash**\n\n`echo probe`\n\n```text\nprobe\n```\n",
111
+ `${thinkingHeader()}${t("diagnostics.probeThinking")}\n\n**💻 bash**\n\n\`echo probe\`\n\n\`\`\`text\n${t("diagnostics.probeCode")}\n\`\`\`\n`,
107
112
  );
108
113
  await sleep(1200);
109
- await stream.append("\n**Intermediate message**: first-turn reply.\n");
114
+ await stream.append(`\n${t("diagnostics.probeIntermediate")}\n`);
110
115
  await sleep(1200);
111
- await stream.append("\n**📖 read**\n\n`src/index.ts`\n\n```text\nprobe file\n```\n");
116
+ await stream.append(
117
+ `\n**📖 read**\n\n\`src/index.ts\`\n\n\`\`\`text\n${t("diagnostics.probeReadFile")}\n\`\`\`\n`,
118
+ );
112
119
  await sleep(800);
113
- await stream.append("\n**Final reply** (streamed append)");
114
- let doneNote = "DONE succeeded";
120
+ await stream.append(`\n${t("diagnostics.probeFinal")}`);
121
+ let doneNote = t("diagnostics.doneSucceeded");
115
122
  try {
116
123
  await stream.done();
117
124
  } catch (doneErr) {
118
- doneNote = `DONE rejected: ${(doneErr as Error).message}`;
125
+ doneNote = t("diagnostics.doneRejected", { message: (doneErr as Error).message });
119
126
  }
120
127
  stream.dispose();
121
128
  stream = undefined;
122
- ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
129
+ ctx.ui.notify(t("diagnostics.streamResult", { done: doneNote }), "info");
123
130
  } catch (err) {
124
131
  stream?.dispose();
125
- ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
132
+ ctx.ui.notify(t("diagnostics.streamFailed", { message: (err as Error).message }), "error");
126
133
  }
127
134
  },
128
135
  });
@@ -1,5 +1,5 @@
1
1
  import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
2
- import { sendReply, type ReplyChannel } from "./reply-sender";
2
+ import { sendReply, sendStreamReply, type ReplyChannel } from "./reply-sender";
3
3
  import type { ReplyBudget } from "../quota/reply-quota";
4
4
  import { formatAttachmentFailures } from "../attachments/attachment-failure";
5
5
  import {
@@ -9,6 +9,7 @@ import {
9
9
  type SavedFile,
10
10
  } from "../attachments/file-attachments";
11
11
  import { log } from "../infra/file-logger";
12
+ import { t } from "../infra/i18n";
12
13
  import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
13
14
  import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
14
15
 
@@ -18,6 +19,8 @@ export interface InboundDeps extends InboundCommandDeps {
18
19
  getDeliverAs: () => "steer" | "followUp";
19
20
  getFileMaxSize: () => number;
20
21
  saveFiles?: typeof saveInboundFiles;
22
+ streamReply?: typeof sendStreamReply;
23
+ repushCurrent: (openid: string, msgId: string) => boolean;
21
24
  onWarn: (msg: string) => void;
22
25
  markQQTrigger: (openid: string, msgId: string) => void;
23
26
  }
@@ -78,14 +81,34 @@ export function createInboundHandler(deps: InboundDeps) {
78
81
  log.info("inbound", "cleared pending attachments for /new", { count: pending.count });
79
82
  pending.clear();
80
83
  }
81
- await handleInboundCommand(contentText, reply, deps);
84
+ await handleInboundCommand(contentText, reply, deps, {
85
+ streamReply: async (text) => {
86
+ try {
87
+ await (deps.streamReply ?? sendStreamReply)(
88
+ bot,
89
+ text,
90
+ { openid: msg.senderId, msgId: msg.messageId },
91
+ deps.budget,
92
+ );
93
+ } catch (err) {
94
+ log.warn("inbound", "stream reply failed; falling back to text", {
95
+ messageId: msg.messageId,
96
+ err,
97
+ });
98
+ await reply(text);
99
+ }
100
+ },
101
+ restartPush: () => {
102
+ deps.repushCurrent(msg.senderId, msg.messageId);
103
+ },
104
+ });
82
105
  return;
83
106
  }
84
107
 
85
108
  const attachments = msg.attachments ?? [];
86
109
  if (!contentText && attachments.length === 0) {
87
110
  log.warn("inbound", "unsupported message: no text and no attachments", { messageId: msg.messageId });
88
- await reply("Unsupported message type.");
111
+ await reply(t("inbound.unsupported"));
89
112
  return;
90
113
  }
91
114
 
@@ -3,6 +3,7 @@ import { generate } from "qrcode-terminal";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import type { Credentials } from "../infra/settings";
5
5
  import { log } from "../infra/file-logger";
6
+ import { t } from "../infra/i18n";
6
7
 
7
8
  export interface QrLoginResult extends Credentials {
8
9
  userOpenid?: string;
@@ -12,7 +13,7 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
12
13
  const ac = new AbortController();
13
14
  log.info("login", "QR login started");
14
15
 
15
- const qr = { lines: [] as string[], hint: "Fetching QR code…" };
16
+ const qr = { lines: [] as string[], hint: t("login.fetchingQr") };
16
17
  let requestRender: (() => void) | undefined;
17
18
  let closeOverlay: (() => void) | undefined;
18
19
 
@@ -46,22 +47,22 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
46
47
  causeCode: cause && typeof cause === "object" ? (cause as NodeJS.ErrnoException).code : undefined,
47
48
  causeMessage: cause instanceof Error ? cause.message : undefined,
48
49
  });
49
- ctx.ui.notify("Error: QR login failed", "error");
50
+ ctx.ui.notify(t("login.failed"), "error");
50
51
  finish();
51
52
  closeOverlay?.();
52
53
  },
53
54
  onQrDisplayed: (url) => {
54
55
  log.debug("login", "QR code displayed");
55
- qr.hint = "Scan with mobile QQ";
56
+ qr.hint = t("login.scan");
56
57
  generate(url, { small: true }, (ascii) => {
57
58
  qr.lines = ascii.split("\n").filter((line) => line.trim().length > 0);
58
59
  });
59
60
  requestRender?.();
60
- if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq QR URL: ${url}`, "info");
61
+ if (ctx.mode !== "tui") ctx.ui.notify(t("login.qrUrl", { url }), "info");
61
62
  },
62
63
  onQrExpired: () => {
63
64
  log.warn("login", "QR code expired; refreshing");
64
- qr.hint = "QR code expired; refreshing…";
65
+ qr.hint = t("login.expired");
65
66
  requestRender?.();
66
67
  },
67
68
  },
@@ -69,7 +70,7 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
69
70
  );
70
71
 
71
72
  if (ctx.mode !== "tui") {
72
- ctx.ui.notify("pi-qq: waiting for mobile QQ scan…", "info");
73
+ ctx.ui.notify(t("login.waiting"), "info");
73
74
  return;
74
75
  }
75
76
 
@@ -79,8 +80,8 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
79
80
  requestRender = () => tui.requestRender();
80
81
  return {
81
82
  render(width: number): string[] {
82
- const lines = qr.lines.length > 0 ? qr.lines : ["(fetching QR code…)"];
83
- return [...lines, "", qr.hint, theme.fg("dim", "Esc to cancel")].map((line) =>
83
+ const lines = qr.lines.length > 0 ? qr.lines : [t("login.fetchingQrShort")];
84
+ return [...lines, "", qr.hint, theme.fg("dim", t("login.cancel"))].map((line) =>
84
85
  line.length > width ? line.slice(0, width) : line,
85
86
  );
86
87
  },
@@ -1,6 +1,8 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { ReplyBudget } from "../quota/reply-quota";
3
+ import { AppendStream } from "../relay/stream-session";
3
4
  import { log } from "../infra/file-logger";
5
+ import { t } from "../infra/i18n";
4
6
 
5
7
  export const TEXT_CHUNK_LIMIT = 4500;
6
8
 
@@ -80,6 +82,28 @@ export interface ReplyChannel {
80
82
  onWarn?: (msg: string) => void;
81
83
  }
82
84
 
85
+ export interface StreamTarget {
86
+ openid: string;
87
+ msgId: string;
88
+ }
89
+
90
+ /** Send a complete message as one new stream bubble. */
91
+ export async function sendStreamReply(
92
+ bot: QQBot,
93
+ text: string,
94
+ target: StreamTarget,
95
+ budget?: ReplyBudget,
96
+ ): Promise<void> {
97
+ const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
98
+ budget?.noteStreamBubble(target.msgId);
99
+ try {
100
+ await stream.append(text);
101
+ await stream.done();
102
+ } finally {
103
+ stream.dispose();
104
+ }
105
+ }
106
+
83
107
  export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
84
108
  for (const chunk of chunkText(text)) {
85
109
  const { mode, openid, msgId } = ch.budget.acquire();
@@ -108,15 +132,15 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
108
132
  try {
109
133
  log.warn("outbound", "passive send failed; retrying proactively", { targetId: ch.boundOpenid });
110
134
  await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
111
- ch.onWarn?.("Passive reply failed; falling back to proactive.");
135
+ ch.onWarn?.(t("outbound.passiveFailed"));
112
136
  continue;
113
137
  } catch (retryErr) {
114
138
  log.error("outbound", "proactive retry failed", { targetId: ch.boundOpenid, err: retryErr });
115
- ch.onWarn?.(`Proactive send failed: ${(retryErr as Error).message}`);
139
+ ch.onWarn?.(t("outbound.proactiveFailed", { message: (retryErr as Error).message }));
116
140
  continue;
117
141
  }
118
142
  }
119
- ch.onWarn?.(`Send failed: ${(err as Error).message}`);
143
+ ch.onWarn?.(t("outbound.sendFailed", { message: (err as Error).message }));
120
144
  }
121
145
  }
122
146
  }