@chen_hu_hu/pi-qq 1.5.1 → 1.6.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/CHANGELOG.md CHANGED
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.6.0] - 2026-11-09
11
+
12
+ ### Added
13
+
14
+ - Added the `replyType` setting to control how much of an agent run is pushed to QQ: `full` (thinking, tool calls, and tool results), `simple` (assistant messages only, one bubble each), or `last` (only the last assistant message, delivered when the run ends). The default is `full`, so the default behaviour is unchanged; set `"replyType": "simple"` or `"last"` to push less to QQ.
15
+ - Added the effective reply type to `/qq-status`.
16
+
17
+ ### Changed
18
+
19
+ - In `last` mode, `/last` during a running task now replies that the task is still running instead of repushing partial output.
20
+ - Consolidated the v6 design and delivery record into `doc/archive/delivery-v6.md`; removed the working document.
21
+
22
+ ### Fixed
23
+
24
+ - The `last` reply mode now records its delivery result (`last delivered`) in the debug log before the run state is cleared, so the record is no longer dropped by the QQ-run log gate.
25
+ - Bubbles that pass 12k characters are now split at the next line break found in the incoming text chunk. Previously the split only happened when a chunk happened to end with a newline, which almost never occurred, so long messages were split by the platform instead and thinking blocks lost their repeated heading.
26
+
10
27
  ## [1.5.1] - 2026-11-05
11
28
 
12
29
  ### Changed
package/README-zh.md CHANGED
@@ -135,6 +135,9 @@ QQ 侧命令:
135
135
  ```json
136
136
  {
137
137
  "thinkingRelay": true,
138
+ "replyType": "full",
139
+ "deliverAs": "steer",
140
+ "fileMaxSize": 52428800,
138
141
  "language": "zh-cn",
139
142
  "logLevel": "silent"
140
143
  }
@@ -143,6 +146,7 @@ QQ 侧命令:
143
146
  | 配置项 | 默认值 | 说明 |
144
147
  | --------------- | ---------- | ------------------------------------------------------ |
145
148
  | `thinkingRelay` | `true` | 以本地化的 `## 💭` 标题纯文本回传思考;`false` 时隐藏 |
149
+ | `replyType` | `"full"` | 推送到 QQ 的内容粒度:`full`、`simple`、`last` |
146
150
  | `deliverAs` | `"steer"` | 忙碌时新消息的排队方式:`steer` 或 `followUp` |
147
151
  | `fileMaxSize` | `52428800` | QQ 附件下载上限(字节,50MB) |
148
152
  | `language` | `"zh-cn"` | UI 和日志语言:`zh-cn` 或 `en-us` |
@@ -150,7 +154,57 @@ QQ 侧命令:
150
154
 
151
155
  配置在 pi 会话启动时读取;修改文件后请重启 pi。未知配置项会被忽略,无效值会回退到默认值并给出提示。
152
156
 
153
- 启用日志后,只有 QQ 触发的 run 处于活动状态时才会写入记录,路径为 `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`;可用 `PI_QQ_LOG_DIR` 覆盖目录。`info` 只记录元数据;`debug` 记录完整事件、附件、提示词和工具参数/结果。
157
+ ### `replyType`
158
+
159
+ 一次 run 中哪些内容会被推送到 QQ。
160
+
161
+ | 模式 | QQ 收到的内容 |
162
+ | -------- | ------------------------------------------------------------- |
163
+ | `full` | 思考块、工具调用、工具结果,以及每一条 assistant 消息(默认) |
164
+ | `simple` | 只推 assistant 消息,每条一个气泡 |
165
+ | `last` | 只推 run 中最后一条 assistant 消息,在 run 结束时送出 |
166
+
167
+ - `full` 是默认值,保持 pi-qq 1.5.x 的行为,也是唯一会应用 `thinkingRelay` 的模式。
168
+ - `simple` 会实时流出每一条 assistant 消息,一条消息一个气泡。
169
+ - `last` 在任务运行期间不推送任何内容;运行期间执行 `/last` 会回复“任务仍在进行中”。
170
+ - 无论哪种模式,模型错误消息都会立即以普通消息发出。
171
+ - `simple` 与 `last` 不回传工具输出,但 `qq_send_media` 发送的文件仍然会送达。
172
+
173
+ ### `thinkingRelay`
174
+
175
+ 是否把模型的思考单独回传成一个气泡。
176
+
177
+ - `true`(默认):以本地化的 `## 💭` 标题纯文本回传思考。
178
+ - `false`:丢弃思考。
179
+ - 只在 `replyType: "full"` 下生效;`simple` 与 `last` 不会回传思考。
180
+
181
+ ### `deliverAs`
182
+
183
+ 任务正在运行时,QQ 消息如何进入 pi。
184
+
185
+ - `steer`(默认):在下一个安全点注入当前任务。
186
+ - `followUp`:排队,等当前任务结束后再处理。
187
+
188
+ ### `fileMaxSize`
189
+
190
+ 入站附件的大小上限,单位为字节(默认 `52428800`,即 50MB)。超过上限的附件会被拒绝并提示,不会下载,避免占满本地磁盘和下载额度。
191
+
192
+ ### `language`
193
+
194
+ UI 提示与日志的语言。
195
+
196
+ - `zh-cn`(默认):简体中文。
197
+ - `en-us`:英文。
198
+
199
+ ### `logLevel`
200
+
201
+ 日志阈值。只有 QQ 触发的 run 处于活动状态时才会写记录,路径为 `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`;可用 `PI_QQ_LOG_DIR` 覆盖目录。
202
+
203
+ - `silent`(默认):完全不写日志文件。
204
+ - `error`:只记录失败。
205
+ - `warn`:记录失败与可恢复的问题。
206
+ - `info`:额外记录 run 元信息——消息 id、内容长度、agent 开始与结束。
207
+ - `debug`:记录全部内容,包括工具参数与结果、附件元数据、提示词和语音转写原文。
154
208
 
155
209
  ## 开发
156
210
 
package/README.md CHANGED
@@ -135,6 +135,9 @@ Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; c
135
135
  ```json
136
136
  {
137
137
  "thinkingRelay": true,
138
+ "replyType": "full",
139
+ "deliverAs": "steer",
140
+ "fileMaxSize": 52428800,
138
141
  "language": "zh-cn",
139
142
  "logLevel": "silent"
140
143
  }
@@ -143,6 +146,7 @@ Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; c
143
146
  | Key | Default | Description |
144
147
  | --------------- | ---------- | ------------------------------------------------------------ |
145
148
  | `thinkingRelay` | `true` | Relay thinking as plain text with a localized `## 💭` header |
149
+ | `replyType` | `"full"` | How much of a run is pushed to QQ: `full`, `simple`, `last` |
146
150
  | `deliverAs` | `"steer"` | Queue new messages while busy: `steer` or `followUp` |
147
151
  | `fileMaxSize` | `52428800` | QQ attachment download limit in bytes (50MB) |
148
152
  | `language` | `"zh-cn"` | UI and log language: `zh-cn` or `en-us` |
@@ -150,7 +154,57 @@ Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; c
150
154
 
151
155
  Settings are read when a pi session starts; restart pi after editing the file. Unknown keys are ignored, and invalid values fall back to defaults with a warning.
152
156
 
