@chen_hu_hu/pi-qq 1.7.1 → 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/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.7.2] - 2026-11-19
11
+
12
+ ### Fixed
13
+
14
+ - `/status` now shows the battery charge on Windows. The probe runs asynchronously with a 3 s timeout and a 30 s cache; the previous 500 ms synchronous call was killed during PowerShell startup.
15
+ - Short IDs in debug logs are now derived from the SHA-256 of the full ID. QQ message IDs share a constant head and tail, so distinct messages previously collapsed to the same `UMkNSaLL` value.
16
+ - `run ended` is logged after the final flush/DONE, reports `delivered`, and includes the last finalized/sent text lengths instead of reset zeros.
17
+ - `bubble split` records the bubble size and rotation reason before resetting writer state.
18
+ - Event-loop diagnostics use a 1 ms histogram and include event-loop utilization; the previous 100 ms resolution produced a constant ~100 ms baseline.
19
+
20
+ ### Changed
21
+
22
+ - Debug logs are much smaller: run diagnostics keep at most five recent tools without arguments or results, no-text takeover decisions are skipped, per-frame `append` / `flush: start` / `timer` logs are replaced by slow-frame and partial-frame summaries, and duplicate tool and run lines are merged. The 2026-11-19 verification log is 188 lines / 43.6 KiB for an 11-minute run, versus 7.64 MiB for 43 active minutes before.
23
+ - `/status` labels the passive remaining count as text replies only; streamed bubbles are counted separately and the conservative estimate line remains.
24
+ - README documents that `replyType: "full"` emits one message per block and that `simple` reduces volume.
25
+
10
26
  ## [1.7.1] - 2026-11-18
11
27
 
12
28
  ### Fixed
package/README-zh.md CHANGED
@@ -84,18 +84,20 @@ Summarize this file.
84
84
  - **普通消息**:原文,不加标题。
85
85
  - **工具图标**:💻 bash、📖 read、📝 write、✏️ edit、🔎 grep、🔍 search、🗂️ find、📁 ls、📋 list、🌐 web、📡 fetch、🗑️ delete、❌ remove、✅ todo、🧪 test;未配置工具使用 🔧。
86
86
 
87
+ 每个块都是一条独立的 QQ 消息,长 run 可能推送几十个气泡;需要更少的消息时使用 `replyType: "simple"`。
88
+
87
89
  模型错误后 60 秒内自动恢复的 run 会继续推送到原 QQ 会话;`/stop` 会等待当前工具和流收尾后再回复。
88
90
 
89
91
  ## 命令
90
92
 
91
93
  在 pi 终端执行:
92
94
 
93
- | 命令 | 说明 |
94
- | ------------ | -------------------------------------- |
95
- | `/qq-login` | 扫码登录并绑定扫码的 QQ 用户 |
96
- | `/qq-status` | 显示登录、连接、模型、上下文和绑定用户 |
97
- | `/qq-logout` | 退出登录并清除凭据 |
98
- | `/qq-new` | 重置当前会话(由 QQ 侧 `/new` 调用) |
95
+ | 命令 | 说明 |
96
+ | ------------ | -------------------------------------------- |
97
+ | `/qq-login` | 扫码登录并绑定扫码的 QQ 用户 |
98
+ | `/qq-status` | 显示登录、连接、模型、上下文、电量和绑定用户 |
99
+ | `/qq-logout` | 退出登录并清除凭据 |
100
+ | `/qq-new` | 重置当前会话(由 QQ 侧 `/new` 调用) |
99
101
 
100
102
  QQ 侧命令:
101
103
 
@@ -209,7 +211,7 @@ npm run format:check
209
211
 
210
212
  - 仅支持 C2C(QQ 私聊)。
211
213
  - QQ 入站消息触发的任务会回传 QQ;直接在 pi 中启动的无关任务不会推送。
212
- - QQ 对每条入站消息的被动回复次数有限制。可用 `/qq-test-budget` 查看本地额度。
214
+ - QQ 对每条入站消息的被动回复次数有限制。`/qq-test-budget` 会显示文本回复的剩余额度和保守估计;流式气泡单独计数,本地不设上限。
213
215
  - 读取 `SKILL.md` 时,QQ 显示 `## 🧩 技能` 和 skill 名称,不转发文件内容。
214
216
 
215
217
  ## 许可证
package/README.md CHANGED
@@ -84,18 +84,20 @@ In `replyType: "full"` mode, QQ receives these block types:
84
84
  - **Regular messages**: raw text with no header.
85
85
  - **Tool icons**: 💻 bash, 📖 read, 📝 write, ✏️ edit, 🔎 grep, 🔍 search, 🗂️ find, 📁 ls, 📋 list, 🌐 web, 📡 fetch, 🗑️ delete, ❌ remove, ✅ todo, 🧪 test; unconfigured tools use 🔧.
86
86
 
87
+ Each block is a separate QQ message, so a long run can push dozens of bubbles; use `replyType: "simple"` to reduce the volume.
88
+
87
89
  After a model error, automatic retries within 60 seconds keep pushing to the original QQ chat. `/stop` waits for active tools and streams to finish before replying.
88
90
 
89
91
  ## Commands
90
92
 
91
93
  Run these in the pi terminal:
92
94
 
93
- | Command | Description |
94
- | ------------ | ------------------------------------------------------ |
95
- | `/qq-login` | Log in with a QR code and bind the scanning QQ user |
96
- | `/qq-status` | Show login, connection, model, context, and bound user |
97
- | `/qq-logout` | Log out and clear credentials |
98
- | `/qq-new` | Reset the current session (used by QQ `/new`) |
95
+ | Command | Description |
96
+ | ------------ | --------------------------------------------------------------- |
97
+ | `/qq-login` | Log in with a QR code and bind the scanning QQ user |
98
+ | `/qq-status` | Show login, connection, model, context, battery, and bound user |
99
+ | `/qq-logout` | Log out and clear credentials |
100
+ | `/qq-new` | Reset the current session (used by QQ `/new`) |
99
101
 
100
102
  QQ-side commands:
101
103
 
@@ -209,7 +211,7 @@ The extension entrypoint is `index.ts`. Source modules are grouped by responsibi
209
211
 
210
212
  - Only C2C (QQ private chat) is supported.
211
213
  - Runs triggered by inbound QQ messages are relayed to QQ. Unrelated tasks started directly in pi stay local.
212
- - QQ limits passive replies per inbound message. Use `/qq-test-budget` to inspect the local budget.
214
+ - QQ limits passive replies per inbound message. `/qq-test-budget` shows the remaining text replies and a conservative estimate; streamed bubbles are counted separately and are not capped locally.
213
215
  - Reading a `SKILL.md` is shown as a `## 🧩 Skill` block with the skill name; the file content is not forwarded to QQ.
214
216
 
215
217
  ## License
