dsh-browser-cdp 1.3.1 → 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
@@ -7434,18 +7580,61 @@ function parseSentinel(stdout) {
7434
7580
  return;
7435
7581
  }
7436
7582
  }
7437
- for (let i = lines.length - 1; i >= 0; i--) {
7438
- const text = lines[i].trim();
7439
- if (text.length < 2 || text[0] !== "{" || text[text.length - 1] !== "}") continue;
7583
+ return lastJsonObject(stdout);
7584
+ }
7585
+ /**
7586
+ * The last balanced `{...}` run in `text` that parses as a JSON object.
7587
+ *
7588
+ * Tracks double-quoted strings (JSON's only string syntax) so braces inside a
7589
+ * string value do not unbalance the scan. Invalid candidates are skipped, not
7590
+ * fatal: log noise before the payload is common.
7591
+ *
7592
+ * A candidate must begin its own line (leading whitespace is fine). That keeps
7593
+ * pretty-printed payloads working while refusing an object merely mentioned in
7594
+ * prose: `[warn] retrying {"attempt":2}` must not become the result, because a
7595
+ * silently wrong payload is worse than no payload at all.
7596
+ */
7597
+ function lastJsonObject(text) {
7598
+ let best;
7599
+ let depth = 0;
7600
+ let start = -1;
7601
+ let inString = false;
7602
+ let escaped = false;
7603
+ for (let i = 0; i < text.length; i++) {
7604
+ const c = text[i];
7605
+ if (inString) {
7606
+ if (escaped) escaped = false;
7607
+ else if (c === "\\") escaped = true;
7608
+ else if (c === "\"") inString = false;
7609
+ continue;
7610
+ }
7611
+ if (c === "\"") {
7612
+ inString = true;
7613
+ continue;
7614
+ }
7615
+ if (c === "{") {
7616
+ if (depth === 0) start = i;
7617
+ depth += 1;
7618
+ continue;
7619
+ }
7620
+ if (c !== "}") continue;
7621
+ if (depth === 0) continue;
7622
+ depth -= 1;
7623
+ if (depth !== 0 || start < 0) continue;
7624
+ let p = start - 1;
7625
+ while (p >= 0 && (text[p] === " " || text[p] === " " || text[p] === "\r")) p -= 1;
7626
+ const atLineStart = p < 0 || text[p] === "\n";
7440
7627
  try {
7441
- const parsed = JSON.parse(text);
7442
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
7628
+ const parsed = atLineStart ? JSON.parse(text.slice(start, i + 1)) : null;
7629
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) best = parsed;
7443
7630
  } catch {}
7631
+ start = -1;
7444
7632
  }
7633
+ return best;
7445
7634
  }
7446
- /** 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 */
7447
7636
  const STATUS_FACADE_SENTINEL = "__BCDP_STATUS__";
7448
- /** @internal exported for tests — the exact heredoc the status probe runs. */
7637
+ /** @internal exported for tests �?the exact heredoc the status probe runs. */
7449
7638
  const STATUS_FACADE_SCRIPT = `console.log(${JSON.stringify(STATUS_FACADE_SENTINEL)} + JSON.stringify({ taskSpaces: typeof taskSpaces, browser: typeof browser, page: typeof page }))
7450
7639
  `;
7451
7640
  /**
@@ -7471,7 +7660,7 @@ function parseStatusFacades(stdout) {
7471
7660
  }
7472
7661
  }
7473
7662
  /**
7474
- * R7 — is the upstream plugin installed anywhere under this DSH home?
7663
+ * R7 �?is the upstream plugin installed anywhere under this DSH home?
7475
7664
  *
7476
7665
  * Reported (never enforced): the two plugins can coexist now that tool names
7477
7666
  * and routes no longer overlap, but both driving ONE local ego-lite would
@@ -7489,7 +7678,7 @@ function findUpstreamPluginInstall(home = process.env.HOME || process.env.USERPR
7489
7678
  return "";
7490
7679
  }
7491
7680
  /**
7492
- * 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`
7493
7682
  * injection: `bcdp_status` and `runEgoScript` must probe/run under the exact
7494
7683
  * same conditions, otherwise "available" and "actually works" diverge again.
7495
7684
  * @internal exported for tests
@@ -7587,6 +7776,22 @@ const useSpace = (name$1) => `const task = await taskSpaces.useOrCreate(${j(name
7587
7776
  * before acting makes cross-process tool calls deterministic.
7588
7777
  */
