@xiaoqiong0v0/opencode-browser-tool 1.2.1 → 1.4.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 +16 -4
- package/dist/binary.js +8 -7
- package/dist/client.js +124 -32
- package/dist/index.js +167 -63
- package/dist/logger.js +6 -0
- package/dist/notify-server.js +53 -0
- package/dist/session-id.js +47 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,6 +30,8 @@ sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**
|
|
|
30
30
|
- 其它平台:暂不提供预编译,请用 `BT_SHELL_PATH` 指定自行构建的二进制
|
|
31
31
|
|
|
32
32
|
> 代理:下载优先调用系统 `curl`(自动遵循 `HTTPS_PROXY`/`HTTP_PROXY`/`NO_PROXY`);无 curl 时回退 Node `fetch`。
|
|
33
|
+
>
|
|
34
|
+
> **本地开发/调试**:插件优先使用本地 Rust 构建(按 opencode 传入的目录定位 `rust/target/release`,也支持 `CARGO_TARGET_DIR`、源码树的 `<install>/../rust/...` 与 `BT_SHELL_PATH`);选中的路径与来源会写进日志 `Shell binary: <path> (source=local-dev|env|cargo-target-dir|download-cache)`;找不到时自动回落下载缓存(普通用户不受影响)。
|
|
33
35
|
|
|
34
36
|
## 版本与产物策略
|
|
35
37
|
|
|
@@ -62,6 +64,7 @@ sha256 校验(**幂等**:sha 与当前 release 期望值一致即跳过;**
|
|
|
62
64
|
- `BT_SHELL_NO_DOWNLOAD` — 设为 `1` 时不自动下载(状态 `disabled`;需自行放置二进制或配合 `BT_SHELL_PATH`)
|
|
63
65
|
- `BT_SHELL_DOWNLOAD_BASE` — 覆盖下载根(默认 GitHub Release `https://github.com/xiaoqiong0v0/opencode-browser-tool/releases/download`),可指向镜像/自建
|
|
64
66
|
- `BT_SHELL_VERSION` — 显式指定**二进制发布版本**(形如 `1.2.0`,即 `x.Y.0` 的 Release;**原样使用、不做归 0 推导**;不设时由插件版本自动推导)
|
|
67
|
+
- `BT_SHELL_NOTIFY_URL` — 插件通知地址(**推送式投递**;一般由插件自动通过 `--notify-url` / `/api/notify-url` 设置,仅在手动启动 shell 时需自行指定)
|
|
65
68
|
|
|
66
69
|
> **附着模式 vs 启动模式**:设置了 `BT_SHELL_URL`(优先)或 `BT_SHELL_PORT` 时进入附着模式——插件**不 spawn** 任何进程,直接连接该地址的外部 shell;两者都未设置时按启动模式 spawn 本地二进制(`BT_SHELL_PATH` 可覆盖查找路径)。附着模式下 `bt_close` 只关闭浏览器窗口并断开连接,**不会**结束外部 shell 进程(进程不归插件管理)。
|
|
67
70
|
|
|
@@ -145,7 +148,7 @@ opencode(Bun)
|
|
|
145
148
|
| `bt_click_and_switch_tab` | `selector`(string) 必填 | 点击元素;若触发新标签则自动切换,返回当前 URL |
|
|
146
149
|
| `bt_iframe_click` | `iframeSelector`, `selector`(string) 必填 | 在 iframe 中点击(仅同源可访问) |
|
|
147
150
|
| `bt_iframe_fill` | `iframeSelector`, `selector`, `value`(string) 必填 | 在 iframe 中输入(仅同源可访问) |
|
|
148
|
-
| `bt_get_browser_status` | 无 |
|
|
151
|
+
| `bt_get_browser_status` | 无 | **纯查询、不启动浏览器**:运行中返回 open/url/title/tabs 数量;未运行时返回未运行提示 + bt-shell 二进制状态(下载中/就绪/失败/禁用) |
|
|
149
152
|
| `bt_list_tabs` | 无 | 列出标签页(索引+URL) |
|
|
150
153
|
| `bt_switch_tab` | `index`(number) 必填 | 按位置(0 起)切换标签 |
|
|
151
154
|
| `bt_new_tab` | `url`(string) 必填 | 新建独立标签页(真多标签)并导航 |
|
|
@@ -163,8 +166,8 @@ opencode(Bun)
|
|
|
163
166
|
| `bt_expect_response` | `url`(string) 必填 | 记录期望匹配的响应模式,清空响应历史后重新捕获 |
|
|
164
167
|
| `bt_assert_response` | `id`(string) 必填 | 断言是否存在匹配的响应(返回 `url` + `status` 码) |
|
|
165
168
|
| `bt_get_accessibility_tree` | `selector`, `maxDepth`(number) | 返回页面可访问性树(role/name/value 嵌套结构) |
|
|
166
|
-
| `bt_list_records` | 无 |
|
|
167
|
-
| `bt_read_record_content` | `id`(number) 必填 |
|
|
169
|
+
| `bt_list_records` | 无 | 列出批注/截图记录(索引/标签/说明;截图带 `+img`,已发送带 `[sent]`) |
|
|
170
|
+
| `bt_read_record_content` | `id`(number) 必填 | 读取单条记录详情(截图附带图片大小与落盘路径) |
|
|
168
171
|
|
|
169
172
|
## 设备预设
|
|
170
173
|
|
|
@@ -186,7 +189,7 @@ opencode(Bun)
|
|
|
186
189
|
- **批注模式** — 悬停高亮元素(覆盖层自绘),点击元素弹出输入框填写说明;引擎层拦截,弹框/下拉类元素不失焦
|
|
187
190
|
- **截图模式** — 点击立即截全屏;也可进入截图模式后拖动框选区域(选区可拖拽手柄调整大小),保存时可按需裁剪(遮罩式选区,默认整图,双击还原)
|
|
188
191
|
- **记录列表** — 面板「AI 功能」区:批注/截图记录卡片(截图带缩略图),显示所属标签 URL 与说明
|
|
189
|
-
- **发送** — 面板底部「发送」按钮:所有记录(批注文字 + 截图图片)推送到 opencode
|
|
192
|
+
- **发送** — 面板底部「发送」按钮:所有记录(批注文字 + 截图图片)推送到 opencode 对话;发送后**面板列表清空**(与旧 Playwright 工具一致,仅列表为空),但**记录本身保留**并标记 `[sent]`(`bt_list_records` 仍可读取,截图也可通过 `bt_read_record_content` 取到)。投递为**推送式**:shell 发送后主动通知插件(`POST /notify`),插件收到即拉取并推送到对话(无轮询、无 2s 延迟)
|
|
190
193
|
- 批注和截图**必须填写说明**才能保存/发送,否则弹出提示
|
|
191
194
|
|
|
192
195
|
面板「配置」区:外观主题(跟随系统/浅色/深色)、设备预设下拉(等价 `bt_set_device`)、开发者工具按钮(等价 `bt_devtools`)。
|
|
@@ -225,6 +228,15 @@ cd rust && cargo build
|
|
|
225
228
|
npm run build
|
|
226
229
|
```
|
|
227
230
|
|
|
231
|
+
## 日志
|
|
232
|
+
|
|
233
|
+
插件侧统一使用公共包 `@xiaoqiong0v0/opencode-plugin-logger`,项目内由 `src/logger.ts` 导出共用实例。日志写入
|
|
234
|
+
`~/.opencode/plugins-log/YYYYMMDD.log`,行格式 `[时间] [级别] browser-tool <内容>`;需在
|
|
235
|
+
`~/.config/opencode/plugin-logger.jsonc` 设 `"enabled": true`(默认关闭)。
|
|
236
|
+
|
|
237
|
+
> **插件侧禁止用 `console.*` 往 stdout/stderr 打日志**——那会污染 opencode TUI。`src/**` 内的 `console.*` 仅允许出现在独立 CLI 的 `isMain` 守卫内(`node dist/binary.js` 直接运行时)。
|
|
238
|
+
> Rust 侧(`bt-shell`)的 `println!`/`eprintln!` 默认会被 spawn 管道吞掉、不可见;插件在启动 shell 时把其 stdout/stderr **转发进 logger**,因此 Rust 日志同样能在上述文件中看到。
|
|
239
|
+
|
|
228
240
|
## 文档
|
|
229
241
|
|
|
230
242
|
- [docs/v5-tauri-architecture.md](./docs/v5-tauri-architecture.md) — V5 当前架构
|
package/dist/binary.js
CHANGED
|
@@ -20,6 +20,7 @@ import { chmodSync, closeSync, createWriteStream, existsSync, mkdirSync, openSyn
|
|
|
20
20
|
import { dirname, resolve } from "path";
|
|
21
21
|
import { fileURLToPath, pathToFileURL } from "url";
|
|
22
22
|
import { getPluginDataDir } from "./config/index.js";
|
|
23
|
+
import { log } from "./logger.js";
|
|
23
24
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
24
25
|
/** 默认下载根(不含 `/v<version>/<asset>`),可用 BT_SHELL_DOWNLOAD_BASE 覆盖 */
|
|
25
26
|
const DEFAULT_DOWNLOAD_BASE = "https://github.com/xiaoqiong0v0/opencode-browser-tool/releases/download";
|
|
@@ -289,7 +290,7 @@ function migrateLegacyDirs(info, finalPath, expected, sourceUrl) {
|
|
|
289
290
|
.map((e) => resolve(dataDir, e.name));
|
|
290
291
|
if (legacyDirs.length === 0)
|
|
291
292
|
return;
|
|
292
|
-
|
|
293
|
+
log.info(`[bt-shell][migrate] dry-run 旧版本目录清单: ${legacyDirs.join(", ")}`);
|
|
293
294
|
const newValid = existsSync(finalPath) && sha256File(finalPath) === expected;
|
|
294
295
|
if (!newValid) {
|
|
295
296
|
for (const dir of legacyDirs) {
|
|
@@ -298,7 +299,7 @@ function migrateLegacyDirs(info, finalPath, expected, sourceUrl) {
|
|
|
298
299
|
if (existsSync(cand) && sha256File(cand) === expected) {
|
|
299
300
|
mkdirSync(dirname(finalPath), { recursive: true });
|
|
300
301
|
renameSync(cand, finalPath); // 同盘 rename
|
|
301
|
-
|
|
302
|
+
log.info(`[bt-shell][migrate] moved ${cand} -> ${finalPath}`);
|
|
302
303
|
break;
|
|
303
304
|
}
|
|
304
305
|
}
|
|
@@ -308,15 +309,15 @@ function migrateLegacyDirs(info, finalPath, expected, sourceUrl) {
|
|
|
308
309
|
}
|
|
309
310
|
}
|
|
310
311
|
else {
|
|
311
|
-
|
|
312
|
+
log.info(`[bt-shell][migrate] 新路径已有合法文件,保留 ${finalPath}`);
|
|
312
313
|
}
|
|
313
314
|
for (const dir of legacyDirs) {
|
|
314
315
|
try {
|
|
315
316
|
rmSync(dir, { recursive: true, force: true });
|
|
316
|
-
|
|
317
|
+
log.info(`[bt-shell][migrate] removed ${dir}`);
|
|
317
318
|
}
|
|
318
319
|
catch (e) {
|
|
319
|
-
|
|
320
|
+
log.error(`[bt-shell][migrate] remove failed ${dir}: ${errMsg(e)}`);
|
|
320
321
|
}
|
|
321
322
|
}
|
|
322
323
|
if (existsSync(finalPath) && sha256File(finalPath) === expected) {
|
|
@@ -345,10 +346,10 @@ function ensureSidecar(finalPath, info, sha256, sourceUrl, extra) {
|
|
|
345
346
|
sourceUrl,
|
|
346
347
|
};
|
|
347
348
|
writeFileSync(sidecarPath, JSON.stringify(version, null, 2), "utf-8");
|
|
348
|
-
|
|
349
|
+
log.info(`[bt-shell] 写入版本旁文件 ${sidecarPath}${extra ? ` (${extra})` : ""}`);
|
|
349
350
|
}
|
|
350
351
|
catch (e) {
|
|
351
|
-
|
|
352
|
+
log.error(`[bt-shell] 写入版本旁文件失败: ${errMsg(e)}`);
|
|
352
353
|
}
|
|
353
354
|
}
|
|
354
355
|
// ---- 下载实现:curl 优先(自动遵循系统代理),回退 fetch ----
|
package/dist/client.js
CHANGED
|
@@ -2,38 +2,52 @@ import { spawn } from "child_process";
|
|
|
2
2
|
import { resolve, dirname } from "path";
|
|
3
3
|
import { existsSync } from "fs";
|
|
4
4
|
import { fileURLToPath } from "url";
|
|
5
|
-
import
|
|
5
|
+
import { log } from "./logger.js";
|
|
6
|
+
import { getNotifyUrl } from "./notify-server.js";
|
|
6
7
|
import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
|
|
7
8
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
8
9
|
/** 就绪轮询超时(ms) */
|
|
9
10
|
const READY_TIMEOUT_MS = 20000;
|
|
10
11
|
/** 就绪轮询间隔(ms) */
|
|
11
12
|
const READY_POLL_INTERVAL_MS = 300;
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
/** opencode 应用/项目目录(插件初始化与工具上下文提供);用于定位本地 Rust 开发构建 */
|
|
14
|
+
let appDirectory = "";
|
|
15
|
+
/** 记录 opencode 目录(插件初始化 / 工具调用时调用) */
|
|
16
|
+
export function setAppDirectory(dir) {
|
|
17
|
+
if (dir)
|
|
18
|
+
appDirectory = dir;
|
|
19
|
+
}
|
|
20
|
+
// Rust 二进制查找:优先级 BT_SHELL_PATH → 本地开发构建(含 opencode 应用目录)→ 下载缓存(binary.ts)
|
|
21
|
+
// 注意:用 `.tmp/publish-local.ps1` 覆盖到 ~/.cache/opencode/packages/... 后,插件 dist 的相对路径
|
|
22
|
+
// (`<install>/../rust/...`)已指向缓存目录而非仓库 → 必须借助 opencode 传入的 directory 定位本地构建。
|
|
23
|
+
// 导出仅供自验/单测直接调用。
|
|
24
|
+
export function resolveShellBinary() {
|
|
14
25
|
const platform = process.platform === "win32" ? "win-x64" : "linux-x64";
|
|
15
26
|
const bin = process.platform === "win32" ? "bt-shell.exe" : "bt-shell";
|
|
16
27
|
// 1) 显式指定:最优先(即使文件暂不存在也返回,由 startService 给出明确错误)
|
|
17
28
|
const envPath = process.env.BT_SHELL_PATH;
|
|
18
29
|
if (envPath)
|
|
19
|
-
return envPath;
|
|
20
|
-
// 2) 本地开发构建(保持开发者流程不变)
|
|
30
|
+
return { path: envPath, source: "env" };
|
|
21
31
|
const cargoTargetDir = process.env.CARGO_TARGET_DIR;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
resolve(
|
|
26
|
-
resolve(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
// 2) 本地开发构建优先(开发者/源码树):含 opencode 应用目录的多种可能布局
|
|
33
|
+
const candidates = [];
|
|
34
|
+
if (appDirectory) {
|
|
35
|
+
candidates.push([resolve(appDirectory, "rust", "target", "release", bin), "local-dev"], // dir = 仓库根
|
|
36
|
+
[resolve(appDirectory, "target", "release", bin), "local-dev"], // dir = rust/
|
|
37
|
+
[resolve(appDirectory, "..", "rust", "target", "release", bin), "local-dev"], // dir = 仓库子目录
|
|
38
|
+
[resolve(appDirectory, "rust", "target", "debug", bin), "local-dev"], [resolve(appDirectory, "target", "debug", bin), "local-dev"], [resolve(appDirectory, "..", "rust", "target", "debug", bin), "local-dev"]);
|
|
39
|
+
}
|
|
40
|
+
candidates.push(
|
|
41
|
+
// 3) 源码树开发(插件直接从仓库 dist 加载时):<install>/../rust/...
|
|
42
|
+
[resolve(__dirname, "..", "rust", "target", "release", bin), "local-dev"], [resolve(__dirname, "..", "rust", "target", "debug", bin), "local-dev"],
|
|
43
|
+
// 4) 自定义 CARGO_TARGET_DIR(WSL 内构建时)
|
|
44
|
+
[cargoTargetDir ? resolve(cargoTargetDir, "release", bin) : undefined, "cargo-target-dir"], [cargoTargetDir ? resolve(cargoTargetDir, "debug", bin) : undefined, "cargo-target-dir"], [resolve(__dirname, "bin", `bt-shell-${platform}.exe`), "local-dev"], [resolve(__dirname, "bin", `bt-shell-${platform}`), "local-dev"]);
|
|
45
|
+
for (const [p, source] of candidates) {
|
|
46
|
+
if (p && existsSync(p))
|
|
47
|
+
return { path: p, source };
|
|
34
48
|
}
|
|
35
|
-
//
|
|
36
|
-
return cachedBinaryPath();
|
|
49
|
+
// 5) 下载缓存(未下载时由 startService 先 ensureBinary)
|
|
50
|
+
return { path: cachedBinaryPath(), source: "download-cache" };
|
|
37
51
|
}
|
|
38
52
|
/** 解析附着模式目标地址:BT_SHELL_URL 优先,其次 BT_SHELL_PORT;均未设置返回 null */
|
|
39
53
|
function resolveAttachBaseUrl() {
|
|
@@ -64,6 +78,12 @@ export function setUserDataDir(dir) {
|
|
|
64
78
|
if (serviceConfig)
|
|
65
79
|
serviceConfig.userDataDir = dir;
|
|
66
80
|
}
|
|
81
|
+
/** 服务就绪回调(插件注册:做一次初始 drain) */
|
|
82
|
+
let serviceReadyHandler = null;
|
|
83
|
+
/** 注册服务就绪回调(spawn/附着成功且注册 notify-url 之后调用一次) */
|
|
84
|
+
export function setServiceReadyHandler(cb) {
|
|
85
|
+
serviceReadyHandler = cb;
|
|
86
|
+
}
|
|
67
87
|
/** 懒启动服务:未启动则 spawn bt-shell(弹窗);已启动直接返回;并发时复用同一个 Promise */
|
|
68
88
|
export async function ensureService() {
|
|
69
89
|
if (serviceReady)
|
|
@@ -76,16 +96,45 @@ export async function ensureService() {
|
|
|
76
96
|
starting = attachToService(attachUrl).finally(() => {
|
|
77
97
|
starting = null;
|
|
78
98
|
});
|
|
79
|
-
return starting;
|
|
80
99
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
starting =
|
|
87
|
-
|
|
88
|
-
|
|
100
|
+
else {
|
|
101
|
+
// 启动模式:懒启动本地 shell
|
|
102
|
+
const cfg = serviceConfig;
|
|
103
|
+
if (!cfg)
|
|
104
|
+
throw new Error("Service not configured");
|
|
105
|
+
starting = startService(cfg.nodePath, cfg.browsersPath, cfg.sessionIsolation, cfg.browserType, cfg.userDataDir).finally(() => {
|
|
106
|
+
starting = null;
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
await starting;
|
|
110
|
+
// 服务就绪:把插件通知地址注册给 shell(推送式投递;附着模式同样走这里)
|
|
111
|
+
await registerNotifyUrl();
|
|
112
|
+
try {
|
|
113
|
+
serviceReadyHandler?.();
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
log.error("[notify] service-ready handler failed", e);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** 把插件通知地址注册给 shell(/api/notify-url);直接 fetch,避免 callApi 触发 ensureService 递归 */
|
|
120
|
+
async function registerNotifyUrl() {
|
|
121
|
+
const url = getNotifyUrl();
|
|
122
|
+
if (!url || !serviceBaseUrl)
|
|
123
|
+
return;
|
|
124
|
+
try {
|
|
125
|
+
const res = await fetch(`${serviceBaseUrl}/api/notify-url`, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: { "Content-Type": "application/json" },
|
|
128
|
+
body: JSON.stringify({ url }),
|
|
129
|
+
});
|
|
130
|
+
if (res.ok)
|
|
131
|
+
log.info(`[notify] notify-url registered: ${url}`);
|
|
132
|
+
else
|
|
133
|
+
log.error(`[notify] register failed: HTTP ${res.status}`);
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
log.error("[notify] register failed", e);
|
|
137
|
+
}
|
|
89
138
|
}
|
|
90
139
|
async function callApi(path, body, sessionId) {
|
|
91
140
|
// 懒启动:首次调用工具时自动打开窗口
|
|
@@ -123,7 +172,6 @@ async function waitForReady(baseUrl, timeoutMessage) {
|
|
|
123
172
|
}
|
|
124
173
|
/** 附着到外部已运行的 shell(不 spawn):等待就绪后记录 base URL */
|
|
125
174
|
async function attachToService(baseUrl) {
|
|
126
|
-
const log = createLogger("opencode-browser-tool");
|
|
127
175
|
attachMode = true;
|
|
128
176
|
log.info(`Attaching to existing bt-shell at ${baseUrl} (no spawn)`);
|
|
129
177
|
await waitForReady(baseUrl, `External bt-shell not ready at ${baseUrl}. Check BT_SHELL_URL/BT_SHELL_PORT and that the shell is running.`);
|
|
@@ -132,9 +180,9 @@ async function attachToService(baseUrl) {
|
|
|
132
180
|
log.info(`Attached to existing bt-shell at ${baseUrl}`);
|
|
133
181
|
}
|
|
134
182
|
export async function startService(nodePath, browsersPath, sessionIsolation, browserType, userDataDir) {
|
|
135
|
-
const log = createLogger("opencode-browser-tool");
|
|
136
183
|
attachMode = false;
|
|
137
|
-
|
|
184
|
+
const resolved = resolveShellBinary();
|
|
185
|
+
let shell = resolved.path;
|
|
138
186
|
// 未就绪:先(有界)等待下载完成;失败/超时给出明确提示
|
|
139
187
|
if (!existsSync(shell)) {
|
|
140
188
|
if (process.env.BT_SHELL_PATH) {
|
|
@@ -146,6 +194,8 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
146
194
|
}
|
|
147
195
|
shell = st.path;
|
|
148
196
|
}
|
|
197
|
+
// 记录最终选中的二进制与来源,便于一眼判断用的是哪份(local-dev / env / download-cache …)
|
|
198
|
+
log.info(`Shell binary: ${shell} (source=${resolved.source})`);
|
|
149
199
|
// 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout)
|
|
150
200
|
const port = 18000 + Math.floor(Math.random() * 1000);
|
|
151
201
|
const args = ["--browsers-path", browsersPath || "", "--port", String(port)];
|
|
@@ -156,7 +206,21 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
156
206
|
// 多用户配置:userDataDir 指向独立 WebView2 用户数据目录
|
|
157
207
|
if (userDataDir)
|
|
158
208
|
args.push("--user-data-dir", userDataDir);
|
|
209
|
+
// 推送式投递:把插件本地通知地址传给 shell(亦可用 BT_SHELL_NOTIFY_URL;附着模式用 /api/notify-url 注册)
|
|
210
|
+
const notifyUrl = getNotifyUrl();
|
|
211
|
+
if (notifyUrl)
|
|
212
|
+
args.push("--notify-url", notifyUrl);
|
|
159
213
|
serviceProcess = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
214
|
+
// 把 shell 的 stdout/stderr 转发进共享日志:Rust 侧 println!/eprintln! 默认被管道吞掉(无人读取 → 日志永远看不到)
|
|
215
|
+
const forwardShell = (tag) => (chunk) => {
|
|
216
|
+
for (const line of chunk.toString().split(/\r?\n/)) {
|
|
217
|
+
const s = line.trim();
|
|
218
|
+
if (s)
|
|
219
|
+
log.info(`${tag} ${s}`);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
serviceProcess.stdout?.on("data", forwardShell("[shell:out]"));
|
|
223
|
+
serviceProcess.stderr?.on("data", forwardShell("[shell:err]"));
|
|
160
224
|
// 等待服务就绪(轮询端口)
|
|
161
225
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
162
226
|
await waitForReady(baseUrl, "Service timeout: bt-shell did not start. Build it with: cd rust && cargo build --release");
|
|
@@ -165,7 +229,6 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
165
229
|
log.info(`Shell service ready on port ${port} (${shell})`);
|
|
166
230
|
}
|
|
167
231
|
export async function stopService() {
|
|
168
|
-
const log = createLogger("opencode-browser-tool");
|
|
169
232
|
if (attachMode) {
|
|
170
233
|
// 附着模式:外部 shell 进程不归插件管,只清空本地状态
|
|
171
234
|
log.info("Detached from external bt-shell (process left running)");
|
|
@@ -189,6 +252,35 @@ export async function openWindow() {
|
|
|
189
252
|
export function isRunning() {
|
|
190
253
|
return serviceReady;
|
|
191
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* 纯查询:探测 shell 是否在运行,**绝不 spawn**。
|
|
257
|
+
* 仅在本进程已启动/附着(`serviceBaseUrl` 已知)时做一次短超时 HTTP 探测;否则返回 null。
|
|
258
|
+
* 用于 `get_browser_status` 这类只读命令,避免查询也弹出浏览器窗口。
|
|
259
|
+
*/
|
|
260
|
+
export async function probeStatus(timeoutMs = 1500) {
|
|
261
|
+
if (!serviceReady || !serviceBaseUrl)
|
|
262
|
+
return null;
|
|
263
|
+
const ac = new AbortController();
|
|
264
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
265
|
+
try {
|
|
266
|
+
const res = await fetch(`${serviceBaseUrl}/api/status`, {
|
|
267
|
+
method: "POST",
|
|
268
|
+
headers: { "Content-Type": "application/json" },
|
|
269
|
+
body: "{}",
|
|
270
|
+
signal: ac.signal,
|
|
271
|
+
});
|
|
272
|
+
if (!res.ok)
|
|
273
|
+
return null;
|
|
274
|
+
const json = await res.json();
|
|
275
|
+
return json?.success ? json.data : null;
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
192
284
|
function cmd(name) {
|
|
193
285
|
return (params, sessionId) => callApi(`/api/${name}`, params, sessionId);
|
|
194
286
|
}
|
package/dist/index.js
CHANGED
|
@@ -6,11 +6,12 @@ import { loadConfig, getConfig, getBrowsersDir, getProfilesDir, getProfileDir, g
|
|
|
6
6
|
import { registerLocale, t } from "./i18n/index.js";
|
|
7
7
|
import en from "./i18n/en.js";
|
|
8
8
|
import zh from "./i18n/zh.js";
|
|
9
|
-
import { configureService, setUserDataDir, ensureService, openWindow, isRunning, stopService, service } from "./client.js";
|
|
10
|
-
import {
|
|
9
|
+
import { configureService, setUserDataDir, setAppDirectory, setServiceReadyHandler, ensureService, openWindow, isRunning, stopService, service, probeStatus } from "./client.js";
|
|
10
|
+
import { startNotifyServer } from "./notify-server.js";
|
|
11
|
+
import { startDownload, getBinaryStatus, describeBinaryStatus } from "./binary.js";
|
|
11
12
|
import { tool } from "@opencode-ai/plugin";
|
|
12
|
-
import
|
|
13
|
-
|
|
13
|
+
import { log } from "./logger.js";
|
|
14
|
+
import { createSessionIDCache, extractSessionIDFromEvent } from "./session-id.js";
|
|
14
15
|
const _t = (k) => t(k);
|
|
15
16
|
/** 降级说明:服务端在无可信通道、退回 untrusted DOM/JS 时返回 degraded,统一在此追加标注 */
|
|
16
17
|
function degradedNote(r) {
|
|
@@ -54,7 +55,7 @@ const COMMANDS = {
|
|
|
54
55
|
upload_file: { usage: "--selector --filePath", descKey: "cli.cmd.upload_file", args: [{ flag: "selector" }, { flag: "filePath" }], run: async (a) => { await service.uploadFile(a); return "Uploaded"; } },
|
|
55
56
|
screenshot: { usage: "[--selector]", descKey: "cli.cmd.screenshot", args: [{ flag: "selector" }], run: async (a) => {
|
|
56
57
|
const r = await service.screenshot(a);
|
|
57
|
-
return { output: `Screenshot taken${a.selector ? ` (element: ${a.selector})` : " (full page)"}`, attachments: [{ type: "file", mime: r.mime || "image/png",
|
|
58
|
+
return { output: `Screenshot taken${a.selector ? ` (element: ${a.selector})` : " (full page)"}`, attachments: [{ type: "file", mime: r.mime || "image/png", url: `data:${r.mime || "image/png"};base64,${r.base64}` }] };
|
|
58
59
|
} },
|
|
59
60
|
evaluate: { usage: "--script", descKey: "cli.cmd.evaluate", args: [{ flag: "script" }], run: async (a) => JSON.stringify(await service.evaluate(a), null, 2) },
|
|
60
61
|
get_visible_text: { usage: "[--selector]", descKey: "cli.cmd.get_visible_text", args: [{ flag: "selector" }], run: async (a) => (await service.visibleText(a))?.text || "(no visible text)" },
|
|
@@ -91,7 +92,12 @@ const COMMANDS = {
|
|
|
91
92
|
iframe_click: { usage: "--iframeSelector --selector", descKey: "cli.cmd.iframe_click", args: [{ flag: "iframeSelector" }, { flag: "selector" }], run: async (a) => { const r = await service.iframeClick(a); return "Clicked in iframe" + degradedNote(r); } },
|
|
92
93
|
iframe_fill: { usage: "--iframeSelector --selector --value", descKey: "cli.cmd.iframe_fill", args: [{ flag: "iframeSelector" }, { flag: "selector" }, { flag: "value" }], run: async (a) => { const r = await service.iframeFill(a); return "Filled in iframe" + degradedNote(r); } },
|
|
93
94
|
get_browser_status: { usage: "", descKey: "cli.cmd.get_browser_status", run: async () => {
|
|
94
|
-
|
|
95
|
+
// 纯查询:不 spawn、不懒启动(未运行只提示,不弹窗)
|
|
96
|
+
const s = await probeStatus();
|
|
97
|
+
if (!s) {
|
|
98
|
+
const b = getBinaryStatus();
|
|
99
|
+
return `Browser is not running.\nbt-shell: ${describeBinaryStatus(b)}\n(执行任意其它工具会自动启动;也可用 open_window 显式启动)`;
|
|
100
|
+
}
|
|
95
101
|
if (s.installing && Object.keys(s.installing).length > 0)
|
|
96
102
|
return `Installing ${Object.entries(s.installing).map(([b, p]) => `${b} (${p})`).join(", ")}.`;
|
|
97
103
|
if (!s.open)
|
|
@@ -116,7 +122,7 @@ const COMMANDS = {
|
|
|
116
122
|
const records = await service.annotateRecords();
|
|
117
123
|
if (!records || !records.length)
|
|
118
124
|
return "(no records)";
|
|
119
|
-
return records.map((r) => { const rect = r.rect ? ` rect=(${r.rect[0]},${r.rect[1]},${r.rect[2]},${r.rect[3]})` : ""; return `[${r.index}] ${r.selector}${rect}${r.note ? ` note="${r.note}"` : ""}`; }).join("\n");
|
|
125
|
+
return records.map((r) => { const rect = r.rect ? ` rect=(${r.rect[0]},${r.rect[1]},${r.rect[2]},${r.rect[3]})` : ""; const img = r.image ? " +img" : ""; const sent = r.sent ? " [sent]" : ""; return `[${r.index}] ${r.selector}${rect}${img}${sent}${r.note ? ` note="${r.note}"` : ""}`; }).join("\n");
|
|
120
126
|
}
|
|
121
127
|
catch {
|
|
122
128
|
return "(no records)";
|
|
@@ -126,7 +132,12 @@ const COMMANDS = {
|
|
|
126
132
|
const rec = (records || []).find((r) => r.index === a.id);
|
|
127
133
|
if (!rec)
|
|
128
134
|
return `(record #${a.id} not found)`;
|
|
129
|
-
|
|
135
|
+
let img = "";
|
|
136
|
+
if (rec.image) {
|
|
137
|
+
const p = saveShotImage(log, rec.index, rec.image);
|
|
138
|
+
img = `\nimage: ${Math.round(rec.image.length / 1024)}KB base64` + (p ? ` (saved: ${p})` : "");
|
|
139
|
+
}
|
|
140
|
+
return `#${rec.index} ${rec.selector}\nrect: ${JSON.stringify(rec.rect)}${img}\nnote: ${rec.note || "(none)"}`;
|
|
130
141
|
}
|
|
131
142
|
catch {
|
|
132
143
|
return "(no records)";
|
|
@@ -248,7 +259,11 @@ function splitCsvLine(line) {
|
|
|
248
259
|
out.push(cur);
|
|
249
260
|
return out;
|
|
250
261
|
}
|
|
251
|
-
export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
262
|
+
export const opencodeBrowserTool = async ({ client, worktree, directory, serverUrl }) => {
|
|
263
|
+
// 插件上下文(仅用于诊断:定位 session.list() 为空时是哪个实例/目录)
|
|
264
|
+
pluginCtx = { directory: directory || "", worktree: worktree || "", serverUrl: serverUrl ? String(serverUrl) : "" };
|
|
265
|
+
// 供 resolveShellBinary 定位本地 Rust 构建(publish-local 到缓存目录后仍能找到仓库)
|
|
266
|
+
setAppDirectory(directory || "");
|
|
252
267
|
registerLocale("en", en);
|
|
253
268
|
registerLocale("zh", zh);
|
|
254
269
|
loadConfig(worktree);
|
|
@@ -266,20 +281,32 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
266
281
|
});
|
|
267
282
|
// 启动即后台下载 bt-shell(fire-and-forget:不阻塞启动,失败不抛出;状态见 getBinaryStatus)
|
|
268
283
|
startDownload();
|
|
269
|
-
//
|
|
270
|
-
|
|
284
|
+
// 事件驱动投递:插件本地监听 shell 通知(推送式,替代轮询)
|
|
285
|
+
setupAnnotateDelivery(client);
|
|
271
286
|
return {
|
|
272
287
|
event: async ({ event }) => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
288
|
+
// 缓存最近会话 id:这是投递批注最可靠的 sessionID 来源
|
|
289
|
+
if (event.type !== "session.deleted") {
|
|
290
|
+
sessionCache.updateFromEvent(event);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
const delId = extractSessionIDFromEvent(event);
|
|
294
|
+
if (delId) {
|
|
295
|
+
sessionCache.clearIf(delId);
|
|
276
296
|
try {
|
|
277
|
-
await service.closeSession({ _sessionId:
|
|
297
|
+
await service.closeSession({ _sessionId: delId });
|
|
278
298
|
}
|
|
279
299
|
catch { }
|
|
280
300
|
}
|
|
281
301
|
}
|
|
282
302
|
},
|
|
303
|
+
// 用户发消息 / 调工具时刷新当前会话 id(参考项目用 ctx.sessionID,此处为等价钩子来源)
|
|
304
|
+
"chat.message": async (input) => {
|
|
305
|
+
sessionCache.updateFromHookInput(input);
|
|
306
|
+
},
|
|
307
|
+
"tool.execute.before": async (input) => {
|
|
308
|
+
sessionCache.updateFromHookInput(input);
|
|
309
|
+
},
|
|
283
310
|
tool: filterDisabled({
|
|
284
311
|
bt_cli: tool({
|
|
285
312
|
description: _t("tool.cli.desc") + "\n" + DESC_INDEX,
|
|
@@ -330,7 +357,9 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
330
357
|
}
|
|
331
358
|
}
|
|
332
359
|
}
|
|
333
|
-
// 透传会话 ID(会话隔离用)
|
|
360
|
+
// 透传会话 ID(会话隔离用),并刷新钩子缓存(兜底:即使钩子未触发也能拿到 sid)
|
|
361
|
+
sessionCache.updateFromHookInput(context);
|
|
362
|
+
setAppDirectory(context?.directory || "");
|
|
334
363
|
params._sessionId = context?.sessionID || "";
|
|
335
364
|
try {
|
|
336
365
|
return await def.run(params);
|
|
@@ -347,6 +376,8 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
347
376
|
mode: tool.schema.enum(["simulate", "real"]).optional().describe(_t("tool.set_media_mode.arg.mode")),
|
|
348
377
|
},
|
|
349
378
|
async execute(a, context) {
|
|
379
|
+
sessionCache.updateFromHookInput(context);
|
|
380
|
+
setAppDirectory(context?.directory || "");
|
|
350
381
|
const r = await service.mediaMode({ ...a, _sessionId: context?.sessionID || "" });
|
|
351
382
|
return `Media mode: ${r.mode}`;
|
|
352
383
|
},
|
|
@@ -394,61 +425,134 @@ function filterDisabled(tools, disabled) {
|
|
|
394
425
|
* 注意:插件函数会随会话/切目录多次执行,轮询器必须进程级单例,
|
|
395
426
|
* 否则同一进程会累积多个 interval 空转(server 与 TUI 进程各一份,互不共享)
|
|
396
427
|
*/
|
|
397
|
-
let annotateTimer = null;
|
|
398
428
|
let annotateClient = null;
|
|
399
|
-
|
|
400
|
-
|
|
429
|
+
/** drain 进行中,避免并发重复投递 */
|
|
430
|
+
let draining = false;
|
|
431
|
+
/** 最近一次见到的会话 id 缓存(来自 event/chat.message/tool.execute.before 钩子) */
|
|
432
|
+
const sessionCache = createSessionIDCache();
|
|
433
|
+
/** 已记录过的 sid(避免重复刷屏) */
|
|
434
|
+
let lastLoggedSessionID = "";
|
|
435
|
+
/** 插件上下文(诊断用) */
|
|
436
|
+
let pluginCtx = { directory: "", worktree: "", serverUrl: "" };
|
|
437
|
+
/** 把截图 base64 落盘为临时 PNG,返回路径(失败返回 null);用于发送时保留图片与给出可读路径 */
|
|
438
|
+
function saveShotImage(log, index, b64) {
|
|
439
|
+
try {
|
|
440
|
+
const dir = resolve(getTmpDir());
|
|
441
|
+
mkdirSync(dir, { recursive: true });
|
|
442
|
+
const p = resolve(dir, `shot-${Date.now()}-${index}.png`);
|
|
443
|
+
writeFileSync(p, Buffer.from(b64, "base64"));
|
|
444
|
+
return p;
|
|
445
|
+
}
|
|
446
|
+
catch (e) {
|
|
447
|
+
log.error("save screenshot image failed", e);
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/** 事件驱动投递:插件本地监听 shell 通知(收到即 drain),不再 setInterval 轮询 */
|
|
452
|
+
function setupAnnotateDelivery(client) {
|
|
453
|
+
// 更新 client 引用(插件重载后使用最新 client)
|
|
401
454
|
annotateClient = client;
|
|
402
|
-
|
|
455
|
+
// 服务就绪时做一次 drain(覆盖"通知机制建立前 shell 已发送过"的窗口,幂等;含 shell 重启)
|
|
456
|
+
setServiceReadyHandler(() => {
|
|
457
|
+
void drainAnnotate();
|
|
458
|
+
});
|
|
459
|
+
// 启动监听并把地址交给 shell(spawn 时 --notify-url,就绪后 /api/notify-url 注册)
|
|
460
|
+
startNotifyServer(() => {
|
|
461
|
+
void drainAnnotate();
|
|
462
|
+
})
|
|
463
|
+
.then((p) => log.info(`[notify] listening 127.0.0.1:${p}/notify (event-driven; no polling)`))
|
|
464
|
+
.catch((e) => log.error("[notify] listen failed (only initial/service-ready drain available)", e));
|
|
465
|
+
// 插件启动时也 drain 一次(此时服务可能未起,isRunning() 会短路)
|
|
466
|
+
void drainAnnotate();
|
|
467
|
+
}
|
|
468
|
+
/** 拉取待发送记录并投递到当前会话(推送触发;空结果不记日志) */
|
|
469
|
+
async function drainAnnotate() {
|
|
470
|
+
if (draining)
|
|
403
471
|
return;
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
472
|
+
const c = annotateClient;
|
|
473
|
+
if (!c)
|
|
474
|
+
return;
|
|
475
|
+
// 服务未启动/已关闭:跳过(服务就绪或通知到达时会再次触发)
|
|
476
|
+
if (!isRunning())
|
|
477
|
+
return;
|
|
478
|
+
draining = true;
|
|
479
|
+
try {
|
|
480
|
+
// 观测钩子缓存:首次学到 sid 时记一次(证明 sid 来源可用)
|
|
481
|
+
const learned = sessionCache.get();
|
|
482
|
+
if (learned && learned !== lastLoggedSessionID) {
|
|
483
|
+
log.info(`[notify] hook-cache sid=${learned}`);
|
|
484
|
+
lastLoggedSessionID = learned;
|
|
485
|
+
}
|
|
486
|
+
const r = await service.annotateConsumeSent();
|
|
487
|
+
const records = r?.records || [];
|
|
488
|
+
if (records.length === 0)
|
|
489
|
+
return; // 空结果不刷屏
|
|
490
|
+
const imgInfo = records
|
|
491
|
+
.filter((x) => x.type === "screenshot" && x.image)
|
|
492
|
+
.map((x) => `#${x.index}:${x.image.length}B`);
|
|
493
|
+
log.info(`[drain] consume-sent -> ${records.length} record(s) ids=[${records.map((x) => x.index).join(",")}] images=[${imgInfo.join(",")}]`);
|
|
494
|
+
const lines = ["User annotated via panel:", ""];
|
|
495
|
+
for (const item of records) {
|
|
496
|
+
const label = item.type === "screenshot"
|
|
497
|
+
? `[#${item.index}] 截图${item.url ? ` @ ${item.url}` : ""}`
|
|
498
|
+
: `[#${item.index}] ${item.selector || "(no selector)"}${item.url ? ` @ ${item.url}` : ""}`;
|
|
499
|
+
lines.push(`- ${label}${item.note ? `: ${item.note}` : ""}`);
|
|
500
|
+
// 截图:落盘保留并写入文本路径。与参考实现(opencode-playwright-tool)一致 ——
|
|
501
|
+
// 图片**不经 session.prompt**(服务端对 image/* part 返回 400),而是走
|
|
502
|
+
// 「工具结果附件」(bt_screenshot)或「读记录返回缓存路径」(read_record_content)。
|
|
503
|
+
if (item.type === "screenshot" && item.image) {
|
|
504
|
+
const savedPath = saveShotImage(log, item.index, item.image);
|
|
505
|
+
if (savedPath)
|
|
506
|
+
lines.push(` (image saved: ${savedPath})`);
|
|
429
507
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
508
|
+
lines.push("");
|
|
509
|
+
}
|
|
510
|
+
const text = lines.join("\n");
|
|
511
|
+
// 取当前会话 id:优先用钩子缓存(参考项目 ctx.sessionID 的等价物),session.list() 仅兜底
|
|
512
|
+
let sid = sessionCache.get();
|
|
513
|
+
let source = "hook-cache";
|
|
514
|
+
let listLen = "-";
|
|
515
|
+
if (!sid) {
|
|
434
516
|
const sessions = await c.session.list();
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
517
|
+
listLen = Array.isArray(sessions?.data) ? sessions.data.length : sessions?.error ? "error" : "none";
|
|
518
|
+
log.info(`[drain] session.list raw=${JSON.stringify(sessions).slice(0, 400)}`);
|
|
519
|
+
sid = sessions?.data?.[0]?.id;
|
|
520
|
+
source = "client.session.list()[0]";
|
|
521
|
+
}
|
|
522
|
+
// 关键诊断:sid 来源/缓存值/list 长度/插件目录(定位"静默失败"断点)
|
|
523
|
+
log.info(`[drain] sid source=${source} cached=${sessionCache.get() || "(EMPTY)"} listLen=${listLen} ctx=${pluginCtx.directory || "(none)"} srv=${pluginCtx.serverUrl || "(none)"} sid=${sid ?? "(EMPTY)"}`);
|
|
524
|
+
if (!sid) {
|
|
525
|
+
const msg = "no session id (hook cache empty and session.list returned none)";
|
|
526
|
+
log.error(`[drain] ${msg}`, new Error(msg));
|
|
527
|
+
try {
|
|
528
|
+
await service.notify({ message: `发送失败: ${msg}`, type: "err" });
|
|
440
529
|
}
|
|
530
|
+
catch { }
|
|
531
|
+
return;
|
|
441
532
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
533
|
+
const send = (parts) => c.session.prompt({ path: { id: sid }, body: { noReply: false, parts } });
|
|
534
|
+
// 只发文本(参考实现同为纯文本;图片由工具附件/缓存路径交付,不在 prompt 里塞图片 part)
|
|
535
|
+
log.info(`[drain] prompt -> sid=${sid} parts=text-only textLen=${text.length}`);
|
|
536
|
+
const res = await send([{ type: "text", text }]);
|
|
537
|
+
const err = res?.error;
|
|
538
|
+
if (err) {
|
|
539
|
+
// 不再静默:写日志 + 页面通知(SDK 返回 {error} 不抛,必须显式检查)
|
|
540
|
+
log.error(`[drain] prompt FAILED sid=${sid}: ${JSON.stringify(err).slice(0, 300)}`, new Error("prompt error"));
|
|
541
|
+
try {
|
|
542
|
+
await service.notify({ message: `发送记录失败: ${JSON.stringify(err).slice(0, 180)}`, type: "err" });
|
|
543
|
+
}
|
|
544
|
+
catch { }
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
log.info(`[drain] prompt OK sid=${sid} delivered ${records.length} record(s)`);
|
|
446
548
|
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
549
|
+
}
|
|
550
|
+
catch (e) {
|
|
551
|
+
log.error("annotate drain error", e);
|
|
552
|
+
}
|
|
553
|
+
finally {
|
|
554
|
+
draining = false;
|
|
555
|
+
}
|
|
452
556
|
}
|
|
453
557
|
// Export default for npm loader
|
|
454
558
|
export default opencodeBrowserTool;
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// 共享日志模块:全局单例 logger,避免各文件重复创建(与 opencode-ssh-tool 的 src/log.ts 同构)
|
|
2
|
+
// 落盘约定由 @xiaoqiong0v0/opencode-plugin-logger 决定:
|
|
3
|
+
// ~/.opencode/plugins-log/<YYYYMMDD>.log,行格式 `[时间] [级别] browser-tool <内容>`
|
|
4
|
+
// 需在 ~/.config/opencode/plugin-logger.jsonc 里 `enabled: true` 才会写文件(默认 false)
|
|
5
|
+
import createLogger from "@xiaoqiong0v0/opencode-plugin-logger";
|
|
6
|
+
export const log = createLogger("browser-tool");
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// 插件侧通知监听:shell 发送记录后主动 POST /notify 到这里(推送式投递,替代轮询)。
|
|
2
|
+
// 仅绑定 127.0.0.1 + 随机空闲端口;端点只接收最小信息(count),大内容仍由插件走
|
|
3
|
+
// /api/annotate/consume-sent 拉取(drain)。
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
let server = null;
|
|
6
|
+
let port = 0;
|
|
7
|
+
let onNotify = null;
|
|
8
|
+
/** 启动监听(幂等);返回实际端口。onNotify 在收到 shell 通知时被调用 */
|
|
9
|
+
export async function startNotifyServer(handler) {
|
|
10
|
+
onNotify = handler;
|
|
11
|
+
if (server && port)
|
|
12
|
+
return port;
|
|
13
|
+
return new Promise((resolvePort, reject) => {
|
|
14
|
+
const srv = createServer((req, res) => {
|
|
15
|
+
if (req.method !== "POST" || !req.url || !req.url.startsWith("/notify")) {
|
|
16
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
17
|
+
res.end('{"ok":false}');
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
// 只读取/丢弃最小 payload,避免大内容经此通道
|
|
21
|
+
let bytes = 0;
|
|
22
|
+
req.on("data", (c) => {
|
|
23
|
+
bytes += c.length;
|
|
24
|
+
if (bytes > 4096)
|
|
25
|
+
req.destroy();
|
|
26
|
+
});
|
|
27
|
+
req.on("end", () => {
|
|
28
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
29
|
+
res.end('{"ok":true}');
|
|
30
|
+
try {
|
|
31
|
+
onNotify?.();
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// 忽略回调异常,不影响响应
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
srv.on("error", reject);
|
|
39
|
+
// 不阻塞插件进程退出
|
|
40
|
+
if (typeof srv.unref === "function")
|
|
41
|
+
srv.unref();
|
|
42
|
+
srv.listen(0, "127.0.0.1", () => {
|
|
43
|
+
server = srv;
|
|
44
|
+
const addr = srv.address();
|
|
45
|
+
port = typeof addr === "object" && addr ? addr.port : 0;
|
|
46
|
+
resolvePort(port);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** 当前通知地址(shell 用它 POST);未就绪返回 null */
|
|
51
|
+
export function getNotifyUrl() {
|
|
52
|
+
return server && port ? `http://127.0.0.1:${port}/notify` : null;
|
|
53
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// 会话 id 提取与缓存(纯逻辑,便于单测):投递批注时必须拿到"当前会话 id"。
|
|
2
|
+
// 可靠来源是插件钩子上下文(等价于参考项目 opencode-playwright-tool 的 ctx.sessionID),
|
|
3
|
+
// 而不是 client.session.list() —— 后者可能返回空/异常包络(见 docs/implementation.md)。
|
|
4
|
+
// - event: Event.properties.sessionID;
|
|
5
|
+
// session.created/updated/deleted 则挂在 properties.info.id
|
|
6
|
+
// - chat.message / tool.execute.before / shell.env / 工具 execute 的 context: 入参 sessionID
|
|
7
|
+
/** 从 opencode 插件 event 提取 sessionID(兼容 properties / data 两种包络) */
|
|
8
|
+
export function extractSessionIDFromEvent(ev) {
|
|
9
|
+
if (!ev || typeof ev !== "object")
|
|
10
|
+
return "";
|
|
11
|
+
const p = ev.properties ?? ev.data ?? {};
|
|
12
|
+
const sid = p.sessionID ?? p.info?.id;
|
|
13
|
+
return typeof sid === "string" ? sid : "";
|
|
14
|
+
}
|
|
15
|
+
/** 从 chat.message / tool.execute.before / 工具 context 等入参提取 sessionID */
|
|
16
|
+
export function extractSessionIDFromHookInput(input) {
|
|
17
|
+
const sid = input?.sessionID;
|
|
18
|
+
return typeof sid === "string" ? sid : "";
|
|
19
|
+
}
|
|
20
|
+
/** 当前会话 id 缓存:优先于 client.session.list(),避免 list() 为空导致投递静默失败 */
|
|
21
|
+
export function createSessionIDCache() {
|
|
22
|
+
let current = "";
|
|
23
|
+
return {
|
|
24
|
+
/** 从钩子入参刷新;返回本次提取到的 id(可能为 "" 表示未提供) */
|
|
25
|
+
updateFromHookInput(input) {
|
|
26
|
+
const sid = extractSessionIDFromHookInput(input);
|
|
27
|
+
if (sid)
|
|
28
|
+
current = sid;
|
|
29
|
+
return sid;
|
|
30
|
+
},
|
|
31
|
+
/** 从 event 刷新(不用于 session.deleted,删除时用 clearIf) */
|
|
32
|
+
updateFromEvent(ev) {
|
|
33
|
+
const sid = extractSessionIDFromEvent(ev);
|
|
34
|
+
if (sid)
|
|
35
|
+
current = sid;
|
|
36
|
+
return sid;
|
|
37
|
+
},
|
|
38
|
+
get() {
|
|
39
|
+
return current;
|
|
40
|
+
},
|
|
41
|
+
/** 会话被删除时清除缓存(仅当匹配) */
|
|
42
|
+
clearIf(id) {
|
|
43
|
+
if (id && current === id)
|
|
44
|
+
current = "";
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|