@chen_hu_hu/pi-qq 1.0.2 → 1.1.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.
package/src/bot.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  } from "@tencent-connect/qqbot-nodejs";
9
9
  import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
10
10
  import type { Credentials } from "./config";
11
+ import { log, sdkLogger } from "./logger";
11
12
 
12
13
  /**
13
14
  * Session-level QQBot lifecycle: creation, middleware, connection state,
@@ -27,8 +28,6 @@ export interface StartBotOptions {
27
28
  /** F2: QR-bound single user; production always provides it */
28
29
  allowedOpenid?: string;
29
30
  markdownSupport?: boolean;
30
- /** Debug mode: print SDK logs (timeouts/rate limits/reconnects) to the terminal. */
31
- debug?: boolean;
32
31
  /** Inbound message handler. */
33
32
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
34
33
  /** Connection state changes; the caller decides how to notify the UI. */
@@ -44,10 +43,17 @@ export interface RunningBot {
44
43
  }
45
44
 
46
45
  export function startBot(opts: StartBotOptions): RunningBot {
46
+ log.info("bot", "starting", {
47
+ appId: opts.credentials.appId,
48
+ allowedOpenid: opts.allowedOpenid,
49
+ markdownSupport: opts.markdownSupport,
50
+ });
51
+
47
52
  const bot = new QQBot({
48
53
  appId: opts.credentials.appId,
49
54
  appSecret: opts.credentials.appSecret,
50
55
  markdownSupport: opts.markdownSupport ?? false,
56
+ logger: sdkLogger,
51
57
  });
52
58
 
53
59
  // Echo filtering + message deduplication (SDK default 5s window).
@@ -59,14 +65,46 @@ export function startBot(opts: StartBotOptions): RunningBot {
59
65
  // Serialize per user so streams and replies do not race.
60
66
  bot.use(concurrencyGuard());
61
67
 
62
- const report = (state: BotState, detail?: string) => opts.onStateChange?.(state, detail);
68
+ const report = (state: BotState, detail?: string) => {
69
+ if (state === "blocked" || (state === "stopped" && detail)) {
70
+ log.error("bot", state, { detail });
71
+ } else if (state === "reconnecting") {
72
+ log.warn("bot", state, { detail });
73
+ } else {
74
+ log.info("bot", state, { detail });
75
+ }
76
+ opts.onStateChange?.(state, detail);
77
+ };
63
78
 
64
79
  bot.on("ready", () => report("connected"));
65
80
  bot.on("resumed", () => report("connected"));
66
81
  bot.on("disconnected", ({ willReconnect }) => report(willReconnect ? "reconnecting" : "stopped"));
67
- bot.on("error", (err) => opts.onRecoverableError?.(err));
82
+ bot.on("error", (err) => {
83
+ log.error("bot", "error event", { err });
84
+ opts.onRecoverableError?.(err);
85
+ });
68
86
  bot.on("message", (_ctx, msg) => {
69
- void opts.onMessage?.(bot, msg);
87
+ log.debug("bot", "inbound message", {
88
+ kind: msg.kind,
89
+ rawEventType: msg.rawEventType,
90
+ messageId: msg.messageId,
91
+ senderId: msg.senderId,
92
+ senderName: msg.senderName,
93
+ senderIsBot: msg.senderIsBot,
94
+ content: msg.content,
95
+ msgType: msg.msgType,
96
+ timestamp: msg.timestamp,
97
+ replyTarget: msg.replyTarget,
98
+ msgIdx: msg.msgIdx,
99
+ refMsgIdx: msg.refMsgIdx,
100
+ messageScene: msg.messageScene,
101
+ attachments: msg.attachments,
102
+ msgElements: msg.msgElements,
103
+ raw: msg.raw,
104
+ });
105
+ Promise.resolve(opts.onMessage?.(bot, msg)).catch((err: unknown) => {
106
+ log.error("bot", "message handler rejected", { err });
107
+ });
70
108
  });
71
109
 
72
110
  let stopped = false;
package/src/config.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
+ import { normalizeLogLevel, type LogLevel } from "./logger";
4
5
 
5
6
  /**
6
7
  * ~/.pi/agent/pi-qq.json contains non-secret settings only.
@@ -27,7 +28,9 @@ export interface PiQQSettings {
27
28
  heartbeatMaxMessages?: number;
28
29
  /** F7: stream summary frame interval (ms, minimum 300) */
29
30
  streamFlushMs?: number;
30
- /** Diagnostic mode: SDK logs + stream retry/timeout logs */
31
+ /** Log threshold: silent, error, warn, info, debug (default: silent) */
32
+ logLevel?: LogLevel;
33
+ /** @deprecated Use logLevel; kept only for config migration. */
31
34
  debug?: boolean;
32
35
  /** F7: append-mode stream relay switch */
33
36
  streamRelay?: boolean;
@@ -59,10 +62,11 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
59
62
  }
60
63
  }
