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