153
- When logging is enabled, records are written only while a QQ-triggered run is active. Logs go to `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`; `PI_QQ_LOG_DIR` overrides the directory. `info` records metadata only; `debug` records full events, attachments, prompts, and tool payloads.
157
+ ### `replyType`
158
+
159
+ How much of an agent run is pushed to QQ.
160
+
161
+ | Value | QQ receives |
162
+ | -------- | -------------------------------------------------------------------------------- |
163
+ | `full` | Thinking blocks, tool calls, tool results, and every assistant message (default) |
164
+ | `simple` | Assistant messages only, one bubble each |
165
+ | `last` | Only the last assistant message of the run, sent when the run ends |
166
+
167
+ - `full` is the default and keeps the behaviour of pi-qq 1.5.x; it is the only mode where `thinkingRelay` applies.
168
+ - `simple` streams every assistant message live, one QQ bubble per message.
169
+ - `last` sends nothing while the task is running; `/last` during a running task replies that the task is still running.
170
+ - Model errors are always delivered immediately as a normal message, in every mode.
171
+ - Tool output is not relayed in `simple` or `last`, but files sent with `qq_send_media` are still delivered.
172
+
173
+ ### `thinkingRelay`
174
+
175
+ Whether the model's thinking is relayed to QQ as its own bubble.
176
+
177
+ - `true` (default): thinking is relayed as plain text under a localized `## 💭` heading.
178
+ - `false`: thinking is dropped.
179
+ - Only applies to `replyType: "full"`; `simple` and `last` never relay thinking.
180
+
181
+ ### `deliverAs`
182
+
183
+ How a QQ message reaches pi while a task is already running.
184
+
185
+ - `steer` (default): the message is injected into the running task at the next safe point.
186
+ - `followUp`: the message is queued and processed after the running task finishes.
187
+
188
+ ### `fileMaxSize`
189
+
190
+ Maximum size of an inbound attachment, in bytes (default `52428800`, 50MB). Larger files are rejected with a notice instead of being downloaded, which keeps the local disk and the download quota under control.
191
+
192
+ ### `language`
193
+
194
+ Language of the UI notifications and the log messages.
195
+
196
+ - `zh-cn` (default): Simplified Chinese.
197
+ - `en-us`: English.
198
+
199
+ ### `logLevel`
200
+
201
+ Log threshold. Records are written only while a QQ-triggered run is active, to `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`; `PI_QQ_LOG_DIR` overrides the directory.
202
+
203
+ - `silent` (default): no log file at all.
204
+ - `error`: failures only.
205
+ - `warn`: failures and recoverable problems.
206
+ - `info`: run metadata as well — message ids, content lengths, agent start and end.
207
+ - `debug`: everything, including tool arguments and results, attachment metadata, prompts, and raw voice transcripts.
154
208
 
155
209
  ## Development
156
210
 
