@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
@@ -9,7 +9,7 @@ import {
9
9
  resolveLaunchOpts,
10
10
  saveSessionDiskMeta,
11
11
  setActivePage
12
- } from "./chunk-KECYFWJO.js";
12
+ } from "./chunk-P33R7F2D.js";
13
13
  import {
14
14
  detectAntiBot,
15
15
  formatDetectionMessage
@@ -24,13 +24,13 @@ import {
24
24
  rand,
25
25
  sleep,
26
26
  wheelDelta
27
- } from "./chunk-R3F4K2SB.js";
27
+ } from "./chunk-SMYSNO4M.js";
28
28
  import {
29
29
  errMsg
30
30
  } from "./chunk-GDKLH7ZY.js";
31
31
  import {
32
32
  createRuleEngine
33
- } from "./chunk-75DNUI6M.js";
33
+ } from "./chunk-6UJU2FJK.js";
34
34
 
35
35
  // src/commands/command-registry.ts
36
36
  var registry = /* @__PURE__ */ new Map();
@@ -1836,14 +1836,14 @@ var preflightCommand = registerCommand({
1836
1836
  let pageUrl = null;
1837
1837
  try {
1838
1838
  const { fileURLToPath } = await import("url");
1839
- const { join: join9, dirname: dirname4 } = await import("path");
1840
- const { existsSync: existsSync7 } = await import("fs");
1839
+ const { join: join10, dirname: dirname4 } = await import("path");
1840
+ const { existsSync: existsSync8 } = await import("fs");
1841
1841
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1842
1842
  const candidates = [
1843
- join9(dirname4(here), "..", "assets", "preflight.html"),
1844
- join9(process.cwd(), "assets", "preflight.html")
1843
+ join10(dirname4(here), "..", "assets", "preflight.html"),
1844
+ join10(process.cwd(), "assets", "preflight.html")
1845
1845
  ];
1846
- pageUrl = candidates.find((c) => existsSync7(c)) || null;
1846
+ pageUrl = candidates.find((c) => existsSync8(c)) || null;
1847
1847
  } catch {
1848
1848
  }
1849
1849
  if (pageUrl) {
@@ -4835,6 +4835,8 @@ var networkCommand = registerCommand({
4835
4835
 
4836
4836
  // src/commands/ai-search-engines.ts
4837
4837
  import { z as z24 } from "zod";
4838
+
4839
+ // src/commands/ai-engine-configs.ts
4838
4840
  var ENGINE_CONFIGS = {
4839
4841
  deepseek: {
4840
4842
  key: "deepseek",
@@ -5087,6 +5089,8 @@ var ENGINE_CONFIGS = {
5087
5089
  sendButtonSelector: "button.send-btn"
5088
5090
  }
5089
5091
  };
5092
+
5093
+ // src/commands/ai-search-engines.ts
5090
5094
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
5091
5095
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
5092
5096
  function getEngineConfig(key) {
@@ -6088,12 +6092,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
6088
6092
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
6089
6093
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
6090
6094
  {"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
6095
+ {"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
6091
6096
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
6092
6097
 
6093
6098
  \u89C4\u5219\uFF1A
6094
6099
  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
6095
6100
  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
6096
- 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`;
6101
+ 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`;
6097
6102
  function extractDecision(raw) {
6098
6103
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
6099
6104
  const start = s.indexOf("{");
@@ -6144,6 +6149,7 @@ var taskCommand = registerCommand({
6144
6149
  let status = "max_steps";
6145
6150
  let summary = "";
6146
6151
  let lastError = "";
6152
+ let emptyReplies = 0;
6147
6153
  for (let step = 1; step <= p.maxSteps; step++) {
6148
6154
  if (Date.now() - started > p.timeout) {
6149
6155
  status = "blocked";
@@ -6163,7 +6169,7 @@ ${history.slice(-6).join("\n")}` : ""
6163
6169
  ].filter(Boolean).join("\n");
6164
6170
  let raw = "";
6165
6171
  try {
6166
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
6172
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
6167
6173
 
6168
6174
  ---
6169
6175
 
@@ -6177,6 +6183,12 @@ ${userPayload}` }], 900);
6177
6183
  }
6178
6184
  const decision = extractDecision(raw);
6179
6185
  if (!decision || typeof decision.action !== "string") {
6186
+ if (!raw.trim() && emptyReplies < 2) {
6187
+ emptyReplies++;
6188
+ steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
6189
+ history.push(`step${step}: (empty reply, retrying)`);
6190
+ continue;
6191
+ }
6180
6192
  status = "blocked";
6181
6193
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
6182
6194
  break;
@@ -6191,6 +6203,13 @@ ${userPayload}` }], 900);
6191
6203
  steps.push({ step, thought, action: "done", ok: true, screenHash });
6192
6204
  break;
6193
6205
  }
6206
+ if (action === "back") {
6207
+ await ctx.page?.goBack?.().catch?.(() => {
6208
+ });
6209
+ steps.push({ step, thought, action: "back", ok: true, screenHash });
6210
+ history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
6211
+ continue;
6212
+ }
6194
6213
  if (action === "blocked") {
6195
6214
  status = "blocked";
6196
6215
  summary = value || thought || "LLM judged blocked";
@@ -6792,6 +6811,8 @@ var visualTagCommand = registerCommand({
6792
6811
  // src/commands/visual-tag-v2.ts
6793
6812
  import { z as z32 } from "zod";
6794
6813
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6814
+
6815
+ // src/commands/visual-tag-v2-script.ts
6795
6816
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6796
6817
  var TAG_V2_SCRIPT = `
6797
6818
  (function() {
@@ -7134,7 +7155,9 @@ var TAG_V2_SCRIPT = `
7134
7155
  return JSON.stringify(window.__xbTagStats);
7135
7156
  })()
7136
7157
  `;
7137
- var visualTagV2Command = registerCommand({
7158
+
7159
+ // src/commands/visual-tag-v2.ts
7160
+ registerCommand({
7138
7161
  name: "visual-tag-v2",
7139
7162
  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",
7140
7163
  scope: "page",
@@ -7409,8 +7432,8 @@ import {
7409
7432
  Core
7410
7433
  } from "@dyyz1993/xcli-core";
7411
7434
  import { resolve as resolve2, basename, dirname as dirname3 } from "path";
7412
- import { existsSync as existsSync6, readdirSync } from "fs";
7413
- import { homedir as homedir4 } from "os";
7435
+ import { existsSync as existsSync7, readdirSync } from "fs";
7436
+ import { homedir as homedir5 } from "os";
7414
7437
 
7415
7438
  // src/plugin/metadata-parser.ts
7416
7439
  import { existsSync as existsSync4 } from "fs";
@@ -7706,6 +7729,75 @@ function patchLoginRequired() {
7706
7729
  });
7707
7730
  }
7708
7731
 
7732
+ // src/lib/mistake-ledger.ts
7733
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
7734
+ import { homedir as homedir4 } from "os";
7735
+ import { join as join7 } from "path";
7736
+ var MISTAKE_THRESHOLD = 3;
7737
+ var MISTAKE_LEDGER_PATH = join7(
7738
+ homedir4(),
7739
+ ".xbrowser",
7740
+ "knowledge",
7741
+ "mistakes.json"
7742
+ );
7743
+ function emptyLedger() {
7744
+ return { version: 1, entries: {} };
7745
+ }
7746
+ function normalizeMistakeText(value) {
7747
+ return value.replace(/\d{4}-\d{2}-\d{2}T[^'"\s]+/g, "<timestamp>").replace(/\d+(?:\.\d+)?\s*(?:ms|s)\b/gi, "<duration>").replace(/\b\d+\b/g, "<number>").replace(/\s+/g, " ").trim();
7748
+ }
7749
+ function mistakeFingerprint(category, message) {
7750
+ return `${category}::${normalizeMistakeText(message)}`;
7751
+ }
7752
+ function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
7753
+ try {
7754
+ const parsed = JSON.parse(readFileSync6(path2, "utf8"));
7755
+ if (parsed.version !== 1 || typeof parsed.entries !== "object") {
7756
+ return emptyLedger();
7757
+ }
7758
+ return parsed;
7759
+ } catch {
7760
+ return emptyLedger();
7761
+ }
7762
+ }
7763
+ function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
7764
+ mkdirSync5(join7(path2, ".."), { recursive: true });
7765
+ writeFileSync6(path2, JSON.stringify(ledger, null, 2), "utf8");
7766
+ }
7767
+ function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
7768
+ if (!input.category) throw new Error("mistake category is required");
7769
+ if (!input.command) throw new Error("mistake command is required");
7770
+ if (!input.message) throw new Error("mistake message is required");
7771
+ const ledger = readMistakeLedger(path2);
7772
+ const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
7773
+ const previous = ledger.entries[fingerprint];
7774
+ const occurrence = {
7775
+ timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
7776
+ command: input.command,
7777
+ message: input.message,
7778
+ ...input.context ? { context: input.context } : {}
7779
+ };
7780
+ const entry = previous ? {
7781
+ ...previous,
7782
+ lastSeen: occurrence.timestamp,
7783
+ occurrences: [...previous.occurrences, occurrence].slice(-100),
7784
+ constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
7785
+ } : {
7786
+ fingerprint,
7787
+ category: input.category,
7788
+ firstSeen: occurrence.timestamp,
7789
+ lastSeen: occurrence.timestamp,
7790
+ occurrences: [occurrence],
7791
+ constrained: false
7792
+ };
7793
+ ledger.entries[fingerprint] = entry;
7794
+ writeMistakeLedger(ledger, path2);
7795
+ return {
7796
+ entry,
7797
+ newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
7798
+ };
7799
+ }
7800
+
7709
7801
  // src/plugin/loader.ts
7710
7802
  var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
7711
7803
  var XBrowserPluginLoader = class {
@@ -7716,6 +7808,7 @@ var XBrowserPluginLoader = class {
7716
7808
  dirSiteAliases = /* @__PURE__ */ new Map();
7717
7809
  constructor(options) {
7718
7810
  patchLoginRequired();
7811
+ globalThis.__xbrowserRecordMistake = recordMistake;
7719
7812
  this.options = options ?? {};
7720
7813
  const cwd = this.options.cwd || process.cwd();
7721
7814
  const coreConfig = {
@@ -7796,18 +7889,18 @@ var XBrowserPluginLoader = class {
7796
7889
  }
7797
7890
  async scanAndLoad() {
7798
7891
  const cwd = this.options.cwd || process.cwd();
7799
- const globalDir = this.options.globalDir || resolve2(homedir4(), ".xbrowser/plugins");
7892
+ const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
7800
7893
  ensurePluginDependencies(globalDir);
7801
7894
  const dirs = [
7802
7895
  resolve2(cwd, ".xcli/plugins"),
7803
7896
  resolve2(cwd, "../.xcli/plugins"),
7804
- this.options.userDir || resolve2(homedir4(), ".xcli/plugins"),
7897
+ this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
7805
7898
  globalDir
7806
7899
  ];
7807
7900
  const loaded = [];
7808
7901
  const seen = /* @__PURE__ */ new Set();
7809
7902
  for (const dir of dirs) {
7810
- if (!existsSync6(dir)) continue;
7903
+ if (!existsSync7(dir)) continue;
7811
7904
  const entries = readdirSync(dir, { withFileTypes: true });
7812
7905
  for (const entry of entries) {
7813
7906
  if (!entry.isDirectory()) continue;
@@ -7815,12 +7908,12 @@ var XBrowserPluginLoader = class {
7815
7908
  seen.add(entry.name);
7816
7909
  const pluginDir = resolve2(dir, entry.name);
7817
7910
  let indexPath = resolve2(pluginDir, "index.js");
7818
- if (!existsSync6(indexPath)) {
7911
+ if (!existsSync7(indexPath)) {
7819
7912
  indexPath = resolve2(pluginDir, "index.ts");
7820
7913
  }
7821
- if (!existsSync6(indexPath)) continue;
7914
+ if (!existsSync7(indexPath)) continue;
7822
7915
  try {
7823
- if (!existsSync6(resolve2(pluginDir, "package.json"))) {
7916
+ if (!existsSync7(resolve2(pluginDir, "package.json"))) {
7824
7917
  console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
7825
7918
  } else {
7826
7919
  const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
@@ -7846,166 +7939,110 @@ var XBrowserPluginLoader = class {
7846
7939
  }
7847
7940
  };
7848
7941
 
7849
- // src/fail-codes.ts
7850
- var FAIL_CODES = {
7851
- selectorNotFound: "RETRYABLE: selector-not-found",
7852
- pageNotReady: "RETRYABLE: page-not-ready",
7853
- elementGone: "RETRYABLE: element-gone",
7854
- inputNotRetained: "RETRYABLE: input-not-retained",
7855
- captcha: "HUMAN: captcha",
7856
- loginWall: "HUMAN: login-wall",
7857
- permissionDenied: "FATAL: permission-denied",
7858
- targetGone: "FATAL: target-gone",
7859
- unknown: "FATAL: unknown"
7860
- };
7861
- function classifyFailure(message) {
7862
- const msg = (message || "").toLowerCase();
7863
- const pick = (code) => ({
7864
- code,
7865
- level: code.split(":")[0],
7866
- message: message || code
7867
- });
7868
- if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
7869
- if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
7870
- if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
7871
- if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
7872
- return pick(FAIL_CODES.selectorNotFound);
7873
- if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
7874
- if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
7875
- if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
7876
- return pick(FAIL_CODES.targetGone);
7877
- return pick(FAIL_CODES.unknown);
7878
- }
7879
-
7880
- // src/executor.ts
7942
+ // src/executor/foundation.ts
7943
+ import { homedir as homedir6 } from "os";
7944
+ import { join as join8 } from "path";
7881
7945
  import {
7882
- ok as ok32,
7883
- fail as fail17,
7884
- isCommandResult,
7885
- CompositeStorage as CompositeStorage2,
7886
- TipCollector as TipCollector2,
7887
- normalizeTips as normalizeTips7,
7946
+ CompositeStorage,
7888
7947
  configureArchiveStore,
7889
7948
  appendCommandToArchive,
7890
- checkGuard,
7891
- unquote as unquote2
7949
+ fail as fail17,
7950
+ checkGuard
7892
7951
  } from "@dyyz1993/xcli-core";
7893
7952
 
7894
- // src/utils/positional-params.ts
7895
- import { unquote } from "@dyyz1993/xcli-core";
7896
- function getTypeName(field) {
7897
- return field?._def?.typeName;
7898
- }
7899
- function unwrapField(field) {
7900
- const typeName = getTypeName(field);
7901
- if (typeName === "ZodOptional" || typeName === "ZodDefault") {
7902
- const innerType = field?._def?.innerType;
7903
- return unwrapField(innerType);
7904
- }
7905
- return field;
7906
- }
7907
- function isOptionalNumber(field) {
7908
- const typeName = getTypeName(field);
7909
- return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
7953
+ // src/utils/plugin-singleton.ts
7954
+ var pluginLoader = null;
7955
+ var pluginsScanned = false;
7956
+ function silenceSchemaWarnings(fn) {
7957
+ if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
7958
+ const originalWarn = console.warn;
7959
+ console.warn = (...args) => {
7960
+ const msg = typeof args[0] === "string" ? args[0] : "";
7961
+ if (msg.includes('has no "result" schema')) return;
7962
+ originalWarn(...args);
7963
+ };
7964
+ return fn().finally(() => {
7965
+ console.warn = originalWarn;
7966
+ });
7910
7967
  }
7911
- function coerceValue(raw, field) {
7912
- const inner = unwrapField(field);
7913
- const optionalNum = isOptionalNumber(field);
7914
- const innerTypeName = getTypeName(inner);
7915
- if (innerTypeName === "ZodString") {
7916
- return { value: unquote(raw), skip: false };
7968
+ async function getPluginLoader() {
7969
+ if (!pluginLoader) {
7970
+ pluginLoader = new XBrowserPluginLoader();
7917
7971
  }
7918
- if (innerTypeName === "ZodNumber") {
7919
- const parsed = Number(raw);
7920
- if (isNaN(parsed)) {
7921
- if (optionalNum) return { value: void 0, skip: true };
7922
- return { value: raw, skip: false };
7923
- }
7924
- return { value: parsed, skip: false };
7972
+ if (!pluginsScanned) {
7973
+ await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
7974
+ pluginsScanned = true;
7925
7975
  }
7926
- if (innerTypeName === "ZodBoolean") {
7927
- if (raw === "true" || raw === "1") return { value: true, skip: false };
7928
- if (raw === "false" || raw === "0") return { value: false, skip: false };
7929
- return { value: raw, skip: false };
7976
+ return pluginLoader;
7977
+ }
7978
+
7979
+ // src/executor/foundation.ts
7980
+ var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
7981
+ var snapshotHintShown = /* @__PURE__ */ new WeakSet();
7982
+ var CONFIG_DIR = join8(homedir6(), ".xbrowser");
7983
+ var storageCache = /* @__PURE__ */ new Map();
7984
+ function getPluginStorage(pluginName) {
7985
+ if (!storageCache.has(pluginName)) {
7986
+ storageCache.set(pluginName, new CompositeStorage(pluginName, CONFIG_DIR, "xbrowser"));
7930
7987
  }
7931
- return { value: unquote(raw), skip: false };
7988
+ return storageCache.get(pluginName);
7932
7989
  }
7933
- function mapPositionalValues(schema, positional, existing) {
7934
- const result = { ...existing };
7935
- if (!schema || typeof schema !== "object") return result;
7936
- const shape = schema.shape;
7937
- if (!shape || typeof shape !== "object") return result;
7938
- const keys = Object.keys(shape);
7939
- let pIdx = 0;
7940
- for (const key of keys) {
7941
- if (pIdx >= positional.length) break;
7942
- if (result[key] !== void 0) {
7943
- pIdx++;
7944
- continue;
7990
+ var archiveInitialized = false;
7991
+ function ensureArchiveInit() {
7992
+ if (!archiveInitialized) {
7993
+ try {
7994
+ configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
7995
+ } catch {
7945
7996
  }
7946
- const field = shape[key];
7947
- const raw = positional[pIdx];
7948
- const { value, skip } = coerceValue(raw, field);
7949
- if (skip) continue;
7950
- result[key] = value;
7951
- pIdx++;
7997
+ archiveInitialized = true;
7952
7998
  }
7953
- return result;
7954
7999
  }
7955
-
7956
- // src/utils/plugin-params.ts
7957
- function parsePluginParams(args, schema, base = {}) {
7958
- const params = { ...base };
7959
- const positionalValues = [];
7960
- for (let i = 0; i < args.length; i++) {
7961
- if (args[i] === "--" && args[i + 1]) {
7962
- try {
7963
- Object.assign(params, JSON.parse(args[i + 1]));
7964
- } catch {
7965
- }
7966
- break;
7967
- }
7968
- if (args[i].startsWith("--")) {
7969
- const key = args[i].slice(2);
7970
- const value = args[i + 1];
7971
- if (value && !value.startsWith("-")) {
7972
- if (value === "true") params[key] = true;
7973
- else if (value === "false") params[key] = false;
7974
- else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
7975
- else {
7976
- try {
7977
- const parsed = JSON.parse(value);
7978
- if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
7979
- params[key] = parsed;
7980
- } else {
7981
- params[key] = value;
7982
- }
7983
- } catch {
7984
- params[key] = value;
7985
- }
7986
- }
7987
- i++;
7988
- } else {
7989
- params[key] = true;
7990
- }
7991
- } else if (!args[i].startsWith("-")) {
7992
- positionalValues.push(args[i]);
7993
- }
8000
+ function recordArchive(sessionId, sessionName, entry) {
8001
+ if (!sessionId) return;
8002
+ try {
8003
+ ensureArchiveInit();
8004
+ appendCommandToArchive(sessionId, sessionName, entry);
8005
+ } catch {
7994
8006
  }
7995
- Object.assign(params, mapPositionalValues(schema, positionalValues, params));
7996
- const result = {};
7997
- for (const [k, v] of Object.entries(params)) {
7998
- const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
7999
- result[camelKey] = v;
8007
+ }
8008
+ async function guardCheck(commandName) {
8009
+ try {
8010
+ const loader = await getPluginLoader();
8011
+ return checkGuard(loader.getCore(), commandName, process.env);
8012
+ } catch {
8013
+ return null;
8000
8014
  }
8001
- return result;
8002
8015
  }
8016
+ function errorResult(message) {
8017
+ return { ...fail17(message), duration: 0 };
8018
+ }
8019
+ function tipsToMessages(tips) {
8020
+ if (!tips || tips.length === 0) return [];
8021
+ return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
8022
+ }
8023
+ var wsServer = null;
8024
+ function setWSServer(server) {
8025
+ wsServer = server;
8026
+ }
8027
+ function streamCommandEvent(sessionId, message) {
8028
+ if (!wsServer || !wsServer.getRunning()) return;
8029
+ wsServer.broadcastToSession(sessionId, { type: "command", data: message });
8030
+ }
8031
+
8032
+ // src/executor.ts
8033
+ import {
8034
+ ok as ok33,
8035
+ fail as fail19,
8036
+ isCommandResult,
8037
+ normalizeTips as normalizeTips8,
8038
+ TipCollector as TipCollector3
8039
+ } from "@dyyz1993/xcli-core";
8003
8040
 
8004
8041
  // src/utils/stub-context.ts
8005
- import { join as join7 } from "path";
8006
- import { homedir as homedir5 } from "os";
8007
- import { TipCollector, CompositeStorage } from "@dyyz1993/xcli-core";
8008
- var CONFIG_DIR = join7(homedir5(), ".xbrowser");
8042
+ import { join as join9 } from "path";
8043
+ import { homedir as homedir7 } from "os";
8044
+ import { TipCollector, CompositeStorage as CompositeStorage2 } from "@dyyz1993/xcli-core";
8045
+ var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
8009
8046
  var NoopSiteInstance = class {
8010
8047
  name = "stub";
8011
8048
  url = "";
@@ -8028,7 +8065,7 @@ var NoopSiteInstance = class {
8028
8065
  async requireLogin() {
8029
8066
  }
8030
8067
  getStorage() {
8031
- return new CompositeStorage("stub", CONFIG_DIR, "xbrowser");
8068
+ return new CompositeStorage2("stub", CONFIG_DIR2, "xbrowser");
8032
8069
  }
8033
8070
  getAllCommands() {
8034
8071
  return [];
@@ -8052,7 +8089,7 @@ function createStubContext(pluginName) {
8052
8089
  args: [],
8053
8090
  options: {},
8054
8091
  cwd: process.cwd(),
8055
- storage: new CompositeStorage(pluginName, CONFIG_DIR, "xbrowser"),
8092
+ storage: new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"),
8056
8093
  output: { mode: "text", showTips: false, color: false, emoji: false },
8057
8094
  error: (msg) => {
8058
8095
  throw new Error(msg);
@@ -8064,140 +8101,6 @@ function createStubContext(pluginName) {
8064
8101
  };
8065
8102
  }
8066
8103
 
8067
- // src/utils/plugin-singleton.ts
8068
- var pluginLoader = null;
8069
- var pluginsScanned = false;
8070
- function silenceSchemaWarnings(fn) {
8071
- if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
8072
- const originalWarn = console.warn;
8073
- console.warn = (...args) => {
8074
- const msg = typeof args[0] === "string" ? args[0] : "";
8075
- if (msg.includes('has no "result" schema')) return;
8076
- originalWarn(...args);
8077
- };
8078
- return fn().finally(() => {
8079
- console.warn = originalWarn;
8080
- });
8081
- }
8082
- async function getPluginLoader() {
8083
- if (!pluginLoader) {
8084
- pluginLoader = new XBrowserPluginLoader();
8085
- }
8086
- if (!pluginsScanned) {
8087
- await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
8088
- pluginsScanned = true;
8089
- }
8090
- return pluginLoader;
8091
- }
8092
-
8093
- // src/plugin/login-guard.ts
8094
- async function checkPluginLoginRequired(options) {
8095
- const { site, command, commandName, ctx, page, sessionName } = options;
8096
- if (commandName === "login" || commandName === "logout") return { ok: true };
8097
- const loginConfig = site.config?.loginConfig;
8098
- const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
8099
- if (!requiresLogin) return { ok: true };
8100
- const pluginName = site.name || "plugin";
8101
- const siteConfig = site.config;
8102
- const configIsLogin = siteConfig?.isLogin;
8103
- if (configIsLogin) {
8104
- try {
8105
- const loggedIn = await configIsLogin(ctx);
8106
- if (loggedIn) return { ok: true };
8107
- return buildLoginRequired({
8108
- plugin: pluginName,
8109
- command: commandName,
8110
- reason: "config.isLogin returned false",
8111
- sessionName,
8112
- loginConfig
8113
- });
8114
- } catch {
8115
- }
8116
- }
8117
- if (typeof site.isLoggedIn === "function") {
8118
- try {
8119
- const loggedIn = await site.isLoggedIn(ctx);
8120
- if (loggedIn) return { ok: true };
8121
- return buildLoginRequired({
8122
- plugin: pluginName,
8123
- command: commandName,
8124
- reason: "plugin isLoggedIn returned false",
8125
- sessionName,
8126
- loginConfig
8127
- });
8128
- } catch {
8129
- }
8130
- }
8131
- if (page && loginConfig) {
8132
- const generic = await detectLoginFromPage(page, loginConfig);
8133
- if (generic === "logged-in") return { ok: true };
8134
- if (generic === "logged-out") {
8135
- return buildLoginRequired({
8136
- plugin: pluginName,
8137
- command: commandName,
8138
- reason: "generic loginConfig detected logged-out page",
8139
- sessionName,
8140
- loginConfig
8141
- });
8142
- }
8143
- }
8144
- return { ok: true };
8145
- }
8146
- function buildLoginRequired(options) {
8147
- const viewerUrl = buildViewerUrl(options.sessionName);
8148
- const loginUrl = options.loginConfig?.loginUrl;
8149
- const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
8150
- const tips = [
8151
- message,
8152
- ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
8153
- ...loginUrl ? [`Login page: ${loginUrl}`] : [],
8154
- `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
8155
- ];
8156
- return {
8157
- ok: false,
8158
- data: {
8159
- code: "LOGIN_REQUIRED",
8160
- plugin: options.plugin,
8161
- command: options.command,
8162
- reason: options.reason,
8163
- ...viewerUrl ? { viewerUrl } : {},
8164
- ...loginUrl ? { loginUrl } : {}
8165
- },
8166
- message,
8167
- tips
8168
- };
8169
- }
8170
- async function detectLoginFromPage(page, config) {
8171
- const url = page.url();
8172
- if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
8173
- const result = await page.evaluate((cfg) => {
8174
- const visible = (selector) => {
8175
- try {
8176
- const el = document.querySelector(selector);
8177
- if (!el) return false;
8178
- const rect = el.getBoundingClientRect();
8179
- const style = window.getComputedStyle(el);
8180
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
8181
- } catch {
8182
- return false;
8183
- }
8184
- };
8185
- if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
8186
- if (cfg.loginSelectors?.some(visible)) return "logged-out";
8187
- const bodyText = document.body?.innerText || "";
8188
- const keywords = cfg.loginKeywords || [];
8189
- if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
8190
- return "logged-out";
8191
- }
8192
- return "unknown";
8193
- }, {
8194
- loginSelectors: config.loginSelectors || [],
8195
- loginKeywords: config.loginKeywords || [],
8196
- loggedInSelectors: config.loggedInSelectors || []
8197
- });
8198
- return result;
8199
- }
8200
-
8201
8104
  // src/tips/dom-watcher.ts
8202
8105
  var DOM_WATCHER_SCRIPT = `
8203
8106
  (function() {
@@ -8698,83 +8601,526 @@ async function loadHooks() {
8698
8601
  return hooks;
8699
8602
  }
8700
8603
 
8701
- // src/executor.ts
8702
- import { homedir as homedir6 } from "os";
8703
- import { join as join8 } from "path";
8704
- function levenshtein(a, b) {
8705
- const m = a.length, n = b.length;
8706
- const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
8707
- for (let i = 0; i <= m; i++) dp[i][0] = i;
8708
- for (let j = 0; j <= n; j++) dp[0][j] = j;
8709
- for (let i = 1; i <= m; i++) {
8710
- for (let j = 1; j <= n; j++) {
8711
- 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]);
8712
- }
8713
- }
8714
- return dp[m][n];
8715
- }
8716
- var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8717
- var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8718
- var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8719
- var storageCache = /* @__PURE__ */ new Map();
8720
- function getPluginStorage(pluginName) {
8721
- if (!storageCache.has(pluginName)) {
8722
- storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
8723
- }
8724
- return storageCache.get(pluginName);
8604
+ // src/fail-codes.ts
8605
+ var FAIL_CODES = {
8606
+ selectorNotFound: "RETRYABLE: selector-not-found",
8607
+ pageNotReady: "RETRYABLE: page-not-ready",
8608
+ elementGone: "RETRYABLE: element-gone",
8609
+ inputNotRetained: "RETRYABLE: input-not-retained",
8610
+ captcha: "HUMAN: captcha",
8611
+ loginWall: "HUMAN: login-wall",
8612
+ permissionDenied: "FATAL: permission-denied",
8613
+ targetGone: "FATAL: target-gone",
8614
+ unknown: "FATAL: unknown"
8615
+ };
8616
+ function classifyFailure(message) {
8617
+ const msg = (message || "").toLowerCase();
8618
+ const pick = (code) => ({
8619
+ code,
8620
+ level: code.split(":")[0],
8621
+ message: message || code
8622
+ });
8623
+ if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
8624
+ if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
8625
+ if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
8626
+ if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
8627
+ return pick(FAIL_CODES.selectorNotFound);
8628
+ if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
8629
+ if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
8630
+ if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
8631
+ return pick(FAIL_CODES.targetGone);
8632
+ return pick(FAIL_CODES.unknown);
8725
8633
  }
8726
- var archiveInitialized = false;
8727
- function ensureArchiveInit() {
8728
- if (!archiveInitialized) {
8634
+
8635
+ // src/executor/chain.ts
8636
+ import {
8637
+ fail as fail18,
8638
+ ok as ok32,
8639
+ TipCollector as TipCollector2,
8640
+ normalizeTips as normalizeTips7,
8641
+ unquote as unquote2
8642
+ } from "@dyyz1993/xcli-core";
8643
+
8644
+ // src/plugin/login-guard.ts
8645
+ async function checkPluginLoginRequired(options) {
8646
+ const { site, command, commandName, ctx, page, sessionName } = options;
8647
+ if (commandName === "login" || commandName === "logout") return { ok: true };
8648
+ const loginConfig = site.config?.loginConfig;
8649
+ const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
8650
+ if (!requiresLogin) return { ok: true };
8651
+ const pluginName = site.name || "plugin";
8652
+ const siteConfig = site.config;
8653
+ const configIsLogin = siteConfig?.isLogin;
8654
+ if (configIsLogin) {
8729
8655
  try {
8730
- configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
8656
+ const loggedIn = await configIsLogin(ctx);
8657
+ if (loggedIn) return { ok: true };
8658
+ return buildLoginRequired({
8659
+ plugin: pluginName,
8660
+ command: commandName,
8661
+ reason: "config.isLogin returned false",
8662
+ sessionName,
8663
+ loginConfig
8664
+ });
8731
8665
  } catch {
8732
8666
  }
8733
- archiveInitialized = true;
8734
8667
  }
8735
- }
8736
- function recordArchive(sessionId, sessionName, entry) {
8737
- if (!sessionId) return;
8738
- try {
8739
- ensureArchiveInit();
8740
- appendCommandToArchive(sessionId, sessionName, entry);
8741
- } catch {
8668
+ if (typeof site.isLoggedIn === "function") {
8669
+ try {
8670
+ const loggedIn = await site.isLoggedIn(ctx);
8671
+ if (loggedIn) return { ok: true };
8672
+ return buildLoginRequired({
8673
+ plugin: pluginName,
8674
+ command: commandName,
8675
+ reason: "plugin isLoggedIn returned false",
8676
+ sessionName,
8677
+ loginConfig
8678
+ });
8679
+ } catch {
8680
+ }
8742
8681
  }
8743
- }
8744
- async function guardCheck(commandName) {
8745
- try {
8746
- const loader = await getPluginLoader();
8747
- const core = loader.getCore();
8748
- return checkGuard(core, commandName, process.env);
8749
- } catch {
8750
- return null;
8682
+ if (page && loginConfig) {
8683
+ const generic = await detectLoginFromPage(page, loginConfig);
8684
+ if (generic === "logged-in") return { ok: true };
8685
+ if (generic === "logged-out") {
8686
+ return buildLoginRequired({
8687
+ plugin: pluginName,
8688
+ command: commandName,
8689
+ reason: "generic loginConfig detected logged-out page",
8690
+ sessionName,
8691
+ loginConfig
8692
+ });
8693
+ }
8751
8694
  }
8695
+ return { ok: true };
8752
8696
  }
8753
- function errorResult(message) {
8754
- return { ...fail17(message), duration: 0 };
8755
- }
8756
- function tipsToMessages(tips) {
8757
- if (!tips || tips.length === 0) return [];
8758
- return tips.map((t) => typeof t === "string" ? t : t.message);
8759
- }
8760
- var wsServer = null;
8761
- function setWSServer(server) {
8762
- wsServer = server;
8763
- }
8764
- function streamCommandEvent(sessionId, message) {
8765
- if (!wsServer || !wsServer.getRunning()) return;
8766
- wsServer.broadcastToSession(sessionId, {
8767
- type: "command",
8768
- data: message
8769
- });
8770
- }
8771
- async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
8772
- const guardResult = await guardCheck(commandName);
8773
- if (guardResult?.blocked) {
8774
- return errorResult(guardResult.message);
8775
- }
8776
- const command = getCommand(commandName);
8777
- if (!command) {
8697
+ function buildLoginRequired(options) {
8698
+ const viewerUrl = buildViewerUrl(options.sessionName);
8699
+ const loginUrl = options.loginConfig?.loginUrl;
8700
+ const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
8701
+ const tips = [
8702
+ message,
8703
+ ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
8704
+ ...loginUrl ? [`Login page: ${loginUrl}`] : [],
8705
+ `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
8706
+ ];
8707
+ return {
8708
+ ok: false,
8709
+ data: {
8710
+ code: "LOGIN_REQUIRED",
8711
+ plugin: options.plugin,
8712
+ command: options.command,
8713
+ reason: options.reason,
8714
+ ...viewerUrl ? { viewerUrl } : {},
8715
+ ...loginUrl ? { loginUrl } : {}
8716
+ },
8717
+ message,
8718
+ tips
8719
+ };
8720
+ }
8721
+ async function detectLoginFromPage(page, config) {
8722
+ const url = page.url();
8723
+ if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
8724
+ const result = await page.evaluate((cfg) => {
8725
+ const visible = (selector) => {
8726
+ try {
8727
+ const el = document.querySelector(selector);
8728
+ if (!el) return false;
8729
+ const rect = el.getBoundingClientRect();
8730
+ const style = window.getComputedStyle(el);
8731
+ return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
8732
+ } catch {
8733
+ return false;
8734
+ }
8735
+ };
8736
+ if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
8737
+ if (cfg.loginSelectors?.some(visible)) return "logged-out";
8738
+ const bodyText = document.body?.innerText || "";
8739
+ const keywords = cfg.loginKeywords || [];
8740
+ if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
8741
+ return "logged-out";
8742
+ }
8743
+ return "unknown";
8744
+ }, {
8745
+ loginSelectors: config.loginSelectors || [],
8746
+ loginKeywords: config.loginKeywords || [],
8747
+ loggedInSelectors: config.loggedInSelectors || []
8748
+ });
8749
+ return result;
8750
+ }
8751
+
8752
+ // src/utils/positional-params.ts
8753
+ import { unquote } from "@dyyz1993/xcli-core";
8754
+ function getTypeName(field) {
8755
+ return field?._def?.typeName;
8756
+ }
8757
+ function unwrapField(field) {
8758
+ const typeName = getTypeName(field);
8759
+ if (typeName === "ZodOptional" || typeName === "ZodDefault") {
8760
+ const innerType = field?._def?.innerType;
8761
+ return unwrapField(innerType);
8762
+ }
8763
+ return field;
8764
+ }
8765
+ function isOptionalNumber(field) {
8766
+ const typeName = getTypeName(field);
8767
+ return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
8768
+ }
8769
+ function coerceValue(raw, field) {
8770
+ const inner = unwrapField(field);
8771
+ const optionalNum = isOptionalNumber(field);
8772
+ const innerTypeName = getTypeName(inner);
8773
+ if (innerTypeName === "ZodString") {
8774
+ return { value: unquote(raw), skip: false };
8775
+ }
8776
+ if (innerTypeName === "ZodNumber") {
8777
+ const parsed = Number(raw);
8778
+ if (isNaN(parsed)) {
8779
+ if (optionalNum) return { value: void 0, skip: true };
8780
+ return { value: raw, skip: false };
8781
+ }
8782
+ return { value: parsed, skip: false };
8783
+ }
8784
+ if (innerTypeName === "ZodBoolean") {
8785
+ if (raw === "true" || raw === "1") return { value: true, skip: false };
8786
+ if (raw === "false" || raw === "0") return { value: false, skip: false };
8787
+ return { value: raw, skip: false };
8788
+ }
8789
+ return { value: unquote(raw), skip: false };
8790
+ }
8791
+ function mapPositionalValues(schema, positional, existing) {
8792
+ const result = { ...existing };
8793
+ if (!schema || typeof schema !== "object") return result;
8794
+ const shape = schema.shape;
8795
+ if (!shape || typeof shape !== "object") return result;
8796
+ const keys = Object.keys(shape);
8797
+ let pIdx = 0;
8798
+ for (const key of keys) {
8799
+ if (pIdx >= positional.length) break;
8800
+ if (result[key] !== void 0) {
8801
+ pIdx++;
8802
+ continue;
8803
+ }
8804
+ const field = shape[key];
8805
+ const raw = positional[pIdx];
8806
+ const { value, skip } = coerceValue(raw, field);
8807
+ if (skip) continue;
8808
+ result[key] = value;
8809
+ pIdx++;
8810
+ }
8811
+ return result;
8812
+ }
8813
+
8814
+ // src/utils/plugin-params.ts
8815
+ function schemaFieldType(schema, key) {
8816
+ const shape = schema?.shape;
8817
+ const field = shape?.[key];
8818
+ let current = field;
8819
+ while (current) {
8820
+ const def = current._def;
8821
+ if (!def) return void 0;
8822
+ const type = def.typeName ?? def.type;
8823
+ if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
8824
+ current = def.innerType ?? def.inner;
8825
+ continue;
8826
+ }
8827
+ return type;
8828
+ }
8829
+ return void 0;
8830
+ }
8831
+ function parsePluginParams(args, schema, base = {}) {
8832
+ const params = { ...base };
8833
+ const positionalValues = [];
8834
+ for (let i = 0; i < args.length; i++) {
8835
+ if (args[i] === "--" && args[i + 1]) {
8836
+ try {
8837
+ Object.assign(params, JSON.parse(args[i + 1]));
8838
+ } catch {
8839
+ }
8840
+ break;
8841
+ }
8842
+ if (args[i].startsWith("--")) {
8843
+ const key = args[i].slice(2);
8844
+ const value = args[i + 1];
8845
+ if (value && !value.startsWith("-")) {
8846
+ const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
8847
+ if (type === "ZodString" || type === "string") params[key] = value;
8848
+ else if (value === "true") params[key] = true;
8849
+ else if (value === "false") params[key] = false;
8850
+ else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
8851
+ else {
8852
+ try {
8853
+ const parsed = JSON.parse(value);
8854
+ if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
8855
+ params[key] = parsed;
8856
+ } else {
8857
+ params[key] = value;
8858
+ }
8859
+ } catch {
8860
+ params[key] = value;
8861
+ }
8862
+ }
8863
+ i++;
8864
+ } else {
8865
+ params[key] = true;
8866
+ }
8867
+ } else if (!args[i].startsWith("-")) {
8868
+ positionalValues.push(args[i]);
8869
+ }
8870
+ }
8871
+ Object.assign(params, mapPositionalValues(schema, positionalValues, params));
8872
+ const result = {};
8873
+ for (const [k, v] of Object.entries(params)) {
8874
+ const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8875
+ result[camelKey] = v;
8876
+ }
8877
+ return result;
8878
+ }
8879
+
8880
+ // src/executor/chain.ts
8881
+ async function executeChain(input, options, executeCommand2) {
8882
+ const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8883
+ const sessionName = options?.sessionName || "default";
8884
+ const results = [];
8885
+ const totalStart = Date.now();
8886
+ let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8887
+ if (!session) {
8888
+ const launchOpts = {};
8889
+ if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
8890
+ session = await createSession(sessionName, void 0, launchOpts);
8891
+ saveSessionDiskMeta(sessionName, {
8892
+ id: session.id,
8893
+ name: sessionName,
8894
+ url: session.page.url(),
8895
+ createdAt: session.createdAt,
8896
+ cdpEndpoint: session.cdpEndpoint
8897
+ });
8898
+ }
8899
+ try {
8900
+ for (const pipeline of pipelines) {
8901
+ const { type, pipeline: commands } = pipeline;
8902
+ for (const cmdStr of commands) {
8903
+ if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
8904
+ await new Promise((resolve3) => setTimeout(resolve3, 800 + Math.random() * 1700));
8905
+ }
8906
+ const parts = splitCommand(cmdStr);
8907
+ if (parts.length === 0) continue;
8908
+ const cmdName = parts[0];
8909
+ const cmdArgs = parts.slice(1);
8910
+ const loader = await getPluginLoader();
8911
+ const internalLoader = loader.getCore().loader;
8912
+ const resolvedName = loader.resolveSiteName(cmdName);
8913
+ const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
8914
+ if (site) {
8915
+ const pluginHandled = await executePluginChainStep({
8916
+ site,
8917
+ cmdName,
8918
+ cmdArgs,
8919
+ cmdStr,
8920
+ type,
8921
+ results,
8922
+ totalStart,
8923
+ session,
8924
+ sessionName
8925
+ });
8926
+ if (pluginHandled) return pluginHandled;
8927
+ continue;
8928
+ }
8929
+ const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8930
+ if (cmdName === "goto" && params.url) {
8931
+ const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8932
+ if (!existing) {
8933
+ session = await createSession(sessionName, params.url, {
8934
+ cdpEndpoint: options?.cdpEndpoint
8935
+ });
8936
+ }
8937
+ }
8938
+ const result = await executeCommand2(cmdName, params, sessionName, {
8939
+ cdpEndpoint: options?.cdpEndpoint,
8940
+ skipCleanup: true
8941
+ });
8942
+ results.push({
8943
+ command: cmdName,
8944
+ raw: cmdStr,
8945
+ success: result.success,
8946
+ data: result.data,
8947
+ message: result.message,
8948
+ duration: 0,
8949
+ tips: result.tips,
8950
+ ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
8951
+ });
8952
+ if (type === "and" && !result.success) {
8953
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
8954
+ }
8955
+ if (type === "or" && result.success) {
8956
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
8957
+ }
8958
+ }
8959
+ }
8960
+ return {
8961
+ success: !results.some((result) => !result.success),
8962
+ steps: results,
8963
+ totalDuration: Date.now() - totalStart
8964
+ };
8965
+ } finally {
8966
+ }
8967
+ }
8968
+ function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
8969
+ return {
8970
+ success,
8971
+ steps,
8972
+ totalDuration: Date.now() - totalStart,
8973
+ stoppedAt,
8974
+ stoppedReason: reason
8975
+ };
8976
+ }
8977
+ async function executePluginChainStep(context) {
8978
+ const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
8979
+ const subCommand = cmdArgs[0];
8980
+ if (!subCommand) {
8981
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
8982
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
8983
+ return void 0;
8984
+ }
8985
+ const cmdEntry = site.getCommand(subCommand);
8986
+ if (!cmdEntry) {
8987
+ results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
8988
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
8989
+ return void 0;
8990
+ }
8991
+ const pluginArgs = cmdArgs.slice(1);
8992
+ const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
8993
+ if (cmdEntry.parameters) {
8994
+ const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
8995
+ if (schemaCheck.success) {
8996
+ for (const [key, value] of Object.entries(schemaCheck.data)) {
8997
+ if (!(key in pluginParams)) pluginParams[key] = value;
8998
+ }
8999
+ }
9000
+ }
9001
+ const pluginCtx = {
9002
+ args: pluginArgs,
9003
+ options: pluginParams,
9004
+ cwd: process.cwd(),
9005
+ page: session.page,
9006
+ browser: session.context.browser(),
9007
+ browserContext: session.context,
9008
+ sessionId: session.id,
9009
+ storage: getPluginStorage(cmdName),
9010
+ output: { mode: "text", showTips: false, color: false, emoji: false },
9011
+ error: (message) => {
9012
+ throw new Error(message);
9013
+ },
9014
+ config: {},
9015
+ site,
9016
+ cliName: "xbrowser",
9017
+ tips: new TipCollector2()
9018
+ };
9019
+ const start = Date.now();
9020
+ try {
9021
+ const loginGuard = await checkPluginLoginRequired({
9022
+ site,
9023
+ command: cmdEntry,
9024
+ commandName: subCommand,
9025
+ ctx: pluginCtx,
9026
+ page: session.page,
9027
+ sessionName
9028
+ });
9029
+ if (!loginGuard.ok) {
9030
+ const duration2 = Date.now() - start;
9031
+ const data2 = loginGuard.data ?? null;
9032
+ recordArchive(session.id, sessionName, {
9033
+ step: results.length,
9034
+ command: `${cmdName} ${subCommand}`,
9035
+ params: pluginParams,
9036
+ result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
9037
+ toolCalls: [],
9038
+ duration: duration2,
9039
+ timestamp: start
9040
+ });
9041
+ results.push({
9042
+ command: `${cmdName} ${subCommand}`,
9043
+ raw: cmdStr,
9044
+ success: false,
9045
+ data: data2,
9046
+ message: loginGuard.message,
9047
+ tips: normalizeTips7(loginGuard.tips),
9048
+ duration: duration2
9049
+ });
9050
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
9051
+ return void 0;
9052
+ }
9053
+ const hooks = await loadHooks();
9054
+ if (hooks.length > 0) {
9055
+ await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
9056
+ }
9057
+ const raw = await cmdEntry.handler(pluginParams, pluginCtx);
9058
+ const duration = Date.now() - start;
9059
+ let hookOutputs;
9060
+ if (hooks.length > 0) {
9061
+ const outputs = [];
9062
+ for (const hook of hooks) {
9063
+ const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
9064
+ if (output) outputs.push({ _hook: hook.name, ...output });
9065
+ }
9066
+ if (outputs.length > 0) hookOutputs = outputs;
9067
+ }
9068
+ const data = raw?.data ?? raw;
9069
+ recordArchive(session.id, sessionName, {
9070
+ step: results.length,
9071
+ command: `${cmdName} ${subCommand}`,
9072
+ params: pluginParams,
9073
+ result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9074
+ toolCalls: [],
9075
+ duration,
9076
+ timestamp: start
9077
+ });
9078
+ results.push({
9079
+ command: `${cmdName} ${subCommand}`,
9080
+ raw: cmdStr,
9081
+ ...ok32(data),
9082
+ duration,
9083
+ ...hookOutputs ? { hookOutputs } : {}
9084
+ });
9085
+ if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9086
+ } catch (error) {
9087
+ const duration = Date.now() - start;
9088
+ const message = errMsg(error);
9089
+ recordArchive(session.id, sessionName, {
9090
+ step: results.length,
9091
+ command: `${cmdName} ${subCommand}`,
9092
+ params: pluginParams,
9093
+ result: { success: false, data: null, message, tips: [] },
9094
+ toolCalls: [],
9095
+ duration,
9096
+ timestamp: start
9097
+ });
9098
+ results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
9099
+ if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
9100
+ }
9101
+ return void 0;
9102
+ }
9103
+
9104
+ // src/executor.ts
9105
+ function levenshtein(a, b) {
9106
+ const m = a.length, n = b.length;
9107
+ const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
9108
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
9109
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
9110
+ for (let i = 1; i <= m; i++) {
9111
+ for (let j = 1; j <= n; j++) {
9112
+ 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]);
9113
+ }
9114
+ }
9115
+ return dp[m][n];
9116
+ }
9117
+ async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
9118
+ const guardResult = await guardCheck(commandName);
9119
+ if (guardResult?.blocked) {
9120
+ return errorResult(guardResult.message);
9121
+ }
9122
+ const command = getCommand(commandName);
9123
+ if (!command) {
8778
9124
  const available = getAllCommands().map((c) => c.name);
8779
9125
  const suggestions = available.map((name) => ({ name, dist: levenshtein(commandName, name) })).filter((s) => s.dist <= 3).sort((a, b) => a.dist - b.dist).slice(0, 3).map((s) => s.name);
8780
9126
  let hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(" or ")}?` : "";
@@ -8815,8 +9161,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8815
9161
  if (knownPlugins.includes(commandName)) {
8816
9162
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8817
9163
  }
9164
+ const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
9165
+ recordMistake({
9166
+ category: classifyFailure(message).code,
9167
+ command: commandName,
9168
+ message,
9169
+ context: { sessionName, params }
9170
+ });
8818
9171
  return errorResult(
8819
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
9172
+ message
8820
9173
  );
8821
9174
  }
8822
9175
  const _target = params._target;
@@ -8831,7 +9184,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8831
9184
  }
8832
9185
  let targetPageOverride = null;
8833
9186
  if (_target && extraOpts?.cdpEndpoint) {
8834
- const { findTargetPage } = await import("./browser-4IYIHZ6R.js");
9187
+ const { findTargetPage } = await import("./browser-XD3IOU5I.js");
8835
9188
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8836
9189
  if (!targetPageOverride) {
8837
9190
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8849,7 +9202,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8849
9202
  }
8850
9203
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8851
9204
  const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
8852
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
9205
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8853
9206
  const result = await forwardExec(
8854
9207
  commandName,
8855
9208
  params,
@@ -8911,7 +9264,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8911
9264
  config: {},
8912
9265
  site: new NoopSiteInstance(),
8913
9266
  cliName: "xbrowser",
8914
- tips: new TipCollector2()
9267
+ tips: new TipCollector3()
8915
9268
  };
8916
9269
  attachDetectAntiBot(ctx);
8917
9270
  if (_tabIndex !== void 0 && session?.context) {
@@ -8943,7 +9296,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8943
9296
  const cache = /* @__PURE__ */ new Map();
8944
9297
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8945
9298
  if (resolved.tips.length > 0) {
8946
- refTips = normalizeTips7(resolved.tips);
9299
+ refTips = normalizeTips8(resolved.tips);
8947
9300
  params = resolved.params;
8948
9301
  }
8949
9302
  }
@@ -9011,11 +9364,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9011
9364
  }
9012
9365
  const merged = [
9013
9366
  ...raw.tips || [],
9014
- ...normalizeTips7(smartTips),
9015
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
9367
+ ...normalizeTips8(smartTips),
9368
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
9016
9369
  ...refTips
9017
9370
  ];
9018
9371
  const isSuccess = raw.success !== false;
9372
+ if (!isSuccess) {
9373
+ recordMistake({
9374
+ category: classifyFailure(raw.message).code,
9375
+ command: commandName,
9376
+ message: raw.message ?? "unknown command failure",
9377
+ context: { sessionName, params }
9378
+ });
9379
+ }
9019
9380
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
9020
9381
  recordArchive(session?.id, sessionName, {
9021
9382
  step: 0,
@@ -9027,7 +9388,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9027
9388
  timestamp: start
9028
9389
  });
9029
9390
  if (isSuccess) {
9030
- return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9391
+ return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9031
9392
  }
9032
9393
  const fc = classifyFailure(raw.message);
9033
9394
  return {
@@ -9040,7 +9401,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9040
9401
  ...hookOutputs ? { hookOutputs } : {}
9041
9402
  };
9042
9403
  }
9043
- const smartTipNormalized = normalizeTips7(smartTips);
9404
+ const smartTipNormalized = normalizeTips8(smartTips);
9044
9405
  recordArchive(session?.id, sessionName, {
9045
9406
  step: 0,
9046
9407
  command: commandName,
@@ -9050,11 +9411,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9050
9411
  duration,
9051
9412
  timestamp: start
9052
9413
  });
9053
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9414
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9054
9415
  } catch (err) {
9055
9416
  const end = Date.now();
9056
9417
  const duration = end - start;
9057
9418
  const errorMessage = errMsg(err);
9419
+ recordMistake({
9420
+ category: classifyFailure(errorMessage).code,
9421
+ command: commandName,
9422
+ message: errorMessage,
9423
+ context: { sessionName, params }
9424
+ });
9058
9425
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
9059
9426
  try {
9060
9427
  const { attemptRecovery } = await import("./recovery-IMZUGWSS.js");
@@ -9095,287 +9462,18 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9095
9462
  duration,
9096
9463
  timestamp: start
9097
9464
  });
9098
- return { ...fail17(errorMessage), duration };
9465
+ return { ...fail19(errorMessage), duration };
9099
9466
  } finally {
9100
9467
  }
9101
9468
  }
9102
- async function executeChain(input, options) {
9103
- const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
9104
- const sessionName = options?.sessionName || "default";
9105
- const results = [];
9106
- const totalStart = Date.now();
9107
- let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
9108
- if (!session) {
9109
- const launchOpts = {};
9110
- if (options?.cdpEndpoint) {
9111
- launchOpts.cdpEndpoint = options.cdpEndpoint;
9112
- }
9113
- session = await createSession(sessionName, void 0, launchOpts);
9114
- saveSessionDiskMeta(sessionName, {
9115
- id: session.id,
9116
- name: sessionName,
9117
- url: session.page.url(),
9118
- createdAt: session.createdAt,
9119
- cdpEndpoint: session.cdpEndpoint
9120
- });
9121
- }
9122
- try {
9123
- for (const pipeline of pipelines) {
9124
- const { type, pipeline: commands } = pipeline;
9125
- for (const cmdStr of commands) {
9126
- if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
9127
- await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
9128
- }
9129
- const parts = splitCommand(cmdStr);
9130
- if (parts.length === 0) continue;
9131
- const cmdName = parts[0];
9132
- const cmdArgs = parts.slice(1);
9133
- const loader = await getPluginLoader();
9134
- const internalLoader = loader.getCore().loader;
9135
- const resolvedName = loader.resolveSiteName(cmdName);
9136
- const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
9137
- if (site) {
9138
- const subCommand = cmdArgs[0];
9139
- if (!subCommand) {
9140
- results.push({
9141
- command: cmdName,
9142
- raw: cmdStr,
9143
- ...fail17(`Plugin "${cmdName}" requires a sub-command`),
9144
- duration: 0
9145
- });
9146
- if (type === "and") {
9147
- return {
9148
- success: false,
9149
- steps: results,
9150
- totalDuration: Date.now() - totalStart,
9151
- stoppedAt: results.length,
9152
- stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
9153
- };
9154
- }
9155
- continue;
9156
- }
9157
- const cmdEntry = site.getCommand(subCommand);
9158
- if (!cmdEntry) {
9159
- results.push({
9160
- command: cmdName,
9161
- raw: cmdStr,
9162
- ...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
9163
- duration: 0
9164
- });
9165
- if (type === "and") {
9166
- return {
9167
- success: false,
9168
- steps: results,
9169
- totalDuration: Date.now() - totalStart,
9170
- stoppedAt: results.length,
9171
- stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
9172
- };
9173
- }
9174
- continue;
9175
- }
9176
- const pluginArgs = cmdArgs.slice(1);
9177
- let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
9178
- if (cmdEntry.parameters) {
9179
- const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
9180
- if (schemaCheck.success) {
9181
- for (const [k, v] of Object.entries(schemaCheck.data)) {
9182
- if (!(k in pluginParams)) pluginParams[k] = v;
9183
- }
9184
- }
9185
- }
9186
- const pluginCtx = {
9187
- args: pluginArgs,
9188
- options: pluginParams,
9189
- cwd: process.cwd(),
9190
- page: session.page,
9191
- browser: session.context.browser(),
9192
- browserContext: session.context,
9193
- sessionId: session.id,
9194
- storage: getPluginStorage(cmdName),
9195
- output: { mode: "text", showTips: false, color: false, emoji: false },
9196
- error: (msg) => {
9197
- throw new Error(msg);
9198
- },
9199
- config: {},
9200
- site,
9201
- cliName: "xbrowser",
9202
- tips: new TipCollector2()
9203
- };
9204
- const start2 = Date.now();
9205
- try {
9206
- const loginGuard = await checkPluginLoginRequired({
9207
- site,
9208
- command: cmdEntry,
9209
- commandName: subCommand,
9210
- ctx: pluginCtx,
9211
- page: session?.page,
9212
- sessionName
9213
- });
9214
- if (!loginGuard.ok) {
9215
- const duration3 = Date.now() - start2;
9216
- const data2 = loginGuard.data ?? null;
9217
- recordArchive(session.id, sessionName, {
9218
- step: results.length,
9219
- command: `${cmdName} ${subCommand}`,
9220
- params: pluginParams,
9221
- result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
9222
- toolCalls: [],
9223
- duration: duration3,
9224
- timestamp: start2
9225
- });
9226
- results.push({
9227
- command: `${cmdName} ${subCommand}`,
9228
- raw: cmdStr,
9229
- success: false,
9230
- data: data2,
9231
- message: loginGuard.message,
9232
- tips: normalizeTips7(loginGuard.tips),
9233
- duration: duration3
9234
- });
9235
- if (type === "and") {
9236
- return {
9237
- success: false,
9238
- steps: results,
9239
- totalDuration: Date.now() - totalStart,
9240
- stoppedAt: results.length,
9241
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
9242
- };
9243
- }
9244
- continue;
9245
- }
9246
- const hooks = await loadHooks();
9247
- if (hooks.length > 0) {
9248
- await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
9249
- }
9250
- const raw = await cmdEntry.handler(pluginParams, pluginCtx);
9251
- const duration2 = Date.now() - start2;
9252
- let hookOutputs;
9253
- if (hooks.length > 0) {
9254
- const outputs = [];
9255
- for (const h of hooks) {
9256
- const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
9257
- if (output) outputs.push({ _hook: h.name, ...output });
9258
- }
9259
- if (outputs.length > 0) hookOutputs = outputs;
9260
- }
9261
- const data = raw?.data ?? raw;
9262
- recordArchive(session.id, sessionName, {
9263
- step: results.length,
9264
- command: `${cmdName} ${subCommand}`,
9265
- params: pluginParams,
9266
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9267
- toolCalls: [],
9268
- duration: duration2,
9269
- timestamp: start2
9270
- });
9271
- results.push({
9272
- command: `${cmdName} ${subCommand}`,
9273
- raw: cmdStr,
9274
- ...ok32(data),
9275
- duration: duration2,
9276
- ...hookOutputs ? { hookOutputs } : {}
9277
- });
9278
- if (type === "or") {
9279
- return {
9280
- success: true,
9281
- steps: results,
9282
- totalDuration: Date.now() - totalStart,
9283
- stoppedAt: results.length,
9284
- stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
9285
- };
9286
- }
9287
- } catch (err) {
9288
- const duration2 = Date.now() - start2;
9289
- const errorMessage = errMsg(err);
9290
- recordArchive(session.id, sessionName, {
9291
- step: results.length,
9292
- command: `${cmdName} ${subCommand}`,
9293
- params: pluginParams,
9294
- result: { success: false, data: null, message: errorMessage, tips: [] },
9295
- toolCalls: [],
9296
- duration: duration2,
9297
- timestamp: start2
9298
- });
9299
- results.push({
9300
- command: `${cmdName} ${subCommand}`,
9301
- raw: cmdStr,
9302
- ...fail17(errorMessage),
9303
- duration: duration2
9304
- });
9305
- if (type === "and") {
9306
- return {
9307
- success: false,
9308
- steps: results,
9309
- totalDuration: Date.now() - totalStart,
9310
- stoppedAt: results.length,
9311
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
9312
- };
9313
- }
9314
- }
9315
- continue;
9316
- }
9317
- const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
9318
- if (cmdName === "goto" && params.url) {
9319
- const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
9320
- if (!existing2) {
9321
- session = await createSession(sessionName, params.url, {
9322
- cdpEndpoint: options?.cdpEndpoint
9323
- });
9324
- }
9325
- }
9326
- const start = Date.now();
9327
- const result = await executeCommand(cmdName, params, sessionName, {
9328
- cdpEndpoint: options?.cdpEndpoint,
9329
- skipCleanup: true
9330
- // executeChain's finally handles cleanup
9331
- });
9332
- const duration = Date.now() - start;
9333
- const stepResult = {
9334
- command: cmdName,
9335
- raw: cmdStr,
9336
- success: result.success,
9337
- data: result.data,
9338
- message: result.message,
9339
- duration,
9340
- tips: result.tips,
9341
- ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
9342
- };
9343
- results.push(stepResult);
9344
- if (type === "and" && !result.success) {
9345
- return {
9346
- success: false,
9347
- steps: results,
9348
- totalDuration: Date.now() - totalStart,
9349
- stoppedAt: results.length,
9350
- stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
9351
- };
9352
- }
9353
- if (type === "or" && result.success) {
9354
- return {
9355
- success: true,
9356
- steps: results,
9357
- totalDuration: Date.now() - totalStart,
9358
- stoppedAt: results.length,
9359
- stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
9360
- };
9361
- }
9362
- }
9363
- }
9364
- const anyFailed = results.some((r) => !r.success);
9365
- return {
9366
- success: !anyFailed,
9367
- steps: results,
9368
- totalDuration: Date.now() - totalStart
9369
- };
9370
- } finally {
9371
- }
9469
+ async function executeChain2(input, options) {
9470
+ return executeChain(input, options, executeCommand);
9372
9471
  }
9373
9472
  function isChainInput(input) {
9374
9473
  return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
9375
9474
  }
9376
9475
 
9377
9476
  export {
9378
- parsePluginParams,
9379
9477
  createStubContext,
9380
9478
  registerCommand,
9381
9479
  getCommand,
@@ -9403,16 +9501,17 @@ export {
9403
9501
  attachDetectAntiBot,
9404
9502
  getWSServerFromCache,
9405
9503
  setWSServerCache,
9504
+ loadHooks,
9406
9505
  readJsonFile,
9407
9506
  PluginMetadataParser,
9408
9507
  ensurePluginDependencies,
9409
9508
  XBrowserPluginLoader,
9410
9509
  getPluginLoader,
9411
- checkPluginLoginRequired,
9412
- loadHooks,
9413
9510
  getPluginStorage,
9414
9511
  setWSServer,
9512
+ checkPluginLoginRequired,
9513
+ parsePluginParams,
9415
9514
  executeCommand,
9416
- executeChain,
9515
+ executeChain2 as executeChain,
9417
9516
  isChainInput
9418
9517
  };