@chen_hu_hu/pi-qq 1.7.0 → 1.7.2

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/todo.md CHANGED
@@ -1,212 +1,39 @@
1
1
  # TODO
2
2
 
3
- > 2026-11-06 更新:已基于 2026-11-05 / 2026-11-06 的真实使用记录完成首轮分析。TODO 1 的启动帧和参数传递已确认正常;TODO 2 仍未复现,等待真正的多分钟单命令日志。详见各条目的“日志验证结果”。
3
+ > 只记录未完成项目;已完成项目直接删除,不使用勾选状态。
4
+ > 1.7.1 交付记录:`doc/archive/delivery.1.7.1.md`
4
5
 
5
- ## 1. 长运行 bash 工具的参数延迟显示
6
+ ## 1. 超长 bash 命令在 QQ 的渲染
6
7
 
7
- > 状态:启动帧已验证正常;待确认 QQ 客户端渲染
8
- > 记录日期:2026-11-04
9
- > 分析日期:2026-11-06
10
- > 相关版本:pi-qq 1.3.6(仅增加 debug 日志);本次日志来自 1.4.0 之后的版本
8
+ > 状态:待一次长命令确认
9
+ > 记录日期:2026-11-04;更新:2026-11-19
11
10
 
12
- ### 现象
11
+ 2026-11-19 的 11 分钟 `sleep 660` 在真实 QQ 上完整显示了 `## 💻 bash` 和命令代码块,说明长运行工具的启动帧与 fenced block 正常,未退化成“bash 和一个点”。
13
12
 
14
- 正常使用中,bash 执行 e2e 测试通常需要数分钟。此时 QQ 上只能看到 `bash` 和一个点,看不到命令参数;理论上工具名称和参数应该在 `tool_execution_start` 后立即出现,只有结果需要等待工具结束。
13
+ 尚未确认:数百到上千字符的超长命令是否会被客户端折叠。
15
14
 
16
- ### 已知事实
15
+ - relay 侧无问题:启动帧在工具开始后 1.1–3.2 s 内发出,参数完整;延迟来自旧气泡 DONE + 新流 RTT,不是队列积压。
16
+ - 下一步:用一条 500+ 字符的命令做 A/B(带 `bash` 语言标记 / 无语言标记 / 行内代码),确认折叠行为;正常则删除本节。
17
17
 
18
- - `AppendStream` 默认有 500ms 节流;这是 pi-qq 自己设置的值,不是 QQ 限制。
19
- - 500ms 定时器不依赖工具 Promise;长工具的启动帧曾在工具结束前通过 `stream_messages` 发出。
20
- - pi 内置 bash 使用异步 `spawn`,正常情况下不会阻塞 Node 事件循环。
21
- - 本地异步子进程可持续触发 500ms timer,说明“bash 子进程本身”不是必然的事件循环阻塞源。
22
- - 2026-11-05 的真实使用记录已覆盖启动帧、`content_raw`、timer/队列和事件循环;但最长单条 bash 只有 94 秒的 docker build,仍没有“数分钟 e2e”样本。分析结果见下文。
18
+ ## 2. 流式消息生命周期的长期观察
23
19
 
24
- ### 已经添加的诊断日志
20
+ > 状态:持续观察;仅保留尚未验证的长期风险
25
21
 
26
- 版本 1.3.6 只增加了 debug 日志,没有改变行为:
22
+ 已确认:总生命周期约 600 秒;过期后同 `msg_id` 新流可恢复;11 分钟静默工具验证了 `40034020` → 新流 → 重放缓冲 → 结果送达(2026-11-19,660 s);20 分钟同 `msg_id` 新流已验证(1203.5 s)。
27
23
 
28
- - `scope: "stream"`,`msgKey: "log.streamTiming"`:
29
- - `phase: "tool queued"`:工具行进入队列;
30
- - `phase: "append start"`:队列开始处理,包含 `waitedMs`;
31
- - `phase: "append done"`:队列处理完成,包含 `totalMs`。
32
- - `AppendStream.onDebug`(同 scope `"stream"`):
33
- - `append: buffered/immediate/while flushing`;
34
- - `timer: fired after ...`;
35
- - `flush: start/done`。
36
- - `scope: "event-loop"`,`msgKey: "log.eventLoopDelay"`:
37
- - 每 5 秒记录一次 `meanMs`、`maxMs`、`p99Ms`。
24
+ 待观察:
38
25
 
39
- 所有日志只在 `logLevel: "debug"` 时写入:
26
+ - 超过 20 分钟的同 `msg_id` 新流;1 小时以上的 `msg_id`;
27
+ - 生命周期是否随账号、地区、客户端版本变化;
28
+ - 真实网络抖动、重连、限流下 `40034020` 的恢复是否稳定送达。
40
29
 
41
- ```json
42
- {
43
- "logLevel": "debug"
44
- }
45
- ```
30
+ 实验记录见 `doc/archive/delivery.1.7.1.md`。
46
31
 
