@xiaoqiong0v0/opencode-browser-tool 1.7.0 → 1.10.1
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 +45 -26
- package/dist/binary.js +27 -10
- package/dist/client.js +682 -200
- package/dist/config/index.js +96 -17
- package/dist/i18n/en.js +132 -48
- package/dist/i18n/index.js +15 -11
- package/dist/i18n/zh.js +132 -48
- package/dist/index.js +320 -177
- package/dist/notify-server.js +26 -7
- package/dist/util/sanitize.js +73 -0
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -1,15 +1,32 @@
|
|
|
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";
|
|
8
|
+
import { randomBytes } from "crypto";
|
|
2
9
|
import { resolve, dirname } from "path";
|
|
3
10
|
import { existsSync } from "fs";
|
|
4
11
|
import { fileURLToPath } from "url";
|
|
5
12
|
import { log } from "./logger.js";
|
|
6
|
-
import {
|
|
13
|
+
import { getNotifyUrlForSession } from "./notify-server.js";
|
|
14
|
+
import { tf } from "./i18n/index.js";
|
|
7
15
|
import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
|
|
16
|
+
import { sanitizeForModel } from "./util/sanitize.js";
|
|
8
17
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
18
|
/** 就绪轮询超时(ms) */
|
|
10
19
|
const READY_TIMEOUT_MS = 20000;
|
|
11
20
|
/** 就绪轮询间隔(ms) */
|
|
12
21
|
const READY_POLL_INTERVAL_MS = 300;
|
|
22
|
+
/** 端口撞车/启动失败时的重试次数(每次换一个随机端口) */
|
|
23
|
+
const PORT_START_ATTEMPTS = 5;
|
|
24
|
+
/** 会话标题解析上限(ms):超时就用 sid 后缀,绝不因标题卡住启动 */
|
|
25
|
+
const TITLE_RESOLVE_TIMEOUT_MS = 250;
|
|
26
|
+
/** HTTP 401 Unauthorized:shell 明确判定令牌不匹配(rust/src/http.rs 的 auth_error) */
|
|
27
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
28
|
+
/** HTTP 403 Forbidden:shell 明确拒绝该请求(带 Origin 的跨源请求) */
|
|
29
|
+
const HTTP_FORBIDDEN = 403;
|
|
13
30
|
/** opencode 应用/项目目录(插件初始化与工具上下文提供);用于定位本地 Rust 开发构建 */
|
|
14
31
|
let appDirectory = "";
|
|
15
32
|
/** 记录 opencode 目录(插件初始化 / 工具调用时调用) */
|
|
@@ -24,7 +41,7 @@ export function setAppDirectory(dir) {
|
|
|
24
41
|
export function resolveShellBinary() {
|
|
25
42
|
const platform = process.platform === "win32" ? "win-x64" : "linux-x64";
|
|
26
43
|
const bin = process.platform === "win32" ? "bt-shell.exe" : "bt-shell";
|
|
27
|
-
// 1) 显式指定:最优先(
|
|
44
|
+
// 1) 显式指定:最优先(即使文件暂不存在也返回,由启动链路 resolveShellPath 给出明确错误)
|
|
28
45
|
const envPath = process.env.BT_SHELL_PATH;
|
|
29
46
|
if (envPath)
|
|
30
47
|
return { path: envPath, source: "env" };
|
|
@@ -46,7 +63,7 @@ export function resolveShellBinary() {
|
|
|
46
63
|
if (p && existsSync(p))
|
|
47
64
|
return { path: p, source };
|
|
48
65
|
}
|
|
49
|
-
// 5) 下载缓存(未下载时由
|
|
66
|
+
// 5) 下载缓存(未下载时由 resolveShellPath 先 ensureBinary)
|
|
50
67
|
return { path: cachedBinaryPath(), source: "download-cache" };
|
|
51
68
|
}
|
|
52
69
|
/** 解析附着模式目标地址:BT_SHELL_URL 优先,其次 BT_SHELL_PORT;均未设置返回 null */
|
|
@@ -59,175 +76,133 @@ function resolveAttachBaseUrl() {
|
|
|
59
76
|
return `http://127.0.0.1:${port}`;
|
|
60
77
|
return null;
|
|
61
78
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
79
|
+
/** 附着模式令牌:由 BT_SHELL_TOKEN 提供(外部 shell 须用同一值启动);缺失直接抛明确错误 */
|
|
80
|
+
function requireAttachToken() {
|
|
81
|
+
const token = process.env.BT_SHELL_TOKEN?.trim();
|
|
82
|
+
if (!token)
|
|
83
|
+
throw new Error(tf("client.attach_need_token"));
|
|
84
|
+
return token;
|
|
85
|
+
}
|
|
86
|
+
/** 实例注册表:每会话一个 shell;并发启动保护见 startingSid */
|
|
87
|
+
const sessions = new Map();
|
|
88
|
+
/** 正在启动中的会话 → Promise(并发保护:同一 sid 多个工具同时调用只启动一次) */
|
|
89
|
+
const startingSid = new Map();
|
|
90
|
+
/** 已请求关闭的会话(P3-①):close 与启动并发时置位,启动链完成后据此自毁,避免孤儿窗口 */
|
|
91
|
+
const closedSids = new Set();
|
|
92
|
+
/** 附着模式共享实例(外部 shell;所有 sid 共用,放弃会话隔离) */
|
|
93
|
+
let attachInstance = null;
|
|
94
|
+
/**
|
|
95
|
+
* 附着模式下**已注册过** notify-url 的 `baseUrl|sid`(去重,避免重复 POST)
|
|
96
|
+
*
|
|
97
|
+
* 语义:`/api/notify-url` 在 shell 侧是**全局单值**(见 rust/src/service.rs 的 set_notify_url),
|
|
98
|
+
* 待发送队列(state.sent_records)也是**全局唯一**的。附着模式只共享一个 shell ⇒ 队列全局,
|
|
99
|
+
* drain 由 notify URL 里带的 sid 执行(后注册的 sid 覆盖前一个,与「按 sid 分发」不同)。
|
|
100
|
+
*/
|
|
101
|
+
const attachNotifyRegistered = new Set();
|
|
102
|
+
/**
|
|
103
|
+
* 同一 key 的注册**进行中** Promise:并发 ensure 共享同一次 POST(第二个调用 await 第一个结果,
|
|
104
|
+
* 而不是直接返回)。失败时只删这里,使下一次调用能重试;成功才写入 attachNotifyRegistered。
|
|
105
|
+
*/
|
|
106
|
+
const attachNotifyInFlight = new Map();
|
|
107
|
+
/** notify-url 注册失败后的重试延迟(ms) */
|
|
108
|
+
const NOTIFY_RETRY_DELAY_MS = 300;
|
|
109
|
+
/** 服务启动参数(configureService 保存,懒启动时使用) */
|
|
69
110
|
let serviceConfig = null;
|
|
70
|
-
/**
|
|
71
|
-
let
|
|
111
|
+
/** 会话 id 兜底解析器(钩子缓存):工具调用没带 _sessionId 时用它 */
|
|
112
|
+
let sessionIdResolver = null;
|
|
113
|
+
/** 可选会话标题解析器(client.session.get 之类);拿不到/超时回退 sid 后缀,不阻塞启动 */
|
|
114
|
+
let titleResolver = null;
|
|
115
|
+
/** 实例就绪回调(插件注册:对该 sid 做一次初始 drain) */
|
|
116
|
+
let serviceReadyHandler = null;
|
|
72
117
|
/** 保存服务启动参数(插件加载时调用,不立即启动窗口) */
|
|
73
118
|
export function configureService(opts) {
|
|
74
119
|
serviceConfig = opts;
|
|
75
120
|
}
|
|
76
|
-
/**
|
|
77
|
-
export function
|
|
78
|
-
|
|
79
|
-
serviceConfig.userDataDir = dir;
|
|
121
|
+
/** 注册会话 id 兜底解析器(通常指向插件的钩子缓存 sessionCache.get) */
|
|
122
|
+
export function setSessionIdResolver(fn) {
|
|
123
|
+
sessionIdResolver = fn;
|
|
80
124
|
}
|
|
81
|
-
/**
|
|
82
|
-
|
|
83
|
-
|
|
125
|
+
/** 注册可选的会话标题解析器(返回 null/抛错则用 sid 后缀;有 250ms 上限,不阻塞启动) */
|
|
126
|
+
export function setTitleResolver(fn) {
|
|
127
|
+
titleResolver = fn;
|
|
128
|
+
}
|
|
129
|
+
/** 注册实例就绪回调(spawn/附着成功且注册 notify-url 之后,按 sid 调用一次) */
|
|
84
130
|
export function setServiceReadyHandler(cb) {
|
|
85
131
|
serviceReadyHandler = cb;
|
|
86
132
|
}
|
|
87
|
-
/**
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (attachUrl) {
|
|
96
|
-
starting = attachToService(attachUrl).finally(() => {
|
|
97
|
-
starting = null;
|
|
98
|
-
});
|
|
99
|
-
}
|
|
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();
|
|
133
|
+
/**
|
|
134
|
+
* 解析本次调用的会话 id:显式参数 > 请求体 _sessionId > 钩子缓存兜底 > "default" 桶
|
|
135
|
+
* "default" 桶用于拿不到任何 sid 的场景(仍有独立实例,不会与其它会话互踩)
|
|
136
|
+
*/
|
|
137
|
+
export function resolveSessionId(explicit) {
|
|
138
|
+
const s = (explicit || "").trim();
|
|
139
|
+
if (s)
|
|
140
|
+
return s;
|
|
112
141
|
try {
|
|
113
|
-
|
|
142
|
+
const cached = sessionIdResolver?.() || "";
|
|
143
|
+
if (cached.trim())
|
|
144
|
+
return cached.trim();
|
|
114
145
|
}
|
|
115
|
-
catch
|
|
116
|
-
|
|
146
|
+
catch {
|
|
147
|
+
// 解析器异常不阻断调用
|
|
117
148
|
}
|
|
149
|
+
return "default";
|
|
118
150
|
}
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
151
|
+
/** 该会话实例是否就绪(不给 sid 则任一实例就绪即 true) */
|
|
152
|
+
export function isRunning(sid) {
|
|
153
|
+
if (sid) {
|
|
154
|
+
const s = resolveSessionId(sid);
|
|
155
|
+
if (sessions.get(s)?.ready)
|
|
156
|
+
return true;
|
|
157
|
+
return !!attachInstance?.ready;
|
|
158
|
+
}
|
|
159
|
+
for (const inst of sessions.values())
|
|
160
|
+
if (inst.ready)
|
|
161
|
+
return true;
|
|
162
|
+
return !!attachInstance?.ready;
|
|
163
|
+
}
|
|
164
|
+
/** 组装窗口标题:优先会话标题(有界等待),拿不到用 sid 后 6 位,保证任务栏可分辨 */
|
|
165
|
+
async function resolveWindowTitle(sid) {
|
|
166
|
+
const suffix = sid.length > 6 ? sid.slice(-6) : sid || "main";
|
|
167
|
+
const fallback = `bt-shell · ${suffix}`;
|
|
168
|
+
if (!titleResolver)
|
|
169
|
+
return fallback;
|
|
124
170
|
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}`);
|
|
171
|
+
const t = await Promise.race([
|
|
172
|
+
Promise.resolve().then(() => titleResolver(sid)),
|
|
173
|
+
new Promise((r) => setTimeout(() => r(null), TITLE_RESOLVE_TIMEOUT_MS)),
|
|
174
|
+
]);
|
|
175
|
+
if (t && t.trim())
|
|
176
|
+
return `bt-shell · ${t.trim()}`;
|
|
134
177
|
}
|
|
135
|
-
catch
|
|
136
|
-
|
|
178
|
+
catch {
|
|
179
|
+
// 标题拿不到就用后缀,绝不因此失败
|
|
137
180
|
}
|
|
181
|
+
return fallback;
|
|
138
182
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
if (!json.success)
|
|
150
|
-
throw new Error(json.error || "Service error");
|
|
151
|
-
return json.data;
|
|
152
|
-
}
|
|
153
|
-
/** 轮询等待服务就绪(READY_TIMEOUT_MS 超时);超时抛出给定提示 */
|
|
154
|
-
async function waitForReady(baseUrl, timeoutMessage) {
|
|
183
|
+
/**
|
|
184
|
+
* 轮询等待服务就绪(READY_TIMEOUT_MS 超时);超时抛出给定提示。
|
|
185
|
+
*
|
|
186
|
+
* `authHint`(仅附着模式传 true):401/403 是**确定性失败** —— shell 已经起来并明确拒绝鉴权,
|
|
187
|
+
* 令牌不一致在它启动那一刻就定死了,重试到超时也永远不会变成 200,继续轮询只会白等
|
|
188
|
+
* READY_TIMEOUT_MS(20s)再报一句无关的超时。因此一旦拿到 401/403 立即抛鉴权错误。
|
|
189
|
+
* spawn 路径不传(authHint=false):令牌由插件自己随机生成并原样透传 --token,
|
|
190
|
+
* 出现 401 属异常(端口上坐着别的进程等),保持原有"继续重试→超时"路径。
|
|
191
|
+
*/
|
|
192
|
+
async function waitForReady(baseUrl, token, timeoutMessage, authHint = false) {
|
|
155
193
|
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
156
194
|
while (Date.now() < deadline) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
catch {
|
|
167
|
-
// 服务未启动,继续等待
|
|
168
|
-
}
|
|
195
|
+
// 就绪语义:只有 ok 算起来;transport(端口还没监听)、server/badjson 都属于
|
|
196
|
+
// 「还没可用」继续等;auth 在附着模式是确定性失败(令牌写错),立即报错不再空等。
|
|
197
|
+
const out = await httpCall(baseUrl, token, "/api/status", {});
|
|
198
|
+
if (out.kind === "ok")
|
|
199
|
+
return;
|
|
200
|
+
if (out.kind === "auth" && authHint)
|
|
201
|
+
throw new Error(tf("client.attach_bad_token"));
|
|
169
202
|
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
170
203
|
}
|
|
171
204
|
throw new Error(timeoutMessage);
|
|
172
205
|
}
|
|
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
206
|
/** 等待子进程退出(有界超时);已退出/出错返回 true,超时返回 false */
|
|
232
207
|
function waitForExit(proc, timeoutMs) {
|
|
233
208
|
return new Promise((resolveExit) => {
|
|
@@ -246,70 +221,578 @@ function waitForExit(proc, timeoutMs) {
|
|
|
246
221
|
proc.once("error", () => finish(true));
|
|
247
222
|
});
|
|
248
223
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
attachMode = false;
|
|
224
|
+
/**
|
|
225
|
+
* 终止**本插件自己 spawn 的**子进程(先等优雅退出,超时才 SIGTERM 该句柄/PID)。
|
|
226
|
+
* 红线:只允许杀自己 spawn 的子进程、按句柄/PID —— 绝不按名/通配匹配。
|
|
227
|
+
*/
|
|
228
|
+
async function terminateOwnProcess(proc) {
|
|
229
|
+
if (!proc)
|
|
256
230
|
return;
|
|
231
|
+
const exited = await waitForExit(proc, 5000);
|
|
232
|
+
if (exited) {
|
|
233
|
+
log.info(`bt-shell pid=${proc.pid} exited gracefully`);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
log.info(`bt-shell pid=${proc.pid} did not exit within 5s; sending SIGTERM to that pid`);
|
|
237
|
+
try {
|
|
238
|
+
proc.kill("SIGTERM");
|
|
257
239
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
240
|
+
catch { }
|
|
241
|
+
await waitForExit(proc, 2000);
|
|
242
|
+
}
|
|
243
|
+
/** 把 shell 的 stdout/stderr 转发进共享日志(Rust println! 默认会被管道吞掉) */
|
|
244
|
+
function attachStdio(proc, sid) {
|
|
245
|
+
const forwardShell = (tag) => (chunk) => {
|
|
246
|
+
for (const line of chunk.toString().split(/\r?\n/)) {
|
|
247
|
+
const s = line.trim();
|
|
248
|
+
if (s)
|
|
249
|
+
log.info(`[${tag}][sid=${sid}] ${s}`);
|
|
264
250
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
251
|
+
};
|
|
252
|
+
proc.stdout?.on("data", forwardShell("shell:out"));
|
|
253
|
+
proc.stderr?.on("data", forwardShell("shell:err"));
|
|
254
|
+
}
|
|
255
|
+
/** 二进制就绪性检查(不存在则等下载;失败抛明确错误) */
|
|
256
|
+
async function resolveShellPath() {
|
|
257
|
+
const resolved = resolveShellBinary();
|
|
258
|
+
let shell = resolved.path;
|
|
259
|
+
if (!existsSync(shell)) {
|
|
260
|
+
if (process.env.BT_SHELL_PATH) {
|
|
261
|
+
// 只提示环境变量名,不回流绝对路径(路径已在插件日志)
|
|
262
|
+
throw new Error(tf("client.bt_shell_path_missing"));
|
|
263
|
+
}
|
|
264
|
+
const st = await ensureBinary(20000);
|
|
265
|
+
if (st.state !== "ready" || !st.path) {
|
|
266
|
+
throw new Error(describeBinaryStatus(st));
|
|
271
267
|
}
|
|
272
|
-
|
|
268
|
+
shell = st.path;
|
|
273
269
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
attachMode = false;
|
|
270
|
+
log.info(`Shell binary: ${shell} (source=${resolved.source})`);
|
|
271
|
+
return shell;
|
|
277
272
|
}
|
|
278
|
-
/**
|
|
279
|
-
|
|
280
|
-
|
|
273
|
+
/**
|
|
274
|
+
* spawn 一个新 shell 实例(带端口重试):端口撞车/启动超时 → 只杀掉**本次刚 spawn 的**
|
|
275
|
+
* 子进程(按句柄/PID),换随机端口重来,最多 PORT_START_ATTEMPTS 次。
|
|
276
|
+
*/
|
|
277
|
+
async function spawnForSession(sid, shell) {
|
|
278
|
+
const cfg = serviceConfig;
|
|
279
|
+
const dataDir = cfg?.resolveDataDir ? cfg.resolveDataDir(sid) : "";
|
|
280
|
+
const title = await resolveWindowTitle(sid);
|
|
281
|
+
// 本实例的鉴权令牌:16 字节 → 32 hex;端口重试沿用同一令牌(新的子进程仍是同一实例语义)
|
|
282
|
+
const token = randomBytes(16).toString("hex");
|
|
283
|
+
let lastErr = null;
|
|
284
|
+
for (let attempt = 1; attempt <= PORT_START_ATTEMPTS; attempt++) {
|
|
285
|
+
// 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout);随机区间避开常用端口
|
|
286
|
+
const port = 18000 + Math.floor(Math.random() * 1000);
|
|
287
|
+
const args = [
|
|
288
|
+
"--browsers-path",
|
|
289
|
+
cfg?.browsersPath || "",
|
|
290
|
+
"--port",
|
|
291
|
+
String(port),
|
|
292
|
+
"--title",
|
|
293
|
+
title,
|
|
294
|
+
"--token",
|
|
295
|
+
token,
|
|
296
|
+
];
|
|
297
|
+
// 每会话独立 user-data-dir(WebView2 profile 隔离);未提供则不传(回落 WebView2 默认目录)
|
|
298
|
+
if (dataDir)
|
|
299
|
+
args.push("--user-data-dir", dataDir);
|
|
300
|
+
// 推送式投递:注册**本会话**的通知地址 → 通知按 sid 归属
|
|
301
|
+
const notifyUrl = getNotifyUrlForSession(sid);
|
|
302
|
+
if (notifyUrl)
|
|
303
|
+
args.push("--notify-url", notifyUrl);
|
|
304
|
+
let proc;
|
|
305
|
+
try {
|
|
306
|
+
proc = spawn(shell, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
307
|
+
}
|
|
308
|
+
catch (e) {
|
|
309
|
+
// spawn 同步失败(如文件被锁):换不含路径的文案,避免绝对路径经错误消息回流模型
|
|
310
|
+
log.error(`spawn bt-shell failed: ${e.message}`, e);
|
|
311
|
+
throw new Error(tf("client.spawn_failed"));
|
|
312
|
+
}
|
|
313
|
+
attachStdio(proc, sid);
|
|
314
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
315
|
+
try {
|
|
316
|
+
// authHint 默认 false:spawn 的令牌是插件本会话随机生成并随 --token 传下去的,
|
|
317
|
+
// 不该出现 401;真出现(如端口被别的进程占住)属于"没起来"一类,走换端口重试而不是鉴权报错
|
|
318
|
+
await waitForReady(baseUrl, token, tf("client.service_timeout"));
|
|
319
|
+
}
|
|
320
|
+
catch (e) {
|
|
321
|
+
// 启动超时(常见:端口被别的进程占住 → bind 失败 → 永远不就绪):杀掉本次子进程换端口重来
|
|
322
|
+
lastErr = e;
|
|
323
|
+
log.error(`[session] sid=${sid} port=${port} not ready (attempt ${attempt}/${PORT_START_ATTEMPTS}); killing that pid and retrying`);
|
|
324
|
+
await terminateOwnProcess(proc);
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
// 就绪:把本会话的通知地址注册给该实例(推送式投递;失败重试一次,不影响工具调用成功)
|
|
328
|
+
const notifyOk = await registerNotifyUrl(baseUrl, sid, token);
|
|
329
|
+
if (!notifyOk) {
|
|
330
|
+
await new Promise((r) => setTimeout(r, NOTIFY_RETRY_DELAY_MS));
|
|
331
|
+
const retried = await registerNotifyUrl(baseUrl, sid, token);
|
|
332
|
+
if (!retried)
|
|
333
|
+
log.error(`[notify] sid=${sid} notify-url registration failed after retry (delivery may be degraded)`);
|
|
334
|
+
}
|
|
335
|
+
log.info(`[session] sid=${sid} ready on port ${port} (title="${title}", dataDir=${dataDir || "(default)"}, attempt ${attempt})`);
|
|
336
|
+
return { sid, proc, baseUrl, port, token, dataDir, title, ready: true, attach: false };
|
|
337
|
+
}
|
|
338
|
+
throw lastErr instanceof Error ? lastErr : new Error(tf("client.service_timeout"));
|
|
281
339
|
}
|
|
282
|
-
/**
|
|
283
|
-
|
|
284
|
-
|
|
340
|
+
/** 附着到外部已运行的 shell(所有 sid 共用;不 spawn、不 kill、放弃会话隔离) */
|
|
341
|
+
async function attachToService(baseUrl, sid) {
|
|
342
|
+
// 令牌必须先有:缺失时直接报错,不去连一个注定 401 的端点
|
|
343
|
+
const token = requireAttachToken();
|
|
344
|
+
log.info(`Attaching to existing bt-shell at ${baseUrl} (no spawn; session isolation disabled in attach mode)`);
|
|
345
|
+
// authHint=true:令牌来自 BT_SHELL_TOKEN(与外部 shell 的启动令牌是两处配置),
|
|
346
|
+
// 401/403 说明两边不一致 → 立即报鉴权失败,不等 20s 超时
|
|
347
|
+
await waitForReady(baseUrl, token, tf("client.attach_timeout", { url: baseUrl }), true);
|
|
348
|
+
const inst = {
|
|
349
|
+
sid,
|
|
350
|
+
proc: null,
|
|
351
|
+
baseUrl,
|
|
352
|
+
port: Number(new URL(baseUrl).port || 0),
|
|
353
|
+
token,
|
|
354
|
+
dataDir: "",
|
|
355
|
+
title: "(external)",
|
|
356
|
+
ready: true,
|
|
357
|
+
attach: true,
|
|
358
|
+
};
|
|
359
|
+
log.info(`Attached to existing bt-shell at ${baseUrl}`);
|
|
360
|
+
return inst;
|
|
285
361
|
}
|
|
286
362
|
/**
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
363
|
+
* 确保某会话的实例存在并就绪(懒启动;并发调用复用同一启动 Promise)
|
|
364
|
+
*
|
|
365
|
+
* **已关闭语义(用户口径)**:用户 `close` 或手动点 X 之后,该 sid 进入「已关闭」态
|
|
366
|
+
* (`closedSids` 置位)—— 之后的**工具调用一律不 spawn**,只返回指引,必须由
|
|
367
|
+
* `open_window`(唯一打开入口,`allowClosed=true` 且先清标记)显式打开。
|
|
290
368
|
*/
|
|
291
|
-
export async function
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
369
|
+
export async function ensureInstance(explicitSid, opts) {
|
|
370
|
+
const sid = resolveSessionId(explicitSid);
|
|
371
|
+
const allowClosed = opts?.allowClosed === true;
|
|
372
|
+
// 已关闭态:不 spawn、不 attach,直接给指引(唯一例外是 open_window 的显式打开)
|
|
373
|
+
if (!allowClosed && closedSids.has(sid)) {
|
|
374
|
+
throw new Error(tf("client.browser_closed"));
|
|
375
|
+
}
|
|
376
|
+
// 附着模式:外部 shell 单例,所有 sid 共用(连接一次,之后直接返回)。
|
|
377
|
+
// notify 语义:`/api/notify-url` 在 shell 内是**全局单值**,待发送队列也是**全局唯一**;
|
|
378
|
+
// 附着模式共享同一个 shell ⇒ 队列全局,drain 由 notify URL 里带的 sid 执行。
|
|
379
|
+
// 因此每个 sid 首次走 attach 分支时都必须注册自己的 notify 地址(按 baseUrl+sid 去重)。
|
|
380
|
+
const attachUrl = resolveAttachBaseUrl();
|
|
381
|
+
if (attachUrl) {
|
|
382
|
+
if (attachInstance?.ready) {
|
|
383
|
+
await ensureAttachNotify(attachInstance, sid);
|
|
384
|
+
return attachInstance;
|
|
385
|
+
}
|
|
386
|
+
const existing = sessions.get(sid);
|
|
387
|
+
if (existing?.attach) {
|
|
388
|
+
await ensureAttachNotify(existing, sid);
|
|
389
|
+
return existing;
|
|
390
|
+
}
|
|
391
|
+
const inst = await attachToService(attachUrl, sid);
|
|
392
|
+
// P3-①:附着期间该 sid 被关闭 → 只解本地关联(外部进程不归插件管,绝不 kill)
|
|
393
|
+
if (closedSids.has(sid)) {
|
|
394
|
+
log.info(`[session] sid=${sid} was closed during attach; discarding local association`);
|
|
395
|
+
throw new Error(tf("client.session_closed_during_start"));
|
|
396
|
+
}
|
|
397
|
+
attachInstance = inst;
|
|
398
|
+
sessions.set(sid, inst);
|
|
399
|
+
await ensureAttachNotify(inst, sid);
|
|
400
|
+
await fireReady(sid);
|
|
401
|
+
return inst;
|
|
402
|
+
}
|
|
403
|
+
const ready = sessions.get(sid);
|
|
404
|
+
if (ready?.ready)
|
|
405
|
+
return ready;
|
|
406
|
+
const starting = startingSid.get(sid);
|
|
407
|
+
if (starting)
|
|
408
|
+
return starting;
|
|
409
|
+
const cfg = serviceConfig;
|
|
410
|
+
if (!cfg)
|
|
411
|
+
throw new Error(tf("client.not_configured"));
|
|
412
|
+
const p = (async () => {
|
|
413
|
+
const shell = await resolveShellPath();
|
|
414
|
+
const inst = await spawnForSession(sid, shell);
|
|
415
|
+
// P3-①:启动期间该 sid 被 closeSession/closeAllSessions 关闭 → 立即自毁刚起的 shell,不注册。
|
|
416
|
+
// 注意**不删** closedSids:用户已表达关闭意图,后续工具调用仍应指引 open_window(不自动重开)
|
|
417
|
+
if (closedSids.has(sid)) {
|
|
418
|
+
log.info(`[session] sid=${sid} was closed during startup; terminating freshly spawned pid=${inst.proc?.pid ?? "?"}`);
|
|
419
|
+
await terminateOwnProcess(inst.proc);
|
|
420
|
+
throw new Error(tf("client.session_closed_during_start"));
|
|
421
|
+
}
|
|
422
|
+
sessions.set(sid, inst);
|
|
423
|
+
// P0 竞态收尾:本轮是 open_window 的显式打开 → 成功后清「已关闭」标记。
|
|
424
|
+
// 期间若有并发 callApi 探活失败把 sid 重新置为 closed,这里也要清掉,
|
|
425
|
+
// 否则会出现「窗口明明开着,后续工具却报已关闭」。
|
|
426
|
+
if (allowClosed)
|
|
427
|
+
closedSids.delete(sid);
|
|
428
|
+
await fireReady(sid);
|
|
429
|
+
return inst;
|
|
430
|
+
})().finally(() => {
|
|
431
|
+
startingSid.delete(sid);
|
|
432
|
+
});
|
|
433
|
+
startingSid.set(sid, p);
|
|
434
|
+
return p;
|
|
435
|
+
}
|
|
436
|
+
/** 实例就绪后的统一回调(插件侧用于对该 sid 做初始 drain) */
|
|
437
|
+
async function fireReady(sid) {
|
|
296
438
|
try {
|
|
297
|
-
|
|
298
|
-
method: "POST",
|
|
299
|
-
headers: { "Content-Type": "application/json" },
|
|
300
|
-
body: "{}",
|
|
301
|
-
signal: ac.signal,
|
|
302
|
-
});
|
|
303
|
-
if (!res.ok)
|
|
304
|
-
return null;
|
|
305
|
-
const json = await res.json();
|
|
306
|
-
return json?.success ? json.data : null;
|
|
439
|
+
serviceReadyHandler?.(sid);
|
|
307
440
|
}
|
|
308
|
-
catch {
|
|
309
|
-
|
|
441
|
+
catch (e) {
|
|
442
|
+
log.error("[notify] service-ready handler failed", e);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** 把某会话的通知地址注册给该实例(/api/notify-url);直接 fetch,避免 callApi 触发 ensure 递归
|
|
446
|
+
* 返回是否注册成功(失败不抛出:推送是增强路径,不能因注册失败阻断工具调用) */
|
|
447
|
+
async function registerNotifyUrl(baseUrl, sid, token) {
|
|
448
|
+
const url = getNotifyUrlForSession(sid);
|
|
449
|
+
if (!url)
|
|
450
|
+
return false;
|
|
451
|
+
// 增强路径:只有 ok 算成功,其余(transport/auth/server/badjson)都降级为 false,
|
|
452
|
+
// 由调用方决定是否重试;绝不因注册失败影响工具调用或实例存活判定。
|
|
453
|
+
const out = await httpCall(baseUrl, token, "/api/notify-url", { url });
|
|
454
|
+
if (out.kind === "ok") {
|
|
455
|
+
log.info(`[notify] sid=${sid} notify-url registered: ${url}`);
|
|
456
|
+
return true;
|
|
457
|
+
}
|
|
458
|
+
const detail = out.kind === "auth" ? `HTTP ${out.status}` : out.kind === "server" ? `server: ${out.error}` : out.kind;
|
|
459
|
+
log.error(`[notify] sid=${sid} register failed: ${detail}`);
|
|
460
|
+
return false;
|
|
461
|
+
}
|
|
462
|
+
/** 附着模式:按 baseUrl+sid 去重注册 notify(附着模式共享一个 shell,队列全局)
|
|
463
|
+
* 并发语义:同 key 的并发调用共享同一次 POST(await 同一个 Promise),失败只清 in-flight,
|
|
464
|
+
* 使下一次调用自动重试;成功才写入「已注册」集合。 */
|
|
465
|
+
async function ensureAttachNotify(inst, sid) {
|
|
466
|
+
const key = `${inst.baseUrl}|${sid}`;
|
|
467
|
+
if (attachNotifyRegistered.has(key))
|
|
468
|
+
return;
|
|
469
|
+
const inflight = attachNotifyInFlight.get(key);
|
|
470
|
+
if (inflight) {
|
|
471
|
+
await inflight;
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const p = registerNotifyUrl(inst.baseUrl, sid, inst.token);
|
|
475
|
+
attachNotifyInFlight.set(key, p);
|
|
476
|
+
let ok = false;
|
|
477
|
+
try {
|
|
478
|
+
ok = await p;
|
|
479
|
+
}
|
|
480
|
+
finally {
|
|
481
|
+
// settle 后清理,避免 Promise 常驻导致内存泄漏
|
|
482
|
+
if (attachNotifyInFlight.get(key) === p)
|
|
483
|
+
attachNotifyInFlight.delete(key);
|
|
484
|
+
}
|
|
485
|
+
if (ok)
|
|
486
|
+
attachNotifyRegistered.add(key);
|
|
487
|
+
}
|
|
488
|
+
/** 清掉某外部 shell 的 notify 注册记录(断开/换实例后重新连接需重新注册) */
|
|
489
|
+
function clearAttachNotify(baseUrl) {
|
|
490
|
+
const prefix = `${baseUrl}|`;
|
|
491
|
+
for (const key of [...attachNotifyRegistered]) {
|
|
492
|
+
if (key.startsWith(prefix))
|
|
493
|
+
attachNotifyRegistered.delete(key);
|
|
494
|
+
}
|
|
495
|
+
for (const key of [...attachNotifyInFlight.keys()]) {
|
|
496
|
+
if (key.startsWith(prefix))
|
|
497
|
+
attachNotifyInFlight.delete(key);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/** 清掉某 sid 的 attach notify 记录(会话删除时调用;键格式为 `baseUrl|sid`) */
|
|
501
|
+
export function clearAttachNotifyForSid(sid) {
|
|
502
|
+
if (!sid)
|
|
503
|
+
return;
|
|
504
|
+
const suffix = `|${sid}`;
|
|
505
|
+
for (const key of [...attachNotifyRegistered]) {
|
|
506
|
+
if (key.endsWith(suffix))
|
|
507
|
+
attachNotifyRegistered.delete(key);
|
|
508
|
+
}
|
|
509
|
+
for (const key of [...attachNotifyInFlight.keys()]) {
|
|
510
|
+
if (key.endsWith(suffix))
|
|
511
|
+
attachNotifyInFlight.delete(key);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* 关闭某会话的实例:优雅(/api/close)→ 等退出 → 超时才 SIGTERM(仅该实例自己的句柄/PID)→ 从注册表移除
|
|
516
|
+
* 语义保证:实例不存在则**直接返回,绝不因此 spawn**;附着模式只解除本地关联,外部进程不动。
|
|
517
|
+
*/
|
|
518
|
+
export async function closeSession(explicitSid) {
|
|
519
|
+
const sid = resolveSessionId(explicitSid);
|
|
520
|
+
// P3-①:先置关闭标记 —— 即使实例尚不存在(启动进行中),启动链完成后也会据此自毁,不留孤儿
|
|
521
|
+
closedSids.add(sid);
|
|
522
|
+
const inst = sessions.get(sid) || (attachInstance && attachInstance.sid === sid ? attachInstance : null);
|
|
523
|
+
if (!inst) {
|
|
524
|
+
log.info(`[session] sid=${sid} has no shell instance; nothing to close (never spawn on close)`);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
sessions.delete(inst.sid);
|
|
528
|
+
// 已关闭态保留 closedSids:后续工具调用不再自动重开,须 open_window 显式打开
|
|
529
|
+
if (attachInstance === inst)
|
|
530
|
+
attachInstance = null;
|
|
531
|
+
if (inst.attach) {
|
|
532
|
+
// 附着模式:外部 shell 进程不归插件管,**绝不 kill**,只清本地关联
|
|
533
|
+
clearAttachNotify(inst.baseUrl);
|
|
534
|
+
log.info(`Detached from external bt-shell at ${inst.baseUrl} (process left running)`);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
// 关闭路径 best-effort:任何结果都忽略(进程可能已自行退出,transport 也正常),
|
|
538
|
+
// 存活收尾交给下面的 terminateOwnProcess/waitForExit。
|
|
539
|
+
await httpCall(inst.baseUrl, inst.token, "/api/close", {});
|
|
540
|
+
await terminateOwnProcess(inst.proc);
|
|
541
|
+
log.info(`[session] sid=${sid} closed (port=${inst.port})`);
|
|
542
|
+
}
|
|
543
|
+
/** 关闭全部实例(插件 dispose / 退出);只按注册表 PID,绝不按名
|
|
544
|
+
* 含**启动中**的 sid:先置 closedSids(启动链自查后自毁刚 spawn 的进程),再等启动链跑完 ——
|
|
545
|
+
* 确保 dispose 返回时不留孤儿窗口。 */
|
|
546
|
+
export async function closeAllSessions() {
|
|
547
|
+
const starting = [...startingSid.values()];
|
|
548
|
+
const sids = new Set([...sessions.keys(), ...startingSid.keys()]);
|
|
549
|
+
for (const sid of sids) {
|
|
550
|
+
await closeSession(sid);
|
|
551
|
+
}
|
|
552
|
+
// 启动链可能仍在 waitForReady:等它自查 closedSids 并终止自己 spawn 的进程(失败也不阻塞 dispose)
|
|
553
|
+
await Promise.allSettled(starting);
|
|
554
|
+
}
|
|
555
|
+
/** 该会话是否正处于启动中(close 需要能关掉「还没就绪」的实例) */
|
|
556
|
+
export function isStarting(sid) {
|
|
557
|
+
return startingSid.has(resolveSessionId(sid));
|
|
558
|
+
}
|
|
559
|
+
/** 清「已关闭」标记(会话删除时用,避免集合无限增长;open_window 亦会清) */
|
|
560
|
+
export function clearClosedState(sid) {
|
|
561
|
+
closedSids.delete(sid);
|
|
562
|
+
}
|
|
563
|
+
/** 打开浏览器窗口(未启动则启动该会话实例;已启动幂等)
|
|
564
|
+
* 手动关窗后注册表里的实例可能仍是 ready(进程已死/窗口已关)→ 先做一次存活探测,
|
|
565
|
+
* 探测失败就摘除死实例再走 ensureInstance,避免「以为已打开」而空转。 */
|
|
566
|
+
export async function openWindow(sid) {
|
|
567
|
+
// 唯一打开入口:显式清「已关闭」标记后再启动
|
|
568
|
+
const s = resolveSessionId(sid);
|
|
569
|
+
closedSids.delete(s);
|
|
570
|
+
const inst = sessions.get(s);
|
|
571
|
+
if (inst?.ready) {
|
|
572
|
+
const alive = await probeOnce(inst.baseUrl, 800, inst.token);
|
|
573
|
+
if (!alive) {
|
|
574
|
+
log.info(`[session] sid=${s} open_window: probe failed (port=${inst.port}); discarding dead instance before reopening`);
|
|
575
|
+
await markInstanceDead(s, inst);
|
|
576
|
+
if (sessions.get(s) === inst)
|
|
577
|
+
sessions.delete(s);
|
|
578
|
+
if (attachInstance === inst)
|
|
579
|
+
attachInstance = null;
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
// 探测通过:实例仍存活,保持幂等直接返回
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
await ensureInstance(s, { allowClosed: true });
|
|
587
|
+
// 启动期间并发的 callApi 可能因连接层错误再次置 closedSids(其探活的是旧实例);
|
|
588
|
+
// 本窗口已确认打开 → 成功路径再清一次,避免「窗口开着却报已关闭」。
|
|
589
|
+
closedSids.delete(s);
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* 纯查询:探测某会话的 shell 是否在运行,**绝不 spawn**。
|
|
593
|
+
* sid 未给 → 先探当前会话,再探任一已就绪实例;都没有则返回 null。
|
|
594
|
+
* 用于 get_browser_status 这类只读命令,避免查询也弹出浏览器窗口。
|
|
595
|
+
*/
|
|
596
|
+
export async function probeStatus(timeoutMs = 1500, sid) {
|
|
597
|
+
// 按实例探测(令牌随实例走:spawn 实例用自己生成的令牌,attach 实例用 BT_SHELL_TOKEN)
|
|
598
|
+
const targets = [];
|
|
599
|
+
const add = (inst) => {
|
|
600
|
+
if (inst?.ready && !targets.some((t) => t.baseUrl === inst.baseUrl))
|
|
601
|
+
targets.push(inst);
|
|
602
|
+
};
|
|
603
|
+
if (sid) {
|
|
604
|
+
add(sessions.get(resolveSessionId(sid)));
|
|
605
|
+
// 附着模式:实例可能只挂在 attachInstance 上(共享单例,放弃按 sid 隔离)→ 同样纳入探测
|
|
606
|
+
add(attachInstance);
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
add(sessions.get(resolveSessionId()));
|
|
610
|
+
for (const inst of sessions.values())
|
|
611
|
+
add(inst);
|
|
612
|
+
add(attachInstance);
|
|
613
|
+
}
|
|
614
|
+
for (const inst of targets) {
|
|
615
|
+
const r = await probeOnce(inst.baseUrl, timeoutMs, inst.token);
|
|
616
|
+
if (r)
|
|
617
|
+
return r;
|
|
618
|
+
}
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
/** 对单个端点做一次短超时探测:只有 ok 有值;其余(auth/server/badjson/transport)一律 null */
|
|
622
|
+
async function probeOnce(baseUrl, timeoutMs, token) {
|
|
623
|
+
const out = await httpCall(baseUrl, token, "/api/status", {}, { timeoutMs });
|
|
624
|
+
return out.kind === "ok" ? out.data : null;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* 单一 HTTP 原语:POST JSON 到 bt-shell 本地 API 并归类结果。**从不抛错**,也不决定
|
|
628
|
+
* 调用方语义(唯一出口是 `HttpOutcome`)。
|
|
629
|
+
*
|
|
630
|
+
* 统一请求头(`Content-Type` + `x-bt-token`)与统一超时(AbortController;`timeoutMs`
|
|
631
|
+
* 省略则不限,与原实现一致)。归类顺序:fetch 抛错/超时 → transport;401/403 → auth;
|
|
632
|
+
* 响应体非 JSON → badjson;其余看 `success` 字段。
|
|
633
|
+
*
|
|
634
|
+
* 策略分工(调用方各自映射,不在本函数里做):
|
|
635
|
+
* - `postJson`(工具调用):ok→data、server→抛错、auth→抛鉴权错、transport→抛
|
|
636
|
+
* `ConnectionError`(供 callApi 判定实例死亡)、badjson→抛解析错(不判死);
|
|
637
|
+
* - `probeOnce`(探活):只有 ok 有值,其余 null;
|
|
638
|
+
* - `registerNotifyUrl`(增强路径):只有 ok 返回 true,其余 false;
|
|
639
|
+
* - `waitForReady`(就绪轮询):ok 结束,transport/server/badjson 继续等,attach 的 auth 立即报错;
|
|
640
|
+
* - `closeSession`(关闭):忽略任何结果。
|
|
641
|
+
*/
|
|
642
|
+
async function httpCall(baseUrl, token, path, payload, opts) {
|
|
643
|
+
const timeoutMs = opts?.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : 0;
|
|
644
|
+
const ac = timeoutMs > 0 ? new AbortController() : null;
|
|
645
|
+
const timer = ac ? setTimeout(() => ac.abort(), timeoutMs) : null;
|
|
646
|
+
try {
|
|
647
|
+
let res;
|
|
648
|
+
try {
|
|
649
|
+
res = await fetch(`${baseUrl}${path}`, {
|
|
650
|
+
method: "POST",
|
|
651
|
+
headers: { "Content-Type": "application/json", "x-bt-token": token },
|
|
652
|
+
body: JSON.stringify(payload ?? {}),
|
|
653
|
+
signal: ac?.signal,
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
catch (e) {
|
|
657
|
+
// 超时与连接失败同归 transport:由抛错点显式标记类型,调用方无需识别运行时文案;
|
|
658
|
+
// 超时在 cause 里留下标记,便于日志区分「端口没监听」与「服务没响应」。
|
|
659
|
+
const timedOut = ac?.signal.aborted === true;
|
|
660
|
+
return {
|
|
661
|
+
kind: "transport",
|
|
662
|
+
error: timedOut
|
|
663
|
+
? new ConnectionError(`request timed out after ${timeoutMs}ms`, { timeout: true, cause: e })
|
|
664
|
+
: new ConnectionError(e?.message || "connection failed", e),
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
if (res.status === HTTP_UNAUTHORIZED || res.status === HTTP_FORBIDDEN) {
|
|
668
|
+
return { kind: "auth", status: res.status };
|
|
669
|
+
}
|
|
670
|
+
let json;
|
|
671
|
+
try {
|
|
672
|
+
json = await res.json();
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return { kind: "badjson" };
|
|
676
|
+
}
|
|
677
|
+
if (json?.success)
|
|
678
|
+
return { kind: "ok", data: json.data };
|
|
679
|
+
return { kind: "server", error: typeof json?.error === "string" ? json.error : "" };
|
|
310
680
|
}
|
|
311
681
|
finally {
|
|
312
|
-
|
|
682
|
+
if (timer)
|
|
683
|
+
clearTimeout(timer);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* 传输层连接错误:`fetch` **本身**抛错(端口没人听 / shell 进程已死)或请求超时时,
|
|
688
|
+
* 由 `httpCall` 标记并用 `HttpOutcome.transport` 交给调用方。
|
|
689
|
+
*
|
|
690
|
+
* 为什么要显式类型:同一份代码会跑在不同运行时上 —— opencode 默认跑在 **Bun**,Bun 的 fetch
|
|
691
|
+
* 失败是 `TypeError: Unable to connect. Is the computer able to access the url?`(无 `cause.code`);
|
|
692
|
+
* Node/undici 是 `TypeError: fetch failed`,真实原因在 `cause.code=ECONNREFUSED`。
|
|
693
|
+
* 靠猜文案/码跨运行时必漏(1.10.1 真机缺陷),因此传输层失败**由抛错点标记类型**,判断方只认类型。
|
|
694
|
+
*/
|
|
695
|
+
export class ConnectionError extends Error {
|
|
696
|
+
/** 原始 fetch 异常(保留运行时细节,便于日志取证) */
|
|
697
|
+
cause;
|
|
698
|
+
/**
|
|
699
|
+
* @param message 人类可读的连接失败信息(通常取原始异常 message)
|
|
700
|
+
* @param cause 原始 fetch 异常
|
|
701
|
+
*/
|
|
702
|
+
constructor(message, cause) {
|
|
703
|
+
super(message);
|
|
704
|
+
this.name = "ConnectionError";
|
|
705
|
+
if (cause !== undefined)
|
|
706
|
+
this.cause = cause;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* 判断是否为**连接层**错误(shell 进程已死/端口没人听 → fetch 直接抛)。
|
|
711
|
+
* 只认这类;HTTP 4xx/5xx 不算(它们是正常响应,由 `httpCall` 归入 auth/server 分支)。
|
|
712
|
+
*
|
|
713
|
+
* 优先级:显式 `ConnectionError`(运行时无关) → Node/undici 的码/文案(兼容旧路径) →
|
|
714
|
+
* Bun 等运行时的文案兜底(`Unable to connect` / `ConnectionRefused` / `Failed to connect`)。
|
|
715
|
+
* 导出仅供自验/单测直接构造运行时文案验证。
|
|
716
|
+
*/
|
|
717
|
+
export function isConnectionError(e) {
|
|
718
|
+
// 首选:传输层抛错点已显式标记类型(不依赖任何运行时文案)
|
|
719
|
+
if (e instanceof ConnectionError)
|
|
720
|
+
return true;
|
|
721
|
+
if (!(e instanceof Error))
|
|
722
|
+
return false;
|
|
723
|
+
// 兼容 Node/undici:message = "fetch failed",真实原因在 cause.code;部分场景直接带码。
|
|
724
|
+
// `ConnectionRefused` 是 Bun 的码名(大小写不固定,故 i 忽略大小写)。
|
|
725
|
+
const code = String(e?.cause?.code || e?.code || "");
|
|
726
|
+
if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR|ETIMEDOUT|ConnectionRefused/i.test(code)) {
|
|
727
|
+
return true;
|
|
728
|
+
}
|
|
729
|
+
// 文案兜底(多运行时):Bun 无 cause.code 只有 "Unable to connect...";Node/undici 各有自己的措辞。
|
|
730
|
+
// 只在这里做兜底,正常路径以 ConnectionError 类型为准。
|
|
731
|
+
return /fetch failed|socket hang up|other side closed|connect ECONN|network error|Unable to connect|ConnectionRefused|Failed to connect/i.test(e.message);
|
|
732
|
+
}
|
|
733
|
+
/** 把一个已死实例从注册表摘除并回收残留句柄(只按该实例自己的句柄/PID,绝不按名) */
|
|
734
|
+
async function markInstanceDead(sid, inst) {
|
|
735
|
+
// 只在注册项仍指向该实例时删除(避免误删之后由 open_window 重新注册的新实例)
|
|
736
|
+
if (sessions.get(sid) === inst)
|
|
737
|
+
sessions.delete(sid);
|
|
738
|
+
if (attachInstance === inst)
|
|
739
|
+
attachInstance = null;
|
|
740
|
+
// 外部 shell 已不可达:清 notify 注册记录,重新附着时才会重新注册
|
|
741
|
+
if (inst.attach)
|
|
742
|
+
clearAttachNotify(inst.baseUrl);
|
|
743
|
+
if (inst.proc)
|
|
744
|
+
await terminateOwnProcess(inst.proc);
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* 工具调用链路的 POST:把 `httpCall` 的分类**映射为对外语义**(这里是唯一决定抛/吞的地方)。
|
|
748
|
+
* 映射规则见 `httpCall` 注释;其中 auth 在自建实例上属异常(令牌由插件自己生成),
|
|
749
|
+
* 报鉴权错误而**不**报连接错误。
|
|
750
|
+
*/
|
|
751
|
+
async function postJson(inst, path, payload) {
|
|
752
|
+
const out = await httpCall(inst.baseUrl, inst.token, path, payload);
|
|
753
|
+
switch (out.kind) {
|
|
754
|
+
case "ok":
|
|
755
|
+
return out.data;
|
|
756
|
+
case "server":
|
|
757
|
+
// 服务端错误文本可能夹带底层路径(如 WebView2/fs 细节):回模型前统一脱敏
|
|
758
|
+
throw new Error(sanitizeForModel(out.error || tf("client.service_error")));
|
|
759
|
+
case "auth":
|
|
760
|
+
throw new Error(tf(inst.attach ? "client.attach_bad_token" : "client.auth_rejected"));
|
|
761
|
+
case "transport":
|
|
762
|
+
throw out.error;
|
|
763
|
+
case "badjson":
|
|
764
|
+
throw new Error(tf("client.bad_response"));
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* 统一 API 调用:按 sid 路由到该会话的实例(懒启动)。
|
|
769
|
+
* sid 来源:显式 sessionId 参数 > body._sessionId > 钩子缓存兜底 > "default" 桶。
|
|
770
|
+
*
|
|
771
|
+
* P3-②:连接层错误(手关窗口/进程被杀)→ 标记实例死亡 + 置「已关闭」态 → 抛 `client.browser_closed`
|
|
772
|
+
* 指引,**绝不自动重开**(唯一打开入口是 `open_window`)。**例外**:
|
|
773
|
+
* - 附着模式:外部进程不归插件管 → 只报 `client.attach_gone`,不动任何进程;
|
|
774
|
+
* - get_browser_status(走 probeStatus/probeOnce,不经本函数)保持纯查询,不 spawn;
|
|
775
|
+
* - HTTP 4xx/5xx 不算连接错误,原样抛服务端错误。
|
|
776
|
+
*/
|
|
777
|
+
async function callApi(path, body, sessionId) {
|
|
778
|
+
const sid = resolveSessionId(sessionId || (body && body._sessionId));
|
|
779
|
+
const inst = await ensureInstance(sid);
|
|
780
|
+
const payload = { ...(body || {}), _sessionId: sid };
|
|
781
|
+
try {
|
|
782
|
+
return await postJson(inst, path, payload);
|
|
783
|
+
}
|
|
784
|
+
catch (e) {
|
|
785
|
+
if (!isConnectionError(e))
|
|
786
|
+
throw e;
|
|
787
|
+
if (inst.attach) {
|
|
788
|
+
// 附着模式:不拥有该进程,只报明确错误(不 respawn)
|
|
789
|
+
throw new Error(tf("client.attach_gone", { url: inst.baseUrl }));
|
|
790
|
+
}
|
|
791
|
+
log.error(`[session] sid=${sid} instance dead (port=${inst.port}, pid=${inst.proc?.pid ?? "?"}): ${e.message}; marking closed`);
|
|
792
|
+
await markInstanceDead(sid, inst);
|
|
793
|
+
// 用户口径:手动关窗**绝不自动重开** → 置位「已关闭」态,指引显式 open_window(不做 respawn 重试)
|
|
794
|
+
closedSids.add(sid);
|
|
795
|
+
throw new Error(tf("client.browser_closed"));
|
|
313
796
|
}
|
|
314
797
|
}
|
|
315
798
|
function cmd(name) {
|
|
@@ -358,7 +841,6 @@ export const service = {
|
|
|
358
841
|
expectResponse: cmd("expect-response"),
|
|
359
842
|
assertResponse: cmd("assert-response"),
|
|
360
843
|
panelConfig: cmd("panel-config"),
|
|
361
|
-
status: cmd("status"),
|
|
362
844
|
tabs: cmd("tabs"),
|
|
363
845
|
annotateToggle: cmd("annotate/toggle"),
|
|
364
846
|
annotateRecords: cmd("annotate/records"),
|