@@ -0,0 +1,163 @@
1
+ # pi-qq delivery 1.7.2
2
+
3
+ > **Delivery record.** 1.7.2 shrinks debug logs, makes short IDs unique, and fixes `/status` battery reporting on Windows. See [README](../../README.md) for current user-facing behavior.
4
+ > Version: 1.7.2
5
+ > Date: 2026-11-19
6
+ > Previous: [delivery.1.7.1.md](./delivery.1.7.1.md).
7
+ > Open work: [doc/todo.md](../todo.md).
8
+
9
+ ## 1. Scope
10
+
11
+ 1.7.2 is a maintenance release driven by the 2026-11-19 real-QQ debug log (7 h 01 min, 17 runs, 246 tool calls, 18 inbound messages):
12
+
13
+ - run diagnostics repeated the full tool list on every event; one field accounted for 46% of the file;
14
+ - "short" message IDs collapsed to a constant value, so logs could not be correlated with inbound messages;
15
+ - per-frame stream logs dominated the remaining volume;
16
+ - `/status` omitted the battery line on Windows because a 500 ms synchronous probe killed PowerShell;
17
+ - several diagnostic fields were misleading: `bubble split` logged zeroed stats, `run ended` reported zero lengths before the final DONE, the first `append` logged an epoch-sized `elapsed`, and the event-loop metric had a fixed ~100 ms floor.
18
+
19
+ The release also documents passive-reply quota semantics and `full`-mode message density.
20
+
21
+ Out of scope:
22
+
23
+ - changes to stream framing, rotation, or lifetime behavior;
24
+ - new quota enforcement, typing changes, or stream-frame protocol changes;
25
+ - masking stable account identifiers (`senderId`, `openid`, `appId`);
26
+ - confirming how the QQ client renders very long commands.
27
+
28
+ ## 2. Findings
29
+
30
+ ### 2.1 Log volume
31
+
32
+ Baseline: 18,452 lines / 7.64 MiB for 43.0 active minutes (about 10.6 MiB per active hour).
33
+
34
+ | Scope | Lines | Size | Share |
35
+ | -------- | ----: | ------: | ----: |
36
+ | `run` | 1,288 | 4.5 MiB | 59% |
37
+ | `stream` | 7,520 | 1.7 MiB | 22% |
38
+ | `qqbot` | 7,770 | 1.1 MiB | 14% |
39
+
40
+ The `tools` field alone was 3.51 MiB (46.0%) across 1,254 lines; the largest line was 11.1 KiB with 86 tools. `run: tool start` and `run: tool end` were each logged twice per tool.
41
+
42
+ ### 2.2 Short IDs
43
+
44
+ - `logMsgId()` used `messageId.slice(0, 8)`: 7,571 lines logged `ROBOT1.0`, while 79 lines elsewhere kept the full 117-character ID.
45
+ - The first fix used the first 8 characters after the last underscore. The 2026-11-19 log then showed two different inbound messages with the same short ID (`UMkNSaLL`).
46
+ - Full IDs from the baseline explain why: QQ message IDs are `ROBOT1.0_` + a 21-character constant head + a variable middle + a ~35-character constant tail (16 of 18 IDs ended with `3ngGb.Wl-sLP-ZQpRmBmM!`). Slicing either edge collides.
47
+ - Final rule: `sha256(id)` truncated to 8 hexadecimal characters. The same ID maps to the same value in every scope, and the raw ID is not logged.
48
+
49
+ ### 2.3 Battery status
50
+
51
+ - `/status` at 01:39:29.707 was answered at 01:39:30.220 (513 ms), with no battery line.
52
+ - Reproducing the code path returned `ETIMEDOUT SIGTERM` after 520 ms; PowerShell plus `Get-CimInstance Win32_Battery` took 556–669 ms.
53
+ - The timeout, not a missing battery, caused the omission.
54
+ - On Linux the same call reads `/sys/class/power_supply` and was unaffected.
55
+
56
+ ### 2.4 Diagnostics
57
+
58
+ - `run ended` reported `finalizedTextLen=0 / resultSentLen=0` while the same instant showed 980 / 980, because the assistant handler reset both before the run-end log; the log also preceded the final DONE.
59
+ - 438 of 1,375 `append` lines logged `elapsed=1795049015062` (`Date.now() - 0`).
60
+ - 421 `bubble split` lines logged zeroed stats and no rotation reason.
61
+ - 516 event-loop samples had p50/p90/p99 of 112/114/120 ms and were uncorrelated with log volume (r = 0.007); only two spikes (363 and 617 ms) stood out. Node's histogram `mean` has a floor roughly equal to `resolution`, so `resolution: 100` produced the constant ~100 ms baseline.
62
+ - Every inbound message produced two `message received` lines (debug + info), and each tool event produced two debug lines 1–2 ms apart.
63
+
64
+ ## 3. Decisions
65
+
66
+ | # | Question | Decision |
67
+ | --- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | D1 | How are short IDs derived? | SHA-256 of the full ID, first 8 hex characters. Only fields at least 16 characters long are hashed, so already-short values are not hashed twice. `senderId`, `openid`, and `appId` stay complete. |
69
+ | D2 | What does run diagnostics include? | At most five tools (latest three finished plus the active one), mapped to `id`, `name`, and state; no arguments or results. |
70
+ | D3 | When is a takeover decision logged? | Only when `textLength > 0` or `streamTookOver=false`. |
71
+ | D4 | Which stream frame logs remain? | Keep aggregate `stream timing`, slow frames (≥1 s), partial frames (`remaining > 0`), retries, and warnings. Remove routine `append`, `timer`, `flush: start`, and non-partial `flush: done`. |
72
+ | D5 | What about the first `append` elapsed value? | Removed with D4; no remaining `elapsed` path. |
73
+ | D6 | What does `bubble split` record? | Size, last block kind, trailing-newline state, and the rotation reason (`thinking`, `text`, `tool`, `skill`, `split`, `restart`), captured before reset. |
74
+ | D7 | When is `run ended` logged? | After the final `flush` / `done`, with `delivered`, `lastFinalizedTextLen`, and `lastResultSentLen`; the separate `finished` line is merged. |
75
+ | D8 | How is the event loop measured? | `resolution: 1` plus `performance.eventLoopUtilization()`. |
76
+ | D9 | Which duplicate lines are merged? | One tool start/end line per transition (with `queueWaitMs`), one full inbound `message received` at info level, one `run ended`. `agent` info lines remain because they serve the info log level. |
77
+ | D10 | Do stream bubbles consume the local passive budget? | No. The limiter records text replies only; `/status` labels `passiveRemaining` as text replies only and keeps `estimated = remaining - streamBubbles` as the conservative value. |
78
+ | D11 | Should `full` mode emit fewer bubbles? | No. Document that each block is a separate message and that `simple` reduces volume. |
79
+ | D12 | How is the 600 s boundary verified? | One controlled 11-minute silent bash tool on real QQ, expecting `40034020`, a fresh stream, buffer replay, and delivery. |
80
+ | D13 | How is battery read? | Async `execFile` with a 3 s timeout and a 30 s cache; `getStatusLines()` is async; failures log platform, code, and signal at debug under the always-allowed `power` scope. |
81
+
82
+ ## 4. Implementation
83
+
84
+ | Area | Files | Change |
85
+ | ------------ | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
86
+ | Short IDs | `src/infra/short-id.ts`, `src/infra/file-logger.ts` | SHA-256 prefix helper; log writer hashes `messageId`, `msgId`, and `streamMsgId` values of at least 16 characters. |
87
+ | Diagnostics | `src/relay/run-timeline.ts`, `src/relay/run-stream-relay.ts` | Snapshot-capped tool list without args/results; takeover filter; one tool line per transition; `run ended` after DONE with delivered/last counters. |
88
+ | Stream logs | `src/relay/stream-session.ts`, `src/relay/bubble-writer.ts` | Remove per-frame logs; add slow/partial summaries; record split reason and pre-reset size; keep aggregate timing. |
89
+ | Event loop | `index.ts` | 1 ms histogram and `eventLoopUtilization`. |
90
+ | Inbound logs | `src/qq/qq-message-handler.ts` | One info-level `message received` after the allowlist check, with the previous debug fields. |
91
+ | Battery | `src/infra/power-status.ts`, `index.ts`, `src/qq/inbound-command.ts` | Async probe, 3 s timeout, 30 s cache, async `getStatusLines()`, failure debug log. |
92
+ | User docs | `README.md`, `README-zh.md`, `src/infra/i18n.ts` | Quota wording, `full`-mode density, battery in `/qq-status` description. |
93
+
94
+ ## 5. Verification
95
+
96
+ ### 5.1 Automated
97
+
98
+ - 25 test files, **259 tests passed**.
99
+ - `npm run lint`, `npm run typecheck`, `npm run format:check`, and `npm pack --dry-run` pass.
100
+ - New coverage: SHA-256 short IDs (including two real IDs with the same head and tail), ID hashing in the log writer, capped diagnostics without args/results, absence of per-frame append logs, partial-frame summary, battery cache and failure fallback, and the updated `/status` wording.
101
+
102
+ ### 5.2 Real QQ: 600 s expiry
103
+
104
+ Environment: WSL Linux; pi 1.5.2; Node.js 24.22.0; local `main`; one C2C user. Test tool: `sleep 660; echo done`.
105
+
106
+ | Time (UTC) | Event |
107
+ | ------------ | ------------------------------------------------------------------------------------ |
108
+ | 10:03:31.949 | `bash` tool starts; stream opens; first frame 200 (46 chars) |
109
+ | 10:03:32.445 | append done, 495 ms |
110
+ | 10:14:32.018 | tool ends after 660,055 ms; result frame POST |
111
+ | 10:14:32.734 | `400 Bad Request`, `40034020`, `expired: true`, `lastFrameAgeMs=660291` |
112
+ | 10:14:33.442 | fresh stream `resumed: true`, `index=0`, no `stream_msg_id`, 17-char buffer replayed |
113
+ | 10:14:34.222 | fresh stream 200; result delivered |
114
+ | 10:14:34.992 | final `OK` 200; `run ended` `delivered: true` after 664,392 ms |
115
+
116
+ A QQ screenshot confirmed the `bash` bubble, the `done` result, the final `OK`, and the battery line (`99% (discharging)`). The recovered result arrives as a new bubble without the original `bash` header.
117
+
118
+ ### 5.3 Battery on Windows
119
+
120
+ The actual `power-status.ts` was run under Windows Node 24.21 against a real battery:
121
+
122
+ - success: `{"percent":100,"state":"ac"}`, 556 ms;
123
+ - timeout forced to 1 ms: `power status read failed { platform: 'win32', killed: true, signal: 'SIGTERM' }`, returns `undefined` without throwing.
124
+
125
+ ### 5.4 Log after the change
126
+
127
+ - 188 lines / 43.6 KiB for the 11.1-minute run; the baseline was 7.64 MiB for 43 active minutes.
128
+ - `event-loop` is now the largest scope (133 lines / 26.2 KiB); `run` 5.1 KiB, `stream` 5.0 KiB, `qqbot` 2.8 KiB.
129
+ - No `append:`, `timer:`, `flush: start`, `flush: done`, `content_raw`, `textPreview`, `"args"`, or `"result"`.
130
+ - Event loop: mean 1.11 ms, worst `max` 86 ms, mean utilization 2.26% (max 6.20%).
131
+ - The test log predates the SHA-256 change and still shows `UMkNSaLL`; the hash rule is covered by unit tests with the real colliding IDs.
132
+
133
+ ## 6. Risks and limitations
134
+
135
+ | Risk | Impact | Handling |
136
+ | -------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------ |
137
+ | Hashed IDs | Short IDs cannot be compared to raw platform IDs without hashing them | Recompute `sha256(id)[:8]` when correlating with an external error |
138
+ | Expiry test coverage | One account, one network, one client; QQ rendering and lifetime may vary | Recovery path is defensive; keep the long-term observation in TODO |
139
+ | Long command rendering | Commands over ~500 characters may still be collapsed by the QQ client | Pending A/B in TODO 1 |
140
+ | `msg_id` beyond 20 minutes | One-hour-old inbound messages are unverified | Long-term observation |
141
+ | Typing timeout | A 10 s timeout was seen earlier but not reproduced | Typing is skipped while a stream is active |
142
+ | Event-loop log share | 60% of the new log is the 5 s event-loop sample | Candidate for threshold logging or a 30 s cadence |
143
+ | `/status` logging | Command replies outside a run are gated off (`outbound` / `qqbot`) | Verified by screenshot; allowing `outbound` is an open option |
144
+ | Recovery bubble | The recovered tool result appears in a new bubble without its tool header | Accepted; the original bubble cannot accept frames after expiry |
145
+
146
+ ## 7. Open items
147
+
148
+ Active work is tracked in [doc/todo.md](../todo.md):
149
+
150
+ - confirm QQ rendering for a 500+ character bash command;
151
+ - observe stream lifetime and `msg_id` validity beyond 20 minutes and one hour;
152
+ - reproduce the typing timeout;
153
+ - reduce event-loop log volume;
154
+ - decide whether `/status` replies should be logged outside runs.
155
+
156
+ ## 8. References
157
+
158
+ - Stream endpoint: `https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_users_user_openid_stream_messages.post.html`
159
+ - Error codes: `https://bot.q.qq.com/wiki/develop/api-v2/openapi/error/error.html`
160
+ - Code: `src/infra/short-id.ts`, `src/infra/file-logger.ts`, `src/infra/power-status.ts`, `src/relay/run-timeline.ts`, `src/relay/run-stream-relay.ts`, `src/relay/bubble-writer.ts`, `src/relay/stream-session.ts`, `index.ts`.
161
+ - Tests: `test/infra/short-id.test.ts`, `test/infra/file-logger.test.ts`, `test/infra/power-status.test.ts`, `test/relay/run-timeline.test.ts`, `test/relay/stream-session.test.ts`, `test/quota/reply-quota-report.test.ts`, `test/index.test.ts`.
162
+ - Previous delivery: [delivery.1.7.1.md](./delivery.1.7.1.md).
163
+ - User-facing behavior: [README.md](../../README.md), [README-zh.md](../../README-zh.md).
package/doc/todo.md CHANGED
@@ -1,124 +1,39 @@
1
1
  # TODO
