@xbrowser/cli 1.28.0 → 1.30.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 (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
@@ -20,171 +20,25 @@ import {
20
20
  resolveLaunchOpts,
21
21
  saveSessionDiskMeta,
22
22
  setActivePage
23
- } from "./chunk-HSYRAV3H.js";
23
+ } from "./chunk-OSIDUT4H.js";
24
24
  import {
25
25
  rand,
26
26
  sleep,
27
27
  wheelDelta
28
- } from "./chunk-R3F4K2SB.js";
28
+ } from "./chunk-SMYSNO4M.js";
29
29
  import {
30
30
  errMsg
31
31
  } from "./chunk-GDKLH7ZY.js";
32
32
 
33
- // src/fail-codes.ts
34
- var FAIL_CODES = {
35
- selectorNotFound: "RETRYABLE: selector-not-found",
36
- pageNotReady: "RETRYABLE: page-not-ready",
37
- elementGone: "RETRYABLE: element-gone",
38
- inputNotRetained: "RETRYABLE: input-not-retained",
39
- captcha: "HUMAN: captcha",
40
- loginWall: "HUMAN: login-wall",
41
- permissionDenied: "FATAL: permission-denied",
42
- targetGone: "FATAL: target-gone",
43
- unknown: "FATAL: unknown"
44
- };
45
- function classifyFailure(message) {
46
- const msg = (message || "").toLowerCase();
47
- const pick = (code) => ({
48
- code,
49
- level: code.split(":")[0],
50
- message: message || code
51
- });
52
- if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
53
- if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
54
- if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
55
- if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
56
- return pick(FAIL_CODES.selectorNotFound);
57
- if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
58
- if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
59
- if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
60
- return pick(FAIL_CODES.targetGone);
61
- return pick(FAIL_CODES.unknown);
62
- }
63
-
64
33
  // src/executor.ts
65
34
  import {
66
- ok as ok32,
67
- fail as fail17,
35
+ ok as ok33,
36
+ fail as fail19,
68
37
  isCommandResult,
69
- CompositeStorage as CompositeStorage2,
70
- TipCollector as TipCollector2,
71
- normalizeTips as normalizeTips7,
72
- configureArchiveStore,
73
- appendCommandToArchive,
74
- checkGuard,
75
- unquote as unquote2
38
+ normalizeTips as normalizeTips8,
39
+ TipCollector as TipCollector3
76
40
  } from "@dyyz1993/xcli-core";
77
41
 
78
- // src/utils/positional-params.ts
79
- import { unquote } from "@dyyz1993/xcli-core";
80
- function getTypeName(field) {
81
- return field?._def?.typeName;
82
- }
83
- function unwrapField(field) {
84
- const typeName = getTypeName(field);
85
- if (typeName === "ZodOptional" || typeName === "ZodDefault") {
86
- const innerType = field?._def?.innerType;
87
- return unwrapField(innerType);
88
- }
89
- return field;
90
- }
91
- function isOptionalNumber(field) {
92
- const typeName = getTypeName(field);
93
- return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
94
- }
95
- function coerceValue(raw, field) {
96
- const inner = unwrapField(field);
97
- const optionalNum = isOptionalNumber(field);
98
- const innerTypeName = getTypeName(inner);
99
- if (innerTypeName === "ZodString") {
100
- return { value: unquote(raw), skip: false };
101
- }
102
- if (innerTypeName === "ZodNumber") {
103
- const parsed = Number(raw);
104
- if (isNaN(parsed)) {
105
- if (optionalNum) return { value: void 0, skip: true };
106
- return { value: raw, skip: false };
107
- }
108
- return { value: parsed, skip: false };
109
- }
110
- if (innerTypeName === "ZodBoolean") {
111
- if (raw === "true" || raw === "1") return { value: true, skip: false };
112
- if (raw === "false" || raw === "0") return { value: false, skip: false };
113
- return { value: raw, skip: false };
114
- }
115
- return { value: unquote(raw), skip: false };
116
- }
117
- function mapPositionalValues(schema, positional, existing) {
118
- const result = { ...existing };
119
- if (!schema || typeof schema !== "object") return result;
120
- const shape = schema.shape;
121
- if (!shape || typeof shape !== "object") return result;
122
- const keys = Object.keys(shape);
123
- let pIdx = 0;
124
- for (const key of keys) {
125
- if (pIdx >= positional.length) break;
126
- if (result[key] !== void 0) {
127
- pIdx++;
128
- continue;
129
- }
130
- const field = shape[key];
131
- const raw = positional[pIdx];
132
- const { value, skip } = coerceValue(raw, field);
133
- if (skip) continue;
134
- result[key] = value;
135
- pIdx++;
136
- }
137
- return result;
138
- }
139
-
140
- // src/utils/plugin-params.ts
141
- function parsePluginParams(args, schema, base = {}) {
142
- const params = { ...base };
143
- const positionalValues = [];
144
- for (let i = 0; i < args.length; i++) {
145
- if (args[i] === "--" && args[i + 1]) {
146
- try {
147
- Object.assign(params, JSON.parse(args[i + 1]));
148
- } catch {
149
- }
150
- break;
151
- }
152
- if (args[i].startsWith("--")) {
153
- const key = args[i].slice(2);
154
- const value = args[i + 1];
155
- if (value && !value.startsWith("-")) {
156
- if (value === "true") params[key] = true;
157
- else if (value === "false") params[key] = false;
158
- else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
159
- else {
160
- try {
161
- const parsed = JSON.parse(value);
162
- if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
163
- params[key] = parsed;
164
- } else {
165
- params[key] = value;
166
- }
167
- } catch {
168
- params[key] = value;
169
- }
170
- }
171
- i++;
172
- } else {
173
- params[key] = true;
174
- }
175
- } else if (!args[i].startsWith("-")) {
176
- positionalValues.push(args[i]);
177
- }
178
- }
179
- Object.assign(params, mapPositionalValues(schema, positionalValues, params));
180
- const result = {};
181
- for (const [k, v] of Object.entries(params)) {
182
- const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
183
- result[camelKey] = v;
184
- }
185
- return result;
186
- }
187
-
188
42
  // src/utils/stub-context.ts
189
43
  import { join } from "path";
190
44
  import { homedir } from "os";
@@ -262,6 +116,7 @@ function registerCommand(def) {
262
116
  parameters: def.parameters,
263
117
  result: def.result,
264
118
  selectorParams: def.selectorParams,
119
+ examples: def.examples,
265
120
  handler: def.handler
266
121
  };
267
122
  registry.set(cmd.name, cmd);
@@ -496,14 +351,23 @@ var clickCommand = registerCommand({
496
351
  clickCount: z2.number().optional(),
497
352
  delay: z2.number().optional(),
498
353
  waitCaptcha: z2.boolean().optional().default(false).describe("\u70B9\u51FB\u540E\u68C0\u6D4B captcha \u5E76\u7B49\u5F85\u89E3\u51B3"),
499
- waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09")
354
+ waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09"),
355
+ frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u9009\u62E9\u5668\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u89E3\u6790\u5E76\u70B9\u51FB\uFF08\u8FDB\u7A0B\u9694\u79BB\u4E0B\u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09")
500
356
  }),
501
357
  result: z2.object({
502
358
  selector: z2.string(),
503
359
  newTab: z2.object({ url: z2.string(), title: z2.string() }).optional(),
504
- captcha: z2.any().optional()
360
+ captcha: z2.any().optional(),
361
+ frame: z2.string().optional(),
362
+ x: z2.number().optional(),
363
+ y: z2.number().optional()
505
364
  }),
