@xbrowser/cli 1.33.0 → 1.35.0

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.
Files changed (53) hide show
  1. package/dist/{browser-3LBSVDSS.js → browser-KY7AIRAB.js} +3 -2
  2. package/dist/{browser-23BMBCH2.js → browser-MLKP72XP.js} +3 -3
  3. package/dist/{browser-D7RFPTD4.js → browser-RZ7DPBI3.js} +3 -3
  4. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  5. package/dist/{cdp-driver-B5KVVI4O.js → cdp-driver-HBMCD7NU.js} +2 -2
  6. package/dist/{cdp-driver-GE6Y6LPI.js → cdp-driver-MJD7YIQI.js} +2 -2
  7. package/dist/{cdp-driver-6G77XM4H.js → cdp-driver-YJU4GRSV.js} +203 -95
  8. package/dist/chunk-3SZTCI33.js +147 -0
  9. package/dist/{chunk-OVAUGFM6.js → chunk-43U5VDLB.js} +8 -2
  10. package/dist/chunk-53VZHESL.js +150 -0
  11. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  12. package/dist/{chunk-YX5KVWGX.js → chunk-6DS3T6UK.js} +203 -95
  13. package/dist/{chunk-DDHHVII7.js → chunk-BLCBCESM.js} +8 -2
  14. package/dist/{chunk-SH6OTPXN.js → chunk-C5ZPXPD7.js} +31 -7
  15. package/dist/chunk-EGOWDZXP.js +149 -0
  16. package/dist/chunk-GNLZWHSP.js +1380 -0
  17. package/dist/{chunk-5MYC6LVL.js → chunk-GYGVHWG3.js} +279 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-JYYKMSFH.js +39 -0
  20. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  21. package/dist/{chunk-ACPMC47K.js → chunk-QRFM4NOV.js} +1025 -202
  22. package/dist/chunk-RGL2YTWQ.js +64 -0
  23. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  24. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  25. package/dist/{chunk-43TEMG4U.js → chunk-WGS3Y6ZV.js} +3 -1
  26. package/dist/{chunk-AKT3WLZM.js → chunk-Y2GRCINH.js} +1004 -183
  27. package/dist/{chunk-H25ECCYJ.js → chunk-ZCZELQCS.js} +203 -95
  28. package/dist/cli.js +2237 -278
  29. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-OXKRGLPQ.js} +32 -8
  30. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-Z3NKNZRL.js} +5 -1
  31. package/dist/daemon-main.js +2214 -159
  32. package/dist/human-interaction-BGAZC3JR.js +12 -0
  33. package/dist/human-interaction-TPKPEE7A.js +11 -0
  34. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  35. package/dist/index.d.ts +225 -94
  36. package/dist/index.js +2880 -267
  37. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  38. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  39. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  40. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  41. package/dist/{recovery-JFGV3DBX.js → recovery-7NRRHLS4.js} +4 -4
  42. package/dist/{recovery-XDKN63O5.js → recovery-TIBRFGRP.js} +4 -4
  43. package/dist/run-routes-SJKVZ34L.js +26 -0
  44. package/dist/run-routes-TFNV5BBR.js +24 -0
  45. package/dist/{server-5JHB4TML.js → server-HUSX7EFE.js} +5 -4
  46. package/dist/{server-6CTC3RHV.js → server-KSP5H4HD.js} +5 -3
  47. package/dist/{session-replayer-IGRRA2QC.js → session-replayer-4TCLQI76.js} +1 -1
  48. package/dist/viewer-routes-YOS5GTCV.js +11 -0
  49. package/package.json +1 -1
  50. package/dist/chunk-QCV2PI7U.js +0 -184
  51. package/dist/human-interaction-ISMMOJOK.js +0 -8
  52. package/dist/human-interaction-STTZZZ5N.js +0 -8
  53. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -1,26 +1,35 @@
