misoai-web 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -8
  3. package/bin/midscene-playground +2 -2
  4. package/package.json +23 -24
  5. package/dist/es/agent.js +0 -2451
  6. package/dist/es/agent.js.map +0 -1
  7. package/dist/es/bridge-mode-browser.js +0 -908
  8. package/dist/es/bridge-mode-browser.js.map +0 -1
  9. package/dist/es/bridge-mode.js +0 -2812
  10. package/dist/es/bridge-mode.js.map +0 -1
  11. package/dist/es/chrome-extension.js +0 -3152
  12. package/dist/es/chrome-extension.js.map +0 -1
  13. package/dist/es/index.js +0 -3052
  14. package/dist/es/index.js.map +0 -1
  15. package/dist/es/midscene-playground.js +0 -2781
  16. package/dist/es/midscene-playground.js.map +0 -1
  17. package/dist/es/midscene-server.js +0 -247
  18. package/dist/es/midscene-server.js.map +0 -1
  19. package/dist/es/playground.js +0 -2552
  20. package/dist/es/playground.js.map +0 -1
  21. package/dist/es/playwright-report.js +0 -120
  22. package/dist/es/playwright-report.js.map +0 -1
  23. package/dist/es/playwright.js +0 -2997
  24. package/dist/es/playwright.js.map +0 -1
  25. package/dist/es/puppeteer-agent-launcher.js +0 -2947
  26. package/dist/es/puppeteer-agent-launcher.js.map +0 -1
  27. package/dist/es/puppeteer.js +0 -2794
  28. package/dist/es/puppeteer.js.map +0 -1
  29. package/dist/es/ui-utils.js +0 -106
  30. package/dist/es/ui-utils.js.map +0 -1
  31. package/dist/es/utils.js +0 -197
  32. package/dist/es/utils.js.map +0 -1
  33. package/dist/es/yaml.js +0 -333
  34. package/dist/es/yaml.js.map +0 -1
  35. package/dist/lib/agent.js +0 -2466
  36. package/dist/lib/agent.js.map +0 -1
  37. package/dist/lib/bridge-mode-browser.js +0 -942
  38. package/dist/lib/bridge-mode-browser.js.map +0 -1
  39. package/dist/lib/bridge-mode.js +0 -2832
  40. package/dist/lib/bridge-mode.js.map +0 -1
  41. package/dist/lib/chrome-extension.js +0 -3169
  42. package/dist/lib/chrome-extension.js.map +0 -1
  43. package/dist/lib/index.js +0 -3071
  44. package/dist/lib/index.js.map +0 -1
  45. package/dist/lib/midscene-playground.js +0 -2785
  46. package/dist/lib/midscene-playground.js.map +0 -1
  47. package/dist/lib/midscene-server.js +0 -273
  48. package/dist/lib/midscene-server.js.map +0 -1
  49. package/dist/lib/playground.js +0 -2571
  50. package/dist/lib/playground.js.map +0 -1
  51. package/dist/lib/playwright-report.js +0 -148
  52. package/dist/lib/playwright-report.js.map +0 -1
  53. package/dist/lib/playwright.js +0 -3017
  54. package/dist/lib/playwright.js.map +0 -1
  55. package/dist/lib/puppeteer-agent-launcher.js +0 -2963
  56. package/dist/lib/puppeteer-agent-launcher.js.map +0 -1
  57. package/dist/lib/puppeteer.js +0 -2808
  58. package/dist/lib/puppeteer.js.map +0 -1
  59. package/dist/lib/ui-utils.js +0 -137
  60. package/dist/lib/ui-utils.js.map +0 -1
  61. package/dist/lib/utils.js +0 -235
  62. package/dist/lib/utils.js.map +0 -1
  63. package/dist/lib/yaml.js +0 -372
  64. package/dist/lib/yaml.js.map +0 -1
  65. package/dist/types/agent.d.ts +0 -254
  66. package/dist/types/bridge-mode-browser.d.ts +0 -9
  67. package/dist/types/bridge-mode.d.ts +0 -40
  68. package/dist/types/browser-d447695b.d.ts +0 -37
  69. package/dist/types/chrome-extension.d.ts +0 -18
  70. package/dist/types/index.d.ts +0 -16
  71. package/dist/types/midscene-playground.d.ts +0 -2
  72. package/dist/types/midscene-server.d.ts +0 -31
  73. package/dist/types/page-b8ada1f3.d.ts +0 -322
  74. package/dist/types/playground.d.ts +0 -17
  75. package/dist/types/playwright-report.d.ts +0 -11
  76. package/dist/types/playwright.d.ts +0 -87
  77. package/dist/types/puppeteer-agent-launcher.d.ts +0 -40
  78. package/dist/types/puppeteer.d.ts +0 -17
  79. package/dist/types/ui-utils.d.ts +0 -14
  80. package/dist/types/utils-badc824e.d.ts +0 -34
  81. package/dist/types/utils.d.ts +0 -8
  82. package/dist/types/yaml.d.ts +0 -15
