@xiaoqiong0v0/opencode-browser-tool 1.3.0 → 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 +13 -1
- package/dist/binary.js +8 -7
- package/dist/client.js +84 -28
- package/dist/index.js +103 -92
- package/dist/notify-server.js +53 -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
|
|
|
@@ -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
|
@@ -3,37 +3,51 @@ import { resolve, dirname } from "path";
|
|
|
3
3
|
import { existsSync } from "fs";
|
|
4
4
|
import { fileURLToPath } from "url";
|
|
5
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
|
// 懒启动:首次调用工具时自动打开窗口
|
|
@@ -132,7 +181,8 @@ async function attachToService(baseUrl) {
|
|
|
132
181
|
}
|
|
133
182
|
export async function startService(nodePath, browsersPath, sessionIsolation, browserType, userDataDir) {
|
|
134
183
|
attachMode = false;
|
|
135
|
-
|
|
184
|
+
const resolved = resolveShellBinary();
|
|
185
|
+
let shell = resolved.path;
|
|
136
186
|
// 未就绪:先(有界)等待下载完成;失败/超时给出明确提示
|
|
137
187
|
if (!existsSync(shell)) {
|
|
138
188
|
if (process.env.BT_SHELL_PATH) {
|
|
@@ -144,6 +194,8 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
144
194
|
}
|
|
145
195
|
shell = st.path;
|
|
146
196
|
}
|
|
197
|
+
// 记录最终选中的二进制与来源,便于一眼判断用的是哪份(local-dev / env / download-cache …)
|
|
198
|
+
log.info(`Shell binary: ${shell} (source=${resolved.source})`);
|
|
147
199
|
// 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout)
|
|
148
200
|
const port = 18000 + Math.floor(Math.random() * 1000);
|
|
149
201
|
const args = ["--browsers-path", browsersPath || "", "--port", String(port)];
|
|
@@ -154,6 +206,10 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
154
206
|
// 多用户配置:userDataDir 指向独立 WebView2 用户数据目录
|
|
155
207
|
if (userDataDir)
|
|
156
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);
|
|
157
213
|
serviceProcess = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
158
214
|
// 把 shell 的 stdout/stderr 转发进共享日志:Rust 侧 println!/eprintln! 默认被管道吞掉(无人读取 → 日志永远看不到)
|
|
159
215
|
const forwardShell = (tag) => (chunk) => {
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,8 @@ 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, probeStatus } from "./client.js";
|
|
9
|
+
import { configureService, setUserDataDir, setAppDirectory, setServiceReadyHandler, ensureService, openWindow, isRunning, stopService, service, probeStatus } from "./client.js";
|
|
10
|
+
import { startNotifyServer } from "./notify-server.js";
|
|
10
11
|
import { startDownload, getBinaryStatus, describeBinaryStatus } from "./binary.js";
|
|
11
12
|
import { tool } from "@opencode-ai/plugin";
|
|
12
13
|
import { log } from "./logger.js";
|
|
@@ -261,6 +262,8 @@ function splitCsvLine(line) {
|
|
|
261
262
|
export const opencodeBrowserTool = async ({ client, worktree, directory, serverUrl }) => {
|
|
262
263
|
// 插件上下文(仅用于诊断:定位 session.list() 为空时是哪个实例/目录)
|
|
263
264
|
pluginCtx = { directory: directory || "", worktree: worktree || "", serverUrl: serverUrl ? String(serverUrl) : "" };
|
|
265
|
+
// 供 resolveShellBinary 定位本地 Rust 构建(publish-local 到缓存目录后仍能找到仓库)
|
|
266
|
+
setAppDirectory(directory || "");
|
|
264
267
|
registerLocale("en", en);
|
|
265
268
|
registerLocale("zh", zh);
|
|
266
269
|
loadConfig(worktree);
|
|
@@ -278,8 +281,8 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
|
|
|
278
281
|
});
|
|
279
282
|
// 启动即后台下载 bt-shell(fire-and-forget:不阻塞启动,失败不抛出;状态见 getBinaryStatus)
|
|
280
283
|
startDownload();
|
|
281
|
-
//
|
|
282
|
-
|
|
284
|
+
// 事件驱动投递:插件本地监听 shell 通知(推送式,替代轮询)
|
|
285
|
+
setupAnnotateDelivery(client);
|
|
283
286
|
return {
|
|
284
287
|
event: async ({ event }) => {
|
|
285
288
|
// 缓存最近会话 id:这是投递批注最可靠的 sessionID 来源
|
|
@@ -356,6 +359,7 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
|
|
|
356
359
|
}
|
|
357
360
|
// 透传会话 ID(会话隔离用),并刷新钩子缓存(兜底:即使钩子未触发也能拿到 sid)
|
|
358
361
|
sessionCache.updateFromHookInput(context);
|
|
362
|
+
setAppDirectory(context?.directory || "");
|
|
359
363
|
params._sessionId = context?.sessionID || "";
|
|
360
364
|
try {
|
|
361
365
|
return await def.run(params);
|
|
@@ -373,6 +377,7 @@ export const opencodeBrowserTool = async ({ client, worktree, directory, serverU
|
|
|
373
377
|
},
|
|
374
378
|
async execute(a, context) {
|
|
375
379
|
sessionCache.updateFromHookInput(context);
|
|
380
|
+
setAppDirectory(context?.directory || "");
|
|
376
381
|
const r = await service.mediaMode({ ...a, _sessionId: context?.sessionID || "" });
|
|
377
382
|
return `Media mode: ${r.mode}`;
|
|
378
383
|
},
|
|
@@ -420,8 +425,9 @@ function filterDisabled(tools, disabled) {
|
|
|
420
425
|
* 注意:插件函数会随会话/切目录多次执行,轮询器必须进程级单例,
|
|
421
426
|
* 否则同一进程会累积多个 interval 空转(server 与 TUI 进程各一份,互不共享)
|
|
422
427
|
*/
|
|
423
|
-
let annotateTimer = null;
|
|
424
428
|
let annotateClient = null;
|
|
429
|
+
/** drain 进行中,避免并发重复投递 */
|
|
430
|
+
let draining = false;
|
|
425
431
|
/** 最近一次见到的会话 id 缓存(来自 event/chat.message/tool.execute.before 钩子) */
|
|
426
432
|
const sessionCache = createSessionIDCache();
|
|
427
433
|
/** 已记录过的 sid(避免重复刷屏) */
|
|
@@ -442,106 +448,111 @@ function saveShotImage(log, index, b64) {
|
|
|
442
448
|
return null;
|
|
443
449
|
}
|
|
444
450
|
}
|
|
445
|
-
|
|
446
|
-
|
|
451
|
+
/** 事件驱动投递:插件本地监听 shell 通知(收到即 drain),不再 setInterval 轮询 */
|
|
452
|
+
function setupAnnotateDelivery(client) {
|
|
453
|
+
// 更新 client 引用(插件重载后使用最新 client)
|
|
447
454
|
annotateClient = client;
|
|
448
|
-
|
|
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)
|
|
471
|
+
return;
|
|
472
|
+
const c = annotateClient;
|
|
473
|
+
if (!c)
|
|
474
|
+
return;
|
|
475
|
+
// 服务未启动/已关闭:跳过(服务就绪或通知到达时会再次触发)
|
|
476
|
+
if (!isRunning())
|
|
449
477
|
return;
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
// 观测钩子缓存:首次学到 sid 时记一次(证明 sid 来源可用,与窗口是否打开无关)
|
|
478
|
+
draining = true;
|
|
479
|
+
try {
|
|
480
|
+
// 观测钩子缓存:首次学到 sid 时记一次(证明 sid 来源可用)
|
|
454
481
|
const learned = sessionCache.get();
|
|
455
482
|
if (learned && learned !== lastLoggedSessionID) {
|
|
456
|
-
log.info(`[
|
|
483
|
+
log.info(`[notify] hook-cache sid=${learned}`);
|
|
457
484
|
lastLoggedSessionID = learned;
|
|
458
485
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
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})`);
|
|
464
507
|
}
|
|
465
|
-
|
|
508
|
+
lines.push("");
|
|
466
509
|
}
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
// 截图:落盘保留并写入文本路径。与参考实现(opencode-playwright-tool)一致 ——
|
|
487
|
-
// 图片**不经 session.prompt**(服务端对 image/* part 返回 400),而是走
|
|
488
|
-
// 「工具结果附件」(bt_screenshot)或「读记录返回缓存路径」(read_record_content)。
|
|
489
|
-
if (item.type === "screenshot" && item.image) {
|
|
490
|
-
const savedPath = saveShotImage(log, item.index, item.image);
|
|
491
|
-
if (savedPath)
|
|
492
|
-
lines.push(` (image saved: ${savedPath})`);
|
|
493
|
-
}
|
|
494
|
-
lines.push("");
|
|
495
|
-
}
|
|
496
|
-
const text = lines.join("\n");
|
|
497
|
-
// 取当前会话 id:优先用钩子缓存(参考项目 ctx.sessionID 的等价物),session.list() 仅兜底
|
|
498
|
-
let sid = sessionCache.get();
|
|
499
|
-
let source = "hook-cache";
|
|
500
|
-
let listLen = "-";
|
|
501
|
-
if (!sid) {
|
|
502
|
-
const sessions = await c.session.list();
|
|
503
|
-
listLen = Array.isArray(sessions?.data) ? sessions.data.length : sessions?.error ? "error" : "none";
|
|
504
|
-
log.info(`[poller] session.list raw=${JSON.stringify(sessions).slice(0, 400)}`);
|
|
505
|
-
sid = sessions?.data?.[0]?.id;
|
|
506
|
-
source = "client.session.list()[0]";
|
|
507
|
-
}
|
|
508
|
-
// 关键诊断:sid 来源/缓存值/list 长度/插件目录(定位"静默失败"断点)
|
|
509
|
-
log.info(`[poller] sid source=${source} cached=${sessionCache.get() || "(EMPTY)"} listLen=${listLen} ctx=${pluginCtx.directory || "(none)"} srv=${pluginCtx.serverUrl || "(none)"} sid=${sid ?? "(EMPTY)"}`);
|
|
510
|
-
if (!sid) {
|
|
511
|
-
const msg = "no session id (hook cache empty and session.list returned none)";
|
|
512
|
-
log.error(`[poller] ${msg}`, new Error(msg));
|
|
513
|
-
try {
|
|
514
|
-
await service.notify({ message: `发送失败: ${msg}`, type: "err" });
|
|
515
|
-
}
|
|
516
|
-
catch { }
|
|
517
|
-
return;
|
|
518
|
-
}
|
|
519
|
-
const send = (parts) => c.session.prompt({ path: { id: sid }, body: { noReply: false, parts } });
|
|
520
|
-
// 只发文本(参考实现同为纯文本;图片由工具附件/缓存路径交付,不在 prompt 里塞图片 part)
|
|
521
|
-
log.info(`[poller] prompt -> sid=${sid} parts=text-only textLen=${text.length}`);
|
|
522
|
-
const res = await send([{ type: "text", text }]);
|
|
523
|
-
const err = res?.error;
|
|
524
|
-
if (err) {
|
|
525
|
-
// 不再静默:写日志 + 页面通知(SDK 返回 {error} 不抛,必须显式检查)
|
|
526
|
-
log.error(`[poller] prompt FAILED sid=${sid}: ${JSON.stringify(err).slice(0, 300)}`, new Error("prompt error"));
|
|
527
|
-
try {
|
|
528
|
-
await service.notify({ message: `发送记录失败: ${JSON.stringify(err).slice(0, 180)}`, type: "err" });
|
|
529
|
-
}
|
|
530
|
-
catch { }
|
|
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) {
|
|
516
|
+
const sessions = await c.session.list();
|
|
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" });
|
|
531
529
|
}
|
|
532
|
-
|
|
533
|
-
|
|
530
|
+
catch { }
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
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" });
|
|
534
543
|
}
|
|
544
|
+
catch { }
|
|
535
545
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
log.error("annotate poller error", e);
|
|
546
|
+
else {
|
|
547
|
+
log.info(`[drain] prompt OK sid=${sid} delivered ${records.length} record(s)`);
|
|
539
548
|
}
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
549
|
+
}
|
|
550
|
+
catch (e) {
|
|
551
|
+
log.error("annotate drain error", e);
|
|
552
|
+
}
|
|
553
|
+
finally {
|
|
554
|
+
draining = false;
|
|
555
|
+
}
|
|
545
556
|
}
|
|
546
557
|
// Export default for npm loader
|
|
547
558
|
export default opencodeBrowserTool;
|
|
@@ -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
|
+
}
|