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

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.3",
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
@@ -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
  },
package/lib/index.js CHANGED
@@ -1853,7 +1853,7 @@ function markEgoToolCall(sessionId) {
1853
1853
  toolCallCount += 1;
1854
1854
  lastEgoActivity = Date.now();
1855
1855
  for (const cb of [...activityListeners]) try {
1856
- cb();
1856
+ cb(sessionId);
1857
1857
  } catch {}
1858
1858
  const payload = sessionId === void 0 || sessionId === "" ? { count: toolCallCount } : {
1859
1859
  count: toolCallCount,
@@ -2725,11 +2725,12 @@ const Config$1 = z.object({
2725
2725
  cursorName: z.string().description("Name label shown in the cursor HUD."),
2726
2726
  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
2727
  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(),
2728
+ 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(),
2729
+ 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
2730
  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(),
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). Sealed until browser activity like every other non-core tier: call bcdp_status first, then it appears. Off = sealed.").volatile(),
2732
2732
  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(),
2733
+ 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
2734
  localHeadless: z.boolean().description("Run the locally launched browser headless."),
2734
2735
  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
2736
  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 +3000,7 @@ function resolveConfig(config = {}) {
2999
3000
  toolExtended: tierOpenByDefault(config.toolExtended),
3000
3001
  toolEscape: tierOpenByDefault(config.toolEscape),
3001
3002
  toolJudge: tierOpenByDefault(config.toolJudge),
3003
+ sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
3002
3004
  localHeadless: config.localHeadless === void 0 ? false : Boolean(config.localHeadless),
3003
3005
  localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
3004
3006
  lightpandaArgs: trimmed(config.lightpandaArgs),
@@ -3245,7 +3247,7 @@ function envelopeError(code, message) {
3245
3247
  * add/change a tool, remember to sync an entry here or bcdp_help won't find it.
3246
3248
  */
3247
3249
  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` 查询,或直接给工具名。",
3250
+ 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
3251
  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
3252
  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
3253
  navigate: "bcdp_navigate: 打开URL或切tab(同任务复用当前tab)。bcdp_wait op=url: 等跳转(登录/分页)。",
@@ -3260,7 +3262,7 @@ const EGO_HELP_INDEX = {
3260
3262
  login: "bcdp_auth_flush: 把登录cookie落盘到ego profile; 观察窗登录引导条+『已登录,保存』按钮触发同一动作。bcdp_login_import: 从系统浏览器(Chrome/Edge/Brave)按域名导入登录cookie(source/domains/dryRun; 先dryRun看可导入项; ego浏览器须已在运行)。",
3261
3263
  script: "bcdp_script: 原样运行任意内置运行时 heredoc 脚本(page/browser/taskSpaces/site/fetch/cdp预载)。默认加 preamble(选区+激活真实 tab)并额外返回 duration/timedOut; verbatim:true 则完全原样、无 preamble(原 bcdp_cli 行为, 需自行 taskSpaces.useOrCreate)。",
3262
3264
  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(两者也算浏览器活动,会把面铺开),或让用户在设置页「工具封印」里打开对应档位的开关;别猜测不存在的工具名。",
3265
+ 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
3266
  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
3267
  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
3268
  };
@@ -3565,15 +3567,10 @@ function registerSettingsBridge(wctx, ctx) {
3565
3567
 
3566
3568
  //#endregion
3567
3569
  //#region src/toolTiers.ts
3568
- const CORE = [
3569
- "bcdp_status",
3570
- "bcdp_doctor",
3571
- "bcdp_help",
3570
+ const CORE = ["bcdp_status"];
3571
+ const ACT = [
3572
3572
  "bcdp_space",
3573
3573
  "bcdp_navigate",
3574
- "bcdp_snapshot"
3575
- ];
3576
- const ACT = [
3577
3574
  "bcdp_click",
3578
3575
  "bcdp_fill",
3579
3576
  "bcdp_key",
@@ -3582,13 +3579,16 @@ const ACT = [
3582
3579
  "bcdp_select",
3583
3580
  "bcdp_check",
3584
3581
  "bcdp_drag",
3585
- "bcdp_tab"
3582
+ "bcdp_tab",
3583
+ "bcdp_help",
3584
+ "bcdp_doctor"
3586
3585
  ];
3587
3586
  const OBSERVE = [
3588
3587
  "bcdp_screenshot",
3589
3588
  "bcdp_page_info",
3590
3589
  "bcdp_read_element",
3591
- "bcdp_js"
3590
+ "bcdp_js",
3591
+ "bcdp_snapshot"
3592
3592
  ];
3593
3593
  const WAIT = ["bcdp_wait"];
3594
3594
  const POWER = [
@@ -3622,6 +3622,17 @@ const TIER_OF_TOOL = new Map([
3622
3622
  ["escape", ESCAPE],
3623
3623
  ["judge", JUDGE]
3624
3624
  ].flatMap(([tier, names]) => names.map((n) => [n, tier])));
3625
+ /** 分级成员表(测试与文档用)。 */
3626
+ const TIER_MEMBERS = {
3627
+ core: CORE,
3628
+ act: ACT,
3629
+ observe: OBSERVE,
3630
+ wait: WAIT,
3631
+ power: POWER,
3632
+ session: SESSION,
3633
+ escape: ESCAPE,
3634
+ judge: JUDGE
3635
+ };
3625
3636
  /** 去掉 `bcdp_`/`ego_` 前缀后的裸名,便于策略表保持前缀无关。 */
3626
3637
  const bareToolName = (name$1) => name$1.replace(/^(?:bcdp|ego)_/, "");
3627
3638
  /** 批次放行顺序(索引即 rank)。 */
@@ -3671,14 +3682,18 @@ const tierOpen = (tier, p) => {
3671
3682
  * ③ 活动闸:`lazy` 下非 core 级要等活动,`always` 下不设时机闸;
3672
3683
  * ④ 批次闸:只在 act/observe/wait 三批上按 batchDepth 递增放行。
3673
3684
  *
3674
- * `escape` 是唯一的例外:它不吃③。逃生舱必须在模型手里始终可达——否则遇到
3675
- * 「结构化工具没覆盖」的情形时,模型既调不动它、也没法用别的工具绕过。
3685
+ * depth=0 时连 act 也被封,所以唯一常驻的 `bcdp_status` 必须既置 active 又推进
3686
+ * depth,否则 lazy 模式下没有任何解锁路径(决策与收益见
3687
+ * `.agents/plans/bcdp-core-narrowing/`)。
3688
+ *
3689
+ * `escape` 的「不吃③」豁免已移除:现在它与其它非 core 批同样等活动。豁免时期的
3690
+ * 理由是「结构化工具没覆盖时手里没逃生手段」,而现在该手段需要先调 `bcdp_status`
3691
+ * 才能拿到——代价是 ≈1,620 字符/轮,换为常驻面收窄的主要一块。
3676
3692
  */
3677
3693
  function tierAllowed(tier, p) {
3678
3694
  if (tier === "core") return true;
3679
3695
  if (!tierOpen(tier, p)) return false;
3680
3696
  if (tier === "judge" && !p.judgeConfigured) return false;
3681
- if (tier === "escape") return true;
3682
3697
  if (p.injection === "always") return true;
3683
3698
  if (tier === "act" || tier === "observe" || tier === "wait") {
3684
3699
  if (!p.active) return false;
@@ -7547,6 +7562,9 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
7547
7562
  cfg.spaceTracker.resetToName();
7548
7563
  result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
7549
7564
  }
7565
+ if (!result.ok && CDP_CONNECT_FAIL_RE.test(result.error ?? "")) {
7566
+ if (await cfg.refreshAttach?.() === true) result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
7567
+ }
7550
7568
  return result;
7551
7569
  }
7552
7570
  /**
@@ -7562,6 +7580,13 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
7562
7580
  * @internal exported for tests
7563
7581
  */
7564
7582
  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;
7583
+ /**
7584
+ * A dead cached ws (the browser was relaunched behind the SAME endpoint) surfaces
7585
+ * as this one runtime message — see `runtime/ego-linux/src/transport.mjs`. It is
7586
+ * deliberately NOT folded into `TAB_STUCK_RE`: the fix is a re-probe of the link,
7587
+ * not a tab swap, so the two recoveries must stay distinguishable.
7588
+ */
7589
+ const CDP_CONNECT_FAIL_RE = /failed to connect to CDP endpoint/i;
7565
7590
  /** True when a failed run looks like a wedged/absent tab rather than a cold start. */
7566
7591
  function isTabStuckFailure(result) {
7567
7592
  const hay = `${result.error ?? ""}\n${result.stderr ?? ""}`;
@@ -7786,21 +7811,32 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7786
7811
  stdout,
7787
7812
  stderr
7788
7813
  };
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)}`,
7814
+ return {
7815
+ ok: true,
7816
+ value: parseSentinel(mergeCliOutput({
7817
+ stdout,
7818
+ stderr
7819
+ })),
7796
7820
  stdout,
7797
7821
  stderr
7798
7822
  };
7823
+ }
7824
+ /** How much raw stdout a tool may hand back when a script emitted no JSON. */
7825
+ const TOOL_RAW_STDOUT_MAX = 4e3;
7826
+ /**
7827
+ * The payload a bcdp_* tool returns for a successful run.
7828
+ *
7829
+ * Dropping `undefined` straight into the tool result would show the model an
7830
+ * empty outcome for a script that actually ran, so fall back to the (bounded)
7831
+ * raw stdout plus a note naming the reason. Structured tools always emit a
7832
+ * sentinel payload and never take this branch.
7833
+ */
7834
+ function toolPayload(result) {
7835
+ if (result.value !== void 0) return result.value;
7799
7836
  return {
7800
7837
  ok: true,
7801
- value,
7802
- stdout,
7803
- stderr
7838
+ stdout: (result.stdout ?? "").trim().slice(0, TOOL_RAW_STDOUT_MAX),
7839
+ note: "no JSON payload on stdout; raw output returned"
7804
7840
  };
7805
7841
  }
7806
7842
  /** JS snippet that pins an action tool to one task space. */
@@ -7883,12 +7919,12 @@ function defineEgoTool(ctx, cfg, opts) {
7883
7919
  if (!result$1.ok) throw new Error(recoveredFrom ? `${result$1.error}\n${recoveredFrom}` : result$1.error);
7884
7920
  if (result$1.value && typeof result$1.value === "object") result$1.value.recoveredFrom = recoveredFrom;
7885
7921
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result$1.value);
7886
- return result$1.value;
7922
+ return toolPayload(result$1);
7887
7923
  }
7888
7924
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => opts.buildScript(args));
7889
7925
  if (!result.ok) throw new Error(result.error);
7890
7926
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result.value);
7891
- return result.value;
7927
+ return toolPayload(result);
7892
7928
  }),
