@xbrowser/cli 1.34.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-GXL6V2JW.js → browser-KY7AIRAB.js} +3 -2
  2. package/dist/{browser-ZWEJ663M.js → browser-MLKP72XP.js} +3 -3
  3. package/dist/{browser-X7LO42UI.js → browser-RZ7DPBI3.js} +3 -3
  4. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  5. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  6. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  7. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  8. package/dist/chunk-3SZTCI33.js +147 -0
  9. package/dist/{chunk-DZ6XEPAH.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-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  13. package/dist/{chunk-N7DFS4V7.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-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -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-J4NOL5XX.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-R57Z5KZX.js → chunk-Y2GRCINH.js} +1004 -183
  27. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -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-5U56MQD2.js → server-HUSX7EFE.js} +5 -4
  46. package/dist/{server-R4OYD7ZC.js → server-KSP5H4HD.js} +5 -3
  47. package/dist/{session-replayer-GHEFFNGV.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
@@ -6,14 +6,21 @@ import {
6
6
  findOrRestoreSession,
7
7
  getBrowser,
8
8
  getSessionById,
9
+ newSessionId,
10
+ readSessionDiskMeta,
11
+ registerSession,
9
12
  resolveLaunchOpts,
10
13
  saveSessionDiskMeta,
14
+ sessions,
11
15
  setActivePage
12
- } from "./chunk-N7DFS4V7.js";
16
+ } from "./chunk-BLCBCESM.js";
13
17
  import {
14
18
  detectAntiBot,
15
19
  formatDetectionMessage
16
20
  } from "./chunk-JKVUFP3G.js";
21
+ import {
22
+ recordMistake
23
+ } from "./chunk-3SZTCI33.js";
17
24
  import {
18
25
  buildViewerUrl
19
26
  } from "./chunk-3OD76SUE.js";
@@ -59,18 +66,18 @@ function getCommandNames() {
59
66
  }
60
67
 
61
68
  // src/runtime/ref-store.ts
62
- var sessions = /* @__PURE__ */ new Map();
69
+ var sessions2 = /* @__PURE__ */ new Map();
63
70
  function normalizeAgentRef(ref) {
64
71
  return ref.startsWith("@") ? ref.slice(1) : ref;
65
72
  }
66
73
  function replaceRefs(sessionKey2, screenHash, targets) {
67
- sessions.set(sessionKey2, {
74
+ sessions2.set(sessionKey2, {
68
75
  screenHash,
69
76
  targets: new Map(targets.map((target) => [target.ref, target]))
70
77
  });
71
78
  }
72
79
  function getRefTarget(sessionKey2, ref) {
73
- const session = sessions.get(sessionKey2);
80
+ const session = sessions2.get(sessionKey2);
74
81
  const target = session?.targets.get(normalizeAgentRef(ref));
75
82
  if (!session || !target) return null;
76
83
  return { screenHash: session.screenHash, target };
@@ -1846,14 +1853,14 @@ var preflightCommand = registerCommand({
1846
1853
  let pageUrl = null;
1847
1854
  try {
1848
1855
  const { fileURLToPath } = await import("url");
1849
- const { join: join10, dirname: dirname5 } = await import("path");
1850
- const { existsSync: existsSync8 } = await import("fs");
1856
+ const { join: join9, dirname: dirname4 } = await import("path");
1857
+ const { existsSync: existsSync7 } = await import("fs");
1851
1858
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1852
1859
  const candidates = [
1853
- join10(dirname5(here), "..", "assets", "preflight.html"),
1854
- join10(process.cwd(), "assets", "preflight.html")
1860
+ join9(dirname4(here), "..", "assets", "preflight.html"),
1861
+ join9(process.cwd(), "assets", "preflight.html")
1855
1862
  ];
1856
- pageUrl = candidates.find((c) => existsSync8(c)) || null;
1863
+ pageUrl = candidates.find((c) => existsSync7(c)) || null;
1857
1864
  } catch {
1858
1865
  }
1859
1866
  if (pageUrl) {
@@ -7563,9 +7570,9 @@ function attachWaitForHuman(ctx, getOrCreateWSServer) {
7563
7570
  if (!ctx.page) {
7564
7571
  throw new Error("waitForHuman requires an active page");
7565
7572
  }
7566
- const { HumanInteractionManager } = await import("./human-interaction-STTZZZ5N.js");
7573
+ const { HumanInteractionManager } = await import("./human-interaction-BGAZC3JR.js");
7567
7574
  const wsServer2 = await getOrCreateWSServer(ctx.browserContext);
7568
- const manager = new HumanInteractionManager(wsServer2, ctx.page);
7575
+ const manager = new HumanInteractionManager(wsServer2, ctx.page, ctx.sessionId);
7569
7576
  return manager.waitForHuman(options);
7570
7577
  };
7571
7578
  }
@@ -7586,9 +7593,9 @@ function setWSServerCache(browserContext, server) {
7586
7593
  import {
7587
7594
  Core
7588
7595
  } from "@dyyz1993/xcli-core";
7589
- import { resolve as resolve2, basename, dirname as dirname4 } from "path";
7590
- import { existsSync as existsSync7, readdirSync } from "fs";
7591
- import { homedir as homedir5 } from "os";
7596
+ import { resolve as resolve2, basename, dirname as dirname3 } from "path";
7597
+ import { existsSync as existsSync6, readdirSync } from "fs";
7598
+ import { homedir as homedir4 } from "os";
7592
7599
 
7593
7600
  // src/plugin/metadata-parser.ts
7594
7601
  import { existsSync as existsSync4 } from "fs";
@@ -7884,124 +7891,6 @@ function patchLoginRequired() {
7884
7891
  });
7885
7892
  }
7886
7893
 
7887
- // src/lib/mistake-ledger.ts
7888
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync6, appendFileSync } from "fs";
7889
- import { homedir as homedir4 } from "os";
7890
- import { join as join7, dirname as dirname3 } from "path";
7891
- var MISTAKE_THRESHOLD = 3;
7892
- var MISTAKE_LEDGER_PATH = join7(
7893
- homedir4(),
7894
- ".xbrowser",
7895
- "knowledge",
7896
- "mistakes.json"
7897
- );
7898
- function emptyLedger() {
7899
- return { version: 1, entries: {} };
7900
- }
7901
- function normalizeMistakeText(value) {
7902
- 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();
7903
- }
7904
- function mistakeFingerprint(category, message) {
7905
- return `${category}::${normalizeMistakeText(message)}`;
7906
- }
7907
- function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
7908
- try {
7909
- const parsed = JSON.parse(readFileSync6(path2, "utf8"));
7910
- if (parsed.version !== 1 || typeof parsed.entries !== "object") {
7911
- return emptyLedger();
7912
- }
7913
- return parsed;
7914
- } catch {
7915
- return emptyLedger();
7916
- }
7917
- }
7918
- function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
7919
- mkdirSync5(join7(path2, ".."), { recursive: true });
7920
- writeFileSync6(path2, JSON.stringify(ledger, null, 2), "utf8");
7921
- }
7922
- var MISTAKES_MD_HEADER = `# \u6301\u4E45\u5316\u9519\u9898\u672C\uFF08 graduated mistake ledger \uFF09
7923
-
7924
- > \u8FD0\u884C\u65F6\u9519\u9898\u672C\uFF08~/.xbrowser/knowledge/mistakes.json\uFF0CJSON\uFF09\u53EA\u505A\u8BA1\u6570\uFF1B
7925
- > **\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
7926
- > \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
7927
- > \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
7928
-
7929
- `;
7930
- function persistentMistakesPath() {
7931
- if (process.env.XBROWSER_MISTAKES_MD) return process.env.XBROWSER_MISTAKES_MD;
7932
- let dir = process.cwd();
7933
- for (let i = 0; i < 8; i++) {
7934
- const pkg = join7(dir, "package.json");
7935
- if (existsSync6(pkg)) {
7936
- try {
7937
- const name = JSON.parse(readFileSync6(pkg, "utf8")).name;
7938
- if (name === "@xbrowser/cli") return join7(dir, "docs", "mistakes.md");
7939
- } catch {
7940
- }
7941
- }
7942
- const parent = join7(dir, "..");
7943
- if (parent === dir) break;
7944
- dir = parent;
7945
- }
7946
- return join7(homedir4(), ".xbrowser", "knowledge", "mistakes.md");
7947
- }
7948
- function graduateToMarkdown(entry) {
7949
- const mdPath = persistentMistakesPath();
7950
- try {
7951
- mkdirSync5(dirname3(mdPath), { recursive: true });
7952
- if (!existsSync6(mdPath)) writeFileSync6(mdPath, MISTAKES_MD_HEADER);
7953
- const day = entry.lastSeen.slice(0, 10);
7954
- const first = entry.occurrences[0];
7955
- const anchor = `<!-- fingerprint:${entry.fingerprint} -->`;
7956
- const existing = existsSync6(mdPath) ? readFileSync6(mdPath, "utf8") : "";
7957
- if (existing.includes(anchor)) return;
7958
- const block = [
7959
- `## ${day} \xB7 ${first.command} \xB7 ${first.message.split("\n")[0].slice(0, 80)}`,
7960
- anchor,
7961
- `- **\u7C7B\u522B**: ${entry.category}`,
7962
- `- **\u9996\u6B21/\u6700\u8FD1**: ${entry.firstSeen.slice(0, 19)} \u2192 ${entry.lastSeen.slice(0, 19)}\uFF08\u7D2F\u8BA1 ${entry.occurrences.length} \u6B21\uFF09`,
7963
- `- **\u5178\u578B\u9519\u8BEF**: ${first.message.split("\n")[0].slice(0, 160)}`,
7964
- `- **\u6839\u56E0**: \uFF08\u5F85\u8865\u2014\u2014\u4FEE\u590D\u65F6\u586B\u5199\uFF09`,
7965
- `- **\u4FEE\u590D**: \uFF08\u5F85\u8865\u2014\u2014\u586B PR \u53F7\u6216\u4FEE\u590D\u8BF4\u660E\uFF09`,
7966
- ""
7967
- ].join("\n");
7968
- appendFileSync(mdPath, block);
7969
- } catch {
7970
- }
7971
- }
7972
- function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
7973
- if (!input.category) throw new Error("mistake category is required");
7974
- if (!input.command) throw new Error("mistake command is required");
7975
- if (!input.message) throw new Error("mistake message is required");
7976
- const ledger = readMistakeLedger(path2);
7977
- const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
7978
- const previous = ledger.entries[fingerprint];
7979
- const occurrence = {
7980
- timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
7981
- command: input.command,
7982
- message: input.message,
7983
- ...input.context ? { context: input.context } : {}
7984
- };
7985
- const entry = previous ? {
7986
- ...previous,
7987
- lastSeen: occurrence.timestamp,
7988
- occurrences: [...previous.occurrences, occurrence].slice(-100),
7989
- constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
7990
- } : {
7991
- fingerprint,
7992
- category: input.category,
7993
- firstSeen: occurrence.timestamp,
7994
- lastSeen: occurrence.timestamp,
7995
- occurrences: [occurrence],
7996
- constrained: false
7997
- };
7998
- ledger.entries[fingerprint] = entry;
7999
- writeMistakeLedger(ledger, path2);
8000
- const newlyConstrained = Boolean(previous && !previous.constrained && entry.constrained);
8001
- if (newlyConstrained) graduateToMarkdown(entry);
8002
- return { entry, newlyConstrained };
8003
- }
8004
-
8005
7894
  // src/plugin/loader.ts