7589
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
+ }
7590
7795
  function renderText(_args, value) {
7591
7796
  const v = value;
7592
7797
  if (v !== null && typeof v === "object" && v.ok === true && typeof v.text === "string") return [{
@@ -7607,7 +7812,7 @@ const commonOutputSchema = {
7607
7812
  } }
7608
7813
  };
7609
7814
  /**
7610
- * 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.
7611
7816
  * Read structurally (`exec.agent` is typed `unknown` in this plugin's own
7612
7817
  * seam); a call with no initiating agent simply leaves the open unscoped.
7613
7818
  */
@@ -7626,6 +7831,7 @@ function defineEgoTool(ctx, cfg, opts) {
7626
7831
  },
7627
7832
  timeoutMs: TOOL_TIMEOUT_MS,
7628
7833
  execute: async (args, exec) => withEgoLock(async () => {
7834
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
7629
7835
  markEgoToolCall(callingSessionId(exec));
7630
7836
  if (typeof opts.gate === "function") {
7631
7837
  const blocked = opts.gate(args);
@@ -7634,6 +7840,13 @@ function defineEgoTool(ctx, cfg, opts) {
7634
7840
  text: blocked
7635
7841
  };
7636
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
+ }
7637
7850
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => opts.buildScript(args));
7638
7851
  if (!result.ok) throw new Error(result.error);
7639
7852
  if (typeof opts.afterExecute === "function") opts.afterExecute(args, result.value);
@@ -7655,12 +7868,17 @@ function apply(ctx, config = {}) {
7655
7868
  configuredPath: initialFfmpegConfig.ffmpegPath,
7656
7869
  requestedEncoder: initialFfmpegConfig.ffmpegEncoder
7657
7870
  }).catch(() => {});
7658
- const spaceTracker = createActiveSpaceTracker(config.defaultSpace ?? DEFAULT_SPACE);
7871
+ const spaceTracker = createSessionSpaceTracker((sessionKey) => deriveSlotDefaultName(resolveConfig(bridge.source()), sessionKey));
7659
7872
  const cfg = {
7660
7873
  egoBin: typeof config.egoBin === "string" && config.egoBin !== "" ? config.egoBin : DEFAULT_EGO_BIN,
7661
- configuredDefaultSpace: config.defaultSpace ?? DEFAULT_SPACE,
7874
+ get configuredDefaultSpace() {
7875
+ return resolveConfig(bridge.source()).defaultSpace;
7876
+ },
7662
7877
  spaceTracker,
7663
7878
  get defaultSpace() {
7879
+ return resolveConfig(bridge.source()).defaultSpace;
7880
+ },
7881
+ get activeSpace() {
7664
7882
  return this.spaceTracker.current();
7665
7883
  },
7666
7884
  maxOutputBytes: config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
@@ -7843,9 +8061,8 @@ function apply(ctx, config = {}) {
7843
8061
  logger: ctx.logger
7844
8062
  });
7845
8063
  /**
7846
- * 活动信号:每次 bcdp_* 调用推进 browse 批次(act → observe → wait),
7847
- * 到顶即止。只有注入面真的变了才 reapply。
7848
- */
8064
+ * 活动信号:每�?bcdp_* 调用推进 browse 批次(act �?observe �?wait),
8065
+ * 到顶即止。只有注入面真的变了�?reapply�? */
7849
8066
  const pulseActivity = () => {
7850
8067
  const before = browseBatchDepth;
7851
8068
  browserActive = true;
@@ -7857,9 +8074,8 @@ function apply(ctx, config = {}) {
7857
8074
  ctx.effect?.(() => offActivity);
7858
8075
  }
7859
8076
  /**
7860
- * 闲置回收后把注入面收回 core 级(lazy 模式专属):浏览器已经停了,模型
7861
- * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开。
7862
- */
8077
+ * 闲置回收后把注入面收�?core 级(lazy 模式专属):浏览器已经停了,模型
8078
+ * 面上留着 30 多个驱动它的工具只是白付。下一次活动会重新铺开�? */
7863
8079
  const sealAfterReap = () => {
7864
8080
  if (cfg.toolInjection !== "lazy" || !browserActive) return;
7865
8081
  browserActive = false;
@@ -7867,9 +8083,7 @@ function apply(ctx, config = {}) {
7867
8083
  tiers.reapply();
7868
8084
  };
7869
8085
  /**
7870
- * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动;
7871
- * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)。
7872
- */
8086
+ * 常驻级工具看到的分级视图:`pulse` = 把本次调用当成一次浏览器活动�? * `surface` = 当前注入面(doctor 直接打出来,开关状态得看得见)�? */
7873
8087
  const tierView = {
7874
8088
  pulse: pulseActivity,
7875
8089
  active: () => browserActive,
@@ -8061,7 +8275,7 @@ function apply(ctx, config = {}) {
8061
8275
  }).done.catch(() => {});
8062
8276
  } catch {}
8063
8277
  });
