dsh-browser-cdp 1.2.2 → 1.2.4

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
@@ -271,12 +271,25 @@ async function connectCdp(wsUrl, timeoutMs) {
271
271
  }
272
272
  };
273
273
  }
274
- async function browserWsUrl(port) {
275
- const r = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(3e3) });
276
- if (!r.ok) throw new Error(`/json/version HTTP ${r.status} on port ${port}`);
277
- const j$1 = await r.json();
278
- if (!j$1.webSocketDebuggerUrl) throw new Error("browser did not expose webSocketDebuggerUrl");
279
- return j$1.webSocketDebuggerUrl;
274
+ async function browserWsUrl(port, retries = 2) {
275
+ for (let attempt = 0;; attempt++) try {
276
+ const r = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(3e3) });
277
+ if (!r.ok) throw new Error(`/json/version HTTP ${r.status} on port ${port}`);
278
+ const j$1 = await r.json();
279
+ if (!j$1.webSocketDebuggerUrl) throw new Error("browser did not expose webSocketDebuggerUrl");
280
+ return j$1.webSocketDebuggerUrl;
281
+ } catch (err) {
282
+ const nm = err?.name;
283
+ const timedOut = nm === "TimeoutError" || nm === "AbortError";
284
+ const refused = err instanceof TypeError;
285
+ if ((timedOut || refused) && attempt < retries) {
286
+ await sleep(500);
287
+ continue;
288
+ }
289
+ if (timedOut) throw new Error(`/json/version on port ${port} timed out after ${retries + 1} attempts`);
290
+ if (refused) throw new Error(`DevTools HTTP endpoint unreachable on port ${port} after ${retries + 1} attempts (connection refused — the browser may have exited right after publishing the port)`);
291
+ throw err;
292
+ }
280
293
  }
281
294
  function sleep(ms) {
282
295
  return new Promise((resolve$1) => setTimeout(resolve$1, ms));
@@ -423,6 +436,7 @@ async function importLoginCookies(opts, deps) {
423
436
  }
424
437
  let closedSource = false;
425
438
  let srcHandle = null;
439
+ let exited = null;
426
440
  let tempCdp = null;
427
441
  let egoCdp = null;
428
442
  let linkDir = null;
@@ -483,7 +497,7 @@ async function importLoginCookies(opts, deps) {
483
497
  }
484
498
  }
485
499
  let port = null;
