@xbrowser/cli 1.28.0 → 1.29.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 (37) hide show
  1. package/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
  2. package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
  3. package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
  4. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
  5. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
  7. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  8. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  9. package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
  10. package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
  11. package/dist/{chunk-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
  12. package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
  13. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  14. package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
  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-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
  18. package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
  19. package/dist/{chunk-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
  20. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  21. package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
  22. package/dist/cli.js +3398 -3357
  23. package/dist/daemon-main.js +737 -707
  24. package/dist/index.d.ts +362 -474
  25. package/dist/index.js +5730 -5689
  26. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  27. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  28. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  29. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  30. package/dist/{server-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-26SE6YZR.js → server-ZTI2K5YJ.js} +7 -7
  32. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
  33. package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
  34. package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
  35. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  36. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  37. package/package.json +6 -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";
@@ -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-FCPVQFTQ.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-CO2ZVOVT.js";
42
43
  import {
43
44
  createRuleEngine
44
- } from "./chunk-ME5FO5YV.js";
45
+ } from "./chunk-NQPXZ74W.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";
@@ -4487,6 +4342,8 @@ var networkCommand = registerCommand({
4487
4342
 
4488
4343
  // src/commands/ai-search-engines.ts
4489
4344
  import { z as z24 } from "zod";
4345
+
4346
+ // src/commands/ai-engine-configs.ts
4490
4347
  var ENGINE_CONFIGS = {
4491
4348
  deepseek: {
4492
4349
  key: "deepseek",
@@ -4739,6 +4596,8 @@ var ENGINE_CONFIGS = {
4739
4596
  sendButtonSelector: "button.send-btn"
4740
4597
  }
4741
4598
  };
4599
+
4600
+ // src/commands/ai-search-engines.ts
4742
4601
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
4743
4602
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
4744
4603
 
@@ -5910,12 +5769,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
5910
5769
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
5911
5770
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
5912
5771
  {"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
5772
+ {"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
5913
5773
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
5914
5774
 
5915
5775
  \u89C4\u5219\uFF1A
5916
5776
  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
5777
  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`;
5778
+ 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
5779
  function extractDecision(raw) {
5920
5780
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
5921
5781
  const start = s.indexOf("{");
@@ -5966,6 +5826,7 @@ var taskCommand = registerCommand({
5966
5826
  let status = "max_steps";
5967
5827
  let summary = "";
5968
5828
  let lastError = "";
5829
+ let emptyReplies = 0;
5969
5830
  for (let step = 1; step <= p.maxSteps; step++) {
5970
5831
  if (Date.now() - started > p.timeout) {
5971
5832
  status = "blocked";
@@ -5985,7 +5846,7 @@ ${history.slice(-6).join("\n")}` : ""
5985
5846
  ].filter(Boolean).join("\n");
5986
5847
  let raw = "";
5987
5848
  try {
5988
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5849
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5989
5850
 
5990
5851
  ---
5991
5852
 
@@ -5999,6 +5860,12 @@ ${userPayload}` }], 900);
5999
5860
  }
6000
5861
  const decision = extractDecision(raw);
6001
5862
  if (!decision || typeof decision.action !== "string") {
5863
+ if (!raw.trim() && emptyReplies < 2) {
5864
+ emptyReplies++;
5865
+ steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
5866
+ history.push(`step${step}: (empty reply, retrying)`);
5867
+ continue;
5868
+ }
6002
5869
  status = "blocked";
6003
5870
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
6004
5871
  break;
@@ -6013,6 +5880,13 @@ ${userPayload}` }], 900);
6013
5880
  steps.push({ step, thought, action: "done", ok: true, screenHash });
6014
5881
  break;
6015
5882
  }
5883
+ if (action === "back") {
5884
+ await ctx.page?.goBack?.().catch?.(() => {
5885
+ });
5886
+ steps.push({ step, thought, action: "back", ok: true, screenHash });
5887
+ history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
5888
+ continue;
5889
+ }
6016
5890
  if (action === "blocked") {
6017
5891
  status = "blocked";
6018
5892
  summary = value || thought || "LLM judged blocked";
@@ -6753,6 +6627,8 @@ var visualTagCommand = registerCommand({
6753
6627
  // src/commands/visual-tag-v2.ts
6754
6628
  import { z as z32 } from "zod";
6755
6629
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6630
+
6631
+ // src/commands/visual-tag-v2-script.ts
6756
6632
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6757
6633
  var TAG_V2_SCRIPT = `
6758
6634
  (function() {
@@ -7095,7 +6971,9 @@ var TAG_V2_SCRIPT = `
7095
6971
  return JSON.stringify(window.__xbTagStats);
7096
6972
  })()
7097
6973
  `;
7098
- var visualTagV2Command = registerCommand({
6974
+
6975
+ // src/commands/visual-tag-v2.ts
6976
+ registerCommand({
7099
6977
  name: "visual-tag-v2",
7100
6978
  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
6979
  scope: "page",
@@ -7328,168 +7206,60 @@ function attachDetectAntiBot(ctx) {
7328
7206
  };
7329
7207
  }
7330
7208
 
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 {
7209
+ // src/tips/dom-watcher.ts
7210
+ var DOM_WATCHER_SCRIPT = `
7211
+ (function() {
7212
+ if (window.__xbrowserDomWatcher) return;
7213
+ window.__xbrowserDomWatcher = true;
7214
+
7215
+ window.__xbrowserDetectedElements = [];
7216
+
7217
+ function getSelector(el) {
7218
+ if (el.id) return '#' + CSS.escape(el.id);
7219
+ if (el.getAttribute('aria-label')) {
7220
+ return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
7353
7221
  }
7222
+ const cls = el.className && typeof el.className === 'string'
7223
+ ? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
7224
+ : '';
7225
+ if (cls) return el.tagName.toLowerCase() + '.' + cls;
7226
+ return el.tagName.toLowerCase();
7354
7227
  }
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 {
7228
+
7229
+ function isPopupLike(el) {
7230
+ const tag = el.tagName?.toLowerCase();
7231
+ if (tag === 'dialog') return true;
7232
+ if (tag === 'body' || tag === 'html') return false;
7233
+
7234
+ const role = el.getAttribute('role');
7235
+ if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
7236
+
7237
+ const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7238
+ const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
7239
+ if (popupPatterns.test(cls)) return true;
7240
+
7241
+ const style = window.getComputedStyle(el);
7242
+ if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
7243
+ const rect = el.getBoundingClientRect();
7244
+ if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
7367
7245
  }
7246
+
7247
+ return false;
7368
7248
  }
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
- // src/tips/dom-watcher.ts
7440
- var DOM_WATCHER_SCRIPT = `
7441
- (function() {
7442
- if (window.__xbrowserDomWatcher) return;
7443
- window.__xbrowserDomWatcher = true;
7444
-
7445
- window.__xbrowserDetectedElements = [];
7446
-
7447
- function getSelector(el) {
7448
- if (el.id) return '#' + CSS.escape(el.id);
7449
- if (el.getAttribute('aria-label')) {
7450
- return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
7451
- }
7452
- const cls = el.className && typeof el.className === 'string'
7453
- ? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
7454
- : '';
7455
- if (cls) return el.tagName.toLowerCase() + '.' + cls;
7456
- return el.tagName.toLowerCase();
7457
- }
7458
-
7459
- function isPopupLike(el) {
7460
- const tag = el.tagName?.toLowerCase();
7461
- if (tag === 'dialog') return true;
7462
- if (tag === 'body' || tag === 'html') return false;
7463
-
7464
- const role = el.getAttribute('role');
7465
- if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
7466
-
7467
- const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7468
- const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
7469
- if (popupPatterns.test(cls)) return true;
7470
-
7471
- const style = window.getComputedStyle(el);
7472
- if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
7473
- const rect = el.getBoundingClientRect();
7474
- if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
7475
- }
7476
-
7477
- return false;
7478
- }
7479
-
7480
- function categorize(el) {
7481
- const tag = el.tagName?.toLowerCase();
7482
- const role = el.getAttribute('role');
7483
- const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7484
-
7485
- if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
7486
- if (role === 'popover' || /popover/.test(cls)) return 'popover';
7487
- if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
7488
- if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
7489
- if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
7490
- if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
7491
- if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
7492
- return 'unknown';
7249
+
7250
+ function categorize(el) {
7251
+ const tag = el.tagName?.toLowerCase();
7252
+ const role = el.getAttribute('role');
7253
+ const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7254
+
7255
+ if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
7256
+ if (role === 'popover' || /popover/.test(cls)) return 'popover';
7257
+ if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
7258
+ if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
7259
+ if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
7260
+ if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
7261
+ if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
7262
+ return 'unknown';
7493
7263
  }
7494
7264
 
7495
7265
  function extractElement(el) {
@@ -7882,63 +7652,620 @@ var HOOK_REGISTRY = {
7882
7652
  if (!tips.some((t) => t.includes("viewer") || t.includes("Viewer"))) {
7883
7653
  tips.push(`Open viewer: ${viewerUrl}`);
7884
7654
  }
7885
- result.tips = tips;
7886
- result.viewerUrl = viewerUrl;
7887
- return void 0;
7655
+ result.tips = tips;
7656
+ result.viewerUrl = viewerUrl;
7657
+ return void 0;
7658
+ }
7659
+ },
7660
+ screenshot: {
7661
+ name: "screenshot",
7662
+ onAfterCommand: async (ctx) => {
7663
+ try {
7664
+ const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
7665
+ if (!buf) return;
7666
+ return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
7667
+ } catch {
7668
+ return;
7669
+ }
7670
+ }
7671
+ },
7672
+ recorder: {
7673
+ name: "recorder",
7674
+ onAfterCommand: async (ctx) => {
7675
+ const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
7676
+ logs.push({
7677
+ timestamp: Date.now(),
7678
+ command: ctx.command,
7679
+ params: JSON.parse(JSON.stringify(ctx.params)),
7680
+ duration: ctx.duration
7681
+ });
7682
+ Reflect.set(ctx, "__commandLogs", logs);
7683
+ return void 0;
7684
+ }
7685
+ }
7686
+ };
7687
+ var customHooks = {};
7688
+ async function loadHooks() {
7689
+ const env = process.env.XBROWSER_HOOKS;
7690
+ if (!env) return [];
7691
+ const names = env.split(",").map((n) => n.trim()).filter(Boolean);
7692
+ if (names.length === 0) return [];
7693
+ const hooks = [];
7694
+ for (const name of names) {
7695
+ const hook = HOOK_REGISTRY[name];
7696
+ if (hook) {
7697
+ hooks.push(hook);
7698
+ continue;
7699
+ }
7700
+ const customFactory = customHooks[name];
7701
+ if (customFactory) {
7702
+ const customHook = await customFactory();
7703
+ if (customHook) hooks.push(customHook);
7704
+ }
7705
+ }
7706
+ return hooks;
7707
+ }
7708
+
7709
+ // src/fail-codes.ts
7710
+ var FAIL_CODES = {
7711
+ selectorNotFound: "RETRYABLE: selector-not-found",
7712
+ pageNotReady: "RETRYABLE: page-not-ready",
7713
+ elementGone: "RETRYABLE: element-gone",
7714
+ inputNotRetained: "RETRYABLE: input-not-retained",
7715
+ captcha: "HUMAN: captcha",
7716
+ loginWall: "HUMAN: login-wall",
7717
+ permissionDenied: "FATAL: permission-denied",
7718
+ targetGone: "FATAL: target-gone",
7719
+ unknown: "FATAL: unknown"
7720
+ };
7721
+ function classifyFailure(message) {
7722
+ const msg = (message || "").toLowerCase();
7723
+ const pick = (code) => ({
7724
+ code,
7725
+ level: code.split(":")[0],
7726
+ message: message || code
7727
+ });
7728
+ if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
7729
+ if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
7730
+ if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
7731
+ if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
7732
+ return pick(FAIL_CODES.selectorNotFound);
7733
+ if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
7734
+ if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
7735
+ if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
7736
+ return pick(FAIL_CODES.targetGone);
7737
+ return pick(FAIL_CODES.unknown);
7738
+ }
7739
+
7740
+ // src/executor/foundation.ts
7741
+ import { homedir as homedir5 } from "os";
7742
+ import { join as join7 } from "path";
7743
+ import {
7744
+ CompositeStorage as CompositeStorage2,
7745
+ configureArchiveStore,
7746
+ appendCommandToArchive,
7747
+ fail as fail17,
7748
+ checkGuard
7749
+ } from "@dyyz1993/xcli-core";
7750
+ var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
7751
+ var snapshotHintShown = /* @__PURE__ */ new WeakSet();
7752
+ var CONFIG_DIR2 = join7(homedir5(), ".xbrowser");
7753
+ var storageCache = /* @__PURE__ */ new Map();
7754
+ function getPluginStorage(pluginName) {
7755
+ if (!storageCache.has(pluginName)) {
7756
+ storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
7757
+ }
7758
+ return storageCache.get(pluginName);
7759
+ }
7760
+ var archiveInitialized = false;
7761
+ function ensureArchiveInit() {
7762
+ if (!archiveInitialized) {
7763
+ try {
7764
+ configureArchiveStore({ archiveDir: join7(homedir5(), ".xbrowser", "archives") });
7765
+ } catch {
7766
+ }
7767
+ archiveInitialized = true;
7768
+ }
7769
+ }
7770
+ function recordArchive(sessionId, sessionName, entry) {
7771
+ if (!sessionId) return;
7772
+ try {
7773
+ ensureArchiveInit();
7774
+ appendCommandToArchive(sessionId, sessionName, entry);
7775
+ } catch {
7776
+ }
7777
+ }
7778
+ async function guardCheck(commandName) {
7779
+ try {
7780
+ const loader = await getPluginLoader();
7781
+ return checkGuard(loader.getCore(), commandName, process.env);
7782
+ } catch {
7783
+ return null;
7784
+ }
7785
+ }
7786
+ function errorResult(message) {
7787
+ return { ...fail17(message), duration: 0 };
7788
+ }
7789
+ function tipsToMessages(tips) {
7790
+ if (!tips || tips.length === 0) return [];
7791
+ return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
7792
+ }
7793
+ var wsServer = null;
7794
+ function streamCommandEvent(sessionId, message) {
7795
+ if (!wsServer || !wsServer.getRunning()) return;
7796
+ wsServer.broadcastToSession(sessionId, { type: "command", data: message });
7797
+ }
7798
+
7799
+ // src/executor/chain.ts
7800
+ import {
7801
+ fail as fail18,
7802
+ ok as ok32,
7803
+ TipCollector as TipCollector2,
7804
+ normalizeTips as normalizeTips7,
7805
+ unquote as unquote2
7806
+ } from "@dyyz1993/xcli-core";
7807
+
7808
+ // src/plugin/login-guard.ts
7809
+ async function checkPluginLoginRequired(options) {
7810
+ const { site, command, commandName, ctx, page, sessionName } = options;
7811
+ if (commandName === "login" || commandName === "logout") return { ok: true };
7812
+ const loginConfig = site.config?.loginConfig;
7813
+ const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
7814
+ if (!requiresLogin) return { ok: true };
7815
+ const pluginName = site.name || "plugin";
7816
+ const siteConfig = site.config;
7817
+ const configIsLogin = siteConfig?.isLogin;
7818
+ if (configIsLogin) {
7819
+ try {
7820
+ const loggedIn = await configIsLogin(ctx);
7821
+ if (loggedIn) return { ok: true };
7822
+ return buildLoginRequired({
7823
+ plugin: pluginName,
7824
+ command: commandName,
7825
+ reason: "config.isLogin returned false",
7826
+ sessionName,
7827
+ loginConfig
7828
+ });
7829
+ } catch {
7830
+ }
7831
+ }
7832
+ if (typeof site.isLoggedIn === "function") {
7833
+ try {
7834
+ const loggedIn = await site.isLoggedIn(ctx);
7835
+ if (loggedIn) return { ok: true };
7836
+ return buildLoginRequired({
7837
+ plugin: pluginName,
7838
+ command: commandName,
7839
+ reason: "plugin isLoggedIn returned false",
7840
+ sessionName,
7841
+ loginConfig
7842
+ });
7843
+ } catch {
7844
+ }
7845
+ }
7846
+ if (page && loginConfig) {
7847
+ const generic = await detectLoginFromPage(page, loginConfig);
7848
+ if (generic === "logged-in") return { ok: true };
7849
+ if (generic === "logged-out") {
7850
+ return buildLoginRequired({
7851
+ plugin: pluginName,
7852
+ command: commandName,
7853
+ reason: "generic loginConfig detected logged-out page",
7854
+ sessionName,
7855
+ loginConfig
7856
+ });
7857
+ }
7858
+ }
7859
+ return { ok: true };
7860
+ }
7861
+ function buildLoginRequired(options) {
7862
+ const viewerUrl = buildViewerUrl(options.sessionName);
7863
+ const loginUrl = options.loginConfig?.loginUrl;
7864
+ const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
7865
+ const tips = [
7866
+ message,
7867
+ ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
7868
+ ...loginUrl ? [`Login page: ${loginUrl}`] : [],
7869
+ `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
7870
+ ];
7871
+ return {
7872
+ ok: false,
7873
+ data: {
7874
+ code: "LOGIN_REQUIRED",
7875
+ plugin: options.plugin,
7876
+ command: options.command,
7877
+ reason: options.reason,
7878
+ ...viewerUrl ? { viewerUrl } : {},
7879
+ ...loginUrl ? { loginUrl } : {}
7880
+ },
7881
+ message,
7882
+ tips
7883
+ };
7884
+ }
7885
+ async function detectLoginFromPage(page, config) {
7886
+ const url = page.url();
7887
+ if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
7888
+ const result = await page.evaluate((cfg) => {
7889
+ const visible = (selector) => {
7890
+ try {
7891
+ const el = document.querySelector(selector);
7892
+ if (!el) return false;
7893
+ const rect = el.getBoundingClientRect();
7894
+ const style = window.getComputedStyle(el);
7895
+ return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
7896
+ } catch {
7897
+ return false;
7898
+ }
7899
+ };
7900
+ if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
7901
+ if (cfg.loginSelectors?.some(visible)) return "logged-out";
7902
+ const bodyText = document.body?.innerText || "";
7903
+ const keywords = cfg.loginKeywords || [];
7904
+ if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
7905
+ return "logged-out";
7906
+ }
7907
+ return "unknown";
7908
+ }, {
7909
+ loginSelectors: config.loginSelectors || [],
7910
+ loginKeywords: config.loginKeywords || [],
7911
+ loggedInSelectors: config.loggedInSelectors || []
7912
+ });
7913
+ return result;
7914
+ }
7915
+
7916
+ // src/utils/positional-params.ts
7917
+ import { unquote } from "@dyyz1993/xcli-core";
7918
+ function getTypeName(field) {
7919
+ return field?._def?.typeName;
7920
+ }
7921
+ function unwrapField(field) {
7922
+ const typeName = getTypeName(field);
7923
+ if (typeName === "ZodOptional" || typeName === "ZodDefault") {
7924
+ const innerType = field?._def?.innerType;
7925
+ return unwrapField(innerType);
7926
+ }
7927
+ return field;
7928
+ }
7929
+ function isOptionalNumber(field) {
7930
+ const typeName = getTypeName(field);
7931
+ return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
7932
+ }
7933
+ function coerceValue(raw, field) {
7934
+ const inner = unwrapField(field);
7935
+ const optionalNum = isOptionalNumber(field);
7936
+ const innerTypeName = getTypeName(inner);
7937
+ if (innerTypeName === "ZodString") {
7938
+ return { value: unquote(raw), skip: false };
7939
+ }
7940
+ if (innerTypeName === "ZodNumber") {
7941
+ const parsed = Number(raw);
7942
+ if (isNaN(parsed)) {
7943
+ if (optionalNum) return { value: void 0, skip: true };
7944
+ return { value: raw, skip: false };
7945
+ }
7946
+ return { value: parsed, skip: false };
7947
+ }
7948
+ if (innerTypeName === "ZodBoolean") {
7949
+ if (raw === "true" || raw === "1") return { value: true, skip: false };
7950
+ if (raw === "false" || raw === "0") return { value: false, skip: false };
7951
+ return { value: raw, skip: false };
7952
+ }
7953
+ return { value: unquote(raw), skip: false };
7954
+ }
7955
+ function mapPositionalValues(schema, positional, existing) {
7956
+ const result = { ...existing };
7957
+ if (!schema || typeof schema !== "object") return result;
7958
+ const shape = schema.shape;
7959
+ if (!shape || typeof shape !== "object") return result;
7960
+ const keys = Object.keys(shape);
7961
+ let pIdx = 0;
7962
+ for (const key of keys) {
7963
+ if (pIdx >= positional.length) break;
7964
+ if (result[key] !== void 0) {
7965
+ pIdx++;
7966
+ continue;
7967
+ }
7968
+ const field = shape[key];
7969
+ const raw = positional[pIdx];
7970
+ const { value, skip } = coerceValue(raw, field);
7971
+ if (skip) continue;
7972
+ result[key] = value;
7973
+ pIdx++;
7974
+ }
7975
+ return result;
7976
+ }
7977
+
7978
+ // src/utils/plugin-params.ts
7979
+ function schemaFieldType(schema, key) {
7980
+ const shape = schema?.shape;
7981
+ const field = shape?.[key];
7982
+ let current = field;
7983
+ while (current) {
7984
+ const def = current._def;
7985
+ if (!def) return void 0;
7986
+ const type = def.typeName ?? def.type;
7987
+ if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
7988
+ current = def.innerType ?? def.inner;
7989
+ continue;
7990
+ }
7991
+ return type;
7992
+ }
7993
+ return void 0;
7994
+ }
7995
+ function parsePluginParams(args, schema, base = {}) {
7996
+ const params = { ...base };
7997
+ const positionalValues = [];
7998
+ for (let i = 0; i < args.length; i++) {
7999
+ if (args[i] === "--" && args[i + 1]) {
8000
+ try {
8001
+ Object.assign(params, JSON.parse(args[i + 1]));
8002
+ } catch {
8003
+ }
8004
+ break;
8005
+ }
8006
+ if (args[i].startsWith("--")) {
8007
+ const key = args[i].slice(2);
8008
+ const value = args[i + 1];
8009
+ if (value && !value.startsWith("-")) {
8010
+ const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
8011
+ if (type === "ZodString" || type === "string") params[key] = value;
8012
+ else if (value === "true") params[key] = true;
8013
+ else if (value === "false") params[key] = false;
8014
+ else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
8015
+ else {
8016
+ try {
8017
+ const parsed = JSON.parse(value);
8018
+ if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
8019
+ params[key] = parsed;
8020
+ } else {
8021
+ params[key] = value;
8022
+ }
8023
+ } catch {
8024
+ params[key] = value;
8025
+ }
8026
+ }
8027
+ i++;
8028
+ } else {
8029
+ params[key] = true;
8030
+ }
8031
+ } else if (!args[i].startsWith("-")) {
8032
+ positionalValues.push(args[i]);
8033
+ }
8034
+ }
8035
+ Object.assign(params, mapPositionalValues(schema, positionalValues, params));
8036
+ const result = {};
8037
+ for (const [k, v] of Object.entries(params)) {
8038
+ const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8039
+ result[camelKey] = v;
8040
+ }
8041
+ return result;
8042
+ }
8043
+
8044
+ // src/executor/chain.ts
8045
+ async function executeChain(input, options, executeCommand2) {
8046
+ const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8047
+ const sessionName = options?.sessionName || "default";
8048
+ const results = [];
8049
+ const totalStart = Date.now();
8050
+ let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8051
+ if (!session) {
8052
+ const launchOpts = {};
8053
+ if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
8054
+ session = await createSession(sessionName, void 0, launchOpts);
8055
+ saveSessionDiskMeta(sessionName, {
8056
+ id: session.id,
8057
+ name: sessionName,
8058
+ url: session.page.url(),
8059
+ createdAt: session.createdAt,
8060
+ cdpEndpoint: session.cdpEndpoint
8061
+ });
8062
+ }
8063
+ try {
8064
+ for (const pipeline of pipelines) {
8065
+ const { type, pipeline: commands } = pipeline;
8066
+ for (const cmdStr of commands) {
8067
+ if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8068
+ await new Promise((resolve) => setTimeout(resolve, 800 + Math.random() * 1700));
8069
+ }
8070
+ const parts = splitCommand(cmdStr);
8071
+ if (parts.length === 0) continue;
8072
+ const cmdName = parts[0];
8073
+ const cmdArgs = parts.slice(1);
8074
+ const loader = await getPluginLoader();
8075
+ const internalLoader = loader.getCore().loader;
8076
+ const resolvedName = loader.resolveSiteName(cmdName);
8077
+ const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8078
+ if (site) {
8079
+ const pluginHandled = await executePluginChainStep({
8080
+ site,
8081
+ cmdName,
8082
+ cmdArgs,
8083
+ cmdStr,
8084
+ type,
8085
+ results,
8086
+ totalStart,
8087
+ session,
8088
+ sessionName
8089
+ });
8090
+ if (pluginHandled) return pluginHandled;
8091
+ continue;
8092
+ }
8093
+ const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8094
+ if (cmdName === "goto" && params.url) {
8095
+ const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8096
+ if (!existing) {
8097
+ session = await createSession(sessionName, params.url, {
8098
+ cdpEndpoint: options?.cdpEndpoint
8099
+ });
8100
+ }
8101
+ }
8102
+ const result = await executeCommand2(cmdName, params, sessionName, {
8103
+ cdpEndpoint: options?.cdpEndpoint,
8104
+ skipCleanup: true
8105
+ });
8106
+ results.push({
8107
+ command: cmdName,
8108
+ raw: cmdStr,
8109
+ success: result.success,
8110
+ data: result.data,
8111
+ message: result.message,
8112
+ duration: 0,
8113
+ tips: result.tips,
8114
+ ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8115
+ });
8116
+ if (type === "and" && !result.success) {
8117
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
8118
+ }
8119
+ if (type === "or" && result.success) {
8120
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
8121
+ }
8122
+ }
7888
8123
  }
7889
- },
7890
- screenshot: {
7891
- name: "screenshot",
7892
- onAfterCommand: async (ctx) => {
7893
- try {
7894
- const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
7895
- if (!buf) return;
7896
- return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
7897
- } catch {
7898
- return;
8124
+ return {
8125
+ success: !results.some((result) => !result.success),
8126
+ steps: results,
8127
+ totalDuration: Date.now() - totalStart
8128
+ };
8129
+ } finally {
8130
+ }
8131
+ }
8132
+ function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
8133
+ return {
8134
+ success,
8135
+ steps,
8136
+ totalDuration: Date.now() - totalStart,
8137
+ stoppedAt,
8138
+ stoppedReason: reason
8139
+ };
8140
+ }
8141
+ async function executePluginChainStep(context) {
8142
+ const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
8143
+ const subCommand = cmdArgs[0];
8144
+ if (!subCommand) {
8145
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
8146
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
8147
+ return void 0;
8148
+ }
8149
+ const cmdEntry = site.getCommand(subCommand);
8150
+ if (!cmdEntry) {
8151
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
8152
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
8153
+ return void 0;
8154
+ }
8155
+ const pluginArgs = cmdArgs.slice(1);
8156
+ const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8157
+ if (cmdEntry.parameters) {
8158
+ const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8159
+ if (schemaCheck.success) {
8160
+ for (const [key, value] of Object.entries(schemaCheck.data)) {
8161
+ if (!(key in pluginParams)) pluginParams[key] = value;
7899
8162
  }
7900
8163
  }
7901
- },
7902
- recorder: {
7903
- name: "recorder",
7904
- onAfterCommand: async (ctx) => {
7905
- const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
7906
- logs.push({
7907
- timestamp: Date.now(),
7908
- command: ctx.command,
7909
- params: JSON.parse(JSON.stringify(ctx.params)),
7910
- duration: ctx.duration
8164
+ }
8165
+ const pluginCtx = {
8166
+ args: pluginArgs,
8167
+ options: pluginParams,
8168
+ cwd: process.cwd(),
8169
+ page: session.page,
8170
+ browser: session.context.browser(),
8171
+ browserContext: session.context,
8172
+ sessionId: session.id,
8173
+ storage: getPluginStorage(cmdName),
8174
+ output: { mode: "text", showTips: false, color: false, emoji: false },
8175
+ error: (message) => {
8176
+ throw new Error(message);
8177
+ },
8178
+ config: {},
8179
+ site,
8180
+ cliName: "xbrowser",
8181
+ tips: new TipCollector2()
8182
+ };
8183
+ const start = Date.now();
8184
+ try {
8185
+ const loginGuard = await checkPluginLoginRequired({
8186
+ site,
8187
+ command: cmdEntry,
8188
+ commandName: subCommand,
8189
+ ctx: pluginCtx,
8190
+ page: session.page,
8191
+ sessionName
8192
+ });
8193
+ if (!loginGuard.ok) {
8194
+ const duration2 = Date.now() - start;
8195
+ const data2 = loginGuard.data ?? null;
8196
+ recordArchive(session.id, sessionName, {
8197
+ step: results.length,
8198
+ command: `${cmdName} ${subCommand}`,
8199
+ params: pluginParams,
8200
+ result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8201
+ toolCalls: [],
8202
+ duration: duration2,
8203
+ timestamp: start
7911
8204
  });
7912
- Reflect.set(ctx, "__commandLogs", logs);
8205
+ results.push({
8206
+ command: `${cmdName} ${subCommand}`,
8207
+ raw: cmdStr,
8208
+ success: false,
8209
+ data: data2,
8210
+ message: loginGuard.message,
8211
+ tips: normalizeTips7(loginGuard.tips),
8212
+ duration: duration2
8213
+ });
8214
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
7913
8215
  return void 0;
7914
8216
  }
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;
8217
+ const hooks = await loadHooks();
8218
+ if (hooks.length > 0) {
8219
+ await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
7929
8220
  }
7930
- const customFactory = customHooks[name];
7931
- if (customFactory) {
7932
- const customHook = await customFactory();
7933
- if (customHook) hooks.push(customHook);
8221
+ const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8222
+ const duration = Date.now() - start;
8223
+ let hookOutputs;
8224
+ if (hooks.length > 0) {
8225
+ const outputs = [];
8226
+ for (const hook of hooks) {
8227
+ const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
8228
+ if (output) outputs.push({ _hook: hook.name, ...output });
8229
+ }
8230
+ if (outputs.length > 0) hookOutputs = outputs;
7934
8231
  }
8232
+ const data = raw?.data ?? raw;
8233
+ recordArchive(session.id, sessionName, {
8234
+ step: results.length,
8235
+ command: `${cmdName} ${subCommand}`,
8236
+ params: pluginParams,
8237
+ result: { success: true, data, tips: tipsToMessages(raw?.tips) },
8238
+ toolCalls: [],
8239
+ duration,
8240
+ timestamp: start
8241
+ });
8242
+ results.push({
8243
+ command: `${cmdName} ${subCommand}`,
8244
+ raw: cmdStr,
8245
+ ...ok32(data),
8246
+ duration,
8247
+ ...hookOutputs ? { hookOutputs } : {}
8248
+ });
8249
+ if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
8250
+ } catch (error) {
8251
+ const duration = Date.now() - start;
8252
+ const message = errMsg(error);
8253
+ recordArchive(session.id, sessionName, {
8254
+ step: results.length,
8255
+ command: `${cmdName} ${subCommand}`,
8256
+ params: pluginParams,
8257
+ result: { success: false, data: null, message, tips: [] },
8258
+ toolCalls: [],
8259
+ duration,
8260
+ timestamp: start
8261
+ });
8262
+ results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
8263
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
7935
8264
  }
7936
- return hooks;
8265
+ return void 0;
7937
8266
  }
7938
8267
 
7939
8268
  // src/executor.ts
7940
- import { homedir as homedir5 } from "os";
7941
- import { join as join7 } from "path";
7942
8269
  function levenshtein(a, b) {
7943
8270
  const m = a.length, n = b.length;
7944
8271
  const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
@@ -7946,63 +8273,11 @@ function levenshtein(a, b) {
7946
8273
  for (let j = 0; j <= n; j++) dp[0][j] = j;
7947
8274
  for (let i = 1; i <= m; i++) {
7948
8275
  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]);
8276
+ 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
8277
  }
7951
8278
  }
7952
8279
  return dp[m][n];
7953
8280
  }
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
8281
  async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
8007
8282
  const guardResult = await guardCheck(commandName);
8008
8283
  if (guardResult?.blocked) {
@@ -8050,8 +8325,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8050
8325
  if (knownPlugins.includes(commandName)) {
8051
8326
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8052
8327
  }
8328
+ const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
8329
+ recordMistake({
8330
+ category: classifyFailure(message).code,
8331
+ command: commandName,
8332
+ message,
8333
+ context: { sessionName, params }
8334
+ });
8053
8335
  return errorResult(
8054
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
8336
+ message
8055
8337
  );
8056
8338
  }
8057
8339
  const _target = params._target;
@@ -8066,7 +8348,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8066
8348
  }
8067
8349
  let targetPageOverride = null;
8068
8350
  if (_target && extraOpts?.cdpEndpoint) {
8069
- const { findTargetPage } = await import("./browser-ZD53IMUJ.js");
8351
+ const { findTargetPage } = await import("./browser-OTEMG5NL.js");
8070
8352
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8071
8353
  if (!targetPageOverride) {
8072
8354
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8084,7 +8366,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8084
8366
  }
8085
8367
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8086
8368
  const { forwardExec } = await import("./daemon-client-7D6EZNOE.js");
8087
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
8369
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8088
8370
  const result = await forwardExec(
8089
8371
  commandName,
8090
8372
  params,
@@ -8146,7 +8428,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8146
8428
  config: {},
8147
8429
  site: new NoopSiteInstance(),
8148
8430
  cliName: "xbrowser",
8149
- tips: new TipCollector2()
8431
+ tips: new TipCollector3()
8150
8432
  };
8151
8433
  attachDetectAntiBot(ctx);
8152
8434
  if (_tabIndex !== void 0 && session?.context) {
@@ -8178,7 +8460,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8178
8460
  const cache = /* @__PURE__ */ new Map();
8179
8461
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8180
8462
  if (resolved.tips.length > 0) {
8181
- refTips = normalizeTips7(resolved.tips);
8463
+ refTips = normalizeTips8(resolved.tips);
8182
8464
  params = resolved.params;
8183
8465
  }
8184
8466
  }
@@ -8246,11 +8528,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8246
8528
  }
8247
8529
  const merged = [
8248
8530
  ...raw.tips || [],
8249
- ...normalizeTips7(smartTips),
8250
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
8531
+ ...normalizeTips8(smartTips),
8532
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
8251
8533
  ...refTips
8252
8534
  ];
8253
8535
  const isSuccess = raw.success !== false;
8536
+ if (!isSuccess) {
8537
+ recordMistake({
8538
+ category: classifyFailure(raw.message).code,
8539
+ command: commandName,
8540
+ message: raw.message ?? "unknown command failure",
8541
+ context: { sessionName, params }
8542
+ });
8543
+ }
8254
8544
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
8255
8545
  recordArchive(session?.id, sessionName, {
8256
8546
  step: 0,
@@ -8262,7 +8552,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8262
8552
  timestamp: start
8263
8553
  });
8264
8554
  if (isSuccess) {
8265
- return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8555
+ return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8266
8556
  }
8267
8557
  const fc = classifyFailure(raw.message);
8268
8558
  return {
@@ -8275,7 +8565,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8275
8565
  ...hookOutputs ? { hookOutputs } : {}
8276
8566
  };
8277
8567
  }
