@chen_hu_hu/pi-qq 1.3.3 → 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.
package/index.ts CHANGED
@@ -8,8 +8,10 @@ import { registerQQDiagnostics } from "./src/qq/qq-diagnostics";
8
8
  import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
9
9
  import { ReplyBudget } from "./src/quota/reply-quota";
10
10
  import { RunFeedback } from "./src/relay/run-stream-relay";
11
- import { formatTokenCount } from "./src/infra/display-format";
12
11
  import { configureLogger, flushLogs, isLogEnabled, log, previewForLog } from "./src/infra/file-logger";
12
+ import { configureI18n, t } from "./src/infra/i18n";
13
+ import { getPowerStatus } from "./src/infra/power-status";
14
+ import { formatStatusReport } from "./src/qq/status-report";
13
15
  import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
14
16
 
15
17
  interface LoginState {
@@ -43,10 +45,9 @@ const runFeedback = new RunFeedback({
43
45
  onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
44
46
  });
45
47
 
46
- const fmtTokens = (n: number | null): string => (n === null ? "unknown" : formatTokenCount(n));
47
-
48
48
  export default function (pi: ExtensionAPI) {
49
- const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
49
+ activeSettings = getSettings(readConfig().config);
50
+ configureI18n(activeSettings.language);
50
51
 
51
52
  const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
52
53
  const getDeliverAs = () => activeSettings.deliverAs;
@@ -56,6 +57,7 @@ export default function (pi: ExtensionAPI) {
56
57
  const applyConfig = (ctx: ExtensionContext) => {
57
58
  const { config, error } = readConfig();
58
59
  activeSettings = getSettings(config);
60
+ configureI18n(activeSettings.language);
59
61
  if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
60
62
  return { settings: activeSettings, error };
61
63
  };
@@ -63,18 +65,23 @@ export default function (pi: ExtensionAPI) {
63
65
  const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
64
66
  const login = getLoginState();
65
67
  const usage = ctx?.getContextUsage();
66
- const model = ctx?.model;
67
- return [
68
- "pi-qq status",
69
- `Login: ${login ? `QR login, in memory (AppID ${maskAppId(login.credentials.appId)})` : "not logged in"}`,
70
- `Connection: ${lastState}${stateDetail ? ` (${stateDetail})` : ""}`,
71
- `Model: ${model?.name ?? "none"}`,
72
- usage
73
- ? `Context: ${fmtTokens(usage.tokens)}/${fmtTokens(usage.contextWindow)} (${usage.percent?.toFixed(1) ?? "?"}%)`
74
- : "Context: unknown",
75
- `Bound user: ${login?.allowedOpenid ?? "none"}`,
76
- `Settings: ~/.pi/agent/pi-qq.json`,
77
- ];
68
+ return formatStatusReport({
69
+ login: login ? { appId: login.credentials.appId, openid: login.allowedOpenid } : undefined,
70
+ connection: { state: lastState, detail: stateDetail },
71
+ agent: {
72
+ running: ctx ? !ctx.isIdle() : runFeedback.isQQRunActive(),
73
+ qq: runFeedback.isQQRunActive(),
74
+ },
75
+ model: ctx?.model ? { name: ctx.model.name } : undefined,
76
+ usage: usage
77
+ ? {
78
+ tokens: usage.tokens,
79
+ contextWindow: usage.contextWindow,
80
+ percent: usage.percent,
81
+ }
82
+ : undefined,
83
+ power: getPowerStatus(),
84
+ });
78
85
  };
79
86
 
80
87
  const stopIfRunning = () => {
@@ -124,8 +131,8 @@ export default function (pi: ExtensionAPI) {
124
131
  onStateChange: (state, detail) => {
125
132
  lastState = state;
126
133
  stateDetail = detail;
127
- if (state === "connected") ctx.ui.notify("pi-qq connected", "info");
128
- else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "connection blocked"}`, "error");
134
+ if (state === "connected") ctx.ui.notify(t("notify.connected"), "info");
135
+ else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? t("notify.connectionBlocked")}`, "error");
129
136
  else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
130
137
  },
131
138
  });
@@ -147,7 +154,7 @@ export default function (pi: ExtensionAPI) {
147
154
  if (login) {
148
155
  await startWithCredentials(ctx, login.credentials, login.allowedOpenid);
149
156
  } else if (ctx.hasUI) {
150
- ctx.ui.notify("pi-qq: run /qq-login to scan a QR code.", "warning");
157
+ ctx.ui.notify(t("notify.loginRequired"), "warning");
151
158
  }
152
159
  });