8064
- 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})`);
8065
8279
  }
8066
8280
  /** `bcdp_status` probes the SAME channel work uses: a `nodejs` heredoc. */
8067
8281
  function registerEgoStatus(ctx, cfg, reg, tiers) {
@@ -8145,11 +8359,11 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
8145
8359
  })
8146
8360
  }));
8147
8361
  }
8148
- /** `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. */
8149
8363
  function registerAuthFlush(ctx, cfg, reg) {
8150
8364
  reg(defineTool({
8151
8365
  name: "bcdp_auth_flush",
8152
- 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.",
8153
8367
  parameters: {},
8154
8368
  output: {
8155
8369
  schema: {
@@ -8200,7 +8414,7 @@ function registerAuthFlush(ctx, cfg, reg) {
8200
8414
  flushed: jbody.flushed ?? 0,
8201
8415
  ...degraded ? {
8202
8416
  degraded: true,
8203
- 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"
8204
8418
  } : {},
8205
8419
  ...!degraded && jbody.error !== void 0 ? { error: jbody.error } : {}
8206
8420
  };
@@ -8219,7 +8433,7 @@ function registerAuthFlush(ctx, cfg, reg) {
8219
8433
  })
8220
8434
  }));
8221
8435
  }
8222
- /** `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). */
8223
8437
  function registerLoginImport(ctx, cfg, reg) {
8224
8438
  reg(defineTool({
8225
8439
  name: "bcdp_login_import",
@@ -8281,7 +8495,7 @@ function registerLoginImport(ctx, cfg, reg) {
8281
8495
  "auto"
8282
8496
  ].includes(source)) return {
8283
8497
  ok: false,
8284
- error: `invalid source "${source}" — expected chrome|edge|brave|auto`
8498
+ error: `invalid source "${source}" �?expected chrome|edge|brave|auto`
8285
8499
  };
8286
8500
  return await importLoginCookies({
8287
8501
  source,
@@ -8324,7 +8538,7 @@ function registerActionTools(ctx, cfg, reg) {
8324
8538
  reg(t({
8325
8539
  name: "bcdp_space_open",
8326
8540
  get description() {
8327
- 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.";
8328
8542
  },
8329
8543
  parameters: { name: {
8330
8544
  type: "string",
@@ -8333,7 +8547,7 @@ function registerActionTools(ctx, cfg, reg) {
8333
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.";
8334
8548
  }
8335
8549
  } },
8336
- 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`
8337
8551
  }));
8338
8552
  reg(t({
8339
8553
  name: "bcdp_space_close",
@@ -8351,32 +8565,87 @@ function registerActionTools(ctx, cfg, reg) {
8351
8565
  description: "Keep the live page open (default false: close it)."
8352
8566
  }
8353
8567
  },
8354
- 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
+ }
8355
8594
  }));
8356
8595
  reg(t({
8357
8596
  name: "bcdp_snapshot",
8358
- 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.",
8359
8598
  parameters: {
8360
8599
  space: spaceParam,
8361
8600
  scope: {
8362
8601
  type: "string",
8363
- 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."
8364
8607
  }
8365
8608
  },
8366
8609
  buildScript: (args) => {
8367
8610
  const scope = str(args.scope, "");
8368
- const call = scope === "" ? "await page.snapshotRaw()" : `await page.snapshotRaw({ scope: ${j(scope)} })`;
8369
- 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`;
8370
8630
  }
8371
8631
  }));
8372
8632
  reg(t({
8373
8633
  name: "bcdp_navigate",
8374
- 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,
8375
8636
  parameters: {
8376
8637
  url: {
8377
8638
  type: "string",
8378
8639
  required: true,
8379
- 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."
8380
8649
  },
8381
8650
  wait: {
8382
8651
  type: "boolean",
@@ -8390,8 +8659,9 @@ function registerActionTools(ctx, cfg, reg) {
8390
8659
  },
8391
8660
  buildScript: (args) => {
8392
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`;
8393
8663
  if (u === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reused: false, page: null, reason: 'bcdp_navigate: url is required' }))\n`;
8394
- 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`;
8395
8665
  }
8396
8666
  }));
8397
8667
  reg(t({
@@ -8431,7 +8701,7 @@ function registerActionTools(ctx, cfg, reg) {
8431
8701
  const labelOpt = str(args.label, "") !== "" ? `{ label: ${j(str(args.label, ""))} }` : "";
8432
8702
  action = dbl ? `await page.locator(${j(sel)}).dblclick(${labelOpt})` : `await page.locator(${j(sel)}).click(${labelOpt})`;
8433
8703
  } else action = dbl ? `await page.mouse.dblclick(${x}, ${y})` : `await page.mouse.click(${x}, ${y})`;
8434
- 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`;
8435
8705
  }
8436
8706
  }));
8437
8707
  reg(t({
@@ -8450,7 +8720,7 @@ function registerActionTools(ctx, cfg, reg) {
8450
8720
  },
8451
8721
  space: spaceParam
8452
8722
  },
8453
- 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`
8454
8724
  }));
8455
8725
  reg(t({
8456
8726
  name: "bcdp_js",
@@ -8463,7 +8733,7 @@ function registerActionTools(ctx, cfg, reg) {
8463
8733
  },
8464
8734
  space: spaceParam
8465
8735
  },
8466
- 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`
8467
8737
  }));
8468
8738
  reg(t({
8469
8739
  name: "bcdp_cdp",
@@ -8484,7 +8754,7 @@ function registerActionTools(ctx, cfg, reg) {
8484
8754
  buildScript: (args) => {
8485
8755
  const params = args.params;
8486
8756
  const call = params !== void 0 && params !== null ? `await cdp(${j(str(args.method, ""))}, ${j(params)})` : `await cdp(${j(str(args.method, ""))})`;
8487
- 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`;
8488
8758
  }
8489
8759
  }));
8490
8760
  reg(t({
@@ -8505,14 +8775,62 @@ function registerActionTools(ctx, cfg, reg) {
8505
8775
  const sel = str(args.selector, "");
8506
8776
  const pth = str(args.path, "");
8507
8777
  const shot = sel !== "" ? `await page.locator(${j(sel)}).screenshot(${pth ? `{ path: ${j(pth)} }` : ""})` : `await page.screenshot(${pth ? `{ path: ${j(pth)} }` : ""})`;
8508
- 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`;
8509
8779
  }
8510
8780
  }));
8511
8781
  reg(t({
8512
8782
  name: "bcdp_page_info",
8513
- 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).",
8514
8784
  parameters: { space: spaceParam },
8515
- 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
+ }
8516
8834
  }));
8517
8835
  reg(t({
8518
8836
  name: "bcdp_wait",
@@ -8546,7 +8864,7 @@ function registerActionTools(ctx, cfg, reg) {
8546
8864
  buildScript: (args) => {
8547
8865
  const sel = str(args.selector, "").trim();
8548
8866
  if (sel === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, waited: false, reason: 'bcdp_wait_for_selector: selector is required' }))\n`;
8549
- 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`;
8550
8868
  }
8551
8869
  }));
8552
8870
  reg(t({
@@ -8567,7 +8885,7 @@ function registerActionTools(ctx, cfg, reg) {
8567
8885
  buildScript: (args) => {
8568
8886
  const p = str(args.pattern, "").trim();
8569
8887
  if (p === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reached: false, reason: 'bcdp_wait_for_url: pattern is required' }))\n`;
8570
- 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`;
8571
8889
  }
8572
8890
  }));
8573
8891
  reg(t({
@@ -8593,7 +8911,54 @@ function registerActionTools(ctx, cfg, reg) {
8593
8911
  const u = str(args.url, "").trim();
8594
8912
  const mode = str(args.body, "none");
8595
8913
  const wantBody = mode === "text" || mode === "json";
8596
- 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")} }`);
8597
8962
  }
8598
8963
  }));
8599
8964
  reg(t({
@@ -8608,14 +8973,21 @@ function registerActionTools(ctx, cfg, reg) {
8608
8973
  type: "string",
8609
8974
  description: "Type this text instead (keyboard.type)."
8610
8975
  },
8976
+ via: {
8977
+ type: "string",
8978
+ description: "text mode: 'type' (default, per-character) | 'insert' (keyboard.insertText, faster for long strings)."
8979
+ },
8611
8980
  space: spaceParam
8612
8981
  },
8613
8982
  buildScript: (args) => {
8614
8983
  const txt = str(args.text, "");
8615
8984
  const k = str(args.key, "").trim();
8616
- 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
+ }
8617
8989
  if (k === "") return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_key: provide key or text to type' }))\n`;
8618
- 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`;
8619
8991
  }
8620
8992
  }));
8621
8993
  reg(t({
@@ -8640,7 +9012,7 @@ function registerActionTools(ctx, cfg, reg) {
8640
9012
  const sel = str(args.selector, "");
8641
9013
  const hasXY = typeof args.x === "number" && typeof args.y === "number";
8642
9014
  if (sel === "" && !hasXY) return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_hover: provide selector or both x and y' }))\n`;
8643
- 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`;
8644
9016
  }
8645
9017
  }));
8646
9018
  reg(t({
@@ -8689,7 +9061,7 @@ function registerActionTools(ctx, cfg, reg) {
8689
9061
  break;
8690
9062
  default: expr = `await ${selExpr}.textContent()`;
8691
9063
  }
8692
- 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`;
8693
9065
  }
8694
9066
  }));
8695
9067
  reg(t({
@@ -8707,7 +9079,7 @@ function registerActionTools(ctx, cfg, reg) {
8707
9079
  },
8708
9080
  space: spaceParam
8709
9081
  },
8710
- 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`
8711
9083
  }));
8712
9084
  reg(t({
8713
9085
  name: "bcdp_drag",
@@ -8733,7 +9105,7 @@ function registerActionTools(ctx, cfg, reg) {
8733
9105
  const hasEl = str(args.from, "") !== "" && str(args.to, "") !== "";
8734
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`;
8735
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`;
8736
- 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`;
8737
9109
  }
8738
9110
  }));