@@ -0,0 +1,263 @@
1
+ # pi-qq delivery-v6
2
+
3
+ > **Delivery record.** v6 adds the `replyType` setting to control how much of an agent run is pushed to QQ, and fixes the 12k bubble split that almost never fired. See [README](../../README.md) for current user-facing behavior.
4
+ > Version: 1.6.0
5
+ > Date: 2026-11-09
6
+ > Previous: [delivery-v1.md](./delivery-v1.md), [delivery-v2.md](./delivery-v2.md), [delivery-v3.md](./delivery-v3.md), [delivery-v4.md](./delivery-v4.md), [delivery-v5.md](./delivery-v5.md).
7
+ > Open work: [doc/todo.md](../todo.md).
8
+
9
+ ## 1. Scope
10
+
11
+ Before v6, pi-qq pushed everything the agent produced into QQ: thinking blocks, tool start lines, tool results, skill blocks, and every assistant message. A 29-minute run produced 184 bubbles (see [doc/todo.md](../todo.md)), so the actual answer was buried in tool noise.
12
+
13
+ v6 gives that choice a name and a setting:
14
+
15
+ - a new `replyType` setting with three modes: `full` (current behaviour), `simple`, `last`;
16
+ - `full` stays the default, so upgrading changes nothing;
17
+ - `/last` during a running task no longer repushes partial output in `last` mode;
18
+ - `/qq-status` shows the effective mode;
19
+ - an unrelated existing defect is fixed: the 12k bubble split almost never fired.
20
+
21
+ In scope:
22
+
23
+ - `replyType` parsing, validation, and defaulting;
24
+ - per-mode relay behaviour in `RunFeedback`;
25
+ - `last` mode delivery at the end of a run, with plain-message fallback;
26
+ - the `/last` command change in `last` mode;
27
+ - the reply type in `/qq-status`;
28
+ - the 12k bubble split fix.
29
+
30
+ Out of scope:
31
+
32
+ - summarising, trimming, or rewriting model output;
33
+ - changing pi's agent behaviour, prompts, or tool set;
34
+ - per-command or per-session mode switching;
35
+ - changing `qq_send_media` behaviour (media files are still delivered in every mode);
36
+ - a "progress hint" while a `last` run is in flight.
37
+
38
+ ## 2. Final decisions
39
+
40
+ | # | Question | Decision |
41
+ | --- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
42
+ | D1 | Should `last` send a progress hint while the task runs? | No. It contradicts "only the last message"; the typing indicator already covers the wait. A hint would be its own setting, not a mode. |
43
+ | D2 | Should `simple` offer a "merge adjacent assistant messages" switch? | No. One assistant message is one bubble; the boundary already comes from `closeBlock()`. |
44
+ | D3 | Should QQ commands switch the mode at runtime (e.g. `/mode last`)? | No. Two sources of truth would compete with `deliverAs` and the other settings. |
45
+ | D4 | How is Markdown handled for the `last` message? | Keep the existing split: the stream channel sends raw Markdown, the plain-message fallback runs `markdownToPlain()`. |
46
+ | D5 | Should `/qq-status` show the reply type? | Yes. One `💬 Reply type: <mode>` line, so the effective setting is verifiable. |
47
+ | D6 | What should `/last` do during a running task in `last` mode? | Do not repush. Reply with a localized notice (`commands.last.running`) instead: whatever is on screen cannot be the last message. |
48
+ | D7 | When is the setting read? | Per session. `activeSettings` is refreshed on `session_start` and `/qq-login`; the config file is never read on the hot path. |
49
+ | D8 | Should `last` still deliver after `/stop` aborts the run? | Yes. `agent_end` also fires on abort, and a conclusion the agent already reached should not be lost. |
50
+
51
+ ## 3. The three modes
52
+
53
+ | Dimension | `full` | `simple` | `last` |
54
+ | -------------------------- | ----------------------------------- | ------------------------- | ---------------------------------- |
55
+ | Thinking blocks | per `thinkingRelay` | no | no |
56
+ | Tool start lines / results | yes | no | no |
57
+ | Assistant text | all, streamed live | all, streamed live | last one only |
58
+ | When the text reaches QQ | while generated | while generated | when the run ends |
59
+ | Bubbles per run | one per block switch (often dozens) | one per assistant message | 1 (or 1 plain message on fallback) |
60
+ | Model error message | immediately, as a plain message | same | same |
61
+
62
+ - `full` is the default and reproduces pi-qq 1.5.x exactly.
63
+ - `simple` streams every assistant message live, one QQ bubble per message. Text produced while a tool is still running is pushed immediately instead of being deferred until the tool batch ends (there is no tool bubble to keep it clear of).
64
+ - `last` sends nothing while the task runs. When the run ends, the last assistant message that has text is delivered as one bubble (stream first, plain message on failure).
65
+ - "Last" means the last assistant message **with text**. A trailing message that only carries a tool call falls back to the previous one with text.
66
+ - A model error is always delivered immediately as a plain message, in every mode, and never occupies the "last message" slot.
67
+ - Tool output is never relayed in `simple` or `last`, but files sent with `qq_send_media` still arrive.
68
+
69
+ Example run:
70
+
71
+ ```text
72
+ user : 帮我看下 README 里的安装步骤对不对
73
+
74
+ agent : thinking 用户问的是安装步骤,先读 README
75
+ tool read README.md
76
+ message 1 我先读一下 README。
77
+ tool bash grep -n install
78
+ message 2 README 里的安装步骤是 npm i -g pi。
79
+ ```
80
+
81
+ | Mode | QQ bubbles |
82
+ | -------- | --------------------------------------------------------------------------------------------------------------- |
83
+ | `full` | ① 💭 thinking ② 📖 read + result ③ 我先读一下 README。 ④ 💻 bash + result ⑤ README 里的安装步骤是 npm i -g pi。 |
84
+ | `simple` | ① 我先读一下 README。 ② README 里的安装步骤是 npm i -g pi。 |
85
+ | `last` | ① README 里的安装步骤是 npm i -g pi。(sent when the run ends) |
86
+
87
+ ## 4. Configuration
88
+
89
+ `~/.pi/agent/pi-qq.json`:
90
+
91
+ ```json
92
+ {
93
+ "replyType": "full"
94
+ }
95
+ ```
96
+
97
+ | Key | Type | Default | Meaning |
98
+ | ----------- | ------------------------------ | -------- | ---------------------------- |
99
+ | `replyType` | `"full" \| "simple" \| "last"` | `"full"` | How much of a run reaches QQ |
100
+
101
+ - An invalid value is ignored and falls back to the default, with a warning at session start: `replyType must be "full", "simple", or "last"`.
102
+ - `thinkingRelay` only applies to `full`; in `simple` and `last` thinking is never relayed.
103
+ - `deliverAs` is unrelated: it controls how QQ messages enter pi, `replyType` controls how pi's output returns to QQ.
104
+ - The default stays `full`, so upgrading changes nothing and there is no migration step.
105
+
106
+ ## 5. Implementation
107
+
108
+ ### 5.1 Layers
109
+
110
+ | File | Change |
111
+ | --------------------------------- | ------------------------------------------------------------------------------------------------------ |
112
+ | `src/infra/reply-type.ts` (new) | `ReplyType`, `REPLY_TYPES`, `DEFAULT_REPLY_TYPE = "full"`, `isReplyType()` |
113
+ | `src/infra/settings.ts` | `PiQQSettings.replyType`, validation in `parseConfig()`, default in `getSettings()` |
114
+ | `src/infra/i18n.ts` | `settings.replyType`, `status.replyType`, `commands.last.running` |
115
+ | `src/relay/reply-policy.ts` (new) | `ReplyPolicy` + `policyFor(type)` |
116
+ | `src/relay/run-stream-relay.ts` | Policy lookup per event; `lastText` buffering; end-of-run delivery and fallback; `onFallbackReply` dep |
117
+ | `src/qq/inbound-command.ts` | `/last` replies with a notice in `last` mode while a task is running |
118
+ | `src/qq/qq-message-handler.ts` | `InboundDeps.getReplyType` |
119
+ | `src/qq/status-report.ts` | `💬 Reply type: <mode>` line |
120
+ | `index.ts` | `getReplyType` / `onFallbackReply` wiring, `replyType` in session and bot logs |
121
+
122
+ `src/relay/bubble-writer.ts` is mode-agnostic: the writer only puts text into bubbles, and every mode difference is absorbed by `RunFeedback`.
123
+
124
+ ### 5.2 Policy
125
+
126
+ ```ts
127
+ export interface ReplyPolicy {
128
+ relayThinking: boolean;
129
+ relayTools: boolean;
130
+ relayTextLive: boolean;
131
+ deferTextWhileToolsPending: boolean;
132
+ deliverLastAtEnd: boolean;
133
+ }
134
+ ```
135
+
136
+ | Mode | relayThinking | relayTools | relayTextLive | deferTextWhileToolsPending | deliverLastAtEnd |
137
+ | -------- | ------------------------- | ---------- | ------------- | -------------------------- | ---------------- |
138
+ | `full` | yes (and `thinkingRelay`) | yes | yes | yes | no |
139
+ | `simple` | no | no | yes | no | no |
140
+ | `last` | no | no | no | no | yes |
141
+
142
+ ### 5.3 `last` mode
143
+
144
+ State: `RunState.lastText` holds the latest assistant message that has text.
145
+
146
+ - `onAssistantDelta(snapshot, thinking)`: nothing is pushed; a non-empty snapshot updates `lastText`.
147
+ - `onAssistantFinal(text, isError)`: a non-empty, non-error text becomes `lastText` and the call returns `true`, which suppresses the plain-message fallback in `index.ts` (the message is delivered at the end of the run instead). An error returns `false`, so the error keeps going out immediately through `sendReply`.
148
+ - `onAgentEnd()`: `planLastDelivery()` delivers `lastText`:
149
+ 1. if `budget.snapshot().fresh` is false (the inbound message is older than the passive window), skip the stream and use the plain message path directly;
150
+ 2. otherwise push the text into the bubble, rotate, flush, and `DONE`;
151
+ 3. if the stream fails, fall back to `onFallbackReply(text)`, which reuses `sendReply()` — passive first, proactive when the window expired, chunked at 4500 characters.
152
+
153
+ ```text
154
+ QQ message ─▶ agent_start
155
+ ├─ thinking / tools / intermediate assistant text ─▶ dropped (latest text buffered)
156
+ ├─ message_end(last assistant message) ─▶ lastText = "..."
157
+ └─ agent_end
158
+ ├─ budget stale? ──yes──▶ sendReply(plain message)
159
+ └─ no ─▶ writer.pushText(lastText) ─▶ flush
160
+ ├─ ok ─▶ DONE
161
+ └─ fail ─▶ onFallbackReply(lastText) ─▶ sendReply(plain message)
162
+ ```
163
+
164
+ ### 5.4 Commands
165
+
166
+ | Command | Behaviour |
167
+ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
168
+ | `/last` (busy) | `full` / `simple`: `repushCurrent()`, the current assistant text is pushed to the new `msg_id`. `last`: a localized notice, no repush. |
169
+ | `/last` (idle) | The last completed reply is re-pushed as a stream, in every mode. |
170
+ | `/stop` | Aborts the run; `agent_end` still fires, so `last` mode still delivers the buffered text. |
171
+ | `/status` | Session, context, and battery; unaffected by the mode. |
172
+
173
+ ### 5.5 Debug logs
174
+
175
+ - `session started`, `starting bot`, and `run started` carry `replyType`.
176
+ - `last` mode adds `run / last buffered` (`textLength`, `isError`) and `run / last delivered` (`delivered`, `fallback`).
177
+ - The `last delivered` record must be written **before** the run state is cleared: the log gate only opens while a QQ run is active, so `onAgentEnd()` now nulls `this.run` after the final flush and guards it with `if (this.run === run)`.
178
+
179
+ ## 6. The 12k bubble split fix
180
+
181
+ This defect is unrelated to `replyType`; it existed in `full` mode as well.
182
+
183
+ **Symptom**: a single assistant message longer than 12k characters was not split. One measured message of 12590 characters used a single `stream_msg_id` for all 28 frames.
184
+
185
+ **Cause**: the split condition was `(blockBoundary || this.lastChar === "\n")`.
186
+
187
+ - `blockBoundary` is only true on a block switch, so it is always false for a continuous text stream;
188
+ - `this.lastChar === "\n"` requires the **previously pushed chunk** to end with a newline. Chunks arrive at the provider's SSE granularity, which has nothing to do with content, so this is a lottery. The measured message had 14 newlines after the 12k mark (all with the code fence closed) and none of them coincided with a chunk boundary.
189
+
190
+ **Impact**: no error, no lost content, no dead stream — the platform splits on its own when its own limit is hit. The cost is that the split point is chosen by the platform (possibly mid-line) and that a platform-split continuation bubble does not repeat the `## 💭` heading, so the v3 intent ("split at the 12k boundary and repeat the header") was lost.
191
+
192
+ **Fix**: find the split point in the chunk that is being pushed:
193
+
194
+ ```ts
195
+ private splitPoint(text: string, newBubble: boolean): number {
196
+ if (newBubble) return -1;
197
+ if (!this.cur) return -1;
198
+ if (this.pendingResume) return -1;
199
+ if (this.fenceOpen) return -1;
200
+ if (this.toolOpen) return -1;
201
+ if (this.bubbleChars < MAX_BUBBLE_CHARS) return -1;
202
+ return text.indexOf("\n");
203
+ }
204
+ ```
205
+
206
+ When a split point exists, the chunk is appended in two parts with a bubble rotation in between: the old bubble ends with the newline, the new bubble starts at a line start, and a thinking block repeats its `## 💭` heading. When the chunk has no newline, nothing is split yet and the next chunk with a newline is used. The overshoot is the distance to the next newline in the stream — normally tens of characters. Pathological single-line content is left to the platform.
207
+
208
+ Unchanged constraints: never split inside an open code fence, never split while a tool block is open (tool header and result stay together), never split while a resume checkpoint is pending.
209
+
210
+ ## 7. Verification
211
+
212
+ Automated:
213
+
214
+ - **224 tests passed** across 19 files (22 new: settings 5, relay 13, inbound command 2, status report 2, i18n 1).
215
+ - `npm run typecheck`, `npm run lint`, `npm run format:check`, and `npm pack --dry-run` passed.
216
+
217
+ Real QQ, log `~/project/mine/pi-qq-test/.pi/pi-qq/logs/pi-qq-2026-11-09.log`:
218
+
219
+ | Case | Result |
220
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
221
+ | `last`, 5 runs | Exactly one stream message per run, each containing only the final assistant text (284 / 899 / 1263 / 1147 / 232 characters) |
222
+ | `last`, long run | Typing indicator kept the chat alive every 50s for a 4.5-minute run |
223
+ | `last`, media tool | `qq_send_media` uploaded and sent the image (passive) even though the tool bubble was suppressed |
224
+ | `last`, log gap | The `last delivered` record was missing because the log gate closed first; fixed, with a regression test |
225
+ | `simple`, 26 runs | 39 frames in 3 bubbles; **0** frames contained a tool or thinking marker |
226
+ | `simple`, live streaming | A 12590-character message was streamed in 28 frames over ~27 seconds |
227
+ | `simple`, one bubble per message | Two assistant messages produced two bubbles |
228
+ | Provider rate limit | 25 runs ended with the model provider's `429` TPM limit; each error was delivered immediately as a plain message, proactive once the passive window had expired |
229
+ | 12k split | The 12590-character message stayed in one bubble (the defect above); fixed in this release |
230
+
231
+ Not covered by the acceptance run:
232
+
233
+ - a message long enough to cross the platform's own limit, so the platform-side auto split was not observed;
234
+ - `last` mode with a run longer than the passive window (the stale-target fallback path was only exercised in tests);
235
+ - the `simple` mode tool-output suppression was verified from the logs, not from the QQ client rendering.
236
+
237
+ ## 8. Risks and limitations
238
+
239
+ | Risk | Impact | Handling |
240
+ | --------------------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------ |
241
+ | The default stays `full`, so `simple` / `last` are opt-in | None for existing users | Documented in both READMEs and the CHANGELOG |
242
+ | `last` sends nothing while the run is in flight | A long task looks idle on the phone | The typing indicator keeps running; a progress hint is a possible follow-up |
243
+ | `last` delivers at the end, when the passive window may be gone | The final message becomes a proactive message | `budget.snapshot().fresh` pre-check plus a plain-message fallback |
244
+ | `simple` pushes text while a tool is still running | Different from "collect everything after the tools" | Documented; the mode is opt-in |
245
+ | `thinkingRelay` has no effect in `simple` / `last` | May confuse users | Both READMEs state it explicitly |
246
+ | `/last` during a run is unavailable in `last` mode | The manual rescue path for stuck runs is gone | The command answers with a localized notice; the run still delivers its last message |
247
+ | `onAssistantFinal` returns `true` in `last` mode | "Handled" now means "delivered later", not "already sent" | Documented in the design and in the code |
248
+
249
+ ## 9. Open work
250
+
251
+ - [doc/todo.md](../todo.md) item 1: long-running bash argument visibility.
252
+ - [doc/todo.md](../todo.md) item 2: long-running tools leading to missing QQ output.
253
+ - `doc/todo.md` recommends using `/last` to recover a stuck run; in `last` mode that path is unavailable during the run, and the note should say so.
254
+ - Whether `last` needs a progress hint (D1) once real usage shows the waiting feels too long.
255
+ - Whether the platform's own bubble limit should be measured, so the 12k margin can be tuned.
256
+
257
+ ## 10. References
258
+
259
+ - Design history: [delivery-v5.md](./delivery-v5.md).
260
+ - User-facing behavior: [README.md](../../README.md), [README-zh.md](../../README-zh.md).
261
+ - Earlier split design: [delivery-v3.md](./delivery-v3.md) §3 (12k split, repeated header).
262
+ - pi extension API: `pi/packages/coding-agent/docs/extensions.md` (`message_update`, `message_end`, `agent_end`).
263
+ - QQ SDK: `@tencent-connect/qqbot-nodejs` 1.0.5, `src/protocol/api/messages.ts` (`sendC2CStreamMessage`).
package/doc/todo.md CHANGED
@@ -1,10 +1,13 @@
1
1
  # TODO
