dsh-browser-cdp 1.3.2 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -2606,6 +2606,8 @@ const cdpMode = z.union([
2606
2606
  "remote"
2607
2607
  ]);
2608
2608
  const toolInjection = z.union(["lazy", "always"]);
2609
+ const DEFAULT_SPACE = "default";
2610
+ const AUTO_SPACE_SENTINEL = ":auto";
2609
2611
  const encoder = z.union([
2610
2612
  "auto",
2611
2613
  "software",
@@ -2618,6 +2620,7 @@ const encoder = z.union([
2618
2620
  ]);
2619
2621
  const Config$1 = z.object({
2620
2622
  isolateSpaces: z.boolean().description("Space isolation: false = persistent profile (keep logins across restarts); true = isolated sandbox.").volatile(),
2623
+ defaultSpace: z.string().description("Default task-space name when a bcdp_* call omits `space`. Persistent-profile mode reuses this single named slot — set it to the same value across sessions to share login state. Set `:auto` in isolated-sandbox mode to derive a per-session name (dsh-agent-<sessionId8>). Leave default (\"default\") unless you are running multiple agents in parallel.").volatile(),
2621
2624
  idleTimeoutMin: z.number().min(0).max(1440).step(1).description("Auto-stop the backing browser after N minutes without an bcdp_* call (0 = off). Relaunches on demand at the next call.").volatile(),
2622
2625
  chromePath: z.string().description("Path to Chrome/Chromium. Empty = auto-detect.").volatile(),
2623
2626
  captureBackend: backend.description("Capture backend: auto, cdp, or ffmpeg.").volatile(),
@@ -2964,6 +2967,7 @@ function resolveConfig(config = {}) {
2964
2967
  runtimeArgs: typeof config.runtimeArgs === "string" ? config.runtimeArgs : typeof config.egoCliArgs === "string" ? config.egoCliArgs : "",
2965
2968
  chromeArgs: typeof config.chromeArgs === "string" ? config.chromeArgs : "",
2966
2969
  isolateSpaces: typeof config.isolateSpaces === "boolean" ? config.isolateSpaces : config.isolateSpaces === "true" || config.isolateSpaces === "1" || config.isolateSpaces === 1,
2970
+ defaultSpace: typeof config.defaultSpace === "string" && config.defaultSpace.trim() !== "" ? config.defaultSpace.trim() : "default",
2967
2971
  idleTimeoutMin: finiteIn(config.idleTimeoutMin, 0, 1440) ? config.idleTimeoutMin : 0,
2968
2972
  links: sanitizeLinks(config.links ?? config.cdpTargets).links.map(normalizeProbeState),
2969
2973
  activeTargetId: typeof config.activeTargetId === "string" ? config.activeTargetId : "",
@@ -3228,7 +3232,7 @@ function envelopeError(code, message) {
3228
3232
  */
3229
3233
  const EGO_HELP_INDEX = {
3230
3234
  overview: "CDP 浏览器代理:结构化浏览器工具。导航/交互/观察/表单/网络/等待/键鼠皆有专项工具,另提供 bcdp_help(本索引)、bcdp_doctor(体检)、bcdp_cli/bcdp_script(自由脚本逃生舱)。连接与激活见 topic=links。分类见: tools / navigate / observe / input / keyboard-mouse / form / wait / network / login / script / doctor / lightpanda / injection。用 `topic` 查询,或直接给工具名。",
3231
- tools: "工具清单: bcdp_status, bcdp_space_open, bcdp_space_close, bcdp_snapshot, bcdp_navigate, bcdp_click(+double), bcdp_fill, bcdp_js, bcdp_cdp, bcdp_screenshot(+selector), bcdp_page_info, bcdp_wait, bcdp_wait_for_selector, bcdp_wait_for_url, bcdp_wait_for_response, bcdp_key(+text/type), 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_cli, bcdp_script, bcdp_jev_status, bcdp_jev_frame, bcdp_jev_attempt, bcdp_jev_ask, bcdp_jev_run。",
3235
+ tools: "工具清单: bcdp_status, bcdp_space_open, bcdp_space, bcdp_space_close, bcdp_snapshot, bcdp_navigate, bcdp_tab, bcdp_click(+double), bcdp_fill, bcdp_js, bcdp_cdp, bcdp_screenshot(+selector), bcdp_page_info, bcdp_wait, bcdp_wait_page, bcdp_wait_for_selector, bcdp_wait_for_url, bcdp_wait_for_response, 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_cli, bcdp_script, bcdp_jev_status, bcdp_jev_frame, bcdp_jev_attempt, bcdp_jev_ask, bcdp_jev_run。",
3232
3236
  links: "连接序列(设置面板):有序列表,顺序即优先级,被激活的一项驱动每一次 bcdp_* 调用。两种类型——CDP 端点(注入 EGO_LINUX_CDP_URL,指向已开调试端口的浏览器)与 本机 ego CLI(不注入端点,由本机 ego CLI 直接驱动 ego-lite 浏览器;仅限本机,全局至多一条)。cdpMode: auto=按激活项;remote=仅接受 CDP 端点;local=受管本地启动器。cdpMode=remote 与「本机 ego CLI」组合会显式报 mode-kind-mismatch。remoteEnabled 只管远端 CDP,不影响本机 CLI 连接。",
3233
3237
  navigate: "bcdp_navigate: 打开URL或切tab(同任务复用当前tab)。bcdp_wait_for_url: 等跳转(登录/分页)。",
3234
3238
  observe: "bcdp_snapshot: 整页语义树(带[ref]/loc供点击); bcdp_page_info: url/标题/视口/滚动/对话框/人机验证; bcdp_read_element: 读单元素文本/HTML/值/属性/可见性/计数; bcdp_screenshot(+selector): 整页或元素截图。",
@@ -3242,7 +3246,7 @@ const EGO_HELP_INDEX = {
3242
3246
  login: "bcdp_auth_flush: 把登录cookie落盘到ego profile; 观察窗登录引导条+『已登录,保存』按钮触发同一动作。bcdp_login_import: 从系统浏览器(Chrome/Edge/Brave)按域名导入登录cookie(source/domains/dryRun; 先dryRun看可导入项; ego浏览器须已在运行)。",
3243
3247
  script: "bcdp_cli / bcdp_script: 原样运行任意内置运行时 heredoc 脚本(page/browser/taskSpaces/site/fetch/cdp预载)。bcdp_script额外返回 duration/timedOut。",
3244
3248
  doctor: "bcdp_doctor: 体检环境(浏览器候选、vendored runtime、状态目录、CDP端口、任务空间、引擎与降级清单);首行附工具注入面快照。",
3245
- injection: "工具分级注入(不是工具,是出现时机):38 个 bcdp_* 分八批——core(status/doctor/help/space_open/space_close/navigate/snapshot,常驻不可封印)/ act(点击填写键鼠拖拽)/ observe(截图页面信息读取js)/ wait(等待类)/ power(裸CDP/HTTP/上传/下载/对话框)/ session(验证码/登录落盘/登录导入)/ escape(cli/script 逃生舱)/ judge(bcdp_jev_*)。设置旋钮(全 volatile):toolInjection = lazy(默认,常驻 core + escape,首次 bcdp_* 调用后铺开其余)/ always(挂载即全量,历史行为);toolBrowse(act+observe+wait,内部按 act→observe→wait 三波放行)/ toolExtended(power+session)/ toolEscape(cli+script)/ toolJudge 四把开关——开 = 开放注册,关 = 该批从工具列表移除(core 级不给开关,封了就没解锁入口);judge 级即使开了仍需配 JEV/Laya Key。**escape 批不吃活动闸**:cli/script 是唯一的「一次调用干完任意多步任务」的入口,必须始终可达,不排在首次活动之后。封印 = 从工具列表里反注册,不是执行期报错;lazy 下闲置回收会把扩展面收回。**若某个 bcdp_* 工具不在你的工具列表里**:它被分级封印了——先跑 bcdp_status 或 bcdp_doctor(两者也算浏览器活动,会把面铺开),或让用户在设置页「工具封印」里打开对应档位的开关;别猜测不存在的工具名。",
3249
+ injection: "工具分级注入(不是工具,是出现时机):41 个 bcdp_* 分八批——core(status/doctor/help/space_open/space_close/space/navigate/snapshot,常驻不可封印)/ act(点击填写键鼠拖拽+tab 标签管理)/ observe(截图页面信息读取js)/ wait(等待类+wait_page 页面级等待)/ power(裸CDP/HTTP/上传/下载/对话框)/ session(验证码/登录落盘/登录导入)/ escape(cli/script 逃生舱)/ judge(bcdp_jev_*)。设置旋钮(全 volatile):toolInjection = lazy(默认,常驻 core + escape,首次 bcdp_* 调用后铺开其余)/ always(挂载即全量,历史行为);toolBrowse(act+observe+wait,内部按 act→observe→wait 三波放行)/ toolExtended(power+session)/ toolEscape(cli+script)/ toolJudge 四把开关——开 = 开放注册,关 = 该批从工具列表移除(core 级不给开关,封了就没解锁入口);judge 级即使开了仍需配 JEV/Laya Key。**escape 批不吃活动闸**:cli/script 是唯一的「一次调用干完任意多步任务」的入口,必须始终可达,不排在首次活动之后。封印 = 从工具列表里反注册,不是执行期报错;lazy 下闲置回收会把扩展面收回。**若某个 bcdp_* 工具不在你的工具列表里**:它被分级封印了——先跑 bcdp_status 或 bcdp_doctor(两者也算浏览器活动,会把面铺开),或让用户在设置页「工具封印」里打开对应档位的开关;别猜测不存在的工具名。",
3246
3250
  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)",
3247
3251
  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 未开放注册)。"
3248
3252
  };
@@ -3553,6 +3557,7 @@ const CORE = [
3553
3557
  "bcdp_help",
3554
3558
  "bcdp_space_open",
3555
3559
  "bcdp_space_close",
3560
+ "bcdp_space",
3556
3561
  "bcdp_navigate",
3557
3562
  "bcdp_snapshot"
3558
3563
  ];
@@ -3564,7 +3569,8 @@ const ACT = [
3564
3569
  "bcdp_scroll",
3565
3570
  "bcdp_select",
3566
3571
  "bcdp_check",
3567
- "bcdp_drag"
3572
+ "bcdp_drag",
3573
+ "bcdp_tab"
3568
3574
  ];
3569
3575
  const OBSERVE = [
3570
3576
  "bcdp_screenshot",
@@ -3576,7 +3582,8 @@ const WAIT = [
3576
3582
  "bcdp_wait",
3577
3583
  "bcdp_wait_for_selector",
3578
3584
  "bcdp_wait_for_url",
3579
- "bcdp_wait_for_response"
3585
+ "bcdp_wait_for_response",
3586
+ "bcdp_wait_page"
3580
3587
  ];
3581
3588
  const POWER = [
3582
3589
  "bcdp_cdp",
@@ -4438,6 +4445,32 @@ const num = (v, fallback) => typeof v === "number" && Number.isFinite(v) ? v : f
4438
4445
  const bool = (v, fallback) => typeof v === "boolean" ? v : fallback;
4439
4446
  /** Inline helper making arbitrary helper results JSON-safe for the payload. */
4440
4447
  const SAFE_FN = "function safe(v){try{return JSON.parse(JSON.stringify(v))}catch{return String(v)}}\n";
4448
+ /**
4449
+ * Build an IN-PAGE wrapper that resolves a JS expression to a value that is
4450
+ * already safe to cross the CDP boundary.
4451
+ *
4452
+ * WHY in-page, not outer: `page.evaluate` / `page.waitForFunction` serialize
4453
+ * their result INSIDE the runtime's `handleMessage` (ego SDK index.js:539 — a
4454
+ * hard reject, not a catchable throw), so a deeply-cyclic global like
4455
+ * `window.top` kills the whole subprocess with "Object reference chain is too
4456
+ * long" before any outer `safe()` could see the value. Doing the stringify/
4457
+ * toString degradation inside the page (where the object graph actually lives)
4458
+ * is the only place the reference chain can be bounded.
4459
+ *
4460
+ * Semantics preserved per-call:
4461
+ * - primitives and plain (non-cyclic) objects round-trip UNCHANGED;
4462
+ * - cyclic/DOM/global handles degrade to `Object.prototype.toString` or a
4463
+ * `<tagName>` hint;
4464
+ * - with `preserveFalsy`, a falsy result is returned as-is (the waitForFunction
4465
+ * truthiness contract depends on falsy meaning "not satisfied yet"), and a
4466
+ * truthy handle is always degraded to a TRUTHY string so the wait still
4467
+ * resolves.
4468
+ *
4469
+ * @internal exported for tests
4470
+ */
4471
+ function safeEvalWrap(expr, preserveFalsy = false) {
4472
+ return `(() => {\nconst __v = (${expr});\n${preserveFalsy ? "if (!__v) return __v;\n" : ""}if (__v === null || typeof __v !== 'object') return __v;\ntry { const __s = JSON.stringify(__v); return __s === undefined ? Object.prototype.toString.call(__v) : JSON.parse(__s); }\ncatch { try { if (__v.tagName) return '<' + String(__v.tagName).toLowerCase() + '>' + (typeof __v.getAttribute === 'function' && __v.getAttribute('id') ? '#' + __v.getAttribute('id') : ''); return Object.prototype.toString.call(__v); } catch { return String(__v); } }\n})()`;
4473
+ }
4441
4474
  /** Read an entire subprocess reader's buffered output. */
4442
4475
  function readAll(reader) {
4443
4476
  if (!reader) return "";
@@ -7098,7 +7131,7 @@ const Config = Config$1;
7098
7131
  /** Vendored ego-linux CLI shipped inside this plugin (runtime/ego-linux/bin/). */
7099
7132
  const VENDORED_EGO_BIN = fileURLToPath(new URL("../runtime/ego-linux/bin/ego-browser.mjs", import.meta.url));
7100
7133
  const DEFAULT_EGO_BIN = VENDORED_EGO_BIN;
7101
- const DEFAULT_SPACE = "dsh-agent";
7134
+ const AUTO_SPACE_PREFIX = "dsh-agent-";
7102
7135
  const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
7103
7136
  const DEFAULT_GRACE_MS = 15e3;
7104
7137
  const TOOL_TIMEOUT_MS = 12e4;
@@ -7132,6 +7165,75 @@ function createActiveSpaceTracker(defaultSpace = DEFAULT_SPACE) {
7132
7165
  }
7133
7166
  };
7134
7167
  }
7168
+ const GLOBAL_SESSION_KEY = "__global__";
7169
+ /**
7170
+ * C — resolve the fallback slot name for a session. `:auto` only expands to a
7171
+ * per-session `dsh-agent-<sid8>` in isolated-sandbox mode; persistent mode
7172
+ * (and the no-session global slot) collapse to the single named `default`,
7173
+ * protecting login reuse. Any other configured value passes through verbatim.
7174
+ * @internal exported for tests
7175
+ */
7176
+ function deriveSlotDefaultName(rc, sessionKey) {
7177
+ const name$1 = rc.defaultSpace;
7178
+ if (name$1 === AUTO_SPACE_SENTINEL) {
7179
+ if (!rc.isolateSpaces) return DEFAULT_SPACE;
7180
+ return sessionKey === GLOBAL_SESSION_KEY ? DEFAULT_SPACE : AUTO_SPACE_PREFIX + sessionKey.slice(0, 8);
7181
+ }
7182
+ return name$1;
7183
+ }
7184
+ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7185
+ const slots = /* @__PURE__ */ new Map();
7186
+ let sessionKey = GLOBAL_SESSION_KEY;
7187
+ let session;
7188
+ const slotOf = (key) => {
7189
+ let s = slots.get(key);
7190
+ if (!s) {
7191
+ const def = defaultNameFor(key);
7192
+ s = {
7193
+ activeSpace: def,
7194
+ activeName: typeof def === "string" ? def : null
7195
+ };
7196
+ slots.set(key, s);
7197
+ }
7198
+ return s;
7199
+ };
7200
+ const withSlot = (fn) => {
7201
+ fn(slotOf(sessionKey), defaultNameFor(sessionKey));
7202
+ };
7203
+ return {
7204
+ setCurrentSession: (id) => {
7205
+ session = id;
7206
+ sessionKey = id ?? GLOBAL_SESSION_KEY;
7207
+ },
7208
+ currentSession: () => session,
7209
+ current: () => slotOf(sessionKey).activeSpace,
7210
+ opened: (args, result) => {
7211
+ withSlot((s, def) => {
7212
+ s.activeName = result?.name ?? str(args?.name, def) ?? null;
7213
+ s.activeSpace = result?.id ?? s.activeName ?? def;
7214
+ });
7215
+ },
7216
+ selected: (space) => {
7217
+ if (space !== void 0 && space !== "") withSlot((s) => {
7218
+ s.activeSpace = space;
7219
+ s.activeName = typeof space === "string" ? space : null;
7220
+ });
7221
+ },
7222
+ closed: (space, done) => {
7223
+ withSlot((s, def) => {
7224
+ if (done && (String(space) === String(s.activeSpace) || s.activeName !== null && String(space) === String(s.activeName))) {
7225
+ s.activeSpace = def;
7226
+ s.activeName = typeof def === "string" ? def : null;
7227
+ }
7228
+ });
7229
+ },
7230
+ resetToName: () => {
7231
+ withSlot((s, def) => {
7232
+ s.activeSpace = s.activeName ?? def;
7233
+ });
7234
+ }
7235
+ };
7236
+ }
7135
7237
  /**
7136
7238
  * The ego-lite host is a single persistent browser shared by every tool call;
7137
7239
  * concurrent tool executions would race on the same task space / tabs. All
@@ -7150,7 +7252,7 @@ function withEgoLock(fn) {
7150
7252
  *
7151
7253
  * The vendored ego-linux CLI reads EGO_LINUX_CHROME (bare Chrome binary/wrapper
7152
7254
  * path) and EGO_LINUX_HEADLESS (=1 to run headless) from the process env. When a
7153
- * host does not set them — the common case on root / Docker / CI boxes — Chrome
7255
+ * host does not set them �?the common case on root / Docker / CI boxes �?Chrome
7154
7256
  * silently fails to start, and consumers see a 20s `DevTools port` timeout.
7155
7257
  *
7156
7258
  * This function makes the plugin self-sufficient WITHOUT touching the host or
@@ -7166,7 +7268,7 @@ function withEgoLock(fn) {
7166
7268
  * - An opt-out switch EGO_BROWSER_AUTO_ADAPT (set to "0"/"false"/"no") restores
7167
7269
  * the original "inherit host env verbatim" behavior.
7168
7270
  */
7169
- /** 阶段 10 — the render worker: the ONLY thing that can see a page. */
7271
+ /** 阶段 10 �?the render worker: the ONLY thing that can see a page. */
7170
7272
  const RENDER_WORKER_BIN = fileURLToPath(new URL("../bin/cdp-render-worker.mjs", import.meta.url));
7171
7273
  const BUNDLED_WRAPPER = fileURLToPath(new URL("../bin/cdp-chrome-wrapper.sh", import.meta.url));
7172
7274
  const IS_WIN = process.platform === "win32";
@@ -7235,7 +7337,7 @@ function isPosixRoot(platform = process.platform) {
7235
7337
  const uid = process.getuid?.();
7236
7338
  return typeof uid === "number" && uid === 0 && platform !== "win32";
7237
7339
  }
7238
- /** No display server → headless is required (Linux/macOS headless servers). */
7340
+ /** No display server �?headless is required (Linux/macOS headless servers). */
7239
7341
  function isHeadlessDetected(platform = process.platform, env = process.env) {
7240
7342
  if (platform === "win32" || platform === "darwin") return false;
7241
7343
  return env.DISPLAY === void 0 || env.DISPLAY === "";
@@ -7267,7 +7369,7 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
7267
7369
  }
7268
7370
  /**
7269
7371
  * Read the attach decision for the CURRENTLY configured mode/activation.
7270
- * Pure over (cfg, cache) — the decision table itself lives in cdp-targets.ts.
7372
+ * Pure over (cfg, cache) �?the decision table itself lives in cdp-targets.ts.
7271
7373
  */
7272
7374
  function decideCdpAttach(cfg) {
7273
7375
  const attach = defaultAttachCache.get();
@@ -7311,7 +7413,7 @@ function describeSpawnFailure(err) {
7311
7413
  * session; a probe that arrives while the DevTools/CDP channel is still
7312
7414
  * coming up can fail with one of these. Such failures are safe to retry
7313
7415
  * briefly (the browser keeps warming up in the background). Anything else
7314
- * must pass through immediately — never mask a genuine error.
7416
+ * must pass through immediately �?never mask a genuine error.
7315
7417
  */
7316
7418
  const COLD_START_SIGNS = [
7317
7419
  /CDP channel is not open/i,
@@ -7362,7 +7464,7 @@ function shouldReapBrowser(nowMs, lastActivityMs, idleTimeoutMin) {
7362
7464
  * runtime's `--open` subcommand replaces a headless instance with a headed
7363
7465
  * one on the same profile (tabs restore) or just raises the existing window.
7364
7466
  * `--open` is on the runtimeArgs blocklist only because USER-supplied args
7365
- * must not steal the window — here it is an explicit user action from the
7467
+ * must not steal the window �?here it is an explicit user action from the
7366
7468
  * watch panel. --open stops+relaunches when headless, so give it real time.
7367
7469
  */
7368
7470
  async function openAgentWindow(ctx, cfg) {
@@ -7410,11 +7512,55 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
7410
7512
  return result;
7411
7513
  }
7412
7514
  /**
7515
+ * F — navigate self-heal. A page whose renderer/main thread is wedged makes
7516
+ * `page.goto`/`page.reload` hang until the subprocess times out, and the SAME
7517
+ * stuck target is re-selected on the next call, so a plain retry never helps.
7518
+ * This revives the tab FIRST (open a fresh blank target, then close the wedged
7519
+ * active one — order matters: closing last would trip the last-tab guard and
7520
+ * leave the dead tab in place), then retries buildScript exactly once.
7521
+ *
7522
+ * Hard cap is one revive: a second hung attempt is returned verbatim rather
7523
+ * than looping, so a genuine error is never masked by tab churn.
7524
+ * @internal exported for tests
7525
+ */
7526
+ 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;
7527
+ /** True when a failed run looks like a wedged/absent tab rather than a cold start. */
7528
+ function isTabStuckFailure(result) {
7529
+ const hay = `${result.error ?? ""}\n${result.stderr ?? ""}`;
7530
+ return TAB_STUCK_RE.test(hay);
7531
+ }
7532
+ /** Heredoc that swaps the stuck target for a fresh blank one (see runWithTabRevive). */
7533
+ function tabReviveScript() {
7534
+ return `const __before = await browser.listTabs()
7535
+ const __stuck = __before.find(t => t.active) ?? __before[0]
7536
+ await browser.openOrReuseTab('about:blank', { wait: true, timeout: 8000 })
7537
+ if (__stuck) { await browser.closeTab(__stuck.targetId) }
7538
+ console.log('${SENTINEL}' + JSON.stringify({ ok: true, revived: true, closed: __stuck?.targetId ?? null }))\n`;
7539
+ }
7540
+ /**
7541
+ * @internal exported for tests. Returns the final WarmupResult plus what it
7542
+ * recovered from (null on the normal path, so the tool result always carries
7543
+ * a `recoveredFrom` field the model can see).
7544
+ */
7545
+ async function runWithTabRevive(ctx, cfg, exec, buildScript, graceOverrideMs) {
7546
+ const first = await runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverrideMs);
7547
+ if (first.ok || !isTabStuckFailure(first)) return {
7548
+ result: first,
7549
+ recoveredFrom: null
7550
+ };
7551
+ const recoveredFrom = (first.error ?? first.stderr ?? "tab stuck").trim().slice(0, 500);
7552
+ await runEgoScript(ctx.subprocess, tabReviveScript(), exec, cfg, graceOverrideMs);
7553
+ return {
7554
+ result: await runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverrideMs),
7555
+ recoveredFrom
7556
+ };
7557
+ }
7558
+ /**
7413
7559
  * Find the last line carrying the sentinel and JSON-parse its payload.
7414
7560
  *
7415
7561
  * Fallback: `bcdp_script` / `bcdp_cli` run user-authored heredocs, and both
7416
7562
  * tool descriptions tell the model to "end with console.log(JSON.stringify(...))"
7417
- * — without the sentinel prefix. A script written to that instruction used to
7563
+ * �?without the sentinel prefix. A script written to that instruction used to
7418
7564
  * succeed and still be reported as a failure ("no @@DSH_RESULT@@ payload"), so
7419
7565
  * when no sentinel line exists we accept the last line that parses as a JSON
7420
7566
  * object. The sentinel still wins whenever it is present (it marks the payload
@@ -7486,9 +7632,9 @@ function lastJsonObject(text) {
7486
7632
  }
7487
7633
  return best;
7488
7634
  }
7489
- /** R2/R3 — sentinel + payload for the `bcdp_status` facade probe. @internal exported for tests */
7635
+ /** R2/R3 �?sentinel + payload for the `bcdp_status` facade probe. @internal exported for tests */
7490
7636
  const STATUS_FACADE_SENTINEL = "__BCDP_STATUS__";
7491
- /** @internal exported for tests — the exact heredoc the status probe runs. */
7637
+ /** @internal exported for tests �?the exact heredoc the status probe runs. */
7492
7638
  const STATUS_FACADE_SCRIPT = `console.log(${JSON.stringify(STATUS_FACADE_SENTINEL)} + JSON.stringify({ taskSpaces: typeof taskSpaces, browser: typeof browser, page: typeof page }))
7493
7639
  `;
7494
7640
  /**
@@ -7514,7 +7660,7 @@ function parseStatusFacades(stdout) {
7514
7660
  }
7515
7661
  }
7516
7662
  /**
7517
- * R7 — is the upstream plugin installed anywhere under this DSH home?
7663
+ * R7 �?is the upstream plugin installed anywhere under this DSH home?
7518
7664
  *
7519
7665
  * Reported (never enforced): the two plugins can coexist now that tool names
7520
7666
  * and routes no longer overlap, but both driving ONE local ego-lite would
@@ -7532,7 +7678,7 @@ function findUpstreamPluginInstall(home = process.env.HOME || process.env.USERPR
7532
7678
  return "";
7533
7679
  }
7534
7680
  /**
7535
- * R1 — argv for one tool run. Single source of truth for the `--sdk-path`
7681
+ * R1 �?argv for one tool run. Single source of truth for the `--sdk-path`
7536
7682
  * injection: `bcdp_status` and `runEgoScript` must probe/run under the exact
7537
7683
  * same conditions, otherwise "available" and "actually works" diverge again.
7538
7684
  * @internal exported for tests
@@ -7630,6 +7776,22 @@ const useSpace = (name$1) => `const task = await taskSpaces.useOrCreate(${j(name
7630
7776
  * before acting makes cross-process tool calls deterministic.
7631
7777
  */
7632
7778
  const ensureRealTab = () => "const __tabs = await browser.listTabs()\nconst __real = __tabs.find(t => !t.url.startsWith('about:') && !t.url.startsWith('chrome://')) ?? __tabs[0]\nif (__real) await browser.switchTab(__real.targetId)\n";
7779
+ /**
7780
+ * G �?a raw heredoc (`bcdp_cli` / `bcdp_script`) that touches `page.*` without
7781
+ * first selecting a task space dies with the runtime's "no active tab to attach
7782
+ * session". Structured bcdp_* tools never hit this because each wraps its body
7783
+ * in `useSpace(...)` + `ensureRealTab()`; a hand-written heredoc has no such
7784
+ * preamble. Detect the signature and append a one-line how-to-fix, so the error
7785
+ * names the escape (call `taskSpaces.useOrCreate(name)` first) instead of
7786
+ * leaving the model to rediscover it.
7787
+ * @internal exported for tests
7788
+ */
7789
+ const ATTACH_SESSION_HINT = "hint: call `await taskSpaces.useOrCreate(name)` (and `browser.switchTab(...)` if the space has no real tab) before using page.* in a raw heredoc — structured bcdp_* tools do this for you.";
7790
+ function attachSessionHint(errorText) {
7791
+ const t = errorText ?? "";
7792
+ if (!/no active tab to attach session/.test(t)) return t;
7793
+ return t.includes(ATTACH_SESSION_HINT) ? t : `${t}\n${ATTACH_SESSION_HINT}`;
7794
+ }
7633
7795
  function renderText(_args, value) {
7634
7796
  const v = value;
7635
7797
  if (v !== null && typeof v === "object" && v.ok === true && typeof v.text === "string") return [{
@@ -7650,7 +7812,7 @@ const commonOutputSchema = {
7650
7812
  } }
7651
7813
  };
7652
7814
  /**
7653
- * The calling session id — the scope the client's sidebar auto-open binds to.
7815
+ * The calling session id �?the scope the client's sidebar auto-open binds to.
7654
7816
  * Read structurally (`exec.agent` is typed `unknown` in this plugin's own
7655
7817
  * seam); a call with no initiating agent simply leaves the open unscoped.
7656
7818
  */
@@ -7669,6 +7831,7 @@ function defineEgoTool(ctx, cfg, opts) {
7669
7831
  },
7670
7832
  timeoutMs: TOOL_TIMEOUT_MS,
7671
7833
  execute: async (args, exec) => withEgoLock(async () => {
7834
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
7672
7835
  markEgoToolCall(callingSessionId(exec));
7673
7836
  if (typeof opts.gate === "function") {
7674
7837
  const blocked = opts.gate(args);
@@ -7677,6 +7840,13 @@ function defineEgoTool(ctx, cfg, opts) {
7677
7840
  text: blocked
7678
7841
  };
7679
7842
  }
7843
+ if (opts.tabRevive) {
7844
+ const { result: result$1, recoveredFrom } = await runWithTabRevive(ctx, cfg, exec, () => opts.buildScript(args));
7845
+ if (!result$1.ok) throw new Error(recoveredFrom ? `${result$1.error}\n${recoveredFrom}` : result$1.error);
7846
+ if (result$1.value && typeof result$1.value === "object") result$1.value.recoveredFrom = recoveredFrom;
7847
+ if (typeof opts.afterExecute === "function") opts.afterExecute(args, result$1.value);
7848
+ return result$1.value;
7849
+ }
7680
7850
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => opts.buildScript(args));
7681
7851
  if (!result.ok) throw new Error(result.error);
7682
7852
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result.value);
@@ -7698,12 +7868,17 @@ function apply(ctx, config = {}) {
7698
7868
  configuredPath: initialFfmpegConfig.ffmpegPath,
7699
7869
  requestedEncoder: initialFfmpegConfig.ffmpegEncoder
7700
7870
  }).catch(() => {});
7701
- const spaceTracker = createActiveSpaceTracker(config.defaultSpace ?? DEFAULT_SPACE);
7871
+ const spaceTracker = createSessionSpaceTracker((sessionKey) => deriveSlotDefaultName(resolveConfig(bridge.source()), sessionKey));
7702
7872
  const cfg = {
7703
7873
  egoBin: typeof config.egoBin === "string" && config.egoBin !== "" ? config.egoBin : DEFAULT_EGO_BIN,
7704
- configuredDefaultSpace: config.defaultSpace ?? DEFAULT_SPACE,
7874
+ get configuredDefaultSpace() {
7875
+ return resolveConfig(bridge.source()).defaultSpace;
7876
+ },
7705
7877
  spaceTracker,
7706
7878
  get defaultSpace() {
7879
+ return resolveConfig(bridge.source()).defaultSpace;
7880
+ },
7881
+ get activeSpace() {
7707
7882
  return this.spaceTracker.current();
7708
7883
  },
7709
7884
  maxOutputBytes: config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
@@ -7886,9 +8061,8 @@ function apply(ctx, config = {}) {
7886
8061
  logger: ctx.logger
7887
8062
  });
7888
8063
  /**
7889
- * 活动信号:每次 bcdp_* 调用推进 browse 批次(act → observe → wait),
7890
- * 到顶即止。只有注入面真的变了才 reapply。
7891
- */
8064
+ * 活动信号:每�?bcdp_* 调用推进 browse 批次(act �?observe �?wait),
8065
+ * 到顶即止。只有注入面真的变了�?reapply�? */
7892
8066
  const pulseActivity = () => {
7893
8067
  const before = browseBatchDepth;
7894
8068
  browserActive = true;
@@ -7900,9 +8074,8 @@ function apply(ctx, config = {}) {
7900
8074
  ctx.effect?.(() => offActivity);
7901
8075
  }
7902
8076
  /**
7903
- * 闲置回收后把注入面收回 core 级(lazy 模式专属):浏览器已经停了,模型
7904
- * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开。
7905
- */
8077
+ * 闲置回收后把注入面收�?core 级(lazy 模式专属):浏览器已经停了,模型
8078
+ * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开�? */
7906
8079
  const sealAfterReap = () => {
7907
8080
  if (cfg.toolInjection !== "lazy" || !browserActive) return;
7908
8081
  browserActive = false;
@@ -7910,9 +8083,7 @@ function apply(ctx, config = {}) {
7910
8083
  tiers.reapply();
7911
8084
  };
7912
8085
  /**
7913
- * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动;
7914
- * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)。
7915
- */
8086
+ * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动�? * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)�? */
7916
8087
  const tierView = {
7917
8088
  pulse: pulseActivity,
7918
8089
  active: () => browserActive,
@@ -8104,7 +8275,7 @@ function apply(ctx, config = {}) {
8104
8275
  }).done.catch(() => {});
8105
8276
  } catch {}
8106
8277
  });
8107
- ctx.logger?.info?.(`dsh-browser-cdp: mounted (egoBin=${cfg.egoBin}, defaultSpace=${cfg.defaultSpace})`);
8278
+ ctx.logger?.info?.(`dsh-browser-cdp: mounted (egoBin=${cfg.egoBin}, defaultSpace=${cfg.activeSpace})`);
8108
8279
  }
8109
8280
  /** `bcdp_status` probes the SAME channel work uses: a `nodejs` heredoc. */
8110
8281
  function registerEgoStatus(ctx, cfg, reg, tiers) {
@@ -8188,11 +8359,11 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
8188
8359
  })
8189
8360
  }));
