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