@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
@@ -3,8 +3,9 @@ import {
3
3
  formatDetectionMessage
4
4
  } from "./chunk-JKVUFP3G.js";
5
5
  import {
6
- getPluginLoader
7
- } from "./chunk-OSZNJT4U.js";
6
+ getPluginLoader,
7
+ recordMistake
8
+ } from "./chunk-LM32MNBB.js";
8
9
  import {
9
10
  version
10
11
  } from "./chunk-43TEMG4U.js";
@@ -14,7 +15,7 @@ import {
14
15
  import {
15
16
  ScreencastCapturer,
16
17
  resolveScreenshotsDir
17
- } from "./chunk-HBMEFSTB.js";
18
+ } from "./chunk-QCV2PI7U.js";
18
19
  import "./chunk-CG3D3CHY.js";
19
20
  import {
20
21
  commandLogStore,
@@ -23,7 +24,7 @@ import {
23
24
  } from "./chunk-VEDJ5XSQ.js";
24
25
  import {
25
26
  SessionRecorder
26
- } from "./chunk-V6KGBU5J.js";
27
+ } from "./chunk-VYTQLZAX.js";
27
28
  import {
28
29
  closeEphemeralContext,
29
30
  closeSessionByName,
@@ -38,10 +39,10 @@ import {
38
39
  resolveLaunchOpts,
39
40
  saveSessionDiskMeta,
40
41
  setActivePage
41
- } from "./chunk-3PUOISKE.js";
42
+ } from "./chunk-NINETOM4.js";
42
43
  import {
43
44
  createRuleEngine
44
- } from "./chunk-ME5FO5YV.js";
45
+ } from "./chunk-OCECE22C.js";
45
46
  import {
46
47
  queryJS
47
48
  } from "./chunk-A7NEA4PA.js";
@@ -49,8 +50,8 @@ import {
49
50
  rand,
50
51
  sleep,
51
52
  wheelDelta
52
- } from "./chunk-R3F4K2SB.js";
53
- import "./chunk-SEEWE5SJ.js";
53
+ } from "./chunk-SMYSNO4M.js";
54
+ import "./chunk-2KPI5GKP.js";
54
55
  import {
55
56
  errMsg
56
57
  } from "./chunk-GDKLH7ZY.js";
@@ -69,161 +70,15 @@ import {
69
70
  removeSession
70
71
  } from "@dyyz1993/xcli-core";
71
72
 
72
- // src/fail-codes.ts
73
- var FAIL_CODES = {
74
- selectorNotFound: "RETRYABLE: selector-not-found",
75
- pageNotReady: "RETRYABLE: page-not-ready",
76
- elementGone: "RETRYABLE: element-gone",
77
- inputNotRetained: "RETRYABLE: input-not-retained",
78
- captcha: "HUMAN: captcha",
79
- loginWall: "HUMAN: login-wall",
80
- permissionDenied: "FATAL: permission-denied",
81
- targetGone: "FATAL: target-gone",
82
- unknown: "FATAL: unknown"
83
- };
84
- function classifyFailure(message) {
85
- const msg = (message || "").toLowerCase();
86
- const pick = (code) => ({
87
- code,
88
- level: code.split(":")[0],
89
- message: message || code
90
- });
91
- if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
92
- if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
93
- if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
94
- if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
95
- return pick(FAIL_CODES.selectorNotFound);
96
- if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
97
- if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
98
- if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
99
- return pick(FAIL_CODES.targetGone);
100
- return pick(FAIL_CODES.unknown);
101
- }
102
-
103
73
  // src/executor.ts
104
74
  import {
105
- ok as ok32,
106
- fail as fail17,
75
+ ok as ok33,
76
+ fail as fail19,
107
77
  isCommandResult,
108
- CompositeStorage as CompositeStorage2,
109
- TipCollector as TipCollector2,
110
- normalizeTips as normalizeTips7,
111
- configureArchiveStore,
112
- appendCommandToArchive,
113
- checkGuard,
114
- unquote as unquote2
78
+ normalizeTips as normalizeTips8,
79
+ TipCollector as TipCollector3
115
80
  } from "@dyyz1993/xcli-core";
116
81
 
117
- // src/utils/positional-params.ts
118
- import { unquote } from "@dyyz1993/xcli-core";
119
- function getTypeName(field) {
120
- return field?._def?.typeName;
121
- }
122
- function unwrapField(field) {
123
- const typeName = getTypeName(field);
124
- if (typeName === "ZodOptional" || typeName === "ZodDefault") {
125
- const innerType = field?._def?.innerType;
126
- return unwrapField(innerType);
127
- }
128
- return field;
129
- }
130
- function isOptionalNumber(field) {
131
- const typeName = getTypeName(field);
132
- return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
133
- }
134
- function coerceValue(raw, field) {
135
- const inner = unwrapField(field);
136
- const optionalNum = isOptionalNumber(field);
137
- const innerTypeName = getTypeName(inner);
138
- if (innerTypeName === "ZodString") {
139
- return { value: unquote(raw), skip: false };
140
- }
141
- if (innerTypeName === "ZodNumber") {
142
- const parsed = Number(raw);
143
- if (isNaN(parsed)) {
144
- if (optionalNum) return { value: void 0, skip: true };
145
- return { value: raw, skip: false };
146
- }
147
- return { value: parsed, skip: false };
148
- }
149
- if (innerTypeName === "ZodBoolean") {
150
- if (raw === "true" || raw === "1") return { value: true, skip: false };
151
- if (raw === "false" || raw === "0") return { value: false, skip: false };
152
- return { value: raw, skip: false };
153
- }
154
- return { value: unquote(raw), skip: false };
155
- }
156
- function mapPositionalValues(schema, positional, existing) {
157
- const result = { ...existing };
158
- if (!schema || typeof schema !== "object") return result;
159
- const shape = schema.shape;
160
- if (!shape || typeof shape !== "object") return result;
161
- const keys = Object.keys(shape);
162
- let pIdx = 0;
163
- for (const key of keys) {
164
- if (pIdx >= positional.length) break;
165
- if (result[key] !== void 0) {
166
- pIdx++;
167
- continue;
168
- }
169
- const field = shape[key];
170
- const raw = positional[pIdx];
171
- const { value, skip } = coerceValue(raw, field);
172
- if (skip) continue;
173
- result[key] = value;
174
- pIdx++;
175
- }
176
- return result;
177
- }
178
-
179
- // src/utils/plugin-params.ts
180
- function parsePluginParams(args, schema, base = {}) {
181
- const params = { ...base };
182
- const positionalValues = [];
183
- for (let i = 0; i < args.length; i++) {
184
- if (args[i] === "--" && args[i + 1]) {
185
- try {
186
- Object.assign(params, JSON.parse(args[i + 1]));
187
- } catch {
188
- }
189
- break;
190
- }
191
- if (args[i].startsWith("--")) {
192
- const key = args[i].slice(2);
193
- const value = args[i + 1];
194
- if (value && !value.startsWith("-")) {
195
- if (value === "true") params[key] = true;
196
- else if (value === "false") params[key] = false;
197
- else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
198
- else {
199
- try {
200
- const parsed = JSON.parse(value);
201
- if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
202
- params[key] = parsed;
203
- } else {
204
- params[key] = value;
205
- }
206
- } catch {
207
- params[key] = value;
208
- }
209
- }
210
- i++;
211
- } else {
212
- params[key] = true;
213
- }
214
- } else if (!args[i].startsWith("-")) {
215
- positionalValues.push(args[i]);
216
- }
217
- }
218
- Object.assign(params, mapPositionalValues(schema, positionalValues, params));
219
- const result = {};
220
- for (const [k, v] of Object.entries(params)) {
221
- const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
222
- result[camelKey] = v;
223
- }
224
- return result;
225
- }
226
-
227
82
  // src/utils/stub-context.ts
228
83
  import { join } from "path";
229
84
  import { homedir } from "os";
@@ -285,6 +140,7 @@ function registerCommand(def) {
285
140
  parameters: def.parameters,
286
141
  result: def.result,
287
142
  selectorParams: def.selectorParams,
143
+ examples: def.examples,
288
144
  handler: def.handler
289
145
  };
290
146
  registry.set(cmd.name, cmd);
@@ -516,14 +372,23 @@ var clickCommand = registerCommand({
516
372
  clickCount: z2.number().optional(),
517
373
  delay: z2.number().optional(),
518
374
  waitCaptcha: z2.boolean().optional().default(false).describe("\u70B9\u51FB\u540E\u68C0\u6D4B captcha \u5E76\u7B49\u5F85\u89E3\u51B3"),
519
- waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09")
375
+ waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09"),
376
+ 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")
520
377
  }),
521
378
  result: z2.object({
522
379
  selector: z2.string(),
523
380
  newTab: z2.object({ url: z2.string(), title: z2.string() }).optional(),
524
- captcha: z2.any().optional()
381
+ captcha: z2.any().optional(),
382
+ frame: z2.string().optional(),
383
+ x: z2.number().optional(),
384
+ y: z2.number().optional()
525
385
  }),
