@chen_hu_hu/pi-qq 1.4.1 → 1.5.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,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.5.0] - 2026-11-05
11
+
12
+ ### Added
13
+
14
+ - 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.
15
+ - Added `scope: "media"` debug logs for registration, activation, validation, upload, budget selection, send, and result.
16
+
17
+ ### Changed
18
+
19
+ - Consolidated the v5 research, feature, and implementation plan into `doc/archive/delivery-v5.md`; removed the three working documents.
20
+
21
+ ### Fixed
22
+
23
+ - 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.
24
+ - Avoided action-method calls during extension loading when registering the media tool.
25
+ - Localized media result labels and removed the long message id from the user-facing tool result.
26
+
27
+ ## [1.4.2] - 2026-11-05
28
+
29
+ ### Changed
30
+
31
+ - Thinking bubbles now start with the `## 💭 <label>` heading, matching the `##` heading syntax used by tool and skill blocks.
32
+ - The English `en-us` thinking label is now `Thinking` instead of `思考`.
33
+ - Skill blocks are localized: `## 🧩 Skill` in `en-us` and `## 🧩 技能` in `zh-cn`.
34
+
10
35
  ## [1.4.1] - 2026-11-04
11
36
 
12
37
  ### Changed
@@ -103,7 +128,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
103
128
  - Added thinking labels, per-tool icons, model-error recovery, and idle-safe session handling.
104
129
  - Reorganized modules by bounded context and updated settings and delivery documentation.
105
130
 
