misoai-web 1.0.3 → 1.0.5

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