526
386
  handler: async (p, ctx) => {
387
+ const frameTarget = p.frame ?? ctx.frame;
388
+ if (frameTarget) {
389
+ const { x, y } = await ctx.page.clickInFrame(frameTarget, p.selector);
390
+ return ok2({ selector: p.selector, frame: frameTarget, x, y });
391
+ }
527
392
  let detectedNewPage;
528
393
  let cleanup;
529
394
  if (ctx.browserContext?.on) {
@@ -614,15 +479,22 @@ var fillCommand = registerCommand({
614
479
  parameters: z2.object({
615
480
  selector: z2.string(),
616
481
  value: z2.string(),
617
- clear: z2.boolean().optional()
482
+ clear: z2.boolean().optional(),
483
+ 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")
618
484
  }),
619
485
  result: z2.object({
620
486
  selector: z2.string(),
621
487
  value: z2.string(),
622
488
  cleared: z2.boolean(),
623
- reactMode: z2.boolean().optional()
489
+ reactMode: z2.boolean().optional(),
490
+ frame: z2.string().optional()
624
491
  }),
625
492
  handler: async (p, ctx) => {
493
+ const frameTarget = p.frame ?? ctx.frame;
494
+ if (frameTarget) {
495
+ const { value } = await ctx.page.fillInFrame(frameTarget, p.selector, p.value);
496
+ return ok2({ selector: p.selector, value, cleared: true, frame: frameTarget });
497
+ }
626
498
  const page = ctx.page;
627
499
  const shouldClear = p.clear !== false;
628
500
  if (shouldClear) {
@@ -809,15 +681,22 @@ var textCommand = registerCommand({
809
681
  scope: "page",
810
682
  selectorParams: ["selector"],
811
683
  parameters: z3.object({
812
- selector: z3.string().optional()
684
+ selector: z3.string().optional(),
685
+ 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")
813
686
  }),
814
- result: z3.object({ text: z3.string() }),
687
+ result: z3.object({ text: z3.string(), frame: z3.string().optional() }),
815
688
  handler: async (p, ctx) => {
689
+ const frameTarget = p.frame ?? ctx.frame;
690
+ if (frameTarget) {
691
+ const expr = p.selector ? `(() => { const el = document.querySelector(${JSON.stringify(p.selector)}); return el ? (el.textContent ?? '').trim() : null; })()` : `(document.body?.innerText || '').trim()`;
692
+ const text2 = await ctx.page.evaluateInFrame(frameTarget, expr);
693
+ return ok3({ text: text2 || "", frame: frameTarget });
694
+ }
816
695
  if (p.selector) {
817
696
  const text2 = await ctx.page.textContent(p.selector);
818
697
  return ok3({ text: text2 || "" });
819
698
  }
820
- const text = await ctx.page.evaluate(() => document.body?.innerText || "");
699
+ const text = await ctx.page.evaluate(() => (document.body?.innerText || "").trim());
821
700
  return ok3({ text });
822
701
  }
823
702
  });
@@ -941,43 +820,64 @@ import { z as z6 } from "zod";
941
820
  import { ok as ok6 } from "@dyyz1993/xcli-core";
942
821
  var mouseCommand = registerCommand({
943
822
  name: "mouse",
944
- description: "Control the mouse (move, click, etc.)",
823
+ 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)",
945
824
  scope: "page",
946
825
  parameters: z6.object({
947
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
826
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
948
827
  x: z6.coerce.number(),
949
828
  y: z6.coerce.number(),
829
+ "delta-x": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u6A2A\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u53F3\uFF09"),
830
+ "delta-y": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u7EB5\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u4E0B\uFF09"),
950
831
  button: z6.enum(["left", "right", "middle"]).optional(),
951
- steps: z6.coerce.number().optional()
832
+ steps: z6.coerce.number().optional(),
833
+ 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")
952
834
  }),
953
835
  result: z6.object({
954
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
836
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
955
837
  x: z6.number(),
956
838
  y: z6.number()
957
839
  }),
958
840
  handler: async (p, ctx) => {
959
841
  const button = p.button || "left";
960
- switch (p.action) {
961
- case "move":
962
- await ctx.page.mouse.move(p.x, p.y, { steps: p.steps || 1 });
963
- break;
964
- case "down":
965
- await ctx.page.mouse.move(p.x, p.y);
966
- await ctx.page.mouse.down({ button });
967
- break;
968
- case "up":
969
- await ctx.page.mouse.move(p.x, p.y);
970
- await ctx.page.mouse.up({ button });
971
- break;
972
- case "click":
973
- await ctx.page.mouse.click(p.x, p.y, { button });
974
- break;
975
- case "dblclick":
976
- await ctx.page.mouse.dblclick(p.x, p.y, { button });
977
- break;
978
- case "drag":
979
- await ctx.page.mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
980
- break;
842
+ const frame = p.frame ?? ctx.frame;
843
+ const dispatch = async (mouse) => {
844
+ switch (p.action) {
845
+ case "move":
846
+ await mouse.move(p.x, p.y, { steps: p.steps || 1 });
847
+ break;
848
+ case "down":
849
+ await mouse.move(p.x, p.y);
850
+ await mouse.down({ button });
851
+ break;
852
+ case "up":
853
+ await mouse.move(p.x, p.y);
854
+ await mouse.up({ button });
855
+ break;
856
+ case "click":
857
+ await mouse.click(p.x, p.y, { button });
858
+ break;
859
+ case "dblclick":
860
+ await mouse.dblclick(p.x, p.y, { button });
861
+ break;
862
+ case "drag":
863
+ await mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
864
+ break;
865
+ case "wheel":
866
+ await mouse.wheelAt(p.x, p.y, Number(p["delta-x"] ?? 0), Number(p["delta-y"] ?? 0));
867
+ break;
868
+ }
869
+ };
870
+ if (frame) {
871
+ try {
872
+ await ctx.page.runFrameMouse(frame, dispatch);
873
+ } catch (err) {
874
+ if (p.action === "drag" && /session/i.test(String(err))) {
875
+ 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`);
876
+ }
877
+ throw err;
878
+ }
879
+ } else {
880
+ await dispatch(ctx.page.mouse);
981
881
  }
982
882
  return ok6({ action: p.action, x: p.x, y: p.y });
983
883
  }
@@ -1419,7 +1319,8 @@ var evaluateCommand = registerCommand({
1419
1319
  direction: "client\u2192browser"
1420
1320
  });
1421
1321
  engine.stop();
1422
- const result = p.frame ? await ctx.page.evaluateInFrame(p.frame, expression) : await ctx.page.evaluate(expression);
1322
+ const frame = p.frame ?? ctx.frame;
1323
+ const result = frame ? await ctx.page.evaluateInFrame(frame, expression) : await ctx.page.evaluate(expression);
1423
1324
  const response = ok9({ result });
1424
1325
  if (decision && decision.severity === "danger") {
1425
1326
  response.tips = normalizeTips2([`${decision.suggestion}`]);
@@ -1848,24 +1749,98 @@ import { z as z16 } from "zod";
1848
1749
  import { ok as ok16, fail as fail7 } from "@dyyz1993/xcli-core";
1849
1750
  var framesCommand = registerCommand({
1850
1751
  name: "frames",
1851
- description: "List all frames in the current page",
1752
+ 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)",
1852
1753
  scope: "page",
1853
1754
  result: z16.object({
1854
1755
  frames: z16.array(z16.object({
1855
1756
  index: z16.number(),
1856
1757
  name: z16.string().nullable(),
1857
- url: z16.string()
1858
- }))
1758
+ url: z16.string(),
1759
+ oopif: z16.boolean().optional(),
1760
+ targetId: z16.string().optional(),
1761
+ parentUrl: z16.string().nullable().optional(),
1762
+ depth: z16.number().nullable().optional()
1763
+ })),
1764
+ warnings: z16.array(z16.string()).optional()
1859
1765
  }),
1860
1766
  handler: async (_p, ctx) => {
1861
1767
  const discover = ctx.page.discoverFrames;
1862
1768
  const rawFrames = discover ? await discover.call(ctx.page) : ctx.page.frames();
1769
+ const mainUrl = ctx.page.url();
1863
1770
  const frameList = rawFrames.map((frame, index) => ({
1864
1771
  index,
1865
1772
  name: frame.name(),
1866
- url: frame.url()
1773
+ url: frame.url(),
1774
+ parentUrl: null,
1775
+ depth: null
1867
1776
  }));
1868
- return ok16({ frames: frameList });
1777
+ const norm = (u) => u.replace(/\/+$/, "");
1778
+ for (const e of frameList) {
1779
+ if (norm(e.url) === norm(mainUrl)) {
1780
+ e.parentUrl = null;
1781
+ e.depth = 0;
1782
+ }
1783
+ }
1784
+ if (typeof ctx.page.listFrameTargets === "function") {
1785
+ const targets = await ctx.page.listFrameTargets();
1786
+ const knownUrls = new Set(frameList.map((f) => f.url));
1787
+ for (const t of targets) {
1788
+ if (knownUrls.has(t.url)) continue;
1789
+ frameList.push({ index: frameList.length, name: null, url: t.url, oopif: true, targetId: t.targetId, parentUrl: null, depth: null });
1790
+ }
1791
+ }
1792
+ const warnings = [];
1793
+ try {
1794
+ const CHILDREN = `JSON.stringify([...document.querySelectorAll('iframe')].map(f=>({src:f.src||'',name:f.name||''})))`;
1795
+ const matchChild = (childSrc, frameUrl) => {
1796
+ const a = norm(childSrc);
1797
+ const b = norm(frameUrl);
1798
+ return Boolean(a && b && (a === b || a.includes(b) || b.includes(a)));
1799
+ };
1800
+ const childrenCache = /* @__PURE__ */ new Map();
1801
+ const childrenOf = async (url) => {
1802
+ const hit = childrenCache.get(url);
1803
+ if (hit) return hit;
1804
+ let out = [];
1805
+ try {
1806
+ const raw = norm(url) === norm(mainUrl) ? await ctx.page.evaluate(CHILDREN) : await ctx.page.evaluateInFrame(url, CHILDREN);
1807
+ out = JSON.parse(String(raw || "[]"));
1808
+ } catch {
1809
+ }
1810
+ childrenCache.set(url, out);
1811
+ return out;
1812
+ };
1813
+ let frontier = frameList.filter((e) => e.depth === 0).map((e) => ({ url: e.url, depth: 0 }));
1814
+ for (let depth = 0; frontier.length > 0 && frameList.some((e) => e.depth === null) && depth < 6; depth++) {
1815
+ const next = [];
1816
+ for (const node of frontier) {
1817
+ const kids = await childrenOf(node.url);
1818
+ if (kids.length === 0) continue;
1819
+ for (const e of frameList) {
1820
+ if (e.depth !== null) continue;
1821
+ if (kids.some((k) => matchChild(k.src, e.url))) {
1822
+ e.parentUrl = node.url;
1823
+ e.depth = node.depth + 1;
1824
+ next.push({ url: e.url, depth: e.depth });
1825
+ }
1826
+ }
1827
+ }
1828
+ frontier = next;
1829
+ }
1830
+ } catch {
1831
+ }
1832
+ const urls = frameList.map((e) => e.url);
1833
+ for (let i = 0; i < urls.length; i++) {
1834
+ for (let j = i + 1; j < urls.length; j++) {
1835
+ const a = urls[i];
1836
+ const b = urls[j];
1837
+ if (a && b && (a.includes(b) || b.includes(a))) {
1838
+ const shorter = a.includes(b) ? b : a;
1839
+ 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`);
1840
+ }
1841
+ }
1842
+ }
1843
+ return ok16({ frames: frameList, warnings });
1869
1844
  }
1870
1845
  });
1871
1846
  var frameCommand = registerCommand({
@@ -3424,8 +3399,26 @@ async function detectSpaRoutes(page, origin) {
3424
3399
  }
3425
3400
  } catch {
3426
3401
  }
3402
+ try {
3403
+ const vueRoutes = await page.evaluate((evalOrigin) => {
3404
+ const win = window;
3405
+ const vue3App = win.__vue_app__;
3406
+ const globalProperties = vue3App?.config?.globalProperties;
3407
+ let router = globalProperties?.$router;
3408
+ if (!router) {
3409
+ const root = document.querySelector("#app");
3410
+ const vm = root ? root.__vue__ : void 0;
3411
+ const rootVm = vm?.$root;
3412
+ router = vm?.$router ?? rootVm?.$router;
3413
+ }
3414
+ const routeList = router?.options?.routes ?? [];
3415
+ return routeList.filter((route) => route.path && route.path !== "/" && !route.path.includes(":") && !route.path.includes("*")).map((route) => `${evalOrigin.replace(/\/$/, "")}/#${route.path}`);
3416
+ }, origin);
3417
+ for (const route of vueRoutes) routeSet.add(route);
3418
+ } catch {
3419
+ }
3427
3420
  return Array.from(routeSet).map(
3428
- (p) => `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3421
+ (p) => p.startsWith("http") ? p : `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3429
3422
  );
3430
3423
  }
3431
3424
  function parseRobotsTxt(text) {
@@ -3618,7 +3611,14 @@ var crawlCommand = registerCommand({
3618
3611
  results.push({ url: seedPage.url(), title, content });
3619
3612
  const firstLinks = await extractLinks(seedPage, startUrl.origin);
3620
3613
  if (options.enableSpa) {
3621
- const spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3614
+ let spaRoutes = [];
3615
+ try {
3616
+ spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3617
+ } catch (error) {
3618
+ const message = error instanceof Error ? error.message : String(error);
3619
+ process.stderr.write(`[SPA] Route detection failed: ${message}
3620
+ `);
3621
+ }
3622
3622
  for (const route of spaRoutes) {
3623
3623
  try {
3624
3624
  const absNorm = normalizeUrl(stripHashAnchorQuery(route));
@@ -4487,6 +4487,8 @@ var networkCommand = registerCommand({
4487
4487
 
4488
4488
  // src/commands/ai-search-engines.ts
4489
4489
  import { z as z24 } from "zod";
4490
+
4491
+ // src/commands/ai-engine-configs.ts
4490
4492
  var ENGINE_CONFIGS = {
4491
4493
  deepseek: {
4492
4494
  key: "deepseek",
@@ -4739,6 +4741,8 @@ var ENGINE_CONFIGS = {
4739
4741
  sendButtonSelector: "button.send-btn"
4740
4742
  }
4741
4743
  };
4744
+
4745
+ // src/commands/ai-search-engines.ts
4742
4746
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
4743
4747
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
4744
4748
 
@@ -4763,25 +4767,6 @@ function getRefTarget(sessionKey2, ref) {
4763
4767
  if (!session || !target) return null;
4764
4768
  return { screenHash: session.screenHash, target };
4765
4769
  }
4766
- function inheritStableRefs(key, rawTargets) {
4767
- const prev = sessions.get(key);
4768
- if (!prev || prev.targets.size === 0) {
4769
- return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
4770
- }
4771
- const bySelector = /* @__PURE__ */ new Map();
4772
- let maxId = 0;
4773
- for (const [ref, target] of prev.targets) {
4774
- bySelector.set(target.selector, ref);
4775
- const id = Number(ref.slice(1));
4776
- if (Number.isFinite(id) && id > maxId) maxId = id;
4777
- }
4778
- let next = maxId + 1;
4779
- return rawTargets.map((target) => {
4780
- const inherited = bySelector.get(target.selector);
4781
- if (inherited) return { ...target, ref: inherited };
4782
- return { ...target, ref: `e${next++}` };
4783
- });
4784
- }
4785
4770
 
4786
4771
  // src/utils/resolve-selector.ts
4787
4772
  function buildElementSelector(el) {
@@ -5344,14 +5329,6 @@ async function observePage(page, sessionId, options = {}) {
5344
5329
  const direct = el.getAttribute("aria-label") || el.getAttribute("placeholder") || el.getAttribute("title") || input.value || el.textContent || "";
5345
5330
  return direct.replace(/\s+/g, " ").trim().slice(0, 120);
5346
5331
  }
5347
- function actionsFor(role, editable) {
5348
- const actions = [];
5349
- if (editable) actions.push("fill", "type");
5350
- if (role === "combobox") actions.push("select");
5351
- if (role === "checkbox" || role === "radio") actions.push("check");
5352
- actions.push("click", "hover");
5353
- return Array.from(new Set(actions));
5354
- }
5355
5332
  const selector = [
5356
5333
  "a[href]",
5357
5334
  "button",
@@ -5362,7 +5339,14 @@ async function observePage(page, sessionId, options = {}) {
5362
5339
  "label",
5363
5340
  "[role]",
5364
5341
  "[tabindex]",
5365
- '[contenteditable="true"]'
5342
+ '[contenteditable="true"]',
5343
+ // 非标准可交互控件:内联事件属性(agent-browser 基于 aria tree 完全不覆盖这类)。
5344
+ // 仅抓 HTML 显式声明 onclick/onmousedown 等的元素;addEventListener 绑定的无法静态发现。
5345
+ "[onclick]",
5346
+ "[onmousedown]",
5347
+ "[onmouseup]",
5348
+ "[onmouseover]",
5349
+ "[onkeydown]"
5366
5350
  ].join(",");
5367
5351
  const candidates = Array.from(document.querySelectorAll(selector));
5368
5352
  const seen = /* @__PURE__ */ new Set();
@@ -5386,13 +5370,10 @@ async function observePage(page, sessionId, options = {}) {
5386
5370
  role,
5387
5371
  name: textName(el),
5388
5372
  tag,
5389
- visible,
5390
5373
  enabled,
5391
5374
  editable,
5392
5375
  ...checked !== void 0 ? { checked } : {},
5393
- ...editable && input.value ? { value: input.value.slice(0, 120) } : {},
5394
- ...visible ? { box: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) } } : {},
5395
- actions: actionsFor(role, editable)
5376
+ ...editable && input.value ? { value: input.value.slice(0, 120) } : {}
5396
5377
  });
5397
5378
  if (targets2.length >= limit) break;
5398
5379
  }
@@ -5406,13 +5387,15 @@ async function observePage(page, sessionId, options = {}) {
5406
5387
  { includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
5407
5388
  )
5408
5389
  ]);
5409
- const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
5390
+ const targets = raw.targets.map((target, index) => ({
5391
+ ref: `e${index + 1}`,
5392
+ ...target
5393
+ }));
5410
5394
  replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
5411
5395
  return {
5412
5396
  url: page.url(),
5413
5397
  title,
5414
5398
  screenHash: raw.screenHash,
5415
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5416
5399
  targets
5417
5400
  };
5418
5401
  }
@@ -5597,23 +5580,8 @@ async function waitForPage(page, input) {
5597
5580
  return { success: true, matched: "selector", timeout, elapsed: Date.now() - startedAt };
5598
5581
  }
5599
5582
  if (input.text) {
5600
- const textToFind = input.text;
5601
- const matched = await pollUntil(timeout, pollInterval, async () => {
5602
- return page.evaluate((text) => {
5603
- const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
5604
- while (walker.nextNode()) {
5605
- if (walker.currentNode.textContent?.includes(text)) return true;
5606
- }
5607
- return false;
5608
- }, textToFind);
5609
- });
5610
- return {
5611
- success: matched,
5612
- matched: "text",
5613
- timeout,
5614
- elapsed: Date.now() - startedAt,
5615
- ...matched ? {} : { message: `Timed out waiting for text: ${input.text}` }
5616
- };
5583
+ await page.getByText(input.text).first().waitFor({ state: "visible", timeout });
5584
+ return { success: true, matched: "text", timeout, elapsed: Date.now() - startedAt };
5617
5585
  }
5618
5586
  if (input.url) {
5619
5587
  const matched = await pollUntil(timeout, pollInterval, async () => matchUrlPattern(page.url(), input.url));
@@ -5669,20 +5637,48 @@ async function waitForPage(page, input) {
5669
5637
  // src/commands/snapshot.ts
5670
5638
  var snapshotCommand = registerCommand({
5671
5639
  name: "snapshot",
5672
- description: "Capture a quick page state snapshot \u2014 aria tree, visible text, or DOM summary",
5640
+ description: "Get page state: interactive @refs to operate (default); --type aria=page outline; --type text=content; --type dom=debug DOM",
5673
5641
  scope: "page",
5674
5642
  selectorParams: ["selector"],
5643
+ examples: [
5644
+ {
5645
+ cmd: "xbrowser snapshot",
5646
+ description: "I want to OPERATE the page \u2192 returns clickable/fillable @refs (use click @e1, fill @e2)",
5647
+ output: '@e1 [button] "Submit"\n@e2 [textbox editable] "Email"'
5648
+ },
5649
+ {
5650
+ cmd: "xbrowser snapshot --type aria",
5651
+ description: "I want the page OUTLINE/skeleton (nav, heading hierarchy, regions)",
5652
+ output: 'banner:\n navigation:\n link "Home"\nmain:\n heading "Welcome"'
5653
+ },
5654
+ {
5655
+ cmd: "xbrowser snapshot --type text",
5656
+ description: "I want the page TEXT CONTENT (extract body copy/information)",
5657
+ output: "Welcome\nPlease enter your email\nSubmit"
5658
+ },
5659
+ {
5660
+ cmd: "xbrowser snapshot --type dom",
5661
+ description: "I want to DEBUG the DOM (tag names, attributes, nesting)"
5662
+ },
5663
+ {
5664
+ cmd: "xbrowser snapshot --selectors",
5665
+ description: "I want to operate AND need stable CSS selectors (reuse across sessions)",
5666
+ output: "e1: #submit | e2: #email"
5667
+ }
5668
+ ],
5675
5669
  parameters: z25.object({
5676
- type: z25.enum(["aria", "text", "dom", "all"]).default("aria").describe("Snapshot type: aria (accessibility tree), text (visible text), dom (element summary), all (combined)"),
5677
- selector: z25.string().optional().describe("Scope to a specific element"),
5678
- depth: z25.number().optional().default(6).describe("Max depth for DOM/aria tree"),
5679
- interactive: z25.boolean().optional().default(false).describe("Return interactive agent refs only"),
5680
- interactiveOnly: z25.boolean().optional().default(false).describe("Alias for interactive"),
5681
- i: z25.boolean().optional().default(false).describe("Short alias for interactive"),
5682
- compact: z25.boolean().optional().default(false).describe("Include compact xbrowser style snapshot text"),
5683
- c: z25.boolean().optional().default(false).describe("Short alias for compact"),
5684
- selectors: z25.boolean().optional().default(false).describe("Include ref to CSS selector map"),
5685
- all: z25.boolean().optional().default(false).describe("Include hidden interactive targets when using interactive snapshot")
5670
+ type: z25.enum(["interactive", "aria", "text", "dom", "all"]).default("interactive").describe(
5671
+ "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"
5672
+ ),
5673
+ selector: z25.string().optional().describe("\u9650\u5B9A\u5230\u67D0\u4E2A\u5143\u7D20\uFF08CSS \u9009\u62E9\u5668\uFF09\uFF0C\u53EA\u5FEB\u7167\u8BE5\u5B50\u6811"),
5674
+ depth: z25.number().optional().default(6).describe("aria/dom \u6811\u7684\u6700\u5927\u6DF1\u5EA6"),
5675
+ interactive: z25.boolean().optional().default(false).describe("\u5F3A\u5236 interactive \u6A21\u5F0F\uFF08\u7B49\u540C --type interactive\uFF0C\u517C\u5BB9 -i\uFF09"),
5676
+ interactiveOnly: z25.boolean().optional().default(false).describe("interactive \u7684\u522B\u540D"),
5677
+ i: z25.boolean().optional().default(false).describe("interactive \u7684\u77ED\u522B\u540D"),
5678
+ compact: z25.boolean().optional().default(false).describe("\u9644\u5E26\u7D27\u51D1\u6587\u672C\u5FEB\u7167\uFF08interactive \u6A21\u5F0F\u9ED8\u8BA4\u5DF2\u542B\uFF09"),
5679
+ c: z25.boolean().optional().default(false).describe("compact \u7684\u77ED\u522B\u540D"),
5680
+ 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"),
5681
+ 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")
5686
5682
  }),
5687
5683
  result: z25.object({
5688
5684
  url: z25.string(),
@@ -5695,14 +5691,13 @@ var snapshotCommand = registerCommand({
5695
5691
  const page = ctx.page;
5696
5692
  const url = page.url();
5697
5693
  const title = await page.title().catch(() => "");
5698
- if (p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors) {
5694
+ const wantInteractive = p.type === "interactive" || p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors;
5695
+ if (wantInteractive) {
5699
5696
  const observation = await observePage(page, ctx.sessionId, {
5700
5697
  includeHidden: p.all
5701
5698
  });
5702
5699
  if (p.selectors) observation.selectors = buildSelectorMap(observation);
5703
- if (p.compact || p.c || p.interactive || p.interactiveOnly || p.i) {
5704
- observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5705
- }
5700
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5706
5701
  return ok24(observation, normalizeTips3([
5707
5702
  `refs refreshed for ${observation.targets.length} targets; use click @e1 or fill @e2 "text"`
5708
5703
  ]));
@@ -5722,14 +5717,20 @@ var snapshotCommand = registerCommand({
5722
5717
  return ok24({ url, title, dom });
5723
5718
  }
5724
5719
  if (p.type === "all") {
5725
- const [aria, text, dom] = await Promise.all([
5720
+ const [observation, aria, text, dom] = await Promise.all([
5721
+ observePage(page, ctx.sessionId, { includeHidden: p.all }),
5726
5722
  captureAriaSnapshot(page, p.selector, p.depth),
5727
5723
  captureTextSnapshot(page, p.selector),
5728
5724
  captureDomSnapshot(page, p.selector, p.depth ?? 6)
5729
5725
  ]);
5726
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5727
+ if (p.selectors) observation.selectors = buildSelectorMap(observation);
5730
5728
  const tips = await buildRefTips(page, aria);
5731
5729
  persistSemantics(url, aria);
5732
- return ok24({ url, title, aria, text, dom }, normalizeTips3(tips));
5730
+ return ok24({ ...observation, aria, text, dom }, normalizeTips3([
5731
+ ...tips,
5732
+ `${observation.targets.length} interactive targets + aria + text + dom combined`
5733
+ ]));
5733
5734
  }
5734
5735
  return fail11(`Unknown snapshot type: ${p.type}`);
5735
5736
  }
@@ -5758,16 +5759,29 @@ async function buildRefTips(page, aria) {
5758
5759
  }
5759
5760
  }
5760
5761
  async function captureAriaSnapshot(page, selector, _depth) {
5762
+ let raw;
5761
5763
  try {
5762
5764
  const locator = selector ? page.locator(selector).first() : page.locator("body");
5763
- return await locator.ariaSnapshot();
5765
+ raw = await locator.ariaSnapshot();
5764
5766
  } catch {
5765
5767
  try {
5766
- return await page.locator("body").ariaSnapshot();
5768
+ raw = await page.locator("body").ariaSnapshot();
5767
5769
  } catch {
5768
5770
  return "(aria snapshot not available)";
5769
5771
  }
5770
5772
  }
5773
+ return filterAriaNoise(raw);
5774
+ }
5775
+ function filterAriaNoise(raw) {
5776
+ return raw.split("\n").filter((line) => {
5777
+ const t = line.trim();
5778
+ if (!t) return false;
5779
+ if (t === "none:" || t.startsWith("none: ")) return false;
5780
+ if (t.includes("InlineTextBox")) return false;
5781
+ if (t.includes("ListMarker")) return false;
5782
+ if (/^[a-z]+$/.test(t) || /^[a-z]+:$/.test(t)) return false;
5783
+ return true;
5784
+ }).join("\n");
5771
5785
  }
5772
5786
  async function captureTextSnapshot(page, selector) {
5773
5787
  if (selector) {
@@ -5910,12 +5924,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
5910
5924
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
5911
5925
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
5912
5926
  {"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
5927
+ {"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
5913
5928
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
5914
5929
 
5915
5930
  \u89C4\u5219\uFF1A
5916
5931
  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
5917
5932
  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
5918
- 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`;
5933
+ 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`;
5919
5934
  function extractDecision(raw) {
5920
5935
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
5921
5936
  const start = s.indexOf("{");
@@ -5966,6 +5981,7 @@ var taskCommand = registerCommand({
5966
5981
  let status = "max_steps";
5967
5982
  let summary = "";
5968
5983
  let lastError = "";
5984
+ let emptyReplies = 0;
5969
5985
  for (let step = 1; step <= p.maxSteps; step++) {
5970
5986
  if (Date.now() - started > p.timeout) {
5971
5987
  status = "blocked";
@@ -5985,7 +6001,7 @@ ${history.slice(-6).join("\n")}` : ""
5985
6001
  ].filter(Boolean).join("\n");
5986
6002
  let raw = "";
5987
6003
  try {
5988
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
6004
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5989
6005
 
5990
6006
  ---
5991
6007
 
@@ -5999,6 +6015,12 @@ ${userPayload}` }], 900);
5999
6015
  }
6000
6016
  const decision = extractDecision(raw);
6001
6017
  if (!decision || typeof decision.action !== "string") {
6018
+ if (!raw.trim() && emptyReplies < 2) {
6019
+ emptyReplies++;
6020
+ steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
6021
+ history.push(`step${step}: (empty reply, retrying)`);
6022
+ continue;
6023
+ }
6002
6024
  status = "blocked";
6003
6025
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
6004
6026
  break;
@@ -6013,6 +6035,13 @@ ${userPayload}` }], 900);
6013
6035
  steps.push({ step, thought, action: "done", ok: true, screenHash });
6014
6036
  break;
6015
6037
  }
6038
+ if (action === "back") {
6039
+ await ctx.page?.goBack?.().catch?.(() => {
6040
+ });
6041
+ steps.push({ step, thought, action: "back", ok: true, screenHash });
6042
+ history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
6043
+ continue;
6044
+ }
6016
6045
  if (action === "blocked") {
6017
6046
  status = "blocked";
6018
6047
  summary = value || thought || "LLM judged blocked";
@@ -6753,6 +6782,8 @@ var visualTagCommand = registerCommand({
6753
6782
  // src/commands/visual-tag-v2.ts
6754
6783
  import { z as z32 } from "zod";
6755
6784
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6785
+
6786
+ // src/commands/visual-tag-v2-script.ts
6756
6787
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6757
6788
  var TAG_V2_SCRIPT = `
6758
6789
  (function() {
@@ -7095,7 +7126,9 @@ var TAG_V2_SCRIPT = `
7095
7126
  return JSON.stringify(window.__xbTagStats);
7096
7127
  })()
7097
7128
  `;
7098
- var visualTagV2Command = registerCommand({
7129
+
7130
+ // src/commands/visual-tag-v2.ts
7131
+ registerCommand({
7099
7132
  name: "visual-tag-v2",
7100
7133
  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",
7101
7134
  scope: "page",
@@ -7328,114 +7361,6 @@ function attachDetectAntiBot(ctx) {
7328
7361
  };
7329
7362
  }
7330
7363
 
7331
- // src/plugin/login-guard.ts
7332
- async function checkPluginLoginRequired(options) {
7333
- const { site, command, commandName, ctx, page, sessionName } = options;
7334
- if (commandName === "login" || commandName === "logout") return { ok: true };
7335
- const loginConfig = site.config?.loginConfig;
7336
- const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
7337
- if (!requiresLogin) return { ok: true };
7338
- const pluginName = site.name || "plugin";
7339
- const siteConfig = site.config;
7340
- const configIsLogin = siteConfig?.isLogin;
7341
- if (configIsLogin) {
7342
- try {
7343
- const loggedIn = await configIsLogin(ctx);
7344
- if (loggedIn) return { ok: true };
7345
- return buildLoginRequired({
7346
- plugin: pluginName,
7347
- command: commandName,
7348
- reason: "config.isLogin returned false",
7349
- sessionName,
7350
- loginConfig
7351
- });
7352
- } catch {
7353
- }
7354
- }
7355
- if (typeof site.isLoggedIn === "function") {
7356
- try {
7357
- const loggedIn = await site.isLoggedIn(ctx);
7358
- if (loggedIn) return { ok: true };
7359
- return buildLoginRequired({
7360
- plugin: pluginName,
7361
- command: commandName,
7362
- reason: "plugin isLoggedIn returned false",
7363
- sessionName,
7364
- loginConfig
7365
- });
7366
- } catch {
7367
- }
7368
- }
7369
- if (page && loginConfig) {
7370
- const generic = await detectLoginFromPage(page, loginConfig);
7371
- if (generic === "logged-in") return { ok: true };
7372
- if (generic === "logged-out") {
7373
- return buildLoginRequired({
7374
- plugin: pluginName,
7375
- command: commandName,
7376
- reason: "generic loginConfig detected logged-out page",
7377
- sessionName,
7378
- loginConfig
7379
- });
7380
- }
7381
- }
7382
- return { ok: true };
7383
- }
7384
- function buildLoginRequired(options) {
7385
- const viewerUrl = buildViewerUrl(options.sessionName);
7386
- const loginUrl = options.loginConfig?.loginUrl;
7387
- const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
7388
- const tips = [
7389
- message,
7390
- ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
7391
- ...loginUrl ? [`Login page: ${loginUrl}`] : [],
7392
- `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
7393
- ];
7394
- return {
7395
- ok: false,
7396
- data: {
7397
- code: "LOGIN_REQUIRED",
7398
- plugin: options.plugin,
7399
- command: options.command,
7400
- reason: options.reason,
7401
- ...viewerUrl ? { viewerUrl } : {},
7402
- ...loginUrl ? { loginUrl } : {}
7403
- },
7404
- message,
7405
- tips
7406
- };
7407
- }
7408
- async function detectLoginFromPage(page, config) {
7409
- const url = page.url();
7410
- if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
7411
- const result = await page.evaluate((cfg) => {
7412
- const visible = (selector) => {
7413
- try {
7414
- const el = document.querySelector(selector);
7415
- if (!el) return false;
7416
- const rect = el.getBoundingClientRect();
7417
- const style = window.getComputedStyle(el);
7418
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
7419
- } catch {
7420
- return false;
7421
- }
7422
- };
7423
- if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
7424
- if (cfg.loginSelectors?.some(visible)) return "logged-out";
7425
- const bodyText = document.body?.innerText || "";
7426
- const keywords = cfg.loginKeywords || [];
7427
- if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
7428
- return "logged-out";
7429
- }
7430
- return "unknown";
7431
- }, {
7432
- loginSelectors: config.loginSelectors || [],
7433
- loginKeywords: config.loginKeywords || [],
7434
- loggedInSelectors: config.loggedInSelectors || []
7435
- });
7436
- return result;
7437
- }
7438
-
7439
7364
  // src/tips/dom-watcher.ts
7440
7365
  var DOM_WATCHER_SCRIPT = `
7441
7366
  (function() {
@@ -7695,6 +7620,9 @@ var TipGenerator = class {
7695
7620
  categoryLabel(category) {
7696
7621
  const labels = {
7697
7622
  dialog: "Dialog",
7623
+ filechooser: "File Chooser",
7624
+ popup: "Popup",
7625
+ download: "Download",
7698
7626
  modal: "Modal",
7699
7627
  popover: "Popover",
7700
7628
  notification: "\u901A\u77E5",
@@ -7759,8 +7687,62 @@ var TipsManager = class {
7759
7687
  generator = new TipGenerator(this.contextTracker);
7760
7688
  beforeSnapshot = null;
7761
7689
  lastDetectionTime = 0;
7690
+ // CDP 弹窗事件检测(filechooser / dialog / popup)
7691
+ detectedEvents = [];
7692
+ eventListenersAttached = false;
7693
+ lastCommandName = "";
7762
7694
  async beforeCommand(page, commandName, params) {
7763
7695
  this.contextTracker.record(commandName, params);
7696
+ this.lastCommandName = commandName;
7697
+ if (!this.eventListenersAttached && typeof page.on === "function") {
7698
+ this.eventListenersAttached = true;
7699
+ page.on("dialog", (dialog) => {
7700
+ const d = dialog;
7701
+ try {
7702
+ this.detectedEvents.push({
7703
+ type: "dialog",
7704
+ message: `[${d.type()}] ${d.message().slice(0, 200)}`,
7705
+ commandName: this.lastCommandName
7706
+ });
7707
+ } catch {
7708
+ }
7709
+ });
7710
+ page.on("filechooser", (chooser) => {
7711
+ const c = chooser;
7712
+ try {
7713
+ this.detectedEvents.push({
7714
+ type: "filechooser",
7715
+ message: `\u6587\u4EF6\u9009\u62E9\u5F39\u7A97${c.isMultiple ? "\uFF08\u591A\u9009\uFF09" : ""}\uFF1Aselector=${c.selector || "input[type=file]"}`,
7716
+ selector: c.selector,
7717
+ commandName: this.lastCommandName
7718
+ });
7719
+ } catch {
7720
+ }
7721
+ });
7722
+ page.on("popup", (info) => {
7723
+ const p = info;
7724
+ try {
7725
+ this.detectedEvents.push({
7726
+ type: "popup",
7727
+ message: `\u65B0\u7A97\u53E3\u5F39\u7A97\uFF1Aurl=${p.url || "(unknown)"}${p.windowName ? ` name=${p.windowName}` : ""}`,
7728
+ commandName: this.lastCommandName
7729
+ });
7730
+ } catch {
7731
+ }
7732
+ });
7733
+ page.on("download", (info) => {
7734
+ const d = info;
7735
+ try {
7736
+ const stateLabel = d.state === "completed" ? "\u5B8C\u6210" : d.state === "canceled" ? "\u53D6\u6D88" : "\u5F00\u59CB";
7737
+ this.detectedEvents.push({
7738
+ type: "download",
7739
+ message: `\u6587\u4EF6\u4E0B\u8F7D${stateLabel}\uFF1A${d.filename || "unknown"}${d.url ? ` (${d.url.slice(0, 80)})` : ""}`,
7740
+ commandName: this.lastCommandName
7741
+ });
7742
+ } catch {
7743
+ }
7744
+ });
7745
+ }
7764
7746
  if (!this.domWatcher) {
7765
7747
  this.domWatcher = new DomWatcher(page);
7766
7748
  }
@@ -7803,20 +7785,59 @@ var TipsManager = class {
7803
7785
  }
7804
7786
  }
7805
7787
  async afterCommand() {
7806
- if (!this.domWatcher || !this.beforeSnapshot) return [];
7788
+ if (!this.domWatcher || !this.beforeSnapshot) {
7789
+ const cdpTips = this.collectCdpEventTips();
7790
+ this.detectedEvents = [];
7791
+ return cdpTips;
7792
+ }
7807
7793
  await this.debounce();
7808
7794
  try {
7809
7795
  const currentElements = await this.domWatcher.scanOverlays();
7810
7796
  const afterSnapshot = buildSnapshot(currentElements);
7811
7797
  const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
7812
7798
  const tips = this.generator.generate(newElements);
7799
+ const cdpTips = this.collectCdpEventTips();
7800
+ tips.push(...cdpTips);
7813
7801
  this.beforeSnapshot = null;
7802
+ this.detectedEvents = [];
7814
7803
  return tips;
7815
7804
  } catch {
7805
+ const cdpTips = this.collectCdpEventTips();
7816
7806
  this.beforeSnapshot = null;
7817
- return [];
7807
+ this.detectedEvents = [];
7808
+ return cdpTips;
7818
7809
  }
7819
7810
  }
7811
+ /**
7812
+ * 把检测到的 CDP 弹窗事件转成 SmartTip
7813
+ * 包括:dialog(alert/confirm/prompt)、filechooser(文件选择弹窗)、popup(新窗口)
7814
+ */
7815
+ collectCdpEventTips() {
7816
+ if (this.detectedEvents.length === 0) return [];
7817
+ return this.detectedEvents.map((evt) => {
7818
+ const suggestions = [];
7819
+ if (evt.type === "dialog") {
7820
+ suggestions.push("\u6B64\u5F39\u7A97\u53EF\u80FD\u963B\u585E\u540E\u7EED\u64CD\u4F5C");
7821
+ suggestions.push('\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 page.on("dialog") \u62E6\u622A');
7822
+ } else if (evt.type === "filechooser") {
7823
+ suggestions.push("\u6B64\u5F39\u7A97\u7531\u9875\u9762\u64CD\u4F5C\u89E6\u53D1\uFF08\u5982\u70B9\u51FB\u4E0A\u4F20\u6309\u94AE\uFF09");
7824
+ suggestions.push("\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 --path/--paths \u53C2\u6570\u4E0A\u4F20\u6587\u4EF6");
7825
+ } else if (evt.type === "popup") {
7826
+ suggestions.push("\u9875\u9762\u5C1D\u8BD5\u6253\u5F00\u65B0\u7A97\u53E3\uFF08\u53EF\u80FD\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF09");
7827
+ suggestions.push('\u5982\u9700\u5904\u7406\uFF1A\u68C0\u67E5\u5F39\u7A97\u62E6\u622A\u8BBE\u7F6E\u6216\u4F7F\u7528 page.on("popup") \u76D1\u542C');
7828
+ } else if (evt.type === "download") {
7829
+ suggestions.push("\u9875\u9762\u89E6\u53D1\u4E86\u6587\u4EF6\u4E0B\u8F7D");
7830
+ suggestions.push("\u5982\u9700\u63A7\u5236\u8DEF\u5F84\uFF1Apage.setDownloadBehavior(path)");
7831
+ }
7832
+ return {
7833
+ category: evt.type,
7834
+ priority: "p1",
7835
+ message: `\u{1F514} [\u5F39\u7A97\u68C0\u6D4B] ${evt.message}\uFF08\u89E6\u53D1\u547D\u4EE4: ${evt.commandName || "\u672A\u77E5"}\uFF09`,
7836
+ selector: evt.selector,
7837
+ suggestions
7838
+ };
7839
+ });
7840
+ }
7820
7841
  debounce() {
7821
7842
  const ms = tipsDebounceMs();
7822
7843
  if (ms <= 0) return Promise.resolve();
@@ -7837,6 +7858,9 @@ var TipsManager = class {
7837
7858
  this.contextTracker.clear();
7838
7859
  this.domWatcher = null;
7839
7860
  this.lastDetectionTime = 0;
7861
+ this.detectedEvents = [];
7862
+ this.eventListenersAttached = false;
7863
+ this.lastCommandName = "";
7840
7864
  }
7841
7865
  };
7842
7866
  var globalTipsManager = null;
@@ -7909,36 +7933,596 @@ var HOOK_REGISTRY = {
7909
7933
  params: JSON.parse(JSON.stringify(ctx.params)),
7910
7934
  duration: ctx.duration
7911
7935
  });
7912
- Reflect.set(ctx, "__commandLogs", logs);
7936
+ Reflect.set(ctx, "__commandLogs", logs);
7937
+ return void 0;
7938
+ }
7939
+ }
7940
+ };
7941
+ var customHooks = {};
7942
+ async function loadHooks() {
7943
+ const env = process.env.XBROWSER_HOOKS;
7944
+ if (!env) return [];
7945
+ const names = env.split(",").map((n) => n.trim()).filter(Boolean);
7946
+ if (names.length === 0) return [];
7947
+ const hooks = [];
7948
+ for (const name of names) {
7949
+ const hook = HOOK_REGISTRY[name];
7950
+ if (hook) {
7951
+ hooks.push(hook);
7952
+ continue;
7953
+ }
7954
+ const customFactory = customHooks[name];
7955
+ if (customFactory) {
7956
+ const customHook = await customFactory();
7957
+ if (customHook) hooks.push(customHook);
7958
+ }
7959
+ }
7960
+ return hooks;
7961
+ }
7962
+
7963
+ // src/fail-codes.ts
7964
+ var FAIL_CODES = {
7965
+ selectorNotFound: "RETRYABLE: selector-not-found",
7966
+ pageNotReady: "RETRYABLE: page-not-ready",
7967
+ elementGone: "RETRYABLE: element-gone",
7968
+ inputNotRetained: "RETRYABLE: input-not-retained",
7969
+ captcha: "HUMAN: captcha",
7970
+ loginWall: "HUMAN: login-wall",
7971
+ permissionDenied: "FATAL: permission-denied",
7972
+ targetGone: "FATAL: target-gone",
7973
+ unknown: "FATAL: unknown"
7974
+ };
7975
+ function classifyFailure(message) {
7976
+ const msg = (message || "").toLowerCase();
7977
+ const pick = (code) => ({
7978
+ code,
7979
+ level: code.split(":")[0],
7980
+ message: message || code
7981
+ });
7982
+ if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
7983
+ if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
7984
+ if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
7985
+ if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
7986
+ return pick(FAIL_CODES.selectorNotFound);
7987
+ if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
7988
+ if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
7989
+ if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
7990
+ return pick(FAIL_CODES.targetGone);
7991
+ return pick(FAIL_CODES.unknown);
7992
+ }
7993
+
7994
+ // src/executor/foundation.ts
7995
+ import { homedir as homedir5 } from "os";
7996
+ import { join as join7 } from "path";
7997
+ import {
7998
+ CompositeStorage as CompositeStorage2,
7999
+ configureArchiveStore,
8000
+ appendCommandToArchive,
8001
+ fail as fail17,
8002
+ checkGuard
8003
+ } from "@dyyz1993/xcli-core";
8004
+ var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8005
+ var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8006
+ var CONFIG_DIR2 = join7(homedir5(), ".xbrowser");
8007
+ var storageCache = /* @__PURE__ */ new Map();
8008
+ function getPluginStorage(pluginName) {
8009
+ if (!storageCache.has(pluginName)) {
8010
+ storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
8011
+ }
8012
+ return storageCache.get(pluginName);
8013
+ }
8014
+ var archiveInitialized = false;
8015
+ function ensureArchiveInit() {
8016
+ if (!archiveInitialized) {
8017
+ try {
8018
+ configureArchiveStore({ archiveDir: join7(homedir5(), ".xbrowser", "archives") });
8019
+ } catch {
8020
+ }
8021
+ archiveInitialized = true;
8022
+ }
8023
+ }
8024
+ function recordArchive(sessionId, sessionName, entry) {
8025
+ if (!sessionId) return;
8026
+ try {
8027
+ ensureArchiveInit();
8028
+ appendCommandToArchive(sessionId, sessionName, entry);
8029
+ } catch {
8030
+ }
8031
+ }
8032
+ async function guardCheck(commandName) {
8033
+ try {
8034
+ const loader = await getPluginLoader();
8035
+ return checkGuard(loader.getCore(), commandName, process.env);
8036
+ } catch {
8037
+ return null;
8038
+ }
8039
+ }
8040
+ function errorResult(message) {
8041
+ return { ...fail17(message), duration: 0 };
8042
+ }
8043
+ function tipsToMessages(tips) {
8044
+ if (!tips || tips.length === 0) return [];
8045
+ return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
8046
+ }
8047
+ var wsServer = null;
8048
+ function streamCommandEvent(sessionId, message) {
8049
+ if (!wsServer || !wsServer.getRunning()) return;
8050
+ wsServer.broadcastToSession(sessionId, { type: "command", data: message });
8051
+ }
8052
+
8053
+ // src/executor/chain.ts
8054
+ import {
8055
+ fail as fail18,
8056
+ ok as ok32,
8057
+ TipCollector as TipCollector2,
8058
+ normalizeTips as normalizeTips7,
8059
+ unquote as unquote2
8060
+ } from "@dyyz1993/xcli-core";
8061
+
8062
+ // src/plugin/login-guard.ts
8063
+ async function checkPluginLoginRequired(options) {
8064
+ const { site, command, commandName, ctx, page, sessionName } = options;
8065
+ if (commandName === "login" || commandName === "logout") return { ok: true };
8066
+ const loginConfig = site.config?.loginConfig;
8067
+ const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
8068
+ if (!requiresLogin) return { ok: true };
8069
+ const pluginName = site.name || "plugin";
8070
+ const siteConfig = site.config;
8071
+ const configIsLogin = siteConfig?.isLogin;
8072
+ if (configIsLogin) {
8073
+ try {
8074
+ const loggedIn = await configIsLogin(ctx);
8075
+ if (loggedIn) return { ok: true };
8076
+ return buildLoginRequired({
8077
+ plugin: pluginName,
8078
+ command: commandName,
8079
+ reason: "config.isLogin returned false",
8080
+ sessionName,
8081
+ loginConfig
8082
+ });
8083
+ } catch {
8084
+ }
8085
+ }
8086
+ if (typeof site.isLoggedIn === "function") {
8087
+ try {
8088
+ const loggedIn = await site.isLoggedIn(ctx);
8089
+ if (loggedIn) return { ok: true };
8090
+ return buildLoginRequired({
8091
+ plugin: pluginName,
8092
+ command: commandName,
8093
+ reason: "plugin isLoggedIn returned false",
8094
+ sessionName,
8095
+ loginConfig
8096
+ });
8097
+ } catch {
8098
+ }
8099
+ }
8100
+ if (page && loginConfig) {
8101
+ const generic = await detectLoginFromPage(page, loginConfig);
8102
+ if (generic === "logged-in") return { ok: true };
8103
+ if (generic === "logged-out") {
8104
+ return buildLoginRequired({
8105
+ plugin: pluginName,
8106
+ command: commandName,
8107
+ reason: "generic loginConfig detected logged-out page",
8108
+ sessionName,
8109
+ loginConfig
8110
+ });
8111
+ }
8112
+ }
8113
+ return { ok: true };
8114
+ }
8115
+ function buildLoginRequired(options) {
8116
+ const viewerUrl = buildViewerUrl(options.sessionName);
8117
+ const loginUrl = options.loginConfig?.loginUrl;
8118
+ const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
8119
+ const tips = [
8120
+ message,
8121
+ ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
8122
+ ...loginUrl ? [`Login page: ${loginUrl}`] : [],
8123
+ `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
8124
+ ];
8125
+ return {
8126
+ ok: false,
8127
+ data: {
8128
+ code: "LOGIN_REQUIRED",
8129
+ plugin: options.plugin,
8130
+ command: options.command,
8131
+ reason: options.reason,
8132
+ ...viewerUrl ? { viewerUrl } : {},
8133
+ ...loginUrl ? { loginUrl } : {}
8134
+ },
8135
+ message,
8136
+ tips
8137
+ };
8138
+ }
8139
+ async function detectLoginFromPage(page, config) {
8140
+ const url = page.url();
8141
+ if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
8142
+ const result = await page.evaluate((cfg) => {
8143
+ const visible = (selector) => {
8144
+ try {
8145
+ const el = document.querySelector(selector);
8146
+ if (!el) return false;
8147
+ const rect = el.getBoundingClientRect();
8148
+ const style = window.getComputedStyle(el);
8149
+ return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
8150
+ } catch {
8151
+ return false;
8152
+ }
8153
+ };
8154
+ if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
8155
+ if (cfg.loginSelectors?.some(visible)) return "logged-out";
8156
+ const bodyText = document.body?.innerText || "";
8157
+ const keywords = cfg.loginKeywords || [];
8158
+ if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
8159
+ return "logged-out";
8160
+ }
8161
+ return "unknown";
8162
+ }, {
8163
+ loginSelectors: config.loginSelectors || [],
8164
+ loginKeywords: config.loginKeywords || [],
8165
+ loggedInSelectors: config.loggedInSelectors || []
8166
+ });
8167
+ return result;
8168
+ }
8169
+
8170
+ // src/utils/positional-params.ts
8171
+ import { unquote } from "@dyyz1993/xcli-core";
8172
+ function getTypeName(field) {
8173
+ return field?._def?.typeName;
8174
+ }
8175
+ function unwrapField(field) {
8176
+ const typeName = getTypeName(field);
8177
+ if (typeName === "ZodOptional" || typeName === "ZodDefault") {
8178
+ const innerType = field?._def?.innerType;
8179
+ return unwrapField(innerType);
8180
+ }
8181
+ return field;
8182
+ }
8183
+ function isOptionalNumber(field) {
8184
+ const typeName = getTypeName(field);
8185
+ return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
8186
+ }
8187
+ function coerceValue(raw, field) {
8188
+ const inner = unwrapField(field);
8189
+ const optionalNum = isOptionalNumber(field);
8190
+ const innerTypeName = getTypeName(inner);
8191
+ if (innerTypeName === "ZodString") {
8192
+ return { value: unquote(raw), skip: false };
8193
+ }
8194
+ if (innerTypeName === "ZodNumber") {
8195
+ const parsed = Number(raw);
8196
+ if (isNaN(parsed)) {
8197
+ if (optionalNum) return { value: void 0, skip: true };
8198
+ return { value: raw, skip: false };
8199
+ }
8200
+ return { value: parsed, skip: false };
8201
+ }
8202
+ if (innerTypeName === "ZodBoolean") {
8203
+ if (raw === "true" || raw === "1") return { value: true, skip: false };
8204
+ if (raw === "false" || raw === "0") return { value: false, skip: false };
8205
+ return { value: raw, skip: false };
8206
+ }
8207
+ return { value: unquote(raw), skip: false };
8208
+ }
8209
+ function mapPositionalValues(schema, positional, existing) {
8210
+ const result = { ...existing };
8211
+ if (!schema || typeof schema !== "object") return result;
8212
+ const shape = schema.shape;
8213
+ if (!shape || typeof shape !== "object") return result;
8214
+ const keys = Object.keys(shape);
8215
+ let pIdx = 0;
8216
+ for (const key of keys) {
8217
+ if (pIdx >= positional.length) break;
8218
+ if (result[key] !== void 0) {
8219
+ pIdx++;
8220
+ continue;
8221
+ }
8222
+ const field = shape[key];
8223
+ const raw = positional[pIdx];
8224
+ const { value, skip } = coerceValue(raw, field);
8225
+ if (skip) continue;
8226
+ result[key] = value;
8227
+ pIdx++;
8228
+ }
8229
+ return result;
8230
+ }
8231
+
8232
+ // src/utils/plugin-params.ts
8233
+ function schemaFieldType(schema, key) {
8234
+ const shape = schema?.shape;
8235
+ const field = shape?.[key];
8236
+ let current = field;
8237
+ while (current) {
8238
+ const def = current._def;
8239
+ if (!def) return void 0;
8240
+ const type = def.typeName ?? def.type;
8241
+ if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
8242
+ current = def.innerType ?? def.inner;
8243
+ continue;
8244
+ }
8245
+ return type;
8246
+ }
8247
+ return void 0;
8248
+ }
8249
+ function parsePluginParams(args, schema, base = {}) {
8250
+ const params = { ...base };
8251
+ const positionalValues = [];
8252
+ for (let i = 0; i < args.length; i++) {
8253
+ if (args[i] === "--" && args[i + 1]) {
8254
+ try {
8255
+ Object.assign(params, JSON.parse(args[i + 1]));
8256
+ } catch {
8257
+ }
8258
+ break;
8259
+ }
8260
+ if (args[i].startsWith("--")) {
8261
+ const key = args[i].slice(2);
8262
+ const value = args[i + 1];
8263
+ if (value && !value.startsWith("-")) {
8264
+ const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
8265
+ if (type === "ZodString" || type === "string") params[key] = value;
8266
+ else if (value === "true") params[key] = true;
8267
+ else if (value === "false") params[key] = false;
8268
+ else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
8269
+ else {
8270
+ try {
8271
+ const parsed = JSON.parse(value);
8272
+ if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
8273
+ params[key] = parsed;
8274
+ } else {
8275
+ params[key] = value;
8276
+ }
8277
+ } catch {
8278
+ params[key] = value;
8279
+ }
8280
+ }
8281
+ i++;
8282
+ } else {
8283
+ params[key] = true;
8284
+ }
8285
+ } else if (!args[i].startsWith("-")) {
8286
+ positionalValues.push(args[i]);
8287
+ }
8288
+ }
8289
+ Object.assign(params, mapPositionalValues(schema, positionalValues, params));
8290
+ const result = {};
8291
+ for (const [k, v] of Object.entries(params)) {
8292
+ const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8293
+ result[camelKey] = v;
8294
+ }
8295
+ return result;
8296
+ }
8297
+
8298
+ // src/executor/chain.ts
8299
+ async function executeChain(input, options, executeCommand2) {
8300
+ const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8301
+ const sessionName = options?.sessionName || "default";
8302
+ const results = [];
8303
+ const totalStart = Date.now();
8304
+ let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8305
+ if (!session) {
8306
+ const launchOpts = {};
8307
+ if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
8308
+ session = await createSession(sessionName, void 0, launchOpts);
8309
+ saveSessionDiskMeta(sessionName, {
8310
+ id: session.id,
8311
+ name: sessionName,
8312
+ url: session.page.url(),
8313
+ createdAt: session.createdAt,
8314
+ cdpEndpoint: session.cdpEndpoint
8315
+ });
8316
+ }
8317
+ try {
8318
+ for (const pipeline of pipelines) {
8319
+ const { type, pipeline: commands } = pipeline;
8320
+ for (const cmdStr of commands) {
8321
+ if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8322
+ await new Promise((resolve) => setTimeout(resolve, 800 + Math.random() * 1700));
8323
+ }
8324
+ const parts = splitCommand(cmdStr);
8325
+ if (parts.length === 0) continue;
8326
+ const cmdName = parts[0];
8327
+ const cmdArgs = parts.slice(1);
8328
+ const loader = await getPluginLoader();
8329
+ const internalLoader = loader.getCore().loader;
8330
+ const resolvedName = loader.resolveSiteName(cmdName);
8331
+ const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8332
+ if (site) {
8333
+ const pluginHandled = await executePluginChainStep({
8334
+ site,
8335
+ cmdName,
8336
+ cmdArgs,
8337
+ cmdStr,
8338
+ type,
8339
+ results,
8340
+ totalStart,
8341
+ session,
8342
+ sessionName
8343
+ });
8344
+ if (pluginHandled) return pluginHandled;
8345
+ continue;
8346
+ }
8347
+ const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8348
+ if (options?.frame && params._frame === void 0 && params.frame === void 0) {
8349
+ params._frame = options.frame;
8350
+ }
8351
+ if (cmdName === "goto" && params.url) {
8352
+ const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8353
+ if (!existing) {
8354
+ session = await createSession(sessionName, params.url, {
8355
+ cdpEndpoint: options?.cdpEndpoint
8356
+ });
8357
+ }
8358
+ }
8359
+ const result = await executeCommand2(cmdName, params, sessionName, {
8360
+ cdpEndpoint: options?.cdpEndpoint,
8361
+ skipCleanup: true
8362
+ });
8363
+ results.push({
8364
+ command: cmdName,
8365
+ raw: cmdStr,
8366
+ success: result.success,
8367
+ data: result.data,
8368
+ message: result.message,
8369
+ duration: 0,
8370
+ tips: result.tips,
8371
+ ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8372
+ });
8373
+ if (type === "and" && !result.success) {
8374
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
8375
+ }
8376
+ if (type === "or" && result.success) {
8377
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
8378
+ }
8379
+ }
8380
+ }
8381
+ return {
8382
+ success: !results.some((result) => !result.success),
8383
+ steps: results,
8384
+ totalDuration: Date.now() - totalStart
8385
+ };
8386
+ } finally {
8387
+ }
8388
+ }
8389
+ function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
8390
+ return {
8391
+ success,
8392
+ steps,
8393
+ totalDuration: Date.now() - totalStart,
8394
+ stoppedAt,
8395
+ stoppedReason: reason
8396
+ };
8397
+ }
8398
+ async function executePluginChainStep(context) {
8399
+ const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
8400
+ const subCommand = cmdArgs[0];
8401
+ if (!subCommand) {
8402
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
8403
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
8404
+ return void 0;
8405
+ }
8406
+ const cmdEntry = site.getCommand(subCommand);
8407
+ if (!cmdEntry) {
8408
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
8409
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
8410
+ return void 0;
8411
+ }
8412
+ const pluginArgs = cmdArgs.slice(1);
8413
+ const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8414
+ if (cmdEntry.parameters) {
8415
+ const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8416
+ if (schemaCheck.success) {
8417
+ for (const [key, value] of Object.entries(schemaCheck.data)) {
8418
+ if (!(key in pluginParams)) pluginParams[key] = value;
8419
+ }
8420
+ }
8421
+ }
8422
+ const pluginCtx = {
8423
+ args: pluginArgs,
8424
+ options: pluginParams,
8425
+ cwd: process.cwd(),
8426
+ page: session.page,
8427
+ browser: session.context.browser(),
8428
+ browserContext: session.context,
8429
+ sessionId: session.id,
8430
+ storage: getPluginStorage(cmdName),
8431
+ output: { mode: "text", showTips: false, color: false, emoji: false },
8432
+ error: (message) => {
8433
+ throw new Error(message);
8434
+ },
8435
+ config: {},
8436
+ site,
8437
+ cliName: "xbrowser",
8438
+ tips: new TipCollector2()
8439
+ };
8440
+ const start = Date.now();
8441
+ try {
8442
+ const loginGuard = await checkPluginLoginRequired({
8443
+ site,
8444
+ command: cmdEntry,
8445
+ commandName: subCommand,
8446
+ ctx: pluginCtx,
8447
+ page: session.page,
8448
+ sessionName
8449
+ });
8450
+ if (!loginGuard.ok) {
8451
+ const duration2 = Date.now() - start;
8452
+ const data2 = loginGuard.data ?? null;
8453
+ recordArchive(session.id, sessionName, {
8454
+ step: results.length,
8455
+ command: `${cmdName} ${subCommand}`,
8456
+ params: pluginParams,
8457
+ result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8458
+ toolCalls: [],
8459
+ duration: duration2,
8460
+ timestamp: start
8461
+ });
8462
+ results.push({
8463
+ command: `${cmdName} ${subCommand}`,
8464
+ raw: cmdStr,
8465
+ success: false,
8466
+ data: data2,
8467
+ message: loginGuard.message,
8468
+ tips: normalizeTips7(loginGuard.tips),
8469
+ duration: duration2
8470
+ });
8471
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
7913
8472
  return void 0;
7914
8473
  }
7915
- }
7916
- };
7917
- var customHooks = {};
7918
- async function loadHooks() {
7919
- const env = process.env.XBROWSER_HOOKS;
7920
- if (!env) return [];
7921
- const names = env.split(",").map((n) => n.trim()).filter(Boolean);
7922
- if (names.length === 0) return [];
7923
- const hooks = [];
7924
- for (const name of names) {
7925
- const hook = HOOK_REGISTRY[name];
7926
- if (hook) {
7927
- hooks.push(hook);
7928
- continue;
8474
+ const hooks = await loadHooks();
8475
+ if (hooks.length > 0) {
8476
+ await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
7929
8477
  }
7930
- const customFactory = customHooks[name];
7931
- if (customFactory) {
7932
- const customHook = await customFactory();
7933
- if (customHook) hooks.push(customHook);
8478
+ const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8479
+ const duration = Date.now() - start;
8480
+ let hookOutputs;
8481
+ if (hooks.length > 0) {
8482
+ const outputs = [];
8483
+ for (const hook of hooks) {
8484
+ const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
8485
+ if (output) outputs.push({ _hook: hook.name, ...output });
8486
+ }
8487
+ if (outputs.length > 0) hookOutputs = outputs;
7934
8488
  }
8489
+ const data = raw?.data ?? raw;
8490
+ recordArchive(session.id, sessionName, {
8491
+ step: results.length,
8492
+ command: `${cmdName} ${subCommand}`,
8493
+ params: pluginParams,
8494
+ result: { success: true, data, tips: tipsToMessages(raw?.tips) },
8495
+ toolCalls: [],
8496
+ duration,
8497
+ timestamp: start
8498
+ });
8499
+ results.push({
8500
+ command: `${cmdName} ${subCommand}`,
8501
+ raw: cmdStr,
8502
+ ...ok32(data),
8503
+ duration,
8504
+ ...hookOutputs ? { hookOutputs } : {}
8505
+ });
8506
+ if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
8507
+ } catch (error) {
8508
+ const duration = Date.now() - start;
8509
+ const message = errMsg(error);
8510
+ recordArchive(session.id, sessionName, {
8511
+ step: results.length,
8512
+ command: `${cmdName} ${subCommand}`,
8513
+ params: pluginParams,
8514
+ result: { success: false, data: null, message, tips: [] },
8515
+ toolCalls: [],
8516
+ duration,
8517
+ timestamp: start
8518
+ });
8519
+ results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
8520
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
7935
8521
  }
7936
- return hooks;
8522
+ return void 0;
7937
8523
  }
7938
8524
 
7939
8525
  // src/executor.ts
7940
- import { homedir as homedir5 } from "os";
7941
- import { join as join7 } from "path";
7942
8526
  function levenshtein(a, b) {
7943
8527
  const m = a.length, n = b.length;
7944
8528
  const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
@@ -7946,63 +8530,11 @@ function levenshtein(a, b) {
7946
8530
  for (let j = 0; j <= n; j++) dp[0][j] = j;
7947
8531
  for (let i = 1; i <= m; i++) {
7948
8532
  for (let j = 1; j <= n; j++) {
7949
- 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]);
8533
+ 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]);
7950
8534
  }
7951
8535
  }
7952
8536
  return dp[m][n];
7953
8537
  }
7954
- var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
7955
- var snapshotHintShown = /* @__PURE__ */ new WeakSet();
7956
- var CONFIG_DIR2 = join7(homedir5(), ".xbrowser");
7957
- var storageCache = /* @__PURE__ */ new Map();
7958
- function getPluginStorage(pluginName) {
7959
- if (!storageCache.has(pluginName)) {
7960
- storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
7961
- }
7962
- return storageCache.get(pluginName);
7963
- }
7964
- var archiveInitialized = false;
7965
- function ensureArchiveInit() {
7966
- if (!archiveInitialized) {
7967
- try {
7968
- configureArchiveStore({ archiveDir: join7(homedir5(), ".xbrowser", "archives") });
7969
- } catch {
7970
- }
7971
- archiveInitialized = true;
7972
- }
7973
- }
7974
- function recordArchive(sessionId, sessionName, entry) {
7975
- if (!sessionId) return;
7976
- try {
7977
- ensureArchiveInit();
7978
- appendCommandToArchive(sessionId, sessionName, entry);
7979
- } catch {
7980
- }
7981
- }
7982
- async function guardCheck(commandName) {
7983
- try {
7984
- const loader = await getPluginLoader();
7985
- const core = loader.getCore();
7986
- return checkGuard(core, commandName, process.env);
7987
- } catch {
7988
- return null;
7989
- }
7990
- }
7991
- function errorResult(message) {
7992
- return { ...fail17(message), duration: 0 };
7993
- }
7994
- function tipsToMessages(tips) {
7995
- if (!tips || tips.length === 0) return [];
7996
- return tips.map((t) => typeof t === "string" ? t : t.message);
7997
- }
7998
- var wsServer = null;
7999
- function streamCommandEvent(sessionId, message) {
8000
- if (!wsServer || !wsServer.getRunning()) return;
8001
- wsServer.broadcastToSession(sessionId, {
8002
- type: "command",
8003
- data: message
8004
- });
8005
- }
8006
8538
  async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
8007
8539
  const guardResult = await guardCheck(commandName);
8008
8540
  if (guardResult?.blocked) {
@@ -8050,8 +8582,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8050
8582
  if (knownPlugins.includes(commandName)) {
8051
8583
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8052
8584
  }
8585
+ const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
8586
+ recordMistake({
8587
+ category: classifyFailure(message).code,
8588
+ command: commandName,
8589
+ message,
8590
+ context: { sessionName, params }
8591
+ });
8053
8592
  return errorResult(
8054
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
8593
+ message
8055
8594
  );
8056
8595
  }
8057
8596
  const _target = params._target;
@@ -8064,9 +8603,14 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8064
8603
  const { _tabIndex: _u, ...rest } = params;
8065
8604
  params = rest;
8066
8605
  }
8606
+ const _frame = params._frame;
8607
+ if (_frame) {
8608
+ const { _frame: _u, ...rest } = params;
8609
+ params = rest;
8610
+ }
8067
8611
  let targetPageOverride = null;
8068
8612
  if (_target && extraOpts?.cdpEndpoint) {
8069
- const { findTargetPage } = await import("./browser-ZD53IMUJ.js");
8613
+ const { findTargetPage } = await import("./browser-KOUA4ZDA.js");
8070
8614
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8071
8615
  if (!targetPageOverride) {
8072
8616
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8084,7 +8628,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8084
8628
  }
8085
8629
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8086
8630
  const { forwardExec } = await import("./daemon-client-7D6EZNOE.js");
8087
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
8631
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8088
8632
  const result = await forwardExec(
8089
8633
  commandName,
8090
8634
  params,
@@ -8130,6 +8674,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8130
8674
  browserContext: session?.context,
8131
8675
  sessionId: session?.id,
8132
8676
  cdpEndpoint: session?.cdpEndpoint || extraOpts?.cdpEndpoint,
8677
+ frame: _frame,
8133
8678
  args: [],
8134
8679
  options: {},
8135
8680
  cwd: process.cwd(),
@@ -8146,7 +8691,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8146
8691
  config: {},
8147
8692
  site: new NoopSiteInstance(),
8148
8693
  cliName: "xbrowser",
8149
- tips: new TipCollector2()
8694
+ tips: new TipCollector3()
8150
8695
  };
8151
8696
  attachDetectAntiBot(ctx);
8152
8697
  if (_tabIndex !== void 0 && session?.context) {
@@ -8178,7 +8723,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8178
8723
  const cache = /* @__PURE__ */ new Map();
8179
8724
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8180
8725
  if (resolved.tips.length > 0) {
8181
- refTips = normalizeTips7(resolved.tips);
8726
+ refTips = normalizeTips8(resolved.tips);
8182
8727
  params = resolved.params;
8183
8728
  }
8184
8729
  }
@@ -8246,11 +8791,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8246
8791
  }
8247
8792
  const merged = [
8248
8793
  ...raw.tips || [],
8249
- ...normalizeTips7(smartTips),
8250
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
8794
+ ...normalizeTips8(smartTips),
8795
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
8251
8796
  ...refTips
8252
8797
  ];
8253
8798
  const isSuccess = raw.success !== false;
8799
+ if (!isSuccess) {
8800
+ recordMistake({
8801
+ category: classifyFailure(raw.message).code,
8802
+ command: commandName,
8803
+ message: raw.message ?? "unknown command failure",
8804
+ context: { sessionName, params }
8805
+ });
8806
+ }
8254
8807
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
8255
8808
  recordArchive(session?.id, sessionName, {
8256
8809
  step: 0,
@@ -8262,7 +8815,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8262
8815
  timestamp: start
8263
8816
  });
8264
8817
  if (isSuccess) {
8265
- return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8818
+ return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8266
8819
  }
8267
8820
  const fc = classifyFailure(raw.message);
8268
8821
  return {
@@ -8275,7 +8828,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8275
8828
  ...hookOutputs ? { hookOutputs } : {}
8276
8829
  };
8277
8830
  }
8278
- const smartTipNormalized = normalizeTips7(smartTips);
8831
+ const smartTipNormalized = normalizeTips8(smartTips);
8279
8832
  recordArchive(session?.id, sessionName, {
8280
8833
  step: 0,
8281
8834
  command: commandName,
@@ -8285,14 +8838,20 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8285
8838
  duration,
8286
8839
  timestamp: start
8287
8840
  });
8288
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8841
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8289
8842
  } catch (err) {
8290
8843
  const end = Date.now();
8291
8844
  const duration = end - start;
8292
8845
  const errorMessage = errMsg(err);
8846
+ recordMistake({
8847
+ category: classifyFailure(errorMessage).code,
8848
+ command: commandName,
8849
+ message: errorMessage,
8850
+ context: { sessionName, params }
8851
+ });
8293
8852
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8294
8853
  try {
8295
- const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
8854
+ const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
8296
8855
  const recovery = await attemptRecovery(
8297
8856
  session.page,
8298
8857
  sessionName,
@@ -8330,280 +8889,12 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8330
8889
  duration,
8331
8890
  timestamp: start
8332
8891
  });
8333
- return { ...fail17(errorMessage), duration };
8892
+ return { ...fail19(errorMessage), duration };
8334
8893
  } finally {
8335
8894
  }
8336
8895
  }
8337
- async function executeChain(input, options) {
8338
- const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8339
- const sessionName = options?.sessionName || "default";
8340
- const results = [];
8341
- const totalStart = Date.now();
8342
- let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8343
- if (!session) {
8344
- const launchOpts = {};
8345
- if (options?.cdpEndpoint) {
8346
- launchOpts.cdpEndpoint = options.cdpEndpoint;
8347
- }
8348
- session = await createSession(sessionName, void 0, launchOpts);
8349
- saveSessionDiskMeta(sessionName, {
8350
- id: session.id,
8351
- name: sessionName,
8352
- url: session.page.url(),
8353
- createdAt: session.createdAt,
8354
- cdpEndpoint: session.cdpEndpoint
8355
- });
8356
- }
8357
- try {
8358
- for (const pipeline of pipelines) {
8359
- const { type, pipeline: commands } = pipeline;
8360
- for (const cmdStr of commands) {
8361
- if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8362
- await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
8363
- }
8364
- const parts = splitCommand(cmdStr);
8365
- if (parts.length === 0) continue;
8366
- const cmdName = parts[0];
8367
- const cmdArgs = parts.slice(1);
8368
- const loader = await getPluginLoader();
8369
- const internalLoader = loader.getCore().loader;
8370
- const resolvedName = loader.resolveSiteName(cmdName);
8371
- const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8372
- if (site) {
8373
- const subCommand = cmdArgs[0];
8374
- if (!subCommand) {
8375
- results.push({
8376
- command: cmdName,
8377
- raw: cmdStr,
8378
- ...fail17(`Plugin "${cmdName}" requires a sub-command`),
8379
- duration: 0
8380
- });
8381
- if (type === "and") {
8382
- return {
8383
- success: false,
8384
- steps: results,
8385
- totalDuration: Date.now() - totalStart,
8386
- stoppedAt: results.length,
8387
- stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
8388
- };
8389
- }
8390
- continue;
8391
- }
8392
- const cmdEntry = site.getCommand(subCommand);
8393
- if (!cmdEntry) {
8394
- results.push({
8395
- command: cmdName,
8396
- raw: cmdStr,
8397
- ...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
8398
- duration: 0
8399
- });
8400
- if (type === "and") {
8401
- return {
8402
- success: false,
8403
- steps: results,
8404
- totalDuration: Date.now() - totalStart,
8405
- stoppedAt: results.length,
8406
- stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
8407
- };
8408
- }
8409
- continue;
8410
- }
8411
- const pluginArgs = cmdArgs.slice(1);
8412
- let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8413
- if (cmdEntry.parameters) {
8414
- const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8415
- if (schemaCheck.success) {
8416
- for (const [k, v] of Object.entries(schemaCheck.data)) {
8417
- if (!(k in pluginParams)) pluginParams[k] = v;
8418
- }
8419
- }
8420
- }
8421
- const pluginCtx = {
8422
- args: pluginArgs,
8423
- options: pluginParams,
8424
- cwd: process.cwd(),
8425
- page: session.page,
8426
- browser: session.context.browser(),
8427
- browserContext: session.context,
8428
- sessionId: session.id,
8429
- storage: getPluginStorage(cmdName),
8430
- output: { mode: "text", showTips: false, color: false, emoji: false },
8431
- error: (msg) => {
8432
- throw new Error(msg);
8433
- },
8434
- config: {},
8435
- site,
8436
- cliName: "xbrowser",
8437
- tips: new TipCollector2()
8438
- };
8439
- const start2 = Date.now();
8440
- try {
8441
- const loginGuard = await checkPluginLoginRequired({
8442
- site,
8443
- command: cmdEntry,
8444
- commandName: subCommand,
8445
- ctx: pluginCtx,
8446
- page: session?.page,
8447
- sessionName
8448
- });
8449
- if (!loginGuard.ok) {
8450
- const duration3 = Date.now() - start2;
8451
- const data2 = loginGuard.data ?? null;
8452
- recordArchive(session.id, sessionName, {
8453
- step: results.length,
8454
- command: `${cmdName} ${subCommand}`,
8455
- params: pluginParams,
8456
- result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8457
- toolCalls: [],
8458
- duration: duration3,
8459
- timestamp: start2
8460
- });
8461
- results.push({
8462
- command: `${cmdName} ${subCommand}`,
8463
- raw: cmdStr,
8464
- success: false,
8465
- data: data2,
8466
- message: loginGuard.message,
8467
- tips: normalizeTips7(loginGuard.tips),
8468
- duration: duration3
8469
- });
8470
- if (type === "and") {
8471
- return {
8472
- success: false,
8473
- steps: results,
8474
- totalDuration: Date.now() - totalStart,
8475
- stoppedAt: results.length,
8476
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
8477
- };
8478
- }
8479
- continue;
8480
- }
8481
- const hooks = await loadHooks();
8482
- if (hooks.length > 0) {
8483
- await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
8484
- }
8485
- const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8486
- const duration2 = Date.now() - start2;
8487
- let hookOutputs;
8488
- if (hooks.length > 0) {
8489
- const outputs = [];
8490
- for (const h of hooks) {
8491
- const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
8492
- if (output) outputs.push({ _hook: h.name, ...output });
8493
- }
8494
- if (outputs.length > 0) hookOutputs = outputs;
8495
- }
8496
- const data = raw?.data ?? raw;
8497
- recordArchive(session.id, sessionName, {
8498
- step: results.length,
8499
- command: `${cmdName} ${subCommand}`,
8500
- params: pluginParams,
8501
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
8502
- toolCalls: [],
8503
- duration: duration2,
8504
- timestamp: start2
8505
- });
8506
- results.push({
8507
- command: `${cmdName} ${subCommand}`,
8508
- raw: cmdStr,
8509
- ...ok32(data),
8510
- duration: duration2,
8511
- ...hookOutputs ? { hookOutputs } : {}
8512
- });
8513
- if (type === "or") {
8514
- return {
8515
- success: true,
8516
- steps: results,
8517
- totalDuration: Date.now() - totalStart,
8518
- stoppedAt: results.length,
8519
- stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
8520
- };
8521
- }
8522
- } catch (err) {
8523
- const duration2 = Date.now() - start2;
8524
- const errorMessage = errMsg(err);
8525
- recordArchive(session.id, sessionName, {
8526
- step: results.length,
8527
- command: `${cmdName} ${subCommand}`,
8528
- params: pluginParams,
8529
- result: { success: false, data: null, message: errorMessage, tips: [] },
8530
- toolCalls: [],
8531
- duration: duration2,
8532
- timestamp: start2
8533
- });
8534
- results.push({
8535
- command: `${cmdName} ${subCommand}`,
8536
- raw: cmdStr,
8537
- ...fail17(errorMessage),
8538
- duration: duration2
8539
- });
8540
- if (type === "and") {
8541
- return {
8542
- success: false,
8543
- steps: results,
8544
- totalDuration: Date.now() - totalStart,
8545
- stoppedAt: results.length,
8546
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
8547
- };
8548
- }
8549
- }
8550
- continue;
8551
- }
8552
- const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8553
- if (cmdName === "goto" && params.url) {
8554
- const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8555
- if (!existing2) {
8556
- session = await createSession(sessionName, params.url, {
8557
- cdpEndpoint: options?.cdpEndpoint
8558
- });
8559
- }
8560
- }
8561
- const start = Date.now();
8562
- const result = await executeCommand(cmdName, params, sessionName, {
8563
- cdpEndpoint: options?.cdpEndpoint,
8564
- skipCleanup: true
8565
- // executeChain's finally handles cleanup
8566
- });
8567
- const duration = Date.now() - start;
8568
- const stepResult = {
8569
- command: cmdName,
8570
- raw: cmdStr,
8571
- success: result.success,
8572
- data: result.data,
8573
- message: result.message,
8574
- duration,
8575
- tips: result.tips,
8576
- ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8577
- };
8578
- results.push(stepResult);
8579
- if (type === "and" && !result.success) {
8580
- return {
8581
- success: false,
8582
- steps: results,
8583
- totalDuration: Date.now() - totalStart,
8584
- stoppedAt: results.length,
8585
- stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
8586
- };
8587
- }
8588
- if (type === "or" && result.success) {
8589
- return {
8590
- success: true,
8591
- steps: results,
8592
- totalDuration: Date.now() - totalStart,
8593
- stoppedAt: results.length,
8594
- stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
8595
- };
8596
- }
8597
- }
8598
- }
8599
- const anyFailed = results.some((r) => !r.success);
8600
- return {
8601
- success: !anyFailed,
8602
- steps: results,
8603
- totalDuration: Date.now() - totalStart
8604
- };
8605
- } finally {
8606
- }
8896
+ async function executeChain2(input, options) {
8897
+ return executeChain(input, options, executeCommand);
8607
8898
  }
8608
8899
 
8609
8900
  // src/daemon/api-analyzer.ts
@@ -9154,7 +9445,7 @@ var PlaybackEngine = class _PlaybackEngine {
9154
9445
  };
9155
9446
 
9156
9447
  // src/daemon/rpc-handlers.ts
9157
- import { TipCollector as TipCollector3 } from "@dyyz1993/xcli-core";
9448
+ import { TipCollector as TipCollector4 } from "@dyyz1993/xcli-core";
9158
9449
  var activeRecorders = /* @__PURE__ */ new Map();
9159
9450
  var replayResumeResolvers = /* @__PURE__ */ new Map();
9160
9451
  function createRPCHandler() {
@@ -9322,7 +9613,7 @@ function createRPCHandler() {
9322
9613
  waitForHuman: async () => {
9323
9614
  return { solved: false, timedOut: true };
9324
9615
  },
9325
- tips: new TipCollector3()
9616
+ tips: new TipCollector4()
9326
9617
  };
9327
9618
  attachDetectAntiBot(ctx);
9328
9619
  const loginGuard = await checkPluginLoginRequired({
@@ -9341,7 +9632,7 @@ function createRPCHandler() {
9341
9632
  return result;
9342
9633
  } catch (err) {
9343
9634
  const errorMessage = errMsg(err);
9344
- const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
9635
+ const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
9345
9636
  const recovery = await attemptRecovery(
9346
9637
  session?.page,
9347
9638
  sessionName,
@@ -9503,14 +9794,14 @@ function createRPCHandler() {
9503
9794
  const input = params.chain;
9504
9795
  const sessionName = params.session || "default";
9505
9796
  const cdp = params.cdpEndpoint;
9506
- const result = await executeChain(input, { cdpEndpoint: cdp, sessionName });
9797
+ const result = await executeChain2(input, { cdpEndpoint: cdp, sessionName });
9507
9798
  registerSessionIfNew(sessionName);
9508
9799
  return result;
9509
9800
  }
9510
9801
  async function handlePluginsReload() {
9511
- const { resetPluginLoader } = await import("./plugin-singleton-GGSBI3EG.js");
9802
+ const { resetPluginLoader } = await import("./plugin-singleton-A6RNITJW.js");
9512
9803
  resetPluginLoader();
9513
- const loader = await import("./plugin-singleton-GGSBI3EG.js").then((m) => m.getPluginLoader());
9804
+ const loader = await import("./plugin-singleton-A6RNITJW.js").then((m) => m.getPluginLoader());
9514
9805
  const sites = loader.getCore().loader.getSites();
9515
9806
  return { ok: true, plugins: sites.length };
9516
9807
  }
@@ -9906,7 +10197,7 @@ function createRPCHandler() {
9906
10197
  if (isNewFormat) {
9907
10198
  try {
9908
10199
  const replayErrors = [];
9909
- const { SessionReplayer } = await import("./session-replayer-TXTNTG33.js");
10200
+ const { SessionReplayer } = await import("./session-replayer-XLWQ47BB.js");
9910
10201
  const replayer = new SessionReplayer({
9911
10202
  page: session.page,
9912
10203
  stepDelay: slowMo * 500,
@@ -9958,10 +10249,10 @@ function createRPCHandler() {
9958
10249
  const errors = Array.isArray(input.errors) ? input.errors : [];
9959
10250
  const eventsPlayed = typeof input.eventsPlayed === "number" ? input.eventsPlayed : 0;
9960
10251
  const totalEvents = typeof input.totalEvents === "number" ? input.totalEvents : eventsPlayed + errors.length;
9961
- const ok33 = input.ok ?? errors.length === 0;
10252
+ const ok34 = input.ok ?? errors.length === 0;
9962
10253
  return {
9963
- ok: ok33,
9964
- success: ok33,
10254
+ ok: ok34,
10255
+ success: ok34,
9965
10256
  duration: typeof input.duration === "number" ? input.duration : 0,
9966
10257
  eventsPlayed,
9967
10258
  totalEvents,
@@ -10150,8 +10441,8 @@ var FrameProcessor = class {
10150
10441
  screencastQuality = 80;
10151
10442
  async process(data, config, viewportWidth, viewportHeight, cropConfig) {
10152
10443
  const buffer = Buffer.from(data, "base64");
10153
- const needsResize = config.scale < 1 && !!viewportWidth && !!viewportHeight;
10154
10444
  const needsCrop = !!cropConfig;
10445
+ const needsResize = needsCrop && !!cropConfig || config.scale < 1 && !!viewportWidth && !!viewportHeight;
10155
10446
  const needsReencode = config.format !== this.screencastFormat || config.quality !== this.screencastQuality;
10156
10447
  if (!needsResize && !needsCrop && !needsReencode) {
10157
10448
  return buffer;
@@ -10180,9 +10471,15 @@ var FrameProcessor = class {
10180
10471
  }
10181
10472
  }
10182
10473
  if (needsResize) {
10183
- const newWidth = Math.round((viewportWidth ?? 0) * config.scale);
10184
- const newHeight = Math.round((viewportHeight ?? 0) * config.scale);
10185
- processed = processed.resize(newWidth, newHeight);
10474
+ const newWidth = Math.round(
10475
+ cropConfig ? cropConfig.width : (viewportWidth ?? 0) * config.scale
10476
+ );
10477
+ const newHeight = Math.round(
10478
+ cropConfig ? cropConfig.height : (viewportHeight ?? 0) * config.scale
10479
+ );
10480
+ if (newWidth > 0 && newHeight > 0) {
10481
+ processed = processed.resize(newWidth, newHeight);
10482
+ }
10186
10483
  }
10187
10484
  if (config.format === "jpeg") {
10188
10485
  processed = processed.jpeg({ quality: config.quality });
@@ -10205,6 +10502,8 @@ var StreamCoordinator = class {
10205
10502
  sink;
10206
10503
  lastFrameData = null;
10207
10504
  lastFrameViewport = null;
10505
+ lastUncroppedFrameData = null;
10506
+ lastUncroppedFrameViewport = null;
10208
10507
  stateManager = new StreamStateManager();
10209
10508
  frameRateController = new FrameRateController();
10210
10509
  frameProcessor = new FrameProcessor();
@@ -10236,6 +10535,8 @@ var StreamCoordinator = class {
10236
10535
  clearLastFrame() {
10237
10536
  this.lastFrameData = null;
10238
10537
  this.lastFrameViewport = null;
10538
+ this.lastUncroppedFrameData = null;
10539
+ this.lastUncroppedFrameViewport = null;
10239
10540
  }
10240
10541
  // -----------------------------------------------------------------------
10241
10542
  // Frame capture callbacks (used by SessionManager)
@@ -10249,15 +10550,16 @@ var StreamCoordinator = class {
10249
10550
  return (frame) => {
10250
10551
  resetStaticSnapshotTimer();
10251
10552
  (async () => {
10252
- this.lastFrameData = frame.data.toString("base64");
10253
- this.lastFrameViewport = frame.viewport;
10553
+ const data = frame.data.toString("base64");
10554
+ this.lastUncroppedFrameData = data;
10555
+ this.lastUncroppedFrameViewport = frame.viewport;
10254
10556
  this.stateManager.onFrameReceived();
10255
10557
  const config = this.stateManager.getConfig();
10256
10558
  if (!this.frameRateController.shouldSendFrame(config.maxFps)) {
10257
10559
  return;
10258
10560
  }
10259
10561
  await this.processAndBroadcast(
10260
- this.lastFrameData,
10562
+ data,
10261
10563
  frame.viewport,
10262
10564
  sessionId,
10263
10565
  frame.sessionId,
@@ -10275,7 +10577,8 @@ var StreamCoordinator = class {
10275
10577
  */
10276
10578
  async takeStaticSnapshot(sessionId, page, clientCount) {
10277
10579
  if (clientCount <= 0) return;
10278
- let viewport = page.viewportSize();
10580
+ const logicalViewport = page.viewportSize();
10581
+ let viewport = logicalViewport;
10279
10582
  if (!viewport) {
10280
10583
  try {
10281
10584
  viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
@@ -10284,10 +10587,11 @@ var StreamCoordinator = class {
10284
10587
  }
10285
10588
  }
10286
10589
  const screenshot = await page.screenshot({ type: "jpeg", quality: 100 });
10287
- this.lastFrameData = screenshot.toString("base64");
10288
- this.lastFrameViewport = viewport;
10590
+ const data = screenshot.toString("base64");
10591
+ this.lastUncroppedFrameData = data;
10592
+ this.lastUncroppedFrameViewport = viewport;
10289
10593
  await this.processAndBroadcast(
10290
- this.lastFrameData,
10594
+ data,
10291
10595
  viewport,
10292
10596
  sessionId,
10293
10597
  sessionId,
@@ -10301,10 +10605,12 @@ var StreamCoordinator = class {
10301
10605
  * replay and crop changes).
10302
10606
  */
10303
10607
  async replayLastFrame(sessionId) {
10304
- if (!this.lastFrameData || !this.lastFrameViewport) return;
10608
+ const data = this.lastUncroppedFrameData ?? this.lastFrameData;
10609
+ const viewport = this.lastUncroppedFrameViewport ?? this.lastFrameViewport;
10610
+ if (!data || !viewport) return;
10305
10611
  await this.processAndBroadcast(
10306
- this.lastFrameData,
10307
- this.lastFrameViewport,
10612
+ data,
10613
+ viewport,
10308
10614
  sessionId,
10309
10615
  sessionId,
10310
10616
  crypto.randomUUID(),
@@ -10324,8 +10630,11 @@ var StreamCoordinator = class {
10324
10630
  async processAndBroadcast(frameData, frameViewport, sessionId, frameSessionId, frameId, frameTimestamp, frameUrl) {
10325
10631
  const config = this.stateManager.getConfig();
10326
10632
  const crop = this.sessionCrops.get(sessionId);
10327
- const cropConfig = crop ? crop.box : void 0;
10328
- const effectiveViewport = crop ? { width: crop.box.width, height: crop.box.height } : frameViewport;
10633
+ const cropFitsViewport = crop ? crop.box.x >= 0 && crop.box.y >= 0 && crop.box.x + crop.box.width <= frameViewport.width + 1 && crop.box.y + crop.box.height <= frameViewport.height + 1 : true;
10634
+ const cropConfig = crop && cropFitsViewport ? crop.box : void 0;
10635
+ const frameIsAlreadyCrop = crop && !cropConfig && Math.abs(frameViewport.width - crop.box.width) <= 1 && Math.abs(frameViewport.height - crop.box.height) <= 1;
10636
+ const processCrop = frameIsAlreadyCrop ? void 0 : cropConfig;
10637
+ const effectiveViewport = cropConfig ? { width: cropConfig.width, height: cropConfig.height } : frameViewport;
10329
10638
  const adjustedConfig = adjustConfigForSize(
10330
10639
  config,
10331
10640
  effectiveViewport.width,
@@ -10336,11 +10645,12 @@ var StreamCoordinator = class {
10336
10645
  const processedBuffer = await this.frameProcessor.process(
10337
10646
  frameData,
10338
10647
  adjustedConfig,
10339
- // Pass the ORIGINAL viewport (not cropped) so crop coordinates
10340
- // can be scaled correctly from viewport space to frame pixel space.
10341
- crop ? frameViewport.width : effectiveViewport.width,
10342
- crop ? frameViewport.height : effectiveViewport.height,
10343
- cropConfig
10648
+ // The full viewport maps crop coordinates to source-frame pixels.
10649
+ // FrameProcessor sizes the final crop from cropConfig, never from this
10650
+ // full-page viewport.
10651
+ frameViewport.width,
10652
+ frameViewport.height,
10653
+ processCrop
10344
10654
  );
10345
10655
  const header = Buffer.from(JSON.stringify({
10346
10656
  type: "screenshot",
@@ -10349,7 +10659,7 @@ var StreamCoordinator = class {
10349
10659
  id: frameId,
10350
10660
  timestamp: frameTimestamp,
10351
10661
  url: frameUrl,
10352
- viewport: effectiveViewport,
10662
+ viewport: cropConfig ? effectiveViewport : frameViewport,
10353
10663
  streamState: this.stateManager.getState(),
10354
10664
  fps: this.frameRateController.getCurrentFps()
10355
10665
  }
@@ -10357,6 +10667,8 @@ var StreamCoordinator = class {
10357
10667
  const headerLen = Buffer.alloc(4);
10358
10668
  headerLen.writeUInt32BE(header.length, 0);
10359
10669
  const payload = Buffer.concat([headerLen, header, processedBuffer]);
10670
+ this.lastFrameData = frameData;
10671
+ this.lastFrameViewport = frameViewport;
10360
10672
  this.sink.broadcastBinaryToSession(sessionId, payload);
10361
10673
  }
10362
10674
  };
@@ -10491,21 +10803,58 @@ var ElementMonitor = class {
10491
10803
  if (this.getClientCount() <= 0) return;
10492
10804
  try {
10493
10805
  const elements = await this.page.evaluate(() => {
10494
- const sel = '[role="dialog"],dialog,[class*="modal"],[class*="popup"],[class*="overlay"],[class*="drawer"],form';
10806
+ const sel = [
10807
+ '[role="dialog"]',
10808
+ "dialog",
10809
+ '[class*="modal"]',
10810
+ '[class*="popup"]',
10811
+ '[class*="overlay"]',
10812
+ '[class*="drawer"]',
10813
+ "form",
10814
+ "img",
10815
+ "canvas"
10816
+ ].join(",");
10495
10817
  const els = document.querySelectorAll(sel);
10496
10818
  const results = [];
10497
10819
  const vpW = window.innerWidth, vpH = window.innerHeight;
10498
10820
  for (const el of els) {
10499
10821
  const r = el.getBoundingClientRect();
10500
- if (r.width < 50 || r.height < 30) continue;
10501
- if (r.width * r.height > vpW * vpH * 0.9) continue;
10502
10822
  const style = window.getComputedStyle(el);
10503
10823
  if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") continue;
10824
+ if (r.bottom < 0 || r.right < 0 || r.top > vpH || r.left > vpW) continue;
10504
10825
  const htmlEl = el;
10826
+ const isImage = el.tagName === "IMG" || el.tagName === "CANVAS";
10827
+ const semantic = `${el.id} ${typeof htmlEl.className === "string" ? htmlEl.className : ""} ${el.getAttribute("alt") || ""} ${el.getAttribute("title") || ""} ${el.getAttribute("src") || ""}`.toLowerCase();
10828
+ const looksLikeQr = isImage && /(qr|qrcode|barcode|二维码)/.test(semantic);
10829
+ const square = Math.abs(r.width - r.height) <= Math.max(8, Math.min(r.width, r.height) * 0.12);
10830
+ if (isImage) {
10831
+ if (r.width < 48 || r.height < 48) continue;
10832
+ if (r.width > vpW || r.height > vpH) continue;
10833
+ if (looksLikeQr && !square) continue;
10834
+ if (!looksLikeQr && !el.getAttribute("src") && !el.getAttribute("alt") && !el.getAttribute("title")) continue;
10835
+ } else {
10836
+ if (r.width < 50 || r.height < 30) continue;
10837
+ if (r.width * r.height > vpW * vpH * 0.9) continue;
10838
+ }
10839
+ let kind = "view";
10840
+ let src;
10841
+ let text;
10842
+ if (looksLikeQr) {
10843
+ kind = "qr";
10844
+ src = el.getAttribute("src") || void 0;
10845
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
10846
+ } else if (isImage) {
10847
+ kind = "image";
10848
+ src = el.getAttribute("src") || void 0;
10849
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
10850
+ }
10505
10851
  results.push({
10506
10852
  tag: el.tagName,
10507
10853
  id: el.id || "",
10508
10854
  cls: (typeof htmlEl.className === "string" ? htmlEl.className : "").slice(0, 40),
10855
+ kind,
10856
+ ...src ? { src } : {},
10857
+ ...text ? { text } : {},
10509
10858
  rect: { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }
10510
10859
  });
10511
10860
  }
@@ -10522,9 +10871,12 @@ var ElementMonitor = class {
10522
10871
  if (!dupe) deduped.push(el);
10523
10872
  }
10524
10873
  deduped.sort((a, b) => b.rect.width * b.rect.height - a.rect.width * a.rect.height);
10874
+ deduped.sort((a, b) => Number(b.kind === "qr") - Number(a.kind === "qr"));
10525
10875
  const views = deduped.map((e, i) => ({
10526
10876
  id: "el-" + i + "-" + (e.id || e.tag),
10527
- label: e.id || e.cls || e.tag,
10877
+ label: e.kind === "qr" ? e.text || "QR code" : e.kind === "image" ? e.text || e.src || "Image" : e.id || e.cls || e.tag,
10878
+ kind: e.kind,
10879
+ ...e.src ? { src: e.src } : {},
10528
10880
  rect: e.rect
10529
10881
  }));
10530
10882
  this.onViewsUpdate({ type: "views_update", views });
@@ -10577,7 +10929,11 @@ var SessionManager = class extends EventEmitter {
10577
10929
  // Session registration
10578
10930
  // -----------------------------------------------------------------------
10579
10931
  registerSession(sessionId, page, options) {
10580
- if (this.screencasts.has(sessionId)) return;
10932
+ if (this.screencasts.has(sessionId)) {
10933
+ if (this.screencasts.get(sessionId).page === page) return;
10934
+ this.updateSessionPage(sessionId, page);
10935
+ return;
10936
+ }
10581
10937
  this.screencasts.set(sessionId, {
10582
10938
  capturer: new ScreencastCapturer({
10583
10939
  interval: options?.interval ?? 100,
@@ -10603,6 +10959,53 @@ var SessionManager = class extends EventEmitter {
10603
10959
  }
10604
10960
  }
10605
10961
  }
10962
+ // Per-session serialization for page switches: rapid `tab switch` commands
10963
+ // must not interleave stopCapture/startCapture on the shared capturer.
10964
+ pageSwitchTasks = /* @__PURE__ */ new Map();
10965
+ /**
10966
+ * Rebind an already-registered session to a new Page (e.g. after
10967
+ * `tab switch` / `tab new` / `tab close` rebound the session's active
10968
+ * page). Moves the ElementMonitor to the new page, notifies viewers via
10969
+ * the `page-switched` event, and restarts the capturer when it is
10970
+ * streaming so frames immediately come from the new tab.
10971
+ */
10972
+ updateSessionPage(sessionId, page) {
10973
+ const sc = this.screencasts.get(sessionId);
10974
+ if (!sc || sc.page === page) return;
10975
+ const oldMonitor = this.monitors.get(sessionId);
10976
+ if (oldMonitor) {
10977
+ oldMonitor.stop();
10978
+ this.monitors.delete(sessionId);
10979
+ }
10980
+ const monitor = new ElementMonitor(
10981
+ page,
10982
+ (msg) => this.emit("broadcast", sessionId, msg),
10983
+ (msg) => this.emit("broadcast", sessionId, msg),
10984
+ () => this.getSessionClientCount(sessionId)
10985
+ );
10986
+ this.monitors.set(sessionId, monitor);
10987
+ monitor.start();
10988
+ sc.page = page;
10989
+ this.emit("page-switched", sessionId, page);
10990
+ const prev = this.pageSwitchTasks.get(sessionId) ?? Promise.resolve();
10991
+ const task = prev.catch(() => {
10992
+ }).then(async () => {
10993
+ const cur = this.screencasts.get(sessionId);
10994
+ if (!cur || cur.page !== page) return;
10995
+ if (cur.capturer.isActive()) {
10996
+ await cur.capturer.stopCapture().catch(() => {
10997
+ });
10998
+ }
10999
+ if (this.screencasts.get(sessionId) === cur && !cur.capturer.isActive() && cur.clientCount > 0) {
11000
+ await this.startCapturer(sessionId).catch(() => {
11001
+ });
11002
+ }
11003
+ });
11004
+ this.pageSwitchTasks.set(sessionId, task);
11005
+ task.finally(() => {
11006
+ if (this.pageSwitchTasks.get(sessionId) === task) this.pageSwitchTasks.delete(sessionId);
11007
+ });
11008
+ }
10606
11009
  unregisterSession(sessionId) {
10607
11010
  const sc = this.screencasts.get(sessionId);
10608
11011
  if (!sc) return;
@@ -11170,6 +11573,10 @@ var WSServer = class extends EventEmitter2 {
11170
11573
  this.sessionManager.on("screencast-stopped", (sessionId) => {
11171
11574
  this.emit("screencast-stopped", sessionId);
11172
11575
  });
11576
+ this.sessionManager.on("page-switched", (sessionId, page) => {
11577
+ this.streamCoordinator.clearLastFrame();
11578
+ this.broadcastToSession(sessionId, { type: "navigation", url: page.url(), title: "" });
11579
+ });
11173
11580
  }
11174
11581
  // -----------------------------------------------------------------------
11175
11582
  // Public session API (delegates to SessionManager)
@@ -11408,7 +11815,11 @@ var WSServer = class extends EventEmitter2 {
11408
11815
  return;
11409
11816
  }
11410
11817
  const fmt = msg.format === "webp" ? "webp" : "png";
11411
- page2.screenshot({ type: fmt, quality: fmt === "webp" ? msg.quality ?? 90 : void 0 }).then((buf) => {
11818
+ page2.screenshot({
11819
+ type: fmt,
11820
+ quality: fmt === "webp" ? msg.quality ?? 90 : void 0,
11821
+ ...msg.clip ? { clip: { ...msg.clip, scale: msg.scale } } : {}
11822
+ }).then((buf) => {
11412
11823
  this.sendToClient(clientId, {
11413
11824
  type: "snapshot_result",
11414
11825
  data: { data: buf.toString("base64"), format: fmt }
@@ -11493,7 +11904,7 @@ var WSServer = class extends EventEmitter2 {
11493
11904
  }
11494
11905
  };
11495
11906
 
11496
- // src/daemon/preview-templates.ts
11907
+ // src/daemon/preview-align-template.ts
11497
11908
  function alignHTML(sessionId, _host) {
11498
11909
  return `<!DOCTYPE html>
11499
11910
  <html lang="en"><head><meta charset="utf-8">
@@ -11620,6 +12031,8 @@ connectWS();
11620
12031
  })();
11621
12032
  </script></body></html>`;
11622
12033
  }
12034
+
12035
+ // src/daemon/preview-main-template.ts
11623
12036
  function previewHTML(sessionId, _host) {
11624
12037
  return `<!DOCTYPE html>
11625
12038
  <html lang="en"><head><meta charset="utf-8">
@@ -11833,17 +12246,27 @@ $('reconnect-btn').addEventListener('click',()=>{
11833
12246
  // Preview shows in bottom-right for 5s with countdown \u2192 click to fullscreen
11834
12247
  var snapshotDataUrl=null;
11835
12248
  var snapshotCountdownTimer=null;
12249
+ var suppressSnapshotPreview=false;
11836
12250
  $('snapshot-btn').addEventListener('click',function(){
11837
12251
  var btn=$('snapshot-btn');
11838
12252
  btn.textContent='\u23F3';
11839
- // Request high-quality screenshot from daemon
11840
- sendMsg({type:'snapshot_request',format:'webp',quality:90});
12253
+ requestSnapshot();
11841
12254
  });
12255
+ function requestSnapshot(clip,scale){
12256
+ var btn=$('snapshot-btn');
12257
+ if(btn) btn.textContent='\u23F3';
12258
+ sendMsg({type:'snapshot_request',format:'webp',quality:95,...(clip?{clip:clip,scale:scale||1}:{})});
12259
+ }
11842
12260
  // Handle snapshot response
11843
12261
  // (added to ws.onmessage handler below)
11844
12262
  var snapshotPendingHandler=function(msg){
11845
12263
  if(msg.type==='snapshot_result'&&msg.data){
11846
12264
  var data=msg.data;
12265
+ if(suppressSnapshotPreview){
12266
+ suppressSnapshotPreview=false;
12267
+ $('snapshot-btn').textContent='\u{1F4F7}';
12268
+ return;
12269
+ }
11847
12270
  snapshotDataUrl='data:image/'+(data.format||'png')+';base64,'+data.data;
11848
12271
  var img=$('snapshot-img');
11849
12272
  img.src=snapshotDataUrl;
@@ -11892,6 +12315,15 @@ $('snapshot-preview').addEventListener('click',function(){
11892
12315
  $('snapshot-fullscreen').addEventListener('click',function(){
11893
12316
  this.style.display='none';
11894
12317
  });
12318
+ document.addEventListener('keydown',function(e){
12319
+ if(e.key==='Escape'){
12320
+ var fullscreen=$('snapshot-fullscreen');
12321
+ if(fullscreen.style.display==='flex'){
12322
+ fullscreen.style.display='none';
12323
+ e.stopPropagation();
12324
+ }
12325
+ }
12326
+ },true);
11895
12327
  // Auto-detect dead connection: if no frames for 30s, show warning
11896
12328
  let lastFrameAt=Date.now();
11897
12329
  setInterval(()=>{
@@ -12010,13 +12442,24 @@ function connectWS(){
12010
12442
  statLatency=Math.max(0,Date.now()-header.data.timestamp);
12011
12443
  }
12012
12444
  const blob=new Blob([jpegData],{type:'image/jpeg'});
12013
- createImageBitmap(blob).then(function(bmp){
12014
- drawFrame(bmp);
12015
- bmp.close();
12016
- });
12017
- canvas.style.display='block';
12018
- wait.style.display='none';
12019
- if(header.data.viewport&&!viewportLocked&&!viewSwitching){remoteViewport=header.data.viewport;viewportLocked=true;resizeCanvas();}
12445
+ var incomingViewport=header.data.viewport;
12446
+ if(incomingViewport&&!viewportLocked&&!viewSwitching){
12447
+ remoteViewport={width:incomingViewport.width,height:incomingViewport.height};
12448
+ viewportLocked=true;
12449
+ resizeCanvas();
12450
+ }
12451
+ // During view switches the server can still deliver one in-flight
12452
+ // full-page frame after the crop status arrives. Drawing it while
12453
+ // remoteViewport remains the crop size produces a stretched corner.
12454
+ var viewportMatches=!incomingViewport||(incomingViewport.width===remoteViewport.width&&incomingViewport.height===remoteViewport.height);
12455
+ if(viewportMatches){
12456
+ createImageBitmap(blob).then(function(bmp){
12457
+ drawFrame(bmp);
12458
+ bmp.close();
12459
+ });
12460
+ canvas.style.display='block';
12461
+ wait.style.display='none';
12462
+ }
12020
12463
  if(header.data.url&&header.data.url!==currentUrl){
12021
12464
  currentUrl=header.data.url;
12022
12465
  urlEl.textContent=currentUrl;
@@ -12216,6 +12659,17 @@ function selectView(vid){
12216
12659
  }else{
12217
12660
  var v=detectedViews.find(function(x){return x.id===vid});
12218
12661
  if(v){
12662
+ if(v.kind==='image'||v.kind==='qr'){
12663
+ suppressSnapshotPreview=true;
12664
+ requestSnapshot(v.rect,v.kind==='qr'?4:2);
12665
+ if(!originalViewport) originalViewport={width:remoteViewport.width,height:remoteViewport.height};
12666
+ sendMsg({type:'select_view',rect:v.rect});
12667
+ remoteViewport={width:v.rect.width,height:v.rect.height};
12668
+ viewportLocked=true;
12669
+ resizeCanvas();
12670
+ renderViewTabs();
12671
+ return;
12672
+ }
12219
12673
  if(!originalViewport) originalViewport={width:remoteViewport.width,height:remoteViewport.height};
12220
12674
  sendMsg({type:'select_view',rect:v.rect});
12221
12675
  remoteViewport={width:v.rect.width,height:v.rect.height};