@midscene/core 1.15.6 → 1.16.1

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 (94) hide show
  1. package/dist/es/agent/agent-options.mjs +36 -0
  2. package/dist/es/agent/agent-options.mjs.map +1 -0
  3. package/dist/es/agent/agent-report-manager.mjs +323 -0
  4. package/dist/es/agent/agent-report-manager.mjs.map +1 -0
  5. package/dist/es/agent/agent.mjs +112 -228
  6. package/dist/es/agent/agent.mjs.map +1 -1
  7. package/dist/es/agent/cache-config.mjs +21 -1
  8. package/dist/es/agent/cache-config.mjs.map +1 -1
  9. package/dist/es/agent/tasks.mjs +3 -1
  10. package/dist/es/agent/tasks.mjs.map +1 -1
  11. package/dist/es/agent/utils.mjs +1 -1
  12. package/dist/es/report-generator.mjs +73 -33
  13. package/dist/es/report-generator.mjs.map +1 -1
  14. package/dist/es/report-html-template.mjs +1 -1
  15. package/dist/es/test-runner/engine/document-runtime.mjs +30 -24
  16. package/dist/es/test-runner/engine/document-runtime.mjs.map +1 -1
  17. package/dist/es/test-runner/engine/project-runtime.mjs +17 -11
  18. package/dist/es/test-runner/engine/project-runtime.mjs.map +1 -1
  19. package/dist/es/test-runner/engine/resource-operations.mjs +33 -8
  20. package/dist/es/test-runner/engine/resource-operations.mjs.map +1 -1
  21. package/dist/es/test-runner/engine/run-collected-case.mjs +1 -0
  22. package/dist/es/test-runner/engine/run-collected-case.mjs.map +1 -1
  23. package/dist/es/test-runner/engine/run-workflow-document.mjs +3 -0
  24. package/dist/es/test-runner/engine/run-workflow-document.mjs.map +1 -1
  25. package/dist/es/test-runner/engine/setup-timeout.mjs +37 -0
  26. package/dist/es/test-runner/engine/setup-timeout.mjs.map +1 -0
  27. package/dist/es/utils.mjs +1 -1
  28. package/dist/es/yaml/execution-session.mjs +2 -1
  29. package/dist/es/yaml/execution-session.mjs.map +1 -1
  30. package/dist/es/yaml/legacy-yaml-report.mjs +1 -1
  31. package/dist/es/yaml/legacy-yaml-report.mjs.map +1 -1
  32. package/dist/es/yaml/player.mjs +17 -3
  33. package/dist/es/yaml/player.mjs.map +1 -1
  34. package/dist/lib/agent/agent-options.js +73 -0
  35. package/dist/lib/agent/agent-options.js.map +1 -0
  36. package/dist/lib/agent/agent-report-manager.js +357 -0
  37. package/dist/lib/agent/agent-report-manager.js.map +1 -0
  38. package/dist/lib/agent/agent.js +110 -226
  39. package/dist/lib/agent/agent.js.map +1 -1
  40. package/dist/lib/agent/cache-config.js +23 -0
  41. package/dist/lib/agent/cache-config.js.map +1 -1
  42. package/dist/lib/agent/tasks.js +3 -1
  43. package/dist/lib/agent/tasks.js.map +1 -1
  44. package/dist/lib/agent/utils.js +1 -1
  45. package/dist/lib/report-generator.js +73 -33
  46. package/dist/lib/report-generator.js.map +1 -1
  47. package/dist/lib/report-html-template.js +1 -1
  48. package/dist/lib/test-runner/engine/document-runtime.js +30 -24
  49. package/dist/lib/test-runner/engine/document-runtime.js.map +1 -1
  50. package/dist/lib/test-runner/engine/project-runtime.js +17 -11
  51. package/dist/lib/test-runner/engine/project-runtime.js.map +1 -1
  52. package/dist/lib/test-runner/engine/resource-operations.js +36 -8
  53. package/dist/lib/test-runner/engine/resource-operations.js.map +1 -1
  54. package/dist/lib/test-runner/engine/run-collected-case.js +1 -0
  55. package/dist/lib/test-runner/engine/run-collected-case.js.map +1 -1
  56. package/dist/lib/test-runner/engine/run-workflow-document.js +3 -0
  57. package/dist/lib/test-runner/engine/run-workflow-document.js.map +1 -1
  58. package/dist/lib/test-runner/engine/setup-timeout.js +71 -0
  59. package/dist/lib/test-runner/engine/setup-timeout.js.map +1 -0
  60. package/dist/lib/utils.js +1 -1
  61. package/dist/lib/yaml/execution-session.js +4 -0
  62. package/dist/lib/yaml/execution-session.js.map +1 -1
  63. package/dist/lib/yaml/legacy-yaml-report.js +1 -1
  64. package/dist/lib/yaml/legacy-yaml-report.js.map +1 -1
  65. package/dist/lib/yaml/player.js +16 -2
  66. package/dist/lib/yaml/player.js.map +1 -1
  67. package/dist/types/agent/agent-options.d.ts +4 -0
  68. package/dist/types/agent/agent-options.d.ts.map +1 -0
  69. package/dist/types/agent/agent-report-manager.d.ts +92 -0
  70. package/dist/types/agent/agent-report-manager.d.ts.map +1 -0
  71. package/dist/types/agent/agent.d.ts +31 -24
  72. package/dist/types/agent/agent.d.ts.map +1 -1
  73. package/dist/types/agent/cache-config.d.ts +10 -0
  74. package/dist/types/agent/cache-config.d.ts.map +1 -1
  75. package/dist/types/agent/tasks.d.ts +1 -0
  76. package/dist/types/agent/tasks.d.ts.map +1 -1
  77. package/dist/types/report-generator.d.ts +5 -1
  78. package/dist/types/report-generator.d.ts.map +1 -1
  79. package/dist/types/test-runner/engine/document-runtime.d.ts.map +1 -1
  80. package/dist/types/test-runner/engine/project-runtime.d.ts.map +1 -1
  81. package/dist/types/test-runner/engine/resource-operations.d.ts +5 -0
  82. package/dist/types/test-runner/engine/resource-operations.d.ts.map +1 -1
  83. package/dist/types/test-runner/engine/run-collected-case.d.ts.map +1 -1
  84. package/dist/types/test-runner/engine/run-workflow-document.d.ts.map +1 -1
  85. package/dist/types/test-runner/engine/setup-timeout.d.ts +3 -0
  86. package/dist/types/test-runner/engine/setup-timeout.d.ts.map +1 -0
  87. package/dist/types/test-runner/engine/types.d.ts +7 -0
  88. package/dist/types/test-runner/engine/types.d.ts.map +1 -1
  89. package/dist/types/test-runner/project.d.ts +22 -0
  90. package/dist/types/test-runner/project.d.ts.map +1 -1
  91. package/dist/types/yaml/execution-session.d.ts +2 -0
  92. package/dist/types/yaml/execution-session.d.ts.map +1 -1
  93. package/dist/types/yaml/player.d.ts.map +1 -1
  94. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport { type AbstractInterface, defineActionSleep } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { renderAIContext } from './prompt-context';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n return new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\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 setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal ??= this.getAbortSignal?.();\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n abortSignal,\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.config.slot === 'default';\n const includeLocateInPlanning =\n effort !== 'deepThink' && noIndividualLocateModel;\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const planImpl =\n planningModel.adapter.planning.kind === 'custom'\n ? planningModel.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: renderAIContext(aiActContext),\n actionSpace,\n modelRuntime: planningModel,\n locateModelRuntime: locateModel,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawAssistantOutput: planError.rawAssistantOutput,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawAssistantOutput,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawAssistantOutput,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)),\n );\n } catch (error: any) {\n // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (!conversationHistory.pendingFeedbackMessage) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n abortSignal,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n { ...executionOptions, abortSignal },\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const abortSignal = this.getAbortSignal?.();\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images, abortSignal },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n { abortSignal },\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","session","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","Array","console","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","String","type","demand","modelRuntime","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAK9C,MAAMC,4BAA4B;AAElC,SAASC,yBACPC,QAAgB,EAChBC,cAAqC;IAErC,IAAIA,AAAmB,gBAAnBA,gBACF,OAAOD;IAET,MAAME,QACJD,kBAAkBE,OAAO,QAAQ,CAACF,mBAAmBA,iBAAiB,IAClEG,KAAK,KAAK,CAACH,kBACXH;IACN,IAAIE,SAAS,MAAM,IAAIE,OACrB,OAAOF;IAGT,OAAO,GAAGA,SAAS,KAAK,CAAC,GAAGE,OAAO;eACtB,EAAEF,SAAS,MAAM,GAAGE,MAAM,iBAAiB,CAAC;AAC3D;AAKO,MAAMG;IAwBX,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,SAAS;IACvB;IA0CQ,uBACNC,KAAa,EACbC,OAUC,EACD;QACA,OAAO,IAAIC,iBACTF,OACA,CAACG,SACCF,SAAS,YACLG,QAAQ,OAAO,CAACH,QAAQ,SAAS,IACjCG,QAAQ,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAACD,UACtD;YACE,aAAaF,SAAS,eAAe,IAAI,CAAC,cAAc;YACxD,aAAa,IAAI,CAAC,mBAAmB;YACrC,OAAOA,SAAS;YAChB,iBAAiBA,SAAS;YAC1B,kBAAkB,OAAOI,QAAQC;gBAC/B,MAAM,IAAI,CAAC,KAAK,EAAE,mBAAmBD,QAAQC;gBAC7C,MAAML,SAAS,mBAAmBI,QAAQC;YAC5C;YACA,GAAIL,SAAS,cAAc;gBAAE,aAAaA,QAAQ,WAAW;YAAC,IAAI,CAAC,CAAC;QACtE;IAEJ;IAEQ,iBAAiC;QACvC,O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,MAAM,GAAG,GAAG;QAC/B,MAAMC,gBAAyC,EAAE;QACjD,IAAK,IAAI3G,IAAI,GAAGA,IAAI0G,OAAO,MAAM,GAAG,GAAG1G,IAAK;YAC1C,MAAM4G,QAAQF,MAAM,CAAC1G,EAAE;YACvB2G,cAAc,IAAI,CAAC;gBACjB,MAAM;gBACN,IAAIC,MAAM,UAAU;gBACpB,YAAYA;gBACZ,aAAa,CAAC,eAAe,EAAE5G,IAAI,EAAE,CAAC,EAAE0G,OAAO,MAAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKAhI,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAIiI;eAAkBjI,KAAK,QAAQ;SAAC,GACpCiI;IACN;IACA,IAAI/H,WAAW,oBACbA,UAAU,kBAAkB,GAAGf;AAEnC"}
1
+ {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport { type AbstractInterface, defineActionSleep } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { renderAIContext } from './prompt-context';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onExecutionCreated?: (runner: TaskRunner) => void;\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n const session = new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n this.hooks?.onExecutionCreated?.(session.getRunner());\n return session;\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\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 setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal ??= this.getAbortSignal?.();\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n abortSignal,\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.config.slot === 'default';\n const includeLocateInPlanning =\n effort !== 'deepThink' && noIndividualLocateModel;\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const planImpl =\n planningModel.adapter.planning.kind === 'custom'\n ? planningModel.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: renderAIContext(aiActContext),\n actionSpace,\n modelRuntime: planningModel,\n locateModelRuntime: locateModel,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\n conversationHistory,\n includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawAssistantOutput: planError.rawAssistantOutput,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawAssistantOutput,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawAssistantOutput,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<ReturnType<typeof this.convertPlanToExecutable>>;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(runner.tasks.slice(taskCountBeforeRun)),\n );\n } catch (error: any) {\n // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (!conversationHistory.pendingFeedbackMessage) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n abortSignal,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n { ...executionOptions, abortSignal },\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const abortSignal = this.getAbortSignal?.();\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images, abortSignal },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n { abortSignal },\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","session","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","Array","console","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","JSON","actions","thought","log","memory","usage","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","String","type","demand","modelRuntime","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAK9C,MAAMC,4BAA4B;AAElC,SAASC,yBACPC,QAAgB,EAChBC,cAAqC;IAErC,IAAIA,AAAmB,gBAAnBA,gBACF,OAAOD;IAET,MAAME,QACJD,kBAAkBE,OAAO,QAAQ,CAACF,mBAAmBA,iBAAiB,IAClEG,KAAK,KAAK,CAACH,kBACXH;IACN,IAAIE,SAAS,M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AQ,GACzB;eAAIiI;eAAkBjI,KAAK,QAAQ;SAAC,GACpCiI;IACN;IACA,IAAI/H,WAAW,oBACbA,UAAU,kBAAkB,GAAGd;AAEnC"}
@@ -153,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
153
153
  return;
154
154
  }
