@midscene/core 0.0.1

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.
@@ -0,0 +1,1124 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
40
+ };
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
48
+ };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __publicField = (obj, key, value) => {
59
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
60
+ return value;
61
+ };
62
+
63
+ // src/index.ts
64
+ var src_exports = {};
65
+ __export(src_exports, {
66
+ AIResponseFormat: () => AIResponseFormat,
67
+ BaseElement: () => BaseElement,
68
+ Executor: () => Executor,
69
+ UIContext: () => UIContext,
70
+ default: () => src_default,
71
+ getElement: () => getElement,
72
+ getSection: () => getSection,
73
+ plan: () => plan,
74
+ setDumpDir: () => setDumpDir
75
+ });
76
+ module.exports = __toCommonJS(src_exports);
77
+
78
+ // src/insight/index.ts
79
+ var import_assert5 = __toESM(require("assert"));
80
+
81
+ // src/ai-model/prompt/util.ts
82
+ var import_assert2 = __toESM(require("assert"));
83
+
84
+ // src/image/info.ts
85
+ var import_node_assert = __toESM(require("assert"));
86
+ var import_buffer = require("buffer");
87
+ var import_node_fs = require("fs");
88
+ var import_sharp = __toESM(require("sharp"));
89
+ async function imageInfo(image) {
90
+ const { width, height } = await (0, import_sharp.default)(image).metadata();
91
+ (0, import_node_assert.default)(width && height, `invalid image: ${image}`);
92
+ return { width, height };
93
+ }
94
+ async function imageInfoOfBase64(imageBase64) {
95
+ const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, "");
96
+ return imageInfo(import_buffer.Buffer.from(base64Data, "base64"));
97
+ }
98
+
99
+ // src/image/transform.ts
100
+ var import_node_buffer = require("buffer");
101
+ var import_sharp2 = __toESM(require("sharp"));
102
+
103
+ // src/image/visualization.ts
104
+ var import_buffer2 = require("buffer");
105
+ var import_sharp3 = __toESM(require("sharp"));
106
+
107
+ // src/utils.ts
108
+ var import_os = require("os");
109
+ var import_path = require("path");
110
+ var import_fs = require("fs");
111
+ var import_crypto = require("crypto");
112
+ var import_assert = __toESM(require("assert"));
113
+ var pkg;
114
+ function getPkgInfo() {
115
+ if (pkg) {
116
+ return pkg;
117
+ }
118
+ let pkgJsonFile = "";
119
+ if ((0, import_fs.existsSync)((0, import_path.join)(__dirname, "../package.json"))) {
120
+ pkgJsonFile = (0, import_path.join)(__dirname, "../package.json");
121
+ } else if ((0, import_fs.existsSync)((0, import_path.join)(__dirname, "../../../package.json"))) {
122
+ pkgJsonFile = (0, import_path.join)(__dirname, "../../../package.json");
123
+ }
124
+ if (pkgJsonFile) {
125
+ const { name, version } = JSON.parse((0, import_fs.readFileSync)(pkgJsonFile, "utf-8"));
126
+ pkg = { name, version };
127
+ return pkg;
128
+ } else {
129
+ return {
130
+ name: "midscene-unknown-page-name",
131
+ version: "0.0.0"
132
+ };
133
+ }
134
+ }
135
+ var logDir = (0, import_path.join)(process.cwd(), "./midscene_run/");
136
+ var logEnvReady = false;
137
+ var insightDumpFileExt = "insight-dump.json";
138
+ function getDumpDir() {
139
+ return logDir;
140
+ }
141
+ function setDumpDir(dir) {
142
+ logDir = dir;
143
+ }
144
+ function writeDumpFile(fileName, fileExt, fileContent) {
145
+ if (!logEnvReady) {
146
+ (0, import_assert.default)(logDir, "logDir should be set before writing dump file");
147
+ if (!(0, import_fs.existsSync)(logDir)) {
148
+ (0, import_fs.mkdirSync)(logDir, { recursive: true });
149
+ }
150
+ const gitIgnorePath = (0, import_path.join)(logDir, "../.gitignore");
151
+ let gitIgnoreContent = "";
152
+ if ((0, import_fs.existsSync)(gitIgnorePath)) {
153
+ gitIgnoreContent = (0, import_fs.readFileSync)(gitIgnorePath, "utf-8");
154
+ }
155
+ const logDirName = (0, import_path.basename)(logDir);
156
+ if (!gitIgnoreContent.includes(`${logDirName}/`)) {
157
+ (0, import_fs.writeFileSync)(
158
+ gitIgnorePath,
159
+ `${gitIgnoreContent}
160
+ # MidScene.js dump files
161
+ ${logDirName}/
162
+ `,
163
+ "utf-8"
164
+ );
165
+ }
166
+ logEnvReady = true;
167
+ }
168
+ const filePath = (0, import_path.join)(getDumpDir(), `${fileName}.${fileExt}`);
169
+ (0, import_fs.writeFileSync)(filePath, fileContent);
170
+ (0, import_fs.copyFileSync)(filePath, (0, import_path.join)(getDumpDir(), `latest.${fileExt}`));
171
+ return filePath;
172
+ }
173
+
174
+ // src/ai-model/prompt/util.ts
175
+ var characteristic = "You are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.";
176
+ var contextFormatIntro = `
177
+ The user will give you a screenshot and the texts on it. There may be some none-English characters (like Chinese) on it, indicating it's an non-English app.`;
178
+ var ONE_ELEMENT_LOCATOR_PREFIX = "LOCATE_ONE_ELEMENT";
179
+ var ELEMENTS_LOCATOR_PREFIX = "LOCATE_ONE_OR_MORE_ELEMENTS";
180
+ var SECTION_MATCHER_FLAG = "SECTION_MATCHER_FLAG/";
181
+ var skillSegment = `skill name: segment_a_web_page
182
+ skill content:
183
+ Based on the functions and content of various elements on the page, segment the screenshot into different sections like navigation bar, product list, news area, etc.
184
+ Some general rules for segmentation:
185
+ * Each section should NOT overlap with each other.
186
+ * Each text should only belong to one section.
187
+ * [IMPORTANT] Whether the content visually appears to belong to different sections is a significant factor in segmenting the page.
188
+ * Analyze the page in a top-to-bottom and left-to-right order.
189
+ * The evidence indicates a separate section, for example
190
+ - The background color of certain parts of the page changes.
191
+ - A section of a page includes a title.
192
+ * Provide the following data for each of the UI section you found.
193
+ {
194
+ "name": "name of the section",
195
+ "description": "briefly summarize the key content or usage of this section.",
196
+ "sectionCharacteristics": "In view of the need to distinguish this section from the surrounding sections, explain the characteristics and how to define boundaries and what precautions to take.",
197
+ "textIds": ["5", "6", "7"], // ids of all text elements in this section
198
+ }
199
+ `;
200
+ var skillExtractData = `skill name: extract_data_from_UI
201
+ related input: DATA_DEMAND
202
+ skill content:
203
+ * User will give you some data requirements in DATA_DEMAND. Consider the UI context, follow the user's instructions, and provide comprehensive data accordingly.
204
+ * There may be some special commands in DATA_DEMAND, please pay extra attention
205
+ - ${ONE_ELEMENT_LOCATOR_PREFIX} and ${ELEMENTS_LOCATOR_PREFIX}: if you see a description that mentions the keyword ${ONE_ELEMENT_LOCATOR_PREFIX} or ${ELEMENTS_LOCATOR_PREFIX}(e.g. follow ${ONE_ELEMENT_LOCATOR_PREFIX} : i want to find ...), it means user wants to locate a specific element meets the description. Return in this way: prefix + the id / comma-separated ids, for example: ${ONE_ELEMENT_LOCATOR_PREFIX}/1 , ${ELEMENTS_LOCATOR_PREFIX}/1,2,3 . If not found, keep the prefix and leave the suffix empty, like ${ONE_ELEMENT_LOCATOR_PREFIX}/ .`;
206
+ function promptsOfSectionQuery(constraints) {
207
+ if (!constraints.length) {
208
+ return "";
209
+ }
210
+ const instruction = "Use your segment_a_web_page skill to find the following section(s)";
211
+ const singleSection = (c) => {
212
+ (0, import_assert2.default)(
213
+ c.name || c.description,
214
+ "either `name` or `description` is required to define a section constraint"
215
+ );
216
+ const number = "One section";
217
+ const name = c.name ? `named \`${c.name}\`` : "";
218
+ const description = c.description ? `, usage or criteria : ${c.description}` : "";
219
+ const basic = `* ${number} ${name}${description}`;
220
+ return basic;
221
+ };
222
+ return `${instruction}
223
+ ${constraints.map(singleSection).join("\n")}`;
224
+ }
225
+ function systemPromptToExtract(dataQuery, sections) {
226
+ const allSectionNames = (sections == null ? void 0 : sections.filter((c) => c.name).map((c) => c.name || "")) || [];
227
+ const sectionFindingPrompt = promptsOfSectionQuery(sections || []);
228
+ const sectionReturnFormat = allSectionNames.length ? " sections: [], // detailed information of each section from segment_a_web_page skill" : "";
229
+ return `
230
+ ${characteristic}
231
+ ${contextFormatIntro}
232
+
233
+ You have the following skills:
234
+ ${allSectionNames.length ? skillSegment : ""}
235
+ ${skillExtractData}
236
+
237
+ Now, do the following jobs:
238
+ ${sectionFindingPrompt}
239
+ Use your extract_data_from_UI skill to find the following data, placing it in the \`data\` field
240
+ DATA_DEMAND start:
241
+ ${typeof dataQuery === "object" ? `return in key-value style object, keys are ${Object.keys(dataQuery).join(",")}` : ""};
242
+ ${typeof dataQuery === "string" ? dataQuery : JSON.stringify(dataQuery, null, 2)}
243
+ DATA_DEMAND ends.
244
+
245
+ Return in the following JSON format:
246
+ {
247
+ language: "en", // "en" or "zh", the language of the page. Use the same language to describe section name, description, and similar fields.
248
+ ${sectionReturnFormat}
249
+ data: any, // the extracted data from extract_data_from_UI skill. Make sure both the value and scheme meet the DATA_DEMAND.
250
+ errors?: [], // string[], error message if any
251
+ }
252
+ `;
253
+ }
254
+ function describeSize(size) {
255
+ return `${size.width} x ${size.height}`;
256
+ }
257
+ function truncateText(text) {
258
+ const maxLength = 50;
259
+ if (text && text.length > maxLength) {
260
+ return `${text.slice(0, maxLength)}...`;
261
+ }
262
+ return text;
263
+ }
264
+ async function describeUserPage(context) {
265
+ const { screenshotBase64 } = context;
266
+ const { width, height } = await imageInfoOfBase64(screenshotBase64);
267
+ const elementsInfo = context.content;
268
+ const idElementMap = {};
269
+ elementsInfo.forEach((item) => {
270
+ idElementMap[item.id] = item;
271
+ return __spreadValues({}, item);
272
+ });
273
+ const elementInfosDescription = cropfieldInformation(elementsInfo);
274
+ return {
275
+ description: `
276
+ {
277
+ // The size of the page
278
+ "pageSize": ${describeSize({ width, height })},
279
+
280
+
281
+ // json description of the element
282
+ "elementInfos": ${JSON.stringify(elementInfosDescription)}
283
+ }`,
284
+ elementById(id) {
285
+ (0, import_assert2.default)(typeof id !== "undefined", "id is required for query");
286
+ const item = idElementMap[`${id}`];
287
+ return item;
288
+ }
289
+ };
290
+ }
291
+ function cropfieldInformation(elementsInfo) {
292
+ const elementInfosDescription = elementsInfo.map((item) => {
293
+ const { id, attributes = {}, rect, content } = item;
294
+ const tailorContent = truncateText(content);
295
+ const tailorAttributes = Object.keys(attributes).reduce((res, currentKey) => {
296
+ const attributeVal = attributes[currentKey];
297
+ res[currentKey] = truncateText(attributeVal);
298
+ return res;
299
+ }, {});
300
+ return {
301
+ id,
302
+ attributes: tailorAttributes,
303
+ rect,
304
+ content: tailorContent
305
+ };
306
+ });
307
+ return JSON.stringify(elementInfosDescription);
308
+ }
309
+ function retrieveElement(prompt, opt) {
310
+ if (opt == null ? void 0 : opt.multi) {
311
+ return `follow ${ELEMENTS_LOCATOR_PREFIX}: ${prompt}`;
312
+ }
313
+ return `follow ${ONE_ELEMENT_LOCATOR_PREFIX}: ${prompt}`;
314
+ }
315
+ function ifElementTypeResponse(response) {
316
+ if (typeof response !== "string") {
317
+ return false;
318
+ }
319
+ return response.startsWith(ONE_ELEMENT_LOCATOR_PREFIX) || response.startsWith(ELEMENTS_LOCATOR_PREFIX);
320
+ }
321
+ function splitElementResponse(response) {
322
+ const oneElementSplitter = `${ONE_ELEMENT_LOCATOR_PREFIX}/`;
323
+ if (response.startsWith(oneElementSplitter)) {
324
+ const id = response.slice(oneElementSplitter.length);
325
+ if (id.indexOf(",") >= 0) {
326
+ console.warn(`unexpected comma in one element response: ${id}`);
327
+ }
328
+ return id ? id : null;
329
+ }
330
+ const elementsSplitter = `${ELEMENTS_LOCATOR_PREFIX}/`;
331
+ if (response.startsWith(elementsSplitter)) {
332
+ const idsString = response.slice(elementsSplitter.length);
333
+ if (!idsString) {
334
+ return [];
335
+ }
336
+ return idsString.split(",");
337
+ }
338
+ return null;
339
+ }
340
+ function retrieveSection(prompt) {
341
+ return `${SECTION_MATCHER_FLAG}${prompt}`;
342
+ }
343
+ function extractSectionQuery(input) {
344
+ if (typeof input === "string" && input.startsWith(SECTION_MATCHER_FLAG)) {
345
+ return input.slice(SECTION_MATCHER_FLAG.length);
346
+ }
347
+ return false;
348
+ }
349
+
350
+ // src/insight/utils.ts
351
+ var import_fs2 = require("fs");
352
+ var import_path2 = require("path");
353
+ var import_crypto2 = require("crypto");
354
+ var import_assert3 = __toESM(require("assert"));
355
+ var logFileName = "";
356
+ var logContent = [];
357
+ var logIdIndexMap = {};
358
+ var { pid } = process;
359
+ var logFileExt = insightDumpFileExt;
360
+ function writeInsightDump(data, logId, dumpSubscriber) {
361
+ const logDir2 = getDumpDir();
362
+ (0, import_assert3.default)(logDir2, "logDir should be set before writing dump file");
363
+ const id = logId || (0, import_crypto2.randomUUID)();
364
+ const baseData = {
365
+ sdkVersion: getPkgInfo().version,
366
+ logTime: Date.now()
367
+ };
368
+ const finalData = __spreadValues(__spreadValues({
369
+ logId: id
370
+ }, baseData), data);
371
+ dumpSubscriber == null ? void 0 : dumpSubscriber(finalData);
372
+ if (!logFileName) {
373
+ logFileName = `pid_${pid}_${baseData.logTime}`;
374
+ while ((0, import_fs2.existsSync)((0, import_path2.join)(logDir2, `${logFileName}.${logFileExt}`))) {
375
+ logFileName = `${pid}_${baseData.logTime}-${Math.random()}`;
376
+ }
377
+ }
378
+ const dataString = JSON.stringify(finalData, null, 2);
379
+ if (typeof logIdIndexMap[id] === "number") {
380
+ logContent[logIdIndexMap[id]] = dataString;
381
+ } else {
382
+ const length = logContent.push(dataString);
383
+ logIdIndexMap[id] = length - 1;
384
+ }
385
+ writeDumpFile(logFileName, logFileExt, `[
386
+ ${logContent.join(",\n")}
387
+ ]`);
388
+ return id;
389
+ }
390
+ function idsIntoElements(ids, elementById) {
391
+ return ids.reduce((acc, id) => {
392
+ const element = elementById(id);
393
+ if (element) {
394
+ acc.push(element);
395
+ } else {
396
+ console.warn(`element not found by id: ${id}`);
397
+ }
398
+ return acc;
399
+ }, []);
400
+ }
401
+ function shallowExpandIds(data, ifMeet, elementsById) {
402
+ const keys = Object.keys(data);
403
+ keys.forEach((key) => {
404
+ const value = data[key];
405
+ if (typeof value === "string" && ifMeet(value)) {
406
+ data[key] = elementsById(value);
407
+ } else if (Array.isArray(value)) {
408
+ const newValue = value.map((id) => ifMeet(id) ? elementsById(id) : id);
409
+ data[key] = newValue;
410
+ }
411
+ });
412
+ return data;
413
+ }
414
+ function expandLiteSection(liteSection, elementById) {
415
+ const _a = liteSection, { textIds } = _a, remainingFields = __objRest(_a, ["textIds"]);
416
+ const texts = idsIntoElements(textIds, elementById);
417
+ let leftMost = -1;
418
+ let topMost = -1;
419
+ let rightMost = -1;
420
+ let bottomMost = -1;
421
+ texts.forEach((text) => {
422
+ leftMost = leftMost === -1 ? text.rect.left : Math.min(leftMost, text.rect.left);
423
+ topMost = topMost === -1 ? text.rect.top : Math.min(topMost, text.rect.top);
424
+ rightMost = Math.max(rightMost, text.rect.left + text.rect.width);
425
+ bottomMost = Math.max(bottomMost, text.rect.top + text.rect.height);
426
+ });
427
+ const sectionRect = {
428
+ left: leftMost,
429
+ top: topMost,
430
+ width: rightMost - leftMost,
431
+ height: bottomMost - topMost
432
+ };
433
+ const section = __spreadProps(__spreadValues({}, remainingFields), {
434
+ content: texts,
435
+ rect: sectionRect
436
+ });
437
+ return section;
438
+ }
439
+
440
+ // src/ai-model/openai.ts
441
+ var import_assert4 = __toESM(require("assert"));
442
+ var import_openai = __toESM(require("openai"));
443
+ var import_wrappers = __toESM(require("langsmith/wrappers"));
444
+
445
+ // src/types.ts
446
+ var BaseElement = class {
447
+ };
448
+ var AIResponseFormat = /* @__PURE__ */ ((AIResponseFormat2) => {
449
+ AIResponseFormat2["JSON"] = "json_object";
450
+ AIResponseFormat2["TEXT"] = "text";
451
+ return AIResponseFormat2;
452
+ })(AIResponseFormat || {});
453
+ var UIContext = class {
454
+ };
455
+
456
+ // src/ai-model/openai.ts
457
+ var envConfigKey = "MIDSCENE_OPENAI_INIT_CONFIG_JSON";
458
+ var envModelKey = "MIDSCENE_MODEL_NAME";
459
+ var envSmithDebug = "MIDSCENE_LANGSMITH_DEBUG";
460
+ var extraConfig = {};
461
+ if (typeof process.env[envConfigKey] === "string") {
462
+ console.log("will use env config for openai");
463
+ extraConfig = JSON.parse(process.env[envConfigKey]);
464
+ }
465
+ var model = "gpt-4o";
466
+ if (typeof process.env[envModelKey] === "string") {
467
+ console.log(`will use model: ${process.env[envModelKey]}`);
468
+ model = process.env[envModelKey];
469
+ }
470
+ async function createOpenAI() {
471
+ const openai = new import_openai.default(extraConfig);
472
+ if (process.env[envSmithDebug]) {
473
+ console.log("DEBUGGING MODE: using langsmith wrapper");
474
+ const openai2 = import_wrappers.default.wrapOpenAI(new import_openai.default());
475
+ return openai2;
476
+ }
477
+ return openai;
478
+ }
479
+ async function call(messages, responseFormat) {
480
+ const openai = await createOpenAI();
481
+ const completion = await openai.chat.completions.create({
482
+ model,
483
+ messages,
484
+ response_format: { type: responseFormat }
485
+ });
486
+ const { content } = completion.choices[0].message;
487
+ (0, import_assert4.default)(content, "empty content");
488
+ return content;
489
+ }
490
+ async function callToGetJSONObject(messages) {
491
+ const response = await call(messages, "json_object" /* JSON */);
492
+ (0, import_assert4.default)(response, "empty response");
493
+ return JSON.parse(response);
494
+ }
495
+
496
+ // src/ai-model/prompt/element_inspector.ts
497
+ function systemPromptToFindElement(description, multi) {
498
+ return `
499
+ ## Role:
500
+ You are an expert in software page image (2D) and page element text analysis.
501
+
502
+ ## Objective:
503
+ - Identify elements in screenshots and text that match the user's description.
504
+ - Return JSON data containing the selection reason and element ID.
505
+
506
+ ## Skills:
507
+ - Image analysis and recognition
508
+ - Multilingual text understanding
509
+ - Software UI design and testing
510
+
511
+ ## Workflow:
512
+ 1. Receive the user's element description, screenshot, and element description information. Note that the text may contain non-English characters (e.g., Chinese), indicating that the application may be non-English.
513
+ 2. Based on the description (${description}), locate the target element ID in the list of element descriptions and the screenshot.
514
+ 3. Return the number of elements: ${multi ? "multiple elements matching the description (two or more)" : "The element closest to the description (only one)"}.
515
+ 4. Return JSON data containing the selection reason and element ID.
516
+
517
+ ## Constraints:
518
+ - Strictly adhere to the specified location when describing the required element; do not select elements from other locations.
519
+ - Elements in the image with NodeType other than "TEXT Node" have been highlighted to identify the element among multiple non-text elements.
520
+ - Accurately identify element information based on the user's description and return the corresponding element ID from the element description information, not extracted from the image.
521
+ - If no elements are found, the "elements" array should be empty.
522
+ - The returned data must conform to the specified JSON format.
523
+
524
+ ## Output Format:
525
+ \`\`\`json
526
+ {
527
+ "elements": [
528
+ // If no matching elements are found, return an empty array []
529
+ {
530
+ "reason": "xxx", // The thought process for finding the element, replace xxx with your thought process
531
+ "text": "xxx", // Replace xxx with the text of elementInfo, if none, leave empty
532
+ "id": "xxx" // Replace xxx with the ID of elementInfo
533
+ }
534
+ // More elements...
535
+ ],
536
+ "errors": [] // Array of strings containing any error messages
537
+ }
538
+ \`\`\`
539
+
540
+ ## Example:
541
+ Example 1:
542
+ Input Example:
543
+ \`\`\`json
544
+ // Description: "Shopping cart icon in the upper right corner"
545
+ {
546
+ "screenshot": "path/screenshot.png",
547
+ "text": '{
548
+ "pageSize": {
549
+ "width": 400, // Width of the page
550
+ "height": 905 // Height of the page
551
+ },
552
+ "elementInfos": [
553
+ {
554
+ "id": "3", // ID of the element
555
+ "attributes": { // Attributes of the element
556
+ "nodeType": "IMG Node", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node
557
+ "src": "https://ap-southeast-3.m",
558
+ "class": ".img"
559
+ },
560
+ "content": "", // Text content of the element
561
+ "rect": {
562
+ "left": 280, // Distance from the left side of the page
563
+ "top": 8, // Distance from the top of the page
564
+ "width": 44, // Width of the element
565
+ "height": 44 // Height of the element
566
+ }
567
+ },
568
+ {
569
+ "id": "4", // ID of the element
570
+ "attributes": { // Attributes of the element
571
+ "nodeType": "IMG Node", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node
572
+ "src": "data:image/png;base64,iVBORw0KGgoAAAANSU...",
573
+ "class": ".icon"
574
+ },
575
+ "content": "", // Text content of the element
576
+ "rect": {
577
+ "left": 350, // Distance from the left side of the page
578
+ "top": 16, // Distance from the top of the page
579
+ "width": 25, // Width of the element
580
+ "height": 25 // Height of the element
581
+ }
582
+ },
583
+ ...
584
+ {
585
+ "id": "27",
586
+ "attributes": {
587
+ "nodeType": "TEXT Node",
588
+ "class": ".product-name"
589
+ },
590
+ "center": [
591
+ 288,
592
+ 834
593
+ ],
594
+ "content": "Mango Drink",
595
+ "rect": {
596
+ "left": 188,
597
+ "top": 827,
598
+ "width": 199,
599
+ "height": 13
600
+ }
601
+ },
602
+ ...
603
+ ]
604
+ }
605
+ '
606
+ }
607
+ \`\`\`
608
+ Output Example:
609
+ \`\`\`json
610
+ {
611
+ "elements": [
612
+ {
613
+ // Describe the reason for finding this element, replace with actual value in practice
614
+ "reason": "Reason for finding element 4: It is located in the upper right corner, is an image type, and according to the screenshot, it is a shopping cart icon button",
615
+ "text": "",
616
+ // ID of this element, replace with actual value in practice
617
+ "id": "4"
618
+ }
619
+ ],
620
+ "errors": []
621
+ }
622
+ \`\`\`
623
+
624
+ `;
625
+ }
626
+
627
+ // src/ai-model/inspect.ts
628
+ async function AiInspectElement(options) {
629
+ const { context, multi, findElementDescription, callAI = callToGetJSONObject } = options;
630
+ const { screenshotBase64 } = context;
631
+ const { description, elementById } = await describeUserPage(context);
632
+ const systemPrompt = systemPromptToFindElement(findElementDescription, multi);
633
+ const msgs = [
634
+ { role: "system", content: systemPrompt },
635
+ {
636
+ role: "user",
637
+ content: [
638
+ {
639
+ type: "image_url",
640
+ image_url: {
641
+ url: screenshotBase64,
642
+ detail: "high"
643
+ }
644
+ },
645
+ {
646
+ type: "text",
647
+ text: description
648
+ }
649
+ ]
650
+ }
651
+ ];
652
+ const parseResult = await callAI(msgs);
653
+ return {
654
+ parseResult,
655
+ elementById,
656
+ systemPrompt
657
+ };
658
+ }
659
+ async function AiExtractElementInfo(options) {
660
+ const { dataQuery, sectionConstraints, context, callAI = callToGetJSONObject } = options;
661
+ const systemPrompt = systemPromptToExtract(dataQuery, sectionConstraints);
662
+ const { screenshotBase64 } = context;
663
+ const { description, elementById } = await describeUserPage(context);
664
+ const msgs = [
665
+ { role: "system", content: systemPrompt },
666
+ {
667
+ role: "user",
668
+ content: [
669
+ {
670
+ type: "image_url",
671
+ image_url: {
672
+ url: screenshotBase64
673
+ }
674
+ },
675
+ {
676
+ type: "text",
677
+ text: description
678
+ }
679
+ ]
680
+ }
681
+ ];
682
+ const parseResult = await callAI(msgs);
683
+ return {
684
+ parseResult,
685
+ elementById,
686
+ systemPrompt
687
+ };
688
+ }
689
+
690
+ // src/insight/index.ts
691
+ var sortByOrder = (a, b) => {
692
+ if (a.rect.top - b.rect.top !== 0) {
693
+ return a.rect.top - b.rect.top;
694
+ } else {
695
+ return a.rect.left - b.rect.left;
696
+ }
697
+ };
698
+ var Insight = class {
699
+ constructor(context, opt) {
700
+ __publicField(this, "contextRetrieverFn");
701
+ __publicField(this, "aiVendorFn", callToGetJSONObject);
702
+ __publicField(this, "onceDumpUpdatedFn");
703
+ __publicField(this, "taskInfo");
704
+ (0, import_assert5.default)(context, "context is required for Insight");
705
+ if (typeof context === "function") {
706
+ this.contextRetrieverFn = context;
707
+ } else {
708
+ this.contextRetrieverFn = () => Promise.resolve(context);
709
+ }
710
+ if (typeof (opt == null ? void 0 : opt.aiVendorFn) !== "undefined") {
711
+ this.aiVendorFn = opt.aiVendorFn;
712
+ }
713
+ if (typeof (opt == null ? void 0 : opt.taskInfo) !== "undefined") {
714
+ this.taskInfo = opt.taskInfo;
715
+ }
716
+ }
717
+ async locate(queryPrompt, opt) {
718
+ var _a;
719
+ (0, import_assert5.default)(queryPrompt, "query is required for located");
720
+ const dumpSubscriber = this.onceDumpUpdatedFn;
721
+ this.onceDumpUpdatedFn = void 0;
722
+ const context = await this.contextRetrieverFn();
723
+ const startTime = Date.now();
724
+ const { parseResult, systemPrompt, elementById } = await AiInspectElement({
725
+ callAI: this.aiVendorFn,
726
+ context,
727
+ multi: Boolean(opt == null ? void 0 : opt.multi),
728
+ findElementDescription: queryPrompt
729
+ });
730
+ const timeCost = Date.now() - startTime;
731
+ const taskInfo = __spreadProps(__spreadValues({}, this.taskInfo ? this.taskInfo : {}), {
732
+ durationMs: timeCost,
733
+ rawResponse: JSON.stringify(parseResult),
734
+ systemPrompt
735
+ });
736
+ let errorLog;
737
+ if ((_a = parseResult.errors) == null ? void 0 : _a.length) {
738
+ errorLog = `locate - AI response error:
739
+ ${parseResult.errors.join("\n")}`;
740
+ }
741
+ const dumpData = {
742
+ type: "locate",
743
+ context,
744
+ userQuery: {
745
+ element: queryPrompt
746
+ },
747
+ matchedSection: [],
748
+ matchedElement: [],
749
+ data: null,
750
+ taskInfo,
751
+ error: errorLog
752
+ };
753
+ const logId = writeInsightDump(dumpData, void 0, dumpSubscriber);
754
+ if (errorLog) {
755
+ console.error(errorLog);
756
+ throw new Error(errorLog);
757
+ }
758
+ const elements = [];
759
+ parseResult.elements.forEach((item) => {
760
+ const element = elementById(item.id);
761
+ if (!element) {
762
+ console.warn(`locate: cannot find element id=${item.id}. Maybe an unstable response from AI model`);
763
+ return;
764
+ }
765
+ elements.push(element);
766
+ });
767
+ writeInsightDump(
768
+ __spreadProps(__spreadValues({}, dumpData), {
769
+ matchedElement: elements
770
+ }),
771
+ logId,
772
+ dumpSubscriber
773
+ );
774
+ if (opt == null ? void 0 : opt.multi) {
775
+ return elements;
776
+ } else if (elements.length >= 2) {
777
+ console.warn(`locate: multiple elements found, return the first one. (query: ${queryPrompt})`);
778
+ return elements[0];
779
+ } else if (elements.length === 1) {
780
+ return elements[0];
781
+ } else {
782
+ return null;
783
+ }
784
+ }
785
+ async extract(dataDemand) {
786
+ var _a;
787
+ let dataQuery = {};
788
+ const sectionQueryMap = {};
789
+ (0, import_assert5.default)(
790
+ typeof dataDemand === "object" || typeof dataDemand === "string",
791
+ `dataDemand should be object or string, but get ${typeof dataDemand}`
792
+ );
793
+ const dumpSubscriber = this.onceDumpUpdatedFn;
794
+ this.onceDumpUpdatedFn = void 0;
795
+ if (typeof dataDemand === "string") {
796
+ dataQuery = dataDemand;
797
+ } else {
798
+ for (const key in dataDemand) {
799
+ const query = dataDemand[key];
800
+ const sectionQuery = extractSectionQuery(query);
801
+ if (sectionQuery) {
802
+ sectionQueryMap[key] = sectionQuery;
803
+ } else {
804
+ dataQuery[key] = query;
805
+ }
806
+ }
807
+ dataQuery = dataDemand;
808
+ }
809
+ const sectionConstraints = Object.keys(sectionQueryMap).map((name) => {
810
+ const sectionQueryPrompt = sectionQueryMap[name];
811
+ return {
812
+ name,
813
+ description: sectionQueryPrompt || ""
814
+ };
815
+ });
816
+ const context = await this.contextRetrieverFn();
817
+ const startTime = Date.now();
818
+ const { parseResult, systemPrompt, elementById } = await AiExtractElementInfo({
819
+ context,
820
+ dataQuery,
821
+ sectionConstraints,
822
+ callAI: this.aiVendorFn
823
+ });
824
+ const timeCost = Date.now() - startTime;
825
+ const taskInfo = __spreadProps(__spreadValues({}, this.taskInfo ? this.taskInfo : {}), {
826
+ durationMs: timeCost,
827
+ rawResponse: JSON.stringify(parseResult),
828
+ systemPrompt
829
+ });
830
+ let errorLog;
831
+ if ((_a = parseResult.errors) == null ? void 0 : _a.length) {
832
+ errorLog = `segment - AI response error:
833
+ ${parseResult.errors.join("\n")}`;
834
+ }
835
+ const dumpData = {
836
+ type: "extract",
837
+ context,
838
+ userQuery: {
839
+ dataDemand
840
+ },
841
+ matchedSection: [],
842
+ matchedElement: [],
843
+ data: null,
844
+ taskInfo,
845
+ error: errorLog
846
+ };
847
+ const logId = writeInsightDump(dumpData, void 0, dumpSubscriber);
848
+ if (errorLog) {
849
+ console.error(errorLog);
850
+ throw new Error(errorLog);
851
+ }
852
+ const sectionsArr = (parseResult.sections || []).map((liteSection) => {
853
+ const section = expandLiteSection(liteSection, (id) => elementById(id));
854
+ return section;
855
+ }).sort(sortByOrder);
856
+ const sectionMap = sectionsArr.reduce((acc, section) => {
857
+ const { name } = section;
858
+ if (acc[name]) {
859
+ let i = 1;
860
+ while (acc[`${name}_${i}`]) {
861
+ i++;
862
+ }
863
+ console.warn(`section name conflict: ${name}, rename to ${name}_${i}`);
864
+ acc[`${name}_${i}`] = section;
865
+ } else {
866
+ acc[name] = section;
867
+ }
868
+ return acc;
869
+ }, {});
870
+ const { data } = parseResult;
871
+ let mergedData = data;
872
+ if (data && typeof data === "object" && !Array.isArray(data)) {
873
+ shallowExpandIds(data, ifElementTypeResponse, (id) => {
874
+ const idList = splitElementResponse(id);
875
+ if (typeof idList === "string") {
876
+ return elementById(idList);
877
+ } else if (Array.isArray(idList)) {
878
+ return idsIntoElements(idList, elementById);
879
+ }
880
+ return idList;
881
+ });
882
+ mergedData = __spreadValues(__spreadValues({}, data), sectionMap);
883
+ }
884
+ writeInsightDump(
885
+ __spreadProps(__spreadValues({}, dumpData), {
886
+ matchedSection: Object.values(sectionMap),
887
+ data: mergedData
888
+ }),
889
+ logId,
890
+ dumpSubscriber
891
+ );
892
+ return mergedData;
893
+ }
894
+ };
895
+
896
+ // src/action/executor.ts
897
+ var import_assert6 = __toESM(require("assert"));
898
+ var Executor = class {
899
+ constructor(name, description, tasks) {
900
+ __publicField(this, "name");
901
+ __publicField(this, "description");
902
+ __publicField(this, "tasks");
903
+ // status of executor
904
+ __publicField(this, "status");
905
+ __publicField(this, "errorMsg");
906
+ __publicField(this, "dumpFileName");
907
+ this.status = tasks && tasks.length > 0 ? "pending" : "init";
908
+ this.name = name;
909
+ this.description = description;
910
+ this.tasks = (tasks || []).map((item) => this.markTaskAsPending(item));
911
+ }
912
+ markTaskAsPending(task) {
913
+ return __spreadValues({
914
+ status: "pending"
915
+ }, task);
916
+ }
917
+ async append(task) {
918
+ (0, import_assert6.default)(this.status !== "error", "executor is in error state, cannot append task");
919
+ if (Array.isArray(task)) {
920
+ this.tasks.push(...task.map((item) => this.markTaskAsPending(item)));
921
+ } else {
922
+ this.tasks.push(this.markTaskAsPending(task));
923
+ }
924
+ if (this.status !== "running") {
925
+ this.status = "pending";
926
+ }
927
+ }
928
+ async flush() {
929
+ if (this.status === "init" && this.tasks.length > 0) {
930
+ console.warn("illegal state for executor, status is init but tasks are not empty");
931
+ }
932
+ (0, import_assert6.default)(this.status !== "running", "executor is already running");
933
+ (0, import_assert6.default)(this.status !== "completed", "executor is already completed");
934
+ (0, import_assert6.default)(this.status !== "error", "executor is in error state");
935
+ const nextPendingIndex = this.tasks.findIndex((task) => task.status === "pending");
936
+ if (nextPendingIndex < 0) {
937
+ return;
938
+ }
939
+ this.status = "running";
940
+ let taskIndex = nextPendingIndex;
941
+ let successfullyCompleted = true;
942
+ let errorMsg = "";
943
+ let previousFindOutput;
944
+ while (taskIndex < this.tasks.length) {
945
+ const task = this.tasks[taskIndex];
946
+ (0, import_assert6.default)(task.status === "pending", `task status should be pending, but got: ${task.status}`);
947
+ task.timing = {
948
+ start: Date.now()
949
+ };
950
+ try {
951
+ task.status = "running";
952
+ (0, import_assert6.default)(
953
+ ["Insight", "Action", "Planning"].indexOf(task.type) >= 0,
954
+ `unsupported task type: ${task.type}`
955
+ );
956
+ const { executor, param } = task;
957
+ (0, import_assert6.default)(executor, `executor is required for task type: ${task.type}`);
958
+ let returnValue;
959
+ const executorContext = {
960
+ task,
961
+ element: previousFindOutput == null ? void 0 : previousFindOutput.element
962
+ };
963
+ if (task.type === "Insight") {
964
+ (0, import_assert6.default)(
965
+ task.subType === "Locate" || task.subType === "Query",
966
+ `unsupported insight subType: ${task.subType}`
967
+ );
968
+ returnValue = await task.executor(param, executorContext);
969
+ if (task.subType === "Locate") {
970
+ previousFindOutput = returnValue == null ? void 0 : returnValue.output;
971
+ }
972
+ } else if (task.type === "Action" || task.type === "Planning") {
973
+ returnValue = await task.executor(param, executorContext);
974
+ } else {
975
+ console.warn(`unsupported task type: ${task.type}, will try to execute it directly`);
976
+ returnValue = await task.executor(param, executorContext);
977
+ }
978
+ Object.assign(task, returnValue);
979
+ task.status = "success";
980
+ task.timing.end = Date.now();
981
+ task.timing.cost = task.timing.end - task.timing.start;
982
+ taskIndex++;
983
+ } catch (e) {
984
+ successfullyCompleted = false;
985
+ task.status = "fail";
986
+ errorMsg = `${e == null ? void 0 : e.message}
987
+ ${e == null ? void 0 : e.stack}`;
988
+ task.error = errorMsg;
989
+ task.timing.end = Date.now();
990
+ task.timing.cost = task.timing.end - task.timing.start;
991
+ this.errorMsg = errorMsg;
992
+ break;
993
+ }
994
+ }
995
+ for (let i = taskIndex + 1; i < this.tasks.length; i++) {
996
+ this.tasks[i].status = "cancelled";
997
+ }
998
+ if (successfullyCompleted) {
999
+ this.status = "completed";
1000
+ } else {
1001
+ this.status = "error";
1002
+ throw new Error(`executor failed: ${errorMsg}`);
1003
+ }
1004
+ }
1005
+ dump() {
1006
+ const dumpData = {
1007
+ sdkVersion: getPkgInfo().version,
1008
+ logTime: Date.now(),
1009
+ name: this.name,
1010
+ description: this.description,
1011
+ tasks: this.tasks
1012
+ };
1013
+ return dumpData;
1014
+ }
1015
+ };
1016
+
1017
+ // src/query/index.ts
1018
+ var getElement = retrieveElement;
1019
+ var getSection = retrieveSection;
1020
+
1021
+ // src/automation/planning.ts
1022
+ var characteristic2 = "You are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.";
1023
+ function systemPromptToTaskPlanning(query) {
1024
+ return `
1025
+ ${characteristic2}
1026
+
1027
+ Based on the page context information (screenshot and description) you get, decompose the task user asked into a series of actions.
1028
+ Actions are executed in the order listed in the list. After executing the actions, the task should be completed.
1029
+
1030
+ Each action has a type and corresponding param. To be detailed:
1031
+ * type: 'Locate', it means to locate one element
1032
+ * param: { prompt: string }, the prompt describes 'which element to focus on page'. Our AI engine will use this prompt to locate the element, so it should clearly describe the obvious features of the element, such as its content, color, size, shape, and position. For example, 'The biggest Download Button on the left side of the page.'
1033
+ * type: 'Tap', tap the previous element found
1034
+ * param: null
1035
+ * type: 'Hover', hover the previous element found
1036
+ * param: null
1037
+ * type: 'Input', 'KeyboardPress', input something or press a key
1038
+ * param: { value: string }, the value to input or the key to press. Use (Enter, Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta, ControlOrMeta) to represent the key.
1039
+ * type: 'Scroll'
1040
+ * param: { scrollType: 'ScrollUntilBottom', 'ScrollUntilTop', 'ScrollDown', 'ScrollUp' }
1041
+ * type: 'Error'
1042
+ * param: { message: string }, the error message
1043
+
1044
+ Here is an example of how to decompose a task.
1045
+ When a user says 'Input "Weather in Shanghai" into the search bar, hit enter', by viewing the page screenshot and description, you my decompose this task into something like this:
1046
+ * Find: 'The search bar'
1047
+ * Input: 'Weather in Shanghai'
1048
+ * KeyboardPress: 'Enter'
1049
+
1050
+ Remember:
1051
+ 1. The actions you composed MUST be based on the page context information you get. Instead of making up actions that are not related to the page context.
1052
+ 2. In most cases, you should Locate one element first, then do other actions on it. For example, alway Find one element, then hover on it. But if you think it's necessary to do other actions first (like global scroll, global key press), you can do that.
1053
+
1054
+ If any error occurs during the task planning (like the page content and task are irrelevant, or the element mentioned does not exist at all), please return the error message with explanation in the errors field. The thoughts、prompts、error messages should all in the same language as the user query.
1055
+
1056
+ Return in the following JSON format:
1057
+ {
1058
+ queryLanguage: '', // language of the description of the task
1059
+ actions: [ // always return in Array
1060
+ {
1061
+ "thought": "Reasons for generating this task, and why this task is feasible on this page",
1062
+ "type": "Tap", // Type of action, like 'Tap' 'Hover' ...
1063
+ "param": any, // Parameter towards the task type
1064
+ },
1065
+ // ... more actions
1066
+ ],
1067
+ error?: string, // Overall error messages. If there is any error occurs during the task planning (i.e. error in previous 'actions' array), conclude the errors again, put error messages here
1068
+ }
1069
+
1070
+ Here is the description of the task. Just go ahead:
1071
+ =====================================
1072
+ ${query}
1073
+ =====================================
1074
+ `;
1075
+ }
1076
+ async function plan(context, userPrompt) {
1077
+ const { screenshotBase64 } = context;
1078
+ const { description } = await describeUserPage(context);
1079
+ const systemPrompt = systemPromptToTaskPlanning(userPrompt);
1080
+ const msgs = [
1081
+ { role: "system", content: systemPrompt },
1082
+ {
1083
+ role: "user",
1084
+ content: [
1085
+ {
1086
+ type: "image_url",
1087
+ image_url: {
1088
+ url: screenshotBase64,
1089
+ detail: "high"
1090
+ }
1091
+ },
1092
+ {
1093
+ type: "text",
1094
+ text: description
1095
+ }
1096
+ ]
1097
+ }
1098
+ ];
1099
+ const planFromAI = await callToGetJSONObject(msgs);
1100
+ if (planFromAI.error) {
1101
+ throw new Error(planFromAI.error);
1102
+ }
1103
+ const { actions } = planFromAI;
1104
+ actions.forEach((task) => {
1105
+ if (task.type === "Error") {
1106
+ throw new Error(task.thought);
1107
+ }
1108
+ });
1109
+ return { plans: actions };
1110
+ }
1111
+
1112
+ // src/index.ts
1113
+ var src_default = Insight;
1114
+ // Annotate the CommonJS export names for ESM import in node:
1115
+ 0 && (module.exports = {
1116
+ AIResponseFormat,
1117
+ BaseElement,
1118
+ Executor,
1119
+ UIContext,
1120
+ getElement,
1121
+ getSection,
1122
+ plan,
1123
+ setDumpDir
1124
+ });