61
64
 
62
- export interface ResolvedSettings extends Required<PiQQSettings> {}
65
+ export interface ResolvedSettings extends Required<Omit<PiQQSettings, "debug">> {}
63
66
 
64
67
  /** Settings with defaults applied (features-v1.md §4). */
65
68
  export function getSettings(config: PiQQConfig): ResolvedSettings {
69
+ const logLevel = normalizeLogLevel(config.logLevel ?? (config.debug ? "debug" : undefined));
66
70
  return {
67
71
  streamAssistant: config.streamAssistant ?? true,
68
72
  markdownSupport: config.markdownSupport ?? false,
@@ -72,7 +76,7 @@ export function getSettings(config: PiQQConfig): ResolvedSettings {
72
76
  heartbeatMinutes: config.heartbeatMinutes ?? 10,
73
77
  heartbeatMaxMessages: config.heartbeatMaxMessages ?? 3,
74
78
  streamFlushMs: config.streamFlushMs ?? 10_000,
75
- debug: config.debug ?? false,
79
+ logLevel,
76
80
  streamRelay: config.streamRelay ?? true,
77
81
  };
78
82
  }
package/src/download.ts CHANGED
@@ -21,7 +21,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
21
21
  if (!response.body) {
22
22
  const body = Buffer.from(await response.arrayBuffer());
23
23
  if (body.byteLength > limit) {
24
- throw new Error(`${kind}过大(${formatBytes(body.byteLength)} > ${formatBytes(limit)})`);
24
+ throw new Error(`${kind} too large (${formatBytes(body.byteLength)} > ${formatBytes(limit)})`);
25
25
  }
26
26
  return body;
27
27
  }
@@ -37,14 +37,14 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
37
37
  total += value.byteLength;
38
38
  if (total > limit) {
39
39
  await reader.cancel();
40
- throw new Error(`${kind}过大(>${formatBytes(limit)})`);
40
+ throw new Error(`${kind} too large (>${formatBytes(limit)})`);
41
41
  }
42
42
  chunks.push(value);
43
43
  }
44
44
  } finally {
45
45
  reader.releaseLock();
46
46
  }
47
- if (total === 0) throw new Error(`${kind}内容为空`);
47
+ if (total === 0) throw new Error(`empty ${kind} content`);
48
48
  return Buffer.concat(chunks, total);
49
49
  }
50
50
 
@@ -55,10 +55,10 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
55
55
  try {
56
56
  parsed = new URL(opts.url);
57
57
  } catch {
58
- throw new Error(`${opts.kind}地址无效`);
58
+ throw new Error(`invalid ${opts.kind} URL`);
59
59
  }
60
60
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
61
- throw new Error(`不支持的${opts.kind}地址协议`);
61
+ throw new Error(`unsupported ${opts.kind} URL protocol`);
62
62
  }
63
63
 
64
64
  const controller = new AbortController();
