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