@xbrowser/cli 1.30.1 → 1.30.2

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.
@@ -2388,6 +2388,17 @@ var RuntimeEvaluationService = class {
2388
2388
  const mainId = tree.frameTree?.frame?.id;
2389
2389
  const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2390
2390
  if (target) {
2391
+ try {
2392
+ const world = await this.options.conn.send(
2393
+ "Page.createIsolatedWorld",
2394
+ { frameId: target.id, grantUniveralAccess: true, allowUniversalAccessFromFileURLs: true },
2395
+ this.options.sessionId
2396
+ );
2397
+ if (world?.executionContextId) {
2398
+ return await evalIn(this.options.sessionId, world.executionContextId);
2399
+ }
2400
+ } catch {
2401
+ }
2391
2402
  const contexts = [];
2392
2403
  const onCtx = (raw) => {
2393
2404
  const c = raw?.context;
@@ -2449,6 +2460,11 @@ var RuntimeEvaluationService = class {
2449
2460
  }
2450
2461
  throw new Error(`no OOPIF target for "${urlIncludes}"\uFF08\u7528 'xbrowser frames' \u67E5\u770B\u53EF\u89C1\u7684 iframe target\uFF1BOOPIF \u53EA\u5728 Target.getTargets \u91CC\u51FA\u73B0\uFF09`);
2451
2462
  }
2463
+ /** 完整 frame 树(递归含嵌套——同进程 iframe 祖先链构造用) */
2464
+ async frameTreeNodes() {
2465
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2466
+ return tree.frameTree;
2467
+ }
2452
2468
  /** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
2453
2469
  async listFrameTargets() {
2454
2470
  try {
@@ -2563,6 +2579,9 @@ var RuntimeEvaluationService = class {
2563
2579
  };
2564
2580
 
2565
2581
  // src/cdp-driver/page-frame-input.ts
2582
+ function isSameProcessError(err) {
2583
+ return /同进程/.test(String(err));
2584
+ }
2566
2585
  function isSessionDeadError(err) {
2567
2586
  return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
2568
2587
  }
@@ -2610,31 +2629,105 @@ var FrameInputService = class {
2610
2629
  }
2611
2630
  /** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
2612
2631
  async clickInFrame(urlIncludes, selector, opts = {}) {
2632
+ try {
2633
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2634
+ const x = rect.x + rect.width / 2;
2635
+ const y = rect.y + rect.height / 2;
2636
+ await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2637
+ return { x, y };
2638
+ } catch (err) {
2639
+ if (!isSameProcessError(err)) throw err;
2640
+ return this.clickInSameProcessFrame(urlIncludes, selector, opts);
2641
+ }
2642
+ }
2643
+ /**
2644
+ * 同进程跨源 iframe 点击(站点隔离按 eTLD+1 分组——qq.com 子域 iframe 同进程
2645
+ * 但跨源,DOM 进不去、也没有独立 target;输入派发到主 session,Input 事件按
2646
+ * hit-test 落进 iframe,isTrusted=true)。坐标 = 祖先 iframe 偏移累加 + 局部 rect。
2647
+ */
2648
+ async clickInSameProcessFrame(urlIncludes, selector, opts = {}) {
2649
+ this.cache.delete(urlIncludes);
2650
+ const { ox, oy } = await this.resolveFrameViewportOffset(urlIncludes);
2613
2651
  const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2614
- const x = rect.x + rect.width / 2;
2615
- const y = rect.y + rect.height / 2;
2616
- await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2652
+ const x = ox + rect.x + rect.width / 2;
2653
+ const y = oy + rect.y + rect.height / 2;
2654
+ await this.deps.pageMouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height });
2617
2655
  return { x, y };
2618
2656
  }
