@midscene/core 0.30.3-beta-20251014030035.0 → 0.30.3-beta-20251015093703.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/agent/agent.mjs +30 -41
- package/dist/es/agent/agent.mjs.map +1 -1
- package/dist/es/agent/task-cache.mjs +17 -1
- package/dist/es/agent/task-cache.mjs.map +1 -1
- package/dist/es/agent/utils.mjs +1 -1
- package/dist/es/report.mjs +88 -0
- package/dist/es/report.mjs.map +1 -0
- package/dist/es/types.mjs.map +1 -1
- package/dist/es/utils.mjs +31 -22
- package/dist/es/utils.mjs.map +1 -1
- package/dist/lib/agent/agent.js +39 -51
- package/dist/lib/agent/agent.js.map +1 -1
- package/dist/lib/agent/task-cache.js +17 -1
- package/dist/lib/agent/task-cache.js.map +1 -1
- package/dist/lib/agent/utils.js +1 -1
- package/dist/lib/report.js +122 -0
- package/dist/lib/report.js.map +1 -0
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/utils.js +41 -26
- package/dist/lib/utils.js.map +1 -1
- package/dist/types/agent/agent.d.ts +8 -6
- package/dist/types/agent/task-cache.d.ts +3 -1
- package/dist/types/report.d.ts +12 -0
- package/dist/types/types.d.ts +11 -0
- package/dist/types/utils.d.ts +8 -5
- package/package.json +8 -3
package/dist/es/agent/agent.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { Insight } from "../index.mjs";
|
|
2
2
|
import js_yaml from "js-yaml";
|
|
3
|
-
import { groupedActionDumpFileExt, reportHTMLContent, stringifyDumpData, writeLogFile } from "../utils.mjs";
|
|
3
|
+
import { groupedActionDumpFileExt, processCacheConfig, reportHTMLContent, stringifyDumpData, writeLogFile } from "../utils.mjs";
|
|
4
4
|
import { ScriptPlayer, buildDetailedLocateParam, parseYamlScript } from "../yaml/index.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { ModelConfigManager, globalModelConfigManager } from "@midscene/shared/env";
|
|
6
6
|
import { imageInfoOfBase64, resizeImgBase64 } from "@midscene/shared/img";
|
|
7
7
|
import { getDebug } from "@midscene/shared/logger";
|
|
8
8
|
import { assert } from "@midscene/shared/utils";
|
|
@@ -475,6 +475,7 @@ class Agent {
|
|
|
475
475
|
}
|
|
476
476
|
async destroy() {
|
|
477
477
|
var _this_interface_destroy, _this_interface;
|
|
478
|
+
if (this.destroyed) return;
|
|
478
479
|
await (null == (_this_interface_destroy = (_this_interface = this.interface).destroy) ? void 0 : _this_interface_destroy.call(_this_interface));
|
|
479
480
|
this.resetDump();
|
|
480
481
|
this.destroyed = true;
|
|
@@ -558,44 +559,32 @@ class Agent {
|
|
|
558
559
|
debug('Page context unfrozen successfully');
|
|
559
560
|
}
|
|
560
561
|
processCacheConfig(opts) {
|
|
561
|
-
if (
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
writeOnly: isWriteOnly
|
|
581
|
-
};
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
if (opts.cacheId) {
|
|
585
|
-
const envEnabled = globalConfigManager.getEnvConfigInBoolean(MIDSCENE_CACHE);
|
|
586
|
-
if (envEnabled) return {
|
|
587
|
-
id: opts.cacheId,
|
|
588
|
-
enabled: true,
|
|
589
|
-
readOnly: false,
|
|
590
|
-
writeOnly: false
|
|
562
|
+
if (true === opts.cache) throw new Error('cache: true requires an explicit cache ID. Please provide:\nExample: cache: { id: "my-cache-id" }');
|
|
563
|
+
if (opts.cache && 'object' == typeof opts.cache && null !== opts.cache && !opts.cache.id) throw new Error('cache configuration requires an explicit id.\nExample: cache: { id: "my-cache-id" }');
|
|
564
|
+
const cacheConfig = processCacheConfig(opts.cache, opts.testId || 'default', opts.cacheId);
|
|
565
|
+
if (!cacheConfig) return null;
|
|
566
|
+
if ('object' == typeof cacheConfig && null !== cacheConfig) {
|
|
567
|
+
const id = cacheConfig.id;
|
|
568
|
+
const rawStrategy = cacheConfig.strategy;
|
|
569
|
+
let strategyValue;
|
|
570
|
+
if (void 0 === rawStrategy) strategyValue = 'read-write';
|
|
571
|
+
else if ('string' == typeof rawStrategy) strategyValue = rawStrategy;
|
|
572
|
+
else throw new Error(`cache.strategy must be a string when provided, but received type ${typeof rawStrategy}`);
|
|
573
|
+
if (!isValidCacheStrategy(strategyValue)) throw new Error(`cache.strategy must be one of ${CACHE_STRATEGY_VALUES}, but received "${strategyValue}"`);
|
|
574
|
+
const isReadOnly = 'read-only' === strategyValue;
|
|
575
|
+
const isWriteOnly = 'write-only' === strategyValue;
|
|
576
|
+
return {
|
|
577
|
+
id,
|
|
578
|
+
enabled: !isWriteOnly,
|
|
579
|
+
readOnly: isReadOnly,
|
|
580
|
+
writeOnly: isWriteOnly
|
|
591
581
|
};
|
|
592
582
|
}
|
|
593
583
|
return null;
|
|
594
584
|
}
|
|
595
|
-
async flushCache() {
|
|
585
|
+
async flushCache(options) {
|
|
596
586
|
if (!this.taskCache) throw new Error('Cache is not configured');
|
|
597
|
-
|
|
598
|
-
this.taskCache.flushCacheToFile();
|
|
587
|
+
this.taskCache.flushCacheToFile(options);
|
|
599
588
|
}
|
|
600
589
|
constructor(interfaceInstance, opts){
|
|
601
590
|
_define_property(this, "interface", void 0);
|
|
@@ -625,11 +614,11 @@ class Agent {
|
|
|
625
614
|
if ((null == opts ? void 0 : opts.modelConfig) && 'function' != typeof (null == opts ? void 0 : opts.modelConfig)) throw new Error(`opts.modelConfig must be one of function or undefined, but got ${typeof (null == opts ? void 0 : opts.modelConfig)}`);
|
|
626
615
|
this.modelConfigManager = (null == opts ? void 0 : opts.modelConfig) ? new ModelConfigManager(opts.modelConfig) : globalModelConfigManager;
|
|
627
616
|
this.onTaskStartTip = this.opts.onTaskStartTip;
|
|
628
|
-
this.insight = new
|
|
629
|
-
const
|
|
630
|
-
if (
|
|
631
|
-
readOnly:
|
|
632
|
-
writeOnly:
|
|
617
|
+
this.insight = new Insight(async (action)=>this.getUIContext(action));
|
|
618
|
+
const cacheConfigObj = this.processCacheConfig(opts || {});
|
|
619
|
+
if (cacheConfigObj) this.taskCache = new TaskCache(cacheConfigObj.id, cacheConfigObj.enabled, void 0, {
|
|
620
|
+
readOnly: cacheConfigObj.readOnly,
|
|
621
|
+
writeOnly: cacheConfigObj.writeOnly
|
|
633
622
|
});
|
|
634
623
|
this.taskExecutor = new TaskExecutor(this.interface, this.insight, {
|
|
635
624
|
taskCache: this.taskCache,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent/agent.mjs","sources":["webpack://@midscene/core/./src/agent/agent.ts"],"sourcesContent":["import type { Executor } from '@/ai-model/action-executor';\nimport type { TUserPrompt } from '@/ai-model/common';\nimport Insight from '@/insight';\nimport type {\n AgentAssertOpt,\n AgentDescribeElementAtPointResult,\n AgentOpt,\n AgentWaitForOpt,\n CacheConfig,\n DeviceAction,\n ExecutionDump,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskLog,\n GroupedActionDump,\n InsightAction,\n InsightExtractOption,\n InsightExtractParam,\n LocateOption,\n LocateResultElement,\n LocateValidatorResult,\n LocatorValidatorOption,\n MidsceneYamlScript,\n OnTaskStartTip,\n PlanningAction,\n Rect,\n ScrollParam,\n UIContext,\n} from '@/types';\n\nimport yaml from 'js-yaml';\n\nimport {\n groupedActionDumpFileExt,\n reportHTMLContent,\n stringifyDumpData,\n writeLogFile,\n} from '@/utils';\nimport {\n ScriptPlayer,\n buildDetailedLocateParam,\n parseYamlScript,\n} from '../yaml/index';\n\nimport type { AbstractInterface } from '@/device';\nimport {\n MIDSCENE_CACHE,\n ModelConfigManager,\n globalConfigManager,\n globalModelConfigManager,\n} from '@midscene/shared/env';\nimport { imageInfoOfBase64, resizeImgBase64 } from '@midscene/shared/img';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\n// import type { AndroidDeviceInputOpt } from '../device';\nimport { TaskCache } from './task-cache';\nimport { TaskExecutor, locatePlanForLocate } from './tasks';\nimport { locateParamStr, paramStr, taskTitleStr, typeStr } from './ui-utils';\nimport {\n commonContextParser,\n getReportFileName,\n parsePrompt,\n printReportMsg,\n} from './utils';\nimport { trimContextByViewport } from './utils';\n\nconst debug = getDebug('agent');\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\nconst defaultInsightExtractOption: InsightExtractOption = {\n domIncluded: false,\n screenshotIncluded: true,\n};\n\ntype CacheStrategy = NonNullable<CacheConfig['strategy']>;\n\nconst CACHE_STRATEGIES: readonly CacheStrategy[] = [\n 'read-only',\n 'read-write',\n 'write-only',\n];\n\nconst isValidCacheStrategy = (strategy: string): strategy is CacheStrategy =>\n CACHE_STRATEGIES.some((value) => value === strategy);\n\nconst CACHE_STRATEGY_VALUES = CACHE_STRATEGIES.map(\n (value) => `\"${value}\"`,\n).join(', ');\n\nexport class Agent<\n InterfaceType extends AbstractInterface = AbstractInterface,\n> {\n interface: InterfaceType;\n\n insight: Insight;\n\n dump: GroupedActionDump;\n\n reportFile?: string | null;\n\n reportFileName?: string;\n\n taskExecutor: TaskExecutor;\n\n opts: AgentOpt;\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 onDumpUpdate?: (dump: string) => void;\n\n destroyed = false;\n\n modelConfigManager: ModelConfigManager;\n\n /**\n * Frozen page context for consistent AI operations\n */\n private frozenUIContext?: UIContext;\n\n /**\n * Flag to track if VL model warning has been shown\n */\n private hasWarnedNonVLModel = false;\n\n /**\n * Screenshot scale factor derived from actual screenshot dimensions\n */\n private screenshotScale?: number;\n\n /**\n * Internal promise to deduplicate screenshot scale computation\n */\n private screenshotScalePromise?: Promise<number>;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n /**\n * Ensures VL model warning is shown once when needed\n */\n private ensureVLModelWarning() {\n if (\n !this.hasWarnedNonVLModel &&\n this.interface.interfaceType !== 'puppeteer' &&\n this.interface.interfaceType !== 'playwright' &&\n this.interface.interfaceType !== 'static' &&\n this.interface.interfaceType !== 'chrome-extension-proxy' &&\n this.interface.interfaceType !== 'page-over-chrome-extension-bridge'\n ) {\n this.modelConfigManager.throwErrorIfNonVLModel();\n this.hasWarnedNonVLModel = true;\n }\n }\n\n /**\n * Lazily compute the ratio between the physical screenshot width and the logical page width\n */\n private async getScreenshotScale(context: UIContext): Promise<number> {\n if (this.screenshotScale !== undefined) {\n return this.screenshotScale;\n }\n\n if (!this.screenshotScalePromise) {\n this.screenshotScalePromise = (async () => {\n const pageWidth = context.size?.width;\n assert(\n pageWidth && pageWidth > 0,\n `Invalid page width when computing screenshot scale: ${pageWidth}`,\n );\n\n const { width: screenshotWidth } = await imageInfoOfBase64(\n context.screenshotBase64,\n );\n\n assert(\n Number.isFinite(screenshotWidth) && screenshotWidth > 0,\n `Invalid screenshot width when computing screenshot scale: ${screenshotWidth}`,\n );\n\n const computedScale = screenshotWidth / pageWidth;\n assert(\n Number.isFinite(computedScale) && computedScale > 0,\n `Invalid computed screenshot scale: ${computedScale}`,\n );\n\n debug(\n `Computed screenshot scale ${computedScale} from screenshot width ${screenshotWidth} and page width ${pageWidth}`,\n );\n return computedScale;\n })();\n }\n\n try {\n this.screenshotScale = await this.screenshotScalePromise;\n return this.screenshotScale;\n } finally {\n this.screenshotScalePromise = undefined;\n }\n }\n\n constructor(interfaceInstance: InterfaceType, opts?: AgentOpt) {\n this.interface = interfaceInstance;\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 (opts?.modelConfig && typeof opts?.modelConfig !== 'function') {\n throw new Error(\n `opts.modelConfig must be one of function or undefined, but got ${typeof opts?.modelConfig}`,\n );\n }\n this.modelConfigManager = opts?.modelConfig\n ? new ModelConfigManager(opts.modelConfig)\n : globalModelConfigManager;\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n\n this.insight = new Insight(async (action: InsightAction) => {\n return this.getUIContext(action);\n });\n\n // Process cache configuration\n const cacheConfig = this.processCacheConfig(opts || {});\n if (cacheConfig) {\n this.taskCache = new TaskCache(\n cacheConfig.id,\n cacheConfig.enabled,\n undefined, // cacheFilePath\n {\n readOnly: cacheConfig.readOnly,\n writeOnly: cacheConfig.writeOnly,\n },\n );\n }\n\n this.taskExecutor = new TaskExecutor(this.interface, this.insight, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n replanningCycleLimit: this.opts.replanningCycleLimit,\n });\n this.dump = this.resetDump();\n this.reportFileName =\n opts?.reportFileName ||\n getReportFileName(opts?.testId || this.interface.interfaceType || 'web');\n }\n\n async getActionSpace(): Promise<DeviceAction[]> {\n return this.interface.actionSpace();\n }\n\n async getUIContext(action?: InsightAction): Promise<UIContext> {\n // Check VL model configuration when UI context is first needed\n this.ensureVLModelWarning();\n\n // If page context is frozen, return the frozen context for all actions\n if (this.frozenUIContext) {\n debug('Using frozen page context for action:', action);\n return this.frozenUIContext;\n }\n\n // Get original context\n let context: UIContext;\n if (this.interface.getContext) {\n debug('Using page.getContext for action:', action);\n context = await this.interface.getContext();\n } else {\n debug('Using commonContextParser for action:', action);\n context = await commonContextParser(this.interface, {\n uploadServerUrl: this.modelConfigManager.getUploadTestServerUrl(),\n });\n }\n\n const computedScreenshotScale = await this.getScreenshotScale(context);\n\n if (computedScreenshotScale !== 1) {\n const scaleForLog = Number.parseFloat(computedScreenshotScale.toFixed(4));\n debug(\n `Applying computed screenshot scale: ${scaleForLog} (resize to logical size)`,\n );\n const targetWidth = Math.round(context.size.width);\n const targetHeight = Math.round(context.size.height);\n debug(`Resizing screenshot to ${targetWidth}x${targetHeight}`);\n context.screenshotBase64 = await resizeImgBase64(\n context.screenshotBase64,\n { width: targetWidth, height: targetHeight },\n );\n } else {\n debug(`screenshot scale=${computedScreenshotScale}`);\n }\n\n return context;\n }\n\n async _snapshotContext(): Promise<UIContext> {\n return await this.getUIContext('locate');\n }\n\n async setAIActionContext(prompt: string) {\n if (this.opts.aiActionContext) {\n console.warn(\n 'aiActionContext is already set, and it is called again, will override the previous setting',\n );\n }\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 modelBriefs: [],\n };\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump) {\n // use trimContextByViewport to process execution\n const trimmedExecution = trimContextByViewport(execution);\n const currentDump = this.dump;\n currentDump.executions.push(trimmedExecution);\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 if (this.destroyed) {\n throw new Error(\n 'PageAgent has been destroyed. Cannot update report file.',\n );\n }\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 async afterTaskRunning(executor: Executor, doNotThrowError = false) {\n const executionDump = executor.dump();\n if (this.opts.aiActionContext) {\n executionDump.aiActionContext = this.opts.aiActionContext;\n }\n this.appendExecutionDump(executionDump);\n\n try {\n if (this.onDumpUpdate) {\n this.onDumpUpdate(this.dumpDataString());\n }\n } catch (error) {\n console.error('Error in onDumpUpdate', error);\n }\n\n this.writeOutActionDumps();\n\n if (executor.isInErrorState() && !doNotThrowError) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.errorMessage}\\n${errorTask?.errorStack}`, {\n cause: errorTask?.error,\n });\n }\n }\n\n async callActionInActionSpace<T = any>(\n type: string,\n opt?: T, // and all other action params\n ) {\n debug('callActionInActionSpace', type, ',', opt);\n\n const actionPlan: PlanningAction<T> = {\n type: type as any,\n param: (opt as any) || {},\n thought: '',\n };\n debug('actionPlan', actionPlan); // , ', in which the locateParam is', locateParam);\n\n const plans: PlanningAction[] = [actionPlan].filter(\n Boolean,\n ) as PlanningAction[];\n\n const title = taskTitleStr(\n type as any,\n locateParamStr((opt as any)?.locate || {}),\n );\n\n // assume all operation in action space is related to locating\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const { output, executor } = await this.taskExecutor.runPlans(\n title,\n plans,\n modelConfig,\n );\n await this.afterTaskRunning(executor);\n return output;\n }\n\n async aiTap(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for tap');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Tap', {\n locate: detailedLocateParam,\n });\n }\n\n async aiRightClick(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for right click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('RightClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiDoubleClick(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for double click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('DoubleClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiHover(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for hover');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Hover', {\n locate: detailedLocateParam,\n });\n }\n\n // New signature, always use locatePrompt as the first param\n async aiInput(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' },\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiInput(locatePrompt, opt) instead where opt contains the value\n */\n async aiInput(\n value: string,\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { autoDismissKeyboard?: boolean } & {\n mode?: 'replace' | 'clear' | 'append';\n }, // AndroidDeviceInputOpt &\n ): Promise<any>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' }) // AndroidDeviceInputOpt &\n | undefined,\n optOrUndefined?: LocateOption, // AndroidDeviceInputOpt &\n ) {\n let value: string;\n let locatePrompt: TUserPrompt;\n let opt:\n | (LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' }) // AndroidDeviceInputOpt &\n | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has value)\n if (\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null &&\n 'value' in locatePromptOrOpt\n ) {\n // New signature: aiInput(locatePrompt, opt)\n locatePrompt = locatePromptOrValue as TUserPrompt;\n const optWithValue = locatePromptOrOpt as LocateOption & {\n // AndroidDeviceInputOpt &\n value: string;\n autoDismissKeyboard?: boolean;\n };\n value = optWithValue.value;\n opt = optWithValue;\n } else {\n // Legacy signature: aiInput(value, locatePrompt, opt)\n value = locatePromptOrValue as string;\n locatePrompt = locatePromptOrOpt as TUserPrompt;\n opt = {\n ...optOrUndefined,\n value,\n };\n }\n\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\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Input', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { keyName: string },\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiKeyboardPress(locatePrompt, opt) instead where opt contains the keyName\n */\n async aiKeyboardPress(\n keyName: string,\n locatePrompt?: TUserPrompt,\n opt?: LocateOption,\n ): Promise<any>;\n\n // Implementation\n async aiKeyboardPress(\n locatePromptOrKeyName: TUserPrompt | string,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { keyName: string })\n | undefined,\n optOrUndefined?: LocateOption,\n ) {\n let keyName: string;\n let locatePrompt: TUserPrompt | undefined;\n let opt: (LocateOption & { keyName: string }) | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has keyName)\n if (\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null &&\n 'keyName' in locatePromptOrOpt\n ) {\n // New signature: aiKeyboardPress(locatePrompt, opt)\n locatePrompt = locatePromptOrKeyName as TUserPrompt;\n opt = locatePromptOrOpt as LocateOption & {\n keyName: string;\n };\n } else {\n // Legacy signature: aiKeyboardPress(keyName, locatePrompt, opt)\n keyName = locatePromptOrKeyName as string;\n locatePrompt = locatePromptOrOpt as TUserPrompt | undefined;\n opt = {\n ...(optOrUndefined || {}),\n keyName,\n };\n }\n\n assert(opt?.keyName, 'missing keyName for keyboard press');\n\n const detailedLocateParam = locatePrompt\n ? buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n\n return this.callActionInActionSpace('KeyboardPress', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n // New signature\n async aiScroll(\n locatePrompt: TUserPrompt | undefined,\n opt: LocateOption & ScrollParam,\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiScroll(locatePrompt, opt) instead where opt contains the scroll parameters\n */\n async aiScroll(\n scrollParam: ScrollParam,\n locatePrompt?: TUserPrompt,\n opt?: LocateOption,\n ): Promise<any>;\n\n // Implementation\n async aiScroll(\n locatePromptOrScrollParam: TUserPrompt | ScrollParam | undefined,\n locatePromptOrOpt: TUserPrompt | (LocateOption & ScrollParam) | undefined,\n optOrUndefined?: LocateOption,\n ) {\n let scrollParam: ScrollParam;\n let locatePrompt: TUserPrompt | undefined;\n let opt: LocateOption | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has scroll params)\n if (\n typeof locatePromptOrOpt === 'object' &&\n ('direction' in locatePromptOrOpt ||\n 'scrollType' in locatePromptOrOpt ||\n 'distance' in locatePromptOrOpt)\n ) {\n // New signature: aiScroll(locatePrompt, opt)\n locatePrompt = locatePromptOrScrollParam as TUserPrompt;\n opt = locatePromptOrOpt as LocateOption & ScrollParam;\n } else {\n // Legacy signature: aiScroll(scrollParam, locatePrompt, opt)\n scrollParam = locatePromptOrScrollParam as ScrollParam;\n locatePrompt = locatePromptOrOpt as TUserPrompt | undefined;\n opt = {\n ...(optOrUndefined || {}),\n ...(scrollParam || {}),\n };\n }\n\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n return this.callActionInActionSpace('Scroll', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiAction(\n taskPrompt: string,\n opt?: {\n cacheable?: boolean;\n },\n ) {\n const modelConfig = this.modelConfigManager.getModelConfig('planning');\n\n const cacheable = opt?.cacheable;\n // if vlm-ui-tars, plan cache is not used\n const isVlmUiTars = modelConfig.vlMode === '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 await this.afterTaskRunning(executor);\n\n debug('matched cache, will call .runYaml to run the action');\n const yaml = matchedCache.cacheContent?.yamlWorkflow;\n return this.runYaml(yaml);\n }\n\n const { output, executor } = await this.taskExecutor.action(\n taskPrompt,\n modelConfig,\n this.opts.aiActionContext,\n cacheable,\n );\n\n // update cache\n if (this.taskCache && output?.yamlFlow && cacheable !== false) {\n const yamlContent: MidsceneYamlScript = {\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 await this.afterTaskRunning(executor);\n return output;\n }\n\n async aiQuery<ReturnType = any>(\n demand: InsightExtractParam,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<ReturnType> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Query',\n demand,\n modelConfig,\n opt,\n );\n await this.afterTaskRunning(executor);\n return output as ReturnType;\n }\n\n async aiBoolean(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<boolean> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Boolean',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as boolean;\n }\n\n async aiNumber(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<number> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Number',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as number;\n }\n\n async aiString(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<string> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'String',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as string;\n }\n\n async aiAsk(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<string> {\n return this.aiString(prompt, opt);\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 // use same intent as aiLocate\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const text = await this.insight.describe(center, modelConfig, {\n deepThink,\n });\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 { center: verifyCenter, rect: verifyRect } = await this.aiLocate(\n prompt,\n locateOpt,\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: TUserPrompt, opt?: LocateOption) {\n const locateParam = buildDetailedLocateParam(prompt, opt);\n assert(locateParam, 'cannot get locate param for aiLocate');\n const locatePlan = locatePlanForLocate(locateParam);\n const plans = [locatePlan];\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(locateParam)),\n plans,\n modelConfig,\n );\n await this.afterTaskRunning(executor);\n\n const { element } = output;\n\n const dprValue = await (this.interface.size() as any).dpr;\n const dprEntry = dprValue\n ? {\n dpr: dprValue,\n }\n : {};\n return {\n rect: element?.rect,\n center: element?.center,\n ...dprEntry,\n } as Pick<LocateResultElement, 'rect' | 'center'> & {\n dpr?: number; // this field is deprecated\n };\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AgentAssertOpt & InsightExtractOption,\n ) {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const insightOpt: InsightExtractOption = {\n domIncluded: opt?.domIncluded ?? defaultInsightExtractOption.domIncluded,\n screenshotIncluded:\n opt?.screenshotIncluded ??\n defaultInsightExtractOption.screenshotIncluded,\n isWaitForAssert: opt?.isWaitForAssert,\n doNotThrowError: opt?.doNotThrowError,\n };\n\n const { output, executor, thought } = await this.taskExecutor.assert(\n assertion,\n modelConfig,\n insightOpt,\n );\n await this.afterTaskRunning(executor, true);\n\n const message = output\n ? undefined\n : `Assertion failed: ${msg || (typeof assertion === 'string' ? assertion : assertion.prompt)}\\nReason: ${\n thought || executor.latestErrorTask()?.error || '(no_reason)'\n }`;\n\n if (opt?.keepRawResponse) {\n return {\n pass: output,\n thought,\n message,\n };\n }\n\n if (!output) {\n throw new Error(message);\n }\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n const { executor } = await this.taskExecutor.waitFor(\n assertion,\n {\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n },\n modelConfig,\n );\n await this.afterTaskRunning(executor, true);\n\n if (executor.isInErrorState()) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}\\n${errorTask?.errorStack}`);\n }\n }\n\n async ai(taskPrompt: string, type = 'action') {\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);\n }\n\n if (type === 'rightClick') {\n return this.aiRightClick(taskPrompt);\n }\n\n if (type === 'doubleClick') {\n return this.aiDoubleClick(taskPrompt);\n }\n\n throw new Error(\n `Unknown type: ${type}, only support 'action', 'query', 'assert', 'tap', 'rightClick', 'doubleClick'`,\n );\n }\n\n async runYaml(yamlScriptContent: string): Promise<{\n result: Record<string, any>;\n }> {\n const script = parseYamlScript(yamlScriptContent, 'yaml');\n const player = new ScriptPlayer(script, async () => {\n return { agent: this, freeFn: [] };\n });\n await player.run();\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 };\n }\n\n async evaluateJavaScript(script: string) {\n assert(\n this.interface.evaluateJavaScript,\n 'evaluateJavaScript is not supported in current agent',\n );\n return this.interface.evaluateJavaScript(script);\n }\n\n async destroy() {\n await this.interface.destroy?.();\n this.resetDump(); // reset dump to release memory\n this.destroyed = true;\n }\n\n async logScreenshot(\n title?: string,\n opt?: {\n content: string;\n },\n ) {\n // 1. screenshot\n const base64 = await this.interface.screenshotBase64();\n const now = Date.now();\n // 2. build recorder\n const recorder: ExecutionRecorderItem[] = [\n {\n type: 'screenshot',\n ts: now,\n screenshot: base64,\n },\n ];\n // 3. build ExecutionTaskLog\n const task: ExecutionTaskLog = {\n type: 'Log',\n subType: 'Screenshot',\n status: 'finished',\n recorder,\n timing: {\n start: now,\n end: now,\n cost: 0,\n },\n param: {\n content: opt?.content || '',\n },\n executor: async () => {},\n };\n // 4. build ExecutionDump\n const executionDump: ExecutionDump = {\n sdkVersion: '',\n logTime: now,\n name: `Log - ${title || 'untitled'}`,\n description: opt?.content || '',\n tasks: [task],\n };\n if (this.opts.aiActionContext) {\n executionDump.aiActionContext = this.opts.aiActionContext;\n }\n // 5. append to execution dump\n this.appendExecutionDump(executionDump);\n\n try {\n this.onDumpUpdate?.(this.dumpDataString());\n } catch (error) {\n console.error('Failed to update dump', error);\n }\n\n this.writeOutActionDumps();\n }\n\n _unstableLogContent() {\n const { groupName, groupDescription, executions } = this.dump;\n const newExecutions = Array.isArray(executions)\n ? executions.map((execution: any) => {\n const { tasks, ...restExecution } = execution;\n let newTasks = tasks;\n if (Array.isArray(tasks)) {\n newTasks = tasks.map((task: any) => {\n // only remove uiContext and log from task\n const { uiContext, log, ...restTask } = task;\n return restTask;\n });\n }\n return { ...restExecution, ...(newTasks ? { tasks: newTasks } : {}) };\n })\n : [];\n return {\n groupName,\n groupDescription,\n executions: newExecutions,\n };\n }\n\n /**\n * Freezes the current page context to be reused in subsequent AI operations\n * This avoids recalculating page context for each operation\n */\n async freezePageContext(): Promise<void> {\n debug('Freezing page context');\n const context = await this._snapshotContext();\n // Mark the context as frozen\n context._isFrozen = true;\n this.frozenUIContext = context;\n debug('Page context frozen successfully');\n }\n\n /**\n * Unfreezes the page context, allowing AI operations to calculate context dynamically\n */\n async unfreezePageContext(): Promise<void> {\n debug('Unfreezing page context');\n this.frozenUIContext = undefined;\n debug('Page context unfrozen successfully');\n }\n\n /**\n * Process cache configuration and return normalized cache settings\n */\n private processCacheConfig(opts: AgentOpt): {\n id: string;\n enabled: boolean;\n readOnly: boolean;\n writeOnly: boolean;\n } | null {\n // 1. New cache object configuration (highest priority)\n if (opts.cache !== undefined) {\n if (opts.cache === false) {\n return null; // Completely disable cache\n }\n\n if (opts.cache === true) {\n throw new Error(\n 'cache: true requires an explicit cache ID. Please provide:\\n' +\n 'Example: cache: { id: \"my-cache-id\" }',\n );\n }\n\n // cache is object configuration\n if (typeof opts.cache === 'object') {\n const config = opts.cache;\n if (!config.id) {\n throw new Error(\n 'cache configuration requires an explicit id. Please provide:\\n' +\n 'Example: cache: { id: \"my-cache-id\" }',\n );\n }\n const id = config.id;\n const rawStrategy = config.strategy as unknown;\n let strategyValue: string;\n\n if (rawStrategy === undefined) {\n strategyValue = 'read-write';\n } else if (typeof rawStrategy === 'string') {\n strategyValue = rawStrategy;\n } else {\n throw new Error(\n `cache.strategy must be a string when provided, but received type ${typeof rawStrategy}`,\n );\n }\n\n if (!isValidCacheStrategy(strategyValue)) {\n throw new Error(\n `cache.strategy must be one of ${CACHE_STRATEGY_VALUES}, but received \"${strategyValue}\"`,\n );\n }\n\n const isReadOnly = strategyValue === 'read-only';\n const isWriteOnly = strategyValue === 'write-only';\n\n return {\n id,\n enabled: !isWriteOnly,\n readOnly: isReadOnly,\n writeOnly: isWriteOnly,\n };\n }\n }\n\n // 2. Backward compatibility: support old cacheId (requires environment variable)\n if (opts.cacheId) {\n const envEnabled =\n globalConfigManager.getEnvConfigInBoolean(MIDSCENE_CACHE);\n if (envEnabled) {\n return {\n id: opts.cacheId,\n enabled: true,\n readOnly: false,\n writeOnly: false,\n };\n }\n }\n\n // 3. No cache configuration\n return null;\n }\n\n /**\n * Manually flush cache to file\n * Only supported in read-only mode where writes are deferred by default\n */\n async flushCache(): Promise<void> {\n if (!this.taskCache) {\n throw new Error('Cache is not configured');\n }\n\n if (!this.taskCache.readOnlyMode) {\n throw new Error('flushCache() can only be called in read-only mode');\n }\n\n this.taskCache.flushCacheToFile();\n }\n}\n\nexport const createAgent = (\n interfaceInstance: AbstractInterface,\n opts?: AgentOpt,\n) => {\n return new Agent(interfaceInstance, opts);\n};\n"],"names":["debug","getDebug","distanceOfTwoPoints","p1","p2","x1","y1","x2","y2","Math","includedInRect","point","rect","x","y","left","top","width","height","defaultInsightExtractOption","CACHE_STRATEGIES","isValidCacheStrategy","strategy","value","CACHE_STRATEGY_VALUES","Agent","context","undefined","_context_size","pageWidth","assert","screenshotWidth","imageInfoOfBase64","Number","computedScale","action","commonContextParser","computedScreenshotScale","scaleForLog","targetWidth","targetHeight","resizeImgBase64","prompt","console","execution","trimmedExecution","trimContextByViewport","currentDump","stringifyDumpData","reportHTMLContent","Error","generateReport","autoPrintReportMsg","writeLogFile","groupedActionDumpFileExt","printReportMsg","task","param","paramStr","tip","typeStr","executor","doNotThrowError","executionDump","error","errorTask","type","opt","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","modelConfig","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","optWithValue","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","taskPrompt","_this_taskCache","_this_taskCache1","cacheable","isVlmUiTars","matchedCache","_matchedCache_cacheContent","_matchedCache_cacheContent1","yaml","yamlContent","yamlFlowStr","demand","textPrompt","multimodalPrompt","parsePrompt","center","verifyPrompt","retryLimit","success","retryCount","resultPrompt","deepThink","verifyResult","text","locateOpt","expectCenter","verifyLocateOption","verifyCenter","verifyRect","distance","included","pass","locateParam","locatePlan","locatePlanForLocate","element","dprValue","dprEntry","assertion","msg","_executor_latestErrorTask","insightOpt","thought","message","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","_task_error","_this_interface","base64","now","Date","recorder","_this","groupName","groupDescription","executions","newExecutions","Array","tasks","restExecution","newTasks","uiContext","log","restTask","opts","config","id","rawStrategy","strategyValue","isReadOnly","isWriteOnly","envEnabled","globalConfigManager","MIDSCENE_CACHE","interfaceInstance","Object","ModelConfigManager","globalModelConfigManager","Insight","cacheConfig","TaskCache","TaskExecutor","getReportFileName","createAgent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAMA,QAAQC,SAAS;AAEvB,MAAMC,sBAAsB,CAACC,IAAsBC;IACjD,MAAM,CAACC,IAAIC,GAAG,GAAGH;IACjB,MAAM,CAACI,IAAIC,GAAG,GAAGJ;IACjB,OAAOK,KAAK,KAAK,CAACA,KAAK,IAAI,CAAEJ,AAAAA,CAAAA,KAAKE,EAAC,KAAM,IAAKD,AAAAA,CAAAA,KAAKE,EAAC,KAAM;AAC5D;AAEA,MAAME,iBAAiB,CAACC,OAAyBC;IAC/C,MAAM,CAACC,GAAGC,EAAE,GAAGH;IACf,MAAM,EAAEI,IAAI,EAAEC,GAAG,EAAEC,KAAK,EAAEC,MAAM,EAAE,GAAGN;IACrC,OAAOC,KAAKE,QAAQF,KAAKE,OAAOE,SAASH,KAAKE,OAAOF,KAAKE,MAAME;AAClE;AAEA,MAAMC,8BAAoD;IACxD,aAAa;IACb,oBAAoB;AACtB;AAIA,MAAMC,mBAA6C;IACjD;IACA;IACA;CACD;AAED,MAAMC,uBAAuB,CAACC,WAC5BF,iBAAiB,IAAI,CAAC,CAACG,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gentAssertOpt,\n type AgentDescribeElementAtPointResult,\n type AgentOpt,\n type AgentWaitForOpt,\n type CacheConfig,\n type DeviceAction,\n type ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskLog,\n type Executor,\n type GroupedActionDump,\n Insight,\n type InsightAction,\n type InsightExtractOption,\n type InsightExtractParam,\n type LocateOption,\n type LocateResultElement,\n type LocateValidatorResult,\n type LocatorValidatorOption,\n type MidsceneYamlScript,\n type OnTaskStartTip,\n type PlanningAction,\n type Rect,\n type ScrollParam,\n type TUserPrompt,\n type UIContext,\n} from '../index';\nexport type TestStatus =\n | 'passed'\n | 'failed'\n | 'timedOut'\n | 'skipped'\n | 'interrupted';\nimport yaml from 'js-yaml';\n\nimport {\n groupedActionDumpFileExt,\n processCacheConfig,\n reportHTMLContent,\n stringifyDumpData,\n writeLogFile,\n} from '@/utils';\nimport {\n ScriptPlayer,\n buildDetailedLocateParam,\n parseYamlScript,\n} from '../yaml/index';\n\nimport type { AbstractInterface } from '@/device';\nimport {\n ModelConfigManager,\n globalModelConfigManager,\n} from '@midscene/shared/env';\nimport { imageInfoOfBase64, resizeImgBase64 } from '@midscene/shared/img';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\n// import type { AndroidDeviceInputOpt } from '../device';\nimport { TaskCache } from './task-cache';\nimport { TaskExecutor, locatePlanForLocate } from './tasks';\nimport { locateParamStr, paramStr, taskTitleStr, typeStr } from './ui-utils';\nimport {\n commonContextParser,\n getReportFileName,\n parsePrompt,\n printReportMsg,\n} from './utils';\nimport { trimContextByViewport } from './utils';\n\nconst debug = getDebug('agent');\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\nconst defaultInsightExtractOption: InsightExtractOption = {\n domIncluded: false,\n screenshotIncluded: true,\n};\n\ntype CacheStrategy = NonNullable<CacheConfig['strategy']>;\n\nconst CACHE_STRATEGIES: readonly CacheStrategy[] = [\n 'read-only',\n 'read-write',\n 'write-only',\n];\n\nconst isValidCacheStrategy = (strategy: string): strategy is CacheStrategy =>\n CACHE_STRATEGIES.some((value) => value === strategy);\n\nconst CACHE_STRATEGY_VALUES = CACHE_STRATEGIES.map(\n (value) => `\"${value}\"`,\n).join(', ');\n\nexport class Agent<\n InterfaceType extends AbstractInterface = AbstractInterface,\n> {\n interface: InterfaceType;\n\n insight: Insight;\n\n dump: GroupedActionDump;\n\n reportFile?: string | null;\n\n reportFileName?: string;\n\n taskExecutor: TaskExecutor;\n\n opts: AgentOpt;\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 onDumpUpdate?: (dump: string) => void;\n\n destroyed = false;\n\n modelConfigManager: ModelConfigManager;\n\n /**\n * Frozen page context for consistent AI operations\n */\n private frozenUIContext?: UIContext;\n\n /**\n * Flag to track if VL model warning has been shown\n */\n private hasWarnedNonVLModel = false;\n\n /**\n * Screenshot scale factor derived from actual screenshot dimensions\n */\n private screenshotScale?: number;\n\n /**\n * Internal promise to deduplicate screenshot scale computation\n */\n private screenshotScalePromise?: Promise<number>;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n /**\n * Ensures VL model warning is shown once when needed\n */\n private ensureVLModelWarning() {\n if (\n !this.hasWarnedNonVLModel &&\n this.interface.interfaceType !== 'puppeteer' &&\n this.interface.interfaceType !== 'playwright' &&\n this.interface.interfaceType !== 'static' &&\n this.interface.interfaceType !== 'chrome-extension-proxy' &&\n this.interface.interfaceType !== 'page-over-chrome-extension-bridge'\n ) {\n this.modelConfigManager.throwErrorIfNonVLModel();\n this.hasWarnedNonVLModel = true;\n }\n }\n\n /**\n * Lazily compute the ratio between the physical screenshot width and the logical page width\n */\n private async getScreenshotScale(context: UIContext): Promise<number> {\n if (this.screenshotScale !== undefined) {\n return this.screenshotScale;\n }\n\n if (!this.screenshotScalePromise) {\n this.screenshotScalePromise = (async () => {\n const pageWidth = context.size?.width;\n assert(\n pageWidth && pageWidth > 0,\n `Invalid page width when computing screenshot scale: ${pageWidth}`,\n );\n\n const { width: screenshotWidth } = await imageInfoOfBase64(\n context.screenshotBase64,\n );\n\n assert(\n Number.isFinite(screenshotWidth) && screenshotWidth > 0,\n `Invalid screenshot width when computing screenshot scale: ${screenshotWidth}`,\n );\n\n const computedScale = screenshotWidth / pageWidth;\n assert(\n Number.isFinite(computedScale) && computedScale > 0,\n `Invalid computed screenshot scale: ${computedScale}`,\n );\n\n debug(\n `Computed screenshot scale ${computedScale} from screenshot width ${screenshotWidth} and page width ${pageWidth}`,\n );\n return computedScale;\n })();\n }\n\n try {\n this.screenshotScale = await this.screenshotScalePromise;\n return this.screenshotScale;\n } finally {\n this.screenshotScalePromise = undefined;\n }\n }\n\n constructor(interfaceInstance: InterfaceType, opts?: AgentOpt) {\n this.interface = interfaceInstance;\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 (opts?.modelConfig && typeof opts?.modelConfig !== 'function') {\n throw new Error(\n `opts.modelConfig must be one of function or undefined, but got ${typeof opts?.modelConfig}`,\n );\n }\n this.modelConfigManager = opts?.modelConfig\n ? new ModelConfigManager(opts.modelConfig)\n : globalModelConfigManager;\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n\n this.insight = new Insight(async (action: InsightAction) => {\n return this.getUIContext(action);\n });\n\n // Process cache configuration\n const cacheConfigObj = this.processCacheConfig(opts || {});\n if (cacheConfigObj) {\n this.taskCache = new TaskCache(\n cacheConfigObj.id,\n cacheConfigObj.enabled,\n undefined, // cacheFilePath\n {\n readOnly: cacheConfigObj.readOnly,\n writeOnly: cacheConfigObj.writeOnly,\n },\n );\n }\n\n this.taskExecutor = new TaskExecutor(this.interface, this.insight, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n replanningCycleLimit: this.opts.replanningCycleLimit,\n });\n this.dump = this.resetDump();\n this.reportFileName =\n opts?.reportFileName ||\n getReportFileName(opts?.testId || this.interface.interfaceType || 'web');\n }\n\n async getActionSpace(): Promise<DeviceAction[]> {\n return this.interface.actionSpace();\n }\n\n async getUIContext(action?: InsightAction): Promise<UIContext> {\n // Check VL model configuration when UI context is first needed\n this.ensureVLModelWarning();\n\n // If page context is frozen, return the frozen context for all actions\n if (this.frozenUIContext) {\n debug('Using frozen page context for action:', action);\n return this.frozenUIContext;\n }\n\n // Get original context\n let context: UIContext;\n if (this.interface.getContext) {\n debug('Using page.getContext for action:', action);\n context = await this.interface.getContext();\n } else {\n debug('Using commonContextParser for action:', action);\n context = await commonContextParser(this.interface, {\n uploadServerUrl: this.modelConfigManager.getUploadTestServerUrl(),\n });\n }\n\n const computedScreenshotScale = await this.getScreenshotScale(context);\n\n if (computedScreenshotScale !== 1) {\n const scaleForLog = Number.parseFloat(computedScreenshotScale.toFixed(4));\n debug(\n `Applying computed screenshot scale: ${scaleForLog} (resize to logical size)`,\n );\n const targetWidth = Math.round(context.size.width);\n const targetHeight = Math.round(context.size.height);\n debug(`Resizing screenshot to ${targetWidth}x${targetHeight}`);\n context.screenshotBase64 = await resizeImgBase64(\n context.screenshotBase64,\n { width: targetWidth, height: targetHeight },\n );\n } else {\n debug(`screenshot scale=${computedScreenshotScale}`);\n }\n\n return context;\n }\n\n async _snapshotContext(): Promise<UIContext> {\n return await this.getUIContext('locate');\n }\n\n async setAIActionContext(prompt: string) {\n if (this.opts.aiActionContext) {\n console.warn(\n 'aiActionContext is already set, and it is called again, will override the previous setting',\n );\n }\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 modelBriefs: [],\n };\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump) {\n // use trimContextByViewport to process execution\n const trimmedExecution = trimContextByViewport(execution);\n const currentDump = this.dump;\n currentDump.executions.push(trimmedExecution);\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 if (this.destroyed) {\n throw new Error(\n 'PageAgent has been destroyed. Cannot update report file.',\n );\n }\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 async afterTaskRunning(executor: Executor, doNotThrowError = false) {\n const executionDump = executor.dump();\n if (this.opts.aiActionContext) {\n executionDump.aiActionContext = this.opts.aiActionContext;\n }\n this.appendExecutionDump(executionDump);\n\n try {\n if (this.onDumpUpdate) {\n this.onDumpUpdate(this.dumpDataString());\n }\n } catch (error) {\n console.error('Error in onDumpUpdate', error);\n }\n\n this.writeOutActionDumps();\n\n if (executor.isInErrorState() && !doNotThrowError) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.errorMessage}\\n${errorTask?.errorStack}`, {\n cause: errorTask?.error,\n });\n }\n }\n\n async callActionInActionSpace<T = any>(\n type: string,\n opt?: T, // and all other action params\n ) {\n debug('callActionInActionSpace', type, ',', opt);\n\n const actionPlan: PlanningAction<T> = {\n type: type as any,\n param: (opt as any) || {},\n thought: '',\n };\n debug('actionPlan', actionPlan); // , ', in which the locateParam is', locateParam);\n\n const plans: PlanningAction[] = [actionPlan].filter(\n Boolean,\n ) as PlanningAction[];\n\n const title = taskTitleStr(\n type as any,\n locateParamStr((opt as any)?.locate || {}),\n );\n\n // assume all operation in action space is related to locating\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const { output, executor } = await this.taskExecutor.runPlans(\n title,\n plans,\n modelConfig,\n );\n await this.afterTaskRunning(executor);\n return output;\n }\n\n async aiTap(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for tap');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Tap', {\n locate: detailedLocateParam,\n });\n }\n\n async aiRightClick(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for right click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('RightClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiDoubleClick(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for double click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('DoubleClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiHover(locatePrompt: TUserPrompt, opt?: LocateOption) {\n assert(locatePrompt, 'missing locate prompt for hover');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Hover', {\n locate: detailedLocateParam,\n });\n }\n\n // New signature, always use locatePrompt as the first param\n async aiInput(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' },\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiInput(locatePrompt, opt) instead where opt contains the value\n */\n async aiInput(\n value: string,\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { autoDismissKeyboard?: boolean } & {\n mode?: 'replace' | 'clear' | 'append';\n }, // AndroidDeviceInputOpt &\n ): Promise<any>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' }) // AndroidDeviceInputOpt &\n | undefined,\n optOrUndefined?: LocateOption, // AndroidDeviceInputOpt &\n ) {\n let value: string;\n let locatePrompt: TUserPrompt;\n let opt:\n | (LocateOption & { value: string } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'append' }) // AndroidDeviceInputOpt &\n | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has value)\n if (\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null &&\n 'value' in locatePromptOrOpt\n ) {\n // New signature: aiInput(locatePrompt, opt)\n locatePrompt = locatePromptOrValue as TUserPrompt;\n const optWithValue = locatePromptOrOpt as LocateOption & {\n // AndroidDeviceInputOpt &\n value: string;\n autoDismissKeyboard?: boolean;\n };\n value = optWithValue.value;\n opt = optWithValue;\n } else {\n // Legacy signature: aiInput(value, locatePrompt, opt)\n value = locatePromptOrValue as string;\n locatePrompt = locatePromptOrOpt as TUserPrompt;\n opt = {\n ...optOrUndefined,\n value,\n };\n }\n\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\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n return this.callActionInActionSpace('Input', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { keyName: string },\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiKeyboardPress(locatePrompt, opt) instead where opt contains the keyName\n */\n async aiKeyboardPress(\n keyName: string,\n locatePrompt?: TUserPrompt,\n opt?: LocateOption,\n ): Promise<any>;\n\n // Implementation\n async aiKeyboardPress(\n locatePromptOrKeyName: TUserPrompt | string,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { keyName: string })\n | undefined,\n optOrUndefined?: LocateOption,\n ) {\n let keyName: string;\n let locatePrompt: TUserPrompt | undefined;\n let opt: (LocateOption & { keyName: string }) | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has keyName)\n if (\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null &&\n 'keyName' in locatePromptOrOpt\n ) {\n // New signature: aiKeyboardPress(locatePrompt, opt)\n locatePrompt = locatePromptOrKeyName as TUserPrompt;\n opt = locatePromptOrOpt as LocateOption & {\n keyName: string;\n };\n } else {\n // Legacy signature: aiKeyboardPress(keyName, locatePrompt, opt)\n keyName = locatePromptOrKeyName as string;\n locatePrompt = locatePromptOrOpt as TUserPrompt | undefined;\n opt = {\n ...(optOrUndefined || {}),\n keyName,\n };\n }\n\n assert(opt?.keyName, 'missing keyName for keyboard press');\n\n const detailedLocateParam = locatePrompt\n ? buildDetailedLocateParam(locatePrompt, opt)\n : undefined;\n\n return this.callActionInActionSpace('KeyboardPress', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n // New signature\n async aiScroll(\n locatePrompt: TUserPrompt | undefined,\n opt: LocateOption & ScrollParam,\n ): Promise<any>;\n\n // Legacy signature - deprecated\n /**\n * @deprecated Use aiScroll(locatePrompt, opt) instead where opt contains the scroll parameters\n */\n async aiScroll(\n scrollParam: ScrollParam,\n locatePrompt?: TUserPrompt,\n opt?: LocateOption,\n ): Promise<any>;\n\n // Implementation\n async aiScroll(\n locatePromptOrScrollParam: TUserPrompt | ScrollParam | undefined,\n locatePromptOrOpt: TUserPrompt | (LocateOption & ScrollParam) | undefined,\n optOrUndefined?: LocateOption,\n ) {\n let scrollParam: ScrollParam;\n let locatePrompt: TUserPrompt | undefined;\n let opt: LocateOption | undefined;\n\n // Check if using new signature (first param is locatePrompt, second has scroll params)\n if (\n typeof locatePromptOrOpt === 'object' &&\n ('direction' in locatePromptOrOpt ||\n 'scrollType' in locatePromptOrOpt ||\n 'distance' in locatePromptOrOpt)\n ) {\n // New signature: aiScroll(locatePrompt, opt)\n locatePrompt = locatePromptOrScrollParam as TUserPrompt;\n opt = locatePromptOrOpt as LocateOption & ScrollParam;\n } else {\n // Legacy signature: aiScroll(scrollParam, locatePrompt, opt)\n scrollParam = locatePromptOrScrollParam as ScrollParam;\n locatePrompt = locatePromptOrOpt as TUserPrompt | undefined;\n opt = {\n ...(optOrUndefined || {}),\n ...(scrollParam || {}),\n };\n }\n\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n return this.callActionInActionSpace('Scroll', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiAction(\n taskPrompt: string,\n opt?: {\n cacheable?: boolean;\n },\n ) {\n const modelConfig = this.modelConfigManager.getModelConfig('planning');\n\n const cacheable = opt?.cacheable;\n // if vlm-ui-tars, plan cache is not used\n const isVlmUiTars = modelConfig.vlMode === '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 await this.afterTaskRunning(executor);\n\n debug('matched cache, will call .runYaml to run the action');\n const yaml = matchedCache.cacheContent?.yamlWorkflow;\n return this.runYaml(yaml);\n }\n\n const { output, executor } = await this.taskExecutor.action(\n taskPrompt,\n modelConfig,\n this.opts.aiActionContext,\n cacheable,\n );\n\n // update cache\n if (this.taskCache && output?.yamlFlow && cacheable !== false) {\n const yamlContent: MidsceneYamlScript = {\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 await this.afterTaskRunning(executor);\n return output;\n }\n\n async aiQuery<ReturnType = any>(\n demand: InsightExtractParam,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<ReturnType> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Query',\n demand,\n modelConfig,\n opt,\n );\n await this.afterTaskRunning(executor);\n return output as ReturnType;\n }\n\n async aiBoolean(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<boolean> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Boolean',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as boolean;\n }\n\n async aiNumber(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<number> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'Number',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as number;\n }\n\n async aiString(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<string> {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output, executor } =\n await this.taskExecutor.createTypeQueryExecution(\n 'String',\n textPrompt,\n modelConfig,\n opt,\n multimodalPrompt,\n );\n await this.afterTaskRunning(executor);\n return output as string;\n }\n\n async aiAsk(\n prompt: TUserPrompt,\n opt: InsightExtractOption = defaultInsightExtractOption,\n ): Promise<string> {\n return this.aiString(prompt, opt);\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 // use same intent as aiLocate\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const text = await this.insight.describe(center, modelConfig, {\n deepThink,\n });\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 { center: verifyCenter, rect: verifyRect } = await this.aiLocate(\n prompt,\n locateOpt,\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: TUserPrompt, opt?: LocateOption) {\n const locateParam = buildDetailedLocateParam(prompt, opt);\n assert(locateParam, 'cannot get locate param for aiLocate');\n const locatePlan = locatePlanForLocate(locateParam);\n const plans = [locatePlan];\n const modelConfig = this.modelConfigManager.getModelConfig('grounding');\n\n const { executor, output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(locateParam)),\n plans,\n modelConfig,\n );\n await this.afterTaskRunning(executor);\n\n const { element } = output;\n\n const dprValue = await (this.interface.size() as any).dpr;\n const dprEntry = dprValue\n ? {\n dpr: dprValue,\n }\n : {};\n return {\n rect: element?.rect,\n center: element?.center,\n ...dprEntry,\n } as Pick<LocateResultElement, 'rect' | 'center'> & {\n dpr?: number; // this field is deprecated\n };\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AgentAssertOpt & InsightExtractOption,\n ) {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n\n const insightOpt: InsightExtractOption = {\n domIncluded: opt?.domIncluded ?? defaultInsightExtractOption.domIncluded,\n screenshotIncluded:\n opt?.screenshotIncluded ??\n defaultInsightExtractOption.screenshotIncluded,\n isWaitForAssert: opt?.isWaitForAssert,\n doNotThrowError: opt?.doNotThrowError,\n };\n\n const { output, executor, thought } = await this.taskExecutor.assert(\n assertion,\n modelConfig,\n insightOpt,\n );\n await this.afterTaskRunning(executor, true);\n\n const message = output\n ? undefined\n : `Assertion failed: ${msg || (typeof assertion === 'string' ? assertion : assertion.prompt)}\\nReason: ${\n thought || executor.latestErrorTask()?.error || '(no_reason)'\n }`;\n\n if (opt?.keepRawResponse) {\n return {\n pass: output,\n thought,\n message,\n };\n }\n\n if (!output) {\n throw new Error(message);\n }\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelConfig = this.modelConfigManager.getModelConfig('VQA');\n const { executor } = await this.taskExecutor.waitFor(\n assertion,\n {\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n },\n modelConfig,\n );\n await this.afterTaskRunning(executor, true);\n\n if (executor.isInErrorState()) {\n const errorTask = executor.latestErrorTask();\n throw new Error(`${errorTask?.error}\\n${errorTask?.errorStack}`);\n }\n }\n\n async ai(taskPrompt: string, type = 'action') {\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);\n }\n\n if (type === 'rightClick') {\n return this.aiRightClick(taskPrompt);\n }\n\n if (type === 'doubleClick') {\n return this.aiDoubleClick(taskPrompt);\n }\n\n throw new Error(\n `Unknown type: ${type}, only support 'action', 'query', 'assert', 'tap', 'rightClick', 'doubleClick'`,\n );\n }\n\n async runYaml(yamlScriptContent: string): Promise<{\n result: Record<string, any>;\n }> {\n const script = parseYamlScript(yamlScriptContent, 'yaml');\n const player = new ScriptPlayer(script, async () => {\n return { agent: this, freeFn: [] };\n });\n await player.run();\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 };\n }\n\n async evaluateJavaScript(script: string) {\n assert(\n this.interface.evaluateJavaScript,\n 'evaluateJavaScript is not supported in current agent',\n );\n return this.interface.evaluateJavaScript(script);\n }\n\n async destroy() {\n // Early return if already destroyed\n if (this.destroyed) {\n return;\n }\n\n await this.interface.destroy?.();\n this.resetDump(); // reset dump to release memory\n this.destroyed = true;\n }\n\n async logScreenshot(\n title?: string,\n opt?: {\n content: string;\n },\n ) {\n // 1. screenshot\n const base64 = await this.interface.screenshotBase64();\n const now = Date.now();\n // 2. build recorder\n const recorder: ExecutionRecorderItem[] = [\n {\n type: 'screenshot',\n ts: now,\n screenshot: base64,\n },\n ];\n // 3. build ExecutionTaskLog\n const task: ExecutionTaskLog = {\n type: 'Log',\n subType: 'Screenshot',\n status: 'finished',\n recorder,\n timing: {\n start: now,\n end: now,\n cost: 0,\n },\n param: {\n content: opt?.content || '',\n },\n executor: async () => {},\n };\n // 4. build ExecutionDump\n const executionDump: ExecutionDump = {\n sdkVersion: '',\n logTime: now,\n name: `Log - ${title || 'untitled'}`,\n description: opt?.content || '',\n tasks: [task],\n };\n if (this.opts.aiActionContext) {\n executionDump.aiActionContext = this.opts.aiActionContext;\n }\n // 5. append to execution dump\n this.appendExecutionDump(executionDump);\n\n try {\n this.onDumpUpdate?.(this.dumpDataString());\n } catch (error) {\n console.error('Failed to update dump', error);\n }\n\n this.writeOutActionDumps();\n }\n\n _unstableLogContent() {\n const { groupName, groupDescription, executions } = this.dump;\n const newExecutions = Array.isArray(executions)\n ? executions.map((execution: any) => {\n const { tasks, ...restExecution } = execution;\n let newTasks = tasks;\n if (Array.isArray(tasks)) {\n newTasks = tasks.map((task: any) => {\n // only remove uiContext and log from task\n const { uiContext, log, ...restTask } = task;\n return restTask;\n });\n }\n return { ...restExecution, ...(newTasks ? { tasks: newTasks } : {}) };\n })\n : [];\n return {\n groupName,\n groupDescription,\n executions: newExecutions,\n };\n }\n\n /**\n * Freezes the current page context to be reused in subsequent AI operations\n * This avoids recalculating page context for each operation\n */\n async freezePageContext(): Promise<void> {\n debug('Freezing page context');\n const context = await this._snapshotContext();\n // Mark the context as frozen\n context._isFrozen = true;\n this.frozenUIContext = context;\n debug('Page context frozen successfully');\n }\n\n /**\n * Unfreezes the page context, allowing AI operations to calculate context dynamically\n */\n async unfreezePageContext(): Promise<void> {\n debug('Unfreezing page context');\n this.frozenUIContext = undefined;\n debug('Page context unfrozen successfully');\n }\n\n /**\n * Process cache configuration and return normalized cache settings\n */\n private processCacheConfig(opts: AgentOpt): {\n id: string;\n enabled: boolean;\n readOnly: boolean;\n writeOnly: boolean;\n } | null {\n // Validate original cache config before processing\n // Agent requires explicit IDs - don't allow auto-generation\n if (opts.cache === true) {\n throw new Error(\n 'cache: true requires an explicit cache ID. Please provide:\\n' +\n 'Example: cache: { id: \"my-cache-id\" }',\n );\n }\n\n // Check if cache config object is missing ID\n if (\n opts.cache &&\n typeof opts.cache === 'object' &&\n opts.cache !== null &&\n !opts.cache.id\n ) {\n throw new Error(\n 'cache configuration requires an explicit id.\\n' +\n 'Example: cache: { id: \"my-cache-id\" }',\n );\n }\n\n // Use the unified utils function to process cache configuration\n const cacheConfig = processCacheConfig(\n opts.cache,\n opts.testId || 'default',\n opts.cacheId,\n );\n\n if (!cacheConfig) {\n return null;\n }\n\n // Handle cache configuration object\n if (typeof cacheConfig === 'object' && cacheConfig !== null) {\n const id = cacheConfig.id;\n const rawStrategy = cacheConfig.strategy as unknown;\n let strategyValue: string;\n\n if (rawStrategy === undefined) {\n strategyValue = 'read-write';\n } else if (typeof rawStrategy === 'string') {\n strategyValue = rawStrategy;\n } else {\n throw new Error(\n `cache.strategy must be a string when provided, but received type ${typeof rawStrategy}`,\n );\n }\n\n if (!isValidCacheStrategy(strategyValue)) {\n throw new Error(\n `cache.strategy must be one of ${CACHE_STRATEGY_VALUES}, but received \"${strategyValue}\"`,\n );\n }\n\n const isReadOnly = strategyValue === 'read-only';\n const isWriteOnly = strategyValue === 'write-only';\n\n return {\n id,\n enabled: !isWriteOnly,\n readOnly: isReadOnly,\n writeOnly: isWriteOnly,\n };\n }\n\n return null;\n }\n\n /**\n * Manually flush cache to file\n * @param options - Optional configuration\n * @param options.cleanUnused - If true, removes unused cache records before flushing\n */\n async flushCache(options?: { cleanUnused?: boolean }): Promise<void> {\n if (!this.taskCache) {\n throw new Error('Cache is not configured');\n }\n\n this.taskCache.flushCacheToFile(options);\n }\n}\n\nexport const createAgent = (\n interfaceInstance: AbstractInterface,\n opts?: AgentOpt,\n) => {\n return new Agent(interfaceInstance, opts);\n};\n"],"names":["debug","getDebug","distanceOfTwoPoints","p1","p2","x1","y1","x2","y2","Math","includedInRect","point","rect","x","y","left","top","width","height","defaultInsightExtractOption","CACHE_STRATEGIES","isValidCacheStrategy","strategy","value","CACHE_STRATEGY_VALUES","Agent","context","undefined","_context_size","pageWidth","assert","screenshotWidth","imageInfoOfBase64","Number","computedScale","action","commonContextParser","computedScreenshotScale","scaleForLog","targetWidth","targetHeight","resizeImgBase64","prompt","console","execution","trimmedExecution","trimContextByViewport","currentDump","stringifyDumpData","reportHTMLContent","Error","generateReport","autoPrintReportMsg","writeLogFile","groupedActionDumpFileExt","printReportMsg","task","param","paramStr","tip","typeStr","executor","doNotThrowError","executionDump","error","errorTask","type","opt","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","modelConfig","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","optWithValue","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","taskPrompt","_this_taskCache","_this_taskCache1","cacheable","isVlmUiTars","matchedCache","_matchedCache_cacheContent","_matchedCache_cacheContent1","yaml","yamlContent","yamlFlowStr","demand","textPrompt","multimodalPrompt","parsePrompt","center","verifyPrompt","retryLimit","success","retryCount","resultPrompt","deepThink","verifyResult","text","locateOpt","expectCenter","verifyLocateOption","verifyCenter","verifyRect","distance","included","pass","locateParam","locatePlan","locatePlanForLocate","element","dprValue","dprEntry","assertion","msg","_executor_latestErrorTask","insightOpt","thought","message","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","_task_error","_this_interface","base64","now","Date","recorder","_this","groupName","groupDescription","executions","newExecutions","Array","tasks","restExecution","newTasks","uiContext","log","restTask","opts","cacheConfig","processCacheConfig","id","rawStrategy","strategyValue","isReadOnly","isWriteOnly","options","interfaceInstance","Object","ModelConfigManager","globalModelConfigManager","Insight","cacheConfigObj","TaskCache","TaskExecutor","getReportF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I,CAAC,OAAO,EAAE;YACjE,WAAW,IAAI,CAAC,SAAS;YACzB,aAAa,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAI;YAClD,sBAAsB,IAAI,CAAC,IAAI,CAAC,oBAAoB;QACtD;QACA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS;QAC1B,IAAI,CAAC,cAAc,GACjBhB,AAAAA,CAAAA,QAAAA,OAAAA,KAAAA,IAAAA,KAAM,cAAc,AAAD,KACnBiB,kBAAkBjB,AAAAA,CAAAA,QAAAA,OAAAA,KAAAA,IAAAA,KAAM,MAAM,AAAD,KAAK,IAAI,CAAC,SAAS,CAAC,aAAa,IAAI;IACtE;AAs+BF;AAEO,MAAMkB,cAAc,CACzBT,mBACAT,OAEO,IAAIlI,MAAM2I,mBAAmBT"}
|
|
@@ -86,10 +86,26 @@ class TaskCache {
|
|
|
86
86
|
return;
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
|
-
flushCacheToFile() {
|
|
89
|
+
flushCacheToFile(options) {
|
|
90
90
|
const version = getMidsceneVersion();
|
|
91
91
|
if (!version) return void debug('no midscene version info, will not write cache to file');
|
|
92
92
|
if (!this.cacheFilePath) return void debug('no cache file path, will not write cache to file');
|
|
93
|
+
if (null == options ? void 0 : options.cleanUnused) if (this.isCacheResultUsed) {
|
|
94
|
+
const originalLength = this.cache.caches.length;
|
|
95
|
+
const usedIndices = new Set();
|
|
96
|
+
for (const key of this.matchedCacheIndices){
|
|
97
|
+
const parts = key.split(':');
|
|
98
|
+
const index = Number.parseInt(parts[parts.length - 1], 10);
|
|
99
|
+
if (!Number.isNaN(index)) usedIndices.add(index);
|
|
100
|
+
}
|
|
101
|
+
this.cache.caches = this.cache.caches.filter((_, index)=>{
|
|
102
|
+
const isUsed = usedIndices.has(index);
|
|
103
|
+
const isNew = index >= this.cacheOriginalLength;
|
|
104
|
+
return isUsed || isNew;
|
|
105
|
+
});
|
|
106
|
+
const removedCount = originalLength - this.cache.caches.length;
|
|
107
|
+
removedCount > 0 ? debug('cleaned %d unused cache record(s)', removedCount) : debug('no unused cache to clean');
|
|
108
|
+
} else debug('skip cleaning: cache is not used for reading');
|
|
93
109
|
try {
|
|
94
110
|
const dir = dirname(this.cacheFilePath);
|
|
95
111
|
if (!existsSync(dir)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent/task-cache.mjs","sources":["webpack://@midscene/core/./src/agent/task-cache.ts"],"sourcesContent":["import assert from 'node:assert';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type { TUserPrompt } from '@/ai-model';\nimport type { ElementCacheFeature } from '@/types';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport {\n MIDSCENE_CACHE_MAX_FILENAME_LENGTH,\n globalConfigManager,\n} from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { ifInBrowser, ifInWorker } from '@midscene/shared/utils';\nimport { generateHashId } from '@midscene/shared/utils';\nimport { replaceIllegalPathCharsAndSpace } from '@midscene/shared/utils';\nimport yaml from 'js-yaml';\nimport semver from 'semver';\nimport { getMidsceneVersion } from './utils';\n\nconst DEFAULT_CACHE_MAX_FILENAME_LENGTH = 200;\n\nexport const 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: TUserPrompt;\n cache?: ElementCacheFeature;\n /** @deprecated kept for backward compatibility */\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';\nexport const 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 readOnlyMode: boolean; // a flag to indicate if the cache is in read-only mode\n\n writeOnlyMode: boolean; // a flag to indicate if the cache is in write-only mode\n\n private matchedCacheIndices: Set<string> = new Set(); // Track matched records\n\n constructor(\n cacheId: string,\n isCacheResultUsed: boolean,\n cacheFilePath?: string,\n options: { readOnly?: boolean; writeOnly?: boolean } = {},\n ) {\n assert(cacheId, 'cacheId is required');\n let safeCacheId = replaceIllegalPathCharsAndSpace(cacheId);\n const cacheMaxFilenameLength =\n globalConfigManager.getEnvConfigInNumber(\n MIDSCENE_CACHE_MAX_FILENAME_LENGTH,\n ) || DEFAULT_CACHE_MAX_FILENAME_LENGTH;\n if (Buffer.byteLength(safeCacheId, 'utf8') > cacheMaxFilenameLength) {\n const prefix = safeCacheId.slice(0, 32);\n const hash = generateHashId(undefined, safeCacheId);\n safeCacheId = `${prefix}-${hash}`;\n }\n this.cacheId = safeCacheId;\n\n this.cacheFilePath =\n ifInBrowser || ifInWorker\n ? undefined\n : cacheFilePath ||\n join(getMidsceneRunSubDir('cache'), `${this.cacheId}${cacheFileExt}`);\n const readOnlyMode = Boolean(options?.readOnly);\n const writeOnlyMode = Boolean(options?.writeOnly);\n\n if (readOnlyMode && writeOnlyMode) {\n throw new Error('TaskCache cannot be both read-only and write-only');\n }\n\n this.isCacheResultUsed = writeOnlyMode ? false : isCacheResultUsed;\n this.readOnlyMode = readOnlyMode;\n this.writeOnlyMode = writeOnlyMode;\n\n let cacheContent;\n if (this.cacheFilePath && !this.writeOnlyMode) {\n cacheContent = this.loadCacheFromFile();\n }\n if (!cacheContent) {\n cacheContent = {\n midsceneVersion: getMidsceneVersion(),\n cacheId: this.cacheId,\n caches: [],\n };\n }\n this.cache = cacheContent;\n this.cacheOriginalLength = this.isCacheResultUsed\n ? this.cache.caches.length\n : 0;\n }\n\n matchCache(\n prompt: TUserPrompt,\n type: 'plan' | 'locate',\n ): MatchCacheResult<PlanningCache | LocateCache> | undefined {\n if (!this.isCacheResultUsed) {\n return undefined;\n }\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 promptStr =\n typeof prompt === 'string' ? prompt : JSON.stringify(prompt);\n const key = `${type}:${promptStr}:${i}`;\n if (\n item.type === type &&\n isDeepStrictEqual(item.prompt, prompt) &&\n !this.matchedCacheIndices.has(key)\n ) {\n if (item.type === 'locate') {\n const locateItem = item as LocateCache;\n if (!locateItem.cache && Array.isArray(locateItem.xpaths)) {\n locateItem.cache = { xpaths: locateItem.xpaths };\n }\n if ('xpaths' in locateItem) {\n locateItem.xpaths = undefined;\n }\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\n if (this.readOnlyMode) {\n debug(\n 'read-only mode, cache updated in memory but not flushed to file',\n );\n return;\n }\n\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(\n prompt: TUserPrompt,\n ): 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\n if (this.readOnlyMode) {\n debug('read-only mode, cache appended to memory but not flushed to file');\n return;\n }\n\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 const version = getMidsceneVersion();\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 = getMidsceneVersion(); // 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 const version = getMidsceneVersion();\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 dir = dirname(this.cacheFilePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n debug('created cache directory: %s', dir);\n }\n\n // Sort caches to ensure plan entries come before locate entries for better readability\n const sortedCaches = [...this.cache.caches].sort((a, b) => {\n if (a.type === 'plan' && b.type === 'locate') return -1;\n if (a.type === 'locate' && b.type === 'plan') return 1;\n return 0;\n });\n\n const cacheToWrite = {\n ...this.cache,\n caches: sortedCaches,\n };\n\n const yamlData = yaml.dump(cacheToWrite);\n writeFileSync(this.cacheFilePath, yamlData);\n debug('cache flushed to file: %s', this.cacheFilePath);\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 const locateCache = cache as LocateCache;\n locateCache.cache = newRecord.cache;\n if ('xpaths' in locateCache) {\n locateCache.xpaths = undefined;\n }\n });\n }\n } else {\n this.appendCache(newRecord);\n }\n }\n}\n"],"names":["DEFAULT_CACHE_MAX_FILENAME_LENGTH","debug","getDebug","lowestSupportedMidsceneVersion","cacheFileExt","TaskCache","prompt","type","i","item","promptStr","JSON","key","isDeepStrictEqual","locateItem","Array","undefined","cb","cache","cacheFile","assert","existsSync","jsonTypeCacheFile","console","data","readFileSync","jsonData","yaml","version","getMidsceneVersion","semver","err","dir","dirname","mkdirSync","sortedCaches","a","b","cacheToWrite","yamlData","writeFileSync","newRecord","cachedRecord","locateCache","cacheId","isCacheResultUsed","cacheFilePath","options","Set","safeCacheId","replaceIllegalPathCharsAndSpace","cacheMaxFilenameLength","globalConfigManager","MIDSCENE_CACHE_MAX_FILENAME_LENGTH","Buffer","prefix","hash","generateHashId","ifInBrowser","ifInWorker","join","getMidsceneRunSubDir","readOnlyMode","Boolean","writeOnlyMode","Error","cacheContent"],"mappings":";;;;;;;;;;;;;;;;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,YAAOwB,SAAS;QAChB,IAAIK,cAAcC,gCAAgCN;QAClD,MAAMO,yBACJC,oBAAoB,oBAAoB,CACtCC,uCACGrD;QACP,IAAIsD,OAAO,UAAU,CAACL,aAAa,UAAUE,wBAAwB;YACnE,MAAMI,SAASN,YAAY,KAAK,CAAC,GAAG;YACpC,MAAMO,OAAOC,eAAezC,QAAWiC;YACvCA,cAAc,GAAGM,OAAO,CAAC,EAAEC,MAAM;QACnC;QACA,IAAI,CAAC,OAAO,GAAGP;QAEf,IAAI,CAAC,aAAa,GAChBS,eAAeC,aACX3C,SACA8B,iBACAc,KAAKC,qBAAqB,UAAU,GAAG,IAAI,CAAC,OAAO,GAAGzD,cAAc;QAC1E,MAAM0D,eAAeC,QAAQhB,QAAAA,UAAAA,KAAAA,IAAAA,QAAS,QAAQ;QAC9C,MAAMiB,gBAAgBD,QAAQhB,QAAAA,UAAAA,KAAAA,IAAAA,QAAS,SAAS;QAEhD,IAAIe,gBAAgBE,eAClB,MAAM,IAAIC,MAAM;QAGlB,IAAI,CAAC,iBAAiB,GAAGD,gBAAgB,QAAQnB;QACjD,IAAI,CAAC,YAAY,GAAGiB;QACpB,IAAI,CAAC,aAAa,GAAGE;QAErB,IAAIE;QACJ,IAAI,IAAI,CAAC,aAAa,IAAI,CAAC,IAAI,CAAC,aAAa,EAC3CA,eAAe,IAAI,CAAC,iBAAiB;QAEvC,IAAI,CAACA,cACHA,eAAe;YACb,iBAAiBrC;YACjB,SAAS,IAAI,CAAC,OAAO;YACrB,QAAQ,EAAE;QACZ;QAEF,IAAI,CAAC,KAAK,GAAGqC;QACb,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,iBAAiB,GAC7C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,GACxB;IACN;AAyNF"}
|
|
1
|
+
{"version":3,"file":"agent/task-cache.mjs","sources":["webpack://@midscene/core/./src/agent/task-cache.ts"],"sourcesContent":["import assert from 'node:assert';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type { TUserPrompt } from '@/ai-model';\nimport type { ElementCacheFeature } from '@/types';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport {\n MIDSCENE_CACHE_MAX_FILENAME_LENGTH,\n globalConfigManager,\n} from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { ifInBrowser, ifInWorker } from '@midscene/shared/utils';\nimport { generateHashId } from '@midscene/shared/utils';\nimport { replaceIllegalPathCharsAndSpace } from '@midscene/shared/utils';\nimport yaml from 'js-yaml';\nimport semver from 'semver';\nimport { getMidsceneVersion } from './utils';\n\nconst DEFAULT_CACHE_MAX_FILENAME_LENGTH = 200;\n\nexport const 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: TUserPrompt;\n cache?: ElementCacheFeature;\n /** @deprecated kept for backward compatibility */\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';\nexport const 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 readOnlyMode: boolean; // a flag to indicate if the cache is in read-only mode\n\n writeOnlyMode: boolean; // a flag to indicate if the cache is in write-only mode\n\n private matchedCacheIndices: Set<string> = new Set(); // Track matched records\n\n constructor(\n cacheId: string,\n isCacheResultUsed: boolean,\n cacheFilePath?: string,\n options: { readOnly?: boolean; writeOnly?: boolean } = {},\n ) {\n assert(cacheId, 'cacheId is required');\n let safeCacheId = replaceIllegalPathCharsAndSpace(cacheId);\n const cacheMaxFilenameLength =\n globalConfigManager.getEnvConfigInNumber(\n MIDSCENE_CACHE_MAX_FILENAME_LENGTH,\n ) || DEFAULT_CACHE_MAX_FILENAME_LENGTH;\n if (Buffer.byteLength(safeCacheId, 'utf8') > cacheMaxFilenameLength) {\n const prefix = safeCacheId.slice(0, 32);\n const hash = generateHashId(undefined, safeCacheId);\n safeCacheId = `${prefix}-${hash}`;\n }\n this.cacheId = safeCacheId;\n\n this.cacheFilePath =\n ifInBrowser || ifInWorker\n ? undefined\n : cacheFilePath ||\n join(getMidsceneRunSubDir('cache'), `${this.cacheId}${cacheFileExt}`);\n const readOnlyMode = Boolean(options?.readOnly);\n const writeOnlyMode = Boolean(options?.writeOnly);\n\n if (readOnlyMode && writeOnlyMode) {\n throw new Error('TaskCache cannot be both read-only and write-only');\n }\n\n this.isCacheResultUsed = writeOnlyMode ? false : isCacheResultUsed;\n this.readOnlyMode = readOnlyMode;\n this.writeOnlyMode = writeOnlyMode;\n\n let cacheContent;\n if (this.cacheFilePath && !this.writeOnlyMode) {\n cacheContent = this.loadCacheFromFile();\n }\n if (!cacheContent) {\n cacheContent = {\n midsceneVersion: getMidsceneVersion(),\n cacheId: this.cacheId,\n caches: [],\n };\n }\n this.cache = cacheContent;\n this.cacheOriginalLength = this.isCacheResultUsed\n ? this.cache.caches.length\n : 0;\n }\n\n matchCache(\n prompt: TUserPrompt,\n type: 'plan' | 'locate',\n ): MatchCacheResult<PlanningCache | LocateCache> | undefined {\n if (!this.isCacheResultUsed) {\n return undefined;\n }\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 promptStr =\n typeof prompt === 'string' ? prompt : JSON.stringify(prompt);\n const key = `${type}:${promptStr}:${i}`;\n if (\n item.type === type &&\n isDeepStrictEqual(item.prompt, prompt) &&\n !this.matchedCacheIndices.has(key)\n ) {\n if (item.type === 'locate') {\n const locateItem = item as LocateCache;\n if (!locateItem.cache && Array.isArray(locateItem.xpaths)) {\n locateItem.cache = { xpaths: locateItem.xpaths };\n }\n if ('xpaths' in locateItem) {\n locateItem.xpaths = undefined;\n }\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\n if (this.readOnlyMode) {\n debug(\n 'read-only mode, cache updated in memory but not flushed to file',\n );\n return;\n }\n\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(\n prompt: TUserPrompt,\n ): 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\n if (this.readOnlyMode) {\n debug('read-only mode, cache appended to memory but not flushed to file');\n return;\n }\n\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 const version = getMidsceneVersion();\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 = getMidsceneVersion(); // 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(options?: { cleanUnused?: boolean }) {\n const version = getMidsceneVersion();\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 // Clean unused caches if requested\n if (options?.cleanUnused) {\n // Skip cleaning in write-only mode or when cache is not used\n if (this.isCacheResultUsed) {\n const originalLength = this.cache.caches.length;\n\n // Collect indices of used caches\n const usedIndices = new Set<number>();\n for (const key of this.matchedCacheIndices) {\n // key format: \"type:prompt:index\"\n const parts = key.split(':');\n const index = Number.parseInt(parts[parts.length - 1], 10);\n if (!Number.isNaN(index)) {\n usedIndices.add(index);\n }\n }\n\n // Filter: keep used caches and newly added caches\n this.cache.caches = this.cache.caches.filter((_, index) => {\n const isUsed = usedIndices.has(index);\n const isNew = index >= this.cacheOriginalLength;\n return isUsed || isNew;\n });\n\n const removedCount = originalLength - this.cache.caches.length;\n if (removedCount > 0) {\n debug('cleaned %d unused cache record(s)', removedCount);\n } else {\n debug('no unused cache to clean');\n }\n } else {\n debug('skip cleaning: cache is not used for reading');\n }\n }\n\n try {\n const dir = dirname(this.cacheFilePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n debug('created cache directory: %s', dir);\n }\n\n // Sort caches to ensure plan entries come before locate entries for better readability\n // Create a sorted copy for writing to disk while keeping in-memory order unchanged\n const sortedCaches = [...this.cache.caches].sort((a, b) => {\n if (a.type === 'plan' && b.type === 'locate') return -1;\n if (a.type === 'locate' && b.type === 'plan') return 1;\n return 0;\n });\n\n const cacheToWrite = {\n ...this.cache,\n caches: sortedCaches,\n };\n\n const yamlData = yaml.dump(cacheToWrite);\n writeFileSync(this.cacheFilePath, yamlData);\n debug('cache flushed to file: %s', this.cacheFilePath);\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 const locateCache = cache as LocateCache;\n locateCache.cache = newRecord.cache;\n if ('xpaths' in locateCache) {\n locateCache.xpaths = undefined;\n }\n });\n }\n } else {\n this.appendCache(newRecord);\n }\n }\n}\n"],"names":["DEFAULT_CACHE_MAX_FILENAME_LENGTH","debug","getDebug","lowestSupportedMidsceneVersion","cacheFileExt","TaskCache","prompt","type","i","item","promptStr","JSON","key","isDeepStrictEqual","locateItem","Array","undefined","cb","cache","cacheFile","assert","existsSync","jsonTypeCacheFile","console","data","readFileSync","jsonData","yaml","version","getMidsceneVersion","semver","err","options","originalLength","usedIndices","Set","parts","index","Number","_","isUsed","isNew","removedCount","dir","dirname","mkdirSync","sortedCaches","a","b","cacheToWrite","yamlData","writeFileSync","newRecord","cachedRecord","locateCache","cacheId","isCacheResultUsed","cacheFilePath","safeCacheId","replaceIllegalPathCharsAndSpace","cacheMaxFilenameLength","globalConfigManager","MIDSCENE_CACHE_MAX_FILENAME_LENGTH","Buffer","prefix","hash","generateHashId","ifInBrowser","ifInWorker","join","getMidsceneRunSubDir","readOnlyMode","Boolean","writeOnlyMode","Error","cacheContent"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmBA,MAAMA,oCAAoC;AAEnC,MAAMC,QAAQC,SAAS;AA2B9B,MAAMC,iCAAiC;AAChC,MAAMC,eAAe;AAErB,MAAMC;IAoEX,WACEC,MAAmB,EACnBC,IAAuB,EACoC;QAC3D,IAAI,CAAC,IAAI,CAAC,iBAAiB,EACzB;QAGF,IAAK,IAAIC,IAAI,GAAGA,IAAI,IAAI,CAAC,mBAAmB,EAAEA,IAAK;YACjD,MAAMC,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAACD,EAAE;YACjC,MAAME,YACJ,AAAkB,YAAlB,OAAOJ,SAAsBA,SAASK,KAAK,SAAS,CAACL;YACvD,MAAMM,MAAM,GAAGL,KAAK,CAAC,EAAEG,UAAU,CAAC,EAAEF,GAAG;YACvC,IACEC,KAAK,IAAI,KAAKF,QACdM,kBAAkBJ,KAAK,MAAM,EAAEH,WAC/B,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACM,MAC9B;gBACA,IAAIH,AAAc,aAAdA,KAAK,IAAI,EAAe;oBAC1B,MAAMK,aAAaL;oBACnB,IAAI,CAACK,WAAW,KAAK,IAAIC,MAAM,OAAO,CAACD,WAAW,MAAM,GACtDA,WAAW,KAAK,GAAG;wBAAE,QAAQA,WAAW,MAAM;oBAAC;oBAEjD,IAAI,YAAYA,YACdA,WAAW,MAAM,GAAGE;gBAExB;gBACA,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACJ;gBAC7BX,MACE,mEACAM,MACAD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9D;QACP,IAAI+D,OAAO,UAAU,CAACL,aAAa,UAAUE,wBAAwB;YACnE,MAAMI,SAASN,YAAY,KAAK,CAAC,GAAG;YACpC,MAAMO,OAAOC,eAAelD,QAAW0C;YACvCA,cAAc,GAAGM,OAAO,CAAC,EAAEC,MAAM;QACnC;QACA,IAAI,CAAC,OAAO,GAAGP;QAEf,IAAI,CAAC,aAAa,GAChBS,eAAeC,aACXpD,SACAyC,iBACAY,KAAKC,qBAAqB,UAAU,GAAG,IAAI,CAAC,OAAO,GAAGlE,cAAc;QAC1E,MAAMmE,eAAeC,QAAQxC,QAAAA,UAAAA,KAAAA,IAAAA,QAAS,QAAQ;QAC9C,MAAMyC,gBAAgBD,QAAQxC,QAAAA,UAAAA,KAAAA,IAAAA,QAAS,SAAS;QAEhD,IAAIuC,gBAAgBE,eAClB,MAAM,IAAIC,MAAM;QAGlB,IAAI,CAAC,iBAAiB,GAAGD,gBAAgB,QAAQjB;QACjD,IAAI,CAAC,YAAY,GAAGe;QACpB,IAAI,CAAC,aAAa,GAAGE;QAErB,IAAIE;QACJ,IAAI,IAAI,CAAC,aAAa,IAAI,CAAC,IAAI,CAAC,aAAa,EAC3CA,eAAe,IAAI,CAAC,iBAAiB;QAEvC,IAAI,CAACA,cACHA,eAAe;YACb,iBAAiB9C;YACjB,SAAS,IAAI,CAAC,OAAO;YACrB,QAAQ,EAAE;QACZ;QAEF,IAAI,CAAC,KAAK,GAAG8C;QACb,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,iBAAiB,GAC7C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,GACxB;IACN;AA6PF"}
|
package/dist/es/agent/utils.mjs
CHANGED
|
@@ -143,7 +143,7 @@ function trimContextByViewport(execution) {
|
|
|
143
143
|
}) : execution.tasks
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
|
-
const getMidsceneVersion = ()=>"0.30.3-beta-
|
|
146
|
+
const getMidsceneVersion = ()=>"0.30.3-beta-20251015093703.0";
|
|
147
147
|
const parsePrompt = (prompt)=>{
|
|
148
148
|
if ('string' == typeof prompt) return {
|
|
149
149
|
textPrompt: prompt,
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { getMidsceneRunSubDir } from "@midscene/shared/common";
|
|
4
|
+
import { getReportFileName } from "./agent/index.mjs";
|
|
5
|
+
import { getReportTpl, reportHTMLContent } from "./utils.mjs";
|
|
6
|
+
function _define_property(obj, key, value) {
|
|
7
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
8
|
+
value: value,
|
|
9
|
+
enumerable: true,
|
|
10
|
+
configurable: true,
|
|
11
|
+
writable: true
|
|
12
|
+
});
|
|
13
|
+
else obj[key] = value;
|
|
14
|
+
return obj;
|
|
15
|
+
}
|
|
16
|
+
class ReportMergingTool {
|
|
17
|
+
append(reportInfo) {
|
|
18
|
+
this.reportInfos.push(reportInfo);
|
|
19
|
+
}
|
|
20
|
+
clear() {
|
|
21
|
+
this.reportInfos = [];
|
|
22
|
+
}
|
|
23
|
+
extractScriptContent(filePath) {
|
|
24
|
+
const scriptRegex = /\n<script type="midscene_web_dump" type="application\/json"[^>]*>([\s\S]*?)\n<\/script>/;
|
|
25
|
+
const fileContent = readFileSync(filePath, 'utf-8');
|
|
26
|
+
const match = scriptRegex.exec(fileContent);
|
|
27
|
+
return match ? match[1].trim() : '';
|
|
28
|
+
}
|
|
29
|
+
mergeReports(reportFileName = 'AUTO', opts) {
|
|
30
|
+
if (this.reportInfos.length <= 1) {
|
|
31
|
+
console.log('Not enough report to merge');
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
opts = Object.assign({
|
|
35
|
+
rmOriginalReports: false,
|
|
36
|
+
overwrite: false
|
|
37
|
+
}, opts || {});
|
|
38
|
+
const { rmOriginalReports, overwrite } = opts;
|
|
39
|
+
let outputFilePath;
|
|
40
|
+
const targetDir = `${getMidsceneRunSubDir('report')}`;
|
|
41
|
+
if ('AUTO' === reportFileName) outputFilePath = resolve(targetDir, `${getReportFileName('merged-report')}.html`);
|
|
42
|
+
else {
|
|
43
|
+
outputFilePath = resolve(targetDir, `${reportFileName}.html`);
|
|
44
|
+
if (existsSync(outputFilePath) && !overwrite) throw Error(`report file already existed: ${outputFilePath}\nset override to true to overwrite this file.`);
|
|
45
|
+
if (existsSync(outputFilePath) && overwrite) unlinkSync(outputFilePath);
|
|
46
|
+
}
|
|
47
|
+
console.log(`Start merging ${this.reportInfos.length} reports...\nCreating template file...`);
|
|
48
|
+
try {
|
|
49
|
+
appendFileSync(outputFilePath, getReportTpl());
|
|
50
|
+
for(let i = 0; i < this.reportInfos.length; i++){
|
|
51
|
+
const reportInfo = this.reportInfos[i];
|
|
52
|
+
console.log(`Processing report ${i + 1}/${this.reportInfos.length}`);
|
|
53
|
+
const dumpString = this.extractScriptContent(reportInfo.reportFilePath);
|
|
54
|
+
const reportAttributes = reportInfo.reportAttributes;
|
|
55
|
+
const reportHtmlStr = `${reportHTMLContent({
|
|
56
|
+
dumpString,
|
|
57
|
+
attributes: {
|
|
58
|
+
playwright_test_duration: reportAttributes.testDuration,
|
|
59
|
+
playwright_test_status: reportAttributes.testStatus,
|
|
60
|
+
playwright_test_title: reportAttributes.testTitle,
|
|
61
|
+
playwright_test_id: reportAttributes.testId,
|
|
62
|
+
playwright_test_description: reportAttributes.testDescription
|
|
63
|
+
}
|
|
64
|
+
}, void 0, void 0, false)}\n`;
|
|
65
|
+
appendFileSync(outputFilePath, reportHtmlStr);
|
|
66
|
+
}
|
|
67
|
+
console.log(`Successfully merged new report: ${outputFilePath}`);
|
|
68
|
+
if (rmOriginalReports) {
|
|
69
|
+
for (const info of this.reportInfos)try {
|
|
70
|
+
unlinkSync(info.reportFilePath);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error(`Error deleting report ${info.reportFilePath}:`, error);
|
|
73
|
+
}
|
|
74
|
+
console.log(`Removed ${this.reportInfos.length} original reports`);
|
|
75
|
+
}
|
|
76
|
+
return outputFilePath;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.error('Error in mergeReports:', error);
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
constructor(){
|
|
83
|
+
_define_property(this, "reportInfos", []);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export { ReportMergingTool };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=report.mjs.map
|