@@ -67,19 +67,19 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
67
67
  try {
68
68
  const response = await fetchImpl(parsed.toString(), { signal: controller.signal, redirect: "follow" });
69
69
  if (!response.ok) {
70
- throw new Error(`下载失败(HTTP ${response.status})`);
70
+ throw new Error(`download failed (HTTP ${response.status})`);
71
71
  }
72
72
 
73
73
  const lengthHeader = response.headers.get("content-length");
74
74
  const contentLength = lengthHeader ? Number(lengthHeader) : NaN;
75
75
  if (Number.isFinite(contentLength) && contentLength > limit) {
76
76
  await response.body?.cancel();
77
- throw new Error(`${opts.kind}过大(${formatBytes(contentLength)} > ${formatBytes(limit)})`);
77
+ throw new Error(`${opts.kind} too large (${formatBytes(contentLength)} > ${formatBytes(limit)})`);
78
78
  }
79
79
  return await readBodyLimited(response, limit, opts.kind);
80
80
  } catch (err) {
81
81
  if (controller.signal.aborted) {
82
- throw new Error(`下载超时(${opts.timeoutMs / 1000}s)`);
82
+ throw new Error(`download timed out after ${opts.timeoutMs / 1000}s`);
83
83
  }
84
84
  throw err;
85
85
  } finally {
package/src/files.ts CHANGED
@@ -78,7 +78,7 @@ async function writeUnique(dir: string, filename: string, body: Buffer): Promise
78
78
  if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
79
79
  }
80
80
  }
81
- throw new Error("无法分配唯一文件名");
81
+ throw new Error("Could not allocate a unique filename");
82
82
  }
83
83
 
84
84
  /** Save non-image attachments in order; one failure does not stop the others. */
@@ -102,7 +102,7 @@ export async function saveInboundFiles(
102
102
  const fallback = `file-${index + 1}`;
103
103
  const filename = sanitizeFilename(attachment.filename, fallback);
104
104
  if (typeof attachment.size === "number" && attachment.size > limit) {
105
- failures.push({ filename, reason: `文件过大(${formatBytes(attachment.size)} > ${formatBytes(limit)})` });
105
+ failures.push({ filename, reason: `file too large (${formatBytes(attachment.size)} > ${formatBytes(limit)})` });
106
106
  continue;
107
107
  }
108
108
 
@@ -111,13 +111,13 @@ export async function saveInboundFiles(
111
111
  url: attachment.url,
112
112
  maxSize: limit,
113
113
  timeoutMs: DOWNLOAD_TIMEOUT_MS,
114
- kind: "文件",
114
+ kind: "file",
115
115
  fetchImpl,
116
116
  });
117
117
  const path = await writeUnique(dir, filename, body);
118
118
  files.push({ path, originalName: filename, size: body.byteLength });
119
119
  } catch (err) {
120
- failures.push({ filename, reason: err instanceof Error ? err.message : "下载失败" });
120
+ failures.push({ filename, reason: err instanceof Error ? err.message : "Download failed" });
121
121
  }
122
122
  }
123
123
 