153
160
 
@@ -228,7 +235,7 @@ export default function (pi: ExtensionAPI) {
228
235
 
229
236
  let text: string;
230
237
  if (isError) {
231
- text = `⚠️ Model error: ${msg.errorMessage ?? "unknown error"}`;
238
+ text = t("errors.model", { message: msg.errorMessage ?? t("status.unknown") });
232
239
  } else {
233
240
  text = msg.content
234
241
  .filter((b) => b.type === "text")
@@ -253,7 +260,7 @@ export default function (pi: ExtensionAPI) {
253
260
  const bound = getLoginState()?.allowedOpenid;
254
261
  if (!bound) {
255
262
  log.warn("pi", "no bound user; reply skipped");
256
- ctx.ui.notify("pi-qq: no bound QQ user; skipping reply.", "warning");
263
+ ctx.ui.notify(t("notify.noBoundUser"), "warning");
257
264
  return;
258
265
  }
259
266
 
@@ -266,7 +273,7 @@ export default function (pi: ExtensionAPI) {
266
273
  });
267
274
 
268
275
  pi.registerCommand("qq-login", {
269
- description: "pi-qq: log in with a QR code and bind the scanning QQ user",
276
+ description: t("commands.descQqLogin"),
270
277
  handler: async (_args, ctx) => {
271
278
  applyConfig(ctx);
272
279
  stopIfRunning();
@@ -276,13 +283,13 @@ export default function (pi: ExtensionAPI) {
276
283
  result = await runQrLogin(ctx);
277
284
  } catch (err) {
278
285
  log.error("login", "QR login command failed", { err });
279
- ctx.ui.notify("Error: QR login failed", "error");
286
+ ctx.ui.notify(t("login.failed"), "error");
280
287
  return;
281
288
  }
282
289
  if (!result) return;
283
290
  if (!result.userOpenid) {
284
291
  log.error("login", "QR login did not return a user openid");
285
- ctx.ui.notify("Error: QR login failed", "error");
292
+ ctx.ui.notify(t("login.failed"), "error");
286
293
  return;
287
294
  }
288
295
 
@@ -292,36 +299,36 @@ export default function (pi: ExtensionAPI) {
292
299
  await startWithCredentials(ctx, credentials, result.userOpenid);
293
300
  } catch (err) {
294
301
  log.error("login", "starting bot after login failed", { err });
295
- ctx.ui.notify("Error: QQ bot start failed", "error");
302
+ ctx.ui.notify(t("login.startFailed"), "error");
296
303
  }
297
304
  },
298
305
  });
299
306
 
300
307
  pi.registerCommand("qq-status", {
301
- description: "pi-qq: show login, connection, and bound QQ user",
308
+ description: t("commands.descQqStatus"),
302
309
  handler: async (_args, ctx) => {
303
310
  ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
304
311
  },
305
312
  });
306
313
 
307
314
  pi.registerCommand("qq-logout", {
308
- description: "pi-qq: log out and clear in-memory credentials",
315
+ description: t("commands.descQqLogout"),
309
316
  handler: async (_args, ctx) => {
310
317
  stopIfRunning();
311
318
  setLoginState(undefined);
312
- ctx.ui.notify("pi-qq logged out.", "info");
319
+ ctx.ui.notify(t("notify.loggedOut"), "info");
313
320
  },
314
321
  });
315
322
 
316
323
  pi.registerCommand("qq-new", {
317
- description: "pi-qq: reset the current session (used by QQ /new)",
324
+ description: t("commands.descQqNew"),
318
325
  handler: async (_args, ctx) => {
319
326
  if (!ctx.isIdle()) {
320
- ctx.ui.notify("pi-qq: the agent is busy; run /stop before resetting the session.", "warning");
327
+ ctx.ui.notify(t("notify.busyReset"), "warning");
321
328
  return;
322
329
  }
323
330
  const { cancelled } = await ctx.newSession();
324
- if (cancelled) ctx.ui.notify("pi-qq: session reset cancelled.", "warning");
331
+ if (cancelled) ctx.ui.notify(t("notify.resetCancelled"), "warning");
325
332
  },
326
333
  });
327
334
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
@@ -1,4 +1,5 @@
1
1
  import { formatBytes } from "../infra/display-format";
2
+ import { t } from "../infra/i18n";
2
3
 
3
4
  export interface InboundAttachmentLike {
4
5
  content_type: string;
@@ -19,7 +20,9 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
19
20
  if (!response.body) {
20
21
  const body = Buffer.from(await response.arrayBuffer());
21
22
  if (body.byteLength > limit) {
22
- throw new Error(`${kind} too large (${formatBytes(body.byteLength)} > ${formatBytes(limit)})`);
23
+ throw new Error(
24
+ t("attachments.tooLarge", { kind, size: formatBytes(body.byteLength), limit: formatBytes(limit) }),
25
+ );
23
26
  }
24
27
  return body;
25
28
  }
@@ -35,14 +38,14 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
35
38
  total += value.byteLength;
36
39
  if (total > limit) {
37
40
  await reader.cancel();
38
- throw new Error(`${kind} too large (>${formatBytes(limit)})`);
41
+ throw new Error(t("attachments.tooLargeShort", { kind, limit: formatBytes(limit) }));
39
42
  }
40
43
  chunks.push(value);
41
44
  }
42
45
  } finally {
43
46
  reader.releaseLock();
44
47
  }
45
- if (total === 0) throw new Error(`empty ${kind} content`);
48
+ if (total === 0) throw new Error(t("attachments.empty", { kind }));
46
49
  return Buffer.concat(chunks, total);
47
50
  }