2
2
 
3
+ > 2026-11-06 更新:已基于 2026-11-05 / 2026-11-06 的真实使用记录完成首轮分析。TODO 1 的启动帧和参数传递已确认正常;TODO 2 仍未复现,等待真正的多分钟单命令日志。详见各条目的“日志验证结果”。
4
+
3
5
  ## 1. 长运行 bash 工具的参数延迟显示
4
6
 
5
- > 状态:TODO,等待长期使用日志
6
- > 记录日期:2026-11-04
7
- > 相关版本:pi-qq 1.3.6(仅增加 debug 日志)
7
+ > 状态:启动帧已验证正常;待确认 QQ 客户端渲染
8
+ > 记录日期:2026-11-04
9
+ > 分析日期:2026-11-06
10
+ > 相关版本:pi-qq 1.3.6(仅增加 debug 日志);本次日志来自 1.4.0 之后的版本
8
11
 
9
12
  ### 现象
10
13
 
@@ -16,11 +19,7 @@
16
19
  - 500ms 定时器不依赖工具 Promise;长工具的启动帧曾在工具结束前通过 `stream_messages` 发出。
17
20
  - pi 内置 bash 使用异步 `spawn`,正常情况下不会阻塞 Node 事件循环。
18
21
  - 本地异步子进程可持续触发 500ms timer,说明“bash 子进程本身”不是必然的事件循环阻塞源。
19
- - 当前还没有这次 e2e 的长期使用日志,无法判断:
20
- - 启动帧是否真的发出;
21
- - `content_raw` 是否包含命令;
22
- - timer/队列/事件循环是否被延迟;
23
- - QQ 是否把长行内代码折叠成了一个点。
22
+ - 2026-11-05 的真实使用记录已覆盖启动帧、`content_raw`、timer/队列和事件循环;但最长单条 bash 只有 94 秒的 docker build,仍没有“数分钟 e2e”样本。分析结果见下文。
24
23
 
25
24
  ### 已经添加的诊断日志
26
25
 
@@ -51,37 +50,43 @@
51
50
  <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