8190
8361
  }
8191
- /** `bcdp_auth_flush` — force persistent login cookies down to the disk profile. */
8362
+ /** `bcdp_auth_flush` �?force persistent login cookies down to the disk profile. */
8192
8363
  function registerAuthFlush(ctx, cfg, reg) {
8193
8364
  reg(defineTool({
8194
8365
  name: "bcdp_auth_flush",
8195
- description: "Force all persistent login cookies in the agent browser to be written to the on-disk profile. Call this after login (or before ending a browsing task) so the login survives a later DSH/browser restart — Chrome only flushes cookies to disk on graceful close, this nudges it to persist them now.",
8366
+ description: "Force all persistent login cookies in the agent browser to be written to the on-disk profile. Call this after login (or before ending a browsing task) so the login survives a later DSH/browser restart �?Chrome only flushes cookies to disk on graceful close, this nudges it to persist them now.",
8196
8367
  parameters: {},
8197
8368
  output: {
8198
8369
  schema: {
@@ -8243,7 +8414,7 @@ function registerAuthFlush(ctx, cfg, reg) {
8243
8414
  flushed: jbody.flushed ?? 0,
8244
8415
  ...degraded ? {
8245
8416
  degraded: true,
8246
- error: "engine-unsupported: Lightpanda has no Storage.flushCookies — cookies persist only while the engine process is alive"
8417
+ error: "engine-unsupported: Lightpanda has no Storage.flushCookies �?cookies persist only while the engine process is alive"
8247
8418
  } : {},
8248
8419
  ...!degraded && jbody.error !== void 0 ? { error: jbody.error } : {}
8249
8420
  };
@@ -8262,7 +8433,7 @@ function registerAuthFlush(ctx, cfg, reg) {
8262
8433
  })
8263
8434
  }));
8264
8435
  }
8265
- /** `bcdp_login_import` — copy login cookies from the system browser (issue #46). */
8436
+ /** `bcdp_login_import` �?copy login cookies from the system browser (issue #46). */
8266
8437
  function registerLoginImport(ctx, cfg, reg) {
8267
8438
  reg(defineTool({
8268
8439
  name: "bcdp_login_import",
@@ -8324,7 +8495,7 @@ function registerLoginImport(ctx, cfg, reg) {
8324
8495
  "auto"
8325
8496
  ].includes(source)) return {
8326
8497
  ok: false,
8327
- error: `invalid source "${source}" — expected chrome|edge|brave|auto`
8498
+ error: `invalid source "${source}" �?expected chrome|edge|brave|auto`
8328
8499
  };
8329
8500
  return await importLoginCookies({
8330
8501
  source,
@@ -8367,7 +8538,7 @@ function registerActionTools(ctx, cfg, reg) {
8367
8538
  reg(t({
8368
8539
  name: "bcdp_space_open",
8369
8540
  get description() {
8370
- return cfg.isolateSpaces ? "Open (or reuse) an ego-lite task space in isolated sandbox mode." : "Open (or reuse) the ego-lite task space. In persistent profile mode (default), ALWAYS use or reuse the single 'default' space. Login credentials automatically persist on disk across restarts — if a page requires login, prompt user to log in manually in the opened window. DO NOT create numbered spaces like #4, #5.";
8541
+ return cfg.isolateSpaces ? "Open (or reuse) an ego-lite task space in isolated sandbox mode." : "Open (or reuse) the ego-lite task space. In persistent profile mode (default), ALWAYS use or reuse the single 'default' space. Login credentials automatically persist on disk across restarts �?if a page requires login, prompt user to log in manually in the opened window. DO NOT create numbered spaces like #4, #5.";
8371
8542
  },
8372
8543
  parameters: { name: {
8373
8544
  type: "string",
@@ -8376,7 +8547,7 @@ function registerActionTools(ctx, cfg, reg) {
8376
8547
  return cfg.isolateSpaces ? "Task-space name or numeric id." : "Task-space name. In persistent mode, ALWAYS specify 'default'. Reuse this single space for all browsing tasks.";
8377
8548
  }
8378
8549
  } },
8379
- buildScript: (args) => `${useSpace(str(args.name, cfg.defaultSpace))}console.log('${SENTINEL}' + JSON.stringify({ ok: true, id: task.id ?? null, name: task.name ?? ${j(str(args.name, cfg.defaultSpace))} }))\n`
8550
+ buildScript: (args) => `${useSpace(str(args.name, cfg.activeSpace))}console.log('${SENTINEL}' + JSON.stringify({ ok: true, id: task.id ?? null, name: task.name ?? ${j(str(args.name, cfg.activeSpace))} }))\n`
8380
8551
  }));
8381
8552
  reg(t({
8382
8553
  name: "bcdp_space_close",
@@ -8394,32 +8565,87 @@ function registerActionTools(ctx, cfg, reg) {
8394
8565
  description: "Keep the live page open (default false: close it)."
8395
8566
  }
8396
8567
  },
8397
- buildScript: (args) => `const res = await taskSpaces.complete(${j(str(args.name, cfg.defaultSpace))}, { keep: ${bool(args.keep, false)} })\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, done: !!res.done, skipped: !!res.skipped, reason: res.skipped ? ${j("target space was not agent-owned")} : null }))\n`
8568
+ buildScript: (args) => `const res = await taskSpaces.complete(${j(str(args.name, cfg.activeSpace))}, { keep: ${bool(args.keep, false)} })\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, done: !!res.done, skipped: !!res.skipped, reason: res.skipped ? ${j("target space was not agent-owned")} : null }))\n`
8569
+ }));
8570
+ reg(t({
8571
+ name: "bcdp_space",
8572
+ description: "Inspect or transfer a task space: op=list|handoff|takeover. handoff yields control to the human (stop driving until they hand back); takeover resumes agent control.",
8573
+ parameters: {
8574
+ op: {
8575
+ type: "string",
8576
+ required: true,
8577
+ description: "\"list\" | \"handoff\" | \"takeover\"."
8578
+ },
8579
+ name: {
8580
+ type: "string",
8581
+ description: "Task-space name or id (default: the configured space)."
8582
+ },
8583
+ space: spaceParam
8584
+ },
8585
+ buildScript: (args) => {
8586
+ const send = (expr) => `console.log('${SENTINEL}' + JSON.stringify(${expr}))\n`;
8587
+ const op = str(args.op, "").trim();
8588
+ const name$1 = str(args.name, str(args.space, cfg.activeSpace));
8589
+ if (op === "list") return `const __sp = await taskSpaces.list()\n` + send(`{ ok: true, spaces: __sp.map(s => ({ id: s.id ?? null, name: s.name ?? null, ownership: s.ownership ?? null })) }`);
8590
+ if (op === "handoff") return `${useSpace(name$1)}const __h = await taskSpaces.handOff(${j(name$1)})\n` + send(`{ ok: true, op: 'handoff', name: ${j(name$1)}, done: !!__h.done, skipped: __h.skipped ?? null, hint: 'user now has control; ask them to confirm before calling op=takeover' }`);
8591
+ if (op === "takeover") return `await taskSpaces.takeOver(${j(name$1)})\nconst __info = await page.info()\n` + send(`{ ok: true, op: 'takeover', name: ${j(name$1)}, page: __info }`);
8592
+ return send(`{ ok: false, reason: ${j("bcdp_space: op must be one of list|handoff|takeover")} }`);
8593
+ }
8398
8594
  }));
8399
8595
  reg(t({
8400
8596
  name: "bcdp_snapshot",
8401
- description: "Read the current page as text: the full-page semantic tree annotated with [ref=N, loc=...] selectors that bcdp_click / bcdp_fill can target. This is the main observation tool for any browser task.",
8597
+ description: "Read the current page as text: the full-page semantic tree annotated with [ref=N, loc=...] selectors that bcdp_click / bcdp_fill can target. To target across calls prefer a `loc=` over `@N`: a loc is stable, a ref is renumbered every snapshot.",
8402
8598
  parameters: {
8403
8599
  space: spaceParam,
8404
8600
  scope: {
8405
8601
  type: "string",
8406
- description: "snapshot scope: 'full_page' (default) or 'only_within_viewport'."
8602
+ description: "scope: 'full_page' (default) | 'only_within_viewport'; 'subtree' captures only `root`'s subtree."
8603
+ },
8604
+ root: {
8605
+ type: "string",
8606
+ description: "scope='subtree': the node to capture - a `loc=` token (stable across calls) or a ref like '@12' from a fresh snapshot."
8407
8607
  }
8408
8608
  },
8409
8609
  buildScript: (args) => {
8410
8610
  const scope = str(args.scope, "");
8411
- const call = scope === "" ? "await page.snapshotRaw()" : `await page.snapshotRaw({ scope: ${j(scope)} })`;
8412
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}let s = ${call}\nlet tries = 0\nwhile (!(s.content ?? '') && tries < 3) { await page.waitForTimeout(400); s = ${call}; tries++ }\nconst text = s.content ?? ''\nconsole.log('${SENTINEL}' + JSON.stringify(text === ''\n ? { ok: false, text, tries, reason: 'snapshot returned no content after retries (page may be blank, still loading, or the browser dropped)' }\n : { ok: true, text, tries }))\n`;
8611
+ const send = (expr) => `console.log('${SENTINEL}' + JSON.stringify(${expr}))\n`;
8612
+ const SNAP_OPTS = "includeStableLocator: true";
8613
+ if (scope === "subtree") {
8614
+ const rootArg = str(args.root, "").trim();
8615
+ if (rootArg === "") return send(`{ ok: false, reason: 'bcdp_snapshot: root (a ref such as @N, or a loc=css:�? is required for scope=subtree' }`);
8616
+ const resolver = `((raw, refs) => {
8617
+ const want = raw.replace(/^loc=/, '').trim()
8618
+ if (want !== '' && want !== 'unstable') {
8619
+ const byLoc = refs.find(r => r.loc != null && String(r.loc).replace(/^loc=/, '') === want)
8620
+ if (byLoc && byLoc.backendNodeId != null) return byLoc.backendNodeId
8621
+ }
8622
+ const id = raw.replace(/^@/, '').trim()
8623
+ const byRef = refs.find(r => String(r.refId) === id)
8624
+ return byRef ? byRef.backendNodeId ?? null : null
8625
+ })(${j(rootArg)}, s.refs ?? [])`;
8626
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}let s = await page.snapshotRaw({ ${SNAP_OPTS} })\nlet tries = 0\nwhile (!(s.content ?? '') && tries < 3) { await page.waitForTimeout(400); s = await page.snapshotRaw({ ${SNAP_OPTS} }); tries++ }\nconst __bn = ${resolver}\nif (__bn === null) { ${send(`{ ok: false, root: ${j(rootArg)}, reason: 'subtree root not present in the current snapshot; take a fresh full snapshot and use a loc= (survives across calls) or a ref @N from it' }`)} }\nelse { const sub = await page.snapshotRaw({ scope: 'subtree', root: __bn, ${SNAP_OPTS} }); const stext = sub.content ?? '';\nconsole.log('${SENTINEL}' + JSON.stringify(stext === ''\n ? { ok: false, root: ${j(rootArg)}, backendNodeId: __bn, text: stext, reason: 'subtree capture came back empty' }\n : { ok: true, root: ${j(rootArg)}, backendNodeId: __bn, text: stext, tries })) }\n`;
8627
+ }
8628
+ const call = scope === "" ? `await page.snapshotRaw({ ${SNAP_OPTS} })` : `await page.snapshotRaw({ scope: ${j(scope)}, ${SNAP_OPTS} })`;
8629
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}let s = ${call}\nlet tries = 0\nwhile (!(s.content ?? '') && tries < 3) { await page.waitForTimeout(400); s = ${call}; tries++ }\nconst text = s.content ?? ''\nconsole.log('${SENTINEL}' + JSON.stringify(text === ''\n ? { ok: false, text, tries, reason: 'snapshot returned no content after retries (page may be blank, still loading, or the browser dropped)' }\n : { ok: true, text, tries }))\n`;
8413
8630
  }
8414
8631
  }));
8415
8632
  reg(t({
8416
8633
  name: "bcdp_navigate",
8417
- description: "Open a URL in the task space, or switch to the existing tab for it. Always prefer reusing existing open tabs before opening duplicate URLs. Waits for document load. Returns resulting page info.",
8634
+ description: "Open a URL in the task space, or switch to the existing tab for it (prefer reuse over duplicates). Waits for document load, returns page info.",
8635
+ tabRevive: true,
8418
8636
  parameters: {
8419
8637
  url: {
8420
8638
  type: "string",
8421
8639
  required: true,
8422
- description: "Absolute URL to open, e.g. https://example.com/path."
8640
+ description: "Absolute URL to open (omit if reload)."
8641
+ },
8642
+ reload: {
8643
+ type: "boolean",
8644
+ description: "Reload the current tab (no url needed)."
8645
+ },
8646
+ ignoreCache: {
8647
+ type: "boolean",
8648
+ description: "With reload: bypass cache."
8423
8649
  },
8424
8650
  wait: {
8425
8651
  type: "boolean",
@@ -8433,8 +8659,9 @@ function registerActionTools(ctx, cfg, reg) {
8433
8659
  },
8434
8660
  buildScript: (args) => {
8435
8661
  const u = str(args.url, "");
8662
+ if (bool(args.reload, false)) return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __ok = await page.reload({ ignoreCache: ${bool(args.ignoreCache, false)}, waitUntil: ${j(bool(args.wait, true) ? "load" : "commit")}, timeout: ${num(args.timeout, 2e4)} })\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, reloaded: true, loaded: __ok !== false, page: pginfo }))\n`;
8436
8663
  if (u === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reused: false, page: null, reason: 'bcdp_navigate: url is required' }))\n`;
8437
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const __existing = __tabs.find(t => t.url.split('#')[0] === ${j(u.split("#")[0])})\nconst tab = __existing ? await browser.switchTab(__existing.targetId) : await page.goto(${j(u)}, { wait: ${bool(args.wait, true)}, timeout: ${num(args.timeout, 2e4)} })\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, reused: !!__existing, page: pginfo }))\n`;
8664
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __existing = __tabs.find(t => t.url.split('#')[0] === ${j(u.split("#")[0])})\nconst tab = __existing ? await browser.switchTab(__existing.targetId) : await page.goto(${j(u)}, { wait: ${bool(args.wait, true)}, timeout: ${num(args.timeout, 2e4)} })\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, reused: !!__existing, page: pginfo }))\n`;
8438
8665
  }
8439
8666
  }));
8440
8667
  reg(t({
@@ -8474,7 +8701,7 @@ function registerActionTools(ctx, cfg, reg) {
8474
8701
  const labelOpt = str(args.label, "") !== "" ? `{ label: ${j(str(args.label, ""))} }` : "";
8475
8702
  action = dbl ? `await page.locator(${j(sel)}).dblclick(${labelOpt})` : `await page.locator(${j(sel)}).click(${labelOpt})`;
8476
8703
  } else action = dbl ? `await page.mouse.dblclick(${x}, ${y})` : `await page.mouse.click(${x}, ${y})`;
8477
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}${action}\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, double: ${dbl}, page: pginfo }))\n`;
8704
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}${action}\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, double: ${dbl}, page: pginfo }))\n`;
8478
8705
  }
8479
8706
  }));
8480
8707
  reg(t({
@@ -8493,7 +8720,7 @@ function registerActionTools(ctx, cfg, reg) {
8493
8720
  },
8494
8721
  space: spaceParam
8495
8722
  },
8496
- buildScript: (args) => `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).fill(${j(str(args.text, ""))})\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, page: pginfo }))\n`
8723
+ buildScript: (args) => `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).fill(${j(str(args.text, ""))})\nconst pginfo = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, page: pginfo }))\n`
8497
8724
  }));
8498
8725
  reg(t({
8499
8726
  name: "bcdp_js",
@@ -8506,7 +8733,7 @@ function registerActionTools(ctx, cfg, reg) {
8506
8733
  },
8507
8734
  space: spaceParam
8508
8735
  },
8509
- buildScript: (args) => `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}${SAFE_FN}const result = await page.evaluate(${j(str(args.expression, ""))})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, result: safe(result) }))\n`
8736
+ buildScript: (args) => `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}${SAFE_FN}const result = await page.evaluate(${j(safeEvalWrap(str(args.expression, "")))})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, result: safe(result) }))\n`
8510
8737
  }));
8511
8738
  reg(t({
8512
8739
  name: "bcdp_cdp",
@@ -8527,7 +8754,7 @@ function registerActionTools(ctx, cfg, reg) {
8527
8754
  buildScript: (args) => {
8528
8755
  const params = args.params;
8529
8756
  const call = params !== void 0 && params !== null ? `await cdp(${j(str(args.method, ""))}, ${j(params)})` : `await cdp(${j(str(args.method, ""))})`;
8530
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}${SAFE_FN}const result = ${call}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, result: safe(result) }))\n`;
8757
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}${SAFE_FN}const result = ${call}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, result: safe(result) }))\n`;
8531
8758
  }
8532
8759
  }));
8533
8760
  reg(t({
@@ -8548,14 +8775,62 @@ function registerActionTools(ctx, cfg, reg) {
8548
8775
  const sel = str(args.selector, "");
8549
8776
  const pth = str(args.path, "");
8550
8777
  const shot = sel !== "" ? `await page.locator(${j(sel)}).screenshot(${pth ? `{ path: ${j(pth)} }` : ""})` : `await page.screenshot(${pth ? `{ path: ${j(pth)} }` : ""})`;
8551
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const path = ${shot}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, path }))\n`;
8778
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const path = ${shot}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, path }))\n`;
8552
8779
  }
8553
8780
  }));
8554
8781
  reg(t({
8555
8782
  name: "bcdp_page_info",
8556
- description: "Return the current page info: url, title, viewport size (w, h), scroll offsets (sx, sy), device metrics (pw, ph), and whether a native dialog is open. Also reports `humanCheck` — whether a CAPTCHA / human-verification challenge is detected on the page (so the agent can alert the user to complete it).",
8783
+ description: "Return the current page info: url, title, viewport size (w, h), scroll offsets (sx, sy), device metrics (pw, ph), and whether a native dialog is open. Also reports `humanCheck` �?whether a CAPTCHA / human-verification challenge is detected on the page (so the agent can alert the user to complete it).",
8557
8784
  parameters: { space: spaceParam },
8558
- buildScript: (args) => `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const pginfo = await page.info()\nlet __hc = null\ntry { __hc = await page.evaluate(${j(HUMAN_CHECK_PROBE)}).catch(() => null); } catch { __hc = null }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, page: pginfo, humanCheck: __hc }))\n`
8785
+ buildScript: (args) => `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const pginfo = await page.info()\nlet __hc = null\ntry { __hc = await page.evaluate(${j(HUMAN_CHECK_PROBE)}).catch(() => null); } catch { __hc = null }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, page: pginfo, humanCheck: __hc }))\n`
8786
+ }));
8787
+ reg(t({
8788
+ name: "bcdp_tab",
8789
+ description: "Manage tabs: op=list|current|new|switch|close. new opens/reuses a tab at url; switch/close take a `target` (targetId or URL substring). Will not close the last tab.",
8790
+ parameters: {
8791
+ op: {
8792
+ type: "string",
8793
+ required: true,
8794
+ description: "\"list\" | \"current\" | \"new\" | \"switch\" | \"close\"."
8795
+ },
8796
+ url: {
8797
+ type: "string",
8798
+ description: "Absolute URL for op=new (reuses a matching tab)."
8799
+ },
8800
+ target: {
8801
+ type: "string",
8802
+ description: "targetId or URL substring for switch / close."
8803
+ },
8804
+ wait: {
8805
+ type: "boolean",
8806
+ description: "op=new: wait for load (default true)."
8807
+ },
8808
+ timeout: {
8809
+ type: "number",
8810
+ description: "op=new: load timeout ms (default 20000)."
8811
+ },
8812
+ space: spaceParam
8813
+ },
8814
+ buildScript: (args) => {
8815
+ const send = (expr) => `console.log('${SENTINEL}' + JSON.stringify(${expr}))\n`;
8816
+ const op = str(args.op, "").trim();
8817
+ const head = useSpace(str(args.space, cfg.activeSpace));
8818
+ if (op === "list") return head + `const __tabs = await browser.listTabs()\n` + send(`{ ok: true, tabs: __tabs.map(t => ({ targetId: t.targetId, title: t.title, url: t.url, active: !!t.active, index: t.index })) }`);
8819
+ if (op === "current") return head + `const __cur = await browser.currentTab()\n` + send(`{ ok: true, tab: __cur }`);
8820
+ if (op === "new") {
8821
+ const u = str(args.url, "");
8822
+ if (u === "") return send(`{ ok: false, reason: 'bcdp_tab: url is required for op=new' }`);
8823
+ return head + `const __t = await browser.openOrReuseTab(${j(u)}, { wait: ${bool(args.wait, true)}, timeout: ${num(args.timeout, 2e4)} })\n` + send(`{ ok: true, tab: __t }`);
8824
+ }
8825
+ if (op === "switch" || op === "close") {
8826
+ const t$1 = str(args.target, "");
8827
+ if (t$1 === "") return send(`{ ok: false, reason: ${j("bcdp_tab: target (targetId or URL substring) is required for op=" + op)} }`);
8828
+ const find = `const __tabs = await browser.listTabs()\nconst __t = __tabs.find(x => x.targetId === ${j(t$1)}) ?? __tabs.find(x => (x.url || '').includes(${j(t$1)}))\n`;
8829
+ if (op === "switch") return head + find + `if (!__t) { ${send(`{ ok: false, reason: 'bcdp_tab: no tab matches switch target ' + ${j(t$1)} }`)} }\nelse { await browser.switchTab(__t.targetId); const pginfo = await page.info(); ${send(`{ ok: true, tab: { ...__t, active: true }, page: pginfo }`)} }\n`;
8830
+ return head + find + `if (!__t) { ${send(`{ ok: false, reason: 'bcdp_tab: no tab matches close target ' + ${j(t$1)} }`)} }\nelse if (__tabs.length <= 1) { ${send(`{ ok: false, reason: 'refusing to close the last tab: open another tab first' }`)} }\nelse { const __closed = await browser.closeTab(__t.targetId); const __after = await browser.listTabs(); ${send(`{ ok: true, closed: __closed, count: __after.length, tabs: __after.map(t => ({ targetId: t.targetId, url: t.url, active: !!t.active })) }`)} }\n`;
8831
+ }
8832
+ return send(`{ ok: false, reason: ${j("bcdp_tab: op must be one of list|current|new|switch|close")} }`);
8833
+ }
8559
8834
  }));
8560
8835
  reg(t({
8561
8836
  name: "bcdp_wait",
@@ -8589,7 +8864,7 @@ function registerActionTools(ctx, cfg, reg) {
8589
8864
  buildScript: (args) => {
8590
8865
  const sel = str(args.selector, "").trim();
8591
8866
  if (sel === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, waited: false, reason: 'bcdp_wait_for_selector: selector is required' }))\n`;
