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