@xiaoqiong0v0/opencode-browser-tool 1.9.0 → 1.10.2

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/dist/client.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // 窗口/标签/UA/批注等一切 shell 状态;进程回收只按注册表里的 PID,**绝不按名杀进程**。
6
6
  // 附着模式(BT_SHELL_URL/BT_SHELL_PORT)例外:连接外部单例,放弃会话隔离(见 docs/implementation.md)。
7
7
  import { spawn } from "child_process";
8
+ import { randomBytes } from "crypto";
8
9
  import { resolve, dirname } from "path";
9
10
  import { existsSync } from "fs";
10
11
  import { fileURLToPath } from "url";
@@ -12,6 +13,7 @@ import { log } from "./logger.js";
12
13
  import { getNotifyUrlForSession } from "./notify-server.js";
13
14
  import { tf } from "./i18n/index.js";
14
15
  import { cachedBinaryPath, describeBinaryStatus, ensureBinary } from "./binary.js";
16
+ import { sanitizeForModel } from "./util/sanitize.js";
15
17
  const __dirname = dirname(fileURLToPath(import.meta.url));
16
18
  /** 就绪轮询超时(ms) */
17
19
  const READY_TIMEOUT_MS = 20000;
@@ -21,6 +23,10 @@ const READY_POLL_INTERVAL_MS = 300;
21
23
  const PORT_START_ATTEMPTS = 5;
22
24
  /** 会话标题解析上限(ms):超时就用 sid 后缀,绝不因标题卡住启动 */
23
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;
24
30
  /** opencode 应用/项目目录(插件初始化与工具上下文提供);用于定位本地 Rust 开发构建 */
25
31
  let appDirectory = "";
26
32
  /** 记录 opencode 目录(插件初始化 / 工具调用时调用) */
@@ -70,6 +76,13 @@ function resolveAttachBaseUrl() {
70
76
  return `http://127.0.0.1:${port}`;
71
77
  return null;
72
78
  }
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
+ }
73
86
  /** 实例注册表:每会话一个 shell;并发启动保护见 startingSid */
74
87
  const sessions = new Map();
75
88
  /** 正在启动中的会话 → Promise(并发保护:同一 sid 多个工具同时调用只启动一次) */
@@ -78,6 +91,21 @@ const startingSid = new Map();
78
91
  const closedSids = new Set();
79
92
  /** 附着模式共享实例(外部 shell;所有 sid 共用,放弃会话隔离) */
80
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;
81
109
  /** 服务启动参数(configureService 保存,懒启动时使用) */
82
110
  let serviceConfig = null;
83
111
  /** 会话 id 兜底解析器(钩子缓存):工具调用没带 _sessionId 时用它 */
@@ -133,23 +161,6 @@ export function isRunning(sid) {
133
161
  return true;
134
162
  return !!attachInstance?.ready;
135
163
  }
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
- });
150
- }
151
- return out;
152
- }
153
164
  /** 组装窗口标题:优先会话标题(有界等待),拿不到用 sid 后 6 位,保证任务栏可分辨 */
154
165
  async function resolveWindowTitle(sid) {
155
166
  const suffix = sid.length > 6 ? sid.slice(-6) : sid || "main";
@@ -169,22 +180,25 @@ async function resolveWindowTitle(sid) {
169
180
  }
170
181
  return fallback;
171
182
  }
