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