misoai-web 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/agent.js +1 -1
- package/dist/es/agent.js.map +1 -1
- package/dist/es/bridge-mode-browser.js +3 -3
- package/dist/es/bridge-mode.js +3 -3
- package/dist/es/bridge-mode.js.map +1 -1
- package/dist/es/chrome-extension.js +2 -2
- package/dist/es/chrome-extension.js.map +1 -1
- package/dist/es/index.js +1 -1
- package/dist/es/index.js.map +1 -1
- package/dist/es/midscene-playground.js +1 -1
- package/dist/es/midscene-playground.js.map +1 -1
- package/dist/es/playground.js +1 -1
- package/dist/es/playground.js.map +1 -1
- package/dist/es/playwright.js +1 -1
- package/dist/es/playwright.js.map +1 -1
- package/dist/es/puppeteer-agent-launcher.js +1 -1
- package/dist/es/puppeteer-agent-launcher.js.map +1 -1
- package/dist/es/puppeteer.js +1 -1
- package/dist/es/puppeteer.js.map +1 -1
- package/dist/lib/agent.js +1 -1
- package/dist/lib/agent.js.map +1 -1
- package/dist/lib/bridge-mode-browser.js +3 -3
- package/dist/lib/bridge-mode.js +3 -3
- package/dist/lib/bridge-mode.js.map +1 -1
- package/dist/lib/chrome-extension.js +2 -2
- package/dist/lib/chrome-extension.js.map +1 -1
- package/dist/lib/index.js +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/midscene-playground.js +1 -1
- package/dist/lib/midscene-playground.js.map +1 -1
- package/dist/lib/playground.js +1 -1
- package/dist/lib/playground.js.map +1 -1
- package/dist/lib/playwright.js +1 -1
- package/dist/lib/playwright.js.map +1 -1
- package/dist/lib/puppeteer-agent-launcher.js +1 -1
- package/dist/lib/puppeteer-agent-launcher.js.map +1 -1
- package/dist/lib/puppeteer.js +1 -1
- package/dist/lib/puppeteer.js.map +1 -1
- package/package.json +2 -2
package/dist/lib/agent.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;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OAAO,eAAe,IAAI,WAAS;AAAA,QACxC,MAAM;AAAA,QACN,SAAS,KAAK;AAAA,QACd,QAAQ,KAAK;AAAA,QACb,OAAO,KAAK,OAAO;AAAA,MACrB,EAAE;AAAA,IACJ;AAEA,QAAI,OAAO,WAAW,SAAS;AAC7B,YAAM,SAAS,OAAO,eACnB,OAAO,CAAC,SAAS,KAAK,WAAW,OAAO,EACxC,IAAI,CAAC,SAAS;AACb,eAAO,UAAU,KAAK,IAAI,KAAK,KAAK,OAAO,OAAO;AAAA,MACpD,CAAC,EACA,KAAK,IAAI;AACZ,YAAM,IAAI,MAAM;AAAA,EAA8C,MAAM,EAAE;AAAA,IACxE;AAEA,WAAO;AAAA,MACL,QAAQ,OAAO;AAAA,MACf;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,mBAAmB,QAA8B;AACrD;AAAA,MACE,KAAK,KAAK;AAAA,MACV;AAAA,IACF;AACA,QAAI,KAAK,KAAK,oBAAoB;AAChC,aAAO,KAAK,KAAK,mBAAmB,MAAM;AAAA,IAC5C;AACA,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AAAA,EAEA,MAAM,UAAU;AACd,UAAM,KAAK,KAAK,QAAQ;AAAA,EAC1B;AACF","names":["import_misoai_core","import_js_yaml","resolve","import_utils","yaml","import_constants","import_env","import_logger","import_ai_model","dayjs","plan","element","log","sleep","debug","locatePlan","import_node_fs","import_node_path","import_common","assert","semver","executor","metadata"],"ignoreList":[],"sources":["../../src/common/agent.ts","../../src/yaml/player.ts","../../src/yaml/builder.ts","../../src/yaml/utils.ts","../../src/common/tasks.ts","../../src/common/ui-utils.ts","../../src/common/utils.ts","../../src/web-element.ts","../../src/common/plan-builder.ts","../../src/common/task-cache.ts","../../package.json"],"sourcesContent":["import type { WebPage } from '@/common/page';\nimport type {\n AgentAssertOpt,\n AgentDescribeElementAtPointResult,\n AgentWaitForOpt,\n AICaptchaResponse,\n AIUsageInfo,\n DetailedLocateParam,\n ExecutionDump,\n ExecutionTask,\n Executor,\n GroupedActionDump,\n InsightAction,\n LocateOption,\n LocateResultElement,\n LocateValidatorResult,\n LocatorValidatorOption,\n OnTaskStartTip,\n PlanningActionParamScroll,\n Rect,\n} from 'misoai-core';\nimport { Insight } from 'misoai-core';\n\n/**\n * Metadata for AI task execution\n */\nexport interface AITaskMetadata {\n /** Status of the task (pending, running, finished, failed, cancelled) */\n status?: string;\n /** Timestamp when the task started */\n start?: number;\n /** Timestamp when the task ended */\n end?: number;\n /** Total time taken to execute the task in milliseconds */\n totalTime?: number;\n /** Cache information */\n cache?: { hit: boolean };\n /** Token usage information */\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n [key: string]: any;\n };\n /** DeepThink information */\n deepthink?: {\n used: boolean;\n mode: string;\n [key: string]: any;\n };\n /** AI's thought process */\n thought?: string;\n /** Element location information */\n locate?: any;\n /** Action plans */\n plan?: any;\n /** Planning information */\n planning?: {\n type: string;\n description: string;\n steps: string[];\n };\n /** Insight information */\n insight?: {\n type: string;\n description: string;\n elements: string[];\n };\n /** Action information */\n action?: {\n type: string;\n description: string;\n result: any;\n };\n /** Action details */\n actionDetails?: Array<{\n type: string;\n subType?: string;\n status: string;\n thought?: string;\n }>;\n /** Task details */\n tasks?: Array<{\n type: string;\n subType?: string;\n status: string;\n thought?: string;\n locate?: any;\n timing?: any;\n usage?: any;\n cache?: any;\n error?: string;\n }>;\n}\n\n/**\n * Result of an AI task with metadata\n */\nexport interface AITaskResult<T = any> {\n /** The actual result of the operation */\n result: T;\n /** Metadata about the task execution */\n metadata: AITaskMetadata;\n}\n\nimport yaml from 'js-yaml';\n\nimport { ScriptPlayer, parseYamlScript } from '@/yaml/index';\nimport {\n groupedActionDumpFileExt,\n reportHTMLContent,\n stringifyDumpData,\n writeLogFile,\n} from 'misoai-core/utils';\nimport {\n DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT,\n DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT,\n} from 'misoai-shared/constants';\nimport { getAIConfigInBoolean, vlLocateMode } from 'misoai-shared/env';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\nimport { PageTaskExecutor } from '../common/tasks';\nimport type { PuppeteerWebPage } from '../puppeteer';\nimport type { WebElementInfo } from '../web-element';\nimport { buildPlans } from './plan-builder';\nimport { TaskCache } from './task-cache';\nimport {\n locateParamStr,\n paramStr,\n scrollParamStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport { printReportMsg, reportFileName } from './utils';\nimport { type WebUIContext, parseContextFromWebPage } from './utils';\n\nconst debug = getDebug('web-integration');\n\nconst distanceOfTwoPoints = (p1: [number, number], p2: [number, number]) => {\n const [x1, y1] = p1;\n const [x2, y2] = p2;\n return Math.round(Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2));\n};\n\nconst includedInRect = (point: [number, number], rect: Rect) => {\n const [x, y] = point;\n const { left, top, width, height } = rect;\n return x >= left && x <= left + width && y >= top && y <= top + height;\n};\n\nexport interface PageAgentOpt {\n forceSameTabNavigation?: boolean /* if limit the new tab to the current page, default true */;\n testId?: string;\n cacheId?: string;\n groupName?: string;\n groupDescription?: string;\n /* if auto generate report, default true */\n generateReport?: boolean;\n /* if auto print report msg, default true */\n autoPrintReportMsg?: boolean;\n onTaskStartTip?: OnTaskStartTip;\n aiActionContext?: string;\n waitForNavigationTimeout?: number;\n waitForNetworkIdleTimeout?: number;\n}\n\nexport class PageAgent<PageType extends WebPage = WebPage> {\n page: PageType;\n\n insight: Insight<WebElementInfo, WebUIContext>;\n\n dump: GroupedActionDump;\n\n reportFile?: string | null;\n\n reportFileName?: string;\n\n taskExecutor: PageTaskExecutor;\n\n opts: PageAgentOpt;\n\n /**\n * If true, the agent will not perform any actions\n */\n dryMode = false;\n\n onTaskStartTip?: OnTaskStartTip;\n\n taskCache?: TaskCache;\n\n constructor(page: PageType, opts?: PageAgentOpt) {\n this.page = page;\n this.opts = Object.assign(\n {\n generateReport: true,\n autoPrintReportMsg: true,\n groupName: 'Midscene Report',\n groupDescription: '',\n },\n opts || {},\n );\n\n if (\n this.page.pageType === 'puppeteer' ||\n this.page.pageType === 'playwright'\n ) {\n (this.page as PuppeteerWebPage).waitForNavigationTimeout =\n this.opts.waitForNavigationTimeout ||\n DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT;\n (this.page as PuppeteerWebPage).waitForNetworkIdleTimeout =\n this.opts.waitForNetworkIdleTimeout ||\n DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT;\n }\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n // get the parent browser of the puppeteer page\n // const browser = (this.page as PuppeteerWebPage).browser();\n\n this.insight = new Insight<WebElementInfo, WebUIContext>(\n async (action: InsightAction) => {\n return this.getUIContext(action);\n },\n );\n\n if (opts?.cacheId && this.page.pageType !== 'android') {\n this.taskCache = new TaskCache(\n opts.cacheId,\n getAIConfigInBoolean('MIDSCENE_CACHE'), // if we should use cache to match the element\n );\n }\n\n this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n });\n this.dump = this.resetDump();\n this.reportFileName = reportFileName(\n opts?.testId || this.page.pageType || 'web',\n );\n }\n\n async getUIContext(action?: InsightAction): Promise<WebUIContext> {\n if (action && (action === 'extract' || action === 'assert' || action === 'captcha')) {\n return await parseContextFromWebPage(this.page, {\n ignoreMarker: true,\n });\n }\n return await parseContextFromWebPage(this.page, {\n ignoreMarker: !!vlLocateMode(),\n });\n }\n\n // Helper method to call the insight.captcha method\n private async _callInsightCaptcha(options?: { deepThink?: boolean }): Promise<{ content: AICaptchaResponse; usage?: AIUsageInfo; deepThink?: boolean }> {\n // This is a workaround for TypeScript type checking\n // We know that insight.captcha exists because we added it\n const context = await this.getUIContext();\n\n // Include the current page URL in the context for better CAPTCHA analysis\n if (this.page.url) {\n const url = await this.page.url();\n context.url = url;\n }\n\n return (this.insight as any).captcha(context, options);\n }\n\n async setAIActionContext(prompt: string) {\n this.opts.aiActionContext = prompt;\n }\n\n resetDump() {\n this.dump = {\n groupName: this.opts.groupName!,\n groupDescription: this.opts.groupDescription,\n executions: [],\n };\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump) {\n const currentDump = this.dump;\n currentDump.executions.push(execution);\n }\n\n dumpDataString() {\n // update dump info\n this.dump.groupName = this.opts.groupName!;\n this.dump.groupDescription = this.opts.groupDescription;\n return stringifyDumpData(this.dump);\n }\n\n reportHTMLString() {\n return reportHTMLContent(this.dumpDataString());\n }\n\n writeOutActionDumps() {\n const { generateReport, autoPrintReportMsg } = this.opts;\n this.reportFile = writeLogFile({\n fileName: this.reportFileName!,\n fileExt: groupedActionDumpFileExt,\n fileContent: this.dumpDataString(),\n type: 'dump',\n generateReport,\n });\n debug('writeOutActionDumps', this.reportFile);\n if (generateReport && autoPrintReportMsg && this.reportFile) {\n printReportMsg(this.reportFile);\n }\n }\n\n private async callbackOnTaskStartTip(task: ExecutionTask) {\n const param = paramStr(task);\n const tip = param ? `${typeStr(task)} - ${param}` : typeStr(task);\n\n if (this.onTaskStartTip) {\n await this.onTaskStartTip(tip);\n }\n }\n\n private afterTaskRunning(executor: Executor, doNotThrowError = false) {\n // Always collect execution data for metadata\n this.appendExecutionDump(executor.dump());\n\n // Only write out dumps if not using Puppeteer\n this.writeOutActionDumps();\n\n if (executor.isInErrorState() && !doNotThrowError) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}`);\n }\n\n // Extract metadata from the executor\n const lastTask = executor.tasks[executor.tasks.length - 1];\n\n // Collect all tasks' thoughts and plans\n const allThoughts = executor.tasks\n .filter(task => task.thought)\n .map(task => task.thought);\n\n // Collect all locate information\n const allLocates = executor.tasks\n .filter(task => task.locate)\n .map(task => task.locate);\n\n // Collect all plans\n const allPlans = executor.tasks\n .filter(task => task.param?.plans)\n .map(task => task.param?.plans);\n\n // Collect tasks by type\n const planningTasks = executor.tasks.filter(task => task.type === 'Planning');\n const insightTasks = executor.tasks.filter(task => task.type === 'Insight');\n const actionTasks = executor.tasks.filter(task => task.type === 'Action');\n\n // Create planning, insight, and action information\n const planning = planningTasks.length > 0 ? {\n type: \"Planning\",\n description: `Planning for task execution`,\n steps: planningTasks.map(task => task.thought || 'Planning step')\n } : undefined;\n\n const insight = insightTasks.length > 0 ? {\n type: \"Insight\",\n description: `Insight for task execution`,\n elements: insightTasks.map(task => task.thought || 'Insight element')\n } : undefined;\n\n const action = actionTasks.length > 0 ? {\n type: \"Action\",\n description: `Action for task execution`,\n result: lastTask?.output\n } : undefined;\n\n // Create action details\n const actionDetails = executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought\n }));\n\n // Extract detailed information from all tasks\n const metadata: AITaskMetadata = {\n status: lastTask?.status,\n start: lastTask?.timing?.start,\n end: lastTask?.timing?.end,\n totalTime: lastTask?.timing?.cost,\n cache: lastTask?.cache,\n usage: lastTask?.usage,\n thought: allThoughts.length > 0 ? allThoughts.join('\\n') : lastTask?.thought,\n locate: allLocates.length > 0 ? allLocates : lastTask?.locate,\n plan: allPlans.length > 0 ? allPlans : lastTask?.param?.plans,\n // Add planning, insight, and action information\n planning,\n insight,\n action,\n actionDetails,\n // Include raw tasks for debugging\n tasks: executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought,\n locate: task.locate,\n timing: task.timing,\n usage: task.usage,\n cache: task.cache,\n error: task.error\n }))\n };\n\n return metadata;\n }\n\n private buildDetailedLocateParam(\n locatePrompt: string,\n opt?: LocateOption,\n ): DetailedLocateParam {\n assert(locatePrompt, 'missing locate prompt');\n if (typeof opt === 'object') {\n const prompt = opt.prompt || locatePrompt;\n const deepThink = opt.deepThink || false;\n const cacheable = opt.cacheable || true;\n return {\n prompt,\n deepThink,\n cacheable,\n };\n }\n return {\n prompt: locatePrompt,\n };\n }\n\n async aiTap(locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Tap', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Tap', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiHover(locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Hover', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Hover', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiInput(value: string, locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n assert(\n typeof value === 'string',\n 'input value must be a string, use empty string if you want to clear the input',\n );\n assert(locatePrompt, 'missing locate prompt for input');\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Input', detailedLocateParam, {\n value,\n });\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Input', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiKeyboardPress(\n keyName: string,\n locatePrompt?: string,\n opt?: LocateOption,\n ): Promise<AITaskResult> {\n assert(keyName, 'missing keyName for keyboard press');\n const detailedLocateParam = locatePrompt\n ? this.buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n const plans = buildPlans('KeyboardPress', detailedLocateParam, {\n value: keyName,\n });\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('KeyboardPress', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiScroll(\n scrollParam: PlanningActionParamScroll,\n locatePrompt?: string,\n opt?: LocateOption,\n ): Promise<AITaskResult> {\n const detailedLocateParam = locatePrompt\n ? this.buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n const plans = buildPlans('Scroll', detailedLocateParam, scrollParam);\n const paramInTitle = locatePrompt\n ? `${locateParamStr(detailedLocateParam)} - ${scrollParamStr(scrollParam)}`\n : scrollParamStr(scrollParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Scroll', paramInTitle),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiAction(\n taskPrompt: string,\n opt?: {\n cacheable?: boolean;\n },\n ): Promise<AITaskResult> {\n const cacheable = opt?.cacheable;\n // if vlm-ui-tars, plan cache is not used\n const isVlmUiTars = vlLocateMode() === 'vlm-ui-tars';\n const matchedCache =\n isVlmUiTars || cacheable === false\n ? undefined\n : this.taskCache?.matchPlanCache(taskPrompt);\n if (matchedCache && this.taskCache?.isCacheResultUsed) {\n // log into report file\n const { executor } = await this.taskExecutor.loadYamlFlowAsPlanning(\n taskPrompt,\n matchedCache.cacheContent?.yamlWorkflow,\n );\n\n const metadata = this.afterTaskRunning(executor);\n\n debug('matched cache, will call .runYaml to run the action');\n const yaml = matchedCache.cacheContent?.yamlWorkflow;\n const result = await this.runYaml(yaml);\n return {\n result: result.result,\n metadata\n };\n }\n\n const { output, executor } = await (isVlmUiTars\n ? this.taskExecutor.actionToGoal(taskPrompt)\n : this.taskExecutor.action(taskPrompt, this.opts.aiActionContext));\n\n // update cache\n if (this.taskCache && output?.yamlFlow && cacheable !== false) {\n const yamlContent = {\n tasks: [\n {\n name: taskPrompt,\n flow: output.yamlFlow,\n },\n ],\n };\n const yamlFlowStr = yaml.dump(yamlContent);\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'plan',\n prompt: taskPrompt,\n yamlWorkflow: yamlFlowStr,\n },\n matchedCache,\n );\n }\n\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiQuery(demand: any): Promise<AITaskResult> {\n const { output, executor } = await this.taskExecutor.query(demand);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiBoolean(prompt: string): Promise<AITaskResult<boolean>> {\n const { output, executor } = await this.taskExecutor.boolean(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiNumber(prompt: string): Promise<AITaskResult<number>> {\n const { output, executor } = await this.taskExecutor.number(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiString(prompt: string): Promise<AITaskResult<string>> {\n const { output, executor } = await this.taskExecutor.string(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async describeElementAtPoint(\n center: [number, number],\n opt?: {\n verifyPrompt?: boolean;\n retryLimit?: number;\n deepThink?: boolean;\n } & LocatorValidatorOption,\n ): Promise<AgentDescribeElementAtPointResult> {\n const { verifyPrompt = true, retryLimit = 3 } = opt || {};\n\n let success = false;\n let retryCount = 0;\n let resultPrompt = '';\n let deepThink = opt?.deepThink || false;\n let verifyResult: LocateValidatorResult | undefined;\n\n while (!success && retryCount < retryLimit) {\n if (retryCount >= 2) {\n deepThink = true;\n }\n debug(\n 'aiDescribe',\n center,\n 'verifyPrompt',\n verifyPrompt,\n 'retryCount',\n retryCount,\n 'deepThink',\n deepThink,\n );\n const text = await this.insight.describe(center, { deepThink });\n debug('aiDescribe text', text);\n assert(text.description, `failed to describe element at [${center}]`);\n resultPrompt = text.description;\n\n verifyResult = await this.verifyLocator(\n resultPrompt,\n deepThink ? { deepThink: true } : undefined,\n center,\n opt,\n );\n if (verifyResult.pass) {\n success = true;\n } else {\n retryCount++;\n }\n }\n\n return {\n prompt: resultPrompt,\n deepThink,\n verifyResult,\n };\n }\n\n async verifyLocator(\n prompt: string,\n locateOpt: LocateOption | undefined,\n expectCenter: [number, number],\n verifyLocateOption?: LocatorValidatorOption,\n ): Promise<LocateValidatorResult> {\n debug('verifyLocator', prompt, locateOpt, expectCenter, verifyLocateOption);\n\n const locateResult = await this.aiLocate(prompt, locateOpt);\n const { center: verifyCenter, rect: verifyRect } = locateResult.result;\n\n const distance = distanceOfTwoPoints(expectCenter, verifyCenter);\n const included = includedInRect(expectCenter, verifyRect);\n const pass =\n distance <= (verifyLocateOption?.centerDistanceThreshold || 20) ||\n included;\n const verifyResult = {\n pass,\n rect: verifyRect,\n center: verifyCenter,\n centerDistance: distance,\n };\n debug('aiDescribe verifyResult', verifyResult);\n return verifyResult;\n }\n\n async aiLocate(prompt: string, opt?: LocateOption): Promise<AITaskResult<Pick<LocateResultElement, 'rect' | 'center'>>> {\n const detailedLocateParam = this.buildDetailedLocateParam(prompt, opt);\n const plans = buildPlans('Locate', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n const { element } = output;\n const result = {\n rect: element?.rect,\n center: element?.center,\n } as Pick<LocateResultElement, 'rect' | 'center'>;\n\n return {\n result,\n metadata\n };\n }\n\n async aiAssert(assertion: string, msg?: string, opt?: AgentAssertOpt): Promise<AITaskResult<any>> {\n // Get the current page URL to include in the assertion context\n let currentUrl = \"\";\n if (this.page.url) {\n try {\n currentUrl = await this.page.url();\n } catch (e) {\n // Ignore errors getting URL\n }\n }\n\n // Add URL context to the assertion if available\n const assertionWithContext = currentUrl\n ? `For the page at URL \"${currentUrl}\", ${assertion}`\n : assertion;\n\n const { output, executor } = await this.taskExecutor.assert(assertionWithContext);\n const metadata = this.afterTaskRunning(executor, true);\n\n if (output && opt?.keepRawResponse) {\n return {\n result: output,\n metadata,\n };\n }\n\n if (!output?.pass) {\n const errMsg = msg || `Assertion failed: ${assertion}`;\n const reasonMsg = `Reason: ${\n output?.thought || executor.latestErrorTask()?.error || '(no_reason)'\n }`;\n throw new Error(`${errMsg}\\n${reasonMsg}`);\n }\n\n return {\n result: true,\n metadata\n };\n }\n\n async aiCaptcha(options?: { deepThink?: boolean; autoDetectComplexity?: boolean }): Promise<AITaskResult<any>> {\n const { deepThink = false, autoDetectComplexity = true } = options || {};\n\n // First, do a preliminary analysis to determine if this is a complex CAPTCHA\n // that would benefit from deep thinking\n let shouldUseDeepThink = deepThink;\n\n if (autoDetectComplexity && !deepThink) {\n // Get a screenshot to analyze\n const context = await this.getUIContext();\n const { screenshotBase64 } = context;\n\n // Simple analysis to determine if this is likely a complex CAPTCHA\n try {\n const complexityAnalysisPrompt = `\nAnalyze this screenshot and determine if it contains a complex CAPTCHA that would benefit from deep thinking.\nA complex CAPTCHA typically has one or more of these characteristics:\n- Distorted or overlapping text that is hard to read\n- Multiple images that need to be selected based on a specific criteria\n- Puzzles that require spatial reasoning\n- Multiple steps or verification methods\n- Small or hard-to-distinguish elements\n\nReturn only \"complex\" or \"simple\" based on your analysis.\n`;\n\n const complexityMsgs = [\n { role: 'system', content: 'You are an AI assistant that analyzes screenshots to determine CAPTCHA complexity.' },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: complexityAnalysisPrompt,\n },\n ],\n },\n ];\n\n // Use a simple call to determine complexity\n // Using any here to avoid type issues since we're just checking the response text\n const complexityResult = await (this.insight as any).aiVendorFn(\n complexityMsgs,\n { type: 'extract_data' }\n );\n\n // Check if the response indicates a complex CAPTCHA\n const responseText = typeof complexityResult.content === 'string'\n ? complexityResult.content.toLowerCase()\n : JSON.stringify(complexityResult.content).toLowerCase();\n\n shouldUseDeepThink = responseText.includes('complex');\n\n debug('CAPTCHA complexity analysis:', responseText, 'Using deep think:', shouldUseDeepThink);\n } catch (error) {\n // If analysis fails, default to not using deep think\n debug('Failed to analyze CAPTCHA complexity:', error);\n }\n }\n\n // Call the AiCaptcha function to analyze the CAPTCHA with the determined deepThink setting\n const captchaResponse = await this._callInsightCaptcha({\n deepThink: shouldUseDeepThink\n });\n\n const captchaResult = captchaResponse.content;\n const usage = captchaResponse.usage;\n // Get the actual deepThink value that was used (may be different due to global settings)\n const actualDeepThink = captchaResponse.deepThink || false;\n\n // Process the CAPTCHA solution based on its type\n if (captchaResult.captchaType === 'text') {\n // For text-based CAPTCHAs, find the input field and enter the solution\n for (const action of captchaResult.actions) {\n if (action.type === 'click' && action.target) {\n // Click on the input field\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n } else if (action.type === 'input' && action.value) {\n // Enter the text solution\n if (action.target) {\n await this.aiInput(action.value, action.target, { deepThink: shouldUseDeepThink });\n }\n } else if (action.type === 'verify' && action.target) {\n // Click on the verify/submit button\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n }\n } else if (captchaResult.captchaType === 'image') {\n // For image-based CAPTCHAs, click on the required elements\n for (const action of captchaResult.actions) {\n if (action.type === 'click') {\n if (action.coordinates) {\n // Click at specific coordinates using aiTap with coordinates\n const x = action.coordinates[0];\n const y = action.coordinates[1];\n await this.aiTap(`element at coordinates (${x}, ${y})`, { deepThink: shouldUseDeepThink });\n } else if (action.target) {\n // Click on described element\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n } else if (action.type === 'verify' && action.target) {\n // Click on the verify/submit button\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n }\n }\n\n // Wait a few seconds after completing the CAPTCHA\n await new Promise(resolve => setTimeout(resolve, 3000));\n\n // Return the result with metadata\n const metadata: AITaskMetadata = {\n status: 'finished',\n usage,\n thought: captchaResult.thought,\n };\n\n // Add additional metadata properties using type assertion\n (metadata as any).deepThink = actualDeepThink;\n if (autoDetectComplexity && !deepThink) {\n (metadata as any).autoDetectedComplexity = shouldUseDeepThink;\n }\n\n return {\n result: captchaResult,\n metadata\n };\n }\n\n async aiWaitFor(assertion: string, opt?: AgentWaitForOpt): Promise<AITaskResult> {\n const startTime = Date.now();\n const { executor } = await this.taskExecutor.waitFor(assertion, {\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n assertion,\n });\n const metadata: AITaskMetadata = {\n status: executor.isInErrorState() ? 'failed' : 'finished',\n start: startTime,\n end: Date.now(),\n totalTime: Date.now() - startTime,\n thought: executor.latestErrorTask()?.thought,\n actionDetails: executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought,\n })),\n };\n\n this.appendExecutionDump(executor.dump());\n this.writeOutActionDumps();\n\n if (executor.isInErrorState()) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}\\n${errorTask?.errorStack}`);\n }\n\n return {\n result: true, // Successfully waited\n metadata,\n };\n }\n\n async ai(\n taskPrompt: string,\n type = 'action',\n options?: { deepThink?: boolean; autoDetectComplexity?: boolean }\n ): Promise<AITaskResult> {\n if (type === 'action') {\n return this.aiAction(taskPrompt);\n }\n if (type === 'query') {\n return this.aiQuery(taskPrompt);\n }\n\n if (type === 'assert') {\n return this.aiAssert(taskPrompt);\n }\n\n if (type === 'tap') {\n return this.aiTap(taskPrompt, options);\n }\n\n if (type === 'captcha') {\n return this.aiCaptcha(options);\n }\n\n throw new Error(\n `Unknown type: ${type}, only support 'action', 'query', 'assert', 'tap', 'captcha'`,\n );\n }\n\n async runYaml(yamlScriptContent: string): Promise<AITaskResult<Record<string, any>>> {\n const startTime = Date.now();\n const script = parseYamlScript(yamlScriptContent, 'yaml', true);\n const player = new ScriptPlayer(script, async () => {\n return { agent: this, freeFn: [] };\n });\n await player.run();\n\n const endTime = Date.now();\n const metadata: AITaskMetadata = {\n status: player.status,\n start: startTime,\n end: endTime,\n totalTime: endTime - startTime,\n tasks: player.taskStatusList.map(task => ({\n type: 'yaml-task',\n subType: task.name,\n status: task.status,\n error: task.error?.message,\n })),\n };\n\n if (player.status === 'error') {\n const errors = player.taskStatusList\n .filter((task) => task.status === 'error')\n .map((task) => {\n return `task - ${task.name}: ${task.error?.message}`;\n })\n .join('\\n');\n throw new Error(`Error(s) occurred in running yaml script:\\n${errors}`);\n }\n\n return {\n result: player.result,\n metadata\n };\n }\n\n async evaluateJavaScript(script: string): Promise<any> {\n assert(\n this.page.evaluateJavaScript,\n 'evaluateJavaScript is not supported in current agent',\n );\n if (this.page.evaluateJavaScript) {\n return this.page.evaluateJavaScript(script);\n }\n throw new Error('evaluateJavaScript is not supported in current agent');\n }\n\n async destroy() {\n await this.page.destroy();\n }\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { assert, ifInBrowser } from 'misoai-shared/utils';\n\nimport type { PageAgent } from '@/common/agent';\nimport type {\n FreeFn,\n MidsceneYamlFlowItemAIAction,\n MidsceneYamlFlowItemAIAssert,\n MidsceneYamlFlowItemAIBoolean,\n MidsceneYamlFlowItemAIHover,\n MidsceneYamlFlowItemAIInput,\n MidsceneYamlFlowItemAIKeyboardPress,\n MidsceneYamlFlowItemAILocate,\n MidsceneYamlFlowItemAINString,\n MidsceneYamlFlowItemAINumber,\n MidsceneYamlFlowItemAIQuery,\n MidsceneYamlFlowItemAIScroll,\n MidsceneYamlFlowItemAITap,\n MidsceneYamlFlowItemAIWaitFor,\n MidsceneYamlFlowItemEvaluateJavaScript,\n MidsceneYamlFlowItemSleep,\n MidsceneYamlScript,\n MidsceneYamlScriptEnv,\n ScriptPlayerStatusValue,\n ScriptPlayerTaskStatus,\n} from 'misoai-core';\nimport { getMidsceneRunSubDir } from 'misoai-shared/common';\n\nexport class ScriptPlayer<T extends MidsceneYamlScriptEnv> {\n public currentTaskIndex?: number;\n public taskStatusList: ScriptPlayerTaskStatus[] = [];\n public status: ScriptPlayerStatusValue = 'init';\n public reportFile?: string | null;\n public result: Record<string, any>;\n private unnamedResultIndex = 0;\n public output?: string | null;\n public errorInSetup?: Error;\n private pageAgent: PageAgent | null = null;\n public agentStatusTip?: string;\n constructor(\n private script: MidsceneYamlScript,\n private setupAgent: (platform: T) => Promise<{\n agent: PageAgent;\n freeFn: FreeFn[];\n }>,\n public onTaskStatusChange?: (taskStatus: ScriptPlayerTaskStatus) => void,\n ) {\n this.result = {};\n\n if (ifInBrowser) {\n this.output = undefined;\n } else if (script.target?.output) {\n this.output = resolve(process.cwd(), script.target.output);\n } else {\n this.output = join(getMidsceneRunSubDir('output'), `${process.pid}.json`);\n }\n\n this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({\n ...task,\n index: taskIndex,\n status: 'init',\n totalSteps: task.flow?.length || 0,\n }));\n }\n\n private setResult(key: string | undefined, value: any) {\n const keyToUse = key || this.unnamedResultIndex++;\n if (this.result[keyToUse]) {\n console.warn(`result key ${keyToUse} already exists, will overwrite`);\n }\n this.result[keyToUse] = value;\n\n this.flushResult();\n }\n\n private setPlayerStatus(status: ScriptPlayerStatusValue, error?: Error) {\n this.status = status;\n this.errorInSetup = error;\n }\n\n private notifyCurrentTaskStatusChange(taskIndex?: number) {\n const taskIndexToNotify =\n typeof taskIndex === 'number' ? taskIndex : this.currentTaskIndex;\n\n if (typeof taskIndexToNotify !== 'number') {\n return;\n }\n\n const taskStatus = this.taskStatusList[taskIndexToNotify];\n if (this.onTaskStatusChange) {\n this.onTaskStatusChange(taskStatus);\n }\n }\n\n private async setTaskStatus(\n index: number,\n statusValue: ScriptPlayerStatusValue,\n error?: Error,\n ) {\n this.taskStatusList[index].status = statusValue;\n if (error) {\n this.taskStatusList[index].error = error;\n }\n\n this.notifyCurrentTaskStatusChange(index);\n }\n\n private setTaskIndex(taskIndex: number) {\n this.currentTaskIndex = taskIndex;\n }\n\n private flushResult() {\n if (Object.keys(this.result).length && this.output) {\n const output = resolve(process.cwd(), this.output);\n const outputDir = dirname(output);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(output, JSON.stringify(this.result, undefined, 2));\n }\n }\n\n async playTask(taskStatus: ScriptPlayerTaskStatus, agent: PageAgent) {\n const { flow } = taskStatus;\n assert(flow, 'missing flow in task');\n\n for (const flowItemIndex in flow) {\n const currentStep = Number.parseInt(flowItemIndex, 10);\n taskStatus.currentStep = currentStep;\n const flowItem = flow[flowItemIndex];\n if (\n 'aiAction' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'ai' in (flowItem as MidsceneYamlFlowItemAIAction)\n ) {\n const actionTask = flowItem as MidsceneYamlFlowItemAIAction;\n const prompt = actionTask.aiAction || actionTask.ai;\n assert(prompt, 'missing prompt for ai (aiAction)');\n assert(\n typeof prompt === 'string',\n 'prompt for aiAction must be a string',\n );\n await agent.aiAction(prompt);\n } else if ('aiAssert' in (flowItem as MidsceneYamlFlowItemAIAssert)) {\n const assertTask = flowItem as MidsceneYamlFlowItemAIAssert;\n const prompt = assertTask.aiAssert;\n assert(prompt, 'missing prompt for aiAssert');\n assert(\n typeof prompt === 'string',\n 'prompt for aiAssert must be a string',\n );\n await agent.aiAssert(prompt);\n } else if ('aiQuery' in (flowItem as MidsceneYamlFlowItemAIQuery)) {\n const queryTask = flowItem as MidsceneYamlFlowItemAIQuery;\n const prompt = queryTask.aiQuery;\n assert(prompt, 'missing prompt for aiQuery');\n assert(\n typeof prompt === 'string',\n 'prompt for aiQuery must be a string',\n );\n const queryResult = await agent.aiQuery(prompt);\n this.setResult(queryTask.name, queryResult);\n } else if ('aiNumber' in (flowItem as MidsceneYamlFlowItemAINumber)) {\n const numberTask = flowItem as MidsceneYamlFlowItemAINumber;\n const prompt = numberTask.aiNumber;\n assert(prompt, 'missing prompt for number');\n assert(\n typeof prompt === 'string',\n 'prompt for number must be a string',\n );\n const numberResult = await agent.aiNumber(prompt);\n this.setResult(numberTask.name, numberResult);\n } else if ('aiString' in (flowItem as MidsceneYamlFlowItemAINString)) {\n const stringTask = flowItem as MidsceneYamlFlowItemAINString;\n const prompt = stringTask.aiString;\n assert(prompt, 'missing prompt for string');\n assert(\n typeof prompt === 'string',\n 'prompt for string must be a string',\n );\n const stringResult = await agent.aiString(prompt);\n this.setResult(stringTask.name, stringResult);\n } else if ('aiBoolean' in (flowItem as MidsceneYamlFlowItemAIBoolean)) {\n const booleanTask = flowItem as MidsceneYamlFlowItemAIBoolean;\n const prompt = booleanTask.aiBoolean;\n assert(prompt, 'missing prompt for boolean');\n assert(\n typeof prompt === 'string',\n 'prompt for boolean must be a string',\n );\n const booleanResult = await agent.aiBoolean(prompt);\n this.setResult(booleanTask.name, booleanResult);\n } else if ('aiLocate' in (flowItem as MidsceneYamlFlowItemAILocate)) {\n const locateTask = flowItem as MidsceneYamlFlowItemAILocate;\n const prompt = locateTask.aiLocate;\n assert(prompt, 'missing prompt for aiLocate');\n assert(\n typeof prompt === 'string',\n 'prompt for aiLocate must be a string',\n );\n const locateResult = await agent.aiLocate(prompt);\n this.setResult(locateTask.name, locateResult);\n } else if ('aiWaitFor' in (flowItem as MidsceneYamlFlowItemAIWaitFor)) {\n const waitForTask = flowItem as MidsceneYamlFlowItemAIWaitFor;\n const prompt = waitForTask.aiWaitFor;\n assert(prompt, 'missing prompt for aiWaitFor');\n assert(\n typeof prompt === 'string',\n 'prompt for aiWaitFor must be a string',\n );\n const timeout = waitForTask.timeout;\n await agent.aiWaitFor(prompt, { timeoutMs: timeout });\n } else if ('sleep' in (flowItem as MidsceneYamlFlowItemSleep)) {\n const sleepTask = flowItem as MidsceneYamlFlowItemSleep;\n const ms = sleepTask.sleep;\n let msNumber = ms;\n if (typeof ms === 'string') {\n msNumber = Number.parseInt(ms, 10);\n }\n assert(\n msNumber && msNumber > 0,\n `ms for sleep must be greater than 0, but got ${ms}`,\n );\n await new Promise((resolve) => setTimeout(resolve, msNumber));\n } else if ('aiTap' in (flowItem as MidsceneYamlFlowItemAITap)) {\n const tapTask = flowItem as MidsceneYamlFlowItemAITap;\n await agent.aiTap(tapTask.aiTap, tapTask);\n } else if ('aiHover' in (flowItem as MidsceneYamlFlowItemAIHover)) {\n const hoverTask = flowItem as MidsceneYamlFlowItemAIHover;\n await agent.aiHover(hoverTask.aiHover, hoverTask);\n } else if ('aiInput' in (flowItem as MidsceneYamlFlowItemAIInput)) {\n // may be input empty string ''\n const inputTask = flowItem as MidsceneYamlFlowItemAIInput;\n await agent.aiInput(inputTask.aiInput, inputTask.locate, inputTask);\n } else if (\n 'aiKeyboardPress' in (flowItem as MidsceneYamlFlowItemAIKeyboardPress)\n ) {\n const keyboardPressTask =\n flowItem as MidsceneYamlFlowItemAIKeyboardPress;\n await agent.aiKeyboardPress(\n keyboardPressTask.aiKeyboardPress,\n keyboardPressTask.locate,\n keyboardPressTask,\n );\n } else if ('aiScroll' in (flowItem as MidsceneYamlFlowItemAIScroll)) {\n const scrollTask = flowItem as MidsceneYamlFlowItemAIScroll;\n await agent.aiScroll(scrollTask, scrollTask.locate, scrollTask);\n } else if (\n 'javascript' in (flowItem as MidsceneYamlFlowItemEvaluateJavaScript)\n ) {\n const evaluateJavaScriptTask =\n flowItem as MidsceneYamlFlowItemEvaluateJavaScript;\n\n const result = await agent.evaluateJavaScript(\n evaluateJavaScriptTask.javascript,\n );\n this.setResult(evaluateJavaScriptTask.name, result);\n } else {\n throw new Error(`unknown flowItem: ${JSON.stringify(flowItem)}`);\n }\n }\n this.reportFile = agent.reportFile;\n }\n\n async run() {\n const { target, web, android, tasks } = this.script;\n const webEnv = web || target;\n const androidEnv = android;\n const platform = webEnv || androidEnv;\n\n this.setPlayerStatus('running');\n\n let agent: PageAgent | null = null;\n let freeFn: FreeFn[] = [];\n try {\n const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(\n platform as T,\n );\n agent = newAgent;\n const originalOnTaskStartTip = agent.onTaskStartTip;\n agent.onTaskStartTip = (tip) => {\n if (this.status === 'running') {\n this.agentStatusTip = tip;\n }\n originalOnTaskStartTip?.(tip);\n };\n freeFn = [\n ...(newFreeFn || []),\n {\n name: 'restore-agent-onTaskStartTip',\n fn: () => {\n if (agent) {\n agent.onTaskStartTip = originalOnTaskStartTip;\n }\n },\n },\n ];\n } catch (e) {\n this.setPlayerStatus('error', e as Error);\n return;\n }\n this.pageAgent = agent;\n\n let taskIndex = 0;\n this.setPlayerStatus('running');\n let errorFlag = false;\n while (taskIndex < tasks.length) {\n const taskStatus = this.taskStatusList[taskIndex];\n this.setTaskStatus(taskIndex, 'running' as any);\n this.setTaskIndex(taskIndex);\n\n try {\n await this.playTask(taskStatus, this.pageAgent);\n this.setTaskStatus(taskIndex, 'done' as any);\n } catch (e) {\n this.setTaskStatus(taskIndex, 'error' as any, e as Error);\n\n if (taskStatus.continueOnError) {\n // nothing more to do\n } else {\n this.reportFile = agent.reportFile;\n errorFlag = true;\n break;\n }\n }\n this.reportFile = agent.reportFile;\n taskIndex++;\n }\n\n if (errorFlag) {\n this.setPlayerStatus('error');\n } else {\n this.setPlayerStatus('done');\n }\n this.agentStatusTip = '';\n\n // free the resources\n for (const fn of freeFn) {\n try {\n // console.log('freeing', fn.name);\n await fn.fn();\n // console.log('freed', fn.name);\n } catch (e) {\n // console.error('error freeing', fn.name, e);\n }\n }\n }\n}\n","import type {\n MidsceneYamlScript,\n MidsceneYamlScriptWebEnv,\n MidsceneYamlTask,\n} from 'misoai-core';\nimport yaml from 'js-yaml';\n\nexport function buildYaml(\n env: MidsceneYamlScriptWebEnv,\n tasks: MidsceneYamlTask[],\n) {\n const result: MidsceneYamlScript = {\n target: env,\n tasks,\n };\n\n return yaml.dump(result, {\n indent: 2,\n });\n}\n","import { assert } from 'misoai-shared/utils';\nimport yaml from 'js-yaml';\n\nimport type { MidsceneYamlScript } from 'misoai-core';\n\nfunction interpolateEnvVars(content: string): string {\n return content.replace(/\\$\\{([^}]+)\\}/g, (_, envVar) => {\n const value = process.env[envVar.trim()];\n if (value === undefined) {\n throw new Error(`Environment variable \"${envVar.trim()}\" is not defined`);\n }\n return value;\n });\n}\n\nexport function parseYamlScript(\n content: string,\n filePath?: string,\n ignoreCheckingTarget?: boolean,\n): MidsceneYamlScript {\n const interpolatedContent = interpolateEnvVars(content);\n const obj = yaml.load(interpolatedContent) as MidsceneYamlScript;\n const pathTip = filePath ? `, failed to load ${filePath}` : '';\n const android =\n typeof obj.android !== 'undefined'\n ? Object.assign({}, obj.android || {})\n : undefined;\n const webConfig = obj.web || obj.target; // no need to handle null case, because web has required parameters url\n const web =\n typeof webConfig !== 'undefined'\n ? Object.assign({}, webConfig || {})\n : undefined;\n\n if (!ignoreCheckingTarget) {\n // make sure at least one of target/web/android is provided\n assert(\n web || android,\n `at least one of \"target\", \"web\", or \"android\" properties is required in yaml script${pathTip}`,\n );\n\n // make sure only one of target/web/android is provided\n assert(\n (web && !android) || (!web && android),\n `only one of \"target\", \"web\", or \"android\" properties is allowed in yaml script${pathTip}`,\n );\n\n // make sure the config is valid\n if (web || android) {\n assert(\n typeof web === 'object' || typeof android === 'object',\n `property \"target/web/android\" must be an object${pathTip}`,\n );\n }\n }\n\n assert(obj.tasks, `property \"tasks\" is required in yaml script ${pathTip}`);\n assert(\n Array.isArray(obj.tasks),\n `property \"tasks\" must be an array in yaml script, but got ${obj.tasks}`,\n );\n return obj;\n}\n","import type { AndroidDevicePage, WebPage } from '@/common/page';\nimport type { PuppeteerWebPage } from '@/puppeteer';\nimport {\n type AIUsageInfo,\n type DumpSubscriber,\n type ExecutionRecorderItem,\n type ExecutionTaskActionApply,\n type ExecutionTaskApply,\n type ExecutionTaskInsightLocateApply,\n type ExecutionTaskInsightQueryApply,\n type ExecutionTaskPlanning,\n type ExecutionTaskPlanningApply,\n type ExecutionTaskProgressOptions,\n Executor,\n type ExecutorContext,\n type Insight,\n type InsightAssertionResponse,\n type InsightDump,\n type InsightExtractParam,\n type LocateResultElement,\n type MidsceneYamlFlowItem,\n type PageType,\n type PlanningAIResponse,\n type PlanningAction,\n type PlanningActionParamAssert,\n type PlanningActionParamError,\n type PlanningActionParamHover,\n type PlanningActionParamInputOrKeyPress,\n type PlanningActionParamScroll,\n type PlanningActionParamSleep,\n type PlanningActionParamTap,\n type PlanningActionParamWaitFor,\n plan,\n} from 'misoai-core';\nimport {\n type ChatCompletionMessageParam,\n elementByPositionWithElementInfo,\n resizeImageForUiTars,\n vlmPlanning,\n} from 'misoai-core/ai-model';\nimport { sleep } from 'misoai-core/utils';\nimport { NodeType } from 'misoai-shared/constants';\nimport type { ElementInfo } from 'misoai-shared/extractor';\nimport { getElementInfosScriptContent } from 'misoai-shared/fs';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\nimport type { WebElementInfo } from '../web-element';\nimport type { TaskCache } from './task-cache';\nimport { getKeyCommands, taskTitleStr } from './ui-utils';\nimport { type WebUIContext, matchElementFromPlan } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n executor: Executor;\n}\n\nconst debug = getDebug('page-task-executor');\n\nconst replanningCountLimit = 10;\n\nconst isAndroidPage = (page: WebPage): page is AndroidDevicePage => {\n return page.pageType === 'android';\n};\n\nexport class PageTaskExecutor {\n page: WebPage;\n\n insight: Insight<WebElementInfo, WebUIContext>;\n\n taskCache?: TaskCache;\n\n conversationHistory: ChatCompletionMessageParam[] = [];\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n constructor(\n page: WebPage,\n insight: Insight<WebElementInfo, WebUIContext>,\n opts: {\n taskCache?: TaskCache;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n },\n ) {\n this.page = page;\n this.insight = insight;\n\n this.taskCache = opts.taskCache;\n\n this.onTaskStartCallback = opts?.onTaskStart;\n }\n\n private async recordScreenshot(timing: ExecutionRecorderItem['timing']) {\n const base64 = await this.page.screenshotBase64();\n const item: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: Date.now(),\n screenshot: base64,\n timing,\n };\n return item;\n }\n\n private async getElementXpath(\n pageContext: WebUIContext,\n element: LocateResultElement,\n ): Promise<string[] | undefined> {\n let elementId = element?.id;\n // find the nearest xpath for the element\n if (element?.attributes?.nodeType === NodeType.POSITION) {\n await this.insight.contextRetrieverFn('locate');\n const info = elementByPositionWithElementInfo(\n pageContext.tree,\n {\n x: element.center[0],\n y: element.center[1],\n },\n {\n requireStrictDistance: false,\n filterPositionElements: true,\n },\n );\n if (info?.id) {\n elementId = info.id;\n }\n }\n\n if (!elementId) {\n return undefined;\n }\n try {\n const elementInfosScriptContent = getElementInfosScriptContent();\n const result = await this.page.evaluateJavaScript?.(\n `${elementInfosScriptContent}midscene_element_inspector.getXpathsById('${elementId}')`,\n );\n return result;\n } catch (error) {\n debug('getXpathsById error: ', error);\n }\n }\n\n private prependExecutorWithScreenshot(\n taskApply: ExecutionTaskApply,\n appendAfterExecution = false,\n ): ExecutionTaskApply {\n const taskWithScreenshot: ExecutionTaskApply = {\n ...taskApply,\n executor: async (param, context, ...args) => {\n const recorder: ExecutionRecorderItem[] = [];\n const { task } = context;\n // set the recorder before executor in case of error\n task.recorder = recorder;\n const shot = await this.recordScreenshot(`before ${task.type}`);\n recorder.push(shot);\n const result = await taskApply.executor(param, context, ...args);\n if (taskApply.type === 'Action') {\n await Promise.all([\n (async () => {\n await sleep(100);\n if ((this.page as PuppeteerWebPage).waitUntilNetworkIdle) {\n try {\n await (this.page as PuppeteerWebPage).waitUntilNetworkIdle();\n } catch (error) {\n // console.error('waitUntilNetworkIdle error', error);\n }\n }\n })(),\n sleep(200),\n ]);\n }\n if (appendAfterExecution) {\n const shot2 = await this.recordScreenshot('after Action');\n recorder.push(shot2);\n }\n return result;\n },\n };\n return taskWithScreenshot;\n }\n\n private async convertPlanToExecutable(plans: PlanningAction[]) {\n const tasks: ExecutionTaskApply[] = [];\n plans.forEach((plan) => {\n if (plan.type === 'Locate') {\n if (\n plan.locate === null ||\n plan.locate?.id === null ||\n plan.locate?.id === 'null'\n ) {\n // console.warn('Locate action with id is null, will be ignored');\n return;\n }\n const taskFind: ExecutionTaskInsightLocateApply = {\n type: 'Insight',\n subType: 'Locate',\n param: plan.locate || undefined,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, taskContext) => {\n const { task } = taskContext;\n assert(\n param?.prompt || param?.id || param?.bbox,\n 'No prompt or id or position or bbox to locate',\n );\n let insightDump: InsightDump | undefined;\n let usage: AIUsageInfo | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n usage = dump?.taskInfo?.usage;\n\n task.log = {\n dump: insightDump,\n };\n\n task.usage = usage;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n const shotTime = Date.now();\n const pageContext = await this.insight.contextRetrieverFn('locate');\n task.pageContext = pageContext;\n\n const recordItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: shotTime,\n screenshot: pageContext.screenshotBase64,\n timing: 'before locate',\n };\n task.recorder = [recordItem];\n\n // try matching cache\n let cacheHitFlag = false;\n const cachePrompt = param.prompt;\n const locateCacheRecord =\n this.taskCache?.matchLocateCache(cachePrompt);\n const xpaths = locateCacheRecord?.cacheContent?.xpaths;\n let elementFromCache = null;\n try {\n if (\n xpaths?.length &&\n this.taskCache?.isCacheResultUsed &&\n param?.cacheable !== false\n ) {\n // hit cache, use new id\n const elementInfosScriptContent =\n getElementInfosScriptContent();\n const element = await this.page.evaluateJavaScript?.(\n `${elementInfosScriptContent}midscene_element_inspector.getElementInfoByXpath('${xpaths[0]}')`,\n );\n\n if (element?.id) {\n elementFromCache = element;\n debug('cache hit, prompt: %s', cachePrompt);\n cacheHitFlag = true;\n debug(\n 'found a new new element with same xpath, xpath: %s, id: %s',\n xpaths[0],\n element?.id,\n );\n }\n }\n } catch (error) {\n debug('get element info by xpath error: ', error);\n }\n\n const startTime = Date.now();\n const element =\n elementFromCache || // try to match element from cache\n matchElementFromPlan(param, pageContext.tree) || // try to match element from plan\n (\n await this.insight.locate(param, {\n context: pageContext,\n })\n ).element;\n\n const aiCost = Date.now() - startTime;\n\n // update cache\n if (\n element &&\n this.taskCache &&\n !cacheHitFlag &&\n param?.cacheable !== false\n ) {\n const elementXpaths = await this.getElementXpath(\n pageContext,\n element,\n );\n if (elementXpaths) {\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'locate',\n prompt: cachePrompt,\n xpaths: elementXpaths,\n },\n locateCacheRecord,\n );\n } else {\n debug('no xpaths found, will not update cache', cachePrompt);\n }\n }\n if (!element) {\n throw new Error(`Element not found: ${param.prompt}`);\n }\n\n return {\n output: {\n element,\n },\n pageContext,\n cache: {\n hit: cacheHitFlag,\n },\n aiCost,\n };\n },\n };\n tasks.push(taskFind);\n } else if (plan.type === 'Assert' || plan.type === 'AssertWithoutThrow') {\n const assertPlan = plan as PlanningAction<PlanningActionParamAssert>;\n const taskAssert: ExecutionTaskApply = {\n type: 'Insight',\n subType: 'Assert',\n param: assertPlan.param,\n thought: assertPlan.thought,\n locate: assertPlan.locate,\n executor: async (param, taskContext) => {\n const { task } = taskContext;\n let insightDump: InsightDump | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n const assertion = await this.insight.assert(\n assertPlan.param.assertion,\n );\n\n if (!assertion.pass) {\n if (plan.type === 'Assert') {\n task.output = assertion;\n task.log = {\n dump: insightDump,\n };\n throw new Error(\n assertion.thought || 'Assertion failed without reason',\n );\n }\n\n task.error = assertion.thought;\n }\n\n return {\n output: assertion,\n log: {\n dump: insightDump,\n },\n usage: assertion.usage,\n };\n },\n };\n tasks.push(taskAssert);\n } else if (plan.type === 'Input') {\n const taskActionInput: ExecutionTaskActionApply<PlanningActionParamInputOrKeyPress> =\n {\n type: 'Action',\n subType: 'Input',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam, { element }) => {\n if (element) {\n await this.page.clearInput(element as unknown as ElementInfo);\n\n if (!taskParam || !taskParam.value) {\n return;\n }\n\n await this.page.keyboard.type(taskParam.value);\n } else {\n await this.page.keyboard.type(taskParam.value);\n }\n },\n };\n tasks.push(taskActionInput);\n } else if (plan.type === 'KeyboardPress') {\n const taskActionKeyboardPress: ExecutionTaskActionApply<PlanningActionParamInputOrKeyPress> =\n {\n type: 'Action',\n subType: 'KeyboardPress',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n const keys = getKeyCommands(taskParam.value);\n\n await this.page.keyboard.press(keys);\n },\n };\n tasks.push(taskActionKeyboardPress);\n } else if (plan.type === 'Tap') {\n const taskActionTap: ExecutionTaskActionApply<PlanningActionParamTap> =\n {\n type: 'Action',\n subType: 'Tap',\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, { element }) => {\n assert(element, 'Element not found, cannot tap');\n await this.page.mouse.click(element.center[0], element.center[1]);\n },\n };\n tasks.push(taskActionTap);\n } else if (plan.type === 'Drag') {\n const taskActionDrag: ExecutionTaskActionApply<{\n start_box: { x: number; y: number };\n end_box: { x: number; y: number };\n }> = {\n type: 'Action',\n subType: 'Drag',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n assert(\n taskParam?.start_box && taskParam?.end_box,\n 'No start_box or end_box to drag',\n );\n await this.page.mouse.drag(taskParam.start_box, taskParam.end_box);\n },\n };\n tasks.push(taskActionDrag);\n } else if (plan.type === 'Hover') {\n const taskActionHover: ExecutionTaskActionApply<PlanningActionParamHover> =\n {\n type: 'Action',\n subType: 'Hover',\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, { element }) => {\n assert(element, 'Element not found, cannot hover');\n await this.page.mouse.move(element.center[0], element.center[1]);\n },\n };\n tasks.push(taskActionHover);\n } else if (plan.type === 'Scroll') {\n const taskActionScroll: ExecutionTaskActionApply<PlanningActionParamScroll> =\n {\n type: 'Action',\n subType: 'Scroll',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam, { element }) => {\n const startingPoint = element\n ? {\n left: element.center[0],\n top: element.center[1],\n }\n : undefined;\n const scrollToEventName = taskParam?.scrollType;\n if (scrollToEventName === 'untilTop') {\n await this.page.scrollUntilTop(startingPoint);\n } else if (scrollToEventName === 'untilBottom') {\n await this.page.scrollUntilBottom(startingPoint);\n } else if (scrollToEventName === 'untilRight') {\n await this.page.scrollUntilRight(startingPoint);\n } else if (scrollToEventName === 'untilLeft') {\n await this.page.scrollUntilLeft(startingPoint);\n } else if (scrollToEventName === 'once' || !scrollToEventName) {\n if (\n taskParam?.direction === 'down' ||\n !taskParam ||\n !taskParam.direction\n ) {\n await this.page.scrollDown(\n taskParam?.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'up') {\n await this.page.scrollUp(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'left') {\n await this.page.scrollLeft(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'right') {\n await this.page.scrollRight(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else {\n throw new Error(\n `Unknown scroll direction: ${taskParam.direction}`,\n );\n }\n // until mouse event is done\n await sleep(500);\n } else {\n throw new Error(\n `Unknown scroll event type: ${scrollToEventName}, taskParam: ${JSON.stringify(\n taskParam,\n )}`,\n );\n }\n },\n };\n tasks.push(taskActionScroll);\n } else if (plan.type === 'Sleep') {\n const taskActionSleep: ExecutionTaskActionApply<PlanningActionParamSleep> =\n {\n type: 'Action',\n subType: 'Sleep',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n await sleep(taskParam?.timeMs || 3000);\n },\n };\n tasks.push(taskActionSleep);\n } else if (plan.type === 'Error') {\n const taskActionError: ExecutionTaskActionApply<PlanningActionParamError> =\n {\n type: 'Action',\n subType: 'Error',\n param: plan.param,\n thought: plan.thought || plan.param?.thought,\n locate: plan.locate,\n executor: async () => {\n throw new Error(\n plan?.thought || plan.param?.thought || 'error without thought',\n );\n },\n };\n tasks.push(taskActionError);\n } else if (plan.type === 'ExpectedFalsyCondition') {\n const taskActionFalsyConditionStatement: ExecutionTaskActionApply<null> =\n {\n type: 'Action',\n subType: 'ExpectedFalsyCondition',\n param: null,\n thought: plan.param?.reason,\n locate: plan.locate,\n executor: async () => {\n // console.warn(`[warn]falsy condition: ${plan.thought}`);\n },\n };\n tasks.push(taskActionFalsyConditionStatement);\n } else if (plan.type === 'Finished') {\n const taskActionFinished: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'Finished',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {},\n };\n tasks.push(taskActionFinished);\n } else if (plan.type === 'AndroidHomeButton') {\n const taskActionAndroidHomeButton: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'AndroidHomeButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n // Check if the page has back method (Android devices)\n assert(\n isAndroidPage(this.page),\n 'Cannot use home button on non-Android devices',\n );\n await this.page.home();\n },\n };\n tasks.push(taskActionAndroidHomeButton);\n } else if (plan.type === 'AndroidBackButton') {\n const taskActionAndroidBackButton: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'AndroidBackButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n assert(\n isAndroidPage(this.page),\n 'Cannot use back button on non-Android devices',\n );\n await this.page.back();\n },\n };\n tasks.push(taskActionAndroidBackButton);\n } else if (plan.type === 'AndroidRecentAppsButton') {\n const taskActionAndroidRecentAppsButton: ExecutionTaskActionApply<null> =\n {\n type: 'Action',\n subType: 'AndroidRecentAppsButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n assert(\n isAndroidPage(this.page),\n 'Cannot use recent apps button on non-Android devices',\n );\n await this.page.recentApps();\n },\n };\n tasks.push(taskActionAndroidRecentAppsButton);\n } else {\n throw new Error(`Unknown or unsupported task type: ${plan.type}`);\n }\n });\n\n const wrappedTasks = tasks.map(\n (task: ExecutionTaskApply, index: number) => {\n if (task.type === 'Action') {\n return this.prependExecutorWithScreenshot(\n task,\n index === tasks.length - 1,\n );\n }\n return task;\n },\n );\n\n return {\n tasks: wrappedTasks,\n };\n }\n\n private async setupPlanningContext(executorContext: ExecutorContext) {\n const shotTime = Date.now();\n const pageContext = await this.insight.contextRetrieverFn('locate');\n const recordItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: shotTime,\n screenshot: pageContext.screenshotBase64,\n timing: 'before planning',\n };\n\n executorContext.task.recorder = [recordItem];\n (executorContext.task as ExecutionTaskPlanning).pageContext = pageContext;\n\n return {\n pageContext,\n };\n }\n\n async loadYamlFlowAsPlanning(userInstruction: string, yamlString: string) {\n const taskExecutor = new Executor(taskTitleStr('Action', userInstruction), {\n onTaskStart: this.onTaskStartCallback,\n });\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n locate: null,\n param: {\n userInstruction,\n },\n executor: async (param, executorContext) => {\n await this.setupPlanningContext(executorContext);\n return {\n output: {\n actions: [],\n more_actions_needed_by_instruction: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n };\n },\n };\n\n await taskExecutor.append(task);\n await taskExecutor.flush();\n\n return {\n executor: taskExecutor,\n };\n }\n\n private planningTaskFromPrompt(\n userInstruction: string,\n log?: string,\n actionContext?: string,\n ) {\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'Plan',\n locate: null,\n param: {\n userInstruction,\n log,\n },\n executor: async (param, executorContext) => {\n const startTime = Date.now();\n const { pageContext } =\n await this.setupPlanningContext(executorContext);\n\n const planResult = await plan(param.userInstruction, {\n context: pageContext,\n log: param.log,\n actionContext,\n pageType: this.page.pageType as PageType,\n });\n\n const {\n actions,\n log,\n more_actions_needed_by_instruction,\n error,\n usage,\n rawResponse,\n sleep,\n } = planResult;\n\n executorContext.task.log = {\n rawResponse,\n };\n executorContext.task.usage = usage;\n\n let stopCollecting = false;\n let bboxCollected = false;\n let planParsingError = '';\n const finalActions = (actions || []).reduce<PlanningAction[]>(\n (acc, planningAction) => {\n if (stopCollecting) {\n return acc;\n }\n\n if (planningAction.locate) {\n // we only collect bbox once, let qwen re-locate in the following steps\n if (bboxCollected && planningAction.locate.bbox) {\n // biome-ignore lint/performance/noDelete: <explanation>\n delete planningAction.locate.bbox;\n }\n\n if (planningAction.locate.bbox) {\n bboxCollected = true;\n }\n\n acc.push({\n type: 'Locate',\n locate: planningAction.locate,\n param: null,\n thought: planningAction.locate.prompt,\n });\n } else if (\n ['Tap', 'Hover', 'Input'].includes(planningAction.type)\n ) {\n planParsingError = `invalid planning response: ${JSON.stringify(planningAction)}`;\n // should include locate but get null\n stopCollecting = true;\n return acc;\n }\n acc.push(planningAction);\n return acc;\n },\n [],\n );\n\n if (sleep) {\n const timeNow = Date.now();\n const timeRemaining = sleep - (timeNow - startTime);\n if (timeRemaining > 0) {\n finalActions.push({\n type: 'Sleep',\n param: {\n timeMs: timeRemaining,\n },\n locate: null,\n } as PlanningAction<PlanningActionParamSleep>);\n }\n }\n\n if (finalActions.length === 0) {\n assert(\n !more_actions_needed_by_instruction || sleep,\n error\n ? `Failed to plan: ${error}`\n : planParsingError || 'No plan found',\n );\n }\n\n return {\n output: {\n actions: finalActions,\n more_actions_needed_by_instruction,\n log,\n yamlFlow: planResult.yamlFlow,\n },\n cache: {\n hit: false,\n },\n pageContext,\n };\n },\n };\n\n return task;\n }\n\n private planningTaskToGoal(userInstruction: string) {\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'Plan',\n locate: null,\n param: {\n userInstruction,\n },\n executor: async (param, executorContext) => {\n const { pageContext } =\n await this.setupPlanningContext(executorContext);\n\n const imagePayload = await resizeImageForUiTars(\n pageContext.screenshotBase64,\n pageContext.size,\n );\n\n this.appendConversationHistory({\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: imagePayload,\n },\n },\n ],\n });\n const startTime = Date.now();\n\n const planResult = await vlmPlanning({\n userInstruction: param.userInstruction,\n conversationHistory: this.conversationHistory,\n size: pageContext.size,\n });\n\n const aiCost = Date.now() - startTime;\n const { actions, action_summary } = planResult;\n this.appendConversationHistory({\n role: 'assistant',\n content: action_summary,\n });\n return {\n output: {\n actions,\n thought: actions[0]?.thought,\n actionType: actions[0].type,\n more_actions_needed_by_instruction: true,\n log: '',\n yamlFlow: planResult.yamlFlow,\n },\n cache: {\n hit: false,\n },\n aiCost,\n };\n },\n };\n\n return task;\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n ): Promise<ExecutionResult> {\n const taskExecutor = new Executor(title, {\n onTaskStart: this.onTaskStartCallback,\n });\n const { tasks } = await this.convertPlanToExecutable(plans);\n await taskExecutor.append(tasks);\n const result = await taskExecutor.flush();\n return {\n output: result,\n executor: taskExecutor,\n };\n }\n\n async action(\n userPrompt: string,\n actionContext?: string,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n }\n | undefined\n >\n > {\n const taskExecutor = new Executor(taskTitleStr('Action', userPrompt), {\n onTaskStart: this.onTaskStartCallback,\n });\n\n let planningTask: ExecutionTaskPlanningApply | null =\n this.planningTaskFromPrompt(userPrompt, undefined, actionContext);\n let replanCount = 0;\n const logList: string[] = [];\n\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n while (planningTask) {\n if (replanCount > replanningCountLimit) {\n const errorMsg =\n 'Replanning too many times, please split the task into multiple steps';\n\n return this.appendErrorPlan(taskExecutor, errorMsg);\n }\n\n // plan\n await taskExecutor.append(planningTask);\n const planResult: PlanningAIResponse = await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: planResult,\n executor: taskExecutor,\n };\n }\n\n const plans = planResult.actions || [];\n yamlFlow.push(...(planResult.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(plans);\n taskExecutor.append(executables.tasks);\n } catch (error) {\n return this.appendErrorPlan(\n taskExecutor,\n `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(\n plans,\n )}`,\n );\n }\n\n await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n if (planResult?.log) {\n logList.push(planResult.log);\n }\n\n if (!planResult.more_actions_needed_by_instruction) {\n planningTask = null;\n break;\n }\n planningTask = this.planningTaskFromPrompt(\n userPrompt,\n logList.length > 0 ? `- ${logList.join('\\n- ')}` : undefined,\n actionContext,\n );\n replanCount++;\n }\n\n return {\n output: {\n yamlFlow,\n },\n executor: taskExecutor,\n };\n }\n\n async actionToGoal(userPrompt: string): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n }\n | undefined\n >\n > {\n const taskExecutor = new Executor(taskTitleStr('Action', userPrompt), {\n onTaskStart: this.onTaskStartCallback,\n });\n this.conversationHistory = [];\n const isCompleted = false;\n let currentActionNumber = 0;\n const maxActionNumber = 40;\n\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n while (!isCompleted && currentActionNumber < maxActionNumber) {\n currentActionNumber++;\n const planningTask: ExecutionTaskPlanningApply =\n this.planningTaskToGoal(userPrompt);\n await taskExecutor.append(planningTask);\n const output = await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n const plans = output.actions;\n yamlFlow.push(...(output.yamlFlow || []));\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(plans);\n taskExecutor.append(executables.tasks);\n } catch (error) {\n return this.appendErrorPlan(\n taskExecutor,\n `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(\n plans,\n )}`,\n );\n }\n\n await taskExecutor.flush();\n\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n if (plans[0].type === 'Finished') {\n break;\n }\n }\n return {\n output: {\n yamlFlow,\n },\n executor: taskExecutor,\n };\n }\n\n private async createTypeQueryTask<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String',\n demand: InsightExtractParam,\n ): Promise<ExecutionResult<T>> {\n const taskExecutor = new Executor(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n onTaskStart: this.onTaskStartCallback,\n },\n );\n\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n locate: null,\n param: {\n dataDemand: demand, // for user param presentation in report right sidebar\n },\n executor: async (param) => {\n let insightDump: InsightDump | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n if (ifTypeRestricted) {\n demandInput = {\n result: `${type}, ${demand}`,\n };\n }\n\n const { data, usage } = await this.insight.extract<any>(demandInput);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n assert(data?.result !== undefined, 'No result in query data');\n outputResult = (data as any).result;\n }\n\n return {\n output: outputResult,\n log: { dump: insightDump },\n usage,\n };\n },\n };\n\n await taskExecutor.append(this.prependExecutorWithScreenshot(queryTask));\n const output = await taskExecutor.flush();\n return {\n output,\n executor: taskExecutor,\n };\n }\n\n async query(demand: InsightExtractParam): Promise<ExecutionResult> {\n return this.createTypeQueryTask('Query', demand);\n }\n\n async boolean(prompt: string): Promise<ExecutionResult<boolean>> {\n return this.createTypeQueryTask<boolean>('Boolean', prompt);\n }\n\n async number(prompt: string): Promise<ExecutionResult<number>> {\n return this.createTypeQueryTask<number>('Number', prompt);\n }\n\n async string(prompt: string): Promise<ExecutionResult<string>> {\n return this.createTypeQueryTask<string>('String', prompt);\n }\n\n async assert(\n assertion: string,\n ): Promise<ExecutionResult<InsightAssertionResponse>> {\n const description = `assert: ${assertion}`;\n const taskExecutor = new Executor(taskTitleStr('Assert', description), {\n onTaskStart: this.onTaskStartCallback,\n });\n const assertionPlan: PlanningAction<PlanningActionParamAssert> = {\n type: 'Assert',\n param: {\n assertion,\n },\n locate: null,\n };\n const { tasks } = await this.convertPlanToExecutable([assertionPlan]);\n\n await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));\n const output: InsightAssertionResponse = await taskExecutor.flush();\n\n return {\n output,\n executor: taskExecutor,\n };\n }\n\n /**\n * Append a message to the conversation history\n * For user messages with images:\n * - Keep max 4 user image messages in history\n * - Remove oldest user image message when limit reached\n * For assistant messages:\n * - Simply append to history\n * @param conversationHistory Message to append\n */\n private appendConversationHistory(\n conversationHistory: ChatCompletionMessageParam,\n ) {\n if (conversationHistory.role === 'user') {\n // Get all existing user messages with images\n const userImgItems = this.conversationHistory.filter(\n (item) => item.role === 'user',\n );\n\n // If we already have 4 user image messages\n if (userImgItems.length >= 4 && conversationHistory.role === 'user') {\n // Remove first user image message when we already have 4, before adding new one\n const firstUserImgIndex = this.conversationHistory.findIndex(\n (item) => item.role === 'user',\n );\n if (firstUserImgIndex >= 0) {\n this.conversationHistory.splice(firstUserImgIndex, 1);\n }\n }\n }\n // For non-user messages, simply append to history\n this.conversationHistory.push(conversationHistory);\n }\n\n private async appendErrorPlan(taskExecutor: Executor, errorMsg: string) {\n const errorPlan: PlanningAction<PlanningActionParamError> = {\n type: 'Error',\n param: {\n thought: errorMsg,\n },\n locate: null,\n };\n const { tasks } = await this.convertPlanToExecutable([errorPlan]);\n await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));\n await taskExecutor.flush();\n\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n async waitFor(\n assertion: string,\n opt: PlanningActionParamWaitFor,\n ): Promise<ExecutionResult<void>> {\n const description = `waitFor: ${assertion}`;\n const taskExecutor = new Executor(taskTitleStr('WaitFor', description), {\n onTaskStart: this.onTaskStartCallback,\n });\n const { timeoutMs, checkIntervalMs } = opt;\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n const overallStartTime = Date.now();\n let startTime = Date.now();\n let errorThought = '';\n while (Date.now() - overallStartTime < timeoutMs) {\n startTime = Date.now();\n const assertPlan: PlanningAction<PlanningActionParamAssert> = {\n type: 'AssertWithoutThrow',\n param: {\n assertion,\n },\n locate: null,\n };\n const { tasks: assertTasks } = await this.convertPlanToExecutable([\n assertPlan,\n ]);\n await taskExecutor.append(\n this.prependExecutorWithScreenshot(assertTasks[0]),\n );\n const output: InsightAssertionResponse = await taskExecutor.flush();\n\n if (output?.pass) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n errorThought =\n output?.thought ||\n `unknown error when waiting for assertion: ${assertion}`;\n const now = Date.now();\n if (now - startTime < checkIntervalMs) {\n const timeRemaining = checkIntervalMs - (now - startTime);\n const sleepPlan: PlanningAction<PlanningActionParamSleep> = {\n type: 'Sleep',\n param: {\n timeMs: timeRemaining,\n },\n locate: null,\n };\n const { tasks: sleepTasks } = await this.convertPlanToExecutable([\n sleepPlan,\n ]);\n await taskExecutor.append(\n this.prependExecutorWithScreenshot(sleepTasks[0]),\n );\n await taskExecutor.flush();\n }\n }\n\n return this.appendErrorPlan(\n taskExecutor,\n `waitFor timeout: ${errorThought}`,\n );\n }\n}\n","import type {\n DetailedLocateParam,\n ExecutionTask,\n ExecutionTaskAction,\n ExecutionTaskInsightAssertion,\n ExecutionTaskInsightLocate,\n ExecutionTaskInsightQuery,\n ExecutionTaskPlanning,\n PlanningActionParamScroll,\n} from 'misoai-core';\n\nexport function typeStr(task: ExecutionTask) {\n return task.subType && task.subType !== 'Plan'\n ? `${task.type} / ${task.subType || ''}`\n : task.type;\n}\n\nexport function getKeyCommands(\n value: string | string[],\n): Array<{ key: string; command?: string }> {\n // Ensure value is an array of keys\n const keys = Array.isArray(value) ? value : [value];\n\n // Process each key to attach a corresponding command if needed, based on the presence of 'Meta' or 'Control' in the keys array.\n // ref: https://github.com/puppeteer/puppeteer/pull/9357/files#diff-32cf475237b000f980eb214a0a823e45a902bddb7d2426d677cae96397aa0ae4R94\n return keys.reduce((acc: Array<{ key: string; command?: string }>, k) => {\n const includeMeta = keys.includes('Meta') || keys.includes('Control');\n if (includeMeta && (k === 'a' || k === 'A')) {\n return acc.concat([{ key: k, command: 'SelectAll' }]);\n }\n if (includeMeta && (k === 'c' || k === 'C')) {\n return acc.concat([{ key: k, command: 'Copy' }]);\n }\n if (includeMeta && (k === 'v' || k === 'V')) {\n return acc.concat([{ key: k, command: 'Paste' }]);\n }\n return acc.concat([{ key: k }]);\n }, []);\n}\n\nexport function locateParamStr(locate?: DetailedLocateParam) {\n if (!locate) {\n return '';\n }\n\n if (typeof locate === 'string') {\n return locate;\n }\n\n return locate.prompt;\n}\n\nexport function scrollParamStr(scrollParam?: PlanningActionParamScroll) {\n if (!scrollParam) {\n return '';\n }\n return `${scrollParam.direction || 'down'}, ${scrollParam.scrollType || 'once'}, ${scrollParam.distance || 'distance-not-set'}`;\n}\n\nexport function taskTitleStr(\n type:\n | 'Tap'\n | 'Hover'\n | 'Input'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Action'\n | 'Query'\n | 'Assert'\n | 'WaitFor'\n | 'Locate'\n | 'Boolean'\n | 'Number'\n | 'String',\n prompt: string,\n) {\n if (prompt) {\n return `${type} - ${prompt}`;\n }\n return type;\n}\n\nexport function paramStr(task: ExecutionTask) {\n let value: string | undefined | object;\n if (task.type === 'Planning') {\n value = (task as ExecutionTaskPlanning)?.param?.userInstruction;\n }\n\n if (task.type === 'Insight') {\n value =\n (task as ExecutionTaskInsightLocate)?.param?.prompt ||\n (task as ExecutionTaskInsightLocate)?.param?.id ||\n (task as ExecutionTaskInsightQuery)?.param?.dataDemand ||\n (task as ExecutionTaskInsightAssertion)?.param?.assertion;\n }\n\n if (task.type === 'Action') {\n const locate = (task as ExecutionTaskAction)?.locate;\n const locateStr = locate ? locateParamStr(locate) : '';\n\n value = task.thought || '';\n if (typeof (task as ExecutionTaskAction)?.param?.timeMs === 'number') {\n value = `${(task as ExecutionTaskAction)?.param?.timeMs}ms`;\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.scrollType === 'string'\n ) {\n value = scrollParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.value !== 'undefined'\n ) {\n value = (task as ExecutionTaskAction)?.param?.value;\n }\n\n if (locateStr) {\n if (value) {\n value = `${locateStr} - ${value}`;\n } else {\n value = locateStr;\n }\n }\n }\n\n if (typeof value === 'undefined') return '';\n return typeof value === 'string'\n ? value\n : JSON.stringify(value, undefined, 2);\n}\n\nexport const limitOpenNewTabScript = `\nif (!window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__) {\n window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__ = true;\n\n // Intercept the window.open method (only once)\n window.open = function(url) {\n console.log('Blocked window.open:', url);\n window.location.href = url;\n return null;\n };\n\n // Block all a tag clicks with target=\"_blank\" (only once)\n document.addEventListener('click', function(e) {\n const target = e.target.closest('a');\n if (target && target.target === '_blank') {\n e.preventDefault();\n console.log('Blocked new tab:', target.href);\n window.location.href = target.href;\n target.removeAttribute('target');\n }\n }, true);\n}\n`;\n","import type { StaticPage } from '@/playground';\nimport type {\n BaseElement,\n ElementTreeNode,\n PlanningLocateParam,\n PlaywrightParserOpt,\n UIContext,\n} from 'misoai-core';\nimport { elementByPositionWithElementInfo } from 'misoai-core/ai-model';\nimport { uploadTestInfoToServer } from 'misoai-core/utils';\nimport { MIDSCENE_REPORT_TAG_NAME, getAIConfig } from 'misoai-shared/env';\nimport type { ElementInfo } from 'misoai-shared/extractor';\nimport {\n generateElementByPosition,\n getNodeFromCacheList,\n traverseTree,\n treeToList,\n} from 'misoai-shared/extractor';\nimport { resizeImgBase64 } from 'misoai-shared/img';\nimport type { DebugFunction } from 'misoai-shared/logger';\nimport { assert, logMsg, uuid } from 'misoai-shared/utils';\nimport dayjs from 'dayjs';\nimport type { Page as PlaywrightPage } from 'playwright';\nimport type { Page as PuppeteerPage } from 'puppeteer';\nimport { WebElementInfo } from '../web-element';\nimport type { WebPage } from './page';\n\nexport type WebUIContext = UIContext<WebElementInfo> & {\n url: string;\n};\n\nexport async function parseContextFromWebPage(\n page: WebPage,\n _opt?: PlaywrightParserOpt,\n): Promise<WebUIContext> {\n assert(page, 'page is required');\n if ((page as StaticPage)._forceUsePageContext) {\n return await (page as any)._forceUsePageContext();\n }\n const url = await page.url();\n uploadTestInfoToServer({ testUrl: url });\n\n let screenshotBase64: string;\n let tree: ElementTreeNode<ElementInfo>;\n\n await Promise.all([\n page.screenshotBase64().then((base64) => {\n screenshotBase64 = base64;\n }),\n page.getElementsNodeTree().then(async (treeRoot) => {\n tree = treeRoot;\n }),\n ]);\n\n const webTree = traverseTree(tree!, (elementInfo) => {\n const { rect, id, content, attributes, locator, indexId } = elementInfo;\n return new WebElementInfo({\n rect,\n locator,\n id,\n content,\n attributes,\n indexId,\n });\n });\n\n assert(screenshotBase64!, 'screenshotBase64 is required');\n\n const elementsInfo = treeToList(webTree);\n const size = await page.size();\n\n if (size.dpr && size.dpr > 1) {\n // console.time('resizeImgBase64');\n screenshotBase64 = await resizeImgBase64(screenshotBase64, {\n width: size.width,\n height: size.height,\n });\n // console.timeEnd('resizeImgBase64');\n }\n\n return {\n content: elementsInfo!,\n tree: webTree,\n size,\n screenshotBase64: screenshotBase64!,\n url,\n };\n}\n\nexport function reportFileName(tag = 'web') {\n const reportTagName = getAIConfig(MIDSCENE_REPORT_TAG_NAME);\n const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');\n // ensure uniqueness at the same time\n const uniqueId = uuid().substring(0, 8);\n return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;\n}\n\nexport function printReportMsg(filepath: string) {\n logMsg(`Midscene - report file updated: ${filepath}`);\n}\n\n/**\n * Get the current execution file name\n * @returns The name of the current execution file\n */\nexport function getCurrentExecutionFile(trace?: string): string | false {\n const error = new Error();\n const stackTrace = trace || error.stack;\n const pkgDir = process.cwd() || '';\n if (stackTrace) {\n const stackLines = stackTrace.split('\\n');\n for (const line of stackLines) {\n if (\n line.includes('.spec.') ||\n line.includes('.test.') ||\n line.includes('.ts') ||\n line.includes('.js')\n ) {\n const match = line.match(/(?:at\\s+)?(.*?\\.(?:spec|test)\\.[jt]s)/);\n if (match?.[1]) {\n const targetFileName = match[1]\n .replace(pkgDir, '')\n .trim()\n .replace('at ', '');\n return targetFileName;\n }\n }\n }\n }\n return false;\n}\n\nconst testFileIndex = new Map<string, number>();\n\nexport function generateCacheId(fileName?: string): string {\n let taskFile = fileName || getCurrentExecutionFile();\n if (!taskFile) {\n taskFile = uuid();\n console.warn(\n 'Midscene - using random UUID for cache id. Cache may be invalid.',\n );\n }\n\n if (testFileIndex.has(taskFile)) {\n const currentIndex = testFileIndex.get(taskFile);\n if (currentIndex !== undefined) {\n testFileIndex.set(taskFile, currentIndex + 1);\n }\n } else {\n testFileIndex.set(taskFile, 1);\n }\n return `${taskFile}-${testFileIndex.get(taskFile)}`;\n}\n\nexport const ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED =\n 'NOT_IMPLEMENTED_AS_DESIGNED';\n\nexport function replaceIllegalPathCharsAndSpace(str: string) {\n return str.replace(/[/\\\\:*?\"<>| ]/g, '-');\n}\n\nexport function forceClosePopup(\n page: PuppeteerPage | PlaywrightPage,\n debug: DebugFunction,\n) {\n page.on('popup', async (popup) => {\n if (!popup) {\n console.warn('got a popup event, but the popup is not ready yet, skip');\n return;\n }\n const url = await (popup as PuppeteerPage).url();\n console.log(`Popup opened: ${url}`);\n if (!(popup as PuppeteerPage).isClosed()) {\n try {\n await (popup as PuppeteerPage).close(); // Close the newly opened TAB\n } catch (error) {\n debug(`failed to close popup ${url}, error: ${error}`);\n }\n } else {\n debug(`popup is already closed, skip close ${url}`);\n }\n\n if (!page.isClosed()) {\n try {\n await page.goto(url);\n } catch (error) {\n debug(`failed to goto ${url}, error: ${error}`);\n }\n } else {\n debug(`page is already closed, skip goto ${url}`);\n }\n });\n}\n\nexport function matchElementFromPlan(\n planLocateParam: PlanningLocateParam,\n tree: ElementTreeNode<BaseElement>,\n) {\n if (!planLocateParam) {\n return undefined;\n }\n if (planLocateParam.id) {\n return getNodeFromCacheList(planLocateParam.id);\n }\n\n if (planLocateParam.bbox) {\n const centerPosition = {\n x: Math.floor((planLocateParam.bbox[0] + planLocateParam.bbox[2]) / 2),\n y: Math.floor((planLocateParam.bbox[1] + planLocateParam.bbox[3]) / 2),\n };\n let element = elementByPositionWithElementInfo(tree, centerPosition);\n\n if (!element) {\n element = generateElementByPosition(centerPosition) as BaseElement;\n }\n\n return element;\n }\n\n return undefined;\n}\n","import type { BaseElement, Rect } from 'misoai-core';\nimport type { NodeType } from 'misoai-shared/constants';\nexport interface WebElementInfoType extends BaseElement {\n id: string;\n locator: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n}\n\nexport class WebElementInfo implements BaseElement {\n content: string;\n\n locator?: string;\n\n rect: Rect;\n\n center: [number, number];\n\n // page: WebPage;\n\n id: string;\n\n indexId: number;\n\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n\n xpaths?: string[];\n\n constructor({\n content,\n rect,\n // page,\n locator,\n id,\n attributes,\n indexId,\n xpaths,\n }: {\n content: string;\n rect: Rect;\n // page: WebPage;\n locator?: string;\n id: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n indexId: number;\n xpaths?: string[];\n }) {\n this.content = content;\n this.rect = rect;\n this.center = [\n Math.floor(rect.left + rect.width / 2),\n Math.floor(rect.top + rect.height / 2),\n ];\n // this.page = page;\n this.locator = locator;\n this.id = id;\n this.attributes = attributes;\n this.indexId = indexId;\n this.xpaths = xpaths;\n }\n}\n","import type {\n DetailedLocateParam,\n MidsceneYamlFlowItem,\n PlanningAction,\n PlanningActionParamInputOrKeyPress,\n PlanningActionParamScroll,\n PlanningActionParamSleep,\n PlanningActionParamTap,\n PlanningLocateParam,\n} from 'misoai-core';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\n\nconst debug = getDebug('plan-builder');\n\nexport function buildPlans(\n type: PlanningAction['type'],\n locateParam?: DetailedLocateParam,\n param?:\n | PlanningActionParamInputOrKeyPress\n | PlanningActionParamScroll\n | PlanningActionParamSleep,\n): PlanningAction[] {\n let returnPlans: PlanningAction[] = [];\n const locatePlan: PlanningAction<PlanningLocateParam> | null = locateParam\n ? {\n type: 'Locate',\n locate: locateParam,\n param: locateParam,\n thought: '',\n }\n : null;\n if (type === 'Tap' || type === 'Hover') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n assert(locatePlan, `missing locate info for action \"${type}\"`);\n const tapPlan: PlanningAction<PlanningActionParamTap> = {\n type,\n param: null,\n thought: '',\n locate: locateParam,\n };\n\n returnPlans = [locatePlan, tapPlan];\n }\n if (type === 'Input' || type === 'KeyboardPress') {\n if (type === 'Input') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n }\n assert(param, `missing param for action \"${type}\"`);\n\n const inputPlan: PlanningAction<PlanningActionParamInputOrKeyPress> = {\n type,\n param: param as PlanningActionParamInputOrKeyPress,\n thought: '',\n locate: locateParam!,\n };\n\n if (locatePlan) {\n returnPlans = [locatePlan, inputPlan];\n } else {\n returnPlans = [inputPlan];\n }\n }\n\n if (type === 'Scroll') {\n assert(param, `missing param for action \"${type}\"`);\n\n const scrollPlan: PlanningAction<PlanningActionParamScroll> = {\n type,\n param: param as PlanningActionParamScroll,\n thought: '',\n locate: locateParam,\n };\n\n if (locatePlan) {\n returnPlans = [locatePlan, scrollPlan];\n } else {\n returnPlans = [scrollPlan];\n }\n }\n\n if (type === 'Sleep') {\n assert(param, `missing param for action \"${type}\"`);\n\n const sleepPlan: PlanningAction<PlanningActionParamSleep> = {\n type,\n param: param as PlanningActionParamSleep,\n thought: '',\n locate: null,\n };\n\n returnPlans = [sleepPlan];\n }\n\n if (type === 'Locate') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n const locatePlan: PlanningAction<PlanningLocateParam> = {\n type,\n param: locateParam as PlanningLocateParam,\n locate: locateParam,\n thought: '',\n };\n returnPlans = [locatePlan];\n }\n\n if (returnPlans) {\n debug('buildPlans', returnPlans);\n return returnPlans;\n }\n\n throw new Error(`Not supported type: ${type}`);\n}\n","import assert from 'node:assert';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getMidsceneRunSubDir } from 'misoai-shared/common';\nimport { getDebug } from 'misoai-shared/logger';\nimport { ifInBrowser } from 'misoai-shared/utils';\nimport yaml from 'js-yaml';\nimport semver from 'semver';\nimport { version } from '../../package.json';\nimport { replaceIllegalPathCharsAndSpace } from './utils';\n\nconst debug = getDebug('cache');\n\nexport interface PlanningCache {\n type: 'plan';\n prompt: string;\n yamlWorkflow: string;\n}\n\nexport interface LocateCache {\n type: 'locate';\n prompt: string;\n xpaths: string[];\n}\n\nexport interface MatchCacheResult<T extends PlanningCache | LocateCache> {\n cacheContent: T;\n updateFn: (cb: (cache: T) => void) => void;\n}\n\nexport type CacheFileContent = {\n midsceneVersion: string;\n cacheId: string;\n caches: Array<PlanningCache | LocateCache>;\n};\n\nconst lowestSupportedMidsceneVersion = '0.16.10';\nconst cacheFileExt = '.cache.yaml';\n\nexport class TaskCache {\n cacheId: string;\n\n cacheFilePath?: string;\n\n cache: CacheFileContent;\n\n isCacheResultUsed: boolean; // a flag to indicate if the cache result should be used\n cacheOriginalLength: number;\n\n private matchedCacheIndices: Set<string> = new Set(); // Track matched records\n\n constructor(\n cacheId: string,\n isCacheResultUsed: boolean,\n cacheFilePath?: string,\n ) {\n assert(cacheId, 'cacheId is required');\n this.cacheId = replaceIllegalPathCharsAndSpace(cacheId);\n\n this.cacheFilePath = ifInBrowser\n ? undefined\n : cacheFilePath ||\n join(getMidsceneRunSubDir('cache'), `${this.cacheId}${cacheFileExt}`);\n\n this.isCacheResultUsed = isCacheResultUsed;\n\n let cacheContent;\n if (this.cacheFilePath) {\n cacheContent = this.loadCacheFromFile();\n }\n if (!cacheContent) {\n cacheContent = {\n midsceneVersion: version,\n cacheId: this.cacheId,\n caches: [],\n };\n }\n this.cache = cacheContent;\n this.cacheOriginalLength = this.cache.caches.length;\n }\n\n matchCache(\n prompt: string,\n type: 'plan' | 'locate',\n ): MatchCacheResult<PlanningCache | LocateCache> | undefined {\n // Find the first unused matching cache\n for (let i = 0; i < this.cacheOriginalLength; i++) {\n const item = this.cache.caches[i];\n const key = `${type}:${prompt}:${i}`;\n if (\n item.type === type &&\n item.prompt === prompt &&\n !this.matchedCacheIndices.has(key)\n ) {\n this.matchedCacheIndices.add(key);\n debug(\n 'cache found and marked as used, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n return {\n cacheContent: item,\n updateFn: (cb: (cache: PlanningCache | LocateCache) => void) => {\n debug(\n 'will call updateFn to update cache, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n cb(item);\n debug(\n 'cache updated, will flush to file, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n this.flushCacheToFile();\n },\n };\n }\n }\n debug('no unused cache found, type: %s, prompt: %s', type, prompt);\n return undefined;\n }\n\n matchPlanCache(prompt: string): MatchCacheResult<PlanningCache> | undefined {\n return this.matchCache(prompt, 'plan') as\n | MatchCacheResult<PlanningCache>\n | undefined;\n }\n\n matchLocateCache(prompt: string): MatchCacheResult<LocateCache> | undefined {\n return this.matchCache(prompt, 'locate') as\n | MatchCacheResult<LocateCache>\n | undefined;\n }\n\n appendCache(cache: PlanningCache | LocateCache) {\n debug('will append cache', cache);\n this.cache.caches.push(cache);\n this.flushCacheToFile();\n }\n\n loadCacheFromFile() {\n const cacheFile = this.cacheFilePath;\n assert(cacheFile, 'cache file path is required');\n\n if (!existsSync(cacheFile)) {\n debug('no cache file found, path: %s', cacheFile);\n return undefined;\n }\n\n // detect old cache file\n const jsonTypeCacheFile = cacheFile.replace(cacheFileExt, '.json');\n if (existsSync(jsonTypeCacheFile) && this.isCacheResultUsed) {\n console.warn(\n `An outdated cache file from an earlier version of Midscene has been detected. Since version 0.17, we have implemented an improved caching strategy. Please delete the old file located at: ${jsonTypeCacheFile}.`,\n );\n return undefined;\n }\n\n try {\n const data = readFileSync(cacheFile, 'utf8');\n const jsonData = yaml.load(data) as CacheFileContent;\n\n if (!version) {\n debug('no midscene version info, will not read cache from file');\n return undefined;\n }\n\n if (\n semver.lt(jsonData.midsceneVersion, lowestSupportedMidsceneVersion) &&\n !jsonData.midsceneVersion.includes('beta') // for internal test\n ) {\n console.warn(\n `You are using an old version of Midscene cache file, and we cannot match any info from it. Starting from Midscene v0.17, we changed our strategy to use xpath for cache info, providing better performance.\\nPlease delete the existing cache and rebuild it. Sorry for the inconvenience.\\ncache file: ${cacheFile}`,\n );\n return undefined;\n }\n\n debug(\n 'cache loaded from file, path: %s, cache version: %s, record length: %s',\n cacheFile,\n jsonData.midsceneVersion,\n jsonData.caches.length,\n );\n jsonData.midsceneVersion = version; // update the version\n return jsonData;\n } catch (err) {\n debug(\n 'cache file exists but load failed, path: %s, error: %s',\n cacheFile,\n err,\n );\n return undefined;\n }\n }\n\n flushCacheToFile() {\n if (!version) {\n debug('no midscene version info, will not write cache to file');\n return;\n }\n\n if (!this.cacheFilePath) {\n debug('no cache file path, will not write cache to file');\n return;\n }\n\n try {\n const yamlData = yaml.dump(this.cache);\n writeFileSync(this.cacheFilePath, yamlData);\n } catch (err) {\n debug(\n 'write cache to file failed, path: %s, error: %s',\n this.cacheFilePath,\n err,\n );\n }\n }\n\n updateOrAppendCacheRecord(\n newRecord: PlanningCache | LocateCache,\n cachedRecord?: MatchCacheResult<PlanningCache | LocateCache>,\n ) {\n if (cachedRecord) {\n // update existing record\n if (newRecord.type === 'plan') {\n cachedRecord.updateFn((cache) => {\n (cache as PlanningCache).yamlWorkflow = newRecord.yamlWorkflow;\n });\n } else {\n cachedRecord.updateFn((cache) => {\n (cache as LocateCache).xpaths = newRecord.xpaths;\n });\n }\n } else {\n this.appendCache(newRecord);\n }\n }\n}\n","{\n \"name\": \"misoai-web\",\n \"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.\",\n \"keywords\": [\n \"AI UI automation\",\n \"AI testing\",\n \"Computer use\",\n \"Browser use\",\n \"Android use\"\n ],\n \"version\": \"1.0.0\",\n \"repository\": \"https://github.com/web-infra-dev/midscene\",\n \"homepage\": \"https://midscenejs.com/\",\n \"jsnext:source\": \"./src/index.ts\",\n \"main\": \"./dist/lib/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"bin\": {\n \"misoai-playground\": \"./bin/midscene-playground\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"default\": \"./dist/lib/index.js\"\n },\n \"./bridge-mode\": {\n \"types\": \"./dist/types/bridge-mode.d.ts\",\n \"default\": \"./dist/lib/bridge-mode.js\"\n },\n \"./bridge-mode-browser\": {\n \"types\": \"./dist/types/bridge-mode-browser.d.ts\",\n \"default\": \"./dist/lib/bridge-mode-browser.js\"\n },\n \"./utils\": {\n \"types\": \"./dist/types/utils.d.ts\",\n \"default\": \"./dist/lib/utils.js\"\n },\n \"./ui-utils\": {\n \"types\": \"./dist/types/ui-utils.d.ts\",\n \"default\": \"./dist/lib/ui-utils.js\"\n },\n \"./puppeteer\": {\n \"types\": \"./dist/types/puppeteer.d.ts\",\n \"default\": \"./dist/lib/puppeteer.js\"\n },\n \"./puppeteer-agent-launcher\": {\n \"types\": \"./dist/types/puppeteer-agent-launcher.d.ts\",\n \"default\": \"./dist/lib/puppeteer-agent-launcher.js\"\n },\n \"./playwright\": {\n \"types\": \"./dist/types/playwright.d.ts\",\n \"default\": \"./dist/lib/playwright.js\"\n },\n \"./playwright-report\": {\n \"types\": \"./dist/types/playwright-report.d.ts\",\n \"default\": \"./dist/lib/playwright-report.js\"\n },\n \"./playground\": {\n \"types\": \"./dist/types/playground.d.ts\",\n \"default\": \"./dist/lib/playground.js\"\n },\n \"./midscene-playground\": {\n \"types\": \"./dist/types/midscene-playground.d.ts\",\n \"default\": \"./dist/lib/midscene-playground.js\"\n },\n \"./midscene-server\": {\n \"types\": \"./dist/types/midscene-server.d.ts\",\n \"default\": \"./dist/lib/midscene-server.js\"\n },\n \"./chrome-extension\": {\n \"types\": \"./dist/types/chrome-extension.d.ts\",\n \"default\": \"./dist/lib/chrome-extension.js\"\n },\n \"./yaml\": {\n \"types\": \"./dist/types/yaml.d.ts\",\n \"default\": \"./dist/lib/yaml.js\"\n },\n \"./agent\": {\n \"types\": \"./dist/types/agent.d.ts\",\n \"default\": \"./dist/lib/agent.js\"\n }\n },\n \"typesVersions\": {\n \"*\": {\n \".\": [\n \"./dist/types/index.d.ts\"\n ],\n \"bridge-mode\": [\n \"./dist/types/bridge-mode.d.ts\"\n ],\n \"bridge-mode-browser\": [\n \"./dist/types/bridge-mode-browser.d.ts\"\n ],\n \"utils\": [\n \"./dist/types/utils.d.ts\"\n ],\n \"ui-utils\": [\n \"./dist/types/ui-utils.d.ts\"\n ],\n \"puppeteer\": [\n \"./dist/types/puppeteer.d.ts\"\n ],\n \"puppeteer-agent-launcher\": [\n \"./dist/types/puppeteer-agent-launcher.d.ts\"\n ],\n \"playwright\": [\n \"./dist/types/playwright.d.ts\"\n ],\n \"playwright-report\": [\n \"./dist/types/playwright-report.d.ts\"\n ],\n \"playground\": [\n \"./dist/types/playground.d.ts\"\n ],\n \"midscene-playground\": [\n \"./dist/types/midscene-playground.d.ts\"\n ],\n \"midscene-server\": [\n \"./dist/types/midscene-server.d.ts\"\n ],\n \"chrome-extension\": [\n \"./dist/types/chrome-extension.d.ts\"\n ],\n \"yaml\": [\n \"./dist/types/yaml.d.ts\"\n ],\n \"agent\": [\n \"./dist/types/agent.d.ts\"\n ]\n }\n },\n \"watch\": {\n \"build\": {\n \"patterns\": [\n \"src\"\n ],\n \"extensions\": \"tsx,less,scss,css,js,jsx,ts\",\n \"quiet\": false\n }\n },\n \"scripts\": {\n \"dev\": \"npm run build && npx npm-watch\",\n \"dev:server\": \"npm run build && ./bin/midscene-playground\",\n \"build\": \"modern build -c ./modern.config.ts\",\n \"postbuild\": \"node scripts/check-exports.js\",\n \"build:watch\": \"modern build -w -c ./modern.config.ts\",\n \"test\": \"vitest --run\",\n \"test:u\": \"vitest --run -u\",\n \"test:ai\": \"AI_TEST_TYPE=web npm run test\",\n \"test:ai:temp\": \"MIDSCENE_CACHE=true BRIDGE_MODE=true vitest --run tests/ai/bridge/open-new-tab.test.ts\",\n \"test:ai:bridge\": \"MIDSCENE_CACHE=true BRIDGE_MODE=true npm run test --inspect tests/ai/bridge/temp.test.ts\",\n \"test:ai:cache\": \"MIDSCENE_CACHE=true npm run test\",\n \"upgrade\": \"modern upgrade\",\n \"e2e\": \"playwright test --config=tests/playwright.config.ts\",\n \"e2e:report\": \"MIDSCENE_REPORT=true playwright test --config=tests/playwright.config.ts\",\n \"e2e:cache\": \"MIDSCENE_CACHE=true playwright test --config=tests/playwright.config.ts\",\n \"e2e:ui\": \"playwright test --config=tests/playwright.config.ts --ui\",\n \"e2e:ui:cache\": \"MIDSCENE_CACHE=true playwright test --config=tests/playwright.config.ts --ui\"\n },\n \"files\": [\n \"static\",\n \"dist\",\n \"iife-script\",\n \"README.md\",\n \"bin\"\n ],\n \"dependencies\": {\n \"misoai-core\": \"1.0.0\",\n \"misoai-shared\": \"1.0.0\",\n \"@xmldom/xmldom\": \"0.8.10\",\n \"cors\": \"2.8.5\",\n \"dayjs\": \"1.11.11\",\n \"devtools-protocol\": \"0.0.1380148\",\n \"dotenv\": \"16.4.5\",\n \"express\": \"^4.21.2\",\n \"fs-extra\": \"11.2.0\",\n \"http-server\": \"14.1.1\",\n \"inquirer\": \"10.1.5\",\n \"js-sha256\": \"0.11.0\",\n \"js-yaml\": \"4.1.0\",\n \"openai\": \"4.81.0\",\n \"semver\": \"7.5.2\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"4.8.1\"\n },\n \"devDependencies\": {\n \"@modern-js/module-tools\": \"2.60.6\",\n \"@playwright/test\": \"^1.44.1\",\n \"@types/chrome\": \"0.0.279\",\n \"@types/cors\": \"2.8.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/fs-extra\": \"11.0.4\",\n \"@types/js-yaml\": \"4.0.9\",\n \"@types/node\": \"^18.0.0\",\n \"@types/semver\": \"7.7.0\",\n \"playwright\": \"1.44.1\",\n \"puppeteer\": \"24.2.0\",\n \"typescript\": \"^5.8.2\",\n \"vitest\": \"3.0.5\"\n },\n \"peerDependencies\": {\n \"@playwright/test\": \"^1.44.1\",\n \"playwright\": \"1.44.1\",\n \"puppeteer\": \"24.2.0\"\n },\n \"peerDependenciesMeta\": {\n \"@playwright/test\": {\n \"optional\": true\n },\n \"puppeteer\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org\"\n },\n \"license\": \"MIT\"\n}\n"]}
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,IAAAA,sBAAwB;AAoFxB,IAAAC,kBAAiB;;;ACzGjB,qBAAqD;AACrD,uBAAuC;AACvC,mBAAoC;AAyBpC,oBAAqC;AAE9B,IAAM,eAAN,MAAoD;AAAA,EAWzD,YACU,QACA,YAID,oBACP;AANQ;AACA;AAID;AAfT,SAAO,iBAA2C,CAAC;AACnD,SAAO,SAAkC;AAGzC,SAAQ,qBAAqB;AAG7B,SAAQ,YAA8B;AAUpC,SAAK,SAAS,CAAC;AAEf,QAAI,0BAAa;AACf,WAAK,SAAS;AAAA,IAChB,WAAW,OAAO,QAAQ,QAAQ;AAChC,WAAK,aAAS,0BAAQ,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAAA,IAC3D,OAAO;AACL,WAAK,aAAS,2BAAK,oCAAqB,QAAQ,GAAG,GAAG,QAAQ,GAAG,OAAO;AAAA,IAC1E;AAEA,SAAK,kBAAkB,OAAO,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,eAAe;AAAA,MACnE,GAAG;AAAA,MACH,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,YAAY,KAAK,MAAM,UAAU;AAAA,IACnC,E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1B;AACF","names":["import_misoai_core","import_js_yaml","resolve","import_utils","yaml","import_constants","import_env","import_logger","import_ai_model","dayjs","plan","element","log","sleep","debug","locatePlan","import_node_fs","import_node_path","import_common","assert","semver","executor","metadata"],"ignoreList":[],"sources":["../../src/common/agent.ts","../../src/yaml/player.ts","../../src/yaml/builder.ts","../../src/yaml/utils.ts","../../src/common/tasks.ts","../../src/common/ui-utils.ts","../../src/common/utils.ts","../../src/web-element.ts","../../src/common/plan-builder.ts","../../src/common/task-cache.ts","../../package.json"],"sourcesContent":["import type { WebPage } from '@/common/page';\nimport type {\n AgentAssertOpt,\n AgentDescribeElementAtPointResult,\n AgentWaitForOpt,\n AICaptchaResponse,\n AIUsageInfo,\n DetailedLocateParam,\n ExecutionDump,\n ExecutionTask,\n Executor,\n GroupedActionDump,\n InsightAction,\n LocateOption,\n LocateResultElement,\n LocateValidatorResult,\n LocatorValidatorOption,\n OnTaskStartTip,\n PlanningActionParamScroll,\n Rect,\n} from 'misoai-core';\nimport { Insight } from 'misoai-core';\n\n/**\n * Metadata for AI task execution\n */\nexport interface AITaskMetadata {\n /** Status of the task (pending, running, finished, failed, cancelled) */\n status?: string;\n /** Timestamp when the task started */\n start?: number;\n /** Timestamp when the task ended */\n end?: number;\n /** Total time taken to execute the task in milliseconds */\n totalTime?: number;\n /** Cache information */\n cache?: { hit: boolean };\n /** Token usage information */\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n [key: string]: any;\n };\n /** DeepThink information */\n deepthink?: {\n used: boolean;\n mode: string;\n [key: string]: any;\n };\n /** AI's thought process */\n thought?: string;\n /** Element location information */\n locate?: any;\n /** Action plans */\n plan?: any;\n /** Planning information */\n planning?: {\n type: string;\n description: string;\n steps: string[];\n };\n /** Insight information */\n insight?: {\n type: string;\n description: string;\n elements: string[];\n };\n /** Action information */\n action?: {\n type: string;\n description: string;\n result: any;\n };\n /** Action details */\n actionDetails?: Array<{\n type: string;\n subType?: string;\n status: string;\n thought?: string;\n }>;\n /** Task details */\n tasks?: Array<{\n type: string;\n subType?: string;\n status: string;\n thought?: string;\n locate?: any;\n timing?: any;\n usage?: any;\n cache?: any;\n error?: string;\n }>;\n}\n\n/**\n * Result of an AI task with metadata\n */\nexport interface AITaskResult<T = any> {\n /** The actual result of the operation */\n result: T;\n /** Metadata about the task execution */\n metadata: AITaskMetadata;\n}\n\nimport yaml from 'js-yaml';\n\nimport { ScriptPlayer, parseYamlScript } from '@/yaml/index';\nimport {\n groupedActionDumpFileExt,\n reportHTMLContent,\n stringifyDumpData,\n writeLogFile,\n} from 'misoai-core/utils';\nimport {\n DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT,\n DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT,\n} from 'misoai-shared/constants';\nimport { getAIConfigInBoolean, vlLocateMode } from 'misoai-shared/env';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\nimport { PageTaskExecutor } from '../common/tasks';\nimport type { PuppeteerWebPage } from '../puppeteer';\nimport type { WebElementInfo } from '../web-element';\nimport { buildPlans } from './plan-builder';\nimport { TaskCache } from './task-cache';\nimport {\n locateParamStr,\n paramStr,\n scrollParamStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport { printReportMsg, reportFileName } from './utils';\nimport { type WebUIContext, parseContextFromWebPage } from './utils';\n\nconst debug = getDebug('web-integration');\n\nconst distanceOfTwoPoints = (p1: [number, number], p2: [number, number]) => {\n const [x1, y1] = p1;\n const [x2, y2] = p2;\n return Math.round(Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2));\n};\n\nconst includedInRect = (point: [number, number], rect: Rect) => {\n const [x, y] = point;\n const { left, top, width, height } = rect;\n return x >= left && x <= left + width && y >= top && y <= top + height;\n};\n\nexport interface PageAgentOpt {\n forceSameTabNavigation?: boolean /* if limit the new tab to the current page, default true */;\n testId?: string;\n cacheId?: string;\n groupName?: string;\n groupDescription?: string;\n /* if auto generate report, default true */\n generateReport?: boolean;\n /* if auto print report msg, default true */\n autoPrintReportMsg?: boolean;\n onTaskStartTip?: OnTaskStartTip;\n aiActionContext?: string;\n waitForNavigationTimeout?: number;\n waitForNetworkIdleTimeout?: number;\n}\n\nexport class PageAgent<PageType extends WebPage = WebPage> {\n page: PageType;\n\n insight: Insight<WebElementInfo, WebUIContext>;\n\n dump: GroupedActionDump;\n\n reportFile?: string | null;\n\n reportFileName?: string;\n\n taskExecutor: PageTaskExecutor;\n\n opts: PageAgentOpt;\n\n /**\n * If true, the agent will not perform any actions\n */\n dryMode = false;\n\n onTaskStartTip?: OnTaskStartTip;\n\n taskCache?: TaskCache;\n\n constructor(page: PageType, opts?: PageAgentOpt) {\n this.page = page;\n this.opts = Object.assign(\n {\n generateReport: true,\n autoPrintReportMsg: true,\n groupName: 'Midscene Report',\n groupDescription: '',\n },\n opts || {},\n );\n\n if (\n this.page.pageType === 'puppeteer' ||\n this.page.pageType === 'playwright'\n ) {\n (this.page as PuppeteerWebPage).waitForNavigationTimeout =\n this.opts.waitForNavigationTimeout ||\n DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT;\n (this.page as PuppeteerWebPage).waitForNetworkIdleTimeout =\n this.opts.waitForNetworkIdleTimeout ||\n DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT;\n }\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n // get the parent browser of the puppeteer page\n // const browser = (this.page as PuppeteerWebPage).browser();\n\n this.insight = new Insight<WebElementInfo, WebUIContext>(\n async (action: InsightAction) => {\n return this.getUIContext(action);\n },\n );\n\n if (opts?.cacheId && this.page.pageType !== 'android') {\n this.taskCache = new TaskCache(\n opts.cacheId,\n getAIConfigInBoolean('MIDSCENE_CACHE'), // if we should use cache to match the element\n );\n }\n\n this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n });\n this.dump = this.resetDump();\n this.reportFileName = reportFileName(\n opts?.testId || this.page.pageType || 'web',\n );\n }\n\n async getUIContext(action?: InsightAction): Promise<WebUIContext> {\n if (action && (action === 'extract' || action === 'assert' || action === 'captcha')) {\n return await parseContextFromWebPage(this.page, {\n ignoreMarker: true,\n });\n }\n return await parseContextFromWebPage(this.page, {\n ignoreMarker: !!vlLocateMode(),\n });\n }\n\n // Helper method to call the insight.captcha method\n private async _callInsightCaptcha(options?: { deepThink?: boolean }): Promise<{ content: AICaptchaResponse; usage?: AIUsageInfo; deepThink?: boolean }> {\n // This is a workaround for TypeScript type checking\n // We know that insight.captcha exists because we added it\n const context = await this.getUIContext();\n\n // Include the current page URL in the context for better CAPTCHA analysis\n if (this.page.url) {\n const url = await this.page.url();\n context.url = url;\n }\n\n return (this.insight as any).captcha(context, options);\n }\n\n async setAIActionContext(prompt: string) {\n this.opts.aiActionContext = prompt;\n }\n\n resetDump() {\n this.dump = {\n groupName: this.opts.groupName!,\n groupDescription: this.opts.groupDescription,\n executions: [],\n };\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump) {\n const currentDump = this.dump;\n currentDump.executions.push(execution);\n }\n\n dumpDataString() {\n // update dump info\n this.dump.groupName = this.opts.groupName!;\n this.dump.groupDescription = this.opts.groupDescription;\n return stringifyDumpData(this.dump);\n }\n\n reportHTMLString() {\n return reportHTMLContent(this.dumpDataString());\n }\n\n writeOutActionDumps() {\n const { generateReport, autoPrintReportMsg } = this.opts;\n this.reportFile = writeLogFile({\n fileName: this.reportFileName!,\n fileExt: groupedActionDumpFileExt,\n fileContent: this.dumpDataString(),\n type: 'dump',\n generateReport,\n });\n debug('writeOutActionDumps', this.reportFile);\n if (generateReport && autoPrintReportMsg && this.reportFile) {\n printReportMsg(this.reportFile);\n }\n }\n\n private async callbackOnTaskStartTip(task: ExecutionTask) {\n const param = paramStr(task);\n const tip = param ? `${typeStr(task)} - ${param}` : typeStr(task);\n\n if (this.onTaskStartTip) {\n await this.onTaskStartTip(tip);\n }\n }\n\n private afterTaskRunning(executor: Executor, doNotThrowError = false) {\n // Always collect execution data for metadata\n this.appendExecutionDump(executor.dump());\n\n // Only write out dumps if not using Puppeteer\n this.writeOutActionDumps();\n\n if (executor.isInErrorState() && !doNotThrowError) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}`);\n }\n\n // Extract metadata from the executor\n const lastTask = executor.tasks[executor.tasks.length - 1];\n\n // Collect all tasks' thoughts and plans\n const allThoughts = executor.tasks\n .filter(task => task.thought)\n .map(task => task.thought);\n\n // Collect all locate information\n const allLocates = executor.tasks\n .filter(task => task.locate)\n .map(task => task.locate);\n\n // Collect all plans\n const allPlans = executor.tasks\n .filter(task => task.param?.plans)\n .map(task => task.param?.plans);\n\n // Collect tasks by type\n const planningTasks = executor.tasks.filter(task => task.type === 'Planning');\n const insightTasks = executor.tasks.filter(task => task.type === 'Insight');\n const actionTasks = executor.tasks.filter(task => task.type === 'Action');\n\n // Create planning, insight, and action information\n const planning = planningTasks.length > 0 ? {\n type: \"Planning\",\n description: `Planning for task execution`,\n steps: planningTasks.map(task => task.thought || 'Planning step')\n } : undefined;\n\n const insight = insightTasks.length > 0 ? {\n type: \"Insight\",\n description: `Insight for task execution`,\n elements: insightTasks.map(task => task.thought || 'Insight element')\n } : undefined;\n\n const action = actionTasks.length > 0 ? {\n type: \"Action\",\n description: `Action for task execution`,\n result: lastTask?.output\n } : undefined;\n\n // Create action details\n const actionDetails = executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought\n }));\n\n // Extract detailed information from all tasks\n const metadata: AITaskMetadata = {\n status: lastTask?.status,\n start: lastTask?.timing?.start,\n end: lastTask?.timing?.end,\n totalTime: lastTask?.timing?.cost,\n cache: lastTask?.cache,\n usage: lastTask?.usage,\n thought: allThoughts.length > 0 ? allThoughts.join('\\n') : lastTask?.thought,\n locate: allLocates.length > 0 ? allLocates : lastTask?.locate,\n plan: allPlans.length > 0 ? allPlans : lastTask?.param?.plans,\n // Add planning, insight, and action information\n planning,\n insight,\n action,\n actionDetails,\n // Include raw tasks for debugging\n tasks: executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought,\n locate: task.locate,\n timing: task.timing,\n usage: task.usage,\n cache: task.cache,\n error: task.error\n }))\n };\n\n return metadata;\n }\n\n private buildDetailedLocateParam(\n locatePrompt: string,\n opt?: LocateOption,\n ): DetailedLocateParam {\n assert(locatePrompt, 'missing locate prompt');\n if (typeof opt === 'object') {\n const prompt = opt.prompt || locatePrompt;\n const deepThink = opt.deepThink || false;\n const cacheable = opt.cacheable || true;\n return {\n prompt,\n deepThink,\n cacheable,\n };\n }\n return {\n prompt: locatePrompt,\n };\n }\n\n async aiTap(locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Tap', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Tap', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiHover(locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Hover', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Hover', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiInput(value: string, locatePrompt: string, opt?: LocateOption): Promise<AITaskResult> {\n assert(\n typeof value === 'string',\n 'input value must be a string, use empty string if you want to clear the input',\n );\n assert(locatePrompt, 'missing locate prompt for input');\n const detailedLocateParam = this.buildDetailedLocateParam(\n locatePrompt,\n opt,\n );\n const plans = buildPlans('Input', detailedLocateParam, {\n value,\n });\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Input', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiKeyboardPress(\n keyName: string,\n locatePrompt?: string,\n opt?: LocateOption,\n ): Promise<AITaskResult> {\n assert(keyName, 'missing keyName for keyboard press');\n const detailedLocateParam = locatePrompt\n ? this.buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n const plans = buildPlans('KeyboardPress', detailedLocateParam, {\n value: keyName,\n });\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('KeyboardPress', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiScroll(\n scrollParam: PlanningActionParamScroll,\n locatePrompt?: string,\n opt?: LocateOption,\n ): Promise<AITaskResult> {\n const detailedLocateParam = locatePrompt\n ? this.buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n const plans = buildPlans('Scroll', detailedLocateParam, scrollParam);\n const paramInTitle = locatePrompt\n ? `${locateParamStr(detailedLocateParam)} - ${scrollParamStr(scrollParam)}`\n : scrollParamStr(scrollParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Scroll', paramInTitle),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n return {\n result: output,\n metadata,\n };\n }\n\n async aiAction(\n taskPrompt: string,\n opt?: {\n cacheable?: boolean;\n },\n ): Promise<AITaskResult> {\n const cacheable = opt?.cacheable;\n // if vlm-ui-tars, plan cache is not used\n const isVlmUiTars = vlLocateMode() === 'vlm-ui-tars';\n const matchedCache =\n isVlmUiTars || cacheable === false\n ? undefined\n : this.taskCache?.matchPlanCache(taskPrompt);\n if (matchedCache && this.taskCache?.isCacheResultUsed) {\n // log into report file\n const { executor } = await this.taskExecutor.loadYamlFlowAsPlanning(\n taskPrompt,\n matchedCache.cacheContent?.yamlWorkflow,\n );\n\n const metadata = this.afterTaskRunning(executor);\n\n debug('matched cache, will call .runYaml to run the action');\n const yaml = matchedCache.cacheContent?.yamlWorkflow;\n const result = await this.runYaml(yaml);\n return {\n result: result.result,\n metadata\n };\n }\n\n const { output, executor } = await (isVlmUiTars\n ? this.taskExecutor.actionToGoal(taskPrompt)\n : this.taskExecutor.action(taskPrompt, this.opts.aiActionContext));\n\n // update cache\n if (this.taskCache && output?.yamlFlow && cacheable !== false) {\n const yamlContent = {\n tasks: [\n {\n name: taskPrompt,\n flow: output.yamlFlow,\n },\n ],\n };\n const yamlFlowStr = yaml.dump(yamlContent);\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'plan',\n prompt: taskPrompt,\n yamlWorkflow: yamlFlowStr,\n },\n matchedCache,\n );\n }\n\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiQuery(demand: any): Promise<AITaskResult> {\n const { output, executor } = await this.taskExecutor.query(demand);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiBoolean(prompt: string): Promise<AITaskResult<boolean>> {\n const { output, executor } = await this.taskExecutor.boolean(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiNumber(prompt: string): Promise<AITaskResult<number>> {\n const { output, executor } = await this.taskExecutor.number(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async aiString(prompt: string): Promise<AITaskResult<string>> {\n const { output, executor } = await this.taskExecutor.string(prompt);\n const metadata = this.afterTaskRunning(executor);\n return {\n result: output,\n metadata\n };\n }\n\n async describeElementAtPoint(\n center: [number, number],\n opt?: {\n verifyPrompt?: boolean;\n retryLimit?: number;\n deepThink?: boolean;\n } & LocatorValidatorOption,\n ): Promise<AgentDescribeElementAtPointResult> {\n const { verifyPrompt = true, retryLimit = 3 } = opt || {};\n\n let success = false;\n let retryCount = 0;\n let resultPrompt = '';\n let deepThink = opt?.deepThink || false;\n let verifyResult: LocateValidatorResult | undefined;\n\n while (!success && retryCount < retryLimit) {\n if (retryCount >= 2) {\n deepThink = true;\n }\n debug(\n 'aiDescribe',\n center,\n 'verifyPrompt',\n verifyPrompt,\n 'retryCount',\n retryCount,\n 'deepThink',\n deepThink,\n );\n const text = await this.insight.describe(center, { deepThink });\n debug('aiDescribe text', text);\n assert(text.description, `failed to describe element at [${center}]`);\n resultPrompt = text.description;\n\n verifyResult = await this.verifyLocator(\n resultPrompt,\n deepThink ? { deepThink: true } : undefined,\n center,\n opt,\n );\n if (verifyResult.pass) {\n success = true;\n } else {\n retryCount++;\n }\n }\n\n return {\n prompt: resultPrompt,\n deepThink,\n verifyResult,\n };\n }\n\n async verifyLocator(\n prompt: string,\n locateOpt: LocateOption | undefined,\n expectCenter: [number, number],\n verifyLocateOption?: LocatorValidatorOption,\n ): Promise<LocateValidatorResult> {\n debug('verifyLocator', prompt, locateOpt, expectCenter, verifyLocateOption);\n\n const locateResult = await this.aiLocate(prompt, locateOpt);\n const { center: verifyCenter, rect: verifyRect } = locateResult.result;\n\n const distance = distanceOfTwoPoints(expectCenter, verifyCenter);\n const included = includedInRect(expectCenter, verifyRect);\n const pass =\n distance <= (verifyLocateOption?.centerDistanceThreshold || 20) ||\n included;\n const verifyResult = {\n pass,\n rect: verifyRect,\n center: verifyCenter,\n centerDistance: distance,\n };\n debug('aiDescribe verifyResult', verifyResult);\n return verifyResult;\n }\n\n async aiLocate(prompt: string, opt?: LocateOption): Promise<AITaskResult<Pick<LocateResultElement, 'rect' | 'center'>>> {\n const detailedLocateParam = this.buildDetailedLocateParam(prompt, opt);\n const plans = buildPlans('Locate', detailedLocateParam);\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(detailedLocateParam)),\n plans,\n );\n const metadata = this.afterTaskRunning(executor);\n\n const { element } = output;\n const result = {\n rect: element?.rect,\n center: element?.center,\n } as Pick<LocateResultElement, 'rect' | 'center'>;\n\n return {\n result,\n metadata\n };\n }\n\n async aiAssert(assertion: string, msg?: string, opt?: AgentAssertOpt): Promise<AITaskResult<any>> {\n // Get the current page URL to include in the assertion context\n let currentUrl = \"\";\n if (this.page.url) {\n try {\n currentUrl = await this.page.url();\n } catch (e) {\n // Ignore errors getting URL\n }\n }\n\n // Add URL context to the assertion if available\n const assertionWithContext = currentUrl\n ? `For the page at URL \"${currentUrl}\", ${assertion}`\n : assertion;\n\n const { output, executor } = await this.taskExecutor.assert(assertionWithContext);\n const metadata = this.afterTaskRunning(executor, true);\n\n if (output && opt?.keepRawResponse) {\n return {\n result: output,\n metadata,\n };\n }\n\n if (!output?.pass) {\n const errMsg = msg || `Assertion failed: ${assertion}`;\n const reasonMsg = `Reason: ${\n output?.thought || executor.latestErrorTask()?.error || '(no_reason)'\n }`;\n throw new Error(`${errMsg}\\n${reasonMsg}`);\n }\n\n return {\n result: true,\n metadata\n };\n }\n\n async aiCaptcha(options?: { deepThink?: boolean; autoDetectComplexity?: boolean }): Promise<AITaskResult<any>> {\n const { deepThink = false, autoDetectComplexity = true } = options || {};\n\n // First, do a preliminary analysis to determine if this is a complex CAPTCHA\n // that would benefit from deep thinking\n let shouldUseDeepThink = deepThink;\n\n if (autoDetectComplexity && !deepThink) {\n // Get a screenshot to analyze\n const context = await this.getUIContext();\n const { screenshotBase64 } = context;\n\n // Simple analysis to determine if this is likely a complex CAPTCHA\n try {\n const complexityAnalysisPrompt = `\nAnalyze this screenshot and determine if it contains a complex CAPTCHA that would benefit from deep thinking.\nA complex CAPTCHA typically has one or more of these characteristics:\n- Distorted or overlapping text that is hard to read\n- Multiple images that need to be selected based on a specific criteria\n- Puzzles that require spatial reasoning\n- Multiple steps or verification methods\n- Small or hard-to-distinguish elements\n\nReturn only \"complex\" or \"simple\" based on your analysis.\n`;\n\n const complexityMsgs = [\n { role: 'system', content: 'You are an AI assistant that analyzes screenshots to determine CAPTCHA complexity.' },\n {\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: screenshotBase64,\n detail: 'high',\n },\n },\n {\n type: 'text',\n text: complexityAnalysisPrompt,\n },\n ],\n },\n ];\n\n // Use a simple call to determine complexity\n // Using any here to avoid type issues since we're just checking the response text\n const complexityResult = await (this.insight as any).aiVendorFn(\n complexityMsgs,\n { type: 'extract_data' }\n );\n\n // Check if the response indicates a complex CAPTCHA\n const responseText = typeof complexityResult.content === 'string'\n ? complexityResult.content.toLowerCase()\n : JSON.stringify(complexityResult.content).toLowerCase();\n\n shouldUseDeepThink = responseText.includes('complex');\n\n debug('CAPTCHA complexity analysis:', responseText, 'Using deep think:', shouldUseDeepThink);\n } catch (error) {\n // If analysis fails, default to not using deep think\n debug('Failed to analyze CAPTCHA complexity:', error);\n }\n }\n\n // Call the AiCaptcha function to analyze the CAPTCHA with the determined deepThink setting\n const captchaResponse = await this._callInsightCaptcha({\n deepThink: shouldUseDeepThink\n });\n\n const captchaResult = captchaResponse.content;\n const usage = captchaResponse.usage;\n // Get the actual deepThink value that was used (may be different due to global settings)\n const actualDeepThink = captchaResponse.deepThink || false;\n\n // Process the CAPTCHA solution based on its type\n if (captchaResult.captchaType === 'text') {\n // For text-based CAPTCHAs, find the input field and enter the solution\n for (const action of captchaResult.actions) {\n if (action.type === 'click' && action.target) {\n // Click on the input field\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n } else if (action.type === 'input' && action.value) {\n // Enter the text solution\n if (action.target) {\n await this.aiInput(action.value, action.target, { deepThink: shouldUseDeepThink });\n }\n } else if (action.type === 'verify' && action.target) {\n // Click on the verify/submit button\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n }\n } else if (captchaResult.captchaType === 'image') {\n // For image-based CAPTCHAs, click on the required elements\n for (const action of captchaResult.actions) {\n if (action.type === 'click') {\n if (action.coordinates) {\n // Click at specific coordinates using aiTap with coordinates\n const x = action.coordinates[0];\n const y = action.coordinates[1];\n await this.aiTap(`element at coordinates (${x}, ${y})`, { deepThink: shouldUseDeepThink });\n } else if (action.target) {\n // Click on described element\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n } else if (action.type === 'verify' && action.target) {\n // Click on the verify/submit button\n await this.aiTap(action.target, { deepThink: shouldUseDeepThink });\n }\n }\n }\n\n // Wait a few seconds after completing the CAPTCHA\n await new Promise(resolve => setTimeout(resolve, 3000));\n\n // Return the result with metadata\n const metadata: AITaskMetadata = {\n status: 'finished',\n usage,\n thought: captchaResult.thought,\n };\n\n // Add additional metadata properties using type assertion\n (metadata as any).deepThink = actualDeepThink;\n if (autoDetectComplexity && !deepThink) {\n (metadata as any).autoDetectedComplexity = shouldUseDeepThink;\n }\n\n return {\n result: captchaResult,\n metadata\n };\n }\n\n async aiWaitFor(assertion: string, opt?: AgentWaitForOpt): Promise<AITaskResult> {\n const startTime = Date.now();\n const { executor } = await this.taskExecutor.waitFor(assertion, {\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n assertion,\n });\n const metadata: AITaskMetadata = {\n status: executor.isInErrorState() ? 'failed' : 'finished',\n start: startTime,\n end: Date.now(),\n totalTime: Date.now() - startTime,\n thought: executor.latestErrorTask()?.thought,\n actionDetails: executor.tasks.map(task => ({\n type: task.type,\n subType: task.subType,\n status: task.status,\n thought: task.thought,\n })),\n };\n\n this.appendExecutionDump(executor.dump());\n this.writeOutActionDumps();\n\n if (executor.isInErrorState()) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}\\n${errorTask?.errorStack}`);\n }\n\n return {\n result: true, // Successfully waited\n metadata,\n };\n }\n\n async ai(\n taskPrompt: string,\n type = 'action',\n options?: { deepThink?: boolean; autoDetectComplexity?: boolean }\n ): Promise<AITaskResult> {\n if (type === 'action') {\n return this.aiAction(taskPrompt);\n }\n if (type === 'query') {\n return this.aiQuery(taskPrompt);\n }\n\n if (type === 'assert') {\n return this.aiAssert(taskPrompt);\n }\n\n if (type === 'tap') {\n return this.aiTap(taskPrompt, options);\n }\n\n if (type === 'captcha') {\n return this.aiCaptcha(options);\n }\n\n throw new Error(\n `Unknown type: ${type}, only support 'action', 'query', 'assert', 'tap', 'captcha'`,\n );\n }\n\n async runYaml(yamlScriptContent: string): Promise<AITaskResult<Record<string, any>>> {\n const startTime = Date.now();\n const script = parseYamlScript(yamlScriptContent, 'yaml', true);\n const player = new ScriptPlayer(script, async () => {\n return { agent: this, freeFn: [] };\n });\n await player.run();\n\n const endTime = Date.now();\n const metadata: AITaskMetadata = {\n status: player.status,\n start: startTime,\n end: endTime,\n totalTime: endTime - startTime,\n tasks: player.taskStatusList.map(task => ({\n type: 'yaml-task',\n subType: task.name,\n status: task.status,\n error: task.error?.message,\n })),\n };\n\n if (player.status === 'error') {\n const errors = player.taskStatusList\n .filter((task) => task.status === 'error')\n .map((task) => {\n return `task - ${task.name}: ${task.error?.message}`;\n })\n .join('\\n');\n throw new Error(`Error(s) occurred in running yaml script:\\n${errors}`);\n }\n\n return {\n result: player.result,\n metadata\n };\n }\n\n async evaluateJavaScript(script: string): Promise<any> {\n assert(\n this.page.evaluateJavaScript,\n 'evaluateJavaScript is not supported in current agent',\n );\n if (this.page.evaluateJavaScript) {\n return this.page.evaluateJavaScript(script);\n }\n throw new Error('evaluateJavaScript is not supported in current agent');\n }\n\n async destroy() {\n await this.page.destroy();\n }\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { assert, ifInBrowser } from 'misoai-shared/utils';\n\nimport type { PageAgent } from '@/common/agent';\nimport type {\n FreeFn,\n MidsceneYamlFlowItemAIAction,\n MidsceneYamlFlowItemAIAssert,\n MidsceneYamlFlowItemAIBoolean,\n MidsceneYamlFlowItemAIHover,\n MidsceneYamlFlowItemAIInput,\n MidsceneYamlFlowItemAIKeyboardPress,\n MidsceneYamlFlowItemAILocate,\n MidsceneYamlFlowItemAINString,\n MidsceneYamlFlowItemAINumber,\n MidsceneYamlFlowItemAIQuery,\n MidsceneYamlFlowItemAIScroll,\n MidsceneYamlFlowItemAITap,\n MidsceneYamlFlowItemAIWaitFor,\n MidsceneYamlFlowItemEvaluateJavaScript,\n MidsceneYamlFlowItemSleep,\n MidsceneYamlScript,\n MidsceneYamlScriptEnv,\n ScriptPlayerStatusValue,\n ScriptPlayerTaskStatus,\n} from 'misoai-core';\nimport { getMidsceneRunSubDir } from 'misoai-shared/common';\n\nexport class ScriptPlayer<T extends MidsceneYamlScriptEnv> {\n public currentTaskIndex?: number;\n public taskStatusList: ScriptPlayerTaskStatus[] = [];\n public status: ScriptPlayerStatusValue = 'init';\n public reportFile?: string | null;\n public result: Record<string, any>;\n private unnamedResultIndex = 0;\n public output?: string | null;\n public errorInSetup?: Error;\n private pageAgent: PageAgent | null = null;\n public agentStatusTip?: string;\n constructor(\n private script: MidsceneYamlScript,\n private setupAgent: (platform: T) => Promise<{\n agent: PageAgent;\n freeFn: FreeFn[];\n }>,\n public onTaskStatusChange?: (taskStatus: ScriptPlayerTaskStatus) => void,\n ) {\n this.result = {};\n\n if (ifInBrowser) {\n this.output = undefined;\n } else if (script.target?.output) {\n this.output = resolve(process.cwd(), script.target.output);\n } else {\n this.output = join(getMidsceneRunSubDir('output'), `${process.pid}.json`);\n }\n\n this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({\n ...task,\n index: taskIndex,\n status: 'init',\n totalSteps: task.flow?.length || 0,\n }));\n }\n\n private setResult(key: string | undefined, value: any) {\n const keyToUse = key || this.unnamedResultIndex++;\n if (this.result[keyToUse]) {\n console.warn(`result key ${keyToUse} already exists, will overwrite`);\n }\n this.result[keyToUse] = value;\n\n this.flushResult();\n }\n\n private setPlayerStatus(status: ScriptPlayerStatusValue, error?: Error) {\n this.status = status;\n this.errorInSetup = error;\n }\n\n private notifyCurrentTaskStatusChange(taskIndex?: number) {\n const taskIndexToNotify =\n typeof taskIndex === 'number' ? taskIndex : this.currentTaskIndex;\n\n if (typeof taskIndexToNotify !== 'number') {\n return;\n }\n\n const taskStatus = this.taskStatusList[taskIndexToNotify];\n if (this.onTaskStatusChange) {\n this.onTaskStatusChange(taskStatus);\n }\n }\n\n private async setTaskStatus(\n index: number,\n statusValue: ScriptPlayerStatusValue,\n error?: Error,\n ) {\n this.taskStatusList[index].status = statusValue;\n if (error) {\n this.taskStatusList[index].error = error;\n }\n\n this.notifyCurrentTaskStatusChange(index);\n }\n\n private setTaskIndex(taskIndex: number) {\n this.currentTaskIndex = taskIndex;\n }\n\n private flushResult() {\n if (Object.keys(this.result).length && this.output) {\n const output = resolve(process.cwd(), this.output);\n const outputDir = dirname(output);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(output, JSON.stringify(this.result, undefined, 2));\n }\n }\n\n async playTask(taskStatus: ScriptPlayerTaskStatus, agent: PageAgent) {\n const { flow } = taskStatus;\n assert(flow, 'missing flow in task');\n\n for (const flowItemIndex in flow) {\n const currentStep = Number.parseInt(flowItemIndex, 10);\n taskStatus.currentStep = currentStep;\n const flowItem = flow[flowItemIndex];\n if (\n 'aiAction' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'ai' in (flowItem as MidsceneYamlFlowItemAIAction)\n ) {\n const actionTask = flowItem as MidsceneYamlFlowItemAIAction;\n const prompt = actionTask.aiAction || actionTask.ai;\n assert(prompt, 'missing prompt for ai (aiAction)');\n assert(\n typeof prompt === 'string',\n 'prompt for aiAction must be a string',\n );\n await agent.aiAction(prompt);\n } else if ('aiAssert' in (flowItem as MidsceneYamlFlowItemAIAssert)) {\n const assertTask = flowItem as MidsceneYamlFlowItemAIAssert;\n const prompt = assertTask.aiAssert;\n assert(prompt, 'missing prompt for aiAssert');\n assert(\n typeof prompt === 'string',\n 'prompt for aiAssert must be a string',\n );\n await agent.aiAssert(prompt);\n } else if ('aiQuery' in (flowItem as MidsceneYamlFlowItemAIQuery)) {\n const queryTask = flowItem as MidsceneYamlFlowItemAIQuery;\n const prompt = queryTask.aiQuery;\n assert(prompt, 'missing prompt for aiQuery');\n assert(\n typeof prompt === 'string',\n 'prompt for aiQuery must be a string',\n );\n const queryResult = await agent.aiQuery(prompt);\n this.setResult(queryTask.name, queryResult);\n } else if ('aiNumber' in (flowItem as MidsceneYamlFlowItemAINumber)) {\n const numberTask = flowItem as MidsceneYamlFlowItemAINumber;\n const prompt = numberTask.aiNumber;\n assert(prompt, 'missing prompt for number');\n assert(\n typeof prompt === 'string',\n 'prompt for number must be a string',\n );\n const numberResult = await agent.aiNumber(prompt);\n this.setResult(numberTask.name, numberResult);\n } else if ('aiString' in (flowItem as MidsceneYamlFlowItemAINString)) {\n const stringTask = flowItem as MidsceneYamlFlowItemAINString;\n const prompt = stringTask.aiString;\n assert(prompt, 'missing prompt for string');\n assert(\n typeof prompt === 'string',\n 'prompt for string must be a string',\n );\n const stringResult = await agent.aiString(prompt);\n this.setResult(stringTask.name, stringResult);\n } else if ('aiBoolean' in (flowItem as MidsceneYamlFlowItemAIBoolean)) {\n const booleanTask = flowItem as MidsceneYamlFlowItemAIBoolean;\n const prompt = booleanTask.aiBoolean;\n assert(prompt, 'missing prompt for boolean');\n assert(\n typeof prompt === 'string',\n 'prompt for boolean must be a string',\n );\n const booleanResult = await agent.aiBoolean(prompt);\n this.setResult(booleanTask.name, booleanResult);\n } else if ('aiLocate' in (flowItem as MidsceneYamlFlowItemAILocate)) {\n const locateTask = flowItem as MidsceneYamlFlowItemAILocate;\n const prompt = locateTask.aiLocate;\n assert(prompt, 'missing prompt for aiLocate');\n assert(\n typeof prompt === 'string',\n 'prompt for aiLocate must be a string',\n );\n const locateResult = await agent.aiLocate(prompt);\n this.setResult(locateTask.name, locateResult);\n } else if ('aiWaitFor' in (flowItem as MidsceneYamlFlowItemAIWaitFor)) {\n const waitForTask = flowItem as MidsceneYamlFlowItemAIWaitFor;\n const prompt = waitForTask.aiWaitFor;\n assert(prompt, 'missing prompt for aiWaitFor');\n assert(\n typeof prompt === 'string',\n 'prompt for aiWaitFor must be a string',\n );\n const timeout = waitForTask.timeout;\n await agent.aiWaitFor(prompt, { timeoutMs: timeout });\n } else if ('sleep' in (flowItem as MidsceneYamlFlowItemSleep)) {\n const sleepTask = flowItem as MidsceneYamlFlowItemSleep;\n const ms = sleepTask.sleep;\n let msNumber = ms;\n if (typeof ms === 'string') {\n msNumber = Number.parseInt(ms, 10);\n }\n assert(\n msNumber && msNumber > 0,\n `ms for sleep must be greater than 0, but got ${ms}`,\n );\n await new Promise((resolve) => setTimeout(resolve, msNumber));\n } else if ('aiTap' in (flowItem as MidsceneYamlFlowItemAITap)) {\n const tapTask = flowItem as MidsceneYamlFlowItemAITap;\n await agent.aiTap(tapTask.aiTap, tapTask);\n } else if ('aiHover' in (flowItem as MidsceneYamlFlowItemAIHover)) {\n const hoverTask = flowItem as MidsceneYamlFlowItemAIHover;\n await agent.aiHover(hoverTask.aiHover, hoverTask);\n } else if ('aiInput' in (flowItem as MidsceneYamlFlowItemAIInput)) {\n // may be input empty string ''\n const inputTask = flowItem as MidsceneYamlFlowItemAIInput;\n await agent.aiInput(inputTask.aiInput, inputTask.locate, inputTask);\n } else if (\n 'aiKeyboardPress' in (flowItem as MidsceneYamlFlowItemAIKeyboardPress)\n ) {\n const keyboardPressTask =\n flowItem as MidsceneYamlFlowItemAIKeyboardPress;\n await agent.aiKeyboardPress(\n keyboardPressTask.aiKeyboardPress,\n keyboardPressTask.locate,\n keyboardPressTask,\n );\n } else if ('aiScroll' in (flowItem as MidsceneYamlFlowItemAIScroll)) {\n const scrollTask = flowItem as MidsceneYamlFlowItemAIScroll;\n await agent.aiScroll(scrollTask, scrollTask.locate, scrollTask);\n } else if (\n 'javascript' in (flowItem as MidsceneYamlFlowItemEvaluateJavaScript)\n ) {\n const evaluateJavaScriptTask =\n flowItem as MidsceneYamlFlowItemEvaluateJavaScript;\n\n const result = await agent.evaluateJavaScript(\n evaluateJavaScriptTask.javascript,\n );\n this.setResult(evaluateJavaScriptTask.name, result);\n } else {\n throw new Error(`unknown flowItem: ${JSON.stringify(flowItem)}`);\n }\n }\n this.reportFile = agent.reportFile;\n }\n\n async run() {\n const { target, web, android, tasks } = this.script;\n const webEnv = web || target;\n const androidEnv = android;\n const platform = webEnv || androidEnv;\n\n this.setPlayerStatus('running');\n\n let agent: PageAgent | null = null;\n let freeFn: FreeFn[] = [];\n try {\n const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(\n platform as T,\n );\n agent = newAgent;\n const originalOnTaskStartTip = agent.onTaskStartTip;\n agent.onTaskStartTip = (tip) => {\n if (this.status === 'running') {\n this.agentStatusTip = tip;\n }\n originalOnTaskStartTip?.(tip);\n };\n freeFn = [\n ...(newFreeFn || []),\n {\n name: 'restore-agent-onTaskStartTip',\n fn: () => {\n if (agent) {\n agent.onTaskStartTip = originalOnTaskStartTip;\n }\n },\n },\n ];\n } catch (e) {\n this.setPlayerStatus('error', e as Error);\n return;\n }\n this.pageAgent = agent;\n\n let taskIndex = 0;\n this.setPlayerStatus('running');\n let errorFlag = false;\n while (taskIndex < tasks.length) {\n const taskStatus = this.taskStatusList[taskIndex];\n this.setTaskStatus(taskIndex, 'running' as any);\n this.setTaskIndex(taskIndex);\n\n try {\n await this.playTask(taskStatus, this.pageAgent);\n this.setTaskStatus(taskIndex, 'done' as any);\n } catch (e) {\n this.setTaskStatus(taskIndex, 'error' as any, e as Error);\n\n if (taskStatus.continueOnError) {\n // nothing more to do\n } else {\n this.reportFile = agent.reportFile;\n errorFlag = true;\n break;\n }\n }\n this.reportFile = agent.reportFile;\n taskIndex++;\n }\n\n if (errorFlag) {\n this.setPlayerStatus('error');\n } else {\n this.setPlayerStatus('done');\n }\n this.agentStatusTip = '';\n\n // free the resources\n for (const fn of freeFn) {\n try {\n // console.log('freeing', fn.name);\n await fn.fn();\n // console.log('freed', fn.name);\n } catch (e) {\n // console.error('error freeing', fn.name, e);\n }\n }\n }\n}\n","import type {\n MidsceneYamlScript,\n MidsceneYamlScriptWebEnv,\n MidsceneYamlTask,\n} from 'misoai-core';\nimport yaml from 'js-yaml';\n\nexport function buildYaml(\n env: MidsceneYamlScriptWebEnv,\n tasks: MidsceneYamlTask[],\n) {\n const result: MidsceneYamlScript = {\n target: env,\n tasks,\n };\n\n return yaml.dump(result, {\n indent: 2,\n });\n}\n","import { assert } from 'misoai-shared/utils';\nimport yaml from 'js-yaml';\n\nimport type { MidsceneYamlScript } from 'misoai-core';\n\nfunction interpolateEnvVars(content: string): string {\n return content.replace(/\\$\\{([^}]+)\\}/g, (_, envVar) => {\n const value = process.env[envVar.trim()];\n if (value === undefined) {\n throw new Error(`Environment variable \"${envVar.trim()}\" is not defined`);\n }\n return value;\n });\n}\n\nexport function parseYamlScript(\n content: string,\n filePath?: string,\n ignoreCheckingTarget?: boolean,\n): MidsceneYamlScript {\n const interpolatedContent = interpolateEnvVars(content);\n const obj = yaml.load(interpolatedContent) as MidsceneYamlScript;\n const pathTip = filePath ? `, failed to load ${filePath}` : '';\n const android =\n typeof obj.android !== 'undefined'\n ? Object.assign({}, obj.android || {})\n : undefined;\n const webConfig = obj.web || obj.target; // no need to handle null case, because web has required parameters url\n const web =\n typeof webConfig !== 'undefined'\n ? Object.assign({}, webConfig || {})\n : undefined;\n\n if (!ignoreCheckingTarget) {\n // make sure at least one of target/web/android is provided\n assert(\n web || android,\n `at least one of \"target\", \"web\", or \"android\" properties is required in yaml script${pathTip}`,\n );\n\n // make sure only one of target/web/android is provided\n assert(\n (web && !android) || (!web && android),\n `only one of \"target\", \"web\", or \"android\" properties is allowed in yaml script${pathTip}`,\n );\n\n // make sure the config is valid\n if (web || android) {\n assert(\n typeof web === 'object' || typeof android === 'object',\n `property \"target/web/android\" must be an object${pathTip}`,\n );\n }\n }\n\n assert(obj.tasks, `property \"tasks\" is required in yaml script ${pathTip}`);\n assert(\n Array.isArray(obj.tasks),\n `property \"tasks\" must be an array in yaml script, but got ${obj.tasks}`,\n );\n return obj;\n}\n","import type { AndroidDevicePage, WebPage } from '@/common/page';\nimport type { PuppeteerWebPage } from '@/puppeteer';\nimport {\n type AIUsageInfo,\n type DumpSubscriber,\n type ExecutionRecorderItem,\n type ExecutionTaskActionApply,\n type ExecutionTaskApply,\n type ExecutionTaskInsightLocateApply,\n type ExecutionTaskInsightQueryApply,\n type ExecutionTaskPlanning,\n type ExecutionTaskPlanningApply,\n type ExecutionTaskProgressOptions,\n Executor,\n type ExecutorContext,\n type Insight,\n type InsightAssertionResponse,\n type InsightDump,\n type InsightExtractParam,\n type LocateResultElement,\n type MidsceneYamlFlowItem,\n type PageType,\n type PlanningAIResponse,\n type PlanningAction,\n type PlanningActionParamAssert,\n type PlanningActionParamError,\n type PlanningActionParamHover,\n type PlanningActionParamInputOrKeyPress,\n type PlanningActionParamScroll,\n type PlanningActionParamSleep,\n type PlanningActionParamTap,\n type PlanningActionParamWaitFor,\n plan,\n} from 'misoai-core';\nimport {\n type ChatCompletionMessageParam,\n elementByPositionWithElementInfo,\n resizeImageForUiTars,\n vlmPlanning,\n} from 'misoai-core/ai-model';\nimport { sleep } from 'misoai-core/utils';\nimport { NodeType } from 'misoai-shared/constants';\nimport type { ElementInfo } from 'misoai-shared/extractor';\nimport { getElementInfosScriptContent } from 'misoai-shared/fs';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\nimport type { WebElementInfo } from '../web-element';\nimport type { TaskCache } from './task-cache';\nimport { getKeyCommands, taskTitleStr } from './ui-utils';\nimport { type WebUIContext, matchElementFromPlan } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n executor: Executor;\n}\n\nconst debug = getDebug('page-task-executor');\n\nconst replanningCountLimit = 10;\n\nconst isAndroidPage = (page: WebPage): page is AndroidDevicePage => {\n return page.pageType === 'android';\n};\n\nexport class PageTaskExecutor {\n page: WebPage;\n\n insight: Insight<WebElementInfo, WebUIContext>;\n\n taskCache?: TaskCache;\n\n conversationHistory: ChatCompletionMessageParam[] = [];\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n constructor(\n page: WebPage,\n insight: Insight<WebElementInfo, WebUIContext>,\n opts: {\n taskCache?: TaskCache;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n },\n ) {\n this.page = page;\n this.insight = insight;\n\n this.taskCache = opts.taskCache;\n\n this.onTaskStartCallback = opts?.onTaskStart;\n }\n\n private async recordScreenshot(timing: ExecutionRecorderItem['timing']) {\n const base64 = await this.page.screenshotBase64();\n const item: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: Date.now(),\n screenshot: base64,\n timing,\n };\n return item;\n }\n\n private async getElementXpath(\n pageContext: WebUIContext,\n element: LocateResultElement,\n ): Promise<string[] | undefined> {\n let elementId = element?.id;\n // find the nearest xpath for the element\n if (element?.attributes?.nodeType === NodeType.POSITION) {\n await this.insight.contextRetrieverFn('locate');\n const info = elementByPositionWithElementInfo(\n pageContext.tree,\n {\n x: element.center[0],\n y: element.center[1],\n },\n {\n requireStrictDistance: false,\n filterPositionElements: true,\n },\n );\n if (info?.id) {\n elementId = info.id;\n }\n }\n\n if (!elementId) {\n return undefined;\n }\n try {\n const elementInfosScriptContent = getElementInfosScriptContent();\n const result = await this.page.evaluateJavaScript?.(\n `${elementInfosScriptContent}midscene_element_inspector.getXpathsById('${elementId}')`,\n );\n return result;\n } catch (error) {\n debug('getXpathsById error: ', error);\n }\n }\n\n private prependExecutorWithScreenshot(\n taskApply: ExecutionTaskApply,\n appendAfterExecution = false,\n ): ExecutionTaskApply {\n const taskWithScreenshot: ExecutionTaskApply = {\n ...taskApply,\n executor: async (param, context, ...args) => {\n const recorder: ExecutionRecorderItem[] = [];\n const { task } = context;\n // set the recorder before executor in case of error\n task.recorder = recorder;\n const shot = await this.recordScreenshot(`before ${task.type}`);\n recorder.push(shot);\n const result = await taskApply.executor(param, context, ...args);\n if (taskApply.type === 'Action') {\n await Promise.all([\n (async () => {\n await sleep(100);\n if ((this.page as PuppeteerWebPage).waitUntilNetworkIdle) {\n try {\n await (this.page as PuppeteerWebPage).waitUntilNetworkIdle();\n } catch (error) {\n // console.error('waitUntilNetworkIdle error', error);\n }\n }\n })(),\n sleep(200),\n ]);\n }\n if (appendAfterExecution) {\n const shot2 = await this.recordScreenshot('after Action');\n recorder.push(shot2);\n }\n return result;\n },\n };\n return taskWithScreenshot;\n }\n\n private async convertPlanToExecutable(plans: PlanningAction[]) {\n const tasks: ExecutionTaskApply[] = [];\n plans.forEach((plan) => {\n if (plan.type === 'Locate') {\n if (\n plan.locate === null ||\n plan.locate?.id === null ||\n plan.locate?.id === 'null'\n ) {\n // console.warn('Locate action with id is null, will be ignored');\n return;\n }\n const taskFind: ExecutionTaskInsightLocateApply = {\n type: 'Insight',\n subType: 'Locate',\n param: plan.locate || undefined,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, taskContext) => {\n const { task } = taskContext;\n assert(\n param?.prompt || param?.id || param?.bbox,\n 'No prompt or id or position or bbox to locate',\n );\n let insightDump: InsightDump | undefined;\n let usage: AIUsageInfo | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n usage = dump?.taskInfo?.usage;\n\n task.log = {\n dump: insightDump,\n };\n\n task.usage = usage;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n const shotTime = Date.now();\n const pageContext = await this.insight.contextRetrieverFn('locate');\n task.pageContext = pageContext;\n\n const recordItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: shotTime,\n screenshot: pageContext.screenshotBase64,\n timing: 'before locate',\n };\n task.recorder = [recordItem];\n\n // try matching cache\n let cacheHitFlag = false;\n const cachePrompt = param.prompt;\n const locateCacheRecord =\n this.taskCache?.matchLocateCache(cachePrompt);\n const xpaths = locateCacheRecord?.cacheContent?.xpaths;\n let elementFromCache = null;\n try {\n if (\n xpaths?.length &&\n this.taskCache?.isCacheResultUsed &&\n param?.cacheable !== false\n ) {\n // hit cache, use new id\n const elementInfosScriptContent =\n getElementInfosScriptContent();\n const element = await this.page.evaluateJavaScript?.(\n `${elementInfosScriptContent}midscene_element_inspector.getElementInfoByXpath('${xpaths[0]}')`,\n );\n\n if (element?.id) {\n elementFromCache = element;\n debug('cache hit, prompt: %s', cachePrompt);\n cacheHitFlag = true;\n debug(\n 'found a new new element with same xpath, xpath: %s, id: %s',\n xpaths[0],\n element?.id,\n );\n }\n }\n } catch (error) {\n debug('get element info by xpath error: ', error);\n }\n\n const startTime = Date.now();\n const element =\n elementFromCache || // try to match element from cache\n matchElementFromPlan(param, pageContext.tree) || // try to match element from plan\n (\n await this.insight.locate(param, {\n context: pageContext,\n })\n ).element;\n\n const aiCost = Date.now() - startTime;\n\n // update cache\n if (\n element &&\n this.taskCache &&\n !cacheHitFlag &&\n param?.cacheable !== false\n ) {\n const elementXpaths = await this.getElementXpath(\n pageContext,\n element,\n );\n if (elementXpaths) {\n this.taskCache.updateOrAppendCacheRecord(\n {\n type: 'locate',\n prompt: cachePrompt,\n xpaths: elementXpaths,\n },\n locateCacheRecord,\n );\n } else {\n debug('no xpaths found, will not update cache', cachePrompt);\n }\n }\n if (!element) {\n throw new Error(`Element not found: ${param.prompt}`);\n }\n\n return {\n output: {\n element,\n },\n pageContext,\n cache: {\n hit: cacheHitFlag,\n },\n aiCost,\n };\n },\n };\n tasks.push(taskFind);\n } else if (plan.type === 'Assert' || plan.type === 'AssertWithoutThrow') {\n const assertPlan = plan as PlanningAction<PlanningActionParamAssert>;\n const taskAssert: ExecutionTaskApply = {\n type: 'Insight',\n subType: 'Assert',\n param: assertPlan.param,\n thought: assertPlan.thought,\n locate: assertPlan.locate,\n executor: async (param, taskContext) => {\n const { task } = taskContext;\n let insightDump: InsightDump | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n const assertion = await this.insight.assert(\n assertPlan.param.assertion,\n );\n\n if (!assertion.pass) {\n if (plan.type === 'Assert') {\n task.output = assertion;\n task.log = {\n dump: insightDump,\n };\n throw new Error(\n assertion.thought || 'Assertion failed without reason',\n );\n }\n\n task.error = assertion.thought;\n }\n\n return {\n output: assertion,\n log: {\n dump: insightDump,\n },\n usage: assertion.usage,\n };\n },\n };\n tasks.push(taskAssert);\n } else if (plan.type === 'Input') {\n const taskActionInput: ExecutionTaskActionApply<PlanningActionParamInputOrKeyPress> =\n {\n type: 'Action',\n subType: 'Input',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam, { element }) => {\n if (element) {\n await this.page.clearInput(element as unknown as ElementInfo);\n\n if (!taskParam || !taskParam.value) {\n return;\n }\n\n await this.page.keyboard.type(taskParam.value);\n } else {\n await this.page.keyboard.type(taskParam.value);\n }\n },\n };\n tasks.push(taskActionInput);\n } else if (plan.type === 'KeyboardPress') {\n const taskActionKeyboardPress: ExecutionTaskActionApply<PlanningActionParamInputOrKeyPress> =\n {\n type: 'Action',\n subType: 'KeyboardPress',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n const keys = getKeyCommands(taskParam.value);\n\n await this.page.keyboard.press(keys);\n },\n };\n tasks.push(taskActionKeyboardPress);\n } else if (plan.type === 'Tap') {\n const taskActionTap: ExecutionTaskActionApply<PlanningActionParamTap> =\n {\n type: 'Action',\n subType: 'Tap',\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, { element }) => {\n assert(element, 'Element not found, cannot tap');\n await this.page.mouse.click(element.center[0], element.center[1]);\n },\n };\n tasks.push(taskActionTap);\n } else if (plan.type === 'Drag') {\n const taskActionDrag: ExecutionTaskActionApply<{\n start_box: { x: number; y: number };\n end_box: { x: number; y: number };\n }> = {\n type: 'Action',\n subType: 'Drag',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n assert(\n taskParam?.start_box && taskParam?.end_box,\n 'No start_box or end_box to drag',\n );\n await this.page.mouse.drag(taskParam.start_box, taskParam.end_box);\n },\n };\n tasks.push(taskActionDrag);\n } else if (plan.type === 'Hover') {\n const taskActionHover: ExecutionTaskActionApply<PlanningActionParamHover> =\n {\n type: 'Action',\n subType: 'Hover',\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param, { element }) => {\n assert(element, 'Element not found, cannot hover');\n await this.page.mouse.move(element.center[0], element.center[1]);\n },\n };\n tasks.push(taskActionHover);\n } else if (plan.type === 'Scroll') {\n const taskActionScroll: ExecutionTaskActionApply<PlanningActionParamScroll> =\n {\n type: 'Action',\n subType: 'Scroll',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam, { element }) => {\n const startingPoint = element\n ? {\n left: element.center[0],\n top: element.center[1],\n }\n : undefined;\n const scrollToEventName = taskParam?.scrollType;\n if (scrollToEventName === 'untilTop') {\n await this.page.scrollUntilTop(startingPoint);\n } else if (scrollToEventName === 'untilBottom') {\n await this.page.scrollUntilBottom(startingPoint);\n } else if (scrollToEventName === 'untilRight') {\n await this.page.scrollUntilRight(startingPoint);\n } else if (scrollToEventName === 'untilLeft') {\n await this.page.scrollUntilLeft(startingPoint);\n } else if (scrollToEventName === 'once' || !scrollToEventName) {\n if (\n taskParam?.direction === 'down' ||\n !taskParam ||\n !taskParam.direction\n ) {\n await this.page.scrollDown(\n taskParam?.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'up') {\n await this.page.scrollUp(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'left') {\n await this.page.scrollLeft(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else if (taskParam.direction === 'right') {\n await this.page.scrollRight(\n taskParam.distance || undefined,\n startingPoint,\n );\n } else {\n throw new Error(\n `Unknown scroll direction: ${taskParam.direction}`,\n );\n }\n // until mouse event is done\n await sleep(500);\n } else {\n throw new Error(\n `Unknown scroll event type: ${scrollToEventName}, taskParam: ${JSON.stringify(\n taskParam,\n )}`,\n );\n }\n },\n };\n tasks.push(taskActionScroll);\n } else if (plan.type === 'Sleep') {\n const taskActionSleep: ExecutionTaskActionApply<PlanningActionParamSleep> =\n {\n type: 'Action',\n subType: 'Sleep',\n param: plan.param,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (taskParam) => {\n await sleep(taskParam?.timeMs || 3000);\n },\n };\n tasks.push(taskActionSleep);\n } else if (plan.type === 'Error') {\n const taskActionError: ExecutionTaskActionApply<PlanningActionParamError> =\n {\n type: 'Action',\n subType: 'Error',\n param: plan.param,\n thought: plan.thought || plan.param?.thought,\n locate: plan.locate,\n executor: async () => {\n throw new Error(\n plan?.thought || plan.param?.thought || 'error without thought',\n );\n },\n };\n tasks.push(taskActionError);\n } else if (plan.type === 'ExpectedFalsyCondition') {\n const taskActionFalsyConditionStatement: ExecutionTaskActionApply<null> =\n {\n type: 'Action',\n subType: 'ExpectedFalsyCondition',\n param: null,\n thought: plan.param?.reason,\n locate: plan.locate,\n executor: async () => {\n // console.warn(`[warn]falsy condition: ${plan.thought}`);\n },\n };\n tasks.push(taskActionFalsyConditionStatement);\n } else if (plan.type === 'Finished') {\n const taskActionFinished: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'Finished',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {},\n };\n tasks.push(taskActionFinished);\n } else if (plan.type === 'AndroidHomeButton') {\n const taskActionAndroidHomeButton: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'AndroidHomeButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n // Check if the page has back method (Android devices)\n assert(\n isAndroidPage(this.page),\n 'Cannot use home button on non-Android devices',\n );\n await this.page.home();\n },\n };\n tasks.push(taskActionAndroidHomeButton);\n } else if (plan.type === 'AndroidBackButton') {\n const taskActionAndroidBackButton: ExecutionTaskActionApply<null> = {\n type: 'Action',\n subType: 'AndroidBackButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n assert(\n isAndroidPage(this.page),\n 'Cannot use back button on non-Android devices',\n );\n await this.page.back();\n },\n };\n tasks.push(taskActionAndroidBackButton);\n } else if (plan.type === 'AndroidRecentAppsButton') {\n const taskActionAndroidRecentAppsButton: ExecutionTaskActionApply<null> =\n {\n type: 'Action',\n subType: 'AndroidRecentAppsButton',\n param: null,\n thought: plan.thought,\n locate: plan.locate,\n executor: async (param) => {\n assert(\n isAndroidPage(this.page),\n 'Cannot use recent apps button on non-Android devices',\n );\n await this.page.recentApps();\n },\n };\n tasks.push(taskActionAndroidRecentAppsButton);\n } else {\n throw new Error(`Unknown or unsupported task type: ${plan.type}`);\n }\n });\n\n const wrappedTasks = tasks.map(\n (task: ExecutionTaskApply, index: number) => {\n if (task.type === 'Action') {\n return this.prependExecutorWithScreenshot(\n task,\n index === tasks.length - 1,\n );\n }\n return task;\n },\n );\n\n return {\n tasks: wrappedTasks,\n };\n }\n\n private async setupPlanningContext(executorContext: ExecutorContext) {\n const shotTime = Date.now();\n const pageContext = await this.insight.contextRetrieverFn('locate');\n const recordItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: shotTime,\n screenshot: pageContext.screenshotBase64,\n timing: 'before planning',\n };\n\n executorContext.task.recorder = [recordItem];\n (executorContext.task as ExecutionTaskPlanning).pageContext = pageContext;\n\n return {\n pageContext,\n };\n }\n\n async loadYamlFlowAsPlanning(userInstruction: string, yamlString: string) {\n const taskExecutor = new Executor(taskTitleStr('Action', userInstruction), {\n onTaskStart: this.onTaskStartCallback,\n });\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n locate: null,\n param: {\n userInstruction,\n },\n executor: async (param, executorContext) => {\n await this.setupPlanningContext(executorContext);\n return {\n output: {\n actions: [],\n more_actions_needed_by_instruction: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n };\n },\n };\n\n await taskExecutor.append(task);\n await taskExecutor.flush();\n\n return {\n executor: taskExecutor,\n };\n }\n\n private planningTaskFromPrompt(\n userInstruction: string,\n log?: string,\n actionContext?: string,\n ) {\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'Plan',\n locate: null,\n param: {\n userInstruction,\n log,\n },\n executor: async (param, executorContext) => {\n const startTime = Date.now();\n const { pageContext } =\n await this.setupPlanningContext(executorContext);\n\n const planResult = await plan(param.userInstruction, {\n context: pageContext,\n log: param.log,\n actionContext,\n pageType: this.page.pageType as PageType,\n });\n\n const {\n actions,\n log,\n more_actions_needed_by_instruction,\n error,\n usage,\n rawResponse,\n sleep,\n } = planResult;\n\n executorContext.task.log = {\n rawResponse,\n };\n executorContext.task.usage = usage;\n\n let stopCollecting = false;\n let bboxCollected = false;\n let planParsingError = '';\n const finalActions = (actions || []).reduce<PlanningAction[]>(\n (acc, planningAction) => {\n if (stopCollecting) {\n return acc;\n }\n\n if (planningAction.locate) {\n // we only collect bbox once, let qwen re-locate in the following steps\n if (bboxCollected && planningAction.locate.bbox) {\n // biome-ignore lint/performance/noDelete: <explanation>\n delete planningAction.locate.bbox;\n }\n\n if (planningAction.locate.bbox) {\n bboxCollected = true;\n }\n\n acc.push({\n type: 'Locate',\n locate: planningAction.locate,\n param: null,\n thought: planningAction.locate.prompt,\n });\n } else if (\n ['Tap', 'Hover', 'Input'].includes(planningAction.type)\n ) {\n planParsingError = `invalid planning response: ${JSON.stringify(planningAction)}`;\n // should include locate but get null\n stopCollecting = true;\n return acc;\n }\n acc.push(planningAction);\n return acc;\n },\n [],\n );\n\n if (sleep) {\n const timeNow = Date.now();\n const timeRemaining = sleep - (timeNow - startTime);\n if (timeRemaining > 0) {\n finalActions.push({\n type: 'Sleep',\n param: {\n timeMs: timeRemaining,\n },\n locate: null,\n } as PlanningAction<PlanningActionParamSleep>);\n }\n }\n\n if (finalActions.length === 0) {\n assert(\n !more_actions_needed_by_instruction || sleep,\n error\n ? `Failed to plan: ${error}`\n : planParsingError || 'No plan found',\n );\n }\n\n return {\n output: {\n actions: finalActions,\n more_actions_needed_by_instruction,\n log,\n yamlFlow: planResult.yamlFlow,\n },\n cache: {\n hit: false,\n },\n pageContext,\n };\n },\n };\n\n return task;\n }\n\n private planningTaskToGoal(userInstruction: string) {\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'Plan',\n locate: null,\n param: {\n userInstruction,\n },\n executor: async (param, executorContext) => {\n const { pageContext } =\n await this.setupPlanningContext(executorContext);\n\n const imagePayload = await resizeImageForUiTars(\n pageContext.screenshotBase64,\n pageContext.size,\n );\n\n this.appendConversationHistory({\n role: 'user',\n content: [\n {\n type: 'image_url',\n image_url: {\n url: imagePayload,\n },\n },\n ],\n });\n const startTime = Date.now();\n\n const planResult = await vlmPlanning({\n userInstruction: param.userInstruction,\n conversationHistory: this.conversationHistory,\n size: pageContext.size,\n });\n\n const aiCost = Date.now() - startTime;\n const { actions, action_summary } = planResult;\n this.appendConversationHistory({\n role: 'assistant',\n content: action_summary,\n });\n return {\n output: {\n actions,\n thought: actions[0]?.thought,\n actionType: actions[0].type,\n more_actions_needed_by_instruction: true,\n log: '',\n yamlFlow: planResult.yamlFlow,\n },\n cache: {\n hit: false,\n },\n aiCost,\n };\n },\n };\n\n return task;\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n ): Promise<ExecutionResult> {\n const taskExecutor = new Executor(title, {\n onTaskStart: this.onTaskStartCallback,\n });\n const { tasks } = await this.convertPlanToExecutable(plans);\n await taskExecutor.append(tasks);\n const result = await taskExecutor.flush();\n return {\n output: result,\n executor: taskExecutor,\n };\n }\n\n async action(\n userPrompt: string,\n actionContext?: string,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n }\n | undefined\n >\n > {\n const taskExecutor = new Executor(taskTitleStr('Action', userPrompt), {\n onTaskStart: this.onTaskStartCallback,\n });\n\n let planningTask: ExecutionTaskPlanningApply | null =\n this.planningTaskFromPrompt(userPrompt, undefined, actionContext);\n let replanCount = 0;\n const logList: string[] = [];\n\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n while (planningTask) {\n if (replanCount > replanningCountLimit) {\n const errorMsg =\n 'Replanning too many times, please split the task into multiple steps';\n\n return this.appendErrorPlan(taskExecutor, errorMsg);\n }\n\n // plan\n await taskExecutor.append(planningTask);\n const planResult: PlanningAIResponse = await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: planResult,\n executor: taskExecutor,\n };\n }\n\n const plans = planResult.actions || [];\n yamlFlow.push(...(planResult.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(plans);\n taskExecutor.append(executables.tasks);\n } catch (error) {\n return this.appendErrorPlan(\n taskExecutor,\n `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(\n plans,\n )}`,\n );\n }\n\n await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n if (planResult?.log) {\n logList.push(planResult.log);\n }\n\n if (!planResult.more_actions_needed_by_instruction) {\n planningTask = null;\n break;\n }\n planningTask = this.planningTaskFromPrompt(\n userPrompt,\n logList.length > 0 ? `- ${logList.join('\\n- ')}` : undefined,\n actionContext,\n );\n replanCount++;\n }\n\n return {\n output: {\n yamlFlow,\n },\n executor: taskExecutor,\n };\n }\n\n async actionToGoal(userPrompt: string): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n }\n | undefined\n >\n > {\n const taskExecutor = new Executor(taskTitleStr('Action', userPrompt), {\n onTaskStart: this.onTaskStartCallback,\n });\n this.conversationHistory = [];\n const isCompleted = false;\n let currentActionNumber = 0;\n const maxActionNumber = 40;\n\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n while (!isCompleted && currentActionNumber < maxActionNumber) {\n currentActionNumber++;\n const planningTask: ExecutionTaskPlanningApply =\n this.planningTaskToGoal(userPrompt);\n await taskExecutor.append(planningTask);\n const output = await taskExecutor.flush();\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n const plans = output.actions;\n yamlFlow.push(...(output.yamlFlow || []));\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(plans);\n taskExecutor.append(executables.tasks);\n } catch (error) {\n return this.appendErrorPlan(\n taskExecutor,\n `Error converting plans to executable tasks: ${error}, plans: ${JSON.stringify(\n plans,\n )}`,\n );\n }\n\n await taskExecutor.flush();\n\n if (taskExecutor.isInErrorState()) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n if (plans[0].type === 'Finished') {\n break;\n }\n }\n return {\n output: {\n yamlFlow,\n },\n executor: taskExecutor,\n };\n }\n\n private async createTypeQueryTask<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String',\n demand: InsightExtractParam,\n ): Promise<ExecutionResult<T>> {\n const taskExecutor = new Executor(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n onTaskStart: this.onTaskStartCallback,\n },\n );\n\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n locate: null,\n param: {\n dataDemand: demand, // for user param presentation in report right sidebar\n },\n executor: async (param) => {\n let insightDump: InsightDump | undefined;\n const dumpCollector: DumpSubscriber = (dump) => {\n insightDump = dump;\n };\n this.insight.onceDumpUpdatedFn = dumpCollector;\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n if (ifTypeRestricted) {\n demandInput = {\n result: `${type}, ${demand}`,\n };\n }\n\n const { data, usage } = await this.insight.extract<any>(demandInput);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n assert(data?.result !== undefined, 'No result in query data');\n outputResult = (data as any).result;\n }\n\n return {\n output: outputResult,\n log: { dump: insightDump },\n usage,\n };\n },\n };\n\n await taskExecutor.append(this.prependExecutorWithScreenshot(queryTask));\n const output = await taskExecutor.flush();\n return {\n output,\n executor: taskExecutor,\n };\n }\n\n async query(demand: InsightExtractParam): Promise<ExecutionResult> {\n return this.createTypeQueryTask('Query', demand);\n }\n\n async boolean(prompt: string): Promise<ExecutionResult<boolean>> {\n return this.createTypeQueryTask<boolean>('Boolean', prompt);\n }\n\n async number(prompt: string): Promise<ExecutionResult<number>> {\n return this.createTypeQueryTask<number>('Number', prompt);\n }\n\n async string(prompt: string): Promise<ExecutionResult<string>> {\n return this.createTypeQueryTask<string>('String', prompt);\n }\n\n async assert(\n assertion: string,\n ): Promise<ExecutionResult<InsightAssertionResponse>> {\n const description = `assert: ${assertion}`;\n const taskExecutor = new Executor(taskTitleStr('Assert', description), {\n onTaskStart: this.onTaskStartCallback,\n });\n const assertionPlan: PlanningAction<PlanningActionParamAssert> = {\n type: 'Assert',\n param: {\n assertion,\n },\n locate: null,\n };\n const { tasks } = await this.convertPlanToExecutable([assertionPlan]);\n\n await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));\n const output: InsightAssertionResponse = await taskExecutor.flush();\n\n return {\n output,\n executor: taskExecutor,\n };\n }\n\n /**\n * Append a message to the conversation history\n * For user messages with images:\n * - Keep max 4 user image messages in history\n * - Remove oldest user image message when limit reached\n * For assistant messages:\n * - Simply append to history\n * @param conversationHistory Message to append\n */\n private appendConversationHistory(\n conversationHistory: ChatCompletionMessageParam,\n ) {\n if (conversationHistory.role === 'user') {\n // Get all existing user messages with images\n const userImgItems = this.conversationHistory.filter(\n (item) => item.role === 'user',\n );\n\n // If we already have 4 user image messages\n if (userImgItems.length >= 4 && conversationHistory.role === 'user') {\n // Remove first user image message when we already have 4, before adding new one\n const firstUserImgIndex = this.conversationHistory.findIndex(\n (item) => item.role === 'user',\n );\n if (firstUserImgIndex >= 0) {\n this.conversationHistory.splice(firstUserImgIndex, 1);\n }\n }\n }\n // For non-user messages, simply append to history\n this.conversationHistory.push(conversationHistory);\n }\n\n private async appendErrorPlan(taskExecutor: Executor, errorMsg: string) {\n const errorPlan: PlanningAction<PlanningActionParamError> = {\n type: 'Error',\n param: {\n thought: errorMsg,\n },\n locate: null,\n };\n const { tasks } = await this.convertPlanToExecutable([errorPlan]);\n await taskExecutor.append(this.prependExecutorWithScreenshot(tasks[0]));\n await taskExecutor.flush();\n\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n async waitFor(\n assertion: string,\n opt: PlanningActionParamWaitFor,\n ): Promise<ExecutionResult<void>> {\n const description = `waitFor: ${assertion}`;\n const taskExecutor = new Executor(taskTitleStr('WaitFor', description), {\n onTaskStart: this.onTaskStartCallback,\n });\n const { timeoutMs, checkIntervalMs } = opt;\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n const overallStartTime = Date.now();\n let startTime = Date.now();\n let errorThought = '';\n while (Date.now() - overallStartTime < timeoutMs) {\n startTime = Date.now();\n const assertPlan: PlanningAction<PlanningActionParamAssert> = {\n type: 'AssertWithoutThrow',\n param: {\n assertion,\n },\n locate: null,\n };\n const { tasks: assertTasks } = await this.convertPlanToExecutable([\n assertPlan,\n ]);\n await taskExecutor.append(\n this.prependExecutorWithScreenshot(assertTasks[0]),\n );\n const output: InsightAssertionResponse = await taskExecutor.flush();\n\n if (output?.pass) {\n return {\n output: undefined,\n executor: taskExecutor,\n };\n }\n\n errorThought =\n output?.thought ||\n `unknown error when waiting for assertion: ${assertion}`;\n const now = Date.now();\n if (now - startTime < checkIntervalMs) {\n const timeRemaining = checkIntervalMs - (now - startTime);\n const sleepPlan: PlanningAction<PlanningActionParamSleep> = {\n type: 'Sleep',\n param: {\n timeMs: timeRemaining,\n },\n locate: null,\n };\n const { tasks: sleepTasks } = await this.convertPlanToExecutable([\n sleepPlan,\n ]);\n await taskExecutor.append(\n this.prependExecutorWithScreenshot(sleepTasks[0]),\n );\n await taskExecutor.flush();\n }\n }\n\n return this.appendErrorPlan(\n taskExecutor,\n `waitFor timeout: ${errorThought}`,\n );\n }\n}\n","import type {\n DetailedLocateParam,\n ExecutionTask,\n ExecutionTaskAction,\n ExecutionTaskInsightAssertion,\n ExecutionTaskInsightLocate,\n ExecutionTaskInsightQuery,\n ExecutionTaskPlanning,\n PlanningActionParamScroll,\n} from 'misoai-core';\n\nexport function typeStr(task: ExecutionTask) {\n return task.subType && task.subType !== 'Plan'\n ? `${task.type} / ${task.subType || ''}`\n : task.type;\n}\n\nexport function getKeyCommands(\n value: string | string[],\n): Array<{ key: string; command?: string }> {\n // Ensure value is an array of keys\n const keys = Array.isArray(value) ? value : [value];\n\n // Process each key to attach a corresponding command if needed, based on the presence of 'Meta' or 'Control' in the keys array.\n // ref: https://github.com/puppeteer/puppeteer/pull/9357/files#diff-32cf475237b000f980eb214a0a823e45a902bddb7d2426d677cae96397aa0ae4R94\n return keys.reduce((acc: Array<{ key: string; command?: string }>, k) => {\n const includeMeta = keys.includes('Meta') || keys.includes('Control');\n if (includeMeta && (k === 'a' || k === 'A')) {\n return acc.concat([{ key: k, command: 'SelectAll' }]);\n }\n if (includeMeta && (k === 'c' || k === 'C')) {\n return acc.concat([{ key: k, command: 'Copy' }]);\n }\n if (includeMeta && (k === 'v' || k === 'V')) {\n return acc.concat([{ key: k, command: 'Paste' }]);\n }\n return acc.concat([{ key: k }]);\n }, []);\n}\n\nexport function locateParamStr(locate?: DetailedLocateParam) {\n if (!locate) {\n return '';\n }\n\n if (typeof locate === 'string') {\n return locate;\n }\n\n return locate.prompt;\n}\n\nexport function scrollParamStr(scrollParam?: PlanningActionParamScroll) {\n if (!scrollParam) {\n return '';\n }\n return `${scrollParam.direction || 'down'}, ${scrollParam.scrollType || 'once'}, ${scrollParam.distance || 'distance-not-set'}`;\n}\n\nexport function taskTitleStr(\n type:\n | 'Tap'\n | 'Hover'\n | 'Input'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Action'\n | 'Query'\n | 'Assert'\n | 'WaitFor'\n | 'Locate'\n | 'Boolean'\n | 'Number'\n | 'String',\n prompt: string,\n) {\n if (prompt) {\n return `${type} - ${prompt}`;\n }\n return type;\n}\n\nexport function paramStr(task: ExecutionTask) {\n let value: string | undefined | object;\n if (task.type === 'Planning') {\n value = (task as ExecutionTaskPlanning)?.param?.userInstruction;\n }\n\n if (task.type === 'Insight') {\n value =\n (task as ExecutionTaskInsightLocate)?.param?.prompt ||\n (task as ExecutionTaskInsightLocate)?.param?.id ||\n (task as ExecutionTaskInsightQuery)?.param?.dataDemand ||\n (task as ExecutionTaskInsightAssertion)?.param?.assertion;\n }\n\n if (task.type === 'Action') {\n const locate = (task as ExecutionTaskAction)?.locate;\n const locateStr = locate ? locateParamStr(locate) : '';\n\n value = task.thought || '';\n if (typeof (task as ExecutionTaskAction)?.param?.timeMs === 'number') {\n value = `${(task as ExecutionTaskAction)?.param?.timeMs}ms`;\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.scrollType === 'string'\n ) {\n value = scrollParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.value !== 'undefined'\n ) {\n value = (task as ExecutionTaskAction)?.param?.value;\n }\n\n if (locateStr) {\n if (value) {\n value = `${locateStr} - ${value}`;\n } else {\n value = locateStr;\n }\n }\n }\n\n if (typeof value === 'undefined') return '';\n return typeof value === 'string'\n ? value\n : JSON.stringify(value, undefined, 2);\n}\n\nexport const limitOpenNewTabScript = `\nif (!window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__) {\n window.__MIDSCENE_NEW_TAB_INTERCEPTOR_INITIALIZED__ = true;\n\n // Intercept the window.open method (only once)\n window.open = function(url) {\n console.log('Blocked window.open:', url);\n window.location.href = url;\n return null;\n };\n\n // Block all a tag clicks with target=\"_blank\" (only once)\n document.addEventListener('click', function(e) {\n const target = e.target.closest('a');\n if (target && target.target === '_blank') {\n e.preventDefault();\n console.log('Blocked new tab:', target.href);\n window.location.href = target.href;\n target.removeAttribute('target');\n }\n }, true);\n}\n`;\n","import type { StaticPage } from '@/playground';\nimport type {\n BaseElement,\n ElementTreeNode,\n PlanningLocateParam,\n PlaywrightParserOpt,\n UIContext,\n} from 'misoai-core';\nimport { elementByPositionWithElementInfo } from 'misoai-core/ai-model';\nimport { uploadTestInfoToServer } from 'misoai-core/utils';\nimport { MIDSCENE_REPORT_TAG_NAME, getAIConfig } from 'misoai-shared/env';\nimport type { ElementInfo } from 'misoai-shared/extractor';\nimport {\n generateElementByPosition,\n getNodeFromCacheList,\n traverseTree,\n treeToList,\n} from 'misoai-shared/extractor';\nimport { resizeImgBase64 } from 'misoai-shared/img';\nimport type { DebugFunction } from 'misoai-shared/logger';\nimport { assert, logMsg, uuid } from 'misoai-shared/utils';\nimport dayjs from 'dayjs';\nimport type { Page as PlaywrightPage } from 'playwright';\nimport type { Page as PuppeteerPage } from 'puppeteer';\nimport { WebElementInfo } from '../web-element';\nimport type { WebPage } from './page';\n\nexport type WebUIContext = UIContext<WebElementInfo> & {\n url: string;\n};\n\nexport async function parseContextFromWebPage(\n page: WebPage,\n _opt?: PlaywrightParserOpt,\n): Promise<WebUIContext> {\n assert(page, 'page is required');\n if ((page as StaticPage)._forceUsePageContext) {\n return await (page as any)._forceUsePageContext();\n }\n const url = await page.url();\n uploadTestInfoToServer({ testUrl: url });\n\n let screenshotBase64: string;\n let tree: ElementTreeNode<ElementInfo>;\n\n await Promise.all([\n page.screenshotBase64().then((base64) => {\n screenshotBase64 = base64;\n }),\n page.getElementsNodeTree().then(async (treeRoot) => {\n tree = treeRoot;\n }),\n ]);\n\n const webTree = traverseTree(tree!, (elementInfo) => {\n const { rect, id, content, attributes, locator, indexId } = elementInfo;\n return new WebElementInfo({\n rect,\n locator,\n id,\n content,\n attributes,\n indexId,\n });\n });\n\n assert(screenshotBase64!, 'screenshotBase64 is required');\n\n const elementsInfo = treeToList(webTree);\n const size = await page.size();\n\n if (size.dpr && size.dpr > 1) {\n // console.time('resizeImgBase64');\n screenshotBase64 = await resizeImgBase64(screenshotBase64, {\n width: size.width,\n height: size.height,\n });\n // console.timeEnd('resizeImgBase64');\n }\n\n return {\n content: elementsInfo!,\n tree: webTree,\n size,\n screenshotBase64: screenshotBase64!,\n url,\n };\n}\n\nexport function reportFileName(tag = 'web') {\n const reportTagName = getAIConfig(MIDSCENE_REPORT_TAG_NAME);\n const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');\n // ensure uniqueness at the same time\n const uniqueId = uuid().substring(0, 8);\n return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;\n}\n\nexport function printReportMsg(filepath: string) {\n logMsg(`Midscene - report file updated: ${filepath}`);\n}\n\n/**\n * Get the current execution file name\n * @returns The name of the current execution file\n */\nexport function getCurrentExecutionFile(trace?: string): string | false {\n const error = new Error();\n const stackTrace = trace || error.stack;\n const pkgDir = process.cwd() || '';\n if (stackTrace) {\n const stackLines = stackTrace.split('\\n');\n for (const line of stackLines) {\n if (\n line.includes('.spec.') ||\n line.includes('.test.') ||\n line.includes('.ts') ||\n line.includes('.js')\n ) {\n const match = line.match(/(?:at\\s+)?(.*?\\.(?:spec|test)\\.[jt]s)/);\n if (match?.[1]) {\n const targetFileName = match[1]\n .replace(pkgDir, '')\n .trim()\n .replace('at ', '');\n return targetFileName;\n }\n }\n }\n }\n return false;\n}\n\nconst testFileIndex = new Map<string, number>();\n\nexport function generateCacheId(fileName?: string): string {\n let taskFile = fileName || getCurrentExecutionFile();\n if (!taskFile) {\n taskFile = uuid();\n console.warn(\n 'Midscene - using random UUID for cache id. Cache may be invalid.',\n );\n }\n\n if (testFileIndex.has(taskFile)) {\n const currentIndex = testFileIndex.get(taskFile);\n if (currentIndex !== undefined) {\n testFileIndex.set(taskFile, currentIndex + 1);\n }\n } else {\n testFileIndex.set(taskFile, 1);\n }\n return `${taskFile}-${testFileIndex.get(taskFile)}`;\n}\n\nexport const ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED =\n 'NOT_IMPLEMENTED_AS_DESIGNED';\n\nexport function replaceIllegalPathCharsAndSpace(str: string) {\n return str.replace(/[/\\\\:*?\"<>| ]/g, '-');\n}\n\nexport function forceClosePopup(\n page: PuppeteerPage | PlaywrightPage,\n debug: DebugFunction,\n) {\n page.on('popup', async (popup) => {\n if (!popup) {\n console.warn('got a popup event, but the popup is not ready yet, skip');\n return;\n }\n const url = await (popup as PuppeteerPage).url();\n console.log(`Popup opened: ${url}`);\n if (!(popup as PuppeteerPage).isClosed()) {\n try {\n await (popup as PuppeteerPage).close(); // Close the newly opened TAB\n } catch (error) {\n debug(`failed to close popup ${url}, error: ${error}`);\n }\n } else {\n debug(`popup is already closed, skip close ${url}`);\n }\n\n if (!page.isClosed()) {\n try {\n await page.goto(url);\n } catch (error) {\n debug(`failed to goto ${url}, error: ${error}`);\n }\n } else {\n debug(`page is already closed, skip goto ${url}`);\n }\n });\n}\n\nexport function matchElementFromPlan(\n planLocateParam: PlanningLocateParam,\n tree: ElementTreeNode<BaseElement>,\n) {\n if (!planLocateParam) {\n return undefined;\n }\n if (planLocateParam.id) {\n return getNodeFromCacheList(planLocateParam.id);\n }\n\n if (planLocateParam.bbox) {\n const centerPosition = {\n x: Math.floor((planLocateParam.bbox[0] + planLocateParam.bbox[2]) / 2),\n y: Math.floor((planLocateParam.bbox[1] + planLocateParam.bbox[3]) / 2),\n };\n let element = elementByPositionWithElementInfo(tree, centerPosition);\n\n if (!element) {\n element = generateElementByPosition(centerPosition) as BaseElement;\n }\n\n return element;\n }\n\n return undefined;\n}\n","import type { BaseElement, Rect } from 'misoai-core';\nimport type { NodeType } from 'misoai-shared/constants';\nexport interface WebElementInfoType extends BaseElement {\n id: string;\n locator: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n}\n\nexport class WebElementInfo implements BaseElement {\n content: string;\n\n locator?: string;\n\n rect: Rect;\n\n center: [number, number];\n\n // page: WebPage;\n\n id: string;\n\n indexId: number;\n\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n\n xpaths?: string[];\n\n constructor({\n content,\n rect,\n // page,\n locator,\n id,\n attributes,\n indexId,\n xpaths,\n }: {\n content: string;\n rect: Rect;\n // page: WebPage;\n locator?: string;\n id: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n indexId: number;\n xpaths?: string[];\n }) {\n this.content = content;\n this.rect = rect;\n this.center = [\n Math.floor(rect.left + rect.width / 2),\n Math.floor(rect.top + rect.height / 2),\n ];\n // this.page = page;\n this.locator = locator;\n this.id = id;\n this.attributes = attributes;\n this.indexId = indexId;\n this.xpaths = xpaths;\n }\n}\n","import type {\n DetailedLocateParam,\n MidsceneYamlFlowItem,\n PlanningAction,\n PlanningActionParamInputOrKeyPress,\n PlanningActionParamScroll,\n PlanningActionParamSleep,\n PlanningActionParamTap,\n PlanningLocateParam,\n} from 'misoai-core';\nimport { getDebug } from 'misoai-shared/logger';\nimport { assert } from 'misoai-shared/utils';\n\nconst debug = getDebug('plan-builder');\n\nexport function buildPlans(\n type: PlanningAction['type'],\n locateParam?: DetailedLocateParam,\n param?:\n | PlanningActionParamInputOrKeyPress\n | PlanningActionParamScroll\n | PlanningActionParamSleep,\n): PlanningAction[] {\n let returnPlans: PlanningAction[] = [];\n const locatePlan: PlanningAction<PlanningLocateParam> | null = locateParam\n ? {\n type: 'Locate',\n locate: locateParam,\n param: locateParam,\n thought: '',\n }\n : null;\n if (type === 'Tap' || type === 'Hover') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n assert(locatePlan, `missing locate info for action \"${type}\"`);\n const tapPlan: PlanningAction<PlanningActionParamTap> = {\n type,\n param: null,\n thought: '',\n locate: locateParam,\n };\n\n returnPlans = [locatePlan, tapPlan];\n }\n if (type === 'Input' || type === 'KeyboardPress') {\n if (type === 'Input') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n }\n assert(param, `missing param for action \"${type}\"`);\n\n const inputPlan: PlanningAction<PlanningActionParamInputOrKeyPress> = {\n type,\n param: param as PlanningActionParamInputOrKeyPress,\n thought: '',\n locate: locateParam!,\n };\n\n if (locatePlan) {\n returnPlans = [locatePlan, inputPlan];\n } else {\n returnPlans = [inputPlan];\n }\n }\n\n if (type === 'Scroll') {\n assert(param, `missing param for action \"${type}\"`);\n\n const scrollPlan: PlanningAction<PlanningActionParamScroll> = {\n type,\n param: param as PlanningActionParamScroll,\n thought: '',\n locate: locateParam,\n };\n\n if (locatePlan) {\n returnPlans = [locatePlan, scrollPlan];\n } else {\n returnPlans = [scrollPlan];\n }\n }\n\n if (type === 'Sleep') {\n assert(param, `missing param for action \"${type}\"`);\n\n const sleepPlan: PlanningAction<PlanningActionParamSleep> = {\n type,\n param: param as PlanningActionParamSleep,\n thought: '',\n locate: null,\n };\n\n returnPlans = [sleepPlan];\n }\n\n if (type === 'Locate') {\n assert(locateParam, `missing locate info for action \"${type}\"`);\n const locatePlan: PlanningAction<PlanningLocateParam> = {\n type,\n param: locateParam as PlanningLocateParam,\n locate: locateParam,\n thought: '',\n };\n returnPlans = [locatePlan];\n }\n\n if (returnPlans) {\n debug('buildPlans', returnPlans);\n return returnPlans;\n }\n\n throw new Error(`Not supported type: ${type}`);\n}\n","import assert from 'node:assert';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getMidsceneRunSubDir } from 'misoai-shared/common';\nimport { getDebug } from 'misoai-shared/logger';\nimport { ifInBrowser } from 'misoai-shared/utils';\nimport yaml from 'js-yaml';\nimport semver from 'semver';\nimport { version } from '../../package.json';\nimport { replaceIllegalPathCharsAndSpace } from './utils';\n\nconst debug = getDebug('cache');\n\nexport interface PlanningCache {\n type: 'plan';\n prompt: string;\n yamlWorkflow: string;\n}\n\nexport interface LocateCache {\n type: 'locate';\n prompt: string;\n xpaths: string[];\n}\n\nexport interface MatchCacheResult<T extends PlanningCache | LocateCache> {\n cacheContent: T;\n updateFn: (cb: (cache: T) => void) => void;\n}\n\nexport type CacheFileContent = {\n midsceneVersion: string;\n cacheId: string;\n caches: Array<PlanningCache | LocateCache>;\n};\n\nconst lowestSupportedMidsceneVersion = '0.16.10';\nconst cacheFileExt = '.cache.yaml';\n\nexport class TaskCache {\n cacheId: string;\n\n cacheFilePath?: string;\n\n cache: CacheFileContent;\n\n isCacheResultUsed: boolean; // a flag to indicate if the cache result should be used\n cacheOriginalLength: number;\n\n private matchedCacheIndices: Set<string> = new Set(); // Track matched records\n\n constructor(\n cacheId: string,\n isCacheResultUsed: boolean,\n cacheFilePath?: string,\n ) {\n assert(cacheId, 'cacheId is required');\n this.cacheId = replaceIllegalPathCharsAndSpace(cacheId);\n\n this.cacheFilePath = ifInBrowser\n ? undefined\n : cacheFilePath ||\n join(getMidsceneRunSubDir('cache'), `${this.cacheId}${cacheFileExt}`);\n\n this.isCacheResultUsed = isCacheResultUsed;\n\n let cacheContent;\n if (this.cacheFilePath) {\n cacheContent = this.loadCacheFromFile();\n }\n if (!cacheContent) {\n cacheContent = {\n midsceneVersion: version,\n cacheId: this.cacheId,\n caches: [],\n };\n }\n this.cache = cacheContent;\n this.cacheOriginalLength = this.cache.caches.length;\n }\n\n matchCache(\n prompt: string,\n type: 'plan' | 'locate',\n ): MatchCacheResult<PlanningCache | LocateCache> | undefined {\n // Find the first unused matching cache\n for (let i = 0; i < this.cacheOriginalLength; i++) {\n const item = this.cache.caches[i];\n const key = `${type}:${prompt}:${i}`;\n if (\n item.type === type &&\n item.prompt === prompt &&\n !this.matchedCacheIndices.has(key)\n ) {\n this.matchedCacheIndices.add(key);\n debug(\n 'cache found and marked as used, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n return {\n cacheContent: item,\n updateFn: (cb: (cache: PlanningCache | LocateCache) => void) => {\n debug(\n 'will call updateFn to update cache, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n cb(item);\n debug(\n 'cache updated, will flush to file, type: %s, prompt: %s, index: %d',\n type,\n prompt,\n i,\n );\n this.flushCacheToFile();\n },\n };\n }\n }\n debug('no unused cache found, type: %s, prompt: %s', type, prompt);\n return undefined;\n }\n\n matchPlanCache(prompt: string): MatchCacheResult<PlanningCache> | undefined {\n return this.matchCache(prompt, 'plan') as\n | MatchCacheResult<PlanningCache>\n | undefined;\n }\n\n matchLocateCache(prompt: string): MatchCacheResult<LocateCache> | undefined {\n return this.matchCache(prompt, 'locate') as\n | MatchCacheResult<LocateCache>\n | undefined;\n }\n\n appendCache(cache: PlanningCache | LocateCache) {\n debug('will append cache', cache);\n this.cache.caches.push(cache);\n this.flushCacheToFile();\n }\n\n loadCacheFromFile() {\n const cacheFile = this.cacheFilePath;\n assert(cacheFile, 'cache file path is required');\n\n if (!existsSync(cacheFile)) {\n debug('no cache file found, path: %s', cacheFile);\n return undefined;\n }\n\n // detect old cache file\n const jsonTypeCacheFile = cacheFile.replace(cacheFileExt, '.json');\n if (existsSync(jsonTypeCacheFile) && this.isCacheResultUsed) {\n console.warn(\n `An outdated cache file from an earlier version of Midscene has been detected. Since version 0.17, we have implemented an improved caching strategy. Please delete the old file located at: ${jsonTypeCacheFile}.`,\n );\n return undefined;\n }\n\n try {\n const data = readFileSync(cacheFile, 'utf8');\n const jsonData = yaml.load(data) as CacheFileContent;\n\n if (!version) {\n debug('no midscene version info, will not read cache from file');\n return undefined;\n }\n\n if (\n semver.lt(jsonData.midsceneVersion, lowestSupportedMidsceneVersion) &&\n !jsonData.midsceneVersion.includes('beta') // for internal test\n ) {\n console.warn(\n `You are using an old version of Midscene cache file, and we cannot match any info from it. Starting from Midscene v0.17, we changed our strategy to use xpath for cache info, providing better performance.\\nPlease delete the existing cache and rebuild it. Sorry for the inconvenience.\\ncache file: ${cacheFile}`,\n );\n return undefined;\n }\n\n debug(\n 'cache loaded from file, path: %s, cache version: %s, record length: %s',\n cacheFile,\n jsonData.midsceneVersion,\n jsonData.caches.length,\n );\n jsonData.midsceneVersion = version; // update the version\n return jsonData;\n } catch (err) {\n debug(\n 'cache file exists but load failed, path: %s, error: %s',\n cacheFile,\n err,\n );\n return undefined;\n }\n }\n\n flushCacheToFile() {\n if (!version) {\n debug('no midscene version info, will not write cache to file');\n return;\n }\n\n if (!this.cacheFilePath) {\n debug('no cache file path, will not write cache to file');\n return;\n }\n\n try {\n const yamlData = yaml.dump(this.cache);\n writeFileSync(this.cacheFilePath, yamlData);\n } catch (err) {\n debug(\n 'write cache to file failed, path: %s, error: %s',\n this.cacheFilePath,\n err,\n );\n }\n }\n\n updateOrAppendCacheRecord(\n newRecord: PlanningCache | LocateCache,\n cachedRecord?: MatchCacheResult<PlanningCache | LocateCache>,\n ) {\n if (cachedRecord) {\n // update existing record\n if (newRecord.type === 'plan') {\n cachedRecord.updateFn((cache) => {\n (cache as PlanningCache).yamlWorkflow = newRecord.yamlWorkflow;\n });\n } else {\n cachedRecord.updateFn((cache) => {\n (cache as LocateCache).xpaths = newRecord.xpaths;\n });\n }\n } else {\n this.appendCache(newRecord);\n }\n }\n}\n","{\n \"name\": \"misoai-web\",\n \"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.\",\n \"keywords\": [\n \"AI UI automation\",\n \"AI testing\",\n \"Computer use\",\n \"Browser use\",\n \"Android use\"\n ],\n \"version\": \"1.0.2\",\n \"repository\": \"https://github.com/web-infra-dev/midscene\",\n \"homepage\": \"https://midscenejs.com/\",\n \"jsnext:source\": \"./src/index.ts\",\n \"main\": \"./dist/lib/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"bin\": {\n \"misoai-playground\": \"./bin/midscene-playground\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/types/index.d.ts\",\n \"default\": \"./dist/lib/index.js\"\n },\n \"./bridge-mode\": {\n \"types\": \"./dist/types/bridge-mode.d.ts\",\n \"default\": \"./dist/lib/bridge-mode.js\"\n },\n \"./bridge-mode-browser\": {\n \"types\": \"./dist/types/bridge-mode-browser.d.ts\",\n \"default\": \"./dist/lib/bridge-mode-browser.js\"\n },\n \"./utils\": {\n \"types\": \"./dist/types/utils.d.ts\",\n \"default\": \"./dist/lib/utils.js\"\n },\n \"./ui-utils\": {\n \"types\": \"./dist/types/ui-utils.d.ts\",\n \"default\": \"./dist/lib/ui-utils.js\"\n },\n \"./puppeteer\": {\n \"types\": \"./dist/types/puppeteer.d.ts\",\n \"default\": \"./dist/lib/puppeteer.js\"\n },\n \"./puppeteer-agent-launcher\": {\n \"types\": \"./dist/types/puppeteer-agent-launcher.d.ts\",\n \"default\": \"./dist/lib/puppeteer-agent-launcher.js\"\n },\n \"./playwright\": {\n \"types\": \"./dist/types/playwright.d.ts\",\n \"default\": \"./dist/lib/playwright.js\"\n },\n \"./playwright-report\": {\n \"types\": \"./dist/types/playwright-report.d.ts\",\n \"default\": \"./dist/lib/playwright-report.js\"\n },\n \"./playground\": {\n \"types\": \"./dist/types/playground.d.ts\",\n \"default\": \"./dist/lib/playground.js\"\n },\n \"./midscene-playground\": {\n \"types\": \"./dist/types/midscene-playground.d.ts\",\n \"default\": \"./dist/lib/midscene-playground.js\"\n },\n \"./midscene-server\": {\n \"types\": \"./dist/types/midscene-server.d.ts\",\n \"default\": \"./dist/lib/midscene-server.js\"\n },\n \"./chrome-extension\": {\n \"types\": \"./dist/types/chrome-extension.d.ts\",\n \"default\": \"./dist/lib/chrome-extension.js\"\n },\n \"./yaml\": {\n \"types\": \"./dist/types/yaml.d.ts\",\n \"default\": \"./dist/lib/yaml.js\"\n },\n \"./agent\": {\n \"types\": \"./dist/types/agent.d.ts\",\n \"default\": \"./dist/lib/agent.js\"\n }\n },\n \"typesVersions\": {\n \"*\": {\n \".\": [\n \"./dist/types/index.d.ts\"\n ],\n \"bridge-mode\": [\n \"./dist/types/bridge-mode.d.ts\"\n ],\n \"bridge-mode-browser\": [\n \"./dist/types/bridge-mode-browser.d.ts\"\n ],\n \"utils\": [\n \"./dist/types/utils.d.ts\"\n ],\n \"ui-utils\": [\n \"./dist/types/ui-utils.d.ts\"\n ],\n \"puppeteer\": [\n \"./dist/types/puppeteer.d.ts\"\n ],\n \"puppeteer-agent-launcher\": [\n \"./dist/types/puppeteer-agent-launcher.d.ts\"\n ],\n \"playwright\": [\n \"./dist/types/playwright.d.ts\"\n ],\n \"playwright-report\": [\n \"./dist/types/playwright-report.d.ts\"\n ],\n \"playground\": [\n \"./dist/types/playground.d.ts\"\n ],\n \"midscene-playground\": [\n \"./dist/types/midscene-playground.d.ts\"\n ],\n \"midscene-server\": [\n \"./dist/types/midscene-server.d.ts\"\n ],\n \"chrome-extension\": [\n \"./dist/types/chrome-extension.d.ts\"\n ],\n \"yaml\": [\n \"./dist/types/yaml.d.ts\"\n ],\n \"agent\": [\n \"./dist/types/agent.d.ts\"\n ]\n }\n },\n \"watch\": {\n \"build\": {\n \"patterns\": [\n \"src\"\n ],\n \"extensions\": \"tsx,less,scss,css,js,jsx,ts\",\n \"quiet\": false\n }\n },\n \"scripts\": {\n \"dev\": \"npm run build && npx npm-watch\",\n \"dev:server\": \"npm run build && ./bin/midscene-playground\",\n \"build\": \"modern build -c ./modern.config.ts\",\n \"postbuild\": \"node scripts/check-exports.js\",\n \"build:watch\": \"modern build -w -c ./modern.config.ts\",\n \"test\": \"vitest --run\",\n \"test:u\": \"vitest --run -u\",\n \"test:ai\": \"AI_TEST_TYPE=web npm run test\",\n \"test:ai:temp\": \"MIDSCENE_CACHE=true BRIDGE_MODE=true vitest --run tests/ai/bridge/open-new-tab.test.ts\",\n \"test:ai:bridge\": \"MIDSCENE_CACHE=true BRIDGE_MODE=true npm run test --inspect tests/ai/bridge/temp.test.ts\",\n \"test:ai:cache\": \"MIDSCENE_CACHE=true npm run test\",\n \"upgrade\": \"modern upgrade\",\n \"e2e\": \"playwright test --config=tests/playwright.config.ts\",\n \"e2e:report\": \"MIDSCENE_REPORT=true playwright test --config=tests/playwright.config.ts\",\n \"e2e:cache\": \"MIDSCENE_CACHE=true playwright test --config=tests/playwright.config.ts\",\n \"e2e:ui\": \"playwright test --config=tests/playwright.config.ts --ui\",\n \"e2e:ui:cache\": \"MIDSCENE_CACHE=true playwright test --config=tests/playwright.config.ts --ui\"\n },\n \"files\": [\n \"static\",\n \"dist\",\n \"iife-script\",\n \"README.md\",\n \"bin\"\n ],\n \"dependencies\": {\n \"misoai-core\": \"1.0.1\",\n \"misoai-shared\": \"1.0.0\",\n \"@xmldom/xmldom\": \"0.8.10\",\n \"cors\": \"2.8.5\",\n \"dayjs\": \"1.11.11\",\n \"devtools-protocol\": \"0.0.1380148\",\n \"dotenv\": \"16.4.5\",\n \"express\": \"^4.21.2\",\n \"fs-extra\": \"11.2.0\",\n \"http-server\": \"14.1.1\",\n \"inquirer\": \"10.1.5\",\n \"js-sha256\": \"0.11.0\",\n \"js-yaml\": \"4.1.0\",\n \"openai\": \"4.81.0\",\n \"semver\": \"7.5.2\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"4.8.1\"\n },\n \"devDependencies\": {\n \"@modern-js/module-tools\": \"2.60.6\",\n \"@playwright/test\": \"^1.44.1\",\n \"@types/chrome\": \"0.0.279\",\n \"@types/cors\": \"2.8.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/fs-extra\": \"11.0.4\",\n \"@types/js-yaml\": \"4.0.9\",\n \"@types/node\": \"^18.0.0\",\n \"@types/semver\": \"7.7.0\",\n \"playwright\": \"1.44.1\",\n \"puppeteer\": \"24.2.0\",\n \"typescript\": \"^5.8.2\",\n \"vitest\": \"3.0.5\"\n },\n \"peerDependencies\": {\n \"@playwright/test\": \"^1.44.1\",\n \"playwright\": \"1.44.1\",\n \"puppeteer\": \"24.2.0\"\n },\n \"peerDependenciesMeta\": {\n \"@playwright/test\": {\n \"optional\": true\n },\n \"puppeteer\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org\"\n },\n \"license\": \"MIT\"\n}\n"]}
|