@xbrowser/cli 1.27.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-IDXOIXQR.js → chunk-GDKKVT2P.js} +773 -655
  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-YITK42HZ.js → chunk-SCYBNSOG.js} +1596 -1478
  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 +749 -700
  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-YKMRFDEM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-WDDGIV3C.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";
@@ -1305,9 +1160,12 @@ var visionTaskCommand = registerCommand({
1305
1160
  } catch {
1306
1161
  }
1307
1162
  }
1308
- const buffer = await page.screenshot({ type: "png" });
1163
+ const shotQuality = Math.max(30, Math.min(95, parseInt(process.env.XBROWSER_VLM_SHOT_QUALITY ?? "75", 10) || 75));
1164
+ const buffer = await page.screenshot({ type: "jpeg", quality: shotQuality });
1309
1165
  const b64 = buffer.toString("base64");
1310
- const { w, h } = pngDims(b64);
1166
+ const vp = typeof page.viewportSize === "function" ? page.viewportSize() : null;
1167
+ const w = vp?.width ?? pngDims(b64).w;
1168
+ const h = vp?.height ?? pngDims(b64).h;
1311
1169
  const obsText = [
1312
1170
  `\u4EFB\u52A1\uFF1A${p.task}`,
1313
1171
  `\u622A\u56FE\u5C3A\u5BF8\uFF1A${w}x${h}\uFF08\u5750\u6807\u539F\u70B9\uFF1A\u5DE6\u4E0A\u89D2\uFF09`,
@@ -1316,7 +1174,7 @@ var visionTaskCommand = registerCommand({
1316
1174
  ${history.slice(-6).join("\n")}` : "\u5C1A\u65E0\u52A8\u4F5C\u3002"
1317
1175
  ].join("\n");
1318
1176
  const reply = await vlmAskRetry(creds, [
1319
- { type: "image", source: { type: "base64", media_type: "image/png", data: b64 } },
1177
+ { type: "image", source: { type: "base64", media_type: shotQuality >= 100 ? "image/png" : "image/jpeg", data: b64 } },
1320
1178
  { type: "text", text: `${SYSTEM_PROMPT}
1321
1179
 
1322
1180
  ${obsText}` }
@@ -4484,6 +4342,8 @@ var networkCommand = registerCommand({
4484
4342
 
4485
4343
  // src/commands/ai-search-engines.ts
4486
4344
  import { z as z24 } from "zod";
4345
+
4346
+ // src/commands/ai-engine-configs.ts
4487
4347
  var ENGINE_CONFIGS = {
4488
4348
  deepseek: {
4489
4349
  key: "deepseek",
@@ -4736,6 +4596,8 @@ var ENGINE_CONFIGS = {
4736
4596
  sendButtonSelector: "button.send-btn"
4737
4597
  }
4738
4598
  };
4599
+
4600
+ // src/commands/ai-search-engines.ts
4739
4601
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
4740
4602
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
4741
4603
 
@@ -4760,6 +4622,25 @@ function getRefTarget(sessionKey2, ref) {
4760
4622
  if (!session || !target) return null;
4761
4623
  return { screenHash: session.screenHash, target };
4762
4624
  }
4625
+ function inheritStableRefs(key, rawTargets) {
4626
+ const prev = sessions.get(key);
4627
+ if (!prev || prev.targets.size === 0) {
4628
+ return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
4629
+ }
4630
+ const bySelector = /* @__PURE__ */ new Map();
4631
+ let maxId = 0;
4632
+ for (const [ref, target] of prev.targets) {
4633
+ bySelector.set(target.selector, ref);
4634
+ const id = Number(ref.slice(1));
4635
+ if (Number.isFinite(id) && id > maxId) maxId = id;
4636
+ }
4637
+ let next = maxId + 1;
4638
+ return rawTargets.map((target) => {
4639
+ const inherited = bySelector.get(target.selector);
4640
+ if (inherited) return { ...target, ref: inherited };
4641
+ return { ...target, ref: `e${next++}` };
4642
+ });
4643
+ }
4763
4644
 
4764
4645
  // src/utils/resolve-selector.ts
4765
4646
  function buildElementSelector(el) {
@@ -5384,10 +5265,7 @@ async function observePage(page, sessionId, options = {}) {
5384
5265
  { includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
5385
5266
  )
5386
5267
  ]);
5387
- const targets = raw.targets.map((target, index) => ({
5388
- ref: `e${index + 1}`,
5389
- ...target
5390
- }));
5268
+ const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
5391
5269
  replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
5392
5270
  return {
5393
5271
  url: page.url(),
@@ -5891,12 +5769,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
5891
5769
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
5892
5770
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
5893
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"}
5894
5773
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
5895
5774
 
5896
5775
  \u89C4\u5219\uFF1A
5897
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
5898
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
5899
- 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`;
5900
5779
  function extractDecision(raw) {
5901
5780
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
5902
5781
  const start = s.indexOf("{");
@@ -5947,6 +5826,7 @@ var taskCommand = registerCommand({
5947
5826
  let status = "max_steps";
5948
5827
  let summary = "";
5949
5828
  let lastError = "";
5829
+ let emptyReplies = 0;
5950
5830
  for (let step = 1; step <= p.maxSteps; step++) {
5951
5831
  if (Date.now() - started > p.timeout) {
5952
5832
  status = "blocked";
@@ -5966,7 +5846,7 @@ ${history.slice(-6).join("\n")}` : ""
5966
5846
  ].filter(Boolean).join("\n");
5967
5847
  let raw = "";
5968
5848
  try {
5969
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5849
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
5970
5850
 
5971
5851
  ---
5972
5852
 
@@ -5980,6 +5860,12 @@ ${userPayload}` }], 900);
5980
5860
  }
5981
5861
  const decision = extractDecision(raw);
5982
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
+ }
5983
5869
  status = "blocked";
5984
5870
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
5985
5871
  break;
@@ -5994,6 +5880,13 @@ ${userPayload}` }], 900);
5994
5880
  steps.push({ step, thought, action: "done", ok: true, screenHash });
5995
5881
  break;
5996
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
+ }
5997
5890
  if (action === "blocked") {
5998
5891
  status = "blocked";
5999
5892
  summary = value || thought || "LLM judged blocked";
@@ -6734,6 +6627,8 @@ var visualTagCommand = registerCommand({
6734
6627
  // src/commands/visual-tag-v2.ts
6735
6628
  import { z as z32 } from "zod";
6736
6629
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6630
+
6631
+ // src/commands/visual-tag-v2-script.ts
6737
6632
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6738
6633
  var TAG_V2_SCRIPT = `
6739
6634
  (function() {
@@ -7076,7 +6971,9 @@ var TAG_V2_SCRIPT = `
7076
6971
  return JSON.stringify(window.__xbTagStats);
7077
6972
  })()
7078
6973
  `;
7079
- var visualTagV2Command = registerCommand({
6974
+
6975
+ // src/commands/visual-tag-v2.ts
6976
+ registerCommand({
7080
6977
  name: "visual-tag-v2",
7081
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",
7082
6979
  scope: "page",
@@ -7309,153 +7206,45 @@ function attachDetectAntiBot(ctx) {
7309
7206
  };
7310
7207
  }
7311
7208
 
7312
- // src/plugin/login-guard.ts
7313
- async function checkPluginLoginRequired(options) {
7314
- const { site, command, commandName, ctx, page, sessionName } = options;
7315
- if (commandName === "login" || commandName === "logout") return { ok: true };
7316
- const loginConfig = site.config?.loginConfig;
7317
- const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
7318
- if (!requiresLogin) return { ok: true };
7319
- const pluginName = site.name || "plugin";
7320
- const siteConfig = site.config;
7321
- const configIsLogin = siteConfig?.isLogin;
7322
- if (configIsLogin) {
7323
- try {
7324
- const loggedIn = await configIsLogin(ctx);
7325
- if (loggedIn) return { ok: true };
7326
- return buildLoginRequired({
7327
- plugin: pluginName,
7328
- command: commandName,
7329
- reason: "config.isLogin returned false",
7330
- sessionName,
7331
- loginConfig
7332
- });
7333
- } catch {
7334
- }
7335
- }
7336
- if (typeof site.isLoggedIn === "function") {
7337
- try {
7338
- const loggedIn = await site.isLoggedIn(ctx);
7339
- if (loggedIn) return { ok: true };
7340
- return buildLoginRequired({
7341
- plugin: pluginName,
7342
- command: commandName,
7343
- reason: "plugin isLoggedIn returned false",
7344
- sessionName,
7345
- loginConfig
7346
- });
7347
- } 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') + '"]';
7348
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();
7349
7227
  }
7350
- if (page && loginConfig) {
7351
- const generic = await detectLoginFromPage(page, loginConfig);
7352
- if (generic === "logged-in") return { ok: true };
7353
- if (generic === "logged-out") {
7354
- return buildLoginRequired({
7355
- plugin: pluginName,
7356
- command: commandName,
7357
- reason: "generic loginConfig detected logged-out page",
7358
- sessionName,
7359
- loginConfig
7360
- });
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;
7361
7245
  }
7362
- }
7363
- return { ok: true };
7364
- }
7365
- function buildLoginRequired(options) {
7366
- const viewerUrl = buildViewerUrl(options.sessionName);
7367
- const loginUrl = options.loginConfig?.loginUrl;
7368
- const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
7369
- const tips = [
7370
- message,
7371
- ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
7372
- ...loginUrl ? [`Login page: ${loginUrl}`] : [],
7373
- `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
7374
- ];
7375
- return {
7376
- ok: false,
7377
- data: {
7378
- code: "LOGIN_REQUIRED",
7379
- plugin: options.plugin,
7380
- command: options.command,
7381
- reason: options.reason,
7382
- ...viewerUrl ? { viewerUrl } : {},
7383
- ...loginUrl ? { loginUrl } : {}
7384
- },
7385
- message,
7386
- tips
7387
- };
7388
- }
7389
- async function detectLoginFromPage(page, config) {
7390
- const url = page.url();
7391
- if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
7392
- const result = await page.evaluate((cfg) => {
7393
- const visible = (selector) => {
7394
- try {
7395
- const el = document.querySelector(selector);
7396
- if (!el) return false;
7397
- const rect = el.getBoundingClientRect();
7398
- const style = window.getComputedStyle(el);
7399
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
7400
- } catch {
7401
- return false;
7402
- }
7403
- };
7404
- if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
7405
- if (cfg.loginSelectors?.some(visible)) return "logged-out";
7406
- const bodyText = document.body?.innerText || "";
7407
- const keywords = cfg.loginKeywords || [];
7408
- if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
7409
- return "logged-out";
7410
- }
7411
- return "unknown";
7412
- }, {
7413
- loginSelectors: config.loginSelectors || [],
7414
- loginKeywords: config.loginKeywords || [],
7415
- loggedInSelectors: config.loggedInSelectors || []
7416
- });
7417
- return result;
7418
- }
7419
-
7420
- // src/tips/dom-watcher.ts
7421
- var DOM_WATCHER_SCRIPT = `
7422
- (function() {
7423
- if (window.__xbrowserDomWatcher) return;
7424
- window.__xbrowserDomWatcher = true;
7425
-
7426
- window.__xbrowserDetectedElements = [];
7427
-
7428
- function getSelector(el) {
7429
- if (el.id) return '#' + CSS.escape(el.id);
7430
- if (el.getAttribute('aria-label')) {
7431
- return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
7432
- }
7433
- const cls = el.className && typeof el.className === 'string'
7434
- ? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
7435
- : '';
7436
- if (cls) return el.tagName.toLowerCase() + '.' + cls;
7437
- return el.tagName.toLowerCase();
7438
- }
7439
-
7440
- function isPopupLike(el) {
7441
- const tag = el.tagName?.toLowerCase();
7442
- if (tag === 'dialog') return true;
7443
- if (tag === 'body' || tag === 'html') return false;
7444
-
7445
- const role = el.getAttribute('role');
7446
- if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
7447
-
7448
- const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
7449
- const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
7450
- if (popupPatterns.test(cls)) return true;
7451
-
7452
- const style = window.getComputedStyle(el);
7453
- if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
7454
- const rect = el.getBoundingClientRect();
7455
- if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
7456
- }
7457
-
7458
- return false;
7246
+
7247
+ return false;
7459
7248
  }
7460
7249
 
7461
7250
  function categorize(el) {
@@ -7863,63 +7652,620 @@ var HOOK_REGISTRY = {
7863
7652
  if (!tips.some((t) => t.includes("viewer") || t.includes("Viewer"))) {
7864
7653
  tips.push(`Open viewer: ${viewerUrl}`);
7865
7654
  }
7866
- result.tips = tips;
7867
- result.viewerUrl = viewerUrl;
7868
- 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
+ }
7869
8123
  }
7870
- },
7871
- screenshot: {
7872
- name: "screenshot",
7873
- onAfterCommand: async (ctx) => {
7874
- try {
7875
- const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
7876
- if (!buf) return;
7877
- return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
7878
- } catch {
7879
- 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;
7880
8162
  }
7881
8163
  }
7882
- },
7883
- recorder: {
7884
- name: "recorder",
7885
- onAfterCommand: async (ctx) => {
7886
- const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
7887
- logs.push({
7888
- timestamp: Date.now(),
7889
- command: ctx.command,
7890
- params: JSON.parse(JSON.stringify(ctx.params)),
7891
- 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
7892
8204
  });
7893
- 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}`);
7894
8215
  return void 0;
7895
8216
  }
7896
- }
7897
- };
7898
- var customHooks = {};
7899
- async function loadHooks() {
7900
- const env = process.env.XBROWSER_HOOKS;
7901
- if (!env) return [];
7902
- const names = env.split(",").map((n) => n.trim()).filter(Boolean);
7903
- if (names.length === 0) return [];
7904
- const hooks = [];
7905
- for (const name of names) {
7906
- const hook = HOOK_REGISTRY[name];
7907
- if (hook) {
7908
- hooks.push(hook);
7909
- 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 })));
7910
8220
  }
7911
- const customFactory = customHooks[name];
7912
- if (customFactory) {
7913
- const customHook = await customFactory();
7914
- 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;
7915
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}`);
7916
8264
  }
7917
- return hooks;
8265
+ return void 0;
7918
8266
  }
7919
8267
 
7920
8268
  // src/executor.ts
7921
- import { homedir as homedir5 } from "os";
7922
- import { join as join7 } from "path";
7923
8269
  function levenshtein(a, b) {
7924
8270
  const m = a.length, n = b.length;
7925
8271
  const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
@@ -7927,63 +8273,11 @@ function levenshtein(a, b) {
7927
8273
  for (let j = 0; j <= n; j++) dp[0][j] = j;
7928
8274
  for (let i = 1; i <= m; i++) {
7929
8275
  for (let j = 1; j <= n; j++) {
7930
- 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]);
7931
8277
  }
7932
8278
  }
7933
8279
  return dp[m][n];
7934
8280
  }
7935
- var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
7936
- var snapshotHintShown = /* @__PURE__ */ new WeakSet();
7937
- var CONFIG_DIR2 = join7(homedir5(), ".xbrowser");
7938
- var storageCache = /* @__PURE__ */ new Map();
7939
- function getPluginStorage(pluginName) {
7940
- if (!storageCache.has(pluginName)) {
7941
- storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
7942
- }
7943
- return storageCache.get(pluginName);
7944
- }
7945
- var archiveInitialized = false;
7946
- function ensureArchiveInit() {
7947
- if (!archiveInitialized) {
7948
- try {
7949
- configureArchiveStore({ archiveDir: join7(homedir5(), ".xbrowser", "archives") });
7950
- } catch {
7951
- }
7952
- archiveInitialized = true;
7953
- }
7954
- }
7955
- function recordArchive(sessionId, sessionName, entry) {
7956
- if (!sessionId) return;
7957
- try {
7958
- ensureArchiveInit();
7959
- appendCommandToArchive(sessionId, sessionName, entry);
7960
- } catch {
7961
- }
7962
- }
7963
- async function guardCheck(commandName) {
7964
- try {
7965
- const loader = await getPluginLoader();
7966
- const core = loader.getCore();
7967
- return checkGuard(core, commandName, process.env);
7968
- } catch {
7969
- return null;
7970
- }
7971
- }
7972
- function errorResult(message) {
7973
- return { ...fail17(message), duration: 0 };
7974
- }
7975
- function tipsToMessages(tips) {
7976
- if (!tips || tips.length === 0) return [];
7977
- return tips.map((t) => typeof t === "string" ? t : t.message);
7978
- }
7979
- var wsServer = null;
7980
- function streamCommandEvent(sessionId, message) {
7981
- if (!wsServer || !wsServer.getRunning()) return;
7982
- wsServer.broadcastToSession(sessionId, {
7983
- type: "command",
7984
- data: message
7985
- });
7986
- }
7987
8281
  async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
7988
8282
  const guardResult = await guardCheck(commandName);
7989
8283
  if (guardResult?.blocked) {
@@ -8031,8 +8325,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8031
8325
  if (knownPlugins.includes(commandName)) {
8032
8326
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8033
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
+ });
8034
8335
  return errorResult(
8035
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
8336
+ message
8036
8337
  );
8037
8338
  }
8038
8339
  const _target = params._target;
@@ -8047,7 +8348,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8047
8348
  }
8048
8349
  let targetPageOverride = null;
8049
8350
  if (_target && extraOpts?.cdpEndpoint) {
8050
- const { findTargetPage } = await import("./browser-ZD53IMUJ.js");
8351
+ const { findTargetPage } = await import("./browser-OTEMG5NL.js");
8051
8352
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8052
8353
  if (!targetPageOverride) {
8053
8354
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8065,7 +8366,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8065
8366
  }
8066
8367
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8067
8368
  const { forwardExec } = await import("./daemon-client-7D6EZNOE.js");
8068
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
8369
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8069
8370
  const result = await forwardExec(
8070
8371
  commandName,
8071
8372
  params,
@@ -8127,7 +8428,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8127
8428
  config: {},
8128
8429
  site: new NoopSiteInstance(),
8129
8430
  cliName: "xbrowser",
8130
- tips: new TipCollector2()
8431
+ tips: new TipCollector3()
8131
8432
  };
8132
8433
  attachDetectAntiBot(ctx);
8133
8434
  if (_tabIndex !== void 0 && session?.context) {
@@ -8159,7 +8460,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8159
8460
  const cache = /* @__PURE__ */ new Map();
8160
8461
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8161
8462
  if (resolved.tips.length > 0) {
8162
- refTips = normalizeTips7(resolved.tips);
8463
+ refTips = normalizeTips8(resolved.tips);
8163
8464
  params = resolved.params;
8164
8465
  }
8165
8466
  }
@@ -8227,11 +8528,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8227
8528
  }
8228
8529
  const merged = [
8229
8530
  ...raw.tips || [],
8230
- ...normalizeTips7(smartTips),
8231
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
8531
+ ...normalizeTips8(smartTips),
8532
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
8232
8533
  ...refTips
8233
8534
  ];
8234
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
+ }
8235
8544
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
8236
8545
  recordArchive(session?.id, sessionName, {
8237
8546
  step: 0,
@@ -8243,7 +8552,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8243
8552
  timestamp: start
8244
8553
  });
8245
8554
  if (isSuccess) {
8246
- 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 } : {} };
8247
8556
  }
8248
8557
  const fc = classifyFailure(raw.message);
8249
8558
  return {
@@ -8256,7 +8565,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8256
8565
  ...hookOutputs ? { hookOutputs } : {}
8257
8566
  };
8258
8567
  }
8259
- const smartTipNormalized = normalizeTips7(smartTips);
8568
+ const smartTipNormalized = normalizeTips8(smartTips);
8260
8569
  recordArchive(session?.id, sessionName, {
8261
8570
  step: 0,
8262
8571
  command: commandName,
@@ -8266,11 +8575,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8266
8575
  duration,
8267
8576
  timestamp: start
8268
8577
  });
8269
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8578
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8270
8579
  } catch (err) {
8271
8580
  const end = Date.now();
8272
8581
  const duration = end - start;
8273
8582
  const errorMessage = errMsg(err);
8583
+ recordMistake({
8584
+ category: classifyFailure(errorMessage).code,
8585
+ command: commandName,
8586
+ message: errorMessage,
8587
+ context: { sessionName, params }
8588
+ });
8274
8589
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8275
8590
  try {
8276
8591
  const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
@@ -8311,280 +8626,12 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8311
8626
  duration,
8312
8627
  timestamp: start
8313
8628
  });