2
2
 
3
3
  > 只记录未完成项目;已完成项目直接删除,不使用勾选状态。
4
- > 1.7.1 交付记录与验证:`doc/archive/delivery.1.7.1.md`
4
+ > 1.7.1 交付记录:`doc/archive/delivery.1.7.1.md`
5
5
 
6
- ## 1. 长运行 bash 工具的参数延迟显示
6
+ ## 1. 超长 bash 命令在 QQ 的渲染
7
7
 
8
- > 状态:启动帧已验证正常;待确认 QQ 客户端渲染
9
- > 记录日期:2026-11-04
10
- > 分析日期:2026-11-06
11
- > 相关版本:pi-qq 1.3.6(仅增加 debug 日志);本次日志来自 1.4.0 之后的版本
8
+ > 状态:待一次长命令确认
9
+ > 记录日期:2026-11-04;更新:2026-11-19
12
10
 
13
- ### 现象
11
+ 2026-11-19 的 11 分钟 `sleep 660` 在真实 QQ 上完整显示了 `## 💻 bash` 和命令代码块,说明长运行工具的启动帧与 fenced block 正常,未退化成“bash 和一个点”。
14
12
 
15
- 正常使用中,bash 执行 e2e 测试通常需要数分钟。此时 QQ 上只能看到 `bash` 和一个点,看不到命令参数;理论上工具名称和参数应该在 `tool_execution_start` 后立即出现,只有结果需要等待工具结束。
13
+ 尚未确认:数百到上千字符的超长命令是否会被客户端折叠。
16
14
 
