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