486
- for (let attempt = 0; attempt < 2 && port === null; attempt++) {
500
+ for (let attempt = 0; attempt < 2 && port === null && exited === null; attempt++) {
487
501
  if (attempt > 0) {
488
502
  await sleep(6e3);
489
503
  try {
@@ -518,8 +532,18 @@ async function importLoginCookies(opts, deps) {
518
532
  graceMs: 8e3
519
533
  });
520
534
  srcHandle.done.catch(() => null);
535
+ exited = null;
536
+ srcHandle.done.then((r) => {
537
+ exited = r;
538
+ }, () => {
539
+ exited = {
540
+ exitCode: null,
541
+ signal: null
542
+ };
543
+ });
521
544
  const deadline = Date.now() + timeoutMs;
522
- while (Date.now() < deadline) {
545
+ while (Date.now() < deadline && port === null) {
546
+ if (exited !== null) break;
523
547
  try {
524
548
  port = parseDevToolsActivePort(await readFile(portFile, "utf8"));
525
549
  if (port !== null) break;
@@ -527,6 +551,19 @@ async function importLoginCookies(opts, deps) {
527
551
  await sleep(250);
528
552
  }
529
553
  }
554
+ const earlyExit = exited;
555
+ if (port === null && earlyExit !== null) {
556
+ let tail = "";
557
+ try {
558
+ tail = srcHandle?.collected?.stderr?.readFrom(0).text ?? "";
559
+ } catch {}
560
+ tail = tail.slice(-500);
561
+ return {
562
+ ok: false,
563
+ closedSource,
564
+ error: `${browser.label} headless instance exited early (code=${earlyExit.exitCode ?? "null"}, signal=${earlyExit.signal ?? "none"})${tail ? `: ${tail}` : ""} — a lingering background instance may have swallowed the throwaway debug port`
565
+ };
566
+ }
530
567
  if (port === null) return {
531
568
  ok: false,
532
569
  closedSource,
@@ -1022,7 +1059,7 @@ async function probeCliLink(input, io) {
1022
1059
  if (parsed.ok) running = parsed.running;
1023
1060
  }
1024
1061
  const sdkArgs = input.useSdkPath === true && (input.sdkPath ?? "") !== "" ? ["--sdk-path", input.sdkPath] : [];
1025
- const script = `console.log(${JSON.stringify(CLI_READY_SENTINEL)})\n`;
1062
+ const script = `console.log(${JSON.stringify(CLI_READY_SENTINEL)}, typeof taskSpaces, typeof browser)\n`;
1026
1063
  const runHeredoc = (extra) => io.run({
1027
1064
  argv: spawnArgvFor(shape, cliPath, ["nodejs", ...extra]),
1028
1065
  stdin: script,
@@ -1055,12 +1092,15 @@ async function probeCliLink(input, io) {
1055
1092
  message: `spawn failed: ${result.spawnErrorCode}`,
1056
1093
  ...base
1057
1094
  };
1058
- if (result.exitCode !== 0 || !result.stdout.includes(CLI_READY_SENTINEL)) {
1095
+ const facadeMatch = (/* @__PURE__ */ new RegExp(`${CLI_READY_SENTINEL} (\\w+) (\\w+)`)).exec(result.stdout);
1096
+ const facadesOk = input.useSdkPath !== true || facadeMatch?.[1] === "object" && facadeMatch?.[2] === "object";
1097
+ if (result.exitCode !== 0 || !result.stdout.includes(CLI_READY_SENTINEL) || !facadesOk) {
1059
1098
  const tail = (result.stderr || result.stdout).trim().slice(-400);
1099
+ const facadeNote = facadesOk ? "" : `; the SDK harness did not expose the facade (taskSpaces=${facadeMatch?.[1] ?? "undefined"}, browser=${facadeMatch?.[2] ?? "undefined"})`;
1060
1100
  return {
1061
1101
  ok: false,
1062
1102
  code: "cli-probe-failed",
1063
- message: `the ego CLI ran but did not reach the readiness sentinel (exit ${String(result.exitCode)})${tail ? `: ${tail}` : ""}`,
1103
+ message: `the ego CLI ran but did not reach the readiness sentinel (exit ${String(result.exitCode)})${facadeNote}${tail ? `: ${tail}` : ""}`,
1064
1104
  ...base
1065
1105
  };
1066
1106
  }
@@ -1480,6 +1520,7 @@ async function refreshCliAttach(input, cache, suggested, link, now) {
1480
1520
  message: probe.warning ?? (coldStart ? "local ego CLI reachable; the backing browser is not running yet and will start on the first call" : "local ego CLI ready"),
1481
1521
  cliPath: probe.cliPath,
1482
1522
  cliShape: probe.shape,
1523
+ sdkPath: link.useSdkPath === true && probe.warning === void 0 ? input.sdkPath ?? "" : "",
1483
1524
  latencyMs: probe.latencyMs,
1484
1525
  resolvedAt: now()
1485
1526
  });
@@ -3496,11 +3537,11 @@ const CORE = [
3496
3537
  "bcdp_doctor",
3497
3538
  "bcdp_help",
3498
3539
  "bcdp_space_open",
3540
+ "bcdp_space_close",
3499
3541
  "bcdp_navigate",
3500
3542
  "bcdp_snapshot"
3501
3543
  ];
3502
3544
  const BROWSE = [
3503
- "bcdp_space_close",
3504
3545
  "bcdp_click",
3505
3546
  "bcdp_fill",
3506
3547
  "bcdp_key",
@@ -3546,6 +3587,30 @@ const TIER_OF_TOOL = new Map([
3546
3587
  ].flatMap(([tier, names]) => names.map((n) => [n, tier])));
3547
3588
  /** 去掉 `bcdp_`/`ego_` 前缀后的裸名,便于策略表保持前缀无关。 */
3548
3589
  const bareToolName = (name$1) => name$1.replace(/^(?:bcdp|ego)_/, "");
3590
+ /** 批次放行顺序(索引即 rank)。 */
3591
+ const BATCH_ORDER = [
3592
+ "act",
3593
+ "observe",
3594
+ "wait"
3595
+ ];
3596
+ /** `browse` 级工具 → 批次。未登记的名字按 'act' 处理,绝不因缺表而被卡住。 */
3597
+ const BROWSE_BATCH = {
3598
+ click: "act",
3599
+ fill: "act",
3600
+ key: "act",
3601
+ hover: "act",
3602
+ scroll: "act",
3603
+ select: "act",
3604
+ check: "act",
3605
+ screenshot: "observe",
3606
+ page_info: "observe",
3607
+ read_element: "observe",
3608
+ js: "observe",
3609
+ wait: "wait",
3610
+ wait_for_selector: "wait"
3611
+ };
3612
+ /** 某工具的注入批次(前缀无关)。 */
3613
+ const batchOfTool = (name$1) => BROWSE_BATCH[bareToolName(name$1)] ?? "act";
3549
3614
  /**
3550
3615
  * 工具所属分级。未登记的名字落到 `extended`(最严的一档:宁可等活动解锁,
3551
3616
  * 也不让新工具悄悄回到常驻面);调用方应当在启动时打一条 warn,见
@@ -3589,7 +3654,15 @@ function tierAllowed(tier, p) {
3589
3654
  return p.injection === "always" || p.active;
3590
3655
  }
3591
3656
  /** 某工具此刻是否允许注册(名字 → 分级 → 策略)。 */
3592
- const toolAllowed = (name$1, p) => tierAllowed(tierOfTool(name$1), p);
3657
+ function toolAllowed(name$1, p) {
3658
+ const tier = tierOfTool(name$1);
3659
+ if (!tierAllowed(tier, p)) return false;
3660
+ if (tier === "browse" && p.injection !== "always") {
3661
+ const depth = p.batchDepth ?? BATCH_ORDER.length;
3662
+ if (BATCH_ORDER.indexOf(batchOfTool(name$1)) >= depth) return false;
3663
+ }
3664
+ return true;
3665
+ }
3593
3666
  function createTierInjector(o) {
3594
3667
  const label = o.label ?? "dsh-browser-cdp";
3595
3668
  /** 全部已登记工具,插入序。 */
@@ -7286,6 +7359,10 @@ async function openAgentWindow(ctx, cfg) {
7286
7359
  ok: false,
7287
7360
  error: gate
7288
7361
  };
7362
+ if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
7363
+ ctx.logger?.info?.("dsh-browser-cdp: ego-cli: browser already visible, skipping --open");
7364
+ return { ok: true };
7365
+ }
7289
7366
  const handle = ctx.subprocess.spawn({
7290
7367
  argv: [...cfg.egoArgvPrefix, "--open"],
7291
7368
  cwd: process.cwd(),
@@ -7333,6 +7410,33 @@ function parseSentinel(stdout) {
7333
7410
  }
7334
7411
  }
7335
7412
  }
7413
+ /** R2/R3 — sentinel + payload for the `bcdp_status` facade probe. @internal exported for tests */
7414
+ const STATUS_FACADE_SENTINEL = "__BCDP_STATUS__";
7415
+ /** @internal exported for tests — the exact heredoc the status probe runs. */
7416
+ const STATUS_FACADE_SCRIPT = `console.log(${JSON.stringify(STATUS_FACADE_SENTINEL)} + JSON.stringify({ taskSpaces: typeof taskSpaces, browser: typeof browser, page: typeof page }))
7417
+ `;
7418
+ /**
7419
+ * Parse the facade payload the status probe prints; `undefined` if absent.
7420
+ * @internal exported for tests
7421
+ */
7422
+ function parseStatusFacades(stdout) {
7423
+ const lines = stdout.split("\n");
7424
+ for (let i = lines.length - 1; i >= 0; i--) {
7425
+ const idx = lines[i].indexOf(STATUS_FACADE_SENTINEL);
7426
+ if (idx === -1) continue;
7427
+ const payload = lines[i].slice(idx + 15).trim();
7428
+ try {
7429
+ const parsed = JSON.parse(payload);
7430
+ return {
7431
+ taskSpaces: typeof parsed.taskSpaces === "string" ? parsed.taskSpaces : "undefined",
7432
+ browser: typeof parsed.browser === "string" ? parsed.browser : "undefined",
7433
+ page: typeof parsed.page === "string" ? parsed.page : "undefined"
7434
+ };
7435
+ } catch {
7436
+ return;
7437
+ }
7438
+ }
7439
+ }
7336
7440
  /**
7337
7441
  * R7 — is the upstream plugin installed anywhere under this DSH home?
7338
7442
  *
@@ -7351,16 +7455,28 @@ function findUpstreamPluginInstall(home = process.env.HOME || process.env.USERPR
7351
7455
  } catch {}
7352
7456
  return "";
7353
7457
  }
7458
+ /**
7459
+ * R1 — argv for one tool run. Single source of truth for the `--sdk-path`
7460
+ * injection: `bcdp_status` and `runEgoScript` must probe/run under the exact
7461
+ * same conditions, otherwise "available" and "actually works" diverge again.
7462
+ * @internal exported for tests
7463
+ */
7464
+ function buildEgoToolArgv(prefix, attach, runtimeArgs) {
7465
+ const extraCliArgs = filterArgs(runtimeArgs, EGO_CLI_BLOCKED);
7466
+ const sdkArgs = attach.linkKind === EGO_CLI_KIND && (attach.sdkPath ?? "") !== "" ? ["--sdk-path", attach.sdkPath] : [];
7467
+ return [
7468
+ ...prefix,
7469
+ "nodejs",
7470
+ ...sdkArgs,
7471
+ ...extraCliArgs
7472
+ ];
7473
+ }
7354
7474
  async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7355
7475
  let handle;
7356
7476
  try {
7357
- const extraCliArgs = filterArgs(cfg.runtimeArgs ?? "", EGO_CLI_BLOCKED);
7477
+ const attach = defaultAttachCache.get();
7358
7478
  handle = subprocess.spawn({
7359
- argv: [
7360
- ...cfg.egoArgvPrefix,
7361
- "nodejs",
7362
- ...extraCliArgs
7363
- ],
7479
+ argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
7364
7480
  cwd: process.cwd(),
7365
7481
  env: resolveEgoEnv(cfg),
7366
7482
  stdio: {
@@ -7665,6 +7781,7 @@ function apply(ctx, config = {}) {
7665
7781
  }
7666
7782
  };
7667
7783
  let browserActive = false;
7784
+ let browseBatchDepth = 0;
7668
7785
  const tiers = createTierInjector({
7669
7786
  register: (tool) => {
7670
7787
  const dispose = ctx.tools.register(tool);
@@ -7680,15 +7797,20 @@ function apply(ctx, config = {}) {
7680
7797
  jevKey: cfg.jevKey,
7681
7798
  layaKey: cfg.layaKey
7682
7799
  }),
7683
- active: browserActive
7800
+ active: browserActive,
7801
+ batchDepth: browseBatchDepth
7684
7802
  }),
7685
7803
  logger: ctx.logger
7686
7804
  });
7687
- /** 活动信号:只翻一次牌,重复调用零成本。 */
7805
+ /**
7806
+ * 活动信号:每次 bcdp_* 调用推进 browse 批次(act → observe → wait),
7807
+ * 到顶即止。只有注入面真的变了才 reapply。
7808
+ */
7688
7809
  const pulseActivity = () => {
7689
- if (browserActive) return;
7810
+ const before = browseBatchDepth;
7690
7811
  browserActive = true;
7691
- tiers.reapply();
7812
+ browseBatchDepth = Math.min(BATCH_ORDER.length, browseBatchDepth + 1);
7813
+ if (before !== browseBatchDepth) tiers.reapply();
7692
7814
  };
7693
7815
  {
7694
7816
  const offActivity = onEgoActivity(pulseActivity);
@@ -7701,6 +7823,7 @@ function apply(ctx, config = {}) {
7701
7823
  const sealAfterReap = () => {
7702
7824
  if (cfg.toolInjection !== "lazy" || !browserActive) return;
7703
7825
  browserActive = false;
7826
+ browseBatchDepth = 0;
7704
7827
  tiers.reapply();
7705
7828
  };
7706
7829
  /**
@@ -7830,6 +7953,11 @@ function apply(ctx, config = {}) {
7830
7953
  const last = getLastEgoActivity();
7831
7954
  if (!shouldReapBrowser(Date.now(), last, cfg.idleTimeoutMin)) return;
7832
7955
  if (last <= reapedFor) return;
7956
+ if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
7957
+ reapedFor = last;
7958
+ ctx.logger?.info?.("dsh-browser-cdp: idle reaper skipped: ego-cli owns the user's browser (never --stop it)");
7959
+ return;
7960
+ }
7833
7961
  try {
7834
7962
  const { localBrowserInfo, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-h0Ca5NV1.js");
7835
7963
  if (localBrowserInfo()) {
@@ -7872,6 +8000,10 @@ function apply(ctx, config = {}) {
7872
8000
  }, "dsh-browser-cdp: idle reaper");
7873
8001
  ctx.effect?.(() => {
7874
8002
  try {
8003
+ if (defaultAttachCache.get().linkKind === EGO_CLI_KIND) {
8004
+ ctx.logger?.info?.("dsh-browser-cdp: teardown skipped --stop: ego-cli owns the user's browser");
8005
+ return;
8006
+ }
7875
8007
  ctx.subprocess.spawn({
7876
8008
  argv: [
7877
8009
  process.execPath,
@@ -7891,11 +8023,11 @@ function apply(ctx, config = {}) {
7891
8023
  });
7892
8024
  ctx.logger?.info?.(`dsh-browser-cdp: mounted (egoBin=${cfg.egoBin}, defaultSpace=${cfg.defaultSpace})`);
7893
8025
  }
7894
- /** `bcdp_status` probes CLI availability by running the real `--status` path. */
8026
+ /** `bcdp_status` probes the SAME channel work uses: a `nodejs` heredoc. */
7895
8027
  function registerEgoStatus(ctx, cfg, reg, tiers) {
7896
8028
  reg(defineTool({
7897
8029
  name: "bcdp_status",
7898
- description: "Check whether the ego-browser CLI is usable (runs `ego-browser --status`). Use this first when other bcdp_* tools report \"CLI not found\".",
8030
+ description: "Check whether the ego-browser CLI can actually run bcdp_* tools (probes the taskSpaces/browser/page facade over the nodejs channel). Use this first when other bcdp_* tools report \"CLI not found\".",
7899
8031
  parameters: {},
7900
8032
  output: {
7901
8033
  schema: {
@@ -7911,34 +8043,45 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
7911
8043
  required: true
7912
8044
  },
7913
8045
  path: { type: "string" },
7914
- exitCode: { type: "integer" }
8046
+ exitCode: { type: "integer" },
8047
+ facades: {
8048
+ type: "object",
8049
+ additionalProperties: false,
8050
+ properties: {
8051
+ taskSpaces: { type: "string" },
8052
+ browser: { type: "string" },
8053
+ page: { type: "string" }
8054
+ }
8055
+ }
7915
8056
  }
7916
8057
  },
7917
8058
  render: renderText
7918
8059
  },
7919
- timeoutMs: 25e3,
8060
+ timeoutMs: 15e3,
7920
8061
  execute: async () => {
7921
8062
  tiers.pulse();
7922
8063
  return withEgoLock(async () => {
7923
8064
  try {
8065
+ const attach = defaultAttachCache.get();
7924
8066
  const handle = ctx.subprocess.spawn({
7925
- argv: [...cfg.egoArgvPrefix, "--status"],
8067
+ argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
7926
8068
  cwd: process.cwd(),
7927
8069
  env: resolveEgoEnv(cfg),
7928
8070
  stdio: {
7929
- stdin: { data: "" },
8071
+ stdin: { data: STATUS_FACADE_SCRIPT },
7930
8072
  stdout: { maxBytes: 4096 },
7931
8073
  stderr: { maxBytes: 4096 }
7932
8074
  },
7933
- graceMs: 25e3
8075
+ graceMs: 15e3
7934
8076
  });
7935
8077
  const outcome = await handle.done;
7936
- const out = readAll(handle.collected.stdout).trim();
8078
+ const facades = parseStatusFacades(readAll(handle.collected.stdout));
7937
8079
  return {
7938
8080
  ok: true,
7939
- available: outcome.exitCode === 0 && out !== "",
7940
- path: cfg.egoBin,
7941
- exitCode: outcome.exitCode
8081
+ available: outcome.exitCode === 0 && facades?.taskSpaces === "object" && facades?.browser === "object",
8082
+ path: attach.cliPath ?? cfg.egoBin,
8083
+ exitCode: outcome.exitCode,
8084
+ ...facades ? { facades } : {}
7942
8085
  };
7943
8086
  } catch (err) {
7944
8087
  return {
@@ -8037,27 +8180,27 @@ function registerAuthFlush(ctx, cfg, reg) {
8037
8180
  function registerLoginImport(ctx, cfg, reg) {
8038
8181
  reg(defineTool({
8039
8182
  name: "bcdp_login_import",
8040
- description: "Import login cookies from the system browser (Chrome/Edge/Brave) into the agent browser, so sites open already logged in. Works via a throwaway headless instance of the REAL system browser (CDP passthrough — no offline decryption; survives Chrome App-Bound Encryption). Run with dryRun=true first to see what is importable, then import with an explicit domains list (e.g. [\"bilibili.com\"]). The agent browser must be running (call bcdp_status first). Imported logins persist in the on-disk profile across restarts. Cookie values are never shown — only domain names and counts.",
8183
+ description: "Import login cookies from the system browser (Chrome/Edge/Brave) into the agent browser via CDP passthrough, so sites open logged in. Run dryRun first, then import explicit domains; logins persist in the profile. Cookie values are never shown.",
8041
8184
  parameters: {
8042
8185
  source: {
8043
8186
  type: "string",
8044
- description: "chrome | edge | brave | auto (default: auto = first detected browser)."
8187
+ description: "chrome | edge | brave | auto (default auto)."
8045
8188
  },
8046
8189
  domains: {
8047
8190
  type: "json",
8048
- description: "Optional array of domains to import, e.g. [\"bilibili.com\",\"zhihu.com\"] (subdomains included). Omit = ALL cookies — prefer an explicit list."
8191
+ description: "Domains to import, e.g. [\"bilibili.com\"] (subdomains included). Omit = all cookies; prefer an explicit list."
8049
8192
  },
8050
8193
  profile: {
8051
8194
  type: "string",
8052
- description: "Source browser profile directory name, e.g. \"Default\" or \"Profile 1\" (default: the first profile)."
8195
+ description: "Source profile dir, e.g. \"Default\" (default: first profile)."
8053
8196
  },
8054
8197
  closeSource: {
8055
8198
  type: "boolean",
8056
- description: "A running source browser holds an exclusive lock on its cookie store (Windows). true = gracefully close it first (its windows/tabs restore on next launch). false (default) = return an actionable error instead."
8199
+ description: "true = gracefully close a running source browser first (tabs restore); false = return an actionable error (default)."
8057
8200
  },
8058
8201
  dryRun: {
8059
8202
  type: "boolean",
8060
- description: "true = only report what would be imported (domains + cookie counts), write nothing."
8203
+ description: "true = report what would be imported; write nothing."
8061
8204
  }
8062
8205
  },
8063
8206
  output: {
@@ -8076,6 +8219,8 @@ function registerLoginImport(ctx, cfg, reg) {
8076
8219
  matched: { type: "integer" },
8077
8220
  written: { type: "integer" },
8078
8221
  domains: { type: "json" },
8222
+ closedSource: { type: "boolean" },
8223
+ restoredFromBackup: { type: "boolean" },
8079
8224
  error: { type: "string" }
8080
8225
  }
8081
8226
  },
@@ -8208,27 +8353,27 @@ function registerActionTools(ctx, cfg, reg) {
8208
8353
  }));
8209
8354
  reg(t({
8210
8355
  name: "bcdp_click",
8211
- description: "Click an element in the current page. Target with a CSS selector, an xpath=.../loc=.../ref=N value from bcdp_snapshot, or viewport coordinates.",
8356
+ description: "Click an element: CSS/xpath/loc/ref selector, or viewport x+y coordinates.",
8212
8357
  parameters: {
8213
8358
  selector: {
8214
8359
  type: "string",
8215
- description: "CSS selector, xpath=..., loc=..., or ref=N from the snapshot. Required unless x/y are given."
8360
+ description: "CSS/xpath/loc/ref=N from bcdp_snapshot; required unless x,y."
8216
8361
  },
8217
8362
  x: {
8218
8363
  type: "number",
8219
- description: "Viewport x coordinate for a coordinate click."
8364
+ description: "Viewport x for a coordinate click."
8220
8365
  },
8221
8366
  y: {
8222
8367
  type: "number",
8223
- description: "Viewport y coordinate for a coordinate click."
8368
+ description: "Viewport y for a coordinate click."
8224
8369
  },
8225
8370
  label: {
8226
8371
  type: "string",
8227
- description: "Short human label for the action, e.g. \"click submit button\"."
8372
+ description: "Short action label, e.g. \"click submit\"."
8228
8373
  },
8229
8374
  double: {
8230
8375
  type: "boolean",
8231
- description: "Double-click instead of single-click. Useful for opening files/rows or triggering dblclick handlers."
8376
+ description: "Double-click instead of single."
8232
8377
  },
8233
8378
  space: spaceParam
8234
8379
  },
@@ -8338,20 +8483,20 @@ function registerActionTools(ctx, cfg, reg) {
8338
8483
  }));
8339
8484
  reg(t({
8340
8485
  name: "bcdp_wait_for_selector",
8341
- description: "Wait until an element matching a CSS selector appears (state=visible, default) or disappears (state=hidden). Use instead of a blind fixed wait when a page renders asynchronously.",
8486
+ description: "Wait until a CSS selector appears (state=visible, default) or disappears (state=hidden). Use instead of a fixed wait for async pages.",
8342
8487
  parameters: {
8343
8488
  selector: {
8344
8489
  type: "string",
8345
8490
  required: true,
8346
- description: "CSS selector of the element to wait for, e.g. '.results' or '[data-id=done]'."
8491
+ description: "CSS selector to wait for, e.g. '.results' or '[data-id=done]'."
8347
8492
  },
8348
8493
  state: {
8349
8494
  type: "string",
8350
- description: "Target state: 'visible' (default) | 'attached' | 'hidden' | 'detached'."
8495
+ description: "'visible' (default) | 'attached' | 'hidden' | 'detached'."
8351
8496
  },
8352
8497
  timeout: {
8353
8498
  type: "number",
8354
- description: "How long to wait in ms (default 10000)."
8499
+ description: "Wait in ms (default 10000)."
8355
8500
  },
8356
8501
  space: spaceParam
8357
8502
  },
@@ -8384,20 +8529,20 @@ function registerActionTools(ctx, cfg, reg) {
8384
8529
  }));
8385
8530
  reg(t({
8386
8531
  name: "bcdp_wait_for_response",
8387
- description: "Wait for a network response matching a URL/glob/regex and return it. Optionally return the body (text or JSON) — ideal for scraping API responses or confirming a submission.",
8532
+ description: "Wait for a network response matching a URL/glob/regex and return it; optionally return the body (text or JSON).",
8388
8533
  parameters: {
8389
8534
  url: {
8390
8535
  type: "string",
8391
8536
  required: true,
8392
- description: "URL/glob/regex to match, e.g. '/api/search' or 'https://*.com/data'."
8537
+ description: "URL/glob/regex, e.g. '/api/search' or 'https://*.com/data'."
8393
8538
  },
8394
8539
  timeout: {
8395
8540
  type: "number",
8396
- description: "How long to wait in ms (default 10000)."
8541
+ description: "Wait in ms (default 10000)."
8397
8542
  },
8398
8543
  body: {
8399
8544
  type: "string",
8400
- description: "Return the response body: 'none' (default) | 'text' | 'json'."
8545
+ description: "'none' (default) | 'text' | 'json'."
8401
8546
  },
8402
8547
  space: spaceParam
8403
8548
  },
@@ -8410,15 +8555,15 @@ function registerActionTools(ctx, cfg, reg) {
8410
8555
  }));
8411
8556
  reg(t({
8412
8557
  name: "bcdp_key",
8413
- description: "Press a keyboard key or shortcut combination on the current page, e.g. 'Enter', 'Tab', 'Control+a', 'Escape', 'ArrowDown'. Useful for forms, shortcuts and navigation. Pass `text` to type a string of characters instead (keyboard.type).",
8558
+ description: "Press a key/combo ('Enter', 'Tab', 'Control+a', 'Escape') or type text character-by-character.",
8414
8559
  parameters: {
8415
8560
  key: {
8416
8561
  type: "string",
8417
- description: "Key or combo: 'Enter', 'Tab', 'Control+c', 'Meta+v', 'ArrowDown', 'Escape', 'F5', etc. (ignored when `text` is given)."
8562
+ description: "Key/combo: 'Enter', 'Control+c', 'ArrowDown', 'F5' (ignored when text is given)."
8418
8563
  },
8419
8564
  text: {
8420
8565
  type: "string",
8421
- description: "Type this text character-by-character (keyboard.type). Use instead of `key` for typing words into the focused element."
8566
+ description: "Type this text instead (keyboard.type)."
8422
8567
  },
8423
8568
  space: spaceParam
8424
8569
  },
@@ -8457,16 +8602,16 @@ function registerActionTools(ctx, cfg, reg) {
8457
8602
  }));
8458
8603
  reg(t({
8459
8604
  name: "bcdp_read_element",
8460
- description: "Read a single element (by selector): its text, HTML, input value, an attribute, or visibility/enabled/count. Cheaper and more precise than a full-page snapshot.",
8605
+ description: "Read one element: text, HTML, value, an attribute, or visible/enabled/count.",
8461
8606
  parameters: {
8462
8607
  selector: {
8463
8608
  type: "string",
8464
8609
  required: true,
8465
- description: "CSS selector of the target element."
8610
+ description: "CSS selector of the target."
8466
8611
  },
8467
8612
  what: {
8468
8613
  type: "string",
8469
- description: "What to read: 'text' (default) | 'html' | 'value' | 'attribute' | 'visible' | 'enabled' | 'count'."
8614
+ description: "'text' (default) | 'html' | 'value' | 'attribute' | 'visible' | 'enabled' | 'count'."
8470
8615
  },
8471
8616
  attribute: {
8472
8617
  type: "string",
@@ -8594,23 +8739,23 @@ function registerActionTools(ctx, cfg, reg) {
8594
8739
  }));
8595
8740
  reg(t({
8596
8741
  name: "bcdp_download",
8597
- description: "Wait for a file download triggered by the current action, then return its saved path. Provide `triggerSelector` (a download button/link to click) or `triggerScript` (arbitrary JS that triggers the download). The file is captured into a temp dir and (optionally) copied to `savePath`. Returns { path, suggestedFilename, url }.",
8742
+ description: "Wait for a download triggered by the current action, then return its saved path. Trigger with triggerSelector or triggerScript; optionally copy to savePath.",
8598
8743
  parameters: {
8599
8744
  triggerSelector: {
8600
8745
  type: "string",
8601
- description: "CSS selector of the element (button/link) whose click starts the download."
8746
+ description: "CSS selector of the button/link whose click starts the download."
8602
8747
  },
8603
8748
  triggerScript: {
8604
8749
  type: "string",
8605
- description: "Full JS snippet that triggers the download (e.g. window.open() or a fetch-to-blob download); runs in the page before waiting for the download."
8750
+ description: "JS snippet that triggers the download (runs before waiting)."
8606
8751
  },
8607
8752
  savePath: {
8608
8753
  type: "string",
8609
- description: "Optional absolute destination path to also copy the downloaded file to. Otherwise only the temp-captured path is returned."
8754
+ description: "Absolute path to also copy the file to."
8610
8755
  },
8611
8756
  timeout: {
8612
8757
  type: "number",
8613
- description: "How long to wait for the download in ms (default 30000)."
8758
+ description: "Wait timeout in ms (default 30000)."
8614
8759
  },
8615
8760
  space: spaceParam
8616
8761
  },
@@ -8668,7 +8813,7 @@ function registerActionTools(ctx, cfg, reg) {
8668
8813
  }));
8669
8814
  reg(t({
8670
8815
  name: "bcdp_http",
8671
- description: "Make an HTTP request and return status + body. Default runs in the agent page's browser context (cross-origin allowed when the server's CORS permits); set `mode: server` to use Node-side fetch.server. Use to scrape an API, POST data, or hit a service. (Note: on the vendored ego-linux Windows runtime, fetch.server can hit a libuv crash, so prefer the default browser mode there.)",
8816
+ description: "Make an HTTP request and return status + body. Default runs in the page's browser context; mode=server uses Node-side fetch.server (may crash on the vendored ego-linux Windows runtime, so prefer browser mode).",
8672
8817
  parameters: {
8673
8818
  url: {
8674
8819
  type: "string",
@@ -8677,7 +8822,7 @@ function registerActionTools(ctx, cfg, reg) {
8677
8822
  },
8678
8823
  method: {
8679
8824
  type: "string",
8680
- description: "HTTP method, default GET."
8825
+ description: "HTTP method (default GET)."
8681
8826
  },
8682
8827
  headers: {
8683
8828
  type: "object",
@@ -8686,7 +8831,7 @@ function registerActionTools(ctx, cfg, reg) {
8686
8831
  },
8687
8832
  body: {
8688
8833
  type: "string",
8689
- description: "Request body (for POST/PUT)."
8834
+ description: "Request body (POST/PUT)."
8690
8835
  },
8691
8836
  timeout: {
8692
8837
  type: "number",
@@ -8694,7 +8839,11 @@ function registerActionTools(ctx, cfg, reg) {
8694
8839
  },
8695
8840
  mode: {
8696
8841
  type: "string",
8697
- description: "'browser' (default) runs via the page context; 'server' uses Node-side fetch.server."
8842
+ description: "'browser' (default) or 'server' (Node-side fetch)."
8843
+ },
8844
+ credentials: {
8845
+ type: "string",
8846
+ description: "Browser mode: 'include' sends the profile's cookies cross-origin; 'omit'/'same-origin' also accepted. Default: engine default."
8698
8847
  },
8699
8848
  space: spaceParam
8700
8849
  },
@@ -8706,6 +8855,8 @@ function registerActionTools(ctx, cfg, reg) {
8706
8855
  };
8707
8856
  if (str(args.body, "") !== "") opts.body = str(args.body, "");
8708
8857
  const mode = str(args.mode, "browser");
8858
+ const cred = str(args.credentials, "");
8859
+ if (mode !== "server" && (cred === "include" || cred === "omit" || cred === "same-origin")) opts.credentials = cred;
8709
8860
  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`;
8710
8861
  }
8711
8862
  }));
@@ -9189,28 +9340,28 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9189
9340
  }));
9190
9341
  reg(defineTool({
9191
9342
  name: "bcdp_jev_ask",
9192
- description: "Assemble the JEV/Laya judgement request for the CURRENT page plus an intent, and either return the assembled request body (dryRun, default) or send it and return the answer. Use dryRun to inspect exactly what would be sent.",
9343
+ description: "Assemble the JEV/Laya judgement request for the current page + intent; return it (dryRun) or send it.",
9193
9344
  parameters: {
9194
9345
  goal: {
9195
9346
  type: "string",
9196
9347
  required: true,
9197
- description: "What we are trying to accomplish, in your own words."
9348
+ description: "What we are trying to accomplish."
9198
9349
  },
9199
9350
  kind: {
9200
9351
  type: "string",
9201
- description: "Intent kind: navigate | extract | fill | click | verify | other (default other)."
9352
+ description: "navigate | extract | fill | click | verify | other."
9202
9353
  },
9203
9354
  hints: {
9204
9355
  type: "string",
9205
- description: "One target hint per line. Hints only — never a CSS selector."
9356
+ description: "Target hint per line; never a selector."
9206
9357
  },
9207
9358
  successCriteria: {
9208
9359
  type: "string",
9209
- description: "One observable success condition per line."
9360
+ description: "Success condition per line."
9210
9361
  },
9211
9362
  stopConditions: {
9212
9363
  type: "string",
9213
- description: "One stop condition per line, e.g. \"a captcha appears\"."
9364
+ description: "Stop condition per line."
9214
9365
  },
9215
9366
  dryRun: {
9216
9367
  type: "boolean",
@@ -9218,19 +9369,19 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9218
9369
  },
9219
9370
  includeImage: {
9220
9371
  type: "boolean",
9221
- description: "Also return the base64 frame image (default false)."
9372
+ description: "Also return the base64 frame (default false)."
9222
9373
  },
9223
9374
  maxCandidates: {
9224
9375
  type: "integer",
9225
- description: "Override the candidate ceiling for this call."
9376
+ description: "Candidate ceiling for this call."
9226
9377
  },
9227
9378
  round: {
9228
9379
  type: "string",
9229
- description: "Which round to assemble: 'control' (should we act), 'chapter' (which part of the page), or 'pick' (which numbered candidate). Default control."
9380
+ description: "'control' | 'chapter' | 'pick' (default control)."
9230
9381
  },
9231
9382
  chapter: {
9232
9383
  type: "string",
9233
- description: "Chapter key to restrict a 'pick' round to, e.g. form#1. From the chapter round's options."
9384
+ description: "Chapter key for a 'pick' round, e.g. form#1."
9234
9385
  }
9235
9386
  },
9236
9387
  output: {
@@ -9448,7 +9599,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9448
9599
  }));
9449
9600
  reg(defineTool({
9450
9601
  name: "bcdp_jev_run",
9451
- description: "Run the JEV judgement loop against the current page for one goal: capture a frame, ask the judge, act, verify. Stops on done (VERIFIED against successCriteria), blocked, exhausted, stuck, unavailable or error. Returns a per-step trace.",
9602
+ description: "Run the JEV loop for one goal; returns a step trace.",
9452
9603
  parameters: {
9453
9604
  goal: {
9454
9605
  type: "string",
@@ -9461,23 +9612,23 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9461
9612
  },
9462
9613
  hints: {
9463
9614
  type: "string",
9464
- description: "One target hint per line (never a selector)."
9615
+ description: "Target hint per line (never a selector)."
9465
9616
  },
9466
9617
  successCriteria: {
9467
9618
  type: "string",
9468
- description: "One observable success condition per line. REQUIRED for a trustworthy `done`."
9619
+ description: "Success condition per line; required for done."
9469
9620
  },
9470
9621
  stopConditions: {
9471
9622
  type: "string",
9472
- description: "One stop condition per line."
9623
+ description: "Stop condition per line."
9473
9624
  },
9474
9625
  stepBudget: {
9475
9626
  type: "integer",
9476
- description: "Judgement rounds allowed (default from settings)."
9627
+ description: "Max judgement rounds (default settings)."
9477
9628
  },
9478
9629
  wallMs: {
9479
9630
  type: "integer",
9480
- description: "Wall-clock ceiling in ms (default from settings)."
9631
+ description: "Wall-clock ceiling in ms (default settings)."
9481
9632
  }
9482
9633
  },
9483
9634
  output: {
@@ -9556,12 +9707,12 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9556
9707
  }));
9557
9708
  reg(defineTool({
9558
9709
  name: "bcdp_jev_attempt",
9559
- description: "Open a URL and let the decision model (laya/jev) ATTEMPT one goal on it: every round the option table is the page's DOM candidates plus an `end` option; the model spends up to N actions (default 5) or picks `end` by itself, then a receipt comes back. The judge context is the DOM tree only (the model cannot read the screenshot). Verify the result yourself afterwards via bcdp_cdp / bcdp_screenshot using the returned targetId — the receipt is a report, not a proof.",
9710
+ description: "Open a URL and let the decision model attempt one goal: each round it picks from the page's DOM candidates plus `end`, up to N actions. Returns a receipt; verify yourself via bcdp_cdp/bcdp_screenshot (a receipt is a report, not proof).",
9560
9711
  parameters: {
9561
9712
  url: {
9562
9713
  type: "string",
9563
9714
  required: true,
9564
- description: "Absolute URL to open, e.g. https://example.com/path."
9715
+ description: "Absolute URL to open."
9565
9716
  },
9566
9717
  goal: {
9567
9718
  type: "string",
@@ -9570,11 +9721,11 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9570
9721
  },
9571
9722
  successCriteria: {
9572
9723
  type: "string",
9573
- description: "One observable success condition per line. Helps the model decide when to pick `end`."
9724
+ description: "Success condition per line; helps the model decide when to stop."
9574
9725
  },
9575
9726
  maxActions: {
9576
9727
  type: "integer",
9577
- description: "Action budget for the decision model (default 5, capped at 20)."
9728
+ description: "Action budget (default 5, max 20)."
9578
9729
  }
9579
9730
  },
9580
9731
  output: {
@@ -9662,4 +9813,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9662
9813
  }
9663
9814
 
9664
9815
  //#endregion
9665
- export { Config, apply, cdpAttachError, createActiveSpaceTracker, decideCdpAttach, findChromeBinary, findUpstreamPluginInstall, inject, name, resolveEgoEnv, runWithStaleSpaceRetry, shouldReapBrowser };
9816
+ export { Config, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, apply, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, decideCdpAttach, findChromeBinary, findUpstreamPluginInstall, inject, name, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, shouldReapBrowser };