@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.
- package/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
- package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
- package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
- package/dist/{chunk-IDXOIXQR.js → chunk-GDKKVT2P.js} +773 -655
- package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
- package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
- package/dist/{chunk-YITK42HZ.js → chunk-SCYBNSOG.js} +1596 -1478
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
- package/dist/cli.js +3398 -3357
- package/dist/daemon-main.js +749 -700
- package/dist/index.d.ts +362 -474
- package/dist/index.js +5730 -5689
- package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
- package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
- package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
- package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
- package/dist/{server-YKMRFDEM.js → server-LNZTDAKT.js} +4 -4
- package/dist/{server-WDDGIV3C.js → server-ZTI2K5YJ.js} +7 -7
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
- package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
- package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
- package/package.json +6 -3
|
@@ -20,171 +20,25 @@ import {
|
|
|
20
20
|
resolveLaunchOpts,
|
|
21
21
|
saveSessionDiskMeta,
|
|
22
22
|
setActivePage
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-LFSLNHW5.js";
|
|
24
24
|
import {
|
|
25
25
|
rand,
|
|
26
26
|
sleep,
|
|
27
27
|
wheelDelta
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-SMYSNO4M.js";
|
|
29
29
|
import {
|
|
30
30
|
errMsg
|
|
31
31
|
} from "./chunk-GDKLH7ZY.js";
|
|
32
32
|
|
|
33
|
-
// src/fail-codes.ts
|
|
34
|
-
var FAIL_CODES = {
|
|
35
|
-
selectorNotFound: "RETRYABLE: selector-not-found",
|
|
36
|
-
pageNotReady: "RETRYABLE: page-not-ready",
|
|
37
|
-
elementGone: "RETRYABLE: element-gone",
|
|
38
|
-
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
39
|
-
captcha: "HUMAN: captcha",
|
|
40
|
-
loginWall: "HUMAN: login-wall",
|
|
41
|
-
permissionDenied: "FATAL: permission-denied",
|
|
42
|
-
targetGone: "FATAL: target-gone",
|
|
43
|
-
unknown: "FATAL: unknown"
|
|
44
|
-
};
|
|
45
|
-
function classifyFailure(message) {
|
|
46
|
-
const msg = (message || "").toLowerCase();
|
|
47
|
-
const pick = (code) => ({
|
|
48
|
-
code,
|
|
49
|
-
level: code.split(":")[0],
|
|
50
|
-
message: message || code
|
|
51
|
-
});
|
|
52
|
-
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
53
|
-
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
54
|
-
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
55
|
-
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
56
|
-
return pick(FAIL_CODES.selectorNotFound);
|
|
57
|
-
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
58
|
-
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
59
|
-
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
60
|
-
return pick(FAIL_CODES.targetGone);
|
|
61
|
-
return pick(FAIL_CODES.unknown);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
33
|
// src/executor.ts
|
|
65
34
|
import {
|
|
66
|
-
ok as
|
|
67
|
-
fail as
|
|
35
|
+
ok as ok33,
|
|
36
|
+
fail as fail19,
|
|
68
37
|
isCommandResult,
|
|
69
|
-
|
|
70
|
-
TipCollector as
|
|
71
|
-
normalizeTips as normalizeTips7,
|
|
72
|
-
configureArchiveStore,
|
|
73
|
-
appendCommandToArchive,
|
|
74
|
-
checkGuard,
|
|
75
|
-
unquote as unquote2
|
|
38
|
+
normalizeTips as normalizeTips8,
|
|
39
|
+
TipCollector as TipCollector3
|
|
76
40
|
} from "@dyyz1993/xcli-core";
|
|
77
41
|
|
|
78
|
-
// src/utils/positional-params.ts
|
|
79
|
-
import { unquote } from "@dyyz1993/xcli-core";
|
|
80
|
-
function getTypeName(field) {
|
|
81
|
-
return field?._def?.typeName;
|
|
82
|
-
}
|
|
83
|
-
function unwrapField(field) {
|
|
84
|
-
const typeName = getTypeName(field);
|
|
85
|
-
if (typeName === "ZodOptional" || typeName === "ZodDefault") {
|
|
86
|
-
const innerType = field?._def?.innerType;
|
|
87
|
-
return unwrapField(innerType);
|
|
88
|
-
}
|
|
89
|
-
return field;
|
|
90
|
-
}
|
|
91
|
-
function isOptionalNumber(field) {
|
|
92
|
-
const typeName = getTypeName(field);
|
|
93
|
-
return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
|
|
94
|
-
}
|
|
95
|
-
function coerceValue(raw, field) {
|
|
96
|
-
const inner = unwrapField(field);
|
|
97
|
-
const optionalNum = isOptionalNumber(field);
|
|
98
|
-
const innerTypeName = getTypeName(inner);
|
|
99
|
-
if (innerTypeName === "ZodString") {
|
|
100
|
-
return { value: unquote(raw), skip: false };
|
|
101
|
-
}
|
|
102
|
-
if (innerTypeName === "ZodNumber") {
|
|
103
|
-
const parsed = Number(raw);
|
|
104
|
-
if (isNaN(parsed)) {
|
|
105
|
-
if (optionalNum) return { value: void 0, skip: true };
|
|
106
|
-
return { value: raw, skip: false };
|
|
107
|
-
}
|
|
108
|
-
return { value: parsed, skip: false };
|
|
109
|
-
}
|
|
110
|
-
if (innerTypeName === "ZodBoolean") {
|
|
111
|
-
if (raw === "true" || raw === "1") return { value: true, skip: false };
|
|
112
|
-
if (raw === "false" || raw === "0") return { value: false, skip: false };
|
|
113
|
-
return { value: raw, skip: false };
|
|
114
|
-
}
|
|
115
|
-
return { value: unquote(raw), skip: false };
|
|
116
|
-
}
|
|
117
|
-
function mapPositionalValues(schema, positional, existing) {
|
|
118
|
-
const result = { ...existing };
|
|
119
|
-
if (!schema || typeof schema !== "object") return result;
|
|
120
|
-
const shape = schema.shape;
|
|
121
|
-
if (!shape || typeof shape !== "object") return result;
|
|
122
|
-
const keys = Object.keys(shape);
|
|
123
|
-
let pIdx = 0;
|
|
124
|
-
for (const key of keys) {
|
|
125
|
-
if (pIdx >= positional.length) break;
|
|
126
|
-
if (result[key] !== void 0) {
|
|
127
|
-
pIdx++;
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
const field = shape[key];
|
|
131
|
-
const raw = positional[pIdx];
|
|
132
|
-
const { value, skip } = coerceValue(raw, field);
|
|
133
|
-
if (skip) continue;
|
|
134
|
-
result[key] = value;
|
|
135
|
-
pIdx++;
|
|
136
|
-
}
|
|
137
|
-
return result;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// src/utils/plugin-params.ts
|
|
141
|
-
function parsePluginParams(args, schema, base = {}) {
|
|
142
|
-
const params = { ...base };
|
|
143
|
-
const positionalValues = [];
|
|
144
|
-
for (let i = 0; i < args.length; i++) {
|
|
145
|
-
if (args[i] === "--" && args[i + 1]) {
|
|
146
|
-
try {
|
|
147
|
-
Object.assign(params, JSON.parse(args[i + 1]));
|
|
148
|
-
} catch {
|
|
149
|
-
}
|
|
150
|
-
break;
|
|
151
|
-
}
|
|
152
|
-
if (args[i].startsWith("--")) {
|
|
153
|
-
const key = args[i].slice(2);
|
|
154
|
-
const value = args[i + 1];
|
|
155
|
-
if (value && !value.startsWith("-")) {
|
|
156
|
-
if (value === "true") params[key] = true;
|
|
157
|
-
else if (value === "false") params[key] = false;
|
|
158
|
-
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
159
|
-
else {
|
|
160
|
-
try {
|
|
161
|
-
const parsed = JSON.parse(value);
|
|
162
|
-
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
163
|
-
params[key] = parsed;
|
|
164
|
-
} else {
|
|
165
|
-
params[key] = value;
|
|
166
|
-
}
|
|
167
|
-
} catch {
|
|
168
|
-
params[key] = value;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
i++;
|
|
172
|
-
} else {
|
|
173
|
-
params[key] = true;
|
|
174
|
-
}
|
|
175
|
-
} else if (!args[i].startsWith("-")) {
|
|
176
|
-
positionalValues.push(args[i]);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
180
|
-
const result = {};
|
|
181
|
-
for (const [k, v] of Object.entries(params)) {
|
|
182
|
-
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
183
|
-
result[camelKey] = v;
|
|
184
|
-
}
|
|
185
|
-
return result;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
42
|
// src/utils/stub-context.ts
|
|
189
43
|
import { join } from "path";
|
|
190
44
|
import { homedir } from "os";
|
|
@@ -1285,9 +1139,12 @@ var visionTaskCommand = registerCommand({
|
|
|
1285
1139
|
} catch {
|
|
1286
1140
|
}
|
|
1287
1141
|
}
|
|
1288
|
-
const
|
|
1142
|
+
const shotQuality = Math.max(30, Math.min(95, parseInt(process.env.XBROWSER_VLM_SHOT_QUALITY ?? "75", 10) || 75));
|
|
1143
|
+
const buffer = await page.screenshot({ type: "jpeg", quality: shotQuality });
|
|
1289
1144
|
const b64 = buffer.toString("base64");
|
|
1290
|
-
const
|
|
1145
|
+
const vp = typeof page.viewportSize === "function" ? page.viewportSize() : null;
|
|
1146
|
+
const w = vp?.width ?? pngDims(b64).w;
|
|
1147
|
+
const h = vp?.height ?? pngDims(b64).h;
|
|
1291
1148
|
const obsText = [
|
|
1292
1149
|
`\u4EFB\u52A1\uFF1A${p.task}`,
|
|
1293
1150
|
`\u622A\u56FE\u5C3A\u5BF8\uFF1A${w}x${h}\uFF08\u5750\u6807\u539F\u70B9\uFF1A\u5DE6\u4E0A\u89D2\uFF09`,
|
|
@@ -1296,7 +1153,7 @@ var visionTaskCommand = registerCommand({
|
|
|
1296
1153
|
${history.slice(-6).join("\n")}` : "\u5C1A\u65E0\u52A8\u4F5C\u3002"
|
|
1297
1154
|
].join("\n");
|
|
1298
1155
|
const reply = await vlmAskRetry(creds, [
|
|
1299
|
-
{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } },
|
|
1156
|
+
{ type: "image", source: { type: "base64", media_type: shotQuality >= 100 ? "image/png" : "image/jpeg", data: b64 } },
|
|
1300
1157
|
{ type: "text", text: `${SYSTEM_PROMPT}
|
|
1301
1158
|
|
|
1302
1159
|
${obsText}` }
|
|
@@ -1465,14 +1322,14 @@ var preflightCommand = registerCommand({
|
|
|
1465
1322
|
let pageUrl = null;
|
|
1466
1323
|
try {
|
|
1467
1324
|
const { fileURLToPath } = await import("url");
|
|
1468
|
-
const { join:
|
|
1469
|
-
const { existsSync:
|
|
1325
|
+
const { join: join10, dirname: dirname4 } = await import("path");
|
|
1326
|
+
const { existsSync: existsSync8 } = await import("fs");
|
|
1470
1327
|
const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
|
|
1471
1328
|
const candidates = [
|
|
1472
|
-
|
|
1473
|
-
|
|
1329
|
+
join10(dirname4(here), "..", "assets", "preflight.html"),
|
|
1330
|
+
join10(process.cwd(), "assets", "preflight.html")
|
|
1474
1331
|
];
|
|
1475
|
-
pageUrl = candidates.find((c) =>
|
|
1332
|
+
pageUrl = candidates.find((c) => existsSync8(c)) || null;
|
|
1476
1333
|
} catch {
|
|
1477
1334
|
}
|
|
1478
1335
|
if (pageUrl) {
|
|
@@ -4464,6 +4321,8 @@ var networkCommand = registerCommand({
|
|
|
4464
4321
|
|
|
4465
4322
|
// src/commands/ai-search-engines.ts
|
|
4466
4323
|
import { z as z24 } from "zod";
|
|
4324
|
+
|
|
4325
|
+
// src/commands/ai-engine-configs.ts
|
|
4467
4326
|
var ENGINE_CONFIGS = {
|
|
4468
4327
|
deepseek: {
|
|
4469
4328
|
key: "deepseek",
|
|
@@ -4716,6 +4575,8 @@ var ENGINE_CONFIGS = {
|
|
|
4716
4575
|
sendButtonSelector: "button.send-btn"
|
|
4717
4576
|
}
|
|
4718
4577
|
};
|
|
4578
|
+
|
|
4579
|
+
// src/commands/ai-search-engines.ts
|
|
4719
4580
|
var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
|
|
4720
4581
|
var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
|
|
4721
4582
|
|
|
@@ -4740,6 +4601,25 @@ function getRefTarget(sessionKey2, ref) {
|
|
|
4740
4601
|
if (!session || !target) return null;
|
|
4741
4602
|
return { screenHash: session.screenHash, target };
|
|
4742
4603
|
}
|
|
4604
|
+
function inheritStableRefs(key, rawTargets) {
|
|
4605
|
+
const prev = sessions.get(key);
|
|
4606
|
+
if (!prev || prev.targets.size === 0) {
|
|
4607
|
+
return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
|
|
4608
|
+
}
|
|
4609
|
+
const bySelector = /* @__PURE__ */ new Map();
|
|
4610
|
+
let maxId = 0;
|
|
4611
|
+
for (const [ref, target] of prev.targets) {
|
|
4612
|
+
bySelector.set(target.selector, ref);
|
|
4613
|
+
const id = Number(ref.slice(1));
|
|
4614
|
+
if (Number.isFinite(id) && id > maxId) maxId = id;
|
|
4615
|
+
}
|
|
4616
|
+
let next = maxId + 1;
|
|
4617
|
+
return rawTargets.map((target) => {
|
|
4618
|
+
const inherited = bySelector.get(target.selector);
|
|
4619
|
+
if (inherited) return { ...target, ref: inherited };
|
|
4620
|
+
return { ...target, ref: `e${next++}` };
|
|
4621
|
+
});
|
|
4622
|
+
}
|
|
4743
4623
|
|
|
4744
4624
|
// src/utils/resolve-selector.ts
|
|
4745
4625
|
function buildElementSelector(el) {
|
|
@@ -5364,10 +5244,7 @@ async function observePage(page, sessionId, options = {}) {
|
|
|
5364
5244
|
{ includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
|
|
5365
5245
|
)
|
|
5366
5246
|
]);
|
|
5367
|
-
const targets =
|
|
5368
|
-
ref: `e${index + 1}`,
|
|
5369
|
-
...target
|
|
5370
|
-
}));
|
|
5247
|
+
const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
|
|
5371
5248
|
replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
|
|
5372
5249
|
return {
|
|
5373
5250
|
url: page.url(),
|
|
@@ -5871,12 +5748,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
|
|
|
5871
5748
|
{"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5872
5749
|
{"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5873
5750
|
{"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5751
|
+
{"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
|
|
5874
5752
|
{"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
|
|
5875
5753
|
|
|
5876
5754
|
\u89C4\u5219\uFF1A
|
|
5877
5755
|
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
|
|
5878
5756
|
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
|
|
5879
|
-
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`;
|
|
5757
|
+
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`;
|
|
5880
5758
|
function extractDecision(raw) {
|
|
5881
5759
|
let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
5882
5760
|
const start = s.indexOf("{");
|
|
@@ -5927,6 +5805,7 @@ var taskCommand = registerCommand({
|
|
|
5927
5805
|
let status = "max_steps";
|
|
5928
5806
|
let summary = "";
|
|
5929
5807
|
let lastError = "";
|
|
5808
|
+
let emptyReplies = 0;
|
|
5930
5809
|
for (let step = 1; step <= p.maxSteps; step++) {
|
|
5931
5810
|
if (Date.now() - started > p.timeout) {
|
|
5932
5811
|
status = "blocked";
|
|
@@ -5946,7 +5825,7 @@ ${history.slice(-6).join("\n")}` : ""
|
|
|
5946
5825
|
].filter(Boolean).join("\n");
|
|
5947
5826
|
let raw = "";
|
|
5948
5827
|
try {
|
|
5949
|
-
raw = await
|
|
5828
|
+
raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
|
|
5950
5829
|
|
|
5951
5830
|
---
|
|
5952
5831
|
|
|
@@ -5960,6 +5839,12 @@ ${userPayload}` }], 900);
|
|
|
5960
5839
|
}
|
|
5961
5840
|
const decision = extractDecision(raw);
|
|
5962
5841
|
if (!decision || typeof decision.action !== "string") {
|
|
5842
|
+
if (!raw.trim() && emptyReplies < 2) {
|
|
5843
|
+
emptyReplies++;
|
|
5844
|
+
steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
|
|
5845
|
+
history.push(`step${step}: (empty reply, retrying)`);
|
|
5846
|
+
continue;
|
|
5847
|
+
}
|
|
5963
5848
|
status = "blocked";
|
|
5964
5849
|
summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
|
|
5965
5850
|
break;
|
|
@@ -5974,6 +5859,13 @@ ${userPayload}` }], 900);
|
|
|
5974
5859
|
steps.push({ step, thought, action: "done", ok: true, screenHash });
|
|
5975
5860
|
break;
|
|
5976
5861
|
}
|
|
5862
|
+
if (action === "back") {
|
|
5863
|
+
await ctx.page?.goBack?.().catch?.(() => {
|
|
5864
|
+
});
|
|
5865
|
+
steps.push({ step, thought, action: "back", ok: true, screenHash });
|
|
5866
|
+
history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
|
|
5867
|
+
continue;
|
|
5868
|
+
}
|
|
5977
5869
|
if (action === "blocked") {
|
|
5978
5870
|
status = "blocked";
|
|
5979
5871
|
summary = value || thought || "LLM judged blocked";
|
|
@@ -6714,6 +6606,8 @@ var visualTagCommand = registerCommand({
|
|
|
6714
6606
|
// src/commands/visual-tag-v2.ts
|
|
6715
6607
|
import { z as z32 } from "zod";
|
|
6716
6608
|
import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
|
|
6609
|
+
|
|
6610
|
+
// src/commands/visual-tag-v2-script.ts
|
|
6717
6611
|
var SAFE_SET2 = "ahjkmnprtw3479".split("");
|
|
6718
6612
|
var TAG_V2_SCRIPT = `
|
|
6719
6613
|
(function() {
|
|
@@ -7056,7 +6950,9 @@ var TAG_V2_SCRIPT = `
|
|
|
7056
6950
|
return JSON.stringify(window.__xbTagStats);
|
|
7057
6951
|
})()
|
|
7058
6952
|
`;
|
|
7059
|
-
|
|
6953
|
+
|
|
6954
|
+
// src/commands/visual-tag-v2.ts
|
|
6955
|
+
registerCommand({
|
|
7060
6956
|
name: "visual-tag-v2",
|
|
7061
6957
|
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",
|
|
7062
6958
|
scope: "page",
|
|
@@ -7289,1085 +7185,1606 @@ function attachDetectAntiBot(ctx) {
|
|
|
7289
7185
|
};
|
|
7290
7186
|
}
|
|
7291
7187
|
|
|
7292
|
-
// src/
|
|
7293
|
-
|
|
7294
|
-
|
|
7295
|
-
|
|
7296
|
-
|
|
7297
|
-
import { existsSync as existsSync6, readdirSync } from "fs";
|
|
7298
|
-
import { homedir as homedir5 } from "os";
|
|
7299
|
-
|
|
7300
|
-
// src/plugin/metadata-parser.ts
|
|
7301
|
-
import { existsSync as existsSync4 } from "fs";
|
|
7302
|
-
import { resolve } from "path";
|
|
7188
|
+
// src/tips/dom-watcher.ts
|
|
7189
|
+
var DOM_WATCHER_SCRIPT = `
|
|
7190
|
+
(function() {
|
|
7191
|
+
if (window.__xbrowserDomWatcher) return;
|
|
7192
|
+
window.__xbrowserDomWatcher = true;
|
|
7303
7193
|
|
|
7304
|
-
|
|
7305
|
-
import { readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
7306
|
-
function readJsonFile(filePath, defaultValue) {
|
|
7307
|
-
try {
|
|
7308
|
-
const content = readFileSync5(filePath, "utf-8");
|
|
7309
|
-
return JSON.parse(content);
|
|
7310
|
-
} catch {
|
|
7311
|
-
return defaultValue;
|
|
7312
|
-
}
|
|
7313
|
-
}
|
|
7194
|
+
window.__xbrowserDetectedElements = [];
|
|
7314
7195
|
|
|
7315
|
-
|
|
7316
|
-
|
|
7317
|
-
|
|
7318
|
-
|
|
7319
|
-
const packageJsonPath = resolve(pluginPath, "package.json");
|
|
7320
|
-
if (!existsSync4(packageJsonPath)) {
|
|
7321
|
-
return null;
|
|
7322
|
-
}
|
|
7323
|
-
const packageJson = readJsonFile(packageJsonPath, null);
|
|
7324
|
-
if (!packageJson) return null;
|
|
7325
|
-
if (!packageJson.xbrowser) {
|
|
7326
|
-
return null;
|
|
7196
|
+
function getSelector(el) {
|
|
7197
|
+
if (el.id) return '#' + CSS.escape(el.id);
|
|
7198
|
+
if (el.getAttribute('aria-label')) {
|
|
7199
|
+
return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
|
|
7327
7200
|
}
|
|
7328
|
-
const
|
|
7329
|
-
|
|
7330
|
-
|
|
7331
|
-
|
|
7332
|
-
|
|
7333
|
-
version: xbrowser.version || packageJson.version || "1.0.0",
|
|
7334
|
-
author: xbrowser.author || this.extractAuthor(packageJson.author),
|
|
7335
|
-
homepage: xbrowser.homepage || packageJson.homepage,
|
|
7336
|
-
commands: xbrowser.commands,
|
|
7337
|
-
sites: xbrowser.sites,
|
|
7338
|
-
tags: xbrowser.tags,
|
|
7339
|
-
screenshot: xbrowser.screenshot,
|
|
7340
|
-
license: xbrowser.license || packageJson.license
|
|
7341
|
-
};
|
|
7342
|
-
return metadata;
|
|
7201
|
+
const cls = el.className && typeof el.className === 'string'
|
|
7202
|
+
? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
|
|
7203
|
+
: '';
|
|
7204
|
+
if (cls) return el.tagName.toLowerCase() + '.' + cls;
|
|
7205
|
+
return el.tagName.toLowerCase();
|
|
7343
7206
|
}
|
|
7344
|
-
|
|
7345
|
-
|
|
7346
|
-
|
|
7207
|
+
|
|
7208
|
+
function isPopupLike(el) {
|
|
7209
|
+
const tag = el.tagName?.toLowerCase();
|
|
7210
|
+
if (tag === 'dialog') return true;
|
|
7211
|
+
if (tag === 'body' || tag === 'html') return false;
|
|
7212
|
+
|
|
7213
|
+
const role = el.getAttribute('role');
|
|
7214
|
+
if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
|
|
7215
|
+
|
|
7216
|
+
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7217
|
+
const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
|
|
7218
|
+
if (popupPatterns.test(cls)) return true;
|
|
7219
|
+
|
|
7220
|
+
const style = window.getComputedStyle(el);
|
|
7221
|
+
if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
|
|
7222
|
+
const rect = el.getBoundingClientRect();
|
|
7223
|
+
if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
|
|
7347
7224
|
}
|
|
7348
|
-
|
|
7349
|
-
|
|
7350
|
-
return this.XBROWSER_KEYWORDS.some((kw) => keywords.includes(kw));
|
|
7225
|
+
|
|
7226
|
+
return false;
|
|
7351
7227
|
}
|
|
7352
|
-
|
|
7353
|
-
|
|
7354
|
-
|
|
7355
|
-
|
|
7356
|
-
|
|
7357
|
-
|
|
7358
|
-
|
|
7359
|
-
|
|
7360
|
-
|
|
7361
|
-
|
|
7362
|
-
|
|
7363
|
-
|
|
7228
|
+
|
|
7229
|
+
function categorize(el) {
|
|
7230
|
+
const tag = el.tagName?.toLowerCase();
|
|
7231
|
+
const role = el.getAttribute('role');
|
|
7232
|
+
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7233
|
+
|
|
7234
|
+
if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
|
|
7235
|
+
if (role === 'popover' || /popover/.test(cls)) return 'popover';
|
|
7236
|
+
if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
|
|
7237
|
+
if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
|
|
7238
|
+
if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
|
|
7239
|
+
if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
|
|
7240
|
+
if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
|
|
7241
|
+
return 'unknown';
|
|
7364
7242
|
}
|
|
7365
|
-
|
|
7366
|
-
|
|
7367
|
-
|
|
7368
|
-
|
|
7369
|
-
|
|
7370
|
-
|
|
7371
|
-
|
|
7243
|
+
|
|
7244
|
+
function extractElement(el) {
|
|
7245
|
+
const rect = el.getBoundingClientRect();
|
|
7246
|
+
const style = window.getComputedStyle(el);
|
|
7247
|
+
return {
|
|
7248
|
+
selector: getSelector(el),
|
|
7249
|
+
tag: el.tagName.toLowerCase(),
|
|
7250
|
+
role: el.getAttribute('role') || undefined,
|
|
7251
|
+
text: (el.textContent || '').trim().slice(0, 100) || undefined,
|
|
7252
|
+
ariaLabel: el.getAttribute('aria-label') || undefined,
|
|
7253
|
+
size: { width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
7254
|
+
position: { x: Math.round(rect.x), y: Math.round(rect.y) },
|
|
7255
|
+
zIndex: parseInt(style.zIndex) || 0,
|
|
7256
|
+
category: categorize(el),
|
|
7257
|
+
};
|
|
7372
7258
|
}
|
|
7373
|
-
|
|
7374
|
-
|
|
7375
|
-
|
|
7376
|
-
|
|
7377
|
-
|
|
7378
|
-
|
|
7379
|
-
|
|
7259
|
+
|
|
7260
|
+
function scanAndReport() {
|
|
7261
|
+
const results = [];
|
|
7262
|
+
document.querySelectorAll('*').forEach(el => {
|
|
7263
|
+
if (isPopupLike(el)) results.push(extractElement(el));
|
|
7264
|
+
});
|
|
7265
|
+
window.__xbrowserDetectedElements = results;
|
|
7380
7266
|
}
|
|
7381
|
-
};
|
|
7382
7267
|
|
|
7383
|
-
|
|
7384
|
-
|
|
7385
|
-
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7391
|
-
|
|
7392
|
-
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
if (existsSync5(pkgPath)) {
|
|
7268
|
+
window.__xbrowserScanOverlays = function() {
|
|
7269
|
+
scanAndReport();
|
|
7270
|
+
return window.__xbrowserDetectedElements;
|
|
7271
|
+
};
|
|
7272
|
+
})();
|
|
7273
|
+
`;
|
|
7274
|
+
var DomWatcher = class {
|
|
7275
|
+
page;
|
|
7276
|
+
injected = false;
|
|
7277
|
+
constructor(page) {
|
|
7278
|
+
this.page = page;
|
|
7279
|
+
}
|
|
7280
|
+
async inject() {
|
|
7281
|
+
if (this.injected) return;
|
|
7398
7282
|
try {
|
|
7399
|
-
|
|
7283
|
+
await this.page.evaluate(DOM_WATCHER_SCRIPT);
|
|
7284
|
+
await this.page.addInitScript(DOM_WATCHER_SCRIPT);
|
|
7285
|
+
this.injected = true;
|
|
7400
7286
|
} catch {
|
|
7401
7287
|
}
|
|
7402
7288
|
}
|
|
7403
|
-
|
|
7404
|
-
|
|
7405
|
-
|
|
7406
|
-
|
|
7407
|
-
|
|
7408
|
-
|
|
7289
|
+
async scanOverlays() {
|
|
7290
|
+
try {
|
|
7291
|
+
if (!this.injected) await this.inject();
|
|
7292
|
+
const result = await this.page.evaluate(
|
|
7293
|
+
"window.__xbrowserScanOverlays ? window.__xbrowserScanOverlays() : []"
|
|
7294
|
+
);
|
|
7295
|
+
return result || [];
|
|
7296
|
+
} catch {
|
|
7297
|
+
return [];
|
|
7409
7298
|
}
|
|
7410
7299
|
}
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
7415
|
-
writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
|
|
7416
|
-
try {
|
|
7417
|
-
execSync("npm install --production --no-package-lock --no-fund --no-audit", {
|
|
7418
|
-
cwd: pluginsDir,
|
|
7419
|
-
stdio: "pipe",
|
|
7420
|
-
timeout: 6e4,
|
|
7421
|
-
env: { ...process.env, NODE_ENV: "production" }
|
|
7422
|
-
});
|
|
7423
|
-
} catch (err) {
|
|
7424
|
-
console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
|
|
7300
|
+
};
|
|
7301
|
+
function classifyPriority(category, element) {
|
|
7302
|
+
if (category === "dialog" && element.text && /error|错误|fail|失败|denied|拒绝/i.test(element.text)) {
|
|
7303
|
+
return "p0";
|
|
7425
7304
|
}
|
|
7305
|
+
if (category === "dialog" || category === "modal") return "p1";
|
|
7306
|
+
if (category === "popover" || category === "overlay") return "p2";
|
|
7307
|
+
if (category === "toast" || category === "notification") return "p2";
|
|
7308
|
+
if (category === "dropdown") return "p3";
|
|
7309
|
+
if (category === "tooltip") return "p3";
|
|
7310
|
+
return "p2";
|
|
7426
7311
|
}
|
|
7427
7312
|
|
|
7428
|
-
// src/
|
|
7429
|
-
|
|
7430
|
-
|
|
7431
|
-
|
|
7432
|
-
|
|
7433
|
-
|
|
7434
|
-
|
|
7435
|
-
|
|
7436
|
-
|
|
7437
|
-
|
|
7438
|
-
return {
|
|
7439
|
-
version: 2,
|
|
7440
|
-
plugin: {
|
|
7441
|
-
name: site.name,
|
|
7442
|
-
url: site.url,
|
|
7443
|
-
description: site.config?.description,
|
|
7444
|
-
requiresLogin: site.config?.requiresLogin
|
|
7445
|
-
},
|
|
7446
|
-
commands
|
|
7447
|
-
};
|
|
7448
|
-
}
|
|
7449
|
-
function buildCommandContract(command, options = {}) {
|
|
7450
|
-
const extension = command.xbrowser || {};
|
|
7451
|
-
const inferredFields = fieldsFromZodObject(command.parameters);
|
|
7452
|
-
const fields = mergeFields(inferredFields, extension.form?.fields || []);
|
|
7453
|
-
const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
|
|
7454
|
-
const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
|
|
7455
|
-
const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
|
|
7456
|
-
const outputSchema = command.result ? summarizeZod(command.result) : void 0;
|
|
7457
|
-
return {
|
|
7458
|
-
name: command.name,
|
|
7459
|
-
description: command.description || "",
|
|
7460
|
-
scope: command.scope || "project",
|
|
7461
|
-
requiresLogin,
|
|
7462
|
-
category: extension.category,
|
|
7463
|
-
capabilities,
|
|
7464
|
-
positional,
|
|
7465
|
-
form: {
|
|
7466
|
-
title: extension.form?.title || command.description || command.name,
|
|
7467
|
-
description: extension.form?.description,
|
|
7468
|
-
submitLabel: extension.form?.submitLabel || "Run",
|
|
7469
|
-
fields
|
|
7470
|
-
},
|
|
7471
|
-
output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
|
|
7472
|
-
};
|
|
7473
|
-
}
|
|
7474
|
-
function fieldsFromZodObject(schema) {
|
|
7475
|
-
const reflected = fieldsFromZodObjectReflected(schema);
|
|
7476
|
-
return reflected.map((field) => {
|
|
7477
|
-
const widget = widgetFor(field.type, field.enum);
|
|
7478
|
-
return {
|
|
7479
|
-
name: field.name,
|
|
7480
|
-
label: toLabel(field.name),
|
|
7481
|
-
type: field.type,
|
|
7482
|
-
widget,
|
|
7483
|
-
required: field.required,
|
|
7484
|
-
...field.description ? { description: field.description } : {},
|
|
7485
|
-
...field.default !== void 0 ? { default: field.default } : {},
|
|
7486
|
-
...field.enum ? { enum: field.enum } : {},
|
|
7487
|
-
...field.type === "array" ? { multiple: true } : {}
|
|
7488
|
-
};
|
|
7489
|
-
});
|
|
7490
|
-
}
|
|
7491
|
-
function mergeFields(inferred, overrides) {
|
|
7492
|
-
if (overrides.length === 0) return inferred;
|
|
7493
|
-
const byName = new Map(inferred.map((field) => [field.name, field]));
|
|
7494
|
-
const seen = /* @__PURE__ */ new Set();
|
|
7495
|
-
const merged = [];
|
|
7496
|
-
for (const override of overrides) {
|
|
7497
|
-
if (!override.name) continue;
|
|
7498
|
-
const base = byName.get(override.name) || {
|
|
7499
|
-
name: override.name,
|
|
7500
|
-
label: toLabel(override.name),
|
|
7501
|
-
type: "string",
|
|
7502
|
-
widget: "text",
|
|
7503
|
-
required: false
|
|
7313
|
+
// src/tips/context-tracker.ts
|
|
7314
|
+
var ContextTracker = class {
|
|
7315
|
+
history = [];
|
|
7316
|
+
maxHistory = 20;
|
|
7317
|
+
record(commandName, params) {
|
|
7318
|
+
const entry = {
|
|
7319
|
+
commandName,
|
|
7320
|
+
params,
|
|
7321
|
+
timestamp: Date.now(),
|
|
7322
|
+
targetSelector: params.selector || params.url || void 0
|
|
7504
7323
|
};
|
|
7505
|
-
|
|
7506
|
-
|
|
7507
|
-
|
|
7508
|
-
|
|
7509
|
-
if (!seen.has(field.name)) merged.push(field);
|
|
7324
|
+
this.history.push(entry);
|
|
7325
|
+
if (this.history.length > this.maxHistory) {
|
|
7326
|
+
this.history.shift();
|
|
7327
|
+
}
|
|
7510
7328
|
}
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
function inferCapabilities(scope, requiresLogin) {
|
|
7514
|
-
const caps = [];
|
|
7515
|
-
if (scope === "page") caps.push("browser.page");
|
|
7516
|
-
if (scope === "browser") caps.push("browser.context");
|
|
7517
|
-
if (requiresLogin) caps.push("auth.login");
|
|
7518
|
-
return caps;
|
|
7519
|
-
}
|
|
7520
|
-
function widgetFor(type, enumValues) {
|
|
7521
|
-
if (enumValues) return "select";
|
|
7522
|
-
if (type === "boolean") return "checkbox";
|
|
7523
|
-
if (type === "number") return "number";
|
|
7524
|
-
if (type === "array") return "multi-select";
|
|
7525
|
-
if (type === "object") return "json";
|
|
7526
|
-
return "text";
|
|
7527
|
-
}
|
|
7528
|
-
function summarizeZod(schema) {
|
|
7529
|
-
const unwrapped = unwrapZod(schema);
|
|
7530
|
-
if (unwrapped.typeName === "ZodArray") {
|
|
7531
|
-
const def = unwrapped.schema?._def;
|
|
7532
|
-
return {
|
|
7533
|
-
type: "array",
|
|
7534
|
-
items: summarizeZod(def?.type || def?.innerType)
|
|
7535
|
-
};
|
|
7329
|
+
getLastCommand() {
|
|
7330
|
+
return this.history.length > 0 ? this.history[this.history.length - 1] : void 0;
|
|
7536
7331
|
}
|
|
7537
|
-
|
|
7538
|
-
|
|
7539
|
-
|
|
7540
|
-
|
|
7541
|
-
|
|
7542
|
-
|
|
7543
|
-
|
|
7332
|
+
getLastSelector() {
|
|
7333
|
+
for (let i = this.history.length - 1; i >= 0; i--) {
|
|
7334
|
+
if (this.history[i].targetSelector) {
|
|
7335
|
+
return this.history[i].targetSelector;
|
|
7336
|
+
}
|
|
7337
|
+
}
|
|
7338
|
+
return void 0;
|
|
7544
7339
|
}
|
|
7545
|
-
|
|
7546
|
-
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
|
|
7552
|
-
}];
|
|
7553
|
-
})
|
|
7554
|
-
);
|
|
7555
|
-
}
|
|
7556
|
-
function getObjectShape(schema) {
|
|
7557
|
-
const zod = schema;
|
|
7558
|
-
const shapeOrFn = zod?.shape ?? zod?._def?.shape;
|
|
7559
|
-
if (!shapeOrFn) return void 0;
|
|
7560
|
-
return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
|
|
7561
|
-
}
|
|
7562
|
-
function toLabel(name) {
|
|
7563
|
-
return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
|
|
7564
|
-
}
|
|
7565
|
-
|
|
7566
|
-
// src/plugin/login-required-patch.ts
|
|
7567
|
-
import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
|
|
7568
|
-
var patched = false;
|
|
7569
|
-
function patchLoginRequired() {
|
|
7570
|
-
if (patched) return;
|
|
7571
|
-
patched = true;
|
|
7572
|
-
const target = SiteInstanceImpl.prototype;
|
|
7573
|
-
const originalCommand = target.command;
|
|
7574
|
-
const wrapped = function(...args) {
|
|
7575
|
-
const result = originalCommand.apply(this, args);
|
|
7576
|
-
const [name, cmd] = args;
|
|
7577
|
-
const loginRequired = cmd.loginRequired;
|
|
7578
|
-
if (loginRequired) {
|
|
7579
|
-
const commands = this.commands;
|
|
7580
|
-
const entry = commands?.get(name);
|
|
7581
|
-
if (entry) {
|
|
7582
|
-
entry.loginRequired = loginRequired;
|
|
7583
|
-
}
|
|
7340
|
+
isLikelyTriggered(selector) {
|
|
7341
|
+
const last = this.getLastCommand();
|
|
7342
|
+
if (!last) return false;
|
|
7343
|
+
const cmd = last.commandName.toLowerCase();
|
|
7344
|
+
const target = last.targetSelector?.toLowerCase() || "";
|
|
7345
|
+
if (["click", "dblclick", "hover", "tap"].includes(cmd)) {
|
|
7346
|
+
return selector === target || selector.startsWith(target.split(/[.\[#]/)[0]);
|
|
7584
7347
|
}
|
|
7585
|
-
|
|
7586
|
-
|
|
7587
|
-
|
|
7588
|
-
|
|
7589
|
-
writable: true,
|
|
7590
|
-
configurable: true
|
|
7591
|
-
});
|
|
7592
|
-
}
|
|
7593
|
-
|
|
7594
|
-
// src/plugin/loader.ts
|
|
7595
|
-
var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
|
|
7596
|
-
var XBrowserPluginLoader = class {
|
|
7597
|
-
core;
|
|
7598
|
-
loader;
|
|
7599
|
-
options;
|
|
7600
|
-
/** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
|
|
7601
|
-
dirSiteAliases = /* @__PURE__ */ new Map();
|
|
7602
|
-
constructor(options) {
|
|
7603
|
-
patchLoginRequired();
|
|
7604
|
-
this.options = options ?? {};
|
|
7605
|
-
const cwd = this.options.cwd || process.cwd();
|
|
7606
|
-
const coreConfig = {
|
|
7607
|
-
name: "xbrowser",
|
|
7608
|
-
version: "0.1.0",
|
|
7609
|
-
description: "Browser automation CLI",
|
|
7610
|
-
configDirName: ".xbrowser",
|
|
7611
|
-
envPrefix: "XBROWSER",
|
|
7612
|
-
pluginDirs: [
|
|
7613
|
-
...DEFAULT_PLUGIN_DIRS,
|
|
7614
|
-
resolve2(cwd, ".xcli/plugins")
|
|
7615
|
-
]
|
|
7616
|
-
};
|
|
7617
|
-
this.core = new Core(coreConfig);
|
|
7618
|
-
this.loader = this.core.loader;
|
|
7348
|
+
if (["fill", "type", "select", "check", "uncheck"].includes(cmd)) {
|
|
7349
|
+
return selector === target;
|
|
7350
|
+
}
|
|
7351
|
+
return false;
|
|
7619
7352
|
}
|
|
7620
|
-
|
|
7621
|
-
|
|
7353
|
+
isRecentCommand(cmdName, withinMs = 2e3) {
|
|
7354
|
+
const last = this.getLastCommand();
|
|
7355
|
+
if (!last) return false;
|
|
7356
|
+
return last.commandName === cmdName && Date.now() - last.timestamp < withinMs;
|
|
7622
7357
|
}
|
|
7623
|
-
|
|
7624
|
-
|
|
7625
|
-
* @returns The xcli-core Core instance.
|
|
7626
|
-
*/
|
|
7627
|
-
getCore() {
|
|
7628
|
-
return this.core;
|
|
7358
|
+
clear() {
|
|
7359
|
+
this.history = [];
|
|
7629
7360
|
}
|
|
7630
|
-
|
|
7631
|
-
|
|
7361
|
+
};
|
|
7362
|
+
|
|
7363
|
+
// src/tips/tip-generator.ts
|
|
7364
|
+
var SILENT_CATEGORIES = /* @__PURE__ */ new Set(["dropdown", "tooltip"]);
|
|
7365
|
+
var NOTIFICATION_CATEGORIES = /* @__PURE__ */ new Set(["toast", "notification"]);
|
|
7366
|
+
var TipGenerator = class {
|
|
7367
|
+
contextTracker;
|
|
7368
|
+
reportedSelectors = /* @__PURE__ */ new Map();
|
|
7369
|
+
dedupWindowMs = 3e4;
|
|
7370
|
+
constructor(contextTracker) {
|
|
7371
|
+
this.contextTracker = contextTracker;
|
|
7632
7372
|
}
|
|
7633
|
-
|
|
7634
|
-
|
|
7373
|
+
diff(before, after, currentElements) {
|
|
7374
|
+
const beforeSet = new Set(before.overlaySelectors);
|
|
7375
|
+
const afterSet = new Set(after.overlaySelectors);
|
|
7376
|
+
const newSelectors = [];
|
|
7377
|
+
for (const sel of afterSet) {
|
|
7378
|
+
if (!beforeSet.has(sel)) newSelectors.push(sel);
|
|
7379
|
+
}
|
|
7380
|
+
if (newSelectors.length === 0) return [];
|
|
7381
|
+
return currentElements.filter((el) => newSelectors.includes(el.selector));
|
|
7635
7382
|
}
|
|
7636
|
-
|
|
7637
|
-
|
|
7383
|
+
generate(newElements) {
|
|
7384
|
+
const tips = [];
|
|
7385
|
+
for (const el of newElements) {
|
|
7386
|
+
if (this.contextTracker.isLikelyTriggered(el.selector)) continue;
|
|
7387
|
+
if (SILENT_CATEGORIES.has(el.category)) continue;
|
|
7388
|
+
if (NOTIFICATION_CATEGORIES.has(el.category) && el.text && /success|成功|done|完成|saved|已保存/i.test(el.text)) {
|
|
7389
|
+
continue;
|
|
7390
|
+
}
|
|
7391
|
+
if (this.isRecentlyReported(el.selector)) continue;
|
|
7392
|
+
const priority = classifyPriority(el.category, el);
|
|
7393
|
+
if (priority === "p3") continue;
|
|
7394
|
+
const message = this.buildMessage(el);
|
|
7395
|
+
const suggestions = this.buildSuggestions(el);
|
|
7396
|
+
tips.push({
|
|
7397
|
+
priority,
|
|
7398
|
+
category: el.category,
|
|
7399
|
+
element: el,
|
|
7400
|
+
message,
|
|
7401
|
+
suggestions
|
|
7402
|
+
});
|
|
7403
|
+
this.reportedSelectors.set(el.selector, Date.now());
|
|
7404
|
+
}
|
|
7405
|
+
tips.sort((a, b) => {
|
|
7406
|
+
const order = { p0: 0, p1: 1, p2: 2 };
|
|
7407
|
+
return (order[a.priority] ?? 3) - (order[b.priority] ?? 3);
|
|
7408
|
+
});
|
|
7409
|
+
return tips;
|
|
7638
7410
|
}
|
|
7639
|
-
|
|
7640
|
-
|
|
7641
|
-
|
|
7642
|
-
|
|
7643
|
-
|
|
7644
|
-
|
|
7645
|
-
*/
|
|
7646
|
-
resolveSiteName(name) {
|
|
7647
|
-
if (this.core.loader.getSite(name)) return name;
|
|
7648
|
-
const aliased = this.dirSiteAliases.get(name);
|
|
7649
|
-
if (aliased && this.core.loader.getSite(aliased)) return aliased;
|
|
7650
|
-
return void 0;
|
|
7411
|
+
buildMessage(el) {
|
|
7412
|
+
const label = el.ariaLabel || el.text?.slice(0, 40) || "";
|
|
7413
|
+
const labelStr = label ? ` "${label}"` : "";
|
|
7414
|
+
const sizeStr = `${el.size.width}x${el.size.height}`;
|
|
7415
|
+
const typeLabel = this.categoryLabel(el.category);
|
|
7416
|
+
return `\u68C0\u6D4B\u5230\u65B0${typeLabel}${labelStr} (${sizeStr})\uFF0C\u9009\u62E9\u5668: ${el.selector}`;
|
|
7651
7417
|
}
|
|
7652
|
-
|
|
7653
|
-
|
|
7654
|
-
|
|
7655
|
-
|
|
7418
|
+
buildSuggestions(el) {
|
|
7419
|
+
const suggestions = [];
|
|
7420
|
+
if (el.category === "dialog" || el.category === "modal") {
|
|
7421
|
+
const confirmBtn = this.guessButtonSelector(el, ["confirm", "ok", "yes", "\u786E\u5B9A", "\u786E\u8BA4", "\u540C\u610F"]);
|
|
7422
|
+
const cancelBtn = this.guessButtonSelector(el, ["cancel", "close", "no", "\u53D6\u6D88", "\u5173\u95ED", "\u62D2\u7EDD"]);
|
|
7423
|
+
if (confirmBtn) suggestions.push(`click "${confirmBtn}"`);
|
|
7424
|
+
if (cancelBtn) suggestions.push(`click "${cancelBtn}"`);
|
|
7656
7425
|
}
|
|
7426
|
+
if (el.category === "popover" || el.category === "overlay") {
|
|
7427
|
+
suggestions.push(`click "${el.selector}"`);
|
|
7428
|
+
}
|
|
7429
|
+
if (el.category === "toast" || el.category === "notification") {
|
|
7430
|
+
suggestions.push(`text "${el.selector}"`);
|
|
7431
|
+
}
|
|
7432
|
+
if (suggestions.length === 0) {
|
|
7433
|
+
suggestions.push(`click "${el.selector}"`);
|
|
7434
|
+
}
|
|
7435
|
+
return suggestions;
|
|
7657
7436
|
}
|
|
7658
|
-
|
|
7659
|
-
const
|
|
7660
|
-
|
|
7661
|
-
|
|
7662
|
-
|
|
7663
|
-
|
|
7664
|
-
if (!commandName) return contract;
|
|
7665
|
-
return contract.commands.find((command) => command.name === commandName);
|
|
7666
|
-
}
|
|
7667
|
-
async loadPlugin(pluginPath, id) {
|
|
7668
|
-
const before = new Set(this.core.loader.getSites().map((s) => s.name));
|
|
7669
|
-
const instance = await this.loader.loadPlugin(pluginPath, id);
|
|
7670
|
-
this.recordSiteAliases(basename(dirname3(pluginPath)), before);
|
|
7671
|
-
return instance;
|
|
7437
|
+
guessButtonSelector(el, keywords) {
|
|
7438
|
+
const base = el.selector;
|
|
7439
|
+
for (const kw of keywords) {
|
|
7440
|
+
return `${base} button:has-text("${kw}"), ${base} [role="button"]:has-text("${kw}")`;
|
|
7441
|
+
}
|
|
7442
|
+
return void 0;
|
|
7672
7443
|
}
|
|
7673
|
-
|
|
7674
|
-
|
|
7444
|
+
categoryLabel(category) {
|
|
7445
|
+
const labels = {
|
|
7446
|
+
dialog: "Dialog",
|
|
7447
|
+
modal: "Modal",
|
|
7448
|
+
popover: "Popover",
|
|
7449
|
+
notification: "\u901A\u77E5",
|
|
7450
|
+
toast: "Toast",
|
|
7451
|
+
dropdown: "\u4E0B\u62C9\u83DC\u5355",
|
|
7452
|
+
tooltip: "Tooltip",
|
|
7453
|
+
overlay: "Overlay",
|
|
7454
|
+
unknown: "\u5F39\u7A97"
|
|
7455
|
+
};
|
|
7456
|
+
return labels[category] || "\u5F39\u7A97";
|
|
7675
7457
|
}
|
|
7676
|
-
|
|
7677
|
-
|
|
7458
|
+
isRecentlyReported(selector) {
|
|
7459
|
+
const lastTime = this.reportedSelectors.get(selector);
|
|
7460
|
+
if (!lastTime) return false;
|
|
7461
|
+
return Date.now() - lastTime < this.dedupWindowMs;
|
|
7678
7462
|
}
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
}
|
|
7682
|
-
async scanAndLoad() {
|
|
7683
|
-
const cwd = this.options.cwd || process.cwd();
|
|
7684
|
-
const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
|
|
7685
|
-
ensurePluginDependencies(globalDir);
|
|
7686
|
-
const dirs = [
|
|
7687
|
-
resolve2(cwd, ".xcli/plugins"),
|
|
7688
|
-
resolve2(cwd, "../.xcli/plugins"),
|
|
7689
|
-
this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
|
|
7690
|
-
globalDir
|
|
7691
|
-
];
|
|
7692
|
-
const loaded = [];
|
|
7693
|
-
const seen = /* @__PURE__ */ new Set();
|
|
7694
|
-
for (const dir of dirs) {
|
|
7695
|
-
if (!existsSync6(dir)) continue;
|
|
7696
|
-
const entries = readdirSync(dir, { withFileTypes: true });
|
|
7697
|
-
for (const entry of entries) {
|
|
7698
|
-
if (!entry.isDirectory()) continue;
|
|
7699
|
-
if (seen.has(entry.name)) continue;
|
|
7700
|
-
seen.add(entry.name);
|
|
7701
|
-
const pluginDir = resolve2(dir, entry.name);
|
|
7702
|
-
let indexPath = resolve2(pluginDir, "index.js");
|
|
7703
|
-
if (!existsSync6(indexPath)) {
|
|
7704
|
-
indexPath = resolve2(pluginDir, "index.ts");
|
|
7705
|
-
}
|
|
7706
|
-
if (!existsSync6(indexPath)) continue;
|
|
7707
|
-
try {
|
|
7708
|
-
if (!existsSync6(resolve2(pluginDir, "package.json"))) {
|
|
7709
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
|
|
7710
|
-
} else {
|
|
7711
|
-
const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
|
|
7712
|
-
if (!metadata) {
|
|
7713
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
|
|
7714
|
-
}
|
|
7715
|
-
}
|
|
7716
|
-
const instance = await this.loadPlugin(indexPath, entry.name);
|
|
7717
|
-
loaded.push(instance);
|
|
7718
|
-
} catch (err) {
|
|
7719
|
-
const errMsg2 = err instanceof Error ? err.message : String(err);
|
|
7720
|
-
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
|
|
7721
|
-
if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
|
|
7722
|
-
console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
|
|
7723
|
-
}
|
|
7724
|
-
}
|
|
7725
|
-
}
|
|
7726
|
-
}
|
|
7727
|
-
return loaded;
|
|
7728
|
-
}
|
|
7729
|
-
async unload() {
|
|
7730
|
-
return this.loader.unload();
|
|
7463
|
+
resetDedup() {
|
|
7464
|
+
this.reportedSelectors.clear();
|
|
7731
7465
|
}
|
|
7732
7466
|
};
|
|
7733
|
-
|
|
7734
|
-
|
|
7735
|
-
|
|
7736
|
-
|
|
7737
|
-
function silenceSchemaWarnings(fn) {
|
|
7738
|
-
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
7739
|
-
const originalWarn = console.warn;
|
|
7740
|
-
console.warn = (...args) => {
|
|
7741
|
-
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
7742
|
-
if (msg.includes('has no "result" schema')) return;
|
|
7743
|
-
originalWarn(...args);
|
|
7467
|
+
function buildSnapshot(elements) {
|
|
7468
|
+
return {
|
|
7469
|
+
timestamp: Date.now(),
|
|
7470
|
+
overlaySelectors: elements.map((el) => el.selector)
|
|
7744
7471
|
};
|
|
7745
|
-
return fn().finally(() => {
|
|
7746
|
-
console.warn = originalWarn;
|
|
7747
|
-
});
|
|
7748
|
-
}
|
|
7749
|
-
async function getPluginLoader() {
|
|
7750
|
-
if (!pluginLoader) {
|
|
7751
|
-
pluginLoader = new XBrowserPluginLoader();
|
|
7752
|
-
}
|
|
7753
|
-
if (!pluginsScanned) {
|
|
7754
|
-
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
7755
|
-
pluginsScanned = true;
|
|
7756
|
-
}
|
|
7757
|
-
return pluginLoader;
|
|
7758
7472
|
}
|
|
7759
7473
|
|
|
7760
|
-
// src/
|
|
7761
|
-
|
|
7762
|
-
const
|
|
7763
|
-
|
|
7764
|
-
|
|
7765
|
-
|
|
7766
|
-
|
|
7767
|
-
|
|
7768
|
-
|
|
7769
|
-
|
|
7770
|
-
|
|
7771
|
-
|
|
7772
|
-
|
|
7773
|
-
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
|
|
7778
|
-
|
|
7779
|
-
|
|
7780
|
-
|
|
7781
|
-
|
|
7474
|
+
// src/tips/index.ts
|
|
7475
|
+
function tipsDebounceMs() {
|
|
7476
|
+
const v = parseInt(process.env.XBROWSER_TIPS_DEBOUNCE ?? "120", 10);
|
|
7477
|
+
return Number.isFinite(v) && v > 0 ? v : 0;
|
|
7478
|
+
}
|
|
7479
|
+
var SKIP_DETECT_COMMANDS = /* @__PURE__ */ new Set([
|
|
7480
|
+
"goto",
|
|
7481
|
+
// 导航命令不需要检测
|
|
7482
|
+
"screenshot",
|
|
7483
|
+
// 截图不需要检测
|
|
7484
|
+
"snapshot",
|
|
7485
|
+
// snapshot 不需要检测
|
|
7486
|
+
"get",
|
|
7487
|
+
// get 命令不需要检测
|
|
7488
|
+
"detect",
|
|
7489
|
+
// detect 命令本身不需要检测
|
|
7490
|
+
"history",
|
|
7491
|
+
// history 命令不需要检测
|
|
7492
|
+
"viewer"
|
|
7493
|
+
// viewer 命令不需要检测
|
|
7494
|
+
]);
|
|
7495
|
+
var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
|
|
7496
|
+
"click",
|
|
7497
|
+
"fill",
|
|
7498
|
+
"type",
|
|
7499
|
+
"select",
|
|
7500
|
+
"check",
|
|
7501
|
+
"uncheck",
|
|
7502
|
+
"hover",
|
|
7503
|
+
"dblclick"
|
|
7504
|
+
]);
|
|
7505
|
+
var TipsManager = class {
|
|
7506
|
+
domWatcher = null;
|
|
7507
|
+
contextTracker = new ContextTracker();
|
|
7508
|
+
generator = new TipGenerator(this.contextTracker);
|
|
7509
|
+
beforeSnapshot = null;
|
|
7510
|
+
lastDetectionTime = 0;
|
|
7511
|
+
async beforeCommand(page, commandName, params) {
|
|
7512
|
+
this.contextTracker.record(commandName, params);
|
|
7513
|
+
if (!this.domWatcher) {
|
|
7514
|
+
this.domWatcher = new DomWatcher(page);
|
|
7782
7515
|
}
|
|
7783
|
-
}
|
|
7784
|
-
if (typeof site.isLoggedIn === "function") {
|
|
7785
7516
|
try {
|
|
7786
|
-
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
plugin: pluginName,
|
|
7790
|
-
command: commandName,
|
|
7791
|
-
reason: "plugin isLoggedIn returned false",
|
|
7792
|
-
sessionName,
|
|
7793
|
-
loginConfig
|
|
7794
|
-
});
|
|
7517
|
+
await this.domWatcher.inject();
|
|
7518
|
+
const elements = await this.domWatcher.scanOverlays();
|
|
7519
|
+
this.beforeSnapshot = buildSnapshot(elements);
|
|
7795
7520
|
} catch {
|
|
7521
|
+
this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
|
|
7796
7522
|
}
|
|
7797
|
-
|
|
7798
|
-
|
|
7799
|
-
const generic = await detectLoginFromPage(page, loginConfig);
|
|
7800
|
-
if (generic === "logged-in") return { ok: true };
|
|
7801
|
-
if (generic === "logged-out") {
|
|
7802
|
-
return buildLoginRequired({
|
|
7803
|
-
plugin: pluginName,
|
|
7804
|
-
command: commandName,
|
|
7805
|
-
reason: "generic loginConfig detected logged-out page",
|
|
7806
|
-
sessionName,
|
|
7807
|
-
loginConfig
|
|
7808
|
-
});
|
|
7523
|
+
if (INTERACTION_COMMANDS.has(commandName) && !SKIP_DETECT_COMMANDS.has(commandName)) {
|
|
7524
|
+
await this.checkAntiBot(page, commandName);
|
|
7809
7525
|
}
|
|
7810
7526
|
}
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
7820
|
-
|
|
7821
|
-
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
data: {
|
|
7826
|
-
code: "LOGIN_REQUIRED",
|
|
7827
|
-
plugin: options.plugin,
|
|
7828
|
-
command: options.command,
|
|
7829
|
-
reason: options.reason,
|
|
7830
|
-
...viewerUrl ? { viewerUrl } : {},
|
|
7831
|
-
...loginUrl ? { loginUrl } : {}
|
|
7832
|
-
},
|
|
7833
|
-
message,
|
|
7834
|
-
tips
|
|
7835
|
-
};
|
|
7836
|
-
}
|
|
7837
|
-
async function detectLoginFromPage(page, config) {
|
|
7838
|
-
const url = page.url();
|
|
7839
|
-
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
7840
|
-
const result = await page.evaluate((cfg) => {
|
|
7841
|
-
const visible = (selector) => {
|
|
7842
|
-
try {
|
|
7843
|
-
const el = document.querySelector(selector);
|
|
7844
|
-
if (!el) return false;
|
|
7845
|
-
const rect = el.getBoundingClientRect();
|
|
7846
|
-
const style = window.getComputedStyle(el);
|
|
7847
|
-
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
7848
|
-
} catch {
|
|
7849
|
-
return false;
|
|
7850
|
-
}
|
|
7527
|
+
/**
|
|
7528
|
+
* 检测反机器人机制
|
|
7529
|
+
*/
|
|
7530
|
+
async checkAntiBot(page, _commandName) {
|
|
7531
|
+
const now = Date.now();
|
|
7532
|
+
if (now - this.lastDetectionTime < 5e3) {
|
|
7533
|
+
return;
|
|
7534
|
+
}
|
|
7535
|
+
this.lastDetectionTime = now;
|
|
7536
|
+
const config = {
|
|
7537
|
+
checkCaptcha: true,
|
|
7538
|
+
checkWarning: true,
|
|
7539
|
+
checkBlocked: true,
|
|
7540
|
+
checkWebdriver: true
|
|
7851
7541
|
};
|
|
7852
|
-
|
|
7853
|
-
if (
|
|
7854
|
-
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
|
|
7542
|
+
const result = await detectAntiBot(page, config);
|
|
7543
|
+
if (result.detected && result.severity === "high") {
|
|
7544
|
+
const message = formatDetectionMessage(result);
|
|
7545
|
+
console.error(`
|
|
7546
|
+
\u{1F6A8} ${message}
|
|
7547
|
+
`);
|
|
7548
|
+
console.log("\u{1F4A1} Action blocked. To continue:");
|
|
7549
|
+
console.log(" 1. Use viewer mode: xbrowser viewer --json");
|
|
7550
|
+
console.log(" 2. Or skip detection with --skip-detect flag\n");
|
|
7551
|
+
throw new Error(`Anti-bot detection blocked: ${result.message}`);
|
|
7858
7552
|
}
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
window.__xbrowserDetectedElements = [];
|
|
7875
|
-
|
|
7876
|
-
function getSelector(el) {
|
|
7877
|
-
if (el.id) return '#' + CSS.escape(el.id);
|
|
7878
|
-
if (el.getAttribute('aria-label')) {
|
|
7879
|
-
return el.tagName.toLowerCase() + '[aria-label="' + el.getAttribute('aria-label') + '"]';
|
|
7553
|
+
}
|
|
7554
|
+
async afterCommand() {
|
|
7555
|
+
if (!this.domWatcher || !this.beforeSnapshot) return [];
|
|
7556
|
+
await this.debounce();
|
|
7557
|
+
try {
|
|
7558
|
+
const currentElements = await this.domWatcher.scanOverlays();
|
|
7559
|
+
const afterSnapshot = buildSnapshot(currentElements);
|
|
7560
|
+
const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
|
|
7561
|
+
const tips = this.generator.generate(newElements);
|
|
7562
|
+
this.beforeSnapshot = null;
|
|
7563
|
+
return tips;
|
|
7564
|
+
} catch {
|
|
7565
|
+
this.beforeSnapshot = null;
|
|
7566
|
+
return [];
|
|
7880
7567
|
}
|
|
7881
|
-
const cls = el.className && typeof el.className === 'string'
|
|
7882
|
-
? el.className.trim().split(/\\s+/).filter(c => c.length > 0 && !c.startsWith('__')).slice(0, 2).join('.')
|
|
7883
|
-
: '';
|
|
7884
|
-
if (cls) return el.tagName.toLowerCase() + '.' + cls;
|
|
7885
|
-
return el.tagName.toLowerCase();
|
|
7886
7568
|
}
|
|
7887
|
-
|
|
7888
|
-
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
if (tag === 'body' || tag === 'html') return false;
|
|
7892
|
-
|
|
7893
|
-
const role = el.getAttribute('role');
|
|
7894
|
-
if (['dialog', 'alertdialog', 'popover', 'alert'].includes(role)) return true;
|
|
7895
|
-
|
|
7896
|
-
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7897
|
-
const popupPatterns = /modal|popup|popover|overlay|drawer|sheet|lightbox|dialog/;
|
|
7898
|
-
if (popupPatterns.test(cls)) return true;
|
|
7899
|
-
|
|
7900
|
-
const style = window.getComputedStyle(el);
|
|
7901
|
-
if ((style.position === 'fixed' || style.position === 'absolute') && style.zIndex !== 'auto') {
|
|
7902
|
-
const rect = el.getBoundingClientRect();
|
|
7903
|
-
if (rect.width > 0 && rect.height > 0 && parseInt(style.zIndex) >= 100) return true;
|
|
7904
|
-
}
|
|
7905
|
-
|
|
7906
|
-
return false;
|
|
7907
|
-
}
|
|
7908
|
-
|
|
7909
|
-
function categorize(el) {
|
|
7910
|
-
const tag = el.tagName?.toLowerCase();
|
|
7911
|
-
const role = el.getAttribute('role');
|
|
7912
|
-
const cls = (typeof el.className === 'string') ? el.className.toLowerCase() : '';
|
|
7913
|
-
|
|
7914
|
-
if (tag === 'dialog' || role === 'dialog' || role === 'alertdialog') return 'dialog';
|
|
7915
|
-
if (role === 'popover' || /popover/.test(cls)) return 'popover';
|
|
7916
|
-
if (/modal/.test(cls) && !/dropdown/.test(cls)) return 'modal';
|
|
7917
|
-
if (/toast|notification|message|notice|snack|alert/.test(cls)) return 'toast';
|
|
7918
|
-
if (/dropdown|select-menu|listbox|menu/.test(cls) || role === 'listbox') return 'dropdown';
|
|
7919
|
-
if (/tooltip|tip/.test(cls) || role === 'tooltip') return 'tooltip';
|
|
7920
|
-
if (/overlay|mask|backdrop|dimmer/.test(cls)) return 'overlay';
|
|
7921
|
-
return 'unknown';
|
|
7922
|
-
}
|
|
7923
|
-
|
|
7924
|
-
function extractElement(el) {
|
|
7925
|
-
const rect = el.getBoundingClientRect();
|
|
7926
|
-
const style = window.getComputedStyle(el);
|
|
7927
|
-
return {
|
|
7928
|
-
selector: getSelector(el),
|
|
7929
|
-
tag: el.tagName.toLowerCase(),
|
|
7930
|
-
role: el.getAttribute('role') || undefined,
|
|
7931
|
-
text: (el.textContent || '').trim().slice(0, 100) || undefined,
|
|
7932
|
-
ariaLabel: el.getAttribute('aria-label') || undefined,
|
|
7933
|
-
size: { width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
7934
|
-
position: { x: Math.round(rect.x), y: Math.round(rect.y) },
|
|
7935
|
-
zIndex: parseInt(style.zIndex) || 0,
|
|
7936
|
-
category: categorize(el),
|
|
7937
|
-
};
|
|
7569
|
+
debounce() {
|
|
7570
|
+
const ms = tipsDebounceMs();
|
|
7571
|
+
if (ms <= 0) return Promise.resolve();
|
|
7572
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
7938
7573
|
}
|
|
7939
|
-
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7574
|
+
formatTips(tips) {
|
|
7575
|
+
return tips.map((tip) => {
|
|
7576
|
+
const lines = [tip.message];
|
|
7577
|
+
for (const s of tip.suggestions) {
|
|
7578
|
+
lines.push(` \u2192 ${s}`);
|
|
7579
|
+
}
|
|
7580
|
+
return lines.join("\n");
|
|
7944
7581
|
});
|
|
7945
|
-
window.__xbrowserDetectedElements = results;
|
|
7946
|
-
}
|
|
7947
|
-
|
|
7948
|
-
window.__xbrowserScanOverlays = function() {
|
|
7949
|
-
scanAndReport();
|
|
7950
|
-
return window.__xbrowserDetectedElements;
|
|
7951
|
-
};
|
|
7952
|
-
})();
|
|
7953
|
-
`;
|
|
7954
|
-
var DomWatcher = class {
|
|
7955
|
-
page;
|
|
7956
|
-
injected = false;
|
|
7957
|
-
constructor(page) {
|
|
7958
|
-
this.page = page;
|
|
7959
|
-
}
|
|
7960
|
-
async inject() {
|
|
7961
|
-
if (this.injected) return;
|
|
7962
|
-
try {
|
|
7963
|
-
await this.page.evaluate(DOM_WATCHER_SCRIPT);
|
|
7964
|
-
await this.page.addInitScript(DOM_WATCHER_SCRIPT);
|
|
7965
|
-
this.injected = true;
|
|
7966
|
-
} catch {
|
|
7967
|
-
}
|
|
7968
7582
|
}
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
|
|
7972
|
-
|
|
7973
|
-
|
|
7974
|
-
|
|
7975
|
-
return result || [];
|
|
7976
|
-
} catch {
|
|
7977
|
-
return [];
|
|
7978
|
-
}
|
|
7583
|
+
reset() {
|
|
7584
|
+
this.beforeSnapshot = null;
|
|
7585
|
+
this.generator.resetDedup();
|
|
7586
|
+
this.contextTracker.clear();
|
|
7587
|
+
this.domWatcher = null;
|
|
7588
|
+
this.lastDetectionTime = 0;
|
|
7979
7589
|
}
|
|
7980
7590
|
};
|
|
7981
|
-
|
|
7982
|
-
|
|
7983
|
-
|
|
7591
|
+
var globalTipsManager = null;
|
|
7592
|
+
function getTipsManager() {
|
|
7593
|
+
if (!globalTipsManager) {
|
|
7594
|
+
globalTipsManager = new TipsManager();
|
|
7984
7595
|
}
|
|
7985
|
-
|
|
7986
|
-
if (category === "popover" || category === "overlay") return "p2";
|
|
7987
|
-
if (category === "toast" || category === "notification") return "p2";
|
|
7988
|
-
if (category === "dropdown") return "p3";
|
|
7989
|
-
if (category === "tooltip") return "p3";
|
|
7990
|
-
return "p2";
|
|
7596
|
+
return globalTipsManager;
|
|
7991
7597
|
}
|
|
7992
7598
|
|
|
7993
|
-
// src/
|
|
7994
|
-
var
|
|
7995
|
-
|
|
7996
|
-
|
|
7997
|
-
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
8003
|
-
|
|
8004
|
-
|
|
8005
|
-
|
|
8006
|
-
|
|
8007
|
-
|
|
8008
|
-
|
|
8009
|
-
|
|
8010
|
-
|
|
8011
|
-
|
|
8012
|
-
|
|
8013
|
-
|
|
8014
|
-
|
|
8015
|
-
|
|
7599
|
+
// src/hooks/loader.ts
|
|
7600
|
+
var FAIL_KEYWORDS = [
|
|
7601
|
+
"\u767B\u5F55",
|
|
7602
|
+
"login",
|
|
7603
|
+
"Login",
|
|
7604
|
+
"\u672A\u767B\u5F55",
|
|
7605
|
+
"not logged in",
|
|
7606
|
+
"cdp",
|
|
7607
|
+
"CDP",
|
|
7608
|
+
"\u9A8C\u8BC1\u7801",
|
|
7609
|
+
"\u9A8C\u8BC1",
|
|
7610
|
+
"captcha",
|
|
7611
|
+
"\u9700\u8981\u767B\u5F55",
|
|
7612
|
+
"requires login",
|
|
7613
|
+
"blocked",
|
|
7614
|
+
"403",
|
|
7615
|
+
"404"
|
|
7616
|
+
];
|
|
7617
|
+
var HOOK_REGISTRY = {
|
|
7618
|
+
viewer: {
|
|
7619
|
+
name: "viewer",
|
|
7620
|
+
onAfterCommand: async (ctx) => {
|
|
7621
|
+
const result = ctx.result;
|
|
7622
|
+
if (!result || result.success !== false) return void 0;
|
|
7623
|
+
const msg = [
|
|
7624
|
+
result.message,
|
|
7625
|
+
...result.tips || []
|
|
7626
|
+
].filter(Boolean).join(" ").toLowerCase();
|
|
7627
|
+
if (!FAIL_KEYWORDS.some((k) => msg.includes(k))) return void 0;
|
|
7628
|
+
const viewerUrl = buildViewerUrl();
|
|
7629
|
+
if (!viewerUrl) return void 0;
|
|
7630
|
+
const tips = result.tips || [];
|
|
7631
|
+
if (!tips.some((t) => t.includes("viewer") || t.includes("Viewer"))) {
|
|
7632
|
+
tips.push(`Open viewer: ${viewerUrl}`);
|
|
8016
7633
|
}
|
|
7634
|
+
result.tips = tips;
|
|
7635
|
+
result.viewerUrl = viewerUrl;
|
|
7636
|
+
return void 0;
|
|
8017
7637
|
}
|
|
8018
|
-
|
|
8019
|
-
|
|
8020
|
-
|
|
8021
|
-
|
|
8022
|
-
|
|
8023
|
-
|
|
8024
|
-
|
|
8025
|
-
|
|
8026
|
-
|
|
7638
|
+
},
|
|
7639
|
+
screenshot: {
|
|
7640
|
+
name: "screenshot",
|
|
7641
|
+
onAfterCommand: async (ctx) => {
|
|
7642
|
+
try {
|
|
7643
|
+
const buf = await ctx.page.screenshot({ type: "jpeg", quality: 40 }).catch(() => null);
|
|
7644
|
+
if (!buf) return;
|
|
7645
|
+
return { screenshot: { url: `data:image/jpeg;base64,${buf.toString("base64").slice(0, 50)}...` } };
|
|
7646
|
+
} catch {
|
|
7647
|
+
return;
|
|
7648
|
+
}
|
|
8027
7649
|
}
|
|
8028
|
-
|
|
8029
|
-
|
|
7650
|
+
},
|
|
7651
|
+
recorder: {
|
|
7652
|
+
name: "recorder",
|
|
7653
|
+
onAfterCommand: async (ctx) => {
|
|
7654
|
+
const logs = ("__commandLogs" in ctx ? ctx.__commandLogs : void 0) || [];
|
|
7655
|
+
logs.push({
|
|
7656
|
+
timestamp: Date.now(),
|
|
7657
|
+
command: ctx.command,
|
|
7658
|
+
params: JSON.parse(JSON.stringify(ctx.params)),
|
|
7659
|
+
duration: ctx.duration
|
|
7660
|
+
});
|
|
7661
|
+
Reflect.set(ctx, "__commandLogs", logs);
|
|
7662
|
+
return void 0;
|
|
8030
7663
|
}
|
|
8031
|
-
return false;
|
|
8032
|
-
}
|
|
8033
|
-
isRecentCommand(cmdName, withinMs = 2e3) {
|
|
8034
|
-
const last = this.getLastCommand();
|
|
8035
|
-
if (!last) return false;
|
|
8036
|
-
return last.commandName === cmdName && Date.now() - last.timestamp < withinMs;
|
|
8037
|
-
}
|
|
8038
|
-
clear() {
|
|
8039
|
-
this.history = [];
|
|
8040
7664
|
}
|
|
8041
7665
|
};
|
|
8042
|
-
|
|
8043
|
-
|
|
8044
|
-
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
|
|
8048
|
-
|
|
8049
|
-
|
|
8050
|
-
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
|
|
8054
|
-
|
|
8055
|
-
const
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
if (
|
|
7666
|
+
var customHooks = {};
|
|
7667
|
+
async function loadHooks() {
|
|
7668
|
+
const env = process.env.XBROWSER_HOOKS;
|
|
7669
|
+
if (!env) return [];
|
|
7670
|
+
const names = env.split(",").map((n) => n.trim()).filter(Boolean);
|
|
7671
|
+
if (names.length === 0) return [];
|
|
7672
|
+
const hooks = [];
|
|
7673
|
+
for (const name of names) {
|
|
7674
|
+
const hook = HOOK_REGISTRY[name];
|
|
7675
|
+
if (hook) {
|
|
7676
|
+
hooks.push(hook);
|
|
7677
|
+
continue;
|
|
7678
|
+
}
|
|
7679
|
+
const customFactory = customHooks[name];
|
|
7680
|
+
if (customFactory) {
|
|
7681
|
+
const customHook = await customFactory();
|
|
7682
|
+
if (customHook) hooks.push(customHook);
|
|
8059
7683
|
}
|
|
8060
|
-
if (newSelectors.length === 0) return [];
|
|
8061
|
-
return currentElements.filter((el) => newSelectors.includes(el.selector));
|
|
8062
7684
|
}
|
|
8063
|
-
|
|
8064
|
-
|
|
8065
|
-
|
|
8066
|
-
|
|
8067
|
-
|
|
8068
|
-
|
|
8069
|
-
|
|
8070
|
-
|
|
8071
|
-
|
|
8072
|
-
|
|
8073
|
-
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
8078
|
-
|
|
8079
|
-
|
|
8080
|
-
|
|
8081
|
-
|
|
8082
|
-
|
|
8083
|
-
|
|
7685
|
+
return hooks;
|
|
7686
|
+
}
|
|
7687
|
+
|
|
7688
|
+
// src/fail-codes.ts
|
|
7689
|
+
var FAIL_CODES = {
|
|
7690
|
+
selectorNotFound: "RETRYABLE: selector-not-found",
|
|
7691
|
+
pageNotReady: "RETRYABLE: page-not-ready",
|
|
7692
|
+
elementGone: "RETRYABLE: element-gone",
|
|
7693
|
+
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
7694
|
+
captcha: "HUMAN: captcha",
|
|
7695
|
+
loginWall: "HUMAN: login-wall",
|
|
7696
|
+
permissionDenied: "FATAL: permission-denied",
|
|
7697
|
+
targetGone: "FATAL: target-gone",
|
|
7698
|
+
unknown: "FATAL: unknown"
|
|
7699
|
+
};
|
|
7700
|
+
function classifyFailure(message) {
|
|
7701
|
+
const msg = (message || "").toLowerCase();
|
|
7702
|
+
const pick = (code) => ({
|
|
7703
|
+
code,
|
|
7704
|
+
level: code.split(":")[0],
|
|
7705
|
+
message: message || code
|
|
7706
|
+
});
|
|
7707
|
+
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
7708
|
+
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
7709
|
+
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
7710
|
+
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
7711
|
+
return pick(FAIL_CODES.selectorNotFound);
|
|
7712
|
+
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
7713
|
+
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
7714
|
+
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
7715
|
+
return pick(FAIL_CODES.targetGone);
|
|
7716
|
+
return pick(FAIL_CODES.unknown);
|
|
7717
|
+
}
|
|
7718
|
+
|
|
7719
|
+
// src/lib/mistake-ledger.ts
|
|
7720
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
|
|
7721
|
+
import { homedir as homedir5 } from "os";
|
|
7722
|
+
import { join as join7 } from "path";
|
|
7723
|
+
var MISTAKE_THRESHOLD = 3;
|
|
7724
|
+
var MISTAKE_LEDGER_PATH = join7(
|
|
7725
|
+
homedir5(),
|
|
7726
|
+
".xbrowser",
|
|
7727
|
+
"knowledge",
|
|
7728
|
+
"mistakes.json"
|
|
7729
|
+
);
|
|
7730
|
+
function emptyLedger() {
|
|
7731
|
+
return { version: 1, entries: {} };
|
|
7732
|
+
}
|
|
7733
|
+
function normalizeMistakeText(value) {
|
|
7734
|
+
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();
|
|
7735
|
+
}
|
|
7736
|
+
function mistakeFingerprint(category, message) {
|
|
7737
|
+
return `${category}::${normalizeMistakeText(message)}`;
|
|
7738
|
+
}
|
|
7739
|
+
function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
|
|
7740
|
+
try {
|
|
7741
|
+
const parsed = JSON.parse(readFileSync5(path2, "utf8"));
|
|
7742
|
+
if (parsed.version !== 1 || typeof parsed.entries !== "object") {
|
|
7743
|
+
return emptyLedger();
|
|
8084
7744
|
}
|
|
8085
|
-
|
|
8086
|
-
|
|
8087
|
-
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
|
|
8091
|
-
|
|
8092
|
-
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
|
|
8096
|
-
|
|
7745
|
+
return parsed;
|
|
7746
|
+
} catch {
|
|
7747
|
+
return emptyLedger();
|
|
7748
|
+
}
|
|
7749
|
+
}
|
|
7750
|
+
function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
|
|
7751
|
+
mkdirSync4(join7(path2, ".."), { recursive: true });
|
|
7752
|
+
writeFileSync4(path2, JSON.stringify(ledger, null, 2), "utf8");
|
|
7753
|
+
}
|
|
7754
|
+
function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
|
|
7755
|
+
if (!input.category) throw new Error("mistake category is required");
|
|
7756
|
+
if (!input.command) throw new Error("mistake command is required");
|
|
7757
|
+
if (!input.message) throw new Error("mistake message is required");
|
|
7758
|
+
const ledger = readMistakeLedger(path2);
|
|
7759
|
+
const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
|
|
7760
|
+
const previous = ledger.entries[fingerprint];
|
|
7761
|
+
const occurrence = {
|
|
7762
|
+
timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
7763
|
+
command: input.command,
|
|
7764
|
+
message: input.message,
|
|
7765
|
+
...input.context ? { context: input.context } : {}
|
|
7766
|
+
};
|
|
7767
|
+
const entry = previous ? {
|
|
7768
|
+
...previous,
|
|
7769
|
+
lastSeen: occurrence.timestamp,
|
|
7770
|
+
occurrences: [...previous.occurrences, occurrence].slice(-100),
|
|
7771
|
+
constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
|
|
7772
|
+
} : {
|
|
7773
|
+
fingerprint,
|
|
7774
|
+
category: input.category,
|
|
7775
|
+
firstSeen: occurrence.timestamp,
|
|
7776
|
+
lastSeen: occurrence.timestamp,
|
|
7777
|
+
occurrences: [occurrence],
|
|
7778
|
+
constrained: false
|
|
7779
|
+
};
|
|
7780
|
+
ledger.entries[fingerprint] = entry;
|
|
7781
|
+
writeMistakeLedger(ledger, path2);
|
|
7782
|
+
return {
|
|
7783
|
+
entry,
|
|
7784
|
+
newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
|
|
7785
|
+
};
|
|
7786
|
+
}
|
|
7787
|
+
|
|
7788
|
+
// src/executor/foundation.ts
|
|
7789
|
+
import { homedir as homedir7 } from "os";
|
|
7790
|
+
import { join as join9 } from "path";
|
|
7791
|
+
import {
|
|
7792
|
+
CompositeStorage as CompositeStorage2,
|
|
7793
|
+
configureArchiveStore,
|
|
7794
|
+
appendCommandToArchive,
|
|
7795
|
+
fail as fail17,
|
|
7796
|
+
checkGuard
|
|
7797
|
+
} from "@dyyz1993/xcli-core";
|
|
7798
|
+
|
|
7799
|
+
// src/plugin/loader.ts
|
|
7800
|
+
import {
|
|
7801
|
+
Core
|
|
7802
|
+
} from "@dyyz1993/xcli-core";
|
|
7803
|
+
import { resolve as resolve2, basename, dirname as dirname3 } from "path";
|
|
7804
|
+
import { existsSync as existsSync7, readdirSync } from "fs";
|
|
7805
|
+
import { homedir as homedir6 } from "os";
|
|
7806
|
+
|
|
7807
|
+
// src/plugin/metadata-parser.ts
|
|
7808
|
+
import { existsSync as existsSync5 } from "fs";
|
|
7809
|
+
import { resolve } from "path";
|
|
7810
|
+
|
|
7811
|
+
// src/utils/json-file.ts
|
|
7812
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
|
|
7813
|
+
function readJsonFile(filePath, defaultValue) {
|
|
7814
|
+
try {
|
|
7815
|
+
const content = readFileSync6(filePath, "utf-8");
|
|
7816
|
+
return JSON.parse(content);
|
|
7817
|
+
} catch {
|
|
7818
|
+
return defaultValue;
|
|
8097
7819
|
}
|
|
8098
|
-
|
|
8099
|
-
|
|
8100
|
-
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8104
|
-
|
|
8105
|
-
|
|
8106
|
-
|
|
8107
|
-
suggestions.push(`click "${el.selector}"`);
|
|
8108
|
-
}
|
|
8109
|
-
if (el.category === "toast" || el.category === "notification") {
|
|
8110
|
-
suggestions.push(`text "${el.selector}"`);
|
|
7820
|
+
}
|
|
7821
|
+
|
|
7822
|
+
// src/plugin/metadata-parser.ts
|
|
7823
|
+
var PluginMetadataParser = class {
|
|
7824
|
+
static XBROWSER_KEYWORDS = ["xbrowser", "xbrowser-plugin"];
|
|
7825
|
+
static parseFromPackageJson(pluginPath) {
|
|
7826
|
+
const packageJsonPath = resolve(pluginPath, "package.json");
|
|
7827
|
+
if (!existsSync5(packageJsonPath)) {
|
|
7828
|
+
return null;
|
|
8111
7829
|
}
|
|
8112
|
-
|
|
8113
|
-
|
|
7830
|
+
const packageJson = readJsonFile(packageJsonPath, null);
|
|
7831
|
+
if (!packageJson) return null;
|
|
7832
|
+
if (!packageJson.xbrowser) {
|
|
7833
|
+
return null;
|
|
8114
7834
|
}
|
|
8115
|
-
|
|
7835
|
+
const xbrowser = packageJson.xbrowser;
|
|
7836
|
+
const metadata = {
|
|
7837
|
+
id: xbrowser.id || packageJson.name,
|
|
7838
|
+
name: xbrowser.name || packageJson.name,
|
|
7839
|
+
description: xbrowser.description || packageJson.description || "",
|
|
7840
|
+
version: xbrowser.version || packageJson.version || "1.0.0",
|
|
7841
|
+
author: xbrowser.author || this.extractAuthor(packageJson.author),
|
|
7842
|
+
homepage: xbrowser.homepage || packageJson.homepage,
|
|
7843
|
+
commands: xbrowser.commands,
|
|
7844
|
+
sites: xbrowser.sites,
|
|
7845
|
+
tags: xbrowser.tags,
|
|
7846
|
+
screenshot: xbrowser.screenshot,
|
|
7847
|
+
license: xbrowser.license || packageJson.license
|
|
7848
|
+
};
|
|
7849
|
+
return metadata;
|
|
8116
7850
|
}
|
|
8117
|
-
|
|
8118
|
-
|
|
8119
|
-
|
|
8120
|
-
return `${base} button:has-text("${kw}"), ${base} [role="button"]:has-text("${kw}")`;
|
|
7851
|
+
static isXBrowserPlugin(packageJson) {
|
|
7852
|
+
if (packageJson.xbrowser) {
|
|
7853
|
+
return true;
|
|
8121
7854
|
}
|
|
8122
|
-
|
|
7855
|
+
const keywords = packageJson.keywords;
|
|
7856
|
+
if (!keywords) return false;
|
|
7857
|
+
return this.XBROWSER_KEYWORDS.some((kw) => keywords.includes(kw));
|
|
8123
7858
|
}
|
|
8124
|
-
|
|
8125
|
-
const
|
|
8126
|
-
|
|
8127
|
-
|
|
8128
|
-
|
|
8129
|
-
|
|
8130
|
-
|
|
8131
|
-
|
|
8132
|
-
|
|
8133
|
-
|
|
8134
|
-
|
|
7859
|
+
static fromNPMResult(result) {
|
|
7860
|
+
const author = typeof result.author === "string" ? result.author : result.author?.name || "Unknown";
|
|
7861
|
+
return {
|
|
7862
|
+
id: result.name,
|
|
7863
|
+
name: result.name.replace(/^xbrowser-plugin-/, "").replace(/^@[^/]+\//, ""),
|
|
7864
|
+
description: result.description || "",
|
|
7865
|
+
version: result.version,
|
|
7866
|
+
author,
|
|
7867
|
+
homepage: result.homepage || result.links?.homepage,
|
|
7868
|
+
tags: result.keywords,
|
|
7869
|
+
license: ""
|
|
8135
7870
|
};
|
|
8136
|
-
return labels[category] || "\u5F39\u7A97";
|
|
8137
7871
|
}
|
|
8138
|
-
|
|
8139
|
-
|
|
8140
|
-
if (
|
|
8141
|
-
|
|
7872
|
+
static extractAuthor(author) {
|
|
7873
|
+
if (typeof author === "string") return author;
|
|
7874
|
+
if (typeof author === "object" && author !== null) {
|
|
7875
|
+
const authorObj = author;
|
|
7876
|
+
return authorObj.name || "Unknown";
|
|
7877
|
+
}
|
|
7878
|
+
return "Unknown";
|
|
8142
7879
|
}
|
|
8143
|
-
|
|
8144
|
-
|
|
7880
|
+
static validateMetadata(metadata) {
|
|
7881
|
+
const errors = [];
|
|
7882
|
+
if (!metadata.id) errors.push("id is required");
|
|
7883
|
+
if (!metadata.name) errors.push("name is required");
|
|
7884
|
+
if (!metadata.description) errors.push("description is required");
|
|
7885
|
+
if (!metadata.version) errors.push("version is required");
|
|
7886
|
+
return errors;
|
|
8145
7887
|
}
|
|
8146
7888
|
};
|
|
8147
|
-
function buildSnapshot(elements) {
|
|
8148
|
-
return {
|
|
8149
|
-
timestamp: Date.now(),
|
|
8150
|
-
overlaySelectors: elements.map((el) => el.selector)
|
|
8151
|
-
};
|
|
8152
|
-
}
|
|
8153
7889
|
|
|
8154
|
-
// src/
|
|
8155
|
-
|
|
8156
|
-
|
|
8157
|
-
|
|
8158
|
-
|
|
8159
|
-
|
|
8160
|
-
"
|
|
8161
|
-
|
|
8162
|
-
|
|
8163
|
-
|
|
8164
|
-
|
|
8165
|
-
|
|
8166
|
-
"
|
|
8167
|
-
|
|
8168
|
-
|
|
8169
|
-
// detect 命令本身不需要检测
|
|
8170
|
-
"history",
|
|
8171
|
-
// history 命令不需要检测
|
|
8172
|
-
"viewer"
|
|
8173
|
-
// viewer 命令不需要检测
|
|
8174
|
-
]);
|
|
8175
|
-
var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
|
|
8176
|
-
"click",
|
|
8177
|
-
"fill",
|
|
8178
|
-
"type",
|
|
8179
|
-
"select",
|
|
8180
|
-
"check",
|
|
8181
|
-
"uncheck",
|
|
8182
|
-
"hover",
|
|
8183
|
-
"dblclick"
|
|
8184
|
-
]);
|
|
8185
|
-
var TipsManager = class {
|
|
8186
|
-
domWatcher = null;
|
|
8187
|
-
contextTracker = new ContextTracker();
|
|
8188
|
-
generator = new TipGenerator(this.contextTracker);
|
|
8189
|
-
beforeSnapshot = null;
|
|
8190
|
-
lastDetectionTime = 0;
|
|
8191
|
-
async beforeCommand(page, commandName, params) {
|
|
8192
|
-
this.contextTracker.record(commandName, params);
|
|
8193
|
-
if (!this.domWatcher) {
|
|
8194
|
-
this.domWatcher = new DomWatcher(page);
|
|
8195
|
-
}
|
|
7890
|
+
// src/plugin/ensure-deps.ts
|
|
7891
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
|
|
7892
|
+
import { join as join8 } from "path";
|
|
7893
|
+
import { execSync } from "child_process";
|
|
7894
|
+
var SHARED_PLUGIN_DEPENDENCIES = {
|
|
7895
|
+
"zod": "^3.24.0",
|
|
7896
|
+
"@dyyz1993/xcli-core": "^0.19.0"
|
|
7897
|
+
};
|
|
7898
|
+
function ensurePluginDependencies(pluginsDir) {
|
|
7899
|
+
const zodPath = join8(pluginsDir, "node_modules", "zod");
|
|
7900
|
+
if (existsSync6(zodPath)) return;
|
|
7901
|
+
mkdirSync5(pluginsDir, { recursive: true });
|
|
7902
|
+
const pkgPath = join8(pluginsDir, "package.json");
|
|
7903
|
+
let pkg = {};
|
|
7904
|
+
if (existsSync6(pkgPath)) {
|
|
8196
7905
|
try {
|
|
8197
|
-
|
|
8198
|
-
const elements = await this.domWatcher.scanOverlays();
|
|
8199
|
-
this.beforeSnapshot = buildSnapshot(elements);
|
|
7906
|
+
pkg = readJsonFile(pkgPath, {});
|
|
8200
7907
|
} catch {
|
|
8201
|
-
this.beforeSnapshot = { timestamp: Date.now(), overlaySelectors: [] };
|
|
8202
|
-
}
|
|
8203
|
-
if (INTERACTION_COMMANDS.has(commandName) && !SKIP_DETECT_COMMANDS.has(commandName)) {
|
|
8204
|
-
await this.checkAntiBot(page, commandName);
|
|
8205
7908
|
}
|
|
8206
7909
|
}
|
|
8207
|
-
|
|
8208
|
-
|
|
8209
|
-
|
|
8210
|
-
|
|
8211
|
-
|
|
8212
|
-
|
|
8213
|
-
return;
|
|
8214
|
-
}
|
|
8215
|
-
this.lastDetectionTime = now;
|
|
8216
|
-
const config = {
|
|
8217
|
-
checkCaptcha: true,
|
|
8218
|
-
checkWarning: true,
|
|
8219
|
-
checkBlocked: true,
|
|
8220
|
-
checkWebdriver: true
|
|
8221
|
-
};
|
|
8222
|
-
const result = await detectAntiBot(page, config);
|
|
8223
|
-
if (result.detected && result.severity === "high") {
|
|
8224
|
-
const message = formatDetectionMessage(result);
|
|
8225
|
-
console.error(`
|
|
8226
|
-
\u{1F6A8} ${message}
|
|
8227
|
-
`);
|
|
8228
|
-
console.log("\u{1F4A1} Action blocked. To continue:");
|
|
8229
|
-
console.log(" 1. Use viewer mode: xbrowser viewer --json");
|
|
8230
|
-
console.log(" 2. Or skip detection with --skip-detect flag\n");
|
|
8231
|
-
throw new Error(`Anti-bot detection blocked: ${result.message}`);
|
|
7910
|
+
const existingDeps = pkg.dependencies || {};
|
|
7911
|
+
let needsInstall = false;
|
|
7912
|
+
for (const [dep, version] of Object.entries(SHARED_PLUGIN_DEPENDENCIES)) {
|
|
7913
|
+
if (!existingDeps[dep]) {
|
|
7914
|
+
existingDeps[dep] = version;
|
|
7915
|
+
needsInstall = true;
|
|
8232
7916
|
}
|
|
8233
7917
|
}
|
|
8234
|
-
|
|
8235
|
-
|
|
8236
|
-
|
|
8237
|
-
|
|
8238
|
-
|
|
8239
|
-
|
|
8240
|
-
|
|
8241
|
-
|
|
8242
|
-
|
|
8243
|
-
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
}
|
|
7918
|
+
if (!needsInstall && existsSync6(join8(pluginsDir, "node_modules"))) return;
|
|
7919
|
+
pkg.dependencies = existingDeps;
|
|
7920
|
+
pkg.private = true;
|
|
7921
|
+
pkg.description = pkg.description || "xbrowser plugins \u2014 shared dependencies";
|
|
7922
|
+
writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
|
|
7923
|
+
try {
|
|
7924
|
+
execSync("npm install --production --no-package-lock --no-fund --no-audit", {
|
|
7925
|
+
cwd: pluginsDir,
|
|
7926
|
+
stdio: "pipe",
|
|
7927
|
+
timeout: 6e4,
|
|
7928
|
+
env: { ...process.env, NODE_ENV: "production" }
|
|
7929
|
+
});
|
|
7930
|
+
} catch (err) {
|
|
7931
|
+
console.warn(`\u26A0\uFE0F Failed to install shared plugin dependencies: ${err instanceof Error ? err.message : String(err)}`);
|
|
8248
7932
|
}
|
|
8249
|
-
|
|
8250
|
-
|
|
8251
|
-
|
|
8252
|
-
|
|
7933
|
+
}
|
|
7934
|
+
|
|
7935
|
+
// src/plugin/contract.ts
|
|
7936
|
+
import {
|
|
7937
|
+
unwrapZod,
|
|
7938
|
+
fieldsFromZodObjectReflected,
|
|
7939
|
+
zodTypeToContractType
|
|
7940
|
+
} from "@dyyz1993/xcli-core";
|
|
7941
|
+
function buildPluginContract(site) {
|
|
7942
|
+
const commands = site.getAllCommands().map((command) => buildCommandContract(site.getCommand?.(command.name) || command, {
|
|
7943
|
+
siteRequiresLogin: site.config?.requiresLogin
|
|
7944
|
+
}));
|
|
7945
|
+
return {
|
|
7946
|
+
version: 2,
|
|
7947
|
+
plugin: {
|
|
7948
|
+
name: site.name,
|
|
7949
|
+
url: site.url,
|
|
7950
|
+
description: site.config?.description,
|
|
7951
|
+
requiresLogin: site.config?.requiresLogin
|
|
7952
|
+
},
|
|
7953
|
+
commands
|
|
7954
|
+
};
|
|
7955
|
+
}
|
|
7956
|
+
function buildCommandContract(command, options = {}) {
|
|
7957
|
+
const extension = command.xbrowser || {};
|
|
7958
|
+
const inferredFields = fieldsFromZodObject(command.parameters);
|
|
7959
|
+
const fields = mergeFields(inferredFields, extension.form?.fields || []);
|
|
7960
|
+
const positional = extension.positional || fields.filter((field) => field.positional).map((field) => field.name);
|
|
7961
|
+
const requiresLogin = command.requiresLogin === true || options.siteRequiresLogin === true && command.name !== "login" && command.name !== "logout";
|
|
7962
|
+
const capabilities = extension.capabilities || inferCapabilities(command.scope || "project", requiresLogin);
|
|
7963
|
+
const outputSchema = command.result ? summarizeZod(command.result) : void 0;
|
|
7964
|
+
return {
|
|
7965
|
+
name: command.name,
|
|
7966
|
+
description: command.description || "",
|
|
7967
|
+
scope: command.scope || "project",
|
|
7968
|
+
requiresLogin,
|
|
7969
|
+
category: extension.category,
|
|
7970
|
+
capabilities,
|
|
7971
|
+
positional,
|
|
7972
|
+
form: {
|
|
7973
|
+
title: extension.form?.title || command.description || command.name,
|
|
7974
|
+
description: extension.form?.description,
|
|
7975
|
+
submitLabel: extension.form?.submitLabel || "Run",
|
|
7976
|
+
fields
|
|
7977
|
+
},
|
|
7978
|
+
output: extension.output || (outputSchema ? { schema: outputSchema } : void 0)
|
|
7979
|
+
};
|
|
7980
|
+
}
|
|
7981
|
+
function fieldsFromZodObject(schema) {
|
|
7982
|
+
const reflected = fieldsFromZodObjectReflected(schema);
|
|
7983
|
+
return reflected.map((field) => {
|
|
7984
|
+
const widget = widgetFor(field.type, field.enum);
|
|
7985
|
+
return {
|
|
7986
|
+
name: field.name,
|
|
7987
|
+
label: toLabel(field.name),
|
|
7988
|
+
type: field.type,
|
|
7989
|
+
widget,
|
|
7990
|
+
required: field.required,
|
|
7991
|
+
...field.description ? { description: field.description } : {},
|
|
7992
|
+
...field.default !== void 0 ? { default: field.default } : {},
|
|
7993
|
+
...field.enum ? { enum: field.enum } : {},
|
|
7994
|
+
...field.type === "array" ? { multiple: true } : {}
|
|
7995
|
+
};
|
|
7996
|
+
});
|
|
7997
|
+
}
|
|
7998
|
+
function mergeFields(inferred, overrides) {
|
|
7999
|
+
if (overrides.length === 0) return inferred;
|
|
8000
|
+
const byName = new Map(inferred.map((field) => [field.name, field]));
|
|
8001
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8002
|
+
const merged = [];
|
|
8003
|
+
for (const override of overrides) {
|
|
8004
|
+
if (!override.name) continue;
|
|
8005
|
+
const base = byName.get(override.name) || {
|
|
8006
|
+
name: override.name,
|
|
8007
|
+
label: toLabel(override.name),
|
|
8008
|
+
type: "string",
|
|
8009
|
+
widget: "text",
|
|
8010
|
+
required: false
|
|
8011
|
+
};
|
|
8012
|
+
merged.push({ ...base, ...override, name: override.name });
|
|
8013
|
+
seen.add(override.name);
|
|
8253
8014
|
}
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
const lines = [tip.message];
|
|
8257
|
-
for (const s of tip.suggestions) {
|
|
8258
|
-
lines.push(` \u2192 ${s}`);
|
|
8259
|
-
}
|
|
8260
|
-
return lines.join("\n");
|
|
8261
|
-
});
|
|
8015
|
+
for (const field of inferred) {
|
|
8016
|
+
if (!seen.has(field.name)) merged.push(field);
|
|
8262
8017
|
}
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8268
|
-
|
|
8018
|
+
return merged;
|
|
8019
|
+
}
|
|
8020
|
+
function inferCapabilities(scope, requiresLogin) {
|
|
8021
|
+
const caps = [];
|
|
8022
|
+
if (scope === "page") caps.push("browser.page");
|
|
8023
|
+
if (scope === "browser") caps.push("browser.context");
|
|
8024
|
+
if (requiresLogin) caps.push("auth.login");
|
|
8025
|
+
return caps;
|
|
8026
|
+
}
|
|
8027
|
+
function widgetFor(type, enumValues) {
|
|
8028
|
+
if (enumValues) return "select";
|
|
8029
|
+
if (type === "boolean") return "checkbox";
|
|
8030
|
+
if (type === "number") return "number";
|
|
8031
|
+
if (type === "array") return "multi-select";
|
|
8032
|
+
if (type === "object") return "json";
|
|
8033
|
+
return "text";
|
|
8034
|
+
}
|
|
8035
|
+
function summarizeZod(schema) {
|
|
8036
|
+
const unwrapped = unwrapZod(schema);
|
|
8037
|
+
if (unwrapped.typeName === "ZodArray") {
|
|
8038
|
+
const def = unwrapped.schema?._def;
|
|
8039
|
+
return {
|
|
8040
|
+
type: "array",
|
|
8041
|
+
items: summarizeZod(def?.type || def?.innerType)
|
|
8042
|
+
};
|
|
8269
8043
|
}
|
|
8270
|
-
|
|
8271
|
-
|
|
8272
|
-
|
|
8273
|
-
|
|
8274
|
-
|
|
8044
|
+
const shape = getObjectShape(schema);
|
|
8045
|
+
if (!shape) {
|
|
8046
|
+
return {
|
|
8047
|
+
type: zodTypeToContractType(unwrapped.typeName),
|
|
8048
|
+
required: !unwrapped.optional,
|
|
8049
|
+
...unwrapped.description ? { description: unwrapped.description } : {}
|
|
8050
|
+
};
|
|
8275
8051
|
}
|
|
8276
|
-
return
|
|
8052
|
+
return Object.fromEntries(
|
|
8053
|
+
Object.entries(shape).map(([name, field]) => {
|
|
8054
|
+
const inner = unwrapZod(field);
|
|
8055
|
+
return [name, {
|
|
8056
|
+
type: zodTypeToContractType(inner.typeName),
|
|
8057
|
+
required: !inner.optional,
|
|
8058
|
+
...inner.description ? { description: inner.description } : {}
|
|
8059
|
+
}];
|
|
8060
|
+
})
|
|
8061
|
+
);
|
|
8062
|
+
}
|
|
8063
|
+
function getObjectShape(schema) {
|
|
8064
|
+
const zod = schema;
|
|
8065
|
+
const shapeOrFn = zod?.shape ?? zod?._def?.shape;
|
|
8066
|
+
if (!shapeOrFn) return void 0;
|
|
8067
|
+
return typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
|
|
8068
|
+
}
|
|
8069
|
+
function toLabel(name) {
|
|
8070
|
+
return name.replace(/([A-Z])/g, " $1").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (char) => char.toUpperCase());
|
|
8277
8071
|
}
|
|
8278
8072
|
|
|
8279
|
-
// src/
|
|
8280
|
-
|
|
8281
|
-
|
|
8282
|
-
|
|
8283
|
-
|
|
8284
|
-
|
|
8285
|
-
|
|
8286
|
-
|
|
8287
|
-
|
|
8288
|
-
|
|
8289
|
-
|
|
8290
|
-
|
|
8291
|
-
|
|
8292
|
-
|
|
8293
|
-
|
|
8294
|
-
|
|
8295
|
-
|
|
8296
|
-
|
|
8297
|
-
|
|
8298
|
-
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8306
|
-
|
|
8307
|
-
|
|
8308
|
-
|
|
8309
|
-
|
|
8310
|
-
|
|
8311
|
-
|
|
8312
|
-
|
|
8073
|
+
// src/plugin/login-required-patch.ts
|
|
8074
|
+
import { SiteInstanceImpl } from "@dyyz1993/xcli-core";
|
|
8075
|
+
var patched = false;
|
|
8076
|
+
function patchLoginRequired() {
|
|
8077
|
+
if (patched) return;
|
|
8078
|
+
patched = true;
|
|
8079
|
+
const target = SiteInstanceImpl.prototype;
|
|
8080
|
+
const originalCommand = target.command;
|
|
8081
|
+
const wrapped = function(...args) {
|
|
8082
|
+
const result = originalCommand.apply(this, args);
|
|
8083
|
+
const [name, cmd] = args;
|
|
8084
|
+
const loginRequired = cmd.loginRequired;
|
|
8085
|
+
if (loginRequired) {
|
|
8086
|
+
const commands = this.commands;
|
|
8087
|
+
const entry = commands?.get(name);
|
|
8088
|
+
if (entry) {
|
|
8089
|
+
entry.loginRequired = loginRequired;
|
|
8090
|
+
}
|
|
8091
|
+
}
|
|
8092
|
+
return result;
|
|
8093
|
+
};
|
|
8094
|
+
Object.defineProperty(target, "command", {
|
|
8095
|
+
value: wrapped,
|
|
8096
|
+
writable: true,
|
|
8097
|
+
configurable: true
|
|
8098
|
+
});
|
|
8099
|
+
}
|
|
8100
|
+
|
|
8101
|
+
// src/plugin/loader.ts
|
|
8102
|
+
var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
|
|
8103
|
+
var XBrowserPluginLoader = class {
|
|
8104
|
+
core;
|
|
8105
|
+
loader;
|
|
8106
|
+
options;
|
|
8107
|
+
/** 目录名 → 该插件注册的 site 名(site.name ≠ 目录名时的命令别名兜底) */
|
|
8108
|
+
dirSiteAliases = /* @__PURE__ */ new Map();
|
|
8109
|
+
constructor(options) {
|
|
8110
|
+
patchLoginRequired();
|
|
8111
|
+
globalThis.__xbrowserRecordMistake = recordMistake;
|
|
8112
|
+
this.options = options ?? {};
|
|
8113
|
+
const cwd = this.options.cwd || process.cwd();
|
|
8114
|
+
const coreConfig = {
|
|
8115
|
+
name: "xbrowser",
|
|
8116
|
+
version: "0.1.0",
|
|
8117
|
+
description: "Browser automation CLI",
|
|
8118
|
+
configDirName: ".xbrowser",
|
|
8119
|
+
envPrefix: "XBROWSER",
|
|
8120
|
+
pluginDirs: [
|
|
8121
|
+
...DEFAULT_PLUGIN_DIRS,
|
|
8122
|
+
resolve2(cwd, ".xcli/plugins")
|
|
8123
|
+
]
|
|
8124
|
+
};
|
|
8125
|
+
this.core = new Core(coreConfig);
|
|
8126
|
+
this.loader = this.core.loader;
|
|
8127
|
+
}
|
|
8128
|
+
getAPI() {
|
|
8129
|
+
return this.loader.getAPI();
|
|
8130
|
+
}
|
|
8131
|
+
/**
|
|
8132
|
+
* Get the core instance for external use.
|
|
8133
|
+
* @returns The xcli-core Core instance.
|
|
8134
|
+
*/
|
|
8135
|
+
getCore() {
|
|
8136
|
+
return this.core;
|
|
8137
|
+
}
|
|
8138
|
+
getPlugin(id) {
|
|
8139
|
+
return this.loader.getPlugin(id);
|
|
8140
|
+
}
|
|
8141
|
+
getPluginStatus(id) {
|
|
8142
|
+
return this.loader.getPluginStatus(id);
|
|
8143
|
+
}
|
|
8144
|
+
getLoadedPlugins() {
|
|
8145
|
+
return this.loader.getLoadedPlugins();
|
|
8146
|
+
}
|
|
8147
|
+
/**
|
|
8148
|
+
* 目录名别名兜底(小白用户实测踩坑):`plugin list` 显示目录名,但命令路由
|
|
8149
|
+
* 按 site.name 匹配——两者不一致时(如目录 alibaba-1688、site 名 1688),
|
|
8150
|
+
* 用户按 list 显示的名字敲命令会 "Unknown command"。映射在 scanAndLoad/
|
|
8151
|
+
* loadPlugin 时通过加载前后 site 快照 diff 记录(instance.siteName 返回的是
|
|
8152
|
+
* 插件 id 而非 site 名,不可用)。
|
|
8153
|
+
*/
|
|
8154
|
+
resolveSiteName(name) {
|
|
8155
|
+
if (this.core.loader.getSite(name)) return name;
|
|
8156
|
+
const aliased = this.dirSiteAliases.get(name);
|
|
8157
|
+
if (aliased && this.core.loader.getSite(aliased)) return aliased;
|
|
8158
|
+
return void 0;
|
|
8159
|
+
}
|
|
8160
|
+
/** 记录一次插件加载引入的 site:加载前后快照 diff(同插件可注册多个 site) */
|
|
8161
|
+
recordSiteAliases(pluginDirName, before) {
|
|
8162
|
+
for (const site of this.core.loader.getSites()) {
|
|
8163
|
+
if (!before.has(site.name)) this.dirSiteAliases.set(pluginDirName, site.name);
|
|
8164
|
+
}
|
|
8165
|
+
}
|
|
8166
|
+
getPluginContract(siteName, commandName) {
|
|
8167
|
+
const resolved = this.resolveSiteName(siteName);
|
|
8168
|
+
if (!resolved) return void 0;
|
|
8169
|
+
const site = this.core.loader.getSite(resolved);
|
|
8170
|
+
if (!site) return void 0;
|
|
8171
|
+
const contract = buildPluginContract(site);
|
|
8172
|
+
if (!commandName) return contract;
|
|
8173
|
+
return contract.commands.find((command) => command.name === commandName);
|
|
8174
|
+
}
|
|
8175
|
+
async loadPlugin(pluginPath, id) {
|
|
8176
|
+
const before = new Set(this.core.loader.getSites().map((s) => s.name));
|
|
8177
|
+
const instance = await this.loader.loadPlugin(pluginPath, id);
|
|
8178
|
+
this.recordSiteAliases(basename(dirname3(pluginPath)), before);
|
|
8179
|
+
return instance;
|
|
8180
|
+
}
|
|
8181
|
+
async unloadPlugin(id) {
|
|
8182
|
+
return this.loader.unloadPlugin(id);
|
|
8183
|
+
}
|
|
8184
|
+
async reloadPlugin(id) {
|
|
8185
|
+
return this.loader.reloadPlugin(id);
|
|
8186
|
+
}
|
|
8187
|
+
async loadFromFunction(setup) {
|
|
8188
|
+
return this.loader.loadFromFunction(setup);
|
|
8189
|
+
}
|
|
8190
|
+
async scanAndLoad() {
|
|
8191
|
+
const cwd = this.options.cwd || process.cwd();
|
|
8192
|
+
const globalDir = this.options.globalDir || resolve2(homedir6(), ".xbrowser/plugins");
|
|
8193
|
+
ensurePluginDependencies(globalDir);
|
|
8194
|
+
const dirs = [
|
|
8195
|
+
resolve2(cwd, ".xcli/plugins"),
|
|
8196
|
+
resolve2(cwd, "../.xcli/plugins"),
|
|
8197
|
+
this.options.userDir || resolve2(homedir6(), ".xcli/plugins"),
|
|
8198
|
+
globalDir
|
|
8199
|
+
];
|
|
8200
|
+
const loaded = [];
|
|
8201
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8202
|
+
for (const dir of dirs) {
|
|
8203
|
+
if (!existsSync7(dir)) continue;
|
|
8204
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
8205
|
+
for (const entry of entries) {
|
|
8206
|
+
if (!entry.isDirectory()) continue;
|
|
8207
|
+
if (seen.has(entry.name)) continue;
|
|
8208
|
+
seen.add(entry.name);
|
|
8209
|
+
const pluginDir = resolve2(dir, entry.name);
|
|
8210
|
+
let indexPath = resolve2(pluginDir, "index.js");
|
|
8211
|
+
if (!existsSync7(indexPath)) {
|
|
8212
|
+
indexPath = resolve2(pluginDir, "index.ts");
|
|
8213
|
+
}
|
|
8214
|
+
if (!existsSync7(indexPath)) continue;
|
|
8215
|
+
try {
|
|
8216
|
+
if (!existsSync7(resolve2(pluginDir, "package.json"))) {
|
|
8217
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
|
|
8218
|
+
} else {
|
|
8219
|
+
const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
|
|
8220
|
+
if (!metadata) {
|
|
8221
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has package.json but no xbrowser metadata. Add { "xbrowser": { "description": "..." } } to package.json.`);
|
|
8222
|
+
}
|
|
8223
|
+
}
|
|
8224
|
+
const instance = await this.loadPlugin(indexPath, entry.name);
|
|
8225
|
+
loaded.push(instance);
|
|
8226
|
+
} catch (err) {
|
|
8227
|
+
const errMsg2 = err instanceof Error ? err.message : String(err);
|
|
8228
|
+
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" load failed: ${errMsg2}`);
|
|
8229
|
+
if (errMsg2.includes("Cannot find module") && errMsg2.includes("shared/")) {
|
|
8230
|
+
console.warn(` \u{1F4A1} This plugin needs shared/ dependencies. Try: xbrowser plugin install shared`);
|
|
8231
|
+
}
|
|
8232
|
+
}
|
|
8233
|
+
}
|
|
8234
|
+
}
|
|
8235
|
+
return loaded;
|
|
8236
|
+
}
|
|
8237
|
+
async unload() {
|
|
8238
|
+
return this.loader.unload();
|
|
8239
|
+
}
|
|
8240
|
+
};
|
|
8241
|
+
|
|
8242
|
+
// src/utils/plugin-singleton.ts
|
|
8243
|
+
var pluginLoader = null;
|
|
8244
|
+
var pluginsScanned = false;
|
|
8245
|
+
function silenceSchemaWarnings(fn) {
|
|
8246
|
+
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
8247
|
+
const originalWarn = console.warn;
|
|
8248
|
+
console.warn = (...args) => {
|
|
8249
|
+
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
8250
|
+
if (msg.includes('has no "result" schema')) return;
|
|
8251
|
+
originalWarn(...args);
|
|
8252
|
+
};
|
|
8253
|
+
return fn().finally(() => {
|
|
8254
|
+
console.warn = originalWarn;
|
|
8255
|
+
});
|
|
8256
|
+
}
|
|
8257
|
+
async function getPluginLoader() {
|
|
8258
|
+
if (!pluginLoader) {
|
|
8259
|
+
pluginLoader = new XBrowserPluginLoader();
|
|
8260
|
+
}
|
|
8261
|
+
if (!pluginsScanned) {
|
|
8262
|
+
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
8263
|
+
pluginsScanned = true;
|
|
8264
|
+
}
|
|
8265
|
+
return pluginLoader;
|
|
8266
|
+
}
|
|
8267
|
+
|
|
8268
|
+
// src/executor/foundation.ts
|
|
8269
|
+
var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
|
|
8270
|
+
var snapshotHintShown = /* @__PURE__ */ new WeakSet();
|
|
8271
|
+
var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
|
|
8272
|
+
var storageCache = /* @__PURE__ */ new Map();
|
|
8273
|
+
function getPluginStorage(pluginName) {
|
|
8274
|
+
if (!storageCache.has(pluginName)) {
|
|
8275
|
+
storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
|
|
8276
|
+
}
|
|
8277
|
+
return storageCache.get(pluginName);
|
|
8278
|
+
}
|
|
8279
|
+
var archiveInitialized = false;
|
|
8280
|
+
function ensureArchiveInit() {
|
|
8281
|
+
if (!archiveInitialized) {
|
|
8282
|
+
try {
|
|
8283
|
+
configureArchiveStore({ archiveDir: join9(homedir7(), ".xbrowser", "archives") });
|
|
8284
|
+
} catch {
|
|
8285
|
+
}
|
|
8286
|
+
archiveInitialized = true;
|
|
8287
|
+
}
|
|
8288
|
+
}
|
|
8289
|
+
function recordArchive(sessionId, sessionName, entry) {
|
|
8290
|
+
if (!sessionId) return;
|
|
8291
|
+
try {
|
|
8292
|
+
ensureArchiveInit();
|
|
8293
|
+
appendCommandToArchive(sessionId, sessionName, entry);
|
|
8294
|
+
} catch {
|
|
8295
|
+
}
|
|
8296
|
+
}
|
|
8297
|
+
async function guardCheck(commandName) {
|
|
8298
|
+
try {
|
|
8299
|
+
const loader = await getPluginLoader();
|
|
8300
|
+
return checkGuard(loader.getCore(), commandName, process.env);
|
|
8301
|
+
} catch {
|
|
8302
|
+
return null;
|
|
8303
|
+
}
|
|
8304
|
+
}
|
|
8305
|
+
function errorResult(message) {
|
|
8306
|
+
return { ...fail17(message), duration: 0 };
|
|
8307
|
+
}
|
|
8308
|
+
function tipsToMessages(tips) {
|
|
8309
|
+
if (!tips || tips.length === 0) return [];
|
|
8310
|
+
return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
|
|
8311
|
+
}
|
|
8312
|
+
var wsServer = null;
|
|
8313
|
+
function streamCommandEvent(sessionId, message) {
|
|
8314
|
+
if (!wsServer || !wsServer.getRunning()) return;
|
|
8315
|
+
wsServer.broadcastToSession(sessionId, { type: "command", data: message });
|
|
8316
|
+
}
|
|
8317
|
+
|
|
8318
|
+
// src/executor/chain.ts
|
|
8319
|
+
import {
|
|
8320
|
+
fail as fail18,
|
|
8321
|
+
ok as ok32,
|
|
8322
|
+
TipCollector as TipCollector2,
|
|
8323
|
+
normalizeTips as normalizeTips7,
|
|
8324
|
+
unquote as unquote2
|
|
8325
|
+
} from "@dyyz1993/xcli-core";
|
|
8326
|
+
|
|
8327
|
+
// src/plugin/login-guard.ts
|
|
8328
|
+
async function checkPluginLoginRequired(options) {
|
|
8329
|
+
const { site, command, commandName, ctx, page, sessionName } = options;
|
|
8330
|
+
if (commandName === "login" || commandName === "logout") return { ok: true };
|
|
8331
|
+
const loginConfig = site.config?.loginConfig;
|
|
8332
|
+
const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
|
|
8333
|
+
if (!requiresLogin) return { ok: true };
|
|
8334
|
+
const pluginName = site.name || "plugin";
|
|
8335
|
+
const siteConfig = site.config;
|
|
8336
|
+
const configIsLogin = siteConfig?.isLogin;
|
|
8337
|
+
if (configIsLogin) {
|
|
8338
|
+
try {
|
|
8339
|
+
const loggedIn = await configIsLogin(ctx);
|
|
8340
|
+
if (loggedIn) return { ok: true };
|
|
8341
|
+
return buildLoginRequired({
|
|
8342
|
+
plugin: pluginName,
|
|
8343
|
+
command: commandName,
|
|
8344
|
+
reason: "config.isLogin returned false",
|
|
8345
|
+
sessionName,
|
|
8346
|
+
loginConfig
|
|
8347
|
+
});
|
|
8348
|
+
} catch {
|
|
8349
|
+
}
|
|
8350
|
+
}
|
|
8351
|
+
if (typeof site.isLoggedIn === "function") {
|
|
8352
|
+
try {
|
|
8353
|
+
const loggedIn = await site.isLoggedIn(ctx);
|
|
8354
|
+
if (loggedIn) return { ok: true };
|
|
8355
|
+
return buildLoginRequired({
|
|
8356
|
+
plugin: pluginName,
|
|
8357
|
+
command: commandName,
|
|
8358
|
+
reason: "plugin isLoggedIn returned false",
|
|
8359
|
+
sessionName,
|
|
8360
|
+
loginConfig
|
|
8361
|
+
});
|
|
8362
|
+
} catch {
|
|
8363
|
+
}
|
|
8364
|
+
}
|
|
8365
|
+
if (page && loginConfig) {
|
|
8366
|
+
const generic = await detectLoginFromPage(page, loginConfig);
|
|
8367
|
+
if (generic === "logged-in") return { ok: true };
|
|
8368
|
+
if (generic === "logged-out") {
|
|
8369
|
+
return buildLoginRequired({
|
|
8370
|
+
plugin: pluginName,
|
|
8371
|
+
command: commandName,
|
|
8372
|
+
reason: "generic loginConfig detected logged-out page",
|
|
8373
|
+
sessionName,
|
|
8374
|
+
loginConfig
|
|
8375
|
+
});
|
|
8376
|
+
}
|
|
8377
|
+
}
|
|
8378
|
+
return { ok: true };
|
|
8379
|
+
}
|
|
8380
|
+
function buildLoginRequired(options) {
|
|
8381
|
+
const viewerUrl = buildViewerUrl(options.sessionName);
|
|
8382
|
+
const loginUrl = options.loginConfig?.loginUrl;
|
|
8383
|
+
const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
|
|
8384
|
+
const tips = [
|
|
8385
|
+
message,
|
|
8386
|
+
...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
|
|
8387
|
+
...loginUrl ? [`Login page: ${loginUrl}`] : [],
|
|
8388
|
+
`After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
|
|
8389
|
+
];
|
|
8390
|
+
return {
|
|
8391
|
+
ok: false,
|
|
8392
|
+
data: {
|
|
8393
|
+
code: "LOGIN_REQUIRED",
|
|
8394
|
+
plugin: options.plugin,
|
|
8395
|
+
command: options.command,
|
|
8396
|
+
reason: options.reason,
|
|
8397
|
+
...viewerUrl ? { viewerUrl } : {},
|
|
8398
|
+
...loginUrl ? { loginUrl } : {}
|
|
8399
|
+
},
|
|
8400
|
+
message,
|
|
8401
|
+
tips
|
|
8402
|
+
};
|
|
8403
|
+
}
|
|
8404
|
+
async function detectLoginFromPage(page, config) {
|
|
8405
|
+
const url = page.url();
|
|
8406
|
+
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
8407
|
+
const result = await page.evaluate((cfg) => {
|
|
8408
|
+
const visible = (selector) => {
|
|
8409
|
+
try {
|
|
8410
|
+
const el = document.querySelector(selector);
|
|
8411
|
+
if (!el) return false;
|
|
8412
|
+
const rect = el.getBoundingClientRect();
|
|
8413
|
+
const style = window.getComputedStyle(el);
|
|
8414
|
+
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
8415
|
+
} catch {
|
|
8416
|
+
return false;
|
|
8417
|
+
}
|
|
8418
|
+
};
|
|
8419
|
+
if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
|
|
8420
|
+
if (cfg.loginSelectors?.some(visible)) return "logged-out";
|
|
8421
|
+
const bodyText = document.body?.innerText || "";
|
|
8422
|
+
const keywords = cfg.loginKeywords || [];
|
|
8423
|
+
if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
|
|
8424
|
+
return "logged-out";
|
|
8425
|
+
}
|
|
8426
|
+
return "unknown";
|
|
8427
|
+
}, {
|
|
8428
|
+
loginSelectors: config.loginSelectors || [],
|
|
8429
|
+
loginKeywords: config.loginKeywords || [],
|
|
8430
|
+
loggedInSelectors: config.loggedInSelectors || []
|
|
8431
|
+
});
|
|
8432
|
+
return result;
|
|
8433
|
+
}
|
|
8434
|
+
|
|
8435
|
+
// src/utils/positional-params.ts
|
|
8436
|
+
import { unquote } from "@dyyz1993/xcli-core";
|
|
8437
|
+
function getTypeName(field) {
|
|
8438
|
+
return field?._def?.typeName;
|
|
8439
|
+
}
|
|
8440
|
+
function unwrapField(field) {
|
|
8441
|
+
const typeName = getTypeName(field);
|
|
8442
|
+
if (typeName === "ZodOptional" || typeName === "ZodDefault") {
|
|
8443
|
+
const innerType = field?._def?.innerType;
|
|
8444
|
+
return unwrapField(innerType);
|
|
8445
|
+
}
|
|
8446
|
+
return field;
|
|
8447
|
+
}
|
|
8448
|
+
function isOptionalNumber(field) {
|
|
8449
|
+
const typeName = getTypeName(field);
|
|
8450
|
+
return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
|
|
8451
|
+
}
|
|
8452
|
+
function coerceValue(raw, field) {
|
|
8453
|
+
const inner = unwrapField(field);
|
|
8454
|
+
const optionalNum = isOptionalNumber(field);
|
|
8455
|
+
const innerTypeName = getTypeName(inner);
|
|
8456
|
+
if (innerTypeName === "ZodString") {
|
|
8457
|
+
return { value: unquote(raw), skip: false };
|
|
8458
|
+
}
|
|
8459
|
+
if (innerTypeName === "ZodNumber") {
|
|
8460
|
+
const parsed = Number(raw);
|
|
8461
|
+
if (isNaN(parsed)) {
|
|
8462
|
+
if (optionalNum) return { value: void 0, skip: true };
|
|
8463
|
+
return { value: raw, skip: false };
|
|
8464
|
+
}
|
|
8465
|
+
return { value: parsed, skip: false };
|
|
8466
|
+
}
|
|
8467
|
+
if (innerTypeName === "ZodBoolean") {
|
|
8468
|
+
if (raw === "true" || raw === "1") return { value: true, skip: false };
|
|
8469
|
+
if (raw === "false" || raw === "0") return { value: false, skip: false };
|
|
8470
|
+
return { value: raw, skip: false };
|
|
8471
|
+
}
|
|
8472
|
+
return { value: unquote(raw), skip: false };
|
|
8473
|
+
}
|
|
8474
|
+
function mapPositionalValues(schema, positional, existing) {
|
|
8475
|
+
const result = { ...existing };
|
|
8476
|
+
if (!schema || typeof schema !== "object") return result;
|
|
8477
|
+
const shape = schema.shape;
|
|
8478
|
+
if (!shape || typeof shape !== "object") return result;
|
|
8479
|
+
const keys = Object.keys(shape);
|
|
8480
|
+
let pIdx = 0;
|
|
8481
|
+
for (const key of keys) {
|
|
8482
|
+
if (pIdx >= positional.length) break;
|
|
8483
|
+
if (result[key] !== void 0) {
|
|
8484
|
+
pIdx++;
|
|
8485
|
+
continue;
|
|
8486
|
+
}
|
|
8487
|
+
const field = shape[key];
|
|
8488
|
+
const raw = positional[pIdx];
|
|
8489
|
+
const { value, skip } = coerceValue(raw, field);
|
|
8490
|
+
if (skip) continue;
|
|
8491
|
+
result[key] = value;
|
|
8492
|
+
pIdx++;
|
|
8493
|
+
}
|
|
8494
|
+
return result;
|
|
8495
|
+
}
|
|
8496
|
+
|
|
8497
|
+
// src/utils/plugin-params.ts
|
|
8498
|
+
function schemaFieldType(schema, key) {
|
|
8499
|
+
const shape = schema?.shape;
|
|
8500
|
+
const field = shape?.[key];
|
|
8501
|
+
let current = field;
|
|
8502
|
+
while (current) {
|
|
8503
|
+
const def = current._def;
|
|
8504
|
+
if (!def) return void 0;
|
|
8505
|
+
const type = def.typeName ?? def.type;
|
|
8506
|
+
if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
|
|
8507
|
+
current = def.innerType ?? def.inner;
|
|
8508
|
+
continue;
|
|
8509
|
+
}
|
|
8510
|
+
return type;
|
|
8511
|
+
}
|
|
8512
|
+
return void 0;
|
|
8513
|
+
}
|
|
8514
|
+
function parsePluginParams(args, schema, base = {}) {
|
|
8515
|
+
const params = { ...base };
|
|
8516
|
+
const positionalValues = [];
|
|
8517
|
+
for (let i = 0; i < args.length; i++) {
|
|
8518
|
+
if (args[i] === "--" && args[i + 1]) {
|
|
8519
|
+
try {
|
|
8520
|
+
Object.assign(params, JSON.parse(args[i + 1]));
|
|
8521
|
+
} catch {
|
|
8522
|
+
}
|
|
8523
|
+
break;
|
|
8524
|
+
}
|
|
8525
|
+
if (args[i].startsWith("--")) {
|
|
8526
|
+
const key = args[i].slice(2);
|
|
8527
|
+
const value = args[i + 1];
|
|
8528
|
+
if (value && !value.startsWith("-")) {
|
|
8529
|
+
const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
|
|
8530
|
+
if (type === "ZodString" || type === "string") params[key] = value;
|
|
8531
|
+
else if (value === "true") params[key] = true;
|
|
8532
|
+
else if (value === "false") params[key] = false;
|
|
8533
|
+
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
8534
|
+
else {
|
|
8535
|
+
try {
|
|
8536
|
+
const parsed = JSON.parse(value);
|
|
8537
|
+
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
8538
|
+
params[key] = parsed;
|
|
8539
|
+
} else {
|
|
8540
|
+
params[key] = value;
|
|
8541
|
+
}
|
|
8542
|
+
} catch {
|
|
8543
|
+
params[key] = value;
|
|
8544
|
+
}
|
|
8545
|
+
}
|
|
8546
|
+
i++;
|
|
8547
|
+
} else {
|
|
8548
|
+
params[key] = true;
|
|
8549
|
+
}
|
|
8550
|
+
} else if (!args[i].startsWith("-")) {
|
|
8551
|
+
positionalValues.push(args[i]);
|
|
8552
|
+
}
|
|
8553
|
+
}
|
|
8554
|
+
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
8555
|
+
const result = {};
|
|
8556
|
+
for (const [k, v] of Object.entries(params)) {
|
|
8557
|
+
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
8558
|
+
result[camelKey] = v;
|
|
8559
|
+
}
|
|
8560
|
+
return result;
|
|
8561
|
+
}
|
|
8562
|
+
|
|
8563
|
+
// src/executor/chain.ts
|
|
8564
|
+
async function executeChain(input, options, executeCommand2) {
|
|
8565
|
+
const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
|
|
8566
|
+
const sessionName = options?.sessionName || "default";
|
|
8567
|
+
const results = [];
|
|
8568
|
+
const totalStart = Date.now();
|
|
8569
|
+
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8570
|
+
if (!session) {
|
|
8571
|
+
const launchOpts = {};
|
|
8572
|
+
if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
8573
|
+
session = await createSession(sessionName, void 0, launchOpts);
|
|
8574
|
+
saveSessionDiskMeta(sessionName, {
|
|
8575
|
+
id: session.id,
|
|
8576
|
+
name: sessionName,
|
|
8577
|
+
url: session.page.url(),
|
|
8578
|
+
createdAt: session.createdAt,
|
|
8579
|
+
cdpEndpoint: session.cdpEndpoint
|
|
8580
|
+
});
|
|
8581
|
+
}
|
|
8582
|
+
try {
|
|
8583
|
+
for (const pipeline of pipelines) {
|
|
8584
|
+
const { type, pipeline: commands } = pipeline;
|
|
8585
|
+
for (const cmdStr of commands) {
|
|
8586
|
+
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
8587
|
+
await new Promise((resolve3) => setTimeout(resolve3, 800 + Math.random() * 1700));
|
|
8588
|
+
}
|
|
8589
|
+
const parts = splitCommand(cmdStr);
|
|
8590
|
+
if (parts.length === 0) continue;
|
|
8591
|
+
const cmdName = parts[0];
|
|
8592
|
+
const cmdArgs = parts.slice(1);
|
|
8593
|
+
const loader = await getPluginLoader();
|
|
8594
|
+
const internalLoader = loader.getCore().loader;
|
|
8595
|
+
const resolvedName = loader.resolveSiteName(cmdName);
|
|
8596
|
+
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
8597
|
+
if (site) {
|
|
8598
|
+
const pluginHandled = await executePluginChainStep({
|
|
8599
|
+
site,
|
|
8600
|
+
cmdName,
|
|
8601
|
+
cmdArgs,
|
|
8602
|
+
cmdStr,
|
|
8603
|
+
type,
|
|
8604
|
+
results,
|
|
8605
|
+
totalStart,
|
|
8606
|
+
session,
|
|
8607
|
+
sessionName
|
|
8608
|
+
});
|
|
8609
|
+
if (pluginHandled) return pluginHandled;
|
|
8610
|
+
continue;
|
|
8611
|
+
}
|
|
8612
|
+
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
8613
|
+
if (cmdName === "goto" && params.url) {
|
|
8614
|
+
const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8615
|
+
if (!existing) {
|
|
8616
|
+
session = await createSession(sessionName, params.url, {
|
|
8617
|
+
cdpEndpoint: options?.cdpEndpoint
|
|
8618
|
+
});
|
|
8619
|
+
}
|
|
8620
|
+
}
|
|
8621
|
+
const result = await executeCommand2(cmdName, params, sessionName, {
|
|
8622
|
+
cdpEndpoint: options?.cdpEndpoint,
|
|
8623
|
+
skipCleanup: true
|
|
8624
|
+
});
|
|
8625
|
+
results.push({
|
|
8626
|
+
command: cmdName,
|
|
8627
|
+
raw: cmdStr,
|
|
8628
|
+
success: result.success,
|
|
8629
|
+
data: result.data,
|
|
8630
|
+
message: result.message,
|
|
8631
|
+
duration: 0,
|
|
8632
|
+
tips: result.tips,
|
|
8633
|
+
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
8634
|
+
});
|
|
8635
|
+
if (type === "and" && !result.success) {
|
|
8636
|
+
return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
|
|
8637
|
+
}
|
|
8638
|
+
if (type === "or" && result.success) {
|
|
8639
|
+
return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
|
|
8640
|
+
}
|
|
8313
8641
|
}
|
|
8314
|
-
result.tips = tips;
|
|
8315
|
-
result.viewerUrl = viewerUrl;
|
|
8316
|
-
return void 0;
|
|
8317
8642
|
}
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8643
|
+
return {
|
|
8644
|
+
success: !results.some((result) => !result.success),
|
|
8645
|
+
steps: results,
|
|
8646
|
+
totalDuration: Date.now() - totalStart
|
|
8647
|
+
};
|
|
8648
|
+
} finally {
|
|
8649
|
+
}
|
|
8650
|
+
}
|
|
8651
|
+
function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
|
|
8652
|
+
return {
|
|
8653
|
+
success,
|
|
8654
|
+
steps,
|
|
8655
|
+
totalDuration: Date.now() - totalStart,
|
|
8656
|
+
stoppedAt,
|
|
8657
|
+
stoppedReason: reason
|
|
8658
|
+
};
|
|
8659
|
+
}
|
|
8660
|
+
async function executePluginChainStep(context) {
|
|
8661
|
+
const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
|
|
8662
|
+
const subCommand = cmdArgs[0];
|
|
8663
|
+
if (!subCommand) {
|
|
8664
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
|
|
8665
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
|
|
8666
|
+
return void 0;
|
|
8667
|
+
}
|
|
8668
|
+
const cmdEntry = site.getCommand(subCommand);
|
|
8669
|
+
if (!cmdEntry) {
|
|
8670
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
|
|
8671
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
|
|
8672
|
+
return void 0;
|
|
8673
|
+
}
|
|
8674
|
+
const pluginArgs = cmdArgs.slice(1);
|
|
8675
|
+
const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
8676
|
+
if (cmdEntry.parameters) {
|
|
8677
|
+
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
8678
|
+
if (schemaCheck.success) {
|
|
8679
|
+
for (const [key, value] of Object.entries(schemaCheck.data)) {
|
|
8680
|
+
if (!(key in pluginParams)) pluginParams[key] = value;
|
|
8328
8681
|
}
|
|
8329
8682
|
}
|
|
8330
|
-
}
|
|
8331
|
-
|
|
8332
|
-
|
|
8333
|
-
|
|
8334
|
-
|
|
8335
|
-
|
|
8336
|
-
|
|
8337
|
-
|
|
8338
|
-
|
|
8339
|
-
|
|
8683
|
+
}
|
|
8684
|
+
const pluginCtx = {
|
|
8685
|
+
args: pluginArgs,
|
|
8686
|
+
options: pluginParams,
|
|
8687
|
+
cwd: process.cwd(),
|
|
8688
|
+
page: session.page,
|
|
8689
|
+
browser: session.context.browser(),
|
|
8690
|
+
browserContext: session.context,
|
|
8691
|
+
sessionId: session.id,
|
|
8692
|
+
storage: getPluginStorage(cmdName),
|
|
8693
|
+
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
8694
|
+
error: (message) => {
|
|
8695
|
+
throw new Error(message);
|
|
8696
|
+
},
|
|
8697
|
+
config: {},
|
|
8698
|
+
site,
|
|
8699
|
+
cliName: "xbrowser",
|
|
8700
|
+
tips: new TipCollector2()
|
|
8701
|
+
};
|
|
8702
|
+
const start = Date.now();
|
|
8703
|
+
try {
|
|
8704
|
+
const loginGuard = await checkPluginLoginRequired({
|
|
8705
|
+
site,
|
|
8706
|
+
command: cmdEntry,
|
|
8707
|
+
commandName: subCommand,
|
|
8708
|
+
ctx: pluginCtx,
|
|
8709
|
+
page: session.page,
|
|
8710
|
+
sessionName
|
|
8711
|
+
});
|
|
8712
|
+
if (!loginGuard.ok) {
|
|
8713
|
+
const duration2 = Date.now() - start;
|
|
8714
|
+
const data2 = loginGuard.data ?? null;
|
|
8715
|
+
recordArchive(session.id, sessionName, {
|
|
8716
|
+
step: results.length,
|
|
8717
|
+
command: `${cmdName} ${subCommand}`,
|
|
8718
|
+
params: pluginParams,
|
|
8719
|
+
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
8720
|
+
toolCalls: [],
|
|
8721
|
+
duration: duration2,
|
|
8722
|
+
timestamp: start
|
|
8340
8723
|
});
|
|
8341
|
-
|
|
8724
|
+
results.push({
|
|
8725
|
+
command: `${cmdName} ${subCommand}`,
|
|
8726
|
+
raw: cmdStr,
|
|
8727
|
+
success: false,
|
|
8728
|
+
data: data2,
|
|
8729
|
+
message: loginGuard.message,
|
|
8730
|
+
tips: normalizeTips7(loginGuard.tips),
|
|
8731
|
+
duration: duration2
|
|
8732
|
+
});
|
|
8733
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
|
|
8342
8734
|
return void 0;
|
|
8343
8735
|
}
|
|
8344
|
-
|
|
8345
|
-
|
|
8346
|
-
|
|
8347
|
-
async function loadHooks() {
|
|
8348
|
-
const env = process.env.XBROWSER_HOOKS;
|
|
8349
|
-
if (!env) return [];
|
|
8350
|
-
const names = env.split(",").map((n) => n.trim()).filter(Boolean);
|
|
8351
|
-
if (names.length === 0) return [];
|
|
8352
|
-
const hooks = [];
|
|
8353
|
-
for (const name of names) {
|
|
8354
|
-
const hook = HOOK_REGISTRY[name];
|
|
8355
|
-
if (hook) {
|
|
8356
|
-
hooks.push(hook);
|
|
8357
|
-
continue;
|
|
8736
|
+
const hooks = await loadHooks();
|
|
8737
|
+
if (hooks.length > 0) {
|
|
8738
|
+
await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
8358
8739
|
}
|
|
8359
|
-
const
|
|
8360
|
-
|
|
8361
|
-
|
|
8362
|
-
|
|
8740
|
+
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
8741
|
+
const duration = Date.now() - start;
|
|
8742
|
+
let hookOutputs;
|
|
8743
|
+
if (hooks.length > 0) {
|
|
8744
|
+
const outputs = [];
|
|
8745
|
+
for (const hook of hooks) {
|
|
8746
|
+
const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
|
|
8747
|
+
if (output) outputs.push({ _hook: hook.name, ...output });
|
|
8748
|
+
}
|
|
8749
|
+
if (outputs.length > 0) hookOutputs = outputs;
|
|
8363
8750
|
}
|
|
8751
|
+
const data = raw?.data ?? raw;
|
|
8752
|
+
recordArchive(session.id, sessionName, {
|
|
8753
|
+
step: results.length,
|
|
8754
|
+
command: `${cmdName} ${subCommand}`,
|
|
8755
|
+
params: pluginParams,
|
|
8756
|
+
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
8757
|
+
toolCalls: [],
|
|
8758
|
+
duration,
|
|
8759
|
+
timestamp: start
|
|
8760
|
+
});
|
|
8761
|
+
results.push({
|
|
8762
|
+
command: `${cmdName} ${subCommand}`,
|
|
8763
|
+
raw: cmdStr,
|
|
8764
|
+
...ok32(data),
|
|
8765
|
+
duration,
|
|
8766
|
+
...hookOutputs ? { hookOutputs } : {}
|
|
8767
|
+
});
|
|
8768
|
+
if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
|
|
8769
|
+
} catch (error) {
|
|
8770
|
+
const duration = Date.now() - start;
|
|
8771
|
+
const message = errMsg(error);
|
|
8772
|
+
recordArchive(session.id, sessionName, {
|
|
8773
|
+
step: results.length,
|
|
8774
|
+
command: `${cmdName} ${subCommand}`,
|
|
8775
|
+
params: pluginParams,
|
|
8776
|
+
result: { success: false, data: null, message, tips: [] },
|
|
8777
|
+
toolCalls: [],
|
|
8778
|
+
duration,
|
|
8779
|
+
timestamp: start
|
|
8780
|
+
});
|
|
8781
|
+
results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
|
|
8782
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
|
|
8364
8783
|
}
|
|
8365
|
-
return
|
|
8784
|
+
return void 0;
|
|
8366
8785
|
}
|
|
8367
8786
|
|
|
8368
8787
|
// src/executor.ts
|
|
8369
|
-
import { homedir as homedir6 } from "os";
|
|
8370
|
-
import { join as join8 } from "path";
|
|
8371
8788
|
function levenshtein(a, b) {
|
|
8372
8789
|
const m = a.length, n = b.length;
|
|
8373
8790
|
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
@@ -8375,63 +8792,11 @@ function levenshtein(a, b) {
|
|
|
8375
8792
|
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
8376
8793
|
for (let i = 1; i <= m; i++) {
|
|
8377
8794
|
for (let j = 1; j <= n; j++) {
|
|
8378
|
-
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j
|
|
8795
|
+
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]);
|
|
8379
8796
|
}
|
|
8380
8797
|
}
|
|
8381
8798
|
return dp[m][n];
|
|
8382
8799
|
}
|
|
8383
|
-
var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
|
|
8384
|
-
var snapshotHintShown = /* @__PURE__ */ new WeakSet();
|
|
8385
|
-
var CONFIG_DIR2 = join8(homedir6(), ".xbrowser");
|
|
8386
|
-
var storageCache = /* @__PURE__ */ new Map();
|
|
8387
|
-
function getPluginStorage(pluginName) {
|
|
8388
|
-
if (!storageCache.has(pluginName)) {
|
|
8389
|
-
storageCache.set(pluginName, new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"));
|
|
8390
|
-
}
|
|
8391
|
-
return storageCache.get(pluginName);
|
|
8392
|
-
}
|
|
8393
|
-
var archiveInitialized = false;
|
|
8394
|
-
function ensureArchiveInit() {
|
|
8395
|
-
if (!archiveInitialized) {
|
|
8396
|
-
try {
|
|
8397
|
-
configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
|
|
8398
|
-
} catch {
|
|
8399
|
-
}
|
|
8400
|
-
archiveInitialized = true;
|
|
8401
|
-
}
|
|
8402
|
-
}
|
|
8403
|
-
function recordArchive(sessionId, sessionName, entry) {
|
|
8404
|
-
if (!sessionId) return;
|
|
8405
|
-
try {
|
|
8406
|
-
ensureArchiveInit();
|
|
8407
|
-
appendCommandToArchive(sessionId, sessionName, entry);
|
|
8408
|
-
} catch {
|
|
8409
|
-
}
|
|
8410
|
-
}
|
|
8411
|
-
async function guardCheck(commandName) {
|
|
8412
|
-
try {
|
|
8413
|
-
const loader = await getPluginLoader();
|
|
8414
|
-
const core = loader.getCore();
|
|
8415
|
-
return checkGuard(core, commandName, process.env);
|
|
8416
|
-
} catch {
|
|
8417
|
-
return null;
|
|
8418
|
-
}
|
|
8419
|
-
}
|
|
8420
|
-
function errorResult(message) {
|
|
8421
|
-
return { ...fail17(message), duration: 0 };
|
|
8422
|
-
}
|
|
8423
|
-
function tipsToMessages(tips) {
|
|
8424
|
-
if (!tips || tips.length === 0) return [];
|
|
8425
|
-
return tips.map((t) => typeof t === "string" ? t : t.message);
|
|
8426
|
-
}
|
|
8427
|
-
var wsServer = null;
|
|
8428
|
-
function streamCommandEvent(sessionId, message) {
|
|
8429
|
-
if (!wsServer || !wsServer.getRunning()) return;
|
|
8430
|
-
wsServer.broadcastToSession(sessionId, {
|
|
8431
|
-
type: "command",
|
|
8432
|
-
data: message
|
|
8433
|
-
});
|
|
8434
|
-
}
|
|
8435
8800
|
async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
|
|
8436
8801
|
const guardResult = await guardCheck(commandName);
|
|
8437
8802
|
if (guardResult?.blocked) {
|
|
@@ -8479,8 +8844,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8479
8844
|
if (knownPlugins.includes(commandName)) {
|
|
8480
8845
|
hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
|
|
8481
8846
|
}
|
|
8847
|
+
const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
|
|
8848
|
+
recordMistake({
|
|
8849
|
+
category: classifyFailure(message).code,
|
|
8850
|
+
command: commandName,
|
|
8851
|
+
message,
|
|
8852
|
+
context: { sessionName, params }
|
|
8853
|
+
});
|
|
8482
8854
|
return errorResult(
|
|
8483
|
-
|
|
8855
|
+
message
|
|
8484
8856
|
);
|
|
8485
8857
|
}
|
|
8486
8858
|
const _target = params._target;
|
|
@@ -8495,7 +8867,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8495
8867
|
}
|
|
8496
8868
|
let targetPageOverride = null;
|
|
8497
8869
|
if (_target && extraOpts?.cdpEndpoint) {
|
|
8498
|
-
const { findTargetPage } = await import("./browser-
|
|
8870
|
+
const { findTargetPage } = await import("./browser-2K3XYAKM.js");
|
|
8499
8871
|
targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
|
|
8500
8872
|
if (!targetPageOverride) {
|
|
8501
8873
|
return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
|
|
@@ -8513,7 +8885,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8513
8885
|
}
|
|
8514
8886
|
if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
|
|
8515
8887
|
const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
|
|
8516
|
-
const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
|
|
8888
|
+
const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
|
|
8517
8889
|
const result = await forwardExec(
|
|
8518
8890
|
commandName,
|
|
8519
8891
|
params,
|
|
@@ -8575,7 +8947,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8575
8947
|
config: {},
|
|
8576
8948
|
site: new NoopSiteInstance(),
|
|
8577
8949
|
cliName: "xbrowser",
|
|
8578
|
-
tips: new
|
|
8950
|
+
tips: new TipCollector3()
|
|
8579
8951
|
};
|
|
8580
8952
|
attachDetectAntiBot(ctx);
|
|
8581
8953
|
if (_tabIndex !== void 0 && session?.context) {
|
|
@@ -8607,7 +8979,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8607
8979
|
const cache = /* @__PURE__ */ new Map();
|
|
8608
8980
|
const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
|
|
8609
8981
|
if (resolved.tips.length > 0) {
|
|
8610
|
-
refTips =
|
|
8982
|
+
refTips = normalizeTips8(resolved.tips);
|
|
8611
8983
|
params = resolved.params;
|
|
8612
8984
|
}
|
|
8613
8985
|
}
|
|
@@ -8675,11 +9047,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8675
9047
|
}
|
|
8676
9048
|
const merged = [
|
|
8677
9049
|
...raw.tips || [],
|
|
8678
|
-
...
|
|
8679
|
-
...snapshotHint ?
|
|
9050
|
+
...normalizeTips8(smartTips),
|
|
9051
|
+
...snapshotHint ? normalizeTips8([snapshotHint]) : [],
|
|
8680
9052
|
...refTips
|
|
8681
9053
|
];
|
|
8682
9054
|
const isSuccess = raw.success !== false;
|
|
9055
|
+
if (!isSuccess) {
|
|
9056
|
+
recordMistake({
|
|
9057
|
+
category: classifyFailure(raw.message).code,
|
|
9058
|
+
command: commandName,
|
|
9059
|
+
message: raw.message ?? "unknown command failure",
|
|
9060
|
+
context: { sessionName, params }
|
|
9061
|
+
});
|
|
9062
|
+
}
|
|
8683
9063
|
const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
|
|
8684
9064
|
recordArchive(session?.id, sessionName, {
|
|
8685
9065
|
step: 0,
|
|
@@ -8691,7 +9071,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8691
9071
|
timestamp: start
|
|
8692
9072
|
});
|
|
8693
9073
|
if (isSuccess) {
|
|
8694
|
-
return { ...
|
|
9074
|
+
return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
8695
9075
|
}
|
|
8696
9076
|
const fc = classifyFailure(raw.message);
|
|
8697
9077
|
return {
|
|
@@ -8704,7 +9084,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8704
9084
|
...hookOutputs ? { hookOutputs } : {}
|
|
8705
9085
|
};
|
|
8706
9086
|
}
|
|
8707
|
-
const smartTipNormalized =
|
|
9087
|
+
const smartTipNormalized = normalizeTips8(smartTips);
|
|
8708
9088
|
recordArchive(session?.id, sessionName, {
|
|
8709
9089
|
step: 0,
|
|
8710
9090
|
command: commandName,
|
|
@@ -8714,11 +9094,17 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8714
9094
|
duration,
|
|
8715
9095
|
timestamp: start
|
|
8716
9096
|
});
|
|
8717
|
-
return { ...
|
|
9097
|
+
return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
8718
9098
|
} catch (err) {
|
|
8719
9099
|
const end = Date.now();
|
|
8720
9100
|
const duration = end - start;
|
|
8721
9101
|
const errorMessage = errMsg(err);
|
|
9102
|
+
recordMistake({
|
|
9103
|
+
category: classifyFailure(errorMessage).code,
|
|
9104
|
+
command: commandName,
|
|
9105
|
+
message: errorMessage,
|
|
9106
|
+
context: { sessionName, params }
|
|
9107
|
+
});
|
|
8722
9108
|
if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
|
|
8723
9109
|
try {
|
|
8724
9110
|
const { attemptRecovery } = await import("./recovery-EBKORYEU.js");
|
|
@@ -8759,301 +9145,33 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8759
9145
|
duration,
|
|
8760
9146
|
timestamp: start
|
|
8761
9147
|
});
|
|
8762
|
-
return { ...
|
|
9148
|
+
return { ...fail19(errorMessage), duration };
|
|
8763
9149
|
} finally {
|
|
8764
9150
|
}
|
|
8765
9151
|
}
|
|
8766
|
-
async function
|
|
8767
|
-
|
|
8768
|
-
const sessionName = options?.sessionName || "default";
|
|
8769
|
-
const results = [];
|
|
8770
|
-
const totalStart = Date.now();
|
|
8771
|
-
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8772
|
-
if (!session) {
|
|
8773
|
-
const launchOpts = {};
|
|
8774
|
-
if (options?.cdpEndpoint) {
|
|
8775
|
-
launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
8776
|
-
}
|
|
8777
|
-
session = await createSession(sessionName, void 0, launchOpts);
|
|
8778
|
-
saveSessionDiskMeta(sessionName, {
|
|
8779
|
-
id: session.id,
|
|
8780
|
-
name: sessionName,
|
|
8781
|
-
url: session.page.url(),
|
|
8782
|
-
createdAt: session.createdAt,
|
|
8783
|
-
cdpEndpoint: session.cdpEndpoint
|
|
8784
|
-
});
|
|
8785
|
-
}
|
|
8786
|
-
try {
|
|
8787
|
-
for (const pipeline of pipelines) {
|
|
8788
|
-
const { type, pipeline: commands } = pipeline;
|
|
8789
|
-
for (const cmdStr of commands) {
|
|
8790
|
-
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
8791
|
-
await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
|
|
8792
|
-
}
|
|
8793
|
-
const parts = splitCommand(cmdStr);
|
|
8794
|
-
if (parts.length === 0) continue;
|
|
8795
|
-
const cmdName = parts[0];
|
|
8796
|
-
const cmdArgs = parts.slice(1);
|
|
8797
|
-
const loader = await getPluginLoader();
|
|
8798
|
-
const internalLoader = loader.getCore().loader;
|
|
8799
|
-
const resolvedName = loader.resolveSiteName(cmdName);
|
|
8800
|
-
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
8801
|
-
if (site) {
|
|
8802
|
-
const subCommand = cmdArgs[0];
|
|
8803
|
-
if (!subCommand) {
|
|
8804
|
-
results.push({
|
|
8805
|
-
command: cmdName,
|
|
8806
|
-
raw: cmdStr,
|
|
8807
|
-
...fail17(`Plugin "${cmdName}" requires a sub-command`),
|
|
8808
|
-
duration: 0
|
|
8809
|
-
});
|
|
8810
|
-
if (type === "and") {
|
|
8811
|
-
return {
|
|
8812
|
-
success: false,
|
|
8813
|
-
steps: results,
|
|
8814
|
-
totalDuration: Date.now() - totalStart,
|
|
8815
|
-
stoppedAt: results.length,
|
|
8816
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
|
|
8817
|
-
};
|
|
8818
|
-
}
|
|
8819
|
-
continue;
|
|
8820
|
-
}
|
|
8821
|
-
const cmdEntry = site.getCommand(subCommand);
|
|
8822
|
-
if (!cmdEntry) {
|
|
8823
|
-
results.push({
|
|
8824
|
-
command: cmdName,
|
|
8825
|
-
raw: cmdStr,
|
|
8826
|
-
...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
|
|
8827
|
-
duration: 0
|
|
8828
|
-
});
|
|
8829
|
-
if (type === "and") {
|
|
8830
|
-
return {
|
|
8831
|
-
success: false,
|
|
8832
|
-
steps: results,
|
|
8833
|
-
totalDuration: Date.now() - totalStart,
|
|
8834
|
-
stoppedAt: results.length,
|
|
8835
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
|
|
8836
|
-
};
|
|
8837
|
-
}
|
|
8838
|
-
continue;
|
|
8839
|
-
}
|
|
8840
|
-
const pluginArgs = cmdArgs.slice(1);
|
|
8841
|
-
let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
8842
|
-
if (cmdEntry.parameters) {
|
|
8843
|
-
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
8844
|
-
if (schemaCheck.success) {
|
|
8845
|
-
for (const [k, v] of Object.entries(schemaCheck.data)) {
|
|
8846
|
-
if (!(k in pluginParams)) pluginParams[k] = v;
|
|
8847
|
-
}
|
|
8848
|
-
}
|
|
8849
|
-
}
|
|
8850
|
-
const pluginCtx = {
|
|
8851
|
-
args: pluginArgs,
|
|
8852
|
-
options: pluginParams,
|
|
8853
|
-
cwd: process.cwd(),
|
|
8854
|
-
page: session.page,
|
|
8855
|
-
browser: session.context.browser(),
|
|
8856
|
-
browserContext: session.context,
|
|
8857
|
-
sessionId: session.id,
|
|
8858
|
-
storage: getPluginStorage(cmdName),
|
|
8859
|
-
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
8860
|
-
error: (msg) => {
|
|
8861
|
-
throw new Error(msg);
|
|
8862
|
-
},
|
|
8863
|
-
config: {},
|
|
8864
|
-
site,
|
|
8865
|
-
cliName: "xbrowser",
|
|
8866
|
-
tips: new TipCollector2()
|
|
8867
|
-
};
|
|
8868
|
-
const start2 = Date.now();
|
|
8869
|
-
try {
|
|
8870
|
-
const loginGuard = await checkPluginLoginRequired({
|
|
8871
|
-
site,
|
|
8872
|
-
command: cmdEntry,
|
|
8873
|
-
commandName: subCommand,
|
|
8874
|
-
ctx: pluginCtx,
|
|
8875
|
-
page: session?.page,
|
|
8876
|
-
sessionName
|
|
8877
|
-
});
|
|
8878
|
-
if (!loginGuard.ok) {
|
|
8879
|
-
const duration3 = Date.now() - start2;
|
|
8880
|
-
const data2 = loginGuard.data ?? null;
|
|
8881
|
-
recordArchive(session.id, sessionName, {
|
|
8882
|
-
step: results.length,
|
|
8883
|
-
command: `${cmdName} ${subCommand}`,
|
|
8884
|
-
params: pluginParams,
|
|
8885
|
-
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
8886
|
-
toolCalls: [],
|
|
8887
|
-
duration: duration3,
|
|
8888
|
-
timestamp: start2
|
|
8889
|
-
});
|
|
8890
|
-
results.push({
|
|
8891
|
-
command: `${cmdName} ${subCommand}`,
|
|
8892
|
-
raw: cmdStr,
|
|
8893
|
-
success: false,
|
|
8894
|
-
data: data2,
|
|
8895
|
-
message: loginGuard.message,
|
|
8896
|
-
tips: normalizeTips7(loginGuard.tips),
|
|
8897
|
-
duration: duration3
|
|
8898
|
-
});
|
|
8899
|
-
if (type === "and") {
|
|
8900
|
-
return {
|
|
8901
|
-
success: false,
|
|
8902
|
-
steps: results,
|
|
8903
|
-
totalDuration: Date.now() - totalStart,
|
|
8904
|
-
stoppedAt: results.length,
|
|
8905
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
|
|
8906
|
-
};
|
|
8907
|
-
}
|
|
8908
|
-
continue;
|
|
8909
|
-
}
|
|
8910
|
-
const hooks = await loadHooks();
|
|
8911
|
-
if (hooks.length > 0) {
|
|
8912
|
-
await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
8913
|
-
}
|
|
8914
|
-
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
8915
|
-
const duration2 = Date.now() - start2;
|
|
8916
|
-
let hookOutputs;
|
|
8917
|
-
if (hooks.length > 0) {
|
|
8918
|
-
const outputs = [];
|
|
8919
|
-
for (const h of hooks) {
|
|
8920
|
-
const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
|
|
8921
|
-
if (output) outputs.push({ _hook: h.name, ...output });
|
|
8922
|
-
}
|
|
8923
|
-
if (outputs.length > 0) hookOutputs = outputs;
|
|
8924
|
-
}
|
|
8925
|
-
const data = raw?.data ?? raw;
|
|
8926
|
-
recordArchive(session.id, sessionName, {
|
|
8927
|
-
step: results.length,
|
|
8928
|
-
command: `${cmdName} ${subCommand}`,
|
|
8929
|
-
params: pluginParams,
|
|
8930
|
-
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
8931
|
-
toolCalls: [],
|
|
8932
|
-
duration: duration2,
|
|
8933
|
-
timestamp: start2
|
|
8934
|
-
});
|
|
8935
|
-
results.push({
|
|
8936
|
-
command: `${cmdName} ${subCommand}`,
|
|
8937
|
-
raw: cmdStr,
|
|
8938
|
-
...ok32(data),
|
|
8939
|
-
duration: duration2,
|
|
8940
|
-
...hookOutputs ? { hookOutputs } : {}
|
|
8941
|
-
});
|
|
8942
|
-
if (type === "or") {
|
|
8943
|
-
return {
|
|
8944
|
-
success: true,
|
|
8945
|
-
steps: results,
|
|
8946
|
-
totalDuration: Date.now() - totalStart,
|
|
8947
|
-
stoppedAt: results.length,
|
|
8948
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
|
|
8949
|
-
};
|
|
8950
|
-
}
|
|
8951
|
-
} catch (err) {
|
|
8952
|
-
const duration2 = Date.now() - start2;
|
|
8953
|
-
const errorMessage = errMsg(err);
|
|
8954
|
-
recordArchive(session.id, sessionName, {
|
|
8955
|
-
step: results.length,
|
|
8956
|
-
command: `${cmdName} ${subCommand}`,
|
|
8957
|
-
params: pluginParams,
|
|
8958
|
-
result: { success: false, data: null, message: errorMessage, tips: [] },
|
|
8959
|
-
toolCalls: [],
|
|
8960
|
-
duration: duration2,
|
|
8961
|
-
timestamp: start2
|
|
8962
|
-
});
|
|
8963
|
-
results.push({
|
|
8964
|
-
command: `${cmdName} ${subCommand}`,
|
|
8965
|
-
raw: cmdStr,
|
|
8966
|
-
...fail17(errorMessage),
|
|
8967
|
-
duration: duration2
|
|
8968
|
-
});
|
|
8969
|
-
if (type === "and") {
|
|
8970
|
-
return {
|
|
8971
|
-
success: false,
|
|
8972
|
-
steps: results,
|
|
8973
|
-
totalDuration: Date.now() - totalStart,
|
|
8974
|
-
stoppedAt: results.length,
|
|
8975
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
|
|
8976
|
-
};
|
|
8977
|
-
}
|
|
8978
|
-
}
|
|
8979
|
-
continue;
|
|
8980
|
-
}
|
|
8981
|
-
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
8982
|
-
if (cmdName === "goto" && params.url) {
|
|
8983
|
-
const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
8984
|
-
if (!existing2) {
|
|
8985
|
-
session = await createSession(sessionName, params.url, {
|
|
8986
|
-
cdpEndpoint: options?.cdpEndpoint
|
|
8987
|
-
});
|
|
8988
|
-
}
|
|
8989
|
-
}
|
|
8990
|
-
const start = Date.now();
|
|
8991
|
-
const result = await executeCommand(cmdName, params, sessionName, {
|
|
8992
|
-
cdpEndpoint: options?.cdpEndpoint,
|
|
8993
|
-
skipCleanup: true
|
|
8994
|
-
// executeChain's finally handles cleanup
|
|
8995
|
-
});
|
|
8996
|
-
const duration = Date.now() - start;
|
|
8997
|
-
const stepResult = {
|
|
8998
|
-
command: cmdName,
|
|
8999
|
-
raw: cmdStr,
|
|
9000
|
-
success: result.success,
|
|
9001
|
-
data: result.data,
|
|
9002
|
-
message: result.message,
|
|
9003
|
-
duration,
|
|
9004
|
-
tips: result.tips,
|
|
9005
|
-
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
9006
|
-
};
|
|
9007
|
-
results.push(stepResult);
|
|
9008
|
-
if (type === "and" && !result.success) {
|
|
9009
|
-
return {
|
|
9010
|
-
success: false,
|
|
9011
|
-
steps: results,
|
|
9012
|
-
totalDuration: Date.now() - totalStart,
|
|
9013
|
-
stoppedAt: results.length,
|
|
9014
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
|
|
9015
|
-
};
|
|
9016
|
-
}
|
|
9017
|
-
if (type === "or" && result.success) {
|
|
9018
|
-
return {
|
|
9019
|
-
success: true,
|
|
9020
|
-
steps: results,
|
|
9021
|
-
totalDuration: Date.now() - totalStart,
|
|
9022
|
-
stoppedAt: results.length,
|
|
9023
|
-
stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
|
|
9024
|
-
};
|
|
9025
|
-
}
|
|
9026
|
-
}
|
|
9027
|
-
}
|
|
9028
|
-
const anyFailed = results.some((r) => !r.success);
|
|
9029
|
-
return {
|
|
9030
|
-
success: !anyFailed,
|
|
9031
|
-
steps: results,
|
|
9032
|
-
totalDuration: Date.now() - totalStart
|
|
9033
|
-
};
|
|
9034
|
-
} finally {
|
|
9035
|
-
}
|
|
9152
|
+
async function executeChain2(input, options) {
|
|
9153
|
+
return executeChain(input, options, executeCommand);
|
|
9036
9154
|
}
|
|
9037
9155
|
function isChainInput(input) {
|
|
9038
9156
|
return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
|
|
9039
9157
|
}
|
|
9040
9158
|
|
|
9041
9159
|
export {
|
|
9042
|
-
parsePluginParams,
|
|
9043
9160
|
createStubContext,
|
|
9044
9161
|
getCommand,
|
|
9045
9162
|
getAllCommands,
|
|
9046
9163
|
getCommandNames,
|
|
9047
9164
|
attachDetectAntiBot,
|
|
9165
|
+
loadHooks,
|
|
9048
9166
|
readJsonFile,
|
|
9049
9167
|
PluginMetadataParser,
|
|
9050
9168
|
ensurePluginDependencies,
|
|
9051
9169
|
XBrowserPluginLoader,
|
|
9052
9170
|
getPluginLoader,
|
|
9053
|
-
checkPluginLoginRequired,
|
|
9054
|
-
loadHooks,
|
|
9055
9171
|
getPluginStorage,
|
|
9172
|
+
checkPluginLoginRequired,
|
|
9173
|
+
parsePluginParams,
|
|
9056
9174
|
executeCommand,
|
|
9057
|
-
executeChain,
|
|
9175
|
+
executeChain2 as executeChain,
|
|
9058
9176
|
isChainInput
|
|
9059
9177
|
};
|