@@ -1,3169 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var __accessCheck = (obj, member, msg) => {
30
- if (!member.has(obj))
31
- throw TypeError("Cannot " + msg);
32
- };
33
- var __privateGet = (obj, member, getter) => {
34
- __accessCheck(obj, member, "read from private field");
35
- return getter ? getter.call(obj) : member.get(obj);
36
- };
37
- var __privateAdd = (obj, member, value) => {
38
- if (member.has(obj))
39
- throw TypeError("Cannot add the same private member more than once");
40
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
- };
42
- var __privateSet = (obj, member, value, setter) => {
43
- __accessCheck(obj, member, "write to private field");
44
- setter ? setter.call(obj, value) : member.set(obj, value);
45
- return value;
46
- };
47
- var __privateMethod = (obj, member, method) => {
48
- __accessCheck(obj, member, "access private method");
49
- return method;
50
- };
51
-
52
- // src/chrome-extension/index.ts
53
- var chrome_extension_exports = {};
54
- __export(chrome_extension_exports, {
55
- ChromeExtensionProxyPage: () => ChromeExtensionProxyPage,
56
- ChromeExtensionProxyPageAgent: () => ChromeExtensionProxyPageAgent,
57
- ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED: () => ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED,
58
- overrideAIConfig: () => import_env3.overrideAIConfig
59
- });
60
- module.exports = __toCommonJS(chrome_extension_exports);
61
-
62
- // src/common/utils.ts
63
- var import_ai_model = require("misoai-core/ai-model");
64
- var import_utils = require("misoai-core/utils");
65
- var import_env = require("misoai-shared/env");
66
- var import_extractor = require("misoai-shared/extractor");
67
- var import_img = require("misoai-shared/img");
68
- var import_utils2 = require("misoai-shared/utils");
69
- var import_dayjs = __toESM(require("dayjs"));
70
-
71
- // src/web-element.ts
72
- var WebElementInfo = class {
73
- constructor({
74
- content,
75
- rect,
76
- // page,
77
- locator,
78
- id,
79
- attributes,
80
- indexId,
81
- xpaths
82
- }) {
83
- this.content = content;
84
- this.rect = rect;
85
- this.center = [
86
- Math.floor(rect.left + rect.width / 2),
87
- Math.floor(rect.top + rect.height / 2)
88
- ];
89
- this.locator = locator;
90
- this.id = id;
91
- this.attributes = attributes;
92
- this.indexId = indexId;
93
- this.xpaths = xpaths;
94
- }
95
- };
96
-
97
- // src/common/utils.ts
98
- async function parseContextFromWebPage(page, _opt) {
99
- (0, import_utils2.assert)(page, "page is required");
100
- if (page._forceUsePageContext) {
101
- return await page._forceUsePageContext();
102
- }
103
- const url = await page.url();
104
- (0, import_utils.uploadTestInfoToServer)({ testUrl: url });
105
- let screenshotBase64;
106
- let tree;
107
- await Promise.all([
108
- page.screenshotBase64().then((base64) => {
109
- screenshotBase64 = base64;
110
- }),
111
- page.getElementsNodeTree().then(async (treeRoot) => {
112
- tree = treeRoot;
113
- })
114
- ]);
115
- const webTree = (0, import_extractor.traverseTree)(tree, (elementInfo) => {
116
- const { rect, id, content, attributes, locator, indexId } = elementInfo;
117
- return new WebElementInfo({
118
- rect,
119
- locator,
120
- id,
121
- content,
122
- attributes,
123
- indexId
124
- });
125
- });
126
- (0, import_utils2.assert)(screenshotBase64, "screenshotBase64 is required");
127
- const elementsInfo = (0, import_extractor.treeToList)(webTree);
128
- const size = await page.size();
129
- if (size.dpr && size.dpr > 1) {
130
- screenshotBase64 = await (0, import_img.resizeImgBase64)(screenshotBase64, {
131
- width: size.width,
132
- height: size.height
133
- });
134
- }
135
- return {
136
- content: elementsInfo,
137
- tree: webTree,
138
- size,
139
- screenshotBase64,
140
- url
141
- };
142
- }
143
- function reportFileName(tag = "web") {
144
- const reportTagName = (0, import_env.getAIConfig)(import_env.MIDSCENE_REPORT_TAG_NAME);
145
- const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss");
146
- const uniqueId = (0, import_utils2.uuid)().substring(0, 8);
147
- return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;
148
- }
149
- function printReportMsg(filepath) {
150
- (0, import_utils2.logMsg)(`Midscene - report file updated: ${filepath}`);
151
- }
152
- var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
153
- function replaceIllegalPathCharsAndSpace(str) {
154
- return str.replace(/[/\\:*?"<>| ]/g, "-");
155
- }
156
- function matchElementFromPlan(planLocateParam, tree) {
157
- if (!planLocateParam) {
158
- return void 0;
159
- }
160
- if (planLocateParam.id) {
161
- return (0, import_extractor.getNodeFromCacheList)(planLocateParam.id);
162
- }
163
- if (planLocateParam.bbox) {
164
- const centerPosition = {
165
- x: Math.floor((planLocateParam.bbox[0] + planLocateParam.bbox[2]) / 2),
166
- y: Math.floor((planLocateParam.bbox[1] + planLocateParam.bbox[3]) / 2)
167
- };
168
- let element = (0, import_ai_model.elementByPositionWithElementInfo)(tree, centerPosition);
169
- if (!element) {
170
- element = (0, import_extractor.generateElementByPosition)(centerPosition);
171
- }
172
- return element;
173
- }
174
- return void 0;
175
- }
176
-
177
- // src/common/agent.ts
178
- var import_misoai_core2 = require("misoai-core");
179
- var import_js_yaml4 = __toESM(require("js-yaml"));
180
-
181
- // src/yaml/player.ts
182
- var import_node_fs = require("fs");
183
- var import_node_path = require("path");
184
- var import_utils3 = require("misoai-shared/utils");
185
- var import_common = require("misoai-shared/common");
186
- var ScriptPlayer = class {
187
- constructor(script, setupAgent, onTaskStatusChange) {
188
- this.script = script;
189
- this.setupAgent = setupAgent;
190
- this.onTaskStatusChange = onTaskStatusChange;
191
- this.taskStatusList = [];
192
- this.status = "init";
193
- this.unnamedResultIndex = 0;
194
- this.pageAgent = null;
195
- this.result = {};
196
- if (import_utils3.ifInBrowser) {
197
- this.output = void 0;
198
- } else if (script.target?.output) {
199
- this.output = (0, import_node_path.resolve)(process.cwd(), script.target.output);
200
- } else {
201
- this.output = (0, import_node_path.join)((0, import_common.getMidsceneRunSubDir)("output"), `${process.pid}.json`);
202
- }
203
- this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({
204
- ...task,
205
- index: taskIndex,
206
- status: "init",
207
- totalSteps: task.flow?.length || 0
208
- }));
209
- }
210
- setResult(key, value) {
211
- const keyToUse = key || this.unnamedResultIndex++;
212
- if (this.result[keyToUse]) {
213
- console.warn(`result key ${keyToUse} already exists, will overwrite`);
214
- }
215
- this.result[keyToUse] = value;
216
- this.flushResult();
217
- }
218
- setPlayerStatus(status, error) {
219
- this.status = status;
220
- this.errorInSetup = error;
221
- }
222
- notifyCurrentTaskStatusChange(taskIndex) {
223
- const taskIndexToNotify = typeof taskIndex === "number" ? taskIndex : this.currentTaskIndex;
224
- if (typeof taskIndexToNotify !== "number") {
225
- return;
226
- }
227
- const taskStatus = this.taskStatusList[taskIndexToNotify];
228
- if (this.onTaskStatusChange) {
229
- this.onTaskStatusChange(taskStatus);
230
- }
231
- }
232
- async setTaskStatus(index, statusValue, error) {
233
- this.taskStatusList[index].status = statusValue;
234
- if (error) {
235
- this.taskStatusList[index].error = error;
236
- }
237
- this.notifyCurrentTaskStatusChange(index);
238
- }
239
- setTaskIndex(taskIndex) {
240
- this.currentTaskIndex = taskIndex;
241
- }
242
- flushResult() {
243
- if (Object.keys(this.result).length && this.output) {
244
- const output = (0, import_node_path.resolve)(process.cwd(), this.output);
245
- const outputDir = (0, import_node_path.dirname)(output);
246
- if (!(0, import_node_fs.existsSync)(outputDir)) {
247
- (0, import_node_fs.mkdirSync)(outputDir, { recursive: true });
248
- }
249
- (0, import_node_fs.writeFileSync)(output, JSON.stringify(this.result, void 0, 2));
250
- }
251
- }
252
- async playTask(taskStatus, agent) {
253
- const { flow } = taskStatus;
254
- (0, import_utils3.assert)(flow, "missing flow in task");
255
- for (const flowItemIndex in flow) {
256
- const currentStep = Number.parseInt(flowItemIndex, 10);
257
- taskStatus.currentStep = currentStep;
258
- const flowItem = flow[flowItemIndex];
259
- if ("aiAction" in flowItem || "ai" in flowItem) {
260
- const actionTask = flowItem;
261
- const prompt = actionTask.aiAction || actionTask.ai;
262
- (0, import_utils3.assert)(prompt, "missing prompt for ai (aiAction)");
263
- (0, import_utils3.assert)(
264
- typeof prompt === "string",
265
- "prompt for aiAction must be a string"
266
- );
267
- await agent.aiAction(prompt);
268
- } else if ("aiAssert" in flowItem) {
269
- const assertTask = flowItem;
270
- const prompt = assertTask.aiAssert;
271
- (0, import_utils3.assert)(prompt, "missing prompt for aiAssert");
272
- (0, import_utils3.assert)(
273
- typeof prompt === "string",
274
- "prompt for aiAssert must be a string"
275
- );
276
- await agent.aiAssert(prompt);
277
- } else if ("aiQuery" in flowItem) {
278
- const queryTask = flowItem;
279
- const prompt = queryTask.aiQuery;
280
- (0, import_utils3.assert)(prompt, "missing prompt for aiQuery");
281
- (0, import_utils3.assert)(
282
- typeof prompt === "string",
283
- "prompt for aiQuery must be a string"
284
- );
285
- const queryResult = await agent.aiQuery(prompt);
286
- this.setResult(queryTask.name, queryResult);
287
- } else if ("aiNumber" in flowItem) {
288
- const numberTask = flowItem;
289
- const prompt = numberTask.aiNumber;
290
- (0, import_utils3.assert)(prompt, "missing prompt for number");
291
- (0, import_utils3.assert)(
292
- typeof prompt === "string",
293
- "prompt for number must be a string"
294
- );
295
- const numberResult = await agent.aiNumber(prompt);
296
- this.setResult(numberTask.name, numberResult);
297
- } else if ("aiString" in flowItem) {
298
- const stringTask = flowItem;
299
- const prompt = stringTask.aiString;
300
- (0, import_utils3.assert)(prompt, "missing prompt for string");
301
- (0, import_utils3.assert)(
302
- typeof prompt === "string",
303
- "prompt for string must be a string"
304
- );
305
- const stringResult = await agent.aiString(prompt);
306
- this.setResult(stringTask.name, stringResult);
307
- } else if ("aiBoolean" in flowItem) {
308
- const booleanTask = flowItem;
309
- const prompt = booleanTask.aiBoolean;
310
- (0, import_utils3.assert)(prompt, "missing prompt for boolean");
311
- (0, import_utils3.assert)(
312
- typeof prompt === "string",
313
- "prompt for boolean must be a string"
314
- );
315
- const booleanResult = await agent.aiBoolean(prompt);
316
- this.setResult(booleanTask.name, booleanResult);
317
- } else if ("aiLocate" in flowItem) {
318
- const locateTask = flowItem;
319
- const prompt = locateTask.aiLocate;
320
- (0, import_utils3.assert)(prompt, "missing prompt for aiLocate");
321
- (0, import_utils3.assert)(
322
- typeof prompt === "string",
323
- "prompt for aiLocate must be a string"
324
- );
325
- const locateResult = await agent.aiLocate(prompt);
326
- this.setResult(locateTask.name, locateResult);
327
- } else if ("aiWaitFor" in flowItem) {
328
- const waitForTask = flowItem;
329
- const prompt = waitForTask.aiWaitFor;
330
- (0, import_utils3.assert)(prompt, "missing prompt for aiWaitFor");
331
- (0, import_utils3.assert)(
332
- typeof prompt === "string",
333
- "prompt for aiWaitFor must be a string"
334
- );
335
- const timeout = waitForTask.timeout;
336
- await agent.aiWaitFor(prompt, { timeoutMs: timeout });
337
- } else if ("sleep" in flowItem) {
338
- const sleepTask = flowItem;
339
- const ms = sleepTask.sleep;
340
- let msNumber = ms;
341
- if (typeof ms === "string") {
342
- msNumber = Number.parseInt(ms, 10);
343
- }
344
- (0, import_utils3.assert)(
345
- msNumber && msNumber > 0,
346
- `ms for sleep must be greater than 0, but got ${ms}`
347
- );
348
- await new Promise((resolve2) => setTimeout(resolve2, msNumber));
349
- } else if ("aiTap" in flowItem) {
350
- const tapTask = flowItem;
351
- await agent.aiTap(tapTask.aiTap, tapTask);
352
- } else if ("aiHover" in flowItem) {
353
- const hoverTask = flowItem;
354
- await agent.aiHover(hoverTask.aiHover, hoverTask);
355
- } else if ("aiInput" in flowItem) {
356
- const inputTask = flowItem;
357
- await agent.aiInput(inputTask.aiInput, inputTask.locate, inputTask);
358
- } else if ("aiKeyboardPress" in flowItem) {
359
- const keyboardPressTask = flowItem;
360
- await agent.aiKeyboardPress(
361
- keyboardPressTask.aiKeyboardPress,
362
- keyboardPressTask.locate,
363
- keyboardPressTask
364
- );
365
- } else if ("aiScroll" in flowItem) {
366
- const scrollTask = flowItem;
367
- await agent.aiScroll(scrollTask, scrollTask.locate, scrollTask);
368
- } else if ("javascript" in flowItem) {
369
- const evaluateJavaScriptTask = flowItem;
370
- const result = await agent.evaluateJavaScript(
371
- evaluateJavaScriptTask.javascript
372
- );
373
- this.setResult(evaluateJavaScriptTask.name, result);
374
- } else {
375
- throw new Error(`unknown flowItem: ${JSON.stringify(flowItem)}`);
376
- }
377
- }
378
- this.reportFile = agent.reportFile;
379
- }
380
- async run() {
381
- const { target, web, android, tasks } = this.script;
382
- const webEnv = web || target;
383
- const androidEnv = android;
384
- const platform = webEnv || androidEnv;
385
- this.setPlayerStatus("running");
386
- let agent = null;
387
- let freeFn = [];
388
- try {
389
- const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(
390
- platform
391
- );
392
- agent = newAgent;
393
- const originalOnTaskStartTip = agent.onTaskStartTip;
394
- agent.onTaskStartTip = (tip) => {
395
- if (this.status === "running") {
396
- this.agentStatusTip = tip;
397
- }
398
- originalOnTaskStartTip?.(tip);
399
- };
400
- freeFn = [
401
- ...newFreeFn || [],
402
- {
403
- name: "restore-agent-onTaskStartTip",
404
- fn: () => {
405
- if (agent) {
406
- agent.onTaskStartTip = originalOnTaskStartTip;
407
- }
408
- }
409
- }
410
- ];
411
- } catch (e) {
412
- this.setPlayerStatus("error", e);
413
- return;
414
- }
415
- this.pageAgent = agent;
416
- let taskIndex = 0;
417
- this.setPlayerStatus("running");
418
- let errorFlag = false;
419
- while (taskIndex < tasks.length) {
420
- const taskStatus = this.taskStatusList[taskIndex];
421
- this.setTaskStatus(taskIndex, "running");
422
- this.setTaskIndex(taskIndex);
423
- try {
424
- await this.playTask(taskStatus, this.pageAgent);
425
- this.setTaskStatus(taskIndex, "done");
426
- } catch (e) {
427
- this.setTaskStatus(taskIndex, "error", e);
428
- if (taskStatus.continueOnError) {
429
- } else {
430
- this.reportFile = agent.reportFile;
431
- errorFlag = true;
432
- break;
433
- }
434
- }
435
- this.reportFile = agent.reportFile;
436
- taskIndex++;
437
- }
438
- if (errorFlag) {
439
- this.setPlayerStatus("error");
440
- } else {
441
- this.setPlayerStatus("done");
442
- }
443
- this.agentStatusTip = "";
444
- for (const fn of freeFn) {
445
- try {
446
- await fn.fn();
447
- } catch (e) {
448
- }
449
- }
450
- }
451
- };
452
-
453
- // src/yaml/builder.ts
454
- var import_js_yaml = __toESM(require("js-yaml"));
455
-
456
- // src/yaml/utils.ts
457
- var import_utils4 = require("misoai-shared/utils");
458
- var import_js_yaml2 = __toESM(require("js-yaml"));
459
- function interpolateEnvVars(content) {
460
- return content.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
461
- const value = process.env[envVar.trim()];
462
- if (value === void 0) {
463
- throw new Error(`Environment variable "${envVar.trim()}" is not defined`);
464
- }
465
- return value;
466
- });
467
- }
468
- function parseYamlScript(content, filePath, ignoreCheckingTarget) {
469
- const interpolatedContent = interpolateEnvVars(content);
470
- const obj = import_js_yaml2.default.load(interpolatedContent);
471
- const pathTip = filePath ? `, failed to load ${filePath}` : "";
472
- const android = typeof obj.android !== "undefined" ? Object.assign({}, obj.android || {}) : void 0;
473
- const webConfig = obj.web || obj.target;
474
- const web = typeof webConfig !== "undefined" ? Object.assign({}, webConfig || {}) : void 0;
475
- if (!ignoreCheckingTarget) {
476
- (0, import_utils4.assert)(
477
- web || android,
478
- `at least one of "target", "web", or "android" properties is required in yaml script${pathTip}`
479
- );
480
- (0, import_utils4.assert)(
481
- web && !android || !web && android,
482
- `only one of "target", "web", or "android" properties is allowed in yaml script${pathTip}`
483
- );
484
- if (web || android) {
485
- (0, import_utils4.assert)(
486
- typeof web === "object" || typeof android === "object",
487
- `property "target/web/android" must be an object${pathTip}`
488
- );
489
- }
490
- }
491
- (0, import_utils4.assert)(obj.tasks, `property "tasks" is required in yaml script ${pathTip}`);
492
- (0, import_utils4.assert)(
493
- Array.isArray(obj.tasks),
494
- `property "tasks" must be an array in yaml script, but got ${obj.tasks}`
495
- );
496
- return obj;
497
- }
498
-
499
- // src/common/agent.ts
500
- var import_utils11 = require("misoai-core/utils");
501
- var import_constants2 = require("misoai-shared/constants");
502
- var import_env2 = require("misoai-shared/env");
503
- var import_logger4 = require("misoai-shared/logger");
504
- var import_utils12 = require("misoai-shared/utils");
505
-
506
- // src/common/tasks.ts
507
- var import_misoai_core = require("misoai-core");
508
- var import_ai_model2 = require("misoai-core/ai-model");
509
- var import_utils5 = require("misoai-core/utils");
510
- var import_constants = require("misoai-shared/constants");
511
- var import_fs = require("misoai-shared/fs");
512
- var import_logger = require("misoai-shared/logger");
513
- var import_utils6 = require("misoai-shared/utils");
514
-
515
- // src/common/ui-utils.ts
516
- function typeStr(task) {
517
- return task.subType && task.subType !== "Plan" ? `${task.type} / ${task.subType || ""}` : task.type;
518
- }
519
- function getKeyCommands(value) {
520
- const keys = Array.isArray(value) ? value : [value];
521
- return keys.reduce((acc, k) => {
522
- const includeMeta = keys.includes("Meta") || keys.includes("Control");
523
- if (includeMeta && (k === "a" || k === "A")) {
524
- return acc.concat([{ key: k, command: "SelectAll" }]);
525
- }
526
- if (includeMeta && (k === "c" || k === "C")) {
527
- return acc.concat([{ key: k, command: "Copy" }]);
528
- }
529
- if (includeMeta && (k === "v" || k === "V")) {
530
- return acc.concat([{ key: k, command: "Paste" }]);
531
- }
532
- return acc.concat([{ key: k }]);
533
- }, []);
534
- }
535
- function locateParamStr(locate) {
536
- if (!locate) {
537
- return "";
538
- }
539
- if (typeof locate === "string") {
540
- return locate;
541
- }
542
- return locate.prompt;
543
- }
544
- function scrollParamStr(scrollParam) {
545
- if (!scrollParam) {
546
- return "";
547
- }
548
- return `${scrollParam.direction || "down"}, ${scrollParam.scrollType || "once"}, ${scrollParam.distance || "distance-not-set"}`;
549
- }
550
- function taskTitleStr(type, prompt) {
551
- if (prompt) {
552
- return `${type} - ${prompt}`;
553
- }
554
- return type;
555
- }
556
- function paramStr(task) {
557
- let value;
558
- if (task.type === "Planning") {
559
- value = task?.param?.userInstruction;
560
- }
561
- if (task.type === "Insight") {
562
- value = task?.param?.prompt || task?.param?.id || task?.param?.dataDemand || task?.param?.assertion;
563
- }
564
- if (task.type === "Action") {
565
- const locate = task?.locate;
566
- const locateStr = locate ? locateParamStr(locate) : "";
567
- value = task.thought || "";
568
- if (typeof task?.param?.timeMs === "number") {
569
- value = `${task?.param?.timeMs}ms`;
570
- } else if (typeof task?.param?.scrollType === "string") {
571
- value = scrollParamStr(task?.param);
572
- } else if (typeof task?.param?.value !== "undefined") {
573
- value = task?.param?.value;
574
- }
575
- if (locateStr) {
576
- if (value) {
577
- value = `${locateStr} - ${value}`;
578
- } else {
579
- value = locateStr;
580
- }
581
- }
582
- }
583
- if (typeof value === "undefined")
584
- return "";
585
- return typeof value === "string" ? value : JSON.stringify(value, void 0, 2);
586
- }
587
- var limitOpenNewTabScript = `
588
- if (!window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__) {
589
- window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__ = true;
590
-
591
- // Intercept the window.open method (only once)
592
- window.open = function(url) {
593
- console.log('Blocked window.open:', url);
594
- window.location.href = url;
595
- return null;
596
- };
597
-
598
- // Block all a tag clicks with target="_blank" (only once)
599
- document.addEventListener('click', function(e) {
600
- const target = e.target.closest('a');
601
- if (target && target.target === '_blank') {
602
- e.preventDefault();
603
- console.log('Blocked new tab:', target.href);
604
- window.location.href = target.href;
605
- target.removeAttribute('target');
606
- }
607
- }, true);
608
- }
609
- `;
610
-
611
- // src/common/tasks.ts
612
- var debug = (0, import_logger.getDebug)("page-task-executor");
613
- var replanningCountLimit = 10;
614
- var isAndroidPage = (page) => {
615
- return page.pageType === "android";
616
- };
617
- var PageTaskExecutor = class {
618
- constructor(page, insight, opts) {
619
- this.conversationHistory = [];
620
- this.page = page;
621
- this.insight = insight;
622
- this.taskCache = opts.taskCache;
623
- this.onTaskStartCallback = opts?.onTaskStart;
624
- }
625
- async recordScreenshot(timing) {
626
- const base64 = await this.page.screenshotBase64();
627
- const item = {
628
- type: "screenshot",
629
- ts: Date.now(),
630
- screenshot: base64,
631
- timing
632
- };
633
- return item;
634
- }
635
- async getElementXpath(pageContext, element) {
636
- let elementId = element?.id;
637
- if (element?.attributes?.nodeType === import_constants.NodeType.POSITION) {
638
- await this.insight.contextRetrieverFn("locate");
639
- const info = (0, import_ai_model2.elementByPositionWithElementInfo)(
640
- pageContext.tree,
641
- {
642
- x: element.center[0],
643
- y: element.center[1]
644
- },
645
- {
646
- requireStrictDistance: false,
647
- filterPositionElements: true
648
- }
649
- );
650
- if (info?.id) {
651
- elementId = info.id;
652
- }
653
- }
654
- if (!elementId) {
655
- return void 0;
656
- }
657
- try {
658
- const elementInfosScriptContent = (0, import_fs.getElementInfosScriptContent)();
659
- const result = await this.page.evaluateJavaScript?.(
660
- `${elementInfosScriptContent}midscene_element_inspector.getXpathsById('${elementId}')`
661
- );
662
- return result;
663
- } catch (error) {
664
- debug("getXpathsById error: ", error);
665
- }
666
- }
667
- prependExecutorWithScreenshot(taskApply, appendAfterExecution = false) {
668
- const taskWithScreenshot = {
669
- ...taskApply,
670
- executor: async (param, context, ...args) => {
671
- const recorder = [];
672
- const { task } = context;
673
- task.recorder = recorder;
674
- const shot = await this.recordScreenshot(`before ${task.type}`);
675
- recorder.push(shot);
676
- const result = await taskApply.executor(param, context, ...args);
677
- if (taskApply.type === "Action") {
678
- await Promise.all([
679
- (async () => {
680
- await (0, import_utils5.sleep)(100);
681
- if (this.page.waitUntilNetworkIdle) {
682
- try {
683
- await this.page.waitUntilNetworkIdle();
684
- } catch (error) {
685
- }
686
- }
687
- })(),
688
- (0, import_utils5.sleep)(200)
689
- ]);
690
- }
691
- if (appendAfterExecution) {
692
- const shot2 = await this.recordScreenshot("after Action");
693
- recorder.push(shot2);
694
- }
695
- return result;
696
- }
697
- };
698
- return taskWithScreenshot;
699
- }
700
- async convertPlanToExecutable(plans) {
701
- const tasks = [];
702
- plans.forEach((plan2) => {
703
- if (plan2.type === "Locate") {
704
- if (plan2.locate === null || plan2.locate?.id === null || plan2.locate?.id === "null") {
705
- return;
706
- }
707
- const taskFind = {
708
- type: "Insight",
709
- subType: "Locate",
710
- param: plan2.locate || void 0,
711
- thought: plan2.thought,
712
- locate: plan2.locate,
713
- executor: async (param, taskContext) => {
714
- const { task } = taskContext;
715
- (0, import_utils6.assert)(
716
- param?.prompt || param?.id || param?.bbox,
717
- "No prompt or id or position or bbox to locate"
718
- );
719
- let insightDump;
720
- let usage;
721
- const dumpCollector = (dump) => {
722
- insightDump = dump;
723
- usage = dump?.taskInfo?.usage;
724
- task.log = {
725
- dump: insightDump
726
- };
727
- task.usage = usage;
728
- };
729
- this.insight.onceDumpUpdatedFn = dumpCollector;
730
- const shotTime = Date.now();
731
- const pageContext = await this.insight.contextRetrieverFn("locate");
732
- task.pageContext = pageContext;
733
- const recordItem = {
734
- type: "screenshot",
735
- ts: shotTime,
736
- screenshot: pageContext.screenshotBase64,
737
- timing: "before locate"
738
- };
739
- task.recorder = [recordItem];
740
- let cacheHitFlag = false;
741
- const cachePrompt = param.prompt;
742
- const locateCacheRecord = this.taskCache?.matchLocateCache(cachePrompt);
743
- const xpaths = locateCacheRecord?.cacheContent?.xpaths;
744
- let elementFromCache = null;
745
- try {
746
- if (xpaths?.length && this.taskCache?.isCacheResultUsed && param?.cacheable !== false) {
747
- const elementInfosScriptContent = (0, import_fs.getElementInfosScriptContent)();
748
- const element2 = await this.page.evaluateJavaScript?.(
749
- `${elementInfosScriptContent}midscene_element_inspector.getElementInfoByXpath('${xpaths[0]}')`
750
- );
751
- if (element2?.id) {
752
- elementFromCache = element2;
753
- debug("cache hit, prompt: %s", cachePrompt);
754
- cacheHitFlag = true;
755
- debug(
756
- "found a new new element with same xpath, xpath: %s, id: %s",
757
- xpaths[0],
758
- element2?.id
759
- );
760
- }
761
- }
762
- } catch (error) {
763
- debug("get element info by xpath error: ", error);
764
- }
765
- const startTime = Date.now();
766
- const element = elementFromCache || // try to match element from cache
767
- matchElementFromPlan(param, pageContext.tree) || // try to match element from plan
768
- (await this.insight.locate(param, {
769
- context: pageContext
770
- })).element;
771
- const aiCost = Date.now() - startTime;
772
- if (element && this.taskCache && !cacheHitFlag && param?.cacheable !== false) {
773
- const elementXpaths = await this.getElementXpath(
774
- pageContext,
775
- element
776
- );
777
- if (elementXpaths) {
778
- this.taskCache.updateOrAppendCacheRecord(
779
- {
780
- type: "locate",
781
- prompt: cachePrompt,
782
- xpaths: elementXpaths
783
- },
784
- locateCacheRecord
785
- );
786
- } else {
787
- debug("no xpaths found, will not update cache", cachePrompt);
788
- }
789
- }
790
- if (!element) {
791
- throw new Error(`Element not found: ${param.prompt}`);
792
- }
793
- return {
794
- output: {
795
- element
796
- },
797
- pageContext,
798
- cache: {
799
- hit: cacheHitFlag
800
- },
801
- aiCost
802
- };
803
- }
804
- };
805
- tasks.push(taskFind);
806
- } else if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
807
- const assertPlan = plan2;
808
- const taskAssert = {
809
- type: "Insight",
810
- subType: "Assert",
811
- param: assertPlan.param,
812
- thought: assertPlan.thought,
813
- locate: assertPlan.locate,
814
- executor: async (param, taskContext) => {
815
- const { task } = taskContext;
816
- let insightDump;
817
- const dumpCollector = (dump) => {
818
- insightDump = dump;
819
- };
820
- this.insight.onceDumpUpdatedFn = dumpCollector;
821
- const assertion = await this.insight.assert(
822
- assertPlan.param.assertion
823
- );
824
- if (!assertion.pass) {
825
- if (plan2.type === "Assert") {
826
- task.output = assertion;
827
- task.log = {
828
- dump: insightDump
829
- };
830
- throw new Error(
831
- assertion.thought || "Assertion failed without reason"
832
- );
833
- }
834
- task.error = assertion.thought;
835
- }
836
- return {
837
- output: assertion,
838
- log: {
839
- dump: insightDump
840
- },
841
- usage: assertion.usage
842
- };
843
- }
844
- };
845
- tasks.push(taskAssert);
846
- } else if (plan2.type === "Input") {
847
- const taskActionInput = {
848
- type: "Action",
849
- subType: "Input",
850
- param: plan2.param,
851
- thought: plan2.thought,
852
- locate: plan2.locate,
853
- executor: async (taskParam, { element }) => {
854
- if (element) {
855
- await this.page.clearInput(element);
856
- if (!taskParam || !taskParam.value) {
857
- return;
858
- }
859
- await this.page.keyboard.type(taskParam.value);
860
- } else {
861
- await this.page.keyboard.type(taskParam.value);
862
- }
863
- }
864
- };
865
- tasks.push(taskActionInput);
866
- } else if (plan2.type === "KeyboardPress") {
867
- const taskActionKeyboardPress = {
868
- type: "Action",
869
- subType: "KeyboardPress",
870
- param: plan2.param,
871
- thought: plan2.thought,
872
- locate: plan2.locate,
873
- executor: async (taskParam) => {
874
- const keys = getKeyCommands(taskParam.value);
875
- await this.page.keyboard.press(keys);
876
- }
877
- };
878
- tasks.push(taskActionKeyboardPress);
879
- } else if (plan2.type === "Tap") {
880
- const taskActionTap = {
881
- type: "Action",
882
- subType: "Tap",
883
- thought: plan2.thought,
884
- locate: plan2.locate,
885
- executor: async (param, { element }) => {
886
- (0, import_utils6.assert)(element, "Element not found, cannot tap");
887
- await this.page.mouse.click(element.center[0], element.center[1]);
888
- }
889
- };
890
- tasks.push(taskActionTap);
891
- } else if (plan2.type === "Drag") {
892
- const taskActionDrag = {
893
- type: "Action",
894
- subType: "Drag",
895
- param: plan2.param,
896
- thought: plan2.thought,
897
- locate: plan2.locate,
898
- executor: async (taskParam) => {
899
- (0, import_utils6.assert)(
900
- taskParam?.start_box && taskParam?.end_box,
901
- "No start_box or end_box to drag"
902
- );
903
- await this.page.mouse.drag(taskParam.start_box, taskParam.end_box);
904
- }
905
- };
906
- tasks.push(taskActionDrag);
907
- } else if (plan2.type === "Hover") {
908
- const taskActionHover = {
909
- type: "Action",
910
- subType: "Hover",
911
- thought: plan2.thought,
912
- locate: plan2.locate,
913
- executor: async (param, { element }) => {
914
- (0, import_utils6.assert)(element, "Element not found, cannot hover");
915
- await this.page.mouse.move(element.center[0], element.center[1]);
916
- }
917
- };
918
- tasks.push(taskActionHover);
919
- } else if (plan2.type === "Scroll") {
920
- const taskActionScroll = {
921
- type: "Action",
922
- subType: "Scroll",
923
- param: plan2.param,
924
- thought: plan2.thought,
925
- locate: plan2.locate,
926
- executor: async (taskParam, { element }) => {
927
- const startingPoint = element ? {
928
- left: element.center[0],
929
- top: element.center[1]
930
- } : void 0;
931
- const scrollToEventName = taskParam?.scrollType;
932
- if (scrollToEventName === "untilTop") {
933
- await this.page.scrollUntilTop(startingPoint);
934
- } else if (scrollToEventName === "untilBottom") {
935
- await this.page.scrollUntilBottom(startingPoint);
936
- } else if (scrollToEventName === "untilRight") {
937
- await this.page.scrollUntilRight(startingPoint);
938
- } else if (scrollToEventName === "untilLeft") {
939
- await this.page.scrollUntilLeft(startingPoint);
940
- } else if (scrollToEventName === "once" || !scrollToEventName) {
941
- if (taskParam?.direction === "down" || !taskParam || !taskParam.direction) {
942
- await this.page.scrollDown(
943
- taskParam?.distance || void 0,
944
- startingPoint
945
- );
946
- } else if (taskParam.direction === "up") {
947
- await this.page.scrollUp(
948
- taskParam.distance || void 0,
949
- startingPoint
950
- );
951
- } else if (taskParam.direction === "left") {
952
- await this.page.scrollLeft(
953
- taskParam.distance || void 0,
954
- startingPoint
955
- );
956
- } else if (taskParam.direction === "right") {
957
- await this.page.scrollRight(
958
- taskParam.distance || void 0,
959
- startingPoint
960
- );
961
- } else {
962
- throw new Error(
963
- `Unknown scroll direction: ${taskParam.direction}`
964
- );
965
- }
966
- await (0, import_utils5.sleep)(500);
967
- } else {
968
- throw new Error(
969
- `Unknown scroll event type: ${scrollToEventName}, taskParam: ${JSON.stringify(
970
- taskParam
971
- )}`
972
- );
973
- }
974
- }
975
- };
976
- tasks.push(taskActionScroll);
977
- } else if (plan2.type === "Sleep") {
978
- const taskActionSleep = {
979
- type: "Action",
980
- subType: "Sleep",
981
- param: plan2.param,
982
- thought: plan2.thought,
983
- locate: plan2.locate,
984
- executor: async (taskParam) => {
985
- await (0, import_utils5.sleep)(taskParam?.timeMs || 3e3);
986
- }
987
- };
988
- tasks.push(taskActionSleep);
989
- } else if (plan2.type === "Error") {
990
- const taskActionError = {
991
- type: "Action",
992
- subType: "Error",
993
- param: plan2.param,
994
- thought: plan2.thought || plan2.param?.thought,
995
- locate: plan2.locate,
996
- executor: async () => {
997
- throw new Error(
998
- plan2?.thought || plan2.param?.thought || "error without thought"
999
- );
1000
- }
1001
- };
1002
- tasks.push(taskActionError);
1003
- } else if (plan2.type === "ExpectedFalsyCondition") {
1004
- const taskActionFalsyConditionStatement = {
1005
- type: "Action",
1006
- subType: "ExpectedFalsyCondition",
1007
- param: null,
1008
- thought: plan2.param?.reason,
1009
- locate: plan2.locate,
1010
- executor: async () => {
1011
- }
1012
- };
1013
- tasks.push(taskActionFalsyConditionStatement);
1014
- } else if (plan2.type === "Finished") {
1015
- const taskActionFinished = {
1016
- type: "Action",
1017
- subType: "Finished",
1018
- param: null,
1019
- thought: plan2.thought,
1020
- locate: plan2.locate,
1021
- executor: async (param) => {
1022
- }
1023
- };
1024
- tasks.push(taskActionFinished);
1025
- } else if (plan2.type === "AndroidHomeButton") {
1026
- const taskActionAndroidHomeButton = {
1027
- type: "Action",
1028
- subType: "AndroidHomeButton",
1029
- param: null,
1030
- thought: plan2.thought,
1031
- locate: plan2.locate,
1032
- executor: async (param) => {
1033
- (0, import_utils6.assert)(
1034
- isAndroidPage(this.page),
1035
- "Cannot use home button on non-Android devices"
1036
- );
1037
- await this.page.home();
1038
- }
1039
- };
1040
- tasks.push(taskActionAndroidHomeButton);
1041
- } else if (plan2.type === "AndroidBackButton") {
1042
- const taskActionAndroidBackButton = {
1043
- type: "Action",
1044
- subType: "AndroidBackButton",
1045
- param: null,
1046
- thought: plan2.thought,
1047
- locate: plan2.locate,
1048
- executor: async (param) => {
1049
- (0, import_utils6.assert)(
1050
- isAndroidPage(this.page),
1051
- "Cannot use back button on non-Android devices"
1052
- );
1053
- await this.page.back();
1054
- }
1055
- };
1056
- tasks.push(taskActionAndroidBackButton);
1057
- } else if (plan2.type === "AndroidRecentAppsButton") {
1058
- const taskActionAndroidRecentAppsButton = {
1059
- type: "Action",
1060
- subType: "AndroidRecentAppsButton",
1061
- param: null,
1062
- thought: plan2.thought,
1063
- locate: plan2.locate,
1064
- executor: async (param) => {
1065
- (0, import_utils6.assert)(
1066
- isAndroidPage(this.page),
1067
- "Cannot use recent apps button on non-Android devices"
1068
- );
1069
- await this.page.recentApps();
1070
- }
1071
- };
1072
- tasks.push(taskActionAndroidRecentAppsButton);
1073
- } else {
1074
- throw new Error(`Unknown or unsupported task type: ${plan2.type}`);
1075
- }
1076
- });
1077
- const wrappedTasks = tasks.map(
1078
- (task, index) => {
1079
- if (task.type === "Action") {
1080
- return this.prependExecutorWithScreenshot(
1081
- task,
1082
- index === tasks.length - 1
1083
- );
1084
- }
1085
- return task;
1086
- }
1087
- );
1088
- return {
1089
- tasks: wrappedTasks
1090
- };
1091
- }
1092
- async setupPlanningContext(executorContext) {
1093
- const shotTime = Date.now();
1094
- const pageContext = await this.insight.contextRetrieverFn("locate");
1095
- const recordItem = {
1096
- type: "screenshot",
1097
- ts: shotTime,
1098
- screenshot: pageContext.screenshotBase64,
1099
- timing: "before planning"
1100
- };
1101
- executorContext.task.recorder = [recordItem];
1102
- executorContext.task.pageContext = pageContext;
1103
- return {
1104
- pageContext
1105
- };
1106
- }
1107
- async loadYamlFlowAsPlanning(userInstruction, yamlString) {
1108
- const taskExecutor = new import_misoai_core.Executor(taskTitleStr("Action", userInstruction), {
1109
- onTaskStart: this.onTaskStartCallback
1110
- });
1111
- const task = {
1112
- type: "Planning",
1113
- subType: "LoadYaml",
1114
- locate: null,
1115
- param: {
1116
- userInstruction
1117
- },
1118
- executor: async (param, executorContext) => {
1119
- await this.setupPlanningContext(executorContext);
1120
- return {
1121
- output: {
1122
- actions: [],
1123
- more_actions_needed_by_instruction: false,
1124
- log: "",
1125
- yamlString
1126
- },
1127
- cache: {
1128
- hit: true
1129
- }
1130
- };
1131
- }
1132
- };
1133
- await taskExecutor.append(task);
1134
- await taskExecutor.flush();
1135
- return {
1136
- executor: taskExecutor
1137
- };
1138
- }
1139
- planningTaskFromPrompt(userInstruction, log, actionContext) {
1140
- const task = {
1141
- type: "Planning",
1142
- subType: "Plan",
1143
- locate: null,
1144
- param: {
1145
- userInstruction,
1146
- log
1147
- },
1148
- executor: async (param, executorContext) => {
1149
- const startTime = Date.now();
1150
- const { pageContext } = await this.setupPlanningContext(executorContext);
1151
- const planResult = await (0, import_misoai_core.plan)(param.userInstruction, {
1152
- context: pageContext,
1153
- log: param.log,
1154
- actionContext,
1155
- pageType: this.page.pageType
1156
- });
1157
- const {
1158
- actions,
1159
- log: log2,
1160
- more_actions_needed_by_instruction,
1161
- error,
1162
- usage,
1163
- rawResponse,
1164
- sleep: sleep3
1165
- } = planResult;
1166
- executorContext.task.log = {
1167
- rawResponse
1168
- };
1169
- executorContext.task.usage = usage;
1170
- let stopCollecting = false;
1171
- let bboxCollected = false;
1172
- let planParsingError = "";
1173
- const finalActions = (actions || []).reduce(
1174
- (acc, planningAction) => {
1175
- if (stopCollecting) {
1176
- return acc;
1177
- }
1178
- if (planningAction.locate) {
1179
- if (bboxCollected && planningAction.locate.bbox) {
1180
- delete planningAction.locate.bbox;
1181
- }
1182
- if (planningAction.locate.bbox) {
1183
- bboxCollected = true;
1184
- }
1185
- acc.push({
1186
- type: "Locate",
1187
- locate: planningAction.locate,
1188
- param: null,
1189
- thought: planningAction.locate.prompt
1190
- });
1191
- } else if (["Tap", "Hover", "Input"].includes(planningAction.type)) {
1192
- planParsingError = `invalid planning response: ${JSON.stringify(planningAction)}`;
1193
- stopCollecting = true;
1194
- return acc;
1195
- }
1196
- acc.push(planningAction);
1197
- return acc;
1198
- },
1199
- []
1200
- );
1201
- if (sleep3) {
1202
- const timeNow = Date.now();
1203
- const timeRemaining = sleep3 - (timeNow - startTime);
1204
- if (timeRemaining > 0) {
1205
- finalActions.push({
1206
- type: "Sleep",
1207
- param: {
1208
- timeMs: timeRemaining
1209
- },
1210
- locate: null
1211
- });
1212
- }
1213
- }
1214
- if (finalActions.length === 0) {
1215
- (0, import_utils6.assert)(
1216
- !more_actions_needed_by_instruction || sleep3,
1217
- error ? `Failed to plan: ${error}` : planParsingError || "No plan found"
1218
- );
1219
- }
1220
- return {
1221
- output: {
1222
- actions: finalActions,
1223
- more_actions_needed_by_instruction,
1224
- log: log2,
1225
- yamlFlow: planResult.yamlFlow
1226
- },
1227
- cache: {
1228
- hit: false
1229
- },
1230
- pageContext
1231
- };
1232
- }
1233
- };
1234
- return task;
1235
- }
1236
- planningTaskToGoal(userInstruction) {
1237
- const task = {
1238
- type: "Planning",
1239
- subType: "Plan",
1240
- locate: null,
1241
- param: {
1242
- userInstruction
1243
- },
1244
- executor: async (param, executorContext) => {
1245
- const { pageContext } = await this.setupPlanningContext(executorContext);
1246
- const imagePayload = await (0, import_ai_model2.resizeImageForUiTars)(
1247
- pageContext.screenshotBase64,
1248
- pageContext.size
1249
- );
1250
- this.appendConversationHistory({
1251
- role: "user",
1252
- content: [
1253
- {
1254
- type: "image_url",
1255
- image_url: {
1256
- url: imagePayload
1257
- }
1258
- }
1259
- ]
1260
- });
1261
- const startTime = Date.now();
1262
- const planResult = await (0, import_ai_model2.vlmPlanning)({
1263
- userInstruction: param.userInstruction,
1264
- conversationHistory: this.conversationHistory,
1265
- size: pageContext.size
1266
- });
1267
- const aiCost = Date.now() - startTime;
1268
- const { actions, action_summary } = planResult;
1269
- this.appendConversationHistory({
1270
- role: "assistant",
1271
- content: action_summary
1272
- });
1273
- return {
1274
- output: {
1275
- actions,
1276
- thought: actions[0]?.thought,
1277
- actionType: actions[0].type,
1278
- more_actions_needed_by_instruction: true,
1279
- log: "",
1280
- yamlFlow: planResult.yamlFlow
1281
- },
1282
- cache: {
1283
- hit: false
1284
- },
1285
- aiCost
1286
- };
1287
- }
1288
- };
1289
- return task;
1290
- }
1291
- async runPlans(title, plans) {
1292
- const taskExecutor = new import_misoai_core.Executor(title, {
1293
- onTaskStart: this.onTaskStartCallback
1294
- });
1295
- const { tasks } = await this.convertPlanToExecutable(plans);
1296
- await taskExecutor.append(tasks);
1297
- const result = await taskExecutor.flush();
1298
- return {
1299
- output: result,
1300
- executor: taskExecutor
1301
- };
1302
- }
1303
- async action(userPrompt, actionContext) {
1304
- const taskExecutor = new import_misoai_core.Executor(taskTitleStr("Action", userPrompt), {
1305
- onTaskStart: this.onTaskStartCallback
1306
- });
1307
- let planningTask = this.planningTaskFromPrompt(userPrompt, void 0, actionContext);
1308
- let replanCount = 0;
1309
- const logList = [];
1310
- const yamlFlow = [];
1311
- while (planningTask) {
1312
- if (replanCount > replanningCountLimit) {
1313
- const errorMsg = "Replanning too many times, please split the task into multiple steps";
1314
- return this.appendErrorPlan(taskExecutor, errorMsg);
1315
- }
1316
- await taskExecutor.append(planningTask);
1317
- const planResult = await taskExecutor.flush();
1318
- if (taskExecutor.isInErrorState()) {
1319
- return {
1320
- output: planResult,
1321
- executor: taskExecutor
1322
- };
1323
- }
1324
- const plans = planResult.actions || [];
1325
- yamlFlow.push(...planResult.yamlFlow || []);
1326
- let executables;
1327
- try {
1328
- executables = await this.convertPlanToExecutable(plans);
1329
- taskExecutor.append(executables.tasks);
1330
- } catch (error) {
1331
- return this.appendErrorPlan(
1332
- taskExecutor,
1333
- `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(
1334
- plans
1335
- )}`
1336
- );
1337
- }
1338
- await taskExecutor.flush();
1339
- if (taskExecutor.isInErrorState()) {
1340
- return {
1341
- output: void 0,
1342
- executor: taskExecutor
1343
- };
1344
- }
1345
- if (planResult?.log) {
1346
- logList.push(planResult.log);
1347
- }
1348
- if (!planResult.more_actions_needed_by_instruction) {
1349
- planningTask = null;
1350
- break;
1351
- }
1352
- planningTask = this.planningTaskFromPrompt(
1353
- userPrompt,
1354
- logList.length > 0 ? `- ${logList.join("\n- ")}` : void 0,
1355
- actionContext
1356
- );
1357
- replanCount++;
1358
- }
1359
- return {
1360
- output: {
1361
- yamlFlow
1362
- },
1363
- executor: taskExecutor
1364
- };
1365
- }
1366
- async actionToGoal(userPrompt) {
1367
- const taskExecutor = new import_misoai_core.Executor(taskTitleStr("Action", userPrompt), {
1368
- onTaskStart: this.onTaskStartCallback
1369
- });
1370
- this.conversationHistory = [];
1371
- const isCompleted = false;
1372
- let currentActionNumber = 0;
1373
- const maxActionNumber = 40;
1374
- const yamlFlow = [];
1375
- while (!isCompleted && currentActionNumber < maxActionNumber) {
1376
- currentActionNumber++;
1377
- const planningTask = this.planningTaskToGoal(userPrompt);
1378
- await taskExecutor.append(planningTask);
1379
- const output = await taskExecutor.flush();
1380
- if (taskExecutor.isInErrorState()) {
1381
- return {
1382
- output: void 0,
1383
- executor: taskExecutor
1384
- };
1385
- }
1386
- const plans = output.actions;
1387
- yamlFlow.push(...output.yamlFlow || []);
1388
- let executables;
1389
- try {
1390
- executables = await this.convertPlanToExecutable(plans);
1391
- taskExecutor.append(executables.tasks);
1392
- } catch (error) {
1393
- return this.appendErrorPlan(
1394
- taskExecutor,
1395
- `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(
1396
- plans
1397
- )}`
1398
- );
1399
- }
1400
- await taskExecutor.flush();
1401
- if (taskExecutor.isInErrorState()) {
1402
- return {
1403
- output: void 0,
1404
- executor: taskExecutor
1405
- };
1406
- }
1407
- if (plans[0].type === "Finished") {
1408
- break;
1409
- }
1410
- }
1411
- return {
1412
- output: {
1413
- yamlFlow
1414
- },
1415
- executor: taskExecutor
1416
- };
1417
- }
1418
- async createTypeQueryTask(type, demand) {
1419
- const taskExecutor = new import_misoai_core.Executor(
1420
- taskTitleStr(
1421
- type,
1422
- typeof demand === "string" ? demand : JSON.stringify(demand)
1423
- ),
1424
- {
1425
- onTaskStart: this.onTaskStartCallback
1426
- }
1427
- );
1428
- const queryTask = {
1429
- type: "Insight",
1430
- subType: type,
1431
- locate: null,
1432
- param: {
1433
- dataDemand: demand
1434
- // for user param presentation in report right sidebar
1435
- },
1436
- executor: async (param) => {
1437
- let insightDump;
1438
- const dumpCollector = (dump) => {
1439
- insightDump = dump;
1440
- };
1441
- this.insight.onceDumpUpdatedFn = dumpCollector;
1442
- const ifTypeRestricted = type !== "Query";
1443
- let demandInput = demand;
1444
- if (ifTypeRestricted) {
1445
- demandInput = {
1446
- result: `${type}, ${demand}`
1447
- };
1448
- }
1449
- const { data, usage } = await this.insight.extract(demandInput);
1450
- let outputResult = data;
1451
- if (ifTypeRestricted) {
1452
- (0, import_utils6.assert)(data?.result !== void 0, "No result in query data");
1453
- outputResult = data.result;
1454
- }
1455
- return {
1456
- output: outputResult,
1457
- log: { dump: insightDump },
1458
- usage
1459
- };
1460
- }
1461
- };
1462
- await taskExecutor.append(this.prependExecutorWithScreenshot(queryTask));
1463
- const output = await taskExecutor.flush();
1464
- return {
1465
- output,
1466
- executor: taskExecutor
1467
- };
1468
- }
1469
- async query(demand) {
1470
- return this.createTypeQueryTask("Query", demand);
1471
- }
1472
- async boolean(prompt) {
1473
- return this.createTypeQueryTask("Boolean", prompt);
1474
- }
1475
- async number(prompt) {
1476
- return this.createTypeQueryTask("Number", prompt);
1477
- }
1478
- async string(prompt) {
1479
- return this.createTypeQueryTask("String", prompt);
1480
- }
1481
- async assert(assertion) {
1482
- const description = `assert: ${assertion}`;
1483
- const taskExecutor = new import_misoai_core.Executor(taskTitleStr("Assert", description), {
1484
- onTaskStart: this.onTaskStartCallback
1485
- });
1486
- const assertionPlan = {
1487
- type: "Assert",
1488
- param: {
1489
- assertion
1490
- },
1491
- locate: null
1492
- };
1493
- const { tasks } = await this.convertPlanToExecutable([assertionPlan]);
1494
- await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));
1495
- const output = await taskExecutor.flush();
1496
- return {
1497
- output,
1498
- executor: taskExecutor
1499
- };
1500
- }
1501
- /**
1502
- * Append a message to the conversation history
1503
- * For user messages with images:
1504
- * - Keep max 4 user image messages in history
1505
- * - Remove oldest user image message when limit reached
1506
- * For assistant messages:
1507
- * - Simply append to history
1508
- * @param conversationHistory Message to append
1509
- */
1510
- appendConversationHistory(conversationHistory) {
1511
- if (conversationHistory.role === "user") {
1512
- const userImgItems = this.conversationHistory.filter(
1513
- (item) => item.role === "user"
1514
- );
1515
- if (userImgItems.length >= 4 && conversationHistory.role === "user") {
1516
- const firstUserImgIndex = this.conversationHistory.findIndex(
1517
- (item) => item.role === "user"
1518
- );
1519
- if (firstUserImgIndex >= 0) {
1520
- this.conversationHistory.splice(firstUserImgIndex, 1);
1521
- }
1522
- }
1523
- }
1524
- this.conversationHistory.push(conversationHistory);
1525
- }
1526
- async appendErrorPlan(taskExecutor, errorMsg) {
1527
- const errorPlan = {
1528
- type: "Error",
1529
- param: {
1530
- thought: errorMsg
1531
- },
1532
- locate: null
1533
- };
1534
- const { tasks } = await this.convertPlanToExecutable([errorPlan]);
1535
- await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));
1536
- await taskExecutor.flush();
1537
- return {
1538
- output: void 0,
1539
- executor: taskExecutor
1540
- };
1541
- }
1542
- async waitFor(assertion, opt) {
1543
- const description = `waitFor: ${assertion}`;
1544
- const taskExecutor = new import_misoai_core.Executor(taskTitleStr("WaitFor", description), {
1545
- onTaskStart: this.onTaskStartCallback
1546
- });
1547
- const { timeoutMs, checkIntervalMs } = opt;
1548
- (0, import_utils6.assert)(assertion, "No assertion for waitFor");
1549
- (0, import_utils6.assert)(timeoutMs, "No timeoutMs for waitFor");
1550
- (0, import_utils6.assert)(checkIntervalMs, "No checkIntervalMs for waitFor");
1551
- const overallStartTime = Date.now();
1552
- let startTime = Date.now();
1553
- let errorThought = "";
1554
- while (Date.now() - overallStartTime < timeoutMs) {
1555
- startTime = Date.now();
1556
- const assertPlan = {
1557
- type: "AssertWithoutThrow",
1558
- param: {
1559
- assertion
1560
- },
1561
- locate: null
1562
- };
1563
- const { tasks: assertTasks } = await this.convertPlanToExecutable([
1564
- assertPlan
1565
- ]);
1566
- await taskExecutor.append(
1567
- this.prependExecutorWithScreenshot(assertTasks[0])
1568
- );
1569
- const output = await taskExecutor.flush();
1570
- if (output?.pass) {
1571
- return {
1572
- output: void 0,
1573
- executor: taskExecutor
1574
- };
1575
- }
1576
- errorThought = output?.thought || `unknown error when waiting for assertion: ${assertion}`;
1577
- const now = Date.now();
1578
- if (now - startTime < checkIntervalMs) {
1579
- const timeRemaining = checkIntervalMs - (now - startTime);
1580
- const sleepPlan = {
1581
- type: "Sleep",
1582
- param: {
1583
- timeMs: timeRemaining
1584
- },
1585
- locate: null
1586
- };
1587
- const { tasks: sleepTasks } = await this.convertPlanToExecutable([
1588
- sleepPlan
1589
- ]);
1590
- await taskExecutor.append(
1591
- this.prependExecutorWithScreenshot(sleepTasks[0])
1592
- );
1593
- await taskExecutor.flush();
1594
- }
1595
- }
1596
- return this.appendErrorPlan(
1597
- taskExecutor,
1598
- `waitFor timeout: ${errorThought}`
1599
- );
1600
- }
1601
- };
1602
-
1603
- // src/common/plan-builder.ts
1604
- var import_logger2 = require("misoai-shared/logger");
1605
- var import_utils8 = require("misoai-shared/utils");
1606
- var debug2 = (0, import_logger2.getDebug)("plan-builder");
1607
- function buildPlans(type, locateParam, param) {
1608
- let returnPlans = [];
1609
- const locatePlan = locateParam ? {
1610
- type: "Locate",
1611
- locate: locateParam,
1612
- param: locateParam,
1613
- thought: ""
1614
- } : null;
1615
- if (type === "Tap" || type === "Hover") {
1616
- (0, import_utils8.assert)(locateParam, `missing locate info for action "${type}"`);
1617
- (0, import_utils8.assert)(locatePlan, `missing locate info for action "${type}"`);
1618
- const tapPlan = {
1619
- type,
1620
- param: null,
1621
- thought: "",
1622
- locate: locateParam
1623
- };
1624
- returnPlans = [locatePlan, tapPlan];
1625
- }
1626
- if (type === "Input" || type === "KeyboardPress") {
1627
- if (type === "Input") {
1628
- (0, import_utils8.assert)(locateParam, `missing locate info for action "${type}"`);
1629
- }
1630
- (0, import_utils8.assert)(param, `missing param for action "${type}"`);
1631
- const inputPlan = {
1632
- type,
1633
- param,
1634
- thought: "",
1635
- locate: locateParam
1636
- };
1637
- if (locatePlan) {
1638
- returnPlans = [locatePlan, inputPlan];
1639
- } else {
1640
- returnPlans = [inputPlan];
1641
- }
1642
- }
1643
- if (type === "Scroll") {
1644
- (0, import_utils8.assert)(param, `missing param for action "${type}"`);
1645
- const scrollPlan = {
1646
- type,
1647
- param,
1648
- thought: "",
1649
- locate: locateParam
1650
- };
1651
- if (locatePlan) {
1652
- returnPlans = [locatePlan, scrollPlan];
1653
- } else {
1654
- returnPlans = [scrollPlan];
1655
- }
1656
- }
1657
- if (type === "Sleep") {
1658
- (0, import_utils8.assert)(param, `missing param for action "${type}"`);
1659
- const sleepPlan = {
1660
- type,
1661
- param,
1662
- thought: "",
1663
- locate: null
1664
- };
1665
- returnPlans = [sleepPlan];
1666
- }
1667
- if (type === "Locate") {
1668
- (0, import_utils8.assert)(locateParam, `missing locate info for action "${type}"`);
1669
- const locatePlan2 = {
1670
- type,
1671
- param: locateParam,
1672
- locate: locateParam,
1673
- thought: ""
1674
- };
1675
- returnPlans = [locatePlan2];
1676
- }
1677
- if (returnPlans) {
1678
- debug2("buildPlans", returnPlans);
1679
- return returnPlans;
1680
- }
1681
- throw new Error(`Not supported type: ${type}`);
1682
- }
1683
-
1684
- // src/common/task-cache.ts
1685
- var import_node_assert = __toESM(require("assert"));
1686
- var import_node_fs2 = require("fs");
1687
- var import_node_path2 = require("path");
1688
- var import_common2 = require("misoai-shared/common");
1689
- var import_logger3 = require("misoai-shared/logger");
1690
- var import_utils9 = require("misoai-shared/utils");
1691
- var import_js_yaml3 = __toESM(require("js-yaml"));
1692
- var import_semver = __toESM(require("semver"));
1693
-
1694
- // package.json
1695
- var version = "1.0.2";
1696
-
1697
- // src/common/task-cache.ts
1698
- var debug3 = (0, import_logger3.getDebug)("cache");
1699
- var lowestSupportedMidsceneVersion = "0.16.10";
1700
- var cacheFileExt = ".cache.yaml";
1701
- var TaskCache = class {
1702
- // Track matched records
1703
- constructor(cacheId, isCacheResultUsed, cacheFilePath) {
1704
- this.matchedCacheIndices = /* @__PURE__ */ new Set();
1705
- (0, import_node_assert.default)(cacheId, "cacheId is required");
1706
- this.cacheId = replaceIllegalPathCharsAndSpace(cacheId);
1707
- this.cacheFilePath = import_utils9.ifInBrowser ? void 0 : cacheFilePath || (0, import_node_path2.join)((0, import_common2.getMidsceneRunSubDir)("cache"), `${this.cacheId}${cacheFileExt}`);
1708
- this.isCacheResultUsed = isCacheResultUsed;
1709
- let cacheContent;
1710
- if (this.cacheFilePath) {
1711
- cacheContent = this.loadCacheFromFile();
1712
- }
1713
- if (!cacheContent) {
1714
- cacheContent = {
1715
- midsceneVersion: version,
1716
- cacheId: this.cacheId,
1717
- caches: []
1718
- };
1719
- }
1720
- this.cache = cacheContent;
1721
- this.cacheOriginalLength = this.cache.caches.length;
1722
- }
1723
- matchCache(prompt, type) {
1724
- for (let i = 0; i < this.cacheOriginalLength; i++) {
1725
- const item = this.cache.caches[i];
1726
- const key = `${type}:${prompt}:${i}`;
1727
- if (item.type === type && item.prompt === prompt && !this.matchedCacheIndices.has(key)) {
1728
- this.matchedCacheIndices.add(key);
1729
- debug3(
1730
- "cache found and marked as used, type: %s, prompt: %s, index: %d",
1731
- type,
1732
- prompt,
1733
- i
1734
- );
1735
- return {
1736
- cacheContent: item,
1737
- updateFn: (cb) => {
1738
- debug3(
1739
- "will call updateFn to update cache, type: %s, prompt: %s, index: %d",
1740
- type,
1741
- prompt,
1742
- i
1743
- );
1744
- cb(item);
1745
- debug3(
1746
- "cache updated, will flush to file, type: %s, prompt: %s, index: %d",
1747
- type,
1748
- prompt,
1749
- i
1750
- );
1751
- this.flushCacheToFile();
1752
- }
1753
- };
1754
- }
1755
- }
1756
- debug3("no unused cache found, type: %s, prompt: %s", type, prompt);
1757
- return void 0;
1758
- }
1759
- matchPlanCache(prompt) {
1760
- return this.matchCache(prompt, "plan");
1761
- }
1762
- matchLocateCache(prompt) {
1763
- return this.matchCache(prompt, "locate");
1764
- }
1765
- appendCache(cache) {
1766
- debug3("will append cache", cache);
1767
- this.cache.caches.push(cache);
1768
- this.flushCacheToFile();
1769
- }
1770
- loadCacheFromFile() {
1771
- const cacheFile = this.cacheFilePath;
1772
- (0, import_node_assert.default)(cacheFile, "cache file path is required");
1773
- if (!(0, import_node_fs2.existsSync)(cacheFile)) {
1774
- debug3("no cache file found, path: %s", cacheFile);
1775
- return void 0;
1776
- }
1777
- const jsonTypeCacheFile = cacheFile.replace(cacheFileExt, ".json");
1778
- if ((0, import_node_fs2.existsSync)(jsonTypeCacheFile) && this.isCacheResultUsed) {
1779
- console.warn(
1780
- `An outdated cache file from an earlier version of Midscene has been detected. Since version 0.17, we have implemented an improved caching strategy. Please delete the old file located at: ${jsonTypeCacheFile}.`
1781
- );
1782
- return void 0;
1783
- }
1784
- try {
1785
- const data = (0, import_node_fs2.readFileSync)(cacheFile, "utf8");
1786
- const jsonData = import_js_yaml3.default.load(data);
1787
- if (!version) {
1788
- debug3("no midscene version info, will not read cache from file");
1789
- return void 0;
1790
- }
1791
- if (import_semver.default.lt(jsonData.midsceneVersion, lowestSupportedMidsceneVersion) && !jsonData.midsceneVersion.includes("beta")) {
1792
- console.warn(
1793
- `You are using an old version of Midscene cache file, and we cannot match any info from it. Starting from Midscene v0.17, we changed our strategy to use xpath for cache info, providing better performance.
1794
- Please delete the existing cache and rebuild it. Sorry for the inconvenience.
1795
- cache file: ${cacheFile}`
1796
- );
1797
- return void 0;
1798
- }
1799
- debug3(
1800
- "cache loaded from file, path: %s, cache version: %s, record length: %s",
1801
- cacheFile,
1802
- jsonData.midsceneVersion,
1803
- jsonData.caches.length
1804
- );
1805
- jsonData.midsceneVersion = version;
1806
- return jsonData;
1807
- } catch (err) {
1808
- debug3(
1809
- "cache file exists but load failed, path: %s, error: %s",
1810
- cacheFile,
1811
- err
1812
- );
1813
- return void 0;
1814
- }
1815
- }
1816
- flushCacheToFile() {
1817
- if (!version) {
1818
- debug3("no midscene version info, will not write cache to file");
1819
- return;
1820
- }
1821
- if (!this.cacheFilePath) {
1822
- debug3("no cache file path, will not write cache to file");
1823
- return;
1824
- }
1825
- try {
1826
- const yamlData = import_js_yaml3.default.dump(this.cache);
1827
- (0, import_node_fs2.writeFileSync)(this.cacheFilePath, yamlData);
1828
- } catch (err) {
1829
- debug3(
1830
- "write cache to file failed, path: %s, error: %s",
1831
- this.cacheFilePath,
1832
- err
1833
- );
1834
- }
1835
- }
1836
- updateOrAppendCacheRecord(newRecord, cachedRecord) {
1837
- if (cachedRecord) {
1838
- if (newRecord.type === "plan") {
1839
- cachedRecord.updateFn((cache) => {
1840
- cache.yamlWorkflow = newRecord.yamlWorkflow;
1841
- });
1842
- } else {
1843
- cachedRecord.updateFn((cache) => {
1844
- cache.xpaths = newRecord.xpaths;
1845
- });
1846
- }
1847
- } else {
1848
- this.appendCache(newRecord);
1849
- }
1850
- }
1851
- };
1852
-
1853
- // src/common/agent.ts
1854
- var debug4 = (0, import_logger4.getDebug)("web-integration");
1855
- var distanceOfTwoPoints = (p1, p2) => {
1856
- const [x1, y1] = p1;
1857
- const [x2, y2] = p2;
1858
- return Math.round(Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2));
1859
- };
1860
- var includedInRect = (point, rect) => {
1861
- const [x, y] = point;
1862
- const { left, top, width, height } = rect;
1863
- return x >= left && x <= left + width && y >= top && y <= top + height;
1864
- };
1865
- var PageAgent = class {
1866
- constructor(page, opts) {
1867
- /**
1868
- * If true, the agent will not perform any actions
1869
- */
1870
- this.dryMode = false;
1871
- this.page = page;
1872
- this.opts = Object.assign(
1873
- {
1874
- generateReport: true,
1875
- autoPrintReportMsg: true,
1876
- groupName: "Midscene Report",
1877
- groupDescription: ""
1878
- },
1879
- opts || {}
1880
- );
1881
- if (this.page.pageType === "puppeteer" || this.page.pageType === "playwright") {
1882
- this.page.waitForNavigationTimeout = this.opts.waitForNavigationTimeout || import_constants2.DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT;
1883
- this.page.waitForNetworkIdleTimeout = this.opts.waitForNetworkIdleTimeout || import_constants2.DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT;
1884
- }
1885
- this.onTaskStartTip = this.opts.onTaskStartTip;
1886
- this.insight = new import_misoai_core2.Insight(
1887
- async (action) => {
1888
- return this.getUIContext(action);
1889
- }
1890
- );
1891
- if (opts?.cacheId && this.page.pageType !== "android") {
1892
- this.taskCache = new TaskCache(
1893
- opts.cacheId,
1894
- (0, import_env2.getAIConfigInBoolean)("MIDSCENE_CACHE")
1895
- // if we should use cache to match the element
1896
- );
1897
- }
1898
- this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {
1899
- taskCache: this.taskCache,
1900
- onTaskStart: this.callbackOnTaskStartTip.bind(this)
1901
- });
1902
- this.dump = this.resetDump();
1903
- this.reportFileName = reportFileName(
1904
- opts?.testId || this.page.pageType || "web"
1905
- );
1906
- }
1907
- async getUIContext(action) {
1908
- if (action && (action === "extract" || action === "assert" || action === "captcha")) {
1909
- return await parseContextFromWebPage(this.page, {
1910
- ignoreMarker: true
1911
- });
1912
- }
1913
- return await parseContextFromWebPage(this.page, {
1914
- ignoreMarker: !!(0, import_env2.vlLocateMode)()
1915
- });
1916
- }
1917
- // Helper method to call the insight.captcha method
1918
- async _callInsightCaptcha(options) {
1919
- const context = await this.getUIContext();
1920
- if (this.page.url) {
1921
- const url = await this.page.url();
1922
- context.url = url;
1923
- }
1924
- return this.insight.captcha(context, options);
1925
- }
1926
- async setAIActionContext(prompt) {
1927
- this.opts.aiActionContext = prompt;
1928
- }
1929
- resetDump() {
1930
- this.dump = {
1931
- groupName: this.opts.groupName,
1932
- groupDescription: this.opts.groupDescription,
1933
- executions: []
1934
- };
1935
- return this.dump;
1936
- }
1937
- appendExecutionDump(execution) {
1938
- const currentDump = this.dump;
1939
- currentDump.executions.push(execution);
1940
- }
1941
- dumpDataString() {
1942
- this.dump.groupName = this.opts.groupName;
1943
- this.dump.groupDescription = this.opts.groupDescription;
1944
- return (0, import_utils11.stringifyDumpData)(this.dump);
1945
- }
1946
- reportHTMLString() {
1947
- return (0, import_utils11.reportHTMLContent)(this.dumpDataString());
1948
- }
1949
- writeOutActionDumps() {
1950
- const { generateReport, autoPrintReportMsg } = this.opts;
1951
- this.reportFile = (0, import_utils11.writeLogFile)({
1952
- fileName: this.reportFileName,
1953
- fileExt: import_utils11.groupedActionDumpFileExt,
1954
- fileContent: this.dumpDataString(),
1955
- type: "dump",
1956
- generateReport
1957
- });
1958
- debug4("writeOutActionDumps", this.reportFile);
1959
- if (generateReport && autoPrintReportMsg && this.reportFile) {
1960
- printReportMsg(this.reportFile);
1961
- }
1962
- }
1963
- async callbackOnTaskStartTip(task) {
1964
- const param = paramStr(task);
1965
- const tip = param ? `${typeStr(task)} - ${param}` : typeStr(task);
1966
- if (this.onTaskStartTip) {
1967
- await this.onTaskStartTip(tip);
1968
- }
1969
- }
1970
- afterTaskRunning(executor, doNotThrowError = false) {
1971
- this.appendExecutionDump(executor.dump());
1972
- this.writeOutActionDumps();
1973
- if (executor.isInErrorState() && !doNotThrowError) {
1974
- const errorTask = executor.latestErrorTask();
1975
- throw new Error(`${errorTask?.error}`);
1976
- }
1977
- const lastTask = executor.tasks[executor.tasks.length - 1];
1978
- const allThoughts = executor.tasks.filter((task) => task.thought).map((task) => task.thought);
1979
- const allLocates = executor.tasks.filter((task) => task.locate).map((task) => task.locate);
1980
- const allPlans = executor.tasks.filter((task) => task.param?.plans).map((task) => task.param?.plans);
1981
- const planningTasks = executor.tasks.filter((task) => task.type === "Planning");
1982
- const insightTasks = executor.tasks.filter((task) => task.type === "Insight");
1983
- const actionTasks = executor.tasks.filter((task) => task.type === "Action");
1984
- const planning = planningTasks.length > 0 ? {
1985
- type: "Planning",
1986
- description: `Planning for task execution`,
1987
- steps: planningTasks.map((task) => task.thought || "Planning step")
1988
- } : void 0;
1989
- const insight = insightTasks.length > 0 ? {
1990
- type: "Insight",
1991
- description: `Insight for task execution`,
1992
- elements: insightTasks.map((task) => task.thought || "Insight element")
1993
- } : void 0;
1994
- const action = actionTasks.length > 0 ? {
1995
- type: "Action",
1996
- description: `Action for task execution`,
1997
- result: lastTask?.output
1998
- } : void 0;
1999
- const actionDetails = executor.tasks.map((task) => ({
2000
- type: task.type,
2001
- subType: task.subType,
2002
- status: task.status,
2003
- thought: task.thought
2004
- }));
2005
- const metadata = {
2006
- status: lastTask?.status,
2007
- start: lastTask?.timing?.start,
2008
- end: lastTask?.timing?.end,
2009
- totalTime: lastTask?.timing?.cost,
2010
- cache: lastTask?.cache,
2011
- usage: lastTask?.usage,
2012
- thought: allThoughts.length > 0 ? allThoughts.join("\n") : lastTask?.thought,
2013
- locate: allLocates.length > 0 ? allLocates : lastTask?.locate,
2014
- plan: allPlans.length > 0 ? allPlans : lastTask?.param?.plans,
2015
- // Add planning, insight, and action information
2016
- planning,
2017
- insight,
2018
- action,
2019
- actionDetails,
2020
- // Include raw tasks for debugging
2021
- tasks: executor.tasks.map((task) => ({
2022
- type: task.type,
2023
- subType: task.subType,
2024
- status: task.status,
2025
- thought: task.thought,
2026
- locate: task.locate,
2027
- timing: task.timing,
2028
- usage: task.usage,
2029
- cache: task.cache,
2030
- error: task.error
2031
- }))
2032
- };
2033
- return metadata;
2034
- }
2035
- buildDetailedLocateParam(locatePrompt, opt) {
2036
- (0, import_utils12.assert)(locatePrompt, "missing locate prompt");
2037
- if (typeof opt === "object") {
2038
- const prompt = opt.prompt || locatePrompt;
2039
- const deepThink = opt.deepThink || false;
2040
- const cacheable = opt.cacheable || true;
2041
- return {
2042
- prompt,
2043
- deepThink,
2044
- cacheable
2045
- };
2046
- }
2047
- return {
2048
- prompt: locatePrompt
2049
- };
2050
- }
2051
- async aiTap(locatePrompt, opt) {
2052
- const detailedLocateParam = this.buildDetailedLocateParam(
2053
- locatePrompt,
2054
- opt
2055
- );
2056
- const plans = buildPlans("Tap", detailedLocateParam);
2057
- const { executor, output } = await this.taskExecutor.runPlans(
2058
- taskTitleStr("Tap", locateParamStr(detailedLocateParam)),
2059
- plans
2060
- );
2061
- const metadata = this.afterTaskRunning(executor);
2062
- return {
2063
- result: output,
2064
- metadata
2065
- };
2066
- }
2067
- async aiHover(locatePrompt, opt) {
2068
- const detailedLocateParam = this.buildDetailedLocateParam(
2069
- locatePrompt,
2070
- opt
2071
- );
2072
- const plans = buildPlans("Hover", detailedLocateParam);
2073
- const { executor, output } = await this.taskExecutor.runPlans(
2074
- taskTitleStr("Hover", locateParamStr(detailedLocateParam)),
2075
- plans
2076
- );
2077
- const metadata = this.afterTaskRunning(executor);
2078
- return {
2079
- result: output,
2080
- metadata
2081
- };
2082
- }
2083
- async aiInput(value, locatePrompt, opt) {
2084
- (0, import_utils12.assert)(
2085
- typeof value === "string",
2086
- "input value must be a string, use empty string if you want to clear the input"
2087
- );
2088
- (0, import_utils12.assert)(locatePrompt, "missing locate prompt for input");
2089
- const detailedLocateParam = this.buildDetailedLocateParam(
2090
- locatePrompt,
2091
- opt
2092
- );
2093
- const plans = buildPlans("Input", detailedLocateParam, {
2094
- value
2095
- });
2096
- const { executor, output } = await this.taskExecutor.runPlans(
2097
- taskTitleStr("Input", locateParamStr(detailedLocateParam)),
2098
- plans
2099
- );
2100
- const metadata = this.afterTaskRunning(executor);
2101
- return {
2102
- result: output,
2103
- metadata
2104
- };
2105
- }
2106
- async aiKeyboardPress(keyName, locatePrompt, opt) {
2107
- (0, import_utils12.assert)(keyName, "missing keyName for keyboard press");
2108
- const detailedLocateParam = locatePrompt ? this.buildDetailedLocateParam(locatePrompt, opt) : void 0;
2109
- const plans = buildPlans("KeyboardPress", detailedLocateParam, {
2110
- value: keyName
2111
- });
2112
- const { executor, output } = await this.taskExecutor.runPlans(
2113
- taskTitleStr("KeyboardPress", locateParamStr(detailedLocateParam)),
2114
- plans
2115
- );
2116
- const metadata = this.afterTaskRunning(executor);
2117
- return {
2118
- result: output,
2119
- metadata
2120
- };
2121
- }
2122
- async aiScroll(scrollParam, locatePrompt, opt) {
2123
- const detailedLocateParam = locatePrompt ? this.buildDetailedLocateParam(locatePrompt, opt) : void 0;
2124
- const plans = buildPlans("Scroll", detailedLocateParam, scrollParam);
2125
- const paramInTitle = locatePrompt ? `${locateParamStr(detailedLocateParam)} - ${scrollParamStr(scrollParam)}` : scrollParamStr(scrollParam);
2126
- const { executor, output } = await this.taskExecutor.runPlans(
2127
- taskTitleStr("Scroll", paramInTitle),
2128
- plans
2129
- );
2130
- const metadata = this.afterTaskRunning(executor);
2131
- return {
2132
- result: output,
2133
- metadata
2134
- };
2135
- }
2136
- async aiAction(taskPrompt, opt) {
2137
- const cacheable = opt?.cacheable;
2138
- const isVlmUiTars = (0, import_env2.vlLocateMode)() === "vlm-ui-tars";
2139
- const matchedCache = isVlmUiTars || cacheable === false ? void 0 : this.taskCache?.matchPlanCache(taskPrompt);
2140
- if (matchedCache && this.taskCache?.isCacheResultUsed) {
2141
- const { executor: executor2 } = await this.taskExecutor.loadYamlFlowAsPlanning(
2142
- taskPrompt,
2143
- matchedCache.cacheContent?.yamlWorkflow
2144
- );
2145
- const metadata2 = this.afterTaskRunning(executor2);
2146
- debug4("matched cache, will call .runYaml to run the action");
2147
- const yaml5 = matchedCache.cacheContent?.yamlWorkflow;
2148
- const result = await this.runYaml(yaml5);
2149
- return {
2150
- result: result.result,
2151
- metadata: metadata2
2152
- };
2153
- }
2154
- const { output, executor } = await (isVlmUiTars ? this.taskExecutor.actionToGoal(taskPrompt) : this.taskExecutor.action(taskPrompt, this.opts.aiActionContext));
2155
- if (this.taskCache && output?.yamlFlow && cacheable !== false) {
2156
- const yamlContent = {
2157
- tasks: [
2158
- {
2159
- name: taskPrompt,
2160
- flow: output.yamlFlow
2161
- }
2162
- ]
2163
- };
2164
- const yamlFlowStr = import_js_yaml4.default.dump(yamlContent);
2165
- this.taskCache.updateOrAppendCacheRecord(
2166
- {
2167
- type: "plan",
2168
- prompt: taskPrompt,
2169
- yamlWorkflow: yamlFlowStr
2170
- },
2171
- matchedCache
2172
- );
2173
- }
2174
- const metadata = this.afterTaskRunning(executor);
2175
- return {
2176
- result: output,
2177
- metadata
2178
- };
2179
- }
2180
- async aiQuery(demand) {
2181
- const { output, executor } = await this.taskExecutor.query(demand);
2182
- const metadata = this.afterTaskRunning(executor);
2183
- return {
2184
- result: output,
2185
- metadata
2186
- };
2187
- }
2188
- async aiBoolean(prompt) {
2189
- const { output, executor } = await this.taskExecutor.boolean(prompt);
2190
- const metadata = this.afterTaskRunning(executor);
2191
- return {
2192
- result: output,
2193
- metadata
2194
- };
2195
- }
2196
- async aiNumber(prompt) {
2197
- const { output, executor } = await this.taskExecutor.number(prompt);
2198
- const metadata = this.afterTaskRunning(executor);
2199
- return {
2200
- result: output,
2201
- metadata
2202
- };
2203
- }
2204
- async aiString(prompt) {
2205
- const { output, executor } = await this.taskExecutor.string(prompt);
2206
- const metadata = this.afterTaskRunning(executor);
2207
- return {
2208
- result: output,
2209
- metadata
2210
- };
2211
- }
2212
- async describeElementAtPoint(center, opt) {
2213
- const { verifyPrompt = true, retryLimit = 3 } = opt || {};
2214
- let success = false;
2215
- let retryCount = 0;
2216
- let resultPrompt = "";
2217
- let deepThink = opt?.deepThink || false;
2218
- let verifyResult;
2219
- while (!success && retryCount < retryLimit) {
2220
- if (retryCount >= 2) {
2221
- deepThink = true;
2222
- }
2223
- debug4(
2224
- "aiDescribe",
2225
- center,
2226
- "verifyPrompt",
2227
- verifyPrompt,
2228
- "retryCount",
2229
- retryCount,
2230
- "deepThink",
2231
- deepThink
2232
- );
2233
- const text = await this.insight.describe(center, { deepThink });
2234
- debug4("aiDescribe text", text);
2235
- (0, import_utils12.assert)(text.description, `failed to describe element at [${center}]`);
2236
- resultPrompt = text.description;
2237
- verifyResult = await this.verifyLocator(
2238
- resultPrompt,
2239
- deepThink ? { deepThink: true } : void 0,
2240
- center,
2241
- opt
2242
- );
2243
- if (verifyResult.pass) {
2244
- success = true;
2245
- } else {
2246
- retryCount++;
2247
- }
2248
- }
2249
- return {
2250
- prompt: resultPrompt,
2251
- deepThink,
2252
- verifyResult
2253
- };
2254
- }
2255
- async verifyLocator(prompt, locateOpt, expectCenter, verifyLocateOption) {
2256
- debug4("verifyLocator", prompt, locateOpt, expectCenter, verifyLocateOption);
2257
- const locateResult = await this.aiLocate(prompt, locateOpt);
2258
- const { center: verifyCenter, rect: verifyRect } = locateResult.result;
2259
- const distance = distanceOfTwoPoints(expectCenter, verifyCenter);
2260
- const included = includedInRect(expectCenter, verifyRect);
2261
- const pass = distance <= (verifyLocateOption?.centerDistanceThreshold || 20) || included;
2262
- const verifyResult = {
2263
- pass,
2264
- rect: verifyRect,
2265
- center: verifyCenter,
2266
- centerDistance: distance
2267
- };
2268
- debug4("aiDescribe verifyResult", verifyResult);
2269
- return verifyResult;
2270
- }
2271
- async aiLocate(prompt, opt) {
2272
- const detailedLocateParam = this.buildDetailedLocateParam(prompt, opt);
2273
- const plans = buildPlans("Locate", detailedLocateParam);
2274
- const { executor, output } = await this.taskExecutor.runPlans(
2275
- taskTitleStr("Locate", locateParamStr(detailedLocateParam)),
2276
- plans
2277
- );
2278
- const metadata = this.afterTaskRunning(executor);
2279
- const { element } = output;
2280
- const result = {
2281
- rect: element?.rect,
2282
- center: element?.center
2283
- };
2284
- return {
2285
- result,
2286
- metadata
2287
- };
2288
- }
2289
- async aiAssert(assertion, msg, opt) {
2290
- let currentUrl = "";
2291
- if (this.page.url) {
2292
- try {
2293
- currentUrl = await this.page.url();
2294
- } catch (e) {
2295
- }
2296
- }
2297
- const assertionWithContext = currentUrl ? `For the page at URL "${currentUrl}", ${assertion}` : assertion;
2298
- const { output, executor } = await this.taskExecutor.assert(assertionWithContext);
2299
- const metadata = this.afterTaskRunning(executor, true);
2300
- if (output && opt?.keepRawResponse) {
2301
- return {
2302
- result: output,
2303
- metadata
2304
- };
2305
- }
2306
- if (!output?.pass) {
2307
- const errMsg = msg || `Assertion failed: ${assertion}`;
2308
- const reasonMsg = `Reason: ${output?.thought || executor.latestErrorTask()?.error || "(no_reason)"}`;
2309
- throw new Error(`${errMsg}
2310
- ${reasonMsg}`);
2311
- }
2312
- return {
2313
- result: true,
2314
- metadata
2315
- };
2316
- }
2317
- async aiCaptcha(options) {
2318
- const { deepThink = false, autoDetectComplexity = true } = options || {};
2319
- let shouldUseDeepThink = deepThink;
2320
- if (autoDetectComplexity && !deepThink) {
2321
- const context = await this.getUIContext();
2322
- const { screenshotBase64 } = context;
2323
- try {
2324
- const complexityAnalysisPrompt = `
2325
- Analyze this screenshot and determine if it contains a complex CAPTCHA that would benefit from deep thinking.
2326
- A complex CAPTCHA typically has one or more of these characteristics:
2327
- - Distorted or overlapping text that is hard to read
2328
- - Multiple images that need to be selected based on a specific criteria
2329
- - Puzzles that require spatial reasoning
2330
- - Multiple steps or verification methods
2331
- - Small or hard-to-distinguish elements
2332
-
2333
- Return only "complex" or "simple" based on your analysis.
2334
- `;
2335
- const complexityMsgs = [
2336
- { role: "system", content: "You are an AI assistant that analyzes screenshots to determine CAPTCHA complexity." },
2337
- {
2338
- role: "user",
2339
- content: [
2340
- {
2341
- type: "image_url",
2342
- image_url: {
2343
- url: screenshotBase64,
2344
- detail: "high"
2345
- }
2346
- },
2347
- {
2348
- type: "text",
2349
- text: complexityAnalysisPrompt
2350
- }
2351
- ]
2352
- }
2353
- ];
2354
- const complexityResult = await this.insight.aiVendorFn(
2355
- complexityMsgs,
2356
- { type: "extract_data" }
2357
- );
2358
- const responseText = typeof complexityResult.content === "string" ? complexityResult.content.toLowerCase() : JSON.stringify(complexityResult.content).toLowerCase();
2359
- shouldUseDeepThink = responseText.includes("complex");
2360
- debug4("CAPTCHA complexity analysis:", responseText, "Using deep think:", shouldUseDeepThink);
2361
- } catch (error) {
2362
- debug4("Failed to analyze CAPTCHA complexity:", error);
2363
- }
2364
- }
2365
- const captchaResponse = await this._callInsightCaptcha({
2366
- deepThink: shouldUseDeepThink
2367
- });
2368
- const captchaResult = captchaResponse.content;
2369
- const usage = captchaResponse.usage;
2370
- const actualDeepThink = captchaResponse.deepThink || false;
2371
- if (captchaResult.captchaType === "text") {
2372
- for (const action of captchaResult.actions) {
2373
- if (action.type === "click" && action.target) {
2374
- await this.aiTap(action.target, { deepThink: shouldUseDeepThink });
2375
- } else if (action.type === "input" && action.value) {
2376
- if (action.target) {
2377
- await this.aiInput(action.value, action.target, { deepThink: shouldUseDeepThink });
2378
- }
2379
- } else if (action.type === "verify" && action.target) {
2380
- await this.aiTap(action.target, { deepThink: shouldUseDeepThink });
2381
- }
2382
- }
2383
- } else if (captchaResult.captchaType === "image") {
2384
- for (const action of captchaResult.actions) {
2385
- if (action.type === "click") {
2386
- if (action.coordinates) {
2387
- const x = action.coordinates[0];
2388
- const y = action.coordinates[1];
2389
- await this.aiTap(`element at coordinates (${x}, ${y})`, { deepThink: shouldUseDeepThink });
2390
- } else if (action.target) {
2391
- await this.aiTap(action.target, { deepThink: shouldUseDeepThink });
2392
- }
2393
- } else if (action.type === "verify" && action.target) {
2394
- await this.aiTap(action.target, { deepThink: shouldUseDeepThink });
2395
- }
2396
- }
2397
- }
2398
- await new Promise((resolve2) => setTimeout(resolve2, 3e3));
2399
- const metadata = {
2400
- status: "finished",
2401
- usage,
2402
- thought: captchaResult.thought
2403
- };
2404
- metadata.deepThink = actualDeepThink;
2405
- if (autoDetectComplexity && !deepThink) {
2406
- metadata.autoDetectedComplexity = shouldUseDeepThink;
2407
- }
2408
- return {
2409
- result: captchaResult,
2410
- metadata
2411
- };
2412
- }
2413
- async aiWaitFor(assertion, opt) {
2414
- const startTime = Date.now();
2415
- const { executor } = await this.taskExecutor.waitFor(assertion, {
2416
- timeoutMs: opt?.timeoutMs || 15 * 1e3,
2417
- checkIntervalMs: opt?.checkIntervalMs || 3 * 1e3,
2418
- assertion
2419
- });
2420
- const metadata = {
2421
- status: executor.isInErrorState() ? "failed" : "finished",
2422
- start: startTime,
2423
- end: Date.now(),
2424
- totalTime: Date.now() - startTime,
2425
- thought: executor.latestErrorTask()?.thought,
2426
- actionDetails: executor.tasks.map((task) => ({
2427
- type: task.type,
2428
- subType: task.subType,
2429
- status: task.status,
2430
- thought: task.thought
2431
- }))
2432
- };
2433
- this.appendExecutionDump(executor.dump());
2434
- this.writeOutActionDumps();
2435
- if (executor.isInErrorState()) {
2436
- const errorTask = executor.latestErrorTask();
2437
- throw new Error(`${errorTask?.error}
2438
- ${errorTask?.errorStack}`);
2439
- }
2440
- return {
2441
- result: true,
2442
- // Successfully waited
2443
- metadata
2444
- };
2445
- }
2446
- async ai(taskPrompt, type = "action", options) {
2447
- if (type === "action") {
2448
- return this.aiAction(taskPrompt);
2449
- }
2450
- if (type === "query") {
2451
- return this.aiQuery(taskPrompt);
2452
- }
2453
- if (type === "assert") {
2454
- return this.aiAssert(taskPrompt);
2455
- }
2456
- if (type === "tap") {
2457
- return this.aiTap(taskPrompt, options);
2458
- }
2459
- if (type === "captcha") {
2460
- return this.aiCaptcha(options);
2461
- }
2462
- throw new Error(
2463
- `Unknown type: ${type}, only support 'action', 'query', 'assert', 'tap', 'captcha'`
2464
- );
2465
- }
2466
- async runYaml(yamlScriptContent) {
2467
- const startTime = Date.now();
2468
- const script = parseYamlScript(yamlScriptContent, "yaml", true);
2469
- const player = new ScriptPlayer(script, async () => {
2470
- return { agent: this, freeFn: [] };
2471
- });
2472
- await player.run();
2473
- const endTime = Date.now();
2474
- const metadata = {
2475
- status: player.status,
2476
- start: startTime,
2477
- end: endTime,
2478
- totalTime: endTime - startTime,
2479
- tasks: player.taskStatusList.map((task) => ({
2480
- type: "yaml-task",
2481
- subType: task.name,
2482
- status: task.status,
2483
- error: task.error?.message
2484
- }))
2485
- };
2486
- if (player.status === "error") {
2487
- const errors = player.taskStatusList.filter((task) => task.status === "error").map((task) => {
2488
- return `task - ${task.name}: ${task.error?.message}`;
2489
- }).join("\n");
2490
- throw new Error(`Error(s) occurred in running yaml script:
2491
- ${errors}`);
2492
- }
2493
- return {
2494
- result: player.result,
2495
- metadata
2496
- };
2497
- }
2498
- async evaluateJavaScript(script) {
2499
- (0, import_utils12.assert)(
2500
- this.page.evaluateJavaScript,
2501
- "evaluateJavaScript is not supported in current agent"
2502
- );
2503
- if (this.page.evaluateJavaScript) {
2504
- return this.page.evaluateJavaScript(script);
2505
- }
2506
- throw new Error("evaluateJavaScript is not supported in current agent");
2507
- }
2508
- async destroy() {
2509
- await this.page.destroy();
2510
- }
2511
- };
2512
-
2513
- // src/chrome-extension/agent.ts
2514
- var ChromeExtensionProxyPageAgent = class extends PageAgent {
2515
- // biome-ignore lint/complexity/noUselessConstructor: <explanation>
2516
- constructor(page, opts) {
2517
- super(page, opts);
2518
- }
2519
- };
2520
-
2521
- // src/chrome-extension/page.ts
2522
- var import_extractor2 = require("misoai-shared/extractor");
2523
- var import_utils17 = require("misoai-shared/utils");
2524
-
2525
- // src/chrome-extension/cdpInput.ts
2526
- var import_keyboard_layout = require("misoai-shared/keyboard-layout");
2527
- var import_utils15 = require("misoai-shared/utils");
2528
- var _pressedKeys, _client, _modifierBit, modifierBit_fn, _keyDescriptionForString, keyDescriptionForString_fn;
2529
- var CdpKeyboard = class {
2530
- constructor(client) {
2531
- __privateAdd(this, _modifierBit);
2532
- __privateAdd(this, _keyDescriptionForString);
2533
- __privateAdd(this, _pressedKeys, /* @__PURE__ */ new Set());
2534
- __privateAdd(this, _client, void 0);
2535
- this._modifiers = 0;
2536
- __privateSet(this, _client, client);
2537
- }
2538
- updateClient(client) {
2539
- __privateSet(this, _client, client);
2540
- }
2541
- async down(key, options = {
2542
- text: void 0,
2543
- commands: []
2544
- }) {
2545
- const description = __privateMethod(this, _keyDescriptionForString, keyDescriptionForString_fn).call(this, key);
2546
- const autoRepeat = __privateGet(this, _pressedKeys).has(description.code);
2547
- __privateGet(this, _pressedKeys).add(description.code);
2548
- this._modifiers |= __privateMethod(this, _modifierBit, modifierBit_fn).call(this, description.key);
2549
- const text = options.text === void 0 ? description.text : options.text;
2550
- await __privateGet(this, _client).send("Input.dispatchKeyEvent", {
2551
- type: text ? "keyDown" : "rawKeyDown",
2552
- modifiers: this._modifiers,
2553
- windowsVirtualKeyCode: description.keyCode,
2554
- code: description.code,
2555
- key: description.key,
2556
- text,
2557
- unmodifiedText: text,
2558
- autoRepeat,
2559
- location: description.location,
2560
- isKeypad: description.location === 3,
2561
- commands: options.commands
2562
- });
2563
- }
2564
- async up(key) {
2565
- const description = __privateMethod(this, _keyDescriptionForString, keyDescriptionForString_fn).call(this, key);
2566
- this._modifiers &= ~__privateMethod(this, _modifierBit, modifierBit_fn).call(this, description.key);
2567
- __privateGet(this, _pressedKeys).delete(description.code);
2568
- await __privateGet(this, _client).send("Input.dispatchKeyEvent", {
2569
- type: "keyUp",
2570
- modifiers: this._modifiers,
2571
- key: description.key,
2572
- windowsVirtualKeyCode: description.keyCode,
2573
- code: description.code,
2574
- location: description.location
2575
- });
2576
- }
2577
- async sendCharacter(char) {
2578
- await __privateGet(this, _client).send("Input.insertText", { text: char });
2579
- }
2580
- charIsKey(char) {
2581
- return !!import_keyboard_layout._keyDefinitions[char];
2582
- }
2583
- async type(text, options = {}) {
2584
- const delay = options.delay || void 0;
2585
- for (const char of text) {
2586
- if (this.charIsKey(char)) {
2587
- await this.press(char, { delay });
2588
- } else {
2589
- if (delay) {
2590
- await new Promise((f) => {
2591
- return setTimeout(f, delay);
2592
- });
2593
- }
2594
- await this.sendCharacter(char);
2595
- }
2596
- }
2597
- }
2598
- async press(key, options = {}) {
2599
- const { delay = null } = options;
2600
- const keys = Array.isArray(key) ? key : [key];
2601
- for (const k of keys) {
2602
- await this.down(k, options);
2603
- }
2604
- if (delay) {
2605
- await new Promise((f) => {
2606
- return setTimeout(f, options.delay);
2607
- });
2608
- }
2609
- for (const k of [...keys].reverse()) {
2610
- await this.up(k);
2611
- }
2612
- }
2613
- };
2614
- _pressedKeys = new WeakMap();
2615
- _client = new WeakMap();
2616
- _modifierBit = new WeakSet();
2617
- modifierBit_fn = function(key) {
2618
- if (key === "Alt") {
2619
- return 1;
2620
- }
2621
- if (key === "Control") {
2622
- return 2;
2623
- }
2624
- if (key === "Meta") {
2625
- return 4;
2626
- }
2627
- if (key === "Shift") {
2628
- return 8;
2629
- }
2630
- return 0;
2631
- };
2632
- _keyDescriptionForString = new WeakSet();
2633
- keyDescriptionForString_fn = function(keyString) {
2634
- const shift = this._modifiers & 8;
2635
- const description = {
2636
- key: "",
2637
- keyCode: 0,
2638
- code: "",
2639
- text: "",
2640
- location: 0
2641
- };
2642
- const definition = import_keyboard_layout._keyDefinitions[keyString];
2643
- (0, import_utils15.assert)(definition, `Unknown key: "${keyString}"`);
2644
- if (definition.key) {
2645
- description.key = definition.key;
2646
- }
2647
- if (shift && definition.shiftKey) {
2648
- description.key = definition.shiftKey;
2649
- }
2650
- if (definition.keyCode) {
2651
- description.keyCode = definition.keyCode;
2652
- }
2653
- if (shift && definition.shiftKeyCode) {
2654
- description.keyCode = definition.shiftKeyCode;
2655
- }
2656
- if (definition.code) {
2657
- description.code = definition.code;
2658
- }
2659
- if (definition.location) {
2660
- description.location = definition.location;
2661
- }
2662
- if (description.key.length === 1) {
2663
- description.text = description.key;
2664
- }
2665
- if (definition.text) {
2666
- description.text = definition.text;
2667
- }
2668
- if (shift && definition.shiftText) {
2669
- description.text = definition.shiftText;
2670
- }
2671
- if (this._modifiers & ~8) {
2672
- description.text = "";
2673
- }
2674
- return description;
2675
- };
2676
-
2677
- // src/chrome-extension/dynamic-scripts.ts
2678
- var import_node_fs3 = __toESM(require("fs"));
2679
- var import_utils16 = require("misoai-shared/utils");
2680
- var scriptFileContentCache = null;
2681
- var getHtmlElementScript = async () => {
2682
- const scriptFileToRetrieve = chrome.runtime.getURL("scripts/htmlElement.js");
2683
- if (scriptFileContentCache)
2684
- return scriptFileContentCache;
2685
- if (import_utils16.ifInBrowser) {
2686
- const script = await fetch(scriptFileToRetrieve);
2687
- scriptFileContentCache = await script.text();
2688
- return scriptFileContentCache;
2689
- }
2690
- return import_node_fs3.default.readFileSync(scriptFileToRetrieve, "utf8");
2691
- };
2692
- var waterFlowScriptFileContentCache = null;
2693
- var injectWaterFlowAnimation = async () => {
2694
- const waterFlowScriptFileToRetrieve = chrome.runtime.getURL(
2695
- "scripts/water-flow.js"
2696
- );
2697
- if (waterFlowScriptFileContentCache)
2698
- return waterFlowScriptFileContentCache;
2699
- if (import_utils16.ifInBrowser) {
2700
- const script = await fetch(waterFlowScriptFileToRetrieve);
2701
- waterFlowScriptFileContentCache = await script.text();
2702
- return waterFlowScriptFileContentCache;
2703
- }
2704
- return import_node_fs3.default.readFileSync(waterFlowScriptFileToRetrieve, "utf8");
2705
- };
2706
- var stopWaterFlowScriptFileContentCache = null;
2707
- var injectStopWaterFlowAnimation = async () => {
2708
- const stopWaterFlowScriptFileToRetrieve = chrome.runtime.getURL(
2709
- "scripts/stop-water-flow.js"
2710
- );
2711
- if (stopWaterFlowScriptFileContentCache)
2712
- return stopWaterFlowScriptFileContentCache;
2713
- if (import_utils16.ifInBrowser) {
2714
- const script = await fetch(stopWaterFlowScriptFileToRetrieve);
2715
- stopWaterFlowScriptFileContentCache = await script.text();
2716
- return stopWaterFlowScriptFileContentCache;
2717
- }
2718
- return import_node_fs3.default.readFileSync(stopWaterFlowScriptFileToRetrieve, "utf8");
2719
- };
2720
-
2721
- // src/chrome-extension/page.ts
2722
- function sleep2(ms) {
2723
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2724
- }
2725
- var ChromeExtensionProxyPage = class {
2726
- constructor(forceSameTabNavigation) {
2727
- this.pageType = "chrome-extension-proxy";
2728
- this.version = "1.0.2";
2729
- this.activeTabId = null;
2730
- this.tabIdOfDebuggerAttached = null;
2731
- this.attachingDebugger = null;
2732
- this.destroyed = false;
2733
- this.latestMouseX = 100;
2734
- this.latestMouseY = 100;
2735
- this.mouse = {
2736
- click: async (x, y) => {
2737
- await this.mouse.move(x, y);
2738
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2739
- type: "mousePressed",
2740
- x,
2741
- y,
2742
- button: "left",
2743
- clickCount: 1
2744
- });
2745
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2746
- type: "mouseReleased",
2747
- x,
2748
- y,
2749
- button: "left",
2750
- clickCount: 1
2751
- });
2752
- },
2753
- wheel: async (deltaX, deltaY, startX, startY) => {
2754
- const finalX = startX || this.latestMouseX;
2755
- const finalY = startY || this.latestMouseY;
2756
- await this.showMousePointer(finalX, finalY);
2757
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2758
- type: "mouseWheel",
2759
- x: finalX,
2760
- y: finalY,
2761
- deltaX,
2762
- deltaY
2763
- });
2764
- this.latestMouseX = finalX;
2765
- this.latestMouseY = finalY;
2766
- },
2767
- move: async (x, y) => {
2768
- await this.showMousePointer(x, y);
2769
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2770
- type: "mouseMoved",
2771
- x,
2772
- y
2773
- });
2774
- this.latestMouseX = x;
2775
- this.latestMouseY = y;
2776
- },
2777
- drag: async (from, to) => {
2778
- await this.mouse.move(from.x, from.y);
2779
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2780
- type: "mousePressed",
2781
- x: from.x,
2782
- y: from.y,
2783
- button: "left",
2784
- clickCount: 1
2785
- });
2786
- await this.mouse.move(to.x, to.y);
2787
- await this.sendCommandToDebugger("Input.dispatchMouseEvent", {
2788
- type: "mouseReleased",
2789
- x: to.x,
2790
- y: to.y,
2791
- button: "left",
2792
- clickCount: 1
2793
- });
2794
- }
2795
- };
2796
- this.keyboard = {
2797
- type: async (text) => {
2798
- const cdpKeyboard = new CdpKeyboard({
2799
- send: this.sendCommandToDebugger.bind(this)
2800
- });
2801
- await cdpKeyboard.type(text, { delay: 0 });
2802
- },
2803
- press: async (action) => {
2804
- const cdpKeyboard = new CdpKeyboard({
2805
- send: this.sendCommandToDebugger.bind(this)
2806
- });
2807
- const keys = Array.isArray(action) ? action : [action];
2808
- for (const k of keys) {
2809
- const commands = k.command ? [k.command] : [];
2810
- await cdpKeyboard.down(k.key, { commands });
2811
- }
2812
- for (const k of [...keys].reverse()) {
2813
- await cdpKeyboard.up(k.key);
2814
- }
2815
- }
2816
- };
2817
- this.forceSameTabNavigation = forceSameTabNavigation;
2818
- }
2819
- async setActiveTabId(tabId) {
2820
- if (this.activeTabId) {
2821
- throw new Error(
2822
- `Active tab id is already set, which is ${this.activeTabId}, cannot set it to ${tabId}`
2823
- );
2824
- }
2825
- await chrome.tabs.update(tabId, { active: true });
2826
- this.activeTabId = tabId;
2827
- }
2828
- async getActiveTabId() {
2829
- return this.activeTabId;
2830
- }
2831
- /**
2832
- * Get a list of current tabs
2833
- * @returns {Promise<Array<{id: number, title: string, url: string}>>}
2834
- */
2835
- async getBrowserTabList() {
2836
- const tabs = await chrome.tabs.query({ currentWindow: true });
2837
- return tabs.map((tab) => ({
2838
- id: `${tab.id}`,
2839
- title: tab.title,
2840
- url: tab.url,
2841
- currentActiveTab: tab.active
2842
- })).filter((tab) => tab.id && tab.title && tab.url);
2843
- }
2844
- async getTabIdOrConnectToCurrentTab() {
2845
- if (this.activeTabId) {
2846
- return this.activeTabId;
2847
- }
2848
- const tabId = await chrome.tabs.query({ active: true, currentWindow: true }).then((tabs) => tabs[0]?.id);
2849
- this.activeTabId = tabId || 0;
2850
- return this.activeTabId;
2851
- }
2852
- async attachDebugger() {
2853
- (0, import_utils17.assert)(!this.destroyed, "Page is destroyed");
2854
- if (this.attachingDebugger) {
2855
- await this.attachingDebugger;
2856
- return;
2857
- }
2858
- this.attachingDebugger = (async () => {
2859
- const url = await this.url();
2860
- let error = null;
2861
- if (url.startsWith("chrome://")) {
2862
- throw new Error(
2863
- "Cannot attach debugger to chrome:// pages, please use Midscene in a normal page with http://, https:// or file://"
2864
- );
2865
- }
2866
- try {
2867
- const currentTabId = await this.getTabIdOrConnectToCurrentTab();
2868
- if (this.tabIdOfDebuggerAttached === currentTabId) {
2869
- return;
2870
- }
2871
- if (this.tabIdOfDebuggerAttached && this.tabIdOfDebuggerAttached !== currentTabId) {
2872
- console.log(
2873
- "detach the previous tab",
2874
- this.tabIdOfDebuggerAttached,
2875
- "->",
2876
- currentTabId
2877
- );
2878
- try {
2879
- await this.detachDebugger(this.tabIdOfDebuggerAttached);
2880
- } catch (error2) {
2881
- console.error("Failed to detach debugger", error2);
2882
- }
2883
- }
2884
- console.log("attaching debugger", currentTabId);
2885
- await chrome.debugger.attach({ tabId: currentTabId }, "1.3");
2886
- await sleep2(500);
2887
- this.tabIdOfDebuggerAttached = currentTabId;
2888
- await this.enableWaterFlowAnimation();
2889
- } catch (e) {
2890
- console.error("Failed to attach debugger", e);
2891
- error = e;
2892
- } finally {
2893
- this.attachingDebugger = null;
2894
- }
2895
- if (error) {
2896
- throw error;
2897
- }
2898
- })();
2899
- await this.attachingDebugger;
2900
- }
2901
- async showMousePointer(x, y) {
2902
- const pointerScript = `(() => {
2903
- if(typeof window.midsceneWaterFlowAnimation !== 'undefined') {
2904
- window.midsceneWaterFlowAnimation.enable();
2905
- window.midsceneWaterFlowAnimation.showMousePointer(${x}, ${y});
2906
- } else {
2907
- console.log('midsceneWaterFlowAnimation is not defined');
2908
- }
2909
- })()`;
2910
- await this.sendCommandToDebugger("Runtime.evaluate", {
2911
- expression: `${pointerScript}`
2912
- });
2913
- }
2914
- async hideMousePointer() {
2915
- await this.sendCommandToDebugger("Runtime.evaluate", {
2916
- expression: `(() => {
2917
- if(typeof window.midsceneWaterFlowAnimation !== 'undefined') {
2918
- window.midsceneWaterFlowAnimation.hideMousePointer();
2919
- }
2920
- })()`
2921
- });
2922
- }
2923
- async detachDebugger(tabId) {
2924
- const tabIdToDetach = tabId || this.tabIdOfDebuggerAttached;
2925
- console.log("detaching debugger", tabIdToDetach);
2926
- if (!tabIdToDetach) {
2927
- console.warn("No tab id to detach");
2928
- return;
2929
- }
2930
- try {
2931
- await this.disableWaterFlowAnimation(tabIdToDetach);
2932
- await sleep2(200);
2933
- } catch (error) {
2934
- console.warn("Failed to disable water flow animation", error);
2935
- }
2936
- try {
2937
- await chrome.debugger.detach({ tabId: tabIdToDetach });
2938
- } catch (error) {
2939
- console.warn("Failed to detach debugger", error);
2940
- }
2941
- this.tabIdOfDebuggerAttached = null;
2942
- }
2943
- async enableWaterFlowAnimation() {
2944
- if (this.forceSameTabNavigation) {
2945
- await chrome.debugger.sendCommand(
2946
- { tabId: this.tabIdOfDebuggerAttached },
2947
- "Runtime.evaluate",
2948
- {
2949
- expression: limitOpenNewTabScript
2950
- }
2951
- );
2952
- }
2953
- const script = await injectWaterFlowAnimation();
2954
- await chrome.debugger.sendCommand(
2955
- { tabId: this.tabIdOfDebuggerAttached },
2956
- "Runtime.evaluate",
2957
- {
2958
- expression: script
2959
- }
2960
- );
2961
- }
2962
- async disableWaterFlowAnimation(tabId) {
2963
- const script = await injectStopWaterFlowAnimation();
2964
- await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", {
2965
- expression: script
2966
- });
2967
- }
2968
- async sendCommandToDebugger(command, params) {
2969
- await this.attachDebugger();
2970
- (0, import_utils17.assert)(this.tabIdOfDebuggerAttached, "Debugger is not attached");
2971
- this.enableWaterFlowAnimation();
2972
- return await chrome.debugger.sendCommand(
2973
- { tabId: this.tabIdOfDebuggerAttached },
2974
- command,
2975
- params
2976
- );
2977
- }
2978
- async getPageContentByCDP() {
2979
- const script = await getHtmlElementScript();
2980
- await this.sendCommandToDebugger("Runtime.evaluate", {
2981
- expression: script
2982
- });
2983
- const expression = () => {
2984
- return {
2985
- tree: window.midscene_element_inspector.webExtractNodeTree(),
2986
- size: {
2987
- width: document.documentElement.clientWidth,
2988
- height: document.documentElement.clientHeight,
2989
- dpr: window.devicePixelRatio
2990
- }
2991
- };
2992
- };
2993
- const returnValue = await this.sendCommandToDebugger("Runtime.evaluate", {
2994
- expression: `(${expression.toString()})()`,
2995
- returnByValue: true
2996
- });
2997
- if (!returnValue.result.value) {
2998
- const errorDescription = returnValue.exceptionDetails?.exception?.description || "";
2999
- if (!errorDescription) {
3000
- console.error("returnValue from cdp", returnValue);
3001
- }
3002
- throw new Error(
3003
- `Failed to get page content from page, error: ${errorDescription}`
3004
- );
3005
- }
3006
- return returnValue.result.value;
3007
- }
3008
- async evaluateJavaScript(script) {
3009
- return this.sendCommandToDebugger("Runtime.evaluate", {
3010
- expression: script
3011
- });
3012
- }
3013
- // current implementation is wait until domReadyState is complete
3014
- async waitUntilNetworkIdle() {
3015
- const timeout = 1e4;
3016
- const startTime = Date.now();
3017
- let lastReadyState = "";
3018
- while (Date.now() - startTime < timeout) {
3019
- const result = await this.sendCommandToDebugger("Runtime.evaluate", {
3020
- expression: "document.readyState"
3021
- });
3022
- lastReadyState = result.result.value;
3023
- if (lastReadyState === "complete") {
3024
- await new Promise((resolve2) => setTimeout(resolve2, 300));
3025
- return;
3026
- }
3027
- await new Promise((resolve2) => setTimeout(resolve2, 300));
3028
- }
3029
- throw new Error(
3030
- `Failed to wait until network idle, last readyState: ${lastReadyState}`
3031
- );
3032
- }
3033
- async getElementsInfo() {
3034
- const tree = await this.getElementsNodeTree();
3035
- return (0, import_extractor2.treeToList)(tree);
3036
- }
3037
- async getElementsNodeTree() {
3038
- await this.hideMousePointer();
3039
- const content = await this.getPageContentByCDP();
3040
- if (content?.size) {
3041
- this.viewportSize = content.size;
3042
- }
3043
- return content?.tree || { node: null, children: [] };
3044
- }
3045
- async size() {
3046
- if (this.viewportSize)
3047
- return this.viewportSize;
3048
- const content = await this.getPageContentByCDP();
3049
- return content.size;
3050
- }
3051
- async screenshotBase64() {
3052
- await this.hideMousePointer();
3053
- const base64 = await this.sendCommandToDebugger("Page.captureScreenshot", {
3054
- format: "jpeg",
3055
- quality: 90
3056
- });
3057
- return `data:image/jpeg;base64,${base64.data}`;
3058
- }
3059
- async url() {
3060
- const tabId = await this.getTabIdOrConnectToCurrentTab();
3061
- const url = await chrome.tabs.get(tabId).then((tab) => tab.url);
3062
- return url || "";
3063
- }
3064
- async scrollUntilTop(startingPoint) {
3065
- if (startingPoint) {
3066
- await this.mouse.move(startingPoint.left, startingPoint.top);
3067
- }
3068
- return this.mouse.wheel(0, -9999999);
3069
- }
3070
- async scrollUntilBottom(startingPoint) {
3071
- if (startingPoint) {
3072
- await this.mouse.move(startingPoint.left, startingPoint.top);
3073
- }
3074
- return this.mouse.wheel(0, 9999999);
3075
- }
3076
- async scrollUntilLeft(startingPoint) {
3077
- if (startingPoint) {
3078
- await this.mouse.move(startingPoint.left, startingPoint.top);
3079
- }
3080
- return this.mouse.wheel(-9999999, 0);
3081
- }
3082
- async scrollUntilRight(startingPoint) {
3083
- if (startingPoint) {
3084
- await this.mouse.move(startingPoint.left, startingPoint.top);
3085
- }
3086
- return this.mouse.wheel(9999999, 0);
3087
- }
3088
- async scrollUp(distance, startingPoint) {
3089
- const { height } = await this.size();
3090
- const scrollDistance = distance || height * 0.7;
3091
- return this.mouse.wheel(
3092
- 0,
3093
- -scrollDistance,
3094
- startingPoint?.left,
3095
- startingPoint?.top
3096
- );
3097
- }
3098
- async scrollDown(distance, startingPoint) {
3099
- const { height } = await this.size();
3100
- const scrollDistance = distance || height * 0.7;
3101
- return this.mouse.wheel(
3102
- 0,
3103
- scrollDistance,
3104
- startingPoint?.left,
3105
- startingPoint?.top
3106
- );
3107
- }
3108
- async scrollLeft(distance, startingPoint) {
3109
- const { width } = await this.size();
3110
- const scrollDistance = distance || width * 0.7;
3111
- return this.mouse.wheel(
3112
- -scrollDistance,
3113
- 0,
3114
- startingPoint?.left,
3115
- startingPoint?.top
3116
- );
3117
- }
3118
- async scrollRight(distance, startingPoint) {
3119
- const { width } = await this.size();
3120
- const scrollDistance = distance || width * 0.7;
3121
- return this.mouse.wheel(
3122
- scrollDistance,
3123
- 0,
3124
- startingPoint?.left,
3125
- startingPoint?.top
3126
- );
3127
- }
3128
- async clearInput(element) {
3129
- if (!element) {
3130
- console.warn("No element to clear input");
3131
- return;
3132
- }
3133
- await this.mouse.click(element.center[0], element.center[1]);
3134
- await this.sendCommandToDebugger("Input.dispatchKeyEvent", {
3135
- type: "keyDown",
3136
- commands: ["selectAll"]
3137
- });
3138
- await this.sendCommandToDebugger("Input.dispatchKeyEvent", {
3139
- type: "keyUp",
3140
- commands: ["selectAll"]
3141
- });
3142
- await sleep2(100);
3143
- await this.keyboard.press({
3144
- key: "Backspace"
3145
- });
3146
- }
3147
- async destroy() {
3148
- this.activeTabId = null;
3149
- await this.detachDebugger();
3150
- this.destroyed = true;
3151
- }
3152
- };
3153
-
3154
- // src/chrome-extension/index.ts
3155
- var import_env3 = require("misoai-shared/env");
3156
- // Annotate the CommonJS export names for ESM import in node:
3157
- 0 && (module.exports = {
3158
- ChromeExtensionProxyPage,
3159
- ChromeExtensionProxyPageAgent,
3160
- ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED,
3161
- overrideAIConfig
3162
- });
3163
- /**
3164
- * @license
3165
- * Copyright 2017 Google Inc.
3166
- * SPDX-License-Identifier: Apache-2.0
3167
- */
3168
-
3169
- //# sourceMappingURL=chrome-extension.js.map