8592
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.waitForSelector(${j(sel)}, { state: ${j(str(args.state, "visible"))}, timeout: ${num(args.timeout, 1e4)} })\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, waited: true, selector: ${j(sel)}, state: ${j(str(args.state, "visible"))} }))\n`;
8867
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.waitForSelector(${j(sel)}, { state: ${j(str(args.state, "visible"))}, timeout: ${num(args.timeout, 1e4)} })\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, waited: true, selector: ${j(sel)}, state: ${j(str(args.state, "visible"))} }))\n`;
8593
8868
  }
8594
8869
  }));
8595
8870
  reg(t({
@@ -8610,7 +8885,7 @@ function registerActionTools(ctx, cfg, reg) {
8610
8885
  buildScript: (args) => {
8611
8886
  const p = str(args.pattern, "").trim();
8612
8887
  if (p === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reached: false, reason: 'bcdp_wait_for_url: pattern is required' }))\n`;
8613
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const __ok = await page.waitForURL(${j(p)}, { timeout: ${num(args.timeout, 1e4)} }).catch(() => false)\nconst __u = await page.url()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: !!__ok, reached: !!__ok, url: __u }))\n`;
8888
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __ok = await page.waitForURL(${j(p)}, { timeout: ${num(args.timeout, 1e4)} }).catch(() => false)\nconst __u = await page.url()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: !!__ok, reached: !!__ok, url: __u }))\n`;
8614
8889
  }
8615
8890
  }));
8616
8891
  reg(t({
@@ -8636,7 +8911,54 @@ function registerActionTools(ctx, cfg, reg) {
8636
8911
  const u = str(args.url, "").trim();
8637
8912
  const mode = str(args.body, "none");
8638
8913
  const wantBody = mode === "text" || mode === "json";
8639
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const __res = await page.waitForResponse(${j(u)}, { timeout: ${num(args.timeout, 1e4)} })\n${wantBody ? `const __body = ${mode === "json" ? "await __res.json().catch(()=>null)" : "await __res.text().catch(()=>null)"}\n` : ""}console.log('${SENTINEL}' + JSON.stringify({ ok: true, url: __res.url(), status: __res.status()${wantBody ? ", body: __body" : ""} }))\n`;
8914
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __res = await page.waitForResponse(${j(u)}, { timeout: ${num(args.timeout, 1e4)} })\n${wantBody ? `const __body = ${mode === "json" ? "await __res.json().catch(()=>null)" : "await __res.text().catch(()=>null)"}\n` : ""}console.log('${SENTINEL}' + JSON.stringify({ ok: true, url: __res.url(), status: __res.status()${wantBody ? ", body: __body" : ""} }))\n`;
8915
+ }
8916
+ }));
8917
+ reg(t({
8918
+ name: "bcdp_wait_page",
8919
+ description: "Page-level wait, op=load|function|request|event. load: a load state (state=load|domcontentloaded|networkidle). function: in-page JS `expression` until truthy (returns the value). request: a request whose URL matches `url` (substring/glob/regex). event: a download. load/function time out softly (ok:false); request/event surface their timeout as ok:false.",
8920
+ parameters: {
8921
+ op: {
8922
+ type: "string",
8923
+ required: true,
8924
+ description: "\"load\" | \"function\" | \"request\" | \"event\"."
8925
+ },
8926
+ state: {
8927
+ type: "string",
8928
+ description: "op=load: \"load\" (default) | \"domcontentloaded\" | \"networkidle\"."
8929
+ },
8930
+ expression: {
8931
+ type: "string",
8932
+ description: "op=function: in-page JS expression evaluated until truthy."
8933
+ },
8934
+ url: {
8935
+ type: "string",
8936
+ description: "op=request: URL substring / glob / regex."
8937
+ },
8938
+ timeout: {
8939
+ type: "number",
8940
+ description: "Wait in ms (default 30000)."
8941
+ },
8942
+ space: spaceParam
8943
+ },
8944
+ buildScript: (args) => {
8945
+ const send = (expr) => `console.log('${SENTINEL}' + JSON.stringify(${expr}))\n`;
8946
+ const op = str(args.op, "").trim();
8947
+ const to = num(args.timeout, 0) > 0 ? num(args.timeout, 0) : 3e4;
8948
+ const head = `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}`;
8949
+ if (op === "load") return head + `const __ok = await page.waitForLoadState(${j(str(args.state, "load"))}, { timeout: ${to} })\n` + send(`{ ok: !!__ok, op: 'load', state: ${j(str(args.state, "load"))}, reason: __ok ? null : 'timed out: load state not reached within ${to}ms' }`);
8950
+ if (op === "function") {
8951
+ const expr = str(args.expression, "").trim();
8952
+ if (expr === "") return send(`{ ok: false, op: 'function', reason: 'bcdp_wait_page: expression is required for op=function' }`);
8953
+ return head + `const __v = await page.waitForFunction(${j(safeEvalWrap(expr, true))}, undefined, { timeout: ${to} })\n` + send(`{ ok: !!__v, op: 'function', value: __v === false ? null : __v, reason: __v === false ? 'timed out: expression never became truthy within ${to}ms' : null }`);
8954
+ }
8955
+ if (op === "request") {
8956
+ const u = str(args.url, "").trim();
8957
+ if (u === "") return send(`{ ok: false, op: 'request', reason: 'bcdp_wait_page: url is required for op=request' }`);
8958
+ return head + `try { const __req = await page.waitForRequest(${j(u)}, { timeout: ${to} })\n` + send(`{ ok: true, op: 'request', url: __req.url(), method: __req.method() }`) + `} catch (e) { ${send(`{ ok: false, op: 'request', reason: String(e && e.message || e) }`)} }\n`;
8959
+ }
8960
+ if (op === "event") return head + `try { const __ev = await page.waitForEvent('download', { timeout: ${to} })\nconst __p = await __ev.path().catch(() => null)\n` + send(`{ ok: true, op: 'event', event: 'download', suggestedFilename: __ev.suggestedFilename(), url: __ev.url(), path: __p }`) + `} catch (e) { ${send(`{ ok: false, op: 'event', reason: String(e && e.message || e) }`)} }\n`;
8961
+ return send(`{ ok: false, reason: ${j("bcdp_wait_page: op must be one of load|function|request|event")} }`);
8640
8962
  }
8641
8963
  }));
8642
8964
  reg(t({
@@ -8651,14 +8973,21 @@ function registerActionTools(ctx, cfg, reg) {
8651
8973
  type: "string",
8652
8974
  description: "Type this text instead (keyboard.type)."
8653
8975
  },
8976
+ via: {
8977
+ type: "string",
8978
+ description: "text mode: 'type' (default, per-character) | 'insert' (keyboard.insertText, faster for long strings)."
8979
+ },
8654
8980
  space: spaceParam
8655
8981
  },
8656
8982
  buildScript: (args) => {
8657
8983
  const txt = str(args.text, "");
8658
8984
  const k = str(args.key, "").trim();
8659
- if (txt !== "") return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.keyboard.type(${j(txt)})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, typed: ${j(txt)} }))\n`;
8985
+ if (txt !== "") {
8986
+ const method = str(args.via, "type") === "insert" ? "insertText" : "type";
8987
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.keyboard.${method}(${j(txt)})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, typed: ${j(txt)} }))\n`;
8988
+ }
8660
8989
  if (k === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_key: provide key or text to type' }))\n`;