1
- import {
2
- detectAntiBot,
3
- formatDetectionMessage
4
- } from "./chunk-JKVUFP3G.js";
5
- import {
6
- buildViewerUrl
7
- } from "./chunk-3OD76SUE.js";
8
- import {
9
- resolveScreenshotsDir
10
- } from "./chunk-ZTHE5RBZ.js";
11
1
  import {
12
2
  closeEphemeralContext,
13
3
  closeSessionByName,
14
4
  createEphemeralContext,
15
- createRuleEngine,
16
5
  createSession,
17
6
  findOrRestoreSession,
18
7
  getBrowser,
19
8
  getSessionById,
9
+ newSessionId,
10
+ readSessionDiskMeta,
11
+ registerSession,
20
12
  resolveLaunchOpts,
21
13
  saveSessionDiskMeta,
14
+ sessions,
22
15
  setActivePage
23
- } from "./chunk-5MYC6LVL.js";
16
+ } from "./chunk-GNLZWHSP.js";
17
+ import {
18
+ detectAntiBot,
19
+ formatDetectionMessage
20
+ } from "./chunk-JKVUFP3G.js";
21
+ import {
22
+ recordMistake
23
+ } from "./chunk-3SZTCI33.js";
24
+ import {
25
+ buildViewerUrl
26
+ } from "./chunk-3OD76SUE.js";
27
+ import {
28
+ resolveScreenshotsDir
29
+ } from "./chunk-ZTHE5RBZ.js";
30
+ import {
31
+ createRuleEngine
32
+ } from "./chunk-GYGVHWG3.js";
24
33
  import {
25
34
  rand,
26
35
  sleep,
@@ -32,7 +41,7 @@ import {
32
41
 
33
42
  // src/executor.ts
34
43
  import {
35
- ok as ok33,
44
+ ok as ok32,
36
45
  fail as fail19,
37
46
  isCommandResult,
38
47
  normalizeTips as normalizeTips8,
@@ -1368,14 +1377,14 @@ var preflightCommand = registerCommand({
1368
1377
  let pageUrl = null;
1369
1378
  try {
1370
1379
  const { fileURLToPath } = await import("url");
1371
- const { join: join10, dirname: dirname5 } = await import("path");
1372
- const { existsSync: existsSync8 } = await import("fs");
1380
+ const { join: join9, dirname: dirname4 } = await import("path");
1381
+ const { existsSync: existsSync7 } = await import("fs");
1373
1382
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1374
1383
  const candidates = [
1375
- join10(dirname5(here), "..", "assets", "preflight.html"),
1376
- join10(process.cwd(), "assets", "preflight.html")
1384
+ join9(dirname4(here), "..", "assets", "preflight.html"),
1385
+ join9(process.cwd(), "assets", "preflight.html")
1377
1386
  ];
1378
- pageUrl = candidates.find((c) => existsSync8(c)) || null;
1387
+ pageUrl = candidates.find((c) => existsSync7(c)) || null;
1379
1388
  } catch {
1380
1389
  }
1381
1390
  if (pageUrl) {
@@ -4730,18 +4739,18 @@ import { z as z25 } from "zod";
4730
4739
  import { ok as ok24, fail as fail11, normalizeTips as normalizeTips3 } from "@dyyz1993/xcli-core";
4731
4740
 
4732
4741
  // src/runtime/ref-store.ts
4733
- var sessions = /* @__PURE__ */ new Map();
4742
+ var sessions2 = /* @__PURE__ */ new Map();
4734
4743
  function normalizeAgentRef(ref) {
4735
4744
  return ref.startsWith("@") ? ref.slice(1) : ref;
4736
4745
  }
4737
4746
  function replaceRefs(sessionKey2, screenHash, targets) {
4738
- sessions.set(sessionKey2, {
4747
+ sessions2.set(sessionKey2, {
4739
4748
  screenHash,
4740
4749
  targets: new Map(targets.map((target) => [target.ref, target]))
4741
4750
  });
4742
4751
  }
4743
4752
  function getRefTarget(sessionKey2, ref) {
4744
- const session = sessions.get(sessionKey2);
4753
+ const session = sessions2.get(sessionKey2);
4745
4754
  const target = session?.targets.get(normalizeAgentRef(ref));
4746
4755
  if (!session || !target) return null;
4747
4756
  return { screenHash: session.screenHash, target };
@@ -7340,6 +7349,857 @@ function attachDetectAntiBot(ctx) {
7340
7349
  };
7341
7350
  }
7342
7351
 
7352
+ // src/browser/bridge-session.ts
7353
+ var DEFAULT_BRIDGE_HTTP = "http://127.0.0.1:9347";
7354
+ function bridgeHttpBase() {
7355
+ return process.env.XBROWSER_BRIDGE_HTTP || DEFAULT_BRIDGE_HTTP;
7356
+ }
7357
+ async function bridgeExec(cmd, args) {
7358
+ let resp;
7359
+ try {
7360
+ resp = await fetch(`${bridgeHttpBase()}/exec`, {
7361
+ method: "POST",
7362
+ headers: { "Content-Type": "application/json" },
7363
+ body: JSON.stringify({ cmd, args })
7364
+ });
7365
+ } catch (e) {
7366
+ throw new Error(`[bridge-session] bridge \u901A\u9053\u4E0D\u53EF\u8FBE\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09: ${e instanceof Error ? e.message : String(e)}`);
7367
+ }
7368
+ const reply = await resp.json().catch(() => null);
7369
+ if (!reply) throw new Error("[bridge-session] bridge \u54CD\u5E94\u975E JSON\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09");
7370
+ if (reply.ok !== true) throw new Error(`[bridge-session] ${cmd} \u5931\u8D25: ${reply.error ?? "unknown"}`);
7371
+ return reply.data ?? {};
7372
+ }
7373
+ function unimplemented(op) {
7374
+ throw new Error(`[bridge-session] \u672A\u652F\u6301\u300C${op}\u300D\u2014\u2014bridge \u4F1A\u8BDD v1 \u80FD\u529B\u9762\uFF1A\u5BFC\u822A/\u6C42\u503C/\u70B9\u51FB/\u586B\u5199/\u952E\u5165/\u622A\u56FE/\u8F6E\u8BE2\u7B49\u5F85\uFF1B\u4E8B\u4EF6\u7C7B\u80FD\u529B\uFF08\u7F51\u7EDC\u6355\u83B7\u3001waitForEvent \u7B49\uFF09\u9700\u8981 CDP \u4E8B\u4EF6\u4E0A\u884C\uFF0C\u6682\u672A\u5F00\u653E`);
7375
+ }
7376
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
7377
+ async function pollUntil2(pred, timeoutMs, intervalMs = 120) {
7378
+ const deadline = Date.now() + timeoutMs;
7379
+ while (Date.now() < deadline) {
7380
+ if (await pred()) return true;
7381
+ await sleep2(intervalMs);
7382
+ }
7383
+ return await pred();
7384
+ }
7385
+ function toExpression(fn, args) {
7386
+ if (typeof fn === "string") return fn;
7387
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7388
+ return `(${fn.toString()})(${callArgs})`;
7389
+ }
7390
+ function rectExpression(selector, index) {
7391
+ return `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); const el = els[${index}]; if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`;
7392
+ }
7393
+ function stateExpression(selector, index) {
7394
+ return `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); const el = els[${index}]; if (!el) return null; const visible = !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); return { found: true, visible, text: el.textContent, html: el.innerHTML, disabled: el.disabled === true || el.getAttribute('disabled') !== null }; })()`;
7395
+ }
7396
+ var BridgePage = class {
7397
+ taskName;
7398
+ tabId;
7399
+ _url;
7400
+ closed = false;
7401
+ mouse;
7402
+ keyboard;
7403
+ ctxStub;
7404
+ constructor(taskName, tabId) {
7405
+ this.taskName = taskName;
7406
+ this.tabId = tabId;
7407
+ this._url = "about:blank";
7408
+ this.mouse = new BridgeMouse(this);
7409
+ this.keyboard = new BridgeKeyboard(this);
7410
+ this.ctxStub = new BridgeContextStub(this);
7411
+ }
7412
+ get bridgeTabId() {
7413
+ return this.tabId;
7414
+ }
7415
+ get bridgeTaskName() {
7416
+ return this.taskName;
7417
+ }
7418
+ /** 会话内 tab 被任务组回收后重锚(task-open 复用路径刷新 tabId) */
7419
+ retab(tabId) {
7420
+ this.tabId = tabId;
7421
+ }
7422
+ async exec(cmd, args = {}) {
7423
+ return bridgeExec(cmd, { ...args, tabId: this.tabId, task: this.taskName });
7424
+ }
7425
+ async evalExpr(expression) {
7426
+ const data = await this.exec("evaluate", { expression });
7427
+ if (data.ok !== true) throw new Error(`[bridge-session] evaluate \u5931\u8D25: ${String(data.error ?? "unknown")}`);
7428
+ return data.value ?? null;
7429
+ }
7430
+ async rectOf(selector, index = 0) {
7431
+ const raw = await this.evalExpr(rectExpression(selector, index));
7432
+ if (raw == null) return null;
7433
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7434
+ }
7435
+ async stateOf(selector, index = 0) {
7436
+ const raw = await this.evalExpr(stateExpression(selector, index));
7437
+ if (raw == null) return null;
7438
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7439
+ }
7440
+ async trustedClickAt(x, y) {
7441
+ const r = await this.exec("trustedClick", { x, y });
7442
+ if (r.ok !== true) throw new Error(`[bridge-session] trustedClick \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7443
+ }
7444
+ async clickSelector(selector, index = 0) {
7445
+ await this.waitForSelector(selector, { state: "attached", timeout: 8e3 }).catch(() => {
7446
+ throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7447
+ });
7448
+ const rect = await this.rectOf(selector, index);
7449
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7450
+ await this.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7451
+ }
7452
+ // ── Navigation ──
7453
+ async goto(url, opts) {
7454
+ await this.exec("navigate", { url });
7455
+ this._url = url;
7456
+ await this.waitForLoadState(opts?.waitUntil ?? "load", opts?.timeout ?? 3e4).catch(() => {
7457
+ });
7458
+ return {
7459
+ status: () => 200,
7460
+ ok: () => true,
7461
+ url: () => url,
7462
+ headers: () => ({})
7463
+ };
7464
+ }
7465
+ async goBack() {
7466
+ await this._cdpSend("Page.navigateToHistory", { entryId: -1 });
7467
+ }
7468
+ async goForward() {
7469
+ await this._cdpSend("Page.navigateToHistory", { entryId: 1 });
7470
+ }
7471
+ async reload(opts) {
7472
+ await this._cdpSend("Page.reload", {});
7473
+ await this.waitForLoadState("load", opts?.timeout ?? 3e4).catch(() => {
7474
+ });
7475
+ }
7476
+ async waitForLoadState(state = "load", timeout = 3e4) {
7477
+ const want = state === "domcontentloaded" ? ["interactive", "complete"] : ["complete"];
7478
+ const ok33 = await pollUntil2(async () => {
7479
+ const rs = await this.evalExpr("document.readyState").catch(() => "loading");
7480
+ return want.includes(rs);
7481
+ }, timeout);
7482
+ if (!ok33) throw new Error(`[bridge-session] waitForLoadState(${state}) \u8D85\u65F6`);
7483
+ }
7484
+ async waitForTimeout(ms) {
7485
+ await sleep2(ms);
7486
+ }
7487
+ async waitForSelector(selector, opts) {
7488
+ const state = opts?.state ?? "visible";
7489
+ const timeout = opts?.timeout ?? 3e4;
7490
+ const ok33 = await pollUntil2(async () => {
7491
+ const st = await this.stateOf(selector).catch(() => null);
7492
+ if (!st) return state === "detached";
7493
+ if (state === "attached") return st.found;
7494
+ if (state === "visible") return st.found && st.visible;
7495
+ if (state === "hidden") return !st.found || !st.visible;
7496
+ return !st.found;
7497
+ }, timeout);
7498
+ if (!ok33) throw new Error(`[bridge-session] waitForSelector(${selector}, ${state}) \u8D85\u65F6`);
7499
+ }
7500
+ async waitForFunction(fn, opts, ...args) {
7501
+ const expression = toExpression(fn, args);
7502
+ const timeout = opts?.timeout ?? 3e4;
7503
+ const interval = typeof opts?.polling === "number" ? opts.polling : 120;
7504
+ let last = null;
7505
+ const ok33 = await pollUntil2(async () => {
7506
+ last = await this.evalExpr(expression).catch(() => false);
7507
+ return Boolean(last);
7508
+ }, timeout, interval);
7509
+ if (!ok33) throw new Error(`[bridge-session] waitForFunction \u8D85\u65F6\uFF08last=${JSON.stringify(last)?.slice(0, 80)}\uFF09`);
7510
+ return last;
7511
+ }
7512
+ async waitForURL(url, opts) {
7513
+ const match = (href) => {
7514
+ if (typeof url === "string") return href === url || href.startsWith(url);
7515
+ if (url instanceof RegExp) return url.test(href);
7516
+ return url(href);
7517
+ };
7518
+ const ok33 = await pollUntil2(async () => {
7519
+ const href = await this.evalExpr("location.href").catch(() => "");
7520
+ if (match(href)) {
7521
+ this._url = href;
7522
+ return true;
7523
+ }
7524
+ return false;
7525
+ }, opts?.timeout ?? 3e4);
7526
+ if (!ok33) throw new Error("[bridge-session] waitForURL \u8D85\u65F6");
7527
+ }
7528
+ async waitForResponse() {
7529
+ return unimplemented("waitForResponse\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7530
+ }
7531
+ async waitForRequest() {
7532
+ return unimplemented("waitForRequest\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7533
+ }
7534
+ url() {
7535
+ return this._url;
7536
+ }
7537
+ async title() {
7538
+ return this.evalExpr("document.title");
7539
+ }
7540
+ async content() {
7541
+ return this.evalExpr("document.documentElement.outerHTML");
7542
+ }
7543
+ // ── Evaluation ──
7544
+ async evaluate(fn, ...args) {
7545
+ return this.evalExpr(toExpression(fn, args));
7546
+ }
7547
+ async $eval(selector, fn, ...args) {
7548
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7549
+ const expression = `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) throw new Error('no element: ${selector.replace(/'/g, "\\'")}'); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "el, " + callArgs : "el"}); })()`;
7550
+ return this.evalExpr(expression);
7551
+ }
7552
+ async $$eval(selector, fn, ...args) {
7553
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7554
+ const expression = `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "els, " + callArgs : "els"}); })()`;
7555
+ return this.evalExpr(expression);
7556
+ }
7557
+ // ── Locator ──
7558
+ locator(selector) {
7559
+ return new BridgeLocator(this, selector, 0);
7560
+ }
7561
+ getByText(text, opts) {
7562
+ return new BridgeLocator(this, BridgeLocator.textQuery(text, opts?.exact ?? true), 0, true);
7563
+ }
7564
+ getByRole(role, opts) {
7565
+ const name = opts?.name ? `[aria-label*=${JSON.stringify(opts.name)}]` : "";
7566
+ return new BridgeLocator(this, `[role="${role}"]${name}, ${role}${name}`, 0);
7567
+ }
7568
+ getByLabel(label, opts) {
7569
+ void opts;
7570
+ return new BridgeLocator(this, `label[for], [aria-label*=${JSON.stringify(label)}]`, 0);
7571
+ }
7572
+ getByPlaceholder(text) {
7573
+ return new BridgeLocator(this, `[placeholder*=${JSON.stringify(text)}]`, 0);
7574
+ }
7575
+ getByTestId(id) {
7576
+ return new BridgeLocator(this, `[data-testid="${id}"]`, 0);
7577
+ }
7578
+ getByAltText(text) {
7579
+ return new BridgeLocator(this, `[alt*=${JSON.stringify(text)}]`, 0);
7580
+ }
7581
+ getByTitle(text) {
7582
+ return new BridgeLocator(this, `[title*=${JSON.stringify(text)}]`, 0);
7583
+ }
7584
+ // ── Interaction shortcuts ──
7585
+ async click(selector, _opts) {
7586
+ await this.clickSelector(selector);
7587
+ }
7588
+ async dblclick(selector, _opts) {
7589
+ const rect = await this.rectOf(selector);
7590
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7591
+ const x = Math.round(rect.x + rect.width / 2);
7592
+ const y = Math.round(rect.y + rect.height / 2);
7593
+ await this.trustedClickAt(x, y);
7594
+ await sleep2(60);
7595
+ await this.trustedClickAt(x, y);
7596
+ }
7597
+ async fill(selector, value, _opts) {
7598
+ const direct = await this.exec("fill", { selector, value });
7599
+ if (direct.ok === true) return;
7600
+ const typed = await this.exec("type", { selector, text: value });
7601
+ if (typed.ok !== true) throw new Error(`[bridge-session] fill \u5931\u8D25: ${String(direct.error ?? typed.error ?? "unknown")}`);
7602
+ }
7603
+ async press(selector, key, _opts) {
7604
+ await this.clickSelector(selector);
7605
+ await this.keyboard.press(key);
7606
+ }
7607
+ async hover(selector, _opts) {
7608
+ const rect = await this.rectOf(selector);
7609
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7610
+ await this.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7611
+ }
7612
+ async type(selector, text, _opts) {
7613
+ const r = await this.exec("type", { selector, text });
7614
+ if (r.ok !== true) throw new Error(`[bridge-session] type \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7615
+ }
7616
+ async check(selector, _opts) {
7617
+ const st = await this.stateOf(selector);
7618
+ if (st && !await this.evalExpr(`document.querySelector(${JSON.stringify(selector)}).checked`)) {
7619
+ await this.clickSelector(selector);
7620
+ }
7621
+ }
7622
+ async uncheck(selector, _opts) {
7623
+ const checked = await this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.checked === true`);
7624
+ if (checked) await this.clickSelector(selector);
7625
+ }
7626
+ async selectOption(selector, value) {
7627
+ const v = Array.isArray(value) ? value : [value];
7628
+ const result = await this.evalExpr(
7629
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return []; const vals = ${JSON.stringify(v)}; let applied = []; for (const opt of el.options) { if (vals.includes(opt.value) || vals.includes(opt.text)) { opt.selected = true; applied.push(opt.value); } } el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); return applied; })()`
7630
+ );
7631
+ return result ?? [];
7632
+ }
7633
+ // ── Convenience selectors ──
7634
+ async textContent(selector) {
7635
+ const st = await this.stateOf(selector);
7636
+ return st?.text ?? null;
7637
+ }
7638
+ async innerText(selector) {
7639
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
7640
+ }
7641
+ async innerHTML(selector) {
7642
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerHTML ?? ''`);
7643
+ }
7644
+ async getAttribute(selector, name) {
7645
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
7646
+ }
7647
+ // ── Query ──
7648
+ async $(selector) {
7649
+ const st = await this.stateOf(selector);
7650
+ return st ? new BridgeElementHandle(this, selector, 0) : null;
7651
+ }
7652
+ async $$(selector) {
7653
+ const count = await this.evalExpr(`document.querySelectorAll(${JSON.stringify(selector)}).length`);
7654
+ return Array.from({ length: count }, (_, i) => new BridgeElementHandle(this, selector, i));
7655
+ }
7656
+ // ── Screen ──
7657
+ async screenshot(_opts) {
7658
+ const r = await this.exec("screenshot", {});
7659
+ const b64 = r.base64;
7660
+ if (!b64) throw new Error(`[bridge-session] screenshot \u5931\u8D25: ${String(r.error ?? "no base64")}`);
7661
+ return Buffer.from(b64, "base64");
7662
+ }
7663
+ async pdf(_opts) {
7664
+ return unimplemented("pdf");
7665
+ }
7666
+ viewportSize() {
7667
+ return null;
7668
+ }
7669
+ async setViewportSize(_size) {
7670
+ unimplemented("setViewportSize");
7671
+ }
7672
+ async setDeviceScaleFactor(_dsf) {
7673
+ unimplemented("setDeviceScaleFactor");
7674
+ }
7675
+ // ── Scripts / UA / Frames / OOPIF ──
7676
+ async addInitScript(_script) {
7677
+ unimplemented("addInitScript");
7678
+ }
7679
+ async setUserAgent(_ua) {
7680
+ unimplemented("setUserAgent");
7681
+ }
7682
+ async discoverFrames() {
7683
+ return [];
7684
+ }
7685
+ async evaluateInFrame(_urlIncludes, _expression) {
7686
+ return unimplemented("evaluateInFrame");
7687
+ }
7688
+ async listFrameTargets() {
7689
+ return [];
7690
+ }
7691
+ async frameMouse(_urlIncludes, _opts) {
7692
+ return unimplemented("frameMouse");
7693
+ }
7694
+ async runFrameMouse(_urlIncludes, _fn) {
7695
+ return unimplemented("runFrameMouse");
7696
+ }
7697
+ async clickInFrame(_urlIncludes, _selector, _opts) {
7698
+ return unimplemented("clickInFrame");
7699
+ }
7700
+ async fillInFrame(_urlIncludes, _selector, _text, _opts) {
7701
+ return unimplemented("fillInFrame");
7702
+ }
7703
+ // ── Page management ──
7704
+ async bringToFront() {
7705
+ await this._cdpSend("Page.bringToFront", {});
7706
+ }
7707
+ async setExtraHTTPHeaders(_headers) {
7708
+ unimplemented("setExtraHTTPHeaders");
7709
+ }
7710
+ async setOfflineMode(_offline) {
7711
+ unimplemented("setOfflineMode");
7712
+ }
7713
+ async route(_url, _handler) {
7714
+ unimplemented("route");
7715
+ }
7716
+ async unroute(_url, _handler) {
7717
+ unimplemented("unroute");
7718
+ }
7719
+ async setInputFiles(_selector, _files) {
7720
+ unimplemented("setInputFiles");
7721
+ }
7722
+ async dropFiles(_selector, _payload) {
7723
+ unimplemented("dropFiles");
7724
+ }
7725
+ setBeforeUnloadBehavior(_mode) {
7726
+ }
7727
+ async dragAndDrop(_source, _target) {
7728
+ unimplemented("dragAndDrop");
7729
+ }
7730
+ // ── Dialog / events ──
7731
+ on(_event, _handler) {
7732
+ }
7733
+ off(_event, _handler) {
7734
+ }
7735
+ async waitForEvent(_event, opts) {
7736
+ await sleep2(opts?.timeout ?? 3e4);
7737
+ return unimplemented(`waitForEvent(${_event})\u2014\u2014\u4E8B\u4EF6\u7C7B\u80FD\u529B`);
7738
+ }
7739
+ // ── CDP escape hatch ──
7740
+ async _cdpSend(method, params) {
7741
+ const r = await this.exec("cdp", { method, params: params ?? {} });
7742
+ if (r.ok !== true) throw new Error(`[bridge-session] cdp ${method} \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7743
+ return r.data ?? null;
7744
+ }
7745
+ _subscribe(_event, _handler) {
7746
+ return () => {
7747
+ };
7748
+ }
7749
+ // ── Lifecycle ──
7750
+ async close() {
7751
+ if (this.closed) return;
7752
+ this.closed = true;
7753
+ await bridgeExec("task-close", { name: this.taskName }).catch(() => {
7754
+ });
7755
+ }
7756
+ isClosed() {
7757
+ return this.closed;
7758
+ }
7759
+ context() {
7760
+ return this.ctxStub;
7761
+ }
7762
+ browser() {
7763
+ return this.ctxStub.browser();
7764
+ }
7765
+ mainFrame() {
7766
+ return new BridgeFrame(this);
7767
+ }
7768
+ frames() {
7769
+ return [this.mainFrame()];
7770
+ }
7771
+ };
7772
+ var BridgeLocator = class _BridgeLocator {
7773
+ constructor(page, selector, index, isText = false) {
7774
+ this.page = page;
7775
+ this.selector = selector;
7776
+ this.index = index;
7777
+ this.isText = isText;
7778
+ }
7779
+ page;
7780
+ selector;
7781
+ index;
7782
+ isText;
7783
+ /** text 伪查询编码:==精确 / ~包含(无等价 CSS,rect() 编译为 evaluate 表达式) */
7784
+ static textQuery(text, exact) {
7785
+ return `${exact ? "==" : "~"}${text}`;
7786
+ }
7787
+ async rect() {
7788
+ if (!this.isText) return this.page.rectOf(this.selector, this.index);
7789
+ const m = /^(==|~)([\s\S]*)$/.exec(this.selector);
7790
+ const exact = m?.[1] === "==";
7791
+ const text = JSON.stringify(m?.[2] ?? this.selector);
7792
+ const cmp = exact ? `e.textContent.trim() === ${text}` : `e.textContent.includes(${text})`;
7793
+ const expression = `(() => { const cand = [...document.querySelectorAll('a,button,[role=button],input,select,textarea,label,h1,h2,h3,p,span,div,li')]; const el = cand.filter(e => ${cmp})[${this.index}]; if (!el) return null; const b = el.getBoundingClientRect(); return { x: b.x, y: b.y, width: b.width, height: b.height }; })()`;
7794
+ const r = await this.page.evaluate(expression);
7795
+ const v = r;
7796
+ return v == null ? null : typeof v === "string" ? JSON.parse(v) : v;
7797
+ }
7798
+ async click(_opts) {
7799
+ const rect = await this.rect();
7800
+ if (!rect) throw new Error(`[bridge-session] locator \u672A\u547D\u4E2D: ${this.selector}`);
7801
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7802
+ }
7803
+ async fill(value, _opts) {
7804
+ if (!this.isText) {
7805
+ await this.page.fill(this.selector, value);
7806
+ return;
7807
+ }
7808
+ await this.click();
7809
+ await this.page.keyboard.type(value);
7810
+ }
7811
+ async press(key, _opts) {
7812
+ await this.page.keyboard.press(key);
7813
+ }
7814
+ async pressSequentially(text, opts) {
7815
+ await this.page.keyboard.type(text, opts);
7816
+ }
7817
+ async hover(_opts) {
7818
+ const rect = await this.rect();
7819
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7820
+ }
7821
+ async type(text, _opts) {
7822
+ await this.page.keyboard.type(text);
7823
+ }
7824
+ async check(_opts) {
7825
+ await this.click();
7826
+ }
7827
+ async uncheck(_opts) {
7828
+ await this.click();
7829
+ }
7830
+ async selectOption(value) {
7831
+ if (!this.isText) return this.page.selectOption(this.selector, value);
7832
+ return unimplemented("text locator selectOption");
7833
+ }
7834
+ async screenshot(opts) {
7835
+ return this.page.screenshot(opts);
7836
+ }
7837
+ async focus() {
7838
+ if (!this.isText) await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.focus()`);
7839
+ }
7840
+ async waitFor(opts) {
7841
+ if (!this.isText) await this.page.waitForSelector(this.selector, opts);
7842
+ }
7843
+ async count() {
7844
+ if (!this.isText) return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)}).length`);
7845
+ const rect = await this.rect();
7846
+ return rect ? 1 : 0;
7847
+ }
7848
+ async isVisible() {
7849
+ const rect = await this.rect();
7850
+ return rect !== null && rect.width + rect.height > 0;
7851
+ }
7852
+ async isHidden() {
7853
+ return !await this.isVisible();
7854
+ }
7855
+ async isEnabled() {
7856
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7857
+ return st ? !st.disabled : false;
7858
+ }
7859
+ async isDisabled() {
7860
+ return !await this.isEnabled();
7861
+ }
7862
+ async boundingBox() {
7863
+ return this.rect();
7864
+ }
7865
+ async textContent() {
7866
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7867
+ return st?.text ?? null;
7868
+ }
7869
+ async innerText() {
7870
+ return await this.textContent() ?? "";
7871
+ }
7872
+ async innerHTML() {
7873
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7874
+ return st?.html ?? "";
7875
+ }
7876
+ async getAttribute(name) {
7877
+ return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.getAttribute(${JSON.stringify(name)}) ?? null`);
7878
+ }
7879
+ async evaluate(fn, ...args) {
7880
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7881
+ return this.page.evaluate(`(() => { const el = document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]; return el ? (${typeof fn === "string" ? fn : fn.toString()})(${callArgs}) : null; })()`);
7882
+ }
7883
+ async ariaSnapshot() {
7884
+ return unimplemented("ariaSnapshot");
7885
+ }
7886
+ first() {
7887
+ return new _BridgeLocator(this.page, this.selector, 0, this.isText);
7888
+ }
7889
+ last() {
7890
+ return unimplemented("locator.last()");
7891
+ }
7892
+ nth(index) {
7893
+ return new _BridgeLocator(this.page, this.selector, index, this.isText);
7894
+ }
7895
+ filter(_opts) {
7896
+ return unimplemented("locator.filter()");
7897
+ }
7898
+ async all() {
7899
+ const n = await this.count();
7900
+ return Array.from({ length: n }, (_, i) => new _BridgeLocator(this.page, this.selector, i, this.isText));
7901
+ }
7902
+ };
7903
+ var BridgeElementHandle = class {
7904
+ constructor(page, selector, index) {
7905
+ this.page = page;
7906
+ this.selector = selector;
7907
+ this.index = index;
7908
+ }
7909
+ page;
7910
+ selector;
7911
+ index;
7912
+ async click(_opts) {
7913
+ const rect = await this.page.rectOf(this.selector, this.index);
7914
+ if (!rect) throw new Error("[bridge-session] element \u672A\u547D\u4E2D");
7915
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7916
+ }
7917
+ async fill(value, _opts) {
7918
+ await this.page.fill(this.selector, value);
7919
+ }
7920
+ async hover() {
7921
+ const rect = await this.page.rectOf(this.selector, this.index);
7922
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7923
+ }
7924
+ async press(key) {
7925
+ await this.page.keyboard.press(key);
7926
+ }
7927
+ async screenshot(opts) {
7928
+ return this.page.screenshot(opts);
7929
+ }
7930
+ async boundingBox() {
7931
+ return this.page.rectOf(this.selector, this.index);
7932
+ }
7933
+ async isVisible() {
7934
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7935
+ return Boolean(st?.visible);
7936
+ }
7937
+ async isEnabled() {
7938
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7939
+ return st ? !st.disabled : false;
7940
+ }
7941
+ async textContent() {
7942
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7943
+ return st?.text ?? null;
7944
+ }
7945
+ async innerText() {
7946
+ return await this.textContent() ?? "";
7947
+ }
7948
+ async innerHTML() {
7949
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7950
+ return st?.html ?? "";
7951
+ }
7952
+ async getAttribute(name) {
7953
+ return this.page.getAttribute(this.selector, name);
7954
+ }
7955
+ async scrollIntoViewIfNeeded() {
7956
+ await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.scrollIntoView({ block: 'center' })`);
7957
+ }
7958
+ dispose() {
7959
+ }
7960
+ };
7961
+ var KEY_CODES = {
7962
+ Enter: 13,
7963
+ Tab: 9,
7964
+ Escape: 27,
7965
+ Backspace: 8,
7966
+ Delete: 46,
7967
+ ArrowUp: 38,
7968
+ ArrowDown: 40,
7969
+ ArrowLeft: 37,
7970
+ ArrowRight: 39,
7971
+ Home: 36,
7972
+ End: 35,
7973
+ PageUp: 33,
7974
+ PageDown: 34
7975
+ };
7976
+ var BridgeMouse = class {
7977
+ constructor(page) {
7978
+ this.page = page;
7979
+ }
7980
+ page;
7981
+ async dispatch(params) {
7982
+ await this.page._cdpSend("Input.dispatchMouseEvent", params);
7983
+ }
7984
+ async click(x, y, opts) {
7985
+ const button = opts?.button ?? "left";
7986
+ const clickCount = opts?.clickCount ?? 1;
7987
+ const buttons = button === "left" ? 1 : button === "right" ? 2 : 4;
7988
+ await this.dispatch({ type: "mousePressed", x, y, button, buttons, clickCount });
7989
+ if (opts?.delay) await sleep2(opts.delay);
7990
+ await this.dispatch({ type: "mouseReleased", x, y, button, buttons, clickCount });
7991
+ }
7992
+ async dblclick(x, y, opts) {
7993
+ await this.click(x, y, { ...opts, clickCount: 1 });
7994
+ await sleep2(60);
7995
+ await this.click(x, y, { ...opts, clickCount: 2 });
7996
+ }
7997
+ async down(opts) {
7998
+ const button = opts?.button ?? "left";
7999
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button, buttons: button === "left" ? 1 : button === "right" ? 2 : 4, clickCount: 1 });
8000
+ }
8001
+ async up(opts) {
8002
+ const button = opts?.button ?? "left";
8003
+ await this.dispatch({ type: "mouseReleased", x: 0, y: 0, button, buttons: 0, clickCount: 1 });
8004
+ }
8005
+ async move(x, y, opts) {
8006
+ const steps = Math.max(1, opts?.steps ?? 1);
8007
+ for (let i = 1; i <= steps; i++) {
8008
+ await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 0 });
8009
+ }
8010
+ }
8011
+ async wheel(deltaX, deltaY) {
8012
+ await this.dispatch({ type: "mouseWheel", x: 0, y: 0, deltaX, deltaY });
8013
+ }
8014
+ async wheelAt(x, y, deltaX, deltaY) {
8015
+ await this.move(x, y);
8016
+ await this.dispatch({ type: "mouseWheel", x, y, deltaX, deltaY });
8017
+ }
8018
+ async drag(x, y, opts) {
8019
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button: "left", buttons: 1, clickCount: 1 });
8020
+ const steps = Math.max(1, opts?.steps ?? 10);
8021
+ for (let i = 1; i <= steps; i++) await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 1 });
8022
+ await this.dispatch({ type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
8023
+ }
8024
+ };
8025
+ var BridgeKeyboard = class {
8026
+ constructor(page) {
8027
+ this.page = page;
8028
+ }
8029
+ page;
8030
+ async key(event) {
8031
+ await this.page._cdpSend("Input.dispatchKeyEvent", {
8032
+ type: event.type,
8033
+ key: event.key,
8034
+ code: event.code ?? event.key,
8035
+ windowsVirtualKeyCode: KEY_CODES[event.key] ?? (event.key.length === 1 ? event.key.toUpperCase().charCodeAt(0) : 0),
8036
+ nativeVirtualKeyCode: KEY_CODES[event.key] ?? 0,
8037
+ ...event.modifiers !== void 0 ? { modifiers: event.modifiers } : {},
8038
+ ...event.text !== void 0 ? { text: event.text } : {}
8039
+ });
8040
+ }
8041
+ async press(key, _opts) {
8042
+ await this.key({ type: "keyDown", key });
8043
+ await this.key({ type: "keyUp", key });
8044
+ }
8045
+ async pressNav(key) {
8046
+ await this.key({ type: "keyDown", key });
8047
+ }
8048
+ async pressCombo(key, modifier) {
8049
+ const bits = { Alt: 1, Meta: 4, Control: 2, Shift: 8 };
8050
+ await this.key({ type: "keyDown", key: modifier, modifiers: bits[modifier] });
8051
+ await this.key({ type: "keyDown", key, modifiers: bits[modifier] });
8052
+ await this.key({ type: "keyUp", key, modifiers: bits[modifier] });
8053
+ await this.key({ type: "keyUp", key: modifier });
8054
+ }
8055
+ async down(key) {
8056
+ await this.key({ type: "keyDown", key });
8057
+ }
8058
+ async up(key) {
8059
+ await this.key({ type: "keyUp", key });
8060
+ }
8061
+ async type(text, _opts) {
8062
+ const r = await this.page.exec("trusted-type", { text });
8063
+ if (r.ok !== true) {
8064
+ for (const ch of text) await this.key({ type: "keyDown", key: ch, text: ch });
8065
+ }
8066
+ }
8067
+ async insertText(text) {
8068
+ await this.page._cdpSend("Input.insertText", { text });
8069
+ }
8070
+ };
8071
+ var BridgeFrame = class {
8072
+ constructor(bridgePage) {
8073
+ this.bridgePage = bridgePage;
8074
+ }
8075
+ bridgePage;
8076
+ url() {
8077
+ return this.bridgePage.url();
8078
+ }
8079
+ name() {
8080
+ return "";
8081
+ }
8082
+ isDetached() {
8083
+ return this.bridgePage.isClosed();
8084
+ }
8085
+ page() {
8086
+ return this.bridgePage;
8087
+ }
8088
+ async evaluate(fn, ...args) {
8089
+ return this.bridgePage.evaluate(fn, ...args);
8090
+ }
8091
+ async $(selector) {
8092
+ return this.bridgePage.$(selector);
8093
+ }
8094
+ async $$(selector) {
8095
+ return this.bridgePage.$$(selector);
8096
+ }
8097
+ };
8098
+ var BridgeBrowserStub = class {
8099
+ disconnected = false;
8100
+ ctx;
8101
+ constructor(ctx) {
8102
+ this.ctx = ctx;
8103
+ }
8104
+ async close() {
8105
+ }
8106
+ async disconnect() {
8107
+ this.disconnected = true;
8108
+ }
8109
+ async newContext(_opts) {
8110
+ return unimplemented("browser.newContext");
8111
+ }
8112
+ contexts() {
8113
+ return [this.ctx];
8114
+ }
8115
+ async discoverContexts() {
8116
+ }
8117
+ on(_event, _handler) {
8118
+ }
8119
+ off(_event, _handler) {
8120
+ }
8121
+ };
8122
+ var BridgeContextStub = class {
8123
+ constructor(bridgePage) {
8124
+ this.bridgePage = bridgePage;
8125
+ this.browserStub = new BridgeBrowserStub(this);
8126
+ }
8127
+ bridgePage;
8128
+ browserStub;
8129
+ async newPage() {
8130
+ return this.bridgePage;
8131
+ }
8132
+ pages() {
8133
+ return this.bridgePage.isClosed() ? [] : [this.bridgePage];
8134
+ }
8135
+ async close() {
8136
+ await this.bridgePage.close();
8137
+ }
8138
+ browser() {
8139
+ return this.browserStub;
8140
+ }
8141
+ async newCDPSession(_page) {
8142
+ return unimplemented("newCDPSession");
8143
+ }
8144
+ async addInitScript(_script) {
8145
+ unimplemented("addInitScript");
8146
+ }
8147
+ async cookies(_urls) {
8148
+ return [];
8149
+ }
8150
+ async addCookies(_cookies) {
8151
+ unimplemented("addCookies");
8152
+ }
8153
+ async clearCookies() {
8154
+ unimplemented("clearCookies");
8155
+ }
8156
+ on(_event, _handler) {
8157
+ }
8158
+ off(_event, _handler) {
8159
+ }
8160
+ };
8161
+ var realMetaStore = {
8162
+ read: (name) => readSessionDiskMeta(name),
8163
+ save: (name, data) => {
8164
+ saveSessionDiskMeta(name, data);
8165
+ }
8166
+ };
8167
+ var metaStore = realMetaStore;
8168
+ async function findOrCreateBridgeSession(name, opts) {
8169
+ const store = metaStore ?? realMetaStore;
8170
+ const meta = store.read(name);
8171
+ if (meta?.kind !== "bridge" && !opts?.preferBridge) return null;
8172
+ const inMemory = sessions.find(name);
8173
+ if (inMemory?.bridge) return inMemory;
8174
+ const taskName = meta?.taskName ?? name;
8175
+ const opened = await bridgeExec("task-open", { name: taskName }).catch(() => null);
8176
+ const tabId = Number(opened?.tabId ?? 0);
8177
+ if (!opened || !tabId) {
8178
+ throw new Error("[bridge-session] task-open \u5931\u8D25\uFF1Abridge \u672A\u542F\u52A8\u6216\u6269\u5C55\u672A\u8FDE\u63A5\uFF08\u5148\u8DD1 xbrowser chrome-bridge serve / revive\uFF09");
8179
+ }
8180
+ const id = meta?.id ?? newSessionId();
8181
+ const createdAt = meta?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
8182
+ store.save(name, {
8183
+ id,
8184
+ kind: "bridge",
8185
+ taskName,
8186
+ tabId,
8187
+ url: opts?.url ?? meta?.url ?? "",
8188
+ createdAt
8189
+ });
8190
+ const page = new BridgePage(taskName, tabId);
8191
+ const session = registerSession({
8192
+ id,
8193
+ name,
8194
+ context: page.context(),
8195
+ page,
8196
+ browser: page.browser(),
8197
+ createdAt,
8198
+ bridge: { taskName, tabId }
8199
+ });
8200
+ return session;
8201
+ }
8202
+
7343
8203
  // src/tips/dom-watcher.ts
7344
8204
  var DOM_WATCHER_SCRIPT = `
7345
8205
  (function() {
@@ -7970,127 +8830,9 @@ function classifyFailure(message) {
7970
8830
  return pick(FAIL_CODES.unknown);
7971
8831
  }
7972
8832
 
7973
- // src/lib/mistake-ledger.ts
7974
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4, appendFileSync } from "fs";
7975
- import { homedir as homedir5 } from "os";
7976
- import { join as join7, dirname as dirname3 } from "path";
7977
- var MISTAKE_THRESHOLD = 3;
7978
- var MISTAKE_LEDGER_PATH = join7(
7979
- homedir5(),
7980
- ".xbrowser",
7981
- "knowledge",
7982
- "mistakes.json"
7983
- );
7984
- function emptyLedger() {
7985
- return { version: 1, entries: {} };
7986
- }
7987
- function normalizeMistakeText(value) {
7988
- return value.replace(/\d{4}-\d{2}-\d{2}T[^'"\s]+/g, "<timestamp>").replace(/\d+(?:\.\d+)?\s*(?:ms|s)\b/gi, "<duration>").replace(/\b\d+\b/g, "<number>").replace(/\s+/g, " ").trim();
7989
- }
7990
- function mistakeFingerprint(category, message) {
7991
- return `${category}::${normalizeMistakeText(message)}`;
7992
- }
7993
- function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
7994
- try {
7995
- const parsed = JSON.parse(readFileSync5(path2, "utf8"));
7996
- if (parsed.version !== 1 || typeof parsed.entries !== "object") {
7997
- return emptyLedger();
7998
- }
7999
- return parsed;
8000
- } catch {
8001
- return emptyLedger();
8002
- }
8003
- }
8004
- function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
8005
- mkdirSync4(join7(path2, ".."), { recursive: true });
8006
- writeFileSync4(path2, JSON.stringify(ledger, null, 2), "utf8");
8007
- }
8008
- var MISTAKES_MD_HEADER = `# \u6301\u4E45\u5316\u9519\u9898\u672C\uFF08 graduated mistake ledger \uFF09
8009
-
8010
- > \u8FD0\u884C\u65F6\u9519\u9898\u672C\uFF08~/.xbrowser/knowledge/mistakes.json\uFF0CJSON\uFF09\u53EA\u505A\u8BA1\u6570\uFF1B
8011
- > **\u540C\u4E00\u9519\u8BEF\u6307\u7EB9\u51FA\u73B0 \u2265${MISTAKE_THRESHOLD} \u6B21\u81EA\u52A8\u6C89\u6DC0\u5230\u672C\u6587\u4EF6**\uFF08\u6309\u65E5\u671F\u8BB0\u5F55\uFF09\u3002
8012
- > \u672C\u6587\u4EF6\u88AB AGENTS.md \u5F15\u7528\u2014\u2014\u6240\u6709 Agent \u5F00\u5DE5\u524D\u5FC5\u8BFB\uFF0C\u907F\u514D\u91CD\u8E48\u8986\u8F99\u3002
8013
- > \u4FEE\u590D\u540E\u5728\u5BF9\u5E94\u6761\u76EE\u8865\u300C\u6839\u56E0\u300D\u4E0E\u300C\u4FEE\u590D\u300D\u4E24\u884C\uFF1B\u65B0\u6761\u76EE\u7531 recordMistake \u81EA\u52A8\u8FFD\u52A0\uFF0C\u4EBA\u5DE5\u53EA\u8865\u4E0D\u5220\u3002
8014
-
8015
- `;
8016
- function persistentMistakesPath() {
8017
- if (process.env.XBROWSER_MISTAKES_MD) return process.env.XBROWSER_MISTAKES_MD;
8018
- let dir = process.cwd();
8019
- for (let i = 0; i < 8; i++) {
8020
- const pkg = join7(dir, "package.json");
8021
- if (existsSync4(pkg)) {
8022
- try {
8023
- const name = JSON.parse(readFileSync5(pkg, "utf8")).name;
8024
- if (name === "@xbrowser/cli") return join7(dir, "docs", "mistakes.md");
8025
- } catch {
8026
- }
8027
- }
8028
- const parent = join7(dir, "..");
8029
- if (parent === dir) break;
8030
- dir = parent;
8031
- }
8032
- return join7(homedir5(), ".xbrowser", "knowledge", "mistakes.md");
8033
- }
8034
- function graduateToMarkdown(entry) {
8035
- const mdPath = persistentMistakesPath();
8036
- try {
8037
- mkdirSync4(dirname3(mdPath), { recursive: true });
8038
- if (!existsSync4(mdPath)) writeFileSync4(mdPath, MISTAKES_MD_HEADER);
8039
- const day = entry.lastSeen.slice(0, 10);
8040
- const first = entry.occurrences[0];
8041
- const anchor = `<!-- fingerprint:${entry.fingerprint} -->`;
8042
- const existing = existsSync4(mdPath) ? readFileSync5(mdPath, "utf8") : "";
8043
- if (existing.includes(anchor)) return;
8044
- const block = [
8045
- `## ${day} \xB7 ${first.command} \xB7 ${first.message.split("\n")[0].slice(0, 80)}`,
8046
- anchor,
8047
- `- **\u7C7B\u522B**: ${entry.category}`,
8048
- `- **\u9996\u6B21/\u6700\u8FD1**: ${entry.firstSeen.slice(0, 19)} \u2192 ${entry.lastSeen.slice(0, 19)}\uFF08\u7D2F\u8BA1 ${entry.occurrences.length} \u6B21\uFF09`,
8049
- `- **\u5178\u578B\u9519\u8BEF**: ${first.message.split("\n")[0].slice(0, 160)}`,
8050
- `- **\u6839\u56E0**: \uFF08\u5F85\u8865\u2014\u2014\u4FEE\u590D\u65F6\u586B\u5199\uFF09`,
8051
- `- **\u4FEE\u590D**: \uFF08\u5F85\u8865\u2014\u2014\u586B PR \u53F7\u6216\u4FEE\u590D\u8BF4\u660E\uFF09`,
8052
- ""
8053
- ].join("\n");
8054
- appendFileSync(mdPath, block);
8055
- } catch {
8056
- }
8057
- }
8058
- function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
8059
- if (!input.category) throw new Error("mistake category is required");
8060
- if (!input.command) throw new Error("mistake command is required");
8061
- if (!input.message) throw new Error("mistake message is required");
8062
- const ledger = readMistakeLedger(path2);
8063
- const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
8064
- const previous = ledger.entries[fingerprint];
8065
- const occurrence = {
8066
- timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
8067
- command: input.command,
8068
- message: input.message,
8069
- ...input.context ? { context: input.context } : {}
8070
- };
8071
- const entry = previous ? {
8072
- ...previous,
8073
- lastSeen: occurrence.timestamp,
8074
- occurrences: [...previous.occurrences, occurrence].slice(-100),
8075
- constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
8076
- } : {
8077
- fingerprint,
8078
- category: input.category,
8079
- firstSeen: occurrence.timestamp,
8080
- lastSeen: occurrence.timestamp,
8081
- occurrences: [occurrence],
8082
- constrained: false
8083
- };
8084
- ledger.entries[fingerprint] = entry;
8085
- writeMistakeLedger(ledger, path2);
8086
- const newlyConstrained = Boolean(previous && !previous.constrained && entry.constrained);
8087
- if (newlyConstrained) graduateToMarkdown(entry);
8088
- return { entry, newlyConstrained };
8089
- }
8090
-
8091
8833
  // src/executor/foundation.ts
8092
- import { homedir as homedir7 } from "os";
8093
- import { join as join9 } from "path";
8834
+ import { homedir as homedir6 } from "os";
8835
+ import { join as join8 } from "path";
8094
8836
  import {
8095
8837
  CompositeStorage as CompositeStorage2,
8096
8838
  configureArchiveStore,
@@ -8103,19 +8845,19 @@ import {
8103
8845
  import {
8104
8846
  Core
8105
8847
  } from "@dyyz1993/xcli-core";
8106
- import { resolve as resolve2, basename, dirname as dirname4 } from "path";
8107
- import { existsSync as existsSync7, readdirSync } from "fs";
8108
- import { homedir as homedir6 } from "os";
8848
+ import { resolve as resolve2, basename, dirname as dirname3 } from "path";
8849
+ import { existsSync as existsSync6, readdirSync } from "fs";
8850
+ import { homedir as homedir5 } from "os";
8109
8851
 
8110
8852
  // src/plugin/metadata-parser.ts
8111
- import { existsSync as existsSync5 } from "fs";
8853
+ import { existsSync as existsSync4 } from "fs";
8112
8854
  import { resolve } from "path";
8113
8855
 
8114
8856
  // src/utils/json-file.ts
8115
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
8857
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
8116
8858
  function readJsonFile(filePath, defaultValue) {
8117
8859
  try {
8118
- const content = readFileSync6(filePath, "utf-8");
8860
+ const content = readFileSync5(filePath, "utf-8");
8119
8861
  return JSON.parse(content);
8120
8862
  } catch {
8121
8863
  return defaultValue;
@@ -8127,7 +8869,7 @@ var PluginMetadataParser = class {
8127
8869
  static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
8128
8870
  static parseFromPackageJson(pluginPath) {
8129
8871
  const packageJsonPath = resolve(pluginPath, "package.json");
8130
- if (!existsSync5(packageJsonPath)) {
8872
+ if (!existsSync4(packageJsonPath)) {
8131
8873
  return null;
8132
8874
  }
8133
8875
  const packageJson = readJsonFile(packageJsonPath, null);
@@ -8191,20 +8933,20 @@ var PluginMetadataParser = class {
8191
8933
  };
8192
8934
 
8193
8935
  // src/plugin/ensure-deps.ts
8194
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
8195
- import { join as join8 } from "path";
8936
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
8937
+ import { join as join7 } from "path";
8196
8938
  import { execSync } from "child_process";
8197
8939
  var SHARED_PLUGIN_DEPENDENCIES = {
8198
8940
  "zod": "^3.24.0",
8199
8941
  "@dyyz1993/xcli-core": "^0.19.0"
8200
8942
  };
8201
8943
  function ensurePluginDependencies(pluginsDir) {
8202
- const zodPath = join8(pluginsDir, "node_modules", "zod");
8203
- if (existsSync6(zodPath)) return;
8204
- mkdirSync5(pluginsDir, { recursive: true });
8205
- const pkgPath = join8(pluginsDir, "package.json");
8944
+ const zodPath = join7(pluginsDir, "node_modules", "zod");
8945
+ if (existsSync5(zodPath)) return;
8946
+ mkdirSync4(pluginsDir, { recursive: true });
8947
+ const pkgPath = join7(pluginsDir, "package.json");
8206
8948
  let pkg = {};
8207
- if (existsSync6(pkgPath)) {
8949
+ if (existsSync5(pkgPath)) {
8208
8950
  try {
8209
8951
  pkg = readJsonFile(pkgPath, {});
8210
8952
  } catch {
@@ -8218,11 +8960,11 @@ function ensurePluginDependencies(pluginsDir) {
8218
8960
  needsInstall = true;
8219
8961
  }
8220
8962
  }
8221
- if (!needsInstall && existsSync6(join8(pluginsDir, "node_modules"))) return;
8963
+ if (!needsInstall && existsSync5(join7(pluginsDir, "node_modules"))) return;
8222
8964
  pkg.dependencies = existingDeps;
8223
8965
  pkg.private = true;
8224
8966
  pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
8225
- writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
8967
+ writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
8226
8968
  try {
8227
8969
  execSync("npm install --production --no-package-lock --no-fund --no-audit", {
8228
8970
  cwd: pluginsDir,
@@ -8478,7 +9220,7 @@ var XBrowserPluginLoader = class {
8478
9220
  async loadPlugin(pluginPath, id) {
8479
9221
  const before = new Set(this.core.loader.getSites().map((s) => s.name));
8480
9222
  const instance = await this.loader.loadPlugin(pluginPath, id);
8481
- this.recordSiteAliases(basename(dirname4(pluginPath)), before);
9223
+ this.recordSiteAliases(basename(dirname3(pluginPath)), before);
8482
9224
  return instance;
8483
9225
  }
8484
9226
  async unloadPlugin(id) {
@@ -8492,18 +9234,18 @@ var XBrowserPluginLoader = class {
8492
9234
  }
8493
9235
  async scanAndLoad() {
8494
9236
  const cwd = this.options.cwd || process.cwd();
8495
- const globalDir = this.options.globalDir || resolve2(homedir6(), ".xbrowser/plugins");
9237
+ const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
8496
9238
  ensurePluginDependencies(globalDir);
8497
9239
  const dirs = [
8498
9240
  resolve2(cwd, ".xcli/plugins"),
8499
9241
  resolve2(cwd, "../.xcli/plugins"),
8500
- this.options.userDir || resolve2(homedir6(), ".xcli/plugins"),
9242
+ this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
8501
9243
  globalDir
8502
9244
  ];
8503
9245
  const loaded = [];
8504
9246
  const seen = /* @__PURE__ */ new Set();
8505
9247
  for (const dir of dirs) {
8506
- if (!existsSync7(dir)) continue;
9248
+ if (!existsSync6(dir)) continue;
8507
9249
  const entries = readdirSync(dir, { withFileTypes: true });
8508
9250
  for (const entry of entries) {
8509
9251
  if (!entry.isDirectory()) continue;
@@ -8511,12 +9253,12 @@ var XBrowserPluginLoader = class {
8511
9253
  seen.add(entry.name);
8512
9254
  const pluginDir = resolve2(dir, entry.name);
8513
9255
  let indexPath = resolve2(pluginDir, "index.js");
8514
- if (!existsSync7(indexPath)) {
9256
+ if (!existsSync6(indexPath)) {
8515
9257
  indexPath = resolve2(pluginDir, "index.ts");
8516
9258
  }
8517
- if (!existsSync7(indexPath)) continue;
9259
+ if (!existsSync6(indexPath)) continue;
8518
9260
  try {
8519
- if (!existsSync7(resolve2(pluginDir, "package.json"))) {
9261
+ if (!existsSync6(resolve2(pluginDir, "package.json"))) {
8520
9262
  console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
8521
9263
  } else {
8522
9264
  const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
@@ -8571,7 +9313,7 @@ async function getPluginLoader() {
8571
9313
  // src/executor/foundation.ts
8572
9314
  var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8573
9315
  var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8574
- var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
9316
+ var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8575
9317
  var storageCache = /* @__PURE__ */ new Map();
8576
9318
  function getPluginStorage(pluginName) {
8577
9319
  if (!storageCache.has(pluginName)) {
@@ -8583,7 +9325,7 @@ var archiveInitialized = false;
8583
9325
  function ensureArchiveInit() {
8584
9326
  if (!archiveInitialized) {
8585
9327
  try {
8586
- configureArchiveStore({ archiveDir: join9(homedir7(), ".xbrowser", "archives") });
9328
+ configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
8587
9329
  } catch {
8588
9330
  }
8589
9331
  archiveInitialized = true;
@@ -8621,7 +9363,6 @@ function streamCommandEvent(sessionId, message) {
8621
9363
  // src/executor/chain.ts
8622
9364
  import {
8623
9365
  fail as fail18,
8624
- ok as ok32,
8625
9366
  TipCollector as TipCollector2,
8626
9367
  normalizeTips as normalizeTips7,
8627
9368
  unquote as unquote2
@@ -8866,7 +9607,34 @@ function parsePluginParams(args, schema, base = {}) {
8866
9607
  // src/executor/chain.ts
8867
9608
  async function executeChain(input, options, executeCommand2) {
8868
9609
  const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8869
- const sessionName = options?.sessionName || "default";
9610
+ let sessionName = options?.sessionName || "default";
9611
+ for (const pipeline of pipelines) {
9612
+ const cleaned = [];
9613
+ for (const step of pipeline.pipeline) {
9614
+ const tokens = splitCommand(step);
9615
+ let stripped = false;
9616
+ const kept = [];
9617
+ for (let i = 0; i < tokens.length; i++) {
9618
+ if (options?.fixedSession && (tokens[i] === "--session" || tokens[i].startsWith("--session="))) {
9619
+ throw new Error("Set the session on the run, outside the command chain");
9620
+ }
9621
+ if (tokens[i] === "--session" && i + 1 < tokens.length) {
9622
+ sessionName = tokens[i + 1];
9623
+ stripped = true;
9624
+ i++;
9625
+ continue;
9626
+ }
9627
+ if (tokens[i].startsWith("--session=")) {
9628
+ sessionName = tokens[i].slice("--session=".length);
9629
+ stripped = true;
9630
+ continue;
9631
+ }
9632
+ kept.push(tokens[i]);
9633
+ }
9634
+ cleaned.push(stripped ? kept.join(" ") : step);
9635
+ }
9636
+ pipeline.pipeline = cleaned;
9637
+ }
8870
9638
  const results = [];
8871
9639
  const totalStart = Date.now();
8872
9640
  let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
@@ -8893,6 +9661,14 @@ async function executeChain(input, options, executeCommand2) {
8893
9661
  if (parts.length === 0) continue;
8894
9662
  const cmdName = parts[0];
8895
9663
  const cmdArgs = parts.slice(1);
9664
+ if (options?.handoff && cmdName === "handoff" && cmdArgs.length === 0) {
9665
+ const started = Date.now();
9666
+ const solved = await options.handoff();
9667
+ const message = solved ? "Human handoff completed" : "Human handoff timed out";
9668
+ results.push({ command: cmdName, raw: cmdStr, success: solved, data: null, message, duration: Date.now() - started });
9669
+ if (!solved || type === "or") return stoppedChain(solved, results, totalStart, results.length, message);
9670
+ continue;
9671
+ }
8896
9672
  const loader = await getPluginLoader();
8897
9673
  const internalLoader = loader.getCore().loader;
8898
9674
  const resolvedName = loader.resolveSiteName(cmdName);
@@ -8987,6 +9763,38 @@ async function executePluginChainStep(context) {
8987
9763
  }
8988
9764
  }
8989
9765
  }
9766
+ const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
9767
+ if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
9768
+ const { forwardPluginExec } = await import("./daemon-client-Z3NKNZRL.js");
9769
+ const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
9770
+ const startFwd = Date.now();
9771
+ const fwd = await forwardPluginExec(
9772
+ `${cmdName}.${subCommand}`,
9773
+ pluginParams,
9774
+ sessionName,
9775
+ void 0,
9776
+ userTimeout
9777
+ );
9778
+ if (fwd != null) {
9779
+ const fwdOk = fwd.success !== false;
9780
+ results.push({
9781
+ command: `${cmdName} ${subCommand}`,
9782
+ raw: cmdStr,
9783
+ success: fwdOk,
9784
+ data: fwd.data ?? null,
9785
+ message: fwd.message,
9786
+ tips: Array.isArray(fwd.tips) ? fwd.tips : void 0,
9787
+ duration: Date.now() - startFwd
9788
+ });
9789
+ if (type === "and" && !fwdOk) {
9790
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${fwd.message ?? ""}`);
9791
+ }
9792
+ if (type === "or" && fwdOk) {
9793
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9794
+ }
9795
+ return void 0;
9796
+ }
9797
+ }
8990
9798
  const pluginCtx = {
8991
9799
  args: pluginArgs,
8992
9800
  options: pluginParams,
@@ -9054,12 +9862,14 @@ async function executePluginChainStep(context) {
9054
9862
  }
9055
9863
  if (outputs.length > 0) hookOutputs = outputs;
9056
9864
  }
9057
- const data = raw?.data ?? raw;
9865
+ const success = raw?.success !== false;
9866
+ const data = raw?.data ?? (success ? raw : null);
9867
+ const message = success ? void 0 : raw.message ?? "Plugin command failed";
9058
9868
  recordArchive(session.id, sessionName, {
9059
9869
  step: results.length,
9060
9870
  command: `${cmdName} ${subCommand}`,
9061
9871
  params: pluginParams,
9062
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9872
+ result: { success, data, message, tips: tipsToMessages(raw?.tips) },
9063
9873
  toolCalls: [],
9064
9874
  duration,
9065
9875
  timestamp: start
@@ -9067,11 +9877,15 @@ async function executePluginChainStep(context) {
9067
9877
  results.push({
9068
9878
  command: `${cmdName} ${subCommand}`,
9069
9879
  raw: cmdStr,
9070
- ...ok32(data),
9880
+ success,
9881
+ data,
9882
+ message,
9883
+ tips: normalizeTips7(raw?.tips),
9071
9884
  duration,
9072
9885
  ...hookOutputs ? { hookOutputs } : {}
9073
9886
  });
9074
- if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9887
+ if (!success && type === "and") return stoppedChain(false, results, totalStart, results.length, message);
9888
+ if (success && type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9075
9889
  } catch (error) {
9076
9890
  const duration = Date.now() - start;
9077
9891
  const message = errMsg(error);
@@ -9178,7 +9992,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9178
9992
  }
9179
9993
  let targetPageOverride = null;
9180
9994
  if (_target && extraOpts?.cdpEndpoint) {
9181
- const { findTargetPage } = await import("./browser-3LBSVDSS.js");
9995
+ const { findTargetPage } = await import("./browser-KY7AIRAB.js");
9182
9996
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9183
9997
  if (!targetPageOverride) {
9184
9998
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -9195,46 +10009,55 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9195
10009
  params = result.data;
9196
10010
  }
9197
10011
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
9198
- const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
10012
+ const { forwardExec } = await import("./daemon-client-Z3NKNZRL.js");
9199
10013
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
9200
10014
  const result = await forwardExec(
9201
10015
  commandName,
9202
10016
  params,
9203
10017
  sessionName,
9204
10018
  extraOpts?.cdpEndpoint,
9205
- longRunning ? 20 * 6e4 : void 0
10019
+ longRunning ? 20 * 6e4 : void 0,
10020
+ extraOpts?.bridge
9206
10021
  );
9207
10022
  if (result) return result;
9208
10023
  }
9209
10024
  let session;
9210
- const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
9211
- if (existing) {
9212
- session = existing;
9213
- if (session.page) {
9214
- try {
9215
- await Promise.race([
9216
- session.page.evaluate(() => true),
9217
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
9218
- ]);
9219
- } catch (err) {
9220
- const msg = err instanceof Error ? err.message : String(err);
9221
- if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
9222
- await closeSessionByName(session.name);
9223
- session = void 0;
10025
+ const bridgeSession = await findOrCreateBridgeSession(sessionName, {
10026
+ preferBridge: extraOpts?.bridge === true,
10027
+ url: params.url
10028
+ });
10029
+ if (bridgeSession) {
10030
+ session = bridgeSession;
10031
+ } else {
10032
+ const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
10033
+ if (existing) {
10034
+ session = existing;
10035
+ if (session.page) {
10036
+ try {
10037
+ await Promise.race([
10038
+ session.page.evaluate(() => true),
10039
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
10040
+ ]);
10041
+ } catch (err) {
10042
+ const msg = err instanceof Error ? err.message : String(err);
10043
+ if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
10044
+ await closeSessionByName(session.name);
10045
+ session = void 0;
10046
+ }
9224
10047
  }
9225
10048
  }
9226
- }
9227
- if (session && targetPageOverride && session.page) {
9228
- const currentUrl = session.page.url();
9229
- if (currentUrl !== targetPageOverride.url) {
9230
- await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
9231
- });
10049
+ if (session && targetPageOverride && session.page) {
10050
+ const currentUrl = session.page.url();
10051
+ if (currentUrl !== targetPageOverride.url) {
10052
+ await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
10053
+ });
10054
+ }
9232
10055
  }
10056
+ } else if (command.scope !== "project") {
10057
+ session = await createSession(sessionName, params.url, {
10058
+ cdpEndpoint: extraOpts?.cdpEndpoint
10059
+ });
9233
10060
  }
9234
- } else if (command.scope !== "project") {
9235
- session = await createSession(sessionName, params.url, {
9236
- cdpEndpoint: extraOpts?.cdpEndpoint
9237
- });
9238
10061
  }
9239
10062
  const ctx = {
9240
10063
  page: session?.page,
@@ -9383,7 +10206,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9383
10206
  timestamp: start
9384
10207
  });
9385
10208
  if (isSuccess) {
9386
- return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
10209
+ return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9387
10210
  }
9388
10211
  const fc = classifyFailure(raw.message);
9389
10212
  return {
@@ -9406,7 +10229,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9406
10229
  duration,
9407
10230
  timestamp: start
9408
10231
  });
9409
- return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
10232
+ return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9410
10233
  } catch (err) {
9411
10234
  const end = Date.now();
9412
10235
  const duration = end - start;
@@ -9419,7 +10242,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9419
10242
  });
9420
10243
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
9421
10244
  try {
9422
- const { attemptRecovery } = await import("./recovery-JFGV3DBX.js");
10245
+ const { attemptRecovery } = await import("./recovery-TIBRFGRP.js");
9423
10246
  const recovery = await attemptRecovery(
9424
10247
  session.page,
9425
10248
  sessionName,