2657
+ /**
2658
+ * 目标帧在主页面视口中的偏移:沿 getFrameTree 祖先链逐帧查询
2659
+ * 「src 匹配子帧 URL 的 iframe 元素」的视口 rect 并累加(嵌套帧每层一次求值)。
2660
+ */
2661
+ async resolveFrameViewportOffset(urlIncludes) {
2662
+ const nodes = await this.deps.frameTreeNodes();
2663
+ const norm = (u) => (u || "").replace(/\/+$/, "");
2664
+ const findPath = (node, path2) => {
2665
+ const next = [...path2, node];
2666
+ if (norm(node.frame.url).includes(norm(urlIncludes))) return next;
2667
+ for (const child of node.childFrames ?? []) {
2668
+ const hit = findPath(child, next);
2669
+ if (hit) return hit;
2670
+ }
2671
+ return null;
2672
+ };
2673
+ const path = findPath(nodes, []);
2674
+ if (!path || path.length < 2) throw new Error(`no ancestor chain for frame "${urlIncludes}"`);
2675
+ let ox = 0;
2676
+ let oy = 0;
2677
+ for (let i = 0; i < path.length - 1; i++) {
2678
+ const parent = path[i];
2679
+ const child = path[i + 1];
2680
+ const isRoot = i === 0;
2681
+ const expr = `(function(){var u=${JSON.stringify(child.frame.url)};var hit=null;var ou='';try{ou=new URL(u).origin;}catch(e){}[...document.querySelectorAll('iframe')].forEach(function(f){if(hit)return;var s=f.src||'';if(!s)return;var os='';try{os=new URL(s).origin;}catch(e){}if(s.indexOf(u)>=0||u.indexOf(s)>=0||(ou&&os&&ou===os))hit=f;});if(!hit)return null;var r=hit.getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y});})()`;
2682
+ const raw = isRoot ? await this.deps.evaluateMain(expr) : await this.deps.evaluateInFrame(parent.frame.url, expr);
2683
+ if (!raw) throw new Error(`ancestor frame offset not found for "${child.frame.url.slice(0, 60)}"`);
2684
+ const off = JSON.parse(String(raw));
2685
+ ox += off.x;
2686
+ oy += off.y;
2687
+ }
2688
+ return { ox, oy };
2689
+ }
2619
2690
  /** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
2620
2691
  async fillInFrame(urlIncludes, selector, text, opts = {}) {
2621
2692
  try {
2622
2693
  return await this.fillInFrameInner(urlIncludes, selector, text, opts);
2623
2694
  } catch (err) {
2695
+ if (isSameProcessError(err)) return this.fillInSameProcessFrame(urlIncludes, selector, text, opts);
2624
2696
  if (!isSessionDeadError(err)) throw err;
2625
2697
  this.cache.delete(urlIncludes);
2626
2698
  return this.fillInFrameInner(urlIncludes, selector, text, opts);
2627
2699
  }
2628
2700
  }
2701
+ /** 同进程跨源 iframe 填写:主 session 点击聚焦 + insertText + frame 内回读 */
2702
+ async fillInSameProcessFrame(urlIncludes, selector, text, opts = {}) {
2703
+ const { ox, oy } = await this.resolveFrameViewportOffset(urlIncludes);
2704
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2705
+ const x = ox + rect.x + rect.width / 2;
2706
+ const y = oy + rect.y + rect.height / 2;
2707
+ await this.deps.pageMouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height });
2708
+ await this.deps.evaluateInFrame(
2709
+ urlIncludes,
2710
+ `(function(){var el=document.querySelector(${JSON.stringify(selector)});if(el&&typeof el.select==='function')el.select();return true;})()`
2711
+ );
2712
+ await this.deps.pageKeyboard.type(text, { delay: 18 });
2713
+ const readback = await this.deps.evaluateInFrame(
2714
+ urlIncludes,
2715
+ `(function(){var el=document.querySelector(${JSON.stringify(selector)});return el?String(el.value??''):'';})()`
2716
+ );
2717
+ return { value: readback ?? "" };
2718
+ }
2629
2719
  async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
2630
2720
  await this.clickInFrame(urlIncludes, selector, opts);