8661
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.keyboard.press(${j(k)})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, key: ${j(k)} }))\n`;
8990
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.keyboard.press(${j(k)})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, key: ${j(k)} }))\n`;
8662
8991
  }
8663
8992
  }));
8664
8993
  reg(t({
@@ -8683,7 +9012,7 @@ function registerActionTools(ctx, cfg, reg) {
8683
9012
  const sel = str(args.selector, "");
8684
9013
  const hasXY = typeof args.x === "number" && typeof args.y === "number";
8685
9014
  if (sel === "" && !hasXY) return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_hover: provide selector or both x and y' }))\n`;
8686
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}` + (sel !== "" ? `await page.locator(${j(sel)}).hover()\n` : `await page.mouse.move(${args.x}, ${args.y})\n`) + `console.log('${SENTINEL}' + JSON.stringify({ ok: true }))\n`;
9015
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}` + (sel !== "" ? `await page.locator(${j(sel)}).hover()\n` : `await page.mouse.move(${args.x}, ${args.y})\n`) + `console.log('${SENTINEL}' + JSON.stringify({ ok: true }))\n`;
8687
9016
  }
8688
9017
  }));
8689
9018
  reg(t({
@@ -8732,7 +9061,7 @@ function registerActionTools(ctx, cfg, reg) {
8732
9061
  break;
8733
9062
  default: expr = `await ${selExpr}.textContent()`;
8734
9063
  }
8735
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}${SAFE_FN}const __v = ${expr}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, what: ${j(what)}, selector: ${j(sel)}, value: safe(__v) }))\n`;
9064
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}${SAFE_FN}const __v = ${expr}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, what: ${j(what)}, selector: ${j(sel)}, value: safe(__v) }))\n`;
8736
9065
  }
