@midscene/core 0.11.1 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/ai-model.js +2 -2
- package/dist/lib/{chunk-LSD3QYTX.js → chunk-IOU6IQ5D.js} +2 -2
- package/dist/lib/{chunk-HMB36AJ4.js → chunk-JCZGPJM3.js} +1 -1
- package/dist/lib/{chunk-HMB36AJ4.js.map → chunk-JCZGPJM3.js.map} +1 -1
- package/dist/lib/{chunk-CL4XCL3T.js → chunk-PQ34NDB5.js} +11 -11
- package/dist/lib/evaluation.js +4 -4
- package/dist/lib/index.js +4 -4
- package/dist/lib/types/ai-model.d.ts +3 -3
- package/dist/lib/types/index.d.ts +5 -5
- package/dist/lib/types/{llm-planning-65378494.d.ts → llm-planning-75af16ef.d.ts} +1 -1
- package/dist/lib/types/tree.d.ts +1 -1
- package/dist/lib/types/{types-4eebf154.d.ts → types-95b0888e.d.ts} +1 -0
- package/dist/lib/types/utils.d.ts +1 -1
- package/dist/lib/utils.js +2 -2
- package/package.json +3 -3
- package/report/index.html +1 -1
- /package/dist/lib/{chunk-LSD3QYTX.js.map → chunk-IOU6IQ5D.js.map} +0 -0
- /package/dist/lib/{chunk-CL4XCL3T.js.map → chunk-PQ34NDB5.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAI,OAAO,WAAW,YAAY,OAAO,OAAO,YAAY;AAAU,aAAO,UAAU;AAEvF,UAAM,UAAU,SAAU,KAAK;AAC3B,YAAM,IAAI,MAAM,oCAAoC,KAAK,QAAQ,KAAK,OAAO,GAAG;AAAA,IACpF;AAEA,aAAS,MAAM,SAAS;AACpB,UAAI,OAAO,YAAY;AAAY,kBAAU,MAAM;AAEnD,UAAI,SAAS,CAAC;AACd,UAAI,QAAQ,CAAC;AACb,UAAI,SAAS;AACb,WAAK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,CAAC,GAAG,CAAC,IAAI,KAAK,MAAM,QAAQ;AAClC,SAAO,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,MAAM;AACzC","names":["fromHex","fromOct","_default","require_lexer","assert","AIResponseFormat","PromptTemplate","content","dJSON","call"],"ignoreList":[],"sources":["../../../../node_modules/.pnpm/lex@1.7.9/node_modules/lex/lexer.js","../../../../node_modules/.pnpm/string.fromcodepoint@0.2.1/node_modules/string.fromcodepoint/fromcodepoint.js","../../../../node_modules/.pnpm/unescape-js@1.1.4/node_modules/unescape-js/dist/index.js","../../../../node_modules/.pnpm/utf8@3.0.0/node_modules/utf8/utf8.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/lexer.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/parser.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/dirty-json.js","../../src/ai-model/service-caller/index.ts","../../src/types.ts","../../src/ai-model/common.ts","../../src/ai-model/prompt/llm-locator.ts","../../src/ai-model/prompt/ui-tars-planning.ts","../../src/ai-model/prompt/ui-tars-locator.ts","../../src/ai-model/prompt/llm-planning.ts","../../src/ai-model/prompt/util.ts","../../src/image/index.ts","../../src/ai-model/inspect.ts","../../src/ai-model/llm-planning.ts","../../src/ai-model/ui-tars-planning.ts"],"sourcesContent":["if (typeof module === \"object\" && typeof module.exports === \"object\") module.exports = Lexer;\n\nLexer.defunct = function (chr) {\n throw new Error(\"Unexpected character at index \" + (this.index - 1) + \": \" + chr);\n};\n\nfunction Lexer(defunct) {\n if (typeof defunct !== \"function\") defunct = Lexer.defunct;\n\n var tokens = [];\n var rules = [];\n var remove = 0;\n this.state = 0;\n this.index = 0;\n this.input = \"\";\n\n this.addRule = function (pattern, action, start) {\n var global = pattern.global;\n\n if (!global) {\n var flags = \"g\";\n if (pattern.multiline) flags += \"m\";\n if (pattern.ignoreCase) flags += \"i\";\n pattern = new RegExp(pattern.source, flags);\n }\n\n if (Object.prototype.toString.call(start) !== \"[object Array]\") start = [0];\n\n rules.push({\n pattern: pattern,\n global: global,\n action: action,\n start: start\n });\n\n return this;\n };\n\n this.setInput = function (input) {\n remove = 0;\n this.state = 0;\n this.index = 0;\n tokens.length = 0;\n this.input = input;\n return this;\n };\n\n this.lex = function () {\n if (tokens.length) return tokens.shift();\n\n this.reject = true;\n\n while (this.index <= this.input.length) {\n var matches = scan.call(this).splice(remove);\n var index = this.index;\n\n while (matches.length) {\n if (this.reject) {\n var match = matches.shift();\n var result = match.result;\n var length = match.length;\n this.index += length;\n this.reject = false;\n remove++;\n\n var token = match.action.apply(this, result);\n if (this.reject) this.index = result.index;\n else if (typeof token !== \"undefined\") {\n switch (Object.prototype.toString.call(token)) {\n case \"[object Array]\":\n tokens = token.slice(1);\n token = token[0];\n default:\n if (length) remove = 0;\n return token;\n }\n }\n } else break;\n }\n\n var input = this.input;\n\n if (index < input.length) {\n if (this.reject) {\n remove = 0;\n var token = defunct.call(this, input.charAt(this.index++));\n if (typeof token !== \"undefined\") {\n if (Object.prototype.toString.call(token) === \"[object Array]\") {\n tokens = token.slice(1);\n return token[0];\n } else return token;\n }\n } else {\n if (this.index !== index) remove = 0;\n this.reject = true;\n }\n } else if (matches.length)\n this.reject = true;\n else break;\n }\n };\n\n function scan() {\n var matches = [];\n var index = 0;\n\n var state = this.state;\n var lastIndex = this.index;\n var input = this.input;\n\n for (var i = 0, length = rules.length; i < length; i++) {\n var rule = rules[i];\n var start = rule.start;\n var states = start.length;\n\n if ((!states || start.indexOf(state) >= 0) ||\n (state % 2 && states === 1 && !start[0])) {\n var pattern = rule.pattern;\n pattern.lastIndex = lastIndex;\n var result = pattern.exec(input);\n\n if (result && result.index === lastIndex) {\n var j = matches.push({\n result: result,\n action: rule.action,\n length: result[0].length\n });\n\n if (rule.global) index = j;\n\n while (--j > index) {\n var k = j - 1;\n\n if (matches[j].length > matches[k].length) {\n var temple = matches[j];\n matches[j] = matches[k];\n matches[k] = temple;\n }\n }\n }\n }\n }\n\n return matches;\n }\n}\n","/*! http://mths.be/fromcodepoint v0.2.1 by @mathias */\nif (!String.fromCodePoint) {\n\t(function() {\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar stringFromCharCode = String.fromCharCode;\n\t\tvar floor = Math.floor;\n\t\tvar fromCodePoint = function(_) {\n\t\t\tvar MAX_SIZE = 0x4000;\n\t\t\tvar codeUnits = [];\n\t\t\tvar highSurrogate;\n\t\t\tvar lowSurrogate;\n\t\t\tvar index = -1;\n\t\t\tvar length = arguments.length;\n\t\t\tif (!length) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tvar result = '';\n\t\t\twhile (++index < length) {\n\t\t\t\tvar codePoint = Number(arguments[index]);\n\t\t\t\tif (\n\t\t\t\t\t!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`\n\t\t\t\t\tcodePoint < 0 || // not a valid Unicode code point\n\t\t\t\t\tcodePoint > 0x10FFFF || // not a valid Unicode code point\n\t\t\t\t\tfloor(codePoint) != codePoint // not an integer\n\t\t\t\t) {\n\t\t\t\t\tthrow RangeError('Invalid code point: ' + codePoint);\n\t\t\t\t}\n\t\t\t\tif (codePoint <= 0xFFFF) { // BMP code point\n\t\t\t\t\tcodeUnits.push(codePoint);\n\t\t\t\t} else { // Astral code point; split in surrogate halves\n\t\t\t\t\t// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n\t\t\t\t\tcodePoint -= 0x10000;\n\t\t\t\t\thighSurrogate = (codePoint >> 10) + 0xD800;\n\t\t\t\t\tlowSurrogate = (codePoint % 0x400) + 0xDC00;\n\t\t\t\t\tcodeUnits.push(highSurrogate, lowSurrogate);\n\t\t\t\t}\n\t\t\t\tif (index + 1 == length || codeUnits.length > MAX_SIZE) {\n\t\t\t\t\tresult += stringFromCharCode.apply(null, codeUnits);\n\t\t\t\t\tcodeUnits.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String, 'fromCodePoint', {\n\t\t\t\t'value': fromCodePoint,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.fromCodePoint = fromCodePoint;\n\t\t}\n\t}());\n}\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nrequire(\"string.fromcodepoint\");\n\n/**\n * \\\\ - matches the backslash which indicates the beginning of an escape sequence\n * (\n * u\\{([0-9A-Fa-f]+)\\} - first alternative; matches the variable-length hexadecimal escape sequence (\\u{ABCD0})\n * |\n * u([0-9A-Fa-f]{4}) - second alternative; matches the 4-digit hexadecimal escape sequence (\\uABCD)\n * |\n * x([0-9A-Fa-f]{2}) - third alternative; matches the 2-digit hexadecimal escape sequence (\\xA5)\n * |\n * ([1-7][0-7]{0,2}|[0-7]{2,3}) - fourth alternative; matches the up-to-3-digit octal escape sequence (\\5 or \\512)\n * |\n * (['\"tbrnfv0\\\\]) - fifth alternative; matches the special escape characters (\\t, \\n and so on)\n * |\n * \\U([0-9A-Fa-f]+) - sixth alternative; matches the 8-digit hexadecimal escape sequence used by python (\\U0001F3B5)\n * )\n */\nvar jsEscapeRegex = /\\\\(u\\{([0-9A-Fa-f]+)\\}|u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([1-7][0-7]{0,2}|[0-7]{2,3})|(['\"tbrnfv0\\\\]))|\\\\U([0-9A-Fa-f]{8})/g;\nvar usualEscapeSequences = {\n '0': '\\0',\n 'b': '\\b',\n 'f': '\\f',\n 'n': '\\n',\n 'r': '\\r',\n 't': '\\t',\n 'v': '\\v',\n '\\'': '\\'',\n '\"': '\"',\n '\\\\': '\\\\'\n};\n\nvar fromHex = function fromHex(str) {\n return String.fromCodePoint(parseInt(str, 16));\n};\n\nvar fromOct = function fromOct(str) {\n return String.fromCodePoint(parseInt(str, 8));\n};\n\nvar _default = function _default(string) {\n return string.replace(jsEscapeRegex, function (_, __, varHex, longHex, shortHex, octal, specialCharacter, python) {\n if (varHex !== undefined) {\n return fromHex(varHex);\n } else if (longHex !== undefined) {\n return fromHex(longHex);\n } else if (shortHex !== undefined) {\n return fromHex(shortHex);\n } else if (octal !== undefined) {\n return fromOct(octal);\n } else if (python !== undefined) {\n return fromHex(python);\n } else {\n return usualEscapeSequences[specialCharacter];\n }\n });\n};\n\nexports.default = _default;\nmodule.exports = exports.default;","/*! https://mths.be/utf8js v3.0.0 by @mathias */\n;(function(root) {\n\n\tvar stringFromCharCode = String.fromCharCode;\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2decode(string) {\n\t\tvar output = [];\n\t\tvar counter = 0;\n\t\tvar length = string.length;\n\t\tvar value;\n\t\tvar extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2encode(array) {\n\t\tvar length = array.length;\n\t\tvar index = -1;\n\t\tvar value;\n\t\tvar output = '';\n\t\twhile (++index < length) {\n\t\t\tvalue = array[index];\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t}\n\t\treturn output;\n\t}\n\n\tfunction checkScalarValue(codePoint) {\n\t\tif (codePoint >= 0xD800 && codePoint <= 0xDFFF) {\n\t\t\tthrow Error(\n\t\t\t\t'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +\n\t\t\t\t' is not a scalar value'\n\t\t\t);\n\t\t}\n\t}\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction createByte(codePoint, shift) {\n\t\treturn stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);\n\t}\n\n\tfunction encodeCodePoint(codePoint) {\n\t\tif ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence\n\t\t\treturn stringFromCharCode(codePoint);\n\t\t}\n\t\tvar symbol = '';\n\t\tif ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);\n\t\t}\n\t\telse if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence\n\t\t\tcheckScalarValue(codePoint);\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\telse if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);\n\t\t\tsymbol += createByte(codePoint, 12);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\tsymbol += stringFromCharCode((codePoint & 0x3F) | 0x80);\n\t\treturn symbol;\n\t}\n\n\tfunction utf8encode(string) {\n\t\tvar codePoints = ucs2decode(string);\n\t\tvar length = codePoints.length;\n\t\tvar index = -1;\n\t\tvar codePoint;\n\t\tvar byteString = '';\n\t\twhile (++index < length) {\n\t\t\tcodePoint = codePoints[index];\n\t\t\tbyteString += encodeCodePoint(codePoint);\n\t\t}\n\t\treturn byteString;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction readContinuationByte() {\n\t\tif (byteIndex >= byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tvar continuationByte = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\tif ((continuationByte & 0xC0) == 0x80) {\n\t\t\treturn continuationByte & 0x3F;\n\t\t}\n\n\t\t// If we end up here, it’s not a continuation byte\n\t\tthrow Error('Invalid continuation byte');\n\t}\n\n\tfunction decodeSymbol() {\n\t\tvar byte1;\n\t\tvar byte2;\n\t\tvar byte3;\n\t\tvar byte4;\n\t\tvar codePoint;\n\n\t\tif (byteIndex > byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tif (byteIndex == byteCount) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Read first byte\n\t\tbyte1 = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\t// 1-byte sequence (no continuation bytes)\n\t\tif ((byte1 & 0x80) == 0) {\n\t\t\treturn byte1;\n\t\t}\n\n\t\t// 2-byte sequence\n\t\tif ((byte1 & 0xE0) == 0xC0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x1F) << 6) | byte2;\n\t\t\tif (codePoint >= 0x80) {\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 3-byte sequence (may include unpaired surrogates)\n\t\tif ((byte1 & 0xF0) == 0xE0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;\n\t\t\tif (codePoint >= 0x0800) {\n\t\t\t\tcheckScalarValue(codePoint);\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 4-byte sequence\n\t\tif ((byte1 & 0xF8) == 0xF0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tbyte4 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |\n\t\t\t\t(byte3 << 0x06) | byte4;\n\t\t\tif (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {\n\t\t\t\treturn codePoint;\n\t\t\t}\n\t\t}\n\n\t\tthrow Error('Invalid UTF-8 detected');\n\t}\n\n\tvar byteArray;\n\tvar byteCount;\n\tvar byteIndex;\n\tfunction utf8decode(byteString) {\n\t\tbyteArray = ucs2decode(byteString);\n\t\tbyteCount = byteArray.length;\n\t\tbyteIndex = 0;\n\t\tvar codePoints = [];\n\t\tvar tmp;\n\t\twhile ((tmp = decodeSymbol()) !== false) {\n\t\t\tcodePoints.push(tmp);\n\t\t}\n\t\treturn ucs2encode(codePoints);\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\troot.version = '3.0.0';\n\troot.encode = utf8encode;\n\troot.decode = utf8decode;\n\n}(typeof exports === 'undefined' ? this.utf8 = {} : exports));\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\"use strict\";\n\nconst Lexer = require(\"lex\");\nconst unescapeJs = require(\"unescape-js\");\nconst utf8 = require(\"utf8\");\n\n// terminals\nconst LEX_KV = 0;\nconst LEX_KVLIST = 1;\nconst LEX_VLIST = 2;\nconst LEX_BOOLEAN = 3;\nconst LEX_COVALUE = 4;\nconst LEX_CVALUE = 5;\nconst LEX_FLOAT = 6;\nconst LEX_INT = 7;\nconst LEX_KEY = 8;\nconst LEX_LIST = 9;\nconst LEX_OBJ = 10;\nconst LEX_QUOTE = 11;\nconst LEX_RB = 12;\nconst LEX_RCB = 13;\nconst LEX_TOKEN = 14;\nconst LEX_VALUE = 15;\n\n// non-terminals\nconst LEX_COLON = -1;\nconst LEX_COMMA = -2;\nconst LEX_LCB = -3;\nconst LEX_LB = -4;\nconst LEX_DOT = -5;\n\n\nconst lexMap = {\n \":\": {type: LEX_COLON},\n \",\": {type: LEX_COMMA},\n \"{\": {type: LEX_LCB},\n \"}\": {type: LEX_RCB},\n \"[\": {type: LEX_LB},\n \"]\": {type: LEX_RB},\n \".\": {type: LEX_DOT} // TODO: remove?\n};\n\nconst lexSpc = [\n [/\\s*:\\s*/, LEX_COLON],\n [/\\s*,\\s*/, LEX_COMMA],\n [/\\s*{\\s*/, LEX_LCB],\n [/\\s*}\\s*/, LEX_RCB],\n [/\\s*\\[\\s*/, LEX_LB],\n [/\\s*\\]\\s*/, LEX_RB],\n [/\\s*\\.\\s*/, LEX_DOT] // TODO: remove?\n];\n\nfunction parseString(str) {\n // unescape-js doesn't cover the \\/ case, but we will here.\n str = str.replace(/\\\\\\//, '/');\n return unescapeJs(str);\n}\n\n\nfunction getLexer(string) {\n let lexer = new Lexer();\n\n let col = 0;\n let row = 0;\n \n lexer.addRule(/\"((?:\\\\.|[^\"])*?)($|\")/, (lexeme, txt) => {\n col += lexeme.length;\n return {type: LEX_QUOTE, value: parseString(txt), row, col, single: false};\n });\n\n lexer.addRule(/'((?:\\\\.|[^'])*?)($|'|(\",?[ \\t]*\\n))/, (lexeme, txt) => {\n col += lexeme.length;\n return {type: LEX_QUOTE, value: parseString(txt), row, col, single: true};\n });\n\n // floats with a dot\n lexer.addRule(/[\\-0-9]*\\.[0-9]*([eE][\\+\\-]?)?[0-9]*(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_FLOAT, value: parseFloat(lexeme), row, col};\n });\n\n // floats without a dot but with e notation\n lexer.addRule(/\\-?[0-9]+([eE][\\+\\-]?)[0-9]*(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_FLOAT, value: parseFloat(lexeme), row, col};\n });\n \n lexer.addRule(/\\-?[0-9]+(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_INT, value: parseInt(lexeme), row, col};\n });\n\n lexSpc.forEach(item => {\n lexer.addRule(item[0], lexeme => {\n col += lexeme.length;\n return {type: item[1], value: lexeme, row, col};\n });\n });\n\n lexer.addRule(/\\s/, lexeme => {\n // chomp whitespace...\n if (lexeme == \"\\n\") {\n col = 0;\n row++;\n } else {\n col += lexeme.length;\n }\n });\n\n \n lexer.addRule(/\\S[ \\t]*/, lexeme => {\n col += lexeme.length;\n \n let lt = LEX_TOKEN;\n let val = lexeme;\n \n return {type: lt, value: val, row, col};\n });\n \n\n\n\n lexer.setInput(string);\n\n return lexer;\n}\n\n\n\nmodule.exports.lexString = lexString;\nfunction lexString(str, emit) {\n let lex = getLexer(str);\n\n let token = \"\";\n while ((token = lex.lex())) {\n emit(token);\n }\n \n}\n\nmodule.exports.getAllTokens = getAllTokens;\nfunction getAllTokens(str) {\n let arr = [];\n let emit = function (i) {\n arr.push(i);\n };\n\n lexString(str, emit);\n\n return arr;\n}\n\n\n\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\"use strict\";\n\nlet lexer = require(\"./lexer\");\n\n// terminals\nconst LEX_KV = 0;\nconst LEX_KVLIST = 1;\nconst LEX_VLIST = 2;\nconst LEX_BOOLEAN = 3;\nconst LEX_COVALUE = 4;\nconst LEX_CVALUE = 5;\nconst LEX_FLOAT = 6;\nconst LEX_INT = 7;\nconst LEX_KEY = 8;\nconst LEX_LIST = 9;\nconst LEX_OBJ = 10;\nconst LEX_QUOTE = 11;\nconst LEX_RB = 12;\nconst LEX_RCB = 13;\nconst LEX_TOKEN = 14;\nconst LEX_VALUE = 15;\n\n// non-terminals\nconst LEX_COLON = -1;\nconst LEX_COMMA = -2;\nconst LEX_LCB = -3;\nconst LEX_LB = -4;\nconst LEX_DOT = -5;\n\nfunction extendArray(arr) {\n if (arr.peek == null) {\n Object.defineProperty(arr, 'peek', {\n enumerable: false,\n value: function() {\n return this[this.length - 1];\n }\n });\n }\n if (arr.last == null) {\n Object.defineProperty(arr, 'last', {\n enumerable: false,\n value: function(i) {\n return this[this.length - (1 + i)];\n }\n });\n }\n}\n\nfunction is(obj, prop) {\n return (obj && obj.hasOwnProperty(\"type\") && obj.type == prop);\n}\n\nfunction log(str) {\n //console.log(str);\n}\n\n\nmodule.exports.parse = parse;\nfunction parse(text, dupKeys) {\n let stack = [];\n\n let tokens = [];\n\n extendArray(stack);\n extendArray(tokens);\n\n let emit = function(t) {\n tokens.push(t);\n };\n\n lexer.lexString(text, emit);\n\n // ensure that if we started with a LB or LCB, we end with a\n // RB or RCB.\n if (tokens[0].type == LEX_LB && tokens.last(0).type != LEX_RB) {\n tokens.push({ type: LEX_RB, value: \"]\", row: -1, col: -1});\n }\n\n if (tokens[0].type == LEX_LCB && tokens.last(0).type != LEX_RCB) {\n tokens.push({ type: LEX_RCB, value: \"}\", row: -1, col: -1});\n }\n\n for (let i = 0; i < tokens.length; i++) {\n log(\"Shifting \" + tokens[i].type);\n stack.push(tokens[i]);\n log(stack);\n log(\"Reducing...\");\n while (reduce(stack)) {\n log(stack);\n log(\"Reducing...\");\n }\n }\n\n // if everything parsed into a KV list, assume it was an object missing the starting\n // \"{\" and ending \"}\"\n if (stack.length == 1 && stack[0].type == LEX_KVLIST) {\n log(\"Pre-compile error fix 1\");\n stack = [{type: LEX_OBJ, value: stack[0].value}];\n }\n\n return compileOST(stack[0], dupKeys);\n\n}\n\nfunction reduce(stack) {\n let next = stack.pop();\n\n switch(next.type) {\n case LEX_KEY:\n if (next.value.trim() == \"true\") {\n log(\"Rule 5\");\n stack.push({'type': LEX_BOOLEAN, 'value': \"true\"});\n return true;\n }\n\n\n if (next.value.trim() == \"false\") {\n log(\"Rule 6\");\n stack.push({'type': LEX_BOOLEAN, 'value': \"false\"});\n return true;\n }\n\n if (next.value.trim() == \"null\") {\n log(\"Rule 7\");\n stack.push({'type': LEX_VALUE, 'value': null});\n return true;\n }\n break;\n\n case LEX_TOKEN:\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Rule 11a\");\n stack.peek().value += next.value;\n return true;\n }\n\n log(\"Rule 11c\");\n stack.push({type: LEX_KEY, value: next.value });\n return true;\n\n\n case LEX_INT:\n if (is(next, LEX_INT) && is(stack.peek(), LEX_KEY)) {\n log(\"Rule 11b\");\n stack.peek().value += next.value;\n return true;\n }\n\n log(\"Rule 11f\");\n next.type = LEX_VALUE;\n stack.push(next);\n return true;\n\n\n case LEX_QUOTE:\n log(\"Rule 11d\");\n next.type = LEX_VALUE;\n next.value = next.value;\n stack.push(next);\n return true;\n\n\n case LEX_BOOLEAN:\n log(\"Rule 11e\");\n next.type = LEX_VALUE;\n\n if (next.value == \"true\") {\n next.value = true;\n } else {\n next.value = false;\n }\n\n stack.push(next);\n return true;\n\n\n case LEX_FLOAT:\n log(\"Rule 11g\");\n next.type = LEX_VALUE;\n stack.push(next);\n return true;\n\n case LEX_VALUE:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12\");\n next.type = LEX_CVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13\");\n next.type = LEX_COVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_VALUE)) {\n log(\"Error rule 1\");\n let middleVal = stack.pop();\n stack.peek().value += '\"' + middleVal.value + '\"';\n stack.peek().value += next.value;\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_VLIST)) {\n log(\"Error rule 2\");\n let middleVal = stack.pop();\n let oldLastVal = stack.peek().value.pop();\n oldLastVal += '\"' + middleVal.value + '\"';\n oldLastVal += next.value;\n \n stack.peek().value.push(oldLastVal);\n \n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_KVLIST)) {\n log(\"Error rule 3\");\n let middleVal = stack.pop();\n let oldLastVal = stack.peek().value.pop();\n const qChar = next.single ? \"'\" : '\"';\n \n oldLastVal.value += qChar + middleVal.value + qChar;\n oldLastVal.value += next.value;\n \n stack.peek().value.push(oldLastVal);\n \n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Error rule 4\");\n let keyValue = stack.pop().value;\n next.value = keyValue + next.value;\n stack.push(next);\n return true;\n }\n\n break;\n\n case LEX_LIST:\n if (is(next, LEX_LIST) && is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12a\");\n next.type = LEX_CVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13a\");\n next.type = LEX_COVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n break;\n\n case LEX_OBJ:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12b\");\n let toPush = {'type': LEX_CVALUE, 'value': next};\n stack.pop();\n stack.push(toPush);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13b\");\n let toPush = {'type': LEX_COVALUE, 'value': next};\n stack.pop();\n stack.push(toPush);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Error rule 9\");\n let key = stack.pop();\n stack.push({'type': LEX_KV, 'key': key.value.trim(), 'value': next});\n return true;\n }\n \n break;\n\n case LEX_CVALUE:\n if (is(stack.peek(), LEX_VLIST)) {\n log(\"Rule 14\");\n stack.peek().value.push(next.value);\n return true;\n }\n\n\n log(\"Rule 15\");\n stack.push({'type': LEX_VLIST, 'value': [next.value]});\n return true;\n\n case LEX_VLIST:\n if (is(stack.peek(), LEX_VALUE)) {\n log(\"Rule 15a\");\n next.value.unshift(stack.peek().value);\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_LIST)) {\n log(\"Rule 15b\");\n next.value.unshift(stack.peek().value);\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_OBJ)) {\n log(\"Rule 15c\");\n next.value.unshift(stack.peek());\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && (stack.last(1), LEX_COMMA)) {\n log(\"Error rule 7\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push(next);\n\n return true;\n }\n\n if (is(stack.peek(), LEX_VLIST)) {\n log(\"Error rule 8\");\n stack.peek().value.push(next.value[0]);\n return true;\n }\n break;\n\n case LEX_COVALUE:\n\n if (is(stack.peek(), LEX_KEY) || is(stack.peek(), LEX_VALUE) || is(stack.peek(), LEX_VLIST)) {\n log(\"Rule 16\");\n let key = stack.pop();\n stack.push({'type': LEX_KV, 'key': key.value, 'value': next.value});\n return true;\n }\n\n\n throw new Error(\"Got a :value that can't be handled at line \" +\n next.row + \":\" + next.col);\n\n case LEX_KV:\n if (is(stack.last(0), LEX_COMMA) && is(stack.last(1), LEX_KVLIST)) {\n log(\"Rule 17\");\n stack.last(1).value.push(next);\n stack.pop();\n return true;\n }\n\n log(\"Rule 18\");\n stack.push({'type': LEX_KVLIST, 'value': [next]});\n return true;\n\n case LEX_KVLIST:\n if (is(stack.peek(), LEX_KVLIST)) {\n log(\"Rule 17a\");\n next.value.forEach(function (i) {\n stack.peek().value.push(i);\n });\n return true;\n }\n\n break;\n\n case LEX_RB:\n if (is(stack.peek(), LEX_VLIST) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 19\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_LIST, 'value': l.value});\n return true;\n }\n\n if (is(stack.peek(), LEX_LIST) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 19b\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_LIST, 'value': [l.value]});\n return true;\n }\n\n if (is(stack.peek(), LEX_LB)) {\n log(\"Rule 22\");\n stack.pop();\n stack.push({type: LEX_LIST, 'value': []});\n return true;\n }\n\n if (is(stack.peek(), LEX_VALUE) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 23\");\n let val = stack.pop().value;\n stack.pop();\n stack.push({type: LEX_LIST, 'value': [val]});\n return true;\n }\n\n if (is(stack.peek(), LEX_OBJ) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 23b\");\n let val = stack.pop();\n stack.pop();\n stack.push({type: LEX_LIST, 'value': [val]});\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_COMMA)) {\n log(\"Error rule 5\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push({type: LEX_RB});\n return true;\n }\n\n \n if (is(stack.peek(), LEX_COMMA) && (\n is(stack.last(1), LEX_KEY)\n || is(stack.last(1), LEX_OBJ)\n || is(stack.last(1), LEX_VALUE))\n ) {\n log(\"Error rule 5a\");\n stack.pop();\n //let l = stack.pop();\n //stack.push({type: LEX_VALUE, 'value': l.value});\n stack.push({type: LEX_RB, 'value': ']'});\n log(\"Start subreduce...\");\n log(\"Content: \" + JSON.stringify(stack));\n while(reduce(stack));\n log(\"End subreduce\");\n\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_LB)) {\n log(\"Error rule 5b\");\n let v = stack.pop();\n stack.pop();\n stack.push({type: LEX_LIST, value: [v.value]});\n return true;\n }\n\n if (is(stack.peek(), LEX_COMMA) && is(stack.last(1), LEX_VLIST)) {\n log(\"Error rule 5c\");\n stack.pop();\n stack.push({type: LEX_RB});\n log(\"Start subreduce...\");\n log(\"Content: \" + JSON.stringify(stack));\n while(reduce(stack));\n log(\"End subreduce\");\n\n return true;\n }\n\n break;\n\n case LEX_RCB:\n if (is(stack.peek(), LEX_KVLIST) && is(stack.last(1), LEX_LCB)) {\n log(\"Rule 20\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_OBJ, 'value': l.value});\n return true;\n }\n\n if (is(stack.peek(), LEX_LCB)) {\n log(\"Rule 21\");\n stack.pop();\n stack.push({type: LEX_OBJ, 'value': null});\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_COLON)) {\n log(\"Error rule 4a\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push({type: LEX_RCB});\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Error rule 4b\");\n stack.push({type: LEX_VALUE, value: null});\n\n log(\"Starting subreduce...\");\n while (reduce(stack));\n log(\"End subreduce.\");\n \n stack.push({type: LEX_RCB});\n return true;\n }\n\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Error rule 10a\");\n stack.pop();\n stack.push({type: LEX_RCB});\n return true;\n }\n \n throw new Error(\"Found } that I can't handle at line \" +\n next.row + \":\" + next.col);\n\n \n case LEX_COMMA:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Comma error rule 1\");\n // do nothing -- so don't push the extra comma onto the stack\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Comma error rule 2\");\n const key = stack.pop();\n stack.push({type: LEX_VALUE, value: key.value});\n \n log(\"Starting subreduce...\");\n while (reduce(stack));\n log (\"End subreduce.\");\n \n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Comma error rule 3\");\n stack.push({type: LEX_VALUE, value: null});\n \n log(\"Starting subreduce...\");\n while (reduce(stack));\n log (\"End subreduce.\");\n \n stack.push(next);\n return true;\n }\n\n }\n\n\n stack.push(next);\n return false;\n}\n\n\n\nfunction compileOST(tree, dupKeys) {\n let rawTypes = [\"boolean\", \"number\", \"string\"];\n\n if (rawTypes.indexOf((typeof tree)) != -1)\n return tree;\n\n if (tree === null)\n return null;\n\n if (Array.isArray(tree)) {\n let toR = [];\n while (tree.length > 0)\n toR.unshift(compileOST(tree.pop()));\n return toR;\n }\n \n\n if (is(tree, LEX_OBJ)) {\n let toR = {};\n if (tree.value === null)\n return {};\n tree.value.forEach(function (i) {\n const key = i.key;\n const val = compileOST(i.value);\n\n if (dupKeys && key in toR) {\n toR[key] = {\n \"value\": toR[key],\n \"next\": val\n };\n } else {\n toR[key] = val;\n }\n });\n return toR;\n }\n\n if (is(tree, LEX_LIST)) {\n return compileOST(tree.value);\n }\n\n // it must be a value\n return tree.value;\n}\n\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\n\n\"use strict\";\n\nlet parser = require('./parser');\n\nmodule.exports.parse = parse;\nfunction parse(text, config) {\n let fallback = true;\n let duplicateKeys = false;\n\n if (config) {\n if ((\"fallback\" in config) && config[fallback] === false) {\n fallback = false;\n }\n\n duplicateKeys = \"duplicateKeys\" in config && config[\"duplicateKeys\"] === true;\n }\n\n try {\n return parser.parse(text, duplicateKeys);\n } catch (e) {\n // our parser threw an error! see if the JSON was valid...\n /* istanbul ignore next */\n if (fallback === false) {\n throw e;\n }\n \n try {\n let json = JSON.parse(text);\n // if we didn't throw, it was valid JSON!\n /* istanbul ignore next */\n console.warn(\"dirty-json got valid JSON that failed with the custom parser. We're returning the valid JSON, but please file a bug report here: https://github.com/RyanMarcus/dirty-json/issues -- the JSON that caused the failure was: \" + text);\n\n /* istanbul ignore next */\n return json;\n } catch (json_error) {\n throw e;\n }\n\n }\n}\n","import assert from 'node:assert';\nimport { AIResponseFormat, type AIUsageInfo } from '@/types';\nimport { Anthropic } from '@anthropic-ai/sdk';\nimport {\n DefaultAzureCredential,\n getBearerTokenProvider,\n} from '@azure/identity';\nimport { ifInBrowser } from '@midscene/shared/utils';\nimport dJSON from 'dirty-json';\nimport OpenAI, { AzureOpenAI } from 'openai';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { SocksProxyAgent } from 'socks-proxy-agent';\nimport {\n ANTHROPIC_API_KEY,\n AZURE_OPENAI_API_VERSION,\n AZURE_OPENAI_DEPLOYMENT,\n AZURE_OPENAI_ENDPOINT,\n AZURE_OPENAI_KEY,\n MIDSCENE_API_TYPE,\n MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON,\n MIDSCENE_AZURE_OPENAI_SCOPE,\n MIDSCENE_DEBUG_AI_PROFILE,\n MIDSCENE_LANGSMITH_DEBUG,\n MIDSCENE_MODEL_NAME,\n MIDSCENE_OPENAI_INIT_CONFIG_JSON,\n MIDSCENE_OPENAI_SOCKS_PROXY,\n MIDSCENE_USE_ANTHROPIC_SDK,\n MIDSCENE_USE_AZURE_OPENAI,\n OPENAI_API_KEY,\n OPENAI_BASE_URL,\n OPENAI_MAX_TOKENS,\n OPENAI_USE_AZURE,\n getAIConfig,\n getAIConfigInJson,\n} from '../../env';\nimport { AIActionType } from '../common';\nimport { findElementSchema } from '../prompt/llm-locator';\nimport { planSchema } from '../prompt/llm-planning';\nimport { assertSchema } from '../prompt/util';\n\nexport function checkAIConfig(preferVendor?: 'openAI') {\n if (preferVendor && preferVendor !== 'openAI') return false;\n if (getAIConfig(OPENAI_API_KEY)) return true;\n if (getAIConfig(MIDSCENE_USE_AZURE_OPENAI)) return true;\n if (getAIConfig(ANTHROPIC_API_KEY)) return true;\n\n return Boolean(getAIConfig(MIDSCENE_OPENAI_INIT_CONFIG_JSON));\n}\n\n// default model\nconst defaultModel = 'gpt-4o-2024-08-06';\nexport function getModelName() {\n let modelName = defaultModel;\n const nameInConfig = getAIConfig(MIDSCENE_MODEL_NAME);\n if (nameInConfig) {\n modelName = nameInConfig;\n }\n return modelName;\n}\n\nasync function createChatClient({\n AIActionTypeValue,\n}: {\n AIActionTypeValue: AIActionType;\n}): Promise<{\n completion: OpenAI.Chat.Completions;\n style: 'openai' | 'anthropic';\n}> {\n let openai: OpenAI | AzureOpenAI | undefined;\n const extraConfig = getAIConfigInJson(MIDSCENE_OPENAI_INIT_CONFIG_JSON);\n\n const socksProxy = getAIConfig(MIDSCENE_OPENAI_SOCKS_PROXY);\n const socksAgent = socksProxy ? new SocksProxyAgent(socksProxy) : undefined;\n\n if (getAIConfig(OPENAI_USE_AZURE)) {\n // this is deprecated\n openai = new AzureOpenAI({\n baseURL: getAIConfig(OPENAI_BASE_URL),\n apiKey: getAIConfig(OPENAI_API_KEY),\n httpAgent: socksAgent,\n ...extraConfig,\n dangerouslyAllowBrowser: true,\n }) as OpenAI;\n } else if (getAIConfig(MIDSCENE_USE_AZURE_OPENAI)) {\n const extraAzureConfig = getAIConfigInJson(\n MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON,\n );\n\n // https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart?tabs=bash%2Cjavascript-key%2Ctypescript-keyless%2Cpython&pivots=programming-language-javascript#rest-api\n // keyless authentication\n const scope = getAIConfig(MIDSCENE_AZURE_OPENAI_SCOPE);\n let tokenProvider: any = undefined;\n if (scope) {\n assert(\n !ifInBrowser,\n 'Azure OpenAI is not supported in browser with Midscene.',\n );\n const credential = new DefaultAzureCredential();\n\n assert(scope, 'MIDSCENE_AZURE_OPENAI_SCOPE is required');\n tokenProvider = getBearerTokenProvider(credential, scope);\n\n openai = new AzureOpenAI({\n azureADTokenProvider: tokenProvider,\n endpoint: getAIConfig(AZURE_OPENAI_ENDPOINT),\n apiVersion: getAIConfig(AZURE_OPENAI_API_VERSION),\n deployment: getAIConfig(AZURE_OPENAI_DEPLOYMENT),\n ...extraConfig,\n ...extraAzureConfig,\n });\n } else {\n // endpoint, apiKey, apiVersion, deployment\n openai = new AzureOpenAI({\n apiKey: getAIConfig(AZURE_OPENAI_KEY),\n endpoint: getAIConfig(AZURE_OPENAI_ENDPOINT),\n apiVersion: getAIConfig(AZURE_OPENAI_API_VERSION),\n deployment: getAIConfig(AZURE_OPENAI_DEPLOYMENT),\n dangerouslyAllowBrowser: true,\n ...extraConfig,\n ...extraAzureConfig,\n });\n }\n } else if (!getAIConfig(MIDSCENE_USE_ANTHROPIC_SDK)) {\n openai = new OpenAI({\n baseURL: getAIConfig(OPENAI_BASE_URL),\n apiKey: getAIConfig(OPENAI_API_KEY),\n httpAgent: socksAgent,\n ...extraConfig,\n defaultHeaders: {\n ...(extraConfig?.defaultHeaders || {}),\n [MIDSCENE_API_TYPE]: AIActionTypeValue.toString(),\n },\n dangerouslyAllowBrowser: true,\n });\n }\n\n if (openai && getAIConfig(MIDSCENE_LANGSMITH_DEBUG)) {\n if (ifInBrowser) {\n throw new Error('langsmith is not supported in browser');\n }\n console.log('DEBUGGING MODE: langsmith wrapper enabled');\n const { wrapOpenAI } = await import('langsmith/wrappers');\n openai = wrapOpenAI(openai);\n }\n\n if (typeof openai !== 'undefined') {\n return {\n completion: openai.chat.completions,\n style: 'openai',\n };\n }\n\n // Anthropic\n if (getAIConfig(MIDSCENE_USE_ANTHROPIC_SDK)) {\n const apiKey = getAIConfig(ANTHROPIC_API_KEY);\n assert(apiKey, 'ANTHROPIC_API_KEY is required');\n openai = new Anthropic({\n apiKey,\n dangerouslyAllowBrowser: true,\n }) as any;\n }\n\n if (typeof openai !== 'undefined' && (openai as any).messages) {\n return {\n completion: (openai as any).messages,\n style: 'anthropic',\n };\n }\n\n throw new Error('Openai SDK or Anthropic SDK is not initialized');\n}\n\nexport async function call(\n messages: ChatCompletionMessageParam[],\n AIActionTypeValue: AIActionType,\n responseFormat?:\n | OpenAI.ChatCompletionCreateParams['response_format']\n | OpenAI.ResponseFormatJSONObject,\n): Promise<{ content: string; usage?: AIUsageInfo }> {\n const { completion, style } = await createChatClient({\n AIActionTypeValue,\n });\n const shouldPrintTiming =\n typeof getAIConfig(MIDSCENE_DEBUG_AI_PROFILE) === 'string';\n\n const maxTokens = getAIConfig(OPENAI_MAX_TOKENS);\n\n const startTime = Date.now();\n const model = getModelName();\n let content: string | undefined;\n let usage: OpenAI.CompletionUsage | undefined;\n const commonConfig = {\n temperature: 0.1,\n stream: false,\n max_tokens:\n typeof maxTokens === 'number'\n ? maxTokens\n : Number.parseInt(maxTokens || '2048', 10),\n };\n\n if (style === 'openai') {\n const result = await completion.create({\n model,\n messages,\n response_format: responseFormat,\n ...commonConfig,\n // betas: ['computer-use-2024-10-22'],\n } as any);\n shouldPrintTiming &&\n console.log(\n 'Midscene - AI call',\n model,\n result.usage,\n `${Date.now() - startTime}ms`,\n );\n assert(\n result.choices,\n `invalid response from LLM service: ${JSON.stringify(result)}`,\n );\n content = result.choices[0].message.content!;\n assert(content, 'empty content');\n usage = result.usage;\n } else if (style === 'anthropic') {\n const convertImageContent = (content: any) => {\n if (content.type === 'image_url') {\n const imgBase64 = content.image_url.url;\n assert(imgBase64, 'image_url is required');\n return {\n source: {\n type: 'base64',\n media_type: imgBase64.includes('data:image/png;base64,')\n ? 'image/png'\n : 'image/jpeg',\n data: imgBase64.split(',')[1],\n },\n type: 'image',\n };\n }\n return content;\n };\n\n const result = await completion.create({\n model,\n system: 'You are a versatile professional in software UI automation',\n messages: messages.map((m) => ({\n role: 'user',\n content: Array.isArray(m.content)\n ? (m.content as any).map(convertImageContent)\n : m.content,\n })),\n response_format: responseFormat,\n ...commonConfig,\n } as any);\n content = (result as any).content[0].text as string;\n assert(content, 'empty content');\n usage = result.usage;\n }\n\n return { content: content || '', usage };\n}\n\nexport async function callToGetJSONObject<T>(\n messages: ChatCompletionMessageParam[],\n AIActionTypeValue: AIActionType,\n): Promise<{ content: T; usage?: AIUsageInfo }> {\n // gpt-4o-2024-05-13 only supports json_object response format\n let responseFormat:\n | OpenAI.ChatCompletionCreateParams['response_format']\n | OpenAI.ResponseFormatJSONObject\n | undefined;\n\n const model = getModelName();\n\n if (model.includes('gpt-4o')) {\n switch (AIActionTypeValue) {\n case AIActionType.ASSERT:\n responseFormat = assertSchema;\n break;\n case AIActionType.INSPECT_ELEMENT:\n responseFormat = findElementSchema;\n break;\n case AIActionType.EXTRACT_DATA:\n //TODO: Currently the restriction type can only be a json subset of the constraint, and the way the extract api is used needs to be adjusted to limit the user's data to this as well\n // targetResponseFormat = extractDataSchema;\n responseFormat = { type: AIResponseFormat.JSON };\n break;\n case AIActionType.PLAN:\n responseFormat = planSchema;\n break;\n }\n\n if (model === 'gpt-4o-2024-05-13' || !responseFormat) {\n responseFormat = { type: AIResponseFormat.JSON };\n }\n }\n\n const response = await call(messages, AIActionTypeValue, responseFormat);\n assert(response, 'empty response');\n const jsonContent = safeParseJson(response.content);\n return { content: jsonContent, usage: response.usage };\n}\n\nexport function extractJSONFromCodeBlock(response: string) {\n try {\n // First, try to match a JSON object directly in the response\n const jsonMatch = response.match(/^\\s*(\\{[\\s\\S]*\\})\\s*$/);\n if (jsonMatch) {\n return jsonMatch[1];\n }\n\n // If no direct JSON object is found, try to extract JSON from a code block\n const codeBlockMatch = response.match(\n /```(?:json)?\\s*(\\{[\\s\\S]*?\\})\\s*```/,\n );\n if (codeBlockMatch) {\n return codeBlockMatch[1];\n }\n\n // If no code block is found, try to find a JSON-like structure in the text\n const jsonLikeMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (jsonLikeMatch) {\n return jsonLikeMatch[0];\n }\n } catch {}\n // If no JSON-like structure is found, return the original response\n return response;\n}\n\nexport function safeParseJson(input: string) {\n const cleanJsonString = extractJSONFromCodeBlock(input);\n // match the point\n if (cleanJsonString.match(/\\((\\d+),(\\d+)\\)/)) {\n return cleanJsonString\n .match(/\\((\\d+),(\\d+)\\)/)\n ?.slice(1)\n .map(Number);\n }\n try {\n return JSON.parse(cleanJsonString);\n } catch {}\n try {\n return dJSON.parse(cleanJsonString);\n } catch (e) {\n console.log('e:', e);\n }\n throw Error(`failed to parse json response: ${input}`);\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { NodeType } from '@midscene/shared/constants';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\n\nexport * from './yaml.d';\n\nexport interface Point {\n left: number;\n top: number;\n}\n\nexport interface Size {\n width: number; // device independent window size\n height: number;\n dpr?: number; // the scale factor of the screenshots\n}\n\nexport type Rect = Point & Size & { zoom?: number };\n\nexport abstract class BaseElement {\n abstract id: string;\n\n abstract indexId?: number; // markerId for web\n\n abstract attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n\n abstract content: string;\n\n abstract rect: Rect;\n\n abstract center: [number, number];\n\n abstract locator?: string;\n}\n\nexport interface ElementTreeNode<\n ElementType extends BaseElement = BaseElement,\n> {\n node: ElementType | null;\n children: ElementTreeNode<ElementType>[];\n}\n\nexport type AIUsageInfo = Record<string, any>;\n\n/**\n * openai\n *\n */\nexport enum AIResponseFormat {\n JSON = 'json_object',\n TEXT = 'text',\n}\n\nexport type AISingleElementResponseById = {\n id: string;\n reason?: string;\n text?: string;\n};\n\nexport type AISingleElementResponseByPosition = {\n position: {\n x: number;\n y: number;\n };\n reason: string;\n text: string;\n};\n\nexport type AISingleElementResponse = AISingleElementResponseById;\nexport interface AIElementIdResponse {\n elements: {\n id: string;\n reason?: string;\n text?: string;\n }[];\n errors?: string[];\n}\n\nexport type AIElementResponse = AIElementIdResponse;\n\nexport interface AISectionParseResponse<DataShape> {\n data: DataShape;\n sections?: LiteUISection[];\n errors?: string[];\n}\n\nexport interface AIAssertionResponse {\n pass: boolean;\n thought: string;\n}\n\n/**\n * context\n */\n\nexport abstract class UIContext<ElementType extends BaseElement = BaseElement> {\n abstract screenshotBase64: string;\n\n abstract screenshotBase64WithElementMarker?: string;\n\n // @deprecated('use tree instead')\n abstract content: ElementType[];\n\n abstract tree: ElementTreeNode<ElementType>;\n\n abstract size: Size;\n}\n\n/**\n * insight\n */\n\nexport type CallAIFn = <T>(\n messages: ChatCompletionMessageParam[],\n) => Promise<T>;\n\nexport interface InsightOptions {\n taskInfo?: Omit<InsightTaskInfo, 'durationMs'>;\n aiVendorFn?: CallAIFn;\n generateElement?: (opts: {\n content?: string;\n rect: BaseElement['rect'];\n }) => BaseElement;\n}\n\n// export interface UISection {\n// name: string;\n// description: string;\n// sectionCharacteristics: string;\n// rect: Rect;\n// content: BaseElement[];\n// }\n\nexport type EnsureObject<T> = { [K in keyof T]: any };\n\nexport type InsightAction = 'locate' | 'extract' | 'assert';\n\nexport type InsightExtractParam = string | Record<string, string>;\n\nexport interface InsightTaskInfo {\n durationMs: number;\n formatResponse?: string;\n rawResponse?: string;\n usage?: AIUsageInfo;\n}\n\nexport interface DumpMeta {\n sdkVersion: string;\n logTime: number;\n model_name: string;\n model_description?: string;\n}\n\nexport interface ReportDumpWithAttributes {\n dumpString: string;\n attributes?: Record<string, any>;\n}\n\nexport interface InsightDump extends DumpMeta {\n type: 'locate' | 'extract' | 'assert';\n logId: string;\n context: UIContext;\n userQuery: {\n element?: string;\n dataDemand?: InsightExtractParam;\n sections?: Record<string, string>;\n assertion?: string;\n }; // ?\n quickAnswer?: Partial<AISingleElementResponse> | null;\n matchedSection: [];\n matchedElement: BaseElement[];\n data: any;\n assertionPass?: boolean;\n assertionThought?: string;\n taskInfo: InsightTaskInfo;\n error?: string;\n}\n\nexport type PartialInsightDumpFromSDK = Omit<\n InsightDump,\n 'sdkVersion' | 'logTime' | 'logId' | 'model_name'\n>;\n\nexport type DumpSubscriber = (dump: InsightDump) => Promise<void> | void;\n\n// intermediate variables to optimize the return value by AI\nexport interface LiteUISection {\n name: string;\n description: string;\n sectionCharacteristics: string;\n textIds: string[];\n}\n\nexport type ElementById = (id: string) => BaseElement | null;\n\nexport type InsightAssertionResponse = AIAssertionResponse;\n\n/**\n * agent\n */\n\nexport type OnTaskStartTip = (tip: string) => Promise<void> | void;\n\nexport interface AgentWaitForOpt {\n checkIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface AgentAssertOpt {\n keepRawResponse?: boolean;\n}\n\n/**\n * planning\n *\n */\n\nexport interface PlanningLocateParam {\n id?: string;\n position?: {\n x: number;\n y: number;\n };\n prompt: string;\n}\n\nexport interface PlanningAction<ParamType = any> {\n thought?: string;\n type:\n | 'Locate'\n | 'Tap'\n | 'Drag'\n | 'Hover'\n | 'Input'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Error'\n | 'FalsyConditionStatement'\n | 'Assert'\n | 'AssertWithoutThrow'\n | 'Sleep'\n | 'Finished';\n param: ParamType;\n locate: PlanningLocateParam | null;\n}\n\nexport interface PlanningAIResponse {\n actions: PlanningAction[];\n taskWillBeAccomplished: boolean;\n furtherPlan?: PlanningFurtherPlan | null;\n error?: string;\n}\n\nexport interface PlanningFurtherPlan {\n whatToDoNext: string;\n whatHaveDone: string;\n}\nexport type PlanningActionParamPlan = PlanningFurtherPlan;\n\nexport type PlanningActionParamTap = null;\nexport type PlanningActionParamHover = null;\nexport interface PlanningActionParamInputOrKeyPress {\n value: string;\n}\nexport interface PlanningActionParamScroll {\n direction: 'down' | 'up' | 'right' | 'left';\n scrollType: 'once' | 'untilBottom' | 'untilTop' | 'untilRight' | 'untilLeft';\n distance: null | number;\n}\n\nexport interface PlanningActionParamAssert {\n assertion: string;\n}\n\nexport interface PlanningActionParamSleep {\n timeMs: number;\n}\n\nexport interface PlanningActionParamError {\n thought: string;\n}\n\nexport type PlanningActionParamWaitFor = AgentWaitForOpt & {\n assertion: string;\n};\n/**\n * misc\n */\n\nexport interface Color {\n name: string;\n hex: string;\n}\n\nexport interface BaseAgentParserOpt {\n selector?: string;\n ignoreMarker?: boolean;\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PuppeteerParserOpt extends BaseAgentParserOpt {}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PlaywrightParserOpt extends BaseAgentParserOpt {}\n\n/*\naction\n*/\nexport interface ExecutionTaskProgressOptions {\n onTaskStart?: (task: ExecutionTask) => Promise<void> | void;\n}\n\nexport interface ExecutionRecorderItem {\n type: 'screenshot';\n ts: number;\n screenshot?: string;\n timing?: string;\n}\n\nexport type ExecutionTaskType = 'Planning' | 'Insight' | 'Action' | 'Assertion';\n\nexport interface ExecutorContext {\n task: ExecutionTask;\n element?: BaseElement | null;\n}\n\nexport interface TaskCacheInfo {\n hit: boolean;\n}\n\nexport interface ExecutionTaskApply<\n Type extends ExecutionTaskType = any,\n TaskParam = any,\n TaskOutput = any,\n TaskLog = any,\n> {\n type: Type;\n subType?: string;\n param?: TaskParam;\n thought?: string;\n locate: PlanningLocateParam | null;\n quickAnswer?: AISingleElementResponse | null;\n executor: (\n param: TaskParam,\n context: ExecutorContext,\n ) => // biome-ignore lint/suspicious/noConfusingVoidType: <explanation>\n | Promise<ExecutionTaskReturn<TaskOutput, TaskLog> | undefined | void>\n | undefined\n | void;\n}\n\nexport interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {\n output?: TaskOutput;\n log?: TaskLog;\n recorder?: ExecutionRecorderItem[];\n cache?: TaskCacheInfo;\n}\n\nexport type ExecutionTask<\n E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<\n any,\n any,\n any\n >,\n> = E &\n ExecutionTaskReturn<\n E extends ExecutionTaskApply<any, any, infer TaskOutput, any>\n ? TaskOutput\n : unknown,\n E extends ExecutionTaskApply<any, any, any, infer TaskLog>\n ? TaskLog\n : unknown\n > & {\n status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';\n error?: string;\n errorStack?: string;\n timing?: {\n start: number;\n end?: number;\n cost?: number;\n aiCost?: number;\n };\n };\n\nexport interface ExecutionDump extends DumpMeta {\n name: string;\n description?: string;\n tasks: ExecutionTask[];\n}\n\n/*\ntask - insight-locate\n*/\nexport type ExecutionTaskInsightLocateParam = PlanningLocateParam;\n\nexport interface ExecutionTaskInsightLocateOutput {\n element: BaseElement | null;\n}\n\nexport interface ExecutionTaskInsightDumpLog {\n dump?: InsightDump;\n}\n\nexport type ExecutionTaskInsightLocateApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightLocateParam,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightLocate =\n ExecutionTask<ExecutionTaskInsightLocateApply>;\n\n/*\ntask - insight-query\n*/\nexport interface ExecutionTaskInsightQueryParam {\n dataDemand: InsightExtractParam;\n}\n\nexport interface ExecutionTaskInsightQueryOutput {\n data: any;\n}\n\nexport type ExecutionTaskInsightQueryApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightQueryParam,\n any,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightQuery =\n ExecutionTask<ExecutionTaskInsightQueryApply>;\n\n/*\ntask - assertion\n*/\nexport interface ExecutionTaskInsightAssertionParam {\n assertion: string;\n}\n\nexport type ExecutionTaskInsightAssertionApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightAssertionParam,\n InsightAssertionResponse,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightAssertion =\n ExecutionTask<ExecutionTaskInsightAssertionApply>;\n\n/*\ntask - action (i.e. interact) \n*/\nexport type ExecutionTaskActionApply<ActionParam = any> = ExecutionTaskApply<\n 'Action',\n ActionParam,\n void,\n void\n>;\n\nexport type ExecutionTaskAction = ExecutionTask<ExecutionTaskActionApply>;\n\n/*\ntask - planning\n*/\n\nexport type ExecutionTaskPlanningApply = ExecutionTaskApply<\n 'Planning',\n {\n userPrompt: string;\n whatHaveDone?: string;\n originalPrompt?: string;\n },\n PlanningAIResponse\n>;\n\nexport type ExecutionTaskPlanning = ExecutionTask<ExecutionTaskPlanningApply>;\n\n/*\nGrouped dump\n*/\nexport interface GroupedActionDump {\n groupName: string;\n groupDescription?: string;\n executions: ExecutionDump[];\n}\n","import assert from 'node:assert';\nimport type { AIUsageInfo } from '@/types';\n\nimport type {\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n} from 'openai/resources';\nimport { callToGetJSONObject, checkAIConfig } from './service-caller';\n\nexport type AIArgs = [\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n];\n\nexport enum AIActionType {\n ASSERT = 0,\n INSPECT_ELEMENT = 1,\n EXTRACT_DATA = 2,\n PLAN = 3,\n}\n\nexport async function callAiFn<T>(\n msgs: AIArgs,\n AIActionTypeValue: AIActionType,\n): Promise<{ content: T; usage?: AIUsageInfo }> {\n assert(\n checkAIConfig(),\n 'Cannot find config for AI model service. You should set it before using. https://midscenejs.com/model-provider.html',\n );\n\n const { content, usage } = await callToGetJSONObject<T>(\n msgs,\n AIActionTypeValue,\n );\n return { content, usage };\n}\n","import { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\nimport { systemPromptToLocateElementPosition } from './ui-tars-locator';\n\nexport function systemPromptToLocateElement() {\n if (getAIConfig(MATCH_BY_POSITION)) {\n return systemPromptToLocateElementPosition();\n }\n return `\n## Role:\nYou are an expert in software page image (2D) and page element text analysis.\n\n## Objective:\n- Identify elements in screenshots and text that match the user's description.\n- Return JSON data containing the selection reason and element ID.\n\n## Skills:\n- Image analysis and recognition\n- Multilingual text understanding\n- Software UI design and testing\n\n## Workflow:\n1. 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.\n2. Based on the user's description, locate the target element ID in the list of element descriptions and the screenshot.\n3. Found the required number of elements\n4. Return JSON data containing the selection reason and element ID.\n\n## Constraints:\n- Strictly adhere to the specified location when describing the required element; do not select elements from other locations.\n- Elements in the image with NodeType other than \"TEXT Node\" have been highlighted to identify the element among multiple non-text elements.\n- 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.\n- If no elements are found, the \"elements\" array should be empty.\n- The returned data must conform to the specified JSON format.\n- The returned value id information must use the id from element info (important: **use id not indexId, id is hash content**)\n\n## Output Format:\n\nPlease return the result in JSON format as follows:\n\n\\`\\`\\`json\n{\n \"elements\": [\n // If no matching elements are found, return an empty array []\n {\n \"reason\": \"PLACEHOLDER\", // The thought process for finding the element, replace PLACEHOLDER with your thought process\n \"text\": \"PLACEHOLDER\", // Replace PLACEHOLDER with the text of elementInfo, if none, leave empty\n \"id\": \"PLACEHOLDER\" // Replace PLACEHOLDER with the ID (important: **use id not indexId, id is hash content**) of elementInfo\n }\n // More elements...\n ],\n \"errors\": [] // Array of strings containing any error messages\n}\n\\`\\`\\`\n\n## Example:\nExample 1:\nInput Example:\n\\`\\`\\`json\n// Description: \"Shopping cart icon in the upper right corner\"\n{\n \"description\": \"PLACEHOLDER\", // Description of the target element\n \"screenshot\": \"path/screenshot.png\",\n \"text\": '{\n \"pageSize\": {\n \"width\": 400, // Width of the page\n \"height\": 905 // Height of the page\n },\n \"elementInfos\": [\n {\n \"id\": \"1231\", // ID of the element\n \"indexId\": \"0\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": { // Attributes of the element\n \"nodeType\": \"IMG Node\", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node\n \"src\": \"https://ap-southeast-3.m\",\n \"class\": \".img\"\n },\n \"content\": \"\", // Text content of the element\n \"rect\": {\n \"left\": 280, // Distance from the left side of the page\n \"top\": 8, // Distance from the top of the page\n \"width\": 44, // Width of the element\n \"height\": 44 // Height of the element\n }\n },\n {\n \"id\": \"66551\", // ID of the element\n \"indexId\": \"1\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": { // Attributes of the element\n \"nodeType\": \"IMG Node\", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node\n \"src\": \"data:image/png;base64,iVBORw0KGgoAAAANSU...\",\n \"class\": \".icon\"\n },\n \"content\": \"\", // Text content of the element\n \"rect\": {\n \"left\": 350, // Distance from the left side of the page\n \"top\": 16, // Distance from the top of the page\n \"width\": 25, // Width of the element\n \"height\": 25 // Height of the element\n }\n },\n ...\n {\n \"id\": \"12344\",\n \"indexId\": \"2\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": {\n \"nodeType\": \"TEXT Node\",\n \"class\": \".product-name\"\n },\n \"center\": [\n 288,\n 834\n ],\n \"content\": \"Mango Drink\",\n \"rect\": {\n \"left\": 188,\n \"top\": 827,\n \"width\": 199,\n \"height\": 13\n }\n },\n ...\n ]\n }\n '\n}\n\\`\\`\\`\nOutput Example:\n\\`\\`\\`json\n{\n \"elements\": [\n {\n // Describe the reason for finding this element, replace with actual value in practice\n \"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\",\n \"text\": \"\",\n // ID(**use id not indexId**) of this element, replace with actual value in practice, **use id not indexId**\n \"id\": \"1231\"\n }\n ],\n \"errors\": []\n}\n\\`\\`\\`\n \n `;\n}\n\nexport const findElementSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'find_elements',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n elements: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n reason: {\n type: 'string',\n description: 'Reason for finding this element',\n },\n text: {\n type: 'string',\n description: 'Text content of the element',\n },\n id: {\n type: 'string',\n description: 'ID of this element',\n },\n },\n required: ['reason', 'text', 'id'],\n additionalProperties: false,\n },\n description: 'List of found elements',\n },\n errors: {\n type: 'array',\n items: {\n type: 'string',\n },\n description: 'List of error messages, if any',\n },\n },\n required: ['elements', 'errors'],\n additionalProperties: false,\n },\n },\n};\n\nexport const findElementPrompt = new PromptTemplate({\n template: `\n Here is the item user want to find. Just go ahead:\n =====================================\n {{\n \"description\": \"{targetElementDescription}\",\n \"multi\": {multi}\n }}\n =====================================\n\n pageDescription: {pageDescription}\n `,\n inputVariables: ['pageDescription', 'targetElementDescription', 'multi'],\n});\n","import type { Action } from '../ui-tars-planning';\n\nexport function getTimeZoneInfo(): { timezone: string; isChina: boolean } {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const offset = -new Date().getTimezoneOffset() / 60;\n\n return {\n timezone: `UTC${offset >= 0 ? '+' : ''}${offset}`,\n isChina: timeZone === 'Asia/Shanghai',\n };\n}\n\nexport const language = getTimeZoneInfo().isChina ? 'Chinese' : 'English';\n\nexport const uiTarsPlanningPrompt = `\nYou are a GUI agent. You are given a task and your action history, with screenshots. You need to perform the next action to complete the task. \n\n## Output Format\n\\`\\`\\`\nThought: ...\nAction: ...\n\\`\\`\\`\n\n## Action Space\nclick(start_box='[x1, y1, x2, y2]')\nleft_double(start_box='[x1, y1, x2, y2]')\nright_single(start_box='[x1, y1, x2, y2]')\ndrag(start_box='[x1, y1, x2, y2]', end_box='[x3, y3, x4, y4]')\nhotkey(key='')\ntype(content='') #If you want to submit your input, use \"\\\\n\" at the end of \\`content\\`.\nscroll(start_box='[x1, y1, x2, y2]', direction='down or up or right or left')\nwait() #Sleep for 5s and take a screenshot to check for any changes.\nfinished()\ncall_user() # Submit the task and call the user when the task is unsolvable, or when you need the user's help.\n\n## Note\n- Use ${language} in \\`Thought\\` part.\n- Write a small plan and finally summarize your next action (with its target element) in one sentence in \\`Thought\\` part.\n\n## User Instruction\n`;\n\nexport const getSummary = (prediction: string) =>\n prediction\n .replace(/Reflection:[\\s\\S]*?(?=Action_Summary:|Action:|$)/g, '')\n .trim();\n","import { language } from './ui-tars-planning';\n\n// claude 3.5 sonnet computer The ability to understand the content of the image is better, Does not provide element snapshot effect\nexport function systemPromptToLocateElementPosition() {\n return `\nYou are a GUI agent. You are given a task and your action history, with screenshots. You need to perform the next action to complete the task. \n\n## Output Format\n\\`\\`\\`\nThought: ...\nAction: ...\n\\`\\`\\`\n\n## Action Space\nclick(start_box='[x1, y1, x2, y2]')\nleft_double(start_box='[x1, y1, x2, y2]')\nright_single(start_box='[x1, y1, x2, y2]')\ndrag(start_box='[x1, y1, x2, y2]', end_box='[x3, y3, x4, y4]')\nhotkey(key='')\ntype(content='') #If you want to submit your input, use \"\\\\n\" at the end of \\`content\\`.\nscroll(start_box='[x1, y1, x2, y2]', direction='down or up or right or left')\nwait() #Sleep for 5s and take a screenshot to check for any changes.\nfinished()\ncall_user() # Submit the task and call the user when the task is unsolvable, or when you need the user's help.\n\n## Note\n- Use ${language} in \\`Thought\\` part.\n- Write a small plan and finally summarize your next action (with its target element) in one sentence in \\`Thought\\` part.\n\n## User Instruction\n `;\n}\n","import { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\nimport { samplePageDescription } from './util';\n\nconst quickAnswerFormat = () => {\n const matchByPosition = getAIConfig(MATCH_BY_POSITION);\n\n const locationFormat = {\n position: {\n description:\n '\"position\": { x: number; y: number } // Represents the position of the element; replace with actual values in practice (ensure it reflects the element\\'s position)',\n format: '\"position\": { x: number; y: number }',\n sample:\n '{\"prompt\": \"the search bar\" // Use language consistent with the information on the page}',\n locateParam: `{\n \"prompt\"?: string // the description of the element to find. It can only be omitted when locate is null.\n } | null // If it's not on the page, the LocateParam should be null`,\n },\n id: {\n description:\n '\"id\": string // Represents the ID of the element; replace with actual values in practice',\n format: '\"id\": string',\n sample: `{\"id\": \"c81c4e9a33\", \"prompt\": \"the search bar\"}`,\n locateParam: `{\n \"id\": string, // the id of the element found. It should either be the id marked with a rectangle in the screenshot or the id described in the description.\n \"prompt\"?: string // the description of the element to find. It can only be omitted when locate is null.\n } | null // If it's not on the page, the LocateParam should be null`,\n },\n };\n\n const type = matchByPosition ? 'position' : 'id';\n const format = locationFormat[type];\n\n return {\n description: format.description,\n format: format.format,\n sample: format.sample,\n locateParam: format.locateParam,\n };\n};\n\nconst systemTemplate = `\n## Role\n\nYou are a versatile professional in software UI automation. Your outstanding contributions will impact the user experience of billions of users.\n\n## Objective\n\n- Decompose the instruction user asked into a series of actions\n- Locate the target element if possible\n- If the instruction cannot be accomplished, give a further plan.\n\n## Workflow\n\n1. Receive the user's element description, screenshot, and instruction.\n2. Decompose the user's task into a sequence of actions, and place it in the \\`actions\\` field. There are different types of actions (Tap / Hover / Input / KeyboardPress / Scroll / FalsyConditionStatement / Sleep). The \"About the action\" section below will give you more details.\n3. Precisely locate the target element if it's already shown in the screenshot, put the location info in the \\`locate\\` field of the action.\n4. If some target elements is not shown in the screenshot, consider the user's instruction is not feasible on this page. Follow the next steps.\n5. Consider whether the user's instruction will be accomplished after all the actions\n - If yes, set \\`taskWillBeAccomplished\\` to true\n - If no, don't plan more actions by closing the array. Get ready to reevaluate the task. Some talent people like you will handle this. Give him a clear description of what have been done and what to do next. Put your new plan in the \\`furtherPlan\\` field. The \"How to compose the \\`taskWillBeAccomplished\\` and \\`furtherPlan\\` fields\" section will give you more details.\n\n## Constraints\n\n- All the actions you composed MUST be based on the page context information you get.\n- Trust the \"What have been done\" field about the task (if any), don't repeat actions in it.\n- Respond only with valid JSON. Do not write an introduction or summary or markdown prefix like \\`\\`\\`json\\`\\`\\`.\n- If you cannot plan any action at all (i.e. empty actions array), set reason in the \\`error\\` field.\n\n## About the \\`actions\\` field\n\n### The common \\`locate\\` param\n\nThe \\`locate\\` param is commonly used in the \\`param\\` field of the action, means to locate the target element to perform the action, it follows the following scheme:\n\ntype LocateParam = {locateParam}\n\n### Supported actions\n\nEach action has a \\`type\\` and corresponding \\`param\\`. To be detailed:\n- type: 'Tap', tap the located element\n * {{ locate: LocateParam, param: null }}\n- type: 'Hover', move mouse over to the located element\n * {{ locate: LocateParam, param: null }}\n- type: 'Input', replace the value in the input field\n * {{ locate: LocateParam, param: {{ value: string }} }}\n * \\`value\\` is the final required input value based on the existing input. No matter what modifications are required, just provide the final value to replace the existing input value. \n- type: 'KeyboardPress', press a key\n * {{ param: {{ value: string }} }}\n- type: 'Scroll', scroll up or down.\n * {{ \n locate: LocateParam | null, \n param: {{ \n direction: 'down'(default) | 'up' | 'right' | 'left', \n scrollType: 'once' (default) | 'untilBottom' | 'untilTop' | 'untilRight' | 'untilLeft', \n distance: null | number \n }} \n }}\n * To scroll some specific element, put the element at the center of the region in the \\`locate\\` field. If it's a page scroll, put \\`null\\` in the \\`locate\\` field. \n * \\`param\\` is required in this action. If some fields are not specified, use direction \\`down\\`, \\`once\\` scroll type, and \\`null\\` distance.\n- type: 'FalsyConditionStatement'\n * {{ param: null }}\n * use this action when the instruction is an \"if\" statement and the condition is falsy.\n- type: 'Sleep'\n * {{ param: {{ timeMs: number }} }}\n\n## How to compose the \\`taskWillBeAccomplished\\` and \\`furtherPlan\\` fields ?\n\n\\`taskWillBeAccomplished\\` is a boolean field, means whether the task will be accomplished after all the actions.\n\n\\`furtherPlan\\` is used when the task cannot be accomplished. It follows the scheme {{ whatHaveDone: string, whatToDoNext: string }}:\n- \\`whatHaveDone\\`: a string, describe what have been done after the previous actions.\n- \\`whatToDoNext\\`: a string, describe what should be done next after the previous actions has finished. It should be a concise and clear description of the actions to be performed. Make sure you don't lose any necessary steps user asked.\n`;\n\nconst outputTemplate = `\n## Output JSON Format:\n\nThe JSON format is as follows:\n\n{{\n \"actions\": [\n {{\n \"thought\": \"Reasons for generating this task, and why this task is feasible on this page.\", // Use the same language as the user's instruction.\n \"type\": \"Tap\",\n \"param\": null,\n \"locate\": {sample} | null,\n }},\n // ... more actions\n ],\n \"taskWillBeAccomplished\": boolean,\n \"furtherPlan\": {{ \"whatHaveDone\": string, \"whatToDoNext\": string }} | null, // Use the same language as the user's instruction.\n \"error\"?: string // Use the same language as the user's instruction.\n}}\n\n## Examples\n\n### Example 1: Decompose a task\n\nWhen a user says 'Click the language switch button, wait 1s, click \"English\"', the user will give you the description like this:\n\n====================\n{pageDescription}\n====================\n\nBy viewing the page screenshot and description, you should consider this and output the JSON:\n\n* The main steps should be: tap the switch button, sleep, and tap the 'English' option \n* The language switch button is shown in the screenshot, but it's not marked with a rectangle. So we have to use the page description to find the element. By carefully checking the context information (coordinates, attributes, content, etc.), you can find the element.\n* The \"English\" option button is not shown in the screenshot now, it means it may only show after the previous actions are finished. So the last action will have a \\`null\\` value in the \\`locate\\` field. \n* The task cannot be accomplished (because we cannot see the \"English\" option now), so a \\`furtherPlan\\` field is needed.\n\n{{\n \"actions\":[\n {{\n \"type\": \"Tap\", \n \"thought\": \"Click the language switch button to open the language options.\",\n \"param\": null,\n \"locate\": {sample},\n }},\n {{\n \"type\": \"Sleep\",\n \"thought\": \"Wait for 1 second to ensure the language options are displayed.\",\n \"param\": {{ \"timeMs\": 1000 }},\n }},\n {{\n \"type\": \"Tap\",\n \"thought\": \"Locate the 'English' option in the language menu.\",\n \"param\": null, \n \"locate\": null\n }},\n ],\n \"error\": null,\n \"taskWillBeAccomplished\": false,\n \"furtherPlan\": {{\n \"whatToDoNext\": \"find the 'English' option and click on it\",\n \"whatHaveDone\": \"Click the language switch button and wait 1s\"\n }}\n}}\n\n### Example 2: Tolerate error situations only when the instruction is an \"if\" statement\n\nIf the user says \"If there is a popup, close it\", you should consider this and output the JSON:\n\n* By viewing the page screenshot and description, you cannot find the popup, so the condition is falsy.\n* The instruction itself is an \"if\" statement, it means the user can tolerate this situation, so you should leave a \\`FalsyConditionStatement\\` action.\n\n{{\n \"actions\": [{{\n \"type\": \"FalsyConditionStatement\",\n \"thought\": \"There is no popup on the page\",\n \"param\": null\n }}\n ],\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null\n}}\n\nFor contrast, if the user says \"Close the popup\" in this situation, you should consider this and output the JSON:\n\n{{\n \"actions\": [],\n \"error\": \"The instruction and page context are irrelevant, there is no popup on the page\",\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null\n}}\n\n### Example 3: When task is accomplished, don't plan more actions\n\nWhen the user ask to \"Wait 4s\", you should consider this:\n\n{{\n \"actions\": [\n {{\n \"type\": \"Sleep\",\n \"thought\": \"Wait for 4 seconds\",\n \"param\": {{ \"timeMs\": 4000 }},\n }},\n ],\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null // All steps have been included in the actions, so no further plan is needed\n}}\n\n### Example 4: What NOT to do\n\nWrong output:\n\n{{\n \"actions\":[\n {{\n \"type\": \"Tap\",\n \"thought\": \"Click the language switch button to open the language options.\",\n \"param\": null,\n \"locate\": {{\n {{\"id\": \"c81c4e9a33\"}}, // WRONG:prompt is missing\n }}\n }},\n {{\n \"type\": \"Tap\", \n \"thought\": \"Click the English option\",\n \"param\": null,\n \"locate\": null, // This means the 'English' option is not shown in the screenshot, the task cannot be accomplished\n }}\n ],\n \"taskWillBeAccomplished\": false,\n // WRONG: should not be null\n \"furtherPlan\": null,\n}}\n\nReason:\n* The \\`prompt\\` is missing in the first 'Locate' action\n* Since the option button is not shown in the screenshot, the task cannot be accomplished, so a \\`furtherPlan\\` field is needed.\n`;\n\nexport async function systemPromptToTaskPlanning() {\n const promptTemplate = new PromptTemplate({\n template: `${systemTemplate}\\n\\n${outputTemplate}`,\n inputVariables: ['pageDescription', 'sample', 'locateParam'],\n });\n\n return await promptTemplate.format({\n pageDescription: samplePageDescription,\n sample: quickAnswerFormat().sample,\n locateParam: quickAnswerFormat().locateParam,\n });\n}\n\nexport const planSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'action_items',\n strict: true,\n schema: {\n type: 'object',\n strict: true,\n properties: {\n actions: {\n type: 'array',\n items: {\n type: 'object',\n strict: true,\n properties: {\n thought: {\n type: 'string',\n description:\n 'Reasons for generating this task, and why this task is feasible on this page',\n },\n type: {\n type: 'string',\n description: 'Type of action, like \"Tap\", \"Hover\", etc.',\n },\n param: {\n anyOf: [\n { type: 'null' },\n {\n type: 'object',\n properties: { value: { type: ['string', 'number'] } },\n required: ['value'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: { timeMs: { type: ['number', 'string'] } },\n required: ['timeMs'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n direction: { type: 'string' },\n scrollType: { type: 'string' },\n distance: { type: ['number', 'string', 'null'] },\n },\n required: ['direction', 'scrollType', 'distance'],\n additionalProperties: false,\n },\n ],\n description:\n 'Parameter of the action, can be null ONLY when the type field is Tap or Hover',\n },\n locate: {\n type: ['object', 'null'],\n properties: {\n ...(getAIConfig(MATCH_BY_POSITION)\n ? {\n position: {\n type: 'object',\n properties: {\n x: { type: 'number' },\n y: { type: 'number' },\n },\n required: ['x', 'y'],\n additionalProperties: false,\n },\n }\n : {\n id: { type: 'string' },\n }),\n prompt: { type: 'string' },\n },\n required: [\n getAIConfig(MATCH_BY_POSITION) ? 'position' : 'id',\n 'prompt',\n ],\n additionalProperties: false,\n description: 'Location information for the target element',\n },\n },\n required: ['thought', 'type', 'param', 'locate'],\n additionalProperties: false,\n },\n description: 'List of actions to be performed',\n },\n taskWillBeAccomplished: {\n type: 'boolean',\n description:\n 'Whether the task will be accomplished after the actions',\n },\n furtherPlan: {\n type: ['object', 'null'],\n properties: {\n whatHaveDone: { type: 'string' },\n whatToDoNext: { type: 'string' },\n },\n required: ['whatHaveDone', 'whatToDoNext'],\n additionalProperties: false,\n description: 'Plan the task when the task cannot be accomplished',\n },\n error: {\n type: ['string', 'null'],\n description: 'Overall error messages',\n },\n },\n required: ['actions', 'taskWillBeAccomplished', 'furtherPlan', 'error'],\n additionalProperties: false,\n },\n },\n};\n\nexport const generateTaskBackgroundContext = (\n userPrompt: string,\n originalPrompt?: string,\n whatHaveDone?: string,\n) => {\n if (originalPrompt && whatHaveDone) {\n return `\n Here is the instruction:\n =====================================\n ${userPrompt}\n =====================================\n \n For your information, this is a task that some important person handed to you. Here is the original task description and what have been done after the previous actions:\n =====================================\n Original task description: ${originalPrompt}\n =====================================\n What have been done: ${whatHaveDone}\n =====================================\n `;\n }\n\n return `\n Here is the instruction:\n =====================================\n ${userPrompt}\n =====================================\n `;\n};\n\nexport const automationUserPrompt = new PromptTemplate({\n template: `\n pageDescription:\n =====================================\n {pageDescription}\n =====================================\n\n {taskBackgroundContext}\n `,\n inputVariables: ['pageDescription', 'taskBackgroundContext'],\n});\n","import assert from 'node:assert';\nimport { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { imageInfoOfBase64 } from '@/image';\nimport type { BaseElement, ElementTreeNode, Size, UIContext } from '@/types';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { NodeType } from '@midscene/shared/constants';\nimport { descriptionOfTree, treeToList } from '@midscene/shared/extractor';\nimport { generateHashId } from '@midscene/shared/utils';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\n\nconst characteristic =\n 'You are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.';\n\nconst contextFormatIntro = `\nThe user will give you a screenshot and some of the texts on it. There may be some none-English characters (like Chinese) on it, indicating it's an non-English app. If some text is shown on screenshot but not introduced by the JSON description, use the information you see on screenshot.`;\n\nexport function systemPromptToLocateElement(\n queryPrompt: string,\n multi: boolean,\n) {\n assert(queryPrompt, 'queryPrompt is required');\n return `\n${characteristic}\n${contextFormatIntro}\n\nBased on the information you get, find ${\n multi ? 'one or more text elements' : 'ONE text element'\n } on the page.\nHere is the description: ${queryPrompt}\n \nReturn in the following JSON format:\n{\n \"elements\": [ // Leave it an empty array when no element is found\n { \n \"id\": \"id of the element, like 123\", \n },\n // more ...\n ], \n errors?: [], // string[], error message if any\n}\n`;\n}\n\nexport function systemPromptToExtract() {\n return `\nYou are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.\nThe user will give you a screenshot and the contents of it. There may be some none-English characters (like Chinese) on it, indicating it's an non-English app.\n\nYou have the following skills:\n\nskill name: extract_data_from_UI\nrelated input: DATA_DEMAND\nskill content: \n* User will give you some data requirements in DATA_DEMAND. Consider the UI context, follow the user's instructions, and provide comprehensive data accordingly.\n* There may be some special commands in DATA_DEMAND, please pay extra attention\n - LOCATE_ONE_ELEMENT and LOCATE_ONE_OR_MORE_ELEMENTS: if you see a description that mentions the keyword LOCATE_ONE_ELEMENT\n - LOCATE_ONE_OR_MORE_ELEMENTS(e.g. follow LOCATE_ONE_ELEMENT : i want to find ...), it means user wants to locate a specific element meets the description. \n\nReturn in this way: prefix + the id / comma-separated ids, for example: LOCATE_ONE_ELEMENT/1 , LOCATE_ONE_OR_MORE_ELEMENTS/1,2,3 . If not found, keep the prefix and leave the suffix empty, like LOCATE_ONE_ELEMENT/ .\n\nReturn in the following JSON format:\n{\n language: \"en\", // \"en\" or \"zh\", the language of the page. Use the same language to describe section name, description, and similar fields.\n data: any, // the extracted data from extract_data_from_UI skill. Make sure both the value and scheme meet the DATA_DEMAND.\n errors: [], // string[], error message if any\n}\n`;\n}\n\nexport const extractDataPrompt = new PromptTemplate({\n template: `\npageDescription: {pageDescription}\n\nUse your extract_data_from_UI skill to find the following data, placing it in the \\`data\\` field\nDATA_DEMAND start:\n=====================================\n{dataKeys}\n\n{dataQuery}\n=====================================\nDATA_DEMAND ends.\n `,\n inputVariables: ['pageDescription', 'dataKeys', 'dataQuery'],\n});\n\nexport const extractDataSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'extract_data',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n language: {\n type: 'string',\n enum: ['en', 'zh'],\n description: 'The language of the page',\n },\n data: {\n type: 'object',\n description: 'The extracted data from extract_data_from_UI skill',\n },\n errors: {\n type: 'array',\n items: {\n type: 'string',\n },\n description: 'Error messages, if any',\n },\n },\n required: ['language', 'data', 'errors'],\n additionalProperties: false,\n },\n },\n};\n\nexport function systemPromptToAssert() {\n return `\n${characteristic}\nUser will give an assertion, and some information about the page. Based on the information you get, tell whether the assertion is truthy.\n\nReturn in the following JSON format:\n{\n thought: string, // string, the thought of the assertion. Should in the same language as the assertion.\n pass: true, // true or false, whether the assertion is truthy\n}\n`;\n}\n\nexport const assertSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'assert',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n thought: {\n type: 'string',\n description: 'The thought process behind the assertion',\n },\n pass: {\n type: 'boolean',\n description: 'Whether the assertion passed or failed',\n },\n },\n required: ['thought', 'pass'],\n additionalProperties: false,\n },\n },\n};\n\nexport function describeSize(size: Size) {\n return `${size.width} x ${size.height}`;\n}\n\nexport function describeTextFormat() {\n // use `right` and `bottom` to help AI reduce the feasibility of performing computations\n return `\nThe following texts elements are formatted in the following way: \nid(string), left, top, right, bottom, content(may be truncated)`;\n}\n\nexport function describeElement(\n elements: (Pick<BaseElement, 'rect' | 'content'> & { id: string })[],\n) {\n const sliceLength = 80;\n return elements\n .map((item) =>\n [\n item.id,\n item.rect.left,\n item.rect.top,\n item.rect.left + item.rect.width,\n item.rect.top + item.rect.height,\n item.content.length > sliceLength\n ? `${item.content.slice(0, sliceLength)}...`\n : item.content,\n ].join(', '),\n )\n .join('\\n');\n}\n\nexport function elementByPositionWithElementInfo(\n treeRoot: ElementTreeNode<BaseElement>,\n position: {\n x: number;\n y: number;\n },\n) {\n assert(typeof position !== 'undefined', 'position is required for query');\n\n const matchingElements: BaseElement[] = [];\n\n function dfs(node: ElementTreeNode<BaseElement>) {\n if (node?.node) {\n const item = node.node;\n if (\n item.attributes.nodeType !== NodeType.CONTAINER &&\n item.rect.left <= position.x &&\n position.x <= item.rect.left + item.rect.width &&\n item.rect.top <= position.y &&\n position.y <= item.rect.top + item.rect.height\n ) {\n matchingElements.push(item);\n }\n }\n\n for (const child of node.children) {\n dfs(child);\n }\n }\n\n dfs(treeRoot);\n\n if (matchingElements.length === 0) {\n return undefined;\n }\n\n // Find the smallest element by area\n return matchingElements.reduce((smallest, current) => {\n const smallestArea = smallest.rect.width * smallest.rect.height;\n const currentArea = current.rect.width * current.rect.height;\n return currentArea < smallestArea ? current : smallest;\n });\n}\n\nexport const samplePageDescription = `\nThe size of the page: 1280 x 720\nSome of the elements are marked with a rectangle in the screenshot corresponding to the markerId, some are not.\n\nDescription of all the elements in screenshot:\n<div id=\"969f1637\" markerId=\"1\" left=\"100\" top=\"100\" width=\"100\" height=\"100\"> // The markerId indicated by the rectangle label in the screenshot\n <h4 id=\"b211ecb2\" markerId=\"5\" left=\"150\" top=\"150\" width=\"90\" height=\"60\">\n The username is accepted\n </h4>\n ...many more\n</div>\n`;\n\nexport async function describeUserPage<\n ElementType extends BaseElement = BaseElement,\n>(\n context: Omit<UIContext<ElementType>, 'describer'>,\n opt?: {\n truncateTextLength?: number;\n filterNonTextContent?: boolean;\n },\n) {\n const { screenshotBase64 } = context;\n let width: number;\n let height: number;\n\n if (context.size) {\n ({ width, height } = context.size);\n } else {\n const imgSize = await imageInfoOfBase64(screenshotBase64);\n ({ width, height } = imgSize);\n }\n\n const treeRoot = context.tree;\n // dfs tree, save the id and element info\n const idElementMap: Record<string, ElementType> = {};\n const flatElements: ElementType[] = treeToList(treeRoot);\n flatElements.forEach((element) => {\n idElementMap[element.id] = element;\n if (typeof element.indexId !== 'undefined') {\n idElementMap[`${element.indexId}`] = element;\n }\n });\n\n const contentTree = await descriptionOfTree(\n treeRoot,\n opt?.truncateTextLength,\n opt?.filterNonTextContent,\n );\n\n // if match by position, don't need to provide the page description\n const pageJSONDescription = getAIConfig(MATCH_BY_POSITION)\n ? ''\n : `Some of the elements are marked with a rectangle in the screenshot, some are not. \\n The page elements tree:\\n${contentTree}`;\n const sizeDescription = describeSize({ width, height });\n\n return {\n description: `The size of the page: ${sizeDescription} \\n ${pageJSONDescription}`,\n elementById(id: string) {\n assert(typeof id !== 'undefined', 'id is required for query');\n const item = idElementMap[`${id}`];\n return item;\n },\n elementByPosition(\n position: { x: number; y: number },\n size: { width: number; height: number },\n ) {\n // console.log('elementByPosition', { position, size });\n return elementByPositionWithElementInfo(treeRoot, position);\n },\n insertElementByPosition(position: { x: number; y: number }) {\n const rect = {\n left: Math.max(position.x - 4, 0),\n top: Math.max(position.y - 4, 0),\n width: 8,\n height: 8,\n };\n const id = generateHashId(rect);\n const element = {\n id,\n attributes: { nodeType: NodeType.POSITION },\n rect,\n content: '',\n center: [position.x, position.y],\n } as ElementType;\n\n treeRoot.children.push({\n node: element,\n children: [],\n });\n flatElements.push(element);\n idElementMap[id] = element;\n return element;\n },\n size: { width, height },\n };\n}\n","export {\n imageInfo,\n imageInfoOfBase64,\n base64Encoded,\n calculateNewDimensions,\n resizeImg,\n transformImgPathToBase64,\n saveBase64Image,\n} from '@midscene/shared/img';\n","import assert from 'node:assert';\nimport type {\n AIAssertionResponse,\n AIElementResponse,\n AISectionParseResponse,\n AISingleElementResponse,\n AISingleElementResponseByPosition,\n AIUsageInfo,\n BaseElement,\n ElementById,\n ElementTreeNode,\n Size,\n UIContext,\n} from '@/types';\nimport type {\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n} from 'openai/resources';\nimport { AIActionType, callAiFn } from './common';\nimport {\n findElementPrompt,\n systemPromptToLocateElement,\n} from './prompt/llm-locator';\nimport {\n describeUserPage,\n elementByPositionWithElementInfo,\n extractDataPrompt,\n systemPromptToAssert,\n systemPromptToExtract,\n} from './prompt/util';\nimport { callToGetJSONObject } from './service-caller';\n\nexport type AIArgs = [\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n];\n\nconst liteContextConfig = {\n filterNonTextContent: true,\n truncateTextLength: 200,\n};\n\nfunction transformToAbsoluteCoords(\n relativePosition: { x: number; y: number },\n size: Size,\n) {\n return {\n x: Number(((relativePosition.x / 1000) * size.width).toFixed(3)),\n y: Number(((relativePosition.y / 1000) * size.height).toFixed(3)),\n };\n}\n\n// let index = 0;\nexport async function transformElementPositionToId(\n aiResult: AIElementResponse | [number, number],\n treeRoot: ElementTreeNode<BaseElement>,\n size: { width: number; height: number },\n) {\n if (Array.isArray(aiResult)) {\n const relativePosition = aiResult;\n const absolutePosition = transformToAbsoluteCoords(\n {\n x: relativePosition[0],\n y: relativePosition[1],\n },\n size,\n );\n\n const element = elementByPositionWithElementInfo(\n treeRoot,\n absolutePosition,\n );\n assert(\n element,\n `inspect: no id found with position: ${JSON.stringify({ absolutePosition })}`,\n );\n\n return {\n errors: [],\n elements: [\n {\n id: element.id,\n },\n ],\n };\n }\n\n return {\n errors: aiResult.errors,\n elements: aiResult.elements,\n };\n}\n\nfunction getQuickAnswer(\n quickAnswer:\n | Partial<AISingleElementResponse>\n | Partial<AISingleElementResponseByPosition>\n | undefined,\n tree: ElementTreeNode<BaseElement>,\n elementById: ElementById,\n insertElementByPosition: (position: { x: number; y: number }) => BaseElement,\n) {\n if (!quickAnswer) {\n return undefined;\n }\n if ('id' in quickAnswer && quickAnswer.id && elementById(quickAnswer.id)) {\n return {\n parseResult: {\n elements: [quickAnswer],\n errors: [],\n },\n rawResponse: quickAnswer,\n elementById,\n };\n }\n\n if ('position' in quickAnswer && quickAnswer.position) {\n let element = elementByPositionWithElementInfo(tree, quickAnswer.position);\n if (!element) {\n element = insertElementByPosition(quickAnswer.position);\n }\n return {\n parseResult: {\n elements: [element],\n errors: [],\n },\n rawResponse: quickAnswer,\n elementById,\n } as any;\n }\n}\n\nexport async function AiInspectElement<\n ElementType extends BaseElement = BaseElement,\n>(options: {\n context: UIContext<ElementType>;\n multi: boolean;\n targetElementDescription: string;\n callAI?: typeof callAiFn<AIElementResponse | [number, number]>;\n quickAnswer?: Partial<\n AISingleElementResponse | AISingleElementResponseByPosition\n >;\n}): Promise<{\n parseResult: AIElementResponse;\n rawResponse: any;\n elementById: ElementById;\n usage?: AIUsageInfo;\n}> {\n const { context, multi, targetElementDescription, callAI } = options;\n const { screenshotBase64, screenshotBase64WithElementMarker } = context;\n const { description, elementById, insertElementByPosition, size } =\n await describeUserPage(context);\n // meet quick answer\n const quickAnswer = getQuickAnswer(\n options.quickAnswer,\n context.tree,\n elementById,\n insertElementByPosition,\n );\n if (quickAnswer) {\n return quickAnswer;\n }\n\n assert(\n targetElementDescription,\n 'cannot find the target element description',\n );\n\n const userInstructionPrompt = await findElementPrompt.format({\n pageDescription: description,\n targetElementDescription,\n multi,\n });\n const systemPrompt = systemPromptToLocateElement();\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64WithElementMarker || screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: userInstructionPrompt,\n },\n ],\n },\n ];\n\n const callAIFn =\n callAI || callToGetJSONObject<AIElementResponse | [number, number]>;\n\n const res = await callAIFn(msgs, AIActionType.INSPECT_ELEMENT);\n return {\n parseResult: await transformElementPositionToId(\n res.content,\n context.tree,\n size,\n ),\n rawResponse: res.content,\n elementById,\n usage: res.usage,\n };\n}\n\nexport async function AiExtractElementInfo<\n T,\n ElementType extends BaseElement = BaseElement,\n>(options: {\n dataQuery: string | Record<string, string>;\n context: UIContext<ElementType>;\n}) {\n const { dataQuery, context } = options;\n const systemPrompt = systemPromptToExtract();\n\n const { screenshotBase64 } = context;\n const { description, elementById } = await describeUserPage(\n context,\n liteContextConfig,\n );\n\n let dataKeys = '';\n let dataQueryText = '';\n if (typeof dataQuery === 'string') {\n dataKeys = '';\n dataQueryText = dataQuery;\n } else {\n dataKeys = `return in key-value style object, keys are ${Object.keys(dataQuery).join(',')}`;\n dataQueryText = JSON.stringify(dataQuery, null, 2);\n }\n const extractDataPromptText = await extractDataPrompt.format({\n pageDescription: description,\n dataKeys,\n dataQuery: dataQueryText,\n });\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: extractDataPromptText,\n },\n ],\n },\n ];\n\n const result = await callAiFn<AISectionParseResponse<T>>(\n msgs,\n AIActionType.EXTRACT_DATA,\n );\n return {\n parseResult: result.content,\n elementById,\n usage: result.usage,\n };\n}\n\nexport async function AiAssert<\n ElementType extends BaseElement = BaseElement,\n>(options: { assertion: string; context: UIContext<ElementType> }) {\n const { assertion, context } = options;\n\n assert(assertion, 'assertion should be a string');\n\n const { screenshotBase64 } = context;\n const systemPrompt = systemPromptToAssert();\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: `\nHere is the description of the assertion. Just go ahead:\n=====================================\n${assertion}\n=====================================\n `,\n },\n ],\n },\n ];\n\n const { content: assertResult, usage } = await callAiFn<AIAssertionResponse>(\n msgs,\n AIActionType.ASSERT,\n );\n return {\n content: assertResult,\n usage,\n };\n}\n","import assert from 'node:assert';\nimport type { AIUsageInfo, PlanningAIResponse, UIContext } from '@/types';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { AIActionType, type AIArgs, callAiFn } from './common';\nimport {\n automationUserPrompt,\n generateTaskBackgroundContext,\n systemPromptToTaskPlanning,\n} from './prompt/llm-planning';\nimport { describeUserPage } from './prompt/util';\n\nexport async function plan(\n userPrompt: string,\n opts: {\n whatHaveDone?: string;\n originalPrompt?: string;\n context: UIContext;\n callAI?: typeof callAiFn<PlanningAIResponse>;\n },\n): Promise<PlanningAIResponse> {\n const { callAI, context } = opts || {};\n const { screenshotBase64, screenshotBase64WithElementMarker } = context;\n const { description: pageDescription } = await describeUserPage(context);\n\n const systemPrompt = await systemPromptToTaskPlanning();\n const taskBackgroundContextText = generateTaskBackgroundContext(\n userPrompt,\n opts.originalPrompt,\n opts.whatHaveDone,\n );\n const userInstructionPrompt = await automationUserPrompt.format({\n pageDescription,\n taskBackgroundContext: taskBackgroundContextText,\n });\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64WithElementMarker || screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: userInstructionPrompt,\n },\n ],\n },\n ];\n\n const call = callAI || callAiFn;\n const { content, usage } = await call(msgs, AIActionType.PLAN);\n const planFromAI = content;\n\n const actions = planFromAI?.actions || [];\n assert(planFromAI, \"can't get plans from AI\");\n assert(\n actions.length > 0,\n `Failed to plan actions: ${planFromAI.error || '(no error details)'}`,\n );\n\n return planFromAI;\n}\n","import assert from 'node:assert';\nimport type { PlanningAction } from '@/types';\nimport { transformHotkeyInput } from '@midscene/shared/keyboard-layout';\nimport { actionParser } from '@ui-tars/action-parser';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { AIActionType } from './common';\nimport { getSummary, uiTarsPlanningPrompt } from './prompt/ui-tars-planning';\nimport { call } from './service-caller';\ntype ActionType =\n | 'click'\n | 'drag'\n | 'type'\n | 'hotkey'\n | 'finished'\n | 'scroll'\n | 'wait';\n\nfunction capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nexport async function vlmPlanning(options: {\n userInstruction: string;\n conversationHistory: ChatCompletionMessageParam[];\n size: { width: number; height: number };\n}): Promise<{\n actions: PlanningAction<any>[];\n realActions: ReturnType<typeof actionParser>['parsed'];\n action_summary: string;\n}> {\n const { conversationHistory, userInstruction, size } = options;\n const systemPrompt = uiTarsPlanningPrompt + userInstruction;\n\n const res = await call(\n [\n {\n role: 'user',\n content: systemPrompt,\n },\n ...conversationHistory,\n ],\n AIActionType.INSPECT_ELEMENT,\n );\n const { parsed } = actionParser({\n prediction: res.content,\n factor: 1000,\n });\n const transformActions: PlanningAction[] = [];\n parsed.forEach((action) => {\n if (action.action_type === 'click') {\n assert(action.action_inputs.start_box, 'start_box is required');\n const point = getPoint(action.action_inputs.start_box, size);\n transformActions.push({\n type: 'Locate',\n locate: {\n prompt: action.thought || '',\n position: { x: point[0], y: point[1] },\n },\n param: {\n // action,\n // position: { x: point[0], y: point[1] },\n },\n });\n transformActions.push({\n type: 'Tap',\n locate: {\n prompt: action.thought || '',\n position: { x: point[0], y: point[1] },\n },\n param: action.thought || '',\n });\n } else if (action.action_type === 'drag') {\n assert(action.action_inputs.start_box, 'start_box is required');\n assert(action.action_inputs.end_box, 'end_box is required');\n const startPoint = getPoint(action.action_inputs.start_box, size);\n const endPoint = getPoint(action.action_inputs.end_box, size);\n transformActions.push({\n type: 'Drag',\n param: {\n start_box: { x: startPoint[0], y: startPoint[1] },\n end_box: { x: endPoint[0], y: endPoint[1] },\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'type') {\n transformActions.push({\n type: 'Input',\n param: {\n value: action.action_inputs.content,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'scroll') {\n transformActions.push({\n type: 'Scroll',\n param: {\n direction: action.action_inputs.direction,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'finished') {\n transformActions.push({\n type: 'Finished',\n param: {},\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'hotkey') {\n assert(action.action_inputs.key, 'key is required');\n const keys = transformHotkeyInput(action.action_inputs.key);\n\n transformActions.push({\n type: 'KeyboardPress',\n param: {\n value: keys,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'wait') {\n transformActions.push({\n type: 'Sleep',\n param: {\n timeMs: 1000,\n },\n locate: null,\n thought: action.thought || '',\n });\n }\n });\n\n if (transformActions.length === 0) {\n throw new Error(`No actions found with reason: ${res.content}`, {\n cause: {\n prediction: res.content,\n parsed,\n },\n });\n }\n\n return {\n actions: transformActions,\n realActions: parsed,\n action_summary: getSummary(res.content),\n };\n}\n\nfunction getPoint(startBox: string, size: { width: number; height: number }) {\n const [x, y] = JSON.parse(startBox);\n return [x * size.width, y * size.height];\n}\n\ninterface BaseAction {\n action_type: ActionType;\n action_inputs: Record<string, any>;\n reflection: string | null;\n thought: string | null;\n}\n\ninterface ClickAction extends BaseAction {\n action_type: 'click';\n action_inputs: {\n start_box: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface DragAction extends BaseAction {\n action_type: 'drag';\n action_inputs: {\n start_box: string; // JSON string of [x, y] coordinates\n end_box: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface WaitAction extends BaseAction {\n action_type: 'wait';\n action_inputs: {\n time: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface TypeAction extends BaseAction {\n action_type: 'type';\n action_inputs: {\n content: string;\n };\n}\n\ninterface HotkeyAction extends BaseAction {\n action_type: 'hotkey';\n action_inputs: {\n key: string;\n };\n}\n\ninterface ScrollAction extends BaseAction {\n action_type: 'scroll';\n action_inputs: {\n direction: 'up' | 'down';\n };\n}\n\ninterface FinishedAction extends BaseAction {\n action_type: 'finished';\n action_inputs: Record<string, never>;\n}\n\nexport type Action =\n | ClickAction\n | DragAction\n | TypeAction\n | HotkeyAction\n | ScrollAction\n | FinishedAction\n | WaitAction;\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAI,OAAO,WAAW,YAAY,OAAO,OAAO,YAAY;AAAU,aAAO,UAAU;AAEvF,UAAM,UAAU,SAAU,KAAK;AAC3B,YAAM,IAAI,MAAM,oCAAoC,KAAK,QAAQ,KAAK,OAAO,GAAG;AAAA,IACpF;AAEA,aAAS,MAAM,SAAS;AACpB,UAAI,OAAO,YAAY;AAAY,kBAAU,MAAM;AAEnD,UAAI,SAAS,CAAC;AACd,UAAI,QAAQ,CAAC;AAC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AkB,MAAyC;AAC3E,QAAM,CAAC,GAAG,CAAC,IAAI,KAAK,MAAM,QAAQ;AAClC,SAAO,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,MAAM;AACzC","names":["fromHex","fromOct","_default","require_lexer","assert","AIResponseFormat","PromptTemplate","content","dJSON","call"],"ignoreList":[],"sources":["../../../../node_modules/.pnpm/lex@1.7.9/node_modules/lex/lexer.js","../../../../node_modules/.pnpm/string.fromcodepoint@0.2.1/node_modules/string.fromcodepoint/fromcodepoint.js","../../../../node_modules/.pnpm/unescape-js@1.1.4/node_modules/unescape-js/dist/index.js","../../../../node_modules/.pnpm/utf8@3.0.0/node_modules/utf8/utf8.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/lexer.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/parser.js","../../../../node_modules/.pnpm/dirty-json@0.9.2/node_modules/dirty-json/dirty-json.js","../../src/ai-model/service-caller/index.ts","../../src/types.ts","../../src/ai-model/common.ts","../../src/ai-model/prompt/llm-locator.ts","../../src/ai-model/prompt/ui-tars-planning.ts","../../src/ai-model/prompt/ui-tars-locator.ts","../../src/ai-model/prompt/llm-planning.ts","../../src/ai-model/prompt/util.ts","../../src/image/index.ts","../../src/ai-model/inspect.ts","../../src/ai-model/llm-planning.ts","../../src/ai-model/ui-tars-planning.ts"],"sourcesContent":["if (typeof module === \"object\" && typeof module.exports === \"object\") module.exports = Lexer;\n\nLexer.defunct = function (chr) {\n throw new Error(\"Unexpected character at index \" + (this.index - 1) + \": \" + chr);\n};\n\nfunction Lexer(defunct) {\n if (typeof defunct !== \"function\") defunct = Lexer.defunct;\n\n var tokens = [];\n var rules = [];\n var remove = 0;\n this.state = 0;\n this.index = 0;\n this.input = \"\";\n\n this.addRule = function (pattern, action, start) {\n var global = pattern.global;\n\n if (!global) {\n var flags = \"g\";\n if (pattern.multiline) flags += \"m\";\n if (pattern.ignoreCase) flags += \"i\";\n pattern = new RegExp(pattern.source, flags);\n }\n\n if (Object.prototype.toString.call(start) !== \"[object Array]\") start = [0];\n\n rules.push({\n pattern: pattern,\n global: global,\n action: action,\n start: start\n });\n\n return this;\n };\n\n this.setInput = function (input) {\n remove = 0;\n this.state = 0;\n this.index = 0;\n tokens.length = 0;\n this.input = input;\n return this;\n };\n\n this.lex = function () {\n if (tokens.length) return tokens.shift();\n\n this.reject = true;\n\n while (this.index <= this.input.length) {\n var matches = scan.call(this).splice(remove);\n var index = this.index;\n\n while (matches.length) {\n if (this.reject) {\n var match = matches.shift();\n var result = match.result;\n var length = match.length;\n this.index += length;\n this.reject = false;\n remove++;\n\n var token = match.action.apply(this, result);\n if (this.reject) this.index = result.index;\n else if (typeof token !== \"undefined\") {\n switch (Object.prototype.toString.call(token)) {\n case \"[object Array]\":\n tokens = token.slice(1);\n token = token[0];\n default:\n if (length) remove = 0;\n return token;\n }\n }\n } else break;\n }\n\n var input = this.input;\n\n if (index < input.length) {\n if (this.reject) {\n remove = 0;\n var token = defunct.call(this, input.charAt(this.index++));\n if (typeof token !== \"undefined\") {\n if (Object.prototype.toString.call(token) === \"[object Array]\") {\n tokens = token.slice(1);\n return token[0];\n } else return token;\n }\n } else {\n if (this.index !== index) remove = 0;\n this.reject = true;\n }\n } else if (matches.length)\n this.reject = true;\n else break;\n }\n };\n\n function scan() {\n var matches = [];\n var index = 0;\n\n var state = this.state;\n var lastIndex = this.index;\n var input = this.input;\n\n for (var i = 0, length = rules.length; i < length; i++) {\n var rule = rules[i];\n var start = rule.start;\n var states = start.length;\n\n if ((!states || start.indexOf(state) >= 0) ||\n (state % 2 && states === 1 && !start[0])) {\n var pattern = rule.pattern;\n pattern.lastIndex = lastIndex;\n var result = pattern.exec(input);\n\n if (result && result.index === lastIndex) {\n var j = matches.push({\n result: result,\n action: rule.action,\n length: result[0].length\n });\n\n if (rule.global) index = j;\n\n while (--j > index) {\n var k = j - 1;\n\n if (matches[j].length > matches[k].length) {\n var temple = matches[j];\n matches[j] = matches[k];\n matches[k] = temple;\n }\n }\n }\n }\n }\n\n return matches;\n }\n}\n","/*! http://mths.be/fromcodepoint v0.2.1 by @mathias */\nif (!String.fromCodePoint) {\n\t(function() {\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar stringFromCharCode = String.fromCharCode;\n\t\tvar floor = Math.floor;\n\t\tvar fromCodePoint = function(_) {\n\t\t\tvar MAX_SIZE = 0x4000;\n\t\t\tvar codeUnits = [];\n\t\t\tvar highSurrogate;\n\t\t\tvar lowSurrogate;\n\t\t\tvar index = -1;\n\t\t\tvar length = arguments.length;\n\t\t\tif (!length) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tvar result = '';\n\t\t\twhile (++index < length) {\n\t\t\t\tvar codePoint = Number(arguments[index]);\n\t\t\t\tif (\n\t\t\t\t\t!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`\n\t\t\t\t\tcodePoint < 0 || // not a valid Unicode code point\n\t\t\t\t\tcodePoint > 0x10FFFF || // not a valid Unicode code point\n\t\t\t\t\tfloor(codePoint) != codePoint // not an integer\n\t\t\t\t) {\n\t\t\t\t\tthrow RangeError('Invalid code point: ' + codePoint);\n\t\t\t\t}\n\t\t\t\tif (codePoint <= 0xFFFF) { // BMP code point\n\t\t\t\t\tcodeUnits.push(codePoint);\n\t\t\t\t} else { // Astral code point; split in surrogate halves\n\t\t\t\t\t// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n\t\t\t\t\tcodePoint -= 0x10000;\n\t\t\t\t\thighSurrogate = (codePoint >> 10) + 0xD800;\n\t\t\t\t\tlowSurrogate = (codePoint % 0x400) + 0xDC00;\n\t\t\t\t\tcodeUnits.push(highSurrogate, lowSurrogate);\n\t\t\t\t}\n\t\t\t\tif (index + 1 == length || codeUnits.length > MAX_SIZE) {\n\t\t\t\t\tresult += stringFromCharCode.apply(null, codeUnits);\n\t\t\t\t\tcodeUnits.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String, 'fromCodePoint', {\n\t\t\t\t'value': fromCodePoint,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.fromCodePoint = fromCodePoint;\n\t\t}\n\t}());\n}\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nrequire(\"string.fromcodepoint\");\n\n/**\n * \\\\ - matches the backslash which indicates the beginning of an escape sequence\n * (\n * u\\{([0-9A-Fa-f]+)\\} - first alternative; matches the variable-length hexadecimal escape sequence (\\u{ABCD0})\n * |\n * u([0-9A-Fa-f]{4}) - second alternative; matches the 4-digit hexadecimal escape sequence (\\uABCD)\n * |\n * x([0-9A-Fa-f]{2}) - third alternative; matches the 2-digit hexadecimal escape sequence (\\xA5)\n * |\n * ([1-7][0-7]{0,2}|[0-7]{2,3}) - fourth alternative; matches the up-to-3-digit octal escape sequence (\\5 or \\512)\n * |\n * (['\"tbrnfv0\\\\]) - fifth alternative; matches the special escape characters (\\t, \\n and so on)\n * |\n * \\U([0-9A-Fa-f]+) - sixth alternative; matches the 8-digit hexadecimal escape sequence used by python (\\U0001F3B5)\n * )\n */\nvar jsEscapeRegex = /\\\\(u\\{([0-9A-Fa-f]+)\\}|u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([1-7][0-7]{0,2}|[0-7]{2,3})|(['\"tbrnfv0\\\\]))|\\\\U([0-9A-Fa-f]{8})/g;\nvar usualEscapeSequences = {\n '0': '\\0',\n 'b': '\\b',\n 'f': '\\f',\n 'n': '\\n',\n 'r': '\\r',\n 't': '\\t',\n 'v': '\\v',\n '\\'': '\\'',\n '\"': '\"',\n '\\\\': '\\\\'\n};\n\nvar fromHex = function fromHex(str) {\n return String.fromCodePoint(parseInt(str, 16));\n};\n\nvar fromOct = function fromOct(str) {\n return String.fromCodePoint(parseInt(str, 8));\n};\n\nvar _default = function _default(string) {\n return string.replace(jsEscapeRegex, function (_, __, varHex, longHex, shortHex, octal, specialCharacter, python) {\n if (varHex !== undefined) {\n return fromHex(varHex);\n } else if (longHex !== undefined) {\n return fromHex(longHex);\n } else if (shortHex !== undefined) {\n return fromHex(shortHex);\n } else if (octal !== undefined) {\n return fromOct(octal);\n } else if (python !== undefined) {\n return fromHex(python);\n } else {\n return usualEscapeSequences[specialCharacter];\n }\n });\n};\n\nexports.default = _default;\nmodule.exports = exports.default;","/*! https://mths.be/utf8js v3.0.0 by @mathias */\n;(function(root) {\n\n\tvar stringFromCharCode = String.fromCharCode;\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2decode(string) {\n\t\tvar output = [];\n\t\tvar counter = 0;\n\t\tvar length = string.length;\n\t\tvar value;\n\t\tvar extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2encode(array) {\n\t\tvar length = array.length;\n\t\tvar index = -1;\n\t\tvar value;\n\t\tvar output = '';\n\t\twhile (++index < length) {\n\t\t\tvalue = array[index];\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t}\n\t\treturn output;\n\t}\n\n\tfunction checkScalarValue(codePoint) {\n\t\tif (codePoint >= 0xD800 && codePoint <= 0xDFFF) {\n\t\t\tthrow Error(\n\t\t\t\t'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +\n\t\t\t\t' is not a scalar value'\n\t\t\t);\n\t\t}\n\t}\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction createByte(codePoint, shift) {\n\t\treturn stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);\n\t}\n\n\tfunction encodeCodePoint(codePoint) {\n\t\tif ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence\n\t\t\treturn stringFromCharCode(codePoint);\n\t\t}\n\t\tvar symbol = '';\n\t\tif ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);\n\t\t}\n\t\telse if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence\n\t\t\tcheckScalarValue(codePoint);\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\telse if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);\n\t\t\tsymbol += createByte(codePoint, 12);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\tsymbol += stringFromCharCode((codePoint & 0x3F) | 0x80);\n\t\treturn symbol;\n\t}\n\n\tfunction utf8encode(string) {\n\t\tvar codePoints = ucs2decode(string);\n\t\tvar length = codePoints.length;\n\t\tvar index = -1;\n\t\tvar codePoint;\n\t\tvar byteString = '';\n\t\twhile (++index < length) {\n\t\t\tcodePoint = codePoints[index];\n\t\t\tbyteString += encodeCodePoint(codePoint);\n\t\t}\n\t\treturn byteString;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction readContinuationByte() {\n\t\tif (byteIndex >= byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tvar continuationByte = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\tif ((continuationByte & 0xC0) == 0x80) {\n\t\t\treturn continuationByte & 0x3F;\n\t\t}\n\n\t\t// If we end up here, it’s not a continuation byte\n\t\tthrow Error('Invalid continuation byte');\n\t}\n\n\tfunction decodeSymbol() {\n\t\tvar byte1;\n\t\tvar byte2;\n\t\tvar byte3;\n\t\tvar byte4;\n\t\tvar codePoint;\n\n\t\tif (byteIndex > byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tif (byteIndex == byteCount) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Read first byte\n\t\tbyte1 = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\t// 1-byte sequence (no continuation bytes)\n\t\tif ((byte1 & 0x80) == 0) {\n\t\t\treturn byte1;\n\t\t}\n\n\t\t// 2-byte sequence\n\t\tif ((byte1 & 0xE0) == 0xC0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x1F) << 6) | byte2;\n\t\t\tif (codePoint >= 0x80) {\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 3-byte sequence (may include unpaired surrogates)\n\t\tif ((byte1 & 0xF0) == 0xE0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;\n\t\t\tif (codePoint >= 0x0800) {\n\t\t\t\tcheckScalarValue(codePoint);\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 4-byte sequence\n\t\tif ((byte1 & 0xF8) == 0xF0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tbyte4 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |\n\t\t\t\t(byte3 << 0x06) | byte4;\n\t\t\tif (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {\n\t\t\t\treturn codePoint;\n\t\t\t}\n\t\t}\n\n\t\tthrow Error('Invalid UTF-8 detected');\n\t}\n\n\tvar byteArray;\n\tvar byteCount;\n\tvar byteIndex;\n\tfunction utf8decode(byteString) {\n\t\tbyteArray = ucs2decode(byteString);\n\t\tbyteCount = byteArray.length;\n\t\tbyteIndex = 0;\n\t\tvar codePoints = [];\n\t\tvar tmp;\n\t\twhile ((tmp = decodeSymbol()) !== false) {\n\t\t\tcodePoints.push(tmp);\n\t\t}\n\t\treturn ucs2encode(codePoints);\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\troot.version = '3.0.0';\n\troot.encode = utf8encode;\n\troot.decode = utf8decode;\n\n}(typeof exports === 'undefined' ? this.utf8 = {} : exports));\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\"use strict\";\n\nconst Lexer = require(\"lex\");\nconst unescapeJs = require(\"unescape-js\");\nconst utf8 = require(\"utf8\");\n\n// terminals\nconst LEX_KV = 0;\nconst LEX_KVLIST = 1;\nconst LEX_VLIST = 2;\nconst LEX_BOOLEAN = 3;\nconst LEX_COVALUE = 4;\nconst LEX_CVALUE = 5;\nconst LEX_FLOAT = 6;\nconst LEX_INT = 7;\nconst LEX_KEY = 8;\nconst LEX_LIST = 9;\nconst LEX_OBJ = 10;\nconst LEX_QUOTE = 11;\nconst LEX_RB = 12;\nconst LEX_RCB = 13;\nconst LEX_TOKEN = 14;\nconst LEX_VALUE = 15;\n\n// non-terminals\nconst LEX_COLON = -1;\nconst LEX_COMMA = -2;\nconst LEX_LCB = -3;\nconst LEX_LB = -4;\nconst LEX_DOT = -5;\n\n\nconst lexMap = {\n \":\": {type: LEX_COLON},\n \",\": {type: LEX_COMMA},\n \"{\": {type: LEX_LCB},\n \"}\": {type: LEX_RCB},\n \"[\": {type: LEX_LB},\n \"]\": {type: LEX_RB},\n \".\": {type: LEX_DOT} // TODO: remove?\n};\n\nconst lexSpc = [\n [/\\s*:\\s*/, LEX_COLON],\n [/\\s*,\\s*/, LEX_COMMA],\n [/\\s*{\\s*/, LEX_LCB],\n [/\\s*}\\s*/, LEX_RCB],\n [/\\s*\\[\\s*/, LEX_LB],\n [/\\s*\\]\\s*/, LEX_RB],\n [/\\s*\\.\\s*/, LEX_DOT] // TODO: remove?\n];\n\nfunction parseString(str) {\n // unescape-js doesn't cover the \\/ case, but we will here.\n str = str.replace(/\\\\\\//, '/');\n return unescapeJs(str);\n}\n\n\nfunction getLexer(string) {\n let lexer = new Lexer();\n\n let col = 0;\n let row = 0;\n \n lexer.addRule(/\"((?:\\\\.|[^\"])*?)($|\")/, (lexeme, txt) => {\n col += lexeme.length;\n return {type: LEX_QUOTE, value: parseString(txt), row, col, single: false};\n });\n\n lexer.addRule(/'((?:\\\\.|[^'])*?)($|'|(\",?[ \\t]*\\n))/, (lexeme, txt) => {\n col += lexeme.length;\n return {type: LEX_QUOTE, value: parseString(txt), row, col, single: true};\n });\n\n // floats with a dot\n lexer.addRule(/[\\-0-9]*\\.[0-9]*([eE][\\+\\-]?)?[0-9]*(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_FLOAT, value: parseFloat(lexeme), row, col};\n });\n\n // floats without a dot but with e notation\n lexer.addRule(/\\-?[0-9]+([eE][\\+\\-]?)[0-9]*(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_FLOAT, value: parseFloat(lexeme), row, col};\n });\n \n lexer.addRule(/\\-?[0-9]+(?:\\s*)/, lexeme => {\n col += lexeme.length;\n return {type: LEX_INT, value: parseInt(lexeme), row, col};\n });\n\n lexSpc.forEach(item => {\n lexer.addRule(item[0], lexeme => {\n col += lexeme.length;\n return {type: item[1], value: lexeme, row, col};\n });\n });\n\n lexer.addRule(/\\s/, lexeme => {\n // chomp whitespace...\n if (lexeme == \"\\n\") {\n col = 0;\n row++;\n } else {\n col += lexeme.length;\n }\n });\n\n \n lexer.addRule(/\\S[ \\t]*/, lexeme => {\n col += lexeme.length;\n \n let lt = LEX_TOKEN;\n let val = lexeme;\n \n return {type: lt, value: val, row, col};\n });\n \n\n\n\n lexer.setInput(string);\n\n return lexer;\n}\n\n\n\nmodule.exports.lexString = lexString;\nfunction lexString(str, emit) {\n let lex = getLexer(str);\n\n let token = \"\";\n while ((token = lex.lex())) {\n emit(token);\n }\n \n}\n\nmodule.exports.getAllTokens = getAllTokens;\nfunction getAllTokens(str) {\n let arr = [];\n let emit = function (i) {\n arr.push(i);\n };\n\n lexString(str, emit);\n\n return arr;\n}\n\n\n\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\"use strict\";\n\nlet lexer = require(\"./lexer\");\n\n// terminals\nconst LEX_KV = 0;\nconst LEX_KVLIST = 1;\nconst LEX_VLIST = 2;\nconst LEX_BOOLEAN = 3;\nconst LEX_COVALUE = 4;\nconst LEX_CVALUE = 5;\nconst LEX_FLOAT = 6;\nconst LEX_INT = 7;\nconst LEX_KEY = 8;\nconst LEX_LIST = 9;\nconst LEX_OBJ = 10;\nconst LEX_QUOTE = 11;\nconst LEX_RB = 12;\nconst LEX_RCB = 13;\nconst LEX_TOKEN = 14;\nconst LEX_VALUE = 15;\n\n// non-terminals\nconst LEX_COLON = -1;\nconst LEX_COMMA = -2;\nconst LEX_LCB = -3;\nconst LEX_LB = -4;\nconst LEX_DOT = -5;\n\nfunction extendArray(arr) {\n if (arr.peek == null) {\n Object.defineProperty(arr, 'peek', {\n enumerable: false,\n value: function() {\n return this[this.length - 1];\n }\n });\n }\n if (arr.last == null) {\n Object.defineProperty(arr, 'last', {\n enumerable: false,\n value: function(i) {\n return this[this.length - (1 + i)];\n }\n });\n }\n}\n\nfunction is(obj, prop) {\n return (obj && obj.hasOwnProperty(\"type\") && obj.type == prop);\n}\n\nfunction log(str) {\n //console.log(str);\n}\n\n\nmodule.exports.parse = parse;\nfunction parse(text, dupKeys) {\n let stack = [];\n\n let tokens = [];\n\n extendArray(stack);\n extendArray(tokens);\n\n let emit = function(t) {\n tokens.push(t);\n };\n\n lexer.lexString(text, emit);\n\n // ensure that if we started with a LB or LCB, we end with a\n // RB or RCB.\n if (tokens[0].type == LEX_LB && tokens.last(0).type != LEX_RB) {\n tokens.push({ type: LEX_RB, value: \"]\", row: -1, col: -1});\n }\n\n if (tokens[0].type == LEX_LCB && tokens.last(0).type != LEX_RCB) {\n tokens.push({ type: LEX_RCB, value: \"}\", row: -1, col: -1});\n }\n\n for (let i = 0; i < tokens.length; i++) {\n log(\"Shifting \" + tokens[i].type);\n stack.push(tokens[i]);\n log(stack);\n log(\"Reducing...\");\n while (reduce(stack)) {\n log(stack);\n log(\"Reducing...\");\n }\n }\n\n // if everything parsed into a KV list, assume it was an object missing the starting\n // \"{\" and ending \"}\"\n if (stack.length == 1 && stack[0].type == LEX_KVLIST) {\n log(\"Pre-compile error fix 1\");\n stack = [{type: LEX_OBJ, value: stack[0].value}];\n }\n\n return compileOST(stack[0], dupKeys);\n\n}\n\nfunction reduce(stack) {\n let next = stack.pop();\n\n switch(next.type) {\n case LEX_KEY:\n if (next.value.trim() == \"true\") {\n log(\"Rule 5\");\n stack.push({'type': LEX_BOOLEAN, 'value': \"true\"});\n return true;\n }\n\n\n if (next.value.trim() == \"false\") {\n log(\"Rule 6\");\n stack.push({'type': LEX_BOOLEAN, 'value': \"false\"});\n return true;\n }\n\n if (next.value.trim() == \"null\") {\n log(\"Rule 7\");\n stack.push({'type': LEX_VALUE, 'value': null});\n return true;\n }\n break;\n\n case LEX_TOKEN:\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Rule 11a\");\n stack.peek().value += next.value;\n return true;\n }\n\n log(\"Rule 11c\");\n stack.push({type: LEX_KEY, value: next.value });\n return true;\n\n\n case LEX_INT:\n if (is(next, LEX_INT) && is(stack.peek(), LEX_KEY)) {\n log(\"Rule 11b\");\n stack.peek().value += next.value;\n return true;\n }\n\n log(\"Rule 11f\");\n next.type = LEX_VALUE;\n stack.push(next);\n return true;\n\n\n case LEX_QUOTE:\n log(\"Rule 11d\");\n next.type = LEX_VALUE;\n next.value = next.value;\n stack.push(next);\n return true;\n\n\n case LEX_BOOLEAN:\n log(\"Rule 11e\");\n next.type = LEX_VALUE;\n\n if (next.value == \"true\") {\n next.value = true;\n } else {\n next.value = false;\n }\n\n stack.push(next);\n return true;\n\n\n case LEX_FLOAT:\n log(\"Rule 11g\");\n next.type = LEX_VALUE;\n stack.push(next);\n return true;\n\n case LEX_VALUE:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12\");\n next.type = LEX_CVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13\");\n next.type = LEX_COVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_VALUE)) {\n log(\"Error rule 1\");\n let middleVal = stack.pop();\n stack.peek().value += '\"' + middleVal.value + '\"';\n stack.peek().value += next.value;\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_VLIST)) {\n log(\"Error rule 2\");\n let middleVal = stack.pop();\n let oldLastVal = stack.peek().value.pop();\n oldLastVal += '\"' + middleVal.value + '\"';\n oldLastVal += next.value;\n \n stack.peek().value.push(oldLastVal);\n \n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_KVLIST)) {\n log(\"Error rule 3\");\n let middleVal = stack.pop();\n let oldLastVal = stack.peek().value.pop();\n const qChar = next.single ? \"'\" : '\"';\n \n oldLastVal.value += qChar + middleVal.value + qChar;\n oldLastVal.value += next.value;\n \n stack.peek().value.push(oldLastVal);\n \n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Error rule 4\");\n let keyValue = stack.pop().value;\n next.value = keyValue + next.value;\n stack.push(next);\n return true;\n }\n\n break;\n\n case LEX_LIST:\n if (is(next, LEX_LIST) && is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12a\");\n next.type = LEX_CVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13a\");\n next.type = LEX_COVALUE;\n stack.pop();\n stack.push(next);\n return true;\n }\n break;\n\n case LEX_OBJ:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Rule 12b\");\n let toPush = {'type': LEX_CVALUE, 'value': next};\n stack.pop();\n stack.push(toPush);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Rule 13b\");\n let toPush = {'type': LEX_COVALUE, 'value': next};\n stack.pop();\n stack.push(toPush);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Error rule 9\");\n let key = stack.pop();\n stack.push({'type': LEX_KV, 'key': key.value.trim(), 'value': next});\n return true;\n }\n \n break;\n\n case LEX_CVALUE:\n if (is(stack.peek(), LEX_VLIST)) {\n log(\"Rule 14\");\n stack.peek().value.push(next.value);\n return true;\n }\n\n\n log(\"Rule 15\");\n stack.push({'type': LEX_VLIST, 'value': [next.value]});\n return true;\n\n case LEX_VLIST:\n if (is(stack.peek(), LEX_VALUE)) {\n log(\"Rule 15a\");\n next.value.unshift(stack.peek().value);\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_LIST)) {\n log(\"Rule 15b\");\n next.value.unshift(stack.peek().value);\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_OBJ)) {\n log(\"Rule 15c\");\n next.value.unshift(stack.peek());\n stack.pop();\n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && (stack.last(1), LEX_COMMA)) {\n log(\"Error rule 7\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push(next);\n\n return true;\n }\n\n if (is(stack.peek(), LEX_VLIST)) {\n log(\"Error rule 8\");\n stack.peek().value.push(next.value[0]);\n return true;\n }\n break;\n\n case LEX_COVALUE:\n\n if (is(stack.peek(), LEX_KEY) || is(stack.peek(), LEX_VALUE) || is(stack.peek(), LEX_VLIST)) {\n log(\"Rule 16\");\n let key = stack.pop();\n stack.push({'type': LEX_KV, 'key': key.value, 'value': next.value});\n return true;\n }\n\n\n throw new Error(\"Got a :value that can't be handled at line \" +\n next.row + \":\" + next.col);\n\n case LEX_KV:\n if (is(stack.last(0), LEX_COMMA) && is(stack.last(1), LEX_KVLIST)) {\n log(\"Rule 17\");\n stack.last(1).value.push(next);\n stack.pop();\n return true;\n }\n\n log(\"Rule 18\");\n stack.push({'type': LEX_KVLIST, 'value': [next]});\n return true;\n\n case LEX_KVLIST:\n if (is(stack.peek(), LEX_KVLIST)) {\n log(\"Rule 17a\");\n next.value.forEach(function (i) {\n stack.peek().value.push(i);\n });\n return true;\n }\n\n break;\n\n case LEX_RB:\n if (is(stack.peek(), LEX_VLIST) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 19\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_LIST, 'value': l.value});\n return true;\n }\n\n if (is(stack.peek(), LEX_LIST) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 19b\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_LIST, 'value': [l.value]});\n return true;\n }\n\n if (is(stack.peek(), LEX_LB)) {\n log(\"Rule 22\");\n stack.pop();\n stack.push({type: LEX_LIST, 'value': []});\n return true;\n }\n\n if (is(stack.peek(), LEX_VALUE) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 23\");\n let val = stack.pop().value;\n stack.pop();\n stack.push({type: LEX_LIST, 'value': [val]});\n return true;\n }\n\n if (is(stack.peek(), LEX_OBJ) && is(stack.last(1), LEX_LB)) {\n log(\"Rule 23b\");\n let val = stack.pop();\n stack.pop();\n stack.push({type: LEX_LIST, 'value': [val]});\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_COMMA)) {\n log(\"Error rule 5\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push({type: LEX_RB});\n return true;\n }\n\n \n if (is(stack.peek(), LEX_COMMA) && (\n is(stack.last(1), LEX_KEY)\n || is(stack.last(1), LEX_OBJ)\n || is(stack.last(1), LEX_VALUE))\n ) {\n log(\"Error rule 5a\");\n stack.pop();\n //let l = stack.pop();\n //stack.push({type: LEX_VALUE, 'value': l.value});\n stack.push({type: LEX_RB, 'value': ']'});\n log(\"Start subreduce...\");\n log(\"Content: \" + JSON.stringify(stack));\n while(reduce(stack));\n log(\"End subreduce\");\n\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_LB)) {\n log(\"Error rule 5b\");\n let v = stack.pop();\n stack.pop();\n stack.push({type: LEX_LIST, value: [v.value]});\n return true;\n }\n\n if (is(stack.peek(), LEX_COMMA) && is(stack.last(1), LEX_VLIST)) {\n log(\"Error rule 5c\");\n stack.pop();\n stack.push({type: LEX_RB});\n log(\"Start subreduce...\");\n log(\"Content: \" + JSON.stringify(stack));\n while(reduce(stack));\n log(\"End subreduce\");\n\n return true;\n }\n\n break;\n\n case LEX_RCB:\n if (is(stack.peek(), LEX_KVLIST) && is(stack.last(1), LEX_LCB)) {\n log(\"Rule 20\");\n let l = stack.pop();\n stack.pop();\n stack.push({'type': LEX_OBJ, 'value': l.value});\n return true;\n }\n\n if (is(stack.peek(), LEX_LCB)) {\n log(\"Rule 21\");\n stack.pop();\n stack.push({type: LEX_OBJ, 'value': null});\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY) && is(stack.last(1), LEX_COLON)) {\n log(\"Error rule 4a\");\n let l = stack.pop();\n stack.push({type: LEX_VALUE, 'value': l.value});\n log(\"Start subreduce... (\" + l.value + \")\");\n while(reduce(stack));\n log(\"End subreduce\");\n stack.push({type: LEX_RCB});\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Error rule 4b\");\n stack.push({type: LEX_VALUE, value: null});\n\n log(\"Starting subreduce...\");\n while (reduce(stack));\n log(\"End subreduce.\");\n \n stack.push({type: LEX_RCB});\n return true;\n }\n\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Error rule 10a\");\n stack.pop();\n stack.push({type: LEX_RCB});\n return true;\n }\n \n throw new Error(\"Found } that I can't handle at line \" +\n next.row + \":\" + next.col);\n\n \n case LEX_COMMA:\n if (is(stack.peek(), LEX_COMMA)) {\n log(\"Comma error rule 1\");\n // do nothing -- so don't push the extra comma onto the stack\n return true;\n }\n\n if (is(stack.peek(), LEX_KEY)) {\n log(\"Comma error rule 2\");\n const key = stack.pop();\n stack.push({type: LEX_VALUE, value: key.value});\n \n log(\"Starting subreduce...\");\n while (reduce(stack));\n log (\"End subreduce.\");\n \n stack.push(next);\n return true;\n }\n\n if (is(stack.peek(), LEX_COLON)) {\n log(\"Comma error rule 3\");\n stack.push({type: LEX_VALUE, value: null});\n \n log(\"Starting subreduce...\");\n while (reduce(stack));\n log (\"End subreduce.\");\n \n stack.push(next);\n return true;\n }\n\n }\n\n\n stack.push(next);\n return false;\n}\n\n\n\nfunction compileOST(tree, dupKeys) {\n let rawTypes = [\"boolean\", \"number\", \"string\"];\n\n if (rawTypes.indexOf((typeof tree)) != -1)\n return tree;\n\n if (tree === null)\n return null;\n\n if (Array.isArray(tree)) {\n let toR = [];\n while (tree.length > 0)\n toR.unshift(compileOST(tree.pop()));\n return toR;\n }\n \n\n if (is(tree, LEX_OBJ)) {\n let toR = {};\n if (tree.value === null)\n return {};\n tree.value.forEach(function (i) {\n const key = i.key;\n const val = compileOST(i.value);\n\n if (dupKeys && key in toR) {\n toR[key] = {\n \"value\": toR[key],\n \"next\": val\n };\n } else {\n toR[key] = val;\n }\n });\n return toR;\n }\n\n if (is(tree, LEX_LIST)) {\n return compileOST(tree.value);\n }\n\n // it must be a value\n return tree.value;\n}\n\n","// < begin copyright > \n// Copyright Ryan Marcus 2018\n// \n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n// \n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n// \n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// \n// < end copyright > \n \n\n\n\"use strict\";\n\nlet parser = require('./parser');\n\nmodule.exports.parse = parse;\nfunction parse(text, config) {\n let fallback = true;\n let duplicateKeys = false;\n\n if (config) {\n if ((\"fallback\" in config) && config[fallback] === false) {\n fallback = false;\n }\n\n duplicateKeys = \"duplicateKeys\" in config && config[\"duplicateKeys\"] === true;\n }\n\n try {\n return parser.parse(text, duplicateKeys);\n } catch (e) {\n // our parser threw an error! see if the JSON was valid...\n /* istanbul ignore next */\n if (fallback === false) {\n throw e;\n }\n \n try {\n let json = JSON.parse(text);\n // if we didn't throw, it was valid JSON!\n /* istanbul ignore next */\n console.warn(\"dirty-json got valid JSON that failed with the custom parser. We're returning the valid JSON, but please file a bug report here: https://github.com/RyanMarcus/dirty-json/issues -- the JSON that caused the failure was: \" + text);\n\n /* istanbul ignore next */\n return json;\n } catch (json_error) {\n throw e;\n }\n\n }\n}\n","import assert from 'node:assert';\nimport { AIResponseFormat, type AIUsageInfo } from '@/types';\nimport { Anthropic } from '@anthropic-ai/sdk';\nimport {\n DefaultAzureCredential,\n getBearerTokenProvider,\n} from '@azure/identity';\nimport { ifInBrowser } from '@midscene/shared/utils';\nimport dJSON from 'dirty-json';\nimport OpenAI, { AzureOpenAI } from 'openai';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { SocksProxyAgent } from 'socks-proxy-agent';\nimport {\n ANTHROPIC_API_KEY,\n AZURE_OPENAI_API_VERSION,\n AZURE_OPENAI_DEPLOYMENT,\n AZURE_OPENAI_ENDPOINT,\n AZURE_OPENAI_KEY,\n MIDSCENE_API_TYPE,\n MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON,\n MIDSCENE_AZURE_OPENAI_SCOPE,\n MIDSCENE_DEBUG_AI_PROFILE,\n MIDSCENE_LANGSMITH_DEBUG,\n MIDSCENE_MODEL_NAME,\n MIDSCENE_OPENAI_INIT_CONFIG_JSON,\n MIDSCENE_OPENAI_SOCKS_PROXY,\n MIDSCENE_USE_ANTHROPIC_SDK,\n MIDSCENE_USE_AZURE_OPENAI,\n OPENAI_API_KEY,\n OPENAI_BASE_URL,\n OPENAI_MAX_TOKENS,\n OPENAI_USE_AZURE,\n getAIConfig,\n getAIConfigInJson,\n} from '../../env';\nimport { AIActionType } from '../common';\nimport { findElementSchema } from '../prompt/llm-locator';\nimport { planSchema } from '../prompt/llm-planning';\nimport { assertSchema } from '../prompt/util';\n\nexport function checkAIConfig(preferVendor?: 'openAI') {\n if (preferVendor && preferVendor !== 'openAI') return false;\n if (getAIConfig(OPENAI_API_KEY)) return true;\n if (getAIConfig(MIDSCENE_USE_AZURE_OPENAI)) return true;\n if (getAIConfig(ANTHROPIC_API_KEY)) return true;\n\n return Boolean(getAIConfig(MIDSCENE_OPENAI_INIT_CONFIG_JSON));\n}\n\n// default model\nconst defaultModel = 'gpt-4o-2024-08-06';\nexport function getModelName() {\n let modelName = defaultModel;\n const nameInConfig = getAIConfig(MIDSCENE_MODEL_NAME);\n if (nameInConfig) {\n modelName = nameInConfig;\n }\n return modelName;\n}\n\nasync function createChatClient({\n AIActionTypeValue,\n}: {\n AIActionTypeValue: AIActionType;\n}): Promise<{\n completion: OpenAI.Chat.Completions;\n style: 'openai' | 'anthropic';\n}> {\n let openai: OpenAI | AzureOpenAI | undefined;\n const extraConfig = getAIConfigInJson(MIDSCENE_OPENAI_INIT_CONFIG_JSON);\n\n const socksProxy = getAIConfig(MIDSCENE_OPENAI_SOCKS_PROXY);\n const socksAgent = socksProxy ? new SocksProxyAgent(socksProxy) : undefined;\n\n if (getAIConfig(OPENAI_USE_AZURE)) {\n // this is deprecated\n openai = new AzureOpenAI({\n baseURL: getAIConfig(OPENAI_BASE_URL),\n apiKey: getAIConfig(OPENAI_API_KEY),\n httpAgent: socksAgent,\n ...extraConfig,\n dangerouslyAllowBrowser: true,\n }) as OpenAI;\n } else if (getAIConfig(MIDSCENE_USE_AZURE_OPENAI)) {\n const extraAzureConfig = getAIConfigInJson(\n MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON,\n );\n\n // https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart?tabs=bash%2Cjavascript-key%2Ctypescript-keyless%2Cpython&pivots=programming-language-javascript#rest-api\n // keyless authentication\n const scope = getAIConfig(MIDSCENE_AZURE_OPENAI_SCOPE);\n let tokenProvider: any = undefined;\n if (scope) {\n assert(\n !ifInBrowser,\n 'Azure OpenAI is not supported in browser with Midscene.',\n );\n const credential = new DefaultAzureCredential();\n\n assert(scope, 'MIDSCENE_AZURE_OPENAI_SCOPE is required');\n tokenProvider = getBearerTokenProvider(credential, scope);\n\n openai = new AzureOpenAI({\n azureADTokenProvider: tokenProvider,\n endpoint: getAIConfig(AZURE_OPENAI_ENDPOINT),\n apiVersion: getAIConfig(AZURE_OPENAI_API_VERSION),\n deployment: getAIConfig(AZURE_OPENAI_DEPLOYMENT),\n ...extraConfig,\n ...extraAzureConfig,\n });\n } else {\n // endpoint, apiKey, apiVersion, deployment\n openai = new AzureOpenAI({\n apiKey: getAIConfig(AZURE_OPENAI_KEY),\n endpoint: getAIConfig(AZURE_OPENAI_ENDPOINT),\n apiVersion: getAIConfig(AZURE_OPENAI_API_VERSION),\n deployment: getAIConfig(AZURE_OPENAI_DEPLOYMENT),\n dangerouslyAllowBrowser: true,\n ...extraConfig,\n ...extraAzureConfig,\n });\n }\n } else if (!getAIConfig(MIDSCENE_USE_ANTHROPIC_SDK)) {\n openai = new OpenAI({\n baseURL: getAIConfig(OPENAI_BASE_URL),\n apiKey: getAIConfig(OPENAI_API_KEY),\n httpAgent: socksAgent,\n ...extraConfig,\n defaultHeaders: {\n ...(extraConfig?.defaultHeaders || {}),\n [MIDSCENE_API_TYPE]: AIActionTypeValue.toString(),\n },\n dangerouslyAllowBrowser: true,\n });\n }\n\n if (openai && getAIConfig(MIDSCENE_LANGSMITH_DEBUG)) {\n if (ifInBrowser) {\n throw new Error('langsmith is not supported in browser');\n }\n console.log('DEBUGGING MODE: langsmith wrapper enabled');\n const { wrapOpenAI } = await import('langsmith/wrappers');\n openai = wrapOpenAI(openai);\n }\n\n if (typeof openai !== 'undefined') {\n return {\n completion: openai.chat.completions,\n style: 'openai',\n };\n }\n\n // Anthropic\n if (getAIConfig(MIDSCENE_USE_ANTHROPIC_SDK)) {\n const apiKey = getAIConfig(ANTHROPIC_API_KEY);\n assert(apiKey, 'ANTHROPIC_API_KEY is required');\n openai = new Anthropic({\n apiKey,\n dangerouslyAllowBrowser: true,\n }) as any;\n }\n\n if (typeof openai !== 'undefined' && (openai as any).messages) {\n return {\n completion: (openai as any).messages,\n style: 'anthropic',\n };\n }\n\n throw new Error('Openai SDK or Anthropic SDK is not initialized');\n}\n\nexport async function call(\n messages: ChatCompletionMessageParam[],\n AIActionTypeValue: AIActionType,\n responseFormat?:\n | OpenAI.ChatCompletionCreateParams['response_format']\n | OpenAI.ResponseFormatJSONObject,\n): Promise<{ content: string; usage?: AIUsageInfo }> {\n const { completion, style } = await createChatClient({\n AIActionTypeValue,\n });\n const shouldPrintTiming =\n typeof getAIConfig(MIDSCENE_DEBUG_AI_PROFILE) === 'string';\n\n const maxTokens = getAIConfig(OPENAI_MAX_TOKENS);\n\n const startTime = Date.now();\n const model = getModelName();\n let content: string | undefined;\n let usage: OpenAI.CompletionUsage | undefined;\n const commonConfig = {\n temperature: 0.1,\n stream: false,\n max_tokens:\n typeof maxTokens === 'number'\n ? maxTokens\n : Number.parseInt(maxTokens || '2048', 10),\n };\n\n if (style === 'openai') {\n const result = await completion.create({\n model,\n messages,\n response_format: responseFormat,\n ...commonConfig,\n // betas: ['computer-use-2024-10-22'],\n } as any);\n shouldPrintTiming &&\n console.log(\n 'Midscene - AI call',\n model,\n result.usage,\n `${Date.now() - startTime}ms`,\n );\n assert(\n result.choices,\n `invalid response from LLM service: ${JSON.stringify(result)}`,\n );\n content = result.choices[0].message.content!;\n assert(content, 'empty content');\n usage = result.usage;\n } else if (style === 'anthropic') {\n const convertImageContent = (content: any) => {\n if (content.type === 'image_url') {\n const imgBase64 = content.image_url.url;\n assert(imgBase64, 'image_url is required');\n return {\n source: {\n type: 'base64',\n media_type: imgBase64.includes('data:image/png;base64,')\n ? 'image/png'\n : 'image/jpeg',\n data: imgBase64.split(',')[1],\n },\n type: 'image',\n };\n }\n return content;\n };\n\n const result = await completion.create({\n model,\n system: 'You are a versatile professional in software UI automation',\n messages: messages.map((m) => ({\n role: 'user',\n content: Array.isArray(m.content)\n ? (m.content as any).map(convertImageContent)\n : m.content,\n })),\n response_format: responseFormat,\n ...commonConfig,\n } as any);\n content = (result as any).content[0].text as string;\n assert(content, 'empty content');\n usage = result.usage;\n }\n\n return { content: content || '', usage };\n}\n\nexport async function callToGetJSONObject<T>(\n messages: ChatCompletionMessageParam[],\n AIActionTypeValue: AIActionType,\n): Promise<{ content: T; usage?: AIUsageInfo }> {\n // gpt-4o-2024-05-13 only supports json_object response format\n let responseFormat:\n | OpenAI.ChatCompletionCreateParams['response_format']\n | OpenAI.ResponseFormatJSONObject\n | undefined;\n\n const model = getModelName();\n\n if (model.includes('gpt-4o')) {\n switch (AIActionTypeValue) {\n case AIActionType.ASSERT:\n responseFormat = assertSchema;\n break;\n case AIActionType.INSPECT_ELEMENT:\n responseFormat = findElementSchema;\n break;\n case AIActionType.EXTRACT_DATA:\n //TODO: Currently the restriction type can only be a json subset of the constraint, and the way the extract api is used needs to be adjusted to limit the user's data to this as well\n // targetResponseFormat = extractDataSchema;\n responseFormat = { type: AIResponseFormat.JSON };\n break;\n case AIActionType.PLAN:\n responseFormat = planSchema;\n break;\n }\n\n if (model === 'gpt-4o-2024-05-13' || !responseFormat) {\n responseFormat = { type: AIResponseFormat.JSON };\n }\n }\n\n const response = await call(messages, AIActionTypeValue, responseFormat);\n assert(response, 'empty response');\n const jsonContent = safeParseJson(response.content);\n return { content: jsonContent, usage: response.usage };\n}\n\nexport function extractJSONFromCodeBlock(response: string) {\n try {\n // First, try to match a JSON object directly in the response\n const jsonMatch = response.match(/^\\s*(\\{[\\s\\S]*\\})\\s*$/);\n if (jsonMatch) {\n return jsonMatch[1];\n }\n\n // If no direct JSON object is found, try to extract JSON from a code block\n const codeBlockMatch = response.match(\n /```(?:json)?\\s*(\\{[\\s\\S]*?\\})\\s*```/,\n );\n if (codeBlockMatch) {\n return codeBlockMatch[1];\n }\n\n // If no code block is found, try to find a JSON-like structure in the text\n const jsonLikeMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (jsonLikeMatch) {\n return jsonLikeMatch[0];\n }\n } catch {}\n // If no JSON-like structure is found, return the original response\n return response;\n}\n\nexport function safeParseJson(input: string) {\n const cleanJsonString = extractJSONFromCodeBlock(input);\n // match the point\n if (cleanJsonString.match(/\\((\\d+),(\\d+)\\)/)) {\n return cleanJsonString\n .match(/\\((\\d+),(\\d+)\\)/)\n ?.slice(1)\n .map(Number);\n }\n try {\n return JSON.parse(cleanJsonString);\n } catch {}\n try {\n return dJSON.parse(cleanJsonString);\n } catch (e) {\n console.log('e:', e);\n }\n throw Error(`failed to parse json response: ${input}`);\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { NodeType } from '@midscene/shared/constants';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\n\nexport * from './yaml.d';\n\nexport interface Point {\n left: number;\n top: number;\n}\n\nexport interface Size {\n width: number; // device independent window size\n height: number;\n dpr?: number; // the scale factor of the screenshots\n}\n\nexport type Rect = Point & Size & { zoom?: number };\n\nexport abstract class BaseElement {\n abstract id: string;\n\n abstract indexId?: number; // markerId for web\n\n abstract attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n\n abstract content: string;\n\n abstract rect: Rect;\n\n abstract center: [number, number];\n\n abstract locator?: string;\n}\n\nexport interface ElementTreeNode<\n ElementType extends BaseElement = BaseElement,\n> {\n node: ElementType | null;\n children: ElementTreeNode<ElementType>[];\n}\n\nexport type AIUsageInfo = Record<string, any>;\n\n/**\n * openai\n *\n */\nexport enum AIResponseFormat {\n JSON = 'json_object',\n TEXT = 'text',\n}\n\nexport type AISingleElementResponseById = {\n id: string;\n reason?: string;\n text?: string;\n};\n\nexport type AISingleElementResponseByPosition = {\n position: {\n x: number;\n y: number;\n };\n reason: string;\n text: string;\n};\n\nexport type AISingleElementResponse = AISingleElementResponseById;\nexport interface AIElementIdResponse {\n elements: {\n id: string;\n reason?: string;\n text?: string;\n }[];\n errors?: string[];\n}\n\nexport type AIElementResponse = AIElementIdResponse;\n\nexport interface AISectionParseResponse<DataShape> {\n data: DataShape;\n sections?: LiteUISection[];\n errors?: string[];\n}\n\nexport interface AIAssertionResponse {\n pass: boolean;\n thought: string;\n}\n\n/**\n * context\n */\n\nexport abstract class UIContext<ElementType extends BaseElement = BaseElement> {\n abstract screenshotBase64: string;\n\n abstract screenshotBase64WithElementMarker?: string;\n\n // @deprecated('use tree instead')\n abstract content: ElementType[];\n\n abstract tree: ElementTreeNode<ElementType>;\n\n abstract size: Size;\n}\n\n/**\n * insight\n */\n\nexport type CallAIFn = <T>(\n messages: ChatCompletionMessageParam[],\n) => Promise<T>;\n\nexport interface InsightOptions {\n taskInfo?: Omit<InsightTaskInfo, 'durationMs'>;\n aiVendorFn?: CallAIFn;\n generateElement?: (opts: {\n content?: string;\n rect: BaseElement['rect'];\n }) => BaseElement;\n}\n\n// export interface UISection {\n// name: string;\n// description: string;\n// sectionCharacteristics: string;\n// rect: Rect;\n// content: BaseElement[];\n// }\n\nexport type EnsureObject<T> = { [K in keyof T]: any };\n\nexport type InsightAction = 'locate' | 'extract' | 'assert';\n\nexport type InsightExtractParam = string | Record<string, string>;\n\nexport interface InsightTaskInfo {\n durationMs: number;\n formatResponse?: string;\n rawResponse?: string;\n usage?: AIUsageInfo;\n}\n\nexport interface DumpMeta {\n sdkVersion: string;\n logTime: number;\n model_name: string;\n model_description?: string;\n}\n\nexport interface ReportDumpWithAttributes {\n dumpString: string;\n attributes?: Record<string, any>;\n}\n\nexport interface InsightDump extends DumpMeta {\n type: 'locate' | 'extract' | 'assert';\n logId: string;\n context: UIContext;\n userQuery: {\n element?: string;\n dataDemand?: InsightExtractParam;\n sections?: Record<string, string>;\n assertion?: string;\n }; // ?\n quickAnswer?: Partial<AISingleElementResponse> | null;\n matchedSection: [];\n matchedElement: BaseElement[];\n data: any;\n assertionPass?: boolean;\n assertionThought?: string;\n taskInfo: InsightTaskInfo;\n error?: string;\n}\n\nexport type PartialInsightDumpFromSDK = Omit<\n InsightDump,\n 'sdkVersion' | 'logTime' | 'logId' | 'model_name'\n>;\n\nexport type DumpSubscriber = (dump: InsightDump) => Promise<void> | void;\n\n// intermediate variables to optimize the return value by AI\nexport interface LiteUISection {\n name: string;\n description: string;\n sectionCharacteristics: string;\n textIds: string[];\n}\n\nexport type ElementById = (id: string) => BaseElement | null;\n\nexport type InsightAssertionResponse = AIAssertionResponse;\n\n/**\n * agent\n */\n\nexport type OnTaskStartTip = (tip: string) => Promise<void> | void;\n\nexport interface AgentWaitForOpt {\n checkIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface AgentAssertOpt {\n keepRawResponse?: boolean;\n}\n\n/**\n * planning\n *\n */\n\nexport interface PlanningLocateParam {\n id?: string;\n position?: {\n x: number;\n y: number;\n };\n prompt: string;\n}\n\nexport interface PlanningAction<ParamType = any> {\n thought?: string;\n type:\n | 'Locate'\n | 'Tap'\n | 'Drag'\n | 'Hover'\n | 'Input'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Error'\n | 'FalsyConditionStatement'\n | 'Assert'\n | 'AssertWithoutThrow'\n | 'Sleep'\n | 'Finished';\n param: ParamType;\n locate: PlanningLocateParam | null;\n}\n\nexport interface PlanningAIResponse {\n actions: PlanningAction[];\n taskWillBeAccomplished: boolean;\n furtherPlan?: PlanningFurtherPlan | null;\n error?: string;\n}\n\nexport interface PlanningFurtherPlan {\n whatToDoNext: string;\n whatHaveDone: string;\n}\nexport type PlanningActionParamPlan = PlanningFurtherPlan;\n\nexport type PlanningActionParamTap = null;\nexport type PlanningActionParamHover = null;\nexport interface PlanningActionParamInputOrKeyPress {\n value: string;\n}\nexport interface PlanningActionParamScroll {\n direction: 'down' | 'up' | 'right' | 'left';\n scrollType: 'once' | 'untilBottom' | 'untilTop' | 'untilRight' | 'untilLeft';\n distance: null | number;\n}\n\nexport interface PlanningActionParamAssert {\n assertion: string;\n}\n\nexport interface PlanningActionParamSleep {\n timeMs: number;\n}\n\nexport interface PlanningActionParamError {\n thought: string;\n}\n\nexport type PlanningActionParamWaitFor = AgentWaitForOpt & {\n assertion: string;\n};\n/**\n * misc\n */\n\nexport interface Color {\n name: string;\n hex: string;\n}\n\nexport interface BaseAgentParserOpt {\n selector?: string;\n ignoreMarker?: boolean;\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PuppeteerParserOpt extends BaseAgentParserOpt {}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PlaywrightParserOpt extends BaseAgentParserOpt {}\n\n/*\naction\n*/\nexport interface ExecutionTaskProgressOptions {\n onTaskStart?: (task: ExecutionTask) => Promise<void> | void;\n}\n\nexport interface ExecutionRecorderItem {\n type: 'screenshot';\n ts: number;\n screenshot?: string;\n timing?: string;\n}\n\nexport type ExecutionTaskType = 'Planning' | 'Insight' | 'Action' | 'Assertion';\n\nexport interface ExecutorContext {\n task: ExecutionTask;\n element?: BaseElement | null;\n}\n\nexport interface TaskCacheInfo {\n hit: boolean;\n}\n\nexport interface ExecutionTaskApply<\n Type extends ExecutionTaskType = any,\n TaskParam = any,\n TaskOutput = any,\n TaskLog = any,\n> {\n type: Type;\n subType?: string;\n param?: TaskParam;\n thought?: string;\n locate: PlanningLocateParam | null;\n quickAnswer?: AISingleElementResponse | null;\n pageContext?: UIContext;\n executor: (\n param: TaskParam,\n context: ExecutorContext,\n ) => // biome-ignore lint/suspicious/noConfusingVoidType: <explanation>\n | Promise<ExecutionTaskReturn<TaskOutput, TaskLog> | undefined | void>\n | undefined\n | void;\n}\n\nexport interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {\n output?: TaskOutput;\n log?: TaskLog;\n recorder?: ExecutionRecorderItem[];\n cache?: TaskCacheInfo;\n}\n\nexport type ExecutionTask<\n E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<\n any,\n any,\n any\n >,\n> = E &\n ExecutionTaskReturn<\n E extends ExecutionTaskApply<any, any, infer TaskOutput, any>\n ? TaskOutput\n : unknown,\n E extends ExecutionTaskApply<any, any, any, infer TaskLog>\n ? TaskLog\n : unknown\n > & {\n status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';\n error?: string;\n errorStack?: string;\n timing?: {\n start: number;\n end?: number;\n cost?: number;\n aiCost?: number;\n };\n };\n\nexport interface ExecutionDump extends DumpMeta {\n name: string;\n description?: string;\n tasks: ExecutionTask[];\n}\n\n/*\ntask - insight-locate\n*/\nexport type ExecutionTaskInsightLocateParam = PlanningLocateParam;\n\nexport interface ExecutionTaskInsightLocateOutput {\n element: BaseElement | null;\n}\n\nexport interface ExecutionTaskInsightDumpLog {\n dump?: InsightDump;\n}\n\nexport type ExecutionTaskInsightLocateApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightLocateParam,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightLocate =\n ExecutionTask<ExecutionTaskInsightLocateApply>;\n\n/*\ntask - insight-query\n*/\nexport interface ExecutionTaskInsightQueryParam {\n dataDemand: InsightExtractParam;\n}\n\nexport interface ExecutionTaskInsightQueryOutput {\n data: any;\n}\n\nexport type ExecutionTaskInsightQueryApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightQueryParam,\n any,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightQuery =\n ExecutionTask<ExecutionTaskInsightQueryApply>;\n\n/*\ntask - assertion\n*/\nexport interface ExecutionTaskInsightAssertionParam {\n assertion: string;\n}\n\nexport type ExecutionTaskInsightAssertionApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightAssertionParam,\n InsightAssertionResponse,\n ExecutionTaskInsightDumpLog\n>;\n\nexport type ExecutionTaskInsightAssertion =\n ExecutionTask<ExecutionTaskInsightAssertionApply>;\n\n/*\ntask - action (i.e. interact) \n*/\nexport type ExecutionTaskActionApply<ActionParam = any> = ExecutionTaskApply<\n 'Action',\n ActionParam,\n void,\n void\n>;\n\nexport type ExecutionTaskAction = ExecutionTask<ExecutionTaskActionApply>;\n\n/*\ntask - planning\n*/\n\nexport type ExecutionTaskPlanningApply = ExecutionTaskApply<\n 'Planning',\n {\n userPrompt: string;\n whatHaveDone?: string;\n originalPrompt?: string;\n },\n PlanningAIResponse\n>;\n\nexport type ExecutionTaskPlanning = ExecutionTask<ExecutionTaskPlanningApply>;\n\n/*\nGrouped dump\n*/\nexport interface GroupedActionDump {\n groupName: string;\n groupDescription?: string;\n executions: ExecutionDump[];\n}\n","import assert from 'node:assert';\nimport type { AIUsageInfo } from '@/types';\n\nimport type {\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n} from 'openai/resources';\nimport { callToGetJSONObject, checkAIConfig } from './service-caller';\n\nexport type AIArgs = [\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n];\n\nexport enum AIActionType {\n ASSERT = 0,\n INSPECT_ELEMENT = 1,\n EXTRACT_DATA = 2,\n PLAN = 3,\n}\n\nexport async function callAiFn<T>(\n msgs: AIArgs,\n AIActionTypeValue: AIActionType,\n): Promise<{ content: T; usage?: AIUsageInfo }> {\n assert(\n checkAIConfig(),\n 'Cannot find config for AI model service. You should set it before using. https://midscenejs.com/model-provider.html',\n );\n\n const { content, usage } = await callToGetJSONObject<T>(\n msgs,\n AIActionTypeValue,\n );\n return { content, usage };\n}\n","import { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\nimport { systemPromptToLocateElementPosition } from './ui-tars-locator';\n\nexport function systemPromptToLocateElement() {\n if (getAIConfig(MATCH_BY_POSITION)) {\n return systemPromptToLocateElementPosition();\n }\n return `\n## Role:\nYou are an expert in software page image (2D) and page element text analysis.\n\n## Objective:\n- Identify elements in screenshots and text that match the user's description.\n- Return JSON data containing the selection reason and element ID.\n\n## Skills:\n- Image analysis and recognition\n- Multilingual text understanding\n- Software UI design and testing\n\n## Workflow:\n1. 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.\n2. Based on the user's description, locate the target element ID in the list of element descriptions and the screenshot.\n3. Found the required number of elements\n4. Return JSON data containing the selection reason and element ID.\n\n## Constraints:\n- Strictly adhere to the specified location when describing the required element; do not select elements from other locations.\n- Elements in the image with NodeType other than \"TEXT Node\" have been highlighted to identify the element among multiple non-text elements.\n- 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.\n- If no elements are found, the \"elements\" array should be empty.\n- The returned data must conform to the specified JSON format.\n- The returned value id information must use the id from element info (important: **use id not indexId, id is hash content**)\n\n## Output Format:\n\nPlease return the result in JSON format as follows:\n\n\\`\\`\\`json\n{\n \"elements\": [\n // If no matching elements are found, return an empty array []\n {\n \"reason\": \"PLACEHOLDER\", // The thought process for finding the element, replace PLACEHOLDER with your thought process\n \"text\": \"PLACEHOLDER\", // Replace PLACEHOLDER with the text of elementInfo, if none, leave empty\n \"id\": \"PLACEHOLDER\" // Replace PLACEHOLDER with the ID (important: **use id not indexId, id is hash content**) of elementInfo\n }\n // More elements...\n ],\n \"errors\": [] // Array of strings containing any error messages\n}\n\\`\\`\\`\n\n## Example:\nExample 1:\nInput Example:\n\\`\\`\\`json\n// Description: \"Shopping cart icon in the upper right corner\"\n{\n \"description\": \"PLACEHOLDER\", // Description of the target element\n \"screenshot\": \"path/screenshot.png\",\n \"text\": '{\n \"pageSize\": {\n \"width\": 400, // Width of the page\n \"height\": 905 // Height of the page\n },\n \"elementInfos\": [\n {\n \"id\": \"1231\", // ID of the element\n \"indexId\": \"0\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": { // Attributes of the element\n \"nodeType\": \"IMG Node\", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node\n \"src\": \"https://ap-southeast-3.m\",\n \"class\": \".img\"\n },\n \"content\": \"\", // Text content of the element\n \"rect\": {\n \"left\": 280, // Distance from the left side of the page\n \"top\": 8, // Distance from the top of the page\n \"width\": 44, // Width of the element\n \"height\": 44 // Height of the element\n }\n },\n {\n \"id\": \"66551\", // ID of the element\n \"indexId\": \"1\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": { // Attributes of the element\n \"nodeType\": \"IMG Node\", // Type of element, types include: TEXT Node, IMG Node, BUTTON Node, INPUT Node\n \"src\": \"data:image/png;base64,iVBORw0KGgoAAAANSU...\",\n \"class\": \".icon\"\n },\n \"content\": \"\", // Text content of the element\n \"rect\": {\n \"left\": 350, // Distance from the left side of the page\n \"top\": 16, // Distance from the top of the page\n \"width\": 25, // Width of the element\n \"height\": 25 // Height of the element\n }\n },\n ...\n {\n \"id\": \"12344\",\n \"indexId\": \"2\", // Index of the element,The image is labeled to the left of the element\n \"attributes\": {\n \"nodeType\": \"TEXT Node\",\n \"class\": \".product-name\"\n },\n \"center\": [\n 288,\n 834\n ],\n \"content\": \"Mango Drink\",\n \"rect\": {\n \"left\": 188,\n \"top\": 827,\n \"width\": 199,\n \"height\": 13\n }\n },\n ...\n ]\n }\n '\n}\n\\`\\`\\`\nOutput Example:\n\\`\\`\\`json\n{\n \"elements\": [\n {\n // Describe the reason for finding this element, replace with actual value in practice\n \"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\",\n \"text\": \"\",\n // ID(**use id not indexId**) of this element, replace with actual value in practice, **use id not indexId**\n \"id\": \"1231\"\n }\n ],\n \"errors\": []\n}\n\\`\\`\\`\n \n `;\n}\n\nexport const findElementSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'find_elements',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n elements: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n reason: {\n type: 'string',\n description: 'Reason for finding this element',\n },\n text: {\n type: 'string',\n description: 'Text content of the element',\n },\n id: {\n type: 'string',\n description: 'ID of this element',\n },\n },\n required: ['reason', 'text', 'id'],\n additionalProperties: false,\n },\n description: 'List of found elements',\n },\n errors: {\n type: 'array',\n items: {\n type: 'string',\n },\n description: 'List of error messages, if any',\n },\n },\n required: ['elements', 'errors'],\n additionalProperties: false,\n },\n },\n};\n\nexport const findElementPrompt = new PromptTemplate({\n template: `\n Here is the item user want to find. Just go ahead:\n =====================================\n {{\n \"description\": \"{targetElementDescription}\",\n \"multi\": {multi}\n }}\n =====================================\n\n pageDescription: {pageDescription}\n `,\n inputVariables: ['pageDescription', 'targetElementDescription', 'multi'],\n});\n","import type { Action } from '../ui-tars-planning';\n\nexport function getTimeZoneInfo(): { timezone: string; isChina: boolean } {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const offset = -new Date().getTimezoneOffset() / 60;\n\n return {\n timezone: `UTC${offset >= 0 ? '+' : ''}${offset}`,\n isChina: timeZone === 'Asia/Shanghai',\n };\n}\n\nexport const language = getTimeZoneInfo().isChina ? 'Chinese' : 'English';\n\nexport const uiTarsPlanningPrompt = `\nYou are a GUI agent. You are given a task and your action history, with screenshots. You need to perform the next action to complete the task. \n\n## Output Format\n\\`\\`\\`\nThought: ...\nAction: ...\n\\`\\`\\`\n\n## Action Space\nclick(start_box='[x1, y1, x2, y2]')\nleft_double(start_box='[x1, y1, x2, y2]')\nright_single(start_box='[x1, y1, x2, y2]')\ndrag(start_box='[x1, y1, x2, y2]', end_box='[x3, y3, x4, y4]')\nhotkey(key='')\ntype(content='') #If you want to submit your input, use \"\\\\n\" at the end of \\`content\\`.\nscroll(start_box='[x1, y1, x2, y2]', direction='down or up or right or left')\nwait() #Sleep for 5s and take a screenshot to check for any changes.\nfinished()\ncall_user() # Submit the task and call the user when the task is unsolvable, or when you need the user's help.\n\n## Note\n- Use ${language} in \\`Thought\\` part.\n- Write a small plan and finally summarize your next action (with its target element) in one sentence in \\`Thought\\` part.\n\n## User Instruction\n`;\n\nexport const getSummary = (prediction: string) =>\n prediction\n .replace(/Reflection:[\\s\\S]*?(?=Action_Summary:|Action:|$)/g, '')\n .trim();\n","import { language } from './ui-tars-planning';\n\n// claude 3.5 sonnet computer The ability to understand the content of the image is better, Does not provide element snapshot effect\nexport function systemPromptToLocateElementPosition() {\n return `\nYou are a GUI agent. You are given a task and your action history, with screenshots. You need to perform the next action to complete the task. \n\n## Output Format\n\\`\\`\\`\nThought: ...\nAction: ...\n\\`\\`\\`\n\n## Action Space\nclick(start_box='[x1, y1, x2, y2]')\nleft_double(start_box='[x1, y1, x2, y2]')\nright_single(start_box='[x1, y1, x2, y2]')\ndrag(start_box='[x1, y1, x2, y2]', end_box='[x3, y3, x4, y4]')\nhotkey(key='')\ntype(content='') #If you want to submit your input, use \"\\\\n\" at the end of \\`content\\`.\nscroll(start_box='[x1, y1, x2, y2]', direction='down or up or right or left')\nwait() #Sleep for 5s and take a screenshot to check for any changes.\nfinished()\ncall_user() # Submit the task and call the user when the task is unsolvable, or when you need the user's help.\n\n## Note\n- Use ${language} in \\`Thought\\` part.\n- Write a small plan and finally summarize your next action (with its target element) in one sentence in \\`Thought\\` part.\n\n## User Instruction\n `;\n}\n","import { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\nimport { samplePageDescription } from './util';\n\nconst quickAnswerFormat = () => {\n const matchByPosition = getAIConfig(MATCH_BY_POSITION);\n\n const locationFormat = {\n position: {\n description:\n '\"position\": { x: number; y: number } // Represents the position of the element; replace with actual values in practice (ensure it reflects the element\\'s position)',\n format: '\"position\": { x: number; y: number }',\n sample:\n '{\"prompt\": \"the search bar\" // Use language consistent with the information on the page}',\n locateParam: `{\n \"prompt\"?: string // the description of the element to find. It can only be omitted when locate is null.\n } | null // If it's not on the page, the LocateParam should be null`,\n },\n id: {\n description:\n '\"id\": string // Represents the ID of the element; replace with actual values in practice',\n format: '\"id\": string',\n sample: `{\"id\": \"c81c4e9a33\", \"prompt\": \"the search bar\"}`,\n locateParam: `{\n \"id\": string, // the id of the element found. It should either be the id marked with a rectangle in the screenshot or the id described in the description.\n \"prompt\"?: string // the description of the element to find. It can only be omitted when locate is null.\n } | null // If it's not on the page, the LocateParam should be null`,\n },\n };\n\n const type = matchByPosition ? 'position' : 'id';\n const format = locationFormat[type];\n\n return {\n description: format.description,\n format: format.format,\n sample: format.sample,\n locateParam: format.locateParam,\n };\n};\n\nconst systemTemplate = `\n## Role\n\nYou are a versatile professional in software UI automation. Your outstanding contributions will impact the user experience of billions of users.\n\n## Objective\n\n- Decompose the instruction user asked into a series of actions\n- Locate the target element if possible\n- If the instruction cannot be accomplished, give a further plan.\n\n## Workflow\n\n1. Receive the user's element description, screenshot, and instruction.\n2. Decompose the user's task into a sequence of actions, and place it in the \\`actions\\` field. There are different types of actions (Tap / Hover / Input / KeyboardPress / Scroll / FalsyConditionStatement / Sleep). The \"About the action\" section below will give you more details.\n3. Precisely locate the target element if it's already shown in the screenshot, put the location info in the \\`locate\\` field of the action.\n4. If some target elements is not shown in the screenshot, consider the user's instruction is not feasible on this page. Follow the next steps.\n5. Consider whether the user's instruction will be accomplished after all the actions\n - If yes, set \\`taskWillBeAccomplished\\` to true\n - If no, don't plan more actions by closing the array. Get ready to reevaluate the task. Some talent people like you will handle this. Give him a clear description of what have been done and what to do next. Put your new plan in the \\`furtherPlan\\` field. The \"How to compose the \\`taskWillBeAccomplished\\` and \\`furtherPlan\\` fields\" section will give you more details.\n\n## Constraints\n\n- All the actions you composed MUST be based on the page context information you get.\n- Trust the \"What have been done\" field about the task (if any), don't repeat actions in it.\n- Respond only with valid JSON. Do not write an introduction or summary or markdown prefix like \\`\\`\\`json\\`\\`\\`.\n- If you cannot plan any action at all (i.e. empty actions array), set reason in the \\`error\\` field.\n\n## About the \\`actions\\` field\n\n### The common \\`locate\\` param\n\nThe \\`locate\\` param is commonly used in the \\`param\\` field of the action, means to locate the target element to perform the action, it follows the following scheme:\n\ntype LocateParam = {locateParam}\n\n### Supported actions\n\nEach action has a \\`type\\` and corresponding \\`param\\`. To be detailed:\n- type: 'Tap', tap the located element\n * {{ locate: LocateParam, param: null }}\n- type: 'Hover', move mouse over to the located element\n * {{ locate: LocateParam, param: null }}\n- type: 'Input', replace the value in the input field\n * {{ locate: LocateParam, param: {{ value: string }} }}\n * \\`value\\` is the final required input value based on the existing input. No matter what modifications are required, just provide the final value to replace the existing input value. \n- type: 'KeyboardPress', press a key\n * {{ param: {{ value: string }} }}\n- type: 'Scroll', scroll up or down.\n * {{ \n locate: LocateParam | null, \n param: {{ \n direction: 'down'(default) | 'up' | 'right' | 'left', \n scrollType: 'once' (default) | 'untilBottom' | 'untilTop' | 'untilRight' | 'untilLeft', \n distance: null | number \n }} \n }}\n * To scroll some specific element, put the element at the center of the region in the \\`locate\\` field. If it's a page scroll, put \\`null\\` in the \\`locate\\` field. \n * \\`param\\` is required in this action. If some fields are not specified, use direction \\`down\\`, \\`once\\` scroll type, and \\`null\\` distance.\n- type: 'FalsyConditionStatement'\n * {{ param: null }}\n * use this action when the instruction is an \"if\" statement and the condition is falsy.\n- type: 'Sleep'\n * {{ param: {{ timeMs: number }} }}\n\n## How to compose the \\`taskWillBeAccomplished\\` and \\`furtherPlan\\` fields ?\n\n\\`taskWillBeAccomplished\\` is a boolean field, means whether the task will be accomplished after all the actions.\n\n\\`furtherPlan\\` is used when the task cannot be accomplished. It follows the scheme {{ whatHaveDone: string, whatToDoNext: string }}:\n- \\`whatHaveDone\\`: a string, describe what have been done after the previous actions.\n- \\`whatToDoNext\\`: a string, describe what should be done next after the previous actions has finished. It should be a concise and clear description of the actions to be performed. Make sure you don't lose any necessary steps user asked.\n`;\n\nconst outputTemplate = `\n## Output JSON Format:\n\nThe JSON format is as follows:\n\n{{\n \"actions\": [\n {{\n \"thought\": \"Reasons for generating this task, and why this task is feasible on this page.\", // Use the same language as the user's instruction.\n \"type\": \"Tap\",\n \"param\": null,\n \"locate\": {sample} | null,\n }},\n // ... more actions\n ],\n \"taskWillBeAccomplished\": boolean,\n \"furtherPlan\": {{ \"whatHaveDone\": string, \"whatToDoNext\": string }} | null, // Use the same language as the user's instruction.\n \"error\"?: string // Use the same language as the user's instruction.\n}}\n\n## Examples\n\n### Example 1: Decompose a task\n\nWhen a user says 'Click the language switch button, wait 1s, click \"English\"', the user will give you the description like this:\n\n====================\n{pageDescription}\n====================\n\nBy viewing the page screenshot and description, you should consider this and output the JSON:\n\n* The main steps should be: tap the switch button, sleep, and tap the 'English' option \n* The language switch button is shown in the screenshot, but it's not marked with a rectangle. So we have to use the page description to find the element. By carefully checking the context information (coordinates, attributes, content, etc.), you can find the element.\n* The \"English\" option button is not shown in the screenshot now, it means it may only show after the previous actions are finished. So the last action will have a \\`null\\` value in the \\`locate\\` field. \n* The task cannot be accomplished (because we cannot see the \"English\" option now), so a \\`furtherPlan\\` field is needed.\n\n{{\n \"actions\":[\n {{\n \"type\": \"Tap\", \n \"thought\": \"Click the language switch button to open the language options.\",\n \"param\": null,\n \"locate\": {sample},\n }},\n {{\n \"type\": \"Sleep\",\n \"thought\": \"Wait for 1 second to ensure the language options are displayed.\",\n \"param\": {{ \"timeMs\": 1000 }},\n }},\n {{\n \"type\": \"Tap\",\n \"thought\": \"Locate the 'English' option in the language menu.\",\n \"param\": null, \n \"locate\": null\n }},\n ],\n \"error\": null,\n \"taskWillBeAccomplished\": false,\n \"furtherPlan\": {{\n \"whatToDoNext\": \"find the 'English' option and click on it\",\n \"whatHaveDone\": \"Click the language switch button and wait 1s\"\n }}\n}}\n\n### Example 2: Tolerate error situations only when the instruction is an \"if\" statement\n\nIf the user says \"If there is a popup, close it\", you should consider this and output the JSON:\n\n* By viewing the page screenshot and description, you cannot find the popup, so the condition is falsy.\n* The instruction itself is an \"if\" statement, it means the user can tolerate this situation, so you should leave a \\`FalsyConditionStatement\\` action.\n\n{{\n \"actions\": [{{\n \"type\": \"FalsyConditionStatement\",\n \"thought\": \"There is no popup on the page\",\n \"param\": null\n }}\n ],\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null\n}}\n\nFor contrast, if the user says \"Close the popup\" in this situation, you should consider this and output the JSON:\n\n{{\n \"actions\": [],\n \"error\": \"The instruction and page context are irrelevant, there is no popup on the page\",\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null\n}}\n\n### Example 3: When task is accomplished, don't plan more actions\n\nWhen the user ask to \"Wait 4s\", you should consider this:\n\n{{\n \"actions\": [\n {{\n \"type\": \"Sleep\",\n \"thought\": \"Wait for 4 seconds\",\n \"param\": {{ \"timeMs\": 4000 }},\n }},\n ],\n \"taskWillBeAccomplished\": true,\n \"furtherPlan\": null // All steps have been included in the actions, so no further plan is needed\n}}\n\n### Example 4: What NOT to do\n\nWrong output:\n\n{{\n \"actions\":[\n {{\n \"type\": \"Tap\",\n \"thought\": \"Click the language switch button to open the language options.\",\n \"param\": null,\n \"locate\": {{\n {{\"id\": \"c81c4e9a33\"}}, // WRONG:prompt is missing\n }}\n }},\n {{\n \"type\": \"Tap\", \n \"thought\": \"Click the English option\",\n \"param\": null,\n \"locate\": null, // This means the 'English' option is not shown in the screenshot, the task cannot be accomplished\n }}\n ],\n \"taskWillBeAccomplished\": false,\n // WRONG: should not be null\n \"furtherPlan\": null,\n}}\n\nReason:\n* The \\`prompt\\` is missing in the first 'Locate' action\n* Since the option button is not shown in the screenshot, the task cannot be accomplished, so a \\`furtherPlan\\` field is needed.\n`;\n\nexport async function systemPromptToTaskPlanning() {\n const promptTemplate = new PromptTemplate({\n template: `${systemTemplate}\\n\\n${outputTemplate}`,\n inputVariables: ['pageDescription', 'sample', 'locateParam'],\n });\n\n return await promptTemplate.format({\n pageDescription: samplePageDescription,\n sample: quickAnswerFormat().sample,\n locateParam: quickAnswerFormat().locateParam,\n });\n}\n\nexport const planSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'action_items',\n strict: true,\n schema: {\n type: 'object',\n strict: true,\n properties: {\n actions: {\n type: 'array',\n items: {\n type: 'object',\n strict: true,\n properties: {\n thought: {\n type: 'string',\n description:\n 'Reasons for generating this task, and why this task is feasible on this page',\n },\n type: {\n type: 'string',\n description: 'Type of action, like \"Tap\", \"Hover\", etc.',\n },\n param: {\n anyOf: [\n { type: 'null' },\n {\n type: 'object',\n properties: { value: { type: ['string', 'number'] } },\n required: ['value'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: { timeMs: { type: ['number', 'string'] } },\n required: ['timeMs'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n direction: { type: 'string' },\n scrollType: { type: 'string' },\n distance: { type: ['number', 'string', 'null'] },\n },\n required: ['direction', 'scrollType', 'distance'],\n additionalProperties: false,\n },\n ],\n description:\n 'Parameter of the action, can be null ONLY when the type field is Tap or Hover',\n },\n locate: {\n type: ['object', 'null'],\n properties: {\n ...(getAIConfig(MATCH_BY_POSITION)\n ? {\n position: {\n type: 'object',\n properties: {\n x: { type: 'number' },\n y: { type: 'number' },\n },\n required: ['x', 'y'],\n additionalProperties: false,\n },\n }\n : {\n id: { type: 'string' },\n }),\n prompt: { type: 'string' },\n },\n required: [\n getAIConfig(MATCH_BY_POSITION) ? 'position' : 'id',\n 'prompt',\n ],\n additionalProperties: false,\n description: 'Location information for the target element',\n },\n },\n required: ['thought', 'type', 'param', 'locate'],\n additionalProperties: false,\n },\n description: 'List of actions to be performed',\n },\n taskWillBeAccomplished: {\n type: 'boolean',\n description:\n 'Whether the task will be accomplished after the actions',\n },\n furtherPlan: {\n type: ['object', 'null'],\n properties: {\n whatHaveDone: { type: 'string' },\n whatToDoNext: { type: 'string' },\n },\n required: ['whatHaveDone', 'whatToDoNext'],\n additionalProperties: false,\n description: 'Plan the task when the task cannot be accomplished',\n },\n error: {\n type: ['string', 'null'],\n description: 'Overall error messages',\n },\n },\n required: ['actions', 'taskWillBeAccomplished', 'furtherPlan', 'error'],\n additionalProperties: false,\n },\n },\n};\n\nexport const generateTaskBackgroundContext = (\n userPrompt: string,\n originalPrompt?: string,\n whatHaveDone?: string,\n) => {\n if (originalPrompt && whatHaveDone) {\n return `\n Here is the instruction:\n =====================================\n ${userPrompt}\n =====================================\n \n For your information, this is a task that some important person handed to you. Here is the original task description and what have been done after the previous actions:\n =====================================\n Original task description: ${originalPrompt}\n =====================================\n What have been done: ${whatHaveDone}\n =====================================\n `;\n }\n\n return `\n Here is the instruction:\n =====================================\n ${userPrompt}\n =====================================\n `;\n};\n\nexport const automationUserPrompt = new PromptTemplate({\n template: `\n pageDescription:\n =====================================\n {pageDescription}\n =====================================\n\n {taskBackgroundContext}\n `,\n inputVariables: ['pageDescription', 'taskBackgroundContext'],\n});\n","import assert from 'node:assert';\nimport { MATCH_BY_POSITION, getAIConfig } from '@/env';\nimport { imageInfoOfBase64 } from '@/image';\nimport type { BaseElement, ElementTreeNode, Size, UIContext } from '@/types';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { NodeType } from '@midscene/shared/constants';\nimport { descriptionOfTree, treeToList } from '@midscene/shared/extractor';\nimport { generateHashId } from '@midscene/shared/utils';\nimport type { ResponseFormatJSONSchema } from 'openai/resources';\n\nconst characteristic =\n 'You are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.';\n\nconst contextFormatIntro = `\nThe user will give you a screenshot and some of the texts on it. There may be some none-English characters (like Chinese) on it, indicating it's an non-English app. If some text is shown on screenshot but not introduced by the JSON description, use the information you see on screenshot.`;\n\nexport function systemPromptToLocateElement(\n queryPrompt: string,\n multi: boolean,\n) {\n assert(queryPrompt, 'queryPrompt is required');\n return `\n${characteristic}\n${contextFormatIntro}\n\nBased on the information you get, find ${\n multi ? 'one or more text elements' : 'ONE text element'\n } on the page.\nHere is the description: ${queryPrompt}\n \nReturn in the following JSON format:\n{\n \"elements\": [ // Leave it an empty array when no element is found\n { \n \"id\": \"id of the element, like 123\", \n },\n // more ...\n ], \n errors?: [], // string[], error message if any\n}\n`;\n}\n\nexport function systemPromptToExtract() {\n return `\nYou are a versatile professional in software UI design and testing. Your outstanding contributions will impact the user experience of billions of users.\nThe user will give you a screenshot and the contents of it. There may be some none-English characters (like Chinese) on it, indicating it's an non-English app.\n\nYou have the following skills:\n\nskill name: extract_data_from_UI\nrelated input: DATA_DEMAND\nskill content: \n* User will give you some data requirements in DATA_DEMAND. Consider the UI context, follow the user's instructions, and provide comprehensive data accordingly.\n* There may be some special commands in DATA_DEMAND, please pay extra attention\n - LOCATE_ONE_ELEMENT and LOCATE_ONE_OR_MORE_ELEMENTS: if you see a description that mentions the keyword LOCATE_ONE_ELEMENT\n - LOCATE_ONE_OR_MORE_ELEMENTS(e.g. follow LOCATE_ONE_ELEMENT : i want to find ...), it means user wants to locate a specific element meets the description. \n\nReturn in this way: prefix + the id / comma-separated ids, for example: LOCATE_ONE_ELEMENT/1 , LOCATE_ONE_OR_MORE_ELEMENTS/1,2,3 . If not found, keep the prefix and leave the suffix empty, like LOCATE_ONE_ELEMENT/ .\n\nReturn in the following JSON format:\n{\n language: \"en\", // \"en\" or \"zh\", the language of the page. Use the same language to describe section name, description, and similar fields.\n data: any, // the extracted data from extract_data_from_UI skill. Make sure both the value and scheme meet the DATA_DEMAND.\n errors: [], // string[], error message if any\n}\n`;\n}\n\nexport const extractDataPrompt = new PromptTemplate({\n template: `\npageDescription: {pageDescription}\n\nUse your extract_data_from_UI skill to find the following data, placing it in the \\`data\\` field\nDATA_DEMAND start:\n=====================================\n{dataKeys}\n\n{dataQuery}\n=====================================\nDATA_DEMAND ends.\n `,\n inputVariables: ['pageDescription', 'dataKeys', 'dataQuery'],\n});\n\nexport const extractDataSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'extract_data',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n language: {\n type: 'string',\n enum: ['en', 'zh'],\n description: 'The language of the page',\n },\n data: {\n type: 'object',\n description: 'The extracted data from extract_data_from_UI skill',\n },\n errors: {\n type: 'array',\n items: {\n type: 'string',\n },\n description: 'Error messages, if any',\n },\n },\n required: ['language', 'data', 'errors'],\n additionalProperties: false,\n },\n },\n};\n\nexport function systemPromptToAssert() {\n return `\n${characteristic}\nUser will give an assertion, and some information about the page. Based on the information you get, tell whether the assertion is truthy.\n\nReturn in the following JSON format:\n{\n thought: string, // string, the thought of the assertion. Should in the same language as the assertion.\n pass: true, // true or false, whether the assertion is truthy\n}\n`;\n}\n\nexport const assertSchema: ResponseFormatJSONSchema = {\n type: 'json_schema',\n json_schema: {\n name: 'assert',\n strict: true,\n schema: {\n type: 'object',\n properties: {\n thought: {\n type: 'string',\n description: 'The thought process behind the assertion',\n },\n pass: {\n type: 'boolean',\n description: 'Whether the assertion passed or failed',\n },\n },\n required: ['thought', 'pass'],\n additionalProperties: false,\n },\n },\n};\n\nexport function describeSize(size: Size) {\n return `${size.width} x ${size.height}`;\n}\n\nexport function describeTextFormat() {\n // use `right` and `bottom` to help AI reduce the feasibility of performing computations\n return `\nThe following texts elements are formatted in the following way: \nid(string), left, top, right, bottom, content(may be truncated)`;\n}\n\nexport function describeElement(\n elements: (Pick<BaseElement, 'rect' | 'content'> & { id: string })[],\n) {\n const sliceLength = 80;\n return elements\n .map((item) =>\n [\n item.id,\n item.rect.left,\n item.rect.top,\n item.rect.left + item.rect.width,\n item.rect.top + item.rect.height,\n item.content.length > sliceLength\n ? `${item.content.slice(0, sliceLength)}...`\n : item.content,\n ].join(', '),\n )\n .join('\\n');\n}\n\nexport function elementByPositionWithElementInfo(\n treeRoot: ElementTreeNode<BaseElement>,\n position: {\n x: number;\n y: number;\n },\n) {\n assert(typeof position !== 'undefined', 'position is required for query');\n\n const matchingElements: BaseElement[] = [];\n\n function dfs(node: ElementTreeNode<BaseElement>) {\n if (node?.node) {\n const item = node.node;\n if (\n item.attributes.nodeType !== NodeType.CONTAINER &&\n item.rect.left <= position.x &&\n position.x <= item.rect.left + item.rect.width &&\n item.rect.top <= position.y &&\n position.y <= item.rect.top + item.rect.height\n ) {\n matchingElements.push(item);\n }\n }\n\n for (const child of node.children) {\n dfs(child);\n }\n }\n\n dfs(treeRoot);\n\n if (matchingElements.length === 0) {\n return undefined;\n }\n\n // Find the smallest element by area\n return matchingElements.reduce((smallest, current) => {\n const smallestArea = smallest.rect.width * smallest.rect.height;\n const currentArea = current.rect.width * current.rect.height;\n return currentArea < smallestArea ? current : smallest;\n });\n}\n\nexport const samplePageDescription = `\nThe size of the page: 1280 x 720\nSome of the elements are marked with a rectangle in the screenshot corresponding to the markerId, some are not.\n\nDescription of all the elements in screenshot:\n<div id=\"969f1637\" markerId=\"1\" left=\"100\" top=\"100\" width=\"100\" height=\"100\"> // The markerId indicated by the rectangle label in the screenshot\n <h4 id=\"b211ecb2\" markerId=\"5\" left=\"150\" top=\"150\" width=\"90\" height=\"60\">\n The username is accepted\n </h4>\n ...many more\n</div>\n`;\n\nexport async function describeUserPage<\n ElementType extends BaseElement = BaseElement,\n>(\n context: Omit<UIContext<ElementType>, 'describer'>,\n opt?: {\n truncateTextLength?: number;\n filterNonTextContent?: boolean;\n },\n) {\n const { screenshotBase64 } = context;\n let width: number;\n let height: number;\n\n if (context.size) {\n ({ width, height } = context.size);\n } else {\n const imgSize = await imageInfoOfBase64(screenshotBase64);\n ({ width, height } = imgSize);\n }\n\n const treeRoot = context.tree;\n // dfs tree, save the id and element info\n const idElementMap: Record<string, ElementType> = {};\n const flatElements: ElementType[] = treeToList(treeRoot);\n flatElements.forEach((element) => {\n idElementMap[element.id] = element;\n if (typeof element.indexId !== 'undefined') {\n idElementMap[`${element.indexId}`] = element;\n }\n });\n\n const contentTree = await descriptionOfTree(\n treeRoot,\n opt?.truncateTextLength,\n opt?.filterNonTextContent,\n );\n\n // if match by position, don't need to provide the page description\n const pageJSONDescription = getAIConfig(MATCH_BY_POSITION)\n ? ''\n : `Some of the elements are marked with a rectangle in the screenshot, some are not. \\n The page elements tree:\\n${contentTree}`;\n const sizeDescription = describeSize({ width, height });\n\n return {\n description: `The size of the page: ${sizeDescription} \\n ${pageJSONDescription}`,\n elementById(id: string) {\n assert(typeof id !== 'undefined', 'id is required for query');\n const item = idElementMap[`${id}`];\n return item;\n },\n elementByPosition(\n position: { x: number; y: number },\n size: { width: number; height: number },\n ) {\n // console.log('elementByPosition', { position, size });\n return elementByPositionWithElementInfo(treeRoot, position);\n },\n insertElementByPosition(position: { x: number; y: number }) {\n const rect = {\n left: Math.max(position.x - 4, 0),\n top: Math.max(position.y - 4, 0),\n width: 8,\n height: 8,\n };\n const id = generateHashId(rect);\n const element = {\n id,\n attributes: { nodeType: NodeType.POSITION },\n rect,\n content: '',\n center: [position.x, position.y],\n } as ElementType;\n\n treeRoot.children.push({\n node: element,\n children: [],\n });\n flatElements.push(element);\n idElementMap[id] = element;\n return element;\n },\n size: { width, height },\n };\n}\n","export {\n imageInfo,\n imageInfoOfBase64,\n base64Encoded,\n calculateNewDimensions,\n resizeImg,\n transformImgPathToBase64,\n saveBase64Image,\n} from '@midscene/shared/img';\n","import assert from 'node:assert';\nimport type {\n AIAssertionResponse,\n AIElementResponse,\n AISectionParseResponse,\n AISingleElementResponse,\n AISingleElementResponseByPosition,\n AIUsageInfo,\n BaseElement,\n ElementById,\n ElementTreeNode,\n Size,\n UIContext,\n} from '@/types';\nimport type {\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n} from 'openai/resources';\nimport { AIActionType, callAiFn } from './common';\nimport {\n findElementPrompt,\n systemPromptToLocateElement,\n} from './prompt/llm-locator';\nimport {\n describeUserPage,\n elementByPositionWithElementInfo,\n extractDataPrompt,\n systemPromptToAssert,\n systemPromptToExtract,\n} from './prompt/util';\nimport { callToGetJSONObject } from './service-caller';\n\nexport type AIArgs = [\n ChatCompletionSystemMessageParam,\n ChatCompletionUserMessageParam,\n];\n\nconst liteContextConfig = {\n filterNonTextContent: true,\n truncateTextLength: 200,\n};\n\nfunction transformToAbsoluteCoords(\n relativePosition: { x: number; y: number },\n size: Size,\n) {\n return {\n x: Number(((relativePosition.x / 1000) * size.width).toFixed(3)),\n y: Number(((relativePosition.y / 1000) * size.height).toFixed(3)),\n };\n}\n\n// let index = 0;\nexport async function transformElementPositionToId(\n aiResult: AIElementResponse | [number, number],\n treeRoot: ElementTreeNode<BaseElement>,\n size: { width: number; height: number },\n) {\n if (Array.isArray(aiResult)) {\n const relativePosition = aiResult;\n const absolutePosition = transformToAbsoluteCoords(\n {\n x: relativePosition[0],\n y: relativePosition[1],\n },\n size,\n );\n\n const element = elementByPositionWithElementInfo(\n treeRoot,\n absolutePosition,\n );\n assert(\n element,\n `inspect: no id found with position: ${JSON.stringify({ absolutePosition })}`,\n );\n\n return {\n errors: [],\n elements: [\n {\n id: element.id,\n },\n ],\n };\n }\n\n return {\n errors: aiResult.errors,\n elements: aiResult.elements,\n };\n}\n\nfunction getQuickAnswer(\n quickAnswer:\n | Partial<AISingleElementResponse>\n | Partial<AISingleElementResponseByPosition>\n | undefined,\n tree: ElementTreeNode<BaseElement>,\n elementById: ElementById,\n insertElementByPosition: (position: { x: number; y: number }) => BaseElement,\n) {\n if (!quickAnswer) {\n return undefined;\n }\n if ('id' in quickAnswer && quickAnswer.id && elementById(quickAnswer.id)) {\n return {\n parseResult: {\n elements: [quickAnswer],\n errors: [],\n },\n rawResponse: quickAnswer,\n elementById,\n };\n }\n\n if ('position' in quickAnswer && quickAnswer.position) {\n let element = elementByPositionWithElementInfo(tree, quickAnswer.position);\n if (!element) {\n element = insertElementByPosition(quickAnswer.position);\n }\n return {\n parseResult: {\n elements: [element],\n errors: [],\n },\n rawResponse: quickAnswer,\n elementById,\n } as any;\n }\n}\n\nexport async function AiInspectElement<\n ElementType extends BaseElement = BaseElement,\n>(options: {\n context: UIContext<ElementType>;\n multi: boolean;\n targetElementDescription: string;\n callAI?: typeof callAiFn<AIElementResponse | [number, number]>;\n quickAnswer?: Partial<\n AISingleElementResponse | AISingleElementResponseByPosition\n >;\n}): Promise<{\n parseResult: AIElementResponse;\n rawResponse: any;\n elementById: ElementById;\n usage?: AIUsageInfo;\n}> {\n const { context, multi, targetElementDescription, callAI } = options;\n const { screenshotBase64, screenshotBase64WithElementMarker } = context;\n const { description, elementById, insertElementByPosition, size } =\n await describeUserPage(context);\n // meet quick answer\n const quickAnswer = getQuickAnswer(\n options.quickAnswer,\n context.tree,\n elementById,\n insertElementByPosition,\n );\n if (quickAnswer) {\n return quickAnswer;\n }\n\n assert(\n targetElementDescription,\n 'cannot find the target element description',\n );\n\n const userInstructionPrompt = await findElementPrompt.format({\n pageDescription: description,\n targetElementDescription,\n multi,\n });\n const systemPrompt = systemPromptToLocateElement();\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64WithElementMarker || screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: userInstructionPrompt,\n },\n ],\n },\n ];\n\n const callAIFn =\n callAI || callToGetJSONObject<AIElementResponse | [number, number]>;\n\n const res = await callAIFn(msgs, AIActionType.INSPECT_ELEMENT);\n return {\n parseResult: await transformElementPositionToId(\n res.content,\n context.tree,\n size,\n ),\n rawResponse: res.content,\n elementById,\n usage: res.usage,\n };\n}\n\nexport async function AiExtractElementInfo<\n T,\n ElementType extends BaseElement = BaseElement,\n>(options: {\n dataQuery: string | Record<string, string>;\n context: UIContext<ElementType>;\n}) {\n const { dataQuery, context } = options;\n const systemPrompt = systemPromptToExtract();\n\n const { screenshotBase64 } = context;\n const { description, elementById } = await describeUserPage(\n context,\n liteContextConfig,\n );\n\n let dataKeys = '';\n let dataQueryText = '';\n if (typeof dataQuery === 'string') {\n dataKeys = '';\n dataQueryText = dataQuery;\n } else {\n dataKeys = `return in key-value style object, keys are ${Object.keys(dataQuery).join(',')}`;\n dataQueryText = JSON.stringify(dataQuery, null, 2);\n }\n const extractDataPromptText = await extractDataPrompt.format({\n pageDescription: description,\n dataKeys,\n dataQuery: dataQueryText,\n });\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: extractDataPromptText,\n },\n ],\n },\n ];\n\n const result = await callAiFn<AISectionParseResponse<T>>(\n msgs,\n AIActionType.EXTRACT_DATA,\n );\n return {\n parseResult: result.content,\n elementById,\n usage: result.usage,\n };\n}\n\nexport async function AiAssert<\n ElementType extends BaseElement = BaseElement,\n>(options: { assertion: string; context: UIContext<ElementType> }) {\n const { assertion, context } = options;\n\n assert(assertion, 'assertion should be a string');\n\n const { screenshotBase64 } = context;\n const systemPrompt = systemPromptToAssert();\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: `\nHere is the description of the assertion. Just go ahead:\n=====================================\n${assertion}\n=====================================\n `,\n },\n ],\n },\n ];\n\n const { content: assertResult, usage } = await callAiFn<AIAssertionResponse>(\n msgs,\n AIActionType.ASSERT,\n );\n return {\n content: assertResult,\n usage,\n };\n}\n","import assert from 'node:assert';\nimport type { AIUsageInfo, PlanningAIResponse, UIContext } from '@/types';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { AIActionType, type AIArgs, callAiFn } from './common';\nimport {\n automationUserPrompt,\n generateTaskBackgroundContext,\n systemPromptToTaskPlanning,\n} from './prompt/llm-planning';\nimport { describeUserPage } from './prompt/util';\n\nexport async function plan(\n userPrompt: string,\n opts: {\n whatHaveDone?: string;\n originalPrompt?: string;\n context: UIContext;\n callAI?: typeof callAiFn<PlanningAIResponse>;\n },\n): Promise<PlanningAIResponse> {\n const { callAI, context } = opts || {};\n const { screenshotBase64, screenshotBase64WithElementMarker } = context;\n const { description: pageDescription } = await describeUserPage(context);\n\n const systemPrompt = await systemPromptToTaskPlanning();\n const taskBackgroundContextText = generateTaskBackgroundContext(\n userPrompt,\n opts.originalPrompt,\n opts.whatHaveDone,\n );\n const userInstructionPrompt = await automationUserPrompt.format({\n pageDescription,\n taskBackgroundContext: taskBackgroundContextText,\n });\n\n const msgs: AIArgs = [\n { role: 'system', content: systemPrompt },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64WithElementMarker || screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: userInstructionPrompt,\n },\n ],\n },\n ];\n\n const call = callAI || callAiFn;\n const { content, usage } = await call(msgs, AIActionType.PLAN);\n const planFromAI = content;\n\n const actions = planFromAI?.actions || [];\n assert(planFromAI, \"can't get plans from AI\");\n assert(\n actions.length > 0,\n `Failed to plan actions: ${planFromAI.error || '(no error details)'}`,\n );\n\n return planFromAI;\n}\n","import assert from 'node:assert';\nimport type { PlanningAction } from '@/types';\nimport { transformHotkeyInput } from '@midscene/shared/keyboard-layout';\nimport { actionParser } from '@ui-tars/action-parser';\nimport type { ChatCompletionMessageParam } from 'openai/resources';\nimport { AIActionType } from './common';\nimport { getSummary, uiTarsPlanningPrompt } from './prompt/ui-tars-planning';\nimport { call } from './service-caller';\ntype ActionType =\n | 'click'\n | 'drag'\n | 'type'\n | 'hotkey'\n | 'finished'\n | 'scroll'\n | 'wait';\n\nfunction capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nexport async function vlmPlanning(options: {\n userInstruction: string;\n conversationHistory: ChatCompletionMessageParam[];\n size: { width: number; height: number };\n}): Promise<{\n actions: PlanningAction<any>[];\n realActions: ReturnType<typeof actionParser>['parsed'];\n action_summary: string;\n}> {\n const { conversationHistory, userInstruction, size } = options;\n const systemPrompt = uiTarsPlanningPrompt + userInstruction;\n\n const res = await call(\n [\n {\n role: 'user',\n content: systemPrompt,\n },\n ...conversationHistory,\n ],\n AIActionType.INSPECT_ELEMENT,\n );\n const { parsed } = actionParser({\n prediction: res.content,\n factor: 1000,\n });\n const transformActions: PlanningAction[] = [];\n parsed.forEach((action) => {\n if (action.action_type === 'click') {\n assert(action.action_inputs.start_box, 'start_box is required');\n const point = getPoint(action.action_inputs.start_box, size);\n transformActions.push({\n type: 'Locate',\n locate: {\n prompt: action.thought || '',\n position: { x: point[0], y: point[1] },\n },\n param: {\n // action,\n // position: { x: point[0], y: point[1] },\n },\n });\n transformActions.push({\n type: 'Tap',\n locate: {\n prompt: action.thought || '',\n position: { x: point[0], y: point[1] },\n },\n param: action.thought || '',\n });\n } else if (action.action_type === 'drag') {\n assert(action.action_inputs.start_box, 'start_box is required');\n assert(action.action_inputs.end_box, 'end_box is required');\n const startPoint = getPoint(action.action_inputs.start_box, size);\n const endPoint = getPoint(action.action_inputs.end_box, size);\n transformActions.push({\n type: 'Drag',\n param: {\n start_box: { x: startPoint[0], y: startPoint[1] },\n end_box: { x: endPoint[0], y: endPoint[1] },\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'type') {\n transformActions.push({\n type: 'Input',\n param: {\n value: action.action_inputs.content,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'scroll') {\n transformActions.push({\n type: 'Scroll',\n param: {\n direction: action.action_inputs.direction,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'finished') {\n transformActions.push({\n type: 'Finished',\n param: {},\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'hotkey') {\n assert(action.action_inputs.key, 'key is required');\n const keys = transformHotkeyInput(action.action_inputs.key);\n\n transformActions.push({\n type: 'KeyboardPress',\n param: {\n value: keys,\n },\n locate: null,\n thought: action.thought || '',\n });\n } else if (action.action_type === 'wait') {\n transformActions.push({\n type: 'Sleep',\n param: {\n timeMs: 1000,\n },\n locate: null,\n thought: action.thought || '',\n });\n }\n });\n\n if (transformActions.length === 0) {\n throw new Error(`No actions found with reason: ${res.content}`, {\n cause: {\n prediction: res.content,\n parsed,\n },\n });\n }\n\n return {\n actions: transformActions,\n realActions: parsed,\n action_summary: getSummary(res.content),\n };\n}\n\nfunction getPoint(startBox: string, size: { width: number; height: number }) {\n const [x, y] = JSON.parse(startBox);\n return [x * size.width, y * size.height];\n}\n\ninterface BaseAction {\n action_type: ActionType;\n action_inputs: Record<string, any>;\n reflection: string | null;\n thought: string | null;\n}\n\ninterface ClickAction extends BaseAction {\n action_type: 'click';\n action_inputs: {\n start_box: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface DragAction extends BaseAction {\n action_type: 'drag';\n action_inputs: {\n start_box: string; // JSON string of [x, y] coordinates\n end_box: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface WaitAction extends BaseAction {\n action_type: 'wait';\n action_inputs: {\n time: string; // JSON string of [x, y] coordinates\n };\n}\n\ninterface TypeAction extends BaseAction {\n action_type: 'type';\n action_inputs: {\n content: string;\n };\n}\n\ninterface HotkeyAction extends BaseAction {\n action_type: 'hotkey';\n action_inputs: {\n key: string;\n };\n}\n\ninterface ScrollAction extends BaseAction {\n action_type: 'scroll';\n action_inputs: {\n direction: 'up' | 'down';\n };\n}\n\ninterface FinishedAction extends BaseAction {\n action_type: 'finished';\n action_inputs: Record<string, never>;\n}\n\nexport type Action =\n | ClickAction\n | DragAction\n | TypeAction\n | HotkeyAction\n | ScrollAction\n | FinishedAction\n | WaitAction;\n"]}
|