47
- 日志路径:
32
+ ## 3. 调试日志的剩余优化
48
33
 
49
- ```text
50
- <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
51
- ```
34
+ > 状态:不阻塞;等下一次真实日志评估
35
+ > 记录日期:2026-11-19
52
36
 
53
- ### 日志验证结果(2026-11-06)
54
-
55
- 基于 2026-11-05 / 2026-11-06 的真实使用记录(`logLevel: "debug"`)验证。11-05 有 4 个 QQ 触发的 run(约 8 / 21 / 29 / 23 分钟),共 529 个启动帧(483 个工具行 + 46 个 skill 块)。
56
-
57
- **启动帧确实发出,且带完整参数:**
58
-
59
- - 94.2 秒的 docker build:
60
- - 11:49:38.449 `tool start`,`args` 包含完整 `command`;
61
- - 11:49:39.032 发出 `POST .../stream_messages`,`content_raw` 以 `## 💻 bash` 开头,命令放在 `bash` fenced code block 中,完整内容为 `cd .../xuanji-mock && docker compose ... build 2>&1 | tail -6`;
62
- - 11:49:39.643 收到 200 OK;
63
- - 工具在 11:51:12.689 才结束,结果帧在 11:51:12.690 发出、11:51:13.323 收到 200。
64
- - 529 个启动帧全部能在 `stream_messages` 请求体中找到:
65
- `93 bash + 194 write + 150 read + 28 codemode + 18 edit + 46 skill = 529`。
66
- - 最长的 bash 命令为 1108 字符;`content_raw` 为完整的 1134 字符(标题 + fence + 命令),没有被截断。
67
- - `append start` 的 `waitedMs` 最大 1ms;`append done` 的 `totalMs` 中位数约 1.3s、最大 2.1s。延迟来自关旧气泡、开新流和网络往返,不是队列积压。
68
- - 94s 工具的启动帧不是被 500ms 节流拖住的:日志为 `append: immediate`,`flush` 在 `stream open` 后立即开始。
69
- - QQ run 期间 `event-loop` 的 `maxMs` 最大 258ms,`driftMs` 最大 82ms;没有数秒级阻塞。
70
-
71
- **结论:** 在这些日志覆盖的场景中,TODO 1 中列出的四种可能——启动帧没发出、`content_raw` 没命令、queue/timer 延迟、事件循环饥饿——均不成立。pi-qq 侧在工具开始后约 1.2 秒内已经把带完整命令的启动帧交给 QQ API。
72
-
73
- ### 尚未验证
74
-
75
- - QQ 客户端如何渲染这个 fenced code block。日志只能证明请求体里有完整命令,不能证明手机 QQ 一定把代码块展开显示。
76
- - 如果手机 QQ 仍只显示“bash 和一个点”,优先检查 QQ 对带 `bash` 语言标记的 fenced block、长代码块或新气泡的折叠/渲染,而不是继续排查 relay。
77
-
78
- ### 下一步
79
-
80
- - 不需要给工具启动行增加 `flushAfter`;当前无队列/节流延迟证据。
81
- - 做一次 QQ 渲染 A/B:同一命令分别用带 `bash` 语言标记的 fenced block、无语言标记的 fenced block、行内代码发送,确认是否只在某种格式下显示异常。
82
- - 如果确认是 QQ 渲染问题,再考虑缩短命令摘要或改用普通文本/行内代码;如果确认正常,可直接关闭 TODO 1。
83
- - 若最终需要改格式,补测试并更新 `CHANGELOG.md`,再发布版本。
84
-
85
- ## 2. 长耗时命令导致 QQ 侧无输出/失去响应
86
-
87
- > 状态:仍未复现;等待多分钟单命令日志
88
- > 记录日期:2026-11-04
89
- > 分析日期:2026-11-06
90
- > 相关版本:pi-qq 1.4.0
91
- > 详细调研:`doc/archive/delivery.1.4.0.md`
92
-
93
- ### 现象
94
-
95
- QQ 侧执行一个运行数分钟到数十分钟的 `bash` 命令后,可能只有最初的工具气泡,之后:
96
-
97
- - 命令结束没有工具结果;
98
- - 没有最终回答;
99
- - 长命令期间发送普通消息,直到命令结束才有反应;
100
- - 看起来像机器人“失去响应”,但电脑上的 pi TUI 仍在运行。
101
-
102
- ### 已知事实
103
-
104
- - pi 的 bash 工具使用异步 `spawn`,长时间运行的普通命令本身不会阻塞 Node 事件循环。
105
- - 长工具期间 pi-qq 不订阅 `tool_execution_update`,所以没有进度帧;只有 50 秒一次的 `typing`。
106
- - 每个思考/工具气泡都会新建一条流式回复,但 `ReplyBudget` 只统计普通文本,没有把流式气泡计入 4 次被动回复上限。
107
- - 长静默后的结果帧如果因 `msg_id` 过期或被动次数超限失败,`BubbleWriter` 会沿用同一个过期 `msg_id` / `stream_msg_id` resume,最终 `killStream()`;之后 `onToolStart()` / `onToolEnd()` 直接早退,后续工具输出丢失。
108
- - 运行中收到的普通消息以 `steer` 进入当前 run,要等当前工具批次结束才处理。
109
- - `/stop` 目前要等 `waitForEnd()` 才回复;如果工具不响应 abort 或流式请求在重试,会占住 SDK 的并发锁。
110
-
111
- ### 临时恢复手段
112
-
113
- QQ 侧的 `/last` 已可用于手动恢复:
114
-
115
- - **run 运行中**:`/last` 调用 `RunFeedback.repushCurrent()`,把当前输出重推到新消息的 `msg_id` 上,并让后续 delta 继续写入新气泡;
116
- - **run 已结束**:`/last` 用流式重新推送最近一次完成的 assistant 文本。
117
-
118
- 因此本次不实现行为修复;`/last` 作为用户可用的手动恢复路径。
119
-
120
- ### 本次决策
121
-
122
- - 暂不实施 v4 归档中的错误分类、预算、心跳、自动重绑等行为修改。
123
- - 只追加可验证的 debug 日志,等待长期使用日志后再决定修复范围。
124
- - 2026-11-06 首轮日志未复现失败路径,继续维持“只加日志、不改行为”的决定;详见“日志验证结果”。
125
- - 新增诊断日志在 `logLevel: "debug"` 时写入;`stream error` / `stream unavailable` 原本就是 `warn`,保留为错误记录,不改变行为。
126
-
127
- ### 已追加的诊断日志
128
-
129
- - `scope: "tool"`:
130
- - `start` / `end` 增加 `parentToolCallId`、`durationMs`;
131
- - `end` 增加 `updateCount`、`updateSpanMs`、`firstPartial`;
132
- - `update` 记录首次部分输出,之后每 50 次记录一次进度。
133
- - `scope: "run"`:
134
- - `run started`:`phase: "no qq target"`、`source: pending/recovery`、`targetAgeMs`;
135
- - `tool start` / `tool end`:`phase: queued / output started / result recorded / output finished / ignored: stream dead / ignored: no active run`;
136
- - `stream takeover decision`:`textLength`、`deltaLength`、`hadPendingTools`、`flushOk`、`hasPushed`、`streamTookOver`、`deferredTextLen`;
137
- - `run ended`:`hasPendingTools`、`hasPushed`、`lastCompletedTextLength`;
138
- - `stream timing`:`phase: last repush / last repush ignored`;
139
- - 工具、最终消息和 cleanup 相关日志都带 `diagnostics`:`activeTool`、`tools`、`deferredTextLen`、`writer stats`、`budget`。
140
- - `scope: "stream"`:
141
- - `stream timing` 的 `stats` 包含 `dead`、`hasStream`、`hasPendingResume`、`resumeAttempts`、`bubbleChars`、`hasPushed`、`lastKind`、`toolOpen`、`lastFrameAgeMs`;
142
- - `stream open` 记录是否 resume、checkpoint 的 `index` / `hasStreamMsgId` / `bufferLength`、`budget`;
143
- - `stream error` 增加 `phase: "frame failed"`,记录 `httpStatus`、`bizCode`、`path`、`msgSeq`、`streamMsgId`、`bufferLength`;
144
- - `stream unavailable` 记录 writer `stats` 和 `budget`;
145
- - `sendStreamReply()`(idle `/last`)记录 `phase: "last reply stream"`、`msgId`、`textLength`。
146
- - `AppendStream` 的 `flush start/done` 增加 `msgSeq` 和 `streamMsgId`(存在时)。
147
- - `scope: "inbound"`:`/stop` 记录 `wait start` / `wait done` 及 `waitedMs`。
148
- - `scope: "event-loop"`:增加 `driftMs`,用于发现 timer 被事件循环延迟。
149
-
150
- ### 日志验证结果(2026-11-06)
151
-
152
- 基于 2026-11-05 / 2026-11-06 的真实使用记录验证。
153
-
154
- **没有复现失败:**
155
-
156
- - 最长的单条命令是 94.2 秒的 docker build;其余 e2e jest 命令为 4.2–6.8 秒。日志中没有“数分钟到数十分钟”的单条 bash。
157
- - 94s 工具期间从启动帧到结果帧有 93.7 秒没有新流式帧,说明长工具确实没有进度帧;但结果帧在工具结束后 0.6 秒发出并收到 200,没有丢失。
158
- - `stream error` / `stream unavailable` / `phase: "frame failed"`:0 条。
159
- - TODO 点名的错误码 `304103`、`40034005`、`40034128`、`40034024`、`429`、`50002`:0 次。
160
- - 529 个工具全部有 `queued → output started → result recorded → output finished`,没有 `ignored: stream dead`。
161
- - 4 个 run 结束时均为 `dead=false`、`hasPendingResume=false`、`resumeAttempts=0`、`hasPendingTools=false`、`hadError=false`;2055 组 `AppendStream` 的 `flush start/done` 一一对应。
162
- - 2026-11-05 有 4 个 QQ run:约 8 / 21 / 29 / 23 分钟;29 分钟的 run 结束时 `streamBubbles=184`、`streamBubblesTotal=502`,但 `budget.remaining=4`。这验证了“流式气泡没有计入 4 次被动回复上限”这个前提,但没有观察到因此失败;同一 `msg_id` 在数十分钟内仍能继续发流式帧。
163
- - `/last` 有 3 次有效调用,全部在 run 已结束后:分别重发 1410、2320、1827 字符,均收到 200 + done。没有 `last repush`(运行中恢复)记录。日志中没有运行中收到的普通消息,也没有 `/stop`,所以 steer 阻塞和非阻塞 `/stop` 仍未验证。
164
- - 2026-11-06 的 `event-loop maxMs=41,266,045.8` 样本与机器休眠/恢复一致,不是事件循环被阻塞 11 小时:它出现在 23:32:06.970,与 WebSocket 1006 关闭/重连同一时刻,下一次采样已回到 259ms。
165
-
166
- **结论:** 这些日志不能验证“长命令后 QQ 无输出/失去响应”的失败路径,也不能据此实施错误分类、预算或自动重绑修复。它们只支持两个前提:长工具期间没有进度帧;流式气泡没有计入被动回复预算。真正的触发条件仍需一次单条命令运行数分钟(最好 >5 分钟,甚至 >1 小时)的日志。
167
-
168
- ### 复现时仍需采集/分析
169
-
170
- 本次日志没有出现这些错误,以下步骤保留给下次复现时使用。
171
-
172
- 1. 找到长命令的 `scope: "tool"` `start` / `end`:
173
- - `durationMs` 是否与用户感知一致;
174
- - `updateCount` 是否为 0,判断长命令期间是否完全没有部分输出。
175
- 2. 看 `scope: "stream"` 的 `stream timing`:
176
- - `tool queued` 时间;
177
- - `append start` 的 `waitedMs` / `lastFrameAgeMs`;
178
- - `append done` 的 `totalMs`;
179
- - 工具结束到结果帧之间隔了多久。
180
- 3. 看 `stream error` 的 `phase: "frame failed"`:
181
- - `httpStatus` / `bizCode` 是否为 `304103`、`40034005`、`40034128`、`40034024`、`429`、`50002`;
182
- - `streamMsgId` 是否存在,`bufferLength` 是否持续增长。
183
- 4. 看 `stream unavailable` 之后 `scope: "run"` 的:
184
- - `tool start/end` 是否出现 `ignored: stream dead`;
185
- - `stream takeover decision` 的 `flushOk` / `hasPushed` / `hadPendingTools`;
186
- - `run ended` 的 `hasPendingTools`。
187
- 5. 如果用户使用了 `/last`,看 `phase: "last repush"` 或 `"last repush ignored"`,确认是否恢复、恢复后是否仍有输出。
188
- 6. 看 `scope: "event-loop"` 的 `maxMs` / `p99Ms` / `driftMs`:
189
- - 如果达到数秒甚至更高,优先排查 CPU 饥饿;
190
- - 如果正常,则更可能是 QQ 被动窗口/配额或 relay 状态问题。
191
- 7. 对照 `/qq-test-budget` 的 `remaining`、`streamBubbles`、`streamBubblesTotal`,确认是否早已超过 4 次。
192
-
193
- ### 需要提供的信息
194
-
195
- 本次日志没有覆盖多分钟单命令、运行中收到的普通消息、`/stop` 和 `/qq-test-budget` 输出;复现时请按以下清单提供:
196
-
197
- - `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`;
198
- - 长命令内容、开始时间和结束时间;
199
- - QQ 上最后一条可见消息及时间;
200
- - 期间是否发送过 `/status`、`/stop`、普通文本、`/last`;
201
- - `/qq-test-budget` 和 `/qq-status` 输出;
202
- - 手机 QQ 是否在前台,是否允许主动消息。
203
-
204
- ### 下一步
205
-
206
- - 本次日志未复现失败;不要据此实施错误分类、预算或自动重绑修复。
207
- - 继续等待一次真正的多分钟单命令日志(最好 >5 分钟,并覆盖 >1 小时的 `msg_id` 生命周期);复现时按上面的“复现时仍需采集/分析”执行。
208
- - 如果目标只是改善长工具期间的体感:优先实现长工具心跳和 `tool_execution_update` 转发,这不依赖失败复现。
209
- - 如果后续日志确认 `msg_id` 过期/被动次数超限:再按 `doc/archive/delivery.1.4.0.md` 的“Long-running tools”建议实现错误分类和预算修复。
210
- - 如果 `/stop` 的 `wait done` 缺失或 `waitedMs` 很大:实现非阻塞 `/stop`。
211
- - `/last` 目前作为手动兜底可用,保持现状,不急于自动重绑。
212
- - 修复后补测试,更新 `doc/todo.md` / `CHANGELOG.md`,再发布版本。
37
+ - typing 真实网络超时:流活跃时已跳过 typing,但 10 s 超时尚未在真实网络复现。
38
+ - event-loop 日志占比:2026-11-19 的 11 分钟 run 中占 26.2 KiB / 43.6 KiB(133 行)。可评估只在 `maxMs` 超阈值或降频(如 30 s)时记录。
39
+ - `/status` 回复未落日志:非 run 期间 `outbound` / `qqbot` scope 被门控关闭。若要排查命令回复,可允许 `outbound` 常驻(仅 `targetId` 和长度)。
package/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { join } from "node:path";
3
- import { monitorEventLoopDelay } from "node:perf_hooks";
3
+ import { monitorEventLoopDelay, performance } from "node:perf_hooks";
4
4
  import { getSettings, readConfig, type Credentials, type ResolvedSettings } from "./src/infra/settings";