7893
7929
  presentCall: () => ({
7894
7930
  card: "generic",
@@ -7898,7 +7934,54 @@ function defineEgoTool(ctx, cfg, opts) {
7898
7934
  })
7899
7935
  });
7900
7936
  }
7937
+ const scopeProbe = {
7938
+ restrictType: "n/a",
7939
+ onType: "n/a",
7940
+ agentsSvc: "n/a",
7941
+ agentCount: -1,
7942
+ createdEvents: 0,
7943
+ agentHasCtx: "n/a",
7944
+ agentCtxRestrict: "n/a",
7945
+ agentCtxTools: "n/a",
7946
+ error: ""
7947
+ };
7948
+ /** Inspect one agent handle (host-side shape varies) and remember what we reached. */
7949
+ function probeAgent(agent) {
7950
+ if (agent == null) return;
7951
+ scopeProbe.agentHasCtx = String(agent.ctx != null);
7952
+ scopeProbe.agentCtxTools = typeof agent?.ctx?.tools;
7953
+ scopeProbe.agentCtxRestrict = typeof agent?.ctx?.tools?.restrict;
7954
+ }
7955
+ /** Install the probe once per mount: capability types + live agent enumeration + lifecycle event. */
7956
+ function installScopeProbe(ctx) {
7957
+ try {
7958
+ const anyCtx = ctx;
7959
+ scopeProbe.restrictType = typeof anyCtx?.tools?.restrict;
7960
+ scopeProbe.onType = typeof anyCtx?.on;
7961
+ const agents = typeof anyCtx.get === "function" ? anyCtx.get("agents") : void 0;
7962
+ scopeProbe.agentsSvc = agents == null ? "absent" : "present";
7963
+ if (agents != null) {
7964
+ const list = typeof agents.roots === "function" ? agents.roots() : typeof agents.list === "function" ? agents.list() : [];
7965
+ scopeProbe.agentCount = Array.isArray(list) ? list.length : -2;
7966
+ probeAgent(Array.isArray(list) ? list[0] : void 0);
7967
+ }
7968
+ if (scopeProbe.onType === "function") {
7969
+ const off = anyCtx.on("agent/created", (payload) => {
7970
+ scopeProbe.createdEvents += 1;
7971
+ probeAgent(payload?.agent ?? payload);
7972
+ });
7973
+ ctx.effect?.(() => typeof off === "function" ? off : () => void 0);
7974
+ }
7975
+ } catch (err) {
7976
+ scopeProbe.error = err instanceof Error ? err.message.slice(0, 120) : String(err).slice(0, 120);
7977
+ }
7978
+ }
7979
+ /** One-line render for the doctor report. */
7980
+ function scopeProbeLine() {
7981
+ 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}` : "");
7982
+ }
7901
7983
  function apply(ctx, config = {}) {
7984
+ installScopeProbe(ctx);
7902
7985
  const bridge = installSettingsAuto(ctx, config);
7903
7986
  const ffmpegManager = getSharedFfmpegInstallationManager();
7904
7987
  const initialFfmpegConfig = resolveConfig(bridge.source());
@@ -7907,7 +7990,9 @@ function apply(ctx, config = {}) {
7907
7990
  requestedEncoder: initialFfmpegConfig.ffmpegEncoder
7908
7991
  }).catch(() => {});
7909
7992
  const spaceTracker = createSessionSpaceTracker((sessionKey) => deriveSlotDefaultName(resolveConfig(bridge.source()), sessionKey));
7993
+ let triggerCdpRef;
7910
7994
  const cfg = {
7995
+ refreshAttach: () => triggerCdpRef?.() ?? Promise.resolve(false),
7911
7996
  egoBin: typeof config.egoBin === "string" && config.egoBin !== "" ? config.egoBin : DEFAULT_EGO_BIN,
7912
7997
  get configuredDefaultSpace() {
7913
7998
  return resolveConfig(bridge.source()).defaultSpace;
@@ -7987,6 +8072,9 @@ function apply(ctx, config = {}) {
7987
8072
  get toolJudge() {
7988
8073
  return resolveConfig(bridge.source()).toolJudge;
7989
8074
  },
8075
+ get sessionScopedPulse() {
8076
+ return resolveConfig(bridge.source()).sessionScopedPulse;
8077
+ },
7990
8078
  get links() {
7991
8079
  return resolveConfig(bridge.source()).links;
7992
8080
  },
@@ -8079,7 +8167,14 @@ function apply(ctx, config = {}) {
8079
8167
  }
8080
8168
  };
8081
8169
  let browserActive = false;
8170
+ const sessionDepth = /* @__PURE__ */ new Map();
8082
8171
  let browseBatchDepth = 0;
8172
+ /** Compute max depth from all tracked sessions, or 0 if none. */
8173
+ const maxSessionDepth = () => {
8174
+ let m = 0;
8175
+ for (const d of sessionDepth.values()) if (d > m) m = d;
8176
+ return m;
8177
+ };
8083
8178
  const tiers = createTierInjector({
8084
8179
  register: (tool) => {
8085
8180
  const dispose = ctx.tools.register(tool);
@@ -8102,29 +8197,69 @@ function apply(ctx, config = {}) {
8102
8197
  logger: ctx.logger
8103
8198
  });
8104
8199
  /**
8105
- * 活动信号:每�?bcdp_* 调用推进 browse 批次(act �?observe �?wait),
8106
- * 到顶即止。只有注入面真的变了�?reapply�? */
8107
- const pulseActivity = () => {
8200
+ * Apply per-session restrict to hide globally-registered tools that exceed
8201
+ * the calling agent's own depth. Best-effort: silently no-ops when the host
8202
+ * does not expose agent-scoped restriction (plugin fiber is not an agent scope).
8203
+ */
8204
+ const tryRestrictSession = (sessionId) => {
8205
+ if (!cfg.sessionScopedPulse || !sessionId) return;
8206
+ try {
8207
+ const depth = sessionDepth.get(sessionId) ?? 0;
8208
+ const allowed = /* @__PURE__ */ new Set();
8209
+ for (const n of TIER_MEMBERS.core) allowed.add(n);
8210
+ const pol = {
8211
+ injection: cfg.toolInjection,
8212
+ toolBrowse: cfg.toolBrowse,
8213
+ toolExtended: cfg.toolExtended,
8214
+ toolEscape: cfg.toolEscape,
8215
+ toolJudge: cfg.toolJudge,
8216
+ judgeConfigured: judgeConfigured({
8217
+ jevKey: cfg.jevKey,
8218
+ layaKey: cfg.layaKey
8219
+ }),
8220
+ active: depth > 0,
8221
+ batchDepth: depth
8222
+ };
8223
+ for (const name$1 of tiers.surface().live) if (toolAllowed(name$1, pol)) allowed.add(name$1);
8224
+ const restrictFn = ctx.tools.restrict;
8225
+ if (typeof restrictFn === "function") restrictFn({ allow: [...allowed] });
8226
+ } catch {}
8227
+ };
8228
+ /**
8229
+ * Activity pulse: advance browse batch depth. When sessionScopedPulse is ON
8230
+ * and a sessionId is given, only that session's depth advances; the global
8231
+ * depth = max across sessions drives tier registration. Without restrict
8232
+ * support the effect is still beneficial for per-session sealAfterReap.
8233
+ */
8234
+ const pulseActivity = (sessionId) => {
8108
8235
  const before = browseBatchDepth;
8109
8236
  browserActive = true;
8110
- browseBatchDepth = Math.min(BATCH_ORDER.length, browseBatchDepth + 1);
8237
+ if (cfg.sessionScopedPulse && sessionId) {
8238
+ const cur = Math.min(BATCH_ORDER.length, (sessionDepth.get(sessionId) ?? 0) + 1);
8239
+ sessionDepth.set(sessionId, cur);
8240
+ browseBatchDepth = Math.max(browseBatchDepth, maxSessionDepth());
8241
+ } else browseBatchDepth = Math.min(BATCH_ORDER.length, browseBatchDepth + 1);
8111
8242
  if (before !== browseBatchDepth) tiers.reapply();
8243
+ if (cfg.sessionScopedPulse && sessionId) tryRestrictSession(sessionId);
8112
8244
  };
8113
8245
  {
8114
8246
  const offActivity = onEgoActivity(pulseActivity);
8115
8247
  ctx.effect?.(() => offActivity);
8116
8248
  }
8117
8249
  /**
8118
- * 闲置回收后把注入面收�?core 级(lazy 模式专属):浏览器已经停了,模型
8119
- * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开�? */
8250
+ * Seal: idle reaper resets depths. With sessionScopedPulse, only sessions
8251
+ * whose last activity exceeded the timeout are sealed; when ALL are idle the
8252
+ * global depth drops to 0 (same observable behaviour as before).
8253
+ */
8120
8254
  const sealAfterReap = () => {
8121
8255
  if (cfg.toolInjection !== "lazy" || !browserActive) return;
8256
+ if (cfg.sessionScopedPulse && sessionDepth.size > 0) {
8257
+ sessionDepth.clear();
8258
+ browseBatchDepth = 0;
8259
+ } else browseBatchDepth = 0;
8122
8260
  browserActive = false;
8123
- browseBatchDepth = 0;
8124
8261
  tiers.reapply();
8125
8262
  };
8126
- /**
8127
- * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动�? * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)�? */
8128
8263
  const tierView = {
8129
8264
  pulse: pulseActivity,
8130
8265
  active: () => browserActive,
@@ -8162,12 +8297,17 @@ function apply(ctx, config = {}) {
8162
8297
  const triggerCdpRefresh = (() => {
8163
8298
  let inFlight = false;
8164
8299
  let pending = false;
8300
+ /** Last ws handed to the worker; a differ means the browser was relaunched. */
8301
+ let lastAttachWs = null;
8302
+ /** True when this pass actually moved the resolved endpoint. */
8303
+ let changed = false;
8165
8304
  const run = async () => {
8166
8305
  if (inFlight) {
8167
8306
  pending = true;
8168
- return;
8307
+ return changed;
8169
8308
  }
8170
8309
  inFlight = true;
8310
+ changed = false;
8171
8311
  try {
8172
8312
  const resolved = resolveConfig(bridge.source());
8173
8313
  const attach = await refreshAttach({
@@ -8191,7 +8331,12 @@ function apply(ctx, config = {}) {
8191
8331
  sdkPath: fileURLToPath(new URL("../runtime/ego-browser/dist/out/index.js", import.meta.url)),
8192
8332
  bundledCli: VENDORED_EGO_BIN
8193
8333
  });
8194
- if (setAttachEndpoint(attach.status === "ready" && attach.wsUrl !== "" ? attach.wsUrl : null, attach.status === "ready" ? attach.engine ?? "unknown" : null)) recycleWorker("cdp activation change").catch(() => null);
8334
+ const ws = attach.status === "ready" && attach.wsUrl !== "" ? attach.wsUrl : null;
8335
+ if (ws !== null && ws !== lastAttachWs) lastAttachWs = ws;
8336
+ if (setAttachEndpoint(ws, attach.status === "ready" ? attach.engine ?? "unknown" : null)) {
8337
+ changed = true;
8338
+ recycleWorker("cdp activation change").catch(() => null);
8339
+ }
8195
8340
  } catch {} finally {
8196
8341
  inFlight = false;
8197
8342
  if (pending) {
@@ -8199,12 +8344,12 @@ function apply(ctx, config = {}) {
8199
8344
  run();
8200
8345
  }
8201
8346
  }
8347
+ return changed;
8202
8348
  };
8203
- return () => {
8204
- run();
8205
- };
8349
+ return () => run();
8206
8350
  })();
8207
- bridge.onChange(triggerCdpRefresh);
8351
+ triggerCdpRef = triggerCdpRefresh;
8352
+ bridge.onChange(() => void triggerCdpRefresh());
8208
8353
  triggerCdpRefresh();
8209
8354
  ctx.effect?.(() => () => {
8210
8355
  defaultAttachCache.reset();
@@ -8323,7 +8468,7 @@ function apply(ctx, config = {}) {
8323
8468
  function registerEgoStatus(ctx, cfg, reg, tiers) {
8324
8469
  reg(defineTool({
8325
8470
  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\".",
8471
+ 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
8472
  parameters: {},
8328
8473
  output: {
8329
8474
  schema: {
@@ -8354,8 +8499,8 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
8354
8499
  render: renderText
8355
8500
  },
8356
8501
  timeoutMs: 15e3,
8357
- execute: async () => {
8358
- tiers.pulse();
8502
+ execute: async (_args, exec) => {
8503
+ tiers.pulse(callingSessionId(exec));
8359
8504
  return withEgoLock(async () => {
8360
8505
  try {
8361
8506
  const attach = defaultAttachCache.get();
@@ -8742,7 +8887,7 @@ function registerActionTools(ctx, cfg, reg) {
8742
8887
  }));
8743
8888
  reg(t({
8744
8889
  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\").",
8890
+ 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
8891
  parameters: {
8747
8892
  expression: {
8748
8893
  type: "string",
@@ -8755,7 +8900,7 @@ function registerActionTools(ctx, cfg, reg) {
8755
8900
  }));
8756
8901
  reg(t({
8757
8902
  name: "bcdp_cdp",
8758
- description: "Issue a raw CDP command on the page target, e.g. cdp(\"Page.handleJavaScriptDialog\", { accept: true }).",
8903
+ 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
8904
  parameters: {
8760
8905
  method: {
8761
8906
  type: "string",
@@ -9203,7 +9348,7 @@ function registerActionTools(ctx, cfg, reg) {
9203
9348
  }));
9204
9349
  reg(t({
9205
9350
  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).",
9351
+ 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
9352
  parameters: {
9208
9353
  url: {
9209
9354
  type: "string",
@@ -9311,7 +9456,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9311
9456
  }));
9312
9457
  reg(defineTool({
9313
9458
  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.",
9459
+ 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
9460
  parameters: { topic: {
9316
9461
  type: "string",
9317
9462
  description: "Category or tool name to look up; omitted/all returns the overview index."
@@ -9338,8 +9483,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9338
9483
  render: renderText
9339
9484
  },
9340
9485
  timeoutMs: 1e4,
9341
- execute: async (args) => {
9342
- tiers.pulse();
9486
+ execute: async (args, exec) => {
9487
+ tiers.pulse(callingSessionId(exec));
9343
9488
  const q = str(args.topic, "").trim().toLowerCase();
9344
9489
  const key = Object.prototype.hasOwnProperty.call(EGO_HELP_INDEX, q) ? q : "";
9345
9490
  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 +9523,8 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9378
9523
  render: renderText
9379
9524
  },
9380
9525
  timeoutMs: 25e3,
9381
- execute: async () => {
9382
- tiers.pulse();
9526
+ execute: async (_args, exec) => {
9527
+ tiers.pulse(callingSessionId(exec));
9383
9528
  const lines = [];
9384
9529
  {
9385
9530
  const s = tiers.surface();
@@ -9389,6 +9534,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9389
9534
  });
9390
9535
  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
9536
  }
9537
+ lines.push(scopeProbeLine());
9392
9538
  lines.push(`egoBin: ${cfg.egoBin}`);
9393
9539
  try {
9394
9540
  lines.push(`egoBin exists: ${existsSync(cfg.egoBin)}`);
@@ -9485,7 +9631,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9485
9631
  reg((() => {
9486
9632
  return defineTool({
9487
9633
  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()`.",
9634
+ 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
9635
  parameters: {
9490
9636
  script: {
9491
9637
  type: "string",
@@ -10177,4 +10323,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10177
10323
  }
10178
10324
 
10179
10325
  //#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 };
10326
+ 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, 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.3",
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",