@midscene/core 1.12.5 → 1.12.6-beta-20260909034232.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/es/agent/agent.mjs +42 -1
  2. package/dist/es/agent/agent.mjs.map +1 -1
  3. package/dist/es/agent/report-file-name.mjs +12 -0
  4. package/dist/es/agent/report-file-name.mjs.map +1 -0
  5. package/dist/es/agent/utils.mjs +4 -10
  6. package/dist/es/agent/utils.mjs.map +1 -1
  7. package/dist/es/ai-model/service-caller/index.mjs +21 -36
  8. package/dist/es/ai-model/service-caller/index.mjs.map +1 -1
  9. package/dist/es/index.mjs +3 -2
  10. package/dist/es/index.mjs.map +1 -1
  11. package/dist/es/report-html-template.mjs +1 -1
  12. package/dist/es/report.mjs +181 -4
  13. package/dist/es/report.mjs.map +1 -1
  14. package/dist/es/test-run-report.mjs +4 -0
  15. package/dist/es/test-run-report.mjs.map +1 -0
  16. package/dist/es/utils.mjs +1 -1
  17. package/dist/es/yaml/player.mjs +6 -6
  18. package/dist/es/yaml/player.mjs.map +1 -1
  19. package/dist/lib/agent/agent.js +41 -0
  20. package/dist/lib/agent/agent.js.map +1 -1
  21. package/dist/lib/agent/report-file-name.js +56 -0
  22. package/dist/lib/agent/report-file-name.js.map +1 -0
  23. package/dist/lib/agent/utils.js +3 -19
  24. package/dist/lib/agent/utils.js.map +1 -1
  25. package/dist/lib/ai-model/service-caller/index.js +21 -36
  26. package/dist/lib/ai-model/service-caller/index.js.map +1 -1
  27. package/dist/lib/index.js +10 -3
  28. package/dist/lib/index.js.map +1 -1
  29. package/dist/lib/report-html-template.js +1 -1
  30. package/dist/lib/report.js +183 -3
  31. package/dist/lib/report.js.map +1 -1
  32. package/dist/lib/test-run-report.js +38 -0
  33. package/dist/lib/test-run-report.js.map +1 -0
  34. package/dist/lib/utils.js +1 -1
  35. package/dist/lib/yaml/player.js +1 -1
  36. package/dist/lib/yaml/player.js.map +1 -1
  37. package/dist/types/agent/agent.d.ts +6 -0
  38. package/dist/types/agent/report-file-name.d.ts +1 -0
  39. package/dist/types/agent/utils.d.ts +1 -2
  40. package/dist/types/index.d.ts +3 -1
  41. package/dist/types/report.d.ts +11 -0
  42. package/dist/types/test-run-report.d.ts +167 -0
  43. package/package.json +2 -2
@@ -6,7 +6,7 @@ import { ScreenshotItem } from "../screenshot-item.mjs";
6
6
  import service from "../service/index.mjs";
7
7
  import { ExecutionDump, ReportActionDump } from "../types.mjs";
8
8
  import { ReportGenerator, assertReportGenerationOptions } from "../report-generator.mjs";
9
- import { getVersion, processCacheConfig, reportHTMLContent } from "../utils.mjs";
9
+ import { getVersion, processCacheConfig, reportHTMLContent, sleep } from "../utils.mjs";
10
10
  import { ScriptPlayer, buildDetailedLocateParam, buildDetailedLocateParamAndRestParams, parseYamlScript } from "../yaml/index.mjs";
11
11
  import { readFile } from "node:fs/promises";
12
12
  import { basename, resolve as external_node_path_resolve } from "node:path";
@@ -654,6 +654,47 @@ class Agent {
654
654
  this.resetDump();
655
655
  if (interfaceDestroyError) throw interfaceDestroyError;
656
656
  }
