@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,96 @@
1
+ // src/utils.ts
2
+ import { tmpdir } from "os";
3
+ import { basename, join } from "path";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
5
+ import { randomUUID } from "crypto";
6
+ import assert from "assert";
7
+ var pkg;
8
+ function getPkgInfo() {
9
+ if (pkg) {
10
+ return pkg;
11
+ }
12
+ let pkgJsonFile = "";
13
+ if (existsSync(join(__dirname, "../package.json"))) {
14
+ pkgJsonFile = join(__dirname, "../package.json");
15
+ } else if (existsSync(join(__dirname, "../../../package.json"))) {
16
+ pkgJsonFile = join(__dirname, "../../../package.json");
17
+ }
18
+ if (pkgJsonFile) {
19
+ const { name, version } = JSON.parse(readFileSync(pkgJsonFile, "utf-8"));
20
+ pkg = { name, version };
21
+ return pkg;
22
+ } else {
23
+ return {
24
+ name: "midscene-unknown-page-name",
25
+ version: "0.0.0"
26
+ };
27
+ }
28
+ }
29
+ var logDir = join(process.cwd(), "./midscene_run/");
30
+ var logEnvReady = false;
31
+ var insightDumpFileExt = "insight-dump.json";
32
+ var groupedActionDumpFileExt = "web-dump.json";
33
+ function getDumpDir() {
34
+ return logDir;
35
+ }
36
+ function setDumpDir(dir) {
37
+ logDir = dir;
38
+ }
39
+ function writeDumpFile(fileName, fileExt, fileContent) {
40
+ if (!logEnvReady) {
41
+ assert(logDir, "logDir should be set before writing dump file");
42
+ if (!existsSync(logDir)) {
43
+ mkdirSync(logDir, { recursive: true });
44
+ }
45
+ const gitIgnorePath = join(logDir, "../.gitignore");
46
+ let gitIgnoreContent = "";
47
+ if (existsSync(gitIgnorePath)) {
48
+ gitIgnoreContent = readFileSync(gitIgnorePath, "utf-8");
49
+ }
50
+ const logDirName = basename(logDir);
51
+ if (!gitIgnoreContent.includes(`${logDirName}/`)) {
52
+ writeFileSync(
53
+ gitIgnorePath,
54
+ `${gitIgnoreContent}
55
+ # MidScene.js dump files
56
+ ${logDirName}/
57
+ `,
58
+ "utf-8"
59
+ );
60
+ }
61
+ logEnvReady = true;
62
+ }
63
+ const filePath = join(getDumpDir(), `${fileName}.${fileExt}`);
64
+ writeFileSync(filePath, fileContent);
65
+ copyFileSync(filePath, join(getDumpDir(), `latest.${fileExt}`));
66
+ return filePath;
67
+ }
68
+ function getTmpDir() {
69
+ const path = join(tmpdir(), getPkgInfo().name);
70
+ mkdirSync(path, { recursive: true });
71
+ return path;
72
+ }
73
+ function getTmpFile(fileExt) {
74
+ const filename = `${randomUUID()}.${fileExt}`;
75
+ return join(getTmpDir(), filename);
76
+ }
77
+ function overlapped(container, target) {
78
+ return container.left < target.left + target.width && container.left + container.width > target.left && container.top < target.top + target.height && container.top + container.height > target.top;
79
+ }
80
+ async function sleep(ms) {
81
+ return new Promise((resolve) => setTimeout(resolve, ms));
82
+ }
83
+ var commonScreenshotParam = { type: "jpeg", quality: 75 };
84
+ export {
85
+ commonScreenshotParam,
86
+ getDumpDir,
87
+ getPkgInfo,
88
+ getTmpDir,
89
+ getTmpFile,
90
+ groupedActionDumpFileExt,
91
+ insightDumpFileExt,
92
+ overlapped,
93
+ setDumpDir,
94
+ sleep,
95
+ writeDumpFile
96
+ };
@@ -0,0 +1,467 @@
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 __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+
44
+ // src/ai-model/index.ts
45
+ var ai_model_exports = {};
46
+ __export(ai_model_exports, {
47
+ AiExtractElementInfo: () => AiExtractElementInfo,
48
+ AiInspectElement: () => AiInspectElement,
49
+ callToGetJSONObject: () => callToGetJSONObject,
50
+ describeUserPage: () => describeUserPage,
51
+ systemPromptToFindElement: () => systemPromptToFindElement
52
+ });
53
+ module.exports = __toCommonJS(ai_model_exports);
54
+
55
+ // src/ai-model/openai.ts
56
+ var import_assert = __toESM(require("assert"));
57
+ var import_openai = __toESM(require("openai"));
58
+ var import_wrappers = __toESM(require("langsmith/wrappers"));
59
+ var envConfigKey = "MIDSCENE_OPENAI_INIT_CONFIG_JSON";
60
+ var envModelKey = "MIDSCENE_MODEL_NAME";
61
+ var envSmithDebug = "MIDSCENE_LANGSMITH_DEBUG";
62
+ var extraConfig = {};
63
+ if (typeof process.env[envConfigKey] === "string") {
64
+ console.log("will use env config for openai");
65
+ extraConfig = JSON.parse(process.env[envConfigKey]);
66
+ }
67
+ var model = "gpt-4o";
68
+ if (typeof process.env[envModelKey] === "string") {
69
+ console.log(`will use model: ${process.env[envModelKey]}`);
70
+ model = process.env[envModelKey];
71
+ }
72
+ async function createOpenAI() {
73
+ const openai = new import_openai.default(extraConfig);
74
+ if (process.env[envSmithDebug]) {
75
+ console.log("DEBUGGING MODE: using langsmith wrapper");
76
+ const openai2 = import_wrappers.default.wrapOpenAI(new import_openai.default());
77
+ return openai2;
78
+ }
79
+ return openai;
80
+ }
81
+ async function call(messages, responseFormat) {
82
+ const openai = await createOpenAI();
83
+ const completion = await openai.chat.completions.create({
84
+ model,
85
+ messages,
86
+ response_format: { type: responseFormat }
87
+ });
88
+ const { content } = completion.choices[0].message;
89
+ (0, import_assert.default)(content, "empty content");
90
+ return content;
91
+ }
92
+ async function callToGetJSONObject(messages) {
93
+ const response = await call(messages, "json_object" /* JSON */);
94
+ (0, import_assert.default)(response, "empty response");
95
+ return JSON.parse(response);
96
+ }
97
+
98
+ // src/ai-model/prompt/element_inspector.ts
99
+ function systemPromptToFindElement(description, multi) {
100
+ return `
101
+ ## Role:
102
+ You are an expert in software page image (2D) and page element text analysis.
103
+
104
+ ## Objective:
105
+ - Identify elements in screenshots and text that match the user's description.
106
+ - Return JSON data containing the selection reason and element ID.
107
+
108
+ ## Skills:
109
+ - Image analysis and recognition
110
+ - Multilingual text understanding
111
+ - Software UI design and testing
112
+
113
+ ## Workflow:
114
+ 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.
115
+ 2. Based on the description (${description}), locate the target element ID in the list of element descriptions and the screenshot.
116
+ 3. Return the number of elements: ${multi ? "multiple elements matching the description (two or more)" : "The element closest to the description (only one)"}.
117
+ 4. Return JSON data containing the selection reason and element ID.
118
+
119
+ ## Constraints:
120
+ - Strictly adhere to the specified location when describing the required element; do not select elements from other locations.
121
+ - Elements in the image with NodeType other than "TEXT Node" have been highlighted to identify the element among multiple non-text elements.
122
+ - 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.
123
+ - If no elements are found, the "elements" array should be empty.
124
+ - The returned data must conform to the specified JSON format.
125
+
126
+ ## Output Format:
127
+ \`\`\`json
128
+ {
129
+ "elements": [
130
+ // If no matching elements are found, return an empty array []
131
+ {
132
+ "reason": "xxx", // The thought process for finding the element, replace xxx with your thought process
133
+ "text": "xxx", // Replace xxx with the text of elementInfo, if none, leave empty
134
+ "id": "xxx" // Replace xxx with the ID of elementInfo
135
+ }
136
+ // More elements...
137
+ ],
138
+ "errors": [] // Array of strings containing any error messages
139
+ }
140
+ \`\`\`
141
+
142
+ ## Example:
143
+ Example 1:
144
+ Input Example:
145
+ \`\`\`json
146
+ // Description: "Shopping cart icon in the upper right corner"
147
+ {
148
+ "screenshot": "path/screenshot.png",
149
+ "text": '{
150
+ "pageSize": {
151
+ "width": 400, // Width of the page
152
+ "height": 905 // Height of the page
153
+ },
154
+ "elementInfos": [
155
+ {
156
+ "id": "3", // ID of the element
157
+ "attributes": { // Attributes of the element
158
+ "nodeType": "IMG Node", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node
159
+ "src": "https://ap-southeast-3.m",
160
+ "class": ".img"
161
+ },
162
+ "content": "", // Text content of the element
163
+ "rect": {
164
+ "left": 280, // Distance from the left side of the page
165
+ "top": 8, // Distance from the top of the page
166
+ "width": 44, // Width of the element
167
+ "height": 44 // Height of the element
168
+ }
169
+ },
170
+ {
171
+ "id": "4", // ID of the element
172
+ "attributes": { // Attributes of the element
173
+ "nodeType": "IMG Node", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node
174
+ "src": "data:image/png;base64,iVBORw0KGgoAAAANSU...",
175
+ "class": ".icon"
176
+ },
177
+ "content": "", // Text content of the element
178
+ "rect": {
179
+ "left": 350, // Distance from the left side of the page
180
+ "top": 16, // Distance from the top of the page
181
+ "width": 25, // Width of the element
182
+ "height": 25 // Height of the element
183
+ }
184
+ },
185
+ ...
186
+ {
187
+ "id": "27",
188
+ "attributes": {
189
+ "nodeType": "TEXT Node",
190
+ "class": ".product-name"
191
+ },
192
+ "center": [
193
+ 288,
194
+ 834
195
+ ],
196
+ "content": "Mango Drink",
197
+ "rect": {
198
+ "left": 188,
199
+ "top": 827,
200
+ "width": 199,
201
+ "height": 13
202
+ }
203
+ },
204
+ ...
205
+ ]
206
+ }
207
+ '
208
+ }
209
+ \`\`\`
210
+ Output Example:
211
+ \`\`\`json
212
+ {
213
+ "elements": [
214
+ {
215
+ // Describe the reason for finding this element, replace with actual value in practice
216
+ "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",
217
+ "text": "",
218
+ // ID of this element, replace with actual value in practice
219
+ "id": "4"
220
+ }
221
+ ],
222
+ "errors": []
223
+ }
224
+ \`\`\`
225
+
226
+ `;
227
+ }
228
+
229
+ // src/ai-model/prompt/util.ts
230
+ var import_assert3 = __toESM(require("assert"));
231
+
232
+ // src/image/info.ts
233
+ var import_node_assert = __toESM(require("assert"));
234
+ var import_buffer = require("buffer");
235
+ var import_node_fs = require("fs");
236
+ var import_sharp = __toESM(require("sharp"));
237
+ async function imageInfo(image) {
238
+ const { width, height } = await (0, import_sharp.default)(image).metadata();
239
+ (0, import_node_assert.default)(width && height, `invalid image: ${image}`);
240
+ return { width, height };
241
+ }
242
+ async function imageInfoOfBase64(imageBase64) {
243
+ const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, "");
244
+ return imageInfo(import_buffer.Buffer.from(base64Data, "base64"));
245
+ }
246
+
247
+ // src/image/transform.ts
248
+ var import_node_buffer = require("buffer");
249
+ var import_sharp2 = __toESM(require("sharp"));
250
+
251
+ // src/image/visualization.ts
252
+ var import_buffer2 = require("buffer");
253
+ var import_sharp3 = __toESM(require("sharp"));
254
+
255
+ // src/utils.ts
256
+ var import_os = require("os");
257
+ var import_path = require("path");
258
+ var import_fs = require("fs");
259
+ var import_crypto = require("crypto");
260
+ var import_assert2 = __toESM(require("assert"));
261
+ var logDir = (0, import_path.join)(process.cwd(), "./midscene_run/");
262
+
263
+ // src/ai-model/prompt/util.ts
264
+ 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.";
265
+ var contextFormatIntro = `
266
+ 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.`;
267
+ var ONE_ELEMENT_LOCATOR_PREFIX = "LOCATE_ONE_ELEMENT";
268
+ var ELEMENTS_LOCATOR_PREFIX = "LOCATE_ONE_OR_MORE_ELEMENTS";
269
+ var skillSegment = `skill name: segment_a_web_page
270
+ skill content:
271
+ 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.
272
+ Some general rules for segmentation:
273
+ * Each section should NOT overlap with each other.
274
+ * Each text should only belong to one section.
275
+ * [IMPORTANT] Whether the content visually appears to belong to different sections is a significant factor in segmenting the page.
276
+ * Analyze the page in a top-to-bottom and left-to-right order.
277
+ * The evidence indicates a separate section, for example
278
+ - The background color of certain parts of the page changes.
279
+ - A section of a page includes a title.
280
+ * Provide the following data for each of the UI section you found.
281
+ {
282
+ "name": "name of the section",
283
+ "description": "briefly summarize the key content or usage of this section.",
284
+ "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.",
285
+ "textIds": ["5", "6", "7"], // ids of all text elements in this section
286
+ }
287
+ `;
288
+ var skillExtractData = `skill name: extract_data_from_UI
289
+ related input: DATA_DEMAND
290
+ skill content:
291
+ * User will give you some data requirements in DATA_DEMAND. Consider the UI context, follow the user's instructions, and provide comprehensive data accordingly.
292
+ * There may be some special commands in DATA_DEMAND, please pay extra attention
293
+ - ${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}/ .`;
294
+ function promptsOfSectionQuery(constraints) {
295
+ if (!constraints.length) {
296
+ return "";
297
+ }
298
+ const instruction = "Use your segment_a_web_page skill to find the following section(s)";
299
+ const singleSection = (c) => {
300
+ (0, import_assert3.default)(
301
+ c.name || c.description,
302
+ "either `name` or `description` is required to define a section constraint"
303
+ );
304
+ const number = "One section";
305
+ const name = c.name ? `named \`${c.name}\`` : "";
306
+ const description = c.description ? `, usage or criteria : ${c.description}` : "";
307
+ const basic = `* ${number} ${name}${description}`;
308
+ return basic;
309
+ };
310
+ return `${instruction}
311
+ ${constraints.map(singleSection).join("\n")}`;
312
+ }
313
+ function systemPromptToExtract(dataQuery, sections) {
314
+ const allSectionNames = (sections == null ? void 0 : sections.filter((c) => c.name).map((c) => c.name || "")) || [];
315
+ const sectionFindingPrompt = promptsOfSectionQuery(sections || []);
316
+ const sectionReturnFormat = allSectionNames.length ? " sections: [], // detailed information of each section from segment_a_web_page skill" : "";
317
+ return `
318
+ ${characteristic}
319
+ ${contextFormatIntro}
320
+
321
+ You have the following skills:
322
+ ${allSectionNames.length ? skillSegment : ""}
323
+ ${skillExtractData}
324
+
325
+ Now, do the following jobs:
326
+ ${sectionFindingPrompt}
327
+ Use your extract_data_from_UI skill to find the following data, placing it in the \`data\` field
328
+ DATA_DEMAND start:
329
+ ${typeof dataQuery === "object" ? `return in key-value style object, keys are ${Object.keys(dataQuery).join(",")}` : ""};
330
+ ${typeof dataQuery === "string" ? dataQuery : JSON.stringify(dataQuery, null, 2)}
331
+ DATA_DEMAND ends.
332
+
333
+ Return in the following JSON format:
334
+ {
335
+ language: "en", // "en" or "zh", the language of the page. Use the same language to describe section name, description, and similar fields.
336
+ ${sectionReturnFormat}
337
+ data: any, // the extracted data from extract_data_from_UI skill. Make sure both the value and scheme meet the DATA_DEMAND.
338
+ errors?: [], // string[], error message if any
339
+ }
340
+ `;
341
+ }
342
+ function describeSize(size) {
343
+ return `${size.width} x ${size.height}`;
344
+ }
345
+ function truncateText(text) {
346
+ const maxLength = 50;
347
+ if (text && text.length > maxLength) {
348
+ return `${text.slice(0, maxLength)}...`;
349
+ }
350
+ return text;
351
+ }
352
+ async function describeUserPage(context) {
353
+ const { screenshotBase64 } = context;
354
+ const { width, height } = await imageInfoOfBase64(screenshotBase64);
355
+ const elementsInfo = context.content;
356
+ const idElementMap = {};
357
+ elementsInfo.forEach((item) => {
358
+ idElementMap[item.id] = item;
359
+ return __spreadValues({}, item);
360
+ });
361
+ const elementInfosDescription = cropfieldInformation(elementsInfo);
362
+ return {
363
+ description: `
364
+ {
365
+ // The size of the page
366
+ "pageSize": ${describeSize({ width, height })},
367
+
368
+
369
+ // json description of the element
370
+ "elementInfos": ${JSON.stringify(elementInfosDescription)}
371
+ }`,
372
+ elementById(id) {
373
+ (0, import_assert3.default)(typeof id !== "undefined", "id is required for query");
374
+ const item = idElementMap[`${id}`];
375
+ return item;
376
+ }
377
+ };
378
+ }
379
+ function cropfieldInformation(elementsInfo) {
380
+ const elementInfosDescription = elementsInfo.map((item) => {
381
+ const { id, attributes = {}, rect, content } = item;
382
+ const tailorContent = truncateText(content);
383
+ const tailorAttributes = Object.keys(attributes).reduce((res, currentKey) => {
384
+ const attributeVal = attributes[currentKey];
385
+ res[currentKey] = truncateText(attributeVal);
386
+ return res;
387
+ }, {});
388
+ return {
389
+ id,
390
+ attributes: tailorAttributes,
391
+ rect,
392
+ content: tailorContent
393
+ };
394
+ });
395
+ return JSON.stringify(elementInfosDescription);
396
+ }
397
+
398
+ // src/ai-model/inspect.ts
399
+ async function AiInspectElement(options) {
400
+ const { context, multi, findElementDescription, callAI = callToGetJSONObject } = options;
401
+ const { screenshotBase64 } = context;
402
+ const { description, elementById } = await describeUserPage(context);
403
+ const systemPrompt = systemPromptToFindElement(findElementDescription, multi);
404
+ const msgs = [
405
+ { role: "system", content: systemPrompt },
406
+ {
407
+ role: "user",
408
+ content: [
409
+ {
410
+ type: "image_url",
411
+ image_url: {
412
+ url: screenshotBase64,
413
+ detail: "high"
414
+ }
415
+ },
416
+ {
417
+ type: "text",
418
+ text: description
419
+ }
420
+ ]
421
+ }
422
+ ];
423
+ const parseResult = await callAI(msgs);
424
+ return {
425
+ parseResult,
426
+ elementById,
427
+ systemPrompt
428
+ };
429
+ }
430
+ async function AiExtractElementInfo(options) {
431
+ const { dataQuery, sectionConstraints, context, callAI = callToGetJSONObject } = options;
432
+ const systemPrompt = systemPromptToExtract(dataQuery, sectionConstraints);
433
+ const { screenshotBase64 } = context;
434
+ const { description, elementById } = await describeUserPage(context);
435
+ const msgs = [
436
+ { role: "system", content: systemPrompt },
437
+ {
438
+ role: "user",
439
+ content: [
440
+ {
441
+ type: "image_url",
442
+ image_url: {
443
+ url: screenshotBase64
444
+ }
445
+ },
446
+ {
447
+ type: "text",
448
+ text: description
449
+ }
450
+ ]
451
+ }
452
+ ];
453
+ const parseResult = await callAI(msgs);
454
+ return {
455
+ parseResult,
456
+ elementById,
457
+ systemPrompt
458
+ };
459
+ }
460
+ // Annotate the CommonJS export names for ESM import in node:
461
+ 0 && (module.exports = {
462
+ AiExtractElementInfo,
463
+ AiInspectElement,
464
+ callToGetJSONObject,
465
+ describeUserPage,
466
+ systemPromptToFindElement
467
+ });