8739
9111
  reg(t({
@@ -8759,7 +9131,7 @@ function registerActionTools(ctx, cfg, reg) {
8759
9131
  const hasDelta = Number.isFinite(args.deltaX) || Number.isFinite(args.deltaY);
8760
9132
  if (!hasSelector && !hasDelta) return `console.log('${SENTINEL}' + JSON.stringify({ ok: false, reason: 'bcdp_scroll: provide deltaX/deltaY or a selector' }))\n`;
8761
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`;
8762
- 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`;
8763
9135
  }
8764
9136
  }));
8765
9137
  reg(t({
@@ -8778,7 +9150,7 @@ function registerActionTools(ctx, cfg, reg) {
8778
9150
  },
8779
9151
  space: spaceParam
8780
9152
  },
8781
- 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`
8782
9154
  }));
8783
9155
  reg(t({
8784
9156
  name: "bcdp_download",
@@ -8802,15 +9174,15 @@ function registerActionTools(ctx, cfg, reg) {
8802
9174
  },
8803
9175
  space: spaceParam
8804
9176
  },
8805
- 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,
8806
9178
  buildScript: (args) => {
8807
9179
  const sel = str(args.triggerSelector, "");
8808
9180
  const script = str(args.triggerScript, "");
8809
9181
  const savePath = str(args.savePath, "");
8810
9182
  const timeout = num(args.timeout, 3e4);
8811
- 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";
8812
9184
  const save = savePath !== "" ? `const __final = await __dl.saveAs(${j(savePath)}).catch(()=>null)\n` : `const __final = await __dl.path().catch(()=>null)\n`;
8813
- 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`;
8814
9186
  }
8815
9187
  }));
