@xbrowser/cli 1.34.0 → 1.36.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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  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-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. 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-3E6VVMK2.js";
16
+ } from "./chunk-KSB4PMCY.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) {
@@ -3348,6 +3357,19 @@ function stripHashAnchorQuery(url) {
3348
3357
  return url;
3349
3358
  }
3350
3359
  }
3360
+ function createPageBudget(limit, used) {
3361
+ let reserved = used;
3362
+ return {
3363
+ tryAcquire() {
3364
+ if (reserved >= limit) return false;
3365
+ reserved++;
3366
+ return true;
3367
+ },
3368
+ isExhausted() {
3369
+ return reserved >= limit;
3370
+ }
3371
+ };
3372
+ }
3351
3373
  async function extractLinks(page, origin) {
3352
3374
  return page.evaluate((evalOrigin) => {
3353
3375
  return Array.from(document.querySelectorAll("a[href]")).map((a) => {
@@ -3625,6 +3647,7 @@ var crawlCommand = registerCommand({
3625
3647
  await seedPage.close();
3626
3648
  const pagePool = [];
3627
3649
  const poolSize = Math.min(options.concurrency, options.limit);
3650
+ const budget = createPageBudget(options.limit, results.length);
3628
3651
  for (let i = 0; i < poolSize; i++) {
3629
3652
  const ctx2 = await browser.newContext();
3630
3653
  contexts.push(ctx2);
@@ -3642,7 +3665,7 @@ var crawlCommand = registerCommand({
3642
3665
  return null;
3643
3666
  };
3644
3667
  const crawlWorker = async (page) => {
3645
- while (results.length < options.limit) {
3668
+ while (budget.tryAcquire()) {
3646
3669
  const item = dequeueNext();
3647
3670
  if (!item) break;
3648
3671
  completedCount++;
@@ -3656,7 +3679,7 @@ var crawlCommand = registerCommand({
3656
3679
  const pageTitle = await page.title();
3657
3680
  const pageContent = options.format === "html" ? pageHtml : htmlToMarkdown(pageHtml, { onlyMainContent: options.onlyMainContent });
3658
3681
  results.push({ url: page.url(), title: pageTitle, content: pageContent });
3659
- if (results.length >= options.limit) break;
3682
+ if (budget.isExhausted()) break;
3660
3683
  const links = await extractLinks(page, startUrl.origin);
3661
3684
  for (const link of links) {
3662
3685
  try {
@@ -4730,18 +4753,18 @@ import { z as z25 } from "zod";
4730
4753
  import { ok as ok24, fail as fail11, normalizeTips as normalizeTips3 } from "@dyyz1993/xcli-core";
4731
4754
 
4732
4755
  // src/runtime/ref-store.ts
4733
- var sessions = /* @__PURE__ */ new Map();
4756
+ var sessions2 = /* @__PURE__ */ new Map();
4734
4757
  function normalizeAgentRef(ref) {
4735
4758
  return ref.startsWith("@") ? ref.slice(1) : ref;
4736
4759
  }
4737
4760
  function replaceRefs(sessionKey2, screenHash, targets) {
4738
- sessions.set(sessionKey2, {
4761
+ sessions2.set(sessionKey2, {
4739
4762
  screenHash,
4740
4763
  targets: new Map(targets.map((target) => [target.ref, target]))
4741
4764
  });
4742
4765
  }
4743
4766
  function getRefTarget(sessionKey2, ref) {
4744
- const session = sessions.get(sessionKey2);
4767
+ const session = sessions2.get(sessionKey2);
4745
4768
  const target = session?.targets.get(normalizeAgentRef(ref));
4746
4769
  if (!session || !target) return null;
4747
4770
  return { screenHash: session.screenHash, target };
@@ -6318,6 +6341,25 @@ function isSpaceAround(input, pos, tokenLen) {
6318
6341
  const after = pos + tokenLen < input.length && input[pos + tokenLen] === " ";
6319
6342
  return before && after;
6320
6343
  }
6344
+ function splitOutsideQuotes(input, separator) {
6345
+ const parts = [];
6346
+ let inQuote = null;
6347
+ let current = "";
6348
+ for (const char of input) {
6349
+ if (!inQuote && (char === "'" || char === '"')) {
6350
+ inQuote = char;
6351
+ } else if (inQuote && char === inQuote) {
6352
+ inQuote = null;
6353
+ } else if (!inQuote && char === separator) {
6354
+ parts.push(current);
6355
+ current = "";
6356
+ continue;
6357
+ }
6358
+ current += char;
6359
+ }
6360
+ parts.push(current);
6361
+ return parts;
6362
+ }
6321
6363
  registerCommandDefinition("goto", ["url"]);
6322
6364
  registerCommandDefinition("click", ["selector"]);
6323
6365
  registerCommandDefinition("fill", ["selector", "value"]);
@@ -7340,6 +7382,857 @@ function attachDetectAntiBot(ctx) {
7340
7382
  };
7341
7383
  }
7342
7384
 
7385
+ // src/browser/bridge-session.ts
7386
+ var DEFAULT_BRIDGE_HTTP = "http://127.0.0.1:9347";
7387
+ function bridgeHttpBase() {
7388
+ return process.env.XBROWSER_BRIDGE_HTTP || DEFAULT_BRIDGE_HTTP;
7389
+ }
7390
+ async function bridgeExec(cmd, args) {
7391
+ let resp;
7392
+ try {
7393
+ resp = await fetch(`${bridgeHttpBase()}/exec`, {
7394
+ method: "POST",
7395
+ headers: { "Content-Type": "application/json" },
7396
+ body: JSON.stringify({ cmd, args })
7397
+ });
7398
+ } catch (e) {
7399
+ 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)}`);
7400
+ }
7401
+ const reply = await resp.json().catch(() => null);
7402
+ if (!reply) throw new Error("[bridge-session] bridge \u54CD\u5E94\u975E JSON\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09");
7403
+ if (reply.ok !== true) throw new Error(`[bridge-session] ${cmd} \u5931\u8D25: ${reply.error ?? "unknown"}`);
7404
+ return reply.data ?? {};
7405
+ }
7406
+ function unimplemented(op) {
7407
+ 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`);
7408
+ }
7409
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
7410
+ async function pollUntil2(pred, timeoutMs, intervalMs = 120) {
7411
+ const deadline = Date.now() + timeoutMs;
7412
+ while (Date.now() < deadline) {
7413
+ if (await pred()) return true;
7414
+ await sleep2(intervalMs);
7415
+ }
7416
+ return await pred();
7417
+ }
7418
+ function toExpression(fn, args) {
7419
+ if (typeof fn === "string") return fn;
7420
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7421
+ return `(${fn.toString()})(${callArgs})`;
7422
+ }
7423
+ function rectExpression(selector, index) {
7424
+ 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 }; })()`;
7425
+ }
7426
+ function stateExpression(selector, index) {
7427
+ 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 }; })()`;
7428
+ }
7429
+ var BridgePage = class {
7430
+ taskName;
7431
+ tabId;
7432
+ _url;
7433
+ closed = false;
7434
+ mouse;
7435
+ keyboard;
7436
+ ctxStub;
7437
+ constructor(taskName, tabId) {
7438
+ this.taskName = taskName;
7439
+ this.tabId = tabId;
7440
+ this._url = "about:blank";
7441
+ this.mouse = new BridgeMouse(this);
7442
+ this.keyboard = new BridgeKeyboard(this);
7443
+ this.ctxStub = new BridgeContextStub(this);
7444
+ }
7445
+ get bridgeTabId() {
7446
+ return this.tabId;
7447
+ }
7448
+ get bridgeTaskName() {
7449
+ return this.taskName;
7450
+ }
7451
+ /** 会话内 tab 被任务组回收后重锚(task-open 复用路径刷新 tabId) */
7452
+ retab(tabId) {
7453
+ this.tabId = tabId;
7454
+ }
7455
+ async exec(cmd, args = {}) {
7456
+ return bridgeExec(cmd, { ...args, tabId: this.tabId, task: this.taskName });
7457
+ }
7458
+ async evalExpr(expression) {
7459
+ const data = await this.exec("evaluate", { expression });
7460
+ if (data.ok !== true) throw new Error(`[bridge-session] evaluate \u5931\u8D25: ${String(data.error ?? "unknown")}`);
7461
+ return data.value ?? null;
7462
+ }
7463
+ async rectOf(selector, index = 0) {
7464
+ const raw = await this.evalExpr(rectExpression(selector, index));
7465
+ if (raw == null) return null;
7466
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7467
+ }
7468
+ async stateOf(selector, index = 0) {
7469
+ const raw = await this.evalExpr(stateExpression(selector, index));
7470
+ if (raw == null) return null;
7471
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7472
+ }
7473
+ async trustedClickAt(x, y) {
7474
+ const r = await this.exec("trustedClick", { x, y });
7475
+ if (r.ok !== true) throw new Error(`[bridge-session] trustedClick \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7476
+ }
7477
+ async clickSelector(selector, index = 0) {
7478
+ await this.waitForSelector(selector, { state: "attached", timeout: 8e3 }).catch(() => {
7479
+ throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7480
+ });
7481
+ const rect = await this.rectOf(selector, index);
7482
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7483
+ await this.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7484
+ }
7485
+ // ── Navigation ──
7486
+ async goto(url, opts) {
7487
+ await this.exec("navigate", { url });
7488
+ this._url = url;
7489
+ await this.waitForLoadState(opts?.waitUntil ?? "load", opts?.timeout ?? 3e4).catch(() => {
7490
+ });
7491
+ return {
7492
+ status: () => 200,
7493
+ ok: () => true,
7494
+ url: () => url,
7495
+ headers: () => ({})
7496
+ };
7497
+ }
7498
+ async goBack() {
7499
+ await this._cdpSend("Page.navigateToHistory", { entryId: -1 });
7500
+ }
7501
+ async goForward() {
7502
+ await this._cdpSend("Page.navigateToHistory", { entryId: 1 });
7503
+ }
7504
+ async reload(opts) {
7505
+ await this._cdpSend("Page.reload", {});
7506
+ await this.waitForLoadState("load", opts?.timeout ?? 3e4).catch(() => {
7507
+ });
7508
+ }
7509
+ async waitForLoadState(state = "load", timeout = 3e4) {
7510
+ const want = state === "domcontentloaded" ? ["interactive", "complete"] : ["complete"];
7511
+ const ok33 = await pollUntil2(async () => {
7512
+ const rs = await this.evalExpr("document.readyState").catch(() => "loading");
7513
+ return want.includes(rs);
7514
+ }, timeout);
7515
+ if (!ok33) throw new Error(`[bridge-session] waitForLoadState(${state}) \u8D85\u65F6`);
7516
+ }
7517
+ async waitForTimeout(ms) {
7518
+ await sleep2(ms);
7519
+ }
7520
+ async waitForSelector(selector, opts) {
7521
+ const state = opts?.state ?? "visible";
7522
+ const timeout = opts?.timeout ?? 3e4;
7523
+ const ok33 = await pollUntil2(async () => {
7524
+ const st = await this.stateOf(selector).catch(() => null);
7525
+ if (!st) return state === "detached";
7526
+ if (state === "attached") return st.found;
7527
+ if (state === "visible") return st.found && st.visible;
7528
+ if (state === "hidden") return !st.found || !st.visible;
7529
+ return !st.found;
7530
+ }, timeout);
7531
+ if (!ok33) throw new Error(`[bridge-session] waitForSelector(${selector}, ${state}) \u8D85\u65F6`);
7532
+ }
7533
+ async waitForFunction(fn, opts, ...args) {
7534
+ const expression = toExpression(fn, args);
7535
+ const timeout = opts?.timeout ?? 3e4;
7536
+ const interval = typeof opts?.polling === "number" ? opts.polling : 120;
7537
+ let last = null;
7538
+ const ok33 = await pollUntil2(async () => {
7539
+ last = await this.evalExpr(expression).catch(() => false);
7540
+ return Boolean(last);
7541
+ }, timeout, interval);
7542
+ if (!ok33) throw new Error(`[bridge-session] waitForFunction \u8D85\u65F6\uFF08last=${JSON.stringify(last)?.slice(0, 80)}\uFF09`);
7543
+ return last;
7544
+ }
7545
+ async waitForURL(url, opts) {
7546
+ const match = (href) => {
7547
+ if (typeof url === "string") return href === url || href.startsWith(url);
7548
+ if (url instanceof RegExp) return url.test(href);
7549
+ return url(href);
7550
+ };
7551
+ const ok33 = await pollUntil2(async () => {
7552
+ const href = await this.evalExpr("location.href").catch(() => "");
7553
+ if (match(href)) {
7554
+ this._url = href;
7555
+ return true;
7556
+ }
7557
+ return false;
7558
+ }, opts?.timeout ?? 3e4);
7559
+ if (!ok33) throw new Error("[bridge-session] waitForURL \u8D85\u65F6");
7560
+ }
7561
+ async waitForResponse() {
7562
+ return unimplemented("waitForResponse\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7563
+ }
7564
+ async waitForRequest() {
7565
+ return unimplemented("waitForRequest\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7566
+ }
7567
+ url() {
7568
+ return this._url;
7569
+ }
7570
+ async title() {
7571
+ return this.evalExpr("document.title");
7572
+ }
7573
+ async content() {
7574
+ return this.evalExpr("document.documentElement.outerHTML");
7575
+ }
7576
+ // ── Evaluation ──
7577
+ async evaluate(fn, ...args) {
7578
+ return this.evalExpr(toExpression(fn, args));
7579
+ }
7580
+ async $eval(selector, fn, ...args) {
7581
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7582
+ 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"}); })()`;
7583
+ return this.evalExpr(expression);
7584
+ }
7585
+ async $$eval(selector, fn, ...args) {
7586
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7587
+ const expression = `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "els, " + callArgs : "els"}); })()`;
7588
+ return this.evalExpr(expression);
7589
+ }
7590
+ // ── Locator ──
7591
+ locator(selector) {
7592
+ return new BridgeLocator(this, selector, 0);
7593
+ }
7594
+ getByText(text, opts) {
7595
+ return new BridgeLocator(this, BridgeLocator.textQuery(text, opts?.exact ?? true), 0, true);
7596
+ }
7597
+ getByRole(role, opts) {
7598
+ const name = opts?.name ? `[aria-label*=${JSON.stringify(opts.name)}]` : "";
7599
+ return new BridgeLocator(this, `[role="${role}"]${name}, ${role}${name}`, 0);
7600
+ }
7601
+ getByLabel(label, opts) {
7602
+ void opts;
7603
+ return new BridgeLocator(this, `label[for], [aria-label*=${JSON.stringify(label)}]`, 0);
7604
+ }
7605
+ getByPlaceholder(text) {
7606
+ return new BridgeLocator(this, `[placeholder*=${JSON.stringify(text)}]`, 0);
7607
+ }
7608
+ getByTestId(id) {
7609
+ return new BridgeLocator(this, `[data-testid="${id}"]`, 0);
7610
+ }
7611
+ getByAltText(text) {
7612
+ return new BridgeLocator(this, `[alt*=${JSON.stringify(text)}]`, 0);
7613
+ }
7614
+ getByTitle(text) {
7615
+ return new BridgeLocator(this, `[title*=${JSON.stringify(text)}]`, 0);
7616
+ }
7617
+ // ── Interaction shortcuts ──
7618
+ async click(selector, _opts) {
7619
+ await this.clickSelector(selector);
7620
+ }
7621
+ async dblclick(selector, _opts) {
7622
+ const rect = await this.rectOf(selector);
7623
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7624
+ const x = Math.round(rect.x + rect.width / 2);
7625
+ const y = Math.round(rect.y + rect.height / 2);
7626
+ await this.trustedClickAt(x, y);
7627
+ await sleep2(60);
7628
+ await this.trustedClickAt(x, y);
7629
+ }
7630
+ async fill(selector, value, _opts) {
7631
+ const direct = await this.exec("fill", { selector, value });
7632
+ if (direct.ok === true) return;
7633
+ const typed = await this.exec("type", { selector, text: value });
7634
+ if (typed.ok !== true) throw new Error(`[bridge-session] fill \u5931\u8D25: ${String(direct.error ?? typed.error ?? "unknown")}`);
7635
+ }
7636
+ async press(selector, key, _opts) {
7637
+ await this.clickSelector(selector);
7638
+ await this.keyboard.press(key);
7639
+ }
7640
+ async hover(selector, _opts) {
7641
+ const rect = await this.rectOf(selector);
7642
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7643
+ await this.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7644
+ }
7645
+ async type(selector, text, _opts) {
7646
+ const r = await this.exec("type", { selector, text });
7647
+ if (r.ok !== true) throw new Error(`[bridge-session] type \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7648
+ }
7649
+ async check(selector, _opts) {
7650
+ const st = await this.stateOf(selector);
7651
+ if (st && !await this.evalExpr(`document.querySelector(${JSON.stringify(selector)}).checked`)) {
7652
+ await this.clickSelector(selector);
7653
+ }
7654
+ }
7655
+ async uncheck(selector, _opts) {
7656
+ const checked = await this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.checked === true`);
7657
+ if (checked) await this.clickSelector(selector);
7658
+ }
7659
+ async selectOption(selector, value) {
7660
+ const v = Array.isArray(value) ? value : [value];
7661
+ const result = await this.evalExpr(
7662
+ `(() => { 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; })()`
7663
+ );
7664
+ return result ?? [];
7665
+ }
7666
+ // ── Convenience selectors ──
7667
+ async textContent(selector) {
7668
+ const st = await this.stateOf(selector);
7669
+ return st?.text ?? null;
7670
+ }
7671
+ async innerText(selector) {
7672
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
7673
+ }
7674
+ async innerHTML(selector) {
7675
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerHTML ?? ''`);
7676
+ }
7677
+ async getAttribute(selector, name) {
7678
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
7679
+ }
7680
+ // ── Query ──
7681
+ async $(selector) {
7682
+ const st = await this.stateOf(selector);
7683
+ return st ? new BridgeElementHandle(this, selector, 0) : null;
7684
+ }
7685
+ async $$(selector) {
7686
+ const count = await this.evalExpr(`document.querySelectorAll(${JSON.stringify(selector)}).length`);
7687
+ return Array.from({ length: count }, (_, i) => new BridgeElementHandle(this, selector, i));
7688
+ }
7689
+ // ── Screen ──
7690
+ async screenshot(_opts) {
7691
+ const r = await this.exec("screenshot", {});
7692
+ const b64 = r.base64;
7693
+ if (!b64) throw new Error(`[bridge-session] screenshot \u5931\u8D25: ${String(r.error ?? "no base64")}`);
7694
+ return Buffer.from(b64, "base64");
7695
+ }
7696
+ async pdf(_opts) {
7697
+ return unimplemented("pdf");
7698
+ }
7699
+ viewportSize() {
7700
+ return null;
7701
+ }
7702
+ async setViewportSize(_size) {
7703
+ unimplemented("setViewportSize");
7704
+ }
7705
+ async setDeviceScaleFactor(_dsf) {
7706
+ unimplemented("setDeviceScaleFactor");
7707
+ }
7708
+ // ── Scripts / UA / Frames / OOPIF ──
7709
+ async addInitScript(_script) {
7710
+ unimplemented("addInitScript");
7711
+ }
7712
+ async setUserAgent(_ua) {
7713
+ unimplemented("setUserAgent");
7714
+ }
7715
+ async discoverFrames() {
7716
+ return [];
7717
+ }
7718
+ async evaluateInFrame(_urlIncludes, _expression) {
7719
+ return unimplemented("evaluateInFrame");
7720
+ }
7721
+ async listFrameTargets() {
7722
+ return [];
7723
+ }
7724
+ async frameMouse(_urlIncludes, _opts) {
7725
+ return unimplemented("frameMouse");
7726
+ }
7727
+ async runFrameMouse(_urlIncludes, _fn) {
7728
+ return unimplemented("runFrameMouse");
7729
+ }
7730
+ async clickInFrame(_urlIncludes, _selector, _opts) {
7731
+ return unimplemented("clickInFrame");
7732
+ }
7733
+ async fillInFrame(_urlIncludes, _selector, _text, _opts) {
7734
+ return unimplemented("fillInFrame");
7735
+ }
7736
+ // ── Page management ──
7737
+ async bringToFront() {
7738
+ await this._cdpSend("Page.bringToFront", {});
7739
+ }
7740
+ async setExtraHTTPHeaders(_headers) {
7741
+ unimplemented("setExtraHTTPHeaders");
7742
+ }
7743
+ async setOfflineMode(_offline) {
7744
+ unimplemented("setOfflineMode");
7745
+ }
7746
+ async route(_url, _handler) {
7747
+ unimplemented("route");
7748
+ }
7749
+ async unroute(_url, _handler) {
7750
+ unimplemented("unroute");
7751
+ }
7752
+ async setInputFiles(_selector, _files) {
7753
+ unimplemented("setInputFiles");
7754
+ }
7755
+ async dropFiles(_selector, _payload) {
7756
+ unimplemented("dropFiles");
7757
+ }
7758
+ setBeforeUnloadBehavior(_mode) {
7759
+ }
7760
+ async dragAndDrop(_source, _target) {
7761
+ unimplemented("dragAndDrop");
7762
+ }
7763
+ // ── Dialog / events ──
7764
+ on(_event, _handler) {
7765
+ }
7766
+ off(_event, _handler) {
7767
+ }
7768
+ async waitForEvent(_event, opts) {
7769
+ await sleep2(opts?.timeout ?? 3e4);
7770
+ return unimplemented(`waitForEvent(${_event})\u2014\u2014\u4E8B\u4EF6\u7C7B\u80FD\u529B`);
7771
+ }
7772
+ // ── CDP escape hatch ──
7773
+ async _cdpSend(method, params) {
7774
+ const r = await this.exec("cdp", { method, params: params ?? {} });
7775
+ if (r.ok !== true) throw new Error(`[bridge-session] cdp ${method} \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7776
+ return r.data ?? null;
7777
+ }
7778
+ _subscribe(_event, _handler) {
7779
+ return () => {
7780
+ };
7781
+ }
7782
+ // ── Lifecycle ──
7783
+ async close() {
7784
+ if (this.closed) return;
7785
+ this.closed = true;
7786
+ await bridgeExec("task-close", { name: this.taskName }).catch(() => {
7787
+ });
7788
+ }
7789
+ isClosed() {
7790
+ return this.closed;
7791
+ }
7792
+ context() {
7793
+ return this.ctxStub;
7794
+ }
7795
+ browser() {
7796
+ return this.ctxStub.browser();
7797
+ }
7798
+ mainFrame() {
7799
+ return new BridgeFrame(this);
7800
+ }
7801
+ frames() {
7802
+ return [this.mainFrame()];
7803
+ }
7804
+ };
7805
+ var BridgeLocator = class _BridgeLocator {
7806
+ constructor(page, selector, index, isText = false) {
7807
+ this.page = page;
7808
+ this.selector = selector;
7809
+ this.index = index;
7810
+ this.isText = isText;
7811
+ }
7812
+ page;
7813
+ selector;
7814
+ index;
7815
+ isText;
7816
+ /** text 伪查询编码:==精确 / ~包含(无等价 CSS,rect() 编译为 evaluate 表达式) */
7817
+ static textQuery(text, exact) {
7818
+ return `${exact ? "==" : "~"}${text}`;
7819
+ }
7820
+ async rect() {
7821
+ if (!this.isText) return this.page.rectOf(this.selector, this.index);
7822
+ const m = /^(==|~)([\s\S]*)$/.exec(this.selector);
7823
+ const exact = m?.[1] === "==";
7824
+ const text = JSON.stringify(m?.[2] ?? this.selector);
7825
+ const cmp = exact ? `e.textContent.trim() === ${text}` : `e.textContent.includes(${text})`;
7826
+ 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 }; })()`;
7827
+ const r = await this.page.evaluate(expression);
7828
+ const v = r;
7829
+ return v == null ? null : typeof v === "string" ? JSON.parse(v) : v;
7830
+ }
7831
+ async click(_opts) {
7832
+ const rect = await this.rect();
7833
+ if (!rect) throw new Error(`[bridge-session] locator \u672A\u547D\u4E2D: ${this.selector}`);
7834
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7835
+ }
7836
+ async fill(value, _opts) {
7837
+ if (!this.isText) {
7838
+ await this.page.fill(this.selector, value);
7839
+ return;
7840
+ }
7841
+ await this.click();
7842
+ await this.page.keyboard.type(value);
7843
+ }
7844
+ async press(key, _opts) {
7845
+ await this.page.keyboard.press(key);
7846
+ }
7847
+ async pressSequentially(text, opts) {
7848
+ await this.page.keyboard.type(text, opts);
7849
+ }
7850
+ async hover(_opts) {
7851
+ const rect = await this.rect();
7852
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7853
+ }
7854
+ async type(text, _opts) {
7855
+ await this.page.keyboard.type(text);
7856
+ }
7857
+ async check(_opts) {
7858
+ await this.click();
7859
+ }
7860
+ async uncheck(_opts) {
7861
+ await this.click();
7862
+ }
7863
+ async selectOption(value) {
7864
+ if (!this.isText) return this.page.selectOption(this.selector, value);
7865
+ return unimplemented("text locator selectOption");
7866
+ }
7867
+ async screenshot(opts) {
7868
+ return this.page.screenshot(opts);
7869
+ }
7870
+ async focus() {
7871
+ if (!this.isText) await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.focus()`);
7872
+ }
7873
+ async waitFor(opts) {
7874
+ if (!this.isText) await this.page.waitForSelector(this.selector, opts);
7875
+ }
7876
+ async count() {
7877
+ if (!this.isText) return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)}).length`);
7878
+ const rect = await this.rect();
7879
+ return rect ? 1 : 0;
7880
+ }
7881
+ async isVisible() {
7882
+ const rect = await this.rect();
7883
+ return rect !== null && rect.width + rect.height > 0;
7884
+ }
7885
+ async isHidden() {
7886
+ return !await this.isVisible();
7887
+ }
7888
+ async isEnabled() {
7889
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7890
+ return st ? !st.disabled : false;
7891
+ }
7892
+ async isDisabled() {
7893
+ return !await this.isEnabled();
7894
+ }
7895
+ async boundingBox() {
7896
+ return this.rect();
7897
+ }
7898
+ async textContent() {
7899
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7900
+ return st?.text ?? null;
7901
+ }
7902
+ async innerText() {
7903
+ return await this.textContent() ?? "";
7904
+ }
7905
+ async innerHTML() {
7906
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7907
+ return st?.html ?? "";
7908
+ }
7909
+ async getAttribute(name) {
7910
+ return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.getAttribute(${JSON.stringify(name)}) ?? null`);
7911
+ }
7912
+ async evaluate(fn, ...args) {
7913
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7914
+ return this.page.evaluate(`(() => { const el = document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]; return el ? (${typeof fn === "string" ? fn : fn.toString()})(${callArgs}) : null; })()`);
7915
+ }
7916
+ async ariaSnapshot() {
7917
+ return unimplemented("ariaSnapshot");
7918
+ }
7919
+ first() {
7920
+ return new _BridgeLocator(this.page, this.selector, 0, this.isText);
7921
+ }
7922
+ last() {
7923
+ return unimplemented("locator.last()");
7924
+ }
7925
+ nth(index) {
7926
+ return new _BridgeLocator(this.page, this.selector, index, this.isText);
7927
+ }
7928
+ filter(_opts) {
7929
+ return unimplemented("locator.filter()");
7930
+ }
7931
+ async all() {
7932
+ const n = await this.count();
7933
+ return Array.from({ length: n }, (_, i) => new _BridgeLocator(this.page, this.selector, i, this.isText));
7934
+ }
7935
+ };
7936
+ var BridgeElementHandle = class {
7937
+ constructor(page, selector, index) {
7938
+ this.page = page;
7939
+ this.selector = selector;
7940
+ this.index = index;
7941
+ }
7942
+ page;
7943
+ selector;
7944
+ index;
7945
+ async click(_opts) {
7946
+ const rect = await this.page.rectOf(this.selector, this.index);
7947
+ if (!rect) throw new Error("[bridge-session] element \u672A\u547D\u4E2D");
7948
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7949
+ }
7950
+ async fill(value, _opts) {
7951
+ await this.page.fill(this.selector, value);
7952
+ }
7953
+ async hover() {
7954
+ const rect = await this.page.rectOf(this.selector, this.index);
7955
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7956
+ }
7957
+ async press(key) {
7958
+ await this.page.keyboard.press(key);
7959
+ }
7960
+ async screenshot(opts) {
7961
+ return this.page.screenshot(opts);
7962
+ }
7963
+ async boundingBox() {
7964
+ return this.page.rectOf(this.selector, this.index);
7965
+ }
7966
+ async isVisible() {
7967
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7968
+ return Boolean(st?.visible);
7969
+ }
7970
+ async isEnabled() {
7971
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7972
+ return st ? !st.disabled : false;
7973
+ }
7974
+ async textContent() {
7975
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7976
+ return st?.text ?? null;
7977
+ }
7978
+ async innerText() {
7979
+ return await this.textContent() ?? "";
7980
+ }
7981
+ async innerHTML() {
7982
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7983
+ return st?.html ?? "";
7984
+ }
7985
+ async getAttribute(name) {
7986
+ return this.page.getAttribute(this.selector, name);
7987
+ }
7988
+ async scrollIntoViewIfNeeded() {
7989
+ await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.scrollIntoView({ block: 'center' })`);
7990
+ }
7991
+ dispose() {
7992
+ }
7993
+ };
7994
+ var KEY_CODES = {
7995
+ Enter: 13,
7996
+ Tab: 9,
7997
+ Escape: 27,
7998
+ Backspace: 8,
7999
+ Delete: 46,
8000
+ ArrowUp: 38,
8001
+ ArrowDown: 40,
8002
+ ArrowLeft: 37,
8003
+ ArrowRight: 39,
8004
+ Home: 36,
8005
+ End: 35,
8006
+ PageUp: 33,
8007
+ PageDown: 34
8008
+ };
8009
+ var BridgeMouse = class {
8010
+ constructor(page) {
8011
+ this.page = page;
8012
+ }
8013
+ page;
8014
+ async dispatch(params) {
8015
+ await this.page._cdpSend("Input.dispatchMouseEvent", params);
8016
+ }
8017
+ async click(x, y, opts) {
8018
+ const button = opts?.button ?? "left";
8019
+ const clickCount = opts?.clickCount ?? 1;
8020
+ const buttons = button === "left" ? 1 : button === "right" ? 2 : 4;
8021
+ await this.dispatch({ type: "mousePressed", x, y, button, buttons, clickCount });
8022
+ if (opts?.delay) await sleep2(opts.delay);
8023
+ await this.dispatch({ type: "mouseReleased", x, y, button, buttons, clickCount });
8024
+ }
8025
+ async dblclick(x, y, opts) {
8026
+ await this.click(x, y, { ...opts, clickCount: 1 });
8027
+ await sleep2(60);
8028
+ await this.click(x, y, { ...opts, clickCount: 2 });
8029
+ }
8030
+ async down(opts) {
8031
+ const button = opts?.button ?? "left";
8032
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button, buttons: button === "left" ? 1 : button === "right" ? 2 : 4, clickCount: 1 });
8033
+ }
8034
+ async up(opts) {
8035
+ const button = opts?.button ?? "left";
8036
+ await this.dispatch({ type: "mouseReleased", x: 0, y: 0, button, buttons: 0, clickCount: 1 });
8037
+ }
8038
+ async move(x, y, opts) {
8039
+ const steps = Math.max(1, opts?.steps ?? 1);
8040
+ for (let i = 1; i <= steps; i++) {
8041
+ await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 0 });
8042
+ }
8043
+ }
8044
+ async wheel(deltaX, deltaY) {
8045
+ await this.dispatch({ type: "mouseWheel", x: 0, y: 0, deltaX, deltaY });
8046
+ }
8047
+ async wheelAt(x, y, deltaX, deltaY) {
8048
+ await this.move(x, y);
8049
+ await this.dispatch({ type: "mouseWheel", x, y, deltaX, deltaY });
8050
+ }
8051
+ async drag(x, y, opts) {
8052
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button: "left", buttons: 1, clickCount: 1 });
8053
+ const steps = Math.max(1, opts?.steps ?? 10);
8054
+ for (let i = 1; i <= steps; i++) await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 1 });
8055
+ await this.dispatch({ type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
8056
+ }
8057
+ };
8058
+ var BridgeKeyboard = class {
8059
+ constructor(page) {
8060
+ this.page = page;
8061
+ }
8062
+ page;
8063
+ async key(event) {
8064
+ await this.page._cdpSend("Input.dispatchKeyEvent", {
8065
+ type: event.type,
8066
+ key: event.key,
8067
+ code: event.code ?? event.key,
8068
+ windowsVirtualKeyCode: KEY_CODES[event.key] ?? (event.key.length === 1 ? event.key.toUpperCase().charCodeAt(0) : 0),
8069
+ nativeVirtualKeyCode: KEY_CODES[event.key] ?? 0,
8070
+ ...event.modifiers !== void 0 ? { modifiers: event.modifiers } : {},
8071
+ ...event.text !== void 0 ? { text: event.text } : {}
8072
+ });
8073
+ }
8074
+ async press(key, _opts) {
8075
+ await this.key({ type: "keyDown", key });
8076
+ await this.key({ type: "keyUp", key });
8077
+ }
8078
+ async pressNav(key) {
8079
+ await this.key({ type: "keyDown", key });
8080
+ }
8081
+ async pressCombo(key, modifier) {
8082
+ const bits = { Alt: 1, Meta: 4, Control: 2, Shift: 8 };
8083
+ await this.key({ type: "keyDown", key: modifier, modifiers: bits[modifier] });
8084
+ await this.key({ type: "keyDown", key, modifiers: bits[modifier] });
8085
+ await this.key({ type: "keyUp", key, modifiers: bits[modifier] });
8086
+ await this.key({ type: "keyUp", key: modifier });
8087
+ }
8088
+ async down(key) {
8089
+ await this.key({ type: "keyDown", key });
8090
+ }
8091
+ async up(key) {
8092
+ await this.key({ type: "keyUp", key });
8093
+ }
8094
+ async type(text, _opts) {
8095
+ const r = await this.page.exec("trusted-type", { text });
8096
+ if (r.ok !== true) {
8097
+ for (const ch of text) await this.key({ type: "keyDown", key: ch, text: ch });
8098
+ }
8099
+ }
8100
+ async insertText(text) {
8101
+ await this.page._cdpSend("Input.insertText", { text });
8102
+ }
8103
+ };
8104
+ var BridgeFrame = class {
8105
+ constructor(bridgePage) {
8106
+ this.bridgePage = bridgePage;
8107
+ }
8108
+ bridgePage;
8109
+ url() {
8110
+ return this.bridgePage.url();
8111
+ }
8112
+ name() {
8113
+ return "";
8114
+ }
8115
+ isDetached() {
8116
+ return this.bridgePage.isClosed();
8117
+ }
8118
+ page() {
8119
+ return this.bridgePage;
8120
+ }
8121
+ async evaluate(fn, ...args) {
8122
+ return this.bridgePage.evaluate(fn, ...args);
8123
+ }
8124
+ async $(selector) {
8125
+ return this.bridgePage.$(selector);
8126
+ }
8127
+ async $$(selector) {
8128
+ return this.bridgePage.$$(selector);
8129
+ }
8130
+ };
8131
+ var BridgeBrowserStub = class {
8132
+ disconnected = false;
8133
+ ctx;
8134
+ constructor(ctx) {
8135
+ this.ctx = ctx;
8136
+ }
8137
+ async close() {
8138
+ }
8139
+ async disconnect() {
8140
+ this.disconnected = true;
8141
+ }
8142
+ async newContext(_opts) {
8143
+ return unimplemented("browser.newContext");
8144
+ }
8145
+ contexts() {
8146
+ return [this.ctx];
8147
+ }
8148
+ async discoverContexts() {
8149
+ }
8150
+ on(_event, _handler) {
8151
+ }
8152
+ off(_event, _handler) {
8153
+ }
8154
+ };
8155
+ var BridgeContextStub = class {
8156
+ constructor(bridgePage) {
8157
+ this.bridgePage = bridgePage;
8158
+ this.browserStub = new BridgeBrowserStub(this);
8159
+ }
8160
+ bridgePage;
8161
+ browserStub;
8162
+ async newPage() {
8163
+ return this.bridgePage;
8164
+ }
8165
+ pages() {
8166
+ return this.bridgePage.isClosed() ? [] : [this.bridgePage];
8167
+ }
8168
+ async close() {
8169
+ await this.bridgePage.close();
8170
+ }
8171
+ browser() {
8172
+ return this.browserStub;
8173
+ }
8174
+ async newCDPSession(_page) {
8175
+ return unimplemented("newCDPSession");
8176
+ }
8177
+ async addInitScript(_script) {
8178
+ unimplemented("addInitScript");
8179
+ }
8180
+ async cookies(_urls) {
8181
+ return [];
8182
+ }
8183
+ async addCookies(_cookies) {
8184
+ unimplemented("addCookies");
8185
+ }
8186
+ async clearCookies() {
8187
+ unimplemented("clearCookies");
8188
+ }
8189
+ on(_event, _handler) {
8190
+ }
8191
+ off(_event, _handler) {
8192
+ }
8193
+ };
8194
+ var realMetaStore = {
8195
+ read: (name) => readSessionDiskMeta(name),
8196
+ save: (name, data) => {
8197
+ saveSessionDiskMeta(name, data);
8198
+ }
8199
+ };
8200
+ var metaStore = realMetaStore;
8201
+ async function findOrCreateBridgeSession(name, opts) {
8202
+ const store = metaStore ?? realMetaStore;
8203
+ const meta = store.read(name);
8204
+ if (meta?.kind !== "bridge" && !opts?.preferBridge) return null;
8205
+ const inMemory = sessions.find(name);
8206
+ if (inMemory?.bridge) return inMemory;
8207
+ const taskName = meta?.taskName ?? name;
8208
+ const opened = await bridgeExec("task-open", { name: taskName }).catch(() => null);
8209
+ const tabId = Number(opened?.tabId ?? 0);
8210
+ if (!opened || !tabId) {
8211
+ 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");
8212
+ }
8213
+ const id = meta?.id ?? newSessionId();
8214
+ const createdAt = meta?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
8215
+ store.save(name, {
8216
+ id,
8217
+ kind: "bridge",
8218
+ taskName,
8219
+ tabId,
8220
+ url: opts?.url ?? meta?.url ?? "",
8221
+ createdAt
8222
+ });
8223
+ const page = new BridgePage(taskName, tabId);
8224
+ const session = registerSession({
8225
+ id,
8226
+ name,
8227
+ context: page.context(),
8228
+ page,
8229
+ browser: page.browser(),
8230
+ createdAt,
8231
+ bridge: { taskName, tabId }
8232
+ });
8233
+ return session;
8234
+ }
8235
+
7343
8236
  // src/tips/dom-watcher.ts
7344
8237
  var DOM_WATCHER_SCRIPT = `
7345
8238
  (function() {
@@ -7850,6 +8743,41 @@ function getTipsManager() {
7850
8743
  return globalTipsManager;
7851
8744
  }
7852
8745
 
8746
+ // src/utils/zod-internal.ts
8747
+ function asZodSchema(value) {
8748
+ return value;
8749
+ }
8750
+
8751
+ // src/utils/kebab-params.ts
8752
+ function toCamelCase(key) {
8753
+ return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8754
+ }
8755
+ function schemaParamNames(schema) {
8756
+ for (let node = schema, depth = 0; node != null && depth < 5; depth++) {
8757
+ const internal = asZodSchema(node);
8758
+ const shape = internal.shape ?? internal._def?.shape;
8759
+ if (shape) {
8760
+ return new Set(Object.keys(typeof shape === "function" ? shape() : shape));
8761
+ }
8762
+ node = internal._def?.innerType ?? internal._def?.schema;
8763
+ }
8764
+ return void 0;
8765
+ }
8766
+ function normalizeKebabParams(schema, params) {
8767
+ const names = schemaParamNames(schema);
8768
+ if (!names) return params;
8769
+ let renamed;
8770
+ for (const [key, value] of Object.entries(params)) {
8771
+ if (!key.includes("-")) continue;
8772
+ const camelKey = toCamelCase(key);
8773
+ if (camelKey === key || !names.has(camelKey) || names.has(key)) continue;
8774
+ renamed ??= { ...params };
8775
+ if (!(camelKey in params)) renamed[camelKey] = value;
8776
+ delete renamed[key];
8777
+ }
8778
+ return renamed ?? params;
8779
+ }
8780
+
7853
8781
  // src/hooks/loader.ts
7854
8782
  var FAIL_KEYWORDS = [
7855
8783
  "\u767B\u5F55",
@@ -7970,127 +8898,9 @@ function classifyFailure(message) {
7970
8898
  return pick(FAIL_CODES.unknown);
7971
8899
  }
7972
8900
 
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
8901
  // src/executor/foundation.ts
8092
- import { homedir as homedir7 } from "os";
8093
- import { join as join9 } from "path";
8902
+ import { homedir as homedir6 } from "os";
8903
+ import { join as join8 } from "path";
8094
8904
  import {
8095
8905
  CompositeStorage as CompositeStorage2,
8096
8906
  configureArchiveStore,
@@ -8103,19 +8913,19 @@ import {
8103
8913
  import {
8104
8914
  Core
8105
8915
  } 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";
8916
+ import { resolve as resolve2, basename, dirname as dirname3 } from "path";
8917
+ import { existsSync as existsSync6, readdirSync } from "fs";
8918
+ import { homedir as homedir5 } from "os";
8109
8919
 
8110
8920
  // src/plugin/metadata-parser.ts
8111
- import { existsSync as existsSync5 } from "fs";
8921
+ import { existsSync as existsSync4 } from "fs";
8112
8922
  import { resolve } from "path";
8113
8923
 
8114
8924
  // src/utils/json-file.ts
8115
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
8925
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
8116
8926
  function readJsonFile(filePath, defaultValue) {
8117
8927
  try {
8118
- const content = readFileSync6(filePath, "utf-8");
8928
+ const content = readFileSync5(filePath, "utf-8");
8119
8929
  return JSON.parse(content);
8120
8930
  } catch {
8121
8931
  return defaultValue;
@@ -8127,7 +8937,7 @@ var PluginMetadataParser = class {
8127
8937
  static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
8128
8938
  static parseFromPackageJson(pluginPath) {
8129
8939
  const packageJsonPath = resolve(pluginPath, "package.json");
8130
- if (!existsSync5(packageJsonPath)) {
8940
+ if (!existsSync4(packageJsonPath)) {
8131
8941
  return null;
8132
8942
  }
8133
8943
  const packageJson = readJsonFile(packageJsonPath, null);
@@ -8191,20 +9001,20 @@ var PluginMetadataParser = class {
8191
9001
  };
8192
9002
 
8193
9003
  // 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";
9004
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
9005
+ import { join as join7 } from "path";
8196
9006
  import { execSync } from "child_process";
8197
9007
  var SHARED_PLUGIN_DEPENDENCIES = {
8198
9008
  "zod": "^3.24.0",
8199
9009
  "@dyyz1993/xcli-core": "^0.19.0"
8200
9010
  };
8201
9011
  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");
9012
+ const zodPath = join7(pluginsDir, "node_modules", "zod");
9013
+ if (existsSync5(zodPath)) return;
9014
+ mkdirSync4(pluginsDir, { recursive: true });
9015
+ const pkgPath = join7(pluginsDir, "package.json");
8206
9016
  let pkg = {};
8207
- if (existsSync6(pkgPath)) {
9017
+ if (existsSync5(pkgPath)) {
8208
9018
  try {
8209
9019
  pkg = readJsonFile(pkgPath, {});
8210
9020
  } catch {
@@ -8218,11 +9028,11 @@ function ensurePluginDependencies(pluginsDir) {
8218
9028
  needsInstall = true;
8219
9029
  }
8220
9030
  }
8221
- if (!needsInstall && existsSync6(join8(pluginsDir, "node_modules"))) return;
9031
+ if (!needsInstall && existsSync5(join7(pluginsDir, "node_modules"))) return;
8222
9032
  pkg.dependencies = existingDeps;
8223
9033
  pkg.private = true;
8224
9034
  pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
8225
- writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
9035
+ writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
8226
9036
  try {
8227
9037
  execSync("npm install --production --no-package-lock --no-fund --no-audit", {
8228
9038
  cwd: pluginsDir,
@@ -8478,7 +9288,7 @@ var XBrowserPluginLoader = class {
8478
9288
  async loadPlugin(pluginPath, id) {
8479
9289
  const before = new Set(this.core.loader.getSites().map((s) => s.name));
8480
9290
  const instance = await this.loader.loadPlugin(pluginPath, id);
8481
- this.recordSiteAliases(basename(dirname4(pluginPath)), before);
9291
+ this.recordSiteAliases(basename(dirname3(pluginPath)), before);
8482
9292
  return instance;
8483
9293
  }
8484
9294
  async unloadPlugin(id) {
@@ -8492,18 +9302,18 @@ var XBrowserPluginLoader = class {
8492
9302
  }
8493
9303
  async scanAndLoad() {
8494
9304
  const cwd = this.options.cwd || process.cwd();
8495
- const globalDir = this.options.globalDir || resolve2(homedir6(), ".xbrowser/plugins");
9305
+ const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
8496
9306
  ensurePluginDependencies(globalDir);
8497
9307
  const dirs = [
8498
9308
  resolve2(cwd, ".xcli/plugins"),
8499
9309
  resolve2(cwd, "../.xcli/plugins"),
8500
- this.options.userDir || resolve2(homedir6(), ".xcli/plugins"),
9310
+ this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
8501
9311
  globalDir
8502
9312
  ];
8503
9313
  const loaded = [];
8504
9314
  const seen = /* @__PURE__ */ new Set();
8505
9315
  for (const dir of dirs) {
8506
- if (!existsSync7(dir)) continue;
9316
+ if (!existsSync6(dir)) continue;
8507
9317
  const entries = readdirSync(dir, { withFileTypes: true });
8508
9318
  for (const entry of entries) {
8509
9319
  if (!entry.isDirectory()) continue;
@@ -8511,12 +9321,12 @@ var XBrowserPluginLoader = class {
8511
9321
  seen.add(entry.name);
8512
9322
  const pluginDir = resolve2(dir, entry.name);
8513
9323
  let indexPath = resolve2(pluginDir, "index.js");
8514
- if (!existsSync7(indexPath)) {
9324
+ if (!existsSync6(indexPath)) {
8515
9325
  indexPath = resolve2(pluginDir, "index.ts");
8516
9326
  }
8517
- if (!existsSync7(indexPath)) continue;
9327
+ if (!existsSync6(indexPath)) continue;
8518
9328
  try {
8519
- if (!existsSync7(resolve2(pluginDir, "package.json"))) {
9329
+ if (!existsSync6(resolve2(pluginDir, "package.json"))) {
8520
9330
  console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
8521
9331
  } else {
8522
9332
  const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
@@ -8571,7 +9381,7 @@ async function getPluginLoader() {
8571
9381
  // src/executor/foundation.ts
8572
9382
  var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8573
9383
  var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8574
- var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
9384
+ var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8575
9385
  var storageCache = /* @__PURE__ */ new Map();
8576
9386
  function getPluginStorage(pluginName) {
8577
9387
  if (!storageCache.has(pluginName)) {
@@ -8583,7 +9393,7 @@ var archiveInitialized = false;
8583
9393
  function ensureArchiveInit() {
8584
9394
  if (!archiveInitialized) {
8585
9395
  try {
8586
- configureArchiveStore({ archiveDir: join9(homedir7(), ".xbrowser", "archives") });
9396
+ configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
8587
9397
  } catch {
8588
9398
  }
8589
9399
  archiveInitialized = true;
@@ -8621,7 +9431,6 @@ function streamCommandEvent(sessionId, message) {
8621
9431
  // src/executor/chain.ts
8622
9432
  import {
8623
9433
  fail as fail18,
8624
- ok as ok32,
8625
9434
  TipCollector as TipCollector2,
8626
9435
  normalizeTips as normalizeTips7,
8627
9436
  unquote as unquote2
@@ -8866,7 +9675,34 @@ function parsePluginParams(args, schema, base = {}) {
8866
9675
  // src/executor/chain.ts
8867
9676
  async function executeChain(input, options, executeCommand2) {
8868
9677
  const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8869
- const sessionName = options?.sessionName || "default";
9678
+ let sessionName = options?.sessionName || "default";
9679
+ for (const pipeline of pipelines) {
9680
+ const cleaned = [];
9681
+ for (const step of pipeline.pipeline) {
9682
+ const tokens = splitCommand(step);
9683
+ let stripped = false;
9684
+ const kept = [];
9685
+ for (let i = 0; i < tokens.length; i++) {
9686
+ if (options?.fixedSession && (tokens[i] === "--session" || tokens[i].startsWith("--session="))) {
9687
+ throw new Error("Set the session on the run, outside the command chain");
9688
+ }
9689
+ if (tokens[i] === "--session" && i + 1 < tokens.length) {
9690
+ sessionName = tokens[i + 1];
9691
+ stripped = true;
9692
+ i++;
9693
+ continue;
9694
+ }
9695
+ if (tokens[i].startsWith("--session=")) {
9696
+ sessionName = tokens[i].slice("--session=".length);
9697
+ stripped = true;
9698
+ continue;
9699
+ }
9700
+ kept.push(tokens[i]);
9701
+ }
9702
+ cleaned.push(stripped ? kept.join(" ") : step);
9703
+ }
9704
+ pipeline.pipeline = cleaned;
9705
+ }
8870
9706
  const results = [];
8871
9707
  const totalStart = Date.now();
8872
9708
  let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
@@ -8893,6 +9729,14 @@ async function executeChain(input, options, executeCommand2) {
8893
9729
  if (parts.length === 0) continue;
8894
9730
  const cmdName = parts[0];
8895
9731
  const cmdArgs = parts.slice(1);
9732
+ if (options?.handoff && cmdName === "handoff" && cmdArgs.length === 0) {
9733
+ const started = Date.now();
9734
+ const solved = await options.handoff();
9735
+ const message = solved ? "Human handoff completed" : "Human handoff timed out";
9736
+ results.push({ command: cmdName, raw: cmdStr, success: solved, data: null, message, duration: Date.now() - started });
9737
+ if (!solved || type === "or") return stoppedChain(solved, results, totalStart, results.length, message);
9738
+ continue;
9739
+ }
8896
9740
  const loader = await getPluginLoader();
8897
9741
  const internalLoader = loader.getCore().loader;
8898
9742
  const resolvedName = loader.resolveSiteName(cmdName);
@@ -8987,6 +9831,38 @@ async function executePluginChainStep(context) {
8987
9831
  }
8988
9832
  }
8989
9833
  }
9834
+ const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
9835
+ if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
9836
+ const { forwardPluginExec } = await import("./daemon-client-BBPQWLUX.js");
9837
+ const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
9838
+ const startFwd = Date.now();
9839
+ const fwd = await forwardPluginExec(
9840
+ `${cmdName}.${subCommand}`,
9841
+ pluginParams,
9842
+ sessionName,
9843
+ void 0,
9844
+ userTimeout
9845
+ );
9846
+ if (fwd != null) {
9847
+ const fwdOk = fwd.success !== false;
9848
+ results.push({
9849
+ command: `${cmdName} ${subCommand}`,
9850
+ raw: cmdStr,
9851
+ success: fwdOk,
9852
+ data: fwd.data ?? null,
9853
+ message: fwd.message,
9854
+ tips: Array.isArray(fwd.tips) ? fwd.tips : void 0,
9855
+ duration: Date.now() - startFwd
9856
+ });
9857
+ if (type === "and" && !fwdOk) {
9858
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${fwd.message ?? ""}`);
9859
+ }
9860
+ if (type === "or" && fwdOk) {
9861
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9862
+ }
9863
+ return void 0;
9864
+ }
9865
+ }
8990
9866
  const pluginCtx = {
8991
9867
  args: pluginArgs,
8992
9868
  options: pluginParams,
@@ -9054,12 +9930,14 @@ async function executePluginChainStep(context) {
9054
9930
  }
9055
9931
  if (outputs.length > 0) hookOutputs = outputs;
9056
9932
  }
9057
- const data = raw?.data ?? raw;
9933
+ const success = raw?.success !== false;
9934
+ const data = raw?.data ?? (success ? raw : null);
9935
+ const message = success ? void 0 : raw.message ?? "Plugin command failed";
9058
9936
  recordArchive(session.id, sessionName, {
9059
9937
  step: results.length,
9060
9938
  command: `${cmdName} ${subCommand}`,
9061
9939
  params: pluginParams,
9062
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9940
+ result: { success, data, message, tips: tipsToMessages(raw?.tips) },
9063
9941
  toolCalls: [],
9064
9942
  duration,
9065
9943
  timestamp: start
@@ -9067,11 +9945,15 @@ async function executePluginChainStep(context) {
9067
9945
  results.push({
9068
9946
  command: `${cmdName} ${subCommand}`,
9069
9947
  raw: cmdStr,
9070
- ...ok32(data),
9948
+ success,
9949
+ data,
9950
+ message,
9951
+ tips: normalizeTips7(raw?.tips),
9071
9952
  duration,
9072
9953
  ...hookOutputs ? { hookOutputs } : {}
9073
9954
  });
9074
- if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9955
+ if (!success && type === "and") return stoppedChain(false, results, totalStart, results.length, message);
9956
+ if (success && type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9075
9957
  } catch (error) {
9076
9958
  const duration = Date.now() - start;
9077
9959
  const message = errMsg(error);
@@ -9178,7 +10060,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9178
10060
  }
9179
10061
  let targetPageOverride = null;
9180
10062
  if (_target && extraOpts?.cdpEndpoint) {
9181
- const { findTargetPage } = await import("./browser-GXL6V2JW.js");
10063
+ const { findTargetPage } = await import("./browser-NHQDQRXB.js");
9182
10064
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9183
10065
  if (!targetPageOverride) {
9184
10066
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -9186,6 +10068,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9186
10068
  params = { ...params, url: targetPageOverride.url };
9187
10069
  }
9188
10070
  if (command.parameters) {
10071
+ params = normalizeKebabParams(command.parameters, params);
9189
10072
  const result = command.parameters.safeParse(params);
9190
10073
  if (!result.success) {
9191
10074
  return errorResult(
@@ -9195,46 +10078,55 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9195
10078
  params = result.data;
9196
10079
  }
9197
10080
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
9198
- const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
10081
+ const { forwardExec } = await import("./daemon-client-BBPQWLUX.js");
9199
10082
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
9200
10083
  const result = await forwardExec(
9201
10084
  commandName,
9202
10085
  params,
9203
10086
  sessionName,
9204
10087
  extraOpts?.cdpEndpoint,
9205
- longRunning ? 20 * 6e4 : void 0
10088
+ longRunning ? 20 * 6e4 : void 0,
10089
+ extraOpts?.bridge
9206
10090
  );
9207
10091
  if (result) return result;
9208
10092
  }
9209
10093
  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;
10094
+ const bridgeSession = await findOrCreateBridgeSession(sessionName, {
10095
+ preferBridge: extraOpts?.bridge === true,
10096
+ url: params.url
10097
+ });
10098
+ if (bridgeSession) {
10099
+ session = bridgeSession;
10100
+ } else {
10101
+ const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
10102
+ if (existing) {
10103
+ session = existing;
10104
+ if (session.page) {
10105
+ try {
10106
+ await Promise.race([
10107
+ session.page.evaluate(() => true),
10108
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
10109
+ ]);
10110
+ } catch (err) {
10111
+ const msg = err instanceof Error ? err.message : String(err);
10112
+ if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
10113
+ await closeSessionByName(session.name);
10114
+ session = void 0;
10115
+ }
9224
10116
  }
9225
10117
  }
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
- });
10118
+ if (session && targetPageOverride && session.page) {
10119
+ const currentUrl = session.page.url();
10120
+ if (currentUrl !== targetPageOverride.url) {
10121
+ await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
10122
+ });
10123
+ }
9232
10124
  }
10125
+ } else if (command.scope !== "project") {
10126
+ session = await createSession(sessionName, params.url, {
10127
+ cdpEndpoint: extraOpts?.cdpEndpoint
10128
+ });
9233
10129
  }
9234
- } else if (command.scope !== "project") {
9235
- session = await createSession(sessionName, params.url, {
9236
- cdpEndpoint: extraOpts?.cdpEndpoint
9237
- });
9238
10130
  }
9239
10131
  const ctx = {
9240
10132
  page: session?.page,
@@ -9383,7 +10275,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9383
10275
  timestamp: start
9384
10276
  });
9385
10277
  if (isSuccess) {
9386
- return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
10278
+ return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9387
10279
  }
9388
10280
  const fc = classifyFailure(raw.message);
9389
10281
  return {
@@ -9406,7 +10298,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9406
10298
  duration,
9407
10299
  timestamp: start
9408
10300
  });
9409
- return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
10301
+ return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9410
10302
  } catch (err) {
9411
10303
  const end = Date.now();
9412
10304
  const duration = end - start;
@@ -9419,7 +10311,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9419
10311
  });
9420
10312
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
9421
10313
  try {
9422
- const { attemptRecovery } = await import("./recovery-JFGV3DBX.js");
10314
+ const { attemptRecovery } = await import("./recovery-TIBRFGRP.js");
9423
10315
  const recovery = await attemptRecovery(
9424
10316
  session.page,
9425
10317
  sessionName,
@@ -9473,7 +10365,10 @@ export {
9473
10365
  getCommand,
9474
10366
  getAllCommands,
9475
10367
  getCommandNames,
10368
+ splitOutsideQuotes,
9476
10369
  attachDetectAntiBot,
10370
+ asZodSchema,
10371
+ normalizeKebabParams,
9477
10372
  loadHooks,
9478
10373
  readJsonFile,
9479
10374
  PluginMetadataParser,