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