dsh-browser-cdp 1.12.1 → 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,33 @@
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
+
21
+ ## 1.12.2 (2026-11-15)
22
+
23
+ **修掉「关了但面板不刷新」。**
24
+
25
+ - **现象**:ego-cli 通道上点 × 关新浪,浏览器里确实没了(`browser.listTabs()` 5 → 4),但面板标签条还挂着那一行。
26
+ - **根因**:面板标签条只认 `spaces` SSE 事件;在 CLI 通道上这个事件是**搭帧广播的车**发的(`writeCliImages` 里 `includeSpaces`),而帧广播在**没有图**时直接 early-return。关闭是结构性变更,不该等下一次成功截图——面板空闲时就是永远等不到。
27
+ - **修法**:`closeCliTab` 的 ego 分支在关闭成功后主动拉一次真实清单并 `broadcastCliSpaces`,用 `void (async …)()` 发射,**不阻塞**给用户的响应(点击不该等第二次 CLI 往返)。新增 `buildEgoListTabsScript`(`src/cast/panel-actions.ts`)与 `PanelActionRunner.listTabs`,走同一套 `taskSpaces.useOrCreate` + `browser.listTabs` + sentinel 协议。
28
+ - 拉清单失败时静默降级——下一次轮询 tick 会自己追上,不因此让关闭报错。
29
+ - 新增 6 条契约测试(`ego-close-contract` 3 条 + 新增 `ego-list-tabs-contract` 3 条):关闭分支必须在返回 `closed` 前广播、清单走 facade、发射不阻塞。
30
+
1
31
  ## 1.12.1 (2026-11-15)
2
32
 
