misoai-web 1.0.3 → 1.0.4

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