@chen_hu_hu/pi-qq 1.0.2 → 1.2.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/doc/plan-v2.md ADDED
@@ -0,0 +1,331 @@
1
+ # pi-qq — plan-v2.md
2
+
3
+ > 执行计划。功能范围见 [features-v2.md](./features-v2.md);本文只回答:改哪些文件、按什么顺序做、每步怎么验收。
4
+ > V2 范围:F8 语音自动转写、F9 轻量日志基础设施、F10 文件消息等待指令、F11 文件存储与去重。不引入新依赖。
5
+
6
+ ## 0. 前置与范围
7
+
8
+ - 无新增 npm 依赖;日志使用 Node 标准库自研。
9
+ - 基线:当前 v1 代码,`npm test` 77 个测试通过。
10
+ - 不实现:本地 Whisper、外部 STT、保存原始语音、语音命令解析。
11
+ - 语音只处理 `content_type === "voice"`;不扩展其他媒体类型。
12
+ - 日志默认 `silent`;需要排查时手动改为 `info` / `debug`。
13
+
14
+ ## 1. 目录与模块
15
+
16
+ ```text
17
+ pi-qq/
18
+ ├── src/
19
+ │ ├── logger.ts # 新增:级别过滤、JSONL、按天单文件、SDK logger 适配
20
+ │ ├── voice.ts # 新增:语音附件判断、ASR 文本提取
21
+ │ ├── config.ts # 修改:logLevel、旧 debug 迁移
22
+ │ ├── inbound.ts # 修改:语音分支 + 日志分级 + pending + session uploads
23
+ │ ├── files.ts # 修改:session uploads、SHA-256 去重、索引维护
24
+ │ ├── bot.ts # 修改:接入 logger,移除 debug 选项
25
+ │ ├── index.ts # 修改:配置 logger,移除 getDebug,日志分级
26
+ │ ├── outbound.ts # 修改:发送日志分级
27
+ │ └── run-feedback.ts # 修改:移除 debug 时间戳,改用 logger
28
+ ├── test/
29
+ │ ├── logger.test.ts # 新增
30
+ │ ├── voice.test.ts # 新增
31
+ │ ├── config.test.ts # 新增或扩展现有设置测试
32
+ │ ├── inbound.test.ts # 修改
33
+ │ ├── bot.test.ts # 新增:message handler 串行回归
34
+ │ └── run-feedback.test.ts # 修改
35
+ ├── README.md # 修改:logLevel、日志路径、语音说明
36
+ └── doc/features-v2.md # 已存在,按实现结果校正
37
+ ```
38
+
39
+ ## 2. 执行步骤
40
+
41
+ ### M5a-1 — 实现 logger
42
+
43
+ **改动**
44
+
45
+ 1. 新增 `src/logger.ts`:
46
+ - `LogLevel = "silent" | "error" | "warn" | "info" | "debug"`。
47
+ - `configureLogger(level, dir?)`、`getLogLevel()`。
48
+ - `log.error/warn/info/debug(scope, message, data?)`。
49
+ - `sdkLogger`:适配 SDK 的 `(message, meta?)` 接口,统一写入同一个 logger。
50
+ - `previewForLog(value, maxChars)`:截断工具参数/结果。
51
+ - 级别过滤:只输出当前级别及以上;`silent` 不写。
52
+ - 输出一行 JSON:`time`、`level`、`scope`、`msg` + 结构化字段。
53
+ - 文件路径:`<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`。
54
+ - `PI_QQ_LOG_DIR` 可覆盖目录,供测试使用。
55
+ - 每次写入时重新计算日期;跨天自动换文件。
56
+ - 日志写入失败静默忽略,不影响消息处理。
57
+ 2. 不新增 `debug-log.ts`;不保留临时调试文件。
58
+
59
+ **验证**
60
+
61
+ - 单测覆盖:级别过滤、日期文件名、`previewForLog`、写入失败不抛错。
62
+ - `logLevel: "silent"` 不产生文件。
63
+ - `logLevel: "debug"` 能写入一行合法 JSON。
64
+ - `src/logger.ts` 不依赖第三方包。
65
+
66
+ ### M5a-2 — 配置与接线
67
+
68
+ **改动**
69
+
70
+ 1. `src/config.ts`:
71
+ - 新增 `logLevel?: LogLevel`,默认 `silent`。
72
+ - 保留 `debug?: boolean` 仅用于旧配置迁移:`debug: true` → `logLevel: "debug"`,其他情况默认 `silent`。
73
+ - `ResolvedSettings` 移除 `debug`。
74
+ 2. `src/index.ts`:
75
+ - 在 `session_start` / `startWithCredentials` 读取设置并 `configureLogger(settings.logLevel)`。
76
+ - 日志目录使用当前工作区 `ctx.cwd`;未配置时 logger 回退到 `process.cwd()`。
77
+ - 移除 `getDebug` 依赖和 `settings.debug` 传递。
78
+ 3. `src/bot.ts`:
79
+ - `StartBotOptions` 移除 `debug`。
80
+ - `new QQBot({ logger: sdkLogger })`。
81
+ - 连接状态用 info;连接失败/异常用 error;入站 raw 用 debug。
82
+ 4. `src/inbound.ts` / `src/outbound.ts`:
83
+ - 详细事件用 debug。
84
+ - 入站/出站摘要用 info。
85
+ - 附件失败、ASR 为空、发送降级用 warn。
86
+ - 发送失败、handler 异常用 error。
87
+ 5. `src/run-feedback.ts`:
88
+ - 移除 `getDebug` 和 QQ 气泡时间戳。
89
+ - 内部诊断改用 `log.debug` / `log.warn`。
90
+
91
+ **验证**
92
+
93
+ - `getSettings({}).logLevel === "silent"`。
94
+ - `getSettings({ debug: true }).logLevel === "debug"`。
95
+ - `getSettings({ logLevel: "info" }).logLevel === "info"`。
96
+ - 非法 `logLevel` 回退到 `silent`。
97
+ - 代码中除迁移读取外不再引用 `debug` 配置。
98
+ - `npm run typecheck` 通过。
99
+
100
+ ### M5a-3 — 日志行为验收
101
+
102
+ **验证**
103
+
104
+ 1. `logLevel: "silent"`:发送 QQ 消息后,`<cwd>/.pi/pi-qq/logs/` 不新增日志。
105
+ 2. `logLevel: "info"`:日志只含元数据,不含消息正文、prompt、工具参数。
106
+ 3. `logLevel: "debug"`:日志包含 raw 事件、附件、prompt、工具参数/结果、消息正文。
107
+ 4. 日期跨天:用注入时间或临时目录测试文件名从 `pi-qq-YYYY-MM-DD.log` 切换。
108
+ 5. 目录不可写:消息仍正常处理,进程不崩溃。
109
+
110
+ ### M5b-1 — 实现语音模块
111
+
112
+ **改动**
113
+
114
+ 1. 新增 `src/voice.ts`:
115
+ - `isVoiceAttachment(attachment)`:仅当 `content_type === "voice"` 返回 true。
116
+ - `resolveVoiceTranscript(attachments)`:
117
+ - 只读取语音附件。
118
+ - `asr_refer_text` 去首尾空白。
119
+ - 过滤空值;多个非空文本按附件顺序换行拼接。
120
+ - 无有效文本返回 `undefined`。
121
+ 2. 不下载 `url` / `voice_wav_url`,不保存语音文件。
122
+
123
+ **验证**
124
+
125
+ - `content_type === "voice"` 识别为语音。
126
+ - 普通文件、图片不识别为语音。
127
+ - `asr_refer_text` 为 `"测试。"` 返回 `"测试。"`。
128
+ - 空字符串、纯空白、缺失返回 `undefined`。
129
+ - 多个语音附件按顺序合并。
130
+
131
+ ### M5b-2 — 接入 inbound
132
+
133
+ **改动**
134
+
135
+ 1. `src/inbound.ts` 在图片/文件分流前增加语音分支:
136
+ - 提取 ASR 文本。
137
+ - 有文本:`markQQTrigger()` → `pi.sendUserMessage(text, { deliverAs })`,然后返回。
138
+ - 无文本:回复 `Could not transcribe this voice message; please resend or type it.`,不触发 run,然后返回。
139
+ 2. 语音分支不调用 `resolveInboundImages()`,不调用 `saveInboundFiles()`。
140
+ 3. 语音与文字不组合,语音转写不参与 QQ 命令解析。
141
+ 4. 更新 `test/inbound.test.ts`:
142
+ - 有 ASR:`sendUserMessage` 收到文本;`saveFiles` 未被调用;`markQQTrigger` 调用 1 次。
143
+ - 空 ASR:只回复提示;不发送 user message;不触发 run。
144
+ - 语音不产生文件保存调用。
145
+ - 文字、图片、文件现有用例不回归。
146
+
147
+ **验证**
148
+
149
+ - `npm test -- test/voice.test.ts test/inbound.test.ts` 通过。
150
+ - 语音消息不会出现在 `saveInboundFiles()` 的附件参数中。
151
+ - 空 ASR 不会启动 agent。
152
+
153
+ ### M5b-3 — F10 文件消息等待指令
154
+
155
+ **改动**
156
+
157
+ 1. `src/inbound.ts` 增加 pending 文件队列,仅处理非图片文件:
158
+ - 文件消息保存后入队,不回复,不调用 `sendUserMessage` / `markQQTrigger`。
159
+ - 下一条文字或语音 ASR 文本出队,合并后走现有 `formatFilePrompt()`。
160
+ - 消费后清空;`/new` 清空;其他命令不消费。
161
+ - 部分失败只入队成功文件;图片、普通文字、文件+文字行为不变。
162
+ 2. 更新 `test/inbound.test.ts`:
163
+ - 文件-only:保存、不回复、不发送 user message、不触发 run。
164
+ - 文件后文字:一次 run,提示词包含路径和文字。
165
+ - 连续文件:多个路径合并。
166
+ - 文件后语音:ASR 文本参与合并。
167
+ - `/new` 清空 pending。
168
+
169
+ **验证**
170
+
171
+ - `npm test -- test/inbound.test.ts` 通过。
172
+ - 文件-only 不启动 agent;下一条指令只启动一次。
173
+ - 图片行为与 v1 一致。
174
+
175
+ ### M5b-4 — F11 文件存储与去重
176
+
177
+ **改动**
178
+
179
+ 1. `src/inbound.ts`:文件保存路径改为 `<cwd>/.pi/pi-qq/<sessionId>/uploads/`,sessionId 来自 `ctx.sessionManager.getSessionId()`。
180
+ 2. `src/files.ts`:
181
+ - 增加 `.index.json` 读写:`{ "<fileName>": "<sha256>" }`。
182
+ - 文件名不重复:保存、计算 SHA-256、写索引、引用。
183
+ - 同名不同内容:保存为下一个可用后缀名,写索引、引用新文件。
184
+ - 同名同内容:不保存,复用已有路径。
185
+ - 登录/会话启动:只检查索引中的文件是否存在,删除失效项;不重算所有 hash。
186
+ - 保存/复用前再次检查目标文件存在性;索引缺失或损坏时按需计算已有文件 hash。
187
+ - `bot.ts` 的 message handler 必须 await `onMessage`,让 SDK concurrencyGuard 持有锁到文件保存完成。
188
+ 3. 更新 `test/files.test.ts` / `test/inbound.test.ts`:
189
+ - 路径、索引格式、三类保存规则。
190
+ - 删除文件后的索引清理与惰性回退。
191
+ - pending 同名同内容不重复入队;不同文件名同内容保留两份。
192
+
193
+ **验证**
194
+
195
+ - `npm test -- test/files.test.ts test/inbound.test.ts` 通过。
196
+ - 登录/会话启动只做存在性检查,不读取文件内容。
197
+ - 同名同内容不新增文件;同名不同内容生成后缀文件。
198
+
199
+ ### M5b-5 — 文档与清理
200
+
201
+ **改动**
202
+
203
+ 1. `README.md`:
204
+ - 设置表移除 `debug`,新增 `logLevel`(默认 `silent`)。
205
+ - 说明日志路径 `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`。
206
+ - Usage 增加语音:直接使用 QQ ASR,不保存语音文件。
207
+ 2. `doc/features-v2.md`:按最终实现校正配置、日志路径和验收项。
208
+ 3. 确认 `log/` 下历史调试日志不进入提交;不新增代码向 `log/` 写入。
209
+ 4. 检查全仓库不再有 `debug` 配置引用(迁移读取除外)。
210
+
211
+ **验证**
212
+
213
+ - README 的配置示例与实际 `getSettings` 一致。
214
+ - `rg "debug"` 只命中迁移代码、历史文档或无关的调试函数名。
215
+ - `npx prettier --check .` 通过。
216
+
217
+ ## 3. Todo-List
218
+
219
+ ### 准备
220
+
221
+ - [x] 阅读 `doc/features-v2.md`,确认范围仅为 F8/F9/F10/F11
222
+ - [x] 运行基线 `npm test`、`npm run typecheck`
223
+ - [x] 确认不新增 npm 依赖
224
+
225
+ ### F9 — 日志基础设施
226
+
227
+ - [x] `src/logger.ts`:级别、过滤、JSONL、按天单文件
228
+ - [x] `src/logger.ts`:`PI_QQ_LOG_DIR` 覆盖、写入失败降级
229
+ - [x] `src/logger.ts`:`sdkLogger` 适配器
230
+ - [x] `src/config.ts`:`logLevel` 默认 `silent`,旧 `debug` 迁移
231
+ - [x] `src/index.ts`:`configureLogger`、移除 `getDebug`
232
+ - [x] `src/bot.ts`:接入 `sdkLogger`,移除 `debug` 选项
233
+ - [x] `src/inbound.ts` / `src/outbound.ts`:日志分级
234
+ - [x] `src/run-feedback.ts`:移除 debug 时间戳,改用 logger
235
+ - [x] `test/logger.test.ts`:级别、文件名、截断、写入失败
236
+ - [x] `test/config.test.ts`:默认值、显式级别、旧配置迁移
237
+ - [x] `test/run-feedback.test.ts`:移除 debug 时间戳用例
238
+ - [x] 验证 silent / info / debug 三档行为
239
+
240
+ ### F8 — 语音自动转写
241
+
242
+ - [x] `src/voice.ts`:`isVoiceAttachment()`、`resolveVoiceTranscript()`
243
+ - [x] `test/voice.test.ts`:识别、trim、空值、多值合并
244
+ - [x] `src/inbound.ts`:语音分支前置
245
+ - [x] `src/inbound.ts`:有 ASR 发送文本,无 ASR 回复提示
246
+ - [x] `src/inbound.ts`:语音不下载、不保存、不走图片/文件
247
+ - [x] `test/inbound.test.ts`:有 ASR / 空 ASR / 不保存文件
248
+ - [x] 确认文字、图片、文件用例不回归
249
+
250
+ ### F10 — 文件等待指令
251
+
252
+ - [x] `src/inbound.ts`:pending 文件队列
253
+ - [x] 文件-only:保存后不回复,不启动 run
254
+ - [x] 下一条文字/语音:合并 pending 文件后注入
255
+ - [x] `/new` 清空 pending
256
+ - [x] `test/inbound.test.ts`:pending 队列相关用例
257
+ - [x] 图片、文字、文件+文字行为不回归
258
+ - [x] QQ 实机文件等待指令验收
259
+
260
+ ### F11 — 文件存储与去重
261
+
262
+ - [x] `inbound.ts`:session uploads 路径
263
+ - [x] `files.ts`:`.index.json` 读写
264
+ - [x] 文件名不重复:保存并索引
265
+ - [x] 同名不同内容:生成后缀文件
266
+ - [x] 同名同内容:复用已有文件
267
+ - [x] 登录/会话启动:清理不存在文件的索引项
268
+ - [x] 惰性检查:复用前确认文件仍存在
269
+ - [x] `test/files.test.ts` / `test/inbound.test.ts`:去重与索引用例
270
+ - [x] `bot.ts`:await message handler,确保文件保存串行
271
+ - [x] `test/bot.test.ts`:handler await 回归
272
+ - [x] QQ 实机文件去重验收(并发文件上传重测)
273
+
274
+ ### 文档与收尾
275
+
276
+ - [x] `README.md`:`logLevel`、日志路径、语音说明、文件等待指令、文件去重
277
+ - [x] `doc/features-v2.md`:F8/F9/F10/F11 与实现保持一致
278
+ - [x] 清理临时调试说明
279
+ - [x] `npm test`
280
+ - [x] `npm run typecheck`
281
+ - [x] `npm run format:check`
282
+ - [x] QQ 实机语音验收
283
+
284
+ ## 4. 整体验证标准
285
+
286
+ ### 自动化
287
+
288
+ - `npm test` 全部通过;新增 `logger` / `voice` / `inbound` 用例。
289
+ - `npm run typecheck` 无错误。
290
+ - `npm run format:check` 通过。
291
+ - 全仓库无第三方日志依赖,`package.json` 依赖不变。
292
+
293
+ ### 实机验收
294
+
295
+ 1. QQ 发送语音“测试”:pi 直接收到 `"测试。"`,不是 `.amr` / `.silk` 路径。
296
+ 2. 不出现 `ffmpeg`、`pilk`、`faster-whisper` 等工具调用。
297
+ 3. 工作区 `.pi/pi-qq/` 下不新增该语音文件。
298
+ 4. 发送无法识别的语音或模拟空 ASR:QQ 收到提示,pi 不启动 run。
299
+ 5. `logLevel: "silent"`:不产生日志文件。
300
+ 6. `logLevel: "debug"`:日志文件包含 `asr_refer_text` 和完整附件;`info` 不含正文。
301
+ 7. 旧配置 `debug: true` 仍能开启 debug 日志。
302
+ 8. 文字、图片、文件消息行为与 v1 一致。
303
+ 9. 只发文件:不回复,不启动 run。
304
+ 10. 文件后发文字/语音:只启动一次 run,提示词包含文件路径和指令。
305
+ 11. 连续上传多个文件:下一条指令合并全部文件。
306
+ 12. `/new` 后 pending 清空。
307
+ 13. 文件保存到 `.pi/pi-qq/<sessionId>/uploads/`。
308
+ 14. 文件名不重复:保存并引用。
309
+ 15. 同名不同内容:生成 `name-1.ext` 并引用。
310
+ 16. 同名同内容:不新增文件,复用已有路径。
311
+ 17. 删除文件后登录/会话启动清理索引,且不重算所有 hash。
312
+
313
+ ## 5. 风险与预案
314
+
315
+ | 风险 | 影响 | 预案 |
316
+ | ------------------------------ | --------------- | -------------------------------------------------- |
317
+ | ASR 为空或识别不准 | 语音无法转写 | 回复提示重发或打字;V2 不做语音回退 |
318
+ | 平台只返回 `voice` 的假定失效 | 语音分支不触发 | 以实测字段为准;若变化再扩展识别条件 |
319
+ | 日志目录不可写 | 无日志 | 捕获写入异常,消息处理继续 |
320
+ | 默认 `silent` 导致排查时无日志 | 诊断困难 | README 明确开启 `logLevel: "info"` / `"debug"` |
321
+ | 移除 debug 时间戳影响现有诊断 | QQ 气泡少时间戳 | 已确认日志级别不影响聊天展示;需要时后续加独立开关 |
322
+
323
+ ## 6. 执行记录
324
+
325
+ - 2026-10-30:M5a / M5b 代码与单测完成;`npm test` 97 项通过,`npm run typecheck`、`npm run format:check` 通过。
326
+ - 2026-10-30:QQ 实机语音验收通过。两条语音均直接使用 `asr_refer_text` 进入 pi;未保存 `.amr`,未调用本地转写工具;`logLevel: "debug"` 日志包含 ASR 元数据与全文。
327
+ - 2026-10-30:F10 文件等待指令实现完成;`npm test` 101 项通过,`typecheck`、`format:check` 通过。
328
+ - 2026-10-30:QQ 实机文件等待指令验收通过。文件-only 无回复、无 run;后续文字指令正确合并 1 个和 2 个 pending 文件并读取。
329
+ - 2026-10-30:F11 文件存储与去重实现完成;`npm test` 109 项通过,`typecheck`、`format:check` 通过。
330
+ - 2026-10-30:实机测试发现两条文件消息并发时索引互相覆盖(`c.txt` 文件存在但索引缺失)。根因是 `bot.ts` 的 message handler 未 await `onMessage`,导致 `concurrencyGuard` 提前释放锁。已修复并新增 `test/bot.test.ts`。
331
+ - 2026-10-30:F11 实机重测通过。`c.txt` / `b.txt` 快速连续上传后索引同时保留两项;`a.txt` / `d.txt` 不同文件名同内容按规则保留两份;索引共 4 项。
package/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { join } from "node:path";
2
3
  import { getSettings, readConfig, type Credentials } from "./src/config";
