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