52
51
  ```
53
52
 
54
- ### 下次日志分析步骤
53
+ ### 日志验证结果(2026-11-06)
55
54
 
56
- 1. 找到 e2e 的 `toolStart`:
57
- - `scope: "tool"`
58
- - `toolName: "bash"`
59
- - `args` 是否包含完整 `command`。
60
- 2. 找到随后 `scope: "stream"` 的时序日志:
61
- - `tool queued` 时间;
62
- - `append start` 的 `waitedMs`;
63
- - `append done` 的 `totalMs`;
64
- - `append: buffered` / `timer: fired` / `flush: start` 时间。
65
- 3. 找到对应的 `POST .../stream_messages`:
66
- - 请求时间;
67
- - `content_raw` 是否包含命令参数。
68
- 4. 对照 `scope: "event-loop"` 的 `maxMs` / `p99Ms`:
69
- - 如果事件循环延迟达到数秒/数分钟,说明 Node 主线程被饿死;
70
- - 如果 event-loop 正常,但 `append start` 的 `waitedMs` 很大,说明前面的流/队列阻塞;
71
- - 如果 POST 很快且 `content_raw` 有命令,但 QQ 只显示一个点,说明是 QQ 渲染/截断。
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。
72
77
 
73
78
  ### 下一步
74
79
 
75
- - 收集长期使用日志后,确定是事件循环、队列、网络还是 QQ 渲染问题。
76
- - 如果是队列/缓冲问题,考虑给工具启动行增加 `flushAfter`。
77
- - 长命令参数已改为 bash fenced code block;如果仍显示异常,检查 QQ 对代码块的渲染并考虑缩短命令摘要。
78
- - 如果是 e2e CPU 导致的事件循环饥饿,需要评估 TUI/tool output 的同步开销,或把 relay 移出主进程。
79
- - 修复后补测试,更新 `doc/todo.md` / `CHANGELOG.md`,再发布版本。
80
+ - 不需要给工具启动行增加 `flushAfter`;当前无队列/节流延迟证据。
81
+ - 做一次 QQ 渲染 A/B:同一命令分别用带 `bash` 语言标记的 fenced block、无语言标记的 fenced block、行内代码发送,确认是否只在某种格式下显示异常。
82
+ - 如果确认是 QQ 渲染问题,再考虑缩短命令摘要或改用普通文本/行内代码;如果确认正常,可直接关闭 TODO 1。
83
+ - 若最终需要改格式,补测试并更新 `CHANGELOG.md`,再发布版本。
80
84
 
81
85
  ## 2. 长耗时命令导致 QQ 侧无输出/失去响应
82
86
 
83
- > 状态:TODO,等待长期使用日志
87
+ > 状态:仍未复现;等待多分钟单命令日志
84
88
  > 记录日期:2026-11-04
89
+ > 分析日期:2026-11-06
85
90
  > 相关版本:pi-qq 1.4.0
86
91
  > 详细调研:`doc/archive/delivery-v4.md`
87
92
 
@@ -116,6 +121,7 @@ QQ 侧的 `/last` 已可用于手动恢复:
116
121
 
117
122
  - 暂不实施 v4 归档中的错误分类、预算、心跳、自动重绑等行为修改。
118
123
  - 只追加可验证的 debug 日志,等待长期使用日志后再决定修复范围。
124
+ - 2026-11-06 首轮日志未复现失败路径,继续维持“只加日志、不改行为”的决定;详见“日志验证结果”。
119
125
  - 新增诊断日志在 `logLevel: "debug"` 时写入;`stream error` / `stream unavailable` 原本就是 `warn`,保留为错误记录,不改变行为。
120
126
 
121
127
  ### 已追加的诊断日志
@@ -141,7 +147,27 @@ QQ 侧的 `/last` 已可用于手动恢复:
141
147
  - `scope: "inbound"`:`/stop` 记录 `wait start` / `wait done` 及 `waitedMs`。
142
148
  - `scope: "event-loop"`:增加 `driftMs`,用于发现 timer 被事件循环延迟。
143
149
 
144
- ### 下次日志分析步骤
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
+ 本次日志没有出现这些错误,以下步骤保留给下次复现时使用。
145
171
 
146
172
  1. 找到长命令的 `scope: "tool"` `start` / `end`:
147
173
  - `durationMs` 是否与用户感知一致;
@@ -166,7 +192,7 @@ QQ 侧的 `/last` 已可用于手动恢复:
166
192
 
167
193
  ### 需要提供的信息
168
194
 
169
- 复现后请提供:
195
+ 本次日志没有覆盖多分钟单命令、运行中收到的普通消息、`/stop` 和 `/qq-test-budget` 输出;复现时请按以下清单提供:
170
196
 
171
197
  - `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`;
172
198
  - 长命令内容、开始时间和结束时间;
@@ -177,8 +203,10 @@ QQ 侧的 `/last` 已可用于手动恢复:
177
203
 
178
204
  ### 下一步
179
205
 
180
- - 如果日志确认 `msg_id` 过期/被动次数超限:按 `doc/archive/delivery-v4.md` 的“Long-running tools”建议实现错误分类和预算修复。
181
- - 如果日志显示流一直存活但没有新帧:优先实现长工具心跳和 `tool_execution_update` 转发。
182
- - 如果事件循环 `driftMs` / `p99Ms` 很高:排查 e2e CPU、TUI 渲染和同步工具代码。
206
+ - 本次日志未复现失败;不要据此实施错误分类、预算或自动重绑修复。
207
+ - 继续等待一次真正的多分钟单命令日志(最好 >5 分钟,并覆盖 >1 小时的 `msg_id` 生命周期);复现时按上面的“复现时仍需采集/分析”执行。
208
+ - 如果目标只是改善长工具期间的体感:优先实现长工具心跳和 `tool_execution_update` 转发,这不依赖失败复现。
209
+ - 如果后续日志确认 `msg_id` 过期/被动次数超限:再按 `doc/archive/delivery-v4.md` 的“Long-running tools”建议实现错误分类和预算修复。
183
210
  - 如果 `/stop` 的 `wait done` 缺失或 `waitedMs` 很大:实现非阻塞 `/stop`。
184
- - 如果 `/last` 已能稳定恢复,保持为手动兜底,不急于自动重绑。
211
+ - `/last` 目前作为手动兜底可用,保持现状,不急于自动重绑。
212
+ - 修复后补测试,更新 `doc/todo.md` / `CHANGELOG.md`,再发布版本。
package/index.ts CHANGED
@@ -45,7 +45,22 @@ const runFeedback = new RunFeedback({
45
45
  bot: () => running?.bot,
46
46
  budget,
47
47
  getThinkingRelay: () => activeSettings.thinkingRelay,
48
+ getReplyType: () => activeSettings.replyType,
48
49
  onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
50
+ onFallbackReply: (text) => {
51
+ const bot = running?.bot;
52
+ const bound = getLoginState()?.allowedOpenid;
53
+ if (!bot || !bound) {
54
+ log.warn("pi", "fallback reply skipped: no bot or bound user");
55
+ return;
56
+ }
57
+ log.info("pi", "sending fallback reply", { textLength: text.length });
58
+ void sendReply(bot, markdownToPlain(text), {
59
+ budget,
60
+ boundOpenid: bound,
61
+ onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
62
+ });
63
+ },
49
64
  });
50
65
 
51
66
  const eventLoopDelay = monitorEventLoopDelay({ resolution: 100 });
@@ -111,6 +126,7 @@ export default function (pi: ExtensionAPI) {
111
126
 
112
127
  const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
113
128
  const getDeliverAs = () => activeSettings.deliverAs;
129
+ const getReplyType = () => activeSettings.replyType;
114
130
 
115
131
  const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
116
132
 
@@ -141,6 +157,7 @@ export default function (pi: ExtensionAPI) {
141
157
  }
142
158
  : undefined,
143
159
  power: getPowerStatus(),
160
+ replyType: activeSettings.replyType,
144
161
  });
145
162
  };
146
163
 
@@ -171,6 +188,7 @@ export default function (pi: ExtensionAPI) {
171
188
  cwd: ctx.cwd,
172
189
  model: ctx.model?.name ?? null,
173
190
  logLevel: settings.logLevel,
191
+ replyType: settings.replyType,
174
192
  uploadDir,
175
193
  indexedFiles: Object.keys(uploadIndex).length,
176
194
  });
@@ -183,6 +201,7 @@ export default function (pi: ExtensionAPI) {
183
201
  budget,
184
202
  getAllowedOpenid,
185
203
  getDeliverAs,
204
+ getReplyType,
186
205
  getFileMaxSize: () => activeSettings.fileMaxSize,
187
206
  getStatusLines,
188
207
  getLastMessage: () => runFeedback.getLastMessage(),
@@ -213,6 +232,7 @@ export default function (pi: ExtensionAPI) {
213
232
  hasUI: ctx.hasUI,
214
233
  model: ctx.model?.name ?? null,
215
234
  logLevel: settings.logLevel,
235
+ replyType: settings.replyType,
216
236
  login: login ? { appId: login.credentials.appId, allowedOpenid: login.allowedOpenid } : null,
217
237
  configError: error ?? null,
218
238
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
package/src/infra/i18n.ts CHANGED
@@ -36,6 +36,7 @@ const enUS = {
36
36
  "status.batteryChargingNoPercent": "charging",
37
37
  "status.batteryDischargingNoPercent": "discharging",
38
38
  "status.settings": "Settings",
39
+ "status.replyType": "Reply type",
39
40
  "status.none": "none",
40
41
 
41
42
  "commands.descQqLogin": "pi-qq: log in with a QR code and bind the scanning QQ user",
@@ -55,6 +56,7 @@ const enUS = {
55
56
  "commands.compact.done": "Context compaction triggered.",
56
57
  "commands.compact.busy": "Task is running; use /stop before /compact.",
57
58
  "commands.last.none": "No completed message yet.",
59
+ "commands.last.running": "The task is still running; the final reply will be sent when it finishes.",
58
60
  "commands.new.busy": "Task is running; use /stop before resetting.",
59
61
  "commands.new.resetting": "Resetting the session…",
60
62
  "commands.unknown": "Unknown command {cmd}; use /help.",
@@ -166,6 +168,7 @@ const enUS = {
166
168
  "settings.parseFailed": "Failed to parse config file ({path}): {message}",
167
169
  "settings.thinkingRelay": "thinkingRelay must be a boolean",
168
170
  "settings.deliverAs": 'deliverAs must be "steer" or "followUp"',
171
+ "settings.replyType": 'replyType must be "full", "simple", or "last"',
169
172
  "settings.fileMaxSize": "fileMaxSize must be a positive finite number",
170
173
  "settings.logLevel": 'logLevel must be "silent", "error", "warn", "info", or "debug"',
171
174
  "settings.language": 'language must be "zh-cn" or "en-us"',
@@ -266,6 +269,7 @@ const zhCN: Record<TranslationKey, string> = {
266
269
  "status.batteryChargingNoPercent": "充电中",
267
270
  "status.batteryDischargingNoPercent": "放电中",
268
271
  "status.settings": "设置",
272
+ "status.replyType": "回复模式",
269
273
  "status.none": "无",
270
274
 
271
275
  "commands.descQqLogin": "pi-qq:扫码登录并绑定扫码的 QQ 用户",
@@ -285,6 +289,7 @@ const zhCN: Record<TranslationKey, string> = {
285
289
  "commands.compact.done": "已触发上下文压缩。",
286
290
  "commands.compact.busy": "任务正在运行;请先使用 /stop 再执行 /compact。",
287
291
  "commands.last.none": "还没有已完成的消息。",
292
+ "commands.last.running": "任务仍在进行中,完成后会自动推送最终回复。",
288
293
  "commands.new.busy": "任务正在运行;请先使用 /stop 再重置会话。",
289
294
  "commands.new.resetting": "正在重置会话…",
290
295
  "commands.unknown": "未知命令 {cmd};请使用 /help。",
@@ -396,6 +401,7 @@ const zhCN: Record<TranslationKey, string> = {
396
401
  "settings.parseFailed": "解析配置文件失败({path}):{message}",
397
402
  "settings.thinkingRelay": "thinkingRelay 必须是布尔值",
398
403
  "settings.deliverAs": 'deliverAs 必须是 "steer" 或 "followUp"',
404
+ "settings.replyType": 'replyType 必须是 "full"、"simple" 或 "last"',
399
405
  "settings.fileMaxSize": "fileMaxSize 必须是正有限数",
400
406
  "settings.logLevel": 'logLevel 必须是 "silent"、"error"、"warn"、"info" 或 "debug"',
401
407
  "settings.language": 'language 必须是 "zh-cn" 或 "en-us"',
@@ -0,0 +1,9 @@
1
+ export const REPLY_TYPES = ["full", "simple", "last"] as const;
2
+
3
+ export type ReplyType = (typeof REPLY_TYPES)[number];
4
+
5
+ export const DEFAULT_REPLY_TYPE: ReplyType = "full";
6
+
7
+ export function isReplyType(value: unknown): value is ReplyType {
8
+ return typeof value === "string" && (REPLY_TYPES as readonly string[]).includes(value);
9
+ }
@@ -3,10 +3,12 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { normalizeLogLevel, type LogLevel } from "./file-logger";
5
5
  import { DEFAULT_LANGUAGE, getLanguage, isLanguage, translate, type Language } from "./i18n";
6
+ import { DEFAULT_REPLY_TYPE, isReplyType, type ReplyType } from "./reply-type";
6
7
 
7
8
  export interface PiQQSettings {
8
9
  thinkingRelay?: boolean;
9
10
  deliverAs?: "steer" | "followUp";
11
+ replyType?: ReplyType;
10
12
  fileMaxSize?: number;
11
13
  logLevel?: LogLevel;
12
14
  language?: Language;
@@ -61,6 +63,10 @@ export function parseConfig(raw: unknown): ReadConfigResult {
61
63
  if (raw.deliverAs === "steer" || raw.deliverAs === "followUp") config.deliverAs = raw.deliverAs;
62
64
  else errors.push(translate(language, "settings.deliverAs"));
63
65
  }
66
+ if (raw.replyType !== undefined) {
67
+ if (isReplyType(raw.replyType)) config.replyType = raw.replyType;
68
+ else errors.push(translate(language, "settings.replyType"));
69
+ }
64
70
  if (raw.fileMaxSize !== undefined) {
65
71
  if (isPositiveSize(raw.fileMaxSize)) config.fileMaxSize = raw.fileMaxSize;
66
72
  else errors.push(translate(language, "settings.fileMaxSize"));
@@ -112,6 +118,7 @@ export function getSettings(config: PiQQSettings): ResolvedSettings {
112
118
  return {
113
119
  thinkingRelay: config.thinkingRelay ?? true,
114
120
  deliverAs: config.deliverAs ?? "steer",
121
+ replyType: config.replyType ?? DEFAULT_REPLY_TYPE,
115
122
  fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
116
123
  logLevel,
117
124
  language: config.language ?? DEFAULT_LANGUAGE,
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { ReplyType } from "../infra/reply-type";
2
3
  import { log } from "../infra/file-logger";
3
4
  import { t } from "../infra/i18n";
4
5
 
@@ -17,6 +18,7 @@ export interface InboundCommandDeps {
17
18
  ctx: InboundContext;
18
19
  getStatusLines: () => string[];
19
20
  getLastMessage?: () => string | undefined;
21
+ getReplyType?: () => ReplyType;
20
22
  onStop?: () => void;
21
23
  waitForEnd?: () => Promise<void>;
22
24
  }
@@ -77,6 +79,10 @@ export async function handleInboundCommand(
77
79
  break;
78
80
  case "/last": {
79
81
  if (!deps.ctx.isIdle()) {
82
+ if (deps.getReplyType?.() === "last") {
83
+ await reply(t("commands.last.running"));
84
+ break;
85
+ }
80
86
  extras.restartPush?.();
81
87
  } else {
82
88
  const text = deps.getLastMessage?.();
@@ -9,6 +9,7 @@ import {
9
9
  type SavedFile,
10
10
  } from "../attachments/file-attachments";
11
11
  import { log } from "../infra/file-logger";
12
+ import type { ReplyType } from "../infra/reply-type";
12
13
  import { t } from "../infra/i18n";
13
14
  import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
14
15
  import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
@@ -17,6 +18,7 @@ export interface InboundDeps extends InboundCommandDeps {
17
18
  budget: ReplyBudget;
18
19
  getAllowedOpenid: () => string | undefined;
19
20
  getDeliverAs: () => "steer" | "followUp";
21
+ getReplyType: () => ReplyType;
20
22
  getFileMaxSize: () => number;
21
23
  saveFiles?: typeof saveInboundFiles;
22
24
  streamReply?: typeof sendStreamReply;
@@ -1,5 +1,6 @@
1
1
  import type { PowerStatus } from "../infra/power-status";
2
2
  import { formatTokenCount } from "../infra/display-format";
3
+ import type { ReplyType } from "../infra/reply-type";
3
4
  import { t, type TranslationKey } from "../infra/i18n";
4
5
  import type { BotState } from "./qq-bot";
5
6
 
@@ -10,6 +11,7 @@ export interface StatusReportInput {
10
11
  model?: { name: string };
11
12
  usage?: { tokens: number | null; contextWindow: number | null; percent?: number | null };
12
13
  power?: PowerStatus;
14
+ replyType?: ReplyType;
13
15
  }
14
16
 
15
17
  const STATE_ICONS: Record<BotState, string> = {
@@ -45,6 +47,7 @@ function label(
45
47
  | "status.connection"
46
48
  | "status.qqUser"
47
49
  | "status.battery"
50
+ | "status.replyType"
48
51
  | "status.settings",
49
52
  value: string,
50
53
  ): string {
@@ -107,6 +110,7 @@ export function formatStatusReport(input: StatusReportInput): string[] {
107
110
 
108
111
  const battery = batteryLine(input.power);
109
112
  if (battery) lines.push(battery);
113
+ if (input.replyType) lines.push(`💬 ${label("status.replyType", input.replyType)}`);
110
114
  lines.push(`⚙️ ${label("status.settings", "~/.pi/agent/pi-qq.json")}`);
111
115
  return lines;
112
116
  }
@@ -288,44 +288,59 @@ export class BubbleWriter {
288
288
  await this.rotateStream();
289
289
  if (this.streamDead || this.disposed) return;
290
290
  }
291
- if (
292
- !newBubble &&
293
- this.bubbleChars >= MAX_BUBBLE_CHARS &&
294
- this.cur &&
295
- !this.pendingResume &&
296
- !this.fenceOpen &&
297
- !this.toolOpen &&
298
- (blockBoundary || this.lastChar === "\n")
299
- ) {
291
+ const cut = this.splitPoint(text, newBubble);
292
+ if (cut >= 0) {
293
+ await this.appendChunk(text.slice(0, cut + 1), { thinking, endTool, trace, queuedAt });
294
+ if (this.streamDead || this.disposed) return;
300
295
  await this.rotateStream();
301
296
  if (this.streamDead || this.disposed) return;
297
+ await this.appendChunk(text.slice(cut + 1), { thinking, endTool, trace, queuedAt });
298
+ return;
302
299
  }
303
- const stream = this.ensureStream();
304
- if (!stream) return;
305
- this.pushedAny = true;
306
- const outgoing = thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
307
- try {
308
- await stream.append(outgoing);
309
- this.bubbleChars += outgoing.length;
310
- this.lastFrameAt = Date.now();
311
- this.trackFences(outgoing);
312
- this.lastChar = outgoing.slice(-1);
313
- if (endTool) this.toolOpen = false;
314
- if (trace && isLogEnabled("debug")) {
315
- log.debug("stream", "stream timing", {
316
- phase: "append done",
317
- trace,
318
- msgId: this.logMsgId(),
319
- totalMs: Date.now() - queuedAt,
320
- stats: this.stats(),
321
- });
322
- }
323
- } catch (err) {
324
- if (this.cur === stream) this.handleStreamError(err as Error);
325
- }
300
+ await this.appendChunk(text, { thinking, endTool, trace, queuedAt });
326
301
  });
327
302
  }
328
303
 
304
+ private splitPoint(text: string, newBubble: boolean): number {
305
+ if (newBubble) return -1;
306
+ if (!this.cur) return -1;
307
+ if (this.pendingResume) return -1;
308
+ if (this.fenceOpen) return -1;
309
+ if (this.toolOpen) return -1;
310
+ if (this.bubbleChars < MAX_BUBBLE_CHARS) return -1;
311
+ return text.indexOf("\n");
312
+ }
313
+
314
+ private async appendChunk(
315
+ text: string,
316
+ opts: { thinking?: boolean; endTool?: boolean; trace?: string; queuedAt?: number },
317
+ ): Promise<void> {
318
+ if (!text || this.streamDead || this.disposed) return;
319
+ const stream = this.ensureStream();
320
+ if (!stream) return;
321
+ this.pushedAny = true;
322
+ const outgoing = opts.thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
323
+ try {
324
+ await stream.append(outgoing);
325
+ this.bubbleChars += outgoing.length;
326
+ this.lastFrameAt = Date.now();
327
+ this.trackFences(outgoing);
328
+ this.lastChar = outgoing.slice(-1);
329
+ if (opts.endTool) this.toolOpen = false;
330
+ if (opts.trace && isLogEnabled("debug")) {
331
+ log.debug("stream", "stream timing", {
332
+ phase: "append done",
333
+ trace: opts.trace,
334
+ msgId: this.logMsgId(),
335
+ totalMs: Date.now() - (opts.queuedAt ?? 0),
336
+ stats: this.stats(),
337
+ });
338
+ }
339
+ } catch (err) {
340
+ if (this.cur === stream) this.handleStreamError(err as Error);
341
+ }
342
+ }
343
+
329
344
  private trackFences(text: string): void {
330
345
  const previousChar = this.lastChar;
331
346
  for (const match of text.matchAll(/(?:^|\n)[ \t>]*(`{3,})/g)) {
@@ -0,0 +1,37 @@
1
+ import type { ReplyType } from "../infra/reply-type";
2
+
3
+ export interface ReplyPolicy {
4
+ relayThinking: boolean;
5
+ relayTools: boolean;
6
+ relayTextLive: boolean;
7
+ deferTextWhileToolsPending: boolean;
8
+ deliverLastAtEnd: boolean;
9
+ }
10
+
11
+ const POLICIES: Record<ReplyType, ReplyPolicy> = {
12
+ full: {
13
+ relayThinking: true,
14
+ relayTools: true,
15
+ relayTextLive: true,
16
+ deferTextWhileToolsPending: true,
17
+ deliverLastAtEnd: false,
18
+ },
19
+ simple: {
20
+ relayThinking: false,
21
+ relayTools: false,
22
+ relayTextLive: true,
23
+ deferTextWhileToolsPending: false,
24
+ deliverLastAtEnd: false,
25
+ },
26
+ last: {
27
+ relayThinking: false,
28
+ relayTools: false,
29
+ relayTextLive: false,
30
+ deferTextWhileToolsPending: false,
31
+ deliverLastAtEnd: true,
32
+ },
33
+ };
34
+
35
+ export function policyFor(type: ReplyType): ReplyPolicy {
36
+ return POLICIES[type];
37
+ }
@@ -1,6 +1,8 @@
1
1
  import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { BubbleWriter } from "./bubble-writer";
3
+ import { policyFor, type ReplyPolicy } from "./reply-policy";
3
4
  import type { ReplyBudget } from "../quota/reply-quota";
5
+ import type { ReplyType } from "../infra/reply-type";
4
6
  import { isLogEnabled, log } from "../infra/file-logger";
5
7
  import { detectSkillRead } from "./stream-block-format";
6
8
 
@@ -8,7 +10,9 @@ export interface RunFeedbackDeps {
8
10
  bot: () => QQBot | undefined;
9
11
  budget: ReplyBudget;
10
12
  getThinkingRelay: () => boolean;
13
+ getReplyType: () => ReplyType;
11
14
  onWarn: (msg: string) => void;
15
+ onFallbackReply?: (text: string) => void;
12
16
  }
13
17
 
14
18
  interface ToolCall {
@@ -34,10 +38,16 @@ interface RunState {
34
38
  deferredThinking: string;
35
39
  deferredText: string;
36
40
  hadError: boolean;
41
+ lastText: string;
37
42
  writer: BubbleWriter;
38
43
  typingTimer?: ReturnType<typeof setInterval>;
39
44
  }
40
45
 
46
+ interface LastDelivery {
47
+ text: string;
48
+ streamed: boolean;
49
+ }
50
+
41
51
  const TYPING_INTERVAL_MS = 50_000;
42
52
  const PENDING_TTL_MS = 15_000;
43
53
  const RECOVERY_TTL_MS = 60_000;
@@ -150,6 +160,7 @@ export class RunFeedback {
150
160
  deferredThinking: "",
151
161
  deferredText: "",
152
162
  hadError: false,
163
+ lastText: "",
153
164
  writer,
154
165
  };
155
166
  this.run = run;
@@ -158,6 +169,7 @@ export class RunFeedback {
158
169
  msgId: run.msgId?.slice(0, 8) ?? "?",
159
170
  source: target === pending ? "pending" : "recovery",
160
171
  targetAgeMs: now - target.at,
172
+ replyType: this.deps.getReplyType(),
161
173
  budget: this.deps.budget.snapshot(),
162
174
  });
163
175
  }