172
- /** 轮询等待服务就绪(READY_TIMEOUT_MS 超时);超时抛出给定提示 */
173
- 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) {
174
193
  const deadline = Date.now() + READY_TIMEOUT_MS;
175
194
  while (Date.now() < deadline) {
176
- try {
177
- const res = await fetch(`${baseUrl}/api/status`, {
178
- method: "POST",
179
- headers: { "Content-Type": "application/json" },
180
- body: "{}",
181
- });
182
- if (res.ok)
183
- return;
184
- }
185
- catch {
186
- // 服务未启动,继续等待
187
- }
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"));
188
202
  await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
189
203
  }
190
204
  throw new Error(timeoutMessage);
@@ -264,11 +278,22 @@ async function spawnForSession(sid, shell) {
264
278
  const cfg = serviceConfig;
265
279
  const dataDir = cfg?.resolveDataDir ? cfg.resolveDataDir(sid) : "";
266
280
  const title = await resolveWindowTitle(sid);
281
+ // 本实例的鉴权令牌:16 字节 → 32 hex;端口重试沿用同一令牌(新的子进程仍是同一实例语义)
282
+ const token = randomBytes(16).toString("hex");
267
283
  let lastErr = null;
268
284
  for (let attempt = 1; attempt <= PORT_START_ATTEMPTS; attempt++) {
269
285
  // 显式指定端口(release 模式 GUI 程序无控制台,无法解析 stdout);随机区间避开常用端口
270
286
  const port = 18000 + Math.floor(Math.random() * 1000);
271
- const args = ["--browsers-path", cfg?.browsersPath || "", "--port", String(port), "--title", title];
287
+ const args = [
288
+ "--browsers-path",
289
+ cfg?.browsersPath || "",
290
+ "--port",
291
+ String(port),
292
+ "--title",
293
+ title,
294
+ "--token",
295
+ token,
296
+ ];
272
297
  // 每会话独立 user-data-dir(WebView2 profile 隔离);未提供则不传(回落 WebView2 默认目录)
273
298
  if (dataDir)
274
299
  args.push("--user-data-dir", dataDir);
@@ -288,7 +313,9 @@ async function spawnForSession(sid, shell) {
288
313
  attachStdio(proc, sid);
289
314
  const baseUrl = `http://127.0.0.1:${port}`;
290
315
  try {
291
- await waitForReady(baseUrl, tf("client.service_timeout"));
316
+ // authHint 默认 false:spawn 的令牌是插件本会话随机生成并随 --token 传下去的,
317
+ // 不该出现 401;真出现(如端口被别的进程占住)属于"没起来"一类,走换端口重试而不是鉴权报错
318
+ await waitForReady(baseUrl, token, tf("client.service_timeout"));
292
319
  }
293
320
  catch (e) {
294
321
  // 启动超时(常见:端口被别的进程占住 → bind 失败 → 永远不就绪):杀掉本次子进程换端口重来
@@ -297,22 +324,33 @@ async function spawnForSession(sid, shell) {
297
324
  await terminateOwnProcess(proc);
298
325
  continue;
299
326
  }
300
- // 就绪:把本会话的通知地址注册给该实例(推送式投递)
301
- await registerNotifyUrl(baseUrl, sid);
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
+ }
302
335
  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 };
336
+ return { sid, proc, baseUrl, port, token, dataDir, title, ready: true, attach: false };
304
337
  }
305
338
  throw lastErr instanceof Error ? lastErr : new Error(tf("client.service_timeout"));
306
339
  }
307
340
  /** 附着到外部已运行的 shell(所有 sid 共用;不 spawn、不 kill、放弃会话隔离) */
308
341
  async function attachToService(baseUrl, sid) {
342
+ // 令牌必须先有:缺失时直接报错,不去连一个注定 401 的端点
343
+ const token = requireAttachToken();
309
344
  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 }));
