@midscene/core 1.9.7 → 1.9.8-beta-20260618091332.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 +29 -20
- package/dist/es/agent/agent.mjs.map +1 -1
- package/dist/es/agent/record-to-report.mjs +14 -0
- package/dist/es/agent/record-to-report.mjs.map +1 -0
- package/dist/es/agent/utils.mjs +14 -2
- package/dist/es/agent/utils.mjs.map +1 -1
- package/dist/es/index.mjs.map +1 -1
- package/dist/es/report-markdown.mjs +2 -1
- package/dist/es/report-markdown.mjs.map +1 -1
- package/dist/es/types.mjs.map +1 -1
- package/dist/es/utils.mjs +2 -2
- package/dist/lib/agent/agent.js +29 -20
- package/dist/lib/agent/agent.js.map +1 -1
- package/dist/lib/agent/record-to-report.js +48 -0
- package/dist/lib/agent/record-to-report.js.map +1 -0
- package/dist/lib/agent/utils.js +16 -1
- package/dist/lib/agent/utils.js.map +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/report-markdown.js +2 -1
- package/dist/lib/report-markdown.js.map +1 -1
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/utils.js +2 -2
- package/dist/types/agent/agent.d.ts +2 -5
- package/dist/types/agent/index.d.ts +1 -0
- package/dist/types/agent/record-to-report.d.ts +2 -0
- package/dist/types/agent/utils.d.ts +2 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/types.d.ts +19 -0
- package/dist/types/yaml.d.ts +13 -0
- package/package.json +2 -2
package/dist/es/agent/agent.mjs
CHANGED
|
@@ -14,11 +14,12 @@ import { getDebug } from "@midscene/shared/logger";
|
|
|
14
14
|
import { assert, ifInBrowser, uuid } from "@midscene/shared/utils";
|
|
15
15
|
import { defineActionSleep } from "../device/index.mjs";
|
|
16
16
|
import { validateAgentCacheInput } from "./cache-config.mjs";
|
|
17
|
+
import { normalizeRecordToReportScreenshot } from "./record-to-report.mjs";
|
|
17
18
|
import { markdownToAiActPrompt } from "./run-markdown.mjs";
|
|
18
19
|
import { TaskCache } from "./task-cache.mjs";
|
|
19
20
|
import { TaskExecutionError, TaskExecutor, locatePlanForLocate, withFileChooser } from "./tasks.mjs";
|
|
20
21
|
import { locateParamStr, paramStr, taskTitleStr, typeStr } from "./ui-utils.mjs";
|
|
21
|
-
import { commonContextParser, createScreenshotBoundUIContext, getReportFileName, parsePrompt } from "./utils.mjs";
|
|
22
|
+
import { commonContextParser, createScreenshotBoundUIContext, getReportFileName, normalizeScrollType, parsePrompt } from "./utils.mjs";
|
|
22
23
|
function _define_property(obj, key, value) {
|
|
23
24
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
24
25
|
value: value,
|
|
@@ -59,18 +60,6 @@ const defaultServiceExtractOption = {
|
|
|
59
60
|
domIncluded: false,
|
|
60
61
|
screenshotIncluded: true
|
|
61
62
|
};
|
|
62
|
-
const legacyScrollTypeMap = {
|
|
63
|
-
once: 'singleAction',
|
|
64
|
-
untilBottom: 'scrollToBottom',
|
|
65
|
-
untilTop: 'scrollToTop',
|
|
66
|
-
untilRight: 'scrollToRight',
|
|
67
|
-
untilLeft: 'scrollToLeft'
|
|
68
|
-
};
|
|
69
|
-
const normalizeScrollType = (scrollType)=>{
|
|
70
|
-
if (!scrollType) return scrollType;
|
|
71
|
-
if (scrollType in legacyScrollTypeMap) return legacyScrollTypeMap[scrollType];
|
|
72
|
-
return scrollType;
|
|
73
|
-
};
|
|
74
63
|
class Agent {
|
|
75
64
|
get onDumpUpdate() {
|
|
76
65
|
return this.dumpUpdateListeners[0];
|
|
@@ -633,16 +622,36 @@ class Agent {
|
|
|
633
622
|
if (interfaceDestroyError) throw interfaceDestroyError;
|
|
634
623
|
}
|
|
635
624
|
async recordToReport(title, opt) {
|
|
636
|
-
const base64 = opt?.screenshotBase64 ?? await this.interface.screenshotBase64();
|
|
637
625
|
const now = Date.now();
|
|
638
|
-
const
|
|
639
|
-
const
|
|
626
|
+
const screenshots = opt?.screenshots;
|
|
627
|
+
const screenshotBase64 = opt?.screenshotBase64;
|
|
628
|
+
const hasScreenshots = void 0 !== screenshots;
|
|
629
|
+
const hasScreenshotBase64 = void 0 !== screenshotBase64;
|
|
630
|
+
if (hasScreenshots && !Array.isArray(screenshots)) throw new Error('recordToReport: screenshots must be an array');
|
|
631
|
+
if (hasScreenshotBase64 && 'string' != typeof screenshotBase64) throw new Error('recordToReport: screenshotBase64 must be a string');
|
|
632
|
+
if (hasScreenshots && hasScreenshotBase64) throw new Error('recordToReport: provide only one of screenshots or screenshotBase64');
|
|
633
|
+
if (opt && 'subType' in opt) throw new Error('recordToReport: subType is not supported');
|
|
634
|
+
const customScreenshots = hasScreenshots ? screenshots : void 0;
|
|
635
|
+
if (customScreenshots && 0 === customScreenshots.length) throw new Error('recordToReport: screenshots cannot be empty');
|
|
636
|
+
const screenshotInputs = customScreenshots ?? (hasScreenshotBase64 ? [
|
|
640
637
|
{
|
|
641
|
-
|
|
642
|
-
ts: now,
|
|
643
|
-
screenshot
|
|
638
|
+
base64: screenshotBase64
|
|
644
639
|
}
|
|
645
|
-
]
|
|
640
|
+
] : [
|
|
641
|
+
{
|
|
642
|
+
base64: await this.interface.screenshotBase64()
|
|
643
|
+
}
|
|
644
|
+
]);
|
|
645
|
+
const recorder = screenshotInputs.map((screenshotInput, index)=>{
|
|
646
|
+
const normalizedScreenshotInput = normalizeRecordToReportScreenshot(screenshotInput, index);
|
|
647
|
+
const ts = now + index;
|
|
648
|
+
return {
|
|
649
|
+
type: 'screenshot',
|
|
650
|
+
ts,
|
|
651
|
+
screenshot: ScreenshotItem.create(normalizedScreenshotInput.base64, ts),
|
|
652
|
+
description: normalizedScreenshotInput.description
|
|
653
|
+
};
|
|
654
|
+
});
|
|
646
655
|
const task = {
|
|
647
656
|
taskId: uuid(),
|
|
648
657
|
type: 'Log',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent/agent.mjs","sources":["../../../src/agent/agent.ts"],"sourcesContent":["import { type ModelRuntime, getModelRuntime } from '@/ai-model/models';\nimport yaml from 'js-yaml';\nimport type { TUserPrompt } from '../ai-model/index';\nimport { ScreenshotItem } from '../screenshot-item';\nimport Service from '../service/index';\n// Import types and values directly from their source files to avoid circular dependency\n// DO NOT import from '../index' as it creates a circular dependency:\n// index.ts -> agent/index.ts -> agent/agent.ts -> index.ts\nimport {\n type ActionParam,\n type ActionReturn,\n type AgentAssertOpt,\n type AgentDescribeElementAtPointResult,\n type AgentOpt,\n type AgentWaitForOpt,\n type DeepThinkOption,\n type DeviceAction,\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskLog,\n type LocateOption,\n type LocateResultElement,\n type LocateValidatorResult,\n type LocatorValidatorOption,\n type OnTaskStartTip,\n type PlanningAction,\n type Rect,\n ReportActionDump,\n type ReportMeta,\n type ScrollParam,\n type ServiceAction,\n type ServiceExtractOption,\n type ServiceExtractParam,\n type Size,\n type TestStatus,\n type UIContext,\n} from '../types';\nimport type { MidsceneYamlScript } from '../yaml';\n\nimport type { IReportGenerator } from '@/report-generator';\nimport {\n ReportGenerator,\n assertReportGenerationOptions,\n} from '@/report-generator';\nimport { getVersion, processCacheConfig, reportHTMLContent } from '@/utils';\nimport {\n ScriptPlayer,\n buildDetailedLocateParam,\n parseYamlScript,\n} from '../yaml/index';\n\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport type { AbstractInterface } from '@/device';\nimport type { TaskRunner } from '@/task-runner';\nimport {\n type IModelConfig,\n MIDSCENE_REPLANNING_CYCLE_LIMIT,\n ModelConfigManager,\n type TIntent,\n globalConfigManager,\n globalModelConfigManager,\n} from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert, ifInBrowser, uuid } from '@midscene/shared/utils';\nimport { defineActionSleep } from '../device';\nimport { validateAgentCacheInput } from './cache-config';\nimport { markdownToAiActPrompt } from './run-markdown';\nimport { TaskCache } from './task-cache';\nimport {\n TaskExecutionError,\n TaskExecutor,\n locatePlanForLocate,\n withFileChooser,\n} from './tasks';\nimport {\n type TaskTitleType,\n locateParamStr,\n paramStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport {\n commonContextParser,\n createScreenshotBoundUIContext,\n getReportFileName,\n parsePrompt,\n} from './utils';\n\nexport type DescribeElementCoordinateSpace = 'screenshot' | 'logical';\n\nexport type DescribeElementAtPointOptions = {\n verifyPrompt?: boolean;\n retryLimit?: number;\n deepLocate?: boolean;\n screenshotBase64?: string;\n screenshotSize?: Size;\n coordinateSpace?: DescribeElementCoordinateSpace;\n logicalSize?: Size;\n onProgress?: (progress: {\n prompt?: string;\n deepLocate?: boolean;\n verifyResult?: LocateValidatorResult;\n }) => void;\n} & LocatorValidatorOption;\n\nconst debug = getDebug('agent');\nconst warn = getDebug('agent', { console: true });\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\nfunction assertPositiveSize(\n size: Size | undefined,\n label: string,\n): asserts size is Size {\n assert(\n size &&\n Number.isFinite(size.width) &&\n Number.isFinite(size.height) &&\n size.width > 0 &&\n size.height > 0,\n `${label} must include positive width and height`,\n );\n}\n\nconst mapPointToScreenshotSpace = (\n center: [number, number],\n screenshotSize: Size,\n opt: DescribeElementAtPointOptions,\n): [number, number] => {\n const coordinateSpace = opt.coordinateSpace || 'screenshot';\n if (coordinateSpace === 'screenshot') {\n return center;\n }\n\n assertPositiveSize(\n opt.logicalSize,\n 'logicalSize is required when coordinateSpace is logical',\n );\n return [\n (center[0] * screenshotSize.width) / opt.logicalSize.width,\n (center[1] * screenshotSize.height) / opt.logicalSize.height,\n ];\n};\n\nconst defaultServiceExtractOption: ServiceExtractOption = {\n domIncluded: false,\n screenshotIncluded: true,\n};\n\nconst legacyScrollTypeMap = {\n once: 'singleAction',\n untilBottom: 'scrollToBottom',\n untilTop: 'scrollToTop',\n untilRight: 'scrollToRight',\n untilLeft: 'scrollToLeft',\n} as const;\n\ntype LegacyScrollType = keyof typeof legacyScrollTypeMap;\n\nconst normalizeScrollType = (\n scrollType: ScrollParam['scrollType'] | LegacyScrollType | undefined,\n): ScrollParam['scrollType'] | undefined => {\n if (!scrollType) {\n return scrollType;\n }\n\n if (scrollType in legacyScrollTypeMap) {\n return legacyScrollTypeMap[scrollType as LegacyScrollType];\n }\n\n return scrollType as ScrollParam['scrollType'];\n};\n\nexport type AiActOptions = {\n cacheable?: boolean;\n fileChooserAccept?: string | string[];\n deepThink?: DeepThinkOption;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n};\n\ntype AiActInternalOptions = AiActOptions & {\n _internalReportDisplay?: {\n type?: TaskTitleType;\n prompt?: string;\n };\n};\n\nexport class Agent<\n InterfaceType extends AbstractInterface = AbstractInterface,\n> {\n interface: InterfaceType;\n\n service: Service;\n\n dump: ReportActionDump;\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 private dumpUpdateListeners: Array<\n (dump: string, executionDump?: ExecutionDump) => void\n > = [];\n\n get onDumpUpdate():\n | ((dump: string, executionDump?: ExecutionDump) => void)\n | undefined {\n return this.dumpUpdateListeners[0];\n }\n\n set onDumpUpdate(callback:\n | ((dump: string, executionDump?: ExecutionDump) => void)\n | undefined) {\n // Clear existing listeners\n this.dumpUpdateListeners = [];\n // Add callback to array if provided\n if (callback) {\n this.dumpUpdateListeners.push(callback);\n }\n }\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 private get aiActContext(): string | undefined {\n return this.opts.aiActContext ?? this.opts.aiActionContext;\n }\n\n private executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n private fullActionSpace: DeviceAction[];\n\n private reportGenerator: IReportGenerator;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n /**\n * Fails fast for non-web interfaces when the model family is missing.\n *\n * Early Midscene web usage allowed running without `modelFamily` and falling\n * back to a default bbox parser. Non-web users do not have that compatibility\n * path, so this check helps surface configuration problems before spending a\n * model call.\n *\n * Web flows validate missing locate model family at workflow boundaries:\n * `Service.locate` throws when aiTap/aiType fallback to the default model for\n * direct locate, and generic planning throws when aiAct asks a planning model\n * to return inline locate coordinates. Those checks are intentionally placed\n * where Midscene knows which model role should provide coordinate parsing.\n */\n private assertModelFamilyForNonWebContext() {\n if (\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 }\n }\n\n private resolveReplanningCycleLimit(planningModel: ModelRuntime): number {\n return (\n this.opts.replanningCycleLimit ??\n globalConfigManager.getEnvConfigValueAsNumber(\n MIDSCENE_REPLANNING_CYCLE_LIMIT,\n ) ??\n planningModel.adapter.planning.defaultReplanningCycleLimit\n );\n }\n\n private resolveModelRuntime(intent: TIntent): ModelRuntime {\n return getModelRuntime(this.modelConfigManager.getModelConfig(intent));\n }\n\n constructor(interfaceInstance: InterfaceType, opts?: AgentOpt) {\n this.interface = interfaceInstance;\n\n this.opts = Object.assign(\n {\n generateReport: true,\n persistExecutionDump: false,\n autoPrintReportMsg: true,\n groupName: 'Midscene Report',\n groupDescription: '',\n },\n opts || {},\n );\n assertReportGenerationOptions(this.opts);\n\n const resolvedAiActContext =\n this.opts.aiActContext ?? this.opts.aiActionContext;\n if (resolvedAiActContext !== undefined) {\n this.opts.aiActContext = resolvedAiActContext;\n this.opts.aiActionContext ??= resolvedAiActContext;\n }\n\n if (\n opts?.modelConfig &&\n (typeof opts?.modelConfig !== 'object' || Array.isArray(opts.modelConfig))\n ) {\n throw new Error(\n `opts.modelConfig must be a plain object map of env keys to values, but got ${typeof opts?.modelConfig}`,\n );\n }\n // Create ModelConfigManager if modelConfig or createOpenAIClient is provided\n // Otherwise, use the global config manager\n const hasCustomConfig = opts?.modelConfig || opts?.createOpenAIClient;\n this.modelConfigManager = hasCustomConfig\n ? new ModelConfigManager(opts?.modelConfig, opts?.createOpenAIClient)\n : globalModelConfigManager;\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n\n this.service = new Service(async () => {\n return this.getUIContext();\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 cacheDir: cacheConfigObj.cacheDir,\n },\n );\n }\n\n const baseActionSpace = this.interface.actionSpace();\n this.fullActionSpace = [...baseActionSpace, defineActionSleep()];\n\n this.taskExecutor = new TaskExecutor(this.interface, this.service, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n replanningCycleLimit: this.opts.replanningCycleLimit,\n waitAfterAction: this.opts.waitAfterAction,\n useDeviceTime: this.opts.useDeviceTime,\n actionSpace: this.fullActionSpace,\n hooks: {\n onTaskUpdate: async (runner) => {\n const executionDump = runner.dump();\n this.appendExecutionDump(executionDump, runner);\n\n // Persist report updates before notifying listeners so screenshot\n // payloads can be released from memory and serialized as references.\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n\n // Call all registered dump update listeners\n const dumpString = this.dumpDataString();\n for (const listener of this.dumpUpdateListeners) {\n try {\n listener(dumpString, executionDump);\n } catch (error) {\n console.error('Error in onDumpUpdate listener', error);\n }\n }\n },\n },\n });\n this.dump = this.resetDump();\n this.reportFileName =\n opts?.reportFileName ??\n // Keep deprecated testId behavior for generated report names until it is\n // fully removed from the public API.\n getReportFileName(opts?.testId || this.interface.interfaceType || 'web');\n\n this.reportGenerator = ReportGenerator.create(this.reportFileName!, {\n generateReport: this.opts.generateReport,\n persistExecutionDump: this.opts.persistExecutionDump,\n outputFormat: this.opts.outputFormat,\n autoPrintReportMsg: this.opts.autoPrintReportMsg,\n reuseExistingReport:\n this.opts.reportAttributes?.['data-group-id'] === this.reportFileName,\n });\n }\n\n async getActionSpace(): Promise<DeviceAction[]> {\n return this.fullActionSpace;\n }\n\n private static readonly CONTEXT_RETRY_MAX = 3;\n private static readonly CONTEXT_RETRY_DELAY_MS = 1500;\n\n /**\n * Override in subclasses to indicate which errors are transient and should\n * trigger an automatic retry when building the UI context.\n * Returns `false` by default (no retry).\n */\n protected isRetryableContextError(_error: unknown): boolean {\n return false;\n }\n\n async getUIContext(action?: ServiceAction): Promise<UIContext> {\n // Some non-web flows, such as Android, need an Agent instance before they\n // can call device methods via ADB, so defer missing modelFamily errors\n // until UI context is actually requested.\n this.assertModelFamilyForNonWebContext();\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 const maxRetries = Agent.CONTEXT_RETRY_MAX;\n for (let attempt = 0; ; attempt++) {\n try {\n return await commonContextParser(this.interface, {\n uploadServerUrl: this.modelConfigManager.getUploadTestServerUrl(),\n screenshotShrinkFactor: this.opts.screenshotShrinkFactor,\n });\n } catch (error) {\n if (attempt < maxRetries && this.isRetryableContextError(error)) {\n debug(\n `retryable context error (attempt ${attempt + 1}/${maxRetries}), retrying in ${Agent.CONTEXT_RETRY_DELAY_MS}ms: ${error}`,\n );\n await new Promise((resolve) =>\n setTimeout(resolve, Agent.CONTEXT_RETRY_DELAY_MS),\n );\n continue;\n }\n throw error;\n }\n }\n }\n\n async _snapshotContext(): Promise<UIContext> {\n return await this.getUIContext('locate');\n }\n\n /**\n * @deprecated Use {@link setAIActContext} instead.\n */\n async setAIActionContext(prompt: string) {\n await this.setAIActContext(prompt);\n }\n\n async setAIActContext(prompt: string) {\n if (this.aiActContext) {\n console.warn(\n 'aiActContext is already set, and it is called again, will override the previous setting',\n );\n }\n this.opts.aiActContext = prompt;\n this.opts.aiActionContext = prompt;\n }\n\n resetDump() {\n this.dump = new ReportActionDump({\n sdkVersion: getVersion(),\n groupName: this.opts.groupName!,\n groupDescription: this.opts.groupDescription,\n executions: [],\n modelBriefs: [],\n deviceType: this.interface.interfaceType,\n });\n this.executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump, runner?: TaskRunner) {\n const currentDump = this.dump;\n if (runner) {\n const existingIndex = this.executionDumpIndexByRunner.get(runner);\n if (existingIndex !== undefined) {\n currentDump.executions[existingIndex] = execution;\n return;\n }\n currentDump.executions.push(execution);\n this.executionDumpIndexByRunner.set(\n runner,\n currentDump.executions.length - 1,\n );\n return;\n }\n currentDump.executions.push(execution);\n }\n\n dumpDataString(opt?: { inlineScreenshots?: boolean }) {\n // update dump info\n this.dump.groupName = this.opts.groupName!;\n this.dump.groupDescription = this.opts.groupDescription;\n // In browser environment, use inline screenshots since file system is not available\n if (ifInBrowser || opt?.inlineScreenshots) {\n return this.dump.serializeWithInlineScreenshots();\n }\n return this.dump.serialize();\n }\n\n reportHTMLString(opt?: { inlineScreenshots?: boolean }) {\n // dumpDataString() handles browser environment with inline screenshots\n return reportHTMLContent(this.dumpDataString(opt));\n }\n\n private lastExecutionDump?: ExecutionDump;\n\n writeOutActionDumps(executionDump?: ExecutionDump) {\n const exec = executionDump || this.lastExecutionDump;\n if (exec) {\n this.lastExecutionDump = exec;\n this.reportGenerator.onExecutionUpdate(\n exec,\n this.getReportMeta(),\n this.opts.reportAttributes,\n );\n }\n this.reportFile = this.reportGenerator.getReportPath();\n }\n\n private getReportMeta(): ReportMeta {\n return {\n groupName: this.dump.groupName,\n groupDescription: this.dump.groupDescription,\n sdkVersion: this.dump.sdkVersion,\n modelBriefs: this.dump.modelBriefs,\n deviceType: this.dump.deviceType,\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 wrapActionInActionSpace<T extends DeviceAction>(\n name: string,\n ): (param: ActionParam<T>) => Promise<ActionReturn<T>> {\n return async (param: ActionParam<T>) => {\n return await this.callActionInActionSpace<ActionReturn<T>>(name, param);\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 defaultModel = this.resolveModelRuntime('default');\n const planningModel = this.resolveModelRuntime('planning');\n\n const { output } = await this.taskExecutor.runPlans(\n title,\n plans,\n planningModel,\n defaultModel,\n );\n return output;\n }\n\n async aiTap(\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { fileChooserAccept?: string | string[] },\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for tap');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n const fileChooserAccept = opt?.fileChooserAccept\n ? this.normalizeFileInput(opt.fileChooserAccept)\n : undefined;\n\n await withFileChooser(this.interface, fileChooserAccept, async () => {\n await this.callActionInActionSpace('Tap', {\n locate: detailedLocateParam,\n });\n });\n }\n\n async aiRightClick(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for right click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('RightClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiDoubleClick(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for double click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('DoubleClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiHover(locatePrompt: TUserPrompt, opt?: LocateOption): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for hover');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await 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 | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | 'append' },\n ): Promise<void>;\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 | number,\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { autoDismissKeyboard?: boolean } & {\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n }, // AndroidDeviceInputOpt &\n ): Promise<void>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string | number,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { value: string | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | 'append' }) // AndroidDeviceInputOpt &\n | undefined,\n optOrUndefined?: LocateOption, // AndroidDeviceInputOpt &\n ) {\n let value: string | number;\n let locatePrompt: TUserPrompt;\n let opt:\n | (LocateOption & { value: string | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | '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 | number;\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 | number;\n locatePrompt = locatePromptOrOpt as TUserPrompt;\n opt = {\n ...optOrUndefined,\n value,\n };\n }\n\n assert(\n typeof value === 'string' || typeof value === 'number',\n 'input value must be a string or number, 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 // Convert value to string to ensure consistency\n const stringValue = typeof value === 'number' ? String(value) : value;\n\n // backward compat: convert deprecated 'append' to 'typeOnly'\n const mode = opt?.mode === 'append' ? 'typeOnly' : opt?.mode;\n\n await this.callActionInActionSpace('Input', {\n ...(opt || {}),\n value: stringValue,\n locate: detailedLocateParam,\n mode,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { keyName: string },\n ): Promise<void>;\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<void>;\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 await 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<void>;\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<void>;\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 const isLocatePromptLike = (value: unknown): value is TUserPrompt => {\n if (\n typeof value === 'string' ||\n typeof value === 'undefined' ||\n value === null\n ) {\n return true;\n }\n\n return typeof value === 'object' && value !== null && 'prompt' in value;\n };\n\n // Check if using new signature (first param is locatePrompt, second is options)\n if (\n isLocatePromptLike(locatePromptOrScrollParam) &&\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null\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 if (opt) {\n const normalizedScrollType = normalizeScrollType(\n (opt as ScrollParam).scrollType as\n | ScrollParam['scrollType']\n | LegacyScrollType\n | undefined,\n );\n\n if (normalizedScrollType !== (opt as ScrollParam).scrollType) {\n (opt as ScrollParam) = {\n ...(opt || {}),\n scrollType: normalizedScrollType as ScrollParam['scrollType'],\n };\n }\n }\n\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n await this.callActionInActionSpace('Scroll', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiPinch(\n locatePrompt: TUserPrompt | undefined,\n opt: LocateOption & {\n direction: 'in' | 'out';\n distance?: number;\n duration?: number;\n },\n ): Promise<void> {\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n await this.callActionInActionSpace('Pinch', {\n ...opt,\n locate: detailedLocateParam,\n });\n }\n\n async aiLongPress(\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { duration?: number },\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for long press');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('LongPress', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiClearInput(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for clear input');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('ClearInput', {\n locate: detailedLocateParam,\n });\n }\n\n async aiAct(\n taskPrompt: TUserPrompt,\n opt?: AiActOptions,\n ): Promise<string | undefined> {\n const internalReportDisplay = (opt as AiActInternalOptions | undefined)\n ?._internalReportDisplay;\n const taskPromptText =\n typeof taskPrompt === 'string' ? taskPrompt : taskPrompt.prompt;\n const reportPrompt = internalReportDisplay?.prompt || taskPromptText;\n const fileChooserAccept = opt?.fileChooserAccept\n ? this.normalizeFileInput(opt.fileChooserAccept)\n : undefined;\n\n const abortSignal = opt?.abortSignal;\n if (abortSignal?.aborted) {\n throw new Error(\n `aiAct aborted: ${abortSignal.reason || 'signal already aborted'}`,\n );\n }\n\n const runAiAct = async () => {\n const planningModel = this.resolveModelRuntime('planning');\n const defaultModel = this.resolveModelRuntime('default');\n // Controls the aiAct planning mode, such as sub-goal prompts and locate result strategy.\n const deepThink = opt?.deepThink === true;\n\n const deepLocate = opt?.deepLocate;\n\n const noIndividualLocateModel = planningModel.config.slot === 'default';\n\n const includeLocateInPlanning = !deepThink && noIndividualLocateModel;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n deepThink,\n noIndividualLocateModel,\n });\n\n const cacheable = opt?.cacheable;\n const replanningCycleLimit =\n this.resolveReplanningCycleLimit(planningModel);\n const planCacheEnabled = planningModel.adapter.planning.cacheEnabled;\n const matchedCache =\n !planCacheEnabled || cacheable === false\n ? undefined\n : this.taskCache?.matchPlanCache(taskPrompt);\n let cachedYamlFailed = false;\n if (\n matchedCache?.cacheUsable &&\n this.taskCache?.isCacheResultUsed &&\n matchedCache.cacheContent?.yamlWorkflow?.trim()\n ) {\n const yaml = matchedCache.cacheContent.yamlWorkflow;\n try {\n // log into report file\n await this.taskExecutor.loadYamlFlowAsPlanning(\n taskPrompt,\n yaml,\n internalReportDisplay,\n );\n\n debug('matched cache, will call .runYaml to run the action');\n await this.runYaml(yaml);\n return;\n } catch (error) {\n cachedYamlFailed = true;\n warn(\n `cached aiAct plan failed, will replan and disable the stale cache: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n // If cache matched but is not executable, fall through to normal execution\n const imagesIncludeCount: number = deepThink ? 2 : 1;\n const { output: actionOutput } = await this.taskExecutor.action(\n taskPrompt,\n planningModel,\n defaultModel,\n includeLocateInPlanning,\n this.aiActContext,\n cacheable,\n replanningCycleLimit,\n imagesIncludeCount,\n deepThink,\n fileChooserAccept,\n deepLocate,\n abortSignal,\n internalReportDisplay,\n );\n\n // update cache\n if (this.taskCache && cacheable !== false) {\n const yamlFlow = cachedYamlFailed ? [] : actionOutput?.yamlFlow;\n\n if (!cachedYamlFailed && !yamlFlow?.length) {\n return actionOutput?.output;\n }\n\n const yamlFlowToCache = yamlFlow ?? [];\n const yamlContent: MidsceneYamlScript = {\n tasks: [\n {\n name: reportPrompt,\n flow: yamlFlowToCache,\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 return actionOutput?.output;\n };\n\n return await runAiAct();\n }\n\n async runMarkdown(\n markdownPath: string,\n opt?: AiActOptions,\n ): Promise<string | undefined> {\n const markdown = await readFile(markdownPath, 'utf-8');\n const { prompt } = await markdownToAiActPrompt(markdown, markdownPath);\n return this.aiAct(prompt, {\n ...opt,\n _internalReportDisplay: {\n type: 'Markdown',\n prompt: basename(markdownPath),\n },\n } as AiActOptions);\n }\n\n /**\n * @deprecated Use {@link Agent.aiAct} instead.\n */\n async aiAction(taskPrompt: TUserPrompt, opt?: AiActOptions) {\n return this.aiAct(taskPrompt, opt);\n }\n\n async aiQuery<ReturnType = any>(\n demand: ServiceExtractParam,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<ReturnType> {\n const modelRuntime = this.resolveModelRuntime('insight');\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Query',\n demand,\n modelRuntime,\n opt,\n );\n return output as ReturnType;\n }\n\n async aiBoolean(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<boolean> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Boolean',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as boolean;\n }\n\n async aiNumber(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<number> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Number',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as number;\n }\n\n async aiString(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<string> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'String',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as string;\n }\n\n async aiAsk(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<string> {\n return this.aiString(prompt, opt);\n }\n\n async describeElementAtPoint(\n center: [number, number],\n opt?: DescribeElementAtPointOptions,\n ): Promise<AgentDescribeElementAtPointResult> {\n const { verifyPrompt = true, retryLimit = 3 } = opt || {};\n const screenshotContext = opt?.screenshotBase64\n ? await createScreenshotBoundUIContext(opt.screenshotBase64, opt)\n : undefined;\n const targetCenter = screenshotContext\n ? mapPointToScreenshotSpace(center, screenshotContext.shotSize, opt || {})\n : center;\n\n let success = false;\n let retryCount = 0;\n let resultPrompt = '';\n let deepLocate = opt?.deepLocate || false;\n let verifyResult: LocateValidatorResult | undefined;\n\n while (!success && retryCount < retryLimit) {\n if (retryCount >= 2) {\n deepLocate = true;\n }\n debug(\n 'aiDescribe',\n targetCenter,\n 'verifyPrompt',\n verifyPrompt,\n 'retryCount',\n retryCount,\n 'deepLocate',\n deepLocate,\n );\n // use same intent as aiLocate\n const modelRuntime = this.resolveModelRuntime('insight');\n const describeOpt = screenshotContext\n ? { deepLocate, context: screenshotContext }\n : { deepLocate };\n\n const text = await this.service.describe(\n targetCenter,\n modelRuntime,\n describeOpt,\n );\n debug('aiDescribe text', text);\n assert(\n text.description,\n `failed to describe element at [${targetCenter}]`,\n );\n resultPrompt = text.description;\n\n if (!verifyPrompt) {\n opt?.onProgress?.({ prompt: resultPrompt, deepLocate });\n success = true;\n break;\n }\n\n // Don't pass deepLocate to verification locate — the description was generated\n // from a cropped view (deepLocate describe), but verification should use regular\n // locate on the full screenshot to confirm the description works universally.\n // Passing deepLocate here would add another first-pass locate and search-area\n // crop around an already element-level description, which is not the intent of\n // verification.\n verifyResult = await this.verifyLocator(\n resultPrompt,\n screenshotContext ? { uiContext: screenshotContext } : undefined,\n targetCenter,\n opt,\n );\n opt?.onProgress?.({ prompt: resultPrompt, deepLocate, verifyResult });\n if (verifyResult.pass) {\n success = true;\n } else {\n retryCount++;\n }\n }\n\n return {\n prompt: resultPrompt,\n deepLocate,\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 includedInRect: included,\n };\n debug('aiDescribe verifyResult', verifyResult);\n return verifyResult;\n }\n\n /**\n * Locate an element and return both its center point and an approximate rect.\n *\n * - In most locate flows, `rect` represents the matched element boundary.\n * - Some models only support point grounding instead of boundary grounding.\n * In those cases (for example, AutoGLM), `rect` falls back to a small 8x8\n * box centered on the located point.\n *\n * Because `rect` may vary with the underlying model capability, avoid relying\n * on it too heavily for strict boundary semantics. If you need a stable click\n * target, prefer `center`.\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 defaultModel = this.resolveModelRuntime('default');\n const planningModel = this.resolveModelRuntime('planning');\n\n const { output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(locateParam)),\n plans,\n planningModel,\n defaultModel,\n opt?.uiContext ? { uiContext: opt.uiContext } : undefined,\n );\n\n const { element } = output;\n\n return {\n rect: element?.rect,\n center: element?.center,\n dpr: element?.dpr,\n } as Pick<LocateResultElement, 'rect' | 'center'>;\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AgentAssertOpt & ServiceExtractOption,\n ) {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const serviceOpt: ServiceExtractOption = {\n domIncluded: opt?.domIncluded ?? defaultServiceExtractOption.domIncluded,\n screenshotIncluded:\n opt?.screenshotIncluded ??\n defaultServiceExtractOption.screenshotIncluded,\n };\n\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n const assertionText =\n typeof assertion === 'string' ? assertion : assertion.prompt;\n\n try {\n const { output, thought } =\n await this.taskExecutor.createTypeQueryExecution<boolean>(\n 'Assert',\n textPrompt,\n modelRuntime,\n serviceOpt,\n multimodalPrompt,\n );\n\n const pass = Boolean(output);\n const message = pass\n ? undefined\n : `Assertion failed: ${msg || assertionText}\\nReason: ${thought || '(no_reason)'}`;\n\n if (opt?.keepRawResponse) {\n return {\n pass,\n thought,\n message,\n };\n }\n\n if (!pass) {\n throw new Error(message);\n }\n } catch (error) {\n if (error instanceof TaskExecutionError) {\n const errorTask = error.errorTask;\n const thought = errorTask?.thought;\n const rawError = errorTask?.error;\n const rawMessage =\n errorTask?.errorMessage ||\n (rawError instanceof Error\n ? rawError.message\n : rawError\n ? String(rawError)\n : undefined);\n const reason = thought || rawMessage || '(no_reason)';\n const message = `Assertion failed: ${msg || assertionText}\\nReason: ${reason}`;\n\n if (opt?.keepRawResponse) {\n return {\n pass: false,\n thought,\n message,\n };\n }\n\n throw new Error(message, {\n cause: rawError ?? error,\n });\n }\n\n throw error;\n }\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelRuntime = this.resolveModelRuntime('insight');\n await this.taskExecutor.waitFor(\n assertion,\n {\n ...opt,\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n },\n modelRuntime,\n );\n }\n\n async ai(...args: Parameters<typeof this.aiAct>) {\n return this.aiAct(...args);\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 /**\n * Add a dump update listener\n * @param listener Listener function\n * @returns A remove function that can be called to remove this listener\n */\n addDumpUpdateListener(\n listener: (dump: string, executionDump?: ExecutionDump) => void,\n ): () => void {\n this.dumpUpdateListeners.push(listener);\n\n // Return remove function\n return () => {\n this.removeDumpUpdateListener(listener);\n };\n }\n\n /**\n * Remove a dump update listener\n * @param listener The listener function to remove\n */\n removeDumpUpdateListener(\n listener: (dump: string, executionDump?: ExecutionDump) => void,\n ): void {\n const index = this.dumpUpdateListeners.indexOf(listener);\n if (index > -1) {\n this.dumpUpdateListeners.splice(index, 1);\n }\n }\n\n /**\n * Clear all dump update listeners\n */\n clearDumpUpdateListeners(): void {\n this.dumpUpdateListeners = [];\n }\n\n private notifyDumpUpdateListeners(executionDump?: ExecutionDump) {\n const dumpString = this.dumpDataString();\n for (const listener of this.dumpUpdateListeners) {\n try {\n listener(dumpString, executionDump);\n } catch (error) {\n console.error('Error in onDumpUpdate listener', error);\n }\n }\n }\n\n async destroy() {\n // Early return if already destroyed\n if (this.destroyed) {\n return;\n }\n\n this.destroyed = true;\n let interfaceDestroyError: unknown;\n try {\n await this.interface.destroy?.();\n } catch (error) {\n interfaceDestroyError = error;\n }\n\n // Wait for all queued write operations to complete\n await this.reportGenerator.flush();\n\n const finalPath = await this.reportGenerator.finalize();\n this.reportFile = finalPath;\n\n this.resetDump(); // reset dump to release memory\n\n if (interfaceDestroyError) {\n throw interfaceDestroyError;\n }\n }\n\n async recordToReport(\n title?: string,\n opt?: {\n content?: string;\n screenshotBase64?: string;\n },\n ) {\n // 1. screenshot\n const base64 =\n opt?.screenshotBase64 ?? (await this.interface.screenshotBase64());\n const now = Date.now();\n const screenshot = ScreenshotItem.create(base64, now);\n // 2. build recorder\n const recorder: ExecutionRecorderItem[] = [\n {\n type: 'screenshot',\n ts: now,\n screenshot,\n },\n ];\n // 3. build ExecutionTaskLog\n const task: ExecutionTaskLog = {\n taskId: uuid(),\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 = new ExecutionDump({\n id: uuid(),\n logTime: now,\n name: `Log - ${title || 'untitled'}`,\n description: opt?.content || '',\n tasks: [task],\n });\n // 5. append to execution dump\n this.appendExecutionDump(executionDump);\n\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n\n // Call all registered dump update listeners\n this.notifyDumpUpdateListeners(executionDump);\n }\n\n async recordErrorToReport(\n title: string,\n opt: {\n error: Error;\n content?: string;\n screenshotBase64?: string;\n },\n ) {\n const now = Date.now();\n const recorder: ExecutionRecorderItem[] = [];\n const base64 =\n opt.screenshotBase64 ?? (await this.interface.screenshotBase64());\n if (base64) {\n recorder.push({\n type: 'screenshot',\n ts: now,\n screenshot: ScreenshotItem.create(base64, now),\n });\n }\n\n const task: ExecutionTaskLog = {\n taskId: uuid(),\n type: 'Log',\n subType: 'Error',\n status: 'failed',\n recorder,\n timing: {\n start: now,\n end: now,\n cost: 0,\n },\n param: {\n content: opt.content || '',\n },\n error: opt.error,\n errorMessage: opt.error.message,\n errorStack: opt.error.stack,\n executor: async () => {},\n };\n\n const executionDump = new ExecutionDump({\n id: uuid(),\n logTime: now,\n name: title,\n description: opt.content || opt.error.message,\n tasks: [task],\n });\n\n this.appendExecutionDump(executionDump);\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n this.notifyDumpUpdateListeners(executionDump);\n }\n\n /**\n * @deprecated Use {@link Agent.recordToReport} instead.\n */\n async logScreenshot(\n title?: string,\n opt?: {\n content: string;\n },\n ) {\n await this.recordToReport(title, opt);\n }\n\n _unstableLogContent() {\n const { groupName, groupDescription, executions } = this.dump;\n return {\n groupName,\n groupDescription,\n executions: executions || [],\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 cacheDir?: string;\n } | null {\n validateAgentCacheInput(opts.cache);\n\n // Use the unified utils function to process cache configuration\n const cacheConfig = processCacheConfig(\n opts.cache,\n opts.cacheId || 'default',\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 strategyValue = cacheConfig.strategy ?? 'read-write';\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 cacheDir: cacheConfig.cacheDir?.trim(),\n };\n }\n\n return null;\n }\n\n private normalizeFilePaths(files: string[]): string[] {\n if (ifInBrowser) {\n throw new Error('File chooser is not supported in browser environment');\n }\n\n return files.map((file) => {\n const absolutePath = resolve(file);\n if (!existsSync(absolutePath)) {\n throw new Error(\n `File not found: ${file}. Resolved to: ${absolutePath}. Current working directory: ${process.cwd()}`,\n );\n }\n return absolutePath;\n });\n }\n\n private normalizeFileInput(files: string | string[]): string[] {\n const filesArray = Array.isArray(files) ? files : [files];\n return this.normalizeFilePaths(filesArray);\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","warn","distanceOfTwoPoints","p1","p2","x1","y1","x2","y2","Math","includedInRect","point","rect","x","y","left","top","width","height","assertPositiveSize","size","label","assert","Number","mapPointToScreenshotSpace","center","screenshotSize","opt","coordinateSpace","defaultServiceExtractOption","legacyScrollTypeMap","normalizeScrollType","scrollType","Agent","callback","planningModel","globalConfigManager","MIDSCENE_REPLANNING_CYCLE_LIMIT","intent","getModelRuntime","_error","action","maxRetries","attempt","commonContextParser","error","Promise","resolve","setTimeout","prompt","console","ReportActionDump","getVersion","WeakMap","execution","runner","currentDump","existingIndex","undefined","ifInBrowser","reportHTMLContent","executionDump","exec","task","param","paramStr","tip","typeStr","name","type","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","defaultModel","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","fileChooserAccept","withFileChooser","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","value","optWithValue","stringValue","String","mode","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","isLocatePromptLike","normalizedScrollType","taskPrompt","internalReportDisplay","taskPromptText","reportPrompt","abortSignal","Error","runAiAct","deepThink","deepLocate","noIndividualLocateModel","includeLocateInPlanning","cacheable","replanningCycleLimit","planCacheEnabled","matchedCache","cachedYamlFailed","yaml","imagesIncludeCount","actionOutput","yamlFlow","yamlFlowToCache","yamlContent","yamlFlowStr","markdownPath","markdown","readFile","markdownToAiActPrompt","basename","demand","modelRuntime","textPrompt","multimodalPrompt","parsePrompt","verifyPrompt","retryLimit","screenshotContext","createScreenshotBoundUIContext","targetCenter","success","retryCount","resultPrompt","verifyResult","describeOpt","text","locateOpt","expectCenter","verifyLocateOption","verifyCenter","verifyRect","distance","included","pass","locateParam","locatePlan","locatePlanForLocate","element","assertion","msg","serviceOpt","assertionText","thought","message","TaskExecutionError","errorTask","rawError","rawMessage","reason","args","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","listener","index","dumpString","interfaceDestroyError","finalPath","base64","now","Date","screenshot","ScreenshotItem","recorder","uuid","ExecutionDump","groupName","groupDescription","executions","context","opts","validateAgentCacheInput","cacheConfig","processCacheConfig","id","strategyValue","isReadOnly","isWriteOnly","files","file","absolutePath","existsSync","process","filesArray","Array","options","interfaceInstance","Object","assertReportGenerationOptions","resolvedAiActContext","hasCustomConfig","ModelConfigManager","globalModelConfigManager","Service","cacheConfigObj","TaskCache","baseActionSpace","defineActionSleep","TaskExecutor","getReportFileName","ReportGenerator","createAgent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,OAAOD,SAAS,SAAS;IAAE,SAAS;AAAK;AAE/C,MAAME,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,SAASC,mBACPC,IAAsB,EACtBC,KAAa;IAEbC,OACEF,QACEG,OAAO,QAAQ,CAACH,KAAK,KAAK,KAC1BG,OAAO,QAAQ,CAACH,KAAK,MAAM,KAC3BA,KAAK,KAAK,GAAG,KACbA,KAAK,MAAM,GAAG,GAChB,GAAGC,MAAM,uCAAuC,CAAC;AAErD;AAEA,MAAMG,4BAA4B,CAChCC,QACAC,gBACAC;IAEA,MAAMC,kBAAkBD,IAAI,eAAe,IAAI;IAC/C,IAAIC,AAAoB,iBAApBA,iBACF,OAAOH;IAGTN,mBACEQ,IAAI,WAAW,EACf;IA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B,OAAO;wBACdK,QAAQ,KAAK,CAAC,kCAAkCL;oBAClD;gBAEJ;YACF;QACF;QACA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS;QAC1B,IAAI,CAAC,cAAc,GACjB+I,MAAM,kBAGN6B,kBAAkB7B,MAAM,UAAU,IAAI,CAAC,SAAS,CAAC,aAAa,IAAI;QAEpE,IAAI,CAAC,eAAe,GAAG8B,gBAAgB,MAAM,CAAC,IAAI,CAAC,cAAc,EAAG;YAClE,gBAAgB,IAAI,CAAC,IAAI,CAAC,cAAc;YACxC,sBAAsB,IAAI,CAAC,IAAI,CAAC,oBAAoB;YACpD,cAAc,IAAI,CAAC,IAAI,CAAC,YAAY;YACpC,oBAAoB,IAAI,CAAC,IAAI,CAAC,kBAAkB;YAChD,qBACE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,gBAAgB,KAAK,IAAI,CAAC,cAAc;QACzE;IACF;AA2yCF;AAryCE,iBA9NWzL,OA8Na,qBAAoB;AAC5C,iBA/NWA,OA+Na,0BAAyB;AAsyC5C,MAAM0L,cAAc,CACzBf,mBACAhB,OAEO,IAAI3J,MAAM2K,mBAAmBhB"}
|
|
1
|
+
{"version":3,"file":"agent/agent.mjs","sources":["../../../src/agent/agent.ts"],"sourcesContent":["import { type ModelRuntime, getModelRuntime } from '@/ai-model/models';\nimport yaml from 'js-yaml';\nimport type { TUserPrompt } from '../ai-model/index';\nimport { ScreenshotItem } from '../screenshot-item';\nimport Service from '../service/index';\n// Import types and values directly from their source files to avoid circular dependency\n// DO NOT import from '../index' as it creates a circular dependency:\n// index.ts -> agent/index.ts -> agent/agent.ts -> index.ts\nimport {\n type ActionParam,\n type ActionReturn,\n type AgentAssertOpt,\n type AgentDescribeElementAtPointResult,\n type AgentOpt,\n type AgentWaitForOpt,\n type DeepThinkOption,\n type DeviceAction,\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskLog,\n type LocateOption,\n type LocateResultElement,\n type LocateValidatorResult,\n type LocatorValidatorOption,\n type OnTaskStartTip,\n type PlanningAction,\n type RecordToReportOptions,\n type RecordToReportScreenshot,\n type Rect,\n ReportActionDump,\n type ReportMeta,\n type ScrollParam,\n type ServiceAction,\n type ServiceExtractOption,\n type ServiceExtractParam,\n type Size,\n type TestStatus,\n type UIContext,\n} from '../types';\nimport type { MidsceneYamlScript } from '../yaml';\n\nimport type { IReportGenerator } from '@/report-generator';\nimport {\n ReportGenerator,\n assertReportGenerationOptions,\n} from '@/report-generator';\nimport { getVersion, processCacheConfig, reportHTMLContent } from '@/utils';\nimport {\n ScriptPlayer,\n buildDetailedLocateParam,\n parseYamlScript,\n} from '../yaml/index';\n\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport type { AbstractInterface } from '@/device';\nimport type { TaskRunner } from '@/task-runner';\nimport {\n type IModelConfig,\n MIDSCENE_REPLANNING_CYCLE_LIMIT,\n ModelConfigManager,\n type TIntent,\n globalConfigManager,\n globalModelConfigManager,\n} from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert, ifInBrowser, uuid } from '@midscene/shared/utils';\nimport { defineActionSleep } from '../device';\nimport { validateAgentCacheInput } from './cache-config';\nimport { normalizeRecordToReportScreenshot } from './record-to-report';\nimport { markdownToAiActPrompt } from './run-markdown';\nimport { TaskCache } from './task-cache';\nimport {\n TaskExecutionError,\n TaskExecutor,\n locatePlanForLocate,\n withFileChooser,\n} from './tasks';\nimport {\n type TaskTitleType,\n locateParamStr,\n paramStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport {\n commonContextParser,\n createScreenshotBoundUIContext,\n getReportFileName,\n normalizeScrollType,\n parsePrompt,\n} from './utils';\n\nexport type DescribeElementCoordinateSpace = 'screenshot' | 'logical';\n\nexport type DescribeElementAtPointOptions = {\n verifyPrompt?: boolean;\n retryLimit?: number;\n deepLocate?: boolean;\n screenshotBase64?: string;\n screenshotSize?: Size;\n coordinateSpace?: DescribeElementCoordinateSpace;\n logicalSize?: Size;\n onProgress?: (progress: {\n prompt?: string;\n deepLocate?: boolean;\n verifyResult?: LocateValidatorResult;\n }) => void;\n} & LocatorValidatorOption;\n\nconst debug = getDebug('agent');\nconst warn = getDebug('agent', { console: true });\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\nfunction assertPositiveSize(\n size: Size | undefined,\n label: string,\n): asserts size is Size {\n assert(\n size &&\n Number.isFinite(size.width) &&\n Number.isFinite(size.height) &&\n size.width > 0 &&\n size.height > 0,\n `${label} must include positive width and height`,\n );\n}\n\nconst mapPointToScreenshotSpace = (\n center: [number, number],\n screenshotSize: Size,\n opt: DescribeElementAtPointOptions,\n): [number, number] => {\n const coordinateSpace = opt.coordinateSpace || 'screenshot';\n if (coordinateSpace === 'screenshot') {\n return center;\n }\n\n assertPositiveSize(\n opt.logicalSize,\n 'logicalSize is required when coordinateSpace is logical',\n );\n return [\n (center[0] * screenshotSize.width) / opt.logicalSize.width,\n (center[1] * screenshotSize.height) / opt.logicalSize.height,\n ];\n};\n\nconst defaultServiceExtractOption: ServiceExtractOption = {\n domIncluded: false,\n screenshotIncluded: true,\n};\n\nexport type AiActOptions = {\n cacheable?: boolean;\n fileChooserAccept?: string | string[];\n deepThink?: DeepThinkOption;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n};\n\ntype AiActInternalOptions = AiActOptions & {\n _internalReportDisplay?: {\n type?: TaskTitleType;\n prompt?: string;\n };\n};\n\nexport class Agent<\n InterfaceType extends AbstractInterface = AbstractInterface,\n> {\n interface: InterfaceType;\n\n service: Service;\n\n dump: ReportActionDump;\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 private dumpUpdateListeners: Array<\n (dump: string, executionDump?: ExecutionDump) => void\n > = [];\n\n get onDumpUpdate():\n | ((dump: string, executionDump?: ExecutionDump) => void)\n | undefined {\n return this.dumpUpdateListeners[0];\n }\n\n set onDumpUpdate(callback:\n | ((dump: string, executionDump?: ExecutionDump) => void)\n | undefined) {\n // Clear existing listeners\n this.dumpUpdateListeners = [];\n // Add callback to array if provided\n if (callback) {\n this.dumpUpdateListeners.push(callback);\n }\n }\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 private get aiActContext(): string | undefined {\n return this.opts.aiActContext ?? this.opts.aiActionContext;\n }\n\n private executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n private fullActionSpace: DeviceAction[];\n\n private reportGenerator: IReportGenerator;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n /**\n * Fails fast for non-web interfaces when the model family is missing.\n *\n * Early Midscene web usage allowed running without `modelFamily` and falling\n * back to a default bbox parser. Non-web users do not have that compatibility\n * path, so this check helps surface configuration problems before spending a\n * model call.\n *\n * Web flows validate missing locate model family at workflow boundaries:\n * `Service.locate` throws when aiTap/aiType fallback to the default model for\n * direct locate, and generic planning throws when aiAct asks a planning model\n * to return inline locate coordinates. Those checks are intentionally placed\n * where Midscene knows which model role should provide coordinate parsing.\n */\n private assertModelFamilyForNonWebContext() {\n if (\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 }\n }\n\n private resolveReplanningCycleLimit(planningModel: ModelRuntime): number {\n return (\n this.opts.replanningCycleLimit ??\n globalConfigManager.getEnvConfigValueAsNumber(\n MIDSCENE_REPLANNING_CYCLE_LIMIT,\n ) ??\n planningModel.adapter.planning.defaultReplanningCycleLimit\n );\n }\n\n private resolveModelRuntime(intent: TIntent): ModelRuntime {\n return getModelRuntime(this.modelConfigManager.getModelConfig(intent));\n }\n\n constructor(interfaceInstance: InterfaceType, opts?: AgentOpt) {\n this.interface = interfaceInstance;\n\n this.opts = Object.assign(\n {\n generateReport: true,\n persistExecutionDump: false,\n autoPrintReportMsg: true,\n groupName: 'Midscene Report',\n groupDescription: '',\n },\n opts || {},\n );\n assertReportGenerationOptions(this.opts);\n\n const resolvedAiActContext =\n this.opts.aiActContext ?? this.opts.aiActionContext;\n if (resolvedAiActContext !== undefined) {\n this.opts.aiActContext = resolvedAiActContext;\n this.opts.aiActionContext ??= resolvedAiActContext;\n }\n\n if (\n opts?.modelConfig &&\n (typeof opts?.modelConfig !== 'object' || Array.isArray(opts.modelConfig))\n ) {\n throw new Error(\n `opts.modelConfig must be a plain object map of env keys to values, but got ${typeof opts?.modelConfig}`,\n );\n }\n // Create ModelConfigManager if modelConfig or createOpenAIClient is provided\n // Otherwise, use the global config manager\n const hasCustomConfig = opts?.modelConfig || opts?.createOpenAIClient;\n this.modelConfigManager = hasCustomConfig\n ? new ModelConfigManager(opts?.modelConfig, opts?.createOpenAIClient)\n : globalModelConfigManager;\n\n this.onTaskStartTip = this.opts.onTaskStartTip;\n\n this.service = new Service(async () => {\n return this.getUIContext();\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 cacheDir: cacheConfigObj.cacheDir,\n },\n );\n }\n\n const baseActionSpace = this.interface.actionSpace();\n this.fullActionSpace = [...baseActionSpace, defineActionSleep()];\n\n this.taskExecutor = new TaskExecutor(this.interface, this.service, {\n taskCache: this.taskCache,\n onTaskStart: this.callbackOnTaskStartTip.bind(this),\n replanningCycleLimit: this.opts.replanningCycleLimit,\n waitAfterAction: this.opts.waitAfterAction,\n useDeviceTime: this.opts.useDeviceTime,\n actionSpace: this.fullActionSpace,\n hooks: {\n onTaskUpdate: async (runner) => {\n const executionDump = runner.dump();\n this.appendExecutionDump(executionDump, runner);\n\n // Persist report updates before notifying listeners so screenshot\n // payloads can be released from memory and serialized as references.\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n\n // Call all registered dump update listeners\n const dumpString = this.dumpDataString();\n for (const listener of this.dumpUpdateListeners) {\n try {\n listener(dumpString, executionDump);\n } catch (error) {\n console.error('Error in onDumpUpdate listener', error);\n }\n }\n },\n },\n });\n this.dump = this.resetDump();\n this.reportFileName =\n opts?.reportFileName ??\n // Keep deprecated testId behavior for generated report names until it is\n // fully removed from the public API.\n getReportFileName(opts?.testId || this.interface.interfaceType || 'web');\n\n this.reportGenerator = ReportGenerator.create(this.reportFileName!, {\n generateReport: this.opts.generateReport,\n persistExecutionDump: this.opts.persistExecutionDump,\n outputFormat: this.opts.outputFormat,\n autoPrintReportMsg: this.opts.autoPrintReportMsg,\n reuseExistingReport:\n this.opts.reportAttributes?.['data-group-id'] === this.reportFileName,\n });\n }\n\n async getActionSpace(): Promise<DeviceAction[]> {\n return this.fullActionSpace;\n }\n\n private static readonly CONTEXT_RETRY_MAX = 3;\n private static readonly CONTEXT_RETRY_DELAY_MS = 1500;\n\n /**\n * Override in subclasses to indicate which errors are transient and should\n * trigger an automatic retry when building the UI context.\n * Returns `false` by default (no retry).\n */\n protected isRetryableContextError(_error: unknown): boolean {\n return false;\n }\n\n async getUIContext(action?: ServiceAction): Promise<UIContext> {\n // Some non-web flows, such as Android, need an Agent instance before they\n // can call device methods via ADB, so defer missing modelFamily errors\n // until UI context is actually requested.\n this.assertModelFamilyForNonWebContext();\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 const maxRetries = Agent.CONTEXT_RETRY_MAX;\n for (let attempt = 0; ; attempt++) {\n try {\n return await commonContextParser(this.interface, {\n uploadServerUrl: this.modelConfigManager.getUploadTestServerUrl(),\n screenshotShrinkFactor: this.opts.screenshotShrinkFactor,\n });\n } catch (error) {\n if (attempt < maxRetries && this.isRetryableContextError(error)) {\n debug(\n `retryable context error (attempt ${attempt + 1}/${maxRetries}), retrying in ${Agent.CONTEXT_RETRY_DELAY_MS}ms: ${error}`,\n );\n await new Promise((resolve) =>\n setTimeout(resolve, Agent.CONTEXT_RETRY_DELAY_MS),\n );\n continue;\n }\n throw error;\n }\n }\n }\n\n async _snapshotContext(): Promise<UIContext> {\n return await this.getUIContext('locate');\n }\n\n /**\n * @deprecated Use {@link setAIActContext} instead.\n */\n async setAIActionContext(prompt: string) {\n await this.setAIActContext(prompt);\n }\n\n async setAIActContext(prompt: string) {\n if (this.aiActContext) {\n console.warn(\n 'aiActContext is already set, and it is called again, will override the previous setting',\n );\n }\n this.opts.aiActContext = prompt;\n this.opts.aiActionContext = prompt;\n }\n\n resetDump() {\n this.dump = new ReportActionDump({\n sdkVersion: getVersion(),\n groupName: this.opts.groupName!,\n groupDescription: this.opts.groupDescription,\n executions: [],\n modelBriefs: [],\n deviceType: this.interface.interfaceType,\n });\n this.executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n return this.dump;\n }\n\n appendExecutionDump(execution: ExecutionDump, runner?: TaskRunner) {\n const currentDump = this.dump;\n if (runner) {\n const existingIndex = this.executionDumpIndexByRunner.get(runner);\n if (existingIndex !== undefined) {\n currentDump.executions[existingIndex] = execution;\n return;\n }\n currentDump.executions.push(execution);\n this.executionDumpIndexByRunner.set(\n runner,\n currentDump.executions.length - 1,\n );\n return;\n }\n currentDump.executions.push(execution);\n }\n\n dumpDataString(opt?: { inlineScreenshots?: boolean }) {\n // update dump info\n this.dump.groupName = this.opts.groupName!;\n this.dump.groupDescription = this.opts.groupDescription;\n // In browser environment, use inline screenshots since file system is not available\n if (ifInBrowser || opt?.inlineScreenshots) {\n return this.dump.serializeWithInlineScreenshots();\n }\n return this.dump.serialize();\n }\n\n reportHTMLString(opt?: { inlineScreenshots?: boolean }) {\n // dumpDataString() handles browser environment with inline screenshots\n return reportHTMLContent(this.dumpDataString(opt));\n }\n\n private lastExecutionDump?: ExecutionDump;\n\n writeOutActionDumps(executionDump?: ExecutionDump) {\n const exec = executionDump || this.lastExecutionDump;\n if (exec) {\n this.lastExecutionDump = exec;\n this.reportGenerator.onExecutionUpdate(\n exec,\n this.getReportMeta(),\n this.opts.reportAttributes,\n );\n }\n this.reportFile = this.reportGenerator.getReportPath();\n }\n\n private getReportMeta(): ReportMeta {\n return {\n groupName: this.dump.groupName,\n groupDescription: this.dump.groupDescription,\n sdkVersion: this.dump.sdkVersion,\n modelBriefs: this.dump.modelBriefs,\n deviceType: this.dump.deviceType,\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 wrapActionInActionSpace<T extends DeviceAction>(\n name: string,\n ): (param: ActionParam<T>) => Promise<ActionReturn<T>> {\n return async (param: ActionParam<T>) => {\n return await this.callActionInActionSpace<ActionReturn<T>>(name, param);\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 defaultModel = this.resolveModelRuntime('default');\n const planningModel = this.resolveModelRuntime('planning');\n\n const { output } = await this.taskExecutor.runPlans(\n title,\n plans,\n planningModel,\n defaultModel,\n );\n return output;\n }\n\n async aiTap(\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { fileChooserAccept?: string | string[] },\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for tap');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n const fileChooserAccept = opt?.fileChooserAccept\n ? this.normalizeFileInput(opt.fileChooserAccept)\n : undefined;\n\n await withFileChooser(this.interface, fileChooserAccept, async () => {\n await this.callActionInActionSpace('Tap', {\n locate: detailedLocateParam,\n });\n });\n }\n\n async aiRightClick(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for right click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('RightClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiDoubleClick(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for double click');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('DoubleClick', {\n locate: detailedLocateParam,\n });\n }\n\n async aiHover(locatePrompt: TUserPrompt, opt?: LocateOption): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for hover');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await 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 | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | 'append' },\n ): Promise<void>;\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 | number,\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { autoDismissKeyboard?: boolean } & {\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n }, // AndroidDeviceInputOpt &\n ): Promise<void>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string | number,\n locatePromptOrOpt:\n | TUserPrompt\n | (LocateOption & { value: string | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | 'append' }) // AndroidDeviceInputOpt &\n | undefined,\n optOrUndefined?: LocateOption, // AndroidDeviceInputOpt &\n ) {\n let value: string | number;\n let locatePrompt: TUserPrompt;\n let opt:\n | (LocateOption & { value: string | number } & {\n autoDismissKeyboard?: boolean;\n } & { mode?: 'replace' | 'clear' | 'typeOnly' | '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 | number;\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 | number;\n locatePrompt = locatePromptOrOpt as TUserPrompt;\n opt = {\n ...optOrUndefined,\n value,\n };\n }\n\n assert(\n typeof value === 'string' || typeof value === 'number',\n 'input value must be a string or number, 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 // Convert value to string to ensure consistency\n const stringValue = typeof value === 'number' ? String(value) : value;\n\n // backward compat: convert deprecated 'append' to 'typeOnly'\n const mode = opt?.mode === 'append' ? 'typeOnly' : opt?.mode;\n\n await this.callActionInActionSpace('Input', {\n ...(opt || {}),\n value: stringValue,\n locate: detailedLocateParam,\n mode,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt,\n opt: LocateOption & { keyName: string },\n ): Promise<void>;\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<void>;\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 await 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<void>;\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<void>;\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 const isLocatePromptLike = (value: unknown): value is TUserPrompt => {\n if (\n typeof value === 'string' ||\n typeof value === 'undefined' ||\n value === null\n ) {\n return true;\n }\n\n return typeof value === 'object' && value !== null && 'prompt' in value;\n };\n\n // Check if using new signature (first param is locatePrompt, second is options)\n if (\n isLocatePromptLike(locatePromptOrScrollParam) &&\n typeof locatePromptOrOpt === 'object' &&\n locatePromptOrOpt !== null\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 if (opt) {\n const normalizedScrollType = normalizeScrollType(\n (opt as ScrollParam).scrollType,\n );\n\n if (normalizedScrollType !== (opt as ScrollParam).scrollType) {\n (opt as ScrollParam) = {\n ...(opt || {}),\n scrollType: normalizedScrollType as ScrollParam['scrollType'],\n };\n }\n }\n\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n await this.callActionInActionSpace('Scroll', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiPinch(\n locatePrompt: TUserPrompt | undefined,\n opt: LocateOption & {\n direction: 'in' | 'out';\n distance?: number;\n duration?: number;\n },\n ): Promise<void> {\n const detailedLocateParam = buildDetailedLocateParam(\n locatePrompt || '',\n opt,\n );\n\n await this.callActionInActionSpace('Pinch', {\n ...opt,\n locate: detailedLocateParam,\n });\n }\n\n async aiLongPress(\n locatePrompt: TUserPrompt,\n opt?: LocateOption & { duration?: number },\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for long press');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('LongPress', {\n ...(opt || {}),\n locate: detailedLocateParam,\n });\n }\n\n async aiClearInput(\n locatePrompt: TUserPrompt,\n opt?: LocateOption,\n ): Promise<void> {\n assert(locatePrompt, 'missing locate prompt for clear input');\n\n const detailedLocateParam = buildDetailedLocateParam(locatePrompt, opt);\n\n await this.callActionInActionSpace('ClearInput', {\n locate: detailedLocateParam,\n });\n }\n\n async aiAct(\n taskPrompt: TUserPrompt,\n opt?: AiActOptions,\n ): Promise<string | undefined> {\n const internalReportDisplay = (opt as AiActInternalOptions | undefined)\n ?._internalReportDisplay;\n const taskPromptText =\n typeof taskPrompt === 'string' ? taskPrompt : taskPrompt.prompt;\n const reportPrompt = internalReportDisplay?.prompt || taskPromptText;\n const fileChooserAccept = opt?.fileChooserAccept\n ? this.normalizeFileInput(opt.fileChooserAccept)\n : undefined;\n\n const abortSignal = opt?.abortSignal;\n if (abortSignal?.aborted) {\n throw new Error(\n `aiAct aborted: ${abortSignal.reason || 'signal already aborted'}`,\n );\n }\n\n const runAiAct = async () => {\n const planningModel = this.resolveModelRuntime('planning');\n const defaultModel = this.resolveModelRuntime('default');\n // Controls the aiAct planning mode, such as sub-goal prompts and locate result strategy.\n const deepThink = opt?.deepThink === true;\n\n const deepLocate = opt?.deepLocate;\n\n const noIndividualLocateModel = planningModel.config.slot === 'default';\n\n const includeLocateInPlanning = !deepThink && noIndividualLocateModel;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n deepThink,\n noIndividualLocateModel,\n });\n\n const cacheable = opt?.cacheable;\n const replanningCycleLimit =\n this.resolveReplanningCycleLimit(planningModel);\n const planCacheEnabled = planningModel.adapter.planning.cacheEnabled;\n const matchedCache =\n !planCacheEnabled || cacheable === false\n ? undefined\n : this.taskCache?.matchPlanCache(taskPrompt);\n let cachedYamlFailed = false;\n if (\n matchedCache?.cacheUsable &&\n this.taskCache?.isCacheResultUsed &&\n matchedCache.cacheContent?.yamlWorkflow?.trim()\n ) {\n const yaml = matchedCache.cacheContent.yamlWorkflow;\n try {\n // log into report file\n await this.taskExecutor.loadYamlFlowAsPlanning(\n taskPrompt,\n yaml,\n internalReportDisplay,\n );\n\n debug('matched cache, will call .runYaml to run the action');\n await this.runYaml(yaml);\n return;\n } catch (error) {\n cachedYamlFailed = true;\n warn(\n `cached aiAct plan failed, will replan and disable the stale cache: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n // If cache matched but is not executable, fall through to normal execution\n const imagesIncludeCount: number = deepThink ? 2 : 1;\n const { output: actionOutput } = await this.taskExecutor.action(\n taskPrompt,\n planningModel,\n defaultModel,\n includeLocateInPlanning,\n this.aiActContext,\n cacheable,\n replanningCycleLimit,\n imagesIncludeCount,\n deepThink,\n fileChooserAccept,\n deepLocate,\n abortSignal,\n internalReportDisplay,\n );\n\n // update cache\n if (this.taskCache && cacheable !== false) {\n const yamlFlow = cachedYamlFailed ? [] : actionOutput?.yamlFlow;\n\n if (!cachedYamlFailed && !yamlFlow?.length) {\n return actionOutput?.output;\n }\n\n const yamlFlowToCache = yamlFlow ?? [];\n const yamlContent: MidsceneYamlScript = {\n tasks: [\n {\n name: reportPrompt,\n flow: yamlFlowToCache,\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 return actionOutput?.output;\n };\n\n return await runAiAct();\n }\n\n async runMarkdown(\n markdownPath: string,\n opt?: AiActOptions,\n ): Promise<string | undefined> {\n const markdown = await readFile(markdownPath, 'utf-8');\n const { prompt } = await markdownToAiActPrompt(markdown, markdownPath);\n return this.aiAct(prompt, {\n ...opt,\n _internalReportDisplay: {\n type: 'Markdown',\n prompt: basename(markdownPath),\n },\n } as AiActOptions);\n }\n\n /**\n * @deprecated Use {@link Agent.aiAct} instead.\n */\n async aiAction(taskPrompt: TUserPrompt, opt?: AiActOptions) {\n return this.aiAct(taskPrompt, opt);\n }\n\n async aiQuery<ReturnType = any>(\n demand: ServiceExtractParam,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<ReturnType> {\n const modelRuntime = this.resolveModelRuntime('insight');\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Query',\n demand,\n modelRuntime,\n opt,\n );\n return output as ReturnType;\n }\n\n async aiBoolean(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<boolean> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Boolean',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as boolean;\n }\n\n async aiNumber(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<number> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'Number',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as number;\n }\n\n async aiString(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<string> {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const { textPrompt, multimodalPrompt } = parsePrompt(prompt);\n const { output } = await this.taskExecutor.createTypeQueryExecution(\n 'String',\n textPrompt,\n modelRuntime,\n opt,\n multimodalPrompt,\n );\n return output as string;\n }\n\n async aiAsk(\n prompt: TUserPrompt,\n opt: ServiceExtractOption = defaultServiceExtractOption,\n ): Promise<string> {\n return this.aiString(prompt, opt);\n }\n\n async describeElementAtPoint(\n center: [number, number],\n opt?: DescribeElementAtPointOptions,\n ): Promise<AgentDescribeElementAtPointResult> {\n const { verifyPrompt = true, retryLimit = 3 } = opt || {};\n const screenshotContext = opt?.screenshotBase64\n ? await createScreenshotBoundUIContext(opt.screenshotBase64, opt)\n : undefined;\n const targetCenter = screenshotContext\n ? mapPointToScreenshotSpace(center, screenshotContext.shotSize, opt || {})\n : center;\n\n let success = false;\n let retryCount = 0;\n let resultPrompt = '';\n let deepLocate = opt?.deepLocate || false;\n let verifyResult: LocateValidatorResult | undefined;\n\n while (!success && retryCount < retryLimit) {\n if (retryCount >= 2) {\n deepLocate = true;\n }\n debug(\n 'aiDescribe',\n targetCenter,\n 'verifyPrompt',\n verifyPrompt,\n 'retryCount',\n retryCount,\n 'deepLocate',\n deepLocate,\n );\n // use same intent as aiLocate\n const modelRuntime = this.resolveModelRuntime('insight');\n const describeOpt = screenshotContext\n ? { deepLocate, context: screenshotContext }\n : { deepLocate };\n\n const text = await this.service.describe(\n targetCenter,\n modelRuntime,\n describeOpt,\n );\n debug('aiDescribe text', text);\n assert(\n text.description,\n `failed to describe element at [${targetCenter}]`,\n );\n resultPrompt = text.description;\n\n if (!verifyPrompt) {\n opt?.onProgress?.({ prompt: resultPrompt, deepLocate });\n success = true;\n break;\n }\n\n // Don't pass deepLocate to verification locate — the description was generated\n // from a cropped view (deepLocate describe), but verification should use regular\n // locate on the full screenshot to confirm the description works universally.\n // Passing deepLocate here would add another first-pass locate and search-area\n // crop around an already element-level description, which is not the intent of\n // verification.\n verifyResult = await this.verifyLocator(\n resultPrompt,\n screenshotContext ? { uiContext: screenshotContext } : undefined,\n targetCenter,\n opt,\n );\n opt?.onProgress?.({ prompt: resultPrompt, deepLocate, verifyResult });\n if (verifyResult.pass) {\n success = true;\n } else {\n retryCount++;\n }\n }\n\n return {\n prompt: resultPrompt,\n deepLocate,\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 includedInRect: included,\n };\n debug('aiDescribe verifyResult', verifyResult);\n return verifyResult;\n }\n\n /**\n * Locate an element and return both its center point and an approximate rect.\n *\n * - In most locate flows, `rect` represents the matched element boundary.\n * - Some models only support point grounding instead of boundary grounding.\n * In those cases (for example, AutoGLM), `rect` falls back to a small 8x8\n * box centered on the located point.\n *\n * Because `rect` may vary with the underlying model capability, avoid relying\n * on it too heavily for strict boundary semantics. If you need a stable click\n * target, prefer `center`.\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 defaultModel = this.resolveModelRuntime('default');\n const planningModel = this.resolveModelRuntime('planning');\n\n const { output } = await this.taskExecutor.runPlans(\n taskTitleStr('Locate', locateParamStr(locateParam)),\n plans,\n planningModel,\n defaultModel,\n opt?.uiContext ? { uiContext: opt.uiContext } : undefined,\n );\n\n const { element } = output;\n\n return {\n rect: element?.rect,\n center: element?.center,\n dpr: element?.dpr,\n } as Pick<LocateResultElement, 'rect' | 'center'>;\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AgentAssertOpt & ServiceExtractOption,\n ) {\n const modelRuntime = this.resolveModelRuntime('insight');\n\n const serviceOpt: ServiceExtractOption = {\n domIncluded: opt?.domIncluded ?? defaultServiceExtractOption.domIncluded,\n screenshotIncluded:\n opt?.screenshotIncluded ??\n defaultServiceExtractOption.screenshotIncluded,\n };\n\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n const assertionText =\n typeof assertion === 'string' ? assertion : assertion.prompt;\n\n try {\n const { output, thought } =\n await this.taskExecutor.createTypeQueryExecution<boolean>(\n 'Assert',\n textPrompt,\n modelRuntime,\n serviceOpt,\n multimodalPrompt,\n );\n\n const pass = Boolean(output);\n const message = pass\n ? undefined\n : `Assertion failed: ${msg || assertionText}\\nReason: ${thought || '(no_reason)'}`;\n\n if (opt?.keepRawResponse) {\n return {\n pass,\n thought,\n message,\n };\n }\n\n if (!pass) {\n throw new Error(message);\n }\n } catch (error) {\n if (error instanceof TaskExecutionError) {\n const errorTask = error.errorTask;\n const thought = errorTask?.thought;\n const rawError = errorTask?.error;\n const rawMessage =\n errorTask?.errorMessage ||\n (rawError instanceof Error\n ? rawError.message\n : rawError\n ? String(rawError)\n : undefined);\n const reason = thought || rawMessage || '(no_reason)';\n const message = `Assertion failed: ${msg || assertionText}\\nReason: ${reason}`;\n\n if (opt?.keepRawResponse) {\n return {\n pass: false,\n thought,\n message,\n };\n }\n\n throw new Error(message, {\n cause: rawError ?? error,\n });\n }\n\n throw error;\n }\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelRuntime = this.resolveModelRuntime('insight');\n await this.taskExecutor.waitFor(\n assertion,\n {\n ...opt,\n timeoutMs: opt?.timeoutMs || 15 * 1000,\n checkIntervalMs: opt?.checkIntervalMs || 3 * 1000,\n },\n modelRuntime,\n );\n }\n\n async ai(...args: Parameters<typeof this.aiAct>) {\n return this.aiAct(...args);\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 /**\n * Add a dump update listener\n * @param listener Listener function\n * @returns A remove function that can be called to remove this listener\n */\n addDumpUpdateListener(\n listener: (dump: string, executionDump?: ExecutionDump) => void,\n ): () => void {\n this.dumpUpdateListeners.push(listener);\n\n // Return remove function\n return () => {\n this.removeDumpUpdateListener(listener);\n };\n }\n\n /**\n * Remove a dump update listener\n * @param listener The listener function to remove\n */\n removeDumpUpdateListener(\n listener: (dump: string, executionDump?: ExecutionDump) => void,\n ): void {\n const index = this.dumpUpdateListeners.indexOf(listener);\n if (index > -1) {\n this.dumpUpdateListeners.splice(index, 1);\n }\n }\n\n /**\n * Clear all dump update listeners\n */\n clearDumpUpdateListeners(): void {\n this.dumpUpdateListeners = [];\n }\n\n private notifyDumpUpdateListeners(executionDump?: ExecutionDump) {\n const dumpString = this.dumpDataString();\n for (const listener of this.dumpUpdateListeners) {\n try {\n listener(dumpString, executionDump);\n } catch (error) {\n console.error('Error in onDumpUpdate listener', error);\n }\n }\n }\n\n async destroy() {\n // Early return if already destroyed\n if (this.destroyed) {\n return;\n }\n\n this.destroyed = true;\n let interfaceDestroyError: unknown;\n try {\n await this.interface.destroy?.();\n } catch (error) {\n interfaceDestroyError = error;\n }\n\n // Wait for all queued write operations to complete\n await this.reportGenerator.flush();\n\n const finalPath = await this.reportGenerator.finalize();\n this.reportFile = finalPath;\n\n this.resetDump(); // reset dump to release memory\n\n if (interfaceDestroyError) {\n throw interfaceDestroyError;\n }\n }\n\n async recordToReport(title?: string, opt?: RecordToReportOptions) {\n const now = Date.now();\n const screenshots = opt?.screenshots;\n const screenshotBase64 = opt?.screenshotBase64;\n const hasScreenshots = screenshots !== undefined;\n const hasScreenshotBase64 = screenshotBase64 !== undefined;\n if (hasScreenshots && !Array.isArray(screenshots)) {\n throw new Error('recordToReport: screenshots must be an array');\n }\n if (hasScreenshotBase64 && typeof screenshotBase64 !== 'string') {\n throw new Error('recordToReport: screenshotBase64 must be a string');\n }\n if (hasScreenshots && hasScreenshotBase64) {\n throw new Error(\n 'recordToReport: provide only one of screenshots or screenshotBase64',\n );\n }\n if (opt && 'subType' in opt) {\n throw new Error('recordToReport: subType is not supported');\n }\n const customScreenshots = hasScreenshots ? screenshots : undefined;\n if (customScreenshots && customScreenshots.length === 0) {\n throw new Error('recordToReport: screenshots cannot be empty');\n }\n const screenshotInputs: RecordToReportScreenshot[] =\n customScreenshots ??\n (hasScreenshotBase64\n ? [{ base64: screenshotBase64 }]\n : [{ base64: await this.interface.screenshotBase64() }]);\n\n // 1. build recorder\n const recorder: ExecutionRecorderItem[] = screenshotInputs.map(\n (screenshotInput, index) => {\n const normalizedScreenshotInput = normalizeRecordToReportScreenshot(\n screenshotInput,\n index,\n );\n const ts = now + index;\n return {\n type: 'screenshot',\n ts,\n screenshot: ScreenshotItem.create(\n normalizedScreenshotInput.base64,\n ts,\n ),\n description: normalizedScreenshotInput.description,\n };\n },\n );\n // 2. build ExecutionTaskLog\n const task: ExecutionTaskLog = {\n taskId: uuid(),\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 // 3. build ExecutionDump\n const executionDump = new ExecutionDump({\n id: uuid(),\n logTime: now,\n name: `Log - ${title || 'untitled'}`,\n description: opt?.content || '',\n tasks: [task],\n });\n // 4. append to execution dump\n this.appendExecutionDump(executionDump);\n\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n\n // Call all registered dump update listeners\n this.notifyDumpUpdateListeners(executionDump);\n }\n\n async recordErrorToReport(\n title: string,\n opt: {\n error: Error;\n content?: string;\n screenshotBase64?: string;\n },\n ) {\n const now = Date.now();\n const recorder: ExecutionRecorderItem[] = [];\n const base64 =\n opt.screenshotBase64 ?? (await this.interface.screenshotBase64());\n if (base64) {\n recorder.push({\n type: 'screenshot',\n ts: now,\n screenshot: ScreenshotItem.create(base64, now),\n });\n }\n\n const task: ExecutionTaskLog = {\n taskId: uuid(),\n type: 'Log',\n subType: 'Error',\n status: 'failed',\n recorder,\n timing: {\n start: now,\n end: now,\n cost: 0,\n },\n param: {\n content: opt.content || '',\n },\n error: opt.error,\n errorMessage: opt.error.message,\n errorStack: opt.error.stack,\n executor: async () => {},\n };\n\n const executionDump = new ExecutionDump({\n id: uuid(),\n logTime: now,\n name: title,\n description: opt.content || opt.error.message,\n tasks: [task],\n });\n\n this.appendExecutionDump(executionDump);\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n this.notifyDumpUpdateListeners(executionDump);\n }\n\n /**\n * @deprecated Use {@link Agent.recordToReport} instead.\n */\n async logScreenshot(\n title?: string,\n opt?: {\n content: string;\n },\n ) {\n await this.recordToReport(title, opt);\n }\n\n _unstableLogContent() {\n const { groupName, groupDescription, executions } = this.dump;\n return {\n groupName,\n groupDescription,\n executions: executions || [],\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 cacheDir?: string;\n } | null {\n validateAgentCacheInput(opts.cache);\n\n // Use the unified utils function to process cache configuration\n const cacheConfig = processCacheConfig(\n opts.cache,\n opts.cacheId || 'default',\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 strategyValue = cacheConfig.strategy ?? 'read-write';\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 cacheDir: cacheConfig.cacheDir?.trim(),\n };\n }\n\n return null;\n }\n\n private normalizeFilePaths(files: string[]): string[] {\n if (ifInBrowser) {\n throw new Error('File chooser is not supported in browser environment');\n }\n\n return files.map((file) => {\n const absolutePath = resolve(file);\n if (!existsSync(absolutePath)) {\n throw new Error(\n `File not found: ${file}. Resolved to: ${absolutePath}. Current working directory: ${process.cwd()}`,\n );\n }\n return absolutePath;\n });\n }\n\n private normalizeFileInput(files: string | string[]): string[] {\n const filesArray = Array.isArray(files) ? files : [files];\n return this.normalizeFilePaths(filesArray);\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","warn","distanceOfTwoPoints","p1","p2","x1","y1","x2","y2","Math","includedInRect","point","rect","x","y","left","top","width","height","assertPositiveSize","size","label","assert","Number","mapPointToScreenshotSpace","center","screenshotSize","opt","coordinateSpace","defaultServiceExtractOption","Agent","callback","planningModel","globalConfigManager","MIDSCENE_REPLANNING_CYCLE_LIMIT","intent","getModelRuntime","_error","action","maxRetries","attempt","commonContextParser","error","Promise","resolve","setTimeout","prompt","console","ReportActionDump","getVersion","WeakMap","execution","runner","currentDump","existingIndex","undefined","ifInBrowser","reportHTMLContent","executionDump","exec","task","param","paramStr","tip","typeStr","name","type","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","defaultModel","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","fileChooserAccept","withFileChooser","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","value","optWithValue","stringValue","String","mode","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","isLocatePromptLike","normalizedScrollType","normalizeScrollType","taskPrompt","internalReportDisplay","taskPromptText","reportPrompt","abortSignal","Error","runAiAct","deepThink","deepLocate","noIndividualLocateModel","includeLocateInPlanning","cacheable","replanningCycleLimit","planCacheEnabled","matchedCache","cachedYamlFailed","yaml","imagesIncludeCount","actionOutput","yamlFlow","yamlFlowToCache","yamlContent","yamlFlowStr","markdownPath","markdown","readFile","markdownToAiActPrompt","basename","demand","modelRuntime","textPrompt","multimodalPrompt","parsePrompt","verifyPrompt","retryLimit","screenshotContext","createScreenshotBoundUIContext","targetCenter","success","retryCount","resultPrompt","verifyResult","describeOpt","text","locateOpt","expectCenter","verifyLocateOption","verifyCenter","verifyRect","distance","included","pass","locateParam","locatePlan","locatePlanForLocate","element","assertion","msg","serviceOpt","assertionText","thought","message","TaskExecutionError","errorTask","rawError","rawMessage","reason","args","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","listener","index","dumpString","interfaceDestroyError","finalPath","now","Date","screenshots","screenshotBase64","hasScreenshots","hasScreenshotBase64","Array","customScreenshots","screenshotInputs","recorder","screenshotInput","normalizedScreenshotInput","normalizeRecordToReportScreenshot","ts","ScreenshotItem","uuid","ExecutionDump","base64","groupName","groupDescription","executions","context","opts","validateAgentCacheInput","cacheConfig","processCacheConfig","id","strategyValue","isReadOnly","isWriteOnly","files","file","absolutePath","existsSync","process","filesArray","options","interfaceInstance","Object","assertReportGenerationOptions","resolvedAiActContext","hasCustomConfig","ModelConfigManager","globalModelConfigManager","Service","cacheConfigObj","TaskCache","baseActionSpace","defineActionSleep","TaskExecutor","getReportFileName","ReportGenerator","createAgent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,OAAOD,SAAS,SAAS;IAAE,SAAS;AAAK;AAE/C,MAAME,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,SAASC,mBACPC,IAAsB,EACtBC,KAAa;IAEbC,OACEF,QACEG,OAAO,QAAQ,CAACH,KAAK,KAAK,KAC1BG,OAAO,QAAQ,CAACH,KAAK,MAAM,KAC3BA,KAAK,KAAK,GAAG,KACbA,KAAK,MAAM,GAAG,GAChB,GAAGC,MAAM,uCAAuC,CAAC;AAErD;AAEA,MAAMG,4BAA4B,CAChCC,QACAC,gBACAC;IAEA,MAAMC,kBAAkBD,IAAI,eAAe,IAAI;IAC/C,IAAIC,AAAoB,iBAApBA,iBACF,OAAOH;IAGTN,mBACEQ,IAAI,WAAW,EACf;IAEF,OAAO;QACJF,MAAM,CA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 +1,14 @@
|
|
|
1
|
+
import { normalizeScreenshotBase64 } from "@midscene/shared/img";
|
|
2
|
+
function normalizeRecordToReportScreenshot(screenshot, index) {
|
|
3
|
+
if (!screenshot || 'string' != typeof screenshot.base64) throw new Error(`recordToReport: screenshot #${index + 1} must include a base64 string`);
|
|
4
|
+
if (void 0 !== screenshot.description && 'string' != typeof screenshot.description) throw new Error(`recordToReport: screenshot #${index + 1} description must be a string`);
|
|
5
|
+
return {
|
|
6
|
+
base64: normalizeScreenshotBase64(screenshot.base64, {
|
|
7
|
+
label: `recordToReport: screenshot #${index + 1} base64`
|
|
8
|
+
}),
|
|
9
|
+
description: screenshot.description
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export { normalizeRecordToReportScreenshot };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=record-to-report.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent/record-to-report.mjs","sources":["../../../src/agent/record-to-report.ts"],"sourcesContent":["import type { RecordToReportScreenshot } from '@/types';\nimport { normalizeScreenshotBase64 } from '@midscene/shared/img';\n\nexport function normalizeRecordToReportScreenshot(\n screenshot: RecordToReportScreenshot,\n index: number,\n): RecordToReportScreenshot {\n if (!screenshot || typeof screenshot.base64 !== 'string') {\n throw new Error(\n `recordToReport: screenshot #${index + 1} must include a base64 string`,\n );\n }\n\n if (\n screenshot.description !== undefined &&\n typeof screenshot.description !== 'string'\n ) {\n throw new Error(\n `recordToReport: screenshot #${index + 1} description must be a string`,\n );\n }\n\n return {\n base64: normalizeScreenshotBase64(screenshot.base64, {\n label: `recordToReport: screenshot #${index + 1} base64`,\n }),\n description: screenshot.description,\n };\n}\n"],"names":["normalizeRecordToReportScreenshot","screenshot","index","Error","undefined","normalizeScreenshotBase64"],"mappings":";AAGO,SAASA,kCACdC,UAAoC,EACpCC,KAAa;IAEb,IAAI,CAACD,cAAc,AAA6B,YAA7B,OAAOA,WAAW,MAAM,EACzC,MAAM,IAAIE,MACR,CAAC,4BAA4B,EAAED,QAAQ,EAAE,6BAA6B,CAAC;IAI3E,IACED,AAA2BG,WAA3BH,WAAW,WAAW,IACtB,AAAkC,YAAlC,OAAOA,WAAW,WAAW,EAE7B,MAAM,IAAIE,MACR,CAAC,4BAA4B,EAAED,QAAQ,EAAE,6BAA6B,CAAC;IAI3E,OAAO;QACL,QAAQG,0BAA0BJ,WAAW,MAAM,EAAE;YACnD,OAAO,CAAC,4BAA4B,EAAEC,QAAQ,EAAE,OAAO,CAAC;QAC1D;QACA,aAAaD,WAAW,WAAW;IACrC;AACF"}
|
package/dist/es/agent/utils.mjs
CHANGED
|
@@ -9,6 +9,18 @@ import { assert, logMsg, uuid } from "@midscene/shared/utils";
|
|
|
9
9
|
import dayjs from "dayjs";
|
|
10
10
|
import { debug as external_task_cache_mjs_debug } from "./task-cache.mjs";
|
|
11
11
|
const agentDebug = getDebug('agent');
|
|
12
|
+
const legacyScrollTypeMap = {
|
|
13
|
+
once: 'singleAction',
|
|
14
|
+
untilBottom: 'scrollToBottom',
|
|
15
|
+
untilTop: 'scrollToTop',
|
|
16
|
+
untilRight: 'scrollToRight',
|
|
17
|
+
untilLeft: 'scrollToLeft'
|
|
18
|
+
};
|
|
19
|
+
const normalizeScrollType = (scrollType)=>{
|
|
20
|
+
if (!scrollType) return;
|
|
21
|
+
if (scrollType in legacyScrollTypeMap) return legacyScrollTypeMap[scrollType];
|
|
22
|
+
return scrollType;
|
|
23
|
+
};
|
|
12
24
|
async function commonContextParser(interfaceInstance, _opt) {
|
|
13
25
|
const debug = getDebug('commonContextParser');
|
|
14
26
|
assert(interfaceInstance, 'interfaceInstance is required');
|
|
@@ -135,7 +147,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
|
|
|
135
147
|
return;
|
|
136
148
|
}
|
|
137
149
|
}
|
|
138
|
-
const getMidsceneVersion = ()=>"1.9.
|
|
150
|
+
const getMidsceneVersion = ()=>"1.9.8-beta-20260618091332.0";
|
|
139
151
|
const parsePrompt = (prompt)=>{
|
|
140
152
|
if ('string' == typeof prompt) return {
|
|
141
153
|
textPrompt: prompt,
|
|
@@ -176,6 +188,6 @@ const transformLogicalRectToScreenshotRect = (rect, shrunkShotToLogicalRatio)=>{
|
|
|
176
188
|
height: Math.round(rect.height * shrunkShotToLogicalRatio)
|
|
177
189
|
};
|
|
178
190
|
};
|
|
179
|
-
export { commonContextParser, createScreenshotBoundUIContext, getMidsceneVersion, getReportFileName, ifPlanLocateParamHasLocatedPixelBbox, isPixelBbox, matchElementFromCache, matchElementFromPlan, parsePrompt, printReportMsg, transformLogicalElementToScreenshot, transformLogicalRectToScreenshotRect };
|
|
191
|
+
export { commonContextParser, createScreenshotBoundUIContext, getMidsceneVersion, getReportFileName, ifPlanLocateParamHasLocatedPixelBbox, isPixelBbox, matchElementFromCache, matchElementFromPlan, normalizeScrollType, parsePrompt, printReportMsg, transformLogicalElementToScreenshot, transformLogicalRectToScreenshotRect };
|
|
180
192
|
|
|
181
193
|
//# sourceMappingURL=utils.mjs.map
|