dsh-browser-cdp 1.14.14 → 1.15.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/lib/index.js CHANGED
@@ -1,15 +1,16 @@
1
- import { _ as windowsEnvChromeCandidates, f as launchLocalBrowser, g as stopLocalBrowser, h as posixChromeCandidates, m as localBrowserInfo, s as darwinChromeCandidates } from "./launcher-BnxRC9AU.js";
1
+ import { _ as windowsEnvChromeCandidates, c as defaultLauncherStatePath, f as launchLocalBrowser, g as stopLocalBrowser, h as posixChromeCandidates, m as localBrowserInfo, s as darwinChromeCandidates } from "./launcher-CArkmr6f.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
4
  import { appendFileSync, constants, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
5
5
  import { homedir, tmpdir } from "node:os";
6
- import { basename, dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
6
+ import path, { basename, dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { execFile, spawn } from "node:child_process";
9
9
  import { isIP } from "node:net";
10
- import { access, chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, symlink, writeFile } from "node:fs/promises";
10
+ import fsp, { access, chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, symlink, writeFile } from "node:fs/promises";
11
11
  import { promisify } from "node:util";
12
12
  import { request } from "node:http";
13
+ import dns from "node:dns";
13
14
  import { createHash, randomUUID } from "node:crypto";
14
15
  import z from "@deepseek-ai/schemastery";
15
16
  import { pipeline } from "node:stream/promises";
@@ -278,20 +279,20 @@ async function browserWsUrl(port, retries = 2) {
278
279
  const j$1 = await r.json();
279
280
  if (!j$1.webSocketDebuggerUrl) throw new Error("browser did not expose webSocketDebuggerUrl");
280
281
  return j$1.webSocketDebuggerUrl;
281
- } catch (err) {
282
- const nm = err?.name;
282
+ } catch (err$1) {
283
+ const nm = err$1?.name;
283
284
  const timedOut = nm === "TimeoutError" || nm === "AbortError";
284
- const refused = err instanceof TypeError;
285
+ const refused = err$1 instanceof TypeError;
285
286
  if ((timedOut || refused) && attempt < retries) {
286
- await sleep(500);
287
+ await sleep$1(500);
287
288
  continue;
288
289
  }
289
290
  if (timedOut) throw new Error(`/json/version on port ${port} timed out after ${retries + 1} attempts`);
290
291
  if (refused) throw new Error(`DevTools HTTP endpoint unreachable on port ${port} after ${retries + 1} attempts (connection refused — the browser may have exited right after publishing the port)`);
291
- throw err;
292
+ throw err$1;
292
293
  }
293
294
  }
294
- function sleep(ms) {
295
+ function sleep$1(ms) {
295
296
  return new Promise((resolve$1) => setTimeout(resolve$1, ms));
296
297
  }
297
298
  /**
@@ -341,7 +342,7 @@ async function closeSourceBrowser(browserExe, platform = process.platform) {
341
342
  const deadline = Date.now() + 15e3;
342
343
  while (Date.now() < deadline) {
343
344
  if ((await sourceBrowserPids(browserExe, null, platform)).length === 0) return true;
344
- await sleep(500);
345
+ await sleep$1(500);
345
346
  }
346
347
  return false;
347
348
  } catch {
@@ -428,10 +429,10 @@ async function importLoginCookies(opts, deps) {
428
429
  ok: false,
429
430
  error: `profile "${opts.profile}" not found in ${browser.label}; available: ${profiles.map((p) => p.dirName).join(", ")}`
430
431
  };
431
- } catch (err) {
432
+ } catch (err$1) {
432
433
  return {
433
434
  ok: false,
434
- error: `cannot read ${browser.label} Local State: ${err?.message || err}`
435
+ error: `cannot read ${browser.label} Local State: ${err$1?.message || err$1}`
435
436
  };
436
437
  }
437
438
  let closedSource = false;
@@ -482,7 +483,7 @@ async function importLoginCookies(opts, deps) {
482
483
  } catch {
483
484
  break;
484
485
  }
485
- await sleep(600);
486
+ await sleep$1(600);
486
487
  }
487
488
  if (leftover.length > 0) {
488
489
  for (const line of leftover) {
@@ -493,13 +494,13 @@ async function importLoginCookies(opts, deps) {
493
494
  "/F"
494
495
  ], { timeout: 5e3 }).catch(() => null);
495
496
  }
496
- await sleep(1500);
497
+ await sleep$1(1500);
497
498
  }
498
499
  }
499
500
  let port = null;
500
501
  for (let attempt = 0; attempt < 2 && port === null && exited === null; attempt++) {
501
502
  if (attempt > 0) {
502
- await sleep(6e3);
503
+ await sleep$1(6e3);
503
504
  try {
504
505
  await rm(linkDir, { force: true });
505
506
  } catch {}
@@ -548,7 +549,7 @@ async function importLoginCookies(opts, deps) {
548
549
  port = parseDevToolsActivePort(await readFile(portFile, "utf8"));
549
550
  if (port !== null) break;
550
551
  } catch {}
551
- await sleep(250);
552
+ await sleep$1(250);
552
553
  }
553
554
  }
554
555
  const earlyExit = exited;
@@ -575,7 +576,7 @@ async function importLoginCookies(opts, deps) {
575
576
  const got = await tempCdp.client.call("Storage.getCookies");
576
577
  all = Array.isArray(got.cookies) ? got.cookies : [];
577
578
  if (all.length > 0 || attempt === 7) break;
578
- await sleep(800);
579
+ await sleep$1(800);
579
580
  }
580
581
  const matched = all.filter((c) => cookieMatchesDomains(c.domain, opts.domains || []));
581
582
  const byDomain = /* @__PURE__ */ new Map();
@@ -630,10 +631,10 @@ async function importLoginCookies(opts, deps) {
630
631
  domains: domainStats
631
632
  };
632
633
  return pendingReport;
633
- } catch (err) {
634
+ } catch (err$1) {
634
635
  return {
635
636
  ok: false,
636
- error: String(err?.message || err)
637
+ error: String(err$1?.message || err$1)
637
638
  };
638
639
  } finally {
639
640
  try {
@@ -647,7 +648,7 @@ async function importLoginCookies(opts, deps) {
647
648
  } catch {}
648
649
  if (srcHandle) {
649
650
  try {
650
- await Promise.race([srcHandle.done, sleep(25e3)]);
651
+ await Promise.race([srcHandle.done, sleep$1(25e3)]);
651
652
  } catch {}
652
653
  if (process.platform === "win32" && linkDir) try {
653
654
  const ps = [
@@ -669,7 +670,7 @@ async function importLoginCookies(opts, deps) {
669
670
  "/F"
670
671
  ], { timeout: 5e3 }).catch(() => null);
671
672
  }
672
- if (String(stdout).trim()) await Promise.race([srcHandle.done, sleep(5e3)]);
673
+ if (String(stdout).trim()) await Promise.race([srcHandle.done, sleep$1(5e3)]);
673
674
  } catch {}
674
675
  }
675
676
  if (linkDir) try {
@@ -819,12 +820,12 @@ async function discoverWebSocketUrl(raw, options = {}) {
819
820
  latencyMs: elapsed()
820
821
  };
821
822
  } catch (error) {
822
- const err = error;
823
- const timedOut = err?.name === "TimeoutError" || err?.name === "AbortError";
823
+ const err$1 = error;
824
+ const timedOut = err$1?.name === "TimeoutError" || err$1?.name === "AbortError";
824
825
  return {
825
826
  ok: false,
826
827
  code: timedOut ? "probe-timeout" : "probe-failed",
827
- message: timedOut ? `no answer from ${target} within ${timeoutMs}ms` : `endpoint unreachable: ${err?.message ?? String(error)}`,
828
+ message: timedOut ? `no answer from ${target} within ${timeoutMs}ms` : `endpoint unreachable: ${err$1?.message ?? String(error)}`,
828
829
  latencyMs: elapsed()
829
830
  };
830
831
  }
@@ -1270,16 +1271,16 @@ function readAll$2(reader) {
1270
1271
  function createSubprocessCliIo(subprocess) {
1271
1272
  return {
1272
1273
  platform: process.platform,
1273
- exists: (path) => {
1274
+ exists: (path$1) => {
1274
1275
  try {
1275
- return existsSync(path);
1276
+ return existsSync(path$1);
1276
1277
  } catch {
1277
1278
  return false;
1278
1279
  }
1279
1280
  },
1280
- which: makeWhich(process.platform, process.env, (path) => {
1281
+ which: makeWhich(process.platform, process.env, (path$1) => {
1281
1282
  try {
1282
- return existsSync(path);
1283
+ return existsSync(path$1);
1283
1284
  } catch {
1284
1285
  return false;
1285
1286
  }
@@ -1312,12 +1313,12 @@ function createSubprocessCliIo(subprocess) {
1312
1313
  ...timedOut ? { timedOut: true } : {},
1313
1314
  latencyMs: Date.now() - startedAt
1314
1315
  };
1315
- } catch (err) {
1316
- const code = err?.code;
1316
+ } catch (err$1) {
1317
+ const code = err$1?.code;
1317
1318
  return {
1318
1319
  exitCode: null,
1319
1320
  stdout: "",
1320
- stderr: err instanceof Error ? err.message : String(err),
1321
+ stderr: err$1 instanceof Error ? err$1.message : String(err$1),
1321
1322
  ...typeof code === "string" ? { spawnErrorCode: code } : {},
1322
1323
  latencyMs: Date.now() - startedAt
1323
1324
  };
@@ -2713,9 +2714,9 @@ function sendJson(res, status, body) {
2713
2714
  res.end(payload);
2714
2715
  }
2715
2716
  /** Proxy a worker loopback endpoint. Returns null when the worker is unreachable. */
2716
- async function proxyFrom(port, path) {
2717
+ async function proxyFrom(port, path$1) {
2717
2718
  try {
2718
- const r = await fetch(`http://127.0.0.1:${port}${path}`, { signal: AbortSignal.timeout(4e3) });
2719
+ const r = await fetch(`http://127.0.0.1:${port}${path$1}`, { signal: AbortSignal.timeout(4e3) });
2719
2720
  if (!r.ok) return null;
2720
2721
  return await r.json();
2721
2722
  } catch {
@@ -2723,9 +2724,9 @@ async function proxyFrom(port, path) {
2723
2724
  }
2724
2725
  }
2725
2726
  /** Proxy a POST with a JSON body to the worker. Returns status and body, or null when unreachable. */
2726
- async function proxyPost(port, path, body, timeoutMs = 4e3) {
2727
+ async function proxyPost(port, path$1, body, timeoutMs = 4e3) {
2727
2728
  try {
2728
- const r = await fetch(`http://127.0.0.1:${port}${path}`, {
2729
+ const r = await fetch(`http://127.0.0.1:${port}${path$1}`, {
2729
2730
  method: "POST",
2730
2731
  headers: { "content-type": "application/json" },
2731
2732
  body: JSON.stringify(body),
@@ -2756,7 +2757,7 @@ async function proxyPost(port, path, body, timeoutMs = 4e3) {
2756
2757
  * markEgoToolCall() can inject `tool-call` events directly into the live
2757
2758
  * stream (the sidebar auto-open signal), without the client polling.
2758
2759
  */
2759
- function proxyWorkerStream(port, res, path) {
2760
+ function proxyWorkerStream(port, res, path$1) {
2760
2761
  let cancelled = false;
2761
2762
  let ended = false;
2762
2763
  const endOnce = () => {
@@ -2786,7 +2787,7 @@ function proxyWorkerStream(port, res, path) {
2786
2787
  const up = request({
2787
2788
  host: "127.0.0.1",
2788
2789
  port,
2789
- path,
2790
+ path: path$1,
2790
2791
  method: "GET",
2791
2792
  headers: { accept: "text/event-stream" }
2792
2793
  }, (upRes) => {
@@ -2833,7 +2834,7 @@ function proxyWorkerStream(port, res, path) {
2833
2834
  }
2834
2835
  function proxyWorkerVideo(port, req, res) {
2835
2836
  const generation = new URL(req.url || EGO_VIDEO_ROUTE, "http://dsh.internal").searchParams.get("generation");
2836
- const path = `/api/video/stream${generation ? `?generation=${encodeURIComponent(generation)}` : ""}`;
2837
+ const path$1 = `/api/video/stream${generation ? `?generation=${encodeURIComponent(generation)}` : ""}`;
2837
2838
  let upstream;
2838
2839
  let ended = false;
2839
2840
  const end = () => {
@@ -2846,7 +2847,7 @@ function proxyWorkerVideo(port, req, res) {
2846
2847
  upstream = request({
2847
2848
  host: "127.0.0.1",
2848
2849
  port,
2849
- path,
2850
+ path: path$1,
2850
2851
  method: "GET",
2851
2852
  headers: { accept: "video/mp4" }
2852
2853
  }, (upRes) => {
@@ -2930,8 +2931,8 @@ function isProcessAlive$1(pid) {
2930
2931
  try {
2931
2932
  process.kill(pid, 0);
2932
2933
  return true;
2933
- } catch (err) {
2934
- const e = err;
2934
+ } catch (err$1) {
2935
+ const e = err$1;
2935
2936
  return e && e.code === "EPERM";
2936
2937
  }
2937
2938
  }
@@ -3282,10 +3283,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
3282
3283
  if (port === null) try {
3283
3284
  const out = await captureOnDemand(targetId);
3284
3285
  return sendJson(res, out.ok === true ? 200 : 502, out);
3285
- } catch (err) {
3286
+ } catch (err$1) {
3286
3287
  return sendJson(res, 500, {
3287
3288
  ok: false,
3288
- error: `${err?.message ?? err}`.slice(0, 200)
3289
+ error: `${err$1?.message ?? err$1}`.slice(0, 200)
3289
3290
  });
3290
3291
  }
3291
3292
  return sendJson(res, 200, {
@@ -3304,10 +3305,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
3304
3305
  try {
3305
3306
  const out = await syncOnRefresh();
3306
3307
  return sendJson(res, out.ok === true ? 200 : 409, out);
3307
- } catch (err) {
3308
+ } catch (err$1) {
3308
3309
  return sendJson(res, 500, {
3309
3310
  ok: false,
3310
- error: `${err?.message ?? err}`.slice(0, 200)
3311
+ error: `${err$1?.message ?? err$1}`.slice(0, 200)
3311
3312
  });
3312
3313
  }
3313
3314
  }
@@ -3616,10 +3617,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
3616
3617
  try {
3617
3618
  const result = await openAgentWindow$1();
3618
3619
  return sendJson(res, result.ok ? 200 : 500, result);
3619
- } catch (err) {
3620
+ } catch (err$1) {
3620
3621
  return sendJson(res, 500, {
3621
3622
  ok: false,
3622
- error: String(err?.message || err)
3623
+ error: String(err$1?.message || err$1)
3623
3624
  });
3624
3625
  }
3625
3626
  }
@@ -3645,10 +3646,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
3645
3646
  dryRun: body.dryRun === true
3646
3647
  });
3647
3648
  return sendJson(res, result.ok ? 200 : 400, result);
3648
- } catch (err) {
3649
+ } catch (err$1) {
3649
3650
  return sendJson(res, 500, {
3650
3651
  ok: false,
3651
- error: String(err?.message || err)
3652
+ error: String(err$1?.message || err$1)
3652
3653
  });
3653
3654
  }
3654
3655
  }
@@ -3680,9 +3681,9 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
3680
3681
  [EGO_WATCH_START_ROUTE, "/api/watch/start"],
3681
3682
  [EGO_WATCH_SWITCH_ROUTE, "/api/watch/switch"],
3682
3683
  [EGO_WATCH_STOP_ROUTE, "/api/watch/stop"]
3683
- ].map(([path, workerPath]) => server.register({
3684
+ ].map(([path$1, workerPath]) => server.register({
3684
3685
  kind: "exact",
3685
- path,
3686
+ path: path$1,
3686
3687
  handler: async (reqRaw, resRaw) => {
3687
3688
  const req = reqRaw;
3688
3689
  const res = resRaw;
@@ -4022,6 +4023,430 @@ function buildFrameScript(spaceJson, opts = {}) {
4022
4023
  return `const __task = await taskSpaces.useOrCreate(${spaceJson})\nlet __tabs = []\ntry { __tabs = await browser.listTabs() } catch { __tabs = [] }\nconst __blank = (u) => /^(about:|chrome:|chrome-extension:|edge:|devtools:|data:)/.test(String(u || ''))\nconst __active = __tabs.find((t) => t.active === true) || __tabs.find((t) => !__blank(t.url)) || __tabs[0] || null\nconst __all = ${all ? "true" : "false"}\nconst __cap = async (t) => {\n try {\n const __att = await cdp('Target.attachToTarget', { targetId: t.targetId, flatten: true })\n const __sid = __att && __att.sessionId\n if (!__sid) return null\n let __u = t.url || ''\n let __ti = t.title || ''\n try {\n const __m = await cdp('Runtime.evaluate', { expression: '({url: location.href, title: document.title})', returnByValue: true }, __sid)\n const __v = (__m && __m.result && __m.result.value) || {}\n __u = __v.url || __u\n __ti = __v.title || __ti\n } catch {}\n const __s = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70, fromSurface: true }, __sid)\n try { await cdp('Target.detachFromTarget', { sessionId: __sid }) } catch {}\n if (!__s || !__s.data) return null\n return { targetId: t.targetId, png: __s.data, fmt: 'jpeg', url: __u, title: __ti }\n } catch { return null }\n}\nconst __frames = []\nconst __plan = __all ? __tabs.slice(0, ${maxTabs}) : (__active ? [__active] : [])\nfor (const __t of __plan) {\n const __img = await __cap(__t)\n if (__img) __frames.push(__img)\n}\nlet __png = ''\nlet __fmt = 'jpeg'\nlet __url = ''\nlet __title = ''\nlet __targetId = ''\nconst __actImg = __frames.find((f) => __active && f.targetId === __active.targetId) || __frames[0] || null\nif (__actImg) { __png = __actImg.png; __fmt = __actImg.fmt; __url = __actImg.url; __title = __actImg.title; __targetId = __actImg.targetId }\nif (__png === '') {\n let __info = {}\n try { __info = await page.info() } catch { __info = {} }\n const __p = await page.screenshot({ fullPage: false })\n const __fs = await import('node:fs/promises')\n __png = (await __fs.readFile(__p)).toString('base64')\n try { await __fs.unlink(__p) } catch {}\n __fmt = 'png'\n __url = __url || __info.url || ''\n __title = __title || __info.title || ''\n if (__targetId === '') {\n const __match = __tabs.find((t) => (__info.url || '') !== '' && t.url === __info.url)\n __targetId = (__match && __match.targetId) || ''\n }\n __frames.push({ targetId: __targetId, png: __png, fmt: __fmt, url: __url, title: __title })\n}\nconsole.log(${JSON.stringify(FRAME_SENTINEL)} + JSON.stringify({ png: __png, fmt: __fmt, url: __url, title: __title, targetId: __targetId, frames: __frames, tabs: __tabs.map((t) => ({ targetId: t.targetId, url: t.url || '', title: t.title || '', active: t.active === true })) }))\n`;
4023
4024
  }
4024
4025
 
4026
+ //#endregion
4027
+ //#region src/worker/endpoint-authority.ts
4028
+ /** pid:port identity of one browser instance; stable across ws reconnects. */
4029
+ function instanceKey(pid, port) {
4030
+ return `${pid ?? "nopid"}:${port ?? "noport"}`;
4031
+ }
4032
+ const LOOPBACK_HOSTS = new Set([
4033
+ "127.0.0.1",
4034
+ "localhost",
4035
+ "0.0.0.0",
4036
+ "::1",
4037
+ "[::1]"
4038
+ ]);
4039
+ /**
4040
+ * Is this host (or ws/http URL host segment) loopback? A proxy-prefixed host
4041
+ * segment like "gateway.corp:8443/127.0.0.1" is NOT loopback — that is a remote
4042
+ * path and keeps env authority (#12 regression guard).
4043
+ */
4044
+ function isLoopbackHost(host) {
4045
+ return LOOPBACK_HOSTS.has(host.toLowerCase());
4046
+ }
4047
+ function num$1(v) {
4048
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null;
4049
+ }
4050
+ function str$1(v) {
4051
+ return typeof v === "string" && v !== "" ? v : null;
4052
+ }
4053
+ /** browser.json / launcher.json share one shape interest: port + optional ws endpoint + pid. */
4054
+ function stateRecord(raw, source, fresh$1) {
4055
+ if (raw === null) return null;
4056
+ const port = num$1(raw.port);
4057
+ if (port === null) return null;
4058
+ return {
4059
+ port,
4060
+ wsUrl: str$1(raw.wsUrl) ?? (str$1(raw.endpoint)?.startsWith("ws") ? str$1(raw.endpoint) : null),
4061
+ pid: num$1(raw.pid),
4062
+ source,
4063
+ fresh: fresh$1
4064
+ };
4065
+ }
4066
+ /** Parse EGO_LINUX_CDP_URL into a candidate; unparseable (proxy-prefixed) URLs keep env-source with wsUrl only. */
4067
+ function envCandidate(env) {
4068
+ const raw = env.EGO_LINUX_CDP_URL;
4069
+ if (!raw) return null;
4070
+ let parsed = null;
4071
+ try {
4072
+ parsed = new URL(raw);
4073
+ } catch {
4074
+ parsed = null;
4075
+ }
4076
+ if (parsed === null || !isLoopbackHost(parsed.hostname)) return {
4077
+ port: null,
4078
+ wsUrl: raw,
4079
+ pid: null,
4080
+ source: "env",
4081
+ fresh: 0,
4082
+ trustWsUrl: true
4083
+ };
4084
+ return {
4085
+ port: num$1(Number(parsed.port)),
4086
+ wsUrl: raw,
4087
+ pid: null,
4088
+ source: "env",
4089
+ fresh: 0
4090
+ };
4091
+ }
4092
+ /**
4093
+ * Build the resolver bound to one set of state paths. `fingerprint()` lets the
4094
+ * 5s watcher skip ALL probing (zero network) while neither mtime nor the
4095
+ * recorded port changed; `remoteAuthoritative()` gates the whole watcher off
4096
+ * for remote env.
4097
+ */
4098
+ function createEndpointResolver(io, paths) {
4099
+ const envRemote = () => {
4100
+ const c = envCandidate(io.env);
4101
+ return c !== null && c.source === "env" && c.port === null;
4102
+ };
4103
+ async function collectCandidates() {
4104
+ const [stateMtime, launcherMtime, stateRaw, launcherRaw] = await Promise.all([
4105
+ io.statMtime(paths.browserStatePath),
4106
+ io.statMtime(paths.launcherStatePath),
4107
+ io.readJson(paths.browserStatePath),
4108
+ io.readJson(paths.launcherStatePath)
4109
+ ]);
4110
+ const out = [];
4111
+ const state$1 = stateRecord(stateRaw, "state", stateMtime);
4112
+ if (state$1) out.push({
4113
+ ...state$1,
4114
+ fresh: Math.max(stateMtime, state$1.fresh)
4115
+ });
4116
+ const launcher = stateRecord(launcherRaw, "launcher", launcherMtime);
4117
+ if (launcher) out.push({
4118
+ ...launcher,
4119
+ fresh: Math.max(launcherMtime, launcher.fresh)
4120
+ });
4121
+ const candidates = out.map((r) => ({
4122
+ port: r.port,
4123
+ wsUrl: r.wsUrl,
4124
+ pid: r.pid,
4125
+ source: r.source,
4126
+ fresh: r.fresh
4127
+ }));
4128
+ candidates.sort((a, b) => Number(io.isAlive(b.pid ?? -1)) - Number(io.isAlive(a.pid ?? -1)) || b.fresh - a.fresh);
4129
+ return candidates;
4130
+ }
4131
+ async function probeCandidate(c) {
4132
+ if (c.trustWsUrl === true && c.wsUrl !== null) return {
4133
+ wsUrl: c.wsUrl,
4134
+ port: c.port,
4135
+ pid: c.pid,
4136
+ instanceKey: instanceKey(c.pid, c.port)
4137
+ };
4138
+ if (c.port === null) return null;
4139
+ const version = await io.fetchVersion(`http://127.0.0.1:${c.port}/json/version`);
4140
+ if (version === null) return null;
4141
+ const wsUrl = c.wsUrl ?? str$1(version.wsUrl);
4142
+ if (wsUrl === null) return null;
4143
+ return {
4144
+ wsUrl,
4145
+ port: c.port,
4146
+ pid: c.pid,
4147
+ instanceKey: instanceKey(c.pid, c.port)
4148
+ };
4149
+ }
4150
+ async function resolve$1() {
4151
+ const env = envCandidate(io.env);
4152
+ if (env !== null && env.trustWsUrl === true) return {
4153
+ wsUrl: env.wsUrl,
4154
+ port: null,
4155
+ pid: null,
4156
+ instanceKey: instanceKey(null, null)
4157
+ };
4158
+ const candidates = await collectCandidates();
4159
+ for (const c of candidates) {
4160
+ const hit = await probeCandidate(c);
4161
+ if (hit !== null) return hit;
4162
+ }
4163
+ if (env !== null && env.source === "env") {
4164
+ const hit = await probeCandidate(env);
4165
+ if (hit !== null) return hit;
4166
+ if (env.wsUrl !== null && env.port === null) return {
4167
+ wsUrl: env.wsUrl,
4168
+ port: null,
4169
+ pid: null,
4170
+ instanceKey: instanceKey(null, null)
4171
+ };
4172
+ }
4173
+ return null;
4174
+ }
4175
+ async function fingerprint() {
4176
+ const [a, b, stateRaw, launcherRaw] = await Promise.all([
4177
+ io.statMtime(paths.browserStatePath),
4178
+ io.statMtime(paths.launcherStatePath),
4179
+ io.readJson(paths.browserStatePath),
4180
+ io.readJson(paths.launcherStatePath)
4181
+ ]);
4182
+ const state$1 = stateRecord(stateRaw, "state", a);
4183
+ const launcher = stateRecord(launcherRaw, "launcher", b);
4184
+ return `${a}:${state$1?.port ?? "-"}|${b}:${launcher?.port ?? "-"}`;
4185
+ }
4186
+ return {
4187
+ resolve: resolve$1,
4188
+ fingerprint,
4189
+ remoteAuthoritative: envRemote
4190
+ };
4191
+ }
4192
+
4193
+ //#endregion
4194
+ //#region src/browser-fetch.ts
4195
+ const BROWSER_FETCH_SERVICE_NAME = "browser-fetch";
4196
+ const MAX_BYTES_LIMIT = 2 * 1024 * 1024;
4197
+ const DEFAULT_MAX_BYTES = 1024 * 1024;
4198
+ const DEFAULT_TIMEOUT_MS = 2e4;
4199
+ /** settle window for waitUntil:'idle' after load fired. */
4200
+ const IDLE_SETTLE_MS = 800;
4201
+ /** Loopback/private/reserved literals + well-known internal names → true (refuse). */
4202
+ function isBlockedHost(host) {
4203
+ const h = host.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
4204
+ if (h === "") return true;
4205
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal") || h.endsWith(".localdomain") || h.endsWith(".onion")) return true;
4206
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(h)) return isPrivateIpV4(h);
4207
+ if (h.includes(":")) {
4208
+ if (h === "::1" || h === "::") return true;
4209
+ const mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
4210
+ if (mapped) return isPrivateIpV4(mapped[1]);
4211
+ const head = h.replace(/[^0-9a-f]/g, "").slice(0, 4);
4212
+ const hi = parseInt(head.padEnd(4, "0"), 16);
4213
+ if (!Number.isFinite(hi)) return true;
4214
+ if ((hi & 65024) === 64512) return true;
4215
+ if ((hi & 65472) === 65152) return true;
4216
+ return false;
4217
+ }
4218
+ return false;
4219
+ }
4220
+ function isPrivateIpV4(ip) {
4221
+ const parts = ip.split(".").map((n) => Number(n));
4222
+ if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
4223
+ const [a = 0, b = 0] = parts;
4224
+ if (a === 0 || a === 10 || a === 127) return true;
4225
+ if (a === 169 && b === 254) return true;
4226
+ if (a === 172 && b >= 16 && b <= 31) return true;
4227
+ if (a === 192 && b === 168) return true;
4228
+ if (a === 100 && b >= 64 && b <= 127) return true;
4229
+ if (a >= 224) return true;
4230
+ return false;
4231
+ }
4232
+ /** Returns an explanation when blocked, '' when allowed. */
4233
+ async function blockedTargetReason(urlObj) {
4234
+ if (urlObj.protocol !== "http:" && urlObj.protocol !== "https:") return `unsupported protocol "${urlObj.protocol}"`;
4235
+ if (isBlockedHost(urlObj.hostname)) return `${urlObj.hostname} is a loopback/private/reserved target`;
4236
+ try {
4237
+ const addrs = await dns.promises.lookup(urlObj.hostname, { all: true });
4238
+ for (const a of addrs) if (a.family === 4 ? isPrivateIpV4(a.address) : isBlockedHost(a.address)) return `${urlObj.hostname} resolves to private/reserved address ${a.address}`;
4239
+ } catch {
4240
+ return `cannot resolve ${urlObj.hostname}`;
4241
+ }
4242
+ return "";
4243
+ }
4244
+ const defaultConnect = async (wsUrl, timeoutMs) => {
4245
+ const WsImpl = globalThis.WebSocket;
4246
+ if (!WsImpl) throw new Error("global WebSocket is unavailable (Node >= 22 required)");
4247
+ const ws = new WsImpl(wsUrl);
4248
+ await new Promise((resolve$1, reject) => {
4249
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`CDP websocket open timed out: ${wsUrl}`)), timeoutMs);
4250
+ ws.addEventListener("open", () => {
4251
+ clearTimeout(timer);
4252
+ resolve$1();
4253
+ }, { once: true });
4254
+ ws.addEventListener("error", () => {
4255
+ clearTimeout(timer);
4256
+ reject(/* @__PURE__ */ new Error(`CDP websocket connect failed: ${wsUrl}`));
4257
+ }, { once: true });
4258
+ });
4259
+ return {
4260
+ client: new CdpClient(ws),
4261
+ close: () => {
4262
+ try {
4263
+ ws.close();
4264
+ } catch {}
4265
+ }
4266
+ };
4267
+ };
4268
+ function createMainEndpointResolver(env = process.env) {
4269
+ const io = {
4270
+ statMtime: async (p) => {
4271
+ try {
4272
+ return (await fsp.stat(p)).mtimeMs;
4273
+ } catch {
4274
+ return -1;
4275
+ }
4276
+ },
4277
+ readJson: async (p) => {
4278
+ try {
4279
+ return JSON.parse(await fsp.readFile(p, "utf8"));
4280
+ } catch {
4281
+ return null;
4282
+ }
4283
+ },
4284
+ fetchVersion: async (u) => {
4285
+ try {
4286
+ const r = await fetch(u, { signal: AbortSignal.timeout(1e3) });
4287
+ if (!r.ok) return null;
4288
+ const j$1 = await r.json();
4289
+ return { wsUrl: typeof j$1.webSocketDebuggerUrl === "string" ? j$1.webSocketDebuggerUrl : void 0 };
4290
+ } catch {
4291
+ return null;
4292
+ }
4293
+ },
4294
+ isAlive: (pid) => {
4295
+ try {
4296
+ process.kill(pid, 0);
4297
+ return true;
4298
+ } catch {
4299
+ return false;
4300
+ }
4301
+ },
4302
+ env
4303
+ };
4304
+ const stateDir = resolveEgoStateDir(env);
4305
+ const resolver = createEndpointResolver(io, {
4306
+ browserStatePath: path.join(stateDir, "browser.json"),
4307
+ launcherStatePath: defaultLauncherStatePath()
4308
+ });
4309
+ return async () => {
4310
+ try {
4311
+ return (await resolver.resolve())?.wsUrl ?? null;
4312
+ } catch {
4313
+ return null;
4314
+ }
4315
+ };
4316
+ }
4317
+ function createBrowserFetchService(deps = {}) {
4318
+ const resolveEndpoint = deps.resolveEndpoint ?? createMainEndpointResolver();
4319
+ const connect = deps.connect ?? defaultConnect;
4320
+ async function fetchOnce(wsUrl, req, budgetMs, byteCap, signal) {
4321
+ let conn = null;
4322
+ let targetId = null;
4323
+ let sessionId = null;
4324
+ try {
4325
+ conn = await connect(wsUrl, 5e3);
4326
+ const client = conn.client;
4327
+ const created = await client.call("Target.createTarget", {
4328
+ url: "about:blank",
4329
+ background: true
4330
+ }, void 0, 8e3);
4331
+ targetId = typeof created?.targetId === "string" ? created.targetId : null;
4332
+ if (!targetId) return err("nav-failed", "Target.createTarget returned no targetId");
4333
+ const attached = await client.call("Target.attachToTarget", {
4334
+ targetId,
4335
+ flatten: true
4336
+ }, void 0, 8e3);
4337
+ sessionId = typeof attached?.sessionId === "string" ? attached.sessionId : null;
4338
+ if (!sessionId) return err("nav-failed", "Target.attachToTarget returned no sessionId");
4339
+ await client.call("Page.enable", {}, sessionId, 5e3);
4340
+ await client.call("Network.enable", {}, sessionId, 5e3);
4341
+ let statusCode = null;
4342
+ let docUrl = null;
4343
+ const offResponse = client.on("Network.responseReceived", (params, sid) => {
4344
+ if (sid !== sessionId) return;
4345
+ const p = params;
4346
+ if (p?.type === "Document" && typeof p.response?.status === "number") {
4347
+ statusCode = p.response.status;
4348
+ if (typeof p.response.url === "string") docUrl = p.response.url;
4349
+ }
4350
+ });
4351
+ const loadWait = new Promise((resolve$1) => {
4352
+ const t = setTimeout(() => resolve$1("timeout"), budgetMs);
4353
+ const off = client.on("Page.loadEventFired", (_params, sid) => {
4354
+ if (sid !== sessionId) return;
4355
+ clearTimeout(t);
4356
+ off();
4357
+ resolve$1("loaded");
4358
+ });
4359
+ const onAb = () => {
4360
+ clearTimeout(t);
4361
+ off();
4362
+ resolve$1("aborted");
4363
+ };
4364
+ if (signal?.aborted) {
4365
+ onAb();
4366
+ return;
4367
+ }
4368
+ signal?.addEventListener("abort", onAb, { once: true });
4369
+ });
4370
+ await client.call("Page.navigate", { url: req.url }, sessionId, Math.min(budgetMs, 15e3));
4371
+ const waited = await loadWait;
4372
+ offResponse();
4373
+ if (waited === "aborted") return err("timeout", "aborted while waiting for page load");
4374
+ if (waited === "timeout") return err("timeout", `page load exceeded ${budgetMs}ms`);
4375
+ if (req.waitUntil === "idle") await sleep(IDLE_SETTLE_MS);
4376
+ const evaluated = await client.call("Runtime.evaluate", {
4377
+ expression: "document.documentElement ? document.documentElement.outerHTML : \"\"",
4378
+ returnByValue: true
4379
+ }, sessionId, 1e4);
4380
+ const html = typeof evaluated?.result?.value === "string" ? evaluated.result.value : "";
4381
+ if (!html) return err("nav-failed", "rendered page produced empty DOM");
4382
+ const truncated = Buffer.byteLength(html, "utf8") > byteCap;
4383
+ return {
4384
+ ok: true,
4385
+ finalUrl: docUrl ?? req.url,
4386
+ statusCode,
4387
+ html: truncated ? clipUtf8(html, byteCap) : html,
4388
+ truncated
4389
+ };
4390
+ } catch (error) {
4391
+ return err("nav-failed", error instanceof Error ? error.message : String(error));
4392
+ } finally {
4393
+ if (conn) {
4394
+ if (targetId) try {
4395
+ await conn.client.call("Target.closeTarget", { targetId }, void 0, 3e3);
4396
+ } catch {}
4397
+ try {
4398
+ conn.close();
4399
+ } catch {}
4400
+ }
4401
+ }
4402
+ }
4403
+ return { async fetchRenderedHtml(req, signal) {
4404
+ let urlObj;
4405
+ try {
4406
+ urlObj = new URL(String(req?.url ?? ""));
4407
+ } catch {
4408
+ return err("bad-request", `invalid url: ${String(req?.url).slice(0, 120)}`);
4409
+ }
4410
+ const blocked = await blockedTargetReason(urlObj);
4411
+ if (blocked !== "") return err("blocked-target", blocked);
4412
+ const byteCap = Math.min(Math.max(Number(req.maxBytes) || DEFAULT_MAX_BYTES, 1024), MAX_BYTES_LIMIT);
4413
+ const budgetMs = Math.min(Math.max(Number(req.timeoutMs) || DEFAULT_TIMEOUT_MS, 1e3), 6e4);
4414
+ let last = err("no-browser", "no endpoint attempt made");
4415
+ for (let attempt = 0; attempt < 2; attempt++) {
4416
+ const wsUrl = await resolveEndpoint();
4417
+ if (wsUrl === null) return err("no-browser", "no live browser endpoint (state files unprobed) — start the agent browser first");
4418
+ try {
4419
+ last = await fetchOnce(wsUrl, req, budgetMs, byteCap, signal);
4420
+ } catch (error) {
4421
+ last = err("nav-failed", error instanceof Error ? error.message : String(error));
4422
+ }
4423
+ if (last.ok === true) return last;
4424
+ if (last.error.code !== "nav-failed" || attempt === 1 || signal?.aborted) return last;
4425
+ }
4426
+ return last;
4427
+ } };
4428
+ }
4429
+ function err(code, message) {
4430
+ return {
4431
+ ok: false,
4432
+ error: {
4433
+ code,
4434
+ message: message.slice(0, 300)
4435
+ }
4436
+ };
4437
+ }
4438
+ function sleep(ms) {
4439
+ return new Promise((resolve$1) => setTimeout(resolve$1, ms));
4440
+ }
4441
+ /** UTF-8 safe clip at byteCap without splitting a multi-byte character. */
4442
+ function clipUtf8(text, byteCap) {
4443
+ const buf = Buffer.from(text, "utf8");
4444
+ if (buf.length <= byteCap) return text;
4445
+ let end = byteCap;
4446
+ while (end > 0 && (buf[end] & 192) === 128) end--;
4447
+ return buf.subarray(0, end).toString("utf8");
4448
+ }
4449
+
4025
4450
  //#endregion
4026
4451
  //#region src/worker/window-size.ts
4027
4452
  /** Chrome refuses slivers; below this a resize is not worth sending. */
@@ -6533,14 +6958,14 @@ async function tabsCommand(deps) {
6533
6958
  }
6534
6959
  /** shot — 复用 `bcdp_screenshot`;默认落到工作区内 `.dsh-tui/shots/`。 */
6535
6960
  async function shotCommand(deps, target) {
6536
- const path = target.trim() === "" ? join(process.cwd(), ".dsh-tui", "shots", `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.png`) : isAbsolute(target.trim()) ? target.trim() : join(process.cwd(), target.trim());
6961
+ const path$1 = target.trim() === "" ? join(process.cwd(), ".dsh-tui", "shots", `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.png`) : isAbsolute(target.trim()) ? target.trim() : join(process.cwd(), target.trim());
6537
6962
  try {
6538
- mkdirSync(dirname(path), { recursive: true });
6539
- const value = await deps.runTool("bcdp_screenshot", { path });
6963
+ mkdirSync(dirname(path$1), { recursive: true });
6964
+ const value = await deps.runTool("bcdp_screenshot", { path: path$1 });
6540
6965
  if (value && value.ok === false) return fail(`bcdp shot: ${clip(value.reason || "截图失败", 80)}`, "next: /bcdp status");
6541
6966
  return ok([
6542
6967
  `bcdp shot — 已保存`,
6543
- ` ${value?.path ?? path}`,
6968
+ ` ${value?.path ?? path$1}`,
6544
6969
  " 用图像工具读取该 PNG;本命令不再回传像素"
6545
6970
  ]);
6546
6971
  } catch (error) {
@@ -7395,7 +7820,7 @@ function codedError$3(code, message) {
7395
7820
 
7396
7821
  //#endregion
7397
7822
  //#region src/ffmpeg-probe.ts
7398
- function runFfmpegProbe(path, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 } = {}) {
7823
+ function runFfmpegProbe(path$1, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 } = {}) {
7399
7824
  return new Promise((resolve$1) => {
7400
7825
  let child;
7401
7826
  let output = "";
@@ -7410,7 +7835,7 @@ function runFfmpegProbe(path, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 }
7410
7835
  });
7411
7836
  };
7412
7837
  try {
7413
- child = spawn$1(path, argv, {
7838
+ child = spawn$1(path$1, argv, {
7414
7839
  shell: false,
7415
7840
  windowsHide: true,
7416
7841
  stdio: [
@@ -7442,23 +7867,23 @@ function runFfmpegProbe(path, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 }
7442
7867
  }, timeoutMs);
7443
7868
  });
7444
7869
  }
7445
- async function probeFfmpeg(path, { platform = process.platform, env = process.env, spawn: spawn$1 = spawn, requestedEncoder = "auto" } = {}) {
7446
- const versionResult = await runFfmpegProbe(path, ["-version"], { spawn: spawn$1 });
7447
- if (!versionResult.ok) throw codedError$2("ffmpeg-not-executable", `FFmpeg is not executable: ${path}`);
7870
+ async function probeFfmpeg(path$1, { platform = process.platform, env = process.env, spawn: spawn$1 = spawn, requestedEncoder = "auto" } = {}) {
7871
+ const versionResult = await runFfmpegProbe(path$1, ["-version"], { spawn: spawn$1 });
7872
+ if (!versionResult.ok) throw codedError$2("ffmpeg-not-executable", `FFmpeg is not executable: ${path$1}`);
7448
7873
  const version = versionResult.output.split(/\r?\n/, 1)[0] || "FFmpeg";
7449
7874
  if (platform === "win32") {
7450
- const support = await runFfmpegProbe(path, [
7875
+ const support = await runFfmpegProbe(path$1, [
7451
7876
  "-hide_banner",
7452
7877
  "-h",
7453
7878
  "filter=gfxcapture"
7454
7879
  ], { spawn: spawn$1 });
7455
7880
  if (!support.ok || !/Filter gfxcapture\b/.test(support.output)) throw codedError$2("ffmpeg-gfxcapture-unavailable", "FFmpeg does not support Windows gfxcapture");
7456
7881
  } else if (platform === "darwin") {
7457
- const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
7882
+ const devices = await runFfmpegProbe(path$1, ["-hide_banner", "-devices"], { spawn: spawn$1 });
7458
7883
  if (!devices.ok || !/avfoundation/i.test(devices.output)) throw codedError$2("ffmpeg-capture-input-unavailable", "FFmpeg does not support avfoundation capture");
7459
7884
  } else if (platform === "linux") {
7460
7885
  if (env.XDG_SESSION_TYPE === "wayland" || env.WAYLAND_DISPLAY) throw codedError$2("ffmpeg-platform-unsupported", "Wayland capture is not supported");
7461
- const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
7886
+ const devices = await runFfmpegProbe(path$1, ["-hide_banner", "-devices"], { spawn: spawn$1 });
7462
7887
  if (!devices.ok || !/x11grab/i.test(devices.output)) throw codedError$2("ffmpeg-capture-input-unavailable", "FFmpeg does not support x11grab capture");
7463
7888
  }
7464
7889
  const encoders = requestedEncoder === "auto" ? platform === "win32" ? [
@@ -7473,7 +7898,7 @@ async function probeFfmpeg(path, { platform = process.platform, env = process.en
7473
7898
  "h264_qsv",
7474
7899
  "libx264"
7475
7900
  ] : [requestedEncoder === "software" ? "libx264" : requestedEncoder];
7476
- for (const encoder$1 of encoders) if ((await runFfmpegProbe(path, [
7901
+ for (const encoder$1 of encoders) if ((await runFfmpegProbe(path$1, [
7477
7902
  "-hide_banner",
7478
7903
  "-loglevel",
7479
7904
  "error",
@@ -7933,22 +8358,22 @@ function safeArchiveEntry(entry) {
7933
8358
  const value = entry.replaceAll("\\", "/");
7934
8359
  return value !== "" && !value.startsWith("/") && !/^[A-Za-z]:/.test(value) && !value.split("/").includes("..");
7935
8360
  }
7936
- async function prepareMacExecutable(path, arch, spawn$1) {
8361
+ async function prepareMacExecutable(path$1, arch, spawn$1) {
7937
8362
  await runCommand("xattr", [
7938
8363
  "-d",
7939
8364
  "com.apple.quarantine",
7940
- path
8365
+ path$1
7941
8366
  ], spawn$1, 5e3).catch(() => {});
7942
8367
  if (arch === "arm64") await runCommand("codesign", [
7943
8368
  "--force",
7944
8369
  "--sign",
7945
8370
  "-",
7946
- path
8371
+ path$1
7947
8372
  ], spawn$1, 15e3).catch(() => {});
7948
8373
  }
7949
- async function hashFile(path) {
8374
+ async function hashFile(path$1) {
7950
8375
  const hash = createHash("sha256");
7951
- for await (const chunk of createReadStream(path)) hash.update(chunk);
8376
+ for await (const chunk of createReadStream(path$1)) hash.update(chunk);
7952
8377
  return hash.digest("hex");
7953
8378
  }
7954
8379
  function readChunk(reader, timeoutMs) {
@@ -8710,8 +9135,8 @@ function numberMap(value) {
8710
9135
  const out = {};
8711
9136
  if (value === null || typeof value !== "object") return out;
8712
9137
  for (const [key, raw] of Object.entries(value)) {
8713
- const num$1 = Number(raw);
8714
- if (Number.isFinite(num$1)) out[key] = num$1;
9138
+ const num$2 = Number(raw);
9139
+ if (Number.isFinite(num$2)) out[key] = num$2;
8715
9140
  }
8716
9141
  return out;
8717
9142
  }
@@ -11434,8 +11859,8 @@ function describeStderr(stderr) {
11434
11859
  const tail = stderr.trim();
11435
11860
  return tail === "" ? "" : `\n--- ego-browser stderr (tail) ---\n${tail.slice(-2e3)}`;
11436
11861
  }
11437
- function describeSpawnFailure(err) {
11438
- const msg = err instanceof Error ? err.message : String(err);
11862
+ function describeSpawnFailure(err$1) {
11863
+ const msg = err$1 instanceof Error ? err$1.message : String(err$1);
11439
11864
  if (/ENOENT|spawn .* ENOENT|not found|could not load|cannot find module/i.test(msg)) return "ego-browser CLI could not be started. For the vendored runtime, make sure a Chrome/Chromium is reachable (PATH, or set EGO_LINUX_CHROME; root users need a --no-sandbox wrapper, see AGENTS.md). To use an official host instead, set egoBin to your `ego-browser` command. " + msg;
11440
11865
  return `failed to start ego-browser: ${msg}`;
11441
11866
  }
@@ -11528,10 +11953,10 @@ async function openAgentWindow(ctx, cfg) {
11528
11953
  error: readAll(handle.collected.stderr).trim() || `ego-browser --open exited with code ${outcome.exitCode}`
11529
11954
  };
11530
11955
  return { ok: true };
11531
- } catch (err) {
11956
+ } catch (err$1) {
11532
11957
  return {
11533
11958
  ok: false,
11534
- error: describeSpawnFailure(err)
11959
+ error: describeSpawnFailure(err$1)
11535
11960
  };
11536
11961
  }
11537
11962
  }
@@ -11782,10 +12207,10 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
11782
12207
  graceMs: Number.isFinite(graceOverrideMs) && graceOverrideMs > 0 ? graceOverrideMs : cfg.graceMs,
11783
12208
  ...exec.signal !== void 0 ? { signal: exec.signal } : {}
11784
12209
  });
11785
- } catch (err) {
12210
+ } catch (err$1) {
11786
12211
  return {
11787
12212
  ok: false,
11788
- error: describeSpawnFailure(err),
12213
+ error: describeSpawnFailure(err$1),
11789
12214
  stdout: "",
11790
12215
  stderr: ""
11791
12216
  };
@@ -11793,10 +12218,10 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
11793
12218
  let outcome;
11794
12219
  try {
11795
12220
  outcome = await handle.done;
11796
- } catch (err) {
12221
+ } catch (err$1) {
11797
12222
  return {
11798
12223
  ok: false,
11799
- error: describeSpawnFailure(err),
12224
+ error: describeSpawnFailure(err$1),
11800
12225
  stdout: "",
11801
12226
  stderr: ""
11802
12227
  };
@@ -12619,10 +13044,10 @@ async function tryTabbitExecute(ctx, cfg, toolName, args, taskName) {
12619
13044
  let base64 = "";
12620
13045
  try {
12621
13046
  base64 = readFileSync(d.path).toString("base64");
12622
- } catch (err) {
13047
+ } catch (err$1) {
12623
13048
  return {
12624
13049
  ok: false,
12625
- text: `bcdp_screenshot: cannot read ${d.path}: ${String(err?.message ?? err)}`
13050
+ text: `bcdp_screenshot: cannot read ${d.path}: ${String(err$1?.message ?? err$1)}`
12626
13051
  };
12627
13052
  }
12628
13053
  return {
@@ -12787,7 +13212,7 @@ function friendlyTabbitScriptError(message) {
12787
13212
  }
12788
13213
  /** 受管本地浏览器是否已经起着(纯读,不 spawn)。 */
12789
13214
  async function managedBrowserIsUp() {
12790
- const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-y5sx1g6M.js");
13215
+ const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-BTnLXC1S.js");
12791
13216
  return localBrowserInfo$1() !== null;
12792
13217
  }
12793
13218
  /**
@@ -12831,7 +13256,7 @@ async function ensureManagedBrowser(ctx, cfg, options = {}) {
12831
13256
  ok: false,
12832
13257
  message: notStartedMessage(cfg.localLaunchPolicy, localBrowserPower)
12833
13258
  };
12834
- const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-y5sx1g6M.js");
13259
+ const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-BTnLXC1S.js");
12835
13260
  if (localBrowserInfo$1() !== null) return { ok: true };
12836
13261
  const attach = await refreshAttach({
12837
13262
  targets: cfg.links,
@@ -12960,8 +13385,8 @@ function installScopeProbe(ctx) {
12960
13385
  });
12961
13386
  ctx.effect?.(() => typeof off === "function" ? off : () => void 0);
12962
13387
  }
12963
- } catch (err) {
12964
- scopeProbe.error = err instanceof Error ? err.message.slice(0, 120) : String(err).slice(0, 120);
13388
+ } catch (err$1) {
13389
+ scopeProbe.error = err$1 instanceof Error ? err$1.message.slice(0, 120) : String(err$1).slice(0, 120);
12965
13390
  }
12966
13391
  }
12967
13392
  /** One-line render for the doctor report. */
@@ -13364,7 +13789,7 @@ function apply(ctx, config = {}) {
13364
13789
  stop: async () => {
13365
13790
  localBrowserPower = "off";
13366
13791
  try {
13367
- const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-y5sx1g6M.js");
13792
+ const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-BTnLXC1S.js");
13368
13793
  if (localBrowserInfo$1() === null) return { ok: true };
13369
13794
  const out = await stopLocalBrowser$1();
13370
13795
  if (out.ok) {
@@ -13876,8 +14301,8 @@ function apply(ctx, config = {}) {
13876
14301
  }
13877
14302
  }
13878
14303
  broadcastCliFrames(images, rowsWithPrimaryActive(rows, typeof plan[0] === "number" ? String(plan[0]) : images[0]?.targetId ?? ""), Date.now());
13879
- } catch (err) {
13880
- ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame poller error: ${String(err?.message ?? err)}`);
14304
+ } catch (err$1) {
14305
+ ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame poller error: ${String(err$1?.message ?? err$1)}`);
13881
14306
  }
13882
14307
  };
13883
14308
  /** Last ws handed to the worker; a differ means the browser was relaunched. */
@@ -14156,8 +14581,8 @@ function apply(ctx, config = {}) {
14156
14581
  url: receipt.data?.url ?? ""
14157
14582
  };
14158
14583
  }, syncOnRefresh, captureOnDemand);
14159
- } catch (err) {
14160
- ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err?.message ?? err}`);
14584
+ } catch (err$1) {
14585
+ ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err$1?.message ?? err$1}`);
14161
14586
  }
14162
14587
  try {
14163
14588
  registerEgoBrowserGateway(wctx, bridge, ffmpegManager, {
@@ -14178,13 +14603,13 @@ function apply(ctx, config = {}) {
14178
14603
  },
14179
14604
  fallbackTabReport: makeFallbackTabReport(ctx, cfg)
14180
14605
  });
14181
- } catch (err) {
14182
- ctx.logger?.warn?.(`dsh-browser-cdp: capability gateway init failed: ${err?.message ?? err}`);
14606
+ } catch (err$1) {
14607
+ ctx.logger?.warn?.(`dsh-browser-cdp: capability gateway init failed: ${err$1?.message ?? err$1}`);
14183
14608
  }
14184
14609
  try {
14185
14610
  registerSettingsBridge(wctx, ctx);
14186
- } catch (err) {
14187
- ctx.logger?.warn?.(`dsh-browser-cdp: settings bridge init failed: ${err?.message ?? err}`);
14611
+ } catch (err$1) {
14612
+ ctx.logger?.warn?.(`dsh-browser-cdp: settings bridge init failed: ${err$1?.message ?? err$1}`);
14188
14613
  }
14189
14614
  });
14190
14615
  ctx.effect?.(() => {
@@ -14203,7 +14628,7 @@ function apply(ctx, config = {}) {
14203
14628
  return;
14204
14629
  }
14205
14630
  try {
14206
- const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-y5sx1g6M.js");
14631
+ const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-BTnLXC1S.js");
14207
14632
  if (localBrowserInfo$1()) {
14208
14633
  await stopLocalBrowser$1();
14209
14634
  ctx.logger?.info?.("dsh-browser-cdp: idle reaper stopped the locally launched browser");
@@ -14265,6 +14690,13 @@ function apply(ctx, config = {}) {
14265
14690
  }).done.catch(() => {});
14266
14691
  } catch {}
14267
14692
  });
14693
+ try {
14694
+ const browserFetch = createBrowserFetchService();
14695
+ const provide = ctx.provide;
14696
+ if (typeof provide === "function") provide(BROWSER_FETCH_SERVICE_NAME, browserFetch);
14697
+ } catch (error) {
14698
+ ctx.logger?.warn?.(`dsh-browser-cdp: browser-fetch service not provided (${String(error?.message ?? error)})`);
14699
+ }
14268
14700
  ctx.logger?.info?.(`dsh-browser-cdp: mounted (egoBin=${cfg.egoBin}, defaultSpace=${cfg.activeSpace})`);
14269
14701
  }
14270
14702
  /** `bcdp_status` probes the SAME channel work uses: a `nodejs` heredoc. */
@@ -14410,14 +14842,14 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
14410
14842
  ...faceFields,
14411
14843
  ...facades ? { facades } : {}
14412
14844
  };
14413
- } catch (err) {
14845
+ } catch (err$1) {
14414
14846
  return {
14415
14847
  ok: true,
14416
14848
  available: false,
14417
14849
  path: "",
14418
14850
  exitCode: null,
14419
14851
  ...faceFields,
14420
- error: describeSpawnFailure(err)
14852
+ error: describeSpawnFailure(err$1)
14421
14853
  };
14422
14854
  }
14423
14855
  });
@@ -14490,10 +14922,10 @@ function registerAuthFlush(ctx, cfg, reg) {
14490
14922
  } : {},
14491
14923
  ...!degraded && jbody.error !== void 0 ? { error: jbody.error } : {}
14492
14924
  };
14493
- } catch (err) {
14925
+ } catch (err$1) {
14494
14926
  return {
14495
14927
  ok: false,
14496
- error: String(err?.message || err)
14928
+ error: String(err$1?.message || err$1)
14497
14929
  };
14498
14930
  }
14499
14931
  }),
@@ -14577,10 +15009,10 @@ function registerLoginImport(ctx, cfg, reg) {
14577
15009
  closeSource: args.closeSource === true,
14578
15010
  dryRun: args.dryRun === true
14579
15011
  }, { subprocess: ctx.subprocess });
14580
- } catch (err) {
15012
+ } catch (err$1) {
14581
15013
  return {
14582
15014
  ok: false,
14583
- error: String(err?.message || err)
15015
+ error: String(err$1?.message || err$1)
14584
15016
  };
14585
15017
  }
14586
15018
  }),
@@ -15630,8 +16062,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
15630
16062
  }
15631
16063
  })() : false;
15632
16064
  browserReport = `browser.json: port=${b.port} pid=${b.pid} alive=${alive} headless=${b.headless}`;
15633
- } catch (err) {
15634
- browserReport = `browser.json: unreadable (${err?.message})`;
16065
+ } catch (err$1) {
16066
+ browserReport = `browser.json: unreadable (${err$1?.message})`;
15635
16067
  }
15636
16068
  lines.push(browserReport);
15637
16069
  const tjson = `${stateDir}/task-spaces.json`;