8737
9066
  }));
8738
9067
  reg(t({
@@ -8750,7 +9079,7 @@ function registerActionTools(ctx, cfg, reg) {
8750
9079
  },
8751
9080
  space: spaceParam
8752
9081
  },
8753
- buildScript: (args) => `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).selectOption(${j(args.value ?? "")})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, select: ${j(str(args.selector, ""))} }))\n`
9082
+ buildScript: (args) => `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).selectOption(${j(args.value ?? "")})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, select: ${j(str(args.selector, ""))} }))\n`
8754
9083
  }));
8755
9084
  reg(t({
8756
9085
  name: "bcdp_drag",
@@ -8776,7 +9105,7 @@ function registerActionTools(ctx, cfg, reg) {
8776
9105
  const hasEl = str(args.from, "") !== "" && str(args.to, "") !== "";
8777
9106
  if (!hasEl && pts.length < 4) return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_drag: provide from+to selectors, or at least 4 points (x1,y1,x2,y2)' }))\n`;
8778
9107
  const action = hasEl ? `await page.locator(${j(str(args.from, ""))}).dragTo(page.locator(${j(str(args.to, ""))}))\n` : `const __pts = ${j(pts)}\nconst __coords=[];for(let __i=0;__i<__pts.length;__i+=2){__coords.push([__pts[__i],__pts[__i+1]])}\nawait page.mouse.drag(__coords)\n`;
8779
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}` + action + `console.log('${SENTINEL}' + JSON.stringify({ ok: true }))\n`;
9108
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}` + action + `console.log('${SENTINEL}' + JSON.stringify({ ok: true }))\n`;
8780
9109
  }
8781
9110
  }));
