@midscene/core 0.24.2-beta-20250731102409.0 → 0.24.2-beta-20250731125910.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/es/ai-model.d.ts +3 -3
  2. package/dist/es/ai-model.js +1 -1
  3. package/dist/es/{chunk-YCHAOUOW.js → chunk-FKQMUAXP.js} +46 -15
  4. package/dist/es/chunk-FKQMUAXP.js.map +1 -0
  5. package/dist/es/{chunk-TYKJHDNK.js → chunk-XIVVQRBC.js} +7 -12
  6. package/dist/es/chunk-XIVVQRBC.js.map +1 -0
  7. package/dist/es/index.d.ts +4 -4
  8. package/dist/es/index.js +3 -4
  9. package/dist/es/index.js.map +1 -1
  10. package/dist/es/{llm-planning-4bc82162.d.ts → llm-planning-ae19dc49.d.ts} +1 -1
  11. package/dist/es/{types-93fa8419.d.ts → types-d187efec.d.ts} +17 -4
  12. package/dist/es/utils.d.ts +1 -1
  13. package/dist/es/utils.js +1 -1
  14. package/dist/lib/ai-model.d.ts +3 -3
  15. package/dist/lib/ai-model.js +2 -2
  16. package/dist/lib/{chunk-YCHAOUOW.js → chunk-FKQMUAXP.js} +55 -24
  17. package/dist/lib/chunk-FKQMUAXP.js.map +1 -0
  18. package/dist/lib/{chunk-TYKJHDNK.js → chunk-XIVVQRBC.js} +6 -11
  19. package/dist/lib/chunk-XIVVQRBC.js.map +1 -0
  20. package/dist/lib/index.d.ts +4 -4
  21. package/dist/lib/index.js +13 -14
  22. package/dist/lib/index.js.map +1 -1
  23. package/dist/lib/{llm-planning-4bc82162.d.ts → llm-planning-ae19dc49.d.ts} +1 -1
  24. package/dist/{types/types-93fa8419.d.ts → lib/types-d187efec.d.ts} +17 -4
  25. package/dist/lib/utils.d.ts +1 -1
  26. package/dist/lib/utils.js +2 -2
  27. package/dist/types/ai-model.d.ts +3 -3
  28. package/dist/types/index.d.ts +4 -4
  29. package/dist/types/{llm-planning-4bc82162.d.ts → llm-planning-ae19dc49.d.ts} +1 -1
  30. package/dist/{lib/types-93fa8419.d.ts → types/types-d187efec.d.ts} +17 -4
  31. package/dist/types/utils.d.ts +1 -1
  32. package/package.json +3 -3
  33. package/dist/es/chunk-TYKJHDNK.js.map +0 -1
  34. package/dist/es/chunk-YCHAOUOW.js.map +0 -1
  35. package/dist/lib/chunk-TYKJHDNK.js.map +0 -1
  36. package/dist/lib/chunk-YCHAOUOW.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"mappings":";AAAA,SAAS,gBAAgB;AACzB,YAAY,QAAQ;AACpB,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,cAAc;AACvB,YAAY,UAAU;AACtB,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,QAAQ,cAAc;AAC/B,SAAS,iBAAiB,aAAa,YAAY;AAGnD,IAAI,cAAc;AAEX,IAAM,2BAA2B;AAExC,IAAM,uBAAuB,oBAAI,IAAqB;AAItD,SAAS,eAAe;AACtB,MAAI,IAAqB;AACvB,WAAU,gBAAa,IAAqB,OAAO;AAAA,EACrD;AACA,QAAM,YAAY;AAElB,SAAO;AACT;AAMO,SAAS,8BACd,UACA,eACM;AACN,QAAM,aAAa;AACnB,QAAM,OAAU,YAAS,QAAQ;AAEjC,QAAM,WAAW,KAAK,IAAI,KAAK,MAAM,IAAI;AACzC,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,OAAO,QAAQ;AAC9C,QAAM,SAAS,OAAO,MAAM,KAAK,OAAO,KAAK;AAC7C,QAAM,KAAQ,YAAS,UAAU,GAAG;AACpC,EAAG,YAAS,IAAI,QAAQ,GAAG,OAAO,QAAQ,KAAK;AAC/C,EAAG,aAAU,EAAE;AAEf,QAAM,UAAU,OAAO,SAAS,MAAM;AACtC,QAAM,aAAa,QAA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AAClD,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,SAAS,kBAAkB,MAAW,SAAkB;AAC7D,SAAO,KAAK,UAAU,MAAM,uBAAuB,OAAO;AAC5D;AAIO,SAAS,aAAa;AAC3B,SAAO;AACT;AAEA,SAAS,YAAY,SAAgB;AACnC,QAAM,YAAY,YAAY,mBAAmB;AACjD,MAAI,WAAW;AACb,YAAQ,IAAI,cAAc,GAAG,OAAO;AAAA,EACtC;AACF;AAEA,IAAI,sBAAsB;AACnB,SAAS,uBAAuB,EAAE,QAAQ,GAAwB;AACvE,MAAI,UAAU;AACd,MAAI,YAAY;AAEhB,QAAM,cAAc,kBAAkB,gCAAgC;AACtE,QAAM,YAAY,aAAa;AAE/B,MAAI;AACF,cAAU,SAAS,oCAAoC,EAAE,SAAS,EAAE,KAAK;AACzE,gBAAY,SAAS,6BAA6B,EAAE,SAAS,EAAE,KAAK;AAAA,EACtE,SAAS,OAAO;AACd,aAAS,2BAA2B,KAAK;AAAA,EAC3C;AAOA,MACE,cACE,WAAW,YAAY,uBAAyB,CAAC,WAAW,UAC9D;AACA,aAAS,iCAAiC;AAAA,MACxC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAED,UAAM,WAAW;AAAA,MACf,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB,UAAU;AAAA,QACV,UAAU;AAAA,QACV,YAAY;AAAA,MACd,CAAC;AAAA,IACH,CAAC,EACE,KAAK,CAAC,aAAa,SAAS,KAAK,CAAC,EAClC,KAAK,CAAC,SAAS;AACd,eAAS,8CAA8C,IAAI;AAAA,IAC7D,CAAC,EACA;AAAA,MAAM,CAAC,UACN,SAAS,yCAAyC,KAAK;AAAA,IACzD;AACF,0BAAsB;AAAA,EACxB;AACF","names":["readFileSync"],"ignoreList":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport * as path from 'node:path';\nimport { dirname } from 'node:path';\nimport {\n defaultRunDirName,\n getMidsceneRunSubDir,\n} from '@midscene/shared/common';\nimport {\n MIDSCENE_DEBUG_MODE,\n MIDSCENE_OPENAI_INIT_CONFIG_JSON,\n getAIConfig,\n getAIConfigInJson,\n} from '@midscene/shared/env';\nimport { getRunningPkgInfo } from '@midscene/shared/fs';\nimport { assert, logMsg } from '@midscene/shared/utils';\nimport { escapeScriptTag, ifInBrowser, uuid } from '@midscene/shared/utils';\nimport type { Rect, ReportDumpWithAttributes } from './types';\n\nlet logEnvReady = false;\n\nexport const groupedActionDumpFileExt = 'web-dump.json';\n\nconst reportInitializedMap = new Map<string, boolean>();\n\ndeclare const __DEV_REPORT_PATH__: string;\n\nfunction getReportTpl() {\n if (__DEV_REPORT_PATH__) {\n return fs.readFileSync(__DEV_REPORT_PATH__, 'utf-8');\n }\n const reportTpl = 'REPLACE_ME_WITH_REPORT_HTML';\n\n return reportTpl;\n}\n\n/**\n * high performance, insert script before </html> in HTML file\n * only truncate and append, no temporary file\n */\nexport function insertScriptBeforeClosingHtml(\n filePath: string,\n scriptContent: string,\n): void {\n const htmlEndTag = '</html>';\n const stat = fs.statSync(filePath);\n\n const readSize = Math.min(stat.size, 4096);\n const start = Math.max(0, stat.size - readSize);\n const buffer = Buffer.alloc(stat.size - start);\n const fd = fs.openSync(filePath, 'r');\n fs.readSync(fd, buffer, 0, buffer.length, start);\n fs.closeSync(fd);\n\n const tailStr = buffer.toString('utf8');\n const htmlEndIdx = tailStr.lastIndexOf(htmlEndTag);\n if (htmlEndIdx === -1) {\n throw new Error(`No </html> found in file:${filePath}`);\n }\n\n // calculate the correct byte position: char position to byte position\n const beforeHtmlInTail = tailStr.slice(0, htmlEndIdx);\n const htmlEndPos = start + Buffer.byteLength(beforeHtmlInTail, 'utf8');\n\n // truncate to </html> before\n fs.truncateSync(filePath, htmlEndPos);\n // append script and </html>\n fs.appendFileSync(filePath, `${scriptContent}\\n${htmlEndTag}\\n`);\n}\n\nexport function reportHTMLContent(\n dumpData: string | ReportDumpWithAttributes,\n reportPath?: string,\n appendReport?: boolean,\n): string {\n const tpl = getReportTpl();\n\n if (!tpl) {\n console.warn('reportTpl is not set, will not write report');\n return '';\n }\n\n // if reportPath is set, it means we are in write to file mode\n const writeToFile = reportPath && !ifInBrowser;\n let dumpContent = '';\n\n if (typeof dumpData === 'string') {\n // do not use template string here, will cause bundle error\n dumpContent =\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\" type=\"application/json\">\\n' +\n escapeScriptTag(dumpData) +\n '\\n</script>';\n } else {\n const { dumpString, attributes } = dumpData;\n const attributesArr = Object.keys(attributes || {}).map((key) => {\n return `${key}=\"${encodeURIComponent(attributes![key])}\"`;\n });\n\n dumpContent =\n // do not use template string here, will cause bundle error\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\" type=\"application/json\" ' +\n attributesArr.join(' ') +\n '>\\n' +\n escapeScriptTag(dumpString) +\n '\\n</script>';\n }\n\n if (writeToFile) {\n if (!appendReport) {\n writeFileSync(reportPath!, tpl + dumpContent, { flag: 'w' });\n return reportPath!;\n }\n\n if (!reportInitializedMap.get(reportPath!)) {\n writeFileSync(reportPath!, tpl, { flag: 'w' });\n reportInitializedMap.set(reportPath!, true);\n }\n\n insertScriptBeforeClosingHtml(reportPath!, dumpContent);\n return reportPath!;\n }\n\n return tpl + dumpContent;\n}\n\nexport function writeDumpReport(\n fileName: string,\n dumpData: string | ReportDumpWithAttributes,\n appendReport?: boolean,\n): string | null {\n if (ifInBrowser) {\n console.log('will not write report in browser');\n return null;\n }\n\n const __dirname = dirname(__filename);\n const midscenePkgInfo = getRunningPkgInfo(__dirname);\n if (!midscenePkgInfo) {\n console.warn('midscenePkgInfo not found, will not write report');\n return null;\n }\n\n const reportPath = path.join(\n getMidsceneRunSubDir('report'),\n `${fileName}.html`,\n );\n\n reportHTMLContent(dumpData, reportPath, appendReport);\n\n if (process.env.MIDSCENE_DEBUG_LOG_JSON) {\n const jsonPath = `${reportPath}.json`;\n let data;\n\n if (typeof dumpData === 'string') {\n data = JSON.parse(dumpData) as ReportDumpWithAttributes;\n } else {\n data = dumpData;\n }\n\n writeFileSync(jsonPath, JSON.stringify(data, null, 2), {\n flag: appendReport ? 'a' : 'w',\n });\n\n logMsg(`Midscene - dump file written: ${jsonPath}`);\n }\n\n return reportPath;\n}\n\nexport function writeLogFile(opts: {\n fileName: string;\n fileExt: string;\n fileContent: string;\n type: 'dump' | 'cache' | 'report' | 'tmp';\n generateReport?: boolean;\n appendReport?: boolean;\n}) {\n if (ifInBrowser) {\n return '/mock/report.html';\n }\n const { fileName, fileExt, fileContent, type = 'dump' } = opts;\n const targetDir = getMidsceneRunSubDir(type);\n // Ensure directory exists\n if (!logEnvReady) {\n assert(targetDir, 'logDir should be set before writing dump file');\n\n // gitIgnore in the parent directory\n const gitIgnorePath = path.join(targetDir, '../../.gitignore');\n const gitPath = path.join(targetDir, '../../.git');\n let gitIgnoreContent = '';\n\n if (existsSync(gitPath)) {\n // if the git path exists, we need to add the log folder to the git ignore file\n if (existsSync(gitIgnorePath)) {\n gitIgnoreContent = readFileSync(gitIgnorePath, 'utf-8');\n }\n\n // ignore the log folder\n if (!gitIgnoreContent.includes(`${defaultRunDirName}/`)) {\n writeFileSync(\n gitIgnorePath,\n `${gitIgnoreContent}\\n# Midscene.js dump files\\n${defaultRunDirName}/dump\\n${defaultRunDirName}/report\\n${defaultRunDirName}/tmp\\n${defaultRunDirName}/log\\n`,\n 'utf-8',\n );\n }\n }\n\n logEnvReady = true;\n }\n\n const filePath = path.join(targetDir, `${fileName}.${fileExt}`);\n\n if (type !== 'dump') {\n // do not write dump file any more\n writeFileSync(filePath, fileContent);\n }\n\n if (opts?.generateReport) {\n return writeDumpReport(fileName, fileContent, opts.appendReport);\n }\n\n return filePath;\n}\n\nexport function getTmpDir(): string | null {\n try {\n const runningPkgInfo = getRunningPkgInfo();\n if (!runningPkgInfo) {\n return null;\n }\n const { name } = runningPkgInfo;\n const tmpPath = path.join(tmpdir(), name);\n mkdirSync(tmpPath, { recursive: true });\n return tmpPath;\n } catch (e) {\n return null;\n }\n}\n\nexport function getTmpFile(fileExtWithoutDot: string): string | null {\n if (ifInBrowser) {\n return null;\n }\n const tmpDir = getTmpDir();\n const filename = `${uuid()}.${fileExtWithoutDot}`;\n return path.join(tmpDir!, filename);\n}\n\nexport function overlapped(container: Rect, target: Rect) {\n // container and the target have some part overlapped\n return (\n container.left < target.left + target.width &&\n container.left + container.width > target.left &&\n container.top < target.top + target.height &&\n container.top + container.height > target.top\n );\n}\n\nexport async function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function replacerForPageObject(key: string, value: any) {\n if (value && value.constructor?.name === 'Page') {\n return '[Page object]';\n }\n if (value && value.constructor?.name === 'Browser') {\n return '[Browser object]';\n }\n return value;\n}\n\nexport function stringifyDumpData(data: any, indents?: number) {\n return JSON.stringify(data, replacerForPageObject, indents);\n}\n\ndeclare const __VERSION__: string;\n\nexport function getVersion() {\n return __VERSION__;\n}\n\nfunction debugLog(...message: any[]) {\n const debugMode = getAIConfig(MIDSCENE_DEBUG_MODE);\n if (debugMode) {\n console.log('[Midscene]', ...message);\n }\n}\n\nlet lastReportedRepoUrl = '';\nexport function uploadTestInfoToServer({ testUrl }: { testUrl: string }) {\n let repoUrl = '';\n let userEmail = '';\n\n const extraConfig = getAIConfigInJson(MIDSCENE_OPENAI_INIT_CONFIG_JSON);\n const serverUrl = extraConfig?.REPORT_SERVER_URL;\n\n try {\n repoUrl = execSync('git config --get remote.origin.url').toString().trim();\n userEmail = execSync('git config --get user.email').toString().trim();\n } catch (error) {\n debugLog('Failed to get git info:', error);\n }\n\n // Only upload test info if:\n // 1. Server URL is configured AND\n // 2. Either:\n // - We have a repo URL that's different from last reported one (to avoid duplicate reports)\n // - OR we don't have a repo URL but have a test URL (for non-git environments)\n if (\n serverUrl &&\n ((repoUrl && repoUrl !== lastReportedRepoUrl) || (!repoUrl && testUrl))\n ) {\n debugLog('Uploading test info to server', {\n serverUrl,\n repoUrl,\n testUrl,\n userEmail,\n });\n\n fetch(serverUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n repo_url: repoUrl,\n test_url: testUrl,\n user_email: userEmail,\n }),\n })\n .then((response) => response.json())\n .then((data) => {\n debugLog('Successfully uploaded test info to server:', data);\n })\n .catch((error) =>\n debugLog('Failed to upload test info to server:', error),\n );\n lastReportedRepoUrl = repoUrl;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightTaskInfo, e as InsightOptions, f as DetailedLocateParam, L as LocateResult, g as InsightExtractOption, h as InsightAssertionResponse, A as AIDescribeElementResponse } from './types-93fa8419.js';
2
- export { w as AIAssertionResponse, u as AIDataExtractionResponse, s as AIElementCoordinatesResponse, r as AIElementLocatorResponse, t as AIElementResponse, n as AIResponseFormat, v as AISectionLocatorResponse, q as AISingleElementResponse, o as AISingleElementResponseById, p as AISingleElementResponseByPosition, m as AIUsageInfo, S as AgentAssertOpt, z as AgentDescribeElementAtPointResult, Q as AgentWaitForOpt, a5 as BaseAgentParserOpt, C as CallAIFn, az as CodeGenerationChunk, a4 as Color, H as DumpMeta, N as ElementById, B as EnsureObject, a8 as ExecutionRecorderItem, aq as ExecutionTaskAction, ap as ExecutionTaskActionApply, ab as ExecutionTaskHitBy, ao as ExecutionTaskInsightAssertion, an as ExecutionTaskInsightAssertionApply, am as ExecutionTaskInsightAssertionParam, af as ExecutionTaskInsightDumpLog, ah as ExecutionTaskInsightLocate, ag as ExecutionTaskInsightLocateApply, ae as ExecutionTaskInsightLocateOutput, ad as ExecutionTaskInsightLocateParam, al as ExecutionTaskInsightQuery, ak as ExecutionTaskInsightQueryApply, aj as ExecutionTaskInsightQueryOutput, ai as ExecutionTaskInsightQueryParam, as as ExecutionTaskLog, ar as ExecutionTaskLogApply, au as ExecutionTaskPlanning, at as ExecutionTaskPlanningApply, ac as ExecutionTaskReturn, a9 as ExecutionTaskType, aa as ExecutorContext, aZ as FreeFn, av as GroupedActionDump, J as InsightDump, F as InsightExtractParam, K as LiteUISection, aB as LocateOption, G as LocateResultElement, y as LocateValidatorResult, x as LocatorValidatorOption, b0 as MidsceneYamlConfig, b1 as MidsceneYamlConfigOutput, l as MidsceneYamlConfigResult, j as MidsceneYamlFlowItem, aI as MidsceneYamlFlowItemAIAction, aN as MidsceneYamlFlowItemAIAsk, aJ as MidsceneYamlFlowItemAIAssert, aO as MidsceneYamlFlowItemAIBoolean, aS as MidsceneYamlFlowItemAIHover, aT as MidsceneYamlFlowItemAIInput, aU as MidsceneYamlFlowItemAIKeyboardPress, aP as MidsceneYamlFlowItemAILocate, aL as MidsceneYamlFlowItemAINumber, aK as MidsceneYamlFlowItemAIQuery, k as MidsceneYamlFlowItemAIRightClick, aV as MidsceneYamlFlowItemAIScroll, aM as MidsceneYamlFlowItemAIString, aR as MidsceneYamlFlowItemAITap, aQ as MidsceneYamlFlowItemAIWaitFor, aW as MidsceneYamlFlowItemEvaluateJavaScript, aY as MidsceneYamlFlowItemLogScreenshot, aX as MidsceneYamlFlowItemSleep, M as MidsceneYamlScript, aG as MidsceneYamlScriptAndroidEnv, aH as MidsceneYamlScriptEnv, aE as MidsceneYamlScriptEnvBase, aF as MidsceneYamlScriptWebEnv, i as MidsceneYamlTask, O as OnTaskStartTip, aw as PageType, P as PartialInsightDumpFromSDK, W as PlanningAIResponse, V as PlanningAction, a0 as PlanningActionParamAssert, a2 as PlanningActionParamError, Y as PlanningActionParamHover, _ as PlanningActionParamInputOrKeyPress, Z as PlanningActionParamRightClick, $ as PlanningActionParamScroll, a1 as PlanningActionParamSleep, X as PlanningActionParamTap, a3 as PlanningActionParamWaitFor, T as PlanningLocateParam, a7 as PlaywrightParserOpt, a6 as PuppeteerParserOpt, aC as ReferenceImage, R as ReportDumpWithAttributes, a$ as ScriptPlayerStatusValue, a_ as ScriptPlayerTaskStatus, aA as StreamingAIResponse, ay as StreamingCallback, ax as StreamingCodeGenerationOptions, aD as scrollParam } from './types-93fa8419.js';
3
- import { c as callAiFn } from './llm-planning-4bc82162.js';
4
- export { a as AiAssert, A as AiLocateElement, d as describeUserPage, p as plan } from './llm-planning-4bc82162.js';
1
+ import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightTaskInfo, e as InsightOptions, f as DetailedLocateParam, L as LocateResult, g as InsightExtractOption, h as InsightAssertionResponse, A as AIDescribeElementResponse } from './types-d187efec.js';
2
+ export { w as AIAssertionResponse, u as AIDataExtractionResponse, s as AIElementCoordinatesResponse, r as AIElementLocatorResponse, t as AIElementResponse, n as AIResponseFormat, v as AISectionLocatorResponse, q as AISingleElementResponse, o as AISingleElementResponseById, p as AISingleElementResponseByPosition, m as AIUsageInfo, S as AgentAssertOpt, z as AgentDescribeElementAtPointResult, Q as AgentWaitForOpt, a7 as BaseAgentParserOpt, C as CallAIFn, aB as CodeGenerationChunk, a6 as Color, H as DumpMeta, N as ElementById, B as EnsureObject, aa as ExecutionRecorderItem, as as ExecutionTaskAction, ar as ExecutionTaskActionApply, ad as ExecutionTaskHitBy, aq as ExecutionTaskInsightAssertion, ap as ExecutionTaskInsightAssertionApply, ao as ExecutionTaskInsightAssertionParam, ah as ExecutionTaskInsightDumpLog, aj as ExecutionTaskInsightLocate, ai as ExecutionTaskInsightLocateApply, ag as ExecutionTaskInsightLocateOutput, af as ExecutionTaskInsightLocateParam, an as ExecutionTaskInsightQuery, am as ExecutionTaskInsightQueryApply, al as ExecutionTaskInsightQueryOutput, ak as ExecutionTaskInsightQueryParam, au as ExecutionTaskLog, at as ExecutionTaskLogApply, aw as ExecutionTaskPlanning, av as ExecutionTaskPlanningApply, ae as ExecutionTaskReturn, ab as ExecutionTaskType, ac as ExecutorContext, a$ as FreeFn, ax as GroupedActionDump, J as InsightDump, F as InsightExtractParam, K as LiteUISection, aD as LocateOption, G as LocateResultElement, y as LocateValidatorResult, x as LocatorValidatorOption, b2 as MidsceneYamlConfig, b3 as MidsceneYamlConfigOutput, l as MidsceneYamlConfigResult, j as MidsceneYamlFlowItem, aK as MidsceneYamlFlowItemAIAction, aP as MidsceneYamlFlowItemAIAsk, aL as MidsceneYamlFlowItemAIAssert, aQ as MidsceneYamlFlowItemAIBoolean, aU as MidsceneYamlFlowItemAIHover, aV as MidsceneYamlFlowItemAIInput, aW as MidsceneYamlFlowItemAIKeyboardPress, aR as MidsceneYamlFlowItemAILocate, aN as MidsceneYamlFlowItemAINumber, aM as MidsceneYamlFlowItemAIQuery, k as MidsceneYamlFlowItemAIRightClick, aX as MidsceneYamlFlowItemAIScroll, aO as MidsceneYamlFlowItemAIString, aT as MidsceneYamlFlowItemAITap, aS as MidsceneYamlFlowItemAIWaitFor, aY as MidsceneYamlFlowItemEvaluateJavaScript, a_ as MidsceneYamlFlowItemLogScreenshot, aZ as MidsceneYamlFlowItemSleep, M as MidsceneYamlScript, aI as MidsceneYamlScriptAndroidEnv, aJ as MidsceneYamlScriptEnv, aG as MidsceneYamlScriptEnvBase, aH as MidsceneYamlScriptWebEnv, i as MidsceneYamlTask, O as OnTaskStartTip, ay as PageType, P as PartialInsightDumpFromSDK, W as PlanningAIResponse, V as PlanningAction, a4 as PlanningActionParamAndroidLongPress, a5 as PlanningActionParamAndroidPull, a0 as PlanningActionParamAssert, a2 as PlanningActionParamError, Y as PlanningActionParamHover, _ as PlanningActionParamInputOrKeyPress, Z as PlanningActionParamRightClick, $ as PlanningActionParamScroll, a1 as PlanningActionParamSleep, X as PlanningActionParamTap, a3 as PlanningActionParamWaitFor, T as PlanningLocateParam, a9 as PlaywrightParserOpt, a8 as PuppeteerParserOpt, aE as ReferenceImage, R as ReportDumpWithAttributes, b1 as ScriptPlayerStatusValue, b0 as ScriptPlayerTaskStatus, aC as StreamingAIResponse, aA as StreamingCallback, az as StreamingCodeGenerationOptions, aF as scrollParam } from './types-d187efec.js';
3
+ import { c as callAiFn } from './llm-planning-ae19dc49.js';
4
+ export { a as AiAssert, A as AiLocateElement, d as describeUserPage, p as plan } from './llm-planning-ae19dc49.js';
5
5
  import { BaseElement, Rect } from '@midscene/shared/types';
