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