8278
- const smartTipNormalized = normalizeTips7(smartTips);
8568
+ const smartTipNormalized = normalizeTips8(smartTips);
8279
8569
  recordArchive(session?.id, sessionName, {
8280
8570
  step: 0,
8281
8571
  command: commandName,
@@ -8285,11 +8575,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8285
8575
  duration,
8286
8576
  timestamp: start
8287
8577
  });
8288
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8578
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8289
8579
  } catch (err) {
8290
8580
  const end = Date.now();
8291
8581
  const duration = end - start;
8292
8582
  const errorMessage = errMsg(err);
8583
+ recordMistake({
8584
+ category: classifyFailure(errorMessage).code,
8585
+ command: commandName,
8586
+ message: errorMessage,
8587
+ context: { sessionName, params }
8588
+ });
8293
8589
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8294
8590
  try {
8295
8591
  const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
@@ -8330,280 +8626,12 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8330
8626
  duration,
8331
8627
  timestamp: start
8332
8628
  });
8333
- return { ...fail17(errorMessage), duration };
8629
+ return { ...fail19(errorMessage), duration };
8334
8630
  } finally {
8335
8631
  }
8336
8632
  }
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
- }
8633
+ async function executeChain2(input, options) {
8634
+ return executeChain(input, options, executeCommand);
8607
8635
  }