17
- ### 已知事实
18
-
19
- - `AppendStream` 默认有 500ms 节流;这是 pi-qq 自己设置的值,不是 QQ 限制。
20
- - 500ms 定时器不依赖工具 Promise;长工具的启动帧曾在工具结束前通过 `stream_messages` 发出。
21
- - pi 内置 bash 使用异步 `spawn`,正常情况下不会阻塞 Node 事件循环。
22
- - 本地异步子进程可持续触发 500ms timer,说明“bash 子进程本身”不是必然的事件循环阻塞源。
23
- - 2026-11-05 的真实使用记录已覆盖启动帧、`content_raw`、timer/队列和事件循环;但最长单条 bash 只有 94 秒的 docker build,仍没有“数分钟 e2e”样本。分析结果见下文。
24
-
25
- ### 已经添加的诊断日志
26
-
27
- 版本 1.3.6 只增加了 debug 日志,没有改变行为:
28
-
29
- - `scope: "stream"`,`msgKey: "log.streamTiming"`:
30
- - `phase: "tool queued"`:工具行进入队列;
31
- - `phase: "append start"`:队列开始处理,包含 `waitedMs`;
32
- - `phase: "append done"`:队列处理完成,包含 `totalMs`。
33
- - `AppendStream.onDebug`(同 scope `"stream"`):
34
- - `append: buffered/immediate/while flushing`;
35
- - `timer: fired after ...`;
36
- - `flush: start/done`。
37
- - `scope: "event-loop"`,`msgKey: "log.eventLoopDelay"`:
38
- - 每 5 秒记录一次 `meanMs`、`maxMs`、`p99Ms`。
39
-
40
- 所有日志只在 `logLevel: "debug"` 时写入:
41
-
42
- ```json
43
- {
44
- "logLevel": "debug"
45
- }
46
- ```
47
-
48
- 日志路径:
49
-
50
- ```text
51
- <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
52
- ```
53
-
54
- ### 日志验证结果(2026-11-06)
55
-
56
- 基于 2026-11-05 / 2026-11-06 的真实使用记录(`logLevel: "debug"`)验证。11-05 有 4 个 QQ 触发的 run(约 8 / 21 / 29 / 23 分钟),共 529 个启动帧(483 个工具行 + 46 个 skill 块)。
57
-
58
- **启动帧确实发出,且带完整参数:**
59
-
60
- - 94.2 秒的 docker build:
61
- - 11:49:38.449 `tool start`,`args` 包含完整 `command`;
62
- - 11:49:39.032 发出 `POST .../stream_messages`,`content_raw` 以 `## 💻 bash` 开头,命令放在 `bash` fenced code block 中,完整内容为 `cd .../xuanji-mock && docker compose ... build 2>&1 | tail -6`;
63
- - 11:49:39.643 收到 200 OK;
64
- - 工具在 11:51:12.689 才结束,结果帧在 11:51:12.690 发出、11:51:13.323 收到 200。
65
- - 529 个启动帧全部能在 `stream_messages` 请求体中找到:
66
- `93 bash + 194 write + 150 read + 28 codemode + 18 edit + 46 skill = 529`。
67
- - 最长的 bash 命令为 1108 字符;`content_raw` 为完整的 1134 字符(标题 + fence + 命令),没有被截断。
68
- - `append start` 的 `waitedMs` 最大 1ms;`append done` 的 `totalMs` 中位数约 1.3s、最大 2.1s。延迟来自关旧气泡、开新流和网络往返,不是队列积压。
69
- - 94s 工具的启动帧不是被 500ms 节流拖住的:日志为 `append: immediate`,`flush` 在 `stream open` 后立即开始。
70
- - QQ run 期间 `event-loop` 的 `maxMs` 最大 258ms,`driftMs` 最大 82ms;没有数秒级阻塞。
71
-
72
- **结论:** 在这些日志覆盖的场景中,TODO 1 中列出的四种可能——启动帧没发出、`content_raw` 没命令、queue/timer 延迟、事件循环饥饿——均不成立。pi-qq 侧在工具开始后约 1.2 秒内已经把带完整命令的启动帧交给 QQ API。
73
-
74
- ### 尚未验证
75
-
76
- - QQ 客户端如何渲染这个 fenced code block。日志只能证明请求体里有完整命令,不能证明手机 QQ 一定把代码块展开显示。
77
- - 如果手机 QQ 仍只显示“bash 和一个点”,优先检查 QQ 对带 `bash` 语言标记的 fenced block、长代码块或新气泡的折叠/渲染,而不是继续排查 relay。
78
- - 2026-11-18 main 构建:`tool start` 后 1.1–3.2s(中位数约 1.4s)工具行才发出;`waitedMs` 多为 0,延迟来自旧气泡 DONE + 新流 RTT,不是队列积压。仍需确认 QQ 客户端是否把长命令折叠成“bash 和一个点”。
79
-
80
- ### 下一步
81
-
82
- - 不需要给工具启动行增加 `flushAfter`;当前无队列/节流延迟证据。
83
- - 做一次 QQ 渲染 A/B:同一命令分别用带 `bash` 语言标记的 fenced block、无语言标记的 fenced block、行内代码发送,确认是否只在某种格式下显示异常。
84
- - 如果确认是 QQ 渲染问题,再考虑缩短命令摘要或改用普通文本/行内代码;如果确认正常,可直接关闭 TODO 1。
85
- - 若最终需要改格式,补测试并更新 `CHANGELOG.md`,再发布版本。
15
+ - relay 侧无问题:启动帧在工具开始后 1.1–3.2 s 内发出,参数完整;延迟来自旧气泡 DONE + 新流 RTT,不是队列积压。
16
+ - 下一步:用一条 500+ 字符的命令做 A/B(带 `bash` 语言标记 / 无语言标记 / 行内代码),确认折叠行为;正常则删除本节。
86
17
 
87
18
  ## 2. 流式消息生命周期的长期观察
88
19
 
89
20
  > 状态:持续观察;仅保留尚未验证的长期风险
90
21
 
91
- ### 背景
92
-
93
- 2026-11-12 的真实 QQ 实验确认:
94
-
95
- - 流的总生命周期约 600 秒,边界有约 1 秒抖动;
96
- - 心跳不能延长生命周期;
97
- - 过期后同 `msg_id` 新流、`is_wakeup=true`、新入站目标都能恢复;
98
- - 12 分钟真实 agent 工具已验证自动新开流。
99
-
100
- ### 进度
101
-
102
- - 20 分钟同 `msg_id` 新流:已验证(`expire 20`,1203.5s);
103
- - 超过 20 分钟的同 `msg_id` 新流:未验证;
104
- - 1 小时以上 `msg_id`:未验证。
22
+ 已确认:总生命周期约 600 秒;过期后同 `msg_id` 新流可恢复;11 分钟静默工具验证了 `40034020` → 新流 → 重放缓冲 → 结果送达(2026-11-19,660 s);20 分钟同 `msg_id` 新流已验证(1203.5 s)。
105
23
 
106
- ### 需要观察
24
+ 待观察:
107
25
 
108
- - 平台生命周期是否随账号、地区、客户端版本变化;
109
- - 真实网络抖动、重连、限流下的表现;
110
- - 超过 20 分钟的同 `msg_id` 新流是否仍可用;
111
- - 真实使用中 `40034020` 的恢复是否仍能稳定送达结果。
26
+ - 超过 20 分钟的同 `msg_id` 新流;1 小时以上的 `msg_id`;
27
+ - 生命周期是否随账号、地区、客户端版本变化;
28
+ - 真实网络抖动、重连、限流下 `40034020` 的恢复是否稳定送达。
112
29
 
113
30
  实验记录见 `doc/archive/delivery.1.7.1.md`。
114
31
 
115
- ## 3. 调试日志与流帧的剩余优化
32
+ ## 3. 调试日志的剩余优化
116
33
 
117
- > 状态:不阻塞 1.7.1;等真实使用数据再评估
118
- > 记录日期:2026-11-18
34
+ > 状态:不阻塞;等下一次真实日志评估
35
+ > 记录日期:2026-11-19
119
36
 