155
155
  }
156
- const getMidsceneVersion = ()=>"1.15.6";
156
+ const getMidsceneVersion = ()=>"1.16.1";
157
157
  const parsePrompt = (prompt)=>{
158
158
  if ('string' == typeof prompt) return {
159
159
  textPrompt: prompt,
@@ -54,12 +54,12 @@ class ReportGenerator {
54
54
  });
55
55
  }
56
56
  onExecutionUpdate(execution, reportMeta, attributes) {
57
+ this.assertOpen();
57
58
  this.lastExecution = execution;
58
59
  this.lastReportMeta = reportMeta;
59
60
  this.executionsByKey.set(this.getExecutionCommentKey(execution), execution);
60
61
  this.mergeReportAttributes(attributes);
61
62
  this.writeQueue = this.writeQueue.then(async ()=>{
62
- if (this.destroyed) return;
63
63
  await this.doWriteExecution(execution, reportMeta);
64
64
  });
65
65
  }
@@ -67,22 +67,40 @@ class ReportGenerator {
67
67
  await this.writeQueue;
68
68
  }
69
69
  async finalize() {
70
- if (this.lastExecution && this.lastReportMeta) this.onExecutionUpdate(this.lastExecution, this.lastReportMeta);
71
- await this.flush();
72
- this.destroyed = true;
73
- if (!this.initialized) return;
74
- await this.appendAgentReportComment();
75
- try {
76
- await compactReportDumps(this.reportPath);
77
- } catch (error) {
78
- warnReport(`Failed to compact report ${this.reportPath}; keeping the uncompressed report: ${String(error)}`);
70
+ if (!this.finalization) {
71
+ if (this.lastExecution && this.lastReportMeta) this.onExecutionUpdate(this.lastExecution, this.lastReportMeta);
72
+ this.finalization = this.finishPublication();
79
73
  }
80
- return this.reportPath;
74
+ return this.finalization;
75
+ }
76
+ async finishPublication() {
77
+ await Promise.all([
78
+ this.flush(),
79
+ ...this.sourcePublications
80
+ ]);
81
+ if (this.initialized) {
82
+ await this.appendAgentReportComment();
83
+ try {
84
+ await compactReportDumps(this.reportPath);
85
+ } catch (error) {
86
+ warnReport(`Failed to compact report ${this.reportPath}; keeping the uncompressed report: ${String(error)}`);
87
+ }
88
+ }
89
+ this.executionsByKey.clear();
90
+ this.lastExecution = void 0;
91
+ this.lastReportMeta = void 0;
92
+ this.executionCommentKeyByObject = new WeakMap();
93
+ this.executionLogFileIndexByExecutionKey.clear();
94
+ return this.initialized ? this.reportPath : void 0;
95
+ }
96
+ assertOpen() {
97
+ if (this.finalization) throw new Error('The report has been finalized.');
81
98
  }
82
99
  getReportPath() {
83
100
  return this.reportPath;
84
101
  }
85
102
  async writeRunnerReport(input, scopeId, meta) {
103
+ this.assertOpen();
86
104
  this.writeQueue = this.writeQueue.then(async ()=>{
87
105
  const reportMeta = this.lastReportMeta ?? meta;
88
106
  const executions = [
@@ -176,6 +194,7 @@ ${generateAgentReportComment(agentDump)}`;
176
194
  };
177
195
  }
178
196
  async createSourceSnapshot(scopeId, executionIds) {
197
+ this.assertOpen();
179
198
  if (!scopeId || basename(scopeId) !== scopeId) throw new Error('Invalid report scope ID');
180
199
  const capturedAt = new Date().toISOString();
181
200
  const selectedIds = executionIds ? new Set(executionIds) : void 0;
@@ -191,22 +210,30 @@ ${generateAgentReportComment(agentDump)}`;
191
210
  },
192
211
  executions
193
212
  }).serialize());
194
- const { serialized } = await this.serializeSourceDump(frozen, screenshots);
195
- const dumpPath = `${this.reportPath}.${scopeId}.${uuid()}.json`;
196
- mkdirSync(dirname(dumpPath), {
197
- recursive: true
198
- });
199
- await writeFile(dumpPath, serialized, {
200
- flag: 'wx'
201
- });
202
- return {
203
- sourcePath: this.reportPath,
204
- dumpPath,
205
- collection: {
206
- status: 'complete',
207
- capturedAt
208
- }
209
- };
213
+ const publication = (async ()=>{
214
+ const { serialized } = await this.serializeSourceDump(frozen, screenshots);
215
+ const dumpPath = `${this.reportPath}.${scopeId}.${uuid()}.json`;
216
+ mkdirSync(dirname(dumpPath), {
217
+ recursive: true
218
+ });
219
+ await writeFile(dumpPath, serialized, {
220
+ flag: 'wx'
221
+ });
222
+ return {
223
+ sourcePath: this.reportPath,
224
+ dumpPath,
225
+ collection: {
226
+ status: 'complete',
227
+ capturedAt
228
+ }
229
+ };
230
+ })();
231
+ this.sourcePublications.add(publication);
232
+ try {
233
+ return await publication;
234
+ } finally{
235
+ this.sourcePublications.delete(publication);
236
+ }
210
237
  }