48
51
 
@@ -52,10 +55,10 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
52
55
  try {
53
56
  parsed = new URL(opts.url);
54
57
  } catch {
55
- throw new Error(`invalid ${opts.kind} URL`);
58
+ throw new Error(t("attachments.invalidUrl", { kind: opts.kind }));
56
59
  }
57
60
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
58
- throw new Error(`unsupported ${opts.kind} URL protocol`);
61
+ throw new Error(t("attachments.unsupportedProtocol", { kind: opts.kind }));
59
62
  }
60
63
 
61
64
  const controller = new AbortController();
@@ -64,19 +67,21 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
64
67
  try {
65
68
  const response = await fetchImpl(parsed.toString(), { signal: controller.signal, redirect: "follow" });
66
69
  if (!response.ok) {
67
- throw new Error(`download failed (HTTP ${response.status})`);
70
+ throw new Error(t("attachments.httpFailed", { status: response.status }));
68
71
  }
69
72
 
70
73
  const lengthHeader = response.headers.get("content-length");
71
74
  const contentLength = lengthHeader ? Number(lengthHeader) : NaN;
72
75
  if (Number.isFinite(contentLength) && contentLength > limit) {
73
76
  await response.body?.cancel();
74
- throw new Error(`${opts.kind} too large (${formatBytes(contentLength)} > ${formatBytes(limit)})`);
77
+ throw new Error(
78
+ t("attachments.tooLarge", { kind: opts.kind, size: formatBytes(contentLength), limit: formatBytes(limit) }),
79
+ );
75
80
  }
76
81
  return await readBodyLimited(response, limit, opts.kind);
77
82
  } catch (err) {
78
83
  if (controller.signal.aborted) {
79
- throw new Error(`download timed out after ${opts.timeoutMs / 1000}s`, { cause: err });
84
+ throw new Error(t("attachments.timeout", { seconds: opts.timeoutMs / 1000 }), { cause: err });
80
85
  }
81
86
  throw err;
82
87
  } finally {
@@ -1,3 +1,5 @@
1
+ import { t } from "../infra/i18n";
2
+
1
3
  export interface AttachmentFailure {
2
4
  filename: string;
3
5
  reason: string;
@@ -6,7 +8,7 @@ export interface AttachmentFailure {
6
8
  export function formatAttachmentFailures(failures: readonly AttachmentFailure[], successCount: number): string {
7
9
  const title =
8
10
  successCount > 0
9
- ? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
10
- : "⚠️ Attachment failed:";
11
+ ? t("attachments.failedMany", { failed: failures.length, success: successCount })
12
+ : t("attachments.failedNone");
11
13
  return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
12
14
  }
@@ -5,6 +5,7 @@ import { downloadLimited, type InboundAttachmentLike } from "./attachment-downlo
5
5
  import type { AttachmentFailure } from "./attachment-failure";
6
6
  import { formatBytes } from "../infra/display-format";
7
7
  import { log } from "../infra/file-logger";
8
+ import { t } from "../infra/i18n";
8
9
 
9
10
  const DOWNLOAD_TIMEOUT_MS = 60_000;
10
11
  const UPLOAD_INDEX_FILENAME = ".index.json";
@@ -179,7 +180,7 @@ async function saveOrReuse(
179
180
  return { file: { path: candidatePath }, changed: true };
180
181
  }
181
182
 
182
- throw new Error("Could not allocate a unique filename");
183
+ throw new Error(t("attachments.noUniqueName"));
183
184
  }
184
185
 
185
186
  export async function saveInboundFiles(
@@ -207,7 +208,13 @@ export async function saveInboundFiles(
207
208
  const fallback = `file-${position + 1}`;
208
209
  const filename = sanitizeFilename(attachment.filename, fallback);
209
210
  if (typeof attachment.size === "number" && attachment.size > limit) {
210
- failures.push({ filename, reason: `file too large (${formatBytes(attachment.size)} > ${formatBytes(limit)})` });
211
+ failures.push({
212
+ filename,
213
+ reason: t("attachments.fileTooLarge", {
214
+ size: formatBytes(attachment.size),
215
+ limit: formatBytes(limit),
216
+ }),
217
+ });
211
218
  continue;
212
219
  }
213
220
 
@@ -216,14 +223,14 @@ export async function saveInboundFiles(
216
223
  url: attachment.url,
217
224
  maxSize: limit,
218
225
  timeoutMs: DOWNLOAD_TIMEOUT_MS,
219
- kind: "file",
226
+ kind: t("attachments.kindFile"),
220
227
  fetchImpl,
221
228
  });
222
229
  const result = await saveOrReuse(uploadDir, filename, body, index);
223
230
  indexChanged ||= result.changed;
224
231
  addFile(result.file);
225
232
  } catch (err) {
226
- failures.push({ filename, reason: err instanceof Error ? err.message : "Download failed" });
233
+ failures.push({ filename, reason: err instanceof Error ? err.message : t("attachments.downloadFailed") });
227
234
  }
228
235
  }
229
236
 
@@ -1,5 +1,6 @@
1
1
  import { appendFile, mkdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { localizeLogMessage } from "./i18n";
3
4
 
4
5
  export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
5
6
  type LogFields = Record<string, unknown>;
@@ -78,11 +79,13 @@ function stringifyError(err: unknown): string {
78
79
  function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message: string, data?: unknown): void {
79
80
  if (!isLevelEnabled(activeLevel, level)) return;
80
81
 
82
+ const localized = localizeLogMessage(message);
81
83
  const record: LogFields = {
82
84
  time: new Date().toISOString(),
83
85
  level,
84
86
  scope,
85
- msg: message,
87
+ ...(localized.msgKey ? { msgKey: localized.msgKey } : {}),
88
+ msg: localized.msg,
86
89
  };
87
90
  const fields = normalizeData(data);
88
91
  if (fields) {
@@ -105,7 +108,8 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
105
108
  time: record.time,
106
109
  level,
107
110
  scope,
108
- msg: message,
111
+ ...(localized.msgKey ? { msgKey: localized.msgKey } : {}),
112
+ msg: localized.msg,
109
113
  serializationError: stringifyError(err),
110
114
  });
111
115
  }