5
5
  import { startBot, type BotState, type RunningBot } from "./src/qq/qq-bot";
6
6
  import { runQrLogin, type QrLoginResult } from "./src/qq/qr-login";
@@ -9,7 +9,7 @@ import { registerQQDiagnostics } from "./src/qq/qq-diagnostics";
9
9
  import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
10
10
  import { ReplyBudget } from "./src/quota/reply-quota";
11
11
  import { RunFeedback } from "./src/relay/run-stream-relay";
12
- import { configureLogger, flushLogs, isLogEnabled, log, previewForLog, setLogGate } from "./src/infra/file-logger";
12
+ import { configureLogger, flushLogs, isLogEnabled, log, logValueLength, setLogGate } from "./src/infra/file-logger";
13
13
  import { configureI18n, t } from "./src/infra/i18n";
14
14
  import { getPowerStatus } from "./src/infra/power-status";
15
15
  import { formatStatusReport } from "./src/qq/status-report";
@@ -49,14 +49,15 @@ const runFeedback = new RunFeedback({
49
49
  onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
50
50
  });
51
51
 
52
- const eventLoopDelay = monitorEventLoopDelay({ resolution: 100 });
52
+ // Node's histogram mean has a floor roughly equal to `resolution` (observed as
53
+ // milliseconds on Node 24), so a large resolution hides real delay. Keep 1 ms.
54
+ const eventLoopDelay = monitorEventLoopDelay({ resolution: 1 });
53
55
  let eventLoopTimer: ReturnType<typeof setInterval> | undefined;
