dsh-browser-cdp 1.12.2 → 1.13.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/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ ## 1.13.0 (2026-11-17)
2
+
3
+ **`cdpMode=local` 不再「一开 DSH 就弹窗」,并且受管浏览器终于真的被用上。**
4
+
5
+ 上游 issue [#14](https://github.com/drscrewdriver/dsh-browser-cdp/issues/14)。
6
+
7
+ - **启动时机可配置**:新增 `localLaunchPolicy`(`eager` / `on-demand` / `manual`),**默认 `on-demand`**。默认值变了,行为也就变了 —— 显式写在这里:`on-demand` 下 DSH 启动后受管浏览器进程数为 0,推迟到首个真正碰页面的 `bcdp_*` 调用才起。
8
+ - **要回退到旧行为**(每次启动 DSH 就弹窗):把 `localLaunchPolicy` 设成 `eager`。1.12.2 及更早就是 eager。
9
+ - 它与 `localHeadless` **正交**,不是三态下拉:`on-demand + 有头` = 启动干净、首次页面操作才出窗口;`on-demand + 无头` = 全程无窗口。
10
+ - `allowProbeColdStart` 只闸 ego-cli 探针,管不到 local 分支 —— 两个后端此前给了相反的默认值,这次补齐。
11
+ - **修掉一个比 #14 更靠前的缺陷:受管 launcher 的端点从来没被注入过**。
12
+ - ① `effectiveChannel` 用 `attachMatchesLink` 按链路过滤缓存,而 local 缓存行的 `targetId` 恒为 `''`(local 模式没有激活目标)—— 两个判据同时把它挡掉,launcher 写进去的 ready/wsUrl 取不出来。
13
+ - ② `decideAttach` 的 local 分支无条件返回 `{kind:'local'}`,而 `resolveEgoEnv` 只在 `kind==='inject'` 时写 `EGO_LINUX_CDP_URL`。
14
+ - 合起来的后果:运行时自己再冷启一个 Chrome(`ego-lite-linux` profile),受管实例只服务观察窗 —— local 模式实际是**两个浏览器**。
15
+ - 修法:`effectiveChannel` 在 local 模式跳过链路作用域;`decideAttach` 在 ready+ws 时返回 `{kind:'inject', source:'local'}`(`inject.source` 由 `'remote'` 扩为 `'remote' | 'local'`)。
16
+ - **运行期开关**:`/bcdp browser on|off|start|status`。`off` 立刻停掉且本会话不再自动起;`on` 解除;`start` 在 `manual` 策略下是唯一入口;`status` **只读**(查询状态绝不起浏览器)。**不落盘** —— 它只覆盖本会话,重启回到配置值(落盘会与 `localLaunchPolicy` 形成两个真相源)。
17
+ - **状态查询零副作用**:`bcdp_status`(含 `refresh:true`)在 local 未启动时改走只读的 `refreshLocalProbe()`,并在既有 `raw` 字段里合成 `not-started: …`(**不新增 output 属性** —— 它是唯一常驻工具,每字符按轮付费);`bcdp_tab op=list` / `bcdp_space op=list|close` 在未启动时直接返回空结果 + 指引,**不进 heredoc**(那条通道的初始化副作用就是冷启动浏览器)。
18
+ - **面板 ⟳ 不再是一条隐藏的启动路径**:`/api/cdp-refresh` 在 local 模式改走 `refreshLocalProbe()`,既不启动,也不再用一个裸 `status:'local'` 把已经起来的浏览器从徽标里抹掉。
19
+ - 新增 41 条测试:`local-launch`(25,谓词与策略矩阵)、`local-inject`(10,断链两端 + 只读探活)、`tui-command`(6,browser 子命令)、`config`(4,默认值与脏值兜底)。顺带修了 `mount-coldstart` 一条既有假绿:它用 `includes('nodejs')` 判 heredoc,而解释器路径 `C:\nodejs\node.exe` 也含 "nodejs",在 node 装在 `nodejs` 目录的机器上恒假。
20
+
1
21
  ## 1.12.2 (2026-11-15)
2
22
 
3
23
  **修掉「关了但面板不刷新」。**
package/dsh-plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://dsh.community/schemas/dsh-plugin-0.15.json",
3
3
  "id": "dsh-browser-cdp",
4
4
  "name": "dsh-browser-cdp",
5
- "version": "1.12.2",
5
+ "version": "1.13.0",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
package/lib/client.js CHANGED
@@ -1692,6 +1692,17 @@ var FAM_FIELD_GROUPS = [
1692
1692
  en: ["Launch local browser headless", "Applies to the locally launched browser"],
1693
1693
  zh: ["本地浏览器无头启动", "仅作用于本地拉起的浏览器"]
1694
1694
  },
1695
+ {
1696
+ k: "localLaunchPolicy",
1697
+ kind: "sel",
1698
+ options: [
1699
+ "on-demand",
1700
+ "eager",
1701
+ "manual"
1702
+ ],
1703
+ en: ["Local browser start policy", "on-demand (default) = start only on the first call that really touches a page, so DSH boots with no browser window; eager = start at plugin mount (pops a window on every DSH start); manual = only via /bcdp browser start. Orthogonal to headless: on-demand + headed = clean boot, window on first page action"],
1704
+ zh: ["本地浏览器启动时机", "on-demand(默认)= 只在首个真正碰页面的调用才启动,DSH 启动不再弹浏览器窗口;eager = 插件挂载即启动(每次开 DSH 都弹窗,1.12.2 及更早的行为);manual = 只有 /bcdp browser start 能起。与无头开关正交:on-demand + 有头 = 启动干净、首次页面操作才出窗口"]
1705
+ },
1695
1706
  {
1696
1707
  k: "localUserDataDir",
1697
1708
  kind: "str",
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { f as stopLocalBrowser, l as launchLocalBrowser } from "./launcher-Vz8i9ylT.js";
1
+ import { d as localBrowserInfo, f as stopLocalBrowser, l as launchLocalBrowser } from "./launcher-Vz8i9ylT.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";
@@ -1787,10 +1787,18 @@ function emptyAttachState() {
1787
1787
  * explicit `allowLocalFallback` AND a working launcher.
1788
1788
  */
1789
1789
  function decideAttach(input) {
1790
- if (input.mode === "local") return {
1791
- kind: "local",
1792
- message: "local mode: using local browser control"
1793
- };
1790
+ if (input.mode === "local") {
1791
+ if (input.status === "ready" && input.wsUrl !== "") return {
1792
+ kind: "inject",
1793
+ wsUrl: input.wsUrl,
1794
+ targetId: "",
1795
+ source: "local"
1796
+ };
1797
+ return {
1798
+ kind: "local",
1799
+ message: "local mode: using local browser control"
1800
+ };
1801
+ }
1794
1802
  if (input.mode === "remote" && input.ownsBrowser === true) return {
1795
1803
  kind: "error",
1796
1804
  code: "mode-kind-mismatch",
@@ -1864,6 +1872,66 @@ function createAttachCache() {
1864
1872
  /** Process-wide attach cache the host half reads synchronously at spawn time. */
1865
1873
  const defaultAttachCache = createAttachCache();
1866
1874
  /**
1875
+ * Re-read the MANAGED launcher's state and publish it, **without ever starting
1876
+ * anything**.
1877
+ *
1878
+ * This is the read-only twin of `refreshAttach`'s `mode:'local'` branch, and it
1879
+ * exists for two callers that must not become a second launch path:
1880
+ * - the panel's ⟳ (`/api/cdp-refresh`) — a refresh button that starts a
1881
+ * browser would silently defeat `localLaunchPolicy` (the same trap
1882
+ * `allowProbeColdStart` already fell into once);
1883
+ * - the on-demand preflight — it asks "is it already up?", and only the
1884
+ * caller that decided to launch is allowed to launch.
1885
+ *
1886
+ * Three outcomes, all honest:
1887
+ * - `local` — nothing recorded / the pid is gone (never started, or died);
1888
+ * - `ready` — the recorded instance answers and has a wsUrl;
1889
+ * - `unreachable`— a live pid whose endpoint does not answer (wedged).
1890
+ */
1891
+ async function refreshLocalProbe(input = {}) {
1892
+ const cache = input.cache ?? defaultAttachCache;
1893
+ const now = input.now ?? (() => Date.now());
1894
+ const suggested = {
1895
+ ...emptyAttachState(),
1896
+ mode: "local",
1897
+ status: "local",
1898
+ targetId: "",
1899
+ linkKind: void 0,
1900
+ cliPath: void 0,
1901
+ cliShape: void 0,
1902
+ sdkPath: "",
1903
+ endpointSource: void 0,
1904
+ engine: void 0,
1905
+ resolvedAt: now()
1906
+ };
1907
+ const info = localBrowserInfo(void 0, input.launcherIo);
1908
+ if (info === null) return cache.patch(suggested);
1909
+ const probe$4 = await probeEndpoint(info.endpoint, {
1910
+ timeoutMs: input.timeoutMs,
1911
+ now
1912
+ });
1913
+ if (probe$4.ok && probe$4.wsUrl) return cache.patch({
1914
+ ...suggested,
1915
+ status: "ready",
1916
+ endpoint: info.endpoint,
1917
+ wsUrl: probe$4.wsUrl,
1918
+ engine: probe$4.engine,
1919
+ code: "",
1920
+ message: "local mode: managed browser already up",
1921
+ latencyMs: probe$4.latencyMs,
1922
+ endpointSource: "local"
1923
+ });
1924
+ return cache.patch({
1925
+ ...suggested,
1926
+ status: "unreachable",
1927
+ endpoint: info.endpoint,
1928
+ engine: void 0,
1929
+ code: "local-launch-not-ready",
1930
+ message: `managed local browser pid ${info.pid} is alive but its endpoint did not answer: ${probe$4.message}`,
1931
+ latencyMs: probe$4.latencyMs
1932
+ });
1933
+ }
1934
+ /**
1867
1935
  * Re-probe the activated target and publish the outcome into the cache.
1868
1936
  *
1869
1937
  * `local` mode short-circuits: there is nothing to probe and nothing to write,
@@ -4885,6 +4953,11 @@ const Config$1 = z.object({
4885
4953
  toolJudge: z.boolean().default(true).description("Judgement tier (5 bcdp_jev_* tools). On still requires a JEV or Laya key: without one they can only answer \"not configured\", so they stay sealed anyway.").volatile(),
4886
4954
  sessionScopedPulse: z.boolean().default(true).description("Per-session unlock: when on, calling bcdp_status in session A only unlocks tools for session A — other sessions stay at their own depth. When off, any session's unlock is process-wide (historical behaviour). Falls back to off when the host does not expose agent-scoped tool restriction.").volatile(),
4887
4955
  localHeadless: z.boolean().description("Run the locally launched browser headless."),
4956
+ localLaunchPolicy: z.union([
4957
+ "eager",
4958
+ "on-demand",
4959
+ "manual"
4960
+ ]).default("on-demand").description("When the managed local browser (cdpMode=local) is allowed to start. on-demand (default) = only on the first call that really touches a page, so DSH starts with no browser window; eager = at plugin mount, which is the pre-1.13 behaviour and pops a window on every start; manual = only via `/bcdp browser start`. Orthogonal to localHeadless: on-demand + headed is a meaningful combination (clean start, window appears on first page action).").volatile(),
4888
4961
  remoteEnabled: z.boolean().description("Master switch for REMOTE attach. Off = the configured target sequence is preserved but inert (nothing probes or connects remotely); flip back on any time. Does not affect cdpMode=local.").volatile(),
4889
4962
  allowProbeColdStart: z.boolean().description("Allow the ego-cli readiness probe to cold-start the backing browser. Off (default): the probe never launches the browser — when --status cannot prove the browser is already up, the heredoc round-trip is skipped and the browser starts on the first real bcdp_* call instead (no browser window at plugin startup). On: the probe verifies the SDK harness up front, which may launch the browser.").volatile(),
4890
4963
  cliFramePollEnabled: z.boolean().default(true).description("Degraded watch-panel frame source for the local ego-cli link: with no CDP screencast available, capture one viewport screenshot every 3s through the CLI channel and serve it to the panel. On (default): the poller runs while an ego-cli link owns routing. Off: the panel keeps its placeholder and no screenshot subprocess is spawned. Hot-applies without reloading the plugin.").volatile(),
@@ -5160,6 +5233,11 @@ function resolveConfig(config = {}) {
5160
5233
  toolJudge: tierOpenByDefault(config.toolJudge),
5161
5234
  sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
5162
5235
  localHeadless: config.localHeadless === void 0 ? false : Boolean(config.localHeadless),
5236
+ localLaunchPolicy: oneOf(config.localLaunchPolicy, [
5237
+ "eager",
5238
+ "on-demand",
5239
+ "manual"
5240
+ ], "on-demand"),
5163
5241
  localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
5164
5242
  lightpandaArgs: trimmed(config.lightpandaArgs),
5165
5243
  remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
@@ -5974,7 +6052,10 @@ function registerEgoBrowserGateway(ctx, bridge, ffmpegManager, picks) {
5974
6052
  } else if (method === "cdp-status") writeJson(res, 200, envelopeOk({ attach: defaultAttachCache.get() }));
5975
6053
  else if (method === "cdp-refresh") {
5976
6054
  const cfg = resolveConfig(bridge.source());
5977
- const attach = await refreshAttach({
6055
+ const attach = cfg.cdpMode === "local" ? await refreshLocalProbe({
6056
+ cache: defaultAttachCache,
6057
+ timeoutMs: cfg.cdpProbeTimeoutMs
6058
+ }) : await refreshAttach({
5978
6059
  targets: cfg.links,
5979
6060
  activeTargetId: cfg.activeTargetId,
5980
6061
  mode: cfg.cdpMode,
@@ -6301,6 +6382,7 @@ const HELP_LINES = [
6301
6382
  " /bcdp config 注入面开关与当前空间(只读)",
6302
6383
  " /bcdp link 已配置链路与激活项",
6303
6384
  " /bcdp doctor 静态体检(attach / cli / 工具面 / 帧轮询)",
6385
+ " /bcdp browser [on|off|start|status] 受管本地浏览器开关(本会话,不落盘)",
6304
6386
  " flags --json 单行 JSON 输出",
6305
6387
  " note 其它页面动作仍走 bcdp_* 工具"
6306
6388
  ];
@@ -6375,6 +6457,41 @@ async function attachCommand(deps, target, yes) {
6375
6457
  if (!outcome.ok) return fail(`bcdp attach: ${outcome.reason ?? "写入失败"}`, "next: 在 Desktop 设置里切换连接项");
6376
6458
  return yes ? ok([`bcdp attach — 已切换到 ${hit.id}`, " next /bcdp status 看通道是否就绪"]) : ok([`bcdp attach — dry run:将切换到 ${hit.id}(当前 ${links.find((row) => row.active)?.id ?? "—"})`, " 确认后加 --yes 执行"]);
6377
6459
  }
6460
+ /**
6461
+ * browser — 受管本地浏览器的运行期开关(issue #14)。
6462
+ *
6463
+ * 子命令语义:
6464
+ * - `status`(默认,只读):浏览器是否在跑 + 配置策略 + 本会话开关;
6465
+ * - `off`:立刻停掉,且本会话不再自动起(不落盘);
6466
+ * - `on`:解除本会话限制(回到 `auto`,仍听配置策略);
6467
+ * - `start`:现在就起(manual 策略下的唯一入口)。
6468
+ *
6469
+ * `--yes` 对 off/start 不是必需(都不是破坏性写盘操作),但保留以和其它子命令
6470
+ * 的手感一致;真正写盘的是 `attach --yes`。
6471
+ */
6472
+ async function browserCommand(deps, raw, _yes) {
6473
+ const sub = (raw ?? "status").toLowerCase();
6474
+ const st = deps.localBrowser.status();
6475
+ if (sub === "status") return ok([
6476
+ `bcdp browser — ${st.running ? "running" : "stopped"}`,
6477
+ ` policy ${st.policy} (设置面板 localLaunchPolicy,持久)`,
6478
+ ` power ${st.power} (本会话开关,不落盘)`,
6479
+ ` endpoint ${st.endpoint ?? "—"}`
6480
+ ]);
6481
+ if (sub === "off") {
6482
+ const out = await deps.localBrowser.stop();
6483
+ return out.ok ? ok(["bcdp browser — 已停止,本会话不再自动启动", " next /bcdp browser on 恢复"]) : fail(`bcdp browser off: ${out.reason ?? "停止失败"}`, "next 手动结束 chrome.exe 后重试");
6484
+ }
6485
+ if (sub === "on") {
6486
+ const out = await deps.localBrowser.start();
6487
+ return out.ok ? ok([`bcdp browser — 本会话已允许启动(policy=${st.policy})`]) : fail(`bcdp browser on: ${out.reason ?? "失败"}`, "next /bcdp browser status 查看当前策略");
6488
+ }
6489
+ if (sub === "start") {
6490
+ const out = await deps.localBrowser.start();
6491
+ return out.ok ? ok(["bcdp browser — 已启动受管本地浏览器", " next /bcdp tabs 看标签页"]) : fail(`bcdp browser start: ${out.reason ?? "启动失败"}`, "next /bcdp doctor 看 Chrome 路径与端口");
6492
+ }
6493
+ return fail(`bcdp browser: 未知子命令 "${sub}"`, "next /bcdp browser [on|off|start|status]");
6494
+ }
6378
6495
  /** 纯函数入口:单测直接打这里,不挂 cordis。tabs/shot/nav/attach 走异步 runTool。 */
6379
6496
  async function runBcdpCommand(rawInput, deps) {
6380
6497
  const parsed = parseBcdpArgs(rawInput);
@@ -6410,6 +6527,9 @@ async function runBcdpCommand(rawInput, deps) {
6410
6527
  case "doctor":
6411
6528
  result = doctorCommand(deps);
6412
6529
  break;
6530
+ case "browser":
6531
+ result = await browserCommand(deps, parsed.argv[1], parsed.yes);
6532
+ break;
6413
6533
  case "help":
6414
6534
  case "?":
6415
6535
  result = ok(HELP_LINES);
@@ -10658,6 +10778,84 @@ function describeNodeName(node) {
10658
10778
  }
10659
10779
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
10660
10780
 
10781
+ //#endregion
10782
+ //#region src/local-launch.ts
10783
+ /**
10784
+ * 不碰页面的工具:调用它们永不触发启动。
10785
+ *
10786
+ * 显式白名单而非黑名单:新增工具默认归「碰页面」,宁可多起一次浏览器,
10787
+ * 也不让一个真正要页面的工具静默失败(失败面朝安全方向)。
10788
+ */
10789
+ const NON_PAGE_TOOLS = new Set([
10790
+ "bcdp_status",
10791
+ "bcdp_help",
10792
+ "bcdp_doctor",
10793
+ "bcdp_jev_status"
10794
+ ]);
10795
+ /**
10796
+ * 只读 op:同名工具在特定 op 下不碰页面。
10797
+ *
10798
+ * `bcdp_tab op=list` 只列举、`bcdp_space op=list` 只读表 —— 它们若走 heredoc
10799
+ * 会顺带冷启动浏览器(issue #14 的「/bcdp tabs 不是只读子命令」)。列进这里
10800
+ * 之后它们改走缓存/worker,不再需要浏览器。
10801
+ */
10802
+ const NON_PAGE_OPS = {
10803
+ bcdp_tab: ["list"],
10804
+ bcdp_space: ["list", "close"]
10805
+ };
10806
+ /** 归一化工具名:`ego_navigate` 与 `bcdp_navigate` 视为同一个(legacy 别名)。 */
10807
+ const canonicalToolName = (name$1) => `bcdp_${String(name$1 ?? "").replace(/^(?:bcdp|ego)_/, "")}`;
10808
+ /**
10809
+ * 执行期谓词:这次调用会不会真的碰页面。
10810
+ *
10811
+ * @param name 工具名(`bcdp_*` 或 legacy `ego_*`)
10812
+ * @param args 本次调用的实参(用于判只读 op)
10813
+ */
10814
+ function toolTouchesPage(name$1, args = {}) {
10815
+ const canonical = canonicalToolName(name$1);
10816
+ if (NON_PAGE_TOOLS.has(canonical)) return false;
10817
+ const readonlyOps = NON_PAGE_OPS[canonical];
10818
+ if (readonlyOps !== void 0) {
10819
+ const raw = args["op"];
10820
+ if (typeof raw !== "string") return canonical !== "bcdp_tab";
10821
+ return !readonlyOps.includes(raw);
10822
+ }
10823
+ return true;
10824
+ }
10825
+ /**
10826
+ * 挂载 / 设置变更时是否允许 launcher 起浏览器。
10827
+ *
10828
+ * `off` 优先于 `on`:运行期关闭是本会话最强的意图,不能被配置轴的 eager 覆盖。
10829
+ */
10830
+ function shouldLaunchOnMount(policy, power) {
10831
+ if (power === "off") return false;
10832
+ if (power === "on") return true;
10833
+ return policy === "eager";
10834
+ }
10835
+ /**
10836
+ * 一次工具调用前是否允许起浏览器。
10837
+ *
10838
+ * 与挂载判定的差别:`on-demand` 在这里放行(调用方已经过 `toolTouchesPage`),
10839
+ * `manual` 在这里仍拒绝 —— manual 的语义是「只有显式命令能起」。
10840
+ */
10841
+ function shouldLaunchOnCall(policy, power, name$1, args = {}) {
10842
+ if (!toolTouchesPage(name$1, args)) return false;
10843
+ if (power === "off") return false;
10844
+ if (power === "on") return true;
10845
+ return policy !== "manual";
10846
+ }
10847
+ /**
10848
+ * 拒绝启动时的可行动文案。
10849
+ *
10850
+ * 三条分支各自给出**下一步命令**,不用「稍后再试」这种无法执行的措辞:
10851
+ * 模型读到它应当能直接决定是调 `/bcdp browser on` 还是改配置。
10852
+ */
10853
+ function notStartedMessage(policy, power) {
10854
+ if (power === "off") return "local browser is switched OFF for this session: run `/bcdp browser on` to re-enable it, or restart DSH (the switch is not persisted).";
10855
+ if (policy === "manual") return "local browser launch is set to manual: run `/bcdp browser start`, or set localLaunchPolicy to eager/on-demand in the plugin settings.";
10856
+ return "local browser is not started yet.";
10857
+ }
10858
+
10661
10859
  //#endregion
10662
10860
  //#region src/index.ts
10663
10861
  const name = "dsh-browser-cdp";
@@ -10862,6 +11060,25 @@ let egoLockDepth = 0;
10862
11060
  function egoLockBusy() {
10863
11061
  return egoLockDepth > 0;
10864
11062
  }
11063
+ /**
11064
+ * 本会话的受管浏览器运行期开关(`/bcdp browser on|off`)。
11065
+ *
11066
+ * **刻意不落盘、不进 `ResolvedConfig`**:落盘会让它和 `localLaunchPolicy`
11067
+ * 形成两个真相源。它的语义就是「本会话临时覆盖」,重启回到配置值 ——
11068
+ * 所以它是模块级可变状态,与 `defaultAttachCache` 同款既有模式。
11069
+ *
11070
+ * `auto` = 听配置轴;`on` = 无视 on-demand 立即允许;`off` = 本会话一律不起
11071
+ * (并且下一次启动请求会被拒绝,文案指向 `/bcdp browser on`)。
11072
+ */
11073
+ let localBrowserPower = "auto";
11074
+ /** 读当前运行期开关(命令面 `/bcdp browser status` 用)。 */
11075
+ function localBrowserPowerState() {
11076
+ return localBrowserPower;
11077
+ }
11078
+ /** 写运行期开关(命令面 `/bcdp browser on|off` 用;`auto` = 恢复听配置)。 */
11079
+ function setLocalBrowserPower(next) {
11080
+ localBrowserPower = next;
11081
+ }
10865
11082
  function withEgoLock(fn) {
10866
11083
  return backendQueue.run({
10867
11084
  key: BACKEND_LANE,
@@ -11035,6 +11252,10 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
11035
11252
  function effectiveChannel(cfg) {
11036
11253
  const effective = resolveEffectiveLink(cfg.links ?? [], cfg.activeTargetId ?? "");
11037
11254
  const live = defaultAttachCache.get();
11255
+ if ((cfg.cdpMode ?? "auto") === "local") return {
11256
+ effective,
11257
+ attach: live
11258
+ };
11038
11259
  return {
11039
11260
  effective,
11040
11261
  attach: effective && attachMatchesLink(live, effective.link) ? live : emptyAttachState()
@@ -12422,6 +12643,79 @@ function friendlyTabbitScriptError(message) {
12422
12643
  if (/is not defined/i.test(message) && /\b(taskSpaces|cdp|fetch)\b/.test(message)) return message + " (bcdp_script on the tabbit backend runs in the browser Playwright runtime: taskSpaces / global cdp() / fetch.browser|server do not exist there. Available: page, context, browser, pages(), usePage, tabbit, expect, assert, artifactPath, page.fetch.)";
12423
12644
  return message;
12424
12645
  }
12646
+ /** 受管本地浏览器是否已经起着(纯读,不 spawn)。 */
12647
+ async function managedBrowserIsUp() {
12648
+ const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-hmPXaWQa.js");
12649
+ return localBrowserInfo$1() !== null;
12650
+ }
12651
+ /**
12652
+ * 只读 op 在「浏览器没起」时的空结果。
12653
+ *
12654
+ * 不 spawn、不进 heredoc:`bcdp_tab op=list` 与 `bcdp_space op=list` 的语义是
12655
+ * 「看看现在有什么」,没起浏览器时正确答案是「什么都没有」+ 怎么起,而不是
12656
+ * 悄悄把一个浏览器拉起来再列它自己的一个空标签页。
12657
+ */
12658
+ function emptyListResultFor(name$1, args, cfg) {
12659
+ const note = notStartedMessage(cfg.localLaunchPolicy, localBrowserPower);
12660
+ const op = typeof args["op"] === "string" ? args["op"] : "";
12661
+ if (name$1.replace(/^(?:bcdp|ego)_/, "") === "tab") return {
12662
+ ok: true,
12663
+ text: `tabs: (none — the managed browser is not running)\n${note}`
12664
+ };
12665
+ if (op === "close") return {
12666
+ ok: false,
12667
+ text: `space close: the managed browser is not running, so there is nothing to close. ${note}`
12668
+ };
12669
+ return {
12670
+ ok: true,
12671
+ text: `spaces: (none — the managed browser is not running)\n${note}`
12672
+ };
12673
+ }
12674
+ /**
12675
+ * 按需拉起受管本地浏览器(issue #14 的 on-demand 路径)。**幂等**。
12676
+ *
12677
+ * 三种结果:
12678
+ * - `ok:true` —— 已经起着(复用),或刚刚起好并被探活;
12679
+ * - `ok:false` —— 本会话被 `/bcdp browser off` 关掉 / manual 策略拒绝启动,
12680
+ * 文案里带可执行命令(`notStartedMessage`);
12681
+ * - `ok:false` —— launcher 起不来(找不到 Chrome、端口不通等),文案来自 launcher。
12682
+ *
12683
+ * 为什么先 `localBrowserInfo()` 再 refreshAttach:前者是纯读(pid 存活即认),
12684
+ * 后者会走完整的 launch→probe 流程。已经起着的时候不该再付一次启动开销。
12685
+ */
12686
+ async function ensureManagedBrowser(ctx, cfg, options = {}) {
12687
+ if (cfg.cdpMode !== "local") return { ok: true };
12688
+ if (!options.force && (localBrowserPower === "off" || cfg.localLaunchPolicy === "manual")) return {
12689
+ ok: false,
12690
+ message: notStartedMessage(cfg.localLaunchPolicy, localBrowserPower)
12691
+ };
12692
+ const { localBrowserInfo: localBrowserInfo$1 } = await import("./launcher-hmPXaWQa.js");
12693
+ if (localBrowserInfo$1() !== null) return { ok: true };
12694
+ const attach = await refreshAttach({
12695
+ targets: cfg.links,
12696
+ activeTargetId: cfg.activeTargetId,
12697
+ mode: "local",
12698
+ timeoutMs: cfg.cdpProbeTimeoutMs,
12699
+ cache: defaultAttachCache,
12700
+ fallback: {
12701
+ enabled: cfg.allowLocalFallback === true,
12702
+ chromePath: cfg.chromePath,
12703
+ chromeArgs: cfg.chromeArgs,
12704
+ localHeadless: cfg.localHeadless,
12705
+ userDataDir: cfg.localUserDataDir
12706
+ },
12707
+ useLauncher: true
12708
+ });
12709
+ if (attach.status === "ready" && attach.wsUrl !== "") {
12710
+ if (setAttachEndpoint(attach.wsUrl, attach.engine ?? "unknown")) recycleWorker("on-demand launch").catch(() => null);
12711
+ ctx.logger?.info?.("dsh-browser-cdp: on-demand launch started the managed browser");
12712
+ return { ok: true };
12713
+ }
12714
+ return {
12715
+ ok: false,
12716
+ message: `could not start the managed local browser: ${attach.code === "" ? attach.message : `${attach.code}: ${attach.message}`}`
12717
+ };
12718
+ }
12425
12719
  function defineEgoTool(ctx, cfg, opts) {
12426
12720
  return defineTool({
12427
12721
  name: opts.name,
@@ -12443,6 +12737,13 @@ function defineEgoTool(ctx, cfg, opts) {
12443
12737
  text: blocked
12444
12738
  };
12445
12739
  }
12740
+ if (shouldLaunchOnCall(cfg.localLaunchPolicy, localBrowserPower, opts.name, args)) {
12741
+ const started = await ensureManagedBrowser(ctx, cfg);
12742
+ if (!started.ok) return {
12743
+ ok: false,
12744
+ text: started.message
12745
+ };
12746
+ } else if (cfg.cdpMode === "local" && !await managedBrowserIsUp()) return emptyListResultFor(opts.name, args, cfg);
12446
12747
  {
12447
12748
  const ownerRuntime = runtimeOfLink(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link);
12448
12749
  if (ownerRuntime?.exec) {
@@ -12668,6 +12969,9 @@ function apply(ctx, config = {}) {
12668
12969
  get localHeadless() {
12669
12970
  return resolveConfig(bridge.source()).localHeadless;
12670
12971
  },
12972
+ get localLaunchPolicy() {
12973
+ return resolveConfig(bridge.source()).localLaunchPolicy;
12974
+ },
12671
12975
  get remoteEnabled() {
12672
12976
  return resolveConfig(bridge.source()).remoteEnabled;
12673
12977
  },
@@ -12890,6 +13194,50 @@ function apply(ctx, config = {}) {
12890
13194
  }),
12891
13195
  poll: getCliPollStatus,
12892
13196
  watch: getWatchCounters,
13197
+ localBrowser: {
13198
+ status: () => {
13199
+ const attach = effectiveChannel(cfg).attach;
13200
+ return {
13201
+ running: cfg.cdpMode === "local" && attach.status === "ready",
13202
+ policy: cfg.localLaunchPolicy,
13203
+ power: localBrowserPower,
13204
+ endpoint: attach.status === "ready" && attach.endpoint !== "" ? attach.endpoint : null
13205
+ };
13206
+ },
13207
+ start: async () => {
13208
+ if (cfg.cdpMode !== "local") return {
13209
+ ok: false,
13210
+ reason: "cdpMode is not local — the managed launcher only serves local mode"
13211
+ };
13212
+ localBrowserPower = "auto";
13213
+ const started = await ensureManagedBrowser(ctx, cfg, { force: true });
13214
+ return started.ok ? { ok: true } : {
13215
+ ok: false,
13216
+ reason: started.message
13217
+ };
13218
+ },
13219
+ stop: async () => {
13220
+ localBrowserPower = "off";
13221
+ try {
13222
+ const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
13223
+ if (localBrowserInfo$1() === null) return { ok: true };
13224
+ const out = await stopLocalBrowser$1();
13225
+ if (out.ok) {
13226
+ await refreshLocalProbe({ cache: defaultAttachCache });
13227
+ recycleWorker("local browser switched off").catch(() => null);
13228
+ }
13229
+ return out.ok ? { ok: true } : {
13230
+ ok: false,
13231
+ reason: out.code
13232
+ };
13233
+ } catch (error) {
13234
+ return {
13235
+ ok: false,
13236
+ reason: error.message
13237
+ };
13238
+ }
13239
+ }
13240
+ },
12893
13241
  runTool: async (name$1, args) => {
12894
13242
  const handle = toolHandles.get(name$1);
12895
13243
  if (!handle) throw new Error(`tool ${name$1} 未注册(可能被分级注入封印)`);
@@ -13415,7 +13763,7 @@ function apply(ctx, config = {}) {
13415
13763
  userDataDir: resolved.localUserDataDir
13416
13764
  },
13417
13765
  remoteEnabled: resolved.remoteEnabled,
13418
- useLauncher: true,
13766
+ useLauncher: shouldLaunchOnMount(resolved.localLaunchPolicy, localBrowserPower),
13419
13767
  cliProbeColdStart: resolved.allowProbeColdStart === true,
13420
13768
  tabbitProbe: (link) => {
13421
13769
  const cli = resolveTabbitCli(link.cliPath);
@@ -13460,6 +13808,7 @@ function apply(ctx, config = {}) {
13460
13808
  try {
13461
13809
  offSettingsChange();
13462
13810
  } catch {}
13811
+ localBrowserPower = "auto";
13463
13812
  setTabbitExecutor(null);
13464
13813
  triggerCdpRef = void 0;
13465
13814
  defaultAttachCache.reset();
@@ -13709,8 +14058,8 @@ function apply(ctx, config = {}) {
13709
14058
  return;
13710
14059
  }
13711
14060
  try {
13712
- const { localBrowserInfo, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
13713
- if (localBrowserInfo()) {
14061
+ const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
14062
+ if (localBrowserInfo$1()) {
13714
14063
  await stopLocalBrowser$1();
13715
14064
  ctx.logger?.info?.("dsh-browser-cdp: idle reaper stopped the locally launched browser");
13716
14065
  }
@@ -13836,12 +14185,13 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
13836
14185
  if (!wantsRefresh && cachedTerminal) {
13837
14186
  const face = tiers.surface();
13838
14187
  const kind = backendKindOf(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link?.kind);
14188
+ const notStarted = cfg.cdpMode === "local" && cachedAttach.status === "local";
13839
14189
  return {
13840
14190
  ok: true,
13841
14191
  available: cachedAttach.status === "ready",
13842
14192
  path: cachedAttach.cliPath ?? cfg.egoBin,
13843
14193
  cached: true,
13844
- raw: cachedAttach.code === "" ? `${cachedAttach.status}${cachedAttach.message === "" ? "" : `: ${cachedAttach.message}`}` : `${cachedAttach.status}: ${cachedAttach.code}: ${cachedAttach.message}`,
14194
+ raw: notStarted ? `not-started: ${notStartedMessage(cfg.localLaunchPolicy, localBrowserPower)}` : cachedAttach.code === "" ? `${cachedAttach.status}${cachedAttach.message === "" ? "" : `: ${cachedAttach.message}`}` : `${cachedAttach.status}: ${cachedAttach.code}: ${cachedAttach.message}`,
13845
14195
  backendKind: kind,
13846
14196
  toolFace: {
13847
14197
  live: face.live.length,
@@ -13850,7 +14200,11 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
13850
14200
  ...kind === "tabbit-cli" ? { guidance: TABBIT_SEALED_GUIDANCE } : {}
13851
14201
  };
13852
14202
  }
13853
- if (wantsRefresh) await cfg.refreshAttach?.();
14203
+ if (wantsRefresh) if (cfg.cdpMode === "local") await refreshLocalProbe({
14204
+ cache: defaultAttachCache,
14205
+ timeoutMs: cfg.cdpProbeTimeoutMs
14206
+ });
14207
+ else await cfg.refreshAttach?.();
13854
14208
  return withEgoLock(async () => {
13855
14209
  const face = tiers.surface();
13856
14210
  const kind = backendKindOf(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link?.kind);
@@ -15877,4 +16231,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
15877
16231
  }
15878
16232
 
15879
16233
  //#endregion
15880
- export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, getCliFrameDiag, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveCliPanelSpace, resolveEgoEnv, rowsWithPrimaryActive, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser, tabbitSpaceRows, waitForHumanScript };
16234
+ export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, getCliFrameDiag, inject, isTabStuckFailure, localBrowserPowerState, name, parseSentinel, parseStatusFacades, resolveCliPanelSpace, resolveEgoEnv, rowsWithPrimaryActive, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, setLocalBrowserPower, shouldReapBrowser, tabbitSpaceRows, waitForHumanScript };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-browser-cdp",
3
- "version": "1.12.2",
3
+ "version": "1.13.0",
4
4
  "description": "dsh-browser-cdp: visible agent browser for DSH — drives the vendored ego-compatible Chromium over CDP, and can also attach to a running Chrome/Edge/Brave or route through egolite, Tabbit and Lightpanda backends. 35 structured bcdp_* tools; only bcdp_status stays resident by default (lazy injection, −91.9% schema per turn for non-browser sessions). Realtime watch panel with direct click/scroll/IME input, element picks quoted into the composer, human-verification notices; non-CDP channels sync frames by 3s polling. Web shell: floating watch ball without dsh-better-sidebar, sidebar tab with it. Headless/TUI hosts: tools-only. [DSH 0.1.0-rc.2 ~ 0.2.2-rc.1: declarative settings via Config .volatile() fields on 0.1.7+; imperative installSection / module-level registration + describe/mutate bridge on 0.1.0 ~ 0.1.5 (experimental, pending farm). Client peers stay optional so gen-1 hosts without dsh-client-store still load; for a production install on the current line use the 0.17.x line]",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",