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