211
238
  printReportPath() {
212
239
  if (!this.autoPrint || !this.reportPath) return;
@@ -230,8 +257,8 @@ ${generateAgentReportComment(agentDump)}`;
230
257
  if (!existsSync(this.reportPath)) return;
231
258
  this.initialized = true;
232
259
  if (!this.shouldPersistExecutionDump) return;
233
- const reportDir = dirname(this.reportPath);
234
- const existingExecutionIndices = readdirSync(reportDir).map((name)=>/^(\d+)\.execution\.json$/.exec(name)?.[1]).filter((index)=>Boolean(index)).map((index)=>Number.parseInt(index, 10)).filter((index)=>Number.isFinite(index));
260
+ if (!existsSync(this.executionDumpDir)) return;
261
+ const existingExecutionIndices = readdirSync(this.executionDumpDir).map((name)=>/^(\d+)\.execution\.json$/.exec(name)?.[1]).filter((index)=>Boolean(index)).map((index)=>Number.parseInt(index, 10)).filter((index)=>Number.isFinite(index));
235
262
  if (existingExecutionIndices.length > 0) this.executionLogIndex = Math.max(...existingExecutionIndices);
236
263
  }
237
264
  getDumpScriptAttributes() {
@@ -302,8 +329,11 @@ ${generateAgentReportComment(agentDump)}`;
302
329
  this.executionCommentKeyByObject.set(execution, key);
303
330
  return key;
304
331
  }