8608
8636
 
8609
8637
  // src/daemon/api-analyzer.ts
@@ -9154,7 +9182,7 @@ var PlaybackEngine = class _PlaybackEngine {
9154
9182
  };
9155
9183
 
9156
9184
  // src/daemon/rpc-handlers.ts
9157
- import { TipCollector as TipCollector3 } from "@dyyz1993/xcli-core";
9185
+ import { TipCollector as TipCollector4 } from "@dyyz1993/xcli-core";
9158
9186
  var activeRecorders = /* @__PURE__ */ new Map();
9159
9187
  var replayResumeResolvers = /* @__PURE__ */ new Map();
9160
9188
  function createRPCHandler() {
@@ -9322,7 +9350,7 @@ function createRPCHandler() {
9322
9350
  waitForHuman: async () => {
9323
9351
  return { solved: false, timedOut: true };
9324
9352
  },
9325
- tips: new TipCollector3()
9353
+ tips: new TipCollector4()
9326
9354
  };
9327
9355
  attachDetectAntiBot(ctx);
9328
9356
  const loginGuard = await checkPluginLoginRequired({
@@ -9503,14 +9531,14 @@ function createRPCHandler() {
9503
9531
  const input = params.chain;
9504
9532
  const sessionName = params.session || "default";
9505
9533
  const cdp = params.cdpEndpoint;
9506
- const result = await executeChain(input, { cdpEndpoint: cdp, sessionName });
9534
+ const result = await executeChain2(input, { cdpEndpoint: cdp, sessionName });
9507
9535
  registerSessionIfNew(sessionName);
9508
9536
  return result;
9509
9537
  }
9510
9538
  async function handlePluginsReload() {
9511
- const { resetPluginLoader } = await import("./plugin-singleton-GGSBI3EG.js");
9539
+ const { resetPluginLoader } = await import("./plugin-singleton-A6RNITJW.js");
9512
9540
  resetPluginLoader();
9513
- const loader = await import("./plugin-singleton-GGSBI3EG.js").then((m) => m.getPluginLoader());
9541
+ const loader = await import("./plugin-singleton-A6RNITJW.js").then((m) => m.getPluginLoader());
9514
9542
  const sites = loader.getCore().loader.getSites();
9515
9543
  return { ok: true, plugins: sites.length };
9516
9544
  }
@@ -9906,7 +9934,7 @@ function createRPCHandler() {
9906
9934
  if (isNewFormat) {
9907
9935
  try {
9908
9936
  const replayErrors = [];
9909
- const { SessionReplayer } = await import("./session-replayer-TXTNTG33.js");
9937
+ const { SessionReplayer } = await import("./session-replayer-CLTZ2URU.js");
9910
9938
  const replayer = new SessionReplayer({
9911
9939
  page: session.page,
9912
9940
  stepDelay: slowMo * 500,
@@ -9958,10 +9986,10 @@ function createRPCHandler() {
9958
9986
  const errors = Array.isArray(input.errors) ? input.errors : [];
9959
9987
  const eventsPlayed = typeof input.eventsPlayed === "number" ? input.eventsPlayed : 0;
9960
9988
  const totalEvents = typeof input.totalEvents === "number" ? input.totalEvents : eventsPlayed + errors.length;
9961
- const ok33 = input.ok ?? errors.length === 0;
9989
+ const ok34 = input.ok ?? errors.length === 0;
9962
9990
  return {
9963
- ok: ok33,
9964
- success: ok33,
9991
+ ok: ok34,
9992
+ success: ok34,
9965
9993
  duration: typeof input.duration === "number" ? input.duration : 0,
9966
9994
  eventsPlayed,
9967
9995
  totalEvents,
@@ -11493,7 +11521,7 @@ var WSServer = class extends EventEmitter2 {
11493
11521
  }
11494
11522
  };
11495
11523
 
11496
- // src/daemon/preview-templates.ts
11524
+ // src/daemon/preview-align-template.ts
11497
11525
  function alignHTML(sessionId, _host) {
11498
11526
  return `<!DOCTYPE html>
11499
11527
  <html lang="en"><head><meta charset="utf-8">
@@ -11620,6 +11648,8 @@ connectWS();
11620
11648
  })();
11621
11649
  </script></body></html>`;
11622
11650
  }
11651
+
11652
+ // src/daemon/preview-main-template.ts
11623
11653
  function previewHTML(sessionId, _host) {
11624
11654
  return `<!DOCTYPE html>
11625
11655
  <html lang="en"><head><meta charset="utf-8">