@chen_hu_hu/pi-qq 1.4.2 → 1.5.1

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,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.5.1] - 2026-11-05
11
+
12
+ ### Changed
13
+
14
+ - Logs are now written only during QQ-triggered runs after login. Local runs, login/QR flows, bot lifecycle events, and idle periods no longer create log files.
15
+
16
+ ## [1.5.0] - 2026-11-05
17
+
18
+ ### Added
19
+
20
+ - Added the `qq_send_media` tool for sending local images, videos, and files back to the bound QQ private chat. The tool is registered inactive and activates after QQ login.
21
+ - Added `scope: "media"` debug logs for registration, activation, validation, upload, budget selection, send, and result.
22
+
23
+ ### Changed
24
+
25
+ - Consolidated the v5 research, feature, and implementation plan into `doc/archive/delivery-v5.md`; removed the three working documents.
26
+
27
+ ### Fixed
28
+
29
+ - Debug logs for local and logged-out sessions: assistant message and agent lifecycle events are now logged even when no QQ run is active. QQ relay logs remain specific to QQ-triggered runs.
30
+ - Avoided action-method calls during extension loading when registering the media tool.
31
+ - Localized media result labels and removed the long message id from the user-facing tool result.
32
+
10
33
  ## [1.4.2] - 2026-11-05
11
34
 
12
35
  ### Changed
@@ -111,7 +134,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
111
134
  - Added thinking labels, per-tool icons, model-error recovery, and idle-safe session handling.
112
135
  - Reorganized modules by bounded context and updated settings and delivery documentation.
113
136
 