8816
9188
  reg(t({
@@ -8830,7 +9202,7 @@ function registerActionTools(ctx, cfg, reg) {
8830
9202
  },
8831
9203
  buildScript: (args) => {
8832
9204
  const chk = bool(args.checked, true);
8833
- 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`;
8834
9206
  }
8835
9207
  }));
8836
9208
  reg(t({
@@ -8851,7 +9223,7 @@ function registerActionTools(ctx, cfg, reg) {
8851
9223
  const accept = bool(args.accept, true);
8852
9224
  const text = str(args.text, "");
8853
9225
  const params = `{ accept: ${accept}${text !== "" ? `, promptText: ${j(text)}` : ""} }`;
8854
- 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`;
8855
9227
  }
8856
9228
  }));
8857
9229
  reg(t({
@@ -8900,17 +9272,17 @@ function registerActionTools(ctx, cfg, reg) {
8900
9272
  const mode = str(args.mode, "browser");
8901
9273
  const cred = str(args.credentials, "");
8902
9274
  if (mode !== "server" && (cred === "include" || cred === "omit" || cred === "same-origin")) opts.credentials = cred;
8903
- 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`;
8904
9276
  }
8905
9277
  }));
8906
9278
  reg((() => {
8907
9279
  return defineTool({
8908
9280
  name: "bcdp_cli",
8909
- 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()`.",
8910
9282
  parameters: { script: {
8911
9283
  type: "string",
8912
9284
  required: true,
8913
- 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`."
8914
9286
  } },
8915
9287
  output: {
8916
9288
  schema: {
@@ -8937,9 +9309,10 @@ function registerActionTools(ctx, cfg, reg) {
8937
9309
  },
8938
9310
  timeoutMs: TOOL_TIMEOUT_MS,
8939
9311
  execute: async (args, exec) => {
9312
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
8940
9313
  markEgoToolCall(callingSessionId(exec));
8941
9314
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => str(args.script, ""));
8942
- if (!result.ok) throw new Error(result.error);
9315
+ if (!result.ok) throw new Error(attachSessionHint(result.error));
8943
9316
  const parsed = parseSentinel(mergeCliOutput(result));
8944
9317
  return {
8945
9318
  ok: true,
@@ -8962,7 +9335,7 @@ function registerActionTools(ctx, cfg, reg) {
8962
9335
  function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
8963
9336
  reg(defineTool({
8964
9337
  name: "bcdp_captcha",
8965
- 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.",
8966
9339
  parameters: { space: {
8967
9340
  type: "string",
8968
9341
  description: "Task-space name or numeric id; defaults to the configured defaultSpace."
@@ -8989,8 +9362,9 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
8989
9362
  },
8990
9363
  timeoutMs: 15e3,
8991
9364
  execute: async (args, exec) => withEgoLock(async () => {
9365
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
8992
9366
  markEgoToolCall(callingSessionId(exec));
8993
- 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)));
8994
9368
  if (!result.ok) return {
8995
9369
  ok: false,
8996
9370
  detected: false,
@@ -9048,7 +9422,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9048
9422
  tiers.pulse();
9049
9423
  const q = str(args.topic, "").trim().toLowerCase();
9050
9424
  const key = Object.prototype.hasOwnProperty.call(EGO_HELP_INDEX, q) ? q : "";
9051
- 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;
9052
9426
  return {
9053
9427
  ok: true,
9054
9428
  topic: q || "overview",
@@ -9093,7 +9467,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9093
9467
  jevKey: cfg.jevKey,
9094
9468
  layaKey: cfg.layaKey
9095
9469
  });
9096
- 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}`);
9097
9471
  }
9098
9472
  lines.push(`egoBin: ${cfg.egoBin}`);
9099
9473
  try {
@@ -9104,7 +9478,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9104
9478
  const chrome = findChromeBinary();
9105
9479
  const configured = cfg.chromePath;
9106
9480
  if (configured) lines.push(`browser binary: ${configured} (from settings)`);
9107
- 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)"}`);
9108
9482
  const cliArgs = filterArgs(cfg.runtimeArgs ?? "", EGO_CLI_BLOCKED);
9109
9483
  const chrArgs = filterArgs(cfg.chromeArgs ?? "", CHROME_BLOCKED);
9110
9484
  lines.push(`runtimeArgs (effective): ${cliArgs.length ? cliArgs.join(" ") : "(none)"}`);
@@ -9113,13 +9487,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9113
9487
  lines.push(`attach: ${attachNow.status}${attachNow.endpointSource ? ` (source: ${attachNow.endpointSource})` : ""}${attachNow.endpoint ? ` @ ${attachNow.endpoint}` : ""}`);
9114
9488
  if (attachNow.engine !== void 0) lines.push(`engine: ${attachNow.engine}`);
9115
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");
9116
- 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`.");
9117
9491
  const kindCount = (kind) => cfg.links.filter((link) => link.kind === kind).length;
9118
9492
  const dropped = cfg.droppedEgoCli;
9119
- 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)` : ""}`);
9120
9494
  if (kindCount(LP_KIND) > 0) {
9121
9495
  const lpRow = cfg.links.find((link) => link.kind === LP_KIND);
9122
- 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`);
9123
9497
  }
9124
9498
  const cliLink = cfg.links.find((link) => link.kind === EGO_CLI_KIND);
9125
9499
  if (cliLink && cliLink.kind === EGO_CLI_KIND) {
@@ -9127,13 +9501,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9127
9501
  cliPath: cliLink.cliPath,
9128
9502
  bundled: VENDORED_EGO_BIN
9129
9503
  }, createSubprocessCliIo(ctx.subprocess));