657
+ async sleep(ms) {
658
+ assert(Number.isFinite(ms) && ms > 0, `ms for sleep must be a finite number greater than 0, but got ${ms}`);
659
+ const start = Date.now();
660
+ const task = {
661
+ taskId: uuid(),
662
+ type: 'Action Space',
663
+ subType: 'Sleep',
664
+ status: 'running',
665
+ param: {
666
+ timeMs: ms
667
+ },
668
+ timing: {
669
+ start,
670
+ callActionStart: start
671
+ },
672
+ executor: async ()=>{}
673
+ };
674
+ const executionDump = new ExecutionDump({
675
+ id: uuid(),
676
+ logTime: start,
677
+ name: 'Sleep',
678
+ tasks: [
679
+ task
680
+ ]
681
+ });
682
+ this.appendExecutionDump(executionDump);
683
+ this.writeOutActionDumps(executionDump);
684
+ await sleep(ms);
685
+ const end = Date.now();
686
+ task.status = 'finished';
687
+ task.timing = {
688
+ start,
689
+ callActionStart: start,
690
+ callActionEnd: end,
691
+ end,
692
+ cost: end - start
693
+ };
694
+ this.writeOutActionDumps(executionDump);
695
+ await this.reportGenerator.flush();
696
+ this.notifyDumpUpdateListeners(executionDump);
697
+ }
657
698
  async recordToReport(title, opt) {
658
699
  const now = Date.now();
659
700
  const screenshots = opt?.screenshots;
@@ -1 +1 @@
1
- {"version":3,"file":"agent/agent.mjs","sources":["../../../src/agent/agent.ts"],"sourcesContent":["import { type ModelRuntime, getModelRuntime } from '@/ai-model/models';\nimport { INTERNAL_CALL_ID_FIELD } from '@/ai-model/service-caller';\nimport { IS_REPORT_BUILD } from '@/constants';\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 AIUsageInfo,\n type ActionParam,\n type ActionReturn,\n type AgentAIContextKey,\n type AgentAIContexts,\n type AgentAssertResult,\n type AgentOpt,\n type AgentProgressListener,\n type AgentWaitForOpt,\n type AiActEffort,\n type AiApiName,\n type AssertOptions,\n type DeepThinkOption,\n type DeviceAction,\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskLog,\n type InsightAPI,\n type LocateOption,\n type LocateResultElement,\n type OnTaskStartTip,\n type PlanningAction,\n type QueryOptions,\n type RecordToReportOptions,\n type RecordToReportScreenshot,\n type Rect,\n ReportActionDump,\n type ReportMeta,\n type ScrollParam,\n type ServiceAction,\n type ServiceExtractParam,\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 buildDetailedLocateParamAndRestParams,\n parseYamlScript,\n} from '../yaml/index';\n\nimport { readFile } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport type { AbstractInterface, InputStrategy } from '@/device';\nimport type { TaskRunner } from '@/task-runner';\nimport { isAgentAIContextKey } from '@midscene/shared/agent-tools/agent-context';\nimport { serializeError } from '@midscene/shared/agent-tools/error-formatter';\nimport {\n type ObservationArtifactAdapter,\n observationArtifactAdapterSymbol,\n} from '@midscene/shared/agent-tools/observation-artifact';\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 {\n defineActionRegisterFileChooserAccept,\n defineActionSleep,\n} from '../device';\nimport { validateAgentCacheInput } from './cache-config';\nimport { FileChooserAccepter } from './file-chooser';\nimport { Insight } from './insight';\nimport { MetricsCollector, type MidsceneUsageMetrics } from './metrics';\nimport { AgentProgressBus } from './progress';\nimport { buildPromptWithContext } from './prompt-context';\nimport { normalizeRecordToReportScreenshot } from './record-to-report';\nimport {\n type RunGherkinScenarioOptions,\n runGherkinScenario,\n} from './run-gherkin-scenario';\nimport { markdownToAiActPrompt } from './run-markdown';\nimport { TaskCache } from './task-cache';\nimport { TaskExecutor, locatePlanForLocate, withFileChooser } from './tasks';\nimport {\n type AgentTestRunnerNodeDefinition,\n commonAgentTestRunnerNodeDefinitions,\n} from './test-runner-nodes';\nimport {\n UIObservationImpl,\n type UIObserver,\n UIObserverImpl,\n type UIObserverOption,\n uiContextFromObservationRecord,\n} from './ui-observer';\nimport {\n type TaskTitleType,\n locateParamStr,\n paramStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport {\n commonContextParser,\n getReportFileName,\n normalizeFilePaths,\n normalizeScrollType,\n} from './utils';\n\nconst debug = getDebug('agent');\nconst warn = getDebug('agent', { console: true });\n\nexport type AiActOptions = {\n cacheable?: boolean;\n fileChooserAccept?: string | string[];\n fileChooserAllowedDir?: string;\n effort?: AiActEffort;\n deepThink?: DeepThinkOption;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n /**\n * Additional facts, rules, constraints, or output requirements for this AI\n * call. It overrides `aiContexts.aiAct` and `aiContexts.default`; `''`\n * disables inherited user context for this call.\n */\n context?: string;\n};\n\ntype AiActInternalOptions = AiActOptions & {\n _internalReportDisplay?: {\n type?: TaskTitleType;\n prompt?: string;\n };\n};\n\n/**\n * Shared input option type for aiInput(), used consistently across\n * overload signatures and the implementation so fields don't drift.\n */\ntype AgentInputOption = LocateOption & {\n autoDismissKeyboard?: boolean;\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n};\n\nexport class Agent<InterfaceType extends AbstractInterface = AbstractInterface>\n implements InsightAPI\n{\n /** Nodes this Agent class intentionally exposes to Test Runner. */\n static getTestRunnerNodeDefinitions(): readonly AgentTestRunnerNodeDefinition[] {\n return commonAgentTestRunnerNodeDefinitions;\n }\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 readonly metricsCollector = new MetricsCollector();\n\n // Monotonic counter for generating unique dedup keys when a usage has no\n // request_id (e.g. estimated streaming usage).\n private usageCallCounter = 0;\n\n // Usage values already folded into `metricsCollector`, keyed by\n // `${taskId}:${field}` so re-emitted snapshots never double-count.\n private readonly countedUsageKeys = new Set<string>();\n\n private dumpUpdateListeners: Array<\n (dump: string, executionDump?: ExecutionDump) => void\n > = [];\n\n // Generic progress bus: every producer (aiAct today, more later) broadcasts\n // through here. Consumers narrow by `event.scope`.\n private readonly progressBus = new AgentProgressBus();\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 /**\n * Currently active UIObserver (from startObserving). Only one observer may\n * be active at a time since frame sources are device-level singletons.\n */\n private activeObserver: UIObserverImpl | null = null;\n\n /** Observers own temporary frame files until their observation is disposed. */\n private ownedObservers = new Set<UIObserverImpl>();\n\n private get aiContexts(): AgentAIContexts {\n if (!this.opts.aiContexts) {\n this.opts.aiContexts = {};\n }\n return this.opts.aiContexts;\n }\n\n private resolveUserContext(\n apiName: AiApiName,\n callContext?: string,\n ): string | undefined {\n if (callContext !== undefined) {\n return callContext;\n }\n\n const apiContext = this.opts.aiContexts?.[apiName];\n if (apiContext !== undefined) {\n return apiContext;\n }\n\n const defaultContext = this.opts.aiContexts?.default;\n if (defaultContext !== undefined) {\n return defaultContext;\n }\n\n return undefined;\n }\n\n private withContext<T extends { context?: string }>(\n apiName: AiApiName,\n options?: T,\n ): T | undefined {\n const resolvedContext = this.resolveUserContext(apiName, options?.context);\n if (resolvedContext === undefined) {\n return options;\n }\n\n return {\n ...(options ?? ({} as T)),\n context: resolvedContext,\n };\n }\n\n private executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n private fullActionSpace: DeviceAction[];\n\n private activeFileChooserAccepter?: FileChooserAccepter;\n\n private activeFileChooserAllowedDir?: string;\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 const runtime = getModelRuntime(\n this.modelConfigManager.getModelConfig(intent),\n );\n return {\n ...runtime,\n onUsage: (usage) => {\n this.usageCallCounter += 1;\n // buildUsageInfo leaves intent undefined; fill it from the model\n // config slot so metrics.byIntent has a meaningful category.\n const enriched = usage.intent\n ? usage\n : { ...usage, intent: usage.slot };\n this.consumeUsage(\n enriched,\n `callai:${usage.request_id ?? this.usageCallCounter}`,\n );\n },\n };\n }\n\n private createInsight(getUIContext?: () => UIContext): Insight {\n return new Insight(\n this.taskExecutor,\n () => this.resolveModelRuntime('insight'),\n (apiName, callContext) => this.resolveUserContext(apiName, callContext),\n getUIContext,\n );\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 if (\n this.opts.aiContexts !== undefined &&\n (typeof this.opts.aiContexts !== 'object' ||\n this.opts.aiContexts === null ||\n Array.isArray(this.opts.aiContexts))\n ) {\n throw new TypeError('opts.aiContexts must be a plain object');\n }\n\n for (const [key, value] of Object.entries(this.opts.aiContexts ?? {})) {\n if (!isAgentAIContextKey(key)) {\n throw new TypeError(`Unknown Agent context key: ${key}`);\n }\n if (value !== undefined && typeof value !== 'string') {\n throw new TypeError(`Agent context \"${key}\" must be a string`);\n }\n }\n\n const deprecatedAiActContextOption =\n this.opts.aiActContext !== undefined\n ? 'aiActContext'\n : this.opts.aiActionContext !== undefined\n ? 'aiActionContext'\n : undefined;\n if (deprecatedAiActContextOption) {\n warn(\n `Agent option \"${deprecatedAiActContextOption}\" is deprecated; use \"aiContexts.aiAct\" instead. When both are provided, \"aiContexts.aiAct\" takes precedence.`,\n );\n }\n\n const normalizedAIContexts: AgentAIContexts = { ...this.opts.aiContexts };\n const resolvedAiActContext =\n normalizedAIContexts.aiAct ??\n this.opts.aiActContext ??\n this.opts.aiActionContext;\n if (resolvedAiActContext !== undefined) {\n normalizedAIContexts.aiAct = resolvedAiActContext;\n this.opts.aiActContext = resolvedAiActContext;\n this.opts.aiActionContext = resolvedAiActContext;\n }\n this.opts.aiContexts = normalizedAIContexts;\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 const fileChooserActions = this.interface.registerFileChooserListener\n ? [\n defineActionRegisterFileChooserAccept(async (files) => {\n if (!this.activeFileChooserAccepter) {\n throw new Error(\n 'RegisterFileChooserAccept can only be used while aiAct is running',\n );\n }\n if (!this.activeFileChooserAllowedDir) {\n throw new Error(\n 'RegisterFileChooserAccept requires aiAct option fileChooserAllowedDir',\n );\n }\n await this.activeFileChooserAccepter.registerFromAllowedDir(\n files,\n this.activeFileChooserAllowedDir,\n );\n }),\n ]\n : [];\n this.fullActionSpace = [\n ...baseActionSpace,\n ...fileChooserActions,\n defineActionSleep(),\n ];\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 onSnapshotChange: async (runner) => {\n const executionDump = runner.dump();\n this.appendExecutionDump(executionDump, runner);\n this.collectUsageMetrics(executionDump);\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 onProgress: this.progressBus.publish,\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 Object.defineProperty(this, observationArtifactAdapterSymbol, {\n value: {\n exportRecord: async (observation) => {\n assert(\n observation instanceof UIObservationImpl,\n 'Cannot export an observation that was not created by this Midscene runtime',\n );\n return observation.exportRecord();\n },\n loadRecord: (record) => {\n // CLI manifests are validated before this adapter is called. Rebuild\n // once here as a final runtime-boundary check before creating insight.\n uiContextFromObservationRecord(record);\n return new UIObservationImpl(\n record,\n this.createInsight(() => uiContextFromObservationRecord(record)),\n );\n },\n } satisfies ObservationArtifactAdapter,\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 * Start observing the screen in the background and return a fixed insight\n * surface when the observation is stopped:\n *\n * ```ts\n * const observer = await agent.startObserving();\n * await agent.aiAct('submit the form');\n * const observation = await observer.stop();\n * await observation.aiAssert('a success toast appeared during the process');\n * ```\n *\n * Frames come from the device's continuous frame source when available\n * (scrcpy on Android, WDA MJPEG on iOS — both opt-in; CDP screencast on\n * web) and fall back to plain screenshots otherwise. Sampling is capped at\n * 5fps, the buffer is bounded and self-thinning, decoding is deferred to\n * the end, and all buffered frames (up to `maxFrames`) are sent to\n * the model at insight time. To control token cost for long windows,\n * increase `intervalMs` or decrease `maxFrames`.\n * Awaiting `startObserving()` guarantees one baseline frame is captured\n * before your next action.\n */\n async startObserving(opt?: UIObserverOption): Promise<UIObserver> {\n // A frozen context pins perception to a single snapshot; observing a\n // window of frames contradicts that. Fail fast instead of silently\n // producing an all-identical sequence.\n assert(\n !this.frozenUIContext,\n 'startObserving() cannot be used while the UI context is frozen (call unfreezePageContext() first)',\n );\n // Frame sources are device-level singletons — two concurrent observers\n // would conflict (scrcpy stream, WDA MJPEG port, CDP screencast).\n assert(\n !this.activeObserver,\n 'An observation window is already active on this agent. ' +\n 'Stop the existing observer first (await observer.stop()) before starting a new one.',\n );\n const observer = new UIObserverImpl(\n {\n openFrameSource: async () =>\n (await this.interface.openFrameSource?.()) ?? undefined,\n // Fallback single-frame capture. Deliberately bypasses getUIContext so\n // the observation loop never pollutes the TaskRunner context cache.\n captureRawScreenshot: () => this.interface.screenshotBase64(),\n capturePreparedRepresentative: () => this.getUIContext('assert'),\n createInsight: (record) =>\n this.createInsight(() => uiContextFromObservationRecord(record)),\n onStopped: () => {\n if (this.activeObserver === observer) {\n this.activeObserver = null;\n }\n },\n onDisposed: () => this.ownedObservers.delete(observer),\n screenshotShrinkFactor: this.opts.screenshotShrinkFactor,\n },\n opt,\n );\n // Mark as active BEFORE the async start() so concurrent calls hit the\n // assert guard above. If start() throws, clear the reference below.\n this.activeObserver = observer;\n this.ownedObservers.add(observer);\n try {\n await observer.start();\n } catch (error) {\n this.activeObserver = null;\n this.ownedObservers.delete(observer);\n await observer.dispose().catch((disposeError) => {\n debug(`error disposing failed observer start: ${disposeError}`);\n });\n throw error;\n }\n return observer;\n }\n\n /**\n * @deprecated Use `setAIContext('aiAct', context)` instead.\n */\n async setAIActionContext(prompt: string) {\n warn(\n 'setAIActionContext() is deprecated; use setAIContext(\"aiAct\", context) instead.',\n );\n this.setAIContext('aiAct', prompt);\n }\n\n /**\n * @deprecated Use `setAIContext('aiAct', context)` instead.\n */\n async setAIActContext(prompt: string) {\n warn(\n 'setAIActContext() is deprecated; use setAIContext(\"aiAct\", context) instead.',\n );\n this.setAIContext('aiAct', prompt);\n }\n\n /**\n * Set Agent-level AI guidance. Use `default` as the shared fallback for all\n * AI-powered APIs, or an API name to override that fallback for the API.\n * API-specific values are not automatically merged with `default`.\n * Passing `undefined` removes the selected value; an API then falls back to\n * `default`, while removing `default` disables the shared fallback. Passing\n * `''` keeps an explicit empty value and therefore prevents an API from using\n * `default`.\n */\n setAIContext(target: AgentAIContextKey, context: string | undefined): void {\n if (!isAgentAIContextKey(target)) {\n throw new TypeError(`Unknown Agent context key: ${String(target)}`);\n }\n if (context !== undefined && typeof context !== 'string') {\n throw new TypeError('Agent context must be a string or undefined');\n }\n\n this.aiContexts[target] = context;\n\n if (target === 'aiAct') {\n if (context === undefined) {\n this.opts.aiActContext = undefined;\n this.opts.aiActionContext = undefined;\n } else {\n this.opts.aiActContext = context;\n this.opts.aiActionContext = context;\n }\n }\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 /**\n * Fold any not-yet-counted task usage from an execution dump into the\n * instance metrics. Snapshots are re-emitted as tasks progress, so each\n * usage value is keyed by `${taskId}:${field}` and counted at most once.\n */\n private collectUsageMetrics(execution: ExecutionDump) {\n for (const task of execution.tasks) {\n this.consumeUsage(task.usage, `${task.taskId}:usage`);\n this.consumeUsage(task.searchAreaUsage, `${task.taskId}:searchAreaUsage`);\n }\n }\n\n private consumeUsage(usage: AIUsageInfo | undefined, key: string) {\n if (!usage) {\n return;\n }\n // Dedup key priority:\n // 1. request_id — provider-issued, stable across onUsage and task dump paths\n // 2. INTERNAL_CALL_ID_FIELD — callAI-generated internal id, covers\n // providers that don't return a request_id\n // 3. caller-provided key (taskId:field or callai:counter)\n let dedupKey: string;\n if (usage.request_id) {\n dedupKey = `req:${usage.request_id}`;\n } else if ((usage as any)[INTERNAL_CALL_ID_FIELD]) {\n dedupKey = `int:${(usage as any)[INTERNAL_CALL_ID_FIELD]}`;\n } else {\n dedupKey = key;\n }\n if (this.countedUsageKeys.has(dedupKey)) {\n return;\n }\n this.countedUsageKeys.add(dedupKey);\n this.metricsCollector.add(usage);\n if (this.opts.onLLMUsage) {\n try {\n this.opts.onLLMUsage(usage);\n } catch (error) {\n warn(`onLLMUsage listener threw, ignoring: ${error}`);\n }\n }\n }\n\n /**\n * Aggregated LLM usage accumulated by this agent since it was created.\n */\n get metrics(): MidsceneUsageMetrics {\n return this.metricsCollector.snapshot();\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 // Short-circuit at the call site because JavaScript evaluates function\n // arguments first. This avoids serializing the dump (including inline\n // screenshots) when the Report Viewer build does not need report HTML.\n if (IS_REPORT_BUILD) {\n return '';\n }\n\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(\n locatePrompt,\n this.withContext('aiTap', opt),\n );\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(\n locatePrompt,\n this.withContext('aiRightClick', opt),\n );\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(\n locatePrompt,\n this.withContext('aiDoubleClick', opt),\n );\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(\n locatePrompt,\n this.withContext('aiHover', opt),\n );\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: AgentInputOption & { value: string | number },\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?: AgentInputOption,\n ): Promise<void>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string | number,\n locatePromptOrOpt:\n | TUserPrompt\n | (AgentInputOption & { value: string | number })\n | undefined,\n optOrUndefined?: AgentInputOption,\n ) {\n let value: string | number;\n let locatePrompt: TUserPrompt;\n let opt: (AgentInputOption & { value: string | number }) | 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 AgentInputOption & {\n value: string | number;\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt,\n this.withContext('aiInput', opt),\n );\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 ...restParams,\n value: stringValue,\n locate: locateParam,\n mode,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt | undefined,\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 | undefined,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiKeyboardPress', opt),\n );\n\n await this.callActionInActionSpace('KeyboardPress', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiScroll', opt),\n );\n\n await this.callActionInActionSpace('Scroll', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiPinch', opt),\n );\n\n await this.callActionInActionSpace('Pinch', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt,\n this.withContext('aiLongPress', opt),\n );\n\n await this.callActionInActionSpace('LongPress', {\n ...restParams,\n locate: locateParam,\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(\n locatePrompt,\n this.withContext('aiClearInput', opt),\n );\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 internalOptions = opt as AiActInternalOptions | undefined;\n const internalReportDisplay = internalOptions?._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 const aiActContext = this.resolveUserContext('aiAct', opt?.context);\n const cachePrompt = buildPromptWithContext(taskPrompt, aiActContext);\n // Resolve the public planning controls at the API boundary. Internal\n // aiAct plumbing only uses effort from this point onward. The explicit\n // effort option takes precedence over deepThink when both are provided.\n const effort: AiActEffort = (() => {\n const resolvedEffort =\n opt?.effort ?? (opt?.deepThink === true ? 'deepThink' : 'balance');\n\n if (opt?.effort !== undefined) {\n warn(\n 'The \"effort\" option is experimental and not yet open for public use. Do not use it. When both \"effort\" and \"deepThink\" are provided, \"effort\" takes precedence.',\n );\n }\n\n if (\n resolvedEffort === 'fast' &&\n planningModel.adapter.planning.kind === 'custom'\n ) {\n throw new Error(\n `The \"fast\" aiAct effort is not supported with custom planning adapters (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}).`,\n );\n }\n\n if (\n resolvedEffort === 'deepThink' &&\n planningModel.adapter.planning.kind === 'custom'\n ) {\n warn(\n `The \"deepThink\" aiAct effort is not supported with custom planning adapters (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}). It will be ignored.`,\n );\n return 'balance';\n }\n\n return resolvedEffort;\n })();\n\n let deepLocate = opt?.deepLocate;\n if (\n deepLocate &&\n !planningModel.adapter.planning.supportsActionDeepLocate\n ) {\n warn(\n `The \"deepLocate\" option is not supported for aiAct with the current planning adapter (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}). It will be ignored.`,\n );\n deepLocate = false;\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(cachePrompt);\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 { output: actionOutput } = await this.taskExecutor.action(\n taskPrompt,\n planningModel,\n defaultModel,\n aiActContext,\n cacheable,\n replanningCycleLimit,\n effort,\n undefined,\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: cachePrompt,\n yamlWorkflow: yamlFlowStr,\n },\n matchedCache,\n );\n }\n\n return actionOutput?.output;\n };\n\n const fileChooserAccepter = this.interface.registerFileChooserListener\n ? new FileChooserAccepter(this.interface)\n : undefined;\n this.activeFileChooserAccepter = fileChooserAccepter;\n this.activeFileChooserAllowedDir = opt?.fileChooserAllowedDir\n ? resolve(opt.fileChooserAllowedDir)\n : undefined;\n let aiActError: { error: unknown } | undefined;\n let fileChooserHandlingError: Error | undefined;\n let result: string | undefined;\n try {\n if (fileChooserAccept?.length) {\n if (!fileChooserAccepter) {\n throw new Error(\n `File upload is not supported on ${this.interface.interfaceType}`,\n );\n }\n await fileChooserAccepter.register(fileChooserAccept);\n }\n result = await runAiAct();\n } catch (error) {\n aiActError = { error };\n } finally {\n this.activeFileChooserAccepter = undefined;\n this.activeFileChooserAllowedDir = undefined;\n try {\n fileChooserHandlingError = await fileChooserAccepter?.clear();\n } catch (error) {\n warn(`Failed to clear file chooser registration: ${error}`);\n }\n }\n\n if (aiActError) {\n throw aiActError.error;\n }\n if (fileChooserHandlingError) {\n throw fileChooserHandlingError;\n }\n return result;\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 async runGherkinScenario(\n scenarioText: string,\n opt?: RunGherkinScenarioOptions,\n ): Promise<void> {\n return runGherkinScenario(this, scenarioText, opt);\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?: QueryOptions,\n ): Promise<ReturnType> {\n return this.createInsight().aiQuery<ReturnType>(demand, opt);\n }\n\n async aiBoolean(prompt: TUserPrompt, opt?: QueryOptions): Promise<boolean> {\n return this.createInsight().aiBoolean(prompt, opt);\n }\n\n async aiNumber(prompt: TUserPrompt, opt?: QueryOptions): Promise<number> {\n return this.createInsight().aiNumber(prompt, opt);\n }\n\n async aiString(prompt: TUserPrompt, opt?: QueryOptions): Promise<string> {\n return this.createInsight().aiString(prompt, opt);\n }\n\n async aiAsk(prompt: TUserPrompt, opt?: QueryOptions): Promise<string> {\n return this.createInsight().aiAsk(prompt, opt);\n }\n\n /**\n * Locate a target in screenshot coordinates. Preserve the model-provided rect\n * when available; otherwise, generate an approximate 8x8 compatibility box.\n * Do not rely on rect for strict element boundaries. Prefer center for the target.\n */\n async aiLocate(prompt: TUserPrompt, opt?: LocateOption) {\n const locateParam = buildDetailedLocateParam(\n prompt,\n this.withContext('aiLocate', opt),\n );\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\n ? (element.rect ?? {\n left: Math.max(element.center[0] - 3.5, 0),\n top: Math.max(element.center[1] - 3.5, 0),\n width: 8,\n height: 8,\n })\n : undefined,\n center: element?.center,\n dpr: element?.dpr,\n } as Pick<LocateResultElement, 'center' | 'dpr'> & {\n rect: Rect;\n };\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AssertOptions,\n ): Promise<AgentAssertResult | undefined> {\n return this.createInsight().aiAssert(assertion, msg, opt);\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelRuntime = this.resolveModelRuntime('insight');\n const options = this.withContext('aiWaitFor', opt);\n await this.taskExecutor.waitFor(\n assertion,\n {\n ...options,\n timeoutMs: options?.timeoutMs || 15 * 1000,\n checkIntervalMs: options?.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 /**\n * Subscribe to the generic agent progress bus. The listener receives every\n * progress event regardless of producer; narrow by `event.scope` to handle a\n * specific producer (e.g. `'aiAct'`).\n * @param listener Listener function\n * @returns A remove function that can be called to remove this listener\n */\n addProgressListener(listener: AgentProgressListener): () => void {\n return this.progressBus.subscribe(listener);\n }\n\n /**\n * Remove a progress listener added via {@link addProgressListener}.\n */\n removeProgressListener(listener: AgentProgressListener): void {\n this.progressBus.unsubscribe(listener);\n }\n\n /**\n * Clear all generic progress listeners.\n */\n clearProgressListeners(): void {\n this.progressBus.clear();\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\n // Observers own observation frame files until explicitly disposed.\n for (const observer of this.ownedObservers) {\n try {\n await observer.dispose();\n } catch (error) {\n debug(`error disposing unexported observer during destroy: ${error}`);\n }\n }\n this.ownedObservers.clear();\n this.activeObserver = null;\n\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 /** Any thrown value; normalized before it is stored in the report. */\n error: unknown;\n content?: string;\n screenshotBase64?: string;\n },\n ) {\n const now = Date.now();\n const error = serializeError(opt.error);\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,\n errorMessage: error.message,\n errorStack: 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 || 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 normalizeFileInput(files: string | string[]): string[] {\n const filesArray = Array.isArray(files) ? files : [files];\n return 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","Agent","commonAgentTestRunnerNodeDefinitions","callback","apiName","callContext","undefined","apiContext","defaultContext","options","resolvedContext","planningModel","globalConfigManager","MIDSCENE_REPLANNING_CYCLE_LIMIT","intent","runtime","getModelRuntime","usage","enriched","getUIContext","Insight","_error","action","maxRetries","attempt","commonContextParser","error","Promise","resolve","setTimeout","opt","assert","observer","UIObserverImpl","record","uiContextFromObservationRecord","disposeError","prompt","target","context","isAgentAIContextKey","TypeError","String","ReportActionDump","getVersion","WeakMap","execution","runner","currentDump","existingIndex","task","key","dedupKey","INTERNAL_CALL_ID_FIELD","ifInBrowser","IS_REPORT_BUILD","reportHTMLContent","executionDump","exec","param","paramStr","tip","typeStr","name","type","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","defaultModel","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","fileChooserAccept","withFileChooser","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","value","optWithValue","locateParam","restParams","buildDetailedLocateParamAndRestParams","stringValue","mode","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","isLocatePromptLike","normalizedScrollType","normalizeScrollType","taskPrompt","internalOptions","internalReportDisplay","taskPromptText","reportPrompt","abortSignal","Error","runAiAct","aiActContext","cachePrompt","buildPromptWithContext","effort","resolvedEffort","deepLocate","cacheable","replanningCycleLimit","planCacheEnabled","matchedCache","cachedYamlFailed","yaml","actionOutput","yamlFlow","yamlFlowToCache","yamlContent","yamlFlowStr","fileChooserAccepter","FileChooserAccepter","aiActError","fileChooserHandlingError","result","markdownPath","markdown","readFile","markdownToAiActPrompt","basename","scenarioText","runGherkinScenario","demand","locatePlan","locatePlanForLocate","element","Math","assertion","msg","modelRuntime","args","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","listener","index","dumpString","console","interfaceDestroyError","finalPath","now","Date","screenshots","screenshotBase64","hasScreenshots","hasScreenshotBase64","Array","customScreenshots","screenshotInputs","recorder","screenshotInput","normalizedScreenshotInput","normalizeRecordToReportScreenshot","ts","ScreenshotItem","uuid","ExecutionDump","serializeError","base64","groupName","groupDescription","executions","opts","validateAgentCacheInput","cacheConfig","processCacheConfig","id","strategyValue","isReadOnly","isWriteOnly","files","filesArray","normalizeFilePaths","interfaceInstance","MetricsCollector","Set","AgentProgressBus","Object","assertReportGenerationOptions","deprecatedAiActContextOption","normalizedAIContexts","resolvedAiActContext","hasCustomConfig","ModelConfigManager","globalModelConfigManager","Service","cacheConfigObj","TaskCache","baseActionSpace","fileChooserActions","defineActionRegisterFileChooserAccept","defineActionSleep","TaskExecutor","getReportFileName","ReportGenerator","observationArtifactAdapterSymbol","observation","UIObservationImpl","createAgent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,OAAOD,SAAS,SAAS;IAAE,SAAS;AAAK;AAoCxC,MAAME;IAIX,OAAO,+BAAyE;QAC9E,OAAOC;IACT;IA2CA,IAAI,eAEU;QACZ,OAAO,IAAI,CAAC,mBAAmB,CAAC,EAAE;IACpC;IAEA,IAAI,aAAaC,QAEJ,EAAE;QAEb,IAAI,CAAC,mBAAmB,GAAG,EAAE;QAE7B,IAAIA,UACF,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAACA;IAElC;IAoBA,IAAY,aAA8B;QACxC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EACvB,IAAI,CAAC,IAAI,CAAC,UAAU,GAAG,CAAC;QAE1B,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU;IAC7B;IAEQ,mBACNC,OAAkB,EAClBC,WAAoB,EACA;QACpB,IAAIA,AAAgBC,WAAhBD,aACF,OAAOA;QAGT,MAAME,aAAa,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAACH,QAAQ;QAClD,IAAIG,AAAeD,WAAfC,YACF,OAAOA;QAGT,MAAMC,iBAAiB,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;QAC7C,IAAIA,AAAmBF,WAAnBE,gBACF,OAAOA;IAIX;IAEQ,YACNJ,OAAkB,EAClBK,OAAW,EACI;QACf,MAAMC,kBAAkB,IAAI,CAAC,kBAAkB,CAACN,SAASK,SAAS;QAClE,IAAIC,AAAoBJ,WAApBI,iBACF,OAAOD;QAGT,OAAO;YACL,GAAIA,WAAY,CAAC,CAAO;YACxB,SAASC;QACX;IACF;IAaA,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,SAAS;IACvB;IAgBQ,o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ACjC;gBACA,YAAY,CAAC/K;oBAGXC,+BAA+BD;oBAC/B,OAAO,IAAIgL,kBACThL,QACA,IAAI,CAAC,aAAa,CAAC,IAAMC,+BAA+BD;gBAE5D;YACF;QACF;IACF;AAu3CF;AAj3CE,iBAjZWjC,OAiZa,qBAAoB;AAC5C,iBAlZWA,OAkZa,0BAAyB;AAk3C5C,MAAMkN,cAAc,CACzBzB,mBACAX,OAEO,IAAI9K,MAAMyL,mBAAmBX"}
1
+ {"version":3,"file":"agent/agent.mjs","sources":["../../../src/agent/agent.ts"],"sourcesContent":["import { type ModelRuntime, getModelRuntime } from '@/ai-model/models';\nimport { INTERNAL_CALL_ID_FIELD } from '@/ai-model/service-caller';\nimport { IS_REPORT_BUILD } from '@/constants';\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 AIUsageInfo,\n type ActionParam,\n type ActionReturn,\n type AgentAIContextKey,\n type AgentAIContexts,\n type AgentAssertResult,\n type AgentOpt,\n type AgentProgressListener,\n type AgentWaitForOpt,\n type AiActEffort,\n type AiApiName,\n type AssertOptions,\n type DeepThinkOption,\n type DeviceAction,\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskLog,\n type InsightAPI,\n type LocateOption,\n type LocateResultElement,\n type OnTaskStartTip,\n type PlanningAction,\n type QueryOptions,\n type RecordToReportOptions,\n type RecordToReportScreenshot,\n type Rect,\n ReportActionDump,\n type ReportMeta,\n type ScrollParam,\n type ServiceAction,\n type ServiceExtractParam,\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 {\n getVersion,\n processCacheConfig,\n reportHTMLContent,\n sleep,\n} from '@/utils';\nimport {\n ScriptPlayer,\n buildDetailedLocateParam,\n buildDetailedLocateParamAndRestParams,\n parseYamlScript,\n} from '../yaml/index';\n\nimport { readFile } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport type { AbstractInterface, InputStrategy } from '@/device';\nimport type { TaskRunner } from '@/task-runner';\nimport { isAgentAIContextKey } from '@midscene/shared/agent-tools/agent-context';\nimport { serializeError } from '@midscene/shared/agent-tools/error-formatter';\nimport {\n type ObservationArtifactAdapter,\n observationArtifactAdapterSymbol,\n} from '@midscene/shared/agent-tools/observation-artifact';\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 {\n defineActionRegisterFileChooserAccept,\n defineActionSleep,\n} from '../device';\nimport { validateAgentCacheInput } from './cache-config';\nimport { FileChooserAccepter } from './file-chooser';\nimport { Insight } from './insight';\nimport { MetricsCollector, type MidsceneUsageMetrics } from './metrics';\nimport { AgentProgressBus } from './progress';\nimport { buildPromptWithContext } from './prompt-context';\nimport { normalizeRecordToReportScreenshot } from './record-to-report';\nimport {\n type RunGherkinScenarioOptions,\n runGherkinScenario,\n} from './run-gherkin-scenario';\nimport { markdownToAiActPrompt } from './run-markdown';\nimport { TaskCache } from './task-cache';\nimport { TaskExecutor, locatePlanForLocate, withFileChooser } from './tasks';\nimport {\n type AgentTestRunnerNodeDefinition,\n commonAgentTestRunnerNodeDefinitions,\n} from './test-runner-nodes';\nimport {\n UIObservationImpl,\n type UIObserver,\n UIObserverImpl,\n type UIObserverOption,\n uiContextFromObservationRecord,\n} from './ui-observer';\nimport {\n type TaskTitleType,\n locateParamStr,\n paramStr,\n taskTitleStr,\n typeStr,\n} from './ui-utils';\nimport {\n commonContextParser,\n getReportFileName,\n normalizeFilePaths,\n normalizeScrollType,\n} from './utils';\n\nconst debug = getDebug('agent');\nconst warn = getDebug('agent', { console: true });\n\nexport type AiActOptions = {\n cacheable?: boolean;\n fileChooserAccept?: string | string[];\n fileChooserAllowedDir?: string;\n effort?: AiActEffort;\n deepThink?: DeepThinkOption;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n /**\n * Additional facts, rules, constraints, or output requirements for this AI\n * call. It overrides `aiContexts.aiAct` and `aiContexts.default`; `''`\n * disables inherited user context for this call.\n */\n context?: string;\n};\n\ntype AiActInternalOptions = AiActOptions & {\n _internalReportDisplay?: {\n type?: TaskTitleType;\n prompt?: string;\n };\n};\n\n/**\n * Shared input option type for aiInput(), used consistently across\n * overload signatures and the implementation so fields don't drift.\n */\ntype AgentInputOption = LocateOption & {\n autoDismissKeyboard?: boolean;\n keyboardTypeDelay?: number;\n inputStrategy?: InputStrategy;\n mode?: 'replace' | 'clear' | 'typeOnly' | 'append';\n};\n\nexport class Agent<InterfaceType extends AbstractInterface = AbstractInterface>\n implements InsightAPI\n{\n /** Nodes this Agent class intentionally exposes to Test Runner. */\n static getTestRunnerNodeDefinitions(): readonly AgentTestRunnerNodeDefinition[] {\n return commonAgentTestRunnerNodeDefinitions;\n }\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 readonly metricsCollector = new MetricsCollector();\n\n // Monotonic counter for generating unique dedup keys when a usage has no\n // request_id (e.g. estimated streaming usage).\n private usageCallCounter = 0;\n\n // Usage values already folded into `metricsCollector`, keyed by\n // `${taskId}:${field}` so re-emitted snapshots never double-count.\n private readonly countedUsageKeys = new Set<string>();\n\n private dumpUpdateListeners: Array<\n (dump: string, executionDump?: ExecutionDump) => void\n > = [];\n\n // Generic progress bus: every producer (aiAct today, more later) broadcasts\n // through here. Consumers narrow by `event.scope`.\n private readonly progressBus = new AgentProgressBus();\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 /**\n * Currently active UIObserver (from startObserving). Only one observer may\n * be active at a time since frame sources are device-level singletons.\n */\n private activeObserver: UIObserverImpl | null = null;\n\n /** Observers own temporary frame files until their observation is disposed. */\n private ownedObservers = new Set<UIObserverImpl>();\n\n private get aiContexts(): AgentAIContexts {\n if (!this.opts.aiContexts) {\n this.opts.aiContexts = {};\n }\n return this.opts.aiContexts;\n }\n\n private resolveUserContext(\n apiName: AiApiName,\n callContext?: string,\n ): string | undefined {\n if (callContext !== undefined) {\n return callContext;\n }\n\n const apiContext = this.opts.aiContexts?.[apiName];\n if (apiContext !== undefined) {\n return apiContext;\n }\n\n const defaultContext = this.opts.aiContexts?.default;\n if (defaultContext !== undefined) {\n return defaultContext;\n }\n\n return undefined;\n }\n\n private withContext<T extends { context?: string }>(\n apiName: AiApiName,\n options?: T,\n ): T | undefined {\n const resolvedContext = this.resolveUserContext(apiName, options?.context);\n if (resolvedContext === undefined) {\n return options;\n }\n\n return {\n ...(options ?? ({} as T)),\n context: resolvedContext,\n };\n }\n\n private executionDumpIndexByRunner = new WeakMap<TaskRunner, number>();\n\n private fullActionSpace: DeviceAction[];\n\n private activeFileChooserAccepter?: FileChooserAccepter;\n\n private activeFileChooserAllowedDir?: string;\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 const runtime = getModelRuntime(\n this.modelConfigManager.getModelConfig(intent),\n );\n return {\n ...runtime,\n onUsage: (usage) => {\n this.usageCallCounter += 1;\n // buildUsageInfo leaves intent undefined; fill it from the model\n // config slot so metrics.byIntent has a meaningful category.\n const enriched = usage.intent\n ? usage\n : { ...usage, intent: usage.slot };\n this.consumeUsage(\n enriched,\n `callai:${usage.request_id ?? this.usageCallCounter}`,\n );\n },\n };\n }\n\n private createInsight(getUIContext?: () => UIContext): Insight {\n return new Insight(\n this.taskExecutor,\n () => this.resolveModelRuntime('insight'),\n (apiName, callContext) => this.resolveUserContext(apiName, callContext),\n getUIContext,\n );\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 if (\n this.opts.aiContexts !== undefined &&\n (typeof this.opts.aiContexts !== 'object' ||\n this.opts.aiContexts === null ||\n Array.isArray(this.opts.aiContexts))\n ) {\n throw new TypeError('opts.aiContexts must be a plain object');\n }\n\n for (const [key, value] of Object.entries(this.opts.aiContexts ?? {})) {\n if (!isAgentAIContextKey(key)) {\n throw new TypeError(`Unknown Agent context key: ${key}`);\n }\n if (value !== undefined && typeof value !== 'string') {\n throw new TypeError(`Agent context \"${key}\" must be a string`);\n }\n }\n\n const deprecatedAiActContextOption =\n this.opts.aiActContext !== undefined\n ? 'aiActContext'\n : this.opts.aiActionContext !== undefined\n ? 'aiActionContext'\n : undefined;\n if (deprecatedAiActContextOption) {\n warn(\n `Agent option \"${deprecatedAiActContextOption}\" is deprecated; use \"aiContexts.aiAct\" instead. When both are provided, \"aiContexts.aiAct\" takes precedence.`,\n );\n }\n\n const normalizedAIContexts: AgentAIContexts = { ...this.opts.aiContexts };\n const resolvedAiActContext =\n normalizedAIContexts.aiAct ??\n this.opts.aiActContext ??\n this.opts.aiActionContext;\n if (resolvedAiActContext !== undefined) {\n normalizedAIContexts.aiAct = resolvedAiActContext;\n this.opts.aiActContext = resolvedAiActContext;\n this.opts.aiActionContext = resolvedAiActContext;\n }\n this.opts.aiContexts = normalizedAIContexts;\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 const fileChooserActions = this.interface.registerFileChooserListener\n ? [\n defineActionRegisterFileChooserAccept(async (files) => {\n if (!this.activeFileChooserAccepter) {\n throw new Error(\n 'RegisterFileChooserAccept can only be used while aiAct is running',\n );\n }\n if (!this.activeFileChooserAllowedDir) {\n throw new Error(\n 'RegisterFileChooserAccept requires aiAct option fileChooserAllowedDir',\n );\n }\n await this.activeFileChooserAccepter.registerFromAllowedDir(\n files,\n this.activeFileChooserAllowedDir,\n );\n }),\n ]\n : [];\n this.fullActionSpace = [\n ...baseActionSpace,\n ...fileChooserActions,\n defineActionSleep(),\n ];\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 onSnapshotChange: async (runner) => {\n const executionDump = runner.dump();\n this.appendExecutionDump(executionDump, runner);\n this.collectUsageMetrics(executionDump);\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 onProgress: this.progressBus.publish,\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 Object.defineProperty(this, observationArtifactAdapterSymbol, {\n value: {\n exportRecord: async (observation) => {\n assert(\n observation instanceof UIObservationImpl,\n 'Cannot export an observation that was not created by this Midscene runtime',\n );\n return observation.exportRecord();\n },\n loadRecord: (record) => {\n // CLI manifests are validated before this adapter is called. Rebuild\n // once here as a final runtime-boundary check before creating insight.\n uiContextFromObservationRecord(record);\n return new UIObservationImpl(\n record,\n this.createInsight(() => uiContextFromObservationRecord(record)),\n );\n },\n } satisfies ObservationArtifactAdapter,\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 * Start observing the screen in the background and return a fixed insight\n * surface when the observation is stopped:\n *\n * ```ts\n * const observer = await agent.startObserving();\n * await agent.aiAct('submit the form');\n * const observation = await observer.stop();\n * await observation.aiAssert('a success toast appeared during the process');\n * ```\n *\n * Frames come from the device's continuous frame source when available\n * (scrcpy on Android, WDA MJPEG on iOS — both opt-in; CDP screencast on\n * web) and fall back to plain screenshots otherwise. Sampling is capped at\n * 5fps, the buffer is bounded and self-thinning, decoding is deferred to\n * the end, and all buffered frames (up to `maxFrames`) are sent to\n * the model at insight time. To control token cost for long windows,\n * increase `intervalMs` or decrease `maxFrames`.\n * Awaiting `startObserving()` guarantees one baseline frame is captured\n * before your next action.\n */\n async startObserving(opt?: UIObserverOption): Promise<UIObserver> {\n // A frozen context pins perception to a single snapshot; observing a\n // window of frames contradicts that. Fail fast instead of silently\n // producing an all-identical sequence.\n assert(\n !this.frozenUIContext,\n 'startObserving() cannot be used while the UI context is frozen (call unfreezePageContext() first)',\n );\n // Frame sources are device-level singletons — two concurrent observers\n // would conflict (scrcpy stream, WDA MJPEG port, CDP screencast).\n assert(\n !this.activeObserver,\n 'An observation window is already active on this agent. ' +\n 'Stop the existing observer first (await observer.stop()) before starting a new one.',\n );\n const observer = new UIObserverImpl(\n {\n openFrameSource: async () =>\n (await this.interface.openFrameSource?.()) ?? undefined,\n // Fallback single-frame capture. Deliberately bypasses getUIContext so\n // the observation loop never pollutes the TaskRunner context cache.\n captureRawScreenshot: () => this.interface.screenshotBase64(),\n capturePreparedRepresentative: () => this.getUIContext('assert'),\n createInsight: (record) =>\n this.createInsight(() => uiContextFromObservationRecord(record)),\n onStopped: () => {\n if (this.activeObserver === observer) {\n this.activeObserver = null;\n }\n },\n onDisposed: () => this.ownedObservers.delete(observer),\n screenshotShrinkFactor: this.opts.screenshotShrinkFactor,\n },\n opt,\n );\n // Mark as active BEFORE the async start() so concurrent calls hit the\n // assert guard above. If start() throws, clear the reference below.\n this.activeObserver = observer;\n this.ownedObservers.add(observer);\n try {\n await observer.start();\n } catch (error) {\n this.activeObserver = null;\n this.ownedObservers.delete(observer);\n await observer.dispose().catch((disposeError) => {\n debug(`error disposing failed observer start: ${disposeError}`);\n });\n throw error;\n }\n return observer;\n }\n\n /**\n * @deprecated Use `setAIContext('aiAct', context)` instead.\n */\n async setAIActionContext(prompt: string) {\n warn(\n 'setAIActionContext() is deprecated; use setAIContext(\"aiAct\", context) instead.',\n );\n this.setAIContext('aiAct', prompt);\n }\n\n /**\n * @deprecated Use `setAIContext('aiAct', context)` instead.\n */\n async setAIActContext(prompt: string) {\n warn(\n 'setAIActContext() is deprecated; use setAIContext(\"aiAct\", context) instead.',\n );\n this.setAIContext('aiAct', prompt);\n }\n\n /**\n * Set Agent-level AI guidance. Use `default` as the shared fallback for all\n * AI-powered APIs, or an API name to override that fallback for the API.\n * API-specific values are not automatically merged with `default`.\n * Passing `undefined` removes the selected value; an API then falls back to\n * `default`, while removing `default` disables the shared fallback. Passing\n * `''` keeps an explicit empty value and therefore prevents an API from using\n * `default`.\n */\n setAIContext(target: AgentAIContextKey, context: string | undefined): void {\n if (!isAgentAIContextKey(target)) {\n throw new TypeError(`Unknown Agent context key: ${String(target)}`);\n }\n if (context !== undefined && typeof context !== 'string') {\n throw new TypeError('Agent context must be a string or undefined');\n }\n\n this.aiContexts[target] = context;\n\n if (target === 'aiAct') {\n if (context === undefined) {\n this.opts.aiActContext = undefined;\n this.opts.aiActionContext = undefined;\n } else {\n this.opts.aiActContext = context;\n this.opts.aiActionContext = context;\n }\n }\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 /**\n * Fold any not-yet-counted task usage from an execution dump into the\n * instance metrics. Snapshots are re-emitted as tasks progress, so each\n * usage value is keyed by `${taskId}:${field}` and counted at most once.\n */\n private collectUsageMetrics(execution: ExecutionDump) {\n for (const task of execution.tasks) {\n this.consumeUsage(task.usage, `${task.taskId}:usage`);\n this.consumeUsage(task.searchAreaUsage, `${task.taskId}:searchAreaUsage`);\n }\n }\n\n private consumeUsage(usage: AIUsageInfo | undefined, key: string) {\n if (!usage) {\n return;\n }\n // Dedup key priority:\n // 1. request_id — provider-issued, stable across onUsage and task dump paths\n // 2. INTERNAL_CALL_ID_FIELD — callAI-generated internal id, covers\n // providers that don't return a request_id\n // 3. caller-provided key (taskId:field or callai:counter)\n let dedupKey: string;\n if (usage.request_id) {\n dedupKey = `req:${usage.request_id}`;\n } else if ((usage as any)[INTERNAL_CALL_ID_FIELD]) {\n dedupKey = `int:${(usage as any)[INTERNAL_CALL_ID_FIELD]}`;\n } else {\n dedupKey = key;\n }\n if (this.countedUsageKeys.has(dedupKey)) {\n return;\n }\n this.countedUsageKeys.add(dedupKey);\n this.metricsCollector.add(usage);\n if (this.opts.onLLMUsage) {\n try {\n this.opts.onLLMUsage(usage);\n } catch (error) {\n warn(`onLLMUsage listener threw, ignoring: ${error}`);\n }\n }\n }\n\n /**\n * Aggregated LLM usage accumulated by this agent since it was created.\n */\n get metrics(): MidsceneUsageMetrics {\n return this.metricsCollector.snapshot();\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 // Short-circuit at the call site because JavaScript evaluates function\n // arguments first. This avoids serializing the dump (including inline\n // screenshots) when the Report Viewer build does not need report HTML.\n if (IS_REPORT_BUILD) {\n return '';\n }\n\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(\n locatePrompt,\n this.withContext('aiTap', opt),\n );\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(\n locatePrompt,\n this.withContext('aiRightClick', opt),\n );\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(\n locatePrompt,\n this.withContext('aiDoubleClick', opt),\n );\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(\n locatePrompt,\n this.withContext('aiHover', opt),\n );\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: AgentInputOption & { value: string | number },\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?: AgentInputOption,\n ): Promise<void>;\n\n // Implementation\n async aiInput(\n locatePromptOrValue: TUserPrompt | string | number,\n locatePromptOrOpt:\n | TUserPrompt\n | (AgentInputOption & { value: string | number })\n | undefined,\n optOrUndefined?: AgentInputOption,\n ) {\n let value: string | number;\n let locatePrompt: TUserPrompt;\n let opt: (AgentInputOption & { value: string | number }) | 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 AgentInputOption & {\n value: string | number;\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt,\n this.withContext('aiInput', opt),\n );\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 ...restParams,\n value: stringValue,\n locate: locateParam,\n mode,\n });\n }\n\n // New signature\n async aiKeyboardPress(\n locatePrompt: TUserPrompt | undefined,\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 | undefined,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiKeyboardPress', opt),\n );\n\n await this.callActionInActionSpace('KeyboardPress', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiScroll', opt),\n );\n\n await this.callActionInActionSpace('Scroll', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt || '',\n this.withContext('aiPinch', opt),\n );\n\n await this.callActionInActionSpace('Pinch', {\n ...restParams,\n locate: locateParam,\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 { locateParam, restParams } = buildDetailedLocateParamAndRestParams(\n locatePrompt,\n this.withContext('aiLongPress', opt),\n );\n\n await this.callActionInActionSpace('LongPress', {\n ...restParams,\n locate: locateParam,\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(\n locatePrompt,\n this.withContext('aiClearInput', opt),\n );\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 internalOptions = opt as AiActInternalOptions | undefined;\n const internalReportDisplay = internalOptions?._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 const aiActContext = this.resolveUserContext('aiAct', opt?.context);\n const cachePrompt = buildPromptWithContext(taskPrompt, aiActContext);\n // Resolve the public planning controls at the API boundary. Internal\n // aiAct plumbing only uses effort from this point onward. The explicit\n // effort option takes precedence over deepThink when both are provided.\n const effort: AiActEffort = (() => {\n const resolvedEffort =\n opt?.effort ?? (opt?.deepThink === true ? 'deepThink' : 'balance');\n\n if (opt?.effort !== undefined) {\n warn(\n 'The \"effort\" option is experimental and not yet open for public use. Do not use it. When both \"effort\" and \"deepThink\" are provided, \"effort\" takes precedence.',\n );\n }\n\n if (\n resolvedEffort === 'fast' &&\n planningModel.adapter.planning.kind === 'custom'\n ) {\n throw new Error(\n `The \"fast\" aiAct effort is not supported with custom planning adapters (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}).`,\n );\n }\n\n if (\n resolvedEffort === 'deepThink' &&\n planningModel.adapter.planning.kind === 'custom'\n ) {\n warn(\n `The \"deepThink\" aiAct effort is not supported with custom planning adapters (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}). It will be ignored.`,\n );\n return 'balance';\n }\n\n return resolvedEffort;\n })();\n\n let deepLocate = opt?.deepLocate;\n if (\n deepLocate &&\n !planningModel.adapter.planning.supportsActionDeepLocate\n ) {\n warn(\n `The \"deepLocate\" option is not supported for aiAct with the current planning adapter (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}). It will be ignored.`,\n );\n deepLocate = false;\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(cachePrompt);\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 { output: actionOutput } = await this.taskExecutor.action(\n taskPrompt,\n planningModel,\n defaultModel,\n aiActContext,\n cacheable,\n replanningCycleLimit,\n effort,\n undefined,\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: cachePrompt,\n yamlWorkflow: yamlFlowStr,\n },\n matchedCache,\n );\n }\n\n return actionOutput?.output;\n };\n\n const fileChooserAccepter = this.interface.registerFileChooserListener\n ? new FileChooserAccepter(this.interface)\n : undefined;\n this.activeFileChooserAccepter = fileChooserAccepter;\n this.activeFileChooserAllowedDir = opt?.fileChooserAllowedDir\n ? resolve(opt.fileChooserAllowedDir)\n : undefined;\n let aiActError: { error: unknown } | undefined;\n let fileChooserHandlingError: Error | undefined;\n let result: string | undefined;\n try {\n if (fileChooserAccept?.length) {\n if (!fileChooserAccepter) {\n throw new Error(\n `File upload is not supported on ${this.interface.interfaceType}`,\n );\n }\n await fileChooserAccepter.register(fileChooserAccept);\n }\n result = await runAiAct();\n } catch (error) {\n aiActError = { error };\n } finally {\n this.activeFileChooserAccepter = undefined;\n this.activeFileChooserAllowedDir = undefined;\n try {\n fileChooserHandlingError = await fileChooserAccepter?.clear();\n } catch (error) {\n warn(`Failed to clear file chooser registration: ${error}`);\n }\n }\n\n if (aiActError) {\n throw aiActError.error;\n }\n if (fileChooserHandlingError) {\n throw fileChooserHandlingError;\n }\n return result;\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 async runGherkinScenario(\n scenarioText: string,\n opt?: RunGherkinScenarioOptions,\n ): Promise<void> {\n return runGherkinScenario(this, scenarioText, opt);\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?: QueryOptions,\n ): Promise<ReturnType> {\n return this.createInsight().aiQuery<ReturnType>(demand, opt);\n }\n\n async aiBoolean(prompt: TUserPrompt, opt?: QueryOptions): Promise<boolean> {\n return this.createInsight().aiBoolean(prompt, opt);\n }\n\n async aiNumber(prompt: TUserPrompt, opt?: QueryOptions): Promise<number> {\n return this.createInsight().aiNumber(prompt, opt);\n }\n\n async aiString(prompt: TUserPrompt, opt?: QueryOptions): Promise<string> {\n return this.createInsight().aiString(prompt, opt);\n }\n\n async aiAsk(prompt: TUserPrompt, opt?: QueryOptions): Promise<string> {\n return this.createInsight().aiAsk(prompt, opt);\n }\n\n /**\n * Locate a target in screenshot coordinates. Preserve the model-provided rect\n * when available; otherwise, generate an approximate 8x8 compatibility box.\n * Do not rely on rect for strict element boundaries. Prefer center for the target.\n */\n async aiLocate(prompt: TUserPrompt, opt?: LocateOption) {\n const locateParam = buildDetailedLocateParam(\n prompt,\n this.withContext('aiLocate', opt),\n );\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\n ? (element.rect ?? {\n left: Math.max(element.center[0] - 3.5, 0),\n top: Math.max(element.center[1] - 3.5, 0),\n width: 8,\n height: 8,\n })\n : undefined,\n center: element?.center,\n dpr: element?.dpr,\n } as Pick<LocateResultElement, 'center' | 'dpr'> & {\n rect: Rect;\n };\n }\n\n async aiAssert(\n assertion: TUserPrompt,\n msg?: string,\n opt?: AssertOptions,\n ): Promise<AgentAssertResult | undefined> {\n return this.createInsight().aiAssert(assertion, msg, opt);\n }\n\n async aiWaitFor(assertion: TUserPrompt, opt?: AgentWaitForOpt) {\n const modelRuntime = this.resolveModelRuntime('insight');\n const options = this.withContext('aiWaitFor', opt);\n await this.taskExecutor.waitFor(\n assertion,\n {\n ...options,\n timeoutMs: options?.timeoutMs || 15 * 1000,\n checkIntervalMs: options?.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 /**\n * Subscribe to the generic agent progress bus. The listener receives every\n * progress event regardless of producer; narrow by `event.scope` to handle a\n * specific producer (e.g. `'aiAct'`).\n * @param listener Listener function\n * @returns A remove function that can be called to remove this listener\n */\n addProgressListener(listener: AgentProgressListener): () => void {\n return this.progressBus.subscribe(listener);\n }\n\n /**\n * Remove a progress listener added via {@link addProgressListener}.\n */\n removeProgressListener(listener: AgentProgressListener): void {\n this.progressBus.unsubscribe(listener);\n }\n\n /**\n * Clear all generic progress listeners.\n */\n clearProgressListeners(): void {\n this.progressBus.clear();\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\n // Observers own observation frame files until explicitly disposed.\n for (const observer of this.ownedObservers) {\n try {\n await observer.dispose();\n } catch (error) {\n debug(`error disposing unexported observer during destroy: ${error}`);\n }\n }\n this.ownedObservers.clear();\n this.activeObserver = null;\n\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 /**\n * Wait for a positive, finite duration in milliseconds and record the wait\n * in the report. Does not use a model, capture screenshots, or invoke device\n * action hooks. The report records both the requested and elapsed duration.\n */\n async sleep(ms: number): Promise<void> {\n assert(\n Number.isFinite(ms) && ms > 0,\n `ms for sleep must be a finite number greater than 0, but got ${ms}`,\n );\n const start = Date.now();\n const task: ExecutionTask = {\n taskId: uuid(),\n type: 'Action Space',\n subType: 'Sleep',\n status: 'running',\n param: { timeMs: ms },\n timing: { start, callActionStart: start },\n executor: async () => {},\n };\n const executionDump = new ExecutionDump({\n id: uuid(),\n logTime: start,\n name: 'Sleep',\n tasks: [task],\n });\n this.appendExecutionDump(executionDump);\n this.writeOutActionDumps(executionDump);\n\n await sleep(ms);\n\n const end = Date.now();\n task.status = 'finished';\n task.timing = {\n start,\n callActionStart: start,\n callActionEnd: end,\n end,\n cost: end - start,\n };\n this.writeOutActionDumps(executionDump);\n await this.reportGenerator.flush();\n this.notifyDumpUpdateListeners(executionDump);\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 /** Any thrown value; normalized before it is stored in the report. */\n error: unknown;\n content?: string;\n screenshotBase64?: string;\n },\n ) {\n const now = Date.now();\n const error = serializeError(opt.error);\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,\n errorMessage: error.message,\n errorStack: 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 || 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 normalizeFileInput(files: string | string[]): string[] {\n const filesArray = Array.isArray(files) ? files : [files];\n return 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","Agent","commonAgentTestRunnerNodeDefinitions","callback","apiName","callContext","undefined","apiContext","defaultContext","options","resolvedContext","planningModel","globalConfigManager","MIDSCENE_REPLANNING_CYCLE_LIMIT","intent","runtime","getModelRuntime","usage","enriched","getUIContext","Insight","_error","action","maxRetries","attempt","commonContextParser","error","Promise","resolve","setTimeout","opt","assert","observer","UIObserverImpl","record","uiContextFromObservationRecord","disposeError","prompt","target","context","isAgentAIContextKey","TypeError","String","ReportActionDump","getVersion","WeakMap","execution","runner","currentDump","existingIndex","task","key","dedupKey","INTERNAL_CALL_ID_FIELD","ifInBrowser","IS_REPORT_BUILD","reportHTMLContent","executionDump","exec","param","paramStr","tip","typeStr","name","type","actionPlan","plans","Boolean","title","taskTitleStr","locateParamStr","defaultModel","output","locatePrompt","detailedLocateParam","buildDetailedLocateParam","fileChooserAccept","withFileChooser","locatePromptOrValue","locatePromptOrOpt","optOrUndefined","value","optWithValue","locateParam","restParams","buildDetailedLocateParamAndRestParams","stringValue","mode","locatePromptOrKeyName","keyName","locatePromptOrScrollParam","scrollParam","isLocatePromptLike","normalizedScrollType","normalizeScrollType","taskPrompt","internalOptions","internalReportDisplay","taskPromptText","reportPrompt","abortSignal","Error","runAiAct","aiActContext","cachePrompt","buildPromptWithContext","effort","resolvedEffort","deepLocate","cacheable","replanningCycleLimit","planCacheEnabled","matchedCache","cachedYamlFailed","yaml","actionOutput","yamlFlow","yamlFlowToCache","yamlContent","yamlFlowStr","fileChooserAccepter","FileChooserAccepter","aiActError","fileChooserHandlingError","result","markdownPath","markdown","readFile","markdownToAiActPrompt","basename","scenarioText","runGherkinScenario","demand","locatePlan","locatePlanForLocate","element","Math","assertion","msg","modelRuntime","args","yamlScriptContent","script","parseYamlScript","player","ScriptPlayer","errors","listener","index","dumpString","console","interfaceDestroyError","finalPath","ms","Number","start","Date","uuid","ExecutionDump","sleep","end","now","screenshots","screenshotBase64","hasScreenshots","hasScreenshotBase64","Array","customScreenshots","screenshotInputs","recorder","screenshotInput","normalizedScreenshotInput","normalizeRecordToReportScreenshot","ts","ScreenshotItem","serializeError","base64","groupName","groupDescription","executions","opts","validateAgentCacheInput","cacheConfig","processCacheConfig","id","strategyValue","isReadOnly","isWriteOnly","files","filesArray","normalizeFilePaths","interfaceInstance","MetricsCollector","Set","AgentProgressBus","Object","assertReportGenerationOptions","deprecatedAiActContextOption","normalizedAIContexts","resolvedAiActContext","hasCustomConfig","ModelConfigManager","globalModelConfigManager","Service","cacheConfigObj","TaskCache","baseActionSpace","fileChooserActions","defineActionRegisterFileChooserAccept","defineActionSleep","TaskExecutor","getReportFileName","ReportGenerator","observationArtifactAdapterSymbol","observation","UIObservationImpl","createAgent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,OAAOD,SAAS,SAAS;IAAE,SAAS;AAAK;AAoCxC,MAAME;IAIX,OAAO,+BAAyE;QAC9E,OAAOC;IACT;IA2CA,IAAI,eAEU;QACZ,OAAO,IAAI,CAAC,mBAAmB,CAAC,EAAE;IACpC;IAEA,IAAI,aAAaC,QAEJ,EAAE;QAEb,IAAI,CAAC,mBAAmB,GAAG,EAAE;QAE7B,IAAIA,UACF,IAAI,CAAC,mBAAmB,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,CAAC,YAAY;YACpC,oBAAoB,IAAI,CAAC,IAAI,CAAC,kBAAkB;YAChD,qBACE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,gBAAgB,KAAK,IAAI,CAAC,cAAc;QACzE;QAEAjB,OAAO,cAAc,CAAC,IAAI,EAAEkB,kCAAkC;YAC5D,OAAO;gBACL,cAAc,OAAOC;oBACnBvL,OACEuL,uBAAuBC,mBACvB;oBAEF,OAAOD,YAAY,YAAY;gBACjC;gBACA,YAAY,CAACpL;oBAGXC,+BAA+BD;oBAC/B,OAAO,IAAIqL,kBACTrL,QACA,IAAI,CAAC,aAAa,CAAC,IAAMC,+BAA+BD;gBAE5D;YACF;QACF;IACF;AAo6CF;AA95CE,iBAjZWjC,OAiZa,qBAAoB;AAC5C,iBAlZWA,OAkZa,0BAAyB;AA+5C5C,MAAMuN,cAAc,CACzBzB,mBACAX,OAEO,IAAInL,MAAM8L,mBAAmBX"}
@@ -0,0 +1,12 @@
1
+ import { MIDSCENE_REPORT_TAG_NAME, globalConfigManager } from "@midscene/shared/env";
2
+ import { uuid } from "@midscene/shared/utils";
3
+ import dayjs from "dayjs";
4
+ function getReportFileName(tag = 'web') {
5
+ const reportTagName = globalConfigManager.getEnvConfigValue(MIDSCENE_REPORT_TAG_NAME);
6
+ const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');
7
+ const uniqueId = uuid().substring(0, 8);
8
+ return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;
9
+ }
10
+ export { getReportFileName };
11
+
12
+ //# sourceMappingURL=report-file-name.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent/report-file-name.mjs","sources":["../../../src/agent/report-file-name.ts"],"sourcesContent":["import {\n MIDSCENE_REPORT_TAG_NAME,\n globalConfigManager,\n} from '@midscene/shared/env';\nimport { uuid } from '@midscene/shared/utils';\nimport dayjs from 'dayjs';\n\nexport function getReportFileName(tag = 'web') {\n const reportTagName = globalConfigManager.getEnvConfigValue(\n MIDSCENE_REPORT_TAG_NAME,\n );\n const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');\n const uniqueId = uuid().substring(0, 8);\n return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;\n}\n"],"names":["getReportFileName","tag","reportTagName","globalConfigManager","MIDSCENE_REPORT_TAG_NAME","dateTimeInFileName","dayjs","uniqueId","uuid"],"mappings":";;;AAOO,SAASA,kBAAkBC,MAAM,KAAK;IAC3C,MAAMC,gBAAgBC,oBAAoB,iBAAiB,CACzDC;IAEF,MAAMC,qBAAqBC,QAAQ,MAAM,CAAC;IAC1C,MAAMC,WAAWC,OAAO,SAAS,CAAC,GAAG;IACrC,OAAO,GAAGN,iBAAiBD,IAAI,CAAC,EAAEI,mBAAmB,CAAC,EAAEE,UAAU;AACpE"}
@@ -2,13 +2,13 @@ import { existsSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import { ScreenshotItem } from "../screenshot-item.mjs";
4
4
  import { uploadTestInfoToServer } from "../utils.mjs";
5
- import { MIDSCENE_REPORT_QUIET, MIDSCENE_REPORT_TAG_NAME, globalConfigManager } from "@midscene/shared/env";
5
+ import { MIDSCENE_REPORT_QUIET, globalConfigManager } from "@midscene/shared/env";
6
6
  import { createImgBase64ByFormat, imageInfoOfBase64 } from "@midscene/shared/img";
7
7
  import { getDebug } from "@midscene/shared/logger";
8
- import { assert, ifInBrowser, logMsg, uuid } from "@midscene/shared/utils";
9
- import dayjs from "dayjs";
8
+ import { assert, ifInBrowser, logMsg } from "@midscene/shared/utils";
10
9
  import { prepareRawScreenshot } from "./screenshot-preparation.mjs";
11
10
  import { debug as external_task_cache_mjs_debug } from "./task-cache.mjs";
11
+ import { getReportFileName } from "./report-file-name.mjs";
12
12
  const agentDebug = getDebug('agent');
13
13
  const screenshotDataUrlPattern = /^data:image\/[a-zA-Z0-9.+-]+;base64,/i;
14
14
  const inferBase64ImageFormat = (base64Body)=>{
@@ -96,12 +96,6 @@ async function createScreenshotBoundUIContext(screenshotBase64, opt) {
96
96
  _isFrozen: true
97
97
  };
98
98
  }
99
- function getReportFileName(tag = 'web') {
100
- const reportTagName = globalConfigManager.getEnvConfigValue(MIDSCENE_REPORT_TAG_NAME);
101
- const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');
102
- const uniqueId = uuid().substring(0, 8);
103
- return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;
104
- }
105
99
  function printReportMsg(filepath) {
106
100
  if (globalConfigManager.getEnvConfigInBoolean(MIDSCENE_REPORT_QUIET)) return;
107
101
  logMsg(`Midscene - report file updated: ${filepath}`);
@@ -159,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
159
153
  return;
160
154
  }
161
155
  }
162
- const getMidsceneVersion = ()=>"1.12.5";
156
+ const getMidsceneVersion = ()=>"1.12.6-beta-20260909034232.0";
163
157
  const parsePrompt = (prompt)=>{
164
158
  if ('string' == typeof prompt) return {
165
159
  textPrompt: prompt,