54
56
 
55
57
  interface ToolUpdateStats {
56
58
  count: number;
57
59
  firstAt: number;
58
60
  lastAt: number;
59
- firstPartial: string;
60
61
  }
61
62
 
62
63
  const toolUpdateStats = new Map<string, ToolUpdateStats>();
@@ -76,15 +77,19 @@ function startEventLoopMonitor(): void {
76
77
  eventLoopDelay.reset();
77
78
  eventLoopDelay.enable();
78
79
  let lastTickAt = Date.now();
80
+ let lastElu = performance.eventLoopUtilization();
79
81
  eventLoopTimer = setInterval(() => {
80
82
  const now = Date.now();
81
83
  const driftMs = now - lastTickAt - 5_000;
82
84
  lastTickAt = now;
85
+ const elu = performance.eventLoopUtilization(lastElu);
86
+ lastElu = performance.eventLoopUtilization();
83
87
  log.debug("event-loop", "event loop delay", {
84
88
  meanMs: roundMs(eventLoopDelay.mean),
85
89
  maxMs: roundMs(eventLoopDelay.max),
86
90
  p99Ms: roundMs(eventLoopDelay.percentile(99)),
87
91
  driftMs,
92
+ utilizationPercent: Math.round(elu.utilization * 1000) / 10,
88
93
  });
89
94
  eventLoopDelay.reset();
90
95
  }, 5_000);
@@ -98,7 +103,14 @@ function stopEventLoopMonitor(): void {
98
103
  }
99
104
 
100
105
  export default function (pi: ExtensionAPI) {
101
- setLogGate(() => Boolean(getLoginState()) && runFeedback.isQQRunActive());
106
+ setLogGate((scope) => {
107
+ if (scope === "login") return true;
108
+ if (!getLoginState()) return false;
109
+ // The message that starts a run arrives before the run becomes active.
110
+ if (scope === "inbound") return true;
111
+ if (scope === "session" || scope === "bot" || scope === "power") return true;
112
+ return runFeedback.isQQRunActive();
113
+ });
102
114
 
103
115
  const notifyConfigError = (ctx: ExtensionContext, error: string | undefined, dedupe: boolean) => {
104
116
  if (!error) {
@@ -135,7 +147,7 @@ export default function (pi: ExtensionAPI) {
135
147
 
136
148
  const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
137
149
 
138
- const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
150
+ const getStatusLines = async (ctx: ExtensionContext | undefined = sessionCtx): Promise<string[]> => {
139
151
  const login = getLoginState();
140
152
  const usage = ctx?.getContextUsage();
141
153
  return formatStatusReport({
@@ -153,7 +165,7 @@ export default function (pi: ExtensionAPI) {
153
165
  percent: usage.percent,
154
166
  }
155
167
  : undefined,
156
- power: getPowerStatus(),
168
+ power: await getPowerStatus(),
157
169
  replyType: activeSettings.replyType,
158
170
  });
159
171
  };
@@ -282,7 +294,7 @@ export default function (pi: ExtensionAPI) {
282
294
  toolCallId: event.toolCallId,
283
295
  parentToolCallId: event.parentToolCallId ?? null,
284
296
  at: Date.now(),
285
- args: previewForLog(event.args),
297
+ argsLength: logValueLength(event.args),
286
298
  });
287
299
  }
288
300
  void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
@@ -297,7 +309,6 @@ export default function (pi: ExtensionAPI) {
297
309
  count: 1,
298
310
  firstAt: now,
299
311
  lastAt: now,
300
- firstPartial: previewForLog(event.partialResult, 300),
301
312
  };
302
313
  toolUpdateStats.set(event.toolCallId, first);
303
314
  log.debug("tool", "update", {
@@ -305,7 +316,7 @@ export default function (pi: ExtensionAPI) {
305
316
  toolName: event.toolName,
306
317
  toolCallId: event.toolCallId,
307
318
  count: 1,
308
- partial: first.firstPartial,
319
+ partialLength: logValueLength(event.partialResult),
309
320
  });
310
321
  return;
311
322
  }
@@ -334,8 +345,7 @@ export default function (pi: ExtensionAPI) {
334
345
  durationMs: event.durationMs ?? null,
335
346
  updateCount: updates?.count ?? 0,
336
347
  updateSpanMs: updates ? updates.lastAt - updates.firstAt : null,
337
- firstPartial: updates?.firstPartial ?? null,
338
- result: previewForLog(event.result),
348
+ resultLength: logValueLength(event.result),
339
349
  });
340
350
  }
341
351
  runFeedback.onToolEnd(event.toolName, event.isError, event.result, event.toolCallId);
@@ -367,12 +377,10 @@ export default function (pi: ExtensionAPI) {
367
377
  hasLogin: Boolean(getLoginState()),
368
378
  stopReason: msg.stopReason,
369
379
  contentTypes: msg.content.map((block) => block.type),
370
- textPreview: previewForLog(
371
- msg.content
372
- .filter((block) => block.type === "text")
373
- .map((block) => block.text)
374
- .join("\n"),
375
- ),
380
+ textLength: msg.content
381
+ .filter((block) => block.type === "text")
382
+ .map((block) => block.text)
383
+ .join("\n").length,
376
384
  });