345
+ // authHint=true:令牌来自 BT_SHELL_TOKEN(与外部 shell 的启动令牌是两处配置),
346
+ // 401/403 说明两边不一致 → 立即报鉴权失败,不等 20s 超时
347
+ await waitForReady(baseUrl, token, tf("client.attach_timeout", { url: baseUrl }), true);
311
348
  const inst = {
312
349
  sid,
313
350
  proc: null,
314
351
  baseUrl,
315
352
  port: Number(new URL(baseUrl).port || 0),
353
+ token,
316
354
  dataDir: "",
317
355
  title: "(external)",
318
356
  ready: true,
@@ -335,14 +373,21 @@ export async function ensureInstance(explicitSid, opts) {
335
373
  if (!allowClosed && closedSids.has(sid)) {
336
374
  throw new Error(tf("client.browser_closed"));
337
375
  }
338
- // 附着模式:外部 shell 单例,所有 sid 共用(连接一次,之后直接返回)
376
+ // 附着模式:外部 shell 单例,所有 sid 共用(连接一次,之后直接返回)。
377
+ // notify 语义:`/api/notify-url` 在 shell 内是**全局单值**,待发送队列也是**全局唯一**;
378
+ // 附着模式共享同一个 shell ⇒ 队列全局,drain 由 notify URL 里带的 sid 执行。
379
+ // 因此每个 sid 首次走 attach 分支时都必须注册自己的 notify 地址(按 baseUrl+sid 去重)。
339
380
  const attachUrl = resolveAttachBaseUrl();
340
381
  if (attachUrl) {
341
- if (attachInstance?.ready)
382
+ if (attachInstance?.ready) {
383
+ await ensureAttachNotify(attachInstance, sid);
342
384
  return attachInstance;
385
+ }
343
386
  const existing = sessions.get(sid);
344
- if (existing?.attach)
387
+ if (existing?.attach) {
388
+ await ensureAttachNotify(existing, sid);
345
389
  return existing;
390
+ }
346
391
  const inst = await attachToService(attachUrl, sid);
347
392
  // P3-①:附着期间该 sid 被关闭 → 只解本地关联(外部进程不归插件管,绝不 kill)
348
393
  if (closedSids.has(sid)) {
@@ -351,6 +396,7 @@ export async function ensureInstance(explicitSid, opts) {
351
396
  }
352
397
  attachInstance = inst;
353
398
  sessions.set(sid, inst);
399
+ await ensureAttachNotify(inst, sid);
354
400
  await fireReady(sid);
355
401
  return inst;
356
402
  }
@@ -374,6 +420,11 @@ export async function ensureInstance(explicitSid, opts) {
374
420
  throw new Error(tf("client.session_closed_during_start"));
375
421
  }
376
422
  sessions.set(sid, inst);
423
+ // P0 竞态收尾:本轮是 open_window 的显式打开 → 成功后清「已关闭」标记。
424
+ // 期间若有并发 callApi 探活失败把 sid 重新置为 closed,这里也要清掉,
425
+ // 否则会出现「窗口明明开着,后续工具却报已关闭」。
426
+ if (allowClosed)
427
+ closedSids.delete(sid);
377
428
  await fireReady(sid);
378
429
  return inst;
379
430
  })().finally(() => {
@@ -391,24 +442,73 @@ async function fireReady(sid) {
391
442
  log.error("[notify] service-ready handler failed", e);
392
443
  }
393
444
  }
394
- /** 把某会话的通知地址注册给该实例(/api/notify-url);直接 fetch,避免 callApi 触发 ensure 递归 */
395
- async function registerNotifyUrl(baseUrl, sid) {
445
+ /** 把某会话的通知地址注册给该实例(/api/notify-url);直接 fetch,避免 callApi 触发 ensure 递归
446
+ * 返回是否注册成功(失败不抛出:推送是增强路径,不能因注册失败阻断工具调用) */
447
+ async function registerNotifyUrl(baseUrl, sid, token) {
396
448
  const url = getNotifyUrlForSession(sid);
397
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))
398
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;
399
477
  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}`);
478
+ ok = await p;
409
479
  }
410
- catch (e) {
411
- log.error("[notify] register failed", e);
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);
412
512
  }
413
513
  }
414
514
  /**
@@ -430,43 +530,63 @@ export async function closeSession(explicitSid) {
430
530
  attachInstance = null;
431
531
  if (inst.attach) {
432
532
  // 附着模式:外部 shell 进程不归插件管,**绝不 kill**,只清本地关联
533
+ clearAttachNotify(inst.baseUrl);
433
534
  log.info(`Detached from external bt-shell at ${inst.baseUrl} (process left running)`);
434
535
  return;
435
536
  }
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
- }
537
+ // 关闭路径 best-effort:任何结果都忽略(进程可能已自行退出,transport 也正常),
538
+ // 存活收尾交给下面的 terminateOwnProcess/waitForExit。
539
+ await httpCall(inst.baseUrl, inst.token, "/api/close", {});
446
540
  await terminateOwnProcess(inst.proc);
447
541
  log.info(`[session] sid=${sid} closed (port=${inst.port})`);
448
542
  }
449
- /** 关闭全部实例(插件 dispose / 退出);只按注册表 PID,绝不按名 */
543
+ /** 关闭全部实例(插件 dispose / 退出);只按注册表 PID,绝不按名
544
+ * 含**启动中**的 sid:先置 closedSids(启动链自查后自毁刚 spawn 的进程),再等启动链跑完 ——
545
+ * 确保 dispose 返回时不留孤儿窗口。 */
450
546
  export async function closeAllSessions() {
451
- const sids = [...sessions.keys()];
547
+ const starting = [...startingSid.values()];
548
+ const sids = new Set([...sessions.keys(), ...startingSid.keys()]);
452
549
  for (const sid of sids) {
453
550
  await closeSession(sid);
454
551
  }
552
+ // 启动链可能仍在 waitForReady:等它自查 closedSids 并终止自己 spawn 的进程(失败也不阻塞 dispose)
553
+ await Promise.allSettled(starting);
455
554
  }
456
- /** 兼容旧名:确保默认/当前会话的实例存在(现语义 = 懒启动该 sid 的实例) */
457
- export async function ensureService(sid) {
458
- await ensureInstance(sid);
555
+ /** 该会话是否正处于启动中(close 需要能关掉「还没就绪」的实例) */
556
+ export function isStarting(sid) {
557
+ return startingSid.has(resolveSessionId(sid));
459
558
  }
460
559
  /** 清「已关闭」标记(会话删除时用,避免集合无限增长;open_window 亦会清) */
461
560
  export function clearClosedState(sid) {
462
561
  closedSids.delete(sid);
463
562
  }
464
- /** 打开浏览器窗口(未启动则启动该会话实例;已启动幂等) */
563
+ /** 打开浏览器窗口(未启动则启动该会话实例;已启动幂等)
564
+ * 手动关窗后注册表里的实例可能仍是 ready(进程已死/窗口已关)→ 先做一次存活探测,
565
+ * 探测失败就摘除死实例再走 ensureInstance,避免「以为已打开」而空转。 */
465
566
  export async function openWindow(sid) {
466
567
  // 唯一打开入口:显式清「已关闭」标记后再启动
467
568
  const s = resolveSessionId(sid);
468
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
+ }
469
586
  await ensureInstance(s, { allowClosed: true });
587
+ // 启动期间并发的 callApi 可能因连接层错误再次置 closedSids(其探活的是旧实例);
588
+ // 本窗口已确认打开 → 成功路径再清一次,避免「窗口开着却报已关闭」。
589
+ closedSids.delete(s);
470
590
  }
471
591
  /**
472
592
  * 纯查询:探测某会话的 shell 是否在运行,**绝不 spawn**。
@@ -474,67 +594,141 @@ export async function openWindow(sid) {
474
594
  * 用于 get_browser_status 这类只读命令,避免查询也弹出浏览器窗口。
475
595
  */
476
596
  export async function probeStatus(timeoutMs = 1500, sid) {
597
+ // 按实例探测(令牌随实例走:spawn 实例用自己生成的令牌,attach 实例用 BT_SHELL_TOKEN)
477
598
  const targets = [];
599
+ const add = (inst) => {
600
+ if (inst?.ready && !targets.some((t) => t.baseUrl === inst.baseUrl))
601
+ targets.push(inst);
602
+ };
478
603
  if (sid) {
479
- const inst = sessions.get(resolveSessionId(sid));
480
- if (inst?.ready)
481
- targets.push(inst.baseUrl);
604
+ add(sessions.get(resolveSessionId(sid)));
605
+ // 附着模式:实例可能只挂在 attachInstance 上(共享单例,放弃按 sid 隔离)→ 同样纳入探测
606
+ add(attachInstance);
482
607
  }
483
608
  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);
609
+ add(sessions.get(resolveSessionId()));
610
+ for (const inst of sessions.values())
611
+ add(inst);
612
+ add(attachInstance);
493
613
  }
494
- for (const baseUrl of targets) {
495
- const r = await probeOnce(baseUrl, timeoutMs);
614
+ for (const inst of targets) {
615
+ const r = await probeOnce(inst.baseUrl, timeoutMs, inst.token);
496
616
  if (r)
497
617
  return r;
498
618
  }
499
619
  return null;
500
620
  }
501
- /** 对单个端点做一次短超时探测 */
502
- async function probeOnce(baseUrl, timeoutMs) {
503
- const ac = new AbortController();
504
- const timer = setTimeout(() => ac.abort(), timeoutMs);
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;
505
646
  try {
506
- const res = await fetch(`${baseUrl}/api/status`, {
507
- method: "POST",
508
- headers: { "Content-Type": "application/json" },
509
- body: "{}",
510
- signal: ac.signal,
511
- });
512
- if (!res.ok)
513
- return null;
514
- const json = await res.json();
515
- return json?.success ? json.data : null;
516
- }
517
- catch {
518
- return null;
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 : "" };
519
680
  }
520
681
  finally {
521
- clearTimeout(timer);
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;
522
707
  }
523
708
  }
524
709
  /**
525
710
  * 判断是否为**连接层**错误(shell 进程已死/端口没人听 → fetch 直接抛)。
526
- * 只认这类;HTTP 4xx/5xx 不算(它们不会抛错,而是 res.ok=false → 走 json.success 分支)。
711
+ * 只认这类;HTTP 4xx/5xx 不算(它们是正常响应,由 `httpCall` 归入 auth/server 分支)。
712
+ *
713
+ * 优先级:显式 `ConnectionError`(运行时无关) → Node/undici 的码/文案(兼容旧路径) →
714
+ * Bun 等运行时的文案兜底(`Unable to connect` / `ConnectionRefused` / `Failed to connect`)。
715
+ * 导出仅供自验/单测直接构造运行时文案验证。
527
716
  */
528
- function isConnectionError(e) {
717
+ export function isConnectionError(e) {
718
+ // 首选:传输层抛错点已显式标记类型(不依赖任何运行时文案)
719
+ if (e instanceof ConnectionError)
720
+ return true;
529
721
  if (!(e instanceof Error))
530
722
  return false;
531
- // undici/node 的连接失败:message = "fetch failed",真实原因在 cause.code;部分场景直接带码
723
+ // 兼容 Node/undici:message = "fetch failed",真实原因在 cause.code;部分场景直接带码。
724
+ // `ConnectionRefused` 是 Bun 的码名(大小写不固定,故 i 忽略大小写)。
532
725
  const code = String(e?.cause?.code || e?.code || "");
533
- if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR|ETIMEDOUT/.test(code)) {
726
+ if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR|ETIMEDOUT|ConnectionRefused/i.test(code)) {
534
727
  return true;
535
728
  }
536
- // 退化:message 里出现连接类字样(不同 node/undici 版本的文案差异)
537
- return /fetch failed|socket hang up|other side closed|connect ECONN|network error/i.test(e.message);
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);
538
732
  }
539
733
  /** 把一个已死实例从注册表摘除并回收残留句柄(只按该实例自己的句柄/PID,绝不按名) */
540
734
  async function markInstanceDead(sid, inst) {
@@ -543,20 +737,32 @@ async function markInstanceDead(sid, inst) {
543
737
  sessions.delete(sid);
544
738
  if (attachInstance === inst)
545
739
  attachInstance = null;
740
+ // 外部 shell 已不可达:清 notify 注册记录,重新附着时才会重新注册
741
+ if (inst.attach)
742
+ clearAttachNotify(inst.baseUrl);
546
743
  if (inst.proc)
547
744
  await terminateOwnProcess(inst.proc);
548
745
  }
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;
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
+ }
560
766
  }
561
767
  /**
562
768
  * 统一 API 调用:按 sid 路由到该会话的实例(懒启动)。
@@ -573,7 +779,7 @@ async function callApi(path, body, sessionId) {
573
779
  const inst = await ensureInstance(sid);
574
780
  const payload = { ...(body || {}), _sessionId: sid };
575
781
  try {
576
- return await postJson(inst.baseUrl, path, payload);
782
+ return await postJson(inst, path, payload);
577
783
  }
578
784
  catch (e) {
579
785
  if (!isConnectionError(e))
@@ -635,8 +841,6 @@ export const service = {
635
841
  expectResponse: cmd("expect-response"),
636
842
  assertResponse: cmd("assert-response"),
637
843
  panelConfig: cmd("panel-config"),
638
- status: cmd("status"),
639
- title: cmd("title"),
640
844
  tabs: cmd("tabs"),
641
845
  annotateToggle: cmd("annotate/toggle"),
642
846
  annotateRecords: cmd("annotate/records"),