3
33
  **修掉面板 × 在 ego-cli 通道上点了没反应。**
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.1",
5
+ "version": "1.13.0",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
package/lib/client.js CHANGED
@@ -326,7 +326,7 @@ function shouldShowGen1SettingsGear(hasConfigForms, hasOpenSettingsDocument) {
326
326
  *
327
327
  * Keep in sync with package.json — `node scripts/bump.mjs <version>` writes both.
328
328
  */
329
- const CLIENT_BUILD = "1.12.1";
329
+ const CLIENT_BUILD = "1.12.2";
330
330
 
331
331
  //#endregion
332
332
  //#region src/client/index.ts
@@ -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,
@@ -2169,7 +2237,7 @@ function focusIdFrom(value) {
2169
2237
  *
2170
2238
  * Keep in sync with package.json — `node scripts/bump.mjs <version>` writes both.
2171
2239
  */
2172
- const CLIENT_BUILD = "1.12.1";
2240
+ const CLIENT_BUILD = "1.12.2";
2173
2241
 
2174
2242
  //#endregion
2175
2243
  //#region src/cast-server.ts
@@ -3938,6 +4006,16 @@ function buildEgoSwitchTabScript(spaceJson, body) {
3938
4006
  return `const __bcdpTarget = ${js$1(pickTargetId(body))}\ntry {\n if (__bcdpTarget === '') throw new Error('targetId required')\n await taskSpaces.useOrCreate(${spaceJson})\n const __tabs = await browser.listTabs()\n const __hit = __tabs.find((t) => t.targetId === __bcdpTarget)\n if (!__hit) throw new Error('tab not found: ' + __bcdpTarget)\n if (__hit.active !== true) await browser.switchTab({ targetId: __bcdpTarget })\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, targetId: __bcdpTarget, url: __hit.url || '', title: __hit.title || '' }))\n} catch (__bcdpErr) {\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: false, error: String((__bcdpErr && __bcdpErr.message) || __bcdpErr) }))\n}\n`;
3939
4007
  }
3940
4008
  /**
4009
+ * tab-inventory heredoc — the panel's tab strip, read from the browser.
4010
+ *
4011
+ * Used after a structural change (a close) so the strip updates NOW instead of
4012
+ * waiting for the next successful frame capture. Prints the raw rows as JSON
4013
+ * behind the sentinel; the host maps them onto its CliSpaceRow contract.
4014
+ */
4015
+ function buildEgoListTabsScript(spaceJson) {
4016
+ return `try {\n await taskSpaces.useOrCreate(${spaceJson})\n const __tabs = await browser.listTabs()\n const __rows = __tabs.map((t) => ({ targetId: String(t.targetId || ''), url: String(t.url || ''), title: String(t.title || ''), active: t.active === true }))\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, tabs: __rows }))\n} catch (__bcdpErr) {\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: false, error: String((__bcdpErr && __bcdpErr.message) || __bcdpErr) }))\n}\n`;
4017
+ }
4018
+ /**
3941
4019
  * close-tab heredoc — the user clicked × in the panel.
3942
4020
  *
3943
4021
  * An `ego-cli` link injects no CDP websocket, so `/api/bcdp/close` used to
@@ -4875,6 +4953,11 @@ const Config$1 = z.object({
4875
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(),
4876
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(),
4877
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(),
4878
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(),
4879
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(),
4880
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(),
@@ -5150,6 +5233,11 @@ function resolveConfig(config = {}) {
5150
5233
  toolJudge: tierOpenByDefault(config.toolJudge),
5151
5234
  sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
5152
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"),
5153
5241
  localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
5154
5242
  lightpandaArgs: trimmed(config.lightpandaArgs),
5155
5243
  remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
@@ -5964,7 +6052,10 @@ function registerEgoBrowserGateway(ctx, bridge, ffmpegManager, picks) {
5964
6052
  } else if (method === "cdp-status") writeJson(res, 200, envelopeOk({ attach: defaultAttachCache.get() }));
5965
6053
  else if (method === "cdp-refresh") {
5966
6054
  const cfg = resolveConfig(bridge.source());
5967
- const attach = await refreshAttach({
6055
+ const attach = cfg.cdpMode === "local" ? await refreshLocalProbe({
6056
+ cache: defaultAttachCache,
6057
+ timeoutMs: cfg.cdpProbeTimeoutMs
6058
+ }) : await refreshAttach({
5968
6059
  targets: cfg.links,
5969
6060
  activeTargetId: cfg.activeTargetId,
5970
6061
  mode: cfg.cdpMode,
@@ -6291,6 +6382,7 @@ const HELP_LINES = [
6291
6382
  " /bcdp config 注入面开关与当前空间(只读)",
6292
6383
  " /bcdp link 已配置链路与激活项",
6293
6384
  " /bcdp doctor 静态体检(attach / cli / 工具面 / 帧轮询)",
6385
+ " /bcdp browser [on|off|start|status] 受管本地浏览器开关(本会话,不落盘)",
6294
6386
  " flags --json 单行 JSON 输出",
6295
6387
  " note 其它页面动作仍走 bcdp_* 工具"
6296
6388
  ];
@@ -6365,6 +6457,41 @@ async function attachCommand(deps, target, yes) {
6365
6457
  if (!outcome.ok) return fail(`bcdp attach: ${outcome.reason ?? "写入失败"}`, "next: 在 Desktop 设置里切换连接项");
6366
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 执行"]);
6367
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
+ }
6368
6495
  /** 纯函数入口:单测直接打这里,不挂 cordis。tabs/shot/nav/attach 走异步 runTool。 */
6369
6496
  async function runBcdpCommand(rawInput, deps) {
6370
6497
  const parsed = parseBcdpArgs(rawInput);
@@ -6400,6 +6527,9 @@ async function runBcdpCommand(rawInput, deps) {
6400
6527
  case "doctor":
6401
6528
  result = doctorCommand(deps);
6402
6529
  break;
6530
+ case "browser":
6531
+ result = await browserCommand(deps, parsed.argv[1], parsed.yes);
6532
+ break;
6403
6533
  case "help":
6404
6534
  case "?":
6405
6535
  result = ok(HELP_LINES);
@@ -10648,6 +10778,84 @@ function describeNodeName(node) {
10648
10778
  }
10649
10779
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
10650
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
+
10651
10859
  //#endregion
10652
10860
  //#region src/index.ts
10653
10861
  const name = "dsh-browser-cdp";
@@ -10852,6 +11060,25 @@ let egoLockDepth = 0;
10852
11060
  function egoLockBusy() {
10853
11061
  return egoLockDepth > 0;
10854
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
+ }
10855
11082
  function withEgoLock(fn) {
10856
11083
  return backendQueue.run({
10857
11084
  key: BACKEND_LANE,
@@ -11025,6 +11252,10 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
11025
11252
  function effectiveChannel(cfg) {
11026
11253
  const effective = resolveEffectiveLink(cfg.links ?? [], cfg.activeTargetId ?? "");
11027
11254
  const live = defaultAttachCache.get();
11255
+ if ((cfg.cdpMode ?? "auto") === "local") return {
11256
+ effective,
11257
+ attach: live
11258
+ };
11028
11259
  return {
11029
11260
  effective,
11030
11261
  attach: effective && attachMatchesLink(live, effective.link) ? live : emptyAttachState()
@@ -11530,7 +11761,21 @@ function makePanelActions(ctx, cfg) {
11530
11761
  windowSize: (body) => run((spaceJson) => buildEgoWindowSizeScript(spaceJson, body)),
11531
11762
  navigate: (body) => run((spaceJson) => buildEgoNavigateScript(spaceJson, body)),
11532
11763
  switchTab: (body) => run((spaceJson) => buildEgoSwitchTabScript(spaceJson, body)),
11533
- closeTab: (body) => run((spaceJson) => buildEgoCloseTabScript(spaceJson, body))
11764
+ closeTab: (body) => run((spaceJson) => buildEgoCloseTabScript(spaceJson, body)),
11765
+ listTabs: async () => {
11766
+ if (resolveCliPanelSpace(cfg) === null) return [];
11767
+ const parsed = await run((spaceJson) => buildEgoListTabsScript(spaceJson));
11768
+ const raw = parsed.tabs;
11769
+ if (parsed.ok !== true || !Array.isArray(raw)) return [];
11770
+ const now = Date.now();
11771
+ return raw.filter((t) => typeof t.targetId === "string" && t.targetId !== "").map((t) => ({
11772
+ targetId: String(t.targetId),
11773
+ url: String(t.url ?? ""),
11774
+ title: String(t.title ?? ""),
11775
+ active: t.active === true,
11776
+ lastActive: now
11777
+ }));
11778
+ }
11534
11779
  };
11535
11780
  }
11536
11781
  /**
@@ -12398,6 +12643,79 @@ function friendlyTabbitScriptError(message) {
12398
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.)";
12399
12644
  return message;
12400
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
+ }
12401
12719
  function defineEgoTool(ctx, cfg, opts) {
12402
12720
  return defineTool({
12403
12721
  name: opts.name,
@@ -12419,6 +12737,13 @@ function defineEgoTool(ctx, cfg, opts) {
12419
12737
  text: blocked
12420
12738
  };
12421
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);
12422
12747
  {
12423
12748
  const ownerRuntime = runtimeOfLink(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link);
12424
12749
  if (ownerRuntime?.exec) {
@@ -12644,6 +12969,9 @@ function apply(ctx, config = {}) {
12644
12969
  get localHeadless() {
12645
12970
  return resolveConfig(bridge.source()).localHeadless;
12646
12971
  },
12972
+ get localLaunchPolicy() {
12973
+ return resolveConfig(bridge.source()).localLaunchPolicy;
12974
+ },
12647
12975
  get remoteEnabled() {
12648
12976
  return resolveConfig(bridge.source()).remoteEnabled;
12649
12977
  },
@@ -12866,6 +13194,50 @@ function apply(ctx, config = {}) {
12866
13194
  }),
12867
13195
  poll: getCliPollStatus,
12868
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
+ },
12869
13241
  runTool: async (name$1, args) => {
12870
13242
  const handle = toolHandles.get(name$1);
12871
13243
  if (!handle) throw new Error(`tool ${name$1} 未注册(可能被分级注入封印)`);
@@ -13391,7 +13763,7 @@ function apply(ctx, config = {}) {
13391
13763
  userDataDir: resolved.localUserDataDir
13392
13764
  },
13393
13765
  remoteEnabled: resolved.remoteEnabled,
13394
- useLauncher: true,
13766
+ useLauncher: shouldLaunchOnMount(resolved.localLaunchPolicy, localBrowserPower),
13395
13767
  cliProbeColdStart: resolved.allowProbeColdStart === true,
13396
13768
  tabbitProbe: (link) => {
13397
13769
  const cli = resolveTabbitCli(link.cliPath);
@@ -13436,6 +13808,7 @@ function apply(ctx, config = {}) {
13436
13808
  try {
13437
13809
  offSettingsChange();
13438
13810
  } catch {}
13811
+ localBrowserPower = "auto";
13439
13812
  setTabbitExecutor(null);
13440
13813
  triggerCdpRef = void 0;
13441
13814
  defaultAttachCache.reset();
@@ -13451,10 +13824,18 @@ function apply(ctx, config = {}) {
13451
13824
  if (__ch?.tabbitInventory !== true) {
13452
13825
  if (__ch?.egoRuntime === true) {
13453
13826
  const out = await panelActions.closeTab({ targetId });
13454
- if (out.ok === true) return {
13455
- ok: true,
13456
- reason: "closed"
13457
- };
13827
+ if (out.ok === true) {
13828
+ (async () => {
13829
+ try {
13830
+ const tabs = await panelActions.listTabs();
13831
+ if (tabs.length > 0) broadcastCliSpaces(tabs);
13832
+ } catch {}
13833
+ })();
13834
+ return {
13835
+ ok: true,
13836
+ reason: "closed"
13837
+ };
13838
+ }
13458
13839
  return {
13459
13840
  ok: false,
13460
13841
  reason: typeof out.reason === "string" && out.reason !== "" ? out.reason : "close-failed"
@@ -13677,8 +14058,8 @@ function apply(ctx, config = {}) {
13677
14058
  return;
13678
14059
  }
13679
14060
  try {
13680
- const { localBrowserInfo, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
13681
- if (localBrowserInfo()) {
14061
+ const { localBrowserInfo: localBrowserInfo$1, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
14062
+ if (localBrowserInfo$1()) {
13682
14063
  await stopLocalBrowser$1();
13683
14064
  ctx.logger?.info?.("dsh-browser-cdp: idle reaper stopped the locally launched browser");
13684
14065
  }
@@ -13804,12 +14185,13 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
13804
14185
  if (!wantsRefresh && cachedTerminal) {
13805
14186
  const face = tiers.surface();
13806
14187
  const kind = backendKindOf(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link?.kind);
14188
+ const notStarted = cfg.cdpMode === "local" && cachedAttach.status === "local";
13807
14189
  return {
13808
14190
  ok: true,
13809
14191
  available: cachedAttach.status === "ready",
13810
14192
  path: cachedAttach.cliPath ?? cfg.egoBin,
13811
14193
  cached: true,
13812
- 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}`,
13813
14195
  backendKind: kind,
13814
14196
  toolFace: {
13815
14197
  live: face.live.length,
@@ -13818,7 +14200,11 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
13818
14200
  ...kind === "tabbit-cli" ? { guidance: TABBIT_SEALED_GUIDANCE } : {}
13819
14201
  };
13820
14202
  }
13821
- 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?.();
13822
14208
  return withEgoLock(async () => {
13823
14209
  const face = tiers.surface();
13824
14210
  const kind = backendKindOf(resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link?.kind);
@@ -15845,4 +16231,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
15845
16231
  }
15846
16232
 
15847
16233
  //#endregion
15848
- 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.1",
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",