@xbrowser/cli 1.28.0 → 1.30.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/README.md +2 -2
- package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
- package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
- package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
- package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
- package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
- package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
- package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
- package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
- package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
- package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
- package/dist/cli.js +3447 -3377
- package/dist/daemon-main.js +1240 -786
- package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
- package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
- package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
- package/dist/index.d.ts +458 -476
- package/dist/index.js +3766 -3576
- 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/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
- package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
- package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
- package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
- package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.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 +9 -3
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
resolveLaunchOpts,
|
|
10
10
|
saveSessionDiskMeta,
|
|
11
11
|
setActivePage
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-BOZTIIBT.js";
|
|
13
13
|
import {
|
|
14
14
|
detectAntiBot,
|
|
15
15
|
formatDetectionMessage
|
|
@@ -24,13 +24,13 @@ import {
|
|
|
24
24
|
rand,
|
|
25
25
|
sleep,
|
|
26
26
|
wheelDelta
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-SMYSNO4M.js";
|
|
28
28
|
import {
|
|
29
29
|
errMsg
|
|
30
30
|
} from "./chunk-GDKLH7ZY.js";
|
|
31
31
|
import {
|
|
32
32
|
createRuleEngine
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-6UJU2FJK.js";
|
|
34
34
|
|
|
35
35
|
// src/commands/command-registry.ts
|
|
36
36
|
var registry = /* @__PURE__ */ new Map();
|
|
@@ -42,6 +42,7 @@ function registerCommand(def) {
|
|
|
42
42
|
parameters: def.parameters,
|
|
43
43
|
result: def.result,
|
|
44
44
|
selectorParams: def.selectorParams,
|
|
45
|
+
examples: def.examples,
|
|
45
46
|
handler: def.handler
|
|
46
47
|
};
|
|
47
48
|
registry.set(cmd.name, cmd);
|
|
@@ -74,25 +75,6 @@ function getRefTarget(sessionKey2, ref) {
|
|
|
74
75
|
if (!session || !target) return null;
|
|
75
76
|
return { screenHash: session.screenHash, target };
|
|
76
77
|
}
|
|
77
|
-
function inheritStableRefs(key, rawTargets) {
|
|
78
|
-
const prev = sessions.get(key);
|
|
79
|
-
if (!prev || prev.targets.size === 0) {
|
|
80
|
-
return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
|
|
81
|
-
}
|
|
82
|
-
const bySelector = /* @__PURE__ */ new Map();
|
|
83
|
-
let maxId = 0;
|
|
84
|
-
for (const [ref, target] of prev.targets) {
|
|
85
|
-
bySelector.set(target.selector, ref);
|
|
86
|
-
const id = Number(ref.slice(1));
|
|
87
|
-
if (Number.isFinite(id) && id > maxId) maxId = id;
|
|
88
|
-
}
|
|
89
|
-
let next = maxId + 1;
|
|
90
|
-
return rawTargets.map((target) => {
|
|
91
|
-
const inherited = bySelector.get(target.selector);
|
|
92
|
-
if (inherited) return { ...target, ref: inherited };
|
|
93
|
-
return { ...target, ref: `e${next++}` };
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
78
|
|
|
97
79
|
// src/runtime/agent-runtime.ts
|
|
98
80
|
function sessionKey(sessionId) {
|
|
@@ -182,14 +164,6 @@ async function observePage(page, sessionId, options = {}) {
|
|
|
182
164
|
const direct = el.getAttribute("aria-label") || el.getAttribute("placeholder") || el.getAttribute("title") || input.value || el.textContent || "";
|
|
183
165
|
return direct.replace(/\s+/g, " ").trim().slice(0, 120);
|
|
184
166
|
}
|
|
185
|
-
function actionsFor(role, editable) {
|
|
186
|
-
const actions = [];
|
|
187
|
-
if (editable) actions.push("fill", "type");
|
|
188
|
-
if (role === "combobox") actions.push("select");
|
|
189
|
-
if (role === "checkbox" || role === "radio") actions.push("check");
|
|
190
|
-
actions.push("click", "hover");
|
|
191
|
-
return Array.from(new Set(actions));
|
|
192
|
-
}
|
|
193
167
|
const selector = [
|
|
194
168
|
"a[href]",
|
|
195
169
|
"button",
|
|
@@ -200,7 +174,14 @@ async function observePage(page, sessionId, options = {}) {
|
|
|
200
174
|
"label",
|
|
201
175
|
"[role]",
|
|
202
176
|
"[tabindex]",
|
|
203
|
-
'[contenteditable="true"]'
|
|
177
|
+
'[contenteditable="true"]',
|
|
178
|
+
// 非标准可交互控件:内联事件属性(agent-browser 基于 aria tree 完全不覆盖这类)。
|
|
179
|
+
// 仅抓 HTML 显式声明 onclick/onmousedown 等的元素;addEventListener 绑定的无法静态发现。
|
|
180
|
+
"[onclick]",
|
|
181
|
+
"[onmousedown]",
|
|
182
|
+
"[onmouseup]",
|
|
183
|
+
"[onmouseover]",
|
|
184
|
+
"[onkeydown]"
|
|
204
185
|
].join(",");
|
|
205
186
|
const candidates = Array.from(document.querySelectorAll(selector));
|
|
206
187
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -224,13 +205,10 @@ async function observePage(page, sessionId, options = {}) {
|
|
|
224
205
|
role,
|
|
225
206
|
name: textName(el),
|
|
226
207
|
tag,
|
|
227
|
-
visible,
|
|
228
208
|
enabled,
|
|
229
209
|
editable,
|
|
230
210
|
...checked !== void 0 ? { checked } : {},
|
|
231
|
-
...editable && input.value ? { value: input.value.slice(0, 120) } : {}
|
|
232
|
-
...visible ? { box: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) } } : {},
|
|
233
|
-
actions: actionsFor(role, editable)
|
|
211
|
+
...editable && input.value ? { value: input.value.slice(0, 120) } : {}
|
|
234
212
|
});
|
|
235
213
|
if (targets2.length >= limit) break;
|
|
236
214
|
}
|
|
@@ -244,13 +222,15 @@ async function observePage(page, sessionId, options = {}) {
|
|
|
244
222
|
{ includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
|
|
245
223
|
)
|
|
246
224
|
]);
|
|
247
|
-
const targets =
|
|
225
|
+
const targets = raw.targets.map((target, index) => ({
|
|
226
|
+
ref: `e${index + 1}`,
|
|
227
|
+
...target
|
|
228
|
+
}));
|
|
248
229
|
replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
|
|
249
230
|
return {
|
|
250
231
|
url: page.url(),
|
|
251
232
|
title,
|
|
252
233
|
screenHash: raw.screenHash,
|
|
253
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
254
234
|
targets
|
|
255
235
|
};
|
|
256
236
|
}
|
|
@@ -435,23 +415,8 @@ async function waitForPage(page, input) {
|
|
|
435
415
|
return { success: true, matched: "selector", timeout, elapsed: Date.now() - startedAt };
|
|
436
416
|
}
|
|
437
417
|
if (input.text) {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
return page.evaluate((text) => {
|
|
441
|
-
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
442
|
-
while (walker.nextNode()) {
|
|
443
|
-
if (walker.currentNode.textContent?.includes(text)) return true;
|
|
444
|
-
}
|
|
445
|
-
return false;
|
|
446
|
-
}, textToFind);
|
|
447
|
-
});
|
|
448
|
-
return {
|
|
449
|
-
success: matched,
|
|
450
|
-
matched: "text",
|
|
451
|
-
timeout,
|
|
452
|
-
elapsed: Date.now() - startedAt,
|
|
453
|
-
...matched ? {} : { message: `Timed out waiting for text: ${input.text}` }
|
|
454
|
-
};
|
|
418
|
+
await page.getByText(input.text).first().waitFor({ state: "visible", timeout });
|
|
419
|
+
return { success: true, matched: "text", timeout, elapsed: Date.now() - startedAt };
|
|
455
420
|
}
|
|
456
421
|
if (input.url) {
|
|
457
422
|
const matched = await pollUntil(timeout, pollInterval, async () => matchUrlPattern(page.url(), input.url));
|
|
@@ -864,14 +829,23 @@ var clickCommand = registerCommand({
|
|
|
864
829
|
clickCount: z2.number().optional(),
|
|
865
830
|
delay: z2.number().optional(),
|
|
866
831
|
waitCaptcha: z2.boolean().optional().default(false).describe("\u70B9\u51FB\u540E\u68C0\u6D4B captcha \u5E76\u7B49\u5F85\u89E3\u51B3"),
|
|
867
|
-
waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09")
|
|
832
|
+
waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09"),
|
|
833
|
+
frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u9009\u62E9\u5668\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u89E3\u6790\u5E76\u70B9\u51FB\uFF08\u8FDB\u7A0B\u9694\u79BB\u4E0B\u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09")
|
|
868
834
|
}),
|
|
869
835
|
result: z2.object({
|
|
870
836
|
selector: z2.string(),
|
|
871
837
|
newTab: z2.object({ url: z2.string(), title: z2.string() }).optional(),
|
|
872
|
-
captcha: z2.any().optional()
|
|
838
|
+
captcha: z2.any().optional(),
|
|
839
|
+
frame: z2.string().optional(),
|
|
840
|
+
x: z2.number().optional(),
|
|
841
|
+
y: z2.number().optional()
|
|
873
842
|
}),
|
|
874
843
|
handler: async (p, ctx) => {
|
|
844
|
+
const frameTarget = p.frame ?? ctx.frame;
|
|
845
|
+
if (frameTarget) {
|
|
846
|
+
const { x, y } = await ctx.page.clickInFrame(frameTarget, p.selector);
|
|
847
|
+
return ok2({ selector: p.selector, frame: frameTarget, x, y });
|
|
848
|
+
}
|
|
875
849
|
let detectedNewPage;
|
|
876
850
|
let cleanup;
|
|
877
851
|
if (ctx.browserContext?.on) {
|
|
@@ -962,15 +936,22 @@ var fillCommand = registerCommand({
|
|
|
962
936
|
parameters: z2.object({
|
|
963
937
|
selector: z2.string(),
|
|
964
938
|
value: z2.string(),
|
|
965
|
-
clear: z2.boolean().optional()
|
|
939
|
+
clear: z2.boolean().optional(),
|
|
940
|
+
frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u5185\u586B\u5165\uFF08\u805A\u7126\u70B9\u51FB + insertText + \u56DE\u8BFB\uFF09")
|
|
966
941
|
}),
|
|
967
942
|
result: z2.object({
|
|
968
943
|
selector: z2.string(),
|
|
969
944
|
value: z2.string(),
|
|
970
945
|
cleared: z2.boolean(),
|
|
971
|
-
reactMode: z2.boolean().optional()
|
|
946
|
+
reactMode: z2.boolean().optional(),
|
|
947
|
+
frame: z2.string().optional()
|
|
972
948
|
}),
|
|
973
949
|
handler: async (p, ctx) => {
|
|
950
|
+
const frameTarget = p.frame ?? ctx.frame;
|
|
951
|
+
if (frameTarget) {
|
|
952
|
+
const { value } = await ctx.page.fillInFrame(frameTarget, p.selector, p.value);
|
|
953
|
+
return ok2({ selector: p.selector, value, cleared: true, frame: frameTarget });
|
|
954
|
+
}
|
|
974
955
|
const page = ctx.page;
|
|
975
956
|
const shouldClear = p.clear !== false;
|
|
976
957
|
if (shouldClear) {
|
|
@@ -1157,15 +1138,22 @@ var textCommand = registerCommand({
|
|
|
1157
1138
|
scope: "page",
|
|
1158
1139
|
selectorParams: ["selector"],
|
|
1159
1140
|
parameters: z3.object({
|
|
1160
|
-
selector: z3.string().optional()
|
|
1141
|
+
selector: z3.string().optional(),
|
|
1142
|
+
frame: z3.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u8BFB\u53D6\u6587\u672C")
|
|
1161
1143
|
}),
|
|
1162
|
-
result: z3.object({ text: z3.string() }),
|
|
1144
|
+
result: z3.object({ text: z3.string(), frame: z3.string().optional() }),
|
|
1163
1145
|
handler: async (p, ctx) => {
|
|
1146
|
+
const frameTarget = p.frame ?? ctx.frame;
|
|
1147
|
+
if (frameTarget) {
|
|
1148
|
+
const expr = p.selector ? `(() => { const el = document.querySelector(${JSON.stringify(p.selector)}); return el ? (el.textContent ?? '').trim() : null; })()` : `(document.body?.innerText || '').trim()`;
|
|
1149
|
+
const text2 = await ctx.page.evaluateInFrame(frameTarget, expr);
|
|
1150
|
+
return ok3({ text: text2 || "", frame: frameTarget });
|
|
1151
|
+
}
|
|
1164
1152
|
if (p.selector) {
|
|
1165
1153
|
const text2 = await ctx.page.textContent(p.selector);
|
|
1166
1154
|
return ok3({ text: text2 || "" });
|
|
1167
1155
|
}
|
|
1168
|
-
const text = await ctx.page.evaluate(() => document.body?.innerText || "");
|
|
1156
|
+
const text = await ctx.page.evaluate(() => (document.body?.innerText || "").trim());
|
|
1169
1157
|
return ok3({ text });
|
|
1170
1158
|
}
|
|
1171
1159
|
});
|
|
@@ -1289,43 +1277,64 @@ import { z as z6 } from "zod";
|
|
|
1289
1277
|
import { ok as ok6 } from "@dyyz1993/xcli-core";
|
|
1290
1278
|
var mouseCommand = registerCommand({
|
|
1291
1279
|
name: "mouse",
|
|
1292
|
-
description: "Control the mouse (move, click, etc.)",
|
|
1280
|
+
description: "Control the mouse (move, click, wheel, etc.) (--frame <url-substring> \u65F6\u5728\u8DE8\u57DF iframe \u5185\u64CD\u4F5C\uFF0C\u5750\u6807\u4E3A iframe \u5C40\u90E8\u5750\u6807)",
|
|
1293
1281
|
scope: "page",
|
|
1294
1282
|
parameters: z6.object({
|
|
1295
|
-
action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
|
|
1283
|
+
action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
|
|
1296
1284
|
x: z6.coerce.number(),
|
|
1297
1285
|
y: z6.coerce.number(),
|
|
1286
|
+
"delta-x": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u6A2A\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u53F3\uFF09"),
|
|
1287
|
+
"delta-y": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u7EB5\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u4E0B\uFF09"),
|
|
1298
1288
|
button: z6.enum(["left", "right", "middle"]).optional(),
|
|
1299
|
-
steps: z6.coerce.number().optional()
|
|
1289
|
+
steps: z6.coerce.number().optional(),
|
|
1290
|
+
frame: z6.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u8F93\u5165\u6D3E\u53D1\u5230 iframe \u81EA\u5DF1\u7684 session\uFF08\u8DE8\u57DF iframe \u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09\uFF0C\u5750\u6807\u7528 iframe \u5C40\u90E8\u5750\u6807\u7CFB")
|
|
1300
1291
|
}),
|
|
1301
1292
|
result: z6.object({
|
|
1302
|
-
action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
|
|
1293
|
+
action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
|
|
1303
1294
|
x: z6.number(),
|
|
1304
1295
|
y: z6.number()
|
|
1305
1296
|
}),
|
|
1306
1297
|
handler: async (p, ctx) => {
|
|
1307
1298
|
const button = p.button || "left";
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1299
|
+
const frame = p.frame ?? ctx.frame;
|
|
1300
|
+
const dispatch = async (mouse) => {
|
|
1301
|
+
switch (p.action) {
|
|
1302
|
+
case "move":
|
|
1303
|
+
await mouse.move(p.x, p.y, { steps: p.steps || 1 });
|
|
1304
|
+
break;
|
|
1305
|
+
case "down":
|
|
1306
|
+
await mouse.move(p.x, p.y);
|
|
1307
|
+
await mouse.down({ button });
|
|
1308
|
+
break;
|
|
1309
|
+
case "up":
|
|
1310
|
+
await mouse.move(p.x, p.y);
|
|
1311
|
+
await mouse.up({ button });
|
|
1312
|
+
break;
|
|
1313
|
+
case "click":
|
|
1314
|
+
await mouse.click(p.x, p.y, { button });
|
|
1315
|
+
break;
|
|
1316
|
+
case "dblclick":
|
|
1317
|
+
await mouse.dblclick(p.x, p.y, { button });
|
|
1318
|
+
break;
|
|
1319
|
+
case "drag":
|
|
1320
|
+
await mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
|
|
1321
|
+
break;
|
|
1322
|
+
case "wheel":
|
|
1323
|
+
await mouse.wheelAt(p.x, p.y, Number(p["delta-x"] ?? 0), Number(p["delta-y"] ?? 0));
|
|
1324
|
+
break;
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
if (frame) {
|
|
1328
|
+
try {
|
|
1329
|
+
await ctx.page.runFrameMouse(frame, dispatch);
|
|
1330
|
+
} catch (err) {
|
|
1331
|
+
if (p.action === "drag" && /session/i.test(String(err))) {
|
|
1332
|
+
throw new Error(`frame session \u5728\u62D6\u52A8\u4E2D\u5931\u6548\uFF08iframe \u53EF\u80FD\u5DF2\u91CD\u5EFA\uFF09\u2014\u2014\u91CD\u65B0\u7528 eval --frame \u8BFB\u53D6\u76EE\u6807\u5750\u6807\u540E\u518D\u62D6`);
|
|
1333
|
+
}
|
|
1334
|
+
throw err;
|
|
1335
|
+
}
|
|
1336
|
+
} else {
|
|
1337
|
+
await dispatch(ctx.page.mouse);
|
|
1329
1338
|
}
|
|
1330
1339
|
return ok6({ action: p.action, x: p.x, y: p.y });
|
|
1331
1340
|
}
|
|
@@ -1767,7 +1776,8 @@ var evaluateCommand = registerCommand({
|
|
|
1767
1776
|
direction: "client\u2192browser"
|
|
1768
1777
|
});
|
|
1769
1778
|
engine.stop();
|
|
1770
|
-
const
|
|
1779
|
+
const frame = p.frame ?? ctx.frame;
|
|
1780
|
+
const result = frame ? await ctx.page.evaluateInFrame(frame, expression) : await ctx.page.evaluate(expression);
|
|
1771
1781
|
const response = ok9({ result });
|
|
1772
1782
|
if (decision && decision.severity === "danger") {
|
|
1773
1783
|
response.tips = normalizeTips2([`${decision.suggestion}`]);
|
|
@@ -1836,14 +1846,14 @@ var preflightCommand = registerCommand({
|
|
|
1836
1846
|
let pageUrl = null;
|
|
1837
1847
|
try {
|
|
1838
1848
|
const { fileURLToPath } = await import("url");
|
|
1839
|
-
const { join:
|
|
1840
|
-
const { existsSync:
|
|
1849
|
+
const { join: join10, dirname: dirname4 } = await import("path");
|
|
1850
|
+
const { existsSync: existsSync8 } = await import("fs");
|
|
1841
1851
|
const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
|
|
1842
1852
|
const candidates = [
|
|
1843
|
-
|
|
1844
|
-
|
|
1853
|
+
join10(dirname4(here), "..", "assets", "preflight.html"),
|
|
1854
|
+
join10(process.cwd(), "assets", "preflight.html")
|
|
1845
1855
|
];
|
|
1846
|
-
pageUrl = candidates.find((c) =>
|
|
1856
|
+
pageUrl = candidates.find((c) => existsSync8(c)) || null;
|
|
1847
1857
|
} catch {
|
|
1848
1858
|
}
|
|
1849
1859
|
if (pageUrl) {
|
|
@@ -2196,24 +2206,98 @@ import { z as z16 } from "zod";
|
|
|
2196
2206
|
import { ok as ok16, fail as fail7 } from "@dyyz1993/xcli-core";
|
|
2197
2207
|
var framesCommand = registerCommand({
|
|
2198
2208
|
name: "frames",
|
|
2199
|
-
description: "List all frames in the current page",
|
|
2209
|
+
description: "List all frames in the current page (\u542B\u8DE8\u57DF OOPIF\u2014\u2014\u5B83\u4EEC\u53EA\u5728\u6D4F\u89C8\u5668\u7EA7 target \u5217\u8868\u53EF\u89C1\uFF1B\u9644 parentUrl/depth \u5C42\u7EA7)",
|
|
2200
2210
|
scope: "page",
|
|
2201
2211
|
result: z16.object({
|
|
2202
2212
|
frames: z16.array(z16.object({
|
|
2203
2213
|
index: z16.number(),
|
|
2204
2214
|
name: z16.string().nullable(),
|
|
2205
|
-
url: z16.string()
|
|
2206
|
-
|
|
2215
|
+
url: z16.string(),
|
|
2216
|
+
oopif: z16.boolean().optional(),
|
|
2217
|
+
targetId: z16.string().optional(),
|
|
2218
|
+
parentUrl: z16.string().nullable().optional(),
|
|
2219
|
+
depth: z16.number().nullable().optional()
|
|
2220
|
+
})),
|
|
2221
|
+
warnings: z16.array(z16.string()).optional()
|
|
2207
2222
|
}),
|
|
2208
2223
|
handler: async (_p, ctx) => {
|
|
2209
2224
|
const discover = ctx.page.discoverFrames;
|
|
2210
2225
|
const rawFrames = discover ? await discover.call(ctx.page) : ctx.page.frames();
|
|
2226
|
+
const mainUrl = ctx.page.url();
|
|
2211
2227
|
const frameList = rawFrames.map((frame, index) => ({
|
|
2212
2228
|
index,
|
|
2213
2229
|
name: frame.name(),
|
|
2214
|
-
url: frame.url()
|
|
2230
|
+
url: frame.url(),
|
|
2231
|
+
parentUrl: null,
|
|
2232
|
+
depth: null
|
|
2215
2233
|
}));
|
|
2216
|
-
|
|
2234
|
+
const norm = (u) => u.replace(/\/+$/, "");
|
|
2235
|
+
for (const e of frameList) {
|
|
2236
|
+
if (norm(e.url) === norm(mainUrl)) {
|
|
2237
|
+
e.parentUrl = null;
|
|
2238
|
+
e.depth = 0;
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
if (typeof ctx.page.listFrameTargets === "function") {
|
|
2242
|
+
const targets = await ctx.page.listFrameTargets();
|
|
2243
|
+
const knownUrls = new Set(frameList.map((f) => f.url));
|
|
2244
|
+
for (const t of targets) {
|
|
2245
|
+
if (knownUrls.has(t.url)) continue;
|
|
2246
|
+
frameList.push({ index: frameList.length, name: null, url: t.url, oopif: true, targetId: t.targetId, parentUrl: null, depth: null });
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
const warnings = [];
|
|
2250
|
+
try {
|
|
2251
|
+
const CHILDREN = `JSON.stringify([...document.querySelectorAll('iframe')].map(f=>({src:f.src||'',name:f.name||''})))`;
|
|
2252
|
+
const matchChild = (childSrc, frameUrl) => {
|
|
2253
|
+
const a = norm(childSrc);
|
|
2254
|
+
const b = norm(frameUrl);
|
|
2255
|
+
return Boolean(a && b && (a === b || a.includes(b) || b.includes(a)));
|
|
2256
|
+
};
|
|
2257
|
+
const childrenCache = /* @__PURE__ */ new Map();
|
|
2258
|
+
const childrenOf = async (url) => {
|
|
2259
|
+
const hit = childrenCache.get(url);
|
|
2260
|
+
if (hit) return hit;
|
|
2261
|
+
let out = [];
|
|
2262
|
+
try {
|
|
2263
|
+
const raw = norm(url) === norm(mainUrl) ? await ctx.page.evaluate(CHILDREN) : await ctx.page.evaluateInFrame(url, CHILDREN);
|
|
2264
|
+
out = JSON.parse(String(raw || "[]"));
|
|
2265
|
+
} catch {
|
|
2266
|
+
}
|
|
2267
|
+
childrenCache.set(url, out);
|
|
2268
|
+
return out;
|
|
2269
|
+
};
|
|
2270
|
+
let frontier = frameList.filter((e) => e.depth === 0).map((e) => ({ url: e.url, depth: 0 }));
|
|
2271
|
+
for (let depth = 0; frontier.length > 0 && frameList.some((e) => e.depth === null) && depth < 6; depth++) {
|
|
2272
|
+
const next = [];
|
|
2273
|
+
for (const node of frontier) {
|
|
2274
|
+
const kids = await childrenOf(node.url);
|
|
2275
|
+
if (kids.length === 0) continue;
|
|
2276
|
+
for (const e of frameList) {
|
|
2277
|
+
if (e.depth !== null) continue;
|
|
2278
|
+
if (kids.some((k) => matchChild(k.src, e.url))) {
|
|
2279
|
+
e.parentUrl = node.url;
|
|
2280
|
+
e.depth = node.depth + 1;
|
|
2281
|
+
next.push({ url: e.url, depth: e.depth });
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
frontier = next;
|
|
2286
|
+
}
|
|
2287
|
+
} catch {
|
|
2288
|
+
}
|
|
2289
|
+
const urls = frameList.map((e) => e.url);
|
|
2290
|
+
for (let i = 0; i < urls.length; i++) {
|
|
2291
|
+
for (let j = i + 1; j < urls.length; j++) {
|
|
2292
|
+
const a = urls[i];
|
|
2293
|
+
const b = urls[j];
|
|
2294
|
+
if (a && b && (a.includes(b) || b.includes(a))) {
|
|
2295
|
+
const shorter = a.includes(b) ? b : a;
|
|
2296
|
+
warnings.push(`URL \u5B50\u4E32\u6B67\u4E49\uFF1A"${shorter}" \u540C\u65F6\u547D\u4E2D ${a} \u548C ${b}\u2014\u2014--frame \u8BF7\u5199\u66F4\u957F/\u66F4\u7CBE\u786E\u7684\u5B50\u4E32`);
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
return ok16({ frames: frameList, warnings });
|
|
2217
2301
|
}
|
|
2218
2302
|
});
|
|
2219
2303
|
var frameCommand = registerCommand({
|
|
@@ -3772,8 +3856,26 @@ async function detectSpaRoutes(page, origin) {
|
|
|
3772
3856
|
}
|
|
3773
3857
|
} catch {
|
|
3774
3858
|
}
|
|
3859
|
+
try {
|
|
3860
|
+
const vueRoutes = await page.evaluate((evalOrigin) => {
|
|
3861
|
+
const win = window;
|
|
3862
|
+
const vue3App = win.__vue_app__;
|
|
3863
|
+
const globalProperties = vue3App?.config?.globalProperties;
|
|
3864
|
+
let router = globalProperties?.$router;
|
|
3865
|
+
if (!router) {
|
|
3866
|
+
const root = document.querySelector("#app");
|
|
3867
|
+
const vm = root ? root.__vue__ : void 0;
|
|
3868
|
+
const rootVm = vm?.$root;
|
|
3869
|
+
router = vm?.$router ?? rootVm?.$router;
|
|
3870
|
+
}
|
|
3871
|
+
const routeList = router?.options?.routes ?? [];
|
|
3872
|
+
return routeList.filter((route) => route.path && route.path !== "/" && !route.path.includes(":") && !route.path.includes("*")).map((route) => `${evalOrigin.replace(/\/$/, "")}/#${route.path}`);
|
|
3873
|
+
}, origin);
|
|
3874
|
+
for (const route of vueRoutes) routeSet.add(route);
|
|
3875
|
+
} catch {
|
|
3876
|
+
}
|
|
3775
3877
|
return Array.from(routeSet).map(
|
|
3776
|
-
(p) => `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
|
|
3878
|
+
(p) => p.startsWith("http") ? p : `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
|
|
3777
3879
|
);
|
|
3778
3880
|
}
|
|
3779
3881
|
function parseRobotsTxt(text) {
|
|
@@ -3966,7 +4068,14 @@ var crawlCommand = registerCommand({
|
|
|
3966
4068
|
results.push({ url: seedPage.url(), title, content });
|
|
3967
4069
|
const firstLinks = await extractLinks(seedPage, startUrl.origin);
|
|
3968
4070
|
if (options.enableSpa) {
|
|
3969
|
-
|
|
4071
|
+
let spaRoutes = [];
|
|
4072
|
+
try {
|
|
4073
|
+
spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
|
|
4074
|
+
} catch (error) {
|
|
4075
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4076
|
+
process.stderr.write(`[SPA] Route detection failed: ${message}
|
|
4077
|
+
`);
|
|
4078
|
+
}
|
|
3970
4079
|
for (const route of spaRoutes) {
|
|
3971
4080
|
try {
|
|
3972
4081
|
const absNorm = normalizeUrl(stripHashAnchorQuery(route));
|
|
@@ -4835,6 +4944,8 @@ var networkCommand = registerCommand({
|
|
|
4835
4944
|
|
|
4836
4945
|
// src/commands/ai-search-engines.ts
|
|
4837
4946
|
import { z as z24 } from "zod";
|
|
4947
|
+
|
|
4948
|
+
// src/commands/ai-engine-configs.ts
|
|
4838
4949
|
var ENGINE_CONFIGS = {
|
|
4839
4950
|
deepseek: {
|
|
4840
4951
|
key: "deepseek",
|
|
@@ -5087,6 +5198,8 @@ var ENGINE_CONFIGS = {
|
|
|
5087
5198
|
sendButtonSelector: "button.send-btn"
|
|
5088
5199
|
}
|
|
5089
5200
|
};
|
|
5201
|
+
|
|
5202
|
+
// src/commands/ai-search-engines.ts
|
|
5090
5203
|
var ALL_ENGINE_KEYS = Object.keys(ENGINE_CONFIGS);
|
|
5091
5204
|
var ENGINE_KEY_ENUM = z24.enum(ALL_ENGINE_KEYS);
|
|
5092
5205
|
function getEngineConfig(key) {
|
|
@@ -5847,20 +5960,48 @@ async function enhanceSemanticsWithLLM(url, ariaSnapshot, ruleBasedElements) {
|
|
|
5847
5960
|
// src/commands/snapshot.ts
|
|
5848
5961
|
var snapshotCommand = registerCommand({
|
|
5849
5962
|
name: "snapshot",
|
|
5850
|
-
description: "
|
|
5963
|
+
description: "Get page state: interactive @refs to operate (default); --type aria=page outline; --type text=content; --type dom=debug DOM",
|
|
5851
5964
|
scope: "page",
|
|
5852
5965
|
selectorParams: ["selector"],
|
|
5966
|
+
examples: [
|
|
5967
|
+
{
|
|
5968
|
+
cmd: "xbrowser snapshot",
|
|
5969
|
+
description: "I want to OPERATE the page \u2192 returns clickable/fillable @refs (use click @e1, fill @e2)",
|
|
5970
|
+
output: '@e1 [button] "Submit"\n@e2 [textbox editable] "Email"'
|
|
5971
|
+
},
|
|
5972
|
+
{
|
|
5973
|
+
cmd: "xbrowser snapshot --type aria",
|
|
5974
|
+
description: "I want the page OUTLINE/skeleton (nav, heading hierarchy, regions)",
|
|
5975
|
+
output: 'banner:\n navigation:\n link "Home"\nmain:\n heading "Welcome"'
|
|
5976
|
+
},
|
|
5977
|
+
{
|
|
5978
|
+
cmd: "xbrowser snapshot --type text",
|
|
5979
|
+
description: "I want the page TEXT CONTENT (extract body copy/information)",
|
|
5980
|
+
output: "Welcome\nPlease enter your email\nSubmit"
|
|
5981
|
+
},
|
|
5982
|
+
{
|
|
5983
|
+
cmd: "xbrowser snapshot --type dom",
|
|
5984
|
+
description: "I want to DEBUG the DOM (tag names, attributes, nesting)"
|
|
5985
|
+
},
|
|
5986
|
+
{
|
|
5987
|
+
cmd: "xbrowser snapshot --selectors",
|
|
5988
|
+
description: "I want to operate AND need stable CSS selectors (reuse across sessions)",
|
|
5989
|
+
output: "e1: #submit | e2: #email"
|
|
5990
|
+
}
|
|
5991
|
+
],
|
|
5853
5992
|
parameters: z25.object({
|
|
5854
|
-
type: z25.enum(["aria", "text", "dom", "all"]).default("
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5993
|
+
type: z25.enum(["interactive", "aria", "text", "dom", "all"]).default("interactive").describe(
|
|
5994
|
+
"Choose by intent: interactive(default)=operate page, get @refs of clickable/fillable elements; aria=page outline (nav/headings/regions); text=page text content; dom=debug DOM tags/attrs; all=everything"
|
|
5995
|
+
),
|
|
5996
|
+
selector: z25.string().optional().describe("\u9650\u5B9A\u5230\u67D0\u4E2A\u5143\u7D20\uFF08CSS \u9009\u62E9\u5668\uFF09\uFF0C\u53EA\u5FEB\u7167\u8BE5\u5B50\u6811"),
|
|
5997
|
+
depth: z25.number().optional().default(6).describe("aria/dom \u6811\u7684\u6700\u5927\u6DF1\u5EA6"),
|
|
5998
|
+
interactive: z25.boolean().optional().default(false).describe("\u5F3A\u5236 interactive \u6A21\u5F0F\uFF08\u7B49\u540C --type interactive\uFF0C\u517C\u5BB9 -i\uFF09"),
|
|
5999
|
+
interactiveOnly: z25.boolean().optional().default(false).describe("interactive \u7684\u522B\u540D"),
|
|
6000
|
+
i: z25.boolean().optional().default(false).describe("interactive \u7684\u77ED\u522B\u540D"),
|
|
6001
|
+
compact: z25.boolean().optional().default(false).describe("\u9644\u5E26\u7D27\u51D1\u6587\u672C\u5FEB\u7167\uFF08interactive \u6A21\u5F0F\u9ED8\u8BA4\u5DF2\u542B\uFF09"),
|
|
6002
|
+
c: z25.boolean().optional().default(false).describe("compact \u7684\u77ED\u522B\u540D"),
|
|
6003
|
+
selectors: z25.boolean().optional().describe("\u9644\u5E26 ref \u2192 CSS \u9009\u62E9\u5668\u6620\u5C04\uFF08\u9700\u8981\u7A33\u5B9A\u9009\u62E9\u5668\u65F6\u5F00\uFF09"),
|
|
6004
|
+
all: z25.boolean().optional().default(false).describe("interactive \u6A21\u5F0F\u4E0B\u8FDE\u9690\u85CF\u5143\u7D20\u4E00\u8D77\u91C7\u96C6\uFF08\u6CE8\u610F\uFF1A\u8FD9\u662F\u91C7\u96C6\u8303\u56F4\uFF0C\u4E0D\u662F --type all \u7684\u5408\u5E76\u5FEB\u7167\uFF09")
|
|
5864
6005
|
}),
|
|
5865
6006
|
result: z25.object({
|
|
5866
6007
|
url: z25.string(),
|
|
@@ -5873,14 +6014,13 @@ var snapshotCommand = registerCommand({
|
|
|
5873
6014
|
const page = ctx.page;
|
|
5874
6015
|
const url = page.url();
|
|
5875
6016
|
const title = await page.title().catch(() => "");
|
|
5876
|
-
|
|
6017
|
+
const wantInteractive = p.type === "interactive" || p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors;
|
|
6018
|
+
if (wantInteractive) {
|
|
5877
6019
|
const observation = await observePage(page, ctx.sessionId, {
|
|
5878
6020
|
includeHidden: p.all
|
|
5879
6021
|
});
|
|
5880
6022
|
if (p.selectors) observation.selectors = buildSelectorMap(observation);
|
|
5881
|
-
|
|
5882
|
-
observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
|
|
5883
|
-
}
|
|
6023
|
+
observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
|
|
5884
6024
|
return ok24(observation, normalizeTips3([
|
|
5885
6025
|
`refs refreshed for ${observation.targets.length} targets; use click @e1 or fill @e2 "text"`
|
|
5886
6026
|
]));
|
|
@@ -5900,14 +6040,20 @@ var snapshotCommand = registerCommand({
|
|
|
5900
6040
|
return ok24({ url, title, dom });
|
|
5901
6041
|
}
|
|
5902
6042
|
if (p.type === "all") {
|
|
5903
|
-
const [aria, text, dom] = await Promise.all([
|
|
6043
|
+
const [observation, aria, text, dom] = await Promise.all([
|
|
6044
|
+
observePage(page, ctx.sessionId, { includeHidden: p.all }),
|
|
5904
6045
|
captureAriaSnapshot(page, p.selector, p.depth),
|
|
5905
6046
|
captureTextSnapshot(page, p.selector),
|
|
5906
6047
|
captureDomSnapshot(page, p.selector, p.depth ?? 6)
|
|
5907
6048
|
]);
|
|
6049
|
+
observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
|
|
6050
|
+
if (p.selectors) observation.selectors = buildSelectorMap(observation);
|
|
5908
6051
|
const tips = await buildRefTips(page, aria);
|
|
5909
6052
|
persistSemantics(url, aria);
|
|
5910
|
-
return ok24({
|
|
6053
|
+
return ok24({ ...observation, aria, text, dom }, normalizeTips3([
|
|
6054
|
+
...tips,
|
|
6055
|
+
`${observation.targets.length} interactive targets + aria + text + dom combined`
|
|
6056
|
+
]));
|
|
5911
6057
|
}
|
|
5912
6058
|
return fail11(`Unknown snapshot type: ${p.type}`);
|
|
5913
6059
|
}
|
|
@@ -5936,16 +6082,29 @@ async function buildRefTips(page, aria) {
|
|
|
5936
6082
|
}
|
|
5937
6083
|
}
|
|
5938
6084
|
async function captureAriaSnapshot(page, selector, _depth) {
|
|
6085
|
+
let raw;
|
|
5939
6086
|
try {
|
|
5940
6087
|
const locator = selector ? page.locator(selector).first() : page.locator("body");
|
|
5941
|
-
|
|
6088
|
+
raw = await locator.ariaSnapshot();
|
|
5942
6089
|
} catch {
|
|
5943
6090
|
try {
|
|
5944
|
-
|
|
6091
|
+
raw = await page.locator("body").ariaSnapshot();
|
|
5945
6092
|
} catch {
|
|
5946
6093
|
return "(aria snapshot not available)";
|
|
5947
6094
|
}
|
|
5948
6095
|
}
|
|
6096
|
+
return filterAriaNoise(raw);
|
|
6097
|
+
}
|
|
6098
|
+
function filterAriaNoise(raw) {
|
|
6099
|
+
return raw.split("\n").filter((line) => {
|
|
6100
|
+
const t = line.trim();
|
|
6101
|
+
if (!t) return false;
|
|
6102
|
+
if (t === "none:" || t.startsWith("none: ")) return false;
|
|
6103
|
+
if (t.includes("InlineTextBox")) return false;
|
|
6104
|
+
if (t.includes("ListMarker")) return false;
|
|
6105
|
+
if (/^[a-z]+$/.test(t) || /^[a-z]+:$/.test(t)) return false;
|
|
6106
|
+
return true;
|
|
6107
|
+
}).join("\n");
|
|
5949
6108
|
}
|
|
5950
6109
|
async function captureTextSnapshot(page, selector) {
|
|
5951
6110
|
if (selector) {
|
|
@@ -6088,12 +6247,13 @@ var DECISION_SYSTEM = `\u4F60\u662F\u6D4F\u89C8\u5668\u4EFB\u52A1\u51B3\u7B56\u5
|
|
|
6088
6247
|
{"action":"press","value":"Enter","thought":"\u4E3A\u4EC0\u4E48"}
|
|
6089
6248
|
{"action":"scroll","value":"down \u6216 up","thought":"\u4E3A\u4EC0\u4E48"}
|
|
6090
6249
|
{"action":"done","value":"\u5B8C\u6210\u6458\u8981","thought":"\u4E3A\u4EC0\u4E48"}
|
|
6250
|
+
{"action":"back","thought":"\u70B9\u9519\u4E86/\u8DF3\u8F6C\u9519\u4E86\uFF0C\u8FD4\u56DE\u4E0A\u4E00\u9875\u91CD\u8BD5"}
|
|
6091
6251
|
{"action":"blocked","value":"\u5361\u4F4F\u539F\u56E0","thought":"\u4E3A\u4EC0\u4E48"}
|
|
6092
6252
|
|
|
6093
6253
|
\u89C4\u5219\uFF1A
|
|
6094
6254
|
1. ref \u5FC5\u987B\u539F\u6837\u6765\u81EA\u672C\u6B21\u5143\u7D20\u6E05\u5355\uFF1B\u6E05\u5355\u91CC\u6CA1\u6709\u80FD\u63A8\u8FDB\u76EE\u6807\u7684\u5143\u7D20\u5C31\u8F93\u51FA blocked\u3002
|
|
6095
6255
|
2. \u76EE\u6807\u5DF2\u5B8C\u6210\uFF08\u9875\u9762\u4E0A\u80FD\u786E\u8BA4\u7ED3\u679C\uFF09\u5C31\u8F93\u51FA done\uFF0Cvalue \u5199\u5B8C\u6210\u6458\u8981\u3002
|
|
6096
|
-
3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
|
|
6256
|
+
3. \u4E0D\u8981\u91CD\u590D\u521A\u5931\u8D25\u8FC7\u7684\u540C\u4E00\u52A8\u4F5C\uFF1B\u52A8\u4F5C\u540E\u9875\u9762\u8DF3\u5230\u4E86\u610F\u6599\u4E4B\u5916\u7684\u5730\u65B9\u5C31\u8F93\u51FA back \u8FD4\u56DE\u91CD\u8BD5\uFF1B\u8FDE\u7EED\u5931\u8D25\u6362\u601D\u8DEF\u6216 blocked\u3002`;
|
|
6097
6257
|
function extractDecision(raw) {
|
|
6098
6258
|
let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
6099
6259
|
const start = s.indexOf("{");
|
|
@@ -6144,6 +6304,7 @@ var taskCommand = registerCommand({
|
|
|
6144
6304
|
let status = "max_steps";
|
|
6145
6305
|
let summary = "";
|
|
6146
6306
|
let lastError = "";
|
|
6307
|
+
let emptyReplies = 0;
|
|
6147
6308
|
for (let step = 1; step <= p.maxSteps; step++) {
|
|
6148
6309
|
if (Date.now() - started > p.timeout) {
|
|
6149
6310
|
status = "blocked";
|
|
@@ -6163,7 +6324,7 @@ ${history.slice(-6).join("\n")}` : ""
|
|
|
6163
6324
|
].filter(Boolean).join("\n");
|
|
6164
6325
|
let raw = "";
|
|
6165
6326
|
try {
|
|
6166
|
-
raw = await
|
|
6327
|
+
raw = await vlmAskRetry({ ...creds, model }, [{ type: "text", text: `${DECISION_SYSTEM}
|
|
6167
6328
|
|
|
6168
6329
|
---
|
|
6169
6330
|
|
|
@@ -6177,6 +6338,12 @@ ${userPayload}` }], 900);
|
|
|
6177
6338
|
}
|
|
6178
6339
|
const decision = extractDecision(raw);
|
|
6179
6340
|
if (!decision || typeof decision.action !== "string") {
|
|
6341
|
+
if (!raw.trim() && emptyReplies < 2) {
|
|
6342
|
+
emptyReplies++;
|
|
6343
|
+
steps.push({ step, action: "(empty reply, re-observe)", ok: false, screenHash: obs.screenHash });
|
|
6344
|
+
history.push(`step${step}: (empty reply, retrying)`);
|
|
6345
|
+
continue;
|
|
6346
|
+
}
|
|
6180
6347
|
status = "blocked";
|
|
6181
6348
|
summary = `LLM returned unparsable decision: ${raw.slice(0, 120)}`;
|
|
6182
6349
|
break;
|
|
@@ -6191,6 +6358,13 @@ ${userPayload}` }], 900);
|
|
|
6191
6358
|
steps.push({ step, thought, action: "done", ok: true, screenHash });
|
|
6192
6359
|
break;
|
|
6193
6360
|
}
|
|
6361
|
+
if (action === "back") {
|
|
6362
|
+
await ctx.page?.goBack?.().catch?.(() => {
|
|
6363
|
+
});
|
|
6364
|
+
steps.push({ step, thought, action: "back", ok: true, screenHash });
|
|
6365
|
+
history.push(`step${step}: back (\u8FD4\u56DE\u4E0A\u4E00\u9875)`);
|
|
6366
|
+
continue;
|
|
6367
|
+
}
|
|
6194
6368
|
if (action === "blocked") {
|
|
6195
6369
|
status = "blocked";
|
|
6196
6370
|
summary = value || thought || "LLM judged blocked";
|
|
@@ -6792,6 +6966,8 @@ var visualTagCommand = registerCommand({
|
|
|
6792
6966
|
// src/commands/visual-tag-v2.ts
|
|
6793
6967
|
import { z as z32 } from "zod";
|
|
6794
6968
|
import { ok as ok31, fail as fail16 } from "@dyyz1993/xcli-core";
|
|
6969
|
+
|
|
6970
|
+
// src/commands/visual-tag-v2-script.ts
|
|
6795
6971
|
var SAFE_SET2 = "ahjkmnprtw3479".split("");
|
|
6796
6972
|
var TAG_V2_SCRIPT = `
|
|
6797
6973
|
(function() {
|
|
@@ -7134,7 +7310,9 @@ var TAG_V2_SCRIPT = `
|
|
|
7134
7310
|
return JSON.stringify(window.__xbTagStats);
|
|
7135
7311
|
})()
|
|
7136
7312
|
`;
|
|
7137
|
-
|
|
7313
|
+
|
|
7314
|
+
// src/commands/visual-tag-v2.ts
|
|
7315
|
+
registerCommand({
|
|
7138
7316
|
name: "visual-tag-v2",
|
|
7139
7317
|
description: "\u5206\u8272\u6807\u6CE8\u9875\u9762\u5143\u7D20\uFF08\u7EA2=\u53EF\u70B9\u51FB \u84DD=\u8F93\u5165 \u7EFF=\u56FE\u7247 \u9EC4=\u5217\u8868 \u7D2B=\u6570\u5B57 \u6A59=\u6587\u672C\uFF09",
|
|
7140
7318
|
scope: "page",
|
|
@@ -7385,7 +7563,7 @@ function attachWaitForHuman(ctx, getOrCreateWSServer) {
|
|
|
7385
7563
|
if (!ctx.page) {
|
|
7386
7564
|
throw new Error("waitForHuman requires an active page");
|
|
7387
7565
|
}
|
|
7388
|
-
const { HumanInteractionManager } = await import("./human-interaction-
|
|
7566
|
+
const { HumanInteractionManager } = await import("./human-interaction-STTZZZ5N.js");
|
|
7389
7567
|
const wsServer2 = await getOrCreateWSServer(ctx.browserContext);
|
|
7390
7568
|
const manager = new HumanInteractionManager(wsServer2, ctx.page);
|
|
7391
7569
|
return manager.waitForHuman(options);
|
|
@@ -7409,8 +7587,8 @@ import {
|
|
|
7409
7587
|
Core
|
|
7410
7588
|
} from "@dyyz1993/xcli-core";
|
|
7411
7589
|
import { resolve as resolve2, basename, dirname as dirname3 } from "path";
|
|
7412
|
-
import { existsSync as
|
|
7413
|
-
import { homedir as
|
|
7590
|
+
import { existsSync as existsSync7, readdirSync } from "fs";
|
|
7591
|
+
import { homedir as homedir5 } from "os";
|
|
7414
7592
|
|
|
7415
7593
|
// src/plugin/metadata-parser.ts
|
|
7416
7594
|
import { existsSync as existsSync4 } from "fs";
|
|
@@ -7706,6 +7884,75 @@ function patchLoginRequired() {
|
|
|
7706
7884
|
});
|
|
7707
7885
|
}
|
|
7708
7886
|
|
|
7887
|
+
// src/lib/mistake-ledger.ts
|
|
7888
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
|
|
7889
|
+
import { homedir as homedir4 } from "os";
|
|
7890
|
+
import { join as join7 } from "path";
|
|
7891
|
+
var MISTAKE_THRESHOLD = 3;
|
|
7892
|
+
var MISTAKE_LEDGER_PATH = join7(
|
|
7893
|
+
homedir4(),
|
|
7894
|
+
".xbrowser",
|
|
7895
|
+
"knowledge",
|
|
7896
|
+
"mistakes.json"
|
|
7897
|
+
);
|
|
7898
|
+
function emptyLedger() {
|
|
7899
|
+
return { version: 1, entries: {} };
|
|
7900
|
+
}
|
|
7901
|
+
function normalizeMistakeText(value) {
|
|
7902
|
+
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();
|
|
7903
|
+
}
|
|
7904
|
+
function mistakeFingerprint(category, message) {
|
|
7905
|
+
return `${category}::${normalizeMistakeText(message)}`;
|
|
7906
|
+
}
|
|
7907
|
+
function readMistakeLedger(path2 = MISTAKE_LEDGER_PATH) {
|
|
7908
|
+
try {
|
|
7909
|
+
const parsed = JSON.parse(readFileSync6(path2, "utf8"));
|
|
7910
|
+
if (parsed.version !== 1 || typeof parsed.entries !== "object") {
|
|
7911
|
+
return emptyLedger();
|
|
7912
|
+
}
|
|
7913
|
+
return parsed;
|
|
7914
|
+
} catch {
|
|
7915
|
+
return emptyLedger();
|
|
7916
|
+
}
|
|
7917
|
+
}
|
|
7918
|
+
function writeMistakeLedger(ledger, path2 = MISTAKE_LEDGER_PATH) {
|
|
7919
|
+
mkdirSync5(join7(path2, ".."), { recursive: true });
|
|
7920
|
+
writeFileSync6(path2, JSON.stringify(ledger, null, 2), "utf8");
|
|
7921
|
+
}
|
|
7922
|
+
function recordMistake(input, path2 = MISTAKE_LEDGER_PATH) {
|
|
7923
|
+
if (!input.category) throw new Error("mistake category is required");
|
|
7924
|
+
if (!input.command) throw new Error("mistake command is required");
|
|
7925
|
+
if (!input.message) throw new Error("mistake message is required");
|
|
7926
|
+
const ledger = readMistakeLedger(path2);
|
|
7927
|
+
const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
|
|
7928
|
+
const previous = ledger.entries[fingerprint];
|
|
7929
|
+
const occurrence = {
|
|
7930
|
+
timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
7931
|
+
command: input.command,
|
|
7932
|
+
message: input.message,
|
|
7933
|
+
...input.context ? { context: input.context } : {}
|
|
7934
|
+
};
|
|
7935
|
+
const entry = previous ? {
|
|
7936
|
+
...previous,
|
|
7937
|
+
lastSeen: occurrence.timestamp,
|
|
7938
|
+
occurrences: [...previous.occurrences, occurrence].slice(-100),
|
|
7939
|
+
constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
|
|
7940
|
+
} : {
|
|
7941
|
+
fingerprint,
|
|
7942
|
+
category: input.category,
|
|
7943
|
+
firstSeen: occurrence.timestamp,
|
|
7944
|
+
lastSeen: occurrence.timestamp,
|
|
7945
|
+
occurrences: [occurrence],
|
|
7946
|
+
constrained: false
|
|
7947
|
+
};
|
|
7948
|
+
ledger.entries[fingerprint] = entry;
|
|
7949
|
+
writeMistakeLedger(ledger, path2);
|
|
7950
|
+
return {
|
|
7951
|
+
entry,
|
|
7952
|
+
newlyConstrained: Boolean(previous && !previous.constrained && entry.constrained)
|
|
7953
|
+
};
|
|
7954
|
+
}
|
|
7955
|
+
|
|
7709
7956
|
// src/plugin/loader.ts
|
|
7710
7957
|
var DEFAULT_PLUGIN_DIRS = [".xcli/plugins", "../.xcli/plugins"];
|
|
7711
7958
|
var XBrowserPluginLoader = class {
|
|
@@ -7716,6 +7963,7 @@ var XBrowserPluginLoader = class {
|
|
|
7716
7963
|
dirSiteAliases = /* @__PURE__ */ new Map();
|
|
7717
7964
|
constructor(options) {
|
|
7718
7965
|
patchLoginRequired();
|
|
7966
|
+
globalThis.__xbrowserRecordMistake = recordMistake;
|
|
7719
7967
|
this.options = options ?? {};
|
|
7720
7968
|
const cwd = this.options.cwd || process.cwd();
|
|
7721
7969
|
const coreConfig = {
|
|
@@ -7796,18 +8044,18 @@ var XBrowserPluginLoader = class {
|
|
|
7796
8044
|
}
|
|
7797
8045
|
async scanAndLoad() {
|
|
7798
8046
|
const cwd = this.options.cwd || process.cwd();
|
|
7799
|
-
const globalDir = this.options.globalDir || resolve2(
|
|
8047
|
+
const globalDir = this.options.globalDir || resolve2(homedir5(), ".xbrowser/plugins");
|
|
7800
8048
|
ensurePluginDependencies(globalDir);
|
|
7801
8049
|
const dirs = [
|
|
7802
8050
|
resolve2(cwd, ".xcli/plugins"),
|
|
7803
8051
|
resolve2(cwd, "../.xcli/plugins"),
|
|
7804
|
-
this.options.userDir || resolve2(
|
|
8052
|
+
this.options.userDir || resolve2(homedir5(), ".xcli/plugins"),
|
|
7805
8053
|
globalDir
|
|
7806
8054
|
];
|
|
7807
8055
|
const loaded = [];
|
|
7808
8056
|
const seen = /* @__PURE__ */ new Set();
|
|
7809
8057
|
for (const dir of dirs) {
|
|
7810
|
-
if (!
|
|
8058
|
+
if (!existsSync7(dir)) continue;
|
|
7811
8059
|
const entries = readdirSync(dir, { withFileTypes: true });
|
|
7812
8060
|
for (const entry of entries) {
|
|
7813
8061
|
if (!entry.isDirectory()) continue;
|
|
@@ -7815,12 +8063,12 @@ var XBrowserPluginLoader = class {
|
|
|
7815
8063
|
seen.add(entry.name);
|
|
7816
8064
|
const pluginDir = resolve2(dir, entry.name);
|
|
7817
8065
|
let indexPath = resolve2(pluginDir, "index.js");
|
|
7818
|
-
if (!
|
|
8066
|
+
if (!existsSync7(indexPath)) {
|
|
7819
8067
|
indexPath = resolve2(pluginDir, "index.ts");
|
|
7820
8068
|
}
|
|
7821
|
-
if (!
|
|
8069
|
+
if (!existsSync7(indexPath)) continue;
|
|
7822
8070
|
try {
|
|
7823
|
-
if (!
|
|
8071
|
+
if (!existsSync7(resolve2(pluginDir, "package.json"))) {
|
|
7824
8072
|
console.warn(`\u26A0\uFE0F Plugin "${entry.name}" has no package.json. Use "xbrowser create ${entry.name} --template static" for proper structure.`);
|
|
7825
8073
|
} else {
|
|
7826
8074
|
const metadata = PluginMetadataParser.parseFromPackageJson(pluginDir);
|
|
@@ -7846,166 +8094,110 @@ var XBrowserPluginLoader = class {
|
|
|
7846
8094
|
}
|
|
7847
8095
|
};
|
|
7848
8096
|
|
|
7849
|
-
// src/
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
pageNotReady: "RETRYABLE: page-not-ready",
|
|
7853
|
-
elementGone: "RETRYABLE: element-gone",
|
|
7854
|
-
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
7855
|
-
captcha: "HUMAN: captcha",
|
|
7856
|
-
loginWall: "HUMAN: login-wall",
|
|
7857
|
-
permissionDenied: "FATAL: permission-denied",
|
|
7858
|
-
targetGone: "FATAL: target-gone",
|
|
7859
|
-
unknown: "FATAL: unknown"
|
|
7860
|
-
};
|
|
7861
|
-
function classifyFailure(message) {
|
|
7862
|
-
const msg = (message || "").toLowerCase();
|
|
7863
|
-
const pick = (code) => ({
|
|
7864
|
-
code,
|
|
7865
|
-
level: code.split(":")[0],
|
|
7866
|
-
message: message || code
|
|
7867
|
-
});
|
|
7868
|
-
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
7869
|
-
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
7870
|
-
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
7871
|
-
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
7872
|
-
return pick(FAIL_CODES.selectorNotFound);
|
|
7873
|
-
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
7874
|
-
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
7875
|
-
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
7876
|
-
return pick(FAIL_CODES.targetGone);
|
|
7877
|
-
return pick(FAIL_CODES.unknown);
|
|
7878
|
-
}
|
|
7879
|
-
|
|
7880
|
-
// src/executor.ts
|
|
8097
|
+
// src/executor/foundation.ts
|
|
8098
|
+
import { homedir as homedir6 } from "os";
|
|
8099
|
+
import { join as join8 } from "path";
|
|
7881
8100
|
import {
|
|
7882
|
-
|
|
7883
|
-
fail as fail17,
|
|
7884
|
-
isCommandResult,
|
|
7885
|
-
CompositeStorage as CompositeStorage2,
|
|
7886
|
-
TipCollector as TipCollector2,
|
|
7887
|
-
normalizeTips as normalizeTips7,
|
|
8101
|
+
CompositeStorage,
|
|
7888
8102
|
configureArchiveStore,
|
|
7889
8103
|
appendCommandToArchive,
|
|
7890
|
-
|
|
7891
|
-
|
|
8104
|
+
fail as fail17,
|
|
8105
|
+
checkGuard
|
|
7892
8106
|
} from "@dyyz1993/xcli-core";
|
|
7893
8107
|
|
|
7894
|
-
// src/utils/
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
8108
|
+
// src/utils/plugin-singleton.ts
|
|
8109
|
+
var pluginLoader = null;
|
|
8110
|
+
var pluginsScanned = false;
|
|
8111
|
+
function silenceSchemaWarnings(fn) {
|
|
8112
|
+
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
8113
|
+
const originalWarn = console.warn;
|
|
8114
|
+
console.warn = (...args) => {
|
|
8115
|
+
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
8116
|
+
if (msg.includes('has no "result" schema')) return;
|
|
8117
|
+
originalWarn(...args);
|
|
8118
|
+
};
|
|
8119
|
+
return fn().finally(() => {
|
|
8120
|
+
console.warn = originalWarn;
|
|
8121
|
+
});
|
|
7898
8122
|
}
|
|
7899
|
-
function
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
const innerType = field?._def?.innerType;
|
|
7903
|
-
return unwrapField(innerType);
|
|
8123
|
+
async function getPluginLoader() {
|
|
8124
|
+
if (!pluginLoader) {
|
|
8125
|
+
pluginLoader = new XBrowserPluginLoader();
|
|
7904
8126
|
}
|
|
7905
|
-
|
|
7906
|
-
|
|
7907
|
-
|
|
7908
|
-
|
|
7909
|
-
return
|
|
8127
|
+
if (!pluginsScanned) {
|
|
8128
|
+
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
8129
|
+
pluginsScanned = true;
|
|
8130
|
+
}
|
|
8131
|
+
return pluginLoader;
|
|
7910
8132
|
}
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
8133
|
+
|
|
8134
|
+
// src/executor/foundation.ts
|
|
8135
|
+
var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set(["goto", "back", "forward", "refresh"]);
|
|
8136
|
+
var snapshotHintShown = /* @__PURE__ */ new WeakSet();
|
|
8137
|
+
var CONFIG_DIR = join8(homedir6(), ".xbrowser");
|
|
8138
|
+
var storageCache = /* @__PURE__ */ new Map();
|
|
8139
|
+
function getPluginStorage(pluginName) {
|
|
8140
|
+
if (!storageCache.has(pluginName)) {
|
|
8141
|
+
storageCache.set(pluginName, new CompositeStorage(pluginName, CONFIG_DIR, "xbrowser"));
|
|
7917
8142
|
}
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
8143
|
+
return storageCache.get(pluginName);
|
|
8144
|
+
}
|
|
8145
|
+
var archiveInitialized = false;
|
|
8146
|
+
function ensureArchiveInit() {
|
|
8147
|
+
if (!archiveInitialized) {
|
|
8148
|
+
try {
|
|
8149
|
+
configureArchiveStore({ archiveDir: join8(homedir6(), ".xbrowser", "archives") });
|
|
8150
|
+
} catch {
|
|
7923
8151
|
}
|
|
7924
|
-
|
|
8152
|
+
archiveInitialized = true;
|
|
7925
8153
|
}
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
8154
|
+
}
|
|
8155
|
+
function recordArchive(sessionId, sessionName, entry) {
|
|
8156
|
+
if (!sessionId) return;
|
|
8157
|
+
try {
|
|
8158
|
+
ensureArchiveInit();
|
|
8159
|
+
appendCommandToArchive(sessionId, sessionName, entry);
|
|
8160
|
+
} catch {
|
|
7930
8161
|
}
|
|
7931
|
-
return { value: unquote(raw), skip: false };
|
|
7932
8162
|
}
|
|
7933
|
-
function
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
let pIdx = 0;
|
|
7940
|
-
for (const key of keys) {
|
|
7941
|
-
if (pIdx >= positional.length) break;
|
|
7942
|
-
if (result[key] !== void 0) {
|
|
7943
|
-
pIdx++;
|
|
7944
|
-
continue;
|
|
7945
|
-
}
|
|
7946
|
-
const field = shape[key];
|
|
7947
|
-
const raw = positional[pIdx];
|
|
7948
|
-
const { value, skip } = coerceValue(raw, field);
|
|
7949
|
-
if (skip) continue;
|
|
7950
|
-
result[key] = value;
|
|
7951
|
-
pIdx++;
|
|
8163
|
+
async function guardCheck(commandName) {
|
|
8164
|
+
try {
|
|
8165
|
+
const loader = await getPluginLoader();
|
|
8166
|
+
return checkGuard(loader.getCore(), commandName, process.env);
|
|
8167
|
+
} catch {
|
|
8168
|
+
return null;
|
|
7952
8169
|
}
|
|
7953
|
-
return result;
|
|
7954
8170
|
}
|
|
7955
|
-
|
|
7956
|
-
|
|
7957
|
-
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
if (args[i] === "--" && args[i + 1]) {
|
|
7962
|
-
try {
|
|
7963
|
-
Object.assign(params, JSON.parse(args[i + 1]));
|
|
7964
|
-
} catch {
|
|
7965
|
-
}
|
|
7966
|
-
break;
|
|
7967
|
-
}
|
|
7968
|
-
if (args[i].startsWith("--")) {
|
|
7969
|
-
const key = args[i].slice(2);
|
|
7970
|
-
const value = args[i + 1];
|
|
7971
|
-
if (value && !value.startsWith("-")) {
|
|
7972
|
-
if (value === "true") params[key] = true;
|
|
7973
|
-
else if (value === "false") params[key] = false;
|
|
7974
|
-
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
7975
|
-
else {
|
|
7976
|
-
try {
|
|
7977
|
-
const parsed = JSON.parse(value);
|
|
7978
|
-
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
7979
|
-
params[key] = parsed;
|
|
7980
|
-
} else {
|
|
7981
|
-
params[key] = value;
|
|
7982
|
-
}
|
|
7983
|
-
} catch {
|
|
7984
|
-
params[key] = value;
|
|
7985
|
-
}
|
|
7986
|
-
}
|
|
7987
|
-
i++;
|
|
7988
|
-
} else {
|
|
7989
|
-
params[key] = true;
|
|
7990
|
-
}
|
|
7991
|
-
} else if (!args[i].startsWith("-")) {
|
|
7992
|
-
positionalValues.push(args[i]);
|
|
7993
|
-
}
|
|
7994
|
-
}
|
|
7995
|
-
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
7996
|
-
const result = {};
|
|
7997
|
-
for (const [k, v] of Object.entries(params)) {
|
|
7998
|
-
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
7999
|
-
result[camelKey] = v;
|
|
8000
|
-
}
|
|
8001
|
-
return result;
|
|
8171
|
+
function errorResult(message) {
|
|
8172
|
+
return { ...fail17(message), duration: 0 };
|
|
8173
|
+
}
|
|
8174
|
+
function tipsToMessages(tips) {
|
|
8175
|
+
if (!tips || tips.length === 0) return [];
|
|
8176
|
+
return tips.map((tip) => typeof tip === "string" ? tip : tip.message);
|
|
8002
8177
|
}
|
|
8178
|
+
var wsServer = null;
|
|
8179
|
+
function setWSServer(server) {
|
|
8180
|
+
wsServer = server;
|
|
8181
|
+
}
|
|
8182
|
+
function streamCommandEvent(sessionId, message) {
|
|
8183
|
+
if (!wsServer || !wsServer.getRunning()) return;
|
|
8184
|
+
wsServer.broadcastToSession(sessionId, { type: "command", data: message });
|
|
8185
|
+
}
|
|
8186
|
+
|
|
8187
|
+
// src/executor.ts
|
|
8188
|
+
import {
|
|
8189
|
+
ok as ok33,
|
|
8190
|
+
fail as fail19,
|
|
8191
|
+
isCommandResult,
|
|
8192
|
+
normalizeTips as normalizeTips8,
|
|
8193
|
+
TipCollector as TipCollector3
|
|
8194
|
+
} from "@dyyz1993/xcli-core";
|
|
8003
8195
|
|
|
8004
8196
|
// src/utils/stub-context.ts
|
|
8005
|
-
import { join as
|
|
8006
|
-
import { homedir as
|
|
8007
|
-
import { TipCollector, CompositeStorage } from "@dyyz1993/xcli-core";
|
|
8008
|
-
var
|
|
8197
|
+
import { join as join9 } from "path";
|
|
8198
|
+
import { homedir as homedir7 } from "os";
|
|
8199
|
+
import { TipCollector, CompositeStorage as CompositeStorage2 } from "@dyyz1993/xcli-core";
|
|
8200
|
+
var CONFIG_DIR2 = join9(homedir7(), ".xbrowser");
|
|
8009
8201
|
var NoopSiteInstance = class {
|
|
8010
8202
|
name = "stub";
|
|
8011
8203
|
url = "";
|
|
@@ -8028,7 +8220,7 @@ var NoopSiteInstance = class {
|
|
|
8028
8220
|
async requireLogin() {
|
|
8029
8221
|
}
|
|
8030
8222
|
getStorage() {
|
|
8031
|
-
return new
|
|
8223
|
+
return new CompositeStorage2("stub", CONFIG_DIR2, "xbrowser");
|
|
8032
8224
|
}
|
|
8033
8225
|
getAllCommands() {
|
|
8034
8226
|
return [];
|
|
@@ -8052,7 +8244,7 @@ function createStubContext(pluginName) {
|
|
|
8052
8244
|
args: [],
|
|
8053
8245
|
options: {},
|
|
8054
8246
|
cwd: process.cwd(),
|
|
8055
|
-
storage: new
|
|
8247
|
+
storage: new CompositeStorage2(pluginName, CONFIG_DIR2, "xbrowser"),
|
|
8056
8248
|
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
8057
8249
|
error: (msg) => {
|
|
8058
8250
|
throw new Error(msg);
|
|
@@ -8064,140 +8256,6 @@ function createStubContext(pluginName) {
|
|
|
8064
8256
|
};
|
|
8065
8257
|
}
|
|
8066
8258
|
|
|
8067
|
-
// src/utils/plugin-singleton.ts
|
|
8068
|
-
var pluginLoader = null;
|
|
8069
|
-
var pluginsScanned = false;
|
|
8070
|
-
function silenceSchemaWarnings(fn) {
|
|
8071
|
-
if (process.env.XBROWSER_DEBUG || process.env.VITEST_WORKER_ID) return fn();
|
|
8072
|
-
const originalWarn = console.warn;
|
|
8073
|
-
console.warn = (...args) => {
|
|
8074
|
-
const msg = typeof args[0] === "string" ? args[0] : "";
|
|
8075
|
-
if (msg.includes('has no "result" schema')) return;
|
|
8076
|
-
originalWarn(...args);
|
|
8077
|
-
};
|
|
8078
|
-
return fn().finally(() => {
|
|
8079
|
-
console.warn = originalWarn;
|
|
8080
|
-
});
|
|
8081
|
-
}
|
|
8082
|
-
async function getPluginLoader() {
|
|
8083
|
-
if (!pluginLoader) {
|
|
8084
|
-
pluginLoader = new XBrowserPluginLoader();
|
|
8085
|
-
}
|
|
8086
|
-
if (!pluginsScanned) {
|
|
8087
|
-
await silenceSchemaWarnings(() => pluginLoader.scanAndLoad());
|
|
8088
|
-
pluginsScanned = true;
|
|
8089
|
-
}
|
|
8090
|
-
return pluginLoader;
|
|
8091
|
-
}
|
|
8092
|
-
|
|
8093
|
-
// src/plugin/login-guard.ts
|
|
8094
|
-
async function checkPluginLoginRequired(options) {
|
|
8095
|
-
const { site, command, commandName, ctx, page, sessionName } = options;
|
|
8096
|
-
if (commandName === "login" || commandName === "logout") return { ok: true };
|
|
8097
|
-
const loginConfig = site.config?.loginConfig;
|
|
8098
|
-
const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
|
|
8099
|
-
if (!requiresLogin) return { ok: true };
|
|
8100
|
-
const pluginName = site.name || "plugin";
|
|
8101
|
-
const siteConfig = site.config;
|
|
8102
|
-
const configIsLogin = siteConfig?.isLogin;
|
|
8103
|
-
if (configIsLogin) {
|
|
8104
|
-
try {
|
|
8105
|
-
const loggedIn = await configIsLogin(ctx);
|
|
8106
|
-
if (loggedIn) return { ok: true };
|
|
8107
|
-
return buildLoginRequired({
|
|
8108
|
-
plugin: pluginName,
|
|
8109
|
-
command: commandName,
|
|
8110
|
-
reason: "config.isLogin returned false",
|
|
8111
|
-
sessionName,
|
|
8112
|
-
loginConfig
|
|
8113
|
-
});
|
|
8114
|
-
} catch {
|
|
8115
|
-
}
|
|
8116
|
-
}
|
|
8117
|
-
if (typeof site.isLoggedIn === "function") {
|
|
8118
|
-
try {
|
|
8119
|
-
const loggedIn = await site.isLoggedIn(ctx);
|
|
8120
|
-
if (loggedIn) return { ok: true };
|
|
8121
|
-
return buildLoginRequired({
|
|
8122
|
-
plugin: pluginName,
|
|
8123
|
-
command: commandName,
|
|
8124
|
-
reason: "plugin isLoggedIn returned false",
|
|
8125
|
-
sessionName,
|
|
8126
|
-
loginConfig
|
|
8127
|
-
});
|
|
8128
|
-
} catch {
|
|
8129
|
-
}
|
|
8130
|
-
}
|
|
8131
|
-
if (page && loginConfig) {
|
|
8132
|
-
const generic = await detectLoginFromPage(page, loginConfig);
|
|
8133
|
-
if (generic === "logged-in") return { ok: true };
|
|
8134
|
-
if (generic === "logged-out") {
|
|
8135
|
-
return buildLoginRequired({
|
|
8136
|
-
plugin: pluginName,
|
|
8137
|
-
command: commandName,
|
|
8138
|
-
reason: "generic loginConfig detected logged-out page",
|
|
8139
|
-
sessionName,
|
|
8140
|
-
loginConfig
|
|
8141
|
-
});
|
|
8142
|
-
}
|
|
8143
|
-
}
|
|
8144
|
-
return { ok: true };
|
|
8145
|
-
}
|
|
8146
|
-
function buildLoginRequired(options) {
|
|
8147
|
-
const viewerUrl = buildViewerUrl(options.sessionName);
|
|
8148
|
-
const loginUrl = options.loginConfig?.loginUrl;
|
|
8149
|
-
const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
|
|
8150
|
-
const tips = [
|
|
8151
|
-
message,
|
|
8152
|
-
...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
|
|
8153
|
-
...loginUrl ? [`Login page: ${loginUrl}`] : [],
|
|
8154
|
-
`After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
|
|
8155
|
-
];
|
|
8156
|
-
return {
|
|
8157
|
-
ok: false,
|
|
8158
|
-
data: {
|
|
8159
|
-
code: "LOGIN_REQUIRED",
|
|
8160
|
-
plugin: options.plugin,
|
|
8161
|
-
command: options.command,
|
|
8162
|
-
reason: options.reason,
|
|
8163
|
-
...viewerUrl ? { viewerUrl } : {},
|
|
8164
|
-
...loginUrl ? { loginUrl } : {}
|
|
8165
|
-
},
|
|
8166
|
-
message,
|
|
8167
|
-
tips
|
|
8168
|
-
};
|
|
8169
|
-
}
|
|
8170
|
-
async function detectLoginFromPage(page, config) {
|
|
8171
|
-
const url = page.url();
|
|
8172
|
-
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
8173
|
-
const result = await page.evaluate((cfg) => {
|
|
8174
|
-
const visible = (selector) => {
|
|
8175
|
-
try {
|
|
8176
|
-
const el = document.querySelector(selector);
|
|
8177
|
-
if (!el) return false;
|
|
8178
|
-
const rect = el.getBoundingClientRect();
|
|
8179
|
-
const style = window.getComputedStyle(el);
|
|
8180
|
-
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
8181
|
-
} catch {
|
|
8182
|
-
return false;
|
|
8183
|
-
}
|
|
8184
|
-
};
|
|
8185
|
-
if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
|
|
8186
|
-
if (cfg.loginSelectors?.some(visible)) return "logged-out";
|
|
8187
|
-
const bodyText = document.body?.innerText || "";
|
|
8188
|
-
const keywords = cfg.loginKeywords || [];
|
|
8189
|
-
if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
|
|
8190
|
-
return "logged-out";
|
|
8191
|
-
}
|
|
8192
|
-
return "unknown";
|
|
8193
|
-
}, {
|
|
8194
|
-
loginSelectors: config.loginSelectors || [],
|
|
8195
|
-
loginKeywords: config.loginKeywords || [],
|
|
8196
|
-
loggedInSelectors: config.loggedInSelectors || []
|
|
8197
|
-
});
|
|
8198
|
-
return result;
|
|
8199
|
-
}
|
|
8200
|
-
|
|
8201
8259
|
// src/tips/dom-watcher.ts
|
|
8202
8260
|
var DOM_WATCHER_SCRIPT = `
|
|
8203
8261
|
(function() {
|
|
@@ -8457,6 +8515,9 @@ var TipGenerator = class {
|
|
|
8457
8515
|
categoryLabel(category) {
|
|
8458
8516
|
const labels = {
|
|
8459
8517
|
dialog: "Dialog",
|
|
8518
|
+
filechooser: "File Chooser",
|
|
8519
|
+
popup: "Popup",
|
|
8520
|
+
download: "Download",
|
|
8460
8521
|
modal: "Modal",
|
|
8461
8522
|
popover: "Popover",
|
|
8462
8523
|
notification: "\u901A\u77E5",
|
|
@@ -8521,8 +8582,62 @@ var TipsManager = class {
|
|
|
8521
8582
|
generator = new TipGenerator(this.contextTracker);
|
|
8522
8583
|
beforeSnapshot = null;
|
|
8523
8584
|
lastDetectionTime = 0;
|
|
8585
|
+
// CDP 弹窗事件检测(filechooser / dialog / popup)
|
|
8586
|
+
detectedEvents = [];
|
|
8587
|
+
eventListenersAttached = false;
|
|
8588
|
+
lastCommandName = "";
|
|
8524
8589
|
async beforeCommand(page, commandName, params) {
|
|
8525
8590
|
this.contextTracker.record(commandName, params);
|
|
8591
|
+
this.lastCommandName = commandName;
|
|
8592
|
+
if (!this.eventListenersAttached && typeof page.on === "function") {
|
|
8593
|
+
this.eventListenersAttached = true;
|
|
8594
|
+
page.on("dialog", (dialog) => {
|
|
8595
|
+
const d = dialog;
|
|
8596
|
+
try {
|
|
8597
|
+
this.detectedEvents.push({
|
|
8598
|
+
type: "dialog",
|
|
8599
|
+
message: `[${d.type()}] ${d.message().slice(0, 200)}`,
|
|
8600
|
+
commandName: this.lastCommandName
|
|
8601
|
+
});
|
|
8602
|
+
} catch {
|
|
8603
|
+
}
|
|
8604
|
+
});
|
|
8605
|
+
page.on("filechooser", (chooser) => {
|
|
8606
|
+
const c = chooser;
|
|
8607
|
+
try {
|
|
8608
|
+
this.detectedEvents.push({
|
|
8609
|
+
type: "filechooser",
|
|
8610
|
+
message: `\u6587\u4EF6\u9009\u62E9\u5F39\u7A97${c.isMultiple ? "\uFF08\u591A\u9009\uFF09" : ""}\uFF1Aselector=${c.selector || "input[type=file]"}`,
|
|
8611
|
+
selector: c.selector,
|
|
8612
|
+
commandName: this.lastCommandName
|
|
8613
|
+
});
|
|
8614
|
+
} catch {
|
|
8615
|
+
}
|
|
8616
|
+
});
|
|
8617
|
+
page.on("popup", (info) => {
|
|
8618
|
+
const p = info;
|
|
8619
|
+
try {
|
|
8620
|
+
this.detectedEvents.push({
|
|
8621
|
+
type: "popup",
|
|
8622
|
+
message: `\u65B0\u7A97\u53E3\u5F39\u7A97\uFF1Aurl=${p.url || "(unknown)"}${p.windowName ? ` name=${p.windowName}` : ""}`,
|
|
8623
|
+
commandName: this.lastCommandName
|
|
8624
|
+
});
|
|
8625
|
+
} catch {
|
|
8626
|
+
}
|
|
8627
|
+
});
|
|
8628
|
+
page.on("download", (info) => {
|
|
8629
|
+
const d = info;
|
|
8630
|
+
try {
|
|
8631
|
+
const stateLabel = d.state === "completed" ? "\u5B8C\u6210" : d.state === "canceled" ? "\u53D6\u6D88" : "\u5F00\u59CB";
|
|
8632
|
+
this.detectedEvents.push({
|
|
8633
|
+
type: "download",
|
|
8634
|
+
message: `\u6587\u4EF6\u4E0B\u8F7D${stateLabel}\uFF1A${d.filename || "unknown"}${d.url ? ` (${d.url.slice(0, 80)})` : ""}`,
|
|
8635
|
+
commandName: this.lastCommandName
|
|
8636
|
+
});
|
|
8637
|
+
} catch {
|
|
8638
|
+
}
|
|
8639
|
+
});
|
|
8640
|
+
}
|
|
8526
8641
|
if (!this.domWatcher) {
|
|
8527
8642
|
this.domWatcher = new DomWatcher(page);
|
|
8528
8643
|
}
|
|
@@ -8565,20 +8680,59 @@ var TipsManager = class {
|
|
|
8565
8680
|
}
|
|
8566
8681
|
}
|
|
8567
8682
|
async afterCommand() {
|
|
8568
|
-
if (!this.domWatcher || !this.beforeSnapshot)
|
|
8683
|
+
if (!this.domWatcher || !this.beforeSnapshot) {
|
|
8684
|
+
const cdpTips = this.collectCdpEventTips();
|
|
8685
|
+
this.detectedEvents = [];
|
|
8686
|
+
return cdpTips;
|
|
8687
|
+
}
|
|
8569
8688
|
await this.debounce();
|
|
8570
8689
|
try {
|
|
8571
8690
|
const currentElements = await this.domWatcher.scanOverlays();
|
|
8572
8691
|
const afterSnapshot = buildSnapshot(currentElements);
|
|
8573
8692
|
const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
|
|
8574
8693
|
const tips = this.generator.generate(newElements);
|
|
8694
|
+
const cdpTips = this.collectCdpEventTips();
|
|
8695
|
+
tips.push(...cdpTips);
|
|
8575
8696
|
this.beforeSnapshot = null;
|
|
8697
|
+
this.detectedEvents = [];
|
|
8576
8698
|
return tips;
|
|
8577
8699
|
} catch {
|
|
8700
|
+
const cdpTips = this.collectCdpEventTips();
|
|
8578
8701
|
this.beforeSnapshot = null;
|
|
8579
|
-
|
|
8702
|
+
this.detectedEvents = [];
|
|
8703
|
+
return cdpTips;
|
|
8580
8704
|
}
|
|
8581
8705
|
}
|
|
8706
|
+
/**
|
|
8707
|
+
* 把检测到的 CDP 弹窗事件转成 SmartTip
|
|
8708
|
+
* 包括:dialog(alert/confirm/prompt)、filechooser(文件选择弹窗)、popup(新窗口)
|
|
8709
|
+
*/
|
|
8710
|
+
collectCdpEventTips() {
|
|
8711
|
+
if (this.detectedEvents.length === 0) return [];
|
|
8712
|
+
return this.detectedEvents.map((evt) => {
|
|
8713
|
+
const suggestions = [];
|
|
8714
|
+
if (evt.type === "dialog") {
|
|
8715
|
+
suggestions.push("\u6B64\u5F39\u7A97\u53EF\u80FD\u963B\u585E\u540E\u7EED\u64CD\u4F5C");
|
|
8716
|
+
suggestions.push('\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 page.on("dialog") \u62E6\u622A');
|
|
8717
|
+
} else if (evt.type === "filechooser") {
|
|
8718
|
+
suggestions.push("\u6B64\u5F39\u7A97\u7531\u9875\u9762\u64CD\u4F5C\u89E6\u53D1\uFF08\u5982\u70B9\u51FB\u4E0A\u4F20\u6309\u94AE\uFF09");
|
|
8719
|
+
suggestions.push("\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 --path/--paths \u53C2\u6570\u4E0A\u4F20\u6587\u4EF6");
|
|
8720
|
+
} else if (evt.type === "popup") {
|
|
8721
|
+
suggestions.push("\u9875\u9762\u5C1D\u8BD5\u6253\u5F00\u65B0\u7A97\u53E3\uFF08\u53EF\u80FD\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF09");
|
|
8722
|
+
suggestions.push('\u5982\u9700\u5904\u7406\uFF1A\u68C0\u67E5\u5F39\u7A97\u62E6\u622A\u8BBE\u7F6E\u6216\u4F7F\u7528 page.on("popup") \u76D1\u542C');
|
|
8723
|
+
} else if (evt.type === "download") {
|
|
8724
|
+
suggestions.push("\u9875\u9762\u89E6\u53D1\u4E86\u6587\u4EF6\u4E0B\u8F7D");
|
|
8725
|
+
suggestions.push("\u5982\u9700\u63A7\u5236\u8DEF\u5F84\uFF1Apage.setDownloadBehavior(path)");
|
|
8726
|
+
}
|
|
8727
|
+
return {
|
|
8728
|
+
category: evt.type,
|
|
8729
|
+
priority: "p1",
|
|
8730
|
+
message: `\u{1F514} [\u5F39\u7A97\u68C0\u6D4B] ${evt.message}\uFF08\u89E6\u53D1\u547D\u4EE4: ${evt.commandName || "\u672A\u77E5"}\uFF09`,
|
|
8731
|
+
selector: evt.selector,
|
|
8732
|
+
suggestions
|
|
8733
|
+
};
|
|
8734
|
+
});
|
|
8735
|
+
}
|
|
8582
8736
|
debounce() {
|
|
8583
8737
|
const ms = tipsDebounceMs();
|
|
8584
8738
|
if (ms <= 0) return Promise.resolve();
|
|
@@ -8599,6 +8753,9 @@ var TipsManager = class {
|
|
|
8599
8753
|
this.contextTracker.clear();
|
|
8600
8754
|
this.domWatcher = null;
|
|
8601
8755
|
this.lastDetectionTime = 0;
|
|
8756
|
+
this.detectedEvents = [];
|
|
8757
|
+
this.eventListenersAttached = false;
|
|
8758
|
+
this.lastCommandName = "";
|
|
8602
8759
|
}
|
|
8603
8760
|
};
|
|
8604
8761
|
var globalTipsManager = null;
|
|
@@ -8698,75 +8855,521 @@ async function loadHooks() {
|
|
|
8698
8855
|
return hooks;
|
|
8699
8856
|
}
|
|
8700
8857
|
|
|
8701
|
-
// src/
|
|
8702
|
-
|
|
8703
|
-
|
|
8704
|
-
|
|
8705
|
-
|
|
8706
|
-
|
|
8707
|
-
|
|
8708
|
-
|
|
8709
|
-
|
|
8710
|
-
|
|
8711
|
-
|
|
8712
|
-
|
|
8713
|
-
|
|
8714
|
-
|
|
8715
|
-
|
|
8716
|
-
|
|
8717
|
-
|
|
8718
|
-
|
|
8719
|
-
|
|
8720
|
-
|
|
8721
|
-
if (
|
|
8722
|
-
|
|
8723
|
-
|
|
8724
|
-
|
|
8725
|
-
|
|
8726
|
-
|
|
8727
|
-
|
|
8728
|
-
|
|
8729
|
-
|
|
8730
|
-
|
|
8731
|
-
|
|
8732
|
-
|
|
8733
|
-
|
|
8734
|
-
|
|
8735
|
-
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
|
|
8739
|
-
|
|
8740
|
-
|
|
8741
|
-
|
|
8858
|
+
// src/fail-codes.ts
|
|
8859
|
+
var FAIL_CODES = {
|
|
8860
|
+
selectorNotFound: "RETRYABLE: selector-not-found",
|
|
8861
|
+
pageNotReady: "RETRYABLE: page-not-ready",
|
|
8862
|
+
elementGone: "RETRYABLE: element-gone",
|
|
8863
|
+
inputNotRetained: "RETRYABLE: input-not-retained",
|
|
8864
|
+
captcha: "HUMAN: captcha",
|
|
8865
|
+
loginWall: "HUMAN: login-wall",
|
|
8866
|
+
permissionDenied: "FATAL: permission-denied",
|
|
8867
|
+
targetGone: "FATAL: target-gone",
|
|
8868
|
+
unknown: "FATAL: unknown"
|
|
8869
|
+
};
|
|
8870
|
+
function classifyFailure(message) {
|
|
8871
|
+
const msg = (message || "").toLowerCase();
|
|
8872
|
+
const pick = (code) => ({
|
|
8873
|
+
code,
|
|
8874
|
+
level: code.split(":")[0],
|
|
8875
|
+
message: message || code
|
|
8876
|
+
});
|
|
8877
|
+
if (/captcha|验证码|人机校验|recaptcha|hcaptcha|turnstile/.test(msg)) return pick(FAIL_CODES.captcha);
|
|
8878
|
+
if (/login|登录|signin|sign in|未登录|login-required|LOGIN_REQUIRED/.test(msg)) return pick(FAIL_CODES.loginWall);
|
|
8879
|
+
if (/permission|权限|not allowed|forbidden|EACCES/.test(msg)) return pick(FAIL_CODES.permissionDenied);
|
|
8880
|
+
if (/selector|选择器|element not found|未找到元素|no such element|queryselector returned null/.test(msg))
|
|
8881
|
+
return pick(FAIL_CODES.selectorNotFound);
|
|
8882
|
+
if (/timeout|超时|timed out|waiting for/.test(msg)) return pick(FAIL_CODES.pageNotReady);
|
|
8883
|
+
if (/not retained|清空了注入值|input-not-retained/.test(msg)) return pick(FAIL_CODES.inputNotRetained);
|
|
8884
|
+
if (/net::err|404|navigation failed|页面不存在|target closed|element-gone/.test(msg))
|
|
8885
|
+
return pick(FAIL_CODES.targetGone);
|
|
8886
|
+
return pick(FAIL_CODES.unknown);
|
|
8887
|
+
}
|
|
8888
|
+
|
|
8889
|
+
// src/executor/chain.ts
|
|
8890
|
+
import {
|
|
8891
|
+
fail as fail18,
|
|
8892
|
+
ok as ok32,
|
|
8893
|
+
TipCollector as TipCollector2,
|
|
8894
|
+
normalizeTips as normalizeTips7,
|
|
8895
|
+
unquote as unquote2
|
|
8896
|
+
} from "@dyyz1993/xcli-core";
|
|
8897
|
+
|
|
8898
|
+
// src/plugin/login-guard.ts
|
|
8899
|
+
async function checkPluginLoginRequired(options) {
|
|
8900
|
+
const { site, command, commandName, ctx, page, sessionName } = options;
|
|
8901
|
+
if (commandName === "login" || commandName === "logout") return { ok: true };
|
|
8902
|
+
const loginConfig = site.config?.loginConfig;
|
|
8903
|
+
const requiresLogin = command.requiresLogin === true || site.config?.requiresLogin === true || loginConfig?.requiresLogin === true || command.loginRequired === "required";
|
|
8904
|
+
if (!requiresLogin) return { ok: true };
|
|
8905
|
+
const pluginName = site.name || "plugin";
|
|
8906
|
+
const siteConfig = site.config;
|
|
8907
|
+
const configIsLogin = siteConfig?.isLogin;
|
|
8908
|
+
if (configIsLogin) {
|
|
8909
|
+
try {
|
|
8910
|
+
const loggedIn = await configIsLogin(ctx);
|
|
8911
|
+
if (loggedIn) return { ok: true };
|
|
8912
|
+
return buildLoginRequired({
|
|
8913
|
+
plugin: pluginName,
|
|
8914
|
+
command: commandName,
|
|
8915
|
+
reason: "config.isLogin returned false",
|
|
8916
|
+
sessionName,
|
|
8917
|
+
loginConfig
|
|
8918
|
+
});
|
|
8919
|
+
} catch {
|
|
8920
|
+
}
|
|
8921
|
+
}
|
|
8922
|
+
if (typeof site.isLoggedIn === "function") {
|
|
8923
|
+
try {
|
|
8924
|
+
const loggedIn = await site.isLoggedIn(ctx);
|
|
8925
|
+
if (loggedIn) return { ok: true };
|
|
8926
|
+
return buildLoginRequired({
|
|
8927
|
+
plugin: pluginName,
|
|
8928
|
+
command: commandName,
|
|
8929
|
+
reason: "plugin isLoggedIn returned false",
|
|
8930
|
+
sessionName,
|
|
8931
|
+
loginConfig
|
|
8932
|
+
});
|
|
8933
|
+
} catch {
|
|
8934
|
+
}
|
|
8935
|
+
}
|
|
8936
|
+
if (page && loginConfig) {
|
|
8937
|
+
const generic = await detectLoginFromPage(page, loginConfig);
|
|
8938
|
+
if (generic === "logged-in") return { ok: true };
|
|
8939
|
+
if (generic === "logged-out") {
|
|
8940
|
+
return buildLoginRequired({
|
|
8941
|
+
plugin: pluginName,
|
|
8942
|
+
command: commandName,
|
|
8943
|
+
reason: "generic loginConfig detected logged-out page",
|
|
8944
|
+
sessionName,
|
|
8945
|
+
loginConfig
|
|
8946
|
+
});
|
|
8947
|
+
}
|
|
8948
|
+
}
|
|
8949
|
+
return { ok: true };
|
|
8950
|
+
}
|
|
8951
|
+
function buildLoginRequired(options) {
|
|
8952
|
+
const viewerUrl = buildViewerUrl(options.sessionName);
|
|
8953
|
+
const loginUrl = options.loginConfig?.loginUrl;
|
|
8954
|
+
const message = options.loginConfig?.loginPrompt || `Plugin "${options.plugin}" requires login before running "${options.command}".`;
|
|
8955
|
+
const tips = [
|
|
8956
|
+
message,
|
|
8957
|
+
...viewerUrl ? [`Open viewer to complete login: ${viewerUrl}`] : [],
|
|
8958
|
+
...loginUrl ? [`Login page: ${loginUrl}`] : [],
|
|
8959
|
+
`After login, retry: xbrowser ${options.plugin} ${options.command} --session ${options.sessionName}`
|
|
8960
|
+
];
|
|
8961
|
+
return {
|
|
8962
|
+
ok: false,
|
|
8963
|
+
data: {
|
|
8964
|
+
code: "LOGIN_REQUIRED",
|
|
8965
|
+
plugin: options.plugin,
|
|
8966
|
+
command: options.command,
|
|
8967
|
+
reason: options.reason,
|
|
8968
|
+
...viewerUrl ? { viewerUrl } : {},
|
|
8969
|
+
...loginUrl ? { loginUrl } : {}
|
|
8970
|
+
},
|
|
8971
|
+
message,
|
|
8972
|
+
tips
|
|
8973
|
+
};
|
|
8974
|
+
}
|
|
8975
|
+
async function detectLoginFromPage(page, config) {
|
|
8976
|
+
const url = page.url();
|
|
8977
|
+
if (config.loginUrls?.some((part) => url.includes(part))) return "logged-out";
|
|
8978
|
+
const result = await page.evaluate((cfg) => {
|
|
8979
|
+
const visible = (selector) => {
|
|
8980
|
+
try {
|
|
8981
|
+
const el = document.querySelector(selector);
|
|
8982
|
+
if (!el) return false;
|
|
8983
|
+
const rect = el.getBoundingClientRect();
|
|
8984
|
+
const style = window.getComputedStyle(el);
|
|
8985
|
+
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
|
|
8986
|
+
} catch {
|
|
8987
|
+
return false;
|
|
8988
|
+
}
|
|
8989
|
+
};
|
|
8990
|
+
if (cfg.loggedInSelectors?.some(visible)) return "logged-in";
|
|
8991
|
+
if (cfg.loginSelectors?.some(visible)) return "logged-out";
|
|
8992
|
+
const bodyText = document.body?.innerText || "";
|
|
8993
|
+
const keywords = cfg.loginKeywords || [];
|
|
8994
|
+
if (keywords.length > 0 && keywords.every((keyword) => bodyText.includes(keyword))) {
|
|
8995
|
+
return "logged-out";
|
|
8996
|
+
}
|
|
8997
|
+
return "unknown";
|
|
8998
|
+
}, {
|
|
8999
|
+
loginSelectors: config.loginSelectors || [],
|
|
9000
|
+
loginKeywords: config.loginKeywords || [],
|
|
9001
|
+
loggedInSelectors: config.loggedInSelectors || []
|
|
9002
|
+
});
|
|
9003
|
+
return result;
|
|
9004
|
+
}
|
|
9005
|
+
|
|
9006
|
+
// src/utils/positional-params.ts
|
|
9007
|
+
import { unquote } from "@dyyz1993/xcli-core";
|
|
9008
|
+
function getTypeName(field) {
|
|
9009
|
+
return field?._def?.typeName;
|
|
9010
|
+
}
|
|
9011
|
+
function unwrapField(field) {
|
|
9012
|
+
const typeName = getTypeName(field);
|
|
9013
|
+
if (typeName === "ZodOptional" || typeName === "ZodDefault") {
|
|
9014
|
+
const innerType = field?._def?.innerType;
|
|
9015
|
+
return unwrapField(innerType);
|
|
9016
|
+
}
|
|
9017
|
+
return field;
|
|
9018
|
+
}
|
|
9019
|
+
function isOptionalNumber(field) {
|
|
9020
|
+
const typeName = getTypeName(field);
|
|
9021
|
+
return typeName === "ZodOptional" && getTypeName(unwrapField(field)) === "ZodNumber";
|
|
9022
|
+
}
|
|
9023
|
+
function coerceValue(raw, field) {
|
|
9024
|
+
const inner = unwrapField(field);
|
|
9025
|
+
const optionalNum = isOptionalNumber(field);
|
|
9026
|
+
const innerTypeName = getTypeName(inner);
|
|
9027
|
+
if (innerTypeName === "ZodString") {
|
|
9028
|
+
return { value: unquote(raw), skip: false };
|
|
9029
|
+
}
|
|
9030
|
+
if (innerTypeName === "ZodNumber") {
|
|
9031
|
+
const parsed = Number(raw);
|
|
9032
|
+
if (isNaN(parsed)) {
|
|
9033
|
+
if (optionalNum) return { value: void 0, skip: true };
|
|
9034
|
+
return { value: raw, skip: false };
|
|
9035
|
+
}
|
|
9036
|
+
return { value: parsed, skip: false };
|
|
9037
|
+
}
|
|
9038
|
+
if (innerTypeName === "ZodBoolean") {
|
|
9039
|
+
if (raw === "true" || raw === "1") return { value: true, skip: false };
|
|
9040
|
+
if (raw === "false" || raw === "0") return { value: false, skip: false };
|
|
9041
|
+
return { value: raw, skip: false };
|
|
9042
|
+
}
|
|
9043
|
+
return { value: unquote(raw), skip: false };
|
|
9044
|
+
}
|
|
9045
|
+
function mapPositionalValues(schema, positional, existing) {
|
|
9046
|
+
const result = { ...existing };
|
|
9047
|
+
if (!schema || typeof schema !== "object") return result;
|
|
9048
|
+
const shape = schema.shape;
|
|
9049
|
+
if (!shape || typeof shape !== "object") return result;
|
|
9050
|
+
const keys = Object.keys(shape);
|
|
9051
|
+
let pIdx = 0;
|
|
9052
|
+
for (const key of keys) {
|
|
9053
|
+
if (pIdx >= positional.length) break;
|
|
9054
|
+
if (result[key] !== void 0) {
|
|
9055
|
+
pIdx++;
|
|
9056
|
+
continue;
|
|
9057
|
+
}
|
|
9058
|
+
const field = shape[key];
|
|
9059
|
+
const raw = positional[pIdx];
|
|
9060
|
+
const { value, skip } = coerceValue(raw, field);
|
|
9061
|
+
if (skip) continue;
|
|
9062
|
+
result[key] = value;
|
|
9063
|
+
pIdx++;
|
|
9064
|
+
}
|
|
9065
|
+
return result;
|
|
9066
|
+
}
|
|
9067
|
+
|
|
9068
|
+
// src/utils/plugin-params.ts
|
|
9069
|
+
function schemaFieldType(schema, key) {
|
|
9070
|
+
const shape = schema?.shape;
|
|
9071
|
+
const field = shape?.[key];
|
|
9072
|
+
let current = field;
|
|
9073
|
+
while (current) {
|
|
9074
|
+
const def = current._def;
|
|
9075
|
+
if (!def) return void 0;
|
|
9076
|
+
const type = def.typeName ?? def.type;
|
|
9077
|
+
if (type === "ZodOptional" || type === "ZodDefault" || type === "ZodNullable" || type === "optional" || type === "default" || type === "nullable") {
|
|
9078
|
+
current = def.innerType ?? def.inner;
|
|
9079
|
+
continue;
|
|
9080
|
+
}
|
|
9081
|
+
return type;
|
|
9082
|
+
}
|
|
9083
|
+
return void 0;
|
|
9084
|
+
}
|
|
9085
|
+
function parsePluginParams(args, schema, base = {}) {
|
|
9086
|
+
const params = { ...base };
|
|
9087
|
+
const positionalValues = [];
|
|
9088
|
+
for (let i = 0; i < args.length; i++) {
|
|
9089
|
+
if (args[i] === "--" && args[i + 1]) {
|
|
9090
|
+
try {
|
|
9091
|
+
Object.assign(params, JSON.parse(args[i + 1]));
|
|
9092
|
+
} catch {
|
|
9093
|
+
}
|
|
9094
|
+
break;
|
|
9095
|
+
}
|
|
9096
|
+
if (args[i].startsWith("--")) {
|
|
9097
|
+
const key = args[i].slice(2);
|
|
9098
|
+
const value = args[i + 1];
|
|
9099
|
+
if (value && !value.startsWith("-")) {
|
|
9100
|
+
const type = schemaFieldType(schema, key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
|
|
9101
|
+
if (type === "ZodString" || type === "string") params[key] = value;
|
|
9102
|
+
else if (value === "true") params[key] = true;
|
|
9103
|
+
else if (value === "false") params[key] = false;
|
|
9104
|
+
else if (/^\d+$/.test(value)) params[key] = parseInt(value, 10);
|
|
9105
|
+
else {
|
|
9106
|
+
try {
|
|
9107
|
+
const parsed = JSON.parse(value);
|
|
9108
|
+
if (Array.isArray(parsed) || typeof parsed === "object" && parsed !== null) {
|
|
9109
|
+
params[key] = parsed;
|
|
9110
|
+
} else {
|
|
9111
|
+
params[key] = value;
|
|
9112
|
+
}
|
|
9113
|
+
} catch {
|
|
9114
|
+
params[key] = value;
|
|
9115
|
+
}
|
|
9116
|
+
}
|
|
9117
|
+
i++;
|
|
9118
|
+
} else {
|
|
9119
|
+
params[key] = true;
|
|
9120
|
+
}
|
|
9121
|
+
} else if (!args[i].startsWith("-")) {
|
|
9122
|
+
positionalValues.push(args[i]);
|
|
9123
|
+
}
|
|
9124
|
+
}
|
|
9125
|
+
Object.assign(params, mapPositionalValues(schema, positionalValues, params));
|
|
9126
|
+
const result = {};
|
|
9127
|
+
for (const [k, v] of Object.entries(params)) {
|
|
9128
|
+
const camelKey = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
9129
|
+
result[camelKey] = v;
|
|
9130
|
+
}
|
|
9131
|
+
return result;
|
|
9132
|
+
}
|
|
9133
|
+
|
|
9134
|
+
// src/executor/chain.ts
|
|
9135
|
+
async function executeChain(input, options, executeCommand2) {
|
|
9136
|
+
const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
|
|
9137
|
+
const sessionName = options?.sessionName || "default";
|
|
9138
|
+
const results = [];
|
|
9139
|
+
const totalStart = Date.now();
|
|
9140
|
+
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
9141
|
+
if (!session) {
|
|
9142
|
+
const launchOpts = {};
|
|
9143
|
+
if (options?.cdpEndpoint) launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
9144
|
+
session = await createSession(sessionName, void 0, launchOpts);
|
|
9145
|
+
saveSessionDiskMeta(sessionName, {
|
|
9146
|
+
id: session.id,
|
|
9147
|
+
name: sessionName,
|
|
9148
|
+
url: session.page.url(),
|
|
9149
|
+
createdAt: session.createdAt,
|
|
9150
|
+
cdpEndpoint: session.cdpEndpoint
|
|
9151
|
+
});
|
|
8742
9152
|
}
|
|
8743
|
-
}
|
|
8744
|
-
async function guardCheck(commandName) {
|
|
8745
9153
|
try {
|
|
8746
|
-
const
|
|
8747
|
-
|
|
8748
|
-
|
|
8749
|
-
|
|
8750
|
-
|
|
9154
|
+
for (const pipeline of pipelines) {
|
|
9155
|
+
const { type, pipeline: commands } = pipeline;
|
|
9156
|
+
for (const cmdStr of commands) {
|
|
9157
|
+
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
9158
|
+
await new Promise((resolve3) => setTimeout(resolve3, 800 + Math.random() * 1700));
|
|
9159
|
+
}
|
|
9160
|
+
const parts = splitCommand(cmdStr);
|
|
9161
|
+
if (parts.length === 0) continue;
|
|
9162
|
+
const cmdName = parts[0];
|
|
9163
|
+
const cmdArgs = parts.slice(1);
|
|
9164
|
+
const loader = await getPluginLoader();
|
|
9165
|
+
const internalLoader = loader.getCore().loader;
|
|
9166
|
+
const resolvedName = loader.resolveSiteName(cmdName);
|
|
9167
|
+
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
9168
|
+
if (site) {
|
|
9169
|
+
const pluginHandled = await executePluginChainStep({
|
|
9170
|
+
site,
|
|
9171
|
+
cmdName,
|
|
9172
|
+
cmdArgs,
|
|
9173
|
+
cmdStr,
|
|
9174
|
+
type,
|
|
9175
|
+
results,
|
|
9176
|
+
totalStart,
|
|
9177
|
+
session,
|
|
9178
|
+
sessionName
|
|
9179
|
+
});
|
|
9180
|
+
if (pluginHandled) return pluginHandled;
|
|
9181
|
+
continue;
|
|
9182
|
+
}
|
|
9183
|
+
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
9184
|
+
if (options?.frame && params._frame === void 0 && params.frame === void 0) {
|
|
9185
|
+
params._frame = options.frame;
|
|
9186
|
+
}
|
|
9187
|
+
if (cmdName === "goto" && params.url) {
|
|
9188
|
+
const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
9189
|
+
if (!existing) {
|
|
9190
|
+
session = await createSession(sessionName, params.url, {
|
|
9191
|
+
cdpEndpoint: options?.cdpEndpoint
|
|
9192
|
+
});
|
|
9193
|
+
}
|
|
9194
|
+
}
|
|
9195
|
+
const result = await executeCommand2(cmdName, params, sessionName, {
|
|
9196
|
+
cdpEndpoint: options?.cdpEndpoint,
|
|
9197
|
+
skipCleanup: true
|
|
9198
|
+
});
|
|
9199
|
+
results.push({
|
|
9200
|
+
command: cmdName,
|
|
9201
|
+
raw: cmdStr,
|
|
9202
|
+
success: result.success,
|
|
9203
|
+
data: result.data,
|
|
9204
|
+
message: result.message,
|
|
9205
|
+
duration: 0,
|
|
9206
|
+
tips: result.tips,
|
|
9207
|
+
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
9208
|
+
});
|
|
9209
|
+
if (type === "and" && !result.success) {
|
|
9210
|
+
return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): ${result.message}`);
|
|
9211
|
+
}
|
|
9212
|
+
if (type === "or" && result.success) {
|
|
9213
|
+
return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName}' succeeded (|| chain)`);
|
|
9214
|
+
}
|
|
9215
|
+
}
|
|
9216
|
+
}
|
|
9217
|
+
return {
|
|
9218
|
+
success: !results.some((result) => !result.success),
|
|
9219
|
+
steps: results,
|
|
9220
|
+
totalDuration: Date.now() - totalStart
|
|
9221
|
+
};
|
|
9222
|
+
} finally {
|
|
8751
9223
|
}
|
|
8752
9224
|
}
|
|
8753
|
-
function
|
|
8754
|
-
return {
|
|
8755
|
-
|
|
8756
|
-
|
|
8757
|
-
|
|
8758
|
-
|
|
9225
|
+
function stoppedChain(success, steps, totalStart, stoppedAt, reason) {
|
|
9226
|
+
return {
|
|
9227
|
+
success,
|
|
9228
|
+
steps,
|
|
9229
|
+
totalDuration: Date.now() - totalStart,
|
|
9230
|
+
stoppedAt,
|
|
9231
|
+
stoppedReason: reason
|
|
9232
|
+
};
|
|
8759
9233
|
}
|
|
8760
|
-
|
|
8761
|
-
|
|
8762
|
-
|
|
9234
|
+
async function executePluginChainStep(context) {
|
|
9235
|
+
const { site, cmdName, cmdArgs, cmdStr, type, results, totalStart, session, sessionName } = context;
|
|
9236
|
+
const subCommand = cmdArgs[0];
|
|
9237
|
+
if (!subCommand) {
|
|
9238
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Plugin "${cmdName}" requires a sub-command`), duration: 0 });
|
|
9239
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): no sub-command`);
|
|
9240
|
+
return void 0;
|
|
9241
|
+
}
|
|
9242
|
+
const cmdEntry = site.getCommand(subCommand);
|
|
9243
|
+
if (!cmdEntry) {
|
|
9244
|
+
results.push({ command: cmdName, raw: cmdStr, ...fail18(`Unknown command "${subCommand}" for plugin "${cmdName}"`), duration: 0 });
|
|
9245
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`);
|
|
9246
|
+
return void 0;
|
|
9247
|
+
}
|
|
9248
|
+
const pluginArgs = cmdArgs.slice(1);
|
|
9249
|
+
const pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
9250
|
+
if (cmdEntry.parameters) {
|
|
9251
|
+
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
9252
|
+
if (schemaCheck.success) {
|
|
9253
|
+
for (const [key, value] of Object.entries(schemaCheck.data)) {
|
|
9254
|
+
if (!(key in pluginParams)) pluginParams[key] = value;
|
|
9255
|
+
}
|
|
9256
|
+
}
|
|
9257
|
+
}
|
|
9258
|
+
const pluginCtx = {
|
|
9259
|
+
args: pluginArgs,
|
|
9260
|
+
options: pluginParams,
|
|
9261
|
+
cwd: process.cwd(),
|
|
9262
|
+
page: session.page,
|
|
9263
|
+
browser: session.context.browser(),
|
|
9264
|
+
browserContext: session.context,
|
|
9265
|
+
sessionId: session.id,
|
|
9266
|
+
storage: getPluginStorage(cmdName),
|
|
9267
|
+
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
9268
|
+
error: (message) => {
|
|
9269
|
+
throw new Error(message);
|
|
9270
|
+
},
|
|
9271
|
+
config: {},
|
|
9272
|
+
site,
|
|
9273
|
+
cliName: "xbrowser",
|
|
9274
|
+
tips: new TipCollector2()
|
|
9275
|
+
};
|
|
9276
|
+
const start = Date.now();
|
|
9277
|
+
try {
|
|
9278
|
+
const loginGuard = await checkPluginLoginRequired({
|
|
9279
|
+
site,
|
|
9280
|
+
command: cmdEntry,
|
|
9281
|
+
commandName: subCommand,
|
|
9282
|
+
ctx: pluginCtx,
|
|
9283
|
+
page: session.page,
|
|
9284
|
+
sessionName
|
|
9285
|
+
});
|
|
9286
|
+
if (!loginGuard.ok) {
|
|
9287
|
+
const duration2 = Date.now() - start;
|
|
9288
|
+
const data2 = loginGuard.data ?? null;
|
|
9289
|
+
recordArchive(session.id, sessionName, {
|
|
9290
|
+
step: results.length,
|
|
9291
|
+
command: `${cmdName} ${subCommand}`,
|
|
9292
|
+
params: pluginParams,
|
|
9293
|
+
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
9294
|
+
toolCalls: [],
|
|
9295
|
+
duration: duration2,
|
|
9296
|
+
timestamp: start
|
|
9297
|
+
});
|
|
9298
|
+
results.push({
|
|
9299
|
+
command: `${cmdName} ${subCommand}`,
|
|
9300
|
+
raw: cmdStr,
|
|
9301
|
+
success: false,
|
|
9302
|
+
data: data2,
|
|
9303
|
+
message: loginGuard.message,
|
|
9304
|
+
tips: normalizeTips7(loginGuard.tips),
|
|
9305
|
+
duration: duration2
|
|
9306
|
+
});
|
|
9307
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`);
|
|
9308
|
+
return void 0;
|
|
9309
|
+
}
|
|
9310
|
+
const hooks = await loadHooks();
|
|
9311
|
+
if (hooks.length > 0) {
|
|
9312
|
+
await Promise.all(hooks.map((hook) => hook.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
9313
|
+
}
|
|
9314
|
+
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
9315
|
+
const duration = Date.now() - start;
|
|
9316
|
+
let hookOutputs;
|
|
9317
|
+
if (hooks.length > 0) {
|
|
9318
|
+
const outputs = [];
|
|
9319
|
+
for (const hook of hooks) {
|
|
9320
|
+
const output = await hook.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration });
|
|
9321
|
+
if (output) outputs.push({ _hook: hook.name, ...output });
|
|
9322
|
+
}
|
|
9323
|
+
if (outputs.length > 0) hookOutputs = outputs;
|
|
9324
|
+
}
|
|
9325
|
+
const data = raw?.data ?? raw;
|
|
9326
|
+
recordArchive(session.id, sessionName, {
|
|
9327
|
+
step: results.length,
|
|
9328
|
+
command: `${cmdName} ${subCommand}`,
|
|
9329
|
+
params: pluginParams,
|
|
9330
|
+
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
9331
|
+
toolCalls: [],
|
|
9332
|
+
duration,
|
|
9333
|
+
timestamp: start
|
|
9334
|
+
});
|
|
9335
|
+
results.push({
|
|
9336
|
+
command: `${cmdName} ${subCommand}`,
|
|
9337
|
+
raw: cmdStr,
|
|
9338
|
+
...ok32(data),
|
|
9339
|
+
duration,
|
|
9340
|
+
...hookOutputs ? { hookOutputs } : {}
|
|
9341
|
+
});
|
|
9342
|
+
if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
|
|
9343
|
+
} catch (error) {
|
|
9344
|
+
const duration = Date.now() - start;
|
|
9345
|
+
const message = errMsg(error);
|
|
9346
|
+
recordArchive(session.id, sessionName, {
|
|
9347
|
+
step: results.length,
|
|
9348
|
+
command: `${cmdName} ${subCommand}`,
|
|
9349
|
+
params: pluginParams,
|
|
9350
|
+
result: { success: false, data: null, message, tips: [] },
|
|
9351
|
+
toolCalls: [],
|
|
9352
|
+
duration,
|
|
9353
|
+
timestamp: start
|
|
9354
|
+
});
|
|
9355
|
+
results.push({ command: `${cmdName} ${subCommand}`, raw: cmdStr, ...fail18(message), duration });
|
|
9356
|
+
if (type === "and") return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${message}`);
|
|
9357
|
+
}
|
|
9358
|
+
return void 0;
|
|
8763
9359
|
}
|
|
8764
|
-
|
|
8765
|
-
|
|
8766
|
-
|
|
8767
|
-
|
|
8768
|
-
|
|
8769
|
-
|
|
9360
|
+
|
|
9361
|
+
// src/executor.ts
|
|
9362
|
+
function levenshtein(a, b) {
|
|
9363
|
+
const m = a.length, n = b.length;
|
|
9364
|
+
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
9365
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
9366
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
9367
|
+
for (let i = 1; i <= m; i++) {
|
|
9368
|
+
for (let j = 1; j <= n; j++) {
|
|
9369
|
+
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]);
|
|
9370
|
+
}
|
|
9371
|
+
}
|
|
9372
|
+
return dp[m][n];
|
|
8770
9373
|
}
|
|
8771
9374
|
async function executeCommand(commandName, params, sessionName = "default", extraOpts) {
|
|
8772
9375
|
const guardResult = await guardCheck(commandName);
|
|
@@ -8815,8 +9418,15 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8815
9418
|
if (knownPlugins.includes(commandName)) {
|
|
8816
9419
|
hint = ` Plugin "${commandName}" may need to be installed. Try: xbrowser plugin install @xbrowser/${commandName}`;
|
|
8817
9420
|
}
|
|
9421
|
+
const message = `Unknown command: ${commandName}.${hint} Available: ${available.join(", ")}`;
|
|
9422
|
+
recordMistake({
|
|
9423
|
+
category: classifyFailure(message).code,
|
|
9424
|
+
command: commandName,
|
|
9425
|
+
message,
|
|
9426
|
+
context: { sessionName, params }
|
|
9427
|
+
});
|
|
8818
9428
|
return errorResult(
|
|
8819
|
-
|
|
9429
|
+
message
|
|
8820
9430
|
);
|
|
8821
9431
|
}
|
|
8822
9432
|
const _target = params._target;
|
|
@@ -8829,9 +9439,14 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8829
9439
|
const { _tabIndex: _u, ...rest } = params;
|
|
8830
9440
|
params = rest;
|
|
8831
9441
|
}
|
|
9442
|
+
const _frame = params._frame;
|
|
9443
|
+
if (_frame) {
|
|
9444
|
+
const { _frame: _u, ...rest } = params;
|
|
9445
|
+
params = rest;
|
|
9446
|
+
}
|
|
8832
9447
|
let targetPageOverride = null;
|
|
8833
9448
|
if (_target && extraOpts?.cdpEndpoint) {
|
|
8834
|
-
const { findTargetPage } = await import("./browser-
|
|
9449
|
+
const { findTargetPage } = await import("./browser-6PFTHZI3.js");
|
|
8835
9450
|
targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
|
|
8836
9451
|
if (!targetPageOverride) {
|
|
8837
9452
|
return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
|
|
@@ -8849,7 +9464,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8849
9464
|
}
|
|
8850
9465
|
if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
|
|
8851
9466
|
const { forwardExec } = await import("./daemon-client-HEGAXWGK.js");
|
|
8852
|
-
const longRunning = /^(vision-task|crawl|scrape|record|replay)$/.test(commandName);
|
|
9467
|
+
const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
|
|
8853
9468
|
const result = await forwardExec(
|
|
8854
9469
|
commandName,
|
|
8855
9470
|
params,
|
|
@@ -8895,6 +9510,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8895
9510
|
browserContext: session?.context,
|
|
8896
9511
|
sessionId: session?.id,
|
|
8897
9512
|
cdpEndpoint: session?.cdpEndpoint || extraOpts?.cdpEndpoint,
|
|
9513
|
+
frame: _frame,
|
|
8898
9514
|
args: [],
|
|
8899
9515
|
options: {},
|
|
8900
9516
|
cwd: process.cwd(),
|
|
@@ -8911,7 +9527,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8911
9527
|
config: {},
|
|
8912
9528
|
site: new NoopSiteInstance(),
|
|
8913
9529
|
cliName: "xbrowser",
|
|
8914
|
-
tips: new
|
|
9530
|
+
tips: new TipCollector3()
|
|
8915
9531
|
};
|
|
8916
9532
|
attachDetectAntiBot(ctx);
|
|
8917
9533
|
if (_tabIndex !== void 0 && session?.context) {
|
|
@@ -8943,7 +9559,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
8943
9559
|
const cache = /* @__PURE__ */ new Map();
|
|
8944
9560
|
const resolved = await resolveRefParams(session.page, params, command.selectorParams, cache, session.id);
|
|
8945
9561
|
if (resolved.tips.length > 0) {
|
|
8946
|
-
refTips =
|
|
9562
|
+
refTips = normalizeTips8(resolved.tips);
|
|
8947
9563
|
params = resolved.params;
|
|
8948
9564
|
}
|
|
8949
9565
|
}
|
|
@@ -9011,11 +9627,19 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
9011
9627
|
}
|
|
9012
9628
|
const merged = [
|
|
9013
9629
|
...raw.tips || [],
|
|
9014
|
-
...
|
|
9015
|
-
...snapshotHint ?
|
|
9630
|
+
...normalizeTips8(smartTips),
|
|
9631
|
+
...snapshotHint ? normalizeTips8([snapshotHint]) : [],
|
|
9016
9632
|
...refTips
|
|
9017
9633
|
];
|
|
9018
9634
|
const isSuccess = raw.success !== false;
|
|
9635
|
+
if (!isSuccess) {
|
|
9636
|
+
recordMistake({
|
|
9637
|
+
category: classifyFailure(raw.message).code,
|
|
9638
|
+
command: commandName,
|
|
9639
|
+
message: raw.message ?? "unknown command failure",
|
|
9640
|
+
context: { sessionName, params }
|
|
9641
|
+
});
|
|
9642
|
+
}
|
|
9019
9643
|
const mergedOrRaw = merged.length > 0 ? merged : raw.tips || [];
|
|
9020
9644
|
recordArchive(session?.id, sessionName, {
|
|
9021
9645
|
step: 0,
|
|
@@ -9027,7 +9651,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
9027
9651
|
timestamp: start
|
|
9028
9652
|
});
|
|
9029
9653
|
if (isSuccess) {
|
|
9030
|
-
return { ...
|
|
9654
|
+
return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
9031
9655
|
}
|
|
9032
9656
|
const fc = classifyFailure(raw.message);
|
|
9033
9657
|
return {
|
|
@@ -9040,7 +9664,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
9040
9664
|
...hookOutputs ? { hookOutputs } : {}
|
|
9041
9665
|
};
|
|
9042
9666
|
}
|
|
9043
|
-
const smartTipNormalized =
|
|
9667
|
+
const smartTipNormalized = normalizeTips8(smartTips);
|
|
9044
9668
|
recordArchive(session?.id, sessionName, {
|
|
9045
9669
|
step: 0,
|
|
9046
9670
|
command: commandName,
|
|
@@ -9050,14 +9674,20 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
9050
9674
|
duration,
|
|
9051
9675
|
timestamp: start
|
|
9052
9676
|
});
|
|
9053
|
-
return { ...
|
|
9677
|
+
return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
|
|
9054
9678
|
} catch (err) {
|
|
9055
9679
|
const end = Date.now();
|
|
9056
9680
|
const duration = end - start;
|
|
9057
9681
|
const errorMessage = errMsg(err);
|
|
9682
|
+
recordMistake({
|
|
9683
|
+
category: classifyFailure(errorMessage).code,
|
|
9684
|
+
command: commandName,
|
|
9685
|
+
message: errorMessage,
|
|
9686
|
+
context: { sessionName, params }
|
|
9687
|
+
});
|
|
9058
9688
|
if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
|
|
9059
9689
|
try {
|
|
9060
|
-
const { attemptRecovery } = await import("./recovery-
|
|
9690
|
+
const { attemptRecovery } = await import("./recovery-XDKN63O5.js");
|
|
9061
9691
|
const recovery = await attemptRecovery(
|
|
9062
9692
|
session.page,
|
|
9063
9693
|
sessionName,
|
|
@@ -9095,287 +9725,18 @@ async function executeCommand(commandName, params, sessionName = "default", extr
|
|
|
9095
9725
|
duration,
|
|
9096
9726
|
timestamp: start
|
|
9097
9727
|
});
|
|
9098
|
-
return { ...
|
|
9728
|
+
return { ...fail19(errorMessage), duration };
|
|
9099
9729
|
} finally {
|
|
9100
9730
|
}
|
|
9101
9731
|
}
|
|
9102
|
-
async function
|
|
9103
|
-
|
|
9104
|
-
const sessionName = options?.sessionName || "default";
|
|
9105
|
-
const results = [];
|
|
9106
|
-
const totalStart = Date.now();
|
|
9107
|
-
let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
9108
|
-
if (!session) {
|
|
9109
|
-
const launchOpts = {};
|
|
9110
|
-
if (options?.cdpEndpoint) {
|
|
9111
|
-
launchOpts.cdpEndpoint = options.cdpEndpoint;
|
|
9112
|
-
}
|
|
9113
|
-
session = await createSession(sessionName, void 0, launchOpts);
|
|
9114
|
-
saveSessionDiskMeta(sessionName, {
|
|
9115
|
-
id: session.id,
|
|
9116
|
-
name: sessionName,
|
|
9117
|
-
url: session.page.url(),
|
|
9118
|
-
createdAt: session.createdAt,
|
|
9119
|
-
cdpEndpoint: session.cdpEndpoint
|
|
9120
|
-
});
|
|
9121
|
-
}
|
|
9122
|
-
try {
|
|
9123
|
-
for (const pipeline of pipelines) {
|
|
9124
|
-
const { type, pipeline: commands } = pipeline;
|
|
9125
|
-
for (const cmdStr of commands) {
|
|
9126
|
-
if (process.env.XBROWSER_CHAIN_PACE === "human" && results.length > 0) {
|
|
9127
|
-
await new Promise((r) => setTimeout(r, 800 + Math.random() * 1700));
|
|
9128
|
-
}
|
|
9129
|
-
const parts = splitCommand(cmdStr);
|
|
9130
|
-
if (parts.length === 0) continue;
|
|
9131
|
-
const cmdName = parts[0];
|
|
9132
|
-
const cmdArgs = parts.slice(1);
|
|
9133
|
-
const loader = await getPluginLoader();
|
|
9134
|
-
const internalLoader = loader.getCore().loader;
|
|
9135
|
-
const resolvedName = loader.resolveSiteName(cmdName);
|
|
9136
|
-
const site = resolvedName ? internalLoader.getSite(resolvedName) : void 0;
|
|
9137
|
-
if (site) {
|
|
9138
|
-
const subCommand = cmdArgs[0];
|
|
9139
|
-
if (!subCommand) {
|
|
9140
|
-
results.push({
|
|
9141
|
-
command: cmdName,
|
|
9142
|
-
raw: cmdStr,
|
|
9143
|
-
...fail17(`Plugin "${cmdName}" requires a sub-command`),
|
|
9144
|
-
duration: 0
|
|
9145
|
-
});
|
|
9146
|
-
if (type === "and") {
|
|
9147
|
-
return {
|
|
9148
|
-
success: false,
|
|
9149
|
-
steps: results,
|
|
9150
|
-
totalDuration: Date.now() - totalStart,
|
|
9151
|
-
stoppedAt: results.length,
|
|
9152
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): no sub-command`
|
|
9153
|
-
};
|
|
9154
|
-
}
|
|
9155
|
-
continue;
|
|
9156
|
-
}
|
|
9157
|
-
const cmdEntry = site.getCommand(subCommand);
|
|
9158
|
-
if (!cmdEntry) {
|
|
9159
|
-
results.push({
|
|
9160
|
-
command: cmdName,
|
|
9161
|
-
raw: cmdStr,
|
|
9162
|
-
...fail17(`Unknown command "${subCommand}" for plugin "${cmdName}"`),
|
|
9163
|
-
duration: 0
|
|
9164
|
-
});
|
|
9165
|
-
if (type === "and") {
|
|
9166
|
-
return {
|
|
9167
|
-
success: false,
|
|
9168
|
-
steps: results,
|
|
9169
|
-
totalDuration: Date.now() - totalStart,
|
|
9170
|
-
stoppedAt: results.length,
|
|
9171
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): unknown sub-command "${subCommand}"`
|
|
9172
|
-
};
|
|
9173
|
-
}
|
|
9174
|
-
continue;
|
|
9175
|
-
}
|
|
9176
|
-
const pluginArgs = cmdArgs.slice(1);
|
|
9177
|
-
let pluginParams = parsePluginParams(pluginArgs, cmdEntry.parameters);
|
|
9178
|
-
if (cmdEntry.parameters) {
|
|
9179
|
-
const schemaCheck = cmdEntry.parameters.safeParse(pluginParams);
|
|
9180
|
-
if (schemaCheck.success) {
|
|
9181
|
-
for (const [k, v] of Object.entries(schemaCheck.data)) {
|
|
9182
|
-
if (!(k in pluginParams)) pluginParams[k] = v;
|
|
9183
|
-
}
|
|
9184
|
-
}
|
|
9185
|
-
}
|
|
9186
|
-
const pluginCtx = {
|
|
9187
|
-
args: pluginArgs,
|
|
9188
|
-
options: pluginParams,
|
|
9189
|
-
cwd: process.cwd(),
|
|
9190
|
-
page: session.page,
|
|
9191
|
-
browser: session.context.browser(),
|
|
9192
|
-
browserContext: session.context,
|
|
9193
|
-
sessionId: session.id,
|
|
9194
|
-
storage: getPluginStorage(cmdName),
|
|
9195
|
-
output: { mode: "text", showTips: false, color: false, emoji: false },
|
|
9196
|
-
error: (msg) => {
|
|
9197
|
-
throw new Error(msg);
|
|
9198
|
-
},
|
|
9199
|
-
config: {},
|
|
9200
|
-
site,
|
|
9201
|
-
cliName: "xbrowser",
|
|
9202
|
-
tips: new TipCollector2()
|
|
9203
|
-
};
|
|
9204
|
-
const start2 = Date.now();
|
|
9205
|
-
try {
|
|
9206
|
-
const loginGuard = await checkPluginLoginRequired({
|
|
9207
|
-
site,
|
|
9208
|
-
command: cmdEntry,
|
|
9209
|
-
commandName: subCommand,
|
|
9210
|
-
ctx: pluginCtx,
|
|
9211
|
-
page: session?.page,
|
|
9212
|
-
sessionName
|
|
9213
|
-
});
|
|
9214
|
-
if (!loginGuard.ok) {
|
|
9215
|
-
const duration3 = Date.now() - start2;
|
|
9216
|
-
const data2 = loginGuard.data ?? null;
|
|
9217
|
-
recordArchive(session.id, sessionName, {
|
|
9218
|
-
step: results.length,
|
|
9219
|
-
command: `${cmdName} ${subCommand}`,
|
|
9220
|
-
params: pluginParams,
|
|
9221
|
-
result: { success: false, data: data2, message: loginGuard.message, tips: loginGuard.tips || [] },
|
|
9222
|
-
toolCalls: [],
|
|
9223
|
-
duration: duration3,
|
|
9224
|
-
timestamp: start2
|
|
9225
|
-
});
|
|
9226
|
-
results.push({
|
|
9227
|
-
command: `${cmdName} ${subCommand}`,
|
|
9228
|
-
raw: cmdStr,
|
|
9229
|
-
success: false,
|
|
9230
|
-
data: data2,
|
|
9231
|
-
message: loginGuard.message,
|
|
9232
|
-
tips: normalizeTips7(loginGuard.tips),
|
|
9233
|
-
duration: duration3
|
|
9234
|
-
});
|
|
9235
|
-
if (type === "and") {
|
|
9236
|
-
return {
|
|
9237
|
-
success: false,
|
|
9238
|
-
steps: results,
|
|
9239
|
-
totalDuration: Date.now() - totalStart,
|
|
9240
|
-
stoppedAt: results.length,
|
|
9241
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${loginGuard.message}`
|
|
9242
|
-
};
|
|
9243
|
-
}
|
|
9244
|
-
continue;
|
|
9245
|
-
}
|
|
9246
|
-
const hooks = await loadHooks();
|
|
9247
|
-
if (hooks.length > 0) {
|
|
9248
|
-
await Promise.all(hooks.map((h) => h.onBeforeCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams })));
|
|
9249
|
-
}
|
|
9250
|
-
const raw = await cmdEntry.handler(pluginParams, pluginCtx);
|
|
9251
|
-
const duration2 = Date.now() - start2;
|
|
9252
|
-
let hookOutputs;
|
|
9253
|
-
if (hooks.length > 0) {
|
|
9254
|
-
const outputs = [];
|
|
9255
|
-
for (const h of hooks) {
|
|
9256
|
-
const output = await h.onAfterCommand?.({ page: session.page, command: `${cmdName} ${subCommand}`, params: pluginParams, result: raw, duration: duration2 });
|
|
9257
|
-
if (output) outputs.push({ _hook: h.name, ...output });
|
|
9258
|
-
}
|
|
9259
|
-
if (outputs.length > 0) hookOutputs = outputs;
|
|
9260
|
-
}
|
|
9261
|
-
const data = raw?.data ?? raw;
|
|
9262
|
-
recordArchive(session.id, sessionName, {
|
|
9263
|
-
step: results.length,
|
|
9264
|
-
command: `${cmdName} ${subCommand}`,
|
|
9265
|
-
params: pluginParams,
|
|
9266
|
-
result: { success: true, data, tips: tipsToMessages(raw?.tips) },
|
|
9267
|
-
toolCalls: [],
|
|
9268
|
-
duration: duration2,
|
|
9269
|
-
timestamp: start2
|
|
9270
|
-
});
|
|
9271
|
-
results.push({
|
|
9272
|
-
command: `${cmdName} ${subCommand}`,
|
|
9273
|
-
raw: cmdStr,
|
|
9274
|
-
...ok32(data),
|
|
9275
|
-
duration: duration2,
|
|
9276
|
-
...hookOutputs ? { hookOutputs } : {}
|
|
9277
|
-
});
|
|
9278
|
-
if (type === "or") {
|
|
9279
|
-
return {
|
|
9280
|
-
success: true,
|
|
9281
|
-
steps: results,
|
|
9282
|
-
totalDuration: Date.now() - totalStart,
|
|
9283
|
-
stoppedAt: results.length,
|
|
9284
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' succeeded (|| chain)`
|
|
9285
|
-
};
|
|
9286
|
-
}
|
|
9287
|
-
} catch (err) {
|
|
9288
|
-
const duration2 = Date.now() - start2;
|
|
9289
|
-
const errorMessage = errMsg(err);
|
|
9290
|
-
recordArchive(session.id, sessionName, {
|
|
9291
|
-
step: results.length,
|
|
9292
|
-
command: `${cmdName} ${subCommand}`,
|
|
9293
|
-
params: pluginParams,
|
|
9294
|
-
result: { success: false, data: null, message: errorMessage, tips: [] },
|
|
9295
|
-
toolCalls: [],
|
|
9296
|
-
duration: duration2,
|
|
9297
|
-
timestamp: start2
|
|
9298
|
-
});
|
|
9299
|
-
results.push({
|
|
9300
|
-
command: `${cmdName} ${subCommand}`,
|
|
9301
|
-
raw: cmdStr,
|
|
9302
|
-
...fail17(errorMessage),
|
|
9303
|
-
duration: duration2
|
|
9304
|
-
});
|
|
9305
|
-
if (type === "and") {
|
|
9306
|
-
return {
|
|
9307
|
-
success: false,
|
|
9308
|
-
steps: results,
|
|
9309
|
-
totalDuration: Date.now() - totalStart,
|
|
9310
|
-
stoppedAt: results.length,
|
|
9311
|
-
stoppedReason: `Command '${cmdName} ${subCommand}' failed (&& chain): ${errorMessage}`
|
|
9312
|
-
};
|
|
9313
|
-
}
|
|
9314
|
-
}
|
|
9315
|
-
continue;
|
|
9316
|
-
}
|
|
9317
|
-
const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
|
|
9318
|
-
if (cmdName === "goto" && params.url) {
|
|
9319
|
-
const existing2 = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
|
|
9320
|
-
if (!existing2) {
|
|
9321
|
-
session = await createSession(sessionName, params.url, {
|
|
9322
|
-
cdpEndpoint: options?.cdpEndpoint
|
|
9323
|
-
});
|
|
9324
|
-
}
|
|
9325
|
-
}
|
|
9326
|
-
const start = Date.now();
|
|
9327
|
-
const result = await executeCommand(cmdName, params, sessionName, {
|
|
9328
|
-
cdpEndpoint: options?.cdpEndpoint,
|
|
9329
|
-
skipCleanup: true
|
|
9330
|
-
// executeChain's finally handles cleanup
|
|
9331
|
-
});
|
|
9332
|
-
const duration = Date.now() - start;
|
|
9333
|
-
const stepResult = {
|
|
9334
|
-
command: cmdName,
|
|
9335
|
-
raw: cmdStr,
|
|
9336
|
-
success: result.success,
|
|
9337
|
-
data: result.data,
|
|
9338
|
-
message: result.message,
|
|
9339
|
-
duration,
|
|
9340
|
-
tips: result.tips,
|
|
9341
|
-
...result.hookOutputs ? { hookOutputs: result.hookOutputs } : {}
|
|
9342
|
-
};
|
|
9343
|
-
results.push(stepResult);
|
|
9344
|
-
if (type === "and" && !result.success) {
|
|
9345
|
-
return {
|
|
9346
|
-
success: false,
|
|
9347
|
-
steps: results,
|
|
9348
|
-
totalDuration: Date.now() - totalStart,
|
|
9349
|
-
stoppedAt: results.length,
|
|
9350
|
-
stoppedReason: `Command '${cmdName}' failed (&& chain): ${result.message}`
|
|
9351
|
-
};
|
|
9352
|
-
}
|
|
9353
|
-
if (type === "or" && result.success) {
|
|
9354
|
-
return {
|
|
9355
|
-
success: true,
|
|
9356
|
-
steps: results,
|
|
9357
|
-
totalDuration: Date.now() - totalStart,
|
|
9358
|
-
stoppedAt: results.length,
|
|
9359
|
-
stoppedReason: `Command '${cmdName}' succeeded (|| chain)`
|
|
9360
|
-
};
|
|
9361
|
-
}
|
|
9362
|
-
}
|
|
9363
|
-
}
|
|
9364
|
-
const anyFailed = results.some((r) => !r.success);
|
|
9365
|
-
return {
|
|
9366
|
-
success: !anyFailed,
|
|
9367
|
-
steps: results,
|
|
9368
|
-
totalDuration: Date.now() - totalStart
|
|
9369
|
-
};
|
|
9370
|
-
} finally {
|
|
9371
|
-
}
|
|
9732
|
+
async function executeChain2(input, options) {
|
|
9733
|
+
return executeChain(input, options, executeCommand);
|
|
9372
9734
|
}
|
|
9373
9735
|
function isChainInput(input) {
|
|
9374
9736
|
return /\s&&\s|\|\|\s|\s;\s|;\s|\s,\s|\s\+\s|\s->\s/.test(input);
|
|
9375
9737
|
}
|
|
9376
9738
|
|
|
9377
9739
|
export {
|
|
9378
|
-
parsePluginParams,
|
|
9379
9740
|
createStubContext,
|
|
9380
9741
|
registerCommand,
|
|
9381
9742
|
getCommand,
|
|
@@ -9403,16 +9764,17 @@ export {
|
|
|
9403
9764
|
attachDetectAntiBot,
|
|
9404
9765
|
getWSServerFromCache,
|
|
9405
9766
|
setWSServerCache,
|
|
9767
|
+
loadHooks,
|
|
9406
9768
|
readJsonFile,
|
|
9407
9769
|
PluginMetadataParser,
|
|
9408
9770
|
ensurePluginDependencies,
|
|
9409
9771
|
XBrowserPluginLoader,
|
|
9410
9772
|
getPluginLoader,
|
|
9411
|
-
checkPluginLoginRequired,
|
|
9412
|
-
loadHooks,
|
|
9413
9773
|
getPluginStorage,
|
|
9414
9774
|
setWSServer,
|
|
9775
|
+
checkPluginLoginRequired,
|
|
9776
|
+
parsePluginParams,
|
|
9415
9777
|
executeCommand,
|
|
9416
|
-
executeChain,
|
|
9778
|
+
executeChain2 as executeChain,
|
|
9417
9779
|
isChainInput
|
|
9418
9780
|
};
|