dsh-browser-cdp 1.6.2 → 1.7.1-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -240,37 +240,39 @@ wait / space / escape 三族已按 `op` 合并,旧工具名**移除**(不保
240
240
 
241
241
  ## 工具注入分级(懒注册 / 分级 / 锁定)
242
242
 
243
- 34 个工具全量注册时,**每个会话每一轮**都要为它们的 schema 付费(挂载级实测 `description` + `parameters` 序列化 = **22,224 字符** ≈ 6.4K token;1.3.2 的 38 工具基线用同一口径实测为 20,951,1.5.0 三族合并后仅高出 **+6.1%**,远低于 ≤+15% 门禁),而不碰浏览器的会话一个也用不上。插件因此把「谁能出现在模型面前」收成一处策略(`src/toolTiers.ts`),分**八批**注入。
243
+ 34 个工具全量注册时,**每个会话每一轮**都要为它们的 schema 付费(挂载级实测 `description` + `parameters` 序列化 = **24,631 字符** ≈ 7.1K token,1.7.0;1.5.0 曾测为 22,224,增量主要来自分级文档与工具描述互斥引导)。而不碰浏览器的会话一个也用不上。插件因此把「谁能出现在模型面前」收成一处策略(`src/toolTiers.ts`),分**八批**注入。
244
244
 
245
- > **8 批 ≠ 8 个开关**。批次是*注入时机*,开关是*用户面*(§9.3「开关与批次解耦」)。当前 4 个开关管 8 批:`toolBrowse` 管 act+observe+wait 三批并按波次放行,`toolExtended` 管 power+session,`toolEscape`、`toolJudge` 各管一批。所以「`toolBrowse` = 14 个」指的是**并集上限**,实际第一波只放 9 个。
245
+ > **8 批 ≠ 8 个开关**。批次是*注入时机*,开关是*用户面*(§9.3「开关与批次解耦」)。当前 4 个开关管 8 批:`toolBrowse` 管 act+observe+wait 三批并按波次放行,`toolExtended` 管 power+session,`toolEscape`、`toolJudge` 各管一批。所以「`toolBrowse` = 19 个」指的是**并集上限**,实际第一波只放 13 个。
246
246
 
247
247
  | 批次 | 成员 | schema | 何时出现 |
248
248
  |---|---|---:|---|
249
- | **core** 常驻(6) | `bcdp_status` `bcdp_doctor` `bcdp_help` `bcdp_space` `bcdp_navigate` `bcdp_snapshot` | 3,589 | 永远在场,不可封印——否则 lazy 模式连解锁入口都没有 |
250
- | **act** 动手(9) | click / fill / key / hover / scroll / select / check / drag / tab | 5,243 | `lazy` 下首次活动放第一波 |
251
- | **observe** 观察(4) | screenshot / page_info / read_element / js | 2,037 | 第二次活动 |
252
- | **wait** 等待(1) | `bcdp_wait`(duration / selector / url / response / load / function / request / event) | 1,925 | 第三次活动 |
253
- | **power** 重量级(5) | raw CDP / http / upload / download / dialog | 3,283 | 首次活动(同 `toolExtended`) |
254
- | **session** 登录态(3) | captcha / auth_flush / login_import | 1,694 | 首次活动(同 `toolExtended`) |
255
- | **escape** 逃生舱(1) | `bcdp_script`(`verbatim:true` = 原 cli 的裸 heredoc) | 1,389 | **冷启动即在**,不吃活动闸(见下) |
256
- | **judge** 评审链(5) | `bcdp_jev_*` | 3,064 | 除解锁外,**还要求配了 JEV 或 Laya Key** |
257
- | **合计** | 34 | **22,224** | — |
249
+ | **core** 常驻(1) | `bcdp_status` | 401 | 永远在场,不可封印——它是 lazy 唯一的解锁入口 |
250
+ | **act** 动手(13) | space / navigate / click / fill / key / hover / scroll / select / check / drag / tab / help / doctor | 8,762 | `lazy` 下首次活动放第一波 |
251
+ | **observe** 观察(5) | screenshot / page_info / read_element / js / snapshot | 3,109 | 第二次活动 |
252
+ | **wait** 等待(1) | `bcdp_wait`(duration / selector / url / response / load / function / request / event) | 1,976 | 第三次活动 |
253
+ | **power** 重量级(5) | raw CDP / http / upload / download / dialog | 3,692 | 首次活动(同 `toolExtended`) |
254
+ | **session** 登录态(3) | captcha / auth_flush / login_import | 1,864 | 首次活动(同 `toolExtended`) |
255
+ | **escape** 逃生舱(1) | `bcdp_script`(`verbatim:true` = 原 cli 的裸 heredoc) | 1,484 | 首次活动(1.7.0 起不再吃活动闸豁免,见下) |
256
+ | **judge** 评审链(5) | `bcdp_jev_*` | 3,343 | 除解锁外,**还要求配了 JEV 或 Laya Key** |
257
+ | **合计** | 34 | **24,631** | — |
258
+
259
+ > 表内 schema 与合计均为 1.7.0 **挂载级实测**(`tests/tier-mount.test.ts` 的度量用例打印),八批求和 = 24,631 与全量档逐字对齐。
258
260
 
259
261
  设置项在插件设置页**最上方**的「工具封印」分块(全部 volatile,翻完当场生效,不重启插件)——一个开关管一组批次,形状照 dsh-prime-memory 的「工具封印」:
260
262
 
261
- - **`toolInjection`** `lazy`(**默认**:常驻 core + escape,其余首次 `bcdp_*` 调用后按开关注入)/ `always`(挂载即全量,历史行为)。
262
- - **`toolBrowse`**(act + observe + wait = 14)/ **`toolExtended`**(power + session = 8)/ **`toolEscape`**(script = 1)/ **`toolJudge`**(5):开 = 开放注册,关 = 该批从模型工具列表移除。四组各自独立,封一组不波及别组;`core` 级不给开关(封了就没了活动入口)。
263
+ - **`toolInjection`** `lazy`(**默认**:只常驻 `bcdp_status`——它是唯一的解锁入口,其余首次 `bcdp_*` 调用后按开关注入)/ `always`(挂载即全量,历史行为)。
264
+ - **`toolBrowse`**(act + observe + wait = 19)/ **`toolExtended`**(power + session = 8)/ **`toolEscape`**(script = 1)/ **`toolJudge`**(5):开 = 开放注册,关 = 该批从模型工具列表移除。四组各自独立,封一组不波及别组;`core` 级不给开关(封了就没了活动入口)。
263
265
 
264
- **escape 批为什么单独成组、且不等活动**:`bcdp_script` 是唯一能在一次调用里干完任意多步任务的入口(`page` / `browser` / `taskSpaces` / `fetch` / `cdp` 全预置),其余 33 个工具能做的事它都能做。所以它必须始终可达——否则模型遇到「结构化工具没覆盖」的情形时手里没有任何逃生手段。这也让它成为**按需只开逃生舱**的合法姿势:关掉 `toolExtended`、留着 `toolEscape`,只留 1 个工具。
266
+ **1.7.0 起 `escape` 不再吃活动闸的例外**:`bcdp_script` 仍是唯一能在一次调用里干完任意多步任务的入口(`page` / `browser` / `taskSpaces` / `fetch` / `cdp` 全预置),但它不再常驻——先调一次常驻的 `bcdp_status` 即可拿到它。豁免的代价是它单独占 ≈1,700 字符/轮(比收窄后的整个常驻面还大四轮),而 lazy 会话里模型本来就要先调 `status`。如果你需要「冷启动直接写脚本」的旧行为,设 `toolInjection = always`(或留在 1.6.x)。
265
267
 
266
268
  行为要点:
267
269
 
268
- - **封印 = 反注册**(工具从模型的工具列表里消失),不是执行期拒绝。解锁信号挂在 `bcdp_*` 调用的公共出口上,工具体不知道分级存在;`bcdp_status` / `bcdp_help` / `bcdp_doctor` 自身也算活动信号(读了指南就得有工具可用)。
270
+ - **封印 = 反注册**(工具从模型的工具列表里消失),不是执行期拒绝。解锁信号挂在 `bcdp_*` 调用的公共出口上,工具体不知道分级存在;`bcdp_status` / `bcdp_help` / `bcdp_doctor` 自身也算活动信号(读了指南就得有工具可用)——但后两者已属 act 批,冷启动下只能靠 `bcdp_status` 触发。
269
271
  - **闲置自动收回**:`lazy` + `idleTimeoutMin > 0` 时,空闲回收把后台浏览器停掉的同一刻收回扩展面;下次活动重新铺开。`always` 模式不受影响。
270
272
  - `legacyEgoToolNames` 的 `ego_*` 别名跟随其 `bcdp_*` 本体的级别。
271
- - 当前注入面写在 `bcdp_doctor` 报告首行(`tool injection: mode=lazy browse=open extended=open escape=open judge=open judgeKey=none active=no → live 7 / sealed 27`),不用猜。
272
- - 默认档下不碰浏览器的会话只有 **7** 个工具在场(core 6 + escape 1 = 4,978 字符 ≈ 1,430 token,−77.6%);要回到历史行为把 `toolInjection` 改成 `always`(34 件全在场需再配一个评审 Key)。
273
- - **各档实测注入面**(挂载级口径,1.5.0;字符为实测,token 按同一比例折算):默认 7 个 / 4,978 字符 ≈1,430 tok → 首次活动 24 个 / 15,198 ≈4,370 tok → 第 2 波(observe)28 个 / 17,235 ≈4,955 tok → 第 3 波(wait)29 个 / 19,160 ≈5,509 tok → 全量 34 个 / 22,224 ≈6,389 tok。
273
+ - 当前注入面写在 `bcdp_doctor` 报告首行(例:`tool injection: mode=lazy browse=open extended=open escape=open judge=open judgeKey=none active=yes → live 28 / sealed 6`,即一次 `bcdp_status` + 一次 `doctor` 之后的面),不用猜。注意 `doctor` 本身已属 act 批,要先调 `bcdp_status` 才能拿到它;冷启动时模型面上只有 `bcdp_status`(live 1 / sealed 33)。
274
+ - 默认档下不碰浏览器的会话只有 **1** 个工具在场(`bcdp_status` = 401 字符 ≈115 tok,较 1.5.0 的 4,978 字符 **−91.9%**);它是解锁入口,调用即按批次铺开其余工具。要回到历史行为把 `toolInjection` 改成 `always`(34 件全在场需再配一个评审 Key)。
275
+ - **各档实测注入面**(挂载级口径,1.7.0;序列化工具的 `name + description + parameters` 求和,token 按 3.48 字符/token 折算):默认 **1 个 / 401 字符 ≈115 tok** → 首次活动(act 批 + power + session + escape)23 个 / 16,203 ≈4,660 tok → 第 2 波(+observe)与第 3 波(+wait)后 29 个 / 21,288 ≈6,120 tok → 全量(always + 评审 Key)34 个 / 24,631 ≈7,080 tok。这些数字由 `tests/tier-mount.test.ts` 的度量用例当场打印,不靠估算。
274
276
  - 五个字段都带 schema `.default()`:volatile 字段的表单描述符直接拿 schema 默认值,不写默认会出现「面板显示 A、运行时用 B」。
275
277
 
276
278
  > 取舍提醒:窄工具(一个动作一个工具)是模型写对参数、少重试的护栏。1.5.0 只合并了 **wait / space / escape** 三族同源冗余(41 → 34,省 1,869 字符 schema):五个 wait 共用同一 preamble 与 timeout 语义、三个 space 本就是同一个 op 工具的碎片、cli/script 是同一 heredoc 运行时。代价是这三族的旧工具名不再存在(见上方迁移表);交互原子(click/fill/key…)**不合并**,因为它们是模型写对参数的护栏。
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.6.2",
5
+ "version": "1.7.1-rc.5",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
@@ -72,15 +72,15 @@
72
72
  "label": "always"
73
73
  }