332
+ get executionDumpDir() {
333
+ return 'inline' === this.screenshotMode ? join(dirname(this.reportPath), '.execution-dumps', basename(this.reportPath)) : dirname(this.reportPath);
334
+ }
305
335
  async persistExecutionDumpToFile(execution, singleDump, referenceImageRefs) {
306
- const dir = dirname(this.reportPath);
336
+ const dir = this.executionDumpDir;
307
337
  if (!existsSync(dir)) mkdirSync(dir, {
308
338
  recursive: true
309
339
  });
@@ -315,8 +345,17 @@ ${generateAgentReportComment(agentDump)}`;
315
345
  this.executionLogFileIndexByExecutionKey.set(executionLogKey, fileIndex);
316
346
  }
317
347
  const fileName = `${fileIndex}.execution.json`;
318
- const filePath = join(dirname(this.reportPath), fileName);
319
- await writeFile(filePath, singleDump.serializeWithReferenceImages(referenceImageRefs, 2), 'utf-8');
348
+ const filePath = join(dir, fileName);
349
+ let serialized = singleDump.serializeWithReferenceImages(referenceImageRefs, 2);
350
+ if ('inline' === this.screenshotMode) serialized = JSON.stringify(JSON.parse(serialized), (_key, value)=>{
351
+ const ref = normalizeStoredImageRef(value);
352
+ return ref ? {
353
+ ...ref,
354
+ storage: 'file',
355
+ path: `../../screenshots/${ref.id}.${imageRefFileExtension(ref)}`
356
+ } : value;
357
+ }, 2);
358
+ await writeFile(filePath, serialized, 'utf-8');
320
359
  }
321
360
  constructor(options){
322
361
  _define_property(this, "reportPath", void 0);
@@ -337,7 +376,8 @@ ${generateAgentReportComment(agentDump)}`;
337
376
  _define_property(this, "reportAttributes", {});
338
377
  _define_property(this, "agentCommentWritten", false);
339
378
  _define_property(this, "writeQueue", Promise.resolve());
340
- _define_property(this, "destroyed", false);
379
+ _define_property(this, "finalization", void 0);
380
+ _define_property(this, "sourcePublications", new Set());
341
381
  this.reportPath = options.reportPath;
342
382
  this.screenshotMode = options.screenshotMode;
343
383
  this.shouldPersistExecutionDump = options.persistExecutionDump ?? false;