3
4
  import { startBot, type BotState, type RunningBot } from "./src/bot";
4
5
  import { runQrLogin } from "./src/login";
@@ -9,6 +10,8 @@ import { RunFeedback } from "./src/run-feedback";
9
10
  import { AppendStream } from "./src/append-stream";
10
11
  import { formatTokenCount } from "./src/format";
11
12
  import { formatBudgetStatus } from "./src/budget-status";
13
+ import { configureLogger, log, previewForLog } from "./src/logger";
14
+ import { pruneUploadIndex, sessionUploadDir } from "./src/files";
12
15
 
13
16
  /**
14
17
  * pi-qq extension entry.
@@ -48,7 +51,6 @@ const runFeedback = new RunFeedback({
48
51
  getHeartbeatMaxMessages: () => getSettings(readConfig().config).heartbeatMaxMessages,
49
52
  getStreamRelay: () => getSettings(readConfig().config).streamRelay,
50
53
  getStreamFlushMs: () => getSettings(readConfig().config).streamFlushMs,
51
- getDebug: () => getSettings(readConfig().config).debug,
52
54
  makeChannel: () => ({
53
55
  budget,
54
56
  boundOpenid: getLoginState()?.allowedOpenid ?? "",
@@ -89,16 +91,28 @@ export default function (pi: ExtensionAPI) {
89
91
 
90
92
  // —— Login and connection ——
91
93
 
92
- const startWithCredentials = (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
94
+ const startWithCredentials = async (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
93
95
  const settings = getSettings(readConfig().config);
96
+ configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
94
97
  running?.stop();
95
98
  stateDetail = undefined;
96
99
  sessionCtx = ctx;
100
+ const uploadDir = sessionUploadDir(ctx.cwd, ctx.sessionManager.getSessionId());
101
+ const uploadIndex = await pruneUploadIndex(uploadDir);
102
+ log.info("session", "starting bot", {
103
+ appId: creds.appId,
104
+ allowedOpenid,
105
+ cwd: ctx.cwd,
106
+ model: ctx.model?.name ?? null,
107
+ markdownSupport: settings.markdownSupport,
108
+ logLevel: settings.logLevel,
109
+ uploadDir,
110
+ indexedFiles: Object.keys(uploadIndex).length,
111
+ });
97
112
  running = startBot({
98
113
  credentials: creds,
99
114
  allowedOpenid,
100
115
  markdownSupport: settings.markdownSupport,
101
- debug: settings.debug,
102
116
  onMessage: createInboundHandler({
103
117
  pi,
104
118
  ctx,
@@ -134,19 +148,30 @@ export default function (pi: ExtensionAPI) {
134
148
 
135
149
  // —— Lifecycle ——
136
150
 
137
- pi.on("session_start", (_event, ctx) => {
138
- const { error } = readConfig();
151
+ pi.on("session_start", async (_event, ctx) => {
152
+ const { config, error } = readConfig();
153
+ const settings = getSettings(config);
154
+ configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
139
155
  if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
140
156
 
141
157
  const login = getLoginState();
158
+ log.info("session", "started", {
159
+ cwd: ctx.cwd,
160
+ hasUI: ctx.hasUI,
161
+ model: ctx.model?.name ?? null,
162
+ logLevel: settings.logLevel,
163
+ login: login ? { appId: login.credentials.appId, allowedOpenid: login.allowedOpenid } : null,
164
+ configError: error ?? null,
165
+ });
142
166
  if (login) {
143
- startWithCredentials(ctx, login.credentials, login.allowedOpenid);
167
+ await startWithCredentials(ctx, login.credentials, login.allowedOpenid);
144
168
  } else if (ctx.hasUI) {
145
169
  ctx.ui.notify("pi-qq: run /qq-login to scan a QR code.", "warning");
146
170
  }
147
171
  });
148
172
 
149
173
  pi.on("session_shutdown", () => {
174
+ log.info("session", "shutting down");
150
175
  stopIfRunning();
151
176
  sessionCtx = undefined;
152
177
  runFeedback.dispose();
@@ -155,18 +180,31 @@ export default function (pi: ExtensionAPI) {
155
180
  // F7 run feedback: agent lifecycle / tool counts / text streaming.
156
181
 
157
182
  pi.on("agent_start", () => {
183
+ log.info("agent", "run started");
158
184
  runFeedback.onAgentStart();
159
185
  });
160
186
 
161
187
  pi.on("agent_end", () => {
188
+ log.info("agent", "run ended");
162
189
  void runFeedback.onAgentEnd();
163
190
  });
164
191
 
165
192
  pi.on("tool_execution_start", (event) => {
193
+ log.debug("tool", "start", {
194
+ toolName: event.toolName,
195
+ toolCallId: event.toolCallId,
196
+ args: previewForLog(event.args),
197
+ });
166
198
  void runFeedback.onToolStart(event.toolName);
167
199
  });
168
200
 
169
201
  pi.on("tool_execution_end", (event) => {
202
+ log.debug("tool", "end", {
203
+ toolName: event.toolName,
204
+ toolCallId: event.toolCallId,
205
+ isError: event.isError,
206
+ result: previewForLog(event.result),
207
+ });
170
208
  runFeedback.onToolEnd(event.toolName, event.isError);
171
209
  });
172
210
 
@@ -190,13 +228,24 @@ export default function (pi: ExtensionAPI) {
190
228
  const msg = event.message;
191
229
  if (msg.role !== "assistant" || !running) return;
192
230
 
231
+ log.debug("pi", "assistant message ended", {
232
+ stopReason: msg.stopReason,
233
+ contentTypes: msg.content.map((block) => block.type),
234
+ textPreview: previewForLog(
235
+ msg.content
236
+ .filter((block) => block.type === "text")
237
+ .map((block) => block.text)
238
+ .join("\n"),
239
+ ),
240
+ });
241
+
193
242
  const { config } = readConfig();
194
243
  const settings = getSettings(config);
195
244
  const isError = msg.stopReason === "error";
196
245
 
197
246
  let text: string;
198
247
  if (isError) {
199
- text = `⚠️ 模型调用失败:${msg.errorMessage ?? "未知错误"}`;
248
+ text = `⚠️ Model error: ${msg.errorMessage ?? "unknown error"}`;
200
249
  } else {
201
250
  text = msg.content
202
251
  .filter((b) => b.type === "text")
@@ -205,6 +254,7 @@ export default function (pi: ExtensionAPI) {
205
254
  .trim();
206
255
  }
207
256
  if (!text) {
257
+ log.debug("pi", "assistant message has no text", { isError });
208
258
  // Textless assistant messages also end the feedback turn: reset thinking state
209
259
  // and flush pending thinking rows so the next message does not swallow them.
210
260
  await runFeedback.onAssistantFinal("", isError);
@@ -212,16 +262,20 @@ export default function (pi: ExtensionAPI) {
212
262
  }
213
263
 
214
264
  // F7 stream takeover: stream frames render Markdown; send raw text so lengths match.
215
- if (await runFeedback.onAssistantFinal(text, isError)) return;
265
+ const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
266
+ log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
267
+ if (streamTookOver) return;
216
268
 
217
269
  const payload = settings.markdownSupport ? text : markdownToPlain(text);
218
270
 
219
271
  const bound = getLoginState()?.allowedOpenid;
220
272
  if (!bound) {
273
+ log.warn("pi", "no bound user; reply skipped");
221
274
  ctx.ui.notify("pi-qq: no bound QQ user; skipping reply.", "warning");
222
275
  return;
223
276
  }
224
277
 
278
+ log.info("pi", "sending reply", { textLength: text.length, payloadLength: payload.length });
225
279
  void sendReply(running.bot, payload, {
226
280
  budget,
227
281
  boundOpenid: bound,
@@ -248,7 +302,7 @@ export default function (pi: ExtensionAPI) {
248
302
 
249
303
  const credentials: Credentials = { appId: result.appId, appSecret: result.appSecret };
250
304
  setLoginState({ credentials, allowedOpenid: result.userOpenid });
251
- startWithCredentials(ctx, credentials, result.userOpenid);
305
+ await startWithCredentials(ctx, credentials, result.userOpenid);
252
306
  },
253
307
  });
254
308
 
@@ -271,7 +325,7 @@ export default function (pi: ExtensionAPI) {
271
325
  handler: async (_args, ctx) => {
272
326
  stopIfRunning();
273
327
  setLoginState(undefined);
274
- ctx.ui.notify("pi-qq logged out. Credentials cleared from memory; run /qq-login to scan again.", "info");
328
+ ctx.ui.notify("pi-qq logged out.", "info");
275
329
  },
276
330
  });
277
331
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
@@ -31,7 +31,7 @@ export interface AppendStreamOptions {
31
31
  retryBaseMs?: number;
32
32
  /** Background throttle flush failure (stream is no longer trusted). */
33
33
  onError?: (err: Error) => void;
34
- /** Diagnostic log (debug mode): rate-limit retries/final failures. */
34
+ /** Diagnostic log via the shared logger: rate-limit retries/final failures. */
35
35
  onDebug?: (message: string) => void;
36
36
  }
37
37
 
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,48 @@ 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));
68
- bot.on("message", (_ctx, msg) => {
69
- void opts.onMessage?.(bot, msg);
82
+ bot.on("error", (err) => {
83
+ log.error("bot", "error event", { err });
84
+ opts.onRecoverableError?.(err);
85
+ });
86
+ bot.on("message", async (_ctx, 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
+ try {
106
+ await opts.onMessage?.(bot, msg);
107
+ } catch (err) {
108
+ log.error("bot", "message handler rejected", { err });
109
+ }
70
110
  });
71
111
 
72
112
  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
  }