74
74
  ],
75
- "hint": "lazy(默认)= 常驻核心 7 个 + 逃生舱 2 个,其余首次 bcdp_* 调用后按下方开关注入,闲置回收时收回;always = 挂载即注册全部 38 个(历史行为)。"
75
+ "hint": "lazy(默认)= 只常驻 1 个(bcdp_status,兼作解锁入口),其余首次 bcdp_* 调用后按下方开关注入,闲置回收时收回;always = 挂载即注册全部 34 个(历史行为)。"
76
76
  },
77
77
  {
78
78
  "path": [
79
79
  "toolBrowse"
80
80
  ],
81
- "label": "基础操作工具(16 个)",
81
+ "label": "基础操作工具(19 个)",
82
82
  "kind": "boolean",
83
- "hint": "开(默认)= 浏览器活动后按 act → observe → wait 三波放行;关 = 16 个工具从模型工具列表移除(点击/填写/键鼠/拖拽/截图/读取/等待…)。"
83
+ "hint": "开(默认)= 浏览器活动后按 act → observe → wait 三波放行;关 = 19 个工具从模型工具列表移除(空间/导航/点击/填写/键鼠/拖拽/截图/读取/指南/预检/等待…)。"
84
84
  },
85
85
  {
86
86
  "path": [
@@ -94,9 +94,9 @@
94
94
  "path": [
95
95
  "toolEscape"
96
96
  ],
97
- "label": "逃生舱 cli / script(2 个)",
97
+ "label": "逃生舱 script(1 个)",
98
98
  "kind": "boolean",
99
- "hint": "始终可用——与其它档不同,它不等浏览器活动,因为一个 heredoc 就能做到其余 36 个工具的事。关 = 封印。"
99
+ "hint": "与其它非 core 档一样等浏览器活动(1.7.0 起不再有「始终可达」豁免):先调 bcdp_status 即可拿到它,一个 heredoc 能做到其余大多数工具的事。关 = 封印。"
100
100
  },
101
101
  {
102
102
  "path": [
@@ -106,6 +106,14 @@
106
106
  "kind": "boolean",
107
107
  "hint": "开仍需配了 JEV 或 Laya Key:没 Key 的评审工具只能回答「未配置」,依旧不注入。关 = 任何情况下都不注入。"
108
108
  },
109
+ {
110
+ "path": [
111
+ "sessionScopedPulse"
112
+ ],
113
+ "label": "按会话隔离解锁 (Per-session unlock)",
114
+ "kind": "boolean",
115
+ "hint": "开(默认)= 每个会话各自调 bcdp_status 解锁,不会影响到其他会话;关 = 进程级共享(任一会话解锁对所有会话生效,历史行为)。宿主不支持时自动降级为关。"
116
+ },
109
117
  {
110
118
  "path": [
111
119
  "isolateSpaces"
package/lib/client.js CHANGED
@@ -103,7 +103,7 @@ function buildCliRow(input) {
103
103
  id: newLinkId(),
104
104
  label: trimmed(input.label) || cliPath || EGO_CLI_LABEL,
105
105
  cliPath,
106
- useSdkPath: false,
106
+ useSdkPath: true,
107
107
  enabled: true,
108
108
  note: "",
109
109
  probeStatus: "unknown",
@@ -1360,14 +1360,14 @@ var FAM_FIELD_GROUPS = [
1360
1360
  k: "toolInjection",
1361
1361
  kind: "sel",
1362
1362
  options: ["lazy", "always"],
1363
- en: ["Injection mode", "lazy (default) = the 7 core tools plus the 2 escape-hatch tools stay resident; the rest are injected after the first bcdp_* call and sealed back on idle reaping. always = every tool registered at mount (historical)"],
1364
- zh: ["工具注入模式", "lazy(默认)= 常驻核心 7 个 + 逃生舱 2 个,其余在首次 bcdp_* 调用后铺开、闲置回收时收回;always = 挂载即注册全部(历史行为)"]
1363
+ en: ["Injection mode", "lazy (default) = only bcdp_status stays resident — it is the unlock entry, and the rest are injected after the first bcdp_* call and sealed back on idle reaping. always = every tool registered at mount (historical)"],
1364
+ zh: ["工具注入模式", "lazy(默认)= 只常驻 bcdp_status(它是解锁入口),其余在首次 bcdp_* 调用后铺开、闲置回收时收回;always = 挂载即注册全部(历史行为)"]
1365
1365
  },
1366
1366
  {
1367
1367
  k: "toolBrowse",
1368
1368
  kind: "bool",
1369
- en: ["Basic browsing tools (16)", "On (default) = released in three waves after browser activity (act → observe → wait); off = 16 tools removed from the model tool list (click / fill / key / drag / screenshot / read / wait ...)"],
1370
- zh: ["基础操作工具(16 个)", "开(默认)= 浏览器活动后按 act → observe → wait 三波放行;关 = 16 个工具从模型工具列表移除(点击/填写/键鼠/拖拽/截图/读取/等待…)"]
1369
+ en: ["Basic browsing tools (19)", "On (default) = released in three waves after browser activity (act → observe → wait); off = 19 tools removed from the model tool list (space / navigate / click / fill / key / drag / screenshot / read / help / doctor / wait ...)"],
1370
+ zh: ["基础操作工具(19 个)", "开(默认)= 浏览器活动后按 act → observe → wait 三波放行;关 = 19 个工具从模型工具列表移除(空间/导航/点击/填写/键鼠/拖拽/截图/读取/指南/预检/等待…)"]
1371
1371
  },
1372
1372
  {
1373
1373
  k: "toolExtended",
@@ -1378,14 +1378,20 @@ var FAM_FIELD_GROUPS = [
1378
1378
  {
1379
1379
  k: "toolEscape",
1380
1380
  kind: "bool",
1381
- en: ["Escape hatch (2: cli / script)", "Always available — unlike the other tiers it does not wait for browser activity, because one heredoc can do what any of the other 36 tools do. Off = sealed"],
1382
- zh: ["逃生舱(2 个:cli / script)", "始终可用——与其它档不同,它不等浏览器活动,因为一个 heredoc 就能做到其余 36 个工具的事。关 = 封印"]
1381
+ en: ["Escape hatch (1: script)", "Sealed until browser activity, like every other non-core tier — call bcdp_status first and it appears. Off = sealed"],
1382
+ zh: ["逃生舱(1 个:script)", "与其它非 core 档一样等浏览器活动(1.7.0 起不再有「始终可达」豁免):先调 bcdp_status 即可拿到。关 = 封印"]
1383
1383
  },
1384
1384
  {
1385
1385
  k: "toolJudge",
1386
1386
  kind: "bool",
1387
1387
  en: ["Judgement tools bcdp_jev_* (5)", "On still requires a JEV or Laya key — without one they can only answer \"not configured\", so they stay sealed anyway"],
1388
1388
  zh: ["评审工具 bcdp_jev_*(5 个)", "开仍需配了 JEV/Laya Key;没 Key 它们本来也只能回答「未配置」,依旧不注入"]
1389
+ },
1390
+ {
1391
+ k: "sessionScopedPulse",
1392
+ kind: "bool",
1393
+ en: ["Per-session unlock", "On (default) = each session must call bcdp_status independently; one session's unlock does not affect others. Off = process-wide (any unlock affects all sessions, historical)"],
1394
+ zh: ["按会话隔离解锁", "开(默认)= 每个会话各自调 bcdp_status 解锁,不互相影响;关 = 进程级共享(任一会话解锁对所有会话生效,历史行为)"]
1389
1395
  }
1390
1396
  ]
1391
1397
  },
@@ -2312,21 +2318,7 @@ function FamLinks(props) {
2312
2318
  }
2313
2319
  writeLinks(updateRow(links, row.id, { endpoint: v }));
2314
2320
  }
2315
- }), isCli ? h("label", { style: {
2316
- display: "flex",
2317
- alignItems: "center",
2318
- gap: "4px",
2319
- fontSize: "11px",
2320
- color: "var(--dsw-alias-label-tertiary, rgba(127,127,127,.7))",
2321
- flex: "0 0 auto"
2322
- } }, h(FamSwitch, {
2323
- checked: row.useSdkPath === true,
2324
- writable,
2325
- title: wt("linksCliSdk"),
2326
- onToggle: function(next) {
2327
- writeLinks(updateRow(links, row.id, { useSdkPath: next }));
2328
- }
2329
- }), wt("linksCliSdk")) : null, !isCli && !isLp ? h("button", {
2321
+ }), !isCli && !isLp ? h("button", {
2330
2322
  type: "button",
2331
2323
  disabled: !writable || probingId === row.id,
2332
2324
  style: btnStyle,
package/lib/index.js CHANGED
@@ -1255,7 +1255,7 @@ function coerceLink(raw) {
1255
1255
  kind: EGO_CLI_KIND,
1256
1256
  label: label === "" ? EGO_CLI_LABEL : label,
1257
1257
  cliPath,
1258
- ...rec.useSdkPath === void 0 ? {} : { useSdkPath: Boolean(rec.useSdkPath) }
1258
+ useSdkPath: true
1259
1259
  };
1260
1260
  }
1261
1261
  if (rec.kind === LP_KIND) {
@@ -1335,13 +1335,40 @@ function findLink(links, id) {
1335
1335
  return links.find((link) => link.id === id) ?? null;
1336
1336
  }
1337
1337
  /**
1338
- * The link that currently owns the tools. A disabled entry never wins even if
1339
- * it is still pointed at by `activeTargetId` — its id may be reactivated later
1340
- * without being removed from the sequence.
1338
+ * The link that owns routing RIGHT NOW — re-derived on every links event
1339
+ * (enable/activation toggle, reorder, add, remove).
1340
+ *
1341
+ * Activation wins while it is usable. The moment an event leaves
1342
+ * `activeTargetId` pointing at a disabled or missing entry, the FIRST enabled
1343
+ * link in sequence order takes over — the sequence order IS the priority
1344
+ * order. An EMPTY activation stays "nothing activated" (explicit off) instead
1345
+ * of silently adopting a link the user never activated.
1341
1346
  */
1342
- function activeLink(links, activeTargetId) {
1343
- const link = findLink(links, activeTargetId);
1344
- return link && link.enabled ? link : null;
1347
+ function resolveEffectiveLink(links, activeTargetId) {
1348
+ if (activeTargetId === "") return null;
1349
+ const activated = findLink(links, activeTargetId);
1350
+ if (activated && activated.enabled) return {
1351
+ link: activated,
1352
+ reason: "activated"
1353
+ };
1354
+ const fallback = links.find((link) => link.enabled);
1355
+ if (!fallback) return null;
1356
+ return {
1357
+ link: fallback,
1358
+ reason: "priority-fallback",
1359
+ demotedId: activeTargetId
1360
+ };
1361
+ }
1362
+ /**
1363
+ * True when an attach cache row describes THIS link (same id, and for a cdp
1364
+ * link the same endpoint string). After a links event the async refresh may
1365
+ * still be probing the new owner; a cache row describing the PREVIOUS owner
1366
+ * must not leak its linkKind/cliPath/wsUrl into the new channel's decisions —
1367
+ * that leak is how a deactivated ego-cli kept driving every bcdp_* call.
1368
+ */
1369
+ function attachMatchesLink(attach, link) {
1370
+ if (attach.targetId !== link.id) return false;
1371
+ return link.kind !== "cdp" || attach.endpoint === link.endpoint;
1345
1372
  }
1346
1373
  /**
1347
1374
  * Resolve one endpoint to a browser websocket URL.
@@ -1606,12 +1633,15 @@ async function refreshAttach(input) {
1606
1633
  const now = input.now ?? (() => Date.now());
1607
1634
  const previous = cache.get();
1608
1635
  const suggested = {
1609
- ...previous,
1636
+ ...emptyAttachState(),
1610
1637
  mode: input.mode,
1611
1638
  status: input.mode === "local" ? "local" : "idle",
1612
- wsUrl: input.mode === "local" ? "" : previous.wsUrl,
1613
- code: "",
1614
- message: ""
1639
+ linkKind: void 0,
1640
+ cliPath: void 0,
1641
+ cliShape: void 0,
1642
+ sdkPath: "",
1643
+ endpointSource: void 0,
1644
+ engine: void 0
1615
1645
  };
1616
1646
  if (input.mode === "local") {
1617
1647
  suggested.targetId = "";
@@ -1658,7 +1688,7 @@ async function refreshAttach(input) {
1658
1688
  }
1659
1689
  return cache.patch(suggested);
1660
1690
  }
1661
- const target = activeLink(input.targets, input.activeTargetId);
1691
+ const target = resolveEffectiveLink(input.targets, input.activeTargetId)?.link ?? null;
1662
1692
  if (!target) return cache.patch({
1663
1693
  ...suggested,
1664
1694
  status: "no-active",
@@ -1666,7 +1696,7 @@ async function refreshAttach(input) {
1666
1696
  endpoint: "",
1667
1697
  wsUrl: "",
1668
1698
  code: input.remoteEnabled === false ? "remote-disabled" : "no-active-target",
1669
- message: input.remoteEnabled === false ? "remote CDP is disabled by the remoteEnabled switch; the target sequence is preserved and can be re-enabled at any time" : "no activated target in the sequence",
1699
+ message: input.remoteEnabled === false ? "remote CDP is disabled by the remoteEnabled switch; the target sequence is preserved and can be re-enabled at any time" : input.activeTargetId === "" ? "no activated target in the sequence" : "the activated entry is disabled or gone and no enabled link can take over; enable a link, activate one, or set cdpMode=local",
1670
1700
  resolvedAt: now()
1671
1701
  });
1672
1702
  if (input.remoteEnabled === false && target.kind !== EGO_CLI_KIND && target.kind !== LP_KIND) return cache.patch({
@@ -1702,6 +1732,7 @@ async function refreshAttach(input) {
1702
1732
  status: "ready",
1703
1733
  wsUrl: outcome.wsUrl,
1704
1734
  engine: outcome.engine,
1735
+ endpointSource: "remote",
1705
1736
  code: "",
1706
1737
  message: "",
1707
1738
  latencyMs: outcome.latencyMs,
@@ -1853,7 +1884,7 @@ function markEgoToolCall(sessionId) {
1853
1884
  toolCallCount += 1;
1854
1885
  lastEgoActivity = Date.now();
1855
1886
  for (const cb of [...activityListeners]) try {
1856
- cb();
1887
+ cb(sessionId);
1857
1888
  } catch {}
1858
1889
  const payload = sessionId === void 0 || sessionId === "" ? { count: toolCallCount } : {
1859
1890
  count: toolCallCount,
@@ -2677,7 +2708,7 @@ const Config$1 = z.object({
2677
2708
  id: z.string(),
2678
2709
  label: z.string(),
2679
2710
  cliPath: z.string(),
2680
- useSdkPath: z.boolean(),
2711
+ useSdkPath: z.boolean().description("Deprecated: ALWAYS treated as true since v1.7.1-rc.5 — the native ego CLI has no taskSpaces facade, so without the bundled harness every call fails. Kept in the row shape so old profiles still validate; a stored false is healed on read."),
2681
2712
  enabled: z.boolean(),
2682
2713
  note: z.string(),
2683
2714
  probeStatus: z.union([
@@ -2717,19 +2748,20 @@ const Config$1 = z.object({
2717
2748
  "unknown"
2718
2749
  ])
2719
2750
  })
2720
- ])).description("Ordered connection sequence: CDP endpoints and (at most one) local ego CLI link. Only the ACTIVATED and enabled entry receives every bcdp_* call. Order IS the priority order.").volatile(),
2721
- activeTargetId: z.string().description("Id of the activated entry in links. Empty = nothing activated.").volatile(),
2751
+ ])).description("Ordered connection sequence: CDP endpoints and (at most one) local ego CLI link. The ACTIVATED entry receives every bcdp_* call; if the activation points at a disabled or removed entry, the FIRST enabled link in this order takes over (logged and shown by bcdp_doctor). Order IS the priority order.").volatile(),
2752
+ activeTargetId: z.string().description("Id of the activated entry in links. Empty = nothing activated (no silent adoption). A disabled/removed entry here falls back to the first enabled link in order.").volatile(),
2722
2753
  cdpMode: cdpMode.description("auto = use the activated target and never start a local browser silently; remote = only ever connect to the activated target; local = always use local browser control.").volatile(),
2723
2754
  cdpProbeTimeoutMs: z.number().min(200).max(3e4).step(100).description("Timeout for one CDP endpoint probe (http endpoints answer /json/version)."),
2724
2755
  cursorHud: z.boolean().description("Draw the agent cursor HUD into screenshots."),
2725
2756
  cursorName: z.string().description("Name label shown in the cursor HUD."),
2726
2757
  allowLocalFallback: z.boolean().description("auto mode may fall back to launching a local browser when the activated target is unreachable. Off by default: the fallback must be explicit.").volatile(),
2727
2758
  legacyEgoToolNames: z.boolean().description("ALSO register the tools under their old ego_* names for scripts written before the bcdp_* rename. Off by default; mutually exclusive with installing the upstream ego-browser plugin (same tool names)."),
2728
- toolInjection: toolInjection.default("lazy").description("lazy = keep only the core tier resident and inject the rest after the first bcdp_* activity (the idle reaper seals them back); always = register every allowed tool at mount (the historical behaviour).").volatile(),
2729
- toolBrowse: z.boolean().default(true).description("Basic browsing tiers — act + observe + wait (14 tools: click / fill / key / hover / scroll / select / check / drag / tab / screenshot / page_info / read_element / js / wait). Internally released in three waves. Off = sealed: removed from the model tool list.").volatile(),
2759
+ toolInjection: toolInjection.default("lazy").description("lazy = keep only bcdp_status resident (it is the unlock entry: the rest are injected after the first bcdp_* activity, and the idle reaper seals them back); always = register every allowed tool at mount (the historical behaviour).").volatile(),
2760
+ toolBrowse: z.boolean().default(true).description("Basic browsing tiers — act + observe + wait (19 tools: space / navigate / click / fill / key / hover / scroll / select / check / drag / tab / help / doctor / screenshot / page_info / read_element / js / snapshot / wait). Internally released in three waves. Off = sealed: removed from the model tool list.").volatile(),
2730
2761
  toolExtended: z.boolean().default(true).description("Extended tiers — power + session (8 tools: raw CDP / http / upload / download / dialog / captcha / auth_flush / login_import). Off = sealed even after browser activity.").volatile(),
2731
- toolEscape: z.boolean().default(true).description("Escape-hatch tier (1 tool: script — run an arbitrary heredoc with page/browser/taskSpaces/fetch/cdp preloaded; verbatim:true reproduces the old bare-heredoc cli behaviour). Unlike every other non-core tier it is NOT held back until browser activity: the one tool that can do anything in a single call must always be reachable. Off = sealed.").volatile(),
2762
+ toolEscape: z.boolean().default(true).description("Escape-hatch tier (1 tool: script — run an arbitrary heredoc with page/browser/taskSpaces/fetch/cdp preloaded; verbatim:true reproduces the old bare-heredoc cli behaviour). Sealed until browser activity like every other non-core tier: call bcdp_status first, then it appears. Off = sealed.").volatile(),
2732
2763
  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(),
2764
+ 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(),
2733
2765
  localHeadless: z.boolean().description("Run the locally launched browser headless."),
2734
2766
  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(),
2735
2767
  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(),
@@ -2999,6 +3031,7 @@ function resolveConfig(config = {}) {
2999
3031
  toolExtended: tierOpenByDefault(config.toolExtended),
3000
3032
  toolEscape: tierOpenByDefault(config.toolEscape),
3001
3033
  toolJudge: tierOpenByDefault(config.toolJudge),
3034
+ sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
3002
3035
  localHeadless: config.localHeadless === void 0 ? false : Boolean(config.localHeadless),
3003
3036
  localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
3004
3037
  lightpandaArgs: trimmed(config.lightpandaArgs),
@@ -3245,7 +3278,7 @@ function envelopeError(code, message) {
3245
3278
  * add/change a tool, remember to sync an entry here or bcdp_help won't find it.
3246
3279
  */
3247
3280
  const EGO_HELP_INDEX = {
3248
- overview: "CDP 浏览器代理:结构化浏览器工具。导航/交互/观察/表单/网络/等待/键鼠皆有专项工具,另提供 bcdp_help(本索引)、bcdp_doctor(体检)、bcdp_script(自由脚本逃生舱;verbatim:true 为裸 heredoc)。连接与激活见 topic=links。分类见: tools / navigate / observe / input / keyboard-mouse / form / wait / network / login / script / doctor / lightpanda / injection。用 `topic` 查询,或直接给工具名。",
3281
+ overview: "CDP 浏览器代理:结构化浏览器工具。导航/交互/观察/表单/网络/等待/键鼠皆有专项工具,另提供 bcdp_help(本索引)、bcdp_doctor(体检)、bcdp_script(自由脚本逃生舱;verbatim:true 为裸 heredoc)。连接与激活见 topic=links。If a bcdp_* tool is missing from your list, read topic=injection first: tools are tiered and only core stays resident. 分类见: tools / navigate / observe / input / keyboard-mouse / form / wait / network / login / script / doctor / lightpanda / injection。用 `topic` 查询,或直接给工具名。",
3249
3282
  tools: "工具清单: bcdp_status, bcdp_space(+op:open/close/list/handoff/takeover), bcdp_snapshot, bcdp_navigate, bcdp_tab, bcdp_click(+double), bcdp_fill, bcdp_js, bcdp_cdp, bcdp_screenshot(+selector), bcdp_page_info, bcdp_wait(+op:duration/selector/url/response/load/function/request/event), bcdp_key(+text/type/insert), bcdp_hover, bcdp_read_element, bcdp_select, bcdp_drag, bcdp_scroll, bcdp_upload, bcdp_check, bcdp_dialog, bcdp_download, bcdp_http, bcdp_captcha, bcdp_auth_flush, bcdp_login_import, bcdp_help, bcdp_doctor, bcdp_script(+verbatim), bcdp_jev_status, bcdp_jev_frame, bcdp_jev_attempt, bcdp_jev_ask, bcdp_jev_run。",
3250
3283
  links: "连接序列(设置面板):有序列表,顺序即优先级,被激活的一项驱动每一次 bcdp_* 调用。两种类型——CDP 端点(注入 EGO_LINUX_CDP_URL,指向已开调试端口的浏览器)与 本机 ego CLI(不注入端点,由本机 ego CLI 直接驱动 ego 浏览器;仅限本机,全局至多一条)。cdpMode: auto=按激活项;remote=仅接受 CDP 端点;local=受管本地启动器。cdpMode=remote 与「本机 ego CLI」组合会显式报 mode-kind-mismatch。remoteEnabled 只管远端 CDP,不影响本机 CLI 连接。",
3251
3284
  navigate: "bcdp_navigate: 打开URL或切tab(同任务复用当前tab)。bcdp_wait op=url: 等跳转(登录/分页)。",
@@ -3260,7 +3293,7 @@ const EGO_HELP_INDEX = {
3260
3293
  login: "bcdp_auth_flush: 把登录cookie落盘到ego profile; 观察窗登录引导条+『已登录,保存』按钮触发同一动作。bcdp_login_import: 从系统浏览器(Chrome/Edge/Brave)按域名导入登录cookie(source/domains/dryRun; 先dryRun看可导入项; ego浏览器须已在运行)。",
3261
3294
  script: "bcdp_script: 原样运行任意内置运行时 heredoc 脚本(page/browser/taskSpaces/site/fetch/cdp预载)。默认加 preamble(选区+激活真实 tab)并额外返回 duration/timedOut; verbatim:true 则完全原样、无 preamble(原 bcdp_cli 行为, 需自行 taskSpaces.useOrCreate)。",
3262
3295
  doctor: "bcdp_doctor: 体检环境(浏览器候选、vendored runtime、状态目录、CDP端口、任务空间、引擎与降级清单);首行附工具注入面快照。",
3263
- injection: "工具分级注入(不是工具,是出现时机):34 个 bcdp_* 分八批——core(status/doctor/help/space/navigate/snapshot,常驻不可封印)/ act(点击填写键鼠拖拽+tab 标签管理)/ observe(截图页面信息读取js)/ wait(bcdp_wait 全 op)/ power(裸CDP/HTTP/上传/下载/对话框)/ session(验证码/登录落盘/登录导入)/ escape(script 逃生舱)/ judge(bcdp_jev_*)。设置旋钮(全 volatile):toolInjection = lazy(默认,常驻 core + escape,首次 bcdp_* 调用后铺开其余)/ always(挂载即全量,历史行为);toolBrowse(act+observe+wait,内部按 act→observe→wait 三波放行)/ toolExtended(power+session)/ toolEscape(script)/ toolJudge 四把开关——开 = 开放注册,关 = 该批从工具列表移除(core 级不给开关,封了就没解锁入口);judge 级即使开了仍需配 JEV/Laya Key。**escape 批不吃活动闸**:script 是唯一的「一次调用干完任意多步任务」的入口,必须始终可达,不排在首次活动之后。封印 = 从工具列表里反注册,不是执行期报错;lazy 下闲置回收会把扩展面收回。**若某个 bcdp_* 工具不在你的工具列表里**:它被分级封印了——先跑 bcdp_status 或 bcdp_doctor(两者也算浏览器活动,会把面铺开),或让用户在设置页「工具封印」里打开对应档位的开关;别猜测不存在的工具名。",
3296
+ injection: "SEALED TOOLS — read this first when a bcdp_* tool you expect is missing from your tool list. Under toolInjection=lazy (the default) only bcdp_status stays registered — it is the unlock entry: calling it re-opens the other batches for this session. Every other batch (act / observe / wait / power / session / escape / judge) is deregistered until browser activity re-opens them; an idle reaper pass or a restart seals them again. Missing from the list = sealed, not broken, and not a wrong name. Fix: call bcdp_status (it counts as browser activity), then retry the tool. A call made before that fails with \"unknown tool\" at the harness level, before this plugin sees it. To keep all 34 resident instead, set toolInjection=always in the profile config. —— 以下为原说明:工具分级注入(不是工具,是出现时机):34 个 bcdp_* 分八批——core(只 bcdp_status 一个:常驻且是解锁入口,不给开关)/ act(空间/导航/点击填写键鼠拖拽/tab 标签管理/指南/预检,13 个)/ observe(截图/页面信息/读取/js/snapshot,5 个)/ wait(bcdp_wait 全 op,1 个)/ power(裸CDP/HTTP/上传/下载/对话框,5 个)/ session(验证码/登录落盘/登录导入,3 个)/ escape(script 逃生舱,1 个)/ judge(bcdp_jev_*,5 个)——1+13+5+1+5+3+1+5=34。设置旋钮(全 volatile):toolInjection = lazy(默认,只常驻 bcdp_status,首次 bcdp_* 调用后按批次铺开)/ always(挂载即全量,历史行为);toolBrowse(act+observe+wait=19,内部按 act→observe→wait 三波放行)/ toolExtended(power+session=8)/ toolEscape(script=1)/ toolJudge(judge=5)四把开关——开 = 开放注册,关 = 该批从工具列表移除(core 级不给开关,封了就没解锁入口);judge 级即使开了仍需配 JEV/Laya Key。**1.7.0 起 escape 与其它非 core 批同闸**:script 不再冷启动可用——先调 bcdp_status 即可拿到它;要回到「始终可达」,设 toolInjection=always。封印 = 从工具列表里反注册,不是执行期报错;lazy 下闲置回收会把扩展面收回。**若某个 bcdp_* 工具不在你的工具列表里**:它被分级封印了——先跑常驻的 bcdp_status(它算浏览器活动,会把面铺开),或让用户在设置页「工具封印」里打开对应档位的开关;别猜测不存在的工具名。",
3264
3297
  lightpanda: "Lightpanda 作为后端(无头文本渲染引擎,beta):设置面板「添加 Lightpanda(受管)」——受管 serve 行(本机单例,插件负责拉起/复用/停止;win32 经 WSL2,linux/mac 本机直装),激活后 probe 自动识别 engine 并全链降级;也可用普通 CDP 端点接已自起的 serve(http://127.0.0.1:9222)。**有头/无头与顺序语义**:CDP 端点/本机 Chrome/ego CLI 是有头类型——可人工兜底(手动输账号、过验证码),是兜底主力;Lightpanda 是无头类型——无法人工介入,只适合快速试验。顺序即优先级:把 Lightpanda 排在前面 = 快速场景优先用它;排在有头类型后面 = 有头兜底优先,Lightpanda 实际不会被启用。安装——linux/macOS:`curl -fsSL https://pkg.lightpanda.io/install.sh | bash`(装入 ~/.local/bin,确保 PATH 含它),`lightpanda serve --host 127.0.0.1 --port 9222`;Windows:无原生版,用 WSL2(管理员 `wsl --install`,WSL 内同上;WSL2 自动把端口映射到宿主 localhost)或 Docker(`docker run -d -p 127.0.0.1:9222:9222 lightpanda/browser:nightly`)。可用:navigate/js/click/fill/key/snapshot(AX树)/http/login_import 等;降级:截图=PNG 文本渲染(jev 输出带 engine/rendering 元数据);关闭:观察窗实时画面、面板点选、bcdp_download(调用即结构化报错)、auth_flush(返回 degraded)",
3265
3298
  judge: "JEV/Laya 判定(阶段 10):机械采集「截图 + 编号 DOM + 意图 + 操作进度」→ 组装问题 → 取选择 → 执行 → 验证。判定器只能回传编号,绝不给选择器(幻觉选择器在结构上不可能)。四件套:bcdp_jev_status(先跑这个:判定链可用性 + 配置体检,不发任何请求)/ bcdp_jev_frame(采一帧,看判定器会看到什么)/bcdp_jev_ask(组装请求体;dryRun 默认 true,可指定 round=control|chapter|pick|evaluate 逐级看)/ bcdp_jev_run(跑循环,返回逐步 trace)。bcdp_jev_attempt(平的尝试循环):给 url + goal,开页后每轮选项 = DOM 候选 + end 项,判定模型在 maxActions(默认 5)预算内行动或自选 end 结束,回执含每步 anchor;判定上下文只走 DOM 树文本(模型不读截图),完成后你用 bcdp_cdp/bcdp_screenshot 按 targetId 自行核验——回执是报告不是证明。**三级缩小**:control(要不要动手,固定 5 项)→ chapter(哪个章节,按 AX 容器聚簇)→ pick(章节内哪个编号 + 风险度)。分章节不是装饰:阈值按候选数分桶,把 20 选 1 拆成「几选 1 × 几选 1」会让两轮都落在更严的桶里。单章节时不问章节轮。**判定上下文是隔离的**:只允许 INTENT / PROGRESS / FRAME / HISTORY 四段,**绝不带 agent 会话 session 前缀**;多出任何一段都会在组装时直接抛错(不靠约定,靠断言)。PROGRESS 由循环自己机械生成,不让模型写(模型写的进度是第二个人幻觉通道)。**评估开关 jevEvaluate(默认开)**:每步执行后判定器再判进度 inprogress/done/fail;fail 或「未验真的 done」不猜下一步,直接 escalate——带有序 RecoveryOption(reload 排第一,因陈旧渲染会藏住已写入的确认),交回你来恢复或停手。被操作元素会保留 class 等定位特征(只剥离检视器外壳 token)随 escalate 回传,便于恢复。**默认链路是 laya -> rule**:JEV 目前无法注册,所以默认不写它;将来可用时把 jev 加回跳序并填 URL 即可。不可用的跳**跳过不调用**(laya-api 强制鉴权无匿名分支,缺 key 必然 401),每一跳的跳过与失败都记进 trace,绝不静默回落;refuse 是结果不是异常。阈值一律用选中项概率 top(不是 confidence:后者是归一化熵,2 选 1 与 20 选 1 不可比)。设置面板键:layaUrl/layaKey/layaModel(laya 端口 8000,不是 7789)、judgePrefer、jevChunkSize、jevMaxImageBytes、jevHistoryLimit、jevArchiveImage、jevStepBudget、jevWallMs;jevUrl/jevKey/jevModel 留空即可(JEV 未开放注册)。"
3266
3299
  };
@@ -3565,15 +3598,10 @@ function registerSettingsBridge(wctx, ctx) {
3565
3598
 
3566
3599
  //#endregion
3567
3600
  //#region src/toolTiers.ts
3568
- const CORE = [
3569
- "bcdp_status",
3570
- "bcdp_doctor",
3571
- "bcdp_help",
3601
+ const CORE = ["bcdp_status"];
3602
+ const ACT = [
3572
3603
  "bcdp_space",
3573
3604
  "bcdp_navigate",
3574
- "bcdp_snapshot"
3575
- ];
3576
- const ACT = [
3577
3605
  "bcdp_click",
3578
3606
  "bcdp_fill",
3579
3607
  "bcdp_key",
@@ -3582,13 +3610,16 @@ const ACT = [
3582
3610
  "bcdp_select",
3583
3611
  "bcdp_check",
3584
3612
  "bcdp_drag",
3585
- "bcdp_tab"
3613
+ "bcdp_tab",
3614
+ "bcdp_help",
3615
+ "bcdp_doctor"
3586
3616
  ];
3587
3617
  const OBSERVE = [
3588
3618
  "bcdp_screenshot",
3589
3619
  "bcdp_page_info",
3590
3620
  "bcdp_read_element",
3591
- "bcdp_js"
3621
+ "bcdp_js",
3622
+ "bcdp_snapshot"
3592
3623
  ];
3593
3624
  const WAIT = ["bcdp_wait"];
3594
3625
  const POWER = [
@@ -3622,6 +3653,17 @@ const TIER_OF_TOOL = new Map([
3622
3653
  ["escape", ESCAPE],
3623
3654
  ["judge", JUDGE]
3624
3655
  ].flatMap(([tier, names]) => names.map((n) => [n, tier])));
3656
+ /** 分级成员表(测试与文档用)。 */
3657
+ const TIER_MEMBERS = {
3658
+ core: CORE,
3659
+ act: ACT,
3660
+ observe: OBSERVE,
3661
+ wait: WAIT,
3662
+ power: POWER,
3663
+ session: SESSION,
3664
+ escape: ESCAPE,
3665
+ judge: JUDGE
3666
+ };
3625
3667
  /** 去掉 `bcdp_`/`ego_` 前缀后的裸名,便于策略表保持前缀无关。 */
3626
3668
  const bareToolName = (name$1) => name$1.replace(/^(?:bcdp|ego)_/, "");
3627
3669
  /** 批次放行顺序(索引即 rank)。 */
@@ -3671,14 +3713,18 @@ const tierOpen = (tier, p) => {
3671
3713
  * ③ 活动闸:`lazy` 下非 core 级要等活动,`always` 下不设时机闸;
3672
3714
  * ④ 批次闸:只在 act/observe/wait 三批上按 batchDepth 递增放行。
3673
3715
  *
3674
- * `escape` 是唯一的例外:它不吃③。逃生舱必须在模型手里始终可达——否则遇到
3675
- * 「结构化工具没覆盖」的情形时,模型既调不动它、也没法用别的工具绕过。
3716
+ * depth=0 时连 act 也被封,所以唯一常驻的 `bcdp_status` 必须既置 active 又推进
3717
+ * depth,否则 lazy 模式下没有任何解锁路径(决策与收益见
3718
+ * `.agents/plans/bcdp-core-narrowing/`)。
3719
+ *
3720
+ * `escape` 的「不吃③」豁免已移除:现在它与其它非 core 批同样等活动。豁免时期的
3721
+ * 理由是「结构化工具没覆盖时手里没逃生手段」,而现在该手段需要先调 `bcdp_status`
3722
+ * 才能拿到——代价是 ≈1,620 字符/轮,换为常驻面收窄的主要一块。
3676
3723
  */
3677
3724
  function tierAllowed(tier, p) {
3678
3725
  if (tier === "core") return true;
3679
3726
  if (!tierOpen(tier, p)) return false;
3680
3727
  if (tier === "judge" && !p.judgeConfigured) return false;
3681
- if (tier === "escape") return true;
3682
3728
  if (p.injection === "always") return true;
3683
3729
  if (tier === "act" || tier === "observe" || tier === "wait") {
3684
3730
  if (!p.active) return false;
@@ -7406,21 +7452,37 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
7406
7452
  return env;
7407
7453
  }
7408
7454
  /**
7455
+ * The channel that owns routing right now: `resolveEffectiveLink` over the
7456
+ * CURRENT config (activation first, sequence order as the visible fallback),
7457
+ * plus the attach cache SCOPED to that link. After any links event
7458
+ * (enable/activation toggle, reorder, add, remove) the async refresh may still
7459
+ * be probing; a cache row describing the PREVIOUS owner must not leak its
7460
+ * linkKind/cliPath/wsUrl into the new channel's spawn decisions.
7461
+ */
7462
+ function effectiveChannel(cfg) {
7463
+ const effective = resolveEffectiveLink(cfg.links ?? [], cfg.activeTargetId ?? "");
7464
+ const live = defaultAttachCache.get();
7465
+ return {
7466
+ effective,
7467
+ attach: effective && attachMatchesLink(live, effective.link) ? live : emptyAttachState()
7468
+ };
7469
+ }
7470
+ /**
7409
7471
  * Read the attach decision for the CURRENTLY configured mode/activation.
7410
- * Pure over (cfg, cache) �?the decision table itself lives in cdp-targets.ts.
7472
+ * Pure over (cfg, cache) — the decision table itself lives in cdp-targets.ts.
7411
7473
  */
7412
7474
  function decideCdpAttach(cfg) {
7413
- const attach = defaultAttachCache.get();
7475
+ const { effective, attach } = effectiveChannel(cfg);
7414
7476
  return decideAttach({
7415
7477
  mode: cfg?.cdpMode ?? "auto",
7416
- hasActive: attach.status !== "no-active" && attach.targetId !== "",
7478
+ hasActive: effective !== null,
7417
7479
  status: attach.status,
7418
7480
  wsUrl: attach.wsUrl,
7419
7481
  code: attach.code,
7420
7482
  message: attach.message,
7421
7483
  allowLocalFallback: Boolean(cfg?.allowLocalFallback),
7422
- remoteDisabled: attach.code === "remote-disabled",
7423
- ...attach.linkKind ? { linkKind: attach.linkKind } : {},
7484
+ remoteDisabled: cfg?.remoteEnabled === false,
7485
+ ...effective ? { linkKind: effective.link.kind } : {},
7424
7486
  localLauncherReady: true
7425
7487
  });
7426
7488
  }
@@ -7512,7 +7574,7 @@ async function openAgentWindow(ctx, cfg) {
7512
7574
  ok: false,
7513
7575
  error: gate
7514
7576
  };
7515
- if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
7577
+ if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND) {
7516
7578
  ctx.logger?.info?.("dsh-browser-cdp: ego-cli: browser already visible, skipping --open");
7517
7579
  return { ok: true };
7518
7580
  }
@@ -7547,6 +7609,9 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
7547
7609
  cfg.spaceTracker.resetToName();
7548
7610
  result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
7549
7611
  }
7612
+ if (!result.ok && CDP_CONNECT_FAIL_RE.test(result.error ?? "")) {
7613
+ if (await cfg.refreshAttach?.() === true) result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
7614
+ }
7550
7615
  return result;
7551
7616
  }
7552
7617
  /**
@@ -7562,6 +7627,13 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
7562
7627
  * @internal exported for tests
7563
7628
  */
7564
7629
  const TAB_STUCK_RE = /no active tab|navigation (?:timed out|timeout)|page\.goto[\s\S]*timeout|timed out after \d+ms|net::ERR_|waiting for (?:document|load) timed out|TimeoutError|target closed/i;
7630
+ /**
7631
+ * A dead cached ws (the browser was relaunched behind the SAME endpoint) surfaces
7632
+ * as this one runtime message — see `runtime/ego-linux/src/transport.mjs`. It is
7633
+ * deliberately NOT folded into `TAB_STUCK_RE`: the fix is a re-probe of the link,
7634
+ * not a tab swap, so the two recoveries must stay distinguishable.
7635
+ */
7636
+ const CDP_CONNECT_FAIL_RE = /failed to connect to CDP endpoint/i;
7565
7637
  /** True when a failed run looks like a wedged/absent tab rather than a cold start. */
7566
7638
  function isTabStuckFailure(result) {
7567
7639
  const hay = `${result.error ?? ""}\n${result.stderr ?? ""}`;
@@ -7734,7 +7806,7 @@ function buildEgoToolArgv(prefix, attach, runtimeArgs) {
7734
7806
  async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7735
7807
  let handle;
7736
7808
  try {
7737
- const attach = defaultAttachCache.get();
7809
+ const { attach } = effectiveChannel(cfg);
7738
7810
  handle = subprocess.spawn({
7739
7811
  argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
7740
7812
  cwd: process.cwd(),
@@ -7786,21 +7858,32 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7786
7858
  stdout,
7787
7859
  stderr
7788
7860
  };
7789
- const value = parseSentinel(mergeCliOutput({
7790
- stdout,
7791
- stderr
7792
- }));
7793
- if (value === void 0) return {
7794
- ok: false,
7795
- error: `ego-browser finished but no ${SENTINEL} JSON payload was found on stdout/stderr${describeStderr(stderr)}`,
7861
+ return {
7862
+ ok: true,
7863
+ value: parseSentinel(mergeCliOutput({
7864
+ stdout,
7865
+ stderr
7866
+ })),
7796
7867
  stdout,
7797
7868
  stderr
7798
7869
  };
7870
+ }
7871
+ /** How much raw stdout a tool may hand back when a script emitted no JSON. */
7872
+ const TOOL_RAW_STDOUT_MAX = 4e3;
7873
+ /**
7874
+ * The payload a bcdp_* tool returns for a successful run.
7875
+ *
7876
+ * Dropping `undefined` straight into the tool result would show the model an
7877
+ * empty outcome for a script that actually ran, so fall back to the (bounded)
7878
+ * raw stdout plus a note naming the reason. Structured tools always emit a
7879
+ * sentinel payload and never take this branch.
7880
+ */
7881
+ function toolPayload(result) {
7882
+ if (result.value !== void 0) return result.value;
7799
7883
  return {
7800
7884
  ok: true,
7801
- value,
7802
- stdout,
7803
- stderr
7885
+ stdout: (result.stdout ?? "").trim().slice(0, TOOL_RAW_STDOUT_MAX),
7886
+ note: "no JSON payload on stdout; raw output returned"
7804
7887
  };
7805
7888
  }
7806
7889
  /** JS snippet that pins an action tool to one task space. */
@@ -7883,12 +7966,12 @@ function defineEgoTool(ctx, cfg, opts) {
7883
7966
  if (!result$1.ok) throw new Error(recoveredFrom ? `${result$1.error}\n${recoveredFrom}` : result$1.error);
7884
7967
  if (result$1.value && typeof result$1.value === "object") result$1.value.recoveredFrom = recoveredFrom;
7885
7968
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result$1.value);
7886
- return result$1.value;
7969
+ return toolPayload(result$1);
7887
7970
  }
7888
7971
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => opts.buildScript(args));
7889
7972
  if (!result.ok) throw new Error(result.error);
7890
7973
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result.value);
7891
- return result.value;
7974
+ return toolPayload(result);
7892
7975
  }),
7893
7976
  presentCall: () => ({
7894
7977
  card: "generic",
@@ -7898,7 +7981,54 @@ function defineEgoTool(ctx, cfg, opts) {
7898
7981
  })
7899
7982
  });
7900
7983
  }
7984
+ const scopeProbe = {
7985
+ restrictType: "n/a",
7986
+ onType: "n/a",
7987
+ agentsSvc: "n/a",
7988
+ agentCount: -1,
7989
+ createdEvents: 0,
7990
+ agentHasCtx: "n/a",
7991
+ agentCtxRestrict: "n/a",
7992
+ agentCtxTools: "n/a",
7993
+ error: ""
7994
+ };
7995
+ /** Inspect one agent handle (host-side shape varies) and remember what we reached. */
7996
+ function probeAgent(agent) {
7997
+ if (agent == null) return;
7998
+ scopeProbe.agentHasCtx = String(agent.ctx != null);
7999
+ scopeProbe.agentCtxTools = typeof agent?.ctx?.tools;
8000
+ scopeProbe.agentCtxRestrict = typeof agent?.ctx?.tools?.restrict;
8001
+ }
8002
+ /** Install the probe once per mount: capability types + live agent enumeration + lifecycle event. */
8003
+ function installScopeProbe(ctx) {
8004
+ try {
8005
+ const anyCtx = ctx;
8006
+ scopeProbe.restrictType = typeof anyCtx?.tools?.restrict;
8007
+ scopeProbe.onType = typeof anyCtx?.on;
8008
+ const agents = typeof anyCtx.get === "function" ? anyCtx.get("agents") : void 0;
8009
+ scopeProbe.agentsSvc = agents == null ? "absent" : "present";
8010
+ if (agents != null) {
8011
+ const list = typeof agents.roots === "function" ? agents.roots() : typeof agents.list === "function" ? agents.list() : [];
8012
+ scopeProbe.agentCount = Array.isArray(list) ? list.length : -2;
8013
+ probeAgent(Array.isArray(list) ? list[0] : void 0);
8014
+ }
8015
+ if (scopeProbe.onType === "function") {
8016
+ const off = anyCtx.on("agent/created", (payload) => {
8017
+ scopeProbe.createdEvents += 1;
8018
+ probeAgent(payload?.agent ?? payload);
8019
+ });
8020
+ ctx.effect?.(() => typeof off === "function" ? off : () => void 0);
8021
+ }
8022
+ } catch (err) {
8023
+ scopeProbe.error = err instanceof Error ? err.message.slice(0, 120) : String(err).slice(0, 120);
8024
+ }
8025
+ }
8026
+ /** One-line render for the doctor report. */
8027
+ function scopeProbeLine() {
8028
+ return `scope probe: tools.restrict=${scopeProbe.restrictType} ctx.on=${scopeProbe.onType} agentsSvc=${scopeProbe.agentsSvc} agentCount=${scopeProbe.agentCount} agentCreatedEvents=${scopeProbe.createdEvents} agentHasCtx=${scopeProbe.agentHasCtx} agent.ctx.tools=${scopeProbe.agentCtxTools} agent.ctx.tools.restrict=${scopeProbe.agentCtxRestrict}` + (scopeProbe.error !== "" ? ` error=${scopeProbe.error}` : "");
8029
+ }
7901
8030
  function apply(ctx, config = {}) {
8031
+ installScopeProbe(ctx);
7902
8032
  const bridge = installSettingsAuto(ctx, config);
7903
8033
  const ffmpegManager = getSharedFfmpegInstallationManager();
7904
8034
  const initialFfmpegConfig = resolveConfig(bridge.source());
@@ -7907,7 +8037,9 @@ function apply(ctx, config = {}) {
7907
8037
  requestedEncoder: initialFfmpegConfig.ffmpegEncoder
7908
8038
  }).catch(() => {});
7909
8039
  const spaceTracker = createSessionSpaceTracker((sessionKey) => deriveSlotDefaultName(resolveConfig(bridge.source()), sessionKey));
8040
+ let triggerCdpRef;
7910
8041
  const cfg = {
8042
+ refreshAttach: () => triggerCdpRef?.() ?? Promise.resolve(false),
7911
8043
  egoBin: typeof config.egoBin === "string" && config.egoBin !== "" ? config.egoBin : DEFAULT_EGO_BIN,
7912
8044
  get configuredDefaultSpace() {
7913
8045
  return resolveConfig(bridge.source()).defaultSpace;
@@ -7987,6 +8119,9 @@ function apply(ctx, config = {}) {
7987
8119
  get toolJudge() {
7988
8120
  return resolveConfig(bridge.source()).toolJudge;
7989
8121
  },
8122
+ get sessionScopedPulse() {
8123
+ return resolveConfig(bridge.source()).sessionScopedPulse;
8124
+ },
7990
8125
  get links() {
7991
8126
  return resolveConfig(bridge.source()).links;
7992
8127
  },
@@ -7995,8 +8130,8 @@ function apply(ctx, config = {}) {
7995
8130
  return sanitizeLinks(raw.links ?? raw.cdpTargets).droppedEgoCli;
7996
8131
  },
7997
8132
  get egoArgvPrefix() {
7998
- const attach = defaultAttachCache.get();
7999
- if (attach.linkKind === EGO_CLI_KIND && attach.cliPath) return spawnArgvFor(attach.cliShape === "node" ? "node" : "direct", attach.cliPath, []);
8133
+ const { effective, attach } = effectiveChannel(this);
8134
+ if (effective?.link.kind === EGO_CLI_KIND && attach.cliPath) return spawnArgvFor(attach.cliShape === "node" ? "node" : "direct", attach.cliPath, []);
8000
8135
  return [process.execPath, this.egoBin];
8001
8136
  },
8002
8137
  get activeTargetId() {
@@ -8079,7 +8214,14 @@ function apply(ctx, config = {}) {
8079
8214
  }
8080
8215
  };
8081
8216
  let browserActive = false;
8217
+ const sessionDepth = /* @__PURE__ */ new Map();
8082
8218
  let browseBatchDepth = 0;
8219
+ /** Compute max depth from all tracked sessions, or 0 if none. */
8220
+ const maxSessionDepth = () => {
8221
+ let m = 0;
8222
+ for (const d of sessionDepth.values()) if (d > m) m = d;
8223
+ return m;
8224
+ };
8083
8225
  const tiers = createTierInjector({
8084
8226
  register: (tool) => {
8085
8227
  const dispose = ctx.tools.register(tool);
@@ -8102,29 +8244,69 @@ function apply(ctx, config = {}) {
8102
8244
  logger: ctx.logger
8103
8245
  });
8104
8246
  /**
8105
- * 活动信号:每�?bcdp_* 调用推进 browse 批次(act �?observe �?wait),
8106
- * 到顶即止。只有注入面真的变了�?reapply�? */
8107
- const pulseActivity = () => {
8247
+ * Apply per-session restrict to hide globally-registered tools that exceed
8248
+ * the calling agent's own depth. Best-effort: silently no-ops when the host
8249
+ * does not expose agent-scoped restriction (plugin fiber is not an agent scope).
8250
+ */
8251
+ const tryRestrictSession = (sessionId) => {
8252
+ if (!cfg.sessionScopedPulse || !sessionId) return;
8253
+ try {
8254
+ const depth = sessionDepth.get(sessionId) ?? 0;
8255
+ const allowed = /* @__PURE__ */ new Set();
8256
+ for (const n of TIER_MEMBERS.core) allowed.add(n);
8257
+ const pol = {
8258
+ injection: cfg.toolInjection,
8259
+ toolBrowse: cfg.toolBrowse,
8260
+ toolExtended: cfg.toolExtended,
8261
+ toolEscape: cfg.toolEscape,
8262
+ toolJudge: cfg.toolJudge,
8263
+ judgeConfigured: judgeConfigured({
8264
+ jevKey: cfg.jevKey,
8265
+ layaKey: cfg.layaKey
8266
+ }),
8267
+ active: depth > 0,
8268
+ batchDepth: depth
8269
+ };
8270
+ for (const name$1 of tiers.surface().live) if (toolAllowed(name$1, pol)) allowed.add(name$1);
8271
+ const restrictFn = ctx.tools.restrict;
8272
+ if (typeof restrictFn === "function") restrictFn({ allow: [...allowed] });
8273
+ } catch {}
8274
+ };
8275
+ /**
8276
+ * Activity pulse: advance browse batch depth. When sessionScopedPulse is ON
8277
+ * and a sessionId is given, only that session's depth advances; the global
8278
+ * depth = max across sessions drives tier registration. Without restrict
8279
+ * support the effect is still beneficial for per-session sealAfterReap.
8280
+ */
8281
+ const pulseActivity = (sessionId) => {
8108
8282
  const before = browseBatchDepth;
8109
8283
  browserActive = true;
8110
- browseBatchDepth = Math.min(BATCH_ORDER.length, browseBatchDepth + 1);
8284
+ if (cfg.sessionScopedPulse && sessionId) {
8285
+ const cur = Math.min(BATCH_ORDER.length, (sessionDepth.get(sessionId) ?? 0) + 1);
8286
+ sessionDepth.set(sessionId, cur);
8287
+ browseBatchDepth = Math.max(browseBatchDepth, maxSessionDepth());
8288
+ } else browseBatchDepth = Math.min(BATCH_ORDER.length, browseBatchDepth + 1);
8111
8289
  if (before !== browseBatchDepth) tiers.reapply();
8290
+ if (cfg.sessionScopedPulse && sessionId) tryRestrictSession(sessionId);
8112
8291
  };
8113
8292
  {
8114
8293
  const offActivity = onEgoActivity(pulseActivity);
8115
8294
  ctx.effect?.(() => offActivity);
8116
8295
  }
8117
8296
  /**
8118
- * 闲置回收后把注入面收�?core 级(lazy 模式专属):浏览器已经停了,模型
8119
- * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开�? */
8297
+ * Seal: idle reaper resets depths. With sessionScopedPulse, only sessions
8298
+ * whose last activity exceeded the timeout are sealed; when ALL are idle the
8299
+ * global depth drops to 0 (same observable behaviour as before).
8300
+ */
8120
8301
  const sealAfterReap = () => {
8121
8302
  if (cfg.toolInjection !== "lazy" || !browserActive) return;
8303
+ if (cfg.sessionScopedPulse && sessionDepth.size > 0) {
8304
+ sessionDepth.clear();
8305
+ browseBatchDepth = 0;
8306
+ } else browseBatchDepth = 0;
8122
8307
  browserActive = false;
8123
- browseBatchDepth = 0;
8124
8308
  tiers.reapply();
8125
8309
  };
8126
- /**
8127
- * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动�? * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)�? */
8128
8310
  const tierView = {
8129
8311
  pulse: pulseActivity,
8130
8312
  active: () => browserActive,
@@ -8162,14 +8344,27 @@ function apply(ctx, config = {}) {
8162
8344
  const triggerCdpRefresh = (() => {
8163
8345
  let inFlight = false;
8164
8346
  let pending = false;
8347
+ /** Last ws handed to the worker; a differ means the browser was relaunched. */
8348
+ let lastAttachWs = null;
8349
+ /** Last channel owner (id|reason); a differ is logged so takeovers are visible. */
8350
+ let lastOwnerKey = null;
8351
+ /** True when this pass actually moved the resolved endpoint. */
8352
+ let changed = false;
8165
8353
  const run = async () => {
8166
8354
  if (inFlight) {
8167
8355
  pending = true;
8168
- return;
8356
+ return changed;
8169
8357
  }
8170
8358
  inFlight = true;
8359
+ changed = false;
8171
8360
  try {
8172
8361
  const resolved = resolveConfig(bridge.source());
8362
+ const owner = resolveEffectiveLink(resolved.links, resolved.activeTargetId);
8363
+ const ownerKey = owner ? `${owner.link.id}|${owner.reason}` : "none";
8364
+ if (ownerKey !== lastOwnerKey) {
8365
+ lastOwnerKey = ownerKey;
8366
+ ctx.logger?.info?.(owner ? `dsh-browser-cdp: channel owner: ${owner.link.label} [${owner.link.id}] (${owner.reason}${owner.demotedId ? `, over ${owner.demotedId}` : ""})` : "dsh-browser-cdp: channel owner: none (no enabled link owns routing)");
8367
+ }
8173
8368
  const attach = await refreshAttach({
8174
8369
  targets: resolved.links,
8175
8370
  activeTargetId: resolved.activeTargetId,
@@ -8191,7 +8386,12 @@ function apply(ctx, config = {}) {
8191
8386
  sdkPath: fileURLToPath(new URL("../runtime/ego-browser/dist/out/index.js", import.meta.url)),
8192
8387
  bundledCli: VENDORED_EGO_BIN
8193
8388
  });
8194
- if (setAttachEndpoint(attach.status === "ready" && attach.wsUrl !== "" ? attach.wsUrl : null, attach.status === "ready" ? attach.engine ?? "unknown" : null)) recycleWorker("cdp activation change").catch(() => null);
8389
+ const ws = attach.status === "ready" && attach.wsUrl !== "" ? attach.wsUrl : null;
8390
+ if (ws !== null && ws !== lastAttachWs) lastAttachWs = ws;
8391
+ if (setAttachEndpoint(ws, attach.status === "ready" ? attach.engine ?? "unknown" : null)) {
8392
+ changed = true;
8393
+ recycleWorker("cdp activation change").catch(() => null);
8394
+ }
8195
8395
  } catch {} finally {
8196
8396
  inFlight = false;
8197
8397
  if (pending) {
@@ -8199,12 +8399,12 @@ function apply(ctx, config = {}) {
8199
8399
  run();
8200
8400
  }
8201
8401
  }
8402
+ return changed;
8202
8403
  };
8203
- return () => {
8204
- run();
8205
- };
8404
+ return () => run();
8206
8405
  })();
8207
- bridge.onChange(triggerCdpRefresh);
8406
+ triggerCdpRef = triggerCdpRefresh;
8407
+ bridge.onChange(() => void triggerCdpRefresh());
8208
8408
  triggerCdpRefresh();
8209
8409
  ctx.effect?.(() => () => {
8210
8410
  defaultAttachCache.reset();
@@ -8249,7 +8449,7 @@ function apply(ctx, config = {}) {
8249
8449
  const last = getLastEgoActivity();
8250
8450
  if (!shouldReapBrowser(Date.now(), last, cfg.idleTimeoutMin)) return;
8251
8451
  if (last <= reapedFor) return;
8252
- if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
8452
+ if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND) {
8253
8453
  reapedFor = last;
8254
8454
  ctx.logger?.info?.("dsh-browser-cdp: idle reaper skipped: ego-cli owns the user's browser (never --stop it)");
8255
8455
  return;
@@ -8296,7 +8496,7 @@ function apply(ctx, config = {}) {
8296
8496
  }, "dsh-browser-cdp: idle reaper");
8297
8497
  ctx.effect?.(() => {
8298
8498
  try {
8299
- if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
8499
+ if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND) {
8300
8500
  ctx.logger?.info?.("dsh-browser-cdp: teardown skipped --stop: ego-cli owns the user's browser");
8301
8501
  return;
8302
8502
  }
@@ -8323,7 +8523,7 @@ function apply(ctx, config = {}) {
8323
8523
  function registerEgoStatus(ctx, cfg, reg, tiers) {
8324
8524
  reg(defineTool({
8325
8525
  name: "bcdp_status",
8326
- description: "Check whether the ego-browser CLI can actually run bcdp_* tools (probes the taskSpaces/browser/page facade over the nodejs channel). Use this first when other bcdp_* tools report \"CLI not found\".",
8526
+ description: "Drive the shared CDP browser (ego runtime): probe the CLI, and unlock the rest of the bcdp_* tools — under lazy injection only this tool is resident, so call it first for any browsing task (open a page, fill a form, screenshot, read, or attach your own Chrome/Edge over CDP). A bcdp_* tool missing from your list is sealed by tiering, not broken.",
8327
8527
  parameters: {},
8328
8528
  output: {
8329
8529
  schema: {
@@ -8354,11 +8554,11 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
8354
8554
  render: renderText
8355
8555
  },
8356
8556
  timeoutMs: 15e3,
8357
- execute: async () => {
8358
- tiers.pulse();
8557
+ execute: async (_args, exec) => {
8558
+ tiers.pulse(callingSessionId(exec));
8359
8559
  return withEgoLock(async () => {
8360
8560
  try {
8361
- const attach = defaultAttachCache.get();
8561
+ const { attach } = effectiveChannel(cfg);
8362
8562
  const handle = ctx.subprocess.spawn({
8363
8563
  argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
8364
8564
  cwd: process.cwd(),
@@ -8742,7 +8942,7 @@ function registerActionTools(ctx, cfg, reg) {
8742
8942
  }));
8743
8943
  reg(t({
8744
8944
  name: "bcdp_js",
8745
- description: "Evaluate a JavaScript expression in the current page and return its JSON-serializable value (e.g. \"document.title\", \"document.querySelectorAll('a').length\").",
8945
+ description: "Evaluate a JavaScript expression in the current page and return its JSON-serializable value (e.g. \"document.title\", \"document.querySelectorAll('a').length\"). One expression only; multi-step: use bcdp_script; raw protocol: use bcdp_cdp.",
8746
8946
  parameters: {
8747
8947
  expression: {
8748
8948
  type: "string",
@@ -8755,7 +8955,7 @@ function registerActionTools(ctx, cfg, reg) {
8755
8955
  }));
8756
8956
  reg(t({
8757
8957
  name: "bcdp_cdp",
8758
- description: "Issue a raw CDP command on the page target, e.g. cdp(\"Page.handleJavaScriptDialog\", { accept: true }).",
8958
+ description: "Issue a raw CDP command on the page target, e.g. cdp(\"Page.handleJavaScriptDialog\", { accept: true }). Prefer a structured tool when one exists; page JS belongs to bcdp_js.",
8759
8959
  parameters: {
8760
8960
  method: {
8761
8961
  type: "string",
@@ -9203,7 +9403,7 @@ function registerActionTools(ctx, cfg, reg) {
9203
9403
  }));
9204
9404
  reg(t({
9205
9405
  name: "bcdp_http",
9206
- description: "Make an HTTP request and return status + body. Default runs in the page's browser context; mode=server uses Node-side fetch.server (may crash on the vendored ego-linux Windows runtime, so prefer browser mode).",
9406
+ description: "Make an HTTP request and return status + body. Default runs in the page's browser context; mode=server uses Node-side fetch.server (may crash on the vendored ego-linux Windows runtime, so prefer browser mode). To render a page use bcdp_navigate; server mode is not bound by page CORS.",
9207
9407
  parameters: {
9208
9408
  url: {
9209
9409
  type: "string",
@@ -9311,7 +9511,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9311
9511
  }));
9312
9512
  reg(defineTool({
9313
9513
  name: "bcdp_help",
9314
- description: "Query the built-in ego-browser tool guide. `topic` may be a category (overview/tools/navigate/observe/input/keyboard-mouse/form/wait/network/login/script/doctor) or a specific tool name (e.g. bcdp_click). Returns the matching usage notes. Call this when unsure which eyebrow tool to use.",
9514
+ description: "Query the built-in ego-browser tool guide. `topic` may be a category (overview/tools/navigate/observe/input/keyboard-mouse/form/wait/network/login/script/doctor) or a specific tool name (e.g. bcdp_click). Returns the matching usage notes. Call this when unsure which eyebrow tool to use. If a bcdp_* tool is missing from your list, ask topic=injection.",
9315
9515
  parameters: { topic: {
9316
9516
  type: "string",
9317
9517
  description: "Category or tool name to look up; omitted/all returns the overview index."
@@ -9338,8 +9538,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9338
9538
  render: renderText
9339
9539
  },
9340
9540
  timeoutMs: 1e4,
9341
- execute: async (args) => {
9342
- tiers.pulse();
9541
+ execute: async (args, exec) => {
9542
+ tiers.pulse(callingSessionId(exec));
9343
9543
  const q = str(args.topic, "").trim().toLowerCase();
9344
9544
  const key = Object.prototype.hasOwnProperty.call(EGO_HELP_INDEX, q) ? q : "";
9345
9545
  const text = key ? EGO_HELP_INDEX[key] : q ? `未找�?topic "${q}"。可�? ` + Object.keys(EGO_HELP_INDEX).filter((k) => k !== "overview").join(", ") + "\n\noverview: " + EGO_HELP_INDEX.overview : EGO_HELP_INDEX.overview;
@@ -9378,8 +9578,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9378
9578
  render: renderText
9379
9579
  },
9380
9580
  timeoutMs: 25e3,
9381
- execute: async () => {
9382
- tiers.pulse();
9581
+ execute: async (_args, exec) => {
9582
+ tiers.pulse(callingSessionId(exec));
9383
9583
  const lines = [];
9384
9584
  {
9385
9585
  const s = tiers.surface();
@@ -9389,6 +9589,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9389
9589
  });
9390
9590
  lines.push(`tool injection: mode=${cfg.toolInjection} browse=${cfg.toolBrowse ? "open" : "sealed"} extended=${cfg.toolExtended ? "open" : "sealed"} escape=${cfg.toolEscape ? "open" : "sealed"} judge=${cfg.toolJudge ? "open" : "sealed"} judgeKey=${key ? "set" : "none"} active=${tiers.active() ? "yes" : "no"} �?live ${s.live.length} / sealed ${s.sealed.length}`);
9391
9591
  }
9592
+ lines.push(scopeProbeLine());
9392
9593
  lines.push(`egoBin: ${cfg.egoBin}`);
9393
9594
  try {
9394
9595
  lines.push(`egoBin exists: ${existsSync(cfg.egoBin)}`);
@@ -9403,6 +9604,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9403
9604
  const chrArgs = filterArgs(cfg.chromeArgs ?? "", CHROME_BLOCKED);
9404
9605
  lines.push(`runtimeArgs (effective): ${cliArgs.length ? cliArgs.join(" ") : "(none)"}`);
9405
9606
  const attachNow = defaultAttachCache.get();
9607
+ const channel = effectiveChannel(cfg);
9608
+ lines.push(`channel: ${channel.effective ? `${channel.effective.link.label} [${channel.effective.link.id}] (${channel.effective.reason}${channel.effective.demotedId ? `, over ${channel.effective.demotedId}` : ""})` : "(none — activate a link or enable one)"}`);
9406
9609
  lines.push(`remote CDP: ${cfg.remoteEnabled === false ? "DISABLED by switch (sequence preserved)" : "enabled"}`);
9407
9610
  lines.push(`attach: ${attachNow.status}${attachNow.endpointSource ? ` (source: ${attachNow.endpointSource})` : ""}${attachNow.endpoint ? ` @ ${attachNow.endpoint}` : ""}`);
9408
9611
  if (attachNow.engine !== void 0) lines.push(`engine: ${attachNow.engine}`);
@@ -9485,7 +9688,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9485
9688
  reg((() => {
9486
9689
  return defineTool({
9487
9690
  name: "bcdp_script",
9488
- description: "Run an arbitrary `ego-browser nodejs` heredoc script in ONE invocation (page/…locator/browser/taskSpaces/site/fetch/cdp preloaded), and return structured {ok, stdout, stderr, result, durationMs, timedOut}. Use for a full multi-step browser task as a single script. The task space is selected and a real (non-blank) tab activated for you before your script runs, so page.* works directly. Set verbatim:true to run the body verbatim with no preamble (the retired bcdp_cli behaviour). These scripts expose the vendored SDK (`taskSpaces`, `page.locator()`, global `cdp()`, `fetch.browser|server`) �?NOT the official docs' `taskSpace()` / `page.click()`.",
9691
+ description: "Run an arbitrary `ego-browser nodejs` heredoc script in ONE invocation (page/…locator/browser/taskSpaces/site/fetch/cdp preloaded), and return structured {ok, stdout, stderr, result, durationMs, timedOut}. Use for a full multi-step browser task as a single script. The task space is selected and a real (non-blank) tab activated for you before your script runs, so page.* works directly. Set verbatim:true to run the body verbatim with no preamble (the retired bcdp_cli behaviour). For a single page expression use bcdp_js. These scripts expose the vendored SDK (`taskSpaces`, `page.locator()`, global `cdp()`, `fetch.browser|server`) �?NOT the official docs' `taskSpace()` / `page.click()`.",
9489
9692
  parameters: {
9490
9693
  script: {
9491
9694
  type: "string",
@@ -9617,7 +9820,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9617
9820
  * must say so rather than failing later with a confusing worker error.
9618
9821
  */
9619
9822
  const effectsOf = (judge, onFrame) => {
9620
- const attach = defaultAttachCache.get();
9823
+ const { attach } = effectiveChannel(cfg);
9621
9824
  return makeJudgeEffects({
9622
9825
  subprocess: ctx.subprocess,
9623
9826
  workerPath: RENDER_WORKER_BIN,
@@ -9636,7 +9839,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9636
9839
  };
9637
9840
  /** The browser must be attached before any frame exists. Shared by 3 tools. */
9638
9841
  const attachGate = () => {
9639
- const attach = defaultAttachCache.get();
9842
+ const { attach } = effectiveChannel(cfg);
9640
9843
  if (attach.wsUrl === "") return `no live browser: the activated link has no CDP endpoint yet. Run bcdp_status (or bcdp_doctor) to attach, then retry. (attach status=${attach.status}${attach.code === "" ? "" : `, code=${attach.code}`})`;
9641
9844
  return "";
9642
9845
  };
@@ -9667,7 +9870,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9667
9870
  markEgoToolCall(callingSessionId(exec));
9668
9871
  const judge = judgeCfg();
9669
9872
  const runtime = judgeRuntimeOf();
9670
- const attach = defaultAttachCache.get();
9873
+ const { attach } = effectiveChannel(cfg);
9671
9874
  const lines = [
9672
9875
  "judgement chain (priority order):",
9673
9876
  ...describeJudge(runtime),
@@ -10177,4 +10380,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10177
10380
  }
10178
10381
 
10179
10382
  //#endregion
10180
- export { ATTACH_SESSION_HINT, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
10383
+ 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, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-browser-cdp",
3
- "version": "1.6.2",
3
+ "version": "1.7.1-rc.5",
4
4
  "description": "dsh-browser-cdp: DSH browser plugin — attach to a running Chrome/Edge over CDP (no bundled browser needed); structured browser-automation tools (30+ bcdp_*) that drive the vendored ego runtime through ctx.subprocess, plus a realtime watch panel (live SSE screencast + direct mouse interaction + download capture + human-verification notice). Web shell: floating watch panel without dsh-better-sidebar, sidebar tab with it. Headless/TUI hosts: tools-only. [DSH 0.1.7-rc.1 ~ 0.2.1-rc.1 line (exact rc enumeration): declarative settings via Config .volatile() fields; for DSH 0.1.2-rc.1 ~ 0.1.5-rc.3 use the 0.17.x line]",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -104,6 +104,6 @@
104
104
  },
105
105
  "publishConfig": {
106
106
  "registry": "https://registry.npmjs.org",
107
- "tag": "dsh-1.1.0"
107
+ "tag": "dsh-0.2.1-rc.3"
108
108
  }
109
109
  }