8782
9111
  reg(t({
@@ -8802,7 +9131,7 @@ function registerActionTools(ctx, cfg, reg) {
8802
9131
  const hasDelta = Number.isFinite(args.deltaX) || Number.isFinite(args.deltaY);
8803
9132
  if (!hasSelector && !hasDelta) return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_scroll: provide deltaX/deltaY or a selector' }))\n`;
8804
9133
  const action = hasSelector ? `await page.locator(${j(str(args.selector, ""))}).scrollIntoViewIfNeeded()\n` : `await page.mouse.wheel(${num(args.deltaX, 0)}, ${num(args.deltaY, 300)})\n`;
8805
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}` + action + `const __p = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, scrollX: __p.sx ?? null, scrollY: __p.sy ?? null }))\n`;
9134
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}` + action + `const __p = await page.info()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, scrollX: __p.sx ?? null, scrollY: __p.sy ?? null }))\n`;
8806
9135
  }
8807
9136
  }));
8808
9137
  reg(t({
@@ -8821,7 +9150,7 @@ function registerActionTools(ctx, cfg, reg) {
8821
9150
  },
8822
9151
  space: spaceParam
8823
9152
  },
8824
- buildScript: (args) => `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).setInputFiles(${j(str(args.path, ""))})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, upload: ${j(str(args.selector, ""))} }))\n`
9153
+ buildScript: (args) => `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).setInputFiles(${j(str(args.path, ""))})\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, upload: ${j(str(args.selector, ""))} }))\n`
8825
9154
  }));
8826
9155
  reg(t({
8827
9156
  name: "bcdp_download",
@@ -8845,15 +9174,15 @@ function registerActionTools(ctx, cfg, reg) {
8845
9174
  },
8846
9175
  space: spaceParam
8847
9176
  },
8848
- gate: () => defaultAttachCache.get().engine === "lightpanda" ? "engine-unsupported: the attached browser is Lightpanda, which has no Page download events — bcdp_download cannot capture files on this engine. Trigger the download another way (e.g. fetch() the URL in-page and return the bytes)." : null,
9177
+ gate: () => defaultAttachCache.get().engine === "lightpanda" ? "engine-unsupported: the attached browser is Lightpanda, which has no Page download events �?bcdp_download cannot capture files on this engine. Trigger the download another way (e.g. fetch() the URL in-page and return the bytes)." : null,
8849
9178
  buildScript: (args) => {
8850
9179
  const sel = str(args.triggerSelector, "");
8851
9180
  const script = str(args.triggerScript, "");
8852
9181
  const savePath = str(args.savePath, "");
8853
9182
  const timeout = num(args.timeout, 3e4);
8854
- const trigger = sel !== "" ? `await page.locator(${j(sel)}).click()\n` : script !== "" ? `await page.evaluate(() => { ${script} })\n` : "/* no trigger given — the download may be started by an earlier navigation */\n";
9183
+ const trigger = sel !== "" ? `await page.locator(${j(sel)}).click()\n` : script !== "" ? `await page.evaluate(() => { ${script} })\n` : "/* no trigger given �?the download may be started by an earlier navigation */\n";
8855
9184
  const save = savePath !== "" ? `const __final = await __dl.saveAs(${j(savePath)}).catch(()=>null)\n` : `const __final = await __dl.path().catch(()=>null)\n`;
8856
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const __dlPromise = page.waitForEvent('download', { timeout: ${timeout} })\n` + trigger + "const __dl = await __dlPromise\nconst __name = typeof __dl.suggestedFilename === 'function' ? __dl.suggestedFilename() : null\nconst __url = typeof __dl.url === 'function' ? __dl.url() : null\n" + save + `console.log('${SENTINEL}' + JSON.stringify({ ok: true, path: __final, suggestedFilename: __name, url: __url }))\n`;
9185
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __dlPromise = page.waitForEvent('download', { timeout: ${timeout} })\n` + trigger + "const __dl = await __dlPromise\nconst __name = typeof __dl.suggestedFilename === 'function' ? __dl.suggestedFilename() : null\nconst __url = typeof __dl.url === 'function' ? __dl.url() : null\n" + save + `console.log('${SENTINEL}' + JSON.stringify({ ok: true, path: __final, suggestedFilename: __name, url: __url }))\n`;
8857
9186
  }
8858
9187
  }));
8859
9188
  reg(t({
@@ -8873,7 +9202,7 @@ function registerActionTools(ctx, cfg, reg) {
8873
9202
  },
8874
9203
  buildScript: (args) => {
8875
9204
  const chk = bool(args.checked, true);
8876
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).${chk ? "check" : "uncheck"}()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, checked: ${chk} }))\n`;
9205
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}await page.locator(${j(str(args.selector, ""))}).${chk ? "check" : "uncheck"}()\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, checked: ${chk} }))\n`;
8877
9206
  }
8878
9207
  }));
