@xiaoqiong0v0/opencode-browser-tool 1.12.1 → 1.13.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/README.md +60 -16
- package/dist/client.js +23 -9
- package/dist/config/index.js +50 -0
- package/dist/i18n/en.js +22 -0
- package/dist/i18n/zh.js +22 -0
- package/dist/index.js +107 -0
- package/dist/util/downloads.js +199 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# opencode-browser-tool
|
|
2
2
|
|
|
3
|
-
opencode 插件:Tauri 多 Webview 浏览器外壳 + 零注入视觉元素选取面板。对外只注册 **2 个工具**:`bt_cli`(命令行式分发器,内含 **
|
|
3
|
+
opencode 插件:Tauri 多 Webview 浏览器外壳 + 零注入视觉元素选取面板。对外只注册 **2 个工具**:`bt_cli`(命令行式分发器,内含 **52 条**浏览器自动化命令)与 `bt_set_media_mode`(摄像头/麦克风真伪切换),见下文「工具」。
|
|
4
4
|
|
|
5
5
|
> 架构演进:V1-V3 使用 Playwright 注入式面板(存在弹框类元素无法批注的问题);V4 改为 Rust Shell + 原始调试协议;V5 迁移到 Tauri 2 多 Webview(跨平台)。
|
|
6
6
|
|
|
@@ -20,7 +20,7 @@ opencode 插件:Tauri 多 Webview 浏览器外壳 + 零注入视觉元素选
|
|
|
20
20
|
`%USERPROFILE%\.opencode\plugins-data\opencode-browser-tool\<triple>\bt-shell.exe`),并**就地覆盖**同一路径
|
|
21
21
|
(不按插件版本建目录);同目录另有 `bt-shell.version.json` 记录该可执行文件的来源
|
|
22
22
|
(`tag` / `pluginVersion` / `asset` / `sha256` / `size` / `downloadedAt` / `sourceUrl`,`src/binary.ts:69-79`)。下载用 Release 的 `SHA256SUMS` 做
|
|
23
|
-
sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**原子**替换;跨进程 `.lock`;Linux 下载后 `chmod 755`)。下载在插件初始化时即发起、后台进行、**不阻塞 opencode 启动**(`src/index.ts:
|
|
23
|
+
sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**原子**替换;跨进程 `.lock`;Linux 下载后 `chmod 755`)。下载在插件初始化时即发起、后台进行、**不阻塞 opencode 启动**(`src/index.ts:859`);未就绪时工具调用会给出
|
|
24
24
|
明确提示(下载进度 / 失败原因),不会假装成功。
|
|
25
25
|
|
|
26
26
|
平台支持与系统依赖:
|
|
@@ -54,22 +54,24 @@ sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**
|
|
|
54
54
|
|
|
55
55
|
项目级配置放 `<项目根目录>/.opencode/browser-tool.jsonc`,会覆盖全局。
|
|
56
56
|
|
|
57
|
-
生成的配置还支持(可选项,见 `src/config/index.ts:
|
|
57
|
+
生成的配置还支持(可选项,见 `src/config/index.ts:55-77,254-288`):
|
|
58
58
|
|
|
59
59
|
- `browsersPath` — 浏览器缓存目录(等价 `BT_BROWSERS_PATH`)
|
|
60
60
|
- `cacheDir` — 插件缓存根(默认 `~/.opencode/plugins-cache/opencode-browser-tool`,下设 `sessions/<profile>/<sid>`、`user-data/<profile>`、`exports`、`tmp`)
|
|
61
61
|
- `nodePath` — Node.js 可执行路径(等价 `BT_NODE_PATH`)
|
|
62
|
-
- `disabledTools` — **按已注册工具名**禁用工具。bt_cli 合并后注册的工具名只有 `bt_cli` 与 `bt_set_media_mode`(`src/index.ts:
|
|
62
|
+
- `disabledTools` — **按已注册工具名**禁用工具。bt_cli 合并后注册的工具名只有 `bt_cli` 与 `bt_set_media_mode`(`src/index.ts:905-1004`、过滤逻辑 `src/index.ts:1034-1041`),因此只有写这两个名字才生效;旧的按命令拆分的工具名(`close`、`custom_user_agent`…)或不带前缀的命令名**不再有效、会被静默忽略**(自动生成配置的注释示例同样偏旧,以本节为准)。禁用 `bt_cli` 等于没有命令入口,慎用。
|
|
63
63
|
- `consoleBufferBytes` / `networkBufferBytes` — console / network 日志流的**字节预算**,默认各 **8 MiB**(8 388 608,跨 tab 全局共享);超出按最旧逐出并计入 `dropped`(等价 `BT_CONSOLE_BUFFER_MB` / `BT_NETWORK_BUFFER_MB`,env 以 **MB** 计)
|
|
64
64
|
- `networkBurstWindowMs` — network 聚合窗口,默认 **2000 ms**:仅当与上一条同 key 且间隔 ≤ 该值才累加 `count`(等价 `BT_NETWORK_BURST_MS`)
|
|
65
65
|
- `consoleInject` — Linux console 注入猴补开关,默认 **Linux `true` / Windows `false`**;Windows 走 CDP 不需要注入(等价 `BT_CONSOLE_INJECT`)
|
|
66
|
-
- `webview2Args` — **仅 Windows** 的 WebView2 额外启动参数(透传为 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS`,与进程已有值合并、已包含则不重复),默认四个参数(`src/config/index.ts:
|
|
66
|
+
- `webview2Args` — **仅 Windows** 的 WebView2 额外启动参数(透传为 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS`,与进程已有值合并、已包含则不重复),默认四个参数(`src/config/index.ts:41-49`):
|
|
67
67
|
- `--disable-features=CalculateNativeWinOcclusion`(关窗口遮挡计算)
|
|
68
68
|
- `--disable-background-timer-throttling` / `--disable-renderer-backgrounding` / `--disable-backgrounding-occluded-windows`(窗口被遮挡/后台时不节流、不挂起 renderer,否则 `ExecuteScript` 可能永不回调 → 同步等 UI 的调用永久阻塞)
|
|
69
69
|
|
|
70
|
-
动机是 **RDP 断连/切后台时 DWM 合成暂停**会让依赖 GPU 合成的 WebView2 卡住 UI 线程。**默认保留 GPU 合成**(不加 `--disable-gpu-compositing`);确实需要 CPU 合成排障时自行追加。写**空串**表示**不加任何参数**(`src/config/index.ts:
|
|
70
|
+
动机是 **RDP 断连/切后台时 DWM 合成暂停**会让依赖 GPU 合成的 WebView2 卡住 UI 线程。**默认保留 GPU 合成**(不加 `--disable-gpu-compositing`);确实需要 CPU 合成排障时自行追加。写**空串**表示**不加任何参数**(`src/config/index.ts:386-396`)。等价 env `BT_WEBVIEW2_ARGS`(优先级更高)
|
|
71
|
+
- `downloadDir` — **下载保存目录模板**,默认 `<cache>/sessions/<profile>/<sid>/downloads`。占位符:`<cache>`(插件缓存根)、`<profile>`(配置名)、`<sid>`(会话 id)、`<sname>`(**会话标题**,已做文件名安全化:去掉 `\ / : * ? " < > |` 与控制字符、段尾 `.`/空格、截断 64 字符)。插件**展开后**以 `--download-dir` 传给 shell(详见「下载」一节)。等价 env `BT_DOWNLOAD_DIR`(env 优先)
|
|
72
|
+
- `downloadHistoryLimit` — 每个下载目录保留的**已完成**记录条数,默认 **64**(进行中不淘汰)。等价 env `BT_DOWNLOAD_HISTORY`
|
|
71
73
|
|
|
72
|
-
环境变量(优先级最高,`src/config/index.ts:
|
|
74
|
+
环境变量(优先级最高,`src/config/index.ts:306-331`):
|
|
73
75
|
- `BT_LANG` — 同时设置 panelLang 和 toolLang
|
|
74
76
|
- `BT_PANEL_LANG` / `BT_TOOL_LANG` — 分别只设置面板 UI 语言 / 工具描述语言
|
|
75
77
|
- `BT_BROWSERS_PATH` — 浏览器缓存目录
|
|
@@ -86,6 +88,8 @@ sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**
|
|
|
86
88
|
- `BT_NETWORK_BURST_MS` — network 聚合窗口(ms,默认 2000;对应配置项 `networkBurstWindowMs`)
|
|
87
89
|
- `BT_CONSOLE_INJECT` — Linux console 注入开关(`1`/`0`;默认 Linux `1`、其它平台 `0`;对应配置项 `consoleInject`)
|
|
88
90
|
- `BT_WEBVIEW2_ARGS` — **仅 Windows**:WebView2 额外启动参数(覆盖配置项 `webview2Args`;**空串=不加任何参数**;默认见上方 `webview2Args` 的四个参数;与进程已有 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS` 合并)
|
|
91
|
+
- `BT_DOWNLOAD_DIR` — 下载保存目录模板(覆盖配置项 `downloadDir`;占位符同配置项;插件展开后随 `--download-dir` 下发)
|
|
92
|
+
- `BT_DOWNLOAD_HISTORY` — 每个下载目录保留的已完成记录条数(默认 64;对应配置项 `downloadHistoryLimit`)
|
|
89
93
|
|
|
90
94
|
> **附着模式 vs 启动模式**:设置了 `BT_SHELL_URL`(优先)或 `BT_SHELL_PORT` 时进入附着模式——插件**不 spawn** 任何进程,直接连接该地址的外部 shell;两者都未设置时按启动模式 spawn 本地二进制(`BT_SHELL_PATH` 可覆盖查找路径)。附着模式下 `close` 命令只断开本地连接(**不关闭外部窗口、不结束外部进程**;进程不归插件管理)。
|
|
91
95
|
>
|
|
@@ -118,7 +122,7 @@ set BT_SHELL_TOKEN=my-secret-token
|
|
|
118
122
|
opencode(Bun)
|
|
119
123
|
└─ spawn("bt-shell", [--port ...]) → HTTP 127.0.0.1:PORT
|
|
120
124
|
└─ Rust Shell(Tauri 2 单窗口 + 多 Webview)
|
|
121
|
-
├─ toolbar Webview(顶部:标签行 + 导航行 +
|
|
125
|
+
├─ toolbar Webview(顶部:标签行 + 导航行 + 批注/截图/下载/面板/窗口按钮)
|
|
122
126
|
├─ page-1..page-N Webview(真多标签,每标签独立 webview,渲染目标网页)
|
|
123
127
|
├─ overlay Webview(透明覆盖层,批注高亮/截图选区/通知)
|
|
124
128
|
├─ panel Webview(右侧覆盖式浮层,AI 功能区 + 配置区)
|
|
@@ -137,7 +141,7 @@ opencode(Bun)
|
|
|
137
141
|
|
|
138
142
|
## 工具
|
|
139
143
|
|
|
140
|
-
插件**只注册 2 个工具**(`src/index.ts:
|
|
144
|
+
插件**只注册 2 个工具**(`src/index.ts:905-1004`):
|
|
141
145
|
|
|
142
146
|
| 工具 | 参数 | 说明 |
|
|
143
147
|
|------|------|------|
|
|
@@ -151,10 +155,10 @@ bt_cli({ args: "<command> [--flag value ...]" })
|
|
|
151
155
|
```
|
|
152
156
|
|
|
153
157
|
- **命令名不带 `bt_` 前缀**:写 `click`、`navigate`、`list_tabs`,**不是** `bt_click` / `bt_navigate` / `bt_list_tabs`(旧文档里的 `bt_*` 名称既不是工具名也不是命令名)
|
|
154
|
-
- **分词**:按 shell 风格切分(`string-argv` 0.3.2,`src/index.ts:3` 引入、`:
|
|
155
|
-
- **flag 解析**:第一个 token 为命令名,其余交给 `node:util.parseArgs`(`src/index.ts:
|
|
158
|
+
- **分词**:按 shell 风格切分(`string-argv` 0.3.2,`src/index.ts:3` 引入、`:918` 使用),含空格的值用引号包裹,如 `fill --selector #q --value "hello world"`;**只按引号配对切分、不处理反斜杠转义**——值里要出现引号就改用**另一种引号**包外层(如 `get_visible_text --selector "[title='a b']"`),写成 `--value "a\"b"` 会把 `\` 原样带进值里
|
|
159
|
+
- **flag 解析**:第一个 token 为命令名,其余交给 `node:util.parseArgs`(`src/index.ts:782-801`);**未知 flag 直接报错并回显该命令用法**(输出可自愈,不必先调 help)
|
|
156
160
|
- **敏感值 `@file:`**:值写成 `@file:<路径>` 时由插件读取文件内容作为实际值,**内容不进模型上下文**。flag 值上的 `@file:` 只允许读插件临时目录(全局 tmp 或本会话 tmp)内的文件,其余路径一律拒绝;`lookup` 生成的密码临时文件即用于 `fill --value @file:...`,位于全局 tmp 的用完即删。**`evaluate` 的位置参数项**额外允许读**工作区目录**内的脚本文件(见下方「evaluate:多脚本顺序执行」);**`type --text @file:`** 与 `evaluate` 同口径(工作区目录 + 插件 tmp,且**不删除**源文件,便于反复输入同一段文本)
|
|
157
|
-
- **全局 flag `--private-session`**(任何命令都可带,`src/index.ts:
|
|
161
|
+
- **全局 flag `--private-session`**(任何命令都可带,`src/index.ts:782-801,938-945`):用**调用者自己的 sid** 建私有浏览器实例,不与根会话共用;并且对**同一子会话粘住**——首次用过之后,后续不带该 flag 也继续私有(根会话带它等价于自身)。典型场景:子代理需要**独立的浏览器环境做隔离测试**(自己的 cookie/登录态与窗口,不污染主会话)。根会话自己带它等价于自身(合法但无实际差别)。注意它紧跟某个 string flag 时会被当成该 flag 的值(`parseArgs` 行为),要写就写在命令名之后或命令末尾
|
|
158
162
|
- **会话归属由插件自动透传**(见「多会话」):实例按会话隔离,但 **task 子代理会话默认归并到根会话**——沿 `Session.parentID` 回溯到最顶层,用**根 sid** 作路由键,于是主会话与所有子会话共用同一 bt-shell 实例、同一数据目录 `sessions/<profile>/<根 sid>/`,窗口标题取根会话标题。`args` 里**不需要**也**不支持**传会话 id
|
|
159
163
|
|
|
160
164
|
示例:
|
|
@@ -170,7 +174,7 @@ bt_cli({ args: "screenshot --selector .chart" })
|
|
|
170
174
|
### `--timeout`(下表标 ⏱ 的 18 条命令支持)
|
|
171
175
|
|
|
172
176
|
- 单位**毫秒**,`--timeout 800` 可让卡住的操作约 0.8s 返回(快失败);**未列出的命令不接受该 flag**
|
|
173
|
-
- 钳制区间 `[100, 60000]`:插件侧(`src/index.ts:
|
|
177
|
+
- 钳制区间 `[100, 60000]`:插件侧(`src/index.ts:111-112,120-130`)与 Rust 服务端(`rust/src/service.rs:96-97,104-116`)**同口径二次钳制**(直连 HTTP 也安全);非正整数直接报错拒绝;被钳制时输出如实标注 `(clamped to …ms)`,服务端响应体带 `timeoutMs` / `timeoutClamped`
|
|
174
178
|
- **未传时走各命令自己的默认,并非统一 15s**:eval / CDP / 截图 / `wait_for_selector` 默认 **15s**(`rust/src/ui/mod.rs:35`、`rust/src/control/cdp.rs:27`、`rust/src/control/screenshot.rs:23`、`rust/src/service.rs:609`);点击类(click / hover / drag / press_key 等)的稳定等待默认 **700ms**(`rust/src/control/mouse.rs:19,177-178`);`fill` / `select` 的读回校验默认 **2500ms**(`rust/src/control/input.rs:343`)
|
|
175
179
|
|
|
176
180
|
### `evaluate`:多脚本顺序执行(插件侧,零 Rust 改动)
|
|
@@ -222,9 +226,9 @@ bt_cli({ args: "inject disable --id r1" })
|
|
|
222
226
|
- **`inject list` 只给结构**:`id / order / enabled / match / items / last`(ok、failed + 最近错误首行),明细只显示每个 item 的 `name` + 字节数,**绝不回显脚本内容**
|
|
223
227
|
- **与 `evaluate` 的区别**:`evaluate` 是**一次性**在当前页面执行并返回结果;`inject` 是**持久规则**,命中 URL 后每次加载都执行,结果只写回规则(不回模型),需用 `inject list` 查看
|
|
224
228
|
|
|
225
|
-
### 命令参考(
|
|
229
|
+
### 命令参考(52 条,与 `COMMANDS` 一致)
|
|
226
230
|
|
|
227
|
-
> 唯一真源:`src/index.ts:
|
|
231
|
+
> 唯一真源:`src/index.ts:521-757` 的 `COMMANDS`(本表与之逐条对应,条数、flag 名、可选性均以代码为准)。说明取自 `src/i18n/en.ts` 的 `cli.cmd.*`(`src/i18n/en.ts:49-100`,中文对照见 `src/i18n/zh.ts`)。参数列中**不带 `[]` 者为必填**;⏱ = 支持 `--timeout ms`。完整命令/参数/help 以 `bt_cli({ args: "help" })` 的实际输出为准。
|
|
228
232
|
|
|
229
233
|
| 命令 | 参数(usage 原文) | 说明 |
|
|
230
234
|
|------|------|------|
|
|
@@ -278,6 +282,8 @@ bt_cli({ args: "inject disable --id r1" })
|
|
|
278
282
|
| `profile` | `[--set <name> \| --delete <name>]` | user-data 配置管理:空参列出;`--set` 切换默认配置(影响**后续新会话**的数据根,不重启运行中的浏览器);`--delete` 删除(default/激活项除外) |
|
|
279
283
|
| `exports` | 无 | 显示导出目录与 Edge/Chrome 密码/书签导出指引 |
|
|
280
284
|
| `lookup` | `--csv <path> --url <site>` 必填 | 从密码 CSV 按站点匹配并返回 `@file:` 临时文件路径(密码不进上下文,用完即删) |
|
|
285
|
+
| `downloads` | `[--limit N --clear --cancel <id> --delete <id>]` | 列出本会话下载:**按目录分组**(组标题 `目录尾段 (n)`,行内 `文件名 已收/总量 状态[ 百分比\|不确定] host`);`--limit N` 限制每组条数;`--cancel <id>` 取消进行中(失败回传 shell 原因);`--delete <id>` 删除单条记录**并删除磁盘文件**(进行中需先取消;文件已不存在时仍删记录并说明原因);`--clear` 清空已完成/失败记录(进行中保留)。详见「下载」一节 |
|
|
286
|
+
| `download_dir` | `[--set <绝对路径>]` | 无参输出当前下载目录;`--set` 切换**本会话**目录(不存在自动创建;盘符根/系统目录被拒绝,错误原样回传) |
|
|
281
287
|
|
|
282
288
|
### `fill` vs `type` vs `press_key`(三种输入方式别混用)
|
|
283
289
|
|
|
@@ -338,7 +344,7 @@ bt_cli({ args: "inject disable --id r1" })
|
|
|
338
344
|
> ⚠️ **行为变更(v1.8.0)**:`resize` 与 `set_device` 的宽高一律指**页面内容区(视口)**尺寸,不再是 OS 窗口尺寸。窗口高 = 内容区高 + 工具栏 72px。**旧脚本若按窗口尺寸理解,高度会偏 72px**。API 返回同时给出 `content` 与 `window` 两组尺寸便于核对。
|
|
339
345
|
|
|
340
346
|
- **内容区下限 360×360**:`resize` 低于下限会被钳制,返回 `clamped:true`(工具输出也标注);窗口 `min_inner_size` 同步为 360×432(= 360 内容高 + 72 工具栏)
|
|
341
|
-
- **窄模式(窗口逻辑宽 < 480)**:面板改为**填满整个窗口**(覆盖式,x=0;页面 webview
|
|
347
|
+
- **窄模式(窗口逻辑宽 < 480)**:面板改为**填满整个窗口**(覆盖式,x=0;页面 webview 保持全宽在下层,关闭面板即见完整页面);工具栏的批注/截图/下载/面板四按钮**去文字只留图标**(媒体查询 `@media (max-width: 479px)`,与 Rust `ui::NARROW_MODE_MAX_W=480` 同步维护;下载角标不是文字标签,窄模式下仍显示)。手机类预设(360~412 宽)天然落入窄模式,避免按钮溢出
|
|
342
348
|
|
|
343
349
|
内置 14 种设备预设(**内容区尺寸** + User-Agent),可通过 `set_device`(不带 `--name` 即列出清单)或右侧面板下拉框一键切换:
|
|
344
350
|
|
|
@@ -363,6 +369,44 @@ bt_cli({ args: "inject disable --id r1" })
|
|
|
363
369
|
|
|
364
370
|
面板「配置」区:外观主题(跟随系统/浅色/深色)、设备预设下拉(等价 `set_device`)、开发者工具按钮(等价 `devtools`)。
|
|
365
371
|
|
|
372
|
+
## 下载
|
|
373
|
+
|
|
374
|
+
下载**按会话隔离**:每个会话有独立保存目录,默认 `<cache>/sessions/<profile>/<sid>/downloads`(`<cache>` = 插件缓存根,见「配置」的 `cacheDir`)。
|
|
375
|
+
|
|
376
|
+
- **默认目录模板**:配置项 `downloadDir`,支持占位符 `<cache>` / `<profile>` / `<sid>` / `<sname>`;`<sname>` 取**会话标题**并做文件名安全化(去掉 `\ / : * ? " < > |` 与控制字符、清理段尾 `.`/空格、截断 64 字符)。默认值 `<cache>/sessions/<profile>/<sid>/downloads`
|
|
377
|
+
- **可配置项**:`downloadDir`(模板)、`downloadHistoryLimit`(每组保留的已完成记录条数,默认 **64**);env `BT_DOWNLOAD_DIR` / `BT_DOWNLOAD_HISTORY` 优先级更高,两者都在插件启动时读取(改完需重启 opencode)
|
|
378
|
+
- **下发方式**:spawn 模式由插件**展开模板**后以 `--download-dir <展开后的路径>` 传给 shell,并按 `--user-data-dir` 从模板派生 `<profile>`/`<sid>`;为避免 shell 用另一套规则二次展开,插件会从子进程环境中**移除** `BT_DOWNLOAD_DIR`。**附着模式(`BT_SHELL_URL` / `BT_SHELL_PORT`)不传**:外部 shell 的下载目录由它的启动参数/环境决定,插件无法影响
|
|
379
|
+
- **持久化**:`download_dir --set <绝对路径>` 会把目录写进 `<会话数据目录>/download-dir.txt`,shell 启动时**优先读该文件**,其次才用 `--download-dir`(所以重启后目录保持)。允许任意绝对路径,但**拒绝**盘符根(`C:\`、`D:\`…)与系统目录(Windows `%SystemRoot%`/`%ProgramFiles%`/`%ProgramFiles(x86)%`/`%ProgramData%`;Linux `/`、`/etc`、`/usr`、`/bin`、`/sbin`、`/lib*`、`/boot`、`/dev`、`/proc`、`/sys`),其它路径自动 `mkdir -p`
|
|
380
|
+
- **分组与上限**:列表**按存储目录分组**,每组按开始时间倒序、默认保留最近 **64** 条已完成记录(`downloadHistoryLimit` 可调,**进行中不淘汰**)。目录切换后,旧目录的记录仍按原目录分组显示
|
|
381
|
+
- **面板视图切换**:右侧面板「AI 功能」页顶部有 `记录` / `下载` 两个视图按钮(窄窗口只留图标);下载视图按目录分组、**每组默认收起**,点组标题展开。组内每行显示文件名、进度条(未知总量为不确定动画)、`已收/总量`、状态与来源 host,进行中可**取消**,组头可**打开所在文件夹**。面板可见时每 1s 轮询 `/api/downloads`
|
|
382
|
+
- **工具栏下载按钮 + 角标**:导航行 `批注/截图/下载/面板` 四按钮(窄窗口去文字只留图标,**角标始终可见**)。下载按钮右侧数字角标显示**进行中**数量(0 条时隐藏;超过 99 显示 `99+`);新下载开始(`downloads-changed` 的 `progress`)时角标**脉冲 1s** 且按钮 `title` 变为 `下载:<文件名>`。计数来自 `/api/downloads`(节流 ≥500ms),**与面板是否打开无关**。点击按钮 → `invoke("panel_show_downloads")`:由 Rust 显示面板并广播 `downloads-view-requested`,面板据此切到「下载」视图并立即刷新(无下载时也切过去,显示「暂无下载」)。工具栏不做下拉(高度放不下)
|
|
383
|
+
- **删除记录 + 文件**:下载视图每行有「删除」按钮(trash 图标;窄窗口只留图标,`title` 给出说明),点击后删除该条记录**并删除磁盘文件**,成功提示 `已删除记录与文件`;文件已不存在/删不掉时仍会移除记录,并如实说明原因。进行中的行按钮禁用(先取消)。模型侧用 `downloads --delete <id>`
|
|
384
|
+
- **面板设置目录**:「配置」页「下载」分组可直接编辑当前目录,`保存` = 切换并持久化,`恢复默认` = 删除 `download-dir.txt` 并回到默认模板目录(响应里的 `defaultDir`),`打开文件夹` = 在系统文件管理器中打开当前目录;保存失败把 shell 的错误原文显示在该行(窄窗口按钮自动换行)
|
|
385
|
+
- **模型命令**:`downloads [--limit N]` / `downloads --cancel <id>` / `downloads --delete <id>` / `downloads --clear` / `download_dir [--set <绝对路径>]`,输出格式见「命令参考」
|
|
386
|
+
- **右键另存为**:页面里对图片/链接右键「另存为」也会保存到**当前下载目录**并记入下载列表(Windows;Linux 保持系统对话框)
|
|
387
|
+
- **整页另存**:页面里按 `Ctrl+S` 整页另存同样被接管(Windows):系统对话框被压制,直接存到**当前下载目录**并记入列表,来源标记 `kind = "save-page"`;格式固定为**单文件 HTML**(不生成资源目录),图片等资源保持远程引用
|
|
388
|
+
- **记录持久化**:下载记录写入 `<会话数据目录>/download-history.json`(会话数据目录根下,**不放**下载目录,避免误删;形状同 `downloads` 输出的条目);旧版 `<会话数据目录>/downloads/history.json` 在启动时一次性迁移并删除;变更后防抖保存(静默 500ms,进度持续刷新时最多 2s 写一次),退出前强制落盘,原子写(临时文件 + rename);坏 JSON 按空列表启动。上次进程被强杀时仍为「进行中」的记录,重启后标为**失败**(原因 `interrupted by restart`)
|
|
389
|
+
- **UI 右键菜单**:面板 / 工具栏 / 覆盖层 / 新标签页已禁用浏览器默认右键菜单(不再出现「刷新」「另存为」等);网页内容区右键保留
|
|
390
|
+
|
|
391
|
+
```text
|
|
392
|
+
bt_cli({ args: "downloads" })
|
|
393
|
+
bt_cli({ args: "downloads --limit 10" })
|
|
394
|
+
bt_cli({ args: "downloads --cancel 3" })
|
|
395
|
+
bt_cli({ args: "downloads --delete 2" })
|
|
396
|
+
bt_cli({ args: "download_dir" })
|
|
397
|
+
bt_cli({ args: "download_dir --set D:\tmp\dl" })
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
`downloads` 输出示例(组标题 = 目录尾段 + 条数;行内为 `文件名 已收/总量 状态[ 百分比|不确定] host`,失败行末附原因):
|
|
401
|
+
|
|
402
|
+
```text
|
|
403
|
+
dl (2)
|
|
404
|
+
report.pdf 12MB/45MB 下载中 27% files.example.com
|
|
405
|
+
setup.exe 3MB 下载中 不确定 cdn.example.com
|
|
406
|
+
proj (1)
|
|
407
|
+
data.csv 700KB/700KB 已完成 example.com
|
|
408
|
+
```
|
|
409
|
+
|
|
366
410
|
## 多会话
|
|
367
411
|
|
|
368
412
|
浏览器实例**按会话隔离**:独立进程 / 独立端口 / 独立用户数据目录,窗口、标签、UA、批注与 cookie/存储互不共享(`sessionIsolation` / `browserType` 配置项及 `--session-isolation` / `--browser` 参数自 1.9.0 已删除,会话隔离是唯一行为;旧配置文件里的这两项会被忽略)。
|
package/dist/client.js
CHANGED
|
@@ -12,7 +12,7 @@ import { fileURLToPath } from "url";
|
|
|
12
12
|
import { log } from "./logger.js";
|
|
13
13
|
import { getNotifyUrlForSession } from "./notify-server.js";
|
|
14
14
|
import { tf } from "./i18n/index.js";
|
|
15
|
-
import { getLogStreamEnv, getWebviewEnv } from "./config/index.js";
|
|
15
|
+
import { getLogStreamEnv, getWebviewEnv, resolveDownloadSpawnConfig } from "./config/index.js";
|
|
16
16
|
import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
|
|
17
17
|
import { sanitizeForModel } from "./util/sanitize.js";
|
|
18
18
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
@@ -166,24 +166,26 @@ export function isRunning(sid) {
|
|
|
166
166
|
return true;
|
|
167
167
|
return !!attachInstance?.ready;
|
|
168
168
|
}
|
|
169
|
-
/**
|
|
170
|
-
|
|
169
|
+
/**
|
|
170
|
+
* 取会话标题(有界等待,不阻塞启动):拿不到/超时/为空时回退 sid 后 6 位。
|
|
171
|
+
* 下载目录模板的 `<sname>` 与窗口标题(`bt-shell · <标题>`)共用这一份来源,保证口径一致。
|
|
172
|
+
*/
|
|
173
|
+
async function resolveSessionTitle(sid) {
|
|
171
174
|
const suffix = sid.length > 6 ? sid.slice(-6) : sid || "main";
|
|
172
|
-
const fallback = `bt-shell · ${suffix}`;
|
|
173
175
|
if (!titleResolver)
|
|
174
|
-
return
|
|
176
|
+
return suffix;
|
|
175
177
|
try {
|
|
176
178
|
const t = await Promise.race([
|
|
177
179
|
Promise.resolve().then(() => titleResolver(sid)),
|
|
178
180
|
new Promise((r) => setTimeout(() => r(null), TITLE_RESOLVE_TIMEOUT_MS)),
|
|
179
181
|
]);
|
|
180
182
|
if (t && t.trim())
|
|
181
|
-
return
|
|
183
|
+
return t.trim();
|
|
182
184
|
}
|
|
183
185
|
catch {
|
|
184
186
|
// 标题拿不到就用后缀,绝不因此失败
|
|
185
187
|
}
|
|
186
|
-
return
|
|
188
|
+
return suffix;
|
|
187
189
|
}
|
|
188
190
|
/**
|
|
189
191
|
* 轮询等待服务就绪(READY_TIMEOUT_MS 超时);超时抛出给定提示。
|
|
@@ -282,7 +284,11 @@ async function resolveShellPath() {
|
|
|
282
284
|
async function spawnForSession(sid, shell) {
|
|
283
285
|
const cfg = serviceConfig;
|
|
284
286
|
const dataDir = cfg?.resolveDataDir ? cfg.resolveDataDir(sid) : "";
|
|
285
|
-
|
|
287
|
+
// 会话标题同时用于窗口标题与下载目录模板的 <sname>(同一份有界等待结果)
|
|
288
|
+
const sessionName = await resolveSessionTitle(sid);
|
|
289
|
+
const title = `bt-shell · ${sessionName}`;
|
|
290
|
+
// 下载目录(1.13.0):插件侧展开模板后以 --download-dir 传入;每组历史上限走 env
|
|
291
|
+
const download = resolveDownloadSpawnConfig(sid, sessionName);
|
|
286
292
|
// 本实例的鉴权令牌:16 字节 → 32 hex;端口重试沿用同一令牌(新的子进程仍是同一实例语义)
|
|
287
293
|
const token = randomBytes(16).toString("hex");
|
|
288
294
|
let lastErr = null;
|
|
@@ -302,6 +308,8 @@ async function spawnForSession(sid, shell) {
|
|
|
302
308
|
// 每会话独立 user-data-dir(WebView2 profile 隔离);未提供则不传(回落 WebView2 默认目录)
|
|
303
309
|
if (dataDir)
|
|
304
310
|
args.push("--user-data-dir", dataDir);
|
|
311
|
+
// 下载目录:模板已由插件展开(见 resolveDownloadSpawnConfig);持久化文件优先于本参数
|
|
312
|
+
args.push("--download-dir", download.dir);
|
|
305
313
|
// 推送式投递:注册**本会话**的通知地址 → 通知按 sid 归属
|
|
306
314
|
const notifyUrl = getNotifyUrlForSession(sid);
|
|
307
315
|
if (notifyUrl)
|
|
@@ -310,7 +318,10 @@ async function spawnForSession(sid, shell) {
|
|
|
310
318
|
try {
|
|
311
319
|
// 日志流配置(1.12.0)以 env 传给 shell:console/network 缓冲预算、network 聚合窗口、
|
|
312
320
|
// Linux 注入开关。附着模式不在本函数(不 spawn → 不传,配置由外部启动者负责)。
|
|
313
|
-
const env = { ...process.env, ...getLogStreamEnv(), ...getWebviewEnv() };
|
|
321
|
+
const env = { ...process.env, ...getLogStreamEnv(), ...getWebviewEnv(), ...download.env };
|
|
322
|
+
// 目录已展开并随 --download-dir 传入:移除 env 里的模板,避免 shell 用另一套规则二次展开
|
|
323
|
+
// (Rust 侧 env 优先级高于命令行参数,留着会让两处口径不一致)
|
|
324
|
+
delete env.BT_DOWNLOAD_DIR;
|
|
314
325
|
proc = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"], env });
|
|
315
326
|
}
|
|
316
327
|
catch (e) {
|
|
@@ -851,6 +862,9 @@ export const service = {
|
|
|
851
862
|
notify: cmd("notify"),
|
|
852
863
|
consoleLogs: cmd("console-logs"),
|
|
853
864
|
networkLogs: cmd("network-logs"),
|
|
865
|
+
// 下载列表 / 下载目录(1.13.0):/api/downloads、/api/download-dir
|
|
866
|
+
downloads: cmd("downloads"),
|
|
867
|
+
downloadDir: cmd("download-dir"),
|
|
854
868
|
expectResponse: cmd("expect-response"),
|
|
855
869
|
assertResponse: cmd("assert-response"),
|
|
856
870
|
panelConfig: cmd("panel-config"),
|
package/dist/config/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import { resolve, dirname, relative, isAbsolute, sep } from "path";
|
|
|
3
3
|
import { homedir } from "os";
|
|
4
4
|
import { tf } from "../i18n/index.js";
|
|
5
5
|
import { log } from "../logger.js";
|
|
6
|
+
import { DEFAULT_DOWNLOAD_DIR_TEMPLATE, DEFAULT_DOWNLOAD_HISTORY, expandDownloadDir } from "../util/downloads.js";
|
|
6
7
|
const PLUGIN_NAME = "opencode-browser-tool";
|
|
7
8
|
const CONFIG_FILE = "browser-tool.jsonc";
|
|
8
9
|
/** profile 名长度上限(字符) */
|
|
@@ -48,6 +49,8 @@ const defaults = {
|
|
|
48
49
|
networkBurstWindowMs: DEFAULT_NETWORK_BURST_MS,
|
|
49
50
|
consoleInject: DEFAULT_CONSOLE_INJECT,
|
|
50
51
|
webview2Args: DEFAULT_WEBVIEW2_ARGS,
|
|
52
|
+
downloadDir: DEFAULT_DOWNLOAD_DIR_TEMPLATE,
|
|
53
|
+
downloadHistoryLimit: DEFAULT_DOWNLOAD_HISTORY,
|
|
51
54
|
};
|
|
52
55
|
let _config = { ...defaults };
|
|
53
56
|
let _worktree = "";
|
|
@@ -234,6 +237,13 @@ function applyConfigFile(config, filePath) {
|
|
|
234
237
|
config.networkBurstWindowMs = burstMs;
|
|
235
238
|
if (typeof fileConfig.consoleInject === "boolean")
|
|
236
239
|
config.consoleInject = fileConfig.consoleInject;
|
|
240
|
+
// 下载目录模板:空串视为未配置(回落默认模板);历史上限只收正整数
|
|
241
|
+
if (typeof fileConfig.downloadDir === "string" && fileConfig.downloadDir.trim()) {
|
|
242
|
+
config.downloadDir = fileConfig.downloadDir.trim();
|
|
243
|
+
}
|
|
244
|
+
const downloadLimit = toPositiveInt(fileConfig.downloadHistoryLimit);
|
|
245
|
+
if (downloadLimit !== undefined)
|
|
246
|
+
config.downloadHistoryLimit = downloadLimit;
|
|
237
247
|
}
|
|
238
248
|
catch { }
|
|
239
249
|
}
|
|
@@ -285,6 +295,13 @@ function applyEnv(config) {
|
|
|
285
295
|
const inject = parseBoolFlag(process.env.BT_CONSOLE_INJECT);
|
|
286
296
|
if (inject !== undefined)
|
|
287
297
|
config.consoleInject = inject;
|
|
298
|
+
// 下载目录模板 / 每组历史上限(1.13.0):与传给 shell 的口径一致,env 优先于配置文件
|
|
299
|
+
const downloadDir = process.env.BT_DOWNLOAD_DIR?.trim();
|
|
300
|
+
if (downloadDir)
|
|
301
|
+
config.downloadDir = downloadDir;
|
|
302
|
+
const downloadLimit = toPositiveInt(process.env.BT_DOWNLOAD_HISTORY);
|
|
303
|
+
if (downloadLimit !== undefined)
|
|
304
|
+
config.downloadHistoryLimit = downloadLimit;
|
|
288
305
|
}
|
|
289
306
|
/**
|
|
290
307
|
* 字节预算 → 传给 shell 的 MB 字符串。
|
|
@@ -341,6 +358,31 @@ export function getWebviewEnv() {
|
|
|
341
358
|
const merged = !existing ? args : existing.includes(args) ? existing : `${existing} ${args}`;
|
|
342
359
|
return { WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: merged };
|
|
343
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* 解析 spawn 时的下载配置(1.13.0)。
|
|
363
|
+
*
|
|
364
|
+
* 目录模板优先级:env `BT_DOWNLOAD_DIR` > 配置 `downloadDir` > 默认模板
|
|
365
|
+
* (env 已在 `applyEnv` 合并进 config)。占位符取值:`<cache>` = 插件缓存根、
|
|
366
|
+
* `<profile>` = 当前 profile、`<sid>` = 会话路由 key、`<sname>` = 会话标题(已安全化)。
|
|
367
|
+
*
|
|
368
|
+
* 只负责「算出传什么」;**是否下传由 spawn 分支决定**(附着模式不传,见 README)。
|
|
369
|
+
*
|
|
370
|
+
* @param sid 会话 id(归并后的浏览器 key)
|
|
371
|
+
* @param sessionName 会话标题(可为空,空则 `<sname>` 回退 `<sid>`)
|
|
372
|
+
* @returns 展开后的目录、历史上限与需下发的环境变量
|
|
373
|
+
*/
|
|
374
|
+
export function resolveDownloadSpawnConfig(sid, sessionName) {
|
|
375
|
+
const cfg = getConfig();
|
|
376
|
+
const template = (cfg.downloadDir || "").trim() || DEFAULT_DOWNLOAD_DIR_TEMPLATE;
|
|
377
|
+
const dir = expandDownloadDir(template, {
|
|
378
|
+
cacheDir: getCacheDir(),
|
|
379
|
+
profile: getActiveProfile(),
|
|
380
|
+
sid,
|
|
381
|
+
sessionName,
|
|
382
|
+
});
|
|
383
|
+
const historyLimit = toPositiveInt(cfg.downloadHistoryLimit) ?? DEFAULT_DOWNLOAD_HISTORY;
|
|
384
|
+
return { dir, historyLimit, env: { BT_DOWNLOAD_HISTORY: String(historyLimit) } };
|
|
385
|
+
}
|
|
344
386
|
function isValidLang(lang) {
|
|
345
387
|
return ["en", "zh"].includes(lang);
|
|
346
388
|
}
|
|
@@ -378,6 +420,14 @@ function generateDefaultConfig(filePath) {
|
|
|
378
420
|
// 1.9.0 起「每会话独立浏览器实例」为唯一行为(原 sessionIsolation 开关从未生效,已移除);
|
|
379
421
|
// browserType 同理移除(--browser 从不被 bt-shell 解析)。旧配置里若仍写着这两项会被忽略。
|
|
380
422
|
|
|
423
|
+
// 下载保存目录模板(可选,默认 "<cache>/sessions/<profile>/<sid>/downloads")
|
|
424
|
+
// 占位符:<cache> 插件缓存根 / <profile> 配置名 / <sid> 会话 id / <sname> 会话标题(已做文件名安全化)
|
|
425
|
+
// 必须展开成绝对路径;等价 BT_DOWNLOAD_DIR(env 优先)
|
|
426
|
+
// "downloadDir": "<cache>/sessions/<profile>/<sid>/downloads",
|
|
427
|
+
|
|
428
|
+
// 每个下载目录保留的已完成记录条数(可选,默认 64;进行中不淘汰;等价 BT_DOWNLOAD_HISTORY)
|
|
429
|
+
// "downloadHistoryLimit": 64,
|
|
430
|
+
|
|
381
431
|
// Node.js 路径(可选,不设则从 PATH 查找 node)
|
|
382
432
|
// "nodePath": "C:/Program Files/nodejs/node.exe",
|
|
383
433
|
}
|
package/dist/i18n/en.js
CHANGED
|
@@ -91,6 +91,8 @@ const en = {
|
|
|
91
91
|
"cli.cmd.profile": "List/switch/delete user profiles (--set <name> switches the default for new sessions without restarting running browsers; --delete removes a non-default, non-active profile)",
|
|
92
92
|
"cli.cmd.exports": "Show export dir + how to export Edge/Chrome passwords/bookmarks",
|
|
93
93
|
"cli.cmd.lookup": "Find a password in a CSV export, return @file: path (not in context)",
|
|
94
|
+
"cli.cmd.downloads": "List this session's downloads grouped by directory (--limit N caps items per group; --cancel <id> cancels an in-progress download; --delete <id> drops one record and deletes its file, cancel it first if in progress; --clear drops finished/failed records, in-progress ones are kept)",
|
|
95
|
+
"cli.cmd.download_dir": "Show the download directory; --set <absolute path> switches it for this session (created if missing; filesystem roots and system directories are refused)",
|
|
94
96
|
// ---- Diagnostic notes appended to command output ----
|
|
95
97
|
"cli.note.degraded": " (degraded: {reason})",
|
|
96
98
|
"cli.note.not_ready": " (not ready after {ms}ms{rs})",
|
|
@@ -121,6 +123,26 @@ const en = {
|
|
|
121
123
|
"cli.out.html_truncated": "…(truncated at maxLength={n})",
|
|
122
124
|
"cli.out.console_empty": "(no console logs — the page may have produced none, may have navigated (logs are per tab and kept across navigation), or the logs may be in another tab; try --tab or list_tabs)",
|
|
123
125
|
"cli.out.network_empty": "(no network requests — the page may have made none, may have navigated, or the requests may be in another tab (also check whether --clear just emptied the stream); try --tab or list_tabs)",
|
|
126
|
+
// ---- Downloads (1.13.0) ----
|
|
127
|
+
"cli.out.downloads_empty": "(no downloads)",
|
|
128
|
+
"cli.out.downloads_unknown_size": "unknown",
|
|
129
|
+
"cli.out.downloads_state_progress": "downloading",
|
|
130
|
+
"cli.out.downloads_state_completed": "completed",
|
|
131
|
+
"cli.out.downloads_state_failed": "failed",
|
|
132
|
+
"cli.out.downloads_state_canceled": "canceled",
|
|
133
|
+
"cli.out.downloads_canceled": "Canceled download: {id}",
|
|
134
|
+
"cli.out.downloads_cleared": "Cleared finished/failed records ({n} in progress kept)",
|
|
135
|
+
"cli.out.downloads_deleted": "Deleted {name} (record + file)",
|
|
136
|
+
"cli.out.downloads_deleted_keep_file": "Deleted record {name} (file kept: {msg})",
|
|
137
|
+
"cli.out.download_dir": "Download directory: {dir}",
|
|
138
|
+
"cli.out.download_dir_set": "Download directory set: {dir}",
|
|
139
|
+
"cli.note.download_dir_not_persisted": " (not persisted: no session data dir; the default is restored after the shell restarts)",
|
|
140
|
+
"cli.err.downloads_limit_invalid": "--limit must be a positive integer, got: {v}",
|
|
141
|
+
"cli.err.downloads_cancel_failed": "Cancel failed for {id}: {msg}",
|
|
142
|
+
"cli.err.downloads_clear_failed": "Failed to clear download records: {msg}",
|
|
143
|
+
"cli.err.downloads_delete_failed": "Failed to delete {id}: {msg}",
|
|
144
|
+
"cli.err.download_dir_set_failed": "Failed to set the download directory: {msg}",
|
|
145
|
+
"cli.err.download_dir_query_failed": "Failed to read the download directory: {msg}",
|
|
124
146
|
// ---- Log stream formatting fragments (technical tokens stay identical across languages) ----
|
|
125
147
|
"cli.out.inject_empty": "No inject rules yet. Add one with: inject add --match \"*host*\" --file hook.js",
|
|
126
148
|
"cli.out.inject_removed": "inject: removed {id} ({n} rule(s) left)",
|
package/dist/i18n/zh.js
CHANGED
|
@@ -91,6 +91,8 @@ const zh = {
|
|
|
91
91
|
"cli.cmd.profile": "列出/切换/删除用户配置(--set <name> 切换默认配置,影响后续新会话、不重启运行中的浏览器;--delete 删除非 default、非当前激活配置)",
|
|
92
92
|
"cli.cmd.exports": "显示导出目录 + Edge/Chrome 密码/书签导出引导",
|
|
93
93
|
"cli.cmd.lookup": "在密码 CSV 中查找站点,返回 @file: 路径(密码不进上下文)",
|
|
94
|
+
"cli.cmd.downloads": "按目录列出本会话的下载(--limit N 限制每组条数;--cancel <id> 取消进行中的下载;--delete <id> 删除单条记录并删除磁盘文件,进行中需先取消;--clear 清空已完成/失败记录,进行中保留)",
|
|
95
|
+
"cli.cmd.download_dir": "查看下载保存目录;--set <绝对路径> 切换本会话目录(不存在会自动创建;盘符根与系统目录会被拒绝)",
|
|
94
96
|
// ---- 诊断型 note(命令输出的追加说明) ----
|
|
95
97
|
"cli.note.degraded": " (已降级: {reason})",
|
|
96
98
|
"cli.note.not_ready": " ({ms}ms 内未就绪{rs})",
|
|
@@ -121,6 +123,26 @@ const zh = {
|
|
|
121
123
|
"cli.out.html_truncated": "…(已在 maxLength={n} 处截断)",
|
|
122
124
|
"cli.out.console_empty": "(无控制台日志——可能页面没有产生日志、页面已导航(日志按标签保留、跨导航不清空)、或日志在其它标签;可试 --tab 或 list_tabs)",
|
|
123
125
|
"cli.out.network_empty": "(无网络请求——可能页面没有发起请求、页面已导航、或请求在其它标签(也请确认是否刚用 --clear 清空);可试 --tab 或 list_tabs)",
|
|
126
|
+
// ---- 下载(1.13.0) ----
|
|
127
|
+
"cli.out.downloads_empty": "(暂无下载)",
|
|
128
|
+
"cli.out.downloads_unknown_size": "不确定",
|
|
129
|
+
"cli.out.downloads_state_progress": "下载中",
|
|
130
|
+
"cli.out.downloads_state_completed": "已完成",
|
|
131
|
+
"cli.out.downloads_state_failed": "失败",
|
|
132
|
+
"cli.out.downloads_state_canceled": "已取消",
|
|
133
|
+
"cli.out.downloads_canceled": "已取消下载:{id}",
|
|
134
|
+
"cli.out.downloads_cleared": "已清空已完成/失败记录(保留进行中 {n} 条)",
|
|
135
|
+
"cli.out.downloads_deleted": "已删除 {name}(记录与文件)",
|
|
136
|
+
"cli.out.downloads_deleted_keep_file": "已删除记录 {name}(文件未删除:{msg})",
|
|
137
|
+
"cli.out.download_dir": "下载目录:{dir}",
|
|
138
|
+
"cli.out.download_dir_set": "下载目录已切换:{dir}",
|
|
139
|
+
"cli.note.download_dir_not_persisted": "(未持久化:没有会话数据目录,shell 重启后会恢复默认目录)",
|
|
140
|
+
"cli.err.downloads_limit_invalid": "--limit 需为正整数,收到:{v}",
|
|
141
|
+
"cli.err.downloads_cancel_failed": "取消 {id} 失败:{msg}",
|
|
142
|
+
"cli.err.downloads_clear_failed": "清空下载记录失败:{msg}",
|
|
143
|
+
"cli.err.downloads_delete_failed": "删除 {id} 失败:{msg}",
|
|
144
|
+
"cli.err.download_dir_set_failed": "切换下载目录失败:{msg}",
|
|
145
|
+
"cli.err.download_dir_query_failed": "读取下载目录失败:{msg}",
|
|
124
146
|
// ---- 日志流格式化片段(技术标记两种语言保持一致) ----
|
|
125
147
|
"cli.out.inject_empty": "尚无注入规则。添加示例: inject add --match \"*host*\" --file hook.js",
|
|
126
148
|
"cli.out.inject_removed": "inject: 已删除 {id}(剩余 {n} 条)",
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,7 @@ import { EVAL_ITEM_MAX_BYTES, EVAL_TOTAL_MAX_BYTES, classifyEvalArgs, runEvalIte
|
|
|
14
14
|
import { INJECT_RULE_MAX_BYTES, buildInjectItems, formatInjectAdd, formatInjectList, formatInjectTest, injectAddIssue, injectRuleLimitIssue, normalizeInjectAction, } from "./util/inject-rules.js";
|
|
15
15
|
import { formatConsoleItems, formatNetworkItems, renderLogText, } from "./util/log-format.js";
|
|
16
16
|
import { TYPE_TEXT_MAX_BYTES, resolveTypeText, typeTextIssue, formatTypeOutput, } from "./util/type-text.js";
|
|
17
|
+
import { formatDownloads, buildDownloadsPayload, buildDownloadDirPayload, downloadsLimitIssue, } from "./util/downloads.js";
|
|
17
18
|
import { tool } from "@opencode-ai/plugin";
|
|
18
19
|
import { log } from "./logger.js";
|
|
19
20
|
import { createSessionIDCache, extractSessionIDFromEvent } from "./session-id.js";
|
|
@@ -399,6 +400,99 @@ function networkLogParams(a) {
|
|
|
399
400
|
p.clear = true;
|
|
400
401
|
return p;
|
|
401
402
|
}
|
|
403
|
+
/** 下载列表输出用的文案(状态名 / 不确定标注 / 空态;util 不依赖 i18n) */
|
|
404
|
+
function downloadsLabels() {
|
|
405
|
+
return {
|
|
406
|
+
empty: _t("cli.out.downloads_empty"),
|
|
407
|
+
unknownSize: _t("cli.out.downloads_unknown_size"),
|
|
408
|
+
states: {
|
|
409
|
+
progress: _t("cli.out.downloads_state_progress"),
|
|
410
|
+
completed: _t("cli.out.downloads_state_completed"),
|
|
411
|
+
failed: _t("cli.out.downloads_state_failed"),
|
|
412
|
+
canceled: _t("cli.out.downloads_state_canceled"),
|
|
413
|
+
},
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/** 快照里的条目总数(`--clear` 后用于说明“保留了几条进行中”) */
|
|
417
|
+
function countDownloadItems(data) {
|
|
418
|
+
return (data?.groups ?? []).reduce((n, g) => n + (Array.isArray(g?.items) ? g.items.length : 0), 0);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* `downloads`:列出本会话下载(按目录分组),或取消/清空/删除单条。
|
|
422
|
+
*
|
|
423
|
+
* - `--limit N`:每组最多返回 N 条(正整数,插件侧先校验,不下发坏值)
|
|
424
|
+
* - `--cancel <id>`:取消进行中的下载;shell 明确报错时原样带回原因
|
|
425
|
+
* - `--clear`:清空已完成/失败记录(进行中保留)
|
|
426
|
+
* - `--delete <id>`:删除一条已结束的记录并删除磁盘文件;进行中会被 shell 拒绝
|
|
427
|
+
*
|
|
428
|
+
* @param a 已解析命令参数
|
|
429
|
+
* @returns 回模型的多行文本
|
|
430
|
+
*/
|
|
431
|
+
async function runDownloads(a) {
|
|
432
|
+
if (downloadsLimitIssue(a.limit))
|
|
433
|
+
return _t("cli.err.downloads_limit_invalid", { v: String(a.limit) });
|
|
434
|
+
const cancelId = typeof a.cancel === "string" ? a.cancel.trim() : "";
|
|
435
|
+
const deleteId = typeof a.delete === "string" ? a.delete.trim() : "";
|
|
436
|
+
const clearing = a.clear === true;
|
|
437
|
+
let data;
|
|
438
|
+
try {
|
|
439
|
+
data = (await service.downloads(buildDownloadsPayload(a)));
|
|
440
|
+
}
|
|
441
|
+
catch (e) {
|
|
442
|
+
// postJson 已脱敏;这里只决定「带原因回模型」还是走统一失败文案
|
|
443
|
+
const msg = sanitizeForModel(e?.message || String(e));
|
|
444
|
+
if (deleteId)
|
|
445
|
+
return _t("cli.err.downloads_delete_failed", { id: deleteId, msg });
|
|
446
|
+
if (cancelId)
|
|
447
|
+
return _t("cli.err.downloads_cancel_failed", { id: cancelId, msg });
|
|
448
|
+
if (clearing)
|
|
449
|
+
return _t("cli.err.downloads_clear_failed", { msg });
|
|
450
|
+
throw e;
|
|
451
|
+
}
|
|
452
|
+
// --delete 是独占动作:shell 只回删除结果(不返回快照),据此输出一行结论
|
|
453
|
+
if (deleteId) {
|
|
454
|
+
const result = (data ?? {});
|
|
455
|
+
const name = (result.filename || "").trim() || deleteId;
|
|
456
|
+
if (result.deleted === false) {
|
|
457
|
+
return _t("cli.out.downloads_deleted_keep_file", { name, msg: result.error || "unknown" });
|
|
458
|
+
}
|
|
459
|
+
return _t("cli.out.downloads_deleted", { name });
|
|
460
|
+
}
|
|
461
|
+
const parts = [];
|
|
462
|
+
if (cancelId)
|
|
463
|
+
parts.push(_t("cli.out.downloads_canceled", { id: cancelId }));
|
|
464
|
+
if (clearing)
|
|
465
|
+
parts.push(_t("cli.out.downloads_cleared", { n: countDownloadItems(data) }));
|
|
466
|
+
parts.push(formatDownloads(data, downloadsLabels()));
|
|
467
|
+
return parts.join("\n");
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* `download_dir`:查询当前保存目录,或 `--set <绝对路径>` 切换本会话目录。
|
|
471
|
+
*
|
|
472
|
+
* 路径合法性(绝对路径 / 非盘符根 / 非系统目录 / 自动 mkdir)全部由 shell 判定,
|
|
473
|
+
* 插件侧**不做白名单**,失败时把 shell 的原始错误带回模型(不在插件侧改写原因)。
|
|
474
|
+
*
|
|
475
|
+
* @param a 已解析命令参数
|
|
476
|
+
* @returns 回模型的文本
|
|
477
|
+
*/
|
|
478
|
+
async function runDownloadDir(a) {
|
|
479
|
+
const setting = typeof a.set === "string";
|
|
480
|
+
let data;
|
|
481
|
+
try {
|
|
482
|
+
data = await service.downloadDir(buildDownloadDirPayload(a));
|
|
483
|
+
}
|
|
484
|
+
catch (e) {
|
|
485
|
+
const msg = sanitizeForModel(e?.message || String(e));
|
|
486
|
+
return setting
|
|
487
|
+
? _t("cli.err.download_dir_set_failed", { msg })
|
|
488
|
+
: _t("cli.err.download_dir_query_failed", { msg });
|
|
489
|
+
}
|
|
490
|
+
const dir = data?.dir || "";
|
|
491
|
+
if (!setting)
|
|
492
|
+
return _t("cli.out.download_dir", { dir });
|
|
493
|
+
// persisted=false:会话数据目录不可用(未传 --user-data-dir),重启后会回到默认目录
|
|
494
|
+
return _t("cli.out.download_dir_set", { dir }) + (data?.persisted === false ? _t("cli.note.download_dir_not_persisted") : "");
|
|
495
|
+
}
|
|
402
496
|
const COMMANDS = {
|
|
403
497
|
navigate: { usage: "--url", descKey: "cli.cmd.navigate", args: [{ flag: "url" }], run: async (a) => {
|
|
404
498
|
const r = await service.navigate(a);
|
|
@@ -491,6 +585,19 @@ const COMMANDS = {
|
|
|
491
585
|
return renderLogText(lines, r?.dropped) || _t("cli.out.network_empty");
|
|
492
586
|
},
|
|
493
587
|
},
|
|
588
|
+
// downloads:本会话下载列表(按目录分组)/取消/清空/删除;download_dir:查询/切换保存目录(1.13.0)
|
|
589
|
+
downloads: {
|
|
590
|
+
usage: "[--limit N --clear --cancel <id> --delete <id>]",
|
|
591
|
+
descKey: "cli.cmd.downloads",
|
|
592
|
+
args: [{ flag: "limit" }, { flag: "clear", type: "boolean" }, { flag: "cancel" }, { flag: "delete" }],
|
|
593
|
+
run: async (a) => runDownloads(a),
|
|
594
|
+
},
|
|
595
|
+
download_dir: {
|
|
596
|
+
usage: "[--set <path>]",
|
|
597
|
+
descKey: "cli.cmd.download_dir",
|
|
598
|
+
args: [{ flag: "set" }],
|
|
599
|
+
run: async (a) => runDownloadDir(a),
|
|
600
|
+
},
|
|
494
601
|
go_back: { usage: "", descKey: "cli.cmd.go_back", run: async (a) => { const r = await service.goBack(sidArgs(a)); return _t("cli.out.go_back", { url: r.url }) + readyNote(r); } },
|
|
495
602
|
go_forward: { usage: "", descKey: "cli.cmd.go_forward", run: async (a) => { const r = await service.goForward(sidArgs(a)); return _t("cli.out.go_forward", { url: r.url }) + readyNote(r); } },
|
|
496
603
|
// resize:宽高=内容区(视口)尺寸;被钳到下限时如实标注(服务端返回 clamped/content/window)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 下载列表 / 下载目录(1.13.0)的纯逻辑:目录模板展开、请求体构造、列表文本格式化。
|
|
3
|
+
*
|
|
4
|
+
* 不接触 fs / 网络 / i18n(文案由调用方传入 `DownloadsLabels`),便于单测。
|
|
5
|
+
* 端点与字段口径见 `rust/src/downloads.rs`(`/api/downloads`、`/api/download-dir`)。
|
|
6
|
+
*/
|
|
7
|
+
/** 默认下载目录模板:插件侧展开后经 `--download-dir` 传给 shell */
|
|
8
|
+
export const DEFAULT_DOWNLOAD_DIR_TEMPLATE = "<cache>/sessions/<profile>/<sid>/downloads";
|
|
9
|
+
/** 每个目录保留的已完成记录数默认值(等价 env `BT_DOWNLOAD_HISTORY`) */
|
|
10
|
+
export const DEFAULT_DOWNLOAD_HISTORY = 64;
|
|
11
|
+
/** `<sname>` 路径段长度上限(字符) */
|
|
12
|
+
export const SNAME_MAX_LEN = 64;
|
|
13
|
+
/** 单条会话 id 路径段长度上限(字符;只做防护,正常 sid 远小于此值) */
|
|
14
|
+
const SID_MAX_LEN = 128;
|
|
15
|
+
/** 文件名不安全字符:Windows 非法字符 + 控制字符 */
|
|
16
|
+
const SEGMENT_FORBIDDEN = /[\\/:*?"<>|\u0000-\u001f\u007f]/g;
|
|
17
|
+
/** 空白折叠(多个空白压成一个空格) */
|
|
18
|
+
const WHITESPACE_RUN = /\s+/g;
|
|
19
|
+
/** 段尾的 `.` / 空格(Windows 会静默去掉,这里主动清理) */
|
|
20
|
+
const TRAILING_DOTS = /[. ]+$/g;
|
|
21
|
+
/**
|
|
22
|
+
* 清理路径段:去掉文件名非法字符与控制字符、折叠空白、去掉段尾 `.`/空格,并按上限截断。
|
|
23
|
+
*
|
|
24
|
+
* @param raw 原始片段(会话标题 / 会话 id)
|
|
25
|
+
* @param maxLen 截断上限(字符)
|
|
26
|
+
* @returns 可安全用作单级目录名的片段;全部被清空时返回空串
|
|
27
|
+
*/
|
|
28
|
+
function cleanSegment(raw, maxLen) {
|
|
29
|
+
const s = String(raw ?? "")
|
|
30
|
+
.replace(WHITESPACE_RUN, " ")
|
|
31
|
+
.replace(SEGMENT_FORBIDDEN, "")
|
|
32
|
+
.replace(WHITESPACE_RUN, " ")
|
|
33
|
+
.trim()
|
|
34
|
+
.replace(TRAILING_DOTS, "");
|
|
35
|
+
return s.slice(0, maxLen);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 会话标题 → `<sname>` 路径段:去掉 `\ / : * ? " < > |` 与控制字符,折叠空白,
|
|
39
|
+
* 段尾 `.`/空格清理,截断到 {@link SNAME_MAX_LEN} 字符。
|
|
40
|
+
*
|
|
41
|
+
* @param raw 会话标题(可为空)
|
|
42
|
+
* @returns 安全化后的片段;全空返回空串(调用方回退 `<sid>`)
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeSessionName(raw) {
|
|
45
|
+
return cleanSegment(raw, SNAME_MAX_LEN);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 展开下载目录模板。
|
|
49
|
+
*
|
|
50
|
+
* 支持占位符 `<cache>` / `<profile>` / `<sid>` / `<sname>`;`<sname>` 为空时回退 `<sid>`,
|
|
51
|
+
* 两者都为空时回退 `default`(与 Rust 侧兜底一致)。返回值**原样拼接**、不 resolve,
|
|
52
|
+
* 绝对/相对由配置决定(Rust 只接受绝对路径,非法值会被它拒绝并回退默认)。
|
|
53
|
+
*
|
|
54
|
+
* @param template 模板(可来自配置 `downloadDir` 或 env `BT_DOWNLOAD_DIR`)
|
|
55
|
+
* @param vars 占位符取值
|
|
56
|
+
* @returns 展开后的目录字符串
|
|
57
|
+
*/
|
|
58
|
+
export function expandDownloadDir(template, vars) {
|
|
59
|
+
const sid = cleanSegment(vars.sid, SID_MAX_LEN);
|
|
60
|
+
const sname = sanitizeSessionName(vars.sessionName) || sid || "default";
|
|
61
|
+
return String(template ?? "")
|
|
62
|
+
.split("<cache>").join(vars.cacheDir)
|
|
63
|
+
.split("<profile>").join(cleanSegment(vars.profile, SNAME_MAX_LEN) || "default")
|
|
64
|
+
.split("<sid>").join(sid || "default")
|
|
65
|
+
.split("<sname>").join(sname);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* `/api/downloads` 请求体:只放实际给出的字段(未传的不下发,交给 shell 默认)。
|
|
69
|
+
*
|
|
70
|
+
* `delete` 与 `clear`/`cancel` 互斥语义由 shell 保证(`delete` 独占:只删这一条)。
|
|
71
|
+
*
|
|
72
|
+
* @param a 已解析命令参数(`limit` / `clear` / `cancel` / `delete`)
|
|
73
|
+
* @returns 请求体对象
|
|
74
|
+
*/
|
|
75
|
+
export function buildDownloadsPayload(a) {
|
|
76
|
+
const p = {};
|
|
77
|
+
if (a?.limit !== undefined && a?.limit !== "")
|
|
78
|
+
p.limit = a.limit;
|
|
79
|
+
if (a?.clear === true)
|
|
80
|
+
p.clear = true;
|
|
81
|
+
const cancel = typeof a?.cancel === "string" ? a.cancel.trim() : "";
|
|
82
|
+
if (cancel)
|
|
83
|
+
p.cancel = cancel;
|
|
84
|
+
const del = typeof a?.delete === "string" ? a.delete.trim() : "";
|
|
85
|
+
if (del)
|
|
86
|
+
p.delete = del;
|
|
87
|
+
return p;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* `/api/download-dir` 请求体:给了 `--set`(哪怕空串)就下发 `set`,交由 shell 校验并报错,
|
|
91
|
+
* 不在插件侧静默降级成「查询」。
|
|
92
|
+
*
|
|
93
|
+
* @param a 已解析命令参数(`set`)
|
|
94
|
+
* @returns 请求体对象
|
|
95
|
+
*/
|
|
96
|
+
export function buildDownloadDirPayload(a) {
|
|
97
|
+
if (typeof a?.set === "string")
|
|
98
|
+
return { set: a.set };
|
|
99
|
+
return {};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* `--limit` 合法性:只接受正整数;未给出返回 null。
|
|
103
|
+
*
|
|
104
|
+
* @param raw 解析后的 limit(parseArgs 已把数字 flag 转成 number)
|
|
105
|
+
* @returns 非法时返回原因码 `invalid`,合法/未给出返回 null
|
|
106
|
+
*/
|
|
107
|
+
export function downloadsLimitIssue(raw) {
|
|
108
|
+
if (raw === undefined || raw === null || raw === "")
|
|
109
|
+
return null;
|
|
110
|
+
const n = typeof raw === "number" ? raw : Number(String(raw).trim());
|
|
111
|
+
if (!Number.isInteger(n) || n <= 0)
|
|
112
|
+
return "invalid";
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* 字节数 → 紧凑文本(`0B` / `640KB` / `1.2MB` / `12MB`)。
|
|
117
|
+
*
|
|
118
|
+
* @param bytes 字节数(非有限或 ≤0 均按 `0B`)
|
|
119
|
+
* @returns 带单位的简短文本
|
|
120
|
+
*/
|
|
121
|
+
export function formatBytes(bytes) {
|
|
122
|
+
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
123
|
+
if (!Number.isFinite(bytes) || bytes <= 0)
|
|
124
|
+
return "0B";
|
|
125
|
+
let value = bytes;
|
|
126
|
+
let unit = 0;
|
|
127
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
128
|
+
value /= 1024;
|
|
129
|
+
unit += 1;
|
|
130
|
+
}
|
|
131
|
+
// 一位小数后去掉多余的 .0(3 MiB → "3MB",1.25 MiB → "1.3MB")
|
|
132
|
+
const rounded = Math.round(value * 10) / 10;
|
|
133
|
+
const text = value >= 10 || unit === 0 ? String(Math.round(value)) : String(rounded);
|
|
134
|
+
return `${text}${units[unit]}`;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* 目录尾段(组标题用):去掉尾随分隔符后取最后一段;根路径(如 `C:\`、`/`)原样回显。
|
|
138
|
+
*
|
|
139
|
+
* @param dir 目录路径
|
|
140
|
+
* @returns 尾段名
|
|
141
|
+
*/
|
|
142
|
+
export function dirTail(dir) {
|
|
143
|
+
const raw = String(dir ?? "");
|
|
144
|
+
const parts = raw.replace(/[\\/]+$/, "").split(/[\\/]/);
|
|
145
|
+
return parts[parts.length - 1] || raw || "?";
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* 来源主机:解析失败时返回空串(不显示原始 URL)。
|
|
149
|
+
*
|
|
150
|
+
* @param url 下载来源 URL
|
|
151
|
+
* @returns host[:port],解析失败为空串
|
|
152
|
+
*/
|
|
153
|
+
export function hostOf(url) {
|
|
154
|
+
try {
|
|
155
|
+
return new URL(String(url)).host;
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return "";
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* 单条下载的行文本:`文件名 已收/总量 状态[ 百分比|不确定] 来源host[ — 错误]`。
|
|
163
|
+
*
|
|
164
|
+
* @param item 下载记录
|
|
165
|
+
* @param labels 状态名 / 不确定标注文案
|
|
166
|
+
* @returns 单行文本(不含缩进)
|
|
167
|
+
*/
|
|
168
|
+
export function formatDownloadRow(item, labels) {
|
|
169
|
+
const total = Number(item.totalBytes) || 0;
|
|
170
|
+
const received = Number(item.receivedBytes) || 0;
|
|
171
|
+
const size = total > 0 ? `${formatBytes(received)}/${formatBytes(total)}` : formatBytes(received);
|
|
172
|
+
const state = labels.states[item.state] ?? String(item.state);
|
|
173
|
+
// 进行中才给进度:总量已知给百分比,未知如实标「不确定」,不假装 0%
|
|
174
|
+
const progress = item.state === "progress"
|
|
175
|
+
? ` ${total > 0 ? `${Math.min(100, Math.round((received / total) * 100))}%` : labels.unknownSize}`
|
|
176
|
+
: "";
|
|
177
|
+
const name = item.filename || item.path || item.id;
|
|
178
|
+
const host = hostOf(item.url);
|
|
179
|
+
const err = item.state === "failed" && item.error ? ` — ${item.error}` : "";
|
|
180
|
+
return [name, size, `${state}${progress}`, host].filter((s) => s !== "").join(" ") + err;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* 整个列表的文本:按目录分组,组标题 `目录尾段 (n)`,组内每行缩进两格。
|
|
184
|
+
*
|
|
185
|
+
* @param data `/api/downloads` 响应体(可能为空/缺字段)
|
|
186
|
+
* @param labels 文案
|
|
187
|
+
* @returns 多行文本;无记录时返回 `labels.empty`
|
|
188
|
+
*/
|
|
189
|
+
export function formatDownloads(data, labels) {
|
|
190
|
+
const groups = data && Array.isArray(data.groups) ? data.groups : [];
|
|
191
|
+
const lines = [];
|
|
192
|
+
for (const group of groups) {
|
|
193
|
+
const items = Array.isArray(group?.items) ? group.items : [];
|
|
194
|
+
lines.push(`${dirTail(group?.dir ?? "")} (${items.length})`);
|
|
195
|
+
for (const item of items)
|
|
196
|
+
lines.push(` ${formatDownloadRow(item, labels)}`);
|
|
197
|
+
}
|
|
198
|
+
return lines.length > 0 ? lines.join("\n") : labels.empty;
|
|
199
|
+
}
|