2631
2721
  const cached = this.cache.get(urlIncludes);
2632
- if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
2633
2722
  await this.deps.evaluateInFrame(
2634
2723
  urlIncludes,
2635
2724
  `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
2636
2725
  );
2637
- await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2726
+ if (cached) {
2727
+ await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2728
+ } else {
2729
+ await this.deps.pageKeyboard.type(text, { delay: 18 });
2730
+ }
2638
2731
  const readback = await this.deps.evaluateInFrame(
2639
2732
  urlIncludes,
2640
2733
  `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
@@ -2751,7 +2844,11 @@ var XBPageImpl = class _XBPageImpl {
2751
2844
  this.frameInputService = new FrameInputService({
2752
2845
  conn,
2753
2846
  resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
2754
- evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
2847
+ evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression),
2848
+ evaluateMain: (expression) => this.evaluate(expression),
2849
+ pageMouse: this.mouse,
2850
+ pageKeyboard: this.keyboard,
2851
+ frameTreeNodes: () => this.runtimeEvaluationService.frameTreeNodes()
2755
2852
  });
2756
2853
  this.domQueryService = new DomQueryService({
2757
2854
  conn,
@@ -2489,6 +2489,17 @@ var RuntimeEvaluationService = class {
2489
2489
  const mainId = tree.frameTree?.frame?.id;
2490
2490
  const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2491
2491
  if (target) {
2492
+ try {
2493
+ const world = await this.options.conn.send(
2494
+ "Page.createIsolatedWorld",
2495
+ { frameId: target.id, grantUniveralAccess: true, allowUniversalAccessFromFileURLs: true },
2496
+ this.options.sessionId
2497
+ );
2498
+ if (world?.executionContextId) {
2499
+ return await evalIn(this.options.sessionId, world.executionContextId);
2500
+ }
2501
+ } catch {
2502
+ }
2492
2503
  const contexts = [];
2493
2504
  const onCtx = (raw) => {
2494
2505
  const c = raw?.context;
@@ -2550,6 +2561,11 @@ var RuntimeEvaluationService = class {
2550
2561
  }
2551
2562
  throw new Error(`no OOPIF target for "${urlIncludes}"\uFF08\u7528 'xbrowser frames' \u67E5\u770B\u53EF\u89C1\u7684 iframe target\uFF1BOOPIF \u53EA\u5728 Target.getTargets \u91CC\u51FA\u73B0\uFF09`);
2552
2563
  }
2564
+ /** 完整 frame 树(递归含嵌套——同进程 iframe 祖先链构造用) */
2565
+ async frameTreeNodes() {
2566
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2567
+ return tree.frameTree;
2568
+ }
2553
2569
  /** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
2554
2570
  async listFrameTargets() {
2555
2571
  try {
@@ -2664,6 +2680,9 @@ var RuntimeEvaluationService = class {
2664
2680
  };
2665
2681
 
2666
2682
  // src/cdp-driver/page-frame-input.ts
2683
+ function isSameProcessError(err) {
2684
+ return /同进程/.test(String(err));
2685
+ }
2667
2686
  function isSessionDeadError(err) {
2668
2687
  return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
2669
2688
  }
@@ -2711,31 +2730,105 @@ var FrameInputService = class {
2711
2730
  }
2712
2731
  /** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
2713
2732
  async clickInFrame(urlIncludes, selector, opts = {}) {
2733
+ try {
2734
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2735
+ const x = rect.x + rect.width / 2;
2736
+ const y = rect.y + rect.height / 2;
2737
+ await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2738
+ return { x, y };
2739
+ } catch (err) {
2740
+ if (!isSameProcessError(err)) throw err;
2741
+ return this.clickInSameProcessFrame(urlIncludes, selector, opts);
2742
+ }
2743
+ }
2744
+ /**
2745
+ * 同进程跨源 iframe 点击(站点隔离按 eTLD+1 分组——qq.com 子域 iframe 同进程
2746
+ * 但跨源,DOM 进不去、也没有独立 target;输入派发到主 session,Input 事件按
2747
+ * hit-test 落进 iframe,isTrusted=true)。坐标 = 祖先 iframe 偏移累加 + 局部 rect。
2748
+ */
2749
+ async clickInSameProcessFrame(urlIncludes, selector, opts = {}) {
2750
+ this.cache.delete(urlIncludes);
2751
+ const { ox, oy } = await this.resolveFrameViewportOffset(urlIncludes);
2714
2752
  const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2715
- const x = rect.x + rect.width / 2;
2716
- const y = rect.y + rect.height / 2;
2717
- await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2753
+ const x = ox + rect.x + rect.width / 2;
2754
+ const y = oy + rect.y + rect.height / 2;
2755
+ await this.deps.pageMouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height });
2718
2756
  return { x, y };
2719
2757
  }
2758
+ /**
2759
+ * 目标帧在主页面视口中的偏移:沿 getFrameTree 祖先链逐帧查询
2760
+ * 「src 匹配子帧 URL 的 iframe 元素」的视口 rect 并累加(嵌套帧每层一次求值)。
2761
+ */
2762
+ async resolveFrameViewportOffset(urlIncludes) {
2763
+ const nodes = await this.deps.frameTreeNodes();
2764
+ const norm = (u) => (u || "").replace(/\/+$/, "");
2765
+ const findPath = (node, path2) => {
2766
+ const next = [...path2, node];
2767
+ if (norm(node.frame.url).includes(norm(urlIncludes))) return next;
2768
+ for (const child of node.childFrames ?? []) {
2769
+ const hit = findPath(child, next);
2770
+ if (hit) return hit;
2771
+ }
2772
+ return null;
2773
+ };
2774
+ const path = findPath(nodes, []);
2775
+ if (!path || path.length < 2) throw new Error(`no ancestor chain for frame "${urlIncludes}"`);
2776
+ let ox = 0;
2777
+ let oy = 0;
2778
+ for (let i = 0; i < path.length - 1; i++) {
2779
+ const parent = path[i];
2780
+ const child = path[i + 1];
2781
+ const isRoot = i === 0;
2782
+ const expr = `(function(){var u=${JSON.stringify(child.frame.url)};var hit=null;var ou='';try{ou=new URL(u).origin;}catch(e){}[...document.querySelectorAll('iframe')].forEach(function(f){if(hit)return;var s=f.src||'';if(!s)return;var os='';try{os=new URL(s).origin;}catch(e){}if(s.indexOf(u)>=0||u.indexOf(s)>=0||(ou&&os&&ou===os))hit=f;});if(!hit)return null;var r=hit.getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y});})()`;
2783
+ const raw = isRoot ? await this.deps.evaluateMain(expr) : await this.deps.evaluateInFrame(parent.frame.url, expr);
2784
+ if (!raw) throw new Error(`ancestor frame offset not found for "${child.frame.url.slice(0, 60)}"`);
2785
+ const off = JSON.parse(String(raw));
2786
+ ox += off.x;
2787
+ oy += off.y;
2788
+ }
2789
+ return { ox, oy };
2790
+ }
2720
2791
  /** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
2721
2792
  async fillInFrame(urlIncludes, selector, text, opts = {}) {
2722
2793
  try {
2723
2794
  return await this.fillInFrameInner(urlIncludes, selector, text, opts);
2724
2795
  } catch (err) {
2796
+ if (isSameProcessError(err)) return this.fillInSameProcessFrame(urlIncludes, selector, text, opts);
2725
2797
  if (!isSessionDeadError(err)) throw err;
2726
2798
  this.cache.delete(urlIncludes);
2727
2799
  return this.fillInFrameInner(urlIncludes, selector, text, opts);
2728
2800
  }
2729
2801
  }
2802
+ /** 同进程跨源 iframe 填写:主 session 点击聚焦 + insertText + frame 内回读 */
2803
+ async fillInSameProcessFrame(urlIncludes, selector, text, opts = {}) {
2804
+ const { ox, oy } = await this.resolveFrameViewportOffset(urlIncludes);
2805
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2806
+ const x = ox + rect.x + rect.width / 2;
2807
+ const y = oy + rect.y + rect.height / 2;
2808
+ await this.deps.pageMouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height });
2809
+ await this.deps.evaluateInFrame(
2810
+ urlIncludes,
2811
+ `(function(){var el=document.querySelector(${JSON.stringify(selector)});if(el&&typeof el.select==='function')el.select();return true;})()`
2812
+ );
2813
+ await this.deps.pageKeyboard.type(text, { delay: 18 });
2814
+ const readback = await this.deps.evaluateInFrame(
2815
+ urlIncludes,
2816
+ `(function(){var el=document.querySelector(${JSON.stringify(selector)});return el?String(el.value??''):'';})()`
2817
+ );
2818
+ return { value: readback ?? "" };
2819
+ }
2730
2820
  async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
2731
2821
  await this.clickInFrame(urlIncludes, selector, opts);
2732
2822
  const cached = this.cache.get(urlIncludes);
2733
- if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
2734
2823
  await this.deps.evaluateInFrame(
2735
2824
  urlIncludes,
2736
2825
  `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
2737
2826
  );
2738
- await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2827
+ if (cached) {
2828
+ await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2829
+ } else {
2830
+ await this.deps.pageKeyboard.type(text, { delay: 18 });
2831
+ }
2739
2832
  const readback = await this.deps.evaluateInFrame(
2740
2833
  urlIncludes,
2741
2834
  `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
@@ -2852,7 +2945,11 @@ var XBPageImpl = class _XBPageImpl {
2852
2945
  this.frameInputService = new FrameInputService({
2853
2946
  conn,
2854
2947
  resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
2855
- evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
2948
+ evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression),
2949
+ evaluateMain: (expression) => this.evaluate(expression),
2950
+ pageMouse: this.mouse,
2951
+ pageKeyboard: this.keyboard,
2952
+ frameTreeNodes: () => this.runtimeEvaluationService.frameTreeNodes()
2856
2953
  });
2857
2954
  this.domQueryService = new DomQueryService({
2858
2955
  conn,
@@ -9,7 +9,7 @@ import {
9
9
  resolveLaunchOpts,
10
10
  saveSessionDiskMeta,
11
11
  setActivePage
12
- } from "./chunk-BOZTIIBT.js";
12
+ } from "./chunk-BM6DDHA2.js";
13
13
  import {
14
14
  detectAntiBot,
15
15
  formatDetectionMessage
@@ -1846,11 +1846,11 @@ var preflightCommand = registerCommand({
1846
1846
  let pageUrl = null;
1847
1847
  try {
1848
1848
  const { fileURLToPath } = await import("url");
1849
- const { join: join10, dirname: dirname4 } = await import("path");
1849
+ const { join: join10, dirname: dirname5 } = await import("path");
1850
1850
  const { existsSync: existsSync8 } = await import("fs");
1851
1851
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1852
1852
  const candidates = [
1853
- join10(dirname4(here), "..", "assets", "preflight.html"),
1853
+ join10(dirname5(here), "..", "assets", "preflight.html"),
1854
1854
  join10(process.cwd(), "assets", "preflight.html")
1855
1855
  ];
1856
1856
  pageUrl = candidates.find((c) => existsSync8(c)) || null;
@@ -7586,7 +7586,7 @@ function setWSServerCache(browserContext, server) {
7586
7586
  import {
7587
7587
  Core
7588
7588
  } from "@dyyz1993/xcli-core";
7589
- import { resolve as resolve2, basename, dirname as dirname3 } from "path";
7589
+ import { resolve as resolve2, basename, dirname as dirname4 } from "path";
7590
7590
  import { existsSync as existsSync7, readdirSync } from "fs";
7591
7591
  import { homedir as homedir5 } from "os";
7592
7592
 
@@ -7885,9 +7885,9 @@ function patchLoginRequired() {
7885
7885
  }
7886
7886
 
7887
7887
  // src/lib/mistake-ledger.ts
7888
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
7888
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync6, appendFileSync } from "fs";
7889
7889
  import { homedir as homedir4 } from "os";
7890
- import { join as join7 } from "path";
7890
+ import { join as join7, dirname as dirname3 } from "path";
7891
7891
  var MISTAKE_THRESHOLD = 3;
7892
7892
  var MISTAKE_LEDGER_PATH = join7(
7893
7893
  homedir4(),
@@ -7919,6 +7919,56 @@ function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
7919
7919
  mkdirSync5(join7(path2, ".."), { recursive: true });
7920
7920
  writeFileSync6(path2, JSON.stringify(ledger, null, 2), "utf8");
7921
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
+ }
7922
7972
  function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
7923
7973
  if (!input.category) throw new Error("mistake category is required");
7924
7974
  if (!input.command) throw new Error("mistake command is required");
@@ -7947,10 +7997,9 @@ function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
7947
7997
  };
7948
7998
  ledger.entries[fingerprint] = entry;
7949
7999
  writeMistakeLedger(ledger, path2);
7950
- return {
7951
- entry,
7952
- newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
7953
- };
8000
+ const newlyConstrained = Boolean(previous && !previous.constrained && entry.constrained);
8001
+ if (newlyConstrained) graduateToMarkdown(entry);
8002
+ return { entry, newlyConstrained };
7954
8003
  }
7955
8004
 
7956
8005
  // src/plugin/loader.ts
@@ -8030,7 +8079,7 @@ var XBrowserPluginLoader = class {
8030
8079
  async loadPlugin(pluginPath, id) {
8031
8080
  const before = new Set(this.core.loader.getSites().map((s) => s.name));
8032
8081
  const instance = await this.loader.loadPlugin(pluginPath, id);
8033
- this.recordSiteAliases(basename(dirname3(pluginPath)), before);
8082
+ this.recordSiteAliases(basename(dirname4(pluginPath)), before);
8034
8083
  return instance;
8035
8084
  }
8036
8085
  async unloadPlugin(id) {
@@ -9446,7 +9495,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9446
9495
  }
9447
9496
  let targetPageOverride = null;
9448
9497
  if (_target && extraOpts?.cdpEndpoint) {
9449
- const { findTargetPage } = await import("./browser-6PFTHZI3.js");
9498
+ const { findTargetPage } = await import("./browser-JPTQ5JA2.js");
9450
9499
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9451
9500
  if (!targetPageOverride) {
9452
9501
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
package/dist/cli.js CHANGED
@@ -17,10 +17,11 @@ import {
17
17
  loadHooks,
18
18
  parsePluginParams,
19
19
  readJsonFile
20
- } from "./chunk-3K57RYVC.js";
20
+ } from "./chunk-G47VJ5OR.js";
21
21
  import "./chunk-JKVUFP3G.js";
22
22
  import {
23
23
  forwardCommandLog,
24
+ forwardExec,
24
25
  forwardNetworkAnalyze,
25
26
  forwardNetworkAround,
26
27
  forwardNetworkClear,
@@ -82,7 +83,7 @@ import {
82
83
  findSession,
83
84
  getAllSessions,
84
85
  saveSessionDiskMeta
85
- } from "./chunk-OSIDUT4H.js";
86
+ } from "./chunk-NBW3GGZB.js";
86
87
  import "./chunk-SMYSNO4M.js";
87
88
  import "./chunk-2KPI5GKP.js";
88
89
  import {
@@ -432,7 +433,8 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
432
433
  type: options.type,
433
434
  selector: options.selector || options.s,
434
435
  base64: !!options.base64,
435
- output: options.output || options.o || args[0]
436
+ // --path 与 --output 等价(docs 曾写 --path 被静默忽略——fresh-agent 冒烟摩擦点 1)
437
+ output: options.output || options.o || options.path || args[0]
436
438
  };
437
439
  break;
438
440
  case "ua": {
@@ -4961,13 +4963,16 @@ async function handleEvalScript(parts, argv) {
4961
4963
  const cdpEndpoint = extractCdpFromArgv(argv);
4962
4964
  const sessionName = extractSessionNameFromArgv(argv);
4963
4965
  const mode = argv.some((a) => a === "--json" || a.startsWith("--json=") || a === "-j") ? "json" : argv.some((a) => a === "--yaml" || a.startsWith("--yaml=")) ? "yaml" : "text";
4964
- if (parts[0] === "--script-b64" && parts[1]) {
4965
- const chainResult2 = await executeChain(`eval --script-b64 ${parts[1]}`, { cdpEndpoint, sessionName, frame: extractFrameFromArgv(argv) });
4966
+ const emit = (result, duration) => {
4966
4967
  if (mode === "json" || mode === "yaml") {
4967
- outputEnvelope({ success: chainResult2.success, data: chainResult2.steps[chainResult2.steps.length - 1]?.data ?? null, duration: chainResult2.totalDuration }, { command: "eval" }, mode);
4968
+ outputEnvelope({ success: result.success, data: result.data, message: result.message, duration }, { command: "eval" }, mode);
4968
4969
  } else {
4969
- printChainResult(chainResult2);
4970
+ printChainResult({ success: result.success, steps: [{ command: "eval", raw: "eval", success: result.success, data: result.data, duration }], totalDuration: duration });
4970
4971
  }
4972
+ };
4973
+ if (parts[0] === "--script-b64" && parts[1]) {
4974
+ const chainResult2 = await executeChain(`eval --script-b64 ${parts[1]}`, { cdpEndpoint, sessionName, frame: extractFrameFromArgv(argv) });
4975
+ emit({ success: chainResult2.success, data: chainResult2.steps[chainResult2.steps.length - 1]?.data ?? null, message: chainResult2.steps[chainResult2.steps.length - 1]?.message }, chainResult2.totalDuration);
4971
4976
  if (!chainResult2.success) throw new Error("Command failed");
4972
4977
  return;
4973
4978
  }
@@ -4993,13 +4998,18 @@ async function handleEvalScript(parts, argv) {
4993
4998
  throw new Error("Command failed");
4994
4999
  }
4995
5000
  const b64 = Buffer.from(script, "utf8").toString("base64url");
5001
+ const forwarded = await forwardExec("eval", {
5002
+ ...frame ? { frame } : {},
5003
+ "script-b64": b64
5004
+ }, sessionName, cdpEndpoint).catch(() => null);
5005
+ if (forwarded) {
5006
+ emit({ success: forwarded.success, data: forwarded.data, message: forwarded.message }, 0);
5007
+ if (!forwarded.success) throw new Error("Command failed");
5008
+ return;
5009
+ }
4996
5010
  const chain = frame ? `eval --frame ${frame} --script-b64 ${b64}` : `eval --script-b64 ${b64}`;
4997
5011
  const chainResult = await executeChain(chain, { cdpEndpoint, sessionName });
4998
- if (mode === "json" || mode === "yaml") {
4999
- outputEnvelope({ success: chainResult.success, data: chainResult.steps[chainResult.steps.length - 1]?.data ?? null, duration: chainResult.totalDuration }, { command: "eval" }, mode);
5000
- } else {
5001
- printChainResult(chainResult);
5002
- }
5012
+ emit({ success: chainResult.success, data: chainResult.steps[chainResult.steps.length - 1]?.data ?? null, message: chainResult.steps[chainResult.steps.length - 1]?.message }, chainResult.totalDuration);
5003
5013
  if (!chainResult.success) throw new Error("Command failed");
5004
5014
  }
5005
5015
  async function handleChainInput(input, argv) {
@@ -5813,7 +5823,7 @@ async function handleRemote(args, options, mode) {
5813
5823
  }
5814
5824
  }
5815
5825
  async function startMcpServer() {
5816
- const { startMcpStdio } = await import("./server-U3YAX5MJ.js");
5826
+ const { startMcpStdio } = await import("./server-QI3UIB4Y.js");
5817
5827
  startMcpStdio();
5818
5828
  }
5819
5829
 
@@ -6128,7 +6138,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6128
6138
  const targetPage = pages[cmdTabIndex];
6129
6139
  await targetPage.bringToFront().catch(() => {
6130
6140
  });
6131
- const { setActivePage } = await import("./browser-I2NLJN2A.js");
6141
+ const { setActivePage } = await import("./browser-CE4GTZRO.js");
6132
6142
  setActivePage(session, targetPage);
6133
6143
  }
6134
6144
  }
@@ -6386,7 +6396,7 @@ async function main() {
6386
6396
  const command = process.argv[2];
6387
6397
  const isLongRunning = command === "preview" || command === "serve" || command === "mcp";
6388
6398
  if (!isLongRunning) {
6389
- const { ensureProcessCanExit } = await import("./browser-I2NLJN2A.js");
6399
+ const { ensureProcessCanExit } = await import("./browser-CE4GTZRO.js");
6390
6400
  await ensureProcessCanExit().catch(() => {
6391
6401
  });
6392
6402
  process.exit(process.exitCode || exitCode);
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  getPluginLoader,
7
7
  recordMistake
8
- } from "./chunk-LM32MNBB.js";
8
+ } from "./chunk-3DC3Y5OE.js";
9
9
  import {
10
10
  version
11
11
  } from "./chunk-43TEMG4U.js";
@@ -39,10 +39,10 @@ import {
39
39
  resolveLaunchOpts,
40
40
  saveSessionDiskMeta,
41
41
  setActivePage
42
- } from "./chunk-NINETOM4.js";
42
+ } from "./chunk-JO6WHY3D.js";
43
43
  import {
44
44
  createRuleEngine
45
- } from "./chunk-OCECE22C.js";
45
+ } from "./chunk-NDBOLP5Z.js";
46
46
  import {
47
47
  queryJS
48
48
  } from "./chunk-A7NEA4PA.js";
@@ -8610,7 +8610,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8610
8610
  }
8611
8611
  let targetPageOverride = null;
8612
8612
  if (_target && extraOpts?.cdpEndpoint) {
8613
- const { findTargetPage } = await import("./browser-KOUA4ZDA.js");
8613
+ const { findTargetPage } = await import("./browser-F4X2ND5E.js");
8614
8614
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8615
8615
  if (!targetPageOverride) {
8616
8616
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -9799,9 +9799,9 @@ function createRPCHandler() {
9799
9799
  return result;
9800
9800
  }
9801
9801
  async function handlePluginsReload() {
9802
- const { resetPluginLoader } = await import("./plugin-singleton-A6RNITJW.js");
9802
+ const { resetPluginLoader } = await import("./plugin-singleton-TDBOCYOZ.js");
9803
9803
  resetPluginLoader();
9804
- const loader = await import("./plugin-singleton-A6RNITJW.js").then((m) => m.getPluginLoader());
9804
+ const loader = await import("./plugin-singleton-TDBOCYOZ.js").then((m) => m.getPluginLoader());
9805
9805
  const sites = loader.getCore().loader.getSites();
9806
9806
  return { ok: true, plugins: sites.length };
9807
9807
  }
@@ -10197,7 +10197,7 @@ function createRPCHandler() {
10197
10197
  if (isNewFormat) {
10198
10198
  try {
10199
10199
  const replayErrors = [];
10200
- const { SessionReplayer } = await import("./session-replayer-XLWQ47BB.js");
10200
+ const { SessionReplayer } = await import("./session-replayer-SUWCEU5L.js");
10201
10201
  const replayer = new SessionReplayer({
10202
10202
  page: session.page,
10203
10203
  stepDelay: slowMo * 500,