8879
9208
  reg(t({
@@ -8894,7 +9223,7 @@ function registerActionTools(ctx, cfg, reg) {
8894
9223
  const accept = bool(args.accept, true);
8895
9224
  const text = str(args.text, "");
8896
9225
  const params = `{ accept: ${accept}${text !== "" ? `, promptText: ${j(text)}` : ""} }`;
8897
- return `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}const __r = await cdp("Page.handleJavaScriptDialog", ${params}).catch((e) => ({ error: String(e) }))\nconst __ok = !!(__r && !__r.error)\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, handled: __ok, accept: ${accept}, error: __r?.error ?? null }))\n`;
9226
+ return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}const __r = await cdp("Page.handleJavaScriptDialog", ${params}).catch((e) => ({ error: String(e) }))\nconst __ok = !!(__r && !__r.error)\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, handled: __ok, accept: ${accept}, error: __r?.error ?? null }))\n`;
8898
9227
  }
8899
9228
  }));
8900
9229
  reg(t({
@@ -8943,17 +9272,17 @@ function registerActionTools(ctx, cfg, reg) {
8943
9272
  const mode = str(args.mode, "browser");
8944
9273
  const cred = str(args.credentials, "");
8945
9274
  if (mode !== "server" && (cred === "include" || cred === "omit" || cred === "same-origin")) opts.credentials = cred;
8946
- return `${mode === "server" ? "" : `${useSpace(str(args.space, cfg.defaultSpace))}${ensureRealTab()}`}${SAFE_FN}const __r = await fetch.${mode === "server" ? "server" : "browser"}(${j(str(args.url, ""))}, ${j(opts)})\nconst __status = typeof __r.status !== "undefined" ? __r.status : 200\nlet __body = null\ntry { __body = typeof __r.text === "function" ? await __r.text() : (typeof __r === "string" ? __r : JSON.stringify(safe(__r))) } catch { __body = null }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, mode: ${j(mode)}, status: __status, body: __body, url: ${j(str(args.url, ""))} }))\n`;
9275
+ return `${mode === "server" ? "" : `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}`}${SAFE_FN}const __r = await fetch.${mode === "server" ? "server" : "browser"}(${j(str(args.url, ""))}, ${j(opts)})\nconst __status = typeof __r.status !== "undefined" ? __r.status : 200\nlet __body = null\ntry { __body = typeof __r.text === "function" ? await __r.text() : (typeof __r === "string" ? __r : JSON.stringify(safe(__r))) } catch { __body = null }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, mode: ${j(mode)}, status: __status, body: __body, url: ${j(str(args.url, ""))} }))\n`;
8947
9276
  }
8948
9277
  }));
8949
9278
  reg((() => {
8950
9279
  return defineTool({
8951
9280
  name: "bcdp_cli",
8952
- description: "Escape hatch: run an arbitrary `ego-browser nodejs` heredoc script VERBATIM (facades page/browser/taskSpaces/site/fetch and the raw cdp() are preloaded; no preamble is added, so select the task space yourself before touching page.*). Use when the structured bcdp_* tools do not cover the task. Returns the raw output plus the parsed console.log payload when present.",
9281
+ description: "Escape hatch: run an arbitrary `ego-browser nodejs` heredoc script VERBATIM (facades page/browser/taskSpaces/site/fetch and the raw cdp() are preloaded; no preamble is added, so select the task space yourself before touching page.*). Use when the structured bcdp_* tools do not cover the task. Returns the raw output plus the parsed console.log payload when present. These scripts expose the vendored SDK (`taskSpaces`, `page.locator()`, global `cdp()`, `fetch.browser|server`) �?NOT the official docs' `taskSpace()` / `page.click()`.",
8953
9282
  parameters: { script: {
8954
9283
  type: "string",
8955
9284
  required: true,
8956
- description: "Full JS script body for the heredoc; ego-browser helpers are preloaded. Runs verbatim — call `await taskSpaces.useOrCreate(name)` first if your script uses page.*. End with console.log(JSON.stringify(payload)) to get it back as `result`."
9285
+ description: "Full JS script body for the heredoc; ego-browser helpers are preloaded. Runs verbatim �?call `await taskSpaces.useOrCreate(name)` first if your script uses page.*. End with console.log(JSON.stringify(payload)) to get it back as `result`."
8957
9286
  } },
8958
9287
  output: {
8959
9288
  schema: {
@@ -8980,9 +9309,10 @@ function registerActionTools(ctx, cfg, reg) {
8980
9309
  },
8981
9310
  timeoutMs: TOOL_TIMEOUT_MS,
8982
9311
  execute: async (args, exec) => {
9312
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
8983
9313
  markEgoToolCall(callingSessionId(exec));
8984
9314
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => str(args.script, ""));
8985
- if (!result.ok) throw new Error(result.error);
9315
+ if (!result.ok) throw new Error(attachSessionHint(result.error));
8986
9316
  const parsed = parseSentinel(mergeCliOutput(result));
8987
9317
  return {
8988
9318
  ok: true,
@@ -9005,7 +9335,7 @@ function registerActionTools(ctx, cfg, reg) {
9005
9335
  function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9006
9336
  reg(defineTool({
9007
9337
  name: "bcdp_captcha",
9008
- description: "Check the current page for a human-verification (CAPTCHA) challenge — reCAPTCHA / hCaptcha / Cloudflare / Turnstile — and return { detected, kind }. If detected=true, ALERT THE USER that they must complete the verification in the 'ego lite - agent' browser window (it is the same live session shown in the watch panel), then continue after they have.",
9338
+ description: "Check the current page for a human-verification (CAPTCHA) challenge �?reCAPTCHA / hCaptcha / Cloudflare / Turnstile �?and return { detected, kind }. If detected=true, ALERT THE USER that they must complete the verification in the 'ego lite - agent' browser window (it is the same live session shown in the watch panel), then continue after they have.",
9009
9339
  parameters: { space: {
9010
9340
  type: "string",
9011
9341
  description: "Task-space name or numeric id; defaults to the configured defaultSpace."
@@ -9032,8 +9362,9 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9032
9362
  },
9033
9363
  timeoutMs: 15e3,
9034
9364
  execute: async (args, exec) => withEgoLock(async () => {
9365
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9035
9366
  markEgoToolCall(callingSessionId(exec));
9036
- const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => humanCheckScript(str(args.space, cfg.defaultSpace)));
9367
+ const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => humanCheckScript(str(args.space, cfg.activeSpace)));
9037
9368
  if (!result.ok) return {
9038
9369
  ok: false,
9039
9370
  detected: false,
@@ -9091,7 +9422,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9091
9422
  tiers.pulse();
9092
9423
  const q = str(args.topic, "").trim().toLowerCase();
9093
9424
  const key = Object.prototype.hasOwnProperty.call(EGO_HELP_INDEX, q) ? q : "";
9094
- 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;
9425
+ 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;
9095
9426
  return {
9096
9427
  ok: true,
9097
9428
  topic: q || "overview",
@@ -9136,7 +9467,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9136
9467
  jevKey: cfg.jevKey,
9137
9468
  layaKey: cfg.layaKey
9138
9469
  });
9139
- 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}`);
9470
+ 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}`);
9140
9471
  }
9141
9472
  lines.push(`egoBin: ${cfg.egoBin}`);
9142
9473
  try {
@@ -9147,7 +9478,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9147
9478
  const chrome = findChromeBinary();
9148
9479
  const configured = cfg.chromePath;
9149
9480
  if (configured) lines.push(`browser binary: ${configured} (from settings)`);
9150
- else lines.push(`browser binary: ${chrome || "(none found — set chromePath in settings, or set EGO_LINUX_CHROME, or install Chrome/Edge/Brave)"}`);
9481
+ else lines.push(`browser binary: ${chrome || "(none found �?set chromePath in settings, or set EGO_LINUX_CHROME, or install Chrome/Edge/Brave)"}`);
9151
9482
  const cliArgs = filterArgs(cfg.runtimeArgs ?? "", EGO_CLI_BLOCKED);
9152
9483
  const chrArgs = filterArgs(cfg.chromeArgs ?? "", CHROME_BLOCKED);
9153
9484
  lines.push(`runtimeArgs (effective): ${cliArgs.length ? cliArgs.join(" ") : "(none)"}`);
@@ -9156,13 +9487,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9156
9487
  lines.push(`attach: ${attachNow.status}${attachNow.endpointSource ? ` (source: ${attachNow.endpointSource})` : ""}${attachNow.endpoint ? ` @ ${attachNow.endpoint}` : ""}`);
9157
9488
  if (attachNow.engine !== void 0) lines.push(`engine: ${attachNow.engine}`);
9158
9489
  if (attachNow.engine === "lightpanda") lines.push("degraded on this engine: live view (no screencast) · panel pick (no Overlay/bindingCalled) · bcdp_download (no Page download events) · screenshots are PNG text-renders · auth_flush is a no-op");
9159
- if (attachNow.engine === "lightpanda" || process.platform === "win32") lines.push(process.platform === "win32" ? "lightpanda on win32: no native build — use WSL2: `wsl --install` (admin), then inside WSL: `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` + `lightpanda serve --host 127.0.0.1 --port 9222`; WSL2 maps the port to Windows localhost, then add http://127.0.0.1:9222 as a CDP endpoint. Docker alternative: `docker run -d -p 127.0.0.1:9222:9222 lightpanda/browser:nightly`." : "lightpanda (linux/macOS): `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` (installs to ~/.local/bin) then `lightpanda serve --host 127.0.0.1 --port 9222`.");
9490
+ if (attachNow.engine === "lightpanda" || process.platform === "win32") lines.push(process.platform === "win32" ? "lightpanda on win32: no native build �?use WSL2: `wsl --install` (admin), then inside WSL: `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` + `lightpanda serve --host 127.0.0.1 --port 9222`; WSL2 maps the port to Windows localhost, then add http://127.0.0.1:9222 as a CDP endpoint. Docker alternative: `docker run -d -p 127.0.0.1:9222:9222 lightpanda/browser:nightly`." : "lightpanda (linux/macOS): `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` (installs to ~/.local/bin) then `lightpanda serve --host 127.0.0.1 --port 9222`.");
9160
9491
  const kindCount = (kind) => cfg.links.filter((link) => link.kind === kind).length;
9161
9492
  const dropped = cfg.droppedEgoCli;
9162
- lines.push(`links: ${cfg.links.length} (cdp ${kindCount("cdp")}, ego-cli ${kindCount(EGO_CLI_KIND)}, lightpanda ${kindCount(LP_KIND)})${dropped > 0 ? ` — ${dropped} extra ego-cli row(s) dropped (local-only singleton)` : ""}`);
9493
+ lines.push(`links: ${cfg.links.length} (cdp ${kindCount("cdp")}, ego-cli ${kindCount(EGO_CLI_KIND)}, lightpanda ${kindCount(LP_KIND)})${dropped > 0 ? ` �?${dropped} extra ego-cli row(s) dropped (local-only singleton)` : ""}`);
9163
9494
  if (kindCount(LP_KIND) > 0) {
9164
9495
  const lpRow = cfg.links.find((link) => link.kind === LP_KIND);
9165
- lines.push(`lightpanda row: servePath=${lpRow?.servePath === void 0 || lpRow.servePath === "" ? "(auto: PATH → ~/.local/bin; win32 via WSL2)" : lpRow.servePath} — headless quick-trial engine; headed kinds (CDP / local Chrome / ego CLI) are the manual-fallback backstop`);
9496
+ lines.push(`lightpanda row: servePath=${lpRow?.servePath === void 0 || lpRow.servePath === "" ? "(auto: PATH �?~/.local/bin; win32 via WSL2)" : lpRow.servePath} �?headless quick-trial engine; headed kinds (CDP / local Chrome / ego CLI) are the manual-fallback backstop`);
9166
9497
  }
9167
9498
  const cliLink = cfg.links.find((link) => link.kind === EGO_CLI_KIND);
9168
9499
  if (cliLink && cliLink.kind === EGO_CLI_KIND) {
@@ -9170,13 +9501,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9170
9501
  cliPath: cliLink.cliPath,
9171
9502
  bundled: VENDORED_EGO_BIN
9172
9503
  }, createSubprocessCliIo(ctx.subprocess));
9173
- lines.push(resolved.ok ? `cli: ${resolved.path} (${resolved.origin}${attachNow.cliShape ? `, shape ${attachNow.cliShape}` : ""})` : `cli: (missing) — ${resolved.message}`);
9504
+ lines.push(resolved.ok ? `cli: ${resolved.path} (${resolved.origin}${attachNow.cliShape ? `, shape ${attachNow.cliShape}` : ""})` : `cli: (missing) �?${resolved.message}`);
9174
9505
  }
9175
9506
  const toolCount = ((EGO_HELP_INDEX["tools"] ?? "").match(/bcdp_/g) ?? []).length;
9176
9507
  const legacy = cfg.legacyEgoToolNames === true;
9177
9508
  lines.push(`naming: ${toolCount} bcdp_* tools; legacy ego_* aliases ${legacy ? "ON (mutually exclusive with the upstream plugin)" : "OFF (coexists with the upstream plugin)"}`);
9178
9509
  const upstream = findUpstreamPluginInstall();
9179
- if (upstream !== "") lines.push(`conflict: upstream dsh-ego-browser installed at ${upstream} — only one plugin should drive the local ego-lite (they would share its task spaces)`);
9510
+ if (upstream !== "") lines.push(`conflict: upstream dsh-ego-browser installed at ${upstream} �?only one plugin should drive the local ego-lite (they would share its task spaces)`);
9180
9511
  lines.push(`chromeArgs (effective, next cold start): ${chrArgs.length ? chrArgs.join(" ") : "(none)"}`);
9181
9512
  const isWin = process.platform === "win32";
9182
9513
  const e = process.env;
@@ -9184,7 +9515,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9184
9515
  const stateDir = e.EGO_LINUX_STATE_DIR || (isWin ? (e.LOCALAPPDATA || `${home}\\AppData\\Local`) + "\\ego-lite-linux" : `${e.XDG_STATE_HOME || `${home}/.local/state`}/ego-lite-linux`);
9185
9516
  lines.push(`state dir: ${stateDir} (exists: ${existsSync(stateDir)})`);
9186
9517
  const bjson = `${stateDir}/browser.json`;
9187
- let browserReport = "browser.json: (none — agent browser not running)";
9518
+ let browserReport = "browser.json: (none �?agent browser not running)";
9188
9519
  if (existsSync(bjson)) try {
9189
9520
  const { readFile: readFile$1 } = await import("node:fs/promises");
9190
9521
  const b = JSON.parse(await readFile$1(bjson, "utf8"));
@@ -9234,12 +9565,12 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9234
9565
  reg((() => {
9235
9566
  return defineTool({
9236
9567
  name: "bcdp_script",
9237
- 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. Differs from bcdp_cli, which runs the body verbatim with no preamble.",
9568
+ 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. Differs from bcdp_cli, which runs the body verbatim with no preamble. These scripts expose the vendored SDK (`taskSpaces`, `page.locator()`, global `cdp()`, `fetch.browser|server`) �?NOT the official docs' `taskSpace()` / `page.click()`.",
9238
9569
  parameters: {
9239
9570
  script: {
9240
9571
  type: "string",
9241
9572
  required: true,
9242
- description: "Full JS script body. You may end with console.log(JSON.stringify(payload)) — bare or prefixed with the sentinel — and it is returned as `result`. Without one, `output` still carries everything the script printed."
9573
+ description: "Full JS script body. You may end with console.log(JSON.stringify(payload)) �?bare or prefixed with the sentinel �?and it is returned as `result`. Without one, `output` still carries everything the script printed."
9243
9574
  },
9244
9575
  timeoutMs: {
9245
9576
  type: "integer",
@@ -9274,12 +9605,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9274
9605
  },
9275
9606
  timeoutMs: TOOL_TIMEOUT_MS,
9276
9607
  execute: async (args, exec) => {
9608
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9277
9609
  markEgoToolCall(callingSessionId(exec));
9278
9610
  const timeoutMs = typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0 ? args.timeoutMs : void 0;
9279
9611
  const start = Date.now();
9280
9612
  const preamble = (body) => {
9281
9613
  if (/taskSpaces\s*\.\s*useOrCreate\s*\(/.test(body)) return body;
9282
- return `${useSpace(cfg.defaultSpace)}${ensureRealTab()}${body}`;
9614
+ return `${useSpace(cfg.activeSpace)}${ensureRealTab()}${body}`;
9283
9615
  };
9284
9616
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => preamble(str(args.script, "")), timeoutMs);
9285
9617
  const durationMs = Date.now() - start;
@@ -9287,10 +9619,10 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9287
9619
  ok: false,
9288
9620
  stdout: result.stdout,
9289
9621
  stderr: result.stderr,
9290
- output: mergeCliOutput(result),
9622
+ output: attachSessionHint(mergeCliOutput(result)),
9291
9623
  durationMs,
9292
9624
  timedOut: false,
9293
- error: result.error
9625
+ error: attachSessionHint(result.error)
9294
9626
  };
9295
9627
  const parsed = parseSentinel(mergeCliOutput(result));
9296
9628
  return {
@@ -9335,7 +9667,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9335
9667
  stepBudget: cfg.jevStepBudget,
9336
9668
  wallMs: cfg.jevWallMs
9337
9669
  });
9338
- /** Build the intent from tool args. Hints stay hints — never selectors. */
9670
+ /** Build the intent from tool args. Hints stay hints �?never selectors. */
9339
9671
  const intentFrom = (args) => {
9340
9672
  const hints = str(args.hints, "");
9341
9673
  const criteria = str(args.successCriteria, "");
@@ -9405,6 +9737,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9405
9737
  },
9406
9738
  timeoutMs: 1e4,
9407
9739
  execute: async (_args, exec) => {
9740
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9408
9741
  markEgoToolCall(callingSessionId(exec));
9409
9742
  const judge = judgeCfg();
9410
9743
  const runtime = judgeRuntimeOf();
@@ -9426,7 +9759,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9426
9759
  "",
9427
9760
  `browser attach : ${attach.wsUrl === "" ? `NOT ATTACHED (status=${attach.status}${attach.code === "" ? "" : `, code=${attach.code}`})` : `${attach.endpoint} (${attach.endpointSource ?? "unknown"})`}`
9428
9761
  ];
9429
- if (judge.layaKey === "") lines.push("", "laya has no key, so that hop is SKIPPED — the chain is running on the offline rule hop alone.", "laya-api has no anonymous branch, so a keyless call is a guaranteed 401; skipping it is deliberate.", "", "To bring laya up locally:", " 1. start the sidecar (it serves 8000, and JevLoop's 7789 is a different tool):", " ENGINE=laya LAYA_PRELOAD=true LAYA_DEVICE=cpu uvicorn laya_api.main:app", " with ALLOW_DEV_LOGIN=true you can sign in without Google.", " 2. open http://localhost:8000, create an API key (it is shown once, format laya_...).", " 3. paste it into this panel's Laya key field and save.");
9762
+ if (judge.layaKey === "") lines.push("", "laya has no key, so that hop is SKIPPED �?the chain is running on the offline rule hop alone.", "laya-api has no anonymous branch, so a keyless call is a guaranteed 401; skipping it is deliberate.", "", "To bring laya up locally:", " 1. start the sidecar (it serves 8000, and JevLoop's 7789 is a different tool):", " ENGINE=laya LAYA_PRELOAD=true LAYA_DEVICE=cpu uvicorn laya_api.main:app", " with ALLOW_DEV_LOGIN=true you can sign in without Google.", " 2. open http://localhost:8000, create an API key (it is shown once, format laya_...).", " 3. paste it into this panel's Laya key field and save.");
9430
9763
  return {
9431
9764
  ok: true,
9432
9765
  text: lines.join("\n")
@@ -9504,6 +9837,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9504
9837
  },
9505
9838
  timeoutMs: 6e4,
9506
9839
  execute: async (args, exec) => {
9840
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9507
9841
  markEgoToolCall(callingSessionId(exec));
9508
9842
  const blocked = attachGate();
9509
9843
  if (blocked !== "") return {
@@ -9576,7 +9910,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9576
9910
  if (assembland !== null) {
9577
9911
  lines.push(`POST : ${assembland.url}`);
9578
9912
  lines.push("", "── assembled request body (exactly the three allowed keys) ──", JSON.stringify(assembland.body, null, 2));
9579
- } else lines.push("", "(no HTTP hop configured — only the rule hop is available)");
9913
+ } else lines.push("", "(no HTTP hop configured �?only the rule hop is available)");
9580
9914
  if (bool(args.dryRun, true)) {
9581
9915
  lines.push("", "dryRun: nothing was sent.");
9582
9916
  return {
@@ -9642,6 +9976,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9642
9976
  },
9643
9977
  timeoutMs: 6e4,
9644
9978
  execute: async (args, exec) => {
9979
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9645
9980
  markEgoToolCall(callingSessionId(exec));
9646
9981
  const blocked = attachGate();
9647
9982
  if (blocked !== "") return {
@@ -9679,13 +10014,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9679
10014
  `budget : ${frame.image === null || frame.image.maxBytes === 0 ? "unbounded" : frame.image.maxBytes + " B"}${frame.image?.overBudget === true ? " *** OVER BUDGET ***" : ""}`,
9680
10015
  `candidates : ${frame.dom.nodes.length} of ${frame.dom.total}${frame.dom.truncated ? " (TRUNCATED)" : ""}`
9681
10016
  ];
9682
- if (defaultAttachCache.get().engine === "lightpanda") lines.push(`engine : lightpanda (rendering: text — screenshot fidelity differs from Chrome)`);
10017
+ if (defaultAttachCache.get().engine === "lightpanda") lines.push(`engine : lightpanda (rendering: text �?screenshot fidelity differs from Chrome)`);
9683
10018
  if (frame.image?.overBudget === true) lines.push("", "The image exceeded the byte budget even at floor quality. Raise jevMaxImageBytes, or accept it and let the count drive chunking.");
9684
10019
  if (bool(args.showCandidates, true)) {
9685
10020
  lines.push("", "── candidates (the judge answers with these numbers) ──");
9686
10021
  for (const node of frame.dom.nodes) lines.push(`${node.n}. ${node.role} "${node.name}" [${node.container}]`);
9687
10022
  }
9688
- lines.push("", "note: rects are NOT carried on this path (the AX tree has none) — the executor re-measures before any action.");
10023
+ lines.push("", "note: rects are NOT carried on this path (the AX tree has none) �?the executor re-measures before any action.");
9689
10024
  return {
9690
10025
  ok: true,
9691
10026
  text: lines.join("\n")
@@ -9751,6 +10086,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9751
10086
  },
9752
10087
  timeoutMs: TOOL_TIMEOUT_MS,
9753
10088
  execute: async (args, exec) => {
10089
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9754
10090
  markEgoToolCall(callingSessionId(exec));
9755
10091
  const blocked = attachGate();
9756
10092
  if (blocked !== "") return {
@@ -9848,6 +10184,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9848
10184
  },
9849
10185
  timeoutMs: TOOL_TIMEOUT_MS,
9850
10186
  execute: async (args, exec) => {
10187
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9851
10188
  markEgoToolCall(callingSessionId(exec));
9852
10189
  const blocked = attachGate();
9853
10190
  if (blocked !== "") return {
@@ -9880,7 +10217,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9880
10217
  const nav = await effects.navigate(url);
9881
10218
  if (!nav.ok) return {
9882
10219
  ok: false,
9883
- text: `bcdp_jev_attempt: navigation failed — ${nav.error ?? "unknown error"}`
10220
+ text: `bcdp_jev_attempt: navigation failed �?${nav.error ?? "unknown error"}`
9884
10221
  };
9885
10222
  const result = await runAttempt({
9886
10223
  intent,
@@ -9892,7 +10229,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9892
10229
  `reason : ${result.reason}`,
9893
10230
  `page : ${result.lastUrl || nav.url}`,
9894
10231
  `elapsed : ${Date.now() - started}ms candidates(last round)=${result.candidates}`,
9895
- `verify via : bcdp_cdp / bcdp_screenshot on targetId=${effects.frames().at(-1)?.target.targetId ?? "unknown"} — the receipt is a report, not a proof`
10232
+ `verify via : bcdp_cdp / bcdp_screenshot on targetId=${effects.frames().at(-1)?.target.targetId ?? "unknown"} �?the receipt is a report, not a proof`
9896
10233
  ];
9897
10234
  if (effects.lastError() !== "") lines.push(`lastError : ${effects.lastError()}`);
9898
10235
  lines.push("", result.actions.length === 0 ? "── actions ── (none)" : "── actions ──");
@@ -9914,4 +10251,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9914
10251
  }
9915
10252
 
9916
10253
  //#endregion
9917
- export { Config, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, apply, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, decideCdpAttach, findChromeBinary, findUpstreamPluginInstall, inject, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, shouldReapBrowser };
10254
+ 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, shouldReapBrowser };