8006
7895
  var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
8007
7896
  var XBrowserPluginLoader = class {
@@ -8079,7 +7968,7 @@ var XBrowserPluginLoader = class {
8079
7968
  async loadPlugin(pluginPath, id) {
8080
7969
  const before = new Set(this.core.loader.getSites().map((s) => s.name));
8081
7970
  const instance = await this.loader.loadPlugin(pluginPath, id);
8082
- this.recordSiteAliases(basename(dirname4(pluginPath)), before);
7971
+ this.recordSiteAliases(basename(dirname3(pluginPath)), before);
8083
7972
  return instance;
8084
7973
  }
8085
7974
  async unloadPlugin(id) {
@@ -8093,18 +7982,18 @@ var XBrowserPluginLoader = class {
8093
7982
  }
8094
7983
  async scanAndLoad() {
8095
7984
  const cwd = this.options.cwd || process.cwd();
8096
- const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
7985
+ const globalDir = this.options.globalDir || resolve2(homedir4(), ".xbrowser/plugins");
8097
7986
  ensurePluginDependencies(globalDir);
8098
7987
  const dirs = [
8099
7988
  resolve2(cwd, ".xcli/plugins"),
8100
7989
  resolve2(cwd, "../.xcli/plugins"),
8101
- this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
7990
+ this.options.userDir || resolve2(homedir4(), ".xcli/plugins"),
8102
7991
  globalDir
8103
7992
  ];
8104
7993
  const loaded = [];
8105
7994
  const seen = /* @__PURE__ */ new Set();
8106
7995
  for (const dir of dirs) {
8107
- if (!existsSync7(dir)) continue;
7996
+ if (!existsSync6(dir)) continue;
8108
7997
  const entries = readdirSync(dir, { withFileTypes: true });
8109
7998
  for (const entry of entries) {
8110
7999
  if (!entry.isDirectory()) continue;
@@ -8112,12 +8001,12 @@ var XBrowserPluginLoader = class {
8112
8001
  seen.add(entry.name);
8113
8002
  const pluginDir = resolve2(dir, entry.name);
8114
8003
  let indexPath = resolve2(pluginDir, "index.js");
8115
- if (!existsSync7(indexPath)) {
8004
+ if (!existsSync6(indexPath)) {
8116
8005
  indexPath = resolve2(pluginDir, "index.ts");
8117
8006
  }
8118
- if (!existsSync7(indexPath)) continue;
8007
+ if (!existsSync6(indexPath)) continue;
8119
8008
  try {
8120
- if (!existsSync7(resolve2(pluginDir, "package.json"))) {
8009
+ if (!existsSync6(resolve2(pluginDir, "package.json"))) {
8121
8010
  console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
8122
8011
  } else {
8123
8012
  const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
@@ -8144,8 +8033,8 @@ var XBrowserPluginLoader = class {
8144
8033
  };
8145
8034
 
8146
8035
  // src/executor/foundation.ts
8147
- import { homedir as homedir6 } from "os";
8148
- import { join as join8 } from "path";
8036
+ import { homedir as homedir5 } from "os";
8037
+ import { join as join7 } from "path";
8149
8038
  import {
8150
8039
  CompositeStorage,
8151
8040
  configureArchiveStore,
@@ -8183,7 +8072,7 @@ async function getPluginLoader() {
8183
8072
  // src/executor/foundation.ts
8184
8073
  var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8185
8074
  var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8186
- var CONFIG_DIR = join8(homedir6(), ".xbrowser");
8075
+ var CONFIG_DIR = join7(homedir5(), ".xbrowser");
8187
8076
  var storageCache = /* @__PURE__ */ new Map();
8188
8077
  function getPluginStorage(pluginName) {
8189
8078
  if (!storageCache.has(pluginName)) {
@@ -8195,7 +8084,7 @@ var archiveInitialized = false;
8195
8084
  function ensureArchiveInit() {
8196
8085
  if (!archiveInitialized) {
8197
8086
  try {
8198
- configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
8087
+ configureArchiveStore({ archiveDir: join7(homedir5(), ".xbrowser", "archives") });
8199
8088
  } catch {
8200
8089
  }
8201
8090
  archiveInitialized = true;
@@ -8235,7 +8124,7 @@ function streamCommandEvent(sessionId, message) {
8235
8124
 
8236
8125
  // src/executor.ts
8237
8126
  import {
8238
- ok as ok33,
8127
+ ok as ok32,
8239
8128
  fail as fail19,
8240
8129
  isCommandResult,
8241
8130
  normalizeTips as normalizeTips8,
@@ -8243,10 +8132,10 @@ import {
8243
8132
  } from "@dyyz1993/xcli-core";
8244
8133
 
8245
8134
  // src/utils/stub-context.ts
8246
- import { join as join9 } from "path";
8247
- import { homedir as homedir7 } from "os";
8135
+ import { join as join8 } from "path";
8136
+ import { homedir as homedir6 } from "os";
8248
8137
  import { TipCollector, CompositeStorage as CompositeStorage2 } from "@dyyz1993/xcli-core";
8249
- var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
8138
+ var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8250
8139
  var NoopSiteInstance = class {
8251
8140
  name = "stub";
8252
8141
  url = "";
@@ -8305,6 +8194,857 @@ function createStubContext(pluginName) {
8305
8194
  };
8306
8195
  }
8307
8196
 
8197
+ // src/browser/bridge-session.ts
8198
+ var DEFAULT_BRIDGE_HTTP = "http://127.0.0.1:9347";
8199
+ function bridgeHttpBase() {
8200
+ return process.env.XBROWSER_BRIDGE_HTTP || DEFAULT_BRIDGE_HTTP;
8201
+ }
8202
+ async function bridgeExec(cmd, args) {
8203
+ let resp;
8204
+ try {
8205
+ resp = await fetch(`${bridgeHttpBase()}/exec`, {
8206
+ method: "POST",
8207
+ headers: { "Content-Type": "application/json" },
8208
+ body: JSON.stringify({ cmd, args })
8209
+ });
8210
+ } catch (e) {
8211
+ 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)}`);
8212
+ }
8213
+ const reply = await resp.json().catch(() => null);
8214
+ if (!reply) throw new Error("[bridge-session] bridge \u54CD\u5E94\u975E JSON\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09");
8215
+ if (reply.ok !== true) throw new Error(`[bridge-session] ${cmd} \u5931\u8D25: ${reply.error ?? "unknown"}`);
8216
+ return reply.data ?? {};
8217
+ }
8218
+ function unimplemented(op) {
8219
+ 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`);
8220
+ }
8221
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
8222
+ async function pollUntil2(pred, timeoutMs, intervalMs = 120) {
8223
+ const deadline = Date.now() + timeoutMs;
8224
+ while (Date.now() < deadline) {
8225
+ if (await pred()) return true;
8226
+ await sleep2(intervalMs);
8227
+ }
8228
+ return await pred();
8229
+ }
8230
+ function toExpression(fn, args) {
8231
+ if (typeof fn === "string") return fn;
8232
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
8233
+ return `(${fn.toString()})(${callArgs})`;
8234
+ }
8235
+ function rectExpression(selector, index) {
8236
+ 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 }; })()`;
8237
+ }
8238
+ function stateExpression(selector, index) {
8239
+ 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 }; })()`;
8240
+ }
8241
+ var BridgePage = class {
8242
+ taskName;
8243
+ tabId;
8244
+ _url;
8245
+ closed = false;
8246
+ mouse;
8247
+ keyboard;
8248
+ ctxStub;
8249
+ constructor(taskName, tabId) {
8250
+ this.taskName = taskName;
8251
+ this.tabId = tabId;
8252
+ this._url = "about:blank";
8253
+ this.mouse = new BridgeMouse(this);
8254
+ this.keyboard = new BridgeKeyboard(this);
8255
+ this.ctxStub = new BridgeContextStub(this);
8256
+ }
8257
+ get bridgeTabId() {
8258
+ return this.tabId;
8259
+ }
8260
+ get bridgeTaskName() {
8261
+ return this.taskName;
8262
+ }
8263
+ /** 会话内 tab 被任务组回收后重锚(task-open 复用路径刷新 tabId) */
8264
+ retab(tabId) {
8265
+ this.tabId = tabId;
8266
+ }
8267
+ async exec(cmd, args = {}) {
8268
+ return bridgeExec(cmd, { ...args, tabId: this.tabId, task: this.taskName });
8269
+ }
8270
+ async evalExpr(expression) {
8271
+ const data = await this.exec("evaluate", { expression });
8272
+ if (data.ok !== true) throw new Error(`[bridge-session] evaluate \u5931\u8D25: ${String(data.error ?? "unknown")}`);
8273
+ return data.value ?? null;
8274
+ }
8275
+ async rectOf(selector, index = 0) {
8276
+ const raw = await this.evalExpr(rectExpression(selector, index));
8277
+ if (raw == null) return null;
8278
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
8279
+ }
8280
+ async stateOf(selector, index = 0) {
8281
+ const raw = await this.evalExpr(stateExpression(selector, index));
8282
+ if (raw == null) return null;
8283
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
8284
+ }
8285
+ async trustedClickAt(x, y) {
8286
+ const r = await this.exec("trustedClick", { x, y });
8287
+ if (r.ok !== true) throw new Error(`[bridge-session] trustedClick \u5931\u8D25: ${String(r.error ?? "unknown")}`);
8288
+ }
8289
+ async clickSelector(selector, index = 0) {
8290
+ await this.waitForSelector(selector, { state: "attached", timeout: 8e3 }).catch(() => {
8291
+ throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
8292
+ });
8293
+ const rect = await this.rectOf(selector, index);
8294
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
8295
+ await this.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8296
+ }
8297
+ // ── Navigation ──
8298
+ async goto(url, opts) {
8299
+ await this.exec("navigate", { url });
8300
+ this._url = url;
8301
+ await this.waitForLoadState(opts?.waitUntil ?? "load", opts?.timeout ?? 3e4).catch(() => {
8302
+ });
8303
+ return {
8304
+ status: () => 200,
8305
+ ok: () => true,
8306
+ url: () => url,
8307
+ headers: () => ({})
8308
+ };
8309
+ }
8310
+ async goBack() {
8311
+ await this._cdpSend("Page.navigateToHistory", { entryId: -1 });
8312
+ }
8313
+ async goForward() {
8314
+ await this._cdpSend("Page.navigateToHistory", { entryId: 1 });
8315
+ }
8316
+ async reload(opts) {
8317
+ await this._cdpSend("Page.reload", {});
8318
+ await this.waitForLoadState("load", opts?.timeout ?? 3e4).catch(() => {
8319
+ });
8320
+ }
8321
+ async waitForLoadState(state = "load", timeout = 3e4) {
8322
+ const want = state === "domcontentloaded" ? ["interactive", "complete"] : ["complete"];
8323
+ const ok33 = await pollUntil2(async () => {
8324
+ const rs = await this.evalExpr("document.readyState").catch(() => "loading");
8325
+ return want.includes(rs);
8326
+ }, timeout);
8327
+ if (!ok33) throw new Error(`[bridge-session] waitForLoadState(${state}) \u8D85\u65F6`);
8328
+ }
8329
+ async waitForTimeout(ms) {
8330
+ await sleep2(ms);
8331
+ }
8332
+ async waitForSelector(selector, opts) {
8333
+ const state = opts?.state ?? "visible";
8334
+ const timeout = opts?.timeout ?? 3e4;
8335
+ const ok33 = await pollUntil2(async () => {
8336
+ const st = await this.stateOf(selector).catch(() => null);
8337
+ if (!st) return state === "detached";
8338
+ if (state === "attached") return st.found;
8339
+ if (state === "visible") return st.found && st.visible;
8340
+ if (state === "hidden") return !st.found || !st.visible;
8341
+ return !st.found;
8342
+ }, timeout);
8343
+ if (!ok33) throw new Error(`[bridge-session] waitForSelector(${selector}, ${state}) \u8D85\u65F6`);
8344
+ }
8345
+ async waitForFunction(fn, opts, ...args) {
8346
+ const expression = toExpression(fn, args);
8347
+ const timeout = opts?.timeout ?? 3e4;
8348
+ const interval = typeof opts?.polling === "number" ? opts.polling : 120;
8349
+ let last = null;
8350
+ const ok33 = await pollUntil2(async () => {
8351
+ last = await this.evalExpr(expression).catch(() => false);
8352
+ return Boolean(last);
8353
+ }, timeout, interval);
8354
+ if (!ok33) throw new Error(`[bridge-session] waitForFunction \u8D85\u65F6\uFF08last=${JSON.stringify(last)?.slice(0, 80)}\uFF09`);
8355
+ return last;
8356
+ }
8357
+ async waitForURL(url, opts) {
8358
+ const match = (href) => {
8359
+ if (typeof url === "string") return href === url || href.startsWith(url);
8360
+ if (url instanceof RegExp) return url.test(href);
8361
+ return url(href);
8362
+ };
8363
+ const ok33 = await pollUntil2(async () => {
8364
+ const href = await this.evalExpr("location.href").catch(() => "");
8365
+ if (match(href)) {
8366
+ this._url = href;
8367
+ return true;
8368
+ }
8369
+ return false;
8370
+ }, opts?.timeout ?? 3e4);
8371
+ if (!ok33) throw new Error("[bridge-session] waitForURL \u8D85\u65F6");
8372
+ }
8373
+ async waitForResponse() {
8374
+ return unimplemented("waitForResponse\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
8375
+ }
8376
+ async waitForRequest() {
8377
+ return unimplemented("waitForRequest\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
8378
+ }
8379
+ url() {
8380
+ return this._url;
8381
+ }
8382
+ async title() {
8383
+ return this.evalExpr("document.title");
8384
+ }
8385
+ async content() {
8386
+ return this.evalExpr("document.documentElement.outerHTML");
8387
+ }
8388
+ // ── Evaluation ──
8389
+ async evaluate(fn, ...args) {
8390
+ return this.evalExpr(toExpression(fn, args));
8391
+ }
8392
+ async $eval(selector, fn, ...args) {
8393
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
8394
+ 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"}); })()`;
8395
+ return this.evalExpr(expression);
8396
+ }
8397
+ async $$eval(selector, fn, ...args) {
8398
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
8399
+ const expression = `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "els, " + callArgs : "els"}); })()`;
8400
+ return this.evalExpr(expression);
8401
+ }
8402
+ // ── Locator ──
8403
+ locator(selector) {
8404
+ return new BridgeLocator(this, selector, 0);
8405
+ }
8406
+ getByText(text, opts) {
8407
+ return new BridgeLocator(this, BridgeLocator.textQuery(text, opts?.exact ?? true), 0, true);
8408
+ }
8409
+ getByRole(role, opts) {
8410
+ const name = opts?.name ? `[aria-label*=${JSON.stringify(opts.name)}]` : "";
8411
+ return new BridgeLocator(this, `[role="${role}"]${name}, ${role}${name}`, 0);
8412
+ }
8413
+ getByLabel(label, opts) {
8414
+ void opts;
8415
+ return new BridgeLocator(this, `label[for], [aria-label*=${JSON.stringify(label)}]`, 0);
8416
+ }
8417
+ getByPlaceholder(text) {
8418
+ return new BridgeLocator(this, `[placeholder*=${JSON.stringify(text)}]`, 0);
8419
+ }
8420
+ getByTestId(id) {
8421
+ return new BridgeLocator(this, `[data-testid="${id}"]`, 0);
8422
+ }
8423
+ getByAltText(text) {
8424
+ return new BridgeLocator(this, `[alt*=${JSON.stringify(text)}]`, 0);
8425
+ }
8426
+ getByTitle(text) {
8427
+ return new BridgeLocator(this, `[title*=${JSON.stringify(text)}]`, 0);
8428
+ }
8429
+ // ── Interaction shortcuts ──
8430
+ async click(selector, _opts) {
8431
+ await this.clickSelector(selector);
8432
+ }
8433
+ async dblclick(selector, _opts) {
8434
+ const rect = await this.rectOf(selector);
8435
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
8436
+ const x = Math.round(rect.x + rect.width / 2);
8437
+ const y = Math.round(rect.y + rect.height / 2);
8438
+ await this.trustedClickAt(x, y);
8439
+ await sleep2(60);
8440
+ await this.trustedClickAt(x, y);
8441
+ }
8442
+ async fill(selector, value, _opts) {
8443
+ const direct = await this.exec("fill", { selector, value });
8444
+ if (direct.ok === true) return;
8445
+ const typed = await this.exec("type", { selector, text: value });
8446
+ if (typed.ok !== true) throw new Error(`[bridge-session] fill \u5931\u8D25: ${String(direct.error ?? typed.error ?? "unknown")}`);
8447
+ }
8448
+ async press(selector, key, _opts) {
8449
+ await this.clickSelector(selector);
8450
+ await this.keyboard.press(key);
8451
+ }
8452
+ async hover(selector, _opts) {
8453
+ const rect = await this.rectOf(selector);
8454
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
8455
+ await this.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8456
+ }
8457
+ async type(selector, text, _opts) {
8458
+ const r = await this.exec("type", { selector, text });
8459
+ if (r.ok !== true) throw new Error(`[bridge-session] type \u5931\u8D25: ${String(r.error ?? "unknown")}`);
8460
+ }
8461
+ async check(selector, _opts) {
8462
+ const st = await this.stateOf(selector);
8463
+ if (st && !await this.evalExpr(`document.querySelector(${JSON.stringify(selector)}).checked`)) {
8464
+ await this.clickSelector(selector);
8465
+ }
8466
+ }
8467
+ async uncheck(selector, _opts) {
8468
+ const checked = await this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.checked === true`);
8469
+ if (checked) await this.clickSelector(selector);
8470
+ }
8471
+ async selectOption(selector, value) {
8472
+ const v = Array.isArray(value) ? value : [value];
8473
+ const result = await this.evalExpr(
8474
+ `(() => { 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; })()`
8475
+ );
8476
+ return result ?? [];
8477
+ }
8478
+ // ── Convenience selectors ──
8479
+ async textContent(selector) {
8480
+ const st = await this.stateOf(selector);
8481
+ return st?.text ?? null;
8482
+ }
8483
+ async innerText(selector) {
8484
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
8485
+ }
8486
+ async innerHTML(selector) {
8487
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerHTML ?? ''`);
8488
+ }
8489
+ async getAttribute(selector, name) {
8490
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
8491
+ }
8492
+ // ── Query ──
8493
+ async $(selector) {
8494
+ const st = await this.stateOf(selector);
8495
+ return st ? new BridgeElementHandle(this, selector, 0) : null;
8496
+ }
8497
+ async $$(selector) {
8498
+ const count = await this.evalExpr(`document.querySelectorAll(${JSON.stringify(selector)}).length`);
8499
+ return Array.from({ length: count }, (_, i) => new BridgeElementHandle(this, selector, i));
8500
+ }
8501
+ // ── Screen ──
8502
+ async screenshot(_opts) {
8503
+ const r = await this.exec("screenshot", {});
8504
+ const b64 = r.base64;
8505
+ if (!b64) throw new Error(`[bridge-session] screenshot \u5931\u8D25: ${String(r.error ?? "no base64")}`);
8506
+ return Buffer.from(b64, "base64");
8507
+ }
8508
+ async pdf(_opts) {
8509
+ return unimplemented("pdf");
8510
+ }
8511
+ viewportSize() {
8512
+ return null;
8513
+ }
8514
+ async setViewportSize(_size) {
8515
+ unimplemented("setViewportSize");
8516
+ }
8517
+ async setDeviceScaleFactor(_dsf) {
8518
+ unimplemented("setDeviceScaleFactor");
8519
+ }
8520
+ // ── Scripts / UA / Frames / OOPIF ──
8521
+ async addInitScript(_script) {
8522
+ unimplemented("addInitScript");
8523
+ }
8524
+ async setUserAgent(_ua) {
8525
+ unimplemented("setUserAgent");
8526
+ }
8527
+ async discoverFrames() {
8528
+ return [];
8529
+ }
8530
+ async evaluateInFrame(_urlIncludes, _expression) {
8531
+ return unimplemented("evaluateInFrame");
8532
+ }
8533
+ async listFrameTargets() {
8534
+ return [];
8535
+ }
8536
+ async frameMouse(_urlIncludes, _opts) {
8537
+ return unimplemented("frameMouse");
8538
+ }
8539
+ async runFrameMouse(_urlIncludes, _fn) {
8540
+ return unimplemented("runFrameMouse");
8541
+ }
8542
+ async clickInFrame(_urlIncludes, _selector, _opts) {
8543
+ return unimplemented("clickInFrame");
8544
+ }
8545
+ async fillInFrame(_urlIncludes, _selector, _text, _opts) {
8546
+ return unimplemented("fillInFrame");
8547
+ }
8548
+ // ── Page management ──
8549
+ async bringToFront() {
8550
+ await this._cdpSend("Page.bringToFront", {});
8551
+ }
8552
+ async setExtraHTTPHeaders(_headers) {
8553
+ unimplemented("setExtraHTTPHeaders");
8554
+ }
8555
+ async setOfflineMode(_offline) {
8556
+ unimplemented("setOfflineMode");
8557
+ }
8558
+ async route(_url, _handler) {
8559
+ unimplemented("route");
8560
+ }
8561
+ async unroute(_url, _handler) {
8562
+ unimplemented("unroute");
8563
+ }
8564
+ async setInputFiles(_selector, _files) {
8565
+ unimplemented("setInputFiles");
8566
+ }
8567
+ async dropFiles(_selector, _payload) {
8568
+ unimplemented("dropFiles");
8569
+ }
8570
+ setBeforeUnloadBehavior(_mode) {
8571
+ }
8572
+ async dragAndDrop(_source, _target) {
8573
+ unimplemented("dragAndDrop");
8574
+ }
8575
+ // ── Dialog / events ──
8576
+ on(_event, _handler) {
8577
+ }
8578
+ off(_event, _handler) {
8579
+ }
8580
+ async waitForEvent(_event, opts) {
8581
+ await sleep2(opts?.timeout ?? 3e4);
8582
+ return unimplemented(`waitForEvent(${_event})\u2014\u2014\u4E8B\u4EF6\u7C7B\u80FD\u529B`);
8583
+ }
8584
+ // ── CDP escape hatch ──
8585
+ async _cdpSend(method, params) {
8586
+ const r = await this.exec("cdp", { method, params: params ?? {} });
8587
+ if (r.ok !== true) throw new Error(`[bridge-session] cdp ${method} \u5931\u8D25: ${String(r.error ?? "unknown")}`);
8588
+ return r.data ?? null;
8589
+ }
8590
+ _subscribe(_event, _handler) {
8591
+ return () => {
8592
+ };
8593
+ }
8594
+ // ── Lifecycle ──
8595
+ async close() {
8596
+ if (this.closed) return;
8597
+ this.closed = true;
8598
+ await bridgeExec("task-close", { name: this.taskName }).catch(() => {
8599
+ });
8600
+ }
8601
+ isClosed() {
8602
+ return this.closed;
8603
+ }
8604
+ context() {
8605
+ return this.ctxStub;
8606
+ }
8607
+ browser() {
8608
+ return this.ctxStub.browser();
8609
+ }
8610
+ mainFrame() {
8611
+ return new BridgeFrame(this);
8612
+ }
8613
+ frames() {
8614
+ return [this.mainFrame()];
8615
+ }
8616
+ };
8617
+ var BridgeLocator = class _BridgeLocator {
8618
+ constructor(page, selector, index, isText = false) {
8619
+ this.page = page;
8620
+ this.selector = selector;
8621
+ this.index = index;
8622
+ this.isText = isText;
8623
+ }
8624
+ page;
8625
+ selector;
8626
+ index;
8627
+ isText;
8628
+ /** text 伪查询编码:==精确 / ~包含(无等价 CSS,rect() 编译为 evaluate 表达式) */
8629
+ static textQuery(text, exact) {
8630
+ return `${exact ? "==" : "~"}${text}`;
8631
+ }
8632
+ async rect() {
8633
+ if (!this.isText) return this.page.rectOf(this.selector, this.index);
8634
+ const m = /^(==|~)([\s\S]*)$/.exec(this.selector);
8635
+ const exact = m?.[1] === "==";
8636
+ const text = JSON.stringify(m?.[2] ?? this.selector);
8637
+ const cmp = exact ? `e.textContent.trim() === ${text}` : `e.textContent.includes(${text})`;
8638
+ 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 }; })()`;
8639
+ const r = await this.page.evaluate(expression);
8640
+ const v = r;
8641
+ return v == null ? null : typeof v === "string" ? JSON.parse(v) : v;
8642
+ }
8643
+ async click(_opts) {
8644
+ const rect = await this.rect();
8645
+ if (!rect) throw new Error(`[bridge-session] locator \u672A\u547D\u4E2D: ${this.selector}`);
8646
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8647
+ }
8648
+ async fill(value, _opts) {
8649
+ if (!this.isText) {
8650
+ await this.page.fill(this.selector, value);
8651
+ return;
8652
+ }
8653
+ await this.click();
8654
+ await this.page.keyboard.type(value);
8655
+ }
8656
+ async press(key, _opts) {
8657
+ await this.page.keyboard.press(key);
8658
+ }
8659
+ async pressSequentially(text, opts) {
8660
+ await this.page.keyboard.type(text, opts);
8661
+ }
8662
+ async hover(_opts) {
8663
+ const rect = await this.rect();
8664
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8665
+ }
8666
+ async type(text, _opts) {
8667
+ await this.page.keyboard.type(text);
8668
+ }
8669
+ async check(_opts) {
8670
+ await this.click();
8671
+ }
8672
+ async uncheck(_opts) {
8673
+ await this.click();
8674
+ }
8675
+ async selectOption(value) {
8676
+ if (!this.isText) return this.page.selectOption(this.selector, value);
8677
+ return unimplemented("text locator selectOption");
8678
+ }
8679
+ async screenshot(opts) {
8680
+ return this.page.screenshot(opts);
8681
+ }
8682
+ async focus() {
8683
+ if (!this.isText) await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.focus()`);
8684
+ }
8685
+ async waitFor(opts) {
8686
+ if (!this.isText) await this.page.waitForSelector(this.selector, opts);
8687
+ }
8688
+ async count() {
8689
+ if (!this.isText) return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)}).length`);
8690
+ const rect = await this.rect();
8691
+ return rect ? 1 : 0;
8692
+ }
8693
+ async isVisible() {
8694
+ const rect = await this.rect();
8695
+ return rect !== null && rect.width + rect.height > 0;
8696
+ }
8697
+ async isHidden() {
8698
+ return !await this.isVisible();
8699
+ }
8700
+ async isEnabled() {
8701
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8702
+ return st ? !st.disabled : false;
8703
+ }
8704
+ async isDisabled() {
8705
+ return !await this.isEnabled();
8706
+ }
8707
+ async boundingBox() {
8708
+ return this.rect();
8709
+ }
8710
+ async textContent() {
8711
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8712
+ return st?.text ?? null;
8713
+ }
8714
+ async innerText() {
8715
+ return await this.textContent() ?? "";
8716
+ }
8717
+ async innerHTML() {
8718
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8719
+ return st?.html ?? "";
8720
+ }
8721
+ async getAttribute(name) {
8722
+ return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.getAttribute(${JSON.stringify(name)}) ?? null`);
8723
+ }
8724
+ async evaluate(fn, ...args) {
8725
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
8726
+ return this.page.evaluate(`(() => { const el = document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]; return el ? (${typeof fn === "string" ? fn : fn.toString()})(${callArgs}) : null; })()`);
8727
+ }
8728
+ async ariaSnapshot() {
8729
+ return unimplemented("ariaSnapshot");
8730
+ }
8731
+ first() {
8732
+ return new _BridgeLocator(this.page, this.selector, 0, this.isText);
8733
+ }
8734
+ last() {
8735
+ return unimplemented("locator.last()");
8736
+ }
8737
+ nth(index) {
8738
+ return new _BridgeLocator(this.page, this.selector, index, this.isText);
8739
+ }
8740
+ filter(_opts) {
8741
+ return unimplemented("locator.filter()");
8742
+ }
8743
+ async all() {
8744
+ const n = await this.count();
8745
+ return Array.from({ length: n }, (_, i) => new _BridgeLocator(this.page, this.selector, i, this.isText));
8746
+ }
8747
+ };
8748
+ var BridgeElementHandle = class {
8749
+ constructor(page, selector, index) {
8750
+ this.page = page;
8751
+ this.selector = selector;
8752
+ this.index = index;
8753
+ }
8754
+ page;
8755
+ selector;
8756
+ index;
8757
+ async click(_opts) {
8758
+ const rect = await this.page.rectOf(this.selector, this.index);
8759
+ if (!rect) throw new Error("[bridge-session] element \u672A\u547D\u4E2D");
8760
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8761
+ }
8762
+ async fill(value, _opts) {
8763
+ await this.page.fill(this.selector, value);
8764
+ }
8765
+ async hover() {
8766
+ const rect = await this.page.rectOf(this.selector, this.index);
8767
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
8768
+ }
8769
+ async press(key) {
8770
+ await this.page.keyboard.press(key);
8771
+ }
8772
+ async screenshot(opts) {
8773
+ return this.page.screenshot(opts);
8774
+ }
8775
+ async boundingBox() {
8776
+ return this.page.rectOf(this.selector, this.index);
8777
+ }
8778
+ async isVisible() {
8779
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8780
+ return Boolean(st?.visible);
8781
+ }
8782
+ async isEnabled() {
8783
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8784
+ return st ? !st.disabled : false;
8785
+ }
8786
+ async textContent() {
8787
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8788
+ return st?.text ?? null;
8789
+ }
8790
+ async innerText() {
8791
+ return await this.textContent() ?? "";
8792
+ }
8793
+ async innerHTML() {
8794
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
8795
+ return st?.html ?? "";
8796
+ }
8797
+ async getAttribute(name) {
8798
+ return this.page.getAttribute(this.selector, name);
8799
+ }
8800
+ async scrollIntoViewIfNeeded() {
8801
+ await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.scrollIntoView({ block: 'center' })`);
8802
+ }
8803
+ dispose() {
8804
+ }
8805
+ };
8806
+ var KEY_CODES = {
8807
+ Enter: 13,
8808
+ Tab: 9,
8809
+ Escape: 27,
8810
+ Backspace: 8,
8811
+ Delete: 46,
8812
+ ArrowUp: 38,
8813
+ ArrowDown: 40,
8814
+ ArrowLeft: 37,
8815
+ ArrowRight: 39,
8816
+ Home: 36,
8817
+ End: 35,
8818
+ PageUp: 33,
8819
+ PageDown: 34
8820
+ };
8821
+ var BridgeMouse = class {
8822
+ constructor(page) {
8823
+ this.page = page;
8824
+ }
8825
+ page;
8826
+ async dispatch(params) {
8827
+ await this.page._cdpSend("Input.dispatchMouseEvent", params);
8828
+ }
8829
+ async click(x, y, opts) {
8830
+ const button = opts?.button ?? "left";
8831
+ const clickCount = opts?.clickCount ?? 1;
8832
+ const buttons = button === "left" ? 1 : button === "right" ? 2 : 4;
8833
+ await this.dispatch({ type: "mousePressed", x, y, button, buttons, clickCount });
8834
+ if (opts?.delay) await sleep2(opts.delay);
8835
+ await this.dispatch({ type: "mouseReleased", x, y, button, buttons, clickCount });
8836
+ }
8837
+ async dblclick(x, y, opts) {
8838
+ await this.click(x, y, { ...opts, clickCount: 1 });
8839
+ await sleep2(60);
8840
+ await this.click(x, y, { ...opts, clickCount: 2 });
8841
+ }
8842
+ async down(opts) {
8843
+ const button = opts?.button ?? "left";
8844
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button, buttons: button === "left" ? 1 : button === "right" ? 2 : 4, clickCount: 1 });
8845
+ }
8846
+ async up(opts) {
8847
+ const button = opts?.button ?? "left";
8848
+ await this.dispatch({ type: "mouseReleased", x: 0, y: 0, button, buttons: 0, clickCount: 1 });
8849
+ }
8850
+ async move(x, y, opts) {
8851
+ const steps = Math.max(1, opts?.steps ?? 1);
8852
+ for (let i = 1; i <= steps; i++) {
8853
+ await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 0 });
8854
+ }
8855
+ }
8856
+ async wheel(deltaX, deltaY) {
8857
+ await this.dispatch({ type: "mouseWheel", x: 0, y: 0, deltaX, deltaY });
8858
+ }
8859
+ async wheelAt(x, y, deltaX, deltaY) {
8860
+ await this.move(x, y);
8861
+ await this.dispatch({ type: "mouseWheel", x, y, deltaX, deltaY });
8862
+ }
8863
+ async drag(x, y, opts) {
8864
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button: "left", buttons: 1, clickCount: 1 });
8865
+ const steps = Math.max(1, opts?.steps ?? 10);
8866
+ for (let i = 1; i <= steps; i++) await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 1 });
8867
+ await this.dispatch({ type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
8868
+ }
8869
+ };
8870
+ var BridgeKeyboard = class {
8871
+ constructor(page) {
8872
+ this.page = page;
8873
+ }
8874
+ page;
8875
+ async key(event) {
8876
+ await this.page._cdpSend("Input.dispatchKeyEvent", {
8877
+ type: event.type,
8878
+ key: event.key,
8879
+ code: event.code ?? event.key,
8880
+ windowsVirtualKeyCode: KEY_CODES[event.key] ?? (event.key.length === 1 ? event.key.toUpperCase().charCodeAt(0) : 0),
8881
+ nativeVirtualKeyCode: KEY_CODES[event.key] ?? 0,
8882
+ ...event.modifiers !== void 0 ? { modifiers: event.modifiers } : {},
8883
+ ...event.text !== void 0 ? { text: event.text } : {}
8884
+ });
8885
+ }
8886
+ async press(key, _opts) {
8887
+ await this.key({ type: "keyDown", key });
8888
+ await this.key({ type: "keyUp", key });
8889
+ }
8890
+ async pressNav(key) {
8891
+ await this.key({ type: "keyDown", key });
8892
+ }
8893
+ async pressCombo(key, modifier) {
8894
+ const bits = { Alt: 1, Meta: 4, Control: 2, Shift: 8 };
8895
+ await this.key({ type: "keyDown", key: modifier, modifiers: bits[modifier] });
8896
+ await this.key({ type: "keyDown", key, modifiers: bits[modifier] });
8897
+ await this.key({ type: "keyUp", key, modifiers: bits[modifier] });
8898
+ await this.key({ type: "keyUp", key: modifier });
8899
+ }
8900
+ async down(key) {
8901
+ await this.key({ type: "keyDown", key });
8902
+ }
8903
+ async up(key) {
8904
+ await this.key({ type: "keyUp", key });
8905
+ }
8906
+ async type(text, _opts) {
8907
+ const r = await this.page.exec("trusted-type", { text });
8908
+ if (r.ok !== true) {
8909
+ for (const ch of text) await this.key({ type: "keyDown", key: ch, text: ch });
8910
+ }
8911
+ }
8912
+ async insertText(text) {
8913
+ await this.page._cdpSend("Input.insertText", { text });
8914
+ }
8915
+ };
8916
+ var BridgeFrame = class {
8917
+ constructor(bridgePage) {
8918
+ this.bridgePage = bridgePage;
8919
+ }
8920
+ bridgePage;
8921
+ url() {
8922
+ return this.bridgePage.url();
8923
+ }
8924
+ name() {
8925
+ return "";
8926
+ }
8927
+ isDetached() {
8928
+ return this.bridgePage.isClosed();
8929
+ }
8930
+ page() {
8931
+ return this.bridgePage;
8932
+ }
8933
+ async evaluate(fn, ...args) {
8934
+ return this.bridgePage.evaluate(fn, ...args);
8935
+ }
8936
+ async $(selector) {
8937
+ return this.bridgePage.$(selector);
8938
+ }
8939
+ async $$(selector) {
8940
+ return this.bridgePage.$$(selector);
8941
+ }
8942
+ };
8943
+ var BridgeBrowserStub = class {
8944
+ disconnected = false;
8945
+ ctx;
8946
+ constructor(ctx) {
8947
+ this.ctx = ctx;
8948
+ }
8949
+ async close() {
8950
+ }
8951
+ async disconnect() {
8952
+ this.disconnected = true;
8953
+ }
8954
+ async newContext(_opts) {
8955
+ return unimplemented("browser.newContext");
8956
+ }
8957
+ contexts() {
8958
+ return [this.ctx];
8959
+ }
8960
+ async discoverContexts() {
8961
+ }
8962
+ on(_event, _handler) {
8963
+ }
8964
+ off(_event, _handler) {
8965
+ }
8966
+ };
8967
+ var BridgeContextStub = class {
8968
+ constructor(bridgePage) {
8969
+ this.bridgePage = bridgePage;
8970
+ this.browserStub = new BridgeBrowserStub(this);
8971
+ }
8972
+ bridgePage;
8973
+ browserStub;
8974
+ async newPage() {
8975
+ return this.bridgePage;
8976
+ }
8977
+ pages() {
8978
+ return this.bridgePage.isClosed() ? [] : [this.bridgePage];
8979
+ }
8980
+ async close() {
8981
+ await this.bridgePage.close();
8982
+ }
8983
+ browser() {
8984
+ return this.browserStub;
8985
+ }
8986
+ async newCDPSession(_page) {
8987
+ return unimplemented("newCDPSession");
8988
+ }
8989
+ async addInitScript(_script) {
8990
+ unimplemented("addInitScript");
8991
+ }
8992
+ async cookies(_urls) {
8993
+ return [];
8994
+ }
8995
+ async addCookies(_cookies) {
8996
+ unimplemented("addCookies");
8997
+ }
8998
+ async clearCookies() {
8999
+ unimplemented("clearCookies");
9000
+ }
9001
+ on(_event, _handler) {
9002
+ }
9003
+ off(_event, _handler) {
9004
+ }
9005
+ };
9006
+ var realMetaStore = {
9007
+ read: (name) => readSessionDiskMeta(name),
9008
+ save: (name, data) => {
9009
+ saveSessionDiskMeta(name, data);
9010
+ }
9011
+ };
9012
+ var metaStore = realMetaStore;
9013
+ async function findOrCreateBridgeSession(name, opts) {
9014
+ const store = metaStore ?? realMetaStore;
9015
+ const meta = store.read(name);
9016
+ if (meta?.kind !== "bridge" && !opts?.preferBridge) return null;
9017
+ const inMemory = sessions.find(name);
9018
+ if (inMemory?.bridge) return inMemory;
9019
+ const taskName = meta?.taskName ?? name;
9020
+ const opened = await bridgeExec("task-open", { name: taskName }).catch(() => null);
9021
+ const tabId = Number(opened?.tabId ?? 0);
9022
+ if (!opened || !tabId) {
9023
+ 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");
9024
+ }
9025
+ const id = meta?.id ?? newSessionId();
9026
+ const createdAt = meta?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
9027
+ store.save(name, {
9028
+ id,
9029
+ kind: "bridge",
9030
+ taskName,
9031
+ tabId,
9032
+ url: opts?.url ?? meta?.url ?? "",
9033
+ createdAt
9034
+ });
9035
+ const page = new BridgePage(taskName, tabId);
9036
+ const session = registerSession({
9037
+ id,
9038
+ name,
9039
+ context: page.context(),
9040
+ page,
9041
+ browser: page.browser(),
9042
+ createdAt,
9043
+ bridge: { taskName, tabId }
9044
+ });
9045
+ return session;
9046
+ }
9047
+
8308
9048
  // src/tips/dom-watcher.ts
8309
9049
  var DOM_WATCHER_SCRIPT = `
8310
9050
  (function() {
@@ -8938,7 +9678,6 @@ function classifyFailure(message) {
8938
9678
  // src/executor/chain.ts
8939
9679
  import {
8940
9680
  fail as fail18,
8941
- ok as ok32,
8942
9681
  TipCollector as TipCollector2,
8943
9682
  normalizeTips as normalizeTips7,
8944
9683
  unquote as unquote2
@@ -9183,7 +9922,34 @@ function parsePluginParams(args, schema, base = {}) {
9183
9922
  // src/executor/chain.ts
9184
9923
  async function executeChain(input, options, executeCommand2) {
9185
9924
  const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
9186
- const sessionName = options?.sessionName || "default";
9925
+ let sessionName = options?.sessionName || "default";
9926
+ for (const pipeline of pipelines) {
9927
+ const cleaned = [];
9928
+ for (const step of pipeline.pipeline) {
9929
+ const tokens = splitCommand(step);
9930
+ let stripped = false;
9931
+ const kept = [];
9932
+ for (let i = 0; i < tokens.length; i++) {
9933
+ if (options?.fixedSession && (tokens[i] === "--session" || tokens[i].startsWith("--session="))) {
9934
+ throw new Error("Set the session on the run, outside the command chain");
9935
+ }
9936
+ if (tokens[i] === "--session" && i + 1 < tokens.length) {
9937
+ sessionName = tokens[i + 1];
9938
+ stripped = true;
9939
+ i++;
9940
+ continue;
9941
+ }
9942
+ if (tokens[i].startsWith("--session=")) {
9943
+ sessionName = tokens[i].slice("--session=".length);
9944
+ stripped = true;
9945
+ continue;
9946
+ }
9947
+ kept.push(tokens[i]);
9948
+ }
9949
+ cleaned.push(stripped ? kept.join(" ") : step);
9950
+ }
9951
+ pipeline.pipeline = cleaned;
9952
+ }
9187
9953
  const results = [];
9188
9954
  const totalStart = Date.now();
9189
9955
  let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
@@ -9210,6 +9976,14 @@ async function executeChain(input, options, executeCommand2) {
9210
9976
  if (parts.length === 0) continue;
9211
9977
  const cmdName = parts[0];
9212
9978
  const cmdArgs = parts.slice(1);
9979
+ if (options?.handoff && cmdName === "handoff" && cmdArgs.length === 0) {
9980
+ const started = Date.now();
9981
+ const solved = await options.handoff();
9982
+ const message = solved ? "Human handoff completed" : "Human handoff timed out";
9983
+ results.push({ command: cmdName, raw: cmdStr, success: solved, data: null, message, duration: Date.now() - started });
9984
+ if (!solved || type === "or") return stoppedChain(solved, results, totalStart, results.length, message);
9985
+ continue;
9986
+ }
9213
9987
  const loader = await getPluginLoader();
9214
9988
  const internalLoader = loader.getCore().loader;
9215
9989
  const resolvedName = loader.resolveSiteName(cmdName);
@@ -9304,6 +10078,38 @@ async function executePluginChainStep(context) {
9304
10078
  }
9305
10079
  }
9306
10080
  }
10081
+ const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
10082
+ if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
10083
+ const { forwardPluginExec } = await import("./daemon-client-Z3NKNZRL.js");
10084
+ const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
10085
+ const startFwd = Date.now();
10086
+ const fwd = await forwardPluginExec(
10087
+ `${cmdName}.${subCommand}`,
10088
+ pluginParams,
10089
+ sessionName,
10090
+ void 0,
10091
+ userTimeout
10092
+ );
10093
+ if (fwd != null) {
10094
+ const fwdOk = fwd.success !== false;
10095
+ results.push({
10096
+ command: `${cmdName} ${subCommand}`,
10097
+ raw: cmdStr,
10098
+ success: fwdOk,
10099
+ data: fwd.data ?? null,
10100
+ message: fwd.message,
10101
+ tips: Array.isArray(fwd.tips) ? fwd.tips : void 0,
10102
+ duration: Date.now() - startFwd
10103
+ });
10104
+ if (type === "and" && !fwdOk) {
10105
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${fwd.message ?? ""}`);
10106
+ }
10107
+ if (type === "or" && fwdOk) {
10108
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
10109
+ }
10110
+ return void 0;
10111
+ }
10112
+ }
9307
10113
  const pluginCtx = {
9308
10114
  args: pluginArgs,
9309
10115
  options: pluginParams,
@@ -9371,12 +10177,14 @@ async function executePluginChainStep(context) {
9371
10177
  }
9372
10178
  if (outputs.length > 0) hookOutputs = outputs;
9373
10179
  }
9374
- const data = raw?.data ?? raw;
10180
+ const success = raw?.success !== false;
10181
+ const data = raw?.data ?? (success ? raw : null);
10182
+ const message = success ? void 0 : raw.message ?? "Plugin command failed";
9375
10183
  recordArchive(session.id, sessionName, {
9376
10184
  step: results.length,
9377
10185
  command: `${cmdName} ${subCommand}`,
9378
10186
  params: pluginParams,
9379
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
10187
+ result: { success, data, message, tips: tipsToMessages(raw?.tips) },
9380
10188
  toolCalls: [],
9381
10189
  duration,
9382
10190
  timestamp: start
@@ -9384,11 +10192,15 @@ async function executePluginChainStep(context) {
9384
10192
  results.push({
9385
10193
  command: `${cmdName} ${subCommand}`,
9386
10194
  raw: cmdStr,
9387
- ...ok32(data),
10195
+ success,
10196
+ data,
10197
+ message,
10198
+ tips: normalizeTips7(raw?.tips),
9388
10199
  duration,
9389
10200
  ...hookOutputs ? { hookOutputs } : {}
9390
10201
  });
9391
- if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
10202
+ if (!success && type === "and") return stoppedChain(false, results, totalStart, results.length, message);
10203
+ if (success && type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9392
10204
  } catch (error) {
9393
10205
  const duration = Date.now() - start;
9394
10206
  const message = errMsg(error);
@@ -9495,7 +10307,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9495
10307
  }
9496
10308
  let targetPageOverride = null;
9497
10309
  if (_target && extraOpts?.cdpEndpoint) {
9498
- const { findTargetPage } = await import("./browser-X7LO42UI.js");
10310
+ const { findTargetPage } = await import("./browser-RZ7DPBI3.js");
9499
10311
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9500
10312
  if (!targetPageOverride) {
9501
10313
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -9512,46 +10324,55 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9512
10324
  params = result.data;
9513
10325
  }
9514
10326
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
9515
- const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
10327
+ const { forwardExec } = await import("./daemon-client-Z3NKNZRL.js");
9516
10328
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
9517
10329
  const result = await forwardExec(
9518
10330
  commandName,
9519
10331
  params,
9520
10332
  sessionName,
9521
10333
  extraOpts?.cdpEndpoint,
9522
- longRunning ? 20 * 6e4 : void 0
10334
+ longRunning ? 20 * 6e4 : void 0,
10335
+ extraOpts?.bridge
9523
10336
  );
9524
10337
  if (result) return result;
9525
10338
  }
9526
10339
  let session;
9527
- const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
9528
- if (existing) {
9529
- session = existing;
9530
- if (session.page) {
9531
- try {
9532
- await Promise.race([
9533
- session.page.evaluate(() => true),
9534
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
9535
- ]);
9536
- } catch (err) {
9537
- const msg = err instanceof Error ? err.message : String(err);
9538
- if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
9539
- await closeSessionByName(session.name);
9540
- session = void 0;
10340
+ const bridgeSession = await findOrCreateBridgeSession(sessionName, {
10341
+ preferBridge: extraOpts?.bridge === true,
10342
+ url: params.url
10343
+ });
10344
+ if (bridgeSession) {
10345
+ session = bridgeSession;
10346
+ } else {
10347
+ const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
10348
+ if (existing) {
10349
+ session = existing;
10350
+ if (session.page) {
10351
+ try {
10352
+ await Promise.race([
10353
+ session.page.evaluate(() => true),
10354
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
10355
+ ]);
10356
+ } catch (err) {
10357
+ const msg = err instanceof Error ? err.message : String(err);
10358
+ if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
10359
+ await closeSessionByName(session.name);
10360
+ session = void 0;
10361
+ }
9541
10362
  }
9542
10363
  }
9543
- }
9544
- if (session && targetPageOverride && session.page) {
9545
- const currentUrl = session.page.url();
9546
- if (currentUrl !== targetPageOverride.url) {
9547
- await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
9548
- });
10364
+ if (session && targetPageOverride && session.page) {
10365
+ const currentUrl = session.page.url();
10366
+ if (currentUrl !== targetPageOverride.url) {
10367
+ await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
10368
+ });
10369
+ }
9549
10370
  }
10371
+ } else if (command.scope !== "project") {
10372
+ session = await createSession(sessionName, params.url, {
10373
+ cdpEndpoint: extraOpts?.cdpEndpoint
10374
+ });
9550
10375
  }
9551
- } else if (command.scope !== "project") {
9552
- session = await createSession(sessionName, params.url, {
9553
- cdpEndpoint: extraOpts?.cdpEndpoint
9554
- });
9555
10376
  }
9556
10377
  const ctx = {
9557
10378
  page: session?.page,
@@ -9700,7 +10521,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9700
10521
  timestamp: start
9701
10522
  });
9702
10523
  if (isSuccess) {
9703
- return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
10524
+ return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9704
10525
  }
9705
10526
  const fc = classifyFailure(raw.message);
9706
10527
  return {
@@ -9723,7 +10544,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9723
10544
  duration,
9724
10545
  timestamp: start
9725
10546
  });
9726
- return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
10547
+ return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9727
10548
  } catch (err) {
9728
10549
  const end = Date.now();
9729
10550
  const duration = end - start;
@@ -9736,7 +10557,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9736
10557
  });
9737
10558
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
9738
10559
  try {
9739
- const { attemptRecovery } = await import("./recovery-XDKN63O5.js");
10560
+ const { attemptRecovery } = await import("./recovery-7NRRHLS4.js");
9740
10561
  const recovery = await attemptRecovery(
9741
10562
  session.page,
9742
10563
  sessionName,