@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
@@ -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();
@@ -74,6 +74,25 @@ function getRefTarget(sessionKey2, ref) {
74
74
  if (!session || !target) return null;
75
75
  return { screenHash: session.screenHash, target };
76
76
  }
77
+ function inheritStableRefs(key, rawTargets) {
78
+ const prev = sessions.get(key);
79
+ if (!prev || prev.targets.size === 0) {
80
+ return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
81
+ }
82
+ const bySelector = /* @__PURE__ */ new Map();
83
+ let maxId = 0;
84
+ for (const [ref, target] of prev.targets) {
85
+ bySelector.set(target.selector, ref);
86
+ const id = Number(ref.slice(1));
87
+ if (Number.isFinite(id) && id > maxId) maxId = id;
88
+ }
89
+ let next = maxId + 1;
90
+ return rawTargets.map((target) => {
91
+ const inherited = bySelector.get(target.selector);
92
+ if (inherited) return { ...target, ref: inherited };
93
+ return { ...target, ref: `e${next++}` };
94
+ });
95
+ }
77
96
 
78
97
  // src/runtime/agent-runtime.ts
79
98
  function sessionKey(sessionId) {
@@ -225,10 +244,7 @@ async function observePage(page, sessionId, options = {}) {
225
244
  { includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
226
245
  )
227
246
  ]);
228
- const targets = raw.targets.map((target, index) => ({
229
- ref: `e${index + 1}`,
230
- ...target
231
- }));
247
+ const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
232
248
  replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
