@xiaoqiong0v0/opencode-browser-tool 1.6.0 → 1.9.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 +38 -10
- package/dist/binary.js +15 -9
- package/dist/client.js +448 -170
- package/dist/config/index.js +22 -10
- package/dist/i18n/en.js +123 -19
- package/dist/i18n/index.js +17 -0
- package/dist/i18n/zh.js +123 -19
- package/dist/index.js +190 -153
- package/dist/notify-server.js +16 -5
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
|
+
// bt-shell 客户端:每会话独立 shell 实例(1.9.0 会话隔离架构)
|
|
2
|
+
//
|
|
3
|
+
// 架构:实例注册表 Map<sid, ShellInstance> —— 同一 opencode 进程内的不同会话各持有
|
|
4
|
+
// 自己的 bt-shell 进程(独立端口 + 独立 --user-data-dir + 独立窗口标题),互不共享
|
|
5
|
+
// 窗口/标签/UA/批注等一切 shell 状态;进程回收只按注册表里的 PID,**绝不按名杀进程**。
|
|
6
|
+
// 附着模式(BT_SHELL_URL/BT_SHELL_PORT)例外:连接外部单例,放弃会话隔离(见 docs/implementation.md)。
|
|
1
7
|
import { spawn } from "child_process";
|
|
2
8
|
import { resolve, dirname } from "path";
|
|
3
9
|
import { existsSync } from "fs";
|
|
4
10
|
import { fileURLToPath } from "url";
|
|
5
11
|
import { log } from "./logger.js";
|
|
6
|
-
import {
|
|
12
|
+
import { getNotifyUrlForSession } from "./notify-server.js";
|
|
13
|
+
import { tf } from "./i18n/index.js";
|
|
7
14
|
import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
|
|
8
15
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
16
|
/** 就绪轮询超时(ms) */
|
|
10
17
|
const READY_TIMEOUT_MS = 20000;
|
|
11
18
|
/** 就绪轮询间隔(ms) */
|
|
12
19
|
const READY_POLL_INTERVAL_MS = 300;
|
|
20
|
+
/** 端口撞车/启动失败时的重试次数(每次换一个随机端口) */
|
|
21
|
+
const PORT_START_ATTEMPTS = 5;
|
|
22
|
+
/** 会话标题解析上限(ms):超时就用 sid 后缀,绝不因标题卡住启动 */
|
|
23
|
+
const TITLE_RESOLVE_TIMEOUT_MS = 250;
|
|
13
24
|
/** opencode 应用/项目目录(插件初始化与工具上下文提供);用于定位本地 Rust 开发构建 */
|
|
14
25
|
let appDirectory = "";
|
|
15
26
|
/** 记录 opencode 目录(插件初始化 / 工具调用时调用) */
|
|
@@ -24,7 +35,7 @@ export function setAppDirectory(dir) {
|
|
|
24
35
|
export function resolveShellBinary() {
|
|
25
36
|
const platform = process.platform === "win32" ? "win-x64" : "linux-x64";
|
|
26
37
|
const bin = process.platform === "win32" ? "bt-shell.exe" : "bt-shell";
|
|
27
|
-
// 1) 显式指定:最优先(
|
|
38
|
+
// 1) 显式指定:最优先(即使文件暂不存在也返回,由启动链路 resolveShellPath 给出明确错误)
|
|
28
39
|
const envPath = process.env.BT_SHELL_PATH;
|
|
29
40
|
if (envPath)
|
|
30
41
|
return { path: envPath, source: "env" };
|
|
@@ -46,7 +57,7 @@ export function resolveShellBinary() {
|
|
|
46
57
|
if (p && existsSync(p))
|
|
47
58
|
return { path: p, source };
|
|
48
59
|
}
|
|
49
|
-
// 5) 下载缓存(未下载时由
|
|
60
|
+
// 5) 下载缓存(未下载时由 resolveShellPath 先 ensureBinary)
|
|
50
61
|
return { path: cachedBinaryPath(), source: "download-cache" };
|
|
51
62
|
}
|
|
52
63
|
/** 解析附着模式目标地址:BT_SHELL_URL 优先,其次 BT_SHELL_PORT;均未设置返回 null */
|
|
@@ -59,96 +70,104 @@ function resolveAttachBaseUrl() {
|
|
|
59
70
|
return `http://127.0.0.1:${port}`;
|
|
60
71
|
return null;
|
|
61
72
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
-
/**
|
|
73
|
+
/** 实例注册表:每会话一个 shell;并发启动保护见 startingSid */
|
|
74
|
+
const sessions = new Map();
|
|
75
|
+
/** 正在启动中的会话 → Promise(并发保护:同一 sid 多个工具同时调用只启动一次) */
|
|
76
|
+
const startingSid = new Map();
|
|
77
|
+
/** 已请求关闭的会话(P3-①):close 与启动并发时置位,启动链完成后据此自毁,避免孤儿窗口 */
|
|
78
|
+
const closedSids = new Set();
|
|
79
|
+
/** 附着模式共享实例(外部 shell;所有 sid 共用,放弃会话隔离) */
|
|
80
|
+
let attachInstance = null;
|
|
81
|
+
/** 服务启动参数(configureService 保存,懒启动时使用) */
|
|
69
82
|
let serviceConfig = null;
|
|
70
|
-
/**
|
|
71
|
-
let
|
|
83
|
+
/** 会话 id 兜底解析器(钩子缓存):工具调用没带 _sessionId 时用它 */
|
|
84
|
+
let sessionIdResolver = null;
|
|
85
|
+
/** 可选会话标题解析器(client.session.get 之类);拿不到/超时回退 sid 后缀,不阻塞启动 */
|
|
86
|
+
let titleResolver = null;
|
|
87
|
+
/** 实例就绪回调(插件注册:对该 sid 做一次初始 drain) */
|
|
88
|
+
let serviceReadyHandler = null;
|
|
72
89
|
/** 保存服务启动参数(插件加载时调用,不立即启动窗口) */
|
|
73
90
|
export function configureService(opts) {
|
|
74
91
|
serviceConfig = opts;
|
|
75
92
|
}
|
|
76
|
-
/**
|
|
77
|
-
export function
|
|
78
|
-
|
|
79
|
-
serviceConfig.userDataDir = dir;
|
|
93
|
+
/** 注册会话 id 兜底解析器(通常指向插件的钩子缓存 sessionCache.get) */
|
|
94
|
+
export function setSessionIdResolver(fn) {
|
|
95
|
+
sessionIdResolver = fn;
|
|
80
96
|
}
|
|
81
|
-
/**
|
|
82
|
-
|
|
83
|
-
|
|
97
|
+
/** 注册可选的会话标题解析器(返回 null/抛错则用 sid 后缀;有 250ms 上限,不阻塞启动) */
|
|
98
|
+
export function setTitleResolver(fn) {
|
|
99
|
+
titleResolver = fn;
|
|
100
|
+
}
|
|
101
|
+
/** 注册实例就绪回调(spawn/附着成功且注册 notify-url 之后,按 sid 调用一次) */
|
|
84
102
|
export function setServiceReadyHandler(cb) {
|
|
85
103
|
serviceReadyHandler = cb;
|
|
86
104
|
}
|
|
87
|
-
/**
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
105
|
+
/**
|
|
106
|
+
* 解析本次调用的会话 id:显式参数 > 请求体 _sessionId > 钩子缓存兜底 > "default" 桶
|
|
107
|
+
* "default" 桶用于拿不到任何 sid 的场景(仍有独立实例,不会与其它会话互踩)
|
|
108
|
+
*/
|
|
109
|
+
export function resolveSessionId(explicit) {
|
|
110
|
+
const s = (explicit || "").trim();
|
|
111
|
+
if (s)
|
|
112
|
+
return s;
|
|
113
|
+
try {
|
|
114
|
+
const cached = sessionIdResolver?.() || "";
|
|
115
|
+
if (cached.trim())
|
|
116
|
+
return cached.trim();
|
|
99
117
|
}
|
|
100
|
-
|
|
101
|
-
//
|
|
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
|
-
});
|
|
118
|
+
catch {
|
|
119
|
+
// 解析器异常不阻断调用
|
|
108
120
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
121
|
+
return "default";
|
|
122
|
+
}
|
|
123
|
+
/** 该会话实例是否就绪(不给 sid 则任一实例就绪即 true) */
|
|
124
|
+
export function isRunning(sid) {
|
|
125
|
+
if (sid) {
|
|
126
|
+
const s = resolveSessionId(sid);
|
|
127
|
+
if (sessions.get(s)?.ready)
|
|
128
|
+
return true;
|
|
129
|
+
return !!attachInstance?.ready;
|
|
114
130
|
}
|
|
115
|
-
|
|
116
|
-
|
|
131
|
+
for (const inst of sessions.values())
|
|
132
|
+
if (inst.ready)
|
|
133
|
+
return true;
|
|
134
|
+
return !!attachInstance?.ready;
|
|
135
|
+
}
|
|
136
|
+
/** 诊断/自验用:列出当前注册的实例(只读,不 spawn) */
|
|
137
|
+
export function listSessions() {
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const inst of sessions.values()) {
|
|
140
|
+
out.push({
|
|
141
|
+
sid: inst.sid,
|
|
142
|
+
baseUrl: inst.baseUrl,
|
|
143
|
+
port: inst.port,
|
|
144
|
+
ready: inst.ready,
|
|
145
|
+
attach: inst.attach,
|
|
146
|
+
dataDir: inst.dataDir,
|
|
147
|
+
title: inst.title,
|
|
148
|
+
pid: inst.proc?.pid ?? null,
|
|
149
|
+
});
|
|
117
150
|
}
|
|
151
|
+
return out;
|
|
118
152
|
}
|
|
119
|
-
/**
|
|
120
|
-
async function
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
153
|
+
/** 组装窗口标题:优先会话标题(有界等待),拿不到用 sid 后 6 位,保证任务栏可分辨 */
|
|
154
|
+
async function resolveWindowTitle(sid) {
|
|
155
|
+
const suffix = sid.length > 6 ? sid.slice(-6) : sid || "main";
|
|
156
|
+
const fallback = `bt-shell · ${suffix}`;
|
|
157
|
+
if (!titleResolver)
|
|
158
|
+
return fallback;
|
|
124
159
|
try {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
log.info(`[notify] notify-url registered: ${url}`);
|
|
132
|
-
else
|
|
133
|
-
log.error(`[notify] register failed: HTTP ${res.status}`);
|
|
160
|
+
const t = await Promise.race([
|
|
161
|
+
Promise.resolve().then(() => titleResolver(sid)),
|
|
162
|
+
new Promise((r) => setTimeout(() => r(null), TITLE_RESOLVE_TIMEOUT_MS)),
|
|
163
|
+
]);
|
|
164
|
+
if (t && t.trim())
|
|
165
|
+
return `bt-shell · ${t.trim()}`;
|
|
134
166
|
}
|
|
135
|
-
catch
|
|
136
|
-
|
|
167
|
+
catch {
|
|
168
|
+
// 标题拿不到就用后缀,绝不因此失败
|
|
137
169
|
}
|
|
138
|
-
|
|
139
|
-
async function callApi(path, body, sessionId) {
|
|
140
|
-
// 懒启动:首次调用工具时自动打开窗口
|
|
141
|
-
await ensureService();
|
|
142
|
-
const payload = { ...(body || {}), _sessionId: sessionId || "" };
|
|
143
|
-
const res = await fetch(`${serviceBaseUrl}${path}`, {
|
|
144
|
-
method: "POST",
|
|
145
|
-
headers: { "Content-Type": "application/json" },
|
|
146
|
-
body: JSON.stringify(payload),
|
|
147
|
-
});
|
|
148
|
-
const json = await res.json();
|
|
149
|
-
if (!json.success)
|
|
150
|
-
throw new Error(json.error || "Service error");
|
|
151
|
-
return json.data;
|
|
170
|
+
return fallback;
|
|
152
171
|
}
|
|
153
172
|
/** 轮询等待服务就绪(READY_TIMEOUT_MS 超时);超时抛出给定提示 */
|
|
154
173
|
async function waitForReady(baseUrl, timeoutMessage) {
|
|
@@ -170,64 +189,6 @@ async function waitForReady(baseUrl, timeoutMessage) {
|
|
|
170
189
|
}
|
|
171
190
|
throw new Error(timeoutMessage);
|
|
172
191
|
}
|
|
173
|
-
/** 附着到外部已运行的 shell(不 spawn):等待就绪后记录 base URL */
|
|
174
|
-
async function attachToService(baseUrl) {
|
|
175
|
-
attachMode = true;
|
|
176
|
-
log.info(`Attaching to existing bt-shell at ${baseUrl} (no spawn)`);
|
|
177
|
-
await waitForReady(baseUrl, `External bt-shell not ready at ${baseUrl}. Check BT_SHELL_URL/BT_SHELL_PORT and that the shell is running.`);
|
|
178
|
-
serviceBaseUrl = baseUrl;
|
|
179
|
-
serviceReady = true;
|
|
180
|
-
log.info(`Attached to existing bt-shell at ${baseUrl}`);
|
|
181
|
-
}
|
|
182
|
-
export async function startService(nodePath, browsersPath, sessionIsolation, browserType, userDataDir) {
|
|
183
|
-
attachMode = false;
|
|
184
|
-
const resolved = resolveShellBinary();
|
|
185
|
-
let shell = resolved.path;
|
|
186
|
-
// 未就绪:先(有界)等待下载完成;失败/超时给出明确提示
|
|
187
|
-
if (!existsSync(shell)) {
|
|
188
|
-
if (process.env.BT_SHELL_PATH) {
|
|
189
|
-
throw new Error(`BT_SHELL_PATH 指向的二进制不存在:${shell}`);
|
|
190
|
-
}
|
|
191
|
-
const st = await ensureBinary(20000);
|
|
192
|
-
if (st.state !== "ready" || !st.path) {
|
|
193
|
-
throw new Error(describeBinaryStatus(st));
|
|
194
|
-
}
|
|
195
|
-
shell = st.path;
|
|
196
|
-
}
|
|
197
|
-
// 记录最终选中的二进制与来源,便于一眼判断用的是哪份(local-dev / env / download-cache …)
|
|
198
|
-
log.info(`Shell binary: ${shell} (source=${resolved.source})`);
|
|
199
|
-
// 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout)
|
|
200
|
-
const port = 18000 + Math.floor(Math.random() * 1000);
|
|
201
|
-
const args = ["--browsers-path", browsersPath || "", "--port", String(port)];
|
|
202
|
-
if (browserType)
|
|
203
|
-
args.push("--browser", browserType);
|
|
204
|
-
if (sessionIsolation)
|
|
205
|
-
args.push("--session-isolation");
|
|
206
|
-
// 多用户配置:userDataDir 指向独立 WebView2 用户数据目录
|
|
207
|
-
if (userDataDir)
|
|
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);
|
|
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]"));
|
|
224
|
-
// 等待服务就绪(轮询端口)
|
|
225
|
-
const baseUrl = `http://127.0.0.1:${port}`;
|
|
226
|
-
await waitForReady(baseUrl, "Service timeout: bt-shell did not start. Build it with: cd rust && cargo build --release");
|
|
227
|
-
serviceBaseUrl = baseUrl;
|
|
228
|
-
serviceReady = true;
|
|
229
|
-
log.info(`Shell service ready on port ${port} (${shell})`);
|
|
230
|
-
}
|
|
231
192
|
/** 等待子进程退出(有界超时);已退出/出错返回 true,超时返回 false */
|
|
232
193
|
function waitForExit(proc, timeoutMs) {
|
|
233
194
|
return new Promise((resolveExit) => {
|
|
@@ -246,55 +207,303 @@ function waitForExit(proc, timeoutMs) {
|
|
|
246
207
|
proc.once("error", () => finish(true));
|
|
247
208
|
});
|
|
248
209
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
210
|
+
/**
|
|
211
|
+
* 终止**本插件自己 spawn 的**子进程(先等优雅退出,超时才 SIGTERM 该句柄/PID)。
|
|
212
|
+
* 红线:只允许杀自己 spawn 的子进程、按句柄/PID —— 绝不按名/通配匹配。
|
|
213
|
+
*/
|
|
214
|
+
async function terminateOwnProcess(proc) {
|
|
215
|
+
if (!proc)
|
|
216
|
+
return;
|
|
217
|
+
const exited = await waitForExit(proc, 5000);
|
|
218
|
+
if (exited) {
|
|
219
|
+
log.info(`bt-shell pid=${proc.pid} exited gracefully`);
|
|
256
220
|
return;
|
|
257
221
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
222
|
+
log.info(`bt-shell pid=${proc.pid} did not exit within 5s; sending SIGTERM to that pid`);
|
|
223
|
+
try {
|
|
224
|
+
proc.kill("SIGTERM");
|
|
225
|
+
}
|
|
226
|
+
catch { }
|
|
227
|
+
await waitForExit(proc, 2000);
|
|
228
|
+
}
|
|
229
|
+
/** 把 shell 的 stdout/stderr 转发进共享日志(Rust println! 默认会被管道吞掉) */
|
|
230
|
+
function attachStdio(proc, sid) {
|
|
231
|
+
const forwardShell = (tag) => (chunk) => {
|
|
232
|
+
for (const line of chunk.toString().split(/\r?\n/)) {
|
|
233
|
+
const s = line.trim();
|
|
234
|
+
if (s)
|
|
235
|
+
log.info(`[${tag}][sid=${sid}] ${s}`);
|
|
264
236
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
237
|
+
};
|
|
238
|
+
proc.stdout?.on("data", forwardShell("shell:out"));
|
|
239
|
+
proc.stderr?.on("data", forwardShell("shell:err"));
|
|
240
|
+
}
|
|
241
|
+
/** 二进制就绪性检查(不存在则等下载;失败抛明确错误) */
|
|
242
|
+
async function resolveShellPath() {
|
|
243
|
+
const resolved = resolveShellBinary();
|
|
244
|
+
let shell = resolved.path;
|
|
245
|
+
if (!existsSync(shell)) {
|
|
246
|
+
if (process.env.BT_SHELL_PATH) {
|
|
247
|
+
// 只提示环境变量名,不回流绝对路径(路径已在插件日志)
|
|
248
|
+
throw new Error(tf("client.bt_shell_path_missing"));
|
|
271
249
|
}
|
|
272
|
-
|
|
250
|
+
const st = await ensureBinary(20000);
|
|
251
|
+
if (st.state !== "ready" || !st.path) {
|
|
252
|
+
throw new Error(describeBinaryStatus(st));
|
|
253
|
+
}
|
|
254
|
+
shell = st.path;
|
|
273
255
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
attachMode = false;
|
|
256
|
+
log.info(`Shell binary: ${shell} (source=${resolved.source})`);
|
|
257
|
+
return shell;
|
|
277
258
|
}
|
|
278
|
-
/**
|
|
279
|
-
|
|
280
|
-
|
|
259
|
+
/**
|
|
260
|
+
* spawn 一个新 shell 实例(带端口重试):端口撞车/启动超时 → 只杀掉**本次刚 spawn 的**
|
|
261
|
+
* 子进程(按句柄/PID),换随机端口重来,最多 PORT_START_ATTEMPTS 次。
|
|
262
|
+
*/
|
|
263
|
+
async function spawnForSession(sid, shell) {
|
|
264
|
+
const cfg = serviceConfig;
|
|
265
|
+
const dataDir = cfg?.resolveDataDir ? cfg.resolveDataDir(sid) : "";
|
|
266
|
+
const title = await resolveWindowTitle(sid);
|
|
267
|
+
let lastErr = null;
|
|
268
|
+
for (let attempt = 1; attempt <= PORT_START_ATTEMPTS; attempt++) {
|
|
269
|
+
// 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout);随机区间避开常用端口
|
|
270
|
+
const port = 18000 + Math.floor(Math.random() * 1000);
|
|
271
|
+
const args = ["--browsers-path", cfg?.browsersPath || "", "--port", String(port), "--title", title];
|
|
272
|
+
// 每会话独立 user-data-dir(WebView2 profile 隔离);未提供则不传(回落 WebView2 默认目录)
|
|
273
|
+
if (dataDir)
|
|
274
|
+
args.push("--user-data-dir", dataDir);
|
|
275
|
+
// 推送式投递:注册**本会话**的通知地址 → 通知按 sid 归属
|
|
276
|
+
const notifyUrl = getNotifyUrlForSession(sid);
|
|
277
|
+
if (notifyUrl)
|
|
278
|
+
args.push("--notify-url", notifyUrl);
|
|
279
|
+
let proc;
|
|
280
|
+
try {
|
|
281
|
+
proc = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
// spawn 同步失败(如文件被锁):换不含路径的文案,避免绝对路径经错误消息回流模型
|
|
285
|
+
log.error(`spawn bt-shell failed: ${e.message}`, e);
|
|
286
|
+
throw new Error(tf("client.spawn_failed"));
|
|
287
|
+
}
|
|
288
|
+
attachStdio(proc, sid);
|
|
289
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
290
|
+
try {
|
|
291
|
+
await waitForReady(baseUrl, tf("client.service_timeout"));
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
// 启动超时(常见:端口被别的进程占住 → bind 失败 → 永远不就绪):杀掉本次子进程换端口重来
|
|
295
|
+
lastErr = e;
|
|
296
|
+
log.error(`[session] sid=${sid} port=${port} not ready (attempt ${attempt}/${PORT_START_ATTEMPTS}); killing that pid and retrying`);
|
|
297
|
+
await terminateOwnProcess(proc);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
// 就绪:把本会话的通知地址注册给该实例(推送式投递)
|
|
301
|
+
await registerNotifyUrl(baseUrl, sid);
|
|
302
|
+
log.info(`[session] sid=${sid} ready on port ${port} (title="${title}", dataDir=${dataDir || "(default)"}, attempt ${attempt})`);
|
|
303
|
+
return { sid, proc, baseUrl, port, dataDir, title, ready: true, attach: false };
|
|
304
|
+
}
|
|
305
|
+
throw lastErr instanceof Error ? lastErr : new Error(tf("client.service_timeout"));
|
|
281
306
|
}
|
|
282
|
-
/**
|
|
283
|
-
|
|
284
|
-
|
|
307
|
+
/** 附着到外部已运行的 shell(所有 sid 共用;不 spawn、不 kill、放弃会话隔离) */
|
|
308
|
+
async function attachToService(baseUrl, sid) {
|
|
309
|
+
log.info(`Attaching to existing bt-shell at ${baseUrl} (no spawn; session isolation disabled in attach mode)`);
|
|
310
|
+
await waitForReady(baseUrl, tf("client.attach_timeout", { url: baseUrl }));
|
|
311
|
+
const inst = {
|
|
312
|
+
sid,
|
|
313
|
+
proc: null,
|
|
314
|
+
baseUrl,
|
|
315
|
+
port: Number(new URL(baseUrl).port || 0),
|
|
316
|
+
dataDir: "",
|
|
317
|
+
title: "(external)",
|
|
318
|
+
ready: true,
|
|
319
|
+
attach: true,
|
|
320
|
+
};
|
|
321
|
+
log.info(`Attached to existing bt-shell at ${baseUrl}`);
|
|
322
|
+
return inst;
|
|
285
323
|
}
|
|
286
324
|
/**
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
325
|
+
* 确保某会话的实例存在并就绪(懒启动;并发调用复用同一启动 Promise)
|
|
326
|
+
*
|
|
327
|
+
* **已关闭语义(用户口径)**:用户 `close` 或手动点 X 之后,该 sid 进入「已关闭」态
|
|
328
|
+
* (`closedSids` 置位)—— 之后的**工具调用一律不 spawn**,只返回指引,必须由
|
|
329
|
+
* `open_window`(唯一打开入口,`allowClosed=true` 且先清标记)显式打开。
|
|
290
330
|
*/
|
|
291
|
-
export async function
|
|
292
|
-
|
|
293
|
-
|
|
331
|
+
export async function ensureInstance(explicitSid, opts) {
|
|
332
|
+
const sid = resolveSessionId(explicitSid);
|
|
333
|
+
const allowClosed = opts?.allowClosed === true;
|
|
334
|
+
// 已关闭态:不 spawn、不 attach,直接给指引(唯一例外是 open_window 的显式打开)
|
|
335
|
+
if (!allowClosed && closedSids.has(sid)) {
|
|
336
|
+
throw new Error(tf("client.browser_closed"));
|
|
337
|
+
}
|
|
338
|
+
// 附着模式:外部 shell 单例,所有 sid 共用(连接一次,之后直接返回)
|
|
339
|
+
const attachUrl = resolveAttachBaseUrl();
|
|
340
|
+
if (attachUrl) {
|
|
341
|
+
if (attachInstance?.ready)
|
|
342
|
+
return attachInstance;
|
|
343
|
+
const existing = sessions.get(sid);
|
|
344
|
+
if (existing?.attach)
|
|
345
|
+
return existing;
|
|
346
|
+
const inst = await attachToService(attachUrl, sid);
|
|
347
|
+
// P3-①:附着期间该 sid 被关闭 → 只解本地关联(外部进程不归插件管,绝不 kill)
|
|
348
|
+
if (closedSids.has(sid)) {
|
|
349
|
+
log.info(`[session] sid=${sid} was closed during attach; discarding local association`);
|
|
350
|
+
throw new Error(tf("client.session_closed_during_start"));
|
|
351
|
+
}
|
|
352
|
+
attachInstance = inst;
|
|
353
|
+
sessions.set(sid, inst);
|
|
354
|
+
await fireReady(sid);
|
|
355
|
+
return inst;
|
|
356
|
+
}
|
|
357
|
+
const ready = sessions.get(sid);
|
|
358
|
+
if (ready?.ready)
|
|
359
|
+
return ready;
|
|
360
|
+
const starting = startingSid.get(sid);
|
|
361
|
+
if (starting)
|
|
362
|
+
return starting;
|
|
363
|
+
const cfg = serviceConfig;
|
|
364
|
+
if (!cfg)
|
|
365
|
+
throw new Error(tf("client.not_configured"));
|
|
366
|
+
const p = (async () => {
|
|
367
|
+
const shell = await resolveShellPath();
|
|
368
|
+
const inst = await spawnForSession(sid, shell);
|
|
369
|
+
// P3-①:启动期间该 sid 被 closeSession/closeAllSessions 关闭 → 立即自毁刚起的 shell,不注册。
|
|
370
|
+
// 注意**不删** closedSids:用户已表达关闭意图,后续工具调用仍应指引 open_window(不自动重开)
|
|
371
|
+
if (closedSids.has(sid)) {
|
|
372
|
+
log.info(`[session] sid=${sid} was closed during startup; terminating freshly spawned pid=${inst.proc?.pid ?? "?"}`);
|
|
373
|
+
await terminateOwnProcess(inst.proc);
|
|
374
|
+
throw new Error(tf("client.session_closed_during_start"));
|
|
375
|
+
}
|
|
376
|
+
sessions.set(sid, inst);
|
|
377
|
+
await fireReady(sid);
|
|
378
|
+
return inst;
|
|
379
|
+
})().finally(() => {
|
|
380
|
+
startingSid.delete(sid);
|
|
381
|
+
});
|
|
382
|
+
startingSid.set(sid, p);
|
|
383
|
+
return p;
|
|
384
|
+
}
|
|
385
|
+
/** 实例就绪后的统一回调(插件侧用于对该 sid 做初始 drain) */
|
|
386
|
+
async function fireReady(sid) {
|
|
387
|
+
try {
|
|
388
|
+
serviceReadyHandler?.(sid);
|
|
389
|
+
}
|
|
390
|
+
catch (e) {
|
|
391
|
+
log.error("[notify] service-ready handler failed", e);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/** 把某会话的通知地址注册给该实例(/api/notify-url);直接 fetch,避免 callApi 触发 ensure 递归 */
|
|
395
|
+
async function registerNotifyUrl(baseUrl, sid) {
|
|
396
|
+
const url = getNotifyUrlForSession(sid);
|
|
397
|
+
if (!url)
|
|
398
|
+
return;
|
|
399
|
+
try {
|
|
400
|
+
const res = await fetch(`${baseUrl}/api/notify-url`, {
|
|
401
|
+
method: "POST",
|
|
402
|
+
headers: { "Content-Type": "application/json" },
|
|
403
|
+
body: JSON.stringify({ url }),
|
|
404
|
+
});
|
|
405
|
+
if (res.ok)
|
|
406
|
+
log.info(`[notify] sid=${sid} notify-url registered: ${url}`);
|
|
407
|
+
else
|
|
408
|
+
log.error(`[notify] sid=${sid} register failed: HTTP ${res.status}`);
|
|
409
|
+
}
|
|
410
|
+
catch (e) {
|
|
411
|
+
log.error("[notify] register failed", e);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* 关闭某会话的实例:优雅(/api/close)→ 等退出 → 超时才 SIGTERM(仅该实例自己的句柄/PID)→ 从注册表移除
|
|
416
|
+
* 语义保证:实例不存在则**直接返回,绝不因此 spawn**;附着模式只解除本地关联,外部进程不动。
|
|
417
|
+
*/
|
|
418
|
+
export async function closeSession(explicitSid) {
|
|
419
|
+
const sid = resolveSessionId(explicitSid);
|
|
420
|
+
// P3-①:先置关闭标记 —— 即使实例尚不存在(启动进行中),启动链完成后也会据此自毁,不留孤儿
|
|
421
|
+
closedSids.add(sid);
|
|
422
|
+
const inst = sessions.get(sid) || (attachInstance && attachInstance.sid === sid ? attachInstance : null);
|
|
423
|
+
if (!inst) {
|
|
424
|
+
log.info(`[session] sid=${sid} has no shell instance; nothing to close (never spawn on close)`);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
sessions.delete(inst.sid);
|
|
428
|
+
// 已关闭态保留 closedSids:后续工具调用不再自动重开,须 open_window 显式打开
|
|
429
|
+
if (attachInstance === inst)
|
|
430
|
+
attachInstance = null;
|
|
431
|
+
if (inst.attach) {
|
|
432
|
+
// 附着模式:外部 shell 进程不归插件管,**绝不 kill**,只清本地关联
|
|
433
|
+
log.info(`Detached from external bt-shell at ${inst.baseUrl} (process left running)`);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
await fetch(`${inst.baseUrl}/api/close`, {
|
|
438
|
+
method: "POST",
|
|
439
|
+
headers: { "Content-Type": "application/json" },
|
|
440
|
+
body: "{}",
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
// 进程可能已自行退出;下面的 waitForExit 会兜住
|
|
445
|
+
}
|
|
446
|
+
await terminateOwnProcess(inst.proc);
|
|
447
|
+
log.info(`[session] sid=${sid} closed (port=${inst.port})`);
|
|
448
|
+
}
|
|
449
|
+
/** 关闭全部实例(插件 dispose / 退出);只按注册表 PID,绝不按名 */
|
|
450
|
+
export async function closeAllSessions() {
|
|
451
|
+
const sids = [...sessions.keys()];
|
|
452
|
+
for (const sid of sids) {
|
|
453
|
+
await closeSession(sid);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
/** 兼容旧名:确保默认/当前会话的实例存在(现语义 = 懒启动该 sid 的实例) */
|
|
457
|
+
export async function ensureService(sid) {
|
|
458
|
+
await ensureInstance(sid);
|
|
459
|
+
}
|
|
460
|
+
/** 清「已关闭」标记(会话删除时用,避免集合无限增长;open_window 亦会清) */
|
|
461
|
+
export function clearClosedState(sid) {
|
|
462
|
+
closedSids.delete(sid);
|
|
463
|
+
}
|
|
464
|
+
/** 打开浏览器窗口(未启动则启动该会话实例;已启动幂等) */
|
|
465
|
+
export async function openWindow(sid) {
|
|
466
|
+
// 唯一打开入口:显式清「已关闭」标记后再启动
|
|
467
|
+
const s = resolveSessionId(sid);
|
|
468
|
+
closedSids.delete(s);
|
|
469
|
+
await ensureInstance(s, { allowClosed: true });
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* 纯查询:探测某会话的 shell 是否在运行,**绝不 spawn**。
|
|
473
|
+
* sid 未给 → 先探当前会话,再探任一已就绪实例;都没有则返回 null。
|
|
474
|
+
* 用于 get_browser_status 这类只读命令,避免查询也弹出浏览器窗口。
|
|
475
|
+
*/
|
|
476
|
+
export async function probeStatus(timeoutMs = 1500, sid) {
|
|
477
|
+
const targets = [];
|
|
478
|
+
if (sid) {
|
|
479
|
+
const inst = sessions.get(resolveSessionId(sid));
|
|
480
|
+
if (inst?.ready)
|
|
481
|
+
targets.push(inst.baseUrl);
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
const cur = sessions.get(resolveSessionId());
|
|
485
|
+
if (cur?.ready)
|
|
486
|
+
targets.push(cur.baseUrl);
|
|
487
|
+
for (const inst of sessions.values()) {
|
|
488
|
+
if (inst.ready && !targets.includes(inst.baseUrl))
|
|
489
|
+
targets.push(inst.baseUrl);
|
|
490
|
+
}
|
|
491
|
+
if (attachInstance?.ready && !targets.includes(attachInstance.baseUrl))
|
|
492
|
+
targets.push(attachInstance.baseUrl);
|
|
493
|
+
}
|
|
494
|
+
for (const baseUrl of targets) {
|
|
495
|
+
const r = await probeOnce(baseUrl, timeoutMs);
|
|
496
|
+
if (r)
|
|
497
|
+
return r;
|
|
498
|
+
}
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
/** 对单个端点做一次短超时探测 */
|
|
502
|
+
async function probeOnce(baseUrl, timeoutMs) {
|
|
294
503
|
const ac = new AbortController();
|
|
295
504
|
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
296
505
|
try {
|
|
297
|
-
const res = await fetch(`${
|
|
506
|
+
const res = await fetch(`${baseUrl}/api/status`, {
|
|
298
507
|
method: "POST",
|
|
299
508
|
headers: { "Content-Type": "application/json" },
|
|
300
509
|
body: "{}",
|
|
@@ -312,6 +521,74 @@ export async function probeStatus(timeoutMs = 1500) {
|
|
|
312
521
|
clearTimeout(timer);
|
|
313
522
|
}
|
|
314
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* 判断是否为**连接层**错误(shell 进程已死/端口没人听 → fetch 直接抛)。
|
|
526
|
+
* 只认这类;HTTP 4xx/5xx 不算(它们不会抛错,而是 res.ok=false → 走 json.success 分支)。
|
|
527
|
+
*/
|
|
528
|
+
function isConnectionError(e) {
|
|
529
|
+
if (!(e instanceof Error))
|
|
530
|
+
return false;
|
|
531
|
+
// undici/node 的连接失败:message = "fetch failed",真实原因在 cause.code;部分场景直接带码
|
|
532
|
+
const code = String(e?.cause?.code || e?.code || "");
|
|
533
|
+
if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR|ETIMEDOUT/.test(code)) {
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
// 退化:message 里出现连接类字样(不同 node/undici 版本的文案差异)
|
|
537
|
+
return /fetch failed|socket hang up|other side closed|connect ECONN|network error/i.test(e.message);
|
|
538
|
+
}
|
|
539
|
+
/** 把一个已死实例从注册表摘除并回收残留句柄(只按该实例自己的句柄/PID,绝不按名) */
|
|
540
|
+
async function markInstanceDead(sid, inst) {
|
|
541
|
+
// 只在注册项仍指向该实例时删除(避免误删之后由 open_window 重新注册的新实例)
|
|
542
|
+
if (sessions.get(sid) === inst)
|
|
543
|
+
sessions.delete(sid);
|
|
544
|
+
if (attachInstance === inst)
|
|
545
|
+
attachInstance = null;
|
|
546
|
+
if (inst.proc)
|
|
547
|
+
await terminateOwnProcess(inst.proc);
|
|
548
|
+
}
|
|
549
|
+
/** 发一次 POST 并解析 {success,data};连接层错误直接抛(fetch 的 TypeError 等) */
|
|
550
|
+
async function postJson(baseUrl, path, payload) {
|
|
551
|
+
const res = await fetch(`${baseUrl}${path}`, {
|
|
552
|
+
method: "POST",
|
|
553
|
+
headers: { "Content-Type": "application/json" },
|
|
554
|
+
body: JSON.stringify(payload ?? {}),
|
|
555
|
+
});
|
|
556
|
+
const json = await res.json();
|
|
557
|
+
if (!json.success)
|
|
558
|
+
throw new Error(json.error || tf("client.service_error"));
|
|
559
|
+
return json.data;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* 统一 API 调用:按 sid 路由到该会话的实例(懒启动)。
|
|
563
|
+
* sid 来源:显式 sessionId 参数 > body._sessionId > 钩子缓存兜底 > "default" 桶。
|
|
564
|
+
*
|
|
565
|
+
* P3-②:连接层错误(手关窗口/进程被杀)→ 标记实例死亡 + 置「已关闭」态 → 抛 `client.browser_closed`
|
|
566
|
+
* 指引,**绝不自动重开**(唯一打开入口是 `open_window`)。**例外**:
|
|
567
|
+
* - 附着模式:外部进程不归插件管 → 只报 `client.attach_gone`,不动任何进程;
|
|
568
|
+
* - get_browser_status(走 probeStatus/probeOnce,不经本函数)保持纯查询,不 spawn;
|
|
569
|
+
* - HTTP 4xx/5xx 不算连接错误,原样抛服务端错误。
|
|
570
|
+
*/
|
|
571
|
+
async function callApi(path, body, sessionId) {
|
|
572
|
+
const sid = resolveSessionId(sessionId || (body && body._sessionId));
|
|
573
|
+
const inst = await ensureInstance(sid);
|
|
574
|
+
const payload = { ...(body || {}), _sessionId: sid };
|
|
575
|
+
try {
|
|
576
|
+
return await postJson(inst.baseUrl, path, payload);
|
|
577
|
+
}
|
|
578
|
+
catch (e) {
|
|
579
|
+
if (!isConnectionError(e))
|
|
580
|
+
throw e;
|
|
581
|
+
if (inst.attach) {
|
|
582
|
+
// 附着模式:不拥有该进程,只报明确错误(不 respawn)
|
|
583
|
+
throw new Error(tf("client.attach_gone", { url: inst.baseUrl }));
|
|
584
|
+
}
|
|
585
|
+
log.error(`[session] sid=${sid} instance dead (port=${inst.port}, pid=${inst.proc?.pid ?? "?"}): ${e.message}; marking closed`);
|
|
586
|
+
await markInstanceDead(sid, inst);
|
|
587
|
+
// 用户口径:手动关窗**绝不自动重开** → 置位「已关闭」态,指引显式 open_window(不做 respawn 重试)
|
|
588
|
+
closedSids.add(sid);
|
|
589
|
+
throw new Error(tf("client.browser_closed"));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
315
592
|
function cmd(name) {
|
|
316
593
|
return (params, sessionId) => callApi(`/api/${name}`, params, sessionId);
|
|
317
594
|
}
|
|
@@ -359,6 +636,7 @@ export const service = {
|
|
|
359
636
|
assertResponse: cmd("assert-response"),
|
|
360
637
|
panelConfig: cmd("panel-config"),
|
|
361
638
|
status: cmd("status"),
|
|
639
|
+
title: cmd("title"),
|
|
362
640
|
tabs: cmd("tabs"),
|
|
363
641
|
annotateToggle: cmd("annotate/toggle"),
|
|
364
642
|
annotateRecords: cmd("annotate/records"),
|