misoai-web 1.0.3 → 1.0.5

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