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