6
6
  export { BaseElement, ElementTreeNode, Point, Rect, Size } from '@midscene/shared/types';
7
7
  export { getVersion } from './utils.js';
package/dist/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkTYKJHDNKjs = require('./chunk-TYKJHDNK.js');
3
+ var _chunkXIVVQRBCjs = require('./chunk-XIVVQRBC.js');
4
4
 
5
5
 
6
6
 
@@ -11,7 +11,7 @@ var _chunkTYKJHDNKjs = require('./chunk-TYKJHDNK.js');
11
11
 
12
12
 
13
13
 
14
- var _chunkYCHAOUOWjs = require('./chunk-YCHAOUOW.js');
14
+ var _chunkFKQMUAXPjs = require('./chunk-FKQMUAXP.js');
15
15
 
16
16
  // src/ai-model/action-executor.ts
17
17
 
@@ -124,8 +124,7 @@ ${_optionalChain([this, 'access', _7 => _7.latestErrorTask, 'call', _8 => _8(),
124
124
  taskIndex++;
125
125
  } catch (e) {
126
126
  successfullyCompleted = false;
127
- task.error = e;
128
- task.errorMessage = _optionalChain([e, 'optionalAccess', _12 => _12.message]) || (typeof e === "string" ? e : "error-without-message");
127
+ task.error = _optionalChain([e, 'optionalAccess', _12 => _12.message]) || (typeof e === "string" ? e : "error-without-message");
129
128
  task.errorStack = e.stack;
130
129
  task.status = "failed";
131
130
  task.timing.end = Date.now();
@@ -172,7 +171,7 @@ ${_optionalChain([this, 'access', _7 => _7.latestErrorTask, 'call', _8 => _8(),
172
171
  }
173
172
  }
174
173
  const dumpData = {
175
- sdkVersion: _chunkTYKJHDNKjs.getVersion.call(void 0, ),
174
+ sdkVersion: _chunkXIVVQRBCjs.getVersion.call(void 0, ),
176
175
  model_name: _env.getAIConfig.call(void 0, _env.MIDSCENE_MODEL_NAME) || "",
177
176
  model_description: modelDescription,
178
177
  logTime: Date.now(),
@@ -220,7 +219,7 @@ var _logger = require('@midscene/shared/logger');
220
219
 
221
220
  function emitInsightDump(data, dumpSubscriber) {
222
221
  const baseData = {
223
- sdkVersion: _chunkTYKJHDNKjs.getVersion.call(void 0, ),
222
+ sdkVersion: _chunkXIVVQRBCjs.getVersion.call(void 0, ),
224
223
  logTime: Date.now(),
225
224
  model_name: _env.getAIConfig.call(void 0, _env.MIDSCENE_MODEL_NAME) || ""
226
225
  };
@@ -236,7 +235,7 @@ function emitInsightDump(data, dumpSubscriber) {
236
235
  var debug = _logger.getDebug.call(void 0, "ai:insight");
237
236
  var Insight = class {
238
237
  constructor(context, opt) {
239
- this.aiVendorFn = _chunkYCHAOUOWjs.callAiFn;
238
+ this.aiVendorFn = _chunkFKQMUAXPjs.callAiFn;
240
239
  _utils.assert.call(void 0, context, "context is required for Insight");
241
240
  if (typeof context === "function") {
242
241
  this.contextRetrieverFn = context;
@@ -279,7 +278,7 @@ var Insight = class {
279
278
  let searchAreaUsage = void 0;
280
279
  let searchAreaResponse = void 0;
281
280
  if (searchAreaPrompt) {
282
- searchAreaResponse = await _chunkYCHAOUOWjs.AiLocateSection.call(void 0, {
281
+ searchAreaResponse = await _chunkFKQMUAXPjs.AiLocateSection.call(void 0, {
283
282
  context,
284
283
  sectionDescription: searchAreaPrompt
285
284
  });
@@ -299,7 +298,7 @@ var Insight = class {
299
298
  rawResponse,
300
299
  usage,
301
300
  isOrderSensitive
302
- } = await _chunkYCHAOUOWjs.AiLocateElement.call(void 0, {
301
+ } = await _chunkFKQMUAXPjs.AiLocateElement.call(void 0, {
303
302
  callAI: callAI || this.aiVendorFn,
304
303
  context,
305
304
  targetElementDescription: queryPrompt,
@@ -388,7 +387,7 @@ ${parseResult.errors.join("\n")}`;
388
387
  this.onceDumpUpdatedFn = void 0;
389
388
  const context = await this.contextRetrieverFn("extract");
390
389
  const startTime = Date.now();
391
- const { parseResult, usage } = await _chunkYCHAOUOWjs.AiExtractElementInfo.call(void 0, {
390
+ const { parseResult, usage } = await _chunkFKQMUAXPjs.AiExtractElementInfo.call(void 0, {
392
391
  context,
393
392
  dataQuery: dataDemand,
394
393
  extractOption: opt
@@ -440,7 +439,7 @@ ${parseResult.errors.join("\n")}`;
440
439
  this.onceDumpUpdatedFn = void 0;
441
440
  const context = await this.contextRetrieverFn("assert");
442
441
  const startTime = Date.now();
443
- const assertResult = await _chunkYCHAOUOWjs.AiAssert.call(void 0, {
442
+ const assertResult = await _chunkFKQMUAXPjs.AiAssert.call(void 0, {
444
443
  assertion,
445
444
  context
446
445
  });
@@ -494,7 +493,7 @@ ${parseResult.errors.join("\n")}`;
494
493
  borderThickness: 3
495
494
  });
496
495
  if (_optionalChain([opt, 'optionalAccess', _22 => _22.deepThink])) {
497
- const searchArea = _chunkYCHAOUOWjs.expandSearchArea.call(void 0, targetRect, context.size);
496
+ const searchArea = _chunkFKQMUAXPjs.expandSearchArea.call(void 0, targetRect, context.size);
498
497
  debug("describe: set searchArea", searchArea);
499
498
  imagePayload = await _img.cropByRect.call(void 0,
500
499
  imagePayload,
@@ -517,7 +516,7 @@ ${parseResult.errors.join("\n")}`;
517
516
  ]
518
517
  }
519
518
  ];
520
- const callAIFn = this.aiVendorFn || _chunkYCHAOUOWjs.callToGetJSONObject;
519
+ const callAIFn = this.aiVendorFn || _chunkFKQMUAXPjs.callToGetJSONObject;
521
520
  const res = await callAIFn(msgs, 4 /* DESCRIBE_ELEMENT */);
522
521
  const { content } = res;
523
522
  _utils.assert.call(void 0, !content.error, `describe failed: ${content.error}`);
@@ -540,6 +539,6 @@ var src_default = Insight;
540
539
 
541
540
 
542
541
 
543
- exports.AiAssert = _chunkYCHAOUOWjs.AiAssert; exports.AiLocateElement = _chunkYCHAOUOWjs.AiLocateElement; exports.Executor = Executor; exports.Insight = Insight; exports.MIDSCENE_MODEL_NAME = _env.MIDSCENE_MODEL_NAME; exports.default = src_default; exports.describeUserPage = _chunkYCHAOUOWjs.describeUserPage; exports.getAIConfig = _env.getAIConfig; exports.getVersion = _chunkTYKJHDNKjs.getVersion; exports.plan = _chunkYCHAOUOWjs.plan;
542
+ exports.AiAssert = _chunkFKQMUAXPjs.AiAssert; exports.AiLocateElement = _chunkFKQMUAXPjs.AiLocateElement; exports.Executor = Executor; exports.Insight = Insight; exports.MIDSCENE_MODEL_NAME = _env.MIDSCENE_MODEL_NAME; exports.default = src_default; exports.describeUserPage = _chunkFKQMUAXPjs.describeUserPage; exports.getAIConfig = _env.getAIConfig; exports.getVersion = _chunkXIVVQRBCjs.getVersion; exports.plan = _chunkFKQMUAXPjs.plan;
544
543
 
545
544
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAEhB,IAAM,WAAN,MAAe;AAAA,EAUpB,YACE,MACA,SAGA;AACA,SAAK,SACH,SAAS,SAAS,QAAQ,MAAM,SAAS,IAAI,YAAY;AAC3D,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS,SAAS,CAAC,GAAG;AAAA,MAAI,CAAC,SACvC,KAAK,kBAAkB,IAAI;AAAA,I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,MACP,QAAQ;AAAA,IACV,IACA;AAEJ,QAAI,eAAe,MAAM,wBAAwB;AAAA,MAC/C,gBAAgB;AAAA,MAChB;AAAA,MACA,sBAAsB;AAAA,QACpB;AAAA,UACE,MAAM;AAAA,QACR;AAAA,MACF;AAAA,MACA,iBAAiB;AAAA,IACnB,CAAC;AAED,QAAI,KAAK,WAAW;AAClB,YAAM,aAAa,iBAAiB,YAAY,QAAQ,IAAI;AAC5D,YAAM,4BAA4B,UAAU;AAC5C,qBAAe,MAAM;AAAA,QACnB;AAAA,QACA;AAAA,QACA,qBAAqB,oBAAoB;AAAA,MAC3C;AAAA,IACF;AAEA,UAAM,OAAe;AAAA,MACnB,EAAE,MAAM,UAAU,SAAS,aAAa;AAAA,MACxC;AAAA,QACE,MAAM;AAAA,QACN,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AAAA,YACN,WAAW;AAAA,cACT,KAAK;AAAA,cACL,QAAQ;AAAA,YACV;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WACJ,KAAK,cAAc;AAErB,UAAM,MAAM,MAAM,SAAS,8BAAmC;AAE9D,UAAM,EAAE,QAAQ,IAAI;AACpB,IAAAA,QAAO,CAAC,QAAQ,OAAO,oBAAoB,QAAQ,KAAK,EAAE;AAC1D,IAAAA,QAAO,QAAQ,aAAa,gCAAgC;AAC5D,WAAO;AAAA,EACT;AACF;;;AEjaA,SAAS,eAAAE,cAAa,uBAAAD,4BAA2B;AAGjD,IAAO,cAAQ","names":["vlLocateMode","assert","MIDSCENE_MODEL_NAME","getAIConfig"],"ignoreList":[],"sources":["../../src/ai-model/action-executor.ts","../../src/ai-model/prompt/describe.ts","../../src/insight/index.ts","../../src/insight/utils.ts","../../src/index.ts"],"sourcesContent":["import type {\n ExecutionDump,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskProgressOptions,\n ExecutionTaskReturn,\n ExecutorContext,\n} from '@/types';\nimport { getVersion } from '@/utils';\nimport {\n MIDSCENE_MODEL_NAME,\n getAIConfig,\n uiTarsModelVersion,\n vlLocateMode,\n} from '@midscene/shared/env';\nimport { assert } from '@midscene/shared/utils';\n\nexport class Executor {\n name: string;\n\n tasks: ExecutionTask[];\n\n // status of executor\n status: 'init' | 'pending' | 'running' | 'completed' | 'error';\n\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n\n constructor(\n name: string,\n options?: ExecutionTaskProgressOptions & {\n tasks?: ExecutionTaskApply[];\n },\n ) {\n this.status =\n options?.tasks && options.tasks.length > 0 ? 'pending' : 'init';\n this.name = name;\n this.tasks = (options?.tasks || []).map((item) =>\n this.markTaskAsPending(item),\n );\n this.onTaskStart = options?.onTaskStart;\n }\n\n private markTaskAsPending(task: ExecutionTaskApply): ExecutionTask {\n return {\n status: 'pending',\n ...task,\n };\n }\n\n async append(task: ExecutionTaskApply[] | ExecutionTaskApply): Promise<void> {\n assert(\n this.status !== 'error',\n `executor is in error state, cannot append task\\nerror=${this.latestErrorTask()?.error}\\n${this.latestErrorTask()?.errorStack}`,\n );\n if (Array.isArray(task)) {\n this.tasks.push(...task.map((item) => this.markTaskAsPending(item)));\n } else {\n this.tasks.push(this.markTaskAsPending(task));\n }\n if (this.status !== 'running') {\n this.status = 'pending';\n }\n }\n\n async flush(): Promise<any> {\n if (this.status === 'init' && this.tasks.length > 0) {\n console.warn(\n 'illegal state for executor, status is init but tasks are not empty',\n );\n }\n\n assert(this.status !== 'running', 'executor is already running');\n assert(this.status !== 'completed', 'executor is already completed');\n assert(this.status !== 'error', 'executor is in error state');\n\n const nextPendingIndex = this.tasks.findIndex(\n (task) => task.status === 'pending',\n );\n if (nextPendingIndex < 0) {\n // all tasks are completed\n return;\n }\n\n this.status = 'running';\n let taskIndex = nextPendingIndex;\n let successfullyCompleted = true;\n\n let previousFindOutput: ExecutionTaskInsightLocateOutput | undefined;\n\n while (taskIndex < this.tasks.length) {\n const task = this.tasks[taskIndex];\n assert(\n task.status === 'pending',\n `task status should be pending, but got: ${task.status}`,\n );\n task.timing = {\n start: Date.now(),\n };\n try {\n task.status = 'running';\n try {\n if (this.onTaskStart) {\n await this.onTaskStart(task);\n }\n } catch (e) {\n console.error('error in onTaskStart', e);\n }\n assert(\n ['Insight', 'Action', 'Planning'].indexOf(task.type) >= 0,\n `unsupported task type: ${task.type}`,\n );\n\n const { executor, param } = task;\n assert(executor, `executor is required for task type: ${task.type}`);\n\n let returnValue;\n const executorContext: ExecutorContext = {\n task,\n element: previousFindOutput?.element,\n };\n\n if (task.type === 'Insight') {\n assert(\n task.subType === 'Locate' ||\n task.subType === 'Query' ||\n task.subType === 'Assert' ||\n task.subType === 'Boolean' ||\n task.subType === 'Number' ||\n task.subType === 'String',\n `unsupported insight subType: ${task.subType}`,\n );\n returnValue = await task.executor(param, executorContext);\n if (task.subType === 'Locate') {\n previousFindOutput = (\n returnValue as ExecutionTaskReturn<ExecutionTaskInsightLocateOutput>\n )?.output;\n }\n } else if (task.type === 'Action' || task.type === 'Planning') {\n returnValue = await task.executor(param, executorContext);\n } else {\n console.warn(\n `unsupported task type: ${task.type}, will try to execute it directly`,\n );\n returnValue = await task.executor(param, executorContext);\n }\n\n Object.assign(task, returnValue);\n task.status = 'finished';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n taskIndex++;\n } catch (e: any) {\n successfullyCompleted = false;\n task.error = e;\n task.errorMessage =\n e?.message || (typeof e === 'string' ? e : 'error-without-message');\n task.errorStack = e.stack;\n\n task.status = 'failed';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n break;\n }\n }\n\n // set all remaining tasks as cancelled\n for (let i = taskIndex + 1; i < this.tasks.length; i++) {\n this.tasks[i].status = 'cancelled';\n }\n\n if (successfullyCompleted) {\n this.status = 'completed';\n } else {\n this.status = 'error';\n }\n\n if (this.tasks.length) {\n // return the last output\n const outputIndex = Math.min(taskIndex, this.tasks.length - 1);\n return this.tasks[outputIndex].output;\n }\n }\n\n isInErrorState(): boolean {\n return this.status === 'error';\n }\n\n latestErrorTask(): ExecutionTask | null {\n if (this.status !== 'error') {\n return null;\n }\n const errorTaskIndex = this.tasks.findIndex(\n (task) => task.status === 'failed',\n );\n if (errorTaskIndex >= 0) {\n return this.tasks[errorTaskIndex];\n }\n return null;\n }\n\n dump(): ExecutionDump {\n let modelDescription = '';\n\n if (vlLocateMode()) {\n const uiTarsModelVer = uiTarsModelVersion();\n if (uiTarsModelVer) {\n modelDescription = `UI-TARS=${uiTarsModelVer}`;\n } else {\n modelDescription = `${vlLocateMode()} mode`;\n }\n }\n const dumpData: ExecutionDump = {\n sdkVersion: getVersion(),\n model_name: getAIConfig(MIDSCENE_MODEL_NAME) || '',\n model_description: modelDescription,\n logTime: Date.now(),\n name: this.name,\n tasks: this.tasks,\n };\n return dumpData;\n }\n}\n","import { getPreferredLanguage } from '@midscene/shared/env';\n\nexport const elementDescriberInstruction = () => {\n return `Describe the element in the red rectangle for precise identification. Use ${getPreferredLanguage()}.\n\nRules:\n1. Start with element type (button, input, link, etc.) \n2. Include key identifiers:\n - Text content: \"with text 'Submit'\"\n - Visual features: \"blue background\", \"icon only\"\n - Position: \"top-right\", \"below search bar\"\n3. Keep description under 20 words\n4. Don't mention the red rectangle\n\nReturn JSON:\n{\n \"description\": \"brief element type with key identifiers\",\n \"error\"?: \"error message if any\"\n}`;\n};\n","import {\n AIActionType,\n type AIArgs,\n callAiFn,\n expandSearchArea,\n} from '@/ai-model/common';\nimport {\n AiExtractElementInfo,\n AiLocateElement,\n callToGetJSONObject,\n} from '@/ai-model/index';\nimport { AiAssert, AiLocateSection } from '@/ai-model/inspect';\nimport { elementDescriberInstruction } from '@/ai-model/prompt/describe';\nimport type {\n AIDescribeElementResponse,\n AIElementResponse,\n AIUsageInfo,\n BaseElement,\n DetailedLocateParam,\n DumpSubscriber,\n InsightAction,\n InsightAssertionResponse,\n InsightExtractOption,\n InsightExtractParam,\n InsightOptions,\n InsightTaskInfo,\n LocateResult,\n PartialInsightDumpFromSDK,\n Rect,\n UIContext,\n} from '@/types';\nimport {\n MIDSCENE_FORCE_DEEP_THINK,\n MIDSCENE_USE_QWEN_VL,\n getAIConfigInBoolean,\n vlLocateMode,\n} from '@midscene/shared/env';\nimport { compositeElementInfoImg, cropByRect } from '@midscene/shared/img';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport { emitInsightDump } from './utils';\n\nexport interface LocateOpts {\n context?: UIContext<BaseElement>;\n callAI?: typeof callAiFn<AIElementResponse>;\n}\n\nexport type AnyValue<T> = {\n [K in keyof T]: unknown extends T[K] ? any : T[K];\n};\n\nconst debug = getDebug('ai:insight');\nexport default class Insight<\n ElementType extends BaseElement = BaseElement,\n ContextType extends UIContext<ElementType> = UIContext<ElementType>,\n> {\n contextRetrieverFn: (\n action: InsightAction,\n ) => Promise<ContextType> | ContextType;\n\n aiVendorFn: (...args: Array<any>) => Promise<any> = callAiFn;\n\n onceDumpUpdatedFn?: DumpSubscriber;\n\n taskInfo?: Omit<InsightTaskInfo, 'durationMs'>;\n\n constructor(\n context:\n | ContextType\n | ((action: InsightAction) => Promise<ContextType> | ContextType),\n opt?: InsightOptions,\n ) {\n assert(context, 'context is required for Insight');\n if (typeof context === 'function') {\n this.contextRetrieverFn = context;\n } else {\n this.contextRetrieverFn = () => Promise.resolve(context);\n }\n\n if (typeof opt?.aiVendorFn !== 'undefined') {\n this.aiVendorFn = opt.aiVendorFn;\n }\n if (typeof opt?.taskInfo !== 'undefined') {\n this.taskInfo = opt.taskInfo;\n }\n }\n\n async locate(\n query: DetailedLocateParam,\n opt?: LocateOpts,\n ): Promise<LocateResult> {\n const { callAI } = opt || {};\n const queryPrompt = typeof query === 'string' ? query : query.prompt;\n assert(queryPrompt, 'query is required for locate');\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n assert(typeof query === 'object', 'query should be an object for locate');\n\n const globalDeepThinkSwitch = getAIConfigInBoolean(\n MIDSCENE_FORCE_DEEP_THINK,\n );\n if (globalDeepThinkSwitch) {\n debug('globalDeepThinkSwitch', globalDeepThinkSwitch);\n }\n let searchAreaPrompt;\n if (query.deepThink || globalDeepThinkSwitch) {\n searchAreaPrompt = query.prompt;\n }\n\n if (searchAreaPrompt && !vlLocateMode()) {\n console.warn(\n 'The \"deepThink\" feature is not supported with multimodal LLM. Please config VL model for Midscene. https://midscenejs.com/choose-a-model',\n );\n searchAreaPrompt = undefined;\n }\n\n const context = opt?.context || (await this.contextRetrieverFn('locate'));\n\n let searchArea: Rect | undefined = undefined;\n let searchAreaRawResponse: string | undefined = undefined;\n let searchAreaUsage: AIUsageInfo | undefined = undefined;\n let searchAreaResponse:\n | Awaited<ReturnType<typeof AiLocateSection>>\n | undefined = undefined;\n if (searchAreaPrompt) {\n searchAreaResponse = await AiLocateSection({\n context,\n sectionDescription: searchAreaPrompt,\n });\n assert(\n searchAreaResponse.rect,\n `cannot find search area for \"${searchAreaPrompt}\"${\n searchAreaResponse.error ? `: ${searchAreaResponse.error}` : ''\n }`,\n );\n searchAreaRawResponse = searchAreaResponse.rawResponse;\n searchAreaUsage = searchAreaResponse.usage;\n searchArea = searchAreaResponse.rect;\n }\n\n const startTime = Date.now();\n const {\n parseResult,\n rect,\n elementById,\n rawResponse,\n usage,\n isOrderSensitive,\n } = await AiLocateElement({\n callAI: callAI || this.aiVendorFn,\n context,\n targetElementDescription: queryPrompt,\n searchConfig: searchAreaResponse,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(rawResponse),\n formatResponse: JSON.stringify(parseResult),\n usage,\n searchArea,\n searchAreaRawResponse,\n searchAreaUsage,\n };\n\n let errorLog: string | undefined;\n if (parseResult.errors?.length) {\n errorLog = `AI model failed to locate: \\n${parseResult.errors.join('\\n')}`;\n }\n\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'locate',\n userQuery: {\n element: queryPrompt,\n },\n matchedElement: [],\n matchedRect: rect,\n data: null,\n taskInfo,\n deepThink: !!searchArea,\n error: errorLog,\n };\n\n const elements: BaseElement[] = [];\n (parseResult.elements || []).forEach((item) => {\n if ('id' in item) {\n const element = elementById(item?.id);\n\n if (!element) {\n console.warn(\n `locate: cannot find element id=${item.id}. Maybe an unstable response from AI model`,\n );\n return;\n }\n elements.push(element);\n }\n });\n\n emitInsightDump(\n {\n ...dumpData,\n matchedElement: elements,\n },\n dumpSubscriber,\n );\n\n if (errorLog) {\n throw new Error(errorLog);\n }\n\n assert(\n elements.length <= 1,\n `locate: multiple elements found, length = ${elements.length}`,\n );\n\n if (elements.length === 1) {\n return {\n element: {\n id: elements[0]!.id,\n indexId: elements[0]!.indexId,\n center: elements[0]!.center,\n rect: elements[0]!.rect,\n xpaths: elements[0]!.xpaths || [],\n attributes: elements[0]!.attributes,\n isOrderSensitive,\n },\n rect,\n };\n }\n return {\n element: null,\n rect,\n };\n }\n\n async extract<T = any>(input: string, opt?: InsightExtractOption): Promise<T>;\n async extract<T extends Record<string, string>>(\n input: T,\n opt?: InsightExtractOption,\n ): Promise<Record<keyof T, any>>;\n async extract<T extends object>(\n input: Record<keyof T, string>,\n opt?: InsightExtractOption,\n ): Promise<T>;\n\n async extract<T>(\n dataDemand: InsightExtractParam,\n opt?: InsightExtractOption,\n ): Promise<any> {\n assert(\n typeof dataDemand === 'object' || typeof dataDemand === 'string',\n `dataDemand should be object or string, but get ${typeof dataDemand}`,\n );\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n const context = await this.contextRetrieverFn('extract');\n\n const startTime = Date.now();\n const { parseResult, usage } = await AiExtractElementInfo<T>({\n context,\n dataQuery: dataDemand,\n extractOption: opt,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(parseResult),\n };\n\n let errorLog: string | undefined;\n if (parseResult.errors?.length) {\n errorLog = `AI response error: \\n${parseResult.errors.join('\\n')}`;\n }\n\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'extract',\n userQuery: {\n dataDemand,\n },\n matchedElement: [],\n data: null,\n taskInfo,\n error: errorLog,\n };\n\n const { data } = parseResult || {};\n\n // 4\n emitInsightDump(\n {\n ...dumpData,\n data,\n },\n dumpSubscriber,\n );\n\n if (errorLog && !data) {\n throw new Error(errorLog);\n }\n\n return {\n data,\n usage,\n };\n }\n\n async assert(assertion: string): Promise<InsightAssertionResponse> {\n if (typeof assertion !== 'string') {\n throw new Error(\n 'This is the assert method for Midscene, the first argument should be a string. If you want to use the assert method from Node.js, please import it from the Node.js assert module.',\n );\n }\n\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n const context = await this.contextRetrieverFn('assert');\n const startTime = Date.now();\n const assertResult = await AiAssert({\n assertion,\n context,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(assertResult.content),\n };\n\n const { thought, pass } = assertResult.content;\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'assert',\n userQuery: {\n assertion,\n },\n matchedElement: [],\n data: null,\n taskInfo,\n assertionPass: pass,\n assertionThought: thought,\n error: pass ? undefined : thought,\n };\n emitInsightDump(dumpData, dumpSubscriber);\n\n return {\n pass,\n thought,\n usage: assertResult.usage,\n };\n }\n async describe(\n target: Rect | [number, number],\n opt?: {\n deepThink?: boolean;\n },\n ): Promise<Pick<AIDescribeElementResponse, 'description'>> {\n assert(target, 'target is required for insight.describe');\n const context = await this.contextRetrieverFn('describe');\n const { screenshotBase64, size } = context;\n assert(screenshotBase64, 'screenshot is required for insight.describe');\n\n const systemPrompt = elementDescriberInstruction();\n\n // Convert [x,y] center point to Rect if needed\n const defaultRectSize = 30;\n const targetRect: Rect = Array.isArray(target)\n ? {\n left: Math.floor(target[0] - defaultRectSize / 2),\n top: Math.floor(target[1] - defaultRectSize / 2),\n width: defaultRectSize,\n height: defaultRectSize,\n }\n : target;\n\n let imagePayload = await compositeElementInfoImg({\n inputImgBase64: screenshotBase64,\n size,\n elementsPositionInfo: [\n {\n rect: targetRect,\n },\n ],\n borderThickness: 3,\n });\n\n if (opt?.deepThink) {\n const searchArea = expandSearchArea(targetRect, context.size);\n debug('describe: set searchArea', searchArea);\n imagePayload = await cropByRect(\n imagePayload,\n searchArea,\n getAIConfigInBoolean(MIDSCENE_USE_QWEN_VL),\n );\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: imagePayload,\n detail: 'high',\n },\n },\n ],\n },\n ];\n\n const callAIFn =\n this.aiVendorFn || callToGetJSONObject<AIDescribeElementResponse>;\n\n const res = await callAIFn(msgs, AIActionType.DESCRIBE_ELEMENT);\n\n const { content } = res;\n assert(!content.error, `describe failed: ${content.error}`);\n assert(content.description, 'failed to describe the element');\n return content;\n }\n}\n","import type {\n DumpMeta,\n DumpSubscriber,\n InsightDump,\n PartialInsightDumpFromSDK,\n} from '@/types';\nimport { getVersion } from '@/utils';\nimport { MIDSCENE_MODEL_NAME, getAIConfig } from '@midscene/shared/env';\nimport { uuid } from '@midscene/shared/utils';\n\nexport function emitInsightDump(\n data: PartialInsightDumpFromSDK,\n dumpSubscriber?: DumpSubscriber,\n) {\n const baseData: DumpMeta = {\n sdkVersion: getVersion(),\n logTime: Date.now(),\n model_name: getAIConfig(MIDSCENE_MODEL_NAME) || '',\n };\n const finalData: InsightDump = {\n logId: uuid(),\n ...baseData,\n ...data,\n };\n\n dumpSubscriber?.(finalData);\n}\n","import { Executor } from './ai-model/action-executor';\nimport Insight from './insight/index';\nimport { getVersion } from './utils';\n\nexport {\n plan,\n describeUserPage,\n AiLocateElement,\n AiAssert,\n} from './ai-model/index';\n\nexport { getAIConfig, MIDSCENE_MODEL_NAME } from '@midscene/shared/env';\n\nexport type * from './types';\nexport default Insight;\nexport { Executor, Insight, getVersion };\n\nexport type {\n MidsceneYamlScript,\n MidsceneYamlTask,\n MidsceneYamlFlowItem,\n MidsceneYamlFlowItemAIRightClick,\n MidsceneYamlConfigResult,\n} from './yaml';\n"]}
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAEhB,IAAM,WAAN,MAAe;AAAA,EAUpB,YACE,MACA,SAGA;AACA,SAAK,SACH,SAAS,SAAS,QAAQ,MAAM,SAAS,IAAI,YAAY;AAC3D,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS,SAAS,CAAC,GAAG;AAAA,MAAI,CAAC,SACvC,KAAK,kBAAkB,IAAI;AAAA,IAC7B;AACA,SAAK,cAAc,SAAS;AAAA,EAC9B;AAAA,EAEQ,kBAAkB,MAAyC;AACjE,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,GAAG;AAAA,IACL;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,MAAgE;AAC3E;AAAA,MACE,KAAK,WAAW;AAAA,MAChB;AAAA,QAAyD,KAAK,gBAAgB,GAAG,KAAK;AAAA,EAAK,KAAK,gBAAgB,GAAG,UAAU;AAAA,IAC/H;AACA,QAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,WAAK,MAAM,KAAK,GAAG,KAAK,IAAI,CAAC,SAAS,KAAK,kBAAkB,IAAI,CAAC,CAAC;AAAA,IACrE,OAAO;AACL,WAAK,MAAM,KAAK,KAAK,kBAAkB,IAAI,CAAC;AAAA,IAC9C;AACA,QAAI,KAAK,WAAW,WAAW;AAC7B,WAAK,SAAS;AAAA,IAChB;AAAA,EACF;AAAA,EAEA,MAAM,QAAsB;AAC1B,QAAI,KAAK,WAAW,UAAU,KAAK,MAAM,SAAS,G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AM,MAAM,MAAM,SAAS,8BAAmC;AAE9D,UAAM,EAAE,QAAQ,IAAI;AACpB,IAAAA,QAAO,CAAC,QAAQ,OAAO,oBAAoB,QAAQ,KAAK,EAAE;AAC1D,IAAAA,QAAO,QAAQ,aAAa,gCAAgC;AAC5D,WAAO;AAAA,EACT;AACF;;;AEjaA,SAAS,eAAAE,cAAa,uBAAAD,4BAA2B;AAGjD,IAAO,cAAQ","names":["vlLocateMode","assert","MIDSCENE_MODEL_NAME","getAIConfig"],"ignoreList":[],"sources":["../../src/ai-model/action-executor.ts","../../src/ai-model/prompt/describe.ts","../../src/insight/index.ts","../../src/insight/utils.ts","../../src/index.ts"],"sourcesContent":["import type {\n ExecutionDump,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskProgressOptions,\n ExecutionTaskReturn,\n ExecutorContext,\n} from '@/types';\nimport { getVersion } from '@/utils';\nimport {\n MIDSCENE_MODEL_NAME,\n getAIConfig,\n uiTarsModelVersion,\n vlLocateMode,\n} from '@midscene/shared/env';\nimport { assert } from '@midscene/shared/utils';\n\nexport class Executor {\n name: string;\n\n tasks: ExecutionTask[];\n\n // status of executor\n status: 'init' | 'pending' | 'running' | 'completed' | 'error';\n\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n\n constructor(\n name: string,\n options?: ExecutionTaskProgressOptions & {\n tasks?: ExecutionTaskApply[];\n },\n ) {\n this.status =\n options?.tasks && options.tasks.length > 0 ? 'pending' : 'init';\n this.name = name;\n this.tasks = (options?.tasks || []).map((item) =>\n this.markTaskAsPending(item),\n );\n this.onTaskStart = options?.onTaskStart;\n }\n\n private markTaskAsPending(task: ExecutionTaskApply): ExecutionTask {\n return {\n status: 'pending',\n ...task,\n };\n }\n\n async append(task: ExecutionTaskApply[] | ExecutionTaskApply): Promise<void> {\n assert(\n this.status !== 'error',\n `executor is in error state, cannot append task\\nerror=${this.latestErrorTask()?.error}\\n${this.latestErrorTask()?.errorStack}`,\n );\n if (Array.isArray(task)) {\n this.tasks.push(...task.map((item) => this.markTaskAsPending(item)));\n } else {\n this.tasks.push(this.markTaskAsPending(task));\n }\n if (this.status !== 'running') {\n this.status = 'pending';\n }\n }\n\n async flush(): Promise<any> {\n if (this.status === 'init' && this.tasks.length > 0) {\n console.warn(\n 'illegal state for executor, status is init but tasks are not empty',\n );\n }\n\n assert(this.status !== 'running', 'executor is already running');\n assert(this.status !== 'completed', 'executor is already completed');\n assert(this.status !== 'error', 'executor is in error state');\n\n const nextPendingIndex = this.tasks.findIndex(\n (task) => task.status === 'pending',\n );\n if (nextPendingIndex < 0) {\n // all tasks are completed\n return;\n }\n\n this.status = 'running';\n let taskIndex = nextPendingIndex;\n let successfullyCompleted = true;\n\n let previousFindOutput: ExecutionTaskInsightLocateOutput | undefined;\n\n while (taskIndex < this.tasks.length) {\n const task = this.tasks[taskIndex];\n assert(\n task.status === 'pending',\n `task status should be pending, but got: ${task.status}`,\n );\n task.timing = {\n start: Date.now(),\n };\n try {\n task.status = 'running';\n try {\n if (this.onTaskStart) {\n await this.onTaskStart(task);\n }\n } catch (e) {\n console.error('error in onTaskStart', e);\n }\n assert(\n ['Insight', 'Action', 'Planning'].indexOf(task.type) >= 0,\n `unsupported task type: ${task.type}`,\n );\n\n const { executor, param } = task;\n assert(executor, `executor is required for task type: ${task.type}`);\n\n let returnValue;\n const executorContext: ExecutorContext = {\n task,\n element: previousFindOutput?.element,\n };\n\n if (task.type === 'Insight') {\n assert(\n task.subType === 'Locate' ||\n task.subType === 'Query' ||\n task.subType === 'Assert' ||\n task.subType === 'Boolean' ||\n task.subType === 'Number' ||\n task.subType === 'String',\n `unsupported insight subType: ${task.subType}`,\n );\n returnValue = await task.executor(param, executorContext);\n if (task.subType === 'Locate') {\n previousFindOutput = (\n returnValue as ExecutionTaskReturn<ExecutionTaskInsightLocateOutput>\n )?.output;\n }\n } else if (task.type === 'Action' || task.type === 'Planning') {\n returnValue = await task.executor(param, executorContext);\n } else {\n console.warn(\n `unsupported task type: ${task.type}, will try to execute it directly`,\n );\n returnValue = await task.executor(param, executorContext);\n }\n\n Object.assign(task, returnValue);\n task.status = 'finished';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n taskIndex++;\n } catch (e: any) {\n successfullyCompleted = false;\n task.error =\n e?.message || (typeof e === 'string' ? e : 'error-without-message');\n task.errorStack = e.stack;\n\n task.status = 'failed';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n break;\n }\n }\n\n // set all remaining tasks as cancelled\n for (let i = taskIndex + 1; i < this.tasks.length; i++) {\n this.tasks[i].status = 'cancelled';\n }\n\n if (successfullyCompleted) {\n this.status = 'completed';\n } else {\n this.status = 'error';\n }\n\n if (this.tasks.length) {\n // return the last output\n const outputIndex = Math.min(taskIndex, this.tasks.length - 1);\n return this.tasks[outputIndex].output;\n }\n }\n\n isInErrorState(): boolean {\n return this.status === 'error';\n }\n\n latestErrorTask(): ExecutionTask | null {\n if (this.status !== 'error') {\n return null;\n }\n const errorTaskIndex = this.tasks.findIndex(\n (task) => task.status === 'failed',\n );\n if (errorTaskIndex >= 0) {\n return this.tasks[errorTaskIndex];\n }\n return null;\n }\n\n dump(): ExecutionDump {\n let modelDescription = '';\n\n if (vlLocateMode()) {\n const uiTarsModelVer = uiTarsModelVersion();\n if (uiTarsModelVer) {\n modelDescription = `UI-TARS=${uiTarsModelVer}`;\n } else {\n modelDescription = `${vlLocateMode()} mode`;\n }\n }\n const dumpData: ExecutionDump = {\n sdkVersion: getVersion(),\n model_name: getAIConfig(MIDSCENE_MODEL_NAME) || '',\n model_description: modelDescription,\n logTime: Date.now(),\n name: this.name,\n tasks: this.tasks,\n };\n return dumpData;\n }\n}\n","import { getPreferredLanguage } from '@midscene/shared/env';\n\nexport const elementDescriberInstruction = () => {\n return `Describe the element in the red rectangle for precise identification. Use ${getPreferredLanguage()}.\n\nRules:\n1. Start with element type (button, input, link, etc.) \n2. Include key identifiers:\n - Text content: \"with text 'Submit'\"\n - Visual features: \"blue background\", \"icon only\"\n - Position: \"top-right\", \"below search bar\"\n3. Keep description under 20 words\n4. Don't mention the red rectangle\n\nReturn JSON:\n{\n \"description\": \"brief element type with key identifiers\",\n \"error\"?: \"error message if any\"\n}`;\n};\n","import {\n AIActionType,\n type AIArgs,\n callAiFn,\n expandSearchArea,\n} from '@/ai-model/common';\nimport {\n AiExtractElementInfo,\n AiLocateElement,\n callToGetJSONObject,\n} from '@/ai-model/index';\nimport { AiAssert, AiLocateSection } from '@/ai-model/inspect';\nimport { elementDescriberInstruction } from '@/ai-model/prompt/describe';\nimport type {\n AIDescribeElementResponse,\n AIElementResponse,\n AIUsageInfo,\n BaseElement,\n DetailedLocateParam,\n DumpSubscriber,\n InsightAction,\n InsightAssertionResponse,\n InsightExtractOption,\n InsightExtractParam,\n InsightOptions,\n InsightTaskInfo,\n LocateResult,\n PartialInsightDumpFromSDK,\n Rect,\n UIContext,\n} from '@/types';\nimport {\n MIDSCENE_FORCE_DEEP_THINK,\n MIDSCENE_USE_QWEN_VL,\n getAIConfigInBoolean,\n vlLocateMode,\n} from '@midscene/shared/env';\nimport { compositeElementInfoImg, cropByRect } from '@midscene/shared/img';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport { emitInsightDump } from './utils';\n\nexport interface LocateOpts {\n context?: UIContext<BaseElement>;\n callAI?: typeof callAiFn<AIElementResponse>;\n}\n\nexport type AnyValue<T> = {\n [K in keyof T]: unknown extends T[K] ? any : T[K];\n};\n\nconst debug = getDebug('ai:insight');\nexport default class Insight<\n ElementType extends BaseElement = BaseElement,\n ContextType extends UIContext<ElementType> = UIContext<ElementType>,\n> {\n contextRetrieverFn: (\n action: InsightAction,\n ) => Promise<ContextType> | ContextType;\n\n aiVendorFn: (...args: Array<any>) => Promise<any> = callAiFn;\n\n onceDumpUpdatedFn?: DumpSubscriber;\n\n taskInfo?: Omit<InsightTaskInfo, 'durationMs'>;\n\n constructor(\n context:\n | ContextType\n | ((action: InsightAction) => Promise<ContextType> | ContextType),\n opt?: InsightOptions,\n ) {\n assert(context, 'context is required for Insight');\n if (typeof context === 'function') {\n this.contextRetrieverFn = context;\n } else {\n this.contextRetrieverFn = () => Promise.resolve(context);\n }\n\n if (typeof opt?.aiVendorFn !== 'undefined') {\n this.aiVendorFn = opt.aiVendorFn;\n }\n if (typeof opt?.taskInfo !== 'undefined') {\n this.taskInfo = opt.taskInfo;\n }\n }\n\n async locate(\n query: DetailedLocateParam,\n opt?: LocateOpts,\n ): Promise<LocateResult> {\n const { callAI } = opt || {};\n const queryPrompt = typeof query === 'string' ? query : query.prompt;\n assert(queryPrompt, 'query is required for locate');\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n assert(typeof query === 'object', 'query should be an object for locate');\n\n const globalDeepThinkSwitch = getAIConfigInBoolean(\n MIDSCENE_FORCE_DEEP_THINK,\n );\n if (globalDeepThinkSwitch) {\n debug('globalDeepThinkSwitch', globalDeepThinkSwitch);\n }\n let searchAreaPrompt;\n if (query.deepThink || globalDeepThinkSwitch) {\n searchAreaPrompt = query.prompt;\n }\n\n if (searchAreaPrompt && !vlLocateMode()) {\n console.warn(\n 'The \"deepThink\" feature is not supported with multimodal LLM. Please config VL model for Midscene. https://midscenejs.com/choose-a-model',\n );\n searchAreaPrompt = undefined;\n }\n\n const context = opt?.context || (await this.contextRetrieverFn('locate'));\n\n let searchArea: Rect | undefined = undefined;\n let searchAreaRawResponse: string | undefined = undefined;\n let searchAreaUsage: AIUsageInfo | undefined = undefined;\n let searchAreaResponse:\n | Awaited<ReturnType<typeof AiLocateSection>>\n | undefined = undefined;\n if (searchAreaPrompt) {\n searchAreaResponse = await AiLocateSection({\n context,\n sectionDescription: searchAreaPrompt,\n });\n assert(\n searchAreaResponse.rect,\n `cannot find search area for \"${searchAreaPrompt}\"${\n searchAreaResponse.error ? `: ${searchAreaResponse.error}` : ''\n }`,\n );\n searchAreaRawResponse = searchAreaResponse.rawResponse;\n searchAreaUsage = searchAreaResponse.usage;\n searchArea = searchAreaResponse.rect;\n }\n\n const startTime = Date.now();\n const {\n parseResult,\n rect,\n elementById,\n rawResponse,\n usage,\n isOrderSensitive,\n } = await AiLocateElement({\n callAI: callAI || this.aiVendorFn,\n context,\n targetElementDescription: queryPrompt,\n searchConfig: searchAreaResponse,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(rawResponse),\n formatResponse: JSON.stringify(parseResult),\n usage,\n searchArea,\n searchAreaRawResponse,\n searchAreaUsage,\n };\n\n let errorLog: string | undefined;\n if (parseResult.errors?.length) {\n errorLog = `AI model failed to locate: \\n${parseResult.errors.join('\\n')}`;\n }\n\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'locate',\n userQuery: {\n element: queryPrompt,\n },\n matchedElement: [],\n matchedRect: rect,\n data: null,\n taskInfo,\n deepThink: !!searchArea,\n error: errorLog,\n };\n\n const elements: BaseElement[] = [];\n (parseResult.elements || []).forEach((item) => {\n if ('id' in item) {\n const element = elementById(item?.id);\n\n if (!element) {\n console.warn(\n `locate: cannot find element id=${item.id}. Maybe an unstable response from AI model`,\n );\n return;\n }\n elements.push(element);\n }\n });\n\n emitInsightDump(\n {\n ...dumpData,\n matchedElement: elements,\n },\n dumpSubscriber,\n );\n\n if (errorLog) {\n throw new Error(errorLog);\n }\n\n assert(\n elements.length <= 1,\n `locate: multiple elements found, length = ${elements.length}`,\n );\n\n if (elements.length === 1) {\n return {\n element: {\n id: elements[0]!.id,\n indexId: elements[0]!.indexId,\n center: elements[0]!.center,\n rect: elements[0]!.rect,\n xpaths: elements[0]!.xpaths || [],\n attributes: elements[0]!.attributes,\n isOrderSensitive,\n },\n rect,\n };\n }\n return {\n element: null,\n rect,\n };\n }\n\n async extract<T = any>(input: string, opt?: InsightExtractOption): Promise<T>;\n async extract<T extends Record<string, string>>(\n input: T,\n opt?: InsightExtractOption,\n ): Promise<Record<keyof T, any>>;\n async extract<T extends object>(\n input: Record<keyof T, string>,\n opt?: InsightExtractOption,\n ): Promise<T>;\n\n async extract<T>(\n dataDemand: InsightExtractParam,\n opt?: InsightExtractOption,\n ): Promise<any> {\n assert(\n typeof dataDemand === 'object' || typeof dataDemand === 'string',\n `dataDemand should be object or string, but get ${typeof dataDemand}`,\n );\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n const context = await this.contextRetrieverFn('extract');\n\n const startTime = Date.now();\n const { parseResult, usage } = await AiExtractElementInfo<T>({\n context,\n dataQuery: dataDemand,\n extractOption: opt,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(parseResult),\n };\n\n let errorLog: string | undefined;\n if (parseResult.errors?.length) {\n errorLog = `AI response error: \\n${parseResult.errors.join('\\n')}`;\n }\n\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'extract',\n userQuery: {\n dataDemand,\n },\n matchedElement: [],\n data: null,\n taskInfo,\n error: errorLog,\n };\n\n const { data } = parseResult || {};\n\n // 4\n emitInsightDump(\n {\n ...dumpData,\n data,\n },\n dumpSubscriber,\n );\n\n if (errorLog && !data) {\n throw new Error(errorLog);\n }\n\n return {\n data,\n usage,\n };\n }\n\n async assert(assertion: string): Promise<InsightAssertionResponse> {\n if (typeof assertion !== 'string') {\n throw new Error(\n 'This is the assert method for Midscene, the first argument should be a string. If you want to use the assert method from Node.js, please import it from the Node.js assert module.',\n );\n }\n\n const dumpSubscriber = this.onceDumpUpdatedFn;\n this.onceDumpUpdatedFn = undefined;\n\n const context = await this.contextRetrieverFn('assert');\n const startTime = Date.now();\n const assertResult = await AiAssert({\n assertion,\n context,\n });\n\n const timeCost = Date.now() - startTime;\n const taskInfo: InsightTaskInfo = {\n ...(this.taskInfo ? this.taskInfo : {}),\n durationMs: timeCost,\n rawResponse: JSON.stringify(assertResult.content),\n };\n\n const { thought, pass } = assertResult.content;\n const dumpData: PartialInsightDumpFromSDK = {\n type: 'assert',\n userQuery: {\n assertion,\n },\n matchedElement: [],\n data: null,\n taskInfo,\n assertionPass: pass,\n assertionThought: thought,\n error: pass ? undefined : thought,\n };\n emitInsightDump(dumpData, dumpSubscriber);\n\n return {\n pass,\n thought,\n usage: assertResult.usage,\n };\n }\n async describe(\n target: Rect | [number, number],\n opt?: {\n deepThink?: boolean;\n },\n ): Promise<Pick<AIDescribeElementResponse, 'description'>> {\n assert(target, 'target is required for insight.describe');\n const context = await this.contextRetrieverFn('describe');\n const { screenshotBase64, size } = context;\n assert(screenshotBase64, 'screenshot is required for insight.describe');\n\n const systemPrompt = elementDescriberInstruction();\n\n // Convert [x,y] center point to Rect if needed\n const defaultRectSize = 30;\n const targetRect: Rect = Array.isArray(target)\n ? {\n left: Math.floor(target[0] - defaultRectSize / 2),\n top: Math.floor(target[1] - defaultRectSize / 2),\n width: defaultRectSize,\n height: defaultRectSize,\n }\n : target;\n\n let imagePayload = await compositeElementInfoImg({\n inputImgBase64: screenshotBase64,\n size,\n elementsPositionInfo: [\n {\n rect: targetRect,\n },\n ],\n borderThickness: 3,\n });\n\n if (opt?.deepThink) {\n const searchArea = expandSearchArea(targetRect, context.size);\n debug('describe: set searchArea', searchArea);\n imagePayload = await cropByRect(\n imagePayload,\n searchArea,\n getAIConfigInBoolean(MIDSCENE_USE_QWEN_VL),\n );\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: imagePayload,\n detail: 'high',\n },\n },\n ],\n },\n ];\n\n const callAIFn =\n this.aiVendorFn || callToGetJSONObject<AIDescribeElementResponse>;\n\n const res = await callAIFn(msgs, AIActionType.DESCRIBE_ELEMENT);\n\n const { content } = res;\n assert(!content.error, `describe failed: ${content.error}`);\n assert(content.description, 'failed to describe the element');\n return content;\n }\n}\n","import type {\n DumpMeta,\n DumpSubscriber,\n InsightDump,\n PartialInsightDumpFromSDK,\n} from '@/types';\nimport { getVersion } from '@/utils';\nimport { MIDSCENE_MODEL_NAME, getAIConfig } from '@midscene/shared/env';\nimport { uuid } from '@midscene/shared/utils';\n\nexport function emitInsightDump(\n data: PartialInsightDumpFromSDK,\n dumpSubscriber?: DumpSubscriber,\n) {\n const baseData: DumpMeta = {\n sdkVersion: getVersion(),\n logTime: Date.now(),\n model_name: getAIConfig(MIDSCENE_MODEL_NAME) || '',\n };\n const finalData: InsightDump = {\n logId: uuid(),\n ...baseData,\n ...data,\n };\n\n dumpSubscriber?.(finalData);\n}\n","import { Executor } from './ai-model/action-executor';\nimport Insight from './insight/index';\nimport { getVersion } from './utils';\n\nexport {\n plan,\n describeUserPage,\n AiLocateElement,\n AiAssert,\n} from './ai-model/index';\n\nexport { getAIConfig, MIDSCENE_MODEL_NAME } from '@midscene/shared/env';\n\nexport type * from './types';\nexport default Insight;\nexport { Executor, Insight, getVersion };\n\nexport type {\n MidsceneYamlScript,\n MidsceneYamlTask,\n MidsceneYamlFlowItem,\n MidsceneYamlFlowItemAIRightClick,\n MidsceneYamlConfigResult,\n} from './yaml';\n"]}
@@ -1,4 +1,4 @@
1
- import { m as AIUsageInfo, U as UIContext, aC as ReferenceImage, r as AIElementLocatorResponse, N as ElementById, g as InsightExtractOption, u as AIDataExtractionResponse, w as AIAssertionResponse, aw as PageType, W as PlanningAIResponse } from './types-93fa8419.js';
1
+ import { m as AIUsageInfo, U as UIContext, aE as ReferenceImage, r as AIElementLocatorResponse, N as ElementById, g as InsightExtractOption, u as AIDataExtractionResponse, w as AIAssertionResponse, ay as PageType, W as PlanningAIResponse } from './types-d187efec.js';
2
2
  import { Rect, ElementTreeNode, BaseElement } from '@midscene/shared/types';
3
3
  import { ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam } from 'openai/resources';
4
4
 
@@ -357,7 +357,7 @@ interface PlanningLocateParam extends DetailedLocateParam {
357
357
  }
358
358
  interface PlanningAction<ParamType = any> {
359
359
  thought?: string;
360
- type: 'Locate' | 'Tap' | 'RightClick' | 'Hover' | 'Drag' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'ExpectedFalsyCondition' | 'Assert' | 'AssertWithoutThrow' | 'Sleep' | 'Finished' | 'AndroidBackButton' | 'AndroidHomeButton' | 'AndroidRecentAppsButton';
360
+ type: 'Locate' | 'Tap' | 'RightClick' | 'Hover' | 'Drag' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'ExpectedFalsyCondition' | 'Assert' | 'AssertWithoutThrow' | 'Sleep' | 'Finished' | 'AndroidBackButton' | 'AndroidHomeButton' | 'AndroidRecentAppsButton' | 'AndroidLongPress' | 'AndroidPull';
361
361
  param: ParamType;
362
362
  locate?: PlanningLocateParam | null;
363
363
  }
@@ -393,6 +393,20 @@ interface PlanningActionParamError {
393
393
  type PlanningActionParamWaitFor = AgentWaitForOpt & {
394
394
  assertion: string;
395
395
  };
396
+ interface PlanningActionParamAndroidLongPress {
397
+ x: number;
398
+ y: number;
399
+ duration?: number;
400
+ }
401
+ interface PlanningActionParamAndroidPull {
402
+ direction: 'up' | 'down';
403
+ startPoint?: {
404
+ x: number;
405
+ y: number;
406
+ };
407
+ distance?: number;
408
+ duration?: number;
409
+ }
396
410
  /**
397
411
  * misc
398
412
  */
@@ -443,8 +457,7 @@ interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {
443
457
  }
444
458
  type ExecutionTask<E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<any, any, any>> = E & ExecutionTaskReturn<E extends ExecutionTaskApply<any, any, infer TaskOutput, any> ? TaskOutput : unknown, E extends ExecutionTaskApply<any, any, any, infer TaskLog> ? TaskLog : unknown> & {
445
459
  status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';
446
- error?: Error;
447
- errorMessage?: string;
460
+ error?: string;
448
461
  errorStack?: string;
449
462
  timing?: {
450
463
  start: number;
@@ -529,4 +542,4 @@ interface StreamingAIResponse {
529
542
  isStreamed: boolean;
530
543
  }
531
544
 
532
- export { type PlanningActionParamScroll as $, type AIDescribeElementResponse as A, type EnsureObject as B, type CallAIFn as C, type DumpSubscriber as D, type ExecutionTask as E, type InsightExtractParam as F, type LocateResultElement as G, type DumpMeta as H, type InsightAction as I, type InsightDump as J, type LiteUISection as K, type LocateResult as L, type MidsceneYamlScript as M, type ElementById as N, type OnTaskStartTip as O, type PartialInsightDumpFromSDK as P, type AgentWaitForOpt as Q, type ReportDumpWithAttributes as R, type AgentAssertOpt as S, type PlanningLocateParam as T, UIContext as U, type PlanningAction as V, type PlanningAIResponse as W, type PlanningActionParamTap as X, type PlanningActionParamHover as Y, type PlanningActionParamRightClick as Z, type PlanningActionParamInputOrKeyPress as _, type ExecutionTaskProgressOptions as a, type ScriptPlayerStatusValue as a$, type PlanningActionParamAssert as a0, type PlanningActionParamSleep as a1, type PlanningActionParamError as a2, type PlanningActionParamWaitFor as a3, type Color as a4, type BaseAgentParserOpt as a5, type PuppeteerParserOpt as a6, type PlaywrightParserOpt as a7, type ExecutionRecorderItem as a8, type ExecutionTaskType as a9, type StreamingAIResponse as aA, type LocateOption as aB, type ReferenceImage as aC, type scrollParam as aD, type MidsceneYamlScriptEnvBase as aE, type MidsceneYamlScriptWebEnv as aF, type MidsceneYamlScriptAndroidEnv as aG, type MidsceneYamlScriptEnv as aH, type MidsceneYamlFlowItemAIAction as aI, type MidsceneYamlFlowItemAIAssert as aJ, type MidsceneYamlFlowItemAIQuery as aK, type MidsceneYamlFlowItemAINumber as aL, type MidsceneYamlFlowItemAIString as aM, type MidsceneYamlFlowItemAIAsk as aN, type MidsceneYamlFlowItemAIBoolean as aO, type MidsceneYamlFlowItemAILocate as aP, type MidsceneYamlFlowItemAIWaitFor as aQ, type MidsceneYamlFlowItemAITap as aR, type MidsceneYamlFlowItemAIHover as aS, type MidsceneYamlFlowItemAIInput as aT, type MidsceneYamlFlowItemAIKeyboardPress as aU, type MidsceneYamlFlowItemAIScroll as aV, type MidsceneYamlFlowItemEvaluateJavaScript as aW, type MidsceneYamlFlowItemSleep as aX, type MidsceneYamlFlowItemLogScreenshot as aY, type FreeFn as aZ, type ScriptPlayerTaskStatus as a_, type ExecutorContext as aa, type ExecutionTaskHitBy as ab, type ExecutionTaskReturn as ac, type ExecutionTaskInsightLocateParam as ad, type ExecutionTaskInsightLocateOutput as ae, type ExecutionTaskInsightDumpLog as af, type ExecutionTaskInsightLocateApply as ag, type ExecutionTaskInsightLocate as ah, type ExecutionTaskInsightQueryParam as ai, type ExecutionTaskInsightQueryOutput as aj, type ExecutionTaskInsightQueryApply as ak, type ExecutionTaskInsightQuery as al, type ExecutionTaskInsightAssertionParam as am, type ExecutionTaskInsightAssertionApply as an, type ExecutionTaskInsightAssertion as ao, type ExecutionTaskActionApply as ap, type ExecutionTaskAction as aq, type ExecutionTaskLogApply as ar, type ExecutionTaskLog as as, type ExecutionTaskPlanningApply as at, type ExecutionTaskPlanning as au, type GroupedActionDump as av, type PageType as aw, type StreamingCodeGenerationOptions as ax, type StreamingCallback as ay, type CodeGenerationChunk as az, type ExecutionTaskApply as b, type MidsceneYamlConfig as b0, type MidsceneYamlConfigOutput as b1, type ExecutionDump as c, type InsightTaskInfo as d, type InsightOptions as e, type DetailedLocateParam as f, type InsightExtractOption as g, type InsightAssertionResponse as h, type MidsceneYamlTask as i, type MidsceneYamlFlowItem as j, type MidsceneYamlFlowItemAIRightClick as k, type MidsceneYamlConfigResult as l, type AIUsageInfo as m, AIResponseFormat as n, type AISingleElementResponseById as o, type AISingleElementResponseByPosition as p, type AISingleElementResponse as q, type AIElementLocatorResponse as r, type AIElementCoordinatesResponse as s, type AIElementResponse as t, type AIDataExtractionResponse as u, type AISectionLocatorResponse as v, type AIAssertionResponse as w, type LocatorValidatorOption as x, type LocateValidatorResult as y, type AgentDescribeElementAtPointResult as z };
545
+ export { type PlanningActionParamScroll as $, type AIDescribeElementResponse as A, type EnsureObject as B, type CallAIFn as C, type DumpSubscriber as D, type ExecutionTask as E, type InsightExtractParam as F, type LocateResultElement as G, type DumpMeta as H, type InsightAction as I, type InsightDump as J, type LiteUISection as K, type LocateResult as L, type MidsceneYamlScript as M, type ElementById as N, type OnTaskStartTip as O, type PartialInsightDumpFromSDK as P, type AgentWaitForOpt as Q, type ReportDumpWithAttributes as R, type AgentAssertOpt as S, type PlanningLocateParam as T, UIContext as U, type PlanningAction as V, type PlanningAIResponse as W, type PlanningActionParamTap as X, type PlanningActionParamHover as Y, type PlanningActionParamRightClick as Z, type PlanningActionParamInputOrKeyPress as _, type ExecutionTaskProgressOptions as a, type FreeFn as a$, type PlanningActionParamAssert as a0, type PlanningActionParamSleep as a1, type PlanningActionParamError as a2, type PlanningActionParamWaitFor as a3, type PlanningActionParamAndroidLongPress as a4, type PlanningActionParamAndroidPull as a5, type Color as a6, type BaseAgentParserOpt as a7, type PuppeteerParserOpt as a8, type PlaywrightParserOpt as a9, type StreamingCallback as aA, type CodeGenerationChunk as aB, type StreamingAIResponse as aC, type LocateOption as aD, type ReferenceImage as aE, type scrollParam as aF, type MidsceneYamlScriptEnvBase as aG, type MidsceneYamlScriptWebEnv as aH, type MidsceneYamlScriptAndroidEnv as aI, type MidsceneYamlScriptEnv as aJ, type MidsceneYamlFlowItemAIAction as aK, type MidsceneYamlFlowItemAIAssert as aL, type MidsceneYamlFlowItemAIQuery as aM, type MidsceneYamlFlowItemAINumber as aN, type MidsceneYamlFlowItemAIString as aO, type MidsceneYamlFlowItemAIAsk as aP, type MidsceneYamlFlowItemAIBoolean as aQ, type MidsceneYamlFlowItemAILocate as aR, type MidsceneYamlFlowItemAIWaitFor as aS, type MidsceneYamlFlowItemAITap as aT, type MidsceneYamlFlowItemAIHover as aU, type MidsceneYamlFlowItemAIInput as aV, type MidsceneYamlFlowItemAIKeyboardPress as aW, type MidsceneYamlFlowItemAIScroll as aX, type MidsceneYamlFlowItemEvaluateJavaScript as aY, type MidsceneYamlFlowItemSleep as aZ, type MidsceneYamlFlowItemLogScreenshot as a_, type ExecutionRecorderItem as aa, type ExecutionTaskType as ab, type ExecutorContext as ac, type ExecutionTaskHitBy as ad, type ExecutionTaskReturn as ae, type ExecutionTaskInsightLocateParam as af, type ExecutionTaskInsightLocateOutput as ag, type ExecutionTaskInsightDumpLog as ah, type ExecutionTaskInsightLocateApply as ai, type ExecutionTaskInsightLocate as aj, type ExecutionTaskInsightQueryParam as ak, type ExecutionTaskInsightQueryOutput as al, type ExecutionTaskInsightQueryApply as am, type ExecutionTaskInsightQuery as an, type ExecutionTaskInsightAssertionParam as ao, type ExecutionTaskInsightAssertionApply as ap, type ExecutionTaskInsightAssertion as aq, type ExecutionTaskActionApply as ar, type ExecutionTaskAction as as, type ExecutionTaskLogApply as at, type ExecutionTaskLog as au, type ExecutionTaskPlanningApply as av, type ExecutionTaskPlanning as aw, type GroupedActionDump as ax, type PageType as ay, type StreamingCodeGenerationOptions as az, type ExecutionTaskApply as b, type ScriptPlayerTaskStatus as b0, type ScriptPlayerStatusValue as b1, type MidsceneYamlConfig as b2, type MidsceneYamlConfigOutput as b3, type ExecutionDump as c, type InsightTaskInfo as d, type InsightOptions as e, type DetailedLocateParam as f, type InsightExtractOption as g, type InsightAssertionResponse as h, type MidsceneYamlTask as i, type MidsceneYamlFlowItem as j, type MidsceneYamlFlowItemAIRightClick as k, type MidsceneYamlConfigResult as l, type AIUsageInfo as m, AIResponseFormat as n, type AISingleElementResponseById as o, type AISingleElementResponseByPosition as p, type AISingleElementResponse as q, type AIElementLocatorResponse as r, type AIElementCoordinatesResponse as s, type AIElementResponse as t, type AIDataExtractionResponse as u, type AISectionLocatorResponse as v, type AIAssertionResponse as w, type LocatorValidatorOption as x, type LocateValidatorResult as y, type AgentDescribeElementAtPointResult as z };
@@ -1,4 +1,4 @@
1
- import { R as ReportDumpWithAttributes } from './types-93fa8419.js';
1
+ import { R as ReportDumpWithAttributes } from './types-d187efec.js';
2
2
  import { Rect } from '@midscene/shared/types';
3
3
  import '@midscene/shared/constants';
4
4
  import 'openai/resources';
package/dist/lib/utils.js CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
 
14
14
 
15
- var _chunkTYKJHDNKjs = require('./chunk-TYKJHDNK.js');
15
+ var _chunkXIVVQRBCjs = require('./chunk-XIVVQRBC.js');
16
16
 
17
17
 
18
18
 
@@ -27,4 +27,4 @@ var _chunkTYKJHDNKjs = require('./chunk-TYKJHDNK.js');
27
27
 
28
28
 
29
29
 
30
- exports.getTmpDir = _chunkTYKJHDNKjs.getTmpDir; exports.getTmpFile = _chunkTYKJHDNKjs.getTmpFile; exports.getVersion = _chunkTYKJHDNKjs.getVersion; exports.groupedActionDumpFileExt = _chunkTYKJHDNKjs.groupedActionDumpFileExt; exports.insertScriptBeforeClosingHtml = _chunkTYKJHDNKjs.insertScriptBeforeClosingHtml; exports.overlapped = _chunkTYKJHDNKjs.overlapped; exports.replacerForPageObject = _chunkTYKJHDNKjs.replacerForPageObject; exports.reportHTMLContent = _chunkTYKJHDNKjs.reportHTMLContent; exports.sleep = _chunkTYKJHDNKjs.sleep; exports.stringifyDumpData = _chunkTYKJHDNKjs.stringifyDumpData; exports.uploadTestInfoToServer = _chunkTYKJHDNKjs.uploadTestInfoToServer; exports.writeDumpReport = _chunkTYKJHDNKjs.writeDumpReport; exports.writeLogFile = _chunkTYKJHDNKjs.writeLogFile;
30
+ exports.getTmpDir = _chunkXIVVQRBCjs.getTmpDir; exports.getTmpFile = _chunkXIVVQRBCjs.getTmpFile; exports.getVersion = _chunkXIVVQRBCjs.getVersion; exports.groupedActionDumpFileExt = _chunkXIVVQRBCjs.groupedActionDumpFileExt; exports.insertScriptBeforeClosingHtml = _chunkXIVVQRBCjs.insertScriptBeforeClosingHtml; exports.overlapped = _chunkXIVVQRBCjs.overlapped; exports.replacerForPageObject = _chunkXIVVQRBCjs.replacerForPageObject; exports.reportHTMLContent = _chunkXIVVQRBCjs.reportHTMLContent; exports.sleep = _chunkXIVVQRBCjs.sleep; exports.stringifyDumpData = _chunkXIVVQRBCjs.stringifyDumpData; exports.uploadTestInfoToServer = _chunkXIVVQRBCjs.uploadTestInfoToServer; exports.writeDumpReport = _chunkXIVVQRBCjs.writeDumpReport; exports.writeLogFile = _chunkXIVVQRBCjs.writeLogFile;
@@ -1,9 +1,9 @@
1
- import { ay as StreamingCallback, m as AIUsageInfo, ax as StreamingCodeGenerationOptions, aA as StreamingAIResponse, V as PlanningAction, j as MidsceneYamlFlowItem } from './types-93fa8419.js';
1
+ import { aA as StreamingCallback, m as AIUsageInfo, az as StreamingCodeGenerationOptions, aC as StreamingAIResponse, V as PlanningAction, j as MidsceneYamlFlowItem } from './types-d187efec.js';
2
2
  import OpenAI from 'openai';
3
3
  import { ChatCompletionMessageParam } from 'openai/resources';
4
4
  export { ChatCompletionMessageParam } from 'openai/resources';
5
- import { b as AIActionType } from './llm-planning-4bc82162.js';
6
- export { a as AiAssert, f as AiExtractElementInfo, A as AiLocateElement, g as AiLocateSection, h as adaptBboxToRect, c as callAiFn, d as describeUserPage, e as elementByPositionWithElementInfo, p as plan } from './llm-planning-4bc82162.js';
5
+ import { b as AIActionType } from './llm-planning-ae19dc49.js';
6
+ export { a as AiAssert, f as AiExtractElementInfo, A as AiLocateElement, g as AiLocateSection, h as adaptBboxToRect, c as callAiFn, d as describeUserPage, e as elementByPositionWithElementInfo, p as plan } from './llm-planning-ae19dc49.js';
7
7
  import { vlLocateMode } from '@midscene/shared/env';
8
8
  import { actionParser } from '@ui-tars/action-parser';
9
9
  import { Size } from '@midscene/shared/types';
@@ -1,7 +1,7 @@
1
- import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightTaskInfo, e as InsightOptions, f as DetailedLocateParam, L as LocateResult, g as InsightExtractOption, h as InsightAssertionResponse, A as AIDescribeElementResponse } from './types-93fa8419.js';
2
- export { w as AIAssertionResponse, u as AIDataExtractionResponse, s as AIElementCoordinatesResponse, r as AIElementLocatorResponse, t as AIElementResponse, n as AIResponseFormat, v as AISectionLocatorResponse, q as AISingleElementResponse, o as AISingleElementResponseById, p as AISingleElementResponseByPosition, m as AIUsageInfo, S as AgentAssertOpt, z as AgentDescribeElementAtPointResult, Q as AgentWaitForOpt, a5 as BaseAgentParserOpt, C as CallAIFn, az as CodeGenerationChunk, a4 as Color, H as DumpMeta, N as ElementById, B as EnsureObject, a8 as ExecutionRecorderItem, aq as ExecutionTaskAction, ap as ExecutionTaskActionApply, ab as ExecutionTaskHitBy, ao as ExecutionTaskInsightAssertion, an as ExecutionTaskInsightAssertionApply, am as ExecutionTaskInsightAssertionParam, af as ExecutionTaskInsightDumpLog, ah as ExecutionTaskInsightLocate, ag as ExecutionTaskInsightLocateApply, ae as ExecutionTaskInsightLocateOutput, ad as ExecutionTaskInsightLocateParam, al as ExecutionTaskInsightQuery, ak as ExecutionTaskInsightQueryApply, aj as ExecutionTaskInsightQueryOutput, ai as ExecutionTaskInsightQueryParam, as as ExecutionTaskLog, ar as ExecutionTaskLogApply, au as ExecutionTaskPlanning, at as ExecutionTaskPlanningApply, ac as ExecutionTaskReturn, a9 as ExecutionTaskType, aa as ExecutorContext, aZ as FreeFn, av as GroupedActionDump, J as InsightDump, F as InsightExtractParam, K as LiteUISection, aB as LocateOption, G as LocateResultElement, y as LocateValidatorResult, x as LocatorValidatorOption, b0 as MidsceneYamlConfig, b1 as MidsceneYamlConfigOutput, l as MidsceneYamlConfigResult, j as MidsceneYamlFlowItem, aI as MidsceneYamlFlowItemAIAction, aN as MidsceneYamlFlowItemAIAsk, aJ as MidsceneYamlFlowItemAIAssert, aO as MidsceneYamlFlowItemAIBoolean, aS as MidsceneYamlFlowItemAIHover, aT as MidsceneYamlFlowItemAIInput, aU as MidsceneYamlFlowItemAIKeyboardPress, aP as MidsceneYamlFlowItemAILocate, aL as MidsceneYamlFlowItemAINumber, aK as MidsceneYamlFlowItemAIQuery, k as MidsceneYamlFlowItemAIRightClick, aV as MidsceneYamlFlowItemAIScroll, aM as MidsceneYamlFlowItemAIString, aR as MidsceneYamlFlowItemAITap, aQ as MidsceneYamlFlowItemAIWaitFor, aW as MidsceneYamlFlowItemEvaluateJavaScript, aY as MidsceneYamlFlowItemLogScreenshot, aX as MidsceneYamlFlowItemSleep, M as MidsceneYamlScript, aG as MidsceneYamlScriptAndroidEnv, aH as MidsceneYamlScriptEnv, aE as MidsceneYamlScriptEnvBase, aF as MidsceneYamlScriptWebEnv, i as MidsceneYamlTask, O as OnTaskStartTip, aw as PageType, P as PartialInsightDumpFromSDK, W as PlanningAIResponse, V as PlanningAction, a0 as PlanningActionParamAssert, a2 as PlanningActionParamError, Y as PlanningActionParamHover, _ as PlanningActionParamInputOrKeyPress, Z as PlanningActionParamRightClick, $ as PlanningActionParamScroll, a1 as PlanningActionParamSleep, X as PlanningActionParamTap, a3 as PlanningActionParamWaitFor, T as PlanningLocateParam, a7 as PlaywrightParserOpt, a6 as PuppeteerParserOpt, aC as ReferenceImage, R as ReportDumpWithAttributes, a$ as ScriptPlayerStatusValue, a_ as ScriptPlayerTaskStatus, aA as StreamingAIResponse, ay as StreamingCallback, ax as StreamingCodeGenerationOptions, aD as scrollParam } from './types-93fa8419.js';
3
- import { c as callAiFn } from './llm-planning-4bc82162.js';
4
- export { a as AiAssert, A as AiLocateElement, d as describeUserPage, p as plan } from './llm-planning-4bc82162.js';
1
+ import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightTaskInfo, e as InsightOptions, f as DetailedLocateParam, L as LocateResult, g as InsightExtractOption, h as InsightAssertionResponse, A as AIDescribeElementResponse } from './types-d187efec.js';
2
+ export { w as AIAssertionResponse, u as AIDataExtractionResponse, s as AIElementCoordinatesResponse, r as AIElementLocatorResponse, t as AIElementResponse, n as AIResponseFormat, v as AISectionLocatorResponse, q as AISingleElementResponse, o as AISingleElementResponseById, p as AISingleElementResponseByPosition, m as AIUsageInfo, S as AgentAssertOpt, z as AgentDescribeElementAtPointResult, Q as AgentWaitForOpt, a7 as BaseAgentParserOpt, C as CallAIFn, aB as CodeGenerationChunk, a6 as Color, H as DumpMeta, N as ElementById, B as EnsureObject, aa as ExecutionRecorderItem, as as ExecutionTaskAction, ar as ExecutionTaskActionApply, ad as ExecutionTaskHitBy, aq as ExecutionTaskInsightAssertion, ap as ExecutionTaskInsightAssertionApply, ao as ExecutionTaskInsightAssertionParam, ah as ExecutionTaskInsightDumpLog, aj as ExecutionTaskInsightLocate, ai as ExecutionTaskInsightLocateApply, ag as ExecutionTaskInsightLocateOutput, af as ExecutionTaskInsightLocateParam, an as ExecutionTaskInsightQuery, am as ExecutionTaskInsightQueryApply, al as ExecutionTaskInsightQueryOutput, ak as ExecutionTaskInsightQueryParam, au as ExecutionTaskLog, at as ExecutionTaskLogApply, aw as ExecutionTaskPlanning, av as ExecutionTaskPlanningApply, ae as ExecutionTaskReturn, ab as ExecutionTaskType, ac as ExecutorContext, a$ as FreeFn, ax as GroupedActionDump, J as InsightDump, F as InsightExtractParam, K as LiteUISection, aD as LocateOption, G as LocateResultElement, y as LocateValidatorResult, x as LocatorValidatorOption, b2 as MidsceneYamlConfig, b3 as MidsceneYamlConfigOutput, l as MidsceneYamlConfigResult, j as MidsceneYamlFlowItem, aK as MidsceneYamlFlowItemAIAction, aP as MidsceneYamlFlowItemAIAsk, aL as MidsceneYamlFlowItemAIAssert, aQ as MidsceneYamlFlowItemAIBoolean, aU as MidsceneYamlFlowItemAIHover, aV as MidsceneYamlFlowItemAIInput, aW as MidsceneYamlFlowItemAIKeyboardPress, aR as MidsceneYamlFlowItemAILocate, aN as MidsceneYamlFlowItemAINumber, aM as MidsceneYamlFlowItemAIQuery, k as MidsceneYamlFlowItemAIRightClick, aX as MidsceneYamlFlowItemAIScroll, aO as MidsceneYamlFlowItemAIString, aT as MidsceneYamlFlowItemAITap, aS as MidsceneYamlFlowItemAIWaitFor, aY as MidsceneYamlFlowItemEvaluateJavaScript, a_ as MidsceneYamlFlowItemLogScreenshot, aZ as MidsceneYamlFlowItemSleep, M as MidsceneYamlScript, aI as MidsceneYamlScriptAndroidEnv, aJ as MidsceneYamlScriptEnv, aG as MidsceneYamlScriptEnvBase, aH as MidsceneYamlScriptWebEnv, i as MidsceneYamlTask, O as OnTaskStartTip, ay as PageType, P as PartialInsightDumpFromSDK, W as PlanningAIResponse, V as PlanningAction, a4 as PlanningActionParamAndroidLongPress, a5 as PlanningActionParamAndroidPull, a0 as PlanningActionParamAssert, a2 as PlanningActionParamError, Y as PlanningActionParamHover, _ as PlanningActionParamInputOrKeyPress, Z as PlanningActionParamRightClick, $ as PlanningActionParamScroll, a1 as PlanningActionParamSleep, X as PlanningActionParamTap, a3 as PlanningActionParamWaitFor, T as PlanningLocateParam, a9 as PlaywrightParserOpt, a8 as PuppeteerParserOpt, aE as ReferenceImage, R as ReportDumpWithAttributes, b1 as ScriptPlayerStatusValue, b0 as ScriptPlayerTaskStatus, aC as StreamingAIResponse, aA as StreamingCallback, az as StreamingCodeGenerationOptions, aF as scrollParam } from './types-d187efec.js';
3
+ import { c as callAiFn } from './llm-planning-ae19dc49.js';
4
+ export { a as AiAssert, A as AiLocateElement, d as describeUserPage, p as plan } from './llm-planning-ae19dc49.js';
5
5
  import { BaseElement, Rect } from '@midscene/shared/types';
6
6
  export { BaseElement, ElementTreeNode, Point, Rect, Size } from '@midscene/shared/types';
7
7
  export { getVersion } from './utils.js';
@@ -1,4 +1,4 @@
1
- import { m as AIUsageInfo, U as UIContext, aC as ReferenceImage, r as AIElementLocatorResponse, N as ElementById, g as InsightExtractOption, u as AIDataExtractionResponse, w as AIAssertionResponse, aw as PageType, W as PlanningAIResponse } from './types-93fa8419.js';
1
+ import { m as AIUsageInfo, U as UIContext, aE as ReferenceImage, r as AIElementLocatorResponse, N as ElementById, g as InsightExtractOption, u as AIDataExtractionResponse, w as AIAssertionResponse, ay as PageType, W as PlanningAIResponse } from './types-d187efec.js';
2
2
  import { Rect, ElementTreeNode, BaseElement } from '@midscene/shared/types';
3
3
  import { ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam } from 'openai/resources';
4
4
 
@@ -357,7 +357,7 @@ interface PlanningLocateParam extends DetailedLocateParam {
357
357
  }
358
358
  interface PlanningAction<ParamType = any> {
359
359
  thought?: string;
360
- type: 'Locate' | 'Tap' | 'RightClick' | 'Hover' | 'Drag' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'ExpectedFalsyCondition' | 'Assert' | 'AssertWithoutThrow' | 'Sleep' | 'Finished' | 'AndroidBackButton' | 'AndroidHomeButton' | 'AndroidRecentAppsButton';
360
+ type: 'Locate' | 'Tap' | 'RightClick' | 'Hover' | 'Drag' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'ExpectedFalsyCondition' | 'Assert' | 'AssertWithoutThrow' | 'Sleep' | 'Finished' | 'AndroidBackButton' | 'AndroidHomeButton' | 'AndroidRecentAppsButton' | 'AndroidLongPress' | 'AndroidPull';
361
361
  param: ParamType;
362
362
  locate?: PlanningLocateParam | null;
363
363
  }
@@ -393,6 +393,20 @@ interface PlanningActionParamError {
393
393
  type PlanningActionParamWaitFor = AgentWaitForOpt & {
394
394
  assertion: string;
395
395
  };
396
+ interface PlanningActionParamAndroidLongPress {
397
+ x: number;
398
+ y: number;
399
+ duration?: number;
400
+ }
401
+ interface PlanningActionParamAndroidPull {
402
+ direction: 'up' | 'down';
403
+ startPoint?: {
404
+ x: number;
405
+ y: number;
406
+ };
407
+ distance?: number;
408
+ duration?: number;
409
+ }
396
410
  /**
397
411
  * misc
398
412
  */
@@ -443,8 +457,7 @@ interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {
443
457
  }
444
458
  type ExecutionTask<E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<any, any, any>> = E & ExecutionTaskReturn<E extends ExecutionTaskApply<any, any, infer TaskOutput, any> ? TaskOutput : unknown, E extends ExecutionTaskApply<any, any, any, infer TaskLog> ? TaskLog : unknown> & {
445
459
  status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';
446
- error?: Error;
447
- errorMessage?: string;
460
+ error?: string;
448
461
  errorStack?: string;
449
462
  timing?: {
450
463
  start: number;
@@ -529,4 +542,4 @@ interface StreamingAIResponse {
529
542
  isStreamed: boolean;
530
543
  }
531
544
 
532
- export { type PlanningActionParamScroll as $, type AIDescribeElementResponse as A, type EnsureObject as B, type CallAIFn as C, type DumpSubscriber as D, type ExecutionTask as E, type InsightExtractParam as F, type LocateResultElement as G, type DumpMeta as H, type InsightAction as I, type InsightDump as J, type LiteUISection as K, type LocateResult as L, type MidsceneYamlScript as M, type ElementById as N, type OnTaskStartTip as O, type PartialInsightDumpFromSDK as P, type AgentWaitForOpt as Q, type ReportDumpWithAttributes as R, type AgentAssertOpt as S, type PlanningLocateParam as T, UIContext as U, type PlanningAction as V, type PlanningAIResponse as W, type PlanningActionParamTap as X, type PlanningActionParamHover as Y, type PlanningActionParamRightClick as Z, type PlanningActionParamInputOrKeyPress as _, type ExecutionTaskProgressOptions as a, type ScriptPlayerStatusValue as a$, type PlanningActionParamAssert as a0, type PlanningActionParamSleep as a1, type PlanningActionParamError as a2, type PlanningActionParamWaitFor as a3, type Color as a4, type BaseAgentParserOpt as a5, type PuppeteerParserOpt as a6, type PlaywrightParserOpt as a7, type ExecutionRecorderItem as a8, type ExecutionTaskType as a9, type StreamingAIResponse as aA, type LocateOption as aB, type ReferenceImage as aC, type scrollParam as aD, type MidsceneYamlScriptEnvBase as aE, type MidsceneYamlScriptWebEnv as aF, type MidsceneYamlScriptAndroidEnv as aG, type MidsceneYamlScriptEnv as aH, type MidsceneYamlFlowItemAIAction as aI, type MidsceneYamlFlowItemAIAssert as aJ, type MidsceneYamlFlowItemAIQuery as aK, type MidsceneYamlFlowItemAINumber as aL, type MidsceneYamlFlowItemAIString as aM, type MidsceneYamlFlowItemAIAsk as aN, type MidsceneYamlFlowItemAIBoolean as aO, type MidsceneYamlFlowItemAILocate as aP, type MidsceneYamlFlowItemAIWaitFor as aQ, type MidsceneYamlFlowItemAITap as aR, type MidsceneYamlFlowItemAIHover as aS, type MidsceneYamlFlowItemAIInput as aT, type MidsceneYamlFlowItemAIKeyboardPress as aU, type MidsceneYamlFlowItemAIScroll as aV, type MidsceneYamlFlowItemEvaluateJavaScript as aW, type MidsceneYamlFlowItemSleep as aX, type MidsceneYamlFlowItemLogScreenshot as aY, type FreeFn as aZ, type ScriptPlayerTaskStatus as a_, type ExecutorContext as aa, type ExecutionTaskHitBy as ab, type ExecutionTaskReturn as ac, type ExecutionTaskInsightLocateParam as ad, type ExecutionTaskInsightLocateOutput as ae, type ExecutionTaskInsightDumpLog as af, type ExecutionTaskInsightLocateApply as ag, type ExecutionTaskInsightLocate as ah, type ExecutionTaskInsightQueryParam as ai, type ExecutionTaskInsightQueryOutput as aj, type ExecutionTaskInsightQueryApply as ak, type ExecutionTaskInsightQuery as al, type ExecutionTaskInsightAssertionParam as am, type ExecutionTaskInsightAssertionApply as an, type ExecutionTaskInsightAssertion as ao, type ExecutionTaskActionApply as ap, type ExecutionTaskAction as aq, type ExecutionTaskLogApply as ar, type ExecutionTaskLog as as, type ExecutionTaskPlanningApply as at, type ExecutionTaskPlanning as au, type GroupedActionDump as av, type PageType as aw, type StreamingCodeGenerationOptions as ax, type StreamingCallback as ay, type CodeGenerationChunk as az, type ExecutionTaskApply as b, type MidsceneYamlConfig as b0, type MidsceneYamlConfigOutput as b1, type ExecutionDump as c, type InsightTaskInfo as d, type InsightOptions as e, type DetailedLocateParam as f, type InsightExtractOption as g, type InsightAssertionResponse as h, type MidsceneYamlTask as i, type MidsceneYamlFlowItem as j, type MidsceneYamlFlowItemAIRightClick as k, type MidsceneYamlConfigResult as l, type AIUsageInfo as m, AIResponseFormat as n, type AISingleElementResponseById as o, type AISingleElementResponseByPosition as p, type AISingleElementResponse as q, type AIElementLocatorResponse as r, type AIElementCoordinatesResponse as s, type AIElementResponse as t, type AIDataExtractionResponse as u, type AISectionLocatorResponse as v, type AIAssertionResponse as w, type LocatorValidatorOption as x, type LocateValidatorResult as y, type AgentDescribeElementAtPointResult as z };
545
+ export { type PlanningActionParamScroll as $, type AIDescribeElementResponse as A, type EnsureObject as B, type CallAIFn as C, type DumpSubscriber as D, type ExecutionTask as E, type InsightExtractParam as F, type LocateResultElement as G, type DumpMeta as H, type InsightAction as I, type InsightDump as J, type LiteUISection as K, type LocateResult as L, type MidsceneYamlScript as M, type ElementById as N, type OnTaskStartTip as O, type PartialInsightDumpFromSDK as P, type AgentWaitForOpt as Q, type ReportDumpWithAttributes as R, type AgentAssertOpt as S, type PlanningLocateParam as T, UIContext as U, type PlanningAction as V, type PlanningAIResponse as W, type PlanningActionParamTap as X, type PlanningActionParamHover as Y, type PlanningActionParamRightClick as Z, type PlanningActionParamInputOrKeyPress as _, type ExecutionTaskProgressOptions as a, type FreeFn as a$, type PlanningActionParamAssert as a0, type PlanningActionParamSleep as a1, type PlanningActionParamError as a2, type PlanningActionParamWaitFor as a3, type PlanningActionParamAndroidLongPress as a4, type PlanningActionParamAndroidPull as a5, type Color as a6, type BaseAgentParserOpt as a7, type PuppeteerParserOpt as a8, type PlaywrightParserOpt as a9, type StreamingCallback as aA, type CodeGenerationChunk as aB, type StreamingAIResponse as aC, type LocateOption as aD, type ReferenceImage as aE, type scrollParam as aF, type MidsceneYamlScriptEnvBase as aG, type MidsceneYamlScriptWebEnv as aH, type MidsceneYamlScriptAndroidEnv as aI, type MidsceneYamlScriptEnv as aJ, type MidsceneYamlFlowItemAIAction as aK, type MidsceneYamlFlowItemAIAssert as aL, type MidsceneYamlFlowItemAIQuery as aM, type MidsceneYamlFlowItemAINumber as aN, type MidsceneYamlFlowItemAIString as aO, type MidsceneYamlFlowItemAIAsk as aP, type MidsceneYamlFlowItemAIBoolean as aQ, type MidsceneYamlFlowItemAILocate as aR, type MidsceneYamlFlowItemAIWaitFor as aS, type MidsceneYamlFlowItemAITap as aT, type MidsceneYamlFlowItemAIHover as aU, type MidsceneYamlFlowItemAIInput as aV, type MidsceneYamlFlowItemAIKeyboardPress as aW, type MidsceneYamlFlowItemAIScroll as aX, type MidsceneYamlFlowItemEvaluateJavaScript as aY, type MidsceneYamlFlowItemSleep as aZ, type MidsceneYamlFlowItemLogScreenshot as a_, type ExecutionRecorderItem as aa, type ExecutionTaskType as ab, type ExecutorContext as ac, type ExecutionTaskHitBy as ad, type ExecutionTaskReturn as ae, type ExecutionTaskInsightLocateParam as af, type ExecutionTaskInsightLocateOutput as ag, type ExecutionTaskInsightDumpLog as ah, type ExecutionTaskInsightLocateApply as ai, type ExecutionTaskInsightLocate as aj, type ExecutionTaskInsightQueryParam as ak, type ExecutionTaskInsightQueryOutput as al, type ExecutionTaskInsightQueryApply as am, type ExecutionTaskInsightQuery as an, type ExecutionTaskInsightAssertionParam as ao, type ExecutionTaskInsightAssertionApply as ap, type ExecutionTaskInsightAssertion as aq, type ExecutionTaskActionApply as ar, type ExecutionTaskAction as as, type ExecutionTaskLogApply as at, type ExecutionTaskLog as au, type ExecutionTaskPlanningApply as av, type ExecutionTaskPlanning as aw, type GroupedActionDump as ax, type PageType as ay, type StreamingCodeGenerationOptions as az, type ExecutionTaskApply as b, type ScriptPlayerTaskStatus as b0, type ScriptPlayerStatusValue as b1, type MidsceneYamlConfig as b2, type MidsceneYamlConfigOutput as b3, type ExecutionDump as c, type InsightTaskInfo as d, type InsightOptions as e, type DetailedLocateParam as f, type InsightExtractOption as g, type InsightAssertionResponse as h, type MidsceneYamlTask as i, type MidsceneYamlFlowItem as j, type MidsceneYamlFlowItemAIRightClick as k, type MidsceneYamlConfigResult as l, type AIUsageInfo as m, AIResponseFormat as n, type AISingleElementResponseById as o, type AISingleElementResponseByPosition as p, type AISingleElementResponse as q, type AIElementLocatorResponse as r, type AIElementCoordinatesResponse as s, type AIElementResponse as t, type AIDataExtractionResponse as u, type AISectionLocatorResponse as v, type AIAssertionResponse as w, type LocatorValidatorOption as x, type LocateValidatorResult as y, type AgentDescribeElementAtPointResult as z };
@@ -1,4 +1,4 @@
1
- import { R as ReportDumpWithAttributes } from './types-93fa8419.js';
1
+ import { R as ReportDumpWithAttributes } from './types-d187efec.js';
2
2
  import { Rect } from '@midscene/shared/types';
3
3
  import '@midscene/shared/constants';
4
4
  import 'openai/resources';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@midscene/core",
3
3
  "description": "Automate browser actions, extract data, and perform assertions using AI. It offers JavaScript SDK, Chrome extension, and support for scripting in YAML. See https://midscenejs.com/ for details.",
4
- "version": "0.24.2-beta-20250731102409.0",
4
+ "version": "0.24.2-beta-20250731125910.0",
5
5
  "repository": "https://github.com/web-infra-dev/midscene",
6
6
  "homepage": "https://midscenejs.com/",
7
7
  "jsnext:source": "./src/index.ts",
@@ -44,8 +44,8 @@
44
44
  "langsmith": "0.3.7",
45
45
  "openai": "4.81.0",
46
46
  "socks-proxy-agent": "8.0.4",
47
- "@midscene/recorder": "0.24.2-beta-20250731102409.0",
48
- "@midscene/shared": "0.24.2-beta-20250731102409.0"
47
+ "@midscene/recorder": "0.24.2-beta-20250731125910.0",
48
+ "@midscene/shared": "0.24.2-beta-20250731125910.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@modern-js/module-tools": "2.60.6",