233
249
  return {
234
250
  url: page.url(),
@@ -1637,9 +1653,12 @@ var visionTaskCommand = registerCommand({
1637
1653
  } catch {
1638
1654
  }
1639
1655
  }
1640
- const buffer = await page.screenshot({ type: "png" });
1656
+ const shotQuality = Math.max(30, Math.min(95, parseInt(process.env.XBROWSER_VLM_SHOT_QUALITY ?? "75", 10) || 75));
1657
+ const buffer = await page.screenshot({ type: "jpeg", quality: shotQuality });
1641
1658
  const b64 = buffer.toString("base64");
1642
- const { w, h } = pngDims(b64);
1659
+ const vp = typeof page.viewportSize === "function" ? page.viewportSize() : null;
1660
+ const w = vp?.width ?? pngDims(b64).w;
1661
+ const h = vp?.height ?? pngDims(b64).h;
1643
1662
  const obsText = [
1644
1663
  `\u4EFB\u52A1\uFF1A${p.task}`,
1645
1664
  `\u622A\u56FE\u5C3A\u5BF8\uFF1A${w}x${h}\uFF08\u5750\u6807\u539F\u70B9\uFF1A\u5DE6\u4E0A\u89D2\uFF09`,
@@ -1648,7 +1667,7 @@ var visionTaskCommand = registerCommand({
1648
1667
  ${history.slice(-6).join("\n")}` : "\u5C1A\u65E0\u52A8\u4F5C\u3002"
1649
1668
  ].join("\n");
1650
1669
  const reply = await vlmAskRetry(creds, [
1651
- { type: "image", source: { type: "base64", media_type: "image/png", data: b64 } },
1670
+ { type: "image", source: { type: "base64", media_type: shotQuality >= 100 ? "image/png" : "image/jpeg", data: b64 } },
1652
1671
  { type: "text", text: `${SYSTEM_PROMPT}
1653
1672
 
1654
1673
  ${obsText}` }
@@ -1817,14 +1836,14 @@ var preflightCommand = registerCommand({
1817
1836
  let pageUrl = null;
1818
1837
  try {
1819
1838
  const { fileURLToPath } = await import("url");
1820
- const { join: join9, dirname: dirname4 } = await import("path");
1821
- const { existsSync: existsSync7 } = await import("fs");
1839
+ const { join: join10, dirname: dirname4 } = await import("path");
1840
+ const { existsSync: existsSync8 } = await import("fs");
1822
1841
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1823
1842
  const candidates = [
1824
- join9(dirname4(here), "..", "assets", "preflight.html"),
1825
- join9(process.cwd(), "assets", "preflight.html")
1843
+ join10(dirname4(here), "..", "assets", "preflight.html"),
1844
+ join10(process.cwd(), "assets", "preflight.html")
1826
1845
  ];
1827
- pageUrl = candidates.find((c) => existsSync7(c)) || null;
1846
+ pageUrl = candidates.find((c) => existsSync8(c)) || null;
1828
1847
  } catch {
1829
1848
  }
1830
1849
  if (pageUrl) {
@@ -4816,6 +4835,8 @@ var networkCommand = registerCommand({
4816
4835
 
4817
4836
  // src/commands/ai-search-engines.ts
4818
4837
  import { z as z24 } from "zod";
4838
+
4839
+ // src/commands/ai-engine-configs.ts
4819
4840
  var ENGINE_CONFIGS = {
4820
4841
  deepseek: {
4821
4842
  key: "deepseek",
@@ -5068,6 +5089,8 @@ var ENGINE_CONFIGS = {
5068
5089
  sendButtonSelector: "button.send-btn"
5069
5090
  }
5070
5091
  };
5092
+
5093
+ // src/commands/ai-search-engines.ts
5071
5094
  var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
5072
5095
  var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
5073
5096
  function getEngineConfig(key) {
@@ -6069,12 +6092,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
6069
6092
  {"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
6070
6093
  {"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
6071
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"}
6072
6096
  {"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
6073
6097
 
6074
6098
  \u89C4\u5219\uFF1A
6075
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
6076
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
6077
- 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`;
6078
6102
  function extractDecision(raw) {
6079
6103
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
6080
6104
  const start = s.indexOf("{");
@@ -6125,6 +6149,7 @@ var taskCommand = registerCommand({
6125
6149
  let status = "max_steps";
6126
6150
  let summary = "";
6127
6151
  let lastError = "";
6152
+ let emptyReplies = 0;
6128
6153
  for (let step = 1; step <= p.maxSteps; step++) {
6129
6154
  if (Date.now() - started > p.timeout) {
6130
6155
  status = "blocked";
@@ -6144,7 +6169,7 @@ ${history.slice(-6).join("\n")}` : ""
6144
6169
  ].filter(Boolean).join("\n");
6145
6170
  let raw = "";
6146
6171
  try {
6147
- raw = await vlmAsk({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
6172
+ raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
6148
6173
 
6149
6174
  ---
6150
6175
 
@@ -6158,6 +6183,12 @@ ${userPayload}` }], 900);
6158
6183
  }
6159
6184
  const decision = extractDecision(raw);
6160
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
+ }
6161
6192
  status = "blocked";
6162
6193
  summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
6163
6194
  break;
@@ -6172,6 +6203,13 @@ ${userPayload}` }], 900);
6172
6203
  steps.push({ step, thought, action: "done", ok: true, screenHash });
6173
6204
  break;
6174
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
+ }
6175
6213
  if (action === "blocked") {
6176
6214
  status = "blocked";
6177
6215
  summary = value || thought || "LLM judged blocked";
@@ -6773,6 +6811,8 @@ var visualTagCommand = registerCommand({
6773
6811
  // src/commands/visual-tag-v2.ts
6774
6812
  import { z as z32 } from "zod";
6775
6813
  import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
6814
+
6815
+ // src/commands/visual-tag-v2-script.ts
6776
6816
  var SAFE_SET2 = "ahjkmnprtw3479".split("");
6777
6817
  var TAG_V2_SCRIPT = `
6778
6818
  (function() {
@@ -7115,7 +7155,9 @@ var TAG_V2_SCRIPT = `
7115
7155
  return JSON.stringify(window.__xbTagStats);
7116
7156
  })()
7117
7157
  `;
7118
- var visualTagV2Command = registerCommand({
7158
+
7159
+ // src/commands/visual-tag-v2.ts
7160
+ registerCommand({
7119
7161
  name: "visual-tag-v2",
7120
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",
7121
7163
  scope: "page",
@@ -7390,8 +7432,8 @@ import {
7390
7432
  Core
7391
7433
  } from "@dyyz1993/xcli-core";
7392
7434
  import { resolve as resolve2, basename, dirname as dirname3 } from "path";
7393
- import { existsSync as existsSync6, readdirSync } from "fs";
7394
- import { homedir as homedir4 } from "os";
7435
+ import { existsSync as existsSync7, readdirSync } from "fs";
7436
+ import { homedir as homedir5 } from "os";
7395
7437
 
7396
7438
  // src/plugin/metadata-parser.ts
7397
7439
  import { existsSync as existsSync4 } from "fs";
@@ -7687,6 +7729,75 @@ function patchLoginRequired() {
7687
7729
  });
7688
7730
  }
7689
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
+
7690
7801
  // src/plugin/loader.ts
7691
7802
  var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
7692
7803
  var XBrowserPluginLoader = class {
@@ -7697,6 +7808,7 @@ var XBrowserPluginLoader = class {
7697
7808
  dirSiteAliases = /* @__PURE__ */ new Map();
7698
7809
  constructor(options) {
7699
7810
  patchLoginRequired();
7811
+ globalThis.__xbrowserRecordMistake = recordMistake;
7700
7812
  this.options = options ?? {};
7701
7813
  const cwd = this.options.cwd || process.cwd();
7702
7814
  const coreConfig = {
@@ -7777,18 +7889,18 @@ var XBrowserPluginLoader = class {
7777
7889
  }
7778
7890
  async scanAndLoad() {
7779
7891
  const cwd = this.options.cwd || process.cwd();
7780
- const globalDir = this.options.globalDir || resolve2(homedir4(), ".xbrowser/plugins");
7892
+ const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
7781
7893
  ensurePluginDependencies(globalDir);
7782
7894
  const dirs = [
7783
7895
  resolve2(cwd, ".xcli/plugins"),
7784
7896
  resolve2(cwd, "../.xcli/plugins"),
7785
- this.options.userDir || resolve2(homedir4(), ".xcli/plugins"),
7897
+ this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
7786
7898
  globalDir
7787
7899
  ];
7788
7900
  const loaded = [];
7789
7901
  const seen = /* @__PURE__ */ new Set();
7790
7902
  for (const dir of dirs) {
7791
- if (!existsSync6(dir)) continue;
7903
+ if (!existsSync7(dir)) continue;
7792
7904
  const entries = readdirSync(dir, { withFileTypes: true });
7793
7905
  for (const entry of entries) {
7794
7906
  if (!entry.isDirectory()) continue;
@@ -7796,12 +7908,12 @@ var XBrowserPluginLoader = class {
7796
7908
  seen.add(entry.name);
7797
7909
  const pluginDir = resolve2(dir, entry.name);
7798
7910
  let indexPath = resolve2(pluginDir, "index.js");
7799
- if (!existsSync6(indexPath)) {
7911
+ if (!existsSync7(indexPath)) {
7800
7912
  indexPath = resolve2(pluginDir, "index.ts");
7801
7913
  }
7802
- if (!existsSync6(indexPath)) continue;
7914
+ if (!existsSync7(indexPath)) continue;
7803
7915
  try {
7804
- if (!existsSync6(resolve2(pluginDir, "package.json"))) {
7916
+ if (!existsSync7(resolve2(pluginDir, "package.json"))) {
7805
7917
  console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
7806
7918
  } else {
7807
7919
  const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
@@ -7827,166 +7939,110 @@ var XBrowserPluginLoader = class {
7827
7939
  }
7828
7940
  };
7829
7941
 
7830
- // src/fail-codes.ts
7831
- var FAIL_CODES = {
7832
- selectorNotFound: "RETRYABLE: selector-not-found",
7833
- pageNotReady: "RETRYABLE: page-not-ready",
7834
- elementGone: "RETRYABLE: element-gone",
7835
- inputNotRetained: "RETRYABLE: input-not-retained",
7836
- captcha: "HUMAN: captcha",
7837
- loginWall: "HUMAN: login-wall",
7838
- permissionDenied: "FATAL: permission-denied",
7839
- targetGone: "FATAL: target-gone",
7840
- unknown: "FATAL: unknown"
7841
- };
7842
- function classifyFailure(message) {
7843
- const msg = (message || "").toLowerCase();
7844
- const pick = (code) => ({
7845
- code,
7846
- level: code.split(":")[0],
7847
- message: message || code
7848
- });
7849
- if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
7850
- if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
7851
- if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
7852
- if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
7853
- return pick(FAIL_CODES.selectorNotFound);
7854
- if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
7855
- if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
7856
- if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
7857
- return pick(FAIL_CODES.targetGone);
7858
- return pick(FAIL_CODES.unknown);
7859
- }
7860
-
7861
- // src/executor.ts
7942
+ // src/executor/foundation.ts
7943
+ import { homedir as homedir6 } from "os";
7944
+ import { join as join8 } from "path";
7862
7945
  import {
7863
- ok as ok32,
7864
- fail as fail17,
7865
- isCommandResult,
7866
- CompositeStorage as CompositeStorage2,
7867
- TipCollector as TipCollector2,
7868
- normalizeTips as normalizeTips7,
7946
+ CompositeStorage,
7869
7947
  configureArchiveStore,
7870
7948
  appendCommandToArchive,
7871
- checkGuard,
7872
- unquote as unquote2
7949
+ fail as fail17,
7950
+ checkGuard
7873
7951
  } from "@dyyz1993/xcli-core";
7874
7952
 
7875
- // src/utils/positional-params.ts
7876
- import { unquote } from "@dyyz1993/xcli-core";
7877
- function getTypeName(field) {
7878
- return field?._def?.typeName;
7879
- }
7880
- function unwrapField(field) {
7881
- const typeName = getTypeName(field);
7882
- if (typeName === "ZodOptional" || typeName === "ZodDefault") {
7883
- const innerType = field?._def?.innerType;
7884
- return unwrapField(innerType);
7885
- }
7886
- return field;
7887
- }
7888
- function isOptionalNumber(field) {
7889
- const typeName = getTypeName(field);
7890
- 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
+ });
7891
7967
  }
7892
- function coerceValue(raw, field) {
7893
- const inner = unwrapField(field);
7894
- const optionalNum = isOptionalNumber(field);
7895
- const innerTypeName = getTypeName(inner);
7896
- if (innerTypeName === "ZodString") {
7897
- return { value: unquote(raw), skip: false };
7968
+ async function getPluginLoader() {
7969
+ if (!pluginLoader) {
7970
+ pluginLoader = new XBrowserPluginLoader();
7898
7971
  }
7899
- if (innerTypeName === "ZodNumber") {
7900
- const parsed = Number(raw);
7901
- if (isNaN(parsed)) {
7902
- if (optionalNum) return { value: void 0, skip: true };
7903
- return { value: raw, skip: false };
7904
- }
7905
- return { value: parsed, skip: false };
7972
+ if (!pluginsScanned) {
7973
+ await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
7974
+ pluginsScanned = true;
7906
7975
  }
7907
- if (innerTypeName === "ZodBoolean") {
7908
- if (raw === "true" || raw === "1") return { value: true, skip: false };
7909
- if (raw === "false" || raw === "0") return { value: false, skip: false };
7910
- 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"));
7911
7987
  }
7912
- return { value: unquote(raw), skip: false };
7988
+ return storageCache.get(pluginName);
7913
7989
  }
7914
- function mapPositionalValues(schema, positional, existing) {
7915
- const result = { ...existing };
7916
- if (!schema || typeof schema !== "object") return result;
7917
- const shape = schema.shape;
7918
- if (!shape || typeof shape !== "object") return result;
7919
- const keys = Object.keys(shape);
7920
- let pIdx = 0;
7921
- for (const key of keys) {
7922
- if (pIdx >= positional.length) break;
7923
- if (result[key] !== void 0) {
7924
- pIdx++;
7925
- continue;
7990
+ var archiveInitialized = false;
7991
+ function ensureArchiveInit() {
7992
+ if (!archiveInitialized) {
7993
+ try {
7994
+ configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
7995
+ } catch {
7926
7996
  }
7927
- const field = shape[key];
7928
- const raw = positional[pIdx];
7929
- const { value, skip } = coerceValue(raw, field);
7930
- if (skip) continue;
7931
- result[key] = value;
7932
- pIdx++;
7997
+ archiveInitialized = true;
7933
7998
  }
7934
- return result;
7935
7999
  }
7936
-
7937
- // src/utils/plugin-params.ts
7938
- function parsePluginParams(args, schema, base = {}) {
7939
- const params = { ...base };
7940
- const positionalValues = [];
7941
- for (let i = 0; i < args.length; i++) {
7942
- if (args[i] === "--" && args[i + 1]) {
7943
- try {
7944
- Object.assign(params, JSON.parse(args[i + 1]));
7945
- } catch {
7946
- }
7947
- break;
7948
- }
7949
- if (args[i].startsWith("--")) {
7950
- const key = args[i].slice(2);
7951
- const value = args[i + 1];
7952
- if (value && !value.startsWith("-")) {
7953
- if (value === "true") params[key] = true;
7954
- else if (value === "false") params[key] = false;
7955
- else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
7956
- else {
7957
- try {
7958
- const parsed = JSON.parse(value);
7959
- if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
7960
- params[key] = parsed;
7961
- } else {
7962
- params[key] = value;
7963
- }
7964
- } catch {
7965
- params[key] = value;
7966
- }
7967
- }
7968
- i++;
7969
- } else {
7970
- params[key] = true;
7971
- }
7972
- } else if (!args[i].startsWith("-")) {
7973
- positionalValues.push(args[i]);
7974
- }
8000
+ function recordArchive(sessionId, sessionName, entry) {
8001
+ if (!sessionId) return;
8002
+ try {
8003
+ ensureArchiveInit();
8004
+ appendCommandToArchive(sessionId, sessionName, entry);
8005
+ } catch {
7975
8006
  }
7976
- Object.assign(params, mapPositionalValues(schema, positionalValues, params));
7977
- const result = {};
7978
- for (const [k, v] of Object.entries(params)) {
7979
- const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
7980
- 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;
7981
8014
  }
7982
- return result;
7983
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";
7984
8040
 
7985
8041
  // src/utils/stub-context.ts
7986
- import { join as join7 } from "path";
7987
- import { homedir as homedir5 } from "os";
7988
- import { TipCollector, CompositeStorage } from "@dyyz1993/xcli-core";
7989
- 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");
7990
8046
  var NoopSiteInstance = class {
7991
8047
  name = "stub";
7992
8048
  url = "";
@@ -8009,7 +8065,7 @@ var NoopSiteInstance = class {
8009
8065
  async requireLogin() {
8010
8066
  }
8011
8067
  getStorage() {
8012
- return new CompositeStorage("stub", CONFIG_DIR, "xbrowser");
8068
+ return new CompositeStorage2("stub", CONFIG_DIR2, "xbrowser");
8013
8069
  }
8014
8070
  getAllCommands() {
8015
8071
  return [];
@@ -8033,7 +8089,7 @@ function createStubContext(pluginName) {
8033
8089
  args: [],
8034
8090
  options: {},
8035
8091
  cwd: process.cwd(),
8036
- storage: new CompositeStorage(pluginName, CONFIG_DIR, "xbrowser"),
8092
+ storage: new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"),
8037
8093
  output: { mode: "text", showTips: false, color: false, emoji: false },
8038
8094
  error: (msg) => {
8039
8095
  throw new Error(msg);
@@ -8045,140 +8101,6 @@ function createStubContext(pluginName) {
8045
8101
  };
8046
8102
  }
8047
8103
 
8048
- // src/utils/plugin-singleton.ts
8049
- var pluginLoader = null;
8050
- var pluginsScanned = false;
8051
- function silenceSchemaWarnings(fn) {
8052
- if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
8053
- const originalWarn = console.warn;
8054
- console.warn = (...args) => {
8055
- const msg = typeof args[0] === "string" ? args[0] : "";
8056
- if (msg.includes('has no "result" schema')) return;
8057
- originalWarn(...args);
8058
- };
8059
- return fn().finally(() => {
8060
- console.warn = originalWarn;
8061
- });
8062
- }
8063
- async function getPluginLoader() {
8064
- if (!pluginLoader) {
8065
- pluginLoader = new XBrowserPluginLoader();
8066
- }
8067
- if (!pluginsScanned) {
8068
- await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
8069
- pluginsScanned = true;
8070
- }
8071
- return pluginLoader;
8072
- }
8073
-
8074
- // src/plugin/login-guard.ts
8075
- async function checkPluginLoginRequired(options) {
8076
- const { site, command, commandName, ctx, page, sessionName } = options;
8077
- if (commandName === "login" || commandName === "logout") return { ok: true };
8078
- const loginConfig = site.config?.loginConfig;
8079
- const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
8080
- if (!requiresLogin) return { ok: true };
8081
- const pluginName = site.name || "plugin";
8082
- const siteConfig = site.config;
8083
- const configIsLogin = siteConfig?.isLogin;
8084
- if (configIsLogin) {
8085
- try {
8086
- const loggedIn = await configIsLogin(ctx);
8087
- if (loggedIn) return { ok: true };
8088
- return buildLoginRequired({
8089
- plugin: pluginName,
8090
- command: commandName,
8091
- reason: "config.isLogin returned false",
8092
- sessionName,
8093
- loginConfig
8094
- });
8095
- } catch {
8096
- }
8097
- }
8098
- if (typeof site.isLoggedIn === "function") {
8099
- try {
8100
- const loggedIn = await site.isLoggedIn(ctx);
8101
- if (loggedIn) return { ok: true };
8102
- return buildLoginRequired({
8103
- plugin: pluginName,
8104
- command: commandName,
8105
- reason: "plugin isLoggedIn returned false",
8106
- sessionName,
8107
- loginConfig
8108
- });
8109
- } catch {
8110
- }
8111
- }
8112
- if (page && loginConfig) {
8113
- const generic = await detectLoginFromPage(page, loginConfig);
8114
- if (generic === "logged-in") return { ok: true };
8115
- if (generic === "logged-out") {
8116
- return buildLoginRequired({
8117
- plugin: pluginName,
8118
- command: commandName,
8119
- reason: "generic loginConfig detected logged-out page",
8120
- sessionName,
8121
- loginConfig
8122
- });
8123
- }
8124
- }
8125
- return { ok: true };
8126
- }
8127
- function buildLoginRequired(options) {
8128
- const viewerUrl = buildViewerUrl(options.sessionName);
8129
- const loginUrl = options.loginConfig?.loginUrl;
8130
- const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
8131
- const tips = [
8132
- message,
8133
- ...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
8134
- ...loginUrl ? [`Login page: ${loginUrl}`] : [],
8135
- `After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
8136
- ];
8137
- return {
8138
- ok: false,
8139
- data: {
8140
- code: "LOGIN_REQUIRED",
8141
- plugin: options.plugin,
8142
- command: options.command,
8143
- reason: options.reason,
8144
- ...viewerUrl ? { viewerUrl } : {},
8145
- ...loginUrl ? { loginUrl } : {}
8146
- },
8147
- message,
8148
- tips
8149
- };
8150
- }
8151
- async function detectLoginFromPage(page, config) {
8152
- const url = page.url();
8153
- if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
8154
- const result = await page.evaluate((cfg) => {
8155
- const visible = (selector) => {
8156
- try {
8157
- const el = document.querySelector(selector);
8158
- if (!el) return false;
8159
- const rect = el.getBoundingClientRect();
8160
- const style = window.getComputedStyle(el);
8161
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
8162
- } catch {
8163
- return false;
8164
- }
8165
- };
8166
- if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
8167
- if (cfg.loginSelectors?.some(visible)) return "logged-out";
8168
- const bodyText = document.body?.innerText || "";
8169
- const keywords = cfg.loginKeywords || [];
8170
- if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
8171
- return "logged-out";
8172
- }
8173
- return "unknown";
8174
- }, {
8175
- loginSelectors: config.loginSelectors || [],
8176
- loginKeywords: config.loginKeywords || [],
8177
- loggedInSelectors: config.loggedInSelectors || []
8178
- });
8179
- return result;
8180
- }
8181
-
8182
8104
  // src/tips/dom-watcher.ts
8183
8105
  var DOM_WATCHER_SCRIPT = `
8184
8106
  (function() {
@@ -8679,80 +8601,523 @@ async function loadHooks() {
8679
8601
  return hooks;
8680
8602
  }
8681
8603
 
8682
- // src/executor.ts
8683
- import { homedir as homedir6 } from "os";
8684
- import { join as join8 } from "path";
8685
- function levenshtein(a, b) {
8686
- const m = a.length, n = b.length;
8687
- const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
8688
- for (let i = 0; i <= m; i++) dp[i][0] = i;
8689
- for (let j = 0; j <= n; j++) dp[0][j] = j;
8690
- for (let i = 1; i <= m; i++) {
8691
- for (let j = 1; j <= n; j++) {
8692
- 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]);
8693
- }
8694
- }
8695
- return dp[m][n];
8696
- }
8697
- var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
8698
- var snapshotHintShown = /* @__PURE__ */ new WeakSet();
8699
- var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
8700
- var storageCache = /* @__PURE__ */ new Map();
8701
- function getPluginStorage(pluginName) {
8702
- if (!storageCache.has(pluginName)) {
8703
- storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
8704
- }
8705
- 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);
8706
8633
  }
8707
- var archiveInitialized = false;
8708
- function ensureArchiveInit() {
8709
- 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) {
8710
8655
  try {
8711
- 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
+ });
8712
8665
  } catch {
8713
8666
  }
8714
- archiveInitialized = true;
8715
8667
  }
8716
- }
8717
- function recordArchive(sessionId, sessionName, entry) {
8718
- if (!sessionId) return;
8719
- try {
8720
- ensureArchiveInit();
8721
- appendCommandToArchive(sessionId, sessionName, entry);
8722
- } 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
+ }
8723
8681
  }
8724
- }
8725
- async function guardCheck(commandName) {
8726
- try {
8727
- const loader = await getPluginLoader();
8728
- const core = loader.getCore();
8729
- return checkGuard(core, commandName, process.env);
8730
- } catch {
8731
- 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
+ }
8732
8694
  }
8695
+ return { ok: true };
8733
8696
  }
8734
- function errorResult(message) {
8735
- return { ...fail17(message), duration: 0 };
8736
- }
8737
- function tipsToMessages(tips) {
8738
- if (!tips || tips.length === 0) return [];
8739
- return tips.map((t) => typeof t === "string" ? t : t.message);
8740
- }
8741
- var wsServer = null;
8742
- function setWSServer(server) {
8743
- wsServer = server;
8744
- }
8745
- function streamCommandEvent(sessionId, message) {
8746
- if (!wsServer || !wsServer.getRunning()) return;
8747
- wsServer.broadcastToSession(sessionId, {
8748
- type: "command",
8749
- data: message
8750
- });
8751
- }
8752
- async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
8753
- const guardResult = await guardCheck(commandName);
8754
- if (guardResult?.blocked) {
8755
- return errorResult(guardResult.message);
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);
8756
9121
  }
8757
9122
  const command = getCommand(commandName);
8758
9123
  if (!command) {
@@ -8796,8 +9161,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8796
9161
  if (knownPlugins.includes(commandName)) {
8797
9162
  hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
8798
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
+ });
8799
9171
  return errorResult(
8800
- `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`
9172
+ message
8801
9173
  );
8802
9174
  }
8803
9175
  const _target = params._target;
@@ -8812,7 +9184,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8812
9184
  }
8813
9185
  let targetPageOverride = null;
8814
9186
  if (_target && extraOpts?.cdpEndpoint) {
8815
- const { findTargetPage } = await import("./browser-4IYIHZ6R.js");
9187
+ const { findTargetPage } = await import("./browser-XD3IOU5I.js");
8816
9188
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8817
9189
  if (!targetPageOverride) {
8818
9190
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8830,7 +9202,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8830
9202
  }
8831
9203
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8832
9204
  const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
8833
- const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
9205
+ const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8834
9206
  const result = await forwardExec(
8835
9207
  commandName,
8836
9208
  params,
@@ -8892,7 +9264,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8892
9264
  config: {},
8893
9265
  site: new NoopSiteInstance(),
8894
9266
  cliName: "xbrowser",
8895
- tips: new TipCollector2()
9267
+ tips: new TipCollector3()
8896
9268
  };
8897
9269
  attachDetectAntiBot(ctx);
8898
9270
  if (_tabIndex !== void 0 && session?.context) {
@@ -8924,7 +9296,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8924
9296
  const cache = /* @__PURE__ */ new Map();
8925
9297
  const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
8926
9298
  if (resolved.tips.length > 0) {
8927
- refTips = normalizeTips7(resolved.tips);
9299
+ refTips = normalizeTips8(resolved.tips);
8928
9300
  params = resolved.params;
8929
9301
  }
8930
9302
  }
@@ -8992,11 +9364,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8992
9364
  }
8993
9365
  const merged = [
8994
9366
  ...raw.tips || [],
8995
- ...normalizeTips7(smartTips),
8996
- ...snapshotHint ? normalizeTips7([snapshotHint]) : [],
9367
+ ...normalizeTips8(smartTips),
9368
+ ...snapshotHint ? normalizeTips8([snapshotHint]) : [],
8997
9369
  ...refTips
8998
9370
  ];
8999
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
+ }
9000
9380
  const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
9001
9381
  recordArchive(session?.id, sessionName, {
9002
9382
  step: 0,
@@ -9008,7 +9388,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9008
9388
  timestamp: start
9009
9389
  });
9010
9390
  if (isSuccess) {
9011
- 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 } : {} };
9012
9392
  }
9013
9393
  const fc = classifyFailure(raw.message);
9014
9394
  return {
@@ -9021,7 +9401,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9021
9401
  ...hookOutputs ? { hookOutputs } : {}
9022
9402
  };
9023
9403
  }
9024
- const smartTipNormalized = normalizeTips7(smartTips);
9404
+ const smartTipNormalized = normalizeTips8(smartTips);
9025
9405
  recordArchive(session?.id, sessionName, {
9026
9406
  step: 0,
9027
9407
  command: commandName,
@@ -9031,11 +9411,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9031
9411
  duration,
9032
9412
  timestamp: start
9033
9413
  });
9034
- return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9414
+ return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9035
9415
  } catch (err) {
9036
9416
  const end = Date.now();
9037
9417
  const duration = end - start;
9038
9418
  const errorMessage = errMsg(err);
9419
+ recordMistake({
9420
+ category: classifyFailure(errorMessage).code,
9421
+ command: commandName,
9422
+ message: errorMessage,
9423
+ context: { sessionName, params }
9424
+ });
9039
9425
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
9040
9426
  try {
9041
9427
  const { attemptRecovery } = await import("./recovery-IMZUGWSS.js");
@@ -9076,287 +9462,18 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9076
9462
  duration,
9077
9463
  timestamp: start
9078
9464
  });
9079
- return { ...fail17(errorMessage), duration };
9465
+ return { ...fail19(errorMessage), duration };
9080
9466
  } finally {
9081
9467
  }
9082
9468
  }
9083
- async function executeChain(input, options) {
9084
- const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
9085
- const sessionName = options?.sessionName || "default";
9086
- const results = [];
9087
- const totalStart = Date.now();
9088
- let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
9089
- if (!session) {
9090
- const launchOpts = {};
9091
- if (options?.cdpEndpoint) {
9092
- launchOpts.cdpEndpoint = options.cdpEndpoint;
9093
- }
9094
- session = await createSession(sessionName, void 0, launchOpts);
9095
- saveSessionDiskMeta(sessionName, {
9096
- id: session.id,
9097
- name: sessionName,
9098
- url: session.page.url(),
9099
- createdAt: session.createdAt,
9100
- cdpEndpoint: session.cdpEndpoint
9101
- });
9102
- }
9103
- try {
9104
- for (const pipeline of pipelines) {
9105
- const { type, pipeline: commands } = pipeline;
9106
- for (const cmdStr of commands) {
9107
- if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
9108
- await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
9109
- }
9110
- const parts = splitCommand(cmdStr);
9111
- if (parts.length === 0) continue;
9112
- const cmdName = parts[0];
9113
- const cmdArgs = parts.slice(1);
9114
- const loader = await getPluginLoader();
9115
- const internalLoader = loader.getCore().loader;
9116
- const resolvedName = loader.resolveSiteName(cmdName);
9117
- const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
9118
- if (site) {
9119
- const subCommand = cmdArgs[0];
9120
- if (!subCommand) {
9121
- results.push({
9122
- command: cmdName,
9123
- raw: cmdStr,
9124
- ...fail17(`Plugin "${cmdName}" requires a sub-command`),
9125
- duration: 0
9126
- });
9127
- if (type === "and") {
9128
- return {
9129
- success: false,
9130
- steps: results,
9131
- totalDuration: Date.now() - totalStart,
9132
- stoppedAt: results.length,
9133
- stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
9134
- };
9135
- }
9136
- continue;
9137
- }
9138
- const cmdEntry = site.getCommand(subCommand);
9139
- if (!cmdEntry) {
9140
- results.push({
9141
- command: cmdName,
9142
- raw: cmdStr,
9143
- ...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
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): unknown sub-command "${subCommand}"`
9153
- };
9154
- }
9155
- continue;
9156
- }
9157
- const pluginArgs = cmdArgs.slice(1);
9158
- let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
9159
- if (cmdEntry.parameters) {
9160
- const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
9161
- if (schemaCheck.success) {
9162
- for (const [k, v] of Object.entries(schemaCheck.data)) {
9163
- if (!(k in pluginParams)) pluginParams[k] = v;
9164
- }
9165
- }
9166
- }
9167
- const pluginCtx = {
9168
- args: pluginArgs,
9169
- options: pluginParams,
9170
- cwd: process.cwd(),
9171
- page: session.page,
9172
- browser: session.context.browser(),
9173
- browserContext: session.context,
9174
- sessionId: session.id,
9175
- storage: getPluginStorage(cmdName),
9176
- output: { mode: "text", showTips: false, color: false, emoji: false },
9177
- error: (msg) => {
9178
- throw new Error(msg);
9179
- },
9180
- config: {},
9181
- site,
9182
- cliName: "xbrowser",
9183
- tips: new TipCollector2()
9184
- };
9185
- const start2 = Date.now();
9186
- try {
9187
- const loginGuard = await checkPluginLoginRequired({
9188
- site,
9189
- command: cmdEntry,
9190
- commandName: subCommand,
9191
- ctx: pluginCtx,
9192
- page: session?.page,
9193
- sessionName
9194
- });
9195
- if (!loginGuard.ok) {
9196
- const duration3 = Date.now() - start2;
9197
- const data2 = loginGuard.data ?? null;
9198
- recordArchive(session.id, sessionName, {
9199
- step: results.length,
9200
- command: `${cmdName} ${subCommand}`,
9201
- params: pluginParams,
9202
- result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
9203
- toolCalls: [],
9204
- duration: duration3,
9205
- timestamp: start2
9206
- });
9207
- results.push({
9208
- command: `${cmdName} ${subCommand}`,
9209
- raw: cmdStr,
9210
- success: false,
9211
- data: data2,
9212
- message: loginGuard.message,
9213
- tips: normalizeTips7(loginGuard.tips),
9214
- duration: duration3
9215
- });
9216
- if (type === "and") {
9217
- return {
9218
- success: false,
9219
- steps: results,
9220
- totalDuration: Date.now() - totalStart,
9221
- stoppedAt: results.length,
9222
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
9223
- };
9224
- }
9225
- continue;
9226
- }
9227
- const hooks = await loadHooks();
9228
- if (hooks.length > 0) {
9229
- await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
9230
- }
9231
- const raw = await cmdEntry.handler(pluginParams, pluginCtx);
9232
- const duration2 = Date.now() - start2;
9233
- let hookOutputs;
9234
- if (hooks.length > 0) {
9235
- const outputs = [];
9236
- for (const h of hooks) {
9237
- const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
9238
- if (output) outputs.push({ _hook: h.name, ...output });
9239
- }
9240
- if (outputs.length > 0) hookOutputs = outputs;
9241
- }
9242
- const data = raw?.data ?? raw;
9243
- recordArchive(session.id, sessionName, {
9244
- step: results.length,
9245
- command: `${cmdName} ${subCommand}`,
9246
- params: pluginParams,
9247
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9248
- toolCalls: [],
9249
- duration: duration2,
9250
- timestamp: start2
9251
- });
9252
- results.push({
9253
- command: `${cmdName} ${subCommand}`,
9254
- raw: cmdStr,
9255
- ...ok32(data),
9256
- duration: duration2,
9257
- ...hookOutputs ? { hookOutputs } : {}
9258
- });
9259
- if (type === "or") {
9260
- return {
9261
- success: true,
9262
- steps: results,
9263
- totalDuration: Date.now() - totalStart,
9264
- stoppedAt: results.length,
9265
- stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
9266
- };
9267
- }
9268
- } catch (err) {
9269
- const duration2 = Date.now() - start2;
9270
- const errorMessage = errMsg(err);
9271
- recordArchive(session.id, sessionName, {
9272
- step: results.length,
9273
- command: `${cmdName} ${subCommand}`,
9274
- params: pluginParams,
9275
- result: { success: false, data: null, message: errorMessage, tips: [] },
9276
- toolCalls: [],
9277
- duration: duration2,
9278
- timestamp: start2
9279
- });
9280
- results.push({
9281
- command: `${cmdName} ${subCommand}`,
9282
- raw: cmdStr,
9283
- ...fail17(errorMessage),
9284
- duration: duration2
9285
- });
9286
- if (type === "and") {
9287
- return {
9288
- success: false,
9289
- steps: results,
9290
- totalDuration: Date.now() - totalStart,
9291
- stoppedAt: results.length,
9292
- stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
9293
- };
9294
- }
9295
- }
9296
- continue;
9297
- }
9298
- const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
9299
- if (cmdName === "goto" && params.url) {
9300
- const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
9301
- if (!existing2) {
9302
- session = await createSession(sessionName, params.url, {
9303
- cdpEndpoint: options?.cdpEndpoint
9304
- });
9305
- }
9306
- }
9307
- const start = Date.now();
9308
- const result = await executeCommand(cmdName, params, sessionName, {
9309
- cdpEndpoint: options?.cdpEndpoint,
9310
- skipCleanup: true
9311
- // executeChain's finally handles cleanup
9312
- });
9313
- const duration = Date.now() - start;
9314
- const stepResult = {
9315
- command: cmdName,
9316
- raw: cmdStr,
9317
- success: result.success,
9318
- data: result.data,
9319
- message: result.message,
9320
- duration,
9321
- tips: result.tips,
9322
- ...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
9323
- };
9324
- results.push(stepResult);
9325
- if (type === "and" && !result.success) {
9326
- return {
9327
- success: false,
9328
- steps: results,
9329
- totalDuration: Date.now() - totalStart,
9330
- stoppedAt: results.length,
9331
- stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
9332
- };
9333
- }
9334
- if (type === "or" && result.success) {
9335
- return {
9336
- success: true,
9337
- steps: results,
9338
- totalDuration: Date.now() - totalStart,
9339
- stoppedAt: results.length,
9340
- stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
9341
- };
9342
- }
9343
- }
9344
- }
9345
- const anyFailed = results.some((r) => !r.success);
9346
- return {
9347
- success: !anyFailed,
9348
- steps: results,
9349
- totalDuration: Date.now() - totalStart
9350
- };
9351
- } finally {
9352
- }
9469
+ async function executeChain2(input, options) {
9470
+ return executeChain(input, options, executeCommand);
9353
9471
  }
9354
9472
  function isChainInput(input) {
9355
9473
  return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
9356
9474
  }
9357
9475
 
9358
9476
  export {
9359
- parsePluginParams,
9360
9477
  createStubContext,
9361
9478
  registerCommand,
9362
9479
  getCommand,
@@ -9384,16 +9501,17 @@ export {
9384
9501
  attachDetectAntiBot,
9385
9502
  getWSServerFromCache,
9386
9503
  setWSServerCache,
9504
+ loadHooks,
9387
9505
  readJsonFile,
9388
9506
  PluginMetadataParser,
9389
9507
  ensurePluginDependencies,
9390
9508
  XBrowserPluginLoader,
9391
9509
  getPluginLoader,
9392
- checkPluginLoginRequired,
9393
- loadHooks,
9394
9510
  getPluginStorage,
9395
9511
  setWSServer,
9512
+ checkPluginLoginRequired,
9513
+ parsePluginParams,
9396
9514
  executeCommand,
9397
- executeChain,
9515
+ executeChain2 as executeChain,
9398
9516
  isChainInput
9399
9517
  };