106
- [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.1...HEAD
131
+ [Unreleased]: https://github.com/CQ-Developer/pi-qq/compare/v1.5.0...HEAD
132
+ [1.5.0]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.2...v1.5.0
133
+ [1.4.2]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.1...v1.4.2
107
134
  [1.4.1]: https://github.com/CQ-Developer/pi-qq/compare/v1.4.0...v1.4.1
108
135
  [1.4.0]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.6...v1.4.0
109
136
  [1.3.6]: https://github.com/CQ-Developer/pi-qq/compare/v1.3.5...v1.3.6
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 不会收到音频文件。
@@ -75,7 +88,7 @@ Summarize this file.
75
88
 
76
89
  ### 回复格式
77
90
 
78
- - **思考**:独立气泡,纯文本,首行 `**💭 思考**`。长思考可能续到新气泡,并重复标题。
91
+ - **思考**:独立气泡,纯文本,首行 `## 💭 思考`。长思考可能续到新气泡,并重复标题。
79
92
  - **工具**:每次调用独立气泡,首行 `## <图标> <工具名>`;`bash` 命令使用 `bash` 代码块,其他参数使用行内代码;结果按工具/文件类型使用 `text`、`markdown`、`python`、`json` 等代码块。
80
93
  - **普通消息**:原文,不加标题。
81
94
  - **工具图标**:💻 bash、📖 read、📝 write、✏️ edit、🔎 grep、🔍 search、🗂️ find、📁 ls、📋 list、🌐 web、📡 fetch、🗑️ delete、❌ remove、✅ todo、🧪 test;未配置工具使用 🔧。
@@ -113,6 +126,8 @@ QQ 侧命令:
113
126
  | `/qq-test-md [text]` | 发送 Markdown 测试消息 |
114
127
  | `/qq-test-stream` | 运行流式时间线诊断(`resume` 验证续写) |
115
128
 
129
+ 将 `logLevel` 设为 `debug` 时,本地 run 和 QQ run 都会写入通用的 agent/message/tool 日志;`scope: "media"` 记录媒体工具的关键步骤。QQ relay 日志只在 QQ 触发的 run 中出现。
130
+
116
131
  ## 设置
117
132
 
118
133
  创建 `~/.pi/agent/pi-qq.json` 覆盖默认值。该文件只保存设置;凭据不会写入其中。
@@ -127,7 +142,7 @@ QQ 侧命令:
127
142
 
128
143
  | 配置项 | 默认值 | 说明 |
129
144
  | --------------- | ---------- | ------------------------------------------------------ |
130
- | `thinkingRelay` | `true` | 以本地化的 `💭` 标题纯文本回传思考;`false` 时隐藏 |
145
+ | `thinkingRelay` | `true` | 以本地化的 `## 💭` 标题纯文本回传思考;`false` 时隐藏 |
131
146
  | `deliverAs` | `"steer"` | 忙碌时新消息的排队方式:`steer` 或 `followUp` |
132
147
  | `fileMaxSize` | `52428800` | QQ 附件下载上限(字节,50MB) |
133
148
  | `language` | `"zh-cn"` | UI 和日志语言:`zh-cn` 或 `en-us` |
@@ -164,7 +179,7 @@ npm run format:check
164
179
  - 图片会保存为文件,并通过 pi 的 `read` 工具查看;当前模型必须支持图片输入才能看到内容。
165
180
  - 保存的附件位于工作区 `.pi/` 下;如有需要,请把 `.pi/` 加入你自己的项目 `.gitignore`。
166
181
  - QQ 对每条入站消息的被动回复次数有限制。可用 `/qq-test-budget` 查看本地额度。
167
- - 读取 `SKILL.md` 时,QQ 显示 `## 🧩 Skill` 和 skill 名称,不转发文件内容。
182
+ - 读取 `SKILL.md` 时,QQ 显示 `## 🧩 技能` 和 skill 名称,不转发文件内容。
168
183
 
169
184
  ## 许可证
170
185
 
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.
@@ -75,7 +88,7 @@ Debug logs include the raw `asr_refer_text` and attachment metadata when `logLev
75
88
 
76
89
  ### Reply format
77
90
 
78
- - **Thinking**: its own bubble, plain text, starting with `**💭 思考**`. Long thinking may continue in a new bubble with the header repeated.
91
+ - **Thinking**: its own bubble, plain text, starting with `## 💭 思考`. Long thinking may continue in a new bubble with the header repeated.
79
92
  - **Tools**: one bubble per call: `## <icon> <name>`; `bash` commands use a `bash` code block, other arguments use inline code, and results use `text`, `markdown`, `python`, `json`, etc. depending on the tool and file type.
80
93
  - **Regular messages**: raw text with no header.
81
94
  - **Tool icons**: 💻 bash, 📖 read, 📝 write, ✏️ edit, 🔎 grep, 🔍 search, 🗂️ find, 📁 ls, 📋 list, 🌐 web, 📡 fetch, 🗑️ delete, ❌ remove, ✅ todo, 🧪 test; unconfigured tools use 🔧.
@@ -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"`, general agent/message/tool logs are written for local and QQ runs, and `scope: "media"` covers media-tool steps. 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.
@@ -127,7 +142,7 @@ Create `~/.pi/agent/pi-qq.json` to override defaults. It stores settings only; c
127
142
 
128
143
  | Key | Default | Description |
129
144
  | --------------- | ---------- | ------------------------------------------------------------ |
130
- | `thinkingRelay` | `true` | Relay thinking as plain text with a localized `💭` header |
145
+ | `thinkingRelay` | `true` | Relay thinking as plain text with a localized `## 💭` header |
131
146
  | `deliverAs` | `"steer"` | Queue new messages while busy: `steer` or `followUp` |
132
147
  | `fileMaxSize` | `52428800` | QQ attachment download limit in bytes (50MB) |
133
148
  | `language` | `"zh-cn"` | UI and log language: `zh-cn` or `en-us` |
@@ -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
@@ -14,6 +14,7 @@ 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,13 @@ function stopEventLoopMonitor(): void {
95
97
  }
96
98
 
97
99
  export default function (pi: ExtensionAPI) {
100
+ mediaTool = registerMediaTool(pi, {
101
+ getBot: () => running?.bot,
102
+ getLogin: () => getLoginState(),
103
+ budget,
104
+ onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
105
+ });
106
+
98
107
  activeSettings = getSettings(readConfig().config);
99
108
  configureI18n(activeSettings.language);
100
109
 
@@ -134,6 +143,7 @@ export default function (pi: ExtensionAPI) {
134
143
  };
135
144
 
136
145
  const stopIfRunning = () => {
146
+ mediaTool?.deactivate();
137
147
  running?.stop();
138
148
  running = undefined;
139
149
  lastState = "stopped";
@@ -188,6 +198,7 @@ export default function (pi: ExtensionAPI) {
188
198
  else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
189
199
  },
190
200
  });
201
+ mediaTool?.activate();
191
202
  };
192
203
 