9130
- 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}`);
9131
9505
  }
9132
9506
  const toolCount = ((EGO_HELP_INDEX["tools"] ?? "").match(/bcdp_/g) ?? []).length;
9133
9507
  const legacy = cfg.legacyEgoToolNames === true;
9134
9508
  lines.push(`naming: ${toolCount} bcdp_* tools; legacy ego_* aliases ${legacy ? "ON (mutually exclusive with the upstream plugin)" : "OFF (coexists with the upstream plugin)"}`);
9135
9509
  const upstream = findUpstreamPluginInstall();
9136
- 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)`);
9137
9511
  lines.push(`chromeArgs (effective, next cold start): ${chrArgs.length ? chrArgs.join(" ") : "(none)"}`);
9138
9512
  const isWin = process.platform === "win32";
9139
9513
  const e = process.env;
@@ -9141,7 +9515,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9141
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`);
9142
9516
  lines.push(`state dir: ${stateDir} (exists: ${existsSync(stateDir)})`);
9143
9517
  const bjson = `${stateDir}/browser.json`;
9144
- let browserReport = "browser.json: (none — agent browser not running)";
9518
+ let browserReport = "browser.json: (none �?agent browser not running)";
9145
9519
  if (existsSync(bjson)) try {
9146
9520
  const { readFile: readFile$1 } = await import("node:fs/promises");
9147
9521
  const b = JSON.parse(await readFile$1(bjson, "utf8"));
@@ -9191,12 +9565,12 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9191
9565
  reg((() => {
9192
9566
  return defineTool({
9193
9567
  name: "bcdp_script",
9194
- 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()`.",
9195
9569
  parameters: {
9196
9570
  script: {
9197
9571
  type: "string",
9198
9572
  required: true,
9199
- 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."
9200
9574
  },
9201
9575
  timeoutMs: {
9202
9576
  type: "integer",
@@ -9231,12 +9605,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9231
9605
  },
9232
9606
  timeoutMs: TOOL_TIMEOUT_MS,
9233
9607
  execute: async (args, exec) => {
9608
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9234
9609
  markEgoToolCall(callingSessionId(exec));
9235
9610
  const timeoutMs = typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0 ? args.timeoutMs : void 0;
9236
9611
  const start = Date.now();
9237
9612
  const preamble = (body) => {
9238
9613
  if (/taskSpaces\s*\.\s*useOrCreate\s*\(/.test(body)) return body;
9239
- return `${useSpace(cfg.defaultSpace)}${ensureRealTab()}${body}`;
9614
+ return `${useSpace(cfg.activeSpace)}${ensureRealTab()}${body}`;
9240
9615
  };
9241
9616
  const result = await runWithStaleSpaceRetry(ctx, cfg, exec, () => preamble(str(args.script, "")), timeoutMs);
9242
9617
  const durationMs = Date.now() - start;
@@ -9244,10 +9619,10 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9244
9619
  ok: false,
9245
9620
  stdout: result.stdout,
9246
9621
  stderr: result.stderr,
9247
- output: mergeCliOutput(result),
9622
+ output: attachSessionHint(mergeCliOutput(result)),
9248
9623
  durationMs,
9249
9624
  timedOut: false,
9250
- error: result.error
9625
+ error: attachSessionHint(result.error)
9251
9626
  };
9252
9627
  const parsed = parseSentinel(mergeCliOutput(result));
9253
9628
  return {
@@ -9292,7 +9667,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9292
9667
  stepBudget: cfg.jevStepBudget,
9293
9668
  wallMs: cfg.jevWallMs
9294
9669
  });
9295
- /** Build the intent from tool args. Hints stay hints — never selectors. */
9670
+ /** Build the intent from tool args. Hints stay hints �?never selectors. */
9296
9671
  const intentFrom = (args) => {
9297
9672
  const hints = str(args.hints, "");
9298
9673
  const criteria = str(args.successCriteria, "");
@@ -9362,6 +9737,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9362
9737
  },
9363
9738
  timeoutMs: 1e4,
9364
9739
  execute: async (_args, exec) => {
9740
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9365
9741
  markEgoToolCall(callingSessionId(exec));
9366
9742
  const judge = judgeCfg();
9367
9743
  const runtime = judgeRuntimeOf();
@@ -9383,7 +9759,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9383
9759
  "",
9384
9760
  `browser attach : ${attach.wsUrl === "" ? `NOT ATTACHED (status=${attach.status}${attach.code === "" ? "" : `, code=${attach.code}`})` : `${attach.endpoint} (${attach.endpointSource ?? "unknown"})`}`
9385
9761
  ];
9386
- 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.");
9387
9763
  return {
9388
9764
  ok: true,
9389
9765
  text: lines.join("\n")
@@ -9461,6 +9837,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9461
9837
  },
9462
9838
  timeoutMs: 6e4,
9463
9839
  execute: async (args, exec) => {
9840
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9464
9841
  markEgoToolCall(callingSessionId(exec));
9465
9842
  const blocked = attachGate();
9466
9843
  if (blocked !== "") return {
@@ -9533,7 +9910,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9533
9910
  if (assembland !== null) {
9534
9911
  lines.push(`POST : ${assembland.url}`);
9535
9912
  lines.push("", "── assembled request body (exactly the three allowed keys) ──", JSON.stringify(assembland.body, null, 2));
9536
- } 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)");
9537
9914
  if (bool(args.dryRun, true)) {
9538
9915
  lines.push("", "dryRun: nothing was sent.");
9539
9916
  return {
@@ -9599,6 +9976,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9599
9976
  },
9600
9977
  timeoutMs: 6e4,
9601
9978
  execute: async (args, exec) => {
9979
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9602
9980
  markEgoToolCall(callingSessionId(exec));
9603
9981
  const blocked = attachGate();
9604
9982
  if (blocked !== "") return {
@@ -9636,13 +10014,13 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9636
10014
  `budget : ${frame.image === null || frame.image.maxBytes === 0 ? "unbounded" : frame.image.maxBytes + " B"}${frame.image?.overBudget === true ? " *** OVER BUDGET ***" : ""}`,
9637
10015
  `candidates : ${frame.dom.nodes.length} of ${frame.dom.total}${frame.dom.truncated ? " (TRUNCATED)" : ""}`
9638
10016
  ];
9639
- 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)`);
9640
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.");
9641
10019
  if (bool(args.showCandidates, true)) {
9642
10020
  lines.push("", "── candidates (the judge answers with these numbers) ──");
9643
10021
  for (const node of frame.dom.nodes) lines.push(`${node.n}. ${node.role} "${node.name}" [${node.container}]`);
9644
10022
  }
9645
- 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.");
9646
10024
  return {
9647
10025
  ok: true,
9648
10026
  text: lines.join("\n")
@@ -9708,6 +10086,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9708
10086
  },
9709
10087
  timeoutMs: TOOL_TIMEOUT_MS,
9710
10088
  execute: async (args, exec) => {
10089
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9711
10090
  markEgoToolCall(callingSessionId(exec));
9712
10091
  const blocked = attachGate();
9713
10092
  if (blocked !== "") return {
@@ -9805,6 +10184,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9805
10184
  },
9806
10185
  timeoutMs: TOOL_TIMEOUT_MS,
9807
10186
  execute: async (args, exec) => {
10187
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9808
10188
  markEgoToolCall(callingSessionId(exec));
9809
10189
  const blocked = attachGate();
9810
10190
  if (blocked !== "") return {
@@ -9837,7 +10217,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9837
10217
  const nav = await effects.navigate(url);
9838
10218
  if (!nav.ok) return {
9839
10219
  ok: false,
9840
- text: `bcdp_jev_attempt: navigation failed — ${nav.error ?? "unknown error"}`
10220
+ text: `bcdp_jev_attempt: navigation failed �?${nav.error ?? "unknown error"}`
9841
10221
  };
9842
10222
  const result = await runAttempt({
9843
10223
  intent,
@@ -9849,7 +10229,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9849
10229
  `reason : ${result.reason}`,
9850
10230
  `page : ${result.lastUrl || nav.url}`,
9851
10231
  `elapsed : ${Date.now() - started}ms candidates(last round)=${result.candidates}`,
9852
- `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`
9853
10233
  ];
9854
10234
  if (effects.lastError() !== "") lines.push(`lastError : ${effects.lastError()}`);
9855
10235
  lines.push("", result.actions.length === 0 ? "── actions ── (none)" : "── actions ──");
@@ -9871,4 +10251,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9871
10251
  }
9872
10252
 
9873
10253
  //#endregion
9874
- 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 };