misoai-web 1.0.2 → 1.0.3

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