193
204
  pi.on("session_start", async (_event, ctx) => {
@@ -220,10 +231,26 @@ export default function (pi: ExtensionAPI) {
220
231
  pi.on("agent_start", () => {
221
232
  log.info("agent", "run started");
222
233
  runFeedback.onAgentStart();
234
+ if (isLogEnabled("debug")) {
235
+ log.debug("agent", "run state", {
236
+ phase: "start",
237
+ fromQQ: runFeedback.isQQRunActive(),
238
+ hasBot: Boolean(running),
239
+ hasLogin: Boolean(getLoginState()),
240
+ });
241
+ }
223
242
  });
224
243
 
225
244
  pi.on("agent_end", () => {
226
245
  log.info("agent", "run ended");
246
+ if (isLogEnabled("debug")) {
247
+ log.debug("agent", "run state", {
248
+ phase: "end",
249
+ fromQQ: runFeedback.isQQRunActive(),
250
+ hasBot: Boolean(running),
251
+ hasLogin: Boolean(getLoginState()),
252
+ });
253
+ }
227
254
  void runFeedback.onAgentEnd();
228
255
  });
229
256
 
@@ -310,12 +337,14 @@ export default function (pi: ExtensionAPI) {
310
337
 
311
338
  pi.on("message_end", async (event, ctx) => {
312
339
  const msg = event.message;
313
- if (msg.role !== "assistant" || !running) return;
340
+ if (msg.role !== "assistant") return;
314
341
 
315
342
  const fromQQ = runFeedback.isQQRunActive();
316
343
  if (isLogEnabled("debug")) {
317
344
  log.debug("pi", "assistant message ended", {
318
345
  fromQQ,
346
+ hasBot: Boolean(running),
347
+ hasLogin: Boolean(getLoginState()),
319
348
  stopReason: msg.stopReason,
320
349
  contentTypes: msg.content.map((block) => block.type),
321
350
  textPreview: previewForLog(
@@ -326,7 +355,7 @@ export default function (pi: ExtensionAPI) {
326
355
  ),
327
356
  });
328
357
  }
329
- if (!fromQQ) return;
358
+ if (!running || !fromQQ) return;
330
359
 
331
360
  const isError = msg.stopReason === "error";
332
361
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.4.1",
3
+ "version": "1.5.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
@@ -138,12 +138,28 @@ const enUS = {
138
138
  "diagnostics.budget.expired": "expired",
139
139
  "diagnostics.budget.recorded": "Recorded: passive {passive} / stream {stream} / {tracked} msgId(s)",
140
140
 
141
- "stream.thinking": "思考",
141
+ "stream.thinking": "Thinking",
142
+ "stream.skill": "Skill",
142
143
  "stream.noOutput": "(no output)",
143
144
  "stream.unavailable": "Stream unavailable; falling back to text ({reason}).",
144
145
  "outbound.passiveFailed": "Passive reply failed; falling back to proactive.",
145
146
  "outbound.proactiveFailed": "Proactive send failed: {message}",
146
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.",
147
163
 
148
164
  "settings.invalidRoot": "Invalid config file ({path}): expected a JSON object; using defaults.",
149
165
  "settings.invalidFields": "Invalid config file ({path}): {errors}; invalid values were ignored.",
@@ -353,11 +369,27 @@ const zhCN: Record<TranslationKey, string> = {
353
369
  "diagnostics.budget.recorded": "已记录:被动 {passive} / 流式 {stream} / {tracked} 个 msgId",
354
370
 
355
371
  "stream.thinking": "思考",
372
+ "stream.skill": "技能",
356
373
  "stream.noOutput": "(无输出)",
357
374
  "stream.unavailable": "流式不可用,回退为文本({reason})。",
358
375
  "outbound.passiveFailed": "被动回复失败,改用主动消息。",
359
376
  "outbound.proactiveFailed": "主动消息发送失败:{message}",
360
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。",
361
393
 
362
394
  "settings.invalidRoot": "配置文件无效({path}):应为 JSON 对象;使用默认值。",
363
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
+ }
@@ -1,7 +1,7 @@
1
1
  import { t } from "../infra/i18n";
2
2
 
3
3
  export function thinkingHeader(): string {
4
- return `**💭 ${t("stream.thinking")}**\n\n`;
4
+ return `## 💭 ${t("stream.thinking")}\n\n`;
5
5
  }
6
6
  const ARG_MAX_CHARS = 200;
7
7
  const RESULT_MAX_CHARS = 600;
@@ -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 {
@@ -99,7 +100,7 @@ export function detectSkillRead(toolName: string, args: unknown): SkillRead | un
99
100
  }
100
101
 
101
102
  export function formatSkillBlock(name: string): string {
102
- return `## 🧩 Skill\n\n${inlineCode(name)}\n`;
103
+ return `## 🧩 ${t("stream.skill")}\n\n${inlineCode(name)}\n`;
103
104
  }
104
105
 
105
106
  export function formatToolLine(name: string, args: unknown): string {