120
- - typing 真实网络超时:1.7.1 已在流活跃时跳过 typing,但 10s 超时尚未在真实网络复现。
121
- - 日志体积:`run` 诊断在每个工具事件重复完整 `tools` 列表;1.7.1 的单工具 run 中占 7 KiB / 21.5 KiB。
122
- - 完整 ID 未掩码:`messageId` / `senderId` / `openid` / `appId` 仍在 debug 日志中;需要决定掩码或保留。
123
- - 流帧开销:气泡结束前补的 `\n` 可能单独成帧;最终回答首帧可能只有 1–4 个字符;`run ended` 日志早于最终 DONE。
124
- - 这些项不影响 1.7.1 的正确性;改动前优先用真实 QQ 日志确认收益。
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";
@@ -49,7 +49,9 @@ 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 {
@@ -75,15 +77,19 @@ function startEventLoopMonitor(): void {
75
77
  eventLoopDelay.reset();
76
78
  eventLoopDelay.enable();
77
79
  let lastTickAt = Date.now();
80
+ let lastElu = performance.eventLoopUtilization();
78
81
  eventLoopTimer = setInterval(() => {
79
82
  const now = Date.now();
80
83
  const driftMs = now - lastTickAt - 5_000;
81
84
  lastTickAt = now;
85
+ const elu = performance.eventLoopUtilization(lastElu);
86
+ lastElu = performance.eventLoopUtilization();
82
87
  log.debug("event-loop", "event loop delay", {
83
88
  meanMs: roundMs(eventLoopDelay.mean),
84
89
  maxMs: roundMs(eventLoopDelay.max),
85
90
  p99Ms: roundMs(eventLoopDelay.percentile(99)),
86
91
  driftMs,
92
+ utilizationPercent: Math.round(elu.utilization * 1000) / 10,
87
93
  });
88
94
  eventLoopDelay.reset();
89
95
  }, 5_000);
@@ -102,7 +108,7 @@ export default function (pi: ExtensionAPI) {
102
108
  if (!getLoginState()) return false;
103
109
  // The message that starts a run arrives before the run becomes active.
104
110
  if (scope === "inbound") return true;
105
- if (scope === "session" || scope === "bot") return true;
111
+ if (scope === "session" || scope === "bot" || scope === "power") return true;
106
112
  return runFeedback.isQQRunActive();
107
113
  });
108
114
 
@@ -141,7 +147,7 @@ export default function (pi: ExtensionAPI) {
141
147
 
142
148
  const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
143
149
 
144
- const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
150
+ const getStatusLines = async (ctx: ExtensionContext | undefined = sessionCtx): Promise<string[]> => {
145
151
  const login = getLoginState();
146
152
  const usage = ctx?.getContextUsage();
147
153
  return formatStatusReport({
@@ -159,7 +165,7 @@ export default function (pi: ExtensionAPI) {
159
165
  percent: usage.percent,
160
166
  }
161
167
  : undefined,
162
- power: getPowerStatus(),
168
+ power: await getPowerStatus(),
163
169
  replyType: activeSettings.replyType,
164
170
  });
165
171
  };
@@ -454,7 +460,7 @@ export default function (pi: ExtensionAPI) {
454
460
  pi.registerCommand("qq-status", {
455
461
  description: t("commands.descQqStatus"),
456
462
  handler: async (_args, ctx) => {
457
- ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
463
+ ctx.ui.notify((await getStatusLines(ctx)).join("\n"), "info");
458
464
  },
459
465
  });
460
466
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.7.1",
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>;
@@ -61,6 +62,9 @@ function isLogAllowed(scope: string): boolean {
61
62
  const REDACTED = "<redacted>";
62
63
  const SECRET_KEY_RE =
63
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;
64
68
 
65
69
  /** Redact common credential shapes while keeping the surrounding log text. */
66
70
  export function redactLogText(text: string): string {
@@ -78,6 +82,9 @@ export function redactLogText(text: string): string {
78
82
 
79
83
  function redactValue(value: unknown, key?: string): unknown {
80
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
+ }
81
88
  if (typeof value === "string") return redactLogText(value);
82
89
  if (Array.isArray(value)) return value.map((item) => redactValue(item));
83
90
  if (value instanceof Error) {
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",
@@ -1,6 +1,7 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
  import { readFileSync, readdirSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { log } from "./file-logger";
4
5
 
5
6
  export interface PowerStatus {
6
7
  percent?: number;
@@ -8,6 +9,10 @@ export interface PowerStatus {
8
9
  }
9
10
 
10
11
  const CACHE_MS = 30_000;
12
+ const MACOS_TIMEOUT_MS = 500;
13
+ // PowerShell cold start plus the CIM query takes about 0.7 s on a warm cache
14
+ // and longer on a cold one; 500 ms killed the process before it could answer.
15
+ const WINDOWS_TIMEOUT_MS = 3000;
11
16
  let cache: { at: number; value: PowerStatus | undefined } | undefined;
12
17
 
13
18
  function clampPercent(value: number): number | undefined {
@@ -67,38 +72,56 @@ export function readLinuxBattery(root = "/sys/class/power_supply"): PowerStatus
67
72
  return undefined;
68
73
  }
69
74
 
70
- function readPowerStatus(): PowerStatus | undefined {
71
- try {
72
- if (process.platform === "linux") return readLinuxBattery();
73
- if (process.platform === "darwin") {
74
- const output = execFileSync("pmset", ["-g", "batt"], {
75
- encoding: "utf8",
76
- timeout: 500,
77
- stdio: ["ignore", "pipe", "ignore"],
78
- });
79
- return parsePmsetOutput(output);
80
- }
81
- if (process.platform === "win32") {
82
- const output = execFileSync(
83
- "powershell",
84
- [
85
- "-NoProfile",
86
- "-Command",
87
- "Get-CimInstance Win32_Battery | Select-Object -First 1 EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json -Compress",
88
- ],
89
- { encoding: "utf8", timeout: 500, stdio: ["ignore", "pipe", "ignore"] },
90
- );
91
- return parseWindowsBattery(output);
92
- }
93
- } catch {
94
- return undefined;
75
+ function run(file: string, args: string[], timeoutMs: number): Promise<string> {
76
+ return new Promise((resolve, reject) => {
77
+ execFile(file, args, { encoding: "utf8", timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
78
+ if (err) reject(err);
79
+ else resolve(stdout);
80
+ });
81
+ });
82
+ }
83
+
84
+ async function readPowerStatus(): Promise<PowerStatus | undefined> {
85
+ if (process.platform === "linux") return readLinuxBattery();
86
+ if (process.platform === "darwin") {
87
+ return parsePmsetOutput(await run("pmset", ["-g", "batt"], MACOS_TIMEOUT_MS));
88
+ }
89
+ if (process.platform === "win32") {
90
+ const output = await run(
91
+ "powershell",
92
+ [
93
+ "-NoProfile",
94
+ "-Command",
95
+ "Get-CimInstance Win32_Battery | Select-Object -First 1 EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json -Compress",
96
+ ],
97
+ WINDOWS_TIMEOUT_MS,
98
+ );
99
+ return parseWindowsBattery(output);
95
100
  }
96
101
  return undefined;
97
102
  }
98
103
 
99
- export function getPowerStatus(now = Date.now()): PowerStatus | undefined {
104
+ export function resetPowerStatusCache(): void {
105
+ cache = undefined;
106
+ }
107
+
108
+ export async function getPowerStatus(
109
+ now = Date.now(),
110
+ read: () => Promise<PowerStatus | undefined> = readPowerStatus,
111
+ ): Promise<PowerStatus | undefined> {
100
112
  if (cache && now - cache.at < CACHE_MS) return cache.value;
101
- const value = readPowerStatus();
113
+ let value: PowerStatus | undefined;
114
+ try {
115
+ value = await read();
116
+ } catch (err) {
117
+ const e = err as { code?: string | number; killed?: boolean; signal?: string };
118
+ log.debug("power", "power status read failed", {
119
+ platform: process.platform,
120
+ code: e?.code ?? null,
121
+ killed: e?.killed ?? null,
122
+ signal: e?.signal ?? null,
123
+ });
124
+ }
102
125
  cache = { at: now, value };
103
126
  return value;
104
127
  }
@@ -0,0 +1,15 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ const SHORT_ID_LENGTH = 8;
4
+
5
+ /**
6
+ * Derive a stable, non-reversible short identifier for logs.
7
+ *
8
+ * QQ message IDs share a long constant head and tail, and only the middle
9
+ * varies. Slicing either edge therefore maps different messages to the same
10
+ * short ID; hashing keeps them distinguishable and hides the raw identifier.
11
+ */
12
+ export function shortId(id: string | null | undefined): string {
13
+ if (!id) return "?";
14
+ return createHash("sha256").update(id).digest("hex").slice(0, SHORT_ID_LENGTH);
15
+ }
@@ -15,7 +15,7 @@ export type InboundPi = Pick<ExtensionAPI, "sendUserMessage">;
15
15
  export interface InboundCommandDeps {
16
16
  pi: InboundPi;
17
17
  ctx: InboundContext;
18
- getStatusLines: () => string[];
18
+ getStatusLines: () => string[] | Promise<string[]>;
19
19
  getLastMessage?: () => string | undefined;
20
20
  onStop?: () => void;
21
21
  waitForEnd?: () => Promise<void>;
@@ -87,7 +87,7 @@ export async function handleInboundCommand(
87
87
  }
88
88
  break;
89
89
  case "/status":
90
- await reply(deps.getStatusLines().join("\n"));
90
+ await reply((await deps.getStatusLines()).join("\n"));
91
91
  break;
92
92
  case "/last": {
93
93
  if (!deps.ctx.isIdle()) {
@@ -31,19 +31,6 @@ export function createInboundHandler(deps: InboundDeps) {
31
31
  const pending = new PendingAttachments();
32
32
 
33
33
  return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
34
- log.debug("inbound", "message received", {
35
- kind: msg.kind,
36
- rawEventType: msg.rawEventType,
37
- messageId: msg.messageId,
38
- senderId: msg.senderId,
39
- senderIsBot: msg.senderIsBot,
40
- msgType: msg.msgType,
41
- timestamp: msg.timestamp,
42
- contentLength: (msg.content ?? "").length,
43
- attachmentCount: (msg.attachments ?? []).length,
44
- elementCount: (msg.msgElements ?? []).length,
45
- });
46
-
47
34
  if (msg.kind !== "c2c") {
48
35
  log.debug("inbound", "skipped non-c2c message", { kind: msg.kind });
49
36
  return;
@@ -58,10 +45,16 @@ export function createInboundHandler(deps: InboundDeps) {
58
45
  deps.reloadSettings();
59
46
  deps.budget.observeInbound(msg.senderId, msg.messageId);
60
47
  log.info("inbound", "message received", {
48
+ kind: msg.kind,
49
+ rawEventType: msg.rawEventType,
61
50
  messageId: msg.messageId,
62
51
  senderId: msg.senderId,
52
+ senderIsBot: msg.senderIsBot,
53
+ msgType: msg.msgType,
54
+ timestamp: msg.timestamp,
63
55
  contentLength: (msg.content ?? "").length,
64
56
  attachmentCount: (msg.attachments ?? []).length,
57
+ elementCount: (msg.msgElements ?? []).length,
65
58
  });
66
59
 
67
60
  const channel: ReplyChannel = {
@@ -3,6 +3,7 @@ import { ReplyBudget } from "../quota/reply-quota";
3
3
  import { AppendStream } from "../relay/stream-session";
4
4
  import { sendWithMsgSeq } from "./msg-seq-send";
5
5
  import { log } from "../infra/file-logger";
6
+ import { shortId } from "../infra/short-id";
6
7
  import { t } from "../infra/i18n";
7
8
 
8
9
  export const TEXT_CHUNK_LIMIT = 4500;
@@ -96,7 +97,7 @@ export async function sendStreamReply(
96
97
  ): Promise<void> {
97
98
  log.debug("stream", "stream timing", {
98
99
  phase: "last reply stream",
99
- msgId: target.msgId.slice(0, 8),
100
+ msgId: shortId(target.msgId),
100
101
  textLength: text.length,
101
102
  });
102
103
  const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
@@ -1,4 +1,5 @@
1
1
  import { t } from "../infra/i18n";
2
+ import { shortId } from "../infra/short-id";
2
3
  import type { BudgetSnapshot } from "./reply-quota";
3
4
 
4
5
  interface BudgetTarget {
@@ -22,7 +23,7 @@ export function formatBudgetStatus(
22
23
  const lastLine = last
23
24
  ? t("diagnostics.budget.lastInbound", {
24
25
  openid: mask(last.openid),
25
- msgId: mask(last.msgId),
26
+ msgId: shortId(last.msgId),
26
27
  age: ageSec ?? 0,
27
28
  })
28
29
  : t("diagnostics.budget.lastInboundNone");
@@ -10,8 +10,10 @@ import {
10
10
  thinkingHeader,
11
11
  } from "./stream-block-format";
12
12
  import { t } from "../infra/i18n";
13
+ import { shortId } from "../infra/short-id";
13
14
 
14
15
  type BlockKind = "none" | "thinking" | "tool" | "text";
16
+ type RotateReason = "restart" | "thinking" | "text" | "tool" | "skill" | "split";
15
17
 
16
18
  const MAX_RESUME_ATTEMPTS = 2;
17
19
  const MAX_BUBBLE_CHARS = 12_000;
@@ -128,14 +130,19 @@ export class BubbleWriter {
128
130
  const newBubble = this.startsNewBlock("thinking");
129
131
  const prefix = this.beginBlock("thinking", newBubble);
130
132
  this.thinkingAtLineStart = delta.endsWith("\n");
131
- this.push(`${prefix}${delta}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble, thinking: true });
133
+ this.push(`${prefix}${delta}`, {
134
+ blockBoundary: prefix.length > 0 || newBubble,
135
+ newBubble,
136
+ reason: "thinking",
137
+ thinking: true,
138
+ });
132
139
  }
133
140
 
134
141
  pushText(text: string): void {
135
142
  if (this.streamDead || this.disposed) return;
136
143
  const newBubble = this.startsNewBlock("text");
137
144
  const prefix = this.beginBlock("text", newBubble);
138
- this.push(`${prefix}${text}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble });
145
+ this.push(`${prefix}${text}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble, reason: "text" });
139
146
  }
140
147
 
141
148
  pushTool(name: string, args: unknown): void {
@@ -156,6 +163,7 @@ export class BubbleWriter {
156
163
  this.push(`${prefix}${formatToolLine(name, args)}\n\n`, {
157
164
  blockBoundary: prefix.length > 0 || newBubble,
158
165
  newBubble,
166
+ reason: "tool",
159
167
  trace: "tool",
160
168
  });
161
169
  }
@@ -168,6 +176,7 @@ export class BubbleWriter {
168
176
  this.push(`${prefix}${formatSkillBlock(name)}`, {
169
177
  blockBoundary: prefix.length > 0 || newBubble,
170
178
  newBubble,
179
+ reason: "skill",
171
180
  trace: "skill",
172
181
  });
173
182
  }
@@ -187,7 +196,7 @@ export class BubbleWriter {
187
196
  void this.enqueue(async () => {
188
197
  if (this.disposed) return;
189
198
  if (this.fenceOpen) await this.closeOpenFence();
190
- if (this.cur) await this.rotateStream();
199
+ if (this.cur) await this.rotateStream("restart");
191
200
 
192
201
  if (target) {
193
202
  this.deps.openid = target.openid;
@@ -273,7 +282,7 @@ export class BubbleWriter {
273
282
  }
274
283
 
275
284
  private logMsgId(): string {
276
- return this.deps.msgId?.slice(0, 8) ?? "?";
285
+ return shortId(this.deps.msgId);
277
286
  }
278
287
 
279
288
  private beginBlock(kind: BlockKind, newBubble = false): string {
@@ -325,11 +334,12 @@ export class BubbleWriter {
325
334
  blockBoundary?: boolean;
326
335
  endTool?: boolean;
327
336
  newBubble?: boolean;
337
+ reason?: RotateReason;
328
338
  thinking?: boolean;
329
339
  trace?: string;
330
340
  } = {},
331
341
  ): void {
332
- const { blockBoundary = false, endTool = false, newBubble = false, thinking = false, trace } = options;
342
+ const { blockBoundary = false, endTool = false, newBubble = false, reason, thinking = false, trace } = options;
333
343
  if (!text || this.streamDead || this.disposed) return;
334
344
  const queuedAt = trace ? Date.now() : 0;
335
345
  void this.enqueue(async () => {
@@ -346,14 +356,14 @@ export class BubbleWriter {
346
356
  }
347
357
  if (blockBoundary && !(await this.closeOpenFence())) return;
348
358
  if (newBubble && this.cur && this.bubbleChars > 0 && !this.pendingResume) {
349
- await this.rotateStream();
359
+ await this.rotateStream(reason ?? "text");
350
360
  if (this.streamDead || this.disposed) return;
351
361
  }
352
362
  const cut = this.splitPoint(text, newBubble);
353
363
  if (cut >= 0) {
354
364
  await this.appendChunk(text.slice(0, cut + 1), { thinking, endTool, trace, queuedAt });
355
365
  if (this.streamDead || this.disposed) return;
356
- await this.rotateStream();
366
+ await this.rotateStream("split");
357
367
  if (this.streamDead || this.disposed) return;
358
368
  await this.appendChunk(text.slice(cut + 1), { thinking, endTool, trace, queuedAt });
359
369
  return;
@@ -423,9 +433,12 @@ export class BubbleWriter {
423
433
  }
424
434
  }
425
435
 
426
- private async rotateStream(): Promise<void> {
436
+ private async rotateStream(reason: RotateReason): Promise<void> {
427
437
  const stream = this.cur;
428
438
  if (!stream) return;
439
+ const bubbleChars = this.bubbleChars;
440
+ const lastKind = this.lastKind;
441
+ const endedWithNewline = this.lastChar === "\n";
429
442
  try {
430
443
  if (this.lastChar && this.lastChar !== "\n") {
431
444
  await stream.append("\n");
@@ -451,8 +464,12 @@ export class BubbleWriter {
451
464
  if (isLogEnabled("debug")) {
452
465
  log.debug("stream", "bubble split", {
453
466
  msgId: this.logMsgId(),
467
+ reason,
454
468
  elapsedMs: Date.now() - this.deps.startedAt,
455
- stats: this.stats(),
469
+ bubbleChars,
470
+ lastKind,
471
+ endedWithNewline,
472
+ hasPushed: this.pushedAny,
456
473
  });
457
474
  }
458
475
  }
@@ -5,6 +5,7 @@ import { policyFor, type ReplyPolicy } from "./reply-policy";
5
5
  import type { ReplyBudget } from "../quota/reply-quota";
6
6
  import type { ReplyType } from "../infra/reply-type";
7
7
  import { isLogEnabled, log } from "../infra/file-logger";
8
+ import { shortId } from "../infra/short-id";
8
9
 
9
10
  export interface RunFeedbackDeps {
10
11
  bot: () => QQBot | undefined;
@@ -20,6 +21,8 @@ interface RunState {
20
21
  thinkingSentLen: number;
21
22
  finalizedText: string;
22
23
  resultSentLen: number;
24
+ lastFinalizedTextLen: number;
25
+ lastResultSentLen: number;
23
26
  deferredThinking: string;
24
27
  deferredText: string;
25
28
  timeline: RunTimeline;
@@ -129,7 +132,7 @@ export class RunFeedback {
129
132
 
130
133
  log.debug("run", "stream timing", {
131
134
  phase: "last repush",
132
- msgId: msgId.slice(0, 8),
135
+ msgId: shortId(msgId),
133
136
  replyType,
134
137
  textLength,
135
138
  thinkingLength,
@@ -171,7 +174,7 @@ export class RunFeedback {
171
174
  }
172
175
  const bot = this.deps.bot();
173
176
  if (!bot) {
174
- log.debug("run", "run started", { phase: "no bot", msgId: target.msgId.slice(0, 8) });
177
+ log.debug("run", "run started", { phase: "no bot", msgId: shortId(target.msgId) });
175
178
  return;
176
179
  }
177
180
 
@@ -191,6 +194,8 @@ export class RunFeedback {
191
194
  thinkingSentLen: 0,
192
195
  finalizedText: "",
193
196
  resultSentLen: 0,
197
+ lastFinalizedTextLen: 0,
198
+ lastResultSentLen: 0,
194
199
  deferredThinking: "",
195
200
  deferredText: "",
196
201
  timeline: new RunTimeline(),
@@ -199,7 +204,7 @@ export class RunFeedback {
199
204
  this.run = run;
200
205
  if (isLogEnabled("debug")) {
201
206
  log.debug("run", "run started", {
202
- msgId: run.msgId?.slice(0, 8) ?? "?",
207
+ msgId: shortId(run.msgId),
203
208
  source: target === pending ? "pending" : "recovery",
204
209
  targetAgeMs: now - target.at,
205
210
  replyType: this.deps.getReplyType(),
@@ -226,13 +231,6 @@ export class RunFeedback {
226
231
  }
227
232
  const tool = run.timeline.addTool(toolName, args, id);
228
233
  if (!tool) return;
229
- log.debug("run", "tool start", {
230
- phase: "queued",
231
- toolName,
232
- toolCallId: id,
233
- skillName: tool.skillName ?? null,
234
- ...this.diagnostics(run),
235
- });
236
234
  this.advanceTools(run);
237
235
  }
238
236
 
@@ -248,13 +246,6 @@ export class RunFeedback {
248
246
  log.debug("run", "tool end", { phase: "ignored: unknown tool", toolName, toolCallId: id });
249
247
  return;
250
248
  }
251
- log.debug("run", "tool end", {
252
- phase: "result recorded",
253
- toolName,
254
- toolCallId: id,
255
- isError,
256
- ...this.diagnostics(run),
257
- });
258
249
  this.advanceTools(run);
259
250
  }
260
251
 
@@ -316,19 +307,23 @@ export class RunFeedback {
316
307
  if (this.autoRebinds > 0) ok = await run.writer.flush();
317
308
  }
318
309
  const streamTookOver = !isError && ok && run.writer.hasPushed;
319
- log.debug("run", "stream takeover decision", {
320
- phase: "assistant final",
321
- textLength: text.length,
322
- deltaLength: delta.length,
323
- isError,
324
- hadPendingTools,
325
- flushOk: ok,
326
- hasPushed: run.writer.hasPushed,
327
- streamTookOver,
328
- deferredTextLen: run.deferredText.length,
329
- deferredThinkingLen: run.deferredThinking.length,
330
- ...this.diagnostics(run),
331
- });
310
+ if (text.length > 0 || !streamTookOver) {
311
+ log.debug("run", "stream takeover decision", {
312
+ phase: "assistant final",
313
+ textLength: text.length,
314
+ deltaLength: delta.length,
315
+ isError,
316
+ hadPendingTools,
317
+ flushOk: ok,
318
+ hasPushed: run.writer.hasPushed,
319
+ streamTookOver,
320
+ deferredTextLen: run.deferredText.length,
321
+ deferredThinkingLen: run.deferredThinking.length,
322
+ ...this.diagnostics(run),
323
+ });
324
+ }
325
+ run.lastFinalizedTextLen = run.finalizedText.length;
326
+ run.lastResultSentLen = run.resultSentLen;
332
327
  run.finalizedText = "";
333
328
  run.resultSentLen = 0;
334
329
  if (isError) return false;
@@ -348,24 +343,26 @@ export class RunFeedback {
348
343
  this.clearTimers();
349
344
  if (run.timeline.currentText.trim()) this.lastCompletedText = run.timeline.currentText;
350
345
  if (!run.timeline.error && run.writer.hasPushed) this.recovery = null;
346
+ let delivered = false;
347
+ if (run.writer.hasPushed) {
348
+ const ok = await run.writer.flush();
349
+ if (ok) {
350
+ await run.writer.done();
351
+ delivered = true;
352
+ }
353
+ }
351
354
  log.debug("run", "run ended", {
352
355
  phase: "cleanup",
353
- msgId: run.msgId?.slice(0, 8) ?? "?",
356
+ msgId: shortId(run.msgId),
354
357
  elapsedMs: Date.now() - run.startedAt,
355
358
  hasPendingTools,
356
359
  hasPushed: run.writer.hasPushed,
360
+ delivered,
357
361
  lastCompletedTextLength: this.lastCompletedText?.length ?? 0,
362
+ lastFinalizedTextLen: run.lastFinalizedTextLen,
363
+ lastResultSentLen: run.lastResultSentLen,
358
364
  ...this.diagnostics(run),
359
365
  });
360
- log.debug("run", "run ended", {
361
- phase: "finished",
362
- msgId: run.msgId?.slice(0, 8) ?? "?",
363
- elapsedMs: Date.now() - run.startedAt,
364
- });
365
- if (run.writer.hasPushed) {
366
- const ok = await run.writer.flush();
367
- if (ok) await run.writer.done();
368
- }
369
366
  run.writer.dispose();
370
367
  if (this.run === run) this.run = null;
371
368
  this.finishEnd();
@@ -419,7 +416,7 @@ export class RunFeedback {
419
416
  this.autoRebinds += 1;
420
417
  log.debug("run", "stream timing", {
421
418
  phase: "auto rebind",
422
- msgId: msgId.slice(0, 8),
419
+ msgId: shortId(msgId),
423
420
  freshTarget,
424
421
  targetAgeMs,
425
422
  textLength: result.textLength,
@@ -480,6 +477,7 @@ export class RunFeedback {
480
477
  toolName: tool.name,
481
478
  toolCallId: tool.id,
482
479
  skillName: tool.skillName ?? null,
480
+ queueWaitMs: Date.now() - tool.startedAt,
483
481
  ...this.diagnostics(run),
484
482
  });
485
483
  if (!run.writer.dead && relayTools) {
@@ -111,7 +111,7 @@ export class RunTimeline {
111
111
  activeTool: this.activeToolId ?? null,
112
112
  toolCount: this.tools.length,
113
113
  pendingToolCount: this.tools.filter((tool) => !tool.finished).length,
114
- tools: this.tools.map((tool) => ({
114
+ tools: this.snapshot().tools.map((tool) => ({
115
115
  id: tool.id,
116
116
  name: tool.name,
117
117
  started: tool.started,
@@ -1,5 +1,6 @@
1
1
  import { StreamContentType, StreamInputState } from "@tencent-connect/qqbot-nodejs/protocol";
2
2
  import { allocateMsgSeq } from "./msg-seq";
3
+ import { shortId } from "../infra/short-id";
3
4
  import type {
4
5
  Credentials,
5
6
  MessageApi,
@@ -10,6 +11,7 @@ import type {
10
11
  const MIN_INTERVAL_MS = 300;
11
12
  const RATE_LIMIT_BASE_MS = 1000;
12
13
  const MAX_RETRIES = 3;
14
+ const SLOW_FRAME_MS = 1000;
13
15
  // QQ rejects oversized markdown shards with 40034017. The platform appears to
14
16
  // split frames larger than roughly 4k and then requires every shard to end at
15
17
  // a newline; 3500 bytes leaves room for that limit and for multi-byte text.
@@ -47,7 +49,6 @@ export class AppendStream {
47
49
  private buffer = "";
48
50
  private flushTimer: ReturnType<typeof setTimeout> | null = null;
49
51
  private flushing = false;
50
- private flushingAppends = 0;
51
52
  private lastFlushAt = 0;
52
53
 
53
54
  constructor(
@@ -97,28 +98,18 @@ export class AppendStream {
97
98
  async append(delta: string): Promise<void> {
98
99
  if (this.doneSent || !delta) return;
99
100
  this.buffer += delta;
101
+ if (this.flushing) return;
100
102
  const elapsed = Date.now() - this.lastFlushAt;
101
103
  const throttle = this.throttleMs();
102
- if (this.flushing) {
103
- this.flushingAppends += 1;
104
- if (this.flushingAppends === 1 || this.flushingAppends % 50 === 0) {
105
- this.opts.onDebug?.(`append: while flushing, count=${this.flushingAppends}, buffer=${this.buffer.length}`);
106
- }
107
- return;
108
- }
109
104
  if (elapsed >= throttle) {
110
- this.opts.onDebug?.(`append: immediate, elapsed=${elapsed}, buffer=${this.buffer.length}`);
111
105
  await this.doFlush("generating");
112
106
  return;
113
107
  }
114
108
  if (!this.flushTimer) {
115
- const waitMs = throttle - elapsed;
116
- this.opts.onDebug?.(`append: buffered, elapsed=${elapsed}, wait=${waitMs}, buffer=${this.buffer.length}`);
117
109
  this.flushTimer = setTimeout(() => {
118
110
  this.flushTimer = null;
119
- this.opts.onDebug?.(`timer: fired after ${waitMs}, buffer=${this.buffer.length}`);
120
111
  void this.doFlush("generating").catch((err) => this.opts.onError?.(err as Error));
121
- }, waitMs);
112
+ }, throttle - elapsed);
122
113
  }
123
114
  }
124
115
 
@@ -196,11 +187,8 @@ export class AppendStream {
196
187
  const frame = state === "done" ? { text: "", consumed: 0 } : this.takeFrame();
197
188
  const content = frame.text;
198
189
  if (!content && state === "generating") return;
199
- this.opts.onDebug?.(
200
- `flush: start state=${state}, content=${content.length}, index=${this.index}, msgSeq=${this.msgSeq ?? "none"}, streamMsgId=${this.streamMsgId ?? "none"}`,
201
- );
190
+ const frameStartedAt = Date.now();
202
191
  this.flushing = true;
203
- this.flushingAppends = 0;
204
192
  let failed = false;
205
193
  try {
206
194
  if (this.msgSeq === null) this.msgSeq = allocateMsgSeq(this.msgId);
@@ -220,9 +208,17 @@ export class AppendStream {
220
208
  if (resp?.id && !this.streamMsgId) this.streamMsgId = resp.id;
221
209
  if (state === "generating") this.buffer = this.buffer.slice(frame.consumed);
222
210
  this.lastFlushAt = Date.now();
223
- this.opts.onDebug?.(
224
- `flush: done state=${state}, remaining=${this.buffer.length}, streamMsgId=${this.streamMsgId ?? "none"}`,
225
- );
211
+ const elapsedMs = this.lastFlushAt - frameStartedAt;
212
+ const remaining = this.buffer.length;
213
+ if (elapsedMs >= SLOW_FRAME_MS) {
214
+ this.opts.onDebug?.(
215
+ `flush: slow state=${state}, elapsed=${elapsedMs}, content=${content.length}, index=${index}, msgSeq=${this.msgSeq ?? "none"}, streamMsgId=${shortId(this.streamMsgId)}, remaining=${remaining}`,
216
+ );
217
+ } else if (remaining > 0) {
218
+ this.opts.onDebug?.(
219
+ `flush: partial state=${state}, index=${index}, msgSeq=${this.msgSeq ?? "none"}, streamMsgId=${shortId(this.streamMsgId)}, remaining=${remaining}`,
220
+ );
221
+ }
226
222
  } catch (err) {
227
223
  failed = true;
228
224
  throw err;