377
385
  }
378
386
  if (!running || !fromQQ) return;
@@ -397,7 +405,7 @@ export default function (pi: ExtensionAPI) {
397
405
 
398
406
  const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
399
407
  if (isLogEnabled("debug")) {
400
- log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
408
+ log.debug("pi", "stream takeover decision", { streamTookOver, isError, textLength: text.length });
401
409
  }
402
410
  if (streamTookOver) return;
403
411
 
@@ -452,7 +460,7 @@ export default function (pi: ExtensionAPI) {
452
460
  pi.registerCommand("qq-status", {
453
461
  description: t("commands.descQqStatus"),
454
462
  handler: async (_args, ctx) => {
455
- ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
463
+ ctx.ui.notify((await getStatusLines(ctx)).join("\n"), "info");
456
464
  },
457
465
  });
458
466
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
@@ -1,6 +1,7 @@
1
1
  import { appendFile, mkdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { logMessageKey } from "./log-message-keys";
4
+ import { shortId } from "./short-id";
4
5
 
5
6
  export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
6
7
  type LogFields = Record<string, unknown>;
@@ -18,7 +19,7 @@ const DEFAULT_LOG_LEVEL: LogLevel = "silent";
18
19
  let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
19
20
  let activeDir: string | undefined;
20
21
  let writeQueue: Promise<void> = Promise.resolve();
21
- let logGate: (() => boolean) | undefined;
22
+ let logGate: ((scope: string) => boolean) | undefined;
22
23
 
23
24
  function isLogLevel(value: unknown): value is LogLevel {
24
25
  return typeof value === "string" && Object.hasOwn(LEVEL_WEIGHT, value);
@@ -45,19 +46,67 @@ export function configureLogger(level: LogLevel, dir?: string): void {
45
46
  activeDir = dir;
46
47
  }
47
48
 
48
- export function setLogGate(gate: (() => boolean) | undefined): void {
49
+ export function setLogGate(gate: ((scope: string) => boolean) | undefined): void {
49
50
  logGate = gate;
50
51
  }
51
52
 
52
- function isLogAllowed(): boolean {
53
+ function isLogAllowed(scope: string): boolean {
53
54
  if (!logGate) return true;
54
55
  try {
55
- return logGate();
56
+ return logGate(scope);
56
57
  } catch {
57
58
  return false;
58
59
  }
59
60
  }
60
61
 
62
+ const REDACTED = "<redacted>";
63
+ const SECRET_KEY_RE =
64
+ /^(?:password|passwd|pwd|secret|token|session|sessionId|cookie|authorization|api[_-]?key|client[_-]?secret|app[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key)$/i;
65
+ const SHORT_ID_KEYS = new Set(["messageId", "msgId", "streamMsgId"]);
66
+ // Platform IDs are long; shorter values are already short or synthetic.
67
+ const FULL_ID_MIN_LENGTH = 16;
68
+
69
+ /** Redact common credential shapes while keeping the surrounding log text. */
70
+ export function redactLogText(text: string): string {
71
+ return text
72
+ .replace(/(\bAuthorization\s*:\s*(?:Bearer\s+)?)([^\s,;]+)/gi, `$1${REDACTED}`)
73
+ .replace(/(\bCookie\s*:\s*)([^\r\n]+)/gi, `$1${REDACTED}`)
74
+ .replace(
75
+ /(\b["']?(?:password|passwd|pwd|secret|token|session|sessionId|api[_-]?key|client[_-]?secret|app[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,
76
+ `$1${REDACTED}`,
77
+ )
78
+ .replace(/(\bBearer\s+)([A-Za-z0-9._~+/=-]+)/gi, `$1${REDACTED}`)
79
+ .replace(/(\bmysql\b[^\r\n]*?\s-p)([^\s]+)/gi, `$1${REDACTED}`)
80
+ .replace(/((?:[A-Za-z0-9_-]+:)+session:)([A-Za-z0-9._:-]{8,})/gi, `$1${REDACTED}`);
81
+ }
82
+
83
+ function redactValue(value: unknown, key?: string): unknown {
84
+ if (key && SECRET_KEY_RE.test(key)) return REDACTED;
85
+ if (key && SHORT_ID_KEYS.has(key) && typeof value === "string" && value.length >= FULL_ID_MIN_LENGTH) {
86
+ return shortId(value);
87
+ }
88
+ if (typeof value === "string") return redactLogText(value);
89
+ if (Array.isArray(value)) return value.map((item) => redactValue(item));
90
+ if (value instanceof Error) {
91
+ return {
92
+ name: value.name,
93
+ message: redactLogText(value.message),
94
+ stack: value.stack ? redactLogText(value.stack) : undefined,
95
+ };
96
+ }
97
+ if (value instanceof Date) return value;
98
+ if (value !== null && typeof value === "object") {
99
+ const prototype = Object.getPrototypeOf(value);
100
+ if (prototype !== Object.prototype && prototype !== null) return value;
101
+ const redacted: LogFields = {};
102
+ for (const [childKey, childValue] of Object.entries(value)) {
103
+ redacted[childKey] = redactValue(childValue, childKey);
104
+ }
105
+ return redacted;
106
+ }
107
+ return value;
108
+ }
109
+
61
110
  function resolveLogDir(): string {
62
111
  return process.env.PI_QQ_LOG_DIR ?? activeDir ?? join(process.cwd(), ".pi", "pi-qq", "logs");
63
112
  }
@@ -91,7 +140,7 @@ function stringifyError(err: unknown): string {
91
140
 
92
141
  function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message: string, data?: unknown): void {
93
142
  if (!isLevelEnabled(activeLevel, level)) return;
94
- if (!isLogAllowed()) return;
143
+ if (!isLogAllowed(scope)) return;
95
144
 
96
145
  const msgKey = logMessageKey(message);
97
146
  const record: LogFields = {
@@ -99,12 +148,12 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
99
148
  level,
100
149
  scope,
101
150
  ...(msgKey ? { msgKey } : {}),
102
- msg: message,
151
+ msg: redactLogText(message),
103
152
  };
104
153
  const fields = normalizeData(data);
105
154
  if (fields) {
106
155
  for (const [key, value] of Object.entries(fields)) {
107
- if (!(key in record)) record[key] = value;
156
+ if (!(key in record)) record[key] = redactValue(value, key);
108
157
  }
109
158
  }
110
159
 
@@ -123,7 +172,7 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
123
172
  level,
124
173
  scope,
125
174
  ...(msgKey ? { msgKey } : {}),
126
- msg: message,
175
+ msg: redactLogText(message),
127
176
  serializationError: stringifyError(err),
128
177
  });
129
178
  }
@@ -140,6 +189,25 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
140
189
  .catch(() => {});
141
190
  }
142
191
 
192
+ export function logValueLength(value: unknown): number {
193
+ if (value === undefined || value === null) return 0;
194
+ if (typeof value === "string") return value.length;
195
+ try {
196
+ const text = JSON.stringify(value);
197
+ return typeof text === "string" ? text.length : 0;
198
+ } catch {
199
+ return 0;
200
+ }
201
+ }
202
+
203
+ function summarizeSdkMessage(message: string): string {
204
+ const marker = "Body: ";
205
+ const index = message.indexOf(marker);
206
+ if (index < 0) return message;
207
+ const bodyLength = message.length - index - marker.length;
208
+ return `${message.slice(0, index + marker.length)}<${bodyLength} chars>`;
209
+ }
210
+
143
211
  export const log = {
144
212
  debug(scope: string, message: string, data?: unknown): void {
145
213
  writeRecord("debug", scope, message, data);
@@ -157,32 +225,15 @@ export const log = {
157
225
 
158
226
  export const sdkLogger = {
159
227
  debug(message: string, meta?: Record<string, unknown>): void {
160
- log.debug("qqbot", message, meta);
228
+ log.debug("qqbot", summarizeSdkMessage(message), meta);
161
229
  },
162
230
  info(message: string, meta?: Record<string, unknown>): void {
163
- log.info("qqbot", message, meta);
231
+ log.info("qqbot", summarizeSdkMessage(message), meta);
164
232
  },
165
233
  warn(message: string, meta?: Record<string, unknown>): void {
166
- log.warn("qqbot", message, meta);
234
+ log.warn("qqbot", summarizeSdkMessage(message), meta);
167
235
  },
168
236
  error(message: string, meta?: Record<string, unknown>): void {
169
- log.error("qqbot", message, meta);
237
+ log.error("qqbot", summarizeSdkMessage(message), meta);
170
238
  },
171
239
  };
172
-
173
- export function previewForLog(value: unknown, maxChars = 2000): string {
174
- let text: string;
175
- if (typeof value === "string") {
176
- text = value;
177
- } else if (value instanceof Error) {
178
- text = `${value.name}: ${value.message}`;
179
- } else {
180
- try {
181
- const stringified = JSON.stringify(value);
182
- text = typeof stringified === "string" ? stringified : String(value);
183
- } catch {
184
- text = String(value);
185
- }
186
- }
187
- return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…(${text.length} chars)`;
188
- }
package/src/infra/i18n.ts CHANGED
@@ -128,10 +128,10 @@ const enUS = {
128
128
  "diagnostics.budget.limit": "Limit: {limit}/msg ({hours}h)",
129
129
  "diagnostics.budget.lastInbound": "Last inbound: {openid} / {msgId}, {age}s ago",
130
130
  "diagnostics.budget.lastInboundNone": "Last inbound: none",
131
- "diagnostics.budget.passiveRemainingNone": "Passive remaining: —",
131
+ "diagnostics.budget.passiveRemainingNone": "Passive remaining (text replies only): —",
132
132
  "diagnostics.budget.estimatedNone": "Estimated remaining: — (diagnostic only)",
133
133
  "diagnostics.budget.windowNone": "msgId window: —",
134
- "diagnostics.budget.passiveRemaining": "Passive remaining: {remaining}",
134
+ "diagnostics.budget.passiveRemaining": "Passive remaining (text replies only): {remaining}",
135
135
  "diagnostics.budget.streamBubbles": "Stream bubbles: {count} (current msgId)",
136
136
  "diagnostics.budget.estimated": "Estimated remaining: {remaining} (diagnostic only)",
137
137
  "diagnostics.budget.window": "msgId window: {window}",
@@ -297,10 +297,10 @@ const zhCN: Record<TranslationKey, string> = {
297
297
  "diagnostics.budget.limit": "额度:{limit}/消息({hours} 小时)",
298
298
  "diagnostics.budget.lastInbound": "最近入站:{openid} / {msgId},{age} 秒前",
299
299
  "diagnostics.budget.lastInboundNone": "最近入站:无",
300
- "diagnostics.budget.passiveRemainingNone": "被动剩余:—",
300
+ "diagnostics.budget.passiveRemainingNone": "被动剩余(仅文本回复):—",
301
301
  "diagnostics.budget.estimatedNone": "预计剩余:—(仅诊断)",
302
302
  "diagnostics.budget.windowNone": "msgId 窗口:—",
303
- "diagnostics.budget.passiveRemaining": "被动剩余:{remaining}",
303
+ "diagnostics.budget.passiveRemaining": "被动剩余(仅文本回复):{remaining}",
304
304
  "diagnostics.budget.streamBubbles": "流式气泡:{count}(当前 msgId)",
305
305
  "diagnostics.budget.estimated": "预计剩余:{remaining}(仅诊断)",
306
306
  "diagnostics.budget.window": "msgId 窗口:{window}",
@@ -25,6 +25,7 @@ const LOG_MESSAGE_KEYS = {
25
25
  "no bound user; reply skipped": "log.noBoundUser",
26
26
  "no injectable content after attachment handling": "log.noInjectableContent",
27
27
  "passive send failed; retrying proactively": "log.passiveSendFailed",
28
+ "power status read failed": "log.powerStatusReadFailed",
28
29
  "proactive retry failed": "log.proactiveRetryFailed",
29
30
  "run ended": "log.runEnded",
30
31
  "run started": "log.runStarted",