package/src/images.ts CHANGED
@@ -78,13 +78,15 @@ export function buildImageMessageContent(
78
78
 
79
79
  export function formatImageFailures(failures: readonly ImageFailure[], successCount: number): string {
80
80
  const title =
81
- successCount > 0 ? `⚠️ 有 ${failures.length} 个附件未处理(成功 ${successCount} 个):` : "⚠️ 附件处理失败:";
82
- return [title, ...failures.map((failure) => `• ${failure.filename}:${failure.reason}`)].join("\n");
81
+ successCount > 0
82
+ ? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
83
+ : "⚠️ Attachment failed:";
84
+ return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
83
85
  }
84
86
 
85
87
  function attachmentLabel(filename: string | undefined, index: number): string {
86
88
  const name = filename?.trim();
87
- return name || `图片 ${index + 1}`;
89
+ return name || `Image ${index + 1}`;
88
90
  }
89
91
 
90
92
  async function downloadOne(
@@ -96,10 +98,20 @@ async function downloadOne(
96
98
  const filename = attachmentLabel(attachment.filename, index);
97
99
  const mimeType = resolveImageMime(attachment.content_type, attachment.filename);
98
100
  if (!mimeType) {
99
- return { failure: { filename, reason: `不支持的附件类型(${attachment.content_type || "未知"})` } };
101
+ return {
102
+ failure: {
103
+ filename,
104
+ reason: `Unsupported attachment type (${attachment.content_type || "unknown"})`,
105
+ },
106
+ };
100
107
  }
101
108
  if (typeof attachment.size === "number" && attachment.size > maxSize) {
102
- return { failure: { filename, reason: `图片过大(${formatBytes(attachment.size)} > ${formatBytes(maxSize)})` } };
109
+ return {
110
+ failure: {
111
+ filename,
112
+ reason: `image too large (${formatBytes(attachment.size)} > ${formatBytes(maxSize)})`,
113
+ },
114
+ };
103
115
  }
104
116
 
105
117
  try {
@@ -107,12 +119,12 @@ async function downloadOne(
107
119
  url: attachment.url,
108
120
  maxSize,
109
121
  timeoutMs: DOWNLOAD_TIMEOUT_MS,
110
- kind: "图片",
122
+ kind: "image",
111
123
  fetchImpl,
112
124
  });
113
125
  return { image: { type: "image", data: body.toString("base64"), mimeType } };
114
126
  } catch (err) {
115
- return { failure: { filename, reason: err instanceof Error ? err.message : "下载失败" } };
127
+ return { failure: { filename, reason: err instanceof Error ? err.message : "Download failed" } };
116
128
  }
117
129
  }
118
130
 
package/src/inbound.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  type ImageContentLike,
12
12
  } from "./images";
13
13
  import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
14
+ import { log } from "./logger";
15
+ import { isVoiceAttachment, resolveVoiceTranscript } from "./voice";
14
16
 
