@xiaoqiong0v0/opencode-browser-tool 1.2.1 → 1.3.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 +3 -3
- package/dist/client.js +40 -4
- package/dist/index.js +130 -37
- package/dist/logger.js +6 -0
- package/dist/session-id.js +47 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -145,7 +145,7 @@ opencode(Bun)
|
|
|
145
145
|
| `bt_click_and_switch_tab` | `selector`(string) 必填 | 点击元素;若触发新标签则自动切换,返回当前 URL |
|
|
146
146
|
| `bt_iframe_click` | `iframeSelector`, `selector`(string) 必填 | 在 iframe 中点击(仅同源可访问) |
|
|
147
147
|
| `bt_iframe_fill` | `iframeSelector`, `selector`, `value`(string) 必填 | 在 iframe 中输入(仅同源可访问) |
|
|
148
|
-
| `bt_get_browser_status` | 无 |
|
|
148
|
+
| `bt_get_browser_status` | 无 | **纯查询、不启动浏览器**:运行中返回 open/url/title/tabs 数量;未运行时返回未运行提示 + bt-shell 二进制状态(下载中/就绪/失败/禁用) |
|
|
149
149
|
| `bt_list_tabs` | 无 | 列出标签页(索引+URL) |
|
|
150
150
|
| `bt_switch_tab` | `index`(number) 必填 | 按位置(0 起)切换标签 |
|
|
151
151
|
| `bt_new_tab` | `url`(string) 必填 | 新建独立标签页(真多标签)并导航 |
|
|
@@ -163,8 +163,8 @@ opencode(Bun)
|
|
|
163
163
|
| `bt_expect_response` | `url`(string) 必填 | 记录期望匹配的响应模式,清空响应历史后重新捕获 |
|
|
164
164
|
| `bt_assert_response` | `id`(string) 必填 | 断言是否存在匹配的响应(返回 `url` + `status` 码) |
|
|
165
165
|
| `bt_get_accessibility_tree` | `selector`, `maxDepth`(number) | 返回页面可访问性树(role/name/value 嵌套结构) |
|
|
166
|
-
| `bt_list_records` | 无 |
|
|
167
|
-
| `bt_read_record_content` | `id`(number) 必填 |
|
|
166
|
+
| `bt_list_records` | 无 | 列出批注/截图记录(索引/标签/说明;截图带 `+img`,已发送带 `[sent]`) |
|
|
167
|
+
| `bt_read_record_content` | `id`(number) 必填 | 读取单条记录详情(截图附带图片大小与落盘路径) |
|
|
168
168
|
|
|
169
169
|
## 设备预设
|
|
170
170
|
|
package/dist/client.js
CHANGED
|
@@ -2,7 +2,7 @@ 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
6
|
import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
|
|
7
7
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
8
8
|
/** 就绪轮询超时(ms) */
|
|
@@ -123,7 +123,6 @@ async function waitForReady(baseUrl, timeoutMessage) {
|
|
|
123
123
|
}
|
|
124
124
|
/** 附着到外部已运行的 shell(不 spawn):等待就绪后记录 base URL */
|
|
125
125
|
async function attachToService(baseUrl) {
|
|
126
|
-
const log = createLogger("opencode-browser-tool");
|
|
127
126
|
attachMode = true;
|
|
128
127
|
log.info(`Attaching to existing bt-shell at ${baseUrl} (no spawn)`);
|
|
129
128
|
await waitForReady(baseUrl, `External bt-shell not ready at ${baseUrl}. Check BT_SHELL_URL/BT_SHELL_PORT and that the shell is running.`);
|
|
@@ -132,7 +131,6 @@ async function attachToService(baseUrl) {
|
|
|
132
131
|
log.info(`Attached to existing bt-shell at ${baseUrl}`);
|
|
133
132
|
}
|
|
134
133
|
export async function startService(nodePath, browsersPath, sessionIsolation, browserType, userDataDir) {
|
|
135
|
-
const log = createLogger("opencode-browser-tool");
|
|
136
134
|
attachMode = false;
|
|
137
135
|
let shell = resolveShellBinary();
|
|
138
136
|
// 未就绪:先(有界)等待下载完成;失败/超时给出明确提示
|
|
@@ -157,6 +155,16 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
157
155
|
if (userDataDir)
|
|
158
156
|
args.push("--user-data-dir", userDataDir);
|
|
159
157
|
serviceProcess = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
158
|
+
// 把 shell 的 stdout/stderr 转发进共享日志:Rust 侧 println!/eprintln! 默认被管道吞掉(无人读取 → 日志永远看不到)
|
|
159
|
+
const forwardShell = (tag) => (chunk) => {
|
|
160
|
+
for (const line of chunk.toString().split(/\r?\n/)) {
|
|
161
|
+
const s = line.trim();
|
|
162
|
+
if (s)
|
|
163
|
+
log.info(`${tag} ${s}`);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
serviceProcess.stdout?.on("data", forwardShell("[shell:out]"));
|
|
167
|
+
serviceProcess.stderr?.on("data", forwardShell("[shell:err]"));
|
|
160
168
|
// 等待服务就绪(轮询端口)
|
|
161
169
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
162
170
|
await waitForReady(baseUrl, "Service timeout: bt-shell did not start. Build it with: cd rust && cargo build --release");
|
|
@@ -165,7 +173,6 @@ export async function startService(nodePath, browsersPath, sessionIsolation, bro
|
|
|
165
173
|
log.info(`Shell service ready on port ${port} (${shell})`);
|
|
166
174
|
}
|
|
167
175
|
export async function stopService() {
|
|
168
|
-
const log = createLogger("opencode-browser-tool");
|
|
169
176
|
if (attachMode) {
|
|
170
177
|
// 附着模式:外部 shell 进程不归插件管,只清空本地状态
|
|
171
178
|
log.info("Detached from external bt-shell (process left running)");
|
|
@@ -189,6 +196,35 @@ export async function openWindow() {
|
|
|
189
196
|
export function isRunning() {
|
|
190
197
|
return serviceReady;
|
|
191
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* 纯查询:探测 shell 是否在运行,**绝不 spawn**。
|
|
201
|
+
* 仅在本进程已启动/附着(`serviceBaseUrl` 已知)时做一次短超时 HTTP 探测;否则返回 null。
|
|
202
|
+
* 用于 `get_browser_status` 这类只读命令,避免查询也弹出浏览器窗口。
|
|
203
|
+
*/
|
|
204
|
+
export async function probeStatus(timeoutMs = 1500) {
|
|
205
|
+
if (!serviceReady || !serviceBaseUrl)
|
|
206
|
+
return null;
|
|
207
|
+
const ac = new AbortController();
|
|
208
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
209
|
+
try {
|
|
210
|
+
const res = await fetch(`${serviceBaseUrl}/api/status`, {
|
|
211
|
+
method: "POST",
|
|
212
|
+
headers: { "Content-Type": "application/json" },
|
|
213
|
+
body: "{}",
|
|
214
|
+
signal: ac.signal,
|
|
215
|
+
});
|
|
216
|
+
if (!res.ok)
|
|
217
|
+
return null;
|
|
218
|
+
const json = await res.json();
|
|
219
|
+
return json?.success ? json.data : null;
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
192
228
|
function cmd(name) {
|
|
193
229
|
return (params, sessionId) => callApi(`/api/${name}`, params, sessionId);
|
|
194
230
|
}
|
package/dist/index.js
CHANGED
|
@@ -6,11 +6,11 @@ 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 { startDownload } from "./binary.js";
|
|
9
|
+
import { configureService, setUserDataDir, ensureService, openWindow, isRunning, stopService, service, probeStatus } from "./client.js";
|
|
10
|
+
import { startDownload, getBinaryStatus, describeBinaryStatus } from "./binary.js";
|
|
11
11
|
import { tool } from "@opencode-ai/plugin";
|
|
12
|
-
import
|
|
13
|
-
|
|
12
|
+
import { log } from "./logger.js";
|
|
13
|
+
import { createSessionIDCache, extractSessionIDFromEvent } from "./session-id.js";
|
|
14
14
|
const _t = (k) => t(k);
|
|
15
15
|
/** 降级说明:服务端在无可信通道、退回 untrusted DOM/JS 时返回 degraded,统一在此追加标注 */
|
|
16
16
|
function degradedNote(r) {
|
|
@@ -54,7 +54,7 @@ const COMMANDS = {
|
|
|
54
54
|
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
55
|
screenshot: { usage: "[--selector]", descKey: "cli.cmd.screenshot", args: [{ flag: "selector" }], run: async (a) => {
|
|
56
56
|
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",
|
|
57
|
+
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
58
|
} },
|
|
59
59
|
evaluate: { usage: "--script", descKey: "cli.cmd.evaluate", args: [{ flag: "script" }], run: async (a) => JSON.stringify(await service.evaluate(a), null, 2) },
|
|
60
60
|
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 +91,12 @@ const COMMANDS = {
|
|
|
91
91
|
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
92
|
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
93
|
get_browser_status: { usage: "", descKey: "cli.cmd.get_browser_status", run: async () => {
|
|
94
|
-
|
|
94
|
+
// 纯查询:不 spawn、不懒启动(未运行只提示,不弹窗)
|
|
95
|
+
const s = await probeStatus();
|
|
96
|
+
if (!s) {
|
|
97
|
+
const b = getBinaryStatus();
|
|
98
|
+
return `Browser is not running.\nbt-shell: ${describeBinaryStatus(b)}\n(执行任意其它工具会自动启动;也可用 open_window 显式启动)`;
|
|
99
|
+
}
|
|
95
100
|
if (s.installing && Object.keys(s.installing).length > 0)
|
|
96
101
|
return `Installing ${Object.entries(s.installing).map(([b, p]) => `${b} (${p})`).join(", ")}.`;
|
|
97
102
|
if (!s.open)
|
|
@@ -116,7 +121,7 @@ const COMMANDS = {
|
|
|
116
121
|
const records = await service.annotateRecords();
|
|
117
122
|
if (!records || !records.length)
|
|
118
123
|
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");
|
|
124
|
+
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
125
|
}
|
|
121
126
|
catch {
|
|
122
127
|
return "(no records)";
|
|
@@ -126,7 +131,12 @@ const COMMANDS = {
|
|
|
126
131
|
const rec = (records || []).find((r) => r.index === a.id);
|
|
127
132
|
if (!rec)
|
|
128
133
|
return `(record #${a.id} not found)`;
|
|
129
|
-
|
|
134
|
+
let img = "";
|
|
135
|
+
if (rec.image) {
|
|
136
|
+
const p = saveShotImage(log, rec.index, rec.image);
|
|
137
|
+
img = `\nimage: ${Math.round(rec.image.length / 1024)}KB base64` + (p ? ` (saved: ${p})` : "");
|
|
138
|
+
}
|
|
139
|
+
return `#${rec.index} ${rec.selector}\nrect: ${JSON.stringify(rec.rect)}${img}\nnote: ${rec.note || "(none)"}`;
|
|
130
140
|
}
|
|
131
141
|
catch {
|
|
132
142
|
return "(no records)";
|
|
@@ -248,7 +258,9 @@ function splitCsvLine(line) {
|
|
|
248
258
|
out.push(cur);
|
|
249
259
|
return out;
|
|
250
260
|
}
|
|
251
|
-
export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
261
|
+
export const opencodeBrowserTool = async ({ client, worktree, directory, serverUrl }) => {
|
|
262
|
+
// 插件上下文(仅用于诊断:定位 session.list() 为空时是哪个实例/目录)
|
|
263
|
+
pluginCtx = { directory: directory || "", worktree: worktree || "", serverUrl: serverUrl ? String(serverUrl) : "" };
|
|
252
264
|
registerLocale("en", en);
|
|
253
265
|
registerLocale("zh", zh);
|
|
254
266
|
loadConfig(worktree);
|
|
@@ -267,19 +279,31 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
267
279
|
// 启动即后台下载 bt-shell(fire-and-forget:不阻塞启动,失败不抛出;状态见 getBinaryStatus)
|
|
268
280
|
startDownload();
|
|
269
281
|
// 轮询批注发送队列(面板"发送全部" → 推送到对话)
|
|
270
|
-
void startAnnotatePoller(client
|
|
282
|
+
void startAnnotatePoller(client);
|
|
271
283
|
return {
|
|
272
284
|
event: async ({ event }) => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
285
|
+
// 缓存最近会话 id:这是投递批注最可靠的 sessionID 来源
|
|
286
|
+
if (event.type !== "session.deleted") {
|
|
287
|
+
sessionCache.updateFromEvent(event);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
const delId = extractSessionIDFromEvent(event);
|
|
291
|
+
if (delId) {
|
|
292
|
+
sessionCache.clearIf(delId);
|
|
276
293
|
try {
|
|
277
|
-
await service.closeSession({ _sessionId:
|
|
294
|
+
await service.closeSession({ _sessionId: delId });
|
|
278
295
|
}
|
|
279
296
|
catch { }
|
|
280
297
|
}
|
|
281
298
|
}
|
|
282
299
|
},
|
|
300
|
+
// 用户发消息 / 调工具时刷新当前会话 id(参考项目用 ctx.sessionID,此处为等价钩子来源)
|
|
301
|
+
"chat.message": async (input) => {
|
|
302
|
+
sessionCache.updateFromHookInput(input);
|
|
303
|
+
},
|
|
304
|
+
"tool.execute.before": async (input) => {
|
|
305
|
+
sessionCache.updateFromHookInput(input);
|
|
306
|
+
},
|
|
283
307
|
tool: filterDisabled({
|
|
284
308
|
bt_cli: tool({
|
|
285
309
|
description: _t("tool.cli.desc") + "\n" + DESC_INDEX,
|
|
@@ -330,7 +354,8 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
330
354
|
}
|
|
331
355
|
}
|
|
332
356
|
}
|
|
333
|
-
// 透传会话 ID(会话隔离用)
|
|
357
|
+
// 透传会话 ID(会话隔离用),并刷新钩子缓存(兜底:即使钩子未触发也能拿到 sid)
|
|
358
|
+
sessionCache.updateFromHookInput(context);
|
|
334
359
|
params._sessionId = context?.sessionID || "";
|
|
335
360
|
try {
|
|
336
361
|
return await def.run(params);
|
|
@@ -347,6 +372,7 @@ export const opencodeBrowserTool = async ({ client, worktree }) => {
|
|
|
347
372
|
mode: tool.schema.enum(["simulate", "real"]).optional().describe(_t("tool.set_media_mode.arg.mode")),
|
|
348
373
|
},
|
|
349
374
|
async execute(a, context) {
|
|
375
|
+
sessionCache.updateFromHookInput(context);
|
|
350
376
|
const r = await service.mediaMode({ ...a, _sessionId: context?.sessionID || "" });
|
|
351
377
|
return `Media mode: ${r.mode}`;
|
|
352
378
|
},
|
|
@@ -396,16 +422,49 @@ function filterDisabled(tools, disabled) {
|
|
|
396
422
|
*/
|
|
397
423
|
let annotateTimer = null;
|
|
398
424
|
let annotateClient = null;
|
|
399
|
-
|
|
425
|
+
/** 最近一次见到的会话 id 缓存(来自 event/chat.message/tool.execute.before 钩子) */
|
|
426
|
+
const sessionCache = createSessionIDCache();
|
|
427
|
+
/** 已记录过的 sid(避免重复刷屏) */
|
|
428
|
+
let lastLoggedSessionID = "";
|
|
429
|
+
/** 插件上下文(诊断用) */
|
|
430
|
+
let pluginCtx = { directory: "", worktree: "", serverUrl: "" };
|
|
431
|
+
/** 把截图 base64 落盘为临时 PNG,返回路径(失败返回 null);用于发送时保留图片与给出可读路径 */
|
|
432
|
+
function saveShotImage(log, index, b64) {
|
|
433
|
+
try {
|
|
434
|
+
const dir = resolve(getTmpDir());
|
|
435
|
+
mkdirSync(dir, { recursive: true });
|
|
436
|
+
const p = resolve(dir, `shot-${Date.now()}-${index}.png`);
|
|
437
|
+
writeFileSync(p, Buffer.from(b64, "base64"));
|
|
438
|
+
return p;
|
|
439
|
+
}
|
|
440
|
+
catch (e) {
|
|
441
|
+
log.error("save screenshot image failed", e);
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
function startAnnotatePoller(client) {
|
|
400
446
|
// 更新 client 引用(插件重载后使用最新 client),但只启动一个轮询器
|
|
401
447
|
annotateClient = client;
|
|
402
448
|
if (annotateTimer)
|
|
403
449
|
return;
|
|
404
450
|
const POLL_MS = 2000;
|
|
451
|
+
let warnedNotRunning = false;
|
|
405
452
|
const timer = setInterval(async () => {
|
|
406
|
-
//
|
|
407
|
-
|
|
453
|
+
// 观测钩子缓存:首次学到 sid 时记一次(证明 sid 来源可用,与窗口是否打开无关)
|
|
454
|
+
const learned = sessionCache.get();
|
|
455
|
+
if (learned && learned !== lastLoggedSessionID) {
|
|
456
|
+
log.info(`[poller] hook-cache sid=${learned}`);
|
|
457
|
+
lastLoggedSessionID = learned;
|
|
458
|
+
}
|
|
459
|
+
// 服务未启动/已关闭:跳过本次轮询(窗口打开后再恢复推送);仅首次提示,避免刷屏
|
|
460
|
+
if (!isRunning()) {
|
|
461
|
+
if (!warnedNotRunning) {
|
|
462
|
+
log.info("[poller] shell not running; poll skipped (will resume after open_window/tool call)");
|
|
463
|
+
warnedNotRunning = true;
|
|
464
|
+
}
|
|
408
465
|
return;
|
|
466
|
+
}
|
|
467
|
+
warnedNotRunning = false;
|
|
409
468
|
const c = annotateClient;
|
|
410
469
|
if (!c)
|
|
411
470
|
return;
|
|
@@ -413,36 +472,70 @@ function startAnnotatePoller(client, log) {
|
|
|
413
472
|
const r = await service.annotateConsumeSent();
|
|
414
473
|
const records = r?.records || [];
|
|
415
474
|
if (records.length === 0)
|
|
416
|
-
return;
|
|
475
|
+
return; // 空结果不刷屏
|
|
476
|
+
const imgInfo = records
|
|
477
|
+
.filter((x) => x.type === "screenshot" && x.image)
|
|
478
|
+
.map((x) => `#${x.index}:${x.image.length}B`);
|
|
479
|
+
log.info(`[poller] consume-sent -> ${records.length} record(s) ids=[${records.map((x) => x.index).join(",")}] images=[${imgInfo.join(",")}]`);
|
|
417
480
|
const lines = ["User annotated via panel:", ""];
|
|
418
|
-
const parts = [];
|
|
419
481
|
for (const item of records) {
|
|
420
|
-
// 截图记录:附带图片 part(裸 base64),AI 可直接看图
|
|
421
|
-
if (item.type === "screenshot" && item.image) {
|
|
422
|
-
parts.push({ type: "file", mime: "image/png", data: item.image, url: "" });
|
|
423
|
-
}
|
|
424
482
|
const label = item.type === "screenshot"
|
|
425
483
|
? `[#${item.index}] 截图${item.url ? ` @ ${item.url}` : ""}`
|
|
426
484
|
: `[#${item.index}] ${item.selector || "(no selector)"}${item.url ? ` @ ${item.url}` : ""}`;
|
|
427
485
|
lines.push(`- ${label}${item.note ? `: ${item.note}` : ""}`);
|
|
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
|
+
}
|
|
428
494
|
lines.push("");
|
|
429
495
|
}
|
|
430
496
|
const text = lines.join("\n");
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
if (
|
|
436
|
-
await c.session.
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
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 { }
|
|
531
|
+
}
|
|
532
|
+
else {
|
|
533
|
+
log.info(`[poller] prompt OK sid=${sid} delivered ${records.length} record(s)`);
|
|
440
534
|
}
|
|
441
535
|
}
|
|
442
|
-
catch {
|
|
443
|
-
//
|
|
444
|
-
|
|
445
|
-
annotateTimer = null;
|
|
536
|
+
catch (e) {
|
|
537
|
+
// 不终止轮询(此前 clearInterval 会导致后续发送永久"无反应")
|
|
538
|
+
log.error("annotate poller error", e);
|
|
446
539
|
}
|
|
447
540
|
}, POLL_MS);
|
|
448
541
|
// 不阻塞进程退出
|
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,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
|
+
}
|