@@ -242,6 +254,16 @@ export class RunFeedback {
242
254
  const run = this.run;
243
255
  if (!run) return;
244
256
 
257
+ const policy = this.policy();
258
+
259
+ if (!policy.relayTextLive) {
260
+ if (snapshotText.trim()) {
261
+ run.currentText = snapshotText;
262
+ run.lastText = snapshotText;
263
+ }
264
+ return;
265
+ }
266
+
245
267
  const full = [run.finalizedText, snapshotText].filter((part) => part.trim()).join("\n\n");
246
268
  if (full.trim()) run.currentText = full;
247
269
 
@@ -250,7 +272,7 @@ export class RunFeedback {
250
272
  if (snapshotThinking.length > run.thinkingSentLen) {
251
273
  const thinkingDelta = snapshotThinking.slice(run.thinkingSentLen);
252
274
  run.thinkingSentLen = snapshotThinking.length;
253
- if (this.deps.getThinkingRelay()) {
275
+ if (policy.relayThinking && this.deps.getThinkingRelay()) {
254
276
  if (this.hasPendingTools(run)) {
255
277
  run.deferredThinking += thinkingDelta;
256
278
  } else {
@@ -262,7 +284,7 @@ export class RunFeedback {
262
284
  const delta = full.slice(run.resultSentLen);
263
285
  if (!delta) return;
264
286
  run.resultSentLen = full.length;
265
- if (this.hasPendingTools(run)) {
287
+ if (policy.deferTextWhileToolsPending && this.hasPendingTools(run)) {
266
288
  run.deferredText += delta;
267
289
  return;
268
290
  }
@@ -280,12 +302,32 @@ export class RunFeedback {
280
302
  return false;
281
303
  }
282
304
 
305
+ const policy = this.policy();
306
+
307
+ if (!policy.relayTextLive) {
308
+ run.finalizedText = "";
309
+ run.resultSentLen = 0;
310
+ run.thinkingSentLen = 0;
311
+ if (isError) {
312
+ run.hadError = true;
313
+ this.recovery = { openid: run.openid, msgId: run.msgId ?? "", at: Date.now() };
314
+ log.debug("run", "last buffered", { textLength: 0, isError: true });
315
+ return false;
316
+ }
317
+ if (text.trim()) {
318
+ run.lastText = text;
319
+ run.currentText = text;
320
+ }
321
+ log.debug("run", "last buffered", { textLength: run.lastText.length, isError: false });
322
+ return true;
323
+ }
324
+
283
325
  run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
284
326
  if (text.trim()) run.currentText = text;
285
327
  const delta = run.finalizedText.slice(run.resultSentLen);
286
328
  run.resultSentLen = run.finalizedText.length;
287
329
  if (!isError && text && delta) {
288
- if (this.hasPendingTools(run)) {
330
+ if (policy.deferTextWhileToolsPending && this.hasPendingTools(run)) {
289
331
  run.deferredText += delta;
290
332
  } else {
291
333
  run.writer.pushText(delta);
@@ -327,6 +369,7 @@ export class RunFeedback {
327
369
  this.finishEnd();
328
370
  return;
329
371
  }
372
+ const lastDelivery = this.planLastDelivery(run);
330
373
  await run.writer.whenIdle();
331
374
  const hasPendingTools = this.hasPendingTools(run);
332
375
  if (!hasPendingTools) this.flushDeferred(run);
@@ -348,15 +391,17 @@ export class RunFeedback {
348
391
  msgId: run.msgId?.slice(0, 8) ?? "?",
349
392
  elapsedMs: Date.now() - run.startedAt,
350
393
  });
351
- this.run = null;
352
- if (!run.writer.hasPushed) {
353
- run.writer.dispose();
354
- this.finishEnd();
355
- return;
394
+ let delivered = false;
395
+ if (run.writer.hasPushed) {
396
+ const ok = await run.writer.flush();
397
+ if (ok) {
398
+ await run.writer.done();
399
+ delivered = true;
400
+ }
356
401
  }
357
- const ok = await run.writer.flush();
358
- if (ok) await run.writer.done();
359
402
  run.writer.dispose();
403
+ this.settleLastDelivery(lastDelivery, delivered);
404
+ if (this.run === run) this.run = null;
360
405
  this.finishEnd();
361
406
  }
362
407
 
@@ -379,6 +424,33 @@ export class RunFeedback {
379
424
  this.endResolve = undefined;
380
425
  }
381
426
 
427
+ private policy(): ReplyPolicy {
428
+ return policyFor(this.deps.getReplyType());
429
+ }
430
+
431
+ private planLastDelivery(run: RunState): LastDelivery | undefined {
432
+ if (!this.policy().deliverLastAtEnd) return undefined;
433
+ const text = run.lastText.trim() ? run.lastText : "";
434
+ if (!text) return undefined;
435
+ const fresh = this.deps.budget.snapshot().fresh;
436
+ if (fresh) {
437
+ run.writer.closeBlock();
438
+ run.writer.pushText(text);
439
+ }
440
+ return { text, streamed: fresh };
441
+ }
442
+
443
+ private settleLastDelivery(delivery: LastDelivery | undefined, delivered: boolean): void {
444
+ if (!delivery) return;
445
+ const ok = delivered && delivery.streamed;
446
+ log.debug("run", "last delivered", {
447
+ delivered: ok,
448
+ fallback: !ok,
449
+ textLength: delivery.text.length,
450
+ });
451
+ if (!ok) this.deps.onFallbackReply?.(delivery.text);
452
+ }
453
+
382
454
  private hasPendingTools(run: RunState): boolean {
383
455
  return Boolean(run.activeTool) || run.tools.some((tool) => !tool.finished);
384
456
  }
@@ -410,10 +482,12 @@ export class RunFeedback {
410
482
  skillName: tool.skillName ?? null,
411
483
  ...this.diagnostics(run),
412
484
  });
413
- if (tool.skillName) {
414
- run.writer.pushSkill(tool.skillName);
415
- } else {
416
- run.writer.pushTool(tool.name, tool.args);
485
+ if (this.policy().relayTools) {
486
+ if (tool.skillName) {
487
+ run.writer.pushSkill(tool.skillName);
488
+ } else {
489
+ run.writer.pushTool(tool.name, tool.args);
490
+ }
417
491
  }
418
492
  if (tool.result) this.finishTool(run, tool);
419
493
  }
@@ -428,7 +502,7 @@ export class RunFeedback {
428
502
  isError: tool.result.isError,
429
503
  ...this.diagnostics(run),
430
504
  });
431
- if (!tool.skillName) {
505
+ if (this.policy().relayTools && !tool.skillName) {
432
506
  run.writer.pushToolResult(tool.result.result, tool.result.isError, tool.name, tool.args);
433
507
  }
434
508
  run.writer.schedule(() => {