15
17
  /**
16
18
  * F2: QQ → pi inbound handling.
@@ -39,13 +41,43 @@ export interface InboundDeps {
39
41
 
40
42
  export function createInboundHandler(deps: InboundDeps) {
41
43
  return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
42
- if (msg.kind !== "c2c") return;
44
+ log.debug("inbound", "message received", {
45
+ kind: msg.kind,
46
+ rawEventType: msg.rawEventType,
47
+ messageId: msg.messageId,
48
+ senderId: msg.senderId,
49
+ senderName: msg.senderName,
50
+ senderIsBot: msg.senderIsBot,
51
+ content: msg.content,
52
+ msgType: msg.msgType,
53
+ timestamp: msg.timestamp,
54
+ msgIdx: msg.msgIdx,
55
+ refMsgIdx: msg.refMsgIdx,
56
+ messageScene: msg.messageScene,
57
+ attachments: msg.attachments,
58
+ msgElements: msg.msgElements,
59
+ raw: msg.raw,
60
+ });
61
+
62
+ if (msg.kind !== "c2c") {
63
+ log.debug("inbound", "skipped non-c2c message", { kind: msg.kind });
64
+ return;
65
+ }
43
66
 
44
67
  const allowed = deps.getAllowedOpenid();
45
- if (!allowed || msg.senderId !== allowed) return;
68
+ if (!allowed || msg.senderId !== allowed) {
69
+ log.debug("inbound", "skipped non-allowlisted sender", { senderId: msg.senderId });
70
+ return;
71
+ }
46
72
 
47
73
  // Record passive reply target/freshness for outbound budget.
48
74
  deps.budget.observeInbound(msg.senderId, msg.messageId);
75
+ log.info("inbound", "message received", {
76
+ messageId: msg.messageId,
77
+ senderId: msg.senderId,
78
+ contentLength: (msg.content ?? "").length,
79
+ attachmentCount: (msg.attachments ?? []).length,
80
+ });
49
81
 
50
82
  const channel: ReplyChannel = {
51
83
  budget: deps.budget,
@@ -57,13 +89,36 @@ export function createInboundHandler(deps: InboundDeps) {
57
89
 
58
90
  const text = (msg.content ?? "").trim();
59
91
  if (text.startsWith("/")) {
92
+ log.info("inbound", "QQ command", { command: text.split(/\s+/)[0] });
60
93
  await handleCommand(text, reply, deps);
61
94
  return;
62
95
  }
63
96
 
64
97
  const attachments = msg.attachments ?? [];
65
98
  if (!text && attachments.length === 0) {
66
- await reply("暂不支持该消息类型");
99
+ log.warn("inbound", "unsupported message: no text and no attachments", { messageId: msg.messageId });
100
+ await reply("Unsupported message type.");
101
+ return;
102
+ }
103
+
104
+ // F8: voice messages use QQ built-in ASR; never download or save the audio.
105
+ const voiceAttachments = attachments.filter(isVoiceAttachment);
106
+ if (voiceAttachments.length > 0) {
107
+ const transcript = resolveVoiceTranscript(voiceAttachments);
108
+ log.info("inbound", "voice message", {
109
+ messageId: msg.messageId,
110
+ hasAsr: Boolean(transcript),
111
+ asrLength: transcript?.length ?? 0,
112
+ });
113
+ if (!transcript) {
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.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
119
+ deps.markQQTrigger(msg.senderId, msg.messageId);
120
+ deps.pi.sendUserMessage(transcript, { deliverAs: deps.getDeliverAs() });
121
+ log.info("inbound", "voice sent to pi", { messageId: msg.messageId, asrLength: transcript.length });
67
122
  return;
68
123
  }
69
124
 
@@ -76,7 +131,11 @@ export function createInboundHandler(deps: InboundDeps) {
76
131
  if (imageAttachments.length > 0) {
77
132
  const supportsImages = deps.ctx.model?.input.includes("image") ?? false;
78
133
  if (!supportsImages) {
79
- await reply(`当前模型不支持图片输入,已跳过 ${imageAttachments.length} 张图片`);
134
+ log.warn("inbound", "model does not support images; skipped", {
135
+ messageId: msg.messageId,
136
+ count: imageAttachments.length,
137
+ });
138
+ await reply(`Model does not support image input; skipped ${imageAttachments.length} image(s).`);
80
139
  } else {
81
140
  const result = await resolveInboundImages(imageAttachments, deps.getImageMaxSize());
82
141
  images = result.images;
@@ -96,14 +155,32 @@ export function createInboundHandler(deps: InboundDeps) {
96
155
  }
97
156
 
98
157
  if (failures.length > 0) {
158
+ log.warn("inbound", "attachment failure summary", {
159
+ messageId: msg.messageId,
160
+ failures,
161
+ successCount: images.length + files.length,
162
+ });
99
163
  await reply(formatImageFailures(failures, images.length + files.length));
100
164
  }
101
- if (!text && images.length === 0 && files.length === 0) return;
165
+ if (!text && images.length === 0 && files.length === 0) {
166
+ log.warn("inbound", "no injectable content after attachment handling", {
167
+ messageId: msg.messageId,
168
+ failures: failures.length,
169
+ });
170
+ return;
171
+ }
102
172
 
103
173
  // F7: mark a QQ-triggered run; do not send a start confirmation.
104
174
  deps.markQQTrigger(msg.senderId, msg.messageId);
105
175
  const promptText = formatFilePrompt(files, text);
106
176
  deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
177
+ log.info("inbound", "sent to pi", {
178
+ messageId: msg.messageId,
179
+ textLength: text.length,
180
+ images: images.length,
181
+ files: files.length,
182
+ deliverAs: deps.getDeliverAs(),
183
+ });
107
184
  };
108
185
  }
109
186
 
@@ -113,30 +190,30 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
113
190
  case "/help":
114
191
  await reply(
115
192
  [
116
- "pi-qq 命令:",
117
- "• /stop — 中止当前任务",
118
- "• /compact — 压缩上下文",
119
- "• /status — 查看状态",
120
- "• /new — 重置会话",
121
- "• /help — 本帮助",
122
- "其他文字将直接发送给 pi",
193
+ "pi-qq commands:",
194
+ "• /stop — abort the current task",
195
+ "• /compact — compact the context",
196
+ "• /status — show status",
197
+ "• /new — reset the session",
198
+ "• /help — this help",
199
+ "Other text is sent to pi.",
123
200
  ].join("\n"),
124
201
  );
125
202
  break;
126
203
  case "/stop":
127
204
  if (deps.ctx.isIdle()) {
128
- await reply("当前没有正在运行的任务");
205
+ await reply("No task is running.");
129
206
  } else {
130
207
  deps.ctx.abort();
131
- await reply("已请求中止当前任务");
208
+ await reply("Abort requested.");
132
209
  }
133
210
  break;
134
211
  case "/compact":
135
212
  if (deps.ctx.isIdle()) {
136
213
  deps.ctx.compact();
137
- await reply("已触发上下文压缩");
214
+ await reply("Context compaction triggered.");
138
215
  } else {
139
- await reply("任务运行中,请先 /stop 再压缩");
216
+ await reply("Task is running; use /stop before /compact.");
140
217
  }
141
218
  break;
142
219
  case "/status":
@@ -144,14 +221,14 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
144
221
  break;
145
222
  case "/new":
146
223
  if (!deps.ctx.isIdle()) {
147
- await reply("任务运行中,请先 /stop 再重置会话");
224
+ await reply("Task is running; use /stop before resetting.");
148
225
  } else {
149
- await reply("正在重置会话…");
226
+ await reply("Resetting the session…");
150
227
  // Built-in /new is interactive-only; dispatch the extension command instead.
151
228
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
152
229
  }
153
230
  break;
154
231
  default:
155
- await reply(`未知命令 ${cmd},发送 /help 查看支持命令`);
232
+ await reply(`Unknown command ${cmd}; use /help.`);
156
233
  }
157
234
  }
package/src/logger.ts ADDED
@@ -0,0 +1,180 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * Structured logger for pi-qq.
6
+ *
7
+ * One JSON record per line, one file per local day:
8
+ * <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
9
+ *
10
+ * The default level is silent. Logging is best-effort and must never break QQ
11
+ * message handling. Tests can override the directory via PI_QQ_LOG_DIR.
12
+ */
13
+
14
+ export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
15
+ export type LogFields = Record<string, unknown>;
16
+
17
+ const LEVEL_WEIGHT: Record<LogLevel, number> = {
18
+ debug: 10,
19
+ info: 20,
20
+ warn: 30,
21
+ error: 40,
22
+ silent: 100,
23
+ };
24
+
25
+ export const DEFAULT_LOG_LEVEL: LogLevel = "silent";
26
+
27
+ let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
28
+ let activeDir: string | undefined;
29
+
30
+ export function isLogLevel(value: unknown): value is LogLevel {
31
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(LEVEL_WEIGHT, value);
32
+ }
33
+
34
+ export function normalizeLogLevel(value: unknown): LogLevel {
35
+ return isLogLevel(value) ? value : DEFAULT_LOG_LEVEL;
36
+ }
37
+
38
+ /** Whether an event at `level` passes the configured threshold. */
39
+ export function isLevelEnabled(configured: LogLevel, level: Exclude<LogLevel, "silent">): boolean {
40
+ return configured !== "silent" && LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[configured];
41
+ }
42
+
43
+ /** Set the active threshold and optional directory. */
44
+ export function configureLogger(level: LogLevel, dir?: string): void {
45
+ activeLevel = normalizeLogLevel(level);
46
+ activeDir = dir;
47
+ }
48
+
49
+ export function getLogLevel(): LogLevel {
50
+ return activeLevel;
51
+ }
52
+
53
+ export function resolveLogDir(): string {
54
+ return process.env.PI_QQ_LOG_DIR ?? activeDir ?? join(process.cwd(), ".pi", "pi-qq", "logs");
55
+ }
56
+
57
+ function pad(n: number): string {
58
+ return String(n).padStart(2, "0");
59
+ }
60
+
61
+ /** Local calendar date used in the log filename. */
62
+ export function dateStamp(now = new Date()): string {
63
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
64
+ }
65
+
66
+ export function logFileName(now = new Date()): string {
67
+ return `pi-qq-${dateStamp(now)}.log`;
68
+ }
69
+
70
+ export function getLogFilePath(now = new Date()): string {
71
+ return join(resolveLogDir(), logFileName(now));
72
+ }
73
+
74
+ function normalizeData(data: unknown): LogFields | undefined {
75
+ if (data === undefined) return undefined;
76
+ if (data instanceof Error) return { err: data };
77
+ if (data !== null && typeof data === "object" && !Array.isArray(data)) return data as LogFields;
78
+ return { data };
79
+ }
80
+
81
+ function stringifyError(err: unknown): string {
82
+ return err instanceof Error ? err.message : String(err);
83
+ }
84
+
85
+ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message: string, data?: unknown): void {
86
+ if (!isLevelEnabled(activeLevel, level)) return;
87
+
88
+ const record: LogFields = {
89
+ time: new Date().toISOString(),
90
+ level,
91
+ scope,
92
+ msg: message,
93
+ };
94
+ const fields = normalizeData(data);
95
+ if (fields) {
96
+ for (const [key, value] of Object.entries(fields)) {
97
+ // Protect the record envelope from accidental overrides.
98
+ if (!(key in record)) record[key] = value;
99
+ }
100
+ }
101
+
102
+ let line: string;
103
+ try {
104
+ line = JSON.stringify(record, (_key, value) => {
105
+ if (typeof value === "bigint") return `${value}n`;
106
+ if (value instanceof Error) {
107
+ return { name: value.name, message: value.message, stack: value.stack };
108
+ }
109
+ return value;
110
+ });
111
+ } catch (err) {
112
+ line = JSON.stringify({
113
+ time: record.time,
114
+ level,
115
+ scope,
116
+ msg: message,
117
+ serializationError: stringifyError(err),
118
+ });
119
+ }
120
+
121
+ try {
122
+ const dir = resolveLogDir();
123
+ mkdirSync(dir, { recursive: true });
124
+ appendFileSync(join(dir, logFileName()), `${line}\n`, "utf8");
125
+ } catch {
126
+ // Logging is diagnostic only; never break message handling.
127
+ }
128
+ }
129
+
130
+ export const log = {
131
+ get level(): LogLevel {
132
+ return activeLevel;
133
+ },
134
+ debug(scope: string, message: string, data?: unknown): void {
135
+ writeRecord("debug", scope, message, data);
136
+ },
137
+ info(scope: string, message: string, data?: unknown): void {
138
+ writeRecord("info", scope, message, data);
139
+ },
140
+ warn(scope: string, message: string, data?: unknown): void {
141
+ writeRecord("warn", scope, message, data);
142
+ },
143
+ error(scope: string, message: string, data?: unknown): void {
144
+ writeRecord("error", scope, message, data);
145
+ },
146
+ };
147
+
148
+ /** Adapter for the QQ SDK's Logger interface: (message, meta?) -> record. */
149
+ export const sdkLogger = {
150
+ debug(message: string, meta?: Record<string, unknown>): void {
151
+ log.debug("qqbot", message, meta);
152
+ },
153
+ info(message: string, meta?: Record<string, unknown>): void {
154
+ log.info("qqbot", message, meta);
155
+ },
156
+ warn(message: string, meta?: Record<string, unknown>): void {
157
+ log.warn("qqbot", message, meta);
158
+ },
159
+ error(message: string, meta?: Record<string, unknown>): void {
160
+ log.error("qqbot", message, meta);
161
+ },
162
+ };
163
+
164
+ /** Short string form for noisy tool payloads. */
165
+ export function previewForLog(value: unknown, maxChars = 2000): string {
166
+ let text: string;
167
+ if (typeof value === "string") {
168
+ text = value;
169
+ } else if (value instanceof Error) {
170
+ text = `${value.name}: ${value.message}`;
171
+ } else {
172
+ try {
173
+ const stringified = JSON.stringify(value);
174
+ text = typeof stringified === "string" ? stringified : String(value);
175
+ } catch {
176
+ text = String(value);
177
+ }
178
+ }
179
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…(${text.length} chars)`;
180
+ }