114
- [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.2...HEAD
137
+ [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.5.0...HEAD
138
+ [1.5.0]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.2...v1.5.0
115
139
  [1.4.2]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.1...v1.4.2
116
140
  [1.4.1]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.0...v1.4.1
117
141
  [1.4.0]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.6...v1.4.0
package/README-zh.md CHANGED
@@ -61,6 +61,19 @@ pi 看到的提示词示例:
61
61
  Summarize this file.
62
62
  ```
63
63
 
64
+ ### 回传媒体到 QQ
65
+
66
+ `qq_send_media` 在启动时注册但未激活;QQ 登录成功后激活,`/qq-logout` 后停用。断线重连不会停用。
67
+
68
+ 明确告诉 pi,例如“把截图发给我”“回传刚才的图片”。模型根据工具描述判断是否调用;请求模糊时应先追问。没有关键词匹配,也没有额外确认步骤。
69
+
70
+ - 图片:`.jpg`、`.jpeg`、`.png`、`.gif`、`.webp`、`.bmp`,最大 30 MB。
71
+ - 视频:`.mp4`、`.mov`、`.avi`、`.mkv`、`.webm`、`.flv`、`.wmv`,最大 100 MB。
72
+ - 其他文件:最大 100 MB;音频按普通文件发送。
73
+ - 允许任意可读的普通文件;符号链接、目录、设备会被拒绝。
74
+ - 每条媒体消息消耗一次被动回复;超过限制后自动降级为主动消息。
75
+ - 工具气泡与其它工具一致:`## 📤 qq_send_media`。
76
+
64
77
  ### 语音消息
65
78
 
66
79
  语音消息使用 QQ 内置 ASR(`asr_refer_text`)。转写文本会作为普通用户文本交给 pi;pi 不会收到音频文件。
@@ -113,6 +126,8 @@ QQ 侧命令:
113
126
  | `/qq-test-md [text]` | 发送 Markdown 测试消息 |
114
127
  | `/qq-test-stream` | 运行流式时间线诊断(`resume` 验证续写) |
115
128
 
129
+ 将 `logLevel` 设为 `debug` 时,只有在登录后由 QQ 消息触发的 run 期间才会写入 agent/message/tool 日志;本地 run、登录流程和空闲时段不写日志。`scope: "media"` 记录媒体工具在这些 run 中的关键步骤,QQ relay 日志也只在 QQ 触发的 run 中出现。
130
+
116
131
  ## 设置
117
132
 
118
133
  创建 `~/.pi/agent/pi-qq.json` 覆盖默认值。该文件只保存设置;凭据不会写入其中。
@@ -135,7 +150,7 @@ QQ 侧命令:
135
150
 
136
151
  配置在 pi 会话启动时读取;修改文件后请重启 pi。未知配置项会被忽略,无效值会回退到默认值并给出提示。
137
152
 
138
- 启用日志后,日志写入 `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`。可用 `PI_QQ_LOG_DIR` 覆盖目录。`info` 只记录元数据;`debug` 记录完整事件、附件、提示词和工具参数/结果。
153
+ 启用日志后,只有 QQ 触发的 run 处于活动状态时才会写入记录,路径为 `<cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log`;可用 `PI_QQ_LOG_DIR` 覆盖目录。`info` 只记录元数据;`debug` 记录完整事件、附件、提示词和工具参数/结果。
139
154
 
140
155
  ## 开发
141
156
 
package/README.md CHANGED
@@ -61,6 +61,19 @@ Example prompt seen by pi:
61
61
  Summarize this file.
62
62
  ```
63
63
 
64
+ ### Sending media back to QQ
65
+
66
+ After QQ login, pi-qq activates the `qq_send_media` tool. It is registered inactive at startup and after `/qq-logout`; a reconnect does not disable it.
67
+
68
+ Ask pi explicitly, for example `send me the screenshot` or `把截图发给我`. The model decides from the tool description; ambiguous requests should be clarified first. There is no keyword matching or extra confirmation step.
69
+
70
+ - Images: `.jpg`, `.jpeg`, `.png`, `.gif`, `.webp`, `.bmp`; up to 30 MB.
71
+ - Videos: `.mp4`, `.mov`, `.avi`, `.mkv`, `.webm`, `.flv`, `.wmv`; up to 100 MB.
72
+ - Other files: up to 100 MB; audio is sent as a file.
73
+ - Any readable regular file is allowed. Symlinks, directories, and devices are rejected.
74
+ - Each media message consumes one passive reply; after the limit, pi-qq falls back to a proactive message.
75
+ - The tool bubble is the same as any other tool: `## 📤 qq_send_media`.
76
+
64
77
  ### Voice messages
65
78
 
66
79
  Voice messages use QQ's built-in ASR (`asr_refer_text`). The transcript is sent to pi as normal user text; pi never receives the audio file.
@@ -113,6 +126,8 @@ These terminal commands are intended for troubleshooting:
113
126
  | `/qq-test-md [text]` | Send a Markdown test message |
114
127
  | `/qq-test-stream` | Run a streamed timeline diagnostic (`resume` for probe) |
115
128
 
129
+ With `logLevel: "debug"`, logs are written only while a QQ-triggered run is active after login; local runs, login, and idle periods are not logged. `scope: "media"` covers media-tool steps during those runs, and QQ relay logs only appear for QQ-triggered runs.
130
+
116
131
  ## Settings
117
132
 
118
133
  Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; credentials are never written to it.
@@ -135,7 +150,7 @@ Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; c
135
150
 
136
151
  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.
137
152
 
138
- When logging is enabled, logs are written 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.
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.
139
154
 
140
155
  ## Development
141
156
 
@@ -0,0 +1,224 @@
1
+ # pi-qq delivery-v5
2
+
3
+ > **Delivery record.** v5 adds outbound media delivery and fixes debug log coverage for non-QQ runs. See [README](../../README.md) for current user-facing behavior.
4
+ > Version: 1.5.0
5
+ > Date: 2026-11-05
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).
7
+ > Supersedes: `doc/research.md`, `doc/feature.md`, and `doc/plan.md`; those working documents were consolidated into this record and removed.
8
+ > Open work: [doc/todo.md](../todo.md).
9
+
10
+ ## 1. Scope
11
+
12
+ v5 closes the gap where a remote QQ user could not see generated images, videos, or files. It adds one LLM-facing tool, `qq_send_media`, and tightens debug logging so local runs are diagnosable too.
13
+
14
+ In scope:
15
+
16
+ - send local images, videos, and files to the bound QQ private chat;
17
+ - activate the tool after QQ login and deactivate it on logout;
18
+ - passive-first delivery with proactive fallback;
19
+ - size/type validation before upload;
20
+ - normal tool bubble for calls and results;
21
+ - debug logs for the media lifecycle and for local/logged-out runs.
22
+
23
+ Out of scope:
24
+
25
+ - inbound intent parsing or keyword matching;
26
+ - a second confirmation step before sending;
27
+ - voice messages;
28
+ - URL-based media sources;
29
+ - multiple files per tool call;
30
+ - path-root restrictions.
31
+
32
+ ## 2. Final decisions
33
+
34
+ | Topic | Decision |
35
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
36
+ | Call timing | The model decides from the tool `description` and `promptGuidelines`. No inbound parser, no keyword list, no confirmation step. |
37
+ | Activation | Registered inactive at startup (`defaultActive: false`). Activated by `startWithCredentials()` after QQ login. Deactivated by `stopIfRunning()` on logout/stop/shutdown. |
38
+ | Reconnect | Login state is the switch, not connection state. Reconnecting does not deactivate the tool; `execute()` errors if the bot is not ready. |
39
+ | Paths | Any readable regular file is allowed. Symlinks, directories, devices, and empty files are rejected. |
40
+ | Media kind | `auto` by default: images/videos by extension, everything else as `FILE`. Explicit `kind` can override; audio is sent as a file. |
41
+ | Tool bubble | Same as any other tool: `## 📤 qq_send_media`; no suppression, no custom renderer. |
42
+ | Configuration | No new settings. |
43
+ | Runtime dependencies | None added. `typebox` is supplied by pi. |
44
+
45
+ The trade-off is explicit: “only call when the user asks” is a model-level instruction, not a hard gate. The tool being inactive before login is a real gate; the per-call decision is not.
46
+
47
+ ## 3. Tool surface
48
+
49
+ ```ts
50
+ const mediaParams = Type.Object({
51
+ path: Type.String({ description: "Local image/video/file path, absolute or relative to cwd." }),
52
+ kind: Type.Optional(StringEnum(["auto", "image", "video", "file"] as const)),
53
+ caption: Type.Optional(Type.String({ description: "Optional caption shown with the media." })),
54
+ name: Type.Optional(Type.String({ description: "Display filename for kind=file." })),
55
+ });
56
+ ```
57
+
58
+ - `path`: local source; leading `@` is stripped; relative paths resolve from `ctx.cwd`.
59
+ - `kind`: `auto` by default; `image`/`video` require a matching extension; `file` always uses `MediaFileType.FILE`.
60
+ - `caption`: optional QQ media-message `content`, displayed with the image/video/file in one bubble. Truncated to 4500 characters.
61
+ - `name`: optional display filename for `FILE` only; passed as `fileName` to the SDK. Images/videos do not use it.
62
+
63
+ Tool metadata:
64
+
65
+ - `defaultActive: false`
66
+ - `executionMode: "sequential"`
67
+ - `promptSnippet`: one-line tool entry in the system prompt.
68
+ - `promptGuidelines`: call only on an explicit user request, never proactively after generating a file, ask when unsure.
69
+
70
+ ## 4. Lifecycle
71
+
72
+ ```text
73
+ [*] --> Inactive: startup / defaultActive=false
74
+ Inactive --> Active: QQ login / startWithCredentials()
75
+ Active --> Inactive: logout / stopIfRunning()
76
+ Active --> Active: reconnect (state unchanged)
77
+ ```
78
+
79
+ - `registerMediaTool()` registers the tool once at extension load.
80
+ - `startWithCredentials()` calls `activate()` after the bot starts.
81
+ - `stopIfRunning()` calls `deactivate()`; covers `/qq-logout`, `/qq-login` restart, and `session_shutdown`.
82
+ - `activate()`/`deactivate()` preserve all other active tools and are idempotent.
83
+ - No `onStateChange` wiring: login, not transient connection state, controls availability.
84
+
85
+ ## 5. Send flow
86
+
87
+ 1. Validate the path with `lstat`.
88
+ 2. Resolve `MediaFileType` and check `getMaxUploadSize()`.
89
+ 3. Upload with `bot.uploadMedia({ localPath, fileType, fileName, srvSendMsg: false })`.
90
+ 4. Pick a reply target with `ReplyBudget.acquire()`.
91
+ 5. Send with `bot.mediaApi.sendMediaMessage()`, passing `msgId` for passive replies.
92
+ 6. Commit the passive reply after success.
93
+ 7. On passive failure, reuse the existing `file_info` for one proactive retry; never re-upload.
94
+
95
+ Type limits:
96
+
97
+ | Type | Max |
98
+ | ----- | -----: |
99
+ | Image | 30 MB |
100
+ | Video | 100 MB |
101
+ | File | 100 MB |
102
+
103
+ - Files ≥5 MB use the SDK chunked-upload path automatically.
104
+ - Only passive sends call `commitPassive()`.
105
+ - The tool is `executionMode: "sequential"` to avoid parallel passive-quota races.
106
+ - `signal.aborted` is checked at entry and after upload.
107
+
108
+ ## 6. Debug logging
109
+
110
+ All new logs use `scope: "media"`; they are written only when `logLevel: "debug"`.
111
+
112
+ Key points:
113
+
114
+ | Point | Fields |
115
+ | ----------------------- | ----------------------------------------------------------------------------------------------- |
116
+ | Tool registration | `defaultActive` |
117
+ | Activation/deactivation | `active`, `removed`, `activeCount` |
118
+ | Call entry | `toolCallId`, `path`, `kind`, `captionLength` |
119
+ | Validation | `fileType`, `sizeBytes`, `displayName`; failure includes `reason` |
120
+ | Upload | start: `fileType`, `sizeBytes`, `path`; done: `fileUuid`, `ttlSec`, `elapsedMs` |
121
+ | Budget | `mode`, `msgId`, `remaining`, `fresh` |
122
+ | Send | start: `mode`, `targetId`, `msgId`, `fileType`, `captionLength`; done: `messageId`, `elapsedMs` |
123
+ | Failure | raw `err` for upload, passive send, and proactive retry |
124
+
125
+ Logs never include file contents, base64, raw `file_info`, or caption text.
126
+
127
+ ### 6.1 Debug log bugfix
128
+
129
+ Before v5, `message_end` returned early when `running` was unset, before writing its debug log. As a result, assistant-message debug logs only appeared after QQ login. v5:
130
+
131
+ - moves the `message_end` debug log before the `!running` / `!fromQQ` guard;
132
+ - adds `fromQQ`, `hasBot`, `hasLogin` to assistant and agent run markers;
133
+ - keeps `src/relay/` stream logs QQ-specific; local runs do not fabricate relay logs;
134
+ - keeps `silent` as the default.
135
+
136
+ ## 7. Tool bubble
137
+
138
+ No special handling:
139
+
140
+ - `RunFeedback` forwards `tool_execution_start` / `tool_execution_end` as usual.
141
+ - `TOOL_ICONS` adds `qq_send_media: "📤"`.
142
+ - The result text is concise and localized; the full message id stays in `details` and logs.
143
+ - The media message is separate from the tool bubble; both appear in QQ.
144
+
145
+ ## 8. Code map
146
+
147
+ | File | Change |
148
+ | ---------------------------------- | ----------------------------------------------------------------------- |
149
+ | `src/qq/media-tool.ts` | Tool schema, validation, upload/send, activation controller, debug logs |
150
+ | `index.ts` | Register tool, activate on login, deactivate on stop, debug log fix |
151
+ | `src/infra/i18n.ts` | Media messages and localized media kinds |
152
+ | `src/relay/stream-block-format.ts` | `📤` tool icon |
153
+ | `test/qq/media-tool.test.ts` | Tool behavior and error mapping |
154
+ | `test/index.test.ts` | Lifecycle, debug logs, activation |
155
+ | `test/infra/i18n.test.ts` | Media message localization |
156
+ | `README.md` / `README-zh.md` | User-facing usage |
157
+ | `CHANGELOG.md` | v5 release notes |
158
+
159
+ ## 9. Verification
160
+
161
+ Real QQ test log: `/home/chen/project/pi-qq-test/.pi/pi-qq/logs/pi-qq-2026-11-05.log`.
162
+
163
+ | Case | Result |
164
+ | ---------------------------- | --------------------------------------------------------------------- |
165
+ | 6 MB image, `kind:image` | `fileType:1`, chunked upload 3.3s, passive send 1.5s |
166
+ | 25 MB image, `kind:image` | `fileType:1`, chunked upload 6.9s, passive send 0.88s |
167
+ | 31 MB image, `kind:image` | Local reject: 31.2 MB > 30 MB |
168
+ | H.264 MP4, `kind:video` | `fileType:2`, upload 1.3s, passive send 0.98s |
169
+ | 1 MB ZIP, `kind:file` | `fileType:4`, passive send success |
170
+ | 101 MB file, `kind:file` | Local reject: 101 MB > 100 MB |
171
+ | 4 passive sends + final text | Budget exhausted; later sends fell back to proactive and succeeded |
172
+ | Tool bubble | `## 📤 qq_send_media` with args/result; media message separate |
173
+ | Debug logs | call/validate/upload/budget/send/result present; no unexpected errors |
174
+
175
+ Automated checks:
176
+
177
+ - **194 tests passed** across 19 files.
178
+ - `npm run typecheck` passed.
179
+ - `npm run lint` passed.
180
+ - `npm run format:check` passed.
181
+ - `npm pack --dry-run` passed.
182
+
183
+ Not covered by the acceptance run:
184
+
185
+ - HEVC/H.265 video as a native video message (H.264 was used);
186
+ - upload daily quota;
187
+ - a bot without file-message permission;
188
+ - upload cancellation;
189
+ - retry duplicate-send behavior;
190
+ - proactive-message quota boundary.
191
+
192
+ ## 10. Risks and limitations
193
+
194
+ - The “call only when asked” rule is a soft model constraint. The model can still call the tool without an explicit request; this is accepted.
195
+ - The tool is available in local sessions after login. This follows the login-level activation decision.
196
+ - Any readable file can be sent; the model already has local read access, so path restriction is not a security boundary.
197
+ - Media and final text share the passive-reply budget. Heavy media use can push the final text to proactive delivery.
198
+ - `caption` and `name` are model-decided; pi-qq does not validate their intent.
199
+ - Reconnect does not deactivate the tool; calls can fail while the bot is not ready.
200
+ - Large uploads block the tool until finished; the SDK has no upload abort signal.
201
+
202
+ ## 11. Open items
203
+
204
+ - `doc/todo.md` item 1: long-running bash argument/tool-start visibility.
205
+ - `doc/todo.md` item 2: long-running tools leading to missing QQ output.
206
+ - Verify HEVC video as `VIDEO` if that format matters.
207
+ - Verify no-file-permission behavior and the large-file upload daily quota.
208
+ - Decide whether the tool description should explicitly prefer `kind=auto` unless the user asks for a file.
209
+
210
+ The v5 acceptance log does not cover the two long-running bash scenarios; they remain separate TODO items.
211
+
212
+ ## 12. References
213
+
214
+ - Design history: [delivery-v4.md](./delivery-v4.md).
215
+ - User-facing behavior: [README.md](../../README.md), [README-zh.md](../../README-zh.md).
216
+ - QQ SDK: `@tencent-connect/qqbot-nodejs` 1.0.5, `src/QQBot.ts`, `src/protocol/api/media.ts`.
217
+ - pi extension API: `pi/packages/coding-agent/docs/extensions.md`.
218
+ - Release commits:
219
+ - `c360c70` — research/design docs;
220
+ - `a0e4d93` — implementation plan;
221
+ - `8528d4f` — `qq_send_media` and debug logging;
222
+ - `62f82db` — avoid action calls during extension loading;
223
+ - `39cd540` — polish media result text;
224
+ - `v1.5.0` — release tag.
package/index.ts CHANGED
@@ -9,11 +9,12 @@ import { registerQQDiagnostics } from "./src/qq/qq-diagnostics";
9
9
  import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
10
10
  import { ReplyBudget } from "./src/quota/reply-quota";
11
11
  import { RunFeedback } from "./src/relay/run-stream-relay";
12
- import { configureLogger, flushLogs, isLogEnabled, log, previewForLog } from "./src/infra/file-logger";
12
+ import { configureLogger, flushLogs, isLogEnabled, log, previewForLog, setLogGate } from "./src/infra/file-logger";
13
13
  import { configureI18n, t } from "./src/infra/i18n";
14
14
  import { getPowerStatus } from "./src/infra/power-status";
15
15
  import { formatStatusReport } from "./src/qq/status-report";
16
16
  import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
17
+ import { registerMediaTool, type MediaToolController } from "./src/qq/media-tool";
17
18
 
18
19
  interface LoginState {
19
20
  credentials: Credentials;
@@ -37,6 +38,7 @@ let running: RunningBot | undefined;
37
38
  let lastState: BotState = "stopped";
38
39
  let stateDetail: string | undefined;
39
40
  let sessionCtx: ExtensionContext | undefined;
41
+ let mediaTool: MediaToolController | undefined;
40
42
  let activeSettings: ResolvedSettings = getSettings({});
41
43
  const budget = new ReplyBudget();
42
44
  const runFeedback = new RunFeedback({
@@ -95,6 +97,15 @@ function stopEventLoopMonitor(): void {
95
97
  }
96
98
 
97
99
  export default function (pi: ExtensionAPI) {
100
+ setLogGate(() => Boolean(getLoginState()) && runFeedback.isQQRunActive());
101
+
102
+ mediaTool = registerMediaTool(pi, {
103
+ getBot: () => running?.bot,
104
+ getLogin: () => getLoginState(),
105
+ budget,
106
+ onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
107
+ });
108
+
98
109
  activeSettings = getSettings(readConfig().config);
99
110
  configureI18n(activeSettings.language);
100
111
 
@@ -134,6 +145,7 @@ export default function (pi: ExtensionAPI) {
134
145
  };
135
146
 
136
147
  const stopIfRunning = () => {
148
+ mediaTool?.deactivate();
137
149
  running?.stop();
138
150
  running = undefined;
139
151
  lastState = "stopped";
@@ -188,12 +200,12 @@ export default function (pi: ExtensionAPI) {
188
200
  else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
189
201
  },
190
202
  });
203
+ mediaTool?.activate();
191
204
  };
192
205
 
193
206
  pi.on("session_start", async (_event, ctx) => {
194
207
  const { settings, error } = applyConfig(ctx);
195
208
  configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
196
- startEventLoopMonitor();
197
209
 
198
210
  const login = getLoginState();
199
211
  log.info("session", "started", {
@@ -218,12 +230,28 @@ export default function (pi: ExtensionAPI) {
218
230
  });
219
231
 
220
232
  pi.on("agent_start", () => {
221
- log.info("agent", "run started");
222
233
  runFeedback.onAgentStart();
234
+ log.info("agent", "run started");
235
+ if (isLogEnabled("debug")) {
236
+ log.debug("agent", "run state", {
237
+ phase: "start",
238
+ fromQQ: runFeedback.isQQRunActive(),
239
+ hasBot: Boolean(running),
240
+ hasLogin: Boolean(getLoginState()),
241
+ });
242
+ }
223
243
  });
224
244
 
225
245
  pi.on("agent_end", () => {
226
246
  log.info("agent", "run ended");
247
+ if (isLogEnabled("debug")) {
248
+ log.debug("agent", "run state", {
249
+ phase: "end",
250
+ fromQQ: runFeedback.isQQRunActive(),
251
+ hasBot: Boolean(running),
252
+ hasLogin: Boolean(getLoginState()),
253
+ });
254
+ }
227
255
  void runFeedback.onAgentEnd();
228
256
  });
229
257
 
@@ -310,12 +338,14 @@ export default function (pi: ExtensionAPI) {
310
338
 
311
339
  pi.on("message_end", async (event, ctx) => {
312
340
  const msg = event.message;
313
- if (msg.role !== "assistant" || !running) return;
341
+ if (msg.role !== "assistant") return;
314
342
 
315
343
  const fromQQ = runFeedback.isQQRunActive();
316
344
  if (isLogEnabled("debug")) {
317
345
  log.debug("pi", "assistant message ended", {
318
346
  fromQQ,
347
+ hasBot: Boolean(running),
348
+ hasLogin: Boolean(getLoginState()),
319
349
  stopReason: msg.stopReason,
320
350
  contentTypes: msg.content.map((block) => block.type),
321
351
  textPreview: previewForLog(
@@ -326,7 +356,7 @@ export default function (pi: ExtensionAPI) {
326
356
  ),
327
357
  });
328
358
  }
329
- if (!fromQQ) return;
359
+ if (!running || !fromQQ) return;
330
360
 
331
361
  const isError = msg.stopReason === "error";
332
362
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.4.2",
3
+ "version": "1.5.1",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
@@ -18,6 +18,7 @@ const DEFAULT_LOG_LEVEL: LogLevel = "silent";
18
18
  let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
19
19
  let activeDir: string | undefined;
20
20
  let writeQueue: Promise<void> = Promise.resolve();
21
+ let logGate: (() => boolean) | undefined;
21
22
 
22
23
  function isLogLevel(value: unknown): value is LogLevel {
23
24
  return typeof value === "string" && Object.hasOwn(LEVEL_WEIGHT, value);
@@ -44,6 +45,19 @@ export function configureLogger(level: LogLevel, dir?: string): void {
44
45
  activeDir = dir;
45
46
  }
46
47
 
48
+ export function setLogGate(gate: (() => boolean) | undefined): void {
49
+ logGate = gate;
50
+ }
51
+
52
+ function isLogAllowed(): boolean {
53
+ if (!logGate) return true;
54
+ try {
55
+ return logGate();
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
47
61
  function resolveLogDir(): string {
48
62
  return process.env.PI_QQ_LOG_DIR ?? activeDir ?? join(process.cwd(), ".pi", "pi-qq", "logs");
49
63
  }
@@ -77,6 +91,7 @@ function stringifyError(err: unknown): string {
77
91
 
78
92
  function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message: string, data?: unknown): void {
79
93
  if (!isLevelEnabled(activeLevel, level)) return;
94
+ if (!isLogAllowed()) return;
80
95
 
81
96
  const localized = localizeLogMessage(message);
82
97
  const record: LogFields = {
package/src/infra/i18n.ts CHANGED
@@ -145,6 +145,21 @@ const enUS = {
145
145
  "outbound.passiveFailed": "Passive reply failed; falling back to proactive.",
146
146
  "outbound.proactiveFailed": "Proactive send failed: {message}",
147
147
  "outbound.sendFailed": "Send failed: {message}",
148
+ "mediaTool.notConnected": "QQ is not connected. Run /qq-login first.",
149
+ "mediaTool.cancelled": "Cancelled.",
150
+ "mediaTool.notFound": "File not found: {path}",
151
+ "mediaTool.notRegularFile": "Not a regular file: {path}",
152
+ "mediaTool.emptyFile": "File is empty: {path}",
153
+ "mediaTool.tooLarge": "File is {size}; QQ limit for this type is {limit}.",
154
+ "mediaTool.unsupportedKind": "Unsupported {kind} extension: {path}",
155
+ "mediaTool.uploadDailyLimit": "QQ daily large-file upload limit reached: {message}",
156
+ "mediaTool.apiFailed": "QQ API error ({code}): {message}",
157
+ "mediaTool.modePassive": "passive",
158
+ "mediaTool.modeProactive": "proactive",
159
+ "mediaTool.kindImage": "image",
160
+ "mediaTool.kindVideo": "video",
161
+ "mediaTool.kindFile": "file",
162
+ "mediaTool.sent": "Sent {kind} {name} to QQ via {mode} reply.",
148
163
 
149
164
  "settings.invalidRoot": "Invalid config file ({path}): expected a JSON object; using defaults.",
150
165
  "settings.invalidFields": "Invalid config file ({path}): {errors}; invalid values were ignored.",
@@ -360,6 +375,21 @@ const zhCN: Record<TranslationKey, string> = {
360
375
  "outbound.passiveFailed": "被动回复失败,改用主动消息。",
361
376
  "outbound.proactiveFailed": "主动消息发送失败:{message}",
362
377
  "outbound.sendFailed": "发送失败:{message}",
378
+ "mediaTool.notConnected": "QQ 未连接,请先执行 /qq-login。",
379
+ "mediaTool.cancelled": "已取消。",
380
+ "mediaTool.notFound": "文件不存在:{path}",
381
+ "mediaTool.notRegularFile": "不是普通文件:{path}",
382
+ "mediaTool.emptyFile": "文件为空:{path}",
383
+ "mediaTool.tooLarge": "文件大小 {size},该类型 QQ 上限为 {limit}。",
384
+ "mediaTool.unsupportedKind": "{kind} 类型不支持该扩展名:{path}",
385
+ "mediaTool.uploadDailyLimit": "QQ 今日大文件上传额度已用完:{message}",
386
+ "mediaTool.apiFailed": "QQ API 错误({code}):{message}",
387
+ "mediaTool.modePassive": "被动",
388
+ "mediaTool.modeProactive": "主动",
389
+ "mediaTool.kindImage": "图片",
390
+ "mediaTool.kindVideo": "视频",
391
+ "mediaTool.kindFile": "文件",
392
+ "mediaTool.sent": "已通过{mode}回复将{kind} {name} 发送到 QQ。",
363
393
 
364
394
  "settings.invalidRoot": "配置文件无效({path}):应为 JSON 对象;使用默认值。",
365
395
  "settings.invalidFields": "配置文件无效({path}):{errors};无效值已忽略。",
@@ -0,0 +1,458 @@
1
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ ApiError,
4
+ MediaFileType,
5
+ UploadDailyLimitExceededError,
6
+ getMaxUploadSize,
7
+ sanitizeFileName,
8
+ type QQBot,
9
+ type UploadMediaResponse,
10
+ } from "@tencent-connect/qqbot-nodejs";
11
+ import { lstat } from "node:fs/promises";
12
+ import type { Stats } from "node:fs";
13
+ import { basename, extname, resolve } from "node:path";
14
+ import { StringEnum } from "@earendil-works/pi-ai";
15
+ import { type Static, Type } from "typebox";
16
+ import { formatBytes } from "../infra/display-format";
17
+ import { log } from "../infra/file-logger";
18
+ import { t } from "../infra/i18n";
19
+ import type { ReplyBudget } from "../quota/reply-quota";
20
+ import { TEXT_CHUNK_LIMIT } from "./reply-sender";
21
+
22
+ export const MEDIA_TOOL_NAME = "qq_send_media";
23
+
24
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
25
+ const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv", ".wmv"]);
26
+
27
+ export const mediaParams = Type.Object({
28
+ path: Type.String({ description: "Local image/video/file path, absolute or relative to cwd." }),
29
+ kind: Type.Optional(StringEnum(["auto", "image", "video", "file"] as const)),
30
+ caption: Type.Optional(Type.String({ description: "Optional caption shown with the media." })),
31
+ name: Type.Optional(Type.String({ description: "Display filename for kind=file." })),
32
+ });
33
+
34
+ export type MediaParams = Static<typeof mediaParams>;
35
+
36
+ export interface MediaToolDetails {
37
+ phase: string;
38
+ path?: string;
39
+ fileType?: MediaFileType;
40
+ sizeBytes?: number;
41
+ displayName?: string;
42
+ mode?: "passive" | "proactive";
43
+ messageId?: string;
44
+ fileUuid?: string;
45
+ ttlSec?: number;
46
+ elapsedMs?: number;
47
+ uploaded?: number;
48
+ total?: number;
49
+ }
50
+
51
+ export interface PreparedMedia {
52
+ path: string;
53
+ fileType: MediaFileType;
54
+ size: number;
55
+ displayName: string;
56
+ details: MediaToolDetails;
57
+ }
58
+
59
+ export interface MediaToolLogin {
60
+ allowedOpenid: string;
61
+ }
62
+
63
+ export interface MediaToolDeps {
64
+ getBot: () => QQBot | undefined;
65
+ getLogin: () => MediaToolLogin | undefined;
66
+ budget: ReplyBudget;
67
+ onWarn: (message: string) => void;
68
+ }
69
+
70
+ export interface MediaToolController {
71
+ activate(): void;
72
+ deactivate(): void;
73
+ isActive(): boolean;
74
+ }
75
+
76
+ function mediaErrorMessage(err: unknown): Error {
77
+ if (err instanceof UploadDailyLimitExceededError) {
78
+ return new Error(t("mediaTool.uploadDailyLimit", { message: err.message }));
79
+ }
80
+ if (err instanceof ApiError) {
81
+ return new Error(
82
+ t("mediaTool.apiFailed", {
83
+ code: err.bizCode ?? "unknown",
84
+ message: err.bizMessage ?? err.message,
85
+ }),
86
+ );
87
+ }
88
+ return err instanceof Error ? err : new Error(String(err));
89
+ }
90
+
91
+ function mediaKindLabel(fileType: MediaFileType): string {
92
+ if (fileType === MediaFileType.IMAGE) return t("mediaTool.kindImage");
93
+ if (fileType === MediaFileType.VIDEO) return t("mediaTool.kindVideo");
94
+ return t("mediaTool.kindFile");
95
+ }
96
+
97
+ export function normalizeMediaPath(cwd: string, rawPath: string): string {
98
+ const trimmed = rawPath.trim();
99
+ const withoutAt = trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
100
+ return resolve(cwd, withoutAt);
101
+ }
102
+
103
+ export function resolveMediaFileType(filePath: string, kind: MediaParams["kind"] = "auto"): MediaFileType {
104
+ const extension = extname(filePath).toLowerCase();
105
+ if (kind === "image") {
106
+ if (!IMAGE_EXTENSIONS.has(extension)) {
107
+ throw new Error(t("mediaTool.unsupportedKind", { kind: "image", path: filePath }));
108
+ }
109
+ return MediaFileType.IMAGE;
110
+ }
111
+ if (kind === "video") {
112
+ if (!VIDEO_EXTENSIONS.has(extension)) {
113
+ throw new Error(t("mediaTool.unsupportedKind", { kind: "video", path: filePath }));
114
+ }
115
+ return MediaFileType.VIDEO;
116
+ }
117
+ if (kind === "file") return MediaFileType.FILE;
118
+ if (IMAGE_EXTENSIONS.has(extension)) return MediaFileType.IMAGE;
119
+ if (VIDEO_EXTENSIONS.has(extension)) return MediaFileType.VIDEO;
120
+ return MediaFileType.FILE;
121
+ }
122
+
123
+ export async function prepareMedia(params: MediaParams, cwd: string): Promise<PreparedMedia> {
124
+ const filePath = normalizeMediaPath(cwd, params.path);
125
+ let info: Stats;
126
+ try {
127
+ info = await lstat(filePath);
128
+ } catch (err) {
129
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
130
+ throw new Error(t("mediaTool.notFound", { path: filePath }), { cause: err });
131
+ }
132
+ throw err;
133
+ }
134
+
135
+ if (info.isSymbolicLink() || !info.isFile()) {
136
+ throw new Error(t("mediaTool.notRegularFile", { path: filePath }));
137
+ }
138
+ if (info.size === 0) {
139
+ throw new Error(t("mediaTool.emptyFile", { path: filePath }));
140
+ }
141
+
142
+ const fileType = resolveMediaFileType(filePath, params.kind ?? "auto");
143
+ const maxSize = getMaxUploadSize(fileType);
144
+ if (info.size > maxSize) {
145
+ throw new Error(
146
+ t("mediaTool.tooLarge", {
147
+ size: formatBytes(info.size),
148
+ limit: formatBytes(maxSize),
149
+ }),
150
+ );
151
+ }
152
+
153
+ const rawName = params.name?.trim() ? basename(params.name) : basename(filePath);
154
+ const displayName = sanitizeFileName(rawName);
155
+ return {
156
+ path: filePath,
157
+ fileType,
158
+ size: info.size,
159
+ displayName,
160
+ details: {
161
+ phase: "prepared",
162
+ path: filePath,
163
+ fileType,
164
+ sizeBytes: info.size,
165
+ displayName,
166
+ },
167
+ };
168
+ }
169
+
170
+ function createTool(deps: MediaToolDeps): ToolDefinition<typeof mediaParams, MediaToolDetails> {
171
+ return {
172
+ name: MEDIA_TOOL_NAME,
173
+ label: "Send to QQ",
174
+ description:
175
+ "Send a local image, video, or file to the bound QQ private chat. " +
176
+ "Call only when the user explicitly asks to send media back to QQ. " +
177
+ "If the request is ambiguous, ask the user before calling.",
178
+ promptSnippet: "Send a local image, video, or file back to the user's QQ chat",
179
+ promptGuidelines: [
180
+ "Use qq_send_media only when the user explicitly asks to send an image, video, or file back to QQ.",
181
+ "Never call qq_send_media proactively after generating, editing, or reading a file; report the local path instead.",
182
+ "If you are unsure whether the user wants the file sent to QQ, ask them first; do not call the tool.",
183
+ ],
184
+ parameters: mediaParams,
185
+ defaultActive: false,
186
+ executionMode: "sequential",
187
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
188
+ const startedAt = Date.now();
189
+ log.debug("media", "media tool", {
190
+ phase: "call.start",
191
+ toolCallId,
192
+ path: params.path,
193
+ kind: params.kind ?? "auto",
194
+ captionLength: params.caption?.length ?? 0,
195
+ });
196
+
197
+ const bot = deps.getBot();
198
+ const login = deps.getLogin();
199
+ if (!bot || !login) {
200
+ log.debug("media", "media tool", {
201
+ phase: "not.connected",
202
+ toolCallId,
203
+ hasBot: Boolean(bot),
204
+ hasLogin: Boolean(login),
205
+ });
206
+ throw new Error(t("mediaTool.notConnected"));
207
+ }
208
+ if (signal?.aborted) {
209
+ log.debug("media", "media tool", { phase: "aborted", toolCallId });
210
+ throw new Error(t("mediaTool.cancelled"));
211
+ }
212
+
213
+ let prepared: PreparedMedia;
214
+ try {
215
+ prepared = await prepareMedia(params, ctx.cwd);
216
+ } catch (err) {
217
+ log.debug("media", "media tool", {
218
+ phase: "validate.fail",
219
+ toolCallId,
220
+ path: params.path,
221
+ reason: err instanceof Error ? err.message : String(err),
222
+ });
223
+ throw err;
224
+ }
225
+
226
+ log.debug("media", "media tool", {
227
+ phase: "validate.ok",
228
+ toolCallId,
229
+ fileType: prepared.fileType,
230
+ sizeBytes: prepared.size,
231
+ displayName: prepared.displayName,
232
+ });
233
+
234
+ let upload: UploadMediaResponse;
235
+ const uploadStartedAt = Date.now();
236
+ try {
237
+ log.debug("media", "media tool", {
238
+ phase: "upload.start",
239
+ toolCallId,
240
+ fileType: prepared.fileType,
241
+ sizeBytes: prepared.size,
242
+ path: prepared.path,
243
+ });
244
+ upload = await bot.uploadMedia({
245
+ target: { scope: "c2c", targetId: login.allowedOpenid },
246
+ fileType: prepared.fileType,
247
+ localPath: prepared.path,
248
+ fileName: prepared.fileType === MediaFileType.FILE ? prepared.displayName : undefined,
249
+ srvSendMsg: false,
250
+ onProgress: (uploaded, total) => {
251
+ onUpdate?.({
252
+ content: [{ type: "text", text: `Uploading ${Math.round((uploaded / total) * 100)}%` }],
253
+ details: { ...prepared.details, phase: "upload", uploaded, total },
254
+ });
255
+ },
256
+ });
257
+ log.debug("media", "media tool", {
258
+ phase: "upload.done",
259
+ toolCallId,
260
+ fileUuid: upload.file_uuid,
261
+ ttlSec: upload.ttl,
262
+ elapsedMs: Date.now() - uploadStartedAt,
263
+ });
264
+ } catch (err) {
265
+ const mapped = mediaErrorMessage(err);
266
+ log.warn("media", "media tool", { phase: "call.error", toolCallId, stage: "upload", err });
267
+ throw mapped;
268
+ }
269
+
270
+ if (signal?.aborted) {
271
+ log.debug("media", "media tool", { phase: "aborted", toolCallId, stage: "upload" });
272
+ throw new Error(t("mediaTool.cancelled"));
273
+ }
274
+
275
+ const reply = deps.budget.acquire();
276
+ const snapshot = deps.budget.snapshot();
277
+ const msgId = reply.mode === "passive" ? reply.msgId : undefined;
278
+ const targetId = reply.openid ?? login.allowedOpenid;
279
+ const caption = params.caption?.slice(0, TEXT_CHUNK_LIMIT);
280
+
281
+ log.debug("media", "media tool", {
282
+ phase: "budget",
283
+ toolCallId,
284
+ mode: reply.mode,
285
+ msgId: msgId ?? null,
286
+ remaining: snapshot.remaining,
287
+ fresh: snapshot.fresh,
288
+ });
289
+
290
+ const sendStartedAt = Date.now();
291
+ log.debug("media", "media tool", {
292
+ phase: "send.start",
293
+ toolCallId,
294
+ mode: reply.mode,
295
+ targetId,
296
+ msgId: msgId ?? null,
297
+ fileType: prepared.fileType,
298
+ captionLength: caption?.length ?? 0,
299
+ });
300
+
301
+ try {
302
+ const message = await bot.mediaApi.sendMediaMessage("c2c", targetId, upload.file_info, bot.getCredentials(), {
303
+ msgId,
304
+ content: caption,
305
+ });
306
+ if (msgId) deps.budget.commitPassive(msgId);
307
+ const elapsedMs = Date.now() - sendStartedAt;
308
+ const mode = reply.mode === "passive" ? t("mediaTool.modePassive") : t("mediaTool.modeProactive");
309
+ log.debug("media", "media tool", {
310
+ phase: "send.done",
311
+ toolCallId,
312
+ mode: reply.mode,
313
+ messageId: message.id,
314
+ elapsedMs,
315
+ });
316
+ log.debug("media", "media tool", {
317
+ phase: "call.result",
318
+ toolCallId,
319
+ ok: true,
320
+ mode: reply.mode,
321
+ messageId: message.id,
322
+ });
323
+ return {
324
+ content: [
325
+ {
326
+ type: "text",
327
+ text: t("mediaTool.sent", {
328
+ kind: mediaKindLabel(prepared.fileType),
329
+ name: prepared.displayName,
330
+ mode,
331
+ }),
332
+ },
333
+ ],
334
+ details: {
335
+ ...prepared.details,
336
+ phase: "sent",
337
+ mode: reply.mode,
338
+ messageId: message.id,
339
+ fileUuid: upload.file_uuid,
340
+ ttlSec: upload.ttl,
341
+ elapsedMs: Date.now() - startedAt,
342
+ },
343
+ };
344
+ } catch (err) {
345
+ if (!msgId) {
346
+ log.warn("media", "media tool", { phase: "call.error", toolCallId, stage: "send", err });
347
+ throw mediaErrorMessage(err);
348
+ }
349
+
350
+ log.warn("media", "media tool", {
351
+ phase: "send.passiveFailed",
352
+ toolCallId,
353
+ msgId,
354
+ err,
355
+ });
356
+ log.warn("media", "media tool", {
357
+ phase: "send.proactiveRetry",
358
+ toolCallId,
359
+ targetId: login.allowedOpenid,
360
+ });
361
+
362
+ try {
363
+ const message = await bot.mediaApi.sendMediaMessage(
364
+ "c2c",
365
+ login.allowedOpenid,
366
+ upload.file_info,
367
+ bot.getCredentials(),
368
+ { content: caption },
369
+ );
370
+ deps.onWarn(t("outbound.passiveFailed"));
371
+ const elapsedMs = Date.now() - sendStartedAt;
372
+ const mode = t("mediaTool.modeProactive");
373
+ log.debug("media", "media tool", {
374
+ phase: "send.done",
375
+ toolCallId,
376
+ mode: "proactive",
377
+ messageId: message.id,
378
+ elapsedMs,
379
+ });
380
+ log.debug("media", "media tool", {
381
+ phase: "call.result",
382
+ toolCallId,
383
+ ok: true,
384
+ mode: "proactive",
385
+ messageId: message.id,
386
+ });
387
+ return {
388
+ content: [
389
+ {
390
+ type: "text",
391
+ text: t("mediaTool.sent", {
392
+ kind: mediaKindLabel(prepared.fileType),
393
+ name: prepared.displayName,
394
+ mode,
395
+ }),
396
+ },
397
+ ],
398
+ details: {
399
+ ...prepared.details,
400
+ phase: "sent",
401
+ mode: "proactive",
402
+ messageId: message.id,
403
+ fileUuid: upload.file_uuid,
404
+ ttlSec: upload.ttl,
405
+ elapsedMs: Date.now() - startedAt,
406
+ },
407
+ };
408
+ } catch (retryErr) {
409
+ log.warn("media", "media tool", {
410
+ phase: "call.error",
411
+ toolCallId,
412
+ stage: "proactiveRetry",
413
+ err: retryErr,
414
+ });
415
+ throw mediaErrorMessage(retryErr);
416
+ }
417
+ }
418
+ },
419
+ };
420
+ }
421
+
422
+ export function registerMediaTool(pi: ExtensionAPI, deps: MediaToolDeps): MediaToolController {
423
+ pi.registerTool(createTool(deps));
424
+ log.debug("media", "media tool", {
425
+ phase: "tool.registered",
426
+ defaultActive: false,
427
+ });
428
+
429
+ return {
430
+ activate() {
431
+ const active = pi.getActiveTools();
432
+ if (!active.includes(MEDIA_TOOL_NAME)) {
433
+ pi.setActiveTools([...new Set([...active, MEDIA_TOOL_NAME])]);
434
+ }
435
+ log.debug("media", "media tool", {
436
+ phase: "tool.activate",
437
+ active: true,
438
+ activeCount: pi.getActiveTools().length,
439
+ });
440
+ },
441
+ deactivate() {
442
+ const active = pi.getActiveTools();
443
+ const removed = active.includes(MEDIA_TOOL_NAME);
444
+ if (removed) {
445
+ pi.setActiveTools(active.filter((name) => name !== MEDIA_TOOL_NAME));
446
+ }
447
+ log.debug("media", "media tool", {
448
+ phase: "tool.deactivate",
449
+ active: false,
450
+ removed,
451
+ activeCount: pi.getActiveTools().length,
452
+ });
453
+ },
454
+ isActive() {
455
+ return pi.getActiveTools().includes(MEDIA_TOOL_NAME);
456
+ },
457
+ };
458
+ }
@@ -343,12 +343,12 @@ export class RunFeedback {
343
343
  lastCompletedTextLength: this.lastCompletedText?.length ?? 0,
344
344
  ...this.diagnostics(run),
345
345
  });
346
- this.run = null;
347
346
  log.debug("run", "run ended", {
348
347
  phase: "finished",
349
348
  msgId: run.msgId?.slice(0, 8) ?? "?",
350
349
  elapsedMs: Date.now() - run.startedAt,
351
350
  });
351
+ this.run = null;
352
352
  if (!run.writer.hasPushed) {
353
353
  run.writer.dispose();
354
354
  this.finishEnd();
@@ -23,6 +23,7 @@ const TOOL_ICONS: Record<string, string> = {
23
23
  remove: "❌",
24
24
  todo: "✅",
25
25
  test: "🧪",
26
+ qq_send_media: "📤",
26
27
  };
27
28
 
28
29
  function backtickFence(text: string, minimum: number): string {