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