506
365
  handler: async (p, ctx) => {
366
+ const frameTarget = p.frame ?? ctx.frame;
367
+ if (frameTarget) {
368
+ const { x, y } = await ctx.page.clickInFrame(frameTarget, p.selector);
369
+ return ok2({ selector: p.selector, frame: frameTarget, x, y });
370
+ }
507
371
  let detectedNewPage;
508
372
  let cleanup;
509
373
  if (ctx.browserContext?.on) {
@@ -594,15 +458,22 @@ var fillCommand = registerCommand({
594
458
  parameters: z2.object({
595
459
  selector: z2.string(),
596
460
  value: z2.string(),
597
- clear: z2.boolean().optional()
461
+ clear: z2.boolean().optional(),
462
+ frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u5185\u586B\u5165\uFF08\u805A\u7126\u70B9\u51FB + insertText + \u56DE\u8BFB\uFF09")
598
463
  }),
599
464
  result: z2.object({
600
465
  selector: z2.string(),
601
466
  value: z2.string(),
602
467
  cleared: z2.boolean(),
603
- reactMode: z2.boolean().optional()
468
+ reactMode: z2.boolean().optional(),
469
+ frame: z2.string().optional()
604
470
  }),
605
471
  handler: async (p, ctx) => {
472
+ const frameTarget = p.frame ?? ctx.frame;
473
+ if (frameTarget) {
474
+ const { value } = await ctx.page.fillInFrame(frameTarget, p.selector, p.value);
475
+ return ok2({ selector: p.selector, value, cleared: true, frame: frameTarget });
476
+ }
606
477
  const page = ctx.page;
607
478
  const shouldClear = p.clear !== false;
608
479
  if (shouldClear) {
@@ -789,15 +660,22 @@ var textCommand = registerCommand({
789
660
  scope: "page",
790
661
  selectorParams: ["selector"],
791
662
  parameters: z3.object({
792
- selector: z3.string().optional()
663
+ selector: z3.string().optional(),
664
+ frame: z3.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u8BFB\u53D6\u6587\u672C")
793
665
  }),
794
- result: z3.object({ text: z3.string() }),
666
+ result: z3.object({ text: z3.string(), frame: z3.string().optional() }),
795
667
  handler: async (p, ctx) => {
668
+ const frameTarget = p.frame ?? ctx.frame;
669
+ if (frameTarget) {
670
+ const expr = p.selector ? `(() => { const el = document.querySelector(${JSON.stringify(p.selector)}); return el ? (el.textContent ?? '').trim() : null; })()` : `(document.body?.innerText || '').trim()`;
671
+ const text2 = await ctx.page.evaluateInFrame(frameTarget, expr);
672
+ return ok3({ text: text2 || "", frame: frameTarget });
673
+ }
796
674
  if (p.selector) {
797
675
  const text2 = await ctx.page.textContent(p.selector);
798
676
  return ok3({ text: text2 || "" });
799
677
  }
800
- const text = await ctx.page.evaluate(() => document.body?.innerText || "");
678
+ const text = await ctx.page.evaluate(() => (document.body?.innerText || "").trim());
801
679
  return ok3({ text });
802
680
  }
803
681
  });
@@ -921,43 +799,64 @@ import { z as z6 } from "zod";
921
799
  import { ok as ok6 } from "@dyyz1993/xcli-core";
922
800
  var mouseCommand = registerCommand({
923
801
  name: "mouse",
924
- description: "Control the mouse (move, click, etc.)",
802
+ description: "Control the mouse (move, click, wheel, etc.) (--frame <url-substring> \u65F6\u5728\u8DE8\u57DF iframe \u5185\u64CD\u4F5C\uFF0C\u5750\u6807\u4E3A iframe \u5C40\u90E8\u5750\u6807)",
925
803
  scope: "page",
926
804
  parameters: z6.object({
927
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
805
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
928
806
  x: z6.coerce.number(),
929
807
  y: z6.coerce.number(),
808
+ "delta-x": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u6A2A\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u53F3\uFF09"),
809
+ "delta-y": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u7EB5\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u4E0B\uFF09"),
930
810
  button: z6.enum(["left", "right", "middle"]).optional(),
931
- steps: z6.coerce.number().optional()
811
+ steps: z6.coerce.number().optional(),
812
+ frame: z6.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u8F93\u5165\u6D3E\u53D1\u5230 iframe \u81EA\u5DF1\u7684 session\uFF08\u8DE8\u57DF iframe \u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09\uFF0C\u5750\u6807\u7528 iframe \u5C40\u90E8\u5750\u6807\u7CFB")
932
813
  }),
933
814
  result: z6.object({
934
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
815
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
935
816
  x: z6.number(),
936
817
  y: z6.number()
937
818
  }),
938
819
  handler: async (p, ctx) => {
939
820
  const button = p.button || "left";
940
- switch (p.action) {
941
- case "move":
942
- await ctx.page.mouse.move(p.x, p.y, { steps: p.steps || 1 });
943
- break;
944
- case "down":
945
- await ctx.page.mouse.move(p.x, p.y);
946
- await ctx.page.mouse.down({ button });
947
- break;
948
- case "up":
949
- await ctx.page.mouse.move(p.x, p.y);
950
- await ctx.page.mouse.up({ button });
951
- break;
952
- case "click":
953
- await ctx.page.mouse.click(p.x, p.y, { button });
954
- break;
955
- case "dblclick":
956
- await ctx.page.mouse.dblclick(p.x, p.y, { button });
957
- break;
958
- case "drag":
959
- await ctx.page.mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
960
- break;
821
+ const frame = p.frame ?? ctx.frame;
822
+ const dispatch = async (mouse) => {
823
+ switch (p.action) {
824
+ case "move":
825
+ await mouse.move(p.x, p.y, { steps: p.steps || 1 });
826
+ break;
827
+ case "down":
828
+ await mouse.move(p.x, p.y);
829
+ await mouse.down({ button });
830
+ break;
831
+ case "up":
832
+ await mouse.move(p.x, p.y);
833
+ await mouse.up({ button });
834
+ break;
835
+ case "click":
836
+ await mouse.click(p.x, p.y, { button });
837
+ break;
838
+ case "dblclick":
839
+ await mouse.dblclick(p.x, p.y, { button });
840
+ break;
841
+ case "drag":
842
+ await mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
843
+ break;
844
+ case "wheel":
845
+ await mouse.wheelAt(p.x, p.y, Number(p["delta-x"] ?? 0), Number(p["delta-y"] ?? 0));
846
+ break;
847
+ }
848
+ };
849
+ if (frame) {
850
+ try {
851
+ await ctx.page.runFrameMouse(frame, dispatch);
852
+ } catch (err) {
853
+ if (p.action === "drag" && /session/i.test(String(err))) {
854
+ throw new Error(`frame session \u5728\u62D6\u52A8\u4E2D\u5931\u6548\uFF08iframe \u53EF\u80FD\u5DF2\u91CD\u5EFA\uFF09\u2014\u2014\u91CD\u65B0\u7528 eval --frame \u8BFB\u53D6\u76EE\u6807\u5750\u6807\u540E\u518D\u62D6`);
855
+ }
856
+ throw err;
857
+ }
858
+ } else {
859
+ await dispatch(ctx.page.mouse);
961
860
  }
962
861
  return ok6({ action: p.action, x: p.x, y: p.y });
963
862
  }
@@ -1399,7 +1298,8 @@ var evaluateCommand = registerCommand({
1399
1298
  direction: "client\u2192browser"
1400
1299
  });
1401
1300
  engine.stop();
1402
- const result = p.frame ? await ctx.page.evaluateInFrame(p.frame, expression) : await ctx.page.evaluate(expression);
1301
+ const frame = p.frame ?? ctx.frame;
1302
+ const result = frame ? await ctx.page.evaluateInFrame(frame, expression) : await ctx.page.evaluate(expression);
1403
1303
  const response = ok9({ result });
1404
1304
  if (decision && decision.severity === "danger") {
1405
1305
  response.tips = normalizeTips2([`${decision.suggestion}`]);
@@ -1468,14 +1368,14 @@ var preflightCommand = registerCommand({
1468
1368
  let pageUrl = null;
1469
1369
  try {
1470
1370
  const { fileURLToPath } = await import("url");
1471
- const { join: join9, dirname: dirname4 } = await import("path");
1472
- const { existsSync: existsSync7 } = await import("fs");
1371
+ const { join: join10, dirname: dirname4 } = await import("path");
1372
+ const { existsSync: existsSync8 } = await import("fs");
1473
1373
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1474
1374
  const candidates = [
1475
- join9(dirname4(here), "..", "assets", "preflight.html"),
1476
- join9(process.cwd(), "assets", "preflight.html")
1375
+ join10(dirname4(here), "..", "assets", "preflight.html"),
1376
+ join10(process.cwd(), "assets", "preflight.html")
1477
1377
  ];
1478
- pageUrl = candidates.find((c) => existsSync7(c)) || null;
1378
+ pageUrl = candidates.find((c) => existsSync8(c)) || null;
1479
1379
  } catch {
1480
1380
  }
1481
1381
  if (pageUrl) {
@@ -1828,24 +1728,98 @@ import { z as z16 } from "zod";
1828
1728
  import { ok as ok16, fail as fail7 } from "@dyyz1993/xcli-core";
1829
1729
  var framesCommand = registerCommand({
1830
1730
  name: "frames",
1831
- description: "List all frames in the current page",
1731
+ description: "List all frames in the current page (\u542B\u8DE8\u57DF OOPIF\u2014\u2014\u5B83\u4EEC\u53EA\u5728\u6D4F\u89C8\u5668\u7EA7 target \u5217\u8868\u53EF\u89C1\uFF1B\u9644 parentUrl/depth \u5C42\u7EA7)",
1832
1732
  scope: "page",
1833
1733
  result: z16.object({
1834
1734
  frames: z16.array(z16.object({
1835
1735
  index: z16.number(),
1836
1736
  name: z16.string().nullable(),
1837
- url: z16.string()
1838
- }))
1737
+ url: z16.string(),
1738
+ oopif: z16.boolean().optional(),
1739
+ targetId: z16.string().optional(),
1740
+ parentUrl: z16.string().nullable().optional(),
1741
+ depth: z16.number().nullable().optional()
1742
+ })),
1743
+ warnings: z16.array(z16.string()).optional()
1839
1744
  }),
1840
1745
  handler: async (_p, ctx) => {
1841
1746
  const discover = ctx.page.discoverFrames;
1842
1747
  const rawFrames = discover ? await discover.call(ctx.page) : ctx.page.frames();
1748
+ const mainUrl = ctx.page.url();
1843
1749
  const frameList = rawFrames.map((frame, index) => ({
1844
1750
  index,
1845
1751
  name: frame.name(),
1846
- url: frame.url()
1752
+ url: frame.url(),
1753
+ parentUrl: null,
1754
+ depth: null
1847
1755
  }));
1848
- return ok16({ frames: frameList });
1756
+ const norm = (u) => u.replace(/\/+$/, "");
1757
+ for (const e of frameList) {
1758
+ if (norm(e.url) === norm(mainUrl)) {
1759
+ e.parentUrl = null;
1760
+ e.depth = 0;
1761
+ }
1762
+ }
1763
+ if (typeof ctx.page.listFrameTargets === "function") {
1764
+ const targets = await ctx.page.listFrameTargets();
1765
+ const knownUrls = new Set(frameList.map((f) => f.url));
1766
+ for (const t of targets) {
1767
+ if (knownUrls.has(t.url)) continue;
1768
+ frameList.push({ index: frameList.length, name: null, url: t.url, oopif: true, targetId: t.targetId, parentUrl: null, depth: null });
1769
+ }
1770
+ }
1771
+ const warnings = [];
1772
+ try {
1773
+ const CHILDREN = `JSON.stringify([...document.querySelectorAll('iframe')].map(f=>({src:f.src||'',name:f.name||''})))`;
1774
+ const matchChild = (childSrc, frameUrl) => {
1775
+ const a = norm(childSrc);
1776
+ const b = norm(frameUrl);
1777
+ return Boolean(a && b && (a === b || a.includes(b) || b.includes(a)));
1778
+ };
1779
+ const childrenCache = /* @__PURE__ */ new Map();
1780
+ const childrenOf = async (url) => {
1781
+ const hit = childrenCache.get(url);
1782
+ if (hit) return hit;
1783
+ let out = [];
1784
+ try {
1785
+ const raw = norm(url) === norm(mainUrl) ? await ctx.page.evaluate(CHILDREN) : await ctx.page.evaluateInFrame(url, CHILDREN);
1786
+ out = JSON.parse(String(raw || "[]"));
1787
+ } catch {
1788
+ }
1789
+ childrenCache.set(url, out);
1790
+ return out;
1791
+ };
1792
+ let frontier = frameList.filter((e) => e.depth === 0).map((e) => ({ url: e.url, depth: 0 }));
1793
+ for (let depth = 0; frontier.length > 0 && frameList.some((e) => e.depth === null) && depth < 6; depth++) {
1794
+ const next = [];
1795
+ for (const node of frontier) {
1796
+ const kids = await childrenOf(node.url);
1797
+ if (kids.length === 0) continue;
1798
+ for (const e of frameList) {
1799
+ if (e.depth !== null) continue;
1800
+ if (kids.some((k) => matchChild(k.src, e.url))) {
1801
+ e.parentUrl = node.url;
1802
+ e.depth = node.depth + 1;
1803
+ next.push({ url: e.url, depth: e.depth });
1804
+ }
1805
+ }
1806
+ }
1807
+ frontier = next;
1808
+ }
1809
+ } catch {
1810
+ }
1811
+ const urls = frameList.map((e) => e.url);
1812
+ for (let i = 0; i < urls.length; i++) {
1813
+ for (let j = i + 1; j < urls.length; j++) {
1814
+ const a = urls[i];
1815
+ const b = urls[j];
1816
+ if (a && b && (a.includes(b) || b.includes(a))) {
1817
+ const shorter = a.includes(b) ? b : a;
1818
+ warnings.push(`URL \u5B50\u4E32\u6B67\u4E49\uFF1A"${shorter}" \u540C\u65F6\u547D\u4E2D ${a} \u548C ${b}\u2014\u2014--frame \u8BF7\u5199\u66F4\u957F/\u66F4\u7CBE\u786E\u7684\u5B50\u4E32`);
1819
+ }
1820
+ }
1821
+ }
1822
+ return ok16({ frames: frameList, warnings });
1849
1823
  }
1850
1824
  });
1851
1825
  var frameCommand = registerCommand({
@@ -3404,8 +3378,26 @@ async function detectSpaRoutes(page, origin) {
3404
3378
  }
3405
3379
  } catch {
3406
3380
  }
3381
+ try {
3382
+ const vueRoutes = await page.evaluate((evalOrigin) => {
3383
+ const win = window;
3384
+ const vue3App = win.__vue_app__;
3385
+ const globalProperties = vue3App?.config?.globalProperties;
3386
+ let router = globalProperties?.$router;
3387
+ if (!router) {
3388
+ const root = document.querySelector("#app");
3389
+ const vm = root ? root.__vue__ : void 0;
3390
+ const rootVm = vm?.$root;
3391
+ router = vm?.$router ?? rootVm?.$router;
3392
+ }
3393
+ const routeList = router?.options?.routes ?? [];
3394
+ return routeList.filter((route) => route.path && route.path !== "/" && !route.path.includes(":") && !route.path.includes("*")).map((route) => `${evalOrigin.replace(/\/$/, "")}/#${route.path}`);
3395
+ }, origin);
3396
+ for (const route of vueRoutes) routeSet.add(route);
3397
+ } catch {
3398
+ }
3407
3399
  return Array.from(routeSet).map(
3408
- (p) => `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3400
+ (p) => p.startsWith("http") ? p : `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3409
3401
  );
3410
3402
  }
3411
3403
  function parseRobotsTxt(text) {
@@ -3598,7 +3590,14 @@ var crawlCommand = registerCommand({
3598
3590
  results.push({ url: seedPage.url(), title, content });
3599
3591
  const firstLinks = await extractLinks(seedPage, startUrl.origin);
3600
3592
  if (options.enableSpa) {
3601
- const spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3593
+ let spaRoutes = [];
3594
+ try {
3595
+ spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3596
+ } catch (error) {
3597
+ const message = error instanceof Error ? error.message : String(error);
3598
+ process.stderr.write(`[SPA] Route detection failed: ${message}
3599
+ `);
3600
+ }
3602
3601
  for (const route of spaRoutes) {
3603
3602
  try {
3604
3603
  const absNorm = normalizeUrl(stripHashAnchorQuery(route));
@@ -4467,6 +4466,8 @@ var networkCommand = registerCommand({
4467
4466
 
4468
4467
  // src/commands/ai-search-engines.ts
4469
4468
  import { z as z24 } from "zod";
4469
+
4470
+ // src/commands/ai-engine-configs.ts
4470
4471
  var ENGINE_CONFIGS = {
4471
4472
  deepseek: {
4472
4473
  key: "deepseek",
@@ -4719,6 +4720,8 @@ var ENGINE_CONFIGS = {
4719
4720
  sendButtonSelector: "button.send-btn"
4720
4721
  }
4721
4722
  };
4723
+
4724
+ // src/commands/ai-search-engines.ts
4722
4725
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
4723
4726
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
4724
4727
 
@@ -4743,25 +4746,6 @@ function getRefTarget(sessionKey2, ref) {
4743
4746
  if (!session || !target) return null;
4744
4747
  return { screenHash: session.screenHash, target };
4745
4748
  }
4746
- function inheritStableRefs(key, rawTargets) {
4747
- const prev = sessions.get(key);
4748
- if (!prev || prev.targets.size === 0) {
4749
- return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
4750
- }
4751
- const bySelector = /* @__PURE__ */ new Map();
4752
- let maxId = 0;
4753
- for (const [ref, target] of prev.targets) {
4754
- bySelector.set(target.selector, ref);
4755
- const id = Number(ref.slice(1));
4756
- if (Number.isFinite(id) && id > maxId) maxId = id;
4757
- }
4758
- let next = maxId + 1;
4759
- return rawTargets.map((target) => {
4760
- const inherited = bySelector.get(target.selector);
4761
- if (inherited) return { ...target, ref: inherited };
4762
- return { ...target, ref: `e${next++}` };
4763
- });
4764
- }
4765
4749
 
4766
4750
  // src/utils/resolve-selector.ts
4767
4751
  function buildElementSelector(el) {
@@ -5324,14 +5308,6 @@ async function observePage(page, sessionId, options = {}) {
5324
5308
  const direct = el.getAttribute("aria-label") || el.getAttribute("placeholder") || el.getAttribute("title") || input.value || el.textContent || "";
5325
5309
  return direct.replace(/\s+/g, " ").trim().slice(0, 120);
5326
5310
  }
5327
- function actionsFor(role, editable) {
5328
- const actions = [];
5329
- if (editable) actions.push("fill", "type");
5330
- if (role === "combobox") actions.push("select");
5331
- if (role === "checkbox" || role === "radio") actions.push("check");
5332
- actions.push("click", "hover");
5333
- return Array.from(new Set(actions));
5334
- }
5335
5311
  const selector = [
5336
5312
  "a[href]",
5337
5313
  "button",
@@ -5342,7 +5318,14 @@ async function observePage(page, sessionId, options = {}) {
5342
5318
  "label",
5343
5319
  "[role]",
5344
5320
  "[tabindex]",
5345
- '[contenteditable="true"]'
5321
+ '[contenteditable="true"]',
5322
+ // 非标准可交互控件:内联事件属性(agent-browser 基于 aria tree 完全不覆盖这类)。
5323
+ // 仅抓 HTML 显式声明 onclick/onmousedown 等的元素;addEventListener 绑定的无法静态发现。
5324
+ "[onclick]",
5325
+ "[onmousedown]",
5326
+ "[onmouseup]",
5327
+ "[onmouseover]",
5328
+ "[onkeydown]"
5346
5329
  ].join(",");
5347
5330
  const candidates = Array.from(document.querySelectorAll(selector));
5348
5331
  const seen = /* @__PURE__ */ new Set();
@@ -5366,13 +5349,10 @@ async function observePage(page, sessionId, options = {}) {
5366
5349
  role,
5367
5350
  name: textName(el),
5368
5351
  tag,
5369
- visible,
5370
5352
  enabled,
5371
5353
  editable,
5372
5354
  ...checked !== void 0 ? { checked } : {},
5373
- ...editable && input.value ? { value: input.value.slice(0, 120) } : {},
5374
- ...visible ? { box: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) } } : {},
5375
- actions: actionsFor(role, editable)
5355
+ ...editable && input.value ? { value: input.value.slice(0, 120) } : {}
5376
5356
  });
5377
5357
  if (targets2.length >= limit) break;
5378
5358
  }
@@ -5386,13 +5366,15 @@ async function observePage(page, sessionId, options = {}) {
5386
5366
  { includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
5387
5367
  )
5388
5368
  ]);
5389
- const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
5369
+ const targets = raw.targets.map((target, index) => ({
5370
+ ref: `e${index + 1}`,
5371
+ ...target
5372
+ }));
5390
5373
  replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
5391
5374
  return {
5392
5375
  url: page.url(),
5393
5376
  title,
5394
5377
  screenHash: raw.screenHash,
5395
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5396
5378
  targets
5397
5379
  };
5398
5380
  }
@@ -5577,23 +5559,8 @@ async function waitForPage(page, input) {
5577
5559
  return { success: true, matched: "selector", timeout, elapsed: Date.now() - startedAt };
5578
5560
  }
5579
5561
  if (input.text) {
5580
- const textToFind = input.text;
5581
- const matched = await pollUntil(timeout, pollInterval, async () => {
5582
- return page.evaluate((text) => {
5583
- const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
5584
- while (walker.nextNode()) {
5585
- if (walker.currentNode.textContent?.includes(text)) return true;
5586
- }
5587
- return false;
5588
- }, textToFind);
5589
- });
5590
- return {
5591
- success: matched,
5592
- matched: "text",
5593
- timeout,
5594
- elapsed: Date.now() - startedAt,
5595
- ...matched ? {} : { message: `Timed out waiting for text: ${input.text}` }
5596
- };
5562
+ await page.getByText(input.text).first().waitFor({ state: "visible", timeout });
5563
+ return { success: true, matched: "text", timeout, elapsed: Date.now() - startedAt };
5597
5564
  }
5598
5565
  if (input.url) {
5599
5566
  const matched = await pollUntil(timeout, pollInterval, async () => matchUrlPattern(page.url(), input.url));
@@ -5649,20 +5616,48 @@ async function waitForPage(page, input) {
5649
5616
  // src/commands/snapshot.ts
5650
5617
  var snapshotCommand = registerCommand({
5651
5618
  name: "snapshot",
5652
- description: "Capture a quick page state snapshot \u2014 aria tree, visible text, or DOM summary",
5619
+ description: "Get page state: interactive @refs to operate (default); --type aria=page outline; --type text=content; --type dom=debug DOM",
5653
5620
  scope: "page",
5654
5621
  selectorParams: ["selector"],
5622
+ examples: [
5623
+ {
5624
+ cmd: "xbrowser snapshot",
5625
+ description: "I want to OPERATE the page \u2192 returns clickable/fillable @refs (use click @e1, fill @e2)",
5626
+ output: '@e1 [button] "Submit"\n@e2 [textbox editable] "Email"'
5627
+ },
5628
+ {
5629
+ cmd: "xbrowser snapshot --type aria",
5630
+ description: "I want the page OUTLINE/skeleton (nav, heading hierarchy, regions)",
5631
+ output: 'banner:\n navigation:\n link "Home"\nmain:\n heading "Welcome"'
5632
+ },
5633
+ {
5634
+ cmd: "xbrowser snapshot --type text",
5635
+ description: "I want the page TEXT CONTENT (extract body copy/information)",
5636
+ output: "Welcome\nPlease enter your email\nSubmit"
5637
+ },
5638
+ {
5639
+ cmd: "xbrowser snapshot --type dom",
5640
+ description: "I want to DEBUG the DOM (tag names, attributes, nesting)"
5641
+ },
5642
+ {
5643
+ cmd: "xbrowser snapshot --selectors",
5644
+ description: "I want to operate AND need stable CSS selectors (reuse across sessions)",
5645
+ output: "e1: #submit | e2: #email"
5646
+ }
5647
+ ],
5655
5648
  parameters: z25.object({
5656
- type: z25.enum(["aria", "text", "dom", "all"]).default("aria").describe("Snapshot type: aria (accessibility tree), text (visible text), dom (element summary), all (combined)"),
5657
- selector: z25.string().optional().describe("Scope to a specific element"),
5658
- depth: z25.number().optional().default(6).describe("Max depth for DOM/aria tree"),
5659
- interactive: z25.boolean().optional().default(false).describe("Return interactive agent refs only"),
5660
- interactiveOnly: z25.boolean().optional().default(false).describe("Alias for interactive"),
5661
- i: z25.boolean().optional().default(false).describe("Short alias for interactive"),
5662
- compact: z25.boolean().optional().default(false).describe("Include compact xbrowser style snapshot text"),
5663
- c: z25.boolean().optional().default(false).describe("Short alias for compact"),
5664
- selectors: z25.boolean().optional().default(false).describe("Include ref to CSS selector map"),
5665
- all: z25.boolean().optional().default(false).describe("Include hidden interactive targets when using interactive snapshot")
5649
+ type: z25.enum(["interactive", "aria", "text", "dom", "all"]).default("interactive").describe(
5650
+ "Choose by intent: interactive(default)=operate page, get @refs of clickable/fillable elements; aria=page outline (nav/headings/regions); text=page text content; dom=debug DOM tags/attrs; all=everything"
5651
+ ),
5652
+ selector: z25.string().optional().describe("\u9650\u5B9A\u5230\u67D0\u4E2A\u5143\u7D20\uFF08CSS \u9009\u62E9\u5668\uFF09\uFF0C\u53EA\u5FEB\u7167\u8BE5\u5B50\u6811"),
5653
+ depth: z25.number().optional().default(6).describe("aria/dom \u6811\u7684\u6700\u5927\u6DF1\u5EA6"),
5654
+ interactive: z25.boolean().optional().default(false).describe("\u5F3A\u5236 interactive \u6A21\u5F0F\uFF08\u7B49\u540C --type interactive\uFF0C\u517C\u5BB9 -i\uFF09"),
5655
+ interactiveOnly: z25.boolean().optional().default(false).describe("interactive \u7684\u522B\u540D"),
5656
+ i: z25.boolean().optional().default(false).describe("interactive \u7684\u77ED\u522B\u540D"),
5657
+ compact: z25.boolean().optional().default(false).describe("\u9644\u5E26\u7D27\u51D1\u6587\u672C\u5FEB\u7167\uFF08interactive \u6A21\u5F0F\u9ED8\u8BA4\u5DF2\u542B\uFF09"),
5658
+ c: z25.boolean().optional().default(false).describe("compact \u7684\u77ED\u522B\u540D"),
5659
+ selectors: z25.boolean().optional().describe("\u9644\u5E26 ref \u2192 CSS \u9009\u62E9\u5668\u6620\u5C04\uFF08\u9700\u8981\u7A33\u5B9A\u9009\u62E9\u5668\u65F6\u5F00\uFF09"),
5660
+ all: z25.boolean().optional().default(false).describe("interactive \u6A21\u5F0F\u4E0B\u8FDE\u9690\u85CF\u5143\u7D20\u4E00\u8D77\u91C7\u96C6\uFF08\u6CE8\u610F\uFF1A\u8FD9\u662F\u91C7\u96C6\u8303\u56F4\uFF0C\u4E0D\u662F --type all \u7684\u5408\u5E76\u5FEB\u7167\uFF09")
5666
5661
  }),
5667
5662
  result: z25.object({
5668
5663
  url: z25.string(),
@@ -5675,14 +5670,13 @@ var snapshotCommand = registerCommand({
5675
5670
  const page = ctx.page;
5676
5671
  const url = page.url();
5677
5672
  const title = await page.title().catch(() => "");
5678
- if (p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors) {
5673
+ const wantInteractive = p.type === "interactive" || p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors;
5674
+ if (wantInteractive) {
5679
5675
  const observation = await observePage(page, ctx.sessionId, {
5680
5676
  includeHidden: p.all
5681
5677
  });
5682
5678
  if (p.selectors) observation.selectors = buildSelectorMap(observation);
5683
- if (p.compact || p.c || p.interactive || p.interactiveOnly || p.i) {
5684
- observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5685
- }
5679
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5686
5680
  return ok24(observation, normalizeTips3([
5687
5681
  `refs refreshed for ${observation.targets.length} targets; use click @e1 or fill @e2 "text"`
5688
5682
  ]));
@@ -5702,14 +5696,20 @@ var snapshotCommand = registerCommand({
5702
5696
  return ok24({ url, title, dom });
5703
5697
  }
5704
5698
  if (p.type === "all") {
5705
- const [aria, text, dom] = await Promise.all([
5699
+ const [observation, aria, text, dom] = await Promise.all([
5700
+ observePage(page, ctx.sessionId, { includeHidden: p.all }),
5706
5701
  captureAriaSnapshot(page, p.selector, p.depth),
5707
5702
  captureTextSnapshot(page, p.selector),
5708
5703
  captureDomSnapshot(page, p.selector, p.depth ?? 6)
5709
5704
  ]);
5705
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5706
+ if (p.selectors) observation.selectors = buildSelectorMap(observation);
5710
5707
  const tips = await buildRefTips(page, aria);
5711
5708
  persistSemantics(url, aria);
5712
- return ok24({ url, title, aria, text, dom }, normalizeTips3(tips));
5709
+ return ok24({ ...observation, aria, text, dom }, normalizeTips3([
5710
+ ...tips,
5711
+ `${observation.targets.length} interactive targets + aria + text + dom combined`
5712
+ ]));
5713
5713
  }
5714
5714
  return fail11(`Unknown snapshot type: ${p.type}`);
5715
5715
  }
@@ -5738,16 +5738,29 @@ async function buildRefTips(page, aria) {
5738
5738
  }
5739
5739
  }
5740
5740
  async function captureAriaSnapshot(page, selector, _depth) {
5741
+ let raw;
5741
5742
  try {
5742
5743
  const locator = selector ? page.locator(selector).first() : page.locator("body");
5743
- return await locator.ariaSnapshot();
5744
+ raw = await locator.ariaSnapshot();
5744
5745
  } catch {
5745
5746
  try {
5746
- return await page.locator("body").ariaSnapshot();
5747
+ raw = await page.locator("body").ariaSnapshot();
5747
5748
  } catch {
5748
5749
  return "(aria snapshot not available)";
5749
5750
  }
5750
5751
  }
5752
+ return filterAriaNoise(raw);
5753
+ }
5754
+ function filterAriaNoise(raw) {
5755
+ return raw.split("\n").filter((line) => {
5756
+ const t = line.trim();
5757
+ if (!t) return false;
5758
+ if (t === "none:" || t.startsWith("none: ")) return false;
5759
+ if (t.includes("InlineTextBox")) return false;
5760
+ if (t.includes("ListMarker")) return false;
5761
+ if (/^[a-z]+$/.test(t) || /^[a-z]+:$/.test(t)) return false;
5762
+ return true;
5763
+ }).join("\n");
5751
5764
  }
5752
5765
  async function captureTextSnapshot(page, selector) {
5753
5766
  if (selector) {
@@ -5890,12 +5903,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
5890
5903
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
5891
5904
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
5892
5905
  {"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
5906
+ {"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
5893
5907
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
5894
5908
 
5895
5909
  \u89C4\u5219\uFF1A
5896
5910
  1. ref \u5FC5\u987B\u539F\u6837\u6765\u81EA\u672C\u6B21\u5143\u7D20\u6E05\u5355\uFF1B\u6E05\u5355\u91CC\u6CA1\u6709\u80FD\u63A8\u8FDB\u76EE\u6807\u7684\u5143\u7D20\u5C31\u8F93\u51FA blocked\u3002
5897
5911
  2. \u76EE\u6807\u5DF2\u5B8C\u6210\uFF08\u9875\u9762\u4E0A\u80FD\u786E\u8BA4\u7ED3\u679C\uFF09\u5C31\u8F93\u51FA done\uFF0Cvalue \u5199\u5B8C\u6210\u6458\u8981\u3002
5898
- 3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
5912
+ 3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u52A8\u4F5C\u540E\u9875\u9762\u8DF3\u5230\u4E86\u610F\u6599\u4E4B\u5916\u7684\u5730\u65B9\u5C31\u8F93\u51FA back \u8FD4\u56DE\u91CD\u8BD5\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
5899
5913
  function extractDecision(raw) {
5900
5914
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
5901
5915
  const start = s.indexOf("{");
@@ -5946,6 +5960,7 @@ var taskCommand = registerCommand({
5946
5960
  let status = "max_steps";
5947
5961
  let summary = "";
5948
5962
  let lastError = "";
5963
+ let emptyReplies = 0;
5949
5964
  for (let step = 1; step <= p.maxSteps; step++) {
5950
5965
  if (Date.now() - started > p.timeout) {
5951
5966
  status = "blocked";
@@ -5965,7 +5980,7 @@ ${history.slice(-6).join("\n")}` : ""
5965
5980
  ].filter(Boolean).join("\n");
5966
5981
  let raw = "";
5967
5982
  try {
5968
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5983
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5969
5984
 
5970
5985
  ---
5971
5986
 
@@ -5979,6 +5994,12 @@ ${userPayload}` }], 900);
5979
5994
  }
5980
5995
  const decision = extractDecision(raw);
5981
5996
  if (!decision || typeof decision.action !== "string") {
5997
+ if (!raw.trim() && emptyReplies < 2) {
5998
+ emptyReplies++;
5999
+ steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
6000
+ history.push(`step${step}: (empty reply, retrying)`);
6001
+ continue;
6002
+ }
5982
6003
  status = "blocked";
5983
6004
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
5984
6005
  break;
@@ -5993,6 +6014,13 @@ ${userPayload}` }], 900);
5993
6014
  steps.push({ step, thought, action: "done", ok: true, screenHash });
5994
6015
  break;
5995
6016
  }
6017
+ if (action === "back") {
6018
+ await ctx.page?.goBack?.().catch?.(() => {
6019
+ });
6020
+ steps.push({ step, thought, action: "back", ok: true, screenHash });
6021
+ history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
6022
+ continue;
6023
+ }
5996
6024
  if (action === "blocked") {
5997
6025
  status = "blocked";
5998
6026
  summary = value || thought || "LLM judged blocked";
@@ -6733,6 +6761,8 @@ var visualTagCommand = registerCommand({
6733
6761
  // src/commands/visual-tag-v2.ts
6734
6762
  import { z as z32 } from "zod";
6735
6763
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6764
+
6765
+ // src/commands/visual-tag-v2-script.ts
6736
6766
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6737
6767
  var TAG_V2_SCRIPT = `
6738
6768
  (function() {
@@ -7075,7 +7105,9 @@ var TAG_V2_SCRIPT = `
7075
7105
  return JSON.stringify(window.__xbTagStats);
7076
7106
  })()
7077
7107
  `;
7078
- var visualTagV2Command = registerCommand({
7108
+
7109
+ // src/commands/visual-tag-v2.ts
7110
+ registerCommand({
7079
7111
  name: "visual-tag-v2",
7080
7112
  description: "\u5206\u8272\u6807\u6CE8\u9875\u9762\u5143\u7D20\uFF08\u7EA2=\u53EF\u70B9\u51FB \u84DD=\u8F93\u5165 \u7EFF=\u56FE\u7247 \u9EC4=\u5217\u8868 \u7D2B=\u6570\u5B57 \u6A59=\u6587\u672C\uFF09",
7081
7113
  scope: "page",
@@ -7308,991 +7340,514 @@ function attachDetectAntiBot(ctx) {
7308
7340
  };
7309
7341
  }
7310
7342
 
7311
- // src/plugin/loader.ts
7312
- import {
7313
- Core
7314
- } from "@dyyz1993/xcli-core";
7315
- import { resolve as resolve2, basename, dirname as dirname3 } from "path";
7316
- import { existsSync as existsSync6, readdirSync } from "fs";
7317
- import { homedir as homedir5 } from "os";
7343
+ // src/tips/dom-watcher.ts
7344
+ var DOM_WATCHER_SCRIPT = `
7345
+ (function() {
7346
+ if (window.__xbrowserDomWatcher) return;
7347
+ window.__xbrowserDomWatcher = true;
7318
7348
 
7319
- // src/plugin/metadata-parser.ts
7320
- import { existsSync as existsSync4 } from "fs";
7321
- import { resolve } from "path";
7349
+ window.__xbrowserDetectedElements = [];
7322
7350
 
7323
- // src/utils/json-file.ts
7324
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
7325
- function readJsonFile(filePath, defaultValue) {
7326
- try {
7327
- const content = readFileSync5(filePath, "utf-8");
7328
- return JSON.parse(content);
7329
- } catch {
7330
- return defaultValue;
7331
- }
7332
- }
7333
-
7334
- // src/plugin/metadata-parser.ts
7335
- var PluginMetadataParser = class {
7336
- static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
7337
- static parseFromPackageJson(pluginPath) {
7338
- const packageJsonPath = resolve(pluginPath, "package.json");
7339
- if (!existsSync4(packageJsonPath)) {
7340
- return null;
7341
- }
7342
- const packageJson = readJsonFile(packageJsonPath, null);
7343
- if (!packageJson) return null;
7344
- if (!packageJson.xbrowser) {
7345
- return null;
7351
+ function getSelector(el) {
7352
+ if (el.id) return '#' + CSS.escape(el.id);
7353
+ if (el.getAttribute('aria-label')) {
7354
+ return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
7346
7355
  }
7347
- const xbrowser = packageJson.xbrowser;
7348
- const metadata = {
7349
- id: xbrowser.id || packageJson.name,
7350
- name: xbrowser.name || packageJson.name,
7351
- description: xbrowser.description || packageJson.description || "",
7352
- version: xbrowser.version || packageJson.version || "1.0.0",
7353
- author: xbrowser.author || this.extractAuthor(packageJson.author),
7354
- homepage: xbrowser.homepage || packageJson.homepage,
7355
- commands: xbrowser.commands,
7356
- sites: xbrowser.sites,
7357
- tags: xbrowser.tags,
7358
- screenshot: xbrowser.screenshot,
7359
- license: xbrowser.license || packageJson.license
7360
- };
7361
- return metadata;
7356
+ const cls = el.className && typeof el.className === 'string'
7357
+ ? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
7358
+ : '';
7359
+ if (cls) return el.tagName.toLowerCase() + '.' + cls;
7360
+ return el.tagName.toLowerCase();
7362
7361
  }
7363
- static isXBrowserPlugin(packageJson) {
7364
- if (packageJson.xbrowser) {
7365
- return true;
7362
+
7363
+ function isPopupLike(el) {
7364
+ const tag = el.tagName?.toLowerCase();
7365
+ if (tag === 'dialog') return true;
7366
+ if (tag === 'body' || tag === 'html') return false;
7367
+
7368
+ const role = el.getAttribute('role');
7369
+ if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
7370
+
7371
+ const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7372
+ const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
7373
+ if (popupPatterns.test(cls)) return true;
7374
+
7375
+ const style = window.getComputedStyle(el);
7376
+ if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
7377
+ const rect = el.getBoundingClientRect();
7378
+ if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
7366
7379
  }
7367
- const keywords = packageJson.keywords;
7368
- if (!keywords) return false;
7369
- return this.XBROWSER_KEYWORDS.some((kw) => keywords.includes(kw));
7380
+
7381
+ return false;
7370
7382
  }
7371
- static fromNPMResult(result) {
7372
- const author = typeof result.author === "string" ? result.author : result.author?.name || "Unknown";
7383
+
7384
+ function categorize(el) {
7385
+ const tag = el.tagName?.toLowerCase();
7386
+ const role = el.getAttribute('role');
7387
+ const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7388
+
7389
+ if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
7390
+ if (role === 'popover' || /popover/.test(cls)) return 'popover';
7391
+ if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
7392
+ if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
7393
+ if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
7394
+ if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
7395
+ if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
7396
+ return 'unknown';
7397
+ }
7398
+
7399
+ function extractElement(el) {
7400
+ const rect = el.getBoundingClientRect();
7401
+ const style = window.getComputedStyle(el);
7373
7402
  return {
7374
- id: result.name,
7375
- name: result.name.replace(/^xbrowser-plugin-/, "").replace(/^@[^/]+\//, ""),
7376
- description: result.description || "",
7377
- version: result.version,
7378
- author,
7379
- homepage: result.homepage || result.links?.homepage,
7380
- tags: result.keywords,
7381
- license: ""
7403
+ selector: getSelector(el),
7404
+ tag: el.tagName.toLowerCase(),
7405
+ role: el.getAttribute('role') || undefined,
7406
+ text: (el.textContent || '').trim().slice(0, 100) || undefined,
7407
+ ariaLabel: el.getAttribute('aria-label') || undefined,
7408
+ size: { width: Math.round(rect.width), height: Math.round(rect.height) },
7409
+ position: { x: Math.round(rect.x), y: Math.round(rect.y) },
7410
+ zIndex: parseInt(style.zIndex) || 0,
7411
+ category: categorize(el),
7382
7412
  };
7383
7413
  }
7384
- static extractAuthor(author) {
7385
- if (typeof author === "string") return author;
7386
- if (typeof author === "object" && author !== null) {
7387
- const authorObj = author;
7388
- return authorObj.name || "Unknown";
7389
- }
7390
- return "Unknown";
7391
- }
7392
- static validateMetadata(metadata) {
7393
- const errors = [];
7394
- if (!metadata.id) errors.push("id is required");
7395
- if (!metadata.name) errors.push("name is required");
7396
- if (!metadata.description) errors.push("description is required");
7397
- if (!metadata.version) errors.push("version is required");
7398
- return errors;
7414
+
7415
+ function scanAndReport() {
7416
+ const results = [];
7417
+ document.querySelectorAll('*').forEach(el => {
7418
+ if (isPopupLike(el)) results.push(extractElement(el));
7419
+ });
7420
+ window.__xbrowserDetectedElements = results;
7399
7421
  }
7400
- };
7401
7422
 
7402
- // src/plugin/ensure-deps.ts
7403
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
7404
- import { join as join7 } from "path";
7405
- import { execSync } from "child_process";
7406
- var SHARED_PLUGIN_DEPENDENCIES = {
7407
- "zod": "^3.24.0",
7408
- "@dyyz1993/xcli-core": "^0.19.0"
7409
- };
7410
- function ensurePluginDependencies(pluginsDir) {
7411
- const zodPath = join7(pluginsDir, "node_modules", "zod");
7412
- if (existsSync5(zodPath)) return;
7413
- mkdirSync4(pluginsDir, { recursive: true });
7414
- const pkgPath = join7(pluginsDir, "package.json");
7415
- let pkg = {};
7416
- if (existsSync5(pkgPath)) {
7423
+ window.__xbrowserScanOverlays = function() {
7424
+ scanAndReport();
7425
+ return window.__xbrowserDetectedElements;
7426
+ };
7427
+ })();
7428
+ `;
7429
+ var DomWatcher = class {
7430
+ page;
7431
+ injected = false;
7432
+ constructor(page) {
7433
+ this.page = page;
7434
+ }
7435
+ async inject() {
7436
+ if (this.injected) return;
7417
7437
  try {
7418
- pkg = readJsonFile(pkgPath, {});
7438
+ await this.page.evaluate(DOM_WATCHER_SCRIPT);
7439
+ await this.page.addInitScript(DOM_WATCHER_SCRIPT);
7440
+ this.injected = true;
7419
7441
  } catch {
7420
7442
  }
7421
7443
  }
7422
- const existingDeps = pkg.dependencies || {};
7423
- let needsInstall = false;
7424
- for (const [dep, version] of Object.entries(SHARED_PLUGIN_DEPENDENCIES)) {
7425
- if (!existingDeps[dep]) {
7426
- existingDeps[dep] = version;
7427
- needsInstall = true;
7444
+ async scanOverlays() {
7445
+ try {
7446
+ if (!this.injected) await this.inject();
7447
+ const result = await this.page.evaluate(
7448
+ "window.__xbrowserScanOverlays ? window.__xbrowserScanOverlays() : []"
7449
+ );
7450
+ return result || [];
7451
+ } catch {
7452
+ return [];
7428
7453
  }
7429
7454
  }
7430
- if (!needsInstall && existsSync5(join7(pluginsDir, "node_modules"))) return;
7431
- pkg.dependencies = existingDeps;
7432
- pkg.private = true;
7433
- pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
7434
- writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
7435
- try {
7436
- execSync("npm install --production --no-package-lock --no-fund --no-audit", {
7437
- cwd: pluginsDir,
7438
- stdio: "pipe",
7439
- timeout: 6e4,
7440
- env: { ...process.env, NODE_ENV: "production" }
7441
- });
7442
- } catch (err) {
7443
- console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
7455
+ };
7456
+ function classifyPriority(category, element) {
7457
+ if (category === "dialog" && element.text && /error|错误|fail|失败|denied|拒绝/i.test(element.text)) {
7458
+ return "p0";
7444
7459
  }
7460
+ if (category === "dialog" || category === "modal") return "p1";
7461
+ if (category === "popover" || category === "overlay") return "p2";
7462
+ if (category === "toast" || category === "notification") return "p2";
7463
+ if (category === "dropdown") return "p3";
7464
+ if (category === "tooltip") return "p3";
7465
+ return "p2";
7445
7466
  }
7446
7467
 
7447
- // src/plugin/contract.ts
7448
- import {
7449
- unwrapZod,
7450
- fieldsFromZodObjectReflected,
7451
- zodTypeToContractType
7452
- } from "@dyyz1993/xcli-core";
7453
- function buildPluginContract(site) {
7454
- const commands = site.getAllCommands().map((command) => buildCommandContract(site.getCommand?.(command.name) || command, {
7455
- siteRequiresLogin: site.config?.requiresLogin
7456
- }));
7457
- return {
7458
- version: 2,
7459
- plugin: {
7460
- name: site.name,
7461
- url: site.url,
7462
- description: site.config?.description,
7463
- requiresLogin: site.config?.requiresLogin
7464
- },
7465
- commands
7466
- };
7467
- }
7468
- function buildCommandContract(command, options = {}) {
7469
- const extension = command.xbrowser || {};
7470
- const inferredFields = fieldsFromZodObject(command.parameters);
7471
- const fields = mergeFields(inferredFields, extension.form?.fields || []);
7472
- const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
7473
- const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
7474
- const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
7475
- const outputSchema = command.result ? summarizeZod(command.result) : void 0;
7476
- return {
7477
- name: command.name,
7478
- description: command.description || "",
7479
- scope: command.scope || "project",
7480
- requiresLogin,
7481
- category: extension.category,
7482
- capabilities,
7483
- positional,
7484
- form: {
7485
- title: extension.form?.title || command.description || command.name,
7486
- description: extension.form?.description,
7487
- submitLabel: extension.form?.submitLabel || "Run",
7488
- fields
7489
- },
7490
- output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
7491
- };
7492
- }
7493
- function fieldsFromZodObject(schema) {
7494
- const reflected = fieldsFromZodObjectReflected(schema);
7495
- return reflected.map((field) => {
7496
- const widget = widgetFor(field.type, field.enum);
7497
- return {
7498
- name: field.name,
7499
- label: toLabel(field.name),
7500
- type: field.type,
7501
- widget,
7502
- required: field.required,
7503
- ...field.description ? { description: field.description } : {},
7504
- ...field.default !== void 0 ? { default: field.default } : {},
7505
- ...field.enum ? { enum: field.enum } : {},
7506
- ...field.type === "array" ? { multiple: true } : {}
7507
- };
7508
- });
7509
- }
7510
- function mergeFields(inferred, overrides) {
7511
- if (overrides.length === 0) return inferred;
7512
- const byName = new Map(inferred.map((field) => [field.name, field]));
7513
- const seen = /* @__PURE__ */ new Set();
7514
- const merged = [];
7515
- for (const override of overrides) {
7516
- if (!override.name) continue;
7517
- const base = byName.get(override.name) || {
7518
- name: override.name,
7519
- label: toLabel(override.name),
7520
- type: "string",
7521
- widget: "text",
7522
- required: false
7523
- };
7524
- merged.push({ ...base, ...override, name: override.name });
7525
- seen.add(override.name);
7526
- }
7527
- for (const field of inferred) {
7528
- if (!seen.has(field.name)) merged.push(field);
7529
- }
7530
- return merged;
7531
- }
7532
- function inferCapabilities(scope, requiresLogin) {
7533
- const caps = [];
7534
- if (scope === "page") caps.push("browser.page");
7535
- if (scope === "browser") caps.push("browser.context");
7536
- if (requiresLogin) caps.push("auth.login");
7537
- return caps;
7538
- }
7539
- function widgetFor(type, enumValues) {
7540
- if (enumValues) return "select";
7541
- if (type === "boolean") return "checkbox";
7542
- if (type === "number") return "number";
7543
- if (type === "array") return "multi-select";
7544
- if (type === "object") return "json";
7545
- return "text";
7546
- }
7547
- function summarizeZod(schema) {
7548
- const unwrapped = unwrapZod(schema);
7549
- if (unwrapped.typeName === "ZodArray") {
7550
- const def = unwrapped.schema?._def;
7551
- return {
7552
- type: "array",
7553
- items: summarizeZod(def?.type || def?.innerType)
7468
+ // src/tips/context-tracker.ts
7469
+ var ContextTracker = class {
7470
+ history = [];
7471
+ maxHistory = 20;
7472
+ record(commandName, params) {
7473
+ const entry = {
7474
+ commandName,
7475
+ params,
7476
+ timestamp: Date.now(),
7477
+ targetSelector: params.selector || params.url || void 0
7554
7478
  };
7479
+ this.history.push(entry);
7480
+ if (this.history.length > this.maxHistory) {
7481
+ this.history.shift();
7482
+ }
7555
7483
  }
7556
- const shape = getObjectShape(schema);
7557
- if (!shape) {
7558
- return {
7559
- type: zodTypeToContractType(unwrapped.typeName),
7560
- required: !unwrapped.optional,
7561
- ...unwrapped.description ? { description: unwrapped.description } : {}
7562
- };
7484
+ getLastCommand() {
7485
+ return this.history.length > 0 ? this.history[this.history.length - 1] : void 0;
7563
7486
  }
7564
- return Object.fromEntries(
7565
- Object.entries(shape).map(([name, field]) => {
7566
- const inner = unwrapZod(field);
7567
- return [name, {
7568
- type: zodTypeToContractType(inner.typeName),
7569
- required: !inner.optional,
7570
- ...inner.description ? { description: inner.description } : {}
7571
- }];
7572
- })
7573
- );
7574
- }
7575
- function getObjectShape(schema) {
7576
- const zod = schema;
7577
- const shapeOrFn = zod?.shape ?? zod?._def?.shape;
7578
- if (!shapeOrFn) return void 0;
7579
- return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
7580
- }
7581
- function toLabel(name) {
7582
- return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
7583
- }
7584
-
7585
- // src/plugin/login-required-patch.ts
7586
- import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
7587
- var patched = false;
7588
- function patchLoginRequired() {
7589
- if (patched) return;
7590
- patched = true;
7591
- const target = SiteInstanceImpl.prototype;
7592
- const originalCommand = target.command;
7593
- const wrapped = function(...args) {
7594
- const result = originalCommand.apply(this, args);
7595
- const [name, cmd] = args;
7596
- const loginRequired = cmd.loginRequired;
7597
- if (loginRequired) {
7598
- const commands = this.commands;
7599
- const entry = commands?.get(name);
7600
- if (entry) {
7601
- entry.loginRequired = loginRequired;
7487
+ getLastSelector() {
7488
+ for (let i = this.history.length - 1; i >= 0; i--) {
7489
+ if (this.history[i].targetSelector) {
7490
+ return this.history[i].targetSelector;
7602
7491
  }
7603
7492
  }
7604
- return result;
7605
- };
7606
- Object.defineProperty(target, "command", {
7607
- value: wrapped,
7608
- writable: true,
7609
- configurable: true
7610
- });
7611
- }
7612
-
7613
- // src/plugin/loader.ts
7614
- var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
7615
- var XBrowserPluginLoader = class {
7616
- core;
7617
- loader;
7618
- options;
7619
- /** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
7620
- dirSiteAliases = /* @__PURE__ */ new Map();
7621
- constructor(options) {
7622
- patchLoginRequired();
7623
- this.options = options ?? {};
7624
- const cwd = this.options.cwd || process.cwd();
7625
- const coreConfig = {
7626
- name: "xbrowser",
7627
- version: "0.1.0",
7628
- description: "Browser automation CLI",
7629
- configDirName: ".xbrowser",
7630
- envPrefix: "XBROWSER",
7631
- pluginDirs: [
7632
- ...DEFAULT_PLUGIN_DIRS,
7633
- resolve2(cwd, ".xcli/plugins")
7634
- ]
7635
- };
7636
- this.core = new Core(coreConfig);
7637
- this.loader = this.core.loader;
7638
- }
7639
- getAPI() {
7640
- return this.loader.getAPI();
7641
- }
7642
- /**
7643
- * Get the core instance for external use.
7644
- * @returns The xcli-core Core instance.
7645
- */
7646
- getCore() {
7647
- return this.core;
7648
- }
7649
- getPlugin(id) {
7650
- return this.loader.getPlugin(id);
7651
- }
7652
- getPluginStatus(id) {
7653
- return this.loader.getPluginStatus(id);
7654
- }
7655
- getLoadedPlugins() {
7656
- return this.loader.getLoadedPlugins();
7657
- }
7658
- /**
7659
- * 目录名别名兜底(小白用户实测踩坑):`plugin list` 显示目录名,但命令路由
7660
- * 按 site.name 匹配——两者不一致时(如目录 alibaba-1688、site 名 1688),
7661
- * 用户按 list 显示的名字敲命令会 "Unknown command"。映射在 scanAndLoad/
7662
- * loadPlugin 时通过加载前后 site 快照 diff 记录(instance.siteName 返回的是
7663
- * 插件 id 而非 site 名,不可用)。
7664
- */
7665
- resolveSiteName(name) {
7666
- if (this.core.loader.getSite(name)) return name;
7667
- const aliased = this.dirSiteAliases.get(name);
7668
- if (aliased && this.core.loader.getSite(aliased)) return aliased;
7669
7493
  return void 0;
7670
7494
  }
7671
- /** 记录一次插件加载引入的 site:加载前后快照 diff(同插件可注册多个 site) */
7672
- recordSiteAliases(pluginDirName, before) {
7673
- for (const site of this.core.loader.getSites()) {
7674
- if (!before.has(site.name)) this.dirSiteAliases.set(pluginDirName, site.name);
7495
+ isLikelyTriggered(selector) {
7496
+ const last = this.getLastCommand();
7497
+ if (!last) return false;
7498
+ const cmd = last.commandName.toLowerCase();
7499
+ const target = last.targetSelector?.toLowerCase() || "";
7500
+ if (["click", "dblclick", "hover", "tap"].includes(cmd)) {
7501
+ return selector === target || selector.startsWith(target.split(/[.\[#]/)[0]);
7502
+ }
7503
+ if (["fill", "type", "select", "check", "uncheck"].includes(cmd)) {
7504
+ return selector === target;
7675
7505
  }
7506
+ return false;
7676
7507
  }
7677
- getPluginContract(siteName, commandName) {
7678
- const resolved = this.resolveSiteName(siteName);
7679
- if (!resolved) return void 0;
7680
- const site = this.core.loader.getSite(resolved);
7681
- if (!site) return void 0;
7682
- const contract = buildPluginContract(site);
7683
- if (!commandName) return contract;
7684
- return contract.commands.find((command) => command.name === commandName);
7508
+ isRecentCommand(cmdName, withinMs = 2e3) {
7509
+ const last = this.getLastCommand();
7510
+ if (!last) return false;
7511
+ return last.commandName === cmdName && Date.now() - last.timestamp < withinMs;
7685
7512
  }
7686
- async loadPlugin(pluginPath, id) {
7687
- const before = new Set(this.core.loader.getSites().map((s) => s.name));
7688
- const instance = await this.loader.loadPlugin(pluginPath, id);
7689
- this.recordSiteAliases(basename(dirname3(pluginPath)), before);
7690
- return instance;
7513
+ clear() {
7514
+ this.history = [];
7691
7515
  }
7692
- async unloadPlugin(id) {
7693
- return this.loader.unloadPlugin(id);
7516
+ };
7517
+
7518
+ // src/tips/tip-generator.ts
7519
+ var SILENT_CATEGORIES = /* @__PURE__ */ new Set(["dropdown", "tooltip"]);
7520
+ var NOTIFICATION_CATEGORIES = /* @__PURE__ */ new Set(["toast", "notification"]);
7521
+ var TipGenerator = class {
7522
+ contextTracker;
7523
+ reportedSelectors = /* @__PURE__ */ new Map();
7524
+ dedupWindowMs = 3e4;
7525
+ constructor(contextTracker) {
7526
+ this.contextTracker = contextTracker;
7694
7527
  }
7695
- async reloadPlugin(id) {
7696
- return this.loader.reloadPlugin(id);
7528
+ diff(before, after, currentElements) {
7529
+ const beforeSet = new Set(before.overlaySelectors);
7530
+ const afterSet = new Set(after.overlaySelectors);
7531
+ const newSelectors = [];
7532
+ for (const sel of afterSet) {
7533
+ if (!beforeSet.has(sel)) newSelectors.push(sel);
7534
+ }
7535
+ if (newSelectors.length === 0) return [];
7536
+ return currentElements.filter((el) => newSelectors.includes(el.selector));
7697
7537
  }
7698
- async loadFromFunction(setup) {
7699
- return this.loader.loadFromFunction(setup);
7538
+ generate(newElements) {
7539
+ const tips = [];
7540
+ for (const el of newElements) {
7541
+ if (this.contextTracker.isLikelyTriggered(el.selector)) continue;
7542
+ if (SILENT_CATEGORIES.has(el.category)) continue;
7543
+ if (NOTIFICATION_CATEGORIES.has(el.category) && el.text && /success|成功|done|完成|saved|已保存/i.test(el.text)) {
7544
+ continue;
7545
+ }
7546
+ if (this.isRecentlyReported(el.selector)) continue;
7547
+ const priority = classifyPriority(el.category, el);
7548
+ if (priority === "p3") continue;
7549
+ const message = this.buildMessage(el);
7550
+ const suggestions = this.buildSuggestions(el);
7551
+ tips.push({
7552
+ priority,
7553
+ category: el.category,
7554
+ element: el,
7555
+ message,
7556
+ suggestions
7557
+ });
7558
+ this.reportedSelectors.set(el.selector, Date.now());
7559
+ }
7560
+ tips.sort((a, b) => {
7561
+ const order = { p0: 0, p1: 1, p2: 2 };
7562
+ return (order[a.priority] ?? 3) - (order[b.priority] ?? 3);
7563
+ });
7564
+ return tips;
7700
7565
  }
7701
- async scanAndLoad() {
7702
- const cwd = this.options.cwd || process.cwd();
7703
- const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
7704
- ensurePluginDependencies(globalDir);
7705
- const dirs = [
7706
- resolve2(cwd, ".xcli/plugins"),
7707
- resolve2(cwd, "../.xcli/plugins"),
7708
- this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
7709
- globalDir
7710
- ];
7711
- const loaded = [];
7712
- const seen = /* @__PURE__ */ new Set();
7713
- for (const dir of dirs) {
7714
- if (!existsSync6(dir)) continue;
7715
- const entries = readdirSync(dir, { withFileTypes: true });
7716
- for (const entry of entries) {
7717
- if (!entry.isDirectory()) continue;
7718
- if (seen.has(entry.name)) continue;
7719
- seen.add(entry.name);
7720
- const pluginDir = resolve2(dir, entry.name);
7721
- let indexPath = resolve2(pluginDir, "index.js");
7722
- if (!existsSync6(indexPath)) {
7723
- indexPath = resolve2(pluginDir, "index.ts");
7724
- }
7725
- if (!existsSync6(indexPath)) continue;
7726
- try {
7727
- if (!existsSync6(resolve2(pluginDir, "package.json"))) {
7728
- console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
7729
- } else {
7730
- const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
7731
- if (!metadata) {
7732
- console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
7733
- }
7734
- }
7735
- const instance = await this.loadPlugin(indexPath, entry.name);
7736
- loaded.push(instance);
7737
- } catch (err) {
7738
- const errMsg2 = err instanceof Error ? err.message : String(err);
7739
- console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
7740
- if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
7741
- console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
7742
- }
7743
- }
7744
- }
7566
+ buildMessage(el) {
7567
+ const label = el.ariaLabel || el.text?.slice(0, 40) || "";
7568
+ const labelStr = label ? ` "${label}"` : "";
7569
+ const sizeStr = `${el.size.width}x${el.size.height}`;
7570
+ const typeLabel = this.categoryLabel(el.category);
7571
+ return `\u68C0\u6D4B\u5230\u65B0${typeLabel}${labelStr} (${sizeStr})\uFF0C\u9009\u62E9\u5668: ${el.selector}`;
7572
+ }
7573
+ buildSuggestions(el) {
7574
+ const suggestions = [];
7575
+ if (el.category === "dialog" || el.category === "modal") {
7576
+ const confirmBtn = this.guessButtonSelector(el, ["confirm", "ok", "yes", "\u786E\u5B9A", "\u786E\u8BA4", "\u540C\u610F"]);
7577
+ const cancelBtn = this.guessButtonSelector(el, ["cancel", "close", "no", "\u53D6\u6D88", "\u5173\u95ED", "\u62D2\u7EDD"]);
7578
+ if (confirmBtn) suggestions.push(`click "${confirmBtn}"`);
7579
+ if (cancelBtn) suggestions.push(`click "${cancelBtn}"`);
7745
7580
  }
7746
- return loaded;
7581
+ if (el.category === "popover" || el.category === "overlay") {
7582
+ suggestions.push(`click "${el.selector}"`);
7583
+ }
7584
+ if (el.category === "toast" || el.category === "notification") {
7585
+ suggestions.push(`text "${el.selector}"`);
7586
+ }
7587
+ if (suggestions.length === 0) {
7588
+ suggestions.push(`click "${el.selector}"`);
7589
+ }
7590
+ return suggestions;
7747
7591
  }
7748
- async unload() {
7749
- return this.loader.unload();
7592
+ guessButtonSelector(el, keywords) {
7593
+ const base = el.selector;
7594
+ for (const kw of keywords) {
7595
+ return `${base} button:has-text("${kw}"), ${base} [role="button"]:has-text("${kw}")`;
7596
+ }
7597
+ return void 0;
7750
7598
  }
7751
- };
7752
-
7753
- // src/utils/plugin-singleton.ts
7754
- var pluginLoader = null;
7755
- var pluginsScanned = false;
7756
- function silenceSchemaWarnings(fn) {
7757
- if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
7758
- const originalWarn = console.warn;
7759
- console.warn = (...args) => {
7760
- const msg = typeof args[0] === "string" ? args[0] : "";
7761
- if (msg.includes('has no "result" schema')) return;
7762
- originalWarn(...args);
7763
- };
7764
- return fn().finally(() => {
7765
- console.warn = originalWarn;
7766
- });
7767
- }
7768
- async function getPluginLoader() {
7769
- if (!pluginLoader) {
7770
- pluginLoader = new XBrowserPluginLoader();
7599
+ categoryLabel(category) {
7600
+ const labels = {
7601
+ dialog: "Dialog",
7602
+ filechooser: "File Chooser",
7603
+ popup: "Popup",
7604
+ download: "Download",
7605
+ modal: "Modal",
7606
+ popover: "Popover",
7607
+ notification: "\u901A\u77E5",
7608
+ toast: "Toast",
7609
+ dropdown: "\u4E0B\u62C9\u83DC\u5355",
7610
+ tooltip: "Tooltip",
7611
+ overlay: "Overlay",
7612
+ unknown: "\u5F39\u7A97"
7613
+ };
7614
+ return labels[category] || "\u5F39\u7A97";
7771
7615
  }
7772
- if (!pluginsScanned) {
7773
- await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
7774
- pluginsScanned = true;
7616
+ isRecentlyReported(selector) {
7617
+ const lastTime = this.reportedSelectors.get(selector);
7618
+ if (!lastTime) return false;
7619
+ return Date.now() - lastTime < this.dedupWindowMs;
7775
7620
  }
7776
- return pluginLoader;
7621
+ resetDedup() {
7622
+ this.reportedSelectors.clear();
7623
+ }
7624
+ };
7625
+ function buildSnapshot(elements) {
7626
+ return {
7627
+ timestamp: Date.now(),
7628
+ overlaySelectors: elements.map((el) => el.selector)
7629
+ };
7777
7630
  }
7778
7631
 
7779
- // src/plugin/login-guard.ts
7780
- async function checkPluginLoginRequired(options) {
7781
- const { site, command, commandName, ctx, page, sessionName } = options;
7782
- if (commandName === "login" || commandName === "logout") return { ok: true };
7783
- const loginConfig = site.config?.loginConfig;
7784
- const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
7785
- if (!requiresLogin) return { ok: true };
7786
- const pluginName = site.name || "plugin";
7787
- const siteConfig = site.config;
7788
- const configIsLogin = siteConfig?.isLogin;
7789
- if (configIsLogin) {
7790
- try {
7791
- const loggedIn = await configIsLogin(ctx);
7792
- if (loggedIn) return { ok: true };
7793
- return buildLoginRequired({
7794
- plugin: pluginName,
7795
- command: commandName,
7796
- reason: "config.isLogin returned false",
7797
- sessionName,
7798
- loginConfig
7632
+ // src/tips/index.ts
7633
+ function tipsDebounceMs() {
7634
+ const v = parseInt(process.env.XBROWSER_TIPS_DEBOUNCE ?? "120", 10);
7635
+ return Number.isFinite(v) && v > 0 ? v : 0;
7636
+ }
7637
+ var SKIP_DETECT_COMMANDS = /* @__PURE__ */ new Set([
7638
+ "goto",
7639
+ // 导航命令不需要检测
7640
+ "screenshot",
7641
+ // 截图不需要检测
7642
+ "snapshot",
7643
+ // snapshot 不需要检测
7644
+ "get",
7645
+ // get 命令不需要检测
7646
+ "detect",
7647
+ // detect 命令本身不需要检测
7648
+ "history",
7649
+ // history 命令不需要检测
7650
+ "viewer"
7651
+ // viewer 命令不需要检测
7652
+ ]);
7653
+ var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
7654
+ "click",
7655
+ "fill",
7656
+ "type",
7657
+ "select",
7658
+ "check",
7659
+ "uncheck",
7660
+ "hover",
7661
+ "dblclick"
7662
+ ]);
7663
+ var TipsManager = class {
7664
+ domWatcher = null;
7665
+ contextTracker = new ContextTracker();
7666
+ generator = new TipGenerator(this.contextTracker);
7667
+ beforeSnapshot = null;
7668
+ lastDetectionTime = 0;
7669
+ // CDP 弹窗事件检测(filechooser / dialog / popup)
7670
+ detectedEvents = [];
7671
+ eventListenersAttached = false;
7672
+ lastCommandName = "";
7673
+ async beforeCommand(page, commandName, params) {
7674
+ this.contextTracker.record(commandName, params);
7675
+ this.lastCommandName = commandName;
7676
+ if (!this.eventListenersAttached && typeof page.on === "function") {
7677
+ this.eventListenersAttached = true;
7678
+ page.on("dialog", (dialog) => {
7679
+ const d = dialog;
7680
+ try {
7681
+ this.detectedEvents.push({
7682
+ type: "dialog",
7683
+ message: `[${d.type()}] ${d.message().slice(0, 200)}`,
7684
+ commandName: this.lastCommandName
7685
+ });
7686
+ } catch {
7687
+ }
7688
+ });
7689
+ page.on("filechooser", (chooser) => {
7690
+ const c = chooser;
7691
+ try {
7692
+ this.detectedEvents.push({
7693
+ type: "filechooser",
7694
+ message: `\u6587\u4EF6\u9009\u62E9\u5F39\u7A97${c.isMultiple ? "\uFF08\u591A\u9009\uFF09" : ""}\uFF1Aselector=${c.selector || "input[type=file]"}`,
7695
+ selector: c.selector,
7696
+ commandName: this.lastCommandName
7697
+ });
7698
+ } catch {
7699
+ }
7700
+ });
7701
+ page.on("popup", (info) => {
7702
+ const p = info;
7703
+ try {
7704
+ this.detectedEvents.push({
7705
+ type: "popup",
7706
+ message: `\u65B0\u7A97\u53E3\u5F39\u7A97\uFF1Aurl=${p.url || "(unknown)"}${p.windowName ? ` name=${p.windowName}` : ""}`,
7707
+ commandName: this.lastCommandName
7708
+ });
7709
+ } catch {
7710
+ }
7711
+ });
7712
+ page.on("download", (info) => {
7713
+ const d = info;
7714
+ try {
7715
+ const stateLabel = d.state === "completed" ? "\u5B8C\u6210" : d.state === "canceled" ? "\u53D6\u6D88" : "\u5F00\u59CB";
7716
+ this.detectedEvents.push({
7717
+ type: "download",
7718
+ message: `\u6587\u4EF6\u4E0B\u8F7D${stateLabel}\uFF1A${d.filename || "unknown"}${d.url ? ` (${d.url.slice(0, 80)})` : ""}`,
7719
+ commandName: this.lastCommandName
7720
+ });
7721
+ } catch {
7722
+ }
7799
7723
  });
7800
- } catch {
7801
7724
  }
7802
- }
7803
- if (typeof site.isLoggedIn === "function") {
7725
+ if (!this.domWatcher) {
7726
+ this.domWatcher = new DomWatcher(page);
7727
+ }
7804
7728
  try {
7805
- const loggedIn = await site.isLoggedIn(ctx);
7806
- if (loggedIn) return { ok: true };
7807
- return buildLoginRequired({
7808
- plugin: pluginName,
7809
- command: commandName,
7810
- reason: "plugin isLoggedIn returned false",
7811
- sessionName,
7812
- loginConfig
7813
- });
7729
+ await this.domWatcher.inject();
7730
+ const elements = await this.domWatcher.scanOverlays();
7731
+ this.beforeSnapshot = buildSnapshot(elements);
7814
7732
  } catch {
7733
+ this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
7734
+ }
7735
+ if (INTERACTION_COMMANDS.has(commandName) && !SKIP_DETECT_COMMANDS.has(commandName)) {
7736
+ await this.checkAntiBot(page, commandName);
7815
7737
  }
7816
7738
  }
7817
- if (page && loginConfig) {
7818
- const generic = await detectLoginFromPage(page, loginConfig);
7819
- if (generic === "logged-in") return { ok: true };
7820
- if (generic === "logged-out") {
7821
- return buildLoginRequired({
7822
- plugin: pluginName,
7823
- command: commandName,
7824
- reason: "generic loginConfig detected logged-out page",
7825
- sessionName,
7826
- loginConfig
7827
- });
7739
+ /**
7740
+ * 检测反机器人机制
7741
+ */
7742
+ async checkAntiBot(page, _commandName) {
7743
+ const now = Date.now();
7744
+ if (now - this.lastDetectionTime < 5e3) {
7745
+ return;
7746
+ }
7747
+ this.lastDetectionTime = now;
7748
+ const config = {
7749
+ checkCaptcha: true,
7750
+ checkWarning: true,
7751
+ checkBlocked: true,
7752
+ checkWebdriver: true
7753
+ };
7754
+ const result = await detectAntiBot(page, config);
7755
+ if (result.detected && result.severity === "high") {
7756
+ const message = formatDetectionMessage(result);
7757
+ console.error(`
7758
+ \u{1F6A8} ${message}
7759
+ `);
7760
+ console.log("\u{1F4A1} Action blocked. To continue:");
7761
+ console.log(" 1. Use viewer mode: xbrowser viewer --json");
7762
+ console.log(" 2. Or skip detection with --skip-detect flag\n");
7763
+ throw new Error(`Anti-bot detection blocked: ${result.message}`);
7828
7764
  }
7829
7765
  }
7830
- return { ok: true };
7831
- }
7832
- function buildLoginRequired(options) {
7833
- const viewerUrl = buildViewerUrl(options.sessionName);
7834
- const loginUrl = options.loginConfig?.loginUrl;
7835
- const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
7836
- const tips = [
7837
- message,
7838
- ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
7839
- ...loginUrl ? [`Login page: ${loginUrl}`] : [],
7840
- `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
7841
- ];
7842
- return {
7843
- ok: false,
7844
- data: {
7845
- code: "LOGIN_REQUIRED",
7846
- plugin: options.plugin,
7847
- command: options.command,
7848
- reason: options.reason,
7849
- ...viewerUrl ? { viewerUrl } : {},
7850
- ...loginUrl ? { loginUrl } : {}
7851
- },
7852
- message,
7853
- tips
7854
- };
7855
- }
7856
- async function detectLoginFromPage(page, config) {
7857
- const url = page.url();
7858
- if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
7859
- const result = await page.evaluate((cfg) => {
7860
- const visible = (selector) => {
7861
- try {
7862
- const el = document.querySelector(selector);
7863
- if (!el) return false;
7864
- const rect = el.getBoundingClientRect();
7865
- const style = window.getComputedStyle(el);
7866
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
7867
- } catch {
7868
- return false;
7869
- }
7870
- };
7871
- if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
7872
- if (cfg.loginSelectors?.some(visible)) return "logged-out";
7873
- const bodyText = document.body?.innerText || "";
7874
- const keywords = cfg.loginKeywords || [];
7875
- if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
7876
- return "logged-out";
7877
- }
7878
- return "unknown";
7879
- }, {
7880
- loginSelectors: config.loginSelectors || [],
7881
- loginKeywords: config.loginKeywords || [],
7882
- loggedInSelectors: config.loggedInSelectors || []
7883
- });
7884
- return result;
7885
- }
7886
-
7887
- // src/tips/dom-watcher.ts
7888
- var DOM_WATCHER_SCRIPT = `
7889
- (function() {
7890
- if (window.__xbrowserDomWatcher) return;
7891
- window.__xbrowserDomWatcher = true;
7892
-
7893
- window.__xbrowserDetectedElements = [];
7894
-
7895
- function getSelector(el) {
7896
- if (el.id) return '#' + CSS.escape(el.id);
7897
- if (el.getAttribute('aria-label')) {
7898
- return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
7766
+ async afterCommand() {
7767
+ if (!this.domWatcher || !this.beforeSnapshot) {
7768
+ const cdpTips = this.collectCdpEventTips();
7769
+ this.detectedEvents = [];
7770
+ return cdpTips;
7899
7771
  }
7900
- const cls = el.className && typeof el.className === 'string'
7901
- ? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
7902
- : '';
7903
- if (cls) return el.tagName.toLowerCase() + '.' + cls;
7904
- return el.tagName.toLowerCase();
7905
- }
7906
-
7907
- function isPopupLike(el) {
7908
- const tag = el.tagName?.toLowerCase();
7909
- if (tag === 'dialog') return true;
7910
- if (tag === 'body' || tag === 'html') return false;
7911
-
7912
- const role = el.getAttribute('role');
7913
- if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
7914
-
7915
- const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7916
- const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
7917
- if (popupPatterns.test(cls)) return true;
7918
-
7919
- const style = window.getComputedStyle(el);
7920
- if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
7921
- const rect = el.getBoundingClientRect();
7922
- if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
7772
+ await this.debounce();
7773
+ try {
7774
+ const currentElements = await this.domWatcher.scanOverlays();
7775
+ const afterSnapshot = buildSnapshot(currentElements);
7776
+ const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
7777
+ const tips = this.generator.generate(newElements);
7778
+ const cdpTips = this.collectCdpEventTips();
7779
+ tips.push(...cdpTips);
7780
+ this.beforeSnapshot = null;
7781
+ this.detectedEvents = [];
7782
+ return tips;
7783
+ } catch {
7784
+ const cdpTips = this.collectCdpEventTips();
7785
+ this.beforeSnapshot = null;
7786
+ this.detectedEvents = [];
7787
+ return cdpTips;
7923
7788
  }
7924
-
7925
- return false;
7926
- }
7927
-
7928
- function categorize(el) {
7929
- const tag = el.tagName?.toLowerCase();
7930
- const role = el.getAttribute('role');
7931
- const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7932
-
7933
- if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
7934
- if (role === 'popover' || /popover/.test(cls)) return 'popover';
7935
- if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
7936
- if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
7937
- if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
7938
- if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
7939
- if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
7940
- return 'unknown';
7941
- }
7942
-
7943
- function extractElement(el) {
7944
- const rect = el.getBoundingClientRect();
7945
- const style = window.getComputedStyle(el);
7946
- return {
7947
- selector: getSelector(el),
7948
- tag: el.tagName.toLowerCase(),
7949
- role: el.getAttribute('role') || undefined,
7950
- text: (el.textContent || '').trim().slice(0, 100) || undefined,
7951
- ariaLabel: el.getAttribute('aria-label') || undefined,
7952
- size: { width: Math.round(rect.width), height: Math.round(rect.height) },
7953
- position: { x: Math.round(rect.x), y: Math.round(rect.y) },
7954
- zIndex: parseInt(style.zIndex) || 0,
7955
- category: categorize(el),
7956
- };
7957
7789
  }
7958
-
7959
- function scanAndReport() {
7960
- const results = [];
7961
- document.querySelectorAll('*').forEach(el => {
7962
- if (isPopupLike(el)) results.push(extractElement(el));
7790
+ /**
7791
+ * 把检测到的 CDP 弹窗事件转成 SmartTip
7792
+ * 包括:dialog(alert/confirm/prompt)、filechooser(文件选择弹窗)、popup(新窗口)
7793
+ */
7794
+ collectCdpEventTips() {
7795
+ if (this.detectedEvents.length === 0) return [];
7796
+ return this.detectedEvents.map((evt) => {
7797
+ const suggestions = [];
7798
+ if (evt.type === "dialog") {
7799
+ suggestions.push("\u6B64\u5F39\u7A97\u53EF\u80FD\u963B\u585E\u540E\u7EED\u64CD\u4F5C");
7800
+ suggestions.push('\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 page.on("dialog") \u62E6\u622A');
7801
+ } else if (evt.type === "filechooser") {
7802
+ suggestions.push("\u6B64\u5F39\u7A97\u7531\u9875\u9762\u64CD\u4F5C\u89E6\u53D1\uFF08\u5982\u70B9\u51FB\u4E0A\u4F20\u6309\u94AE\uFF09");
7803
+ suggestions.push("\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 --path/--paths \u53C2\u6570\u4E0A\u4F20\u6587\u4EF6");
7804
+ } else if (evt.type === "popup") {
7805
+ suggestions.push("\u9875\u9762\u5C1D\u8BD5\u6253\u5F00\u65B0\u7A97\u53E3\uFF08\u53EF\u80FD\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF09");
7806
+ suggestions.push('\u5982\u9700\u5904\u7406\uFF1A\u68C0\u67E5\u5F39\u7A97\u62E6\u622A\u8BBE\u7F6E\u6216\u4F7F\u7528 page.on("popup") \u76D1\u542C');
7807
+ } else if (evt.type === "download") {
7808
+ suggestions.push("\u9875\u9762\u89E6\u53D1\u4E86\u6587\u4EF6\u4E0B\u8F7D");
7809
+ suggestions.push("\u5982\u9700\u63A7\u5236\u8DEF\u5F84\uFF1Apage.setDownloadBehavior(path)");
7810
+ }
7811
+ return {
7812
+ category: evt.type,
7813
+ priority: "p1",
7814
+ message: `\u{1F514} [\u5F39\u7A97\u68C0\u6D4B] ${evt.message}\uFF08\u89E6\u53D1\u547D\u4EE4: ${evt.commandName || "\u672A\u77E5"}\uFF09`,
7815
+ selector: evt.selector,
7816
+ suggestions
7817
+ };
7963
7818
  });
7964
- window.__xbrowserDetectedElements = results;
7965
7819
  }
7966
-
7967
- window.__xbrowserScanOverlays = function() {
7968
- scanAndReport();
7969
- return window.__xbrowserDetectedElements;
7970
- };
7971
- })();
7972
- `;
7973
- var DomWatcher = class {
7974
- page;
7975
- injected = false;
7976
- constructor(page) {
7977
- this.page = page;
7820
+ debounce() {
7821
+ const ms = tipsDebounceMs();
7822
+ if (ms <= 0) return Promise.resolve();
7823
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
7978
7824
  }
7979
- async inject() {
7980
- if (this.injected) return;
7981
- try {
7982
- await this.page.evaluate(DOM_WATCHER_SCRIPT);
7983
- await this.page.addInitScript(DOM_WATCHER_SCRIPT);
7984
- this.injected = true;
7985
- } catch {
7986
- }
7825
+ formatTips(tips) {
7826
+ return tips.map((tip) => {
7827
+ const lines = [tip.message];
7828
+ for (const s of tip.suggestions) {
7829
+ lines.push(` \u2192 ${s}`);
7830
+ }
7831
+ return lines.join("\n");
7832
+ });
7987
7833
  }
7988
- async scanOverlays() {
7989
- try {
7990
- if (!this.injected) await this.inject();
7991
- const result = await this.page.evaluate(
7992
- "window.__xbrowserScanOverlays ? window.__xbrowserScanOverlays() : []"
7993
- );
7994
- return result || [];
7995
- } catch {
7996
- return [];
7997
- }
7834
+ reset() {
7835
+ this.beforeSnapshot = null;
7836
+ this.generator.resetDedup();
7837
+ this.contextTracker.clear();
7838
+ this.domWatcher = null;
7839
+ this.lastDetectionTime = 0;
7840
+ this.detectedEvents = [];
7841
+ this.eventListenersAttached = false;
7842
+ this.lastCommandName = "";
7998
7843
  }
7999
7844
  };
8000
- function classifyPriority(category, element) {
8001
- if (category === "dialog" && element.text && /error|错误|fail|失败|denied|拒绝/i.test(element.text)) {
8002
- return "p0";
7845
+ var globalTipsManager = null;
7846
+ function getTipsManager() {
7847
+ if (!globalTipsManager) {
7848
+ globalTipsManager = new TipsManager();
8003
7849
  }
8004
- if (category === "dialog" || category === "modal") return "p1";
8005
- if (category === "popover" || category === "overlay") return "p2";
8006
- if (category === "toast" || category === "notification") return "p2";
8007
- if (category === "dropdown") return "p3";
8008
- if (category === "tooltip") return "p3";
8009
- return "p2";
8010
- }
8011
-
8012
- // src/tips/context-tracker.ts
8013
- var ContextTracker = class {
8014
- history = [];
8015
- maxHistory = 20;
8016
- record(commandName, params) {
8017
- const entry = {
8018
- commandName,
8019
- params,
8020
- timestamp: Date.now(),
8021
- targetSelector: params.selector || params.url || void 0
8022
- };
8023
- this.history.push(entry);
8024
- if (this.history.length > this.maxHistory) {
8025
- this.history.shift();
8026
- }
8027
- }
8028
- getLastCommand() {
8029
- return this.history.length > 0 ? this.history[this.history.length - 1] : void 0;
8030
- }
8031
- getLastSelector() {
8032
- for (let i = this.history.length - 1; i >= 0; i--) {
8033
- if (this.history[i].targetSelector) {
8034
- return this.history[i].targetSelector;
8035
- }
8036
- }
8037
- return void 0;
8038
- }
8039
- isLikelyTriggered(selector) {
8040
- const last = this.getLastCommand();
8041
- if (!last) return false;
8042
- const cmd = last.commandName.toLowerCase();
8043
- const target = last.targetSelector?.toLowerCase() || "";
8044
- if (["click", "dblclick", "hover", "tap"].includes(cmd)) {
8045
- return selector === target || selector.startsWith(target.split(/[.\[#]/)[0]);
8046
- }
8047
- if (["fill", "type", "select", "check", "uncheck"].includes(cmd)) {
8048
- return selector === target;
8049
- }
8050
- return false;
8051
- }
8052
- isRecentCommand(cmdName, withinMs = 2e3) {
8053
- const last = this.getLastCommand();
8054
- if (!last) return false;
8055
- return last.commandName === cmdName && Date.now() - last.timestamp < withinMs;
8056
- }
8057
- clear() {
8058
- this.history = [];
8059
- }
8060
- };
8061
-
8062
- // src/tips/tip-generator.ts
8063
- var SILENT_CATEGORIES = /* @__PURE__ */ new Set(["dropdown", "tooltip"]);
8064
- var NOTIFICATION_CATEGORIES = /* @__PURE__ */ new Set(["toast", "notification"]);
8065
- var TipGenerator = class {
8066
- contextTracker;
8067
- reportedSelectors = /* @__PURE__ */ new Map();
8068
- dedupWindowMs = 3e4;
8069
- constructor(contextTracker) {
8070
- this.contextTracker = contextTracker;
8071
- }
8072
- diff(before, after, currentElements) {
8073
- const beforeSet = new Set(before.overlaySelectors);
8074
- const afterSet = new Set(after.overlaySelectors);
8075
- const newSelectors = [];
8076
- for (const sel of afterSet) {
8077
- if (!beforeSet.has(sel)) newSelectors.push(sel);
8078
- }
8079
- if (newSelectors.length === 0) return [];
8080
- return currentElements.filter((el) => newSelectors.includes(el.selector));
8081
- }
8082
- generate(newElements) {
8083
- const tips = [];
8084
- for (const el of newElements) {
8085
- if (this.contextTracker.isLikelyTriggered(el.selector)) continue;
8086
- if (SILENT_CATEGORIES.has(el.category)) continue;
8087
- if (NOTIFICATION_CATEGORIES.has(el.category) && el.text && /success|成功|done|完成|saved|已保存/i.test(el.text)) {
8088
- continue;
8089
- }
8090
- if (this.isRecentlyReported(el.selector)) continue;
8091
- const priority = classifyPriority(el.category, el);
8092
- if (priority === "p3") continue;
8093
- const message = this.buildMessage(el);
8094
- const suggestions = this.buildSuggestions(el);
8095
- tips.push({
8096
- priority,
8097
- category: el.category,
8098
- element: el,
8099
- message,
8100
- suggestions
8101
- });
8102
- this.reportedSelectors.set(el.selector, Date.now());
8103
- }
8104
- tips.sort((a, b) => {
8105
- const order = { p0: 0, p1: 1, p2: 2 };
8106
- return (order[a.priority] ?? 3) - (order[b.priority] ?? 3);
8107
- });
8108
- return tips;
8109
- }
8110
- buildMessage(el) {
8111
- const label = el.ariaLabel || el.text?.slice(0, 40) || "";
8112
- const labelStr = label ? ` "${label}"` : "";
8113
- const sizeStr = `${el.size.width}x${el.size.height}`;
8114
- const typeLabel = this.categoryLabel(el.category);
8115
- return `\u68C0\u6D4B\u5230\u65B0${typeLabel}${labelStr} (${sizeStr})\uFF0C\u9009\u62E9\u5668: ${el.selector}`;
8116
- }
8117
- buildSuggestions(el) {
8118
- const suggestions = [];
8119
- if (el.category === "dialog" || el.category === "modal") {
8120
- const confirmBtn = this.guessButtonSelector(el, ["confirm", "ok", "yes", "\u786E\u5B9A", "\u786E\u8BA4", "\u540C\u610F"]);
8121
- const cancelBtn = this.guessButtonSelector(el, ["cancel", "close", "no", "\u53D6\u6D88", "\u5173\u95ED", "\u62D2\u7EDD"]);
8122
- if (confirmBtn) suggestions.push(`click "${confirmBtn}"`);
8123
- if (cancelBtn) suggestions.push(`click "${cancelBtn}"`);
8124
- }
8125
- if (el.category === "popover" || el.category === "overlay") {
8126
- suggestions.push(`click "${el.selector}"`);
8127
- }
8128
- if (el.category === "toast" || el.category === "notification") {
8129
- suggestions.push(`text "${el.selector}"`);
8130
- }
8131
- if (suggestions.length === 0) {
8132
- suggestions.push(`click "${el.selector}"`);
8133
- }
8134
- return suggestions;
8135
- }
8136
- guessButtonSelector(el, keywords) {
8137
- const base = el.selector;
8138
- for (const kw of keywords) {
8139
- return `${base} button:has-text("${kw}"), ${base} [role="button"]:has-text("${kw}")`;
8140
- }
8141
- return void 0;
8142
- }
8143
- categoryLabel(category) {
8144
- const labels = {
8145
- dialog: "Dialog",
8146
- modal: "Modal",
8147
- popover: "Popover",
8148
- notification: "\u901A\u77E5",
8149
- toast: "Toast",
8150
- dropdown: "\u4E0B\u62C9\u83DC\u5355",
8151
- tooltip: "Tooltip",
8152
- overlay: "Overlay",
8153
- unknown: "\u5F39\u7A97"
8154
- };
8155
- return labels[category] || "\u5F39\u7A97";
8156
- }
8157
- isRecentlyReported(selector) {
8158
- const lastTime = this.reportedSelectors.get(selector);
8159
- if (!lastTime) return false;
8160
- return Date.now() - lastTime < this.dedupWindowMs;
8161
- }
8162
- resetDedup() {
8163
- this.reportedSelectors.clear();
8164
- }
8165
- };
8166
- function buildSnapshot(elements) {
8167
- return {
8168
- timestamp: Date.now(),
8169
- overlaySelectors: elements.map((el) => el.selector)
8170
- };
8171
- }
8172
-
8173
- // src/tips/index.ts
8174
- function tipsDebounceMs() {
8175
- const v = parseInt(process.env.XBROWSER_TIPS_DEBOUNCE ?? "120", 10);
8176
- return Number.isFinite(v) && v > 0 ? v : 0;
8177
- }
8178
- var SKIP_DETECT_COMMANDS = /* @__PURE__ */ new Set([
8179
- "goto",
8180
- // 导航命令不需要检测
8181
- "screenshot",
8182
- // 截图不需要检测
8183
- "snapshot",
8184
- // snapshot 不需要检测
8185
- "get",
8186
- // get 命令不需要检测
8187
- "detect",
8188
- // detect 命令本身不需要检测
8189
- "history",
8190
- // history 命令不需要检测
8191
- "viewer"
8192
- // viewer 命令不需要检测
8193
- ]);
8194
- var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
8195
- "click",
8196
- "fill",
8197
- "type",
8198
- "select",
8199
- "check",
8200
- "uncheck",
8201
- "hover",
8202
- "dblclick"
8203
- ]);
8204
- var TipsManager = class {
8205
- domWatcher = null;
8206
- contextTracker = new ContextTracker();
8207
- generator = new TipGenerator(this.contextTracker);
8208
- beforeSnapshot = null;
8209
- lastDetectionTime = 0;
8210
- async beforeCommand(page, commandName, params) {
8211
- this.contextTracker.record(commandName, params);
8212
- if (!this.domWatcher) {
8213
- this.domWatcher = new DomWatcher(page);
8214
- }
8215
- try {
8216
- await this.domWatcher.inject();
8217
- const elements = await this.domWatcher.scanOverlays();
8218
- this.beforeSnapshot = buildSnapshot(elements);
8219
- } catch {
8220
- this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
8221
- }
8222
- if (INTERACTION_COMMANDS.has(commandName) && !SKIP_DETECT_COMMANDS.has(commandName)) {
8223
- await this.checkAntiBot(page, commandName);
8224
- }
8225
- }
8226
- /**
8227
- * 检测反机器人机制
8228
- */
8229
- async checkAntiBot(page, _commandName) {
8230
- const now = Date.now();
8231
- if (now - this.lastDetectionTime < 5e3) {
8232
- return;
8233
- }
8234
- this.lastDetectionTime = now;
8235
- const config = {
8236
- checkCaptcha: true,
8237
- checkWarning: true,
8238
- checkBlocked: true,
8239
- checkWebdriver: true
8240
- };
8241
- const result = await detectAntiBot(page, config);
8242
- if (result.detected && result.severity === "high") {
8243
- const message = formatDetectionMessage(result);
8244
- console.error(`
8245
- \u{1F6A8} ${message}
8246
- `);
8247
- console.log("\u{1F4A1} Action blocked. To continue:");
8248
- console.log(" 1. Use viewer mode: xbrowser viewer --json");
8249
- console.log(" 2. Or skip detection with --skip-detect flag\n");
8250
- throw new Error(`Anti-bot detection blocked: ${result.message}`);
8251
- }
8252
- }
8253
- async afterCommand() {
8254
- if (!this.domWatcher || !this.beforeSnapshot) return [];
8255
- await this.debounce();
8256
- try {
8257
- const currentElements = await this.domWatcher.scanOverlays();
8258
- const afterSnapshot = buildSnapshot(currentElements);
8259
- const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
8260
- const tips = this.generator.generate(newElements);
8261
- this.beforeSnapshot = null;
8262
- return tips;
8263
- } catch {
8264
- this.beforeSnapshot = null;
8265
- return [];
8266
- }
8267
- }
8268
- debounce() {
8269
- const ms = tipsDebounceMs();
8270
- if (ms <= 0) return Promise.resolve();
8271
- return new Promise((resolve3) => setTimeout(resolve3, ms));
8272
- }
8273
- formatTips(tips) {
8274
- return tips.map((tip) => {
8275
- const lines = [tip.message];
8276
- for (const s of tip.suggestions) {
8277
- lines.push(` \u2192 ${s}`);
8278
- }
8279
- return lines.join("\n");
8280
- });
8281
- }
8282
- reset() {
8283
- this.beforeSnapshot = null;
8284
- this.generator.resetDedup();
8285
- this.contextTracker.clear();
8286
- this.domWatcher = null;
8287
- this.lastDetectionTime = 0;
8288
- }
8289
- };
8290
- var globalTipsManager = null;
8291
- function getTipsManager() {
8292
- if (!globalTipsManager) {
8293
- globalTipsManager = new TipsManager();
8294
- }
8295
- return globalTipsManager;
7850
+ return globalTipsManager;
8296
7851
  }
8297
7852
 
8298
7853
  // src/hooks/loader.ts
@@ -8330,63 +7885,1163 @@ var HOOK_REGISTRY = {
8330
7885
  if (!tips.some((t) => t.includes("viewer") || t.includes("Viewer"))) {
8331
7886
  tips.push(`Open viewer: ${viewerUrl}`);
8332
7887
  }
8333
- result.tips = tips;
8334
- result.viewerUrl = viewerUrl;
8335
- return void 0;
7888
+ result.tips = tips;
7889
+ result.viewerUrl = viewerUrl;
7890
+ return void 0;
7891
+ }
7892
+ },
7893
+ screenshot: {
7894
+ name: "screenshot",
7895
+ onAfterCommand: async (ctx) => {
7896
+ try {
7897
+ const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
7898
+ if (!buf) return;
7899
+ return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
7900
+ } catch {
7901
+ return;
7902
+ }
7903
+ }
7904
+ },
7905
+ recorder: {
7906
+ name: "recorder",
7907
+ onAfterCommand: async (ctx) => {
7908
+ const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
7909
+ logs.push({
7910
+ timestamp: Date.now(),
7911
+ command: ctx.command,
7912
+ params: JSON.parse(JSON.stringify(ctx.params)),
7913
+ duration: ctx.duration
7914
+ });
7915
+ Reflect.set(ctx, "__commandLogs", logs);
7916
+ return void 0;
7917
+ }
7918
+ }
7919
+ };
7920
+ var customHooks = {};
7921
+ async function loadHooks() {
7922
+ const env = process.env.XBROWSER_HOOKS;
7923
+ if (!env) return [];
7924
+ const names = env.split(",").map((n) => n.trim()).filter(Boolean);
7925
+ if (names.length === 0) return [];
7926
+ const hooks = [];
7927
+ for (const name of names) {
7928
+ const hook = HOOK_REGISTRY[name];
7929
+ if (hook) {
7930
+ hooks.push(hook);
7931
+ continue;
7932
+ }
7933
+ const customFactory = customHooks[name];
7934
+ if (customFactory) {
7935
+ const customHook = await customFactory();
7936
+ if (customHook) hooks.push(customHook);
7937
+ }
7938
+ }
7939
+ return hooks;
7940
+ }
7941
+
7942
+ // src/fail-codes.ts
7943
+ var FAIL_CODES = {
7944
+ selectorNotFound: "RETRYABLE: selector-not-found",
7945
+ pageNotReady: "RETRYABLE: page-not-ready",
7946
+ elementGone: "RETRYABLE: element-gone",
7947
+ inputNotRetained: "RETRYABLE: input-not-retained",
7948
+ captcha: "HUMAN: captcha",
7949
+ loginWall: "HUMAN: login-wall",
7950
+ permissionDenied: "FATAL: permission-denied",
7951
+ targetGone: "FATAL: target-gone",
7952
+ unknown: "FATAL: unknown"
7953
+ };
7954
+ function classifyFailure(message) {
7955
+ const msg = (message || "").toLowerCase();
7956
+ const pick = (code) => ({
7957
+ code,
7958
+ level: code.split(":")[0],
7959
+ message: message || code
7960
+ });
7961
+ if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
7962
+ if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
7963
+ if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
7964
+ if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
7965
+ return pick(FAIL_CODES.selectorNotFound);
7966
+ if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
7967
+ if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
7968
+ if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
7969
+ return pick(FAIL_CODES.targetGone);
7970
+ return pick(FAIL_CODES.unknown);
7971
+ }
7972
+
7973
+ // src/lib/mistake-ledger.ts
7974
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
7975
+ import { homedir as homedir5 } from "os";
7976
+ import { join as join7 } 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
+ function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
8009
+ if (!input.category) throw new Error("mistake category is required");
8010
+ if (!input.command) throw new Error("mistake command is required");
8011
+ if (!input.message) throw new Error("mistake message is required");
8012
+ const ledger = readMistakeLedger(path2);
8013
+ const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
8014
+ const previous = ledger.entries[fingerprint];
8015
+ const occurrence = {
8016
+ timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
8017
+ command: input.command,
8018
+ message: input.message,
8019
+ ...input.context ? { context: input.context } : {}
8020
+ };
8021
+ const entry = previous ? {
8022
+ ...previous,
8023
+ lastSeen: occurrence.timestamp,
8024
+ occurrences: [...previous.occurrences, occurrence].slice(-100),
8025
+ constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
8026
+ } : {
8027
+ fingerprint,
8028
+ category: input.category,
8029
+ firstSeen: occurrence.timestamp,
8030
+ lastSeen: occurrence.timestamp,
8031
+ occurrences: [occurrence],
8032
+ constrained: false
8033
+ };
8034
+ ledger.entries[fingerprint] = entry;
8035
+ writeMistakeLedger(ledger, path2);
8036
+ return {
8037
+ entry,
8038
+ newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
8039
+ };
8040
+ }
8041
+
8042
+ // src/executor/foundation.ts
8043
+ import { homedir as homedir7 } from "os";
8044
+ import { join as join9 } from "path";
8045
+ import {
8046
+ CompositeStorage as CompositeStorage2,
8047
+ configureArchiveStore,
8048
+ appendCommandToArchive,
8049
+ fail as fail17,
8050
+ checkGuard
8051
+ } from "@dyyz1993/xcli-core";
8052
+
8053
+ // src/plugin/loader.ts
8054
+ import {
8055
+ Core
8056
+ } from "@dyyz1993/xcli-core";
8057
+ import { resolve as resolve2, basename, dirname as dirname3 } from "path";
8058
+ import { existsSync as existsSync7, readdirSync } from "fs";
8059
+ import { homedir as homedir6 } from "os";
8060
+
8061
+ // src/plugin/metadata-parser.ts
8062
+ import { existsSync as existsSync5 } from "fs";
8063
+ import { resolve } from "path";
8064
+
8065
+ // src/utils/json-file.ts
8066
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
8067
+ function readJsonFile(filePath, defaultValue) {
8068
+ try {
8069
+ const content = readFileSync6(filePath, "utf-8");
8070
+ return JSON.parse(content);
8071
+ } catch {
8072
+ return defaultValue;
8073
+ }
8074
+ }
8075
+
8076
+ // src/plugin/metadata-parser.ts
8077
+ var PluginMetadataParser = class {
8078
+ static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
8079
+ static parseFromPackageJson(pluginPath) {
8080
+ const packageJsonPath = resolve(pluginPath, "package.json");
8081
+ if (!existsSync5(packageJsonPath)) {
8082
+ return null;
8083
+ }
8084
+ const packageJson = readJsonFile(packageJsonPath, null);
8085
+ if (!packageJson) return null;
8086
+ if (!packageJson.xbrowser) {
8087
+ return null;
8088
+ }
8089
+ const xbrowser = packageJson.xbrowser;
8090
+ const metadata = {
8091
+ id: xbrowser.id || packageJson.name,
8092
+ name: xbrowser.name || packageJson.name,
8093
+ description: xbrowser.description || packageJson.description || "",
8094
+ version: xbrowser.version || packageJson.version || "1.0.0",
8095
+ author: xbrowser.author || this.extractAuthor(packageJson.author),
8096
+ homepage: xbrowser.homepage || packageJson.homepage,
8097
+ commands: xbrowser.commands,
8098
+ sites: xbrowser.sites,
8099
+ tags: xbrowser.tags,
8100
+ screenshot: xbrowser.screenshot,
8101
+ license: xbrowser.license || packageJson.license
8102
+ };
8103
+ return metadata;
8104
+ }
8105
+ static isXBrowserPlugin(packageJson) {
8106
+ if (packageJson.xbrowser) {
8107
+ return true;
8108
+ }
8109
+ const keywords = packageJson.keywords;
8110
+ if (!keywords) return false;
8111
+ return this.XBROWSER_KEYWORDS.some((kw) => keywords.includes(kw));
8112
+ }
8113
+ static fromNPMResult(result) {
8114
+ const author = typeof result.author === "string" ? result.author : result.author?.name || "Unknown";
8115
+ return {
8116
+ id: result.name,
8117
+ name: result.name.replace(/^xbrowser-plugin-/, "").replace(/^@[^/]+\//, ""),
8118
+ description: result.description || "",
8119
+ version: result.version,
8120
+ author,
8121
+ homepage: result.homepage || result.links?.homepage,
8122
+ tags: result.keywords,
8123
+ license: ""
8124
+ };
8125
+ }
8126
+ static extractAuthor(author) {
8127
+ if (typeof author === "string") return author;
8128
+ if (typeof author === "object" && author !== null) {
8129
+ const authorObj = author;
8130
+ return authorObj.name || "Unknown";
8131
+ }
8132
+ return "Unknown";
8133
+ }
8134
+ static validateMetadata(metadata) {
8135
+ const errors = [];
8136
+ if (!metadata.id) errors.push("id is required");
8137
+ if (!metadata.name) errors.push("name is required");
8138
+ if (!metadata.description) errors.push("description is required");
8139
+ if (!metadata.version) errors.push("version is required");
8140
+ return errors;
8141
+ }
8142
+ };
8143
+
8144
+ // src/plugin/ensure-deps.ts
8145
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
8146
+ import { join as join8 } from "path";
8147
+ import { execSync } from "child_process";
8148
+ var SHARED_PLUGIN_DEPENDENCIES = {
8149
+ "zod": "^3.24.0",
8150
+ "@dyyz1993/xcli-core": "^0.19.0"
8151
+ };
8152
+ function ensurePluginDependencies(pluginsDir) {
8153
+ const zodPath = join8(pluginsDir, "node_modules", "zod");
8154
+ if (existsSync6(zodPath)) return;
8155
+ mkdirSync5(pluginsDir, { recursive: true });
8156
+ const pkgPath = join8(pluginsDir, "package.json");
8157
+ let pkg = {};
8158
+ if (existsSync6(pkgPath)) {
8159
+ try {
8160
+ pkg = readJsonFile(pkgPath, {});
8161
+ } catch {
8162
+ }
8163
+ }
8164
+ const existingDeps = pkg.dependencies || {};
8165
+ let needsInstall = false;
8166
+ for (const [dep, version] of Object.entries(SHARED_PLUGIN_DEPENDENCIES)) {
8167
+ if (!existingDeps[dep]) {
8168
+ existingDeps[dep] = version;
8169
+ needsInstall = true;
8170
+ }
8171
+ }
8172
+ if (!needsInstall && existsSync6(join8(pluginsDir, "node_modules"))) return;
8173
+ pkg.dependencies = existingDeps;
8174
+ pkg.private = true;
8175
+ pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
8176
+ writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
8177
+ try {
8178
+ execSync("npm install --production --no-package-lock --no-fund --no-audit", {
8179
+ cwd: pluginsDir,
8180
+ stdio: "pipe",
8181
+ timeout: 6e4,
8182
+ env: { ...process.env, NODE_ENV: "production" }
8183
+ });
8184
+ } catch (err) {
8185
+ console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
8186
+ }
8187
+ }
8188
+
8189
+ // src/plugin/contract.ts
8190
+ import {
8191
+ unwrapZod,
8192
+ fieldsFromZodObjectReflected,
8193
+ zodTypeToContractType
8194
+ } from "@dyyz1993/xcli-core";
8195
+ function buildPluginContract(site) {
8196
+ const commands = site.getAllCommands().map((command) => buildCommandContract(site.getCommand?.(command.name) || command, {
8197
+ siteRequiresLogin: site.config?.requiresLogin
8198
+ }));
8199
+ return {
8200
+ version: 2,
8201
+ plugin: {
8202
+ name: site.name,
8203
+ url: site.url,
8204
+ description: site.config?.description,
8205
+ requiresLogin: site.config?.requiresLogin
8206
+ },
8207
+ commands
8208
+ };
8209
+ }
8210
+ function buildCommandContract(command, options = {}) {
8211
+ const extension = command.xbrowser || {};
8212
+ const inferredFields = fieldsFromZodObject(command.parameters);
8213
+ const fields = mergeFields(inferredFields, extension.form?.fields || []);
8214
+ const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
8215
+ const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
8216
+ const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
8217
+ const outputSchema = command.result ? summarizeZod(command.result) : void 0;
8218
+ return {
8219
+ name: command.name,
8220
+ description: command.description || "",
8221
+ scope: command.scope || "project",
8222
+ requiresLogin,
8223
+ category: extension.category,
8224
+ capabilities,
8225
+ positional,
8226
+ form: {
8227
+ title: extension.form?.title || command.description || command.name,
8228
+ description: extension.form?.description,
8229
+ submitLabel: extension.form?.submitLabel || "Run",
8230
+ fields
8231
+ },
8232
+ output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
8233
+ };
8234
+ }
8235
+ function fieldsFromZodObject(schema) {
8236
+ const reflected = fieldsFromZodObjectReflected(schema);
8237
+ return reflected.map((field) => {
8238
+ const widget = widgetFor(field.type, field.enum);
8239
+ return {
8240
+ name: field.name,
8241
+ label: toLabel(field.name),
8242
+ type: field.type,
8243
+ widget,
8244
+ required: field.required,
8245
+ ...field.description ? { description: field.description } : {},
8246
+ ...field.default !== void 0 ? { default: field.default } : {},
8247
+ ...field.enum ? { enum: field.enum } : {},
8248
+ ...field.type === "array" ? { multiple: true } : {}
8249
+ };
8250
+ });
8251
+ }
8252
+ function mergeFields(inferred, overrides) {
8253
+ if (overrides.length === 0) return inferred;
8254
+ const byName = new Map(inferred.map((field) => [field.name, field]));
8255
+ const seen = /* @__PURE__ */ new Set();
8256
+ const merged = [];
8257
+ for (const override of overrides) {
8258
+ if (!override.name) continue;
8259
+ const base = byName.get(override.name) || {
8260
+ name: override.name,
8261
+ label: toLabel(override.name),
8262
+ type: "string",
8263
+ widget: "text",
8264
+ required: false
8265
+ };
8266
+ merged.push({ ...base, ...override, name: override.name });
8267
+ seen.add(override.name);
8268
+ }
8269
+ for (const field of inferred) {
8270
+ if (!seen.has(field.name)) merged.push(field);
8271
+ }
8272
+ return merged;
8273
+ }
8274
+ function inferCapabilities(scope, requiresLogin) {
8275
+ const caps = [];
8276
+ if (scope === "page") caps.push("browser.page");
8277
+ if (scope === "browser") caps.push("browser.context");
8278
+ if (requiresLogin) caps.push("auth.login");
8279
+ return caps;
8280
+ }
8281
+ function widgetFor(type, enumValues) {
8282
+ if (enumValues) return "select";
8283
+ if (type === "boolean") return "checkbox";
8284
+ if (type === "number") return "number";
8285
+ if (type === "array") return "multi-select";
8286
+ if (type === "object") return "json";
8287
+ return "text";
8288
+ }
8289
+ function summarizeZod(schema) {
8290
+ const unwrapped = unwrapZod(schema);
8291
+ if (unwrapped.typeName === "ZodArray") {
8292
+ const def = unwrapped.schema?._def;
8293
+ return {
8294
+ type: "array",
8295
+ items: summarizeZod(def?.type || def?.innerType)
8296
+ };
8297
+ }
8298
+ const shape = getObjectShape(schema);
8299
+ if (!shape) {
8300
+ return {
8301
+ type: zodTypeToContractType(unwrapped.typeName),
8302
+ required: !unwrapped.optional,
8303
+ ...unwrapped.description ? { description: unwrapped.description } : {}
8304
+ };
8305
+ }
8306
+ return Object.fromEntries(
8307
+ Object.entries(shape).map(([name, field]) => {
8308
+ const inner = unwrapZod(field);
8309
+ return [name, {
8310
+ type: zodTypeToContractType(inner.typeName),
8311
+ required: !inner.optional,
8312
+ ...inner.description ? { description: inner.description } : {}
8313
+ }];
8314
+ })
8315
+ );
8316
+ }
8317
+ function getObjectShape(schema) {
8318
+ const zod = schema;
8319
+ const shapeOrFn = zod?.shape ?? zod?._def?.shape;
8320
+ if (!shapeOrFn) return void 0;
8321
+ return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
8322
+ }
8323
+ function toLabel(name) {
8324
+ return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
8325
+ }
8326
+
8327
+ // src/plugin/login-required-patch.ts
8328
+ import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
8329
+ var patched = false;
8330
+ function patchLoginRequired() {
8331
+ if (patched) return;
8332
+ patched = true;
8333
+ const target = SiteInstanceImpl.prototype;
8334
+ const originalCommand = target.command;
8335
+ const wrapped = function(...args) {
8336
+ const result = originalCommand.apply(this, args);
8337
+ const [name, cmd] = args;
8338
+ const loginRequired = cmd.loginRequired;
8339
+ if (loginRequired) {
8340
+ const commands = this.commands;
8341
+ const entry = commands?.get(name);
8342
+ if (entry) {
8343
+ entry.loginRequired = loginRequired;
8344
+ }
8345
+ }
8346
+ return result;
8347
+ };
8348
+ Object.defineProperty(target, "command", {
8349
+ value: wrapped,
8350
+ writable: true,
8351
+ configurable: true
8352
+ });
8353
+ }
8354
+
8355
+ // src/plugin/loader.ts
8356
+ var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
8357
+ var XBrowserPluginLoader = class {
8358
+ core;
8359
+ loader;
8360
+ options;
8361
+ /** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
8362
+ dirSiteAliases = /* @__PURE__ */ new Map();
8363
+ constructor(options) {
8364
+ patchLoginRequired();
8365
+ globalThis.__xbrowserRecordMistake = recordMistake;
8366
+ this.options = options ?? {};
8367
+ const cwd = this.options.cwd || process.cwd();
8368
+ const coreConfig = {
8369
+ name: "xbrowser",
8370
+ version: "0.1.0",
8371
+ description: "Browser automation CLI",
8372
+ configDirName: ".xbrowser",
8373
+ envPrefix: "XBROWSER",
8374
+ pluginDirs: [
8375
+ ...DEFAULT_PLUGIN_DIRS,
8376
+ resolve2(cwd, ".xcli/plugins")
8377
+ ]
8378
+ };
8379
+ this.core = new Core(coreConfig);
8380
+ this.loader = this.core.loader;
8381
+ }
8382
+ getAPI() {
8383
+ return this.loader.getAPI();
8384
+ }
8385
+ /**
8386
+ * Get the core instance for external use.
8387
+ * @returns The xcli-core Core instance.
8388
+ */
8389
+ getCore() {
8390
+ return this.core;
8391
+ }
8392
+ getPlugin(id) {
8393
+ return this.loader.getPlugin(id);
8394
+ }
8395
+ getPluginStatus(id) {
8396
+ return this.loader.getPluginStatus(id);
8397
+ }
8398
+ getLoadedPlugins() {
8399
+ return this.loader.getLoadedPlugins();
8400
+ }
8401
+ /**
8402
+ * 目录名别名兜底(小白用户实测踩坑):`plugin list` 显示目录名,但命令路由
8403
+ * 按 site.name 匹配——两者不一致时(如目录 alibaba-1688、site 名 1688),
8404
+ * 用户按 list 显示的名字敲命令会 "Unknown command"。映射在 scanAndLoad/
8405
+ * loadPlugin 时通过加载前后 site 快照 diff 记录(instance.siteName 返回的是
8406
+ * 插件 id 而非 site 名,不可用)。
8407
+ */
8408
+ resolveSiteName(name) {
8409
+ if (this.core.loader.getSite(name)) return name;
8410
+ const aliased = this.dirSiteAliases.get(name);
8411
+ if (aliased && this.core.loader.getSite(aliased)) return aliased;
8412
+ return void 0;
8413
+ }
8414
+ /** 记录一次插件加载引入的 site:加载前后快照 diff(同插件可注册多个 site) */
8415
+ recordSiteAliases(pluginDirName, before) {
8416
+ for (const site of this.core.loader.getSites()) {
8417
+ if (!before.has(site.name)) this.dirSiteAliases.set(pluginDirName, site.name);
8418
+ }
8419
+ }
8420
+ getPluginContract(siteName, commandName) {
8421
+ const resolved = this.resolveSiteName(siteName);
8422
+ if (!resolved) return void 0;
8423
+ const site = this.core.loader.getSite(resolved);
8424
+ if (!site) return void 0;
8425
+ const contract = buildPluginContract(site);
8426
+ if (!commandName) return contract;
8427
+ return contract.commands.find((command) => command.name === commandName);
8428
+ }
8429
+ async loadPlugin(pluginPath, id) {
8430
+ const before = new Set(this.core.loader.getSites().map((s) => s.name));
8431
+ const instance = await this.loader.loadPlugin(pluginPath, id);
8432
+ this.recordSiteAliases(basename(dirname3(pluginPath)), before);
8433
+ return instance;
8434
+ }
8435
+ async unloadPlugin(id) {
8436
+ return this.loader.unloadPlugin(id);
8437
+ }
8438
+ async reloadPlugin(id) {
8439
+ return this.loader.reloadPlugin(id);
8440
+ }
8441
+ async loadFromFunction(setup) {
8442
+ return this.loader.loadFromFunction(setup);
8443
+ }
8444
+ async scanAndLoad() {
8445
+ const cwd = this.options.cwd || process.cwd();
8446
+ const globalDir = this.options.globalDir || resolve2(homedir6(), ".xbrowser/plugins");
8447
+ ensurePluginDependencies(globalDir);
8448
+ const dirs = [
8449
+ resolve2(cwd, ".xcli/plugins"),
8450
+ resolve2(cwd, "../.xcli/plugins"),
8451
+ this.options.userDir || resolve2(homedir6(), ".xcli/plugins"),
8452
+ globalDir
8453
+ ];
8454
+ const loaded = [];
8455
+ const seen = /* @__PURE__ */ new Set();
8456
+ for (const dir of dirs) {
8457
+ if (!existsSync7(dir)) continue;
8458
+ const entries = readdirSync(dir, { withFileTypes: true });
8459
+ for (const entry of entries) {
8460
+ if (!entry.isDirectory()) continue;
8461
+ if (seen.has(entry.name)) continue;
8462
+ seen.add(entry.name);
8463
+ const pluginDir = resolve2(dir, entry.name);
8464
+ let indexPath = resolve2(pluginDir, "index.js");
8465
+ if (!existsSync7(indexPath)) {
8466
+ indexPath = resolve2(pluginDir, "index.ts");
8467
+ }
8468
+ if (!existsSync7(indexPath)) continue;
8469
+ try {
8470
+ if (!existsSync7(resolve2(pluginDir, "package.json"))) {
8471
+ console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
8472
+ } else {
8473
+ const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
8474
+ if (!metadata) {
8475
+ console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
8476
+ }
8477
+ }
8478
+ const instance = await this.loadPlugin(indexPath, entry.name);
8479
+ loaded.push(instance);
8480
+ } catch (err) {
8481
+ const errMsg2 = err instanceof Error ? err.message : String(err);
8482
+ console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
8483
+ if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
8484
+ console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
8485
+ }
8486
+ }
8487
+ }
8488
+ }
8489
+ return loaded;
8490
+ }
8491
+ async unload() {
8492
+ return this.loader.unload();
8493
+ }
8494
+ };
8495
+
8496
+ // src/utils/plugin-singleton.ts
8497
+ var pluginLoader = null;
8498
+ var pluginsScanned = false;
8499
+ function silenceSchemaWarnings(fn) {
8500
+ if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
8501
+ const originalWarn = console.warn;
8502
+ console.warn = (...args) => {
8503
+ const msg = typeof args[0] === "string" ? args[0] : "";
8504
+ if (msg.includes('has no "result" schema')) return;
8505
+ originalWarn(...args);
8506
+ };
8507
+ return fn().finally(() => {
8508
+ console.warn = originalWarn;
8509
+ });
8510
+ }
8511
+ async function getPluginLoader() {
8512
+ if (!pluginLoader) {
8513
+ pluginLoader = new XBrowserPluginLoader();
8514
+ }
8515
+ if (!pluginsScanned) {
8516
+ await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
8517
+ pluginsScanned = true;
8518
+ }
8519
+ return pluginLoader;
8520
+ }
8521
+
8522
+ // src/executor/foundation.ts
8523
+ var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8524
+ var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8525
+ var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
8526
+ var storageCache = /* @__PURE__ */ new Map();
8527
+ function getPluginStorage(pluginName) {
8528
+ if (!storageCache.has(pluginName)) {
8529
+ storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
8530
+ }
8531
+ return storageCache.get(pluginName);
8532
+ }
8533
+ var archiveInitialized = false;
8534
+ function ensureArchiveInit() {
8535
+ if (!archiveInitialized) {
8536
+ try {
8537
+ configureArchiveStore({ archiveDir: join9(homedir7(), ".xbrowser", "archives") });
8538
+ } catch {
8539
+ }
8540
+ archiveInitialized = true;
8541
+ }
8542
+ }
8543
+ function recordArchive(sessionId, sessionName, entry) {
8544
+ if (!sessionId) return;
8545
+ try {
8546
+ ensureArchiveInit();
8547
+ appendCommandToArchive(sessionId, sessionName, entry);
8548
+ } catch {
8549
+ }
8550
+ }
8551
+ async function guardCheck(commandName) {
8552
+ try {
8553
+ const loader = await getPluginLoader();
8554
+ return checkGuard(loader.getCore(), commandName, process.env);
8555
+ } catch {
8556
+ return null;
8557
+ }
8558
+ }
8559
+ function errorResult(message) {
8560
+ return { ...fail17(message), duration: 0 };
8561
+ }
8562
+ function tipsToMessages(tips) {
8563
+ if (!tips || tips.length === 0) return [];
8564
+ return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
8565
+ }
8566
+ var wsServer = null;
8567
+ function streamCommandEvent(sessionId, message) {
8568
+ if (!wsServer || !wsServer.getRunning()) return;
8569
+ wsServer.broadcastToSession(sessionId, { type: "command", data: message });
8570
+ }
8571
+
8572
+ // src/executor/chain.ts
8573
+ import {
8574
+ fail as fail18,
8575
+ ok as ok32,
8576
+ TipCollector as TipCollector2,
8577
+ normalizeTips as normalizeTips7,
8578
+ unquote as unquote2
8579
+ } from "@dyyz1993/xcli-core";
8580
+
8581
+ // src/plugin/login-guard.ts
8582
+ async function checkPluginLoginRequired(options) {
8583
+ const { site, command, commandName, ctx, page, sessionName } = options;
8584
+ if (commandName === "login" || commandName === "logout") return { ok: true };
8585
+ const loginConfig = site.config?.loginConfig;
8586
+ const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
8587
+ if (!requiresLogin) return { ok: true };
8588
+ const pluginName = site.name || "plugin";
8589
+ const siteConfig = site.config;
8590
+ const configIsLogin = siteConfig?.isLogin;
8591
+ if (configIsLogin) {
8592
+ try {
8593
+ const loggedIn = await configIsLogin(ctx);
8594
+ if (loggedIn) return { ok: true };
8595
+ return buildLoginRequired({
8596
+ plugin: pluginName,
8597
+ command: commandName,
8598
+ reason: "config.isLogin returned false",
8599
+ sessionName,
8600
+ loginConfig
8601
+ });
8602
+ } catch {
8603
+ }
8604
+ }
8605
+ if (typeof site.isLoggedIn === "function") {
8606
+ try {
8607
+ const loggedIn = await site.isLoggedIn(ctx);
8608
+ if (loggedIn) return { ok: true };
8609
+ return buildLoginRequired({
8610
+ plugin: pluginName,
8611
+ command: commandName,
8612
+ reason: "plugin isLoggedIn returned false",
8613
+ sessionName,
8614
+ loginConfig
8615
+ });
8616
+ } catch {
8617
+ }
8618
+ }
8619
+ if (page && loginConfig) {
8620
+ const generic = await detectLoginFromPage(page, loginConfig);
8621
+ if (generic === "logged-in") return { ok: true };
8622
+ if (generic === "logged-out") {
8623
+ return buildLoginRequired({
8624
+ plugin: pluginName,
8625
+ command: commandName,
8626
+ reason: "generic loginConfig detected logged-out page",
8627
+ sessionName,
8628
+ loginConfig
8629
+ });
8630
+ }
8631
+ }
8632
+ return { ok: true };
8633
+ }
8634
+ function buildLoginRequired(options) {
8635
+ const viewerUrl = buildViewerUrl(options.sessionName);
8636
+ const loginUrl = options.loginConfig?.loginUrl;
8637
+ const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
8638
+ const tips = [
8639
+ message,
8640
+ ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
8641
+ ...loginUrl ? [`Login page: ${loginUrl}`] : [],
8642
+ `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
8643
+ ];
8644
+ return {
8645
+ ok: false,
8646
+ data: {
8647
+ code: "LOGIN_REQUIRED",
8648
+ plugin: options.plugin,
8649
+ command: options.command,
8650
+ reason: options.reason,
8651
+ ...viewerUrl ? { viewerUrl } : {},
8652
+ ...loginUrl ? { loginUrl } : {}
8653
+ },
8654
+ message,
8655
+ tips
8656
+ };
8657
+ }
8658
+ async function detectLoginFromPage(page, config) {
8659
+ const url = page.url();
8660
+ if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
8661
+ const result = await page.evaluate((cfg) => {
8662
+ const visible = (selector) => {
8663
+ try {
8664
+ const el = document.querySelector(selector);
8665
+ if (!el) return false;
8666
+ const rect = el.getBoundingClientRect();
8667
+ const style = window.getComputedStyle(el);
8668
+ return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
8669
+ } catch {
8670
+ return false;
8671
+ }
8672
+ };
8673
+ if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
8674
+ if (cfg.loginSelectors?.some(visible)) return "logged-out";
8675
+ const bodyText = document.body?.innerText || "";
8676
+ const keywords = cfg.loginKeywords || [];
8677
+ if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
8678
+ return "logged-out";
8679
+ }
8680
+ return "unknown";
8681
+ }, {
8682
+ loginSelectors: config.loginSelectors || [],
8683
+ loginKeywords: config.loginKeywords || [],
8684
+ loggedInSelectors: config.loggedInSelectors || []
8685
+ });
8686
+ return result;
8687
+ }
8688
+
8689
+ // src/utils/positional-params.ts
8690
+ import { unquote } from "@dyyz1993/xcli-core";
8691
+ function getTypeName(field) {
8692
+ return field?._def?.typeName;
8693
+ }
8694
+ function unwrapField(field) {
8695
+ const typeName = getTypeName(field);
8696
+ if (typeName === "ZodOptional" || typeName === "ZodDefault") {
8697
+ const innerType = field?._def?.innerType;
8698
+ return unwrapField(innerType);
8699
+ }
8700
+ return field;
8701
+ }
8702
+ function isOptionalNumber(field) {
8703
+ const typeName = getTypeName(field);
8704
+ return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
8705
+ }
8706
+ function coerceValue(raw, field) {
8707
+ const inner = unwrapField(field);
8708
+ const optionalNum = isOptionalNumber(field);
8709
+ const innerTypeName = getTypeName(inner);
8710
+ if (innerTypeName === "ZodString") {
8711
+ return { value: unquote(raw), skip: false };
8712
+ }
8713
+ if (innerTypeName === "ZodNumber") {
8714
+ const parsed = Number(raw);
8715
+ if (isNaN(parsed)) {
8716
+ if (optionalNum) return { value: void 0, skip: true };
8717
+ return { value: raw, skip: false };
8718
+ }
8719
+ return { value: parsed, skip: false };
8720
+ }
8721
+ if (innerTypeName === "ZodBoolean") {
8722
+ if (raw === "true" || raw === "1") return { value: true, skip: false };
8723
+ if (raw === "false" || raw === "0") return { value: false, skip: false };
8724
+ return { value: raw, skip: false };
8725
+ }
8726
+ return { value: unquote(raw), skip: false };
8727
+ }
8728
+ function mapPositionalValues(schema, positional, existing) {
8729
+ const result = { ...existing };
8730
+ if (!schema || typeof schema !== "object") return result;
8731
+ const shape = schema.shape;
8732
+ if (!shape || typeof shape !== "object") return result;
8733
+ const keys = Object.keys(shape);
8734
+ let pIdx = 0;
8735
+ for (const key of keys) {
8736
+ if (pIdx >= positional.length) break;
8737
+ if (result[key] !== void 0) {
8738
+ pIdx++;
8739
+ continue;
8740
+ }
8741
+ const field = shape[key];
8742
+ const raw = positional[pIdx];
8743
+ const { value, skip } = coerceValue(raw, field);
8744
+ if (skip) continue;
8745
+ result[key] = value;
8746
+ pIdx++;
8747
+ }
8748
+ return result;
8749
+ }
8750
+
8751
+ // src/utils/plugin-params.ts
8752
+ function schemaFieldType(schema, key) {
8753
+ const shape = schema?.shape;
8754
+ const field = shape?.[key];
8755
+ let current = field;
8756
+ while (current) {
8757
+ const def = current._def;
8758
+ if (!def) return void 0;
8759
+ const type = def.typeName ?? def.type;
8760
+ if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
8761
+ current = def.innerType ?? def.inner;
8762
+ continue;
8763
+ }
8764
+ return type;
8765
+ }
8766
+ return void 0;
8767
+ }
8768
+ function parsePluginParams(args, schema, base = {}) {
8769
+ const params = { ...base };
8770
+ const positionalValues = [];
8771
+ for (let i = 0; i < args.length; i++) {
8772
+ if (args[i] === "--" && args[i + 1]) {
8773
+ try {
8774
+ Object.assign(params, JSON.parse(args[i + 1]));
8775
+ } catch {
8776
+ }
8777
+ break;
8778
+ }
8779
+ if (args[i].startsWith("--")) {
8780
+ const key = args[i].slice(2);
8781
+ const value = args[i + 1];
8782
+ if (value && !value.startsWith("-")) {
8783
+ const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
8784
+ if (type === "ZodString" || type === "string") params[key] = value;
8785
+ else if (value === "true") params[key] = true;
8786
+ else if (value === "false") params[key] = false;
8787
+ else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
8788
+ else {
8789
+ try {
8790
+ const parsed = JSON.parse(value);
8791
+ if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
8792
+ params[key] = parsed;
8793
+ } else {
8794
+ params[key] = value;
8795
+ }
8796
+ } catch {
8797
+ params[key] = value;
8798
+ }
8799
+ }
8800
+ i++;
8801
+ } else {
8802
+ params[key] = true;
8803
+ }
8804
+ } else if (!args[i].startsWith("-")) {
8805
+ positionalValues.push(args[i]);
8806
+ }
8807
+ }
8808
+ Object.assign(params, mapPositionalValues(schema, positionalValues, params));
8809
+ const result = {};
8810
+ for (const [k, v] of Object.entries(params)) {
8811
+ const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8812
+ result[camelKey] = v;
8813
+ }
8814
+ return result;
8815
+ }
8816
+
8817
+ // src/executor/chain.ts
8818
+ async function executeChain(input, options, executeCommand2) {
8819
+ const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8820
+ const sessionName = options?.sessionName || "default";
8821
+ const results = [];
8822
+ const totalStart = Date.now();
8823
+ let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8824
+ if (!session) {
8825
+ const launchOpts = {};
8826
+ if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
8827
+ session = await createSession(sessionName, void 0, launchOpts);
8828
+ saveSessionDiskMeta(sessionName, {
8829
+ id: session.id,
8830
+ name: sessionName,
8831
+ url: session.page.url(),
8832
+ createdAt: session.createdAt,
8833
+ cdpEndpoint: session.cdpEndpoint
8834
+ });
8835
+ }
8836
+ try {
8837
+ for (const pipeline of pipelines) {
8838
+ const { type, pipeline: commands } = pipeline;
8839
+ for (const cmdStr of commands) {
8840
+ if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8841
+ await new Promise((resolve3) => setTimeout(resolve3, 800 + Math.random() * 1700));
8842
+ }
8843
+ const parts = splitCommand(cmdStr);
8844
+ if (parts.length === 0) continue;
8845
+ const cmdName = parts[0];
8846
+ const cmdArgs = parts.slice(1);
8847
+ const loader = await getPluginLoader();
8848
+ const internalLoader = loader.getCore().loader;
8849
+ const resolvedName = loader.resolveSiteName(cmdName);
8850
+ const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8851
+ if (site) {
8852
+ const pluginHandled = await executePluginChainStep({
8853
+ site,
8854
+ cmdName,
8855
+ cmdArgs,
8856
+ cmdStr,
8857
+ type,
8858
+ results,
8859
+ totalStart,
8860
+ session,
8861
+ sessionName
8862
+ });
8863
+ if (pluginHandled) return pluginHandled;
8864
+ continue;
8865
+ }
8866
+ const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8867
+ if (options?.frame && params._frame === void 0 && params.frame === void 0) {
8868
+ params._frame = options.frame;
8869
+ }
8870
+ if (cmdName === "goto" && params.url) {
8871
+ const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8872
+ if (!existing) {
8873
+ session = await createSession(sessionName, params.url, {
8874
+ cdpEndpoint: options?.cdpEndpoint
8875
+ });
8876
+ }
8877
+ }
8878
+ const result = await executeCommand2(cmdName, params, sessionName, {
8879
+ cdpEndpoint: options?.cdpEndpoint,
8880
+ skipCleanup: true
8881
+ });
8882
+ results.push({
8883
+ command: cmdName,
8884
+ raw: cmdStr,
8885
+ success: result.success,
8886
+ data: result.data,
8887
+ message: result.message,
8888
+ duration: 0,
8889
+ tips: result.tips,
8890
+ ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8891
+ });
8892
+ if (type === "and" && !result.success) {
8893
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
8894
+ }
8895
+ if (type === "or" && result.success) {
8896
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
8897
+ }
8898
+ }
8336
8899
  }
8337
- },
8338
- screenshot: {
8339
- name: "screenshot",
8340
- onAfterCommand: async (ctx) => {
8341
- try {
8342
- const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
8343
- if (!buf) return;
8344
- return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
8345
- } catch {
8346
- return;
8900
+ return {
8901
+ success: !results.some((result) => !result.success),
8902
+ steps: results,
8903
+ totalDuration: Date.now() - totalStart
8904
+ };
8905
+ } finally {
8906
+ }
8907
+ }
8908
+ function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
8909
+ return {
8910
+ success,
8911
+ steps,
8912
+ totalDuration: Date.now() - totalStart,
8913
+ stoppedAt,
8914
+ stoppedReason: reason
8915
+ };
8916
+ }
8917
+ async function executePluginChainStep(context) {
8918
+ const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
8919
+ const subCommand = cmdArgs[0];
8920
+ if (!subCommand) {
8921
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
8922
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
8923
+ return void 0;
8924
+ }
8925
+ const cmdEntry = site.getCommand(subCommand);
8926
+ if (!cmdEntry) {
8927
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
8928
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
8929
+ return void 0;
8930
+ }
8931
+ const pluginArgs = cmdArgs.slice(1);
8932
+ const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8933
+ if (cmdEntry.parameters) {
8934
+ const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8935
+ if (schemaCheck.success) {
8936
+ for (const [key, value] of Object.entries(schemaCheck.data)) {
8937
+ if (!(key in pluginParams)) pluginParams[key] = value;
8347
8938
  }
8348
8939
  }
8349
- },
8350
- recorder: {
8351
- name: "recorder",
8352
- onAfterCommand: async (ctx) => {
8353
- const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
8354
- logs.push({
8355
- timestamp: Date.now(),
8356
- command: ctx.command,
8357
- params: JSON.parse(JSON.stringify(ctx.params)),
8358
- duration: ctx.duration
8940
+ }
8941
+ const pluginCtx = {
8942
+ args: pluginArgs,
8943
+ options: pluginParams,
8944
+ cwd: process.cwd(),
8945
+ page: session.page,
8946
+ browser: session.context.browser(),
8947
+ browserContext: session.context,
8948
+ sessionId: session.id,
8949
+ storage: getPluginStorage(cmdName),
8950
+ output: { mode: "text", showTips: false, color: false, emoji: false },
8951
+ error: (message) => {
8952
+ throw new Error(message);
8953
+ },
8954
+ config: {},
8955
+ site,
8956
+ cliName: "xbrowser",
8957
+ tips: new TipCollector2()
8958
+ };
8959
+ const start = Date.now();
8960
+ try {
8961
+ const loginGuard = await checkPluginLoginRequired({
8962
+ site,
8963
+ command: cmdEntry,
8964
+ commandName: subCommand,
8965
+ ctx: pluginCtx,
8966
+ page: session.page,
8967
+ sessionName
8968
+ });
8969
+ if (!loginGuard.ok) {
8970
+ const duration2 = Date.now() - start;
8971
+ const data2 = loginGuard.data ?? null;
8972
+ recordArchive(session.id, sessionName, {
8973
+ step: results.length,
8974
+ command: `${cmdName} ${subCommand}`,
8975
+ params: pluginParams,
8976
+ result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8977
+ toolCalls: [],
8978
+ duration: duration2,
8979
+ timestamp: start
8359
8980
  });
8360
- Reflect.set(ctx, "__commandLogs", logs);
8981
+ results.push({
8982
+ command: `${cmdName} ${subCommand}`,
8983
+ raw: cmdStr,
8984
+ success: false,
8985
+ data: data2,
8986
+ message: loginGuard.message,
8987
+ tips: normalizeTips7(loginGuard.tips),
8988
+ duration: duration2
8989
+ });
8990
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
8361
8991
  return void 0;
8362
8992
  }
8363
- }
8364
- };
8365
- var customHooks = {};
8366
- async function loadHooks() {
8367
- const env = process.env.XBROWSER_HOOKS;
8368
- if (!env) return [];
8369
- const names = env.split(",").map((n) => n.trim()).filter(Boolean);
8370
- if (names.length === 0) return [];
8371
- const hooks = [];
8372
- for (const name of names) {
8373
- const hook = HOOK_REGISTRY[name];
8374
- if (hook) {
8375
- hooks.push(hook);
8376
- continue;
8993
+ const hooks = await loadHooks();
8994
+ if (hooks.length > 0) {
8995
+ await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
8377
8996
  }
8378
- const customFactory = customHooks[name];
8379
- if (customFactory) {
8380
- const customHook = await customFactory();
8381
- if (customHook) hooks.push(customHook);
8997
+ const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8998
+ const duration = Date.now() - start;
8999
+ let hookOutputs;
9000
+ if (hooks.length > 0) {
9001
+ const outputs = [];
9002
+ for (const hook of hooks) {
9003
+ const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
9004
+ if (output) outputs.push({ _hook: hook.name, ...output });
9005
+ }
9006
+ if (outputs.length > 0) hookOutputs = outputs;
8382
9007
  }
9008
+ const data = raw?.data ?? raw;
9009
+ recordArchive(session.id, sessionName, {
9010
+ step: results.length,
9011
+ command: `${cmdName} ${subCommand}`,
9012
+ params: pluginParams,
9013
+ result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9014
+ toolCalls: [],
9015
+ duration,
9016
+ timestamp: start
9017
+ });
9018
+ results.push({
9019
+ command: `${cmdName} ${subCommand}`,
9020
+ raw: cmdStr,
9021
+ ...ok32(data),
9022
+ duration,
9023
+ ...hookOutputs ? { hookOutputs } : {}
9024
+ });
9025
+ if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9026
+ } catch (error) {
9027
+ const duration = Date.now() - start;
9028
+ const message = errMsg(error);
9029
+ recordArchive(session.id, sessionName, {
9030
+ step: results.length,
9031
+ command: `${cmdName} ${subCommand}`,
9032
+ params: pluginParams,
9033
+ result: { success: false, data: null, message, tips: [] },
9034
+ toolCalls: [],
9035
+ duration,
9036
+ timestamp: start
9037
+ });
9038
+ results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
9039
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
8383
9040
  }
8384
- return hooks;
9041
+ return void 0;
8385
9042
  }
8386
9043
 
8387
9044
  // src/executor.ts
8388
- import { homedir as homedir6 } from "os";
8389
- import { join as join8 } from "path";
8390
9045
  function levenshtein(a, b) {
8391
9046
  const m = a.length, n = b.length;
8392
9047
  const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
@@ -8394,63 +9049,11 @@ function levenshtein(a, b) {
8394
9049
  for (let j = 0; j <= n; j++) dp[0][j] = j;
8395
9050
  for (let i = 1; i <= m; i++) {
8396
9051
  for (let j = 1; j <= n; j++) {
8397
- dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
9052
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j - 1]);
8398
9053
  }
8399
9054
  }
8400
9055
  return dp[m][n];
8401
9056
  }
8402
- var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8403
- var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8404
- var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8405
- var storageCache = /* @__PURE__ */ new Map();
8406
- function getPluginStorage(pluginName) {
8407
- if (!storageCache.has(pluginName)) {
8408
- storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
8409
- }
8410
- return storageCache.get(pluginName);
8411
- }
8412
- var archiveInitialized = false;
8413
- function ensureArchiveInit() {
8414
- if (!archiveInitialized) {
8415
- try {
8416
- configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
8417
- } catch {
8418
- }
8419
- archiveInitialized = true;
8420
- }
8421
- }
8422
- function recordArchive(sessionId, sessionName, entry) {
8423
- if (!sessionId) return;
8424
- try {
8425
- ensureArchiveInit();
8426
- appendCommandToArchive(sessionId, sessionName, entry);
8427
- } catch {
8428
- }
8429
- }
8430
- async function guardCheck(commandName) {
8431
- try {
8432
- const loader = await getPluginLoader();
8433
- const core = loader.getCore();
8434
- return checkGuard(core, commandName, process.env);
8435
- } catch {
8436
- return null;
8437
- }
8438
- }
8439
- function errorResult(message) {
8440
- return { ...fail17(message), duration: 0 };
8441
- }
8442
- function tipsToMessages(tips) {
8443
- if (!tips || tips.length === 0) return [];
8444
- return tips.map((t) => typeof t === "string" ? t : t.message);
8445
- }
8446
- var wsServer = null;
8447
- function streamCommandEvent(sessionId, message) {
8448
- if (!wsServer || !wsServer.getRunning()) return;
8449
- wsServer.broadcastToSession(sessionId, {
8450
- type: "command",
8451
- data: message
8452
- });
8453
- }
8454
9057
  async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
8455
9058
  const guardResult = await guardCheck(commandName);
8456
9059
  if (guardResult?.blocked) {
@@ -8498,8 +9101,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8498
9101
  if (knownPlugins.includes(commandName)) {
8499
9102
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8500
9103
  }
9104
+ const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
9105
+ recordMistake({
9106
+ category: classifyFailure(message).code,
9107
+ command: commandName,
9108
+ message,
9109
+ context: { sessionName, params }
9110
+ });
8501
9111
  return errorResult(
8502
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
9112
+ message
8503
9113
  );
8504
9114
  }
8505
9115
  const _target = params._target;
@@ -8512,9 +9122,14 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8512
9122
  const { _tabIndex: _u, ...rest } = params;
8513
9123
  params = rest;
8514
9124
  }
9125
+ const _frame = params._frame;
9126
+ if (_frame) {
9127
+ const { _frame: _u, ...rest } = params;
9128
+ params = rest;
9129
+ }
8515
9130
  let targetPageOverride = null;
8516
9131
  if (_target && extraOpts?.cdpEndpoint) {
8517
- const { findTargetPage } = await import("./browser-NYYCR4O7.js");
9132
+ const { findTargetPage } = await import("./browser-I2NLJN2A.js");
8518
9133
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8519
9134
  if (!targetPageOverride) {
8520
9135
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8532,7 +9147,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8532
9147
  }
8533
9148
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8534
9149
  const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
8535
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
9150
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8536
9151
  const result = await forwardExec(
8537
9152
  commandName,
8538
9153
  params,
@@ -8578,6 +9193,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8578
9193
  browserContext: session?.context,
8579
9194
  sessionId: session?.id,
8580
9195
  cdpEndpoint: session?.cdpEndpoint || extraOpts?.cdpEndpoint,
9196
+ frame: _frame,
8581
9197
  args: [],
8582
9198
  options: {},
8583
9199
  cwd: process.cwd(),
@@ -8594,7 +9210,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8594
9210
  config: {},
8595
9211
  site: new NoopSiteInstance(),
8596
9212
  cliName: "xbrowser",
8597
- tips: new TipCollector2()
9213
+ tips: new TipCollector3()
8598
9214
  };
8599
9215
  attachDetectAntiBot(ctx);
8600
9216
  if (_tabIndex !== void 0 && session?.context) {
@@ -8626,7 +9242,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8626
9242
  const cache = /* @__PURE__ */ new Map();
8627
9243
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8628
9244
  if (resolved.tips.length > 0) {
8629
- refTips = normalizeTips7(resolved.tips);
9245
+ refTips = normalizeTips8(resolved.tips);
8630
9246
  params = resolved.params;
8631
9247
  }
8632
9248
  }
@@ -8694,11 +9310,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8694
9310
  }
8695
9311
  const merged = [
8696
9312
  ...raw.tips || [],
8697
- ...normalizeTips7(smartTips),
8698
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
9313
+ ...normalizeTips8(smartTips),
9314
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
8699
9315
  ...refTips
8700
9316
  ];
8701
9317
  const isSuccess = raw.success !== false;
9318
+ if (!isSuccess) {
9319
+ recordMistake({
9320
+ category: classifyFailure(raw.message).code,
9321
+ command: commandName,
9322
+ message: raw.message ?? "unknown command failure",
9323
+ context: { sessionName, params }
9324
+ });
9325
+ }
8702
9326
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
8703
9327
  recordArchive(session?.id, sessionName, {
8704
9328
  step: 0,
@@ -8710,7 +9334,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8710
9334
  timestamp: start
8711
9335
  });
8712
9336
  if (isSuccess) {
8713
- return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9337
+ return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8714
9338
  }
8715
9339
  const fc = classifyFailure(raw.message);
8716
9340
  return {
@@ -8723,7 +9347,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8723
9347
  ...hookOutputs ? { hookOutputs } : {}
8724
9348
  };
8725
9349
  }
8726
- const smartTipNormalized = normalizeTips7(smartTips);
9350
+ const smartTipNormalized = normalizeTips8(smartTips);
8727
9351
  recordArchive(session?.id, sessionName, {
8728
9352
  step: 0,
8729
9353
  command: commandName,
@@ -8733,14 +9357,20 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8733
9357
  duration,
8734
9358
  timestamp: start
8735
9359
  });
8736
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9360
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8737
9361
  } catch (err) {
8738
9362
  const end = Date.now();
8739
9363
  const duration = end - start;
8740
9364
  const errorMessage = errMsg(err);
9365
+ recordMistake({
9366
+ category: classifyFailure(errorMessage).code,
9367
+ command: commandName,
9368
+ message: errorMessage,
9369
+ context: { sessionName, params }
9370
+ });
8741
9371
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8742
9372
  try {
8743
- const { attemptRecovery } = await import("./recovery-EBKORYEU.js");
9373
+ const { attemptRecovery } = await import("./recovery-JFGV3DBX.js");
8744
9374
  const recovery = await attemptRecovery(
8745
9375
  session.page,
8746
9376
  sessionName,
@@ -8778,301 +9408,33 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8778
9408
  duration,
8779
9409
  timestamp: start
8780
9410
  });
8781
- return { ...fail17(errorMessage), duration };
9411
+ return { ...fail19(errorMessage), duration };
8782
9412
  } finally {
8783
9413
  }
8784
9414
  }
8785
- async function executeChain(input, options) {
8786
- const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8787
- const sessionName = options?.sessionName || "default";
8788
- const results = [];
8789
- const totalStart = Date.now();
8790
- let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8791
- if (!session) {
8792
- const launchOpts = {};
8793
- if (options?.cdpEndpoint) {
8794
- launchOpts.cdpEndpoint = options.cdpEndpoint;
8795
- }
8796
- session = await createSession(sessionName, void 0, launchOpts);
8797
- saveSessionDiskMeta(sessionName, {
8798
- id: session.id,
8799
- name: sessionName,
8800
- url: session.page.url(),
8801
- createdAt: session.createdAt,
8802
- cdpEndpoint: session.cdpEndpoint
8803
- });
8804
- }
8805
- try {
8806
- for (const pipeline of pipelines) {
8807
- const { type, pipeline: commands } = pipeline;
8808
- for (const cmdStr of commands) {
8809
- if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8810
- await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
8811
- }
8812
- const parts = splitCommand(cmdStr);
8813
- if (parts.length === 0) continue;
8814
- const cmdName = parts[0];
8815
- const cmdArgs = parts.slice(1);
8816
- const loader = await getPluginLoader();
8817
- const internalLoader = loader.getCore().loader;
8818
- const resolvedName = loader.resolveSiteName(cmdName);
8819
- const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8820
- if (site) {
8821
- const subCommand = cmdArgs[0];
8822
- if (!subCommand) {
8823
- results.push({
8824
- command: cmdName,
8825
- raw: cmdStr,
8826
- ...fail17(`Plugin "${cmdName}" requires a sub-command`),
8827
- duration: 0
8828
- });
8829
- if (type === "and") {
8830
- return {
8831
- success: false,
8832
- steps: results,
8833
- totalDuration: Date.now() - totalStart,
8834
- stoppedAt: results.length,
8835
- stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
8836
- };
8837
- }
8838
- continue;
8839
- }
8840
- const cmdEntry = site.getCommand(subCommand);
8841
- if (!cmdEntry) {
8842
- results.push({
8843
- command: cmdName,
8844
- raw: cmdStr,
8845
- ...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
8846
- duration: 0
8847
- });
8848
- if (type === "and") {
8849
- return {
8850
- success: false,
8851
- steps: results,
8852
- totalDuration: Date.now() - totalStart,
8853
- stoppedAt: results.length,
8854
- stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
8855
- };
8856
- }
8857
- continue;
8858
- }
8859
- const pluginArgs = cmdArgs.slice(1);
8860
- let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8861
- if (cmdEntry.parameters) {
8862
- const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8863
- if (schemaCheck.success) {
8864
- for (const [k, v] of Object.entries(schemaCheck.data)) {
8865
- if (!(k in pluginParams)) pluginParams[k] = v;
8866
- }
8867
- }
8868
- }
8869
- const pluginCtx = {
8870
- args: pluginArgs,
8871
- options: pluginParams,
8872
- cwd: process.cwd(),
8873
- page: session.page,
8874
- browser: session.context.browser(),
8875
- browserContext: session.context,
8876
- sessionId: session.id,
8877
- storage: getPluginStorage(cmdName),
8878
- output: { mode: "text", showTips: false, color: false, emoji: false },
8879
- error: (msg) => {
8880
- throw new Error(msg);
8881
- },
8882
- config: {},
8883
- site,
8884
- cliName: "xbrowser",
8885
- tips: new TipCollector2()
8886
- };
8887
- const start2 = Date.now();
8888
- try {
8889
- const loginGuard = await checkPluginLoginRequired({
8890
- site,
8891
- command: cmdEntry,
8892
- commandName: subCommand,
8893
- ctx: pluginCtx,
8894
- page: session?.page,
8895
- sessionName
8896
- });
8897
- if (!loginGuard.ok) {
8898
- const duration3 = Date.now() - start2;
8899
- const data2 = loginGuard.data ?? null;
8900
- recordArchive(session.id, sessionName, {
8901
- step: results.length,
8902
- command: `${cmdName} ${subCommand}`,
8903
- params: pluginParams,
8904
- result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8905
- toolCalls: [],
8906
- duration: duration3,
8907
- timestamp: start2
8908
- });
8909
- results.push({
8910
- command: `${cmdName} ${subCommand}`,
8911
- raw: cmdStr,
8912
- success: false,
8913
- data: data2,
8914
- message: loginGuard.message,
8915
- tips: normalizeTips7(loginGuard.tips),
8916
- duration: duration3
8917
- });
8918
- if (type === "and") {
8919
- return {
8920
- success: false,
8921
- steps: results,
8922
- totalDuration: Date.now() - totalStart,
8923
- stoppedAt: results.length,
8924
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
8925
- };
8926
- }
8927
- continue;
8928
- }
8929
- const hooks = await loadHooks();
8930
- if (hooks.length > 0) {
8931
- await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
8932
- }
8933
- const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8934
- const duration2 = Date.now() - start2;
8935
- let hookOutputs;
8936
- if (hooks.length > 0) {
8937
- const outputs = [];
8938
- for (const h of hooks) {
8939
- const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
8940
- if (output) outputs.push({ _hook: h.name, ...output });
8941
- }
8942
- if (outputs.length > 0) hookOutputs = outputs;
8943
- }
8944
- const data = raw?.data ?? raw;
8945
- recordArchive(session.id, sessionName, {
8946
- step: results.length,
8947
- command: `${cmdName} ${subCommand}`,
8948
- params: pluginParams,
8949
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
8950
- toolCalls: [],
8951
- duration: duration2,
8952
- timestamp: start2
8953
- });
8954
- results.push({
8955
- command: `${cmdName} ${subCommand}`,
8956
- raw: cmdStr,
8957
- ...ok32(data),
8958
- duration: duration2,
8959
- ...hookOutputs ? { hookOutputs } : {}
8960
- });
8961
- if (type === "or") {
8962
- return {
8963
- success: true,
8964
- steps: results,
8965
- totalDuration: Date.now() - totalStart,
8966
- stoppedAt: results.length,
8967
- stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
8968
- };
8969
- }
8970
- } catch (err) {
8971
- const duration2 = Date.now() - start2;
8972
- const errorMessage = errMsg(err);
8973
- recordArchive(session.id, sessionName, {
8974
- step: results.length,
8975
- command: `${cmdName} ${subCommand}`,
8976
- params: pluginParams,
8977
- result: { success: false, data: null, message: errorMessage, tips: [] },
8978
- toolCalls: [],
8979
- duration: duration2,
8980
- timestamp: start2
8981
- });
8982
- results.push({
8983
- command: `${cmdName} ${subCommand}`,
8984
- raw: cmdStr,
8985
- ...fail17(errorMessage),
8986
- duration: duration2
8987
- });
8988
- if (type === "and") {
8989
- return {
8990
- success: false,
8991
- steps: results,
8992
- totalDuration: Date.now() - totalStart,
8993
- stoppedAt: results.length,
8994
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
8995
- };
8996
- }
8997
- }
8998
- continue;
8999
- }
9000
- const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
9001
- if (cmdName === "goto" && params.url) {
9002
- const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
9003
- if (!existing2) {
9004
- session = await createSession(sessionName, params.url, {
9005
- cdpEndpoint: options?.cdpEndpoint
9006
- });
9007
- }
9008
- }
9009
- const start = Date.now();
9010
- const result = await executeCommand(cmdName, params, sessionName, {
9011
- cdpEndpoint: options?.cdpEndpoint,
9012
- skipCleanup: true
9013
- // executeChain's finally handles cleanup
9014
- });
9015
- const duration = Date.now() - start;
9016
- const stepResult = {
9017
- command: cmdName,
9018
- raw: cmdStr,
9019
- success: result.success,
9020
- data: result.data,
9021
- message: result.message,
9022
- duration,
9023
- tips: result.tips,
9024
- ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
9025
- };
9026
- results.push(stepResult);
9027
- if (type === "and" && !result.success) {
9028
- return {
9029
- success: false,
9030
- steps: results,
9031
- totalDuration: Date.now() - totalStart,
9032
- stoppedAt: results.length,
9033
- stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
9034
- };
9035
- }
9036
- if (type === "or" && result.success) {
9037
- return {
9038
- success: true,
9039
- steps: results,
9040
- totalDuration: Date.now() - totalStart,
9041
- stoppedAt: results.length,
9042
- stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
9043
- };
9044
- }
9045
- }
9046
- }
9047
- const anyFailed = results.some((r) => !r.success);
9048
- return {
9049
- success: !anyFailed,
9050
- steps: results,
9051
- totalDuration: Date.now() - totalStart
9052
- };
9053
- } finally {
9054
- }
9415
+ async function executeChain2(input, options) {
9416
+ return executeChain(input, options, executeCommand);
9055
9417
  }
9056
9418
  function isChainInput(input) {
9057
9419
  return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
9058
9420
  }
9059
9421
 
9060
9422
  export {
9061
- parsePluginParams,
9062
9423
  createStubContext,
9063
9424
  getCommand,
9064
9425
  getAllCommands,
9065
9426
  getCommandNames,
9066
9427
  attachDetectAntiBot,
9428
+ loadHooks,
9067
9429
  readJsonFile,
9068
9430
  PluginMetadataParser,
9069
9431
  ensurePluginDependencies,
9070
9432
  XBrowserPluginLoader,
9071
9433
  getPluginLoader,
9072
- checkPluginLoginRequired,
9073
- loadHooks,
9074
9434
  getPluginStorage,
9435
+ checkPluginLoginRequired,
9436
+ parsePluginParams,
9075
9437
  executeCommand,
9076
- executeChain,
9438
+ executeChain2 as executeChain,
9077
9439
  isChainInput
9078
9440
  };