8314
- return { ...fail17(errorMessage), duration };
8629
+ return { ...fail19(errorMessage), duration };
8315
8630
  } finally {
8316
8631
  }
8317
8632
  }
8318
- async function executeChain(input, options) {
8319
- const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8320
- const sessionName = options?.sessionName || "default";
8321
- const results = [];
8322
- const totalStart = Date.now();
8323
- let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8324
- if (!session) {
8325
- const launchOpts = {};
8326
- if (options?.cdpEndpoint) {
8327
- launchOpts.cdpEndpoint = options.cdpEndpoint;
8328
- }
8329
- session = await createSession(sessionName, void 0, launchOpts);
8330
- saveSessionDiskMeta(sessionName, {
8331
- id: session.id,
8332
- name: sessionName,
8333
- url: session.page.url(),
8334
- createdAt: session.createdAt,
8335
- cdpEndpoint: session.cdpEndpoint
8336
- });
8337
- }
8338
- try {
8339
- for (const pipeline of pipelines) {
8340
- const { type, pipeline: commands } = pipeline;
8341
- for (const cmdStr of commands) {
8342
- if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8343
- await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
8344
- }
8345
- const parts = splitCommand(cmdStr);
8346
- if (parts.length === 0) continue;
8347
- const cmdName = parts[0];
8348
- const cmdArgs = parts.slice(1);
8349
- const loader = await getPluginLoader();
8350
- const internalLoader = loader.getCore().loader;
8351
- const resolvedName = loader.resolveSiteName(cmdName);
8352
- const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8353
- if (site) {
8354
- const subCommand = cmdArgs[0];
8355
- if (!subCommand) {
8356
- results.push({
8357
- command: cmdName,
8358
- raw: cmdStr,
8359
- ...fail17(`Plugin "${cmdName}" requires a sub-command`),
8360
- duration: 0
8361
- });
8362
- if (type === "and") {
8363
- return {
8364
- success: false,
8365
- steps: results,
8366
- totalDuration: Date.now() - totalStart,
8367
- stoppedAt: results.length,
8368
- stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
8369
- };
8370
- }
8371
- continue;
8372
- }
8373
- const cmdEntry = site.getCommand(subCommand);
8374
- if (!cmdEntry) {
8375
- results.push({
8376
- command: cmdName,
8377
- raw: cmdStr,
8378
- ...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
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): unknown sub-command "${subCommand}"`
8388
- };
8389
- }
8390
- continue;
8391
- }
8392
- const pluginArgs = cmdArgs.slice(1);
8393
- let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8394
- if (cmdEntry.parameters) {
8395
- const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8396
- if (schemaCheck.success) {
8397
- for (const [k, v] of Object.entries(schemaCheck.data)) {
8398
- if (!(k in pluginParams)) pluginParams[k] = v;
8399
- }
8400
- }
8401
- }
8402
- const pluginCtx = {
8403
- args: pluginArgs,
8404
- options: pluginParams,
8405
- cwd: process.cwd(),
8406
- page: session.page,
8407
- browser: session.context.browser(),
8408
- browserContext: session.context,
8409
- sessionId: session.id,
8410
- storage: getPluginStorage(cmdName),
8411
- output: { mode: "text", showTips: false, color: false, emoji: false },
8412
- error: (msg) => {
8413
- throw new Error(msg);
8414
- },
8415
- config: {},
8416
- site,
8417
- cliName: "xbrowser",
8418
- tips: new TipCollector2()
8419
- };
8420
- const start2 = Date.now();
8421
- try {
8422
- const loginGuard = await checkPluginLoginRequired({
8423
- site,
8424
- command: cmdEntry,
8425
- commandName: subCommand,
8426
- ctx: pluginCtx,
8427
- page: session?.page,
8428
- sessionName
8429
- });
8430
- if (!loginGuard.ok) {
8431
- const duration3 = Date.now() - start2;
8432
- const data2 = loginGuard.data ?? null;
8433
- recordArchive(session.id, sessionName, {
8434
- step: results.length,
8435
- command: `${cmdName} ${subCommand}`,
8436
- params: pluginParams,
8437
- result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
8438
- toolCalls: [],
8439
- duration: duration3,
8440
- timestamp: start2
8441
- });
8442
- results.push({
8443
- command: `${cmdName} ${subCommand}`,
8444
- raw: cmdStr,
8445
- success: false,
8446
- data: data2,
8447
- message: loginGuard.message,
8448
- tips: normalizeTips7(loginGuard.tips),
8449
- duration: duration3
8450
- });
8451
- if (type === "and") {
8452
- return {
8453
- success: false,
8454
- steps: results,
8455
- totalDuration: Date.now() - totalStart,
8456
- stoppedAt: results.length,
8457
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
8458
- };
8459
- }
8460
- continue;
8461
- }
8462
- const hooks = await loadHooks();
8463
- if (hooks.length > 0) {
8464
- await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
8465
- }
8466
- const raw = await cmdEntry.handler(pluginParams, pluginCtx);
8467
- const duration2 = Date.now() - start2;
8468
- let hookOutputs;
8469
- if (hooks.length > 0) {
8470
- const outputs = [];
8471
- for (const h of hooks) {
8472
- const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
8473
- if (output) outputs.push({ _hook: h.name, ...output });
8474
- }
8475
- if (outputs.length > 0) hookOutputs = outputs;
8476
- }
8477
- const data = raw?.data ?? raw;
8478
- recordArchive(session.id, sessionName, {
8479
- step: results.length,
8480
- command: `${cmdName} ${subCommand}`,
8481
- params: pluginParams,
8482
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
8483
- toolCalls: [],
8484
- duration: duration2,
8485
- timestamp: start2
8486
- });
8487
- results.push({
8488
- command: `${cmdName} ${subCommand}`,
8489
- raw: cmdStr,
8490
- ...ok32(data),
8491
- duration: duration2,
8492
- ...hookOutputs ? { hookOutputs } : {}
8493
- });
8494
- if (type === "or") {
8495
- return {
8496
- success: true,
8497
- steps: results,
8498
- totalDuration: Date.now() - totalStart,
8499
- stoppedAt: results.length,
8500
- stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
8501
- };
8502
- }
8503
- } catch (err) {
8504
- const duration2 = Date.now() - start2;
8505
- const errorMessage = errMsg(err);
8506
- recordArchive(session.id, sessionName, {
8507
- step: results.length,
8508
- command: `${cmdName} ${subCommand}`,
8509
- params: pluginParams,
8510
- result: { success: false, data: null, message: errorMessage, tips: [] },
8511
- toolCalls: [],
8512
- duration: duration2,
8513
- timestamp: start2
8514
- });
8515
- results.push({
8516
- command: `${cmdName} ${subCommand}`,
8517
- raw: cmdStr,
8518
- ...fail17(errorMessage),
8519
- duration: duration2
8520
- });
8521
- if (type === "and") {
8522
- return {
8523
- success: false,
8524
- steps: results,
8525
- totalDuration: Date.now() - totalStart,
8526
- stoppedAt: results.length,
8527
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
8528
- };
8529
- }
8530
- }
8531
- continue;
8532
- }
8533
- const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8534
- if (cmdName === "goto" && params.url) {
8535
- const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8536
- if (!existing2) {
8537
- session = await createSession(sessionName, params.url, {
8538
- cdpEndpoint: options?.cdpEndpoint
8539
- });
8540
- }
8541
- }
8542
- const start = Date.now();
8543
- const result = await executeCommand(cmdName, params, sessionName, {
8544
- cdpEndpoint: options?.cdpEndpoint,
8545
- skipCleanup: true
8546
- // executeChain's finally handles cleanup
8547
- });
8548
- const duration = Date.now() - start;
8549
- const stepResult = {
8550
- command: cmdName,
8551
- raw: cmdStr,
8552
- success: result.success,
8553
- data: result.data,
8554
- message: result.message,
8555
- duration,
8556
- tips: result.tips,
8557
- ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8558
- };
8559
- results.push(stepResult);
8560
- if (type === "and" && !result.success) {
8561
- return {
8562
- success: false,
8563
- steps: results,
8564
- totalDuration: Date.now() - totalStart,
8565
- stoppedAt: results.length,
8566
- stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
8567
- };
8568
- }
8569
- if (type === "or" && result.success) {
8570
- return {
8571
- success: true,
8572
- steps: results,
8573
- totalDuration: Date.now() - totalStart,
8574
- stoppedAt: results.length,
8575
- stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
8576
- };
8577
- }
8578
- }
8579
- }
8580
- const anyFailed = results.some((r) => !r.success);
8581
- return {
8582
- success: !anyFailed,
8583
- steps: results,
8584
- totalDuration: Date.now() - totalStart
8585
- };
8586
- } finally {
8587
- }
8633
+ async function executeChain2(input, options) {
8634
+ return executeChain(input, options, executeCommand);
8588
8635
  }
8589
8636
 
8590
8637
  // src/daemon/api-analyzer.ts
@@ -9135,7 +9182,7 @@ var PlaybackEngine = class _PlaybackEngine {
9135
9182
  };
9136
9183
 
9137
9184
  // src/daemon/rpc-handlers.ts
9138
- import { TipCollector as TipCollector3 } from "@dyyz1993/xcli-core";
9185
+ import { TipCollector as TipCollector4 } from "@dyyz1993/xcli-core";
9139
9186
  var activeRecorders = /* @__PURE__ */ new Map();
9140
9187
  var replayResumeResolvers = /* @__PURE__ */ new Map();
9141
9188
  function createRPCHandler() {
@@ -9303,7 +9350,7 @@ function createRPCHandler() {
9303
9350
  waitForHuman: async () => {
9304
9351
  return { solved: false, timedOut: true };
9305
9352
  },
9306
- tips: new TipCollector3()
9353
+ tips: new TipCollector4()
9307
9354
  };
9308
9355
  attachDetectAntiBot(ctx);
9309
9356
  const loginGuard = await checkPluginLoginRequired({
@@ -9484,14 +9531,14 @@ function createRPCHandler() {
9484
9531
  const input = params.chain;
9485
9532
  const sessionName = params.session || "default";
9486
9533
  const cdp = params.cdpEndpoint;
9487
- const result = await executeChain(input, { cdpEndpoint: cdp, sessionName });
9534
+ const result = await executeChain2(input, { cdpEndpoint: cdp, sessionName });
9488
9535
  registerSessionIfNew(sessionName);
9489
9536
  return result;
9490
9537
  }
9491
9538
  async function handlePluginsReload() {
9492
- const { resetPluginLoader } = await import("./plugin-singleton-GGSBI3EG.js");
9539
+ const { resetPluginLoader } = await import("./plugin-singleton-A6RNITJW.js");
9493
9540
  resetPluginLoader();
9494
- 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());
9495
9542
  const sites = loader.getCore().loader.getSites();
9496
9543
  return { ok: true, plugins: sites.length };
9497
9544
  }
@@ -9887,7 +9934,7 @@ function createRPCHandler() {
9887
9934
  if (isNewFormat) {
9888
9935
  try {
9889
9936
  const replayErrors = [];
9890
- const { SessionReplayer } = await import("./session-replayer-TXTNTG33.js");
9937
+ const { SessionReplayer } = await import("./session-replayer-CLTZ2URU.js");
9891
9938
  const replayer = new SessionReplayer({
9892
9939
  page: session.page,
9893
9940
  stepDelay: slowMo * 500,
@@ -9939,10 +9986,10 @@ function createRPCHandler() {
9939
9986
  const errors = Array.isArray(input.errors) ? input.errors : [];
9940
9987
  const eventsPlayed = typeof input.eventsPlayed === "number" ? input.eventsPlayed : 0;
9941
9988
  const totalEvents = typeof input.totalEvents === "number" ? input.totalEvents : eventsPlayed + errors.length;
9942
- const ok33 = input.ok ?? errors.length === 0;
9989
+ const ok34 = input.ok ?? errors.length === 0;
9943
9990
  return {
9944
- ok: ok33,
9945
- success: ok33,
9991
+ ok: ok34,
9992
+ success: ok34,
9946
9993
  duration: typeof input.duration === "number" ? input.duration : 0,
9947
9994
  eventsPlayed,
9948
9995
  totalEvents,
@@ -11474,7 +11521,7 @@ var WSServer = class extends EventEmitter2 {
11474
11521
  }
11475
11522
  };
11476
11523
 
11477
- // src/daemon/preview-templates.ts
11524
+ // src/daemon/preview-align-template.ts
11478
11525
  function alignHTML(sessionId, _host) {
11479
11526
  return `<!DOCTYPE html>
11480
11527
  <html lang="en"><head><meta charset="utf-8">
@@ -11601,6 +11648,8 @@ connectWS();
11601
11648
  })();
11602
11649
  </script></body></html>`;
11603
11650
  }
11651
+
11652
+ // src/daemon/preview-main-template.ts
11604
11653
  function previewHTML(sessionId, _host) {
11605
11654
  return `<!DOCTYPE html>
11606
11655
  <html lang="en"><head><meta charset="utf-8">